commit 2a81b4a50256891d960dfa8503826f29fb2ad0e3 Author: jhartworks Date: Mon Nov 9 10:37:41 2026 +0100 first push diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d0d6371 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto eol=lf +*.png binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..235943a --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +node_modules/ +__pycache__/ +*.pyc +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +.venv/ +deploy.local.json +preview/screenshots/ +private/ +*.pem +*.key + +# owned 3D models never go into the repository +*.glb +nextfloor_meshes/ +preview/.tutorial-state.json + +# local tutorial recordings +frontend/tutorial/out/ +# tool installers do not belong here +*.whl + +# knowledge-graph tooling output +graphify-out/ +*.bak-graphify +tools/docs/dist/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e0ba057 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,652 @@ +# Changelog + +All notable changes to NextFloor, newest first. Every release lists what is **Added**, **Changed** and **Fixed**. Releases: [GitHub releases](https://github.com/therealMRBK/NextFloor/releases). + +## [Unreleased] + +## [0.26.6] + +### Added + +- **Notes with a height and a photo** (#113): a note in the plan gets its own height above the floor (a pin under the ceiling, at the shutoff valve) and a photo, uploaded or as a URL, that shows when the note is tapped in the 3D view. +- **Temperature of technical devices** (thanks @tfischer84, #112): an inverter, a battery, a PC or any other electric device takes a temperature sensor under *Device temperature*. Its value shows on the device's pin in the 3D view; from 60 °C the pin is highlighted. + +### Changed + +- **Outside has its own section in the editor** (thanks @eskahone, #83): the view for Outside and the devices its panel hides moved from the favourites into *🌳 Outside*, right below *Start view*. + +### Fixed + +- **Lamps light up in the editor plan as in 3D** (thanks @tfischer84, #111): a lamp whose light was found in its room by itself (not picked by hand), or that glows with one of its further lights, now lights up in the editor's floor plan too. + +## [0.26.5] + +### Added + +- **Chimneys on the roof:** the roof tool places chimneys in four shapes (brick, round, wide with two flues, steel flue pipe with a rain cap), with their own width, depth and height above the roof. Drag them in the plan or in the 3D view. +- **Furniture colours per material** (thanks @eskahone, #82): in the editor under *Settings*, each material furniture is built from (body, wood, fabric, white, metal, dark) gets a colour for the whole house, pieces from the furniture builder and the packs included. A card can set its own with `furniture_colors`, or in the card editor under *Furniture colours of this card*. +- **Fold the energy card:** a small button in the corner of the glass energy card folds it down to its ring and the solar power, on phones and desktops; the browser remembers it. +- **Fine-tune a robot map by hand** (#109): after calibrating, arrows move the map by 10 cm, ⟲ ⟳ turn it by 1° and − + change its size by 1 %. +- **Weather forecast card** (thanks @eskahone, #84): in the house settings under *Weather forecast*, choose 3, 5 or 7 days and a top corner. A small card shows the weather of each day with its high and low and the rain. +- **More days on the "Today" card** (#84): *Days on the "Today" card* lists the appointments of up to seven days, each later day under its own heading. + +- **Outside wall colour per floor** (thanks @LDSign, #110): in the solid wall view a floor can have an outside colour of its own (*Wall colour outside (this floor)* in the floor's settings), for a plinth or a garage that is not the colour of the storeys above. + +- **Calibrate a robot map from its rooms** (#109): when the robot's map names its rooms, as the Dreame integration does, the dock has a button *Calibrate from the rooms*. It matches them to the rooms with the same names on the plan, so the robot no longer has to be parked 1.5 m from its dock and tapped. With three or more matching rooms a mirrored map is recognised by itself. + +- **A view of its own for Outside** (thanks @eskahone, #83): under *Settings → Outside: hide devices* the button *Use this view for Outside* stores the camera of the editor's 3D preview. Opening Outside then flies to the garden instead of staying on the house view; closing it goes back. + +### Changed + +- **A tidier 3D view on phones:** the switches under the 3D view (walls, floors, roof, heat map, room names, weather) now sit behind one *☰ Switches* button that opens them as a menu above the bar. The house stays in view instead of a row of buttons across the bottom; a tap beside the menu closes it again. + +### Fixed + +- **Live cards cut off on phones:** a card near the edge of the view now slides back in, its thread still pointing to where it belongs. +- **Room colours on other floors** (thanks @LDSign, #110): a room with its own wall colour no longer paints the walls of the floors above or below that lie in the same spot of the plan. + +- **Dreame robot maps** (thanks @lina-alexrt, #109): the map camera of the Dreame integration names the dock `charger_position` instead of `charger`. NextFloor now reads both, so the robot's real position can be calibrated and shown on the plan. Without a `path` on the camera no trail is drawn. + +## [0.26.4] + +### Added + +- **Invert the rain sensor** (thanks @tfischer84, #107): a checkbox under the rain sensor in the settings for sensors that read off (or 0) when it rains. +- **Plan check: look first, ignore what you do not want** (#103): the line "devices not in the plan yet" opens a list of the devices behind it, with *Ignore* for each one (internal KNX devices, say) or for all. Ignored devices are no longer listed; one button brings them back. +- **Smart speakers link to a media player** (#104): a smart speaker, multiroom or hi-fi speaker picks the only free media player of its room by itself, so the quick menu offers volume, play and pause. Linking it by hand in the furniture form works as before. + +### Fixed + +- **Pieces lying on others can be selected** (thanks @tfischer84, #105): in the plan, what stands higher (a speaker on a desk, a lamp on a shelf) is drawn on top and is the one a click hits. + +## [0.26.3] + +### Fixed + +- **The editor is fast again with many entities** (thanks @alex1255, #101): the list *Outside: hide devices* in the editor's settings worked out the devices of the Outside panel once for every entity of Home Assistant, on every update. With a few thousand entities that kept the browser busy and made clicks and turning the view sluggish. It is now worked out once. + +## [0.26.2] + +### Added + +- **Bluetooth locating (new, experimental):** find out which room a Bluetooth tag, watch or phone is in, learned by walking. Under *Settings → Bluetooth locating* in the editor you pick a tag, walk through each room with it for 30 seconds and record the room. NextFloor compares how strongly the Bluetooth scanners Home Assistant already has (ESPHome Bluetooth proxies, Shelly devices with Bluetooth scanning on, the server's adapter) hear the tag with those recordings. Every tag gets a sensor whose state is the room name, usable in automations and as a person's room sensor under *Presence*. Phones and watches work through Home Assistant's *Private BLE Device*. It needs at least two scanners, more is better. The recordings stay in the plan and are left out of shared plans. +- **See-through outdoor areas** (thanks @thelichtler-cloud, #95): every outdoor area has *Opacity (%)* in its form, from 100 (solid) down to 10, saved with the plan. A driveway or lawn above the cellar no longer hides it in the stacked view; the outline stays. + +### Changed + +- **A new README:** a shorter, picture-led front page with the three ideas in one minute, a gallery that links into the documentation, the features grouped by what you do, a two-minute install and a table of where to read what. + +## [0.26.1] + +### Added + +- **A documentation site**, in English and German, at [therealmrbk.github.io/NextFloor/docs](https://therealmrbk.github.io/NextFloor/docs/en/): 26 pages from the quick start to the full list of card options, with search (Ctrl+K), a dark and a light look, a table of contents, copyable code and a full-size view of every picture. The sources are Markdown in `docs/content`, built by `tools/docs`, and CI checks every link and anchor. +- The README points into the documentation and lists where to read what. + +## [0.26.0] + +### Added + +- **Eight more languages for the core screens:** Danish, Finnish, Hungarian, Norwegian (Bokmål), Romanian, Slovak, Slovenian and Turkish for the 3D view, the room panel and the card's texts (about 150 each). Everything else still shows in English in those languages until someone adds it; the files are plain JSON in `frontend/lang/`, and a pull request that completes one is very welcome. +- **Card templates:** *Card templates* in the editor's settings set a dashboard card up once, with the card's own settings dialog and a name (say `kitchen_tablet`). On a dashboard card you then choose the template in its settings (or `template: kitchen_tablet`); the card's own options win. A change in the editor reaches every card that uses the template. *Reload screens with this template* and *Reload all screens* (also the action `nextfloor.reload_screens`, with an optional `template`) make the open tablets load their page again a few seconds apart, for example after an update. +- **3D print export:** a *3D print (STL)* button in the 3D view's settings saves the house as an STL file (walls, floors, furniture and outdoor areas of every floor) at 1:100, one metre becoming 10 mm. Windows, lights and the roof are not in it. +- **Right click goes one step back** (the view's settings, or the card option `right_back: true`, off by default): a short right click in the 3D view closes the room or goes from the floor back to the house, like a double tap on empty space; dragging with the right button still pans. +- **Two decoration packs, free:** *Winter & Christmas* (Christmas tree, Advent wreath, window star, candle arch, light-up reindeer, snowman, fairy lights) and *Halloween* (pumpkin, ghost, gravestone, witch's cauldron). The glowing parts follow a light or switch you link; to show a decoration only in its season, set *Only show while …* on the piece. That makes 43 furniture packs. +- **Tilt furniture:** a piece of furniture has *Tilt front/back* and *Tilt sideways* (degrees) in its form, for a leaning ladder, a tilted picture or a roof-sloped shelf. (Owned 3D models are not tilted.) +- **A card for chosen rooms:** the dashboard card's settings list the rooms (*Only these rooms*, YAML `rooms: [id, …]`); the card then shows just those rooms with their furniture, devices, doors and windows, and cannot leave them, for example for a tablet in the kitchen. Nothing ticked: the whole plan as before. +- **Gates in fences:** a fence's form has *+ Gate in the fence*: a gap in one side with gate posts and a garden gate, a double gate or a sliding gate. With a motor or switch (cover, switch, input_boolean, lock) and/or a contact the gate opens in 3D: garden and double gates swing inwards, a sliding gate runs along the fence. (Tapping the gate in 3D to switch it is not there yet.) +- **Sun arc and compass:** the editor's settings have *Sun arc and compass*: today's path of the sun as an arc over the plot, with a ring on the ground, the compass points (north in red) and a bead where the sun stands now. It uses your home's location in Home Assistant and follows the time-of-day slider. +- **Sloping free-standing walls:** a wall drawn with the wall tool can fall from one end to the other (*◢ Sloping* in its form, with a height at each end). +- **Overhang per roof side:** a roof section's form has *Overhang per side*: the eaves and both ends of the ridge each get their own overhang; unset sides stay automatic (none where the roof meets the house). +- **Floor plan only:** a *Floor plan only* button in the view's settings (and a card option `plain: true`) leaves the furniture out of the 3D view and draws walls, doors, windows and stairs; devices and their pins stay. +- **Import of an Apple room scan** (an iPhone or iPad with LiDAR, scanned with an app that exports the RoomPlan JSON): walls become the room, doors and windows sit on their walls with width and sill, and sofa, bed, table, chair and a few more objects become furniture. Choose the file under *Backup → Import*; the plan format page now also describes furniture, free walls, outdoor areas and devices for AI drawn plans. +- **A default room for people** (thanks @ToniB1984, #71): in the *Presence* section every person has a *Default room*. While they are home and no room sensor names a room, they stand there; it also works without any room sensor. Besides persons, any other entity that is on or home (an input_boolean helper, a device tracker, a binary sensor) can be added there for the same. +- **Hide devices in Outside** (thanks @eskahone, #83): the house settings have an *Outside: hide devices* list; the devices on it stay in the plan but no longer show in the Outside panel. +- **Reverse the direction of an awning or curtain** (thanks @Spawnkiller1, #100): a curtain, roller screen, awning or gate linked to a cover has a *Reverse the direction* checkbox, for the ones that move the opposite way in the plan than in reality. + +## [0.25.4] + +### Added + +- **People in their rooms** (tested thoroughly by @thelichtler-cloud, #71): the house settings have a *Presence* section again. Per `person`, pick a room sensor (ESPresense, Bermuda, a template sensor …) whose state names the room or its area; while the person is home and the sensor names a room, their picture (or initials) stands in that room, two people side by side, and moves along when they change rooms. The house view counts the people per floor. The feature existed but was switched off until it had been tested. +- **Size of the sound rings per speaker** (thanks @thelichtler-cloud, #94): a speaker or TV linked to a media player, and a media player marker, have a *Sound rings (%)* field. A small speaker such as an Echo Dot can get small rings, and 0 switches them off while the cover picture and the glow stay. + +### Fixed + +- **Pets stood still for good while anything else moved** (thanks @thelichtler-cloud for the exact diagnosis, #97): a resting pet only counted its rest down while the view was otherwise idle, so with energy flows, sound rings or weather running it walked once and then stayed put. Pets now keep their own clock and walk on every few seconds. +- **Store plugins on Home Assistant opened over plain http** (thanks @MarioFey1979, #78): a browser on `http://` has no built-in checksum function, so NextFloor imported the plugin straight from GitHub, which serves it as plain text, and the browser refused it (the Cameras plugin loaded nowhere and no camera appeared in the lists). The file is now checked with NextFloor's own SHA-256 and loaded from memory, as over https. +- **A plugin added as `/local/www/…` never loaded** (thanks @MarioFey1979, #78): Home Assistant serves its `www` folder as `/local/`, so a path with `www` in it pointed nowhere and the plugin's devices (cameras, say) were missing from every list. Such a path now loads from `/local/…`, and a new one is stored that way. +- **Zigzag in a straight interior wall** (thanks @Dragi2k, #65): one straight wall that runs past several rooms (bathroom, store room and hall along the bedroom, say) was drawn in pieces, and a piece next to an outer wall sat flush on one side while its neighbours sat centred, so the top of the wall jumped back and forth. The whole straight wall is now aligned as one. + +### Changed + +- **The editor and the card's settings load faster**: they now use the texts the main bundle already has instead of bringing their own copy, so the editor download is about 200 KB smaller and the card's settings shrink from 236 KB to 31 KB. + +## [0.25.3] + +### Fixed + +- **Close gaps flattened a wall that changes its thickness** (thanks @Dragi2k for the plan, #65): when one room faced two walls of another room at different distances (a wall that is thicker over part of its length), all of them were pulled onto one line, so the step disappeared and the room changed its shape. Each room now keeps its step: the nearer wall closes its gap, the thicker part stays as drawn. + +## [0.25.2] + +### Fixed + +- **Outside on a small tablet** (thanks @eskahone, #83): with Outside open, the Today card (calendar) lay over its panel and caught the taps, so Outside could not be closed again. The Today card now steps aside while a room or Outside is open, as it already did for rooms. + +## [0.25.1] + +### Added + +- **Czech** (thanks @MiraK-2000, #76): the whole interface, the setup and the announcement action in Czech. That makes eleven languages. +- A room's temperature, humidity or CO₂ can be read from several sensors that are averaged: pick one in the room's climate settings, then add another one below it (#80). +- A favourite in the star menu can be limited to one floor (dropdown beside it in the house settings); it then shows only while that floor is open (#73). +- A lamp can be set to "switch only in the room panel" (no brightness, colour temperature or colour sliders), and the name given to a placed device now also shows in the room panel (#73). +- The house settings choose which facts the room panel shows in its header: sun hours, comfort, airing hint, fuse-box circuits (#73). + +### Fixed + +- **A blind in front of the garage door** (thanks @eskahone, #85): a garage door linked to a cover drew a roller blind with its box in front of it, and the blind moved with the door. The cover now moves only the garage door itself. +- A wide window or sliding door with two blinds: a tap on its right half now opens the second blind; before, every tap went to the first one (#79). +- The plan check no longer offers devices as missing that a window, door or piece of furniture already picks up automatically through its area (a KNX blind, say) (#81). +- A plan with floors but no room no longer says "no floor plan yet": the 3D page now says that walls alone are not enough and that a room is drawn with *Rectangle* or *Free form*. + +## [0.25.0] + +### Fixed + +- **Close gaps no longer puts corners into straight walls** (thanks @Dragi2k, #65): a wall that consists of several edges in a row (for example with a point in the middle of it) is now moved as one wall. Before, each part moved to its own neighbour, so a corner appeared in the wall that was not there before. +- **Clean view on a tablet** (thanks @Melles96, #75): the eye button that brings the controls back now sits at the top edge, so a tablet's taskbar or gesture bar can no longer cover it. *Esc* brings the controls back as well. +- **Phones held upright** (thanks @Duell10111, #70): the floor pictures step aside (the floor tabs above do their job), and the row of view switches along the bottom is one row that scrolls sideways, with a fade at its edge, instead of a column that spilled over the floor cards and the star. +- **Editor side bar covered** (thanks @marcelgschwendtner, #67): a row of tools wider than the plan no longer pushes the plan over the side bar; the row scrolls inside its pill. +- **Second blind on a door** (thanks @tfischer84, #79): a sliding door can now have a second blind for its right half, as a window can. +- **Clock on the card** (thanks @HA-Luz, #68): the clock now keeps ticking; it only moved when the view was reloaded. + +### Added + +- **A glass wall that follows a curved wall as one pane** (thanks @Sugsss, #66): a curved wall is stored as a chain of short straight edges, and a glass wall could only be as wide as one of them, so glazing an arc meant one pane per edge with a mullion at every bend. A glass wall placed on a curved wall now runs on from edge to edge as a single pane, with jambs only at its two ends, and stays one pane when it is moved, lengthened or deleted. It is stored as an ordinary opening per edge, sharing a `front` id, so the plan, the printed plan, the sun hours and the walls themselves need no special case. +- **Glass walls without mullions**: a glass wall divided into panes of about 0.9 m by itself, with no way to say otherwise. Its form now has a *Panes* field: `0` gives one single pane across the whole wall, for the large glazing modern houses have, and any other number sets how many panes the mullions make. Left empty, a plan keeps exactly the spacing it had. +- **Sanitary pack VIGOUR derby** (thanks @huepfer13, #63): a wall-hung WC, a urinal, a 60 cm washbasin, a paper towel dispenser and a soap dispenser in the sizes of the VIGOUR derby series. That makes 41 furniture packs. +- **A robot vacuum's own trail on the plan** (thanks @Sugsss, #77): a `robot_vacuum` on the plan drove lanes the view invented inside the room it reports. When the robot's integration puts its map on a camera — `vacuum_position`, `charger` and `path` as attributes, which NarwalIntegration's map card does — the view shows the truth instead: the robot stands where it says it is, facing where it faces, and the floor keeps the pad it has really driven, while the dock is drawn where the robot reports it. The robot's grid is tied to the plan by two places known in both (`settings.vacuum_map`); `mirror` covers a map whose y axis runs along plan −z, which two places alone cannot tell apart from a turn. The camera is found by its attributes, so nothing has to be chosen; the calibration is one tap — select the robot's dock, let it drive away, tap it on the plan — and a plan without one keeps the lanes it had. Ten minutes after the robot docks the pad fades out — the timeline keeps a finished clean, the floor does not. The attribute names are the vacuum map card's, so the Xiaomi map extractors, the Roborock integration, NarwalIntegration and any other integration that publishes them fit — including units in millimetres, since the two places set the scale. The manual and the Anleitung describe the calibration. + +## [0.24.0] + +### Added + +- **NextFloor is in the official HACS store.** Install it by searching for *NextFloor* in HACS, no custom repository needed any more. If you installed it as a custom repository, nothing changes: your installation, plan and settings stay as they are and updates keep coming through HACS. A one-time notification in Home Assistant tells you so, in your language. The README, the manual and the Anleitung now describe the store install. Thank you to the HACS team for the review. +- **Choose what a double tap on a room switches** (thanks @mymoll, #62): settings → *Double tap on a room*: the lamps in the plan and every light of the room's area (as before), only the lamps in the plan, or nothing. Smart plugs that Home Assistant reports as lights (Hue plugs) are no longer switched by accident when they are not placed as a lamp. The card can override it with `room_double_tap: auto | area | plan | off`. + +### Fixed + +- **Shared plans and share views kept data of your home** (thanks to the HACS review): the copy for sharing removed the entity links but kept the settings as they were, so the map position of your home, favourites, own buttons and warnings, calendars, status sensors, the fuse box, announcement phrases and plugin paths travelled with the file, and so did picture rules of screens, light moods, own tap actions, room panel entity lists and Home Assistant areas. A shared copy now keeps only the look of the house (walls, roof, north, units, start view) plus its rooms, furniture and doors, and every field that names an entity, area or device of your Home Assistant is cleared on top of that, so a field added later cannot slip through. Your own plan and the normal backup are not changed. Files you shared earlier still hold the old data; share them again if that matters. + +## [0.23.1] + +### Fixed + +- **Doors in a lowered room** (thanks @ayque): the door leaf, frame, threshold and handle now start on the room's own lower floor instead of the floor level, so there is no gap under the door any more; the edge lines of the opening follow too. + +## [0.23.0] + +### Added + +- **Chinese setup and docs** (thanks @Sugsss): the config flow, the announcement action and the floor sensors in Simplified Chinese, plus a Chinese README and guide. +- **IFC import**: *Backup → Import* also takes an `.ifc` model from a BIM program (Revit, ArchiCAD, Allplan, Vectorworks …) – its storeys become floors at their elevation, its spaces rooms with their names and footprints, in the model's unit turned into metres. NextFloor draws the walls from the rooms. +- **Someone there?** The room panel says whether its motion, occupancy or presence sensors see someone now (*🚶 someone here*), or when they last did (*🚶 last seen 12 min ago*). +- **Power of sockets and switch plates**: a socket or switch whose button is a smart plug or a measuring switch now counts its power – in the room's power and the heat map *Power*, in the room panel, and in the power flow – from the power sensor on that button's device. + +## [0.22.0] + +### Added + +- **A room on its own level**: *Floor level* in the room form puts a room's floor lower or higher than its floor (a sunken entrance at −0.39 m, a split level). Its floor, the bottom of its walls, its doors and windows, the furniture and device pins in it move with it, the step to the rooms around it shows, and its living area counts from its own floor; the ceiling stays where it is. Thanks to @ayque ([#57](https://github.com/therealMRBK/NextFloor/issues/57)). +- **Simplified Chinese**: the whole interface in Simplified Chinese (中文), fetched when Home Assistant runs in Chinese. Thanks to @Sugsss ([#59](https://github.com/therealMRBK/NextFloor/pull/59)). +- **Rooms open to the floor above**: a room's *Ceiling height* may now be higher than its floor – a living room open up to the floor above or under the roof, a gallery. Its walls and windows rise with it, ceiling lights hang from the high ceiling, and the floor above stays open over it; that floor's editor shows the area hatched. Thanks to @Xtiger123X ([#55](https://github.com/therealMRBK/NextFloor/issues/55)). +- **Furniture studio in the editor**: *🛠️ Build your own piece* at the top of the furniture library builds a cabinet (any width, doors, drawers, handles, plinth or legs), a shelf, a lamp (floor, table, pendant, wall) or a device with a display, in centimetres and with a front view that follows every change. It goes straight into the plan and into the pack *Own furniture*; *Change in the studio* on a placed piece changes it again, everywhere it stands. +- **A meter per floor**: *Floor meter (power)* in the floor form takes a power sensor for that floor alone (a sub-meter, a flat). Its value shows on the floor label in the house view, and in the floor's own view the house card adds a row with it and its share of the house's use. +- **Plan check**: *✓ Check the plan* at the top of the editor's side panel lists, floor by floor, what is missing or off – rooms without a Home Assistant area (with the area of the same name to link in one tap), areas without a room, devices of a room not in the plan yet, rooms lying on top of each other, doors and windows off their wall, pins or furniture pointing to entities Home Assistant no longer knows, and **standby eaters** – devices that are off but still draw more than 3 W, with what that costs over a year. Each line has a button that shows the place or makes the fix; undo works as always. +- **Sensors from the plan**: NextFloor now adds sensors to Home Assistant – *Open windows and doors* and *Lights on*, for the whole house and for every floor (e.g. `sensor.nextfloor_ground_floor_open_windows_and_doors`). They count what the plan links (contacts, garage doors, device pins and lamps), list the entities that are open or on in their `entities` attribute, and follow the plan when floors are added or renamed – ready for automations ("nothing open when the alarm goes on") and voice. +- **Everything off, with undo**: the room panel has *⏻ Everything off* while two or more things are on – lights, switches, fans and media (playing speakers pause, TVs switch off). In a floor's view the bar on top has the same for the whole floor (*⏻* with the number of devices). For ten seconds *↶ Undo* brings everything back as it was, lights with their brightness and colour. +- **Living area**: every room shows its living area in the editor, counted like the German Wohnflächenverordnung – the floor inside the walls, in full from 2 m clear height, half between 1 and 2 m under a slope, nothing below. The floor form adds it up for the floor and the house. Garages, cellars and utility rooms are left out by their name; *Counts as living area* in the room form decides it by hand. +- **The plan on paper**: *🖨️ Print plan / PDF* in the floor form opens every floor as a clean black-on-white drawing at 1:100 – walls, doors with their swing, windows, garage doors, room names with their areas, the outer measurements and a metre bar – and a table of all areas at the end. The browser's print dialog prints it or saves it as PDF. +- **Quality by itself**: with the quality on *Auto*, the 3D view now watches how fast the tablet draws while something moves. When it keeps drawing too slowly it uses fewer pixels, a quarter step at a time, and the simple look when even that is not enough; with plenty of room left the pixels come back slowly. *Low* and *High* stay as chosen. +- **Plan versions**: *📌 Save this state …* under *Backup → Restore points* keeps the plan under a name ("before the renovation"); named states stay when the automatic restore points go, and can be deleted again. *Compare* on any point lists, floor by floor, what differs from the plan as it is now – rooms added, removed, renamed or reshaped (with the change in m²), doors and windows, furniture moved, devices placed or removed. +- **Easy to read**: *Aa Easy to read* in the view options (and `readable: true` for the card) gives stronger contrast and larger text – the bars and the room panel a size larger, the pins and floor labels in 3D in bigger letters, Home Assistant's quiet greys in the full text colour. Made for wall tablets across the room and for anyone who reads better that way. +- **First steps**: a new plan starts with a short tour of four cards – drawing rooms, doors and windows, furniture and devices, looking and checking – naming the buttons as the editor shows them; it can be skipped and does not come back. The round *?* in the corner of the plan (or the *?* key) opens the sheet of the editor's keys. +- **Power per room**: the heat map has a new mode *Power* that colours every room by what its devices draw now – the power sensors of its device pins and furniture added up, each counted once, the house's own meters left out (from blue at nothing over green and yellow to red at 3 kW). The room panel shows the same next to temperature and humidity (*⚡ 340 W*), and below it what the room used today and this month, from the statistics of those sensors, with the month's cost at the house's tariff (*⚡ today 0.46 kWh · month 3.34 kWh · 0.97 €*). +- **Notes in the plan**: a right-click (or long press) in the editor has *✎ Note here* – a note pinned to that spot ("bleed the radiator", "fuse 12: cooker"), with an optional day it is due. In 3D it stands as a yellow pin on its floor, orange from the day it is due, and a tap shows its whole text; the search finds notes by their text. +- **Sun in the rooms**: the heat map has a mode *Sun* that colours every room by the hours of sun it gets today through its outside windows – from the plan, its compass and the sun's path at the home's place (neighbours, trees and the roof's overhang are not counted). The room panel shows the same, with the directions its windows look to (*☀ 5.5 h of sun today (S, W)*); a tap on *☀ Sun over the year* adds a bar for every month. +- **Share a view**: *🔗 Share a view* under *Backup* saves the house as a small HTML file that opens in any browser without Home Assistant – it shows the plan in 3D through NextFloor's online demo, with the furniture packs it uses and without any devices or entities, like a template. To show the house to family or a planner. +- **Shade hint**: when the sun stands on a room's outside windows, the room is 24 °C or warmer and those windows' blinds are open, the room panel says so (*☀ Sun on 2 windows at 25.3 °C – lower the blinds?*) and *Lower* closes them in one tap. +- **Clean this room**: a room's form has *Cleaning* – the script or button that sends the robot vacuum there (the room cleaning of your robot's integration). The room panel then shows *🧹 Clean*. +- **Fuse box**: the house settings have a *Fuse box* – circuits by name ("F12 kitchen") with the rooms they feed. The room panel names a room's circuits (*🔌 F12*), and the search finds a circuit and opens its room. +- **Heating with the window open**: when one of a room's windows or doors stands open (its contact or tilt sensor) while the room's thermostat heats, the room panel says so (*🪟 1 window open while the heating runs*) and *Heating off* switches it off – or to its lowest temperature where it has no off. +- **Low batteries**: the batteries of the plan's devices – device pins, the contacts, locks and blinds of doors and windows, linked furniture – from the battery sensor on their device or their own battery attribute. Below 20 % they are in the plan check (*🪫 Battery low: kitchen window (12 %)*) and in their room's panel. +- **Lights on, nobody there**: when a room's motion, occupancy and presence sensors have seen nobody for ten minutes while lights are on, the room panel says so and *Lights off* switches them off. +- **Comfort score**: every room with climate sensors gets a score from 0 to 100 – the temperature in its band (20–23 °C, 22–26 °C in summer), humidity between 40 and 60 %, CO₂ up to 800 ppm, where one bad value always shows. As the heat map mode *Comfort* and in the room panel (*😊 Comfort 85*). +- **Open for …**: the room panel shows how long the room's windows and doors stand open (*🪟 open for 12 min*), the one open longest – handy for airing. +- **Measurements in the plan**: *📏 Measurements* in the editor's bar labels every room edge with its length; the switch is remembered on the browser. +- **Temperatures on the floor label**: a floor's label in the house view shows its coolest and warmest room (*19–22 °C*). +- **Door not locked at night**: *Warn at night when a door is not locked* in the settings names the plan's door locks that stand unlocked between 10 pm and 6 am, as a quiet note in the warning bar. +- **A power sensor for lamps**: lamps now have the *Power sensor* field too, like every other electric piece – for a light behind a measuring switch or a smart plug. Its watts show on the lamp's pin and count in the power flow and the room's power. Thanks to @Robsonator ([#56](https://github.com/therealMRBK/NextFloor/discussions/56)). +- **Stairs: the landing where you want it, and a mount height**: L and U stairs have *Risers up to the landing* – the flights can differ (8 up to the landing, 11 after it), the form says how high the landing lies. Stairs now have the *Mount height* like other furniture, so the upper flight can start on a landing. Thanks to @ayque ([#58](https://github.com/therealMRBK/NextFloor/issues/58)). + +### Fixed + +- **Floor pictures on a low card**: on a stage lower than 520 px (a dashboard card of 420 px) the floor pictures are smaller and stop above the star, the search and the buttons at the bottom left instead of sliding under them. + +## [0.21.0] + +### Added + +- **Turned roof sections**: a roof section has a *Turn (°)* in its form and turns about its middle – a wing at an angle, a roof over a house that does not stand square to the plan. Its slopes, ridge, gables, solar fields and the ceilings under it follow. Thanks to @XingLii ([#53](https://github.com/therealMRBK/NextFloor/issues/53)). +- **DXF import**: *Backup → Import* also takes a `.dxf` drawing from a CAD program – closed polylines become rooms, lines and open polylines free walls, in the drawing's unit turned into metres. +- **A tap on an own warning**: opens the entity's details by default, or – as chosen per warning – switches the entity or jumps to its room. Thanks to @HA-Luz ([#52](https://github.com/therealMRBK/NextFloor/discussions/52)). + +## [0.20.0] + +### Added + +- **Half-hips of any height**: a half-hip end of a roof section has a slider for how high up the gable its hip starts – from a large hip down low to only the tip. +- **Areas within a room**: a room can take more Home Assistant areas as its parts (*+ Area within the room*) – a reading corner, a shelf, the kitchenette of a living room – whose devices and sensors then belong to the room: in its panel, the climate, the lights and the warnings. +- **Pets where they really are**: a pet from the packs can follow a room sensor (Bermuda, ESPresense or any sensor naming a room, with a tag on its collar) – it appears in the room the sensor names and roams it there. +- **Light designer**: set a room's lamps as you like and press *+ Save mood* in its panel – the mood is kept with the plan, a tap on ✨ sets it again, and *→* carries it over to another room's lamps (the first lamp takes the first setting …). +- **Layers**: a floor can be marked as a *Layer* – all the trees, the decoration, the garden furniture – and the 3D view shows an eye for it at the top that shows or hides it with its pins, remembered on each device. +- **Lamps under the roof slope**: a ceiling lamp, fan or hanging item in an attic room gets *📐 Up to the roof slope* in its form, which hangs it from the underside of the roof right above it; its height stays adjustable. +- **Walls**: a split wall can have its own thickness on each part (a thick outer wall next to a thin glass front), and the room form shows a rectangular room's inside size from wall face to wall face. +- **Solar racks**: a field on a flat roof can stand on **east-west racks** – every second row turned, the pairs back to back, low and close – and a field on a pitched roof can stand on a rack that tilts it further than the roof (the upper edge on brackets). +- **L- and U-shaped sofas without a pack**: the built-in sofa has a *Shape* – straight, L (mirror it for the other side) or U – with a chaise at one or both ends; choosing one makes a small sofa large enough for it. +- **Own warnings**: *House → Own warnings* turns any entity into a line in the warning bar while it is in a state – "Water tank empty" from the robot vacuum, "Dishwasher done", "Salt low" below 20 (several states with commas, `<20` or `>80` for numbers), for the whole house or one room, with a colour of your choice for the stripe on the left. They look like the warning for a contact that stops answering. Thanks to @HA-Luz ([#52](https://github.com/therealMRBK/NextFloor/discussions/52)). +- **Which sensor set the alarm off**: when an alarm panel is triggered, the banner names the door, window or motion sensor that set it off (Alarmo tells it, otherwise the one that changed just before), and only its room pulses red instead of the whole house. +- **Outdoor areas like rooms**: a garden, terrace or pool can be linked to a Home Assistant area – its devices and sensors join the Outside panel, and a pin on the area opens it. A pool, pond or bed can show its water temperature and pump on that pin ("24.5 °C · pump on"). +- **Robot mowers mow their lawn**: a robot mower or its dock from the *Garden 2* pack linked to a `lawn_mower` drives lanes over its lawn in 3D while it mows (around the beds, ponds and terraces on it), and drives home when it returns. +- **Wi-Fi map**: the map selector has a new **Wi-Fi** mode – every access point, router or mesh node from the packs linked to its device spreads its reach as a disc over the floor (through the walls), blue while it has room, amber when it is busy, red when it is down; its pin tells how many devices it carries, and the legend sums up the access points, their devices and which network devices of the plan are offline. +- **Room climate**: the heat map has a new **Mould** mode – the risk at each room's coldest wall from its temperature and humidity – and the temperature map uses a summer scale from May to September (rooms count as hot later). Rooms without a sensor of their own take the temperature and humidity of their thermostat. The room panel shows the room's temperature over the last 24 hours as a small curve, and both the panel and the *Values* map tell when to air a room (too much CO₂, too damp, risk of mould). +- **Underfloor heating**: a room can name its floor heating's thermostat, valve or switch, and its floor glows warm in 3D while it heats. +- **Heat pump**: a heat pump from the packs linked to any entity of its device shows a card with what it does (heating, hot water, cooling, defrosting), flow and return, the outside temperature, the power it draws, the heat it delivers and its COP as a ring – and with the energy flow on, its heat runs into the house in orange. +- **Your 3D printer, live**: link a 3D printer from the packs to any entity of your printer's device (Bambu Lab, OctoPrint, Moonraker/Klipper or PrusaLink), and while it prints a card floats above it with the model's picture, the progress, the time left and "done at", the layer, nozzle and bed temperatures and the filament colours of the AMS – and the print grows on the bed in 3D in the colour of its filament. +- **"Today" on the wall tablet**: choose calendars in *House → Calendars for "Today"*, and a card top right in the 3D view lists the day's appointments (all-day ones first, past ones dimmed) together with the waste bins collected today or tomorrow. A tap on its title folds it; the card option `today: false` hides it on a dashboard card. +- **Move a pin by hand**: when devices stand close together and their pins cover each other, *Move the pin* in the device's or furniture's form pushes the pin aside or up (in metres) while the device stays where it is. +- **Small tablets and phones**: a 🔍 zoom in the view options (card option `zoom`) brings the fitted views closer so the house looks larger on a small tablet; *🎥 Keep camera* (card option `keep_camera`) keeps the camera's side, height and distance when you switch floors; the room panel takes a little more of the width on small landscape tablets; and on a phone the editor's tools are one dropdown instead of a row of eleven buttons. +- **Favourites first**: the star menu can stand open from the start and a size larger (*★ Menu open* in the view options, card option `central_open`) for a wall tablet that mostly runs scenes; own buttons light up while their entity is on (the one they open or switch, or one you name); and the room panel lists the room's scenes at the top. +- **Speakers and TVs get their own quick menu**: a tap on one opens play/pause, back and next, the volume, its sources (inputs, apps, Spotify Connect …) and the stations and playlists of *House → Presets*. A preset can now be kept to some speakers – the kitchen radio station on the kitchen speaker only. +- **The car tells more**: a car plugged in at a wallbox nearby hangs on its charging cable in 3D (with the energy flow on), and the power runs along it while it charges. Its card says how far it is from home while it is away, when it leaves (a departure time it reports, or one set on the spot), and warns which doors, hatches, windows or the charge port stand open. +- **More of the energy picture**: the house card now shows the last seven days as bars (sun and use per day, from Home Assistant's long-term statistics), gas and water meters (*Energy → Balance*) appear in the energy bar and on the card, the card stays above the open floor in the floor views, and a home battery shows its charge on its own front – a bar that fills, green when full, yellow, red when nearly empty. +- **Venetian blinds, inside blinds, two blinds per window and Somfy "My"**: a window's blind can be a roller shutter outside (as before), a venetian blind whose slats turn in 3D with the cover's tilt, or a roller blind inside behind the glass. A wide window takes a second blind for its right half. A favourite position shows as **My** in the blind's quick menu – a blind with positions moves there, a Somfy RTS motor without feedback goes to its own My. +- **Every electric piece works alike**: any electric piece of furniture with a switch or power sensor shows its draw beside its state on its pin ("On · 1.2 kW"), and its status lights and display light up while it runs – a coffee machine, a compressor, a 3D printer – like the washer and dishwasher always did. +- **Lamps with several bulbs**: a lamp's form takes up to four more lights of the same fixture – a night light, an ambient ring, an uplight. While the main light is off, the lamp glows in 3D with the next light that is on, a little dimmer, and its pin says which one. +- **Picture frames with your own photos**: the new *Pictures & frames* pack (frames in four formats and six colours, canvas, poster, table frame, digital photo frame, picture ledge) shows a photo you upload in the frame's form, a picture address (/local/…) or the current picture of an image or camera entity – a photo of the day changes on the wall by itself. A white mat of any width, and the photo fills the frame or shows whole. +- **Show a piece only while …**: every piece of furniture can wait for a helper, a calendar, the sun or any sensor before it appears in 3D – the Christmas tree only while *input_boolean.christmas* is on, the paddling pool only in summer, a tent while a calendar says "camping". Several states separated by commas, or the other way round; the editor always shows the piece. +- **13 new furniture packs with 124 pieces**: *Season & decoration* (a Christmas tree whose fairy lights follow its light, Advent wreath, window star, candle arch, light-up reindeer, outdoor string lights, pumpkins, Easter tree, snowman, presents), *Smart home 2* (siren, Wi-Fi access points, smoke, CO, presence and water leak sensors, air quality monitor, dehumidifier, cube lamp, video doorbell), *Building services 2* (water tank, oil tank and oil boiler, water softener, buffer tank, cistern, ventilation unit, indoor heat pump), *Wellness* (sauna, barrel sauna, infrared cabin, hot tub, plunge pool, ice bath, steam shower, lounger – the heated ones link to a climate entity and show its temperature), *Garden 2* (water feature with light, pond with pump, robot mower and its dock, sandbox, beach chair, wood pile, bird house, raised bed, garden shower), *Kitchen 2* (bean-to-cup and espresso machines, kettle, toaster, stand mixer, cooking food processor, air fryer, microwave, wine fridge, sparkling water maker, slim dishwasher), *Vehicles 2* (motorbike, scooter, camper van, trailer, e-bike, cargo bike, quad, boat on a trailer, each in six colours), *Outdoor kitchen & terrace*, *Workshop 2*, *Japandi & Scandi*, *Loft & industrial*, *Indoor greenery* (plants that show their soil moisture) and *Music & studio*. The library has two new shelves for them: *Music & studio* and *Season & decoration*. + +### Changed + +- **A tap on a speaker or TV opens its quick menu** (play, skip, volume, sources, presets) instead of Home Assistant's details; *Details …* in the menu still opens them. +- **Scenes come first in the room panel**, above the lights. +- **Every electric piece shows its power beside its state** on its pin. + +## [0.17.0] + +### Added + +- **Duplicate a floor**: the floor form copies the open floor on top of the house, with its rooms, walls, doors and windows, and on request its furniture, device pins and outdoor areas. The copy is unlinked from Home Assistant (areas, floor, furniture entities), so it can be set up for the new storey; energy devices stay on the original floor. +- **Move furniture to another floor**: the furniture form moves an item to the same spot on another floor. +- **Curved walls**: the ◠ Arc button on a wall of a room (in the room's wall list) or on a free wall bends it into an arc: type how far its middle bulges, outwards or into the room, and press *Bend*. A room sharing the wall bends along, doors and windows move with it and stay whole, and everything else (3D, solid walls, cut view, wall heights) treats the arc like any wall. Undo takes the arc back. +- **The house throws its shadow**: with north set, the house casts its shadow on the plot from the sun's real position, long in the morning and evening and paler behind clouds. It follows the "Sunlight and shadows" setting (formerly "Sunlight through the windows") and is off on the Tablet level. +- **Time of day**: switch on *☀ Time of day* in the view options (⚙), and a ☀ switch under the 3D view opens a slider over the hours of today, in Home Assistant's time zone. Sun patches, the shadow, the sky, the sun or moon and the *Auto* look follow the chosen hour once the slider is let go; tapping the switch again goes back to now. +- **Night sky and weather on the ground**: with the weather on, stars come out on a clear night; snow lies white around the house while it snows, and the ground turns dark and wet in the rain. +- **Stairs with a shape**: the new **Stairs** tool in the editor's toolbar draws a stair where you drag (it runs along the long side), and the stair from the library has a shape as well: straight, quarter turn with winders, L with a landing, half turn with winders, U with a landing or spiral, turning to the left or right, built solid, on stringers, on one spine or as floating steps, with or without risers and with a railing on either or both sides. The number of risers comes from the floor height and can be set by hand; the form shows rise, going and step measure and warns when the stair would be uncomfortable. The plan draws every tread with the walking line. Older stairs keep their look until you press **Set the shape**. +- **Stairs going down**: a stair can lead down from its floor, for example into a cellar that is not drawn. It opens its own floor and is drawn dashed in the plan. +- **Openings that fit the stair**: a shaped stair opens the floor above only where its steps lack 2.2 m of headroom, following its shape, instead of the whole rectangle. The stair's **Floor opening** choice opens the whole stair instead (an open stairwell) or nothing (a hatch or closed stairwell). Older stairs and the stairs of the *Stairs & railings* pack open their footprint as before. +- **LED strips that rise along a slope**: an LED strip's form has *Rise along its length (°)*, so a strip can climb up a sloped ceiling or a gable wall from the eaves towards the ridge, or follow a stair. Its low end stays at the mount height (or its high end under the ceiling), and its light and glow follow the strip. Thanks to @jan74berlin ([#36](https://github.com/therealMRBK/NextFloor/issues/36)). +- **Cable routes for the energy flow**: the energy tool's new *Cable routes* section draws where a cable really runs, from a solar field on the carport to the inverter and battery in the cellar, along walls and through ceilings across floors. The flow follows the route instead of an arc through the house, a battery's route is walked either way as it charges or discharges, and *Show as cable* draws it as a visible cable. Connections without a route keep their arc. Thanks to @galionsfigur ([#49](https://github.com/therealMRBK/NextFloor/issues/49)). +- **Outside, next to the floors**: a **🌳 Outside** chip beside the floors opens the house view with its own panel, like a room's, for every device outside the rooms: the irrigation valves, garden lights and sensors at a glance. A device on the roof or above a room that belongs outside (a weather station) gets *Belongs to Outside* in its form, so it no longer counts for the room below. The dashboard card shows the chip with its room buttons. Thanks to @jan74berlin ([#39](https://github.com/therealMRBK/NextFloor/issues/39)). + +### Changed + +- **New stairs are shaped stairs**: a stair placed from now on opens the floor above only where its steps lack headroom, so the opening is smaller than the whole rectangle as before. Choose *Floor opening → Over the whole stair* in its form for the old opening; stairs already in the plan keep theirs. + +### Fixed + +- **Cameras of an NVR are easy to find in the device list**: with the *Cameras* plugin, a camera that shares its device with the NVR's motion, person and vehicle sensors (ONVIF) now leads that device's row instead of hiding behind "more" after the sensors. Thanks to @toshi24 ([#50](https://github.com/therealMRBK/NextFloor/discussions/50)). +- **The clock top left no longer covers the sensors at the top**: with *Top left* chosen, the clock stands above the own sensors and the energy bar, which move down below it. Thanks to @toshi24 ([#35](https://github.com/therealMRBK/NextFloor/issues/35)). +- **Sensors a plugin handles can be placed**: the editor's device lists show every entity a plugin takes on, whatever its device class (a 3D printer's enum print-state sensor from Moonraker), and it leads its device's row. Entities no plugin handles are filtered as before. Thanks to @Luca-Bachini-Barr ([#51](https://github.com/therealMRBK/NextFloor/issues/51)). + +## [0.16.1] + +### Added + +- **Wall buttons in the plan**: `event.*` entities (Homematic, Hue or Zigbee wall buttons and remotes) can be placed like any device. Their marker shows when the button was last pressed, and a tap opens its details. Thanks to @jan74berlin ([#35](https://github.com/therealMRBK/NextFloor/issues/35)). + +### Changed + +- **The room form warns when a room's ceiling lies above its floor height** (it can come from an import or a floor height lowered later): walls, windows and doors stop at the floor height, so a window above it was squeezed. Thanks to @jan74berlin ([#37](https://github.com/therealMRBK/NextFloor/issues/37)). +- **The switches at the bottom of the 3D view take less room**: on a smaller window, a zoomed browser or a dashboard column they are drawn smaller, and in the panel the new ▾ button folds them into one "Switches" button (remembered per device). Thanks to @jan74berlin ([#38](https://github.com/therealMRBK/NextFloor/issues/38)). +- **Garden devices set to "Always show" are visible from every view**: a device placed outside every room (irrigation valves, outdoor lights, a pool pump) whose marker is set to "Always show" now also shows in the house view ("All floors") and while another floor is opened, wherever its floor is drawn. Other markers keep to their floor as before. Thanks to @jan74berlin ([#33](https://github.com/therealMRBK/NextFloor/issues/33)). + +### Fixed + +- **Sweet Home 3D import no longer doubles walls**: a wall that runs along a room for only part of its length was taken over whole as a free wall, so it stood twice along that room (windows in it could face the wrong way). Now only the stretches beyond the rooms become free walls. Re-import the plan to get the clean walls. Thanks to @alexhass ([#40](https://github.com/therealMRBK/NextFloor/issues/40)). +- **The roof sits on its walls**: at rest in the house view it hovered 13 cm above them, and while zooming in the walls under it showed through. It now rests exactly on its height and keeps hiding what is below until it has mostly faded. Thanks to @LDSign ([#41](https://github.com/therealMRBK/NextFloor/issues/41)). +- **A roof section stays on the floor under it**: on a slope, a flat garage roof could ride with a higher floor beside it ("Pulled apart" lifted it off the garage). A section now belongs to the floor whose rooms lie under it. Thanks to @LDSign ([#42](https://github.com/therealMRBK/NextFloor/issues/42)). +- **Device names under markers are readable again**: the caption of a device with its own name ("Show the name under the marker in 3D") was dark text on a dark plate in some themes; it is now light text on the dark plate in every theme. Thanks to @jan74berlin ([#34](https://github.com/therealMRBK/NextFloor/issues/34)). +- **TVs that only report "on"** (Samsung, LG on live TV, and others) show their channel, input and logo on the screen in the plan, and appear in the live media card, instead of staying blank. Thanks to @Luca-Bachini-Barr ([#31](https://github.com/therealMRBK/NextFloor/issues/31)). +- **Heaters from furniture packs glow while they heat**, as the built-in radiator does: link a towel radiator (or any pack heater) to a thermostat and it glows orange while that thermostat heats; a thermostat or A/C unit with a display glows on its display. Thanks to @Luca-Bachini-Barr ([#32](https://github.com/therealMRBK/NextFloor/issues/32)). + +## [0.16.0] + +### Added + +- **Furniture builder** ([open it](https://therealmrbk.github.io/NextFloor/builder/)): build your own furniture in the browser from boxes, cylinders, tapers and round bodies, in centimetres, beside a 3D view that draws it exactly as NextFloor does. Start from a template (cabinet, table, shelf, floor lamp, sofa), tap parts in 3D to select them, set colours that follow the look, lamps and screens. The builder checks the pack as NextFloor's import does, keeps it in the browser, saves it as a pack file, and shares it in the community store with one button. +- **Community furniture** (Extensions → Furniture packs): furniture others built with the builder and shared, checked by the store and by NextFloor's import, installed with one tap; a newer release of an installed pack shows as an update. +- **Announcements, free for everyone**: *"Dinner is ready!"* – and the room that should hear it, hears it. + - **In the room panel**, a **📢 Announcement** section for rooms with a speaker: tap a sentence or type your own. Own sentences under *Editor → Settings*. + - **Each room speaks through its own speaker**: chosen in the room's form, else one placed in the room, else a voice satellite, an Echo or a speaker of its area (never a TV or a speaker that is off). Voice satellites chime, Echos make a real announcement (Alexa Devices or Alexa Media Player), speakers that can (Sonos and others) lower their music and play on after, every other speaker uses Home Assistant's text-to-speech. + - **Quiet time per room** (a nursery from 20:00): announcements to several rooms leave it out, one meant only for it still gets through. + - **Every open NextFloor screen** (panel or card) shows the message big over the house, plays a soft chime and speaks it. A screen can get a name (⚙ → 📢) to be addressed alone, or stay silent. Card options `announcements` and `screen_name`. + - **The action `nextfloor.announce`** for automations (message, rooms, floor, screens, on_speakers, on_screens, tts_entity); it answers which speaker said it and which rooms were left out. +- **Own sensors at the top of the 3D view** (Editor → Settings, up to 12): the outside temperature, the alarm, the air quality – each with its name and value at the top left, in an opened room too; a tap opens its details. Card option `sensor_bar`. +- **Markers only while active**: a device's marker can show *Only while active* (a motion sensor while it detects, a contact while open, a device while on), and *Editor → Settings* can show every motion, occupancy and presence sensor only while it detects something. +- **Irrigation**: a lawn sprinkler (garden pack) linked to a valve or a switch throws water in arcs around it while it runs – six jets that turn slowly, as far as its *Reach of the water* (default 3 m). The irrigation valve box links to a valve too. +- **Valves** (`valve.*`, irrigation or the main water) work like switches everywhere: they show open or closed, count as on while open, and a tap opens or closes them. +- **How opaque the glass walls are**: a slider under ⚙ (per screen) and the card option `glass_walls` set the walls you look through into the rooms from almost invisible (0 %) to opaque (100 %); 20 % is the faint glass as before. +- **Fridge and freezer temperatures**: a fridge (also a pack's fridge or freezer) takes a thermometer for the fridge and one for the freezer compartment. Its pin shows both ("4.3 °C · −18.2 °C") and lights up as a warning above 8 °C in the fridge or −12 °C in the freezer; sensors in °F work too. +- **Lift-and-slide doors and sliding windows**: a new kind *Lift-and-slide door*, and every window can now open *sliding*. The pane at the hinge side slides in front of the fixed one when its contact reports open; with two leaves the two middle panes slide outwards, each on its own contact. The plan draws the panes on their two tracks. +- **Top-hung windows**: a window can open *top-hung* – its bottom swings out of the wall when its contact (or a tilt sensor) reports open. +- **Opening angle for doors**: every door has an *Opening angle* (default, 15° to 180°). With a contact the leaf opens that far as soon as it reports open; without one it stands that far open instead of half open. A door that is only assumed to stand open no longer glows as open. *Default* keeps everything as it was. +- **Warning for contacts that stop answering** (off by default, Editor → Settings): when a door or window contact has been unavailable for 10 minutes (an empty battery, out of radio reach), a note in the warning bar names it, because the window then looks shut in 3D although nobody knows. It is a quiet note: the room does not pulse and the view does not jump to it. A restart of Home Assistant does not warn. + +### Fixed + +- **A glass wall placed from the toolbar is a glass wall**: dropping the *Glass wall* kind made a plain terrace window; it now keeps its look (doors still pick room or front door by their wall). + +## 0.15.1 + +### Changed + +- **Furniture with an own tap action keeps showing its state** by @Mika2108 ([#30](https://github.com/therealMRBK/NextFloor/pull/30)): an item linked to an entity (a meter with its power, a lamp, a washing machine, a light switch, a bin) keeps its usual marker, glow and energy flow when *Tapping the item* is set; only a tap on the item or its marker runs the action, a long press still opens the details. Example: the meter shows the grid power and a tap opens the energy dashboard. Items without a marker of their own still get the tap marker. + +### Fixed + +- **Plugin devices show their own icon in the editor** by @Mika2108 ([#28](https://github.com/therealMRBK/NextFloor/pull/28)): the plan, the device's form and the room's device list use the icon picked in the plan, else the plugin's Material Design icon, else the kind's symbol, as the 3D view does. Cameras no longer show as clocks. +- **A garage remote keeps its buttons in the room panel** by @Mika2108 ([#29](https://github.com/therealMRBK/NextFloor/pull/29)): a cover that only sends commands and never reports its position is no longer greyed out there, as in the quick menu since 0.14.0. *Open all* / *Close all* now leave out covers set to ask first, so a garage door no longer moves along without the confirmation, and they are hidden when no cover is left. + +## [0.15.0] + +### Added + +- **Wall-mounted air conditioner** (#23): the *Utility & building services* pack has a split air conditioner, an indoor unit for the wall and an outdoor unit. The indoor unit links to a climate entity like the wall thermostat. +- **Switch devices only in the opened room** by @Mika2108 (#26): card option *Switch devices only in the opened room* (`tap_in_room: true`). In the house and floor views a tap opens the floor or room, even on a device or its marker, so a tap meant for a room no longer switches a lamp by accident. In the opened room nothing changes; a long press still opens the menu or details everywhere. +- **Choose the markers outside the opened room** by @Mika2108 (#26): card option `markers_outside` with one chip per kind (lights, blinds, heating, media, switches, fans, locks, contacts and detectors, sensors, furniture with an action, other). In the opened room the usual marker setting applies. +- **Own tap action for furniture** by @Mika2108 (#26): *Tapping the item* in the furniture form runs one of the own-button actions (open a path, an entity's details, a service, a browser_mod popup) instead of the usual tap, with a marker above the item. + +- **Cameras and alarm panels as a plugin** (#27): the new *Cameras* plugin in the plugin store (*Extensions → Plugins → Open plugin store*) puts security cameras back into the plan. A camera shows its field of view as a wedge on the floor that stops at walls and turns red while a motion, person, vehicle or animal sensor of the same device detects something. A tap on the camera or its wedge opens Home Assistant's own live player in a small window in the corner (or HA's dialog). Mount, field of view, reach, tilt and detections are set in the camera's form, and a handle in the plan turns it. Alarm panels get a shield with their state, and a tap opens the keypad. +- **More for plugins**: a device extension can now add fields to the device's form (`settings`), draw a wedge on the floor (`floorWedge`), handle taps and open a small window in the corner of the 3D view (`tap`, `showWindow`), and name further entities to watch (`watch`). Devices a plugin takes on are drawn in the editor's plan too. See [docs/plugins.md](https://github.com/therealMRBK/NextFloor/blob/main/docs/plugins.md). + +### Changed + +- **Hide any entity of a room** (#24): in a room's device list, the further entities of a device (behind *more*) can now be hidden from the room and have their state hidden too, like the device's main entity. + +### Fixed + +- **Editing doors and windows froze the plan** (#25): when the form of a selected item could not be drawn, the whole editor stopped updating. A new door only showed up after a second click, the door form did not open and a dragged door stayed put. The plan now keeps working, and the side bar shows what went wrong (with a way back) so it can be reported. +- An entity whose name is a number (set in YAML) no longer breaks the entity lists in the editor. + +## [0.14.0] + +### Added + +- **Less rain and snow on a card** by @Mika2108 (#18): the card option *Amount of rain and snow* (`weather_density`, 15 to 100 %) thins out rain, hail and snow, so a wall tablet still shows the house in heavy weather. Clouds, fog and lightning stay as the weather says. +- **New furniture library**: the built-in models and all packs stand together, sorted by what they are (seating, beds, kitchen, bathroom, TV & audio, pets …) instead of pack by pack. Every card shows a picture, the size and where it comes from; a model in several sizes (a base unit from 30 to 120 cm, a bed from 90 to 200) is one card with size chips. With a room selected the library shows what fits it (*Fits Kitchen*, its main kind open and on top), *Show all rooms* lifts that. Chips narrow it to ⚡ linkable, 💡 lit or 🌳 outdoor items, ★ favourites and recently used items stand at the top. Pictures are drawn once and kept in the browser; weak tablets show the cards without pictures. +- **Resizing keeps what should stay**: a pack item made wider, deeper or taller keeps its legs, arms, plates and handles at their real size and distance from the edge, and only the middle grows: a sofa stretched to 3.6 m keeps its 20 cm arms, a taller table gets longer legs under the same plate. Pack authors can switch it off per item with `"stretch": true`. +- **Smart locks on doors**: a door takes a smart lock (door form → *Smart lock*). A tap on the door in 3D locks or unlocks it, always asking first; while it stands unlocked, the door's free edge glows in the accent colour. +- **Light switches and sockets**: the *Smart home & tech* pack has light switches and sockets with 1 to 4 buttons in one frame, and an outdoor socket with a lid. Each button gets its own entity; it glows while that is on, a light switch in its light's colour, a socket green and brighter the more it draws. A tap switches it; with several buttons a small menu asks which. The same entity may sit on several switches. +- **Curtains, screens, awnings and gates that move**: furniture with moving parts follows a cover entity (*Moves with* in its form): awnings in three widths reach out over the terrace, a curtain gathers to both sides, an inside roller blind and the roll-down projection screen roll up, a sliding gate slides away, the motorised curtain gathers to its side. They travel at motor speed, and a tap opens the cover's menu (up, stop, down). Pack authors mark parts with `move` (`down`, `left`, `right`, `out`, `slide_left`, `slide_right`) and the item with `cover`. +- **Look *Auto***: the day look while the sun is up, neon after sunset (from `sun.sun`), in the panel and as card option `theme: auto`. +- **Clock in the view**: a large clock with the date in a corner of the 3D view (panel: 🕒 next to the markers; card option `clock: top_left | top_right | bottom_left | bottom_right`). +- **3D lock** for wall tablets: the 🔒 button next to the eye stops turning, zooming and panning by hand on this device; taps, long presses and swipes on devices still work. Cards can hide the button (`lock_button: false`). +- **Own background**: *Editor → Settings → Own background* puts the house in front of a colour or a picture of your own (`/local/…` or https), dimmed as much as you like, instead of the look's sky. +- **Light wells**: an outer window whose sill lies below the ground (a cellar window) gets a concrete light well with a grating at ground level by itself; *Light well in front* in the window's form switches it off. +- **Different end at each end of a roof**: gable, hip and half-hip sections can take their own shape at the start and at the end of the ridge (a hip at one end, an upright gable at the other). +- **Sill and board per window**: automatic, none, inside only or outside only. +- **Import from Sweet Home 3D**: *Backup → Import* also takes a `.sh3d` file (Sweet Home 3D 5.3 and newer): levels become floors, rooms become rooms (moved onto the walls' centre lines, so neighbours share one wall), doors and windows go into the walls they stand in, and walls without a room become free walls. Its furniture stays behind; before taking it over NextFloor says what it found. +- **Household**: waste bins (residual, organic, paper, recycling; 120 and 240 l) and mailboxes in the garden pack. A bin shows its next pickup from a sensor (days, a date, "today"/"tomorrow" or Waste Collection Schedule) and glows the day before and on the day; a mailbox glows while there is post; a plant (the built-in one and the pack plants) shows its soil moisture and glows when it is thirsty. Their pins come up while something is due. Washers, dryers and dishwashers show the time they have left when their device has a remaining-time sensor. +- **Pets that roam**: a cat, a dog and a rabbit in the pets pack walk around their room in 3D, round the furniture, and sit for a while between their walks. While they all sit nothing is drawn, and on the *Tablet* level they rest with the other decorations. +- **Day curve on the house card**: the energy card over the roof shows the last 24 hours, solar as a filled curve and consumption as a line, worked out from the history of exactly the sensors the card reads (refreshed every 10 minutes). +- **Feet and inches**: *Editor → Settings → Show lengths in* shows the lengths and areas of the plan, the forms and the wall view in feet and inches (to the half inch) and square feet; inputs stay in metres. +- **Valleys for L- and T-shaped houses**: a wing roof that butts against the eave of a bigger roof at a right angle now runs into that roof's slope like a cross gable, so the two roofs meet in valleys instead of the wing ending in a gable wall at the eave. +- **Sloped walls**: a third wall view next to *Tall walls* and *Cut*: the walls are cut on a slope, half height on the side facing the camera and full height at the back, like a doll's house; the slope turns with the camera. +- **Solid walls with colours**: the new switch *Solid* shows opaque walls in real colours instead of glass. *Editor → Settings* sets the wall colour outside and inside, and each room can have its own inside colour. In an open room the walls in front of the camera are lowered. Works in the dashboard card too (`solid_walls: true`, `walls: slope`). +- **Seven more languages**: NextFloor now speaks French (thanks to Mika2108), Spanish, Italian, Dutch, Polish, Portuguese and Swedish besides German and English, following the language of your Home Assistant user, furniture names included. Each language loads only when it is needed. +- **Plan format and AI import**: [docs/plan-format.md](https://github.com/therealMRBK/NextFloor/blob/main/docs/plan-format.md) describes the plan file, with a ready prompt that lets an AI turn a picture of your floor plan into a plan for *Backup → Import*. + +### Fixed + +- **A garage door follows its contact when the cover cannot tell** by @Mika2108 (#21): a remote without feedback (`assumed_state`, always `unknown`) no longer shows the door open while its contact says closed. +- **Quick menu for covers without feedback** by @Mika2108 (#21): such a cover keeps its open, close and stop buttons; the centre button stays off while the state is unknown. +- **Entities that a plugin gives a kind** by @Mika2108 (#21) are offered in the editor's area lists, *without area* and *other areas*. +- **Walking keys by their place on the keyboard** by @Mika2108 (#21): W A S D walk under the same fingers on QWERTY, QWERTZ and AZERTY (Z Q S D). +- **Doors and windows of an imported plan can be selected again**: a plan written by hand or by an AI without ids (or with repeated ones) gets an id for every room, door, window, piece of furniture and outdoor area, so they can be picked and changed (e.g. into a garage door). Missing sizes, the plan version and the settings are filled in instead of refusing the file. + +## [0.13.0] + +### Added + +- **Import furniture packs again**: *Extensions → Furniture packs* imports your own packs as files or as JSON pasted straight into a text field, lists the packs you imported and removes them. The format is in [docs/packs.md](https://github.com/therealMRBK/NextFloor/blob/main/docs/packs.md). +- **Climate devices in furniture packs** by @carmona15 (#14): a pack item marked `climate: true` (a wall-mounted A/C, a heat pump) links to a Home Assistant climate entity, found automatically in the room's area like a radiator's thermostat, and can have a power sensor. How to mark an item: [docs/packs.md](https://github.com/therealMRBK/NextFloor/blob/main/docs/packs.md). + +### Fixed + +- **Wall thermostat** (#17) now links to a climate entity instead of asking for a TV. Climate items from packs are also offered under *Show as furniture* for a climate entity, next to the radiator. + +## [0.12.0] + +### Added + +- **Plugin store**: *Extensions → Plugins → Open plugin store* lists reviewed community plugins from [NextFloor-Plugins](https://github.com/therealMRBK/NextFloor-Plugins) and installs them with one click. Authors submit a plugin with a pull request, which is reviewed by hand. Every entry points at a file pinned to one commit and carries its SHA-256; NextFloor checks the hash before the plugin runs and offers newer versions as an update. + +### Fixed + +- **Solar fields on a mansard roof** (#13) now lie on the roof instead of sinking into it. Each side offers two roof faces to choose from: the steep lower slope and the flatter upper slope above the break. Fields placed on a mansard before keep their spot on the lower slope; move a field that should sit higher onto the upper face. + +## [0.11.0] + +### Added + +- **Ceiling height per room** (#12): a room can have its own ceiling height (room form → *Ceiling height*), e.g. a 2.12 m bathroom on a 4 m floor. Ceiling lights, ceiling fans, LED strips under the ceiling, ceiling devices and placed ceiling lights hang from it, and the room's walls are that high (a wall shared with a room without its own ceiling keeps the floor height; between two rooms with their own ceilings it takes the higher one). Heights set by hand on a wall still win. +- **Ceiling height at one spot** (#12): ceiling lights and other hanging items have a *Ceiling here* field for a sloping ceiling or a single high spot (a light at 4 m). +- **Ceiling fans** (#11): a new *Ceiling fan* in the lights section. Link its light kit like any lamp and its fan entity (found on the light's device or in the room). In 3D the blades turn as fast as the fan runs; the fan's pin shows its speed, a tap switches it, swiping up or down changes the speed and a long press opens the quick menu. Its height is how far it hangs from the ceiling, so a fan on a downrod hangs lower. + +## [0.10.0] + +### Added + +- **Plugins:** NextFloor can now be extended without changing its code. A plugin is a JavaScript file you add on the **Extensions** page (from `/config/www`, HACS or HTTPS). Plugins can add their own light animations (they show up in a light's effect settings), show entities NextFloor does not know (a robot vacuum, a lawn mower) with their own icon and text, and add small cards to a room's panel. A broken plugin never breaks the house view; its errors show next to it on the Extensions page. How to write one: [docs/plugins.md](https://github.com/therealMRBK/NextFloor/blob/main/docs/plugins.md). +- **Sub-meters (advanced energy mode)** by @TheRealSimon42 (#8): a meter can hang off another meter, e.g. one sub-meter per flat behind the house's main meter; solar plants and batteries can hang off a sub-meter, and the house card shows the common rest. Off by default. +- **Configurable light effects** by @TazztheMonster (#9): map a light's effect names to rainbow, pulse, flicker or a static look, or turn animations off for one lamp without changing anything in Home Assistant. + +### Changed + +- The README credits NeonPlan 3D by Mastershort, the project NextFloor started from. + +### Fixed + +- Light effects are no longer all shown as a rainbow: plans without a mapping and unknown effects keep the colour and brightness from Home Assistant, pulse and flicker keep the base colour, and lights that are off or unavailable do not animate. + +## [0.9.1] + +### Changed + +- **A pool cuts itself out of the areas around it:** a pool drawn inside a terrace (or a lawn) now leaves a hole there on its own, so the terrace runs around the pool and not over it. Any other area can still do the same with **Cut out of surrounding areas**. The order the areas were drawn in no longer matters: before, only areas drawn *before* the cutting one got the hole. The hole carries no light of the area around it either. Asked for in discussion #6. + +### Fixed + +- **A folded room panel no longer hangs in the picture:** on a wide window or in landscape the folded panel stayed at the top right and covered the view. It now drops to the bottom edge, above the switches (and to the bottom of the card), so it is out of the way. Reported in discussion #3. + +## [0.9.0] + +### Added + +- **Sloping walls:** every wall in the room's wall list has a new button **Sloping**. It gives the wall a height at its start and another at its end, and the top runs straight between them: a lean-to room, a wall that follows a sloping ceiling, clerestory windows high on the tall side. Both heights may be above the floor height. Windows and doors on such a wall stay under its top, so a window near the high end can be taller than one near the low end. A corner added to a sloping wall splits the slope at the height it has there. Asked for in discussion #4. +- **Outdoor areas can have any shape:** the selected lawn, terrace, pool, fence and so on now shows a **+** in the middle of every edge, like a room. Drag it to add a corner; the corner buttons in the form (**1 ×**, **2 ×** …) take a corner away again. Asked for in discussion #6. +- **Flat roofs can be reshaped the same way:** the **+** on the edges of a flat or parapet roof turns the rectangle into a free shape, and its corners can be added, dragged and removed. (Pitched roofs stay rectangles over their ridge; L- and T-shaped houses are still built from several sections.) Asked for in discussion #6. +- **Turn a solar field on a flat roof:** the solar form has **Rotation** with quick **↺ 90°** and **↻ 90°** buttons. The field turns about its middle, its modules and frames turn with it, and it is kept on the roof. Asked for in discussion #5. +- **Fold the room panel away:** the room panel has a new **−** button next to the ✕. It hides the devices and keeps the room in view, which is what you want on a phone; a tap on the arrow opens it again. The panel starts open for every room. Asked for in discussion #3. + +## [0.8.3] + +### Fixed + +- **Real map showed "Access blocked" (403) instead of the map:** Home Assistant asks the browser to send no Referer to other sites, and OpenStreetMap's tile servers refuse requests without one. NextFloor now loads every map tile with an explicit referrer policy (only your Home Assistant's address, not the full page address), in the plan and in 3D. The tiles are kept in the browser while the map is on. + +## [0.8.2] + +### Added + +- **Room buttons on the dashboard card:** a new switch *Room buttons* in the card editor puts a row of buttons, one per room, along the top of the card. A tap opens the room (switching to its floor first when needed), a second tap closes it. In the house view the rooms of all floors show, grouped by floor. Asked for in discussion #2. + +## [0.8.1] + +### Fixed + +- **Blue light frame around a TV that is on, even with *Glow behind the TV* at 0:** the glow frame that fades out around the screen of a TV that is on ignored the setting. With 0 it is now gone completely, and values below 100 make it weaker. (0.8.0 only removed the bright outline of the TV's body.) + +## [0.8.0] + +### Added + +- **Twelve new furniture packs with 417 models, all built from scratch:** Living room (70), Kitchen (66), Bedroom (41), Bathroom (38), Garden & patio (33), Home cinema & hi-fi (36), Smart home & tech (30), Office & gaming (26), Pets (24), Kids' room (18), Utility & building services (18) and Fitness (17). +- **Existing packs grew:** Vehicles now has cars of every class, vans, a pickup, a campervan, a motorhome and a caravan (34); Stairs & railings has floating and winder stairs and a corner railing (13); Architecture & fit-out has steel columns, ceiling beams, niches, a light cove, a window seat and more (21); Garage & workshop has a tool wall, shelving, a mower, wallbox holder and more (22). +- Every model is visible in the demo's showcase. +- **Compass control:** under Settings a dial shows where north lies, with **Swap north ↔ south** (180°) and quarter turns. Turning the compass never moves the drawing, the roof faces or the solar fields; sunlight, wind and the compass directions of roof faces follow it. So a plan drawn the wrong way round is fixed in one tap, without placing the solar fields again. +- **Real map under the plan (off by default):** a dimmed OpenStreetMap (or your own tile address) lies under the plan in the editor and under the house in 3D, turned by the compass. Start at Home Assistant's location, set the visibility and detail level, and move the map with arrow buttons until the house sits on its plot. Nothing is loaded while it is off. + +### Fixed + +- **TV without glow still had a blue frame:** with *Glow behind the TV* set to 0 the TV's own bright blue outline stayed. It now takes the plain furniture outline, so a TV set to no glow is not lit at all. + +### Changed + +- **Guide rewritten:** `docs/manual.md` and `docs/anleitung.md` are new, organised by what you do (install, draw, furnish, connect, use) instead of by feature list, and match the current features. +- **Demo of the development version:** the online demo now has a second page under `/dev/` that always shows the latest state of the `dev` branch (marked "DEV"); the normal demo keeps showing the released version. +- **Cameras are gone:** the camera wall, flying into a camera's live picture, the motion trail, detection pins, the field-of-view wedge and the camera device kind were removed. Placed `camera.*` entities are no longer shown. +- **Extensions tab:** it now only holds the upload of your own 3D models and the project links. The feature list and the furniture pack list are gone, and so is the hint box in the furniture library. + +## [0.7.0] + +### Added + +- **Three new free furniture packs**, all built from scratch in NextFloor's own part format: + - **Treppen & Geländer (10):** straight, L-shaped, U-shaped, spiral and space-saving staircases, landing, outdoor steps and railings in metal, glass and wood. The staircases cut their opening into the floor above. + - **Architektur & Ausbau (10):** round and square columns, ceiling beam, chimney breast, glass partition, sliding wall, raised platform, half wall, shelving divider and pilaster. + - **Garage & Werkstatt (9):** workbench, tool cabinet and trolley, storage rack, stack of tyres, drill press, compressor, bicycle stand and paint cabinet. +- All three appear in the demo's model showcase. + +## [0.6.3] + +### Added + +- **Model showcase in the online demo:** every model of NextFloor, the basic ones and those of all packs, can be looked at live in a room of their own, ten at a time, with the names listed in the order they stand. Open the demo and choose "All models" (bottom right), or use `?showcase`. + +### Changed + +- **Languages:** NextFloor now comes in German and English only; Home Assistant instances in any other language show English. The 14 further language files were removed. + +### Fixed + +- The online demo no longer fails to deploy on a release (it deploys when the demo changes on `main`). +- A formatting slip in the Python code that made the checks fail. + +## [0.6.2] + +### Added + +- **Glow behind the TV:** a TV, monitor or TV board has a new setting "Glow behind the TV (%)" in the editor. 0 switches the blue ambilight off (handy with LED strips on the TV), 100 is the usual strength, up to 150. + +## [0.6.1] + +### Fixed + +- **Camera wall:** the pictures are now tiles of a sensible size (at most 560 px wide, as many per row as fit, centred) instead of one picture stretched over the whole screen when there is a single camera. Tiles lift slightly when you point at them. + +## [0.6.0] + +### Added + +- **Upload 3D models in the app:** on the Extensions page every item that takes a model has an "Add a model" button. Choose the `.glb`, turn the front towards you, tick the body paint (guessed for you), pick the level of detail, check the preview and store it on your Home Assistant. NextFloor does the work of `tools/prepare-model.mjs` itself: it merges the parts, makes the model lighter, writes plain glTF without textures and marks the paint. Files that are compressed (Draco, Meshopt) are refused with a hint. You can replace and remove models there too. + +### Changed + +- The editor, the side panel, the dashboard card and parts of the 3D view were reorganised internally into smaller, tested modules. Behaviour and look are unchanged. +- The README is shorter, with a feature table and a screenshot gallery. + +## [0.5.0] + +- **Twelve Tesla models:** Model 3 (to 2023, 2024 and Performance), Model S and S Plaid, Model X, Model Y (2020 to 2024, 2025 Standard, Premium and Performance, and Model Y L) and the Cybertruck are separate items, each ready for its own 3D model, in the paint colours Tesla offers. Without a model file on your Home Assistant they show the simple shape. +- `tools/prepare-model.mjs` can leave out see-through fade layers and light beams (`--drop-materials`) and finds the front of the car by its charge port (`--rear`). + +## [0.4.0] + +- **Paint colours for vehicles:** every Tesla has the paint colours Tesla offers (Pearl White, Solid Black, Deep Blue, Ultra Red, Quicksilver and more; the Cybertruck its steel and wraps). Pick the colour in the editor, also for a car in a parking spot. +- **Your own 3D models:** put a model you own (`.glb`) on your Home Assistant and NextFloor draws it in place of the simple shape, with the paint colour you picked. The Tesla Model Y is the first item that takes one. NextFloor ships no model files; see [docs/models.md](docs/models.md) for how to prepare and add yours. + +## [0.3.0] + +- **IKEA sizes:** a new furniture pack with 20 popular pieces in their published outer dimensions: bookcases, cube shelves, beds, chests of drawers, wardrobes, sofas, an armchair, a desk, tables and more. They are our own simple models of the sizes, not IKEA's designs or files. + +## [0.2.0] + +- **Tesla models in 3D:** Model S, 3, X, Y, Cybertruck, Roadster and Semi in the vehicles pack, with their real outer dimensions. Put one on a parking spot and the car card follows it. +- **Smooth bodies for packs:** a new part shape, `sweep`, stretches a rounded skin over cross sections along the length. The Teslas are built with it; the format is described in [docs/packs.md](docs/packs.md). + +## [0.1.0] + +The first release. + +- Draw your home right inside Home Assistant: floors, rooms, walls, doors, windows, stairs, outdoor areas and a roof, with a 3D view next to the plan. +- Control it in 3D: lamps glow in their colours, blinds and doors follow their state, a room panel lists everything of the area. +- Ten built-in furniture packs (about 100 items) plus your own packs as plain JSON ([docs/packs.md](docs/packs.md)). +- Six live features: weather at the house, energy flow, TV screens, sound, car and cameras (camera wall, detection pins, motion trail). +- A dashboard card with a visual editor, three looks, kiosk mode for wall tablets, warnings for smoke, gas, water and open windows in the rain. +- English and German in the box, fourteen more languages fetched on demand. +- Free and open source, no account, no cloud: NextFloor does not talk to the internet. + +[Unreleased]: https://github.com/therealMRBK/NextFloor/compare/v0.26.6...main +[0.26.6]: https://github.com/therealMRBK/NextFloor/compare/v0.26.5...v0.26.6 +[0.26.5]: https://github.com/therealMRBK/NextFloor/compare/v0.26.4...v0.26.5 +[0.25.4]: https://github.com/therealMRBK/NextFloor/compare/v0.25.3...v0.25.4 +[0.25.3]: https://github.com/therealMRBK/NextFloor/compare/v0.25.2...v0.25.3 +[0.25.2]: https://github.com/therealMRBK/NextFloor/compare/v0.25.1...v0.25.2 +[0.25.1]: https://github.com/therealMRBK/NextFloor/compare/v0.25.0...v0.25.1 +[0.25.0]: https://github.com/therealMRBK/NextFloor/compare/v0.24.0...v0.25.0 +[0.24.0]: https://github.com/therealMRBK/NextFloor/compare/v0.23.1...v0.24.0 +[0.23.1]: https://github.com/therealMRBK/NextFloor/compare/v0.23.0...v0.23.1 +[0.23.0]: https://github.com/therealMRBK/NextFloor/compare/v0.22.0...v0.23.0 +[0.22.0]: https://github.com/therealMRBK/NextFloor/compare/v0.21.0...v0.22.0 +[0.21.0]: https://github.com/therealMRBK/NextFloor/compare/v0.20.0...v0.21.0 +[0.20.0]: https://github.com/therealMRBK/NextFloor/compare/v0.17.0...v0.20.0 +[0.17.0]: https://github.com/therealMRBK/NextFloor/compare/v0.16.1...v0.17.0 +[0.16.1]: https://github.com/therealMRBK/NextFloor/compare/v0.16.0...v0.16.1 +[0.16.0]: https://github.com/therealMRBK/NextFloor/compare/v0.15.0...v0.16.0 +[0.15.0]: https://github.com/therealMRBK/NextFloor/compare/v0.14.0...v0.15.0 +[0.14.0]: https://github.com/therealMRBK/NextFloor/compare/v0.13.0...v0.14.0 +[0.13.0]: https://github.com/therealMRBK/NextFloor/compare/v0.12.0...v0.13.0 +[0.12.0]: https://github.com/therealMRBK/NextFloor/compare/v0.11.0...v0.12.0 +[0.11.0]: https://github.com/therealMRBK/NextFloor/compare/v0.10.0...v0.11.0 +[0.10.0]: https://github.com/therealMRBK/NextFloor/compare/v0.9.1...v0.10.0 +[0.9.1]: https://github.com/therealMRBK/NextFloor/compare/v0.9.0...v0.9.1 +[0.9.0]: https://github.com/therealMRBK/NextFloor/compare/v0.8.3...v0.9.0 +[0.8.3]: https://github.com/therealMRBK/NextFloor/compare/v0.8.2...v0.8.3 +[0.8.2]: https://github.com/therealMRBK/NextFloor/compare/v0.8.1...v0.8.2 +[0.8.1]: https://github.com/therealMRBK/NextFloor/compare/v0.8.0...v0.8.1 +[0.8.0]: https://github.com/therealMRBK/NextFloor/compare/v0.7.0...v0.8.0 +[0.7.0]: https://github.com/therealMRBK/NextFloor/compare/v0.6.3...v0.7.0 +[0.6.3]: https://github.com/therealMRBK/NextFloor/compare/v0.6.2...v0.6.3 +[0.6.2]: https://github.com/therealMRBK/NextFloor/compare/v0.6.1...v0.6.2 +[0.6.1]: https://github.com/therealMRBK/NextFloor/compare/v0.6.0...v0.6.1 +[0.6.0]: https://github.com/therealMRBK/NextFloor/compare/v0.5.0...v0.6.0 +[0.5.0]: https://github.com/therealMRBK/NextFloor/compare/v0.4.0...v0.5.0 +[0.4.0]: https://github.com/therealMRBK/NextFloor/compare/v0.3.0...v0.4.0 +[0.3.0]: https://github.com/therealMRBK/NextFloor/compare/v0.2.0...v0.3.0 +[0.2.0]: https://github.com/therealMRBK/NextFloor/compare/v0.1.0...v0.2.0 +[0.1.0]: https://github.com/therealMRBK/NextFloor/releases/tag/v0.1.0 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..f983540 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,18 @@ +# NextFloor – notes for Claude + +- Spec and phase plan: `docs/plan.md` (German). Talk to the user in German; code, identifiers and comments in English. +- Domain `nextfloor`, repo `therealMRBK/NextFloor`, minimum Home Assistant 2025.1. +- Frontend lives in `frontend/` (Lit 3 + TypeScript, no decorators; three.js in a separate lazily loaded bundle). + Bundles are committed to `custom_components/nextfloor/frontend/`, and CI fails when they are stale, so run `npm run build` before committing. +- Checks: `npm test`, `npm run typecheck`, `npm run build` (size budgets), `ruff check` / `ruff format`. + HA integration tests only run in the Linux CI. +- Visual self-check: `npm run screenshot` renders `preview/index.html` (invented demo data, mock hass) into `preview/screenshots/`. +- Deploy to the user's HA: `npm run deploy` (target in the untracked `deploy.local.json`). Never commit real floor plans, IPs or device names. +- **Branches:** work happens on `dev` (CI runs there too). `main` is what HACS users receive, so it only moves about once a day or after a bigger batch of features: merge `dev` into `main` (fast-forward), bump `manifest.json`, write the changelog section and cut the GitHub release then, not per commit. Never push single small changes straight to `main`. +- After each phase: commit and push to `dev`, check CI, and tell the user in German what is new and how to test it. Only a release (merge to `main`) is published. + +- **Changelog:** every change that reaches users goes into `CHANGELOG.md` in the same commit, under the version it ships in, sorted into **Added**, **Changed** and **Fixed** (bump `manifest.json` when a release is cut). Say what the user notices, not what the code did. Use the same text for the GitHub release notes. +- **README is shown inside HACS too, which does not resolve relative paths:** keep every image and link in `README.md` absolute (`raw.githubusercontent.com/therealMRBK/NextFloor/main/…` for images, `github.com/therealMRBK/NextFloor/blob/main/…` for files). + +- **Token economy:** when a symbol or string is known, use a targeted `grep -rn` (graphify only for "where does X live" questions); `graphify update .` after code changes. No broad exploration when the scope is clear: read only the lines you need. While developing, run only the affected test file (`npx tsx --test src/.test.ts`); the full gate (typecheck, tests, build, ruff, HA tests) runs once before each commit, with its output filtered to pass/fail lines. Do not spawn subagents for work that fits in a few commands. Do not take screenshots unless the change is visual and the check can answer a concrete question. +- **Quality rules (as in good open-source projects):** commits as Conventional Commits (`feat:`, `fix:`, `docs:`, `build:`, `test:`); larger features on a branch with a pull request, small fixes straight to `dev`; version numbers as in `CONTRIBUTING.md` → *Version numbers* (decided with the user 2026-11-08): `0.MINOR.PATCH.HOTFIX` — a fourth part only for a fix of a reported bug on top of the current release (hotfix branch from the tag, PR into `main`, then merge `main` back into `dev`), patch for the usual collected release, minor for a topic release or anything users must act on; the gate also runs `mypy custom_components/nextfloor`; `main` is protected (CI must be green, no force-push); a release is cut only with the user's go and needs tag = manifest version (the release workflow checks it and attaches `nextfloor.zip`); security reports go through the private advisory, never a public issue. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..5675190 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,7 @@ +# Code of conduct + +This project follows the [Contributor Covenant 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). + +In short: be kind and patient, assume good faith, keep criticism about the work and not the person, and no harassment of any kind. Issues, pull requests and discussions that break this can be edited, locked or removed. + +To report a problem, contact the maintainer through a private message on GitHub (@therealMRBK). Reports are handled confidentially. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..31d8fb9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,53 @@ +# Contributing + +Thanks for looking. NextFloor is free and open source out of conviction, and every contribution keeps it that way: whatever you add belongs to everyone, under the MIT licence. It is a small project and is built with AI assistance (see the README), so contributions are welcome the same way: written by you, with a tool, or both. Please just say in the pull request if an AI wrote a good part of it, and make sure you have understood and run what you send. + +## Before a pull request + +```bash +cd frontend +npm install +npm run typecheck +npm test +npm run build # the built bundles are committed; CI fails when they are stale +cd .. +ruff check . && ruff format --check . +pytest -q # the Home Assistant side +``` + +- Keep a change small and say what it is for. A screenshot helps for anything you can see (`npm run screenshot` renders the preview). +- New furniture or vehicles: the built-in packs come from `tools/build_packs.py`; the format of your own packs is in [docs/packs.md](docs/packs.md). Please only use sizes and shapes you made yourself, never another project's files or a brand's own 3D models. +- 3D models you own (for example a car): they stay on your own Home Assistant and never go into this repository, see [docs/models.md](docs/models.md). + +## How changes flow + +- Work happens on `dev`; `main` is what HACS users receive and only moves with a release. Larger features are developed on a branch and merged through a pull request, so CI runs before the merge. +- Commit messages: a short summary in the style `feat: …`, `fix: …`, `docs: …`, `build: …`, `test: …` (Conventional Commits), with the issue number when there is one. +- Every user-visible change goes into `CHANGELOG.md` under **Unreleased** in the same commit. +- A release: `manifest.json` version, the changelog section, a tag `v` on `main` and a GitHub release with the changelog text. The release workflow then attaches `nextfloor.zip`, which HACS installs. + +## Version numbers + +Versions read `0.MINOR.PATCH` or `0.MINOR.PATCH.HOTFIX`. The number tells what an update brings: + +| Part | Example | When | +| --- | --- | --- | +| **Hotfix** | 0.26.5 → 0.26.5.1 | A bug reported in an issue that breaks something in the current release. The hotfix holds that fix only, nothing else from `dev`. | +| **Patch** | 0.26.5.x → 0.26.6 | The usual release: fixes and small additions collected on `dev`, nothing anyone has to change. The hotfix part is dropped again. | +| **Minor** | 0.26.x → 0.27.0 | A planned release around one big topic, or anything users have to act on: a storage migration, a removed or renamed option, changed card YAML. Rule of thumb: if someone has to do or relearn something after the update, it is a minor. | +| **Major** | 1.0.0 | Once, when storage format, card YAML and plugin API are stable and documented, and no known bug loses data or crashes. | + +- A wish or an improvement is never a hotfix, even when it comes as an issue: it ships with the next patch. +- **A hotfix:** branch `hotfix/` from the release tag, the fix and its changelog section `## []`, a pull request into `main`, then the release. Afterwards `main` is merged into `dev`, so the next release is a fast-forward again. The fix lands on `dev` as well and is part of the next patch. +- Before a minor, a pre-release `0.27.0-beta.1` can go out on GitHub for those who switched on betas. +- Counted on their own, not with the app version: the plugin API (`apiVersion`) only climbs when plugins would break, and a change of the stored plan format always means a minor. +- Home Assistant and HACS accept and sort the four-part numbers (0.26.5 < 0.26.5.1 < 0.26.5.10 < 0.26.6). +- Security problems go through [private reporting](SECURITY.md), not a public issue. + +## Translations + +German and English are built in. Further languages are files in `frontend/lang/.json` (keys as in `frontend/src/i18n.ts`), fetched only when Home Assistant runs in that language; a key a file lacks shows in English. They are community-maintained: new texts land in German and English first. Pack items and paint colours are named under `pack::`, `packname:` and `color:`. The integration's own texts are in `custom_components/nextfloor/translations/`. + +## Ideas and bugs + +[Discussions](https://github.com/therealMRBK/NextFloor/discussions) for ideas and questions, [issues](https://github.com/therealMRBK/NextFloor/issues/new/choose) for bugs. For a bug, the version, your Home Assistant version and what you expected help most. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..654293b --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2026 Mastershort +Copyright (c) 2026 therealMRBK + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..707ceb3 --- /dev/null +++ b/README.md @@ -0,0 +1,230 @@ +

NextFloor logo

+ +

NextFloor

+ +

Draw your home once. Watch it live in 3D.
+Lamps light their room, blinds move, doors open, the TV shows what plays, rain falls outside.
+A free 3D floor plan for Home Assistant. No cloud, no account. Made for wall tablets.

+ +

+Open in HACS +Documentation +Online demo +All models +

+ +

+Release +CI +In the official HACS store +Free forever +MIT +Built with AI +

+ +

NextFloor in a real house: the house turns, the ground floor opens, a room panel with its lights and blinds slides in

+ +

+📚 Documentation · +Quick start · +Card options · +Plugins · +FAQ · +Deutsch · +简体中文 · +🎬 Setup video · +Roadmap +

+ +--- + +## ✨ In one minute + +| | | | +|---|---|---| +| **✏️ Draw it** | **💡 Watch it live** | **🧩 Make it yours** | +| Floors, rooms, curved walls, doors, windows, stairs, roofs and gardens, with the 3D model growing beside the plan. Or import a room scan, a CAD drawing or a Sweet Home 3D plan. | Tap a lamp and the real light switches. Blinds travel, doors open, the TV shows the running app, solar power flows along your real cables, rain falls. | 43 free furniture packs with about 800 models, a furniture studio and a browser builder, a dashboard card with templates, and a reviewed plugin store. | + +

A house in the 3D view, floors apart, rooms lit

+ +## 🖼️ What it looks like + + + + + + + + + + + + + + + + + + +
The plan editor with the 3D view beside it
The editor. Draw while the house grows beside you.
A room in 3D with its lamps and the room panel
A room. Every device of the room in one panel.
The energy flow from the solar field through the house
Energy. Power flows along the cables you drew.
A heat map of the house by temperature
Climate. Temperature, humidity, CO₂, mould and sun by room.
Rain falling on the house
Weather. Rain, snow, fog, lightning, sun and moon.
Furniture from several packs in a room
Furniture. About 800 models, and your own.
NextFloor on a wall tablet
The wall tablet. Kiosk mode, night dimming, announcements.
The NextFloor card on a dashboard
The card. On any dashboard, with a visual editor.
+ +Looks: Blueprint · Day · Cut-away walls · Stacked floors · Vehicles · IKEA sizes + +## 🚀 Install in two minutes + +NextFloor is in the **official HACS store**. + +1. Open **HACS**, search for **NextFloor** and press **Download** (or use the HACS button above). +2. **Restart Home Assistant.** +3. Add the integration: [![Start setting up NextFloor.](https://my.home-assistant.io/badges/config_flow_start.svg)](https://my.home-assistant.io/redirect/config_flow_start/?domain=nextfloor), or *Settings → Devices & services → Add integration → NextFloor*. +4. Open **NextFloor** in the sidebar, switch to **Editor** and draw your first floor. The [quick start](https://therealmrbk.github.io/NextFloor/docs/en/quickstart/) takes you through the first room and lamp. + +**Manual install:** copy `custom_components/nextfloor` into `config/custom_components/` and restart. Needs Home Assistant 2025.1 or newer. **Installed earlier as a custom repository?** Nothing to change: your plan and settings stay, and updates keep coming through HACS. More in the [installation guide](https://therealmrbk.github.io/NextFloor/docs/en/install/). + +## 🧭 What it does + +
+Draw and plan + +- **Plan editor:** floors, rooms, curved and sloping walls, doors, windows, shaped stairs, outdoor areas with fences and gates, roofs with overhang per side. Rooms open to the floor above, turned roof sections, wall thickness per part. +- **Import:** iPhone room scans (Apple RoomPlan), Sweet Home 3D, DXF and IFC, or a plan an AI draws from a picture of your floor plan. +- **Plan check:** one list of what is missing or off, with a fix in one tap, including standby eaters and their yearly cost. +- **Areas and paper:** living area per room, floor and house, counted like the German *Wohnflächenverordnung*; the plan at 1:100 to print or save as PDF. +- **Versions and notes:** named states of the plan ("before the renovation"), compared with the plan now; notes pinned to a spot, with a due day. +- **3D print:** save the house as an STL file at 1:100. + +→ [Draw the house](https://therealmrbk.github.io/NextFloor/docs/en/draw/) · [Plan tools](https://therealmrbk.github.io/NextFloor/docs/en/plan-tools/) +
+ +
+Furnish and connect + +- **Furniture:** 40 basic models and 43 packs with about 800 more: season and decoration, wellness, music, loft, Japandi, workshop, vehicles, picture frames with your own photos, L- and U-sofas, IKEA sizes. +- **Build your own:** the furniture studio in the editor, and the [browser builder](https://therealmrbk.github.io/NextFloor/builder/) that shares to a community store. +- **Devices:** lamps with several bulbs, light programs, blinds (roller, venetian, inside, Somfy *My*), smart locks, gates, TVs with ambilight, speakers, a 3D printer, a heat pump, the car, pets, robot vacuums and mowers. +- **People:** a room sensor or a default room per person, shown in their rooms and counted per floor. + +→ [Furnish](https://therealmrbk.github.io/NextFloor/docs/en/furnish/) · [Connect devices](https://therealmrbk.github.io/NextFloor/docs/en/devices/) · [Furniture packs](https://therealmrbk.github.io/NextFloor/docs/en/packs/) +
+ +
+Live in 3D + +- **Control:** tap to switch, swipe to dim, long press for colours, a room panel with scenes and moods, a central menu, search. +- **Weather and sun:** rain, snow, hail, fog, lightning, sun and moon, real shadows, a time-of-day slider, the sun's arc over the property. +- **Walk and time travel:** walk through the house at eye level, or replay the last day or week. +- **Warnings:** smoke, gas, water, the alarm with the sensor that set it off, windows open in the rain, and your own warnings. +- **Announcements:** *"Dinner is ready!"* in the room that should hear it, through its speaker and on every open screen. + +→ [The 3D view](https://therealmrbk.github.io/NextFloor/docs/en/view3d/) · [Live features](https://therealmrbk.github.io/NextFloor/docs/en/live/) · [Announcements](https://therealmrbk.github.io/NextFloor/docs/en/announcements/) +
+ +
+Climate, sun and energy + +- **Heat maps:** temperature (summer and winter scale), humidity, CO₂, mould risk and a comfort score, Wi-Fi reach, hours of sun and power draw per room. +- **Room hints:** airing, low batteries, lights left on in empty rooms, shade when the sun heats a room, a window open while the heating runs. +- **Energy:** solar fields (also east-west racks), power flow along real cable routes, battery charge, gas and water meters, a meter per floor, the last 24 hours and seven days. + +→ [Climate and energy](https://therealmrbk.github.io/NextFloor/docs/en/climate-energy/) · [Outside, roof and energy](https://therealmrbk.github.io/NextFloor/docs/en/outside/) +
+ +
+Dashboard, tablet and automations + +- **The card:** `custom:nextfloor-card` with a visual editor, card templates, a card for chosen rooms, floor-plan-only mode. +- **Wall tablet:** kiosk mode with night dimming, an easy-to-read mode, and quality that steps down by itself on slow tablets. +- **Automations:** *Open windows and doors* and *Lights on* as sensors for the house and every floor, plus the actions `nextfloor.announce` and `nextfloor.reload_screens`. +- **Look:** colours, font and corner radius from your Home Assistant theme; looks *Neon*, *Blueprint* and *Day*. Nineteen languages. + +→ [The dashboard card](https://therealmrbk.github.io/NextFloor/docs/en/cards/) · [Wall tablet](https://therealmrbk.github.io/NextFloor/docs/en/tablet/) · [Services and sensors](https://therealmrbk.github.io/NextFloor/docs/en/automations/) +
+ +## 🧩 The dashboard card + +```yaml +type: custom:nextfloor-card +floor: ground # optional: start floor +theme: neon # neon | blueprint | day +room_buttons: true # a row of room buttons +template: kitchen # optional: a card template set up once in the editor +``` + +The visual editor sets every option without YAML. The [complete list of card options](https://therealmrbk.github.io/NextFloor/docs/en/cards/) has them all, with their defaults. + +## 📚 Documentation + +The full documentation is at **[therealmrbk.github.io/NextFloor/docs](https://therealmrbk.github.io/NextFloor/docs/en/)**: search, a dark and a light look, and every page in English and German. + +| I want to … | Read | +|---|---| +| install and draw my first room | [Install](https://therealmrbk.github.io/NextFloor/docs/en/install/) · [Quick start](https://therealmrbk.github.io/NextFloor/docs/en/quickstart/) · [How it works](https://therealmrbk.github.io/NextFloor/docs/en/concepts/) | +| draw the house, furnish it, connect devices | [Draw](https://therealmrbk.github.io/NextFloor/docs/en/draw/) · [Furnish](https://therealmrbk.github.io/NextFloor/docs/en/furnish/) · [Connect devices](https://therealmrbk.github.io/NextFloor/docs/en/devices/) | +| use weather, energy, climate and announcements | [The 3D view](https://therealmrbk.github.io/NextFloor/docs/en/view3d/) · [Live features](https://therealmrbk.github.io/NextFloor/docs/en/live/) · [Climate and energy](https://therealmrbk.github.io/NextFloor/docs/en/climate-energy/) | +| put it on a dashboard or a wall tablet | [The dashboard card](https://therealmrbk.github.io/NextFloor/docs/en/cards/) · [Wall tablet](https://therealmrbk.github.io/NextFloor/docs/en/tablet/) | +| automate, extend, build my own | [Services and sensors](https://therealmrbk.github.io/NextFloor/docs/en/automations/) · [Plugins](https://therealmrbk.github.io/NextFloor/docs/en/plugins/) · [Furniture packs](https://therealmrbk.github.io/NextFloor/docs/en/packs/) · [Plan format](https://therealmrbk.github.io/NextFloor/docs/en/plan-format/) | +| fix something | [FAQ and troubleshooting](https://therealmrbk.github.io/NextFloor/docs/en/faq/) | + +The Markdown sources are in [`docs/content`](https://github.com/therealMRBK/NextFloor/tree/main/docs/content). A pull request that improves a page is welcome. + +## 💚 Free forever + +NextFloor is free, and it stays free: not "free to try", not "free with a paid Pro", not "free until the next version". **Free, for everyone, forever.** + +- **Nothing to buy, ever.** No Pro version, no paid modules, no packs sold one by one, no supporter pass, no licence key, no shop. The weather, the energy flow, TV screens, the car, announcements, the heat pump and the 3D printer are simply part of NextFloor. +- **New furniture all the time, for free.** 43 packs with about 800 models come with it, and new packs keep coming. +- **Build and extend it yourself.** The [furniture builder](https://therealmrbk.github.io/NextFloor/builder/) shares to a community store; a [plugin system](https://therealmrbk.github.io/NextFloor/docs/en/plugins/) with a reviewed [plugin store](https://github.com/therealMRBK/NextFloor-Plugins) adds device kinds, light animations and room cards, from anyone. +- **Your data stays home.** No account, no cloud, no usage data. +- **The promise is in the licence.** NextFloor is MIT licensed: anyone may read, change and share it. Nobody can take it away from you, not even me. + +I believe in open source: software that anyone may read, change and share, and that every home can use without paying a cent. That conviction is the reason NextFloor exists. + +## 🔒 Privacy + +The plan, its pictures and the packs live in Home Assistant's `.storage`. NextFloor does not talk to the internet on its own. Only if you switch on the optional real map, your browser loads map tiles from the tile server (OpenStreetMap by default). Pictures and history come from your own Home Assistant. + +## 🤖 Made with AI + +NextFloor was built entirely with AI assistance. The idea, the decisions and the testing in a real house come from a person; the design, the code, the tests and the documentation were written together with [Claude](https://www.anthropic.com/claude) (Anthropic) in [Claude Code](https://www.anthropic.com/claude-code). I would rather say so openly than let you guess. + +What that means for you: + +- **It is tested, but young.** There are automated tests (frontend logic, the furniture packs, the Home Assistant side) and releases are looked at in a real browser and installed on a real Home Assistant, but it has far fewer users than most integrations. Expect rough edges and report them. +- **Back up before you trust it.** The plan lives in Home Assistant's `.storage`; the editor has a backup and restore of the whole plan. +- **Read the code if it matters to you.** It is MIT licensed and small enough to read. Pull requests are welcome, also ones written with AI, as long as you say so and have run the checks (see [CONTRIBUTING.md](https://github.com/therealMRBK/NextFloor/blob/main/CONTRIBUTING.md)). + +## 💬 Ideas, questions and bugs + +[Discussions](https://github.com/therealMRBK/NextFloor/discussions) for ideas and questions, [Issues](https://github.com/therealMRBK/NextFloor/issues/new/choose) for bugs. Security problems go through [private reporting](https://github.com/therealMRBK/NextFloor/security/advisories/new). + +## 🛠️ Development + +
+Build, test, preview + +```bash +cd frontend +npm install +npm test # pure logic +npm run typecheck +npm run build # writes the bundles to custom_components/nextfloor/frontend (committed) +npm run screenshot # renders preview/index.html (invented demo data) with a local Chrome or Chromium +``` + +- **Preview without Home Assistant:** open `preview/index.html` through any local web server. +- **Deploy to a test instance:** create `deploy.local.json` with `{"target": "/custom_components/nextfloor"}` and run `npm run deploy` in `frontend/`. +- **Python tests** run in CI with `pytest-homeassistant-custom-component`. +- **Documentation site:** `cd tools/docs && npm install && npm run build` (sources in `docs/content`, English and German). +- **Furniture packs:** the built-in packs are generated by `tools/build_packs.py`. The format of your own packs is in the [documentation](https://therealmrbk.github.io/NextFloor/docs/en/packs/). + +
+ +## 🙏 Credits + +NextFloor started as a fork of [NeonPlan 3D](https://github.com/Mastershort/neonplan3d) by Mastershort (Torsten). The idea of a live 3D home right inside Home Assistant, and the groundwork NextFloor grew from, are his. NextFloor carries that idea on in its own direction: entirely free and open source, for everyone. Thank you, Torsten! + +## Licence + +MIT, see [LICENSE](https://github.com/therealMRBK/NextFloor/blob/main/LICENSE). NextFloor ships [three.js](https://threejs.org) (MIT), [Lit](https://lit.dev) (BSD-3-Clause); their notices are in [THIRD_PARTY_NOTICES.md](https://github.com/therealMRBK/NextFloor/blob/main/THIRD_PARTY_NOTICES.md). + +"Home Assistant" is a trademark of its owners; "Tesla" and the Tesla model names are trademarks of Tesla, Inc., and "IKEA" and its product names are trademarks of Inter IKEA Systems B.V.; they are used here only to name the sizes and models. NextFloor is an independent community project and not affiliated with or endorsed by Nabu Casa, Tesla or IKEA. diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..f7750d7 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,209 @@ +

NextFloor 标志

+ +

NextFloor

+ +

在 Home Assistant 里画出你的家,实时看它活起来。
+灯会照亮所在的房间,卷帘会动,门会开,电视播什么就显示什么,屋外在下雨。
+没有云端,不用账号。为墙上平板而生。

+ +

💚 永久免费。每一个功能、每一个家具包、每一次更新——所有人都能用,而且一直如此。
+没有 Pro 版,没有付费插件,没有赞助通行证,没有许可证密钥,没有商店。

+ +

+在 HACS 中打开 +在线演示 +全部模型 +开发版演示 +

+ +

+版本 +CI +HACS 官方商店 +永久免费 +MIT +由 AI 协助构建 +

+ +

真实住宅里的 NextFloor:房子旋转,一层展开,房间面板列出它的灯和设备

+ +

📖 English · 简体中文

+ +

🎬 在浏览器里看安装视频,从空白页面开始(45 分钟,英语配音,中/英/德字幕)

+ +

📖 中文手册 · 英文手册 · Anleitung(德语) · 🗺️ 路线图 · 📝 更新日志

+ +--- + +## ✨ 它能做什么 + +| | | +|---|---| +| ✏️ **平面图编辑器** | 楼层、房间、弧形墙、门窗、异形楼梯、室外区域和屋顶,都在 Home Assistant 里绘制,3D 视图就在平面图旁边。房间内的分区、图层、内侧尺寸、分段墙厚、**通到上层的挑高房间**、可转向的屋顶段、DXF 导入。 | +| ✓ **平面图检查** | 一张清单列出缺什么、哪里不对——房间没有区域、设备没放进去、房间重叠、门窗不在墙上、关联的实体已不存在——还有待机耗电设备及其年度电费,每项都能一键修复。新平面图有简短引导,按 `?` 看快捷键表。 | +| 📐 **面积与图纸** | 每个房间、每个楼层、整栋房子的居住面积,按德国《居住面积条例》计算;**1:100 的纸质平面图**,带尺寸和面积表,可直接打印或存为 PDF。 | +| 🕘 **版本与便签** | 给平面图起名存档(比如"装修前"),会一直保留,可与当前平面图对比;**便签可以钉在某个位置**,带到期日,在 3D 里显示为标记,搜索也能找到。 | +| 💡 **实时 3D** | 点击开关、滑动调光、长按换色。多灯泡灯具、卷帘(卷帘、百叶、内遮阳、Somfy *My*)、门窗都跟随对应实体;房间面板列出房间里的一切,场景排在最前。 | +| ✨ **灯光设计器** | 把房间的灯存成一个氛围,一键重现,还能套用到另一个房间。 | +| 🌡️ **房间气候** | 温度(夏季/冬季色阶)、湿度、CO₂、**发霉风险**和**舒适度评分**的热图,通风提示、低电量、空房间里忘关的灯、每个房间 24 小时温度曲线、会发亮的地暖。 | +| ☀️ **每个房间的阳光与用电** | 热图显示每个房间今天透过窗户获得的**日照小时**(依据平面图、朝向和太阳轨迹)和**当前用电功率**;房间面板里还有今日与本月的 kWh 和费用、全年日照、阳光晒热房间时的**遮阳提示**,以及供暖时开窗的提示。 | +| ⚡ **能源** | 光伏板阵(含东西向支架)、沿真实线缆路径的功率流动、储能电池电量、燃气与水表、每层独立电表,房屋卡片上显示最近 24 小时和**最近七天**。 | +| 🤖 **给自动化用的传感器** | *开着的门窗*和*开着的灯*作为 Home Assistant 传感器,有全屋和每层两种,实体列在属性里。按房间或按楼层**一键全关**,可撤销。 | +| 🔥 **热泵与 🖨️ 3D 打印机** | 实时卡片:出水/回水温度、热量与 COP;打印进度、剩余时间、层数、温度与耗材——打印件会在热床上长出来。 | +| 🚗 **汽车** | 电量、续航、充电时电流沿充电线从充电桩流向车、出发时间、离家距离、开着的门和后备箱、门锁与空调按钮。 | +| 📶 **Wi-Fi 地图** | 每个接入点在本层的覆盖范围、它带的设备,以及哪些网络设备离线。 | +| 📅 **今日** | 当天的日程和要收的垃圾桶,做成墙上平板的一张卡片。 | +| ⚠️ **告警** | 烟雾、燃气、漏水、报警器(并指出是哪个传感器触发的)、下雨时开着的窗、失联的门磁——还能为任意实体做**你自己的告警**。 | +| 📢 **播报** | *"开饭了!"* 只传给该听到的房间,通过它的音箱播,也会显示在每个打开的 NextFloor 屏幕上。 | +| 🏡 **家务与庭院** | 垃圾桶、信箱、缺水的植物、只在真实所在房间走动的宠物、扫地机和**割草机器人**按路线工作、喷灌、带水温和水泵的泳池、关联到 Home Assistant 区域的花园、每个房间的 *🧹 清洁*、每个房间对应的配电箱回路。 | +| 📺 **媒体** | 电视屏幕带封面和氛围灯;每个音箱和电视都有快捷菜单,含输入源、音量和每个音箱的预设。 | +| 🛋️ **家具** | 40 个基础模型和**41 个家具包、近 800 件家具**——季节与装饰、卫浴、音乐、Loft、日式、工坊、车辆、**可放自己照片的相框**——L 形和 U 形沙发、宜家尺寸、按原厂漆色渲染的特斯拉车型。任何家具都能设为"仅当某个辅助实体开启时显示"。 | +| 🚶 **漫游与时光回溯** | 以视线高度在屋里走动;回放最近几小时或几天。 | +| 🖥️ **为墙上平板准备** | 展示模式支持夜间调暗、星标菜单常开且更大、小屏幕的缩放与固定视角、慢速平板上**画质自动降级**、对比度更高字号更大的**易读模式**。 | +| 🎨 **跟随你的主题** | 颜色、字体、圆角都取自 Home Assistant;外观有 *Neon*、*Blueprint*、*Day*,以及实心刷漆墙面。 | +| 🧩 **卡片、插件、多语言** | `custom:nextfloor-card` 带可视化编辑器,插件系统带自己的商店,支持九种语言(含**简体中文**)。 | +| 🪑 **自己动手做** | **编辑器里的 🛠️ 家具工作室**(带门和抽屉的柜子、搁架、灯具、带屏幕的设备)、[家具构建器](https://therealmrbk.github.io/NextFloor/builder/)和社区商店、自己的 `.glb` 模型、Sweet Home 3D 与 DXF 导入、可被 AI 直接编写的平面图格式——还能把房屋**分享成一个视图文件**,在任何浏览器里打开。 | + +

0.22 新增:编辑器里的家具工作室、按日照小时的热图与房间面板、平面图检查、带居住面积的纸质平面图

+ +

放着自己照片的相框、L 形与 U 形沙发、带实时卡片正在打印的 3D 打印机,以及显示电量家用储能

+ +## 💚 永久免费 —— 一个承诺 + +NextFloor 是免费的,而且会一直免费。不是"免费试用",不是"免费但 Pro 要钱",也不是"这一版免费":**对所有人、永远免费。** 每一个功能、每一个家具包、每一次更新,发布当天就属于所有人。 + +- **没有任何要买的东西。** 没有 Pro 版,没有付费模块,没有逐个售卖的家具包,没有能优先拿到功能的赞助通行证,没有许可证密钥,没有商店。所有东西——窗外天气、能量流动、电视与音箱、汽车、播报、家务与庭院、热泵和 3D 打印机——本来就是 NextFloor 的一部分。 +- **家具一直在增加,而且免费。** 自带 41 个家具包、近 800 个模型,新家具包会随更新持续到来。 +- **自己做家具。** [家具构建器](https://therealmrbk.github.io/NextFloor/builder/)在浏览器里运行:做完就能看到它和 NextFloor 里一模一样的样子,还能分享到社区商店,别人一键就能装上。 +- **自己扩展。** 带审核[插件商店](https://github.com/therealMRBK/NextFloor-Plugins)的[插件系统](https://github.com/therealMRBK/NextFloor/blob/main/docs/plugins.md):新的设备类型、灯光动画、房间卡片——谁都可以做。 +- **数据留在家里。** 没有账号,没有云端,不上传任何使用数据。 +- **承诺写进了许可证。** NextFloor 采用 MIT 许可证:任何人都可以阅读、修改和分发。没有人能把它从你手里拿走——包括我。 + +我相信开源:任何人都能阅读、修改和分享的软件,每个家庭都能不花一分钱地用。这个信念就是 NextFloor 存在的原因。它起初是 NeonPlan 3D 的一个分支,后来走上自己的路,由这一个承诺支撑,由使用它的人一起塑造。 + +## 🖼️ 图集 + + + + + + +
带面板的实时房间视图
带面板的实时房间视图
平面图编辑器与旁边的 3D
平面图编辑器与旁边的 3D
楼层叠放
楼层叠放
能量流动
能量流动
窗外天气
窗外天气
电视屏幕
电视屏幕
热图
热图
剖切墙体
剖切墙体
墙上平板
墙上平板
家具库
家具库
宜家尺寸
宜家尺寸
特斯拉车型
特斯拉车型
+ + + +
Neon
Neon
Blueprint
Blueprint
Day
Day
+ +## 🚀 安装 + +**HACS**(推荐) + +1. NextFloor 已进入 **HACS 官方商店**:打开 HACS,搜索 **NextFloor** 并下载(或点上面的 HACS 按钮)。 +2. 重启 Home Assistant。 +3. 添加集成:[![开始配置 NextFloor。](https://my.home-assistant.io/badges/config_flow_start.svg)](https://my.home-assistant.io/redirect/config_flow_start/?domain=nextfloor),或 *设置 → 设备与服务 → 添加集成 → NextFloor*。 +4. 在侧边栏打开 **NextFloor**,切到**编辑器**,画出你的第一个楼层。 + +**之前是通过自定义仓库安装的?** 无需任何更改。NextFloor 现已进入 HACS 官方商店,你的安装、平面图和设置保持不变,更新仍通过 HACS 提供。HACS 刷新列表后会自动把它识别为普通仓库。 + +**手动安装:** 把 `custom_components/nextfloor` 复制到 `config/custom_components/` 并重启。需要 Home Assistant 2025.1 或更高版本。 + +## 🧩 仪表盘卡片 + +所有选项都在卡片的可视化编辑器里。YAML 里也一样: + +
+全部选项 + +```yaml +type: custom:nextfloor-card +floor: floor_ab12cd34 # 可选:只显示某一层(id 来自编辑器) +room: room_ab12cd34 # 可选:从这个房间开始 +height: 420 # 可选:高度(像素) +fill: false # 可选:填满仪表盘标题以下的整屏,而不是固定高度 +walls: auto # 可选:auto | cut +explode: true # 可选:在房屋视图里把楼层拉开 +floor_stack: dim # 可选:打开某层时下面楼层的处理:dim | stacked | single +quality: auto # 可选:auto | low | high +theme: neon # 可选:neon | blueprint | day +accent: "#00e5ff" # 可选:Neon 外观的强调色 +markers: important # 可选:none | important | all +heatmap: none # 可选:none | temperature | humidity | co2 | mould | values | wifi +room_panel: true # 可选:点击房间打开详情 +room_names: true # 可选:3D 里显示房间名 +controls: true # 可选:卡片里的开关,或 wall、floor、temperature、humidity、co2 的列表 +floor_thumbs: true # 可选:用楼层缩略图切换楼层 +fullscreen_button: false +stats: false # 可选:性能显示 +alerts: true # 可选:烟雾、燃气、CO、漏水、报警器,以及下雨时开着的窗,会脉动提示 +alert_jump: false # 可选:出现新告警时跳到对应房间 +scenes: true # 可选:所选房间的场景与脚本按钮 +energy: true # 可选:顶部显示能源数值 +flows: true # 可选:功率流动线常开(true)或常关(false);留空则显示为开关 +holograms: true # 可选:实时卡片(能量平衡、汽车、媒体)常开或常关;留空则显示为开关 +weather: true # 可选:窗外天气 +weather_entity: weather.home # 可选:用哪个天气实体(默认:按平面图里的设置) +idle_return: 0 # 可选:展示模式,无操作多少秒后回到起始视图 +night: "off" # 可选:展示模式,夜间调暗:off | sun | "22:00-06:00" +idle_orbit: false # 可选:展示模式,空闲返回后镜头缓慢转动 +central_open: false # 可选:星标菜单(收藏)默认展开,且字号更大 +keep_camera: false # 可选:切换楼层时保持方位、高度和距离 +readable: false # 可选:更高对比度和更大字号(墙上平板) +zoom: 1 # 可选:0.6 … 2.5,自适应视图的拉近程度 +today: true # 可选:带日程和垃圾桶的「今日」卡片 +sensor_bar: true # 可选:把你自己的传感器显示在顶部 +``` + +
+ +## 📦 使用自己的 3D 模型 + +有车辆模型(`.glb`)?在 NextFloor 面板里打开**扩展**,选择文件,把车头转向你,选好细节级别,保存到你的 Home Assistant。NextFloor 在浏览器里完成预处理,本身不带任何模型。详见 [docs/models.md](https://github.com/therealMRBK/NextFloor/blob/main/docs/models.md)。 + +## 🔒 隐私 + +平面图、图片和家具包都存放在 Home Assistant 的 `.storage` 里。NextFloor 不会自行联网;只有当你打开可选的真实地图时,浏览器才会从瓦片服务器加载地图瓦片(默认是 OpenStreetMap)。图片和历史都来自你自己的 Home Assistant。 + +## 🤖 由 AI 协助构建 + +NextFloor 完全在 AI 协助下构建。想法、决策和在真实住宅里的测试来自一个人;设计、代码、测试和文档是与 [Claude](https://www.anthropic.com/claude)(Anthropic)在 [Claude Code](https://www.anthropic.com/claude-code) 里一起写出来的。我更愿意直接说出来,而不是让你去猜。 + +这对你意味着什么: + +- **有测试,但还年轻。** 有自动化测试(前端逻辑、家具包、Home Assistant 后端),每个版本也会在真实浏览器里看、装到真实的 Home Assistant 上,但用户数远少于大多数集成。请预期会有粗糙的地方,并反馈给我们。 +- **信任它之前先备份。** 平面图保存在 Home Assistant 的 `.storage` 里;编辑器里有整份平面图的备份与恢复。 +- **在意的话就去读代码。** 它是 MIT 许可,体量小到可以通读。欢迎提交 PR,AI 写的也欢迎,只要说明并跑过检查(见 [CONTRIBUTING.md](https://github.com/therealMRBK/NextFloor/blob/main/CONTRIBUTING.md))。 + +## 🛠️ 开发 + +
+构建、测试、预览 + +```bash +cd frontend +npm install +npm test # 纯逻辑测试 +npm run typecheck +npm run build # 把 bundle 写到 custom_components/nextfloor/frontend(需提交) +npm run screenshot # 用本地 Chrome 或 Chromium 渲染 preview/index.html(虚构的演示数据) +``` + +- **不装 Home Assistant 也能预览**:用任意本地 Web 服务器打开 `preview/index.html`。 +- **部署到测试实例**:创建 `deploy.local.json`,内容为 `{"target": "/custom_components/nextfloor"}`,然后在 `frontend/` 里运行 `npm run deploy`。 +- **Python 测试**在 CI 里用 `pytest-homeassistant-custom-component` 运行。 +- **家具包**:内置家具包由 `tools/build_packs.py` 生成。自己做的家具包格式见 [docs/packs.md](https://github.com/therealMRBK/NextFloor/blob/main/docs/packs.md)(德语)。 + +
+ +## 💬 想法、问题与缺陷 + +想法和问题请到 [Discussions](https://github.com/therealMRBK/NextFloor/discussions),缺陷请到 [Issues](https://github.com/therealMRBK/NextFloor/issues/new/choose)。 + +## 🙏 致谢 + +NextFloor 起初是 Mastershort(Torsten)的 [NeonPlan 3D](https://github.com/Mastershort/neonplan3d) 的一个分支。"在 Home Assistant 里拥有一套实时 3D 的家"这个想法,以及 NextFloor 生长所依赖的基础,都是他的。NextFloor 沿着自己的方向把这个想法继续下去:完全免费、开源,面向所有人。谢谢你,Torsten! + +## 许可证 + +MIT,见 [LICENSE](https://github.com/therealMRBK/NextFloor/blob/main/LICENSE)。NextFloor 包含 [three.js](https://threejs.org)(MIT)、[Lit](https://lit.dev)(BSD-3-Clause);它们的声明在 [THIRD_PARTY_NOTICES.md](https://github.com/therealMRBK/NextFloor/blob/main/THIRD_PARTY_NOTICES.md) 里。 + +"Home Assistant" 是其所有者的商标;"Tesla" 及特斯拉车型名称是 Tesla, Inc. 的商标;"IKEA" 及其产品名称是 Inter IKEA Systems B.V. 的商标;此处仅用于说明尺寸和车型。NextFloor 是独立的社区项目,与 Nabu Casa、Tesla 或 IKEA 没有关联,也未获其背书。 diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..cdf440e --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,19 @@ +# NextFloor – Roadmap + +Ideas for what comes next. There are no fixed dates; everything lands in NextFloor for free. What comes next is mostly decided by the wishes in [Discussions](https://github.com/therealMRBK/NextFloor/discussions) and the [issues](https://github.com/therealMRBK/NextFloor/issues) – vote there or add your own. Everything has to keep running on old, weak wall tablets. What is already done is in the [changelog](https://github.com/therealMRBK/NextFloor/blob/main/CHANGELOG.md). + +*Deutsch weiter unten.* + +| Topic | What it is about | +|---|---| +| More imports | More plan and scan formats besides JSON, Sweet Home 3D, DXF and IFC (doors and windows from IFC next) | + +--- + +# NextFloor – Roadmap (Deutsch) + +Ideen für das, was als Nächstes kommt. Es gibt keine festen Termine; alles kommt kostenlos in NextFloor. Was als Nächstes kommt, bestimmen vor allem die Wünsche in den [Discussions](https://github.com/therealMRBK/NextFloor/discussions) und den [Issues](https://github.com/therealMRBK/NextFloor/issues) – stimm dort ab oder schreib deinen eigenen. Alles muss weiter auf alten, schwachen Wand-Tablets laufen. Was schon fertig ist, steht im [Changelog](https://github.com/therealMRBK/NextFloor/blob/main/CHANGELOG.md). + +| Thema | Worum es geht | +|---|---| +| Weitere Importe | Weitere Plan- und Scan-Formate neben JSON, Sweet Home 3D, DXF und IFC (als Nächstes Türen und Fenster aus IFC) | diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..58b8285 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,18 @@ +# Security policy + +## Supported versions + +Only the latest release receives fixes. Update through HACS. + +## Reporting a vulnerability + +Please do **not** open a public issue for a security problem. Use GitHub's private reporting instead: +[Report a vulnerability](https://github.com/therealMRBK/NextFloor/security/advisories/new). + +Include what you found, the NextFloor and Home Assistant versions and, if you can, how to reproduce it. You get an answer within a few days; a confirmed problem is fixed in a patch release and credited in the changelog unless you prefer otherwise. + +## What NextFloor does and does not do + +- It does not talk to the internet on its own and has no account or cloud part. +- Plugins run with the same rights as NextFloor in your browser, so install only plugins whose source you trust (the plugin store pins every file by sha256). +- Shared plans and share views are built from an allowlist and carry no entity ids, areas, map position or other data of your home. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..d1422da --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,76 @@ +# Third-party notices + +NextFloor ships the following third-party software inside its bundles +(`custom_components/nextfloor/frontend/`). Their licence texts are reproduced here, as they require. + +NextFloor itself is released under the MIT licence (see `LICENSE`). + +## three.js 0.186.1 (MIT) + + + +``` +The MIT License + +Copyright © 2010-2026 three.js authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +## Lit 3.3.3 (BSD-3-Clause) + +Includes `lit-html` 3.3.3, `lit-element` 4.2.2 and `@lit/reactive-element` 2.1.2, all by Google LLC under the same licence. + + + +``` +BSD 3-Clause License + +Copyright (c) 2017 Google LLC. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +## Build and development tools + +TypeScript (Apache-2.0), esbuild (MIT) and puppeteer-core (Apache-2.0) are used to build and test the project. +They are not part of what is distributed. diff --git a/brand-src/icon.svg b/brand-src/icon.svg new file mode 100644 index 0000000..4e24beb --- /dev/null +++ b/brand-src/icon.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/custom_components/nextfloor/LICENSE b/custom_components/nextfloor/LICENSE new file mode 100644 index 0000000..654293b --- /dev/null +++ b/custom_components/nextfloor/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2026 Mastershort +Copyright (c) 2026 therealMRBK + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/custom_components/nextfloor/THIRD_PARTY_NOTICES.md b/custom_components/nextfloor/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..d1422da --- /dev/null +++ b/custom_components/nextfloor/THIRD_PARTY_NOTICES.md @@ -0,0 +1,76 @@ +# Third-party notices + +NextFloor ships the following third-party software inside its bundles +(`custom_components/nextfloor/frontend/`). Their licence texts are reproduced here, as they require. + +NextFloor itself is released under the MIT licence (see `LICENSE`). + +## three.js 0.186.1 (MIT) + + + +``` +The MIT License + +Copyright © 2010-2026 three.js authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +## Lit 3.3.3 (BSD-3-Clause) + +Includes `lit-html` 3.3.3, `lit-element` 4.2.2 and `@lit/reactive-element` 2.1.2, all by Google LLC under the same licence. + + + +``` +BSD 3-Clause License + +Copyright (c) 2017 Google LLC. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +## Build and development tools + +TypeScript (Apache-2.0), esbuild (MIT) and puppeteer-core (Apache-2.0) are used to build and test the project. +They are not part of what is distributed. diff --git a/custom_components/nextfloor/__init__.py b/custom_components/nextfloor/__init__.py new file mode 100644 index 0000000..83ff7e3 --- /dev/null +++ b/custom_components/nextfloor/__init__.py @@ -0,0 +1,115 @@ +"""NextFloor: draw your home in Home Assistant and control it in 3D.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +from homeassistant.components import frontend, panel_custom +from homeassistant.components.http import StaticPathConfig +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import config_validation as cv +from homeassistant.helpers.typing import ConfigType +from homeassistant.loader import async_get_integration + +from .announce import async_register_announce +from .card_resource import async_remove_card_resource, async_schedule_card_resource +from .const import ( + DOMAIN, + MAIN_BUNDLE, + PANEL_COMPONENT, + PANEL_ICON, + PANEL_TITLE, + PANEL_URL_PATH, + URL_BASE, +) +from .meshes import async_register_mesh_view +from .storage import NextFloorData +from .store_notice import async_notify_official_store +from .websocket import async_register_commands + +CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) + +_STATIC_REGISTERED = f"{DOMAIN}_static_registered" +# sensors from the plan: open windows and doors, lights on (per floor and for the house) +PLATFORMS = [Platform.SENSOR] + + +async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: + """Register the websocket commands and the actions once.""" + async_register_commands(hass) + async_register_mesh_view(hass) + async_register_announce(hass) + return True + + +_MAIN_URL = f"{DOMAIN}_main_url" + + +def _bundle_hash() -> str: + """A short hash of the main bundle: a rebuilt bundle gets a new URL even when the version stays.""" + path = Path(__file__).parent / "frontend" / MAIN_BUNDLE + try: + return hashlib.sha256(path.read_bytes()).hexdigest()[:10] + except OSError: + return "0" + + +async def _async_main_url(hass: HomeAssistant) -> str: + # computed once per run, so adding and removing the script use the same URL + if url := hass.data.get(_MAIN_URL): + return url + integration = await async_get_integration(hass, DOMAIN) + digest = await hass.async_add_executor_job(_bundle_hash) + url = f"{URL_BASE}/{MAIN_BUNDLE}?v={integration.version}-{digest}" + hass.data[_MAIN_URL] = url + return url + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Load the stores and register the frontend (panel and card).""" + data = NextFloorData(hass) + await data.async_load() + hass.data[DOMAIN] = data + + # static paths cannot be unregistered, so they are registered once per run + if not hass.data.get(_STATIC_REGISTERED): + await hass.http.async_register_static_paths( + [StaticPathConfig(URL_BASE, str(Path(__file__).parent / "frontend"), cache_headers=False)] + ) + hass.data[_STATIC_REGISTERED] = True + + url = await _async_main_url(hass) + frontend.add_extra_js_url(hass, url) + # and as a dashboard resource, so a dashboard never draws the card before its script is there (#252) + async_schedule_card_resource(hass, url) + await panel_custom.async_register_panel( + hass, + frontend_url_path=PANEL_URL_PATH, + webcomponent_name=PANEL_COMPONENT, + sidebar_title=PANEL_TITLE, + sidebar_icon=PANEL_ICON, + module_url=url, + require_admin=False, + config={}, + ) + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + await async_notify_official_store(hass, entry) + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Remove panel, card and sensors.""" + await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + frontend.async_remove_panel(hass, PANEL_URL_PATH) + frontend.remove_extra_js_url(hass, await _async_main_url(hass)) + hass.data.pop(DOMAIN, None) + return True + + +async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + """The plan, its pictures and packs stay in .storage when the integration is removed: they are the + user's work, and removing and re-adding the integration must never cost it.""" + await async_remove_card_resource(hass) diff --git a/custom_components/nextfloor/announce.py b/custom_components/nextfloor/announce.py new file mode 100644 index 0000000..2b8218f --- /dev/null +++ b/custom_components/nextfloor/announce.py @@ -0,0 +1,347 @@ +"""Announcements: the action nextfloor.announce speaks a message in rooms of the plan and on the open NextFloor screens. + +Each room speaks through its own speaker: the one chosen for the room in the plan, else one placed in the room, else +one of the room's area. A voice satellite announces with its chime, an Echo through its announce entity (Alexa Devices) +or as an announcement (Alexa Media Player), a speaker that can announce (Sonos and others) lowers its music for it, any +other speaker plays it through text-to-speech. TVs and speakers that are off are never picked by themselves. Rooms +with a quiet time are left out while it runs, unless the announcement names only that room. +""" + +from __future__ import annotations + +from datetime import time as dtime +import logging +from typing import Any + +from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse, callback +from homeassistant.exceptions import ServiceValidationError +from homeassistant.helpers import config_validation as cv +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.dispatcher import async_dispatcher_send +from homeassistant.util import dt as dt_util +import voluptuous as vol + +from .const import DOMAIN, SIGNAL_ANNOUNCE + +_LOGGER = logging.getLogger(__name__) + +SERVICE_ANNOUNCE = "announce" + +ANNOUNCE_SCHEMA = vol.Schema( + { + vol.Required("message"): vol.All(cv.string, vol.Length(min=1, max=500)), + # rooms by name, room id or area id; none and no floor: every room with a speaker + vol.Optional("rooms"): vol.All(cv.ensure_list, [cv.string]), + vol.Optional("floor"): cv.string, + vol.Optional("on_speakers", default=True): cv.boolean, + vol.Optional("on_screens", default=True): cv.boolean, + # only the NextFloor screens with these names (set on each screen); none: every screen + vol.Optional("screens"): vol.All(cv.ensure_list, [cv.string]), + # a text-to-speech entity instead of the one chosen in the plan (or the first one) + vol.Optional("tts_entity"): cv.entity_id, + } +) + +_TV_CLASSES = {"tv"} +# MediaPlayerEntityFeature.MEDIA_ANNOUNCE: the speaker lowers what it plays for the announcement and carries on after +_MEDIA_ANNOUNCE = 1048576 + + +class NoSpeech(Exception): + """A speaker that needs text-to-speech while there is no text-to-speech entity.""" + + +def _point_in(points: list[list[float]], x: float, z: float) -> bool: + """Ray casting: whether (x, z) lies inside the polygon.""" + inside = False + j = len(points) - 1 + for i, (xi, zi) in enumerate(points): + xj, zj = points[j] + if (zi > z) != (zj > z) and x < (xj - xi) * (z - zi) / ((zj - zi) or 1e-12) + xi: + inside = not inside + j = i + return inside + + +def _parse_time(text: Any) -> dtime | None: + try: + hours, minutes = str(text).split(":")[:2] + return dtime(int(hours), int(minutes)) + except (ValueError, TypeError): + return None + + +def in_quiet_time(room: dict[str, Any], now: dtime) -> bool: + """Whether the room's quiet time runs at `now` (a time span over midnight works too).""" + quiet = room.get("announce_quiet") or {} + start, end = _parse_time(quiet.get("from")), _parse_time(quiet.get("to")) + if start is None or end is None or start == end: + return False + return start <= now < end if start < end else now >= start or now < end + + +def _matches(room: dict[str, Any], wanted: str) -> bool: + key = wanted.strip().casefold() + return key in ( + str(room.get("id", "")).casefold(), + str(room.get("area_id") or "").casefold(), + str(room.get("name", "")).strip().casefold(), + ) + + +def target_rooms( + building: dict[str, Any], rooms: list[str] | None, floor: str | None +) -> tuple[list[tuple[dict, dict]], bool]: + """The (floor, room) pairs an announcement goes to, and whether exactly the rooms asked for were named.""" + pairs = [(f, r) for f in building.get("floors", []) for r in f.get("rooms", [])] + if floor: + key = floor.strip().casefold() + pairs = [ + (f, r) + for f, r in pairs + if key + in ( + str(f.get("id", "")).casefold(), + str(f.get("name", "")).strip().casefold(), + str(f.get("ha_floor") or "").casefold(), + ) + ] + if rooms: + pairs = [(f, r) for f, r in pairs if any(_matches(r, w) for w in rooms)] + return pairs, True + return pairs, False + + +def _area_entities(hass: HomeAssistant, area_id: str | None) -> list[str]: + if not area_id: + return [] + ent_reg = er.async_get(hass) + dev_reg = dr.async_get(hass) + found = [] + for entry in ent_reg.entities.values(): + if entry.disabled_by or entry.hidden_by: + continue + area = entry.area_id + if area is None and entry.device_id and (device := dev_reg.async_get(entry.device_id)): + area = device.area_id + if area == area_id: + found.append(entry.entity_id) + return found + + +def _is_echo_announce(hass: HomeAssistant, entity_id: str) -> bool: + """The announce entity of an Echo (Alexa Devices: a notify entity whose unique id ends in "-announce").""" + if not entity_id.startswith("notify."): + return False + entry = er.async_get(hass).async_get(entity_id) + return entry is not None and str(entry.unique_id).endswith("-announce") + + +def _usable_speaker(hass: HomeAssistant, entity_id: str) -> bool: + """A speaker that may be picked by itself: no TV, not off or gone. An Echo's announce entity has no state to ask.""" + st = hass.states.get(entity_id) + if st is None or st.state == "unavailable": + return False + if entity_id.startswith("notify."): + return _is_echo_announce(hass, entity_id) + if st.state in ("off", "unknown"): + return False + return st.attributes.get("device_class") not in _TV_CLASSES + + +def room_speaker(hass: HomeAssistant, floor: dict[str, Any], room: dict[str, Any]) -> str | None: + """A room's speaker: chosen in the plan, else placed in the room, else a voice satellite or speaker of its area.""" + chosen = room.get("announce_speaker") + if chosen == "none": + return None + if chosen: + return chosen + points = room.get("points") or [] + if len(points) >= 3: + placed = [ + p["entity_id"] + for p in floor.get("placements", []) + if str(p.get("entity_id", "")).startswith(("media_player.", "assist_satellite.")) + and _point_in(points, float(p.get("x", 0)), float(p.get("z", 0))) + ] + placed += [ + f["entity"] + for f in floor.get("furniture", []) + if str(f.get("entity") or "").startswith(("media_player.", "assist_satellite.")) + and _point_in(points, float(f.get("x", 0)), float(f.get("z", 0))) + ] + for entity_id in placed: + if _usable_speaker(hass, entity_id): + return entity_id + area = _area_entities(hass, room.get("area_id")) + for domain in ("assist_satellite.", "notify.", "media_player."): + for entity_id in sorted(e for e in area if e.startswith(domain)): + if _usable_speaker(hass, entity_id): + return entity_id + return None + + +def _announce_entity(hass: HomeAssistant, media_player: str) -> str | None: + """The announce entity of the same device (an Echo of the Alexa Devices integration).""" + ent_reg = er.async_get(hass) + entry = ent_reg.async_get(media_player) + if entry is None or entry.device_id is None: + return None + for other in er.async_entries_for_device(ent_reg, entry.device_id): + if other.domain == "notify" and str(other.unique_id).endswith("-announce"): + return other.entity_id + return None + + +def _platform(hass: HomeAssistant, entity_id: str) -> str | None: + entry = er.async_get(hass).async_get(entity_id) + return entry.platform if entry else None + + +def _tts_entity(hass: HomeAssistant, building: dict[str, Any], wanted: str | None) -> str | None: + """The text-to-speech entity: asked for, chosen in the plan, else the first one.""" + for candidate in (wanted, (building.get("settings") or {}).get("announce_tts")): + if candidate and candidate != "none" and hass.states.get(candidate): + return candidate + entities = sorted(hass.states.async_entity_ids("tts")) + return entities[0] if entities else None + + +async def _speak(hass: HomeAssistant, speaker: str, message: str, tts: str | None) -> str: + """Say the message on one speaker; returns how (for the response). Raises NoSpeech when it needs text-to-speech.""" + if speaker.startswith("assist_satellite."): + await hass.services.async_call( + "assist_satellite", "announce", {"entity_id": speaker, "message": message}, blocking=True + ) + return "satellite" + announce = speaker if speaker.startswith("notify.") else _announce_entity(hass, speaker) + if announce: + await hass.services.async_call( + "notify", "send_message", {"entity_id": announce, "message": message}, blocking=True + ) + return "echo" + if _platform(hass, speaker) == "alexa_media" and hass.services.has_service("notify", "alexa_media"): + await hass.services.async_call( + "notify", + "alexa_media", + {"message": message, "target": [speaker], "data": {"type": "announce"}}, + blocking=True, + ) + return "echo" + if tts is None: + raise NoSpeech + st = hass.states.get(speaker) + features = int(st.attributes.get("supported_features", 0)) if st else 0 + if features & _MEDIA_ANNOUNCE: + media_id = tts_media_id(hass, message, tts) + await hass.services.async_call( + "media_player", + "play_media", + {"entity_id": speaker, "media_content_id": media_id, "media_content_type": "music", "announce": True}, + blocking=True, + ) + return "announce" + await hass.services.async_call( + "tts", + "speak", + {"entity_id": tts, "media_player_entity_id": speaker, "message": message, "cache": True}, + blocking=True, + ) + return "tts" + + +def tts_media_id(hass: HomeAssistant, message: str, tts: str) -> str: + """The media source id of the spoken message (text-to-speech is loaded only when it is needed).""" + from homeassistant.components.tts import generate_media_source_id + + return generate_media_source_id(hass, message, engine=tts, cache=True) + + +async def screen_audio(hass: HomeAssistant, tts: str | None, message: str) -> str | None: + """A URL with the spoken message for the screens (None: they speak with the browser's own voice).""" + if tts is None: + return None + try: + from homeassistant.components import media_source + + resolved = await media_source.async_resolve_media(hass, tts_media_id(hass, message, tts), None) + except Exception as err: # any engine error just leaves the screens to the browser's voice + _LOGGER.debug("No text-to-speech audio for the screens: %s", err) + return None + return resolved.url + + +async def async_announce(hass: HomeAssistant, building: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]: + """Speak an announcement on the rooms' speakers and send it to the NextFloor screens.""" + message: str = data["message"] + tts = _tts_entity(hass, building, data.get("tts_entity")) + spoken: dict[str, str] = {} + skipped: dict[str, str] = {} + if data.get("on_speakers", True): + pairs, named = target_rooms(building, data.get("rooms"), data.get("floor")) + if data.get("rooms") and not pairs: + raise ServiceValidationError(translation_domain=DOMAIN, translation_key="no_rooms") + now = dt_util.now().time() + done: set[str] = set() + for floor, room in pairs: + name = room.get("name") or room.get("id", "") + # a quiet room only hears what is meant for it alone + if in_quiet_time(room, now) and not (named and len(pairs) == 1): + skipped[name] = "quiet" + continue + speaker = room_speaker(hass, floor, room) + if speaker is None: + if named: + skipped[name] = "no_speaker" + continue + if speaker in done: + continue + done.add(speaker) + try: + spoken[speaker] = await _speak(hass, speaker, message, tts) + except NoSpeech: + skipped[name] = "no_tts" + except Exception as err: # one speaker failing must not stop the others + _LOGGER.warning("Announcement on %s failed: %s", speaker, err) + skipped[name] = "failed" + on_screens = bool(data.get("on_screens", True)) + if on_screens: + audio = await screen_audio(hass, tts, message) + payload = { + "message": message, + "screens": data.get("screens") or [], + "audio": audio, + "time": dt_util.utcnow().isoformat(), + } + async_dispatcher_send(hass, SIGNAL_ANNOUNCE, payload) + # nobody heard it because no speaker could talk: say why instead of failing silently + if not spoken and not on_screens and skipped and all(why == "no_tts" for why in skipped.values()): + raise ServiceValidationError(translation_domain=DOMAIN, translation_key="no_tts") + return {"speakers": spoken, "skipped": skipped, "screens": on_screens} + + +RELOAD_SCHEMA = vol.Schema({vol.Optional("template"): vol.All(cv.string, vol.Length(max=64))}) + + +@callback +def async_register_announce(hass: HomeAssistant) -> None: + """Register the actions nextfloor.announce and nextfloor.reload_screens.""" + + async def reload_screens(call: ServiceCall) -> None: + # the open screens load their page again, some seconds apart; with a template only the cards that use it + payload = {"reload": True, "template": call.data.get("template"), "time": dt_util.utcnow().isoformat()} + async_dispatcher_send(hass, SIGNAL_ANNOUNCE, payload) + + hass.services.async_register(DOMAIN, "reload_screens", reload_screens, schema=RELOAD_SCHEMA) + + async def handle(call: ServiceCall) -> dict[str, Any] | None: + data = hass.data.get(DOMAIN) + if data is None: + raise ServiceValidationError(translation_domain=DOMAIN, translation_key="not_loaded") + result = await async_announce(hass, data.building, call.data) + return result if call.return_response else None + + hass.services.async_register( + DOMAIN, SERVICE_ANNOUNCE, handle, schema=ANNOUNCE_SCHEMA, supports_response=SupportsResponse.OPTIONAL + ) diff --git a/custom_components/nextfloor/ble.py b/custom_components/nextfloor/ble.py new file mode 100644 index 0000000..9b8a8a5 --- /dev/null +++ b/custom_components/nextfloor/ble.py @@ -0,0 +1,167 @@ +"""Locate a Bluetooth tag by room, learned by walking. + +Every Bluetooth scanner Home Assistant knows (ESPHome Bluetooth proxies, Shelly devices with Bluetooth scanning on, the +host's own adapters) hears a tag with a different signal strength. While you walk from room to room with the tag, the +editor records that pattern per room (a fingerprint). Later the current pattern is compared with the fingerprints and +the nearest room wins. Nothing here talks to the tag; it only reads what the scanners already report. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +import math +import statistics +from typing import Any + +from homeassistant.core import HomeAssistant + +# a scanner that does not hear the tag counts as this (dBm); differences are capped, so one odd scanner cannot decide +MISSING = -100.0 +MAX_DIFF = 40.0 +# above this distance (RMS over the scanners, in dB) no room is a good match +UNKNOWN_DISTANCE = 18.0 +# a new room has to win this many readings in a row before the sensor switches +SWITCH_VOTES = 3 + +Reading = Mapping[str, float] + + +def distance(a: Reading, b: Reading) -> float: + """The distance between two signal patterns: RMS of the per-scanner differences in dB.""" + keys = set(a) | set(b) + if not keys: + return math.inf + total = sum(min(abs(a.get(k, MISSING) - b.get(k, MISSING)), MAX_DIFF) ** 2 for k in keys) + return math.sqrt(total / len(keys)) + + +def locate(prints: Iterable[Mapping[str, Any]], reading: Reading) -> tuple[str | None, float, float]: + """The room that fits a reading best: (room id, its distance in dB, how far the runner-up is behind). + + `prints` are {"room": id, "rssi": {scanner: dBm}}; a room may have several (one per spot you recorded there). + No room is returned when nothing is heard or no fingerprint is close enough. + """ + if not reading: + return None, math.inf, 0.0 + best: dict[str, float] = {} + for fp in prints: + d = distance(fp.get("rssi") or {}, reading) + room = fp.get("room") + if isinstance(room, str) and d < best.get(room, math.inf): + best[room] = d + if not best: + return None, math.inf, 0.0 + ranked = sorted(best.items(), key=lambda kv: kv[1]) + room, dist = ranked[0] + if dist > UNKNOWN_DISTANCE: + return None, dist, 0.0 + margin = ranked[1][1] - dist if len(ranked) > 1 else UNKNOWN_DISTANCE + return room, dist, margin + + +def median_reading(samples: Iterable[Reading]) -> dict[str, float]: + """The median signal per scanner over several samples. A scanner that missed the tag in most samples is left out.""" + samples = list(samples) + if not samples: + return {} + out: dict[str, float] = {} + for key in {k for s in samples for k in s}: + values = [s[key] for s in samples if key in s] + if len(values) * 2 > len(samples): + out[key] = round(statistics.median(values), 1) + return out + + +class Smoother: + """Keeps the answer from flickering: a different room has to win several readings in a row.""" + + def __init__(self, votes: int = SWITCH_VOTES) -> None: + self.votes = votes + self.room: str | None = None + self._candidate: str | None = None + self._count = 0 + + def update(self, room: str | None) -> str | None: + """Take one reading's room and return the room to show.""" + if room == self.room: + self._candidate, self._count = None, 0 + return self.room + if room == self._candidate: + self._count += 1 + else: + self._candidate, self._count = room, 1 + if self._count >= self.votes: + self.room, self._candidate, self._count = room, None, 0 + return self.room + + +def smooth_reading(history: list[dict[str, float]], reading: Reading, size: int = 5) -> dict[str, float]: + """Adds a reading to the history (newest last, `size` kept) and returns the median over it.""" + history.append(dict(reading)) + del history[:-size] + return median_reading(history) + + +def rooms_of(building: Mapping[str, Any]) -> dict[str, dict[str, str]]: + """Room id -> {"name", "floor"} of every room of the plan.""" + out: dict[str, dict[str, str]] = {} + for floor in building.get("floors", []): + for room in floor.get("rooms", []): + out[room["id"]] = {"name": room.get("name") or room["id"], "floor": floor.get("name") or floor["id"]} + return out + + +def tags_of(building: Mapping[str, Any]) -> list[dict[str, Any]]: + """The Bluetooth tags set up in the plan.""" + ble = building.get("settings", {}).get("ble") or {} + return list(ble.get("tags") or []) + + +# --- Home Assistant side --------------------------------------------------------------------------------------------- + + +def available(hass: HomeAssistant) -> bool: + """Whether Home Assistant's Bluetooth integration is running.""" + return "bluetooth" in hass.config.components + + +def tag_address(hass: HomeAssistant, tag: Mapping[str, Any]) -> str | None: + """The address to listen for: the fixed one, or the current one of a Private BLE Device tracker.""" + if entity := tag.get("entity"): + state = hass.states.get(entity) + current = state.attributes.get("current_address") if state else None + return str(current).upper() if current else None + address = tag.get("address") + return str(address).upper() if address else None + + +def scanner_readings(hass: HomeAssistant, address: str) -> dict[str, tuple[str, float]]: + """What every scanner last heard of an address: source -> (scanner name, RSSI in dBm).""" + if not available(hass): + return {} + from homeassistant.components import bluetooth # imported late: Bluetooth is optional + + out: dict[str, tuple[str, float]] = {} + for device in bluetooth.async_scanner_devices_by_address(hass, address.upper(), False): + rssi = device.advertisement.rssi + if rssi is not None and rssi > -127: + out[device.scanner.source] = (device.scanner.name, float(rssi)) + return out + + +def discovered(hass: HomeAssistant, limit: int = 80) -> dict[str, Any]: + """The scanners and the devices they hear, strongest first, for choosing a tag in the editor.""" + if not available(hass): + return {"available": False, "scanners": [], "devices": []} + from homeassistant.components import bluetooth + + scanners = [{"source": s.source, "name": s.name} for s in bluetooth.async_current_scanners(hass)] + seen: dict[str, dict[str, Any]] = {} + for info in bluetooth.async_discovered_service_info(hass, False): + row = seen.setdefault(info.address, {"address": info.address, "name": info.name, "rssi": -200, "named": False}) + row["rssi"] = max(row["rssi"], info.rssi) + # a device without a name shows up with its address as the name + row["named"] = info.name != info.address + row["name"] = info.name + devices = sorted(seen.values(), key=lambda r: (not r["named"], -r["rssi"]))[:limit] + return {"available": True, "scanners": scanners, "devices": devices} diff --git a/custom_components/nextfloor/brand/icon.png b/custom_components/nextfloor/brand/icon.png new file mode 100644 index 0000000..a7e5300 Binary files /dev/null and b/custom_components/nextfloor/brand/icon.png differ diff --git a/custom_components/nextfloor/brand/icon@2x.png b/custom_components/nextfloor/brand/icon@2x.png new file mode 100644 index 0000000..f1e2d1a Binary files /dev/null and b/custom_components/nextfloor/brand/icon@2x.png differ diff --git a/custom_components/nextfloor/card_resource.py b/custom_components/nextfloor/card_resource.py new file mode 100644 index 0000000..0059a1a --- /dev/null +++ b/custom_components/nextfloor/card_resource.py @@ -0,0 +1,83 @@ +"""The dashboard card as a Lovelace resource. + +The main bundle is also loaded as an extra frontend module, but in the companion app a dashboard may be drawn +before that module has arrived; the card then stays "Custom element doesn't exist: nextfloor-card" until the +sidebar page is opened (#252). Lovelace waits for its resources before it draws cards, so the card's bundle is +kept in the resource list as well, in storage mode only (YAML resources belong to the user). +""" + +from __future__ import annotations + +import logging +from typing import Any + +from homeassistant.const import EVENT_HOMEASSISTANT_STARTED +from homeassistant.core import CoreState, Event, HomeAssistant + +from .const import MAIN_BUNDLE, URL_BASE + +_LOGGER = logging.getLogger(__name__) + + +def _resources(hass: HomeAssistant) -> Any | None: + """Lovelace's resource collection when it can be changed (storage mode), else None.""" + data = hass.data.get("lovelace") + if data is None: + return None + # since 2025.2 a LovelaceData object, before a dict + resources = data.get("resources") if isinstance(data, dict) else getattr(data, "resources", None) + if resources is None or not hasattr(resources, "async_create_item"): + return None + return resources + + +def _is_ours(url: str) -> bool: + """A resource that loads our main bundle: ours, or an older copy of it (another path, an old hand install).""" + return url.split("?")[0].endswith(f"/{MAIN_BUNDLE}") + + +async def async_ensure_card_resource(hass: HomeAssistant, url: str) -> None: + """Keep exactly our current bundle URL in the dashboard resources (added once, updated after an update).""" + resources = _resources(hass) + if resources is None: + return + try: + await resources.async_get_info() # loads the collection + ours = [item for item in resources.async_items() if _is_ours(str(item.get("url", "")))] + if not ours: + await resources.async_create_item({"res_type": "module", "url": url}) + _LOGGER.debug("Added the dashboard card resource %s", url) + return + for item in ours: + if item.get("url") != url: + # an older version or an old copy of the bundle: it would define the card first, so it points to ours + await resources.async_update_item(item["id"], {"res_type": "module", "url": url}) + _LOGGER.debug("Updated dashboard resource %s to %s", item.get("url"), url) + except Exception: # the card still loads as an extra module, this is only a help + _LOGGER.debug("Could not update the dashboard resources", exc_info=True) + + +def async_schedule_card_resource(hass: HomeAssistant, url: str) -> None: + """Run once Home Assistant has started (Lovelace and its resources are set up by then).""" + if hass.state is CoreState.running: + hass.async_create_task(async_ensure_card_resource(hass, url)) + return + + async def _started(_event: Event) -> None: + await async_ensure_card_resource(hass, url) + + hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, _started) + + +async def async_remove_card_resource(hass: HomeAssistant) -> None: + """When the integration is removed: drop the resources that point to our own static path.""" + resources = _resources(hass) + if resources is None: + return + try: + await resources.async_get_info() + for item in list(resources.async_items()): + if str(item.get("url", "")).startswith(f"{URL_BASE}/"): + await resources.async_delete_item(item["id"]) + except Exception: + _LOGGER.debug("Could not remove the dashboard resource", exc_info=True) diff --git a/custom_components/nextfloor/config_flow.py b/custom_components/nextfloor/config_flow.py new file mode 100644 index 0000000..498f5e1 --- /dev/null +++ b/custom_components/nextfloor/config_flow.py @@ -0,0 +1,21 @@ +"""Config flow for NextFloor (no options: everything is set up in the panel).""" + +from __future__ import annotations + +from typing import Any + +from homeassistant.config_entries import ConfigFlow, ConfigFlowResult + +from .const import DOMAIN, PANEL_TITLE + + +class NextFloorConfigFlow(ConfigFlow, domain=DOMAIN): + """Single-step flow.""" + + VERSION = 1 + + async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: + """Confirm and create the entry.""" + if user_input is not None: + return self.async_create_entry(title=PANEL_TITLE, data={}) + return self.async_show_form(step_id="user") diff --git a/custom_components/nextfloor/const.py b/custom_components/nextfloor/const.py new file mode 100644 index 0000000..596e641 --- /dev/null +++ b/custom_components/nextfloor/const.py @@ -0,0 +1,27 @@ +"""Constants for NextFloor.""" + +from __future__ import annotations + +DOMAIN = "nextfloor" + +STORAGE_VERSION = 1 +# minor versions of the building store; each step has a migration in storage.py +STORAGE_MINOR_VERSION = 2 +STORAGE_KEY_BUILDING = f"{DOMAIN}.building" +STORAGE_KEY_IMAGES = f"{DOMAIN}.images" +STORAGE_KEY_HISTORY = f"{DOMAIN}.history" +STORAGE_KEY_PACKS = f"{DOMAIN}.packs" + +# restore points: at most this many, and a new one only after this pause since the last one +HISTORY_MAX = 20 +HISTORY_INTERVAL = 600 + +URL_BASE = "/nextfloor_static" +MAIN_BUNDLE = "nextfloor.js" +PANEL_URL_PATH = "nextfloor" +PANEL_COMPONENT = "nextfloor-panel" +PANEL_ICON = "mdi:floor-plan" +PANEL_TITLE = "NextFloor" + +SIGNAL_BUILDING_UPDATED = f"{DOMAIN}_building_updated" +SIGNAL_ANNOUNCE = f"{DOMAIN}_announce" diff --git a/custom_components/nextfloor/frontend/lang/cs.json b/custom_components/nextfloor/frontend/lang/cs.json new file mode 100644 index 0000000..61a7080 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/cs.json @@ -0,0 +1,2763 @@ +{ + "view": "3D", + "editor": "Editor", + "all_floors": "Všechna podlaží", + "outside_area": "Venku", + "outside_area_hint": "Všechna venkovní zařízení na jednom místě: na zahradě, mimo místnosti a to, co patří k exteriéru (například meteostanice na střeše).", + "device_outside": "Patří k venku", + "device_outside_hint": "Zařízení se nepočítá do místnosti pod ním (meteostanice na střeše) a je uvedeno v seznamu v panelu Venku.", + "no_building": "Chybí plán.", + "no_building_admin": "Chybí plán. Nakreslete první podlaží v editoru.", + "no_rooms_admin": "Podlaží existují, ale zatím tu není žádná místnost. Samotné zdi nestačí: v editoru nakreslete alespoň jednu místnost nástrojem „Obdélník“ nebo „Volný tvar“.", + "open_editor": "Otevřít editor", + "loading": "Načítání …", + "load_error": "Načítání selhalo", + "saving": "Ukládání …", + "saved": "Uloženo", + "save_error": "Uložení selhalo", + "save_failed_detail": "Uložení selhalo: {error}. Vaše změny zůstávají v tomto prohlížeči.", + "needs_restart": "Byla nainstalována nová verze NextFloor ({frontend}), ale Home Assistant stále běží na {version}. Restartujte Home Assistant – do té doby se uložení nemusí zdařit.", + "needs_reload": "Tato stránka stále zobrazuje NextFloor {frontend}, ale Home Assistant má již {backend}. Obnovte stránku; v aplikaci Companion: Nastavení → Aplikace Companion → Vymazat mezipaměť frontendu.", + "reload_page": "Obnovit", + "needs_restart_old": "Byla nainstalována nová verze NextFloor, ale Home Assistant stále běží na starší verzi. Restartujte Home Assistant – do té doby se uložení nezdaří.", + "draft_found": "Nalezeny neuložené změny z {time}.", + "draft_restore": "Obnovit a uložit", + "draft_discard": "Zahodit", + "walls_auto": "Vysoké zdi", + "walls_cut": "Průřez", + "walls_slope": "Šikmé", + "walls_slope_hint": "Zdi seříznuté šikmo: vpředu do poloviny výšky, vzadu na plnou výšku – jako domeček pro panenky; otáčí se s kamerou", + "walls_solid": "Plné", + "walls_solid_hint": "Plné zdi v jejich barvách místo skla (barvy: editor → nastavení, pro místnost v místnosti)", + "wall_paint_outside": "Barva vnějších zdí", + "wall_paint_inside": "Barva vnitřních zdí", + "wall_paint_room": "Barva vnitřních zdí (tato místnost)", + "wall_paint_hint": "Používá se v 3D zobrazení „Plné“.", + "wall_paint_default": "Výchozí", + "card_solid_walls": "Plné zdi (v jejich barvách)", + "reset_view": "Přehled", + "back": "Zpět", + "floor": "Podlaží", + "floors": "Podlaží", + "add_floor": "Přidat podlaží", + "floor_from_ha": "Podlaží z Home Assistant:", + "floor_empty": "Prázdné podlaží", + "level": "Podlaží {n}", + "ha_floor": "Podlaží v Home Assistant", + "floor_layer": "Vrstva (pro zobrazení a skrytí)", + "floor_power": "Elektroměr podlaží (výkon)", + "floor_power_hint": "Snímač výkonu pouze pro toto podlaží (podružný elektroměr, byt). Jeho hodnota je vidět na štítku podlaží a v zobrazení tohoto podlaží na kartě domu spolu s podílem na spotřebě domu.", + "floor_power_share": "{n} % domu", + "living_area": "Obytná plocha {living}", + "room_living": "Započítává se do obytné plochy", + "living_area_none": "Žádná obytná plocha · podlaha {floor}", + "living_area_low": "Obytná plocha {living} (podlaha {floor}, z toho {low} pod 2 m)", + "living_area_hint": "Počítáno podle německé Vyhlášky o obytných prostorech:podlaha uvnitř zdí, zcela od 2 m světlé výšky, z poloviny mezi 1 a 2 m (pod šikminami), vůbec pod 1 m. Orientační hodnota, nikoli měření.", + "living_area_floor": "Obytná plocha: {floor}", + "living_area_floor_house": "Obytná plocha podlaží: {floor} · celý dům: {house}", + "print_plan": "Tisk plánu / PDF", + "print_plan_hint": "Každé podlaží jako čistý plán s rozměry a plochami a tabulkou ploch – k tisku nebo uložení jako PDF v okně tisku.", + "print_title": "Plán", + "print_room": "Místnost", + "print_floor_area": "Plocha podlahy", + "print_living": "Obytná plocha", + "print_low": "pod 2 m", + "print_total": "Celkem", + "print_blocked": "Okno tisku bylo zablokováno – povolte vyskakovací okna pro Home Assistant.", + "check_open": "Zkontrolovat plán", + "note": "Poznámka", + "note_add": "Poznámka zde", + "note_text": "Text", + "note_placeholder": "např. „vyměnit filtr“ nebo „jistič 12“", + "note_due": "Termín", + "note_due_hint": "Od tohoto dne se špendlík zbarví oranžově.", + "note_is_due": "Tato poznámka je k vyřízení.", + "keys_title": "Klávesy editoru", + "keys_undo": "Zpět", + "keys_redo": "Znovu", + "keys_duplicate": "Duplikovat místnost", + "keys_delete": "Smazat výběr", + "keys_nudge": "Posunout výběr o krok mřížky", + "keys_nudge_10": "… o 10 cm", + "keys_nudge_1": "… o 1 cm", + "keys_rotate": "Otočit nábytek o 90° (Shift: zpět)", + "keys_lock": "Zamknout nebo odemknout nábytek, zařízení nebo část střechy", + "keys_close_shape": "Uzavřít libovolný tvar", + "keys_escape": "Zrušit, opustit nástroj, zrušit výběr", + "keys_straight": "Během kreslení: přímé čáry", + "keys_sheet": "Tato nápověda", + "tour_title": "První kroky", + "tour_1_title": "Nakreslete místnosti", + "tour_1": "Kreslete místnosti nástrojem „{rect}“ nebo „{free}“; zdi vznikají samy. Přiřaďte každé místnosti její oblast Home Assistant – NextFloor pak najde její zařízení. Pokud již oblasti máte, „{rooms}“ ve formuláři podlaží je vytvoří najednou.", + "tour_2_title": "Dveře a okna", + "tour_2": "„{opening}“ je umístí na zeď. Propojte jejich magnetický kontakt nebo roletu – v 3D se otevírají a zavírají společně s ním a otevřená okna dávají vědět.", + "tour_3_title": "Nábytek a zařízení", + "tour_3": "„{furniture}“ otevře knihovnu – nebo si postavte vlastní v 🛠️ dílně. Vyberte místnost a dole se zobrazí zařízení její oblasti připravená k umístění; lampy svítí barvou svého světla.", + "tour_4_title": "Prohlédněte a zkontrolujte", + "tour_4": "„{split}“ zobrazuje dům během kreslení; nahoře přepínáte na 3D zobrazení. „{check}“ vypíše, co ještě chybí – a ? vždy zobrazí klávesy.", + "tour_next": "Dále", + "tour_back": "Zpět", + "tour_done": "Jdeme na to", + "tour_skip": "Přeskočit", + "check_open_hint": "Zobrazuje, co chybí nebo co je špatně v plánu, s opravou jedním klepnutím.", + "check_title": "Kontrola plánu", + "check_all_good": "Vše v pořádku – nic nenalezeno.", + "check_hint": "Nalezeno {n} bodů. Modrá tlačítka mění plán (vrácení zpět funguje jako vždy), ostatní zobrazují místo.", + "check_room_no_area": "„{room}“ nemá oblast Home Assistant: její zařízení se nenacházejí.", + "check_room_no_area_named": "„{room}“ nemá oblast – volná oblast „{area}“ se jmenuje stejně.", + "check_areas_unplaced": "{n} oblastí tohoto podlaží ještě nemá místnost: {names}", + "check_devices_unplaced": "„{room}“: {n} zařízení oblasti ještě není v plánu.", + "check_rooms_overlap": "„{a}“ a „{b}“ se překrývají.", + "check_opening_off_wall": "Dveře nebo okno v „{room}“ nejsou na žádné zdi.", + "check_entity_missing": "{n} špendlíků ukazuje na entity, které Home Assistant již nezná ({ids}).", + "check_furniture_entity_missing": "Nábytek je propojen s {id} – tato entita již neexistuje.", + "check_battery_low": "Slabá baterie: {name} ({level} %)", + "battery_low_n": "Slabá baterie: {names}", + "check_standby": "{name} odebírá {w} W, ačkoliv je vypnutý – cca {cost} ročně.", + "check_fix_show": "Zobrazit", + "check_fix_set_area": "Přiřadit „{area}“", + "check_fix_add_rooms": "Přidat místnosti", + "check_fix_place": "Umístit {n}", + "check_fix_remove": "Odstranit {n}", + "floor_layer_hint": "Toto podlaží není podlažím, ale vrstvou – např. všechny stromy nebo dekorace. 3D zobrazení zobrazuje nahoře oko, které ji zobrazí nebo skryje na každém zařízení.", + "no_ha_floor": "– žádné –", + "area_rooms": "Přidat místnosti z oblastí HA ({n})", + "area_rooms_hint": "Přidá místnost (4 × 3 m) pro každou oblast tohoto podlaží – poté je přetáhněte na místo a upravte rohy", + "floor_name": "Název", + "elevation": "Výška umístění (m)", + "floor_shift": "Posunout podlaží (m)", + "floor_shift_apply": "Posunout", + "floor_shift_hint": "Posune všechny místnosti, nábytek, zařízení, venkovní plochy, volné zdi a obrázek pozadí tohoto podlaží o X a Z. Střešní roviny zůstávají.", + "height": "Výška stropu (m)", + "cut_height": "Výška řezu (m)", + "delete_floor": "Smazat podlaží", + "delete_floor_confirm": "Smazat podlaží „{name}“ se všemi místnostmi?", + "move_up": "Nahoru", + "move_down": "Dolů", + "default_floor": "Přízemí", + "new_floor": "Podlaží {n}", + "tool_select": "Vybrat", + "tool_rect": "Obdélník", + "tool_polygon": "Libovolný tvar", + "undo": "Zpět", + "redo": "Znovu", + "fit": "Zobrazit vše", + "room": "Místnost", + "rooms": "Místnosti", + "room_name": "Název", + "area": "Oblast", + "no_area": "Bez oblasti", + "sub_area_add": "+ Oblast v místnosti", + "sub_area_hint": "Část místnosti s vlastní oblastí v Home Assistant, ale bez zdí – čtenářský koutek, regál, kuchyňský kout. Její zařízení a snímače patří do této místnosti.", + "material": "Podlaha", + "x": "X (m)", + "z": "Y (m)", + "width": "Šířka (m)", + "depth": "Hloubka (m)", + "points": "Rohy", + "delete_point": "Smazat roh", + "duplicate": "Duplikovat", + "delete": "Smazat", + "new_room": "Místnost {n}", + "settings": "Nastavení", + "pendant_shape": "Tvar", + "pendant_shade": "Stínidlo", + "paint_colour": "Barva nátěru", + "pendant_globe": "Koule", + "pendant_cone": "Kužel", + "pendant_drum": "Buben", + "sofa_shape": "Tvar", + "sofa_straight": "Rovná", + "sofa_l": "Ve tvaru L (zrcadlově: druhá strana)", + "sofa_u": "Ve tvaru U", + "pkg_open": "Vybavit nábytkem …", + "pkg_hint": "Nábytek se umístí ke zdem místnosti; lampy se propojí se světly oblasti. Poté upravte jednotlivé prvky – Ctrl+Z vrátí vše zpět.", + "pkg_done": "Umístěno {n} prvků – Ctrl+Z vrátí zpět.", + "pkg_kitchen_row": "Lineární kuchyně", + "pkg_kitchen_row_desc": "Linka u zadní zdi s lednicí, troubou, dřezem, myčkou a varnou deskou, závěsná skříňka, jídelní stůl se závěsnou lampou", + "pkg_kitchen_l": "Kuchyně ve tvaru L", + "pkg_kitchen_l_desc": "Linky vzadu a vlevo, kuchyňský ostrůvek s barovými židlemi", + "pkg_bath": "Koupelna", + "pkg_bath_desc": "Umyvadlo, WC, vana, pračka, stropní bodové světlo", + "pkg_bedroom": "Ložnice", + "pkg_bedroom_desc": "Manželská postel se dvěma nočními stolky, skříň, komoda, stropní lampa", + "pkg_living": "Obývací pokoj", + "pkg_living_desc": "TV stolek, pohovka, konferenční stolek, koberec, křeslo, regál, stojací lampa, rostlina", + "pkg_dining": "Jídelna", + "pkg_dining_desc": "Stůl se čtyřmi židlemi, příborník, závěsná lampa", + "pkg_office": "Kancelář", + "pkg_office_desc": "Psací stůl s kancelářskou židlí, dva regály, stropní lampa", + "pkg_kids": "Dětský pokoj", + "pkg_kids_desc": "Jednolůžková postel, psací stůl, regál, koberec", + "pkg_hall": "Předsíň", + "pkg_hall_desc": "Věšák, dvě stropní bodová světla", + "spots_place": "Rozmístit bodová světla", + "spots_type": "Lampa", + "spots_cols": "Sloupce (vlevo–vpravo)", + "spots_rows": "Řady (vpředu–vzadu)", + "spots_add": "Rozmístit {n} lamp", + "spots_placed": "Rozmístěno {n} lamp.", + "spots_hint": "Všechny lampy následují vybrané světlo (např. bodovky na jednom stmívači). Poté lze každou posunout a propojit s jiným světlem jako jakýkoliv nábytek.", + "cancel": "Zrušit", + "backup": "Záloha", + "backup_history": "Body obnovení", + "share_view": "Sdílet zobrazení", + "share_view_hint": "Uloží dům jako malý soubor, který se otevře v jakémkoli prohlížeči bez Home Assistant (přes online demo NextFloor) – pro ukázku rodině nebo projektantovi. Bez zařízení a entit, jako šablona.", + "share_view_title": "Náš dům v NextFloor", + "share_view_needs_js": "Tato stránka vyžaduje JavaScript a připojení k internetu.", + "share_view_file": "pohled", + "share_view_done": "Pohled uložen – otevřete soubor v prohlížeči nebo jej předejte dál.", + "version_save": "Uložit tento stav …", + "version_save_hint": "Uchová plán pod názvem („před rekonstrukcí“). Pojmenované stavy zůstávají, i když automatické body zmizí.", + "version_name_prompt": "Název tohoto stavu (např. „před rekonstrukcí“):", + "version_saved": "Stav „{name}“ uložen.", + "version_compare": "Porovnat", + "version_delete_confirm": "Smazat „{name}“?", + "version_same": "Žádné rozdíly oproti plánu.", + "version_diff_n": "{n} rozdílů oproti současnému plánu:", + "diff_floor_added": "Podlaží „{name}“ přidáno", + "diff_floor_removed": "Podlaží „{name}“ odstraněno", + "diff_room_added": "Místnost „{name}“ přidána", + "diff_room_removed": "Místnost „{name}“ odstraněna", + "diff_room_renamed": "„{detail}“ se nyní jmenuje „{name}“", + "diff_room_reshaped": "„{name}“ změněno ({detail} m²)", + "diff_opening_added": "{name} přidáno ({detail})", + "diff_opening_removed": "{name} odstraněno ({detail})", + "diff_furniture_added": "{name} přidáno", + "diff_furniture_removed": "{name} odstraněno", + "diff_furniture_moved": "{name} posunuto nebo změněno", + "diff_device_added": "Zařízení {name} umístěno", + "diff_device_removed": "Zařízení {name} odstraněno", + "diff_device_moved": "Zařízení {name} posunuto", + "backup_none": "Zatím žádné. Během úprav se bod obnovení ukládá nejvýše každých 10 minut.", + "backup_summary": "{rooms} místností, {furniture} prvků", + "backup_restore": "Obnovit", + "backup_restore_confirm": "Obnovit stav z {time}? Současný stav bude zachován jako bod obnovení.", + "backup_restored": "Obnoveno.", + "backup_file": "Soubor", + "backup_export": "Exportovat", + "backup_export_share": "Sdílet jako šablonu", + "backup_export_share_hint": "Bez oblastí, zařízení, snímačů a obrázků – k předání ostatním.", + "backup_import": "Importovat …", + "backup_import_confirm": "Nahradit celý plán souborem? Současný stav bude zachován jako bod obnovení.", + "backup_import_error": "Soubor není plánem NextFloor ({error}).", + "backup_imported": "Nainstalováno.", + "backup_hint": "Obrázky pozadí nejsou součástí souboru.", + "backup_full": "Kompletní záloha", + "backup_full_export": "Uložit vše (plán, obrázky, balíčky)", + "backup_full_import": "Obnovit kompletní zálohu …", + "backup_full_hint": "Jeden soubor s plánem, všemi obrázky pozadí a obrazovek a nainstalovanými balíčky. Při obnovení je každý balíček znovu zkontrolován; licenční klíč není zahrnut.", + "backup_full_confirm": "Nahradit plán, obrázky a balíčky zálohou? Současný stav zůstává jako bod obnovení.", + "backup_full_not_backup": "Toto není kompletní záloha NextFloor.", + "backup_full_restored": "Záloha obnovena: {packs} balíčků, {pictures} obrázků.", + "backup_full_skipped": "Přeskočeno (nečitelné): {packs}.", + "export_name_full": "kompletní", + "device_confirm": "Ptát se před přepnutím", + "device_confirm_hint": "Klepnutí v 3D, rychlé nabídce a panelu místnosti se nejprve zeptá. Dvojité klepnutí na místnost toto zařízení vyloučí.", + "cover_confirm_hint": "Otevírání, zavírání a pozice se nejprve ptají v rychlé nabídce a panelu místnosti, a posunutí po značce již nepohybuje roletou (otáčí pohled). Stop se nikdy neptá.", + "blind_kind": "Druh stínění", + "blind_roller": "Venkovní roleta", + "blind_venetian": "Fasádní žaluzie s lamelami", + "blind_inside": "Vnitřní roleta", + "cover2_entity": "Druhá roleta (pravá polovina)", + "cover_my": "Oblíbená pozice „My“ (%, 0 = žádná)", + "cover_my_go": "Do oblíbené pozice ({p} %)", + "blind_hint": "Fasádní žaluzie otáčí lamely v 3D podle naklonění rolety; vnitřní roleta visí za sklem. Široké okno může mít druhou roletu pro pravou polovinu. Oblíbená pozice se zobrazuje jako „My“ v rychlé nabídce: roleta s pozicemi jede tam, motor Somfy RTS bez zpětné vazby jede Stopem do vlastní pozice My.", + "confirm_switch": "Opravdu přepnout {name}?", + "lock_confirm_unlock": "Opravdu odemknout {name}?", + "gang_switch_one": "Vypínače", + "furn_cover_entity": "Pohybuje se s", + "furn_cover_hint": "Závěs, zástěna, markýza nebo brána sleduje tuto entitu stínění (roleta, závěs, markýza, brána) a pohybuje se s ní. Klepnutí otevře její nabídku (nahoru, stop, dolů).", + "furn_cover_inverted": "Obrátit směr", + "furn_cover_inverted_hint": "Pro markýzu nebo závěs, který se v plánu pohybuje opačně než ve skutečnosti: vysunutý se zobrazí jako zasunutý a naopak.", + "gang_switch": "Tlačítko {n} přepíná", + "gang_socket_one": "Zásuvka napájena přes", + "gang_socket": "Zásuvka {n} napájena přes", + "gang_switch_hint": "Tlačítko svítí, když je jeho světlo zapnuté (v jeho barvě). Klepnutí na něj jej přepne; při více tlačítkách se malá nabídka zeptá které. Stejná entita může být na více tlačítkách.", + "gang_socket_hint": "Zásuvka svítí zeleně, když je její vypínač zapnutý – jasněji, čím více odebírá. Klepnutí ji přepne; při více zásuvkách se malá nabídka zeptá která.", + "lock_confirm_lock": "Zamknout {name}?", + "opening_lock": "Chytrý zámek", + "opening_lock_hint": "Klepnutí na dveře je zamkne nebo odemkne (vždy se nejprve zeptá). Když jsou odemčené, jejich hrana svítí.", + "split_handle_hint": "Přetažení: šířka plánu a 3D zobrazení", + "wall_exterior": "Vnější zeď (m)", + "wall_interior": "Vnitřní zeď (m)", + "grid": "Mřížka (m)", + "units": "Zobrazovat délky v", + "units_metric": "Metrech", + "units_imperial": "Stopách a palcích", + "units_hint": "Jak délky a plochy vypadají v plánu, formulářích a pohledu na zeď. Zadávání zůstává v metrech.", + "background": "Šablona (obrázek půdorysu)", + "background_upload": "Vybrat obrázek …", + "background_width": "Šířka v plánu (m)", + "background_opacity": "Krytí", + "background_rotation": "Otočení (°)", + "background_edit": "Posunout, změnit měřítko a otočit", + "background_edit_done": "Hotovo", + "background_edit_hint": "Když je režim zapnutý: přetažením obrázku jej posunete, úchyt v pravém dolním rohu mění měřítko. Nejprve upravte měřítko, pak otočte.", + "background_remove": "Odstranit šablonu", + "hint_select": "Klepněte na místnost pro její výběr · přetáhněte rohy · „+“ na hraně vloží roh · šipky posouvají · Del smaže · Ctrl+Z", + "hint_rect": "Přetáhněte pro nakreslení obdélníku", + "hint_polygon": "Vkládejte rohy · klepněte na první roh nebo stiskněte Enter pro uzavření · Esc zruší", + "hint_empty": "Nejprve přidejte podlaží.", + "area_m2": "{a} m²", + "overlap_warning": "Místnosti se překrývají – zdi jsou tam neúplné.", + "read_only": "Pouze správci mohou upravovat plán.", + "side_failed": "Nepodařilo se zobrazit tento formulář ({error}). Plán stále funguje. Nahlaste tento text v hlášení na GitHubu.", + "mat_wood": "Dřevo", + "mat_oak": "Dub", + "mat_tiles": "Dlažba", + "mat_carpet": "Koberec", + "mat_stone": "Kámen", + "mat_concrete": "Beton", + "card_name": "NextFloor", + "card_description": "Váš dům v 3D (neon).", + "stats": "{calls} volání kreslení · {tris} trojúhelníků", + "stats_fps": "{fps} fps (nejpomalejší snímek {ms} ms)", + "stats_idle": "V klidu (0 fps)", + "stats_busy_floors": "podlaží", + "stats_busy_openings": "dveře/okna", + "stats_busy_flash": "záblesk", + "stats_busy_roof": "střecha", + "stats_busy_flow": "tok energie", + "stats_busy_effect": "barevný efekt", + "stats_busy_robot": "robot", + "stats_busy_orbit": "otáčení kamery", + "stats_busy_tint": "odstín místnosti", + "stats_low": "úroveň tablet, faktor pixelů {r}", + "stats_full": "úroveň plná, faktor pixelů {r}", + "floors_apart": "Oddělený", + "floors_stacked": "Složený", + "roof_keep": "Střecha zůstává", + "roof_keep_hint": "Střecha zůstává na domě při přiblížení místo toho, aby se vznášela a mizela", + "floor_rooms_one": "1 místnost", + "floor_rooms": "{n} místností", + "quality": "Kvalita", + "quality_auto": "Auto", + "quality_low": "Tablet", + "quality_high": "Vysoká", + "state_on": "Zap.", + "state_off": "Vyp.", + "state_open": "Otevřeno", + "state_closed": "Zavřeno", + "state_opening": "Otevírání", + "state_closing": "Zavírání", + "state_playing": "Přehrávání", + "state_paused": "Pauza", + "state_idle": "Nečinný", + "state_locked": "Zamčeno", + "state_unlocked": "Odemčeno", + "state_detected": "Zjištěno", + "state_clear": "Čisto", + "state_unavailable": "Nedostupné", + "state_heat": "Topení", + "state_cool": "Chlazení", + "state_auto": "Auto", + "state_heat_cool": "Topení/Chlazení", + "state_dry": "Vysoušení", + "state_fan_only": "Ventilátor", + "devices": "Zařízení", + "devices_none_area": "Propojte místnost s oblastí a její zařízení se zobrazí zde.", + "devices_none": "Oblast nemá odpovídající zařízení.", + "devices_place_all_n": "Umístit všech {n} …", + "devices_place_all_confirm": "Umístit ihned {n} zařízení v místnosti? (Ctrl+Z nebo „Zpět“ je odstraní všechny v jednom kroku.)", + "devices_src_area": "Tato oblast", + "devices_src_other": "Ostatní oblasti", + "devices_src_none": "Bez oblasti", + "panel_hide": "Skrýt v panelu místnosti", + "panel_unhide": "Znovu zobrazit v panelu místnosti", + "panel_state_hide": "Skrýt stav v panelu místnosti (např. stínění, které hlásí pouze \"unknown\")", + "panel_state_show": "Znovu zobrazit stav v panelu místnosti", + "devices_place": "Umístit", + "devices_remove": "Odstranit", + "devices_hint": "Umístěná zařízení se zobrazují v 3D. Přetáhněte je v plánu pro jejich posun.", + "panel_lights": "Světla", + "panel_covers": "Stínění", + "panel_climate": "Vytápění", + "panel_media": "Média", + "panel_switches": "Vypínače", + "panel_sensors": "Snímače", + "panel_scenes": "Scény a skripty", + "panel_announce": "📢 Oznámení", + "announce_placeholder": "Vlastní zpráva …", + "announce_send": "Říct", + "announce_sent": "Řečeno: „{message}“", + "announce_failed": "Oznámení selhalo: {error}", + "announce_phrase_1": "Oběd je hotový!", + "announce_phrase_2": "Čas jít spát!", + "announce_phrase_3": "Pojďte dolů, prosím!", + "announce_phrase_4": "Za chvíli odcházíme!", + "announce_phrase_5": "Pes musí jít ven!", + "state_recording": "Nahrávání", + "state_streaming": "Vysílání", + "panel_all_off": "Vše vyp.", + "readable": "Čitelně", + "readable_hint": "Silnější kontrast a větší text – pro nástěnné tablety a kohokoli, komu se tak lépe čte.", + "plain": "Jen půdorys", + "plain_hint": "Zobrazí jen zdi, dveře, okna a schody, bez nábytku. Zařízení a jejich značky zůstanou.", + "right_back": "Pravý klik = zpět", + "right_back_hint": "Krátké kliknutí pravým tlačítkem v 3D pohledu vrátí o krok zpět: z místnosti na patro, z patra k domu (jako dvojité klepnutí na prázdné místo). Tažení pravým tlačítkem stále posouvá pohled.", + "stl": "3D tisk (STL)", + "stl_hint": "Uloží dům jako soubor STL (zdi, podlahy, nábytek a venkovní plochy všech pater) pro 3D tisk v měřítku 1:100 (metr je 10 mm). Okna, světla a střecha v něm nejsou; slicer soubor v případě potřeby opraví.", + "card_plain": "Jen půdorys", + "card_rooms": "Jen tyto místnosti", + "card_rooms_hint": "Karta zobrazí jen zaškrtnuté místnosti s nábytkem, zařízeními, dveřmi a okny (například pro tablet v kuchyni). Nic zaškrtnuto: celý plán.", + "card_templates": "Šablony karty", + "card_templates_hint": "Nastavte kartu na nástěnce jednou tady (s vlastním nastavením karty) a na každém tabletu uveďte jen její název: `template: kitchen_tablet`. Změny se projeví na všech kartách s touto šablonou; co je napsáno na samotné kartě, má přednost před šablonou.", + "template_name": "Nová šablona (název)", + "template_add": "Vytvořit šablonu", + "template_reload": "Znovu načíst obrazovky s touto šablonou", + "template_reload_all": "Znovu načíst všechny obrazovky", + "template_use": "Na kartě nástěnky: `template: {name}`", + "card_template": "Šablona karty", + "card_template_none": "žádná (jen tato karta)", + "card_readable": "Čitelně", + "all_off_n": "Vypnout vše ({n})", + "all_off_hint": "Vypne světla, vypínače, ventilátory a média v místnosti; po dobu deseti sekund to lze vrátit zpět.", + "all_off_done": "Vše vypnuto.", + "all_off_undo": "Zpět", + "all_off_floor": "Vypnout vše na {floor} ({n} zařízení), možnost vrácení po dobu deseti sekund", + "mood_save": "Uložit náladu", + "mood_save_hint": "Uloží, jak nyní svítí lampy v místnosti, jako náladu – klepnutí ji později obnoví, „→“ ji přenese do jiné místnosti.", + "mood_new": "Nálada", + "mood_set": "Nastavit tuto náladu", + "mood_carry": "Přenést do jiné místnosti", + "panel_all_on": "Vše zap.", + "view_options": "Zobrazení: kvalita, vzhled, značky, FPS", + "panel_all_open": "Vše nahoru", + "panel_all_close": "Vše dolů", + "central": "Centrální: všechna světla, rolety a oblíbené", + "central_house": "Celý dům", + "central_lights": "Světla", + "central_covers": "Rolety", + "central_on": "Zap.", + "central_off": "Vyp.", + "central_open": "Nahoru", + "central_close": "Dolů", + "central_sure": "Jste si jisti?", + "central_favorites": "Oblíbené", + "central_no_favorites": "Žádné oblíbené. Nastavte scény, skripty a vypínače v editoru v sekci \"Oblíbené\".", + "card_central": "Hvězdička s centrální nabídkou", + "card_central_hint": "Všechna světla a rolety podlaží nebo domu a oblíbené položky z editoru.", + "favorites": "Oblíbené", + "favorites_hint": "Scény, skripty, automatizace, tlačítka a vypínače pro centrální nabídku (hvězdička) 3D zobrazení – párty, simulace přítomnosti, stínění, zalévání.", + "favorites_add": "Přidat oblíbené", + "favorite_floor": "Na kterém podlaží se tento oblíbený prvek zobrazí", + "favorite_all_floors": "Všechna podlaží", + "outside_hidden": "Venku: skrýt zařízení", + "outside_hidden_hint": "Zařízení, která panel Venku nemá zobrazovat (zůstávají v plánu).", + "outside_hidden_add": "Skrýt zařízení", + "room_facts": "Panel místnosti: zobrazené údaje", + "room_fact_sun": "Hodiny slunce", + "room_fact_comfort": "Komfort", + "room_fact_air": "Upozornění na větrání", + "room_fact_circuits": "Okruhy", + "background_handles_hint": "Obrázek má nyní úchyty jako nábytek: přetažení jej posouvá, pravý dolní roh mění měřítko, kulatý úchyt nahoře otáčí (Shift pro kroky po 15°). Když vyhovuje, klepněte na \"Hotovo\" – pak zůstane na místě.", + "background_fixed_hint": "Obrázek zůstane na místě, můžete na něm kreslit. Chcete-li jej upravit, klepněte na \"Posunout, změnit měřítko a otočit\".", + "bg_level": "Vyrovnat", + "bg_level_cancel": "Zrušit vyrovnání", + "bg_level_first": "Klepněte na začátek zdi na obrázku, která má běžet rovně (horizontálně nebo vertikálně).", + "bg_level_second": "Nyní klepněte na konec této zdi – obrázek se otočí, aby odpovídal.", + "bg_ruler": "Měřítko pravítkem", + "bg_ruler_cancel": "Zrušit pravítko", + "bg_ruler_first": "Klepněte na začátek úseku o známé délce na obrázku – např. kótované zdi.", + "bg_ruler_second": "Nyní klepněte na konec úseku.", + "bg_ruler_length_hint": "Naměřeno v plánu: {m} m. Zadejte skutečnou délku a obrázek se přeškáluje.", + "bg_ruler_length": "Skutečná délka (m)", + "bg_ruler_apply": "Použít měřítko", + "thumbs_fold": "Složit obrázky podlaží do tlačítek", + "thumbs_show": "Znovu zobrazit obrázky podlaží", + "room_start_view": "Pohled jako start této místnosti", + "room_start_view_hint": "Po klepnutí na místnost v 3D kamera letí přesně do pohledu, který nyní zobrazuje panel 3D vpravo – úhel, přiblížení a záběr. Nejprve zapněte 3D vedle, otočte a přibližte místnost, pak klepněte.", + "room_start_view_reset": "Odstranit startovací pohled místnosti (opět shora)", + "room_start_view_need_pane": "Nejprve zapněte \"3D vedle\", a poté otočte a přibližte místnost tak, jak se má otevírat.", + "floor_start_view": "Pohled jako start tohoto podlaží", + "floor_start_view_hint": "Toto podlaží se otevírá v 3D tak, jak nyní stojí panel 3D vpravo – např. přízemí zepředu a podlaží zezadu. Nejprve zapněte 3D vedle, otočte ho, pak klepněte.", + "floor_start_view_reset": "Odstranit startovací pohled podlaží (opět jako dům)", + "floor_start_view_need_pane": "Nejprve zapněte \"3D vedle\" a otočte podlaží tak, jak se má otevírat.", + "ambilight": "Záře za TV (%)", + "ambilight_hint": "Jak silně svítí za televizorem během přehrávání. 0 ji vypne (např. máte-li LED pásky na TV), 100 je běžná intenzita.", + "sound_rings": "Zvukové kruhy (%)", + "sound_rings_hint": "Jak velké jsou kruhy kolem reproduktoru, když hraje. 0 je vypne, obraz a záře zůstanou; 100 je běžná velikost. Velikost se řídí i hlasitostí reproduktoru: tišeji znamená menší.", + "glow_scale": "Záře v 3D (%)", + "light_effects": "Animace efektů v 3D", + "light_effects_hint": "Přiřazujte pouze přesné názvy efektů z HA. Nepřiřazené efekty si zachovávají statickou barvu HA. Nic nemění v Home Assistant.", + "light_effects_enabled": "Povolit animace pro tuto lampu", + "light_effect_unmapped": "Nepřiřazeno (statický)", + "light_effect_add": "Přidat přesný název efektu", + "light_effect_name_limit": "Přesný název efektu musí mít 1 až 255 znaků. Nebude zkrácen.", + "light_effect_count_limit": "Nejvýše 100 přiřazení. Nejprve odstraňte stávající.", + "light_effect_exists": "Tento název efektu je již přiřazen. Stávající přiřazení bude zachováno.", + "light_animation_none": "Statický", + "light_animation_rainbow": "Duhový (nahrazuje barvu)", + "light_animation_pulse": "Puls (intenzita)", + "light_animation_flicker": "Blikání (intenzita)", + "glow_scale_hint": "Jak silně lampa svítí v 3D: pod 100 % ztlumí jasné LED pásky, aby se místnost nepřesvětlovala; nad 100 % způsobí, že slabá lampa svítí silněji. Nic nepředělává v Home Assistant.", + "vehicle_to_spot": "Změnit na parkovací místo", + "vehicle_to_spot_hint": "Vozidlo jako běžný nábytek stojí stále na místě. Jako parkovací místo se zobrazí pouze tehdy, když snímač hlásí auto, a tam se propojí zařízení auta (nabíjení, dojezd, zámek, klimatizace).", + "as_furniture": "Zobrazit jako nábytek", + "as_furniture_hint": "Nahradí značku nábytkem na stejném místě, propojeným s tímto zařízením – reproduktor pro přehrávač, lampa pro světlo. Ctrl+Z vrátí zpět.", + "as_furniture_pick": "Vybrat nábytek …", + "as_device": "Zpět na značku zařízení", + "as_device_hint": "Nahradí nábytek běžnou značkou jeho zařízení na stejném místě.", + "presets": "Stanice a playlisty (Zvuk)", + "presets_hint": "Zobrazované v rychlé nabídce každého reproduktoru pod \"Přehrát\", vedle zdrojů přehrávače. Pro Echo (Alexa Media Player): zadejte SPOTIFY, AMAZON_MUSIC nebo TUNEIN, a jako obsah to, co byste řekli (\"Rock Antenne\"). Pro Sonos, Music Assistant a ostatní: zadejte music nebo url s adresou streamu nebo URI.", + "preset_type": "Typ", + "preset_type_hint": "media_content_type z play_media, např. music, url, playlist, SPOTIFY, AMAZON_MUSIC, TUNEIN", + "preset_content": "Obsah", + "preset_content_hint": "media_content_id: URL streamu, URI (spotify:playlist:…) nebo, pro Alexu, vyhledávací fráze", + "preset_speakers": "Pouze na těchto reproduktorech (žádný = na všech)", + "media_play": "Přehrát", + "media_pause": "Pauza", + "media_previous": "Předchozí", + "media_next": "Následující", + "media_volume": "Hlasitost", + "media_sources": "Zdroje", + "preset_add": "Stanice nebo playlist", + "own_buttons": "Vlastní tlačítka", + "own_buttons_hint": "Zobrazované v centrální nabídce (hvězdička) pod oblíbenými: otevřete cestu řídicího panelu, zobrazte podrobnosti entity, zavolejte službu nebo otevřete popup browser_mod s vlastní kartou.", + "own_alerts": "Vlastní varování", + "circuits": "Rozvaděč", + "circuits_hint": "Okruhy s místnostmi, které napájejí. Panel místnosti je vypisuje a vyhledávač nachází („F12“).", + "circuit_name": "Název", + "circuit_new": "Nový okruh", + "circuit_add": "Přidat okruh", + "circuit_add_room": "Přidat místnost", + "own_alerts_hint": "Řádek na liště varování 3D zobrazení, když je entita v daném stavu – „Prázdná nádržka“ robota, „Myčka hotova“. Více stavů oddělte čárkou; pro čísla <20 nebo >80.", + "own_alert_entity": "Když …", + "own_alert_state": "… je ve stavu (prázdné = zapnuto)", + "own_alert_text": "… pak toto varování", + "own_alert_color": "Barva", + "own_alert_tap": "Klepnutí", + "own_alert_tap_info": "otevře podrobnosti", + "own_alert_tap_toggle": "přepne entitu", + "own_alert_tap_room": "přejde do místnosti", + "own_alert_house": "Celý dům", + "own_alert_new": "Nové varování", + "own_alert_add": "Přidat varování", + "today": "Dnes", + "today_none": "Dnes není nic naplánováno.", + "today_calendars": "Kalendáře pro „Dnes“", + "today_calendars_hint": "Události z těchto kalendářů se zobrazují v pravém horním rohu 3D zobrazení na kartě „Dnes“, společně s popelnicemi vyváženými dnes nebo zítra. Klepnutí na název kartu složí.", + "own_button_state": "Svítí, když … je zapnuté (volitelné)", + "own_button_label": "Popisek", + "own_button_action": "Akce", + "own_button_new": "Nové tlačítko", + "own_button_add": "Vlastní tlačítko", + "own_action_navigate": "Otevřít cestu", + "own_action_more_info": "Podrobnosti entity", + "own_action_service": "Zavolat službu", + "own_action_fire_dom_event": "fire-dom-event (browser_mod)", + "own_target_navigate": "Cesta", + "own_target_more_info": "Entita", + "own_target_service": "Služba (doména.služba)", + "own_data": "Data (JSON)", + "own_data_hint": "Pro službu její data, pro fire-dom-event obsah události, např. {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}.", + "own_data_bad": "Toto není platný objekt JSON.", + "panel_no_area": "Tato místnost není propojena s oblastí. Můžete ji propojit v editoru.", + "panel_empty": "Žádné zařízení této místnosti není v plánu. V editoru umístěte zařízení nebo je vyberte pro panel místnosti pomocí ☆.", + "close": "Zavřít", + "panel_fold": "Složit (místnost zůstává v zobrazení)", + "panel_unfold": "Znovu otevřít", + "brightness": "Jas", + "color_temp": "Teplota chromatičnosti", + "color": "Barva", + "position": "Pozice", + "cover_open": "Otevřít", + "cover_stop": "Stop", + "cover_tilt": "Lamely", + "cover_tilt_open": "Lamely otevřené", + "cover_tilt_close": "Lamely zavřené", + "cover_close": "Zavřít", + "target_temp": "Cíl", + "current_temp": "Aktuálně", + "temp_down": "Chladněji", + "temp_up": "Tepleji", + "volume": "Hlasitost", + "play_pause": "Přehrát/pauza", + "previous": "Předchozí", + "next": "Následující", + "run": "Spustit", + "details": "Podrobnosti", + "hold_hint": "Klepnutí přepne · dlouhé podržení otevře podrobnosti", + "tool_opening": "Dveře a okna", + "tool_furniture": "Nábytek", + "qm_off": "Vyp.", + "find": "Hledat", + "find_placeholder": "Kde je …? Zařízení nebo místnost", + "find_none": "Nic nenalezeno", + "swipe_off": "Vyp.", + "panel_pin": "Zobrazit v panelu místnosti", + "panel_unpin": "Nezobrazovat v panelu místnosti", + "devices_panel_hint": "Panel místnosti zobrazuje zařízení z plánu. ☆ přidá zařízení do panelu bez jeho umístění.", + "card_section_view": "Zobrazení", + "card_size": "Velikost", + "card_size_fixed": "Pevná výška", + "card_size_fill": "Vyplnit obrazovku", + "card_fill_hint": "Funguje nejlépe v zobrazení řídicího panelu typu „Panel (jediná karta)“ – karta pak zabírá veškeré místo.", + "card_controls": "Přepínače v kartě", + "card_floor_thumbs": "Podlaží jako náhledy", + "card_floor_thumbs_hint": "Malé obrázky podlaží na straně – klepněte na jeden pro přepnutí", + "card_floor_thumbs_hint_start": "Vybrané podlaží je pak tím, od kterého karta začíná – obrázky na straně přepínají na ostatní", + "card_room_names": "Zobrazit názvy místností", + "card_section_kiosk": "Nástěnný tablet (kiosk)", + "card_section_features": "Funkce", + "card_weather_plan": "jako v plánu", + "card_pro_hint": "Stopa pohybu a stěna kamer patří ke kamerám: stopa zobrazuje poslední půlhodinu, stěna všechny kamery z plánu.", + "card_idle_return": "Návrat do výchozího zobrazení po", + "card_idle_off": "Nikdy", + "card_idle_min": "{n} min bez dotyku", + "card_idle_hint": "Po čekání karta zavře místnost a opět zobrazí výchozí zobrazení.", + "card_night": "Noční stmívání", + "card_night_off": "Vyp.", + "card_night_sun": "Podle slunce", + "card_night_time": "Časový interval", + "card_night_range": "Časový interval (např. 22:00-06:00)", + "card_idle_orbit": "Otáčení kamery jako šetřič", + "card_idle_orbit_hint": "Po návratu se pohled pomalu otáčí, dokud se někdo nedotkne tabletu", + "card_dashboard": "Tlačítko na řídicí panel (cesta)", + "card_dashboard_label": "Popisek tlačítka", + "card_dashboard_hint": "Tlačítko v pravém horním rohu karty otevře řídicí panel nebo zobrazení na této cestě, např. /lovelace/home nebo /dashboard-house/0. Bez popisku zobrazuje ⌂.", + "card_alerts": "Zobrazovat varování", + "card_alerts_hint": "Kouř, plyn, CO, voda, alarm a otevřená okna při dešti: místnost pulzuje, nahoře se zobrazí zpráva", + "card_alert_jump": "Přejít do místnosti nového varování", + "card_alert_jump_hint": "Pohled se sám přepne na podlaží a místnost varování", + "card_scenes": "Tlačítka scén v místnosti", + "card_scenes_hint": "Scény a skripty oblasti jako tlačítka pod 3D zobrazením, když je vybrána místnost", + "card_sensor_bar": "Vlastní snímače nahoře", + "card_sensor_bar_hint": "Snímače vybrané v editoru (Nastavení) v levém horním rohu karty", + "card_central_open": "Nabídka hvězdičky otevřená a velká", + "card_central_open_hint": "Oblíbené a vlastní tlačítka jsou od začátku otevřená, větší", + "card_keep_camera": "Zachovat kameru při změně podlaží", + "card_keep_camera_hint": "Stejná strana, výška a vzdálenost na každém podlaží", + "card_today": "Karta „Dnes“", + "card_today_hint": "Dnešní události a popelnice k vyvezení, v pravém horním rohu", + "card_announcements": "Oznámení", + "card_announcements_hint": "Oznámení (akce „NextFloor: Oznámení“) se zobrazují velká na kartě, s gongem, a jsou předčítána", + "weather_short": "Počasí", + "weather_entity": "Entita počasí", + "weather_effects": "Efekty počasí v 3D", + "card_weather_density": "Množství deště a sněhu", + "card_weather_density_hint": "Méně kapek a vloček, než udává počasí; mraky, mlha a blesky zůstávají", + "rain_warning": "Varování: okno otevřené při dešti", + "sun_patches": "Slunce a stíny", + "sun_patches_hint": "Při nastaveném severu dopadá sluneční světlo z sun.sun přes okna jasnými skvrnami na podlahu a dům vrhá stín na pozemek. Odznačte, aby podlaha a pozemek zůstaly bez skvrn slunce a stínů.", + "sun_arc": "Sluneční oblouk a kompas", + "sun_arc_hint": "Nakreslí dnešní dráhu slunce jako oblouk nad pozemkem, s prstencem a světovými stranami na zemi (sever červeně). Potřebuje polohu domova v Home Assistant.", + "weather_effect_rain": "Déšť", + "weather_effect_snow": "Sníh", + "weather_effect_fog": "Mlha (zašedí scénu)", + "weather_effect_clouds": "Mraky ztmavují oblohu a slunce", + "weather_effect_lightning": "Blesky během bouřky", + "weather_effect_sky": "Slunce a měsíc na obloze", + "weather_entity_hint": "Která entita počasí řídí oblohu kolem domu. Automaticky použije první nalezenou.", + "weather_hint": "Počasí u domu: déšť a sníh padají s reálným větrem, mraky se posouvají nad pozemkem se stíny, blesky, mlha, slunce a měsíc", + "card_weather": "Venkovní počasí", + "card_weather_hint": "Déšť, sníh, kroupy, mraky se stíny, blesky a mlha z první entity počasí (weather_entity vybírá jinou); méně částic na úrovni tablet", + "alerts": "Varování", + "alert_smoke": "Kouř: {name}", + "alert_gas": "Plyn: {name}", + "alert_co": "Oxid uhelnatý: {name}", + "alert_water": "Voda: {name}", + "alert_alarm": "Alarm spuštěn", + "alert_alarm_by": "Alarm vyvolán čím: {cause}", + "alert_alarm_pending": "Alarm čeká", + "alert_window_rain": "Okno otevřené při dešti: {name}", + "alert_power_outage": "Výpadek proudu: {name}", + "alert_contact_lost": "Snímač neodpovídá: {name}", + "rain_sensor": "Dešťový snímač (vlastní meteostanice)", + "outage_sensor": "Snímač výpadku proudu", + "outage_hint": "Binární snímač třídy power, který je vypnutý, jiný binární snímač, který je zapnutý, stav jako \"off_grid\" nebo \"backup\" nebo napětí pod 50 V vyvolají varování pro celý dům.", + "contact_warning": "Varovat, když je snímač dveří nebo okna nedostupný", + "contact_warning_hint": "Když je snímač nedostupný déle než 10 minut (vybitá baterie, mimo dosah), okno v 3D vypadá jako zavřené, ačkoliv to nikdo neví. Zpráva pak nahlásí snímač. Restart Home Assistant nevaruje.", + "night_lock_warning": "Varovat v noci, když dveře nejsou zamčené", + "night_lock_warning_hint": "Mezi 22 a 6 hodinou zpráva vypíše zámky z plánu, které nejsou zamčené.", + "alert_unlocked_night": "Nezamčeno: {name}", + "motion_markers_active": "Zobrazovat snímače pohybu pouze tehdy, když něco zjistí", + "motion_markers_active_hint": "Platí pro snímače pohybu, obsazenosti a přítomnosti. Snímač, jehož symbol má být vždy viditelný, zůstává viditelný.", + "room_double_tap": "Dvojité klepnutí na pokoj", + "room_double_tap_hint": "Dvojité klepnutí na pokoj vypne jeho světla, když některé svítí, jinak zapne všechna. Zařízení, která se nejprve ptají, jsou vždy přeskočena.", + "room_double_tap_area": "Lampy v plánu a všechna světla oblasti", + "room_double_tap_plan": "Pouze lampy v plánu", + "room_double_tap_off": "Nic nepřepínat", + "card_room_double_tap_auto": "Jak je nastaveno v plánu", + "status_entities": "Vlastní snímače nahoře v 3D zobrazení", + "status_add": "Přidat snímač", + "status_entities_hint": "Například venkovní teplota, alarm nebo kvalita vzduchu: zobrazují se v levém horním rohu s názvem a hodnotou, a to i v otevřené místnosti. Klepnutí otevře podrobnosti. Až 12.", + "announce_tts": "Převod textu na řeč pro oznámení", + "announce_phrases": "Věty oznámení (jedna na řádek)", + "announce_phrases_hint": "Prázdné: věty přiložené k NextFloor. Oznámení jsou také akcí „NextFloor: Oznámení“ pro automatizace – na reproduktorech místností a na každé otevřené obrazovce NextFloor.", + "opening_rain_warning": "Varovat, když prší", + "opening_light_well": "Světlík vpředu", + "sill_boards": "Parapet a podokeník", + "sill_boards_auto": "Automaticky", + "sill_boards_none": "Žádný", + "sill_boards_inside": "Pouze uvnitř", + "sill_boards_outside": "Pouze venku", + "room_names_short": "Názvy místností", + "floor_stack_short_dim": "Ztlumené", + "floor_stack_short_stacked": "Složené", + "floor_stack_short_single": "Samostatně", + "size_short_w": "Š", + "size_short_d": "H", + "size_short_h": "V", + "import_error_not_json": "Soubor není JSON.", + "import_error_not_plan": "Soubor není plánem NextFloor.", + "import_other_hint": "Ze Sweet Home 3D: importujte zde soubor .sh3d. Přenášejí se podlaží, místnosti, dveře, okna a volné zdi, nábytek ne.", + "import_sh3d_found": "Sweet Home 3D: {floors} podlaží, {rooms} místností, {openings} dveří a oken, {walls} volných zdí ({furniture} kusů nábytku nepřenášeno).", + "import_dxf_found": "DXF: {rooms} místností (uzavřené křivky) a {walls} volných zdí (čáry) na jednom podlaží.", + "import_ifc_found": "V souboru IFC: {floors} podlaží a {rooms} místností (zdi NextFloor kreslí z místností).", + "import_roomplan_found": "Sken místnosti (RoomPlan): {rooms} místností, {openings} dveří a oken; {skipped} objektů nebylo převzato (nábytek umístíte sami).", + "import_error_roomplan_empty": "Sken neobsahuje žádné zdi.", + "import_error_ifc_empty": "Soubor IFC neobsahuje prostory (IfcSpace) s obrysem.", + "import_error_dxf_empty": "Soubor DXF neobsahuje čáry ani křivky.", + "import_error_sh3d": "Toto není čitelný soubor Sweet Home 3D (vyžaduje Sweet Home 3D 5.3 nebo novější).", + "import_error_sh3d_empty": "Soubor Sweet Home 3D nemá místnosti ani zdi.", + "export_name_template": "šablona", + "export_name_backup": "záloha", + "card_floor_stack": "Podlaží nižší", + "floor_stack_dim": "Ztlumené", + "floor_stack_stacked": "Složené (dům do tohoto místa)", + "floor_stack_single": "Skryté (pouze toto podlaží)", + "card_control_walls": "Vysoké zdi/průřez", + "card_control_floors": "Rozsunutá podlaží", + "card_control_temperature": "Teplota", + "card_control_humidity": "Vlhkost", + "card_control_co2": "CO₂", + "card_controls_hint": "Vysoké zdi/průřez, rozsunutá podlaží a teplota, vlhkost, CO₂ pro přepínání", + "controls_hide": "Skrýt ovládání – zůstane pouze 3D zobrazení", + "nav_wrap": "Zalamovat lištu: všechna podlaží a místnosti ve více řádcích", + "bars_fold": "Složit přepínače", + "bars_unfold": "Přepínače", + "nav_row": "Lišta v jednom řádku (posouvá se do stran)", + "controls_show": "Znovu zobrazit ovládání", + "card_controls_hidden": "Začít se skrytým ovládáním", + "card_controls_hidden_hint": "Pouze 3D zobrazení; oko v levém dolním rohu obnovuje lišty, hodnoty a přepínače", + "card_controls_hide_after": "Skrýt ovládání po", + "card_hide_after_s": "{n} s bez dotyku", + "card_fullscreen_button": "Tlačítko celé obrazovky", + "card_fullscreen_button_hint": "Skryje řídicí panel kolem karty (např. na nástěnném tabletu)", + "fullscreen": "Celá obrazovka", + "fullscreen_exit": "Opustit celou obrazovku", + "card_section_show": "Zobrazit", + "card_floor": "Podlaží", + "card_floor_house": "Celý dům (klepněte na podlaží pro otevření)", + "card_height": "Výška (pixely)", + "card_walls": "Zdi", + "card_quality_hint": "„Tablet“ je nejlehčí nastavení – ideální pro tablety Fire a ostatní nástěnné tablety.", + "card_flows_switch": "Přepínač v kartě", + "card_flows_on": "Vždy zap.", + "card_flows_off": "Vždy vyp.", + "holos": "Karty", + "holos_hint": "Zobrazit nebo skrýt živé karty nad domem (energetická bilance, auto, média)", + "card_energy": "Zobrazovat hodnoty energie nahoře", + "card_room_panel": "Podrobnosti místnosti po klepnutí", + "card_room_buttons": "Tlačítka místností", + "card_room_buttons_hint": "Řada s jedním tlačítkem na místnost nahoře na kartě – klepnutím otevřete místnost jako v modelu", + "card_room_panel_hint": "Světla a rolety místnosti v postranním panelu", + "card_explode": "Rozsunout podlaží v zobrazení domu", + "card_roof_fade": "Zatmívat střechu při přiblížení", + "card_roof_fade_hint": "Vyp.: střecha zůstává na domě, i když se kamera přibližuje.", + "card_stats": "Ukazatel výkonu (snímky za sekundu)", + "card_stats_hint": "K ověření, jak plynule karta funguje na zařízení", + "packs": "Balíčky nábytku", + "lib_badge_light": "Lampa: propojuje se se světlem a přepíná v 3D", + "lib_badge_electric": "Elektrické: propojuje se s entitou a snímačem výkonu (přepínání, obrázky, spotřeba)", + "lib_badge_hint": "Prvky se symbolem se propojují s entitami: lampy přepínají, obrazovky zobrazují obrázky, zařízení zobrazují spotřebu.", + "care_bin_today": "Odvoz dnes", + "care_bin_tomorrow": "Odvoz zítra", + "care_bin_days": "Za {n} dní", + "care_mail_yes": "Je pošta", + "care_mail_no": "Prázdná", + "care_plant_thirsty": "Žíznivá", + "care_plant_ok": "Dobře zalitá", + "care_time_left": "Zbývá {time}", + "care_entity_bin": "Datum odvozu (snímač)", + "care_entity_mail": "Snímač pošty", + "care_entity_plant": "Vlhkost půdy (snímač)", + "care_thirsty_below": "Žíznivá pod (%)", + "care_hint_bin": "Snímač s nejbližším odvozem: dny, datum, \"dnes\"/\"zítra\" nebo integrace Waste Collection Schedule. Popelnice svítí den předem a v den odvozu.", + "care_hint_mail": "Snímač hlásící poštu ve schránce (např. magnetický kontakt na klapce). Schránka pak svítí.", + "care_hint_plant": "Snímač vlhkosti v půdě. Pod prahovou hodnotou rostlina svítí a říká, že má žízeň.", + "lib_cat_lights": "Světla", + "lib_cat_seating": "Sedadla", + "lib_cat_tables": "Stoly", + "lib_cat_storage": "Skříně a regály", + "lib_cat_beds": "Postele", + "lib_cat_kitchen": "Kuchyně", + "lib_cat_appliances": "Domácí spotřebiče", + "lib_cat_bath": "Koupelna", + "lib_cat_media": "TV a audio", + "lib_cat_office": "Kancelář", + "lib_cat_tech": "Technika", + "lib_cat_climate": "Vytápění a klima", + "lib_cat_energy": "Energie", + "lib_cat_garden": "Zahrada a terasa", + "lib_cat_plants": "Rostliny", + "lib_cat_kids": "Děti", + "lib_cat_fitness": "Fitness", + "lib_cat_pets": "Zvířata", + "lib_cat_workshop": "Dílna a garáž", + "lib_cat_music": "Hudba a ateliér", + "lib_cat_season": "Sezóna a dekorace", + "lib_cat_pictures": "Obrázky a rámečky", + "lib_cat_vehicles": "Vozidla", + "lib_cat_building": "Schody a prvky budovy", + "lib_cat_decor": "Dekorace a ostatní", + "lib_favourites": "Oblíbené", + "lib_recent": "Nedávno použité", + "lib_for_room": "Hodí se do {room}", + "lib_all_rooms": "Zobrazit všechny místnosti", + "lib_linkable": "k propojení", + "lib_lit": "svítící", + "lib_outdoor": "venkovní", + "lib_fav_add": "Přidat do oblíbených", + "lib_fav_remove": "Odstranit z oblíbených", + "lib_sizes": "Rozměry", + "feature_name_energy": "Tok energie", + "ext_tab": "Rozšíření", + "ext_title": "Rozšíření", + "models": "Vlastní 3D modely", + "models_hint": "Pro některá vozila může NextFloor zobrazit skutečný 3D model, pokud jej vlastníte. Vyberte zde soubor (.glb): NextFloor jej správně nastaví, odlehčí, označí lak a uloží do vašeho Home Assistant. Bez modelu vypadá vozidlo jako dříve.", + "models_licence": "Soubory jsou vaše a zůstávají ve vašem Home Assistant. NextFloor modely nedodává; ujistěte se, že licence modelu umožňuje jeho použití ve vlastní instalaci.", + "model_add": "Přidat model …", + "model_replace": "Nahradit model …", + "model_remove": "Odstranit", + "model_present": "v použití", + "model_missing": "zatím chybí", + "model_remove_confirm": "Odstranit model „{id}“ z Home Assistant?", + "model_removed": "Model „{id}“ byl odstraněn.", + "model_uploaded": "Model „{id}“ byl uložen ({size}). Obnovte panel pro jeho zobrazení.", + "model_upload": "Uložit do Home Assistant", + "model_info": "{triangles} trojúhelníků, {size} m", + "model_front": "Přední část", + "model_front_hint": "Otáčejte modelem, dokud jeho přední část nebude směřovat k pozorovateli (vlevo dole na obrázku).", + "model_paint": "Lak (barva vybíraná v editoru)", + "model_paint_preview": "Barva v náhledu", + "model_detail": "Úroveň detailů", + "model_detail_light": "Lehká (tablet)", + "model_detail_normal": "Normální", + "model_detail_fine": "Jemná", + "model_result": "Výsledek: {triangles} trojúhelníků, {size}", + "model_error_not_glb": "Toto není soubor .glb (binární glTF). Exportujte model jako „glTF binary“.", + "model_error_compressed": "Soubor je komprimován (Draco, Meshopt nebo KTX). Exportujte jej bez komprese.", + "model_error_empty": "Soubor neobsahuje nic trojrozměrného.", + "model_error_unreadable": "Soubor nelze přečíst: {detail}", + "model_error_too_large": "Soubor je větší než {max}. Vyberte nižší úroveň detailů.", + "model_upload_forbidden": "Pouze správci mohou nahrávat modely.", + "model_upload_too_large": "Home Assistant nepřijímá soubory větší než {max}. Vyberte nižší úroveň detailů.", + "model_upload_not_glb": "Home Assistant odmítl soubor (není to binární glTF).", + "model_upload_bad_id": "Identifikátor modelu je neplatný.", + "model_upload_other": "Nahrávání selhalo: {detail}", + "ext_intro": "Importujte zde vlastní balíčky nábytku, nahrávejte vlastní 3D modely a přidávejte zásuvné moduly.", + "plugin": "zásuvný modul", + "plugins_title": "Zásuvné moduly", + "plugins_intro": "Zásuvné moduly přidávají vlastní animace světla, zařízení a karty v panelu místnosti. Zadejte adresu zásuvného modulu (soubor .js v /config/www, tj. /local/…, z HACS /hacsfiles/… nebo https://…).", + "plugins_docs": "Jak napsat zásuvný modul", + "plugins_warning": "Zásuvné moduly běží se stejnými oprávněními jako NextFloor ve vašem prohlížeči. Používejte pouze zásuvné moduly z důvěryhodných zdrojů.", + "plugins_off": "vyp.", + "plugins_error": "chyba", + "plugins_loading": "načítání …", + "plugins_nothing_registered": "načten, ale nic nezaregistroval", + "plugins_loaded": "aktivní", + "plugins_reload_hint": "Funguje po obnovení stránky", + "plugins_remove": "Odstranit", + "plugins_none": "Žádné zásuvné moduly.", + "plugins_from_dashboard": "Zaregistrováno prostřednictvím zdroje řídicího panelu", + "plugins_add": "Přidat", + "plugins_url_invalid": "Zadejte adresu .js pod /local/…, /hacsfiles/… nebo https://….", + "plugins_exists": "Tento zásuvný modul již je v seznamu.", + "plugins_limit": "Nejvýše 20 zásuvných modulů.", + "packs_title": "Balíčky nábytku", + "packs_intro": "Importujte vlastní nábytek jako balíček (JSON): jako soubor nebo vložený níže. {n} balíčků je přiloženo k NextFloor a jsou vždy dostupné.", + "packs_docs": "Formát balíčku", + "packs_none": "Žádné vlastní balíčky.", + "community_title": "Nábytek komunity", + "community_intro": "Nábytek vytvořený a sdílený ostatními v tvůrci nábytku – prověřený a zdarma. Vytvořte si vlastní:", + "community_builder": "Otevřít tvůrce nábytku", + "community_how": "Jak sdílet své", + "community_load": "Načíst nábytek komunity", + "community_none": "Zatím není žádný nábytek komunity – buďte první!", + "community_install": "Nainstalovat", + "community_update": "Aktualizovat", + "community_installed": "Nainstalováno", + "community_failed": "Nepodařilo se načíst nábytek komunity: {detail}", + "pack_import": "Importovat soubory balíčků …", + "pack_paste": "Importovat JSON", + "pack_paste_empty": "Nejprve vložte JSON balíčku.", + "pack_paste_not_json": "Toto není platný JSON: {detail}", + "pack_imported": "Importováno „{name}“ od {publisher} – {n} prvků", + "packs_imported_n": "Importováno {n} z {total} balíčků", + "pack_by": "od {publisher} · {n} prvků", + "pack_remove": "Odstranit", + "pack_remove_confirm": "Odstranit balíček „{name}“? Jeho nábytek zůstane v plánu jako běžná tělesa.", + "pack_error_not_a_pack": "Toto není balíček nábytku (chybí \"format\": \"nfpack\").", + "pack_error_builtin": "Balíček přiložený k NextFloor již má tento identifikátor.", + "pack_error_invalid_content": "Balíček obsahuje neplatný nábytek: {detail}", + "pack_error_too_large": "Balíček je příliš velký (nejvýše 1 MB).", + "pack_error_needs_update": "Tento balíček vyžaduje novější verzi NextFloor. Nejprve aktualizujte (HACS › NextFloor › ⋮ › \"Informace o aktualizaci\" › \"Stáhnout\"), restartujte Home Assistant a importujte znovu.", + "pack_error_other": "Import selhal: {detail}", + "store_open": "Otevřít obchod se zásuvnými moduly", + "store_close": "Zavřít obchod se zásuvnými moduly", + "store_intro": "Prověřené zásuvné moduly komunity. Každý je před přidáním zkontrolován a poté se nemění.", + "store_submit": "Nahlásit vlastní zásuvný modul", + "store_empty": "Žádné zásuvné moduly v obchodě.", + "store_failed": "Nepodařilo se načíst obchod ({error}).", + "store_install": "Nainstalovat", + "store_installed": "nainstalováno", + "store_update": "Aktualizovat", + "store_confirm": "Nainstalovat „{name}“ od {author}?\n\nZásuvný modul běží se stejnými oprávněními jako NextFloor ve vašem prohlížeči. Soubor byl zkontrolován a jeho obsah je neměnný:\n{url}", + "manual": "Návod", + "manual_more": "Dozvědět se více", + "feature_text_energy": "Částice energie létají v obloucích ze solárních panelů do střídače, mezi domem, úložištěm, sítí a spotřebiči – rychleji a hustěji, čím více výkonu teče. Moduly jiskří svou produkcí, skleněná karta nad střechou zobrazuje bilanci a to, jak soběstačný dům právě je.", + "live_autarky": "soběstačnost", + "live_day_hint": "Posledních 24 hodin: slunce (pole) a spotřeba (čára)", + "live_week_hint": "Posledních 7 dní: slunce {solar} kWh, spotřeba {use} kWh (žlutá: slunce, světlá: spotřeba)", + "live_days": "dní", + "live_car_away": "Na cestě", + "live_car_charging": "Nabíjení", + "live_car_plugged": "Připojeno", + "live_car_lock": "Zamknout", + "live_car_unlock": "Odemknout", + "live_car_unlock_confirm": "Opravdu odemknout {name}?", + "live_car_climate": "Klimatizace", + "live_car_charge": "Spustit/zastavit nabíjení", + "live_media_prev": "Předchozí", + "live_media_playpause": "Přehrát/pauza", + "live_media_next": "Následující", + "live_media_volume": "Hlasitost", + "live_car_device": "Auto (libovolná entita auta)", + "live_car_device_hint": "Stav nabití, dojezd, nabíjení, zástrčku, zámek a klimatizaci NextFloor nachází na zařízení auta. Bez něj používá snímač přítomnosti místa.", + "live_car_departure_entity": "Čas odjezdu (volitelně)", + "live_car_departure": "Odjezd {time}", + "live_car_open": "Otevřeno: {parts}", + "printer_printing": "tiskne", + "printer_done": "hotovo", + "printer_paused": "pozastaveno", + "printer_error": "chyba", + "printer_idle": "připravena", + "printer_done_at": "hotovo v {time}", + "printer_layer": "Vrstva", + "printer_nozzle": "Tryska", + "printer_bed": "Podložka", + "heatpump_heating": "topí", + "heatpump_water": "teplá voda", + "heatpump_cooling": "chladí", + "heatpump_defrost": "odmrazuje", + "heatpump_idle": "v klidu", + "heatpump_flow_return": "Vstup → zpátečka", + "heatpump_heat": "Teplo", + "heatpump_power": "Proud", + "heatpump_outside": "venku", + "pack_missing_item": "Nábytek z odstraněného balíčku", + "back_to_room": "Vrátit se do {room}", + "back_to_floor": "Vrátit se do podlaží", + "hint_furniture": "Klepněte na místnost, poté vyberte prvek vpravo · přetahujte prvky, měňte velikost za rohy", + "furniture_into": "Nové prvky směřují do středu „{room}“.", + "furniture_pick_room": "Tip: nejprve klepněte na místnost – nové prvky se zobrazí v jejím středu.", + "flows": "Tok energie", + "flows_hint": "Zobrazit nebo skrýt oblouky energie mezi solárními poli, střídačem, úložištěm, sítí a spotřebiči", + "chk_title": "Konfigurace", + "chk_hint": "Co potřebuje tok energie. Klepněte na řádek pro přechod tam.", + "chk_solar": "Solární pole na místě", + "chk_solar_add": "Položit solární pole na střechu", + "chk_meter": "Elektroměr se snímačem sítě", + "chk_meter_sensor": "Elektroměr: chybí snímač sítě (W)", + "chk_meter_add": "Přidat elektroměr", + "chk_inverter": "Střídač se snímačem výkonu", + "chk_inverter_sensor": "Střídač: chybí snímač výkonu", + "chk_inverter_add": "Přidat střídač", + "chk_battery": "Úložiště energie s výkonem a stavem nabití", + "chk_battery_sensor": "Úložiště energie: chybí výkon nebo stav nabití", + "chk_battery_opt": "Úložiště energie (volitelně)", + "chk_grid": "Připojení k síti nastaveno", + "chk_grid_opt": "Připojení k síti (volitelně, jinak automaticky)", + "energy_sign_grid": "Dům zobrazuje dodávání do sítě, když slunce nic nevyrábí. Snímač sítě má pravděpodobně obrácené znaménko.", + "energy_sign_battery": "Úložiště se sjíždí bez slunce a bez odběru ze sítě. Jeho snímač má pravděpodobně obrácené znaménko.", + "energy_sign_flip": "Obrátit znaménko", + "help_title": "Nápověda a zpětná vazba", + "help_hint": "Hlaste problémy jako Issue na GitHubu a přání jako Discussion – nic se neztratí a všichni vidí stav.", + "help_issue": "Nahlásit problém", + "help_idea": "Navrhnout nápad", + "furn_name": "Název (volitelně)", + "furn_mirror": "Zrcadlit", + "furn_mirror_hint": "Prohoďte vlevo a vpravo – roh na druhou stranu, skříň s dveřmi na druhé straně, kuchyňská linka zrcadlově.", + "hint_opening": "Klepněte na zeď pro přidání dveří nebo okna – druh vyberte potom vpravo", + "preset_door": "Dveře", + "preset_door_double": "Dvoukřídlé dveře", + "preset_window": "Okno", + "preset_window_double": "Dvoukřídlé okno", + "preset_terrace": "Terasové dveře", + "preset_terrace_double": "Dvoukřídlé balkonové dveře", + "preset_lift_slide": "Zdvižně-posuvné dveře", + "preset_garage": "Garážová vrata", + "preset_front": "Vchodové dveře", + "opening_style": "Styl", + "sidelight_auto": "automaticky", + "sidelight_hinge": "Světlík na straně pantů", + "sidelight_hinge_hint": "Jinak je světlík naproti pantům; zaškrtnuto – vedle pantů.", + "sidelight_width": "Šířka světlíku (m)", + "sidelight_width_left": "Levý světlík (m)", + "sidelight_width_right": "Pravý světlík (m)", + "style_auto": "Automaticky ({style})", + "style_interior": "Vnitřní dveře", + "style_front": "Vchodové dveře", + "style_front_glass": "Vchodové dveře se sklem", + "style_sidelight": "Vchodové dveře se světlíkem", + "style_sidelights": "Vchodové dveře se dvěma světlíky", + "style_glass": "Skleněné dveře", + "style_sliding": "Posuvné dveře", + "style_passage": "Otvor (bez dveří)", + "style_standard": "Standardní", + "style_bars": "S příčkami", + "style_glass_wall": "Skleněná zeď (stálá)", + "preset_glass_wall": "Skleněná zeď", + "flip_hinge": "Změnit stranu pantů", + "flip_main_leaf": "Změnit hlavní křídlo", + "flip_hinge_hint": "Panty na druhou stranu", + "flip_swing": "Obrátit směr otevírání", + "flip_swing_hint": "Dveře se otevírají do místnosti nebo na druhou stranu", + "main_leaf": "Hlavní křídlo (ze strany místnosti)", + "contact_main": "Kontakt hlavního křídla", + "contact_second": "Kontakt druhého křídla", + "tool_outdoor": "Exteriér", + "tool_measure": "Podle rozměrů", + "hint_measure": "Klepněte na počáteční bod, potom zadejte vpravo délku zdí tím směrem", + "measure": "Místnost podle rozměrů", + "measure_start": "Klepněte na počáteční bod v plánu, např. roh místnosti.", + "measure_from": "Start v {x} / {z} m – klepnutí posune start.", + "measure_length": "Délka následující zdi (m)", + "measure_close": "Uzavřít místnost", + "measure_undo": "Odstranit poslední zeď", + "measure_gap": "Mezera ke startu: {gap} m (spojuje se při uzavření)", + "measure_hint": "Tip: zadejte délku a stiskněte šipku. Při naměřených vnitřních rozměrech použijte potom „Uzavřít mezery“.", + "rect_by_size": "Obdélník podle rozměrů", + "rect_add": "Přidat obdélník", + "dir_up": "Nahoru", + "dir_down": "Dolů", + "dir_left": "Vlevo", + "dir_right": "Vpravo", + "hint_outdoor": "Přetáhněte pro nakreslení venkovního terénu (trávník, terasa, bazén …)", + "outdoor": "Venkovní terén", + "outdoor_type": "Typ", + "outdoor_height": "Výška (m)", + "outdoor_offset": "Výškový posun (m, − = níže)", + "outdoor_outline": "Zobrazit obrys", + "outdoor_outline_hint": "Označený terén nekreslí svítící čáru podél hrany – pro velké pozemky z několika trávníků.", + "outdoor_corners_hint": "Rohy: + na hraně přidává roh, přetahování tvaruje terén, × smaže roh.", + "outdoor_hint": "Venkovní lampy (sloupek, zahradní reflektor, venkovní nástěnné svítidlo) osvětlují všechny venkovní terény a fasádu.", + "out_lawn": "Trávník", + "out_terrace": "Terasa", + "out_path": "Cesta", + "out_driveway": "Příjezdová cesta", + "out_pool": "Bazén", + "out_bed": "Záhon", + "out_hedge": "Živý plot", + "out_fence": "Oplocení", + "out_wild": "Divoký koutek", + "out_pergola": "Pergola / rám", + "outdoor_open": "Otevřený (přeskočit poslední hranu)", + "outdoor_open_hint": "Hrana od posledního bodu k prvnímu se nekreslí – plot nebo pergola opřená o dům.", + "fence_gates": "Brány v plotě", + "gate_add": "+ Brána v plotě", + "gate_edge": "Strana plotu", + "gate_kind": "Druh", + "gate_single": "Branka", + "gate_double": "Dvoukřídlá brána", + "gate_sliding": "Posuvná brána", + "gate_offset": "Střed od začátku (m)", + "gate_width": "Šířka (m)", + "gate_entity": "Pohon nebo spínač", + "gate_contact": "Kontakt (zapnuto = otevřeno)", + "fence_gates_hint": "Brána je mezera v plotě se sloupky a křídlem. S pohonem (cover, spínač, input_boolean, zámek) a/nebo kontaktem se ve 3D otevře: branka a dvoukřídlá brána se otáčejí dovnitř, posuvná brána jede podél plotu.", + "outdoor_bracing": "Křížové ztužení", + "outdoor_cut": "Vyříznout z okolních terénů", + "outdoor_cut_hint": "Každý terén, který zcela obsahuje tento, zde získá otvor – bazén v terase, rybníček nebo divoký koutek v trávníku. Pořadí kreslení nemá vliv. Bazén se vyřezává sám.", + "outdoor_area_hint": "Oblast Home Assistant této plochy (zahrada, terasa, bazén): její zařízení a snímače jsou v sekci Venku a značka na ploše ji otevírá.", + "pool_temp": "Teplota vody (volitelně)", + "pool_pump": "Čerpadlo / filtr (volitelně)", + "pool_pump_on": "čerpadlo pracuje", + "outdoor_slope": "Sklon (m)", + "outdoor_slope_hint": "Rozdíl výšek od vysoké k nízké hraně; vysoká hrana leží na výškovém posunu. Lampy na terénu jej sledují.", + "outdoor_slope_dir": "Klesá směrem k", + "slope_x": "vpravo (+X)", + "slope_nx": "vlevo (−X)", + "slope_z": "dolů (+Z)", + "slope_nz": "nahoru (−Z)", + "north": "Sever (° ve směru hodinových ručiček odshora)", + "north_hint": "Sever je potřebný pro slunce (světlo přes okna).", + "map_on": "Zobrazit skutečnou mapu pod plánem", + "map_lat": "Zeměpisná šířka", + "map_lon": "Zeměpisná délka", + "map_use_ha": "Použít polohu Home Assistant", + "map_opacity": "Průhlednost (%)", + "map_zoom": "Úroveň detailů", + "map_zoom_coarse": "hrubá", + "map_zoom_fine": "Jemná", + "map_move": "Posunout mapu pod plánem", + "map_step": "Krok", + "map_url": "Vlastní adresa dlaždic (prázdné = OpenStreetMap)", + "map_hint": "Prohlížeč načítá dlaždice mapy přímo ze serveru map (výchozí OpenStreetMap, dodržujte jejich pravidla použití); když je mapa vypnutá, nic se nenačítá. Plán leží na mapě podle kompasu – otočte kompas nebo posuňte mapu, dokud dům nebude odpovídat.", + "compass_title": "Kompas", + "compass_n_short": "S", + "compass_s_short": "J", + "compass_swap": "Prohodit sever ↔ jih", + "compass_swap_hint": "Otočí kompas o 180°. Výkres, střešní roviny a solární pole zůstávají bez změn.", + "compass_hint": "Pokud kompas neodpovídá skutečnosti, otočte jej zde – nic se nemusí kreslit znova. Sluneční světlo, vítr a směry střešních rovin jej sledují.", + "roof": "Střecha", + "roof_none": "Bez střechy", + "roof_flat": "Plochá střecha", + "roof_gable": "Sedlová střecha", + "roof_custom": "Střešní roviny (vlastní)", + "roof_sections": "Střešní roviny", + "roof_sections_hint": "Každá střešní rovina pokrývá obdélník domu, např. dům, stodolu nebo přístavbu – každá s vlastním tvarem, směrem hřebene, výškou okapu a sklonem. Přetáhněte v plánu pro nakreslení nové; klepnutím vyberete, přetažením posunete, rohy mění velikost.", + "roof_sections_start": "Vytvořit střešní roviny z místností", + "roof_sections_regen": "Vytvořit znovu z místností", + "roof_sections_off": "Vrátit se k jedné střeše", + "roof_regen_confirm": "Nahradit všechny střešní roviny novým návrhem z místností?", + "roof_section": "Střešní rovina", + "roof_section_hint": "Výšky se počítají od terénu. Strana s nižším okapem zasahuje níže (catslide); pultové střechy stoupají od první strany.", + "roof_shape_gable": "Sedlová", + "roof_shape_hip": "Valbová", + "roof_shape_pent": "Pultová", + "roof_shape_flat": "Plochá", + "roof_shape_halfhip": "Polovalbová", + "roof_shape_pyramid": "Stanová", + "roof_shape_mansard": "Mansardová", + "roof_shape_parapet": "S atikou", + "roof_shape": "Tvar", + "roof_end_start": "Zakončení na začátku hřebene", + "roof_end_end": "Zakončení na konci hřebene", + "roof_halfhip": "Polovalba začíná na", + "roof_halfhip_hint": "V jaké výšce štítu začíná polovalba, jako část výšky štítu: nízká = velká polovalba, vysoká = pouze špička.", + "roof_axis_x": "Hřeben ↔", + "roof_axis_z": "Hřeben ↕", + "roof_eave": "Okap (m)", + "roof_pitch_short": "Sklon (°)", + "roof_height": "Výška (m)", + "roof_base": "Horní hrana zdí (m)", + "roof_rotation": "Otočení (°)", + "roof_on_floor": "Stojí na podlaží", + "roof_on_floor_hint": "Staví rovinu na koruny zdí tohoto podlaží; základna a okapy se posouvají společně. V 3D zobrazení střecha patří k tomuto podlaží.", + "roof_base_hint": "Pod výškou stropu podlaží pod ní zdi tohoto podlaží končí pod střechou: nadezdívky u okapů, štíty k hřebeni, vnitřní zdi seříznuté sklonem. Čárkované čáry v plánu ukazují, kde zůstává výška 1,5 m a 2 m.", + "roof_ridge_height": "Výška hřebene", + "roof_side_top": "nahoru", + "roof_side_bottom": "dolů", + "roof_side_left": "vlevo", + "roof_side_right": "vpravo", + "roof_swap": "Prohodit strany", + "roof_open": "Zastřešení (sloupky místo zdí, průhledné)", + "roof_open_short": "Zastřešení", + "roof_dormer": "Vikýř", + "roof_dormer_hint": "Vikýř na této straně střechy: široký 2 m, čelo u okapní zdi, okapy 1,4 m nad okapem střechy, sedlová střecha. Potom jej posuňte a změňte šířku a výšky jako každou rovinu; hlavní sklon se pod ním otevírá a zeď podkroví stoupá k vikýři – vejde se tam okno.", + "roof_outline": "Převzít obrys podlaží", + "roof_outline_hint": "Plochá střecha libovolného tvaru: přebírá obrys místností zobrazeného podlaží (i ve tvaru L nebo Z) jako jednu plochu bez spojů. Rohy lze potom přetahovat.", + "roof_points_hint": "Libovolný tvar: přetahujte rohy v plánu, + na hraně přidá roh, × jej smaže. Návrat k obdélníku opustí tvar.", + "roof_rect": "Vrátit se k obdélníku", + "roof_open_hint": "Pro zastřešení terasy nebo přístřešek: sloupky a trámy nesou střechu místo zdí a je průhledná. Tam, kde se zastřešení dotýká zdi domu, se o ni opírá.", + "roof_swap_hint": "Otočí střechu: obě strany si prohodí okap a sklon, pultová střecha stoupá na druhou stranu.", + "roof_pitch": "Sklon střechy (°)", + "roof_overhang": "Přesah střechy (m)", + "roof_overhang_sides": "Přesah po stranách", + "roof_overhang_a": "Přesah okapu A (m)", + "roof_overhang_b": "Přesah okapu B (m)", + "roof_overhang_u0": "Přesah štítu začátek (m)", + "roof_overhang_u1": "Přesah štítu konec (m)", + "roof_overhang_auto": "Zpět na automatiku", + "roof_overhang_sides_hint": "Bez vlastních hodnot je přesah automatický: všude stejný, kromě míst, kde střecha přiléhá k domu (tam žádný).", + "roof_ridge": "Hřeben", + "roof_ridge_long": "Podél delší strany", + "roof_ridge_short": "Podél kratší strany (např. řadový dům)", + "device": "Zařízení", + "lamp_mount": "Lampa", + "lamp_ceiling": "Stropní svítidlo", + "lamp_floor": "Stojací lampa", + "lamp_table": "Stolní lampa", + "lamp_wall": "Nástěnné svítidlo", + "marker_height": "Výška značky (m)", + "height_auto": "Automatická výška", + "device_centre": "Do středu místnosti", + "lights_spread": "Rozmístit stropní lampy rovnoměrně", + "devices_search": "Hledat zařízení …", + "devices_more": "+{n} dalších", + "devices_less": "méně", + "panel_more": "Více zařízení oblasti ({n})", + "panel_less": "Zobrazit méně", + "gaps_close": "Uzavřít mezery", + "gaps_hint": "Spojí místnosti vzdálené do 60 cm jednou společnou zdí; mezera se stane tloušťkou vnitřní zdi.", + "gaps_none": "Nebyly nalezeny žádné mezery mezi místnostmi.", + "gaps_closed": "Uzavřeno {n} míst.", + "gaps_closed_wall": "Uzavřeno {n} míst, vnitřní zeď má nyní {t} m.", + "fps": "FPS", + "fps_title": "Ukazatel výkonu (snímky za sekundu)", + "hint_garage": "Klepněte na zeď pro přidání garážových vrat", + "opening_garage": "Garážová vrata", + "garage_hint": "Vrata sledují stínění garáže (pozici nebo otevřeno/zavřeno) nebo magnetický kontakt vrat z oblasti místnosti.", + "door_hint": "S magnetickým kontaktem se křídlo otevírá; bez snímače stojí napůl otevřené.", + "hint_door": "Klepněte na zeď pro přidání dveří", + "hint_window": "Klepněte na zeď pro přidání okna", + "opening_door": "Dveře", + "opening_window": "Okno", + "opening_type": "Typ", + "opening_position": "Střed od rohu (m)", + "sill": "Výška parapetu (m)", + "opening_height": "Výška (m)", + "hinge": "Pant (ze strany místnosti)", + "hinge_left": "Levý", + "hinge_right": "Pravý", + "cover_entity": "Roleta", + "door_cover": "Pohon (dveře nebo vrata s motorem)", + "cover_position_entity": "Snímač pozice (živě)", + "cover_position_invert": "Snímač počítá obráceně (0 = otevřeno)", + "contact_entity": "Kontakt", + "sensor_kind": "Typ snímače", + "sensor_kind_contact": "Magnetický kontakt okna (otevřeno/zavřeno)", + "sensor_kind_handle": "Snímač kličky (otevřeno/vyklopeno/zavřeno)", + "sensor_kind_contact_tilt": "Kontakt + snímač vyklopení", + "handle_entity": "Snímač kličky", + "handle_main": "Snímač kličky hlavního křídla", + "leaf_main": "Hlavní křídlo", + "leaf_second": "Druhé křídlo", + "tilt_entity": "Snímač vyklopení", + "tilt_angle_entity": "Snímač úhlu vyklopení (°, volitelně)", + "tilt_angle_max": "Úhel považovaný za plné vyklopení (°)", + "tilt_angle_offset": "Posun: úhel v zavřeném stavu (°)", + "tilt_angle_invert": "Úhel počítá obráceně", + "door_shut": "Zobrazit zavřené bez snímače", + "door_shut_hint": "Dveře bez kontaktu stojí v 3D napůl otevřené, aby bylo vidět, že jsou to dveře. Zaškrtnuto – kreslí se zavřené: vchodové dveře, přístřešek, postranní dveře.", + "door_angle": "Úhel otevření", + "door_angle_default": "Výchozí", + "door_angle_hint": "Jak široce se křídlo otevírá. Se snímačem se otevírá takto, když nahlásí „otevřeno“; bez snímače stojí otevřené pod tímto úhlem (místo napůl). Výchozí zůstává jako dosud.", + "entity_auto": "Automaticky ({name})", + "entity_auto_none": "Automaticky (nic nenalezeno)", + "entity_none": "Žádný", + "entity_search": "Pište pro vyhledávání …", + "opening_hint": "Typ snímače: magnetický kontakt okna (hlásí otevřeno/zavřeno), snímač kličky (hlásí otevřeno, vyklopeno a zavřeno – např. klička Homematic) nebo kontakt + snímač vyklopení (druhý snímač, který hlásí pouze vyklopení). Automaticky používá rolety a kontakty oblasti místnosti. Snímač pozice: entita hlásící pozici rolety během pohybu (např. \"level\" Homematic, 0–100 % nebo 0–1, otevřeno = nahoře) – roleta se pak pohybuje živě v 3D.", + "furniture": "Nábytek", + "furniture_add": "Přidat nábytek", + "studio_new": "Vytvořit vlastní nábytek", + "studio_title": "Dílna nábytku", + "studio_title_edit": "Dílna nábytku: změnit", + "studio_hint": "Vyberte šablonu, nastavte rozměry a čela a vložte nábytek do plánu. Uloží se do balíčku „Vlastní nábytek“ a později jej zde lze upravit.", + "studio_kind": "Šablona", + "studio_kind_cabinet": "Skříňka", + "studio_kind_shelf": "Regál", + "studio_kind_lamp": "Lampa", + "studio_kind_device": "Zařízení", + "studio_name": "Název", + "studio_width": "Šířka (cm)", + "studio_depth": "Hloubka (cm)", + "studio_height": "Výška (cm)", + "studio_doors": "Dvířka", + "studio_drawers": "Zásuvky", + "studio_shelves": "Police", + "studio_handle": "Úchytky", + "studio_handle_bar": "Lišta", + "studio_handle_knob": "Knoflík", + "studio_handle_none": "Bez", + "studio_base": "Základna", + "studio_base_plinth": "Sokl", + "studio_base_legs": "Nožičky", + "studio_base_none": "Žádná", + "studio_back": "Záda", + "studio_lamp": "Druh", + "studio_lamp_floor": "Stojací lampa", + "studio_lamp_table": "Stolní lampička", + "studio_lamp_pendant": "Závěsná lampa", + "studio_lamp_wall": "Nástěnné svítidlo", + "studio_display": "Displej vpředu (zobrazuje přehrávač)", + "studio_mount": "Stojí", + "studio_mount_floor": "Na podlaze", + "studio_mount_surface": "Na nábytku", + "studio_mount_wall": "Na zdi", + "studio_color_body": "Korpus", + "studio_color_lamp_body": "Základna a kostra", + "studio_color_front": "Čela", + "studio_color_boards": "Police", + "studio_color_shade": "Stínidlo", + "studio_color_display": "Rám displeje", + "studio_color_white": "Bílá", + "studio_color_wood": "Dřevo", + "studio_color_metal": "Kov", + "studio_color_dark": "Tmavá", + "studio_color_glass": "Sklo", + "studio_color_accent": "Akcent", + "studio_color_own": "Vlastní barva", + "studio_color_plan": "Barva plánu", + "studio_place": "Vložit do plánu", + "studio_save": "Uložit změnu", + "studio_open": "Upravit v dílně", + "studio_error": "Uložení selhalo: {detail}", + "studio_pack_name": "Vlastní nábytek", + "studio_pack_publisher": "Dílna nábytku", + "furniture_search": "Hledat nábytek …", + "furniture_search_none": "Nic nenalezeno. Zkuste jiné slovo – anglicky nebo německy.", + "furniture_type": "Prvek", + "rotation": "Otočení (°)", + "tilt_x": "Náklon vpřed/vzad (°)", + "tilt_z": "Náklon do strany (°)", + "strip_tilt": "Naklonění podél délky (°)", + "strip_upright": "Svisle", + "strip_rise": "Sklon podél délky (°)", + "strip_upright_hint": "Pásek stojí svisle: jeho délka běží nahoru od výšky nad podlahou – podél zárubně, jako světelný sloupec. Naklonění položí ležící pásek na šikminu (90° = přední část směřuje do strany).", + "rotate_left": "↺ 90°", + "rotate_right": "↻ 90°", + "height_m": "Výška (m)", + "furn_sofa": "Pohovka", + "furn_armchair": "Křeslo", + "furn_table": "Stůl", + "furn_chair": "Židle", + "furn_bed": "Postel", + "furn_nightstand": "Noční stolek", + "furn_wardrobe": "Skříň", + "furn_shelf": "Regál", + "furn_kitchen": "Kuchyňská skříňka", + "furn_worktop": "Pracovní deska", + "furn_fridge": "Lednice", + "furn_fridge_smart": "Chytrá lednice (side by side)", + "furn_door_left": "Snímač dveří levý (strana mrazáku)", + "furn_door_right": "Snímač dveří pravý (strana lednice)", + "fridge_hint": "Když snímač dveří hlásí otevření, dveře se otevřou v 3D.", + "furn_stove": "Sporák", + "furn_sink": "Dřez", + "furn_bathtub": "Vana", + "furn_shower": "Sprcha", + "furn_wc": "WC", + "furn_washbasin": "Umyvadlo", + "furn_desk": "Psací stůl", + "furn_tv_board": "TV stolek", + "furn_plant": "Rostlina", + "furn_rug": "Koberec", + "furn_stairs": "Schody", + "furn_stairwell": "Otvor ve stropu", + "stairwell_hint": "Otvor v tomto podlaží, např. nad schody nebo pro mezipatro; shora je skrz něj vidět. Otvor musí ležet v jedné místnosti; více otvorů se může překrývat (např. pro tvar L). Schody z nižšího podlaží zasahující sem také samy otevírají strop.", + "tool_hole": "Otvor ve stropu", + "tool_roof": "Střecha", + "tool_energy": "Energie", + "tool_wall": "Zeď", + "hint_wall": "Přetáhněte pro nakreslení jednotlivé zdi (příčky, polozdi) · Shift ji udržuje rovnou · Alt bez přichytávání", + "free_wall": "Zeď", + "wall_length": "Délka (m)", + "wall_thickness": "Tloušťka zdi (m)", + "wall_height": "Výška (m)", + "wall_height_full": "Plná výška místnosti", + "wall_slope": "Šikmá", + "wall_slope_start": "Výška na začátku (m)", + "wall_slope_end": "Výška na konci (m)", + "wall_slope_hint": "Šikmá zeď: horní část běží rovně od výšky na začátku zdi (roh s nižším číslem) k výšce na jejím konci. Obě mohou být vyšší než podlaží, např. pro přístavbu s vysokými okny.", + "wall_slope_off": "Vrátit se k rovné zdi", + "wall_none": "Bez zdi", + "wall_none_hint": "Přeskočit tuto zeď úplně: pro otevřené plány, jejichž místnosti tvoří jeden prostor, ale v Home Assistant jsou oddělené.", + "edge_thickness": "Tloušťka (m)", + "wall_thickness_hint": "Tloušťka této zdi, např. 0,365 pro silnou vnější zeď nebo 0,115 pro lehkou příčku. Zeď mezi dvěma místnostmi přebírá silnější nastavení.", + "wall_thickness_reset": "Tloušťka jak je nastaveno pro dům", + "wall_heights": "Výšky zdí", + "wall_n": "Zeď {a}–{b}", + "wall_view": "Pohled na zeď", + "wall_view_hint": "Zeď zepředu: přetahujte dveře, okna a nábytek nebo zadejte jejich vzdálenost.", + "wall_view_prev": "Předchozí zeď", + "wall_view_next": "Následující zeď", + "wall_view_left": "Zleva (m)", + "wall_view_height": "Nad podlahou (m)", + "wall_part": "část {n}", + "wall_split_hint": "Rozdělte zde zeď: část získá vlastní výšku, např. 2,5 m vedle 1,7 m v jedné linii", + "wall_split_at": "Bod rozdělení od rohu (m)", + "wall_join_hint": "Odstranit bod rozdělení: část se opět spojí s předchozí", + "wall_exterior_short": "vnější zeď", + "room_wall_hint": "Nižší výška změní zeď v zábradlí nebo pult. Když dvě místnosti sdílejí zeď, platí nižší nastavení. Okna a dveře v ní končí ve výšce zdi.", + "free_wall_hint": "Volně stojící zeď, např. příčka. Tam, kde se dotýká zdi místnosti, je roh seříznut pod úhlem. Přetahujte úchyty pro posun konců, čáru pro posun celé zdi.", + "free_wall_slope": "◢ Šikmá", + "free_wall_slope_hint": "Zeď od jednoho konce ke druhému stoupá nebo klesá: výška nahoře platí na začátku, tato na konci.", + "free_wall_height_end": "Výška na konci (m)", + "stairwell_outside": "Tento otvor protíná hranici místnosti, a proto se nevyřezává. Posuňte jej zcela do jedné místnosti nebo jej zmenšete.", + "hint_hole": "Přetáhněte pro nakreslení otvoru ve stropu (schodiště, mezipatro)", + "hint_roof": "Přetáhněte pro nakreslení střešní roviny · klepnutím vyberete · přetažením posunete · rohy mění velikost", + "hint_energy": "Klepněte na solární pole pro jeho výběr · přetáhněte pro posun, i na jinou rovinu · nová pole přes + Solární pole vpravo", + "furn_parking": "Parkovací místo", + "furn_group_vehicles": "Parkování", + "parking_entity": "Snímač \"auto přítomno\"", + "parking_vehicle": "Vozidlo", + "parking_vehicle_none": "Žádné", + "parking_no_pack": "Není importován balíček vozidel – vozila pocházejí z balíčku \"Vozidla\" (Rozšíření → Balíčky nábytku).", + "parking_scale": "Velikost (%)", + "parking_type_entity": "Snímač typu vozidla (volitelně)", + "parking_types": "Stav → vozidlo", + "parking_type_state": "Stav (např. dodávka)", + "parking_add_type": "+ Přiřazení", + "parking_hint": "Bez snímače vozidlo stojí stále na místě. Se snímačem se zobrazí, když hlásí \"on\", \"home\" nebo \"present\". Snímač typu vozidla (např. z AI analýzy kamery) vybírá model: když jeho stav odpovídá přiřazení – i jako slovo v textu – zobrazí se toto vozidlo, jinak výchozí.", + "parking_too_tall": "Vozidlo ({car} m) je vyšší než místnost ({room} m).", + "furn_lamp_ceiling": "Stropní svítidlo", + "furn_lamp_downlight": "Zápustné bodové svítidlo", + "furn_lamp_spot": "Přisazené bodové svítidlo", + "furn_lamp_panel": "LED panel", + "furn_lamp_uplight": "Podlahový reflektor", + "furn_lamp_bollard": "Osvětlovací sloupek", + "furn_lamp_garden": "Zahradní reflektor", + "furn_radiator": "Radiátor", + "furn_robot_vacuum": "Robotický vysavač", + "furn_entity_vacuum": "Robotický vysavač", + "furn_entity_mower": "Robotická sekačka", + "pet_room_sensor": "Snímač místnosti zvířete (volitelně)", + "pet_room_hint": "Snímač udávající místnost, ve které se zvíře nachází – Bermuda nebo ESPresense s přívěskem na obojku: v 3D pak chodí po této místnosti.", + "furn_entity_water": "Ventil nebo vypínač", + "fridge_temp": "Teplota chladničky", + "freezer_temp": "Teplota mrazničky", + "fridge_temp_hint": "Značka zobrazuje teploty. Nad 8 °C v chladničce nebo −12 °C v mrazničce svítí jako varování.", + "spray_reach": "Dosah vody (m)", + "spray_hint": "Dokud je ventil otevřený nebo vypínač zapnutý, rozstřikovač stříká vodu v obloucích kolem sebe.", + "furn_robot_room": "Aktuální místnost (snímač)", + "robot_hint": "Když robot uklízí v Home Assistant, jezdí v 3D v pásech po místnosti, kterou hlásí (snímač „aktuální místnost“, porovnávaný s názvem místnosti nebo oblasti), jinak po místnosti své stanice. Trasa je simulována – Home Assistant obvykle nezná přesnou polohu. Po dokončení se vrací do stanice.", + "furn_lamp_pendant": "Závěsná lampa", + "furn_ceiling_fan": "Stropní ventilátor", + "furn_fan_entity": "Ventilátor", + "fan_hint": "Světlo je sada osvětlení ventilátoru (ponechte prázdné, pokud chybí). Ventilátor se vyhledá v místnosti nebo vybere zde: v 3D se lopatky otáčejí tak rychle, jak pracuje, jeho ikona jej přepíná, posun nahoru/dolů mění rychlost, dlouhé podržení otevře rychlou nabídku. Výška udává, jak nízko visí pod stropem (více = delší tyč).", + "room_ceiling": "Výška stropu", + "room_ceiling_tip": "Níže než podlaží (koupelna pod schody) nebo výše (obývací pokoj otevřený až pod střechu): stropní lampy, ventilátory, LED pásky a stropní zařízení pak visí zde a zdi místnosti mají tuto výšku.", + "room_ceiling_through": "Strop ({ceiling} m) je výše než výška podlaží ({floor} m): místnost zasahuje do podlaží nad ní, její zdi rostou s ní a podlaží nad ní zůstává nad ní otevřené. Editor vyššího podlaží zobrazuje tuto oblast šrafovaně.", + "room_floor_offset": "Úroveň podlahy (m)", + "room_floor_offset_hint": "Pokud podlaha této místnosti leží níže nebo výše než podlaží (snížený vstup: −0,39), podlaha, zdi, dveře, okna a to, co v ní stojí, se posunou; strop zůstává. Stupně přidejte jako schody.", + "room_inner": "Uvnitř {w} × {d}", + "room_inner_hint": "Měřeno od zdi ke zdi: vnitřní zdi zabírají polovinu tloušťky, vnější stojí mimo obrys.", + "floor_heating": "Podlahové vytápění (volitelně)", + "floor_heating_hint": "Dokud termostat topí (nebo je ventil otevřený, vypínač zapnutý), podlaha místnosti svítí teplo v 3D.", + "room_announce_speaker": "Reproduktor oznámení", + "room_announce_quiet": "Doba klidu pro oznámení", + "room_announce_hint": "Bez výběru mluví reproduktor nastavený v místnosti, jinak hlasový asistent, Echo nebo reproduktor oblasti (nikdy televizor). V době klidu je oznámení pro více místností přeskočí; oznámení pouze pro ni i tak dorazí.", + "ceiling_here": "Strop zde", + "ceiling_here_hint": "Výška stropu přesně v tomto místě, např. u šikminy. Prázdné = strop místnosti.", + "ceiling_slope": "Pod sklon střechy", + "ceiling_slope_hint": "Strop zde leží pod sklonem střechy: lampa visí na jeho spodní straně, přesně nad svým místem.", + "furn_lamp_floor": "Stojací lampa", + "furn_lamp_table": "Stolní lampa", + "furn_lamp_wall": "Nástěnné svítidlo", + "furn_led_strip": "LED pásek", + "furn_group_lights": "Světla", + "furn_entity_light": "Světlo nebo vypínač", + "furn_color_entity": "Barva a jas z (volitelně)", + "furn_color_entity_hint": "Pro světla, která relé (Shelly, aktor) zapíná a vypíná, zatímco žárovka sama zná barvu a jas: zap./vyp. pochází z vypínače výše, barva a jas z této entity.", + "lamp_extra_light": "Zdroj světla {n} (volitelně)", + "lamp_extra_hint": "Svítidlo s několika světly – hlavní, noční, náladový kroužek: když je hlavní vypnuté, svítí v 3D dalším zapnutým, o něco slaběji. Přepínejte světla samostatně v panelu místnosti.", + "furn_entity_climate": "Vytápění (termostat)", + "lamp_hint": "Klepněte na lampu v 3D pro její přepnutí, podržte pro rychlou nabídku. Fungují i vypínače (např. relé stropní lampy) – lampa svítí, když je zapnuté. Stolní lampy stojí na nábytku pod nimi.", + "lamp_hint_pendant": "Výška = svěšení pod stropem. Klepněte v 3D pro přepnutí, podržte pro podrobnosti.", + "theme": "Vzhled", + "version_hint": "Nainstalovaná verze NextFloor – frontend; integrace v Home Assistant hlásí {backend}", + "accent": "Barva akcentu", + "accent_hint": "Vlastní barva akcentu: čáry a svítící hrany ve vzhledu neon, tlačítka a značky – ↺ obnoví neonovou azurovou", + "accent_reset": "Vrátit se k azurové", + "theme_neon": "Neon", + "theme_blueprint": "Technický výkres", + "theme_day": "Den", + "theme_auto": "Auto", + "clock": "Hodiny", + "clock_none": "Žádné", + "clock_top_left": "Levý horní", + "clock_top_right": "Pravý horní", + "clock_bottom_left": "Levý dolní", + "clock_bottom_right": "Pravý dolní", + "glass_walls": "Skleněné zdi", + "glass_walls_hint": "Jak moc krycí jsou zdi, přes které je vidět do místností: vlevo téměř neviditelné, vpravo neprůhledné. Pro tuto obrazovku.", + "screen_name": "Název této obrazovky", + "screen_name_hint": "Oznámení se zobrazují na každé otevřené obrazovce NextFloor. S názvem (např. „Chodba“) může oznámení směřovat pouze na tuto obrazovku. Bez zaškrtnutí tato obrazovka mlčí.", + "announce_on": "Oznámení na této obrazovce zapnutá", + "announce_muted": "Oznámení na této obrazovce ztlumena", + "lock3d_on": "Zamknout 3D (bez otáčení, přibližování a posouvání; klepnutí stále fungují)", + "lock3d_off": "Odemknout 3D", + "walk": "Projít se po domě", + "travel": "Cestování v čase: přehrát posledních 24 hodin nebo 7 dní", + "travel_play": "Přehrát", + "travel_pause": "Pauza", + "travel_loading": "Načítání historie …", + "travel_failed": "Nepodařilo se načíst historii.", + "travel_speed": "Rychlost", + "travel_speed_min": "1 min/s", + "travel_speed_10min": "10 min/s", + "travel_speed_hour": "1 h/s", + "travel_days": "dní", + "travel_live": "Živě", + "card_travel_button": "Tlačítko cestování v čase", + "walk_stop": "Ukončit procházku", + "walk_hint": "Přetažení: rozhlížení · W A S D / šipky nebo páčka: chůze · kolečko: krok", + "card_walk_button": "Tlačítko procházky", + "card_lock_button": "Tlačítko zámku 3D", + "backdrop": "Vlastní pozadí", + "backdrop_color": "Barva", + "backdrop_image": "Obrázek (/local/… nebo https://…)", + "backdrop_dim": "Ztmavit", + "backdrop_hint": "Místo oblohy vzhledu dům stojí před vlastní barvou nebo obrázkem. Obrázek v /config/www je dostupný pod /local/….", + "furnish": "Vybavit nábytkem", + "split_3d": "3D vedle", + "plan_dims": "Rozměry", + "plan_dims_hint": "Popisuje každou hranu místnosti její délkou.", + "mount_height": "Výška nad podlahou (m)", + "side_open": "Otevřít postranní panel", + "side_close": "Zavřít", + "side_details": "Podrobnosti výběru", + "side_pin": "Připnout", + "side_pinned": "Připnutý", + "side_pin_hint": "Připnutý postranní panel zůstává otevřený; jinak se složí vedle 3D zobrazení, když nic není vybráno", + "split_3d_hint": "Živé 3D vedle plánu: přetahujte a otáčejte tam nábytek a zařízení – s možností vrácení zpět, ukládá se s plánem", + "size_w": "Šířka (m)", + "size_d": "Hloubka (m)", + "size_h": "Výška (m)", + "furnish_hint": "Přetahujte nábytek, lampy a zařízení · nábytek se přichytává ke zdem · klepněte na prvek pro jeho otočení, nastavení výšky a montáže", + "done": "Hotovo", + "heatmap": "Tepelná mapa", + "heat_off": "Normálně", + "heat_short_temperature": "Tepl.", + "heat_short_humidity": "Vlh.", + "heat_short_co2": "CO₂", + "heat_short_mould": "Plíseň", + "heat_short_power": "Výkon", + "heat_short_comfort": "Komfort", + "heat_short_sun": "Slunce", + "heat_short_wifi": "Wi-Fi", + "heat_short_values": "Hodnoty", + "heat_temperature": "Teplota", + "heat_humidity": "Vlhkost", + "heat_co2": "CO₂", + "heat_mould": "Plíseň", + "heat_power": "Příkon", + "heat_comfort": "Ukazatel komfortu", + "heat_sun": "Slunce dnes", + "room_sun_hours": "{h} h slunce dnes ({facing})", + "open_since": "otevřeno od {time}", + "presence_now": "někdo tu je", + "presence_last": "naposledy před {time}", + "comfort_n": "Komfort {n}", + "empty_lights_hint": "{n} světel zapnuto, nikdo tu není {min} min.", + "empty_lights_off": "Vypnout světlo", + "open_heating_hint": "{n} oken otevřených při zapnutém vytápění.", + "open_heating_off": "Vypnout vytápění", + "room_clean": "Úklid (skript nebo tlačítko)", + "room_clean_hint": "Skript nebo tlačítko, které pošle robotický vysavač do této místnosti (např. úklid pokoje z vaší integrace). Panel místnosti pak zobrazí „🧹 Vysát“.", + "room_clean_run": "Vysát", + "room_clean_run_hint": "Pošle robotický vysavač do této místnosti.", + "shade_hint": "Slunce na {n} oknech při {temp} – zatáhnout rolety?", + "shade_close": "Zatáhnout", + "room_sun_year": "Slunce v průběhu roku", + "room_sun_year_hint": "Hodin slunce přes vnější okna místnosti 15. dne každého měsíce.", + "room_energy": "dnes {today} · měsíc {month}", + "room_energy_hint": "Ze statistik snímačů výkonu zařízení v místnosti; cena za měsíc podle tarifu domu.", + "heat_summer": "Léto", + "heat_winter": "Zima", + "air_co2": "vyvětrat (CO₂)", + "air_humidity": "vyvětrat (vlhkost)", + "air_mould": "riziko plísně – vyvětrat", + "room_curve_hint": "Teplota místnosti v posledních 24 hodinách", + "heat_values": "Hodnoty u názvů místností", + "heat_wifi": "Wi-Fi", + "wifi_aps": "{n} přístupových bodů · {clients} zařízení", + "wifi_network": "Síť: {online} online · {offline} offline", + "wifi_none": "Nastavte přístupové body nebo směrovače z balíčků (Chytrý dům 2) a propojte je s entitou jejich zařízení.", + "wifi_clients": "{n} zařízení", + "heat_none_found": "Žádné odpovídající snímače v oblastech místností.", + "markers": "Značky", + "markers_none": "Žádné", + "markers_important": "Důležité", + "markers_all": "Všechny", + "furn_stool": "Stolička", + "furn_coffee_table": "Konferenční stolek", + "furn_tv_wall": "TV (nástěnná)", + "furn_sideboard": "Příborník", + "furn_table_round": "Kulatý stůl", + "furn_bench": "Lavice", + "furn_corner_bench": "Rohová lavice", + "furn_bar_stool": "Barová židle", + "furn_kitchen_wall": "Závěsná skříňka", + "furn_kitchen_tall": "Vysoká skříňka s troubou", + "furn_island": "Kuchyňský ostrůvek", + "furn_dishwasher": "Myčka", + "furn_bunk_bed": "Patrová postel", + "furn_dresser": "Komoda", + "furn_washer": "Pračka", + "furn_dryer": "Sušička", + "furn_office_chair": "Kancelářská židle", + "furn_tall_cabinet": "Vysoká skříň", + "furn_coat_rack": "Věšák", + "furn_group_living": "Bydlení", + "furn_group_dining": "Jídelna", + "furn_group_energy": "Energie a fotovoltaika", + "energy_devices": "Zařízení", + "wallbox_charging": "nabíjení", + "wallbox_plugged": "připojeno", + "furn_soc": "Stav nabití (%)", + "furn_export": "Dodávaný výkon (W, samostatný snímač, volitelně)", + "furn_export_hint": "Pokud elektroměr hlásí odběr a dodávání ve dvou snímačích (např. Growatt, Tibber Pulse), použijte snímač odběru jako výkon výše a snímač dodávání zde. Snímač se znaménkem to nepotřebuje.", + "meter_parent": "Připojeno k elektroměru", + "meter_parent_none": "žádný (hlavní elektroměr)", + "meter_main": "Hlavní elektroměr", + "meter_unmetered": "{w} neměřeno", + "meter_device_hint": "Pokud je zařízení za podružným elektroměrem (např. balkónová elektrárna v bytě), jeho výkon se započítává do tohoto bytu. Podružný elektroměr musí měřit v obou směrech (− = dodávání); pokud měří pouze odběr, vychází spotřeba bytu při přebytku příliš vysoká.", + "meter_sub_power": "Výkon okruhu (W, + = odběr, − = dodávání)", + "meter_floors": "Napájí podlaží", + "meter_sub_hint": "Podružný elektroměr měří svůj okruh, např. byt. Zařízení na vybraných podlažích jsou v 3D připojena pod něj místo pod hlavní elektroměr; to, co hlavní elektroměr měří nad to, se v bilanci zobrazí jako „Společné (zbytek)“.", + "furn_charge": "Nabíjecí výkon (W, samostatný snímač, volitelně)", + "furn_charge_hint": "Pokud úložiště hlásí nabíjení a vybíjení ve dvou snímačích (např. Anker Solix), použijte snímač vybíjení jako výkon výše a snímač nabíjení zde. Snímač se znaménkem to nepotřebuje.", + "furn_wallbox_status": "Stav (nabíjení, připojeno)", + "energy_only_note": "⚡ Energie: zde lze posouvat pouze solární pole a energetická zařízení; místnosti a nábytek jsou uzamčeny.", + "roof_only_note": "🏠 Střecha: zde lze posouvat pouze střešní roviny a okna; místnosti a nábytek jsou uzamčeny.", + "energy_devices_hint": "Elektroměr, střídače, úložiště energie, wallboxy a připojení k síti se přidávají zde: na podlaží vybraném výše, posuvné v plánu. Se snímačem výkonu zobrazují své watty; elektroměr přebírá snímač sítě, string vybírá svůj střídač. Funguje i více střídačů a úložišť (např. dodatečná balkónová elektrárna): každý s vlastním snímačem.", + "energy_routes": "Trasy kabelů", + "energy_routes_hint": "Kde skutečně běží kabel: tok pak sleduje vaše body místo oblouku přes dům. Bez trasy zůstává oblouk. Spotřebiče si zachovávají svůj oblouk.", + "route_conn_solar": "{name} → střídač", + "route_conn_battery": "Baterie ↔ dům", + "route_conn_inverter": "Střídač → dům", + "route_conn_grid": "Síť ↔ dům", + "route_conn_meter": "{name} ↔ nadřazený elektroměr", + "route_conn_device": "{name} ↔ podružný elektroměr", + "route_points": "{n} bodů", + "route_none": "přímý oblouk", + "route_draw": "Kreslit trasu", + "route_redraw": "Nakreslit znovu", + "route_drawing": "Klepněte na plánu body, kterými běží kabel, od jednoho konce k druhému; mezitím změňte podlaží tam, kde prochází stropem. {n} bodů.", + "route_undo": "Poslední bod", + "route_done": "Hotovo", + "route_cable": "Zobrazit jako kabel", + "route_cable_hint": "Kreslí trasu jako viditelný kabel, nikoli pouze tenkou čáru pod částicemi.", + "solar_fields": "Solární pole", + "solar_hint": "Položte moduly na střechu: leží ve sklonu roviny; na ploché střeše stojí na konstrukcích. Přetáhněte pole v plánu pro jeho posun.", + "solar_no_roof": "Solární pole potřebují střechu: sedlovou nebo plochou v Nastavení nebo střešní roviny zde v nástroji Střecha.", + "solar_face_gone": "chybí rovina", + "solar_summary": "{n} modulů · {kwp} kWp", + "solar_add": "Solární pole", + "solar_field": "Solární pole", + "solar_face": "Střešní rovina", + "solar_rows": "Řady", + "solar_cols": "Moduly v řadě", + "solar_portrait": "Na výšku", + "solar_landscape": "Na šířku", + "solar_u": "Vzdálenost od hrany (m)", + "solar_v": "Vzdálenost od okapu (m)", + "solar_tilt": "Sklon konstrukcí (°)", + "solar_rack_ew": "Konstrukce východ-západ", + "solar_rack_ew_hint": "Každá druhá řada směřuje na druhou stranu, páry stojí zády k sobě – nízko a hustě, jako na mnoha plochých střechách.", + "solar_rack_tilt": "Konstrukce (° dodatečného sklonu)", + "solar_flip": "Sklopit na druhou stranu", + "solar_partial": "na rovinu se vejde pouze {n} z {total}", + "solar_form_hint": "Moduly přesahující rovinu se přeskakují. „Vyplnit rovinu“ položí tolik modulů, kolik se vejde. kWp počítáno při 400 W na modul.", + "solar_fit": "Vyplnit rovinu", + "roof_windows": "Střešní okna", + "roof_window": "Střešní okno", + "roof_windows_hint": "Střešní okna leží v rovině, s roletou a kontakty jako okna. Přetahujte je v plánu, i na jinou rovinu.", + "roof_window_tilt": "Kontakt vyklopení", + "roof_window_name": "Název (volitelně)", + "roof_window_motor": "Motor okna (stínění, volitelně)", + "roof_window_motor_hint": "Motor okna (Velux, Roto, Fakro) hlásí pozici jako stínění: křídlo se v 3D otevírá tak, jak stojí motor. Kontakt nebo kontakt vyklopení funguje i bez motoru.", + "roof_window_hint": "Otevřené křídlo se vyklápí ven na pantu nahoře; vyklopené – trochu; rám svítí teplo; roleta sjíždí na sklo shora. Ve střešní rovině okno vyřezává otvor ve sklonu, aby přes něj podkroví vypadalo.", + "solar_ground": "Volně stojící (zahrada, střecha garáže …)", + "solar_add_ground": "Volně stojící", + "solar_base": "Výška plochy (m, 0 = terén)", + "solar_add_wall": "Na zdi", + "solar_wall": "Zeď", + "solar_v_wall": "Výška nad podlahou (m)", + "solar_tilt_wall": "Odklon od zdi (°, 90 = stříška)", + "solar_flip_wall": "Odstávající dole místo nahoře", + "solar_rotation": "Otočení (°)", + "solar_name": "Název", + "solar_name_hint": "např. string 1 jih", + "solar_module_w": "Šířka modulu (m)", + "solar_module_h": "Výška modulu (m)", + "solar_wp": "Výkon modulu (Wp)", + "solar_string": "String", + "solar_strings": "Stringy", + "solar_string_none": "Bez stringu", + "solar_string_new": "Nový string", + "solar_string_n": "String {n}", + "solar_string_name": "Název stringu", + "solar_string_entity": "PV výkon stringu", + "solar_string_inverter": "Střídač", + "solar_string_inverter_none": "Není vybrán střídač", + "inverter_strings": "Stringy na tomto střídači: {names}", + "inverter_strings_none": "Žádný string na tomto střídači – přiřaďte jej v solárním poli v String › Střídač.", + "solar_string_inverter_missing": "Chybí střídač v plánu (přidejte jej níže v Zařízeních)", + "solar_string_hint": "Pole v stejném stringu patří k sobě, i na různých střechách (např. 5 modulů na domě a 5 na garáži). Snímač a střídač se počítají pro celý string.", + "solar_string_sum": "{fields} polí · {n} modulů · {kwp} kWp", + "solar_face_size": "Rovina {w} × {h} m (podél okapu × nahoru ve sklonu)", + "solar_cols_hint": "Jedno číslo pro řady stejné délky nebo seznam pro vlastní řady: „4, 4, 3“ (od okapu).", + "solar_align_left": "Vlevo", + "solar_align_center": "Střed", + "solar_align_right": "Vpravo", + "solar_look_black": "Černý", + "solar_look_blue": "Modrý", + "solar_pick": "Moduly zap./vyp. jednotlivě", + "solar_pick_all": "Všechny opět zap.", + "solar_pick_hint": "Klepněte na modul v plánu pro jeho odstranění nebo obnovení. Odstraněné jsou čárkované.", + "solar_entity": "PV výkon tohoto pole (např. jeho stringu)", + "solar_main": "Hlavní střecha", + "solar_section": "Rovina {n}", + "solar_flat": "plochá střecha", + "compass_n": "sever", + "compass_ne": "severovýchod", + "compass_e": "východ", + "compass_se": "jihovýchod", + "compass_s": "jih", + "compass_sw": "jihozápad", + "compass_w": "západ", + "compass_nw": "severozápad", + "furn_meter": "Elektroměr", + "furn_grid_point": "Připojení k síti", + "grid_point_hint": "Zde stojí připojení k síti: předávací bod dodavateli, např. na konci příjezdové cesty. Posuvné v plánu.", + "furn_model": "Model", + "inverter_std": "Standardní (nástěnná jednotka s displejem)", + "inverter_slim": "Úzký a vysoký (světelný pás)", + "inverter_hybrid": "Hybridní (kulatý kotouč, ventilátory)", + "battery_std": "Věž (moduly v sestavě)", + "battery_wall": "Nástěnné úložiště (ploché, závěsné)", + "battery_cube": "Kompaktní (balkónové úložiště)", + "furn_inverter": "Fotovoltaický střídač", + "furn_home_battery": "Úložiště energie", + "furn_wallbox": "Wallbox", + "furn_group_kitchen": "Kuchyně", + "furn_group_sleeping": "Spaní", + "furn_group_bath": "Koupelna a prádlo", + "furn_group_work": "Práce a ostatní", + "furn_entity": "Zařízení (vypínač, zásuvka …)", + "furn_state_entity": "Stav z (volitelně)", + "furn_state_entity2": "Druhý stav (druhá polovina)", + "furn_state_split": "Poloviny", + "furn_state_left_right": "Vlevo / vpravo", + "furn_state_top_bottom": "Dole / nahoře (patrová postel)", + "furn_state_hint": "Prvek svítí, když entita hlásí zap., obsazeno nebo doma – postel se snímačem přítomnosti, křeslo, sauna. Dvě entity podsvěcují poloviny: levou a pravou, dolní a horní v patrové posteli.", + "furn_entity_tv": "TV (přehrávač nebo chytrá zásuvka)", + "fix": "Zamknout", + "unfix": "Odemknout", + "fix_hint": "Zamknutý: nelze jej již náhodně posunout (klávesa L, pravé klepnutí nebo dlouhé podržení)", + "fixed_drag_hint": "🔒 Zamknutý – nejprve odemkněte pro posun (zámek ve formuláři, pravé klepnutí nebo klávesa L)", + "fixed_delete_confirm": "Tento prvek je zamknutý. Přesto odstranit?", + "lock_plan": "🔒 Plán", + "lock_plan_hint": "Zamknout plán: místnosti, zdi, dveře, okna a venkovní terény nelze náhodně posunout. Nábytek a zařízení zůstávají volné.", + "start_view": "Výchozí zobrazení", + "start_view_hint": "3D zobrazení, karta a kiosk otevírají dům v tomto zobrazení, např. ze strany zahrady. Otáčejte, přibližujte a posouvejte dům v panelu 3D vpravo, dokud nebude vyhovovat, pak zapamatujte.", + "start_view_card": "Pokud se karta má otevírat v jiném zobrazení, vložte tento řádek do její konfigurace YAML.", + "start_view_set": "Zapamatovat aktuální 3D zobrazení jako výchozí", + "start_view_reset": "Výchozí", + "start_view_saved": "Uloženo vlastní výchozí zobrazení.", + "ctx_rotate": "Otočit o 90°", + "devices_placed_in": "v {room}", + "devices_narrow": "ještě {n} – zúžit vyhledávání", + "climate": "Klima místnosti", + "climate_temperature": "Teplota", + "climate_humidity": "Vlhkost", + "climate_co2": "CO₂", + "climate_hint": "Tyto snímače se počítají pro tepelnou mapu a panel místnosti. „Automaticky“ přebírá snímače oblasti a umístěné v místnosti, ale nikoli teploty zařízení (3D tiskárna, tepelné čerpadlo, napájení …).", + "climate_more": "… a další snímač (průměr)", + "plan_locked": "Plán zamknut", + "plan_lock": "Zamknout plán", + "plan_unlock": "Odemknout plán", + "opening_mark": "Zvýraznit v 3D", + "opening_mark_open": "Když je otevřeno", + "opening_mark_closed": "Když je zavřeno (např. WC)", + "opening_mark_hint": "Zvýrazněné okno nebo dveře svítí teplo. „Když je zavřeno“ vyžaduje kontakt; bez snímače se nic nezvýrazňuje.", + "window_opens": "Otevírá se", + "window_opens_turn": "Otvíravě-vyklápěcí (dovnitř)", + "window_opens_slide": "Posuvné (posuvné okno, zdvižně-posuvné dveře)", + "window_opens_top": "Vyklápěcí ven (spodek se vyklápí ven)", + "window_opens_hint": "Posuvné: křídlo na straně pantu se posouvá před stálé; při dvou křídlech se dvě střední posouvají do stran. Vyklápěcí okna se otevírají se snímačem kontaktu nebo vyklopení.", + "marker_show": "Značka v 3D", + "marker_show_hint": "Automaticky sleduje přepínač Žádné / Důležité / Všechny 3D zobrazení. Vždy zobrazovat a Skrýt platí nezávisle (kromě Žádné).", + "pin_shift": "Posunout značku", + "pin_shift_up": "↑ výška", + "pin_shift_hint": "Když zařízení stojí blízko sebe, posuňte zde značku trochu do strany nebo nahoru (v metrech); samotné zařízení zůstává na místě.", + "marker_show_auto": "Automaticky", + "marker_show_always": "Vždy zobrazovat", + "marker_show_no_power": "Bez wattů", + "marker_show_active": "Pouze když je aktivní", + "marker_show_never": "Skrýt", + "marker_icon": "Vlastní symbol (ikona Material Design)", + "device_name": "Vlastní název (volitelně)", + "show_name": "Zobrazit název pod značkou v 3D", + "card_marker_names": "Vlastní názvy u značek", + "card_marker_names_hint": "Každé zařízení s vlastním názvem jej zobrazuje malý pod značkou – tři teploměry na zahradě lze rozlišit.", + "device_name_hint": "Název pouze pro plán a panel místnosti, např. \"Akcentové světlo ostrůvku\" – entita v Home Assistant zůstává bez změn.", + "device_simple": "V panelu místnosti jen vypínač", + "device_simple_hint": "Panel místnosti u této lampy ukazuje jen vypínač, bez jasu, teploty barvy a barev.", + "floor_turn": "Otočit o 90°", + "floor_shift_all": "Vzít všechna podlaží (celý dům)", + "floor_shift_all_hint": "Posun a otočení fungují na všechna podlaží se střešními rovinami, venkovními terény, energetickými zařízeními a elektroměrem – celý dům se pohybuje jako celek.", + "floor_turn_hint": "Otočí vše na podlaží o 90° ve směru hodinových ručiček kolem středu místností – když bylo podlaží nakresleno obráceně. Třikrát = 270°.", + "marker_icon_hint": "Název ikony Material Design jako v Home Assistant, např. mdi:thermometer nebo mdi:water-alert. Prázdné = symbol druhu zařízení.", + "furn_power": "Snímač výkonu (W)", + "furn_links_hint": "Se snímačem výkonu prvek zobrazuje své watty a účastní se toku energie.", + "furn_links_hint_tv": "Obrazovka svítí, když je TV zapnutý, v barvě aplikace (Netflix, YouTube …); štítek zobrazuje aplikaci nebo název.", + "stairs_hint": "Schody stoupají dozadu (od vyznačené přední hrany) a otevírají strop podlaží nad nimi.", + "floor_lights": "{n} světel zap.", + "floor_open": "{n} otevřených", + "floor_persons": "{n} osob", + "energy_consumption": "Spotřeba", + "energy_grid_import": "Odběr ze sítě", + "energy_grid_export": "Dodávání", + "energy_solar": "Slunce", + "energy_battery": "Úložiště", + "energy_tariff": "Tarif", + "energy": "Energie", + "energy_meter": "Elektroměr", + "energy_grid": "Síť (W, + = odběr)", + "energy_solar_sensor": "PV výroba (W)", + "energy_battery_sensor": "Výkon úložiště (W, + = vybíjení)", + "energy_battery_soc": "Nabití úložiště (%)", + "energy_tariff_sensor": "Tarif (např. Kč/kWh)", + "energy_gas": "Plynoměr (volitelně)", + "energy_water": "Vodoměr (volitelně)", + "energy_meters_hint": "Plyn a voda se zobrazují u bilance domu – na liště energie a na kartě domu: snímač s aktuálním průtokem (m³/h, l/min) nebo dnešním odečtem.", + "energy_gas_short": "Plyn", + "energy_water_short": "Voda", + "energy_invert": "Obrátit znaménko", + "energy_hint": "Spotřebiče jsou umístěná zařízení se snímačem výkonu (W) – samotný snímač nebo jeden ze stejného zařízení.", + "energy_balance": "Bilance energie", + "energy_balance_hint": "Síť, slunce a úložiště pocházejí ze zařízení v plánu: elektroměru, střídače a úložiště energie. Zde můžete vybrat jiné snímače, obrátit znaménka a nastavit spotřebu domu.", + "energy_rest": "Společné (zbytek)", + "energy_advanced": "Pokročilý režim energie", + "energy_advanced_on": "Používat podružné elektroměry", + "energy_show_unmetered": "Zobrazovat neměřenou spotřebu u podružných elektroměrů", + "energy_show_unmetered_hint": "Štítek podružného elektroměru pak zobrazuje, kolik spotřebovávají jeho podlaží a kolik z toho neměří žádné umístěné zařízení, např. „500 W · 450 W neměřeno“. Jinak zobrazuje odečet elektroměru.", + "energy_advanced_hint": "Pro podružné elektroměry, např. jeden pro byt za hlavním elektroměrem: elektroměr pak může viset pod jiným a napájet vlastní podlaží. Vyp. = první elektroměr je připojení k síti, další jsou spotřebiče.", + "energy_consumption_sensor": "Spotřeba domu (W, jinak z bilance)", + "energy_import_prefs": "Převzít z panelu energie", + "energy_import_done": "Převzato {n} snímačů – zkontrolujte znaménka.", + "energy_import_none": "V panelu energie nebyly nalezeny žádné odpovídající snímače výkonu (W) – vyberte je ručně.", + "energy_import_failed": "Panel energie Home Assistant není nakonfigurován.", + "tool_meter": "Elektroměr", + "hint_meter": "Klepněte na místo elektroměru", + "presence": "Přítomnost", + "presence_hint": "Snímač místnosti na osobu (např. ESPresense, Bermuda): jeho stav pojmenovává místnost nebo oblast.", + "presence_sensor": "Snímač místnosti", + "no_persons": "V Home Assistant nejsou žádné osoby.", + "packname:nextfloor.a_bad": "Koupelna", + "pack:nextfloor.a_bad:vanity_60": "Skříňka s umyvadlem 60", + "pack:nextfloor.a_bad:vanity_80": "Skříňka s umyvadlem 80", + "pack:nextfloor.a_bad:vanity_100": "Skříňka s umyvadlem 100", + "pack:nextfloor.a_bad:vanity_double_120": "Dvojité umyvadlo 120", + "pack:nextfloor.a_bad:vanity_double_160": "Dvojité umyvadlo", + "pack:nextfloor.a_bad:pedestal_basin": "Umyvadlo na sloupu", + "pack:nextfloor.a_bad:bathtub_builtin": "Vestavěná vana", + "pack:nextfloor.a_bad:bathtub_corner": "Rohová vana", + "pack:nextfloor.a_bad:bathtub_corner_compact": "Kompaktní rohová vana", + "pack:nextfloor.a_bad:bathtub_free": "Volně stojící vana", + "pack:nextfloor.a_bad:whirlpool_indoor": "Vířivá vana", + "pack:nextfloor.a_bad:shower_corner_90": "Rohový kout 90 × 90", + "pack:nextfloor.a_bad:shower_niche_120": "Sprcha ve výklenku 120 × 90", + "pack:nextfloor.a_bad:shower_walkin_140": "Sprcha walk-in 140 × 90", + "pack:nextfloor.a_bad:shower_walkin_120": "Sprcha walk-in", + "pack:nextfloor.a_bad:shower_rain_led": "Dešťová sprcha s LED", + "pack:nextfloor.a_bad:toilet_close": "WC kombi", + "pack:nextfloor.a_bad:toilet_hung": "Závěsné WC", + "pack:nextfloor.a_bad:toilet_hung_compact": "Závěsné WC (kompaktní)", + "pack:nextfloor.a_bad:bidet": "Bidet", + "pack:nextfloor.a_bad:cabinet_tall": "Vysoká koupelnová skříňka", + "pack:nextfloor.a_bad:cabinet_mid": "Střední koupelnová skříňka", + "pack:nextfloor.a_bad:mirror_round_light": "Kulaté zrcadlo s osvětlením", + "pack:nextfloor.a_bad:mirror_80": "Zrcadlo 80 × 60 s osvětlením", + "pack:nextfloor.a_bad:mirror_led_100": "LED zrcadlo 100 × 70 s hodinami", + "pack:nextfloor.a_bad:mirror_cabinet": "Zrcadlová skříňka s osvětlením", + "pack:nextfloor.a_bad:wall_shelf_bath": "Nástěnná koupelnová police", + "pack:nextfloor.a_bad:towel_rail": "Držák na ručníky s ručníkem", + "pack:nextfloor.a_bad:towel_radiator": "Koupelnový žebříkový radiátor", + "pack:nextfloor.a_bad:towel_heater_electric": "Elektrický ohřívač ručníků", + "pack:nextfloor.a_bad:sauna": "Sauna", + "pack:nextfloor.a_bad:bath_fan": "Koupelnový ventilátor", + "pack:nextfloor.a_bad:washer_cabinet": "Skříňka na pračku", + "pack:nextfloor.a_bad:washer_under_vanity": "Pračka pod umyvadlem", + "pack:nextfloor.a_bad:laundry_basket": "Koš na prádlo", + "pack:nextfloor.a_bad:laundry_cabinet": "Skříňka na prádlo s košem", + "pack:nextfloor.a_bad:ladder_shelf": "Police žebřík s ručníky", + "pack:nextfloor.a_bad:plant_stool": "Rostlina na stoličce", + "packname:nextfloor.a_buero": "Kancelář a gaming", + "pack:nextfloor.a_buero:desk_standing": "Výškově stavitelný stůl", + "pack:nextfloor.a_buero:desk_standing_bare": "Stavitelný stůl bez monitoru", + "pack:nextfloor.a_buero:chair_gaming": "Herní křeslo", + "pack:nextfloor.a_buero:chair_office": "Ergonomická kancelářská židle", + "pack:nextfloor.a_buero:sim_cockpit": "Kokpit pro sim racing", + "pack:nextfloor.a_buero:server_rack_42u": "Serverová skříň (42U)", + "pack:nextfloor.a_buero:filing_cabinet": "Skříň na dokumenty", + "pack:nextfloor.a_buero:whiteboard": "Magneziová tabule", + "pack:nextfloor.a_buero:triple_monitor": "Sestava tří monitorů", + "pack:nextfloor.a_buero:bookcase_wall": "Stěna s regály", + "pack:nextfloor.a_buero:desk_lamp": "Stolní lampička", + "pack:nextfloor.a_buero:desk_lamp_led": "LED stolní lampička", + "pack:nextfloor.a_buero:arcade_cabinet": "Arkádový automat", + "pack:nextfloor.a_buero:office_lounge_sofa": "Kancelářská sofa lounge", + "pack:nextfloor.a_buero:monitor_light_bar": "Monitor se světelnou lištou", + "pack:nextfloor.a_buero:printer_laser": "Laserová tiskárna", + "pack:nextfloor.a_buero:wifi_router": "Wi-Fi směrovač", + "pack:nextfloor.a_buero:phone_booth": "Hovorová budka", + "pack:nextfloor.a_buero:printer_3d": "3D tiskárna", + "pack:nextfloor.a_buero:printer_cube": "Uzavřená 3D tiskárna typu kostka", + "pack:nextfloor.a_buero:printer_multi": "3D tiskárna kostka s vícebarevným modulem", + "pack:nextfloor.a_buero:printer_large": "Velká 3D tiskárna se dvěma tryskami", + "pack:nextfloor.a_buero:printer_open": "Kompaktní otevřená 3D tiskárna", + "pack:nextfloor.a_buero:printer_resin": "SLA 3D tiskárna (na pryskyřici)", + "pack:nextfloor.a_buero:filament_dryer": "Sušička filamentu", + "pack:nextfloor.a_buero:filament_rack": "Nástěnný stojan na filament", + "packname:nextfloor.a_fitness": "Fitness", + "pack:nextfloor.a_fitness:treadmill": "Běžecký pás", + "pack:nextfloor.a_fitness:power_rack": "Posilovací klec s lavicí", + "pack:nextfloor.a_fitness:rowing_machine": "Veslovací trenažér", + "pack:nextfloor.a_fitness:spin_bike": "Cyklotrenažér", + "pack:nextfloor.a_fitness:dumbbell_rack": "Stojan na činky", + "pack:nextfloor.a_fitness:punching_bag": "Boxovací pytel", + "pack:nextfloor.a_fitness:yoga_mat": "Podložka na jógu s kostkou", + "pack:nextfloor.a_fitness:elliptical": "Eliptický trenažér", + "pack:nextfloor.a_fitness:mirror_wall_gym": "Zrcadlová stěna", + "pack:nextfloor.a_fitness:exercise_ball": "Gymnastický míč", + "pack:nextfloor.a_fitness:wall_bars": "Nástěnné žebřiny", + "pack:nextfloor.a_fitness:fitness_mirror_smart": "Chytré fitness zrcadlo", + "pack:nextfloor.a_fitness:bike_trainer": "Kolo na chytrém trenažéru", + "pack:nextfloor.a_fitness:sauna_cabin": "Kabina sauny", + "pack:nextfloor.a_fitness:massage_chair": "Masážní křeslo", + "pack:nextfloor.a_fitness:kettlebells": "Sada kettlebellů", + "pack:nextfloor.a_fitness:water_cooler": "Dávkovač vody", + "packname:nextfloor.a_garten": "Zahrada a terasa", + "pack:nextfloor.a_garten:grill_gas": "Plynový gril", + "pack:nextfloor.a_garten:lounge_set": "Zahradní posezení", + "pack:nextfloor.a_garten:sun_lounger_adj": "Lehátko", + "pack:nextfloor.a_garten:parasol": "Slunečník", + "pack:nextfloor.a_garten:pergola": "Pergola", + "pack:nextfloor.a_garten:raised_bed": "Vyvýšený záhon", + "pack:nextfloor.a_garten:greenhouse": "Skleník", + "pack:nextfloor.a_garten:hot_tub": "Zahradní vířivka", + "pack:nextfloor.a_garten:fire_bowl": "Ohniště", + "pack:nextfloor.a_garten:garden_torch": "Zahradní pochodeň", + "pack:nextfloor.a_garten:play_tower": "Hrací věž se skluzavkou", + "pack:nextfloor.a_garten:garden_shed": "Zahradní domek", + "pack:nextfloor.a_garten:trampoline": "Trampolína", + "pack:nextfloor.a_garten:flower_pots": "Květináče (sada 3)", + "pack:nextfloor.a_garten:sprinkler": "Zavlažovač trávníku", + "pack:nextfloor.a_garten:valve_box": "Šachta zavlažovacích ventilů", + "pack:nextfloor.a_garten:rain_barrel": "Sud na dešťovou vodu", + "pack:nextfloor.a_garten:garden_lantern": "Zahradní Lucerna", + "pack:nextfloor.a_garten:outdoor_kitchen": "Zahradní kuchyně", + "pack:nextfloor.a_garten:hammock": "Houpací síť se stojanem", + "pack:nextfloor.a_garten:patio_heater": "Terasový ohřívač", + "pack:nextfloor.a_garten:tree_oak": "Dub", + "pack:nextfloor.a_garten:tree_lime": "Lípa", + "pack:nextfloor.a_garten:tree_birch": "Bříza", + "pack:nextfloor.a_garten:tree_maple": "Javor", + "pack:nextfloor.a_garten:tree_fruit": "Ovocný strom", + "pack:nextfloor.a_garten:tree_spruce": "Smrk", + "pack:nextfloor.a_garten:tree_pine": "Borovice", + "pack:nextfloor.a_garten:tree_thuja": "Tuje", + "pack:nextfloor.a_garten:shrub": "Keř", + "pack:nextfloor.a_garten:shrub_flowering": "Kvetoucí keř", + "pack:nextfloor.a_garten:brush_wild": "Hustí (divoký koutek)", + "pack:nextfloor.a_garten:tree_group_3": "Skupina stromů (3)", + "pack:nextfloor.a_garten:bin_rest_120": "Popelnice na směsný odpad 120 l", + "pack:nextfloor.a_garten:bin_rest_240": "Popelnice na směsný odpad 240 l", + "pack:nextfloor.a_garten:bin_bio_120": "Popelnice na bioodpad 120 l", + "pack:nextfloor.a_garten:bin_bio_240": "Popelnice na bioodpad 240 l", + "pack:nextfloor.a_garten:bin_paper_120": "Popelnice na papír 120 l", + "pack:nextfloor.a_garten:bin_paper_240": "Popelnice na papír 240 l", + "pack:nextfloor.a_garten:bin_yellow_120": "Popelnice na plasty 120 l", + "pack:nextfloor.a_garten:bin_yellow_240": "Popelnice na plasty 240 l", + "pack:nextfloor.a_garten:mailbox": "Poštovní schránka", + "pack:nextfloor.a_garten:mailbox_post": "Poštovní schránka na sloupku", + "pack:nextfloor.a_garten:awning_300": "Markýza 3 m", + "pack:nextfloor.a_garten:awning_400": "Markýza 4 m", + "pack:nextfloor.a_garten:awning_500": "Markýza 5 m", + "pack:nextfloor.a_garten:sliding_gate": "Posuvná brána", + "packname:nextfloor.a_haustechnik": "Hospodářství a instalace", + "pack:nextfloor.a_haustechnik:gas_boiler": "Plynový kondenzační kotel", + "pack:nextfloor.a_haustechnik:heat_pump_tower": "Vnitřní jednotka tepelného čerpadla (hydraulická věž)", + "pack:nextfloor.a_haustechnik:buffer_tank": "Akumulační nádrž", + "pack:nextfloor.a_haustechnik:heating_manifold": "Rozdělovač podlahového topení", + "pack:nextfloor.a_haustechnik:ventilation_unit": "Rekuperační jednotka", + "pack:nextfloor.a_haustechnik:split_indoor": "Klimatizace split (vnitřní nástěnná jednotka)", + "pack:nextfloor.a_haustechnik:split_outdoor": "Klimatizace split (venkovní jednotka)", + "pack:nextfloor.a_haustechnik:radiator_tall": "Vysoký designový radiátor", + "pack:nextfloor.a_haustechnik:meter_cabinet": "Elektroměrový rozvaděč", + "pack:nextfloor.a_haustechnik:water_softener": "Změkčovač vody", + "pack:nextfloor.a_haustechnik:water_pump": "Domácí vodárna", + "pack:nextfloor.a_haustechnik:drip_tray": "Vana se snímačem úniku", + "pack:nextfloor.a_haustechnik:chest_freezer": "Pultový mrazák", + "pack:nextfloor.a_haustechnik:ironing_station": "Žehlička s parním generátorem", + "pack:nextfloor.a_haustechnik:drying_rack": "Sušák na prádlo", + "pack:nextfloor.a_haustechnik:rotary_line": "Vnější otočný sušák", + "pack:nextfloor.a_haustechnik:pantry_shelf_util": "Spížní regál", + "pack:nextfloor.a_haustechnik:utility_sink": "Hospodářský dřez", + "pack:nextfloor.a_haustechnik:laundry_basket_util": "Koš na prádlo", + "pack:nextfloor.a_haustechnik:vacuum_station": "Stanice pro tyčový vysavač", + "packname:nextfloor.a_haustiere": "Domácí mazlíčci", + "pack:nextfloor.a_haustiere:cat_tree_large": "Škrabadlo pro kočky (velké)", + "pack:nextfloor.a_haustiere:scratch_post": "Škrabací sloupek", + "pack:nextfloor.a_haustiere:scratch_board_wall": "Nástěnné škrabadlo", + "pack:nextfloor.a_haustiere:cat_cave": "Kukaň pro kočku", + "pack:nextfloor.a_haustiere:cat_bed_round": "Kulatý pelíšek pro kočku", + "pack:nextfloor.a_haustiere:cat_wall_shelf": "Nástěnná police pro kočku", + "pack:nextfloor.a_haustiere:cat_steps": "Schůdky pro kočku", + "pack:nextfloor.a_haustiere:litter_covered": "Krytá kočičí toaleta", + "pack:nextfloor.a_haustiere:litter_auto": "Samočisticí kočičí toaleta", + "pack:nextfloor.a_haustiere:dog_bed": "Pelíšek pro psa", + "pack:nextfloor.a_haustiere:dog_basket": "Koš pro psa", + "pack:nextfloor.a_haustiere:dog_house": "Psí bouda", + "pack:nextfloor.a_haustiere:pet_bowls": "Misky na krmivo a vodu", + "pack:nextfloor.a_haustiere:pet_feeder": "Automatické krmítko", + "pack:nextfloor.a_haustiere:pet_fountain": "Fontánka na pití", + "pack:nextfloor.a_haustiere:pet_gate": "Zábrana pro zvířata", + "pack:nextfloor.a_haustiere:pet_stairs": "Schůdky pro zvířata", + "pack:nextfloor.a_haustiere:hamster_cage": "Klec pro křečka", + "pack:nextfloor.a_haustiere:small_animal_cage": "Klec pro malá zvířata", + "pack:nextfloor.a_haustiere:rabbit_run": "Výběh pro králíky (venkovní)", + "pack:nextfloor.a_haustiere:bird_cage": "Klec pro ptáky", + "pack:nextfloor.a_haustiere:aquarium_100": "Akvárium 100 l", + "pack:nextfloor.a_haustiere:aquarium_240": "Akvárium 240 l se skříňkou", + "pack:nextfloor.a_haustiere:terrarium": "Terárium", + "pack:nextfloor.a_haustiere:pet_cat": "Kočka (chodí po domě)", + "pack:nextfloor.a_haustiere:pet_dog": "Pes (chodí po domě)", + "pack:nextfloor.a_haustiere:pet_rabbit": "Králík (skáče po domě)", + "packname:nextfloor.a_kinderzimmer": "Dětský pokoj", + "pack:nextfloor.a_kinderzimmer:loft_bed_slide": "Patrová postel se skluzavkou", + "pack:nextfloor.a_kinderzimmer:teepee": "Stan týpí", + "pack:nextfloor.a_kinderzimmer:play_kitchen": "Dětská kuchyňka", + "pack:nextfloor.a_kinderzimmer:kids_desk": "Dětský psací stůl", + "pack:nextfloor.a_kinderzimmer:toy_shelf": "Regál na hračky s boxy", + "pack:nextfloor.a_kinderzimmer:cosy_corner": "Útulný koutek", + "pack:nextfloor.a_kinderzimmer:rocking_horse": "Houpací kůň", + "pack:nextfloor.a_kinderzimmer:play_mat_road": "Kobercová dráha se silnicemi", + "pack:nextfloor.a_kinderzimmer:kids_table_2": "Dětský stůl se 2 židlemi", + "pack:nextfloor.a_kinderzimmer:moon_light": "Noční lampička měsíc", + "pack:nextfloor.a_kinderzimmer:ball_pit": "Bazének s kuličkami", + "pack:nextfloor.a_kinderzimmer:house_bed": "Postel domeček", + "pack:nextfloor.a_kinderzimmer:baby_monitor": "Dětská chůvička s kamerou", + "pack:nextfloor.a_kinderzimmer:star_projector": "Projektor hvězd", + "pack:nextfloor.a_kinderzimmer:kids_cot": "Postýlka", + "pack:nextfloor.a_kinderzimmer:kids_changing_table": "Přebalovací pult", + "pack:nextfloor.a_kinderzimmer:kids_wardrobe": "Dětská skříň", + "pack:nextfloor.a_kinderzimmer:toy_boxes_3": "Boxy na hračky (3)", + "packname:nextfloor.a_kino": "Domácí kino a hi-fi", + "pack:nextfloor.a_kino:screen_wall": "Promítací plátno (nástěnné)", + "pack:nextfloor.a_kino:screen_roll": "Roletové promítací plátno", + "pack:nextfloor.a_kino:projector_ceiling": "Projektor (stropní)", + "pack:nextfloor.a_kino:projector_table": "Projektor (stolní)", + "pack:nextfloor.a_kino:speaker_floor": "Sloupový reproduktor", + "pack:nextfloor.a_kino:speaker_shelf": "Regálový reproduktor", + "pack:nextfloor.a_kino:speaker_centre": "Centrální reproduktor", + "pack:nextfloor.a_kino:subwoofer": "Subwoofer", + "pack:nextfloor.a_kino:soundbar": "Soundbar", + "pack:nextfloor.a_kino:soundbar_premium": "Prémiový soundbar", + "pack:nextfloor.a_kino:speaker_wall": "Nástěnný reproduktor", + "pack:nextfloor.a_kino:speaker_ceiling": "Stropní reproduktor", + "pack:nextfloor.a_kino:av_receiver": "AV přijímač", + "pack:nextfloor.a_kino:turntable": "Gramofon", + "pack:nextfloor.a_kino:record_shelf": "Police na desky", + "pack:nextfloor.a_kino:game_console": "Herní konzole", + "pack:nextfloor.a_kino:hifi_rack": "Hi-fi skříňka", + "pack:nextfloor.a_kino:cinema_seat": "Kinosedačka", + "pack:nextfloor.a_kino:cinema_row_3": "Řada kinosedaček (3)", + "pack:nextfloor.a_kino:acoustic_panel": "Akustický panel", + "pack:nextfloor.a_kino:bass_trap": "Rohová basová past", + "pack:nextfloor.a_kino:popcorn_maker": "Popkornovač", + "pack:nextfloor.a_kino:star_ceiling": "Hvězdné nebe", + "pack:nextfloor.a_kino:smart_speaker_ball": "Chytrý reproduktor (koule)", + "pack:nextfloor.a_kino:smart_speaker_cylinder": "Chytrý reproduktor (válec)", + "pack:nextfloor.a_kino:smart_speaker_puck": "Chytrý reproduktor (puk)", + "pack:nextfloor.a_kino:smart_speaker_pod": "Chytrý reproduktor (pod)", + "pack:nextfloor.a_kino:smart_speaker_tall": "Chytrý reproduktor (vysoký)", + "pack:nextfloor.a_kino:smart_speaker_oval": "Chytrý reproduktor (oválný)", + "pack:nextfloor.a_kino:multiroom_compact": "Kompaktní multiroom reproduktor", + "pack:nextfloor.a_kino:speaker_portable": "Přenosný reproduktor", + "pack:nextfloor.a_kino:display_5": "Chytrý displej 5″", + "pack:nextfloor.a_kino:display_8": "Chytrý displej 8″", + "pack:nextfloor.a_kino:display_7_float": "Chytrý displej 7″ (plovoucí)", + "pack:nextfloor.a_kino:display_15_wall": "Chytrý displej 15″ (nástěnný)", + "pack:nextfloor.a_kino:speaker_stand": "Stojan na reproduktor", + "packname:nextfloor.a_kueche": "Kuchyně", + "pack:nextfloor.a_kueche:base_30": "Spodní skříňka 30", + "pack:nextfloor.a_kueche:base_40": "Spodní skříňka 40", + "pack:nextfloor.a_kueche:base_50": "Spodní skříňka 50", + "pack:nextfloor.a_kueche:base_60": "Spodní skříňka 60", + "pack:nextfloor.a_kueche:base_80": "Spodní skříňka 80", + "pack:nextfloor.a_kueche:base_90": "Spodní skříňka 90", + "pack:nextfloor.a_kueche:base_100": "Spodní skříňka 100", + "pack:nextfloor.a_kueche:base_120": "Spodní skříňka 120", + "pack:nextfloor.a_kueche:drawer_40": "Zásuvková skříňka 40", + "pack:nextfloor.a_kueche:drawer_50": "Zásuvková skříňka 50", + "pack:nextfloor.a_kueche:drawer_60": "Zásuvková skříňka 60", + "pack:nextfloor.a_kueche:drawer_80": "Zásuvková skříňka 80", + "pack:nextfloor.a_kueche:drawer_90": "Zásuvková skříňka 90", + "pack:nextfloor.a_kueche:drawer_100": "Zásuvková skříňka 100", + "pack:nextfloor.a_kueche:drawer_120": "Zásuvková skříňka 120", + "pack:nextfloor.a_kueche:sink_60": "Dřezová skříňka 60", + "pack:nextfloor.a_kueche:sink_80": "Dřezová skříňka 80", + "pack:nextfloor.a_kueche:sink_100": "Dřezová skříňka 100", + "pack:nextfloor.a_kueche:hob_60": "Skříňka pod varnou desku 60", + "pack:nextfloor.a_kueche:hob_80": "Skříňka pod varnou desku 80", + "pack:nextfloor.a_kueche:cooker_60": "Sporák s troubou 60", + "pack:nextfloor.a_kueche:dishwasher_60": "Vestavná myčka 60", + "pack:nextfloor.a_kueche:dishwasher_45": "Vestavná myčka 45", + "pack:nextfloor.a_kueche:base_corner": "Rohová spodní skříňka", + "pack:nextfloor.a_kueche:wall_40": "Závěsná skříňka 40", + "pack:nextfloor.a_kueche:wall_50": "Závěsná skříňka 50", + "pack:nextfloor.a_kueche:wall_60": "Závěsná skříňka 60", + "pack:nextfloor.a_kueche:wall_80": "Závěsná skříňka 80", + "pack:nextfloor.a_kueche:wall_90": "Závěsná skříňka 90", + "pack:nextfloor.a_kueche:wall_100": "Závěsná skříňka 100", + "pack:nextfloor.a_kueche:wall_120": "Závěsná skříňka 120", + "pack:nextfloor.a_kueche:wall_glass_80": "Skleněná závěsná skříňka 80", + "pack:nextfloor.a_kueche:wall_corner": "Rohová závěsná skříňka", + "pack:nextfloor.a_kueche:hood_wall": "Nástěnnou digestoř", + "pack:nextfloor.a_kueche:hood_island": "Ostrůvková digestoř", + "pack:nextfloor.a_kueche:tall_pantry": "Vysoká potravinová skříň", + "pack:nextfloor.a_kueche:tall_oven": "Vysoká skříň s troubou a mikrovlnkou", + "pack:nextfloor.a_kueche:tall_fridge": "Vysoká skříň s lednicí a mrazákem", + "pack:nextfloor.a_kueche:tall_steam": "Vysoká skříň s parní troubou", + "pack:nextfloor.a_kueche:fridge_freezer": "Kombinovaná lednice s mrazákem", + "pack:nextfloor.a_kueche:fridge_french": "Lednice French door", + "pack:nextfloor.a_kueche:wine_fridge": "Vinotéka", + "pack:nextfloor.a_kueche:glass_cabinet": "Vitrína", + "pack:nextfloor.a_kueche:row_270": "Lineární kuchyně 270", + "pack:nextfloor.a_kueche:row_330": "Lineární kuchyně 330", + "pack:nextfloor.a_kueche:island_bar": "Kuchyňský ostrůvek s barem", + "pack:nextfloor.a_kueche:island_hob": "Kuchyňský ostrůvek s varnou deskou", + "pack:nextfloor.a_kueche:breakfast_bar": "Snídaňový bar (nástěnný)", + "pack:nextfloor.a_kueche:bar_stools_2": "Barové židle (sada 2)", + "pack:nextfloor.a_kueche:dining_bench_long": "Dlouhý jídelní stůl s lavicí", + "pack:nextfloor.a_kueche:dining_round_4": "Kulatý jídelní stůl se 4 židlemi", + "pack:nextfloor.a_kueche:high_table_2": "Barový stůl se 2 židlemi", + "pack:nextfloor.a_kueche:kitchen_trolley": "Kuchyňský vozík", + "pack:nextfloor.a_kueche:pantry_shelf": "Spížní regál", + "pack:nextfloor.a_kueche:spice_rack": "Nástěnná police na koření", + "pack:nextfloor.a_kueche:coffee_machine": "Automatický kávovar", + "pack:nextfloor.a_kueche:microwave": "Mikrovlnná trouba", + "pack:nextfloor.a_kueche:stand_mixer": "Kuchyňský robot", + "pack:nextfloor.a_kueche:kettle": "Rychlovarná konvice", + "pack:nextfloor.a_kueche:toaster": "Toustovač", + "pack:nextfloor.a_kueche:herb_garden": "Chytrá bylinková zahrádka", + "pack:nextfloor.a_kueche:pendant_trio": "Tři závěsné lampy", + "pack:nextfloor.a_kueche:pendant_linear": "Liniové závěsné svítidlo", + "pack:nextfloor.a_kueche:cabinet_light_60": "LED osvětlení pod skříňku 60", + "pack:nextfloor.a_kueche:cabinet_light_80": "LED osvětlení pod skříňku 80", + "pack:nextfloor.a_kueche:range_cooker_90": "Volně stojící sporák 90", + "packname:nextfloor.a_schlafzimmer": "Ložnice", + "pack:nextfloor.a_schlafzimmer:bed_90": "Postel 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_140": "Postel 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_160": "Postel 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_180": "Postel 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_200": "Postel 200 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_180": "Čalouněná postel 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_140": "Čalouněná postel 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_boxspring": "Kontinentální postel 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_futon": "Futonová postel 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_storage": "Postel s úložným prostorem 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_canopy": "Postel s nebesy", + "pack:nextfloor.a_schlafzimmer:bed_ambient": "Postel 180 s podsvícením", + "pack:nextfloor.a_schlafzimmer:bed_bench": "Lavice k posteli", + "pack:nextfloor.a_schlafzimmer:shoe_bench": "Botník s lavicí", + "pack:nextfloor.a_schlafzimmer:wardrobe_2": "Skříň dvoudveřová", + "pack:nextfloor.a_schlafzimmer:wardrobe_3": "Skříň třídveřová", + "pack:nextfloor.a_schlafzimmer:wardrobe_4": "Skříň čtyřdveřová", + "pack:nextfloor.a_schlafzimmer:wardrobe_6": "Skříň šestidveřová", + "pack:nextfloor.a_schlafzimmer:wardrobe_mirror": "Skříň se zrcadlovými dveřmi", + "pack:nextfloor.a_schlafzimmer:wardrobe_sliding": "Skříň s posuvnými dveřmi", + "pack:nextfloor.a_schlafzimmer:wardrobe_light": "Skříň s vnitřním osvětlením", + "pack:nextfloor.a_schlafzimmer:wardrobe_corner": "Rohová skříň", + "pack:nextfloor.a_schlafzimmer:walk_in_closet": "Otevřená šatna", + "pack:nextfloor.a_schlafzimmer:clothes_rail": "Šatní stojan", + "pack:nextfloor.a_schlafzimmer:nightstand": "Noční stolek se zásuvkou", + "pack:nextfloor.a_schlafzimmer:nightstand_slim": "Úzký noční stolek", + "pack:nextfloor.a_schlafzimmer:nightstand_floating": "Závěsný noční stolek", + "pack:nextfloor.a_schlafzimmer:dresser_6": "Komoda se 6 zásuvkami 140", + "pack:nextfloor.a_schlafzimmer:chest_tall_5": "Vysoká komoda se 5 zásuvkami", + "pack:nextfloor.a_schlafzimmer:chest_tall": "Vysoká komoda", + "pack:nextfloor.a_schlafzimmer:chest_80": "Komoda se 3 zásuvkami 80", + "pack:nextfloor.a_schlafzimmer:vanity_table": "Toaletní stolek se zrcadlem", + "pack:nextfloor.a_schlafzimmer:dressing_table_light": "Toaletní stolek s podsvíceným zrcadlem", + "pack:nextfloor.a_schlafzimmer:cot": "Dětská postýlka", + "pack:nextfloor.a_schlafzimmer:changing_table": "Přebalovací pult", + "pack:nextfloor.a_schlafzimmer:standing_mirror": "Stojací zrcadlo", + "pack:nextfloor.a_schlafzimmer:reading_nook": "Čtenářský koutek s křeslem", + "pack:nextfloor.a_schlafzimmer:bedside_lamp": "Stolní lampička k posteli", + "pack:nextfloor.a_schlafzimmer:touch_lamp": "Dotyková lampička k posteli", + "pack:nextfloor.a_schlafzimmer:humidifier": "Zvlhčovač vzduchu", + "pack:nextfloor.a_schlafzimmer:sunrise_clock": "Budík se simulací svítání", + "packname:nextfloor.a_smart": "Chytrý dům a technika", + "pack:nextfloor.a_smart:wallbox": "Wallbox", + "pack:nextfloor.a_smart:electric_car": "Elektromobil", + "pack:nextfloor.a_smart:heat_pump_outdoor": "Tepelné čerpadlo (venkovní jednotka)", + "pack:nextfloor.a_smart:home_battery": "Úložiště energie", + "pack:nextfloor.a_smart:inverter_solar": "Fotovoltaický střídač", + "pack:nextfloor.a_smart:robot_vacuum": "Robotický vysavač se stanicí", + "pack:nextfloor.a_smart:mower_garage": "Robotická sekačka s garáží", + "pack:nextfloor.a_smart:washer_dryer_stack": "Sestava pračky a sušičky", + "pack:nextfloor.a_smart:network_rack": "Datový rozvaděč", + "pack:nextfloor.a_smart:smart_display": "Chytrý displej", + "pack:nextfloor.a_smart:solar_balcony": "Balkónový solární panel", + "pack:nextfloor.a_smart:fuse_box": "Jističová skříň", + "pack:nextfloor.a_smart:nas_server": "NAS server", + "pack:nextfloor.a_smart:hot_water_tank": "Zásobník teplé vody", + "pack:nextfloor.a_smart:light_pillar": "Světelný sloup s gradientem", + "pack:nextfloor.a_smart:light_bars_tv": "Dvojice světelných lišt (TV)", + "pack:nextfloor.a_smart:orb_lamp": "Svítící koule na stůl", + "pack:nextfloor.a_smart:glow_lamp_portable": "Přenosné svítidlo", + "pack:nextfloor.a_smart:mood_spot": "Náladový spot na stůl", + "pack:nextfloor.a_smart:cube_lamp": "Kostková lampa", + "pack:nextfloor.a_smart:ceiling_panel_round": "Kulatý stropní panel", + "pack:nextfloor.a_smart:garden_spots_3": "Zahradní reflektory (sada 3)", + "pack:nextfloor.a_smart:wall_light_updown": "Venkovní svítidlo nahoru-dolů", + "pack:nextfloor.a_smart:siren_strobe": "Siréna se stroboskopem", + "pack:nextfloor.a_smart:access_point": "Wi-Fi přístupový bod (stropní)", + "pack:nextfloor.a_smart:smoke_detector": "Kouřový snímač", + "pack:nextfloor.a_smart:thermostat_wall": "Nástěnný termostat", + "pack:nextfloor.a_smart:dehumidifier": "Odvlhčovač vzduchu", + "pack:nextfloor.a_smart:ceiling_fan": "Stropní ventilátor", + "pack:nextfloor.a_smart:ceiling_fan_light": "Stropní ventilátor s osvětlením", + "pack:nextfloor.a_smart:light_switch_1": "Vypínač světla, jednoduchý", + "pack:nextfloor.a_smart:socket_1": "Zásuvka, jednoduchá", + "pack:nextfloor.a_smart:light_switch_2": "Vypínač světla, dvojitý", + "pack:nextfloor.a_smart:socket_2": "Zásuvka, dvojitá", + "pack:nextfloor.a_smart:light_switch_3": "Vypínač světla, trojitý", + "pack:nextfloor.a_smart:socket_3": "Zásuvka, trojitá", + "pack:nextfloor.a_smart:light_switch_4": "Vypínač světla, čtyřnásobný", + "pack:nextfloor.a_smart:socket_4": "Zásuvka, čtyřnásobná", + "pack:nextfloor.a_smart:socket_outdoor": "Venkovní Zásuvka s víčkem", + "packname:nextfloor.a_wohnzimmer": "Obývací pokoj", + "pack:nextfloor.a_wohnzimmer:sofa_2": "Dvoumístná pohovka", + "pack:nextfloor.a_wohnzimmer:sofa_3": "Třímístná pohovka", + "pack:nextfloor.a_wohnzimmer:sofa_4": "Velká čtyřmístná pohovka", + "pack:nextfloor.a_wohnzimmer:sofa_velvet": "Sametová třímístná pohovka", + "pack:nextfloor.a_wohnzimmer:sofa_armless": "Pohovka bez područek", + "pack:nextfloor.a_wohnzimmer:sofa_chaise": "Pohovka s lenoškou", + "pack:nextfloor.a_wohnzimmer:sofa_chesterfield": "Pohovka Chesterfield", + "pack:nextfloor.a_wohnzimmer:sofa_bed": "Rozkládací pohovka", + "pack:nextfloor.a_wohnzimmer:sofa_corner_l": "Rohová pohovka (levá)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_r": "Rohová pohovka (pravá)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_xl": "Velká rohová pohovka (ve tvaru L)", + "pack:nextfloor.a_wohnzimmer:sofa_u": "Pohovka ve tvaru U", + "pack:nextfloor.a_wohnzimmer:chaise_longue": "Lenoška", + "pack:nextfloor.a_wohnzimmer:modular_sofa": "Modulární pohovka (5 částí)", + "pack:nextfloor.a_wohnzimmer:armchair": "Křeslo", + "pack:nextfloor.a_wohnzimmer:club_chair": "Klubové křeslo", + "pack:nextfloor.a_wohnzimmer:wingback": "Křeslo ušák", + "pack:nextfloor.a_wohnzimmer:cocktail_chair": "Koktejlové křeslo", + "pack:nextfloor.a_wohnzimmer:recliner": "Relaxační křeslo s podnožkou", + "pack:nextfloor.a_wohnzimmer:bean_bag": "Sedací vak", + "pack:nextfloor.a_wohnzimmer:pouf": "Taburet", + "pack:nextfloor.a_wohnzimmer:rocking_chair": "Houpací křeslo", + "pack:nextfloor.a_wohnzimmer:coffee_rect": "Obdélníkový konferenční stolek", + "pack:nextfloor.a_wohnzimmer:coffee_glass": "Skleněný konferenční stolek", + "pack:nextfloor.a_wohnzimmer:coffee_round": "Kulatý konferenční stolek", + "pack:nextfloor.a_wohnzimmer:coffee_nesting": "Sada konferenčních stolků", + "pack:nextfloor.a_wohnzimmer:side_round": "Kulatý odkládací stolek", + "pack:nextfloor.a_wohnzimmer:console": "Konzolový stolek", + "pack:nextfloor.a_wohnzimmer:dining_120": "Jídelní stůl 120 × 90", + "pack:nextfloor.a_wohnzimmer:dining_160": "Jídelní stůl 160 × 90", + "pack:nextfloor.a_wohnzimmer:dining_200": "Jídelní stůl 200 × 90", + "pack:nextfloor.a_wohnzimmer:dining_220": "Stůl z masivního dřeva 220 × 100", + "pack:nextfloor.a_wohnzimmer:chair_wood": "Dřevěná židle", + "pack:nextfloor.a_wohnzimmer:chair_upholstered": "Čalouněná židle", + "pack:nextfloor.a_wohnzimmer:chair_shell": "Skořepinová židle", + "pack:nextfloor.a_wohnzimmer:dining_bench": "Jídelní lavice 160", + "pack:nextfloor.a_wohnzimmer:lowboard_120": "TV stolek 120", + "pack:nextfloor.a_wohnzimmer:lowboard_160": "TV stolek 160", + "pack:nextfloor.a_wohnzimmer:lowboard_200": "TV stolek 200", + "pack:nextfloor.a_wohnzimmer:sideboard_160": "Příborník 160", + "pack:nextfloor.a_wohnzimmer:highboard": "Vysoká komoda", + "pack:nextfloor.a_wohnzimmer:display_cabinet": "Vitrína", + "pack:nextfloor.a_wohnzimmer:chest_3": "Komoda se 3 zásuvkami", + "pack:nextfloor.a_wohnzimmer:bookshelf_tall": "Vysoká knihovna", + "pack:nextfloor.a_wohnzimmer:bookshelf_wide": "Široká knihovna", + "pack:nextfloor.a_wohnzimmer:cube_2x2": "Regál kostka 2 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x2": "Regál kostka 4 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x4": "Regál kostka 4 × 4", + "pack:nextfloor.a_wohnzimmer:divider_open": "Dělící regál", + "pack:nextfloor.a_wohnzimmer:wall_shelf": "Závěsná police", + "pack:nextfloor.a_wohnzimmer:coat_stand": "Stojací věšák", + "pack:nextfloor.a_wohnzimmer:wall_unit_vitrines": "Obývací stěna s vitrínami", + "pack:nextfloor.a_wohnzimmer:wall_unit_tv": "Obývací stěna s TV", + "pack:nextfloor.a_wohnzimmer:tv_on_stand": "TV na stojanu", + "pack:nextfloor.a_wohnzimmer:media_wall": "Multimediální stěna s TV", + "pack:nextfloor.a_wohnzimmer:wood_stove": "Krbová kamna na dřevo", + "pack:nextfloor.a_wohnzimmer:fireplace_wall": "Nástěnný elektrický krb", + "pack:nextfloor.a_wohnzimmer:piano": "Pianino s stoličkou", + "pack:nextfloor.a_wohnzimmer:floor_lamp_arc": "Oblouková stojací lampa", + "pack:nextfloor.a_wohnzimmer:floor_lamp_tripod": "Stojací lampa trojnožka", + "pack:nextfloor.a_wohnzimmer:table_lamp_ceramic": "Keramická stolní lampa", + "pack:nextfloor.a_wohnzimmer:vase_pampas": "Podlahová váza s pampovou trávou", + "pack:nextfloor.a_wohnzimmer:monstera": "Velká monstera", + "pack:nextfloor.a_wohnzimmer:rug_round": "Kulatý koberec", + "pack:nextfloor.a_wohnzimmer:rug_240": "Koberec 240 × 170", + "pack:nextfloor.a_wohnzimmer:painting_light": "Obraz s osvětlením", + "pack:nextfloor.a_wohnzimmer:shelf_led": "Regál s LED policemi", + "pack:nextfloor.a_wohnzimmer:air_purifier": "Čistička vzduchu", + "pack:nextfloor.a_wohnzimmer:tower_fan": "Sloupový ventilátor", + "pack:nextfloor.a_wohnzimmer:smart_speaker_living": "Chytrý reproduktor", + "packname:nextfloor.ausbau": "Architektura a dokončení", + "pack:nextfloor.ausbau:column_round": "Kulatý sloup", + "pack:nextfloor.ausbau:column_square": "Hranatý sloup", + "pack:nextfloor.ausbau:beam": "Stropní trám", + "pack:nextfloor.ausbau:chimney": "Komín", + "pack:nextfloor.ausbau:glass_wall": "Skleněná příčka", + "pack:nextfloor.ausbau:sliding_wall": "Posuvná stěna", + "pack:nextfloor.ausbau:platform": "Podesta", + "pack:nextfloor.ausbau:half_wall": "Polozeď", + "pack:nextfloor.ausbau:divider_shelf": "Dělící regál", + "pack:nextfloor.ausbau:pilaster": "Pilastr", + "pack:nextfloor.ausbau:column_steel": "Ocelový sloup", + "pack:nextfloor.ausbau:beams_wood_5": "Dřevěné stropní trámy (5)", + "pack:nextfloor.ausbau:beam_downstand": "Průvlak", + "pack:nextfloor.ausbau:fireplace_builtin": "Vestavěný krb", + "pack:nextfloor.ausbau:divider_slats": "Lamelová dělící příčka", + "pack:nextfloor.ausbau:curtain_motor": "Motorický závěs", + "pack:nextfloor.ausbau:niche_shelf": "Police ve výklenku", + "pack:nextfloor.ausbau:niche_led": "LED výklenek", + "pack:nextfloor.ausbau:light_cove": "Světelný podhled (strop)", + "pack:nextfloor.ausbau:gallery_rail_glass": "Zábradlí mezipatra (sklo)", + "pack:nextfloor.ausbau:window_seat": "Okenní sedátko", + "pack:nextfloor.ausbau:curtain_pair": "Závěs (rozhrnovaný do obou stran)", + "pack:nextfloor.ausbau:roller_blind_inside": "Vnitřní roleta", + "packname:nextfloor.bad": "Koupelna – doplňky", + "pack:nextfloor.bad:double_vanity": "Dvojité umyvadlo", + "pack:nextfloor.bad:walkin_shower": "Sprcha walk-in", + "pack:nextfloor.bad:towel_radiator": "Koupelnový žebříkový radiátor", + "pack:nextfloor.bad:mirror_cabinet": "Zrcadlová skříňka s osvětlením", + "pack:nextfloor.bad:washer_tower": "Sestava pračky a sušičky", + "pack:nextfloor.bad:laundry_basket": "Koš na prádlo", + "pack:nextfloor.bad:bath_shelf": "Koupelnová police", + "packname:nextfloor.energie": "Energie a instalace", + "pack:nextfloor.energie:heat_pump": "Tepelné čerpadlo (venkovní jednotka)", + "pack:nextfloor.energie:pellet_boiler": "Kotel na pelety", + "pack:nextfloor.energie:buffer_tank": "Akumulační nádrž", + "pack:nextfloor.energie:hot_water_tank": "Zásobník teplé vody", + "pack:nextfloor.energie:home_battery": "Úložiště energie (věž)", + "pack:nextfloor.energie:inverter": "Střídač", + "pack:nextfloor.energie:wallbox": "Wallbox", + "pack:nextfloor.energie:meter_cabinet": "Elektroměrový rozvaděč", + "pack:nextfloor.energie:ventilation": "Vzduchotechnická jednotka", + "pack:nextfloor.energie:solar_carport_pillar": "Sloup solárního přístřešku", + "packname:nextfloor.fahrzeuge": "Vozidla", + "pack:nextfloor.fahrzeuge:tesla_model_s": "Tesla Model S", + "packname:nextfloor.a_saison": "Sezóna a dekorace", + "packname:nextfloor.a_smart2": "Chytrý dům 2", + "packname:nextfloor.a_haustechnik2": "Instalace 2", + "packname:nextfloor.a_wellness": "Wellness", + "packname:nextfloor.a_garten2": "Zahrada 2", + "packname:nextfloor.a_kueche2": "Kuchyně 2", + "packname:nextfloor.a_fahrzeuge2": "Vozidla 2", + "packname:nextfloor.a_aussenkueche": "Zahradní kuchyně a terasa", + "packname:nextfloor.a_werkstatt2": "Dílna 2", + "packname:nextfloor.a_japandi": "Japandi a skandinávský", + "packname:nextfloor.a_loft": "Loft a industriální", + "packname:nextfloor.a_gruen": "Pokojové rostliny", + "packname:nextfloor.a_musik": "Hudba a ateliér", + "pack:nextfloor.a_saison:xmas_tree": "Vánoční stromeček s osvětlením", + "pack:nextfloor.a_saison:advent_wreath": "Adventní věnec", + "pack:nextfloor.a_saison:lights_outdoor": "Venkovní světelný řetěz", + "pack:nextfloor.a_saison:window_star": "Okenní hvězda", + "pack:nextfloor.a_saison:candle_arch": "Svíčkový oblouk", + "pack:nextfloor.a_saison:reindeer_light": "Svítící sob", + "pack:nextfloor.a_saison:pumpkin": "Dýně", + "pack:nextfloor.a_saison:pumpkin_lantern": "Dýňová svítilna", + "pack:nextfloor.a_saison:easter_tree": "Velikonoční stromek", + "pack:nextfloor.a_saison:snowman": "Sněhulák", + "pack:nextfloor.a_saison:gift_pile": "Dárky", + "pack:nextfloor.a_smart2:siren": "Siréna", + "pack:nextfloor.a_smart2:access_point": "Wi-Fi přístupový bod", + "pack:nextfloor.a_smart2:access_point_wall": "Wi-Fi přístupový bod (nástěnný)", + "pack:nextfloor.a_smart2:smoke_detector": "Kouřový snímač", + "pack:nextfloor.a_smart2:co_detector": "Snímač CO", + "pack:nextfloor.a_smart2:dehumidifier": "Odvlhčovač vzduchu", + "pack:nextfloor.a_smart2:cube_lamp": "Kostková lampa", + "pack:nextfloor.a_smart2:presence_ceiling": "Snímač přítomnosti (stropní)", + "pack:nextfloor.a_smart2:water_leak": "Snímač úniku vody", + "pack:nextfloor.a_smart2:air_quality": "Snímač kvality vzduchu", + "pack:nextfloor.a_smart2:doorbell_cam": "Videozvonek", + "pack:nextfloor.a_haustechnik2:water_tank": "Nádrž na vodu", + "pack:nextfloor.a_haustechnik2:oil_tank": "Nádrž na olej", + "pack:nextfloor.a_haustechnik2:oil_boiler": "Olejový kotel", + "pack:nextfloor.a_haustechnik2:water_softener": "Změkčovač vody", + "pack:nextfloor.a_haustechnik2:buffer_tank": "Akumulační nádrž", + "pack:nextfloor.a_haustechnik2:cistern": "Nádrž na dešťovou vodu", + "pack:nextfloor.a_haustechnik2:ventilation_unit": "Rekuperační jednotka", + "pack:nextfloor.a_haustechnik2:expansion_vessel": "Expanzní nádoba", + "pack:nextfloor.a_haustechnik2:heat_pump_indoor": "Tepelné čerpadlo (vnitřní jednotka)", + "pack:nextfloor.a_wellness:sauna_cabin": "Sauna", + "pack:nextfloor.a_wellness:sauna_barrel": "Sudová sauna", + "pack:nextfloor.a_wellness:infrared_cabin": "Infrasauna", + "pack:nextfloor.a_wellness:hot_tub": "Vířivka", + "pack:nextfloor.a_wellness:plunge_pool": "Ochlazovací bazének", + "pack:nextfloor.a_wellness:steam_shower": "Parní sprcha", + "pack:nextfloor.a_wellness:relax_lounger": "Relaxační lehátko", + "pack:nextfloor.a_wellness:cold_bath": "Ledová koupel", + "pack:nextfloor.a_garten2:water_feature": "Vodní prvek s osvětlením", + "pack:nextfloor.a_garten2:pond": "Jezírko s čerpadlem", + "pack:nextfloor.a_garten2:robot_mower": "Robotická sekačka", + "pack:nextfloor.a_garten2:mower_dock": "Nabíjecí stanice sekačky", + "pack:nextfloor.a_garten2:sandbox": "Pískoviště", + "pack:nextfloor.a_garten2:beach_chair": "Plážový koš", + "pack:nextfloor.a_garten2:wood_pile": "Hranice dřeva", + "pack:nextfloor.a_garten2:bird_house": "Krmítko pro ptáky", + "pack:nextfloor.a_garten2:raised_bed": "Vyvýšený záhon", + "pack:nextfloor.a_garten2:garden_shower": "Zahradní sprcha", + "pack:nextfloor.a_kueche2:coffee_machine": "Automatický kávovar", + "pack:nextfloor.a_kueche2:espresso": "Pákový kávovar", + "pack:nextfloor.a_kueche2:kettle": "Rychlovarná konvice", + "pack:nextfloor.a_kueche2:toaster": "Toustovač", + "pack:nextfloor.a_kueche2:stand_mixer": "Kuchyňský robot", + "pack:nextfloor.a_kueche2:thermo_cooker": "Varný robot", + "pack:nextfloor.a_kueche2:air_fryer": "Horkovzdušná fritéza", + "pack:nextfloor.a_kueche2:microwave": "Mikrovlnná trouba", + "pack:nextfloor.a_kueche2:wine_fridge": "Vinotéka", + "pack:nextfloor.a_kueche2:water_bar": "Výrobník perlivé vody", + "pack:nextfloor.a_kueche2:dishwasher_slim": "Myčka 45 cm", + "pack:nextfloor.a_fahrzeuge2:motorbike": "Motocykl", + "pack:nextfloor.a_fahrzeuge2:scooter": "Skútr", + "pack:nextfloor.a_fahrzeuge2:camper_van": "Obytné auto", + "pack:nextfloor.a_fahrzeuge2:trailer": "Přívěs", + "pack:nextfloor.a_fahrzeuge2:e_bike": "Elektrokolo", + "pack:nextfloor.a_fahrzeuge2:cargo_bike": "Nákladní kolo", + "pack:nextfloor.a_fahrzeuge2:quad": "Čtyřkolka", + "pack:nextfloor.a_fahrzeuge2:boat_trailer": "Přívěs s lodí", + "pack:nextfloor.a_aussenkueche:outdoor_kitchen": "Venkovní kuchyně", + "pack:nextfloor.a_aussenkueche:kamado": "Grill kamado", + "pack:nextfloor.a_aussenkueche:pizza_oven": "Pec na pizzu", + "pack:nextfloor.a_aussenkueche:fire_pit": "Ohniště", + "pack:nextfloor.a_aussenkueche:patio_heater": "Terasový ohřívač", + "pack:nextfloor.a_aussenkueche:outdoor_fridge": "Venkovní lednice", + "pack:nextfloor.a_aussenkueche:bar_counter": "Barový pult", + "pack:nextfloor.a_aussenkueche:bar_stool_out": "Venkovní barová židle", + "pack:nextfloor.a_aussenkueche:hanging_chair": "Závěsné křeslo", + "pack:nextfloor.a_werkstatt2:workbench_wall": "Pracovní stůl s nástěnnou deskou", + "pack:nextfloor.a_werkstatt2:drill_press": "Stolní vrtačka", + "pack:nextfloor.a_werkstatt2:table_saw": "Stolní kotoučová pila", + "pack:nextfloor.a_werkstatt2:compressor": "Kompresor", + "pack:nextfloor.a_werkstatt2:welder": "Svářečka", + "pack:nextfloor.a_werkstatt2:heavy_shelf": "Skladový regál", + "pack:nextfloor.a_werkstatt2:parts_cabinet": "Organizér na drobnosti", + "pack:nextfloor.a_werkstatt2:tool_chest": "Nářaďový vozík", + "pack:nextfloor.a_werkstatt2:ev_bike_charger": "Stanice pro nabíjení akumulátorů", + "pack:nextfloor.a_japandi:low_bed": "Nízká postel", + "pack:nextfloor.a_japandi:tatami": "Tatami", + "pack:nextfloor.a_japandi:paper_lamp": "Papírová stojací lampa", + "pack:nextfloor.a_japandi:paper_pendant": "Papírové závěsné svítidlo", + "pack:nextfloor.a_japandi:tea_table": "Nízký čajový stolek", + "pack:nextfloor.a_japandi:shoji_screen": "Paraván šódži", + "pack:nextfloor.a_japandi:bonsai": "Bonsaj", + "pack:nextfloor.a_japandi:floor_cushion": "Podlahový polštář", + "pack:nextfloor.a_japandi:wood_bench": "Dřevěná lavice", + "pack:nextfloor.a_japandi:rattan_chair": "Ratanové křeslo", + "pack:nextfloor.a_loft:steel_shelf": "Ocelový regál", + "pack:nextfloor.a_loft:factory_pendant": "Industriální závěsné svítidlo", + "pack:nextfloor.a_loft:leather_sofa": "Kožená pohovka", + "pack:nextfloor.a_loft:plank_table": "Stůl z prken", + "pack:nextfloor.a_loft:locker": "Kovová skříňka", + "pack:nextfloor.a_loft:edison_floor_lamp": "Stojací lampa Edison", + "pack:nextfloor.a_loft:bar_stool_loft": "Industriální barová židle", + "pack:nextfloor.a_loft:pipe_shelf": "Police z trubek", + "pack:nextfloor.a_gruen:monstera": "Monstera", + "pack:nextfloor.a_gruen:ficus": "Fíkus", + "pack:nextfloor.a_gruen:olive_tree": "Olivovník v květináči", + "pack:nextfloor.a_gruen:cactus_group": "Kaktusy", + "pack:nextfloor.a_gruen:hanging_plant": "Převislá rostlina", + "pack:nextfloor.a_gruen:plant_shelf": "Regál na rostliny s osvětlením", + "pack:nextfloor.a_gruen:vertical_garden": "Vertikální zahrada", + "pack:nextfloor.a_gruen:grow_light": "Růstová lampa pro rostliny", + "pack:nextfloor.a_gruen:herb_planter": "Chytrá bylinková zahrádka", + "pack:nextfloor.a_musik:upright_piano": "Pianino", + "pack:nextfloor.a_musik:grand_piano": "Klavírní křídlo", + "pack:nextfloor.a_musik:drum_kit": "Bicí souprava", + "pack:nextfloor.a_musik:guitar_stand": "Kytary na stojanech", + "pack:nextfloor.a_musik:guitar_amp": "Kytarový zesilovač", + "pack:nextfloor.a_musik:mixing_desk": "Studiový stůl s mixážním pultem", + "pack:nextfloor.a_musik:studio_monitor": "Studiový monitor", + "pack:nextfloor.a_musik:synth": "Syntetizér", + "pack:nextfloor.a_musik:mic_stand": "Mikrofon na stojanu", + "pack:nextfloor.a_musik:easel": "Malířský stojan", + "pack:nextfloor.a_musik:vinyl_player": "Gramofon", + "packname:nextfloor.a_bilder": "Obrázky a rámečky", + "pack:nextfloor.a_bilder:frame_landscape": "Rámeček (na šířku)", + "pack:nextfloor.a_bilder:frame_portrait": "Rámeček (na výšku)", + "pack:nextfloor.a_bilder:frame_square": "Rámeček (čtvercový)", + "pack:nextfloor.a_bilder:frame_large": "Velký rámeček", + "pack:nextfloor.a_bilder:canvas": "Obraz na plátně", + "pack:nextfloor.a_bilder:poster": "Plakát", + "pack:nextfloor.a_bilder:frame_table": "Stolní rámeček", + "pack:nextfloor.a_bilder:frame_digital": "Digitální fotorámeček", + "pack:nextfloor.a_bilder:picture_ledge": "Lišta na obrázky", + "color:pearl_white": "Perleťově bílá", + "color:solid_black": "Plně černá", + "color:midnight_silver": "Půlnoční stříbrná", + "color:quicksilver": "Quicksilver", + "color:deep_blue": "Hluboká modrá", + "color:ultra_red": "Ultra červená", + "color:midnight_cherry": "Půlnoční višňová", + "pack:nextfloor.fahrzeuge:tesla_model_3": "Tesla Model 3", + "color:red": "Červená Multi-Coat", + "color:stealth_grey": "Stealth Grey", + "pack:nextfloor.fahrzeuge:tesla_model_x": "Tesla Model X", + "pack:nextfloor.fahrzeuge:tesla_model_y": "Tesla Model Y", + "pack:nextfloor.fahrzeuge:tesla_cybertruck": "Tesla Cybertruck", + "color:stainless": "Nerezová ocel", + "color:wrap_black": "Fólie Satin Black", + "color:wrap_white": "Fólie Satin White", + "color:wrap_grey": "Fólie Satin Grey", + "color:wrap_blue": "Fólie Satin Blue", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024": "Tesla Model 3 (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024_performance": "Tesla Model 3 Performance (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_s_plaid": "Tesla Model S Plaid", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025": "Tesla Model Y Standard (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_premium": "Tesla Model Y Premium (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_performance": "Tesla Model Y Performance (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_l": "Tesla Model Y L", + "pack:nextfloor.fahrzeuge:tesla_roadster": "Tesla Roadster", + "pack:nextfloor.fahrzeuge:tesla_semi": "Tesla Semi", + "pack:nextfloor.fahrzeuge:ev_suv": "Elektrické SUV (velikost Model Y)", + "pack:nextfloor.fahrzeuge:small_car": "Malé auto", + "pack:nextfloor.fahrzeuge:estate_car": "Kombi", + "pack:nextfloor.fahrzeuge:van": "Dodávka", + "pack:nextfloor.fahrzeuge:bicycle": "Jízdní kolo", + "pack:nextfloor.fahrzeuge:ebike": "Elektrokolo", + "pack:nextfloor.fahrzeuge:motorbike": "Motocykl", + "pack:nextfloor.fahrzeuge:trailer": "Přívěs", + "pack:nextfloor.fahrzeuge:sedan": "Sedan", + "pack:nextfloor.fahrzeuge:coupe": "Sportovní coupé", + "pack:nextfloor.fahrzeuge:convertible": "Kabriolet (otevřený)", + "pack:nextfloor.fahrzeuge:small_ev": "Malý elektromobil", + "pack:nextfloor.fahrzeuge:suv": "SUV", + "pack:nextfloor.fahrzeuge:family_van": "Rodinná dodávka", + "pack:nextfloor.fahrzeuge:minibus": "Minibus", + "pack:nextfloor.fahrzeuge:panel_van": "Furgon", + "pack:nextfloor.fahrzeuge:pickup": "Pickup", + "pack:nextfloor.fahrzeuge:campervan": "Obytná dodávka (zvedací střecha)", + "pack:nextfloor.fahrzeuge:motorhome": "Obytný automobil", + "pack:nextfloor.fahrzeuge:caravan": "Obytný přívěs", + "packname:nextfloor.fitness": "Fitness (starší)", + "pack:nextfloor.fitness:treadmill": "Běžecký pás", + "pack:nextfloor.fitness:bike_trainer": "Rotoped", + "pack:nextfloor.fitness:rower": "Veslovací trenažér", + "pack:nextfloor.fitness:weight_bench": "Posilovací lavice", + "pack:nextfloor.fitness:power_rack": "Posilovací klec", + "pack:nextfloor.fitness:yoga_mat": "Podložka na jógu", + "pack:nextfloor.fitness:dumbbell_rack": "Stojan na činky", + "packname:nextfloor.garten": "Zahrada a terasa (starší)", + "pack:nextfloor.garten:sun_lounger": "Lehátko", + "pack:nextfloor.garten:garden_table": "Zahradní stůl", + "pack:nextfloor.garten:garden_chair": "Zahradní židle", + "pack:nextfloor.garten:lounge_set": "Zahradní posezení", + "pack:nextfloor.garten:parasol": "Slunečník", + "pack:nextfloor.garten:gas_grill": "Plynový gril", + "pack:nextfloor.garten:fire_bowl": "Ohniště", + "pack:nextfloor.garten:pool": "Bazén", + "pack:nextfloor.garten:hot_tub": "Vířivka", + "pack:nextfloor.garten:trampoline": "Trampolína", + "pack:nextfloor.garten:greenhouse": "Skleník", + "pack:nextfloor.garten:raised_bed": "Vyvýšený záhon", + "pack:nextfloor.garten:garden_shed": "Zahradní domek", + "pack:nextfloor.garten:swing_bench": "Houpací lavice", + "pack:nextfloor.garten:mower_robot": "Robotická sekačka", + "pack:nextfloor.garten:tree_oak": "Listnatý strom", + "pack:nextfloor.garten:tree_birch": "Bříza", + "pack:nextfloor.garten:tree_fruit": "Ovocný strom", + "pack:nextfloor.garten:conifer": "Jehličnatý strom", + "pack:nextfloor.garten:shrub": "Keř", + "pack:nextfloor.garten:shrub_flowering": "Kvetoucí keř", + "pack:nextfloor.garten:hedge": "Živý plot", + "pack:nextfloor.garten:lawn_brush": "Roští", + "pack:nextfloor.garten:bike_rack": "Stojan na kola", + "pack:nextfloor.garten:bin_box": "Kryt na popelnice (4)", + "packname:nextfloor.ikea": "Rozměry IKEA", + "pack:nextfloor.ikea:billy": "Regál 80x202 (rozměr Billy)", + "pack:nextfloor.ikea:billy_low": "Regál 80x106 (rozměr Billy)", + "pack:nextfloor.ikea:kallax_2x2": "Regál kostka 2x2 (rozměr Kallax)", + "pack:nextfloor.ikea:kallax_2x4": "Regál kostka 2x4 (rozměr Kallax)", + "pack:nextfloor.ikea:kallax_4x4": "Regál kostka 4x4 (rozměr Kallax)", + "pack:nextfloor.ikea:lack_side": "Stolek 55x55 (rozměr Lack)", + "pack:nextfloor.ikea:lack_coffee": "Konferenční stolek 90x55 (rozměr Lack)", + "pack:nextfloor.ikea:malm_bed_140": "Postel 140x200 (rozměr Malm)", + "pack:nextfloor.ikea:malm_bed_160": "Postel 160x200 (rozměr Malm)", + "pack:nextfloor.ikea:malm_chest_6": "Komoda se 6 zásuvkami (rozměr Malm)", + "pack:nextfloor.ikea:malm_chest_4": "Komoda se 4 zásuvkami (rozměr Malm)", + "pack:nextfloor.ikea:pax_100": "Skříň 100x236 (rozměr Pax)", + "pack:nextfloor.ikea:pax_150": "Skříň 150x236 (rozměr Pax)", + "pack:nextfloor.ikea:poang": "Křeslo (rozměr Poäng)", + "pack:nextfloor.ikea:ektorp_2": "Dvoumístná pohovka (rozměr Ektorp)", + "pack:nextfloor.ikea:ektorp_3": "Třímístná pohovka (rozměr Ektorp)", + "pack:nextfloor.ikea:bekant": "Psací stůl 160x80 (rozměr Bekant)", + "pack:nextfloor.ikea:alex": "Zásuvkový díl (rozměr Alex)", + "pack:nextfloor.ikea:besta_tv": "TV stolek 180x42 (rozměr Bestå)", + "pack:nextfloor.ikea:ivar": "Borovicový regál 89x179 (rozměr Ivar)", + "packname:nextfloor.kino": "Domácí kino a gaming", + "pack:nextfloor.kino:projection_screen": "Promítací plátno", + "pack:nextfloor.kino:projector": "Projektor", + "pack:nextfloor.kino:floor_speaker": "Sloupový reproduktor", + "pack:nextfloor.kino:subwoofer": "Subwoofer", + "pack:nextfloor.kino:soundbar": "Soundbar", + "pack:nextfloor.kino:gaming_desk": "Herní stůl", + "pack:nextfloor.kino:gaming_chair": "Herní křeslo", + "pack:nextfloor.kino:game_console": "Herní konzole", + "pack:nextfloor.kino:arcade": "Arkádový automat", + "pack:nextfloor.kino:media_wall": "Multimediální stěna s TV", + "pack:nextfloor.kino:media_rack": "Multimediální skříňka", + "packname:nextfloor.kueche": "Kuchyně – doplňky", + "pack:nextfloor.kueche:coffee_machine": "Kávovar", + "pack:nextfloor.kueche:microwave": "Mikrovlnná trouba", + "pack:nextfloor.kueche:hood_island": "Ostrůvková digestoř", + "pack:nextfloor.kueche:wine_fridge": "Vinotéka", + "pack:nextfloor.kueche:stand_mixer": "Kuchyňský robot", + "pack:nextfloor.kueche:toaster": "Toustovač", + "pack:nextfloor.kueche:kettle": "Rychlovarná konvice", + "pack:nextfloor.kueche:long_dining_table": "Dlouhý jídelní stůl", + "pack:nextfloor.kueche:bar_cart": "Servírovací vozík", + "pack:nextfloor.kueche:trash_station": "Stanice na tříděný odpad", + "packname:nextfloor.schlafen": "Spaní a děti", + "pack:nextfloor.schlafen:boxspring": "Kontinentální postel", + "pack:nextfloor.schlafen:baby_crib": "Dětská postýlka", + "pack:nextfloor.schlafen:changing_table": "Přebalovací pult", + "pack:nextfloor.schlafen:vanity_table": "Toaletní stolek", + "pack:nextfloor.schlafen:clothes_rail": "Šatní stojan", + "pack:nextfloor.schlafen:loft_bed_desk": "Patrová postel s psacím stolem", + "pack:nextfloor.schlafen:toy_box": "Truhla na hračky", + "packname:nextfloor.technik": "Kancelář a homelab", + "pack:nextfloor.technik:standing_desk": "Výškově stavitelný stůl", + "pack:nextfloor.technik:server_rack": "Serverová skříň (19 palců)", + "pack:nextfloor.technik:nas": "NAS", + "pack:nextfloor.technik:printer_3d": "3D tiskárna", + "pack:nextfloor.technik:office_printer": "Tiskárna", + "pack:nextfloor.technik:router": "Směrovač / přístupový bod", + "pack:nextfloor.technik:tower_pc": "Počítač typu tower", + "pack:nextfloor.technik:filing_cabinet": "Zásuvkový díl", + "packname:nextfloor.treppen": "Schody a zábradlí", + "pack:nextfloor.treppen:stairs_straight": "Přímé schody", + "pack:nextfloor.treppen:stairs_l": "L-schody s podestou", + "pack:nextfloor.treppen:stairs_u": "U-schody", + "pack:nextfloor.treppen:stairs_spiral": "Točité schody", + "pack:nextfloor.treppen:stairs_compact": "Úsporné schody", + "pack:nextfloor.treppen:landing": "Podesta", + "pack:nextfloor.treppen:steps_outdoor": "Venkovní schody", + "pack:nextfloor.treppen:rail_metal": "Kovové zábradlí", + "pack:nextfloor.treppen:rail_glass": "Skleněné zábradlí", + "pack:nextfloor.treppen:rail_wood": "Dřevěné zábradlí", + "pack:nextfloor.treppen:stairs_floating": "Konzolové schody (vznášející se)", + "pack:nextfloor.treppen:stairs_u_winder": "Otevřené U-schody s navíjením", + "pack:nextfloor.treppen:rail_corner": "Rohové zábradlí", + "packname:nextfloor.werkstatt": "Garáž a dílna", + "pack:nextfloor.werkstatt:workbench": "Pracovní stůl", + "pack:nextfloor.werkstatt:tool_cabinet": "Nářaďová skříň", + "pack:nextfloor.werkstatt:tool_chest": "Nářaďový vozík", + "pack:nextfloor.werkstatt:shelf_rack": "Skladový regál", + "pack:nextfloor.werkstatt:tyre_stack": "Stoh pneumatik", + "pack:nextfloor.werkstatt:drill_press": "Sloupová vrtačka", + "pack:nextfloor.werkstatt:compressor": "Kompresor", + "pack:nextfloor.werkstatt:bike_stand": "Stojan na kolo", + "pack:nextfloor.werkstatt:paint_cabinet": "Skříň na barvy", + "pack:nextfloor.werkstatt:tool_wall": "Nářaďová stěna", + "pack:nextfloor.werkstatt:heavy_shelf": "Těžký regál", + "pack:nextfloor.werkstatt:chest_freezer_garage": "Pultový mrazák", + "pack:nextfloor.werkstatt:tyre_rack": "Stojan na pneumatiky", + "pack:nextfloor.werkstatt:lawn_mower": "Sekačka", + "pack:nextfloor.werkstatt:bike_stand_2": "Stojan se 2 koly", + "pack:nextfloor.werkstatt:workshop_light": "Dílenské svítidlo", + "pack:nextfloor.werkstatt:garage_opener": "Pohon garážových vrat", + "pack:nextfloor.werkstatt:wallbox_holder": "Wallbox s držákem na kabel", + "pack:nextfloor.werkstatt:wall_bike_holder": "Nástěnný držák na kola (2)", + "pack:nextfloor.werkstatt:workshop_vacuum": "Dílenský vysavač", + "pack:nextfloor.werkstatt:workshop_cabinet": "Dílenská skříň", + "pack:nextfloor.werkstatt:printer_enclosed": "Uzavřená 3D tiskárna", + "packname:nextfloor.wohnen": "Bydlení a zvířata", + "pack:nextfloor.wohnen:corner_sofa": "Rohová pohovka (ve tvaru L)", + "pack:nextfloor.wohnen:bean_bag": "Sedací vak", + "pack:nextfloor.wohnen:fireplace": "Krb", + "pack:nextfloor.wohnen:bookcase_wall": "Nástěnný regál", + "pack:nextfloor.wohnen:piano": "Pianino", + "pack:nextfloor.wohnen:aquarium": "Akvárium", + "pack:nextfloor.wohnen:cat_tree": "Škrabadlo", + "pack:nextfloor.wohnen:dog_bed": "Pelíšek pro psa", + "pack:nextfloor.wohnen:hanging_chair": "Závěsné křeslo", + "pack:nextfloor.wohnen:display_cabinet": "Vitrína", + "pack:nextfloor.wohnen:high_table": "Barový stůl", + "pack:nextfloor.wohnen:floor_mirror": "Stojací zrcadlo", + "furn_tap": "Klepnutí na prvek", + "furn_tap_default": "Jako obvykle", + "furn_tap_hint": "Vlastní akce jako vlastní tlačítka nabídky hvězdičky, např. okno browser_mod s vaší kartou.", + "furn_show_when": "Zobrazovat pouze tehdy, když …", + "furn_show_when_state": "… je ve stavu (prázdné = zapnuto)", + "furn_show_when_invert": "Obráceně: zobrazovat, když tomu tak není", + "furn_show_when_hint": "Sezónní dekorace, které stojí pouze v prosinci: pomocník (input_boolean), kalendář nebo snímač rozhoduje, zda se nábytek zobrazí v 3D. Více stavů oddělte čárkou. Editor jej zobrazuje vždy.", + "picture_upload": "Nahrát fotku", + "picture_replace": "Nahrát jinou fotku", + "picture_stored": "Uložena vlastní fotka.", + "picture_url": "… nebo adresa obrázku", + "picture_entity": "… nebo obrázek entity", + "picture_border": "Pasparta (%)", + "picture_fit": "Fotka", + "picture_fit_cover": "vyplňuje rámeček", + "picture_fit_contain": "viditelná celá", + "picture_hint": "Vaše fotka v rámečku, v 3D a na nástěnném tabletu. Nahrané fotky se ukládají s plánem v menší velikosti; entita obrázku (fotka dne) nebo kamera zobrazuje svůj aktuální obrázek.", + "card_tap_in_room": "Přepínat zařízení pouze v otevřené místnosti", + "card_tap_in_room_hint": "V zobrazení domu a podlaží klepnutí otevře podlaží nebo místnost, i na zařízení nebo jeho symbolu. V otevřené místnosti přepíná zařízení. Dlouhé stisknutí vždy otevře jeho nabídku nebo podrobnosti.", + "card_markers_outside": "Vybrat symboly mimo otevřenou místnost", + "card_markers_outside_hint": "V domě, na podlaží a v ostatních místnostech pouze vybrané druhy; v otevřené místnosti všechny, jak je nastaveno výše. \"Vždy\" a \"Nikdy\" u zařízení mají přednost.", + "marker_kind_light": "Světla", + "marker_kind_cover": "Rolety", + "marker_kind_climate": "Vytápění", + "marker_kind_media": "Média", + "marker_kind_switch": "Vypínače", + "marker_kind_fan": "Ventilátory", + "marker_kind_lock": "Zámky", + "marker_kind_binary": "Kontakty a detektory", + "marker_kind_sensor": "Snímače", + "marker_kind_tap": "Nábytek s akcí", + "marker_kind_other": "Ostatní", + "floor_copy": "Duplikovat podlaží", + "floor_copy_hint": "Kopie směřuje nahoru do domu se všemi místnostmi, zdmi, dveřmi a okny. Místnosti a podlaží ztrácejí propojení s Home Assistant, nábytek své entity; energetická zařízení zůstávají na starém podlaží.", + "floor_copy_furniture": "Kopírovat nábytek", + "floor_copy_devices": "Kopírovat značky zařízení", + "floor_copy_devices_hint": "Stejná entita se pak zobrazí na obou podlažích.", + "floor_copy_outdoor": "Kopírovat venkovní terény", + "floor_copy_make": "Vytvořit kopii", + "floor_copy_name": "{name} (kopie)", + "furn_to_floor": "Přesunout na podlaží", + "furn_to_floor_hint": "Nábytek se posune na stejné místo na vybraném podlaží.", + "arc": "Oblouk", + "arc_hint": "Ohne zeď do oblouku. Místnost sdílející tuto zeď se ohne spolu s ní, dveře a okna se posunou; Zpět odstraní oblouk.", + "arc_bulge": "Prohnutí (m)", + "arc_bulge_hint": "Jak moc se střed zdi ohýbá: kladně ven, záporně do místnosti.", + "arc_apply": "Ohnout", + "arc_too_wide": "Dveře nebo okno v této zdi jsou příliš široké pro tento oblouk. Vyrovnejte oblouk nebo zúžíte otvor.", + "time_of_day": "Denní doba", + "time_of_day_hint": "Zobrazuje slunce, světlo, stíny a vzhled v jinou dobu dnešního dne. Klepněte znovu pro návrat k aktuálnímu času.", + "menu_open": "Nabídka otevřena", + "menu_open_hint": "Nabídka hvězdičky s oblíbenými a vlastními tlačítky je na tomto zařízení otevřená od začátku a větší – pro nástěnný tablet, který hlavně spouští scény.", + "keep_camera": "Zachovat kameru", + "keep_camera_hint": "Při změně podlaží zůstává kamera na stejné straně, ve stejné výšce a vzdálenosti, místo toho, aby zabírala nové podlaží ze startovací strany.", + "view_zoom": "Přiblížení", + "view_zoom_hint": "Jak blízko přicházejí přizpůsobené pohledy – na malých tabletech dům vypadá větší.", + "stair_shape": "Tvar", + "stair_shape_straight": "Přímé", + "stair_shape_quarter": "Čtvrtotočné s navíjením", + "stair_shape_l": "Ve tvaru L s podestou", + "stair_shape_half": "Půlotočné s navíjením", + "stair_shape_u": "Ve tvaru U s podestou", + "stair_shape_spiral": "Točité", + "stair_turn": "Směr zatáčení (při výstupu)", + "stair_turn_left": "Vlevo", + "stair_turn_right": "Vpravo", + "stair_build": "Konstrukce", + "stair_build_solid": "Masivní (beton)", + "stair_build_stringer": "Schodnicové", + "stair_build_mono": "Na středovém nosníku", + "stair_build_cantilever": "Konzolové (vznášející se)", + "stair_risers": "Podstupnice", + "stair_steps": "Počet stupňů", + "stair_run_width": "Šířka ramene (m)", + "stair_landing_after": "Stupně k podestě", + "stair_landing_hint": "Podesta je {h} cm nad podlahou; ostatní stupně jsou za ní.", + "stair_rail": "Zábradlí", + "stair_rail_none": "Žádné", + "stair_rail_left": "Levé", + "stair_rail_right": "Pravé", + "stair_rail_both": "Oboustranné", + "stair_down": "Vede dolů", + "stair_down_hint": "Schody začínají na tomto podlaží a vedou dolů, například do sklepa, který není potřeba kreslit. Otevírají podlahu tohoto podlaží.", + "stair_measures": "{steps} stupňů po {rise} cm · šířka stupně {going} cm · krok {measure} cm", + "stair_uncomfortable": "pohodlné (krok 59–65 cm, výška stupně nejvýše 21 cm)", + "stair_up_note": "Schody začínají u vyznačené přední hrany. Strop nad nimi se otevírá pouze tam, kde nad stupni zůstává méně než 2,2 m průchozí výšky.", + "stair_down_note": "Vstupuje se na schody u vyznačené přední hrany a sestupuje dolů. Plán je kreslí čárkovanou čárou; toto podlaží se otevírá nad stupni.", + "stair_upgrade": "Nastavit tvar", + "stair_upgrade_hint": "Změní je na schody s tvarem (s navíjením, L, U, točité), konstrukcí, zábradlím a počtem stupňů.", + "tool_stairs": "Schody", + "hint_stairs": "Přetáhněte tam, kde mají stát schody – běží podél delší strany; potom vpravo nastavte tvar, směr a konstrukci", + "stair_opening": "Otvor ve stropu", + "stair_opening_headroom": "Podle průchozí výšky (pouze kde je třeba)", + "stair_opening_full": "Nad celými schody", + "stair_opening_none": "Žádný (poklop, uzavřené schodiště)", + "stair_opening_hint": "Jak moc schody otevírají strop, do kterého zasahují: podlaží výše nebo vlastní podlaží při schodech dolů. Podle průchozí výšky otevírá pouze nad stupni, nad kterými zůstává méně než 2,2 m.", + "stair_up_note_plain": "Schody začínají u vyznačené přední hrany a stoupají dozadu." +} \ No newline at end of file diff --git a/custom_components/nextfloor/frontend/lang/da.json b/custom_components/nextfloor/frontend/lang/da.json new file mode 100644 index 0000000..f5a9700 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/da.json @@ -0,0 +1,153 @@ +{ + "accent": "Accentfarve", + "accent_reset": "Tilbage til cyan", + "alert_alarm_by": "Alarm udløst af {cause}", + "all_floors": "Alle etager", + "all_off_done": "Alt slukket.", + "all_off_floor": "Alt slukket på {floor} ({n} enheder), fortryd i ti sekunder", + "all_off_n": "Alt slukket ({n})", + "all_off_undo": "Fortryd", + "announce_failed": "Meddelelsen mislykkedes: {error}", + "announce_on": "Meddelelser på denne skærm er slået til", + "announce_placeholder": "Din egen besked …", + "announce_send": "Sig det", + "announce_sent": "Sagt: \"{message}\"", + "back": "Tilbage", + "bars_fold": "Fold kontakterne væk", + "bars_unfold": "Kontakter", + "battery_low_n": "Lavt batteri: {names}", + "brightness": "Lysstyrke", + "card_description": "Dit hjem i 3D (neon).", + "card_floor_stack": "Etager nedenunder", + "card_room_buttons": "Rumknapper", + "care_bin_days": "Om {n} dage", + "care_bin_today": "Hentes i dag", + "care_bin_tomorrow": "Hentes i morgen", + "care_time_left": "{time} tilbage", + "central": "Central: alle lys, persienner og favoritter", + "central_covers": "Persienner", + "central_favorites": "Favoritter", + "central_house": "Hele huset", + "central_lights": "Lys", + "central_sure": "Sikker?", + "clock": "Ur", + "close": "Luk", + "color": "Farve", + "color_temp": "Farvetemperatur", + "comfort_n": "Komfort {n}", + "confirm_switch": "Vil du virkelig skifte {name}?", + "cover_close": "Luk", + "cover_my_go": "Til favoritposition ({p} %)", + "cover_open": "Åbn", + "cover_stop": "Stop", + "cover_tilt": "Lameller", + "cover_tilt_close": "Lameller lukket", + "cover_tilt_open": "Lameller åbne", + "delete": "Slet", + "details": "Detaljer", + "draft_discard": "Kassér", + "draft_found": "Ikke-gemte ændringer fra {time} fundet.", + "draft_restore": "Gendan og gem", + "empty_lights_hint": "{n} lys tændt, ingen her i {min} min.", + "empty_lights_off": "Sluk lys", + "energy_battery": "Batteri", + "energy_consumption": "Forbrug", + "energy_rest": "Fælles (rest)", + "energy_solar": "Sol", + "energy_tariff": "Takst", + "ext_tab": "Udvidelser", + "find": "Søg", + "find_none": "Intet fundet", + "find_placeholder": "Hvor er …? Enhed eller rum", + "floor_layer": "Lag (kan vises og skjules)", + "floor_power_share": "{n} % af huset", + "floor_rooms": "{n} rum", + "floor_rooms_one": "1 rum", + "floors": "Etager", + "floors_apart": "Fra hinanden", + "floors_stacked": "Stablet", + "flows": "Strømflow", + "fps_title": "Ydelsesvisning (billeder i sekundet)", + "glass_walls": "Glasvægge", + "heat_none_found": "Ingen passende sensorer i rummenes områder.", + "heat_wifi": "Wi-Fi", + "heatmap": "Varmekort", + "holos": "Kort", + "keep_camera": "Behold kamera", + "load_error": "Indlæsning mislykkedes", + "loading": "Indlæser …", + "markers": "Markører", + "media_next": "Næste", + "media_previous": "Forrige", + "media_sources": "Kilder", + "media_volume": "Lydstyrke", + "menu_open": "Menu åben", + "meter_unmetered": "{w} umålt", + "mood_carry": "Overfør til et andet rum", + "mood_new": "Stemning", + "mood_save": "Gem stemning", + "mood_set": "Brug denne stemning", + "next": "Næste", + "no_building": "Ingen plantegning endnu.", + "open_editor": "Åbn editor", + "open_heating_hint": "{n} vinduer er åbne, mens varmen kører.", + "open_heating_off": "Sluk varmen", + "open_since": "åben i {time}", + "outside_area": "Udenfor", + "panel_all_close": "Alle ned", + "panel_all_off": "Alle fra", + "panel_all_on": "Alle til", + "panel_all_open": "Alle op", + "panel_less": "Vis mindre", + "panel_more": "Flere enheder i området ({n})", + "plain": "Kun plantegning", + "play_pause": "Afspil/pause", + "pool_pump_on": "pumpe til", + "position": "Position", + "presence_last": "sidst set for {time} siden", + "presence_now": "nogen er her", + "presets": "Stationer og afspilningslister (lyd)", + "previous": "Forrige", + "qm_off": "Fra", + "readable": "Letlæselig", + "reload_page": "Genindlæs", + "right_back": "Højreklik = tilbage", + "roof_keep": "Taget bliver", + "room_clean_run": "Støvsug", + "room_clean_run_hint": "Sender robotstøvsugeren til dette rum.", + "room_curve_hint": "Rummets temperatur de sidste 24 timer", + "room_energy": "i dag {today} · måned {month}", + "room_sun_hours": "{h} t sol i dag ({facing})", + "room_sun_year": "Sol over året", + "save_failed_detail": "Det mislykkedes at gemme: {error}. Dine ændringer bevares i denne browser.", + "screen_name": "Navn på denne skærm", + "shade_close": "Sænk", + "shade_hint": "Sol på {n} vinduer ved {temp} – sænk persiennerne?", + "stats_idle": "I hvile (0 fps)", + "stl": "3D-print (STL)", + "swipe_off": "Fra", + "target_temp": "Mål", + "temp_down": "Køligere", + "temp_up": "Varmere", + "time_of_day": "Tid på dagen", + "today": "I dag", + "today_none": "Intet i dag.", + "travel": "Tidsrejse: afspil de sidste 24 timer eller 7 dage", + "travel_days": "dage", + "travel_failed": "Historikken kunne ikke indlæses.", + "travel_live": "Live", + "travel_loading": "Indlæser historik …", + "travel_speed": "Hastighed", + "view_options": "Visning: kvalitet, look, markører, FPS", + "view_zoom": "Zoom", + "volume": "Lydstyrke", + "wallbox_charging": "oplader", + "wallbox_plugged": "tilsluttet", + "walls_auto": "Høje vægge", + "walls_cut": "Snit", + "walls_slope": "Skrå", + "walls_solid": "Massive", + "wifi_aps": "{n} adgangspunkter · {clients} enheder", + "wifi_clients": "{n} enheder", + "wifi_network": "Netværk: {online} online · {offline} offline" +} diff --git a/custom_components/nextfloor/frontend/lang/es.json b/custom_components/nextfloor/frontend/lang/es.json new file mode 100644 index 0000000..511e4f9 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/es.json @@ -0,0 +1,2763 @@ +{ + "view": "3D", + "editor": "Editor", + "all_floors": "Todas las plantas", + "outside_area": "Exterior", + "outside_area_hint": "Todos los dispositivos de fuera de un vistazo: en el jardín, fuera de las estancias y lo que pertenece al exterior (por ejemplo, la estación meteorológica en el tejado).", + "device_outside": "Pertenece al exterior", + "device_outside_hint": "El dispositivo no cuenta para la estancia de debajo (una estación meteorológica en el tejado) y aparece en el panel Exterior.", + "no_building": "Todavía no hay plano.", + "no_building_admin": "Todavía no hay plano. Dibuja tu primera planta en el editor.", + "no_rooms_admin": "Las plantas existen, pero aún no hay ninguna habitación. Las paredes solas no bastan: dibuja al menos una habitación en el editor con «Rectángulo» o «Forma libre».", + "open_editor": "Abrir editor", + "loading": "Cargando …", + "load_error": "Error al cargar", + "saving": "Guardando …", + "saved": "Guardado", + "save_error": "Error al guardar", + "save_failed_detail": "Error al guardar: {error}. Tus cambios se conservan en este navegador.", + "needs_restart": "Hay instalada una nueva versión de NextFloor ({frontend}), pero Home Assistant sigue ejecutando {version}. Reinicia Home Assistant; hasta entonces el guardado puede fallar.", + "needs_reload": "Esta página aún muestra NextFloor {frontend}, Home Assistant ya tiene {backend}. Recarga la página; en la app complementaria: Ajustes → App complementaria → Restablecer caché del frontend.", + "reload_page": "Recargar", + "needs_restart_old": "Hay instalada una nueva versión de NextFloor, pero Home Assistant sigue ejecutando una anterior. Reinicia Home Assistant; hasta entonces el guardado falla.", + "draft_found": "Se encontraron cambios sin guardar del {time}.", + "draft_restore": "Restaurar y guardar", + "draft_discard": "Descartar", + "walls_auto": "Paredes altas", + "walls_cut": "Corte", + "walls_slope": "Inclinado", + "walls_slope_hint": "Paredes cortadas en pendiente: media altura delante, altura completa detrás, como una casa de muñecas; gira con la cámara", + "walls_solid": "Macizo", + "walls_solid_hint": "Paredes macizas con sus colores en lugar de cristal (colores: editor → ajustes, por estancia en la estancia)", + "wall_paint_outside": "Color de pared exterior", + "wall_paint_inside": "Color de pared interior", + "wall_paint_room": "Color de pared interior (esta estancia)", + "wall_paint_hint": "Se usa en la vista 3D «Macizo».", + "wall_paint_default": "Predeterminado", + "card_solid_walls": "Paredes macizas (con sus colores)", + "reset_view": "Vista general", + "back": "Atrás", + "floor": "Planta", + "floors": "Plantas", + "add_floor": "Añadir planta", + "floor_from_ha": "Plantas de Home Assistant:", + "floor_empty": "Planta vacía", + "level": "Nivel {n}", + "ha_floor": "Planta en Home Assistant", + "floor_layer": "Capa (se puede mostrar y ocultar)", + "floor_power": "Contador de la planta (potencia)", + "floor_power_hint": "Un sensor de potencia solo para esta planta (un subcontador, un piso). Su valor aparece en la etiqueta de la planta y, en la vista de esta planta, en la tarjeta de la casa con su parte del consumo.", + "floor_power_share": "{n} % de la casa", + "living_area": "Superficie útil {living}", + "room_living": "Cuenta como superficie útil", + "living_area_none": "Sin superficie útil · suelo {floor}", + "living_area_low": "Superficie útil {living} (suelo {floor}, de ello {low} bajo 2 m)", + "living_area_hint": "Calculado como la Wohnflächenverordnung alemana: el suelo dentro de las paredes, entero desde 2 m de altura libre, la mitad entre 1 y 2 m (bajo pendientes), nada por debajo de 1 m. Un valor orientativo, no una medición.", + "living_area_floor": "Superficie útil: {floor}", + "living_area_floor_house": "Superficie útil de esta planta: {floor} · toda la casa: {house}", + "print_plan": "Imprimir plano / PDF", + "print_plan_hint": "Cada planta como plano limpio con medidas y superficies, y una tabla de superficies: para imprimir o guardar como PDF desde el diálogo de impresión.", + "print_title": "Plano", + "print_room": "Habitación", + "print_floor_area": "Superficie", + "print_living": "Superficie útil", + "print_low": "bajo 2 m", + "print_total": "Total", + "print_blocked": "Se bloqueó la ventana de impresión: permite ventanas emergentes para Home Assistant.", + "check_open": "Revisar el plano", + "note": "Nota", + "note_add": "Nota aquí", + "note_text": "Texto", + "note_placeholder": "p. ej. «cambiar el filtro» o «fusible 12»", + "note_due": "Pendiente el", + "note_due_hint": "Desde ese día el marcador se vuelve naranja.", + "note_is_due": "Esta nota está pendiente.", + "keys_title": "Teclas del editor", + "keys_undo": "Deshacer", + "keys_redo": "Rehacer", + "keys_duplicate": "Duplicar la habitación", + "keys_delete": "Borrar la selección", + "keys_nudge": "Mover la selección un paso de cuadrícula", + "keys_nudge_10": "… 10 cm", + "keys_nudge_1": "… 1 cm", + "keys_rotate": "Girar el mueble 90° (Mayús: atrás)", + "keys_lock": "Fijar o soltar un mueble, un dispositivo o una sección de tejado", + "keys_close_shape": "Cerrar la forma libre", + "keys_escape": "Cancelar, salir de la herramienta, quitar la selección", + "keys_straight": "Al dibujar: líneas rectas", + "keys_sheet": "Esta lista", + "tour_title": "Primeros pasos", + "tour_1_title": "Dibujar las habitaciones", + "tour_1": "Dibuja las habitaciones con «{rect}» o «{free}»; las paredes salen solas. Asigna a cada habitación su área de Home Assistant y NextFloor encontrará sus dispositivos. Si ya tienes áreas, «{rooms}» en el formulario de planta las crea de una vez.", + "tour_2_title": "Puertas y ventanas", + "tour_2": "«{opening}» las coloca en una pared. Vincula su contacto o persiana: en 3D se abren y cierran con él, y las ventanas abiertas avisan.", + "tour_3_title": "Muebles y dispositivos", + "tour_3": "«{furniture}» abre la biblioteca, o construye tus piezas en el 🛠️ taller. Elige una habitación y debajo aparecen los dispositivos de su área, listos para colocar; las lámparas brillan del color de su luz.", + "tour_4_title": "Mirar y revisar", + "tour_4": "«{split}» muestra tu casa mientras dibujas; arriba cambias a la vista 3D. «{check}» lista lo que aún falta, y ? muestra las teclas en cualquier momento.", + "tour_next": "Siguiente", + "tour_back": "Atrás", + "tour_done": "Vamos", + "tour_skip": "Omitir", + "check_open_hint": "Muestra lo que falta o está mal en el plano, con un arreglo en un toque.", + "check_title": "Revisión del plano", + "check_all_good": "Todo bien: no se encontró nada.", + "check_hint": "{n} puntos encontrados. Los botones azules cambian el plano (deshacer funciona como siempre), los demás muestran el lugar.", + "check_room_no_area": "«{room}» no tiene área de Home Assistant: no se encuentran sus dispositivos.", + "check_room_no_area_named": "«{room}» no tiene área – el área libre «{area}» se llama igual.", + "check_areas_unplaced": "{n} áreas de esta planta aún no tienen habitación: {names}", + "check_devices_unplaced": "«{room}»: {n} dispositivos del área aún no están en el plano.", + "check_rooms_overlap": "«{a}» y «{b}» se superponen.", + "check_opening_off_wall": "Una puerta o ventana de «{room}» no está en ninguna pared.", + "check_entity_missing": "{n} marcadores apuntan a entidades que Home Assistant ya no conoce ({ids}).", + "check_furniture_entity_missing": "Un mueble está vinculado a {id}: esa entidad ya no existe.", + "check_battery_low": "Batería baja: {name} ({level} %)", + "battery_low_n": "Batería baja: {names}", + "check_standby": "{name} consume {w} W apagado: unos {cost} al año.", + "check_fix_show": "Mostrar", + "check_fix_set_area": "Asignar «{area}»", + "check_fix_add_rooms": "Añadir las habitaciones", + "check_fix_place": "Colocar {n}", + "check_fix_remove": "Quitar {n}", + "floor_layer_hint": "Esta planta no es un piso sino una capa – todos los árboles o la decoración. La vista 3D muestra arriba un ojo que la muestra u oculta en cada dispositivo.", + "no_ha_floor": "– ninguna –", + "area_rooms": "Añadir estancias desde áreas de HA ({n})", + "area_rooms_hint": "Añade una estancia (4 × 3 m) por cada área de esta planta; después arrástrala a su sitio y ajusta las esquinas", + "floor_name": "Nombre", + "elevation": "Elevación (m)", + "floor_shift": "Desplazar la planta (m)", + "floor_shift_apply": "Desplazar", + "floor_shift_hint": "Mueve todas las estancias, muebles, dispositivos, zonas exteriores, paredes libres y la imagen de fondo de esta planta en X y Z. Las secciones de tejado se quedan.", + "height": "Altura del techo (m)", + "cut_height": "Altura de corte (m)", + "delete_floor": "Eliminar planta", + "delete_floor_confirm": "¿Eliminar la planta «{name}» con todas sus estancias?", + "move_up": "Subir", + "move_down": "Bajar", + "default_floor": "Planta baja", + "new_floor": "Planta {n}", + "tool_select": "Seleccionar", + "tool_rect": "Rectángulo", + "tool_polygon": "Forma libre", + "undo": "Deshacer", + "redo": "Rehacer", + "fit": "Mostrar todo", + "room": "Estancia", + "rooms": "Estancias", + "room_name": "Nombre", + "area": "Área", + "no_area": "Sin área", + "sub_area_add": "+ Área dentro de la estancia", + "sub_area_hint": "Una parte de la estancia con área propia en Home Assistant pero sin paredes – un rincón de lectura, una estantería, una cocina americana. Sus dispositivos y sensores pertenecen a esta estancia.", + "material": "Suelo", + "x": "X (m)", + "z": "Y (m)", + "width": "Ancho (m)", + "depth": "Fondo (m)", + "points": "Esquinas", + "delete_point": "Eliminar esquina", + "duplicate": "Duplicar", + "delete": "Eliminar", + "new_room": "Estancia {n}", + "settings": "Ajustes", + "pendant_shape": "Forma", + "pendant_shade": "Pantalla", + "paint_colour": "Color de pintura", + "pendant_globe": "Globo", + "pendant_cone": "Cono", + "pendant_drum": "Tambor", + "sofa_shape": "Forma", + "sofa_straight": "Recto", + "sofa_l": "En L (espejo: otro lado)", + "sofa_u": "En U", + "pkg_open": "Amueblar …", + "pkg_hint": "Los muebles van contra las paredes de la estancia; las lámparas se vinculan a las luces del área. Ajusta cada elemento después; Ctrl+Z lo deshace todo.", + "pkg_done": "{n} elementos colocados; Ctrl+Z lo deshace.", + "pkg_kitchen_row": "Cocina en línea", + "pkg_kitchen_row_desc": "Línea en la pared del fondo con frigorífico, horno, fregadero, lavavajillas y placa, mueble alto, mesa de comedor con lámpara colgante", + "pkg_kitchen_l": "Cocina en L", + "pkg_kitchen_l_desc": "Líneas al fondo y a la izquierda, isla de cocina con taburetes", + "pkg_bath": "Baño", + "pkg_bath_desc": "Lavabo, inodoro, bañera, lavadora, foco empotrado", + "pkg_bedroom": "Dormitorio", + "pkg_bedroom_desc": "Cama doble con dos mesitas de noche, armario, cómoda, lámpara de techo", + "pkg_living": "Salón", + "pkg_living_desc": "Mueble de TV, sofá, mesa de centro, alfombra, sillón, estantería, lámpara de pie, planta", + "pkg_dining": "Comedor", + "pkg_dining_desc": "Mesa con cuatro sillas, aparador, lámpara colgante", + "pkg_office": "Oficina", + "pkg_office_desc": "Escritorio con silla de oficina, dos estanterías, lámpara de techo", + "pkg_kids": "Habitación infantil", + "pkg_kids_desc": "Cama individual, escritorio, estantería, alfombra", + "pkg_hall": "Pasillo", + "pkg_hall_desc": "Perchero, dos focos empotrados", + "spots_place": "Colocar focos", + "spots_type": "Lámpara", + "spots_cols": "Columnas (izquierda–derecha)", + "spots_rows": "Filas (delante–detrás)", + "spots_add": "Colocar {n} lámparas", + "spots_placed": "{n} lámparas colocadas.", + "spots_hint": "Todas las lámparas siguen a la luz elegida (p. ej. focos en un mismo regulador). Después cada una se puede mover y vincular a otra luz como cualquier mueble.", + "cancel": "Cancelar", + "backup": "Copia de seguridad", + "backup_history": "Puntos de restauración", + "share_view": "Compartir una vista", + "share_view_hint": "Guarda la casa como un archivo pequeño que se abre en cualquier navegador sin Home Assistant (a través de la demo en línea de NextFloor): para enseñarla a la familia o a un proyectista. Sin dispositivos ni entidades, como una plantilla.", + "share_view_title": "Nuestra casa en NextFloor", + "share_view_needs_js": "Esta página necesita JavaScript y conexión a internet.", + "share_view_file": "vista", + "share_view_done": "Vista guardada: abre el archivo en un navegador o compártelo.", + "version_save": "Guardar este estado …", + "version_save_hint": "Guarda el plano con un nombre («antes de la reforma»). Los estados con nombre se quedan cuando los puntos automáticos se van.", + "version_name_prompt": "Nombre de este estado (p. ej. «antes de la reforma»):", + "version_saved": "Estado «{name}» guardado.", + "version_compare": "Comparar", + "version_delete_confirm": "¿Eliminar «{name}»?", + "version_same": "Sin diferencias con el plano.", + "version_diff_n": "{n} diferencias con el plano actual:", + "diff_floor_added": "Planta «{name}» añadida", + "diff_floor_removed": "Planta «{name}» eliminada", + "diff_room_added": "Habitación «{name}» añadida", + "diff_room_removed": "Habitación «{name}» eliminada", + "diff_room_renamed": "«{detail}» ahora se llama «{name}»", + "diff_room_reshaped": "«{name}» cambiada de forma ({detail} m²)", + "diff_opening_added": "{name} añadido/a ({detail})", + "diff_opening_removed": "{name} eliminado/a ({detail})", + "diff_furniture_added": "{name} añadido", + "diff_furniture_removed": "{name} eliminado", + "diff_furniture_moved": "{name} movido o cambiado", + "diff_device_added": "Dispositivo {name} colocado", + "diff_device_removed": "Dispositivo {name} quitado", + "diff_device_moved": "Dispositivo {name} movido", + "backup_none": "Ninguno todavía. Mientras editas se guarda un punto de restauración como máximo cada 10 minutos.", + "backup_summary": "{rooms} estancias, {furniture} elementos", + "backup_restore": "Restaurar", + "backup_restore_confirm": "¿Restaurar el estado del {time}? El estado actual se conserva como punto de restauración.", + "backup_restored": "Restaurado.", + "backup_file": "Archivo", + "backup_export": "Exportar", + "backup_export_share": "Compartir como plantilla", + "backup_export_share_hint": "Sin áreas, dispositivos, sensores ni imágenes, para pasarlo a otros.", + "backup_import": "Importar …", + "backup_import_confirm": "¿Sustituir todo el plano por el archivo? El estado actual se conserva como punto de restauración.", + "backup_import_error": "El archivo no es un plano de NextFloor ({error}).", + "backup_imported": "Importado.", + "backup_hint": "Las imágenes de fondo no forman parte del archivo.", + "backup_full": "Copia de seguridad completa", + "backup_full_export": "Guardar todo (plano, imágenes, packs)", + "backup_full_import": "Restaurar una copia completa …", + "backup_full_hint": "Un archivo con el plano, todas las imágenes de fondo y de pantalla y los packs instalados. Al restaurar se vuelve a comprobar cada pack; la clave de licencia no se incluye.", + "backup_full_confirm": "¿Sustituir el plano, las imágenes y los packs por la copia? El estado actual queda como punto de restauración.", + "backup_full_not_backup": "Esta no es una copia de seguridad completa de NextFloor.", + "backup_full_restored": "Copia restaurada: {packs} packs, {pictures} imágenes.", + "backup_full_skipped": "Omitidos (no se pudieron leer): {packs}.", + "export_name_full": "completa", + "device_confirm": "Preguntar antes de conmutar", + "device_confirm_hint": "Un toque en 3D, el menú rápido y el panel de la estancia preguntan antes. Un doble toque en la estancia excluye este dispositivo.", + "cover_confirm_hint": "Abrir, cerrar y las posiciones preguntan antes en el menú rápido y en el panel de la estancia, y deslizar sobre el marcador ya no mueve la persiana (gira la vista). Parar nunca pregunta.", + "blind_kind": "Tipo de persiana", + "blind_roller": "Persiana enrollable exterior", + "blind_venetian": "Veneciana exterior con lamas", + "blind_inside": "Estor interior", + "cover2_entity": "Segunda persiana (mitad derecha)", + "cover_my": "Posición favorita «My» (%, 0 = ninguna)", + "cover_my_go": "A la posición favorita ({p} %)", + "blind_hint": "Una veneciana exterior gira sus lamas en 3D según la inclinación de la persiana; un estor interior cuelga detrás del cristal. Una ventana ancha puede tener una segunda persiana para su mitad derecha. La posición favorita aparece como «My» en el menú rápido: una persiana con posiciones va allí, un motor Somfy RTS sin respuesta va a su propio My con Parar.", + "confirm_switch": "¿Conmutar realmente {name}?", + "lock_confirm_unlock": "¿Desbloquear realmente {name}?", + "gang_switch_one": "Interruptores", + "furn_cover_entity": "Se mueve con", + "furn_cover_hint": "La cortina, pantalla, toldo o portón sigue a esta entidad de cubierta (persiana, cortina, toldo, portón) y se desplaza con ella. Un toque abre su menú (subir, parar, bajar).", + "furn_cover_inverted": "Invertir el sentido", + "furn_cover_inverted_hint": "Para un toldo o una cortina que se mueve al revés en el plano: extendido se muestra recogido y al revés.", + "gang_switch": "El botón {n} conmuta", + "gang_socket_one": "Enchufe alimentado por", + "gang_socket": "Enchufe {n} alimentado por", + "gang_switch_hint": "Un botón brilla mientras su luz está encendida (en su color). Un toque lo conmuta; con varios botones, un pequeño menú pregunta cuál. La misma entidad puede estar en varios interruptores.", + "gang_socket_hint": "Un enchufe brilla en verde mientras su interruptor está encendido, más cuanto más consume. Un toque lo conmuta; con varios, un pequeño menú pregunta cuál.", + "lock_confirm_lock": "¿Bloquear {name}?", + "opening_lock": "Cerradura inteligente", + "opening_lock_hint": "Un toque en la puerta la bloquea o desbloquea (siempre preguntando antes). Mientras está desbloqueada, su borde brilla.", + "split_handle_hint": "Arrastrar: ancho del plano y de la vista 3D", + "wall_exterior": "Pared exterior (m)", + "wall_interior": "Pared interior (m)", + "grid": "Cuadrícula (m)", + "units": "Mostrar longitudes en", + "units_metric": "Metros", + "units_imperial": "Pies y pulgadas", + "units_hint": "Cómo aparecen longitudes y superficies en el plano, los formularios y la vista de pared. Las entradas siguen en metros.", + "background": "Plantilla (imagen del plano)", + "background_upload": "Elegir imagen …", + "background_width": "Ancho en el plano (m)", + "background_opacity": "Opacidad", + "background_rotation": "Rotación (°)", + "background_edit": "Mover, escalar y girar", + "background_edit_done": "Hecho", + "background_edit_hint": "Con el modo activo: arrastrar la imagen la mueve, el tirador de abajo a la derecha la escala. Ajusta primero la escala y luego gírala.", + "background_remove": "Quitar plantilla", + "hint_select": "Toca una estancia para seleccionarla · arrastra las esquinas · «+» en un borde inserta una esquina · las flechas desplazan · Supr elimina · Ctrl+Z", + "hint_rect": "Arrastra para dibujar un rectángulo", + "hint_polygon": "Coloca esquinas · toca la primera esquina o pulsa Intro para cerrar · Esc cancela", + "hint_empty": "Añade primero una planta.", + "area_m2": "{a} m²", + "overlap_warning": "Las estancias se solapan; ahí las paredes están incompletas.", + "read_only": "Solo los administradores pueden editar el plano.", + "side_failed": "No se pudo mostrar este formulario ({error}). El plano sigue funcionando. Por favor, informa del texto en un issue de GitHub.", + "mat_wood": "Madera", + "mat_oak": "Roble", + "mat_tiles": "Baldosas", + "mat_carpet": "Moqueta", + "mat_stone": "Piedra", + "mat_concrete": "Hormigón", + "card_name": "NextFloor", + "card_description": "Tu hogar en 3D (neón).", + "stats": "{calls} llamadas de dibujo · {tris} triángulos", + "stats_fps": "{fps} fps (fotograma más lento {ms} ms)", + "stats_idle": "En reposo (0 fps)", + "stats_busy_floors": "plantas", + "stats_busy_openings": "puertas/ventanas", + "stats_busy_flash": "destello", + "stats_busy_roof": "tejado", + "stats_busy_flow": "flujo de energía", + "stats_busy_effect": "efecto de color", + "stats_busy_robot": "robot", + "stats_busy_orbit": "giro de cámara", + "stats_busy_tint": "tinte de estancia", + "stats_low": "nivel tablet, ratio de píxeles {r}", + "stats_full": "nivel completo, ratio de píxeles {r}", + "floors_apart": "Separadas", + "floors_stacked": "Apiladas", + "roof_keep": "El tejado se queda", + "roof_keep_hint": "El tejado permanece en la casa al acercar el zoom en lugar de elevarse y desvanecerse", + "floor_rooms_one": "1 estancia", + "floor_rooms": "{n} estancias", + "quality": "Calidad", + "quality_auto": "Auto", + "quality_low": "Tablet", + "quality_high": "Alta", + "state_on": "Encendido", + "state_off": "Apagado", + "state_open": "Abierto", + "state_closed": "Cerrado", + "state_opening": "Abriendo", + "state_closing": "Cerrando", + "state_playing": "Reproduciendo", + "state_paused": "En pausa", + "state_idle": "Inactivo", + "state_locked": "Bloqueado", + "state_unlocked": "Desbloqueado", + "state_detected": "Detectado", + "state_clear": "Despejado", + "state_unavailable": "No disponible", + "state_heat": "Calor", + "state_cool": "Frío", + "state_auto": "Auto", + "state_heat_cool": "Calor/frío", + "state_dry": "Secar", + "state_fan_only": "Ventilador", + "devices": "Dispositivos", + "devices_none_area": "Vincula la estancia a un área y sus dispositivos aparecerán aquí.", + "devices_none": "El área no tiene dispositivos adecuados.", + "devices_place_all_n": "Colocar los {n} …", + "devices_place_all_confirm": "¿Colocar {n} dispositivos en la estancia a la vez? (Ctrl+Z o «Deshacer» los quita todos en un paso.)", + "devices_src_area": "Esta área", + "devices_src_other": "Otras áreas", + "devices_src_none": "Sin área", + "panel_hide": "Ocultar del panel de la estancia", + "panel_unhide": "Mostrar de nuevo en el panel de la estancia", + "panel_state_hide": "Ocultar el estado en el panel de la estancia (p. ej. una cubierta que solo informa \"unknown\")", + "panel_state_show": "Mostrar de nuevo el estado en el panel de la estancia", + "devices_place": "Colocar", + "devices_remove": "Quitar", + "devices_hint": "Los dispositivos colocados aparecen en 3D. Arrástralos en el plano para moverlos.", + "panel_lights": "Luces", + "panel_covers": "Cubiertas", + "panel_climate": "Calefacción", + "panel_media": "Multimedia", + "panel_switches": "Interruptores", + "panel_sensors": "Sensores", + "panel_scenes": "Escenas y scripts", + "panel_announce": "📢 Anuncio", + "announce_placeholder": "Tu mensaje …", + "announce_send": "Decir", + "announce_sent": "Dicho: «{message}»", + "announce_failed": "El anuncio falló: {error}", + "announce_phrase_1": "¡La comida está lista!", + "announce_phrase_2": "¡Hora de dormir!", + "announce_phrase_3": "¡Bajad, por favor!", + "announce_phrase_4": "¡Salimos enseguida!", + "announce_phrase_5": "¡Hay que sacar al perro!", + "state_recording": "Grabando", + "state_streaming": "Transmitiendo", + "panel_all_off": "Apagar todo", + "readable": "Fácil de leer", + "readable_hint": "Más contraste y texto más grande: para tabletas de pared y quien lea mejor así.", + "plain": "Solo plano", + "plain_hint": "Muestra solo paredes, puertas, ventanas y escaleras, sin muebles. Los dispositivos y sus marcadores se mantienen.", + "right_back": "Clic derecho = atrás", + "right_back_hint": "Un clic derecho corto en la vista 3D retrocede un paso: de la habitación a la planta, de la planta a la casa (como un doble toque en un espacio vacío). Arrastrar con el botón derecho sigue desplazando la vista.", + "stl": "Impresión 3D (STL)", + "stl_hint": "Guarda la casa como archivo STL (paredes, suelos, muebles y exteriores de todas las plantas) para impresión 3D, a escala 1:100 (un metro son 10 mm). No incluye ventanas, luces ni tejado; un slicer repara el archivo si hace falta.", + "card_plain": "Solo plano", + "card_rooms": "Solo estas habitaciones", + "card_rooms_hint": "La tarjeta muestra solo las habitaciones marcadas con sus muebles, dispositivos, puertas y ventanas (por ejemplo para una tableta en la cocina). Sin marcar: todo el plano.", + "card_templates": "Plantillas de tarjeta", + "card_templates_hint": "Configura una tarjeta una vez aquí (con los ajustes de la propia tarjeta) e indica solo su nombre en cada tableta: `template: kitchen_tablet`. Los cambios llegan a todas las tarjetas que la usan; lo que figura en la propia tarjeta prevalece sobre la plantilla.", + "template_name": "Nueva plantilla (nombre)", + "template_add": "Crear plantilla", + "template_reload": "Recargar las pantallas con esta plantilla", + "template_reload_all": "Recargar todas las pantallas", + "template_use": "En la tarjeta del panel: `template: {name}`", + "card_template": "Plantilla de tarjeta", + "card_template_none": "ninguna (solo esta tarjeta)", + "card_readable": "Fácil de leer", + "all_off_n": "Apagar todo ({n})", + "all_off_hint": "Apaga luces, interruptores, ventiladores y medios de la habitación; se puede deshacer durante diez segundos.", + "all_off_done": "Todo apagado.", + "all_off_undo": "Deshacer", + "all_off_floor": "Apagar todo en {floor} ({n} dispositivos), deshacer durante diez segundos", + "mood_save": "Guardar ambiente", + "mood_save_hint": "Guarda cómo brillan ahora las lámparas de la estancia como ambiente – un toque lo restablece después, «→» lo lleva a otra estancia.", + "mood_new": "Ambiente", + "mood_set": "Aplicar este ambiente", + "mood_carry": "Llevar a otra estancia", + "panel_all_on": "Encender todo", + "view_options": "Vista: calidad, aspecto, marcadores, FPS", + "panel_all_open": "Subir todo", + "panel_all_close": "Bajar todo", + "central": "Central: todas las luces, persianas y favoritos", + "central_house": "Toda la casa", + "central_lights": "Luces", + "central_covers": "Persianas", + "central_on": "Encender", + "central_off": "Apagar", + "central_open": "Subir", + "central_close": "Bajar", + "central_sure": "¿Seguro?", + "central_favorites": "Favoritos", + "central_no_favorites": "Aún no hay favoritos. Define escenas, scripts e interruptores en el editor en \"Favoritos\".", + "card_central": "Estrella con el menú central", + "card_central_hint": "Todas las luces y persianas de la planta o de la casa y los favoritos del editor.", + "favorites": "Favoritos", + "favorites_hint": "Escenas, scripts, automatizaciones, botones e interruptores para el menú central (estrella) de la vista 3D: fiesta, simulación de presencia, sombreado, riego.", + "favorites_add": "Añadir un favorito", + "favorite_floor": "En qué planta aparece este favorito", + "favorite_all_floors": "Todas las plantas", + "outside_hidden": "Exterior: ocultar dispositivos", + "outside_hidden_hint": "Dispositivos que el panel Exterior no debe mostrar (siguen en el plano).", + "outside_hidden_add": "Ocultar un dispositivo", + "room_facts": "Panel de la habitación: datos mostrados", + "room_fact_sun": "Horas de sol", + "room_fact_comfort": "Confort", + "room_fact_air": "Aviso de ventilación", + "room_fact_circuits": "Circuitos", + "background_handles_hint": "La imagen tiene ahora tiradores como un mueble: arrastrar la mueve, la esquina inferior derecha la escala, el tirador redondo de arriba la gira (Mayús para pasos de 15°). Cuando encaje, toca \"Hecho\" y se quedará fija.", + "background_fixed_hint": "La imagen se queda fija, puedes dibujar encima. Para ajustarla, toca \"Mover, escalar y girar\".", + "bg_level": "Enderezar", + "bg_level_cancel": "Cancelar el enderezado", + "bg_level_first": "Toca el inicio de una pared de la imagen que deba quedar recta (horizontal o vertical).", + "bg_level_second": "Ahora toca el final de esa pared; la imagen gira para ajustarse.", + "bg_ruler": "Escalar con una regla", + "bg_ruler_cancel": "Cancelar la regla", + "bg_ruler_first": "Toca el inicio de un tramo de longitud conocida en la imagen, p. ej. una pared acotada.", + "bg_ruler_second": "Ahora toca el final del tramo.", + "bg_ruler_length_hint": "Medido en el plano: {m} m. Introduce la longitud real y la imagen se escalará para ajustarse.", + "bg_ruler_length": "Longitud real (m)", + "bg_ruler_apply": "Aplicar la escala", + "thumbs_fold": "Plegar las imágenes de las plantas en botones", + "thumbs_show": "Mostrar de nuevo las imágenes de las plantas", + "room_start_view": "Vista como inicio de esta estancia", + "room_start_view_hint": "Al tocar la estancia en 3D, la cámara vuela exactamente a la vista que muestra ahora el panel 3D de la derecha: ángulo, zoom y encuadre. Activa primero 3D al lado, gira y acerca la estancia y luego toca.", + "room_start_view_reset": "Quitar la vista de inicio de la estancia (de nuevo desde arriba)", + "room_start_view_need_pane": "Activa primero \"3D al lado\" y gira y acerca la estancia como deba abrirse.", + "floor_start_view": "Vista como inicio de esta planta", + "floor_start_view_hint": "Esta planta se abre en 3D tal como está ahora el panel 3D de la derecha, p. ej. la planta baja desde delante y la superior desde detrás. Activa primero 3D al lado, gíralo y luego toca.", + "floor_start_view_reset": "Quitar la vista de inicio de la planta (como la casa de nuevo)", + "floor_start_view_need_pane": "Activa primero \"3D al lado\" y gira la planta como deba abrirse.", + "ambilight": "Brillo detrás del TV (%)", + "ambilight_hint": "Con qué intensidad brilla detrás del TV mientras reproduce. 0 lo apaga (por ejemplo si tienes tiras LED en el TV), 100 es la intensidad habitual.", + "sound_rings": "Ondas de sonido (%)", + "sound_rings_hint": "Tamaño de las ondas alrededor del altavoz mientras suena. 0 las desactiva, la imagen y el brillo se mantienen; 100 es el tamaño habitual. El tamaño también sigue el volumen del altavoz: más bajo, más pequeño.", + "glow_scale": "Brillo en 3D (%)", + "light_effects": "Animaciones de efectos en 3D", + "light_effects_hint": "Asigna solo nombres de efecto exactos de HA. Los efectos sin asignar mantienen el color estático de HA. No cambia nada en Home Assistant.", + "light_effects_enabled": "Permitir animaciones para esta lámpara", + "light_effect_unmapped": "Sin asignar (estático)", + "light_effect_add": "Añadir nombre de efecto exacto", + "light_effect_name_limit": "El nombre exacto del efecto debe tener entre 1 y 255 caracteres. No se acortará.", + "light_effect_count_limit": "Como máximo 100 asignaciones. Quita primero una existente.", + "light_effect_exists": "Este nombre de efecto ya está asignado. Se conserva su asignación existente.", + "light_animation_none": "Estático", + "light_animation_rainbow": "Arcoíris (sustituye el color)", + "light_animation_pulse": "Pulso (intensidad)", + "light_animation_flicker": "Parpadeo (intensidad)", + "glow_scale_hint": "Con qué intensidad brilla la lámpara en 3D: por debajo del 100 % atenúa tiras LED potentes para que la estancia no se queme; por encima del 100 % hace brillar más una lámpara débil. No conmuta nada en Home Assistant.", + "vehicle_to_spot": "Convertir en plaza de aparcamiento", + "vehicle_to_spot_hint": "Un vehículo como mueble simple está siempre ahí. Como plaza de aparcamiento solo aparece mientras un sensor detecta el coche, y ahí se vincula el dispositivo del coche (carga, autonomía, cierre, climatización).", + "as_furniture": "Mostrar como mueble", + "as_furniture_hint": "Sustituye el marcador por un mueble en el mismo lugar, vinculado a este dispositivo: un altavoz para un reproductor multimedia, una lámpara para una luz. Ctrl+Z lo deshace.", + "as_furniture_pick": "Elegir mueble …", + "as_device": "Volver a marcador de dispositivo", + "as_device_hint": "Sustituye el mueble por el marcador simple de su dispositivo en el mismo lugar.", + "presets": "Emisoras y listas (Sonido)", + "presets_hint": "Se muestran en el menú rápido de cada altavoz en \"Reproducir\", junto a las fuentes del reproductor. Para un Echo (Alexa Media Player): escribe SPOTIFY, AMAZON_MUSIC o TUNEIN y como contenido lo que dirías (\"Rock Antenne\"). Para Sonos, Music Assistant y otros: escribe music o url con una dirección de stream o un URI.", + "preset_type": "Tipo", + "preset_type_hint": "media_content_type de play_media, p. ej. music, url, playlist, SPOTIFY, AMAZON_MUSIC, TUNEIN", + "preset_content": "Contenido", + "preset_content_hint": "media_content_id: URL de stream, URI (spotify:playlist:…) o, para Alexa, una frase de búsqueda", + "preset_speakers": "Solo en estos altavoces (ninguno = en todos)", + "media_play": "Reproducir", + "media_pause": "Pausa", + "media_previous": "Anterior", + "media_next": "Siguiente", + "media_volume": "Volumen", + "media_sources": "Fuentes", + "preset_add": "Emisora o lista", + "own_buttons": "Botones propios", + "own_buttons_hint": "Se muestran en el menú central (estrella) bajo los favoritos: abrir una ruta de dashboard, mostrar los detalles de una entidad, llamar a un servicio o abrir un popup de browser_mod con tu propia tarjeta.", + "own_alerts": "Avisos propios", + "circuits": "Cuadro eléctrico", + "circuits_hint": "Los circuitos con las habitaciones que alimentan. El panel de la habitación los nombra y la búsqueda los encuentra («F12»).", + "circuit_name": "Nombre", + "circuit_new": "Nuevo circuito", + "circuit_add": "Añadir un circuito", + "circuit_add_room": "Añadir una habitación", + "own_alerts_hint": "Una línea en la barra de avisos de la vista 3D mientras una entidad está en un estado – «Depósito vacío» del robot, «Lavavajillas terminado». Varios estados con comas; para números <20 o >80.", + "own_alert_entity": "Cuando …", + "own_alert_state": "… está en el estado (vacío = encendido)", + "own_alert_text": "… entonces este aviso", + "own_alert_color": "Color", + "own_alert_tap": "Un toque", + "own_alert_tap_info": "abre los detalles", + "own_alert_tap_toggle": "cambia la entidad", + "own_alert_tap_room": "salta a la estancia", + "own_alert_house": "Toda la casa", + "own_alert_new": "Nuevo aviso", + "own_alert_add": "Añadir aviso", + "today": "Hoy", + "today_none": "Nada previsto para hoy.", + "today_calendars": "Calendarios para «Hoy»", + "today_calendars_hint": "Las citas de estos calendarios aparecen arriba a la derecha en la vista 3D en la tarjeta «Hoy», junto con los contenedores que se recogen hoy o mañana. Un toque en el título pliega la tarjeta.", + "own_button_state": "Se ilumina mientras … está encendido (opcional)", + "own_button_label": "Etiqueta", + "own_button_action": "Acción", + "own_button_new": "Nuevo botón", + "own_button_add": "Botón propio", + "own_action_navigate": "Abrir una ruta", + "own_action_more_info": "Detalles de la entidad", + "own_action_service": "Llamar a un servicio", + "own_action_fire_dom_event": "fire-dom-event (browser_mod)", + "own_target_navigate": "Ruta", + "own_target_more_info": "Entidad", + "own_target_service": "Servicio (dominio.servicio)", + "own_data": "Datos (JSON)", + "own_data_hint": "Para un servicio sus datos, para fire-dom-event el contenido del evento, p. ej. {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}.", + "own_data_bad": "No es un objeto JSON válido.", + "panel_no_area": "Esta estancia no está vinculada a un área. Puedes vincularla en el editor.", + "panel_empty": "Ningún dispositivo de esta estancia está en el plano. En el editor, coloca dispositivos o elígelos para el panel de la estancia con ☆.", + "close": "Cerrar", + "panel_fold": "Plegar (la estancia sigue a la vista)", + "panel_unfold": "Abrir de nuevo", + "brightness": "Brillo", + "color_temp": "Temperatura de color", + "color": "Color", + "position": "Posición", + "cover_open": "Abrir", + "cover_stop": "Parar", + "cover_tilt": "Lamas", + "cover_tilt_open": "Lamas abiertas", + "cover_tilt_close": "Lamas cerradas", + "cover_close": "Cerrar", + "target_temp": "Objetivo", + "current_temp": "Actual", + "temp_down": "Más frío", + "temp_up": "Más cálido", + "volume": "Volumen", + "play_pause": "Reproducir/pausa", + "previous": "Anterior", + "next": "Siguiente", + "run": "Ejecutar", + "details": "Detalles", + "hold_hint": "Tocar conmuta · pulsación larga abre los detalles", + "tool_opening": "Puertas y ventanas", + "tool_furniture": "Muebles", + "qm_off": "Apagado", + "find": "Buscar", + "find_placeholder": "¿Dónde está …? Dispositivo o estancia", + "find_none": "No se encontró nada", + "swipe_off": "Apagado", + "panel_pin": "Mostrar en el panel de la estancia", + "panel_unpin": "No mostrar en el panel de la estancia", + "devices_panel_hint": "El panel de la estancia muestra los dispositivos del plano. ☆ añade un dispositivo al panel sin colocarlo.", + "card_section_view": "Vista", + "card_size": "Tamaño", + "card_size_fixed": "Altura fija", + "card_size_fill": "Llenar la pantalla", + "card_fill_hint": "Funciona mejor en una vista de dashboard del tipo «Panel (tarjeta única)»: la tarjeta ocupa entonces todo el espacio.", + "card_controls": "Interruptores en la tarjeta", + "card_floor_thumbs": "Plantas en miniatura", + "card_floor_thumbs_hint": "Pequeñas imágenes de las plantas al lado; toca una para cambiar", + "card_floor_thumbs_hint_start": "La planta elegida es entonces donde empieza la tarjeta; las imágenes del lado cambian a las demás", + "card_room_names": "Mostrar nombres de estancias", + "card_section_kiosk": "Tablet de pared (kiosco)", + "card_section_features": "Funciones", + "card_weather_plan": "como en el plano", + "card_pro_hint": "El rastro de movimiento y el muro de cámaras pertenecen a las cámaras: el rastro muestra la última media hora, el muro todas las cámaras del plano.", + "card_idle_return": "Volver a la vista de inicio tras", + "card_idle_off": "Nunca", + "card_idle_min": "{n} min sin tocar", + "card_idle_hint": "Tras la espera, la tarjeta cierra la estancia y vuelve a mostrar la vista de inicio.", + "card_night": "Atenuación nocturna", + "card_night_off": "Apagado", + "card_night_sun": "Según el sol", + "card_night_time": "Franja horaria", + "card_night_range": "Franja horaria (p. ej. 22:00-06:00)", + "card_idle_orbit": "Giro de cámara como salvapantallas", + "card_idle_orbit_hint": "Tras el regreso, la vista gira despacio hasta que alguien toca la tablet", + "card_dashboard": "Botón a un dashboard (ruta)", + "card_dashboard_label": "Etiqueta del botón", + "card_dashboard_hint": "Un botón arriba a la derecha de la tarjeta abre el dashboard o la vista con esta ruta, p. ej. /lovelace/home o /dashboard-house/0. Sin etiqueta muestra ⌂.", + "card_alerts": "Mostrar avisos", + "card_alerts_hint": "Humo, gas, CO, agua, alarma y ventanas abiertas con lluvia: la estancia pulsa y aparece una nota arriba", + "card_alert_jump": "Saltar a la estancia de un aviso nuevo", + "card_alert_jump_hint": "La vista cambia sola a la planta y estancia del aviso", + "card_scenes": "Botones de escena en la estancia", + "card_scenes_hint": "Escenas y scripts del área como botones bajo la vista 3D mientras hay una estancia seleccionada", + "card_sensor_bar": "Sensores propios arriba", + "card_sensor_bar_hint": "Los sensores elegidos en el editor (Ajustes) arriba a la izquierda de la tarjeta", + "card_central_open": "Menú estrella abierto y grande", + "card_central_open_hint": "Los favoritos y botones propios están abiertos desde el inicio, más grandes", + "card_keep_camera": "Mantener la cámara al cambiar de planta", + "card_keep_camera_hint": "El mismo lado, altura y distancia en cada planta", + "card_today": "Tarjeta «Hoy»", + "card_today_hint": "Citas de hoy y contenedores pendientes, arriba a la derecha", + "card_announcements": "Anuncios", + "card_announcements_hint": "Los anuncios (acción «NextFloor: Anuncio») aparecen en grande en la tarjeta, con un timbre, y se dicen en voz alta", + "weather_short": "Tiempo", + "weather_entity": "Entidad del tiempo", + "weather_effects": "Efectos del tiempo en 3D", + "card_weather_density": "Cantidad de lluvia y nieve", + "card_weather_density_hint": "Menos gotas y copos de los que indica el tiempo; nubes, niebla y rayos se mantienen", + "rain_warning": "Aviso: ventana abierta mientras llueve", + "sun_patches": "Sol y sombras", + "sun_patches_hint": "Con el norte definido, la luz del sol de sun.sun entra por las ventanas como manchas claras en el suelo y la casa proyecta su sombra sobre la parcela. Desmárcalo para dejar suelo y parcela sin manchas de sol ni sombras.", + "sun_arc": "Arco solar y brújula", + "sun_arc_hint": "Dibuja el recorrido del sol de hoy como un arco sobre la parcela, con un anillo y los puntos cardinales en el suelo (norte en rojo). Necesita la ubicación de tu casa en Home Assistant.", + "weather_effect_rain": "Lluvia", + "weather_effect_snow": "Nieve", + "weather_effect_fog": "Niebla (agrisa la escena)", + "weather_effect_clouds": "Las nubes oscurecen el cielo y el sol", + "weather_effect_lightning": "Rayos en las tormentas", + "weather_effect_sky": "Sol y luna en el cielo", + "weather_entity_hint": "Qué entidad del tiempo controla el cielo alrededor de la casa. Automático usa la primera encontrada.", + "weather_hint": "Tiempo en la casa: lluvia y nieve caen con el viento real, las nubes cruzan la parcela con sus sombras, rayos, niebla, sol y luna", + "card_weather": "Tiempo exterior", + "card_weather_hint": "Lluvia, nieve, granizo, nubes con sombras, rayos y niebla de la primera entidad del tiempo (weather_entity elige otra); menos partículas en el nivel tablet", + "alerts": "Avisos", + "alert_smoke": "Humo: {name}", + "alert_gas": "Gas: {name}", + "alert_co": "Monóxido de carbono: {name}", + "alert_water": "Agua: {name}", + "alert_alarm": "Alarma activada", + "alert_alarm_by": "Alarma disparada por {cause}", + "alert_alarm_pending": "Alarma pendiente", + "alert_window_rain": "Ventana abierta con lluvia: {name}", + "alert_power_outage": "Corte de luz: {name}", + "alert_contact_lost": "El contacto no responde: {name}", + "rain_sensor": "Sensor de lluvia (estación meteorológica propia)", + "outage_sensor": "Sensor de corte de luz", + "outage_hint": "Un sensor binario de clase power apagado, otro sensor binario encendido, un estado como \"off_grid\" o \"backup\", o una tensión por debajo de 50 V lanzan un aviso para toda la casa.", + "contact_warning": "Avisar cuando un contacto de puerta o ventana no esté disponible", + "contact_warning_hint": "Si un contacto lleva 10 minutos no disponible (batería vacía, fuera de alcance), la ventana parece cerrada en 3D aunque nadie lo sabe. Entonces un aviso nombra el contacto. Reiniciar Home Assistant no avisa.", + "night_lock_warning": "Avisar de noche si una puerta no está cerrada con llave", + "night_lock_warning_hint": "Entre las 22 y las 6 h una nota nombra las cerraduras del plano que están abiertas.", + "alert_unlocked_night": "Sin cerrar con llave: {name}", + "motion_markers_active": "Mostrar los sensores de movimiento solo mientras detectan", + "motion_markers_active_hint": "Se aplica a los sensores de movimiento, ocupación y presencia. Un sensor cuyo símbolo está ajustado para mostrarse siempre sigue visible.", + "room_double_tap": "Doble toque en una habitación", + "room_double_tap_hint": "Un doble toque en una habitación apaga sus luces si alguna está encendida; si no, las enciende todas. Los dispositivos que preguntan antes siempre quedan fuera.", + "room_double_tap_area": "Lámparas del plano y todas las luces del área", + "room_double_tap_plan": "Solo las lámparas del plano", + "room_double_tap_off": "No conmutar nada", + "card_room_double_tap_auto": "Como en el plano", + "status_entities": "Sensores propios arriba en la vista 3D", + "status_add": "Añadir un sensor", + "status_entities_hint": "Por ejemplo la temperatura exterior, la alarma o la calidad del aire: aparecen arriba a la izquierda con nombre y valor, también en una habitación abierta. Al tocar se abren los detalles. Hasta 12.", + "announce_tts": "Texto a voz para anuncios", + "announce_phrases": "Frases para anuncios (una por línea)", + "announce_phrases_hint": "Vacío: las frases incluidas. Los anuncios también existen como acción «NextFloor: Anuncio» para automatizaciones, en los altavoces de las habitaciones y en cada pantalla de NextFloor abierta.", + "opening_rain_warning": "Avisar cuando llueve", + "opening_light_well": "Patio inglés delante", + "sill_boards": "Alféizar y repisa", + "sill_boards_auto": "Automático", + "sill_boards_none": "Ninguno", + "sill_boards_inside": "Solo interior", + "sill_boards_outside": "Solo exterior", + "room_names_short": "Nombres de estancias", + "floor_stack_short_dim": "Atenuadas", + "floor_stack_short_stacked": "Apiladas", + "floor_stack_short_single": "Sola", + "size_short_w": "An", + "size_short_d": "Fo", + "size_short_h": "Al", + "import_error_not_json": "El archivo no es JSON.", + "import_error_not_plan": "El archivo no es un plano de NextFloor.", + "import_other_hint": "Desde Sweet Home 3D: importa aquí el archivo .sh3d. Se traen plantas, estancias, puertas, ventanas y paredes libres; los muebles no.", + "import_sh3d_found": "Sweet Home 3D: {floors} plantas, {rooms} estancias, {openings} puertas y ventanas, {walls} paredes libres ({furniture} muebles no se traen).", + "import_dxf_found": "DXF: {rooms} estancias (polilíneas cerradas) y {walls} paredes libres (líneas) en una planta.", + "import_ifc_found": "En el archivo IFC: {floors} plantas y {rooms} habitaciones (NextFloor dibuja las paredes a partir de las habitaciones).", + "import_roomplan_found": "Escaneo de habitación (RoomPlan): {rooms} habitaciones, {openings} puertas y ventanas; {skipped} objetos no se importaron (los muebles los colocas tú).", + "import_error_roomplan_empty": "El escaneo no tiene paredes.", + "import_error_ifc_empty": "El archivo IFC no tiene espacios (IfcSpace) con planta.", + "import_error_dxf_empty": "El archivo DXF no tiene líneas ni polilíneas.", + "import_error_sh3d": "Este no es un archivo de Sweet Home 3D legible (necesita Sweet Home 3D 5.3 o posterior).", + "import_error_sh3d_empty": "El archivo de Sweet Home 3D no tiene estancias ni paredes.", + "export_name_template": "plantilla", + "export_name_backup": "copia", + "card_floor_stack": "Plantas inferiores", + "floor_stack_dim": "Atenuadas", + "floor_stack_stacked": "Apiladas (la casa hasta aquí)", + "floor_stack_single": "Ocultas (solo esta planta)", + "card_control_walls": "Paredes altas/corte", + "card_control_floors": "Plantas separadas", + "card_control_temperature": "Temperatura", + "card_control_humidity": "Humedad", + "card_control_co2": "CO₂", + "card_controls_hint": "Paredes altas/corte, plantas separadas y temperatura, humedad, CO₂ para cambiar", + "controls_hide": "Ocultar los controles; solo queda la vista 3D", + "nav_wrap": "Ajustar la barra: todas las plantas y estancias en varias líneas", + "bars_fold": "Plegar los interruptores", + "bars_unfold": "Interruptores", + "nav_row": "Barra en una línea (se desplaza de lado)", + "controls_show": "Mostrar de nuevo los controles", + "card_controls_hidden": "Empezar con los controles ocultos", + "card_controls_hidden_hint": "Solo la vista 3D; un ojo abajo a la izquierda devuelve barras, valores e interruptores", + "card_controls_hide_after": "Ocultar los controles tras", + "card_hide_after_s": "{n} s sin tocar", + "card_fullscreen_button": "Botón de pantalla completa", + "card_fullscreen_button_hint": "Oculta el dashboard alrededor de la tarjeta (p. ej. en una tablet de pared)", + "fullscreen": "Pantalla completa", + "fullscreen_exit": "Salir de pantalla completa", + "card_section_show": "Mostrar", + "card_floor": "Planta", + "card_floor_house": "Toda la casa (toca una planta para abrirla)", + "card_height": "Altura (píxeles)", + "card_walls": "Paredes", + "card_quality_hint": "«Tablet» es el ajuste más ligero, ideal para tablets Fire y otras tablets de pared.", + "card_flows_switch": "Interruptor en la tarjeta", + "card_flows_on": "Siempre activado", + "card_flows_off": "Siempre desactivado", + "holos": "Tarjetas", + "holos_hint": "Mostrar u ocultar las tarjetas en vivo sobre la casa (balance energético, coche, multimedia)", + "card_energy": "Mostrar valores de energía arriba", + "card_room_panel": "Detalles de la estancia al tocar", + "card_room_buttons": "Botones de estancia", + "card_room_buttons_hint": "Una fila con un botón por estancia arriba en la tarjeta; toca uno para abrir la estancia, como al tocarla en el modelo", + "card_room_panel_hint": "Las luces y persianas de la estancia en un panel lateral", + "card_explode": "Separar las plantas en la vista de la casa", + "card_roof_fade": "Desvanecer el tejado al acercar el zoom", + "card_roof_fade_hint": "Desactivado: el tejado se queda en la casa aunque la cámara se acerque.", + "card_stats": "Indicador de rendimiento (fotogramas por segundo)", + "card_stats_hint": "Para comprobar lo fluida que va la tarjeta en el dispositivo", + "packs": "Packs de muebles", + "lib_badge_light": "Lámpara: se vincula a una luz y conmuta en 3D", + "lib_badge_electric": "Eléctrico: se vincula a una entidad y a un sensor de potencia (conmutar, imágenes, consumo)", + "lib_badge_hint": "Los elementos con un símbolo se vinculan a entidades: las lámparas conmutan, las pantallas muestran imágenes, los electrodomésticos muestran su consumo.", + "care_bin_today": "Se recoge hoy", + "care_bin_tomorrow": "Se recoge mañana", + "care_bin_days": "En {n} días", + "care_mail_yes": "Hay correo", + "care_mail_no": "Vacío", + "care_plant_thirsty": "Sedienta", + "care_plant_ok": "Bien regada", + "care_time_left": "Quedan {time}", + "care_entity_bin": "Fecha de recogida (sensor)", + "care_entity_mail": "Sensor de correo", + "care_entity_plant": "Humedad del suelo (sensor)", + "care_thirsty_below": "Sedienta por debajo de (%)", + "care_hint_bin": "Un sensor con la próxima recogida: días, una fecha, \"hoy\"/\"mañana\" o la integración Waste Collection Schedule. El cubo brilla el día anterior y el mismo día.", + "care_hint_mail": "Un sensor que indica que hay correo en el buzón (un contacto en la trampilla, por ejemplo). El buzón brilla entonces.", + "care_hint_plant": "Un sensor de humedad en la tierra. Por debajo del umbral la planta brilla y dice que tiene sed.", + "lib_cat_lights": "Luces", + "lib_cat_seating": "Asientos", + "lib_cat_tables": "Mesas", + "lib_cat_storage": "Armarios y estanterías", + "lib_cat_beds": "Camas", + "lib_cat_kitchen": "Cocina", + "lib_cat_appliances": "Electrodomésticos", + "lib_cat_bath": "Baño", + "lib_cat_media": "TV y audio", + "lib_cat_office": "Oficina", + "lib_cat_tech": "Tecnología", + "lib_cat_climate": "Calefacción y clima", + "lib_cat_energy": "Energía", + "lib_cat_garden": "Jardín y terraza", + "lib_cat_plants": "Plantas", + "lib_cat_kids": "Niños", + "lib_cat_fitness": "Fitness", + "lib_cat_pets": "Mascotas", + "lib_cat_workshop": "Taller y garaje", + "lib_cat_music": "Música y estudio", + "lib_cat_season": "Temporada y decoración", + "lib_cat_pictures": "Cuadros y marcos", + "lib_cat_vehicles": "Vehículos", + "lib_cat_building": "Escaleras y elementos de obra", + "lib_cat_decor": "Decoración y más", + "lib_favourites": "Favoritos", + "lib_recent": "Usados recientemente", + "lib_for_room": "Encaja en {room}", + "lib_all_rooms": "Mostrar todas las estancias", + "lib_linkable": "vinculable", + "lib_lit": "iluminado", + "lib_outdoor": "exterior", + "lib_fav_add": "Añadir a favoritos", + "lib_fav_remove": "Quitar de favoritos", + "lib_sizes": "Tamaños", + "feature_name_energy": "Flujo de energía", + "ext_tab": "Extensiones", + "ext_title": "Extensiones", + "models": "Tus propios modelos 3D", + "models_hint": "Para algunos vehículos NextFloor puede mostrar un modelo 3D real si tienes uno. Elige aquí el archivo (.glb): NextFloor lo orienta correctamente, lo aligera, marca la pintura y lo guarda en tu Home Assistant. Sin modelo, el vehículo se ve como antes.", + "models_licence": "Los archivos son tuyos y se quedan en tu Home Assistant. NextFloor no incluye modelos; asegúrate de que la licencia de tu modelo te permite usarlo en tu propia instalación.", + "model_add": "Añadir un modelo …", + "model_replace": "Sustituir el modelo …", + "model_remove": "Quitar", + "model_present": "en uso", + "model_missing": "ninguno todavía", + "model_remove_confirm": "¿Eliminar el modelo «{id}» de Home Assistant?", + "model_removed": "Modelo «{id}» eliminado.", + "model_uploaded": "Modelo «{id}» guardado ({size}). Recarga el panel para verlo.", + "model_upload": "Guardar en Home Assistant", + "model_info": "{triangles} triángulos, {size} m", + "model_front": "Frente", + "model_front_hint": "Gira el modelo hasta que su frente mire al espectador (hacia abajo a la izquierda en la imagen).", + "model_paint": "Pintura (el color que eliges en el editor)", + "model_paint_preview": "Color en la vista previa", + "model_detail": "Nivel de detalle", + "model_detail_light": "Ligero (tablet)", + "model_detail_normal": "Normal", + "model_detail_fine": "Fino", + "model_result": "Resultado: {triangles} triángulos, {size}", + "model_error_not_glb": "Este no es un archivo .glb (glTF binario). Exporta el modelo como «glTF binario».", + "model_error_compressed": "El archivo está comprimido (Draco, Meshopt o KTX). Expórtalo sin compresión.", + "model_error_empty": "El archivo no contiene nada tridimensional.", + "model_error_unreadable": "No se puede leer el archivo: {detail}", + "model_error_too_large": "El archivo supera {max}. Elige un nivel de detalle menor.", + "model_upload_forbidden": "Solo los administradores pueden subir modelos.", + "model_upload_too_large": "Home Assistant no acepta archivos de más de {max}. Elige un nivel de detalle menor.", + "model_upload_not_glb": "Home Assistant rechazó el archivo (no es un glTF binario).", + "model_upload_bad_id": "El id del modelo no es válido.", + "model_upload_other": "La subida no funcionó: {detail}", + "ext_intro": "Importa tus propios packs de muebles, sube tus propios modelos 3D y añade plugins aquí.", + "plugin": "plugin", + "plugins_title": "Plugins", + "plugins_intro": "Los plugins añaden tus propias animaciones de luz, dispositivos y tarjetas en el panel de la estancia. Introduce la dirección de un plugin (un archivo .js en /config/www, es decir /local/…, de HACS /hacsfiles/…, o https://…).", + "plugins_docs": "Cómo escribir un plugin", + "plugins_warning": "Los plugins se ejecutan con los mismos permisos que NextFloor en tu navegador. Usa solo plugins de fuentes de confianza.", + "plugins_off": "desactivado", + "plugins_error": "error", + "plugins_loading": "cargando …", + "plugins_nothing_registered": "cargado, pero no registró nada", + "plugins_loaded": "activo", + "plugins_reload_hint": "Surte efecto tras recargar la página", + "plugins_remove": "Quitar", + "plugins_none": "Aún no hay plugins.", + "plugins_from_dashboard": "Registrado por un recurso del dashboard", + "plugins_add": "Añadir", + "plugins_url_invalid": "Introduce una dirección .js bajo /local/…, /hacsfiles/… o https://….", + "plugins_exists": "Este plugin ya está en la lista.", + "plugins_limit": "Como máximo 20 plugins.", + "packs_title": "Packs de muebles", + "packs_intro": "Importa tus propios muebles como pack (JSON): como archivo o pegado abajo. {n} packs vienen con NextFloor y están siempre disponibles.", + "packs_docs": "Formato de pack", + "packs_none": "Aún no hay packs propios.", + "community_title": "Muebles de la comunidad", + "community_intro": "Muebles que otros han construido y compartido con el constructor de muebles, revisados y gratis. Construye los tuyos:", + "community_builder": "Abrir el constructor de muebles", + "community_how": "Cómo compartir los tuyos", + "community_load": "Cargar muebles de la comunidad", + "community_none": "Todavía no hay muebles de la comunidad: ¡sé el primero!", + "community_install": "Instalar", + "community_update": "Actualizar", + "community_installed": "Instalado", + "community_failed": "No se pudieron cargar los muebles de la comunidad: {detail}", + "pack_import": "Importar archivos de pack …", + "pack_paste": "Importar JSON", + "pack_paste_empty": "Pega primero el JSON de un pack.", + "pack_paste_not_json": "Esto no es JSON válido: {detail}", + "pack_imported": "Importado «{name}» de {publisher}: {n} elementos", + "packs_imported_n": "{n} de {total} packs importados", + "pack_by": "de {publisher} · {n} elementos", + "pack_remove": "Quitar", + "pack_remove_confirm": "¿Quitar el pack «{name}»? Sus muebles se quedan en el plano como cajas simples.", + "pack_error_not_a_pack": "Esto no es un pack de muebles (falta \"format\": \"nfpack\").", + "pack_error_builtin": "Un pack incluido con NextFloor ya tiene este id.", + "pack_error_invalid_content": "El pack contiene muebles no válidos: {detail}", + "pack_error_too_large": "El pack es demasiado grande (1 MB como máximo).", + "pack_error_needs_update": "Este pack necesita una versión más reciente de NextFloor. Actualiza primero (HACS › NextFloor › ⋮ › \"Información de actualización\" › \"Descargar\"), reinicia Home Assistant y vuelve a importar.", + "pack_error_other": "Error al importar: {detail}", + "store_open": "Abrir la tienda de plugins", + "store_close": "Cerrar la tienda de plugins", + "store_intro": "Plugins revisados de la comunidad. Cada uno se revisa antes de añadirse y no cambia después.", + "store_submit": "Enviar tu propio plugin", + "store_empty": "Aún no hay plugins en la tienda.", + "store_failed": "No se pudo cargar la tienda ({error}).", + "store_install": "Instalar", + "store_installed": "instalado", + "store_update": "Actualizar", + "store_confirm": "¿Instalar «{name}» de {author}?\n\nUn plugin se ejecuta con los mismos permisos que NextFloor en tu navegador. El archivo ha sido revisado y su contenido es fijo:\n{url}", + "manual": "Manual", + "manual_more": "Más información", + "feature_text_energy": "Partículas de energía vuelan en arcos desde los campos solares al inversor, entre casa, batería, red y consumidores, más rápidas y densas cuanta más potencia fluye. Los módulos centellean con su producción y una tarjeta de cristal sobre el tejado muestra el balance y lo autosuficiente que es la casa ahora mismo.", + "live_autarky": "autonomía", + "live_day_hint": "Las últimas 24 horas: solar (área) y consumo (línea)", + "live_week_hint": "Los últimos 7 días: sol {solar} kWh, consumo {use} kWh (amarillo: sol, claro: consumo)", + "live_days": "días", + "live_car_away": "En ruta", + "live_car_charging": "Cargando", + "live_car_plugged": "Enchufado", + "live_car_lock": "Bloquear", + "live_car_unlock": "Desbloquear", + "live_car_unlock_confirm": "¿Desbloquear realmente {name}?", + "live_car_climate": "Climatización", + "live_car_charge": "Iniciar/detener carga", + "live_media_prev": "Anterior", + "live_media_playpause": "Reproducir/pausa", + "live_media_next": "Siguiente", + "live_media_volume": "Volumen", + "live_car_device": "Coche (cualquier entidad del coche)", + "live_car_device_hint": "NextFloor encuentra carga, autonomía, carga en curso, enchufe, cierre y climatización en el dispositivo del coche. Sin él usa el sensor de presencia de la plaza.", + "live_car_departure_entity": "Hora de salida (opcional)", + "live_car_departure": "Salida a las {time}", + "live_car_open": "Abierto: {parts}", + "printer_printing": "imprimiendo", + "printer_done": "terminado", + "printer_paused": "en pausa", + "printer_error": "error", + "printer_idle": "lista", + "printer_done_at": "lista a las {time}", + "printer_layer": "Capa", + "printer_nozzle": "Boquilla", + "printer_bed": "Cama", + "heatpump_heating": "calentando", + "heatpump_water": "agua caliente", + "heatpump_cooling": "enfriando", + "heatpump_defrost": "desescarchando", + "heatpump_idle": "en reposo", + "heatpump_flow_return": "Impulsión → retorno", + "heatpump_heat": "Calor", + "heatpump_power": "Electricidad", + "heatpump_outside": "fuera", + "pack_missing_item": "Mueble de un pack eliminado", + "back_to_room": "Volver a {room}", + "back_to_floor": "Volver a la planta", + "hint_furniture": "Toca una estancia y elige un elemento a la derecha · arrastra los elementos, cambia su tamaño por las esquinas", + "furniture_into": "Los elementos nuevos van al centro de «{room}».", + "furniture_pick_room": "Consejo: toca primero una estancia; los elementos nuevos aparecerán en su centro.", + "flows": "Flujo de energía", + "flows_hint": "Mostrar u ocultar los arcos de energía entre campos solares, inversor, batería, red y consumidores", + "chk_title": "Configuración", + "chk_hint": "Lo que necesita el flujo de energía. Toca una fila para ir allí.", + "chk_solar": "Campo solar colocado", + "chk_solar_add": "Pon un campo solar en el tejado", + "chk_meter": "Contador con sensor de red", + "chk_meter_sensor": "Contador: falta el sensor de red (W)", + "chk_meter_add": "Añadir el contador", + "chk_inverter": "Inversor con sensor de potencia", + "chk_inverter_sensor": "Inversor: falta el sensor de potencia", + "chk_inverter_add": "Añadir un inversor", + "chk_battery": "Batería doméstica con potencia y carga", + "chk_battery_sensor": "Batería doméstica: falta la potencia o la carga", + "chk_battery_opt": "Batería doméstica (opcional)", + "chk_grid": "Conexión a la red definida", + "chk_grid_opt": "Conexión a la red (opcional, si no automática)", + "energy_sign_grid": "La casa muestra exportación mientras el sol no produce nada. Probablemente el sensor de red tiene el signo invertido.", + "energy_sign_battery": "La batería carga sin sol y sin consumo de red. Probablemente su sensor tiene el signo invertido.", + "energy_sign_flip": "Invertir el signo", + "help_title": "Ayuda y comentarios", + "help_hint": "Informa de los problemas como issue en GitHub y de los deseos como discussion: nada se pierde y todos ven el estado.", + "help_issue": "Informar de un problema", + "help_idea": "Proponer una idea", + "furn_name": "Nombre (opcional)", + "furn_mirror": "Reflejar", + "furn_mirror_hint": "Intercambiar izquierda y derecha: el sofá en L al revés, el armario con la puerta al otro lado, la cocina reflejada.", + "hint_opening": "Toca una pared para añadir una puerta o ventana; elige su tipo a la derecha después", + "preset_door": "Puerta", + "preset_door_double": "Puerta doble", + "preset_window": "Ventana", + "preset_window_double": "Ventana doble", + "preset_terrace": "Puerta de terraza", + "preset_terrace_double": "Puertas francesas", + "preset_lift_slide": "Puerta corredera elevable", + "preset_garage": "Puerta de garaje", + "preset_front": "Puerta de entrada", + "opening_style": "Estilo", + "sidelight_auto": "automático", + "sidelight_hinge": "Lateral de cristal en el lado de las bisagras", + "sidelight_hinge_hint": "Si no, el lateral queda frente a las bisagras; marcado, queda junto a ellas.", + "sidelight_width": "Ancho del lateral (m)", + "sidelight_width_left": "Lateral izquierdo (m)", + "sidelight_width_right": "Lateral derecho (m)", + "style_auto": "Automático ({style})", + "style_interior": "Puerta interior", + "style_front": "Puerta de entrada", + "style_front_glass": "Puerta de entrada con cristal", + "style_sidelight": "Puerta de entrada con lateral", + "style_sidelights": "Puerta de entrada con dos laterales", + "style_glass": "Puerta de cristal", + "style_sliding": "Puerta corredera", + "style_passage": "Hueco (sin puerta)", + "style_standard": "Estándar", + "style_bars": "Con travesaños", + "style_glass_wall": "Pared de cristal (fija)", + "preset_glass_wall": "Pared de cristal", + "flip_hinge": "Cambiar el lado de las bisagras", + "flip_main_leaf": "Cambiar la hoja principal", + "flip_hinge_hint": "Bisagras al otro lado", + "flip_swing": "Invertir el sentido de apertura", + "flip_swing_hint": "La puerta abre hacia la estancia o hacia el otro lado", + "main_leaf": "Hoja principal (vista desde la estancia)", + "contact_main": "Contacto hoja principal", + "contact_second": "Contacto segunda hoja", + "tool_outdoor": "Exterior", + "tool_measure": "Por medidas", + "hint_measure": "Toca el punto de inicio y escribe a la derecha las longitudes de pared con su dirección", + "measure": "Estancia por medidas", + "measure_start": "Toca el punto de inicio en el plano, p. ej. una esquina de la estancia.", + "measure_from": "Inicio en {x} / {z} m; tocar mueve el inicio.", + "measure_length": "Longitud de la siguiente pared (m)", + "measure_close": "Cerrar estancia", + "measure_undo": "Quitar la última pared", + "measure_gap": "Hueco hasta el inicio: {gap} m (se une al cerrar)", + "measure_hint": "Consejo: escribe una longitud y pulsa una flecha. Con medidas interiores, usa después «Cerrar huecos».", + "rect_by_size": "Rectángulo por tamaño", + "rect_add": "Añadir rectángulo", + "dir_up": "Arriba", + "dir_down": "Abajo", + "dir_left": "Izquierda", + "dir_right": "Derecha", + "hint_outdoor": "Arrastra para dibujar una zona exterior (césped, terraza, piscina …)", + "outdoor": "Zona exterior", + "outdoor_type": "Tipo", + "outdoor_height": "Altura (m)", + "outdoor_offset": "Desfase de altura (m, − = más bajo)", + "outdoor_outline": "Mostrar el contorno", + "outdoor_outline_hint": "Desmarcado, la zona no dibuja una línea brillante en su borde, para parcelas grandes hechas de varios céspedes.", + "outdoor_corners_hint": "Esquinas: un + en un borde añade una esquina, arrastrar da forma a la zona, × quita una esquina.", + "outdoor_hint": "Las luces exteriores (baliza, foco de jardín, aplique exterior) iluminan todas las zonas exteriores y la fachada.", + "out_lawn": "Césped", + "out_terrace": "Terraza", + "out_path": "Camino", + "out_driveway": "Acceso", + "out_pool": "Piscina", + "out_bed": "Parterre", + "out_hedge": "Seto", + "out_fence": "Valla", + "out_wild": "Zona silvestre", + "out_pergola": "Pérgola / estructura", + "outdoor_open": "Abierta (omitir el último borde)", + "outdoor_open_hint": "El borde del último punto al primero no se dibuja: una valla o pérgola apoyada en la casa.", + "fence_gates": "Puertas en la valla", + "gate_add": "+ Puerta en la valla", + "gate_edge": "Lado de la valla", + "gate_kind": "Tipo", + "gate_single": "Puerta de jardín", + "gate_double": "Puerta doble", + "gate_sliding": "Puerta corredera", + "gate_offset": "Centro desde el inicio (m)", + "gate_width": "Ancho (m)", + "gate_entity": "Motor o interruptor", + "gate_contact": "Contacto (activo = abierto)", + "fence_gates_hint": "Una puerta es un hueco en la valla con postes y hoja. Con un motor (cover, interruptor, input_boolean, cerradura) y/o un contacto se abre en 3D: las puertas de jardín y dobles giran hacia dentro, una corredera se desliza a lo largo de la valla.", + "outdoor_bracing": "Arriostramiento en X", + "outdoor_cut": "Recortar de las zonas que la rodean", + "outdoor_cut_hint": "Cada zona que contenga esta por completo recibe aquí un agujero: una piscina en la terraza, un estanque o una zona silvestre en el césped. El orden de dibujo no importa. Una piscina se recorta sola.", + "outdoor_area_hint": "El área de Home Assistant de esta superficie (jardín, terraza, piscina): sus dispositivos y sensores aparecen en Exterior, y un marcador sobre la superficie lo abre.", + "pool_temp": "Temperatura del agua (opcional)", + "pool_pump": "Bomba / filtro (opcional)", + "pool_pump_on": "bomba en marcha", + "outdoor_slope": "Pendiente (m)", + "outdoor_slope_hint": "Diferencia de altura del borde alto al bajo; el borde alto está en el desfase de altura. Las lámparas sobre la zona la siguen.", + "outdoor_slope_dir": "Cae hacia", + "slope_x": "derecha (+X)", + "slope_nx": "izquierda (−X)", + "slope_z": "abajo (+Z)", + "slope_nz": "arriba (−Z)", + "north": "Norte (° en sentido horario desde arriba)", + "north_hint": "El norte es necesario para el sol (luz por las ventanas).", + "map_on": "Mostrar un mapa real bajo el plano", + "map_lat": "Latitud", + "map_lon": "Longitud", + "map_use_ha": "Usar la ubicación de Home Assistant", + "map_opacity": "Visibilidad (%)", + "map_zoom": "Nivel de detalle", + "map_zoom_coarse": "grueso", + "map_zoom_fine": "fino", + "map_move": "Mover el mapa bajo el plano", + "map_step": "Paso", + "map_url": "Dirección de teselas propia (vacío = OpenStreetMap)", + "map_hint": "Tu navegador carga las teselas directamente del servidor de mapas (OpenStreetMap por defecto, respeta su política de uso); no se carga nada mientras el mapa está apagado. El plano se sitúa sobre el mapa según la brújula: gira la brújula o mueve el mapa hasta que la casa encaje.", + "compass_title": "Brújula", + "compass_n_short": "N", + "compass_s_short": "S", + "compass_swap": "Intercambiar norte ↔ sur", + "compass_swap_hint": "Gira la brújula 180°. El dibujo, los faldones y los campos solares se quedan como están.", + "compass_hint": "Si la brújula no coincide con la realidad, gírala aquí; no hay que redibujar nada. La luz del sol, el viento y la orientación de los faldones la siguen.", + "roof": "Tejado", + "roof_none": "Sin tejado", + "roof_flat": "Tejado plano", + "roof_gable": "Tejado a dos aguas", + "roof_custom": "Secciones de tejado (personalizado)", + "roof_sections": "Secciones de tejado", + "roof_sections_hint": "Cada sección de tejado cubre un rectángulo de la casa, p. ej. la casa, el granero o una ampliación, cada una con su forma, dirección de cumbrera, altura de alero e inclinación. Arrastra en el plano para dibujar una nueva; tocar la selecciona, arrastrar la mueve, las esquinas cambian su tamaño.", + "roof_sections_start": "Crear secciones de tejado a partir de las estancias", + "roof_sections_regen": "Crear de nuevo a partir de las estancias", + "roof_sections_off": "Volver a un solo tejado", + "roof_regen_confirm": "¿Sustituir todas las secciones de tejado por una nueva propuesta a partir de las estancias?", + "roof_section": "Sección de tejado", + "roof_section_hint": "Las alturas cuentan desde el suelo. Un lado con alero más bajo llega más abajo (catslide); los tejados a un agua suben desde el primer lado.", + "roof_shape_gable": "A dos aguas", + "roof_shape_hip": "A cuatro aguas", + "roof_shape_pent": "A un agua", + "roof_shape_flat": "Plano", + "roof_shape_halfhip": "Media cadera", + "roof_shape_pyramid": "Piramidal", + "roof_shape_mansard": "Mansarda", + "roof_shape_parapet": "Con antepecho", + "roof_shape": "Forma", + "roof_end_start": "Final al inicio de la cumbrera", + "roof_end_end": "Final al final de la cumbrera", + "roof_halfhip": "El faldón comienza a", + "roof_halfhip_hint": "A qué altura del hastial empieza el faldón, como parte de su altura: bajo = un faldón grande, alto = solo la punta.", + "roof_axis_x": "Cumbrera ↔", + "roof_axis_z": "Cumbrera ↕", + "roof_eave": "Alero (m)", + "roof_pitch_short": "Inclinación (°)", + "roof_height": "Altura (m)", + "roof_base": "Coronación de muros (m)", + "roof_rotation": "Giro (°)", + "roof_on_floor": "Sobre la planta", + "roof_on_floor_hint": "Coloca la sección sobre la coronación de los muros de esta planta; base y aleros se mueven con ella. En la vista 3D el tejado pertenece a esta planta.", + "roof_base_hint": "Por debajo de la altura del techo de la planta inferior, las paredes de esa planta terminan bajo el tejado: muretes en los aleros, hastiales hasta la cumbrera, paredes interiores cortadas por la pendiente. Las líneas discontinuas del plano muestran dónde quedan 1,5 m y 2 m de altura libre.", + "roof_ridge_height": "Altura de cumbrera", + "roof_side_top": "arriba", + "roof_side_bottom": "abajo", + "roof_side_left": "izquierda", + "roof_side_right": "derecha", + "roof_swap": "Intercambiar lados", + "roof_open": "Marquesina (postes en lugar de paredes, transparente)", + "roof_open_short": "Marquesina", + "roof_dormer": "Buhardilla", + "roof_dormer_hint": "Una buhardilla en este lado del tejado: 2 m de ancho, su frente en el muro del alero, aleros 1,4 m por encima del alero del tejado, tejado a dos aguas. Después muévela y cambia su ancho y alturas como cualquier sección; la pendiente principal se abre debajo y el muro del ático sube hasta la buhardilla; ahí cabe una ventana.", + "roof_outline": "Tomar el contorno de la planta", + "roof_outline_hint": "Un tejado plano de forma libre: toma el contorno de las estancias de la planta mostrada (también en L o Z) como una superficie sin juntas. Después se pueden arrastrar las esquinas.", + "roof_points_hint": "Forma libre: arrastra las esquinas en el plano, un + en un borde añade una esquina, × quita una. Volver al rectángulo descarta la forma.", + "roof_rect": "Volver al rectángulo", + "roof_open_hint": "Para un tejado de terraza o una cochera: postes y vigas sostienen el tejado en lugar de paredes, y es transparente. Donde la marquesina toca la pared de la casa, se apoya en ella.", + "roof_swap_hint": "Da la vuelta al tejado: los dos lados intercambian alero e inclinación, un tejado a un agua sube hacia el otro lado.", + "roof_pitch": "Inclinación del tejado (°)", + "roof_overhang": "Vuelo del tejado (m)", + "roof_overhang_sides": "Alero por lado", + "roof_overhang_a": "Alero A (m)", + "roof_overhang_b": "Alero B (m)", + "roof_overhang_u0": "Alero hastial inicio (m)", + "roof_overhang_u1": "Alero hastial final (m)", + "roof_overhang_auto": "Volver a automático", + "roof_overhang_sides_hint": "Sin valores propios el alero es automático: igual en todos los lados, salvo donde la parte del tejado toca la casa (ninguno).", + "roof_ridge": "Cumbrera", + "roof_ridge_long": "A lo largo del lado largo", + "roof_ridge_short": "A lo largo del lado corto (p. ej. casa adosada)", + "device": "Dispositivo", + "lamp_mount": "Lámpara", + "lamp_ceiling": "Lámpara de techo", + "lamp_floor": "Lámpara de pie", + "lamp_table": "Lámpara de mesa", + "lamp_wall": "Aplique de pared", + "marker_height": "Altura del marcador (m)", + "height_auto": "Altura automática", + "device_centre": "Al centro de la estancia", + "lights_spread": "Repartir las lámparas de techo de forma uniforme", + "devices_search": "Buscar dispositivos …", + "devices_more": "+{n} más", + "devices_less": "menos", + "panel_more": "Más dispositivos del área ({n})", + "panel_less": "Mostrar menos", + "gaps_close": "Cerrar huecos", + "gaps_hint": "Une estancias separadas hasta 60 cm en una pared compartida; el hueco pasa a ser el grosor de la pared interior.", + "gaps_none": "No se encontraron huecos entre estancias.", + "gaps_closed": "{n} lugares cerrados.", + "gaps_closed_wall": "{n} lugares cerrados, pared interior ahora {t} m.", + "fps": "FPS", + "fps_title": "Indicador de rendimiento (fotogramas por segundo)", + "hint_garage": "Toca una pared para añadir una puerta de garaje", + "opening_garage": "Puerta de garaje", + "garage_hint": "La puerta sigue a una cubierta de garaje (posición o abierta/cerrada) o a un contacto de puerta de garaje del área de la estancia.", + "door_hint": "Con un contacto de puerta la hoja se abre; sin sensor queda medio abierta.", + "hint_door": "Toca una pared para añadir una puerta", + "hint_window": "Toca una pared para añadir una ventana", + "opening_door": "Puerta", + "opening_window": "Ventana", + "opening_type": "Tipo", + "opening_position": "Centro desde la esquina (m)", + "sill": "Altura del alféizar (m)", + "opening_height": "Altura (m)", + "hinge": "Bisagra (vista desde la estancia)", + "hinge_left": "Izquierda", + "hinge_right": "Derecha", + "cover_entity": "Persiana", + "door_cover": "Motor (puerta o portón motorizado)", + "cover_position_entity": "Sensor de posición (en vivo)", + "cover_position_invert": "El sensor cuenta al revés (0 = abierto)", + "contact_entity": "Contacto", + "sensor_kind": "Tipo de sensor", + "sensor_kind_contact": "Contacto de ventana (abierta/cerrada)", + "sensor_kind_handle": "Sensor de manilla (abierta/oscilobatiente/cerrada)", + "sensor_kind_contact_tilt": "Contacto + sensor de inclinación", + "handle_entity": "Sensor de manilla", + "handle_main": "Sensor de manilla hoja principal", + "leaf_main": "Hoja principal", + "leaf_second": "Segunda hoja", + "tilt_entity": "Sensor de inclinación", + "tilt_angle_entity": "Sensor de ángulo de inclinación (°, opcional)", + "tilt_angle_max": "Ángulo que cuenta como totalmente inclinada (°)", + "tilt_angle_offset": "Desfase: ángulo indicado estando cerrada (°)", + "tilt_angle_invert": "El ángulo cuenta al revés", + "door_shut": "Mostrar cerrada sin sensor", + "door_shut_hint": "Una puerta sin contacto aparece medio abierta en 3D para que se lea como puerta. Marcado, se dibuja cerrada: puerta de entrada, cochera, puerta lateral.", + "door_angle": "Ángulo de apertura", + "door_angle_default": "Predeterminado", + "door_angle_hint": "Hasta dónde se abre la hoja. Con sensor se abre así en cuanto indica «abierta»; sin sensor queda abierta en ese ángulo (en lugar de a medias). Predeterminado no cambia nada.", + "entity_auto": "Automático ({name})", + "entity_auto_none": "Automático (no se encontró ninguno)", + "entity_none": "Ninguno", + "entity_search": "Escribe para buscar …", + "opening_hint": "Tipo de sensor: contacto de ventana (indica abierta/cerrada), sensor de manilla (indica abierta, oscilobatiente y cerrada, p. ej. una manilla Homematic) o contacto + sensor de inclinación (un segundo sensor que solo indica inclinada). Automático usa las persianas y contactos del área de la estancia. Sensor de posición: una entidad que indica la posición de la persiana mientras se mueve (p. ej. un \"level\" de Homematic, 0–100 % o 0–1, abierta = alto); la persiana se mueve entonces en vivo en 3D.", + "furniture": "Muebles", + "furniture_add": "Añadir mueble", + "studio_new": "Construir un mueble propio", + "studio_title": "Taller de muebles", + "studio_title_edit": "Taller de muebles: cambiar", + "studio_hint": "Elige una plantilla, ajusta medidas y frentes y coloca el mueble en el plano. Va al paquete «Muebles propios» y se puede cambiar aquí más tarde.", + "studio_kind": "Plantilla", + "studio_kind_cabinet": "Armario", + "studio_kind_shelf": "Estantería", + "studio_kind_lamp": "Lámpara", + "studio_kind_device": "Aparato", + "studio_name": "Nombre", + "studio_width": "Ancho (cm)", + "studio_depth": "Fondo (cm)", + "studio_height": "Alto (cm)", + "studio_doors": "Puertas", + "studio_drawers": "Cajones", + "studio_shelves": "Baldas", + "studio_handle": "Tiradores", + "studio_handle_bar": "Barra", + "studio_handle_knob": "Pomo", + "studio_handle_none": "Sin", + "studio_base": "Base", + "studio_base_plinth": "Zócalo", + "studio_base_legs": "Patas", + "studio_base_none": "Ninguna", + "studio_back": "Trasera", + "studio_lamp": "Tipo", + "studio_lamp_floor": "Lámpara de pie", + "studio_lamp_table": "Lámpara de mesa", + "studio_lamp_pendant": "Colgante", + "studio_lamp_wall": "Aplique", + "studio_display": "Pantalla delante (muestra el reproductor)", + "studio_mount": "Se coloca", + "studio_mount_floor": "En el suelo", + "studio_mount_surface": "Sobre un mueble", + "studio_mount_wall": "En la pared", + "studio_color_body": "Cuerpo", + "studio_color_lamp_body": "Pie y estructura", + "studio_color_front": "Frentes", + "studio_color_boards": "Baldas", + "studio_color_shade": "Pantalla", + "studio_color_display": "Marco de la pantalla", + "studio_color_white": "Blanco", + "studio_color_wood": "Madera", + "studio_color_metal": "Metal", + "studio_color_dark": "Oscuro", + "studio_color_glass": "Cristal", + "studio_color_accent": "Acento", + "studio_color_own": "Color propio", + "studio_color_plan": "Color del plano", + "studio_place": "Colocar en el plano", + "studio_save": "Guardar el cambio", + "studio_open": "Cambiar en el taller", + "studio_error": "No se pudo guardar: {detail}", + "studio_pack_name": "Muebles propios", + "studio_pack_publisher": "Taller de muebles", + "furniture_search": "Buscar muebles …", + "furniture_search_none": "No se encontró nada. Prueba otra palabra, en inglés o alemán.", + "furniture_type": "Elemento", + "rotation": "Rotación (°)", + "tilt_x": "Inclinación delante/detrás (°)", + "tilt_z": "Inclinación lateral (°)", + "strip_tilt": "Inclinación sobre su longitud (°)", + "strip_upright": "Vertical", + "strip_rise": "Inclinación a lo largo (°)", + "strip_upright_hint": "La tira queda de pie: su longitud sube desde la altura sobre el suelo, a lo largo de un marco de puerta, como columna de luz. La inclinación apoya una tira tumbada contra una pendiente (90° = su cara mira de lado).", + "rotate_left": "↺ 90°", + "rotate_right": "↻ 90°", + "height_m": "Altura (m)", + "furn_sofa": "Sofá", + "furn_armchair": "Sillón", + "furn_table": "Mesa", + "furn_chair": "Silla", + "furn_bed": "Cama", + "furn_nightstand": "Mesita de noche", + "furn_wardrobe": "Armario", + "furn_shelf": "Estantería", + "furn_kitchen": "Mueble de cocina", + "furn_worktop": "Encimera", + "furn_fridge": "Frigorífico", + "furn_fridge_smart": "Frigorífico inteligente (side by side)", + "furn_door_left": "Sensor de puerta izquierda (lado congelador)", + "furn_door_right": "Sensor de puerta derecha (lado frigorífico)", + "fridge_hint": "Mientras un sensor de puerta indica abierta, la puerta se abre en 3D.", + "furn_stove": "Cocina", + "furn_sink": "Fregadero", + "furn_bathtub": "Bañera", + "furn_shower": "Ducha", + "furn_wc": "Inodoro", + "furn_washbasin": "Lavabo", + "furn_desk": "Escritorio", + "furn_tv_board": "Mueble de TV", + "furn_plant": "Planta", + "furn_rug": "Alfombra", + "furn_stairs": "Escalera", + "furn_stairwell": "Abertura en el suelo", + "stairwell_hint": "Un hueco en esta planta, por ejemplo sobre la escalera o para una galería; desde arriba se ve a través. La abertura debe estar dentro de una estancia; varias aberturas pueden solaparse (para una forma en L, por ejemplo). Las escaleras de la planta inferior que llegan hasta aquí también abren el suelo por sí solas.", + "tool_hole": "Abertura en el suelo", + "tool_roof": "Tejado", + "tool_energy": "Energía", + "tool_wall": "Pared", + "hint_wall": "Arrastra para dibujar una pared suelta (tabique, media pared) · Mayús la mantiene recta · Alt sin ajuste", + "free_wall": "Pared", + "wall_length": "Longitud (m)", + "wall_thickness": "Grosor de pared (m)", + "wall_height": "Altura (m)", + "wall_height_full": "Altura completa de la estancia", + "wall_slope": "Inclinada", + "wall_slope_start": "Altura al inicio (m)", + "wall_slope_end": "Altura al final (m)", + "wall_slope_hint": "Pared inclinada: la parte superior va recta desde la altura al inicio de la pared (la esquina con el número menor) hasta la altura al final. Ambas pueden superar la altura de la planta, por ejemplo para una estancia adosada con ventanas altas.", + "wall_slope_off": "Volver a una pared recta", + "wall_none": "Sin pared", + "wall_none_hint": "Omitir esta pared por completo: para plantas abiertas cuyas estancias son un solo espacio pero están separadas en Home Assistant.", + "edge_thickness": "Grosor (m)", + "wall_thickness_hint": "Grosor de esta pared, p. ej. 0,365 en un muro exterior grueso o 0,115 en un tabique ligero. Una pared entre dos estancias toma el ajuste más grueso.", + "wall_thickness_reset": "Grosor según la casa", + "wall_heights": "Alturas de pared", + "wall_n": "Pared {a}–{b}", + "wall_view": "Vista de pared", + "wall_view_hint": "La pared de frente: arrastra sus puertas, ventanas y muebles o escribe su distancia.", + "wall_view_prev": "Pared anterior", + "wall_view_next": "Pared siguiente", + "wall_view_left": "Desde la izquierda (m)", + "wall_view_height": "Sobre el suelo (m)", + "wall_part": "parte {n}", + "wall_split_hint": "Dividir la pared aquí: la parte tiene su propia altura, p. ej. 2,5 m junto a 1,7 m en línea", + "wall_split_at": "Punto de división desde la esquina (m)", + "wall_join_hint": "Quitar el punto de división: la parte se une de nuevo a la anterior", + "wall_exterior_short": "muro exterior", + "room_wall_hint": "Una altura menor convierte la pared en un antepecho o una barra. Si dos estancias comparten la pared, se aplica el ajuste más bajo. Ventanas y puertas en ella terminan a la altura de la pared.", + "free_wall_hint": "Una pared suelta, p. ej. un tabique. Donde toca una pared de estancia, la esquina se inglete. Arrastra los tiradores para mover sus extremos, arrastra la línea para mover toda la pared.", + "free_wall_slope": "◢ Inclinada", + "free_wall_slope_hint": "La pared sube o baja de un extremo al otro: la altura de arriba es la del inicio, esta la del final.", + "free_wall_height_end": "Altura al final (m)", + "stairwell_outside": "Esta abertura atraviesa el límite de una estancia y por eso no se recorta. Muévela por completo a una estancia o hazla más pequeña.", + "hint_hole": "Arrastra para dibujar una abertura en el suelo (hueco de escalera, galería)", + "hint_roof": "Arrastra para dibujar una sección de tejado · tocar selecciona · arrastrar mueve · las esquinas cambian el tamaño", + "hint_energy": "Toca un campo solar para seleccionarlo · arrastra para moverlo, también a otro faldón · campos nuevos con + Campo solar a la derecha", + "furn_parking": "Plaza de aparcamiento", + "furn_group_vehicles": "Aparcamiento", + "parking_entity": "Sensor \"coche presente\"", + "parking_vehicle": "Vehículo", + "parking_vehicle_none": "Ninguno", + "parking_no_pack": "No se ha importado ningún pack de vehículos; los vehículos vienen del pack \"Vehículos\" (Extensiones → Packs de muebles).", + "parking_scale": "Tamaño (%)", + "parking_type_entity": "Sensor de tipo de vehículo (opcional)", + "parking_types": "Estado → vehículo", + "parking_type_state": "Estado (p. ej. van)", + "parking_add_type": "+ Asignación", + "parking_hint": "Sin sensor el vehículo está siempre ahí. Con uno aparece en cuanto el sensor indica \"on\", \"home\" o \"present\". Un sensor de tipo de vehículo (p. ej. de un análisis de cámara con IA) elige el modelo: cuando su estado coincide con una asignación, también como palabra en el texto, se muestra ese vehículo; si no, el predeterminado.", + "parking_too_tall": "El vehículo ({car} m) es más alto que la estancia ({room} m).", + "furn_lamp_ceiling": "Lámpara de techo", + "furn_lamp_downlight": "Foco empotrado", + "furn_lamp_spot": "Foco de superficie", + "furn_lamp_panel": "Panel LED", + "furn_lamp_uplight": "Foco de suelo", + "furn_lamp_bollard": "Baliza de camino", + "furn_lamp_garden": "Foco de jardín", + "furn_radiator": "Radiador", + "furn_robot_vacuum": "Robot aspirador", + "furn_entity_vacuum": "Robot aspirador", + "furn_entity_mower": "Robot cortacésped", + "pet_room_sensor": "Sensor de estancia de la mascota (opcional)", + "pet_room_hint": "Un sensor que nombra la estancia en la que está la mascota – Bermuda o ESPresense con una etiqueta en el collar: en 3D pasea por esa estancia.", + "furn_entity_water": "Válvula o interruptor", + "fridge_temp": "Temperatura del frigorífico", + "freezer_temp": "Temperatura del congelador", + "fridge_temp_hint": "El marcador muestra las temperaturas. Por encima de 8 °C en el frigorífico o −12 °C en el congelador se ilumina como aviso.", + "spray_reach": "Alcance del agua (m)", + "spray_hint": "Mientras la válvula esté abierta o el interruptor encendido, el aspersor lanza agua en arcos a su alrededor.", + "furn_robot_room": "Estancia actual (sensor)", + "robot_hint": "Mientras el robot limpia en Home Assistant, recorre carriles en 3D por la estancia que indica (un sensor de «estancia actual», comparado por nombre de estancia o área); si no, por la estancia de su base. El recorrido es simulado: Home Assistant normalmente no conoce la posición exacta. Vuelve a la base cuando regresa.", + "furn_lamp_pendant": "Lámpara colgante", + "furn_ceiling_fan": "Ventilador de techo", + "furn_fan_entity": "Ventilador", + "fan_hint": "La luz es el kit de luz del ventilador (déjala vacía si no tiene). El ventilador se encuentra en la estancia o se elige aquí: en 3D las aspas giran tan rápido como funciona, su icono lo conmuta, deslizar arriba/abajo cambia la velocidad y una pulsación larga abre el menú rápido. La altura es lo que cuelga del techo (más = una barra más larga).", + "room_ceiling": "Altura del techo", + "room_ceiling_tip": "Más bajo que la planta (un baño bajo la escalera) o más alto (un salón abierto hasta el tejado): las lámparas de techo, ventiladores, tiras LED y aparatos de techo cuelgan desde aquí, y las paredes de la habitación tienen esta altura.", + "room_ceiling_through": "El techo ({ceiling} m) está por encima de la altura de la planta ({floor} m): la habitación llega a la planta de arriba, sus paredes suben con ella y la planta de arriba queda abierta sobre ella. El editor de la planta superior muestra la zona rayada.", + "room_floor_offset": "Nivel del suelo (m)", + "room_floor_offset_hint": "Si el suelo de esta habitación está más bajo o más alto que la planta (una entrada hundida: −0,39), suelo, paredes, puertas, ventanas y lo que hay en ella se mueven; el techo se queda. Añade los peldaños como escalera.", + "room_inner": "Interior {w} × {d}", + "room_inner_hint": "Medido de pared a pared: las paredes interiores restan la mitad de su grosor, las exteriores quedan fuera del contorno.", + "floor_heating": "Suelo radiante (opcional)", + "floor_heating_hint": "Mientras el termostato calienta (o la válvula está abierta, el interruptor encendido), el suelo de la estancia brilla cálido en 3D.", + "room_announce_speaker": "Altavoz para anuncios", + "room_announce_quiet": "Hora de silencio para anuncios", + "room_announce_hint": "Sin elegir, habla el altavoz colocado en la habitación; si no, un asistente de voz, un Echo o un altavoz de su área (nunca un televisor). En la hora de silencio, los anuncios a varias habitaciones la omiten; uno solo para ella llega igualmente.", + "ceiling_here": "Techo aquí", + "ceiling_here_hint": "Altura del techo justo en este punto, p. ej. en un techo inclinado. Vacío = el techo de la estancia.", + "ceiling_slope": "A la pendiente del tejado", + "ceiling_slope_hint": "Aquí el techo está bajo la pendiente: la lámpara cuelga de su cara inferior, justo encima de su sitio.", + "furn_lamp_floor": "Lámpara de pie", + "furn_lamp_table": "Lámpara de mesa", + "furn_lamp_wall": "Aplique de pared", + "furn_led_strip": "Tira LED", + "furn_group_lights": "Luces", + "furn_entity_light": "Luz o interruptor", + "furn_color_entity": "Color y brillo de (opcional)", + "furn_color_entity_hint": "Para luces que un relé (Shelly, actuador) enciende y apaga mientras la bombilla conoce su color y brillo: el encendido viene del interruptor de arriba, color y brillo de esta entidad.", + "lamp_extra_light": "Bombilla {n} (opcional)", + "lamp_extra_hint": "Una lámpara con varias luces – principal, luz nocturna, anillo de ambiente: con la principal apagada brilla en 3D con la siguiente encendida, algo más tenue. Enciéndelas una a una en el panel de la estancia.", + "furn_entity_climate": "Calefacción (termostato)", + "lamp_hint": "Toca la lámpara en 3D para conmutarla, pulsación larga para el menú rápido. También funcionan interruptores (p. ej. un relé para la lámpara de techo): la lámpara brilla mientras está encendido. Las lámparas de mesa se apoyan sobre el mueble que tienen debajo.", + "lamp_hint_pendant": "Altura = caída bajo el techo. Toca en 3D para conmutar, pulsación larga para los detalles.", + "theme": "Aspecto", + "version_hint": "Versión instalada de NextFloor: el frontend; la integración en Home Assistant indica {backend}", + "accent": "Color de acento", + "accent_hint": "Un color de acento propio: líneas y bordes brillantes en el aspecto neón, botones y marcadores; ↺ recupera el cian neón", + "accent_reset": "Volver al cian", + "theme_neon": "Neón", + "theme_blueprint": "Plano azul", + "theme_day": "Día", + "theme_auto": "Auto", + "clock": "Reloj", + "clock_none": "Ninguno", + "clock_top_left": "Arriba a la izquierda", + "clock_top_right": "Arriba a la derecha", + "clock_bottom_left": "Abajo a la izquierda", + "clock_bottom_right": "Abajo a la derecha", + "glass_walls": "Paredes de cristal", + "glass_walls_hint": "Opacidad de las paredes a través de las que se ven las habitaciones: a la izquierda casi invisibles, a la derecha opacas. Para esta pantalla.", + "screen_name": "Nombre de esta pantalla", + "screen_name_hint": "Los anuncios aparecen en cada pantalla de NextFloor abierta. Con un nombre (p. ej. «Pasillo»), un anuncio puede ir solo a esta pantalla. Sin marcar, esta pantalla queda en silencio.", + "announce_on": "Anuncios activados en esta pantalla", + "announce_muted": "Anuncios silenciados en esta pantalla", + "lock3d_on": "Bloquear 3D (sin girar, hacer zoom ni desplazar; los toques siguen funcionando)", + "lock3d_off": "Desbloquear 3D", + "walk": "Recorrer la casa", + "travel": "Viaje en el tiempo: reproducir las últimas 24 horas o 7 días", + "travel_play": "Reproducir", + "travel_pause": "Pausa", + "travel_loading": "Cargando historial …", + "travel_failed": "No se pudo cargar el historial.", + "travel_speed": "Velocidad", + "travel_speed_min": "1 min/s", + "travel_speed_10min": "10 min/s", + "travel_speed_hour": "1 h/s", + "travel_days": "días", + "travel_live": "En vivo", + "card_travel_button": "Botón de viaje en el tiempo", + "walk_stop": "Dejar de caminar", + "walk_hint": "Arrastrar: mirar alrededor · W A S D / flechas o joystick: caminar · rueda: paso", + "card_walk_button": "Botón para recorrer", + "card_lock_button": "Botón del bloqueo 3D", + "backdrop": "Fondo propio", + "backdrop_color": "Color", + "backdrop_image": "Imagen (/local/… o https://…)", + "backdrop_dim": "Atenuar", + "backdrop_hint": "En lugar del cielo del aspecto, la casa se sitúa ante un color o una imagen propia. Una imagen en /config/www está disponible en /local/….", + "furnish": "Amueblar", + "split_3d": "3D al lado", + "plan_dims": "Medidas", + "plan_dims_hint": "Escribe su longitud en cada borde de habitación.", + "mount_height": "Altura sobre el suelo (m)", + "side_open": "Abrir la barra lateral", + "side_close": "Cerrar", + "side_details": "Detalles de la selección", + "side_pin": "Fijar", + "side_pinned": "Fijada", + "side_pin_hint": "Fijada, la barra lateral queda abierta; si no, se pliega junto a la vista 3D mientras no hay nada seleccionado", + "split_3d_hint": "3D en vivo junto al plano: arrastra y gira muebles y dispositivos ahí, con deshacer, guardado con el plano", + "size_w": "Ancho (m)", + "size_d": "Fondo (m)", + "size_h": "Altura (m)", + "furnish_hint": "Arrastra muebles, lámparas y dispositivos · los muebles se ajustan a las paredes · toca uno para girarlo, fijar su altura y montaje", + "done": "Hecho", + "heatmap": "Mapa de calor", + "heat_off": "Normal", + "heat_short_temperature": "Temp.", + "heat_short_humidity": "Humedad", + "heat_short_co2": "CO₂", + "heat_short_mould": "Moho", + "heat_short_power": "Consumo", + "heat_short_comfort": "Confort", + "heat_short_sun": "Sol", + "heat_short_wifi": "Wi-Fi", + "heat_short_values": "Valores", + "heat_temperature": "Temperatura", + "heat_humidity": "Humedad", + "heat_co2": "CO₂", + "heat_mould": "Moho", + "heat_power": "Consumo eléctrico", + "heat_comfort": "Índice de confort", + "heat_sun": "Sol hoy", + "room_sun_hours": "{h} h de sol hoy ({facing})", + "open_since": "abierto desde hace {time}", + "presence_now": "hay alguien", + "presence_last": "visto hace {time}", + "comfort_n": "Confort {n}", + "empty_lights_hint": "{n} luces encendidas, nadie desde hace {min} min.", + "empty_lights_off": "Apagar luces", + "open_heating_hint": "{n} ventanas abiertas con la calefacción en marcha.", + "open_heating_off": "Apagar calefacción", + "room_clean": "Limpieza (script o botón)", + "room_clean_hint": "Un script o botón que envía el robot aspirador a esta habitación (p. ej. la limpieza por habitaciones de tu integración). El panel de la habitación mostrará «🧹 Limpiar».", + "room_clean_run": "Limpiar", + "room_clean_run_hint": "Envía el robot aspirador a esta habitación.", + "shade_hint": "Sol en {n} ventanas a {temp}: ¿bajar las persianas?", + "shade_close": "Bajar", + "room_sun_year": "Sol a lo largo del año", + "room_sun_year_hint": "Las horas de sol por las ventanas exteriores de la habitación el día 15 de cada mes.", + "room_energy": "hoy {today} · mes {month}", + "room_energy_hint": "De las estadísticas de los sensores de potencia de los dispositivos de la habitación; el coste del mes con la tarifa de la casa.", + "heat_summer": "verano", + "heat_winter": "invierno", + "air_co2": "ventilar (CO₂)", + "air_humidity": "ventilar (húmedo)", + "air_mould": "riesgo de moho – ventilar", + "room_curve_hint": "La temperatura de la estancia en las últimas 24 horas", + "heat_values": "Valores junto a los nombres de las estancias", + "heat_wifi": "Wi-Fi", + "wifi_aps": "{n} puntos de acceso · {clients} dispositivos", + "wifi_network": "Red: {online} en línea · {offline} sin conexión", + "wifi_none": "Coloca puntos de acceso o routers de los packs (Hogar inteligente 2) y vincúlalos a una entidad de su dispositivo.", + "wifi_clients": "{n} dispositivos", + "heat_none_found": "No hay sensores adecuados en las áreas de las estancias.", + "markers": "Marcadores", + "markers_none": "Ninguno", + "markers_important": "Importantes", + "markers_all": "Todos", + "furn_stool": "Taburete", + "furn_coffee_table": "Mesa de centro", + "furn_tv_wall": "TV (pared)", + "furn_sideboard": "Aparador", + "furn_table_round": "Mesa redonda", + "furn_bench": "Banco", + "furn_corner_bench": "Banco de esquina", + "furn_bar_stool": "Taburete de bar", + "furn_kitchen_wall": "Mueble alto de pared", + "furn_kitchen_tall": "Columna con horno", + "furn_island": "Isla de cocina", + "furn_dishwasher": "Lavavajillas", + "furn_bunk_bed": "Litera", + "furn_dresser": "Cómoda", + "furn_washer": "Lavadora", + "furn_dryer": "Secadora", + "furn_office_chair": "Silla de oficina", + "furn_tall_cabinet": "Armario alto", + "furn_coat_rack": "Perchero", + "furn_group_living": "Vivir", + "furn_group_dining": "Comer", + "furn_group_energy": "Energía y solar", + "energy_devices": "Dispositivos", + "wallbox_charging": "cargando", + "wallbox_plugged": "enchufado", + "furn_soc": "Estado de carga (%)", + "furn_export": "Potencia de exportación (W, sensor aparte, opcional)", + "furn_export_hint": "Si tu contador indica importación y exportación en dos sensores (p. ej. Growatt, Tibber Pulse), usa el de importación como potencia arriba y el de exportación aquí. Un sensor con signo no lo necesita.", + "meter_parent": "Cuelga del contador", + "meter_parent_none": "ninguno (contador principal)", + "meter_main": "Contador principal", + "meter_unmetered": "{w} sin medir", + "meter_device_hint": "Si el dispositivo está detrás de un subcontador (p. ej. una placa de balcón en un piso), su potencia cuenta para ese piso. Para ello el subcontador debe medir en ambos sentidos (− = inyección); si solo cuenta la importación, el consumo del piso sale demasiado alto mientras hay excedente.", + "meter_sub_power": "Potencia del ramal (W, + = consumida, − = inyectada)", + "meter_floors": "Alimenta las plantas", + "meter_sub_hint": "Un subcontador mide su ramal, p. ej. un piso. Los dispositivos de las plantas marcadas cuelgan de él en 3D en lugar del contador principal; lo que el contador principal cuenta de más aparece como «Común (resto)» en el balance.", + "furn_charge": "Potencia de carga (W, sensor aparte, opcional)", + "furn_charge_hint": "Si tu batería indica carga y descarga en dos sensores (p. ej. Anker Solix), usa el de descarga como potencia arriba y el de carga aquí. Un sensor con signo no lo necesita.", + "furn_wallbox_status": "Estado (cargando, enchufado)", + "energy_only_note": "⚡ Energía: aquí solo se pueden mover campos solares y dispositivos de energía; estancias y muebles están bloqueados.", + "roof_only_note": "🏠 Tejado: aquí solo se pueden mover secciones y ventanas de tejado; estancias y muebles están bloqueados.", + "energy_devices_hint": "Contador, inversores, baterías domésticas, wallboxes y la conexión a la red se añaden aquí: en la planta elegida arriba, movibles en el plano. Con un sensor de potencia muestran sus vatios; el contador toma el sensor de red, un string elige su inversor. También funcionan varios inversores y baterías (por ejemplo una placa de balcón además): cada uno con su propio sensor.", + "energy_routes": "Recorridos de cable", + "energy_routes_hint": "Por dónde va realmente un cable: el flujo sigue tus puntos en lugar de un arco a través de la casa. Sin recorrido se queda el arco. Los consumidores mantienen su arco.", + "route_conn_solar": "{name} → inversor", + "route_conn_battery": "Batería ↔ casa", + "route_conn_inverter": "Inversor → casa", + "route_conn_grid": "Red ↔ casa", + "route_conn_meter": "{name} ↔ contador superior", + "route_conn_device": "{name} ↔ subcontador", + "route_points": "{n} puntos", + "route_none": "arco directo", + "route_draw": "Dibujar recorrido", + "route_redraw": "Volver a dibujar", + "route_drawing": "Toca en el plano los puntos por los que pasa el cable, de un extremo al otro; cambia de planta donde atraviesa un techo. {n} puntos.", + "route_undo": "Último punto", + "route_done": "Listo", + "route_cable": "Mostrar como cable", + "route_cable_hint": "Dibuja el recorrido como un cable visible, no solo como la línea fina bajo las partículas.", + "solar_fields": "Campos solares", + "solar_hint": "Pon módulos en el tejado: se apoyan en la pendiente del faldón; en un tejado plano se colocan sobre soportes. Arrastra un campo en el plano para moverlo.", + "solar_no_roof": "Los campos solares necesitan un tejado: a dos aguas o plano en Ajustes, o secciones de tejado aquí en la herramienta Tejado.", + "solar_face_gone": "falta el faldón", + "solar_summary": "{n} módulos · {kwp} kWp", + "solar_add": "Campo solar", + "solar_field": "Campo solar", + "solar_face": "Faldón", + "solar_rows": "Filas", + "solar_cols": "Módulos por fila", + "solar_portrait": "Vertical", + "solar_landscape": "Horizontal", + "solar_u": "Distancia al borde (m)", + "solar_v": "Distancia al alero (m)", + "solar_tilt": "Inclinación de los soportes (°)", + "solar_rack_ew": "Estructura este-oeste", + "solar_rack_ew_hint": "Cada segunda fila mira al otro lado, las parejas espalda con espalda – bajo y compacto, como en muchas cubiertas planas.", + "solar_rack_tilt": "Soporte (° de inclinación extra)", + "solar_flip": "Inclinar hacia el otro lado", + "solar_partial": "solo caben {n} de {total} en el faldón", + "solar_form_hint": "Los módulos que sobresaldrían del faldón se omiten. «Llenar faldón» pone tantos módulos como quepan. kWp calculados con 400 W por módulo.", + "solar_fit": "Llenar faldón", + "roof_windows": "Ventanas de tejado", + "roof_window": "Ventana de tejado", + "roof_windows_hint": "Las ventanas de tejado se apoyan en el faldón, con persiana y contactos como las ventanas. Arrástralas en el plano, también a otro faldón.", + "roof_window_tilt": "Contacto de inclinación", + "roof_window_name": "Nombre (opcional)", + "roof_window_motor": "Motor de ventana (cubierta, opcional)", + "roof_window_motor_hint": "Un motor de ventana (Velux, Roto, Fakro) indica su posición como cubierta: la hoja se abre en 3D tanto como esté el motor. Un contacto o contacto de inclinación funciona también sin motor.", + "roof_window_hint": "Abierta, la hoja gira hacia fuera con bisagra arriba; inclinada, un poco; y el marco brilla cálido; la persiana baja sobre el cristal desde arriba. En una sección de tejado la ventana corta un hueco en la pendiente, para que el ático mire a través.", + "solar_ground": "Independiente (jardín, tejado del garaje …)", + "solar_add_ground": "Independiente", + "solar_base": "Altura de la superficie (m, 0 = suelo)", + "solar_add_wall": "En una pared", + "solar_wall": "Pared", + "solar_v_wall": "Altura sobre el suelo (m)", + "solar_tilt_wall": "Inclinación respecto a la pared (°, 90 = marquesina)", + "solar_flip_wall": "Separado abajo en lugar de arriba", + "solar_rotation": "Rotación (°)", + "solar_name": "Nombre", + "solar_name_hint": "p. ej. string 1 sur", + "solar_module_w": "Ancho del módulo (m)", + "solar_module_h": "Alto del módulo (m)", + "solar_wp": "Potencia del módulo (Wp)", + "solar_string": "String", + "solar_strings": "Strings", + "solar_string_none": "Sin string", + "solar_string_new": "Nuevo string", + "solar_string_n": "String {n}", + "solar_string_name": "Nombre del string", + "solar_string_entity": "Potencia FV del string", + "solar_string_inverter": "Inversor", + "solar_string_inverter_none": "Ningún inversor elegido", + "inverter_strings": "Strings en este inversor: {names}", + "inverter_strings_none": "Aún no hay string en este inversor; asígnalo en un campo solar en String › Inversor.", + "solar_string_inverter_missing": "Aún no hay inversor en el plano (añade uno abajo en Dispositivos)", + "solar_string_hint": "Los campos del mismo string van juntos, también en tejados distintos (p. ej. 5 módulos en la casa y 5 en el garaje). Sensor e inversor cuentan para todo el string.", + "solar_string_sum": "{fields} campos · {n} módulos · {kwp} kWp", + "solar_face_size": "Faldón {w} × {h} m (a lo largo del alero × subiendo la pendiente)", + "solar_cols_hint": "Un número para filas de igual longitud, o una lista para filas propias: «4, 4, 3» (desde el alero).", + "solar_align_left": "Izquierda", + "solar_align_center": "Centro", + "solar_align_right": "Derecha", + "solar_look_black": "Full black", + "solar_look_blue": "Azul", + "solar_pick": "Módulos activar/desactivar uno a uno", + "solar_pick_all": "Todos activos de nuevo", + "solar_pick_hint": "Toca un módulo en el plano para quitarlo o volver a ponerlo. Los quitados aparecen discontinuos.", + "solar_entity": "Potencia FV de este campo (p. ej. su string)", + "solar_main": "Tejado principal", + "solar_section": "Sección {n}", + "solar_flat": "tejado plano", + "compass_n": "norte", + "compass_ne": "noreste", + "compass_e": "este", + "compass_se": "sureste", + "compass_s": "sur", + "compass_sw": "suroeste", + "compass_w": "oeste", + "compass_nw": "noroeste", + "furn_meter": "Contador eléctrico", + "furn_grid_point": "Conexión a la red", + "grid_point_hint": "La conexión a la red está aquí: el punto de entrega a la compañía, p. ej. al final del acceso. Movible en el plano.", + "furn_model": "Modelo", + "inverter_std": "Estándar (unidad de pared con pantalla)", + "inverter_slim": "Estrecho y alto (franja de luz)", + "inverter_hybrid": "Híbrido (dial redondo, ventiladores)", + "battery_std": "Torre (módulos apilados)", + "battery_wall": "Batería de pared (plana, colgada)", + "battery_cube": "Compacta (batería de balcón)", + "furn_inverter": "Inversor solar", + "furn_home_battery": "Batería doméstica", + "furn_wallbox": "Wallbox", + "furn_group_kitchen": "Cocina", + "furn_group_sleeping": "Dormir", + "furn_group_bath": "Baño y lavandería", + "furn_group_work": "Trabajo y otros", + "furn_entity": "Dispositivo (interruptor, enchufe …)", + "furn_state_entity": "Estado de (opcional)", + "furn_state_entity2": "Segundo estado (la otra mitad)", + "furn_state_split": "Mitades", + "furn_state_left_right": "Izquierda / derecha", + "furn_state_top_bottom": "Abajo / arriba (litera)", + "furn_state_hint": "El elemento brilla mientras la entidad indica encendido, ocupado o en casa: una cama con alfombra de ocupación, un sillón, la sauna. Dos entidades iluminan las mitades: izquierda y derecha, abajo y arriba en una litera.", + "furn_entity_tv": "TV (reproductor multimedia o enchufe inteligente)", + "fix": "Fijar", + "unfix": "Soltar", + "fix_hint": "Fijado: ya no se puede mover por accidente (tecla L, clic derecho o pulsación larga)", + "fixed_drag_hint": "🔒 Fijado: suéltalo primero para moverlo (candado en el formulario, clic derecho o tecla L)", + "fixed_delete_confirm": "Este elemento está fijado. ¿Eliminarlo de todos modos?", + "lock_plan": "🔒 Plano", + "lock_plan_hint": "Bloquear el plano: estancias, paredes, puertas, ventanas y zonas exteriores no se pueden mover por accidente. Muebles y dispositivos quedan libres.", + "start_view": "Vista de inicio", + "start_view_hint": "La vista 3D, la tarjeta y el kiosco abren la casa con esta vista, p. ej. desde el lado del jardín. Gira, acerca y mueve la casa en el panel 3D de la derecha hasta que encaje y luego recuérdala.", + "start_view_card": "Si una tarjeta debe abrirse con otra vista, pon esta línea en su configuración YAML.", + "start_view_set": "Recordar la vista 3D actual como inicio", + "start_view_reset": "Predeterminada", + "start_view_saved": "Hay guardada una vista de inicio propia.", + "ctx_rotate": "Girar 90°", + "devices_placed_in": "en {room}", + "devices_narrow": "{n} más: afina la búsqueda", + "climate": "Clima de la estancia", + "climate_temperature": "Temperatura", + "climate_humidity": "Humedad", + "climate_co2": "CO₂", + "climate_hint": "Estos sensores cuentan para el mapa de calor y el panel de la estancia. «Automático» toma los sensores del área y los colocados en la estancia, pero no las temperaturas de dispositivos (impresora 3D, bomba de calor, impulsión …).", + "climate_more": "… y otro sensor (promedio)", + "plan_locked": "Plano bloqueado", + "plan_lock": "Bloquear el plano", + "plan_unlock": "Desbloquear el plano", + "opening_mark": "Resaltar en 3D", + "opening_mark_open": "Cuando está abierta", + "opening_mark_closed": "Cuando está cerrada (p. ej. WC)", + "opening_mark_hint": "Una ventana o puerta resaltada brilla cálida. «Cuando está cerrada» necesita un contacto; sin sensor no se resalta nada.", + "window_opens": "Se abre", + "window_opens_turn": "Oscilobatiente (hacia dentro)", + "window_opens_slide": "Corredera (ventana corredera, puerta elevable)", + "window_opens_top": "Abatible (la parte baja sale hacia fuera)", + "window_opens_hint": "Corredera: la hoja del lado de la bisagra se desliza delante de la fija; con dos hojas, las dos centrales se deslizan hacia los lados. Las abatibles se abren con su contacto o un sensor de inclinación.", + "marker_show": "Marcador en 3D", + "marker_show_hint": "Automático sigue el interruptor Ninguno / Importantes / Todos de la vista 3D. Mostrar siempre y Ocultar se aplican igualmente (salvo con Ninguno).", + "pin_shift": "Mover el marcador", + "pin_shift_up": "↑ altura", + "pin_shift_hint": "Si los dispositivos están muy juntos, desplaza aquí el marcador un poco a un lado o hacia arriba (en metros); el dispositivo se queda donde está.", + "marker_show_auto": "Automático", + "marker_show_always": "Mostrar siempre", + "marker_show_no_power": "Sin vatios", + "marker_show_active": "Solo mientras esté activo", + "marker_show_never": "Ocultar", + "marker_icon": "Símbolo propio (icono Material Design)", + "device_name": "Nombre propio (opcional)", + "show_name": "Mostrar el nombre bajo el marcador en 3D", + "card_marker_names": "Nombres propios en los marcadores", + "card_marker_names_hint": "Cada dispositivo con nombre propio lo muestra pequeño bajo su marcador: tres termómetros en el jardín se distinguen.", + "device_name_hint": "Un nombre solo para el plano y el panel de la habitación, p. ej. \"Luz de acento de la isla\"; la entidad en Home Assistant no cambia.", + "device_simple": "Solo interruptor en el panel de la habitación", + "device_simple_hint": "El panel de la habitación muestra solo el interruptor de esta lámpara, sin brillo, temperatura de color ni colores.", + "floor_turn": "Girar 90°", + "floor_shift_all": "Llevar todas las plantas (toda la casa)", + "floor_shift_all_hint": "Desplazar y girar actúan sobre todas las plantas con las secciones de tejado, zonas exteriores, dispositivos de energía y contador: toda la casa se mueve como una.", + "floor_turn_hint": "Gira todo lo de la planta 90° en sentido horario alrededor del centro de sus estancias, cuando una planta se dibujó al revés. Tres veces = 270°.", + "marker_icon_hint": "El nombre de un icono Material Design como en Home Assistant, p. ej. mdi:thermometer o mdi:water-alert. Vacío = el símbolo del tipo de dispositivo.", + "furn_power": "Sensor de potencia (W)", + "furn_links_hint": "Con un sensor de potencia el elemento muestra sus vatios y participa en el flujo de energía.", + "furn_links_hint_tv": "La pantalla brilla mientras el TV está encendido, con el color de la app (Netflix, YouTube …); la etiqueta muestra la app o el título.", + "stairs_hint": "La escalera sube hacia atrás (alejándose del borde frontal marcado) y abre el techo de la planta superior.", + "floor_lights": "{n} luces encendidas", + "floor_open": "{n} abiertas", + "floor_persons": "{n} personas", + "energy_consumption": "Consumo", + "energy_grid_import": "Importación de red", + "energy_grid_export": "Exportación", + "energy_solar": "Solar", + "energy_battery": "Batería", + "energy_tariff": "Tarifa", + "energy": "Energía", + "energy_meter": "Contador", + "energy_grid": "Red (W, + = importación)", + "energy_solar_sensor": "Producción solar (W)", + "energy_battery_sensor": "Potencia de batería (W, + = descarga)", + "energy_battery_soc": "Carga de batería (%)", + "energy_tariff_sensor": "Tarifa (p. ej. €/kWh)", + "energy_gas": "Contador de gas (opcional)", + "energy_water": "Contador de agua (opcional)", + "energy_meters_hint": "El gas y el agua aparecen con el balance de la casa – en la barra de energía y en la tarjeta de la casa: un sensor con el caudal actual (m³/h, l/min) o la lectura de hoy.", + "energy_gas_short": "Gas", + "energy_water_short": "Agua", + "energy_invert": "Invertir signo", + "energy_hint": "Los consumidores son dispositivos colocados con un sensor de potencia (W): el propio sensor o uno del mismo dispositivo.", + "energy_balance": "Balance energético", + "energy_balance_hint": "Red, solar y batería vienen de los dispositivos del plano: contador, inversor y batería doméstica. Aquí puedes elegir otros sensores, invertir signos y fijar el consumo de la casa.", + "energy_rest": "Común (resto)", + "energy_advanced": "Modo de energía avanzado", + "energy_advanced_on": "Usar subcontadores", + "energy_show_unmetered": "Mostrar el consumo sin medir en los subcontadores", + "energy_show_unmetered_hint": "La etiqueta de un subcontador muestra entonces lo que consumen sus plantas y cuánto de ello no mide ningún dispositivo colocado, p. ej. «500 W · 450 W sin medir». Si no, muestra la lectura del contador.", + "energy_advanced_hint": "Para subcontadores, p. ej. uno por piso detrás de un contador principal: un contador puede colgar de otro y alimentar sus propias plantas. Desactivado = el primer contador es la conexión a la red, los demás son consumidores.", + "energy_consumption_sensor": "Consumo de la casa (W, si no, del balance)", + "energy_import_prefs": "Tomar del panel de energía", + "energy_import_done": "{n} sensores tomados; comprueba los signos.", + "energy_import_none": "No se encontraron sensores de potencia (W) adecuados en el panel de energía; elígelos a mano.", + "energy_import_failed": "El panel de energía de Home Assistant no está configurado.", + "tool_meter": "Contador", + "hint_meter": "Toca el lugar del contador", + "presence": "Presencia", + "presence_hint": "Sensor de estancia por persona (p. ej. ESPresense, Bermuda): su estado nombra la estancia o el área.", + "presence_sensor": "Sensor de estancia", + "no_persons": "No hay personas en Home Assistant.", + "packname:nextfloor.a_bad": "Baño", + "pack:nextfloor.a_bad:vanity_60": "Mueble de lavabo 60 con armario bajo", + "pack:nextfloor.a_bad:vanity_80": "Mueble de lavabo 80 con armario bajo", + "pack:nextfloor.a_bad:vanity_100": "Mueble de lavabo 100 con armario bajo", + "pack:nextfloor.a_bad:vanity_double_120": "Doble lavabo 120", + "pack:nextfloor.a_bad:vanity_double_160": "Doble lavabo", + "pack:nextfloor.a_bad:pedestal_basin": "Lavabo de pedestal", + "pack:nextfloor.a_bad:bathtub_builtin": "Bañera empotrada", + "pack:nextfloor.a_bad:bathtub_corner": "Bañera de esquina", + "pack:nextfloor.a_bad:bathtub_corner_compact": "Bañera de esquina compacta", + "pack:nextfloor.a_bad:bathtub_free": "Bañera exenta", + "pack:nextfloor.a_bad:whirlpool_indoor": "Hidromasaje interior", + "pack:nextfloor.a_bad:shower_corner_90": "Ducha de esquina 90 × 90", + "pack:nextfloor.a_bad:shower_niche_120": "Ducha en nicho 120 × 90", + "pack:nextfloor.a_bad:shower_walkin_140": "Ducha a ras de suelo 140 × 90", + "pack:nextfloor.a_bad:shower_walkin_120": "Ducha a ras de suelo", + "pack:nextfloor.a_bad:shower_rain_led": "Ducha de lluvia con LED", + "pack:nextfloor.a_bad:toilet_close": "Inodoro de tanque bajo", + "pack:nextfloor.a_bad:toilet_hung": "Inodoro suspendido", + "pack:nextfloor.a_bad:toilet_hung_compact": "Inodoro suspendido (compacto)", + "pack:nextfloor.a_bad:bidet": "Bidé", + "pack:nextfloor.a_bad:cabinet_tall": "Armario alto de baño", + "pack:nextfloor.a_bad:cabinet_mid": "Armario de baño de media altura", + "pack:nextfloor.a_bad:mirror_round_light": "Espejo redondo con luz", + "pack:nextfloor.a_bad:mirror_80": "Espejo 80 × 60 con luz", + "pack:nextfloor.a_bad:mirror_led_100": "Espejo LED 100 × 70 con reloj", + "pack:nextfloor.a_bad:mirror_cabinet": "Armario con espejo y luz", + "pack:nextfloor.a_bad:wall_shelf_bath": "Estante de pared de baño", + "pack:nextfloor.a_bad:towel_rail": "Toallero con toalla", + "pack:nextfloor.a_bad:towel_radiator": "Radiador toallero", + "pack:nextfloor.a_bad:towel_heater_electric": "Toallero eléctrico", + "pack:nextfloor.a_bad:sauna": "Sauna", + "pack:nextfloor.a_bad:bath_fan": "Extractor de baño", + "pack:nextfloor.a_bad:washer_cabinet": "Armario para lavadora", + "pack:nextfloor.a_bad:washer_under_vanity": "Lavadora bajo el lavabo", + "pack:nextfloor.a_bad:laundry_basket": "Cesto de la ropa", + "pack:nextfloor.a_bad:laundry_cabinet": "Armario de lavandería con cesto", + "pack:nextfloor.a_bad:ladder_shelf": "Estantería escalera con toallas", + "pack:nextfloor.a_bad:plant_stool": "Planta sobre taburete", + "packname:nextfloor.a_buero": "Oficina y gaming", + "pack:nextfloor.a_buero:desk_standing": "Escritorio elevable", + "pack:nextfloor.a_buero:desk_standing_bare": "Escritorio elevable sin monitor", + "pack:nextfloor.a_buero:chair_gaming": "Silla gaming", + "pack:nextfloor.a_buero:chair_office": "Silla de oficina ergonómica", + "pack:nextfloor.a_buero:sim_cockpit": "Cockpit de sim racing", + "pack:nextfloor.a_buero:server_rack_42u": "Rack de servidores (42U)", + "pack:nextfloor.a_buero:filing_cabinet": "Archivador", + "pack:nextfloor.a_buero:whiteboard": "Pizarra blanca", + "pack:nextfloor.a_buero:triple_monitor": "Configuración de tres monitores", + "pack:nextfloor.a_buero:bookcase_wall": "Pared de librerías", + "pack:nextfloor.a_buero:desk_lamp": "Lámpara de escritorio", + "pack:nextfloor.a_buero:desk_lamp_led": "Lámpara de escritorio LED", + "pack:nextfloor.a_buero:arcade_cabinet": "Máquina arcade", + "pack:nextfloor.a_buero:office_lounge_sofa": "Sofá lounge de oficina", + "pack:nextfloor.a_buero:monitor_light_bar": "Monitor con barra de luz", + "pack:nextfloor.a_buero:printer_laser": "Impresora láser", + "pack:nextfloor.a_buero:wifi_router": "Router Wi-Fi", + "pack:nextfloor.a_buero:phone_booth": "Cabina telefónica", + "pack:nextfloor.a_buero:printer_3d": "Impresora 3D", + "pack:nextfloor.a_buero:printer_cube": "Impresora 3D cerrada tipo cubo", + "pack:nextfloor.a_buero:printer_multi": "Impresora 3D cubo con unidad multicolor", + "pack:nextfloor.a_buero:printer_large": "Impresora 3D grande de doble boquilla", + "pack:nextfloor.a_buero:printer_open": "Impresora 3D abierta compacta", + "pack:nextfloor.a_buero:printer_resin": "Impresora 3D de resina", + "pack:nextfloor.a_buero:filament_dryer": "Secador de filamento", + "pack:nextfloor.a_buero:filament_rack": "Soporte de pared para filamento", + "packname:nextfloor.a_fitness": "Fitness", + "pack:nextfloor.a_fitness:treadmill": "Cinta de correr", + "pack:nextfloor.a_fitness:power_rack": "Rack de potencia con banco", + "pack:nextfloor.a_fitness:rowing_machine": "Máquina de remo", + "pack:nextfloor.a_fitness:spin_bike": "Bicicleta de spinning", + "pack:nextfloor.a_fitness:dumbbell_rack": "Soporte de mancuernas", + "pack:nextfloor.a_fitness:punching_bag": "Saco de boxeo", + "pack:nextfloor.a_fitness:yoga_mat": "Esterilla de yoga con bloque", + "pack:nextfloor.a_fitness:elliptical": "Elíptica", + "pack:nextfloor.a_fitness:mirror_wall_gym": "Pared de espejos", + "pack:nextfloor.a_fitness:exercise_ball": "Pelota de ejercicio", + "pack:nextfloor.a_fitness:wall_bars": "Espalderas", + "pack:nextfloor.a_fitness:fitness_mirror_smart": "Espejo de fitness inteligente", + "pack:nextfloor.a_fitness:bike_trainer": "Bicicleta en rodillo inteligente", + "pack:nextfloor.a_fitness:sauna_cabin": "Cabina de sauna", + "pack:nextfloor.a_fitness:massage_chair": "Sillón de masaje", + "pack:nextfloor.a_fitness:kettlebells": "Juego de kettlebells", + "pack:nextfloor.a_fitness:water_cooler": "Fuente de agua", + "packname:nextfloor.a_garten": "Jardín y terraza", + "pack:nextfloor.a_garten:grill_gas": "Barbacoa de gas", + "pack:nextfloor.a_garten:lounge_set": "Conjunto lounge", + "pack:nextfloor.a_garten:sun_lounger_adj": "Tumbona", + "pack:nextfloor.a_garten:parasol": "Sombrilla", + "pack:nextfloor.a_garten:pergola": "Pérgola", + "pack:nextfloor.a_garten:raised_bed": "Bancal elevado", + "pack:nextfloor.a_garten:greenhouse": "Invernadero", + "pack:nextfloor.a_garten:hot_tub": "Jacuzzi exterior", + "pack:nextfloor.a_garten:fire_bowl": "Brasero", + "pack:nextfloor.a_garten:garden_torch": "Antorcha de jardín", + "pack:nextfloor.a_garten:play_tower": "Torre de juegos con tobogán", + "pack:nextfloor.a_garten:garden_shed": "Caseta de jardín", + "pack:nextfloor.a_garten:trampoline": "Cama elástica", + "pack:nextfloor.a_garten:flower_pots": "Macetas (juego de 3)", + "pack:nextfloor.a_garten:sprinkler": "Aspersor de césped", + "pack:nextfloor.a_garten:valve_box": "Arqueta de válvulas de riego", + "pack:nextfloor.a_garten:rain_barrel": "Depósito de lluvia", + "pack:nextfloor.a_garten:garden_lantern": "Farol de jardín", + "pack:nextfloor.a_garten:outdoor_kitchen": "Cocina exterior", + "pack:nextfloor.a_garten:hammock": "Hamaca con soporte", + "pack:nextfloor.a_garten:patio_heater": "Estufa de terraza", + "pack:nextfloor.a_garten:tree_oak": "Roble", + "pack:nextfloor.a_garten:tree_lime": "Tilo", + "pack:nextfloor.a_garten:tree_birch": "Abedul", + "pack:nextfloor.a_garten:tree_maple": "Arce", + "pack:nextfloor.a_garten:tree_fruit": "Árbol frutal", + "pack:nextfloor.a_garten:tree_spruce": "Abeto", + "pack:nextfloor.a_garten:tree_pine": "Pino", + "pack:nextfloor.a_garten:tree_thuja": "Tuya", + "pack:nextfloor.a_garten:shrub": "Arbusto", + "pack:nextfloor.a_garten:shrub_flowering": "Arbusto con flores", + "pack:nextfloor.a_garten:brush_wild": "Matorral (zona silvestre)", + "pack:nextfloor.a_garten:tree_group_3": "Grupo de árboles (3)", + "pack:nextfloor.a_garten:bin_rest_120": "Cubo de basura general 120 l", + "pack:nextfloor.a_garten:bin_rest_240": "Cubo de basura general 240 l", + "pack:nextfloor.a_garten:bin_bio_120": "Cubo orgánico 120 l", + "pack:nextfloor.a_garten:bin_bio_240": "Cubo orgánico 240 l", + "pack:nextfloor.a_garten:bin_paper_120": "Cubo de papel 120 l", + "pack:nextfloor.a_garten:bin_paper_240": "Cubo de papel 240 l", + "pack:nextfloor.a_garten:bin_yellow_120": "Cubo de reciclaje 120 l", + "pack:nextfloor.a_garten:bin_yellow_240": "Cubo de reciclaje 240 l", + "pack:nextfloor.a_garten:mailbox": "Buzón", + "pack:nextfloor.a_garten:mailbox_post": "Buzón sobre poste", + "pack:nextfloor.a_garten:awning_300": "Toldo 3 m", + "pack:nextfloor.a_garten:awning_400": "Toldo 4 m", + "pack:nextfloor.a_garten:awning_500": "Toldo 5 m", + "pack:nextfloor.a_garten:sliding_gate": "Portón corredero", + "packname:nextfloor.a_haustechnik": "Hogar e instalaciones", + "pack:nextfloor.a_haustechnik:gas_boiler": "Caldera de condensación de gas", + "pack:nextfloor.a_haustechnik:heat_pump_tower": "Unidad interior de bomba de calor (torre hidráulica)", + "pack:nextfloor.a_haustechnik:buffer_tank": "Depósito de inercia", + "pack:nextfloor.a_haustechnik:heating_manifold": "Colector de suelo radiante", + "pack:nextfloor.a_haustechnik:ventilation_unit": "Ventilación con recuperación de calor", + "pack:nextfloor.a_haustechnik:split_indoor": "Aire acondicionado split (unidad interior, pared)", + "pack:nextfloor.a_haustechnik:split_outdoor": "Aire acondicionado split (unidad exterior)", + "pack:nextfloor.a_haustechnik:radiator_tall": "Radiador de diseño alto", + "pack:nextfloor.a_haustechnik:meter_cabinet": "Armario de contadores", + "pack:nextfloor.a_haustechnik:water_softener": "Descalcificador", + "pack:nextfloor.a_haustechnik:water_pump": "Bomba de agua doméstica", + "pack:nextfloor.a_haustechnik:drip_tray": "Bandeja con sensor de fugas", + "pack:nextfloor.a_haustechnik:chest_freezer": "Arcón congelador", + "pack:nextfloor.a_haustechnik:ironing_station": "Centro de planchado a vapor", + "pack:nextfloor.a_haustechnik:drying_rack": "Tendedero", + "pack:nextfloor.a_haustechnik:rotary_line": "Tendedero giratorio", + "pack:nextfloor.a_haustechnik:pantry_shelf_util": "Estantería de despensa", + "pack:nextfloor.a_haustechnik:utility_sink": "Pila de lavadero", + "pack:nextfloor.a_haustechnik:laundry_basket_util": "Cesto de la ropa", + "pack:nextfloor.a_haustechnik:vacuum_station": "Estación de aspiradora sin cable", + "packname:nextfloor.a_haustiere": "Mascotas", + "pack:nextfloor.a_haustiere:cat_tree_large": "Árbol para gatos (grande)", + "pack:nextfloor.a_haustiere:scratch_post": "Rascador", + "pack:nextfloor.a_haustiere:scratch_board_wall": "Rascador de pared", + "pack:nextfloor.a_haustiere:cat_cave": "Cueva para gatos", + "pack:nextfloor.a_haustiere:cat_bed_round": "Cama redonda para gatos", + "pack:nextfloor.a_haustiere:cat_wall_shelf": "Estante de pared para gatos", + "pack:nextfloor.a_haustiere:cat_steps": "Escalones para gatos", + "pack:nextfloor.a_haustiere:litter_covered": "Arenero cubierto", + "pack:nextfloor.a_haustiere:litter_auto": "Arenero autolimpiable", + "pack:nextfloor.a_haustiere:dog_bed": "Cama para perros", + "pack:nextfloor.a_haustiere:dog_basket": "Cesta para perros", + "pack:nextfloor.a_haustiere:dog_house": "Caseta para perros", + "pack:nextfloor.a_haustiere:pet_bowls": "Comedero y bebedero", + "pack:nextfloor.a_haustiere:pet_feeder": "Comedero automático", + "pack:nextfloor.a_haustiere:pet_fountain": "Fuente para mascotas", + "pack:nextfloor.a_haustiere:pet_gate": "Barrera para mascotas", + "pack:nextfloor.a_haustiere:pet_stairs": "Escalera para mascotas", + "pack:nextfloor.a_haustiere:hamster_cage": "Jaula de hámster", + "pack:nextfloor.a_haustiere:small_animal_cage": "Jaula para animales pequeños", + "pack:nextfloor.a_haustiere:rabbit_run": "Recinto para conejos (exterior)", + "pack:nextfloor.a_haustiere:bird_cage": "Jaula para pájaros", + "pack:nextfloor.a_haustiere:aquarium_100": "Acuario 100 l", + "pack:nextfloor.a_haustiere:aquarium_240": "Acuario 240 l con mueble", + "pack:nextfloor.a_haustiere:terrarium": "Terrario", + "pack:nextfloor.a_haustiere:pet_cat": "Gato (pasea por ahí)", + "pack:nextfloor.a_haustiere:pet_dog": "Perro (pasea por ahí)", + "pack:nextfloor.a_haustiere:pet_rabbit": "Conejo (salta por ahí)", + "packname:nextfloor.a_kinderzimmer": "Habitación infantil", + "pack:nextfloor.a_kinderzimmer:loft_bed_slide": "Cama alta con tobogán", + "pack:nextfloor.a_kinderzimmer:teepee": "Tipi", + "pack:nextfloor.a_kinderzimmer:play_kitchen": "Cocinita de juguete", + "pack:nextfloor.a_kinderzimmer:kids_desk": "Escritorio infantil", + "pack:nextfloor.a_kinderzimmer:toy_shelf": "Estantería de juguetes con cajas", + "pack:nextfloor.a_kinderzimmer:cosy_corner": "Rincón acogedor", + "pack:nextfloor.a_kinderzimmer:rocking_horse": "Caballito balancín", + "pack:nextfloor.a_kinderzimmer:play_mat_road": "Alfombra de carreteras", + "pack:nextfloor.a_kinderzimmer:kids_table_2": "Mesa infantil con 2 sillas", + "pack:nextfloor.a_kinderzimmer:moon_light": "Luz nocturna de luna", + "pack:nextfloor.a_kinderzimmer:ball_pit": "Piscina de bolas", + "pack:nextfloor.a_kinderzimmer:house_bed": "Cama casita", + "pack:nextfloor.a_kinderzimmer:baby_monitor": "Vigilabebés con cámara", + "pack:nextfloor.a_kinderzimmer:star_projector": "Proyector de estrellas", + "pack:nextfloor.a_kinderzimmer:kids_cot": "Cuna", + "pack:nextfloor.a_kinderzimmer:kids_changing_table": "Cambiador", + "pack:nextfloor.a_kinderzimmer:kids_wardrobe": "Armario infantil", + "pack:nextfloor.a_kinderzimmer:toy_boxes_3": "Cajas de juguetes (3)", + "packname:nextfloor.a_kino": "Cine en casa y hi-fi", + "pack:nextfloor.a_kino:screen_wall": "Pantalla de proyección (pared)", + "pack:nextfloor.a_kino:screen_roll": "Pantalla de proyección enrollable", + "pack:nextfloor.a_kino:projector_ceiling": "Proyector (techo)", + "pack:nextfloor.a_kino:projector_table": "Proyector (mesa)", + "pack:nextfloor.a_kino:speaker_floor": "Altavoz de suelo", + "pack:nextfloor.a_kino:speaker_shelf": "Altavoz de estantería", + "pack:nextfloor.a_kino:speaker_centre": "Altavoz central", + "pack:nextfloor.a_kino:subwoofer": "Subwoofer", + "pack:nextfloor.a_kino:soundbar": "Barra de sonido", + "pack:nextfloor.a_kino:soundbar_premium": "Barra de sonido premium", + "pack:nextfloor.a_kino:speaker_wall": "Altavoz de pared", + "pack:nextfloor.a_kino:speaker_ceiling": "Altavoz de techo", + "pack:nextfloor.a_kino:av_receiver": "Receptor AV", + "pack:nextfloor.a_kino:turntable": "Tocadiscos", + "pack:nextfloor.a_kino:record_shelf": "Estantería de discos", + "pack:nextfloor.a_kino:game_console": "Videoconsola", + "pack:nextfloor.a_kino:hifi_rack": "Rack hi-fi", + "pack:nextfloor.a_kino:cinema_seat": "Butaca de cine", + "pack:nextfloor.a_kino:cinema_row_3": "Fila de butacas de cine (3)", + "pack:nextfloor.a_kino:acoustic_panel": "Panel acústico", + "pack:nextfloor.a_kino:bass_trap": "Trampa de graves (esquina)", + "pack:nextfloor.a_kino:popcorn_maker": "Máquina de palomitas", + "pack:nextfloor.a_kino:star_ceiling": "Techo de estrellas", + "pack:nextfloor.a_kino:smart_speaker_ball": "Altavoz inteligente (esfera)", + "pack:nextfloor.a_kino:smart_speaker_cylinder": "Altavoz inteligente (cilindro)", + "pack:nextfloor.a_kino:smart_speaker_puck": "Altavoz inteligente (disco)", + "pack:nextfloor.a_kino:smart_speaker_pod": "Altavoz inteligente (pod)", + "pack:nextfloor.a_kino:smart_speaker_tall": "Altavoz inteligente (alto)", + "pack:nextfloor.a_kino:smart_speaker_oval": "Altavoz inteligente (ovalado)", + "pack:nextfloor.a_kino:multiroom_compact": "Altavoz multiroom compacto", + "pack:nextfloor.a_kino:speaker_portable": "Altavoz portátil", + "pack:nextfloor.a_kino:display_5": "Pantalla inteligente 5″", + "pack:nextfloor.a_kino:display_8": "Pantalla inteligente 8″", + "pack:nextfloor.a_kino:display_7_float": "Pantalla inteligente 7″ (flotante)", + "pack:nextfloor.a_kino:display_15_wall": "Pantalla inteligente 15″ (pared)", + "pack:nextfloor.a_kino:speaker_stand": "Soporte de altavoz", + "packname:nextfloor.a_kueche": "Cocina", + "pack:nextfloor.a_kueche:base_30": "Mueble bajo 30", + "pack:nextfloor.a_kueche:base_40": "Mueble bajo 40", + "pack:nextfloor.a_kueche:base_50": "Mueble bajo 50", + "pack:nextfloor.a_kueche:base_60": "Mueble bajo 60", + "pack:nextfloor.a_kueche:base_80": "Mueble bajo 80", + "pack:nextfloor.a_kueche:base_90": "Mueble bajo 90", + "pack:nextfloor.a_kueche:base_100": "Mueble bajo 100", + "pack:nextfloor.a_kueche:base_120": "Mueble bajo 120", + "pack:nextfloor.a_kueche:drawer_40": "Cajonera 40", + "pack:nextfloor.a_kueche:drawer_50": "Cajonera 50", + "pack:nextfloor.a_kueche:drawer_60": "Cajonera 60", + "pack:nextfloor.a_kueche:drawer_80": "Cajonera 80", + "pack:nextfloor.a_kueche:drawer_90": "Cajonera 90", + "pack:nextfloor.a_kueche:drawer_100": "Cajonera 100", + "pack:nextfloor.a_kueche:drawer_120": "Cajonera 120", + "pack:nextfloor.a_kueche:sink_60": "Mueble fregadero 60", + "pack:nextfloor.a_kueche:sink_80": "Mueble fregadero 80", + "pack:nextfloor.a_kueche:sink_100": "Mueble fregadero 100", + "pack:nextfloor.a_kueche:hob_60": "Mueble de placa 60", + "pack:nextfloor.a_kueche:hob_80": "Mueble de placa 80", + "pack:nextfloor.a_kueche:cooker_60": "Cocina con horno 60", + "pack:nextfloor.a_kueche:dishwasher_60": "Lavavajillas integrable 60", + "pack:nextfloor.a_kueche:dishwasher_45": "Lavavajillas integrable 45", + "pack:nextfloor.a_kueche:base_corner": "Mueble bajo de esquina", + "pack:nextfloor.a_kueche:wall_40": "Mueble alto 40", + "pack:nextfloor.a_kueche:wall_50": "Mueble alto 50", + "pack:nextfloor.a_kueche:wall_60": "Mueble alto 60", + "pack:nextfloor.a_kueche:wall_80": "Mueble alto 80", + "pack:nextfloor.a_kueche:wall_90": "Mueble alto 90", + "pack:nextfloor.a_kueche:wall_100": "Mueble alto 100", + "pack:nextfloor.a_kueche:wall_120": "Mueble alto 120", + "pack:nextfloor.a_kueche:wall_glass_80": "Mueble alto de cristal 80", + "pack:nextfloor.a_kueche:wall_corner": "Mueble alto de esquina", + "pack:nextfloor.a_kueche:hood_wall": "Campana de pared", + "pack:nextfloor.a_kueche:hood_island": "Campana de isla", + "pack:nextfloor.a_kueche:tall_pantry": "Columna despensa", + "pack:nextfloor.a_kueche:tall_oven": "Columna horno y microondas", + "pack:nextfloor.a_kueche:tall_fridge": "Columna frigorífico-congelador", + "pack:nextfloor.a_kueche:tall_steam": "Columna vapor y horno", + "pack:nextfloor.a_kueche:fridge_freezer": "Frigorífico-congelador", + "pack:nextfloor.a_kueche:fridge_french": "Frigorífico de puertas francesas", + "pack:nextfloor.a_kueche:wine_fridge": "Vinoteca", + "pack:nextfloor.a_kueche:glass_cabinet": "Vitrina", + "pack:nextfloor.a_kueche:row_270": "Cocina en línea 270", + "pack:nextfloor.a_kueche:row_330": "Cocina en línea 330", + "pack:nextfloor.a_kueche:island_bar": "Isla de cocina con barra", + "pack:nextfloor.a_kueche:island_hob": "Isla de cocina con placa", + "pack:nextfloor.a_kueche:breakfast_bar": "Barra de desayuno (pared)", + "pack:nextfloor.a_kueche:bar_stools_2": "Taburetes de bar (juego de 2)", + "pack:nextfloor.a_kueche:dining_bench_long": "Mesa de comedor larga con banco", + "pack:nextfloor.a_kueche:dining_round_4": "Mesa de comedor redonda con 4 sillas", + "pack:nextfloor.a_kueche:high_table_2": "Mesa alta con 2 taburetes", + "pack:nextfloor.a_kueche:kitchen_trolley": "Carrito de cocina", + "pack:nextfloor.a_kueche:pantry_shelf": "Estantería de despensa", + "pack:nextfloor.a_kueche:spice_rack": "Especiero de pared", + "pack:nextfloor.a_kueche:coffee_machine": "Cafetera superautomática", + "pack:nextfloor.a_kueche:microwave": "Microondas", + "pack:nextfloor.a_kueche:stand_mixer": "Batidora amasadora", + "pack:nextfloor.a_kueche:kettle": "Hervidor", + "pack:nextfloor.a_kueche:toaster": "Tostadora", + "pack:nextfloor.a_kueche:herb_garden": "Huerto inteligente de hierbas", + "pack:nextfloor.a_kueche:pendant_trio": "Trío de lámparas colgantes", + "pack:nextfloor.a_kueche:pendant_linear": "Lámpara colgante lineal", + "pack:nextfloor.a_kueche:cabinet_light_60": "Luz LED bajo mueble 60", + "pack:nextfloor.a_kueche:cabinet_light_80": "Luz LED bajo mueble 80", + "pack:nextfloor.a_kueche:range_cooker_90": "Cocina de gran formato 90", + "packname:nextfloor.a_schlafzimmer": "Dormitorio", + "pack:nextfloor.a_schlafzimmer:bed_90": "Cama 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_140": "Cama 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_160": "Cama 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_180": "Cama 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_200": "Cama 200 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_180": "Cama tapizada 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_140": "Cama tapizada 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_boxspring": "Cama box spring 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_futon": "Cama futón 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_storage": "Cama con almacenaje 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_canopy": "Cama con dosel", + "pack:nextfloor.a_schlafzimmer:bed_ambient": "Cama 180 con luz ambiental", + "pack:nextfloor.a_schlafzimmer:bed_bench": "Banco de cama", + "pack:nextfloor.a_schlafzimmer:shoe_bench": "Banco zapatero", + "pack:nextfloor.a_schlafzimmer:wardrobe_2": "Armario de 2 puertas", + "pack:nextfloor.a_schlafzimmer:wardrobe_3": "Armario de 3 puertas", + "pack:nextfloor.a_schlafzimmer:wardrobe_4": "Armario de 4 puertas", + "pack:nextfloor.a_schlafzimmer:wardrobe_6": "Armario de 6 puertas", + "pack:nextfloor.a_schlafzimmer:wardrobe_mirror": "Armario con puerta de espejo", + "pack:nextfloor.a_schlafzimmer:wardrobe_sliding": "Armario de puertas correderas", + "pack:nextfloor.a_schlafzimmer:wardrobe_light": "Armario con luz interior", + "pack:nextfloor.a_schlafzimmer:wardrobe_corner": "Armario de esquina", + "pack:nextfloor.a_schlafzimmer:walk_in_closet": "Vestidor abierto", + "pack:nextfloor.a_schlafzimmer:clothes_rail": "Burro para ropa", + "pack:nextfloor.a_schlafzimmer:nightstand": "Mesita de noche con cajón", + "pack:nextfloor.a_schlafzimmer:nightstand_slim": "Mesita de noche estrecha", + "pack:nextfloor.a_schlafzimmer:nightstand_floating": "Mesita de noche flotante", + "pack:nextfloor.a_schlafzimmer:dresser_6": "Cómoda de 6 cajones 140", + "pack:nextfloor.a_schlafzimmer:chest_tall_5": "Sinfonier de 5 cajones", + "pack:nextfloor.a_schlafzimmer:chest_tall": "Cómoda alta", + "pack:nextfloor.a_schlafzimmer:chest_80": "Cómoda de 3 cajones 80", + "pack:nextfloor.a_schlafzimmer:vanity_table": "Tocador con espejo", + "pack:nextfloor.a_schlafzimmer:dressing_table_light": "Tocador con espejo iluminado", + "pack:nextfloor.a_schlafzimmer:cot": "Cuna", + "pack:nextfloor.a_schlafzimmer:changing_table": "Cambiador", + "pack:nextfloor.a_schlafzimmer:standing_mirror": "Espejo de pie", + "pack:nextfloor.a_schlafzimmer:reading_nook": "Rincón de lectura con sillón", + "pack:nextfloor.a_schlafzimmer:bedside_lamp": "Lámpara de mesita", + "pack:nextfloor.a_schlafzimmer:touch_lamp": "Lámpara de mesita táctil", + "pack:nextfloor.a_schlafzimmer:humidifier": "Humidificador", + "pack:nextfloor.a_schlafzimmer:sunrise_clock": "Despertador de amanecer", + "packname:nextfloor.a_smart": "Hogar inteligente y tecnología", + "pack:nextfloor.a_smart:wallbox": "Wallbox", + "pack:nextfloor.a_smart:electric_car": "Coche eléctrico", + "pack:nextfloor.a_smart:heat_pump_outdoor": "Bomba de calor (unidad exterior)", + "pack:nextfloor.a_smart:home_battery": "Batería doméstica", + "pack:nextfloor.a_smart:inverter_solar": "Inversor solar", + "pack:nextfloor.a_smart:robot_vacuum": "Robot aspirador con base", + "pack:nextfloor.a_smart:mower_garage": "Robot cortacésped con garaje", + "pack:nextfloor.a_smart:washer_dryer_stack": "Columna lavadora-secadora", + "pack:nextfloor.a_smart:network_rack": "Rack de red", + "pack:nextfloor.a_smart:smart_display": "Pantalla inteligente", + "pack:nextfloor.a_smart:solar_balcony": "Placa solar de balcón", + "pack:nextfloor.a_smart:fuse_box": "Cuadro eléctrico", + "pack:nextfloor.a_smart:nas_server": "Servidor NAS", + "pack:nextfloor.a_smart:hot_water_tank": "Termo de agua caliente", + "pack:nextfloor.a_smart:light_pillar": "Columna de luz degradada", + "pack:nextfloor.a_smart:light_bars_tv": "Par de barras de luz (TV)", + "pack:nextfloor.a_smart:orb_lamp": "Lámpara de mesa esfera luminosa", + "pack:nextfloor.a_smart:glow_lamp_portable": "Lámpara luminosa portátil", + "pack:nextfloor.a_smart:mood_spot": "Foco ambiental de mesa", + "pack:nextfloor.a_smart:cube_lamp": "Lámpara cubo", + "pack:nextfloor.a_smart:ceiling_panel_round": "Panel de techo redondo", + "pack:nextfloor.a_smart:garden_spots_3": "Focos de jardín (juego de 3)", + "pack:nextfloor.a_smart:wall_light_updown": "Aplique exterior arriba y abajo", + "pack:nextfloor.a_smart:siren_strobe": "Sirena con estroboscopio", + "pack:nextfloor.a_smart:access_point": "Punto de acceso Wi-Fi (techo)", + "pack:nextfloor.a_smart:smoke_detector": "Detector de humo", + "pack:nextfloor.a_smart:thermostat_wall": "Termostato de pared", + "pack:nextfloor.a_smart:dehumidifier": "Deshumidificador", + "pack:nextfloor.a_smart:ceiling_fan": "Ventilador de techo", + "pack:nextfloor.a_smart:ceiling_fan_light": "Ventilador de techo con luz", + "pack:nextfloor.a_smart:light_switch_1": "Interruptor de luz, 1 tecla", + "pack:nextfloor.a_smart:socket_1": "Enchufe, 1 toma", + "pack:nextfloor.a_smart:light_switch_2": "Interruptor de luz, 2 teclas", + "pack:nextfloor.a_smart:socket_2": "Enchufe, 2 tomas", + "pack:nextfloor.a_smart:light_switch_3": "Interruptor de luz, 3 teclas", + "pack:nextfloor.a_smart:socket_3": "Enchufe, 3 tomas", + "pack:nextfloor.a_smart:light_switch_4": "Interruptor de luz, 4 teclas", + "pack:nextfloor.a_smart:socket_4": "Enchufe, 4 tomas", + "pack:nextfloor.a_smart:socket_outdoor": "Enchufe exterior con tapa", + "packname:nextfloor.a_wohnzimmer": "Salón", + "pack:nextfloor.a_wohnzimmer:sofa_2": "Sofá de 2 plazas", + "pack:nextfloor.a_wohnzimmer:sofa_3": "Sofá de 3 plazas", + "pack:nextfloor.a_wohnzimmer:sofa_4": "Sofá grande de 4 plazas", + "pack:nextfloor.a_wohnzimmer:sofa_velvet": "Sofá de terciopelo de 3 plazas", + "pack:nextfloor.a_wohnzimmer:sofa_armless": "Sofá sin brazos", + "pack:nextfloor.a_wohnzimmer:sofa_chaise": "Sofá con chaise longue", + "pack:nextfloor.a_wohnzimmer:sofa_chesterfield": "Sofá Chesterfield", + "pack:nextfloor.a_wohnzimmer:sofa_bed": "Sofá cama", + "pack:nextfloor.a_wohnzimmer:sofa_corner_l": "Sofá rinconera (izquierda)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_r": "Sofá rinconera (derecha)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_xl": "Sofá rinconera grande (en L)", + "pack:nextfloor.a_wohnzimmer:sofa_u": "Sofá en U", + "pack:nextfloor.a_wohnzimmer:chaise_longue": "Chaise longue", + "pack:nextfloor.a_wohnzimmer:modular_sofa": "Sofá modular (5 piezas)", + "pack:nextfloor.a_wohnzimmer:armchair": "Sillón", + "pack:nextfloor.a_wohnzimmer:club_chair": "Sillón club", + "pack:nextfloor.a_wohnzimmer:wingback": "Sillón orejero", + "pack:nextfloor.a_wohnzimmer:cocktail_chair": "Sillón cóctel", + "pack:nextfloor.a_wohnzimmer:recliner": "Sillón reclinable con reposapiés", + "pack:nextfloor.a_wohnzimmer:bean_bag": "Puf saco", + "pack:nextfloor.a_wohnzimmer:pouf": "Puf", + "pack:nextfloor.a_wohnzimmer:rocking_chair": "Mecedora", + "pack:nextfloor.a_wohnzimmer:coffee_rect": "Mesa de centro rectangular", + "pack:nextfloor.a_wohnzimmer:coffee_glass": "Mesa de centro de cristal", + "pack:nextfloor.a_wohnzimmer:coffee_round": "Mesa de centro redonda", + "pack:nextfloor.a_wohnzimmer:coffee_nesting": "Mesas de centro nido", + "pack:nextfloor.a_wohnzimmer:side_round": "Mesa auxiliar redonda", + "pack:nextfloor.a_wohnzimmer:console": "Consola", + "pack:nextfloor.a_wohnzimmer:dining_120": "Mesa de comedor 120 × 90", + "pack:nextfloor.a_wohnzimmer:dining_160": "Mesa de comedor 160 × 90", + "pack:nextfloor.a_wohnzimmer:dining_200": "Mesa de comedor 200 × 90", + "pack:nextfloor.a_wohnzimmer:dining_220": "Mesa de comedor de madera maciza 220 × 100", + "pack:nextfloor.a_wohnzimmer:chair_wood": "Silla de madera", + "pack:nextfloor.a_wohnzimmer:chair_upholstered": "Silla tapizada", + "pack:nextfloor.a_wohnzimmer:chair_shell": "Silla de carcasa", + "pack:nextfloor.a_wohnzimmer:dining_bench": "Banco de comedor 160", + "pack:nextfloor.a_wohnzimmer:lowboard_120": "Mueble bajo 120", + "pack:nextfloor.a_wohnzimmer:lowboard_160": "Mueble bajo 160", + "pack:nextfloor.a_wohnzimmer:lowboard_200": "Mueble bajo 200", + "pack:nextfloor.a_wohnzimmer:sideboard_160": "Aparador 160", + "pack:nextfloor.a_wohnzimmer:highboard": "Aparador alto", + "pack:nextfloor.a_wohnzimmer:display_cabinet": "Vitrina", + "pack:nextfloor.a_wohnzimmer:chest_3": "Cómoda de 3 cajones", + "pack:nextfloor.a_wohnzimmer:bookshelf_tall": "Librería alta", + "pack:nextfloor.a_wohnzimmer:bookshelf_wide": "Librería ancha", + "pack:nextfloor.a_wohnzimmer:cube_2x2": "Estantería de cubos 2 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x2": "Estantería de cubos 4 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x4": "Estantería de cubos 4 × 4", + "pack:nextfloor.a_wohnzimmer:divider_open": "Estantería separadora", + "pack:nextfloor.a_wohnzimmer:wall_shelf": "Estante flotante", + "pack:nextfloor.a_wohnzimmer:coat_stand": "Perchero de pie", + "pack:nextfloor.a_wohnzimmer:wall_unit_vitrines": "Mueble de pared con vitrinas", + "pack:nextfloor.a_wohnzimmer:wall_unit_tv": "Mueble de pared con TV", + "pack:nextfloor.a_wohnzimmer:tv_on_stand": "TV sobre soporte", + "pack:nextfloor.a_wohnzimmer:media_wall": "Pared multimedia con TV", + "pack:nextfloor.a_wohnzimmer:wood_stove": "Estufa de leña", + "pack:nextfloor.a_wohnzimmer:fireplace_wall": "Chimenea eléctrica de pared", + "pack:nextfloor.a_wohnzimmer:piano": "Piano vertical con banqueta", + "pack:nextfloor.a_wohnzimmer:floor_lamp_arc": "Lámpara de pie de arco", + "pack:nextfloor.a_wohnzimmer:floor_lamp_tripod": "Lámpara de pie trípode", + "pack:nextfloor.a_wohnzimmer:table_lamp_ceramic": "Lámpara de mesa de cerámica", + "pack:nextfloor.a_wohnzimmer:vase_pampas": "Jarrón de suelo con hierba de las pampas", + "pack:nextfloor.a_wohnzimmer:monstera": "Monstera grande", + "pack:nextfloor.a_wohnzimmer:rug_round": "Alfombra redonda", + "pack:nextfloor.a_wohnzimmer:rug_240": "Alfombra 240 × 170", + "pack:nextfloor.a_wohnzimmer:painting_light": "Cuadro con luz de cuadro", + "pack:nextfloor.a_wohnzimmer:shelf_led": "Estantería con baldas LED", + "pack:nextfloor.a_wohnzimmer:air_purifier": "Purificador de aire", + "pack:nextfloor.a_wohnzimmer:tower_fan": "Ventilador de torre", + "pack:nextfloor.a_wohnzimmer:smart_speaker_living": "Altavoz inteligente", + "packname:nextfloor.ausbau": "Arquitectura y acabados", + "pack:nextfloor.ausbau:column_round": "Columna redonda", + "pack:nextfloor.ausbau:column_square": "Columna cuadrada", + "pack:nextfloor.ausbau:beam": "Viga de techo", + "pack:nextfloor.ausbau:chimney": "Chimenea (obra)", + "pack:nextfloor.ausbau:glass_wall": "Mampara de cristal", + "pack:nextfloor.ausbau:sliding_wall": "Pared corredera", + "pack:nextfloor.ausbau:platform": "Tarima", + "pack:nextfloor.ausbau:half_wall": "Media pared", + "pack:nextfloor.ausbau:divider_shelf": "Estantería divisoria", + "pack:nextfloor.ausbau:pilaster": "Pilastra", + "pack:nextfloor.ausbau:column_steel": "Columna de acero", + "pack:nextfloor.ausbau:beams_wood_5": "Vigas de madera del techo (5)", + "pack:nextfloor.ausbau:beam_downstand": "Viga descolgada", + "pack:nextfloor.ausbau:fireplace_builtin": "Chimenea empotrada", + "pack:nextfloor.ausbau:divider_slats": "Separador de listones", + "pack:nextfloor.ausbau:curtain_motor": "Cortina motorizada", + "pack:nextfloor.ausbau:niche_shelf": "Estantería empotrada (hornacina)", + "pack:nextfloor.ausbau:niche_led": "Nicho LED", + "pack:nextfloor.ausbau:light_cove": "Foseado de luz (techo)", + "pack:nextfloor.ausbau:gallery_rail_glass": "Barandilla de galería (cristal)", + "pack:nextfloor.ausbau:window_seat": "Banco de ventana", + "pack:nextfloor.ausbau:curtain_pair": "Cortina (abre a ambos lados)", + "pack:nextfloor.ausbau:roller_blind_inside": "Estor enrollable (interior)", + "packname:nextfloor.bad": "Baño extra", + "pack:nextfloor.bad:double_vanity": "Doble lavabo", + "pack:nextfloor.bad:walkin_shower": "Ducha a ras de suelo", + "pack:nextfloor.bad:towel_radiator": "Radiador toallero", + "pack:nextfloor.bad:mirror_cabinet": "Armario con espejo y luz", + "pack:nextfloor.bad:washer_tower": "Columna lavadora-secadora", + "pack:nextfloor.bad:laundry_basket": "Cesto de la ropa", + "pack:nextfloor.bad:bath_shelf": "Estante de baño", + "packname:nextfloor.energie": "Energía e instalaciones", + "pack:nextfloor.energie:heat_pump": "Bomba de calor (unidad exterior)", + "pack:nextfloor.energie:pellet_boiler": "Caldera de pellets", + "pack:nextfloor.energie:buffer_tank": "Depósito de inercia", + "pack:nextfloor.energie:hot_water_tank": "Termo de agua caliente", + "pack:nextfloor.energie:home_battery": "Batería doméstica (torre)", + "pack:nextfloor.energie:inverter": "Inversor", + "pack:nextfloor.energie:wallbox": "Wallbox", + "pack:nextfloor.energie:meter_cabinet": "Armario de contadores", + "pack:nextfloor.energie:ventilation": "Unidad de ventilación", + "pack:nextfloor.energie:solar_carport_pillar": "Poste de cochera solar", + "packname:nextfloor.fahrzeuge": "Vehículos", + "pack:nextfloor.fahrzeuge:tesla_model_s": "Tesla Model S", + "packname:nextfloor.a_saison": "Temporada y decoración", + "packname:nextfloor.a_smart2": "Hogar inteligente 2", + "packname:nextfloor.a_haustechnik2": "Instalaciones 2", + "packname:nextfloor.a_wellness": "Bienestar", + "packname:nextfloor.a_garten2": "Jardín 2", + "packname:nextfloor.a_kueche2": "Cocina 2", + "packname:nextfloor.a_fahrzeuge2": "Vehículos 2", + "packname:nextfloor.a_aussenkueche": "Cocina exterior y terraza", + "packname:nextfloor.a_werkstatt2": "Taller 2", + "packname:nextfloor.a_japandi": "Japandi y escandinavo", + "packname:nextfloor.a_loft": "Loft e industrial", + "packname:nextfloor.a_gruen": "Plantas de interior", + "packname:nextfloor.a_musik": "Música y estudio", + "pack:nextfloor.a_saison:xmas_tree": "Árbol de Navidad con luces", + "pack:nextfloor.a_saison:advent_wreath": "Corona de Adviento", + "pack:nextfloor.a_saison:lights_outdoor": "Guirnalda exterior", + "pack:nextfloor.a_saison:window_star": "Estrella de ventana", + "pack:nextfloor.a_saison:candle_arch": "Arco de velas", + "pack:nextfloor.a_saison:reindeer_light": "Reno luminoso", + "pack:nextfloor.a_saison:pumpkin": "Calabaza", + "pack:nextfloor.a_saison:pumpkin_lantern": "Calabaza iluminada", + "pack:nextfloor.a_saison:easter_tree": "Árbol de Pascua", + "pack:nextfloor.a_saison:snowman": "Muñeco de nieve", + "pack:nextfloor.a_saison:gift_pile": "Regalos", + "pack:nextfloor.a_smart2:siren": "Sirena", + "pack:nextfloor.a_smart2:access_point": "Punto de acceso Wi-Fi", + "pack:nextfloor.a_smart2:access_point_wall": "Punto de acceso Wi-Fi (pared)", + "pack:nextfloor.a_smart2:smoke_detector": "Detector de humo", + "pack:nextfloor.a_smart2:co_detector": "Detector de CO", + "pack:nextfloor.a_smart2:dehumidifier": "Deshumidificador", + "pack:nextfloor.a_smart2:cube_lamp": "Lámpara cubo", + "pack:nextfloor.a_smart2:presence_ceiling": "Sensor de presencia (techo)", + "pack:nextfloor.a_smart2:water_leak": "Detector de fugas", + "pack:nextfloor.a_smart2:air_quality": "Medidor de calidad del aire", + "pack:nextfloor.a_smart2:doorbell_cam": "Timbre con vídeo", + "pack:nextfloor.a_haustechnik2:water_tank": "Depósito de agua", + "pack:nextfloor.a_haustechnik2:oil_tank": "Depósito de gasóleo", + "pack:nextfloor.a_haustechnik2:oil_boiler": "Caldera de gasóleo", + "pack:nextfloor.a_haustechnik2:water_softener": "Descalcificador", + "pack:nextfloor.a_haustechnik2:buffer_tank": "Depósito de inercia", + "pack:nextfloor.a_haustechnik2:cistern": "Cisterna de agua de lluvia", + "pack:nextfloor.a_haustechnik2:ventilation_unit": "Unidad de ventilación", + "pack:nextfloor.a_haustechnik2:expansion_vessel": "Vaso de expansión", + "pack:nextfloor.a_haustechnik2:heat_pump_indoor": "Bomba de calor (unidad interior)", + "pack:nextfloor.a_wellness:sauna_cabin": "Sauna", + "pack:nextfloor.a_wellness:sauna_barrel": "Sauna barril", + "pack:nextfloor.a_wellness:infrared_cabin": "Cabina de infrarrojos", + "pack:nextfloor.a_wellness:hot_tub": "Jacuzzi", + "pack:nextfloor.a_wellness:plunge_pool": "Piscina de inmersión", + "pack:nextfloor.a_wellness:steam_shower": "Ducha de vapor", + "pack:nextfloor.a_wellness:relax_lounger": "Tumbona de relajación", + "pack:nextfloor.a_wellness:cold_bath": "Baño de hielo", + "pack:nextfloor.a_garten2:water_feature": "Fuente con luz", + "pack:nextfloor.a_garten2:pond": "Estanque con bomba", + "pack:nextfloor.a_garten2:robot_mower": "Robot cortacésped", + "pack:nextfloor.a_garten2:mower_dock": "Base de carga del robot", + "pack:nextfloor.a_garten2:sandbox": "Arenero", + "pack:nextfloor.a_garten2:beach_chair": "Silla de playa con capota", + "pack:nextfloor.a_garten2:wood_pile": "Pila de leña", + "pack:nextfloor.a_garten2:bird_house": "Comedero para pájaros", + "pack:nextfloor.a_garten2:raised_bed": "Bancal elevado", + "pack:nextfloor.a_garten2:garden_shower": "Ducha de jardín", + "pack:nextfloor.a_kueche2:coffee_machine": "Cafetera superautomática", + "pack:nextfloor.a_kueche2:espresso": "Cafetera espresso", + "pack:nextfloor.a_kueche2:kettle": "Hervidor", + "pack:nextfloor.a_kueche2:toaster": "Tostadora", + "pack:nextfloor.a_kueche2:stand_mixer": "Batidora amasadora", + "pack:nextfloor.a_kueche2:thermo_cooker": "Robot de cocina con cocción", + "pack:nextfloor.a_kueche2:air_fryer": "Freidora de aire", + "pack:nextfloor.a_kueche2:microwave": "Microondas", + "pack:nextfloor.a_kueche2:wine_fridge": "Vinoteca", + "pack:nextfloor.a_kueche2:water_bar": "Máquina de soda", + "pack:nextfloor.a_kueche2:dishwasher_slim": "Lavavajillas de 45 cm", + "pack:nextfloor.a_fahrzeuge2:motorbike": "Moto", + "pack:nextfloor.a_fahrzeuge2:scooter": "Scooter", + "pack:nextfloor.a_fahrzeuge2:camper_van": "Autocaravana", + "pack:nextfloor.a_fahrzeuge2:trailer": "Remolque", + "pack:nextfloor.a_fahrzeuge2:e_bike": "Bicicleta eléctrica", + "pack:nextfloor.a_fahrzeuge2:cargo_bike": "Bicicleta de carga", + "pack:nextfloor.a_fahrzeuge2:quad": "Quad", + "pack:nextfloor.a_fahrzeuge2:boat_trailer": "Remolque con barco", + "pack:nextfloor.a_aussenkueche:outdoor_kitchen": "Cocina exterior", + "pack:nextfloor.a_aussenkueche:kamado": "Parrilla kamado", + "pack:nextfloor.a_aussenkueche:pizza_oven": "Horno de pizza", + "pack:nextfloor.a_aussenkueche:fire_pit": "Brasero", + "pack:nextfloor.a_aussenkueche:patio_heater": "Estufa de terraza", + "pack:nextfloor.a_aussenkueche:outdoor_fridge": "Nevera exterior", + "pack:nextfloor.a_aussenkueche:bar_counter": "Barra de bar", + "pack:nextfloor.a_aussenkueche:bar_stool_out": "Taburete de bar exterior", + "pack:nextfloor.a_aussenkueche:hanging_chair": "Silla colgante", + "pack:nextfloor.a_werkstatt2:workbench_wall": "Banco con panel perforado", + "pack:nextfloor.a_werkstatt2:drill_press": "Taladro de columna", + "pack:nextfloor.a_werkstatt2:table_saw": "Sierra de mesa", + "pack:nextfloor.a_werkstatt2:compressor": "Compresor", + "pack:nextfloor.a_werkstatt2:welder": "Soldadora", + "pack:nextfloor.a_werkstatt2:heavy_shelf": "Estantería de carga pesada", + "pack:nextfloor.a_werkstatt2:parts_cabinet": "Organizador de piezas", + "pack:nextfloor.a_werkstatt2:tool_chest": "Carro de herramientas", + "pack:nextfloor.a_werkstatt2:ev_bike_charger": "Estación de carga de baterías", + "pack:nextfloor.a_japandi:low_bed": "Cama baja", + "pack:nextfloor.a_japandi:tatami": "Tatami", + "pack:nextfloor.a_japandi:paper_lamp": "Lámpara de papel", + "pack:nextfloor.a_japandi:paper_pendant": "Lámpara colgante de papel", + "pack:nextfloor.a_japandi:tea_table": "Mesa de té baja", + "pack:nextfloor.a_japandi:shoji_screen": "Biombo shoji", + "pack:nextfloor.a_japandi:bonsai": "Bonsái", + "pack:nextfloor.a_japandi:floor_cushion": "Cojín de suelo", + "pack:nextfloor.a_japandi:wood_bench": "Banco de madera", + "pack:nextfloor.a_japandi:rattan_chair": "Sillón de ratán", + "pack:nextfloor.a_loft:steel_shelf": "Estantería de acero", + "pack:nextfloor.a_loft:factory_pendant": "Lámpara industrial colgante", + "pack:nextfloor.a_loft:leather_sofa": "Sofá de cuero", + "pack:nextfloor.a_loft:plank_table": "Mesa de tablones", + "pack:nextfloor.a_loft:locker": "Taquilla metálica", + "pack:nextfloor.a_loft:edison_floor_lamp": "Lámpara de pie Edison", + "pack:nextfloor.a_loft:bar_stool_loft": "Taburete industrial", + "pack:nextfloor.a_loft:pipe_shelf": "Estante de tubos", + "pack:nextfloor.a_gruen:monstera": "Monstera", + "pack:nextfloor.a_gruen:ficus": "Ficus", + "pack:nextfloor.a_gruen:olive_tree": "Olivo en maceta", + "pack:nextfloor.a_gruen:cactus_group": "Cactus", + "pack:nextfloor.a_gruen:hanging_plant": "Planta colgante", + "pack:nextfloor.a_gruen:plant_shelf": "Estante para plantas con luz", + "pack:nextfloor.a_gruen:vertical_garden": "Jardín vertical", + "pack:nextfloor.a_gruen:grow_light": "Lámpara de cultivo", + "pack:nextfloor.a_gruen:herb_planter": "Huerto de hierbas inteligente", + "pack:nextfloor.a_musik:upright_piano": "Piano vertical", + "pack:nextfloor.a_musik:grand_piano": "Piano de cola", + "pack:nextfloor.a_musik:drum_kit": "Batería", + "pack:nextfloor.a_musik:guitar_stand": "Guitarras en soporte", + "pack:nextfloor.a_musik:guitar_amp": "Amplificador de guitarra", + "pack:nextfloor.a_musik:mixing_desk": "Mesa de estudio con mezclador", + "pack:nextfloor.a_musik:studio_monitor": "Monitor de estudio", + "pack:nextfloor.a_musik:synth": "Sintetizador", + "pack:nextfloor.a_musik:mic_stand": "Micrófono con pie", + "pack:nextfloor.a_musik:easel": "Caballete", + "pack:nextfloor.a_musik:vinyl_player": "Tocadiscos", + "packname:nextfloor.a_bilder": "Cuadros y marcos", + "pack:nextfloor.a_bilder:frame_landscape": "Marco (horizontal)", + "pack:nextfloor.a_bilder:frame_portrait": "Marco (vertical)", + "pack:nextfloor.a_bilder:frame_square": "Marco (cuadrado)", + "pack:nextfloor.a_bilder:frame_large": "Marco grande", + "pack:nextfloor.a_bilder:canvas": "Lienzo", + "pack:nextfloor.a_bilder:poster": "Póster", + "pack:nextfloor.a_bilder:frame_table": "Marco de mesa", + "pack:nextfloor.a_bilder:frame_digital": "Marco digital", + "pack:nextfloor.a_bilder:picture_ledge": "Repisa para cuadros", + "color:pearl_white": "Pearl White", + "color:solid_black": "Solid Black", + "color:midnight_silver": "Midnight Silver", + "color:quicksilver": "Quicksilver", + "color:deep_blue": "Deep Blue", + "color:ultra_red": "Ultra Red", + "color:midnight_cherry": "Midnight Cherry Red", + "pack:nextfloor.fahrzeuge:tesla_model_3": "Tesla Model 3", + "color:red": "Red Multi-Coat", + "color:stealth_grey": "Stealth Grey", + "pack:nextfloor.fahrzeuge:tesla_model_x": "Tesla Model X", + "pack:nextfloor.fahrzeuge:tesla_model_y": "Tesla Model Y", + "pack:nextfloor.fahrzeuge:tesla_cybertruck": "Tesla Cybertruck", + "color:stainless": "Stainless Steel", + "color:wrap_black": "Vinilo Satin Black", + "color:wrap_white": "Vinilo Satin White", + "color:wrap_grey": "Vinilo Satin Grey", + "color:wrap_blue": "Vinilo Satin Blue", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024": "Tesla Model 3 (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024_performance": "Tesla Model 3 Performance (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_s_plaid": "Tesla Model S Plaid", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025": "Tesla Model Y Standard (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_premium": "Tesla Model Y Premium (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_performance": "Tesla Model Y Performance (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_l": "Tesla Model Y L", + "pack:nextfloor.fahrzeuge:tesla_roadster": "Tesla Roadster", + "pack:nextfloor.fahrzeuge:tesla_semi": "Tesla Semi", + "pack:nextfloor.fahrzeuge:ev_suv": "SUV eléctrico (tamaño Model Y)", + "pack:nextfloor.fahrzeuge:small_car": "Coche pequeño", + "pack:nextfloor.fahrzeuge:estate_car": "Familiar", + "pack:nextfloor.fahrzeuge:van": "Furgoneta", + "pack:nextfloor.fahrzeuge:bicycle": "Bicicleta", + "pack:nextfloor.fahrzeuge:ebike": "Bicicleta eléctrica", + "pack:nextfloor.fahrzeuge:motorbike": "Moto", + "pack:nextfloor.fahrzeuge:trailer": "Remolque", + "pack:nextfloor.fahrzeuge:sedan": "Berlina", + "pack:nextfloor.fahrzeuge:coupe": "Coupé deportivo", + "pack:nextfloor.fahrzeuge:convertible": "Descapotable (abierto)", + "pack:nextfloor.fahrzeuge:small_ev": "Eléctrico pequeño", + "pack:nextfloor.fahrzeuge:suv": "SUV", + "pack:nextfloor.fahrzeuge:family_van": "Monovolumen", + "pack:nextfloor.fahrzeuge:minibus": "Minibús", + "pack:nextfloor.fahrzeuge:panel_van": "Furgón", + "pack:nextfloor.fahrzeuge:pickup": "Pickup", + "pack:nextfloor.fahrzeuge:campervan": "Camper (techo elevable)", + "pack:nextfloor.fahrzeuge:motorhome": "Autocaravana", + "pack:nextfloor.fahrzeuge:caravan": "Caravana", + "packname:nextfloor.fitness": "Fitness (anterior)", + "pack:nextfloor.fitness:treadmill": "Cinta de correr", + "pack:nextfloor.fitness:bike_trainer": "Bicicleta estática", + "pack:nextfloor.fitness:rower": "Máquina de remo", + "pack:nextfloor.fitness:weight_bench": "Banco de pesas", + "pack:nextfloor.fitness:power_rack": "Rack de potencia", + "pack:nextfloor.fitness:yoga_mat": "Esterilla de yoga", + "pack:nextfloor.fitness:dumbbell_rack": "Soporte de mancuernas", + "packname:nextfloor.garten": "Jardín y terraza (anterior)", + "pack:nextfloor.garten:sun_lounger": "Tumbona", + "pack:nextfloor.garten:garden_table": "Mesa de jardín", + "pack:nextfloor.garten:garden_chair": "Silla de jardín", + "pack:nextfloor.garten:lounge_set": "Lounge exterior", + "pack:nextfloor.garten:parasol": "Sombrilla", + "pack:nextfloor.garten:gas_grill": "Barbacoa de gas", + "pack:nextfloor.garten:fire_bowl": "Brasero", + "pack:nextfloor.garten:pool": "Piscina", + "pack:nextfloor.garten:hot_tub": "Jacuzzi", + "pack:nextfloor.garten:trampoline": "Cama elástica", + "pack:nextfloor.garten:greenhouse": "Invernadero", + "pack:nextfloor.garten:raised_bed": "Bancal elevado", + "pack:nextfloor.garten:garden_shed": "Caseta de jardín", + "pack:nextfloor.garten:swing_bench": "Columpio de porche", + "pack:nextfloor.garten:mower_robot": "Robot cortacésped", + "pack:nextfloor.garten:tree_oak": "Árbol de hoja caduca", + "pack:nextfloor.garten:tree_birch": "Abedul", + "pack:nextfloor.garten:tree_fruit": "Árbol frutal", + "pack:nextfloor.garten:conifer": "Conífera", + "pack:nextfloor.garten:shrub": "Arbusto", + "pack:nextfloor.garten:shrub_flowering": "Arbusto con flores", + "pack:nextfloor.garten:hedge": "Seto", + "pack:nextfloor.garten:lawn_brush": "Maleza", + "pack:nextfloor.garten:bike_rack": "Aparcabicis", + "pack:nextfloor.garten:bin_box": "Cubrecontenedores (4 cubos)", + "packname:nextfloor.ikea": "Medidas IKEA", + "pack:nextfloor.ikea:billy": "Librería 80x202 (tamaño Billy)", + "pack:nextfloor.ikea:billy_low": "Librería 80x106 (tamaño Billy)", + "pack:nextfloor.ikea:kallax_2x2": "Estantería de cubos 2x2 (tamaño Kallax)", + "pack:nextfloor.ikea:kallax_2x4": "Estantería de cubos 2x4 (tamaño Kallax)", + "pack:nextfloor.ikea:kallax_4x4": "Estantería de cubos 4x4 (tamaño Kallax)", + "pack:nextfloor.ikea:lack_side": "Mesa auxiliar 55x55 (tamaño Lack)", + "pack:nextfloor.ikea:lack_coffee": "Mesa de centro 90x55 (tamaño Lack)", + "pack:nextfloor.ikea:malm_bed_140": "Cama 140x200 (tamaño Malm)", + "pack:nextfloor.ikea:malm_bed_160": "Cama 160x200 (tamaño Malm)", + "pack:nextfloor.ikea:malm_chest_6": "Cómoda de 6 cajones (tamaño Malm)", + "pack:nextfloor.ikea:malm_chest_4": "Cómoda de 4 cajones (tamaño Malm)", + "pack:nextfloor.ikea:pax_100": "Armario 100x236 (tamaño Pax)", + "pack:nextfloor.ikea:pax_150": "Armario 150x236 (tamaño Pax)", + "pack:nextfloor.ikea:poang": "Sillón (tamaño Poäng)", + "pack:nextfloor.ikea:ektorp_2": "Sofá de 2 plazas (tamaño Ektorp)", + "pack:nextfloor.ikea:ektorp_3": "Sofá de 3 plazas (tamaño Ektorp)", + "pack:nextfloor.ikea:bekant": "Escritorio 160x80 (tamaño Bekant)", + "pack:nextfloor.ikea:alex": "Cajonera (tamaño Alex)", + "pack:nextfloor.ikea:besta_tv": "Mueble de TV 180x42 (tamaño Bestå)", + "pack:nextfloor.ikea:ivar": "Estantería de pino 89x179 (tamaño Ivar)", + "packname:nextfloor.kino": "Cine en casa y gaming", + "pack:nextfloor.kino:projection_screen": "Pantalla de proyección", + "pack:nextfloor.kino:projector": "Proyector", + "pack:nextfloor.kino:floor_speaker": "Altavoz de suelo", + "pack:nextfloor.kino:subwoofer": "Subwoofer", + "pack:nextfloor.kino:soundbar": "Barra de sonido", + "pack:nextfloor.kino:gaming_desk": "Escritorio gaming", + "pack:nextfloor.kino:gaming_chair": "Silla gaming", + "pack:nextfloor.kino:game_console": "Videoconsola", + "pack:nextfloor.kino:arcade": "Máquina arcade", + "pack:nextfloor.kino:media_wall": "Pared multimedia con TV", + "pack:nextfloor.kino:media_rack": "Rack multimedia", + "packname:nextfloor.kueche": "Cocina extra", + "pack:nextfloor.kueche:coffee_machine": "Cafetera", + "pack:nextfloor.kueche:microwave": "Microondas", + "pack:nextfloor.kueche:hood_island": "Campana de isla", + "pack:nextfloor.kueche:wine_fridge": "Vinoteca", + "pack:nextfloor.kueche:stand_mixer": "Batidora amasadora", + "pack:nextfloor.kueche:toaster": "Tostadora", + "pack:nextfloor.kueche:kettle": "Hervidor", + "pack:nextfloor.kueche:long_dining_table": "Mesa de comedor larga", + "pack:nextfloor.kueche:bar_cart": "Carrito de bar", + "pack:nextfloor.kueche:trash_station": "Separación de residuos", + "packname:nextfloor.schlafen": "Dormir y niños", + "pack:nextfloor.schlafen:boxspring": "Cama box spring", + "pack:nextfloor.schlafen:baby_crib": "Cuna", + "pack:nextfloor.schlafen:changing_table": "Cambiador", + "pack:nextfloor.schlafen:vanity_table": "Tocador", + "pack:nextfloor.schlafen:clothes_rail": "Burro para ropa", + "pack:nextfloor.schlafen:loft_bed_desk": "Cama alta con escritorio", + "pack:nextfloor.schlafen:toy_box": "Baúl de juguetes", + "packname:nextfloor.technik": "Oficina y homelab", + "pack:nextfloor.technik:standing_desk": "Escritorio elevable", + "pack:nextfloor.technik:server_rack": "Rack de servidores (19 pulgadas)", + "pack:nextfloor.technik:nas": "NAS", + "pack:nextfloor.technik:printer_3d": "Impresora 3D", + "pack:nextfloor.technik:office_printer": "Impresora", + "pack:nextfloor.technik:router": "Router / punto de acceso", + "pack:nextfloor.technik:tower_pc": "PC torre", + "pack:nextfloor.technik:filing_cabinet": "Cajonera con ruedas", + "packname:nextfloor.treppen": "Escaleras y barandillas", + "pack:nextfloor.treppen:stairs_straight": "Escalera recta", + "pack:nextfloor.treppen:stairs_l": "Escalera en L con rellano", + "pack:nextfloor.treppen:stairs_u": "Escalera en U", + "pack:nextfloor.treppen:stairs_spiral": "Escalera de caracol", + "pack:nextfloor.treppen:stairs_compact": "Escalera de ahorro de espacio", + "pack:nextfloor.treppen:landing": "Rellano", + "pack:nextfloor.treppen:steps_outdoor": "Escalones exteriores", + "pack:nextfloor.treppen:rail_metal": "Barandilla metálica", + "pack:nextfloor.treppen:rail_glass": "Barandilla de cristal", + "pack:nextfloor.treppen:rail_wood": "Barandilla de madera", + "pack:nextfloor.treppen:stairs_floating": "Escalera volada", + "pack:nextfloor.treppen:stairs_u_winder": "Escalera en U abierta con peldaños compensados", + "pack:nextfloor.treppen:rail_corner": "Barandilla de esquina", + "packname:nextfloor.werkstatt": "Garaje y taller", + "pack:nextfloor.werkstatt:workbench": "Banco de trabajo", + "pack:nextfloor.werkstatt:tool_cabinet": "Armario de herramientas", + "pack:nextfloor.werkstatt:tool_chest": "Carro de herramientas", + "pack:nextfloor.werkstatt:shelf_rack": "Estantería de almacenaje", + "pack:nextfloor.werkstatt:tyre_stack": "Pila de neumáticos", + "pack:nextfloor.werkstatt:drill_press": "Taladro de columna", + "pack:nextfloor.werkstatt:compressor": "Compresor de aire", + "pack:nextfloor.werkstatt:bike_stand": "Soporte de bicicleta", + "pack:nextfloor.werkstatt:paint_cabinet": "Armario de pinturas", + "pack:nextfloor.werkstatt:tool_wall": "Panel de herramientas", + "pack:nextfloor.werkstatt:heavy_shelf": "Estantería de carga pesada", + "pack:nextfloor.werkstatt:chest_freezer_garage": "Arcón congelador", + "pack:nextfloor.werkstatt:tyre_rack": "Soporte de neumáticos", + "pack:nextfloor.werkstatt:lawn_mower": "Cortacésped", + "pack:nextfloor.werkstatt:bike_stand_2": "Soporte con 2 bicicletas", + "pack:nextfloor.werkstatt:workshop_light": "Lámpara de taller", + "pack:nextfloor.werkstatt:garage_opener": "Motor de puerta de garaje", + "pack:nextfloor.werkstatt:wallbox_holder": "Wallbox con soporte de cable", + "pack:nextfloor.werkstatt:wall_bike_holder": "Soporte de pared para bicis (2)", + "pack:nextfloor.werkstatt:workshop_vacuum": "Aspirador de taller", + "pack:nextfloor.werkstatt:workshop_cabinet": "Armario de taller", + "pack:nextfloor.werkstatt:printer_enclosed": "Impresora 3D cerrada", + "packname:nextfloor.wohnen": "Vivir y mascotas", + "pack:nextfloor.wohnen:corner_sofa": "Sofá rinconera (en L)", + "pack:nextfloor.wohnen:bean_bag": "Puf saco", + "pack:nextfloor.wohnen:fireplace": "Chimenea", + "pack:nextfloor.wohnen:bookcase_wall": "Librería de pared", + "pack:nextfloor.wohnen:piano": "Piano vertical", + "pack:nextfloor.wohnen:aquarium": "Acuario", + "pack:nextfloor.wohnen:cat_tree": "Árbol para gatos", + "pack:nextfloor.wohnen:dog_bed": "Cama para perros", + "pack:nextfloor.wohnen:hanging_chair": "Silla colgante", + "pack:nextfloor.wohnen:display_cabinet": "Vitrina", + "pack:nextfloor.wohnen:high_table": "Mesa de bar", + "pack:nextfloor.wohnen:floor_mirror": "Espejo de pie", + "furn_tap": "Tocar el elemento", + "furn_tap_default": "Como siempre", + "furn_tap_hint": "Una acción propia como los botones propios del menú de estrella, p. ej. una ventana emergente de browser_mod con tu tarjeta.", + "furn_show_when": "Mostrar solo mientras …", + "furn_show_when_state": "… está en el estado (vacío = encendido)", + "furn_show_when_invert": "Al revés: mostrar mientras no lo esté", + "furn_show_when_hint": "Decoración de temporada que solo está en diciembre: un ayudante (input_boolean), un calendario o un sensor decide si el objeto aparece en 3D. Separa varios estados con comas. El editor siempre lo muestra.", + "picture_upload": "Subir una foto", + "picture_replace": "Subir otra foto", + "picture_stored": "Hay una foto propia guardada.", + "picture_url": "… o dirección de la imagen", + "picture_entity": "… o la imagen de una entidad", + "picture_border": "Paspartú (%)", + "picture_fit": "Foto", + "picture_fit_cover": "llena el marco", + "picture_fit_contain": "se ve entera", + "picture_hint": "Tu foto en el marco, en 3D y en la tableta de pared. Las fotos subidas se guardan con el plano en tamaño reducido; una entidad de imagen (foto del día) o una cámara muestra su imagen actual.", + "card_tap_in_room": "Activar dispositivos solo en la habitación abierta", + "card_tap_in_room_hint": "En la vista de la casa y de la planta, un toque abre la planta o la habitación, también sobre un dispositivo o su icono. En la habitación abierta activa el dispositivo. Una pulsación larga siempre abre su menú o sus detalles.", + "card_markers_outside": "Elegir los iconos fuera de la habitación abierta", + "card_markers_outside_hint": "En la casa, en la planta y en las otras habitaciones solo los tipos marcados; en la habitación abierta todos, como arriba. \"Siempre\" y \"Nunca\" del dispositivo tienen prioridad.", + "marker_kind_light": "Luces", + "marker_kind_cover": "Persianas", + "marker_kind_climate": "Calefacción", + "marker_kind_media": "Multimedia", + "marker_kind_switch": "Interruptores", + "marker_kind_fan": "Ventiladores", + "marker_kind_lock": "Cerraduras", + "marker_kind_binary": "Contactos y detectores", + "marker_kind_sensor": "Sensores", + "marker_kind_tap": "Muebles con acción", + "marker_kind_other": "Otros", + "floor_copy": "Duplicar planta", + "floor_copy_hint": "La copia va encima de la casa con todas las habitaciones, paredes, puertas y ventanas. Las habitaciones y la planta pierden su enlace con Home Assistant, los muebles sus entidades; los equipos de energía se quedan en la planta antigua.", + "floor_copy_furniture": "Copiar los muebles", + "floor_copy_devices": "Copiar los marcadores de dispositivos", + "floor_copy_devices_hint": "La misma entidad aparecerá entonces en ambas plantas.", + "floor_copy_outdoor": "Copiar las zonas exteriores", + "floor_copy_make": "Crear la copia", + "floor_copy_name": "{name} (copia)", + "furn_to_floor": "Mover a la planta", + "furn_to_floor_hint": "El mueble pasa al mismo sitio en la planta elegida.", + "arc": "Arco", + "arc_hint": "Curva la pared en arco. Una habitación que comparte la pared se curva con ella, puertas y ventanas la siguen; Deshacer quita el arco.", + "arc_bulge": "Curvatura (m)", + "arc_bulge_hint": "Cuánto se curva el centro de la pared: positivo hacia fuera, negativo hacia la estancia.", + "arc_apply": "Curvar", + "arc_too_wide": "Una puerta o ventana de esta pared es demasiado ancha para esta curva. Haz la curva más plana o la abertura más estrecha.", + "time_of_day": "Hora del día", + "time_of_day_hint": "Muestra sol, luz, sombras y aspecto a otra hora de hoy. Toca de nuevo para volver a ahora.", + "menu_open": "Menú abierto", + "menu_open_hint": "El menú estrella con favoritos y botones propios está abierto desde el inicio en este dispositivo, un tamaño más grande – para una tableta de pared que sobre todo activa escenas.", + "keep_camera": "Mantener cámara", + "keep_camera_hint": "Al cambiar de planta, la cámara mantiene el mismo lado, altura y distancia en lugar de encuadrar la nueva planta desde el lado inicial.", + "view_zoom": "Zoom", + "view_zoom_hint": "Lo cerca que llegan las vistas encuadradas – en tabletas pequeñas la casa se ve más grande.", + "stair_shape": "Forma", + "stair_shape_straight": "Recta", + "stair_shape_quarter": "Cuarto de vuelta (compensada)", + "stair_shape_l": "En L con rellano", + "stair_shape_half": "Media vuelta (compensada)", + "stair_shape_u": "En U con rellano", + "stair_shape_spiral": "De caracol", + "stair_turn": "Sentido de giro (al subir)", + "stair_turn_left": "Hacia la izquierda", + "stair_turn_right": "Hacia la derecha", + "stair_build": "Construcción", + "stair_build_solid": "Maciza (hormigón)", + "stair_build_stringer": "Con zancas", + "stair_build_mono": "Zanca central", + "stair_build_cantilever": "Voladizas (flotantes)", + "stair_risers": "Tabicas", + "stair_steps": "Peldaños (número)", + "stair_run_width": "Ancho de tramo (m)", + "stair_landing_after": "Peldaños hasta el descansillo", + "stair_landing_hint": "El descansillo está a {h} cm del suelo; el resto de peldaños viene después.", + "stair_rail": "Barandilla", + "stair_rail_none": "Ninguna", + "stair_rail_left": "Izquierda", + "stair_rail_right": "Derecha", + "stair_rail_both": "Ambos lados", + "stair_down": "Baja", + "stair_down_hint": "La escalera empieza en esta planta y baja, por ejemplo a un sótano que no hace falta dibujar. Abre el suelo de esta planta.", + "stair_measures": "{steps} peldaños de {rise} cm · huella {going} cm · paso {measure} cm", + "stair_uncomfortable": "incómoda (paso 59–65 cm, contrahuella máx. 21 cm)", + "stair_up_note": "La escalera empieza en el borde delantero marcado. El suelo de arriba solo se abre donde quedan menos de 2,2 m de altura libre sobre los peldaños.", + "stair_down_note": "Se entra en la escalera por el borde delantero marcado y se baja. El plano la dibuja discontinua; esta planta se abre sobre los peldaños.", + "stair_upgrade": "Elegir la forma", + "stair_upgrade_hint": "La convierte en una escalera con forma (compensada, L, U, caracol), construcción, barandilla y número de peldaños.", + "tool_stairs": "Escalera", + "hint_stairs": "Arrastra donde debe ir la escalera – sigue el lado largo; después ajusta forma, giro y construcción a la derecha", + "stair_opening": "Hueco en el forjado", + "stair_opening_headroom": "Según la altura libre (solo donde haga falta)", + "stair_opening_full": "Sobre toda la escalera", + "stair_opening_none": "Ninguno (trampilla, caja cerrada)", + "stair_opening_hint": "Cuánto abre la escalera el suelo al que llega: la planta de arriba, o la propia si baja. Según la altura libre solo abre sobre los peldaños con menos de 2,2 m.", + "stair_up_note_plain": "La escalera empieza en el borde delantero marcado y sube hacia atrás." +} diff --git a/custom_components/nextfloor/frontend/lang/fi.json b/custom_components/nextfloor/frontend/lang/fi.json new file mode 100644 index 0000000..b222ff8 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/fi.json @@ -0,0 +1,153 @@ +{ + "accent": "Korostusväri", + "accent_reset": "Takaisin syaaniin", + "alert_alarm_by": "Hälytyksen laukaisi {cause}", + "all_floors": "Kaikki kerrokset", + "all_off_done": "Kaikki pois päältä.", + "all_off_floor": "Kaikki pois päältä: {floor} ({n} laitetta), kumoa kymmenen sekuntia", + "all_off_n": "Kaikki pois ({n})", + "all_off_undo": "Kumoa", + "announce_failed": "Ilmoitus epäonnistui: {error}", + "announce_on": "Ilmoitukset tällä näytöllä ovat päällä", + "announce_placeholder": "Oma viestisi …", + "announce_send": "Sano se", + "announce_sent": "Sanottu: \"{message}\"", + "back": "Takaisin", + "bars_fold": "Piilota kytkimet", + "bars_unfold": "Kytkimet", + "battery_low_n": "Akku vähissä: {names}", + "brightness": "Kirkkaus", + "card_description": "Kotisi 3D:nä (neon).", + "card_floor_stack": "Alla olevat kerrokset", + "card_room_buttons": "Huonepainikkeet", + "care_bin_days": "{n} päivän päästä", + "care_bin_today": "Tyhjennetään tänään", + "care_bin_tomorrow": "Tyhjennetään huomenna", + "care_time_left": "{time} jäljellä", + "central": "Keskus: kaikki valot, jalousiet ja suosikit", + "central_covers": "Jalousiet", + "central_favorites": "Suosikit", + "central_house": "Koko talo", + "central_lights": "Valot", + "central_sure": "Varmasti?", + "clock": "Kello", + "close": "Sulje", + "color": "Väri", + "color_temp": "Värilämpötila", + "comfort_n": "Mukavuus {n}", + "confirm_switch": "Vaihdetaanko varmasti {name}?", + "cover_close": "Sulje", + "cover_my_go": "Suosikkiasentoon ({p} %)", + "cover_open": "Avaa", + "cover_stop": "Pysäytä", + "cover_tilt": "Lamellit", + "cover_tilt_close": "Lamellit kiinni", + "cover_tilt_open": "Lamellit auki", + "delete": "Poista", + "details": "Tiedot", + "draft_discard": "Hylkää", + "draft_found": "Tallentamattomia muutoksia löytyi kohdasta {time}.", + "draft_restore": "Palauta ja tallenna", + "empty_lights_hint": "{n} valoa päällä, ei ketään paikalla {min} min.", + "empty_lights_off": "Sammuta valot", + "energy_battery": "Akku", + "energy_consumption": "Kulutus", + "energy_rest": "Yhteinen (loput)", + "energy_solar": "Aurinko", + "energy_tariff": "Hinnasto", + "ext_tab": "Laajennukset", + "find": "Etsi", + "find_none": "Ei tuloksia", + "find_placeholder": "Missä on …? Laite tai huone", + "floor_layer": "Taso (voi näyttää ja piilottaa)", + "floor_power_share": "{n} % talosta", + "floor_rooms": "{n} huonetta", + "floor_rooms_one": "1 huone", + "floors": "Kerrokset", + "floors_apart": "Erillään", + "floors_stacked": "Päällekkäin", + "flows": "Sähkövirta", + "fps_title": "Suorituskykynäyttö (kuvaa sekunnissa)", + "glass_walls": "Lasiseinät", + "heat_none_found": "Sopivia antureita ei löytynyt huoneiden alueilta.", + "heat_wifi": "Wi-Fi", + "heatmap": "Lämpökartta", + "holos": "Kortit", + "keep_camera": "Säilytä kamera", + "load_error": "Lataus epäonnistui", + "loading": "Ladataan …", + "markers": "Merkit", + "media_next": "Seuraava", + "media_previous": "Edellinen", + "media_sources": "Lähteet", + "media_volume": "Äänenvoimakkuus", + "menu_open": "Valikko auki", + "meter_unmetered": "{w} mittaamatta", + "mood_carry": "Siirrä toiseen huoneeseen", + "mood_new": "Tunnelma", + "mood_save": "Tallenna tunnelma", + "mood_set": "Käytä tätä tunnelmaa", + "next": "Seuraava", + "no_building": "Ei pohjapiirrosta vielä.", + "open_editor": "Avaa editori", + "open_heating_hint": "{n} ikkunaa auki lämmityksen ollessa päällä.", + "open_heating_off": "Sammuta lämmitys", + "open_since": "auki {time}", + "outside_area": "Ulkona", + "panel_all_close": "Kaikki alas", + "panel_all_off": "Kaikki pois", + "panel_all_on": "Kaikki päälle", + "panel_all_open": "Kaikki ylös", + "panel_less": "Näytä vähemmän", + "panel_more": "Lisää alueen laitteita ({n})", + "plain": "Vain pohjapiirros", + "play_pause": "Toista/tauko", + "pool_pump_on": "pumppu päällä", + "position": "Asento", + "presence_last": "nähty viimeksi {time} sitten", + "presence_now": "joku on täällä", + "presets": "Kanavat ja soittolistat (ääni)", + "previous": "Edellinen", + "qm_off": "Pois", + "readable": "Helppolukuinen", + "reload_page": "Lataa uudelleen", + "right_back": "Oikea napsautus = takaisin", + "roof_keep": "Katto pysyy", + "room_clean_run": "Imuroi", + "room_clean_run_hint": "Lähettää robotti-imurin tähän huoneeseen.", + "room_curve_hint": "Huoneen lämpötila viimeisen 24 tunnin ajalta", + "room_energy": "tänään {today} · kuukausi {month}", + "room_sun_hours": "{h} h aurinkoa tänään ({facing})", + "room_sun_year": "Aurinko vuoden aikana", + "save_failed_detail": "Tallennus epäonnistui: {error}. Muutokset säilyvät tässä selaimessa.", + "screen_name": "Tämän näytön nimi", + "shade_close": "Laske", + "shade_hint": "Aurinko paistaa {n} ikkunaan, {temp} – lasketaanko jalousiet?", + "stats_idle": "Lepotilassa (0 fps)", + "stl": "3D-tulostus (STL)", + "swipe_off": "Pois", + "target_temp": "Tavoite", + "temp_down": "Viileämpää", + "temp_up": "Lämpimämpää", + "time_of_day": "Vuorokaudenaika", + "today": "Tänään", + "today_none": "Ei mitään tänään.", + "travel": "Aikamatka: toista viimeiset 24 tuntia tai 7 päivää", + "travel_days": "päivää", + "travel_failed": "Historiaa ei voitu ladata.", + "travel_live": "Livenä", + "travel_loading": "Ladataan historiaa …", + "travel_speed": "Nopeus", + "view_options": "Näkymä: laatu, ulkoasu, merkit, FPS", + "view_zoom": "Zoom", + "volume": "Äänenvoimakkuus", + "wallbox_charging": "lataa", + "wallbox_plugged": "kytketty", + "walls_auto": "Korkeat seinät", + "walls_cut": "Leikkaus", + "walls_slope": "Viistetty", + "walls_solid": "Umpinaiset", + "wifi_aps": "{n} tukiasemaa · {clients} laitetta", + "wifi_clients": "{n} laitetta", + "wifi_network": "Verkko: {online} verkossa · {offline} ei yhteyttä" +} diff --git a/custom_components/nextfloor/frontend/lang/fr.json b/custom_components/nextfloor/frontend/lang/fr.json new file mode 100644 index 0000000..7b60fb4 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/fr.json @@ -0,0 +1,2763 @@ +{ + "view": "3D", + "editor": "Éditeur", + "all_floors": "Tous les étages", + "outside_area": "Extérieur", + "outside_area_hint": "Tous les appareils dehors en un coup d'œil : au jardin, hors des pièces, et ce qui appartient à l'extérieur (une station météo sur le toit, par exemple).", + "device_outside": "Appartient à l'extérieur", + "device_outside_hint": "L'appareil ne compte pas pour la pièce en dessous (une station météo sur le toit) et figure dans le panneau Extérieur.", + "no_building": "Aucun plan pour le moment.", + "no_building_admin": "Aucun plan pour le moment. Dessinez votre premier étage dans l'éditeur.", + "no_rooms_admin": "Les étages existent, mais il n’y a pas encore de pièce. Les murs seuls ne suffisent pas : dessinez au moins une pièce dans l’éditeur avec « Rectangle » ou « Forme libre ».", + "open_editor": "Ouvrir l'éditeur", + "loading": "Chargement …", + "load_error": "Échec du chargement", + "saving": "Enregistrement …", + "saved": "Enregistré", + "save_error": "Échec de l'enregistrement", + "save_failed_detail": "Échec de l'enregistrement : {error}. Vos modifications sont conservées dans ce navigateur.", + "needs_restart": "Une nouvelle version de NextFloor ({frontend}) est installée, mais Home Assistant exécute encore la {version}. Veuillez redémarrer Home Assistant – d'ici là, l'enregistrement peut échouer.", + "needs_reload": "Cette page affiche encore NextFloor {frontend}, alors que Home Assistant est déjà en {backend}. Veuillez recharger la page ; dans l'application Companion : Paramètres → Application Companion → Réinitialiser le cache du frontend.", + "reload_page": "Recharger", + "needs_restart_old": "Une nouvelle version de NextFloor est installée, mais Home Assistant exécute encore une version plus ancienne. Veuillez redémarrer Home Assistant – d'ici là, l'enregistrement échoue.", + "draft_found": "Modifications non enregistrées de {time} trouvées.", + "draft_restore": "Restaurer et enregistrer", + "draft_discard": "Abandonner", + "walls_auto": "Murs hauts", + "walls_cut": "Coupe", + "reset_view": "Vue d'ensemble", + "back": "Retour", + "floor": "Étage", + "floors": "Étages", + "add_floor": "Ajouter un étage", + "floor_from_ha": "Étages de Home Assistant :", + "floor_empty": "Étage vide", + "level": "Niveau {n}", + "ha_floor": "Étage dans Home Assistant", + "floor_layer": "Calque (affichable et masquable)", + "floor_power": "Compteur de l'étage (puissance)", + "floor_power_hint": "Un capteur de puissance pour cet étage seul (un sous-compteur, un appartement). Sa valeur s'affiche sur l'étiquette de l'étage et, dans la vue de cet étage, sur la carte de la maison avec sa part de la consommation.", + "floor_power_share": "{n} % de la maison", + "living_area": "Surface habitable {living}", + "room_living": "Compte dans la surface habitable", + "living_area_none": "Pas de surface habitable · sol {floor}", + "living_area_low": "Surface habitable {living} (sol {floor}, dont {low} sous 2 m)", + "living_area_hint": "Calculé comme la Wohnflächenverordnung allemande : le sol à l'intérieur des murs, en entier dès 2 m de hauteur libre, à moitié entre 1 et 2 m (sous les pentes), pas du tout sous 1 m. Une valeur indicative, pas un métrage.", + "living_area_floor": "Surface habitable : {floor}", + "living_area_floor_house": "Surface habitable de cet étage : {floor} · toute la maison : {house}", + "print_plan": "Imprimer le plan / PDF", + "print_plan_hint": "Chaque étage en plan net avec cotes et surfaces, plus un tableau des surfaces – à imprimer ou à enregistrer en PDF depuis la boîte d'impression.", + "print_title": "Plan", + "print_room": "Pièce", + "print_floor_area": "Surface au sol", + "print_living": "Surface habitable", + "print_low": "sous 2 m", + "print_total": "Total", + "print_blocked": "La fenêtre d'impression a été bloquée – autorise les fenêtres pop-up pour Home Assistant.", + "check_open": "Vérifier le plan", + "note": "Note", + "note_add": "Note ici", + "note_text": "Texte", + "note_placeholder": "p. ex. « changer le filtre » ou « fusible 12 »", + "note_due": "À faire le", + "note_due_hint": "À partir de ce jour, l'épingle devient orange.", + "note_is_due": "Cette note est à faire.", + "keys_title": "Touches de l'éditeur", + "keys_undo": "Annuler", + "keys_redo": "Rétablir", + "keys_duplicate": "Dupliquer la pièce", + "keys_delete": "Supprimer la sélection", + "keys_nudge": "Déplacer la sélection d'un pas de grille", + "keys_nudge_10": "… de 10 cm", + "keys_nudge_1": "… de 1 cm", + "keys_rotate": "Tourner le meuble de 90° (Maj : en arrière)", + "keys_lock": "Fixer ou libérer un meuble, un appareil ou une section de toit", + "keys_close_shape": "Fermer la forme libre", + "keys_escape": "Annuler, quitter l'outil, désélectionner", + "keys_straight": "En dessinant : lignes droites", + "keys_sheet": "Cet aperçu", + "tour_title": "Premiers pas", + "tour_1_title": "Dessiner les pièces", + "tour_1": "Dessine les pièces avec « {rect} » ou « {free} » ; les murs viennent tout seuls. Donne à chaque pièce sa pièce Home Assistant – NextFloor trouve alors ses appareils. Si tes pièces existent déjà, « {rooms} » dans le formulaire d'étage les crée d'un coup.", + "tour_2_title": "Portes et fenêtres", + "tour_2": "« {opening} » les place sur un mur. Lie leur contact ou leur volet – en 3D ils s'ouvrent et se ferment avec, et les fenêtres ouvertes te préviennent.", + "tour_3_title": "Meubles et appareils", + "tour_3": "« {furniture} » ouvre la bibliothèque – ou crée tes propres pièces dans l'🛠️ atelier. Choisis une pièce : ses appareils sont listés dessous, prêts à placer ; les lampes brillent alors de la couleur de leur lumière.", + "tour_4_title": "Regarder et vérifier", + "tour_4": "« {split} » montre ta maison pendant que tu dessines ; en haut tu passes à la vue 3D. « {check} » liste ce qui manque encore – et ? montre les touches à tout moment.", + "tour_next": "Suivant", + "tour_back": "Retour", + "tour_done": "C'est parti", + "tour_skip": "Passer", + "check_open_hint": "Liste ce qui manque ou cloche dans le plan, avec une correction en un geste.", + "check_title": "Vérification du plan", + "check_all_good": "Tout est en ordre – rien trouvé.", + "check_hint": "{n} points trouvés. Les boutons bleus modifient le plan (annuler marche comme toujours), les autres montrent l'endroit.", + "check_room_no_area": "« {room} » n'a pas de pièce Home Assistant : ses appareils ne sont pas trouvés.", + "check_room_no_area_named": "« {room} » n'a pas de pièce – la pièce libre « {area} » porte le même nom.", + "check_areas_unplaced": "{n} pièces de cet étage n'ont pas encore de pièce dessinée : {names}", + "check_devices_unplaced": "« {room} » : {n} appareils de la pièce ne sont pas encore dans le plan.", + "check_rooms_overlap": "« {a} » et « {b} » se chevauchent.", + "check_opening_off_wall": "Une porte ou une fenêtre de « {room} » n'est sur aucun mur.", + "check_entity_missing": "{n} repères pointent vers des entités que Home Assistant ne connaît plus ({ids}).", + "check_furniture_entity_missing": "Un meuble est lié à {id} – cette entité n'existe plus.", + "check_battery_low": "Pile faible : {name} ({level} %)", + "battery_low_n": "Pile faible : {names}", + "check_standby": "{name} consomme {w} W éteint – environ {cost} par an.", + "check_fix_show": "Afficher", + "check_fix_set_area": "Lier « {area} »", + "check_fix_add_rooms": "Ajouter les pièces", + "check_fix_place": "Placer {n}", + "check_fix_remove": "Retirer {n}", + "floor_layer_hint": "Cet étage n'est pas un niveau mais un calque – tous les arbres ou la déco. La vue 3D affiche en haut un œil qui l'affiche ou le masque sur chaque appareil.", + "no_ha_floor": "– aucun –", + "area_rooms": "Ajouter des pièces depuis les zones HA ({n})", + "area_rooms_hint": "Ajoute une pièce (4 × 3 m) pour chaque zone de cet étage – placez-la ensuite par glisser-déposer et ajustez les coins", + "floor_name": "Nom", + "elevation": "Hauteur au-dessus du sol (m)", + "floor_shift": "Décaler l'étage (m)", + "floor_shift_apply": "Décaler", + "floor_shift_hint": "Déplace de X et Z toutes les pièces, tous les meubles, appareils, espaces extérieurs, murs libres et l'image de fond de cet étage. Les pans de toit restent en place.", + "height": "Hauteur sous plafond (m)", + "cut_height": "Hauteur de coupe (m)", + "delete_floor": "Supprimer l'étage", + "delete_floor_confirm": "Supprimer l'étage « {name} » avec toutes ses pièces ?", + "move_up": "Monter", + "move_down": "Descendre", + "default_floor": "Rez-de-chaussée", + "new_floor": "Étage {n}", + "tool_select": "Sélectionner", + "tool_rect": "Rectangle", + "tool_polygon": "Forme libre", + "undo": "Annuler", + "redo": "Rétablir", + "fit": "Tout afficher", + "room": "Pièce", + "rooms": "Pièces", + "room_name": "Nom", + "area": "Zone", + "no_area": "Aucune zone", + "sub_area_add": "+ Zone dans la pièce", + "sub_area_hint": "Une partie de la pièce avec sa propre pièce Home Assistant mais sans murs – un coin lecture, une étagère, une kitchenette dans le séjour. Ses appareils et capteurs appartiennent à cette pièce.", + "material": "Sol", + "x": "X (m)", + "z": "Y (m)", + "width": "Largeur (m)", + "depth": "Profondeur (m)", + "points": "Coins", + "delete_point": "Supprimer le coin", + "duplicate": "Dupliquer", + "delete": "Supprimer", + "new_room": "Pièce {n}", + "settings": "Paramètres", + "pendant_shape": "Forme", + "pendant_shade": "Abat-jour", + "paint_colour": "Couleur de peinture", + "pendant_globe": "Globe", + "pendant_cone": "Cône", + "pendant_drum": "Tambour", + "sofa_shape": "Forme", + "sofa_straight": "Droit", + "sofa_l": "En L (miroir : autre côté)", + "sofa_u": "En U", + "pkg_open": "Meubler …", + "pkg_hint": "Les meubles se placent contre les murs de la pièce ; les lampes sont liées aux lumières de la zone. Ajustez ensuite chaque élément – Ctrl+Z annule tout.", + "pkg_done": "{n} éléments placés – Ctrl+Z annule.", + "pkg_kitchen_row": "Cuisine linéaire", + "pkg_kitchen_row_desc": "Rangée sur le mur du fond avec réfrigérateur, four, évier, lave-vaisselle et cuisinière, placard mural, table à manger avec suspension", + "pkg_kitchen_l": "Cuisine en L", + "pkg_kitchen_l_desc": "Rangées au fond et à gauche, îlot de cuisine avec tabourets de bar", + "pkg_bath": "Salle de bain", + "pkg_bath_desc": "Lavabo, WC, baignoire, lave-linge, spot encastré", + "pkg_bedroom": "Chambre", + "pkg_bedroom_desc": "Lit double avec deux tables de chevet, armoire, commode, plafonnier", + "pkg_living": "Salon", + "pkg_living_desc": "Meuble TV, canapé, table basse, tapis, fauteuil, étagère, lampadaire, plante", + "pkg_dining": "Salle à manger", + "pkg_dining_desc": "Table avec quatre chaises, buffet, suspension", + "pkg_office": "Bureau", + "pkg_office_desc": "Bureau avec chaise de bureau, deux étagères, plafonnier", + "pkg_kids": "Chambre d'enfant", + "pkg_kids_desc": "Lit simple, bureau, étagère, tapis", + "pkg_hall": "Entrée", + "pkg_hall_desc": "Portemanteau, deux spots encastrés", + "spots_place": "Placer des spots", + "spots_type": "Lampe", + "spots_cols": "Colonnes (gauche–droite)", + "spots_rows": "Rangées (avant–arrière)", + "spots_add": "Placer {n} lampes", + "spots_placed": "{n} lampes placées.", + "spots_hint": "Toutes les lampes suivent la lumière choisie (p. ex. des spots sur un même variateur). Ensuite, chacune peut être déplacée et liée à une autre lumière comme n'importe quel meuble.", + "cancel": "Annuler", + "backup": "Sauvegarde", + "backup_history": "Points de restauration", + "share_view": "Partager une vue", + "share_view_hint": "Enregistre la maison dans un petit fichier qui s'ouvre dans n'importe quel navigateur sans Home Assistant (via la démo en ligne de NextFloor) – pour la montrer à la famille ou à un architecte. Sans appareils ni entités, comme un modèle.", + "share_view_title": "Notre maison dans NextFloor", + "share_view_needs_js": "Cette page a besoin de JavaScript et d'une connexion internet.", + "share_view_file": "vue", + "share_view_done": "Vue enregistrée – ouvre le fichier dans un navigateur ou transmets-le.", + "version_save": "Enregistrer cet état …", + "version_save_hint": "Garde le plan sous un nom (« avant les travaux »). Les états nommés restent quand les points automatiques disparaissent.", + "version_name_prompt": "Nom de cet état (p. ex. « avant les travaux ») :", + "version_saved": "État « {name} » enregistré.", + "version_compare": "Comparer", + "version_delete_confirm": "Supprimer « {name} » ?", + "version_same": "Aucune différence avec le plan.", + "version_diff_n": "{n} différences avec le plan actuel :", + "diff_floor_added": "Étage « {name} » ajouté", + "diff_floor_removed": "Étage « {name} » supprimé", + "diff_room_added": "Pièce « {name} » ajoutée", + "diff_room_removed": "Pièce « {name} » supprimée", + "diff_room_renamed": "« {detail} » s'appelle maintenant « {name} »", + "diff_room_reshaped": "« {name} » remodelée ({detail} m²)", + "diff_opening_added": "{name} ajouté(e) ({detail})", + "diff_opening_removed": "{name} supprimé(e) ({detail})", + "diff_furniture_added": "{name} ajouté", + "diff_furniture_removed": "{name} supprimé", + "diff_furniture_moved": "{name} déplacé ou modifié", + "diff_device_added": "Appareil {name} placé", + "diff_device_removed": "Appareil {name} retiré", + "diff_device_moved": "Appareil {name} déplacé", + "backup_none": "Aucun pour le moment. Pendant l'édition, un point de restauration est conservé toutes les 10 minutes au plus.", + "backup_summary": "{rooms} pièces, {furniture} meubles", + "backup_restore": "Restaurer", + "backup_restore_confirm": "Restaurer l'état de {time} ? L'état actuel est conservé comme point de restauration.", + "backup_restored": "Restauré.", + "backup_file": "Fichier", + "backup_export": "Exporter", + "backup_export_share": "Partager comme modèle", + "backup_export_share_hint": "Sans zones, appareils, capteurs ni images – pour le transmettre à d'autres.", + "backup_import": "Importer …", + "backup_import_confirm": "Remplacer tout le plan par le fichier ? L'état actuel est conservé comme point de restauration.", + "backup_import_error": "Le fichier n'est pas un plan NextFloor ({error}).", + "backup_imported": "Importé.", + "backup_hint": "Les images de fond ne font pas partie du fichier.", + "backup_full": "Sauvegarde complète", + "backup_full_export": "Tout sauvegarder (plan, images, packs)", + "backup_full_import": "Restaurer une sauvegarde complète …", + "backup_full_hint": "Un seul fichier avec le plan, toutes les images de fond et d'écran et les packs installés. À la restauration, chaque pack est vérifié à nouveau ; la clé de licence n'est pas incluse.", + "backup_full_confirm": "Remplacer le plan, les images et les packs par la sauvegarde ? L'état actuel est conservé comme point de restauration.", + "backup_full_not_backup": "Ce n'est pas une sauvegarde complète de NextFloor.", + "backup_full_restored": "Sauvegarde restaurée : {packs} packs, {pictures} images.", + "backup_full_skipped": "Ignorés (illisibles) : {packs}.", + "export_name_full": "complet", + "device_confirm": "Confirmer avant de commuter", + "device_confirm_hint": "Un appui en 3D, le menu rapide et le panneau de la pièce demandent d'abord confirmation. Un double appui sur la pièce exclut cet appareil.", + "cover_confirm_hint": "Ouvrir, fermer et les positions demandent d'abord confirmation dans le menu rapide et le panneau de la pièce, et un balayage sur le repère ne déplace plus le volet (il fait tourner la vue). Arrêter ne demande jamais confirmation.", + "blind_kind": "Type de store", + "blind_roller": "Volet roulant extérieur", + "blind_venetian": "Brise-soleil orientable", + "blind_inside": "Store intérieur", + "cover2_entity": "Deuxième volet (moitié droite)", + "cover_my": "Position favorite « My » (%, 0 = aucune)", + "cover_my_go": "Vers la position favorite ({p} %)", + "blind_hint": "Un brise-soleil orientable tourne ses lames en 3D selon l'inclinaison du volet ; un store intérieur pend derrière la vitre. Une grande fenêtre peut avoir un deuxième volet pour sa moitié droite. La position favorite apparaît comme « My » dans le menu rapide : un volet à positions s'y rend, un moteur Somfy RTS sans retour va à son propre My avec Stop.", + "confirm_switch": "Vraiment commuter {name} ?", + "lock_confirm_unlock": "Vraiment déverrouiller {name} ?", + "gang_switch_one": "Commande", + "furn_cover_entity": "Suit", + "furn_cover_hint": "Le rideau, le store, l'auvent ou le portail suit cette entité de type volet (volet roulant, rideau, store banne, portail) et se déplace avec elle. Un appui ouvre son menu (ouvrir, stop, fermer).", + "furn_cover_inverted": "Inverser le sens", + "furn_cover_inverted_hint": "Pour un store ou un rideau qui bouge à l’envers sur le plan : sorti s’affiche rentré, et inversement.", + "gang_switch": "Le bouton {n} commande", + "gang_socket_one": "Prise alimentée par", + "gang_socket": "Prise {n} alimentée par", + "gang_switch_hint": "Un bouton s'éclaire tant que sa lumière est allumée (dans sa couleur). Un appui la bascule ; avec plusieurs boutons, un petit menu demande lequel. La même entité peut être sur plusieurs interrupteurs.", + "gang_socket_hint": "Une prise s'éclaire en vert tant que son interrupteur est allumé – d'autant plus qu'elle consomme. Un appui la bascule ; avec plusieurs prises, un petit menu demande laquelle.", + "lock_confirm_lock": "Verrouiller {name} ?", + "opening_lock": "Serrure connectée", + "opening_lock_hint": "Un appui sur la porte la verrouille ou la déverrouille (toujours après confirmation). Tant qu'elle est déverrouillée, son contour s'éclaire.", + "split_handle_hint": "Glisser : largeur du plan et de la vue 3D", + "wall_exterior": "Mur extérieur (m)", + "wall_interior": "Mur intérieur (m)", + "grid": "Grille (m)", + "background": "Calque (image du plan)", + "background_upload": "Choisir une image …", + "background_width": "Largeur dans le plan (m)", + "background_opacity": "Opacité", + "background_rotation": "Rotation (°)", + "background_edit": "Déplacer, mettre à l'échelle et pivoter", + "background_edit_done": "Terminé", + "background_edit_hint": "Mode activé : faire glisser l'image la déplace, la poignée en bas à droite la met à l'échelle. Ajustez d'abord l'échelle de l'image, puis faites-la pivoter.", + "background_remove": "Supprimer le calque", + "hint_select": "Touchez une pièce pour la sélectionner · faites glisser les coins · « + » sur un bord insère un coin · les flèches déplacent · Suppr supprime · Ctrl+Z", + "hint_rect": "Faites glisser pour dessiner un rectangle", + "hint_polygon": "Placez les coins · touchez le premier coin ou appuyez sur Entrée pour fermer · Esc annule", + "hint_empty": "Ajoutez d'abord un étage.", + "area_m2": "{a} m²", + "overlap_warning": "Des pièces se chevauchent – les murs y sont incomplets.", + "read_only": "Seuls les administrateurs peuvent modifier le plan.", + "side_failed": "Ce formulaire n'a pas pu s'afficher ({error}). Le plan reste utilisable. Merci de signaler ce texte dans une issue GitHub.", + "mat_wood": "Bois", + "mat_oak": "Chêne", + "mat_tiles": "Carrelage", + "mat_carpet": "Moquette", + "mat_stone": "Pierre", + "mat_concrete": "Béton", + "card_name": "NextFloor", + "card_description": "Votre maison en 3D (néon).", + "stats": "{calls} appels de rendu · {tris} triangles", + "stats_fps": "{fps} i/s (image la plus lente {ms} ms)", + "stats_idle": "Au repos (0 i/s)", + "stats_busy_floors": "étages", + "stats_busy_openings": "portes/fenêtres", + "stats_busy_flash": "flash", + "stats_busy_roof": "toit", + "stats_busy_flow": "flux d'énergie", + "stats_busy_effect": "effet de couleur", + "stats_busy_robot": "robot", + "stats_busy_orbit": "rotation de la caméra", + "stats_busy_tint": "teinte de la pièce", + "stats_low": "niveau tablette, ratio de pixels {r}", + "stats_full": "niveau complet, ratio de pixels {r}", + "floors_apart": "Écartés", + "floors_stacked": "Empilés", + "roof_keep": "Garder le toit", + "roof_keep_hint": "Le toit reste sur la maison pendant le zoom au lieu de se soulever et de s'estomper", + "floor_rooms_one": "1 pièce", + "floor_rooms": "{n} pièces", + "quality": "Qualité", + "quality_auto": "Auto", + "quality_low": "Tablette", + "quality_high": "Élevée", + "state_on": "Allumé", + "state_off": "Éteint", + "state_open": "Ouvert", + "state_closed": "Fermé", + "state_opening": "Ouverture", + "state_closing": "Fermeture", + "state_playing": "Lecture", + "state_paused": "En pause", + "state_idle": "Inactif", + "state_locked": "Verrouillé", + "state_unlocked": "Déverrouillé", + "state_detected": "Détecté", + "state_clear": "Libre", + "state_unavailable": "Indisponible", + "state_heat": "Chauffage", + "state_cool": "Refroidissement", + "state_auto": "Auto", + "state_heat_cool": "Chaud/froid", + "state_dry": "Déshumidification", + "state_fan_only": "Ventilation", + "devices": "Appareils", + "devices_none_area": "Liez la pièce à une zone et ses appareils apparaîtront ici.", + "devices_none": "La zone n'a aucun appareil adapté.", + "devices_place_all_n": "Placer les {n} …", + "devices_place_all_confirm": "Placer {n} appareils dans la pièce d'un coup ? (Ctrl+Z ou « Annuler » les retire tous en une seule étape.)", + "devices_src_area": "Cette zone", + "devices_src_other": "Autres zones", + "devices_src_none": "Aucune zone", + "panel_hide": "Masquer du panneau de la pièce", + "panel_unhide": "Afficher à nouveau dans le panneau de la pièce", + "panel_state_hide": "Masquer l'état dans le panneau de la pièce (p. ex. un volet qui n'indique que « inconnu »)", + "panel_state_show": "Afficher à nouveau l'état dans le panneau de la pièce", + "devices_place": "Placer", + "devices_remove": "Retirer", + "devices_hint": "Les appareils placés apparaissent en 3D. Faites-les glisser dans le plan pour les déplacer.", + "panel_lights": "Lumières", + "panel_covers": "Volets", + "panel_climate": "Chauffage", + "panel_media": "Médias", + "panel_switches": "Interrupteurs", + "panel_sensors": "Capteurs", + "panel_scenes": "Scènes et scripts", + "panel_announce": "📢 Annonce", + "announce_placeholder": "Votre message …", + "announce_send": "Dire", + "announce_sent": "Dit : « {message} »", + "announce_failed": "L'annonce a échoué : {error}", + "announce_phrase_1": "À table !", + "announce_phrase_2": "C'est l'heure d'aller au lit !", + "announce_phrase_3": "Descendez, s'il vous plaît !", + "announce_phrase_4": "On part bientôt !", + "announce_phrase_5": "Le chien doit sortir !", + "state_recording": "Enregistrement", + "state_streaming": "Diffusion", + "panel_all_off": "Tout éteindre", + "readable": "Lisible", + "readable_hint": "Contrastes plus forts et texte plus grand – pour les tablettes murales et tous ceux qui lisent mieux ainsi.", + "plain": "Plan seul", + "plain_hint": "Affiche seulement murs, portes, fenêtres et escaliers, sans meubles. Les appareils et leurs repères restent.", + "right_back": "Clic droit = retour", + "right_back_hint": "Un court clic droit dans la vue 3D revient d’un pas : de la pièce à l’étage, de l’étage à la maison (comme un double appui sur une zone vide). Glisser avec le bouton droit déplace toujours la vue.", + "stl": "Impression 3D (STL)", + "stl_hint": "Enregistre la maison en fichier STL (murs, sols, meubles et extérieurs de tous les étages) pour l’impression 3D, à l’échelle 1:100 (un mètre devient 10 mm). Fenêtres, lumières et toit en sont absents ; un slicer répare le fichier si besoin.", + "card_plain": "Plan seul", + "card_rooms": "Seulement ces pièces", + "card_rooms_hint": "La carte n’affiche que les pièces cochées avec leurs meubles, appareils, portes et fenêtres (par exemple pour une tablette dans la cuisine). Rien de coché : tout le plan.", + "card_templates": "Modèles de carte", + "card_templates_hint": "Configurez une carte une fois ici (avec les réglages de la carte) et indiquez seulement son nom sur chaque tablette : `template: kitchen_tablet`. Les changements atteignent toutes les cartes qui l’utilisent ; ce qui figure sur la carte elle-même l’emporte sur le modèle.", + "template_name": "Nouveau modèle (nom)", + "template_add": "Créer le modèle", + "template_reload": "Recharger les écrans avec ce modèle", + "template_reload_all": "Recharger tous les écrans", + "template_use": "Sur la carte du tableau de bord : `template: {name}`", + "card_template": "Modèle de carte", + "card_template_none": "aucun (cette carte seulement)", + "card_readable": "Lisible", + "all_off_n": "Tout éteindre ({n})", + "all_off_hint": "Éteint lumières, interrupteurs, ventilateurs et médias de la pièce ; annulable pendant dix secondes.", + "all_off_done": "Tout est éteint.", + "all_off_undo": "Annuler", + "all_off_floor": "Tout éteindre à {floor} ({n} appareils), annulable dix secondes", + "mood_save": "Enregistrer l'ambiance", + "mood_save_hint": "Garde l'éclairage actuel de la pièce comme ambiance – un appui la rétablit plus tard, « → » la transfère dans une autre pièce.", + "mood_new": "Ambiance", + "mood_set": "Appliquer cette ambiance", + "mood_carry": "Transférer dans une autre pièce", + "panel_all_on": "Tout allumer", + "view_options": "Vue : qualité, aspect, repères, i/s", + "panel_all_open": "Tout ouvrir", + "panel_all_close": "Tout fermer", + "central": "Central : toutes les lumières, volets roulants et favoris", + "central_house": "Toute la maison", + "central_lights": "Lumières", + "central_covers": "Volets roulants", + "central_on": "Allumer", + "central_off": "Éteindre", + "central_open": "Ouvrir", + "central_close": "Fermer", + "central_sure": "Sûr ?", + "central_favorites": "Favoris", + "central_no_favorites": "Aucun favori pour le moment. Définissez des scènes, scripts et interrupteurs dans l'éditeur sous « Favoris ».", + "card_central": "Étoile avec le menu central", + "card_central_hint": "Toutes les lumières et tous les volets roulants de l'étage ou de la maison, et les favoris de l'éditeur.", + "favorites": "Favoris", + "favorites_hint": "Scènes, scripts, automatisations, boutons et interrupteurs pour le menu central (étoile) de la vue 3D – fête, simulation de présence, ombrage, arrosage.", + "favorites_add": "Ajouter un favori", + "favorite_floor": "Étage où ce favori apparaît", + "favorite_all_floors": "Tous les étages", + "outside_hidden": "Extérieur : masquer des appareils", + "outside_hidden_hint": "Appareils que le panneau Extérieur ne doit pas afficher (ils restent sur le plan).", + "outside_hidden_add": "Masquer un appareil", + "room_facts": "Panneau de la pièce : informations affichées", + "room_fact_sun": "Heures de soleil", + "room_fact_comfort": "Confort", + "room_fact_air": "Conseil d'aération", + "room_fact_circuits": "Circuits", + "background_handles_hint": "L'image a maintenant des poignées comme un meuble : glisser la déplace, le coin inférieur droit la met à l'échelle, la poignée ronde en haut la fait pivoter (Maj pour des pas de 15°). Quand elle est bien placée, touchez « Terminé » – elle ne bouge plus ensuite.", + "background_fixed_hint": "L'image reste fixe, vous pouvez dessiner par-dessus. Pour l'ajuster, touchez « Déplacer, mettre à l'échelle et pivoter ».", + "bg_level": "Redresser", + "bg_level_cancel": "Annuler le redressement", + "bg_level_first": "Touchez le début d'un mur de l'image qui doit être droit (horizontal ou vertical).", + "bg_level_second": "Touchez maintenant la fin de ce mur – l'image pivote pour s'ajuster.", + "bg_ruler": "Mettre à l'échelle avec une règle", + "bg_ruler_cancel": "Annuler la règle", + "bg_ruler_first": "Touchez le début d'un tronçon de longueur connue dans l'image – p. ex. un mur coté.", + "bg_ruler_second": "Touchez maintenant la fin du tronçon.", + "bg_ruler_length_hint": "Mesuré dans le plan : {m} m. Saisissez la longueur réelle et l'image sera mise à l'échelle.", + "bg_ruler_length": "Longueur réelle (m)", + "bg_ruler_apply": "Appliquer l'échelle", + "thumbs_fold": "Réduire les images des étages en boutons", + "thumbs_show": "Afficher à nouveau les images des étages", + "room_start_view": "Vue comme départ de cette pièce", + "room_start_view_hint": "Quand vous touchez la pièce en 3D, la caméra rejoint exactement la vue affichée à droite dans le volet 3D – angle, zoom et cadrage. Activez d'abord « 3D à côté », tournez et zoomez sur la pièce, puis touchez.", + "room_start_view_reset": "Supprimer la vue de départ de la pièce (de nouveau du dessus)", + "room_start_view_need_pane": "Activez d'abord « 3D à côté », puis tournez et zoomez sur la pièce comme elle doit s'ouvrir.", + "floor_start_view": "Vue comme départ de cet étage", + "floor_start_view_hint": "Cet étage s'ouvre en 3D comme le volet 3D de droite est placé en ce moment – p. ex. le rez-de-chaussée de face et l'étage de dos. Activez d'abord « 3D à côté », tournez la vue, puis touchez.", + "floor_start_view_reset": "Supprimer la vue de départ de l'étage (comme la maison de nouveau)", + "floor_start_view_need_pane": "Activez d'abord « 3D à côté » et tournez l'étage comme il doit s'ouvrir.", + "ambilight": "Lueur derrière la TV (%)", + "ambilight_hint": "Intensité de la lueur derrière la TV pendant la lecture. 0 la désactive (p. ex. si la TV a des bandes LED), 100 est l'intensité habituelle.", + "sound_rings": "Ondes sonores (%)", + "sound_rings_hint": "Taille des ondes autour de l’enceinte pendant la lecture. 0 les désactive, l’image et la lueur restent ; 100 est la taille habituelle. La taille suit aussi le volume de l’enceinte : plus bas, plus petit.", + "glow_scale": "Lueur en 3D (%)", + "light_effects": "Animations d'effets en 3D", + "light_effects_hint": "Associez uniquement des noms d'effets HA exacts. Les effets non associés gardent la couleur HA statique. Ne change rien dans Home Assistant.", + "light_effects_enabled": "Autoriser les animations pour cette lampe", + "light_effect_unmapped": "Non associé (statique)", + "light_effect_add": "Ajouter un nom d'effet exact", + "light_effect_name_limit": "Le nom d'effet exact doit contenir de 1 à 255 caractères. Il ne sera pas raccourci.", + "light_effect_count_limit": "100 associations au maximum. Supprimez d'abord une entrée existante.", + "light_effect_exists": "Ce nom d'effet est déjà associé. Son association existante est conservée.", + "light_animation_none": "Statique", + "light_animation_rainbow": "Arc-en-ciel (remplace la couleur)", + "light_animation_pulse": "Pulsation (intensité)", + "light_animation_flicker": "Scintillement (intensité)", + "glow_scale_hint": "Intensité de la lueur de la lampe en 3D : en dessous de 100 %, les bandes LED vives sont atténuées pour que la pièce ne soit pas brûlée ; au-dessus de 100 %, une lampe faible rayonne davantage. Ne commute rien dans Home Assistant.", + "vehicle_to_spot": "Transformer en place de stationnement", + "vehicle_to_spot_hint": "Un véhicule en simple meuble est toujours là. En place de stationnement, il n'apparaît que lorsqu'un capteur signale la voiture, et c'est là que l'appareil de la voiture est lié (charge, autonomie, verrouillage, climatisation).", + "as_furniture": "Afficher comme meuble", + "as_furniture_hint": "Remplace l'épingle par un meuble au même endroit, lié à cet appareil – une enceinte pour un lecteur multimédia, une lampe pour une lumière. Ctrl+Z annule.", + "as_furniture_pick": "Choisir un meuble …", + "as_device": "Retour à un repère d'appareil", + "as_device_hint": "Remplace le meuble par le simple repère de son appareil au même endroit.", + "presets": "Stations et playlists (son)", + "presets_hint": "Affichés dans le menu rapide de chaque enceinte sous « Lire », à côté des sources du lecteur. Pour un Echo (Alexa Media Player) : saisissez SPOTIFY, AMAZON_MUSIC ou TUNEIN et, comme contenu, ce que vous diriez (« Rock Antenne »). Pour Sonos, Music Assistant et autres : saisissez music ou url avec une adresse de flux ou un URI.", + "preset_type": "Type", + "preset_type_hint": "media_content_type de play_media, p. ex. music, url, playlist, SPOTIFY, AMAZON_MUSIC, TUNEIN", + "preset_content": "Contenu", + "preset_content_hint": "media_content_id : URL de flux, URI (spotify:playlist:…) ou, pour Alexa, une phrase de recherche", + "preset_speakers": "Seulement sur ces enceintes (aucune = toutes)", + "media_play": "Lecture", + "media_pause": "Pause", + "media_previous": "Précédent", + "media_next": "Suivant", + "media_volume": "Volume", + "media_sources": "Sources", + "preset_add": "Station ou playlist", + "own_buttons": "Boutons personnalisés", + "own_buttons_hint": "Affichés dans le menu central (étoile) sous les favoris : ouvrir un chemin de tableau de bord, afficher les détails d'une entité, appeler un service, ou ouvrir une fenêtre browser_mod avec votre propre carte.", + "own_alerts": "Alertes personnelles", + "circuits": "Tableau électrique", + "circuits_hint": "Les circuits avec les pièces qu'ils alimentent. Le panneau de la pièce les cite, et la recherche les trouve (« F12 »).", + "circuit_name": "Nom", + "circuit_new": "Nouveau circuit", + "circuit_add": "Ajouter un circuit", + "circuit_add_room": "Ajouter une pièce", + "own_alerts_hint": "Une ligne dans la barre d'alertes de la vue 3D tant qu'une entité est dans un état – « Réservoir vide » du robot, « Lave-vaisselle terminé ». Plusieurs états séparés par des virgules ; pour les nombres <20 ou >80.", + "own_alert_entity": "Quand …", + "own_alert_state": "… est dans l'état (vide = activé)", + "own_alert_text": "… alors cette alerte", + "own_alert_color": "Couleur", + "own_alert_tap": "Un appui", + "own_alert_tap_info": "ouvre les détails", + "own_alert_tap_toggle": "bascule l'entité", + "own_alert_tap_room": "va dans la pièce", + "own_alert_house": "Toute la maison", + "own_alert_new": "Nouvelle alerte", + "own_alert_add": "Ajouter une alerte", + "today": "Aujourd'hui", + "today_none": "Rien de prévu aujourd'hui.", + "today_calendars": "Calendriers pour « Aujourd'hui »", + "today_calendars_hint": "Les rendez-vous de ces calendriers s'affichent en haut à droite de la vue 3D sur la carte « Aujourd'hui », avec les poubelles ramassées aujourd'hui ou demain. Un appui sur le titre replie la carte.", + "own_button_state": "S'allume tant que … est activé (facultatif)", + "own_button_label": "Libellé", + "own_button_action": "Action", + "own_button_new": "Nouveau bouton", + "own_button_add": "Bouton personnalisé", + "own_action_navigate": "Ouvrir un chemin", + "own_action_more_info": "Détails de l'entité", + "own_action_service": "Appeler un service", + "own_action_fire_dom_event": "fire-dom-event (browser_mod)", + "own_target_navigate": "Chemin", + "own_target_more_info": "Entité", + "own_target_service": "Service (domain.service)", + "own_data": "Données (JSON)", + "own_data_hint": "Pour un service, ses données ; pour fire-dom-event, le contenu de l'événement, p. ex. {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}.", + "own_data_bad": "Objet JSON non valide.", + "panel_no_area": "Cette pièce n'est liée à aucune zone. Vous pouvez la lier dans l'éditeur.", + "panel_empty": "Aucun appareil de cette pièce n'est dans le plan. Dans l'éditeur, placez des appareils ou choisissez-les pour le panneau de la pièce avec ☆.", + "close": "Fermer", + "panel_fold": "Replier (la pièce reste visible)", + "panel_unfold": "Rouvrir", + "brightness": "Luminosité", + "color_temp": "Température de couleur", + "color": "Couleur", + "position": "Position", + "cover_open": "Ouvrir", + "cover_stop": "Arrêter", + "cover_tilt": "Lames", + "cover_tilt_open": "Lames ouvertes", + "cover_tilt_close": "Lames fermées", + "cover_close": "Fermer", + "target_temp": "Consigne", + "current_temp": "Actuelle", + "temp_down": "Plus frais", + "temp_up": "Plus chaud", + "volume": "Volume", + "play_pause": "Lecture/pause", + "previous": "Précédent", + "next": "Suivant", + "run": "Exécuter", + "details": "Détails", + "hold_hint": "Un appui commute · un appui long ouvre les détails", + "tool_opening": "Portes et fenêtres", + "tool_furniture": "Meubles", + "qm_off": "Éteindre", + "find": "Rechercher", + "find_placeholder": "Où est … ? Appareil ou pièce", + "find_none": "Rien trouvé", + "swipe_off": "Éteindre", + "panel_pin": "Afficher dans le panneau de la pièce", + "panel_unpin": "Ne pas afficher dans le panneau de la pièce", + "devices_panel_hint": "Le panneau de la pièce affiche les appareils du plan. ☆ ajoute un appareil au panneau de la pièce sans le placer.", + "card_section_view": "Vue", + "card_size": "Taille", + "card_size_fixed": "Hauteur fixe", + "card_size_fill": "Remplir l'écran", + "card_fill_hint": "Fonctionne mieux dans une vue de tableau de bord de type « Panneau (carte unique) » – la carte prend alors tout l'espace.", + "card_controls": "Commandes dans la carte", + "card_floor_thumbs": "Étages en miniatures", + "card_floor_thumbs_hint": "De petites images des étages sur le côté – touchez-en une pour changer", + "card_floor_thumbs_hint_start": "L'étage choisi est alors celui où la carte démarre – les images sur le côté permettent de passer aux autres", + "card_room_names": "Afficher les noms des pièces", + "card_section_kiosk": "Tablette murale (mode kiosque)", + "card_section_features": "Fonctionnalités", + "card_weather_plan": "comme défini dans le plan", + "card_pro_hint": "La trace de mouvement et le mur de caméras relèvent des caméras : la trace montre la dernière demi-heure, le mur toutes les caméras du plan.", + "card_idle_return": "Retour à la vue de départ après", + "card_idle_off": "Jamais", + "card_idle_min": "{n} min sans toucher", + "card_idle_hint": "Après ce délai, la carte ferme la pièce et réaffiche la vue de départ.", + "card_night": "Atténuation de nuit", + "card_night_off": "Désactivée", + "card_night_sun": "Selon le soleil", + "card_night_time": "Plage horaire", + "card_night_range": "Plage horaire (p. ex. 22:00-06:00)", + "card_idle_orbit": "Rotation de la caméra comme économiseur d'écran", + "card_idle_orbit_hint": "Après le retour, la vue tourne lentement jusqu'à ce que quelqu'un touche la tablette", + "card_dashboard": "Bouton vers un tableau de bord (chemin)", + "card_dashboard_label": "Libellé du bouton", + "card_dashboard_hint": "Un bouton en haut à droite de la carte ouvre le tableau de bord ou la vue avec ce chemin, p. ex. /lovelace/home ou /dashboard-house/0. Sans libellé, il affiche ⌂.", + "card_alerts": "Afficher les alertes", + "card_alerts_hint": "Fumée, gaz, CO, eau, centrale d'alarme et fenêtres ouvertes sous la pluie : la pièce pulse, une note apparaît en haut", + "card_alert_jump": "Aller à la pièce d'une nouvelle alerte", + "card_alert_jump_hint": "La vue passe d'elle-même à l'étage et à la pièce de l'alerte", + "card_scenes": "Boutons de scène dans la pièce", + "card_scenes_hint": "Scènes et scripts de la zone sous forme de boutons sous la vue 3D quand une pièce est sélectionnée", + "card_sensor_bar": "Capteurs en haut", + "card_sensor_bar_hint": "Les capteurs choisis dans l'éditeur (Réglages) en haut à gauche de la carte", + "card_central_open": "Menu étoile ouvert et grand", + "card_central_open_hint": "Les favoris et boutons personnels sont ouverts dès le départ, en plus grand", + "card_keep_camera": "Garder la caméra en changeant d'étage", + "card_keep_camera_hint": "Même côté, hauteur et distance à chaque étage", + "card_today": "Carte « Aujourd'hui »", + "card_today_hint": "Rendez-vous du jour et poubelles à sortir, en haut à droite", + "card_announcements": "Annonces", + "card_announcements_hint": "Les annonces (action « NextFloor : Annonce ») s'affichent en grand sur la carte, avec un carillon, et sont prononcées", + "weather_short": "Météo", + "weather_entity": "Entité météo", + "weather_effects": "Effets météo en 3D", + "card_weather_density": "Quantité de pluie et de neige", + "card_weather_density_hint": "Moins de gouttes et de flocons que la météo n'en annonce ; les nuages, le brouillard et les éclairs restent", + "rain_warning": "Alerte : fenêtre ouverte sous la pluie", + "sun_patches": "Soleil et ombres", + "sun_patches_hint": "Avec le nord défini, la lumière du soleil de sun.sun traverse les fenêtres en taches lumineuses sur le sol, et la maison projette son ombre sur le terrain. Décochez pour garder sol et terrain sans taches de soleil ni ombres.", + "sun_arc": "Arc du soleil et boussole", + "sun_arc_hint": "Dessine le trajet du soleil d’aujourd’hui en arc au-dessus du terrain, avec un anneau et les points cardinaux au sol (nord en rouge). Nécessite la position de votre domicile dans Home Assistant.", + "weather_effect_rain": "Pluie", + "weather_effect_snow": "Neige", + "weather_effect_fog": "Brouillard (grise la scène)", + "weather_effect_clouds": "Les nuages atténuent le ciel et le soleil", + "weather_effect_lightning": "Éclairs en cas d'orage", + "weather_effect_sky": "Soleil et lune dans le ciel", + "weather_entity_hint": "L'entité météo qui pilote le ciel autour de la maison. Automatique utilise la première trouvée.", + "weather_hint": "Météo à la maison : pluie et neige tombent avec le vent réel, les nuages défilent au-dessus du terrain avec leurs ombres, éclairs, brouillard, soleil et lune", + "card_weather": "Météo extérieure", + "card_weather_hint": "Pluie, neige, grêle, nuages avec ombres, éclairs et brouillard à partir de la première entité météo (weather_entity en choisit une autre) ; moins de particules en niveau Tablette", + "alerts": "Alertes", + "alert_smoke": "Fumée : {name}", + "alert_gas": "Gaz : {name}", + "alert_co": "Monoxyde de carbone : {name}", + "alert_water": "Eau : {name}", + "alert_alarm": "Alarme déclenchée", + "alert_alarm_by": "Alarme déclenchée par {cause}", + "alert_alarm_pending": "Alarme en attente", + "alert_window_rain": "Fenêtre ouverte sous la pluie : {name}", + "alert_power_outage": "Coupure de courant : {name}", + "alert_contact_lost": "Le contact ne répond pas : {name}", + "rain_sensor": "Capteur de pluie (station météo personnelle)", + "outage_sensor": "Capteur de coupure de courant", + "outage_hint": "Un capteur binaire de classe « power » éteint, un autre capteur binaire allumé, un état comme « off_grid » ou « backup », ou une tension sous 50 V déclenchent une alerte pour toute la maison.", + "contact_warning": "Avertir quand un contact de porte ou de fenêtre est injoignable", + "contact_warning_hint": "Quand un contact est indisponible depuis 10 minutes (pile vide, hors de portée radio), la fenêtre paraît fermée en 3D sans que personne ne le sache. Une note nomme alors le contact. Un redémarrage de Home Assistant n'avertit pas.", + "night_lock_warning": "Avertir la nuit si une porte n'est pas verrouillée", + "night_lock_warning_hint": "Entre 22 h et 6 h, une note cite les serrures du plan qui ne sont pas verrouillées.", + "alert_unlocked_night": "Non verrouillée : {name}", + "motion_markers_active": "N'afficher les détecteurs de mouvement que lorsqu'ils détectent", + "motion_markers_active_hint": "S'applique aux détecteurs de mouvement, d'occupation et de présence. Un détecteur dont le symbole est réglé pour toujours s'afficher reste visible.", + "room_double_tap": "Double appui sur une pièce", + "room_double_tap_hint": "Un double appui sur une pièce éteint ses lumières si l'une est allumée, sinon les allume toutes. Les appareils qui demandent d'abord restent toujours à l'écart.", + "room_double_tap_area": "Lampes du plan et toutes les lumières de la zone", + "room_double_tap_plan": "Seulement les lampes du plan", + "room_double_tap_off": "Ne rien commuter", + "card_room_double_tap_auto": "Comme réglé dans le plan", + "status_entities": "Capteurs à afficher en haut de la vue 3D", + "status_add": "Ajouter un capteur", + "status_entities_hint": "Par exemple la température extérieure, l'alarme ou la qualité de l'air : ils s'affichent en haut à gauche avec nom et valeur, aussi dans une pièce ouverte. Un appui ouvre les détails. Jusqu'à 12.", + "announce_tts": "Synthèse vocale des annonces", + "announce_phrases": "Phrases pour les annonces (une par ligne)", + "announce_phrases_hint": "Vide : les phrases fournies. Les annonces existent aussi comme action « NextFloor : Annonce » pour les automatisations – sur les haut-parleurs des pièces et sur chaque écran NextFloor ouvert.", + "opening_rain_warning": "Avertir quand il pleut", + "room_names_short": "Noms des pièces", + "floor_stack_short_dim": "Atténués", + "floor_stack_short_stacked": "Empilés", + "floor_stack_short_single": "Seul", + "size_short_w": "L", + "size_short_d": "P", + "size_short_h": "H", + "import_error_not_json": "Le fichier n'est pas du JSON.", + "import_error_not_plan": "Le fichier n'est pas un plan NextFloor.", + "export_name_template": "calque", + "export_name_backup": "sauvegarde", + "card_floor_stack": "Étages inférieurs", + "floor_stack_dim": "Atténués", + "floor_stack_stacked": "Empilés (la maison jusqu'ici)", + "floor_stack_single": "Masqués (cet étage uniquement)", + "card_control_walls": "Murs hauts/coupe", + "card_control_floors": "Étages écartés", + "card_control_temperature": "Température", + "card_control_humidity": "Humidité", + "card_control_co2": "CO₂", + "card_controls_hint": "Murs hauts/coupe, étages écartés et température, humidité, CO₂ à basculer", + "controls_hide": "Masquer les commandes – seule la vue 3D reste", + "nav_wrap": "Répartir la barre : chaque étage et chaque pièce sur plusieurs lignes", + "bars_fold": "Replier les commandes", + "bars_unfold": "Commandes", + "nav_row": "Barre sur une ligne (défilement latéral)", + "controls_show": "Réafficher les commandes", + "card_controls_hidden": "Démarrer avec les commandes masquées", + "card_controls_hidden_hint": "Seule la vue 3D ; un œil en bas à gauche ramène barres, valeurs et boutons", + "card_controls_hide_after": "Masquer les commandes après", + "card_hide_after_s": "{n} s sans toucher", + "card_fullscreen_button": "Bouton plein écran", + "card_fullscreen_button_hint": "Masque le tableau de bord autour de la carte (p. ex. sur une tablette murale)", + "fullscreen": "Plein écran", + "fullscreen_exit": "Quitter le plein écran", + "card_section_show": "Afficher", + "card_floor": "Étage", + "card_floor_house": "Toute la maison (touchez un étage pour l'ouvrir)", + "card_height": "Hauteur (pixels)", + "card_walls": "Murs", + "card_quality_hint": "« Tablette » est le réglage le plus léger – idéal pour les tablettes Fire et autres tablettes murales.", + "card_flows_switch": "Bouton dans la carte", + "card_flows_on": "Toujours activé", + "card_flows_off": "Toujours désactivé", + "holos": "Cartes", + "holos_hint": "Afficher ou masquer les cartes en direct au-dessus de la maison (bilan énergétique, voiture, média)", + "card_energy": "Afficher les valeurs d'énergie en haut", + "card_room_panel": "Détails de la pièce au toucher", + "card_room_buttons": "Boutons des pièces", + "card_room_buttons_hint": "Une rangée avec un bouton par pièce en haut de la carte – touchez-en un pour ouvrir la pièce, comme en la touchant dans le modèle", + "card_room_panel_hint": "Les lumières et volets roulants de la pièce dans un panneau latéral", + "card_explode": "Écarter les étages dans la vue de la maison", + "card_roof_fade": "Estomper le toit lors du zoom avant", + "card_roof_fade_hint": "Désactivé : le toit reste sur la maison même quand la caméra s'approche.", + "card_stats": "Affichage des performances (images par seconde)", + "card_stats_hint": "Pour vérifier la fluidité de la carte sur l'appareil", + "packs": "Packs de meubles", + "lib_badge_light": "Lampe : liée à une lumière, s'allume en 3D", + "lib_badge_electric": "Électrique : lié à une entité et à un capteur de puissance (commutation, images, consommation)", + "lib_badge_hint": "Les éléments avec un symbole sont liés à des entités : les lampes s'allument, les écrans affichent des images, les appareils affichent leur consommation.", + "lib_cat_lights": "Luminaires", + "lib_cat_seating": "Assises", + "lib_cat_tables": "Tables", + "lib_cat_storage": "Meubles et étagères", + "lib_cat_beds": "Lits", + "lib_cat_kitchen": "Cuisine", + "lib_cat_appliances": "Électroménager", + "lib_cat_bath": "Salle de bain", + "lib_cat_media": "TV et audio", + "lib_cat_office": "Bureau", + "lib_cat_tech": "Technique", + "lib_cat_climate": "Chauffage et climatisation", + "lib_cat_energy": "Énergie", + "lib_cat_garden": "Jardin et terrasse", + "lib_cat_plants": "Plantes", + "lib_cat_kids": "Enfants", + "lib_cat_fitness": "Sport", + "lib_cat_pets": "Animaux", + "lib_cat_workshop": "Atelier et garage", + "lib_cat_music": "Musique et atelier", + "lib_cat_season": "Saisons et déco", + "lib_cat_pictures": "Cadres et photos", + "lib_cat_vehicles": "Véhicules", + "lib_cat_building": "Escaliers et éléments du bâtiment", + "lib_cat_decor": "Décoration et divers", + "lib_favourites": "Favoris", + "lib_recent": "Utilisés récemment", + "lib_for_room": "Pour {room}", + "lib_all_rooms": "Afficher toutes les pièces", + "lib_linkable": "reliable", + "lib_lit": "lumineux", + "lib_outdoor": "extérieur", + "lib_fav_add": "Ajouter aux favoris", + "lib_fav_remove": "Retirer des favoris", + "lib_sizes": "Tailles", + "feature_name_energy": "Flux d'énergie", + "ext_tab": "Extensions", + "ext_title": "Extensions", + "models": "Vos propres modèles 3D", + "models_hint": "Pour certains véhicules, NextFloor peut afficher un vrai modèle 3D si vous en possédez un. Choisissez ici le fichier (.glb) : NextFloor l'oriente correctement, l'allège, repère la peinture et le stocke sur votre Home Assistant. Sans modèle, le véhicule garde son apparence d'avant.", + "models_licence": "Les fichiers vous appartiennent et restent sur votre Home Assistant. NextFloor ne fournit aucun modèle ; vérifiez que la licence de votre modèle vous autorise à l'utiliser dans votre propre installation.", + "model_add": "Ajouter un modèle …", + "model_replace": "Remplacer le modèle …", + "model_remove": "Supprimer", + "model_present": "en place", + "model_missing": "aucun pour l'instant", + "model_remove_confirm": "Supprimer le modèle « {id} » de Home Assistant ?", + "model_removed": "Modèle « {id} » supprimé.", + "model_uploaded": "Modèle « {id} » enregistré ({size}). Rechargez le panneau pour le voir.", + "model_upload": "Enregistrer sur Home Assistant", + "model_info": "{triangles} triangles, {size} m", + "model_front": "Avant", + "model_front_hint": "Tournez le modèle jusqu'à ce que son avant fasse face à l'observateur (vers le bas à gauche sur l'image).", + "model_paint": "Peinture (la couleur choisie dans l'éditeur)", + "model_paint_preview": "Couleur dans l'aperçu", + "model_detail": "Niveau de détail", + "model_detail_light": "Léger (tablette)", + "model_detail_normal": "Normal", + "model_detail_fine": "Fin", + "model_result": "Résultat : {triangles} triangles, {size}", + "model_error_not_glb": "Ce n'est pas un fichier .glb (glTF binaire). Exportez le modèle en « glTF binary ».", + "model_error_compressed": "Le fichier est compressé (Draco, Meshopt ou KTX). Exportez-le sans compression.", + "model_error_empty": "Le fichier ne contient rien de tridimensionnel.", + "model_error_unreadable": "Le fichier est illisible : {detail}", + "model_error_too_large": "Le fichier dépasse {max}. Choisissez un niveau de détail plus bas.", + "model_upload_forbidden": "Seuls les administrateurs peuvent téléverser des modèles.", + "model_upload_too_large": "Home Assistant n'accepte pas les fichiers de plus de {max}. Choisissez un niveau de détail plus bas.", + "model_upload_not_glb": "Home Assistant a refusé le fichier (ce n'est pas un glTF binaire).", + "model_upload_bad_id": "L'identifiant du modèle n'est pas valide.", + "model_upload_other": "Le téléversement a échoué : {detail}", + "ext_intro": "Importez ici vos propres packs de meubles, téléversez vos propres modèles 3D et ajoutez des plugins.", + "plugin": "plugin", + "plugins_title": "Plugins", + "plugins_intro": "Les plugins ajoutent vos propres animations de lumière, appareils et cartes dans le panneau de la pièce. Saisissez l'adresse d'un plugin (un fichier .js dans /config/www, soit /local/…, depuis HACS /hacsfiles/…, ou https://…).", + "plugins_docs": "Comment écrire un plugin", + "plugins_warning": "Les plugins s'exécutent avec les mêmes droits que NextFloor dans votre navigateur. N'utilisez que des plugins de sources de confiance.", + "plugins_off": "désactivé", + "plugins_error": "erreur", + "plugins_loading": "chargement …", + "plugins_nothing_registered": "chargé, mais n'a rien enregistré", + "plugins_loaded": "actif", + "plugins_reload_hint": "Pris en compte après rechargement de la page", + "plugins_remove": "Supprimer", + "plugins_none": "Aucun plugin pour l'instant.", + "plugins_from_dashboard": "Enregistré par une ressource du tableau de bord", + "plugins_add": "Ajouter", + "plugins_url_invalid": "Saisissez une adresse .js sous /local/…, /hacsfiles/… ou https://….", + "plugins_exists": "Ce plugin figure déjà dans la liste.", + "plugins_limit": "20 plugins au maximum.", + "packs_title": "Packs de meubles", + "packs_intro": "Importez vos propres meubles sous forme de pack (JSON) : en fichier ou collé ci-dessous. {n} packs sont fournis avec NextFloor et toujours disponibles.", + "packs_docs": "Format des packs", + "packs_none": "Aucun pack personnel pour l'instant.", + "community_title": "Meubles de la communauté", + "community_intro": "Des meubles construits et partagés par d'autres avec le constructeur de meubles – vérifiés et gratuits. Construisez les vôtres :", + "community_builder": "Ouvrir le constructeur de meubles", + "community_how": "Comment partager les vôtres", + "community_load": "Charger les meubles de la communauté", + "community_none": "Pas encore de meubles de la communauté – soyez le premier !", + "community_install": "Installer", + "community_update": "Mettre à jour", + "community_installed": "Installé", + "community_failed": "Impossible de charger les meubles de la communauté : {detail}", + "pack_import": "Importer des fichiers de pack …", + "pack_paste": "Importer le JSON", + "pack_paste_empty": "Collez d'abord le JSON d'un pack.", + "pack_paste_not_json": "Ce JSON n'est pas valide : {detail}", + "pack_imported": "« {name} » de {publisher} importé – {n} éléments", + "packs_imported_n": "{n} packs sur {total} importés", + "pack_by": "par {publisher} · {n} éléments", + "pack_remove": "Supprimer", + "pack_remove_confirm": "Supprimer le pack « {name} » ? Ses meubles restent dans le plan sous forme de simples boîtes.", + "pack_error_not_a_pack": "Ce n'est pas un pack de meubles (« \"format\": \"nfpack\" » est absent).", + "pack_error_builtin": "Un pack fourni avec NextFloor porte déjà cet identifiant.", + "pack_error_invalid_content": "Le pack contient des meubles invalides : {detail}", + "pack_error_too_large": "Le pack est trop volumineux (1 Mo au maximum).", + "pack_error_needs_update": "Ce pack nécessite une version plus récente de NextFloor. Mettez d'abord à jour (HACS › NextFloor › ⋮ › « Informations de mise à jour » › « Télécharger »), redémarrez Home Assistant, puis réimportez.", + "pack_error_other": "Échec de l'import : {detail}", + "store_open": "Ouvrir la boutique de plugins", + "store_close": "Fermer la boutique de plugins", + "store_intro": "Plugins de la communauté vérifiés. Chacun est examiné avant d'être ajouté et ne change plus ensuite.", + "store_submit": "Proposer votre propre plugin", + "store_empty": "Aucun plugin dans la boutique pour l'instant.", + "store_failed": "Impossible de charger la boutique ({error}).", + "store_install": "Installer", + "store_installed": "installé", + "store_update": "Mettre à jour", + "store_confirm": "Installer « {name} » de {author} ?\n\nUn plugin s'exécute avec les mêmes droits que NextFloor dans votre navigateur. Le fichier a été vérifié et son contenu est figé :\n{url}", + "manual": "Manuel", + "manual_more": "En savoir plus", + "feature_text_energy": "Des particules d'énergie volent en arcs des champs solaires vers l'onduleur, entre la maison, la batterie, le réseau et les consommateurs – plus vite et plus denses quand la puissance augmente. Les modules scintillent selon leur production, une carte flottante au-dessus du toit affiche le bilan et l'autonomie actuelle de la maison.", + "live_autarky": "autonome", + "live_car_away": "En route", + "live_car_charging": "En charge", + "live_car_plugged": "Branchée", + "live_car_lock": "Verrouiller", + "live_car_unlock": "Déverrouiller", + "live_car_unlock_confirm": "Vraiment déverrouiller {name} ?", + "live_car_climate": "Climatisation", + "live_car_charge": "Démarrer/arrêter la charge", + "live_media_prev": "Précédent", + "live_media_playpause": "Lecture/pause", + "live_media_next": "Suivant", + "live_media_volume": "Volume", + "live_car_device": "Voiture (n'importe quelle entité de la voiture)", + "live_car_device_hint": "La charge, l'autonomie, la recharge, la prise, le verrouillage et la climatisation sont retrouvés par NextFloor sur l'appareil de la voiture. Sans appareil, il utilise le capteur de présence de la place.", + "live_car_departure_entity": "Heure de départ (facultatif)", + "live_car_departure": "Départ à {time}", + "live_car_open": "Ouvert : {parts}", + "printer_printing": "impression", + "printer_done": "terminé", + "printer_paused": "en pause", + "printer_error": "erreur", + "printer_idle": "prête", + "printer_done_at": "fini à {time}", + "printer_layer": "Couche", + "printer_nozzle": "Buse", + "printer_bed": "Plateau", + "heatpump_heating": "chauffe", + "heatpump_water": "eau chaude", + "heatpump_cooling": "refroidit", + "heatpump_defrost": "dégivre", + "heatpump_idle": "au repos", + "heatpump_flow_return": "Départ → retour", + "heatpump_heat": "Chaleur", + "heatpump_power": "Électricité", + "heatpump_outside": "dehors", + "pack_missing_item": "Meuble d'un pack supprimé", + "back_to_room": "Retour à {room}", + "back_to_floor": "Retour à l'étage", + "hint_furniture": "Touchez une pièce, puis choisissez un élément à droite · faites glisser les éléments, redimensionnez-les par leurs coins", + "furniture_into": "Les nouveaux éléments sont placés au milieu de « {room} ».", + "furniture_pick_room": "Astuce : touchez d'abord une pièce – les nouveaux éléments s'y placent alors au milieu.", + "flows": "Flux d'énergie", + "flows_hint": "Afficher ou masquer les arcs d'énergie entre champs solaires, onduleur, batterie, réseau et consommateurs", + "chk_title": "Configuration", + "chk_hint": "Ce dont le flux d'énergie a besoin. Touchez une ligne pour y accéder.", + "chk_solar": "Champ solaire en place", + "chk_solar_add": "Placer un champ solaire sur le toit", + "chk_meter": "Compteur avec capteur du réseau", + "chk_meter_sensor": "Compteur : capteur du réseau (W) manquant", + "chk_meter_add": "Ajouter le compteur", + "chk_inverter": "Onduleur avec capteur de puissance", + "chk_inverter_sensor": "Onduleur : capteur de puissance manquant", + "chk_inverter_add": "Ajouter un onduleur", + "chk_battery": "Batterie domestique avec puissance et charge", + "chk_battery_sensor": "Batterie domestique : puissance ou charge manquante", + "chk_battery_opt": "Batterie domestique (facultatif)", + "chk_grid": "Raccordement au réseau défini", + "chk_grid_opt": "Raccordement au réseau (facultatif, sinon automatique)", + "energy_sign_grid": "La maison indique une injection alors que le soleil ne produit rien. Le signe du capteur du réseau est probablement inversé.", + "energy_sign_battery": "La batterie se charge sans soleil ni soutirage du réseau. Le signe de son capteur est probablement inversé.", + "energy_sign_flip": "Inverser le signe", + "help_title": "Aide et retours", + "help_hint": "Signalez les problèmes dans un ticket GitHub et les souhaits dans une discussion – rien ne se perd et chacun voit l'état d'avancement.", + "help_issue": "Signaler un problème", + "help_idea": "Proposer une idée", + "furn_name": "Nom (facultatif)", + "furn_mirror": "Miroir", + "furn_mirror_hint": "Inverse la gauche et la droite – le canapé d'angle dans l'autre sens, l'armoire avec sa porte de l'autre côté, la cuisine en miroir.", + "hint_opening": "Touchez un mur pour ajouter une porte ou une fenêtre – choisissez ensuite son type à droite", + "preset_door": "Porte", + "preset_door_double": "Porte double", + "preset_window": "Fenêtre", + "preset_window_double": "Fenêtre double", + "preset_terrace": "Porte-fenêtre", + "preset_terrace_double": "Porte-fenêtre double", + "preset_lift_slide": "Porte coulissante à levage", + "preset_garage": "Porte de garage", + "preset_front": "Porte d'entrée", + "opening_style": "Style", + "sidelight_auto": "automatique", + "sidelight_hinge": "Vitrage latéral côté charnières", + "sidelight_hinge_hint": "Sinon le vitrage latéral est à l'opposé des charnières ; coché, il est à côté des charnières.", + "sidelight_width": "Largeur du vitrage latéral (m)", + "sidelight_width_left": "Vitrage latéral gauche (m)", + "sidelight_width_right": "Vitrage latéral droit (m)", + "style_auto": "Automatique ({style})", + "style_interior": "Porte de pièce", + "style_front": "Porte d'entrée", + "style_front_glass": "Porte d'entrée vitrée", + "style_sidelight": "Porte d'entrée avec vitrage latéral", + "style_sidelights": "Porte d'entrée avec deux vitrages latéraux", + "style_glass": "Porte vitrée", + "style_sliding": "Porte coulissante", + "style_passage": "Ouverture (sans porte)", + "style_standard": "Standard", + "style_bars": "Avec petits-bois", + "style_glass_wall": "Mur de verre (fixe)", + "preset_glass_wall": "Mur de verre", + "flip_hinge": "Inverser le côté des charnières", + "flip_main_leaf": "Inverser le vantail principal", + "flip_hinge_hint": "Charnières de l'autre côté", + "flip_swing": "Inverser le sens d'ouverture", + "flip_swing_hint": "La porte s'ouvre vers la pièce ou de l'autre côté", + "main_leaf": "Vantail principal (vu de la pièce)", + "contact_main": "Contact du vantail principal", + "contact_second": "Contact du second vantail", + "tool_outdoor": "Extérieur", + "tool_measure": "Aux mesures", + "hint_measure": "Touchez le point de départ, puis saisissez à droite la longueur des murs avec leur direction", + "measure": "Pièce aux mesures", + "measure_start": "Touchez le point de départ dans le plan, p. ex. un coin de pièce.", + "measure_from": "Départ à {x} / {z} m – toucher déplace le départ.", + "measure_length": "Longueur du mur suivant (m)", + "measure_close": "Fermer la pièce", + "measure_undo": "Supprimer le dernier mur", + "measure_gap": "Écart avec le départ : {gap} m (joint à la fermeture)", + "measure_hint": "Astuce : saisissez une longueur et appuyez sur une flèche. Avec des cotes intérieures, utilisez ensuite « Combler les écarts ».", + "rect_by_size": "Rectangle aux dimensions", + "rect_add": "Ajouter un rectangle", + "dir_up": "Haut", + "dir_down": "Bas", + "dir_left": "Gauche", + "dir_right": "Droite", + "hint_outdoor": "Faites glisser pour dessiner un espace extérieur (pelouse, terrasse, piscine …)", + "outdoor": "Espace extérieur", + "outdoor_type": "Type", + "outdoor_height": "Hauteur (m)", + "outdoor_offset": "Décalage de hauteur (m, − = plus bas)", + "outdoor_outline": "Afficher le contour", + "outdoor_outline_hint": "Décoché, l'espace ne trace aucune ligne lumineuse le long de son bord – pour les grands terrains faits de plusieurs pelouses.", + "outdoor_corners_hint": "Coins : un + sur un bord ajoute un coin, faire glisser modèle l'espace, × supprime un coin.", + "outdoor_hint": "Les lumières extérieures (borne d'allée, spot de jardin, applique extérieure) éclairent tous les espaces extérieurs et la façade.", + "out_lawn": "Pelouse", + "out_terrace": "Terrasse", + "out_path": "Allée", + "out_driveway": "Allée carrossable", + "out_pool": "Piscine", + "out_bed": "Massif de fleurs", + "out_hedge": "Haie", + "out_fence": "Clôture", + "out_wild": "Zone sauvage", + "out_pergola": "Pergola / structure", + "outdoor_open": "Ouvert (sans le dernier côté)", + "outdoor_open_hint": "Le côté du dernier point vers le premier n'est pas dessiné – une clôture ou une pergola adossée à la maison.", + "fence_gates": "Portails dans la clôture", + "gate_add": "+ Portail dans la clôture", + "gate_edge": "Côté de la clôture", + "gate_kind": "Type", + "gate_single": "Portillon", + "gate_double": "Portail double", + "gate_sliding": "Portail coulissant", + "gate_offset": "Milieu depuis le début (m)", + "gate_width": "Largeur (m)", + "gate_entity": "Moteur ou interrupteur", + "gate_contact": "Contact (actif = ouvert)", + "fence_gates_hint": "Un portail est une ouverture dans la clôture avec poteaux et vantail. Avec un moteur (cover, interrupteur, input_boolean, serrure) et/ou un contact, il s’ouvre en 3D : portillon et portail double s’ouvrent vers l’intérieur, un portail coulissant glisse le long de la clôture.", + "outdoor_bracing": "Croix de Saint-André", + "outdoor_cut": "Découper dans les espaces environnants", + "outdoor_cut_hint": "Chaque espace qui contient entièrement celui-ci y reçoit un trou – une piscine dans la terrasse, un bassin ou une zone sauvage dans la pelouse. L'ordre de dessin n'a pas d'importance. Une piscine se découpe toute seule.", + "outdoor_area_hint": "La pièce Home Assistant de cette surface (jardin, terrasse, piscine) : ses appareils et capteurs figurent sous Extérieur, et une épingle sur la surface l'ouvre.", + "pool_temp": "Température de l'eau (facultatif)", + "pool_pump": "Pompe / filtre (facultatif)", + "pool_pump_on": "pompe en marche", + "outdoor_slope": "Pente (m)", + "outdoor_slope_hint": "Différence de hauteur entre le bord haut et le bord bas ; le bord haut se trouve au décalage de hauteur. Les lampes de l'espace suivent.", + "outdoor_slope_dir": "Descend vers", + "slope_x": "la droite (+X)", + "slope_nx": "la gauche (−X)", + "slope_z": "le bas (+Z)", + "slope_nz": "le haut (−Z)", + "north": "Nord (° dans le sens horaire depuis le haut)", + "north_hint": "Le nord est nécessaire pour le soleil (lumière à travers les fenêtres).", + "map_on": "Afficher une vraie carte sous le plan", + "map_lat": "Latitude", + "map_lon": "Longitude", + "map_use_ha": "Utiliser la position de Home Assistant", + "map_opacity": "Visibilité (%)", + "map_zoom": "Niveau de détail", + "map_zoom_coarse": "grossier", + "map_zoom_fine": "fin", + "map_move": "Déplacer la carte sous le plan", + "map_step": "Pas", + "map_url": "Adresse de tuiles personnalisée (vide = OpenStreetMap)", + "map_hint": "Votre navigateur charge les tuiles de la carte directement depuis le serveur de cartes (OpenStreetMap par défaut, respectez leur politique d'utilisation) ; rien n'est chargé tant que la carte est désactivée. Le plan se pose sur la carte selon la boussole – tournez la boussole ou déplacez la carte jusqu'à ce que la maison corresponde.", + "compass_title": "Boussole", + "compass_n_short": "N", + "compass_s_short": "S", + "compass_swap": "Inverser nord ↔ sud", + "compass_swap_hint": "Tourne la boussole de 180°. Le dessin, les pans de toit et les champs solaires restent tels quels.", + "compass_hint": "Si la boussole ne correspond pas à la réalité, tournez-la ici – rien n'est à redessiner. L'ensoleillement, le vent et les orientations des pans de toit la suivent.", + "roof": "Toit", + "roof_none": "Pas de toit", + "roof_flat": "Toit plat", + "roof_gable": "Toit à deux pans", + "roof_custom": "Sections de toit (personnalisé)", + "roof_sections": "Sections de toit", + "roof_sections_hint": "Chaque section de toit couvre un rectangle de la maison, p. ex. la maison, la grange ou une extension – chacune avec sa propre forme, direction de faîtage, hauteur d'avant-toit et pente. Faites glisser dans le plan pour en dessiner une nouvelle ; toucher la sélectionne, faire glisser la déplace, les coins la redimensionnent.", + "roof_sections_start": "Créer les sections de toit à partir des pièces", + "roof_sections_regen": "Recréer à partir des pièces", + "roof_sections_off": "Revenir à un seul toit", + "roof_regen_confirm": "Remplacer toutes les sections de toit par une nouvelle proposition issue des pièces ?", + "roof_section": "Section de toit", + "roof_section_hint": "Les hauteurs se comptent depuis le sol. Un côté avec un avant-toit plus bas descend plus loin (rampant asymétrique) ; les toits à un pan montent depuis le premier côté.", + "roof_shape_gable": "Deux pans", + "roof_shape_hip": "Quatre pans", + "roof_shape_pent": "Un pan", + "roof_shape_flat": "Plat", + "roof_shape_halfhip": "Demi-croupe", + "roof_shape_pyramid": "Pyramide", + "roof_shape_mansard": "Mansarde", + "roof_shape_parapet": "Acrotère", + "roof_shape": "Forme", + "roof_axis_x": "Faîtage ↔", + "roof_axis_z": "Faîtage ↕", + "roof_eave": "Avant-toit (m)", + "roof_pitch_short": "Pente (°)", + "roof_height": "Hauteur (m)", + "roof_base": "Haut des murs (m)", + "roof_rotation": "Rotation (°)", + "roof_on_floor": "Posé sur l'étage", + "roof_on_floor_hint": "Pose la section sur le haut des murs de cet étage ; la base et les avant-toits suivent. Dans la vue 3D, le toit appartient à cet étage.", + "roof_base_hint": "Sous la hauteur sous plafond de l'étage inférieur, les murs de cet étage s'arrêtent sous le toit : murs de comble aux avant-toits, pignons jusqu'au faîtage, murs intérieurs coupés par la pente. Les lignes en pointillés du plan montrent où il reste 1,5 m et 2 m de hauteur libre.", + "roof_ridge_height": "Hauteur du faîtage", + "roof_side_top": "haut", + "roof_side_bottom": "bas", + "roof_side_left": "gauche", + "roof_side_right": "droite", + "roof_swap": "Inverser les côtés", + "roof_open": "Auvent (poteaux au lieu de murs, transparent)", + "roof_open_short": "Auvent", + "roof_dormer": "Lucarne", + "roof_dormer_hint": "Une lucarne sur ce côté du toit : 2 m de large, sa façade au mur de l'avant-toit, avant-toit à 1,4 m au-dessus de celui du toit, toit à deux pans. Déplacez-la ensuite et modifiez sa largeur et ses hauteurs comme n'importe quelle section ; le pan principal s'ouvre dessous et le mur du comble monte jusqu'à la lucarne – une fenêtre peut y prendre place.", + "roof_outline": "Reprendre le contour de l'étage", + "roof_outline_hint": "Un toit plat de forme libre : reprend le contour des pièces de l'étage affiché (en L ou en Z aussi) comme une seule surface sans jointure. Les coins peuvent ensuite être déplacés.", + "roof_points_hint": "Forme libre : faites glisser les coins dans le plan, un + sur un bord ajoute un coin, × en supprime un. Revenir au rectangle abandonne la forme.", + "roof_rect": "Revenir au rectangle", + "roof_open_hint": "Pour un toit de terrasse ou un carport : poteaux et poutres portent le toit à la place des murs, et il est transparent. Là où l'auvent rejoint le mur de la maison, il s'appuie sur le mur.", + "roof_swap_hint": "Retourne le toit : les deux côtés échangent avant-toit et pente, un toit à un pan monte dans l'autre sens.", + "roof_pitch": "Pente du toit (°)", + "roof_overhang": "Débord de toit (m)", + "roof_overhang_sides": "Débord par côté", + "roof_overhang_a": "Débord égout A (m)", + "roof_overhang_b": "Débord égout B (m)", + "roof_overhang_u0": "Débord pignon début (m)", + "roof_overhang_u1": "Débord pignon fin (m)", + "roof_overhang_auto": "Revenir à l’automatique", + "roof_overhang_sides_hint": "Sans valeurs propres, le débord est automatique : identique partout, sauf là où la partie de toit touche la maison (aucun).", + "roof_ridge": "Faîtage", + "roof_ridge_long": "Le long du grand côté", + "roof_ridge_short": "Le long du petit côté (p. ex. maison mitoyenne)", + "device": "Appareil", + "lamp_mount": "Lampe", + "lamp_ceiling": "Plafonnier", + "lamp_floor": "Lampadaire", + "lamp_table": "Lampe de table", + "lamp_wall": "Applique", + "marker_height": "Hauteur du repère (m)", + "height_auto": "Hauteur automatique", + "device_centre": "Au centre de la pièce", + "lights_spread": "Répartir les plafonniers uniformément", + "devices_search": "Rechercher des appareils …", + "devices_more": "+{n} de plus", + "devices_less": "moins", + "panel_more": "Autres appareils de la zone ({n})", + "panel_less": "Afficher moins", + "gaps_close": "Combler les écarts", + "gaps_hint": "Joint les pièces distantes de 60 cm au plus par un mur commun ; l'écart devient l'épaisseur du mur intérieur.", + "gaps_none": "Aucun écart trouvé entre les pièces.", + "gaps_closed": "{n} endroits comblés.", + "gaps_closed_wall": "{n} endroits comblés, mur intérieur désormais de {t} m.", + "fps": "FPS", + "fps_title": "Affichage des performances (images par seconde)", + "hint_garage": "Touchez un mur pour ajouter une porte de garage", + "opening_garage": "Porte de garage", + "garage_hint": "La porte suit un volet de garage (position ou ouvert/fermé) ou un contact de porte de garage de la zone de la pièce.", + "door_hint": "Avec un contact de porte, le battant s'ouvre ; sans capteur, il reste entrouvert.", + "hint_door": "Touchez un mur pour ajouter une porte", + "hint_window": "Touchez un mur pour ajouter une fenêtre", + "opening_door": "Porte", + "opening_window": "Fenêtre", + "opening_type": "Type", + "opening_position": "Centre depuis le coin (m)", + "sill": "Hauteur d'allège (m)", + "opening_height": "Hauteur (m)", + "hinge": "Charnière (vue de la pièce)", + "hinge_left": "Gauche", + "hinge_right": "Droite", + "cover_entity": "Volet roulant", + "door_cover": "Motorisation (porte ou portail motorisé)", + "cover_position_entity": "Capteur de position (en direct)", + "cover_position_invert": "Le capteur compte dans l'autre sens (0 = ouvert)", + "contact_entity": "Contact", + "sensor_kind": "Type de capteur", + "sensor_kind_contact": "Contact de fenêtre (ouvert/fermé)", + "sensor_kind_handle": "Capteur de poignée (ouverte/oscillo-battante/fermée)", + "sensor_kind_contact_tilt": "Contact + capteur d'oscillo-battant", + "handle_entity": "Capteur de poignée", + "handle_main": "Capteur de poignée du vantail principal", + "leaf_main": "Vantail principal", + "leaf_second": "Second vantail", + "tilt_entity": "Capteur d'oscillo-battant", + "tilt_angle_entity": "Capteur d'angle d'inclinaison (°, facultatif)", + "tilt_angle_max": "Angle considéré comme pleinement basculé (°)", + "tilt_angle_offset": "Décalage : angle indiqué à l'état fermé (°)", + "tilt_angle_invert": "L'angle compte dans l'autre sens", + "door_shut": "Afficher fermée sans capteur", + "door_shut_hint": "Sans contact, une porte reste entrouverte en 3D pour qu'on la reconnaisse comme porte. Cochée, elle est dessinée fermée – porte d'entrée, abri de voiture, porte latérale.", + "door_angle": "Angle d'ouverture", + "door_angle_default": "Par défaut", + "door_angle_hint": "Jusqu'où le battant s'ouvre. Avec un capteur, il s'ouvre ainsi dès qu'il signale « ouvert » ; sans capteur, il reste ouvert à cet angle (au lieu de moitié). Par défaut, rien ne change.", + "entity_auto": "Automatique ({name})", + "entity_auto_none": "Automatique (aucune trouvée)", + "entity_none": "Aucune", + "entity_search": "Tapez pour rechercher …", + "opening_hint": "Type de capteur : contact de fenêtre (indique ouvert/fermé), capteur de poignée (indique ouvert, basculé et fermé – p. ex. une poignée de fenêtre Homematic) ou contact + capteur d'oscillo-battant (un second capteur qui n'indique que le basculement). Automatique utilise les volets roulants et contacts de la zone de la pièce. Capteur de position : une entité indiquant la position du volet roulant pendant son mouvement (p. ex. un « level » Homematic, 0–100 % ou 0–1, ouvert = valeur haute) – le volet roulant bouge alors en direct en 3D.", + "furniture": "Meubles", + "furniture_add": "Ajouter un meuble", + "studio_new": "Créer son propre meuble", + "studio_title": "Atelier de meubles", + "studio_title_edit": "Atelier de meubles : modifier", + "studio_hint": "Choisis un modèle, règle ses dimensions et ses façades et place le meuble dans le plan. Il rejoint le pack « Mes meubles » et reste modifiable ici.", + "studio_kind": "Modèle", + "studio_kind_cabinet": "Meuble", + "studio_kind_shelf": "Étagère", + "studio_kind_lamp": "Lampe", + "studio_kind_device": "Appareil", + "studio_name": "Nom", + "studio_width": "Largeur (cm)", + "studio_depth": "Profondeur (cm)", + "studio_height": "Hauteur (cm)", + "studio_doors": "Portes", + "studio_drawers": "Tiroirs", + "studio_shelves": "Tablettes", + "studio_handle": "Poignées", + "studio_handle_bar": "Barre", + "studio_handle_knob": "Bouton", + "studio_handle_none": "Sans", + "studio_base": "Socle", + "studio_base_plinth": "Plinthe", + "studio_base_legs": "Pieds", + "studio_base_none": "Aucun", + "studio_back": "Panneau arrière", + "studio_lamp": "Type", + "studio_lamp_floor": "Lampadaire", + "studio_lamp_table": "Lampe de table", + "studio_lamp_pendant": "Suspension", + "studio_lamp_wall": "Applique", + "studio_display": "Écran en façade (montre le lecteur)", + "studio_mount": "Pose", + "studio_mount_floor": "Au sol", + "studio_mount_surface": "Sur un meuble", + "studio_mount_wall": "Au mur", + "studio_color_body": "Corps", + "studio_color_lamp_body": "Pied et structure", + "studio_color_front": "Façades", + "studio_color_boards": "Tablettes", + "studio_color_shade": "Abat-jour", + "studio_color_display": "Cadre de l'écran", + "studio_color_white": "Blanc", + "studio_color_wood": "Bois", + "studio_color_metal": "Métal", + "studio_color_dark": "Foncé", + "studio_color_glass": "Verre", + "studio_color_accent": "Accent", + "studio_color_own": "Couleur perso", + "studio_color_plan": "Couleur du plan", + "studio_place": "Placer dans le plan", + "studio_save": "Enregistrer", + "studio_open": "Modifier dans l'atelier", + "studio_error": "Enregistrement impossible : {detail}", + "studio_pack_name": "Mes meubles", + "studio_pack_publisher": "Atelier de meubles", + "furniture_search": "Rechercher un meuble …", + "furniture_search_none": "Aucun résultat. Essayez un autre mot – en anglais ou en allemand.", + "furniture_type": "Élément", + "rotation": "Rotation (°)", + "tilt_x": "Inclinaison avant/arrière (°)", + "tilt_z": "Inclinaison latérale (°)", + "strip_tilt": "Inclinaison autour de sa longueur (°)", + "strip_upright": "Debout", + "strip_rise": "Pente sur la longueur (°)", + "strip_upright_hint": "Le ruban est dressé : sa longueur part de la hauteur au-dessus du sol – le long d'un encadrement de porte, comme une colonne lumineuse. L'inclinaison plaque un ruban couché contre une pente (90° = sa face regarde sur le côté).", + "rotate_left": "↺ 90°", + "rotate_right": "↻ 90°", + "height_m": "Hauteur (m)", + "furn_sofa": "Canapé", + "furn_armchair": "Fauteuil", + "furn_table": "Table", + "furn_chair": "Chaise", + "furn_bed": "Lit", + "furn_nightstand": "Table de chevet", + "furn_wardrobe": "Armoire", + "furn_shelf": "Étagère", + "furn_kitchen": "Meuble de cuisine", + "furn_worktop": "Plan de travail", + "furn_fridge": "Réfrigérateur", + "furn_fridge_smart": "Réfrigérateur connecté (américain)", + "furn_door_left": "Capteur de porte à gauche (côté congélateur)", + "furn_door_right": "Capteur de porte à droite (côté réfrigérateur)", + "fridge_hint": "Tant qu'un capteur de porte indique ouvert, la porte s'ouvre en 3D.", + "furn_stove": "Cuisinière", + "furn_sink": "Évier", + "furn_bathtub": "Baignoire", + "furn_shower": "Douche", + "furn_wc": "WC", + "furn_washbasin": "Lavabo", + "furn_desk": "Bureau", + "furn_tv_board": "Meuble TV", + "furn_plant": "Plante", + "furn_rug": "Tapis", + "furn_stairs": "Escalier", + "furn_stairwell": "Trémie", + "stairwell_hint": "Un trou dans cet étage, par exemple au-dessus de l'escalier ou pour une galerie ; vu du dessus, on voit à travers. La trémie doit se trouver dans une seule pièce ; plusieurs trémies peuvent se chevaucher (pour une forme en L, par exemple). Les escaliers de l'étage inférieur qui montent jusqu'ici ouvrent aussi le plancher d'eux-mêmes.", + "tool_hole": "Trémie", + "tool_roof": "Toit", + "tool_energy": "Énergie", + "tool_wall": "Mur", + "hint_wall": "Glissez pour tracer un mur isolé (cloison, muret) · Shift le garde droit · Alt sans aimantation", + "free_wall": "Mur", + "wall_length": "Longueur (m)", + "wall_thickness": "Épaisseur du mur (m)", + "wall_height": "Hauteur (m)", + "wall_height_full": "Hauteur totale de la pièce", + "wall_slope": "En pente", + "wall_slope_start": "Hauteur au début (m)", + "wall_slope_end": "Hauteur à la fin (m)", + "wall_slope_hint": "Mur en pente : le haut va en ligne droite de la hauteur au début du mur (l'angle portant le plus petit numéro) à la hauteur à sa fin. Les deux peuvent dépasser la hauteur de l'étage, par exemple pour une pièce à toit monopente avec de hautes fenêtres.", + "wall_slope_off": "Revenir à un mur droit", + "wall_none": "Pas de mur", + "wall_none_hint": "Omettre complètement ce mur : pour les plans ouverts dont les pièces ne forment qu'un seul espace mais sont séparées dans Home Assistant.", + "edge_thickness": "Épaisseur (m)", + "wall_thickness_hint": "Épaisseur de ce mur, p. ex. 0,365 pour un épais mur extérieur ou 0,115 pour une cloison légère. Un mur entre deux pièces prend le réglage le plus épais.", + "wall_thickness_reset": "Épaisseur définie pour la maison", + "wall_heights": "Hauteurs des murs", + "wall_n": "Mur {a}–{b}", + "wall_view": "Vue du mur", + "wall_view_hint": "Le mur vu de face : faites glisser ses portes, fenêtres et meubles ou saisissez leur distance.", + "wall_view_prev": "Mur précédent", + "wall_view_next": "Mur suivant", + "wall_view_left": "Depuis la gauche (m)", + "wall_view_height": "Au-dessus du sol (m)", + "wall_part": "partie {n}", + "wall_split_hint": "Diviser le mur ici : la partie a sa propre hauteur, p. ex. 2,5 m à côté de 1,7 m à la suite", + "wall_split_at": "Point de division depuis l'angle (m)", + "wall_join_hint": "Supprimer le point de division : la partie rejoint à nouveau la précédente", + "wall_exterior_short": "mur extérieur", + "room_wall_hint": "Une hauteur plus faible transforme le mur en garde-corps ou en comptoir. Si deux pièces partagent le mur, le réglage le plus bas s'applique. Les fenêtres et portes qu'il contient s'arrêtent à la hauteur du mur.", + "free_wall_hint": "Un mur isolé, p. ex. une cloison. Là où il rejoint un mur de pièce, l'angle est biseauté. Glissez les poignées pour déplacer ses extrémités, glissez la ligne pour déplacer tout le mur.", + "free_wall_slope": "◢ En pente", + "free_wall_slope_hint": "Le mur monte ou descend d’un bout à l’autre : la hauteur au-dessus est au début, celle-ci à la fin.", + "free_wall_height_end": "Hauteur à la fin (m)", + "stairwell_outside": "Cette trémie dépasse la limite d'une pièce et n'est donc pas découpée. Placez-la entièrement dans une pièce ou réduisez-la.", + "hint_hole": "Glissez pour tracer une trémie (escalier, galerie)", + "hint_roof": "Glissez pour tracer un pan de toit · toucher sélectionne · glisser déplace · les coins redimensionnent", + "hint_energy": "Touchez un champ solaire pour le sélectionner · glissez pour le déplacer, y compris sur un autre pan de toit · nouveaux champs avec + Champ solaire à droite", + "furn_parking": "Place de stationnement", + "furn_group_vehicles": "Stationnement", + "parking_entity": "Capteur « voiture présente »", + "parking_vehicle": "Véhicule", + "parking_vehicle_none": "Aucun", + "parking_no_pack": "Aucun pack de véhicules importé – les véhicules viennent du pack « Véhicules » (Extensions → Packs de meubles).", + "parking_scale": "Taille (%)", + "parking_type_entity": "Capteur de type de véhicule (facultatif)", + "parking_types": "État → véhicule", + "parking_type_state": "État (p. ex. van)", + "parking_add_type": "+ Correspondance", + "parking_hint": "Sans capteur, le véhicule est toujours là. Avec un capteur, il apparaît dès que celui-ci indique « on », « home » ou « present ». Un capteur de type de véhicule (p. ex. issu d'une analyse de caméra par IA) choisit le modèle : si son état correspond à une association – y compris comme mot dans le texte – ce véhicule s'affiche, sinon le véhicule par défaut.", + "parking_too_tall": "Le véhicule ({car} m) est plus haut que la pièce ({room} m).", + "furn_lamp_ceiling": "Plafonnier", + "furn_lamp_downlight": "Spot encastré", + "furn_lamp_spot": "Spot en saillie", + "furn_lamp_panel": "Panneau LED", + "furn_lamp_uplight": "Liseuse au sol", + "furn_lamp_bollard": "Borne lumineuse", + "furn_lamp_garden": "Spot de jardin", + "furn_radiator": "Radiateur", + "furn_robot_vacuum": "Robot aspirateur", + "furn_entity_vacuum": "Robot aspirateur", + "furn_entity_mower": "Robot tondeuse", + "pet_room_sensor": "Capteur de pièce de l'animal (facultatif)", + "pet_room_hint": "Un capteur qui nomme la pièce où se trouve l'animal – Bermuda ou ESPresense avec une balise au collier : en 3D il se promène alors dans cette pièce.", + "furn_entity_water": "Vanne ou interrupteur", + "fridge_temp": "Température du réfrigérateur", + "freezer_temp": "Température du congélateur", + "fridge_temp_hint": "Le repère affiche les températures. Au-dessus de 8 °C au réfrigérateur ou de −12 °C au congélateur, il s'allume en alerte.", + "spray_reach": "Portée de l'eau (m)", + "spray_hint": "Tant que la vanne est ouverte ou l'interrupteur allumé, l'arroseur projette de l'eau en arcs autour de lui.", + "furn_robot_room": "Pièce actuelle (capteur)", + "robot_hint": "Pendant que le robot nettoie dans Home Assistant, il circule en 3D par bandes dans la pièce qu'il indique (un capteur de « pièce actuelle », associé par nom de pièce ou de zone), sinon dans la pièce de sa base. Le trajet est simulé – Home Assistant ne connaît généralement pas la position exacte. Il retourne à la base lorsqu'il rentre.", + "furn_lamp_pendant": "Suspension", + "furn_ceiling_fan": "Ventilateur de plafond", + "furn_fan_entity": "Ventilateur", + "fan_hint": "La lumière est le kit d'éclairage du ventilateur (laissez vide s'il n'en a pas). Le ventilateur est trouvé dans la pièce ou choisi ici : en 3D, les pales tournent à sa vitesse, son icône l'allume ou l'éteint, un balayage haut/bas change la vitesse, un appui long ouvre le menu rapide. La hauteur est la distance de suspension au plafond (plus = une tige plus longue).", + "room_ceiling": "Hauteur sous plafond", + "room_ceiling_tip": "Plus bas que l'étage (une salle de bain sous l'escalier) ou plus haut (un séjour ouvert jusque sous le toit) : plafonniers, ventilateurs, rubans LED et appareils de plafond sont suspendus à partir d'ici, et les murs de la pièce ont cette hauteur.", + "room_ceiling_through": "Le plafond ({ceiling} m) est plus haut que l'étage ({floor} m) : la pièce monte dans l'étage du dessus, ses murs suivent, et l'étage du dessus reste ouvert au-dessus d'elle. L'éditeur de l'étage supérieur montre la zone hachurée.", + "room_floor_offset": "Niveau du sol (m)", + "room_floor_offset_hint": "Si le sol de cette pièce est plus bas ou plus haut que l'étage (une entrée en contrebas : −0,39), sol, murs, portes, fenêtres et ce qui s'y trouve suivent ; le plafond reste. Ajoute les marches comme un escalier.", + "room_inner": "Intérieur {w} × {d}", + "room_inner_hint": "Mesuré de mur à mur : les murs intérieurs prennent la moitié de leur épaisseur, les murs extérieurs sont hors du contour.", + "floor_heating": "Plancher chauffant (facultatif)", + "floor_heating_hint": "Tant que le thermostat chauffe (ou que la vanne est ouverte, l'interrupteur activé), le sol de la pièce rougeoie en 3D.", + "room_announce_speaker": "Haut-parleur des annonces", + "room_announce_quiet": "Heure calme pour les annonces", + "room_announce_hint": "Sans choix, c'est le haut-parleur placé dans la pièce qui parle, sinon un assistant vocal, un Echo ou un haut-parleur de sa zone (jamais un téléviseur). Pendant l'heure calme, les annonces à plusieurs pièces ignorent celle-ci ; une annonce pour elle seule passe quand même.", + "ceiling_here": "Plafond ici", + "ceiling_here_hint": "Hauteur du plafond à cet endroit précis, p. ex. sous un plafond en pente. Vide = le plafond de la pièce.", + "ceiling_slope": "Sous le rampant", + "ceiling_slope_hint": "Ici le plafond est sous le rampant : la lampe est suspendue à sa face inférieure, juste au-dessus de sa place.", + "furn_lamp_floor": "Lampadaire", + "furn_lamp_table": "Lampe de table", + "furn_lamp_wall": "Applique", + "furn_led_strip": "Ruban LED", + "furn_group_lights": "Lumières", + "furn_entity_light": "Lumière ou interrupteur", + "furn_color_entity": "Couleur et luminosité depuis (facultatif)", + "furn_color_entity_hint": "Pour les lumières qu'un relais (Shelly, actionneur) allume et éteint alors que l'ampoule connaît elle-même sa couleur et sa luminosité : l'allumage/extinction vient de l'interrupteur ci-dessus, la couleur et la luminosité de cette entité.", + "lamp_extra_light": "Ampoule {n} (facultatif)", + "lamp_extra_hint": "Un luminaire à plusieurs lumières – principale, veilleuse, anneau d'ambiance : lorsque la principale est éteinte, il brille en 3D avec la suivante allumée, un peu plus faiblement. Allumez-les une par une dans le panneau de la pièce.", + "furn_entity_climate": "Chauffage (thermostat)", + "lamp_hint": "Touchez la lampe en 3D pour l'allumer ou l'éteindre, appui long pour le menu rapide. Les interrupteurs fonctionnent aussi (p. ex. un relais pour le plafonnier) – la lampe brille tant qu'il est allumé. Les lampes de table reposent sur les meubles situés en dessous.", + "lamp_hint_pendant": "Hauteur = longueur sous le plafond. Touchez en 3D pour allumer/éteindre, appui long pour les détails.", + "theme": "Apparence", + "version_hint": "Version installée de NextFloor – l'interface ; l'intégration dans Home Assistant indique {backend}", + "accent": "Couleur d'accent", + "accent_hint": "Une couleur d'accent personnelle : lignes et bords lumineux dans le thème Néon, boutons et repères – ↺ rétablit le cyan néon", + "accent_reset": "Revenir au cyan", + "theme_neon": "Néon", + "theme_blueprint": "Plan", + "theme_day": "Jour", + "theme_auto": "Auto", + "clock": "Horloge", + "clock_none": "Aucune", + "clock_top_left": "En haut à gauche", + "clock_top_right": "En haut à droite", + "clock_bottom_left": "En bas à gauche", + "clock_bottom_right": "En bas à droite", + "glass_walls": "Murs vitrés", + "glass_walls_hint": "Opacité des murs à travers lesquels on voit les pièces : à gauche presque invisibles, à droite opaques. Pour cet écran.", + "screen_name": "Nom de cet écran", + "screen_name_hint": "Les annonces s'affichent sur chaque écran NextFloor ouvert. Avec un nom (p. ex. « Entrée »), une annonce peut viser cet écran seul. Décoché, cet écran reste muet.", + "announce_on": "Annonces activées sur cet écran", + "announce_muted": "Annonces coupées sur cet écran", + "lock3d_on": "Verrouiller la 3D (ni rotation, ni zoom, ni déplacement ; les appuis restent actifs)", + "lock3d_off": "Déverrouiller la 3D", + "walk": "Se promener dans la maison", + "walk_stop": "Arrêter la promenade", + "walk_hint": "Glisser : regarder autour · Z Q S D / flèches ou joystick : avancer · molette : pas", + "card_walk_button": "Bouton de promenade", + "card_lock_button": "Bouton de verrouillage de la 3D", + "backdrop": "Fond personnalisé", + "backdrop_color": "Couleur", + "backdrop_image": "Image (/local/… ou https://…)", + "backdrop_dim": "Assombrir", + "backdrop_hint": "Au lieu du ciel de l'apparence, la maison se détache sur une couleur ou une image de votre choix. Une image placée dans /config/www est accessible sous /local/….", + "furnish": "Aménager", + "split_3d": "3D à côté", + "plan_dims": "Cotes", + "plan_dims_hint": "Écrit sa longueur sur chaque bord de pièce.", + "mount_height": "Hauteur au-dessus du sol (m)", + "side_open": "Ouvrir la barre latérale", + "side_close": "Fermer", + "side_details": "Détails de la sélection", + "side_pin": "Épingler", + "side_pinned": "Épinglée", + "side_pin_hint": "Épinglée, la barre latérale reste ouverte ; sinon elle se replie à côté de la vue 3D tant que rien n'est sélectionné", + "split_3d_hint": "3D en direct à côté du plan : déplacez et faites pivoter meubles et appareils directement – avec annulation, enregistré avec le plan", + "size_w": "Largeur (m)", + "size_d": "Profondeur (m)", + "size_h": "Hauteur (m)", + "furnish_hint": "Glissez meubles, lampes et appareils · les meubles s'aimantent aux murs · touchez-en un pour le tourner, régler sa hauteur et sa fixation", + "done": "Terminé", + "heatmap": "Carte de chaleur", + "heat_off": "Normal", + "heat_short_temperature": "Temp.", + "heat_short_humidity": "Humidité", + "heat_short_co2": "CO₂", + "heat_short_mould": "Moisissure", + "heat_short_power": "Conso.", + "heat_short_comfort": "Confort", + "heat_short_sun": "Soleil", + "heat_short_wifi": "Wi-Fi", + "heat_short_values": "Valeurs", + "heat_temperature": "Température", + "heat_humidity": "Humidité", + "heat_co2": "CO₂", + "heat_mould": "Moisissure", + "heat_power": "Consommation", + "heat_comfort": "Indice de confort", + "heat_sun": "Soleil aujourd'hui", + "room_sun_hours": "{h} h de soleil aujourd'hui ({facing})", + "open_since": "ouvert depuis {time}", + "presence_now": "quelqu'un est là", + "presence_last": "vu il y a {time}", + "comfort_n": "Confort {n}", + "empty_lights_hint": "{n} lumières allumées, personne depuis {min} min.", + "empty_lights_off": "Éteindre", + "open_heating_hint": "{n} fenêtres ouvertes pendant que le chauffage tourne.", + "open_heating_off": "Chauffage éteint", + "room_clean": "Nettoyage (script ou bouton)", + "room_clean_hint": "Un script ou bouton qui envoie l'aspirateur robot dans cette pièce (p. ex. le nettoyage par pièce de ton intégration). Le panneau de la pièce affiche alors « 🧹 Nettoyer ».", + "room_clean_run": "Nettoyer", + "room_clean_run_hint": "Envoie l'aspirateur robot dans cette pièce.", + "shade_hint": "Soleil sur {n} fenêtres à {temp} – baisser les volets ?", + "shade_close": "Baisser", + "room_sun_year": "Soleil sur l'année", + "room_sun_year_hint": "Les heures de soleil par les fenêtres extérieures de la pièce le 15 de chaque mois.", + "room_energy": "aujourd'hui {today} · mois {month}", + "room_energy_hint": "D'après les statistiques des capteurs de puissance des appareils de la pièce ; le coût du mois au tarif de la maison.", + "heat_summer": "été", + "heat_winter": "hiver", + "air_co2": "aérer (CO₂)", + "air_humidity": "aérer (humide)", + "air_mould": "risque de moisissure – aérer", + "room_curve_hint": "La température de la pièce sur les dernières 24 heures", + "heat_values": "Valeurs aux noms des pièces", + "heat_wifi": "Wi-Fi", + "wifi_aps": "{n} points d'accès · {clients} appareils", + "wifi_network": "Réseau : {online} en ligne · {offline} hors ligne", + "wifi_none": "Placez des points d'accès ou routeurs des packs (Maison connectée 2) et liez-les à une entité de leur appareil.", + "wifi_clients": "{n} appareils", + "heat_none_found": "Aucun capteur correspondant dans les zones des pièces.", + "markers": "Repères", + "markers_none": "Aucun", + "markers_important": "Importants", + "markers_all": "Tous", + "furn_stool": "Tabouret", + "furn_coffee_table": "Table basse", + "furn_tv_wall": "TV (murale)", + "furn_sideboard": "Buffet", + "furn_table_round": "Table ronde", + "furn_bench": "Banc", + "furn_corner_bench": "Banquette d'angle", + "furn_bar_stool": "Tabouret de bar", + "furn_kitchen_wall": "Meuble haut", + "furn_kitchen_tall": "Colonne avec four", + "furn_island": "Îlot de cuisine", + "furn_dishwasher": "Lave-vaisselle", + "furn_bunk_bed": "Lits superposés", + "furn_dresser": "Commode", + "furn_washer": "Lave-linge", + "furn_dryer": "Sèche-linge", + "furn_office_chair": "Chaise de bureau", + "furn_tall_cabinet": "Armoire haute", + "furn_coat_rack": "Portemanteau", + "furn_group_living": "Séjour", + "furn_group_dining": "Repas", + "furn_group_energy": "Énergie et solaire", + "energy_devices": "Appareils", + "wallbox_charging": "en charge", + "wallbox_plugged": "branché", + "furn_soc": "État de charge (%)", + "furn_export": "Puissance d'injection (W, capteur séparé, facultatif)", + "furn_export_hint": "Si votre compteur indique l'import et l'export dans deux capteurs (p. ex. Growatt, Tibber Pulse), prenez le capteur d'import comme puissance ci-dessus et le capteur d'export ici. Un capteur signé n'en a pas besoin.", + "meter_parent": "Dépend du compteur", + "meter_parent_none": "aucun (compteur principal)", + "meter_main": "Compteur principal", + "meter_unmetered": "{w} non mesurés", + "meter_device_hint": "Si l'appareil se trouve derrière un sous-compteur (p. ex. une installation de balcon dans un logement), sa puissance compte pour ce logement. Pour cela, le sous-compteur doit mesurer dans les deux sens (− = réinjection) ; s'il ne compte que l'import, la consommation du logement ressort trop élevée en cas d'excédent.", + "meter_sub_power": "Puissance de la branche (W, + = soutirage, − = réinjection)", + "meter_floors": "Alimente les étages", + "meter_sub_hint": "Un sous-compteur mesure sa branche, p. ex. un logement. Les appareils des étages cochés en dépendent en 3D au lieu du compteur principal ; ce que le compteur principal compte en plus apparaît comme « Commun (reste) » dans le bilan.", + "furn_charge": "Puissance de charge (W, capteur séparé, facultatif)", + "furn_charge_hint": "Si votre batterie indique la charge et la décharge dans deux capteurs (p. ex. Anker Solix), prenez le capteur de décharge comme puissance ci-dessus et le capteur de charge ici. Un capteur signé n'en a pas besoin.", + "furn_wallbox_status": "État (en charge, branché)", + "energy_only_note": "⚡ Énergie : seuls les champs solaires et les appareils d'énergie peuvent être déplacés ici ; pièces et meubles sont verrouillés.", + "roof_only_note": "🏠 Toit : seuls les pans de toit et les fenêtres de toit peuvent être déplacés ici ; pièces et meubles sont verrouillés.", + "energy_devices_hint": "Compteur, onduleurs, batteries domestiques, bornes de recharge et raccordement au réseau s'ajoutent ici : sur l'étage choisi ci-dessus, déplaçables dans le plan. Avec un capteur de puissance, ils affichent leurs watts ; le compteur prend le capteur de réseau, un string choisit son onduleur. Plusieurs onduleurs et batteries (par exemple une installation de balcon en plus) fonctionnent aussi : chacun a son propre capteur.", + "energy_routes": "Tracés de câble", + "energy_routes_hint": "Là où un câble passe vraiment : le flux suit alors tes points au lieu d'un arc à travers la maison. Sans tracé, l'arc reste. Les consommateurs gardent leur arc.", + "route_conn_solar": "{name} → onduleur", + "route_conn_battery": "Batterie ↔ maison", + "route_conn_inverter": "Onduleur → maison", + "route_conn_grid": "Réseau ↔ maison", + "route_conn_meter": "{name} ↔ compteur parent", + "route_conn_device": "{name} ↔ sous-compteur", + "route_points": "{n} points", + "route_none": "arc direct", + "route_draw": "Tracer", + "route_redraw": "Retracer", + "route_drawing": "Touche sur le plan les points par lesquels passe le câble, d'un bout à l'autre ; change d'étage entre-temps là où il traverse un plafond. {n} points.", + "route_undo": "Dernier point", + "route_done": "Terminé", + "route_cable": "Afficher comme câble", + "route_cable_hint": "Dessine le tracé comme un câble visible, pas seulement comme la fine ligne sous les particules.", + "solar_fields": "Champs solaires", + "solar_hint": "Posez des modules sur le toit : ils suivent la pente du pan de toit ; sur un toit plat, ils reposent sur des supports. Glissez un champ dans le plan pour le déplacer.", + "solar_no_roof": "Les champs solaires ont besoin d'un toit : un toit à deux pans ou plat dans les réglages, ou des pans de toit ici avec l'outil Toit.", + "solar_face_gone": "pan de toit manquant", + "solar_summary": "{n} modules · {kwp} kWc", + "solar_add": "Champ solaire", + "solar_field": "Champ solaire", + "solar_face": "Pan de toit", + "solar_rows": "Rangées", + "solar_cols": "Modules par rangée", + "solar_portrait": "Portrait", + "solar_landscape": "Paysage", + "solar_u": "Distance au bord (m)", + "solar_v": "Distance à l'avant-toit (m)", + "solar_tilt": "Inclinaison des supports (°)", + "solar_rack_ew": "Support est-ouest", + "solar_rack_ew_hint": "Une rangée sur deux est tournée dans l'autre sens, les paires dos à dos – bas et serré, comme sur beaucoup de toits plats.", + "solar_rack_tilt": "Support (° d'inclinaison en plus)", + "solar_flip": "Incliner dans l'autre sens", + "solar_partial": "seulement {n} sur {total} tiennent sur le pan", + "solar_form_hint": "Les modules qui dépasseraient du pan de toit sont omis. « Remplir le pan » pose autant de modules que le toit peut en accueillir. kWc calculé avec 400 W par module.", + "solar_fit": "Remplir le pan", + "roof_windows": "Fenêtres de toit", + "roof_window": "Fenêtre de toit", + "roof_windows_hint": "Les fenêtres de toit sont intégrées au pan de toit, avec un volet roulant et des contacts comme les fenêtres. Glissez-les dans le plan, y compris sur un autre pan de toit.", + "roof_window_tilt": "Contact de basculement", + "roof_window_name": "Nom (facultatif)", + "roof_window_motor": "Moteur de fenêtre (volet, facultatif)", + "roof_window_motor_hint": "Un moteur de fenêtre (Velux, Roto, Fakro) indique sa position comme un volet : l'ouvrant s'ouvre en 3D autant que le moteur. Un contact ou contact de basculement fonctionne toujours sans moteur.", + "roof_window_hint": "Ouvert, l'ouvrant bascule vers l'extérieur, articulé en haut ; basculé, un peu ; le cadre s'illumine en teinte chaude ; le volet roulant descend sur la vitre depuis le haut. Dans un pan de toit, la fenêtre découpe un trou dans la pente, et les combles donnent ainsi sur l'extérieur.", + "solar_ground": "Au sol (jardin, toit de garage …)", + "solar_add_ground": "Au sol", + "solar_base": "Hauteur de la surface (m, 0 = sol)", + "solar_add_wall": "Sur un mur", + "solar_wall": "Mur", + "solar_v_wall": "Hauteur au-dessus du sol (m)", + "solar_tilt_wall": "Inclinaison par rapport au mur (°, 90 = auvent)", + "solar_flip_wall": "Écarté en bas plutôt qu'en haut", + "solar_rotation": "Rotation (°)", + "solar_name": "Nom", + "solar_name_hint": "p. ex. string 1 sud", + "solar_module_w": "Largeur du module (m)", + "solar_module_h": "Hauteur du module (m)", + "solar_wp": "Puissance du module (Wc)", + "solar_string": "String", + "solar_strings": "Strings", + "solar_string_none": "Aucun string", + "solar_string_new": "Nouveau string", + "solar_string_n": "String {n}", + "solar_string_name": "Nom du string", + "solar_string_entity": "Puissance PV du string", + "solar_string_inverter": "Onduleur", + "solar_string_inverter_none": "Aucun onduleur choisi", + "inverter_strings": "Strings sur cet onduleur : {names}", + "inverter_strings_none": "Aucun string sur cet onduleur pour l'instant – affectez-le à un champ solaire sous String › Onduleur.", + "solar_string_inverter_missing": "Aucun onduleur dans le plan pour l'instant (ajoutez-en un plus bas sous Appareils)", + "solar_string_hint": "Les champs d'un même string vont ensemble, même sur des toits différents (p. ex. 5 modules sur la maison et 5 sur le garage). Le capteur et l'onduleur valent pour tout le string.", + "solar_string_sum": "{fields} champs · {n} modules · {kwp} kWc", + "solar_face_size": "Pan de toit {w} × {h} m (le long de l'avant-toit × le long de la pente)", + "solar_cols_hint": "Un seul nombre pour des rangées de même longueur, ou une liste pour des rangées distinctes : « 4, 4, 3 » (depuis l'avant-toit).", + "solar_align_left": "Gauche", + "solar_align_center": "Centre", + "solar_align_right": "Droite", + "solar_look_black": "Full black", + "solar_look_blue": "Bleu", + "solar_pick": "Modules activés/désactivés un par un", + "solar_pick_all": "Tout réactiver", + "solar_pick_hint": "Touchez un module dans le plan pour le retirer ou le remettre. Les modules retirés sont en pointillés.", + "solar_entity": "Puissance PV de ce champ (p. ex. son string)", + "solar_main": "Toit principal", + "solar_section": "Pan {n}", + "solar_flat": "toit plat", + "compass_n": "nord", + "compass_ne": "nord-est", + "compass_e": "est", + "compass_se": "sud-est", + "compass_s": "sud", + "compass_sw": "sud-ouest", + "compass_w": "ouest", + "compass_nw": "nord-ouest", + "furn_meter": "Compteur électrique", + "furn_grid_point": "Raccordement au réseau", + "grid_point_hint": "Le raccordement au réseau se trouve ici : le point de livraison du fournisseur, p. ex. au bout de l'allée carrossable. Déplaçable dans le plan.", + "furn_model": "Modèle", + "inverter_std": "Standard (boîtier mural avec écran)", + "inverter_slim": "Fin et haut (bandeau lumineux)", + "inverter_hybrid": "Hybride (cadran rond, ventilateurs)", + "battery_std": "Tour (modules empilés)", + "battery_wall": "Batterie murale (plate, suspendue)", + "battery_cube": "Compacte (batterie de balcon)", + "furn_inverter": "Onduleur solaire", + "furn_home_battery": "Batterie domestique", + "furn_wallbox": "Borne de recharge", + "furn_group_kitchen": "Cuisine", + "furn_group_sleeping": "Chambre", + "furn_group_bath": "Salle de bain et buanderie", + "furn_group_work": "Travail et autres", + "furn_entity": "Appareil (interrupteur, prise …)", + "furn_state_entity": "État depuis (facultatif)", + "furn_state_entity2": "Second état (l'autre moitié)", + "furn_tap": "Un appui sur le meuble", + "furn_tap_default": "Comme d'habitude", + "furn_tap_hint": "Une action à vous, comme les boutons perso du menu étoile : par exemple un pop-up browser_mod avec votre carte.", + "furn_show_when": "Afficher seulement tant que …", + "furn_show_when_state": "… est dans l'état (vide = activé)", + "furn_show_when_invert": "À l'inverse : afficher tant que ce n'est pas le cas", + "furn_show_when_hint": "Une déco de saison qui n'apparaît qu'en décembre : une entrée (input_boolean), un calendrier ou un capteur décide si l'objet s'affiche en 3D. Séparez plusieurs états par des virgules. L'éditeur l'affiche toujours.", + "picture_upload": "Importer une photo", + "picture_replace": "Importer une autre photo", + "picture_stored": "Une photo personnelle est enregistrée.", + "picture_url": "… ou adresse de l'image", + "picture_entity": "… ou l'image d'une entité", + "picture_border": "Passe-partout (%)", + "picture_fit": "Photo", + "picture_fit_cover": "remplit le cadre", + "picture_fit_contain": "visible en entier", + "picture_hint": "Votre photo dans le cadre, en 3D et sur la tablette murale. Les photos importées sont réduites et enregistrées avec le plan ; une entité image (photo du jour) ou une caméra montre son image actuelle.", + "furn_state_split": "Moitiés", + "furn_state_left_right": "Gauche / droite", + "furn_state_top_bottom": "Bas / haut (lits superposés)", + "furn_state_hint": "L'élément s'illumine tant que l'entité indique on, occupé ou présent – un lit avec un tapis de présence, un fauteuil, le sauna. Deux entités éclairent les moitiés : gauche et droite, bas et haut pour des lits superposés.", + "furn_entity_tv": "TV (lecteur multimédia ou prise connectée)", + "fix": "Fixer", + "unfix": "Libérer", + "fix_hint": "Fixé : ne peut plus être déplacé par erreur (touche L, clic droit ou appui long)", + "fixed_drag_hint": "🔒 Fixé – libérez-le d'abord pour le déplacer (verrou dans le formulaire, clic droit ou touche L)", + "fixed_delete_confirm": "Cet élément est fixé. Le supprimer quand même ?", + "lock_plan": "🔒 Plan", + "lock_plan_hint": "Verrouiller le plan : pièces, murs, portes, fenêtres et espaces extérieurs ne peuvent plus être déplacés par erreur. Les meubles et appareils restent libres.", + "start_view": "Vue de départ", + "start_view_hint": "La vue 3D, la carte et le mode kiosque ouvrent la maison avec cette vue, p. ex. côté jardin. Tournez, zoomez et déplacez la maison dans le volet 3D à droite jusqu'à ce qu'elle convienne, puis mémorisez-la.", + "start_view_card": "Si une carte doit s'ouvrir avec une autre vue, ajoutez cette ligne à sa configuration YAML.", + "start_view_set": "Mémoriser la vue 3D actuelle comme vue de départ", + "start_view_reset": "Par défaut", + "start_view_saved": "Une vue de départ personnalisée est enregistrée.", + "ctx_rotate": "Pivoter de 90°", + "devices_placed_in": "dans {room}", + "devices_narrow": "{n} de plus – affinez la recherche", + "climate": "Climat de la pièce", + "climate_temperature": "Température", + "climate_humidity": "Humidité", + "climate_co2": "CO₂", + "climate_hint": "Ces capteurs servent à la carte de chaleur et au panneau de la pièce. « Automatique » prend les capteurs de la zone et ceux placés dans la pièce, mais pas les températures d'appareils (imprimante 3D, pompe à chaleur, départ …).", + "climate_more": "… et un autre capteur (moyenne)", + "plan_locked": "Plan verrouillé", + "plan_lock": "Verrouiller le plan", + "plan_unlock": "Déverrouiller le plan", + "opening_mark": "Mettre en évidence en 3D", + "opening_mark_open": "Quand ouverte", + "opening_mark_closed": "Quand fermée (p. ex. WC)", + "opening_mark_hint": "Une fenêtre ou une porte mise en évidence s'illumine en teinte chaude. « Quand fermée » nécessite un contact ; sans capteur, rien n'est mis en évidence.", + "window_opens": "S'ouvre", + "window_opens_turn": "Oscillo-battant (vers l'intérieur)", + "window_opens_slide": "Coulissant (fenêtre coulissante, porte à levage)", + "window_opens_top": "À l'italienne (le bas s'ouvre vers l'extérieur)", + "window_opens_hint": "Coulissant : le vantail côté charnière glisse devant le fixe ; à deux vantaux, les deux du milieu glissent vers l'extérieur. Les fenêtres à l'italienne s'ouvrent avec leur contact ou un capteur d'inclinaison.", + "marker_show": "Repère en 3D", + "marker_show_hint": "Automatique suit le sélecteur Aucun / Importants / Tous de la vue 3D. Toujours afficher et Masquer s'appliquent dans tous les cas (sauf avec Aucun).", + "pin_shift": "Déplacer l'épingle", + "pin_shift_up": "↑ hauteur", + "pin_shift_hint": "Quand des appareils sont proches, décalez ici l'épingle un peu sur le côté ou vers le haut (en mètres) ; l'appareil reste à sa place.", + "marker_show_auto": "Automatique", + "marker_show_always": "Toujours afficher", + "marker_show_no_power": "Sans watts", + "marker_show_active": "Seulement si actif", + "marker_show_never": "Masquer", + "marker_icon": "Symbole personnalisé (icône Material Design)", + "device_name": "Nom personnalisé (facultatif)", + "show_name": "Afficher le nom sous le repère en 3D", + "card_marker_names": "Noms personnalisés sur les repères", + "card_marker_names_hint": "Chaque appareil ayant un nom personnalisé l'affiche en petit sous son repère – trois thermomètres dans le jardin restent distincts.", + "card_tap_in_room": "Piloter les appareils seulement dans la pièce ouverte", + "card_tap_in_room_hint": "Vue maison et vue étage : un appui ouvre l'étage ou la pièce, même sur un appareil ou son repère. Dans la pièce ouverte, il pilote l'appareil. L'appui long ouvre toujours son menu ou sa fiche.", + "card_markers_outside": "Choisir les repères hors de la pièce ouverte", + "card_markers_outside_hint": "Dans la maison, sur l'étage et dans les autres pièces, seulement les types cochés ; dans la pièce ouverte, tous, comme réglé plus haut. « Toujours » et « Jamais » réglés sur un appareil passent avant.", + "marker_kind_light": "Lumières", + "marker_kind_cover": "Volets", + "marker_kind_climate": "Chauffage", + "marker_kind_media": "Médias", + "marker_kind_switch": "Interrupteurs", + "marker_kind_fan": "Ventilateurs", + "marker_kind_lock": "Serrures", + "marker_kind_binary": "Contacts et détecteurs", + "marker_kind_sensor": "Capteurs", + "marker_kind_tap": "Meubles avec une action", + "marker_kind_other": "Autres", + "device_name_hint": "Un nom pour le plan et le panneau de la pièce uniquement, p. ex. « Éclairage d'ambiance de l'îlot » – l'entité dans Home Assistant reste inchangée.", + "device_simple": "Seulement allumer/éteindre dans le panneau", + "device_simple_hint": "Le panneau de la pièce n'affiche que l'interrupteur de cette lampe, sans luminosité, température de couleur ni couleurs.", + "floor_turn": "Pivoter de 90°", + "floor_shift_all": "Entraîner tous les étages (toute la maison)", + "floor_shift_all_hint": "Le déplacement et la rotation agissent sur chaque étage avec les pans de toit, espaces extérieurs, appareils d'énergie et compteur – toute la maison bouge d'un bloc.", + "floor_turn_hint": "Pivote tout l'étage de 90° dans le sens horaire autour du centre de ses pièces – quand un étage a été dessiné à l'envers. Trois fois = 270°.", + "marker_icon_hint": "Le nom d'une icône Material Design comme dans Home Assistant, p. ex. mdi:thermometer ou mdi:water-alert. Vide = le symbole du type d'appareil.", + "furn_power": "Capteur de puissance (W)", + "furn_links_hint": "Avec un capteur de puissance, l'élément affiche ses watts et participe au flux d'énergie.", + "furn_links_hint_tv": "L'écran s'illumine quand la TV est allumée, dans la couleur de l'application (Netflix, YouTube …) ; l'étiquette indique l'application ou le titre.", + "stairs_hint": "L'escalier monte vers l'arrière (à l'opposé du bord avant marqué) et ouvre le plafond de l'étage du dessus.", + "floor_lights": "{n} lumières allumées", + "floor_open": "{n} ouvert(s)", + "floor_persons": "{n} personnes", + "energy_consumption": "Consommation", + "energy_grid_import": "Import réseau", + "energy_grid_export": "Export", + "energy_solar": "Solaire", + "energy_battery": "Batterie", + "energy_tariff": "Tarif", + "energy": "Énergie", + "energy_meter": "Compteur", + "energy_grid": "Réseau (W, + = import)", + "energy_solar_sensor": "Production solaire (W)", + "energy_battery_sensor": "Puissance de la batterie (W, + = décharge)", + "energy_battery_soc": "Charge de la batterie (%)", + "energy_tariff_sensor": "Tarif (p. ex. €/kWh)", + "energy_gas": "Compteur de gaz (facultatif)", + "energy_water": "Compteur d'eau (facultatif)", + "energy_meters_hint": "Le gaz et l'eau apparaissent avec le bilan de la maison – dans la barre d'énergie et sur la carte de la maison : un capteur du débit actuel (m³/h, l/min) ou du relevé du jour.", + "energy_gas_short": "Gaz", + "energy_water_short": "Eau", + "energy_invert": "Inverser le signe", + "energy_hint": "Les consommateurs sont des appareils placés avec un capteur de puissance (W) – le capteur lui-même ou un capteur du même appareil.", + "energy_balance": "Bilan énergétique", + "energy_balance_hint": "Réseau, solaire et batterie proviennent des appareils du plan : compteur, onduleur et batterie domestique. Ici, vous pouvez choisir d'autres capteurs, inverser les signes et définir la consommation de la maison.", + "energy_rest": "Commun (reste)", + "energy_advanced": "Mode énergie avancé", + "energy_advanced_on": "Utiliser des sous-compteurs", + "energy_show_unmetered": "Afficher la consommation non mesurée aux sous-compteurs", + "energy_show_unmetered_hint": "L'étiquette d'un sous-compteur indique alors ce que consomment ses étages et la part qu'aucun appareil placé ne mesure, p. ex. « 500 W · 450 W non mesurés ». Sinon, elle affiche la valeur du compteur.", + "energy_advanced_hint": "Pour les sous-compteurs, p. ex. un par logement derrière un compteur principal : un compteur peut alors dépendre d'un autre et alimenter ses propres étages. Désactivé = le premier compteur est le raccordement au réseau, les suivants sont des consommateurs.", + "energy_consumption_sensor": "Consommation de la maison (W, sinon issue du bilan)", + "energy_import_prefs": "Reprendre depuis le tableau de bord Énergie", + "energy_import_done": "{n} capteurs repris – vérifiez les signes.", + "energy_import_none": "Aucun capteur de puissance (W) correspondant n'a été trouvé dans le tableau de bord Énergie – choisissez-les à la main.", + "energy_import_failed": "Le tableau de bord Énergie de Home Assistant n'est pas configuré.", + "tool_meter": "Compteur", + "hint_meter": "Touchez l'emplacement du compteur", + "presence": "Présence", + "presence_hint": "Capteur de pièce par personne (p. ex. ESPresense, Bermuda) : son état indique la pièce ou la zone.", + "presence_sensor": "Capteur de pièce", + "no_persons": "Il n'y a aucune personne dans Home Assistant.", + "packname:nextfloor.a_bad": "Salle de bain", + "pack:nextfloor.a_bad:vanity_60": "Meuble vasque 60 avec meuble bas", + "pack:nextfloor.a_bad:vanity_80": "Meuble vasque 80 avec meuble bas", + "pack:nextfloor.a_bad:vanity_100": "Meuble vasque 100 avec meuble bas", + "pack:nextfloor.a_bad:vanity_double_120": "Meuble double vasque 120", + "pack:nextfloor.a_bad:vanity_double_160": "Meuble double vasque", + "pack:nextfloor.a_bad:pedestal_basin": "Lavabo sur colonne", + "pack:nextfloor.a_bad:bathtub_builtin": "Baignoire encastrée", + "pack:nextfloor.a_bad:bathtub_corner": "Baignoire d'angle", + "pack:nextfloor.a_bad:bathtub_corner_compact": "Baignoire d'angle compacte", + "pack:nextfloor.a_bad:bathtub_free": "Baignoire îlot", + "pack:nextfloor.a_bad:whirlpool_indoor": "Bain à remous intérieur", + "pack:nextfloor.a_bad:shower_corner_90": "Douche d'angle 90 × 90", + "pack:nextfloor.a_bad:shower_niche_120": "Douche en niche 120 × 90", + "pack:nextfloor.a_bad:shower_walkin_140": "Douche à l'italienne 140 × 90", + "pack:nextfloor.a_bad:shower_walkin_120": "Douche à l'italienne", + "pack:nextfloor.a_bad:shower_rain_led": "Douche pluie avec LED", + "pack:nextfloor.a_bad:toilet_close": "WC à poser", + "pack:nextfloor.a_bad:toilet_hung": "WC suspendu", + "pack:nextfloor.a_bad:toilet_hung_compact": "WC suspendu (compact)", + "pack:nextfloor.a_bad:bidet": "Bidet", + "pack:nextfloor.a_bad:cabinet_tall": "Colonne de salle de bain", + "pack:nextfloor.a_bad:cabinet_mid": "Meuble de salle de bain mi-hauteur", + "pack:nextfloor.a_bad:mirror_round_light": "Miroir rond avec éclairage", + "pack:nextfloor.a_bad:mirror_80": "Miroir 80 × 60 avec éclairage", + "pack:nextfloor.a_bad:mirror_led_100": "Miroir LED 100 × 70 avec horloge", + "pack:nextfloor.a_bad:mirror_cabinet": "Armoire de toilette avec éclairage", + "pack:nextfloor.a_bad:wall_shelf_bath": "Étagère murale de salle de bain", + "pack:nextfloor.a_bad:towel_rail": "Porte-serviettes avec serviette", + "pack:nextfloor.a_bad:towel_radiator": "Sèche-serviettes", + "pack:nextfloor.a_bad:towel_heater_electric": "Sèche-serviettes électrique", + "pack:nextfloor.a_bad:sauna": "Sauna", + "pack:nextfloor.a_bad:bath_fan": "Ventilateur de salle de bain", + "pack:nextfloor.a_bad:washer_cabinet": "Meuble pour lave-linge", + "pack:nextfloor.a_bad:washer_under_vanity": "Lave-linge sous le meuble vasque", + "pack:nextfloor.a_bad:laundry_basket": "Panier à linge", + "pack:nextfloor.a_bad:laundry_cabinet": "Meuble à linge avec panier", + "pack:nextfloor.a_bad:ladder_shelf": "Étagère échelle avec serviettes", + "pack:nextfloor.a_bad:plant_stool": "Plante sur tabouret", + "packname:nextfloor.a_buero": "Bureau et gaming", + "pack:nextfloor.a_buero:desk_standing": "Bureau assis-debout", + "pack:nextfloor.a_buero:desk_standing_bare": "Bureau assis-debout sans écran", + "pack:nextfloor.a_buero:chair_gaming": "Chaise gaming", + "pack:nextfloor.a_buero:chair_office": "Chaise de bureau ergonomique", + "pack:nextfloor.a_buero:sim_cockpit": "Cockpit de simulation de course", + "pack:nextfloor.a_buero:server_rack_42u": "Baie de serveur (42U)", + "pack:nextfloor.a_buero:filing_cabinet": "Classeur à tiroirs", + "pack:nextfloor.a_buero:whiteboard": "Tableau blanc", + "pack:nextfloor.a_buero:triple_monitor": "Triple écran", + "pack:nextfloor.a_buero:bookcase_wall": "Bibliothèque murale", + "pack:nextfloor.a_buero:desk_lamp": "Lampe de bureau", + "pack:nextfloor.a_buero:desk_lamp_led": "Lampe de bureau LED", + "pack:nextfloor.a_buero:arcade_cabinet": "Borne d'arcade", + "pack:nextfloor.a_buero:office_lounge_sofa": "Canapé lounge de bureau", + "pack:nextfloor.a_buero:monitor_light_bar": "Écran avec barre lumineuse", + "pack:nextfloor.a_buero:printer_laser": "Imprimante laser", + "pack:nextfloor.a_buero:wifi_router": "Routeur Wi-Fi", + "pack:nextfloor.a_buero:phone_booth": "Cabine téléphonique", + "pack:nextfloor.a_buero:printer_3d": "Imprimante 3D", + "pack:nextfloor.a_buero:printer_cube": "Imprimante 3D cube fermée", + "pack:nextfloor.a_buero:printer_multi": "Imprimante 3D cube avec module multicolore", + "pack:nextfloor.a_buero:printer_large": "Grande imprimante 3D double buse", + "pack:nextfloor.a_buero:printer_open": "Imprimante 3D ouverte compacte", + "pack:nextfloor.a_buero:printer_resin": "Imprimante 3D résine", + "pack:nextfloor.a_buero:filament_dryer": "Sécheur de filament", + "pack:nextfloor.a_buero:filament_rack": "Support mural pour filament", + "packname:nextfloor.a_fitness": "Fitness", + "pack:nextfloor.a_fitness:treadmill": "Tapis de course", + "pack:nextfloor.a_fitness:power_rack": "Rack de musculation avec banc", + "pack:nextfloor.a_fitness:rowing_machine": "Rameur", + "pack:nextfloor.a_fitness:spin_bike": "Vélo de spinning", + "pack:nextfloor.a_fitness:dumbbell_rack": "Rack d'haltères", + "pack:nextfloor.a_fitness:punching_bag": "Sac de frappe", + "pack:nextfloor.a_fitness:yoga_mat": "Tapis de yoga avec brique", + "pack:nextfloor.a_fitness:elliptical": "Vélo elliptique", + "pack:nextfloor.a_fitness:mirror_wall_gym": "Mur de miroirs", + "pack:nextfloor.a_fitness:exercise_ball": "Ballon de gym", + "pack:nextfloor.a_fitness:wall_bars": "Espalier", + "pack:nextfloor.a_fitness:fitness_mirror_smart": "Miroir de fitness connecté", + "pack:nextfloor.a_fitness:bike_trainer": "Vélo sur home trainer connecté", + "pack:nextfloor.a_fitness:sauna_cabin": "Cabine de sauna", + "pack:nextfloor.a_fitness:massage_chair": "Fauteuil de massage", + "pack:nextfloor.a_fitness:kettlebells": "Set de kettlebells", + "pack:nextfloor.a_fitness:water_cooler": "Fontaine à eau", + "packname:nextfloor.a_garten": "Jardin et terrasse", + "pack:nextfloor.a_garten:grill_gas": "Barbecue à gaz", + "pack:nextfloor.a_garten:lounge_set": "Salon de jardin", + "pack:nextfloor.a_garten:sun_lounger_adj": "Bain de soleil", + "pack:nextfloor.a_garten:parasol": "Parasol", + "pack:nextfloor.a_garten:pergola": "Pergola", + "pack:nextfloor.a_garten:raised_bed": "Carré potager surélevé", + "pack:nextfloor.a_garten:greenhouse": "Serre", + "pack:nextfloor.a_garten:hot_tub": "Spa extérieur", + "pack:nextfloor.a_garten:fire_bowl": "Brasero", + "pack:nextfloor.a_garten:garden_torch": "Torche de jardin", + "pack:nextfloor.a_garten:play_tower": "Tour de jeux avec toboggan", + "pack:nextfloor.a_garten:garden_shed": "Abri de jardin", + "pack:nextfloor.a_garten:trampoline": "Trampoline", + "pack:nextfloor.a_garten:flower_pots": "Pots de fleurs (lot de 3)", + "pack:nextfloor.a_garten:sprinkler": "Arroseur de pelouse", + "pack:nextfloor.a_garten:valve_box": "Boîtier de vannes d'arrosage", + "pack:nextfloor.a_garten:rain_barrel": "Récupérateur d'eau de pluie", + "pack:nextfloor.a_garten:garden_lantern": "Lanterne de jardin", + "pack:nextfloor.a_garten:outdoor_kitchen": "Cuisine d'extérieur", + "pack:nextfloor.a_garten:hammock": "Hamac avec support", + "pack:nextfloor.a_garten:patio_heater": "Chauffage de terrasse", + "pack:nextfloor.a_garten:tree_oak": "Chêne", + "pack:nextfloor.a_garten:tree_lime": "Tilleul", + "pack:nextfloor.a_garten:tree_birch": "Bouleau", + "pack:nextfloor.a_garten:tree_maple": "Érable", + "pack:nextfloor.a_garten:tree_fruit": "Arbre fruitier", + "pack:nextfloor.a_garten:tree_spruce": "Épicéa", + "pack:nextfloor.a_garten:tree_pine": "Pin", + "pack:nextfloor.a_garten:tree_thuja": "Thuya", + "pack:nextfloor.a_garten:shrub": "Arbuste", + "pack:nextfloor.a_garten:shrub_flowering": "Arbuste à fleurs", + "pack:nextfloor.a_garten:brush_wild": "Broussailles (zone sauvage)", + "pack:nextfloor.a_garten:tree_group_3": "Groupe d'arbres (3)", + "packname:nextfloor.a_haustechnik": "Local technique et équipements du bâtiment", + "pack:nextfloor.a_haustechnik:gas_boiler": "Chaudière gaz à condensation", + "pack:nextfloor.a_haustechnik:heat_pump_tower": "Unité intérieure de pompe à chaleur (module hydraulique)", + "pack:nextfloor.a_haustechnik:buffer_tank": "Ballon tampon", + "pack:nextfloor.a_haustechnik:heating_manifold": "Collecteur de plancher chauffant", + "pack:nextfloor.a_haustechnik:ventilation_unit": "Ventilation avec récupération de chaleur", + "pack:nextfloor.a_haustechnik:split_indoor": "Climatiseur split (unité intérieure, murale)", + "pack:nextfloor.a_haustechnik:split_outdoor": "Climatiseur split (unité extérieure)", + "pack:nextfloor.a_haustechnik:radiator_tall": "Radiateur design haut", + "pack:nextfloor.a_haustechnik:meter_cabinet": "Armoire à compteurs", + "pack:nextfloor.a_haustechnik:water_softener": "Adoucisseur d'eau", + "pack:nextfloor.a_haustechnik:water_pump": "Surpresseur d'eau domestique", + "pack:nextfloor.a_haustechnik:drip_tray": "Bac de rétention avec détecteur de fuite", + "pack:nextfloor.a_haustechnik:chest_freezer": "Congélateur coffre", + "pack:nextfloor.a_haustechnik:ironing_station": "Centrale vapeur de repassage", + "pack:nextfloor.a_haustechnik:drying_rack": "Étendoir à linge", + "pack:nextfloor.a_haustechnik:rotary_line": "Séchoir rotatif", + "pack:nextfloor.a_haustechnik:pantry_shelf_util": "Étagère de cellier", + "pack:nextfloor.a_haustechnik:utility_sink": "Évier de buanderie", + "pack:nextfloor.a_haustechnik:laundry_basket_util": "Panier à linge", + "pack:nextfloor.a_haustechnik:vacuum_station": "Station d'aspirateur sans fil", + "packname:nextfloor.a_haustiere": "Animaux", + "pack:nextfloor.a_haustiere:cat_tree_large": "Grand arbre à chat", + "pack:nextfloor.a_haustiere:scratch_post": "Griffoir", + "pack:nextfloor.a_haustiere:scratch_board_wall": "Planche à griffer (murale)", + "pack:nextfloor.a_haustiere:cat_cave": "Niche pour chat", + "pack:nextfloor.a_haustiere:cat_bed_round": "Panier rond pour chat", + "pack:nextfloor.a_haustiere:cat_wall_shelf": "Étagère murale pour chat", + "pack:nextfloor.a_haustiere:cat_steps": "Marches d'escalade pour chat", + "pack:nextfloor.a_haustiere:litter_covered": "Litière couverte", + "pack:nextfloor.a_haustiere:litter_auto": "Litière autonettoyante", + "pack:nextfloor.a_haustiere:dog_bed": "Coussin pour chien", + "pack:nextfloor.a_haustiere:dog_basket": "Panier pour chien", + "pack:nextfloor.a_haustiere:dog_house": "Niche pour chien", + "pack:nextfloor.a_haustiere:pet_bowls": "Gamelles d'eau et de nourriture", + "pack:nextfloor.a_haustiere:pet_feeder": "Distributeur automatique de croquettes", + "pack:nextfloor.a_haustiere:pet_fountain": "Fontaine à eau pour animaux", + "pack:nextfloor.a_haustiere:pet_gate": "Barrière pour animaux", + "pack:nextfloor.a_haustiere:pet_stairs": "Escalier pour animaux", + "pack:nextfloor.a_haustiere:hamster_cage": "Cage à hamster", + "pack:nextfloor.a_haustiere:small_animal_cage": "Cage pour petit animal", + "pack:nextfloor.a_haustiere:rabbit_run": "Enclos pour lapin (extérieur)", + "pack:nextfloor.a_haustiere:bird_cage": "Cage à oiseaux", + "pack:nextfloor.a_haustiere:aquarium_100": "Aquarium 100 l", + "pack:nextfloor.a_haustiere:aquarium_240": "Aquarium 240 l avec meuble", + "pack:nextfloor.a_haustiere:terrarium": "Terrarium", + "packname:nextfloor.a_kinderzimmer": "Chambre d'enfant", + "pack:nextfloor.a_kinderzimmer:loft_bed_slide": "Lit mezzanine avec toboggan", + "pack:nextfloor.a_kinderzimmer:teepee": "Tipi", + "pack:nextfloor.a_kinderzimmer:play_kitchen": "Cuisine de jeu", + "pack:nextfloor.a_kinderzimmer:kids_desk": "Bureau enfant", + "pack:nextfloor.a_kinderzimmer:toy_shelf": "Étagère à jouets avec bacs", + "pack:nextfloor.a_kinderzimmer:cosy_corner": "Coin douillet", + "pack:nextfloor.a_kinderzimmer:rocking_horse": "Cheval à bascule", + "pack:nextfloor.a_kinderzimmer:play_mat_road": "Tapis de jeu route", + "pack:nextfloor.a_kinderzimmer:kids_table_2": "Table enfant avec 2 chaises", + "pack:nextfloor.a_kinderzimmer:moon_light": "Veilleuse lune", + "pack:nextfloor.a_kinderzimmer:ball_pit": "Piscine à balles", + "pack:nextfloor.a_kinderzimmer:house_bed": "Lit cabane", + "pack:nextfloor.a_kinderzimmer:baby_monitor": "Babyphone avec caméra", + "pack:nextfloor.a_kinderzimmer:star_projector": "Projecteur d'étoiles", + "pack:nextfloor.a_kinderzimmer:kids_cot": "Lit bébé", + "pack:nextfloor.a_kinderzimmer:kids_changing_table": "Table à langer", + "pack:nextfloor.a_kinderzimmer:kids_wardrobe": "Armoire enfant", + "pack:nextfloor.a_kinderzimmer:toy_boxes_3": "Coffres à jouets (3)", + "packname:nextfloor.a_kino": "Home cinéma et hi-fi", + "pack:nextfloor.a_kino:screen_wall": "Écran de projection (mural)", + "pack:nextfloor.a_kino:screen_roll": "Écran de projection enroulable", + "pack:nextfloor.a_kino:projector_ceiling": "Vidéoprojecteur (plafond)", + "pack:nextfloor.a_kino:projector_table": "Vidéoprojecteur (table)", + "pack:nextfloor.a_kino:speaker_floor": "Enceinte colonne", + "pack:nextfloor.a_kino:speaker_shelf": "Enceinte bibliothèque", + "pack:nextfloor.a_kino:speaker_centre": "Enceinte centrale", + "pack:nextfloor.a_kino:subwoofer": "Caisson de basses", + "pack:nextfloor.a_kino:soundbar": "Barre de son", + "pack:nextfloor.a_kino:soundbar_premium": "Barre de son premium", + "pack:nextfloor.a_kino:speaker_wall": "Enceinte murale", + "pack:nextfloor.a_kino:speaker_ceiling": "Enceinte de plafond", + "pack:nextfloor.a_kino:av_receiver": "Amplificateur audio-vidéo", + "pack:nextfloor.a_kino:turntable": "Platine vinyle", + "pack:nextfloor.a_kino:record_shelf": "Étagère à vinyles", + "pack:nextfloor.a_kino:game_console": "Console de jeux", + "pack:nextfloor.a_kino:hifi_rack": "Meuble hi-fi", + "pack:nextfloor.a_kino:cinema_seat": "Fauteuil de cinéma", + "pack:nextfloor.a_kino:cinema_row_3": "Rangée de fauteuils de cinéma (3)", + "pack:nextfloor.a_kino:acoustic_panel": "Panneau acoustique", + "pack:nextfloor.a_kino:bass_trap": "Bass trap (angle)", + "pack:nextfloor.a_kino:popcorn_maker": "Machine à pop-corn", + "pack:nextfloor.a_kino:star_ceiling": "Ciel étoilé", + "pack:nextfloor.a_kino:smart_speaker_ball": "Enceinte connectée (boule)", + "pack:nextfloor.a_kino:smart_speaker_cylinder": "Enceinte connectée (cylindre)", + "pack:nextfloor.a_kino:smart_speaker_puck": "Enceinte connectée (palet)", + "pack:nextfloor.a_kino:smart_speaker_pod": "Enceinte connectée (capsule)", + "pack:nextfloor.a_kino:smart_speaker_tall": "Enceinte connectée (haute)", + "pack:nextfloor.a_kino:smart_speaker_oval": "Enceinte connectée (ovale)", + "pack:nextfloor.a_kino:multiroom_compact": "Enceinte multiroom compacte", + "pack:nextfloor.a_kino:speaker_portable": "Enceinte portable", + "pack:nextfloor.a_kino:display_5": "Écran connecté 5″", + "pack:nextfloor.a_kino:display_8": "Écran connecté 8″", + "pack:nextfloor.a_kino:display_7_float": "Écran connecté 7″ (flottant)", + "pack:nextfloor.a_kino:display_15_wall": "Écran connecté 15″ (mural)", + "pack:nextfloor.a_kino:speaker_stand": "Pied d'enceinte", + "packname:nextfloor.a_kueche": "Cuisine", + "pack:nextfloor.a_kueche:base_30": "Meuble bas 30", + "pack:nextfloor.a_kueche:base_40": "Meuble bas 40", + "pack:nextfloor.a_kueche:base_50": "Meuble bas 50", + "pack:nextfloor.a_kueche:base_60": "Meuble bas 60", + "pack:nextfloor.a_kueche:base_80": "Meuble bas 80", + "pack:nextfloor.a_kueche:base_90": "Meuble bas 90", + "pack:nextfloor.a_kueche:base_100": "Meuble bas 100", + "pack:nextfloor.a_kueche:base_120": "Meuble bas 120", + "pack:nextfloor.a_kueche:drawer_40": "Meuble bas à tiroirs 40", + "pack:nextfloor.a_kueche:drawer_50": "Meuble bas à tiroirs 50", + "pack:nextfloor.a_kueche:drawer_60": "Meuble bas à tiroirs 60", + "pack:nextfloor.a_kueche:drawer_80": "Meuble bas à tiroirs 80", + "pack:nextfloor.a_kueche:drawer_90": "Meuble bas à tiroirs 90", + "pack:nextfloor.a_kueche:drawer_100": "Meuble bas à tiroirs 100", + "pack:nextfloor.a_kueche:drawer_120": "Meuble bas à tiroirs 120", + "pack:nextfloor.a_kueche:sink_60": "Meuble sous évier 60", + "pack:nextfloor.a_kueche:sink_80": "Meuble sous évier 80", + "pack:nextfloor.a_kueche:sink_100": "Meuble sous évier 100", + "pack:nextfloor.a_kueche:hob_60": "Meuble plaque de cuisson 60", + "pack:nextfloor.a_kueche:hob_80": "Meuble plaque de cuisson 80", + "pack:nextfloor.a_kueche:cooker_60": "Cuisinière avec four 60", + "pack:nextfloor.a_kueche:dishwasher_60": "Lave-vaisselle encastrable 60", + "pack:nextfloor.a_kueche:dishwasher_45": "Lave-vaisselle encastrable 45", + "pack:nextfloor.a_kueche:base_corner": "Meuble bas d'angle", + "pack:nextfloor.a_kueche:wall_40": "Meuble haut 40", + "pack:nextfloor.a_kueche:wall_50": "Meuble haut 50", + "pack:nextfloor.a_kueche:wall_60": "Meuble haut 60", + "pack:nextfloor.a_kueche:wall_80": "Meuble haut 80", + "pack:nextfloor.a_kueche:wall_90": "Meuble haut 90", + "pack:nextfloor.a_kueche:wall_100": "Meuble haut 100", + "pack:nextfloor.a_kueche:wall_120": "Meuble haut 120", + "pack:nextfloor.a_kueche:wall_glass_80": "Meuble haut vitré 80", + "pack:nextfloor.a_kueche:wall_corner": "Meuble haut d'angle", + "pack:nextfloor.a_kueche:hood_wall": "Hotte murale", + "pack:nextfloor.a_kueche:hood_island": "Hotte îlot", + "pack:nextfloor.a_kueche:tall_pantry": "Colonne garde-manger", + "pack:nextfloor.a_kueche:tall_oven": "Colonne four et micro-ondes", + "pack:nextfloor.a_kueche:tall_fridge": "Colonne réfrigérateur-congélateur", + "pack:nextfloor.a_kueche:tall_steam": "Colonne four vapeur et four", + "pack:nextfloor.a_kueche:fridge_freezer": "Réfrigérateur-congélateur", + "pack:nextfloor.a_kueche:fridge_french": "Réfrigérateur à portes françaises", + "pack:nextfloor.a_kueche:wine_fridge": "Cave à vin", + "pack:nextfloor.a_kueche:glass_cabinet": "Vitrine", + "pack:nextfloor.a_kueche:row_270": "Ligne de cuisine 270", + "pack:nextfloor.a_kueche:row_330": "Ligne de cuisine 330", + "pack:nextfloor.a_kueche:island_bar": "Îlot de cuisine avec bar", + "pack:nextfloor.a_kueche:island_hob": "Îlot de cuisine avec plaque de cuisson", + "pack:nextfloor.a_kueche:breakfast_bar": "Bar de petit-déjeuner (mural)", + "pack:nextfloor.a_kueche:bar_stools_2": "Tabourets de bar (lot de 2)", + "pack:nextfloor.a_kueche:dining_bench_long": "Longue table à manger avec banc", + "pack:nextfloor.a_kueche:dining_round_4": "Table à manger ronde avec 4 chaises", + "pack:nextfloor.a_kueche:high_table_2": "Table haute avec 2 tabourets", + "pack:nextfloor.a_kueche:kitchen_trolley": "Desserte de cuisine", + "pack:nextfloor.a_kueche:pantry_shelf": "Étagère de garde-manger", + "pack:nextfloor.a_kueche:spice_rack": "Étagère à épices murale", + "pack:nextfloor.a_kueche:coffee_machine": "Machine à café à grains", + "pack:nextfloor.a_kueche:microwave": "Micro-ondes", + "pack:nextfloor.a_kueche:stand_mixer": "Robot pâtissier", + "pack:nextfloor.a_kueche:kettle": "Bouilloire", + "pack:nextfloor.a_kueche:toaster": "Grille-pain", + "pack:nextfloor.a_kueche:herb_garden": "Potager d'intérieur connecté", + "pack:nextfloor.a_kueche:pendant_trio": "Trio de suspensions", + "pack:nextfloor.a_kueche:pendant_linear": "Suspension linéaire", + "pack:nextfloor.a_kueche:cabinet_light_60": "Éclairage LED sous meuble 60", + "pack:nextfloor.a_kueche:cabinet_light_80": "Éclairage LED sous meuble 80", + "pack:nextfloor.a_kueche:range_cooker_90": "Piano de cuisson 90", + "packname:nextfloor.a_schlafzimmer": "Chambre", + "pack:nextfloor.a_schlafzimmer:bed_90": "Lit 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_140": "Lit 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_160": "Lit 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_180": "Lit 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_200": "Lit 200 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_180": "Lit capitonné 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_140": "Lit capitonné 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_boxspring": "Lit boxspring 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_futon": "Lit futon 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_storage": "Lit avec rangement 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_canopy": "Lit à baldaquin", + "pack:nextfloor.a_schlafzimmer:bed_ambient": "Lit 180 avec éclairage d'ambiance", + "pack:nextfloor.a_schlafzimmer:bed_bench": "Banc de lit", + "pack:nextfloor.a_schlafzimmer:shoe_bench": "Banc à chaussures", + "pack:nextfloor.a_schlafzimmer:wardrobe_2": "Armoire 2 portes", + "pack:nextfloor.a_schlafzimmer:wardrobe_3": "Armoire 3 portes", + "pack:nextfloor.a_schlafzimmer:wardrobe_4": "Armoire 4 portes", + "pack:nextfloor.a_schlafzimmer:wardrobe_6": "Armoire 6 portes", + "pack:nextfloor.a_schlafzimmer:wardrobe_mirror": "Armoire avec porte miroir", + "pack:nextfloor.a_schlafzimmer:wardrobe_sliding": "Armoire à portes coulissantes", + "pack:nextfloor.a_schlafzimmer:wardrobe_light": "Armoire avec éclairage intérieur", + "pack:nextfloor.a_schlafzimmer:wardrobe_corner": "Armoire d'angle", + "pack:nextfloor.a_schlafzimmer:walk_in_closet": "Dressing ouvert", + "pack:nextfloor.a_schlafzimmer:clothes_rail": "Portant à vêtements", + "pack:nextfloor.a_schlafzimmer:nightstand": "Table de chevet avec tiroir", + "pack:nextfloor.a_schlafzimmer:nightstand_slim": "Table de chevet étroite", + "pack:nextfloor.a_schlafzimmer:nightstand_floating": "Table de chevet suspendue", + "pack:nextfloor.a_schlafzimmer:dresser_6": "Commode 6 tiroirs 140", + "pack:nextfloor.a_schlafzimmer:chest_tall_5": "Chiffonnier 5 tiroirs", + "pack:nextfloor.a_schlafzimmer:chest_tall": "Chiffonnier", + "pack:nextfloor.a_schlafzimmer:chest_80": "Commode 3 tiroirs 80", + "pack:nextfloor.a_schlafzimmer:vanity_table": "Coiffeuse avec miroir", + "pack:nextfloor.a_schlafzimmer:dressing_table_light": "Coiffeuse avec miroir lumineux", + "pack:nextfloor.a_schlafzimmer:cot": "Lit bébé", + "pack:nextfloor.a_schlafzimmer:changing_table": "Table à langer", + "pack:nextfloor.a_schlafzimmer:standing_mirror": "Miroir sur pied", + "pack:nextfloor.a_schlafzimmer:reading_nook": "Coin lecture avec fauteuil", + "pack:nextfloor.a_schlafzimmer:bedside_lamp": "Lampe de chevet", + "pack:nextfloor.a_schlafzimmer:touch_lamp": "Lampe de chevet tactile", + "pack:nextfloor.a_schlafzimmer:humidifier": "Humidificateur", + "pack:nextfloor.a_schlafzimmer:sunrise_clock": "Réveil lumière", + "packname:nextfloor.a_smart": "Maison connectée et technique", + "pack:nextfloor.a_smart:wallbox": "Borne de recharge", + "pack:nextfloor.a_smart:electric_car": "Voiture électrique", + "pack:nextfloor.a_smart:heat_pump_outdoor": "Pompe à chaleur (unité extérieure)", + "pack:nextfloor.a_smart:home_battery": "Batterie domestique", + "pack:nextfloor.a_smart:inverter_solar": "Onduleur solaire", + "pack:nextfloor.a_smart:robot_vacuum": "Robot aspirateur avec station", + "pack:nextfloor.a_smart:mower_garage": "Tondeuse robot avec abri", + "pack:nextfloor.a_smart:washer_dryer_stack": "Colonne lave-linge et sèche-linge", + "pack:nextfloor.a_smart:network_rack": "Baie de brassage", + "pack:nextfloor.a_smart:smart_display": "Écran connecté", + "pack:nextfloor.a_smart:solar_balcony": "Panneau solaire de balcon", + "pack:nextfloor.a_smart:fuse_box": "Tableau électrique", + "pack:nextfloor.a_smart:nas_server": "Serveur NAS", + "pack:nextfloor.a_smart:hot_water_tank": "Ballon d'eau chaude", + "pack:nextfloor.a_smart:light_pillar": "Colonne lumineuse dégradée", + "pack:nextfloor.a_smart:light_bars_tv": "Paire de barres lumineuses (TV)", + "pack:nextfloor.a_smart:orb_lamp": "Lampe de table sphère lumineuse", + "pack:nextfloor.a_smart:glow_lamp_portable": "Lampe lumineuse portable", + "pack:nextfloor.a_smart:mood_spot": "Spot d'ambiance de table", + "pack:nextfloor.a_smart:cube_lamp": "Lampe cube", + "pack:nextfloor.a_smart:ceiling_panel_round": "Plafonnier rond", + "pack:nextfloor.a_smart:garden_spots_3": "Spots de jardin (lot de 3)", + "pack:nextfloor.a_smart:wall_light_updown": "Applique extérieure haut et bas", + "pack:nextfloor.a_smart:siren_strobe": "Sirène avec flash", + "pack:nextfloor.a_smart:access_point": "Borne Wi-Fi (plafond)", + "pack:nextfloor.a_smart:smoke_detector": "Détecteur de fumée", + "pack:nextfloor.a_smart:thermostat_wall": "Thermostat mural", + "pack:nextfloor.a_smart:dehumidifier": "Déshumidificateur", + "pack:nextfloor.a_smart:ceiling_fan": "Ventilateur de plafond", + "pack:nextfloor.a_smart:ceiling_fan_light": "Ventilateur de plafond avec lumière", + "packname:nextfloor.a_wohnzimmer": "Salon", + "pack:nextfloor.a_wohnzimmer:sofa_2": "Canapé 2 places", + "pack:nextfloor.a_wohnzimmer:sofa_3": "Canapé 3 places", + "pack:nextfloor.a_wohnzimmer:sofa_4": "Grand canapé 4 places", + "pack:nextfloor.a_wohnzimmer:sofa_velvet": "Canapé 3 places en velours", + "pack:nextfloor.a_wohnzimmer:sofa_armless": "Canapé sans accoudoirs", + "pack:nextfloor.a_wohnzimmer:sofa_chaise": "Canapé avec méridienne", + "pack:nextfloor.a_wohnzimmer:sofa_chesterfield": "Canapé Chesterfield", + "pack:nextfloor.a_wohnzimmer:sofa_bed": "Canapé-lit", + "pack:nextfloor.a_wohnzimmer:sofa_corner_l": "Canapé d'angle (gauche)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_r": "Canapé d'angle (droit)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_xl": "Grand canapé d'angle (en L)", + "pack:nextfloor.a_wohnzimmer:sofa_u": "Canapé en U", + "pack:nextfloor.a_wohnzimmer:chaise_longue": "Chaise longue", + "pack:nextfloor.a_wohnzimmer:modular_sofa": "Canapé modulable (5 éléments)", + "pack:nextfloor.a_wohnzimmer:armchair": "Fauteuil", + "pack:nextfloor.a_wohnzimmer:club_chair": "Fauteuil club", + "pack:nextfloor.a_wohnzimmer:wingback": "Fauteuil à oreilles", + "pack:nextfloor.a_wohnzimmer:cocktail_chair": "Fauteuil cocktail", + "pack:nextfloor.a_wohnzimmer:recliner": "Fauteuil relax avec repose-pieds", + "pack:nextfloor.a_wohnzimmer:bean_bag": "Pouf poire", + "pack:nextfloor.a_wohnzimmer:pouf": "Pouf", + "pack:nextfloor.a_wohnzimmer:rocking_chair": "Fauteuil à bascule", + "pack:nextfloor.a_wohnzimmer:coffee_rect": "Table basse rectangulaire", + "pack:nextfloor.a_wohnzimmer:coffee_glass": "Table basse en verre", + "pack:nextfloor.a_wohnzimmer:coffee_round": "Table basse ronde", + "pack:nextfloor.a_wohnzimmer:coffee_nesting": "Tables basses gigognes", + "pack:nextfloor.a_wohnzimmer:side_round": "Table d'appoint ronde", + "pack:nextfloor.a_wohnzimmer:console": "Console", + "pack:nextfloor.a_wohnzimmer:dining_120": "Table à manger 120 × 90", + "pack:nextfloor.a_wohnzimmer:dining_160": "Table à manger 160 × 90", + "pack:nextfloor.a_wohnzimmer:dining_200": "Table à manger 200 × 90", + "pack:nextfloor.a_wohnzimmer:dining_220": "Table à manger en bois massif 220 × 100", + "pack:nextfloor.a_wohnzimmer:chair_wood": "Chaise en bois", + "pack:nextfloor.a_wohnzimmer:chair_upholstered": "Chaise rembourrée", + "pack:nextfloor.a_wohnzimmer:chair_shell": "Chaise coque", + "pack:nextfloor.a_wohnzimmer:dining_bench": "Banc de salle à manger 160", + "pack:nextfloor.a_wohnzimmer:lowboard_120": "Meuble TV bas 120", + "pack:nextfloor.a_wohnzimmer:lowboard_160": "Meuble TV bas 160", + "pack:nextfloor.a_wohnzimmer:lowboard_200": "Meuble TV bas 200", + "pack:nextfloor.a_wohnzimmer:sideboard_160": "Buffet 160", + "pack:nextfloor.a_wohnzimmer:highboard": "Buffet haut", + "pack:nextfloor.a_wohnzimmer:display_cabinet": "Vitrine", + "pack:nextfloor.a_wohnzimmer:chest_3": "Commode 3 tiroirs", + "pack:nextfloor.a_wohnzimmer:bookshelf_tall": "Bibliothèque haute", + "pack:nextfloor.a_wohnzimmer:bookshelf_wide": "Bibliothèque large", + "pack:nextfloor.a_wohnzimmer:cube_2x2": "Étagère à cubes 2 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x2": "Étagère à cubes 4 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x4": "Étagère à cubes 4 × 4", + "pack:nextfloor.a_wohnzimmer:divider_open": "Étagère de séparation de pièce", + "pack:nextfloor.a_wohnzimmer:wall_shelf": "Étagère murale flottante", + "pack:nextfloor.a_wohnzimmer:coat_stand": "Porte-manteau sur pied", + "pack:nextfloor.a_wohnzimmer:wall_unit_vitrines": "Meuble mural avec vitrines", + "pack:nextfloor.a_wohnzimmer:wall_unit_tv": "Meuble mural avec TV", + "pack:nextfloor.a_wohnzimmer:tv_on_stand": "TV sur pied", + "pack:nextfloor.a_wohnzimmer:media_wall": "Mur média avec TV", + "pack:nextfloor.a_wohnzimmer:wood_stove": "Poêle à bois", + "pack:nextfloor.a_wohnzimmer:fireplace_wall": "Cheminée électrique murale", + "pack:nextfloor.a_wohnzimmer:piano": "Piano droit avec banquette", + "pack:nextfloor.a_wohnzimmer:floor_lamp_arc": "Lampadaire arc", + "pack:nextfloor.a_wohnzimmer:floor_lamp_tripod": "Lampadaire trépied", + "pack:nextfloor.a_wohnzimmer:table_lamp_ceramic": "Lampe de table en céramique", + "pack:nextfloor.a_wohnzimmer:vase_pampas": "Vase de sol avec herbe de la pampa", + "pack:nextfloor.a_wohnzimmer:monstera": "Grand monstera", + "pack:nextfloor.a_wohnzimmer:rug_round": "Tapis rond", + "pack:nextfloor.a_wohnzimmer:rug_240": "Tapis 240 × 170", + "pack:nextfloor.a_wohnzimmer:painting_light": "Tableau avec lampe de tableau", + "pack:nextfloor.a_wohnzimmer:shelf_led": "Étagère avec tablettes LED", + "pack:nextfloor.a_wohnzimmer:air_purifier": "Purificateur d'air", + "pack:nextfloor.a_wohnzimmer:tower_fan": "Ventilateur colonne", + "pack:nextfloor.a_wohnzimmer:smart_speaker_living": "Enceinte connectée", + "packname:nextfloor.ausbau": "Architecture et aménagement", + "pack:nextfloor.ausbau:column_round": "Colonne ronde", + "pack:nextfloor.ausbau:column_square": "Colonne carrée", + "pack:nextfloor.ausbau:beam": "Poutre de plafond", + "pack:nextfloor.ausbau:chimney": "Conduit de cheminée", + "pack:nextfloor.ausbau:glass_wall": "Cloison vitrée", + "pack:nextfloor.ausbau:sliding_wall": "Cloison coulissante", + "pack:nextfloor.ausbau:platform": "Estrade", + "pack:nextfloor.ausbau:half_wall": "Muret", + "pack:nextfloor.ausbau:divider_shelf": "Étagère de séparation", + "pack:nextfloor.ausbau:pilaster": "Pilastre", + "pack:nextfloor.ausbau:column_steel": "Poteau en acier", + "pack:nextfloor.ausbau:beams_wood_5": "Poutres de plafond en bois (5)", + "pack:nextfloor.ausbau:beam_downstand": "Poutre apparente", + "pack:nextfloor.ausbau:fireplace_builtin": "Cheminée encastrée", + "pack:nextfloor.ausbau:divider_slats": "Claustra à lames", + "pack:nextfloor.ausbau:curtain_motor": "Rideau motorisé", + "pack:nextfloor.ausbau:niche_shelf": "Étagère encastrée (niche murale)", + "pack:nextfloor.ausbau:niche_led": "Niche LED", + "pack:nextfloor.ausbau:light_cove": "Corniche lumineuse (plafond)", + "pack:nextfloor.ausbau:gallery_rail_glass": "Garde-corps de galerie (verre)", + "pack:nextfloor.ausbau:window_seat": "Banquette de fenêtre", + "packname:nextfloor.bad": "Accessoires de salle de bain", + "pack:nextfloor.bad:double_vanity": "Meuble double vasque", + "pack:nextfloor.bad:walkin_shower": "Douche à l'italienne", + "pack:nextfloor.bad:towel_radiator": "Sèche-serviettes", + "pack:nextfloor.bad:mirror_cabinet": "Armoire de toilette lumineuse", + "pack:nextfloor.bad:washer_tower": "Colonne lave-linge/sèche-linge", + "pack:nextfloor.bad:laundry_basket": "Panier à linge", + "pack:nextfloor.bad:bath_shelf": "Étagère de bain", + "packname:nextfloor.energie": "Énergie et équipements techniques", + "pack:nextfloor.energie:heat_pump": "Pompe à chaleur (unité extérieure)", + "pack:nextfloor.energie:pellet_boiler": "Chaudière à granulés", + "pack:nextfloor.energie:buffer_tank": "Ballon tampon", + "pack:nextfloor.energie:hot_water_tank": "Ballon d'eau chaude", + "pack:nextfloor.energie:home_battery": "Batterie domestique (colonne)", + "pack:nextfloor.energie:inverter": "Onduleur", + "pack:nextfloor.energie:wallbox": "Borne de recharge", + "pack:nextfloor.energie:meter_cabinet": "Armoire de comptage", + "pack:nextfloor.energie:ventilation": "Centrale de ventilation", + "pack:nextfloor.energie:solar_carport_pillar": "Poteau de carport solaire", + "packname:nextfloor.fahrzeuge": "Véhicules", + "pack:nextfloor.fahrzeuge:tesla_model_s": "Tesla Model S", + "pack:nextfloor.fahrzeuge:tesla_model_3": "Tesla Model 3", + "pack:nextfloor.fahrzeuge:tesla_model_x": "Tesla Model X", + "pack:nextfloor.fahrzeuge:tesla_model_y": "Tesla Model Y", + "pack:nextfloor.fahrzeuge:tesla_cybertruck": "Tesla Cybertruck", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024": "Tesla Model 3 (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024_performance": "Tesla Model 3 Performance (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_s_plaid": "Tesla Model S Plaid", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025": "Tesla Model Y Standard (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_premium": "Tesla Model Y Premium (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_performance": "Tesla Model Y Performance (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_l": "Tesla Model Y L", + "pack:nextfloor.fahrzeuge:tesla_roadster": "Tesla Roadster", + "pack:nextfloor.fahrzeuge:tesla_semi": "Tesla Semi", + "pack:nextfloor.fahrzeuge:ev_suv": "SUV électrique (taille Model Y)", + "pack:nextfloor.fahrzeuge:small_car": "Citadine", + "pack:nextfloor.fahrzeuge:estate_car": "Break", + "pack:nextfloor.fahrzeuge:van": "Fourgonnette", + "pack:nextfloor.fahrzeuge:bicycle": "Vélo", + "pack:nextfloor.fahrzeuge:ebike": "Vélo électrique", + "pack:nextfloor.fahrzeuge:motorbike": "Moto", + "pack:nextfloor.fahrzeuge:trailer": "Remorque", + "pack:nextfloor.fahrzeuge:sedan": "Berline", + "pack:nextfloor.fahrzeuge:coupe": "Coupé sportif", + "pack:nextfloor.fahrzeuge:convertible": "Cabriolet (ouvert)", + "pack:nextfloor.fahrzeuge:small_ev": "Petite voiture électrique", + "pack:nextfloor.fahrzeuge:suv": "SUV", + "pack:nextfloor.fahrzeuge:family_van": "Monospace familial", + "pack:nextfloor.fahrzeuge:minibus": "Minibus", + "pack:nextfloor.fahrzeuge:panel_van": "Fourgon", + "pack:nextfloor.fahrzeuge:pickup": "Pick-up", + "pack:nextfloor.fahrzeuge:campervan": "Van aménagé (toit relevable)", + "pack:nextfloor.fahrzeuge:motorhome": "Camping-car", + "pack:nextfloor.fahrzeuge:caravan": "Caravane", + "packname:nextfloor.fitness": "Fitness (ancien)", + "pack:nextfloor.fitness:treadmill": "Tapis de course", + "pack:nextfloor.fitness:bike_trainer": "Vélo d'appartement", + "pack:nextfloor.fitness:rower": "Rameur", + "pack:nextfloor.fitness:weight_bench": "Banc de musculation", + "pack:nextfloor.fitness:power_rack": "Cage de musculation", + "pack:nextfloor.fitness:yoga_mat": "Tapis de yoga", + "pack:nextfloor.fitness:dumbbell_rack": "Râtelier d'haltères", + "packname:nextfloor.garten": "Jardin et terrasse (ancien)", + "pack:nextfloor.garten:sun_lounger": "Bain de soleil", + "pack:nextfloor.garten:garden_table": "Table de jardin", + "pack:nextfloor.garten:garden_chair": "Chaise de jardin", + "pack:nextfloor.garten:lounge_set": "Salon de jardin", + "pack:nextfloor.garten:parasol": "Parasol", + "pack:nextfloor.garten:gas_grill": "Barbecue à gaz", + "pack:nextfloor.garten:fire_bowl": "Brasero", + "pack:nextfloor.garten:pool": "Piscine", + "pack:nextfloor.garten:hot_tub": "Spa", + "pack:nextfloor.garten:trampoline": "Trampoline", + "pack:nextfloor.garten:greenhouse": "Serre", + "pack:nextfloor.garten:raised_bed": "Carré potager surélevé", + "pack:nextfloor.garten:garden_shed": "Abri de jardin", + "pack:nextfloor.garten:swing_bench": "Banc balancelle", + "pack:nextfloor.garten:mower_robot": "Tondeuse robot", + "pack:nextfloor.garten:tree_oak": "Arbre à feuilles caduques", + "pack:nextfloor.garten:tree_birch": "Bouleau", + "pack:nextfloor.garten:tree_fruit": "Arbre fruitier", + "pack:nextfloor.garten:conifer": "Conifère", + "pack:nextfloor.garten:shrub": "Arbuste", + "pack:nextfloor.garten:shrub_flowering": "Arbuste à fleurs", + "pack:nextfloor.garten:hedge": "Haie", + "pack:nextfloor.garten:lawn_brush": "Broussailles", + "pack:nextfloor.garten:bike_rack": "Range-vélos", + "pack:nextfloor.garten:bin_box": "Abri poubelles (4 bacs)", + "packname:nextfloor.ikea": "Tailles IKEA", + "pack:nextfloor.ikea:billy": "Bibliothèque 80x202 (taille Billy)", + "pack:nextfloor.ikea:billy_low": "Bibliothèque 80x106 (taille Billy)", + "pack:nextfloor.ikea:kallax_2x2": "Étagère à cases 2x2 (taille Kallax)", + "pack:nextfloor.ikea:kallax_2x4": "Étagère à cases 2x4 (taille Kallax)", + "pack:nextfloor.ikea:kallax_4x4": "Étagère à cases 4x4 (taille Kallax)", + "pack:nextfloor.ikea:lack_side": "Table d'appoint 55x55 (taille Lack)", + "pack:nextfloor.ikea:lack_coffee": "Table basse 90x55 (taille Lack)", + "pack:nextfloor.ikea:malm_bed_140": "Lit 140x200 (taille Malm)", + "pack:nextfloor.ikea:malm_bed_160": "Lit 160x200 (taille Malm)", + "pack:nextfloor.ikea:malm_chest_6": "Commode 6 tiroirs (taille Malm)", + "pack:nextfloor.ikea:malm_chest_4": "Commode 4 tiroirs (taille Malm)", + "pack:nextfloor.ikea:pax_100": "Armoire 100x236 (taille Pax)", + "pack:nextfloor.ikea:pax_150": "Armoire 150x236 (taille Pax)", + "pack:nextfloor.ikea:poang": "Fauteuil (taille Poäng)", + "pack:nextfloor.ikea:ektorp_2": "Canapé 2 places (taille Ektorp)", + "pack:nextfloor.ikea:ektorp_3": "Canapé 3 places (taille Ektorp)", + "pack:nextfloor.ikea:bekant": "Bureau 160x80 (taille Bekant)", + "pack:nextfloor.ikea:alex": "Caisson à tiroirs (taille Alex)", + "pack:nextfloor.ikea:besta_tv": "Meuble TV 180x42 (taille Bestå)", + "pack:nextfloor.ikea:ivar": "Étagère en pin 89x179 (taille Ivar)", + "packname:nextfloor.kino": "Home cinéma et gaming", + "pack:nextfloor.kino:projection_screen": "Écran de projection", + "pack:nextfloor.kino:projector": "Vidéoprojecteur", + "pack:nextfloor.kino:floor_speaker": "Enceinte colonne", + "pack:nextfloor.kino:subwoofer": "Caisson de basses", + "pack:nextfloor.kino:soundbar": "Barre de son", + "pack:nextfloor.kino:gaming_desk": "Bureau gaming", + "pack:nextfloor.kino:gaming_chair": "Fauteuil gaming", + "pack:nextfloor.kino:game_console": "Console de jeu", + "pack:nextfloor.kino:arcade": "Borne d'arcade", + "pack:nextfloor.kino:media_wall": "Mur multimédia avec TV", + "pack:nextfloor.kino:media_rack": "Meuble multimédia", + "packname:nextfloor.kueche": "Accessoires de cuisine", + "pack:nextfloor.kueche:coffee_machine": "Machine à café", + "pack:nextfloor.kueche:microwave": "Micro-ondes", + "pack:nextfloor.kueche:hood_island": "Hotte îlot", + "pack:nextfloor.kueche:wine_fridge": "Cave à vin", + "pack:nextfloor.kueche:stand_mixer": "Robot pâtissier", + "pack:nextfloor.kueche:toaster": "Grille-pain", + "pack:nextfloor.kueche:kettle": "Bouilloire", + "pack:nextfloor.kueche:long_dining_table": "Longue table à manger", + "pack:nextfloor.kueche:bar_cart": "Desserte de bar", + "pack:nextfloor.kueche:trash_station": "Poubelle de tri", + "packname:nextfloor.schlafen": "Chambre et enfants", + "pack:nextfloor.schlafen:boxspring": "Lit boxspring", + "pack:nextfloor.schlafen:baby_crib": "Lit bébé", + "pack:nextfloor.schlafen:changing_table": "Table à langer", + "pack:nextfloor.schlafen:vanity_table": "Coiffeuse", + "pack:nextfloor.schlafen:clothes_rail": "Portant à vêtements", + "pack:nextfloor.schlafen:loft_bed_desk": "Lit mezzanine avec bureau", + "pack:nextfloor.schlafen:toy_box": "Coffre à jouets", + "packname:nextfloor.technik": "Bureau et homelab", + "pack:nextfloor.technik:standing_desk": "Bureau assis-debout", + "pack:nextfloor.technik:server_rack": "Baie serveur (19 pouces)", + "pack:nextfloor.technik:nas": "NAS", + "pack:nextfloor.technik:printer_3d": "Imprimante 3D", + "pack:nextfloor.technik:office_printer": "Imprimante", + "pack:nextfloor.technik:router": "Routeur / borne Wi-Fi", + "pack:nextfloor.technik:tower_pc": "PC tour", + "pack:nextfloor.technik:filing_cabinet": "Caisson de bureau", + "packname:nextfloor.treppen": "Escaliers et garde-corps", + "pack:nextfloor.treppen:stairs_straight": "Escalier droit", + "pack:nextfloor.treppen:stairs_l": "Escalier quart tournant avec palier", + "pack:nextfloor.treppen:stairs_u": "Escalier demi-tournant", + "pack:nextfloor.treppen:stairs_spiral": "Escalier hélicoïdal", + "pack:nextfloor.treppen:stairs_compact": "Escalier gain de place", + "pack:nextfloor.treppen:landing": "Palier", + "pack:nextfloor.treppen:steps_outdoor": "Marches extérieures", + "pack:nextfloor.treppen:rail_metal": "Garde-corps métallique", + "pack:nextfloor.treppen:rail_glass": "Garde-corps en verre", + "pack:nextfloor.treppen:rail_wood": "Garde-corps en bois", + "pack:nextfloor.treppen:stairs_floating": "Escalier suspendu", + "pack:nextfloor.treppen:stairs_u_winder": "Escalier demi-tournant ouvert à balancement", + "pack:nextfloor.treppen:rail_corner": "Garde-corps d'angle", + "packname:nextfloor.werkstatt": "Garage et atelier", + "pack:nextfloor.werkstatt:workbench": "Établi", + "pack:nextfloor.werkstatt:tool_cabinet": "Armoire à outils", + "pack:nextfloor.werkstatt:tool_chest": "Servante d'atelier", + "pack:nextfloor.werkstatt:shelf_rack": "Rayonnage de rangement", + "pack:nextfloor.werkstatt:tyre_stack": "Pile de pneus", + "pack:nextfloor.werkstatt:drill_press": "Perceuse à colonne", + "pack:nextfloor.werkstatt:compressor": "Compresseur d'air", + "pack:nextfloor.werkstatt:bike_stand": "Support à vélo", + "pack:nextfloor.werkstatt:paint_cabinet": "Armoire à peinture", + "pack:nextfloor.werkstatt:tool_wall": "Panneau mural à outils", + "pack:nextfloor.werkstatt:heavy_shelf": "Étagère robuste", + "pack:nextfloor.werkstatt:chest_freezer_garage": "Congélateur coffre", + "pack:nextfloor.werkstatt:tyre_rack": "Rack à pneus", + "pack:nextfloor.werkstatt:lawn_mower": "Tondeuse à gazon", + "pack:nextfloor.werkstatt:bike_stand_2": "Support avec 2 vélos", + "pack:nextfloor.werkstatt:workshop_light": "Lampe d'atelier", + "pack:nextfloor.werkstatt:garage_opener": "Motorisation de porte de garage", + "pack:nextfloor.werkstatt:wallbox_holder": "Borne de recharge avec support de câble", + "pack:nextfloor.werkstatt:wall_bike_holder": "Support mural pour vélos (2)", + "pack:nextfloor.werkstatt:workshop_vacuum": "Aspirateur d'atelier", + "pack:nextfloor.werkstatt:workshop_cabinet": "Armoire d'atelier", + "pack:nextfloor.werkstatt:printer_enclosed": "Imprimante 3D fermée", + "packname:nextfloor.wohnen": "Salon et animaux", + "pack:nextfloor.wohnen:corner_sofa": "Canapé d'angle (en L)", + "pack:nextfloor.wohnen:bean_bag": "Pouf poire", + "pack:nextfloor.wohnen:fireplace": "Cheminée", + "pack:nextfloor.wohnen:bookcase_wall": "Bibliothèque murale", + "pack:nextfloor.wohnen:piano": "Piano droit", + "pack:nextfloor.wohnen:aquarium": "Aquarium", + "pack:nextfloor.wohnen:cat_tree": "Arbre à chat", + "pack:nextfloor.wohnen:dog_bed": "Panier pour chien", + "pack:nextfloor.wohnen:hanging_chair": "Fauteuil suspendu", + "pack:nextfloor.wohnen:display_cabinet": "Vitrine", + "pack:nextfloor.wohnen:high_table": "Table haute", + "pack:nextfloor.wohnen:floor_mirror": "Miroir sur pied", + "packname:nextfloor.a_saison": "Saisons et déco", + "packname:nextfloor.a_smart2": "Maison connectée 2", + "packname:nextfloor.a_haustechnik2": "Équipements du bâtiment 2", + "packname:nextfloor.a_wellness": "Bien-être", + "packname:nextfloor.a_garten2": "Jardin 2", + "packname:nextfloor.a_kueche2": "Cuisine 2", + "packname:nextfloor.a_fahrzeuge2": "Véhicules 2", + "packname:nextfloor.a_aussenkueche": "Cuisine d'extérieur et terrasse", + "packname:nextfloor.a_werkstatt2": "Atelier 2", + "packname:nextfloor.a_japandi": "Japandi et scandinave", + "packname:nextfloor.a_loft": "Loft et industriel", + "packname:nextfloor.a_gruen": "Plantes d'intérieur", + "packname:nextfloor.a_musik": "Musique et atelier", + "pack:nextfloor.a_saison:xmas_tree": "Sapin de Noël lumineux", + "pack:nextfloor.a_saison:advent_wreath": "Couronne de l'Avent", + "pack:nextfloor.a_saison:lights_outdoor": "Guirlande extérieure", + "pack:nextfloor.a_saison:window_star": "Étoile de fenêtre", + "pack:nextfloor.a_saison:candle_arch": "Arche de bougies", + "pack:nextfloor.a_saison:reindeer_light": "Renne lumineux", + "pack:nextfloor.a_saison:pumpkin": "Citrouille", + "pack:nextfloor.a_saison:pumpkin_lantern": "Lanterne citrouille", + "pack:nextfloor.a_saison:easter_tree": "Arbre de Pâques", + "pack:nextfloor.a_saison:snowman": "Bonhomme de neige", + "pack:nextfloor.a_saison:gift_pile": "Cadeaux", + "pack:nextfloor.a_smart2:siren": "Sirène", + "pack:nextfloor.a_smart2:access_point": "Point d'accès Wi-Fi", + "pack:nextfloor.a_smart2:access_point_wall": "Point d'accès Wi-Fi (mur)", + "pack:nextfloor.a_smart2:smoke_detector": "Détecteur de fumée", + "pack:nextfloor.a_smart2:co_detector": "Détecteur de CO", + "pack:nextfloor.a_smart2:dehumidifier": "Déshumidificateur", + "pack:nextfloor.a_smart2:cube_lamp": "Lampe cube", + "pack:nextfloor.a_smart2:presence_ceiling": "Détecteur de présence (plafond)", + "pack:nextfloor.a_smart2:water_leak": "Détecteur de fuite", + "pack:nextfloor.a_smart2:air_quality": "Capteur de qualité d'air", + "pack:nextfloor.a_smart2:doorbell_cam": "Sonnette vidéo", + "pack:nextfloor.a_haustechnik2:water_tank": "Réservoir d'eau", + "pack:nextfloor.a_haustechnik2:oil_tank": "Cuve à fioul", + "pack:nextfloor.a_haustechnik2:oil_boiler": "Chaudière fioul", + "pack:nextfloor.a_haustechnik2:water_softener": "Adoucisseur d'eau", + "pack:nextfloor.a_haustechnik2:buffer_tank": "Ballon tampon", + "pack:nextfloor.a_haustechnik2:cistern": "Citerne d'eau de pluie", + "pack:nextfloor.a_haustechnik2:ventilation_unit": "Ventilation double flux", + "pack:nextfloor.a_haustechnik2:expansion_vessel": "Vase d'expansion", + "pack:nextfloor.a_haustechnik2:heat_pump_indoor": "Pompe à chaleur (unité intérieure)", + "pack:nextfloor.a_wellness:sauna_cabin": "Sauna", + "pack:nextfloor.a_wellness:sauna_barrel": "Sauna tonneau", + "pack:nextfloor.a_wellness:infrared_cabin": "Cabine infrarouge", + "pack:nextfloor.a_wellness:hot_tub": "Spa / jacuzzi", + "pack:nextfloor.a_wellness:plunge_pool": "Bassin d'immersion", + "pack:nextfloor.a_wellness:steam_shower": "Douche hammam", + "pack:nextfloor.a_wellness:relax_lounger": "Chaise longue de relaxation", + "pack:nextfloor.a_wellness:cold_bath": "Bain glacé", + "pack:nextfloor.a_garten2:water_feature": "Fontaine lumineuse", + "pack:nextfloor.a_garten2:pond": "Bassin avec pompe", + "pack:nextfloor.a_garten2:robot_mower": "Robot tondeuse", + "pack:nextfloor.a_garten2:mower_dock": "Station de charge tondeuse", + "pack:nextfloor.a_garten2:sandbox": "Bac à sable", + "pack:nextfloor.a_garten2:beach_chair": "Fauteuil de plage", + "pack:nextfloor.a_garten2:wood_pile": "Pile de bois", + "pack:nextfloor.a_garten2:bird_house": "Mangeoire pour oiseaux", + "pack:nextfloor.a_garten2:raised_bed": "Potager surélevé", + "pack:nextfloor.a_garten2:garden_shower": "Douche de jardin", + "pack:nextfloor.a_kueche2:coffee_machine": "Machine à café automatique", + "pack:nextfloor.a_kueche2:espresso": "Machine expresso", + "pack:nextfloor.a_kueche2:kettle": "Bouilloire", + "pack:nextfloor.a_kueche2:toaster": "Grille-pain", + "pack:nextfloor.a_kueche2:stand_mixer": "Robot pâtissier", + "pack:nextfloor.a_kueche2:thermo_cooker": "Robot cuiseur", + "pack:nextfloor.a_kueche2:air_fryer": "Friteuse à air chaud", + "pack:nextfloor.a_kueche2:microwave": "Micro-ondes", + "pack:nextfloor.a_kueche2:wine_fridge": "Cave à vin", + "pack:nextfloor.a_kueche2:water_bar": "Machine à eau gazeuse", + "pack:nextfloor.a_kueche2:dishwasher_slim": "Lave-vaisselle 45 cm", + "pack:nextfloor.a_fahrzeuge2:motorbike": "Moto", + "pack:nextfloor.a_fahrzeuge2:scooter": "Scooter", + "pack:nextfloor.a_fahrzeuge2:camper_van": "Camping-car", + "pack:nextfloor.a_fahrzeuge2:trailer": "Remorque", + "pack:nextfloor.a_fahrzeuge2:e_bike": "Vélo électrique", + "pack:nextfloor.a_fahrzeuge2:cargo_bike": "Vélo cargo", + "pack:nextfloor.a_fahrzeuge2:quad": "Quad", + "pack:nextfloor.a_fahrzeuge2:boat_trailer": "Remorque avec bateau", + "pack:nextfloor.a_aussenkueche:outdoor_kitchen": "Cuisine d'extérieur", + "pack:nextfloor.a_aussenkueche:kamado": "Barbecue kamado", + "pack:nextfloor.a_aussenkueche:pizza_oven": "Four à pizza", + "pack:nextfloor.a_aussenkueche:fire_pit": "Brasero", + "pack:nextfloor.a_aussenkueche:patio_heater": "Parasol chauffant", + "pack:nextfloor.a_aussenkueche:outdoor_fridge": "Réfrigérateur d'extérieur", + "pack:nextfloor.a_aussenkueche:bar_counter": "Comptoir de bar", + "pack:nextfloor.a_aussenkueche:bar_stool_out": "Tabouret de bar extérieur", + "pack:nextfloor.a_aussenkueche:hanging_chair": "Fauteuil suspendu", + "pack:nextfloor.a_werkstatt2:workbench_wall": "Établi avec panneau perforé", + "pack:nextfloor.a_werkstatt2:drill_press": "Perceuse à colonne", + "pack:nextfloor.a_werkstatt2:table_saw": "Scie sur table", + "pack:nextfloor.a_werkstatt2:compressor": "Compresseur", + "pack:nextfloor.a_werkstatt2:welder": "Poste à souder", + "pack:nextfloor.a_werkstatt2:heavy_shelf": "Étagère charge lourde", + "pack:nextfloor.a_werkstatt2:parts_cabinet": "Casier à petites pièces", + "pack:nextfloor.a_werkstatt2:tool_chest": "Servante d'atelier", + "pack:nextfloor.a_werkstatt2:ev_bike_charger": "Station de charge des batteries", + "pack:nextfloor.a_japandi:low_bed": "Lit bas", + "pack:nextfloor.a_japandi:tatami": "Tatami", + "pack:nextfloor.a_japandi:paper_lamp": "Lampadaire en papier", + "pack:nextfloor.a_japandi:paper_pendant": "Suspension en papier", + "pack:nextfloor.a_japandi:tea_table": "Table à thé basse", + "pack:nextfloor.a_japandi:shoji_screen": "Paravent shoji", + "pack:nextfloor.a_japandi:bonsai": "Bonsaï", + "pack:nextfloor.a_japandi:floor_cushion": "Coussin de sol", + "pack:nextfloor.a_japandi:wood_bench": "Banc en bois", + "pack:nextfloor.a_japandi:rattan_chair": "Fauteuil en rotin", + "pack:nextfloor.a_loft:steel_shelf": "Étagère acier", + "pack:nextfloor.a_loft:factory_pendant": "Suspension industrielle", + "pack:nextfloor.a_loft:leather_sofa": "Canapé en cuir", + "pack:nextfloor.a_loft:plank_table": "Table en planches", + "pack:nextfloor.a_loft:locker": "Casier métallique", + "pack:nextfloor.a_loft:edison_floor_lamp": "Lampadaire Edison", + "pack:nextfloor.a_loft:bar_stool_loft": "Tabouret de bar industriel", + "pack:nextfloor.a_loft:pipe_shelf": "Étagère en tubes", + "pack:nextfloor.a_gruen:monstera": "Monstera", + "pack:nextfloor.a_gruen:ficus": "Ficus", + "pack:nextfloor.a_gruen:olive_tree": "Olivier en pot", + "pack:nextfloor.a_gruen:cactus_group": "Cactus", + "pack:nextfloor.a_gruen:hanging_plant": "Plante suspendue", + "pack:nextfloor.a_gruen:plant_shelf": "Étagère à plantes avec lampe", + "pack:nextfloor.a_gruen:vertical_garden": "Mur végétal", + "pack:nextfloor.a_gruen:grow_light": "Lampe horticole", + "pack:nextfloor.a_gruen:herb_planter": "Jardin d'herbes connecté", + "pack:nextfloor.a_musik:upright_piano": "Piano droit", + "pack:nextfloor.a_musik:grand_piano": "Piano à queue", + "pack:nextfloor.a_musik:drum_kit": "Batterie", + "pack:nextfloor.a_musik:guitar_stand": "Guitares sur pied", + "pack:nextfloor.a_musik:guitar_amp": "Ampli guitare", + "pack:nextfloor.a_musik:mixing_desk": "Bureau de studio avec console", + "pack:nextfloor.a_musik:studio_monitor": "Moniteur de studio", + "pack:nextfloor.a_musik:synth": "Synthétiseur", + "pack:nextfloor.a_musik:mic_stand": "Micro sur pied", + "pack:nextfloor.a_musik:easel": "Chevalet", + "pack:nextfloor.a_musik:vinyl_player": "Platine vinyle", + "packname:nextfloor.a_bilder": "Cadres et photos", + "pack:nextfloor.a_bilder:frame_landscape": "Cadre photo (paysage)", + "pack:nextfloor.a_bilder:frame_portrait": "Cadre photo (portrait)", + "pack:nextfloor.a_bilder:frame_square": "Cadre photo (carré)", + "pack:nextfloor.a_bilder:frame_large": "Grand cadre", + "pack:nextfloor.a_bilder:canvas": "Toile imprimée", + "pack:nextfloor.a_bilder:poster": "Affiche", + "pack:nextfloor.a_bilder:frame_table": "Cadre à poser", + "pack:nextfloor.a_bilder:frame_digital": "Cadre photo numérique", + "pack:nextfloor.a_bilder:picture_ledge": "Étagère à cadres", + "color:pearl_white": "Blanc nacré", + "color:solid_black": "Noir uni", + "color:midnight_silver": "Argent nocturne", + "color:quicksilver": "Vif-argent", + "color:deep_blue": "Bleu profond", + "color:ultra_red": "Rouge Ultra", + "color:midnight_cherry": "Rouge cerise nocturne", + "color:red": "Rouge multicouche", + "color:stealth_grey": "Gris furtif", + "color:stainless": "Acier inoxydable", + "color:wrap_black": "Film noir satiné", + "color:wrap_white": "Film blanc satiné", + "color:wrap_grey": "Film gris satiné", + "color:wrap_blue": "Film bleu satiné", + "pack:nextfloor.a_smart:light_switch_1": "Interrupteur simple", + "pack:nextfloor.a_smart:light_switch_2": "Interrupteur double", + "pack:nextfloor.a_smart:light_switch_3": "Interrupteur triple", + "pack:nextfloor.a_smart:light_switch_4": "Interrupteur quadruple", + "pack:nextfloor.a_smart:socket_1": "Prise simple", + "pack:nextfloor.a_smart:socket_2": "Prise double", + "pack:nextfloor.a_smart:socket_3": "Prise triple", + "pack:nextfloor.a_smart:socket_4": "Prise quadruple", + "pack:nextfloor.a_smart:socket_outdoor": "Prise extérieure à clapet", + "pack:nextfloor.ausbau:curtain_pair": "Rideau (ouverture des deux côtés)", + "pack:nextfloor.ausbau:roller_blind_inside": "Store enrouleur (intérieur)", + "pack:nextfloor.a_garten:awning_300": "Store banne 3 m", + "pack:nextfloor.a_garten:awning_400": "Store banne 4 m", + "pack:nextfloor.a_garten:awning_500": "Store banne 5 m", + "pack:nextfloor.a_garten:sliding_gate": "Portail coulissant", + "walls_slope": "En biais", + "walls_slope_hint": "Murs coupés en biais : mi-hauteur devant, pleine hauteur derrière – comme une maison de poupée ; tourne avec la caméra", + "walls_solid": "Pleins", + "walls_solid_hint": "Murs pleins dans leurs couleurs au lieu du verre (couleurs : éditeur → paramètres, par pièce dans la pièce)", + "wall_paint_outside": "Couleur des murs à l'extérieur", + "wall_paint_inside": "Couleur des murs à l'intérieur", + "wall_paint_room": "Couleur des murs à l'intérieur (cette pièce)", + "wall_paint_hint": "Utilisée dans la vue 3D « Pleins ».", + "wall_paint_default": "Par défaut", + "card_solid_walls": "Murs pleins (dans leurs couleurs)", + "units": "Afficher les longueurs en", + "units_metric": "Mètres", + "units_imperial": "Pieds et pouces", + "units_hint": "Comment les longueurs et les surfaces apparaissent dans le plan, les formulaires et la vue du mur. Les saisies restent en mètres.", + "opening_light_well": "Saut-de-loup devant", + "sill_boards": "Appui et tablette", + "sill_boards_auto": "Automatique", + "sill_boards_none": "Aucun", + "sill_boards_inside": "Intérieur seulement", + "sill_boards_outside": "Extérieur seulement", + "import_other_hint": "Depuis Sweet Home 3D : importez ici le fichier .sh3d. Étages, pièces, portes, fenêtres et murs libres sont repris, les meubles non.", + "import_sh3d_found": "Sweet Home 3D : {floors} étages, {rooms} pièces, {openings} portes et fenêtres, {walls} murs libres ({furniture} meubles ne sont pas repris).", + "import_dxf_found": "DXF : {rooms} pièces (polylignes fermées) et {walls} murs libres (lignes) sur un étage.", + "import_ifc_found": "Dans le fichier IFC : {floors} étages et {rooms} pièces (NextFloor dessine les murs à partir des pièces).", + "import_roomplan_found": "Scan de pièce (RoomPlan) : {rooms} pièces, {openings} portes et fenêtres ; {skipped} objets non repris (vous placez les meubles vous-même).", + "import_error_roomplan_empty": "Le scan ne contient aucun mur.", + "import_error_ifc_empty": "Le fichier IFC ne contient aucun espace (IfcSpace) avec une emprise.", + "import_error_dxf_empty": "Le fichier DXF ne contient ni lignes ni polylignes.", + "import_error_sh3d": "Ce n'est pas un fichier Sweet Home 3D lisible (il faut Sweet Home 3D 5.3 ou plus récent).", + "import_error_sh3d_empty": "Le fichier Sweet Home 3D ne contient ni pièces ni murs.", + "care_bin_today": "Collecte aujourd'hui", + "care_bin_tomorrow": "Collecte demain", + "care_bin_days": "Dans {n} jours", + "care_mail_yes": "Du courrier est arrivé", + "care_mail_no": "Vide", + "care_plant_thirsty": "Assoiffée", + "care_plant_ok": "Bien arrosée", + "care_time_left": "Encore {time}", + "care_entity_bin": "Date de collecte (capteur)", + "care_entity_mail": "Capteur de courrier", + "care_entity_plant": "Humidité du sol (capteur)", + "care_thirsty_below": "Assoiffée en dessous de (%)", + "care_hint_bin": "Un capteur avec la prochaine collecte : des jours, une date, \"aujourd'hui\"/\"demain\" ou l'intégration Waste Collection Schedule. La poubelle s'allume la veille et le jour même.", + "care_hint_mail": "Un capteur qui signale du courrier dans la boîte (un contact sur le clapet, par exemple). La boîte aux lettres s'allume alors.", + "care_hint_plant": "Un capteur d'humidité dans la terre. Sous le seuil, la plante s'allume et dit qu'elle a soif.", + "live_day_hint": "Les dernières 24 heures : solaire (surface) et consommation (ligne)", + "live_week_hint": "Les 7 derniers jours : soleil {solar} kWh, consommation {use} kWh (jaune : soleil, clair : consommation)", + "live_days": "jours", + "roof_end_start": "Extrémité au début du faîtage", + "roof_end_end": "Extrémité à la fin du faîtage", + "roof_halfhip": "La croupe commence à", + "roof_halfhip_hint": "À quelle hauteur du pignon commence la croupe, en part de la hauteur du pignon : bas = grande croupe, haut = seule la pointe est en croupe.", + "travel": "Voyage dans le temps : rejouer les dernières 24 heures ou 7 jours", + "travel_play": "Lecture", + "travel_pause": "Pause", + "travel_loading": "Chargement de l'historique …", + "travel_failed": "L'historique n'a pas pu être chargé.", + "travel_speed": "Vitesse", + "travel_speed_min": "1 min/s", + "travel_speed_10min": "10 min/s", + "travel_speed_hour": "1 h/s", + "travel_days": "jours", + "travel_live": "Direct", + "card_travel_button": "Bouton du voyage dans le temps", + "pack:nextfloor.a_garten:bin_rest_120": "Poubelle ordures ménagères 120 l", + "pack:nextfloor.a_garten:bin_rest_240": "Poubelle ordures ménagères 240 l", + "pack:nextfloor.a_garten:bin_bio_120": "Bac à biodéchets 120 l", + "pack:nextfloor.a_garten:bin_bio_240": "Bac à biodéchets 240 l", + "pack:nextfloor.a_garten:bin_paper_120": "Bac à papier 120 l", + "pack:nextfloor.a_garten:bin_paper_240": "Bac à papier 240 l", + "pack:nextfloor.a_garten:bin_yellow_120": "Bac de recyclage 120 l", + "pack:nextfloor.a_garten:bin_yellow_240": "Bac de recyclage 240 l", + "pack:nextfloor.a_garten:mailbox": "Boîte aux lettres", + "pack:nextfloor.a_garten:mailbox_post": "Boîte aux lettres sur pied", + "pack:nextfloor.a_haustiere:pet_cat": "Chat (se promène)", + "pack:nextfloor.a_haustiere:pet_dog": "Chien (se promène)", + "pack:nextfloor.a_haustiere:pet_rabbit": "Lapin (sautille partout)", + "floor_copy": "Dupliquer l'étage", + "floor_copy_hint": "La copie se place au-dessus de la maison avec toutes les pièces, murs, portes et fenêtres. Les pièces et l'étage perdent leur lien avec Home Assistant, les meubles leurs entités ; les appareils d'énergie restent sur l'ancien étage.", + "floor_copy_furniture": "Copier les meubles", + "floor_copy_devices": "Copier les repères d'appareils", + "floor_copy_devices_hint": "La même entité apparaît alors aux deux étages.", + "floor_copy_outdoor": "Copier les zones extérieures", + "floor_copy_make": "Créer la copie", + "floor_copy_name": "{name} (copie)", + "furn_to_floor": "Déplacer vers l'étage", + "furn_to_floor_hint": "Le meuble se place au même endroit à l'étage choisi.", + "arc": "Arc", + "arc_hint": "Courbe le mur en arc. Une pièce qui partage ce mur se courbe avec, les portes et fenêtres suivent ; Annuler retire l'arc.", + "arc_bulge": "Courbure (m)", + "arc_bulge_hint": "De combien le milieu du mur se bombe : positif vers l'extérieur, négatif vers la pièce.", + "arc_apply": "Courber", + "arc_too_wide": "Une porte ou une fenêtre de ce mur est trop large pour cette courbe. Rends la courbe plus plate ou l'ouverture plus étroite.", + "time_of_day": "Heure du jour", + "time_of_day_hint": "Montre soleil, lumière, ombres et apparence à une autre heure d'aujourd'hui. Touchez à nouveau pour revenir à maintenant.", + "menu_open": "Menu ouvert", + "menu_open_hint": "Le menu étoile avec les favoris et les boutons personnels est ouvert dès le départ sur cet appareil, en plus grand – pour une tablette murale qui lance surtout des scènes.", + "keep_camera": "Garder la caméra", + "keep_camera_hint": "En changeant d'étage, la caméra garde le même côté, la même hauteur et la même distance au lieu de cadrer le nouvel étage depuis le côté de départ.", + "view_zoom": "Zoom", + "view_zoom_hint": "À quelle distance les vues cadrées s'approchent – sur les petites tablettes la maison paraît plus grande.", + "stair_shape": "Forme", + "stair_shape_straight": "Droit", + "stair_shape_quarter": "Quart tournant (balancé)", + "stair_shape_l": "En L avec palier", + "stair_shape_half": "Demi-tournant (balancé)", + "stair_shape_u": "En U avec palier", + "stair_shape_spiral": "Hélicoïdal", + "stair_turn": "Sens de rotation (en montant)", + "stair_turn_left": "Vers la gauche", + "stair_turn_right": "Vers la droite", + "stair_build": "Construction", + "stair_build_solid": "Massif (béton)", + "stair_build_stringer": "À limons", + "stair_build_mono": "Limon central", + "stair_build_cantilever": "Marches en porte-à-faux (flottantes)", + "stair_risers": "Contremarches", + "stair_steps": "Contremarches (nombre)", + "stair_run_width": "Largeur de volée (m)", + "stair_landing_after": "Marches jusqu'au palier", + "stair_landing_hint": "Le palier est à {h} cm au-dessus du sol ; les autres marches viennent après.", + "stair_rail": "Garde-corps", + "stair_rail_none": "Aucun", + "stair_rail_left": "Gauche", + "stair_rail_right": "Droite", + "stair_rail_both": "Des deux côtés", + "stair_down": "Descend", + "stair_down_hint": "L'escalier part de cet étage et descend, par exemple vers une cave qui n'a pas besoin d'être dessinée. Il ouvre le sol de cet étage.", + "stair_measures": "{steps} contremarches de {rise} cm · giron {going} cm · pas {measure} cm", + "stair_uncomfortable": "inconfortable (pas 59–65 cm, hauteur de marche 21 cm au plus)", + "stair_up_note": "L'escalier commence au bord avant marqué. Le sol au-dessus ne s'ouvre que là où il reste moins de 2,2 m d'échappée au-dessus des marches.", + "stair_down_note": "On monte sur l'escalier au bord avant marqué et on descend. Le plan le dessine en pointillés ; cet étage s'ouvre au-dessus des marches.", + "stair_upgrade": "Choisir la forme", + "stair_upgrade_hint": "En fait un escalier avec une forme (balancé, L, U, hélicoïdal), une construction, un garde-corps et un nombre de marches.", + "tool_stairs": "Escalier", + "hint_stairs": "Faites glisser là où l'escalier doit se trouver – il suit le grand côté ; réglez ensuite forme, sens et construction à droite", + "stair_opening": "Trémie", + "stair_opening_headroom": "Selon l'échappée (seulement si nécessaire)", + "stair_opening_full": "Au-dessus de tout l'escalier", + "stair_opening_none": "Aucune (trappe, cage fermée)", + "stair_opening_hint": "Jusqu'où l'escalier ouvre le sol qu'il atteint : l'étage au-dessus, ou son propre étage pour un escalier qui descend. Selon l'échappée n'ouvre qu'au-dessus des marches où il reste moins de 2,2 m.", + "stair_up_note_plain": "L'escalier commence au bord avant marqué et monte vers l'arrière." +} diff --git a/custom_components/nextfloor/frontend/lang/hu.json b/custom_components/nextfloor/frontend/lang/hu.json new file mode 100644 index 0000000..d17b3fd --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/hu.json @@ -0,0 +1,153 @@ +{ + "accent": "Kiemelő szín", + "accent_reset": "Vissza ciánra", + "alert_alarm_by": "Riasztást kiváltotta: {cause}", + "all_floors": "Minden szint", + "all_off_done": "Minden kikapcsolva.", + "all_off_floor": "Minden kikapcsolva: {floor} ({n} eszköz), visszavonás tíz másodpercig", + "all_off_n": "Minden ki ({n})", + "all_off_undo": "Visszavonás", + "announce_failed": "A közlemény nem sikerült: {error}", + "announce_on": "A közlemények ezen a képernyőn be vannak kapcsolva", + "announce_placeholder": "Saját üzeneted …", + "announce_send": "Mondd ki", + "announce_sent": "Kimondva: \"{message}\"", + "back": "Vissza", + "bars_fold": "Kapcsolók elrejtése", + "bars_unfold": "Kapcsolók", + "battery_low_n": "Gyenge elem: {names}", + "brightness": "Fényerő", + "card_description": "Otthonod 3D-ben (neon).", + "card_floor_stack": "Alatta lévő szintek", + "card_room_buttons": "Szobagombok", + "care_bin_days": "{n} nap múlva", + "care_bin_today": "Ma szállítják el", + "care_bin_tomorrow": "Holnap szállítják el", + "care_time_left": "{time} van hátra", + "central": "Központ: minden lámpa, redőny és kedvenc", + "central_covers": "Redőnyök", + "central_favorites": "Kedvencek", + "central_house": "Az egész ház", + "central_lights": "Lámpák", + "central_sure": "Biztos?", + "clock": "Óra", + "close": "Bezár", + "color": "Szín", + "color_temp": "Színhőmérséklet", + "comfort_n": "Komfort {n}", + "confirm_switch": "Tényleg átkapcsolod: {name}?", + "cover_close": "Zár", + "cover_my_go": "A kedvenc helyzetbe ({p} %)", + "cover_open": "Nyit", + "cover_stop": "Megállít", + "cover_tilt": "Lamellák", + "cover_tilt_close": "Lamellák zárva", + "cover_tilt_open": "Lamellák nyitva", + "delete": "Törlés", + "details": "Részletek", + "draft_discard": "Elvet", + "draft_found": "Mentetlen módosítások találhatók ({time}).", + "draft_restore": "Visszaállít és ment", + "empty_lights_hint": "{n} lámpa ég, {min} perce nincs itt senki.", + "empty_lights_off": "Lámpák ki", + "energy_battery": "Akkumulátor", + "energy_consumption": "Fogyasztás", + "energy_rest": "Közös (maradék)", + "energy_solar": "Nap", + "energy_tariff": "Tarifa", + "ext_tab": "Bővítmények", + "find": "Keresés", + "find_none": "Nincs találat", + "find_placeholder": "Hol van …? Eszköz vagy szoba", + "floor_layer": "Réteg (megjeleníthető és elrejthető)", + "floor_power_share": "A ház {n} %-a", + "floor_rooms": "{n} szoba", + "floor_rooms_one": "1 szoba", + "floors": "Szintek", + "floors_apart": "Szétválasztva", + "floors_stacked": "Egymáson", + "flows": "Energiaáramlás", + "fps_title": "Teljesítménykijelzés (képkocka/mp)", + "glass_walls": "Üvegfalak", + "heat_none_found": "Nincs megfelelő érzékelő a szobák területein.", + "heat_wifi": "Wi-Fi", + "heatmap": "Hőtérkép", + "holos": "Kártyák", + "keep_camera": "Kamera megtartása", + "load_error": "A betöltés sikertelen", + "loading": "Betöltés …", + "markers": "Jelölők", + "media_next": "Következő", + "media_previous": "Előző", + "media_sources": "Források", + "media_volume": "Hangerő", + "menu_open": "Menü nyitva", + "meter_unmetered": "{w} mérés nélkül", + "mood_carry": "Átvitel másik szobába", + "mood_new": "Hangulat", + "mood_save": "Hangulat mentése", + "mood_set": "Hangulat beállítása", + "next": "Következő", + "no_building": "Még nincs alaprajz.", + "open_editor": "Szerkesztő megnyitása", + "open_heating_hint": "{n} ablak nyitva, miközben fűt a fűtés.", + "open_heating_off": "Fűtés ki", + "open_since": "nyitva {time} óta", + "outside_area": "Kint", + "panel_all_close": "Mind le", + "panel_all_off": "Mind ki", + "panel_all_on": "Mind be", + "panel_all_open": "Mind fel", + "panel_less": "Kevesebb", + "panel_more": "Több eszköz a területről ({n})", + "plain": "Csak alaprajz", + "play_pause": "Lejátszás/szünet", + "pool_pump_on": "szivattyú be", + "position": "Pozíció", + "presence_last": "utoljára {time} ezelőtt látva", + "presence_now": "valaki itt van", + "presets": "Állomások és lejátszási listák (hang)", + "previous": "Előző", + "qm_off": "Ki", + "readable": "Jól olvasható", + "reload_page": "Újratöltés", + "right_back": "Jobb klikk = vissza", + "roof_keep": "A tető marad", + "room_clean_run": "Takarítás", + "room_clean_run_hint": "Ide küldi a robotporszívót.", + "room_curve_hint": "A szoba hőmérséklete az elmúlt 24 órában", + "room_energy": "ma {today} · hónap {month}", + "room_sun_hours": "{h} óra napsütés ma ({facing})", + "room_sun_year": "Nap az év során", + "save_failed_detail": "A mentés nem sikerült: {error}. A módosítások megmaradnak ebben a böngészőben.", + "screen_name": "A képernyő neve", + "shade_close": "Leenged", + "shade_hint": "Nap süt {n} ablakra, {temp} – lehúzzuk a redőnyt?", + "stats_idle": "Nyugalomban (0 fps)", + "stl": "3D nyomtatás (STL)", + "swipe_off": "Ki", + "target_temp": "Cél", + "temp_down": "Hűvösebb", + "temp_up": "Melegebb", + "time_of_day": "Napszak", + "today": "Ma", + "today_none": "Ma nincs semmi.", + "travel": "Időutazás: az elmúlt 24 óra vagy 7 nap lejátszása", + "travel_days": "nap", + "travel_failed": "Az előzményeket nem sikerült betölteni.", + "travel_live": "Élő", + "travel_loading": "Előzmények betöltése …", + "travel_speed": "Sebesség", + "view_options": "Nézet: minőség, megjelenés, jelölők, FPS", + "view_zoom": "Nagyítás", + "volume": "Hangerő", + "wallbox_charging": "tölt", + "wallbox_plugged": "csatlakoztatva", + "walls_auto": "Magas falak", + "walls_cut": "Metszet", + "walls_slope": "Ferde", + "walls_solid": "Tömör", + "wifi_aps": "{n} hozzáférési pont · {clients} eszköz", + "wifi_clients": "{n} eszköz", + "wifi_network": "Hálózat: {online} online · {offline} offline" +} diff --git a/custom_components/nextfloor/frontend/lang/it.json b/custom_components/nextfloor/frontend/lang/it.json new file mode 100644 index 0000000..4f1a0ad --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/it.json @@ -0,0 +1,2763 @@ +{ + "view": "3D", + "editor": "Editor", + "all_floors": "Tutti i piani", + "outside_area": "Esterno", + "outside_area_hint": "Tutti i dispositivi all'aperto a colpo d'occhio: in giardino, fuori dalle stanze e ciò che appartiene all'esterno (ad esempio la stazione meteo sul tetto).", + "device_outside": "Appartiene all'esterno", + "device_outside_hint": "Il dispositivo non conta per la stanza sottostante (una stazione meteo sul tetto) ed è elencato nel pannello Esterno.", + "no_building": "Ancora nessuna planimetria.", + "no_building_admin": "Ancora nessuna planimetria. Disegna il tuo primo piano nell'editor.", + "no_rooms_admin": "I piani esistono, ma non c’è ancora nessuna stanza. Le sole pareti non bastano: disegna almeno una stanza nell’editor con «Rettangolo» o «Forma libera».", + "open_editor": "Apri l'editor", + "loading": "Caricamento …", + "load_error": "Caricamento non riuscito", + "saving": "Salvataggio …", + "saved": "Salvato", + "save_error": "Salvataggio non riuscito", + "save_failed_detail": "Salvataggio non riuscito: {error}. Le modifiche restano in questo browser.", + "needs_restart": "È installata una nuova versione di NextFloor ({frontend}), ma Home Assistant esegue ancora {version}. Riavvia Home Assistant: fino ad allora il salvataggio può non riuscire.", + "needs_reload": "Questa pagina mostra ancora NextFloor {frontend}, Home Assistant ha già {backend}. Ricarica la pagina; nell'app companion: Impostazioni → App companion → Reimposta cache del frontend.", + "reload_page": "Ricarica", + "needs_restart_old": "È installata una nuova versione di NextFloor, ma Home Assistant esegue ancora una versione precedente. Riavvia Home Assistant: fino ad allora il salvataggio non riesce.", + "draft_found": "Trovate modifiche non salvate del {time}.", + "draft_restore": "Ripristina e salva", + "draft_discard": "Scarta", + "walls_auto": "Pareti alte", + "walls_cut": "Sezione", + "walls_slope": "Inclinate", + "walls_slope_hint": "Pareti tagliate in pendenza: a mezza altezza davanti, a tutta altezza dietro, come una casa delle bambole; ruota con la telecamera", + "walls_solid": "Piene", + "walls_solid_hint": "Pareti piene nei loro colori invece del vetro (colori: editor → impostazioni, per stanza nella stanza)", + "wall_paint_outside": "Colore parete esterna", + "wall_paint_inside": "Colore parete interna", + "wall_paint_room": "Colore parete interna (questa stanza)", + "wall_paint_hint": "Usato nella vista 3D «Piene».", + "wall_paint_default": "Predefinito", + "card_solid_walls": "Pareti piene (nei loro colori)", + "reset_view": "Panoramica", + "back": "Indietro", + "floor": "Piano", + "floors": "Piani", + "add_floor": "Aggiungi piano", + "floor_from_ha": "Piani da Home Assistant:", + "floor_empty": "Piano vuoto", + "level": "Livello {n}", + "ha_floor": "Piano in Home Assistant", + "floor_layer": "Livello (mostrabile e nascondibile)", + "floor_power": "Contatore del piano (potenza)", + "floor_power_hint": "Un sensore di potenza solo per questo piano (un sottocontatore, un appartamento). Il suo valore compare sull'etichetta del piano e, nella vista di questo piano, sulla scheda della casa con la sua quota dei consumi.", + "floor_power_share": "{n} % della casa", + "living_area": "Superficie abitabile {living}", + "room_living": "Conta come superficie abitabile", + "living_area_none": "Nessuna superficie abitabile · pavimento {floor}", + "living_area_low": "Superficie abitabile {living} (pavimento {floor}, di cui {low} sotto 2 m)", + "living_area_hint": "Calcolato come la Wohnflächenverordnung tedesca: il pavimento dentro le pareti, per intero da 2 m di altezza libera, a metà tra 1 e 2 m (sotto le falde), per niente sotto 1 m. Un valore indicativo, non un rilievo.", + "living_area_floor": "Superficie abitabile: {floor}", + "living_area_floor_house": "Superficie abitabile di questo piano: {floor} · tutta la casa: {house}", + "print_plan": "Stampa pianta / PDF", + "print_plan_hint": "Ogni piano come pianta pulita con misure e superfici, più una tabella delle superfici – da stampare o salvare in PDF dalla finestra di stampa.", + "print_title": "Pianta", + "print_room": "Stanza", + "print_floor_area": "Superficie", + "print_living": "Superficie abitabile", + "print_low": "sotto 2 m", + "print_total": "Totale", + "print_blocked": "La finestra di stampa è stata bloccata – consenti i pop-up per Home Assistant.", + "check_open": "Controlla la pianta", + "note": "Nota", + "note_add": "Nota qui", + "note_text": "Testo", + "note_placeholder": "es. «cambiare il filtro» o «fusibile 12»", + "note_due": "Scadenza", + "note_due_hint": "Da quel giorno il segnaposto diventa arancione.", + "note_is_due": "Questa nota è scaduta.", + "keys_title": "Tasti dell'editor", + "keys_undo": "Annulla", + "keys_redo": "Ripeti", + "keys_duplicate": "Duplica la stanza", + "keys_delete": "Elimina la selezione", + "keys_nudge": "Sposta la selezione di un passo di griglia", + "keys_nudge_10": "… di 10 cm", + "keys_nudge_1": "… di 1 cm", + "keys_rotate": "Ruota il mobile di 90° (Maiusc: indietro)", + "keys_lock": "Blocca o sblocca un mobile, un dispositivo o una falda", + "keys_close_shape": "Chiudi la forma libera", + "keys_escape": "Annulla, esci dallo strumento, deseleziona", + "keys_straight": "Mentre disegni: linee dritte", + "keys_sheet": "Questo elenco", + "tour_title": "Primi passi", + "tour_1_title": "Disegna le stanze", + "tour_1": "Disegna le stanze con «{rect}» o «{free}»; le pareti vengono da sole. Assegna a ogni stanza la sua area di Home Assistant – così NextFloor trova i suoi dispositivi. Con le aree già pronte, «{rooms}» nel modulo del piano le crea tutte insieme.", + "tour_2_title": "Porte e finestre", + "tour_2": "«{opening}» le mette su una parete. Collega il loro contatto o la tapparella – in 3D si aprono e chiudono con esso, e le finestre aperte avvisano.", + "tour_3_title": "Mobili e dispositivi", + "tour_3": "«{furniture}» apre la libreria – o costruisci i tuoi pezzi nel 🛠️ laboratorio. Scegli una stanza e sotto trovi i dispositivi della sua area, pronti da posizionare; le lampade si accendono del colore della loro luce.", + "tour_4_title": "Guarda e controlla", + "tour_4": "«{split}» mostra la casa mentre disegni; in alto passi alla vista 3D. «{check}» elenca cosa manca ancora – e ? mostra i tasti in ogni momento.", + "tour_next": "Avanti", + "tour_back": "Indietro", + "tour_done": "Si parte", + "tour_skip": "Salta", + "check_open_hint": "Elenca cosa manca o non va nella pianta, con una correzione in un tocco.", + "check_title": "Controllo della pianta", + "check_all_good": "Tutto a posto – nulla da segnalare.", + "check_hint": "{n} punti trovati. I pulsanti blu cambiano la pianta (annulla funziona come sempre), gli altri mostrano il punto.", + "check_room_no_area": "«{room}» non ha un'area di Home Assistant: i suoi dispositivi non vengono trovati.", + "check_room_no_area_named": "«{room}» non ha un'area – l'area libera «{area}» ha lo stesso nome.", + "check_areas_unplaced": "{n} aree di questo piano non hanno ancora una stanza: {names}", + "check_devices_unplaced": "«{room}»: {n} dispositivi dell'area non sono ancora nella pianta.", + "check_rooms_overlap": "«{a}» e «{b}» si sovrappongono.", + "check_opening_off_wall": "Una porta o finestra in «{room}» non è su una parete.", + "check_entity_missing": "{n} segnaposto puntano a entità che Home Assistant non conosce più ({ids}).", + "check_furniture_entity_missing": "Un mobile è collegato a {id} – quell'entità non esiste più.", + "check_battery_low": "Batteria scarica: {name} ({level} %)", + "battery_low_n": "Batteria scarica: {names}", + "check_standby": "{name} assorbe {w} W da spento – circa {cost} l'anno.", + "check_fix_show": "Mostra", + "check_fix_set_area": "Collega «{area}»", + "check_fix_add_rooms": "Aggiungi le stanze", + "check_fix_place": "Posiziona {n}", + "check_fix_remove": "Rimuovi {n}", + "floor_layer_hint": "Questo piano non è un livello dell'edificio ma uno strato – tutti gli alberi o le decorazioni. La vista 3D mostra in alto un occhio che lo mostra o nasconde su ogni dispositivo.", + "no_ha_floor": "– nessuno –", + "area_rooms": "Aggiungi stanze dalle aree di HA ({n})", + "area_rooms_hint": "Aggiunge una stanza (4 × 3 m) per ogni area di questo piano; poi trascinala in posizione e regola gli angoli", + "floor_name": "Nome", + "elevation": "Quota (m)", + "floor_shift": "Sposta il piano (m)", + "floor_shift_apply": "Sposta", + "floor_shift_hint": "Sposta di X e Z tutte le stanze, gli arredi, i dispositivi, le aree esterne, le pareti libere e l'immagine di sfondo di questo piano. Le falde del tetto restano.", + "height": "Altezza soffitto (m)", + "cut_height": "Altezza di taglio (m)", + "delete_floor": "Elimina piano", + "delete_floor_confirm": "Eliminare il piano «{name}» con tutte le sue stanze?", + "move_up": "Sposta su", + "move_down": "Sposta giù", + "default_floor": "Piano terra", + "new_floor": "Piano {n}", + "tool_select": "Seleziona", + "tool_rect": "Rettangolo", + "tool_polygon": "Forma libera", + "undo": "Annulla", + "redo": "Ripeti", + "fit": "Mostra tutto", + "room": "Stanza", + "rooms": "Stanze", + "room_name": "Nome", + "area": "Area", + "no_area": "Nessuna area", + "sub_area_add": "+ Area nella stanza", + "sub_area_hint": "Una parte della stanza con un'area propria in Home Assistant ma senza pareti – un angolo lettura, uno scaffale, un angolo cottura. I suoi dispositivi e sensori appartengono a questa stanza.", + "material": "Pavimento", + "x": "X (m)", + "z": "Y (m)", + "width": "Larghezza (m)", + "depth": "Profondità (m)", + "points": "Angoli", + "delete_point": "Elimina angolo", + "duplicate": "Duplica", + "delete": "Elimina", + "new_room": "Stanza {n}", + "settings": "Impostazioni", + "pendant_shape": "Forma", + "pendant_shade": "Paralume", + "paint_colour": "Colore della vernice", + "pendant_globe": "Globo", + "pendant_cone": "Cono", + "pendant_drum": "Tamburo", + "sofa_shape": "Forma", + "sofa_straight": "Lineare", + "sofa_l": "A L (specchia: altro lato)", + "sofa_u": "A U", + "pkg_open": "Arreda …", + "pkg_hint": "Gli arredi vanno contro le pareti della stanza; le lampade si collegano alle luci dell'area. Regola i singoli elementi dopo: Ctrl+Z annulla tutto.", + "pkg_done": "{n} elementi posizionati: Ctrl+Z annulla.", + "pkg_kitchen_row": "Cucina lineare", + "pkg_kitchen_row_desc": "Fila sulla parete di fondo con frigorifero, forno, lavello, lavastoviglie e piano cottura, pensile, tavolo da pranzo con lampada a sospensione", + "pkg_kitchen_l": "Cucina ad L", + "pkg_kitchen_l_desc": "File in fondo e a sinistra, isola con sgabelli", + "pkg_bath": "Bagno", + "pkg_bath_desc": "Lavabo, WC, vasca, lavatrice, faretto a incasso", + "pkg_bedroom": "Camera da letto", + "pkg_bedroom_desc": "Letto matrimoniale con due comodini, armadio, cassettiera, plafoniera", + "pkg_living": "Soggiorno", + "pkg_living_desc": "Mobile TV, divano, tavolino, tappeto, poltrona, libreria, lampada da terra, pianta", + "pkg_dining": "Sala da pranzo", + "pkg_dining_desc": "Tavolo con quattro sedie, credenza, lampada a sospensione", + "pkg_office": "Ufficio", + "pkg_office_desc": "Scrivania con sedia da ufficio, due librerie, plafoniera", + "pkg_kids": "Cameretta", + "pkg_kids_desc": "Letto singolo, scrivania, libreria, tappeto", + "pkg_hall": "Ingresso", + "pkg_hall_desc": "Appendiabiti, due faretti a incasso", + "spots_place": "Posiziona faretti", + "spots_type": "Lampada", + "spots_cols": "Colonne (sinistra–destra)", + "spots_rows": "File (davanti–dietro)", + "spots_add": "Posiziona {n} lampade", + "spots_placed": "{n} lampade posizionate.", + "spots_hint": "Tutte le lampade seguono la luce scelta (ad es. faretti su un unico dimmer). Dopo, ognuna si può spostare e collegare a un'altra luce come qualsiasi arredo.", + "cancel": "Annulla", + "backup": "Backup", + "backup_history": "Punti di ripristino", + "share_view": "Condividi una vista", + "share_view_hint": "Salva la casa come un piccolo file che si apre in qualsiasi browser senza Home Assistant (tramite la demo online di NextFloor) – per mostrarla a famiglia o progettisti. Senza dispositivi né entità, come un modello.", + "share_view_title": "La nostra casa in NextFloor", + "share_view_needs_js": "Questa pagina richiede JavaScript e una connessione internet.", + "share_view_file": "vista", + "share_view_done": "Vista salvata – apri il file in un browser o condividilo.", + "version_save": "Salva questo stato …", + "version_save_hint": "Conserva la pianta con un nome («prima della ristrutturazione»). Gli stati con nome restano quando i punti automatici se ne vanno.", + "version_name_prompt": "Nome di questo stato (es. «prima della ristrutturazione»):", + "version_saved": "Stato «{name}» salvato.", + "version_compare": "Confronta", + "version_delete_confirm": "Eliminare «{name}»?", + "version_same": "Nessuna differenza con la pianta.", + "version_diff_n": "{n} differenze con la pianta attuale:", + "diff_floor_added": "Piano «{name}» aggiunto", + "diff_floor_removed": "Piano «{name}» rimosso", + "diff_room_added": "Stanza «{name}» aggiunta", + "diff_room_removed": "Stanza «{name}» rimossa", + "diff_room_renamed": "«{detail}» ora si chiama «{name}»", + "diff_room_reshaped": "«{name}» rimodellata ({detail} m²)", + "diff_opening_added": "{name} aggiunto/a ({detail})", + "diff_opening_removed": "{name} rimosso/a ({detail})", + "diff_furniture_added": "{name} aggiunto", + "diff_furniture_removed": "{name} rimosso", + "diff_furniture_moved": "{name} spostato o modificato", + "diff_device_added": "Dispositivo {name} posizionato", + "diff_device_removed": "Dispositivo {name} rimosso", + "diff_device_moved": "Dispositivo {name} spostato", + "backup_none": "Ancora nessuno. Durante la modifica si salva un punto di ripristino al massimo ogni 10 minuti.", + "backup_summary": "{rooms} stanze, {furniture} elementi", + "backup_restore": "Ripristina", + "backup_restore_confirm": "Ripristinare lo stato del {time}? Lo stato attuale viene conservato come punto di ripristino.", + "backup_restored": "Ripristinato.", + "backup_file": "File", + "backup_export": "Esporta", + "backup_export_share": "Condividi come modello", + "backup_export_share_hint": "Senza aree, dispositivi, sensori e immagini, da passare ad altri.", + "backup_import": "Importa …", + "backup_import_confirm": "Sostituire l'intera planimetria con il file? Lo stato attuale viene conservato come punto di ripristino.", + "backup_import_error": "Il file non è una planimetria NextFloor ({error}).", + "backup_imported": "Importato.", + "backup_hint": "Le immagini di sfondo non fanno parte del file.", + "backup_full": "Backup completo", + "backup_full_export": "Salva tutto (planimetria, immagini, pacchetti)", + "backup_full_import": "Ripristina un backup completo …", + "backup_full_hint": "Un file con la planimetria, tutte le immagini di sfondo e degli schermi e i pacchetti installati. Al ripristino ogni pacchetto viene ricontrollato; la chiave di licenza non è inclusa.", + "backup_full_confirm": "Sostituire planimetria, immagini e pacchetti con il backup? Lo stato attuale resta come punto di ripristino.", + "backup_full_not_backup": "Questo non è un backup completo di NextFloor.", + "backup_full_restored": "Backup ripristinato: {packs} pacchetti, {pictures} immagini.", + "backup_full_skipped": "Saltati (non leggibili): {packs}.", + "export_name_full": "completo", + "device_confirm": "Chiedi prima di commutare", + "device_confirm_hint": "Un tocco in 3D, il menu rapido e il pannello della stanza chiedono prima. Un doppio tocco sulla stanza esclude questo dispositivo.", + "cover_confirm_hint": "Apri, chiudi e posizioni chiedono prima nel menu rapido e nel pannello della stanza, e uno scorrimento sul marcatore non muove più la tapparella (ruota invece la vista). Stop non chiede mai.", + "blind_kind": "Tipo di schermatura", + "blind_roller": "Tapparella esterna", + "blind_venetian": "Frangisole a lamelle", + "blind_inside": "Tenda a rullo interna", + "cover2_entity": "Seconda tapparella (metà destra)", + "cover_my": "Posizione preferita «My» (%, 0 = nessuna)", + "cover_my_go": "Alla posizione preferita ({p} %)", + "blind_hint": "Un frangisole ruota le lamelle in 3D con l'inclinazione della tapparella; una tenda interna pende dietro il vetro. Una finestra larga può avere una seconda tapparella per la metà destra. La posizione preferita appare come «My» nel menu rapido: una tapparella con posizioni ci va, un motore Somfy RTS senza ritorno va al suo My con Stop.", + "confirm_switch": "Commutare davvero {name}?", + "lock_confirm_unlock": "Sbloccare davvero {name}?", + "gang_switch_one": "Interruttori", + "furn_cover_entity": "Si muove con", + "furn_cover_hint": "La tenda, lo schermo, la tenda da sole o il cancello segue questa entità di copertura (tapparella, tenda, tenda da sole, cancello) e si muove con essa. Un tocco apre il suo menu (su, stop, giù).", + "furn_cover_inverted": "Inverti la direzione", + "furn_cover_inverted_hint": "Per una tenda da sole o una tenda che nel piano si muove al contrario: aperta appare chiusa e viceversa.", + "gang_switch": "Il tasto {n} commuta", + "gang_socket_one": "Presa alimentata da", + "gang_socket": "Presa {n} alimentata da", + "gang_switch_hint": "Un tasto si illumina mentre la sua luce è accesa (nel suo colore). Un tocco lo commuta; con più tasti un piccolo menu chiede quale. La stessa entità può stare su più interruttori.", + "gang_socket_hint": "Una presa si illumina di verde mentre il suo interruttore è acceso, più forte quanto più assorbe. Un tocco la commuta; con più prese un piccolo menu chiede quale.", + "lock_confirm_lock": "Bloccare {name}?", + "opening_lock": "Serratura smart", + "opening_lock_hint": "Un tocco sulla porta la blocca o la sblocca (chiedendo sempre prima). Mentre è sbloccata, il suo bordo si illumina.", + "split_handle_hint": "Trascina: larghezza della planimetria e della vista 3D", + "wall_exterior": "Parete esterna (m)", + "wall_interior": "Parete interna (m)", + "grid": "Griglia (m)", + "units": "Mostra le lunghezze in", + "units_metric": "Metri", + "units_imperial": "Piedi e pollici", + "units_hint": "Come appaiono lunghezze e superfici nella planimetria, nei moduli e nella vista parete. Gli input restano in metri.", + "background": "Modello (immagine della planimetria)", + "background_upload": "Scegli immagine …", + "background_width": "Larghezza nella planimetria (m)", + "background_opacity": "Opacità", + "background_rotation": "Rotazione (°)", + "background_edit": "Sposta, scala e ruota", + "background_edit_done": "Fatto", + "background_edit_hint": "Con la modalità attiva: trascinando l'immagine la sposti, la maniglia in basso a destra la scala. Adatta prima l'immagine alla scala, poi ruotala.", + "background_remove": "Rimuovi modello", + "hint_select": "Tocca una stanza per selezionarla · trascina gli angoli · «+» su un bordo inserisce un angolo · le frecce spostano · Canc elimina · Ctrl+Z", + "hint_rect": "Trascina per disegnare un rettangolo", + "hint_polygon": "Posiziona gli angoli · tocca il primo angolo o premi Invio per chiudere · Esc annulla", + "hint_empty": "Aggiungi prima un piano.", + "area_m2": "{a} m²", + "overlap_warning": "Le stanze si sovrappongono: lì le pareti sono incomplete.", + "read_only": "Solo gli amministratori possono modificare la planimetria.", + "side_failed": "Impossibile mostrare questo modulo ({error}). La planimetria resta utilizzabile. Segnala il testo in una issue su GitHub.", + "mat_wood": "Legno", + "mat_oak": "Rovere", + "mat_tiles": "Piastrelle", + "mat_carpet": "Moquette", + "mat_stone": "Pietra", + "mat_concrete": "Cemento", + "card_name": "NextFloor", + "card_description": "La tua casa in 3D (neon).", + "stats": "{calls} draw call · {tris} triangoli", + "stats_fps": "{fps} fps (fotogramma più lento {ms} ms)", + "stats_idle": "A riposo (0 fps)", + "stats_busy_floors": "piani", + "stats_busy_openings": "porte/finestre", + "stats_busy_flash": "lampeggio", + "stats_busy_roof": "tetto", + "stats_busy_flow": "flusso di energia", + "stats_busy_effect": "effetto colore", + "stats_busy_robot": "robot", + "stats_busy_orbit": "rotazione telecamera", + "stats_busy_tint": "tinta stanza", + "stats_low": "livello tablet, rapporto pixel {r}", + "stats_full": "livello pieno, rapporto pixel {r}", + "floors_apart": "Separati", + "floors_stacked": "Impilati", + "roof_keep": "Tetto fisso", + "roof_keep_hint": "Il tetto resta sulla casa durante lo zoom invece di sollevarsi e sparire", + "floor_rooms_one": "1 stanza", + "floor_rooms": "{n} stanze", + "quality": "Qualità", + "quality_auto": "Auto", + "quality_low": "Tablet", + "quality_high": "Alta", + "state_on": "Acceso", + "state_off": "Spento", + "state_open": "Aperto", + "state_closed": "Chiuso", + "state_opening": "In apertura", + "state_closing": "In chiusura", + "state_playing": "In riproduzione", + "state_paused": "In pausa", + "state_idle": "Inattivo", + "state_locked": "Bloccato", + "state_unlocked": "Sbloccato", + "state_detected": "Rilevato", + "state_clear": "Libero", + "state_unavailable": "Non disponibile", + "state_heat": "Caldo", + "state_cool": "Freddo", + "state_auto": "Auto", + "state_heat_cool": "Caldo/freddo", + "state_dry": "Deumidifica", + "state_fan_only": "Ventola", + "devices": "Dispositivi", + "devices_none_area": "Collega la stanza a un'area e i suoi dispositivi compariranno qui.", + "devices_none": "L'area non ha dispositivi adatti.", + "devices_place_all_n": "Posiziona tutti i {n} …", + "devices_place_all_confirm": "Inserire {n} dispositivi nella stanza in una volta? (Ctrl+Z o «Annulla» li rimuove tutti in un passo.)", + "devices_src_area": "Questa area", + "devices_src_other": "Altre aree", + "devices_src_none": "Nessuna area", + "panel_hide": "Nascondi dal pannello della stanza", + "panel_unhide": "Mostra di nuovo nel pannello della stanza", + "panel_state_hide": "Nascondi lo stato nel pannello della stanza (ad es. una copertura che segnala solo \"unknown\")", + "panel_state_show": "Mostra di nuovo lo stato nel pannello della stanza", + "devices_place": "Posiziona", + "devices_remove": "Rimuovi", + "devices_hint": "I dispositivi posizionati appaiono in 3D. Trascinali nella planimetria per spostarli.", + "panel_lights": "Luci", + "panel_covers": "Coperture", + "panel_climate": "Riscaldamento", + "panel_media": "Media", + "panel_switches": "Interruttori", + "panel_sensors": "Sensori", + "panel_scenes": "Scene e script", + "panel_announce": "📢 Annuncio", + "announce_placeholder": "Il tuo messaggio …", + "announce_send": "Di'", + "announce_sent": "Detto: «{message}»", + "announce_failed": "Annuncio non riuscito: {error}", + "announce_phrase_1": "È pronto in tavola!", + "announce_phrase_2": "È ora di andare a letto!", + "announce_phrase_3": "Scendete, per favore!", + "announce_phrase_4": "Partiamo tra poco!", + "announce_phrase_5": "Il cane deve uscire!", + "state_recording": "Registrazione", + "state_streaming": "Streaming", + "panel_all_off": "Spegni tutto", + "readable": "Facile da leggere", + "readable_hint": "Contrasti più forti e testo più grande – per tablet a parete e chi legge meglio così.", + "plain": "Solo pianta", + "plain_hint": "Mostra solo pareti, porte, finestre e scale, senza mobili. Dispositivi e relativi pin restano.", + "right_back": "Clic destro = indietro", + "right_back_hint": "Un breve clic destro nella vista 3D torna indietro di un passo: dalla stanza al piano, dal piano alla casa (come un doppio tocco su uno spazio vuoto). Trascinare con il tasto destro sposta ancora la vista.", + "stl": "Stampa 3D (STL)", + "stl_hint": "Salva la casa come file STL (pareti, pavimenti, mobili e aree esterne di tutti i piani) per la stampa 3D, in scala 1:100 (un metro diventa 10 mm). Finestre, luci e tetto non sono inclusi; uno slicer ripara il file se serve.", + "card_plain": "Solo pianta", + "card_rooms": "Solo queste stanze", + "card_rooms_hint": "La scheda mostra solo le stanze selezionate con mobili, dispositivi, porte e finestre (ad esempio per un tablet in cucina). Nulla selezionato: tutta la pianta.", + "card_templates": "Modelli di scheda", + "card_templates_hint": "Imposta una scheda una volta qui (con le impostazioni della scheda) e indica solo il nome su ogni tablet: `template: kitchen_tablet`. Le modifiche raggiungono tutte le schede che lo usano; quanto scritto sulla scheda stessa ha la precedenza sul modello.", + "template_name": "Nuovo modello (nome)", + "template_add": "Crea modello", + "template_reload": "Ricarica gli schermi con questo modello", + "template_reload_all": "Ricarica tutti gli schermi", + "template_use": "Sulla scheda della dashboard: `template: {name}`", + "card_template": "Modello di scheda", + "card_template_none": "nessuno (solo questa scheda)", + "card_readable": "Facile da leggere", + "all_off_n": "Spegni tutto ({n})", + "all_off_hint": "Spegne luci, interruttori, ventilatori e media della stanza; si può annullare per dieci secondi.", + "all_off_done": "Tutto spento.", + "all_off_undo": "Annulla", + "all_off_floor": "Spegni tutto in {floor} ({n} dispositivi), annullabile per dieci secondi", + "mood_save": "Salva atmosfera", + "mood_save_hint": "Salva come brillano ora le luci della stanza come atmosfera – un tocco la ripristina, «→» la porta in un'altra stanza.", + "mood_new": "Atmosfera", + "mood_set": "Imposta questa atmosfera", + "mood_carry": "Porta in un'altra stanza", + "panel_all_on": "Accendi tutto", + "view_options": "Vista: qualità, aspetto, marcatori, FPS", + "panel_all_open": "Tutto su", + "panel_all_close": "Tutto giù", + "central": "Centrale: tutte le luci, le tapparelle e i preferiti", + "central_house": "Tutta la casa", + "central_lights": "Luci", + "central_covers": "Tapparelle", + "central_on": "Accendi", + "central_off": "Spegni", + "central_open": "Su", + "central_close": "Giù", + "central_sure": "Sicuro?", + "central_favorites": "Preferiti", + "central_no_favorites": "Ancora nessun preferito. Imposta scene, script e interruttori nell'editor in \"Preferiti\".", + "card_central": "Stella con il menu centrale", + "card_central_hint": "Tutte le luci e le tapparelle del piano o della casa e i preferiti dell'editor.", + "favorites": "Preferiti", + "favorites_hint": "Scene, script, automazioni, pulsanti e interruttori per il menu centrale (stella) della vista 3D: festa, simulazione di presenza, ombreggiatura, irrigazione.", + "favorites_add": "Aggiungi un preferito", + "favorite_floor": "In quale piano compare questo preferito", + "favorite_all_floors": "Tutti i piani", + "outside_hidden": "Esterno: nascondi dispositivi", + "outside_hidden_hint": "Dispositivi che il pannello Esterno non deve mostrare (restano nel piano).", + "outside_hidden_add": "Nascondi un dispositivo", + "room_facts": "Pannello della stanza: dati mostrati", + "room_fact_sun": "Ore di sole", + "room_fact_comfort": "Comfort", + "room_fact_air": "Avviso di ventilazione", + "room_fact_circuits": "Circuiti", + "background_handles_hint": "L'immagine ora ha maniglie come un arredo: trascinarla la sposta, l'angolo in basso a destra la scala, la maniglia rotonda in alto la ruota (Maiusc per passi di 15°). Quando è a posto, tocca \"Fatto\" e resterà ferma.", + "background_fixed_hint": "L'immagine resta ferma, puoi disegnarci sopra. Per regolarla tocca \"Sposta, scala e ruota\".", + "bg_level": "Raddrizza", + "bg_level_cancel": "Annulla il raddrizzamento", + "bg_level_first": "Tocca l'inizio di una parete nell'immagine che deve essere dritta (orizzontale o verticale).", + "bg_level_second": "Ora tocca la fine di quella parete: l'immagine ruota per adattarsi.", + "bg_ruler": "Scala con un righello", + "bg_ruler_cancel": "Annulla il righello", + "bg_ruler_first": "Tocca l'inizio di un tratto di lunghezza nota nell'immagine, ad es. una parete quotata.", + "bg_ruler_second": "Ora tocca la fine del tratto.", + "bg_ruler_length_hint": "Misurato nella planimetria: {m} m. Inserisci la lunghezza reale e l'immagine verrà scalata.", + "bg_ruler_length": "Lunghezza reale (m)", + "bg_ruler_apply": "Applica la scala", + "thumbs_fold": "Riduci le immagini dei piani a pulsanti", + "thumbs_show": "Mostra di nuovo le immagini dei piani", + "room_start_view": "Vista come inizio di questa stanza", + "room_start_view_hint": "Toccando la stanza in 3D, la telecamera vola esattamente alla vista mostrata ora dal riquadro 3D a destra: angolo, zoom e inquadratura. Attiva prima 3D a fianco, ruota e ingrandisci la stanza, poi tocca.", + "room_start_view_reset": "Rimuovi la vista iniziale della stanza (di nuovo dall'alto)", + "room_start_view_need_pane": "Attiva prima \"3D a fianco\", poi ruota e ingrandisci la stanza come deve aprirsi.", + "floor_start_view": "Vista come inizio di questo piano", + "floor_start_view_hint": "Questo piano si apre in 3D come è ora il riquadro 3D a destra, ad es. il piano terra da davanti e quello superiore da dietro. Attiva prima 3D a fianco, ruotalo, poi tocca.", + "floor_start_view_reset": "Rimuovi la vista iniziale del piano (di nuovo come la casa)", + "floor_start_view_need_pane": "Attiva prima \"3D a fianco\" e ruota il piano come deve aprirsi.", + "ambilight": "Bagliore dietro la TV (%)", + "ambilight_hint": "Quanto brilla dietro la TV mentre è in riproduzione. 0 lo spegne (ad es. se hai strisce LED sulla TV), 100 è l'intensità normale.", + "sound_rings": "Onde sonore (%)", + "sound_rings_hint": "Quanto si allargano le onde intorno all’altoparlante durante la riproduzione. 0 le spegne, immagine e bagliore restano; 100 è la dimensione normale. La dimensione segue anche il volume dell’altoparlante: più basso, più piccolo.", + "glow_scale": "Bagliore in 3D (%)", + "light_effects": "Animazioni degli effetti in 3D", + "light_effects_hint": "Associa solo nomi di effetto esatti di HA. Gli effetti non associati mantengono il colore statico di HA. Non cambia nulla in Home Assistant.", + "light_effects_enabled": "Consenti animazioni per questa lampada", + "light_effect_unmapped": "Non associato (statico)", + "light_effect_add": "Aggiungi nome effetto esatto", + "light_effect_name_limit": "Il nome esatto dell'effetto deve avere da 1 a 255 caratteri. Non verrà accorciato.", + "light_effect_count_limit": "Al massimo 100 associazioni. Rimuovine prima una esistente.", + "light_effect_exists": "Questo nome di effetto è già associato. L'associazione esistente viene mantenuta.", + "light_animation_none": "Statico", + "light_animation_rainbow": "Arcobaleno (sostituisce il colore)", + "light_animation_pulse": "Pulsazione (intensità)", + "light_animation_flicker": "Sfarfallio (intensità)", + "glow_scale_hint": "Quanto brilla la lampada in 3D: sotto il 100 % attenua le strisce LED luminose perché la stanza non bruci; sopra il 100 % fa brillare di più una lampada debole. Non commuta nulla in Home Assistant.", + "vehicle_to_spot": "Trasforma in posto auto", + "vehicle_to_spot_hint": "Un veicolo come semplice arredo sta sempre lì. Come posto auto appare solo mentre un sensore rileva l'auto, ed è lì che si collega il dispositivo dell'auto (carica, autonomia, chiusura, clima).", + "as_furniture": "Mostra come arredo", + "as_furniture_hint": "Sostituisce il marcatore con un arredo nello stesso punto, collegato a questo dispositivo: un altoparlante per un media player, una lampada per una luce. Ctrl+Z annulla.", + "as_furniture_pick": "Scegli arredo …", + "as_device": "Torna a marcatore dispositivo", + "as_device_hint": "Sostituisce l'arredo con il semplice marcatore del suo dispositivo nello stesso punto.", + "presets": "Stazioni e playlist (Suono)", + "presets_hint": "Mostrate nel menu rapido di ogni altoparlante sotto \"Riproduci\", accanto alle sorgenti del lettore. Per un Echo (Alexa Media Player): scrivi SPOTIFY, AMAZON_MUSIC o TUNEIN e come contenuto ciò che diresti (\"Rock Antenne\"). Per Sonos, Music Assistant e altri: scrivi music o url con un indirizzo di stream o un URI.", + "preset_type": "Tipo", + "preset_type_hint": "media_content_type di play_media, ad es. music, url, playlist, SPOTIFY, AMAZON_MUSIC, TUNEIN", + "preset_content": "Contenuto", + "preset_content_hint": "media_content_id: URL dello stream, URI (spotify:playlist:…) o, per Alexa, una frase di ricerca", + "preset_speakers": "Solo su questi altoparlanti (nessuno = su tutti)", + "media_play": "Riproduci", + "media_pause": "Pausa", + "media_previous": "Precedente", + "media_next": "Successivo", + "media_volume": "Volume", + "media_sources": "Sorgenti", + "preset_add": "Stazione o playlist", + "own_buttons": "Pulsanti propri", + "own_buttons_hint": "Mostrati nel menu centrale (stella) sotto i preferiti: apri un percorso di dashboard, mostra i dettagli di un'entità, chiama un servizio o apri un popup browser_mod con una tua card.", + "own_alerts": "Avvisi personali", + "circuits": "Quadro elettrico", + "circuits_hint": "I circuiti con le stanze che alimentano. Il pannello della stanza li nomina e la ricerca li trova («F12»).", + "circuit_name": "Nome", + "circuit_new": "Nuovo circuito", + "circuit_add": "Aggiungi un circuito", + "circuit_add_room": "Aggiungi una stanza", + "own_alerts_hint": "Una riga nella barra degli avvisi della vista 3D finché un'entità è in uno stato – «Serbatoio vuoto» dal robot, «Lavastoviglie finita». Più stati con virgole; per i numeri <20 o >80.", + "own_alert_entity": "Quando …", + "own_alert_state": "… è nello stato (vuoto = acceso)", + "own_alert_text": "… allora questo avviso", + "own_alert_color": "Colore", + "own_alert_tap": "Un tocco", + "own_alert_tap_info": "apre i dettagli", + "own_alert_tap_toggle": "commuta l'entità", + "own_alert_tap_room": "va nella stanza", + "own_alert_house": "Tutta la casa", + "own_alert_new": "Nuovo avviso", + "own_alert_add": "Aggiungi avviso", + "today": "Oggi", + "today_none": "Niente in programma oggi.", + "today_calendars": "Calendari per «Oggi»", + "today_calendars_hint": "Gli appuntamenti di questi calendari compaiono in alto a destra nella vista 3D sulla scheda «Oggi», con i bidoni ritirati oggi o domani. Un tocco sul titolo chiude la scheda.", + "own_button_state": "Si illumina finché … è acceso (facoltativo)", + "own_button_label": "Etichetta", + "own_button_action": "Azione", + "own_button_new": "Nuovo pulsante", + "own_button_add": "Pulsante proprio", + "own_action_navigate": "Apri un percorso", + "own_action_more_info": "Dettagli entità", + "own_action_service": "Chiama un servizio", + "own_action_fire_dom_event": "fire-dom-event (browser_mod)", + "own_target_navigate": "Percorso", + "own_target_more_info": "Entità", + "own_target_service": "Servizio (dominio.servizio)", + "own_data": "Dati (JSON)", + "own_data_hint": "Per un servizio i suoi dati, per fire-dom-event il contenuto dell'evento, ad es. {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}.", + "own_data_bad": "Non è un oggetto JSON valido.", + "panel_no_area": "Questa stanza non è collegata a un'area. Puoi collegarla nell'editor.", + "panel_empty": "Nessun dispositivo di questa stanza è nella planimetria. Nell'editor posiziona i dispositivi o sceglili per il pannello della stanza con ☆.", + "close": "Chiudi", + "panel_fold": "Riduci (la stanza resta in vista)", + "panel_unfold": "Riapri", + "brightness": "Luminosità", + "color_temp": "Temperatura colore", + "color": "Colore", + "position": "Posizione", + "cover_open": "Apri", + "cover_stop": "Stop", + "cover_tilt": "Lamelle", + "cover_tilt_open": "Lamelle aperte", + "cover_tilt_close": "Lamelle chiuse", + "cover_close": "Chiudi", + "target_temp": "Obiettivo", + "current_temp": "Attuale", + "temp_down": "Più fresco", + "temp_up": "Più caldo", + "volume": "Volume", + "play_pause": "Play/pausa", + "previous": "Precedente", + "next": "Successivo", + "run": "Esegui", + "details": "Dettagli", + "hold_hint": "Tocco commuta · pressione lunga apre i dettagli", + "tool_opening": "Porte e finestre", + "tool_furniture": "Arredi", + "qm_off": "Spento", + "find": "Cerca", + "find_placeholder": "Dov'è …? Dispositivo o stanza", + "find_none": "Nessun risultato", + "swipe_off": "Spento", + "panel_pin": "Mostra nel pannello della stanza", + "panel_unpin": "Non mostrare nel pannello della stanza", + "devices_panel_hint": "Il pannello della stanza mostra i dispositivi della planimetria. ☆ aggiunge un dispositivo al pannello senza posizionarlo.", + "card_section_view": "Vista", + "card_size": "Dimensione", + "card_size_fixed": "Altezza fissa", + "card_size_fill": "Riempi lo schermo", + "card_fill_hint": "Funziona meglio in una vista dashboard di tipo «Pannello (card singola)»: la card occupa allora tutto lo spazio.", + "card_controls": "Interruttori nella card", + "card_floor_thumbs": "Piani in miniatura", + "card_floor_thumbs_hint": "Piccole immagini dei piani a lato: toccane una per cambiare", + "card_floor_thumbs_hint_start": "Il piano scelto è quello da cui parte la card; le immagini a lato passano agli altri", + "card_room_names": "Mostra i nomi delle stanze", + "card_section_kiosk": "Tablet a parete (kiosk)", + "card_section_features": "Funzioni", + "card_weather_plan": "come impostato nella planimetria", + "card_pro_hint": "Scia di movimento e parete di telecamere appartengono alle telecamere: la scia mostra l'ultima mezz'ora, la parete tutte le telecamere della planimetria.", + "card_idle_return": "Torna alla vista iniziale dopo", + "card_idle_off": "Mai", + "card_idle_min": "{n} min senza tocchi", + "card_idle_hint": "Dopo l'attesa la card chiude la stanza e mostra di nuovo la vista iniziale.", + "card_night": "Attenuazione notturna", + "card_night_off": "Spento", + "card_night_sun": "In base al sole", + "card_night_time": "Fascia oraria", + "card_night_range": "Fascia oraria (ad es. 22:00-06:00)", + "card_idle_orbit": "Rotazione telecamera come salvaschermo", + "card_idle_orbit_hint": "Dopo il ritorno la vista ruota lentamente finché qualcuno tocca il tablet", + "card_dashboard": "Pulsante verso una dashboard (percorso)", + "card_dashboard_label": "Etichetta del pulsante", + "card_dashboard_hint": "Un pulsante in alto a destra nella card apre la dashboard o la vista con questo percorso, ad es. /lovelace/home o /dashboard-house/0. Senza etichetta mostra ⌂.", + "card_alerts": "Mostra avvisi", + "card_alerts_hint": "Fumo, gas, CO, acqua, allarme e finestre aperte con la pioggia: la stanza pulsa, in alto appare una nota", + "card_alert_jump": "Vai alla stanza di un nuovo avviso", + "card_alert_jump_hint": "La vista passa da sola al piano e alla stanza dell'avviso", + "card_scenes": "Pulsanti scena nella stanza", + "card_scenes_hint": "Scene e script dell'area come pulsanti sotto la vista 3D mentre è selezionata una stanza", + "card_sensor_bar": "Sensori propri in alto", + "card_sensor_bar_hint": "I sensori scelti nell'editor (Impostazioni) in alto a sinistra della scheda", + "card_central_open": "Menu a stella aperto e grande", + "card_central_open_hint": "Preferiti e pulsanti propri sono aperti fin dall'inizio, più grandi", + "card_keep_camera": "Mantieni la vista cambiando piano", + "card_keep_camera_hint": "Stesso lato, altezza e distanza su ogni piano", + "card_today": "Scheda «Oggi»", + "card_today_hint": "Appuntamenti di oggi e bidoni da esporre, in alto a destra", + "card_announcements": "Annunci", + "card_announcements_hint": "Gli annunci (azione «NextFloor: Annuncio») compaiono in grande sulla scheda, con un gong, e vengono pronunciati", + "weather_short": "Meteo", + "weather_entity": "Entità meteo", + "weather_effects": "Effetti meteo in 3D", + "card_weather_density": "Quantità di pioggia e neve", + "card_weather_density_hint": "Meno gocce e fiocchi di quanto indica il meteo; nuvole, nebbia e fulmini restano", + "rain_warning": "Avviso: finestra aperta mentre piove", + "sun_patches": "Sole e ombre", + "sun_patches_hint": "Con il nord impostato, la luce del sole di sun.sun entra dalle finestre come macchie chiare sul pavimento e la casa proietta la sua ombra sul terreno. Togli la spunta per lasciare pavimento e terreno senza macchie di sole e ombre.", + "sun_arc": "Arco solare e bussola", + "sun_arc_hint": "Disegna il percorso del sole di oggi come un arco sul terreno, con un anello e i punti cardinali a terra (nord in rosso). Richiede la posizione della casa in Home Assistant.", + "weather_effect_rain": "Pioggia", + "weather_effect_snow": "Neve", + "weather_effect_fog": "Nebbia (ingrigisce la scena)", + "weather_effect_clouds": "Le nuvole oscurano il cielo e il sole", + "weather_effect_lightning": "Fulmini nei temporali", + "weather_effect_sky": "Sole e luna nel cielo", + "weather_entity_hint": "Quale entità meteo guida il cielo intorno alla casa. Automatico usa la prima trovata.", + "weather_hint": "Meteo alla casa: pioggia e neve cadono con il vento reale, le nuvole passano sul terreno con le loro ombre, fulmini, nebbia, sole e luna", + "card_weather": "Meteo esterno", + "card_weather_hint": "Pioggia, neve, grandine, nuvole con ombre, fulmini e nebbia dalla prima entità meteo (weather_entity ne sceglie un'altra); meno particelle al livello tablet", + "alerts": "Avvisi", + "alert_smoke": "Fumo: {name}", + "alert_gas": "Gas: {name}", + "alert_co": "Monossido di carbonio: {name}", + "alert_water": "Acqua: {name}", + "alert_alarm": "Allarme scattato", + "alert_alarm_by": "Allarme attivato da {cause}", + "alert_alarm_pending": "Allarme in attesa", + "alert_window_rain": "Finestra aperta con la pioggia: {name}", + "alert_power_outage": "Blackout: {name}", + "alert_contact_lost": "Il contatto non risponde: {name}", + "rain_sensor": "Sensore di pioggia (stazione meteo propria)", + "outage_sensor": "Sensore di blackout", + "outage_hint": "Un sensore binario di classe power spento, un altro sensore binario acceso, uno stato come \"off_grid\" o \"backup\", o una tensione sotto i 50 V generano un avviso per tutta la casa.", + "contact_warning": "Avvisa quando un contatto di porta o finestra non è raggiungibile", + "contact_warning_hint": "Se un contatto è non disponibile da 10 minuti (batteria scarica, fuori portata radio), la finestra in 3D sembra chiusa anche se nessuno lo sa. Un avviso nomina allora il contatto. Un riavvio di Home Assistant non avvisa.", + "night_lock_warning": "Avvisa di notte se una porta non è chiusa a chiave", + "night_lock_warning_hint": "Tra le 22 e le 6 una nota indica le serrature della pianta non chiuse a chiave.", + "alert_unlocked_night": "Non chiusa a chiave: {name}", + "motion_markers_active": "Mostra i sensori di movimento solo mentre rilevano", + "motion_markers_active_hint": "Vale per i sensori di movimento, occupazione e presenza. Un sensore il cui simbolo è impostato per essere sempre mostrato resta visibile.", + "room_double_tap": "Doppio tocco su una stanza", + "room_double_tap_hint": "Un doppio tocco su una stanza spegne le sue luci se una è accesa, altrimenti le accende tutte. I dispositivi che chiedono prima restano sempre esclusi.", + "room_double_tap_area": "Lampade nella pianta e tutte le luci dell'area", + "room_double_tap_plan": "Solo le lampade nella pianta", + "room_double_tap_off": "Non commutare nulla", + "card_room_double_tap_auto": "Come impostato nella pianta", + "status_entities": "Sensori propri in alto nella vista 3D", + "status_add": "Aggiungi un sensore", + "status_entities_hint": "Per esempio la temperatura esterna, l'allarme o la qualità dell'aria: compaiono in alto a sinistra con nome e valore, anche in una stanza aperta. Un tocco apre i dettagli. Fino a 12.", + "announce_tts": "Sintesi vocale per gli annunci", + "announce_phrases": "Frasi per gli annunci (una per riga)", + "announce_phrases_hint": "Vuoto: le frasi incluse. Gli annunci esistono anche come azione «NextFloor: Annuncio» per le automazioni, sugli altoparlanti delle stanze e su ogni schermo NextFloor aperto.", + "opening_rain_warning": "Avvisa quando piove", + "opening_light_well": "Bocca di lupo davanti", + "sill_boards": "Davanzale e mensola", + "sill_boards_auto": "Automatico", + "sill_boards_none": "Nessuno", + "sill_boards_inside": "Solo interno", + "sill_boards_outside": "Solo esterno", + "room_names_short": "Nomi delle stanze", + "floor_stack_short_dim": "Attenuati", + "floor_stack_short_stacked": "Impilati", + "floor_stack_short_single": "Solo", + "size_short_w": "L", + "size_short_d": "P", + "size_short_h": "A", + "import_error_not_json": "Il file non è JSON.", + "import_error_not_plan": "Il file non è una planimetria NextFloor.", + "import_other_hint": "Da Sweet Home 3D: importa qui il file .sh3d. Vengono importati piani, stanze, porte, finestre e pareti libere, gli arredi no.", + "import_sh3d_found": "Sweet Home 3D: {floors} piani, {rooms} stanze, {openings} porte e finestre, {walls} pareti libere ({furniture} arredi non vengono importati).", + "import_dxf_found": "DXF: {rooms} stanze (polilinee chiuse) e {walls} pareti libere (linee) su un piano.", + "import_ifc_found": "Nel file IFC: {floors} piani e {rooms} stanze (NextFloor disegna le pareti dalle stanze).", + "import_roomplan_found": "Scansione della stanza (RoomPlan): {rooms} stanze, {openings} porte e finestre; {skipped} oggetti non importati (i mobili li posizioni tu).", + "import_error_roomplan_empty": "La scansione non contiene pareti.", + "import_error_ifc_empty": "Il file IFC non contiene spazi (IfcSpace) con una pianta.", + "import_error_dxf_empty": "Il file DXF non contiene linee né polilinee.", + "import_error_sh3d": "Questo non è un file Sweet Home 3D leggibile (serve Sweet Home 3D 5.3 o successivo).", + "import_error_sh3d_empty": "Il file Sweet Home 3D non ha stanze né pareti.", + "export_name_template": "modello", + "export_name_backup": "backup", + "card_floor_stack": "Piani sottostanti", + "floor_stack_dim": "Attenuati", + "floor_stack_stacked": "Impilati (la casa fino a qui)", + "floor_stack_single": "Nascosti (solo questo piano)", + "card_control_walls": "Pareti alte/sezione", + "card_control_floors": "Piani separati", + "card_control_temperature": "Temperatura", + "card_control_humidity": "Umidità", + "card_control_co2": "CO₂", + "card_controls_hint": "Pareti alte/sezione, piani separati e temperatura, umidità, CO₂ da commutare", + "controls_hide": "Nascondi i controlli: resta solo la vista 3D", + "nav_wrap": "Barra a capo: tutti i piani e le stanze su più righe", + "bars_fold": "Comprimi i comandi", + "bars_unfold": "Comandi", + "nav_row": "Barra su una riga (scorre di lato)", + "controls_show": "Mostra di nuovo i controlli", + "card_controls_hidden": "Inizia con i controlli nascosti", + "card_controls_hidden_hint": "Solo la vista 3D; un occhio in basso a sinistra riporta barre, valori e interruttori", + "card_controls_hide_after": "Nascondi i controlli dopo", + "card_hide_after_s": "{n} s senza tocchi", + "card_fullscreen_button": "Pulsante schermo intero", + "card_fullscreen_button_hint": "Nasconde la dashboard intorno alla card (ad es. su un tablet a parete)", + "fullscreen": "Schermo intero", + "fullscreen_exit": "Esci dallo schermo intero", + "card_section_show": "Mostra", + "card_floor": "Piano", + "card_floor_house": "Tutta la casa (tocca un piano per aprirlo)", + "card_height": "Altezza (pixel)", + "card_walls": "Pareti", + "card_quality_hint": "«Tablet» è l'impostazione più leggera, ideale per tablet Fire e altri tablet a parete.", + "card_flows_switch": "Interruttore nella card", + "card_flows_on": "Sempre attivo", + "card_flows_off": "Sempre disattivo", + "holos": "Card", + "holos_hint": "Mostra o nascondi le card live sopra la casa (bilancio energetico, auto, media)", + "card_energy": "Mostra i valori di energia in alto", + "card_room_panel": "Dettagli della stanza al tocco", + "card_room_buttons": "Pulsanti stanza", + "card_room_buttons_hint": "Una riga con un pulsante per stanza in cima alla card: toccane uno per aprire la stanza, come toccandola nel modello", + "card_room_panel_hint": "Luci e tapparelle della stanza in un pannello laterale", + "card_explode": "Separa i piani nella vista della casa", + "card_roof_fade": "Dissolvi il tetto durante lo zoom", + "card_roof_fade_hint": "Disattivo: il tetto resta sulla casa anche quando la telecamera si avvicina.", + "card_stats": "Indicatore di prestazioni (fotogrammi al secondo)", + "card_stats_hint": "Per verificare quanto fluida è la card sul dispositivo", + "packs": "Pacchetti di arredi", + "lib_badge_light": "Lampada: si collega a una luce e commuta in 3D", + "lib_badge_electric": "Elettrico: si collega a un'entità e a un sensore di potenza (commutazione, immagini, consumo)", + "lib_badge_hint": "Gli elementi con un simbolo si collegano a entità: le lampade commutano, gli schermi mostrano immagini, gli elettrodomestici mostrano il consumo.", + "care_bin_today": "Ritiro oggi", + "care_bin_tomorrow": "Ritiro domani", + "care_bin_days": "Tra {n} giorni", + "care_mail_yes": "C'è posta", + "care_mail_no": "Vuota", + "care_plant_thirsty": "Assetata", + "care_plant_ok": "Ben annaffiata", + "care_time_left": "Mancano {time}", + "care_entity_bin": "Data di ritiro (sensore)", + "care_entity_mail": "Sensore della posta", + "care_entity_plant": "Umidità del terreno (sensore)", + "care_thirsty_below": "Assetata sotto (%)", + "care_hint_bin": "Un sensore con il prossimo ritiro: giorni, una data, \"oggi\"/\"domani\" o l'integrazione Waste Collection Schedule. Il bidone si illumina il giorno prima e il giorno stesso.", + "care_hint_mail": "Un sensore che segnala posta nella cassetta (ad es. un contatto sullo sportello). La cassetta si illumina allora.", + "care_hint_plant": "Un sensore di umidità nel terreno. Sotto la soglia la pianta si illumina e dice di avere sete.", + "lib_cat_lights": "Luci", + "lib_cat_seating": "Sedute", + "lib_cat_tables": "Tavoli", + "lib_cat_storage": "Mobili e scaffali", + "lib_cat_beds": "Letti", + "lib_cat_kitchen": "Cucina", + "lib_cat_appliances": "Elettrodomestici", + "lib_cat_bath": "Bagno", + "lib_cat_media": "TV e audio", + "lib_cat_office": "Ufficio", + "lib_cat_tech": "Tecnologia", + "lib_cat_climate": "Riscaldamento e clima", + "lib_cat_energy": "Energia", + "lib_cat_garden": "Giardino e terrazza", + "lib_cat_plants": "Piante", + "lib_cat_kids": "Bambini", + "lib_cat_fitness": "Fitness", + "lib_cat_pets": "Animali", + "lib_cat_workshop": "Officina e garage", + "lib_cat_music": "Musica e atelier", + "lib_cat_season": "Stagioni e decorazioni", + "lib_cat_pictures": "Quadri e cornici", + "lib_cat_vehicles": "Veicoli", + "lib_cat_building": "Scale ed elementi edilizi", + "lib_cat_decor": "Decorazione e altro", + "lib_favourites": "Preferiti", + "lib_recent": "Usati di recente", + "lib_for_room": "Adatto a {room}", + "lib_all_rooms": "Mostra tutte le stanze", + "lib_linkable": "collegabile", + "lib_lit": "illuminato", + "lib_outdoor": "esterno", + "lib_fav_add": "Aggiungi ai preferiti", + "lib_fav_remove": "Rimuovi dai preferiti", + "lib_sizes": "Misure", + "feature_name_energy": "Flusso di energia", + "ext_tab": "Estensioni", + "ext_title": "Estensioni", + "models": "I tuoi modelli 3D", + "models_hint": "Per alcuni veicoli NextFloor può mostrare un vero modello 3D se ne possiedi uno. Scegli qui il file (.glb): NextFloor lo orienta correttamente, lo alleggerisce, marca la vernice e lo salva sul tuo Home Assistant. Senza modello il veicolo appare come prima.", + "models_licence": "I file sono tuoi e restano sul tuo Home Assistant. NextFloor non include modelli; assicurati che la licenza del tuo modello ti permetta di usarlo nella tua installazione.", + "model_add": "Aggiungi un modello …", + "model_replace": "Sostituisci il modello …", + "model_remove": "Rimuovi", + "model_present": "in uso", + "model_missing": "ancora nessuno", + "model_remove_confirm": "Eliminare il modello «{id}» da Home Assistant?", + "model_removed": "Modello «{id}» eliminato.", + "model_uploaded": "Modello «{id}» salvato ({size}). Ricarica il pannello per vederlo.", + "model_upload": "Salva su Home Assistant", + "model_info": "{triangles} triangoli, {size} m", + "model_front": "Fronte", + "model_front_hint": "Ruota il modello finché il fronte guarda verso chi osserva (in basso a sinistra nell'immagine).", + "model_paint": "Vernice (il colore che scegli nell'editor)", + "model_paint_preview": "Colore nell'anteprima", + "model_detail": "Livello di dettaglio", + "model_detail_light": "Leggero (tablet)", + "model_detail_normal": "Normale", + "model_detail_fine": "Fine", + "model_result": "Risultato: {triangles} triangoli, {size}", + "model_error_not_glb": "Questo non è un file .glb (glTF binario). Esporta il modello come «glTF binario».", + "model_error_compressed": "Il file è compresso (Draco, Meshopt o KTX). Esportalo senza compressione.", + "model_error_empty": "Il file non contiene nulla di tridimensionale.", + "model_error_unreadable": "Impossibile leggere il file: {detail}", + "model_error_too_large": "Il file supera {max}. Scegli un livello di dettaglio inferiore.", + "model_upload_forbidden": "Solo gli amministratori possono caricare modelli.", + "model_upload_too_large": "Home Assistant non accetta file oltre {max}. Scegli un livello di dettaglio inferiore.", + "model_upload_not_glb": "Home Assistant ha rifiutato il file (non è un glTF binario).", + "model_upload_bad_id": "L'id del modello non è valido.", + "model_upload_other": "Caricamento non riuscito: {detail}", + "ext_intro": "Importa i tuoi pacchetti di arredi, carica i tuoi modelli 3D e aggiungi plugin qui.", + "plugin": "plugin", + "plugins_title": "Plugin", + "plugins_intro": "I plugin aggiungono animazioni di luce, dispositivi e card nel pannello della stanza. Inserisci l'indirizzo di un plugin (un file .js in /config/www, cioè /local/…, da HACS /hacsfiles/…, o https://…).", + "plugins_docs": "Come scrivere un plugin", + "plugins_warning": "I plugin girano con gli stessi diritti di NextFloor nel tuo browser. Usa solo plugin da fonti affidabili.", + "plugins_off": "disattivato", + "plugins_error": "errore", + "plugins_loading": "caricamento …", + "plugins_nothing_registered": "caricato, ma non ha registrato nulla", + "plugins_loaded": "attivo", + "plugins_reload_hint": "Ha effetto dopo aver ricaricato la pagina", + "plugins_remove": "Rimuovi", + "plugins_none": "Ancora nessun plugin.", + "plugins_from_dashboard": "Registrato da una risorsa della dashboard", + "plugins_add": "Aggiungi", + "plugins_url_invalid": "Inserisci un indirizzo .js sotto /local/…, /hacsfiles/… o https://….", + "plugins_exists": "Questo plugin è già nell'elenco.", + "plugins_limit": "Al massimo 20 plugin.", + "packs_title": "Pacchetti di arredi", + "packs_intro": "Importa i tuoi arredi come pacchetto (JSON): come file o incollato qui sotto. {n} pacchetti sono inclusi in NextFloor e sono sempre disponibili.", + "packs_docs": "Formato del pacchetto", + "packs_none": "Ancora nessun pacchetto proprio.", + "community_title": "Mobili della community", + "community_intro": "Mobili costruiti e condivisi da altri con il costruttore di mobili, controllati e gratuiti. Costruisci i tuoi:", + "community_builder": "Apri il costruttore di mobili", + "community_how": "Come condividere i tuoi", + "community_load": "Carica i mobili della community", + "community_none": "Ancora nessun mobile della community: sii il primo!", + "community_install": "Installa", + "community_update": "Aggiorna", + "community_installed": "Installato", + "community_failed": "Impossibile caricare i mobili della community: {detail}", + "pack_import": "Importa file di pacchetto …", + "pack_paste": "Importa JSON", + "pack_paste_empty": "Incolla prima il JSON di un pacchetto.", + "pack_paste_not_json": "Questo non è JSON valido: {detail}", + "pack_imported": "Importato «{name}» di {publisher}: {n} elementi", + "packs_imported_n": "{n} di {total} pacchetti importati", + "pack_by": "di {publisher} · {n} elementi", + "pack_remove": "Rimuovi", + "pack_remove_confirm": "Rimuovere il pacchetto «{name}»? I suoi arredi restano nella planimetria come semplici scatole.", + "pack_error_not_a_pack": "Questo non è un pacchetto di arredi (manca \"format\": \"nfpack\").", + "pack_error_builtin": "Un pacchetto incluso in NextFloor ha già questo id.", + "pack_error_invalid_content": "Il pacchetto contiene arredi non validi: {detail}", + "pack_error_too_large": "Il pacchetto è troppo grande (al massimo 1 MB).", + "pack_error_needs_update": "Questo pacchetto richiede una versione più recente di NextFloor. Aggiorna prima (HACS › NextFloor › ⋮ › \"Informazioni sull'aggiornamento\" › \"Scarica\"), riavvia Home Assistant e importa di nuovo.", + "pack_error_other": "Importazione non riuscita: {detail}", + "store_open": "Apri lo store dei plugin", + "store_close": "Chiudi lo store dei plugin", + "store_intro": "Plugin verificati della community. Ognuno viene esaminato prima di essere aggiunto e poi non cambia più.", + "store_submit": "Invia il tuo plugin", + "store_empty": "Ancora nessun plugin nello store.", + "store_failed": "Impossibile caricare lo store ({error}).", + "store_install": "Installa", + "store_installed": "installato", + "store_update": "Aggiorna", + "store_confirm": "Installare «{name}» di {author}?\n\nUn plugin gira con gli stessi diritti di NextFloor nel tuo browser. Il file è stato verificato e il suo contenuto è fisso:\n{url}", + "manual": "Manuale", + "manual_more": "Scopri di più", + "feature_text_energy": "Particelle di energia volano ad arco dai campi solari all'inverter, tra casa, batteria, rete e utenze, più veloci e fitte quanta più potenza scorre. I moduli scintillano con la loro produzione, una card di vetro sopra il tetto mostra il bilancio e quanto è autosufficiente la casa in questo momento.", + "live_autarky": "autonomia", + "live_day_hint": "Le ultime 24 ore: solare (area) e consumo (linea)", + "live_week_hint": "Gli ultimi 7 giorni: sole {solar} kWh, consumo {use} kWh (giallo: sole, chiaro: consumo)", + "live_days": "giorni", + "live_car_away": "In viaggio", + "live_car_charging": "In carica", + "live_car_plugged": "Collegata", + "live_car_lock": "Blocca", + "live_car_unlock": "Sblocca", + "live_car_unlock_confirm": "Sbloccare davvero {name}?", + "live_car_climate": "Clima", + "live_car_charge": "Avvia/ferma la ricarica", + "live_media_prev": "Precedente", + "live_media_playpause": "Play/pausa", + "live_media_next": "Successivo", + "live_media_volume": "Volume", + "live_car_device": "Auto (qualsiasi entità dell'auto)", + "live_car_device_hint": "Carica, autonomia, ricarica, spina, chiusura e clima vengono trovati da NextFloor sul dispositivo dell'auto. Senza, usa il sensore di presenza del posto auto.", + "live_car_departure_entity": "Orario di partenza (facoltativo)", + "live_car_departure": "Partenza alle {time}", + "live_car_open": "Aperto: {parts}", + "printer_printing": "in stampa", + "printer_done": "finito", + "printer_paused": "in pausa", + "printer_error": "errore", + "printer_idle": "pronta", + "printer_done_at": "pronta alle {time}", + "printer_layer": "Strato", + "printer_nozzle": "Ugello", + "printer_bed": "Piatto", + "heatpump_heating": "riscalda", + "heatpump_water": "acqua calda", + "heatpump_cooling": "raffresca", + "heatpump_defrost": "sbrina", + "heatpump_idle": "a riposo", + "heatpump_flow_return": "Mandata → ritorno", + "heatpump_heat": "Calore", + "heatpump_power": "Elettricità", + "heatpump_outside": "fuori", + "pack_missing_item": "Arredo di un pacchetto rimosso", + "back_to_room": "Torna a {room}", + "back_to_floor": "Torna al piano", + "hint_furniture": "Tocca una stanza, poi scegli un elemento a destra · trascina gli elementi, ridimensionali dagli angoli", + "furniture_into": "I nuovi elementi vanno al centro di «{room}».", + "furniture_pick_room": "Suggerimento: tocca prima una stanza, i nuovi elementi finiranno al suo centro.", + "flows": "Flusso di energia", + "flows_hint": "Mostra o nascondi gli archi di energia tra campi solari, inverter, batteria, rete e utenze", + "chk_title": "Configurazione", + "chk_hint": "Ciò che serve al flusso di energia. Tocca una riga per andarci.", + "chk_solar": "Campo solare posizionato", + "chk_solar_add": "Metti un campo solare sul tetto", + "chk_meter": "Contatore con sensore di rete", + "chk_meter_sensor": "Contatore: manca il sensore di rete (W)", + "chk_meter_add": "Aggiungi il contatore", + "chk_inverter": "Inverter con sensore di potenza", + "chk_inverter_sensor": "Inverter: manca il sensore di potenza", + "chk_inverter_add": "Aggiungi un inverter", + "chk_battery": "Batteria domestica con potenza e carica", + "chk_battery_sensor": "Batteria domestica: manca potenza o carica", + "chk_battery_opt": "Batteria domestica (facoltativa)", + "chk_grid": "Allacciamento alla rete impostato", + "chk_grid_opt": "Allacciamento alla rete (facoltativo, altrimenti automatico)", + "energy_sign_grid": "La casa mostra immissione mentre il sole non produce nulla. Probabilmente il sensore di rete ha il segno invertito.", + "energy_sign_battery": "La batteria si carica senza sole e senza prelievo dalla rete. Probabilmente il suo sensore ha il segno invertito.", + "energy_sign_flip": "Inverti il segno", + "help_title": "Aiuto e feedback", + "help_hint": "Segnala i problemi come issue su GitHub e i desideri come discussion: non si perde nulla e tutti vedono lo stato.", + "help_issue": "Segnala un problema", + "help_idea": "Proponi un'idea", + "furn_name": "Nome (facoltativo)", + "furn_mirror": "Specchia", + "furn_mirror_hint": "Scambia sinistra e destra: il divano ad L al contrario, l'armadio con l'anta dall'altro lato, la cucina specchiata.", + "hint_opening": "Tocca una parete per aggiungere una porta o una finestra; scegline il tipo a destra dopo", + "preset_door": "Porta", + "preset_door_double": "Porta doppia", + "preset_window": "Finestra", + "preset_window_double": "Finestra doppia", + "preset_terrace": "Porta finestra", + "preset_terrace_double": "Portafinestra a due ante", + "preset_lift_slide": "Porta alzante scorrevole", + "preset_garage": "Porta del garage", + "preset_front": "Porta d'ingresso", + "opening_style": "Stile", + "sidelight_auto": "automatico", + "sidelight_hinge": "Fiancoluce sul lato cerniere", + "sidelight_hinge_hint": "Altrimenti il fiancoluce sta di fronte alle cerniere; selezionato, sta accanto alle cerniere.", + "sidelight_width": "Larghezza fiancoluce (m)", + "sidelight_width_left": "Fiancoluce sinistro (m)", + "sidelight_width_right": "Fiancoluce destro (m)", + "style_auto": "Automatico ({style})", + "style_interior": "Porta interna", + "style_front": "Porta d'ingresso", + "style_front_glass": "Porta d'ingresso con vetro", + "style_sidelight": "Porta d'ingresso con fiancoluce", + "style_sidelights": "Porta d'ingresso con due fiancoluce", + "style_glass": "Porta in vetro", + "style_sliding": "Porta scorrevole", + "style_passage": "Apertura (senza porta)", + "style_standard": "Standard", + "style_bars": "Con inglesine", + "style_glass_wall": "Parete in vetro (fissa)", + "preset_glass_wall": "Parete in vetro", + "flip_hinge": "Inverti lato cerniere", + "flip_main_leaf": "Inverti anta principale", + "flip_hinge_hint": "Cerniere dall'altro lato", + "flip_swing": "Inverti il verso di apertura", + "flip_swing_hint": "La porta si apre verso la stanza o dall'altro lato", + "main_leaf": "Anta principale (vista dalla stanza)", + "contact_main": "Contatto anta principale", + "contact_second": "Contatto seconda anta", + "tool_outdoor": "Esterno", + "tool_measure": "A misura", + "hint_measure": "Tocca il punto di partenza, poi scrivi a destra le lunghezze delle pareti con la loro direzione", + "measure": "Stanza a misura", + "measure_start": "Tocca il punto di partenza nella planimetria, ad es. un angolo della stanza.", + "measure_from": "Partenza a {x} / {z} m: toccare sposta la partenza.", + "measure_length": "Lunghezza della parete successiva (m)", + "measure_close": "Chiudi la stanza", + "measure_undo": "Rimuovi l'ultima parete", + "measure_gap": "Distanza dalla partenza: {gap} m (unita alla chiusura)", + "measure_hint": "Suggerimento: scrivi una lunghezza e premi una freccia. Con misure interne usa poi «Chiudi gli spazi».", + "rect_by_size": "Rettangolo a misura", + "rect_add": "Aggiungi rettangolo", + "dir_up": "Su", + "dir_down": "Giù", + "dir_left": "Sinistra", + "dir_right": "Destra", + "hint_outdoor": "Trascina per disegnare un'area esterna (prato, terrazza, piscina …)", + "outdoor": "Area esterna", + "outdoor_type": "Tipo", + "outdoor_height": "Altezza (m)", + "outdoor_offset": "Scostamento in altezza (m, − = più in basso)", + "outdoor_outline": "Mostra il contorno", + "outdoor_outline_hint": "Deselezionato, l'area non disegna una linea luminosa lungo il bordo, per grandi lotti fatti di più prati.", + "outdoor_corners_hint": "Angoli: un + su un bordo aggiunge un angolo, trascinando si modella l'area, × rimuove un angolo.", + "outdoor_hint": "Le luci esterne (paletto, faretto da giardino, applique esterna) illuminano tutte le aree esterne e la facciata.", + "out_lawn": "Prato", + "out_terrace": "Terrazza", + "out_path": "Vialetto", + "out_driveway": "Passo carraio", + "out_pool": "Piscina", + "out_bed": "Aiuola", + "out_hedge": "Siepe", + "out_fence": "Recinzione", + "out_wild": "Zona selvatica", + "out_pergola": "Pergola / telaio", + "outdoor_open": "Aperta (ometti l'ultimo bordo)", + "outdoor_open_hint": "Il bordo dall'ultimo punto al primo non viene disegnato: una recinzione o pergola appoggiata alla casa.", + "fence_gates": "Cancelli nella recinzione", + "gate_add": "+ Cancello nella recinzione", + "gate_edge": "Lato della recinzione", + "gate_kind": "Tipo", + "gate_single": "Cancelletto", + "gate_double": "Cancello doppio", + "gate_sliding": "Cancello scorrevole", + "gate_offset": "Centro dall’inizio (m)", + "gate_width": "Larghezza (m)", + "gate_entity": "Motore o interruttore", + "gate_contact": "Contatto (attivo = aperto)", + "fence_gates_hint": "Un cancello è un’apertura nella recinzione con montanti e anta. Con un motore (cover, interruttore, input_boolean, serratura) e/o un contatto si apre in 3D: cancelletti e cancelli doppi si aprono verso l’interno, uno scorrevole scorre lungo la recinzione.", + "outdoor_bracing": "Controventatura a X", + "outdoor_cut": "Ritaglia dalle aree circostanti", + "outdoor_cut_hint": "Ogni area che contiene interamente questa riceve qui un foro: una piscina nella terrazza, uno stagno o una zona selvatica nel prato. L'ordine di disegno non conta. Una piscina si ritaglia da sola.", + "outdoor_area_hint": "L'area di Home Assistant di questa superficie (giardino, terrazza, piscina): i suoi dispositivi e sensori compaiono in Esterno, e un segnaposto sulla superficie lo apre.", + "pool_temp": "Temperatura dell'acqua (facoltativo)", + "pool_pump": "Pompa / filtro (facoltativo)", + "pool_pump_on": "pompa accesa", + "outdoor_slope": "Pendenza (m)", + "outdoor_slope_hint": "Dislivello dal bordo alto al bordo basso; il bordo alto sta allo scostamento in altezza. Le lampade sull'area la seguono.", + "outdoor_slope_dir": "Scende verso", + "slope_x": "destra (+X)", + "slope_nx": "sinistra (−X)", + "slope_z": "giù (+Z)", + "slope_nz": "su (−Z)", + "north": "Nord (° in senso orario dall'alto)", + "north_hint": "Il nord serve per il sole (luce dalle finestre).", + "map_on": "Mostra una mappa reale sotto la planimetria", + "map_lat": "Latitudine", + "map_lon": "Longitudine", + "map_use_ha": "Usa la posizione di Home Assistant", + "map_opacity": "Visibilità (%)", + "map_zoom": "Livello di dettaglio", + "map_zoom_coarse": "grossolano", + "map_zoom_fine": "fine", + "map_move": "Sposta la mappa sotto la planimetria", + "map_step": "Passo", + "map_url": "Indirizzo tile proprio (vuoto = OpenStreetMap)", + "map_hint": "Il browser carica le tile della mappa direttamente dal server (OpenStreetMap di default, rispetta la loro policy d'uso); con la mappa spenta non si carica nulla. La planimetria sta sulla mappa come indica la bussola: ruota la bussola o sposta la mappa finché la casa combacia.", + "compass_title": "Bussola", + "compass_n_short": "N", + "compass_s_short": "S", + "compass_swap": "Scambia nord ↔ sud", + "compass_swap_hint": "Ruota la bussola di 180°. Il disegno, le falde e i campi solari restano come sono.", + "compass_hint": "Se la bussola non corrisponde alla realtà, ruotala qui: non serve ridisegnare nulla. Luce del sole, vento e orientamento delle falde la seguono.", + "roof": "Tetto", + "roof_none": "Nessun tetto", + "roof_flat": "Tetto piano", + "roof_gable": "Tetto a due falde", + "roof_custom": "Falde del tetto (personalizzate)", + "roof_sections": "Falde del tetto", + "roof_sections_hint": "Ogni falda copre un rettangolo della casa, ad es. la casa, il fienile o un ampliamento, ognuna con forma, direzione del colmo, altezza di gronda e pendenza proprie. Trascina nella planimetria per disegnarne una nuova; tocca per selezionarla, trascina per spostarla, gli angoli la ridimensionano.", + "roof_sections_start": "Crea le falde dalle stanze", + "roof_sections_regen": "Crea di nuovo dalle stanze", + "roof_sections_off": "Torna a un solo tetto", + "roof_regen_confirm": "Sostituire tutte le falde con una nuova proposta dalle stanze?", + "roof_section": "Falda del tetto", + "roof_section_hint": "Le altezze contano da terra. Un lato con gronda più bassa scende di più (catslide); i tetti a una falda salgono dal primo lato.", + "roof_shape_gable": "A due falde", + "roof_shape_hip": "A padiglione", + "roof_shape_pent": "A una falda", + "roof_shape_flat": "Piano", + "roof_shape_halfhip": "Mezzo padiglione", + "roof_shape_pyramid": "Piramidale", + "roof_shape_mansard": "Mansarda", + "roof_shape_parapet": "Con parapetto", + "roof_shape": "Forma", + "roof_end_start": "Estremità all'inizio del colmo", + "roof_end_end": "Estremità alla fine del colmo", + "roof_halfhip": "La falda a padiglione inizia al", + "roof_halfhip_hint": "A che altezza del timpano inizia la falda, come quota dell'altezza del timpano: basso = falda grande, alto = solo la punta.", + "roof_axis_x": "Colmo ↔", + "roof_axis_z": "Colmo ↕", + "roof_eave": "Gronda (m)", + "roof_pitch_short": "Pendenza (°)", + "roof_height": "Altezza (m)", + "roof_base": "Sommità dei muri (m)", + "roof_rotation": "Rotazione (°)", + "roof_on_floor": "Poggia sul piano", + "roof_on_floor_hint": "Appoggia la falda sulla sommità dei muri di questo piano; base e gronde si spostano con essa. Nella vista 3D il tetto appartiene a questo piano.", + "roof_base_hint": "Sotto l'altezza del soffitto del piano inferiore, le pareti di quel piano finiscono sotto il tetto: muretti alle gronde, timpani fino al colmo, pareti interne tagliate dalla pendenza. Le linee tratteggiate nella planimetria mostrano dove restano 1,5 m e 2 m di altezza libera.", + "roof_ridge_height": "Altezza del colmo", + "roof_side_top": "alto", + "roof_side_bottom": "basso", + "roof_side_left": "sinistra", + "roof_side_right": "destra", + "roof_swap": "Scambia i lati", + "roof_open": "Pensilina (pilastri invece di pareti, trasparente)", + "roof_open_short": "Pensilina", + "roof_dormer": "Abbaino", + "roof_dormer_hint": "Un abbaino su questo lato del tetto: largo 2 m, il fronte sul muro di gronda, gronde 1,4 m sopra la gronda del tetto, tetto a due falde. Poi spostalo e cambiane larghezza e altezze come qualsiasi falda; la falda principale si apre sotto e la parete del sottotetto sale fino all'abbaino: lì entra una finestra.", + "roof_outline": "Prendi il contorno del piano", + "roof_outline_hint": "Un tetto piano a forma libera: prende il contorno delle stanze del piano mostrato (anche a L o Z) come un'unica superficie senza giunti. Poi si possono trascinare gli angoli.", + "roof_points_hint": "Forma libera: trascina gli angoli nella planimetria, un + su un bordo aggiunge un angolo, × ne rimuove uno. Tornando al rettangolo la forma si perde.", + "roof_rect": "Torna al rettangolo", + "roof_open_hint": "Per una tettoia di terrazza o un carport: pilastri e travi reggono il tetto invece delle pareti, ed è trasparente. Dove la pensilina incontra il muro della casa, vi si appoggia.", + "roof_swap_hint": "Gira il tetto: i due lati si scambiano gronda e pendenza, un tetto a una falda sale dall'altra parte.", + "roof_pitch": "Pendenza del tetto (°)", + "roof_overhang": "Sporgenza del tetto (m)", + "roof_overhang_sides": "Sporgenza per lato", + "roof_overhang_a": "Sporgenza gronda A (m)", + "roof_overhang_b": "Sporgenza gronda B (m)", + "roof_overhang_u0": "Sporgenza timpano inizio (m)", + "roof_overhang_u1": "Sporgenza timpano fine (m)", + "roof_overhang_auto": "Torna automatico", + "roof_overhang_sides_hint": "Senza valori propri la sporgenza è automatica: uguale ovunque, tranne dove la parte di tetto tocca la casa (nessuna).", + "roof_ridge": "Colmo", + "roof_ridge_long": "Lungo il lato lungo", + "roof_ridge_short": "Lungo il lato corto (ad es. casa a schiera)", + "device": "Dispositivo", + "lamp_mount": "Lampada", + "lamp_ceiling": "Plafoniera", + "lamp_floor": "Lampada da terra", + "lamp_table": "Lampada da tavolo", + "lamp_wall": "Applique", + "marker_height": "Altezza del marcatore (m)", + "height_auto": "Altezza automatica", + "device_centre": "Al centro della stanza", + "lights_spread": "Distribuisci le plafoniere in modo uniforme", + "devices_search": "Cerca dispositivi …", + "devices_more": "+{n} altri", + "devices_less": "meno", + "panel_more": "Altri dispositivi dell'area ({n})", + "panel_less": "Mostra meno", + "gaps_close": "Chiudi gli spazi", + "gaps_hint": "Unisce stanze distanti fino a 60 cm in una parete condivisa; lo spazio diventa lo spessore della parete interna.", + "gaps_none": "Nessuno spazio tra le stanze trovato.", + "gaps_closed": "{n} punti chiusi.", + "gaps_closed_wall": "{n} punti chiusi, parete interna ora {t} m.", + "fps": "FPS", + "fps_title": "Indicatore di prestazioni (fotogrammi al secondo)", + "hint_garage": "Tocca una parete per aggiungere una porta del garage", + "opening_garage": "Porta del garage", + "garage_hint": "La porta segue una copertura del garage (posizione o aperta/chiusa) o un contatto della porta del garage dell'area della stanza.", + "door_hint": "Con un contatto porta l'anta si apre; senza sensore resta socchiusa.", + "hint_door": "Tocca una parete per aggiungere una porta", + "hint_window": "Tocca una parete per aggiungere una finestra", + "opening_door": "Porta", + "opening_window": "Finestra", + "opening_type": "Tipo", + "opening_position": "Centro dall'angolo (m)", + "sill": "Altezza davanzale (m)", + "opening_height": "Altezza (m)", + "hinge": "Cerniera (vista dalla stanza)", + "hinge_left": "Sinistra", + "hinge_right": "Destra", + "cover_entity": "Tapparella", + "door_cover": "Motore (porta o cancello motorizzato)", + "cover_position_entity": "Sensore di posizione (live)", + "cover_position_invert": "Il sensore conta al contrario (0 = aperto)", + "contact_entity": "Contatto", + "sensor_kind": "Tipo di sensore", + "sensor_kind_contact": "Contatto finestra (aperta/chiusa)", + "sensor_kind_handle": "Sensore maniglia (aperta/a ribalta/chiusa)", + "sensor_kind_contact_tilt": "Contatto + sensore ribalta", + "handle_entity": "Sensore maniglia", + "handle_main": "Sensore maniglia anta principale", + "leaf_main": "Anta principale", + "leaf_second": "Seconda anta", + "tilt_entity": "Sensore ribalta", + "tilt_angle_entity": "Sensore angolo di ribalta (°, facoltativo)", + "tilt_angle_max": "Angolo che conta come completamente a ribalta (°)", + "tilt_angle_offset": "Offset: angolo segnalato da chiusa (°)", + "tilt_angle_invert": "L'angolo conta al contrario", + "door_shut": "Mostra chiusa senza sensore", + "door_shut_hint": "Una porta senza contatto appare socchiusa in 3D perché si legga come porta. Selezionato, viene disegnata chiusa: porta d'ingresso, carport, porta laterale.", + "door_angle": "Angolo di apertura", + "door_angle_default": "Predefinito", + "door_angle_hint": "Quanto si apre l'anta. Con un sensore si apre così appena segnala «aperta»; senza sensore resta aperta a quell'angolo (invece che a metà). Predefinito resta come prima.", + "entity_auto": "Automatico ({name})", + "entity_auto_none": "Automatico (nessuno trovato)", + "entity_none": "Nessuno", + "entity_search": "Scrivi per cercare …", + "opening_hint": "Tipo di sensore: contatto finestra (segnala aperta/chiusa), sensore maniglia (segnala aperta, a ribalta e chiusa, ad es. una maniglia Homematic) o contatto + sensore ribalta (un secondo sensore che segnala solo la ribalta). Automatico usa tapparelle e contatti dell'area della stanza. Sensore di posizione: un'entità che segnala la posizione della tapparella mentre si muove (ad es. un \"level\" Homematic, 0–100 % o 0–1, aperta = alto); la tapparella si muove allora dal vivo in 3D.", + "furniture": "Arredi", + "furniture_add": "Aggiungi arredo", + "studio_new": "Crea un mobile tuo", + "studio_title": "Laboratorio mobili", + "studio_title_edit": "Laboratorio mobili: modifica", + "studio_hint": "Scegli un modello, imposta misure e frontali e metti il mobile nella pianta. Finisce nel pacchetto «Mobili miei» e qui si può modificare in seguito.", + "studio_kind": "Modello", + "studio_kind_cabinet": "Mobile", + "studio_kind_shelf": "Scaffale", + "studio_kind_lamp": "Lampada", + "studio_kind_device": "Apparecchio", + "studio_name": "Nome", + "studio_width": "Larghezza (cm)", + "studio_depth": "Profondità (cm)", + "studio_height": "Altezza (cm)", + "studio_doors": "Ante", + "studio_drawers": "Cassetti", + "studio_shelves": "Ripiani", + "studio_handle": "Maniglie", + "studio_handle_bar": "Barra", + "studio_handle_knob": "Pomello", + "studio_handle_none": "Senza", + "studio_base": "Base", + "studio_base_plinth": "Zoccolo", + "studio_base_legs": "Piedini", + "studio_base_none": "Nessuna", + "studio_back": "Schienale", + "studio_lamp": "Tipo", + "studio_lamp_floor": "Lampada da terra", + "studio_lamp_table": "Lampada da tavolo", + "studio_lamp_pendant": "Sospensione", + "studio_lamp_wall": "Applique", + "studio_display": "Display davanti (mostra il lettore)", + "studio_mount": "Posizione", + "studio_mount_floor": "A terra", + "studio_mount_surface": "Su un mobile", + "studio_mount_wall": "A parete", + "studio_color_body": "Corpo", + "studio_color_lamp_body": "Base e struttura", + "studio_color_front": "Frontali", + "studio_color_boards": "Ripiani", + "studio_color_shade": "Paralume", + "studio_color_display": "Cornice del display", + "studio_color_white": "Bianco", + "studio_color_wood": "Legno", + "studio_color_metal": "Metallo", + "studio_color_dark": "Scuro", + "studio_color_glass": "Vetro", + "studio_color_accent": "Accento", + "studio_color_own": "Colore proprio", + "studio_color_plan": "Colore della pianta", + "studio_place": "Metti nella pianta", + "studio_save": "Salva la modifica", + "studio_open": "Modifica nel laboratorio", + "studio_error": "Salvataggio non riuscito: {detail}", + "studio_pack_name": "Mobili miei", + "studio_pack_publisher": "Laboratorio mobili", + "furniture_search": "Cerca arredi …", + "furniture_search_none": "Nessun risultato. Prova un'altra parola, in inglese o tedesco.", + "furniture_type": "Elemento", + "rotation": "Rotazione (°)", + "tilt_x": "Inclinazione avanti/indietro (°)", + "tilt_z": "Inclinazione laterale (°)", + "strip_tilt": "Inclinazione lungo la sua lunghezza (°)", + "strip_upright": "In verticale", + "strip_rise": "Pendenza lungo la lunghezza (°)", + "strip_upright_hint": "La striscia sta in piedi: la sua lunghezza sale dall'altezza dal pavimento, lungo un telaio di porta, come colonna luminosa. L'inclinazione appoggia una striscia distesa contro una pendenza (90° = la faccia guarda di lato).", + "rotate_left": "↺ 90°", + "rotate_right": "↻ 90°", + "height_m": "Altezza (m)", + "furn_sofa": "Divano", + "furn_armchair": "Poltrona", + "furn_table": "Tavolo", + "furn_chair": "Sedia", + "furn_bed": "Letto", + "furn_nightstand": "Comodino", + "furn_wardrobe": "Armadio", + "furn_shelf": "Scaffale", + "furn_kitchen": "Mobile cucina", + "furn_worktop": "Piano di lavoro", + "furn_fridge": "Frigorifero", + "furn_fridge_smart": "Frigorifero smart (side by side)", + "furn_door_left": "Sensore porta sinistra (lato congelatore)", + "furn_door_right": "Sensore porta destra (lato frigorifero)", + "fridge_hint": "Mentre un sensore porta segnala aperta, l'anta si apre in 3D.", + "furn_stove": "Piano cottura", + "furn_sink": "Lavello", + "furn_bathtub": "Vasca", + "furn_shower": "Doccia", + "furn_wc": "WC", + "furn_washbasin": "Lavabo", + "furn_desk": "Scrivania", + "furn_tv_board": "Mobile TV", + "furn_plant": "Pianta", + "furn_rug": "Tappeto", + "furn_stairs": "Scala", + "furn_stairwell": "Apertura nel solaio", + "stairwell_hint": "Un foro in questo piano, ad esempio sopra la scala o per un soppalco; dall'alto si vede attraverso. L'apertura deve stare in una sola stanza; più aperture possono sovrapporsi (per una forma a L, ad esempio). Anche le scale del piano inferiore che arrivano fin qui aprono il solaio da sole.", + "tool_hole": "Apertura nel solaio", + "tool_roof": "Tetto", + "tool_energy": "Energia", + "tool_wall": "Parete", + "hint_wall": "Trascina per disegnare una parete singola (tramezzo, muretto) · Maiusc la tiene dritta · Alt senza aggancio", + "free_wall": "Parete", + "wall_length": "Lunghezza (m)", + "wall_thickness": "Spessore parete (m)", + "wall_height": "Altezza (m)", + "wall_height_full": "Altezza piena della stanza", + "wall_slope": "Inclinata", + "wall_slope_start": "Altezza all'inizio (m)", + "wall_slope_end": "Altezza alla fine (m)", + "wall_slope_hint": "Parete inclinata: la sommità va dritta dall'altezza all'inizio della parete (l'angolo con il numero più basso) all'altezza alla fine. Entrambe possono superare l'altezza del piano, ad esempio per una stanza a tetto spiovente con finestre alte.", + "wall_slope_off": "Torna a una parete dritta", + "wall_none": "Nessuna parete", + "wall_none_hint": "Ometti del tutto questa parete: per open space le cui stanze sono un unico spazio ma separate in Home Assistant.", + "edge_thickness": "Spessore (m)", + "wall_thickness_hint": "Spessore di questa parete, ad es. 0,365 su un muro esterno spesso o 0,115 su un tramezzo leggero. Una parete tra due stanze prende l'impostazione più spessa.", + "wall_thickness_reset": "Spessore come impostato per la casa", + "wall_heights": "Altezze delle pareti", + "wall_n": "Parete {a}–{b}", + "wall_view": "Vista parete", + "wall_view_hint": "La parete di fronte: trascina porte, finestre e arredi o scrivi la loro distanza.", + "wall_view_prev": "Parete precedente", + "wall_view_next": "Parete successiva", + "wall_view_left": "Da sinistra (m)", + "wall_view_height": "Dal pavimento (m)", + "wall_part": "parte {n}", + "wall_split_hint": "Dividi qui la parete: la parte ha un'altezza propria, ad es. 2,5 m accanto a 1,7 m in linea", + "wall_split_at": "Punto di divisione dall'angolo (m)", + "wall_join_hint": "Rimuovi il punto di divisione: la parte si riunisce a quella precedente", + "wall_exterior_short": "muro esterno", + "room_wall_hint": "Un'altezza minore trasforma la parete in un parapetto o un bancone. Se due stanze condividono la parete vale l'impostazione più bassa. Finestre e porte al suo interno finiscono all'altezza della parete.", + "free_wall_hint": "Una parete libera, ad es. un tramezzo. Dove incontra una parete di stanza l'angolo viene smussato. Trascina le maniglie per spostarne gli estremi, la linea per spostare tutta la parete.", + "free_wall_slope": "◢ Inclinata", + "free_wall_slope_hint": "Il muro sale o scende da un’estremità all’altra: l’altezza sopra è quella iniziale, questa quella finale.", + "free_wall_height_end": "Altezza alla fine (m)", + "stairwell_outside": "Questa apertura attraversa il confine di una stanza e per questo non viene ritagliata. Spostala del tutto in una stanza o rimpiccioliscila.", + "hint_hole": "Trascina per disegnare un'apertura nel solaio (vano scala, soppalco)", + "hint_roof": "Trascina per disegnare una falda · tocca seleziona · trascina sposta · gli angoli ridimensionano", + "hint_energy": "Tocca un campo solare per selezionarlo · trascina per spostarlo, anche su un'altra falda · nuovi campi con + Campo solare a destra", + "furn_parking": "Posto auto", + "furn_group_vehicles": "Parcheggio", + "parking_entity": "Sensore \"auto presente\"", + "parking_vehicle": "Veicolo", + "parking_vehicle_none": "Nessuno", + "parking_no_pack": "Nessun pacchetto veicoli importato: i veicoli vengono dal pacchetto \"Veicoli\" (Estensioni → Pacchetti di arredi).", + "parking_scale": "Dimensione (%)", + "parking_type_entity": "Sensore tipo di veicolo (facoltativo)", + "parking_types": "Stato → veicolo", + "parking_type_state": "Stato (ad es. van)", + "parking_add_type": "+ Associazione", + "parking_hint": "Senza sensore il veicolo sta sempre lì. Con un sensore appare appena questo segnala \"on\", \"home\" o \"present\". Un sensore del tipo di veicolo (ad es. da un'analisi IA della telecamera) sceglie il modello: quando il suo stato corrisponde a un'associazione, anche come parola nel testo, viene mostrato quel veicolo, altrimenti quello predefinito.", + "parking_too_tall": "Il veicolo ({car} m) è più alto della stanza ({room} m).", + "furn_lamp_ceiling": "Plafoniera", + "furn_lamp_downlight": "Faretto a incasso", + "furn_lamp_spot": "Faretto a vista", + "furn_lamp_panel": "Pannello LED", + "furn_lamp_uplight": "Faretto da pavimento", + "furn_lamp_bollard": "Paletto luminoso", + "furn_lamp_garden": "Faretto da giardino", + "furn_radiator": "Radiatore", + "furn_robot_vacuum": "Robot aspirapolvere", + "furn_entity_vacuum": "Robot aspirapolvere", + "furn_entity_mower": "Robot tagliaerba", + "pet_room_sensor": "Sensore di stanza dell'animale (facoltativo)", + "pet_room_hint": "Un sensore che indica la stanza in cui si trova l'animale – Bermuda o ESPresense con un tag al collare: in 3D gira in quella stanza.", + "furn_entity_water": "Valvola o interruttore", + "fridge_temp": "Temperatura del frigorifero", + "freezer_temp": "Temperatura del congelatore", + "fridge_temp_hint": "Il segnaposto mostra le temperature. Sopra 8 °C nel frigorifero o −12 °C nel congelatore si accende come avviso.", + "spray_reach": "Portata dell'acqua (m)", + "spray_hint": "Finché la valvola è aperta o l'interruttore acceso, l'irrigatore spruzza acqua ad archi intorno a sé.", + "furn_robot_room": "Stanza attuale (sensore)", + "robot_hint": "Mentre il robot pulisce in Home Assistant, percorre corsie in 3D nella stanza che segnala (un sensore «stanza attuale», confrontato con il nome della stanza o dell'area), altrimenti nella stanza della sua base. Il percorso è simulato: di solito Home Assistant non conosce la posizione esatta. Torna alla base quando rientra.", + "furn_lamp_pendant": "Lampada a sospensione", + "furn_ceiling_fan": "Ventilatore da soffitto", + "furn_fan_entity": "Ventilatore", + "fan_hint": "La luce è il kit luce del ventilatore (lasciala vuota se non ce l'ha). Il ventilatore si trova nella stanza o si sceglie qui: in 3D le pale girano alla sua velocità, l'icona lo commuta, scorrere su/giù cambia la velocità, una pressione lunga apre il menu rapido. L'altezza è quanto pende dal soffitto (di più = un'asta più lunga).", + "room_ceiling": "Altezza soffitto", + "room_ceiling_tip": "Più basso del piano (un bagno sotto le scale) o più alto (un soggiorno aperto fino al tetto): plafoniere, ventilatori, strisce LED e dispositivi a soffitto pendono da qui, e le pareti della stanza sono così alte.", + "room_ceiling_through": "Il soffitto ({ceiling} m) è sopra l'altezza del piano ({floor} m): la stanza arriva nel piano superiore, le sue pareti salgono con lei e il piano superiore resta aperto sopra di essa. L'editor del piano superiore mostra l'area tratteggiata.", + "room_floor_offset": "Livello del pavimento (m)", + "room_floor_offset_hint": "Se il pavimento di questa stanza è più basso o più alto del piano (un ingresso ribassato: −0,39), pavimento, pareti, porte, finestre e ciò che c'è dentro si spostano; il soffitto resta. Aggiungi i gradini come scala.", + "room_inner": "Interno {w} × {d}", + "room_inner_hint": "Misurato da parete a parete: le pareti interne tolgono metà del loro spessore, quelle esterne stanno fuori dal contorno.", + "floor_heating": "Riscaldamento a pavimento (facoltativo)", + "floor_heating_hint": "Finché il termostato riscalda (o la valvola è aperta, l'interruttore acceso), il pavimento della stanza si illumina caldo in 3D.", + "room_announce_speaker": "Altoparlante per gli annunci", + "room_announce_quiet": "Ora di silenzio per gli annunci", + "room_announce_hint": "Senza scelta parla l'altoparlante posizionato nella stanza, altrimenti un assistente vocale, un Echo o un altoparlante della sua area (mai un televisore). Nell'ora di silenzio gli annunci a più stanze la saltano; uno solo per lei arriva comunque.", + "ceiling_here": "Soffitto qui", + "ceiling_here_hint": "Altezza del soffitto proprio in questo punto, ad es. in un soffitto inclinato. Vuoto = il soffitto della stanza.", + "ceiling_slope": "Sotto la falda", + "ceiling_slope_hint": "Qui il soffitto è sotto la falda: la lampada pende dalla sua parte inferiore, proprio sopra il suo posto.", + "furn_lamp_floor": "Lampada da terra", + "furn_lamp_table": "Lampada da tavolo", + "furn_lamp_wall": "Applique", + "furn_led_strip": "Striscia LED", + "furn_group_lights": "Luci", + "furn_entity_light": "Luce o interruttore", + "furn_color_entity": "Colore e luminosità da (facoltativo)", + "furn_color_entity_hint": "Per luci che un relè (Shelly, attuatore) accende e spegne mentre la lampadina conosce colore e luminosità: acceso/spento viene dall'interruttore sopra, colore e luminosità da questa entità.", + "lamp_extra_light": "Lampadina {n} (facoltativa)", + "lamp_extra_hint": "Una lampada con più luci – principale, luce notturna, anello d'atmosfera: a principale spenta brilla in 3D con la successiva accesa, un po' più tenue. Accendile una a una nel pannello della stanza.", + "furn_entity_climate": "Riscaldamento (termostato)", + "lamp_hint": "Tocca la lampada in 3D per commutarla, pressione lunga per il menu rapido. Funzionano anche gli interruttori (ad es. un relè per la plafoniera): la lampada brilla mentre è acceso. Le lampade da tavolo poggiano sull'arredo sottostante.", + "lamp_hint_pendant": "Altezza = calata sotto il soffitto. Tocca in 3D per commutare, pressione lunga per i dettagli.", + "theme": "Aspetto", + "version_hint": "Versione installata di NextFloor (il frontend); l'integrazione in Home Assistant segnala {backend}", + "accent": "Colore d'accento", + "accent_hint": "Un colore d'accento tuo: linee e bordi luminosi nell'aspetto neon, pulsanti e marcatori; ↺ riporta il ciano neon", + "accent_reset": "Torna al ciano", + "theme_neon": "Neon", + "theme_blueprint": "Progetto", + "theme_day": "Giorno", + "theme_auto": "Auto", + "clock": "Orologio", + "clock_none": "Nessuno", + "clock_top_left": "In alto a sinistra", + "clock_top_right": "In alto a destra", + "clock_bottom_left": "In basso a sinistra", + "clock_bottom_right": "In basso a destra", + "glass_walls": "Pareti di vetro", + "glass_walls_hint": "Quanto sono coprenti le pareti attraverso cui si guardano le stanze: a sinistra quasi invisibili, a destra opache. Per questo schermo.", + "screen_name": "Nome di questo schermo", + "screen_name_hint": "Gli annunci compaiono su ogni schermo NextFloor aperto. Con un nome (es. «Corridoio») un annuncio può andare solo a questo schermo. Senza spunta, questo schermo resta muto.", + "announce_on": "Annunci attivi su questo schermo", + "announce_muted": "Annunci silenziati su questo schermo", + "lock3d_on": "Blocca il 3D (niente rotazione, zoom o spostamento; i tocchi funzionano)", + "lock3d_off": "Sblocca il 3D", + "walk": "Cammina per la casa", + "travel": "Viaggio nel tempo: rivedi le ultime 24 ore o 7 giorni", + "travel_play": "Riproduci", + "travel_pause": "Pausa", + "travel_loading": "Caricamento della cronologia …", + "travel_failed": "Impossibile caricare la cronologia.", + "travel_speed": "Velocità", + "travel_speed_min": "1 min/s", + "travel_speed_10min": "10 min/s", + "travel_speed_hour": "1 h/s", + "travel_days": "giorni", + "travel_live": "Live", + "card_travel_button": "Pulsante per il viaggio nel tempo", + "walk_stop": "Smetti di camminare", + "walk_hint": "Trascina: guardati intorno · W A S D / frecce o stick: cammina · rotella: passo", + "card_walk_button": "Pulsante per camminare", + "card_lock_button": "Pulsante per il blocco 3D", + "backdrop": "Sfondo proprio", + "backdrop_color": "Colore", + "backdrop_image": "Immagine (/local/… o https://…)", + "backdrop_dim": "Attenua", + "backdrop_hint": "Invece del cielo dell'aspetto, la casa sta davanti a un colore o a un'immagine tua. Un'immagine in /config/www è raggiungibile su /local/….", + "furnish": "Arreda", + "split_3d": "3D a fianco", + "plan_dims": "Misure", + "plan_dims_hint": "Scrive la lunghezza su ogni lato della stanza.", + "mount_height": "Altezza dal pavimento (m)", + "side_open": "Apri la barra laterale", + "side_close": "Chiudi", + "side_details": "Dettagli della selezione", + "side_pin": "Fissa", + "side_pinned": "Fissata", + "side_pin_hint": "Fissata, la barra laterale resta aperta; altrimenti si ripiega accanto alla vista 3D quando non c'è selezione", + "split_3d_hint": "3D live accanto alla planimetria: trascina e ruota lì arredi e dispositivi, con annulla, salvato con la planimetria", + "size_w": "Larghezza (m)", + "size_d": "Profondità (m)", + "size_h": "Altezza (m)", + "furnish_hint": "Trascina arredi, lampade e dispositivi · gli arredi si agganciano alle pareti · tocca un elemento per ruotarlo, impostarne altezza e montaggio", + "done": "Fatto", + "heatmap": "Mappa di calore", + "heat_off": "Normale", + "heat_short_temperature": "Temp.", + "heat_short_humidity": "Umidità", + "heat_short_co2": "CO₂", + "heat_short_mould": "Muffa", + "heat_short_power": "Consumi", + "heat_short_comfort": "Comfort", + "heat_short_sun": "Sole", + "heat_short_wifi": "Wi-Fi", + "heat_short_values": "Valori", + "heat_temperature": "Temperatura", + "heat_humidity": "Umidità", + "heat_co2": "CO₂", + "heat_mould": "Muffa", + "heat_power": "Consumo elettrico", + "heat_comfort": "Indice di comfort", + "heat_sun": "Sole oggi", + "room_sun_hours": "{h} h di sole oggi ({facing})", + "open_since": "aperto da {time}", + "presence_now": "c'è qualcuno", + "presence_last": "visto {time} fa", + "comfort_n": "Comfort {n}", + "empty_lights_hint": "{n} luci accese, nessuno da {min} min.", + "empty_lights_off": "Spegni luci", + "open_heating_hint": "{n} finestre aperte mentre il riscaldamento è acceso.", + "open_heating_off": "Spegni riscaldamento", + "room_clean": "Pulizia (script o pulsante)", + "room_clean_hint": "Uno script o pulsante che manda il robot aspirapolvere in questa stanza (es. la pulizia per stanza della tua integrazione). Il pannello della stanza mostra allora «🧹 Pulisci».", + "room_clean_run": "Pulisci", + "room_clean_run_hint": "Manda il robot aspirapolvere in questa stanza.", + "shade_hint": "Sole su {n} finestre a {temp} – abbassare le tapparelle?", + "shade_close": "Abbassa", + "room_sun_year": "Sole nell'anno", + "room_sun_year_hint": "Le ore di sole dalle finestre esterne della stanza il 15 di ogni mese.", + "room_energy": "oggi {today} · mese {month}", + "room_energy_hint": "Dalle statistiche dei sensori di potenza dei dispositivi della stanza; il costo del mese con la tariffa della casa.", + "heat_summer": "estate", + "heat_winter": "inverno", + "air_co2": "arieggiare (CO₂)", + "air_humidity": "arieggiare (umido)", + "air_mould": "rischio muffa – arieggiare", + "room_curve_hint": "La temperatura della stanza nelle ultime 24 ore", + "heat_values": "Valori accanto ai nomi delle stanze", + "heat_wifi": "Wi-Fi", + "wifi_aps": "{n} access point · {clients} dispositivi", + "wifi_network": "Rete: {online} online · {offline} offline", + "wifi_none": "Posiziona access point o router dai pacchetti (Casa smart 2) e collegali a un'entità del loro dispositivo.", + "wifi_clients": "{n} dispositivi", + "heat_none_found": "Nessun sensore adatto nelle aree delle stanze.", + "markers": "Marcatori", + "markers_none": "Nessuno", + "markers_important": "Importanti", + "markers_all": "Tutti", + "furn_stool": "Sgabello", + "furn_coffee_table": "Tavolino", + "furn_tv_wall": "TV (a parete)", + "furn_sideboard": "Credenza", + "furn_table_round": "Tavolo rotondo", + "furn_bench": "Panca", + "furn_corner_bench": "Panca angolare", + "furn_bar_stool": "Sgabello da bar", + "furn_kitchen_wall": "Pensile", + "furn_kitchen_tall": "Colonna con forno", + "furn_island": "Isola della cucina", + "furn_dishwasher": "Lavastoviglie", + "furn_bunk_bed": "Letto a castello", + "furn_dresser": "Cassettiera", + "furn_washer": "Lavatrice", + "furn_dryer": "Asciugatrice", + "furn_office_chair": "Sedia da ufficio", + "furn_tall_cabinet": "Armadio alto", + "furn_coat_rack": "Appendiabiti", + "furn_group_living": "Soggiorno", + "furn_group_dining": "Pranzo", + "furn_group_energy": "Energia e solare", + "energy_devices": "Dispositivi", + "wallbox_charging": "in carica", + "wallbox_plugged": "collegata", + "furn_soc": "Stato di carica (%)", + "furn_export": "Potenza immessa (W, sensore separato, facoltativo)", + "furn_export_hint": "Se il contatore segnala prelievo e immissione in due sensori (ad es. Growatt, Tibber Pulse), usa il sensore di prelievo come potenza sopra e quello di immissione qui. Un sensore con segno non ne ha bisogno.", + "meter_parent": "Dipende dal contatore", + "meter_parent_none": "nessuno (contatore principale)", + "meter_main": "Contatore principale", + "meter_unmetered": "{w} non misurati", + "meter_device_hint": "Se il dispositivo sta dietro un sottocontatore (ad es. un impianto da balcone in un appartamento), la sua potenza conta per quell'appartamento. Il sottocontatore deve misurare in entrambe le direzioni (− = immissione); se conta solo il prelievo, il consumo dell'appartamento risulta troppo alto durante un'eccedenza.", + "meter_sub_power": "Potenza della linea (W, + = prelevata, − = immessa)", + "meter_floors": "Alimenta i piani", + "meter_sub_hint": "Un sottocontatore misura la sua linea, ad es. un appartamento. I dispositivi dei piani selezionati dipendono da esso in 3D invece che dal contatore principale; ciò che il principale conta in più appare come «Comune (resto)» nel bilancio.", + "furn_charge": "Potenza di carica (W, sensore separato, facoltativo)", + "furn_charge_hint": "Se la batteria segnala carica e scarica in due sensori (ad es. Anker Solix), usa il sensore di scarica come potenza sopra e quello di carica qui. Un sensore con segno non ne ha bisogno.", + "furn_wallbox_status": "Stato (in carica, collegata)", + "energy_only_note": "⚡ Energia: qui si possono spostare solo campi solari e dispositivi energetici; stanze e arredi sono bloccati.", + "roof_only_note": "🏠 Tetto: qui si possono spostare solo falde e finestre da tetto; stanze e arredi sono bloccati.", + "energy_devices_hint": "Contatore, inverter, batterie domestiche, wallbox e allacciamento alla rete si aggiungono qui: sul piano scelto sopra, spostabili nella planimetria. Con un sensore di potenza mostrano i watt; il contatore prende il sensore di rete, una stringa sceglie il suo inverter. Funzionano anche più inverter e batterie (ad es. un impianto da balcone in più): ognuno con il proprio sensore.", + "energy_routes": "Percorsi dei cavi", + "energy_routes_hint": "Dove passa davvero un cavo: il flusso segue i tuoi punti invece di un arco attraverso la casa. Senza percorso resta l'arco. Le utenze mantengono il loro arco.", + "route_conn_solar": "{name} → inverter", + "route_conn_battery": "Batteria ↔ casa", + "route_conn_inverter": "Inverter → casa", + "route_conn_grid": "Rete ↔ casa", + "route_conn_meter": "{name} ↔ contatore superiore", + "route_conn_device": "{name} ↔ sottocontatore", + "route_points": "{n} punti", + "route_none": "arco diretto", + "route_draw": "Disegna percorso", + "route_redraw": "Ridisegna", + "route_drawing": "Tocca nella pianta i punti da cui passa il cavo, da un capo all'altro; cambia piano dove attraversa un soffitto. {n} punti.", + "route_undo": "Ultimo punto", + "route_done": "Fatto", + "route_cable": "Mostra come cavo", + "route_cable_hint": "Disegna il percorso come un cavo visibile, non solo come la linea sottile sotto le particelle.", + "solar_fields": "Campi solari", + "solar_hint": "Metti moduli sul tetto: seguono la pendenza della falda; su un tetto piano stanno su supporti. Trascina un campo nella planimetria per spostarlo.", + "solar_no_roof": "I campi solari richiedono un tetto: a due falde o piano in Impostazioni, oppure falde qui nello strumento Tetto.", + "solar_face_gone": "manca la falda", + "solar_summary": "{n} moduli · {kwp} kWp", + "solar_add": "Campo solare", + "solar_field": "Campo solare", + "solar_face": "Falda", + "solar_rows": "File", + "solar_cols": "Moduli per fila", + "solar_portrait": "Verticale", + "solar_landscape": "Orizzontale", + "solar_u": "Distanza dal bordo (m)", + "solar_v": "Distanza dalla gronda (m)", + "solar_tilt": "Inclinazione dei supporti (°)", + "solar_rack_ew": "Struttura est-ovest", + "solar_rack_ew_hint": "Una fila su due guarda dall'altra parte, le coppie schiena contro schiena – basse e fitte, come su molti tetti piani.", + "solar_rack_tilt": "Supporto (° di inclinazione in più)", + "solar_flip": "Inclina dall'altra parte", + "solar_partial": "solo {n} su {total} entrano nella falda", + "solar_form_hint": "I moduli che sporgerebbero dalla falda vengono omessi. «Riempi falda» mette tutti i moduli che entrano. kWp calcolati con 400 W per modulo.", + "solar_fit": "Riempi falda", + "roof_windows": "Finestre da tetto", + "roof_window": "Finestra da tetto", + "roof_windows_hint": "Le finestre da tetto stanno nella falda, con tapparella e contatti come le finestre. Trascinale nella planimetria, anche su un'altra falda.", + "roof_window_tilt": "Contatto ribalta", + "roof_window_name": "Nome (facoltativo)", + "roof_window_motor": "Motore finestra (copertura, facoltativo)", + "roof_window_motor_hint": "Un motore per finestre (Velux, Roto, Fakro) segnala la posizione come copertura: l'anta si apre in 3D quanto il motore. Un contatto o un contatto ribalta funziona anche senza motore.", + "roof_window_hint": "Aperta, l'anta si apre verso l'esterno incernierata in alto; a ribalta, poco; il telaio si illumina caldo; la tapparella scende sul vetro dall'alto. In una falda la finestra apre un foro nella pendenza, così il sottotetto vi guarda attraverso.", + "solar_ground": "Libero (giardino, tetto del garage …)", + "solar_add_ground": "Libero", + "solar_base": "Altezza della superficie (m, 0 = suolo)", + "solar_add_wall": "Su una parete", + "solar_wall": "Parete", + "solar_v_wall": "Altezza dal pavimento (m)", + "solar_tilt_wall": "Inclinazione dalla parete (°, 90 = pensilina)", + "solar_flip_wall": "Distanziato in basso invece che in alto", + "solar_rotation": "Rotazione (°)", + "solar_name": "Nome", + "solar_name_hint": "ad es. stringa 1 sud", + "solar_module_w": "Larghezza modulo (m)", + "solar_module_h": "Altezza modulo (m)", + "solar_wp": "Potenza modulo (Wp)", + "solar_string": "Stringa", + "solar_strings": "Stringhe", + "solar_string_none": "Nessuna stringa", + "solar_string_new": "Nuova stringa", + "solar_string_n": "Stringa {n}", + "solar_string_name": "Nome della stringa", + "solar_string_entity": "Potenza FV della stringa", + "solar_string_inverter": "Inverter", + "solar_string_inverter_none": "Nessun inverter scelto", + "inverter_strings": "Stringhe su questo inverter: {names}", + "inverter_strings_none": "Ancora nessuna stringa su questo inverter: assegnala in un campo solare in Stringa › Inverter.", + "solar_string_inverter_missing": "Ancora nessun inverter nella planimetria (aggiungine uno sotto in Dispositivi)", + "solar_string_hint": "I campi della stessa stringa vanno insieme, anche su tetti diversi (ad es. 5 moduli sulla casa e 5 sul garage). Sensore e inverter valgono per tutta la stringa.", + "solar_string_sum": "{fields} campi · {n} moduli · {kwp} kWp", + "solar_face_size": "Falda {w} × {h} m (lungo la gronda × su per la pendenza)", + "solar_cols_hint": "Un numero per file di uguale lunghezza, o una lista per file diverse: «4, 4, 3» (dalla gronda).", + "solar_align_left": "Sinistra", + "solar_align_center": "Centro", + "solar_align_right": "Destra", + "solar_look_black": "Full black", + "solar_look_blue": "Blu", + "solar_pick": "Moduli on/off uno per uno", + "solar_pick_all": "Di nuovo tutti attivi", + "solar_pick_hint": "Tocca un modulo nella planimetria per toglierlo o rimetterlo. Quelli tolti sono tratteggiati.", + "solar_entity": "Potenza FV di questo campo (ad es. la sua stringa)", + "solar_main": "Tetto principale", + "solar_section": "Falda {n}", + "solar_flat": "tetto piano", + "compass_n": "nord", + "compass_ne": "nord-est", + "compass_e": "est", + "compass_se": "sud-est", + "compass_s": "sud", + "compass_sw": "sud-ovest", + "compass_w": "ovest", + "compass_nw": "nord-ovest", + "furn_meter": "Contatore elettrico", + "furn_grid_point": "Allacciamento alla rete", + "grid_point_hint": "L'allacciamento alla rete sta qui: il punto di consegna al gestore, ad es. in fondo al vialetto. Spostabile nella planimetria.", + "furn_model": "Modello", + "inverter_std": "Standard (unità a parete con display)", + "inverter_slim": "Sottile e alto (striscia luminosa)", + "inverter_hybrid": "Ibrido (quadrante rotondo, ventole)", + "battery_std": "Torre (moduli impilati)", + "battery_wall": "Batteria a parete (piatta, appesa)", + "battery_cube": "Compatta (batteria da balcone)", + "furn_inverter": "Inverter solare", + "furn_home_battery": "Batteria domestica", + "furn_wallbox": "Wallbox", + "furn_group_kitchen": "Cucina", + "furn_group_sleeping": "Notte", + "furn_group_bath": "Bagno e lavanderia", + "furn_group_work": "Lavoro e altro", + "furn_entity": "Dispositivo (interruttore, presa …)", + "furn_state_entity": "Stato da (facoltativo)", + "furn_state_entity2": "Secondo stato (l'altra metà)", + "furn_state_split": "Metà", + "furn_state_left_right": "Sinistra / destra", + "furn_state_top_bottom": "Sotto / sopra (letto a castello)", + "furn_state_hint": "L'elemento si illumina mentre l'entità segnala acceso, occupato o a casa: un letto con tappetino di presenza, una poltrona, la sauna. Due entità illuminano le metà: sinistra e destra, sotto e sopra per un letto a castello.", + "furn_entity_tv": "TV (media player o presa smart)", + "fix": "Fissa", + "unfix": "Sblocca", + "fix_hint": "Fissato: non si può più spostare per sbaglio (tasto L, clic destro o pressione lunga)", + "fixed_drag_hint": "🔒 Fissato: sbloccalo prima per spostarlo (lucchetto nel modulo, clic destro o tasto L)", + "fixed_delete_confirm": "Questo elemento è fissato. Eliminarlo comunque?", + "lock_plan": "🔒 Planimetria", + "lock_plan_hint": "Blocca la planimetria: stanze, pareti, porte, finestre e aree esterne non si possono spostare per sbaglio. Arredi e dispositivi restano liberi.", + "start_view": "Vista iniziale", + "start_view_hint": "La vista 3D, la card e il kiosk aprono la casa con questa vista, ad es. dal lato giardino. Ruota, ingrandisci e sposta la casa nel riquadro 3D a destra finché va bene, poi memorizzala.", + "start_view_card": "Se una card deve aprirsi con un'altra vista, inserisci questa riga nella sua configurazione YAML.", + "start_view_set": "Memorizza la vista 3D attuale come iniziale", + "start_view_reset": "Predefinita", + "start_view_saved": "È salvata una vista iniziale propria.", + "ctx_rotate": "Ruota di 90°", + "devices_placed_in": "in {room}", + "devices_narrow": "altri {n}: restringi la ricerca", + "climate": "Clima della stanza", + "climate_temperature": "Temperatura", + "climate_humidity": "Umidità", + "climate_co2": "CO₂", + "climate_hint": "Questi sensori valgono per la mappa di calore e il pannello della stanza. «Automatico» prende i sensori dell'area e quelli posizionati nella stanza, ma non le temperature dei dispositivi (stampante 3D, pompa di calore, mandata …).", + "climate_more": "… e un altro sensore (media)", + "plan_locked": "Planimetria bloccata", + "plan_lock": "Blocca la planimetria", + "plan_unlock": "Sblocca la planimetria", + "opening_mark": "Evidenzia in 3D", + "opening_mark_open": "Quando è aperta", + "opening_mark_closed": "Quando è chiusa (ad es. WC)", + "opening_mark_hint": "Una finestra o porta evidenziata si illumina calda. «Quando è chiusa» richiede un contatto; senza sensore non si evidenzia nulla.", + "window_opens": "Si apre", + "window_opens_turn": "Anta-ribalta (verso l'interno)", + "window_opens_slide": "Scorrevole (finestra scorrevole, porta alzante)", + "window_opens_top": "A sporgere (la parte bassa si apre verso l'esterno)", + "window_opens_hint": "Scorrevole: l'anta dal lato della cerniera scorre davanti a quella fissa; con due ante, le due centrali scorrono verso l'esterno. Le finestre a sporgere si aprono con il contatto o un sensore di ribalta.", + "marker_show": "Marcatore in 3D", + "marker_show_hint": "Automatico segue l'interruttore Nessuno / Importanti / Tutti della vista 3D. Mostra sempre e Nascondi valgono comunque (tranne con Nessuno).", + "pin_shift": "Sposta il segnaposto", + "pin_shift_up": "↑ altezza", + "pin_shift_hint": "Se i dispositivi sono vicini, sposta qui il segnaposto un po' di lato o in alto (in metri); il dispositivo resta dov'è.", + "marker_show_auto": "Automatico", + "marker_show_always": "Mostra sempre", + "marker_show_no_power": "Senza watt", + "marker_show_active": "Solo quando attivo", + "marker_show_never": "Nascondi", + "marker_icon": "Simbolo proprio (icona Material Design)", + "device_name": "Nome proprio (facoltativo)", + "show_name": "Mostra il nome sotto il marcatore in 3D", + "card_marker_names": "Nomi propri ai marcatori", + "card_marker_names_hint": "Ogni dispositivo con un nome proprio lo mostra in piccolo sotto il marcatore: tre termometri in giardino restano distinguibili.", + "device_name_hint": "Un nome solo per la planimetria e il pannello della stanza, ad es. \"Luce d'accento isola\": l'entità in Home Assistant resta com'è.", + "device_simple": "Solo interruttore nel pannello della stanza", + "device_simple_hint": "Il pannello della stanza mostra per questa lampada solo l'interruttore, senza luminosità, temperatura colore e colori.", + "floor_turn": "Ruota di 90°", + "floor_shift_all": "Porta con sé tutti i piani (tutta la casa)", + "floor_shift_all_hint": "Sposta e ruota agiscono su tutti i piani con falde, aree esterne, dispositivi energetici e contatore: tutta la casa si muove insieme.", + "floor_turn_hint": "Ruota tutto il piano di 90° in senso orario attorno al centro delle sue stanze, quando un piano è stato disegnato al contrario. Tre volte = 270°.", + "marker_icon_hint": "Il nome di un'icona Material Design come in Home Assistant, ad es. mdi:thermometer o mdi:water-alert. Vuoto = il simbolo del tipo di dispositivo.", + "furn_power": "Sensore di potenza (W)", + "furn_links_hint": "Con un sensore di potenza l'elemento mostra i watt e partecipa al flusso di energia.", + "furn_links_hint_tv": "Lo schermo si illumina mentre la TV è accesa, nel colore dell'app (Netflix, YouTube …); l'etichetta mostra l'app o il titolo.", + "stairs_hint": "La scala sale verso il fondo (lontano dal bordo frontale segnato) e apre il soffitto del piano superiore.", + "floor_lights": "{n} luci accese", + "floor_open": "{n} aperte", + "floor_persons": "{n} persone", + "energy_consumption": "Consumo", + "energy_grid_import": "Prelievo dalla rete", + "energy_grid_export": "Immissione", + "energy_solar": "Solare", + "energy_battery": "Batteria", + "energy_tariff": "Tariffa", + "energy": "Energia", + "energy_meter": "Contatore", + "energy_grid": "Rete (W, + = prelievo)", + "energy_solar_sensor": "Produzione solare (W)", + "energy_battery_sensor": "Potenza batteria (W, + = scarica)", + "energy_battery_soc": "Carica batteria (%)", + "energy_tariff_sensor": "Tariffa (ad es. €/kWh)", + "energy_gas": "Contatore del gas (facoltativo)", + "energy_water": "Contatore dell'acqua (facoltativo)", + "energy_meters_hint": "Gas e acqua compaiono con il bilancio della casa – nella barra dell'energia e sulla scheda della casa: un sensore con il flusso attuale (m³/h, l/min) o la lettura di oggi.", + "energy_gas_short": "Gas", + "energy_water_short": "Acqua", + "energy_invert": "Inverti segno", + "energy_hint": "Le utenze sono dispositivi posizionati con un sensore di potenza (W): il sensore stesso o uno dello stesso dispositivo.", + "energy_balance": "Bilancio energetico", + "energy_balance_hint": "Rete, solare e batteria vengono dai dispositivi della planimetria: contatore, inverter e batteria domestica. Qui puoi scegliere altri sensori, invertire i segni e impostare il consumo della casa.", + "energy_rest": "Comune (resto)", + "energy_advanced": "Modalità energia avanzata", + "energy_advanced_on": "Usa i sottocontatori", + "energy_show_unmetered": "Mostra il consumo non misurato ai sottocontatori", + "energy_show_unmetered_hint": "L'etichetta di un sottocontatore mostra allora quanto consumano i suoi piani e quanto di questo non è misurato da nessun dispositivo, ad es. «500 W · 450 W non misurati». Altrimenti mostra la lettura del contatore.", + "energy_advanced_hint": "Per sottocontatori, ad es. uno per appartamento dietro un contatore principale: un contatore può dipendere da un altro e alimentare i propri piani. Disattivo = il primo contatore è l'allacciamento alla rete, gli altri sono utenze.", + "energy_consumption_sensor": "Consumo della casa (W, altrimenti dal bilancio)", + "energy_import_prefs": "Prendi dalla dashboard energia", + "energy_import_done": "{n} sensori presi: controlla i segni.", + "energy_import_none": "Nella dashboard energia non sono stati trovati sensori di potenza (W) adatti: sceglili a mano.", + "energy_import_failed": "La dashboard energia di Home Assistant non è configurata.", + "tool_meter": "Contatore", + "hint_meter": "Tocca il punto del contatore", + "presence": "Presenza", + "presence_hint": "Sensore di stanza per persona (ad es. ESPresense, Bermuda): il suo stato nomina la stanza o l'area.", + "presence_sensor": "Sensore di stanza", + "no_persons": "Non ci sono persone in Home Assistant.", + "packname:nextfloor.a_bad": "Bagno", + "pack:nextfloor.a_bad:vanity_60": "Mobile lavabo 60 con base", + "pack:nextfloor.a_bad:vanity_80": "Mobile lavabo 80 con base", + "pack:nextfloor.a_bad:vanity_100": "Mobile lavabo 100 con base", + "pack:nextfloor.a_bad:vanity_double_120": "Doppio lavabo 120", + "pack:nextfloor.a_bad:vanity_double_160": "Doppio lavabo", + "pack:nextfloor.a_bad:pedestal_basin": "Lavabo a colonna", + "pack:nextfloor.a_bad:bathtub_builtin": "Vasca da incasso", + "pack:nextfloor.a_bad:bathtub_corner": "Vasca angolare", + "pack:nextfloor.a_bad:bathtub_corner_compact": "Vasca angolare salvaspazio", + "pack:nextfloor.a_bad:bathtub_free": "Vasca freestanding", + "pack:nextfloor.a_bad:whirlpool_indoor": "Idromassaggio da interno", + "pack:nextfloor.a_bad:shower_corner_90": "Doccia angolare 90 × 90", + "pack:nextfloor.a_bad:shower_niche_120": "Doccia a nicchia 120 × 90", + "pack:nextfloor.a_bad:shower_walkin_140": "Doccia walk-in 140 × 90", + "pack:nextfloor.a_bad:shower_walkin_120": "Doccia walk-in", + "pack:nextfloor.a_bad:shower_rain_led": "Doccia a pioggia con LED", + "pack:nextfloor.a_bad:toilet_close": "WC monoblocco", + "pack:nextfloor.a_bad:toilet_hung": "WC sospeso", + "pack:nextfloor.a_bad:toilet_hung_compact": "WC sospeso (compatto)", + "pack:nextfloor.a_bad:bidet": "Bidet", + "pack:nextfloor.a_bad:cabinet_tall": "Colonna bagno alta", + "pack:nextfloor.a_bad:cabinet_mid": "Mobile bagno a mezza altezza", + "pack:nextfloor.a_bad:mirror_round_light": "Specchio rotondo con luce", + "pack:nextfloor.a_bad:mirror_80": "Specchio 80 × 60 con luce", + "pack:nextfloor.a_bad:mirror_led_100": "Specchio LED 100 × 70 con orologio", + "pack:nextfloor.a_bad:mirror_cabinet": "Pensile a specchio con luce", + "pack:nextfloor.a_bad:wall_shelf_bath": "Mensola da bagno", + "pack:nextfloor.a_bad:towel_rail": "Portasciugamani con asciugamano", + "pack:nextfloor.a_bad:towel_radiator": "Termoarredo", + "pack:nextfloor.a_bad:towel_heater_electric": "Scaldasalviette elettrico", + "pack:nextfloor.a_bad:sauna": "Sauna", + "pack:nextfloor.a_bad:bath_fan": "Aspiratore da bagno", + "pack:nextfloor.a_bad:washer_cabinet": "Mobile per lavatrice", + "pack:nextfloor.a_bad:washer_under_vanity": "Lavatrice sotto il lavabo", + "pack:nextfloor.a_bad:laundry_basket": "Cesto della biancheria", + "pack:nextfloor.a_bad:laundry_cabinet": "Mobile lavanderia con cesto", + "pack:nextfloor.a_bad:ladder_shelf": "Scaffale a scala con asciugamani", + "pack:nextfloor.a_bad:plant_stool": "Pianta su sgabello", + "packname:nextfloor.a_buero": "Ufficio e gaming", + "pack:nextfloor.a_buero:desk_standing": "Scrivania regolabile", + "pack:nextfloor.a_buero:desk_standing_bare": "Scrivania regolabile senza monitor", + "pack:nextfloor.a_buero:chair_gaming": "Sedia gaming", + "pack:nextfloor.a_buero:chair_office": "Sedia da ufficio ergonomica", + "pack:nextfloor.a_buero:sim_cockpit": "Cockpit sim racing", + "pack:nextfloor.a_buero:server_rack_42u": "Rack server (42U)", + "pack:nextfloor.a_buero:filing_cabinet": "Schedario", + "pack:nextfloor.a_buero:whiteboard": "Lavagna bianca", + "pack:nextfloor.a_buero:triple_monitor": "Postazione con tre monitor", + "pack:nextfloor.a_buero:bookcase_wall": "Parete libreria", + "pack:nextfloor.a_buero:desk_lamp": "Lampada da scrivania", + "pack:nextfloor.a_buero:desk_lamp_led": "Lampada da scrivania LED", + "pack:nextfloor.a_buero:arcade_cabinet": "Cabinato arcade", + "pack:nextfloor.a_buero:office_lounge_sofa": "Divano lounge da ufficio", + "pack:nextfloor.a_buero:monitor_light_bar": "Monitor con barra luminosa", + "pack:nextfloor.a_buero:printer_laser": "Stampante laser", + "pack:nextfloor.a_buero:wifi_router": "Router Wi-Fi", + "pack:nextfloor.a_buero:phone_booth": "Cabina telefonica", + "pack:nextfloor.a_buero:printer_3d": "Stampante 3D", + "pack:nextfloor.a_buero:printer_cube": "Stampante 3D chiusa a cubo", + "pack:nextfloor.a_buero:printer_multi": "Stampante 3D a cubo con unità multicolore", + "pack:nextfloor.a_buero:printer_large": "Stampante 3D grande a doppio ugello", + "pack:nextfloor.a_buero:printer_open": "Stampante 3D aperta compatta", + "pack:nextfloor.a_buero:printer_resin": "Stampante 3D a resina", + "pack:nextfloor.a_buero:filament_dryer": "Essiccatore di filamento", + "pack:nextfloor.a_buero:filament_rack": "Rastrelliera a parete per filamento", + "packname:nextfloor.a_fitness": "Fitness", + "pack:nextfloor.a_fitness:treadmill": "Tapis roulant", + "pack:nextfloor.a_fitness:power_rack": "Power rack con panca", + "pack:nextfloor.a_fitness:rowing_machine": "Vogatore", + "pack:nextfloor.a_fitness:spin_bike": "Spin bike", + "pack:nextfloor.a_fitness:dumbbell_rack": "Rastrelliera manubri", + "pack:nextfloor.a_fitness:punching_bag": "Sacco da boxe", + "pack:nextfloor.a_fitness:yoga_mat": "Tappetino yoga con blocco", + "pack:nextfloor.a_fitness:elliptical": "Ellittica", + "pack:nextfloor.a_fitness:mirror_wall_gym": "Parete a specchio", + "pack:nextfloor.a_fitness:exercise_ball": "Palla fitness", + "pack:nextfloor.a_fitness:wall_bars": "Spalliera", + "pack:nextfloor.a_fitness:fitness_mirror_smart": "Specchio fitness smart", + "pack:nextfloor.a_fitness:bike_trainer": "Bici su rullo smart", + "pack:nextfloor.a_fitness:sauna_cabin": "Cabina sauna", + "pack:nextfloor.a_fitness:massage_chair": "Poltrona massaggiante", + "pack:nextfloor.a_fitness:kettlebells": "Set di kettlebell", + "pack:nextfloor.a_fitness:water_cooler": "Erogatore d'acqua", + "packname:nextfloor.a_garten": "Giardino e terrazza", + "pack:nextfloor.a_garten:grill_gas": "Barbecue a gas", + "pack:nextfloor.a_garten:lounge_set": "Set lounge", + "pack:nextfloor.a_garten:sun_lounger_adj": "Lettino", + "pack:nextfloor.a_garten:parasol": "Ombrellone", + "pack:nextfloor.a_garten:pergola": "Pergola", + "pack:nextfloor.a_garten:raised_bed": "Orto rialzato", + "pack:nextfloor.a_garten:greenhouse": "Serra", + "pack:nextfloor.a_garten:hot_tub": "Vasca idromassaggio esterna", + "pack:nextfloor.a_garten:fire_bowl": "Braciere", + "pack:nextfloor.a_garten:garden_torch": "Fiaccola da giardino", + "pack:nextfloor.a_garten:play_tower": "Torre gioco con scivolo", + "pack:nextfloor.a_garten:garden_shed": "Casetta da giardino", + "pack:nextfloor.a_garten:trampoline": "Trampolino", + "pack:nextfloor.a_garten:flower_pots": "Vasi da fiori (set di 3)", + "pack:nextfloor.a_garten:sprinkler": "Irrigatore per prato", + "pack:nextfloor.a_garten:valve_box": "Pozzetto valvole irrigazione", + "pack:nextfloor.a_garten:rain_barrel": "Cisterna per pioggia", + "pack:nextfloor.a_garten:garden_lantern": "Lanterna da giardino", + "pack:nextfloor.a_garten:outdoor_kitchen": "Cucina da esterno", + "pack:nextfloor.a_garten:hammock": "Amaca con supporto", + "pack:nextfloor.a_garten:patio_heater": "Fungo riscaldante", + "pack:nextfloor.a_garten:tree_oak": "Quercia", + "pack:nextfloor.a_garten:tree_lime": "Tiglio", + "pack:nextfloor.a_garten:tree_birch": "Betulla", + "pack:nextfloor.a_garten:tree_maple": "Acero", + "pack:nextfloor.a_garten:tree_fruit": "Albero da frutto", + "pack:nextfloor.a_garten:tree_spruce": "Abete rosso", + "pack:nextfloor.a_garten:tree_pine": "Pino", + "pack:nextfloor.a_garten:tree_thuja": "Tuia", + "pack:nextfloor.a_garten:shrub": "Arbusto", + "pack:nextfloor.a_garten:shrub_flowering": "Arbusto fiorito", + "pack:nextfloor.a_garten:brush_wild": "Sterpaglia (zona selvatica)", + "pack:nextfloor.a_garten:tree_group_3": "Gruppo di alberi (3)", + "pack:nextfloor.a_garten:bin_rest_120": "Bidone indifferenziato 120 l", + "pack:nextfloor.a_garten:bin_rest_240": "Bidone indifferenziato 240 l", + "pack:nextfloor.a_garten:bin_bio_120": "Bidone organico 120 l", + "pack:nextfloor.a_garten:bin_bio_240": "Bidone organico 240 l", + "pack:nextfloor.a_garten:bin_paper_120": "Bidone carta 120 l", + "pack:nextfloor.a_garten:bin_paper_240": "Bidone carta 240 l", + "pack:nextfloor.a_garten:bin_yellow_120": "Bidone riciclabile 120 l", + "pack:nextfloor.a_garten:bin_yellow_240": "Bidone riciclabile 240 l", + "pack:nextfloor.a_garten:mailbox": "Cassetta della posta", + "pack:nextfloor.a_garten:mailbox_post": "Cassetta della posta su palo", + "pack:nextfloor.a_garten:awning_300": "Tenda da sole 3 m", + "pack:nextfloor.a_garten:awning_400": "Tenda da sole 4 m", + "pack:nextfloor.a_garten:awning_500": "Tenda da sole 5 m", + "pack:nextfloor.a_garten:sliding_gate": "Cancello scorrevole", + "packname:nextfloor.a_haustechnik": "Economia domestica e impianti", + "pack:nextfloor.a_haustechnik:gas_boiler": "Caldaia a condensazione a gas", + "pack:nextfloor.a_haustechnik:heat_pump_tower": "Unità interna pompa di calore (torre idronica)", + "pack:nextfloor.a_haustechnik:buffer_tank": "Serbatoio di accumulo", + "pack:nextfloor.a_haustechnik:heating_manifold": "Collettore riscaldamento a pavimento", + "pack:nextfloor.a_haustechnik:ventilation_unit": "Ventilazione con recupero di calore", + "pack:nextfloor.a_haustechnik:split_indoor": "Climatizzatore split (unità interna, a parete)", + "pack:nextfloor.a_haustechnik:split_outdoor": "Climatizzatore split (unità esterna)", + "pack:nextfloor.a_haustechnik:radiator_tall": "Radiatore di design alto", + "pack:nextfloor.a_haustechnik:meter_cabinet": "Armadio contatori", + "pack:nextfloor.a_haustechnik:water_softener": "Addolcitore d'acqua", + "pack:nextfloor.a_haustechnik:water_pump": "Pompa acqua domestica", + "pack:nextfloor.a_haustechnik:drip_tray": "Vaschetta con sensore perdite", + "pack:nextfloor.a_haustechnik:chest_freezer": "Congelatore a pozzo", + "pack:nextfloor.a_haustechnik:ironing_station": "Ferro da stiro con caldaia", + "pack:nextfloor.a_haustechnik:drying_rack": "Stendibiancheria", + "pack:nextfloor.a_haustechnik:rotary_line": "Stendibiancheria ad ombrello", + "pack:nextfloor.a_haustechnik:pantry_shelf_util": "Scaffale dispensa", + "pack:nextfloor.a_haustechnik:utility_sink": "Lavatoio", + "pack:nextfloor.a_haustechnik:laundry_basket_util": "Cesto della biancheria", + "pack:nextfloor.a_haustechnik:vacuum_station": "Stazione aspirapolvere senza filo", + "packname:nextfloor.a_haustiere": "Animali domestici", + "pack:nextfloor.a_haustiere:cat_tree_large": "Tiragraffi grande", + "pack:nextfloor.a_haustiere:scratch_post": "Palo tiragraffi", + "pack:nextfloor.a_haustiere:scratch_board_wall": "Tiragraffi a parete", + "pack:nextfloor.a_haustiere:cat_cave": "Cuccia a grotta per gatti", + "pack:nextfloor.a_haustiere:cat_bed_round": "Cuccia rotonda per gatti", + "pack:nextfloor.a_haustiere:cat_wall_shelf": "Mensola a parete per gatti", + "pack:nextfloor.a_haustiere:cat_steps": "Gradini per gatti", + "pack:nextfloor.a_haustiere:litter_covered": "Lettiera coperta", + "pack:nextfloor.a_haustiere:litter_auto": "Lettiera autopulente", + "pack:nextfloor.a_haustiere:dog_bed": "Cuccia per cani", + "pack:nextfloor.a_haustiere:dog_basket": "Cesta per cani", + "pack:nextfloor.a_haustiere:dog_house": "Casetta per cani", + "pack:nextfloor.a_haustiere:pet_bowls": "Ciotole cibo e acqua", + "pack:nextfloor.a_haustiere:pet_feeder": "Distributore automatico di cibo", + "pack:nextfloor.a_haustiere:pet_fountain": "Fontanella per animali", + "pack:nextfloor.a_haustiere:pet_gate": "Cancelletto per animali", + "pack:nextfloor.a_haustiere:pet_stairs": "Scaletta per animali", + "pack:nextfloor.a_haustiere:hamster_cage": "Gabbia per criceti", + "pack:nextfloor.a_haustiere:small_animal_cage": "Gabbia per piccoli animali", + "pack:nextfloor.a_haustiere:rabbit_run": "Recinto per conigli (esterno)", + "pack:nextfloor.a_haustiere:bird_cage": "Gabbia per uccelli", + "pack:nextfloor.a_haustiere:aquarium_100": "Acquario 100 l", + "pack:nextfloor.a_haustiere:aquarium_240": "Acquario 240 l con mobile", + "pack:nextfloor.a_haustiere:terrarium": "Terrario", + "pack:nextfloor.a_haustiere:pet_cat": "Gatto (gironzola)", + "pack:nextfloor.a_haustiere:pet_dog": "Cane (gironzola)", + "pack:nextfloor.a_haustiere:pet_rabbit": "Coniglio (saltella in giro)", + "packname:nextfloor.a_kinderzimmer": "Cameretta", + "pack:nextfloor.a_kinderzimmer:loft_bed_slide": "Letto soppalco con scivolo", + "pack:nextfloor.a_kinderzimmer:teepee": "Tenda tipi", + "pack:nextfloor.a_kinderzimmer:play_kitchen": "Cucina giocattolo", + "pack:nextfloor.a_kinderzimmer:kids_desk": "Scrivania per bambini", + "pack:nextfloor.a_kinderzimmer:toy_shelf": "Scaffale giochi con contenitori", + "pack:nextfloor.a_kinderzimmer:cosy_corner": "Angolo relax", + "pack:nextfloor.a_kinderzimmer:rocking_horse": "Cavallo a dondolo", + "pack:nextfloor.a_kinderzimmer:play_mat_road": "Tappeto strade", + "pack:nextfloor.a_kinderzimmer:kids_table_2": "Tavolino per bambini con 2 sedie", + "pack:nextfloor.a_kinderzimmer:moon_light": "Luce notturna a luna", + "pack:nextfloor.a_kinderzimmer:ball_pit": "Piscina di palline", + "pack:nextfloor.a_kinderzimmer:house_bed": "Letto casetta", + "pack:nextfloor.a_kinderzimmer:baby_monitor": "Baby monitor con telecamera", + "pack:nextfloor.a_kinderzimmer:star_projector": "Proiettore di stelle", + "pack:nextfloor.a_kinderzimmer:kids_cot": "Lettino", + "pack:nextfloor.a_kinderzimmer:kids_changing_table": "Fasciatoio", + "pack:nextfloor.a_kinderzimmer:kids_wardrobe": "Armadio per bambini", + "pack:nextfloor.a_kinderzimmer:toy_boxes_3": "Contenitori giochi (3)", + "packname:nextfloor.a_kino": "Home cinema e hi-fi", + "pack:nextfloor.a_kino:screen_wall": "Schermo di proiezione (a parete)", + "pack:nextfloor.a_kino:screen_roll": "Schermo di proiezione avvolgibile", + "pack:nextfloor.a_kino:projector_ceiling": "Proiettore (a soffitto)", + "pack:nextfloor.a_kino:projector_table": "Proiettore (da tavolo)", + "pack:nextfloor.a_kino:speaker_floor": "Diffusore da pavimento", + "pack:nextfloor.a_kino:speaker_shelf": "Diffusore da scaffale", + "pack:nextfloor.a_kino:speaker_centre": "Diffusore centrale", + "pack:nextfloor.a_kino:subwoofer": "Subwoofer", + "pack:nextfloor.a_kino:soundbar": "Soundbar", + "pack:nextfloor.a_kino:soundbar_premium": "Soundbar premium", + "pack:nextfloor.a_kino:speaker_wall": "Diffusore a parete", + "pack:nextfloor.a_kino:speaker_ceiling": "Diffusore da soffitto", + "pack:nextfloor.a_kino:av_receiver": "Ricevitore AV", + "pack:nextfloor.a_kino:turntable": "Giradischi", + "pack:nextfloor.a_kino:record_shelf": "Scaffale per vinili", + "pack:nextfloor.a_kino:game_console": "Console di gioco", + "pack:nextfloor.a_kino:hifi_rack": "Mobile hi-fi", + "pack:nextfloor.a_kino:cinema_seat": "Poltrona da cinema", + "pack:nextfloor.a_kino:cinema_row_3": "Fila di poltrone da cinema (3)", + "pack:nextfloor.a_kino:acoustic_panel": "Pannello acustico", + "pack:nextfloor.a_kino:bass_trap": "Bass trap (angolo)", + "pack:nextfloor.a_kino:popcorn_maker": "Macchina per popcorn", + "pack:nextfloor.a_kino:star_ceiling": "Cielo stellato", + "pack:nextfloor.a_kino:smart_speaker_ball": "Smart speaker (sfera)", + "pack:nextfloor.a_kino:smart_speaker_cylinder": "Smart speaker (cilindro)", + "pack:nextfloor.a_kino:smart_speaker_puck": "Smart speaker (disco)", + "pack:nextfloor.a_kino:smart_speaker_pod": "Smart speaker (pod)", + "pack:nextfloor.a_kino:smart_speaker_tall": "Smart speaker (alto)", + "pack:nextfloor.a_kino:smart_speaker_oval": "Smart speaker (ovale)", + "pack:nextfloor.a_kino:multiroom_compact": "Diffusore multiroom compatto", + "pack:nextfloor.a_kino:speaker_portable": "Diffusore portatile", + "pack:nextfloor.a_kino:display_5": "Smart display 5″", + "pack:nextfloor.a_kino:display_8": "Smart display 8″", + "pack:nextfloor.a_kino:display_7_float": "Smart display 7″ (sospeso)", + "pack:nextfloor.a_kino:display_15_wall": "Smart display 15″ (a parete)", + "pack:nextfloor.a_kino:speaker_stand": "Supporto per diffusori", + "packname:nextfloor.a_kueche": "Cucina", + "pack:nextfloor.a_kueche:base_30": "Base 30", + "pack:nextfloor.a_kueche:base_40": "Base 40", + "pack:nextfloor.a_kueche:base_50": "Base 50", + "pack:nextfloor.a_kueche:base_60": "Base 60", + "pack:nextfloor.a_kueche:base_80": "Base 80", + "pack:nextfloor.a_kueche:base_90": "Base 90", + "pack:nextfloor.a_kueche:base_100": "Base 100", + "pack:nextfloor.a_kueche:base_120": "Base 120", + "pack:nextfloor.a_kueche:drawer_40": "Cassettiera 40", + "pack:nextfloor.a_kueche:drawer_50": "Cassettiera 50", + "pack:nextfloor.a_kueche:drawer_60": "Cassettiera 60", + "pack:nextfloor.a_kueche:drawer_80": "Cassettiera 80", + "pack:nextfloor.a_kueche:drawer_90": "Cassettiera 90", + "pack:nextfloor.a_kueche:drawer_100": "Cassettiera 100", + "pack:nextfloor.a_kueche:drawer_120": "Cassettiera 120", + "pack:nextfloor.a_kueche:sink_60": "Base lavello 60", + "pack:nextfloor.a_kueche:sink_80": "Base lavello 80", + "pack:nextfloor.a_kueche:sink_100": "Base lavello 100", + "pack:nextfloor.a_kueche:hob_60": "Base piano cottura 60", + "pack:nextfloor.a_kueche:hob_80": "Base piano cottura 80", + "pack:nextfloor.a_kueche:cooker_60": "Cucina con forno 60", + "pack:nextfloor.a_kueche:dishwasher_60": "Lavastoviglie a incasso 60", + "pack:nextfloor.a_kueche:dishwasher_45": "Lavastoviglie a incasso 45", + "pack:nextfloor.a_kueche:base_corner": "Base angolare", + "pack:nextfloor.a_kueche:wall_40": "Pensile 40", + "pack:nextfloor.a_kueche:wall_50": "Pensile 50", + "pack:nextfloor.a_kueche:wall_60": "Pensile 60", + "pack:nextfloor.a_kueche:wall_80": "Pensile 80", + "pack:nextfloor.a_kueche:wall_90": "Pensile 90", + "pack:nextfloor.a_kueche:wall_100": "Pensile 100", + "pack:nextfloor.a_kueche:wall_120": "Pensile 120", + "pack:nextfloor.a_kueche:wall_glass_80": "Pensile vetrina 80", + "pack:nextfloor.a_kueche:wall_corner": "Pensile angolare", + "pack:nextfloor.a_kueche:hood_wall": "Cappa a parete", + "pack:nextfloor.a_kueche:hood_island": "Cappa a isola", + "pack:nextfloor.a_kueche:tall_pantry": "Colonna dispensa", + "pack:nextfloor.a_kueche:tall_oven": "Colonna forno e microonde", + "pack:nextfloor.a_kueche:tall_fridge": "Colonna frigo-congelatore", + "pack:nextfloor.a_kueche:tall_steam": "Colonna forno a vapore e forno", + "pack:nextfloor.a_kueche:fridge_freezer": "Frigo-congelatore", + "pack:nextfloor.a_kueche:fridge_french": "Frigorifero French door", + "pack:nextfloor.a_kueche:wine_fridge": "Cantinetta vini", + "pack:nextfloor.a_kueche:glass_cabinet": "Vetrinetta", + "pack:nextfloor.a_kueche:row_270": "Cucina lineare 270", + "pack:nextfloor.a_kueche:row_330": "Cucina lineare 330", + "pack:nextfloor.a_kueche:island_bar": "Isola con bancone", + "pack:nextfloor.a_kueche:island_hob": "Isola con piano cottura", + "pack:nextfloor.a_kueche:breakfast_bar": "Bancone colazione (a parete)", + "pack:nextfloor.a_kueche:bar_stools_2": "Sgabelli da bar (set di 2)", + "pack:nextfloor.a_kueche:dining_bench_long": "Tavolo da pranzo lungo con panca", + "pack:nextfloor.a_kueche:dining_round_4": "Tavolo rotondo con 4 sedie", + "pack:nextfloor.a_kueche:high_table_2": "Tavolo alto con 2 sgabelli", + "pack:nextfloor.a_kueche:kitchen_trolley": "Carrello da cucina", + "pack:nextfloor.a_kueche:pantry_shelf": "Scaffale dispensa", + "pack:nextfloor.a_kueche:spice_rack": "Portaspezie a parete", + "pack:nextfloor.a_kueche:coffee_machine": "Macchina da caffè automatica", + "pack:nextfloor.a_kueche:microwave": "Microonde", + "pack:nextfloor.a_kueche:stand_mixer": "Impastatrice planetaria", + "pack:nextfloor.a_kueche:kettle": "Bollitore", + "pack:nextfloor.a_kueche:toaster": "Tostapane", + "pack:nextfloor.a_kueche:herb_garden": "Orto smart di erbe aromatiche", + "pack:nextfloor.a_kueche:pendant_trio": "Trio di lampade a sospensione", + "pack:nextfloor.a_kueche:pendant_linear": "Lampada a sospensione lineare", + "pack:nextfloor.a_kueche:cabinet_light_60": "Luce LED sottopensile 60", + "pack:nextfloor.a_kueche:cabinet_light_80": "Luce LED sottopensile 80", + "pack:nextfloor.a_kueche:range_cooker_90": "Cucina professionale 90", + "packname:nextfloor.a_schlafzimmer": "Camera da letto", + "pack:nextfloor.a_schlafzimmer:bed_90": "Letto 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_140": "Letto 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_160": "Letto 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_180": "Letto 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_200": "Letto 200 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_180": "Letto imbottito 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_140": "Letto imbottito 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_boxspring": "Letto boxspring 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_futon": "Letto futon 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_storage": "Letto contenitore 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_canopy": "Letto a baldacchino", + "pack:nextfloor.a_schlafzimmer:bed_ambient": "Letto 180 con luce d'ambiente", + "pack:nextfloor.a_schlafzimmer:bed_bench": "Panca da letto", + "pack:nextfloor.a_schlafzimmer:shoe_bench": "Scarpiera con seduta", + "pack:nextfloor.a_schlafzimmer:wardrobe_2": "Armadio a 2 ante", + "pack:nextfloor.a_schlafzimmer:wardrobe_3": "Armadio a 3 ante", + "pack:nextfloor.a_schlafzimmer:wardrobe_4": "Armadio a 4 ante", + "pack:nextfloor.a_schlafzimmer:wardrobe_6": "Armadio a 6 ante", + "pack:nextfloor.a_schlafzimmer:wardrobe_mirror": "Armadio con anta a specchio", + "pack:nextfloor.a_schlafzimmer:wardrobe_sliding": "Armadio con ante scorrevoli", + "pack:nextfloor.a_schlafzimmer:wardrobe_light": "Armadio con luce interna", + "pack:nextfloor.a_schlafzimmer:wardrobe_corner": "Armadio angolare", + "pack:nextfloor.a_schlafzimmer:walk_in_closet": "Cabina armadio aperta", + "pack:nextfloor.a_schlafzimmer:clothes_rail": "Appendiabiti a stender", + "pack:nextfloor.a_schlafzimmer:nightstand": "Comodino con cassetto", + "pack:nextfloor.a_schlafzimmer:nightstand_slim": "Comodino stretto", + "pack:nextfloor.a_schlafzimmer:nightstand_floating": "Comodino sospeso", + "pack:nextfloor.a_schlafzimmer:dresser_6": "Cassettiera a 6 cassetti 140", + "pack:nextfloor.a_schlafzimmer:chest_tall_5": "Settimino a 5 cassetti", + "pack:nextfloor.a_schlafzimmer:chest_tall": "Cassettiera alta", + "pack:nextfloor.a_schlafzimmer:chest_80": "Cassettiera a 3 cassetti 80", + "pack:nextfloor.a_schlafzimmer:vanity_table": "Toeletta con specchio", + "pack:nextfloor.a_schlafzimmer:dressing_table_light": "Toeletta con specchio luminoso", + "pack:nextfloor.a_schlafzimmer:cot": "Lettino", + "pack:nextfloor.a_schlafzimmer:changing_table": "Fasciatoio", + "pack:nextfloor.a_schlafzimmer:standing_mirror": "Specchio da terra", + "pack:nextfloor.a_schlafzimmer:reading_nook": "Angolo lettura con poltrona", + "pack:nextfloor.a_schlafzimmer:bedside_lamp": "Lampada da comodino", + "pack:nextfloor.a_schlafzimmer:touch_lamp": "Lampada da comodino touch", + "pack:nextfloor.a_schlafzimmer:humidifier": "Umidificatore", + "pack:nextfloor.a_schlafzimmer:sunrise_clock": "Sveglia con alba simulata", + "packname:nextfloor.a_smart": "Smart home e tecnologia", + "pack:nextfloor.a_smart:wallbox": "Wallbox", + "pack:nextfloor.a_smart:electric_car": "Auto elettrica", + "pack:nextfloor.a_smart:heat_pump_outdoor": "Pompa di calore (unità esterna)", + "pack:nextfloor.a_smart:home_battery": "Batteria domestica", + "pack:nextfloor.a_smart:inverter_solar": "Inverter solare", + "pack:nextfloor.a_smart:robot_vacuum": "Robot aspirapolvere con base", + "pack:nextfloor.a_smart:mower_garage": "Robot tagliaerba con garage", + "pack:nextfloor.a_smart:washer_dryer_stack": "Colonna lavatrice-asciugatrice", + "pack:nextfloor.a_smart:network_rack": "Rack di rete", + "pack:nextfloor.a_smart:smart_display": "Smart display", + "pack:nextfloor.a_smart:solar_balcony": "Pannello solare da balcone", + "pack:nextfloor.a_smart:fuse_box": "Quadro elettrico", + "pack:nextfloor.a_smart:nas_server": "Server NAS", + "pack:nextfloor.a_smart:hot_water_tank": "Bollitore acqua calda", + "pack:nextfloor.a_smart:light_pillar": "Colonna luminosa sfumata", + "pack:nextfloor.a_smart:light_bars_tv": "Coppia di barre luminose (TV)", + "pack:nextfloor.a_smart:orb_lamp": "Lampada da tavolo a sfera luminosa", + "pack:nextfloor.a_smart:glow_lamp_portable": "Lampada luminosa portatile", + "pack:nextfloor.a_smart:mood_spot": "Faretto d'atmosfera da tavolo", + "pack:nextfloor.a_smart:cube_lamp": "Lampada a cubo", + "pack:nextfloor.a_smart:ceiling_panel_round": "Pannello rotondo a soffitto", + "pack:nextfloor.a_smart:garden_spots_3": "Faretti da giardino (set di 3)", + "pack:nextfloor.a_smart:wall_light_updown": "Applique esterna su e giù", + "pack:nextfloor.a_smart:siren_strobe": "Sirena con lampeggiante", + "pack:nextfloor.a_smart:access_point": "Access point Wi-Fi (a soffitto)", + "pack:nextfloor.a_smart:smoke_detector": "Rilevatore di fumo", + "pack:nextfloor.a_smart:thermostat_wall": "Termostato a parete", + "pack:nextfloor.a_smart:dehumidifier": "Deumidificatore", + "pack:nextfloor.a_smart:ceiling_fan": "Ventilatore da soffitto", + "pack:nextfloor.a_smart:ceiling_fan_light": "Ventilatore da soffitto con luce", + "pack:nextfloor.a_smart:light_switch_1": "Interruttore luce, 1 tasto", + "pack:nextfloor.a_smart:socket_1": "Presa, 1 posto", + "pack:nextfloor.a_smart:light_switch_2": "Interruttore luce, 2 tasti", + "pack:nextfloor.a_smart:socket_2": "Presa, 2 posti", + "pack:nextfloor.a_smart:light_switch_3": "Interruttore luce, 3 tasti", + "pack:nextfloor.a_smart:socket_3": "Presa, 3 posti", + "pack:nextfloor.a_smart:light_switch_4": "Interruttore luce, 4 tasti", + "pack:nextfloor.a_smart:socket_4": "Presa, 4 posti", + "pack:nextfloor.a_smart:socket_outdoor": "Presa esterna con coperchio", + "packname:nextfloor.a_wohnzimmer": "Soggiorno", + "pack:nextfloor.a_wohnzimmer:sofa_2": "Divano 2 posti", + "pack:nextfloor.a_wohnzimmer:sofa_3": "Divano 3 posti", + "pack:nextfloor.a_wohnzimmer:sofa_4": "Divano grande 4 posti", + "pack:nextfloor.a_wohnzimmer:sofa_velvet": "Divano in velluto 3 posti", + "pack:nextfloor.a_wohnzimmer:sofa_armless": "Divano senza braccioli", + "pack:nextfloor.a_wohnzimmer:sofa_chaise": "Divano con chaise longue", + "pack:nextfloor.a_wohnzimmer:sofa_chesterfield": "Divano Chesterfield", + "pack:nextfloor.a_wohnzimmer:sofa_bed": "Divano letto", + "pack:nextfloor.a_wohnzimmer:sofa_corner_l": "Divano angolare (sinistra)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_r": "Divano angolare (destra)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_xl": "Divano angolare grande (a L)", + "pack:nextfloor.a_wohnzimmer:sofa_u": "Divano a U", + "pack:nextfloor.a_wohnzimmer:chaise_longue": "Chaise longue", + "pack:nextfloor.a_wohnzimmer:modular_sofa": "Divano modulare (5 pezzi)", + "pack:nextfloor.a_wohnzimmer:armchair": "Poltrona", + "pack:nextfloor.a_wohnzimmer:club_chair": "Poltrona club", + "pack:nextfloor.a_wohnzimmer:wingback": "Poltrona bergère", + "pack:nextfloor.a_wohnzimmer:cocktail_chair": "Poltroncina cocktail", + "pack:nextfloor.a_wohnzimmer:recliner": "Poltrona reclinabile con poggiapiedi", + "pack:nextfloor.a_wohnzimmer:bean_bag": "Pouf sacco", + "pack:nextfloor.a_wohnzimmer:pouf": "Pouf", + "pack:nextfloor.a_wohnzimmer:rocking_chair": "Sedia a dondolo", + "pack:nextfloor.a_wohnzimmer:coffee_rect": "Tavolino rettangolare", + "pack:nextfloor.a_wohnzimmer:coffee_glass": "Tavolino in vetro", + "pack:nextfloor.a_wohnzimmer:coffee_round": "Tavolino rotondo", + "pack:nextfloor.a_wohnzimmer:coffee_nesting": "Tavolini a nido", + "pack:nextfloor.a_wohnzimmer:side_round": "Tavolino rotondo di servizio", + "pack:nextfloor.a_wohnzimmer:console": "Consolle", + "pack:nextfloor.a_wohnzimmer:dining_120": "Tavolo da pranzo 120 × 90", + "pack:nextfloor.a_wohnzimmer:dining_160": "Tavolo da pranzo 160 × 90", + "pack:nextfloor.a_wohnzimmer:dining_200": "Tavolo da pranzo 200 × 90", + "pack:nextfloor.a_wohnzimmer:dining_220": "Tavolo in legno massello 220 × 100", + "pack:nextfloor.a_wohnzimmer:chair_wood": "Sedia in legno", + "pack:nextfloor.a_wohnzimmer:chair_upholstered": "Sedia imbottita", + "pack:nextfloor.a_wohnzimmer:chair_shell": "Sedia a scocca", + "pack:nextfloor.a_wohnzimmer:dining_bench": "Panca da pranzo 160", + "pack:nextfloor.a_wohnzimmer:lowboard_120": "Mobile basso 120", + "pack:nextfloor.a_wohnzimmer:lowboard_160": "Mobile basso 160", + "pack:nextfloor.a_wohnzimmer:lowboard_200": "Mobile basso 200", + "pack:nextfloor.a_wohnzimmer:sideboard_160": "Credenza 160", + "pack:nextfloor.a_wohnzimmer:highboard": "Credenza alta", + "pack:nextfloor.a_wohnzimmer:display_cabinet": "Vetrina", + "pack:nextfloor.a_wohnzimmer:chest_3": "Cassettiera a 3 cassetti", + "pack:nextfloor.a_wohnzimmer:bookshelf_tall": "Libreria alta", + "pack:nextfloor.a_wohnzimmer:bookshelf_wide": "Libreria larga", + "pack:nextfloor.a_wohnzimmer:cube_2x2": "Scaffale a cubi 2 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x2": "Scaffale a cubi 4 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x4": "Scaffale a cubi 4 × 4", + "pack:nextfloor.a_wohnzimmer:divider_open": "Scaffale divisorio", + "pack:nextfloor.a_wohnzimmer:wall_shelf": "Mensola sospesa", + "pack:nextfloor.a_wohnzimmer:coat_stand": "Appendiabiti da terra", + "pack:nextfloor.a_wohnzimmer:wall_unit_vitrines": "Parete attrezzata con vetrine", + "pack:nextfloor.a_wohnzimmer:wall_unit_tv": "Parete attrezzata con TV", + "pack:nextfloor.a_wohnzimmer:tv_on_stand": "TV su piedistallo", + "pack:nextfloor.a_wohnzimmer:media_wall": "Parete media con TV", + "pack:nextfloor.a_wohnzimmer:wood_stove": "Stufa a legna", + "pack:nextfloor.a_wohnzimmer:fireplace_wall": "Camino elettrico a parete", + "pack:nextfloor.a_wohnzimmer:piano": "Pianoforte verticale con panca", + "pack:nextfloor.a_wohnzimmer:floor_lamp_arc": "Lampada ad arco", + "pack:nextfloor.a_wohnzimmer:floor_lamp_tripod": "Lampada a treppiede", + "pack:nextfloor.a_wohnzimmer:table_lamp_ceramic": "Lampada da tavolo in ceramica", + "pack:nextfloor.a_wohnzimmer:vase_pampas": "Vaso da terra con erba della pampa", + "pack:nextfloor.a_wohnzimmer:monstera": "Monstera grande", + "pack:nextfloor.a_wohnzimmer:rug_round": "Tappeto rotondo", + "pack:nextfloor.a_wohnzimmer:rug_240": "Tappeto 240 × 170", + "pack:nextfloor.a_wohnzimmer:painting_light": "Quadro con luce", + "pack:nextfloor.a_wohnzimmer:shelf_led": "Scaffale con ripiani LED", + "pack:nextfloor.a_wohnzimmer:air_purifier": "Purificatore d'aria", + "pack:nextfloor.a_wohnzimmer:tower_fan": "Ventilatore a colonna", + "pack:nextfloor.a_wohnzimmer:smart_speaker_living": "Smart speaker", + "packname:nextfloor.ausbau": "Architettura e finiture", + "pack:nextfloor.ausbau:column_round": "Colonna rotonda", + "pack:nextfloor.ausbau:column_square": "Colonna quadrata", + "pack:nextfloor.ausbau:beam": "Trave a soffitto", + "pack:nextfloor.ausbau:chimney": "Canna fumaria", + "pack:nextfloor.ausbau:glass_wall": "Parete divisoria in vetro", + "pack:nextfloor.ausbau:sliding_wall": "Parete scorrevole", + "pack:nextfloor.ausbau:platform": "Pedana", + "pack:nextfloor.ausbau:half_wall": "Muretto", + "pack:nextfloor.ausbau:divider_shelf": "Scaffale divisorio", + "pack:nextfloor.ausbau:pilaster": "Lesena", + "pack:nextfloor.ausbau:column_steel": "Colonna in acciaio", + "pack:nextfloor.ausbau:beams_wood_5": "Travi in legno a soffitto (5)", + "pack:nextfloor.ausbau:beam_downstand": "Trave ribassata", + "pack:nextfloor.ausbau:fireplace_builtin": "Camino a incasso", + "pack:nextfloor.ausbau:divider_slats": "Divisorio a listelli", + "pack:nextfloor.ausbau:curtain_motor": "Tenda motorizzata", + "pack:nextfloor.ausbau:niche_shelf": "Scaffale a incasso (nicchia)", + "pack:nextfloor.ausbau:niche_led": "Nicchia LED", + "pack:nextfloor.ausbau:light_cove": "Gola luminosa (soffitto)", + "pack:nextfloor.ausbau:gallery_rail_glass": "Ringhiera del soppalco (vetro)", + "pack:nextfloor.ausbau:window_seat": "Seduta alla finestra", + "pack:nextfloor.ausbau:curtain_pair": "Tenda (si apre da entrambi i lati)", + "pack:nextfloor.ausbau:roller_blind_inside": "Tenda a rullo (interna)", + "packname:nextfloor.bad": "Bagno extra", + "pack:nextfloor.bad:double_vanity": "Doppio lavabo", + "pack:nextfloor.bad:walkin_shower": "Doccia walk-in", + "pack:nextfloor.bad:towel_radiator": "Termoarredo", + "pack:nextfloor.bad:mirror_cabinet": "Pensile a specchio con luce", + "pack:nextfloor.bad:washer_tower": "Colonna lavatrice-asciugatrice", + "pack:nextfloor.bad:laundry_basket": "Cesto della biancheria", + "pack:nextfloor.bad:bath_shelf": "Mensola da bagno", + "packname:nextfloor.energie": "Energia e impianti", + "pack:nextfloor.energie:heat_pump": "Pompa di calore (unità esterna)", + "pack:nextfloor.energie:pellet_boiler": "Caldaia a pellet", + "pack:nextfloor.energie:buffer_tank": "Serbatoio di accumulo", + "pack:nextfloor.energie:hot_water_tank": "Bollitore acqua calda", + "pack:nextfloor.energie:home_battery": "Batteria domestica (torre)", + "pack:nextfloor.energie:inverter": "Inverter", + "pack:nextfloor.energie:wallbox": "Wallbox", + "pack:nextfloor.energie:meter_cabinet": "Armadio contatori", + "pack:nextfloor.energie:ventilation": "Unità di ventilazione", + "pack:nextfloor.energie:solar_carport_pillar": "Pilastro carport solare", + "packname:nextfloor.fahrzeuge": "Veicoli", + "pack:nextfloor.fahrzeuge:tesla_model_s": "Tesla Model S", + "packname:nextfloor.a_saison": "Stagioni e decorazioni", + "packname:nextfloor.a_smart2": "Casa smart 2", + "packname:nextfloor.a_haustechnik2": "Impianti 2", + "packname:nextfloor.a_wellness": "Benessere", + "packname:nextfloor.a_garten2": "Giardino 2", + "packname:nextfloor.a_kueche2": "Cucina 2", + "packname:nextfloor.a_fahrzeuge2": "Veicoli 2", + "packname:nextfloor.a_aussenkueche": "Cucina esterna e terrazza", + "packname:nextfloor.a_werkstatt2": "Officina 2", + "packname:nextfloor.a_japandi": "Japandi e scandinavo", + "packname:nextfloor.a_loft": "Loft e industriale", + "packname:nextfloor.a_gruen": "Piante da interno", + "packname:nextfloor.a_musik": "Musica e atelier", + "pack:nextfloor.a_saison:xmas_tree": "Albero di Natale con luci", + "pack:nextfloor.a_saison:advent_wreath": "Corona dell'Avvento", + "pack:nextfloor.a_saison:lights_outdoor": "Catena luminosa esterna", + "pack:nextfloor.a_saison:window_star": "Stella da finestra", + "pack:nextfloor.a_saison:candle_arch": "Arco di candele", + "pack:nextfloor.a_saison:reindeer_light": "Renna luminosa", + "pack:nextfloor.a_saison:pumpkin": "Zucca", + "pack:nextfloor.a_saison:pumpkin_lantern": "Zucca intagliata", + "pack:nextfloor.a_saison:easter_tree": "Albero di Pasqua", + "pack:nextfloor.a_saison:snowman": "Pupazzo di neve", + "pack:nextfloor.a_saison:gift_pile": "Regali", + "pack:nextfloor.a_smart2:siren": "Sirena", + "pack:nextfloor.a_smart2:access_point": "Access point Wi-Fi", + "pack:nextfloor.a_smart2:access_point_wall": "Access point Wi-Fi (parete)", + "pack:nextfloor.a_smart2:smoke_detector": "Rilevatore di fumo", + "pack:nextfloor.a_smart2:co_detector": "Rilevatore di CO", + "pack:nextfloor.a_smart2:dehumidifier": "Deumidificatore", + "pack:nextfloor.a_smart2:cube_lamp": "Lampada cubo", + "pack:nextfloor.a_smart2:presence_ceiling": "Sensore di presenza (soffitto)", + "pack:nextfloor.a_smart2:water_leak": "Sensore di allagamento", + "pack:nextfloor.a_smart2:air_quality": "Sensore qualità dell'aria", + "pack:nextfloor.a_smart2:doorbell_cam": "Videocitofono", + "pack:nextfloor.a_haustechnik2:water_tank": "Serbatoio d'acqua", + "pack:nextfloor.a_haustechnik2:oil_tank": "Serbatoio del gasolio", + "pack:nextfloor.a_haustechnik2:oil_boiler": "Caldaia a gasolio", + "pack:nextfloor.a_haustechnik2:water_softener": "Addolcitore", + "pack:nextfloor.a_haustechnik2:buffer_tank": "Accumulo inerziale", + "pack:nextfloor.a_haustechnik2:cistern": "Cisterna per acqua piovana", + "pack:nextfloor.a_haustechnik2:ventilation_unit": "Unità di ventilazione", + "pack:nextfloor.a_haustechnik2:expansion_vessel": "Vaso di espansione", + "pack:nextfloor.a_haustechnik2:heat_pump_indoor": "Pompa di calore (unità interna)", + "pack:nextfloor.a_wellness:sauna_cabin": "Sauna", + "pack:nextfloor.a_wellness:sauna_barrel": "Sauna a botte", + "pack:nextfloor.a_wellness:infrared_cabin": "Cabina a infrarossi", + "pack:nextfloor.a_wellness:hot_tub": "Idromassaggio", + "pack:nextfloor.a_wellness:plunge_pool": "Vasca a immersione", + "pack:nextfloor.a_wellness:steam_shower": "Doccia a vapore", + "pack:nextfloor.a_wellness:relax_lounger": "Lettino relax", + "pack:nextfloor.a_wellness:cold_bath": "Vasca del ghiaccio", + "pack:nextfloor.a_garten2:water_feature": "Fontana con luce", + "pack:nextfloor.a_garten2:pond": "Laghetto con pompa", + "pack:nextfloor.a_garten2:robot_mower": "Robot tagliaerba", + "pack:nextfloor.a_garten2:mower_dock": "Base di ricarica robot", + "pack:nextfloor.a_garten2:sandbox": "Sabbiera", + "pack:nextfloor.a_garten2:beach_chair": "Poltrona da spiaggia", + "pack:nextfloor.a_garten2:wood_pile": "Catasta di legna", + "pack:nextfloor.a_garten2:bird_house": "Casetta per uccelli", + "pack:nextfloor.a_garten2:raised_bed": "Orto rialzato", + "pack:nextfloor.a_garten2:garden_shower": "Doccia da giardino", + "pack:nextfloor.a_kueche2:coffee_machine": "Macchina da caffè automatica", + "pack:nextfloor.a_kueche2:espresso": "Macchina espresso", + "pack:nextfloor.a_kueche2:kettle": "Bollitore", + "pack:nextfloor.a_kueche2:toaster": "Tostapane", + "pack:nextfloor.a_kueche2:stand_mixer": "Impastatrice planetaria", + "pack:nextfloor.a_kueche2:thermo_cooker": "Robot da cucina con cottura", + "pack:nextfloor.a_kueche2:air_fryer": "Friggitrice ad aria", + "pack:nextfloor.a_kueche2:microwave": "Microonde", + "pack:nextfloor.a_kueche2:wine_fridge": "Cantinetta frigo", + "pack:nextfloor.a_kueche2:water_bar": "Gasatore", + "pack:nextfloor.a_kueche2:dishwasher_slim": "Lavastoviglie 45 cm", + "pack:nextfloor.a_fahrzeuge2:motorbike": "Moto", + "pack:nextfloor.a_fahrzeuge2:scooter": "Scooter", + "pack:nextfloor.a_fahrzeuge2:camper_van": "Camper", + "pack:nextfloor.a_fahrzeuge2:trailer": "Rimorchio", + "pack:nextfloor.a_fahrzeuge2:e_bike": "E-bike", + "pack:nextfloor.a_fahrzeuge2:cargo_bike": "Cargo bike", + "pack:nextfloor.a_fahrzeuge2:quad": "Quad", + "pack:nextfloor.a_fahrzeuge2:boat_trailer": "Carrello con barca", + "pack:nextfloor.a_aussenkueche:outdoor_kitchen": "Cucina da esterno", + "pack:nextfloor.a_aussenkueche:kamado": "Barbecue kamado", + "pack:nextfloor.a_aussenkueche:pizza_oven": "Forno per pizza", + "pack:nextfloor.a_aussenkueche:fire_pit": "Braciere", + "pack:nextfloor.a_aussenkueche:patio_heater": "Fungo riscaldante", + "pack:nextfloor.a_aussenkueche:outdoor_fridge": "Frigorifero da esterno", + "pack:nextfloor.a_aussenkueche:bar_counter": "Bancone bar", + "pack:nextfloor.a_aussenkueche:bar_stool_out": "Sgabello da esterno", + "pack:nextfloor.a_aussenkueche:hanging_chair": "Poltrona sospesa", + "pack:nextfloor.a_werkstatt2:workbench_wall": "Banco con pannello forato", + "pack:nextfloor.a_werkstatt2:drill_press": "Trapano a colonna", + "pack:nextfloor.a_werkstatt2:table_saw": "Sega circolare da banco", + "pack:nextfloor.a_werkstatt2:compressor": "Compressore", + "pack:nextfloor.a_werkstatt2:welder": "Saldatrice", + "pack:nextfloor.a_werkstatt2:heavy_shelf": "Scaffale per carichi pesanti", + "pack:nextfloor.a_werkstatt2:parts_cabinet": "Cassettiera minuteria", + "pack:nextfloor.a_werkstatt2:tool_chest": "Carrello porta utensili", + "pack:nextfloor.a_werkstatt2:ev_bike_charger": "Stazione ricarica batterie", + "pack:nextfloor.a_japandi:low_bed": "Letto basso", + "pack:nextfloor.a_japandi:tatami": "Tatami", + "pack:nextfloor.a_japandi:paper_lamp": "Lampada di carta", + "pack:nextfloor.a_japandi:paper_pendant": "Sospensione di carta", + "pack:nextfloor.a_japandi:tea_table": "Tavolino da tè", + "pack:nextfloor.a_japandi:shoji_screen": "Paravento shoji", + "pack:nextfloor.a_japandi:bonsai": "Bonsai", + "pack:nextfloor.a_japandi:floor_cushion": "Cuscino da pavimento", + "pack:nextfloor.a_japandi:wood_bench": "Panca in legno", + "pack:nextfloor.a_japandi:rattan_chair": "Poltrona in rattan", + "pack:nextfloor.a_loft:steel_shelf": "Libreria in acciaio", + "pack:nextfloor.a_loft:factory_pendant": "Sospensione industriale", + "pack:nextfloor.a_loft:leather_sofa": "Divano in pelle", + "pack:nextfloor.a_loft:plank_table": "Tavolo in tavole", + "pack:nextfloor.a_loft:locker": "Armadietto in metallo", + "pack:nextfloor.a_loft:edison_floor_lamp": "Lampada da terra Edison", + "pack:nextfloor.a_loft:bar_stool_loft": "Sgabello industriale", + "pack:nextfloor.a_loft:pipe_shelf": "Mensola a tubi", + "pack:nextfloor.a_gruen:monstera": "Monstera", + "pack:nextfloor.a_gruen:ficus": "Ficus", + "pack:nextfloor.a_gruen:olive_tree": "Ulivo in vaso", + "pack:nextfloor.a_gruen:cactus_group": "Cactus", + "pack:nextfloor.a_gruen:hanging_plant": "Pianta pendente", + "pack:nextfloor.a_gruen:plant_shelf": "Scaffale piante con luce", + "pack:nextfloor.a_gruen:vertical_garden": "Giardino verticale", + "pack:nextfloor.a_gruen:grow_light": "Lampada per piante", + "pack:nextfloor.a_gruen:herb_planter": "Orto di erbe smart", + "pack:nextfloor.a_musik:upright_piano": "Pianoforte verticale", + "pack:nextfloor.a_musik:grand_piano": "Pianoforte a coda", + "pack:nextfloor.a_musik:drum_kit": "Batteria", + "pack:nextfloor.a_musik:guitar_stand": "Chitarre su supporto", + "pack:nextfloor.a_musik:guitar_amp": "Amplificatore per chitarra", + "pack:nextfloor.a_musik:mixing_desk": "Scrivania da studio con mixer", + "pack:nextfloor.a_musik:studio_monitor": "Monitor da studio", + "pack:nextfloor.a_musik:synth": "Sintetizzatore", + "pack:nextfloor.a_musik:mic_stand": "Microfono con asta", + "pack:nextfloor.a_musik:easel": "Cavalletto", + "pack:nextfloor.a_musik:vinyl_player": "Giradischi", + "packname:nextfloor.a_bilder": "Quadri e cornici", + "pack:nextfloor.a_bilder:frame_landscape": "Cornice (orizzontale)", + "pack:nextfloor.a_bilder:frame_portrait": "Cornice (verticale)", + "pack:nextfloor.a_bilder:frame_square": "Cornice (quadrata)", + "pack:nextfloor.a_bilder:frame_large": "Cornice grande", + "pack:nextfloor.a_bilder:canvas": "Stampa su tela", + "pack:nextfloor.a_bilder:poster": "Poster", + "pack:nextfloor.a_bilder:frame_table": "Cornice da tavolo", + "pack:nextfloor.a_bilder:frame_digital": "Cornice digitale", + "pack:nextfloor.a_bilder:picture_ledge": "Mensola portaquadri", + "color:pearl_white": "Pearl White", + "color:solid_black": "Solid Black", + "color:midnight_silver": "Midnight Silver", + "color:quicksilver": "Quicksilver", + "color:deep_blue": "Deep Blue", + "color:ultra_red": "Ultra Red", + "color:midnight_cherry": "Midnight Cherry Red", + "pack:nextfloor.fahrzeuge:tesla_model_3": "Tesla Model 3", + "color:red": "Red Multi-Coat", + "color:stealth_grey": "Stealth Grey", + "pack:nextfloor.fahrzeuge:tesla_model_x": "Tesla Model X", + "pack:nextfloor.fahrzeuge:tesla_model_y": "Tesla Model Y", + "pack:nextfloor.fahrzeuge:tesla_cybertruck": "Tesla Cybertruck", + "color:stainless": "Stainless Steel", + "color:wrap_black": "Wrap Satin Black", + "color:wrap_white": "Wrap Satin White", + "color:wrap_grey": "Wrap Satin Grey", + "color:wrap_blue": "Wrap Satin Blue", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024": "Tesla Model 3 (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024_performance": "Tesla Model 3 Performance (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_s_plaid": "Tesla Model S Plaid", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025": "Tesla Model Y Standard (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_premium": "Tesla Model Y Premium (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_performance": "Tesla Model Y Performance (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_l": "Tesla Model Y L", + "pack:nextfloor.fahrzeuge:tesla_roadster": "Tesla Roadster", + "pack:nextfloor.fahrzeuge:tesla_semi": "Tesla Semi", + "pack:nextfloor.fahrzeuge:ev_suv": "SUV elettrico (taglia Model Y)", + "pack:nextfloor.fahrzeuge:small_car": "Utilitaria", + "pack:nextfloor.fahrzeuge:estate_car": "Station wagon", + "pack:nextfloor.fahrzeuge:van": "Furgone", + "pack:nextfloor.fahrzeuge:bicycle": "Bicicletta", + "pack:nextfloor.fahrzeuge:ebike": "E-bike", + "pack:nextfloor.fahrzeuge:motorbike": "Moto", + "pack:nextfloor.fahrzeuge:trailer": "Rimorchio", + "pack:nextfloor.fahrzeuge:sedan": "Berlina", + "pack:nextfloor.fahrzeuge:coupe": "Coupé sportiva", + "pack:nextfloor.fahrzeuge:convertible": "Cabriolet (aperta)", + "pack:nextfloor.fahrzeuge:small_ev": "Piccola elettrica", + "pack:nextfloor.fahrzeuge:suv": "SUV", + "pack:nextfloor.fahrzeuge:family_van": "Monovolume", + "pack:nextfloor.fahrzeuge:minibus": "Minibus", + "pack:nextfloor.fahrzeuge:panel_van": "Furgone chiuso", + "pack:nextfloor.fahrzeuge:pickup": "Pick-up", + "pack:nextfloor.fahrzeuge:campervan": "Camper van (tetto sollevabile)", + "pack:nextfloor.fahrzeuge:motorhome": "Autocaravan", + "pack:nextfloor.fahrzeuge:caravan": "Roulotte", + "packname:nextfloor.fitness": "Fitness (precedente)", + "pack:nextfloor.fitness:treadmill": "Tapis roulant", + "pack:nextfloor.fitness:bike_trainer": "Cyclette", + "pack:nextfloor.fitness:rower": "Vogatore", + "pack:nextfloor.fitness:weight_bench": "Panca pesi", + "pack:nextfloor.fitness:power_rack": "Power rack", + "pack:nextfloor.fitness:yoga_mat": "Tappetino yoga", + "pack:nextfloor.fitness:dumbbell_rack": "Rastrelliera manubri", + "packname:nextfloor.garten": "Giardino e terrazza (precedente)", + "pack:nextfloor.garten:sun_lounger": "Lettino", + "pack:nextfloor.garten:garden_table": "Tavolo da giardino", + "pack:nextfloor.garten:garden_chair": "Sedia da giardino", + "pack:nextfloor.garten:lounge_set": "Lounge da esterno", + "pack:nextfloor.garten:parasol": "Ombrellone", + "pack:nextfloor.garten:gas_grill": "Barbecue a gas", + "pack:nextfloor.garten:fire_bowl": "Braciere", + "pack:nextfloor.garten:pool": "Piscina", + "pack:nextfloor.garten:hot_tub": "Vasca idromassaggio", + "pack:nextfloor.garten:trampoline": "Trampolino", + "pack:nextfloor.garten:greenhouse": "Serra", + "pack:nextfloor.garten:raised_bed": "Orto rialzato", + "pack:nextfloor.garten:garden_shed": "Casetta da giardino", + "pack:nextfloor.garten:swing_bench": "Dondolo", + "pack:nextfloor.garten:mower_robot": "Robot tagliaerba", + "pack:nextfloor.garten:tree_oak": "Latifoglia", + "pack:nextfloor.garten:tree_birch": "Betulla", + "pack:nextfloor.garten:tree_fruit": "Albero da frutto", + "pack:nextfloor.garten:conifer": "Conifera", + "pack:nextfloor.garten:shrub": "Arbusto", + "pack:nextfloor.garten:shrub_flowering": "Arbusto fiorito", + "pack:nextfloor.garten:hedge": "Siepe", + "pack:nextfloor.garten:lawn_brush": "Sterpaglia", + "pack:nextfloor.garten:bike_rack": "Rastrelliera bici", + "pack:nextfloor.garten:bin_box": "Copribidoni (4 bidoni)", + "packname:nextfloor.ikea": "Misure IKEA", + "pack:nextfloor.ikea:billy": "Libreria 80x202 (misura Billy)", + "pack:nextfloor.ikea:billy_low": "Libreria 80x106 (misura Billy)", + "pack:nextfloor.ikea:kallax_2x2": "Scaffale a cubi 2x2 (misura Kallax)", + "pack:nextfloor.ikea:kallax_2x4": "Scaffale a cubi 2x4 (misura Kallax)", + "pack:nextfloor.ikea:kallax_4x4": "Scaffale a cubi 4x4 (misura Kallax)", + "pack:nextfloor.ikea:lack_side": "Tavolino 55x55 (misura Lack)", + "pack:nextfloor.ikea:lack_coffee": "Tavolino 90x55 (misura Lack)", + "pack:nextfloor.ikea:malm_bed_140": "Letto 140x200 (misura Malm)", + "pack:nextfloor.ikea:malm_bed_160": "Letto 160x200 (misura Malm)", + "pack:nextfloor.ikea:malm_chest_6": "Cassettiera a 6 cassetti (misura Malm)", + "pack:nextfloor.ikea:malm_chest_4": "Cassettiera a 4 cassetti (misura Malm)", + "pack:nextfloor.ikea:pax_100": "Armadio 100x236 (misura Pax)", + "pack:nextfloor.ikea:pax_150": "Armadio 150x236 (misura Pax)", + "pack:nextfloor.ikea:poang": "Poltrona (misura Poäng)", + "pack:nextfloor.ikea:ektorp_2": "Divano 2 posti (misura Ektorp)", + "pack:nextfloor.ikea:ektorp_3": "Divano 3 posti (misura Ektorp)", + "pack:nextfloor.ikea:bekant": "Scrivania 160x80 (misura Bekant)", + "pack:nextfloor.ikea:alex": "Cassettiera (misura Alex)", + "pack:nextfloor.ikea:besta_tv": "Mobile TV 180x42 (misura Bestå)", + "pack:nextfloor.ikea:ivar": "Scaffale in pino 89x179 (misura Ivar)", + "packname:nextfloor.kino": "Home cinema e gaming", + "pack:nextfloor.kino:projection_screen": "Schermo di proiezione", + "pack:nextfloor.kino:projector": "Proiettore", + "pack:nextfloor.kino:floor_speaker": "Diffusore da pavimento", + "pack:nextfloor.kino:subwoofer": "Subwoofer", + "pack:nextfloor.kino:soundbar": "Soundbar", + "pack:nextfloor.kino:gaming_desk": "Scrivania gaming", + "pack:nextfloor.kino:gaming_chair": "Sedia gaming", + "pack:nextfloor.kino:game_console": "Console di gioco", + "pack:nextfloor.kino:arcade": "Cabinato arcade", + "pack:nextfloor.kino:media_wall": "Parete media con TV", + "pack:nextfloor.kino:media_rack": "Mobile media", + "packname:nextfloor.kueche": "Cucina extra", + "pack:nextfloor.kueche:coffee_machine": "Macchina da caffè", + "pack:nextfloor.kueche:microwave": "Microonde", + "pack:nextfloor.kueche:hood_island": "Cappa a isola", + "pack:nextfloor.kueche:wine_fridge": "Cantinetta vini", + "pack:nextfloor.kueche:stand_mixer": "Impastatrice planetaria", + "pack:nextfloor.kueche:toaster": "Tostapane", + "pack:nextfloor.kueche:kettle": "Bollitore", + "pack:nextfloor.kueche:long_dining_table": "Tavolo da pranzo lungo", + "pack:nextfloor.kueche:bar_cart": "Carrello bar", + "pack:nextfloor.kueche:trash_station": "Raccolta differenziata", + "packname:nextfloor.schlafen": "Notte e bambini", + "pack:nextfloor.schlafen:boxspring": "Letto boxspring", + "pack:nextfloor.schlafen:baby_crib": "Lettino", + "pack:nextfloor.schlafen:changing_table": "Fasciatoio", + "pack:nextfloor.schlafen:vanity_table": "Toeletta", + "pack:nextfloor.schlafen:clothes_rail": "Appendiabiti a stender", + "pack:nextfloor.schlafen:loft_bed_desk": "Letto soppalco con scrivania", + "pack:nextfloor.schlafen:toy_box": "Baule dei giochi", + "packname:nextfloor.technik": "Ufficio e homelab", + "pack:nextfloor.technik:standing_desk": "Scrivania regolabile", + "pack:nextfloor.technik:server_rack": "Rack server (19 pollici)", + "pack:nextfloor.technik:nas": "NAS", + "pack:nextfloor.technik:printer_3d": "Stampante 3D", + "pack:nextfloor.technik:office_printer": "Stampante", + "pack:nextfloor.technik:router": "Router / access point", + "pack:nextfloor.technik:tower_pc": "PC tower", + "pack:nextfloor.technik:filing_cabinet": "Cassettiera su ruote", + "packname:nextfloor.treppen": "Scale e ringhiere", + "pack:nextfloor.treppen:stairs_straight": "Scala dritta", + "pack:nextfloor.treppen:stairs_l": "Scala a L con pianerottolo", + "pack:nextfloor.treppen:stairs_u": "Scala a U", + "pack:nextfloor.treppen:stairs_spiral": "Scala a chiocciola", + "pack:nextfloor.treppen:stairs_compact": "Scala salvaspazio", + "pack:nextfloor.treppen:landing": "Pianerottolo", + "pack:nextfloor.treppen:steps_outdoor": "Gradini esterni", + "pack:nextfloor.treppen:rail_metal": "Ringhiera in metallo", + "pack:nextfloor.treppen:rail_glass": "Ringhiera in vetro", + "pack:nextfloor.treppen:rail_wood": "Ringhiera in legno", + "pack:nextfloor.treppen:stairs_floating": "Scala a sbalzo", + "pack:nextfloor.treppen:stairs_u_winder": "Scala a U aperta con gradini a ventaglio", + "pack:nextfloor.treppen:rail_corner": "Ringhiera angolare", + "packname:nextfloor.werkstatt": "Garage e officina", + "pack:nextfloor.werkstatt:workbench": "Banco da lavoro", + "pack:nextfloor.werkstatt:tool_cabinet": "Armadio portautensili", + "pack:nextfloor.werkstatt:tool_chest": "Carrello portautensili", + "pack:nextfloor.werkstatt:shelf_rack": "Scaffale di stoccaggio", + "pack:nextfloor.werkstatt:tyre_stack": "Pila di pneumatici", + "pack:nextfloor.werkstatt:drill_press": "Trapano a colonna", + "pack:nextfloor.werkstatt:compressor": "Compressore", + "pack:nextfloor.werkstatt:bike_stand": "Cavalletto per bici", + "pack:nextfloor.werkstatt:paint_cabinet": "Armadio vernici", + "pack:nextfloor.werkstatt:tool_wall": "Pannello portautensili", + "pack:nextfloor.werkstatt:heavy_shelf": "Scaffale per carichi pesanti", + "pack:nextfloor.werkstatt:chest_freezer_garage": "Congelatore a pozzo", + "pack:nextfloor.werkstatt:tyre_rack": "Rastrelliera pneumatici", + "pack:nextfloor.werkstatt:lawn_mower": "Tosaerba", + "pack:nextfloor.werkstatt:bike_stand_2": "Supporto con 2 bici", + "pack:nextfloor.werkstatt:workshop_light": "Lampada da officina", + "pack:nextfloor.werkstatt:garage_opener": "Motore porta garage", + "pack:nextfloor.werkstatt:wallbox_holder": "Wallbox con supporto cavo", + "pack:nextfloor.werkstatt:wall_bike_holder": "Porta bici a parete (2)", + "pack:nextfloor.werkstatt:workshop_vacuum": "Aspiratore da officina", + "pack:nextfloor.werkstatt:workshop_cabinet": "Armadio da officina", + "pack:nextfloor.werkstatt:printer_enclosed": "Stampante 3D chiusa", + "packname:nextfloor.wohnen": "Soggiorno e animali", + "pack:nextfloor.wohnen:corner_sofa": "Divano angolare (a L)", + "pack:nextfloor.wohnen:bean_bag": "Pouf sacco", + "pack:nextfloor.wohnen:fireplace": "Camino", + "pack:nextfloor.wohnen:bookcase_wall": "Libreria a parete", + "pack:nextfloor.wohnen:piano": "Pianoforte verticale", + "pack:nextfloor.wohnen:aquarium": "Acquario", + "pack:nextfloor.wohnen:cat_tree": "Tiragraffi", + "pack:nextfloor.wohnen:dog_bed": "Cuccia per cani", + "pack:nextfloor.wohnen:hanging_chair": "Poltrona sospesa", + "pack:nextfloor.wohnen:display_cabinet": "Vetrina", + "pack:nextfloor.wohnen:high_table": "Tavolo da bar", + "pack:nextfloor.wohnen:floor_mirror": "Specchio da terra", + "furn_tap": "Tocco sull'elemento", + "furn_tap_default": "Come al solito", + "furn_tap_hint": "Un'azione propria come i pulsanti propri del menu a stella, ad es. un popup di browser_mod con la tua scheda.", + "furn_show_when": "Mostra solo finché …", + "furn_show_when_state": "… è nello stato (vuoto = acceso)", + "furn_show_when_invert": "Al contrario: mostra finché non lo è", + "furn_show_when_hint": "Decorazioni stagionali che ci sono solo a dicembre: un helper (input_boolean), un calendario o un sensore decide se l'oggetto appare in 3D. Separa più stati con virgole. L'editor lo mostra sempre.", + "picture_upload": "Carica una foto", + "picture_replace": "Carica un'altra foto", + "picture_stored": "È salvata una foto propria.", + "picture_url": "… o indirizzo dell'immagine", + "picture_entity": "… o l'immagine di un'entità", + "picture_border": "Passe-partout (%)", + "picture_fit": "Foto", + "picture_fit_cover": "riempie la cornice", + "picture_fit_contain": "visibile per intero", + "picture_hint": "La tua foto nella cornice, in 3D e sul tablet a parete. Le foto caricate vengono salvate ridotte con la planimetria; un'entità immagine (foto del giorno) o una telecamera mostra l'immagine attuale.", + "card_tap_in_room": "Attivare i dispositivi solo nella stanza aperta", + "card_tap_in_room_hint": "Nella vista della casa e del piano un tocco apre il piano o la stanza, anche su un dispositivo o sul suo simbolo. Nella stanza aperta attiva il dispositivo. Una pressione prolungata apre sempre il suo menu o i dettagli.", + "card_markers_outside": "Scegliere i simboli fuori dalla stanza aperta", + "card_markers_outside_hint": "Nella casa, sul piano e nelle altre stanze solo i tipi spuntati; nella stanza aperta tutti, come impostato sopra. \"Sempre\" e \"Mai\" del dispositivo hanno la precedenza.", + "marker_kind_light": "Luci", + "marker_kind_cover": "Tapparelle", + "marker_kind_climate": "Riscaldamento", + "marker_kind_media": "Media", + "marker_kind_switch": "Interruttori", + "marker_kind_fan": "Ventilatori", + "marker_kind_lock": "Serrature", + "marker_kind_binary": "Contatti e rilevatori", + "marker_kind_sensor": "Sensori", + "marker_kind_tap": "Mobili con un'azione", + "marker_kind_other": "Altro", + "floor_copy": "Duplica piano", + "floor_copy_hint": "La copia va in cima alla casa con tutte le stanze, pareti, porte e finestre. Stanze e piano perdono il collegamento a Home Assistant, i mobili le loro entità; i dispositivi energetici restano sul piano originale.", + "floor_copy_furniture": "Copia i mobili", + "floor_copy_devices": "Copia i segnaposto dei dispositivi", + "floor_copy_devices_hint": "La stessa entità compare allora su entrambi i piani.", + "floor_copy_outdoor": "Copia le aree esterne", + "floor_copy_make": "Crea la copia", + "floor_copy_name": "{name} (copia)", + "furn_to_floor": "Sposta al piano", + "furn_to_floor_hint": "Il mobile si sposta nello stesso punto del piano scelto.", + "arc": "Arco", + "arc_hint": "Curva la parete ad arco. Una stanza che condivide la parete si curva con lei, porte e finestre la seguono; Annulla toglie l'arco.", + "arc_bulge": "Curvatura (m)", + "arc_bulge_hint": "Quanto si incurva il centro della parete: positivo verso l'esterno, negativo verso la stanza.", + "arc_apply": "Curva", + "arc_too_wide": "Una porta o finestra in questa parete è troppo larga per questa curva. Rendi la curva più piatta o l'apertura più stretta.", + "time_of_day": "Ora del giorno", + "time_of_day_hint": "Mostra sole, luce, ombre e aspetto a un'altra ora di oggi. Tocca di nuovo per tornare ad adesso.", + "menu_open": "Menu aperto", + "menu_open_hint": "Il menu a stella con preferiti e pulsanti propri è aperto fin dall'inizio su questo dispositivo, più grande – per un tablet a parete che attiva soprattutto scene.", + "keep_camera": "Mantieni la vista", + "keep_camera_hint": "Cambiando piano la vista resta dallo stesso lato, alla stessa altezza e distanza invece di inquadrare il nuovo piano dal lato iniziale.", + "view_zoom": "Zoom", + "view_zoom_hint": "Quanto si avvicinano le viste inquadrate – sui tablet piccoli la casa appare più grande.", + "stair_shape": "Forma", + "stair_shape_straight": "Dritta", + "stair_shape_quarter": "Quarto di giro (gradini a ventaglio)", + "stair_shape_l": "A L con pianerottolo", + "stair_shape_half": "Mezzo giro (gradini a ventaglio)", + "stair_shape_u": "A U con pianerottolo", + "stair_shape_spiral": "A chiocciola", + "stair_turn": "Senso di rotazione (salendo)", + "stair_turn_left": "Verso sinistra", + "stair_turn_right": "Verso destra", + "stair_build": "Costruzione", + "stair_build_solid": "Massiccia (cemento)", + "stair_build_stringer": "Con cosciali", + "stair_build_mono": "Trave centrale", + "stair_build_cantilever": "A sbalzo (sospese)", + "stair_risers": "Alzate chiuse", + "stair_steps": "Alzate (numero)", + "stair_run_width": "Larghezza rampa (m)", + "stair_landing_after": "Gradini fino al pianerottolo", + "stair_landing_hint": "Il pianerottolo è a {h} cm dal pavimento; gli altri gradini vengono dopo.", + "stair_rail": "Ringhiera", + "stair_rail_none": "Nessuna", + "stair_rail_left": "Sinistra", + "stair_rail_right": "Destra", + "stair_rail_both": "Entrambi i lati", + "stair_down": "Scende", + "stair_down_hint": "La scala parte da questo piano e scende, per esempio in una cantina che non serve disegnare. Apre il pavimento di questo piano.", + "stair_measures": "{steps} alzate da {rise} cm · pedata {going} cm · passo {measure} cm", + "stair_uncomfortable": "scomoda (passo 59–65 cm, alzata al massimo 21 cm)", + "stair_up_note": "La scala inizia dal bordo anteriore segnato. Il pavimento sopra si apre solo dove sopra i gradini restano meno di 2,2 m di altezza libera.", + "stair_down_note": "Si sale sulla scala dal bordo anteriore segnato e si scende. La pianta la disegna tratteggiata; questo piano si apre sopra i gradini.", + "stair_upgrade": "Scegli la forma", + "stair_upgrade_hint": "La trasforma in una scala con forma (a ventaglio, L, U, chiocciola), costruzione, ringhiera e numero di gradini.", + "tool_stairs": "Scala", + "hint_stairs": "Trascina dove deve stare la scala – segue il lato lungo; poi imposta forma, verso e costruzione a destra", + "stair_opening": "Apertura del solaio", + "stair_opening_headroom": "In base all'altezza libera (solo dove serve)", + "stair_opening_full": "Sopra tutta la scala", + "stair_opening_none": "Nessuna (botola, vano chiuso)", + "stair_opening_hint": "Quanto la scala apre il pavimento che raggiunge: il piano di sopra, o il proprio se scende. In base all'altezza libera apre solo sopra i gradini con meno di 2,2 m.", + "stair_up_note_plain": "La scala inizia dal bordo anteriore segnato e sale verso il retro." +} diff --git a/custom_components/nextfloor/frontend/lang/nb.json b/custom_components/nextfloor/frontend/lang/nb.json new file mode 100644 index 0000000..5f9de0e --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/nb.json @@ -0,0 +1,153 @@ +{ + "accent": "Aksentfarge", + "accent_reset": "Tilbake til cyan", + "alert_alarm_by": "Alarm utløst av {cause}", + "all_floors": "Alle etasjer", + "all_off_done": "Alt slått av.", + "all_off_floor": "Alt slått av på {floor} ({n} enheter), angre i ti sekunder", + "all_off_n": "Alt av ({n})", + "all_off_undo": "Angre", + "announce_failed": "Kunngjøringen mislyktes: {error}", + "announce_on": "Kunngjøringer på denne skjermen er slått på", + "announce_placeholder": "Din egen melding …", + "announce_send": "Si det", + "announce_sent": "Sagt: \"{message}\"", + "back": "Tilbake", + "bars_fold": "Skjul bryterne", + "bars_unfold": "Brytere", + "battery_low_n": "Lavt batteri: {names}", + "brightness": "Lysstyrke", + "card_description": "Hjemmet ditt i 3D (neon).", + "card_floor_stack": "Etasjer under", + "card_room_buttons": "Romknapper", + "care_bin_days": "Om {n} dager", + "care_bin_today": "Hentes i dag", + "care_bin_tomorrow": "Hentes i morgen", + "care_time_left": "{time} igjen", + "central": "Sentralt: alle lys, persienner og favoritter", + "central_covers": "Persienner", + "central_favorites": "Favoritter", + "central_house": "Hele huset", + "central_lights": "Lys", + "central_sure": "Sikker?", + "clock": "Klokke", + "close": "Lukk", + "color": "Farge", + "color_temp": "Fargetemperatur", + "comfort_n": "Komfort {n}", + "confirm_switch": "Vil du virkelig bytte {name}?", + "cover_close": "Lukk", + "cover_my_go": "Til favorittposisjon ({p} %)", + "cover_open": "Åpne", + "cover_stop": "Stopp", + "cover_tilt": "Lameller", + "cover_tilt_close": "Lameller lukket", + "cover_tilt_open": "Lameller åpne", + "delete": "Slett", + "details": "Detaljer", + "draft_discard": "Forkast", + "draft_found": "Fant ulagrede endringer fra {time}.", + "draft_restore": "Gjenopprett og lagre", + "empty_lights_hint": "{n} lys på, ingen her på {min} min.", + "empty_lights_off": "Slå av lys", + "energy_battery": "Batteri", + "energy_consumption": "Forbruk", + "energy_rest": "Felles (rest)", + "energy_solar": "Sol", + "energy_tariff": "Tariff", + "ext_tab": "Utvidelser", + "find": "Søk", + "find_none": "Ingenting funnet", + "find_placeholder": "Hvor er …? Enhet eller rom", + "floor_layer": "Lag (kan vises og skjules)", + "floor_power_share": "{n} % av huset", + "floor_rooms": "{n} rom", + "floor_rooms_one": "1 rom", + "floors": "Etasjer", + "floors_apart": "Fra hverandre", + "floors_stacked": "Stablet", + "flows": "Strømflyt", + "fps_title": "Ytelsesvisning (bilder per sekund)", + "glass_walls": "Glassvegger", + "heat_none_found": "Ingen passende sensorer i rommenes områder.", + "heat_wifi": "Wi-Fi", + "heatmap": "Varmekart", + "holos": "Kort", + "keep_camera": "Behold kamera", + "load_error": "Innlasting mislyktes", + "loading": "Laster …", + "markers": "Markører", + "media_next": "Neste", + "media_previous": "Forrige", + "media_sources": "Kilder", + "media_volume": "Volum", + "menu_open": "Meny åpen", + "meter_unmetered": "{w} umålt", + "mood_carry": "Overfør til et annet rom", + "mood_new": "Stemning", + "mood_save": "Lagre stemning", + "mood_set": "Bruk denne stemningen", + "next": "Neste", + "no_building": "Ingen plantegning ennå.", + "open_editor": "Åpne redigering", + "open_heating_hint": "{n} vinduer er åpne mens varmen går.", + "open_heating_off": "Slå av varmen", + "open_since": "åpen i {time}", + "outside_area": "Utendørs", + "panel_all_close": "Alle ned", + "panel_all_off": "Alle av", + "panel_all_on": "Alle på", + "panel_all_open": "Alle opp", + "panel_less": "Vis mindre", + "panel_more": "Flere enheter i området ({n})", + "plain": "Bare plantegning", + "play_pause": "Spill av/pause", + "pool_pump_on": "pumpe på", + "position": "Posisjon", + "presence_last": "sist sett for {time} siden", + "presence_now": "noen er her", + "presets": "Stasjoner og spillelister (lyd)", + "previous": "Forrige", + "qm_off": "Av", + "readable": "Lettlest", + "reload_page": "Last på nytt", + "right_back": "Høyreklikk = tilbake", + "roof_keep": "Taket blir", + "room_clean_run": "Støvsug", + "room_clean_run_hint": "Sender robotstøvsugeren til dette rommet.", + "room_curve_hint": "Temperaturen i rommet de siste 24 timene", + "room_energy": "i dag {today} · måned {month}", + "room_sun_hours": "{h} t sol i dag ({facing})", + "room_sun_year": "Sol gjennom året", + "save_failed_detail": "Lagringen mislyktes: {error}. Endringene dine beholdes i denne nettleseren.", + "screen_name": "Navn på denne skjermen", + "shade_close": "Senk", + "shade_hint": "Sol på {n} vinduer ved {temp} – senke persiennene?", + "stats_idle": "I ro (0 fps)", + "stl": "3D-utskrift (STL)", + "swipe_off": "Av", + "target_temp": "Mål", + "temp_down": "Kjøligere", + "temp_up": "Varmere", + "time_of_day": "Tid på dagen", + "today": "I dag", + "today_none": "Ingenting i dag.", + "travel": "Tidsreise: spill av de siste 24 timene eller 7 dagene", + "travel_days": "dager", + "travel_failed": "Historikken kunne ikke lastes.", + "travel_live": "Live", + "travel_loading": "Laster historikk …", + "travel_speed": "Hastighet", + "view_options": "Visning: kvalitet, utseende, markører, FPS", + "view_zoom": "Zoom", + "volume": "Volum", + "wallbox_charging": "lader", + "wallbox_plugged": "tilkoblet", + "walls_auto": "Høye vegger", + "walls_cut": "Snitt", + "walls_slope": "Skrå", + "walls_solid": "Massive", + "wifi_aps": "{n} tilgangspunkter · {clients} enheter", + "wifi_clients": "{n} enheter", + "wifi_network": "Nettverk: {online} online · {offline} offline" +} diff --git a/custom_components/nextfloor/frontend/lang/nl.json b/custom_components/nextfloor/frontend/lang/nl.json new file mode 100644 index 0000000..2dd26e2 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/nl.json @@ -0,0 +1,2763 @@ +{ + "view": "3D", + "editor": "Editor", + "all_floors": "Alle verdiepingen", + "outside_area": "Buiten", + "outside_area_hint": "Alle apparaten buiten in één oogopslag: in de tuin, buiten de kamers, en wat bij Buiten hoort (bijvoorbeeld het weerstation op het dak).", + "device_outside": "Hoort bij Buiten", + "device_outside_hint": "Het apparaat telt niet mee voor de kamer eronder (een weerstation op het dak) en staat in het paneel Buiten.", + "no_building": "Nog geen plattegrond.", + "no_building_admin": "Nog geen plattegrond. Teken je eerste verdieping in de editor.", + "no_rooms_admin": "De verdiepingen bestaan, maar er is nog geen kamer. Alleen muren zijn niet genoeg: teken in de editor minstens één kamer met ‘Rechthoek’ of ‘Vrije vorm’.", + "open_editor": "Editor openen", + "loading": "Laden …", + "load_error": "Laden mislukt", + "saving": "Opslaan …", + "saved": "Opgeslagen", + "save_error": "Opslaan mislukt", + "save_failed_detail": "Opslaan mislukt: {error}. Je wijzigingen blijven in deze browser bewaard.", + "needs_restart": "Er is een nieuwe versie van NextFloor ({frontend}) geïnstalleerd, maar Home Assistant draait nog {version}. Herstart Home Assistant; tot dan kan opslaan mislukken.", + "needs_reload": "Deze pagina toont nog NextFloor {frontend}, Home Assistant heeft al {backend}. Herlaad de pagina; in de companion-app: Instellingen → Companion-app → Frontend-cache resetten.", + "reload_page": "Herladen", + "needs_restart_old": "Er is een nieuwe versie van NextFloor geïnstalleerd, maar Home Assistant draait nog een oudere. Herstart Home Assistant; tot dan mislukt opslaan.", + "draft_found": "Niet-opgeslagen wijzigingen van {time} gevonden.", + "draft_restore": "Herstellen en opslaan", + "draft_discard": "Verwerpen", + "walls_auto": "Hoge muren", + "walls_cut": "Doorsnede", + "walls_slope": "Schuin", + "walls_slope_hint": "Muren schuin afgesneden: voor halfhoog, achter volle hoogte, als een poppenhuis; draait mee met de camera", + "walls_solid": "Massief", + "walls_solid_hint": "Massieve muren in hun kleuren in plaats van glas (kleuren: editor → instellingen, per ruimte in de ruimte)", + "wall_paint_outside": "Muurkleur buiten", + "wall_paint_inside": "Muurkleur binnen", + "wall_paint_room": "Muurkleur binnen (deze ruimte)", + "wall_paint_hint": "Gebruikt in de 3D-weergave „Massief”.", + "wall_paint_default": "Standaard", + "card_solid_walls": "Massieve muren (in hun kleuren)", + "reset_view": "Overzicht", + "back": "Terug", + "floor": "Verdieping", + "floors": "Verdiepingen", + "add_floor": "Verdieping toevoegen", + "floor_from_ha": "Verdiepingen uit Home Assistant:", + "floor_empty": "Lege verdieping", + "level": "Niveau {n}", + "ha_floor": "Verdieping in Home Assistant", + "floor_layer": "Laag (in- en uit te schakelen)", + "floor_power": "Verdiepingsmeter (vermogen)", + "floor_power_hint": "Een vermogenssensor alleen voor deze verdieping (een tussenmeter, een appartement). De waarde staat op het verdiepingslabel en, in de weergave van deze verdieping, op de huiskaart met het aandeel in het verbruik van het huis.", + "floor_power_share": "{n} % van het huis", + "living_area": "Woonoppervlak {living}", + "room_living": "Telt mee als woonoppervlak", + "living_area_none": "Geen woonoppervlak · vloer {floor}", + "living_area_low": "Woonoppervlak {living} (vloer {floor}, waarvan {low} onder 2 m)", + "living_area_hint": "Berekend zoals de Duitse Wohnflächenverordnung: de vloer binnen de muren, volledig vanaf 2 m vrije hoogte, voor de helft tussen 1 en 2 m (onder schuine daken), niet onder 1 m. Een richtwaarde, geen opmeting.", + "living_area_floor": "Woonoppervlak: {floor}", + "living_area_floor_house": "Woonoppervlak van deze verdieping: {floor} · heel het huis: {house}", + "print_plan": "Plattegrond afdrukken / PDF", + "print_plan_hint": "Elke verdieping als nette plattegrond met maten en oppervlakken, plus een oppervlaktetabel – om af te drukken of via het afdrukvenster als pdf op te slaan.", + "print_title": "Plattegrond", + "print_room": "Kamer", + "print_floor_area": "Vloeroppervlak", + "print_living": "Woonoppervlak", + "print_low": "onder 2 m", + "print_total": "Totaal", + "print_blocked": "Het afdrukvenster is geblokkeerd – sta pop-ups toe voor Home Assistant.", + "check_open": "Plattegrond controleren", + "note": "Notitie", + "note_add": "Notitie hier", + "note_text": "Tekst", + "note_placeholder": "bv. ‘filter vervangen’ of ‘zekering 12’", + "note_due": "Vervalt op", + "note_due_hint": "Vanaf die dag wordt de pin oranje.", + "note_is_due": "Deze notitie is aan de beurt.", + "keys_title": "Toetsen in de editor", + "keys_undo": "Ongedaan maken", + "keys_redo": "Opnieuw", + "keys_duplicate": "Kamer dupliceren", + "keys_delete": "Selectie verwijderen", + "keys_nudge": "Selectie één rasterstap verschuiven", + "keys_nudge_10": "… 10 cm", + "keys_nudge_1": "… 1 cm", + "keys_rotate": "Meubel 90° draaien (Shift: terug)", + "keys_lock": "Meubel, apparaat of dakdeel vastzetten / losmaken", + "keys_close_shape": "Vrije vorm sluiten", + "keys_escape": "Annuleren, gereedschap verlaten, selectie opheffen", + "keys_straight": "Tijdens tekenen: rechte lijnen", + "keys_sheet": "Dit overzicht", + "tour_title": "Eerste stappen", + "tour_1_title": "Kamers tekenen", + "tour_1": "Teken de kamers met ‘{rect}’ of ‘{free}’; de muren ontstaan vanzelf. Geef elke kamer haar Home Assistant-ruimte – dan vindt NextFloor de apparaten. Heb je al ruimtes, dan maakt ‘{rooms}’ in het verdiepingsformulier ze in één keer aan.", + "tour_2_title": "Deuren en ramen", + "tour_2": "‘{opening}’ zet ze op een muur. Koppel hun contact of rolluik – in 3D gaan ze dan mee open en dicht, en open ramen melden zich.", + "tour_3_title": "Meubels en apparaten", + "tour_3": "‘{furniture}’ opent de bibliotheek – of bouw eigen stukken in de 🛠️ meubelwerkplaats. Kies een kamer en eronder staan de apparaten van haar ruimte klaar om te plaatsen; lampen schijnen dan in de kleur van hun licht.", + "tour_4_title": "Bekijken en controleren", + "tour_4": "‘{split}’ toont je huis terwijl je tekent; bovenaan wissel je naar de 3D-weergave. ‘{check}’ toont wat nog ontbreekt – en ? toont altijd de toetsen.", + "tour_next": "Volgende", + "tour_back": "Terug", + "tour_done": "Aan de slag", + "tour_skip": "Overslaan", + "check_open_hint": "Toont wat er ontbreekt of niet klopt in de plattegrond, met een oplossing in één tik.", + "check_title": "Plattegrondcontrole", + "check_all_good": "Alles in orde – niets gevonden.", + "check_hint": "{n} punten gevonden. Blauwe knoppen wijzigen de plattegrond (ongedaan maken werkt zoals altijd), de andere tonen de plek.", + "check_room_no_area": "‘{room}’ heeft geen Home Assistant-ruimte: de apparaten worden niet gevonden.", + "check_room_no_area_named": "‘{room}’ heeft geen ruimte – de vrije ruimte ‘{area}’ heet precies zo.", + "check_areas_unplaced": "{n} ruimtes van deze verdieping hebben nog geen kamer: {names}", + "check_devices_unplaced": "‘{room}’: {n} apparaten van de ruimte staan nog niet in de plattegrond.", + "check_rooms_overlap": "‘{a}’ en ‘{b}’ overlappen.", + "check_opening_off_wall": "Een deur of raam in ‘{room}’ zit niet in een muur.", + "check_entity_missing": "{n} apparaatpinnen wijzen naar entiteiten die Home Assistant niet meer kent ({ids}).", + "check_furniture_entity_missing": "Een meubel is gekoppeld aan {id} – die entiteit bestaat niet meer.", + "check_battery_low": "Batterij bijna leeg: {name} ({level} %)", + "battery_low_n": "Batterij bijna leeg: {names}", + "check_standby": "{name} verbruikt {w} W terwijl uit – ongeveer {cost} per jaar.", + "check_fix_show": "Tonen", + "check_fix_set_area": "‘{area}’ koppelen", + "check_fix_add_rooms": "Kamers toevoegen", + "check_fix_place": "{n} plaatsen", + "check_fix_remove": "{n} verwijderen", + "floor_layer_hint": "Deze verdieping is geen bouwlaag maar een laag – alle bomen of de decoratie. De 3D-weergave toont bovenaan een oog dat hem per apparaat toont of verbergt.", + "no_ha_floor": "– geen –", + "area_rooms": "Ruimtes toevoegen uit HA-gebieden ({n})", + "area_rooms_hint": "Voegt per gebied van deze verdieping een ruimte (4 × 3 m) toe; sleep die daarna op zijn plaats en pas de hoeken aan", + "floor_name": "Naam", + "elevation": "Hoogte (m)", + "floor_shift": "Verdieping verschuiven (m)", + "floor_shift_apply": "Verschuiven", + "floor_shift_hint": "Verschuift alle ruimtes, meubels, apparaten, buitengebieden, losse muren en de achtergrondafbeelding van deze verdieping over X en Z. Dakvlakken blijven staan.", + "height": "Plafondhoogte (m)", + "cut_height": "Snijhoogte (m)", + "delete_floor": "Verdieping verwijderen", + "delete_floor_confirm": "Verdieping „{name}” met al haar ruimtes verwijderen?", + "move_up": "Omhoog", + "move_down": "Omlaag", + "default_floor": "Begane grond", + "new_floor": "Verdieping {n}", + "tool_select": "Selecteren", + "tool_rect": "Rechthoek", + "tool_polygon": "Vrije vorm", + "undo": "Ongedaan maken", + "redo": "Opnieuw", + "fit": "Alles tonen", + "room": "Ruimte", + "rooms": "Ruimtes", + "room_name": "Naam", + "area": "Gebied", + "no_area": "Geen gebied", + "sub_area_add": "+ Gebied in de kamer", + "sub_area_hint": "Een deel van de kamer met een eigen Home Assistant-gebied maar zonder wanden – een leeshoek, een kast, een kitchenette in de woonkamer. De apparaten en sensoren horen bij deze kamer.", + "material": "Vloer", + "x": "X (m)", + "z": "Y (m)", + "width": "Breedte (m)", + "depth": "Diepte (m)", + "points": "Hoeken", + "delete_point": "Hoek verwijderen", + "duplicate": "Dupliceren", + "delete": "Verwijderen", + "new_room": "Ruimte {n}", + "settings": "Instellingen", + "pendant_shape": "Vorm", + "pendant_shade": "Kap", + "paint_colour": "Verfkleur", + "pendant_globe": "Bol", + "pendant_cone": "Kegel", + "pendant_drum": "Trommel", + "sofa_shape": "Vorm", + "sofa_straight": "Recht", + "sofa_l": "L-vorm (spiegelen: andere kant)", + "sofa_u": "U-vorm", + "pkg_open": "Inrichten …", + "pkg_hint": "Meubels komen tegen de muren van de ruimte; lampen worden gekoppeld aan de lampen van het gebied. Pas daarna losse items aan; Ctrl+Z draait alles terug.", + "pkg_done": "{n} items geplaatst; Ctrl+Z draait het terug.", + "pkg_kitchen_row": "Rechte keuken", + "pkg_kitchen_row_desc": "Rij aan de achterwand met koelkast, oven, spoelbak, vaatwasser en kookplaat, bovenkast, eettafel met hanglamp", + "pkg_kitchen_l": "L-keuken", + "pkg_kitchen_l_desc": "Rijen achter en links, kookeiland met barkrukken", + "pkg_bath": "Badkamer", + "pkg_bath_desc": "Wastafel, wc, bad, wasmachine, inbouwspot", + "pkg_bedroom": "Slaapkamer", + "pkg_bedroom_desc": "Tweepersoonsbed met twee nachtkastjes, kledingkast, ladekast, plafondlamp", + "pkg_living": "Woonkamer", + "pkg_living_desc": "Tv-meubel, bank, salontafel, vloerkleed, fauteuil, kast, vloerlamp, plant", + "pkg_dining": "Eetkamer", + "pkg_dining_desc": "Tafel met vier stoelen, dressoir, hanglamp", + "pkg_office": "Kantoor", + "pkg_office_desc": "Bureau met bureaustoel, twee kasten, plafondlamp", + "pkg_kids": "Kinderkamer", + "pkg_kids_desc": "Eenpersoonsbed, bureau, kast, vloerkleed", + "pkg_hall": "Hal", + "pkg_hall_desc": "Kapstok, twee inbouwspots", + "spots_place": "Spots plaatsen", + "spots_type": "Lamp", + "spots_cols": "Kolommen (links–rechts)", + "spots_rows": "Rijen (voor–achter)", + "spots_add": "{n} lampen plaatsen", + "spots_placed": "{n} lampen geplaatst.", + "spots_hint": "Alle lampen volgen de gekozen lamp (bijv. spots op één dimmer). Daarna kan elke lamp worden verplaatst en aan een andere lamp gekoppeld zoals elk meubel.", + "cancel": "Annuleren", + "backup": "Back-up", + "backup_history": "Herstelpunten", + "share_view": "Weergave delen", + "share_view_hint": "Slaat het huis op als klein bestand dat in elke browser opent zonder Home Assistant (via de online demo van NextFloor) – om het aan familie of een ontwerper te tonen. Zonder apparaten en entiteiten, als sjabloon.", + "share_view_title": "Ons huis in NextFloor", + "share_view_needs_js": "Deze pagina heeft JavaScript en een internetverbinding nodig.", + "share_view_file": "weergave", + "share_view_done": "Weergave opgeslagen – open het bestand in een browser of geef het door.", + "version_save": "Deze stand opslaan …", + "version_save_hint": "Bewaart de plattegrond onder een naam (‘voor de verbouwing’). Benoemde standen blijven als de automatische herstelpunten verdwijnen.", + "version_name_prompt": "Naam voor deze stand (bv. ‘voor de verbouwing’):", + "version_saved": "Stand ‘{name}’ opgeslagen.", + "version_compare": "Vergelijken", + "version_delete_confirm": "‘{name}’ verwijderen?", + "version_same": "Geen verschil met de plattegrond.", + "version_diff_n": "{n} verschillen met de plattegrond zoals hij nu is:", + "diff_floor_added": "Verdieping ‘{name}’ toegevoegd", + "diff_floor_removed": "Verdieping ‘{name}’ verwijderd", + "diff_room_added": "Kamer ‘{name}’ toegevoegd", + "diff_room_removed": "Kamer ‘{name}’ verwijderd", + "diff_room_renamed": "‘{detail}’ heet nu ‘{name}’", + "diff_room_reshaped": "‘{name}’ van vorm veranderd ({detail} m²)", + "diff_opening_added": "{name} toegevoegd ({detail})", + "diff_opening_removed": "{name} verwijderd ({detail})", + "diff_furniture_added": "{name} toegevoegd", + "diff_furniture_removed": "{name} verwijderd", + "diff_furniture_moved": "{name} verplaatst of gewijzigd", + "diff_device_added": "Apparaat {name} geplaatst", + "diff_device_removed": "Apparaat {name} verwijderd", + "diff_device_moved": "Apparaat {name} verplaatst", + "backup_none": "Nog geen. Tijdens het bewerken wordt hoogstens elke 10 minuten een herstelpunt bewaard.", + "backup_summary": "{rooms} ruimtes, {furniture} items", + "backup_restore": "Herstellen", + "backup_restore_confirm": "De stand van {time} herstellen? De huidige stand blijft bewaard als herstelpunt.", + "backup_restored": "Hersteld.", + "backup_file": "Bestand", + "backup_export": "Exporteren", + "backup_export_share": "Delen als sjabloon", + "backup_export_share_hint": "Zonder gebieden, apparaten, sensoren en afbeeldingen, om door te geven aan anderen.", + "backup_import": "Importeren …", + "backup_import_confirm": "De hele plattegrond vervangen door het bestand? De huidige stand blijft bewaard als herstelpunt.", + "backup_import_error": "Het bestand is geen NextFloor-plattegrond ({error}).", + "backup_imported": "Geïmporteerd.", + "backup_hint": "Achtergrondafbeeldingen maken geen deel uit van het bestand.", + "backup_full": "Volledige back-up", + "backup_full_export": "Alles opslaan (plattegrond, afbeeldingen, packs)", + "backup_full_import": "Een volledige back-up herstellen …", + "backup_full_hint": "Eén bestand met de plattegrond, alle achtergrond- en schermafbeeldingen en de geïnstalleerde packs. Bij herstellen wordt elk pack opnieuw gecontroleerd; de licentiesleutel zit er niet in.", + "backup_full_confirm": "Plattegrond, afbeeldingen en packs vervangen door de back-up? De huidige stand blijft als herstelpunt.", + "backup_full_not_backup": "Dit is geen volledige NextFloor-back-up.", + "backup_full_restored": "Back-up hersteld: {packs} packs, {pictures} afbeeldingen.", + "backup_full_skipped": "Overgeslagen (niet leesbaar): {packs}.", + "export_name_full": "volledig", + "device_confirm": "Vragen voor schakelen", + "device_confirm_hint": "Een tik in 3D, het snelmenu en het ruimtepaneel vragen eerst. Een dubbeltik op de ruimte sluit dit apparaat uit.", + "cover_confirm_hint": "Openen, sluiten en posities vragen eerst in het snelmenu en het ruimtepaneel, en vegen over de markering beweegt het rolluik niet meer (het draait de weergave). Stoppen vraagt nooit.", + "blind_kind": "Soort zonwering", + "blind_roller": "Rolluik buiten", + "blind_venetian": "Screens met lamellen (raffstore)", + "blind_inside": "Rolgordijn binnen", + "cover2_entity": "Tweede rolluik (rechterhelft)", + "cover_my": "Favoriete stand „My” (%, 0 = geen)", + "cover_my_go": "Naar de favoriete stand ({p} %)", + "blind_hint": "Een raffstore draait zijn lamellen in 3D mee met de kantelstand van het rolluik; een rolgordijn binnen hangt achter het glas. Een breed raam kan een tweede rolluik voor de rechterhelft hebben. De favoriete stand verschijnt als „My” in het snelmenu: een rolluik met standen gaat erheen, een Somfy RTS-motor zonder terugmelding gaat met Stop naar zijn eigen My.", + "confirm_switch": "{name} echt schakelen?", + "lock_confirm_unlock": "{name} echt ontgrendelen?", + "gang_switch_one": "Schakelaars", + "furn_cover_entity": "Beweegt mee met", + "furn_cover_hint": "Het gordijn, scherm, zonnescherm of de poort volgt deze cover-entiteit (rolluik, gordijn, zonnescherm, poort) en beweegt mee. Een tik opent het menu (omhoog, stop, omlaag).", + "furn_cover_inverted": "Looprichting omkeren", + "furn_cover_inverted_hint": "Voor een zonwering of gordijn die op het plan precies andersom beweegt: uitgerold toont ingerold en omgekeerd.", + "gang_switch": "Knop {n} schakelt", + "gang_socket_one": "Stopcontact gevoed door", + "gang_socket": "Stopcontact {n} gevoed door", + "gang_switch_hint": "Een knop gloeit zolang zijn lamp aan is (in haar kleur). Een tik schakelt hem; bij meerdere knoppen vraagt een klein menu welke. Dezelfde entiteit mag op meerdere schakelaars zitten.", + "gang_socket_hint": "Een stopcontact gloeit groen zolang zijn schakelaar aan is, feller naarmate het meer verbruikt. Een tik schakelt het; bij meerdere vraagt een klein menu welk.", + "lock_confirm_lock": "{name} vergrendelen?", + "opening_lock": "Slim slot", + "opening_lock_hint": "Een tik op de deur vergrendelt of ontgrendelt haar (altijd eerst vragend). Zolang ze ontgrendeld is, gloeit haar rand.", + "split_handle_hint": "Slepen: breedte van plattegrond en 3D-weergave", + "wall_exterior": "Buitenmuur (m)", + "wall_interior": "Binnenmuur (m)", + "grid": "Raster (m)", + "units": "Lengtes tonen in", + "units_metric": "Meters", + "units_imperial": "Voet en inch", + "units_hint": "Hoe lengtes en oppervlaktes verschijnen in de plattegrond, de formulieren en de muurweergave. Invoer blijft in meters.", + "background": "Sjabloon (afbeelding van plattegrond)", + "background_upload": "Afbeelding kiezen …", + "background_width": "Breedte in plattegrond (m)", + "background_opacity": "Dekking", + "background_rotation": "Rotatie (°)", + "background_edit": "Verplaatsen, schalen en draaien", + "background_edit_done": "Klaar", + "background_edit_hint": "Zolang de modus aan staat: slepen verplaatst de afbeelding, de greep rechtsonder schaalt haar. Breng de afbeelding eerst op schaal, draai haar dan.", + "background_remove": "Sjabloon verwijderen", + "hint_select": "Tik op een ruimte om te selecteren · sleep hoeken · „+” op een rand voegt een hoek in · pijltoetsen verschuiven · Del verwijdert · Ctrl+Z", + "hint_rect": "Sleep om een rechthoek te tekenen", + "hint_polygon": "Plaats hoeken · tik op de eerste hoek of druk op Enter om te sluiten · Esc annuleert", + "hint_empty": "Voeg eerst een verdieping toe.", + "area_m2": "{a} m²", + "overlap_warning": "Ruimtes overlappen; daar zijn de muren onvolledig.", + "read_only": "Alleen beheerders kunnen de plattegrond bewerken.", + "side_failed": "Dit formulier kon niet worden getoond ({error}). De plattegrond blijft bruikbaar. Meld de tekst graag in een GitHub-issue.", + "mat_wood": "Hout", + "mat_oak": "Eiken", + "mat_tiles": "Tegels", + "mat_carpet": "Vaste vloerbedekking", + "mat_stone": "Steen", + "mat_concrete": "Beton", + "card_name": "NextFloor", + "card_description": "Je huis in 3D (neon).", + "stats": "{calls} draw calls · {tris} driehoeken", + "stats_fps": "{fps} fps (traagste frame {ms} ms)", + "stats_idle": "In rust (0 fps)", + "stats_busy_floors": "verdiepingen", + "stats_busy_openings": "deuren/ramen", + "stats_busy_flash": "flits", + "stats_busy_roof": "dak", + "stats_busy_flow": "energiestroom", + "stats_busy_effect": "kleureffect", + "stats_busy_robot": "robot", + "stats_busy_orbit": "cameradraai", + "stats_busy_tint": "ruimtetint", + "stats_low": "tabletniveau, pixelverhouding {r}", + "stats_full": "volledig niveau, pixelverhouding {r}", + "floors_apart": "Uit elkaar", + "floors_stacked": "Gestapeld", + "roof_keep": "Dak blijft", + "roof_keep_hint": "Het dak blijft op het huis bij inzoomen in plaats van op te tillen en te vervagen", + "floor_rooms_one": "1 ruimte", + "floor_rooms": "{n} ruimtes", + "quality": "Kwaliteit", + "quality_auto": "Auto", + "quality_low": "Tablet", + "quality_high": "Hoog", + "state_on": "Aan", + "state_off": "Uit", + "state_open": "Open", + "state_closed": "Gesloten", + "state_opening": "Gaat open", + "state_closing": "Gaat dicht", + "state_playing": "Speelt", + "state_paused": "Gepauzeerd", + "state_idle": "Inactief", + "state_locked": "Vergrendeld", + "state_unlocked": "Ontgrendeld", + "state_detected": "Gedetecteerd", + "state_clear": "Vrij", + "state_unavailable": "Niet beschikbaar", + "state_heat": "Verwarmen", + "state_cool": "Koelen", + "state_auto": "Auto", + "state_heat_cool": "Verwarmen/koelen", + "state_dry": "Drogen", + "state_fan_only": "Ventilator", + "devices": "Apparaten", + "devices_none_area": "Koppel de ruimte aan een gebied en de apparaten ervan verschijnen hier.", + "devices_none": "Het gebied heeft geen geschikte apparaten.", + "devices_place_all_n": "Alle {n} plaatsen …", + "devices_place_all_confirm": "{n} apparaten in één keer in de ruimte zetten? (Ctrl+Z of „Ongedaan maken” haalt ze in één stap weg.)", + "devices_src_area": "Dit gebied", + "devices_src_other": "Andere gebieden", + "devices_src_none": "Geen gebied", + "panel_hide": "Verbergen in het ruimtepaneel", + "panel_unhide": "Weer tonen in het ruimtepaneel", + "panel_state_hide": "Status verbergen in het ruimtepaneel (bijv. een cover die alleen \"unknown\" meldt)", + "panel_state_show": "Status weer tonen in het ruimtepaneel", + "devices_place": "Plaatsen", + "devices_remove": "Verwijderen", + "devices_hint": "Geplaatste apparaten verschijnen in 3D. Sleep ze in de plattegrond om ze te verplaatsen.", + "panel_lights": "Lampen", + "panel_covers": "Covers", + "panel_climate": "Verwarming", + "panel_media": "Media", + "panel_switches": "Schakelaars", + "panel_sensors": "Sensoren", + "panel_scenes": "Scènes en scripts", + "panel_announce": "📢 Omroep", + "announce_placeholder": "Eigen bericht …", + "announce_send": "Zeggen", + "announce_sent": "Gezegd: ‘{message}’", + "announce_failed": "Omroep mislukt: {error}", + "announce_phrase_1": "Het eten is klaar!", + "announce_phrase_2": "Bedtijd!", + "announce_phrase_3": "Kom even naar beneden!", + "announce_phrase_4": "We gaan zo weg!", + "announce_phrase_5": "De hond moet uit!", + "state_recording": "Opnemen", + "state_streaming": "Streamen", + "panel_all_off": "Alles uit", + "readable": "Goed leesbaar", + "readable_hint": "Sterker contrast en grotere tekst – voor wandtablets en iedereen die zo beter leest.", + "plain": "Alleen plattegrond", + "plain_hint": "Toont alleen muren, deuren, ramen en trappen, zonder meubels. Apparaten en hun pins blijven.", + "right_back": "Rechtsklik = terug", + "right_back_hint": "Een korte rechtsklik in de 3D-weergave gaat een stap terug: van de kamer naar de verdieping, van de verdieping naar het huis (zoals een dubbele tik op lege ruimte). Slepen met de rechterknop verschuift de weergave nog steeds.", + "stl": "3D-print (STL)", + "stl_hint": "Slaat het huis op als STL-bestand (muren, vloeren, meubels en buitenruimtes van alle verdiepingen) voor 3D-printen, op schaal 1:100 (een meter wordt 10 mm). Ramen, licht en dak zitten er niet in; een slicer herstelt het bestand indien nodig.", + "card_plain": "Alleen plattegrond", + "card_rooms": "Alleen deze kamers", + "card_rooms_hint": "De kaart toont alleen de aangevinkte kamers met hun meubels, apparaten, deuren en ramen (bijvoorbeeld voor een tablet in de keuken). Niets aangevinkt: het hele plan.", + "card_templates": "Kaartsjablonen", + "card_templates_hint": "Stel hier één keer een dashboardkaart in (met de eigen instellingen van de kaart) en geef op elke tablet alleen de naam op: `template: kitchen_tablet`. Wijzigingen bereiken elke kaart met dit sjabloon; wat op de kaart zelf staat gaat voor het sjabloon.", + "template_name": "Nieuw sjabloon (naam)", + "template_add": "Sjabloon maken", + "template_reload": "Schermen met dit sjabloon herladen", + "template_reload_all": "Alle schermen herladen", + "template_use": "Op de dashboardkaart: `template: {name}`", + "card_template": "Kaartsjabloon", + "card_template_none": "geen (alleen deze kaart)", + "card_readable": "Goed leesbaar", + "all_off_n": "Alles uit ({n})", + "all_off_hint": "Zet lampen, schakelaars, ventilatoren en media van de kamer uit; tien seconden lang ongedaan te maken.", + "all_off_done": "Alles uit.", + "all_off_undo": "Ongedaan maken", + "all_off_floor": "Alles uit op {floor} ({n} apparaten), tien seconden ongedaan te maken", + "mood_save": "Sfeer opslaan", + "mood_save_hint": "Bewaart hoe de lampen van de kamer nu branden als sfeer – een tik zet ze later terug, „→” neemt hem mee naar een andere kamer.", + "mood_new": "Sfeer", + "mood_set": "Deze sfeer instellen", + "mood_carry": "Naar een andere kamer overnemen", + "panel_all_on": "Alles aan", + "view_options": "Weergave: kwaliteit, look, markeringen, FPS", + "panel_all_open": "Alles omhoog", + "panel_all_close": "Alles omlaag", + "central": "Centraal: alle lampen, rolluiken en favorieten", + "central_house": "Hele huis", + "central_lights": "Lampen", + "central_covers": "Rolluiken", + "central_on": "Aan", + "central_off": "Uit", + "central_open": "Omhoog", + "central_close": "Omlaag", + "central_sure": "Zeker?", + "central_favorites": "Favorieten", + "central_no_favorites": "Nog geen favorieten. Stel scènes, scripts en schakelaars in de editor in onder \"Favorieten\".", + "card_central": "Ster met het centrale menu", + "card_central_hint": "Alle lampen en rolluiken van de verdieping of het huis en de favorieten uit de editor.", + "favorites": "Favorieten", + "favorites_hint": "Scènes, scripts, automatiseringen, knoppen en schakelaars voor het centrale menu (ster) van de 3D-weergave: feest, aanwezigheidssimulatie, zonwering, besproeiing.", + "favorites_add": "Favoriet toevoegen", + "favorite_floor": "Op welke verdieping deze favoriet verschijnt", + "favorite_all_floors": "Alle verdiepingen", + "outside_hidden": "Buiten: apparaten verbergen", + "outside_hidden_hint": "Apparaten die het paneel Buiten niet moet tonen (ze blijven in het plan).", + "outside_hidden_add": "Apparaat verbergen", + "room_facts": "Kamerpaneel: getoonde gegevens", + "room_fact_sun": "Zonuren", + "room_fact_comfort": "Comfort", + "room_fact_air": "Ventilatietip", + "room_fact_circuits": "Groepen", + "background_handles_hint": "De afbeelding heeft nu grepen zoals een meubel: slepen verplaatst haar, de hoek rechtsonder schaalt haar, de ronde greep bovenaan draait haar (Shift voor stappen van 15°). Past het, tik dan op \"Klaar\"; daarna blijft ze staan.", + "background_fixed_hint": "De afbeelding blijft staan, je kunt erover tekenen. Om haar aan te passen, tik op \"Verplaatsen, schalen en draaien\".", + "bg_level": "Rechtzetten", + "bg_level_cancel": "Rechtzetten annuleren", + "bg_level_first": "Tik op het begin van een muur in de afbeelding die recht moet lopen (horizontaal of verticaal).", + "bg_level_second": "Tik nu op het eind van die muur; de afbeelding draait mee.", + "bg_ruler": "Schalen met een liniaal", + "bg_ruler_cancel": "Liniaal annuleren", + "bg_ruler_first": "Tik op het begin van een stuk met bekende lengte in de afbeelding, bijv. een gemaatvoerde muur.", + "bg_ruler_second": "Tik nu op het eind van het stuk.", + "bg_ruler_length_hint": "Gemeten in de plattegrond: {m} m. Vul de echte lengte in en de afbeelding wordt passend geschaald.", + "bg_ruler_length": "Echte lengte (m)", + "bg_ruler_apply": "Schaal toepassen", + "thumbs_fold": "Verdiepingsafbeeldingen tot knoppen inklappen", + "thumbs_show": "Verdiepingsafbeeldingen weer tonen", + "room_start_view": "Weergave als start van deze ruimte", + "room_start_view_hint": "Tik je de ruimte in 3D aan, dan vliegt de camera precies naar de weergave die het 3D-paneel rechts nu toont: hoek, zoom en uitsnede. Zet eerst 3D ernaast aan, draai en zoom in op de ruimte en tik dan.", + "room_start_view_reset": "Startweergave van de ruimte verwijderen (weer van boven)", + "room_start_view_need_pane": "Zet eerst \"3D ernaast\" aan en draai en zoom de ruimte zoals ze moet openen.", + "floor_start_view": "Weergave als start van deze verdieping", + "floor_start_view_hint": "Deze verdieping opent in 3D zoals het 3D-paneel rechts nu staat, bijv. de begane grond van voren en de bovenverdieping van achteren. Zet eerst 3D ernaast aan, draai het en tik dan.", + "floor_start_view_reset": "Startweergave van de verdieping verwijderen (weer zoals het huis)", + "floor_start_view_need_pane": "Zet eerst \"3D ernaast\" aan en draai de verdieping zoals ze moet openen.", + "ambilight": "Gloed achter de tv (%)", + "ambilight_hint": "Hoe sterk het achter de tv gloeit tijdens het afspelen. 0 schakelt het uit (bijvoorbeeld als je ledstrips op de tv hebt), 100 is de gewone sterkte.", + "sound_rings": "Geluidsringen (%)", + "sound_rings_hint": "Hoe groot de ringen rond de speaker worden zolang hij speelt. 0 zet ze uit, het beeld en de gloed blijven; 100 is de gewone grootte. De grootte volgt ook het volume van de speaker: zachter betekent kleiner.", + "glow_scale": "Gloed in 3D (%)", + "light_effects": "Effectanimaties in 3D", + "light_effects_hint": "Koppel alleen exacte effectnamen uit HA. Niet-gekoppelde effecten houden de statische HA-kleur. Verandert niets in Home Assistant.", + "light_effects_enabled": "Animaties voor deze lamp toestaan", + "light_effect_unmapped": "Niet gekoppeld (statisch)", + "light_effect_add": "Exacte effectnaam toevoegen", + "light_effect_name_limit": "De exacte effectnaam moet 1 tot 255 tekens hebben. Hij wordt niet ingekort.", + "light_effect_count_limit": "Hoogstens 100 koppelingen. Verwijder eerst een bestaande.", + "light_effect_exists": "Deze effectnaam is al gekoppeld. De bestaande koppeling blijft behouden.", + "light_animation_none": "Statisch", + "light_animation_rainbow": "Regenboog (vervangt de kleur)", + "light_animation_pulse": "Puls (intensiteit)", + "light_animation_flicker": "Flikkeren (intensiteit)", + "glow_scale_hint": "Hoe sterk de lamp in 3D gloeit: onder 100 % dempt felle ledstrips zodat de ruimte niet overstraalt; boven 100 % laat een zwakke lamp meer gloeien. Schakelt niets in Home Assistant.", + "vehicle_to_spot": "Omzetten in parkeerplaats", + "vehicle_to_spot_hint": "Een voertuig als gewoon meubel staat er altijd. Als parkeerplaats verschijnt het alleen zolang een sensor de auto meldt, en daar wordt het auto-apparaat gekoppeld (laden, bereik, slot, klimaat).", + "as_furniture": "Als meubel tonen", + "as_furniture_hint": "Vervangt de markering door een meubel op dezelfde plek, gekoppeld aan dit apparaat: een speaker voor een mediaspeler, een lamp voor een licht. Ctrl+Z draait het terug.", + "as_furniture_pick": "Meubel kiezen …", + "as_device": "Terug naar apparaatmarkering", + "as_device_hint": "Vervangt het meubel door de gewone markering van zijn apparaat op dezelfde plek.", + "presets": "Zenders en afspeellijsten (Geluid)", + "presets_hint": "Getoond in het snelmenu van elke speaker onder \"Afspelen\", naast de bronnen van de speler. Voor een Echo (Alexa Media Player): typ SPOTIFY, AMAZON_MUSIC of TUNEIN en als inhoud wat je zou zeggen (\"Rock Antenne\"). Voor Sonos, Music Assistant en andere: typ music of url met een streamadres of een URI.", + "preset_type": "Type", + "preset_type_hint": "media_content_type van play_media, bijv. music, url, playlist, SPOTIFY, AMAZON_MUSIC, TUNEIN", + "preset_content": "Inhoud", + "preset_content_hint": "media_content_id: stream-URL, URI (spotify:playlist:…) of, voor Alexa, een zoekzin", + "preset_speakers": "Alleen op deze speakers (geen = op alle)", + "media_play": "Afspelen", + "media_pause": "Pauze", + "media_previous": "Vorige", + "media_next": "Volgende", + "media_volume": "Volume", + "media_sources": "Bronnen", + "preset_add": "Zender of afspeellijst", + "own_buttons": "Eigen knoppen", + "own_buttons_hint": "Getoond in het centrale menu (ster) onder de favorieten: een dashboardpad openen, de details van een entiteit tonen, een service aanroepen of een browser_mod-popup met je eigen kaart openen.", + "own_alerts": "Eigen waarschuwingen", + "circuits": "Meterkast", + "circuits_hint": "De groepen met de kamers die eraan hangen. Het kamerpaneel noemt ze, en de zoekfunctie vindt ze (‘F12’).", + "circuit_name": "Naam", + "circuit_new": "Nieuwe groep", + "circuit_add": "Groep toevoegen", + "circuit_add_room": "Kamer toevoegen", + "own_alerts_hint": "Een regel in de waarschuwingsbalk van de 3D-weergave zolang een entiteit in een status is – „Watertank leeg” van de robot, „Vaatwasser klaar”. Meerdere statussen met komma's; voor getallen <20 of >80.", + "own_alert_entity": "Als …", + "own_alert_state": "… in de status is (leeg = aan)", + "own_alert_text": "… dan deze waarschuwing", + "own_alert_color": "Kleur", + "own_alert_tap": "Een tik", + "own_alert_tap_info": "opent de details", + "own_alert_tap_toggle": "schakelt de entiteit", + "own_alert_tap_room": "springt naar de kamer", + "own_alert_house": "Hele huis", + "own_alert_new": "Nieuwe waarschuwing", + "own_alert_add": "Waarschuwing toevoegen", + "today": "Vandaag", + "today_none": "Vandaag staat er niets gepland.", + "today_calendars": "Agenda's voor „Vandaag”", + "today_calendars_hint": "De afspraken van deze agenda's staan rechtsboven in de 3D-weergave op de kaart „Vandaag”, samen met de containers die vandaag of morgen worden geleegd. Een tik op de titel klapt de kaart in.", + "own_button_state": "Licht op zolang … aan is (optioneel)", + "own_button_label": "Label", + "own_button_action": "Actie", + "own_button_new": "Nieuwe knop", + "own_button_add": "Eigen knop", + "own_action_navigate": "Pad openen", + "own_action_more_info": "Entiteitdetails", + "own_action_service": "Service aanroepen", + "own_action_fire_dom_event": "fire-dom-event (browser_mod)", + "own_target_navigate": "Pad", + "own_target_more_info": "Entiteit", + "own_target_service": "Service (domein.service)", + "own_data": "Gegevens (JSON)", + "own_data_hint": "Voor een service de gegevens, voor fire-dom-event de inhoud van het event, bijv. {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}.", + "own_data_bad": "Geen geldig JSON-object.", + "panel_no_area": "Deze ruimte is niet aan een gebied gekoppeld. Je kunt haar in de editor koppelen.", + "panel_empty": "Geen apparaten van deze ruimte staan in de plattegrond. Plaats in de editor apparaten of kies ze voor het ruimtepaneel met ☆.", + "close": "Sluiten", + "panel_fold": "Inklappen (de ruimte blijft in beeld)", + "panel_unfold": "Weer openen", + "brightness": "Helderheid", + "color_temp": "Kleurtemperatuur", + "color": "Kleur", + "position": "Positie", + "cover_open": "Openen", + "cover_stop": "Stop", + "cover_tilt": "Lamellen", + "cover_tilt_open": "Lamellen open", + "cover_tilt_close": "Lamellen dicht", + "cover_close": "Sluiten", + "target_temp": "Doel", + "current_temp": "Huidig", + "temp_down": "Koeler", + "temp_up": "Warmer", + "volume": "Volume", + "play_pause": "Afspelen/pauze", + "previous": "Vorige", + "next": "Volgende", + "run": "Uitvoeren", + "details": "Details", + "hold_hint": "Tikken schakelt · lang drukken opent details", + "tool_opening": "Deuren en ramen", + "tool_furniture": "Meubels", + "qm_off": "Uit", + "find": "Zoeken", + "find_placeholder": "Waar is …? Apparaat of ruimte", + "find_none": "Niets gevonden", + "swipe_off": "Uit", + "panel_pin": "Tonen in het ruimtepaneel", + "panel_unpin": "Niet tonen in het ruimtepaneel", + "devices_panel_hint": "Het ruimtepaneel toont de apparaten in de plattegrond. ☆ voegt een apparaat toe aan het ruimtepaneel zonder het te plaatsen.", + "card_section_view": "Weergave", + "card_size": "Grootte", + "card_size_fixed": "Vaste hoogte", + "card_size_fill": "Scherm vullen", + "card_fill_hint": "Werkt het best in een dashboardweergave van het type „Paneel (enkele kaart)”; de kaart neemt dan alle ruimte.", + "card_controls": "Schakelaars in de kaart", + "card_floor_thumbs": "Verdiepingen als miniaturen", + "card_floor_thumbs_hint": "Kleine afbeeldingen van de verdiepingen aan de zijkant; tik er een aan om te wisselen", + "card_floor_thumbs_hint_start": "De gekozen verdieping is dan waar de kaart start; de afbeeldingen aan de zijkant wisselen naar de andere", + "card_room_names": "Ruimtenamen tonen", + "card_section_kiosk": "Wandtablet (kiosk)", + "card_section_features": "Functies", + "card_weather_plan": "zoals ingesteld in de plattegrond", + "card_pro_hint": "Bewegingsspoor en camerawand horen bij de camera's: het spoor toont het laatste halfuur, de wand alle camera's van de plattegrond.", + "card_idle_return": "Terug naar de startweergave na", + "card_idle_off": "Nooit", + "card_idle_min": "{n} min zonder aanraking", + "card_idle_hint": "Na het wachten sluit de kaart de ruimte en toont weer de startweergave.", + "card_night": "Nachtdimming", + "card_night_off": "Uit", + "card_night_sun": "Volgens de zon", + "card_night_time": "Tijdvak", + "card_night_range": "Tijdvak (bijv. 22:00-06:00)", + "card_idle_orbit": "Cameradraai als schermbeveiliging", + "card_idle_orbit_hint": "Na de terugkeer draait de weergave langzaam tot iemand de tablet aanraakt", + "card_dashboard": "Knop naar een dashboard (pad)", + "card_dashboard_label": "Label van de knop", + "card_dashboard_hint": "Een knop rechtsboven op de kaart opent het dashboard of de weergave met dit pad, bijv. /lovelace/home of /dashboard-house/0. Zonder label toont hij ⌂.", + "card_alerts": "Waarschuwingen tonen", + "card_alerts_hint": "Rook, gas, CO, water, alarmsysteem en ramen open bij regen: de ruimte pulseert, bovenaan verschijnt een melding", + "card_alert_jump": "Naar de ruimte van een nieuwe waarschuwing springen", + "card_alert_jump_hint": "De weergave wisselt zelf naar de verdieping en ruimte van de waarschuwing", + "card_scenes": "Scèneknoppen in de ruimte", + "card_scenes_hint": "Scènes en scripts van het gebied als knoppen onder de 3D-weergave zolang een ruimte geselecteerd is", + "card_sensor_bar": "Eigen sensoren bovenaan", + "card_sensor_bar_hint": "De sensoren gekozen in de editor (Instellingen) linksboven op de kaart", + "card_central_open": "Stermenu open en groot", + "card_central_open_hint": "Favorieten en eigen knoppen staan meteen open, een maat groter", + "card_keep_camera": "Camera behouden bij wisselen van verdieping", + "card_keep_camera_hint": "Dezelfde kant, hoogte en afstand op elke verdieping", + "card_today": "Kaart „Vandaag”", + "card_today_hint": "Afspraken van vandaag en containers die aan de beurt zijn, rechtsboven", + "card_announcements": "Omroepen", + "card_announcements_hint": "Omroepen (actie ‘NextFloor: Omroep’) verschijnen groot op de kaart, met een gong, en worden uitgesproken", + "weather_short": "Weer", + "weather_entity": "Weer-entiteit", + "weather_effects": "Weereffecten in 3D", + "card_weather_density": "Hoeveelheid regen en sneeuw", + "card_weather_density_hint": "Minder druppels en vlokken dan het weer meldt; wolken, mist en bliksem blijven", + "rain_warning": "Waarschuwing: raam open terwijl het regent", + "sun_patches": "Zon en schaduwen", + "sun_patches_hint": "Met het noorden ingesteld valt het zonlicht van sun.sun als lichte vlekken door de ramen op de vloer, en werpt het huis zijn schaduw op het perceel. Vink uit om vloer en perceel zonder zonnevlekken en schaduwen te laten.", + "sun_arc": "Zonneboog en kompas", + "sun_arc_hint": "Tekent de baan van de zon van vandaag als boog over het perceel, met een ring en de windstreken op de grond (noord in rood). Heeft de locatie van je huis in Home Assistant nodig.", + "weather_effect_rain": "Regen", + "weather_effect_snow": "Sneeuw", + "weather_effect_fog": "Mist (maakt de scène grijs)", + "weather_effect_clouds": "Wolken dimmen de lucht en de zon", + "weather_effect_lightning": "Bliksem bij onweer", + "weather_effect_sky": "Zon en maan aan de hemel", + "weather_entity_hint": "Welke weer-entiteit de lucht rond het huis aanstuurt. Automatisch gebruikt de eerst gevonden.", + "weather_hint": "Weer bij het huis: regen en sneeuw vallen met de echte wind, wolken drijven met hun schaduwen over het perceel, bliksem, mist, zon en maan", + "card_weather": "Weer buiten", + "card_weather_hint": "Regen, sneeuw, hagel, wolken met schaduwen, bliksem en mist van de eerste weer-entiteit (weather_entity kiest een andere); minder deeltjes op tabletniveau", + "alerts": "Waarschuwingen", + "alert_smoke": "Rook: {name}", + "alert_gas": "Gas: {name}", + "alert_co": "Koolmonoxide: {name}", + "alert_water": "Water: {name}", + "alert_alarm": "Alarm afgegaan", + "alert_alarm_by": "Alarm afgegaan door {cause}", + "alert_alarm_pending": "Alarm in afwachting", + "alert_window_rain": "Raam open bij regen: {name}", + "alert_power_outage": "Stroomstoring: {name}", + "alert_contact_lost": "Contact reageert niet: {name}", + "rain_sensor": "Regensensor (eigen weerstation)", + "outage_sensor": "Stroomstoringsensor", + "outage_hint": "Een binaire sensor van klasse power die uit is, een andere binaire sensor die aan is, een status als \"off_grid\" of \"backup\", of een spanning onder 50 V geven een waarschuwing voor het hele huis.", + "contact_warning": "Waarschuwen als een deur- of raamcontact onbereikbaar is", + "contact_warning_hint": "Is een contact 10 minuten onbeschikbaar (lege batterij, buiten bereik), dan lijkt het raam in 3D dicht terwijl niemand het weet. Een melding noemt dan het contact. Een herstart van Home Assistant waarschuwt niet.", + "night_lock_warning": "'s Nachts waarschuwen als een deur niet op slot is", + "night_lock_warning_hint": "Tussen 22 en 6 uur noemt een melding de deursloten van de plattegrond die open staan.", + "alert_unlocked_night": "Niet op slot: {name}", + "motion_markers_active": "Bewegingssensoren alleen tonen als ze iets detecteren", + "motion_markers_active_hint": "Geldt voor bewegings-, bezettings- en aanwezigheidssensoren. Een sensor waarvan het symbool altijd getoond wordt, blijft zichtbaar.", + "room_double_tap": "Dubbeltik op een ruimte", + "room_double_tap_hint": "Een dubbeltik op een ruimte zet de lampen uit als er één aan is, anders allemaal aan. Apparaten die eerst vragen blijven altijd buiten beschouwing.", + "room_double_tap_area": "Lampen in het plan en alle lampen van het gebied", + "room_double_tap_plan": "Alleen lampen in het plan", + "room_double_tap_off": "Niets schakelen", + "card_room_double_tap_auto": "Zoals ingesteld in het plan", + "status_entities": "Eigen sensoren bovenaan in de 3D-weergave", + "status_add": "Sensor toevoegen", + "status_entities_hint": "Bijvoorbeeld buitentemperatuur, alarm of luchtkwaliteit: ze staan linksboven met naam en waarde, ook in een geopende kamer. Tikken opent de details. Tot 12.", + "announce_tts": "Tekst-naar-spraak voor omroepen", + "announce_phrases": "Zinnen voor omroepen (één per regel)", + "announce_phrases_hint": "Leeg: de meegeleverde zinnen. Omroepen bestaan ook als actie ‘NextFloor: Omroep’ voor automatiseringen – op de luidsprekers van de kamers en op elk open NextFloor-scherm.", + "opening_rain_warning": "Waarschuwen als het regent", + "opening_light_well": "Lichtschacht ervoor", + "sill_boards": "Vensterbank en plank", + "sill_boards_auto": "Automatisch", + "sill_boards_none": "Geen", + "sill_boards_inside": "Alleen binnen", + "sill_boards_outside": "Alleen buiten", + "room_names_short": "Ruimtenamen", + "floor_stack_short_dim": "Gedimd", + "floor_stack_short_stacked": "Gestapeld", + "floor_stack_short_single": "Alleen", + "size_short_w": "B", + "size_short_d": "D", + "size_short_h": "H", + "import_error_not_json": "Het bestand is geen JSON.", + "import_error_not_plan": "Het bestand is geen NextFloor-plattegrond.", + "import_other_hint": "Vanuit Sweet Home 3D: importeer hier het .sh3d-bestand. Verdiepingen, ruimtes, deuren, ramen en losse muren komen mee, meubels niet.", + "import_sh3d_found": "Sweet Home 3D: {floors} verdiepingen, {rooms} ruimtes, {openings} deuren en ramen, {walls} losse muren ({furniture} meubels worden niet overgenomen).", + "import_dxf_found": "DXF: {rooms} kamers (gesloten polylijnen) en {walls} vrije wanden (lijnen) op één verdieping.", + "import_ifc_found": "In het IFC-bestand: {floors} verdiepingen en {rooms} kamers (NextFloor tekent de muren uit de kamers).", + "import_roomplan_found": "Ruimtescan (RoomPlan): {rooms} kamers, {openings} deuren en ramen; {skipped} objecten zijn niet overgenomen (meubels plaats je zelf).", + "import_error_roomplan_empty": "De ruimtescan bevat geen muren.", + "import_error_ifc_empty": "Het IFC-bestand bevat geen ruimtes (IfcSpace) met een plattegrond.", + "import_error_dxf_empty": "Het DXF-bestand bevat geen lijnen of polylijnen.", + "import_error_sh3d": "Dit is geen leesbaar Sweet Home 3D-bestand (Sweet Home 3D 5.3 of nieuwer nodig).", + "import_error_sh3d_empty": "Het Sweet Home 3D-bestand heeft geen ruimtes of muren.", + "export_name_template": "sjabloon", + "export_name_backup": "back-up", + "card_floor_stack": "Verdiepingen eronder", + "floor_stack_dim": "Gedimd", + "floor_stack_stacked": "Gestapeld (het huis tot hier)", + "floor_stack_single": "Verborgen (alleen deze verdieping)", + "card_control_walls": "Hoge muren/doorsnede", + "card_control_floors": "Verdiepingen uit elkaar", + "card_control_temperature": "Temperatuur", + "card_control_humidity": "Luchtvochtigheid", + "card_control_co2": "CO₂", + "card_controls_hint": "Hoge muren/doorsnede, verdiepingen uit elkaar en temperatuur, luchtvochtigheid, CO₂ om te schakelen", + "controls_hide": "Bedieningen verbergen; alleen de 3D-weergave blijft", + "nav_wrap": "Balk afbreken: alle verdiepingen en ruimtes op meerdere regels", + "bars_fold": "Schakelaars inklappen", + "bars_unfold": "Schakelaars", + "nav_row": "Balk op één regel (scrolt zijwaarts)", + "controls_show": "Bedieningen weer tonen", + "card_controls_hidden": "Starten met verborgen bedieningen", + "card_controls_hidden_hint": "Alleen de 3D-weergave; een oog linksonder brengt balken, waarden en schakelaars terug", + "card_controls_hide_after": "Bedieningen verbergen na", + "card_hide_after_s": "{n} s zonder aanraking", + "card_fullscreen_button": "Volledig-schermknop", + "card_fullscreen_button_hint": "Verbergt het dashboard rond de kaart (bijv. op een wandtablet)", + "fullscreen": "Volledig scherm", + "fullscreen_exit": "Volledig scherm sluiten", + "card_section_show": "Tonen", + "card_floor": "Verdieping", + "card_floor_house": "Hele huis (tik op een verdieping om haar te openen)", + "card_height": "Hoogte (pixels)", + "card_walls": "Muren", + "card_quality_hint": "„Tablet” is de lichtste instelling, ideaal voor Fire-tablets en andere wandtablets.", + "card_flows_switch": "Schakelaar in de kaart", + "card_flows_on": "Altijd aan", + "card_flows_off": "Altijd uit", + "holos": "Kaarten", + "holos_hint": "Livekaarten boven het huis tonen of verbergen (energiebalans, auto, media)", + "card_energy": "Energiewaarden bovenaan tonen", + "card_room_panel": "Ruimtedetails bij tikken", + "card_room_buttons": "Ruimteknoppen", + "card_room_buttons_hint": "Een rij met één knop per ruimte bovenaan de kaart; tik erop om de ruimte te openen, net als in het model", + "card_room_panel_hint": "De lampen en rolluiken van de ruimte in een zijpaneel", + "card_explode": "Verdiepingen uit elkaar trekken in de huisweergave", + "card_roof_fade": "Dak laten vervagen bij inzoomen", + "card_roof_fade_hint": "Uit: het dak blijft op het huis, ook als de camera dichtbij komt.", + "card_stats": "Prestatieweergave (frames per seconde)", + "card_stats_hint": "Om te zien hoe soepel de kaart op het apparaat draait", + "packs": "Meubelpacks", + "lib_badge_light": "Lamp: koppelt aan een licht en schakelt in 3D", + "lib_badge_electric": "Elektrisch: koppelt aan een entiteit en een vermogenssensor (schakelen, afbeeldingen, verbruik)", + "lib_badge_hint": "Items met een symbool koppelen aan entiteiten: lampen schakelen, schermen tonen beelden, apparaten tonen hun verbruik.", + "care_bin_today": "Vandaag opgehaald", + "care_bin_tomorrow": "Morgen opgehaald", + "care_bin_days": "Over {n} dagen", + "care_mail_yes": "Er is post", + "care_mail_no": "Leeg", + "care_plant_thirsty": "Dorstig", + "care_plant_ok": "Goed bewaterd", + "care_time_left": "Nog {time}", + "care_entity_bin": "Ophaaldatum (sensor)", + "care_entity_mail": "Postsensor", + "care_entity_plant": "Bodemvocht (sensor)", + "care_thirsty_below": "Dorstig onder (%)", + "care_hint_bin": "Een sensor met de volgende ophaling: dagen, een datum, \"vandaag\"/\"morgen\" of de integratie Waste Collection Schedule. De container gloeit de dag ervoor en op de dag zelf.", + "care_hint_mail": "Een sensor die post in de bus meldt (bijv. een contact op de klep). De brievenbus gloeit dan.", + "care_hint_plant": "Een vochtsensor in de grond. Onder de drempel gloeit de plant en zegt ze dat ze dorst heeft.", + "lib_cat_lights": "Lampen", + "lib_cat_seating": "Zitten", + "lib_cat_tables": "Tafels", + "lib_cat_storage": "Kasten en rekken", + "lib_cat_beds": "Bedden", + "lib_cat_kitchen": "Keuken", + "lib_cat_appliances": "Apparaten", + "lib_cat_bath": "Badkamer", + "lib_cat_media": "Tv en audio", + "lib_cat_office": "Kantoor", + "lib_cat_tech": "Techniek", + "lib_cat_climate": "Verwarming en klimaat", + "lib_cat_energy": "Energie", + "lib_cat_garden": "Tuin en terras", + "lib_cat_plants": "Planten", + "lib_cat_kids": "Kinderen", + "lib_cat_fitness": "Fitness", + "lib_cat_pets": "Huisdieren", + "lib_cat_workshop": "Werkplaats en garage", + "lib_cat_music": "Muziek & atelier", + "lib_cat_season": "Seizoen & decoratie", + "lib_cat_pictures": "Foto's & lijsten", + "lib_cat_vehicles": "Voertuigen", + "lib_cat_building": "Trappen en bouwdelen", + "lib_cat_decor": "Decoratie en meer", + "lib_favourites": "Favorieten", + "lib_recent": "Recent gebruikt", + "lib_for_room": "Past in {room}", + "lib_all_rooms": "Alle ruimtes tonen", + "lib_linkable": "koppelbaar", + "lib_lit": "verlicht", + "lib_outdoor": "buiten", + "lib_fav_add": "Aan favorieten toevoegen", + "lib_fav_remove": "Uit favorieten verwijderen", + "lib_sizes": "Maten", + "feature_name_energy": "Energiestroom", + "ext_tab": "Uitbreidingen", + "ext_title": "Uitbreidingen", + "models": "Je eigen 3D-modellen", + "models_hint": "Voor sommige voertuigen kan NextFloor een echt 3D-model tonen als je er een hebt. Kies hier het bestand (.glb): NextFloor draait het goed, maakt het lichter, markeert de lak en bewaart het op je Home Assistant. Zonder model ziet het voertuig eruit als voorheen.", + "models_licence": "De bestanden zijn van jou en blijven op je Home Assistant. NextFloor levert geen modellen; zorg dat de licentie van je model gebruik in je eigen installatie toestaat.", + "model_add": "Model toevoegen …", + "model_replace": "Model vervangen …", + "model_remove": "Verwijderen", + "model_present": "in gebruik", + "model_missing": "nog geen", + "model_remove_confirm": "Model „{id}” uit Home Assistant verwijderen?", + "model_removed": "Model „{id}” verwijderd.", + "model_uploaded": "Model „{id}” opgeslagen ({size}). Herlaad het paneel om het te zien.", + "model_upload": "Opslaan op Home Assistant", + "model_info": "{triangles} driehoeken, {size} m", + "model_front": "Voorkant", + "model_front_hint": "Draai het model tot de voorkant naar de kijker wijst (naar linksonder in de afbeelding).", + "model_paint": "Lak (de kleur die je in de editor kiest)", + "model_paint_preview": "Kleur in de voorvertoning", + "model_detail": "Detailniveau", + "model_detail_light": "Licht (tablet)", + "model_detail_normal": "Normaal", + "model_detail_fine": "Fijn", + "model_result": "Resultaat: {triangles} driehoeken, {size}", + "model_error_not_glb": "Dit is geen .glb-bestand (binaire glTF). Exporteer het model als „glTF binary”.", + "model_error_compressed": "Het bestand is gecomprimeerd (Draco, Meshopt of KTX). Exporteer het zonder compressie.", + "model_error_empty": "Het bestand bevat niets driedimensionaals.", + "model_error_unreadable": "Het bestand kan niet worden gelezen: {detail}", + "model_error_too_large": "Het bestand is groter dan {max}. Kies een lager detailniveau.", + "model_upload_forbidden": "Alleen beheerders mogen modellen uploaden.", + "model_upload_too_large": "Home Assistant accepteert geen bestanden boven {max}. Kies een lager detailniveau.", + "model_upload_not_glb": "Home Assistant weigerde het bestand (geen binaire glTF).", + "model_upload_bad_id": "De model-id is niet geldig.", + "model_upload_other": "Uploaden is niet gelukt: {detail}", + "ext_intro": "Importeer hier je eigen meubelpacks, upload je eigen 3D-modellen en voeg plug-ins toe.", + "plugin": "plug-in", + "plugins_title": "Plug-ins", + "plugins_intro": "Plug-ins voegen eigen lichtanimaties, apparaten en kaarten in het ruimtepaneel toe. Vul het adres van een plug-in in (een .js-bestand in /config/www, dus /local/…, van HACS /hacsfiles/…, of https://…).", + "plugins_docs": "Een plug-in schrijven", + "plugins_warning": "Plug-ins draaien met dezelfde rechten als NextFloor in je browser. Gebruik alleen plug-ins uit bronnen die je vertrouwt.", + "plugins_off": "uit", + "plugins_error": "fout", + "plugins_loading": "laden …", + "plugins_nothing_registered": "geladen, maar niets geregistreerd", + "plugins_loaded": "actief", + "plugins_reload_hint": "Werkt na herladen van de pagina", + "plugins_remove": "Verwijderen", + "plugins_none": "Nog geen plug-ins.", + "plugins_from_dashboard": "Geregistreerd door een dashboardresource", + "plugins_add": "Toevoegen", + "plugins_url_invalid": "Vul een .js-adres in onder /local/…, /hacsfiles/… of https://….", + "plugins_exists": "Deze plug-in staat al in de lijst.", + "plugins_limit": "Hoogstens 20 plug-ins.", + "packs_title": "Meubelpacks", + "packs_intro": "Importeer je eigen meubels als pack (JSON): als bestand of hieronder geplakt. {n} packs worden met NextFloor meegeleverd en zijn er altijd.", + "packs_docs": "Packformaat", + "packs_none": "Nog geen eigen packs.", + "community_title": "Community-meubels", + "community_intro": "Meubels die anderen met de meubelbouwer hebben gemaakt en gedeeld – gecontroleerd en gratis. Bouw je eigen:", + "community_builder": "Meubelbouwer openen", + "community_how": "Zo deel je de jouwe", + "community_load": "Community-meubels laden", + "community_none": "Nog geen community-meubels – wees de eerste!", + "community_install": "Installeren", + "community_update": "Bijwerken", + "community_installed": "Geïnstalleerd", + "community_failed": "De community-meubels konden niet worden geladen: {detail}", + "pack_import": "Packbestanden importeren …", + "pack_paste": "JSON importeren", + "pack_paste_empty": "Plak eerst de JSON van een pack.", + "pack_paste_not_json": "Dit is geen geldige JSON: {detail}", + "pack_imported": "„{name}” van {publisher} geïmporteerd: {n} items", + "packs_imported_n": "{n} van {total} packs geïmporteerd", + "pack_by": "van {publisher} · {n} items", + "pack_remove": "Verwijderen", + "pack_remove_confirm": "Pack „{name}” verwijderen? De meubels blijven in de plattegrond als gewone blokken.", + "pack_error_not_a_pack": "Dit is geen meubelpack (\"format\": \"nfpack\" ontbreekt).", + "pack_error_builtin": "Een meegeleverd pack heeft al deze id.", + "pack_error_invalid_content": "Het pack bevat ongeldige meubels: {detail}", + "pack_error_too_large": "Het pack is te groot (hoogstens 1 MB).", + "pack_error_needs_update": "Dit pack heeft een nieuwere versie van NextFloor nodig. Werk eerst bij (HACS › NextFloor › ⋮ › \"Update-informatie\" › \"Downloaden\"), herstart Home Assistant en importeer opnieuw.", + "pack_error_other": "Importeren mislukt: {detail}", + "store_open": "Plug-inwinkel openen", + "store_close": "Plug-inwinkel sluiten", + "store_intro": "Gecontroleerde plug-ins uit de community. Elke plug-in wordt bekeken voordat hij wordt toegevoegd en verandert daarna niet meer.", + "store_submit": "Eigen plug-in indienen", + "store_empty": "Nog geen plug-ins in de winkel.", + "store_failed": "De winkel kon niet worden geladen ({error}).", + "store_install": "Installeren", + "store_installed": "geïnstalleerd", + "store_update": "Bijwerken", + "store_confirm": "„{name}” van {author} installeren?\n\nEen plug-in draait met dezelfde rechten als NextFloor in je browser. Het bestand is gecontroleerd en de inhoud staat vast:\n{url}", + "manual": "Handleiding", + "manual_more": "Meer weten", + "feature_text_energy": "Energiedeeltjes vliegen in bogen van de zonnevelden naar de omvormer, tussen huis, accu, net en verbruikers, sneller en dichter naarmate er meer vermogen stroomt. De panelen fonkelen met hun opbrengst, een glazen kaart boven het dak toont de balans en hoe zelfvoorzienend het huis nu is.", + "live_autarky": "autarkie", + "live_day_hint": "De laatste 24 uur: zon (vlak) en verbruik (lijn)", + "live_week_hint": "De laatste 7 dagen: zon {solar} kWh, verbruik {use} kWh (geel: zon, licht: verbruik)", + "live_days": "dagen", + "live_car_away": "Onderweg", + "live_car_charging": "Laadt", + "live_car_plugged": "Aangesloten", + "live_car_lock": "Vergrendelen", + "live_car_unlock": "Ontgrendelen", + "live_car_unlock_confirm": "{name} echt ontgrendelen?", + "live_car_climate": "Klimaat", + "live_car_charge": "Laden starten/stoppen", + "live_media_prev": "Vorige", + "live_media_playpause": "Afspelen/pauze", + "live_media_next": "Volgende", + "live_media_volume": "Volume", + "live_car_device": "Auto (elke entiteit van de auto)", + "live_car_device_hint": "Laadstand, bereik, laden, stekker, slot en klimaat vindt NextFloor op het apparaat van de auto. Zonder dat gebruikt het de aanwezigheidssensor van de plek.", + "live_car_departure_entity": "Vertrektijd (optioneel)", + "live_car_departure": "Vertrek {time}", + "live_car_open": "Open: {parts}", + "printer_printing": "print", + "printer_done": "klaar", + "printer_paused": "gepauzeerd", + "printer_error": "fout", + "printer_idle": "gereed", + "printer_done_at": "klaar om {time}", + "printer_layer": "Laag", + "printer_nozzle": "Nozzle", + "printer_bed": "Bed", + "heatpump_heating": "verwarmt", + "heatpump_water": "maakt warm water", + "heatpump_cooling": "koelt", + "heatpump_defrost": "ontdooit", + "heatpump_idle": "rust", + "heatpump_flow_return": "Aanvoer → retour", + "heatpump_heat": "Warmte", + "heatpump_power": "Stroom", + "heatpump_outside": "buiten", + "pack_missing_item": "Meubel van een verwijderd pack", + "back_to_room": "Terug naar {room}", + "back_to_floor": "Terug naar de verdieping", + "hint_furniture": "Tik op een ruimte, kies dan rechts een item · sleep items, wijzig hun grootte via de hoeken", + "furniture_into": "Nieuwe items komen in het midden van „{room}”.", + "furniture_pick_room": "Tip: tik eerst op een ruimte; nieuwe items komen dan in het midden ervan.", + "flows": "Energiestroom", + "flows_hint": "De energiebogen tussen zonnevelden, omvormer, accu, net en verbruikers tonen of verbergen", + "chk_title": "Instellen", + "chk_hint": "Wat de energiestroom nodig heeft. Tik op een rij om erheen te gaan.", + "chk_solar": "Zonneveld geplaatst", + "chk_solar_add": "Leg een zonneveld op het dak", + "chk_meter": "Meter met netsensor", + "chk_meter_sensor": "Meter: netsensor (W) ontbreekt", + "chk_meter_add": "Meter toevoegen", + "chk_inverter": "Omvormer met vermogenssensor", + "chk_inverter_sensor": "Omvormer: vermogenssensor ontbreekt", + "chk_inverter_add": "Omvormer toevoegen", + "chk_battery": "Thuisaccu met vermogen en laadstand", + "chk_battery_sensor": "Thuisaccu: vermogen of laadstand ontbreekt", + "chk_battery_opt": "Thuisaccu (optioneel)", + "chk_grid": "Netaansluiting ingesteld", + "chk_grid_opt": "Netaansluiting (optioneel, anders automatisch)", + "energy_sign_grid": "Het huis toont teruglevering terwijl de zon niets opwekt. De netsensor heeft waarschijnlijk een omgekeerd teken.", + "energy_sign_battery": "De accu laadt zonder zon en zonder netafname. Zijn sensor heeft waarschijnlijk een omgekeerd teken.", + "energy_sign_flip": "Teken omdraaien", + "help_title": "Hulp en feedback", + "help_hint": "Meld problemen als GitHub-issue en wensen als discussion: niets raakt kwijt en iedereen ziet de stand.", + "help_issue": "Probleem melden", + "help_idea": "Idee voorstellen", + "furn_name": "Naam (optioneel)", + "furn_mirror": "Spiegelen", + "furn_mirror_hint": "Links en rechts verwisselen: de hoekbank andersom, de kast met de deur aan de andere kant, de keuken gespiegeld.", + "hint_opening": "Tik op een muur om een deur of raam toe te voegen; kies daarna rechts het soort", + "preset_door": "Deur", + "preset_door_double": "Dubbele deur", + "preset_window": "Raam", + "preset_window_double": "Dubbel raam", + "preset_terrace": "Terrasdeur", + "preset_terrace_double": "Openslaande deuren", + "preset_lift_slide": "Hefschuifpui", + "preset_garage": "Garagedeur", + "preset_front": "Voordeur", + "opening_style": "Stijl", + "sidelight_auto": "automatisch", + "sidelight_hinge": "Zijlicht aan de scharnierkant", + "sidelight_hinge_hint": "Anders zit het zijlicht tegenover de scharnieren; aangevinkt zit het naast de scharnieren.", + "sidelight_width": "Breedte zijlicht (m)", + "sidelight_width_left": "Linker zijlicht (m)", + "sidelight_width_right": "Rechter zijlicht (m)", + "style_auto": "Automatisch ({style})", + "style_interior": "Binnendeur", + "style_front": "Voordeur", + "style_front_glass": "Voordeur met glas", + "style_sidelight": "Voordeur met zijlicht", + "style_sidelights": "Voordeur met twee zijlichten", + "style_glass": "Glazen deur", + "style_sliding": "Schuifdeur", + "style_passage": "Opening (zonder deur)", + "style_standard": "Standaard", + "style_bars": "Met roeden", + "style_glass_wall": "Glazen wand (vast)", + "preset_glass_wall": "Glazen wand", + "flip_hinge": "Scharnierkant wisselen", + "flip_main_leaf": "Hoofdvleugel wisselen", + "flip_hinge_hint": "Scharnieren naar de andere kant", + "flip_swing": "Draairichting omkeren", + "flip_swing_hint": "De deur draait de ruimte in of naar de andere kant", + "main_leaf": "Hoofdvleugel (gezien vanuit de ruimte)", + "contact_main": "Contact hoofdvleugel", + "contact_second": "Contact tweede vleugel", + "tool_outdoor": "Buiten", + "tool_measure": "Op maat", + "hint_measure": "Tik op het beginpunt en typ rechts de muurlengtes met hun richting", + "measure": "Ruimte op maat", + "measure_start": "Tik op het beginpunt in de plattegrond, bijv. een hoek van de ruimte.", + "measure_from": "Start op {x} / {z} m; tikken verplaatst de start.", + "measure_length": "Lengte van de volgende muur (m)", + "measure_close": "Ruimte sluiten", + "measure_undo": "Laatste muur verwijderen", + "measure_gap": "Afstand tot de start: {gap} m (wordt bij sluiten verbonden)", + "measure_hint": "Tip: typ een lengte en druk op een pijltoets. Met gemeten binnenmaten gebruik je daarna „Kieren dichten”.", + "rect_by_size": "Rechthoek op maat", + "rect_add": "Rechthoek toevoegen", + "dir_up": "Omhoog", + "dir_down": "Omlaag", + "dir_left": "Links", + "dir_right": "Rechts", + "hint_outdoor": "Sleep om een buitengebied te tekenen (gazon, terras, zwembad …)", + "outdoor": "Buitengebied", + "outdoor_type": "Type", + "outdoor_height": "Hoogte (m)", + "outdoor_offset": "Hoogteverschuiving (m, − = lager)", + "outdoor_outline": "Omtrek tonen", + "outdoor_outline_hint": "Uitgevinkt tekent het gebied geen gloeiende lijn langs de rand, voor grote percelen uit meerdere gazons.", + "outdoor_corners_hint": "Hoeken: een + op een rand voegt een hoek toe, slepen vormt het gebied, × verwijdert een hoek.", + "outdoor_hint": "Buitenlampen (padlamp, tuinspot, buitenwandlamp) verlichten alle buitengebieden en de gevel.", + "out_lawn": "Gazon", + "out_terrace": "Terras", + "out_path": "Pad", + "out_driveway": "Oprit", + "out_pool": "Zwembad", + "out_bed": "Bloemperk", + "out_hedge": "Haag", + "out_fence": "Hek", + "out_wild": "Wilde hoek", + "out_pergola": "Pergola / frame", + "outdoor_open": "Open (laatste rand weglaten)", + "outdoor_open_hint": "De rand van het laatste punt terug naar het eerste wordt niet getekend: een hek of pergola tegen het huis.", + "fence_gates": "Poorten in het hek", + "gate_add": "+ Poort in het hek", + "gate_edge": "Hekzijde", + "gate_kind": "Soort", + "gate_single": "Tuinpoort", + "gate_double": "Dubbele poort", + "gate_sliding": "Schuifpoort", + "gate_offset": "Midden vanaf het begin (m)", + "gate_width": "Breedte (m)", + "gate_entity": "Motor of schakelaar", + "gate_contact": "Contact (aan = open)", + "fence_gates_hint": "Een poort is een opening in het hek met poortstijlen en een vleugel. Met een motor (cover, schakelaar, input_boolean, slot) en/of een contact gaat hij in 3D open: tuin- en dubbele poorten zwaaien naar binnen, een schuifpoort loopt langs het hek.", + "outdoor_bracing": "X-verband", + "outdoor_cut": "Uit omliggende gebieden snijden", + "outdoor_cut_hint": "Elk gebied dat dit gebied helemaal bevat, krijgt hier een gat: een zwembad in het terras, een vijver of wilde hoek in het gazon. De tekenvolgorde maakt niet uit. Een zwembad snijdt zichzelf uit.", + "outdoor_area_hint": "Het Home Assistant-gebied van dit vlak (tuin, terras, zwembad): de apparaten en sensoren staan onder Buiten, en een pin op het vlak opent het.", + "pool_temp": "Watertemperatuur (optioneel)", + "pool_pump": "Pomp / filter (optioneel)", + "pool_pump_on": "pomp aan", + "outdoor_slope": "Helling (m)", + "outdoor_slope_hint": "Hoogteverschil van de hoge naar de lage rand; de hoge rand ligt op de hoogteverschuiving. Lampen op het gebied volgen.", + "outdoor_slope_dir": "Loopt af naar", + "slope_x": "rechts (+X)", + "slope_nx": "links (−X)", + "slope_z": "omlaag (+Z)", + "slope_nz": "omhoog (−Z)", + "north": "Noorden (° met de klok mee vanaf boven)", + "north_hint": "Het noorden is nodig voor de zon (licht door de ramen).", + "map_on": "Een echte kaart onder de plattegrond tonen", + "map_lat": "Breedtegraad", + "map_lon": "Lengtegraad", + "map_use_ha": "Locatie van Home Assistant gebruiken", + "map_opacity": "Zichtbaarheid (%)", + "map_zoom": "Detailniveau", + "map_zoom_coarse": "grof", + "map_zoom_fine": "fijn", + "map_move": "Kaart onder de plattegrond verschuiven", + "map_step": "Stap", + "map_url": "Eigen tegeladres (leeg = OpenStreetMap)", + "map_hint": "Je browser laadt de kaarttegels direct van de kaartserver (standaard OpenStreetMap, let op hun gebruiksbeleid); zolang de kaart uit staat, wordt niets geladen. De plattegrond ligt op de kaart zoals het kompas aangeeft; draai het kompas of verschuif de kaart tot het huis past.", + "compass_title": "Kompas", + "compass_n_short": "N", + "compass_s_short": "Z", + "compass_swap": "Noord ↔ zuid wisselen", + "compass_swap_hint": "Draait het kompas 180°. De tekening, dakvlakken en zonnevelden blijven zoals ze zijn.", + "compass_hint": "Klopt het kompas niet met de werkelijkheid, draai het hier; niets hoeft opnieuw getekend te worden. Zonlicht, wind en de windrichting van dakvlakken volgen het.", + "roof": "Dak", + "roof_none": "Geen dak", + "roof_flat": "Plat dak", + "roof_gable": "Zadeldak", + "roof_custom": "Dakvlakken (eigen)", + "roof_sections": "Dakvlakken", + "roof_sections_hint": "Elk dakvlak dekt een rechthoek van het huis, bijv. het huis, de schuur of een aanbouw, elk met eigen vorm, nokrichting, goothoogte en helling. Sleep in de plattegrond om er een te tekenen; tikken selecteert, slepen verplaatst, de hoeken wijzigen de grootte.", + "roof_sections_start": "Dakvlakken uit de ruimtes maken", + "roof_sections_regen": "Opnieuw uit de ruimtes maken", + "roof_sections_off": "Terug naar één dak", + "roof_regen_confirm": "Alle dakvlakken vervangen door een nieuw voorstel uit de ruimtes?", + "roof_section": "Dakvlak", + "roof_section_hint": "Hoogtes tellen vanaf de grond. Een kant met lagere goot reikt verder omlaag (catslide); lessenaarsdaken stijgen vanaf de eerste kant.", + "roof_shape_gable": "Zadeldak", + "roof_shape_hip": "Schilddak", + "roof_shape_pent": "Lessenaarsdak", + "roof_shape_flat": "Plat", + "roof_shape_halfhip": "Wolfsdak", + "roof_shape_pyramid": "Tentdak", + "roof_shape_mansard": "Mansarde", + "roof_shape_parapet": "Met borstwering", + "roof_shape": "Vorm", + "roof_end_start": "Eind aan het nokbegin", + "roof_end_end": "Eind aan het nokeinde", + "roof_halfhip": "Wolfseind begint op", + "roof_halfhip_hint": "Hoe hoog in de topgevel het schilddeel begint, als deel van de gevelhoogte: laag = een groot schild, hoog = alleen de top.", + "roof_axis_x": "Nok ↔", + "roof_axis_z": "Nok ↕", + "roof_eave": "Goot (m)", + "roof_pitch_short": "Helling (°)", + "roof_height": "Hoogte (m)", + "roof_base": "Bovenkant muren (m)", + "roof_rotation": "Draaiing (°)", + "roof_on_floor": "Staat op verdieping", + "roof_on_floor_hint": "Zet het vlak op de muurkoppen van deze verdieping; basis en goten bewegen mee. In de 3D-weergave hoort het dak bij deze verdieping.", + "roof_base_hint": "Onder de plafondhoogte van de verdieping eronder eindigen de muren van die verdieping onder het dak: knieschotten bij de goten, topgevels tot de nok, binnenmuren afgesneden door de helling. Gestreepte lijnen in de plattegrond tonen waar 1,5 m en 2 m stahoogte overblijven.", + "roof_ridge_height": "Nokhoogte", + "roof_side_top": "boven", + "roof_side_bottom": "onder", + "roof_side_left": "links", + "roof_side_right": "rechts", + "roof_swap": "Kanten wisselen", + "roof_open": "Overkapping (palen in plaats van muren, doorzichtig)", + "roof_open_short": "Overkapping", + "roof_dormer": "Dakkapel", + "roof_dormer_hint": "Een dakkapel aan deze kant van het dak: 2 m breed, de voorkant op de gootmuur, goten 1,4 m boven de dakgoot, zadeldak. Verplaats haar daarna en wijzig breedte en hoogtes zoals elk vlak; het hoofddakvlak opent eronder en de zoldermuur stijgt tot de dakkapel; daar past een raam.", + "roof_outline": "Omtrek van de verdieping overnemen", + "roof_outline_hint": "Een plat dak in vrije vorm: neemt de omtrek van de ruimtes van de getoonde verdieping (ook L- of Z-vormig) als één naadloos vlak. De hoeken kunnen daarna worden versleept.", + "roof_points_hint": "Vrije vorm: sleep de hoeken in de plattegrond, een + op een rand voegt een hoek toe, × verwijdert er een. Terug naar de rechthoek laat de vorm vallen.", + "roof_rect": "Terug naar de rechthoek", + "roof_open_hint": "Voor een terrasoverkapping of carport: palen en balken dragen het dak in plaats van muren, en het is doorzichtig. Waar de overkapping de huismuur raakt, rust ze op de muur.", + "roof_swap_hint": "Draait het dak om: de twee kanten wisselen goot en helling, een lessenaarsdak stijgt de andere kant op.", + "roof_pitch": "Dakhelling (°)", + "roof_overhang": "Dakoverstek (m)", + "roof_overhang_sides": "Overstek per zijde", + "roof_overhang_a": "Overstek dakrand A (m)", + "roof_overhang_b": "Overstek dakrand B (m)", + "roof_overhang_u0": "Overstek gevel begin (m)", + "roof_overhang_u1": "Overstek gevel eind (m)", + "roof_overhang_auto": "Terug naar automatisch", + "roof_overhang_sides_hint": "Zonder eigen waarden is de overstek automatisch: overal gelijk, behalve waar het dakdeel het huis raakt (daar geen).", + "roof_ridge": "Nok", + "roof_ridge_long": "Langs de lange zijde", + "roof_ridge_short": "Langs de korte zijde (bijv. rijtjeshuis)", + "device": "Apparaat", + "lamp_mount": "Lamp", + "lamp_ceiling": "Plafondlamp", + "lamp_floor": "Vloerlamp", + "lamp_table": "Tafellamp", + "lamp_wall": "Wandlamp", + "marker_height": "Hoogte markering (m)", + "height_auto": "Automatische hoogte", + "device_centre": "Naar het midden van de ruimte", + "lights_spread": "Plafondlampen gelijkmatig verdelen", + "devices_search": "Apparaten zoeken …", + "devices_more": "+{n} meer", + "devices_less": "minder", + "panel_more": "Meer apparaten van het gebied ({n})", + "panel_less": "Minder tonen", + "gaps_close": "Kieren dichten", + "gaps_hint": "Verbindt ruimtes tot 60 cm uit elkaar met één gedeelde muur; de kier wordt de dikte van de binnenmuur.", + "gaps_none": "Geen kieren tussen ruimtes gevonden.", + "gaps_closed": "{n} plekken gedicht.", + "gaps_closed_wall": "{n} plekken gedicht, binnenmuur nu {t} m.", + "fps": "FPS", + "fps_title": "Prestatieweergave (frames per seconde)", + "hint_garage": "Tik op een muur om een garagedeur toe te voegen", + "opening_garage": "Garagedeur", + "garage_hint": "De deur volgt een garage-cover (positie of open/dicht) of een garagedeurcontact van het gebied van de ruimte.", + "door_hint": "Met een deurcontact zwaait het blad open; zonder sensor staat het half open.", + "hint_door": "Tik op een muur om een deur toe te voegen", + "hint_window": "Tik op een muur om een raam toe te voegen", + "opening_door": "Deur", + "opening_window": "Raam", + "opening_type": "Type", + "opening_position": "Midden vanaf de hoek (m)", + "sill": "Borstweringshoogte (m)", + "opening_height": "Hoogte (m)", + "hinge": "Scharnier (gezien vanuit de ruimte)", + "hinge_left": "Links", + "hinge_right": "Rechts", + "cover_entity": "Rolluik", + "door_cover": "Aandrijving (gemotoriseerde deur of poort)", + "cover_position_entity": "Positiesensor (live)", + "cover_position_invert": "Sensor telt andersom (0 = open)", + "contact_entity": "Contact", + "sensor_kind": "Sensortype", + "sensor_kind_contact": "Raamcontact (open/dicht)", + "sensor_kind_handle": "Greepsensor (open/kiep/dicht)", + "sensor_kind_contact_tilt": "Contact + kiepsensor", + "handle_entity": "Greepsensor", + "handle_main": "Greepsensor hoofdvleugel", + "leaf_main": "Hoofdvleugel", + "leaf_second": "Tweede vleugel", + "tilt_entity": "Kiepsensor", + "tilt_angle_entity": "Kiephoeksensor (°, optioneel)", + "tilt_angle_max": "Hoek die als volledig gekiept telt (°)", + "tilt_angle_offset": "Offset: gemelde hoek in gesloten stand (°)", + "tilt_angle_invert": "De hoek telt andersom", + "door_shut": "Gesloten tonen zonder sensor", + "door_shut_hint": "Een deur zonder contact staat in 3D half open zodat ze als deur herkenbaar is. Aangevinkt wordt ze gesloten getekend: voordeur, carport, zijdeur.", + "door_angle": "Openingshoek", + "door_angle_default": "Standaard", + "door_angle_hint": "Hoe ver het deurblad opengaat. Met een sensor gaat het zo ver open zodra die ‘open’ meldt; zonder sensor staat het zo ver open (in plaats van half). Standaard blijft zoals het was.", + "entity_auto": "Automatisch ({name})", + "entity_auto_none": "Automatisch (niets gevonden)", + "entity_none": "Geen", + "entity_search": "Typ om te zoeken …", + "opening_hint": "Sensortype: raamcontact (meldt open/dicht), greepsensor (meldt open, gekiept en dicht, bijv. een Homematic-raamgreep) of contact + kiepsensor (een tweede sensor die alleen gekiept meldt). Automatisch gebruikt de rolluiken en contacten van het gebied van de ruimte. Positiesensor: een entiteit die de positie van het rolluik meldt terwijl het beweegt (bijv. een Homematic-\"level\", 0–100 % of 0–1, open = hoog); het rolluik beweegt dan live in 3D.", + "furniture": "Meubels", + "furniture_add": "Meubel toevoegen", + "studio_new": "Eigen meubel bouwen", + "studio_title": "Meubelwerkplaats", + "studio_title_edit": "Meubelwerkplaats: wijzigen", + "studio_hint": "Kies een sjabloon, stel maten en fronten in en zet het meubel in de plattegrond. Het komt in het pakket ‘Eigen meubels’ en is hier later weer aan te passen.", + "studio_kind": "Sjabloon", + "studio_kind_cabinet": "Kast", + "studio_kind_shelf": "Rek", + "studio_kind_lamp": "Lamp", + "studio_kind_device": "Apparaat", + "studio_name": "Naam", + "studio_width": "Breedte (cm)", + "studio_depth": "Diepte (cm)", + "studio_height": "Hoogte (cm)", + "studio_doors": "Deuren", + "studio_drawers": "Laden", + "studio_shelves": "Planken", + "studio_handle": "Grepen", + "studio_handle_bar": "Staaf", + "studio_handle_knob": "Knop", + "studio_handle_none": "Greeploos", + "studio_base": "Onderbouw", + "studio_base_plinth": "Plint", + "studio_base_legs": "Poten", + "studio_base_none": "Geen", + "studio_back": "Achterwand", + "studio_lamp": "Soort", + "studio_lamp_floor": "Staande lamp", + "studio_lamp_table": "Tafellamp", + "studio_lamp_pendant": "Hanglamp", + "studio_lamp_wall": "Wandlamp", + "studio_display": "Display aan de voorkant (toont de mediaspeler)", + "studio_mount": "Staat", + "studio_mount_floor": "Op de vloer", + "studio_mount_surface": "Op een meubel", + "studio_mount_wall": "Aan de muur", + "studio_color_body": "Korpus", + "studio_color_lamp_body": "Voet en frame", + "studio_color_front": "Fronten", + "studio_color_boards": "Planken", + "studio_color_shade": "Kap", + "studio_color_display": "Rand van het display", + "studio_color_white": "Wit", + "studio_color_wood": "Hout", + "studio_color_metal": "Metaal", + "studio_color_dark": "Donker", + "studio_color_glass": "Glas", + "studio_color_accent": "Accent", + "studio_color_own": "Eigen kleur", + "studio_color_plan": "Kleur van de plattegrond", + "studio_place": "In de plattegrond zetten", + "studio_save": "Wijziging opslaan", + "studio_open": "In de werkplaats wijzigen", + "studio_error": "Opslaan lukte niet: {detail}", + "studio_pack_name": "Eigen meubels", + "studio_pack_publisher": "Meubelwerkplaats", + "furniture_search": "Meubels zoeken …", + "furniture_search_none": "Niets gevonden. Probeer een ander woord, in het Engels of Duits.", + "furniture_type": "Item", + "rotation": "Rotatie (°)", + "tilt_x": "Kanteling voor/achter (°)", + "tilt_z": "Kanteling zijwaarts (°)", + "strip_tilt": "Kanteling om de lengteas (°)", + "strip_upright": "Rechtop", + "strip_rise": "Helling over de lengte (°)", + "strip_upright_hint": "De strip staat op zijn kant: zijn lengte loopt omhoog vanaf de hoogte boven de vloer, langs een deurkozijn, als lichtzuil. De kanteling legt een liggende strip tegen een helling (90° = de voorkant wijst opzij).", + "rotate_left": "↺ 90°", + "rotate_right": "↻ 90°", + "height_m": "Hoogte (m)", + "furn_sofa": "Bank", + "furn_armchair": "Fauteuil", + "furn_table": "Tafel", + "furn_chair": "Stoel", + "furn_bed": "Bed", + "furn_nightstand": "Nachtkastje", + "furn_wardrobe": "Kledingkast", + "furn_shelf": "Kast", + "furn_kitchen": "Keukenkast", + "furn_worktop": "Werkblad", + "furn_fridge": "Koelkast", + "furn_fridge_smart": "Slimme koelkast (side-by-side)", + "furn_door_left": "Deursensor links (vriezerkant)", + "furn_door_right": "Deursensor rechts (koelkastkant)", + "fridge_hint": "Zolang een deursensor open meldt, zwaait de deur in 3D open.", + "furn_stove": "Fornuis", + "furn_sink": "Spoelbak", + "furn_bathtub": "Bad", + "furn_shower": "Douche", + "furn_wc": "Wc", + "furn_washbasin": "Wastafel", + "furn_desk": "Bureau", + "furn_tv_board": "Tv-meubel", + "furn_plant": "Plant", + "furn_rug": "Vloerkleed", + "furn_stairs": "Trap", + "furn_stairwell": "Vloeropening", + "stairwell_hint": "Een gat in deze verdieping, bijvoorbeeld boven de trap of voor een vide; van boven kijk je erdoor. De opening moet binnen één ruimte liggen; meerdere openingen mogen overlappen (bijvoorbeeld voor een L-vorm). Trappen op de verdieping eronder die tot hier reiken, openen de vloer ook vanzelf.", + "tool_hole": "Vloeropening", + "tool_roof": "Dak", + "tool_energy": "Energie", + "tool_wall": "Muur", + "hint_wall": "Sleep om een losse muur te tekenen (scheidingswand, halve muur) · Shift houdt hem recht · Alt zonder snappen", + "free_wall": "Muur", + "wall_length": "Lengte (m)", + "wall_thickness": "Muurdikte (m)", + "wall_height": "Hoogte (m)", + "wall_height_full": "Volle ruimtehoogte", + "wall_slope": "Schuin", + "wall_slope_start": "Hoogte aan het begin (m)", + "wall_slope_end": "Hoogte aan het eind (m)", + "wall_slope_hint": "Schuine muur: de bovenkant loopt recht van de hoogte aan het begin van de muur (de hoek met het lagere nummer) naar de hoogte aan het eind. Beide mogen boven de verdiepingshoogte liggen, bijvoorbeeld voor een aanbouw met hoge bovenramen.", + "wall_slope_off": "Terug naar een rechte muur", + "wall_none": "Geen muur", + "wall_none_hint": "Laat deze muur helemaal weg: voor open plattegronden waarvan de ruimtes één geheel zijn maar in Home Assistant gescheiden.", + "edge_thickness": "Dikte (m)", + "wall_thickness_hint": "Dikte van deze muur, bijv. 0,365 bij een dikke buitenmuur of 0,115 bij een lichte scheidingswand. Een muur tussen twee ruimtes krijgt de dikste instelling.", + "wall_thickness_reset": "Dikte zoals ingesteld voor het huis", + "wall_heights": "Muurhoogtes", + "wall_n": "Muur {a}–{b}", + "wall_view": "Muurweergave", + "wall_view_hint": "De muur van voren: sleep deuren, ramen en meubels of typ hun afstand.", + "wall_view_prev": "Vorige muur", + "wall_view_next": "Volgende muur", + "wall_view_left": "Vanaf links (m)", + "wall_view_height": "Boven de vloer (m)", + "wall_part": "deel {n}", + "wall_split_hint": "Splits de muur hier: het deel krijgt een eigen hoogte, bijv. 2,5 m naast 1,7 m op één lijn", + "wall_split_at": "Splitspunt vanaf de hoek (m)", + "wall_join_hint": "Splitspunt verwijderen: het deel sluit weer aan bij het vorige", + "wall_exterior_short": "buitenmuur", + "room_wall_hint": "Een lagere hoogte maakt van de muur een borstwering of toonbank. Delen twee ruimtes de muur, dan geldt de lagere instelling. Ramen en deuren erin eindigen op de muurhoogte.", + "free_wall_hint": "Een vrijstaande muur, bijv. een scheidingswand. Waar hij een ruimtemuur raakt, wordt de hoek verstek gezaagd. Sleep de grepen om de uiteinden te verplaatsen, sleep de lijn om de hele muur te verplaatsen.", + "free_wall_slope": "◢ Hellend", + "free_wall_slope_hint": "De muur wordt van het ene naar het andere eind hoger of lager: de hoogte erboven is die aan het begin, deze aan het eind.", + "free_wall_height_end": "Hoogte aan het eind (m)", + "stairwell_outside": "Deze opening loopt over een ruimtegrens en wordt daarom niet uitgesneden. Verplaats haar volledig in één ruimte of maak haar kleiner.", + "hint_hole": "Sleep om een vloeropening te tekenen (trapgat, vide)", + "hint_roof": "Sleep om een dakvlak te tekenen · tikken selecteert · slepen verplaatst · hoeken wijzigen de grootte", + "hint_energy": "Tik op een zonneveld om het te selecteren · sleep om het te verplaatsen, ook naar een ander dakvlak · nieuwe velden met + Zonneveld rechts", + "furn_parking": "Parkeerplaats", + "furn_group_vehicles": "Parkeren", + "parking_entity": "Sensor \"auto aanwezig\"", + "parking_vehicle": "Voertuig", + "parking_vehicle_none": "Geen", + "parking_no_pack": "Geen voertuigpack geïmporteerd; voertuigen komen uit het pack \"Voertuigen\" (Uitbreidingen → Meubelpacks).", + "parking_scale": "Grootte (%)", + "parking_type_entity": "Sensor voertuigtype (optioneel)", + "parking_types": "Status → voertuig", + "parking_type_state": "Status (bijv. van)", + "parking_add_type": "+ Koppeling", + "parking_hint": "Zonder sensor staat het voertuig er altijd. Met sensor verschijnt het zodra die \"on\", \"home\" of \"present\" meldt. Een sensor voor het voertuigtype (bijv. uit een AI-camera-analyse) kiest het model: komt de status overeen met een koppeling, ook als woord in de tekst, dan wordt dat voertuig getoond, anders het standaardvoertuig.", + "parking_too_tall": "Het voertuig ({car} m) is hoger dan de ruimte ({room} m).", + "furn_lamp_ceiling": "Plafondlamp", + "furn_lamp_downlight": "Inbouwspot", + "furn_lamp_spot": "Opbouwspot", + "furn_lamp_panel": "Ledpaneel", + "furn_lamp_uplight": "Grondspot", + "furn_lamp_bollard": "Padlamp", + "furn_lamp_garden": "Tuinspot", + "furn_radiator": "Radiator", + "furn_robot_vacuum": "Robotstofzuiger", + "furn_entity_vacuum": "Robotstofzuiger", + "furn_entity_mower": "Robotmaaier", + "pet_room_sensor": "Kamersensor van het dier (optioneel)", + "pet_room_hint": "Een sensor die de kamer noemt waar het dier is – Bermuda of ESPresense met een tag aan de halsband: in 3D loopt het dan in die kamer rond.", + "furn_entity_water": "Klep of schakelaar", + "fridge_temp": "Temperatuur koelkast", + "freezer_temp": "Temperatuur vriezer", + "fridge_temp_hint": "De pin toont de temperaturen. Boven 8 °C in de koelkast of −12 °C in de vriezer licht hij op als waarschuwing.", + "spray_reach": "Bereik van het water (m)", + "spray_hint": "Zolang de klep open of de schakelaar aan is, spuit de sproeier water in bogen om zich heen.", + "furn_robot_room": "Huidige ruimte (sensor)", + "robot_hint": "Zolang de robot in Home Assistant schoonmaakt, rijdt hij in 3D banen door de ruimte die hij meldt (een sensor „huidige ruimte”, vergeleken met ruimte- of gebiedsnaam), anders door de ruimte van zijn dock. Het spoor is gesimuleerd; Home Assistant kent meestal de exacte positie niet. Hij rijdt terug naar het dock als hij terugkeert.", + "furn_lamp_pendant": "Hanglamp", + "furn_ceiling_fan": "Plafondventilator", + "furn_fan_entity": "Ventilator", + "fan_hint": "De lamp is de lichtkit van de ventilator (leeg laten als hij er geen heeft). De ventilator wordt in de ruimte gevonden of hier gekozen: in 3D draaien de bladen zo snel als hij draait, zijn pictogram schakelt hem, omhoog/omlaag vegen wijzigt de snelheid, lang drukken opent het snelmenu. De hoogte is hoe ver hij onder het plafond hangt (meer = een langere stang).", + "room_ceiling": "Plafondhoogte", + "room_ceiling_tip": "Lager dan de verdieping (een badkamer onder de trap) of hoger (een woonkamer open tot onder het dak): plafondlampen, ventilatoren, ledstrips en plafondapparaten hangen dan hier, en de muren van de ruimte zijn zo hoog.", + "room_ceiling_through": "Het plafond ({ceiling} m) ligt boven de verdiepingshoogte ({floor} m): de ruimte reikt tot in de verdieping erboven, de muren groeien mee en de verdieping erboven blijft boven de ruimte open (vide). De editor van de bovenste verdieping toont het vlak gearceerd.", + "room_floor_offset": "Vloerniveau (m)", + "room_floor_offset_hint": "Ligt de vloer van deze kamer lager of hoger dan de verdieping (een verlaagde entree: −0,39), dan gaan vloer, muren, deuren, ramen en wat erin staat mee; het plafond blijft. Zet de treden erbij als trap.", + "room_inner": "Binnenmaat {w} × {d}", + "room_inner_hint": "Van wand tot wand gemeten: binnenwanden nemen de helft van hun dikte, buitenwanden staan buiten de omtrek.", + "floor_heating": "Vloerverwarming (optioneel)", + "floor_heating_hint": "Zolang de thermostaat verwarmt (of de klep open, de schakelaar aan is), gloeit de vloer van de kamer warm in 3D.", + "room_announce_speaker": "Luidspreker voor omroepen", + "room_announce_quiet": "Stille tijd voor omroepen", + "room_announce_hint": "Zonder keuze spreekt de luidspreker die in de kamer staat, anders een spraakassistent, een Echo of een luidspreker van de ruimte (nooit een tv). In de stille tijd slaan omroepen naar meerdere kamers deze kamer over; een omroep alleen voor deze kamer komt wel aan.", + "ceiling_here": "Plafond hier", + "ceiling_here_hint": "Hoogte van het plafond precies op deze plek, bijv. bij een schuin plafond. Leeg = het plafond van de ruimte.", + "ceiling_slope": "Tegen het schuine dak", + "ceiling_slope_hint": "Het plafond ligt hier onder het schuine dak: de lamp hangt aan de onderkant, precies boven zijn plek.", + "furn_lamp_floor": "Vloerlamp", + "furn_lamp_table": "Tafellamp", + "furn_lamp_wall": "Wandlamp", + "furn_led_strip": "Ledstrip", + "furn_group_lights": "Lampen", + "furn_entity_light": "Licht of schakelaar", + "furn_color_entity": "Kleur en helderheid van (optioneel)", + "furn_color_entity_hint": "Voor lampen die een relais (Shelly, schakelactor) aan- en uitzet terwijl de lamp zelf haar kleur en helderheid kent: aan/uit komt van de schakelaar hierboven, kleur en helderheid van deze entiteit.", + "lamp_extra_light": "Lamp {n} (optioneel)", + "lamp_extra_hint": "Een armatuur met meerdere lichten – hoofdlicht, nachtlampje, sfeerring: staat het hoofdlicht uit, dan gloeit het in 3D met het volgende licht dat aan is, iets zwakker. Schakel de lichten afzonderlijk in het kamerpaneel.", + "furn_entity_climate": "Verwarming (thermostaat)", + "lamp_hint": "Tik op de lamp in 3D om haar te schakelen, lang drukken voor het snelmenu. Schakelaars werken ook (bijv. een relais voor de plafondlamp); de lamp brandt zolang hij aan is. Tafellampen staan op het meubel eronder.", + "lamp_hint_pendant": "Hoogte = afhang onder het plafond. Tik in 3D om te schakelen, lang drukken voor details.", + "theme": "Look", + "version_hint": "Geïnstalleerde versie van NextFloor (de frontend); de integratie in Home Assistant meldt {backend}", + "accent": "Accentkleur", + "accent_hint": "Een eigen accentkleur: lijnen en gloeiende randen in de neonlook, knoppen en markeringen; ↺ brengt het neoncyaan terug", + "accent_reset": "Terug naar cyaan", + "theme_neon": "Neon", + "theme_blueprint": "Blauwdruk", + "theme_day": "Dag", + "theme_auto": "Auto", + "clock": "Klok", + "clock_none": "Geen", + "clock_top_left": "Linksboven", + "clock_top_right": "Rechtsboven", + "clock_bottom_left": "Linksonder", + "clock_bottom_right": "Rechtsonder", + "glass_walls": "Glazen wanden", + "glass_walls_hint": "Hoe dekkend de wanden zijn waardoor je in de kamers kijkt: links bijna onzichtbaar, rechts ondoorzichtig. Voor dit scherm.", + "screen_name": "Naam van dit scherm", + "screen_name_hint": "Omroepen verschijnen op elk open NextFloor-scherm. Met een naam (bijv. ‘Gang’) kan een omroep alleen naar dit scherm gaan. Zonder vinkje blijft dit scherm stil.", + "announce_on": "Omroepen op dit scherm aan", + "announce_muted": "Omroepen op dit scherm gedempt", + "lock3d_on": "3D vergrendelen (niet draaien, zoomen of verschuiven; tikken werkt nog)", + "lock3d_off": "3D ontgrendelen", + "walk": "Door het huis lopen", + "travel": "Tijdreis: de laatste 24 uur of 7 dagen terugspelen", + "travel_play": "Afspelen", + "travel_pause": "Pauze", + "travel_loading": "Geschiedenis laden …", + "travel_failed": "De geschiedenis kon niet worden geladen.", + "travel_speed": "Snelheid", + "travel_speed_min": "1 min/s", + "travel_speed_10min": "10 min/s", + "travel_speed_hour": "1 u/s", + "travel_days": "dagen", + "travel_live": "Live", + "card_travel_button": "Knop voor tijdreis", + "walk_stop": "Stoppen met lopen", + "walk_hint": "Slepen: rondkijken · W A S D / pijlen of stick: lopen · wieltje: stap", + "card_walk_button": "Knop om rond te lopen", + "card_lock_button": "Knop voor de 3D-vergrendeling", + "backdrop": "Eigen achtergrond", + "backdrop_color": "Kleur", + "backdrop_image": "Afbeelding (/local/… of https://…)", + "backdrop_dim": "Dimmen", + "backdrop_hint": "In plaats van de lucht van de look staat het huis voor een eigen kleur of afbeelding. Een afbeelding in /config/www is bereikbaar onder /local/….", + "furnish": "Inrichten", + "split_3d": "3D ernaast", + "plan_dims": "Maten", + "plan_dims_hint": "Zet bij elke kamerrand de lengte.", + "mount_height": "Hoogte boven de vloer (m)", + "side_open": "Zijbalk openen", + "side_close": "Sluiten", + "side_details": "Details van de selectie", + "side_pin": "Vastzetten", + "side_pinned": "Vastgezet", + "side_pin_hint": "Vastgezet blijft de zijbalk open; anders klapt hij in naast de 3D-weergave zolang niets geselecteerd is", + "split_3d_hint": "Live 3D naast de plattegrond: sleep en draai daar meubels en apparaten, met ongedaan maken, opgeslagen met de plattegrond", + "size_w": "Breedte (m)", + "size_d": "Diepte (m)", + "size_h": "Hoogte (m)", + "furnish_hint": "Sleep meubels, lampen en apparaten · meubels snappen aan muren · tik op een item om het te draaien en hoogte en montage in te stellen", + "done": "Klaar", + "heatmap": "Heatmap", + "heat_off": "Normaal", + "heat_short_temperature": "Temp.", + "heat_short_humidity": "Vocht", + "heat_short_co2": "CO₂", + "heat_short_mould": "Schimmel", + "heat_short_power": "Stroom", + "heat_short_comfort": "Comfort", + "heat_short_sun": "Zon", + "heat_short_wifi": "Wifi", + "heat_short_values": "Waarden", + "heat_temperature": "Temperatuur", + "heat_humidity": "Luchtvochtigheid", + "heat_co2": "CO₂", + "heat_mould": "Schimmel", + "heat_power": "Stroomverbruik", + "heat_comfort": "Comfortscore", + "heat_sun": "Zon vandaag", + "room_sun_hours": "{h} u zon vandaag ({facing})", + "open_since": "open sinds {time}", + "presence_now": "er is iemand", + "presence_last": "{time} geleden gezien", + "comfort_n": "Comfort {n}", + "empty_lights_hint": "{n} lampen aan, al {min} min niemand.", + "empty_lights_off": "Licht uit", + "open_heating_hint": "{n} ramen open terwijl de verwarming aan staat.", + "open_heating_off": "Verwarming uit", + "room_clean": "Schoonmaken (script of knop)", + "room_clean_hint": "Een script of knop die de robotstofzuiger naar deze kamer stuurt (bv. de kamerreiniging van je robotintegratie). Het kamerpaneel toont dan ‘🧹 Zuigen’.", + "room_clean_run": "Zuigen", + "room_clean_run_hint": "Stuurt de robotstofzuiger naar deze kamer.", + "shade_hint": "Zon op {n} ramen bij {temp} – rolluiken omlaag?", + "shade_close": "Omlaag", + "room_sun_year": "Zon over het jaar", + "room_sun_year_hint": "De zonuren door de buitenramen van de kamer op de 15e van elke maand.", + "room_energy": "vandaag {today} · maand {month}", + "room_energy_hint": "Uit de statistieken van de vermogenssensoren van de apparaten in de kamer; de kosten van de maand met het tarief van het huis.", + "heat_summer": "zomer", + "heat_winter": "winter", + "air_co2": "luchten (CO₂)", + "air_humidity": "luchten (vochtig)", + "air_mould": "schimmelrisico – luchten", + "room_curve_hint": "De temperatuur van de kamer in de afgelopen 24 uur", + "heat_values": "Waarden bij de ruimtenamen", + "heat_wifi": "Wifi", + "wifi_aps": "{n} accesspoints · {clients} apparaten", + "wifi_network": "Netwerk: {online} online · {offline} offline", + "wifi_none": "Plaats accesspoints of routers uit de packs (Slim huis 2) en koppel ze aan een entiteit van hun apparaat.", + "wifi_clients": "{n} apparaten", + "heat_none_found": "Geen passende sensoren in de gebieden van de ruimtes.", + "markers": "Markeringen", + "markers_none": "Geen", + "markers_important": "Belangrijk", + "markers_all": "Alle", + "furn_stool": "Kruk", + "furn_coffee_table": "Salontafel", + "furn_tv_wall": "Tv (wand)", + "furn_sideboard": "Dressoir", + "furn_table_round": "Ronde tafel", + "furn_bench": "Bank", + "furn_corner_bench": "Hoekbank", + "furn_bar_stool": "Barkruk", + "furn_kitchen_wall": "Bovenkast", + "furn_kitchen_tall": "Hoge kast met oven", + "furn_island": "Kookeiland", + "furn_dishwasher": "Vaatwasser", + "furn_bunk_bed": "Stapelbed", + "furn_dresser": "Ladekast", + "furn_washer": "Wasmachine", + "furn_dryer": "Droger", + "furn_office_chair": "Bureaustoel", + "furn_tall_cabinet": "Hoge kast", + "furn_coat_rack": "Kapstok", + "furn_group_living": "Wonen", + "furn_group_dining": "Eten", + "furn_group_energy": "Energie en zon", + "energy_devices": "Apparaten", + "wallbox_charging": "laadt", + "wallbox_plugged": "aangesloten", + "furn_soc": "Laadtoestand (%)", + "furn_export": "Terugleververmogen (W, aparte sensor, optioneel)", + "furn_export_hint": "Meldt je meter afname en teruglevering in twee sensoren (bijv. Growatt, Tibber Pulse), neem dan de afnamesensor als vermogen hierboven en de terugleversensor hier. Een sensor met teken heeft dit niet nodig.", + "meter_parent": "Hangt aan meter", + "meter_parent_none": "geen (hoofdmeter)", + "meter_main": "Hoofdmeter", + "meter_unmetered": "{w} niet gemeten", + "meter_device_hint": "Zit het apparaat achter een tussenmeter (bijv. een balkoncentrale in een appartement), dan telt zijn vermogen voor dat appartement. De tussenmeter moet daarvoor in beide richtingen meten (− = teruglevering); telt hij alleen afname, dan valt het verbruik van het appartement bij overschot te hoog uit.", + "meter_sub_power": "Vermogen van de groep (W, + = afgenomen, − = teruggeleverd)", + "meter_floors": "Voedt de verdiepingen", + "meter_sub_hint": "Een tussenmeter meet zijn groep, bijv. een appartement. Apparaten op de aangevinkte verdiepingen hangen er in 3D aan in plaats van aan de hoofdmeter; wat de hoofdmeter daarbuiten telt, verschijnt als „Gemeenschappelijk (rest)” in de balans.", + "furn_charge": "Laadvermogen (W, aparte sensor, optioneel)", + "furn_charge_hint": "Meldt je accu laden en ontladen in twee sensoren (bijv. Anker Solix), neem dan de ontlaadsensor als vermogen hierboven en de laadsensor hier. Een sensor met teken heeft dit niet nodig.", + "furn_wallbox_status": "Status (laadt, aangesloten)", + "energy_only_note": "⚡ Energie: hier kunnen alleen zonnevelden en energieapparaten worden verplaatst; ruimtes en meubels zijn vergrendeld.", + "roof_only_note": "🏠 Dak: hier kunnen alleen dakvlakken en dakramen worden verplaatst; ruimtes en meubels zijn vergrendeld.", + "energy_devices_hint": "Meter, omvormers, thuisaccu's, laadpalen en de netaansluiting worden hier toegevoegd: op de hierboven gekozen verdieping, verplaatsbaar in de plattegrond. Met een vermogenssensor tonen ze hun watt; de meter neemt de netsensor, een string kiest zijn omvormer. Meerdere omvormers en accu's (bijv. een extra balkoncentrale) werken ook: elk met een eigen sensor.", + "energy_routes": "Kabelroutes", + "energy_routes_hint": "Waar een kabel echt loopt: de stroom volgt dan jouw punten in plaats van een boog door het huis. Zonder route blijft de boog. Verbruikers houden hun boog.", + "route_conn_solar": "{name} → omvormer", + "route_conn_battery": "Batterij ↔ huis", + "route_conn_inverter": "Omvormer → huis", + "route_conn_grid": "Net ↔ huis", + "route_conn_meter": "{name} ↔ bovenliggende meter", + "route_conn_device": "{name} ↔ tussenmeter", + "route_points": "{n} punten", + "route_none": "directe boog", + "route_draw": "Route tekenen", + "route_redraw": "Opnieuw tekenen", + "route_drawing": "Tik in de plattegrond de punten aan waar de kabel langs loopt, van het ene eind naar het andere; wissel tussendoor van verdieping waar hij door een plafond gaat. {n} punten.", + "route_undo": "Laatste punt", + "route_done": "Klaar", + "route_cable": "Als kabel tonen", + "route_cable_hint": "Tekent de route als zichtbare kabel, niet alleen als de dunne lijn onder de deeltjes.", + "solar_fields": "Zonnevelden", + "solar_hint": "Leg panelen op het dak: ze liggen in de helling van het dakvlak; op een plat dak staan ze op frames. Sleep een veld in de plattegrond om het te verplaatsen.", + "solar_no_roof": "Zonnevelden hebben een dak nodig: een zadel- of plat dak onder Instellingen, of dakvlakken hier in het gereedschap Dak.", + "solar_face_gone": "dakvlak ontbreekt", + "solar_summary": "{n} panelen · {kwp} kWp", + "solar_add": "Zonneveld", + "solar_field": "Zonneveld", + "solar_face": "Dakvlak", + "solar_rows": "Rijen", + "solar_cols": "Panelen per rij", + "solar_portrait": "Staand", + "solar_landscape": "Liggend", + "solar_u": "Afstand tot de rand (m)", + "solar_v": "Afstand tot de goot (m)", + "solar_tilt": "Kanteling van de frames (°)", + "solar_rack_ew": "Oost-west-opstelling", + "solar_rack_ew_hint": "Elke tweede rij kijkt de andere kant op, de paren staan rug aan rug – laag en dicht, zoals op veel platte daken.", + "solar_rack_tilt": "Opstelling (° extra helling)", + "solar_flip": "Andersom laten hellen", + "solar_partial": "slechts {n} van {total} passen op het vlak", + "solar_form_hint": "Panelen die buiten het dakvlak zouden uitsteken, worden weggelaten. „Vlak vullen” legt zoveel panelen als er passen. kWp gerekend met 400 W per paneel.", + "solar_fit": "Vlak vullen", + "roof_windows": "Dakramen", + "roof_window": "Dakraam", + "roof_windows_hint": "Dakramen liggen in het dakvlak, met rolluik en contacten zoals ramen. Sleep ze in de plattegrond, ook naar een ander dakvlak.", + "roof_window_tilt": "Kiepcontact", + "roof_window_name": "Naam (optioneel)", + "roof_window_motor": "Raammotor (cover, optioneel)", + "roof_window_motor_hint": "Een raammotor (Velux, Roto, Fakro) meldt zijn positie als cover: de vleugel opent in 3D zo ver als de motor staat. Een contact of kiepcontact werkt ook zonder motor.", + "roof_window_hint": "Open zwaait de vleugel naar buiten, scharnierend aan de bovenkant; gekiept een beetje; het kozijn gloeit warm; het rolluik zakt van boven over het glas. In een dakvlak snijdt het raam een gat in de helling, zodat de zolder erdoor naar buiten kijkt.", + "solar_ground": "Vrijstaand (tuin, garagedak …)", + "solar_add_ground": "Vrijstaand", + "solar_base": "Hoogte van het vlak (m, 0 = grond)", + "solar_add_wall": "Aan een muur", + "solar_wall": "Muur", + "solar_v_wall": "Hoogte boven de vloer (m)", + "solar_tilt_wall": "Kanteling van de muur af (°, 90 = luifel)", + "solar_flip_wall": "Onderaan afstaand in plaats van bovenaan", + "solar_rotation": "Rotatie (°)", + "solar_name": "Naam", + "solar_name_hint": "bijv. string 1 zuid", + "solar_module_w": "Paneelbreedte (m)", + "solar_module_h": "Paneelhoogte (m)", + "solar_wp": "Paneelvermogen (Wp)", + "solar_string": "String", + "solar_strings": "Strings", + "solar_string_none": "Geen string", + "solar_string_new": "Nieuwe string", + "solar_string_n": "String {n}", + "solar_string_name": "Naam van de string", + "solar_string_entity": "PV-vermogen van de string", + "solar_string_inverter": "Omvormer", + "solar_string_inverter_none": "Geen omvormer gekozen", + "inverter_strings": "Strings op deze omvormer: {names}", + "inverter_strings_none": "Nog geen string op deze omvormer; wijs hem toe bij een zonneveld onder String › Omvormer.", + "solar_string_inverter_missing": "Nog geen omvormer in de plattegrond (voeg er hieronder een toe onder Apparaten)", + "solar_string_hint": "Velden in dezelfde string horen bij elkaar, ook op verschillende daken (bijv. 5 panelen op het huis en 5 op de garage). Sensor en omvormer gelden voor de hele string.", + "solar_string_sum": "{fields} velden · {n} panelen · {kwp} kWp", + "solar_face_size": "Dakvlak {w} × {h} m (langs de goot × de helling op)", + "solar_cols_hint": "Eén getal voor rijen van gelijke lengte, of een lijst voor eigen rijen: „4, 4, 3” (vanaf de goot).", + "solar_align_left": "Links", + "solar_align_center": "Midden", + "solar_align_right": "Rechts", + "solar_look_black": "Full black", + "solar_look_blue": "Blauw", + "solar_pick": "Panelen één voor één aan/uit", + "solar_pick_all": "Weer alle aan", + "solar_pick_hint": "Tik op een paneel in de plattegrond om het weg te halen of terug te zetten. Weggehaalde zijn gestreept.", + "solar_entity": "PV-vermogen van dit veld (bijv. zijn string)", + "solar_main": "Hoofddak", + "solar_section": "Vlak {n}", + "solar_flat": "plat dak", + "compass_n": "noord", + "compass_ne": "noordoost", + "compass_e": "oost", + "compass_se": "zuidoost", + "compass_s": "zuid", + "compass_sw": "zuidwest", + "compass_w": "west", + "compass_nw": "noordwest", + "furn_meter": "Elektriciteitsmeter", + "furn_grid_point": "Netaansluiting", + "grid_point_hint": "De netaansluiting staat hier: het overdrachtspunt naar het energiebedrijf, bijv. aan het eind van de oprit. Verplaatsbaar in de plattegrond.", + "furn_model": "Model", + "inverter_std": "Standaard (wandunit met display)", + "inverter_slim": "Smal en hoog (lichtstrook)", + "inverter_hybrid": "Hybride (ronde wijzerplaat, ventilatoren)", + "battery_std": "Toren (gestapelde modules)", + "battery_wall": "Wandaccu (plat, hangend)", + "battery_cube": "Compact (balkonaccu)", + "furn_inverter": "Zonne-omvormer", + "furn_home_battery": "Thuisaccu", + "furn_wallbox": "Laadpaal", + "furn_group_kitchen": "Keuken", + "furn_group_sleeping": "Slapen", + "furn_group_bath": "Bad en was", + "furn_group_work": "Werk en overig", + "furn_entity": "Apparaat (schakelaar, stekker …)", + "furn_state_entity": "Status van (optioneel)", + "furn_state_entity2": "Tweede status (de andere helft)", + "furn_state_split": "Helften", + "furn_state_left_right": "Links / rechts", + "furn_state_top_bottom": "Onder / boven (stapelbed)", + "furn_state_hint": "Het item gloeit zolang de entiteit aan, bezet of thuis meldt: een bed met bezettingsmat, een fauteuil, de sauna. Twee entiteiten verlichten de helften: links en rechts, onder en boven bij een stapelbed.", + "furn_entity_tv": "Tv (mediaspeler of slimme stekker)", + "fix": "Vastzetten", + "unfix": "Losmaken", + "fix_hint": "Vastgezet: kan niet meer per ongeluk worden verplaatst (toets L, rechtsklik of lang drukken)", + "fixed_drag_hint": "🔒 Vastgezet; maak het eerst los om het te verplaatsen (slot in het formulier, rechtsklik of toets L)", + "fixed_delete_confirm": "Dit item is vastgezet. Toch verwijderen?", + "lock_plan": "🔒 Plattegrond", + "lock_plan_hint": "Plattegrond vergrendelen: ruimtes, muren, deuren, ramen en buitengebieden kunnen niet per ongeluk worden verplaatst. Meubels en apparaten blijven vrij.", + "start_view": "Startweergave", + "start_view_hint": "De 3D-weergave, de kaart en de kiosk openen het huis met deze weergave, bijv. vanaf de tuinkant. Draai, zoom en verschuif het huis in het 3D-paneel rechts tot het past en onthoud het dan.", + "start_view_card": "Moet een kaart met een andere weergave openen, zet dan deze regel in haar YAML-configuratie.", + "start_view_set": "Huidige 3D-weergave als start onthouden", + "start_view_reset": "Standaard", + "start_view_saved": "Er is een eigen startweergave opgeslagen.", + "ctx_rotate": "90° draaien", + "devices_placed_in": "in {room}", + "devices_narrow": "nog {n}: verfijn de zoekopdracht", + "climate": "Ruimteklimaat", + "climate_temperature": "Temperatuur", + "climate_humidity": "Luchtvochtigheid", + "climate_co2": "CO₂", + "climate_hint": "Deze sensoren tellen voor de heatmap en het ruimtepaneel. „Automatisch” neemt de sensoren van het gebied en die in de ruimte geplaatst zijn, maar geen apparaattemperaturen (3D-printer, warmtepomp, aanvoer …).", + "climate_more": "… en nog een sensor (gemiddelde)", + "plan_locked": "Plattegrond vergrendeld", + "plan_lock": "Plattegrond vergrendelen", + "plan_unlock": "Plattegrond ontgrendelen", + "opening_mark": "Markeren in 3D", + "opening_mark_open": "Als het open is", + "opening_mark_closed": "Als het dicht is (bijv. wc)", + "opening_mark_hint": "Een gemarkeerd raam of gemarkeerde deur gloeit warm. „Als het dicht is” heeft een contact nodig; zonder sensor wordt niets gemarkeerd.", + "window_opens": "Opent", + "window_opens_turn": "Draai-kiep (naar binnen)", + "window_opens_slide": "Schuivend (schuifraam, hefschuifpui)", + "window_opens_top": "Uitzetraam (onderkant naar buiten)", + "window_opens_hint": "Schuivend: het raam aan de scharnierkant schuift voor het vaste; met twee vleugels schuiven de middelste twee naar buiten. Uitzetramen openen met hun contact of een kiepsensor.", + "marker_show": "Markering in 3D", + "marker_show_hint": "Automatisch volgt de schakelaar Geen / Belangrijk / Alle van de 3D-weergave. Altijd tonen en Verbergen gelden hoe dan ook (behalve bij Geen).", + "pin_shift": "Pin verplaatsen", + "pin_shift_up": "↑ hoogte", + "pin_shift_hint": "Staan apparaten dicht bij elkaar, schuif de pin hier een stukje opzij of omhoog (in meters); het apparaat zelf blijft staan.", + "marker_show_auto": "Automatisch", + "marker_show_always": "Altijd tonen", + "marker_show_no_power": "Zonder watt", + "marker_show_active": "Alleen als actief", + "marker_show_never": "Verbergen", + "marker_icon": "Eigen symbool (Material Design-pictogram)", + "device_name": "Eigen naam (optioneel)", + "show_name": "Naam onder de markering in 3D tonen", + "card_marker_names": "Eigen namen bij de markeringen", + "card_marker_names_hint": "Elk apparaat met een eigen naam toont die klein onder zijn markering; drie thermometers in de tuin blijven uit elkaar te houden.", + "device_name_hint": "Een naam alleen voor de plattegrond en het kamerpaneel, bijv. \"Accentlicht eiland\"; de entiteit in Home Assistant blijft zoals ze is.", + "device_simple": "Alleen schakelen in het kamerpaneel", + "device_simple_hint": "Het kamerpaneel toont voor deze lamp alleen de schakelaar, zonder helderheid, kleurtemperatuur en kleuren.", + "floor_turn": "90° draaien", + "floor_shift_all": "Alle verdiepingen meenemen (hele huis)", + "floor_shift_all_hint": "Verschuiven en draaien werken op alle verdiepingen met dakvlakken, buitengebieden, energieapparaten en meter: het hele huis beweegt als één geheel.", + "floor_turn_hint": "Draait alles op de verdieping 90° met de klok mee om het midden van haar ruimtes, als een verdieping verkeerd om getekend is. Drie keer = 270°.", + "marker_icon_hint": "De naam van een Material Design-pictogram zoals in Home Assistant, bijv. mdi:thermometer of mdi:water-alert. Leeg = het symbool van het apparaattype.", + "furn_power": "Vermogenssensor (W)", + "furn_links_hint": "Met een vermogenssensor toont het item zijn watt en doet het mee in de energiestroom.", + "furn_links_hint_tv": "Het scherm gloeit zolang de tv aan is, in de kleur van de app (Netflix, YouTube …); het label toont de app of titel.", + "stairs_hint": "De trap stijgt naar achteren (weg van de gemarkeerde voorrand) en opent het plafond van de verdieping erboven.", + "floor_lights": "{n} lampen aan", + "floor_open": "{n} open", + "floor_persons": "{n} personen", + "energy_consumption": "Verbruik", + "energy_grid_import": "Netafname", + "energy_grid_export": "Teruglevering", + "energy_solar": "Zon", + "energy_battery": "Accu", + "energy_tariff": "Tarief", + "energy": "Energie", + "energy_meter": "Meter", + "energy_grid": "Net (W, + = afname)", + "energy_solar_sensor": "Zonne-opbrengst (W)", + "energy_battery_sensor": "Accuvermogen (W, + = ontladen)", + "energy_battery_soc": "Accu-laadstand (%)", + "energy_tariff_sensor": "Tarief (bijv. €/kWh)", + "energy_gas": "Gasmeter (optioneel)", + "energy_water": "Watermeter (optioneel)", + "energy_meters_hint": "Gas en water staan bij de huisbalans – in de energiebalk en op de huiskaart: een sensor met het debiet nu (m³/u, l/min) of de meterstand van vandaag.", + "energy_gas_short": "Gas", + "energy_water_short": "Water", + "energy_invert": "Teken omdraaien", + "energy_hint": "Verbruikers zijn geplaatste apparaten met een vermogenssensor (W): de sensor zelf of een van hetzelfde apparaat.", + "energy_balance": "Energiebalans", + "energy_balance_hint": "Net, zon en accu komen van de apparaten in de plattegrond: meter, omvormer en thuisaccu. Hier kun je andere sensoren kiezen, tekens omdraaien en het huisverbruik instellen.", + "energy_rest": "Gemeenschappelijk (rest)", + "energy_advanced": "Geavanceerde energiemodus", + "energy_advanced_on": "Tussenmeters gebruiken", + "energy_show_unmetered": "Niet-gemeten verbruik bij tussenmeters tonen", + "energy_show_unmetered_hint": "Het label van een tussenmeter toont dan wat zijn verdiepingen verbruiken en hoeveel daarvan door geen geplaatst apparaat wordt gemeten, bijv. „500 W · 450 W niet gemeten”. Anders toont het de meterstand.", + "energy_advanced_hint": "Voor tussenmeters, bijv. één per appartement achter een hoofdmeter: een meter kan dan aan een andere hangen en eigen verdiepingen voeden. Uit = de eerste meter is de netaansluiting, verdere zijn verbruikers.", + "energy_consumption_sensor": "Huisverbruik (W, anders uit de balans)", + "energy_import_prefs": "Overnemen uit het energiedashboard", + "energy_import_done": "{n} sensoren overgenomen; controleer de tekens.", + "energy_import_none": "In het energiedashboard zijn geen passende vermogenssensoren (W) gevonden; kies ze met de hand.", + "energy_import_failed": "Het energiedashboard van Home Assistant is niet ingesteld.", + "tool_meter": "Meter", + "hint_meter": "Tik op de plek van de meter", + "presence": "Aanwezigheid", + "presence_hint": "Ruimtesensor per persoon (bijv. ESPresense, Bermuda): de status noemt de ruimte of het gebied.", + "presence_sensor": "Ruimtesensor", + "no_persons": "Er zijn geen personen in Home Assistant.", + "packname:nextfloor.a_bad": "Badkamer", + "pack:nextfloor.a_bad:vanity_60": "Wastafelmeubel 60 met onderkast", + "pack:nextfloor.a_bad:vanity_80": "Wastafelmeubel 80 met onderkast", + "pack:nextfloor.a_bad:vanity_100": "Wastafelmeubel 100 met onderkast", + "pack:nextfloor.a_bad:vanity_double_120": "Dubbele wastafel 120", + "pack:nextfloor.a_bad:vanity_double_160": "Dubbele wastafel", + "pack:nextfloor.a_bad:pedestal_basin": "Zuilwastafel", + "pack:nextfloor.a_bad:bathtub_builtin": "Inbouwbad", + "pack:nextfloor.a_bad:bathtub_corner": "Hoekbad", + "pack:nextfloor.a_bad:bathtub_corner_compact": "Ruimtebesparend hoekbad", + "pack:nextfloor.a_bad:bathtub_free": "Vrijstaand bad", + "pack:nextfloor.a_bad:whirlpool_indoor": "Whirlpool binnen", + "pack:nextfloor.a_bad:shower_corner_90": "Hoekdouche 90 × 90", + "pack:nextfloor.a_bad:shower_niche_120": "Nisdouche 120 × 90", + "pack:nextfloor.a_bad:shower_walkin_140": "Inloopdouche 140 × 90", + "pack:nextfloor.a_bad:shower_walkin_120": "Inloopdouche", + "pack:nextfloor.a_bad:shower_rain_led": "Regendouche met led", + "pack:nextfloor.a_bad:toilet_close": "Staand toilet", + "pack:nextfloor.a_bad:toilet_hung": "Hangtoilet", + "pack:nextfloor.a_bad:toilet_hung_compact": "Hangtoilet (compact)", + "pack:nextfloor.a_bad:bidet": "Bidet", + "pack:nextfloor.a_bad:cabinet_tall": "Hoge badkamerkast", + "pack:nextfloor.a_bad:cabinet_mid": "Halfhoge badkamerkast", + "pack:nextfloor.a_bad:mirror_round_light": "Ronde spiegel met licht", + "pack:nextfloor.a_bad:mirror_80": "Spiegel 80 × 60 met licht", + "pack:nextfloor.a_bad:mirror_led_100": "Ledspiegel 100 × 70 met klok", + "pack:nextfloor.a_bad:mirror_cabinet": "Spiegelkast met licht", + "pack:nextfloor.a_bad:wall_shelf_bath": "Badkamerwandplank", + "pack:nextfloor.a_bad:towel_rail": "Handdoekrek met handdoek", + "pack:nextfloor.a_bad:towel_radiator": "Handdoekradiator", + "pack:nextfloor.a_bad:towel_heater_electric": "Elektrische handdoekverwarmer", + "pack:nextfloor.a_bad:sauna": "Sauna", + "pack:nextfloor.a_bad:bath_fan": "Badkamerventilator", + "pack:nextfloor.a_bad:washer_cabinet": "Wasmachinekast", + "pack:nextfloor.a_bad:washer_under_vanity": "Wasmachine onder de wastafel", + "pack:nextfloor.a_bad:laundry_basket": "Wasmand", + "pack:nextfloor.a_bad:laundry_cabinet": "Waskast met mand", + "pack:nextfloor.a_bad:ladder_shelf": "Ladderrek met handdoeken", + "pack:nextfloor.a_bad:plant_stool": "Plant op kruk", + "packname:nextfloor.a_buero": "Kantoor en gaming", + "pack:nextfloor.a_buero:desk_standing": "Zit-sta-bureau", + "pack:nextfloor.a_buero:desk_standing_bare": "Zit-sta-bureau zonder monitor", + "pack:nextfloor.a_buero:chair_gaming": "Gamingstoel", + "pack:nextfloor.a_buero:chair_office": "Ergonomische bureaustoel", + "pack:nextfloor.a_buero:sim_cockpit": "Simracing-cockpit", + "pack:nextfloor.a_buero:server_rack_42u": "Serverrack (42U)", + "pack:nextfloor.a_buero:filing_cabinet": "Archiefkast", + "pack:nextfloor.a_buero:whiteboard": "Whiteboard", + "pack:nextfloor.a_buero:triple_monitor": "Opstelling met drie monitoren", + "pack:nextfloor.a_buero:bookcase_wall": "Boekenwand", + "pack:nextfloor.a_buero:desk_lamp": "Bureaulamp", + "pack:nextfloor.a_buero:desk_lamp_led": "Led-bureaulamp", + "pack:nextfloor.a_buero:arcade_cabinet": "Arcadekast", + "pack:nextfloor.a_buero:office_lounge_sofa": "Loungebank voor kantoor", + "pack:nextfloor.a_buero:monitor_light_bar": "Monitor met lichtbalk", + "pack:nextfloor.a_buero:printer_laser": "Laserprinter", + "pack:nextfloor.a_buero:wifi_router": "Wifi-router", + "pack:nextfloor.a_buero:phone_booth": "Belcel", + "pack:nextfloor.a_buero:printer_3d": "3D-printer", + "pack:nextfloor.a_buero:printer_cube": "Gesloten kubus-3D-printer", + "pack:nextfloor.a_buero:printer_multi": "Kubus-3D-printer met meerkleurenunit", + "pack:nextfloor.a_buero:printer_large": "Grote 3D-printer met dubbele nozzle", + "pack:nextfloor.a_buero:printer_open": "Compacte open 3D-printer", + "pack:nextfloor.a_buero:printer_resin": "Hars-3D-printer", + "pack:nextfloor.a_buero:filament_dryer": "Filamentdroger", + "pack:nextfloor.a_buero:filament_rack": "Filamentwandrek", + "packname:nextfloor.a_fitness": "Fitness", + "pack:nextfloor.a_fitness:treadmill": "Loopband", + "pack:nextfloor.a_fitness:power_rack": "Powerrack met bank", + "pack:nextfloor.a_fitness:rowing_machine": "Roeitrainer", + "pack:nextfloor.a_fitness:spin_bike": "Spinningfiets", + "pack:nextfloor.a_fitness:dumbbell_rack": "Dumbbellrek", + "pack:nextfloor.a_fitness:punching_bag": "Bokszak", + "pack:nextfloor.a_fitness:yoga_mat": "Yogamat met blok", + "pack:nextfloor.a_fitness:elliptical": "Crosstrainer", + "pack:nextfloor.a_fitness:mirror_wall_gym": "Spiegelwand", + "pack:nextfloor.a_fitness:exercise_ball": "Fitnessbal", + "pack:nextfloor.a_fitness:wall_bars": "Wandrek", + "pack:nextfloor.a_fitness:fitness_mirror_smart": "Slimme fitnessspiegel", + "pack:nextfloor.a_fitness:bike_trainer": "Fiets op smart trainer", + "pack:nextfloor.a_fitness:sauna_cabin": "Saunacabine", + "pack:nextfloor.a_fitness:massage_chair": "Massagestoel", + "pack:nextfloor.a_fitness:kettlebells": "Kettlebellset", + "pack:nextfloor.a_fitness:water_cooler": "Waterkoeler", + "packname:nextfloor.a_garten": "Tuin en terras", + "pack:nextfloor.a_garten:grill_gas": "Gasbarbecue", + "pack:nextfloor.a_garten:lounge_set": "Loungeset", + "pack:nextfloor.a_garten:sun_lounger_adj": "Ligbed", + "pack:nextfloor.a_garten:parasol": "Parasol", + "pack:nextfloor.a_garten:pergola": "Pergola", + "pack:nextfloor.a_garten:raised_bed": "Moestuinbak", + "pack:nextfloor.a_garten:greenhouse": "Kas", + "pack:nextfloor.a_garten:hot_tub": "Buitenjacuzzi", + "pack:nextfloor.a_garten:fire_bowl": "Vuurschaal", + "pack:nextfloor.a_garten:garden_torch": "Tuinfakkel", + "pack:nextfloor.a_garten:play_tower": "Speeltoren met glijbaan", + "pack:nextfloor.a_garten:garden_shed": "Tuinhuis", + "pack:nextfloor.a_garten:trampoline": "Trampoline", + "pack:nextfloor.a_garten:flower_pots": "Bloempotten (set van 3)", + "pack:nextfloor.a_garten:sprinkler": "Gazonsproeier", + "pack:nextfloor.a_garten:valve_box": "Beregeningsventielbox", + "pack:nextfloor.a_garten:rain_barrel": "Regenton", + "pack:nextfloor.a_garten:garden_lantern": "Tuinlantaarn", + "pack:nextfloor.a_garten:outdoor_kitchen": "Buitenkeuken", + "pack:nextfloor.a_garten:hammock": "Hangmat met standaard", + "pack:nextfloor.a_garten:patio_heater": "Terrasverwarmer", + "pack:nextfloor.a_garten:tree_oak": "Eik", + "pack:nextfloor.a_garten:tree_lime": "Linde", + "pack:nextfloor.a_garten:tree_birch": "Berk", + "pack:nextfloor.a_garten:tree_maple": "Esdoorn", + "pack:nextfloor.a_garten:tree_fruit": "Fruitboom", + "pack:nextfloor.a_garten:tree_spruce": "Spar", + "pack:nextfloor.a_garten:tree_pine": "Den", + "pack:nextfloor.a_garten:tree_thuja": "Thuja (levensboom)", + "pack:nextfloor.a_garten:shrub": "Struik", + "pack:nextfloor.a_garten:shrub_flowering": "Bloeiende struik", + "pack:nextfloor.a_garten:brush_wild": "Kreupelhout (wilde hoek)", + "pack:nextfloor.a_garten:tree_group_3": "Groep bomen (3)", + "pack:nextfloor.a_garten:bin_rest_120": "Restafvalcontainer 120 l", + "pack:nextfloor.a_garten:bin_rest_240": "Restafvalcontainer 240 l", + "pack:nextfloor.a_garten:bin_bio_120": "Gft-container 120 l", + "pack:nextfloor.a_garten:bin_bio_240": "Gft-container 240 l", + "pack:nextfloor.a_garten:bin_paper_120": "Papiercontainer 120 l", + "pack:nextfloor.a_garten:bin_paper_240": "Papiercontainer 240 l", + "pack:nextfloor.a_garten:bin_yellow_120": "Plasticcontainer 120 l", + "pack:nextfloor.a_garten:bin_yellow_240": "Plasticcontainer 240 l", + "pack:nextfloor.a_garten:mailbox": "Brievenbus", + "pack:nextfloor.a_garten:mailbox_post": "Brievenbus op paal", + "pack:nextfloor.a_garten:awning_300": "Zonnescherm 3 m", + "pack:nextfloor.a_garten:awning_400": "Zonnescherm 4 m", + "pack:nextfloor.a_garten:awning_500": "Zonnescherm 5 m", + "pack:nextfloor.a_garten:sliding_gate": "Schuifpoort", + "packname:nextfloor.a_haustechnik": "Huishouding en installaties", + "pack:nextfloor.a_haustechnik:gas_boiler": "Gascondensatieketel", + "pack:nextfloor.a_haustechnik:heat_pump_tower": "Warmtepomp-binnenunit (hydrotoren)", + "pack:nextfloor.a_haustechnik:buffer_tank": "Buffervat", + "pack:nextfloor.a_haustechnik:heating_manifold": "Vloerverwarmingsverdeler", + "pack:nextfloor.a_haustechnik:ventilation_unit": "Ventilatie met warmteterugwinning", + "pack:nextfloor.a_haustechnik:split_indoor": "Split-airco (binnenunit, aan de muur)", + "pack:nextfloor.a_haustechnik:split_outdoor": "Split-airco (buitenunit)", + "pack:nextfloor.a_haustechnik:radiator_tall": "Hoge designradiator", + "pack:nextfloor.a_haustechnik:meter_cabinet": "Meterkast", + "pack:nextfloor.a_haustechnik:water_softener": "Waterontharder", + "pack:nextfloor.a_haustechnik:water_pump": "Hydrofoorpomp", + "pack:nextfloor.a_haustechnik:drip_tray": "Lekbak met lekkagesensor", + "pack:nextfloor.a_haustechnik:chest_freezer": "Vrieskist", + "pack:nextfloor.a_haustechnik:ironing_station": "Stoomstrijkstation", + "pack:nextfloor.a_haustechnik:drying_rack": "Droogrek", + "pack:nextfloor.a_haustechnik:rotary_line": "Droogmolen", + "pack:nextfloor.a_haustechnik:pantry_shelf_util": "Voorraadrek", + "pack:nextfloor.a_haustechnik:utility_sink": "Uitstortgootsteen", + "pack:nextfloor.a_haustechnik:laundry_basket_util": "Wasmand", + "pack:nextfloor.a_haustechnik:vacuum_station": "Station voor snoerloze stofzuiger", + "packname:nextfloor.a_haustiere": "Huisdieren", + "pack:nextfloor.a_haustiere:cat_tree_large": "Krabpaal (groot)", + "pack:nextfloor.a_haustiere:scratch_post": "Krabpaal", + "pack:nextfloor.a_haustiere:scratch_board_wall": "Krabplank (wand)", + "pack:nextfloor.a_haustiere:cat_cave": "Kattengrot", + "pack:nextfloor.a_haustiere:cat_bed_round": "Rond kattenbed", + "pack:nextfloor.a_haustiere:cat_wall_shelf": "Kattenwandplank", + "pack:nextfloor.a_haustiere:cat_steps": "Kattentrapjes", + "pack:nextfloor.a_haustiere:litter_covered": "Overdekte kattenbak", + "pack:nextfloor.a_haustiere:litter_auto": "Zelfreinigende kattenbak", + "pack:nextfloor.a_haustiere:dog_bed": "Hondenbed", + "pack:nextfloor.a_haustiere:dog_basket": "Hondenmand", + "pack:nextfloor.a_haustiere:dog_house": "Hondenhok", + "pack:nextfloor.a_haustiere:pet_bowls": "Voer- en waterbak", + "pack:nextfloor.a_haustiere:pet_feeder": "Automatische voerbak", + "pack:nextfloor.a_haustiere:pet_fountain": "Drinkfontein voor huisdieren", + "pack:nextfloor.a_haustiere:pet_gate": "Huisdierenhekje", + "pack:nextfloor.a_haustiere:pet_stairs": "Huisdierentrapje", + "pack:nextfloor.a_haustiere:hamster_cage": "Hamsterkooi", + "pack:nextfloor.a_haustiere:small_animal_cage": "Knaagdierenkooi", + "pack:nextfloor.a_haustiere:rabbit_run": "Konijnenren (buiten)", + "pack:nextfloor.a_haustiere:bird_cage": "Vogelkooi", + "pack:nextfloor.a_haustiere:aquarium_100": "Aquarium 100 l", + "pack:nextfloor.a_haustiere:aquarium_240": "Aquarium 240 l met kast", + "pack:nextfloor.a_haustiere:terrarium": "Terrarium", + "pack:nextfloor.a_haustiere:pet_cat": "Kat (loopt rond)", + "pack:nextfloor.a_haustiere:pet_dog": "Hond (loopt rond)", + "pack:nextfloor.a_haustiere:pet_rabbit": "Konijn (hupt rond)", + "packname:nextfloor.a_kinderzimmer": "Kinderkamer", + "pack:nextfloor.a_kinderzimmer:loft_bed_slide": "Hoogslaper met glijbaan", + "pack:nextfloor.a_kinderzimmer:teepee": "Tipitent", + "pack:nextfloor.a_kinderzimmer:play_kitchen": "Speelkeuken", + "pack:nextfloor.a_kinderzimmer:kids_desk": "Kinderbureau", + "pack:nextfloor.a_kinderzimmer:toy_shelf": "Speelgoedrek met bakken", + "pack:nextfloor.a_kinderzimmer:cosy_corner": "Knusse hoek", + "pack:nextfloor.a_kinderzimmer:rocking_horse": "Hobbelpaard", + "pack:nextfloor.a_kinderzimmer:play_mat_road": "Verkeerskleed", + "pack:nextfloor.a_kinderzimmer:kids_table_2": "Kindertafel met 2 stoelen", + "pack:nextfloor.a_kinderzimmer:moon_light": "Maan-nachtlampje", + "pack:nextfloor.a_kinderzimmer:ball_pit": "Ballenbak", + "pack:nextfloor.a_kinderzimmer:house_bed": "Huisbed", + "pack:nextfloor.a_kinderzimmer:baby_monitor": "Babyfoon met camera", + "pack:nextfloor.a_kinderzimmer:star_projector": "Sterrenprojector", + "pack:nextfloor.a_kinderzimmer:kids_cot": "Babybedje", + "pack:nextfloor.a_kinderzimmer:kids_changing_table": "Commode", + "pack:nextfloor.a_kinderzimmer:kids_wardrobe": "Kinderkledingkast", + "pack:nextfloor.a_kinderzimmer:toy_boxes_3": "Speelgoedkisten (3)", + "packname:nextfloor.a_kino": "Thuisbioscoop en hifi", + "pack:nextfloor.a_kino:screen_wall": "Projectiescherm (wand)", + "pack:nextfloor.a_kino:screen_roll": "Oprolbaar projectiescherm", + "pack:nextfloor.a_kino:projector_ceiling": "Projector (plafond)", + "pack:nextfloor.a_kino:projector_table": "Projector (tafel)", + "pack:nextfloor.a_kino:speaker_floor": "Vloerstaande speaker", + "pack:nextfloor.a_kino:speaker_shelf": "Boekenplankspeaker", + "pack:nextfloor.a_kino:speaker_centre": "Centerspeaker", + "pack:nextfloor.a_kino:subwoofer": "Subwoofer", + "pack:nextfloor.a_kino:soundbar": "Soundbar", + "pack:nextfloor.a_kino:soundbar_premium": "Premium soundbar", + "pack:nextfloor.a_kino:speaker_wall": "Wandspeaker", + "pack:nextfloor.a_kino:speaker_ceiling": "Plafondspeaker", + "pack:nextfloor.a_kino:av_receiver": "AV-receiver", + "pack:nextfloor.a_kino:turntable": "Platenspeler", + "pack:nextfloor.a_kino:record_shelf": "Platenkast", + "pack:nextfloor.a_kino:game_console": "Spelconsole", + "pack:nextfloor.a_kino:hifi_rack": "Hifi-meubel", + "pack:nextfloor.a_kino:cinema_seat": "Bioscoopstoel", + "pack:nextfloor.a_kino:cinema_row_3": "Rij bioscoopstoelen (3)", + "pack:nextfloor.a_kino:acoustic_panel": "Akoestisch paneel", + "pack:nextfloor.a_kino:bass_trap": "Bass trap (hoek)", + "pack:nextfloor.a_kino:popcorn_maker": "Popcornmachine", + "pack:nextfloor.a_kino:star_ceiling": "Sterrenplafond", + "pack:nextfloor.a_kino:smart_speaker_ball": "Slimme speaker (bol)", + "pack:nextfloor.a_kino:smart_speaker_cylinder": "Slimme speaker (cilinder)", + "pack:nextfloor.a_kino:smart_speaker_puck": "Slimme speaker (puck)", + "pack:nextfloor.a_kino:smart_speaker_pod": "Slimme speaker (pod)", + "pack:nextfloor.a_kino:smart_speaker_tall": "Slimme speaker (hoog)", + "pack:nextfloor.a_kino:smart_speaker_oval": "Slimme speaker (ovaal)", + "pack:nextfloor.a_kino:multiroom_compact": "Compacte multiroomspeaker", + "pack:nextfloor.a_kino:speaker_portable": "Draagbare speaker", + "pack:nextfloor.a_kino:display_5": "Smart display 5″", + "pack:nextfloor.a_kino:display_8": "Smart display 8″", + "pack:nextfloor.a_kino:display_7_float": "Smart display 7″ (zwevend)", + "pack:nextfloor.a_kino:display_15_wall": "Smart display 15″ (wand)", + "pack:nextfloor.a_kino:speaker_stand": "Speakerstandaard", + "packname:nextfloor.a_kueche": "Keuken", + "pack:nextfloor.a_kueche:base_30": "Onderkast 30", + "pack:nextfloor.a_kueche:base_40": "Onderkast 40", + "pack:nextfloor.a_kueche:base_50": "Onderkast 50", + "pack:nextfloor.a_kueche:base_60": "Onderkast 60", + "pack:nextfloor.a_kueche:base_80": "Onderkast 80", + "pack:nextfloor.a_kueche:base_90": "Onderkast 90", + "pack:nextfloor.a_kueche:base_100": "Onderkast 100", + "pack:nextfloor.a_kueche:base_120": "Onderkast 120", + "pack:nextfloor.a_kueche:drawer_40": "Ladekast 40", + "pack:nextfloor.a_kueche:drawer_50": "Ladekast 50", + "pack:nextfloor.a_kueche:drawer_60": "Ladekast 60", + "pack:nextfloor.a_kueche:drawer_80": "Ladekast 80", + "pack:nextfloor.a_kueche:drawer_90": "Ladekast 90", + "pack:nextfloor.a_kueche:drawer_100": "Ladekast 100", + "pack:nextfloor.a_kueche:drawer_120": "Ladekast 120", + "pack:nextfloor.a_kueche:sink_60": "Spoelbakkast 60", + "pack:nextfloor.a_kueche:sink_80": "Spoelbakkast 80", + "pack:nextfloor.a_kueche:sink_100": "Spoelbakkast 100", + "pack:nextfloor.a_kueche:hob_60": "Kookplaatkast 60", + "pack:nextfloor.a_kueche:hob_80": "Kookplaatkast 80", + "pack:nextfloor.a_kueche:cooker_60": "Fornuis met oven 60", + "pack:nextfloor.a_kueche:dishwasher_60": "Inbouwvaatwasser 60", + "pack:nextfloor.a_kueche:dishwasher_45": "Inbouwvaatwasser 45", + "pack:nextfloor.a_kueche:base_corner": "Hoekonderkast", + "pack:nextfloor.a_kueche:wall_40": "Bovenkast 40", + "pack:nextfloor.a_kueche:wall_50": "Bovenkast 50", + "pack:nextfloor.a_kueche:wall_60": "Bovenkast 60", + "pack:nextfloor.a_kueche:wall_80": "Bovenkast 80", + "pack:nextfloor.a_kueche:wall_90": "Bovenkast 90", + "pack:nextfloor.a_kueche:wall_100": "Bovenkast 100", + "pack:nextfloor.a_kueche:wall_120": "Bovenkast 120", + "pack:nextfloor.a_kueche:wall_glass_80": "Glazen bovenkast 80", + "pack:nextfloor.a_kueche:wall_corner": "Hoekbovenkast", + "pack:nextfloor.a_kueche:hood_wall": "Wandafzuigkap", + "pack:nextfloor.a_kueche:hood_island": "Eilandafzuigkap", + "pack:nextfloor.a_kueche:tall_pantry": "Hoge voorraadkast", + "pack:nextfloor.a_kueche:tall_oven": "Hoge kast oven en magnetron", + "pack:nextfloor.a_kueche:tall_fridge": "Hoge kast koel-vriescombinatie", + "pack:nextfloor.a_kueche:tall_steam": "Hoge kast stoom en oven", + "pack:nextfloor.a_kueche:fridge_freezer": "Koel-vriescombinatie", + "pack:nextfloor.a_kueche:fridge_french": "French-door-koelkast", + "pack:nextfloor.a_kueche:wine_fridge": "Wijnklimaatkast", + "pack:nextfloor.a_kueche:glass_cabinet": "Vitrinekast", + "pack:nextfloor.a_kueche:row_270": "Keukenblok 270", + "pack:nextfloor.a_kueche:row_330": "Keukenblok 330", + "pack:nextfloor.a_kueche:island_bar": "Kookeiland met bar", + "pack:nextfloor.a_kueche:island_hob": "Kookeiland met kookplaat", + "pack:nextfloor.a_kueche:breakfast_bar": "Ontbijtbar (wand)", + "pack:nextfloor.a_kueche:bar_stools_2": "Barkrukken (set van 2)", + "pack:nextfloor.a_kueche:dining_bench_long": "Lange eettafel met bank", + "pack:nextfloor.a_kueche:dining_round_4": "Ronde eettafel met 4 stoelen", + "pack:nextfloor.a_kueche:high_table_2": "Statafel met 2 krukken", + "pack:nextfloor.a_kueche:kitchen_trolley": "Keukentrolley", + "pack:nextfloor.a_kueche:pantry_shelf": "Voorraadrek", + "pack:nextfloor.a_kueche:spice_rack": "Kruidenrek (wand)", + "pack:nextfloor.a_kueche:coffee_machine": "Volautomatische koffiemachine", + "pack:nextfloor.a_kueche:microwave": "Magnetron", + "pack:nextfloor.a_kueche:stand_mixer": "Keukenmachine", + "pack:nextfloor.a_kueche:kettle": "Waterkoker", + "pack:nextfloor.a_kueche:toaster": "Broodrooster", + "pack:nextfloor.a_kueche:herb_garden": "Slimme kruidentuin", + "pack:nextfloor.a_kueche:pendant_trio": "Trio hanglampen", + "pack:nextfloor.a_kueche:pendant_linear": "Lineaire hanglamp", + "pack:nextfloor.a_kueche:cabinet_light_60": "Led-onderbouwlamp 60", + "pack:nextfloor.a_kueche:cabinet_light_80": "Led-onderbouwlamp 80", + "pack:nextfloor.a_kueche:range_cooker_90": "Fornuis 90", + "packname:nextfloor.a_schlafzimmer": "Slaapkamer", + "pack:nextfloor.a_schlafzimmer:bed_90": "Bed 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_140": "Bed 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_160": "Bed 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_180": "Bed 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_200": "Bed 200 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_180": "Gestoffeerd bed 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_140": "Gestoffeerd bed 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_boxspring": "Boxspring 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_futon": "Futonbed 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_storage": "Bed met opbergruimte 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_canopy": "Hemelbed", + "pack:nextfloor.a_schlafzimmer:bed_ambient": "Bed 180 met sfeerverlichting", + "pack:nextfloor.a_schlafzimmer:bed_bench": "Bedbank", + "pack:nextfloor.a_schlafzimmer:shoe_bench": "Schoenenbank", + "pack:nextfloor.a_schlafzimmer:wardrobe_2": "2-deurs kledingkast", + "pack:nextfloor.a_schlafzimmer:wardrobe_3": "3-deurs kledingkast", + "pack:nextfloor.a_schlafzimmer:wardrobe_4": "4-deurs kledingkast", + "pack:nextfloor.a_schlafzimmer:wardrobe_6": "6-deurs kledingkast", + "pack:nextfloor.a_schlafzimmer:wardrobe_mirror": "Kledingkast met spiegeldeur", + "pack:nextfloor.a_schlafzimmer:wardrobe_sliding": "Schuifdeurkast", + "pack:nextfloor.a_schlafzimmer:wardrobe_light": "Kledingkast met binnenverlichting", + "pack:nextfloor.a_schlafzimmer:wardrobe_corner": "Hoekkledingkast", + "pack:nextfloor.a_schlafzimmer:walk_in_closet": "Open inloopkast", + "pack:nextfloor.a_schlafzimmer:clothes_rail": "Kledingrek", + "pack:nextfloor.a_schlafzimmer:nightstand": "Nachtkastje met lade", + "pack:nextfloor.a_schlafzimmer:nightstand_slim": "Smal nachtkastje", + "pack:nextfloor.a_schlafzimmer:nightstand_floating": "Zwevend nachtkastje", + "pack:nextfloor.a_schlafzimmer:dresser_6": "Ladekast met 6 lades 140", + "pack:nextfloor.a_schlafzimmer:chest_tall_5": "Hoge ladekast met 5 lades", + "pack:nextfloor.a_schlafzimmer:chest_tall": "Hoge ladekast", + "pack:nextfloor.a_schlafzimmer:chest_80": "Ladekast met 3 lades 80", + "pack:nextfloor.a_schlafzimmer:vanity_table": "Kaptafel met spiegel", + "pack:nextfloor.a_schlafzimmer:dressing_table_light": "Kaptafel met spiegelverlichting", + "pack:nextfloor.a_schlafzimmer:cot": "Babybedje", + "pack:nextfloor.a_schlafzimmer:changing_table": "Commode", + "pack:nextfloor.a_schlafzimmer:standing_mirror": "Staande spiegel", + "pack:nextfloor.a_schlafzimmer:reading_nook": "Leeshoek met stoel", + "pack:nextfloor.a_schlafzimmer:bedside_lamp": "Bedlampje", + "pack:nextfloor.a_schlafzimmer:touch_lamp": "Touch-bedlampje", + "pack:nextfloor.a_schlafzimmer:humidifier": "Luchtbevochtiger", + "pack:nextfloor.a_schlafzimmer:sunrise_clock": "Wake-up light", + "packname:nextfloor.a_smart": "Smart home en techniek", + "pack:nextfloor.a_smart:wallbox": "Laadpaal", + "pack:nextfloor.a_smart:electric_car": "Elektrische auto", + "pack:nextfloor.a_smart:heat_pump_outdoor": "Warmtepomp (buitenunit)", + "pack:nextfloor.a_smart:home_battery": "Thuisaccu", + "pack:nextfloor.a_smart:inverter_solar": "Zonne-omvormer", + "pack:nextfloor.a_smart:robot_vacuum": "Robotstofzuiger met dock", + "pack:nextfloor.a_smart:mower_garage": "Robotmaaier met garage", + "pack:nextfloor.a_smart:washer_dryer_stack": "Was-droogzuil", + "pack:nextfloor.a_smart:network_rack": "Netwerkrack", + "pack:nextfloor.a_smart:smart_display": "Smart display", + "pack:nextfloor.a_smart:solar_balcony": "Balkonzonnepaneel", + "pack:nextfloor.a_smart:fuse_box": "Groepenkast", + "pack:nextfloor.a_smart:nas_server": "NAS-server", + "pack:nextfloor.a_smart:hot_water_tank": "Boiler", + "pack:nextfloor.a_smart:light_pillar": "Lichtzuil met kleurverloop", + "pack:nextfloor.a_smart:light_bars_tv": "Paar lichtbalken (tv)", + "pack:nextfloor.a_smart:orb_lamp": "Gloeiende bol-tafellamp", + "pack:nextfloor.a_smart:glow_lamp_portable": "Draagbare gloeilamp", + "pack:nextfloor.a_smart:mood_spot": "Sfeerspot voor op tafel", + "pack:nextfloor.a_smart:cube_lamp": "Kubuslamp", + "pack:nextfloor.a_smart:ceiling_panel_round": "Rond plafondpaneel", + "pack:nextfloor.a_smart:garden_spots_3": "Tuinspots (set van 3)", + "pack:nextfloor.a_smart:wall_light_updown": "Buitenwandlamp op en neer", + "pack:nextfloor.a_smart:siren_strobe": "Sirene met flitslicht", + "pack:nextfloor.a_smart:access_point": "Wifi-accesspoint (plafond)", + "pack:nextfloor.a_smart:smoke_detector": "Rookmelder", + "pack:nextfloor.a_smart:thermostat_wall": "Wandthermostaat", + "pack:nextfloor.a_smart:dehumidifier": "Luchtontvochtiger", + "pack:nextfloor.a_smart:ceiling_fan": "Plafondventilator", + "pack:nextfloor.a_smart:ceiling_fan_light": "Plafondventilator met lamp", + "pack:nextfloor.a_smart:light_switch_1": "Lichtschakelaar, 1-voudig", + "pack:nextfloor.a_smart:socket_1": "Stopcontact, 1-voudig", + "pack:nextfloor.a_smart:light_switch_2": "Lichtschakelaar, 2-voudig", + "pack:nextfloor.a_smart:socket_2": "Stopcontact, 2-voudig", + "pack:nextfloor.a_smart:light_switch_3": "Lichtschakelaar, 3-voudig", + "pack:nextfloor.a_smart:socket_3": "Stopcontact, 3-voudig", + "pack:nextfloor.a_smart:light_switch_4": "Lichtschakelaar, 4-voudig", + "pack:nextfloor.a_smart:socket_4": "Stopcontact, 4-voudig", + "pack:nextfloor.a_smart:socket_outdoor": "Buitenstopcontact met klep", + "packname:nextfloor.a_wohnzimmer": "Woonkamer", + "pack:nextfloor.a_wohnzimmer:sofa_2": "2-zitsbank", + "pack:nextfloor.a_wohnzimmer:sofa_3": "3-zitsbank", + "pack:nextfloor.a_wohnzimmer:sofa_4": "Grote 4-zitsbank", + "pack:nextfloor.a_wohnzimmer:sofa_velvet": "Fluwelen 3-zitsbank", + "pack:nextfloor.a_wohnzimmer:sofa_armless": "Bank zonder armleuningen", + "pack:nextfloor.a_wohnzimmer:sofa_chaise": "Bank met chaise", + "pack:nextfloor.a_wohnzimmer:sofa_chesterfield": "Chesterfieldbank", + "pack:nextfloor.a_wohnzimmer:sofa_bed": "Slaapbank", + "pack:nextfloor.a_wohnzimmer:sofa_corner_l": "Hoekbank (links)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_r": "Hoekbank (rechts)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_xl": "Grote hoekbank (L-vorm)", + "pack:nextfloor.a_wohnzimmer:sofa_u": "U-bank", + "pack:nextfloor.a_wohnzimmer:chaise_longue": "Chaise longue", + "pack:nextfloor.a_wohnzimmer:modular_sofa": "Modulaire bank (5 delen)", + "pack:nextfloor.a_wohnzimmer:armchair": "Fauteuil", + "pack:nextfloor.a_wohnzimmer:club_chair": "Clubfauteuil", + "pack:nextfloor.a_wohnzimmer:wingback": "Oorfauteuil", + "pack:nextfloor.a_wohnzimmer:cocktail_chair": "Cocktailstoel", + "pack:nextfloor.a_wohnzimmer:recliner": "Relaxfauteuil met voetenbank", + "pack:nextfloor.a_wohnzimmer:bean_bag": "Zitzak", + "pack:nextfloor.a_wohnzimmer:pouf": "Poef", + "pack:nextfloor.a_wohnzimmer:rocking_chair": "Schommelstoel", + "pack:nextfloor.a_wohnzimmer:coffee_rect": "Rechthoekige salontafel", + "pack:nextfloor.a_wohnzimmer:coffee_glass": "Glazen salontafel", + "pack:nextfloor.a_wohnzimmer:coffee_round": "Ronde salontafel", + "pack:nextfloor.a_wohnzimmer:coffee_nesting": "Set salontafels", + "pack:nextfloor.a_wohnzimmer:side_round": "Rond bijzettafeltje", + "pack:nextfloor.a_wohnzimmer:console": "Sidetable", + "pack:nextfloor.a_wohnzimmer:dining_120": "Eettafel 120 × 90", + "pack:nextfloor.a_wohnzimmer:dining_160": "Eettafel 160 × 90", + "pack:nextfloor.a_wohnzimmer:dining_200": "Eettafel 200 × 90", + "pack:nextfloor.a_wohnzimmer:dining_220": "Massief houten eettafel 220 × 100", + "pack:nextfloor.a_wohnzimmer:chair_wood": "Houten stoel", + "pack:nextfloor.a_wohnzimmer:chair_upholstered": "Gestoffeerde stoel", + "pack:nextfloor.a_wohnzimmer:chair_shell": "Kuipstoel", + "pack:nextfloor.a_wohnzimmer:dining_bench": "Eetbank 160", + "pack:nextfloor.a_wohnzimmer:lowboard_120": "Lowboard 120", + "pack:nextfloor.a_wohnzimmer:lowboard_160": "Lowboard 160", + "pack:nextfloor.a_wohnzimmer:lowboard_200": "Lowboard 200", + "pack:nextfloor.a_wohnzimmer:sideboard_160": "Dressoir 160", + "pack:nextfloor.a_wohnzimmer:highboard": "Highboard", + "pack:nextfloor.a_wohnzimmer:display_cabinet": "Vitrinekast", + "pack:nextfloor.a_wohnzimmer:chest_3": "Ladekast met 3 lades", + "pack:nextfloor.a_wohnzimmer:bookshelf_tall": "Hoge boekenkast", + "pack:nextfloor.a_wohnzimmer:bookshelf_wide": "Brede boekenkast", + "pack:nextfloor.a_wohnzimmer:cube_2x2": "Vakkenkast 2 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x2": "Vakkenkast 4 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x4": "Vakkenkast 4 × 4", + "pack:nextfloor.a_wohnzimmer:divider_open": "Roomdivider-kast", + "pack:nextfloor.a_wohnzimmer:wall_shelf": "Zwevende wandplank", + "pack:nextfloor.a_wohnzimmer:coat_stand": "Staande kapstok", + "pack:nextfloor.a_wohnzimmer:wall_unit_vitrines": "Wandmeubel met vitrines", + "pack:nextfloor.a_wohnzimmer:wall_unit_tv": "Wandmeubel met tv", + "pack:nextfloor.a_wohnzimmer:tv_on_stand": "Tv op standaard", + "pack:nextfloor.a_wohnzimmer:media_wall": "Mediawand met tv", + "pack:nextfloor.a_wohnzimmer:wood_stove": "Houtkachel", + "pack:nextfloor.a_wohnzimmer:fireplace_wall": "Elektrische wandhaard", + "pack:nextfloor.a_wohnzimmer:piano": "Piano met bankje", + "pack:nextfloor.a_wohnzimmer:floor_lamp_arc": "Booglamp", + "pack:nextfloor.a_wohnzimmer:floor_lamp_tripod": "Driepoot-vloerlamp", + "pack:nextfloor.a_wohnzimmer:table_lamp_ceramic": "Keramische tafellamp", + "pack:nextfloor.a_wohnzimmer:vase_pampas": "Vloervaas met pampasgras", + "pack:nextfloor.a_wohnzimmer:monstera": "Grote monstera", + "pack:nextfloor.a_wohnzimmer:rug_round": "Rond vloerkleed", + "pack:nextfloor.a_wohnzimmer:rug_240": "Vloerkleed 240 × 170", + "pack:nextfloor.a_wohnzimmer:painting_light": "Schilderij met schilderijlamp", + "pack:nextfloor.a_wohnzimmer:shelf_led": "Kast met ledplanken", + "pack:nextfloor.a_wohnzimmer:air_purifier": "Luchtreiniger", + "pack:nextfloor.a_wohnzimmer:tower_fan": "Torenventilator", + "pack:nextfloor.a_wohnzimmer:smart_speaker_living": "Slimme speaker", + "packname:nextfloor.ausbau": "Architectuur en afbouw", + "pack:nextfloor.ausbau:column_round": "Ronde kolom", + "pack:nextfloor.ausbau:column_square": "Vierkante kolom", + "pack:nextfloor.ausbau:beam": "Plafondbalk", + "pack:nextfloor.ausbau:chimney": "Schoorsteenmantel", + "pack:nextfloor.ausbau:glass_wall": "Glazen scheidingswand", + "pack:nextfloor.ausbau:sliding_wall": "Schuifwand", + "pack:nextfloor.ausbau:platform": "Podium", + "pack:nextfloor.ausbau:half_wall": "Halve muur", + "pack:nextfloor.ausbau:divider_shelf": "Scheidingskast", + "pack:nextfloor.ausbau:pilaster": "Pilaster", + "pack:nextfloor.ausbau:column_steel": "Stalen kolom", + "pack:nextfloor.ausbau:beams_wood_5": "Houten plafondbalken (5)", + "pack:nextfloor.ausbau:beam_downstand": "Onderslagbalk", + "pack:nextfloor.ausbau:fireplace_builtin": "Inbouwhaard", + "pack:nextfloor.ausbau:divider_slats": "Lamellen-roomdivider", + "pack:nextfloor.ausbau:curtain_motor": "Gemotoriseerd gordijn", + "pack:nextfloor.ausbau:niche_shelf": "Inbouwkast (nis)", + "pack:nextfloor.ausbau:niche_led": "Lednis", + "pack:nextfloor.ausbau:light_cove": "Lichtlijst (plafond)", + "pack:nextfloor.ausbau:gallery_rail_glass": "Videleuning (glas)", + "pack:nextfloor.ausbau:window_seat": "Vensterbank-zitplek", + "pack:nextfloor.ausbau:curtain_pair": "Gordijn (opent naar beide kanten)", + "pack:nextfloor.ausbau:roller_blind_inside": "Rolgordijn (binnen)", + "packname:nextfloor.bad": "Badkamer extra", + "pack:nextfloor.bad:double_vanity": "Dubbele wastafel", + "pack:nextfloor.bad:walkin_shower": "Inloopdouche", + "pack:nextfloor.bad:towel_radiator": "Handdoekradiator", + "pack:nextfloor.bad:mirror_cabinet": "Spiegelkast met licht", + "pack:nextfloor.bad:washer_tower": "Was-droogzuil", + "pack:nextfloor.bad:laundry_basket": "Wasmand", + "pack:nextfloor.bad:bath_shelf": "Badkamerrek", + "packname:nextfloor.energie": "Energie en installaties", + "pack:nextfloor.energie:heat_pump": "Warmtepomp (buitenunit)", + "pack:nextfloor.energie:pellet_boiler": "Pelletketel", + "pack:nextfloor.energie:buffer_tank": "Buffervat", + "pack:nextfloor.energie:hot_water_tank": "Boiler", + "pack:nextfloor.energie:home_battery": "Thuisaccu (toren)", + "pack:nextfloor.energie:inverter": "Omvormer", + "pack:nextfloor.energie:wallbox": "Laadpaal", + "pack:nextfloor.energie:meter_cabinet": "Meterkast", + "pack:nextfloor.energie:ventilation": "Ventilatie-unit", + "pack:nextfloor.energie:solar_carport_pillar": "Zonnecarportpaal", + "packname:nextfloor.fahrzeuge": "Voertuigen", + "pack:nextfloor.fahrzeuge:tesla_model_s": "Tesla Model S", + "packname:nextfloor.a_saison": "Seizoen & decoratie", + "packname:nextfloor.a_smart2": "Slim huis 2", + "packname:nextfloor.a_haustechnik2": "Installaties 2", + "packname:nextfloor.a_wellness": "Wellness", + "packname:nextfloor.a_garten2": "Tuin 2", + "packname:nextfloor.a_kueche2": "Keuken 2", + "packname:nextfloor.a_fahrzeuge2": "Voertuigen 2", + "packname:nextfloor.a_aussenkueche": "Buitenkeuken & terras", + "packname:nextfloor.a_werkstatt2": "Werkplaats 2", + "packname:nextfloor.a_japandi": "Japandi & Scandinavisch", + "packname:nextfloor.a_loft": "Loft & industrieel", + "packname:nextfloor.a_gruen": "Kamerplanten", + "packname:nextfloor.a_musik": "Muziek & atelier", + "pack:nextfloor.a_saison:xmas_tree": "Kerstboom met lichtjes", + "pack:nextfloor.a_saison:advent_wreath": "Adventskrans", + "pack:nextfloor.a_saison:lights_outdoor": "Lichtsnoer buiten", + "pack:nextfloor.a_saison:window_star": "Raamster", + "pack:nextfloor.a_saison:candle_arch": "Kaarsenboog", + "pack:nextfloor.a_saison:reindeer_light": "Lichtgevend rendier", + "pack:nextfloor.a_saison:pumpkin": "Pompoen", + "pack:nextfloor.a_saison:pumpkin_lantern": "Pompoenlantaarn", + "pack:nextfloor.a_saison:easter_tree": "Paastak", + "pack:nextfloor.a_saison:snowman": "Sneeuwpop", + "pack:nextfloor.a_saison:gift_pile": "Cadeaus", + "pack:nextfloor.a_smart2:siren": "Sirene", + "pack:nextfloor.a_smart2:access_point": "Wifi-accesspoint", + "pack:nextfloor.a_smart2:access_point_wall": "Wifi-accesspoint (wand)", + "pack:nextfloor.a_smart2:smoke_detector": "Rookmelder", + "pack:nextfloor.a_smart2:co_detector": "CO-melder", + "pack:nextfloor.a_smart2:dehumidifier": "Luchtontvochtiger", + "pack:nextfloor.a_smart2:cube_lamp": "Kubuslamp", + "pack:nextfloor.a_smart2:presence_ceiling": "Aanwezigheidssensor (plafond)", + "pack:nextfloor.a_smart2:water_leak": "Watermelder", + "pack:nextfloor.a_smart2:air_quality": "Luchtkwaliteitsmeter", + "pack:nextfloor.a_smart2:doorbell_cam": "Videodeurbel", + "pack:nextfloor.a_haustechnik2:water_tank": "Watertank", + "pack:nextfloor.a_haustechnik2:oil_tank": "Olietank", + "pack:nextfloor.a_haustechnik2:oil_boiler": "Oliegestookte ketel", + "pack:nextfloor.a_haustechnik2:water_softener": "Waterontharder", + "pack:nextfloor.a_haustechnik2:buffer_tank": "Buffervat", + "pack:nextfloor.a_haustechnik2:cistern": "Regenwaterput", + "pack:nextfloor.a_haustechnik2:ventilation_unit": "Ventilatie-unit", + "pack:nextfloor.a_haustechnik2:expansion_vessel": "Expansievat", + "pack:nextfloor.a_haustechnik2:heat_pump_indoor": "Warmtepomp (binnendeel)", + "pack:nextfloor.a_wellness:sauna_cabin": "Sauna", + "pack:nextfloor.a_wellness:sauna_barrel": "Barrelsauna", + "pack:nextfloor.a_wellness:infrared_cabin": "Infraroodcabine", + "pack:nextfloor.a_wellness:hot_tub": "Bubbelbad", + "pack:nextfloor.a_wellness:plunge_pool": "Dompelbad", + "pack:nextfloor.a_wellness:steam_shower": "Stoomdouche", + "pack:nextfloor.a_wellness:relax_lounger": "Relaxligstoel", + "pack:nextfloor.a_wellness:cold_bath": "Ijsbad", + "pack:nextfloor.a_garten2:water_feature": "Waterornament met licht", + "pack:nextfloor.a_garten2:pond": "Vijver met pomp", + "pack:nextfloor.a_garten2:robot_mower": "Robotmaaier", + "pack:nextfloor.a_garten2:mower_dock": "Laadstation robotmaaier", + "pack:nextfloor.a_garten2:sandbox": "Zandbak", + "pack:nextfloor.a_garten2:beach_chair": "Strandstoel", + "pack:nextfloor.a_garten2:wood_pile": "Houtstapel", + "pack:nextfloor.a_garten2:bird_house": "Vogelhuisje", + "pack:nextfloor.a_garten2:raised_bed": "Moestuinbak", + "pack:nextfloor.a_garten2:garden_shower": "Tuindouche", + "pack:nextfloor.a_kueche2:coffee_machine": "Volautomatische koffiemachine", + "pack:nextfloor.a_kueche2:espresso": "Espressomachine", + "pack:nextfloor.a_kueche2:kettle": "Waterkoker", + "pack:nextfloor.a_kueche2:toaster": "Broodrooster", + "pack:nextfloor.a_kueche2:stand_mixer": "Keukenmachine", + "pack:nextfloor.a_kueche2:thermo_cooker": "Kookmachine", + "pack:nextfloor.a_kueche2:air_fryer": "Airfryer", + "pack:nextfloor.a_kueche2:microwave": "Magnetron", + "pack:nextfloor.a_kueche2:wine_fridge": "Wijnklimaatkast", + "pack:nextfloor.a_kueche2:water_bar": "Bruiswatermaker", + "pack:nextfloor.a_kueche2:dishwasher_slim": "Vaatwasser 45 cm", + "pack:nextfloor.a_fahrzeuge2:motorbike": "Motor", + "pack:nextfloor.a_fahrzeuge2:scooter": "Scooter", + "pack:nextfloor.a_fahrzeuge2:camper_van": "Camper", + "pack:nextfloor.a_fahrzeuge2:trailer": "Aanhangwagen", + "pack:nextfloor.a_fahrzeuge2:e_bike": "E-bike", + "pack:nextfloor.a_fahrzeuge2:cargo_bike": "Bakfiets", + "pack:nextfloor.a_fahrzeuge2:quad": "Quad", + "pack:nextfloor.a_fahrzeuge2:boat_trailer": "Boottrailer met boot", + "pack:nextfloor.a_aussenkueche:outdoor_kitchen": "Buitenkeuken", + "pack:nextfloor.a_aussenkueche:kamado": "Kamado", + "pack:nextfloor.a_aussenkueche:pizza_oven": "Pizzaoven", + "pack:nextfloor.a_aussenkueche:fire_pit": "Vuurschaal", + "pack:nextfloor.a_aussenkueche:patio_heater": "Terrasverwarmer", + "pack:nextfloor.a_aussenkueche:outdoor_fridge": "Buitenkoelkast", + "pack:nextfloor.a_aussenkueche:bar_counter": "Bar", + "pack:nextfloor.a_aussenkueche:bar_stool_out": "Barkruk buiten", + "pack:nextfloor.a_aussenkueche:hanging_chair": "Hangstoel", + "pack:nextfloor.a_werkstatt2:workbench_wall": "Werkbank met gaatjesbord", + "pack:nextfloor.a_werkstatt2:drill_press": "Kolomboormachine", + "pack:nextfloor.a_werkstatt2:table_saw": "Tafelzaag", + "pack:nextfloor.a_werkstatt2:compressor": "Compressor", + "pack:nextfloor.a_werkstatt2:welder": "Lasapparaat", + "pack:nextfloor.a_werkstatt2:heavy_shelf": "Zwaarlastrek", + "pack:nextfloor.a_werkstatt2:parts_cabinet": "Assortimentskast", + "pack:nextfloor.a_werkstatt2:tool_chest": "Gereedschapswagen", + "pack:nextfloor.a_werkstatt2:ev_bike_charger": "Accu-oplaadplek", + "pack:nextfloor.a_japandi:low_bed": "Laag bed", + "pack:nextfloor.a_japandi:tatami": "Tatami", + "pack:nextfloor.a_japandi:paper_lamp": "Papieren vloerlamp", + "pack:nextfloor.a_japandi:paper_pendant": "Papieren hanglamp", + "pack:nextfloor.a_japandi:tea_table": "Lage theetafel", + "pack:nextfloor.a_japandi:shoji_screen": "Shoji-kamerscherm", + "pack:nextfloor.a_japandi:bonsai": "Bonsai", + "pack:nextfloor.a_japandi:floor_cushion": "Vloerkussen", + "pack:nextfloor.a_japandi:wood_bench": "Houten bank", + "pack:nextfloor.a_japandi:rattan_chair": "Rotan fauteuil", + "pack:nextfloor.a_loft:steel_shelf": "Stalen kast", + "pack:nextfloor.a_loft:factory_pendant": "Industriële hanglamp", + "pack:nextfloor.a_loft:leather_sofa": "Leren bank", + "pack:nextfloor.a_loft:plank_table": "Plankentafel", + "pack:nextfloor.a_loft:locker": "Lockerkast", + "pack:nextfloor.a_loft:edison_floor_lamp": "Edison-vloerlamp", + "pack:nextfloor.a_loft:bar_stool_loft": "Industriële barkruk", + "pack:nextfloor.a_loft:pipe_shelf": "Buizenwandrek", + "pack:nextfloor.a_gruen:monstera": "Monstera", + "pack:nextfloor.a_gruen:ficus": "Ficus", + "pack:nextfloor.a_gruen:olive_tree": "Olijfboom in pot", + "pack:nextfloor.a_gruen:cactus_group": "Cactussen", + "pack:nextfloor.a_gruen:hanging_plant": "Hangplant", + "pack:nextfloor.a_gruen:plant_shelf": "Plantenrek met kweeklamp", + "pack:nextfloor.a_gruen:vertical_garden": "Groene wand", + "pack:nextfloor.a_gruen:grow_light": "Kweeklamp", + "pack:nextfloor.a_gruen:herb_planter": "Slimme kruidentuin", + "pack:nextfloor.a_musik:upright_piano": "Piano", + "pack:nextfloor.a_musik:grand_piano": "Vleugel", + "pack:nextfloor.a_musik:drum_kit": "Drumstel", + "pack:nextfloor.a_musik:guitar_stand": "Gitaren op standaard", + "pack:nextfloor.a_musik:guitar_amp": "Gitaarversterker", + "pack:nextfloor.a_musik:mixing_desk": "Studiobureau met mengpaneel", + "pack:nextfloor.a_musik:studio_monitor": "Studiomonitor", + "pack:nextfloor.a_musik:synth": "Synthesizer", + "pack:nextfloor.a_musik:mic_stand": "Microfoon op standaard", + "pack:nextfloor.a_musik:easel": "Schildersezel", + "pack:nextfloor.a_musik:vinyl_player": "Platenspeler", + "packname:nextfloor.a_bilder": "Foto's & lijsten", + "pack:nextfloor.a_bilder:frame_landscape": "Fotolijst (liggend)", + "pack:nextfloor.a_bilder:frame_portrait": "Fotolijst (staand)", + "pack:nextfloor.a_bilder:frame_square": "Fotolijst (vierkant)", + "pack:nextfloor.a_bilder:frame_large": "Grote fotolijst", + "pack:nextfloor.a_bilder:canvas": "Canvas", + "pack:nextfloor.a_bilder:poster": "Poster", + "pack:nextfloor.a_bilder:frame_table": "Fotolijstje", + "pack:nextfloor.a_bilder:frame_digital": "Digitale fotolijst", + "pack:nextfloor.a_bilder:picture_ledge": "Fotoplank met lijsten", + "color:pearl_white": "Pearl White", + "color:solid_black": "Solid Black", + "color:midnight_silver": "Midnight Silver", + "color:quicksilver": "Quicksilver", + "color:deep_blue": "Deep Blue", + "color:ultra_red": "Ultra Red", + "color:midnight_cherry": "Midnight Cherry Red", + "pack:nextfloor.fahrzeuge:tesla_model_3": "Tesla Model 3", + "color:red": "Red Multi-Coat", + "color:stealth_grey": "Stealth Grey", + "pack:nextfloor.fahrzeuge:tesla_model_x": "Tesla Model X", + "pack:nextfloor.fahrzeuge:tesla_model_y": "Tesla Model Y", + "pack:nextfloor.fahrzeuge:tesla_cybertruck": "Tesla Cybertruck", + "color:stainless": "Stainless Steel", + "color:wrap_black": "Satin Black-wrap", + "color:wrap_white": "Satin White-wrap", + "color:wrap_grey": "Satin Grey-wrap", + "color:wrap_blue": "Satin Blue-wrap", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024": "Tesla Model 3 (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024_performance": "Tesla Model 3 Performance (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_s_plaid": "Tesla Model S Plaid", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025": "Tesla Model Y Standard (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_premium": "Tesla Model Y Premium (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_performance": "Tesla Model Y Performance (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_l": "Tesla Model Y L", + "pack:nextfloor.fahrzeuge:tesla_roadster": "Tesla Roadster", + "pack:nextfloor.fahrzeuge:tesla_semi": "Tesla Semi", + "pack:nextfloor.fahrzeuge:ev_suv": "Elektrische SUV (formaat Model Y)", + "pack:nextfloor.fahrzeuge:small_car": "Kleine auto", + "pack:nextfloor.fahrzeuge:estate_car": "Stationwagen", + "pack:nextfloor.fahrzeuge:van": "Bus", + "pack:nextfloor.fahrzeuge:bicycle": "Fiets", + "pack:nextfloor.fahrzeuge:ebike": "E-bike", + "pack:nextfloor.fahrzeuge:motorbike": "Motor", + "pack:nextfloor.fahrzeuge:trailer": "Aanhanger", + "pack:nextfloor.fahrzeuge:sedan": "Sedan", + "pack:nextfloor.fahrzeuge:coupe": "Sportcoupé", + "pack:nextfloor.fahrzeuge:convertible": "Cabriolet (open)", + "pack:nextfloor.fahrzeuge:small_ev": "Kleine EV", + "pack:nextfloor.fahrzeuge:suv": "SUV", + "pack:nextfloor.fahrzeuge:family_van": "Gezinsbus", + "pack:nextfloor.fahrzeuge:minibus": "Minibus", + "pack:nextfloor.fahrzeuge:panel_van": "Bestelbus", + "pack:nextfloor.fahrzeuge:pickup": "Pick-up", + "pack:nextfloor.fahrzeuge:campervan": "Camperbus (hefdak)", + "pack:nextfloor.fahrzeuge:motorhome": "Camper", + "pack:nextfloor.fahrzeuge:caravan": "Caravan", + "packname:nextfloor.fitness": "Fitness (ouder)", + "pack:nextfloor.fitness:treadmill": "Loopband", + "pack:nextfloor.fitness:bike_trainer": "Hometrainer", + "pack:nextfloor.fitness:rower": "Roeitrainer", + "pack:nextfloor.fitness:weight_bench": "Halterbank", + "pack:nextfloor.fitness:power_rack": "Powerrack", + "pack:nextfloor.fitness:yoga_mat": "Yogamat", + "pack:nextfloor.fitness:dumbbell_rack": "Dumbbellrek", + "packname:nextfloor.garten": "Tuin en terras (ouder)", + "pack:nextfloor.garten:sun_lounger": "Ligbed", + "pack:nextfloor.garten:garden_table": "Tuintafel", + "pack:nextfloor.garten:garden_chair": "Tuinstoel", + "pack:nextfloor.garten:lounge_set": "Buitenlounge", + "pack:nextfloor.garten:parasol": "Parasol", + "pack:nextfloor.garten:gas_grill": "Gasbarbecue", + "pack:nextfloor.garten:fire_bowl": "Vuurschaal", + "pack:nextfloor.garten:pool": "Zwembad", + "pack:nextfloor.garten:hot_tub": "Jacuzzi", + "pack:nextfloor.garten:trampoline": "Trampoline", + "pack:nextfloor.garten:greenhouse": "Kas", + "pack:nextfloor.garten:raised_bed": "Moestuinbak", + "pack:nextfloor.garten:garden_shed": "Tuinhuis", + "pack:nextfloor.garten:swing_bench": "Schommelbank", + "pack:nextfloor.garten:mower_robot": "Robotmaaier", + "pack:nextfloor.garten:tree_oak": "Loofboom", + "pack:nextfloor.garten:tree_birch": "Berk", + "pack:nextfloor.garten:tree_fruit": "Fruitboom", + "pack:nextfloor.garten:conifer": "Conifeer", + "pack:nextfloor.garten:shrub": "Struik", + "pack:nextfloor.garten:shrub_flowering": "Bloeiende struik", + "pack:nextfloor.garten:hedge": "Haag", + "pack:nextfloor.garten:lawn_brush": "Kreupelhout", + "pack:nextfloor.garten:bike_rack": "Fietsenrek", + "pack:nextfloor.garten:bin_box": "Containerberging (4 containers)", + "packname:nextfloor.ikea": "IKEA-maten", + "pack:nextfloor.ikea:billy": "Boekenkast 80x202 (Billy-maat)", + "pack:nextfloor.ikea:billy_low": "Boekenkast 80x106 (Billy-maat)", + "pack:nextfloor.ikea:kallax_2x2": "Vakkenkast 2x2 (Kallax-maat)", + "pack:nextfloor.ikea:kallax_2x4": "Vakkenkast 2x4 (Kallax-maat)", + "pack:nextfloor.ikea:kallax_4x4": "Vakkenkast 4x4 (Kallax-maat)", + "pack:nextfloor.ikea:lack_side": "Bijzettafel 55x55 (Lack-maat)", + "pack:nextfloor.ikea:lack_coffee": "Salontafel 90x55 (Lack-maat)", + "pack:nextfloor.ikea:malm_bed_140": "Bed 140x200 (Malm-maat)", + "pack:nextfloor.ikea:malm_bed_160": "Bed 160x200 (Malm-maat)", + "pack:nextfloor.ikea:malm_chest_6": "Ladekast met 6 lades (Malm-maat)", + "pack:nextfloor.ikea:malm_chest_4": "Ladekast met 4 lades (Malm-maat)", + "pack:nextfloor.ikea:pax_100": "Kledingkast 100x236 (Pax-maat)", + "pack:nextfloor.ikea:pax_150": "Kledingkast 150x236 (Pax-maat)", + "pack:nextfloor.ikea:poang": "Fauteuil (Poäng-maat)", + "pack:nextfloor.ikea:ektorp_2": "2-zitsbank (Ektorp-maat)", + "pack:nextfloor.ikea:ektorp_3": "3-zitsbank (Ektorp-maat)", + "pack:nextfloor.ikea:bekant": "Bureau 160x80 (Bekant-maat)", + "pack:nextfloor.ikea:alex": "Ladeblok (Alex-maat)", + "pack:nextfloor.ikea:besta_tv": "Tv-meubel 180x42 (Bestå-maat)", + "pack:nextfloor.ikea:ivar": "Grenen kast 89x179 (Ivar-maat)", + "packname:nextfloor.kino": "Thuisbioscoop en gaming", + "pack:nextfloor.kino:projection_screen": "Projectiescherm", + "pack:nextfloor.kino:projector": "Projector", + "pack:nextfloor.kino:floor_speaker": "Vloerspeaker", + "pack:nextfloor.kino:subwoofer": "Subwoofer", + "pack:nextfloor.kino:soundbar": "Soundbar", + "pack:nextfloor.kino:gaming_desk": "Gamingbureau", + "pack:nextfloor.kino:gaming_chair": "Gamingstoel", + "pack:nextfloor.kino:game_console": "Spelconsole", + "pack:nextfloor.kino:arcade": "Arcadekast", + "pack:nextfloor.kino:media_wall": "Mediawand met tv", + "pack:nextfloor.kino:media_rack": "Mediarek", + "packname:nextfloor.kueche": "Keuken extra", + "pack:nextfloor.kueche:coffee_machine": "Koffiemachine", + "pack:nextfloor.kueche:microwave": "Magnetron", + "pack:nextfloor.kueche:hood_island": "Eilandafzuigkap", + "pack:nextfloor.kueche:wine_fridge": "Wijnklimaatkast", + "pack:nextfloor.kueche:stand_mixer": "Keukenmachine", + "pack:nextfloor.kueche:toaster": "Broodrooster", + "pack:nextfloor.kueche:kettle": "Waterkoker", + "pack:nextfloor.kueche:long_dining_table": "Lange eettafel", + "pack:nextfloor.kueche:bar_cart": "Barkar", + "pack:nextfloor.kueche:trash_station": "Afvalscheiding", + "packname:nextfloor.schlafen": "Slapen en kinderen", + "pack:nextfloor.schlafen:boxspring": "Boxspring", + "pack:nextfloor.schlafen:baby_crib": "Babybedje", + "pack:nextfloor.schlafen:changing_table": "Commode", + "pack:nextfloor.schlafen:vanity_table": "Kaptafel", + "pack:nextfloor.schlafen:clothes_rail": "Kledingrek", + "pack:nextfloor.schlafen:loft_bed_desk": "Hoogslaper met bureau", + "pack:nextfloor.schlafen:toy_box": "Speelgoedkist", + "packname:nextfloor.technik": "Kantoor en homelab", + "pack:nextfloor.technik:standing_desk": "Zit-sta-bureau", + "pack:nextfloor.technik:server_rack": "Serverrack (19 inch)", + "pack:nextfloor.technik:nas": "NAS", + "pack:nextfloor.technik:printer_3d": "3D-printer", + "pack:nextfloor.technik:office_printer": "Printer", + "pack:nextfloor.technik:router": "Router / accesspoint", + "pack:nextfloor.technik:tower_pc": "Tower-pc", + "pack:nextfloor.technik:filing_cabinet": "Ladeblok", + "packname:nextfloor.treppen": "Trappen en leuningen", + "pack:nextfloor.treppen:stairs_straight": "Rechte trap", + "pack:nextfloor.treppen:stairs_l": "L-trap met bordes", + "pack:nextfloor.treppen:stairs_u": "U-trap", + "pack:nextfloor.treppen:stairs_spiral": "Wenteltrap", + "pack:nextfloor.treppen:stairs_compact": "Ruimtebesparende trap", + "pack:nextfloor.treppen:landing": "Bordes", + "pack:nextfloor.treppen:steps_outdoor": "Buitentrap", + "pack:nextfloor.treppen:rail_metal": "Metalen leuning", + "pack:nextfloor.treppen:rail_glass": "Glazen leuning", + "pack:nextfloor.treppen:rail_wood": "Houten leuning", + "pack:nextfloor.treppen:stairs_floating": "Zwevende trap", + "pack:nextfloor.treppen:stairs_u_winder": "Open U-trap met kwartslag", + "pack:nextfloor.treppen:rail_corner": "Hoekleuning", + "packname:nextfloor.werkstatt": "Garage en werkplaats", + "pack:nextfloor.werkstatt:workbench": "Werkbank", + "pack:nextfloor.werkstatt:tool_cabinet": "Gereedschapskast", + "pack:nextfloor.werkstatt:tool_chest": "Gereedschapswagen", + "pack:nextfloor.werkstatt:shelf_rack": "Opslagrek", + "pack:nextfloor.werkstatt:tyre_stack": "Stapel banden", + "pack:nextfloor.werkstatt:drill_press": "Kolomboormachine", + "pack:nextfloor.werkstatt:compressor": "Compressor", + "pack:nextfloor.werkstatt:bike_stand": "Fietsstandaard", + "pack:nextfloor.werkstatt:paint_cabinet": "Verfkast", + "pack:nextfloor.werkstatt:tool_wall": "Gereedschapswand", + "pack:nextfloor.werkstatt:heavy_shelf": "Zwaar opslagrek", + "pack:nextfloor.werkstatt:chest_freezer_garage": "Vrieskist", + "pack:nextfloor.werkstatt:tyre_rack": "Bandenrek", + "pack:nextfloor.werkstatt:lawn_mower": "Grasmaaier", + "pack:nextfloor.werkstatt:bike_stand_2": "Fietsstandaard met 2 fietsen", + "pack:nextfloor.werkstatt:workshop_light": "Werkplaatslamp", + "pack:nextfloor.werkstatt:garage_opener": "Garagedeuropener", + "pack:nextfloor.werkstatt:wallbox_holder": "Laadpaal met kabelhouder", + "pack:nextfloor.werkstatt:wall_bike_holder": "Wandfietshouder (2)", + "pack:nextfloor.werkstatt:workshop_vacuum": "Werkplaatsstofzuiger", + "pack:nextfloor.werkstatt:workshop_cabinet": "Werkplaatskast", + "pack:nextfloor.werkstatt:printer_enclosed": "Gesloten 3D-printer", + "packname:nextfloor.wohnen": "Wonen en huisdieren", + "pack:nextfloor.wohnen:corner_sofa": "Hoekbank (L-vorm)", + "pack:nextfloor.wohnen:bean_bag": "Zitzak", + "pack:nextfloor.wohnen:fireplace": "Open haard", + "pack:nextfloor.wohnen:bookcase_wall": "Wandboekenkast", + "pack:nextfloor.wohnen:piano": "Piano", + "pack:nextfloor.wohnen:aquarium": "Aquarium", + "pack:nextfloor.wohnen:cat_tree": "Krabpaal", + "pack:nextfloor.wohnen:dog_bed": "Hondenbed", + "pack:nextfloor.wohnen:hanging_chair": "Hangstoel", + "pack:nextfloor.wohnen:display_cabinet": "Vitrinekast", + "pack:nextfloor.wohnen:high_table": "Bartafel", + "pack:nextfloor.wohnen:floor_mirror": "Staande spiegel", + "furn_tap": "Tikken op het item", + "furn_tap_default": "Zoals gewoonlijk", + "furn_tap_hint": "Een eigen actie zoals de eigen knoppen van het stermenu, bijv. een browser_mod-pop-up met je kaart.", + "furn_show_when": "Alleen tonen zolang …", + "furn_show_when_state": "… in de status is (leeg = aan)", + "furn_show_when_invert": "Andersom: tonen zolang het niet zo is", + "furn_show_when_hint": "Seizoensdecoratie die alleen in december staat: een helper (input_boolean), een agenda of een sensor bepaalt of het meubel in 3D verschijnt. Scheid meerdere statussen met komma's. De editor toont het altijd.", + "picture_upload": "Foto uploaden", + "picture_replace": "Andere foto uploaden", + "picture_stored": "Er is een eigen foto opgeslagen.", + "picture_url": "… of adres van de afbeelding", + "picture_entity": "… of de afbeelding van een entiteit", + "picture_border": "Passe-partout (%)", + "picture_fit": "Foto", + "picture_fit_cover": "vult de lijst", + "picture_fit_contain": "helemaal zichtbaar", + "picture_hint": "Je foto in de lijst, in 3D en op de wandtablet. Geüploade foto's worden verkleind bij het plan opgeslagen; een afbeeldingsentiteit (foto van de dag) of een camera toont zijn huidige beeld.", + "card_tap_in_room": "Apparaten alleen in de geopende kamer schakelen", + "card_tap_in_room_hint": "In de huis- en verdiepingsweergave opent tikken de verdieping of kamer, ook op een apparaat of zijn symbool. In de geopende kamer schakelt het het apparaat. Lang drukken opent altijd het menu of de details.", + "card_markers_outside": "Symbolen buiten de geopende kamer kiezen", + "card_markers_outside_hint": "In het huis, op de verdieping en in de andere kamers alleen de aangevinkte soorten; in de geopende kamer alles zoals hierboven ingesteld. \"Altijd\" en \"Nooit\" bij het apparaat gaan voor.", + "marker_kind_light": "Lampen", + "marker_kind_cover": "Rolluiken", + "marker_kind_climate": "Verwarming", + "marker_kind_media": "Media", + "marker_kind_switch": "Schakelaars", + "marker_kind_fan": "Ventilatoren", + "marker_kind_lock": "Sloten", + "marker_kind_binary": "Contacten en melders", + "marker_kind_sensor": "Sensoren", + "marker_kind_tap": "Meubels met een actie", + "marker_kind_other": "Overig", + "floor_copy": "Verdieping dupliceren", + "floor_copy_hint": "De kopie komt boven op het huis met alle kamers, muren, deuren en ramen. Kamers en verdieping verliezen hun koppeling met Home Assistant, meubels hun entiteiten; energieapparaten blijven op de oude verdieping.", + "floor_copy_furniture": "Meubels meenemen", + "floor_copy_devices": "Apparaatpinnen meenemen", + "floor_copy_devices_hint": "Dezelfde entiteit staat dan op beide verdiepingen.", + "floor_copy_outdoor": "Buitenzones meenemen", + "floor_copy_make": "Kopie maken", + "floor_copy_name": "{name} (kopie)", + "furn_to_floor": "Naar verdieping verplaatsen", + "furn_to_floor_hint": "Het meubel gaat naar dezelfde plek op de gekozen verdieping.", + "arc": "Boog", + "arc_hint": "Buigt de muur tot een boog. Een kamer die de muur deelt buigt mee, deuren en ramen gaan mee; Ongedaan maken haalt de boog weg.", + "arc_bulge": "Bolling (m)", + "arc_bulge_hint": "Hoe ver het midden van de muur bolt: positief naar buiten, negatief de kamer in.", + "arc_apply": "Buigen", + "arc_too_wide": "Een deur of raam in deze muur is te breed voor deze boog. Maak de boog vlakker of de opening smaller.", + "time_of_day": "Tijdstip", + "time_of_day_hint": "Toont zon, licht, schaduwen en uiterlijk op een ander tijdstip van vandaag. Tik opnieuw om terug te gaan naar nu.", + "menu_open": "Menu open", + "menu_open_hint": "Het stermenu met favorieten en eigen knoppen staat op dit apparaat meteen open, een maat groter – voor een wandtablet dat vooral scènes schakelt.", + "keep_camera": "Camera behouden", + "keep_camera_hint": "Bij het wisselen van verdieping blijft de camera aan dezelfde kant, op dezelfde hoogte en afstand, in plaats van de nieuwe verdieping vanaf de startkant in te passen.", + "view_zoom": "Zoom", + "view_zoom_hint": "Hoe dichtbij de ingepaste weergaven komen – op kleine tablets oogt het huis groter.", + "stair_shape": "Vorm", + "stair_shape_straight": "Recht", + "stair_shape_quarter": "Kwartslag (gedraaid)", + "stair_shape_l": "L-vorm met bordes", + "stair_shape_half": "Halve draai (gedraaid)", + "stair_shape_u": "U-vorm met bordes", + "stair_shape_spiral": "Wenteltrap", + "stair_turn": "Draairichting (naar boven)", + "stair_turn_left": "Naar links", + "stair_turn_right": "Naar rechts", + "stair_build": "Constructie", + "stair_build_solid": "Massief (beton)", + "stair_build_stringer": "Met trapbomen", + "stair_build_mono": "Middenboom", + "stair_build_cantilever": "Uitkragend (zwevend)", + "stair_risers": "Stootborden", + "stair_steps": "Optreden (aantal)", + "stair_run_width": "Trapbreedte (m)", + "stair_landing_after": "Treden tot het bordes", + "stair_landing_hint": "Het bordes ligt {h} cm boven de vloer; de overige treden komen erna.", + "stair_rail": "Leuning", + "stair_rail_none": "Geen", + "stair_rail_left": "Links", + "stair_rail_right": "Rechts", + "stair_rail_both": "Beide zijden", + "stair_down": "Gaat naar beneden", + "stair_down_hint": "De trap begint op deze verdieping en gaat naar beneden, bijvoorbeeld naar een kelder die niet getekend hoeft te zijn. Hij opent de vloer van deze verdieping.", + "stair_measures": "{steps} optreden van {rise} cm · aantrede {going} cm · staplengte {measure} cm", + "stair_uncomfortable": "oncomfortabel (staplengte 59–65 cm, optrede hoogstens 21 cm)", + "stair_up_note": "De trap begint aan de gemarkeerde voorkant. De vloer erboven gaat alleen open waar boven de treden minder dan 2,2 m hoofdruimte overblijft.", + "stair_down_note": "Je stapt op de trap aan de gemarkeerde voorkant en loopt naar beneden. De plattegrond tekent hem gestreept; deze verdieping gaat boven de treden open.", + "stair_upgrade": "Vorm instellen", + "stair_upgrade_hint": "Maakt er een trap van met een vorm (gedraaid, L, U, wenteltrap), constructie, leuning en aantal treden.", + "tool_stairs": "Trap", + "hint_stairs": "Sleep waar de trap moet komen – hij loopt langs de lange zijde; stel daarna rechts vorm, draairichting en constructie in", + "stair_opening": "Trapgat", + "stair_opening_headroom": "Naar hoofdruimte (alleen waar nodig)", + "stair_opening_full": "Boven de hele trap", + "stair_opening_none": "Geen (luik, gesloten trappenhuis)", + "stair_opening_hint": "Hoeveel de trap de vloer opent die hij bereikt: de verdieping erboven, of de eigen verdieping bij een trap naar beneden. Naar hoofdruimte opent alleen boven de treden met minder dan 2,2 m.", + "stair_up_note_plain": "De trap begint aan de gemarkeerde voorkant en stijgt naar achteren." +} diff --git a/custom_components/nextfloor/frontend/lang/pl.json b/custom_components/nextfloor/frontend/lang/pl.json new file mode 100644 index 0000000..e2eb2d4 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/pl.json @@ -0,0 +1,2763 @@ +{ + "view": "3D", + "editor": "Edytor", + "all_floors": "Wszystkie piętra", + "outside_area": "Na zewnątrz", + "outside_area_hint": "Wszystkie urządzenia na zewnątrz w jednym miejscu: w ogrodzie, poza pomieszczeniami i to, co należy do zewnątrz (na przykład stacja pogodowa na dachu).", + "device_outside": "Należy do zewnątrz", + "device_outside_hint": "Urządzenie nie liczy się do pomieszczenia pod nim (stacja pogodowa na dachu) i jest na liście w panelu Na zewnątrz.", + "no_building": "Brak planu.", + "no_building_admin": "Brak planu. Narysuj pierwsze piętro w edytorze.", + "no_rooms_admin": "Piętra istnieją, ale nie ma jeszcze żadnego pomieszczenia. Same ściany nie wystarczą: narysuj w edytorze co najmniej jedno pomieszczenie narzędziem „Prostokąt” lub „Dowolny kształt”.", + "open_editor": "Otwórz edytor", + "loading": "Wczytywanie …", + "load_error": "Wczytywanie nie powiodło się", + "saving": "Zapisywanie …", + "saved": "Zapisano", + "save_error": "Zapis nie powiódł się", + "save_failed_detail": "Zapis nie powiódł się: {error}. Twoje zmiany zostają w tej przeglądarce.", + "needs_restart": "Zainstalowano nową wersję NextFloor ({frontend}), ale Home Assistant nadal działa na {version}. Uruchom ponownie Home Assistant – do tego czasu zapis może się nie udać.", + "needs_reload": "Ta strona pokazuje jeszcze NextFloor {frontend}, a Home Assistant ma już {backend}. Odśwież stronę; w aplikacji companion: Ustawienia → Aplikacja companion → Zresetuj pamięć podręczną frontendu.", + "reload_page": "Odśwież", + "needs_restart_old": "Zainstalowano nową wersję NextFloor, ale Home Assistant nadal działa na starszej. Uruchom ponownie Home Assistant – do tego czasu zapis się nie uda.", + "draft_found": "Znaleziono niezapisane zmiany z {time}.", + "draft_restore": "Przywróć i zapisz", + "draft_discard": "Odrzuć", + "walls_auto": "Wysokie ściany", + "walls_cut": "Przekrój", + "walls_slope": "Skos", + "walls_slope_hint": "Ściany ścięte skośnie: z przodu do połowy wysokości, z tyłu na pełną wysokość – jak domek dla lalek; obraca się z kamerą", + "walls_solid": "Pełne", + "walls_solid_hint": "Pełne ściany w ich kolorach zamiast szkła (kolory: edytor → ustawienia, dla pomieszczenia w pomieszczeniu)", + "wall_paint_outside": "Kolor ścian na zewnątrz", + "wall_paint_inside": "Kolor ścian wewnątrz", + "wall_paint_room": "Kolor ścian wewnątrz (to pomieszczenie)", + "wall_paint_hint": "Używane w widoku 3D „Pełne”.", + "wall_paint_default": "Domyślny", + "card_solid_walls": "Pełne ściany (w ich kolorach)", + "reset_view": "Przegląd", + "back": "Wstecz", + "floor": "Piętro", + "floors": "Piętra", + "add_floor": "Dodaj piętro", + "floor_from_ha": "Piętra z Home Assistant:", + "floor_empty": "Puste piętro", + "level": "Poziom {n}", + "ha_floor": "Piętro w Home Assistant", + "floor_layer": "Warstwa (do pokazania i ukrycia)", + "floor_power": "Licznik piętra (moc)", + "floor_power_hint": "Czujnik mocy tylko dla tego piętra (podlicznik, mieszkanie). Jego wartość widać na etykiecie piętra, a w widoku tego piętra na karcie domu wraz z udziałem w zużyciu domu.", + "floor_power_share": "{n} % domu", + "living_area": "Powierzchnia mieszkalna {living}", + "room_living": "Wlicza się do powierzchni mieszkalnej", + "living_area_none": "Brak powierzchni mieszkalnej · podłoga {floor}", + "living_area_low": "Powierzchnia mieszkalna {living} (podłoga {floor}, z czego {low} poniżej 2 m)", + "living_area_hint": "Liczone jak niemiecka Wohnflächenverordnung: podłoga wewnątrz ścian, w całości od 2 m wysokości w świetle, w połowie między 1 a 2 m (pod skosami), wcale poniżej 1 m. Wartość orientacyjna, nie pomiar.", + "living_area_floor": "Powierzchnia mieszkalna: {floor}", + "living_area_floor_house": "Powierzchnia mieszkalna piętra: {floor} · cały dom: {house}", + "print_plan": "Drukuj plan / PDF", + "print_plan_hint": "Każde piętro jako czysty plan z wymiarami i powierzchniami oraz tabela powierzchni – do druku lub zapisu jako PDF w oknie drukowania.", + "print_title": "Plan", + "print_room": "Pomieszczenie", + "print_floor_area": "Powierzchnia podłogi", + "print_living": "Powierzchnia mieszkalna", + "print_low": "poniżej 2 m", + "print_total": "Suma", + "print_blocked": "Okno drukowania zostało zablokowane – zezwól na wyskakujące okna dla Home Assistant.", + "check_open": "Sprawdź plan", + "note": "Notatka", + "note_add": "Notatka tutaj", + "note_text": "Tekst", + "note_placeholder": "np. „wymienić filtr” lub „bezpiecznik 12”", + "note_due": "Termin", + "note_due_hint": "Od tego dnia pinezka robi się pomarańczowa.", + "note_is_due": "Ta notatka jest do zrobienia.", + "keys_title": "Klawisze edytora", + "keys_undo": "Cofnij", + "keys_redo": "Ponów", + "keys_duplicate": "Powiel pomieszczenie", + "keys_delete": "Usuń zaznaczenie", + "keys_nudge": "Przesuń zaznaczenie o krok siatki", + "keys_nudge_10": "… o 10 cm", + "keys_nudge_1": "… o 1 cm", + "keys_rotate": "Obróć mebel o 90° (Shift: wstecz)", + "keys_lock": "Zablokuj lub odblokuj mebel, urządzenie lub część dachu", + "keys_close_shape": "Zamknij dowolny kształt", + "keys_escape": "Anuluj, wyjdź z narzędzia, usuń zaznaczenie", + "keys_straight": "Podczas rysowania: proste linie", + "keys_sheet": "Ta ściągawka", + "tour_title": "Pierwsze kroki", + "tour_1_title": "Narysuj pomieszczenia", + "tour_1": "Rysuj pomieszczenia narzędziem „{rect}” lub „{free}”; ściany powstają same. Przypisz każdemu pomieszczeniu jego obszar Home Assistant – wtedy NextFloor znajdzie jego urządzenia. Jeśli masz już obszary, „{rooms}” w formularzu piętra utworzy je naraz.", + "tour_2_title": "Drzwi i okna", + "tour_2": "„{opening}” umieszcza je na ścianie. Powiąż ich kontaktron lub roletę – w 3D otwierają się i zamykają razem z nim, a otwarte okna dają znać.", + "tour_3_title": "Meble i urządzenia", + "tour_3": "„{furniture}” otwiera bibliotekę – albo zbuduj własne w 🛠️ pracowni. Wybierz pomieszczenie, a pod spodem pojawią się urządzenia jego obszaru gotowe do umieszczenia; lampy świecą kolorem swojego światła.", + "tour_4_title": "Obejrzyj i sprawdź", + "tour_4": "„{split}” pokazuje dom podczas rysowania; u góry przełączasz na widok 3D. „{check}” wymienia, czego jeszcze brakuje – a ? zawsze pokazuje klawisze.", + "tour_next": "Dalej", + "tour_back": "Wstecz", + "tour_done": "Do dzieła", + "tour_skip": "Pomiń", + "check_open_hint": "Pokazuje, czego brakuje lub co jest nie tak w planie, z poprawką jednym dotknięciem.", + "check_title": "Kontrola planu", + "check_all_good": "Wszystko w porządku – nic nie znaleziono.", + "check_hint": "Znaleziono {n} punktów. Niebieskie przyciski zmieniają plan (cofanie działa jak zawsze), pozostałe pokazują miejsce.", + "check_room_no_area": "„{room}” nie ma obszaru Home Assistant: jego urządzenia nie są znajdowane.", + "check_room_no_area_named": "„{room}” nie ma obszaru – wolny obszar „{area}” nazywa się tak samo.", + "check_areas_unplaced": "{n} obszarów tego piętra nie ma jeszcze pomieszczenia: {names}", + "check_devices_unplaced": "„{room}”: {n} urządzeń obszaru nie ma jeszcze w planie.", + "check_rooms_overlap": "„{a}” i „{b}” nachodzą na siebie.", + "check_opening_off_wall": "Drzwi lub okno w „{room}” nie są na żadnej ścianie.", + "check_entity_missing": "{n} pinezek wskazuje encje, których Home Assistant już nie zna ({ids}).", + "check_furniture_entity_missing": "Mebel jest powiązany z {id} – ta encja już nie istnieje.", + "check_battery_low": "Słaba bateria: {name} ({level} %)", + "battery_low_n": "Słaba bateria: {names}", + "check_standby": "{name} pobiera {w} W, choć wyłączony – ok. {cost} rocznie.", + "check_fix_show": "Pokaż", + "check_fix_set_area": "Przypisz „{area}”", + "check_fix_add_rooms": "Dodaj pomieszczenia", + "check_fix_place": "Umieść {n}", + "check_fix_remove": "Usuń {n}", + "floor_layer_hint": "To piętro nie jest kondygnacją, lecz warstwą – np. wszystkie drzewa albo dekoracje. Widok 3D pokazuje u góry oko, które ją pokazuje lub ukrywa na każdym urządzeniu.", + "no_ha_floor": "– brak –", + "area_rooms": "Dodaj pomieszczenia z obszarów HA ({n})", + "area_rooms_hint": "Dodaje pomieszczenie (4 × 3 m) dla każdego obszaru tego piętra – potem przeciągnij je na miejsce i dopasuj narożniki", + "floor_name": "Nazwa", + "elevation": "Wysokość położenia (m)", + "floor_shift": "Przesuń piętro (m)", + "floor_shift_apply": "Przesuń", + "floor_shift_hint": "Przesuwa wszystkie pomieszczenia, meble, urządzenia, tereny zewnętrzne, wolne ściany i obraz tła tego piętra o X i Z. Połacie dachu zostają.", + "height": "Wysokość sufitu (m)", + "cut_height": "Wysokość przekroju (m)", + "delete_floor": "Usuń piętro", + "delete_floor_confirm": "Usunąć piętro „{name}” ze wszystkimi pomieszczeniami?", + "move_up": "W górę", + "move_down": "W dół", + "default_floor": "Parter", + "new_floor": "Piętro {n}", + "tool_select": "Zaznacz", + "tool_rect": "Prostokąt", + "tool_polygon": "Dowolny kształt", + "undo": "Cofnij", + "redo": "Ponów", + "fit": "Pokaż wszystko", + "room": "Pomieszczenie", + "rooms": "Pomieszczenia", + "room_name": "Nazwa", + "area": "Obszar", + "no_area": "Bez obszaru", + "sub_area_add": "+ Obszar w pomieszczeniu", + "sub_area_hint": "Część pomieszczenia z własnym obszarem w Home Assistant, ale bez ścian – kącik do czytania, regał, aneks kuchenny. Jej urządzenia i czujniki należą do tego pomieszczenia.", + "material": "Podłoga", + "x": "X (m)", + "z": "Y (m)", + "width": "Szerokość (m)", + "depth": "Głębokość (m)", + "points": "Narożniki", + "delete_point": "Usuń narożnik", + "duplicate": "Duplikuj", + "delete": "Usuń", + "new_room": "Pomieszczenie {n}", + "settings": "Ustawienia", + "pendant_shape": "Kształt", + "pendant_shade": "Klosz", + "paint_colour": "Kolor farby", + "pendant_globe": "Kula", + "pendant_cone": "Stożek", + "pendant_drum": "Bęben", + "sofa_shape": "Kształt", + "sofa_straight": "Prosta", + "sofa_l": "W kształcie L (lustro: druga strona)", + "sofa_u": "W kształcie U", + "pkg_open": "Umebluj …", + "pkg_hint": "Meble stają przy ścianach pomieszczenia; lampy łączą się ze światłami obszaru. Potem dopasuj pojedyncze elementy – Ctrl+Z cofa wszystko.", + "pkg_done": "Umieszczono {n} elementów – Ctrl+Z cofa.", + "pkg_kitchen_row": "Kuchnia w linii", + "pkg_kitchen_row_desc": "Ciąg przy tylnej ścianie z lodówką, piekarnikiem, zlewem, zmywarką i płytą, szafka wisząca, stół jadalny z lampą wiszącą", + "pkg_kitchen_l": "Kuchnia w kształcie L", + "pkg_kitchen_l_desc": "Ciągi z tyłu i z lewej, wyspa kuchenna z hokerami", + "pkg_bath": "Łazienka", + "pkg_bath_desc": "Umywalka, WC, wanna, pralka, oczko sufitowe", + "pkg_bedroom": "Sypialnia", + "pkg_bedroom_desc": "Łóżko podwójne z dwiema szafkami nocnymi, szafa, komoda, lampa sufitowa", + "pkg_living": "Salon", + "pkg_living_desc": "Szafka RTV, sofa, stolik kawowy, dywan, fotel, regał, lampa podłogowa, roślina", + "pkg_dining": "Jadalnia", + "pkg_dining_desc": "Stół z czterema krzesłami, kredens, lampa wisząca", + "pkg_office": "Biuro", + "pkg_office_desc": "Biurko z krzesłem biurowym, dwa regały, lampa sufitowa", + "pkg_kids": "Pokój dziecięcy", + "pkg_kids_desc": "Łóżko pojedyncze, biurko, regał, dywan", + "pkg_hall": "Przedpokój", + "pkg_hall_desc": "Wieszak, dwa oczka sufitowe", + "spots_place": "Rozmieść oczka", + "spots_type": "Lampa", + "spots_cols": "Kolumny (lewo–prawo)", + "spots_rows": "Rzędy (przód–tył)", + "spots_add": "Rozmieść {n} lamp", + "spots_placed": "Rozmieszczono {n} lamp.", + "spots_hint": "Wszystkie lampy podążają za wybranym światłem (np. oczka na jednym ściemniaczu). Potem każdą można przesunąć i połączyć z innym światłem jak każdy mebel.", + "cancel": "Anuluj", + "backup": "Kopia zapasowa", + "backup_history": "Punkty przywracania", + "share_view": "Udostępnij widok", + "share_view_hint": "Zapisuje dom jako mały plik, który otwiera się w każdej przeglądarce bez Home Assistant (przez demo online NextFloor) – by pokazać go rodzinie lub projektantowi. Bez urządzeń i encji, jak szablon.", + "share_view_title": "Nasz dom w NextFloor", + "share_view_needs_js": "Ta strona wymaga JavaScriptu i połączenia z internetem.", + "share_view_file": "widok", + "share_view_done": "Widok zapisany – otwórz plik w przeglądarce lub przekaż dalej.", + "version_save": "Zapisz ten stan …", + "version_save_hint": "Zachowuje plan pod nazwą („przed remontem”). Nazwane stany zostają, gdy automatyczne punkty znikają.", + "version_name_prompt": "Nazwa tego stanu (np. „przed remontem”):", + "version_saved": "Stan „{name}” zapisany.", + "version_compare": "Porównaj", + "version_delete_confirm": "Usunąć „{name}”?", + "version_same": "Brak różnic z planem.", + "version_diff_n": "{n} różnic w stosunku do obecnego planu:", + "diff_floor_added": "Piętro „{name}” dodane", + "diff_floor_removed": "Piętro „{name}” usunięte", + "diff_room_added": "Pomieszczenie „{name}” dodane", + "diff_room_removed": "Pomieszczenie „{name}” usunięte", + "diff_room_renamed": "„{detail}” nazywa się teraz „{name}”", + "diff_room_reshaped": "„{name}” zmienione ({detail} m²)", + "diff_opening_added": "{name} dodane ({detail})", + "diff_opening_removed": "{name} usunięte ({detail})", + "diff_furniture_added": "{name} dodane", + "diff_furniture_removed": "{name} usunięte", + "diff_furniture_moved": "{name} przesunięte lub zmienione", + "diff_device_added": "Urządzenie {name} umieszczone", + "diff_device_removed": "Urządzenie {name} usunięte", + "diff_device_moved": "Urządzenie {name} przesunięte", + "backup_none": "Jeszcze brak. Podczas edycji punkt przywracania zapisywany jest najwyżej co 10 minut.", + "backup_summary": "{rooms} pomieszczeń, {furniture} elementów", + "backup_restore": "Przywróć", + "backup_restore_confirm": "Przywrócić stan z {time}? Obecny stan zostanie zachowany jako punkt przywracania.", + "backup_restored": "Przywrócono.", + "backup_file": "Plik", + "backup_export": "Eksportuj", + "backup_export_share": "Udostępnij jako szablon", + "backup_export_share_hint": "Bez obszarów, urządzeń, czujników i obrazów – do przekazania innym.", + "backup_import": "Importuj …", + "backup_import_confirm": "Zastąpić cały plan plikiem? Obecny stan zostanie zachowany jako punkt przywracania.", + "backup_import_error": "Plik nie jest planem NextFloor ({error}).", + "backup_imported": "Zaimportowano.", + "backup_hint": "Obrazy tła nie są częścią pliku.", + "backup_full": "Pełna kopia zapasowa", + "backup_full_export": "Zapisz wszystko (plan, obrazy, pakiety)", + "backup_full_import": "Przywróć pełną kopię …", + "backup_full_hint": "Jeden plik z planem, wszystkimi obrazami tła i ekranów oraz zainstalowanymi pakietami. Przy przywracaniu każdy pakiet jest sprawdzany ponownie; klucz licencji nie jest dołączony.", + "backup_full_confirm": "Zastąpić plan, obrazy i pakiety kopią? Obecny stan zostaje jako punkt przywracania.", + "backup_full_not_backup": "To nie jest pełna kopia zapasowa NextFloor.", + "backup_full_restored": "Przywrócono kopię: {packs} pakietów, {pictures} obrazów.", + "backup_full_skipped": "Pominięto (nieczytelne): {packs}.", + "export_name_full": "pełna", + "device_confirm": "Pytaj przed przełączeniem", + "device_confirm_hint": "Dotknięcie w 3D, szybkie menu i panel pomieszczenia najpierw pytają. Podwójne dotknięcie pomieszczenia wyklucza to urządzenie.", + "cover_confirm_hint": "Otwieranie, zamykanie i pozycje najpierw pytają w szybkim menu i panelu pomieszczenia, a przesunięcie po znaczniku nie porusza już rolety (obraca widok). Stop nigdy nie pyta.", + "blind_kind": "Rodzaj osłony", + "blind_roller": "Roleta zewnętrzna", + "blind_venetian": "Żaluzja fasadowa z lamelami", + "blind_inside": "Roleta wewnętrzna", + "cover2_entity": "Druga roleta (prawa połowa)", + "cover_my": "Ulubiona pozycja „My” (%, 0 = brak)", + "cover_my_go": "Do ulubionej pozycji ({p} %)", + "blind_hint": "Żaluzja fasadowa obraca lamele w 3D zgodnie z nachyleniem rolety; roleta wewnętrzna wisi za szybą. Szerokie okno może mieć drugą roletę dla prawej połowy. Ulubiona pozycja pojawia się jako „My” w szybkim menu: roleta z pozycjami jedzie tam, silnik Somfy RTS bez informacji zwrotnej jedzie Stopem do własnej pozycji My.", + "confirm_switch": "Naprawdę przełączyć {name}?", + "lock_confirm_unlock": "Naprawdę odblokować {name}?", + "gang_switch_one": "Przełączniki", + "furn_cover_entity": "Porusza się z", + "furn_cover_hint": "Zasłona, ekran, markiza lub brama podąża za tą encją osłony (roleta, zasłona, markiza, brama) i porusza się razem z nią. Dotknięcie otwiera jej menu (w górę, stop, w dół).", + "furn_cover_inverted": "Odwróć kierunek", + "furn_cover_inverted_hint": "Dla markizy lub zasłony, która na planie rusza się odwrotnie niż w rzeczywistości: wysunięta pokazuje się jako zwinięta i odwrotnie.", + "gang_switch": "Przycisk {n} przełącza", + "gang_socket_one": "Gniazdo zasilane przez", + "gang_socket": "Gniazdo {n} zasilane przez", + "gang_switch_hint": "Przycisk świeci, gdy jego światło jest włączone (w jego kolorze). Dotknięcie go przełącza; przy kilku przyciskach małe menu pyta który. Ta sama encja może być na kilku przełącznikach.", + "gang_socket_hint": "Gniazdo świeci na zielono, gdy jego przełącznik jest włączony – jaśniej, im więcej pobiera. Dotknięcie je przełącza; przy kilku małe menu pyta które.", + "lock_confirm_lock": "Zablokować {name}?", + "opening_lock": "Inteligentny zamek", + "opening_lock_hint": "Dotknięcie drzwi blokuje je lub odblokowuje (zawsze najpierw pytając). Gdy są odblokowane, ich krawędź świeci.", + "split_handle_hint": "Przeciągnij: szerokość planu i widoku 3D", + "wall_exterior": "Ściana zewnętrzna (m)", + "wall_interior": "Ściana wewnętrzna (m)", + "grid": "Siatka (m)", + "units": "Pokazuj długości w", + "units_metric": "Metrach", + "units_imperial": "Stopach i calach", + "units_hint": "Jak długości i powierzchnie wyglądają w planie, formularzach i widoku ściany. Wpisywanie pozostaje w metrach.", + "background": "Szablon (obraz rzutu)", + "background_upload": "Wybierz obraz …", + "background_width": "Szerokość w planie (m)", + "background_opacity": "Krycie", + "background_rotation": "Obrót (°)", + "background_edit": "Przesuń, skaluj i obróć", + "background_edit_done": "Gotowe", + "background_edit_hint": "Gdy tryb jest włączony: przeciąganie obrazu go przesuwa, uchwyt w prawym dolnym rogu skaluje. Najpierw dopasuj skalę, potem obróć.", + "background_remove": "Usuń szablon", + "hint_select": "Dotknij pomieszczenia, by je zaznaczyć · przeciągnij narożniki · „+” na krawędzi wstawia narożnik · strzałki przesuwają · Del usuwa · Ctrl+Z", + "hint_rect": "Przeciągnij, by narysować prostokąt", + "hint_polygon": "Wstawiaj narożniki · dotknij pierwszego narożnika lub naciśnij Enter, by zamknąć · Esc anuluje", + "hint_empty": "Najpierw dodaj piętro.", + "area_m2": "{a} m²", + "overlap_warning": "Pomieszczenia nachodzą na siebie – ściany są tam niepełne.", + "read_only": "Tylko administratorzy mogą edytować plan.", + "side_failed": "Nie udało się wyświetlić tego formularza ({error}). Plan nadal działa. Zgłoś ten tekst w zgłoszeniu na GitHubie.", + "mat_wood": "Drewno", + "mat_oak": "Dąb", + "mat_tiles": "Płytki", + "mat_carpet": "Wykładzina", + "mat_stone": "Kamień", + "mat_concrete": "Beton", + "card_name": "NextFloor", + "card_description": "Twój dom w 3D (neon).", + "stats": "{calls} wywołań rysowania · {tris} trójkątów", + "stats_fps": "{fps} fps (najwolniejsza klatka {ms} ms)", + "stats_idle": "W spoczynku (0 fps)", + "stats_busy_floors": "piętra", + "stats_busy_openings": "drzwi/okna", + "stats_busy_flash": "błysk", + "stats_busy_roof": "dach", + "stats_busy_flow": "przepływ energii", + "stats_busy_effect": "efekt koloru", + "stats_busy_robot": "robot", + "stats_busy_orbit": "obrót kamery", + "stats_busy_tint": "odcień pomieszczenia", + "stats_low": "poziom tablet, współczynnik pikseli {r}", + "stats_full": "poziom pełny, współczynnik pikseli {r}", + "floors_apart": "Rozsunięte", + "floors_stacked": "Ułożone", + "roof_keep": "Dach zostaje", + "roof_keep_hint": "Dach zostaje na domu przy przybliżaniu zamiast unosić się i znikać", + "floor_rooms_one": "1 pomieszczenie", + "floor_rooms": "{n} pomieszczeń", + "quality": "Jakość", + "quality_auto": "Auto", + "quality_low": "Tablet", + "quality_high": "Wysoka", + "state_on": "Wł.", + "state_off": "Wył.", + "state_open": "Otwarte", + "state_closed": "Zamknięte", + "state_opening": "Otwieranie", + "state_closing": "Zamykanie", + "state_playing": "Odtwarzanie", + "state_paused": "Pauza", + "state_idle": "Bezczynny", + "state_locked": "Zablokowane", + "state_unlocked": "Odblokowane", + "state_detected": "Wykryto", + "state_clear": "Brak", + "state_unavailable": "Niedostępne", + "state_heat": "Grzanie", + "state_cool": "Chłodzenie", + "state_auto": "Auto", + "state_heat_cool": "Grzanie/chłodzenie", + "state_dry": "Osuszanie", + "state_fan_only": "Wentylator", + "devices": "Urządzenia", + "devices_none_area": "Połącz pomieszczenie z obszarem, a jego urządzenia pojawią się tutaj.", + "devices_none": "Obszar nie ma odpowiednich urządzeń.", + "devices_place_all_n": "Umieść wszystkie {n} …", + "devices_place_all_confirm": "Umieścić od razu {n} urządzeń w pomieszczeniu? (Ctrl+Z lub „Cofnij” usuwa je wszystkie jednym krokiem.)", + "devices_src_area": "Ten obszar", + "devices_src_other": "Inne obszary", + "devices_src_none": "Bez obszaru", + "panel_hide": "Ukryj w panelu pomieszczenia", + "panel_unhide": "Pokaż ponownie w panelu pomieszczenia", + "panel_state_hide": "Ukryj stan w panelu pomieszczenia (np. osłona, która zgłasza tylko \"unknown\")", + "panel_state_show": "Pokaż ponownie stan w panelu pomieszczenia", + "devices_place": "Umieść", + "devices_remove": "Usuń", + "devices_hint": "Umieszczone urządzenia pojawiają się w 3D. Przeciągnij je w planie, by je przesunąć.", + "panel_lights": "Światła", + "panel_covers": "Osłony", + "panel_climate": "Ogrzewanie", + "panel_media": "Multimedia", + "panel_switches": "Przełączniki", + "panel_sensors": "Czujniki", + "panel_scenes": "Sceny i skrypty", + "panel_announce": "📢 Komunikat", + "announce_placeholder": "Własna wiadomość …", + "announce_send": "Powiedz", + "announce_sent": "Powiedziano: „{message}”", + "announce_failed": "Komunikat nie powiódł się: {error}", + "announce_phrase_1": "Obiad gotowy!", + "announce_phrase_2": "Czas spać!", + "announce_phrase_3": "Zejdźcie, proszę!", + "announce_phrase_4": "Zaraz wychodzimy!", + "announce_phrase_5": "Pies musi wyjść!", + "state_recording": "Nagrywanie", + "state_streaming": "Transmisja", + "panel_all_off": "Wszystko wył.", + "readable": "Czytelnie", + "readable_hint": "Mocniejszy kontrast i większy tekst – dla tabletów ściennych i każdego, kto tak lepiej czyta.", + "plain": "Tylko plan", + "plain_hint": "Pokazuje tylko ściany, drzwi, okna i schody, bez mebli. Urządzenia i ich piny zostają.", + "right_back": "Prawy klik = wstecz", + "right_back_hint": "Krótkie kliknięcie prawym przyciskiem w widoku 3D cofa o krok: z pomieszczenia na piętro, z piętra do domu (jak dwukrotne dotknięcie pustego miejsca). Przeciąganie prawym przyciskiem nadal przesuwa widok.", + "stl": "Druk 3D (STL)", + "stl_hint": "Zapisuje dom jako plik STL (ściany, podłogi, meble i tereny zewnętrzne wszystkich pięter) do druku 3D w skali 1:100 (metr to 10 mm). Nie ma w nim okien, świateł ani dachu; slicer w razie potrzeby naprawi plik.", + "card_plain": "Tylko plan", + "card_rooms": "Tylko te pomieszczenia", + "card_rooms_hint": "Karta pokazuje tylko zaznaczone pomieszczenia z meblami, urządzeniami, drzwiami i oknami (na przykład dla tabletu w kuchni). Nic nie zaznaczono: cały plan.", + "card_templates": "Szablony karty", + "card_templates_hint": "Skonfiguruj kartę pulpitu raz tutaj (z jej własnymi ustawieniami) i na każdym tablecie podaj tylko jej nazwę: `template: kitchen_tablet`. Zmiany docierają do wszystkich kart z tym szablonem; to, co jest na samej karcie, ma pierwszeństwo przed szablonem.", + "template_name": "Nowy szablon (nazwa)", + "template_add": "Utwórz szablon", + "template_reload": "Odśwież ekrany z tym szablonem", + "template_reload_all": "Odśwież wszystkie ekrany", + "template_use": "Na karcie pulpitu: `template: {name}`", + "card_template": "Szablon karty", + "card_template_none": "brak (tylko ta karta)", + "card_readable": "Czytelnie", + "all_off_n": "Wyłącz wszystko ({n})", + "all_off_hint": "Wyłącza światła, przełączniki, wentylatory i media w pomieszczeniu; przez dziesięć sekund można to cofnąć.", + "all_off_done": "Wszystko wyłączone.", + "all_off_undo": "Cofnij", + "all_off_floor": "Wyłącz wszystko na {floor} ({n} urządzeń), cofnięcie przez dziesięć sekund", + "mood_save": "Zapisz nastrój", + "mood_save_hint": "Zapisuje, jak teraz świecą lampy pomieszczenia, jako nastrój – dotknięcie przywraca go później, „→” przenosi do innego pomieszczenia.", + "mood_new": "Nastrój", + "mood_set": "Ustaw ten nastrój", + "mood_carry": "Przenieś do innego pomieszczenia", + "panel_all_on": "Wszystko wł.", + "view_options": "Widok: jakość, wygląd, znaczniki, FPS", + "panel_all_open": "Wszystko w górę", + "panel_all_close": "Wszystko w dół", + "central": "Centralne: wszystkie światła, rolety i ulubione", + "central_house": "Cały dom", + "central_lights": "Światła", + "central_covers": "Rolety", + "central_on": "Wł.", + "central_off": "Wył.", + "central_open": "W górę", + "central_close": "W dół", + "central_sure": "Na pewno?", + "central_favorites": "Ulubione", + "central_no_favorites": "Brak ulubionych. Ustaw sceny, skrypty i przełączniki w edytorze w \"Ulubione\".", + "card_central": "Gwiazda z menu centralnym", + "card_central_hint": "Wszystkie światła i rolety piętra lub domu oraz ulubione z edytora.", + "favorites": "Ulubione", + "favorites_hint": "Sceny, skrypty, automatyzacje, przyciski i przełączniki do menu centralnego (gwiazdy) widoku 3D – impreza, symulacja obecności, zacienienie, podlewanie.", + "favorites_add": "Dodaj ulubione", + "favorite_floor": "Na którym piętrze pojawia się ten ulubiony", + "favorite_all_floors": "Wszystkie piętra", + "outside_hidden": "Na zewnątrz: ukryj urządzenia", + "outside_hidden_hint": "Urządzenia, których panel Na zewnątrz nie ma pokazywać (zostają na planie).", + "outside_hidden_add": "Ukryj urządzenie", + "room_facts": "Panel pomieszczenia: pokazywane dane", + "room_fact_sun": "Godziny słońca", + "room_fact_comfort": "Komfort", + "room_fact_air": "Wskazówka wietrzenia", + "room_fact_circuits": "Obwody", + "background_handles_hint": "Obraz ma teraz uchwyty jak mebel: przeciąganie go przesuwa, prawy dolny róg skaluje, okrągły uchwyt u góry obraca (Shift dla kroków co 15°). Gdy pasuje, dotknij \"Gotowe\" – wtedy zostaje na miejscu.", + "background_fixed_hint": "Obraz zostaje na miejscu, możesz rysować na nim. Aby go dopasować, dotknij \"Przesuń, skaluj i obróć\".", + "bg_level": "Wyprostuj", + "bg_level_cancel": "Anuluj prostowanie", + "bg_level_first": "Dotknij początku ściany na obrazie, która ma biec prosto (poziomo lub pionowo).", + "bg_level_second": "Teraz dotknij końca tej ściany – obraz obróci się, by pasował.", + "bg_ruler": "Skaluj linijką", + "bg_ruler_cancel": "Anuluj linijkę", + "bg_ruler_first": "Dotknij początku odcinka o znanej długości na obrazie – np. zwymiarowanej ściany.", + "bg_ruler_second": "Teraz dotknij końca odcinka.", + "bg_ruler_length_hint": "Zmierzono w planie: {m} m. Wpisz rzeczywistą długość, a obraz zostanie przeskalowany.", + "bg_ruler_length": "Rzeczywista długość (m)", + "bg_ruler_apply": "Zastosuj skalę", + "thumbs_fold": "Zwiń obrazy pięter do przycisków", + "thumbs_show": "Pokaż ponownie obrazy pięter", + "room_start_view": "Widok jako start tego pomieszczenia", + "room_start_view_hint": "Po dotknięciu pomieszczenia w 3D kamera leci dokładnie do widoku, który pokazuje teraz panel 3D po prawej – kąt, zoom i kadr. Najpierw włącz 3D obok, obróć i przybliż pomieszczenie, potem dotknij.", + "room_start_view_reset": "Usuń widok startowy pomieszczenia (znów z góry)", + "room_start_view_need_pane": "Najpierw włącz \"3D obok\", a potem obróć i przybliż pomieszczenie tak, jak ma się otwierać.", + "floor_start_view": "Widok jako start tego piętra", + "floor_start_view_hint": "To piętro otwiera się w 3D tak, jak teraz stoi panel 3D po prawej – np. parter od przodu, a piętro od tyłu. Najpierw włącz 3D obok, obróć je, potem dotknij.", + "floor_start_view_reset": "Usuń widok startowy piętra (znów jak dom)", + "floor_start_view_need_pane": "Najpierw włącz \"3D obok\" i obróć piętro tak, jak ma się otwierać.", + "ambilight": "Poświata za TV (%)", + "ambilight_hint": "Jak mocno świeci za telewizorem podczas odtwarzania. 0 ją wyłącza (np. gdy masz taśmy LED na TV), 100 to zwykła siła.", + "sound_rings": "Fale dźwięku (%)", + "sound_rings_hint": "Jak duże są fale wokół głośnika podczas odtwarzania. 0 je wyłącza, obraz i poświata zostają; 100 to zwykły rozmiar. Rozmiar zależy też od głośności głośnika: ciszej to mniejsze.", + "glow_scale": "Poświata w 3D (%)", + "light_effects": "Animacje efektów w 3D", + "light_effects_hint": "Przypisuj tylko dokładne nazwy efektów z HA. Nieprzypisane efekty zachowują statyczny kolor HA. Niczego nie zmienia w Home Assistant.", + "light_effects_enabled": "Zezwól na animacje dla tej lampy", + "light_effect_unmapped": "Nieprzypisany (statyczny)", + "light_effect_add": "Dodaj dokładną nazwę efektu", + "light_effect_name_limit": "Dokładna nazwa efektu musi mieć od 1 do 255 znaków. Nie zostanie skrócona.", + "light_effect_count_limit": "Najwyżej 100 przypisań. Najpierw usuń istniejące.", + "light_effect_exists": "Ta nazwa efektu jest już przypisana. Istniejące przypisanie zostaje zachowane.", + "light_animation_none": "Statyczny", + "light_animation_rainbow": "Tęcza (zastępuje kolor)", + "light_animation_pulse": "Puls (intensywność)", + "light_animation_flicker": "Migotanie (intensywność)", + "glow_scale_hint": "Jak mocno lampa świeci w 3D: poniżej 100 % przygasza jasne taśmy LED, by pomieszczenie się nie prześwietlało; powyżej 100 % sprawia, że słaba lampa świeci mocniej. Niczego nie przełącza w Home Assistant.", + "vehicle_to_spot": "Zamień w miejsce parkingowe", + "vehicle_to_spot_hint": "Pojazd jako zwykły mebel stoi tam zawsze. Jako miejsce parkingowe pojawia się tylko, gdy czujnik zgłasza samochód, i tam łączy się urządzenie samochodu (ładowanie, zasięg, zamek, klimatyzacja).", + "as_furniture": "Pokaż jako mebel", + "as_furniture_hint": "Zastępuje znacznik meblem w tym samym miejscu, połączonym z tym urządzeniem – głośnik dla odtwarzacza, lampa dla światła. Ctrl+Z cofa.", + "as_furniture_pick": "Wybierz mebel …", + "as_device": "Z powrotem do znacznika urządzenia", + "as_device_hint": "Zastępuje mebel zwykłym znacznikiem jego urządzenia w tym samym miejscu.", + "presets": "Stacje i playlisty (Dźwięk)", + "presets_hint": "Pokazywane w szybkim menu każdego głośnika pod \"Odtwórz\", obok źródeł odtwarzacza. Dla Echo (Alexa Media Player): wpisz SPOTIFY, AMAZON_MUSIC lub TUNEIN, a jako treść to, co byś powiedział (\"Rock Antenne\"). Dla Sonos, Music Assistant i innych: wpisz music lub url z adresem strumienia lub URI.", + "preset_type": "Typ", + "preset_type_hint": "media_content_type z play_media, np. music, url, playlist, SPOTIFY, AMAZON_MUSIC, TUNEIN", + "preset_content": "Treść", + "preset_content_hint": "media_content_id: URL strumienia, URI (spotify:playlist:…) lub, dla Alexy, fraza wyszukiwania", + "preset_speakers": "Tylko na tych głośnikach (żaden = na wszystkich)", + "media_play": "Odtwórz", + "media_pause": "Pauza", + "media_previous": "Poprzedni", + "media_next": "Następny", + "media_volume": "Głośność", + "media_sources": "Źródła", + "preset_add": "Stacja lub playlista", + "own_buttons": "Własne przyciski", + "own_buttons_hint": "Pokazywane w menu centralnym (gwiazda) pod ulubionymi: otwórz ścieżkę dashboardu, pokaż szczegóły encji, wywołaj usługę lub otwórz popup browser_mod z własną kartą.", + "own_alerts": "Własne ostrzeżenia", + "circuits": "Rozdzielnica", + "circuits_hint": "Obwody z pomieszczeniami, które zasilają. Panel pomieszczenia je wymienia, a wyszukiwarka znajduje („F12”).", + "circuit_name": "Nazwa", + "circuit_new": "Nowy obwód", + "circuit_add": "Dodaj obwód", + "circuit_add_room": "Dodaj pomieszczenie", + "own_alerts_hint": "Wiersz na pasku ostrzeżeń widoku 3D, gdy encja jest w danym stanie – „Pusty zbiornik” z robota, „Zmywarka gotowa”. Kilka stanów po przecinku; dla liczb <20 lub >80.", + "own_alert_entity": "Gdy …", + "own_alert_state": "… jest w stanie (puste = włączone)", + "own_alert_text": "… wtedy to ostrzeżenie", + "own_alert_color": "Kolor", + "own_alert_tap": "Dotknięcie", + "own_alert_tap_info": "otwiera szczegóły", + "own_alert_tap_toggle": "przełącza encję", + "own_alert_tap_room": "przechodzi do pomieszczenia", + "own_alert_house": "Cały dom", + "own_alert_new": "Nowe ostrzeżenie", + "own_alert_add": "Dodaj ostrzeżenie", + "today": "Dziś", + "today_none": "Dziś nic nie zaplanowano.", + "today_calendars": "Kalendarze dla „Dziś”", + "today_calendars_hint": "Terminy z tych kalendarzy pojawiają się w prawym górnym rogu widoku 3D na karcie „Dziś”, razem z pojemnikami odbieranymi dziś lub jutro. Dotknięcie tytułu zwija kartę.", + "own_button_state": "Świeci, gdy … jest włączone (opcjonalnie)", + "own_button_label": "Etykieta", + "own_button_action": "Akcja", + "own_button_new": "Nowy przycisk", + "own_button_add": "Własny przycisk", + "own_action_navigate": "Otwórz ścieżkę", + "own_action_more_info": "Szczegóły encji", + "own_action_service": "Wywołaj usługę", + "own_action_fire_dom_event": "fire-dom-event (browser_mod)", + "own_target_navigate": "Ścieżka", + "own_target_more_info": "Encja", + "own_target_service": "Usługa (domena.usługa)", + "own_data": "Dane (JSON)", + "own_data_hint": "Dla usługi jej dane, dla fire-dom-event treść zdarzenia, np. {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}.", + "own_data_bad": "To nie jest prawidłowy obiekt JSON.", + "panel_no_area": "To pomieszczenie nie jest połączone z obszarem. Możesz je połączyć w edytorze.", + "panel_empty": "Żadne urządzenie tego pomieszczenia nie jest w planie. W edytorze umieść urządzenia lub wybierz je dla panelu pomieszczenia przez ☆.", + "close": "Zamknij", + "panel_fold": "Zwiń (pomieszczenie zostaje w widoku)", + "panel_unfold": "Otwórz ponownie", + "brightness": "Jasność", + "color_temp": "Temperatura barwowa", + "color": "Kolor", + "position": "Pozycja", + "cover_open": "Otwórz", + "cover_stop": "Stop", + "cover_tilt": "Lamele", + "cover_tilt_open": "Lamele otwarte", + "cover_tilt_close": "Lamele zamknięte", + "cover_close": "Zamknij", + "target_temp": "Cel", + "current_temp": "Aktualnie", + "temp_down": "Chłodniej", + "temp_up": "Cieplej", + "volume": "Głośność", + "play_pause": "Odtwórz/pauza", + "previous": "Poprzedni", + "next": "Następny", + "run": "Uruchom", + "details": "Szczegóły", + "hold_hint": "Dotknięcie przełącza · długie przytrzymanie otwiera szczegóły", + "tool_opening": "Drzwi i okna", + "tool_furniture": "Meble", + "qm_off": "Wył.", + "find": "Szukaj", + "find_placeholder": "Gdzie jest …? Urządzenie lub pomieszczenie", + "find_none": "Nic nie znaleziono", + "swipe_off": "Wył.", + "panel_pin": "Pokaż w panelu pomieszczenia", + "panel_unpin": "Nie pokazuj w panelu pomieszczenia", + "devices_panel_hint": "Panel pomieszczenia pokazuje urządzenia z planu. ☆ dodaje urządzenie do panelu bez umieszczania go.", + "card_section_view": "Widok", + "card_size": "Rozmiar", + "card_size_fixed": "Stała wysokość", + "card_size_fill": "Wypełnij ekran", + "card_fill_hint": "Działa najlepiej w widoku dashboardu typu „Panel (pojedyncza karta)” – karta zajmuje wtedy całe miejsce.", + "card_controls": "Przełączniki w karcie", + "card_floor_thumbs": "Piętra jako miniatury", + "card_floor_thumbs_hint": "Małe obrazy pięter z boku – dotknij jednego, by przełączyć", + "card_floor_thumbs_hint_start": "Wybrane piętro jest wtedy tym, od którego karta startuje – obrazy z boku przełączają na pozostałe", + "card_room_names": "Pokaż nazwy pomieszczeń", + "card_section_kiosk": "Tablet ścienny (kiosk)", + "card_section_features": "Funkcje", + "card_weather_plan": "jak w planie", + "card_pro_hint": "Ślad ruchu i ściana kamer należą do kamer: ślad pokazuje ostatnie pół godziny, ściana wszystkie kamery z planu.", + "card_idle_return": "Powrót do widoku startowego po", + "card_idle_off": "Nigdy", + "card_idle_min": "{n} min bez dotyku", + "card_idle_hint": "Po odczekaniu karta zamyka pomieszczenie i znów pokazuje widok startowy.", + "card_night": "Przyciemnianie nocne", + "card_night_off": "Wył.", + "card_night_sun": "Według słońca", + "card_night_time": "Przedział czasu", + "card_night_range": "Przedział czasu (np. 22:00-06:00)", + "card_idle_orbit": "Obrót kamery jako wygaszacz", + "card_idle_orbit_hint": "Po powrocie widok obraca się powoli, aż ktoś dotknie tabletu", + "card_dashboard": "Przycisk do dashboardu (ścieżka)", + "card_dashboard_label": "Etykieta przycisku", + "card_dashboard_hint": "Przycisk w prawym górnym rogu karty otwiera dashboard lub widok o tej ścieżce, np. /lovelace/home lub /dashboard-house/0. Bez etykiety pokazuje ⌂.", + "card_alerts": "Pokazuj ostrzeżenia", + "card_alerts_hint": "Dym, gaz, CO, woda, alarm i okna otwarte w deszczu: pomieszczenie pulsuje, u góry pojawia się komunikat", + "card_alert_jump": "Przejdź do pomieszczenia nowego ostrzeżenia", + "card_alert_jump_hint": "Widok sam przełącza się na piętro i pomieszczenie ostrzeżenia", + "card_scenes": "Przyciski scen w pomieszczeniu", + "card_scenes_hint": "Sceny i skrypty obszaru jako przyciski pod widokiem 3D, gdy zaznaczone jest pomieszczenie", + "card_sensor_bar": "Własne czujniki u góry", + "card_sensor_bar_hint": "Czujniki wybrane w edytorze (Ustawienia) w lewym górnym rogu karty", + "card_central_open": "Menu gwiazdki otwarte i duże", + "card_central_open_hint": "Ulubione i własne przyciski są otwarte od początku, większe", + "card_keep_camera": "Zachowaj kamerę przy zmianie piętra", + "card_keep_camera_hint": "Ta sama strona, wysokość i odległość na każdym piętrze", + "card_today": "Karta „Dziś”", + "card_today_hint": "Dzisiejsze terminy i pojemniki do wystawienia, w prawym górnym rogu", + "card_announcements": "Komunikaty", + "card_announcements_hint": "Komunikaty (akcja „NextFloor: Komunikat”) pojawiają się duże na karcie, z gongiem, i są wypowiadane", + "weather_short": "Pogoda", + "weather_entity": "Encja pogody", + "weather_effects": "Efekty pogody w 3D", + "card_weather_density": "Ilość deszczu i śniegu", + "card_weather_density_hint": "Mniej kropli i płatków, niż podaje pogoda; chmury, mgła i błyskawice zostają", + "rain_warning": "Ostrzeżenie: okno otwarte podczas deszczu", + "sun_patches": "Słońce i cienie", + "sun_patches_hint": "Przy ustawionej północy światło słońca z sun.sun pada przez okna jasnymi plamami na podłogę, a dom rzuca cień na działkę. Odznacz, aby podłoga i działka zostały bez plam słońca i cieni.", + "sun_arc": "Łuk słońca i kompas", + "sun_arc_hint": "Rysuje dzisiejszą drogę słońca jako łuk nad działką, z pierścieniem i stronami świata na ziemi (północ na czerwono). Wymaga lokalizacji domu w Home Assistant.", + "weather_effect_rain": "Deszcz", + "weather_effect_snow": "Śnieg", + "weather_effect_fog": "Mgła (szarzy scenę)", + "weather_effect_clouds": "Chmury przyciemniają niebo i słońce", + "weather_effect_lightning": "Błyskawice w czasie burzy", + "weather_effect_sky": "Słońce i księżyc na niebie", + "weather_entity_hint": "Która encja pogody steruje niebem wokół domu. Automatycznie używa pierwszej znalezionej.", + "weather_hint": "Pogoda przy domu: deszcz i śnieg padają z prawdziwym wiatrem, chmury przesuwają się nad działką z cieniami, błyskawice, mgła, słońce i księżyc", + "card_weather": "Pogoda na zewnątrz", + "card_weather_hint": "Deszcz, śnieg, grad, chmury z cieniami, błyskawice i mgła z pierwszej encji pogody (weather_entity wybiera inną); mniej cząsteczek na poziomie tablet", + "alerts": "Ostrzeżenia", + "alert_smoke": "Dym: {name}", + "alert_gas": "Gaz: {name}", + "alert_co": "Tlenek węgla: {name}", + "alert_water": "Woda: {name}", + "alert_alarm": "Alarm wyzwolony", + "alert_alarm_by": "Alarm wywołany przez {cause}", + "alert_alarm_pending": "Alarm oczekuje", + "alert_window_rain": "Okno otwarte w deszczu: {name}", + "alert_power_outage": "Brak zasilania: {name}", + "alert_contact_lost": "Czujnik nie odpowiada: {name}", + "rain_sensor": "Czujnik deszczu (własna stacja pogodowa)", + "outage_sensor": "Czujnik braku zasilania", + "outage_hint": "Czujnik binarny klasy power, który jest wyłączony, inny czujnik binarny, który jest włączony, stan taki jak \"off_grid\" lub \"backup\" albo napięcie poniżej 50 V wywołują ostrzeżenie dla całego domu.", + "contact_warning": "Ostrzegaj, gdy czujnik drzwi lub okna jest niedostępny", + "contact_warning_hint": "Gdy czujnik jest niedostępny od 10 minut (pusta bateria, poza zasięgiem), okno w 3D wygląda na zamknięte, choć nikt tego nie wie. Wtedy komunikat podaje czujnik. Restart Home Assistant nie ostrzega.", + "night_lock_warning": "Ostrzegaj w nocy, gdy drzwi nie są zamknięte na klucz", + "night_lock_warning_hint": "Między 22 a 6 komunikat wymienia zamki z planu, które nie są zamknięte.", + "alert_unlocked_night": "Niezamknięte: {name}", + "motion_markers_active": "Pokazuj czujniki ruchu tylko, gdy coś wykryją", + "motion_markers_active_hint": "Dotyczy czujników ruchu, zajętości i obecności. Czujnik, którego symbol ma być zawsze widoczny, pozostaje widoczny.", + "room_double_tap": "Podwójne dotknięcie pokoju", + "room_double_tap_hint": "Podwójne dotknięcie pokoju wyłącza jego światła, gdy któreś świeci, w przeciwnym razie włącza wszystkie. Urządzenia, które najpierw pytają, są zawsze pomijane.", + "room_double_tap_area": "Lampy w planie i wszystkie światła obszaru", + "room_double_tap_plan": "Tylko lampy w planie", + "room_double_tap_off": "Nic nie przełączaj", + "card_room_double_tap_auto": "Jak ustawiono w planie", + "status_entities": "Własne czujniki u góry widoku 3D", + "status_add": "Dodaj czujnik", + "status_entities_hint": "Na przykład temperatura zewnętrzna, alarm lub jakość powietrza: pokazują się w lewym górnym rogu z nazwą i wartością, także w otwartym pomieszczeniu. Dotknięcie otwiera szczegóły. Do 12.", + "announce_tts": "Zamiana tekstu na mowę dla komunikatów", + "announce_phrases": "Zdania komunikatów (jedno w wierszu)", + "announce_phrases_hint": "Puste: zdania dołączone do NextFloor. Komunikaty są też akcją „NextFloor: Komunikat” dla automatyzacji – na głośnikach pomieszczeń i na każdym otwartym ekranie NextFloor.", + "opening_rain_warning": "Ostrzegaj, gdy pada", + "opening_light_well": "Doświetlacz z przodu", + "sill_boards": "Parapet i podokiennik", + "sill_boards_auto": "Automatycznie", + "sill_boards_none": "Brak", + "sill_boards_inside": "Tylko wewnątrz", + "sill_boards_outside": "Tylko na zewnątrz", + "room_names_short": "Nazwy pomieszczeń", + "floor_stack_short_dim": "Przyciemnione", + "floor_stack_short_stacked": "Ułożone", + "floor_stack_short_single": "Osobno", + "size_short_w": "S", + "size_short_d": "G", + "size_short_h": "W", + "import_error_not_json": "Plik nie jest JSON.", + "import_error_not_plan": "Plik nie jest planem NextFloor.", + "import_other_hint": "Ze Sweet Home 3D: zaimportuj tutaj plik .sh3d. Przenoszone są piętra, pomieszczenia, drzwi, okna i wolne ściany, meble nie.", + "import_sh3d_found": "Sweet Home 3D: {floors} pięter, {rooms} pomieszczeń, {openings} drzwi i okien, {walls} wolnych ścian ({furniture} mebli nie przeniesiono).", + "import_dxf_found": "DXF: {rooms} pomieszczeń (zamknięte polilinie) i {walls} wolnych ścian (linie) na jednym piętrze.", + "import_ifc_found": "W pliku IFC: {floors} pięter i {rooms} pomieszczeń (ściany NextFloor rysuje z pomieszczeń).", + "import_roomplan_found": "Skan pomieszczenia (RoomPlan): {rooms} pomieszczeń, {openings} drzwi i okien; {skipped} obiektów nie przeniesiono (meble ustawiasz sam).", + "import_error_roomplan_empty": "Skan nie zawiera ścian.", + "import_error_ifc_empty": "Plik IFC nie zawiera przestrzeni (IfcSpace) z obrysem.", + "import_error_dxf_empty": "Plik DXF nie zawiera linii ani polilinii.", + "import_error_sh3d": "To nie jest czytelny plik Sweet Home 3D (wymaga Sweet Home 3D 5.3 lub nowszego).", + "import_error_sh3d_empty": "Plik Sweet Home 3D nie ma pomieszczeń ani ścian.", + "export_name_template": "szablon", + "export_name_backup": "kopia", + "card_floor_stack": "Piętra poniżej", + "floor_stack_dim": "Przyciemnione", + "floor_stack_stacked": "Ułożone (dom do tego miejsca)", + "floor_stack_single": "Ukryte (tylko to piętro)", + "card_control_walls": "Wysokie ściany/przekrój", + "card_control_floors": "Piętra rozsunięte", + "card_control_temperature": "Temperatura", + "card_control_humidity": "Wilgotność", + "card_control_co2": "CO₂", + "card_controls_hint": "Wysokie ściany/przekrój, rozsunięte piętra oraz temperatura, wilgotność, CO₂ do przełączania", + "controls_hide": "Ukryj sterowanie – zostaje tylko widok 3D", + "nav_wrap": "Zawijaj pasek: wszystkie piętra i pomieszczenia w kilku wierszach", + "bars_fold": "Zwiń przełączniki", + "bars_unfold": "Przełączniki", + "nav_row": "Pasek w jednym wierszu (przewija się w bok)", + "controls_show": "Pokaż ponownie sterowanie", + "card_controls_hidden": "Zacznij z ukrytym sterowaniem", + "card_controls_hidden_hint": "Tylko widok 3D; oko w lewym dolnym rogu przywraca paski, wartości i przełączniki", + "card_controls_hide_after": "Ukryj sterowanie po", + "card_hide_after_s": "{n} s bez dotyku", + "card_fullscreen_button": "Przycisk pełnego ekranu", + "card_fullscreen_button_hint": "Ukrywa dashboard wokół karty (np. na tablecie ściennym)", + "fullscreen": "Pełny ekran", + "fullscreen_exit": "Zamknij pełny ekran", + "card_section_show": "Pokaż", + "card_floor": "Piętro", + "card_floor_house": "Cały dom (dotknij piętra, by je otworzyć)", + "card_height": "Wysokość (piksele)", + "card_walls": "Ściany", + "card_quality_hint": "„Tablet” to najlżejsze ustawienie – idealne dla tabletów Fire i innych tabletów ściennych.", + "card_flows_switch": "Przełącznik w karcie", + "card_flows_on": "Zawsze wł.", + "card_flows_off": "Zawsze wył.", + "holos": "Karty", + "holos_hint": "Pokaż lub ukryj karty na żywo nad domem (bilans energii, samochód, multimedia)", + "card_energy": "Pokaż wartości energii u góry", + "card_room_panel": "Szczegóły pomieszczenia po dotknięciu", + "card_room_buttons": "Przyciski pomieszczeń", + "card_room_buttons_hint": "Rząd z jednym przyciskiem na pomieszczenie u góry karty – dotknij, by otworzyć pomieszczenie, jak w modelu", + "card_room_panel_hint": "Światła i rolety pomieszczenia w panelu bocznym", + "card_explode": "Rozsuń piętra w widoku domu", + "card_roof_fade": "Wygaszaj dach przy przybliżaniu", + "card_roof_fade_hint": "Wył.: dach zostaje na domu, nawet gdy kamera się zbliża.", + "card_stats": "Wskaźnik wydajności (klatki na sekundę)", + "card_stats_hint": "Aby sprawdzić, jak płynnie karta działa na urządzeniu", + "packs": "Pakiety mebli", + "lib_badge_light": "Lampa: łączy się ze światłem i przełącza w 3D", + "lib_badge_electric": "Elektryczne: łączy się z encją i czujnikiem mocy (przełączanie, obrazy, zużycie)", + "lib_badge_hint": "Elementy z symbolem łączą się z encjami: lampy przełączają, ekrany pokazują obrazy, urządzenia pokazują zużycie.", + "care_bin_today": "Odbiór dzisiaj", + "care_bin_tomorrow": "Odbiór jutro", + "care_bin_days": "Za {n} dni", + "care_mail_yes": "Jest poczta", + "care_mail_no": "Pusta", + "care_plant_thirsty": "Spragniona", + "care_plant_ok": "Dobrze podlana", + "care_time_left": "Pozostało {time}", + "care_entity_bin": "Data odbioru (czujnik)", + "care_entity_mail": "Czujnik poczty", + "care_entity_plant": "Wilgotność gleby (czujnik)", + "care_thirsty_below": "Spragniona poniżej (%)", + "care_hint_bin": "Czujnik z najbliższym odbiorem: dni, data, \"dziś\"/\"jutro\" lub integracja Waste Collection Schedule. Pojemnik świeci dzień wcześniej i w dniu odbioru.", + "care_hint_mail": "Czujnik zgłaszający pocztę w skrzynce (np. kontaktron na klapce). Skrzynka wtedy świeci.", + "care_hint_plant": "Czujnik wilgotności w ziemi. Poniżej progu roślina świeci i mówi, że chce pić.", + "lib_cat_lights": "Światła", + "lib_cat_seating": "Siedziska", + "lib_cat_tables": "Stoły", + "lib_cat_storage": "Szafy i regały", + "lib_cat_beds": "Łóżka", + "lib_cat_kitchen": "Kuchnia", + "lib_cat_appliances": "Urządzenia AGD", + "lib_cat_bath": "Łazienka", + "lib_cat_media": "TV i audio", + "lib_cat_office": "Biuro", + "lib_cat_tech": "Technika", + "lib_cat_climate": "Ogrzewanie i klimat", + "lib_cat_energy": "Energia", + "lib_cat_garden": "Ogród i taras", + "lib_cat_plants": "Rośliny", + "lib_cat_kids": "Dzieci", + "lib_cat_fitness": "Fitness", + "lib_cat_pets": "Zwierzęta", + "lib_cat_workshop": "Warsztat i garaż", + "lib_cat_music": "Muzyka i pracownia", + "lib_cat_season": "Sezon i dekoracje", + "lib_cat_pictures": "Obrazy i ramki", + "lib_cat_vehicles": "Pojazdy", + "lib_cat_building": "Schody i elementy budynku", + "lib_cat_decor": "Dekoracje i inne", + "lib_favourites": "Ulubione", + "lib_recent": "Ostatnio używane", + "lib_for_room": "Pasuje do {room}", + "lib_all_rooms": "Pokaż wszystkie pomieszczenia", + "lib_linkable": "do połączenia", + "lib_lit": "świecące", + "lib_outdoor": "zewnętrzne", + "lib_fav_add": "Dodaj do ulubionych", + "lib_fav_remove": "Usuń z ulubionych", + "lib_sizes": "Rozmiary", + "feature_name_energy": "Przepływ energii", + "ext_tab": "Rozszerzenia", + "ext_title": "Rozszerzenia", + "models": "Własne modele 3D", + "models_hint": "Dla niektórych pojazdów NextFloor może pokazać prawdziwy model 3D, jeśli go posiadasz. Wybierz tu plik (.glb): NextFloor ustawi go właściwie, odchudzi, oznaczy lakier i zapisze w Twoim Home Assistant. Bez modelu pojazd wygląda jak wcześniej.", + "models_licence": "Pliki są Twoje i zostają w Twoim Home Assistant. NextFloor nie dostarcza modeli; upewnij się, że licencja modelu pozwala używać go we własnej instalacji.", + "model_add": "Dodaj model …", + "model_replace": "Zastąp model …", + "model_remove": "Usuń", + "model_present": "w użyciu", + "model_missing": "jeszcze brak", + "model_remove_confirm": "Usunąć model „{id}” z Home Assistant?", + "model_removed": "Usunięto model „{id}”.", + "model_uploaded": "Zapisano model „{id}” ({size}). Odśwież panel, by go zobaczyć.", + "model_upload": "Zapisz w Home Assistant", + "model_info": "{triangles} trójkątów, {size} m", + "model_front": "Przód", + "model_front_hint": "Obracaj model, aż jego przód będzie skierowany do patrzącego (w lewo w dół na obrazie).", + "model_paint": "Lakier (kolor wybierany w edytorze)", + "model_paint_preview": "Kolor w podglądzie", + "model_detail": "Poziom szczegółów", + "model_detail_light": "Lekki (tablet)", + "model_detail_normal": "Normalny", + "model_detail_fine": "Dokładny", + "model_result": "Wynik: {triangles} trójkątów, {size}", + "model_error_not_glb": "To nie jest plik .glb (binarny glTF). Wyeksportuj model jako „glTF binary”.", + "model_error_compressed": "Plik jest skompresowany (Draco, Meshopt lub KTX). Wyeksportuj go bez kompresji.", + "model_error_empty": "Plik nie zawiera niczego trójwymiarowego.", + "model_error_unreadable": "Nie można odczytać pliku: {detail}", + "model_error_too_large": "Plik jest większy niż {max}. Wybierz niższy poziom szczegółów.", + "model_upload_forbidden": "Tylko administratorzy mogą przesyłać modele.", + "model_upload_too_large": "Home Assistant nie przyjmuje plików większych niż {max}. Wybierz niższy poziom szczegółów.", + "model_upload_not_glb": "Home Assistant odrzucił plik (to nie binarny glTF).", + "model_upload_bad_id": "Identyfikator modelu jest nieprawidłowy.", + "model_upload_other": "Przesyłanie nie powiodło się: {detail}", + "ext_intro": "Importuj tu własne pakiety mebli, przesyłaj własne modele 3D i dodawaj wtyczki.", + "plugin": "wtyczka", + "plugins_title": "Wtyczki", + "plugins_intro": "Wtyczki dodają własne animacje światła, urządzenia i karty w panelu pomieszczenia. Wpisz adres wtyczki (plik .js w /config/www, czyli /local/…, z HACS /hacsfiles/… lub https://…).", + "plugins_docs": "Jak napisać wtyczkę", + "plugins_warning": "Wtyczki działają z tymi samymi uprawnieniami co NextFloor w Twojej przeglądarce. Używaj tylko wtyczek z zaufanych źródeł.", + "plugins_off": "wył.", + "plugins_error": "błąd", + "plugins_loading": "wczytywanie …", + "plugins_nothing_registered": "wczytana, ale nic nie zarejestrowała", + "plugins_loaded": "aktywna", + "plugins_reload_hint": "Działa po odświeżeniu strony", + "plugins_remove": "Usuń", + "plugins_none": "Brak wtyczek.", + "plugins_from_dashboard": "Zarejestrowana przez zasób dashboardu", + "plugins_add": "Dodaj", + "plugins_url_invalid": "Wpisz adres .js pod /local/…, /hacsfiles/… lub https://….", + "plugins_exists": "Ta wtyczka jest już na liście.", + "plugins_limit": "Najwyżej 20 wtyczek.", + "packs_title": "Pakiety mebli", + "packs_intro": "Importuj własne meble jako pakiet (JSON): jako plik lub wklejone poniżej. {n} pakietów jest dołączonych do NextFloor i zawsze dostępnych.", + "packs_docs": "Format pakietu", + "packs_none": "Brak własnych pakietów.", + "community_title": "Meble społeczności", + "community_intro": "Meble zbudowane i udostępnione przez innych w kreatorze mebli – sprawdzone i darmowe. Zbuduj własne:", + "community_builder": "Otwórz kreator mebli", + "community_how": "Jak udostępnić swoje", + "community_load": "Wczytaj meble społeczności", + "community_none": "Jeszcze nie ma mebli społeczności – bądź pierwszy!", + "community_install": "Zainstaluj", + "community_update": "Aktualizuj", + "community_installed": "Zainstalowano", + "community_failed": "Nie udało się wczytać mebli społeczności: {detail}", + "pack_import": "Importuj pliki pakietów …", + "pack_paste": "Importuj JSON", + "pack_paste_empty": "Najpierw wklej JSON pakietu.", + "pack_paste_not_json": "To nie jest prawidłowy JSON: {detail}", + "pack_imported": "Zaimportowano „{name}” od {publisher} – {n} elementów", + "packs_imported_n": "Zaimportowano {n} z {total} pakietów", + "pack_by": "od {publisher} · {n} elementów", + "pack_remove": "Usuń", + "pack_remove_confirm": "Usunąć pakiet „{name}”? Jego meble zostaną w planie jako zwykłe bryły.", + "pack_error_not_a_pack": "To nie jest pakiet mebli (brak \"format\": \"nfpack\").", + "pack_error_builtin": "Dołączony do NextFloor pakiet ma już ten identyfikator.", + "pack_error_invalid_content": "Pakiet zawiera nieprawidłowe meble: {detail}", + "pack_error_too_large": "Pakiet jest za duży (najwyżej 1 MB).", + "pack_error_needs_update": "Ten pakiet wymaga nowszej wersji NextFloor. Najpierw zaktualizuj (HACS › NextFloor › ⋮ › \"Informacje o aktualizacji\" › \"Pobierz\"), uruchom ponownie Home Assistant i zaimportuj jeszcze raz.", + "pack_error_other": "Import nie powiódł się: {detail}", + "store_open": "Otwórz sklep z wtyczkami", + "store_close": "Zamknij sklep z wtyczkami", + "store_intro": "Sprawdzone wtyczki społeczności. Każda jest przejrzana przed dodaniem i potem się nie zmienia.", + "store_submit": "Zgłoś własną wtyczkę", + "store_empty": "Brak wtyczek w sklepie.", + "store_failed": "Nie udało się wczytać sklepu ({error}).", + "store_install": "Zainstaluj", + "store_installed": "zainstalowana", + "store_update": "Aktualizuj", + "store_confirm": "Zainstalować „{name}” od {author}?\n\nWtyczka działa z tymi samymi uprawnieniami co NextFloor w Twojej przeglądarce. Plik został sprawdzony, a jego treść jest niezmienna:\n{url}", + "manual": "Instrukcja", + "manual_more": "Dowiedz się więcej", + "feature_text_energy": "Cząsteczki energii lecą łukami z pól solarnych do falownika, między domem, magazynem, siecią i odbiornikami – szybciej i gęściej, im więcej mocy płynie. Moduły skrzą się swoją produkcją, szklana karta nad dachem pokazuje bilans i to, jak samowystarczalny jest teraz dom.", + "live_autarky": "autarkia", + "live_day_hint": "Ostatnie 24 godziny: słońce (pole) i zużycie (linia)", + "live_week_hint": "Ostatnie 7 dni: słońce {solar} kWh, zużycie {use} kWh (żółty: słońce, jasny: zużycie)", + "live_days": "dni", + "live_car_away": "W drodze", + "live_car_charging": "Ładowanie", + "live_car_plugged": "Podłączony", + "live_car_lock": "Zablokuj", + "live_car_unlock": "Odblokuj", + "live_car_unlock_confirm": "Naprawdę odblokować {name}?", + "live_car_climate": "Klimatyzacja", + "live_car_charge": "Uruchom/zatrzymaj ładowanie", + "live_media_prev": "Poprzedni", + "live_media_playpause": "Odtwórz/pauza", + "live_media_next": "Następny", + "live_media_volume": "Głośność", + "live_car_device": "Samochód (dowolna encja samochodu)", + "live_car_device_hint": "Stan naładowania, zasięg, ładowanie, wtyczkę, zamek i klimatyzację NextFloor znajduje na urządzeniu samochodu. Bez niego używa czujnika obecności miejsca.", + "live_car_departure_entity": "Godzina wyjazdu (opcjonalnie)", + "live_car_departure": "Wyjazd {time}", + "live_car_open": "Otwarte: {parts}", + "printer_printing": "drukuje", + "printer_done": "gotowe", + "printer_paused": "wstrzymano", + "printer_error": "błąd", + "printer_idle": "gotowa", + "printer_done_at": "gotowe o {time}", + "printer_layer": "Warstwa", + "printer_nozzle": "Dysza", + "printer_bed": "Stół", + "heatpump_heating": "grzeje", + "heatpump_water": "ciepła woda", + "heatpump_cooling": "chłodzi", + "heatpump_defrost": "odszrania", + "heatpump_idle": "w spoczynku", + "heatpump_flow_return": "Zasilanie → powrót", + "heatpump_heat": "Ciepło", + "heatpump_power": "Prąd", + "heatpump_outside": "na zewnątrz", + "pack_missing_item": "Mebel z usuniętego pakietu", + "back_to_room": "Wróć do {room}", + "back_to_floor": "Wróć do piętra", + "hint_furniture": "Dotknij pomieszczenia, potem wybierz element po prawej · przeciągaj elementy, zmieniaj rozmiar za narożniki", + "furniture_into": "Nowe elementy trafiają na środek „{room}”.", + "furniture_pick_room": "Wskazówka: najpierw dotknij pomieszczenia – nowe elementy pojawią się na jego środku.", + "flows": "Przepływ energii", + "flows_hint": "Pokaż lub ukryj łuki energii między polami solarnymi, falownikiem, magazynem, siecią i odbiornikami", + "chk_title": "Konfiguracja", + "chk_hint": "Czego potrzebuje przepływ energii. Dotknij wiersza, by tam przejść.", + "chk_solar": "Pole solarne na miejscu", + "chk_solar_add": "Połóż pole solarne na dachu", + "chk_meter": "Licznik z czujnikiem sieci", + "chk_meter_sensor": "Licznik: brak czujnika sieci (W)", + "chk_meter_add": "Dodaj licznik", + "chk_inverter": "Falownik z czujnikiem mocy", + "chk_inverter_sensor": "Falownik: brak czujnika mocy", + "chk_inverter_add": "Dodaj falownik", + "chk_battery": "Magazyn energii z mocą i stanem naładowania", + "chk_battery_sensor": "Magazyn energii: brak mocy lub stanu naładowania", + "chk_battery_opt": "Magazyn energii (opcjonalnie)", + "chk_grid": "Przyłącze sieci ustawione", + "chk_grid_opt": "Przyłącze sieci (opcjonalnie, inaczej automatycznie)", + "energy_sign_grid": "Dom pokazuje oddawanie do sieci, gdy słońce nic nie produkuje. Czujnik sieci ma prawdopodobnie odwrócony znak.", + "energy_sign_battery": "Magazyn ładuje się bez słońca i bez poboru z sieci. Jego czujnik ma prawdopodobnie odwrócony znak.", + "energy_sign_flip": "Odwróć znak", + "help_title": "Pomoc i opinie", + "help_hint": "Zgłaszaj problemy jako issue na GitHubie, a życzenia jako discussion – nic nie zginie, a wszyscy widzą stan.", + "help_issue": "Zgłoś problem", + "help_idea": "Zaproponuj pomysł", + "furn_name": "Nazwa (opcjonalnie)", + "furn_mirror": "Odbij lustrzanie", + "furn_mirror_hint": "Zamień lewo i prawo – narożnik w drugą stronę, szafa z drzwiami po drugiej stronie, ciąg kuchenny odbity.", + "hint_opening": "Dotknij ściany, by dodać drzwi lub okno – rodzaj wybierz potem po prawej", + "preset_door": "Drzwi", + "preset_door_double": "Drzwi dwuskrzydłowe", + "preset_window": "Okno", + "preset_window_double": "Okno dwuskrzydłowe", + "preset_terrace": "Drzwi tarasowe", + "preset_terrace_double": "Drzwi balkonowe dwuskrzydłowe", + "preset_lift_slide": "Drzwi podnośno-przesuwne", + "preset_garage": "Brama garażowa", + "preset_front": "Drzwi wejściowe", + "opening_style": "Styl", + "sidelight_auto": "automatycznie", + "sidelight_hinge": "Doświetle po stronie zawiasów", + "sidelight_hinge_hint": "Inaczej doświetle jest naprzeciw zawiasów; zaznaczone – obok zawiasów.", + "sidelight_width": "Szerokość doświetla (m)", + "sidelight_width_left": "Lewe doświetle (m)", + "sidelight_width_right": "Prawe doświetle (m)", + "style_auto": "Automatycznie ({style})", + "style_interior": "Drzwi wewnętrzne", + "style_front": "Drzwi wejściowe", + "style_front_glass": "Drzwi wejściowe z szybą", + "style_sidelight": "Drzwi wejściowe z doświetlem", + "style_sidelights": "Drzwi wejściowe z dwoma doświetlami", + "style_glass": "Drzwi szklane", + "style_sliding": "Drzwi przesuwne", + "style_passage": "Otwór (bez drzwi)", + "style_standard": "Standard", + "style_bars": "Ze szprosami", + "style_glass_wall": "Ściana szklana (stała)", + "preset_glass_wall": "Ściana szklana", + "flip_hinge": "Zamień stronę zawiasów", + "flip_main_leaf": "Zamień skrzydło główne", + "flip_hinge_hint": "Zawiasy na drugą stronę", + "flip_swing": "Odwróć kierunek otwierania", + "flip_swing_hint": "Drzwi otwierają się do pomieszczenia lub na drugą stronę", + "main_leaf": "Skrzydło główne (od strony pomieszczenia)", + "contact_main": "Kontakt skrzydła głównego", + "contact_second": "Kontakt drugiego skrzydła", + "tool_outdoor": "Zewnętrze", + "tool_measure": "Według wymiarów", + "hint_measure": "Dotknij punktu początkowego, potem wpisz po prawej długości ścian z kierunkiem", + "measure": "Pomieszczenie według wymiarów", + "measure_start": "Dotknij punktu początkowego w planie, np. narożnika pomieszczenia.", + "measure_from": "Start w {x} / {z} m – dotknięcie przesuwa start.", + "measure_length": "Długość następnej ściany (m)", + "measure_close": "Zamknij pomieszczenie", + "measure_undo": "Usuń ostatnią ścianę", + "measure_gap": "Odstęp do startu: {gap} m (łączony przy zamykaniu)", + "measure_hint": "Wskazówka: wpisz długość i naciśnij strzałkę. Przy zmierzonych wymiarach wewnętrznych użyj potem „Zamknij szczeliny”.", + "rect_by_size": "Prostokąt według wymiarów", + "rect_add": "Dodaj prostokąt", + "dir_up": "W górę", + "dir_down": "W dół", + "dir_left": "W lewo", + "dir_right": "W prawo", + "hint_outdoor": "Przeciągnij, by narysować teren zewnętrzny (trawnik, taras, basen …)", + "outdoor": "Teren zewnętrzny", + "outdoor_type": "Typ", + "outdoor_height": "Wysokość (m)", + "outdoor_offset": "Przesunięcie wysokości (m, − = niżej)", + "outdoor_outline": "Pokaż obrys", + "outdoor_outline_hint": "Odznaczony teren nie rysuje świecącej linii wzdłuż krawędzi – dla dużych działek z kilku trawników.", + "outdoor_corners_hint": "Narożniki: + na krawędzi dodaje narożnik, przeciąganie kształtuje teren, × usuwa narożnik.", + "outdoor_hint": "Lampy zewnętrzne (słupek, reflektor ogrodowy, kinkiet zewnętrzny) oświetlają wszystkie tereny zewnętrzne i elewację.", + "out_lawn": "Trawnik", + "out_terrace": "Taras", + "out_path": "Ścieżka", + "out_driveway": "Podjazd", + "out_pool": "Basen", + "out_bed": "Rabata", + "out_hedge": "Żywopłot", + "out_fence": "Ogrodzenie", + "out_wild": "Dziki zakątek", + "out_pergola": "Pergola / rama", + "outdoor_open": "Otwarty (pomiń ostatnią krawędź)", + "outdoor_open_hint": "Krawędź od ostatniego punktu do pierwszego nie jest rysowana – płot lub pergola oparta o dom.", + "fence_gates": "Bramy w ogrodzeniu", + "gate_add": "+ Brama w ogrodzeniu", + "gate_edge": "Bok ogrodzenia", + "gate_kind": "Rodzaj", + "gate_single": "Furtka", + "gate_double": "Brama dwuskrzydłowa", + "gate_sliding": "Brama przesuwna", + "gate_offset": "Środek od początku (m)", + "gate_width": "Szerokość (m)", + "gate_entity": "Napęd lub przełącznik", + "gate_contact": "Kontaktron (włączony = otwarta)", + "fence_gates_hint": "Brama to przerwa w ogrodzeniu ze słupkami i skrzydłem. Z napędem (cover, przełącznik, input_boolean, zamek) i/lub kontaktronem otwiera się w 3D: furtka i brama dwuskrzydłowa wahają się do środka, brama przesuwna jedzie wzdłuż ogrodzenia.", + "outdoor_bracing": "Stężenie krzyżowe", + "outdoor_cut": "Wytnij z otaczających terenów", + "outdoor_cut_hint": "Każdy teren, który w całości zawiera ten, dostaje tu otwór – basen w tarasie, staw lub dziki zakątek w trawniku. Kolejność rysowania nie ma znaczenia. Basen wycina się sam.", + "outdoor_area_hint": "Obszar Home Assistant tej powierzchni (ogród, taras, basen): jego urządzenia i czujniki są w sekcji Na zewnątrz, a znacznik na powierzchni ją otwiera.", + "pool_temp": "Temperatura wody (opcjonalnie)", + "pool_pump": "Pompa / filtr (opcjonalnie)", + "pool_pump_on": "pompa pracuje", + "outdoor_slope": "Spadek (m)", + "outdoor_slope_hint": "Różnica wysokości od wysokiej do niskiej krawędzi; wysoka krawędź leży na przesunięciu wysokości. Lampy na terenie podążają za nim.", + "outdoor_slope_dir": "Opada w stronę", + "slope_x": "prawo (+X)", + "slope_nx": "lewo (−X)", + "slope_z": "dół (+Z)", + "slope_nz": "góra (−Z)", + "north": "Północ (° zgodnie z ruchem wskazówek od góry)", + "north_hint": "Północ jest potrzebna dla słońca (światło przez okna).", + "map_on": "Pokaż prawdziwą mapę pod planem", + "map_lat": "Szerokość geograficzna", + "map_lon": "Długość geograficzna", + "map_use_ha": "Użyj lokalizacji Home Assistant", + "map_opacity": "Widoczność (%)", + "map_zoom": "Poziom szczegółów", + "map_zoom_coarse": "zgrubny", + "map_zoom_fine": "dokładny", + "map_move": "Przesuń mapę pod planem", + "map_step": "Krok", + "map_url": "Własny adres kafelków (puste = OpenStreetMap)", + "map_hint": "Przeglądarka wczytuje kafelki mapy bezpośrednio z serwera map (domyślnie OpenStreetMap, przestrzegaj ich zasad użycia); gdy mapa jest wyłączona, nic nie jest wczytywane. Plan leży na mapie zgodnie z kompasem – obróć kompas lub przesuń mapę, aż dom będzie pasował.", + "compass_title": "Kompas", + "compass_n_short": "N", + "compass_s_short": "S", + "compass_swap": "Zamień północ ↔ południe", + "compass_swap_hint": "Obraca kompas o 180°. Rysunek, połacie dachu i pola solarne zostają bez zmian.", + "compass_hint": "Jeśli kompas nie zgadza się z rzeczywistością, obróć go tutaj – nic nie trzeba rysować od nowa. Światło słońca, wiatr i kierunki połaci dachu podążają za nim.", + "roof": "Dach", + "roof_none": "Bez dachu", + "roof_flat": "Dach płaski", + "roof_gable": "Dach dwuspadowy", + "roof_custom": "Połacie dachu (własne)", + "roof_sections": "Połacie dachu", + "roof_sections_hint": "Każda połać dachu pokrywa prostokąt domu, np. dom, stodołę lub dobudówkę – każda z własnym kształtem, kierunkiem kalenicy, wysokością okapu i nachyleniem. Przeciągnij w planie, by narysować nową; dotknięcie zaznacza, przeciąganie przesuwa, narożniki zmieniają rozmiar.", + "roof_sections_start": "Utwórz połacie dachu z pomieszczeń", + "roof_sections_regen": "Utwórz ponownie z pomieszczeń", + "roof_sections_off": "Wróć do jednego dachu", + "roof_regen_confirm": "Zastąpić wszystkie połacie dachu nową propozycją z pomieszczeń?", + "roof_section": "Połać dachu", + "roof_section_hint": "Wysokości liczone są od gruntu. Strona z niższym okapem sięga niżej (catslide); dachy jednospadowe wznoszą się od pierwszej strony.", + "roof_shape_gable": "Dwuspadowy", + "roof_shape_hip": "Czterospadowy", + "roof_shape_pent": "Jednospadowy", + "roof_shape_flat": "Płaski", + "roof_shape_halfhip": "Naczółkowy", + "roof_shape_pyramid": "Namiotowy", + "roof_shape_mansard": "Mansardowy", + "roof_shape_parapet": "Z attyką", + "roof_shape": "Kształt", + "roof_end_start": "Zakończenie na początku kalenicy", + "roof_end_end": "Zakończenie na końcu kalenicy", + "roof_halfhip": "Naczółek zaczyna się na", + "roof_halfhip_hint": "Na jakiej wysokości szczytu zaczyna się naczółek, jako część wysokości szczytu: nisko = duży naczółek, wysoko = tylko wierzchołek.", + "roof_axis_x": "Kalenica ↔", + "roof_axis_z": "Kalenica ↕", + "roof_eave": "Okap (m)", + "roof_pitch_short": "Nachylenie (°)", + "roof_height": "Wysokość (m)", + "roof_base": "Wierzch ścian (m)", + "roof_rotation": "Obrót (°)", + "roof_on_floor": "Stoi na piętrze", + "roof_on_floor_hint": "Stawia połać na koronach ścian tego piętra; podstawa i okapy przesuwają się razem. W widoku 3D dach należy do tego piętra.", + "roof_base_hint": "Poniżej wysokości sufitu piętra pod spodem ściany tego piętra kończą się pod dachem: ścianki kolankowe przy okapach, szczyty do kalenicy, ściany wewnętrzne ścięte spadkiem. Przerywane linie w planie pokazują, gdzie zostaje 1,5 m i 2 m wysokości.", + "roof_ridge_height": "Wysokość kalenicy", + "roof_side_top": "góra", + "roof_side_bottom": "dół", + "roof_side_left": "lewo", + "roof_side_right": "prawo", + "roof_swap": "Zamień strony", + "roof_open": "Zadaszenie (słupy zamiast ścian, przezroczyste)", + "roof_open_short": "Zadaszenie", + "roof_dormer": "Lukarna", + "roof_dormer_hint": "Lukarna po tej stronie dachu: szeroka na 2 m, front przy ścianie okapowej, okapy 1,4 m nad okapem dachu, dach dwuspadowy. Potem przesuń ją i zmień szerokość i wysokości jak każdą połać; główny spadek otwiera się pod nią, a ściana poddasza wznosi się do lukarny – zmieści się tam okno.", + "roof_outline": "Przejmij obrys piętra", + "roof_outline_hint": "Dach płaski o dowolnym kształcie: przejmuje obrys pomieszczeń pokazanego piętra (także w kształcie L lub Z) jako jedną powierzchnię bez łączeń. Narożniki można potem przeciągać.", + "roof_points_hint": "Dowolny kształt: przeciągaj narożniki w planie, + na krawędzi dodaje narożnik, × go usuwa. Powrót do prostokąta porzuca kształt.", + "roof_rect": "Wróć do prostokąta", + "roof_open_hint": "Dla zadaszenia tarasu lub wiaty: słupy i belki niosą dach zamiast ścian i jest on przezroczysty. Tam, gdzie zadaszenie styka się ze ścianą domu, opiera się na niej.", + "roof_swap_hint": "Obraca dach: obie strony zamieniają okap i nachylenie, dach jednospadowy wznosi się w drugą stronę.", + "roof_pitch": "Nachylenie dachu (°)", + "roof_overhang": "Okap dachu (m)", + "roof_overhang_sides": "Okap na każdej stronie", + "roof_overhang_a": "Okap A (m)", + "roof_overhang_b": "Okap B (m)", + "roof_overhang_u0": "Okap szczyt początek (m)", + "roof_overhang_u1": "Okap szczyt koniec (m)", + "roof_overhang_auto": "Wróć do automatycznego", + "roof_overhang_sides_hint": "Bez własnych wartości okap jest automatyczny: wszędzie taki sam, poza miejscem, gdzie część dachu styka się z domem (tam brak).", + "roof_ridge": "Kalenica", + "roof_ridge_long": "Wzdłuż dłuższego boku", + "roof_ridge_short": "Wzdłuż krótszego boku (np. szeregowiec)", + "device": "Urządzenie", + "lamp_mount": "Lampa", + "lamp_ceiling": "Lampa sufitowa", + "lamp_floor": "Lampa podłogowa", + "lamp_table": "Lampa stołowa", + "lamp_wall": "Kinkiet", + "marker_height": "Wysokość znacznika (m)", + "height_auto": "Wysokość automatyczna", + "device_centre": "Na środek pomieszczenia", + "lights_spread": "Rozmieść lampy sufitowe równomiernie", + "devices_search": "Szukaj urządzeń …", + "devices_more": "+{n} więcej", + "devices_less": "mniej", + "panel_more": "Więcej urządzeń obszaru ({n})", + "panel_less": "Pokaż mniej", + "gaps_close": "Zamknij szczeliny", + "gaps_hint": "Łączy pomieszczenia oddalone do 60 cm jedną wspólną ścianą; szczelina staje się grubością ściany wewnętrznej.", + "gaps_none": "Nie znaleziono szczelin między pomieszczeniami.", + "gaps_closed": "Zamknięto {n} miejsc.", + "gaps_closed_wall": "Zamknięto {n} miejsc, ściana wewnętrzna ma teraz {t} m.", + "fps": "FPS", + "fps_title": "Wskaźnik wydajności (klatki na sekundę)", + "hint_garage": "Dotknij ściany, by dodać bramę garażową", + "opening_garage": "Brama garażowa", + "garage_hint": "Brama podąża za osłoną garażu (pozycja lub otwarta/zamknięta) albo kontaktronem bramy garażowej z obszaru pomieszczenia.", + "door_hint": "Z kontaktronem skrzydło się otwiera; bez czujnika stoi w połowie otwarte.", + "hint_door": "Dotknij ściany, by dodać drzwi", + "hint_window": "Dotknij ściany, by dodać okno", + "opening_door": "Drzwi", + "opening_window": "Okno", + "opening_type": "Typ", + "opening_position": "Środek od narożnika (m)", + "sill": "Wysokość parapetu (m)", + "opening_height": "Wysokość (m)", + "hinge": "Zawias (od strony pomieszczenia)", + "hinge_left": "Lewy", + "hinge_right": "Prawy", + "cover_entity": "Roleta", + "door_cover": "Napęd (drzwi lub brama z silnikiem)", + "cover_position_entity": "Czujnik pozycji (na żywo)", + "cover_position_invert": "Czujnik liczy odwrotnie (0 = otwarte)", + "contact_entity": "Kontakt", + "sensor_kind": "Typ czujnika", + "sensor_kind_contact": "Kontaktron okienny (otwarte/zamknięte)", + "sensor_kind_handle": "Czujnik klamki (otwarte/uchylone/zamknięte)", + "sensor_kind_contact_tilt": "Kontakt + czujnik uchyłu", + "handle_entity": "Czujnik klamki", + "handle_main": "Czujnik klamki skrzydła głównego", + "leaf_main": "Skrzydło główne", + "leaf_second": "Drugie skrzydło", + "tilt_entity": "Czujnik uchyłu", + "tilt_angle_entity": "Czujnik kąta uchyłu (°, opcjonalnie)", + "tilt_angle_max": "Kąt uznawany za pełny uchył (°)", + "tilt_angle_offset": "Przesunięcie: kąt zgłaszany w stanie zamkniętym (°)", + "tilt_angle_invert": "Kąt liczy odwrotnie", + "door_shut": "Pokaż zamknięte bez czujnika", + "door_shut_hint": "Drzwi bez kontaktu stoją w 3D w połowie otwarte, by było widać, że to drzwi. Zaznaczone – rysowane są zamknięte: drzwi wejściowe, wiata, drzwi boczne.", + "door_angle": "Kąt otwarcia", + "door_angle_default": "Domyślny", + "door_angle_hint": "Jak szeroko otwiera się skrzydło. Z czujnikiem otwiera się tak, gdy zgłosi „otwarte”; bez czujnika stoi otwarte pod tym kątem (zamiast do połowy). Domyślny zostaje jak dotąd.", + "entity_auto": "Automatycznie ({name})", + "entity_auto_none": "Automatycznie (nic nie znaleziono)", + "entity_none": "Brak", + "entity_search": "Pisz, by szukać …", + "opening_hint": "Typ czujnika: kontaktron okienny (zgłasza otwarte/zamknięte), czujnik klamki (zgłasza otwarte, uchylone i zamknięte – np. klamka Homematic) lub kontakt + czujnik uchyłu (drugi czujnik, który zgłasza tylko uchył). Automatycznie używa rolet i kontaktów obszaru pomieszczenia. Czujnik pozycji: encja zgłaszająca pozycję rolety podczas ruchu (np. \"level\" Homematic, 0–100 % lub 0–1, otwarta = wysoko) – roleta porusza się wtedy na żywo w 3D.", + "furniture": "Meble", + "furniture_add": "Dodaj mebel", + "studio_new": "Zbuduj własny mebel", + "studio_title": "Pracownia mebli", + "studio_title_edit": "Pracownia mebli: zmień", + "studio_hint": "Wybierz szablon, ustaw wymiary i fronty i wstaw mebel do planu. Trafia do pakietu „Własne meble” i później można go tu zmienić.", + "studio_kind": "Szablon", + "studio_kind_cabinet": "Szafka", + "studio_kind_shelf": "Regał", + "studio_kind_lamp": "Lampa", + "studio_kind_device": "Urządzenie", + "studio_name": "Nazwa", + "studio_width": "Szerokość (cm)", + "studio_depth": "Głębokość (cm)", + "studio_height": "Wysokość (cm)", + "studio_doors": "Drzwiczki", + "studio_drawers": "Szuflady", + "studio_shelves": "Półki", + "studio_handle": "Uchwyty", + "studio_handle_bar": "Listwa", + "studio_handle_knob": "Gałka", + "studio_handle_none": "Bez", + "studio_base": "Podstawa", + "studio_base_plinth": "Cokół", + "studio_base_legs": "Nóżki", + "studio_base_none": "Brak", + "studio_back": "Plecy", + "studio_lamp": "Rodzaj", + "studio_lamp_floor": "Lampa stojąca", + "studio_lamp_table": "Lampka stołowa", + "studio_lamp_pendant": "Lampa wisząca", + "studio_lamp_wall": "Kinkiet", + "studio_display": "Wyświetlacz z przodu (pokazuje odtwarzacz)", + "studio_mount": "Stoi", + "studio_mount_floor": "Na podłodze", + "studio_mount_surface": "Na meblu", + "studio_mount_wall": "Na ścianie", + "studio_color_body": "Korpus", + "studio_color_lamp_body": "Podstawa i stelaż", + "studio_color_front": "Fronty", + "studio_color_boards": "Półki", + "studio_color_shade": "Klosz", + "studio_color_display": "Ramka wyświetlacza", + "studio_color_white": "Biały", + "studio_color_wood": "Drewno", + "studio_color_metal": "Metal", + "studio_color_dark": "Ciemny", + "studio_color_glass": "Szkło", + "studio_color_accent": "Akcent", + "studio_color_own": "Własny kolor", + "studio_color_plan": "Kolor planu", + "studio_place": "Wstaw do planu", + "studio_save": "Zapisz zmianę", + "studio_open": "Zmień w pracowni", + "studio_error": "Nie udało się zapisać: {detail}", + "studio_pack_name": "Własne meble", + "studio_pack_publisher": "Pracownia mebli", + "furniture_search": "Szukaj mebli …", + "furniture_search_none": "Nic nie znaleziono. Spróbuj innego słowa – po angielsku lub niemiecku.", + "furniture_type": "Element", + "rotation": "Obrót (°)", + "tilt_x": "Pochylenie przód/tył (°)", + "tilt_z": "Pochylenie na bok (°)", + "strip_tilt": "Pochylenie wzdłuż długości (°)", + "strip_upright": "Pionowo", + "strip_rise": "Nachylenie wzdłuż długości (°)", + "strip_upright_hint": "Taśma stoi pionowo: jej długość biegnie w górę od wysokości nad podłogą – wzdłuż ościeżnicy, jako kolumna świetlna. Pochylenie kładzie leżącą taśmę na skosie (90° = przód skierowany w bok).", + "rotate_left": "↺ 90°", + "rotate_right": "↻ 90°", + "height_m": "Wysokość (m)", + "furn_sofa": "Sofa", + "furn_armchair": "Fotel", + "furn_table": "Stół", + "furn_chair": "Krzesło", + "furn_bed": "Łóżko", + "furn_nightstand": "Szafka nocna", + "furn_wardrobe": "Szafa", + "furn_shelf": "Regał", + "furn_kitchen": "Szafka kuchenna", + "furn_worktop": "Blat roboczy", + "furn_fridge": "Lodówka", + "furn_fridge_smart": "Inteligentna lodówka (side by side)", + "furn_door_left": "Czujnik drzwi lewy (strona zamrażarki)", + "furn_door_right": "Czujnik drzwi prawy (strona lodówki)", + "fridge_hint": "Gdy czujnik drzwi zgłasza otwarcie, drzwi otwierają się w 3D.", + "furn_stove": "Kuchenka", + "furn_sink": "Zlew", + "furn_bathtub": "Wanna", + "furn_shower": "Prysznic", + "furn_wc": "WC", + "furn_washbasin": "Umywalka", + "furn_desk": "Biurko", + "furn_tv_board": "Szafka RTV", + "furn_plant": "Roślina", + "furn_rug": "Dywan", + "furn_stairs": "Schody", + "furn_stairwell": "Otwór w stropie", + "stairwell_hint": "Otwór w tym piętrze, np. nad schodami lub dla antresoli; z góry widać przez niego. Otwór musi leżeć w jednym pomieszczeniu; kilka otworów może się nakładać (np. dla kształtu L). Schody z piętra niżej sięgające tutaj też same otwierają strop.", + "tool_hole": "Otwór w stropie", + "tool_roof": "Dach", + "tool_energy": "Energia", + "tool_wall": "Ściana", + "hint_wall": "Przeciągnij, by narysować pojedynczą ścianę (działową, półścianę) · Shift utrzymuje ją prosto · Alt bez przyciągania", + "free_wall": "Ściana", + "wall_length": "Długość (m)", + "wall_thickness": "Grubość ściany (m)", + "wall_height": "Wysokość (m)", + "wall_height_full": "Pełna wysokość pomieszczenia", + "wall_slope": "Skośna", + "wall_slope_start": "Wysokość na początku (m)", + "wall_slope_end": "Wysokość na końcu (m)", + "wall_slope_hint": "Ściana skośna: góra biegnie prosto od wysokości na początku ściany (narożnik o niższym numerze) do wysokości na jej końcu. Obie mogą być wyższe niż piętro, np. dla przybudówki z wysokimi oknami.", + "wall_slope_off": "Wróć do prostej ściany", + "wall_none": "Bez ściany", + "wall_none_hint": "Pomiń tę ścianę całkowicie: dla otwartych planów, których pomieszczenia są jedną przestrzenią, ale w Home Assistant są oddzielne.", + "edge_thickness": "Grubość (m)", + "wall_thickness_hint": "Grubość tej ściany, np. 0,365 dla grubej ściany zewnętrznej lub 0,115 dla lekkiej ścianki działowej. Ściana między dwoma pomieszczeniami przyjmuje grubsze ustawienie.", + "wall_thickness_reset": "Grubość jak ustawiona dla domu", + "wall_heights": "Wysokości ścian", + "wall_n": "Ściana {a}–{b}", + "wall_view": "Widok ściany", + "wall_view_hint": "Ściana od frontu: przeciągaj drzwi, okna i meble lub wpisz ich odległość.", + "wall_view_prev": "Poprzednia ściana", + "wall_view_next": "Następna ściana", + "wall_view_left": "Od lewej (m)", + "wall_view_height": "Nad podłogą (m)", + "wall_part": "część {n}", + "wall_split_hint": "Podziel tu ścianę: część dostaje własną wysokość, np. 2,5 m obok 1,7 m w jednej linii", + "wall_split_at": "Punkt podziału od narożnika (m)", + "wall_join_hint": "Usuń punkt podziału: część znów łączy się z poprzednią", + "wall_exterior_short": "ściana zewnętrzna", + "room_wall_hint": "Niższa wysokość zamienia ścianę w balustradę lub ladę. Gdy dwa pomieszczenia dzielą ścianę, obowiązuje niższe ustawienie. Okna i drzwi w niej kończą się na wysokości ściany.", + "free_wall_hint": "Wolnostojąca ściana, np. działowa. Tam, gdzie styka się ze ścianą pomieszczenia, narożnik jest ścięty pod kątem. Przeciągaj uchwyty, by przesunąć końce, linię – by przesunąć całą ścianę.", + "free_wall_slope": "◢ Skośna", + "free_wall_slope_hint": "Ściana rośnie lub maleje od jednego końca do drugiego: wysokość wyżej dotyczy początku, ta tutaj końca.", + "free_wall_height_end": "Wysokość na końcu (m)", + "stairwell_outside": "Ten otwór przecina granicę pomieszczenia i dlatego nie jest wycinany. Przesuń go całkowicie do jednego pomieszczenia lub zmniejsz.", + "hint_hole": "Przeciągnij, by narysować otwór w stropie (klatka schodowa, antresola)", + "hint_roof": "Przeciągnij, by narysować połać dachu · dotknięcie zaznacza · przeciąganie przesuwa · narożniki zmieniają rozmiar", + "hint_energy": "Dotknij pola solarnego, by je zaznaczyć · przeciągnij, by przesunąć, także na inną połać · nowe pola przez + Pole solarne po prawej", + "furn_parking": "Miejsce parkingowe", + "furn_group_vehicles": "Parkowanie", + "parking_entity": "Czujnik \"samochód obecny\"", + "parking_vehicle": "Pojazd", + "parking_vehicle_none": "Brak", + "parking_no_pack": "Nie zaimportowano pakietu pojazdów – pojazdy pochodzą z pakietu \"Pojazdy\" (Rozszerzenia → Pakiety mebli).", + "parking_scale": "Rozmiar (%)", + "parking_type_entity": "Czujnik typu pojazdu (opcjonalnie)", + "parking_types": "Stan → pojazd", + "parking_type_state": "Stan (np. van)", + "parking_add_type": "+ Przypisanie", + "parking_hint": "Bez czujnika pojazd stoi tam zawsze. Z czujnikiem pojawia się, gdy ten zgłasza \"on\", \"home\" lub \"present\". Czujnik typu pojazdu (np. z analizy AI kamery) wybiera model: gdy jego stan pasuje do przypisania – także jako słowo w tekście – pokazywany jest ten pojazd, inaczej domyślny.", + "parking_too_tall": "Pojazd ({car} m) jest wyższy niż pomieszczenie ({room} m).", + "furn_lamp_ceiling": "Lampa sufitowa", + "furn_lamp_downlight": "Oczko wpuszczane", + "furn_lamp_spot": "Oczko natynkowe", + "furn_lamp_panel": "Panel LED", + "furn_lamp_uplight": "Reflektor podłogowy", + "furn_lamp_bollard": "Słupek oświetleniowy", + "furn_lamp_garden": "Reflektor ogrodowy", + "furn_radiator": "Grzejnik", + "furn_robot_vacuum": "Robot sprzątający", + "furn_entity_vacuum": "Robot sprzątający", + "furn_entity_mower": "Robot koszący", + "pet_room_sensor": "Czujnik pomieszczenia zwierzęcia (opcjonalnie)", + "pet_room_hint": "Czujnik podający pomieszczenie, w którym jest zwierzę – Bermuda lub ESPresense z brelokiem na obroży: w 3D chodzi wtedy po tym pomieszczeniu.", + "furn_entity_water": "Zawór lub przełącznik", + "fridge_temp": "Temperatura chłodziarki", + "freezer_temp": "Temperatura zamrażarki", + "fridge_temp_hint": "Znacznik pokazuje temperatury. Powyżej 8 °C w chłodziarce lub −12 °C w zamrażarce świeci jako ostrzeżenie.", + "spray_reach": "Zasięg wody (m)", + "spray_hint": "Dopóki zawór jest otwarty lub przełącznik włączony, zraszacz rozpryskuje wodę łukami wokół siebie.", + "furn_robot_room": "Bieżące pomieszczenie (czujnik)", + "robot_hint": "Gdy robot sprząta w Home Assistant, jeździ w 3D pasami po pomieszczeniu, które zgłasza (czujnik „bieżące pomieszczenie”, porównywany z nazwą pomieszczenia lub obszaru), inaczej po pomieszczeniu swojej stacji. Trasa jest symulowana – Home Assistant zwykle nie zna dokładnej pozycji. Wraca do stacji, gdy kończy.", + "furn_lamp_pendant": "Lampa wisząca", + "furn_ceiling_fan": "Wentylator sufitowy", + "furn_fan_entity": "Wentylator", + "fan_hint": "Światło to zestaw oświetleniowy wentylatora (zostaw puste, jeśli go nie ma). Wentylator jest wyszukiwany w pomieszczeniu lub wybierany tutaj: w 3D łopaty obracają się tak szybko, jak pracuje, jego ikona go przełącza, przesunięcie w górę/dół zmienia prędkość, długie przytrzymanie otwiera szybkie menu. Wysokość to, jak nisko wisi pod sufitem (więcej = dłuższy pręt).", + "room_ceiling": "Wysokość sufitu", + "room_ceiling_tip": "Niżej niż piętro (łazienka pod schodami) albo wyżej (salon otwarty aż pod dach): lampy sufitowe, wentylatory, taśmy LED i urządzenia sufitowe wiszą wtedy tutaj, a ściany pomieszczenia mają tę wysokość.", + "room_ceiling_through": "Sufit ({ceiling} m) jest wyżej niż wysokość piętra ({floor} m): pomieszczenie sięga w piętro powyżej, jego ściany rosną razem z nim, a piętro powyżej pozostaje nad nim otwarte. Edytor wyższego piętra pokazuje ten obszar zakreskowany.", + "room_floor_offset": "Poziom podłogi (m)", + "room_floor_offset_hint": "Jeśli podłoga tego pomieszczenia leży niżej lub wyżej niż piętro (obniżone wejście: −0,39), podłoga, ściany, drzwi, okna i to, co w nim stoi, przesuwają się; sufit zostaje. Stopnie dodaj jako schody.", + "room_inner": "Wewnątrz {w} × {d}", + "room_inner_hint": "Mierzone od ściany do ściany: ściany wewnętrzne zabierają połowę grubości, zewnętrzne stoją poza obrysem.", + "floor_heating": "Ogrzewanie podłogowe (opcjonalnie)", + "floor_heating_hint": "Dopóki termostat grzeje (lub zawór jest otwarty, przełącznik włączony), podłoga pomieszczenia świeci ciepło w 3D.", + "room_announce_speaker": "Głośnik komunikatów", + "room_announce_quiet": "Czas ciszy dla komunikatów", + "room_announce_hint": "Bez wyboru mówi głośnik ustawiony w pomieszczeniu, w przeciwnym razie asystent głosowy, Echo lub głośnik obszaru (nigdy telewizor). W czasie ciszy komunikaty do wielu pomieszczeń je pomijają; komunikat tylko dla niego i tak dotrze.", + "ceiling_here": "Sufit tutaj", + "ceiling_here_hint": "Wysokość sufitu dokładnie w tym miejscu, np. przy skosie. Puste = sufit pomieszczenia.", + "ceiling_slope": "Pod skos dachu", + "ceiling_slope_hint": "Sufit leży tu pod skosem dachu: lampa wisi na jego spodzie, dokładnie nad swoim miejscem.", + "furn_lamp_floor": "Lampa podłogowa", + "furn_lamp_table": "Lampa stołowa", + "furn_lamp_wall": "Kinkiet", + "furn_led_strip": "Taśma LED", + "furn_group_lights": "Światła", + "furn_entity_light": "Światło lub przełącznik", + "furn_color_entity": "Kolor i jasność z (opcjonalnie)", + "furn_color_entity_hint": "Dla świateł, które przekaźnik (Shelly, aktor) włącza i wyłącza, podczas gdy żarówka sama zna kolor i jasność: wł./wył. pochodzi z przełącznika powyżej, kolor i jasność z tej encji.", + "lamp_extra_light": "Źródło światła {n} (opcjonalnie)", + "lamp_extra_hint": "Oprawa z kilkoma światłami – główne, nocne, pierścień nastrojowy: gdy główne jest wyłączone, świeci w 3D następnym włączonym, nieco słabiej. Przełączaj światła osobno w panelu pomieszczenia.", + "furn_entity_climate": "Ogrzewanie (termostat)", + "lamp_hint": "Dotknij lampy w 3D, by ją przełączyć, przytrzymaj dla szybkiego menu. Działają też przełączniki (np. przekaźnik lampy sufitowej) – lampa świeci, gdy jest włączony. Lampy stołowe stoją na meblu pod nimi.", + "lamp_hint_pendant": "Wysokość = zwis pod sufitem. Dotknij w 3D, by przełączyć, przytrzymaj dla szczegółów.", + "theme": "Wygląd", + "version_hint": "Zainstalowana wersja NextFloor – frontend; integracja w Home Assistant zgłasza {backend}", + "accent": "Kolor akcentu", + "accent_hint": "Własny kolor akcentu: linie i świecące krawędzie w wyglądzie neon, przyciski i znaczniki – ↺ przywraca neonowy cyjan", + "accent_reset": "Wróć do cyjanu", + "theme_neon": "Neon", + "theme_blueprint": "Plan techniczny", + "theme_day": "Dzień", + "theme_auto": "Auto", + "clock": "Zegar", + "clock_none": "Brak", + "clock_top_left": "Lewy górny", + "clock_top_right": "Prawy górny", + "clock_bottom_left": "Lewy dolny", + "clock_bottom_right": "Prawy dolny", + "glass_walls": "Szklane ściany", + "glass_walls_hint": "Jak bardzo kryjące są ściany, przez które widać pomieszczenia: w lewo prawie niewidoczne, w prawo nieprzezroczyste. Dla tego ekranu.", + "screen_name": "Nazwa tego ekranu", + "screen_name_hint": "Komunikaty pojawiają się na każdym otwartym ekranie NextFloor. Z nazwą (np. „Korytarz”) komunikat może trafić tylko na ten ekran. Bez zaznaczenia ten ekran milczy.", + "announce_on": "Komunikaty na tym ekranie włączone", + "announce_muted": "Komunikaty na tym ekranie wyciszone", + "lock3d_on": "Zablokuj 3D (bez obracania, przybliżania i przesuwania; dotknięcia nadal działają)", + "lock3d_off": "Odblokuj 3D", + "walk": "Przejdź się po domu", + "travel": "Podróż w czasie: odtwórz ostatnie 24 godziny lub 7 dni", + "travel_play": "Odtwórz", + "travel_pause": "Pauza", + "travel_loading": "Wczytywanie historii …", + "travel_failed": "Nie udało się wczytać historii.", + "travel_speed": "Prędkość", + "travel_speed_min": "1 min/s", + "travel_speed_10min": "10 min/s", + "travel_speed_hour": "1 h/s", + "travel_days": "dni", + "travel_live": "Na żywo", + "card_travel_button": "Przycisk podróży w czasie", + "walk_stop": "Zakończ spacer", + "walk_hint": "Przeciągnij: rozglądaj się · W A S D / strzałki lub drążek: idź · kółko: krok", + "card_walk_button": "Przycisk spaceru", + "card_lock_button": "Przycisk blokady 3D", + "backdrop": "Własne tło", + "backdrop_color": "Kolor", + "backdrop_image": "Obraz (/local/… lub https://…)", + "backdrop_dim": "Przyciemnij", + "backdrop_hint": "Zamiast nieba wyglądu dom stoi przed własnym kolorem lub obrazem. Obraz w /config/www jest dostępny pod /local/….", + "furnish": "Umebluj", + "split_3d": "3D obok", + "plan_dims": "Wymiary", + "plan_dims_hint": "Opisuje każdą krawędź pomieszczenia jej długością.", + "mount_height": "Wysokość nad podłogą (m)", + "side_open": "Otwórz pasek boczny", + "side_close": "Zamknij", + "side_details": "Szczegóły zaznaczenia", + "side_pin": "Przypnij", + "side_pinned": "Przypięty", + "side_pin_hint": "Przypięty pasek boczny zostaje otwarty; inaczej zwija się obok widoku 3D, gdy nic nie jest zaznaczone", + "split_3d_hint": "3D na żywo obok planu: przeciągaj i obracaj tam meble i urządzenia – z cofaniem, zapisywane z planem", + "size_w": "Szerokość (m)", + "size_d": "Głębokość (m)", + "size_h": "Wysokość (m)", + "furnish_hint": "Przeciągaj meble, lampy i urządzenia · meble przyciągają się do ścian · dotknij elementu, by go obrócić, ustawić wysokość i montaż", + "done": "Gotowe", + "heatmap": "Mapa ciepła", + "heat_off": "Normalnie", + "heat_short_temperature": "Temp.", + "heat_short_humidity": "Wilgotność", + "heat_short_co2": "CO₂", + "heat_short_mould": "Pleśń", + "heat_short_power": "Moc", + "heat_short_comfort": "Komfort", + "heat_short_sun": "Słońce", + "heat_short_wifi": "Wi-Fi", + "heat_short_values": "Wartości", + "heat_temperature": "Temperatura", + "heat_humidity": "Wilgotność", + "heat_co2": "CO₂", + "heat_mould": "Pleśń", + "heat_power": "Pobór mocy", + "heat_comfort": "Wskaźnik komfortu", + "heat_sun": "Słońce dziś", + "room_sun_hours": "{h} h słońca dziś ({facing})", + "open_since": "otwarte od {time}", + "presence_now": "ktoś jest", + "presence_last": "ostatnio {time} temu", + "comfort_n": "Komfort {n}", + "empty_lights_hint": "{n} świateł włączonych, nikogo od {min} min.", + "empty_lights_off": "Wyłącz światło", + "open_heating_hint": "{n} okien otwartych przy włączonym ogrzewaniu.", + "open_heating_off": "Wyłącz ogrzewanie", + "room_clean": "Sprzątanie (skrypt lub przycisk)", + "room_clean_hint": "Skrypt lub przycisk, który wysyła robota sprzątającego do tego pomieszczenia (np. sprzątanie pokoju z Twojej integracji). Panel pomieszczenia pokaże wtedy „🧹 Odkurz”.", + "room_clean_run": "Odkurz", + "room_clean_run_hint": "Wysyła robota sprzątającego do tego pomieszczenia.", + "shade_hint": "Słońce na {n} oknach przy {temp} – opuścić rolety?", + "shade_close": "Opuść", + "room_sun_year": "Słońce w ciągu roku", + "room_sun_year_hint": "Godziny słońca przez zewnętrzne okna pomieszczenia 15. dnia każdego miesiąca.", + "room_energy": "dziś {today} · miesiąc {month}", + "room_energy_hint": "Ze statystyk czujników mocy urządzeń w pomieszczeniu; koszt miesiąca według taryfy domu.", + "heat_summer": "lato", + "heat_winter": "zima", + "air_co2": "przewietrz (CO₂)", + "air_humidity": "przewietrz (wilgoć)", + "air_mould": "ryzyko pleśni – przewietrz", + "room_curve_hint": "Temperatura pomieszczenia w ostatnich 24 godzinach", + "heat_values": "Wartości przy nazwach pomieszczeń", + "heat_wifi": "Wi-Fi", + "wifi_aps": "{n} punktów dostępu · {clients} urządzeń", + "wifi_network": "Sieć: {online} online · {offline} offline", + "wifi_none": "Ustaw punkty dostępu lub routery z pakietów (Inteligentny dom 2) i połącz je z encją ich urządzenia.", + "wifi_clients": "{n} urządzeń", + "heat_none_found": "Brak pasujących czujników w obszarach pomieszczeń.", + "markers": "Znaczniki", + "markers_none": "Brak", + "markers_important": "Ważne", + "markers_all": "Wszystkie", + "furn_stool": "Taboret", + "furn_coffee_table": "Stolik kawowy", + "furn_tv_wall": "TV (ścienny)", + "furn_sideboard": "Kredens", + "furn_table_round": "Stół okrągły", + "furn_bench": "Ławka", + "furn_corner_bench": "Ławka narożna", + "furn_bar_stool": "Hoker", + "furn_kitchen_wall": "Szafka wisząca", + "furn_kitchen_tall": "Słupek z piekarnikiem", + "furn_island": "Wyspa kuchenna", + "furn_dishwasher": "Zmywarka", + "furn_bunk_bed": "Łóżko piętrowe", + "furn_dresser": "Komoda", + "furn_washer": "Pralka", + "furn_dryer": "Suszarka", + "furn_office_chair": "Krzesło biurowe", + "furn_tall_cabinet": "Wysoka szafa", + "furn_coat_rack": "Wieszak", + "furn_group_living": "Mieszkanie", + "furn_group_dining": "Jadalnia", + "furn_group_energy": "Energia i fotowoltaika", + "energy_devices": "Urządzenia", + "wallbox_charging": "ładowanie", + "wallbox_plugged": "podłączony", + "furn_soc": "Stan naładowania (%)", + "furn_export": "Moc oddawana (W, osobny czujnik, opcjonalnie)", + "furn_export_hint": "Jeśli licznik zgłasza pobór i oddawanie w dwóch czujnikach (np. Growatt, Tibber Pulse), użyj czujnika poboru jako mocy powyżej, a czujnika oddawania tutaj. Czujnik ze znakiem tego nie potrzebuje.", + "meter_parent": "Podłączony do licznika", + "meter_parent_none": "brak (licznik główny)", + "meter_main": "Licznik główny", + "meter_unmetered": "{w} niezmierzone", + "meter_device_hint": "Jeśli urządzenie jest za podlicznikiem (np. elektrownia balkonowa w mieszkaniu), jego moc liczy się do tego mieszkania. Podlicznik musi mierzyć w obu kierunkach (− = oddawanie); jeśli liczy tylko pobór, zużycie mieszkania przy nadwyżce wychodzi za wysokie.", + "meter_sub_power": "Moc obwodu (W, + = pobór, − = oddawanie)", + "meter_floors": "Zasila piętra", + "meter_sub_hint": "Podlicznik mierzy swój obwód, np. mieszkanie. Urządzenia na zaznaczonych piętrach są w 3D podpięte pod niego zamiast pod licznik główny; to, co licznik główny liczy ponad to, pojawia się w bilansie jako „Wspólne (reszta)”.", + "furn_charge": "Moc ładowania (W, osobny czujnik, opcjonalnie)", + "furn_charge_hint": "Jeśli magazyn zgłasza ładowanie i rozładowanie w dwóch czujnikach (np. Anker Solix), użyj czujnika rozładowania jako mocy powyżej, a czujnika ładowania tutaj. Czujnik ze znakiem tego nie potrzebuje.", + "furn_wallbox_status": "Stan (ładowanie, podłączony)", + "energy_only_note": "⚡ Energia: tu można przesuwać tylko pola solarne i urządzenia energetyczne; pomieszczenia i meble są zablokowane.", + "roof_only_note": "🏠 Dach: tu można przesuwać tylko połacie i okna dachowe; pomieszczenia i meble są zablokowane.", + "energy_devices_hint": "Licznik, falowniki, magazyny energii, wallboxy i przyłącze sieci dodaje się tutaj: na piętrze wybranym powyżej, przesuwalne w planie. Z czujnikiem mocy pokazują swoje waty; licznik bierze czujnik sieci, string wybiera swój falownik. Działa też kilka falowników i magazynów (np. dodatkowa elektrownia balkonowa): każdy z własnym czujnikiem.", + "energy_routes": "Trasy kabli", + "energy_routes_hint": "Gdzie naprawdę biegnie kabel: przepływ podąża wtedy za twoimi punktami zamiast łukiem przez dom. Bez trasy zostaje łuk. Odbiorniki zachowują swój łuk.", + "route_conn_solar": "{name} → falownik", + "route_conn_battery": "Bateria ↔ dom", + "route_conn_inverter": "Falownik → dom", + "route_conn_grid": "Sieć ↔ dom", + "route_conn_meter": "{name} ↔ licznik nadrzędny", + "route_conn_device": "{name} ↔ podlicznik", + "route_points": "{n} punktów", + "route_none": "łuk bezpośredni", + "route_draw": "Rysuj trasę", + "route_redraw": "Narysuj ponownie", + "route_drawing": "Stuknij na planie punkty, przez które biegnie kabel, od jednego końca do drugiego; w międzyczasie zmień piętro tam, gdzie przechodzi przez strop. {n} punktów.", + "route_undo": "Ostatni punkt", + "route_done": "Gotowe", + "route_cable": "Pokaż jako kabel", + "route_cable_hint": "Rysuje trasę jako widoczny kabel, a nie tylko cienką linię pod cząsteczkami.", + "solar_fields": "Pola solarne", + "solar_hint": "Połóż moduły na dachu: leżą w spadku połaci; na dachu płaskim stoją na stelażach. Przeciągnij pole w planie, by je przesunąć.", + "solar_no_roof": "Pola solarne potrzebują dachu: dwuspadowego lub płaskiego w Ustawieniach albo połaci dachu tutaj w narzędziu Dach.", + "solar_face_gone": "brak połaci", + "solar_summary": "{n} modułów · {kwp} kWp", + "solar_add": "Pole solarne", + "solar_field": "Pole solarne", + "solar_face": "Połać dachu", + "solar_rows": "Rzędy", + "solar_cols": "Moduły w rzędzie", + "solar_portrait": "Pionowo", + "solar_landscape": "Poziomo", + "solar_u": "Odstęp od krawędzi (m)", + "solar_v": "Odstęp od okapu (m)", + "solar_tilt": "Nachylenie stelaży (°)", + "solar_rack_ew": "Konstrukcja wschód-zachód", + "solar_rack_ew_hint": "Co drugi rząd jest skierowany w drugą stronę, pary stoją plecami do siebie – nisko i gęsto, jak na wielu płaskich dachach.", + "solar_rack_tilt": "Konstrukcja (° dodatkowego nachylenia)", + "solar_flip": "Pochyl w drugą stronę", + "solar_partial": "na połaci mieści się tylko {n} z {total}", + "solar_form_hint": "Moduły wystające poza połać są pomijane. „Wypełnij połać” kładzie tyle modułów, ile się zmieści. kWp liczone przy 400 W na moduł.", + "solar_fit": "Wypełnij połać", + "roof_windows": "Okna dachowe", + "roof_window": "Okno dachowe", + "roof_windows_hint": "Okna dachowe leżą w połaci, z roletą i kontaktami jak okna. Przeciągaj je w planie, także na inną połać.", + "roof_window_tilt": "Kontakt uchyłu", + "roof_window_name": "Nazwa (opcjonalnie)", + "roof_window_motor": "Silnik okna (osłona, opcjonalnie)", + "roof_window_motor_hint": "Silnik okna (Velux, Roto, Fakro) zgłasza pozycję jako osłonę: skrzydło otwiera się w 3D tak, jak stoi silnik. Kontakt lub kontakt uchyłu działa też bez silnika.", + "roof_window_hint": "Otwarte skrzydło odchyla się na zewnątrz na zawiasie u góry; uchylone – trochę; rama świeci ciepło; roleta zjeżdża na szybę od góry. W połaci dachu okno wycina otwór w spadku, by poddasze przez nie wyglądało.", + "solar_ground": "Wolnostojące (ogród, dach garażu …)", + "solar_add_ground": "Wolnostojące", + "solar_base": "Wysokość powierzchni (m, 0 = grunt)", + "solar_add_wall": "Na ścianie", + "solar_wall": "Ściana", + "solar_v_wall": "Wysokość nad podłogą (m)", + "solar_tilt_wall": "Odchylenie od ściany (°, 90 = daszek)", + "solar_flip_wall": "Odstające u dołu zamiast u góry", + "solar_rotation": "Obrót (°)", + "solar_name": "Nazwa", + "solar_name_hint": "np. string 1 południe", + "solar_module_w": "Szerokość modułu (m)", + "solar_module_h": "Wysokość modułu (m)", + "solar_wp": "Moc modułu (Wp)", + "solar_string": "String", + "solar_strings": "Stringi", + "solar_string_none": "Bez stringu", + "solar_string_new": "Nowy string", + "solar_string_n": "String {n}", + "solar_string_name": "Nazwa stringu", + "solar_string_entity": "Moc PV stringu", + "solar_string_inverter": "Falownik", + "solar_string_inverter_none": "Nie wybrano falownika", + "inverter_strings": "Stringi na tym falowniku: {names}", + "inverter_strings_none": "Brak stringu na tym falowniku – przypisz go w polu solarnym w String › Falownik.", + "solar_string_inverter_missing": "Brak falownika w planie (dodaj go poniżej w Urządzeniach)", + "solar_string_hint": "Pola w tym samym stringu należą do siebie, także na różnych dachach (np. 5 modułów na domu i 5 na garażu). Czujnik i falownik liczą się dla całego stringu.", + "solar_string_sum": "{fields} pól · {n} modułów · {kwp} kWp", + "solar_face_size": "Połać {w} × {h} m (wzdłuż okapu × w górę spadku)", + "solar_cols_hint": "Jedna liczba dla rzędów równej długości lub lista dla własnych rzędów: „4, 4, 3” (od okapu).", + "solar_align_left": "Lewo", + "solar_align_center": "Środek", + "solar_align_right": "Prawo", + "solar_look_black": "Full black", + "solar_look_blue": "Niebieski", + "solar_pick": "Moduły wł./wył. pojedynczo", + "solar_pick_all": "Wszystkie znów wł.", + "solar_pick_hint": "Dotknij modułu w planie, by go usunąć lub przywrócić. Usunięte są przerywane.", + "solar_entity": "Moc PV tego pola (np. jego stringu)", + "solar_main": "Dach główny", + "solar_section": "Połać {n}", + "solar_flat": "dach płaski", + "compass_n": "północ", + "compass_ne": "północny wschód", + "compass_e": "wschód", + "compass_se": "południowy wschód", + "compass_s": "południe", + "compass_sw": "południowy zachód", + "compass_w": "zachód", + "compass_nw": "północny zachód", + "furn_meter": "Licznik energii", + "furn_grid_point": "Przyłącze sieci", + "grid_point_hint": "Tu stoi przyłącze sieci: punkt przekazania do dostawcy, np. na końcu podjazdu. Przesuwalne w planie.", + "furn_model": "Model", + "inverter_std": "Standard (jednostka ścienna z wyświetlaczem)", + "inverter_slim": "Wąski i wysoki (pas światła)", + "inverter_hybrid": "Hybrydowy (okrągła tarcza, wentylatory)", + "battery_std": "Wieża (moduły w stosie)", + "battery_wall": "Magazyn ścienny (płaski, wiszący)", + "battery_cube": "Kompaktowy (magazyn balkonowy)", + "furn_inverter": "Falownik fotowoltaiczny", + "furn_home_battery": "Magazyn energii", + "furn_wallbox": "Wallbox", + "furn_group_kitchen": "Kuchnia", + "furn_group_sleeping": "Spanie", + "furn_group_bath": "Łazienka i pranie", + "furn_group_work": "Praca i inne", + "furn_entity": "Urządzenie (przełącznik, gniazdo …)", + "furn_state_entity": "Stan z (opcjonalnie)", + "furn_state_entity2": "Drugi stan (druga połowa)", + "furn_state_split": "Połowy", + "furn_state_left_right": "Lewo / prawo", + "furn_state_top_bottom": "Dół / góra (łóżko piętrowe)", + "furn_state_hint": "Element świeci, gdy encja zgłasza wł., zajęte lub w domu – łóżko z matą obecności, fotel, sauna. Dwie encje podświetlają połowy: lewą i prawą, dolną i górną w łóżku piętrowym.", + "furn_entity_tv": "TV (odtwarzacz lub inteligentne gniazdo)", + "fix": "Zablokuj", + "unfix": "Odblokuj", + "fix_hint": "Zablokowany: nie da się go już przypadkiem przesunąć (klawisz L, prawy klik lub długie przytrzymanie)", + "fixed_drag_hint": "🔒 Zablokowany – najpierw odblokuj, by przesunąć (kłódka w formularzu, prawy klik lub klawisz L)", + "fixed_delete_confirm": "Ten element jest zablokowany. Mimo to usunąć?", + "lock_plan": "🔒 Plan", + "lock_plan_hint": "Zablokuj plan: pomieszczeń, ścian, drzwi, okien i terenów zewnętrznych nie da się przypadkiem przesunąć. Meble i urządzenia pozostają wolne.", + "start_view": "Widok startowy", + "start_view_hint": "Widok 3D, karta i kiosk otwierają dom w tym widoku, np. od strony ogrodu. Obracaj, przybliżaj i przesuwaj dom w panelu 3D po prawej, aż będzie pasował, potem zapamiętaj.", + "start_view_card": "Jeśli karta ma się otwierać w innym widoku, wstaw tę linię do jej konfiguracji YAML.", + "start_view_set": "Zapamiętaj bieżący widok 3D jako startowy", + "start_view_reset": "Domyślny", + "start_view_saved": "Zapisano własny widok startowy.", + "ctx_rotate": "Obróć o 90°", + "devices_placed_in": "w {room}", + "devices_narrow": "jeszcze {n} – zawęź wyszukiwanie", + "climate": "Klimat pomieszczenia", + "climate_temperature": "Temperatura", + "climate_humidity": "Wilgotność", + "climate_co2": "CO₂", + "climate_hint": "Te czujniki liczą się dla mapy ciepła i panelu pomieszczenia. „Automatycznie” bierze czujniki obszaru i umieszczone w pomieszczeniu, ale nie temperatury urządzeń (drukarka 3D, pompa ciepła, zasilanie …).", + "climate_more": "… i kolejny czujnik (średnia)", + "plan_locked": "Plan zablokowany", + "plan_lock": "Zablokuj plan", + "plan_unlock": "Odblokuj plan", + "opening_mark": "Wyróżnij w 3D", + "opening_mark_open": "Gdy otwarte", + "opening_mark_closed": "Gdy zamknięte (np. WC)", + "opening_mark_hint": "Wyróżnione okno lub drzwi świecą ciepło. „Gdy zamknięte” wymaga kontaktu; bez czujnika nic nie jest wyróżniane.", + "window_opens": "Otwiera się", + "window_opens_turn": "Rozwierno-uchylne (do środka)", + "window_opens_slide": "Przesuwne (okno przesuwne, drzwi podnośno-przesuwne)", + "window_opens_top": "Uchylne na zewnątrz (dół wychyla się na zewnątrz)", + "window_opens_hint": "Przesuwne: skrzydło po stronie zawiasu przesuwa się przed stałe; przy dwóch skrzydłach dwa środkowe przesuwają się na boki. Okna uchylne otwierają się z czujnikiem kontaktu lub uchyłu.", + "marker_show": "Znacznik w 3D", + "marker_show_hint": "Automatycznie podąża za przełącznikiem Brak / Ważne / Wszystkie widoku 3D. Zawsze pokazuj i Ukryj obowiązują niezależnie (oprócz Brak).", + "pin_shift": "Przesuń znacznik", + "pin_shift_up": "↑ wysokość", + "pin_shift_hint": "Gdy urządzenia stoją blisko siebie, przesuń tu znacznik trochę w bok lub w górę (w metrach); samo urządzenie zostaje na miejscu.", + "marker_show_auto": "Automatycznie", + "marker_show_always": "Zawsze pokazuj", + "marker_show_no_power": "Bez watów", + "marker_show_active": "Tylko gdy aktywny", + "marker_show_never": "Ukryj", + "marker_icon": "Własny symbol (ikona Material Design)", + "device_name": "Własna nazwa (opcjonalnie)", + "show_name": "Pokaż nazwę pod znacznikiem w 3D", + "card_marker_names": "Własne nazwy przy znacznikach", + "card_marker_names_hint": "Każde urządzenie z własną nazwą pokazuje ją małą pod znacznikiem – trzy termometry w ogrodzie da się rozróżnić.", + "device_name_hint": "Nazwa tylko dla planu i panelu pomieszczenia, np. \"Światło akcentowe wyspy\" – encja w Home Assistant pozostaje bez zmian.", + "device_simple": "Tylko włącznik w panelu pomieszczenia", + "device_simple_hint": "Panel pomieszczenia pokazuje dla tej lampy tylko włącznik, bez jasności, temperatury barwy i kolorów.", + "floor_turn": "Obróć o 90°", + "floor_shift_all": "Zabierz wszystkie piętra (cały dom)", + "floor_shift_all_hint": "Przesunięcie i obrót działają na wszystkie piętra z połaciami dachu, terenami zewnętrznymi, urządzeniami energetycznymi i licznikiem – cały dom porusza się jako całość.", + "floor_turn_hint": "Obraca wszystko na piętrze o 90° zgodnie z ruchem wskazówek wokół środka pomieszczeń – gdy piętro narysowano odwrotnie. Trzy razy = 270°.", + "marker_icon_hint": "Nazwa ikony Material Design jak w Home Assistant, np. mdi:thermometer lub mdi:water-alert. Puste = symbol rodzaju urządzenia.", + "furn_power": "Czujnik mocy (W)", + "furn_links_hint": "Z czujnikiem mocy element pokazuje swoje waty i bierze udział w przepływie energii.", + "furn_links_hint_tv": "Ekran świeci, gdy TV jest włączony, w kolorze aplikacji (Netflix, YouTube …); etykieta pokazuje aplikację lub tytuł.", + "stairs_hint": "Schody wznoszą się do tyłu (od zaznaczonej przedniej krawędzi) i otwierają strop piętra powyżej.", + "floor_lights": "{n} świateł wł.", + "floor_open": "{n} otwartych", + "floor_persons": "{n} osób", + "energy_consumption": "Zużycie", + "energy_grid_import": "Pobór z sieci", + "energy_grid_export": "Oddawanie", + "energy_solar": "Słońce", + "energy_battery": "Magazyn", + "energy_tariff": "Taryfa", + "energy": "Energia", + "energy_meter": "Licznik", + "energy_grid": "Sieć (W, + = pobór)", + "energy_solar_sensor": "Produkcja PV (W)", + "energy_battery_sensor": "Moc magazynu (W, + = rozładowanie)", + "energy_battery_soc": "Naładowanie magazynu (%)", + "energy_tariff_sensor": "Taryfa (np. zł/kWh)", + "energy_gas": "Licznik gazu (opcjonalnie)", + "energy_water": "Wodomierz (opcjonalnie)", + "energy_meters_hint": "Gaz i woda pojawiają się przy bilansie domu – na pasku energii i na karcie domu: czujnik z bieżącym przepływem (m³/h, l/min) lub dzisiejszym odczytem.", + "energy_gas_short": "Gaz", + "energy_water_short": "Woda", + "energy_invert": "Odwróć znak", + "energy_hint": "Odbiorniki to umieszczone urządzenia z czujnikiem mocy (W) – sam czujnik lub jeden z tego samego urządzenia.", + "energy_balance": "Bilans energii", + "energy_balance_hint": "Sieć, słońce i magazyn pochodzą z urządzeń w planie: licznika, falownika i magazynu energii. Tutaj możesz wybrać inne czujniki, odwrócić znaki i ustawić zużycie domu.", + "energy_rest": "Wspólne (reszta)", + "energy_advanced": "Zaawansowany tryb energii", + "energy_advanced_on": "Używaj podliczników", + "energy_show_unmetered": "Pokazuj niezmierzone zużycie przy podlicznikach", + "energy_show_unmetered_hint": "Etykieta podlicznika pokazuje wtedy, ile zużywają jego piętra i ile z tego nie mierzy żadne umieszczone urządzenie, np. „500 W · 450 W niezmierzone”. Inaczej pokazuje odczyt licznika.", + "energy_advanced_hint": "Dla podliczników, np. jednego na mieszkanie za licznikiem głównym: licznik może wtedy wisieć pod innym i zasilać własne piętra. Wył. = pierwszy licznik to przyłącze sieci, kolejne to odbiorniki.", + "energy_consumption_sensor": "Zużycie domu (W, inaczej z bilansu)", + "energy_import_prefs": "Przejmij z panelu energii", + "energy_import_done": "Przejęto {n} czujników – sprawdź znaki.", + "energy_import_none": "W panelu energii nie znaleziono pasujących czujników mocy (W) – wybierz je ręcznie.", + "energy_import_failed": "Panel energii Home Assistant nie jest skonfigurowany.", + "tool_meter": "Licznik", + "hint_meter": "Dotknij miejsca licznika", + "presence": "Obecność", + "presence_hint": "Czujnik pomieszczenia na osobę (np. ESPresense, Bermuda): jego stan nazywa pomieszczenie lub obszar.", + "presence_sensor": "Czujnik pomieszczenia", + "no_persons": "W Home Assistant nie ma osób.", + "packname:nextfloor.a_bad": "Łazienka", + "pack:nextfloor.a_bad:vanity_60": "Szafka z umywalką 60", + "pack:nextfloor.a_bad:vanity_80": "Szafka z umywalką 80", + "pack:nextfloor.a_bad:vanity_100": "Szafka z umywalką 100", + "pack:nextfloor.a_bad:vanity_double_120": "Podwójna umywalka 120", + "pack:nextfloor.a_bad:vanity_double_160": "Podwójna umywalka", + "pack:nextfloor.a_bad:pedestal_basin": "Umywalka na postumencie", + "pack:nextfloor.a_bad:bathtub_builtin": "Wanna zabudowana", + "pack:nextfloor.a_bad:bathtub_corner": "Wanna narożna", + "pack:nextfloor.a_bad:bathtub_corner_compact": "Kompaktowa wanna narożna", + "pack:nextfloor.a_bad:bathtub_free": "Wanna wolnostojąca", + "pack:nextfloor.a_bad:whirlpool_indoor": "Wanna z hydromasażem", + "pack:nextfloor.a_bad:shower_corner_90": "Kabina narożna 90 × 90", + "pack:nextfloor.a_bad:shower_niche_120": "Prysznic we wnęce 120 × 90", + "pack:nextfloor.a_bad:shower_walkin_140": "Prysznic walk-in 140 × 90", + "pack:nextfloor.a_bad:shower_walkin_120": "Prysznic walk-in", + "pack:nextfloor.a_bad:shower_rain_led": "Deszczownica z LED", + "pack:nextfloor.a_bad:toilet_close": "WC kompakt", + "pack:nextfloor.a_bad:toilet_hung": "WC podwieszane", + "pack:nextfloor.a_bad:toilet_hung_compact": "WC podwieszane (kompaktowe)", + "pack:nextfloor.a_bad:bidet": "Bidet", + "pack:nextfloor.a_bad:cabinet_tall": "Wysoki słupek łazienkowy", + "pack:nextfloor.a_bad:cabinet_mid": "Średni słupek łazienkowy", + "pack:nextfloor.a_bad:mirror_round_light": "Okrągłe lustro z oświetleniem", + "pack:nextfloor.a_bad:mirror_80": "Lustro 80 × 60 z oświetleniem", + "pack:nextfloor.a_bad:mirror_led_100": "Lustro LED 100 × 70 z zegarem", + "pack:nextfloor.a_bad:mirror_cabinet": "Szafka z lustrem i oświetleniem", + "pack:nextfloor.a_bad:wall_shelf_bath": "Półka ścienna łazienkowa", + "pack:nextfloor.a_bad:towel_rail": "Wieszak z ręcznikiem", + "pack:nextfloor.a_bad:towel_radiator": "Grzejnik łazienkowy", + "pack:nextfloor.a_bad:towel_heater_electric": "Elektryczny grzejnik na ręczniki", + "pack:nextfloor.a_bad:sauna": "Sauna", + "pack:nextfloor.a_bad:bath_fan": "Wentylator łazienkowy", + "pack:nextfloor.a_bad:washer_cabinet": "Szafka na pralkę", + "pack:nextfloor.a_bad:washer_under_vanity": "Pralka pod umywalką", + "pack:nextfloor.a_bad:laundry_basket": "Kosz na pranie", + "pack:nextfloor.a_bad:laundry_cabinet": "Szafka na pranie z koszem", + "pack:nextfloor.a_bad:ladder_shelf": "Półka drabinka z ręcznikami", + "pack:nextfloor.a_bad:plant_stool": "Roślina na stołku", + "packname:nextfloor.a_buero": "Biuro i gaming", + "pack:nextfloor.a_buero:desk_standing": "Biurko z regulacją wysokości", + "pack:nextfloor.a_buero:desk_standing_bare": "Biurko z regulacją bez monitora", + "pack:nextfloor.a_buero:chair_gaming": "Fotel gamingowy", + "pack:nextfloor.a_buero:chair_office": "Ergonomiczne krzesło biurowe", + "pack:nextfloor.a_buero:sim_cockpit": "Kokpit do sim racingu", + "pack:nextfloor.a_buero:server_rack_42u": "Szafa serwerowa (42U)", + "pack:nextfloor.a_buero:filing_cabinet": "Szafa na dokumenty", + "pack:nextfloor.a_buero:whiteboard": "Tablica suchościeralna", + "pack:nextfloor.a_buero:triple_monitor": "Zestaw trzech monitorów", + "pack:nextfloor.a_buero:bookcase_wall": "Ściana z regałami", + "pack:nextfloor.a_buero:desk_lamp": "Lampka biurkowa", + "pack:nextfloor.a_buero:desk_lamp_led": "Lampka biurkowa LED", + "pack:nextfloor.a_buero:arcade_cabinet": "Automat arcade", + "pack:nextfloor.a_buero:office_lounge_sofa": "Sofa lounge do biura", + "pack:nextfloor.a_buero:monitor_light_bar": "Monitor z listwą świetlną", + "pack:nextfloor.a_buero:printer_laser": "Drukarka laserowa", + "pack:nextfloor.a_buero:wifi_router": "Router Wi-Fi", + "pack:nextfloor.a_buero:phone_booth": "Budka do rozmów", + "pack:nextfloor.a_buero:printer_3d": "Drukarka 3D", + "pack:nextfloor.a_buero:printer_cube": "Zamknięta drukarka 3D typu kostka", + "pack:nextfloor.a_buero:printer_multi": "Drukarka 3D kostka z modułem wielokolorowym", + "pack:nextfloor.a_buero:printer_large": "Duża drukarka 3D z dwiema dyszami", + "pack:nextfloor.a_buero:printer_open": "Kompaktowa otwarta drukarka 3D", + "pack:nextfloor.a_buero:printer_resin": "Drukarka 3D żywiczna", + "pack:nextfloor.a_buero:filament_dryer": "Suszarka do filamentu", + "pack:nextfloor.a_buero:filament_rack": "Ścienny stojak na filament", + "packname:nextfloor.a_fitness": "Fitness", + "pack:nextfloor.a_fitness:treadmill": "Bieżnia", + "pack:nextfloor.a_fitness:power_rack": "Klatka treningowa z ławką", + "pack:nextfloor.a_fitness:rowing_machine": "Wioślarz", + "pack:nextfloor.a_fitness:spin_bike": "Rower spinningowy", + "pack:nextfloor.a_fitness:dumbbell_rack": "Stojak na hantle", + "pack:nextfloor.a_fitness:punching_bag": "Worek treningowy", + "pack:nextfloor.a_fitness:yoga_mat": "Mata do jogi z kostką", + "pack:nextfloor.a_fitness:elliptical": "Orbitrek", + "pack:nextfloor.a_fitness:mirror_wall_gym": "Ściana luster", + "pack:nextfloor.a_fitness:exercise_ball": "Piłka gimnastyczna", + "pack:nextfloor.a_fitness:wall_bars": "Drabinka gimnastyczna", + "pack:nextfloor.a_fitness:fitness_mirror_smart": "Inteligentne lustro fitness", + "pack:nextfloor.a_fitness:bike_trainer": "Rower na trenażerze smart", + "pack:nextfloor.a_fitness:sauna_cabin": "Kabina sauny", + "pack:nextfloor.a_fitness:massage_chair": "Fotel masujący", + "pack:nextfloor.a_fitness:kettlebells": "Zestaw kettlebelli", + "pack:nextfloor.a_fitness:water_cooler": "Dystrybutor wody", + "packname:nextfloor.a_garten": "Ogród i taras", + "pack:nextfloor.a_garten:grill_gas": "Grill gazowy", + "pack:nextfloor.a_garten:lounge_set": "Zestaw wypoczynkowy", + "pack:nextfloor.a_garten:sun_lounger_adj": "Leżak", + "pack:nextfloor.a_garten:parasol": "Parasol", + "pack:nextfloor.a_garten:pergola": "Pergola", + "pack:nextfloor.a_garten:raised_bed": "Grządka podwyższona", + "pack:nextfloor.a_garten:greenhouse": "Szklarnia", + "pack:nextfloor.a_garten:hot_tub": "Jacuzzi ogrodowe", + "pack:nextfloor.a_garten:fire_bowl": "Palenisko", + "pack:nextfloor.a_garten:garden_torch": "Pochodnia ogrodowa", + "pack:nextfloor.a_garten:play_tower": "Wieża zabaw ze zjeżdżalnią", + "pack:nextfloor.a_garten:garden_shed": "Domek ogrodowy", + "pack:nextfloor.a_garten:trampoline": "Trampolina", + "pack:nextfloor.a_garten:flower_pots": "Doniczki (zestaw 3)", + "pack:nextfloor.a_garten:sprinkler": "Zraszacz trawnika", + "pack:nextfloor.a_garten:valve_box": "Skrzynka zaworów nawadniania", + "pack:nextfloor.a_garten:rain_barrel": "Beczka na deszczówkę", + "pack:nextfloor.a_garten:garden_lantern": "Latarnia ogrodowa", + "pack:nextfloor.a_garten:outdoor_kitchen": "Kuchnia ogrodowa", + "pack:nextfloor.a_garten:hammock": "Hamak ze stojakiem", + "pack:nextfloor.a_garten:patio_heater": "Promiennik tarasowy", + "pack:nextfloor.a_garten:tree_oak": "Dąb", + "pack:nextfloor.a_garten:tree_lime": "Lipa", + "pack:nextfloor.a_garten:tree_birch": "Brzoza", + "pack:nextfloor.a_garten:tree_maple": "Klon", + "pack:nextfloor.a_garten:tree_fruit": "Drzewo owocowe", + "pack:nextfloor.a_garten:tree_spruce": "Świerk", + "pack:nextfloor.a_garten:tree_pine": "Sosna", + "pack:nextfloor.a_garten:tree_thuja": "Tuja", + "pack:nextfloor.a_garten:shrub": "Krzew", + "pack:nextfloor.a_garten:shrub_flowering": "Krzew kwitnący", + "pack:nextfloor.a_garten:brush_wild": "Zarośla (dziki zakątek)", + "pack:nextfloor.a_garten:tree_group_3": "Grupa drzew (3)", + "pack:nextfloor.a_garten:bin_rest_120": "Pojemnik na odpady zmieszane 120 l", + "pack:nextfloor.a_garten:bin_rest_240": "Pojemnik na odpady zmieszane 240 l", + "pack:nextfloor.a_garten:bin_bio_120": "Pojemnik na bioodpady 120 l", + "pack:nextfloor.a_garten:bin_bio_240": "Pojemnik na bioodpady 240 l", + "pack:nextfloor.a_garten:bin_paper_120": "Pojemnik na papier 120 l", + "pack:nextfloor.a_garten:bin_paper_240": "Pojemnik na papier 240 l", + "pack:nextfloor.a_garten:bin_yellow_120": "Pojemnik na tworzywa 120 l", + "pack:nextfloor.a_garten:bin_yellow_240": "Pojemnik na tworzywa 240 l", + "pack:nextfloor.a_garten:mailbox": "Skrzynka pocztowa", + "pack:nextfloor.a_garten:mailbox_post": "Skrzynka pocztowa na słupku", + "pack:nextfloor.a_garten:awning_300": "Markiza 3 m", + "pack:nextfloor.a_garten:awning_400": "Markiza 4 m", + "pack:nextfloor.a_garten:awning_500": "Markiza 5 m", + "pack:nextfloor.a_garten:sliding_gate": "Brama przesuwna", + "packname:nextfloor.a_haustechnik": "Gospodarstwo i instalacje", + "pack:nextfloor.a_haustechnik:gas_boiler": "Gazowy kocioł kondensacyjny", + "pack:nextfloor.a_haustechnik:heat_pump_tower": "Jednostka wewnętrzna pompy ciepła (wieża hydrauliczna)", + "pack:nextfloor.a_haustechnik:buffer_tank": "Zbiornik buforowy", + "pack:nextfloor.a_haustechnik:heating_manifold": "Rozdzielacz ogrzewania podłogowego", + "pack:nextfloor.a_haustechnik:ventilation_unit": "Rekuperator", + "pack:nextfloor.a_haustechnik:split_indoor": "Klimatyzator split (jednostka wewnętrzna, ścienna)", + "pack:nextfloor.a_haustechnik:split_outdoor": "Klimatyzator split (jednostka zewnętrzna)", + "pack:nextfloor.a_haustechnik:radiator_tall": "Wysoki grzejnik dekoracyjny", + "pack:nextfloor.a_haustechnik:meter_cabinet": "Szafka licznikowa", + "pack:nextfloor.a_haustechnik:water_softener": "Zmiękczacz wody", + "pack:nextfloor.a_haustechnik:water_pump": "Hydrofor", + "pack:nextfloor.a_haustechnik:drip_tray": "Taca z czujnikiem wycieku", + "pack:nextfloor.a_haustechnik:chest_freezer": "Zamrażarka skrzyniowa", + "pack:nextfloor.a_haustechnik:ironing_station": "Żelazko z generatorem pary", + "pack:nextfloor.a_haustechnik:drying_rack": "Suszarka na pranie", + "pack:nextfloor.a_haustechnik:rotary_line": "Suszarka ogrodowa obrotowa", + "pack:nextfloor.a_haustechnik:pantry_shelf_util": "Regał spiżarniany", + "pack:nextfloor.a_haustechnik:utility_sink": "Zlew gospodarczy", + "pack:nextfloor.a_haustechnik:laundry_basket_util": "Kosz na pranie", + "pack:nextfloor.a_haustechnik:vacuum_station": "Stacja odkurzacza bezprzewodowego", + "packname:nextfloor.a_haustiere": "Zwierzęta domowe", + "pack:nextfloor.a_haustiere:cat_tree_large": "Drapak (duży)", + "pack:nextfloor.a_haustiere:scratch_post": "Słupek do drapania", + "pack:nextfloor.a_haustiere:scratch_board_wall": "Drapak ścienny", + "pack:nextfloor.a_haustiere:cat_cave": "Budka dla kota", + "pack:nextfloor.a_haustiere:cat_bed_round": "Okrągłe legowisko dla kota", + "pack:nextfloor.a_haustiere:cat_wall_shelf": "Półka ścienna dla kota", + "pack:nextfloor.a_haustiere:cat_steps": "Schodki dla kota", + "pack:nextfloor.a_haustiere:litter_covered": "Kuweta kryta", + "pack:nextfloor.a_haustiere:litter_auto": "Kuweta samoczyszcząca", + "pack:nextfloor.a_haustiere:dog_bed": "Legowisko dla psa", + "pack:nextfloor.a_haustiere:dog_basket": "Kosz dla psa", + "pack:nextfloor.a_haustiere:dog_house": "Buda dla psa", + "pack:nextfloor.a_haustiere:pet_bowls": "Miski na karmę i wodę", + "pack:nextfloor.a_haustiere:pet_feeder": "Automatyczny karmnik", + "pack:nextfloor.a_haustiere:pet_fountain": "Poidełko fontanna", + "pack:nextfloor.a_haustiere:pet_gate": "Bramka dla zwierząt", + "pack:nextfloor.a_haustiere:pet_stairs": "Schodki dla zwierząt", + "pack:nextfloor.a_haustiere:hamster_cage": "Klatka dla chomika", + "pack:nextfloor.a_haustiere:small_animal_cage": "Klatka dla małych zwierząt", + "pack:nextfloor.a_haustiere:rabbit_run": "Wybieg dla królików (zewnętrzny)", + "pack:nextfloor.a_haustiere:bird_cage": "Klatka dla ptaków", + "pack:nextfloor.a_haustiere:aquarium_100": "Akwarium 100 l", + "pack:nextfloor.a_haustiere:aquarium_240": "Akwarium 240 l z szafką", + "pack:nextfloor.a_haustiere:terrarium": "Terrarium", + "pack:nextfloor.a_haustiere:pet_cat": "Kot (chodzi po domu)", + "pack:nextfloor.a_haustiere:pet_dog": "Pies (chodzi po domu)", + "pack:nextfloor.a_haustiere:pet_rabbit": "Królik (skacze po domu)", + "packname:nextfloor.a_kinderzimmer": "Pokój dziecięcy", + "pack:nextfloor.a_kinderzimmer:loft_bed_slide": "Łóżko na antresoli ze zjeżdżalnią", + "pack:nextfloor.a_kinderzimmer:teepee": "Namiot tipi", + "pack:nextfloor.a_kinderzimmer:play_kitchen": "Kuchnia do zabawy", + "pack:nextfloor.a_kinderzimmer:kids_desk": "Biurko dziecięce", + "pack:nextfloor.a_kinderzimmer:toy_shelf": "Regał na zabawki z pojemnikami", + "pack:nextfloor.a_kinderzimmer:cosy_corner": "Przytulny kącik", + "pack:nextfloor.a_kinderzimmer:rocking_horse": "Koń na biegunach", + "pack:nextfloor.a_kinderzimmer:play_mat_road": "Mata z ulicami", + "pack:nextfloor.a_kinderzimmer:kids_table_2": "Stolik dziecięcy z 2 krzesłami", + "pack:nextfloor.a_kinderzimmer:moon_light": "Lampka nocna księżyc", + "pack:nextfloor.a_kinderzimmer:ball_pit": "Basen z kulkami", + "pack:nextfloor.a_kinderzimmer:house_bed": "Łóżko domek", + "pack:nextfloor.a_kinderzimmer:baby_monitor": "Niania z kamerą", + "pack:nextfloor.a_kinderzimmer:star_projector": "Projektor gwiazd", + "pack:nextfloor.a_kinderzimmer:kids_cot": "Łóżeczko", + "pack:nextfloor.a_kinderzimmer:kids_changing_table": "Przewijak", + "pack:nextfloor.a_kinderzimmer:kids_wardrobe": "Szafa dziecięca", + "pack:nextfloor.a_kinderzimmer:toy_boxes_3": "Pudełka na zabawki (3)", + "packname:nextfloor.a_kino": "Kino domowe i hi-fi", + "pack:nextfloor.a_kino:screen_wall": "Ekran projekcyjny (ścienny)", + "pack:nextfloor.a_kino:screen_roll": "Ekran projekcyjny rozwijany", + "pack:nextfloor.a_kino:projector_ceiling": "Projektor (sufitowy)", + "pack:nextfloor.a_kino:projector_table": "Projektor (stołowy)", + "pack:nextfloor.a_kino:speaker_floor": "Kolumna podłogowa", + "pack:nextfloor.a_kino:speaker_shelf": "Kolumna podstawkowa", + "pack:nextfloor.a_kino:speaker_centre": "Głośnik centralny", + "pack:nextfloor.a_kino:subwoofer": "Subwoofer", + "pack:nextfloor.a_kino:soundbar": "Soundbar", + "pack:nextfloor.a_kino:soundbar_premium": "Soundbar premium", + "pack:nextfloor.a_kino:speaker_wall": "Głośnik ścienny", + "pack:nextfloor.a_kino:speaker_ceiling": "Głośnik sufitowy", + "pack:nextfloor.a_kino:av_receiver": "Amplituner AV", + "pack:nextfloor.a_kino:turntable": "Gramofon", + "pack:nextfloor.a_kino:record_shelf": "Półka na płyty", + "pack:nextfloor.a_kino:game_console": "Konsola do gier", + "pack:nextfloor.a_kino:hifi_rack": "Szafka hi-fi", + "pack:nextfloor.a_kino:cinema_seat": "Fotel kinowy", + "pack:nextfloor.a_kino:cinema_row_3": "Rząd foteli kinowych (3)", + "pack:nextfloor.a_kino:acoustic_panel": "Panel akustyczny", + "pack:nextfloor.a_kino:bass_trap": "Pułapka basowa (narożna)", + "pack:nextfloor.a_kino:popcorn_maker": "Maszyna do popcornu", + "pack:nextfloor.a_kino:star_ceiling": "Gwiaździste niebo", + "pack:nextfloor.a_kino:smart_speaker_ball": "Inteligentny głośnik (kula)", + "pack:nextfloor.a_kino:smart_speaker_cylinder": "Inteligentny głośnik (walec)", + "pack:nextfloor.a_kino:smart_speaker_puck": "Inteligentny głośnik (krążek)", + "pack:nextfloor.a_kino:smart_speaker_pod": "Inteligentny głośnik (pod)", + "pack:nextfloor.a_kino:smart_speaker_tall": "Inteligentny głośnik (wysoki)", + "pack:nextfloor.a_kino:smart_speaker_oval": "Inteligentny głośnik (owalny)", + "pack:nextfloor.a_kino:multiroom_compact": "Kompaktowy głośnik multiroom", + "pack:nextfloor.a_kino:speaker_portable": "Głośnik przenośny", + "pack:nextfloor.a_kino:display_5": "Inteligentny ekran 5″", + "pack:nextfloor.a_kino:display_8": "Inteligentny ekran 8″", + "pack:nextfloor.a_kino:display_7_float": "Inteligentny ekran 7″ (pływający)", + "pack:nextfloor.a_kino:display_15_wall": "Inteligentny ekran 15″ (ścienny)", + "pack:nextfloor.a_kino:speaker_stand": "Stojak na głośnik", + "packname:nextfloor.a_kueche": "Kuchnia", + "pack:nextfloor.a_kueche:base_30": "Szafka dolna 30", + "pack:nextfloor.a_kueche:base_40": "Szafka dolna 40", + "pack:nextfloor.a_kueche:base_50": "Szafka dolna 50", + "pack:nextfloor.a_kueche:base_60": "Szafka dolna 60", + "pack:nextfloor.a_kueche:base_80": "Szafka dolna 80", + "pack:nextfloor.a_kueche:base_90": "Szafka dolna 90", + "pack:nextfloor.a_kueche:base_100": "Szafka dolna 100", + "pack:nextfloor.a_kueche:base_120": "Szafka dolna 120", + "pack:nextfloor.a_kueche:drawer_40": "Szafka z szufladami 40", + "pack:nextfloor.a_kueche:drawer_50": "Szafka z szufladami 50", + "pack:nextfloor.a_kueche:drawer_60": "Szafka z szufladami 60", + "pack:nextfloor.a_kueche:drawer_80": "Szafka z szufladami 80", + "pack:nextfloor.a_kueche:drawer_90": "Szafka z szufladami 90", + "pack:nextfloor.a_kueche:drawer_100": "Szafka z szufladami 100", + "pack:nextfloor.a_kueche:drawer_120": "Szafka z szufladami 120", + "pack:nextfloor.a_kueche:sink_60": "Szafka zlewowa 60", + "pack:nextfloor.a_kueche:sink_80": "Szafka zlewowa 80", + "pack:nextfloor.a_kueche:sink_100": "Szafka zlewowa 100", + "pack:nextfloor.a_kueche:hob_60": "Szafka pod płytę 60", + "pack:nextfloor.a_kueche:hob_80": "Szafka pod płytę 80", + "pack:nextfloor.a_kueche:cooker_60": "Kuchenka z piekarnikiem 60", + "pack:nextfloor.a_kueche:dishwasher_60": "Zmywarka do zabudowy 60", + "pack:nextfloor.a_kueche:dishwasher_45": "Zmywarka do zabudowy 45", + "pack:nextfloor.a_kueche:base_corner": "Szafka narożna dolna", + "pack:nextfloor.a_kueche:wall_40": "Szafka wisząca 40", + "pack:nextfloor.a_kueche:wall_50": "Szafka wisząca 50", + "pack:nextfloor.a_kueche:wall_60": "Szafka wisząca 60", + "pack:nextfloor.a_kueche:wall_80": "Szafka wisząca 80", + "pack:nextfloor.a_kueche:wall_90": "Szafka wisząca 90", + "pack:nextfloor.a_kueche:wall_100": "Szafka wisząca 100", + "pack:nextfloor.a_kueche:wall_120": "Szafka wisząca 120", + "pack:nextfloor.a_kueche:wall_glass_80": "Szklana szafka wisząca 80", + "pack:nextfloor.a_kueche:wall_corner": "Narożna szafka wisząca", + "pack:nextfloor.a_kueche:hood_wall": "Okap przyścienny", + "pack:nextfloor.a_kueche:hood_island": "Okap wyspowy", + "pack:nextfloor.a_kueche:tall_pantry": "Wysoki słupek spiżarniany", + "pack:nextfloor.a_kueche:tall_oven": "Słupek z piekarnikiem i mikrofalówką", + "pack:nextfloor.a_kueche:tall_fridge": "Słupek z lodówko-zamrażarką", + "pack:nextfloor.a_kueche:tall_steam": "Słupek z piekarnikiem parowym", + "pack:nextfloor.a_kueche:fridge_freezer": "Lodówko-zamrażarka", + "pack:nextfloor.a_kueche:fridge_french": "Lodówka French door", + "pack:nextfloor.a_kueche:wine_fridge": "Chłodziarka do wina", + "pack:nextfloor.a_kueche:glass_cabinet": "Witryna", + "pack:nextfloor.a_kueche:row_270": "Kuchnia w linii 270", + "pack:nextfloor.a_kueche:row_330": "Kuchnia w linii 330", + "pack:nextfloor.a_kueche:island_bar": "Wyspa kuchenna z barem", + "pack:nextfloor.a_kueche:island_hob": "Wyspa kuchenna z płytą", + "pack:nextfloor.a_kueche:breakfast_bar": "Bar śniadaniowy (ścienny)", + "pack:nextfloor.a_kueche:bar_stools_2": "Hokery (zestaw 2)", + "pack:nextfloor.a_kueche:dining_bench_long": "Długi stół jadalny z ławką", + "pack:nextfloor.a_kueche:dining_round_4": "Okrągły stół jadalny z 4 krzesłami", + "pack:nextfloor.a_kueche:high_table_2": "Stół barowy z 2 hokerami", + "pack:nextfloor.a_kueche:kitchen_trolley": "Wózek kuchenny", + "pack:nextfloor.a_kueche:pantry_shelf": "Regał spiżarniany", + "pack:nextfloor.a_kueche:spice_rack": "Ścienna półka na przyprawy", + "pack:nextfloor.a_kueche:coffee_machine": "Ekspres automatyczny", + "pack:nextfloor.a_kueche:microwave": "Mikrofalówka", + "pack:nextfloor.a_kueche:stand_mixer": "Robot planetarny", + "pack:nextfloor.a_kueche:kettle": "Czajnik", + "pack:nextfloor.a_kueche:toaster": "Toster", + "pack:nextfloor.a_kueche:herb_garden": "Inteligentny ogródek ziołowy", + "pack:nextfloor.a_kueche:pendant_trio": "Trzy lampy wiszące", + "pack:nextfloor.a_kueche:pendant_linear": "Liniowa lampa wisząca", + "pack:nextfloor.a_kueche:cabinet_light_60": "Oświetlenie LED pod szafkę 60", + "pack:nextfloor.a_kueche:cabinet_light_80": "Oświetlenie LED pod szafkę 80", + "pack:nextfloor.a_kueche:range_cooker_90": "Kuchnia wolnostojąca 90", + "packname:nextfloor.a_schlafzimmer": "Sypialnia", + "pack:nextfloor.a_schlafzimmer:bed_90": "Łóżko 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_140": "Łóżko 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_160": "Łóżko 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_180": "Łóżko 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_200": "Łóżko 200 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_180": "Łóżko tapicerowane 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_140": "Łóżko tapicerowane 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_boxspring": "Łóżko kontynentalne 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_futon": "Łóżko futon 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_storage": "Łóżko z pojemnikiem 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_canopy": "Łóżko z baldachimem", + "pack:nextfloor.a_schlafzimmer:bed_ambient": "Łóżko 180 z podświetleniem", + "pack:nextfloor.a_schlafzimmer:bed_bench": "Ławka do łóżka", + "pack:nextfloor.a_schlafzimmer:shoe_bench": "Ławka na buty", + "pack:nextfloor.a_schlafzimmer:wardrobe_2": "Szafa 2-drzwiowa", + "pack:nextfloor.a_schlafzimmer:wardrobe_3": "Szafa 3-drzwiowa", + "pack:nextfloor.a_schlafzimmer:wardrobe_4": "Szafa 4-drzwiowa", + "pack:nextfloor.a_schlafzimmer:wardrobe_6": "Szafa 6-drzwiowa", + "pack:nextfloor.a_schlafzimmer:wardrobe_mirror": "Szafa z lustrzanymi drzwiami", + "pack:nextfloor.a_schlafzimmer:wardrobe_sliding": "Szafa przesuwna", + "pack:nextfloor.a_schlafzimmer:wardrobe_light": "Szafa z oświetleniem wewnętrznym", + "pack:nextfloor.a_schlafzimmer:wardrobe_corner": "Szafa narożna", + "pack:nextfloor.a_schlafzimmer:walk_in_closet": "Otwarta garderoba", + "pack:nextfloor.a_schlafzimmer:clothes_rail": "Wieszak na ubrania", + "pack:nextfloor.a_schlafzimmer:nightstand": "Szafka nocna z szufladą", + "pack:nextfloor.a_schlafzimmer:nightstand_slim": "Wąska szafka nocna", + "pack:nextfloor.a_schlafzimmer:nightstand_floating": "Wisząca szafka nocna", + "pack:nextfloor.a_schlafzimmer:dresser_6": "Komoda 6 szuflad 140", + "pack:nextfloor.a_schlafzimmer:chest_tall_5": "Wysoka komoda 5 szuflad", + "pack:nextfloor.a_schlafzimmer:chest_tall": "Wysoka komoda", + "pack:nextfloor.a_schlafzimmer:chest_80": "Komoda 3 szuflady 80", + "pack:nextfloor.a_schlafzimmer:vanity_table": "Toaletka z lustrem", + "pack:nextfloor.a_schlafzimmer:dressing_table_light": "Toaletka z podświetlanym lustrem", + "pack:nextfloor.a_schlafzimmer:cot": "Łóżeczko", + "pack:nextfloor.a_schlafzimmer:changing_table": "Przewijak", + "pack:nextfloor.a_schlafzimmer:standing_mirror": "Lustro stojące", + "pack:nextfloor.a_schlafzimmer:reading_nook": "Kącik do czytania z fotelem", + "pack:nextfloor.a_schlafzimmer:bedside_lamp": "Lampka nocna", + "pack:nextfloor.a_schlafzimmer:touch_lamp": "Dotykowa lampka nocna", + "pack:nextfloor.a_schlafzimmer:humidifier": "Nawilżacz powietrza", + "pack:nextfloor.a_schlafzimmer:sunrise_clock": "Budzik ze świtem", + "packname:nextfloor.a_smart": "Smart home i technika", + "pack:nextfloor.a_smart:wallbox": "Wallbox", + "pack:nextfloor.a_smart:electric_car": "Samochód elektryczny", + "pack:nextfloor.a_smart:heat_pump_outdoor": "Pompa ciepła (jednostka zewnętrzna)", + "pack:nextfloor.a_smart:home_battery": "Magazyn energii", + "pack:nextfloor.a_smart:inverter_solar": "Falownik fotowoltaiczny", + "pack:nextfloor.a_smart:robot_vacuum": "Robot sprzątający ze stacją", + "pack:nextfloor.a_smart:mower_garage": "Robot koszący z garażem", + "pack:nextfloor.a_smart:washer_dryer_stack": "Słupek pralka-suszarka", + "pack:nextfloor.a_smart:network_rack": "Szafa sieciowa", + "pack:nextfloor.a_smart:smart_display": "Inteligentny ekran", + "pack:nextfloor.a_smart:solar_balcony": "Panel solarny balkonowy", + "pack:nextfloor.a_smart:fuse_box": "Rozdzielnica", + "pack:nextfloor.a_smart:nas_server": "Serwer NAS", + "pack:nextfloor.a_smart:hot_water_tank": "Zasobnik ciepłej wody", + "pack:nextfloor.a_smart:light_pillar": "Kolumna świetlna z gradientem", + "pack:nextfloor.a_smart:light_bars_tv": "Para listew świetlnych (TV)", + "pack:nextfloor.a_smart:orb_lamp": "Świecąca kula na stół", + "pack:nextfloor.a_smart:glow_lamp_portable": "Przenośna lampka", + "pack:nextfloor.a_smart:mood_spot": "Nastrojowy reflektorek na stół", + "pack:nextfloor.a_smart:cube_lamp": "Lampa sześcian", + "pack:nextfloor.a_smart:ceiling_panel_round": "Okrągły panel sufitowy", + "pack:nextfloor.a_smart:garden_spots_3": "Reflektory ogrodowe (zestaw 3)", + "pack:nextfloor.a_smart:wall_light_updown": "Kinkiet zewnętrzny góra-dół", + "pack:nextfloor.a_smart:siren_strobe": "Syrena ze stroboskopem", + "pack:nextfloor.a_smart:access_point": "Punkt dostępowy Wi-Fi (sufitowy)", + "pack:nextfloor.a_smart:smoke_detector": "Czujnik dymu", + "pack:nextfloor.a_smart:thermostat_wall": "Termostat ścienny", + "pack:nextfloor.a_smart:dehumidifier": "Osuszacz powietrza", + "pack:nextfloor.a_smart:ceiling_fan": "Wentylator sufitowy", + "pack:nextfloor.a_smart:ceiling_fan_light": "Wentylator sufitowy z oświetleniem", + "pack:nextfloor.a_smart:light_switch_1": "Włącznik światła, pojedynczy", + "pack:nextfloor.a_smart:socket_1": "Gniazdo, pojedyncze", + "pack:nextfloor.a_smart:light_switch_2": "Włącznik światła, podwójny", + "pack:nextfloor.a_smart:socket_2": "Gniazdo, podwójne", + "pack:nextfloor.a_smart:light_switch_3": "Włącznik światła, potrójny", + "pack:nextfloor.a_smart:socket_3": "Gniazdo, potrójne", + "pack:nextfloor.a_smart:light_switch_4": "Włącznik światła, poczwórny", + "pack:nextfloor.a_smart:socket_4": "Gniazdo, poczwórne", + "pack:nextfloor.a_smart:socket_outdoor": "Gniazdo zewnętrzne z klapką", + "packname:nextfloor.a_wohnzimmer": "Salon", + "pack:nextfloor.a_wohnzimmer:sofa_2": "Sofa 2-osobowa", + "pack:nextfloor.a_wohnzimmer:sofa_3": "Sofa 3-osobowa", + "pack:nextfloor.a_wohnzimmer:sofa_4": "Duża sofa 4-osobowa", + "pack:nextfloor.a_wohnzimmer:sofa_velvet": "Aksamitna sofa 3-osobowa", + "pack:nextfloor.a_wohnzimmer:sofa_armless": "Sofa bez podłokietników", + "pack:nextfloor.a_wohnzimmer:sofa_chaise": "Sofa z szezlongiem", + "pack:nextfloor.a_wohnzimmer:sofa_chesterfield": "Sofa Chesterfield", + "pack:nextfloor.a_wohnzimmer:sofa_bed": "Sofa rozkładana", + "pack:nextfloor.a_wohnzimmer:sofa_corner_l": "Narożnik (lewy)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_r": "Narożnik (prawy)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_xl": "Duży narożnik (w kształcie L)", + "pack:nextfloor.a_wohnzimmer:sofa_u": "Sofa w kształcie U", + "pack:nextfloor.a_wohnzimmer:chaise_longue": "Szezlong", + "pack:nextfloor.a_wohnzimmer:modular_sofa": "Sofa modułowa (5 części)", + "pack:nextfloor.a_wohnzimmer:armchair": "Fotel", + "pack:nextfloor.a_wohnzimmer:club_chair": "Fotel klubowy", + "pack:nextfloor.a_wohnzimmer:wingback": "Fotel uszak", + "pack:nextfloor.a_wohnzimmer:cocktail_chair": "Fotel koktajlowy", + "pack:nextfloor.a_wohnzimmer:recliner": "Fotel relaksacyjny z podnóżkiem", + "pack:nextfloor.a_wohnzimmer:bean_bag": "Pufa sako", + "pack:nextfloor.a_wohnzimmer:pouf": "Puf", + "pack:nextfloor.a_wohnzimmer:rocking_chair": "Fotel bujany", + "pack:nextfloor.a_wohnzimmer:coffee_rect": "Prostokątny stolik kawowy", + "pack:nextfloor.a_wohnzimmer:coffee_glass": "Szklany stolik kawowy", + "pack:nextfloor.a_wohnzimmer:coffee_round": "Okrągły stolik kawowy", + "pack:nextfloor.a_wohnzimmer:coffee_nesting": "Zestaw stolików", + "pack:nextfloor.a_wohnzimmer:side_round": "Okrągły stolik pomocniczy", + "pack:nextfloor.a_wohnzimmer:console": "Konsola", + "pack:nextfloor.a_wohnzimmer:dining_120": "Stół jadalny 120 × 90", + "pack:nextfloor.a_wohnzimmer:dining_160": "Stół jadalny 160 × 90", + "pack:nextfloor.a_wohnzimmer:dining_200": "Stół jadalny 200 × 90", + "pack:nextfloor.a_wohnzimmer:dining_220": "Stół z litego drewna 220 × 100", + "pack:nextfloor.a_wohnzimmer:chair_wood": "Krzesło drewniane", + "pack:nextfloor.a_wohnzimmer:chair_upholstered": "Krzesło tapicerowane", + "pack:nextfloor.a_wohnzimmer:chair_shell": "Krzesło kubełkowe", + "pack:nextfloor.a_wohnzimmer:dining_bench": "Ławka do jadalni 160", + "pack:nextfloor.a_wohnzimmer:lowboard_120": "Szafka RTV 120", + "pack:nextfloor.a_wohnzimmer:lowboard_160": "Szafka RTV 160", + "pack:nextfloor.a_wohnzimmer:lowboard_200": "Szafka RTV 200", + "pack:nextfloor.a_wohnzimmer:sideboard_160": "Kredens 160", + "pack:nextfloor.a_wohnzimmer:highboard": "Wysoka komoda", + "pack:nextfloor.a_wohnzimmer:display_cabinet": "Witryna", + "pack:nextfloor.a_wohnzimmer:chest_3": "Komoda z 3 szufladami", + "pack:nextfloor.a_wohnzimmer:bookshelf_tall": "Wysoki regał na książki", + "pack:nextfloor.a_wohnzimmer:bookshelf_wide": "Szeroki regał na książki", + "pack:nextfloor.a_wohnzimmer:cube_2x2": "Regał kubik 2 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x2": "Regał kubik 4 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x4": "Regał kubik 4 × 4", + "pack:nextfloor.a_wohnzimmer:divider_open": "Regał działowy", + "pack:nextfloor.a_wohnzimmer:wall_shelf": "Wisząca półka", + "pack:nextfloor.a_wohnzimmer:coat_stand": "Wieszak stojący", + "pack:nextfloor.a_wohnzimmer:wall_unit_vitrines": "Meblościanka z witrynami", + "pack:nextfloor.a_wohnzimmer:wall_unit_tv": "Meblościanka z TV", + "pack:nextfloor.a_wohnzimmer:tv_on_stand": "TV na stojaku", + "pack:nextfloor.a_wohnzimmer:media_wall": "Ściana multimedialna z TV", + "pack:nextfloor.a_wohnzimmer:wood_stove": "Piec na drewno", + "pack:nextfloor.a_wohnzimmer:fireplace_wall": "Elektryczny kominek ścienny", + "pack:nextfloor.a_wohnzimmer:piano": "Pianino z ławeczką", + "pack:nextfloor.a_wohnzimmer:floor_lamp_arc": "Lampa łukowa", + "pack:nextfloor.a_wohnzimmer:floor_lamp_tripod": "Lampa trójnóg", + "pack:nextfloor.a_wohnzimmer:table_lamp_ceramic": "Ceramiczna lampa stołowa", + "pack:nextfloor.a_wohnzimmer:vase_pampas": "Wazon podłogowy z trawą pampasową", + "pack:nextfloor.a_wohnzimmer:monstera": "Duża monstera", + "pack:nextfloor.a_wohnzimmer:rug_round": "Okrągły dywan", + "pack:nextfloor.a_wohnzimmer:rug_240": "Dywan 240 × 170", + "pack:nextfloor.a_wohnzimmer:painting_light": "Obraz z oświetleniem", + "pack:nextfloor.a_wohnzimmer:shelf_led": "Regał z półkami LED", + "pack:nextfloor.a_wohnzimmer:air_purifier": "Oczyszczacz powietrza", + "pack:nextfloor.a_wohnzimmer:tower_fan": "Wentylator kolumnowy", + "pack:nextfloor.a_wohnzimmer:smart_speaker_living": "Inteligentny głośnik", + "packname:nextfloor.ausbau": "Architektura i wykończenie", + "pack:nextfloor.ausbau:column_round": "Okrągła kolumna", + "pack:nextfloor.ausbau:column_square": "Kwadratowa kolumna", + "pack:nextfloor.ausbau:beam": "Belka sufitowa", + "pack:nextfloor.ausbau:chimney": "Komin", + "pack:nextfloor.ausbau:glass_wall": "Szklana ścianka działowa", + "pack:nextfloor.ausbau:sliding_wall": "Ściana przesuwna", + "pack:nextfloor.ausbau:platform": "Podest", + "pack:nextfloor.ausbau:half_wall": "Półścianka", + "pack:nextfloor.ausbau:divider_shelf": "Regał działowy", + "pack:nextfloor.ausbau:pilaster": "Pilaster", + "pack:nextfloor.ausbau:column_steel": "Słup stalowy", + "pack:nextfloor.ausbau:beams_wood_5": "Drewniane belki sufitowe (5)", + "pack:nextfloor.ausbau:beam_downstand": "Podciąg", + "pack:nextfloor.ausbau:fireplace_builtin": "Kominek w zabudowie", + "pack:nextfloor.ausbau:divider_slats": "Lamelowa ścianka działowa", + "pack:nextfloor.ausbau:curtain_motor": "Zasłona z napędem", + "pack:nextfloor.ausbau:niche_shelf": "Regał we wnęce", + "pack:nextfloor.ausbau:niche_led": "Wnęka LED", + "pack:nextfloor.ausbau:light_cove": "Fasada świetlna (sufit)", + "pack:nextfloor.ausbau:gallery_rail_glass": "Balustrada antresoli (szkło)", + "pack:nextfloor.ausbau:window_seat": "Siedzisko okienne", + "pack:nextfloor.ausbau:curtain_pair": "Zasłona (rozsuwana na obie strony)", + "pack:nextfloor.ausbau:roller_blind_inside": "Roleta wewnętrzna", + "packname:nextfloor.bad": "Łazienka – dodatki", + "pack:nextfloor.bad:double_vanity": "Podwójna umywalka", + "pack:nextfloor.bad:walkin_shower": "Prysznic walk-in", + "pack:nextfloor.bad:towel_radiator": "Grzejnik łazienkowy", + "pack:nextfloor.bad:mirror_cabinet": "Szafka z lustrem i oświetleniem", + "pack:nextfloor.bad:washer_tower": "Słupek pralka-suszarka", + "pack:nextfloor.bad:laundry_basket": "Kosz na pranie", + "pack:nextfloor.bad:bath_shelf": "Półka łazienkowa", + "packname:nextfloor.energie": "Energia i instalacje", + "pack:nextfloor.energie:heat_pump": "Pompa ciepła (jednostka zewnętrzna)", + "pack:nextfloor.energie:pellet_boiler": "Kocioł na pellet", + "pack:nextfloor.energie:buffer_tank": "Zbiornik buforowy", + "pack:nextfloor.energie:hot_water_tank": "Zasobnik ciepłej wody", + "pack:nextfloor.energie:home_battery": "Magazyn energii (wieża)", + "pack:nextfloor.energie:inverter": "Falownik", + "pack:nextfloor.energie:wallbox": "Wallbox", + "pack:nextfloor.energie:meter_cabinet": "Szafka licznikowa", + "pack:nextfloor.energie:ventilation": "Centrala wentylacyjna", + "pack:nextfloor.energie:solar_carport_pillar": "Słup wiaty solarnej", + "packname:nextfloor.fahrzeuge": "Pojazdy", + "pack:nextfloor.fahrzeuge:tesla_model_s": "Tesla Model S", + "packname:nextfloor.a_saison": "Sezon i dekoracje", + "packname:nextfloor.a_smart2": "Inteligentny dom 2", + "packname:nextfloor.a_haustechnik2": "Instalacje 2", + "packname:nextfloor.a_wellness": "Wellness", + "packname:nextfloor.a_garten2": "Ogród 2", + "packname:nextfloor.a_kueche2": "Kuchnia 2", + "packname:nextfloor.a_fahrzeuge2": "Pojazdy 2", + "packname:nextfloor.a_aussenkueche": "Kuchnia ogrodowa i taras", + "packname:nextfloor.a_werkstatt2": "Warsztat 2", + "packname:nextfloor.a_japandi": "Japandi i skandynawski", + "packname:nextfloor.a_loft": "Loft i industrialny", + "packname:nextfloor.a_gruen": "Rośliny domowe", + "packname:nextfloor.a_musik": "Muzyka i pracownia", + "pack:nextfloor.a_saison:xmas_tree": "Choinka z lampkami", + "pack:nextfloor.a_saison:advent_wreath": "Wieniec adwentowy", + "pack:nextfloor.a_saison:lights_outdoor": "Girlanda zewnętrzna", + "pack:nextfloor.a_saison:window_star": "Gwiazda okienna", + "pack:nextfloor.a_saison:candle_arch": "Łuk świecznikowy", + "pack:nextfloor.a_saison:reindeer_light": "Świecący renifer", + "pack:nextfloor.a_saison:pumpkin": "Dynia", + "pack:nextfloor.a_saison:pumpkin_lantern": "Lampion z dyni", + "pack:nextfloor.a_saison:easter_tree": "Drzewko wielkanocne", + "pack:nextfloor.a_saison:snowman": "Bałwan", + "pack:nextfloor.a_saison:gift_pile": "Prezenty", + "pack:nextfloor.a_smart2:siren": "Syrena", + "pack:nextfloor.a_smart2:access_point": "Punkt dostępowy Wi-Fi", + "pack:nextfloor.a_smart2:access_point_wall": "Punkt dostępowy Wi-Fi (ścienny)", + "pack:nextfloor.a_smart2:smoke_detector": "Czujnik dymu", + "pack:nextfloor.a_smart2:co_detector": "Czujnik czadu", + "pack:nextfloor.a_smart2:dehumidifier": "Osuszacz powietrza", + "pack:nextfloor.a_smart2:cube_lamp": "Lampa kostka", + "pack:nextfloor.a_smart2:presence_ceiling": "Czujnik obecności (sufit)", + "pack:nextfloor.a_smart2:water_leak": "Czujnik zalania", + "pack:nextfloor.a_smart2:air_quality": "Czujnik jakości powietrza", + "pack:nextfloor.a_smart2:doorbell_cam": "Wideodzwonek", + "pack:nextfloor.a_haustechnik2:water_tank": "Zbiornik wody", + "pack:nextfloor.a_haustechnik2:oil_tank": "Zbiornik oleju", + "pack:nextfloor.a_haustechnik2:oil_boiler": "Kocioł olejowy", + "pack:nextfloor.a_haustechnik2:water_softener": "Zmiękczacz wody", + "pack:nextfloor.a_haustechnik2:buffer_tank": "Zbiornik buforowy", + "pack:nextfloor.a_haustechnik2:cistern": "Zbiornik na deszczówkę", + "pack:nextfloor.a_haustechnik2:ventilation_unit": "Rekuperator", + "pack:nextfloor.a_haustechnik2:expansion_vessel": "Naczynie wzbiorcze", + "pack:nextfloor.a_haustechnik2:heat_pump_indoor": "Pompa ciepła (jednostka wewnętrzna)", + "pack:nextfloor.a_wellness:sauna_cabin": "Sauna", + "pack:nextfloor.a_wellness:sauna_barrel": "Sauna beczka", + "pack:nextfloor.a_wellness:infrared_cabin": "Kabina na podczerwień", + "pack:nextfloor.a_wellness:hot_tub": "Jacuzzi", + "pack:nextfloor.a_wellness:plunge_pool": "Basen do zanurzeń", + "pack:nextfloor.a_wellness:steam_shower": "Kabina parowa", + "pack:nextfloor.a_wellness:relax_lounger": "Leżak relaksacyjny", + "pack:nextfloor.a_wellness:cold_bath": "Balia z lodem", + "pack:nextfloor.a_garten2:water_feature": "Fontanna z oświetleniem", + "pack:nextfloor.a_garten2:pond": "Oczko wodne z pompą", + "pack:nextfloor.a_garten2:robot_mower": "Robot koszący", + "pack:nextfloor.a_garten2:mower_dock": "Stacja ładująca robota", + "pack:nextfloor.a_garten2:sandbox": "Piaskownica", + "pack:nextfloor.a_garten2:beach_chair": "Kosz plażowy", + "pack:nextfloor.a_garten2:wood_pile": "Stos drewna", + "pack:nextfloor.a_garten2:bird_house": "Karmnik", + "pack:nextfloor.a_garten2:raised_bed": "Podwyższona grządka", + "pack:nextfloor.a_garten2:garden_shower": "Prysznic ogrodowy", + "pack:nextfloor.a_kueche2:coffee_machine": "Ekspres automatyczny", + "pack:nextfloor.a_kueche2:espresso": "Ekspres kolbowy", + "pack:nextfloor.a_kueche2:kettle": "Czajnik elektryczny", + "pack:nextfloor.a_kueche2:toaster": "Toster", + "pack:nextfloor.a_kueche2:stand_mixer": "Robot planetarny", + "pack:nextfloor.a_kueche2:thermo_cooker": "Robot kuchenny z gotowaniem", + "pack:nextfloor.a_kueche2:air_fryer": "Frytkownica beztłuszczowa", + "pack:nextfloor.a_kueche2:microwave": "Mikrofalówka", + "pack:nextfloor.a_kueche2:wine_fridge": "Chłodziarka do wina", + "pack:nextfloor.a_kueche2:water_bar": "Saturator", + "pack:nextfloor.a_kueche2:dishwasher_slim": "Zmywarka 45 cm", + "pack:nextfloor.a_fahrzeuge2:motorbike": "Motocykl", + "pack:nextfloor.a_fahrzeuge2:scooter": "Skuter", + "pack:nextfloor.a_fahrzeuge2:camper_van": "Kamper", + "pack:nextfloor.a_fahrzeuge2:trailer": "Przyczepa", + "pack:nextfloor.a_fahrzeuge2:e_bike": "Rower elektryczny", + "pack:nextfloor.a_fahrzeuge2:cargo_bike": "Rower cargo", + "pack:nextfloor.a_fahrzeuge2:quad": "Quad", + "pack:nextfloor.a_fahrzeuge2:boat_trailer": "Przyczepa z łodzią", + "pack:nextfloor.a_aussenkueche:outdoor_kitchen": "Kuchnia zewnętrzna", + "pack:nextfloor.a_aussenkueche:kamado": "Grill kamado", + "pack:nextfloor.a_aussenkueche:pizza_oven": "Piec do pizzy", + "pack:nextfloor.a_aussenkueche:fire_pit": "Palenisko", + "pack:nextfloor.a_aussenkueche:patio_heater": "Promiennik tarasowy", + "pack:nextfloor.a_aussenkueche:outdoor_fridge": "Lodówka zewnętrzna", + "pack:nextfloor.a_aussenkueche:bar_counter": "Bar", + "pack:nextfloor.a_aussenkueche:bar_stool_out": "Hoker zewnętrzny", + "pack:nextfloor.a_aussenkueche:hanging_chair": "Fotel wiszący", + "pack:nextfloor.a_werkstatt2:workbench_wall": "Stół warsztatowy z tablicą", + "pack:nextfloor.a_werkstatt2:drill_press": "Wiertarka stołowa", + "pack:nextfloor.a_werkstatt2:table_saw": "Pilarka stołowa", + "pack:nextfloor.a_werkstatt2:compressor": "Kompresor", + "pack:nextfloor.a_werkstatt2:welder": "Spawarka", + "pack:nextfloor.a_werkstatt2:heavy_shelf": "Regał magazynowy", + "pack:nextfloor.a_werkstatt2:parts_cabinet": "Kasetka na drobiazgi", + "pack:nextfloor.a_werkstatt2:tool_chest": "Wózek narzędziowy", + "pack:nextfloor.a_werkstatt2:ev_bike_charger": "Stacja ładowania akumulatorów", + "pack:nextfloor.a_japandi:low_bed": "Niskie łóżko", + "pack:nextfloor.a_japandi:tatami": "Tatami", + "pack:nextfloor.a_japandi:paper_lamp": "Papierowa lampa podłogowa", + "pack:nextfloor.a_japandi:paper_pendant": "Papierowa lampa wisząca", + "pack:nextfloor.a_japandi:tea_table": "Niski stolik do herbaty", + "pack:nextfloor.a_japandi:shoji_screen": "Parawan shoji", + "pack:nextfloor.a_japandi:bonsai": "Bonsai", + "pack:nextfloor.a_japandi:floor_cushion": "Poduszka podłogowa", + "pack:nextfloor.a_japandi:wood_bench": "Drewniana ławka", + "pack:nextfloor.a_japandi:rattan_chair": "Fotel rattanowy", + "pack:nextfloor.a_loft:steel_shelf": "Regał stalowy", + "pack:nextfloor.a_loft:factory_pendant": "Industrialna lampa wisząca", + "pack:nextfloor.a_loft:leather_sofa": "Skórzana sofa", + "pack:nextfloor.a_loft:plank_table": "Stół z desek", + "pack:nextfloor.a_loft:locker": "Szafka metalowa", + "pack:nextfloor.a_loft:edison_floor_lamp": "Lampa podłogowa Edison", + "pack:nextfloor.a_loft:bar_stool_loft": "Industrialny hoker", + "pack:nextfloor.a_loft:pipe_shelf": "Półka z rur", + "pack:nextfloor.a_gruen:monstera": "Monstera", + "pack:nextfloor.a_gruen:ficus": "Fikus", + "pack:nextfloor.a_gruen:olive_tree": "Drzewko oliwne w donicy", + "pack:nextfloor.a_gruen:cactus_group": "Kaktusy", + "pack:nextfloor.a_gruen:hanging_plant": "Roślina wisząca", + "pack:nextfloor.a_gruen:plant_shelf": "Regał na rośliny z lampą", + "pack:nextfloor.a_gruen:vertical_garden": "Ogród wertykalny", + "pack:nextfloor.a_gruen:grow_light": "Lampa do roślin", + "pack:nextfloor.a_gruen:herb_planter": "Inteligentny ogródek ziołowy", + "pack:nextfloor.a_musik:upright_piano": "Pianino", + "pack:nextfloor.a_musik:grand_piano": "Fortepian", + "pack:nextfloor.a_musik:drum_kit": "Perkusja", + "pack:nextfloor.a_musik:guitar_stand": "Gitary na statywach", + "pack:nextfloor.a_musik:guitar_amp": "Wzmacniacz gitarowy", + "pack:nextfloor.a_musik:mixing_desk": "Biurko studyjne z mikserem", + "pack:nextfloor.a_musik:studio_monitor": "Monitor studyjny", + "pack:nextfloor.a_musik:synth": "Syntezator", + "pack:nextfloor.a_musik:mic_stand": "Mikrofon na statywie", + "pack:nextfloor.a_musik:easel": "Sztaluga", + "pack:nextfloor.a_musik:vinyl_player": "Gramofon", + "packname:nextfloor.a_bilder": "Obrazy i ramki", + "pack:nextfloor.a_bilder:frame_landscape": "Ramka (pozioma)", + "pack:nextfloor.a_bilder:frame_portrait": "Ramka (pionowa)", + "pack:nextfloor.a_bilder:frame_square": "Ramka (kwadratowa)", + "pack:nextfloor.a_bilder:frame_large": "Duża ramka", + "pack:nextfloor.a_bilder:canvas": "Obraz na płótnie", + "pack:nextfloor.a_bilder:poster": "Plakat", + "pack:nextfloor.a_bilder:frame_table": "Ramka na stół", + "pack:nextfloor.a_bilder:frame_digital": "Cyfrowa ramka", + "pack:nextfloor.a_bilder:picture_ledge": "Półka na ramki", + "color:pearl_white": "Pearl White", + "color:solid_black": "Solid Black", + "color:midnight_silver": "Midnight Silver", + "color:quicksilver": "Quicksilver", + "color:deep_blue": "Deep Blue", + "color:ultra_red": "Ultra Red", + "color:midnight_cherry": "Midnight Cherry Red", + "pack:nextfloor.fahrzeuge:tesla_model_3": "Tesla Model 3", + "color:red": "Red Multi-Coat", + "color:stealth_grey": "Stealth Grey", + "pack:nextfloor.fahrzeuge:tesla_model_x": "Tesla Model X", + "pack:nextfloor.fahrzeuge:tesla_model_y": "Tesla Model Y", + "pack:nextfloor.fahrzeuge:tesla_cybertruck": "Tesla Cybertruck", + "color:stainless": "Stainless Steel", + "color:wrap_black": "Folia Satin Black", + "color:wrap_white": "Folia Satin White", + "color:wrap_grey": "Folia Satin Grey", + "color:wrap_blue": "Folia Satin Blue", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024": "Tesla Model 3 (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024_performance": "Tesla Model 3 Performance (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_s_plaid": "Tesla Model S Plaid", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025": "Tesla Model Y Standard (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_premium": "Tesla Model Y Premium (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_performance": "Tesla Model Y Performance (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_l": "Tesla Model Y L", + "pack:nextfloor.fahrzeuge:tesla_roadster": "Tesla Roadster", + "pack:nextfloor.fahrzeuge:tesla_semi": "Tesla Semi", + "pack:nextfloor.fahrzeuge:ev_suv": "Elektryczny SUV (rozmiar Model Y)", + "pack:nextfloor.fahrzeuge:small_car": "Mały samochód", + "pack:nextfloor.fahrzeuge:estate_car": "Kombi", + "pack:nextfloor.fahrzeuge:van": "Van", + "pack:nextfloor.fahrzeuge:bicycle": "Rower", + "pack:nextfloor.fahrzeuge:ebike": "Rower elektryczny", + "pack:nextfloor.fahrzeuge:motorbike": "Motocykl", + "pack:nextfloor.fahrzeuge:trailer": "Przyczepa", + "pack:nextfloor.fahrzeuge:sedan": "Sedan", + "pack:nextfloor.fahrzeuge:coupe": "Sportowe coupé", + "pack:nextfloor.fahrzeuge:convertible": "Kabriolet (otwarty)", + "pack:nextfloor.fahrzeuge:small_ev": "Mały EV", + "pack:nextfloor.fahrzeuge:suv": "SUV", + "pack:nextfloor.fahrzeuge:family_van": "Van rodzinny", + "pack:nextfloor.fahrzeuge:minibus": "Minibus", + "pack:nextfloor.fahrzeuge:panel_van": "Furgon", + "pack:nextfloor.fahrzeuge:pickup": "Pickup", + "pack:nextfloor.fahrzeuge:campervan": "Kamper (podnoszony dach)", + "pack:nextfloor.fahrzeuge:motorhome": "Samochód kempingowy", + "pack:nextfloor.fahrzeuge:caravan": "Przyczepa kempingowa", + "packname:nextfloor.fitness": "Fitness (starsze)", + "pack:nextfloor.fitness:treadmill": "Bieżnia", + "pack:nextfloor.fitness:bike_trainer": "Rower stacjonarny", + "pack:nextfloor.fitness:rower": "Wioślarz", + "pack:nextfloor.fitness:weight_bench": "Ławka treningowa", + "pack:nextfloor.fitness:power_rack": "Klatka treningowa", + "pack:nextfloor.fitness:yoga_mat": "Mata do jogi", + "pack:nextfloor.fitness:dumbbell_rack": "Stojak na hantle", + "packname:nextfloor.garten": "Ogród i taras (starsze)", + "pack:nextfloor.garten:sun_lounger": "Leżak", + "pack:nextfloor.garten:garden_table": "Stół ogrodowy", + "pack:nextfloor.garten:garden_chair": "Krzesło ogrodowe", + "pack:nextfloor.garten:lounge_set": "Wypoczynek ogrodowy", + "pack:nextfloor.garten:parasol": "Parasol", + "pack:nextfloor.garten:gas_grill": "Grill gazowy", + "pack:nextfloor.garten:fire_bowl": "Palenisko", + "pack:nextfloor.garten:pool": "Basen", + "pack:nextfloor.garten:hot_tub": "Jacuzzi", + "pack:nextfloor.garten:trampoline": "Trampolina", + "pack:nextfloor.garten:greenhouse": "Szklarnia", + "pack:nextfloor.garten:raised_bed": "Grządka podwyższona", + "pack:nextfloor.garten:garden_shed": "Domek ogrodowy", + "pack:nextfloor.garten:swing_bench": "Huśtawka ogrodowa", + "pack:nextfloor.garten:mower_robot": "Robot koszący", + "pack:nextfloor.garten:tree_oak": "Drzewo liściaste", + "pack:nextfloor.garten:tree_birch": "Brzoza", + "pack:nextfloor.garten:tree_fruit": "Drzewo owocowe", + "pack:nextfloor.garten:conifer": "Drzewo iglaste", + "pack:nextfloor.garten:shrub": "Krzew", + "pack:nextfloor.garten:shrub_flowering": "Krzew kwitnący", + "pack:nextfloor.garten:hedge": "Żywopłot", + "pack:nextfloor.garten:lawn_brush": "Chrust", + "pack:nextfloor.garten:bike_rack": "Stojak na rowery", + "pack:nextfloor.garten:bin_box": "Osłona na pojemniki (4)", + "packname:nextfloor.ikea": "Wymiary IKEA", + "pack:nextfloor.ikea:billy": "Regał 80x202 (rozmiar Billy)", + "pack:nextfloor.ikea:billy_low": "Regał 80x106 (rozmiar Billy)", + "pack:nextfloor.ikea:kallax_2x2": "Regał kubik 2x2 (rozmiar Kallax)", + "pack:nextfloor.ikea:kallax_2x4": "Regał kubik 2x4 (rozmiar Kallax)", + "pack:nextfloor.ikea:kallax_4x4": "Regał kubik 4x4 (rozmiar Kallax)", + "pack:nextfloor.ikea:lack_side": "Stolik 55x55 (rozmiar Lack)", + "pack:nextfloor.ikea:lack_coffee": "Stolik kawowy 90x55 (rozmiar Lack)", + "pack:nextfloor.ikea:malm_bed_140": "Łóżko 140x200 (rozmiar Malm)", + "pack:nextfloor.ikea:malm_bed_160": "Łóżko 160x200 (rozmiar Malm)", + "pack:nextfloor.ikea:malm_chest_6": "Komoda 6 szuflad (rozmiar Malm)", + "pack:nextfloor.ikea:malm_chest_4": "Komoda 4 szuflady (rozmiar Malm)", + "pack:nextfloor.ikea:pax_100": "Szafa 100x236 (rozmiar Pax)", + "pack:nextfloor.ikea:pax_150": "Szafa 150x236 (rozmiar Pax)", + "pack:nextfloor.ikea:poang": "Fotel (rozmiar Poäng)", + "pack:nextfloor.ikea:ektorp_2": "Sofa 2-osobowa (rozmiar Ektorp)", + "pack:nextfloor.ikea:ektorp_3": "Sofa 3-osobowa (rozmiar Ektorp)", + "pack:nextfloor.ikea:bekant": "Biurko 160x80 (rozmiar Bekant)", + "pack:nextfloor.ikea:alex": "Kontener z szufladami (rozmiar Alex)", + "pack:nextfloor.ikea:besta_tv": "Szafka RTV 180x42 (rozmiar Bestå)", + "pack:nextfloor.ikea:ivar": "Regał sosnowy 89x179 (rozmiar Ivar)", + "packname:nextfloor.kino": "Kino domowe i gaming", + "pack:nextfloor.kino:projection_screen": "Ekran projekcyjny", + "pack:nextfloor.kino:projector": "Projektor", + "pack:nextfloor.kino:floor_speaker": "Kolumna podłogowa", + "pack:nextfloor.kino:subwoofer": "Subwoofer", + "pack:nextfloor.kino:soundbar": "Soundbar", + "pack:nextfloor.kino:gaming_desk": "Biurko gamingowe", + "pack:nextfloor.kino:gaming_chair": "Fotel gamingowy", + "pack:nextfloor.kino:game_console": "Konsola do gier", + "pack:nextfloor.kino:arcade": "Automat arcade", + "pack:nextfloor.kino:media_wall": "Ściana multimedialna z TV", + "pack:nextfloor.kino:media_rack": "Szafka multimedialna", + "packname:nextfloor.kueche": "Kuchnia – dodatki", + "pack:nextfloor.kueche:coffee_machine": "Ekspres do kawy", + "pack:nextfloor.kueche:microwave": "Mikrofalówka", + "pack:nextfloor.kueche:hood_island": "Okap wyspowy", + "pack:nextfloor.kueche:wine_fridge": "Chłodziarka do wina", + "pack:nextfloor.kueche:stand_mixer": "Robot planetarny", + "pack:nextfloor.kueche:toaster": "Toster", + "pack:nextfloor.kueche:kettle": "Czajnik", + "pack:nextfloor.kueche:long_dining_table": "Długi stół jadalny", + "pack:nextfloor.kueche:bar_cart": "Barek na kółkach", + "pack:nextfloor.kueche:trash_station": "Segregacja odpadów", + "packname:nextfloor.schlafen": "Spanie i dzieci", + "pack:nextfloor.schlafen:boxspring": "Łóżko kontynentalne", + "pack:nextfloor.schlafen:baby_crib": "Łóżeczko", + "pack:nextfloor.schlafen:changing_table": "Przewijak", + "pack:nextfloor.schlafen:vanity_table": "Toaletka", + "pack:nextfloor.schlafen:clothes_rail": "Wieszak na ubrania", + "pack:nextfloor.schlafen:loft_bed_desk": "Łóżko na antresoli z biurkiem", + "pack:nextfloor.schlafen:toy_box": "Skrzynia na zabawki", + "packname:nextfloor.technik": "Biuro i homelab", + "pack:nextfloor.technik:standing_desk": "Biurko z regulacją wysokości", + "pack:nextfloor.technik:server_rack": "Szafa serwerowa (19 cali)", + "pack:nextfloor.technik:nas": "NAS", + "pack:nextfloor.technik:printer_3d": "Drukarka 3D", + "pack:nextfloor.technik:office_printer": "Drukarka", + "pack:nextfloor.technik:router": "Router / punkt dostępowy", + "pack:nextfloor.technik:tower_pc": "Komputer typu tower", + "pack:nextfloor.technik:filing_cabinet": "Kontener z szufladami", + "packname:nextfloor.treppen": "Schody i balustrady", + "pack:nextfloor.treppen:stairs_straight": "Schody proste", + "pack:nextfloor.treppen:stairs_l": "Schody L ze spocznikiem", + "pack:nextfloor.treppen:stairs_u": "Schody U", + "pack:nextfloor.treppen:stairs_spiral": "Schody kręcone", + "pack:nextfloor.treppen:stairs_compact": "Schody oszczędzające miejsce", + "pack:nextfloor.treppen:landing": "Spocznik", + "pack:nextfloor.treppen:steps_outdoor": "Schody zewnętrzne", + "pack:nextfloor.treppen:rail_metal": "Balustrada metalowa", + "pack:nextfloor.treppen:rail_glass": "Balustrada szklana", + "pack:nextfloor.treppen:rail_wood": "Balustrada drewniana", + "pack:nextfloor.treppen:stairs_floating": "Schody wspornikowe", + "pack:nextfloor.treppen:stairs_u_winder": "Otwarte schody U z zabiegami", + "pack:nextfloor.treppen:rail_corner": "Balustrada narożna", + "packname:nextfloor.werkstatt": "Garaż i warsztat", + "pack:nextfloor.werkstatt:workbench": "Stół warsztatowy", + "pack:nextfloor.werkstatt:tool_cabinet": "Szafa narzędziowa", + "pack:nextfloor.werkstatt:tool_chest": "Wózek narzędziowy", + "pack:nextfloor.werkstatt:shelf_rack": "Regał magazynowy", + "pack:nextfloor.werkstatt:tyre_stack": "Stos opon", + "pack:nextfloor.werkstatt:drill_press": "Wiertarka kolumnowa", + "pack:nextfloor.werkstatt:compressor": "Kompresor", + "pack:nextfloor.werkstatt:bike_stand": "Stojak na rower", + "pack:nextfloor.werkstatt:paint_cabinet": "Szafa na farby", + "pack:nextfloor.werkstatt:tool_wall": "Ściana narzędziowa", + "pack:nextfloor.werkstatt:heavy_shelf": "Regał ciężki", + "pack:nextfloor.werkstatt:chest_freezer_garage": "Zamrażarka skrzyniowa", + "pack:nextfloor.werkstatt:tyre_rack": "Stojak na opony", + "pack:nextfloor.werkstatt:lawn_mower": "Kosiarka", + "pack:nextfloor.werkstatt:bike_stand_2": "Stojak z 2 rowerami", + "pack:nextfloor.werkstatt:workshop_light": "Lampa warsztatowa", + "pack:nextfloor.werkstatt:garage_opener": "Napęd bramy garażowej", + "pack:nextfloor.werkstatt:wallbox_holder": "Wallbox z uchwytem na kabel", + "pack:nextfloor.werkstatt:wall_bike_holder": "Ścienny uchwyt na rowery (2)", + "pack:nextfloor.werkstatt:workshop_vacuum": "Odkurzacz warsztatowy", + "pack:nextfloor.werkstatt:workshop_cabinet": "Szafa warsztatowa", + "pack:nextfloor.werkstatt:printer_enclosed": "Zamknięta drukarka 3D", + "packname:nextfloor.wohnen": "Mieszkanie i zwierzęta", + "pack:nextfloor.wohnen:corner_sofa": "Narożnik (w kształcie L)", + "pack:nextfloor.wohnen:bean_bag": "Pufa sako", + "pack:nextfloor.wohnen:fireplace": "Kominek", + "pack:nextfloor.wohnen:bookcase_wall": "Regał ścienny", + "pack:nextfloor.wohnen:piano": "Pianino", + "pack:nextfloor.wohnen:aquarium": "Akwarium", + "pack:nextfloor.wohnen:cat_tree": "Drapak", + "pack:nextfloor.wohnen:dog_bed": "Legowisko dla psa", + "pack:nextfloor.wohnen:hanging_chair": "Fotel wiszący", + "pack:nextfloor.wohnen:display_cabinet": "Witryna", + "pack:nextfloor.wohnen:high_table": "Stół barowy", + "pack:nextfloor.wohnen:floor_mirror": "Lustro stojące", + "furn_tap": "Dotknięcie elementu", + "furn_tap_default": "Jak zwykle", + "furn_tap_hint": "Własna akcja jak własne przyciski menu gwiazdki, np. okno browser_mod z twoją kartą.", + "furn_show_when": "Pokazuj tylko, gdy …", + "furn_show_when_state": "… jest w stanie (puste = włączone)", + "furn_show_when_invert": "Odwrotnie: pokazuj, gdy tak nie jest", + "furn_show_when_hint": "Sezonowe dekoracje, które stoją tylko w grudniu: pomocnik (input_boolean), kalendarz lub czujnik decyduje, czy mebel pojawi się w 3D. Kilka stanów oddziel przecinkami. Edytor zawsze go pokazuje.", + "picture_upload": "Prześlij zdjęcie", + "picture_replace": "Prześlij inne zdjęcie", + "picture_stored": "Zapisano własne zdjęcie.", + "picture_url": "… lub adres obrazu", + "picture_entity": "… lub obraz encji", + "picture_border": "Passe-partout (%)", + "picture_fit": "Zdjęcie", + "picture_fit_cover": "wypełnia ramkę", + "picture_fit_contain": "widoczne w całości", + "picture_hint": "Twoje zdjęcie w ramce, w 3D i na tablecie ściennym. Przesłane zdjęcia są zapisywane z planem w mniejszym rozmiarze; encja obrazu (zdjęcie dnia) lub kamera pokazuje swój bieżący obraz.", + "card_tap_in_room": "Przełączaj urządzenia tylko w otwartym pomieszczeniu", + "card_tap_in_room_hint": "W widoku domu i piętra dotknięcie otwiera piętro lub pomieszczenie, także na urządzeniu lub jego symbolu. W otwartym pomieszczeniu przełącza urządzenie. Długie naciśnięcie zawsze otwiera jego menu lub szczegóły.", + "card_markers_outside": "Wybierz symbole poza otwartym pomieszczeniem", + "card_markers_outside_hint": "W domu, na piętrze i w innych pomieszczeniach tylko zaznaczone rodzaje; w otwartym pomieszczeniu wszystkie, jak ustawiono wyżej. \"Zawsze\" i \"Nigdy\" przy urządzeniu mają pierwszeństwo.", + "marker_kind_light": "Światła", + "marker_kind_cover": "Rolety", + "marker_kind_climate": "Ogrzewanie", + "marker_kind_media": "Multimedia", + "marker_kind_switch": "Przełączniki", + "marker_kind_fan": "Wentylatory", + "marker_kind_lock": "Zamki", + "marker_kind_binary": "Kontaktrony i czujki", + "marker_kind_sensor": "Czujniki", + "marker_kind_tap": "Meble z akcją", + "marker_kind_other": "Inne", + "floor_copy": "Duplikuj piętro", + "floor_copy_hint": "Kopia trafia na górę domu ze wszystkimi pomieszczeniami, ścianami, drzwiami i oknami. Pomieszczenia i piętro tracą powiązanie z Home Assistant, meble swoje encje; urządzenia energetyczne zostają na starym piętrze.", + "floor_copy_furniture": "Kopiuj meble", + "floor_copy_devices": "Kopiuj znaczniki urządzeń", + "floor_copy_devices_hint": "Ta sama encja pojawi się wtedy na obu piętrach.", + "floor_copy_outdoor": "Kopiuj tereny zewnętrzne", + "floor_copy_make": "Utwórz kopię", + "floor_copy_name": "{name} (kopia)", + "furn_to_floor": "Przenieś na piętro", + "furn_to_floor_hint": "Mebel trafia w to samo miejsce na wybranym piętrze.", + "arc": "Łuk", + "arc_hint": "Wygina ścianę w łuk. Pomieszczenie dzielące tę ścianę wygina się razem z nią, drzwi i okna przesuwają się; Cofnij usuwa łuk.", + "arc_bulge": "Wygięcie (m)", + "arc_bulge_hint": "Jak bardzo środek ściany się wygina: dodatnio na zewnątrz, ujemnie do pomieszczenia.", + "arc_apply": "Wygnij", + "arc_too_wide": "Drzwi lub okno w tej ścianie są za szerokie dla tego łuku. Spłaszcz łuk albo zwęż otwór.", + "time_of_day": "Pora dnia", + "time_of_day_hint": "Pokazuje słońce, światło, cienie i wygląd o innej porze dzisiejszego dnia. Dotknij ponownie, aby wrócić do teraz.", + "menu_open": "Menu otwarte", + "menu_open_hint": "Menu gwiazdki z ulubionymi i własnymi przyciskami jest na tym urządzeniu otwarte od początku i większe – dla tabletu ściennego, który głównie włącza sceny.", + "keep_camera": "Zachowaj kamerę", + "keep_camera_hint": "Przy zmianie piętra kamera zostaje po tej samej stronie, na tej samej wysokości i odległości, zamiast kadrować nowe piętro od strony startowej.", + "view_zoom": "Powiększenie", + "view_zoom_hint": "Jak blisko podchodzą dopasowane widoki – na małych tabletach dom wygląda na większy.", + "stair_shape": "Kształt", + "stair_shape_straight": "Prosta", + "stair_shape_quarter": "Zabiegowa ćwierćobrotowa", + "stair_shape_l": "W kształcie L z podestem", + "stair_shape_half": "Zabiegowa półobrotowa", + "stair_shape_u": "W kształcie U z podestem", + "stair_shape_spiral": "Kręcone", + "stair_turn": "Kierunek skrętu (wchodząc)", + "stair_turn_left": "W lewo", + "stair_turn_right": "W prawo", + "stair_build": "Konstrukcja", + "stair_build_solid": "Masywne (beton)", + "stair_build_stringer": "Policzkowe", + "stair_build_mono": "Na belce środkowej", + "stair_build_cantilever": "Wspornikowe (wiszące)", + "stair_risers": "Podstopnice", + "stair_steps": "Liczba stopni", + "stair_run_width": "Szerokość biegu (m)", + "stair_landing_after": "Stopnie do spocznika", + "stair_landing_hint": "Spocznik jest {h} cm nad podłogą; pozostałe stopnie są za nim.", + "stair_rail": "Balustrada", + "stair_rail_none": "Brak", + "stair_rail_left": "Lewa", + "stair_rail_right": "Prawa", + "stair_rail_both": "Obustronna", + "stair_down": "Prowadzi w dół", + "stair_down_hint": "Schody zaczynają się na tym piętrze i prowadzą w dół, na przykład do piwnicy, której nie trzeba rysować. Otwierają podłogę tego piętra.", + "stair_measures": "{steps} stopni po {rise} cm · szerokość stopnia {going} cm · krok {measure} cm", + "stair_uncomfortable": "niewygodne (krok 59–65 cm, wysokość stopnia najwyżej 21 cm)", + "stair_up_note": "Schody zaczynają się przy zaznaczonej przedniej krawędzi. Strop nad nimi otwiera się tylko tam, gdzie nad stopniami zostaje mniej niż 2,2 m prześwitu.", + "stair_down_note": "Wchodzi się na schody przy zaznaczonej przedniej krawędzi i schodzi w dół. Plan rysuje je przerywaną linią; to piętro otwiera się nad stopniami.", + "stair_upgrade": "Ustaw kształt", + "stair_upgrade_hint": "Zmienia je w schody z kształtem (zabiegowe, L, U, kręcone), konstrukcją, balustradą i liczbą stopni.", + "tool_stairs": "Schody", + "hint_stairs": "Przeciągnij tam, gdzie mają stać schody – biegną wzdłuż dłuższego boku; potem po prawej ustaw kształt, kierunek i konstrukcję", + "stair_opening": "Otwór w stropie", + "stair_opening_headroom": "Według prześwitu (tylko gdzie trzeba)", + "stair_opening_full": "Nad całymi schodami", + "stair_opening_none": "Brak (właz, zamknięta klatka)", + "stair_opening_hint": "Jak bardzo schody otwierają strop, do którego sięgają: piętro wyżej albo własne piętro przy schodach w dół. Według prześwitu otwiera tylko nad stopniami, nad którymi zostaje mniej niż 2,2 m.", + "stair_up_note_plain": "Schody zaczynają się przy zaznaczonej przedniej krawędzi i wznoszą się do tyłu." +} diff --git a/custom_components/nextfloor/frontend/lang/pt.json b/custom_components/nextfloor/frontend/lang/pt.json new file mode 100644 index 0000000..4caddaa --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/pt.json @@ -0,0 +1,2763 @@ +{ + "view": "3D", + "editor": "Editor", + "all_floors": "Todos os pisos", + "outside_area": "Exterior", + "outside_area_hint": "Todos os dispositivos lá fora num relance: no jardim, fora das divisões e o que pertence ao exterior (por exemplo, a estação meteorológica no telhado).", + "device_outside": "Pertence ao exterior", + "device_outside_hint": "O dispositivo não conta para a divisão por baixo (uma estação meteorológica no telhado) e aparece no painel Exterior.", + "no_building": "Ainda não há planta.", + "no_building_admin": "Ainda não há planta. Desenhe o seu primeiro piso no editor.", + "no_rooms_admin": "Os andares existem, mas ainda não há nenhuma divisão. Só paredes não chegam: desenhe pelo menos uma divisão no editor com «Retângulo» ou «Forma livre».", + "open_editor": "Abrir editor", + "loading": "A carregar …", + "load_error": "Falha ao carregar", + "saving": "A guardar …", + "saved": "Guardado", + "save_error": "Falha ao guardar", + "save_failed_detail": "Falha ao guardar: {error}. As suas alterações ficam guardadas neste navegador.", + "needs_restart": "Está instalada uma nova versão do NextFloor ({frontend}), mas o Home Assistant ainda executa {version}. Reinicie o Home Assistant; até lá, guardar pode falhar.", + "needs_reload": "Esta página ainda mostra o NextFloor {frontend}, o Home Assistant já tem {backend}. Recarregue a página; na app companion: Definições → App companion → Repor cache do frontend.", + "reload_page": "Recarregar", + "needs_restart_old": "Está instalada uma nova versão do NextFloor, mas o Home Assistant ainda executa uma mais antiga. Reinicie o Home Assistant; até lá, guardar falha.", + "draft_found": "Encontradas alterações não guardadas de {time}.", + "draft_restore": "Restaurar e guardar", + "draft_discard": "Descartar", + "walls_auto": "Paredes altas", + "walls_cut": "Corte", + "walls_slope": "Inclinado", + "walls_slope_hint": "Paredes cortadas em rampa: meia altura à frente, altura total atrás, como uma casa de bonecas; roda com a câmara", + "walls_solid": "Maciço", + "walls_solid_hint": "Paredes maciças nas suas cores em vez de vidro (cores: editor → definições, por divisão na divisão)", + "wall_paint_outside": "Cor da parede exterior", + "wall_paint_inside": "Cor da parede interior", + "wall_paint_room": "Cor da parede interior (esta divisão)", + "wall_paint_hint": "Usada na vista 3D «Maciço».", + "wall_paint_default": "Predefinição", + "card_solid_walls": "Paredes maciças (nas suas cores)", + "reset_view": "Visão geral", + "back": "Voltar", + "floor": "Piso", + "floors": "Pisos", + "add_floor": "Adicionar piso", + "floor_from_ha": "Pisos do Home Assistant:", + "floor_empty": "Piso vazio", + "level": "Nível {n}", + "ha_floor": "Piso no Home Assistant", + "floor_layer": "Camada (pode mostrar e ocultar)", + "floor_power": "Contador do piso (potência)", + "floor_power_hint": "Um sensor de potência só para este piso (um subcontador, um apartamento). O valor aparece na etiqueta do piso e, na vista deste piso, no cartão da casa com a sua parte do consumo.", + "floor_power_share": "{n} % da casa", + "living_area": "Área útil {living}", + "room_living": "Conta como área útil", + "living_area_none": "Sem área útil · piso {floor}", + "living_area_low": "Área útil {living} (piso {floor}, dos quais {low} abaixo de 2 m)", + "living_area_hint": "Calculado como a Wohnflächenverordnung alemã: o piso dentro das paredes, por inteiro a partir de 2 m de pé-direito, metade entre 1 e 2 m (sob inclinações), nada abaixo de 1 m. Um valor indicativo, não uma medição.", + "living_area_floor": "Área útil: {floor}", + "living_area_floor_house": "Área útil deste piso: {floor} · casa inteira: {house}", + "print_plan": "Imprimir planta / PDF", + "print_plan_hint": "Cada piso como planta limpa com medidas e áreas, e uma tabela de áreas – para imprimir ou guardar como PDF na janela de impressão.", + "print_title": "Planta", + "print_room": "Divisão", + "print_floor_area": "Área do piso", + "print_living": "Área útil", + "print_low": "abaixo de 2 m", + "print_total": "Total", + "print_blocked": "A janela de impressão foi bloqueada – permite pop-ups para o Home Assistant.", + "check_open": "Verificar a planta", + "note": "Nota", + "note_add": "Nota aqui", + "note_text": "Texto", + "note_placeholder": "p. ex. «trocar o filtro» ou «fusível 12»", + "note_due": "Prazo", + "note_due_hint": "A partir desse dia o marcador fica laranja.", + "note_is_due": "Esta nota está no prazo.", + "keys_title": "Teclas do editor", + "keys_undo": "Anular", + "keys_redo": "Refazer", + "keys_duplicate": "Duplicar a divisão", + "keys_delete": "Eliminar a seleção", + "keys_nudge": "Mover a seleção um passo da grelha", + "keys_nudge_10": "… 10 cm", + "keys_nudge_1": "… 1 cm", + "keys_rotate": "Rodar o móvel 90° (Shift: para trás)", + "keys_lock": "Fixar ou soltar um móvel, dispositivo ou secção de telhado", + "keys_close_shape": "Fechar a forma livre", + "keys_escape": "Cancelar, sair da ferramenta, limpar a seleção", + "keys_straight": "Ao desenhar: linhas retas", + "keys_sheet": "Esta lista", + "tour_title": "Primeiros passos", + "tour_1_title": "Desenhar as divisões", + "tour_1": "Desenha as divisões com «{rect}» ou «{free}»; as paredes surgem sozinhas. Dá a cada divisão a sua área do Home Assistant – assim o NextFloor encontra os seus dispositivos. Com áreas já criadas, «{rooms}» no formulário do piso cria-as de uma vez.", + "tour_2_title": "Portas e janelas", + "tour_2": "«{opening}» coloca-as numa parede. Liga o contacto ou o estore – em 3D abrem e fecham com ele, e as janelas abertas avisam.", + "tour_3_title": "Móveis e dispositivos", + "tour_3": "«{furniture}» abre a biblioteca – ou constrói as tuas peças na 🛠️ oficina. Escolhe uma divisão e por baixo aparecem os dispositivos da sua área, prontos a colocar; os candeeiros brilham na cor da sua luz.", + "tour_4_title": "Ver e verificar", + "tour_4": "«{split}» mostra a tua casa enquanto desenhas; em cima mudas para a vista 3D. «{check}» lista o que ainda falta – e ? mostra as teclas a qualquer momento.", + "tour_next": "Seguinte", + "tour_back": "Voltar", + "tour_done": "Vamos lá", + "tour_skip": "Saltar", + "check_open_hint": "Mostra o que falta ou está errado na planta, com uma correção num toque.", + "check_title": "Verificação da planta", + "check_all_good": "Tudo certo – nada encontrado.", + "check_hint": "{n} pontos encontrados. Os botões azuis alteram a planta (anular funciona como sempre), os outros mostram o local.", + "check_room_no_area": "«{room}» não tem área do Home Assistant: os seus dispositivos não são encontrados.", + "check_room_no_area_named": "«{room}» não tem área – a área livre «{area}» tem o mesmo nome.", + "check_areas_unplaced": "{n} áreas deste piso ainda não têm divisão: {names}", + "check_devices_unplaced": "«{room}»: {n} dispositivos da área ainda não estão na planta.", + "check_rooms_overlap": "«{a}» e «{b}» sobrepõem-se.", + "check_opening_off_wall": "Uma porta ou janela em «{room}» não está numa parede.", + "check_entity_missing": "{n} marcadores apontam para entidades que o Home Assistant já não conhece ({ids}).", + "check_furniture_entity_missing": "Um móvel está ligado a {id} – essa entidade já não existe.", + "check_battery_low": "Bateria fraca: {name} ({level} %)", + "battery_low_n": "Bateria fraca: {names}", + "check_standby": "{name} consome {w} W desligado – cerca de {cost} por ano.", + "check_fix_show": "Mostrar", + "check_fix_set_area": "Associar «{area}»", + "check_fix_add_rooms": "Adicionar divisões", + "check_fix_place": "Colocar {n}", + "check_fix_remove": "Remover {n}", + "floor_layer_hint": "Este piso não é um andar mas uma camada – todas as árvores ou a decoração. A vista 3D mostra em cima um olho que a mostra ou oculta em cada dispositivo.", + "no_ha_floor": "– nenhum –", + "area_rooms": "Adicionar divisões a partir das áreas do HA ({n})", + "area_rooms_hint": "Adiciona uma divisão (4 × 3 m) por cada área deste piso; depois arraste-a para o lugar e ajuste os cantos", + "floor_name": "Nome", + "elevation": "Cota (m)", + "floor_shift": "Deslocar o piso (m)", + "floor_shift_apply": "Deslocar", + "floor_shift_hint": "Desloca em X e Z todas as divisões, móveis, dispositivos, áreas exteriores, paredes livres e a imagem de fundo deste piso. As águas do telhado ficam.", + "height": "Pé-direito (m)", + "cut_height": "Altura de corte (m)", + "delete_floor": "Eliminar piso", + "delete_floor_confirm": "Eliminar o piso «{name}» com todas as suas divisões?", + "move_up": "Subir", + "move_down": "Descer", + "default_floor": "Rés-do-chão", + "new_floor": "Piso {n}", + "tool_select": "Selecionar", + "tool_rect": "Retângulo", + "tool_polygon": "Forma livre", + "undo": "Anular", + "redo": "Refazer", + "fit": "Mostrar tudo", + "room": "Divisão", + "rooms": "Divisões", + "room_name": "Nome", + "area": "Área", + "no_area": "Sem área", + "sub_area_add": "+ Área dentro da divisão", + "sub_area_hint": "Uma parte da divisão com área própria no Home Assistant mas sem paredes – um canto de leitura, uma estante, uma kitchenette na sala. Os seus dispositivos e sensores pertencem a esta divisão.", + "material": "Pavimento", + "x": "X (m)", + "z": "Y (m)", + "width": "Largura (m)", + "depth": "Profundidade (m)", + "points": "Cantos", + "delete_point": "Eliminar canto", + "duplicate": "Duplicar", + "delete": "Eliminar", + "new_room": "Divisão {n}", + "settings": "Definições", + "pendant_shape": "Forma", + "pendant_shade": "Abajur", + "paint_colour": "Cor da tinta", + "pendant_globe": "Globo", + "pendant_cone": "Cone", + "pendant_drum": "Tambor", + "sofa_shape": "Forma", + "sofa_straight": "Reto", + "sofa_l": "Em L (espelhar: outro lado)", + "sofa_u": "Em U", + "pkg_open": "Mobilar …", + "pkg_hint": "Os móveis encostam às paredes da divisão; os candeeiros ligam-se às luzes da área. Ajuste cada elemento depois; Ctrl+Z desfaz tudo.", + "pkg_done": "{n} elementos colocados; Ctrl+Z desfaz.", + "pkg_kitchen_row": "Cozinha linear", + "pkg_kitchen_row_desc": "Linha na parede do fundo com frigorífico, forno, lava-loiça, máquina de lavar loiça e placa, armário superior, mesa de jantar com candeeiro suspenso", + "pkg_kitchen_l": "Cozinha em L", + "pkg_kitchen_l_desc": "Linhas ao fundo e à esquerda, ilha com bancos altos", + "pkg_bath": "Casa de banho", + "pkg_bath_desc": "Lavatório, sanita, banheira, máquina de lavar roupa, foco embutido", + "pkg_bedroom": "Quarto", + "pkg_bedroom_desc": "Cama de casal com duas mesas de cabeceira, roupeiro, cómoda, candeeiro de teto", + "pkg_living": "Sala de estar", + "pkg_living_desc": "Móvel de TV, sofá, mesa de centro, tapete, poltrona, estante, candeeiro de pé, planta", + "pkg_dining": "Sala de jantar", + "pkg_dining_desc": "Mesa com quatro cadeiras, aparador, candeeiro suspenso", + "pkg_office": "Escritório", + "pkg_office_desc": "Secretária com cadeira de escritório, duas estantes, candeeiro de teto", + "pkg_kids": "Quarto de criança", + "pkg_kids_desc": "Cama de solteiro, secretária, estante, tapete", + "pkg_hall": "Hall", + "pkg_hall_desc": "Bengaleiro, dois focos embutidos", + "spots_place": "Colocar focos", + "spots_type": "Candeeiro", + "spots_cols": "Colunas (esquerda–direita)", + "spots_rows": "Filas (frente–trás)", + "spots_add": "Colocar {n} candeeiros", + "spots_placed": "{n} candeeiros colocados.", + "spots_hint": "Todos os candeeiros seguem a luz escolhida (p. ex. focos num só regulador). Depois, cada um pode ser movido e ligado a outra luz como qualquer móvel.", + "cancel": "Cancelar", + "backup": "Cópia de segurança", + "backup_history": "Pontos de restauro", + "share_view": "Partilhar uma vista", + "share_view_hint": "Guarda a casa como um pequeno ficheiro que abre em qualquer navegador sem Home Assistant (através da demo online do NextFloor) – para a mostrar à família ou a um projetista. Sem dispositivos nem entidades, como um modelo.", + "share_view_title": "A nossa casa no NextFloor", + "share_view_needs_js": "Esta página precisa de JavaScript e de ligação à internet.", + "share_view_file": "vista", + "share_view_done": "Vista guardada – abre o ficheiro num navegador ou partilha-o.", + "version_save": "Guardar este estado …", + "version_save_hint": "Guarda a planta com um nome («antes da obra»). Os estados com nome ficam quando os pontos automáticos desaparecem.", + "version_name_prompt": "Nome deste estado (p. ex. «antes da obra»):", + "version_saved": "Estado «{name}» guardado.", + "version_compare": "Comparar", + "version_delete_confirm": "Eliminar «{name}»?", + "version_same": "Sem diferenças em relação à planta.", + "version_diff_n": "{n} diferenças em relação à planta atual:", + "diff_floor_added": "Piso «{name}» adicionado", + "diff_floor_removed": "Piso «{name}» removido", + "diff_room_added": "Divisão «{name}» adicionada", + "diff_room_removed": "Divisão «{name}» removida", + "diff_room_renamed": "«{detail}» chama-se agora «{name}»", + "diff_room_reshaped": "«{name}» alterada ({detail} m²)", + "diff_opening_added": "{name} adicionado/a ({detail})", + "diff_opening_removed": "{name} removido/a ({detail})", + "diff_furniture_added": "{name} adicionado", + "diff_furniture_removed": "{name} removido", + "diff_furniture_moved": "{name} movido ou alterado", + "diff_device_added": "Dispositivo {name} colocado", + "diff_device_removed": "Dispositivo {name} removido", + "diff_device_moved": "Dispositivo {name} movido", + "backup_none": "Ainda nenhum. Durante a edição guarda-se um ponto de restauro no máximo a cada 10 minutos.", + "backup_summary": "{rooms} divisões, {furniture} elementos", + "backup_restore": "Restaurar", + "backup_restore_confirm": "Restaurar o estado de {time}? O estado atual fica guardado como ponto de restauro.", + "backup_restored": "Restaurado.", + "backup_file": "Ficheiro", + "backup_export": "Exportar", + "backup_export_share": "Partilhar como modelo", + "backup_export_share_hint": "Sem áreas, dispositivos, sensores e imagens, para passar a outros.", + "backup_import": "Importar …", + "backup_import_confirm": "Substituir toda a planta pelo ficheiro? O estado atual fica guardado como ponto de restauro.", + "backup_import_error": "O ficheiro não é uma planta do NextFloor ({error}).", + "backup_imported": "Importado.", + "backup_hint": "As imagens de fundo não fazem parte do ficheiro.", + "backup_full": "Cópia de segurança completa", + "backup_full_export": "Guardar tudo (planta, imagens, pacotes)", + "backup_full_import": "Restaurar uma cópia completa …", + "backup_full_hint": "Um ficheiro com a planta, todas as imagens de fundo e de ecrã e os pacotes instalados. Ao restaurar, cada pacote é verificado de novo; a chave de licença não está incluída.", + "backup_full_confirm": "Substituir a planta, as imagens e os pacotes pela cópia? O estado atual fica como ponto de restauro.", + "backup_full_not_backup": "Isto não é uma cópia de segurança completa do NextFloor.", + "backup_full_restored": "Cópia restaurada: {packs} pacotes, {pictures} imagens.", + "backup_full_skipped": "Ignorados (não foi possível ler): {packs}.", + "export_name_full": "completa", + "device_confirm": "Perguntar antes de comutar", + "device_confirm_hint": "Um toque em 3D, o menu rápido e o painel da divisão perguntam antes. Um toque duplo na divisão exclui este dispositivo.", + "cover_confirm_hint": "Abrir, fechar e posições perguntam antes no menu rápido e no painel da divisão, e deslizar no marcador já não move o estore (roda a vista). Parar nunca pergunta.", + "blind_kind": "Tipo de estore", + "blind_roller": "Estore de enrolar exterior", + "blind_venetian": "Estore veneziano de lâminas", + "blind_inside": "Estore interior", + "cover2_entity": "Segundo estore (metade direita)", + "cover_my": "Posição favorita «My» (%, 0 = nenhuma)", + "cover_my_go": "Para a posição favorita ({p} %)", + "blind_hint": "Um estore veneziano roda as lâminas em 3D com a inclinação do estore; um estore interior fica atrás do vidro. Uma janela larga pode ter um segundo estore para a metade direita. A posição favorita aparece como «My» no menu rápido: um estore com posições vai até lá, um motor Somfy RTS sem retorno vai para o seu próprio My com Parar.", + "confirm_switch": "Comutar mesmo {name}?", + "lock_confirm_unlock": "Desbloquear mesmo {name}?", + "gang_switch_one": "Interruptores", + "furn_cover_entity": "Move-se com", + "furn_cover_hint": "A cortina, tela, toldo ou portão segue esta entidade de cobertura (estore, cortina, toldo, portão) e move-se com ela. Um toque abre o menu (subir, parar, descer).", + "furn_cover_inverted": "Inverter o sentido", + "furn_cover_inverted_hint": "Para um toldo ou cortina que se move ao contrário no plano: aberto aparece fechado e vice-versa.", + "gang_switch": "O botão {n} comuta", + "gang_socket_one": "Tomada alimentada por", + "gang_socket": "Tomada {n} alimentada por", + "gang_switch_hint": "Um botão brilha enquanto a sua luz está acesa (na sua cor). Um toque comuta-o; com vários botões, um pequeno menu pergunta qual. A mesma entidade pode estar em vários interruptores.", + "gang_socket_hint": "Uma tomada brilha a verde enquanto o seu interruptor está ligado, mais quanto mais consome. Um toque comuta-a; com várias, um pequeno menu pergunta qual.", + "lock_confirm_lock": "Trancar {name}?", + "opening_lock": "Fechadura inteligente", + "opening_lock_hint": "Um toque na porta tranca-a ou destranca-a (perguntando sempre antes). Enquanto está destrancada, a sua aresta brilha.", + "split_handle_hint": "Arrastar: largura da planta e da vista 3D", + "wall_exterior": "Parede exterior (m)", + "wall_interior": "Parede interior (m)", + "grid": "Grelha (m)", + "units": "Mostrar comprimentos em", + "units_metric": "Metros", + "units_imperial": "Pés e polegadas", + "units_hint": "Como comprimentos e áreas aparecem na planta, nos formulários e na vista de parede. As entradas continuam em metros.", + "background": "Modelo (imagem da planta)", + "background_upload": "Escolher imagem …", + "background_width": "Largura na planta (m)", + "background_opacity": "Opacidade", + "background_rotation": "Rotação (°)", + "background_edit": "Mover, escalar e rodar", + "background_edit_done": "Concluído", + "background_edit_hint": "Com o modo ativo: arrastar a imagem move-a, a pega em baixo à direita escala-a. Ajuste primeiro a escala e depois rode-a.", + "background_remove": "Remover modelo", + "hint_select": "Toque numa divisão para a selecionar · arraste os cantos · «+» numa aresta insere um canto · as setas deslocam · Del elimina · Ctrl+Z", + "hint_rect": "Arraste para desenhar um retângulo", + "hint_polygon": "Coloque cantos · toque no primeiro canto ou prima Enter para fechar · Esc cancela", + "hint_empty": "Adicione primeiro um piso.", + "area_m2": "{a} m²", + "overlap_warning": "As divisões sobrepõem-se; aí as paredes ficam incompletas.", + "read_only": "Só os administradores podem editar a planta.", + "side_failed": "Não foi possível mostrar este formulário ({error}). A planta continua utilizável. Por favor, reporta o texto numa issue no GitHub.", + "mat_wood": "Madeira", + "mat_oak": "Carvalho", + "mat_tiles": "Azulejo", + "mat_carpet": "Alcatifa", + "mat_stone": "Pedra", + "mat_concrete": "Betão", + "card_name": "NextFloor", + "card_description": "A sua casa em 3D (néon).", + "stats": "{calls} draw calls · {tris} triângulos", + "stats_fps": "{fps} fps (fotograma mais lento {ms} ms)", + "stats_idle": "Em repouso (0 fps)", + "stats_busy_floors": "pisos", + "stats_busy_openings": "portas/janelas", + "stats_busy_flash": "flash", + "stats_busy_roof": "telhado", + "stats_busy_flow": "fluxo de energia", + "stats_busy_effect": "efeito de cor", + "stats_busy_robot": "robô", + "stats_busy_orbit": "rotação da câmara", + "stats_busy_tint": "tom da divisão", + "stats_low": "nível tablet, rácio de píxeis {r}", + "stats_full": "nível total, rácio de píxeis {r}", + "floors_apart": "Afastados", + "floors_stacked": "Empilhados", + "roof_keep": "Telhado fica", + "roof_keep_hint": "O telhado fica na casa ao aproximar em vez de subir e desvanecer", + "floor_rooms_one": "1 divisão", + "floor_rooms": "{n} divisões", + "quality": "Qualidade", + "quality_auto": "Auto", + "quality_low": "Tablet", + "quality_high": "Alta", + "state_on": "Ligado", + "state_off": "Desligado", + "state_open": "Aberto", + "state_closed": "Fechado", + "state_opening": "A abrir", + "state_closing": "A fechar", + "state_playing": "A reproduzir", + "state_paused": "Em pausa", + "state_idle": "Inativo", + "state_locked": "Trancado", + "state_unlocked": "Destrancado", + "state_detected": "Detetado", + "state_clear": "Livre", + "state_unavailable": "Indisponível", + "state_heat": "Aquecer", + "state_cool": "Arrefecer", + "state_auto": "Auto", + "state_heat_cool": "Aquecer/arrefecer", + "state_dry": "Desumidificar", + "state_fan_only": "Ventilador", + "devices": "Dispositivos", + "devices_none_area": "Ligue a divisão a uma área e os seus dispositivos aparecem aqui.", + "devices_none": "A área não tem dispositivos adequados.", + "devices_place_all_n": "Colocar todos os {n} …", + "devices_place_all_confirm": "Colocar {n} dispositivos na divisão de uma vez? (Ctrl+Z ou «Anular» retira-os todos num passo.)", + "devices_src_area": "Esta área", + "devices_src_other": "Outras áreas", + "devices_src_none": "Sem área", + "panel_hide": "Ocultar do painel da divisão", + "panel_unhide": "Mostrar de novo no painel da divisão", + "panel_state_hide": "Ocultar o estado no painel da divisão (p. ex. uma cobertura que só indica \"unknown\")", + "panel_state_show": "Mostrar de novo o estado no painel da divisão", + "devices_place": "Colocar", + "devices_remove": "Remover", + "devices_hint": "Os dispositivos colocados aparecem em 3D. Arraste-os na planta para os mover.", + "panel_lights": "Luzes", + "panel_covers": "Coberturas", + "panel_climate": "Aquecimento", + "panel_media": "Multimédia", + "panel_switches": "Interruptores", + "panel_sensors": "Sensores", + "panel_scenes": "Cenas e scripts", + "panel_announce": "📢 Anúncio", + "announce_placeholder": "A sua mensagem …", + "announce_send": "Dizer", + "announce_sent": "Dito: «{message}»", + "announce_failed": "O anúncio falhou: {error}", + "announce_phrase_1": "O jantar está pronto!", + "announce_phrase_2": "Hora de dormir!", + "announce_phrase_3": "Desçam, por favor!", + "announce_phrase_4": "Vamos sair já!", + "announce_phrase_5": "O cão precisa de sair!", + "state_recording": "A gravar", + "state_streaming": "Em streaming", + "panel_all_off": "Desligar tudo", + "readable": "Fácil de ler", + "readable_hint": "Mais contraste e texto maior – para tablets de parede e quem lê melhor assim.", + "plain": "Só planta", + "plain_hint": "Mostra só paredes, portas, janelas e escadas, sem móveis. Os dispositivos e os seus pinos ficam.", + "right_back": "Clique direito = voltar", + "right_back_hint": "Um clique curto com o botão direito na vista 3D recua um passo: da divisão para o andar, do andar para a casa (como um toque duplo num espaço vazio). Arrastar com o botão direito continua a mover a vista.", + "stl": "Impressão 3D (STL)", + "stl_hint": "Guarda a casa como ficheiro STL (paredes, pisos, móveis e áreas exteriores de todos os andares) para impressão 3D, à escala 1:100 (um metro passa a 10 mm). Janelas, luzes e telhado não estão incluídos; um slicer repara o ficheiro se for preciso.", + "card_plain": "Só planta", + "card_rooms": "Só estas divisões", + "card_rooms_hint": "O cartão mostra só as divisões marcadas com os seus móveis, dispositivos, portas e janelas (por exemplo para um tablet na cozinha). Nada marcado: a planta toda.", + "card_templates": "Modelos de cartão", + "card_templates_hint": "Configura um cartão do painel uma vez aqui (com as definições do próprio cartão) e indica só o nome em cada tablet: `template: kitchen_tablet`. As alterações chegam a todos os cartões que o usam; o que está no próprio cartão prevalece sobre o modelo.", + "template_name": "Novo modelo (nome)", + "template_add": "Criar modelo", + "template_reload": "Recarregar os ecrãs com este modelo", + "template_reload_all": "Recarregar todos os ecrãs", + "template_use": "No cartão do painel: `template: {name}`", + "card_template": "Modelo de cartão", + "card_template_none": "nenhum (só este cartão)", + "card_readable": "Fácil de ler", + "all_off_n": "Desligar tudo ({n})", + "all_off_hint": "Desliga luzes, interruptores, ventoinhas e multimédia da divisão; pode ser anulado durante dez segundos.", + "all_off_done": "Tudo desligado.", + "all_off_undo": "Anular", + "all_off_floor": "Desligar tudo em {floor} ({n} dispositivos), anular durante dez segundos", + "mood_save": "Guardar ambiente", + "mood_save_hint": "Guarda como as luzes da divisão brilham agora como ambiente – um toque repõe-no depois, «→» leva-o para outra divisão.", + "mood_new": "Ambiente", + "mood_set": "Aplicar este ambiente", + "mood_carry": "Levar para outra divisão", + "panel_all_on": "Ligar tudo", + "view_options": "Vista: qualidade, aspeto, marcadores, FPS", + "panel_all_open": "Subir tudo", + "panel_all_close": "Descer tudo", + "central": "Central: todas as luzes, estores e favoritos", + "central_house": "Casa inteira", + "central_lights": "Luzes", + "central_covers": "Estores", + "central_on": "Ligar", + "central_off": "Desligar", + "central_open": "Subir", + "central_close": "Descer", + "central_sure": "Tem a certeza?", + "central_favorites": "Favoritos", + "central_no_favorites": "Ainda sem favoritos. Defina cenas, scripts e interruptores no editor em \"Favoritos\".", + "card_central": "Estrela com o menu central", + "card_central_hint": "Todas as luzes e estores do piso ou da casa e os favoritos do editor.", + "favorites": "Favoritos", + "favorites_hint": "Cenas, scripts, automatizações, botões e interruptores para o menu central (estrela) da vista 3D: festa, simulação de presença, sombreamento, rega.", + "favorites_add": "Adicionar um favorito", + "favorite_floor": "Em que piso este favorito aparece", + "favorite_all_floors": "Todos os pisos", + "outside_hidden": "Exterior: ocultar dispositivos", + "outside_hidden_hint": "Dispositivos que o painel Exterior não deve mostrar (continuam no plano).", + "outside_hidden_add": "Ocultar um dispositivo", + "room_facts": "Painel da divisão: dados mostrados", + "room_fact_sun": "Horas de sol", + "room_fact_comfort": "Conforto", + "room_fact_air": "Aviso de ventilação", + "room_fact_circuits": "Circuitos", + "background_handles_hint": "A imagem tem agora pegas como um móvel: arrastar move-a, o canto inferior direito escala-a, a pega redonda em cima roda-a (Shift para passos de 15°). Quando encaixar, toque em \"Concluído\" e fica fixa.", + "background_fixed_hint": "A imagem fica fixa, pode desenhar por cima. Para a ajustar, toque em \"Mover, escalar e rodar\".", + "bg_level": "Endireitar", + "bg_level_cancel": "Cancelar endireitar", + "bg_level_first": "Toque no início de uma parede na imagem que deve ficar direita (horizontal ou vertical).", + "bg_level_second": "Agora toque no fim dessa parede; a imagem roda para ajustar.", + "bg_ruler": "Escalar com régua", + "bg_ruler_cancel": "Cancelar a régua", + "bg_ruler_first": "Toque no início de um troço de comprimento conhecido na imagem, p. ex. uma parede cotada.", + "bg_ruler_second": "Agora toque no fim do troço.", + "bg_ruler_length_hint": "Medido na planta: {m} m. Introduza o comprimento real e a imagem é escalada para ajustar.", + "bg_ruler_length": "Comprimento real (m)", + "bg_ruler_apply": "Aplicar a escala", + "thumbs_fold": "Recolher as imagens dos pisos em botões", + "thumbs_show": "Mostrar de novo as imagens dos pisos", + "room_start_view": "Vista como início desta divisão", + "room_start_view_hint": "Ao tocar na divisão em 3D, a câmara voa exatamente para a vista que o painel 3D à direita mostra agora: ângulo, zoom e enquadramento. Ative primeiro 3D ao lado, rode e aproxime a divisão e depois toque.", + "room_start_view_reset": "Remover a vista inicial da divisão (de novo vista de cima)", + "room_start_view_need_pane": "Ative primeiro \"3D ao lado\" e rode e aproxime a divisão como deve abrir.", + "floor_start_view": "Vista como início deste piso", + "floor_start_view_hint": "Este piso abre em 3D como o painel 3D à direita está agora, p. ex. o rés-do-chão pela frente e o piso superior por trás. Ative primeiro 3D ao lado, rode-o e depois toque.", + "floor_start_view_reset": "Remover a vista inicial do piso (de novo como a casa)", + "floor_start_view_need_pane": "Ative primeiro \"3D ao lado\" e rode o piso como deve abrir.", + "ambilight": "Brilho atrás da TV (%)", + "ambilight_hint": "Com que intensidade brilha atrás da TV durante a reprodução. 0 desliga-o (por exemplo, se tiver fitas LED na TV), 100 é a intensidade habitual.", + "sound_rings": "Ondas de som (%)", + "sound_rings_hint": "Tamanho das ondas à volta do altifalante enquanto toca. 0 desliga-as, a imagem e o brilho mantêm-se; 100 é o tamanho habitual. O tamanho também acompanha o volume do altifalante: mais baixo, mais pequeno.", + "glow_scale": "Brilho em 3D (%)", + "light_effects": "Animações de efeitos em 3D", + "light_effects_hint": "Associe apenas nomes de efeito exatos do HA. Efeitos não associados mantêm a cor estática do HA. Não altera nada no Home Assistant.", + "light_effects_enabled": "Permitir animações para este candeeiro", + "light_effect_unmapped": "Não associado (estático)", + "light_effect_add": "Adicionar nome de efeito exato", + "light_effect_name_limit": "O nome exato do efeito deve ter entre 1 e 255 caracteres. Não será encurtado.", + "light_effect_count_limit": "No máximo 100 associações. Remova primeiro uma existente.", + "light_effect_exists": "Este nome de efeito já está associado. A associação existente é mantida.", + "light_animation_none": "Estático", + "light_animation_rainbow": "Arco-íris (substitui a cor)", + "light_animation_pulse": "Pulsar (intensidade)", + "light_animation_flicker": "Cintilar (intensidade)", + "glow_scale_hint": "Com que intensidade o candeeiro brilha em 3D: abaixo de 100 % atenua fitas LED fortes para a divisão não queimar; acima de 100 % faz brilhar mais um candeeiro fraco. Não comuta nada no Home Assistant.", + "vehicle_to_spot": "Transformar em lugar de estacionamento", + "vehicle_to_spot_hint": "Um veículo como móvel simples está sempre lá. Como lugar de estacionamento só aparece enquanto um sensor indica o carro, e é aí que se liga o dispositivo do carro (carga, autonomia, trancamento, climatização).", + "as_furniture": "Mostrar como móvel", + "as_furniture_hint": "Substitui o marcador por um móvel no mesmo sítio, ligado a este dispositivo: uma coluna para um leitor multimédia, um candeeiro para uma luz. Ctrl+Z desfaz.", + "as_furniture_pick": "Escolher móvel …", + "as_device": "Voltar ao marcador do dispositivo", + "as_device_hint": "Substitui o móvel pelo marcador simples do seu dispositivo no mesmo sítio.", + "presets": "Estações e listas (Som)", + "presets_hint": "Mostradas no menu rápido de cada coluna em \"Reproduzir\", junto às fontes do leitor. Para um Echo (Alexa Media Player): escreva SPOTIFY, AMAZON_MUSIC ou TUNEIN e como conteúdo o que diria (\"Rock Antenne\"). Para Sonos, Music Assistant e outros: escreva music ou url com um endereço de stream ou um URI.", + "preset_type": "Tipo", + "preset_type_hint": "media_content_type de play_media, p. ex. music, url, playlist, SPOTIFY, AMAZON_MUSIC, TUNEIN", + "preset_content": "Conteúdo", + "preset_content_hint": "media_content_id: URL de stream, URI (spotify:playlist:…) ou, para a Alexa, uma frase de pesquisa", + "preset_speakers": "Só nestas colunas (nenhuma = em todas)", + "media_play": "Reproduzir", + "media_pause": "Pausa", + "media_previous": "Anterior", + "media_next": "Seguinte", + "media_volume": "Volume", + "media_sources": "Fontes", + "preset_add": "Estação ou lista", + "own_buttons": "Botões próprios", + "own_buttons_hint": "Mostrados no menu central (estrela) abaixo dos favoritos: abrir um caminho de dashboard, mostrar os detalhes de uma entidade, chamar um serviço ou abrir um popup do browser_mod com o seu próprio cartão.", + "own_alerts": "Avisos próprios", + "circuits": "Quadro elétrico", + "circuits_hint": "Os circuitos com as divisões que alimentam. O painel da divisão indica-os e a pesquisa encontra-os («F12»).", + "circuit_name": "Nome", + "circuit_new": "Novo circuito", + "circuit_add": "Adicionar circuito", + "circuit_add_room": "Adicionar divisão", + "own_alerts_hint": "Uma linha na barra de avisos da vista 3D enquanto uma entidade está num estado – «Depósito vazio» do robô, «Máquina de loiça concluída». Vários estados com vírgulas; para números <20 ou >80.", + "own_alert_entity": "Quando …", + "own_alert_state": "… está no estado (vazio = ligado)", + "own_alert_text": "… então este aviso", + "own_alert_color": "Cor", + "own_alert_tap": "Um toque", + "own_alert_tap_info": "abre os detalhes", + "own_alert_tap_toggle": "alterna a entidade", + "own_alert_tap_room": "salta para a divisão", + "own_alert_house": "Toda a casa", + "own_alert_new": "Novo aviso", + "own_alert_add": "Adicionar aviso", + "today": "Hoje", + "today_none": "Nada marcado para hoje.", + "today_calendars": "Calendários para «Hoje»", + "today_calendars_hint": "Os compromissos destes calendários aparecem no canto superior direito da vista 3D no cartão «Hoje», com os contentores recolhidos hoje ou amanhã. Um toque no título recolhe o cartão.", + "own_button_state": "Acende enquanto … está ligado (opcional)", + "own_button_label": "Etiqueta", + "own_button_action": "Ação", + "own_button_new": "Novo botão", + "own_button_add": "Botão próprio", + "own_action_navigate": "Abrir um caminho", + "own_action_more_info": "Detalhes da entidade", + "own_action_service": "Chamar um serviço", + "own_action_fire_dom_event": "fire-dom-event (browser_mod)", + "own_target_navigate": "Caminho", + "own_target_more_info": "Entidade", + "own_target_service": "Serviço (domínio.serviço)", + "own_data": "Dados (JSON)", + "own_data_hint": "Para um serviço os seus dados, para fire-dom-event o conteúdo do evento, p. ex. {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}.", + "own_data_bad": "Não é um objeto JSON válido.", + "panel_no_area": "Esta divisão não está ligada a uma área. Pode ligá-la no editor.", + "panel_empty": "Nenhum dispositivo desta divisão está na planta. No editor, coloque dispositivos ou escolha-os para o painel da divisão com ☆.", + "close": "Fechar", + "panel_fold": "Recolher (a divisão continua visível)", + "panel_unfold": "Abrir de novo", + "brightness": "Brilho", + "color_temp": "Temperatura de cor", + "color": "Cor", + "position": "Posição", + "cover_open": "Abrir", + "cover_stop": "Parar", + "cover_tilt": "Lâminas", + "cover_tilt_open": "Lâminas abertas", + "cover_tilt_close": "Lâminas fechadas", + "cover_close": "Fechar", + "target_temp": "Alvo", + "current_temp": "Atual", + "temp_down": "Mais fresco", + "temp_up": "Mais quente", + "volume": "Volume", + "play_pause": "Reproduzir/pausa", + "previous": "Anterior", + "next": "Seguinte", + "run": "Executar", + "details": "Detalhes", + "hold_hint": "Tocar comuta · toque longo abre os detalhes", + "tool_opening": "Portas e janelas", + "tool_furniture": "Móveis", + "qm_off": "Desligado", + "find": "Pesquisar", + "find_placeholder": "Onde está …? Dispositivo ou divisão", + "find_none": "Nada encontrado", + "swipe_off": "Desligado", + "panel_pin": "Mostrar no painel da divisão", + "panel_unpin": "Não mostrar no painel da divisão", + "devices_panel_hint": "O painel da divisão mostra os dispositivos da planta. ☆ adiciona um dispositivo ao painel sem o colocar.", + "card_section_view": "Vista", + "card_size": "Tamanho", + "card_size_fixed": "Altura fixa", + "card_size_fill": "Preencher o ecrã", + "card_fill_hint": "Funciona melhor numa vista de dashboard do tipo «Painel (cartão único)»: o cartão ocupa então todo o espaço.", + "card_controls": "Interruptores no cartão", + "card_floor_thumbs": "Pisos em miniatura", + "card_floor_thumbs_hint": "Pequenas imagens dos pisos ao lado; toque numa para mudar", + "card_floor_thumbs_hint_start": "O piso escolhido é então onde o cartão começa; as imagens ao lado mudam para os outros", + "card_room_names": "Mostrar nomes das divisões", + "card_section_kiosk": "Tablet de parede (quiosque)", + "card_section_features": "Funções", + "card_weather_plan": "como definido na planta", + "card_pro_hint": "O rasto de movimento e a parede de câmaras pertencem às câmaras: o rasto mostra a última meia hora, a parede todas as câmaras da planta.", + "card_idle_return": "Voltar à vista inicial após", + "card_idle_off": "Nunca", + "card_idle_min": "{n} min sem toque", + "card_idle_hint": "Após a espera, o cartão fecha a divisão e mostra de novo a vista inicial.", + "card_night": "Escurecimento noturno", + "card_night_off": "Desligado", + "card_night_sun": "Pelo sol", + "card_night_time": "Intervalo horário", + "card_night_range": "Intervalo horário (p. ex. 22:00-06:00)", + "card_idle_orbit": "Rotação da câmara como protetor de ecrã", + "card_idle_orbit_hint": "Após o regresso, a vista roda devagar até alguém tocar no tablet", + "card_dashboard": "Botão para um dashboard (caminho)", + "card_dashboard_label": "Etiqueta do botão", + "card_dashboard_hint": "Um botão no canto superior direito do cartão abre o dashboard ou a vista com este caminho, p. ex. /lovelace/home ou /dashboard-house/0. Sem etiqueta mostra ⌂.", + "card_alerts": "Mostrar avisos", + "card_alerts_hint": "Fumo, gás, CO, água, alarme e janelas abertas à chuva: a divisão pulsa, aparece uma nota no topo", + "card_alert_jump": "Saltar para a divisão de um novo aviso", + "card_alert_jump_hint": "A vista muda sozinha para o piso e a divisão do aviso", + "card_scenes": "Botões de cena na divisão", + "card_scenes_hint": "Cenas e scripts da área como botões por baixo da vista 3D enquanto uma divisão está selecionada", + "card_sensor_bar": "Sensores próprios no topo", + "card_sensor_bar_hint": "Os sensores escolhidos no editor (Definições) em cima à esquerda do cartão", + "card_central_open": "Menu estrela aberto e grande", + "card_central_open_hint": "Favoritos e botões próprios ficam abertos desde o início, maiores", + "card_keep_camera": "Manter a câmara ao mudar de piso", + "card_keep_camera_hint": "O mesmo lado, altura e distância em cada piso", + "card_today": "Cartão «Hoje»", + "card_today_hint": "Compromissos de hoje e contentores a pôr na rua, em cima à direita", + "card_announcements": "Anúncios", + "card_announcements_hint": "Os anúncios (ação «NextFloor: Anúncio») aparecem em grande no cartão, com um toque, e são ditos em voz alta", + "weather_short": "Tempo", + "weather_entity": "Entidade de tempo", + "weather_effects": "Efeitos do tempo em 3D", + "card_weather_density": "Quantidade de chuva e neve", + "card_weather_density_hint": "Menos gotas e flocos do que o tempo indica; nuvens, nevoeiro e relâmpagos mantêm-se", + "rain_warning": "Aviso: janela aberta enquanto chove", + "sun_patches": "Sol e sombras", + "sun_patches_hint": "Com o norte definido, a luz do sol de sun.sun entra pelas janelas em manchas claras no chão e a casa projeta a sua sombra no terreno. Desmarque para manter chão e terreno sem manchas de sol nem sombras.", + "sun_arc": "Arco solar e bússola", + "sun_arc_hint": "Desenha o percurso do sol de hoje como um arco sobre o terreno, com um anel e os pontos cardeais no chão (norte a vermelho). Precisa da localização da casa no Home Assistant.", + "weather_effect_rain": "Chuva", + "weather_effect_snow": "Neve", + "weather_effect_fog": "Nevoeiro (acinzenta a cena)", + "weather_effect_clouds": "As nuvens escurecem o céu e o sol", + "weather_effect_lightning": "Relâmpagos nas trovoadas", + "weather_effect_sky": "Sol e lua no céu", + "weather_entity_hint": "Que entidade de tempo controla o céu à volta da casa. Automático usa a primeira encontrada.", + "weather_hint": "Tempo na casa: chuva e neve caem com o vento real, nuvens passam sobre o terreno com as suas sombras, relâmpagos, nevoeiro, sol e lua", + "card_weather": "Tempo exterior", + "card_weather_hint": "Chuva, neve, granizo, nuvens com sombras, relâmpagos e nevoeiro da primeira entidade de tempo (weather_entity escolhe outra); menos partículas no nível tablet", + "alerts": "Avisos", + "alert_smoke": "Fumo: {name}", + "alert_gas": "Gás: {name}", + "alert_co": "Monóxido de carbono: {name}", + "alert_water": "Água: {name}", + "alert_alarm": "Alarme disparado", + "alert_alarm_by": "Alarme disparado por {cause}", + "alert_alarm_pending": "Alarme pendente", + "alert_window_rain": "Janela aberta à chuva: {name}", + "alert_power_outage": "Falha de energia: {name}", + "alert_contact_lost": "O contacto não responde: {name}", + "rain_sensor": "Sensor de chuva (estação meteorológica própria)", + "outage_sensor": "Sensor de falha de energia", + "outage_hint": "Um sensor binário da classe power desligado, outro sensor binário ligado, um estado como \"off_grid\" ou \"backup\", ou uma tensão abaixo de 50 V geram um aviso para toda a casa.", + "contact_warning": "Avisar quando um contacto de porta ou janela não estiver disponível", + "contact_warning_hint": "Quando um contacto está indisponível há 10 minutos (pilha gasta, fora de alcance), a janela parece fechada em 3D sem que ninguém saiba. Um aviso indica então o contacto. Reiniciar o Home Assistant não avisa.", + "night_lock_warning": "Avisar à noite se uma porta não estiver trancada", + "night_lock_warning_hint": "Entre as 22 e as 6 h uma nota indica as fechaduras da planta que estão destrancadas.", + "alert_unlocked_night": "Não trancada: {name}", + "motion_markers_active": "Mostrar sensores de movimento só quando detetam", + "motion_markers_active_hint": "Aplica-se a sensores de movimento, ocupação e presença. Um sensor cujo símbolo está definido para aparecer sempre continua visível.", + "room_double_tap": "Toque duplo numa divisão", + "room_double_tap_hint": "Um toque duplo numa divisão desliga as luzes se alguma estiver acesa; caso contrário, liga todas. Os dispositivos que perguntam primeiro ficam sempre de fora.", + "room_double_tap_area": "Candeeiros na planta e todas as luzes da área", + "room_double_tap_plan": "Apenas os candeeiros na planta", + "room_double_tap_off": "Não comutar nada", + "card_room_double_tap_auto": "Como definido na planta", + "status_entities": "Sensores próprios no topo da vista 3D", + "status_add": "Adicionar um sensor", + "status_entities_hint": "Por exemplo a temperatura exterior, o alarme ou a qualidade do ar: aparecem em cima à esquerda com nome e valor, também numa divisão aberta. Tocar abre os detalhes. Até 12.", + "announce_tts": "Texto para voz dos anúncios", + "announce_phrases": "Frases para anúncios (uma por linha)", + "announce_phrases_hint": "Vazio: as frases incluídas. Os anúncios também existem como ação «NextFloor: Anúncio» para automações, nos altifalantes das divisões e em cada ecrã NextFloor aberto.", + "opening_rain_warning": "Avisar quando chove", + "opening_light_well": "Poço de luz à frente", + "sill_boards": "Peitoril e parapeito", + "sill_boards_auto": "Automático", + "sill_boards_none": "Nenhum", + "sill_boards_inside": "Só interior", + "sill_boards_outside": "Só exterior", + "room_names_short": "Nomes das divisões", + "floor_stack_short_dim": "Atenuados", + "floor_stack_short_stacked": "Empilhados", + "floor_stack_short_single": "Sozinho", + "size_short_w": "L", + "size_short_d": "P", + "size_short_h": "A", + "import_error_not_json": "O ficheiro não é JSON.", + "import_error_not_plan": "O ficheiro não é uma planta do NextFloor.", + "import_other_hint": "Do Sweet Home 3D: importe aqui o ficheiro .sh3d. Pisos, divisões, portas, janelas e paredes livres são importados, os móveis não.", + "import_sh3d_found": "Sweet Home 3D: {floors} pisos, {rooms} divisões, {openings} portas e janelas, {walls} paredes livres ({furniture} móveis não são importados).", + "import_dxf_found": "DXF: {rooms} divisões (polilinhas fechadas) e {walls} paredes livres (linhas) num piso.", + "import_ifc_found": "No ficheiro IFC: {floors} pisos e {rooms} divisões (o NextFloor desenha as paredes a partir das divisões).", + "import_roomplan_found": "Digitalização da divisão (RoomPlan): {rooms} divisões, {openings} portas e janelas; {skipped} objetos não foram importados (os móveis colocas tu).", + "import_error_roomplan_empty": "A digitalização não tem paredes.", + "import_error_ifc_empty": "O ficheiro IFC não tem espaços (IfcSpace) com planta.", + "import_error_dxf_empty": "O ficheiro DXF não tem linhas nem polilinhas.", + "import_error_sh3d": "Isto não é um ficheiro Sweet Home 3D legível (requer Sweet Home 3D 5.3 ou mais recente).", + "import_error_sh3d_empty": "O ficheiro Sweet Home 3D não tem divisões nem paredes.", + "export_name_template": "modelo", + "export_name_backup": "cópia", + "card_floor_stack": "Pisos abaixo", + "floor_stack_dim": "Atenuados", + "floor_stack_stacked": "Empilhados (a casa até aqui)", + "floor_stack_single": "Ocultos (só este piso)", + "card_control_walls": "Paredes altas/corte", + "card_control_floors": "Pisos afastados", + "card_control_temperature": "Temperatura", + "card_control_humidity": "Humidade", + "card_control_co2": "CO₂", + "card_controls_hint": "Paredes altas/corte, pisos afastados e temperatura, humidade, CO₂ para alternar", + "controls_hide": "Ocultar os controlos; só fica a vista 3D", + "nav_wrap": "Quebrar a barra: todos os pisos e divisões em várias linhas", + "bars_fold": "Recolher os interruptores", + "bars_unfold": "Interruptores", + "nav_row": "Barra numa linha (desliza para o lado)", + "controls_show": "Mostrar de novo os controlos", + "card_controls_hidden": "Começar com os controlos ocultos", + "card_controls_hidden_hint": "Só a vista 3D; um olho em baixo à esquerda traz de volta barras, valores e interruptores", + "card_controls_hide_after": "Ocultar os controlos após", + "card_hide_after_s": "{n} s sem toque", + "card_fullscreen_button": "Botão de ecrã inteiro", + "card_fullscreen_button_hint": "Oculta o dashboard à volta do cartão (p. ex. num tablet de parede)", + "fullscreen": "Ecrã inteiro", + "fullscreen_exit": "Sair do ecrã inteiro", + "card_section_show": "Mostrar", + "card_floor": "Piso", + "card_floor_house": "Casa inteira (toque num piso para o abrir)", + "card_height": "Altura (píxeis)", + "card_walls": "Paredes", + "card_quality_hint": "«Tablet» é a definição mais leve, ideal para tablets Fire e outros tablets de parede.", + "card_flows_switch": "Interruptor no cartão", + "card_flows_on": "Sempre ligado", + "card_flows_off": "Sempre desligado", + "holos": "Cartões", + "holos_hint": "Mostrar ou ocultar os cartões em direto sobre a casa (balanço energético, carro, multimédia)", + "card_energy": "Mostrar valores de energia no topo", + "card_room_panel": "Detalhes da divisão ao tocar", + "card_room_buttons": "Botões das divisões", + "card_room_buttons_hint": "Uma linha com um botão por divisão no topo do cartão; toque num para abrir a divisão, como ao tocá-la no modelo", + "card_room_panel_hint": "As luzes e estores da divisão num painel lateral", + "card_explode": "Afastar os pisos na vista da casa", + "card_roof_fade": "Desvanecer o telhado ao aproximar", + "card_roof_fade_hint": "Desligado: o telhado fica na casa mesmo quando a câmara se aproxima.", + "card_stats": "Indicador de desempenho (fotogramas por segundo)", + "card_stats_hint": "Para verificar a fluidez do cartão no dispositivo", + "packs": "Pacotes de móveis", + "lib_badge_light": "Candeeiro: liga-se a uma luz e comuta em 3D", + "lib_badge_electric": "Elétrico: liga-se a uma entidade e a um sensor de potência (comutar, imagens, consumo)", + "lib_badge_hint": "Os elementos com um símbolo ligam-se a entidades: os candeeiros comutam, os ecrãs mostram imagens, os eletrodomésticos mostram o consumo.", + "care_bin_today": "Recolha hoje", + "care_bin_tomorrow": "Recolha amanhã", + "care_bin_days": "Daqui a {n} dias", + "care_mail_yes": "Há correio", + "care_mail_no": "Vazia", + "care_plant_thirsty": "Com sede", + "care_plant_ok": "Bem regada", + "care_time_left": "Faltam {time}", + "care_entity_bin": "Data de recolha (sensor)", + "care_entity_mail": "Sensor de correio", + "care_entity_plant": "Humidade do solo (sensor)", + "care_thirsty_below": "Com sede abaixo de (%)", + "care_hint_bin": "Um sensor com a próxima recolha: dias, uma data, \"hoje\"/\"amanhã\" ou a integração Waste Collection Schedule. O contentor brilha na véspera e no próprio dia.", + "care_hint_mail": "Um sensor que indica correio na caixa (p. ex. um contacto na portinhola). A caixa de correio brilha então.", + "care_hint_plant": "Um sensor de humidade no solo. Abaixo do limite, a planta brilha e diz que tem sede.", + "lib_cat_lights": "Luzes", + "lib_cat_seating": "Assentos", + "lib_cat_tables": "Mesas", + "lib_cat_storage": "Armários e estantes", + "lib_cat_beds": "Camas", + "lib_cat_kitchen": "Cozinha", + "lib_cat_appliances": "Eletrodomésticos", + "lib_cat_bath": "Casa de banho", + "lib_cat_media": "TV e áudio", + "lib_cat_office": "Escritório", + "lib_cat_tech": "Tecnologia", + "lib_cat_climate": "Aquecimento e clima", + "lib_cat_energy": "Energia", + "lib_cat_garden": "Jardim e terraço", + "lib_cat_plants": "Plantas", + "lib_cat_kids": "Crianças", + "lib_cat_fitness": "Fitness", + "lib_cat_pets": "Animais", + "lib_cat_workshop": "Oficina e garagem", + "lib_cat_music": "Música e ateliê", + "lib_cat_season": "Estações e decoração", + "lib_cat_pictures": "Quadros e molduras", + "lib_cat_vehicles": "Veículos", + "lib_cat_building": "Escadas e elementos construtivos", + "lib_cat_decor": "Decoração e mais", + "lib_favourites": "Favoritos", + "lib_recent": "Usados recentemente", + "lib_for_room": "Cabe em {room}", + "lib_all_rooms": "Mostrar todas as divisões", + "lib_linkable": "ligável", + "lib_lit": "iluminado", + "lib_outdoor": "exterior", + "lib_fav_add": "Adicionar aos favoritos", + "lib_fav_remove": "Remover dos favoritos", + "lib_sizes": "Tamanhos", + "feature_name_energy": "Fluxo de energia", + "ext_tab": "Extensões", + "ext_title": "Extensões", + "models": "Os seus próprios modelos 3D", + "models_hint": "Para alguns veículos o NextFloor pode mostrar um modelo 3D real, se tiver um. Escolha aqui o ficheiro (.glb): o NextFloor orienta-o corretamente, torna-o mais leve, marca a pintura e guarda-o no seu Home Assistant. Sem modelo, o veículo aparece como antes.", + "models_licence": "Os ficheiros são seus e ficam no seu Home Assistant. O NextFloor não inclui modelos; confirme que a licença do seu modelo permite usá-lo na sua própria instalação.", + "model_add": "Adicionar um modelo …", + "model_replace": "Substituir o modelo …", + "model_remove": "Remover", + "model_present": "em uso", + "model_missing": "ainda nenhum", + "model_remove_confirm": "Eliminar o modelo «{id}» do Home Assistant?", + "model_removed": "Modelo «{id}» eliminado.", + "model_uploaded": "Modelo «{id}» guardado ({size}). Recarregue o painel para o ver.", + "model_upload": "Guardar no Home Assistant", + "model_info": "{triangles} triângulos, {size} m", + "model_front": "Frente", + "model_front_hint": "Rode o modelo até a frente ficar virada para quem vê (para baixo à esquerda na imagem).", + "model_paint": "Pintura (a cor que escolhe no editor)", + "model_paint_preview": "Cor na pré-visualização", + "model_detail": "Nível de detalhe", + "model_detail_light": "Leve (tablet)", + "model_detail_normal": "Normal", + "model_detail_fine": "Fino", + "model_result": "Resultado: {triangles} triângulos, {size}", + "model_error_not_glb": "Isto não é um ficheiro .glb (glTF binário). Exporte o modelo como «glTF binário».", + "model_error_compressed": "O ficheiro está comprimido (Draco, Meshopt ou KTX). Exporte-o sem compressão.", + "model_error_empty": "O ficheiro não contém nada tridimensional.", + "model_error_unreadable": "Não é possível ler o ficheiro: {detail}", + "model_error_too_large": "O ficheiro é maior do que {max}. Escolha um nível de detalhe menor.", + "model_upload_forbidden": "Só os administradores podem carregar modelos.", + "model_upload_too_large": "O Home Assistant não aceita ficheiros acima de {max}. Escolha um nível de detalhe menor.", + "model_upload_not_glb": "O Home Assistant recusou o ficheiro (não é um glTF binário).", + "model_upload_bad_id": "O id do modelo não é válido.", + "model_upload_other": "O carregamento não funcionou: {detail}", + "ext_intro": "Importe aqui os seus pacotes de móveis, carregue os seus modelos 3D e adicione plugins.", + "plugin": "plugin", + "plugins_title": "Plugins", + "plugins_intro": "Os plugins adicionam animações de luz, dispositivos e cartões no painel da divisão. Introduza o endereço de um plugin (um ficheiro .js em /config/www, ou seja /local/…, do HACS /hacsfiles/…, ou https://…).", + "plugins_docs": "Como escrever um plugin", + "plugins_warning": "Os plugins correm com os mesmos direitos do NextFloor no seu navegador. Use apenas plugins de fontes em que confia.", + "plugins_off": "desligado", + "plugins_error": "erro", + "plugins_loading": "a carregar …", + "plugins_nothing_registered": "carregado, mas não registou nada", + "plugins_loaded": "ativo", + "plugins_reload_hint": "Tem efeito após recarregar a página", + "plugins_remove": "Remover", + "plugins_none": "Ainda sem plugins.", + "plugins_from_dashboard": "Registado por um recurso do dashboard", + "plugins_add": "Adicionar", + "plugins_url_invalid": "Introduza um endereço .js em /local/…, /hacsfiles/… ou https://….", + "plugins_exists": "Este plugin já está na lista.", + "plugins_limit": "No máximo 20 plugins.", + "packs_title": "Pacotes de móveis", + "packs_intro": "Importe os seus móveis como pacote (JSON): como ficheiro ou colado abaixo. {n} pacotes vêm com o NextFloor e estão sempre disponíveis.", + "packs_docs": "Formato do pacote", + "packs_none": "Ainda sem pacotes próprios.", + "community_title": "Móveis da comunidade", + "community_intro": "Móveis que outros construíram e partilharam com o construtor de móveis, verificados e gratuitos. Construa os seus:", + "community_builder": "Abrir o construtor de móveis", + "community_how": "Como partilhar os seus", + "community_load": "Carregar móveis da comunidade", + "community_none": "Ainda não há móveis da comunidade – seja o primeiro!", + "community_install": "Instalar", + "community_update": "Atualizar", + "community_installed": "Instalado", + "community_failed": "Não foi possível carregar os móveis da comunidade: {detail}", + "pack_import": "Importar ficheiros de pacote …", + "pack_paste": "Importar JSON", + "pack_paste_empty": "Cole primeiro o JSON de um pacote.", + "pack_paste_not_json": "Isto não é JSON válido: {detail}", + "pack_imported": "Importado «{name}» de {publisher}: {n} elementos", + "packs_imported_n": "{n} de {total} pacotes importados", + "pack_by": "de {publisher} · {n} elementos", + "pack_remove": "Remover", + "pack_remove_confirm": "Remover o pacote «{name}»? Os seus móveis ficam na planta como caixas simples.", + "pack_error_not_a_pack": "Isto não é um pacote de móveis (falta \"format\": \"nfpack\").", + "pack_error_builtin": "Um pacote incluído no NextFloor já tem este id.", + "pack_error_invalid_content": "O pacote contém móveis inválidos: {detail}", + "pack_error_too_large": "O pacote é demasiado grande (no máximo 1 MB).", + "pack_error_needs_update": "Este pacote precisa de uma versão mais recente do NextFloor. Atualize primeiro (HACS › NextFloor › ⋮ › \"Informação de atualização\" › \"Transferir\"), reinicie o Home Assistant e importe de novo.", + "pack_error_other": "A importação falhou: {detail}", + "store_open": "Abrir a loja de plugins", + "store_close": "Fechar a loja de plugins", + "store_intro": "Plugins verificados da comunidade. Cada um é revisto antes de ser adicionado e depois não muda.", + "store_submit": "Submeter o seu plugin", + "store_empty": "Ainda sem plugins na loja.", + "store_failed": "Não foi possível carregar a loja ({error}).", + "store_install": "Instalar", + "store_installed": "instalado", + "store_update": "Atualizar", + "store_confirm": "Instalar «{name}» de {author}?\n\nUm plugin corre com os mesmos direitos do NextFloor no seu navegador. O ficheiro foi revisto e o seu conteúdo é fixo:\n{url}", + "manual": "Manual", + "manual_more": "Saber mais", + "feature_text_energy": "Partículas de energia voam em arcos dos campos solares para o inversor, entre casa, bateria, rede e consumidores, mais rápidas e densas quanto mais potência flui. Os módulos cintilam com a sua produção, um cartão de vidro sobre o telhado mostra o balanço e quão autossuficiente a casa está agora.", + "live_autarky": "autonomia", + "live_day_hint": "As últimas 24 horas: solar (área) e consumo (linha)", + "live_week_hint": "Os últimos 7 dias: sol {solar} kWh, consumo {use} kWh (amarelo: sol, claro: consumo)", + "live_days": "dias", + "live_car_away": "Em viagem", + "live_car_charging": "A carregar", + "live_car_plugged": "Ligado", + "live_car_lock": "Trancar", + "live_car_unlock": "Destrancar", + "live_car_unlock_confirm": "Destrancar mesmo {name}?", + "live_car_climate": "Climatização", + "live_car_charge": "Iniciar/parar carregamento", + "live_media_prev": "Anterior", + "live_media_playpause": "Reproduzir/pausa", + "live_media_next": "Seguinte", + "live_media_volume": "Volume", + "live_car_device": "Carro (qualquer entidade do carro)", + "live_car_device_hint": "Carga, autonomia, carregamento, ficha, trancamento e climatização são encontrados pelo NextFloor no dispositivo do carro. Sem ele, usa o sensor de presença do lugar.", + "live_car_departure_entity": "Hora de partida (opcional)", + "live_car_departure": "Partida às {time}", + "live_car_open": "Aberto: {parts}", + "printer_printing": "a imprimir", + "printer_done": "concluído", + "printer_paused": "em pausa", + "printer_error": "erro", + "printer_idle": "pronta", + "printer_done_at": "pronta às {time}", + "printer_layer": "Camada", + "printer_nozzle": "Bico", + "printer_bed": "Mesa", + "heatpump_heating": "a aquecer", + "heatpump_water": "água quente", + "heatpump_cooling": "a arrefecer", + "heatpump_defrost": "a descongelar", + "heatpump_idle": "em repouso", + "heatpump_flow_return": "Ida → retorno", + "heatpump_heat": "Calor", + "heatpump_power": "Eletricidade", + "heatpump_outside": "fora", + "pack_missing_item": "Móvel de um pacote removido", + "back_to_room": "Voltar a {room}", + "back_to_floor": "Voltar ao piso", + "hint_furniture": "Toque numa divisão e escolha um elemento à direita · arraste os elementos, redimensione-os pelos cantos", + "furniture_into": "Os novos elementos vão para o centro de «{room}».", + "furniture_pick_room": "Dica: toque primeiro numa divisão; os novos elementos ficam então no seu centro.", + "flows": "Fluxo de energia", + "flows_hint": "Mostrar ou ocultar os arcos de energia entre campos solares, inversor, bateria, rede e consumidores", + "chk_title": "Configuração", + "chk_hint": "O que o fluxo de energia precisa. Toque numa linha para ir lá.", + "chk_solar": "Campo solar colocado", + "chk_solar_add": "Ponha um campo solar no telhado", + "chk_meter": "Contador com sensor de rede", + "chk_meter_sensor": "Contador: falta o sensor de rede (W)", + "chk_meter_add": "Adicionar o contador", + "chk_inverter": "Inversor com sensor de potência", + "chk_inverter_sensor": "Inversor: falta o sensor de potência", + "chk_inverter_add": "Adicionar um inversor", + "chk_battery": "Bateria doméstica com potência e carga", + "chk_battery_sensor": "Bateria doméstica: falta a potência ou a carga", + "chk_battery_opt": "Bateria doméstica (opcional)", + "chk_grid": "Ligação à rede definida", + "chk_grid_opt": "Ligação à rede (opcional, senão automática)", + "energy_sign_grid": "A casa mostra injeção enquanto o sol não produz nada. O sensor de rede tem provavelmente o sinal invertido.", + "energy_sign_battery": "A bateria carrega sem sol e sem consumo da rede. O seu sensor tem provavelmente o sinal invertido.", + "energy_sign_flip": "Inverter o sinal", + "help_title": "Ajuda e feedback", + "help_hint": "Comunique problemas como issue no GitHub e desejos como discussion: nada se perde e todos veem o estado.", + "help_issue": "Comunicar um problema", + "help_idea": "Propor uma ideia", + "furn_name": "Nome (opcional)", + "furn_mirror": "Espelhar", + "furn_mirror_hint": "Trocar esquerda e direita: o sofá em L ao contrário, o armário com a porta do outro lado, a cozinha espelhada.", + "hint_opening": "Toque numa parede para adicionar uma porta ou janela; escolha o tipo à direita depois", + "preset_door": "Porta", + "preset_door_double": "Porta dupla", + "preset_window": "Janela", + "preset_window_double": "Janela dupla", + "preset_terrace": "Porta de terraço", + "preset_terrace_double": "Portas de sacada", + "preset_lift_slide": "Porta de correr elevatória", + "preset_garage": "Portão de garagem", + "preset_front": "Porta de entrada", + "opening_style": "Estilo", + "sidelight_auto": "automático", + "sidelight_hinge": "Bandeira lateral do lado das dobradiças", + "sidelight_hinge_hint": "Caso contrário a bandeira fica oposta às dobradiças; marcado, fica junto às dobradiças.", + "sidelight_width": "Largura da bandeira (m)", + "sidelight_width_left": "Bandeira esquerda (m)", + "sidelight_width_right": "Bandeira direita (m)", + "style_auto": "Automático ({style})", + "style_interior": "Porta interior", + "style_front": "Porta de entrada", + "style_front_glass": "Porta de entrada com vidro", + "style_sidelight": "Porta de entrada com bandeira lateral", + "style_sidelights": "Porta de entrada com duas bandeiras laterais", + "style_glass": "Porta de vidro", + "style_sliding": "Porta de correr", + "style_passage": "Abertura (sem porta)", + "style_standard": "Padrão", + "style_bars": "Com travessas", + "style_glass_wall": "Parede de vidro (fixa)", + "preset_glass_wall": "Parede de vidro", + "flip_hinge": "Trocar lado das dobradiças", + "flip_main_leaf": "Trocar folha principal", + "flip_hinge_hint": "Dobradiças para o outro lado", + "flip_swing": "Inverter o sentido de abertura", + "flip_swing_hint": "A porta abre para a divisão ou para o outro lado", + "main_leaf": "Folha principal (vista da divisão)", + "contact_main": "Contacto da folha principal", + "contact_second": "Contacto da segunda folha", + "tool_outdoor": "Exterior", + "tool_measure": "Por medidas", + "hint_measure": "Toque no ponto de partida e escreva à direita os comprimentos das paredes com a sua direção", + "measure": "Divisão por medidas", + "measure_start": "Toque no ponto de partida na planta, p. ex. um canto da divisão.", + "measure_from": "Início em {x} / {z} m; tocar move o início.", + "measure_length": "Comprimento da próxima parede (m)", + "measure_close": "Fechar divisão", + "measure_undo": "Remover a última parede", + "measure_gap": "Distância ao início: {gap} m (unida ao fechar)", + "measure_hint": "Dica: escreva um comprimento e prima uma seta. Com medidas interiores, use depois «Fechar folgas».", + "rect_by_size": "Retângulo por tamanho", + "rect_add": "Adicionar retângulo", + "dir_up": "Cima", + "dir_down": "Baixo", + "dir_left": "Esquerda", + "dir_right": "Direita", + "hint_outdoor": "Arraste para desenhar uma área exterior (relvado, terraço, piscina …)", + "outdoor": "Área exterior", + "outdoor_type": "Tipo", + "outdoor_height": "Altura (m)", + "outdoor_offset": "Desvio de altura (m, − = mais baixo)", + "outdoor_outline": "Mostrar o contorno", + "outdoor_outline_hint": "Desmarcado, a área não desenha uma linha luminosa ao longo da borda, para terrenos grandes feitos de vários relvados.", + "outdoor_corners_hint": "Cantos: um + numa aresta adiciona um canto, arrastar molda a área, × remove um canto.", + "outdoor_hint": "As luzes exteriores (baliza, projetor de jardim, aplique exterior) iluminam todas as áreas exteriores e a fachada.", + "out_lawn": "Relvado", + "out_terrace": "Terraço", + "out_path": "Caminho", + "out_driveway": "Acesso", + "out_pool": "Piscina", + "out_bed": "Canteiro", + "out_hedge": "Sebe", + "out_fence": "Vedação", + "out_wild": "Zona selvagem", + "out_pergola": "Pérgula / estrutura", + "outdoor_open": "Aberta (omitir a última aresta)", + "outdoor_open_hint": "A aresta do último ponto ao primeiro não é desenhada: uma vedação ou pérgula encostada à casa.", + "fence_gates": "Portões na vedação", + "gate_add": "+ Portão na vedação", + "gate_edge": "Lado da vedação", + "gate_kind": "Tipo", + "gate_single": "Portão de jardim", + "gate_double": "Portão duplo", + "gate_sliding": "Portão de correr", + "gate_offset": "Centro desde o início (m)", + "gate_width": "Largura (m)", + "gate_entity": "Motor ou interruptor", + "gate_contact": "Contacto (ligado = aberto)", + "fence_gates_hint": "Um portão é uma abertura na vedação com postes e folha. Com um motor (cover, interruptor, input_boolean, fechadura) e/ou um contacto abre-se em 3D: portões de jardim e duplos abrem para dentro, um portão de correr desliza ao longo da vedação.", + "outdoor_bracing": "Contraventamento em X", + "outdoor_cut": "Recortar das áreas envolventes", + "outdoor_cut_hint": "Cada área que contém esta por completo recebe aqui um buraco: uma piscina no terraço, um lago ou zona selvagem no relvado. A ordem de desenho não importa. Uma piscina recorta-se sozinha.", + "outdoor_area_hint": "A área do Home Assistant desta superfície (jardim, terraço, piscina): os seus dispositivos e sensores aparecem em Exterior, e um marcador na superfície abre-o.", + "pool_temp": "Temperatura da água (opcional)", + "pool_pump": "Bomba / filtro (opcional)", + "pool_pump_on": "bomba ligada", + "outdoor_slope": "Inclinação (m)", + "outdoor_slope_hint": "Diferença de altura da aresta alta para a baixa; a aresta alta fica no desvio de altura. Os candeeiros na área seguem-na.", + "outdoor_slope_dir": "Desce para", + "slope_x": "direita (+X)", + "slope_nx": "esquerda (−X)", + "slope_z": "baixo (+Z)", + "slope_nz": "cima (−Z)", + "north": "Norte (° no sentido horário a partir de cima)", + "north_hint": "O norte é necessário para o sol (luz pelas janelas).", + "map_on": "Mostrar um mapa real sob a planta", + "map_lat": "Latitude", + "map_lon": "Longitude", + "map_use_ha": "Usar a localização do Home Assistant", + "map_opacity": "Visibilidade (%)", + "map_zoom": "Nível de detalhe", + "map_zoom_coarse": "grosso", + "map_zoom_fine": "fino", + "map_move": "Mover o mapa sob a planta", + "map_step": "Passo", + "map_url": "Endereço de mosaicos próprio (vazio = OpenStreetMap)", + "map_hint": "O navegador carrega os mosaicos do mapa diretamente do servidor (OpenStreetMap por omissão, respeite a sua política de utilização); com o mapa desligado nada é carregado. A planta fica sobre o mapa como a bússola indica: rode a bússola ou mova o mapa até a casa encaixar.", + "compass_title": "Bússola", + "compass_n_short": "N", + "compass_s_short": "S", + "compass_swap": "Trocar norte ↔ sul", + "compass_swap_hint": "Roda a bússola 180°. O desenho, as águas do telhado e os campos solares ficam como estão.", + "compass_hint": "Se a bússola não corresponder à realidade, rode-a aqui; não é preciso redesenhar nada. A luz do sol, o vento e a orientação das águas seguem-na.", + "roof": "Telhado", + "roof_none": "Sem telhado", + "roof_flat": "Telhado plano", + "roof_gable": "Telhado de duas águas", + "roof_custom": "Águas do telhado (personalizado)", + "roof_sections": "Águas do telhado", + "roof_sections_hint": "Cada água cobre um retângulo da casa, p. ex. a casa, o celeiro ou uma ampliação, cada uma com forma, direção da cumeeira, altura do beiral e inclinação próprias. Arraste na planta para desenhar uma nova; tocar seleciona, arrastar move, os cantos redimensionam.", + "roof_sections_start": "Criar águas do telhado a partir das divisões", + "roof_sections_regen": "Criar de novo a partir das divisões", + "roof_sections_off": "Voltar a um só telhado", + "roof_regen_confirm": "Substituir todas as águas por uma nova proposta a partir das divisões?", + "roof_section": "Água do telhado", + "roof_section_hint": "As alturas contam a partir do solo. Um lado com beiral mais baixo desce mais (catslide); os telhados de uma água sobem a partir do primeiro lado.", + "roof_shape_gable": "Duas águas", + "roof_shape_hip": "Quatro águas", + "roof_shape_pent": "Uma água", + "roof_shape_flat": "Plano", + "roof_shape_halfhip": "Meia-água", + "roof_shape_pyramid": "Piramidal", + "roof_shape_mansard": "Mansarda", + "roof_shape_parapet": "Com platibanda", + "roof_shape": "Forma", + "roof_end_start": "Remate no início da cumeeira", + "roof_end_end": "Remate no fim da cumeeira", + "roof_halfhip": "A tacaniça começa a", + "roof_halfhip_hint": "A que altura da empena começa a tacaniça, como parte da altura da empena: baixo = tacaniça grande, alto = só a ponta.", + "roof_axis_x": "Cumeeira ↔", + "roof_axis_z": "Cumeeira ↕", + "roof_eave": "Beiral (m)", + "roof_pitch_short": "Inclinação (°)", + "roof_height": "Altura (m)", + "roof_base": "Topo das paredes (m)", + "roof_rotation": "Rotação (°)", + "roof_on_floor": "Assente no piso", + "roof_on_floor_hint": "Assenta a água no topo das paredes deste piso; base e beirais acompanham. Na vista 3D o telhado pertence a este piso.", + "roof_base_hint": "Abaixo do pé-direito do piso inferior, as paredes desse piso terminam sob o telhado: muretes nos beirais, empenas até à cumeeira, paredes interiores cortadas pela inclinação. Linhas tracejadas na planta mostram onde restam 1,5 m e 2 m de altura livre.", + "roof_ridge_height": "Altura da cumeeira", + "roof_side_top": "cima", + "roof_side_bottom": "baixo", + "roof_side_left": "esquerda", + "roof_side_right": "direita", + "roof_swap": "Trocar lados", + "roof_open": "Telheiro (pilares em vez de paredes, transparente)", + "roof_open_short": "Telheiro", + "roof_dormer": "Trapeira", + "roof_dormer_hint": "Uma trapeira deste lado do telhado: 2 m de largura, a frente na parede do beiral, beirais 1,4 m acima do beiral do telhado, duas águas. Depois mova-a e mude a largura e as alturas como qualquer água; a água principal abre por baixo e a parede do sótão sobe até à trapeira; aí cabe uma janela.", + "roof_outline": "Usar o contorno do piso", + "roof_outline_hint": "Um telhado plano de forma livre: usa o contorno das divisões do piso mostrado (também em L ou Z) como uma superfície sem juntas. Os cantos podem depois ser arrastados.", + "roof_points_hint": "Forma livre: arraste os cantos na planta, um + numa aresta adiciona um canto, × remove um. Voltar ao retângulo descarta a forma.", + "roof_rect": "Voltar ao retângulo", + "roof_open_hint": "Para uma cobertura de terraço ou um telheiro de carro: pilares e vigas suportam o telhado em vez de paredes, e é transparente. Onde o telheiro toca a parede da casa, apoia-se nela.", + "roof_swap_hint": "Vira o telhado: os dois lados trocam beiral e inclinação, um telhado de uma água sobe para o outro lado.", + "roof_pitch": "Inclinação do telhado (°)", + "roof_overhang": "Beiral do telhado (m)", + "roof_overhang_sides": "Beiral por lado", + "roof_overhang_a": "Beiral A (m)", + "roof_overhang_b": "Beiral B (m)", + "roof_overhang_u0": "Beiral empena início (m)", + "roof_overhang_u1": "Beiral empena fim (m)", + "roof_overhang_auto": "Voltar ao automático", + "roof_overhang_sides_hint": "Sem valores próprios o beiral é automático: igual em todo o lado, exceto onde a parte do telhado toca na casa (nenhum).", + "roof_ridge": "Cumeeira", + "roof_ridge_long": "Ao longo do lado comprido", + "roof_ridge_short": "Ao longo do lado curto (p. ex. moradia em banda)", + "device": "Dispositivo", + "lamp_mount": "Candeeiro", + "lamp_ceiling": "Candeeiro de teto", + "lamp_floor": "Candeeiro de pé", + "lamp_table": "Candeeiro de mesa", + "lamp_wall": "Aplique de parede", + "marker_height": "Altura do marcador (m)", + "height_auto": "Altura automática", + "device_centre": "Para o centro da divisão", + "lights_spread": "Distribuir os candeeiros de teto uniformemente", + "devices_search": "Pesquisar dispositivos …", + "devices_more": "+{n} mais", + "devices_less": "menos", + "panel_more": "Mais dispositivos da área ({n})", + "panel_less": "Mostrar menos", + "gaps_close": "Fechar folgas", + "gaps_hint": "Une divisões afastadas até 60 cm numa parede partilhada; a folga passa a ser a espessura da parede interior.", + "gaps_none": "Não foram encontradas folgas entre divisões.", + "gaps_closed": "{n} locais fechados.", + "gaps_closed_wall": "{n} locais fechados, parede interior agora com {t} m.", + "fps": "FPS", + "fps_title": "Indicador de desempenho (fotogramas por segundo)", + "hint_garage": "Toque numa parede para adicionar um portão de garagem", + "opening_garage": "Portão de garagem", + "garage_hint": "O portão segue uma cobertura da garagem (posição ou aberto/fechado) ou um contacto do portão da área da divisão.", + "door_hint": "Com um contacto de porta a folha abre; sem sensor fica meio aberta.", + "hint_door": "Toque numa parede para adicionar uma porta", + "hint_window": "Toque numa parede para adicionar uma janela", + "opening_door": "Porta", + "opening_window": "Janela", + "opening_type": "Tipo", + "opening_position": "Centro a partir do canto (m)", + "sill": "Altura do peitoril (m)", + "opening_height": "Altura (m)", + "hinge": "Dobradiça (vista da divisão)", + "hinge_left": "Esquerda", + "hinge_right": "Direita", + "cover_entity": "Estore", + "door_cover": "Motor (porta ou portão motorizado)", + "cover_position_entity": "Sensor de posição (em direto)", + "cover_position_invert": "O sensor conta ao contrário (0 = aberto)", + "contact_entity": "Contacto", + "sensor_kind": "Tipo de sensor", + "sensor_kind_contact": "Contacto de janela (aberta/fechada)", + "sensor_kind_handle": "Sensor de puxador (aberta/basculante/fechada)", + "sensor_kind_contact_tilt": "Contacto + sensor basculante", + "handle_entity": "Sensor de puxador", + "handle_main": "Sensor de puxador da folha principal", + "leaf_main": "Folha principal", + "leaf_second": "Segunda folha", + "tilt_entity": "Sensor basculante", + "tilt_angle_entity": "Sensor de ângulo basculante (°, opcional)", + "tilt_angle_max": "Ângulo considerado totalmente basculante (°)", + "tilt_angle_offset": "Desvio: ângulo indicado quando fechada (°)", + "tilt_angle_invert": "O ângulo conta ao contrário", + "door_shut": "Mostrar fechada sem sensor", + "door_shut_hint": "Uma porta sem contacto aparece meio aberta em 3D para se perceber que é uma porta. Marcado, é desenhada fechada: porta de entrada, telheiro, porta lateral.", + "door_angle": "Ângulo de abertura", + "door_angle_default": "Predefinido", + "door_angle_hint": "Até onde a folha abre. Com sensor abre assim que ele indica «aberta»; sem sensor fica aberta nesse ângulo (em vez de a meio). Predefinido fica como antes.", + "entity_auto": "Automático ({name})", + "entity_auto_none": "Automático (nenhum encontrado)", + "entity_none": "Nenhum", + "entity_search": "Escreva para pesquisar …", + "opening_hint": "Tipo de sensor: contacto de janela (indica aberta/fechada), sensor de puxador (indica aberta, basculante e fechada, p. ex. um puxador Homematic) ou contacto + sensor basculante (um segundo sensor que só indica basculante). Automático usa os estores e contactos da área da divisão. Sensor de posição: uma entidade que indica a posição do estore enquanto se move (p. ex. um \"level\" Homematic, 0–100 % ou 0–1, aberto = alto); o estore move-se então em direto em 3D.", + "furniture": "Móveis", + "furniture_add": "Adicionar móvel", + "studio_new": "Construir um móvel próprio", + "studio_title": "Oficina de móveis", + "studio_title_edit": "Oficina de móveis: alterar", + "studio_hint": "Escolhe um modelo, define medidas e frentes e coloca o móvel na planta. Fica no pacote «Móveis próprios» e pode ser alterado aqui mais tarde.", + "studio_kind": "Modelo", + "studio_kind_cabinet": "Armário", + "studio_kind_shelf": "Estante", + "studio_kind_lamp": "Candeeiro", + "studio_kind_device": "Aparelho", + "studio_name": "Nome", + "studio_width": "Largura (cm)", + "studio_depth": "Profundidade (cm)", + "studio_height": "Altura (cm)", + "studio_doors": "Portas", + "studio_drawers": "Gavetas", + "studio_shelves": "Prateleiras", + "studio_handle": "Puxadores", + "studio_handle_bar": "Barra", + "studio_handle_knob": "Botão", + "studio_handle_none": "Sem", + "studio_base": "Base", + "studio_base_plinth": "Rodapé", + "studio_base_legs": "Pés", + "studio_base_none": "Nenhuma", + "studio_back": "Painel traseiro", + "studio_lamp": "Tipo", + "studio_lamp_floor": "Candeeiro de pé", + "studio_lamp_table": "Candeeiro de mesa", + "studio_lamp_pendant": "Pendente", + "studio_lamp_wall": "Aplique", + "studio_display": "Ecrã à frente (mostra o leitor)", + "studio_mount": "Fica", + "studio_mount_floor": "No chão", + "studio_mount_surface": "Sobre um móvel", + "studio_mount_wall": "Na parede", + "studio_color_body": "Corpo", + "studio_color_lamp_body": "Base e estrutura", + "studio_color_front": "Frentes", + "studio_color_boards": "Prateleiras", + "studio_color_shade": "Abajur", + "studio_color_display": "Moldura do ecrã", + "studio_color_white": "Branco", + "studio_color_wood": "Madeira", + "studio_color_metal": "Metal", + "studio_color_dark": "Escuro", + "studio_color_glass": "Vidro", + "studio_color_accent": "Destaque", + "studio_color_own": "Cor própria", + "studio_color_plan": "Cor da planta", + "studio_place": "Colocar na planta", + "studio_save": "Guardar a alteração", + "studio_open": "Alterar na oficina", + "studio_error": "Não foi possível guardar: {detail}", + "studio_pack_name": "Móveis próprios", + "studio_pack_publisher": "Oficina de móveis", + "furniture_search": "Pesquisar móveis …", + "furniture_search_none": "Nada encontrado. Tente outra palavra, em inglês ou alemão.", + "furniture_type": "Elemento", + "rotation": "Rotação (°)", + "tilt_x": "Inclinação frente/trás (°)", + "tilt_z": "Inclinação lateral (°)", + "strip_tilt": "Inclinação sobre o comprimento (°)", + "strip_upright": "Na vertical", + "strip_rise": "Inclinação ao longo do comprimento (°)", + "strip_upright_hint": "A fita fica de pé: o seu comprimento sobe a partir da altura acima do chão, ao longo de um aro de porta, como coluna de luz. A inclinação encosta uma fita deitada a um declive (90° = a face fica de lado).", + "rotate_left": "↺ 90°", + "rotate_right": "↻ 90°", + "height_m": "Altura (m)", + "furn_sofa": "Sofá", + "furn_armchair": "Poltrona", + "furn_table": "Mesa", + "furn_chair": "Cadeira", + "furn_bed": "Cama", + "furn_nightstand": "Mesa de cabeceira", + "furn_wardrobe": "Roupeiro", + "furn_shelf": "Estante", + "furn_kitchen": "Móvel de cozinha", + "furn_worktop": "Bancada", + "furn_fridge": "Frigorífico", + "furn_fridge_smart": "Frigorífico inteligente (side by side)", + "furn_door_left": "Sensor da porta esquerda (lado do congelador)", + "furn_door_right": "Sensor da porta direita (lado do frigorífico)", + "fridge_hint": "Enquanto um sensor de porta indica aberta, a porta abre em 3D.", + "furn_stove": "Fogão", + "furn_sink": "Lava-loiça", + "furn_bathtub": "Banheira", + "furn_shower": "Duche", + "furn_wc": "Sanita", + "furn_washbasin": "Lavatório", + "furn_desk": "Secretária", + "furn_tv_board": "Móvel de TV", + "furn_plant": "Planta", + "furn_rug": "Tapete", + "furn_stairs": "Escada", + "furn_stairwell": "Abertura no piso", + "stairwell_hint": "Um buraco neste piso, por exemplo por cima da escada ou para um mezanino; de cima vê-se através. A abertura deve ficar dentro de uma divisão; várias aberturas podem sobrepor-se (para uma forma em L, por exemplo). As escadas do piso de baixo que chegam aqui também abrem o piso sozinhas.", + "tool_hole": "Abertura no piso", + "tool_roof": "Telhado", + "tool_energy": "Energia", + "tool_wall": "Parede", + "hint_wall": "Arraste para desenhar uma parede solta (divisória, meia parede) · Shift mantém-na direita · Alt sem encaixe", + "free_wall": "Parede", + "wall_length": "Comprimento (m)", + "wall_thickness": "Espessura da parede (m)", + "wall_height": "Altura (m)", + "wall_height_full": "Altura total da divisão", + "wall_slope": "Inclinada", + "wall_slope_start": "Altura no início (m)", + "wall_slope_end": "Altura no fim (m)", + "wall_slope_hint": "Parede inclinada: o topo vai direito da altura no início da parede (o canto com o número menor) à altura no fim. Ambas podem ultrapassar a altura do piso, por exemplo para um anexo com janelas altas.", + "wall_slope_off": "Voltar a uma parede reta", + "wall_none": "Sem parede", + "wall_none_hint": "Omitir esta parede por completo: para plantas abertas cujas divisões são um só espaço mas separadas no Home Assistant.", + "edge_thickness": "Espessura (m)", + "wall_thickness_hint": "Espessura desta parede, p. ex. 0,365 numa parede exterior grossa ou 0,115 numa divisória leve. Uma parede entre duas divisões usa a definição mais grossa.", + "wall_thickness_reset": "Espessura definida para a casa", + "wall_heights": "Alturas das paredes", + "wall_n": "Parede {a}–{b}", + "wall_view": "Vista de parede", + "wall_view_hint": "A parede de frente: arraste as suas portas, janelas e móveis ou escreva a distância.", + "wall_view_prev": "Parede anterior", + "wall_view_next": "Parede seguinte", + "wall_view_left": "Da esquerda (m)", + "wall_view_height": "Acima do chão (m)", + "wall_part": "parte {n}", + "wall_split_hint": "Dividir a parede aqui: a parte tem a sua própria altura, p. ex. 2,5 m ao lado de 1,7 m em linha", + "wall_split_at": "Ponto de divisão a partir do canto (m)", + "wall_join_hint": "Remover o ponto de divisão: a parte junta-se de novo à anterior", + "wall_exterior_short": "parede exterior", + "room_wall_hint": "Uma altura menor transforma a parede num parapeito ou balcão. Se duas divisões partilham a parede, vale a definição mais baixa. Janelas e portas nela terminam à altura da parede.", + "free_wall_hint": "Uma parede solta, p. ex. uma divisória. Onde encontra uma parede de divisão, o canto é chanfrado. Arraste as pegas para mover as pontas, arraste a linha para mover a parede toda.", + "free_wall_slope": "◢ Inclinada", + "free_wall_slope_hint": "A parede sobe ou desce de uma ponta à outra: a altura acima é a do início, esta a do fim.", + "free_wall_height_end": "Altura no fim (m)", + "stairwell_outside": "Esta abertura atravessa o limite de uma divisão e por isso não é recortada. Mova-a totalmente para uma divisão ou torne-a mais pequena.", + "hint_hole": "Arraste para desenhar uma abertura no piso (vão de escada, mezanino)", + "hint_roof": "Arraste para desenhar uma água do telhado · tocar seleciona · arrastar move · os cantos redimensionam", + "hint_energy": "Toque num campo solar para o selecionar · arraste para o mover, também para outra água · novos campos com + Campo solar à direita", + "furn_parking": "Lugar de estacionamento", + "furn_group_vehicles": "Estacionamento", + "parking_entity": "Sensor \"carro presente\"", + "parking_vehicle": "Veículo", + "parking_vehicle_none": "Nenhum", + "parking_no_pack": "Nenhum pacote de veículos importado; os veículos vêm do pacote \"Veículos\" (Extensões → Pacotes de móveis).", + "parking_scale": "Tamanho (%)", + "parking_type_entity": "Sensor do tipo de veículo (opcional)", + "parking_types": "Estado → veículo", + "parking_type_state": "Estado (p. ex. van)", + "parking_add_type": "+ Associação", + "parking_hint": "Sem sensor o veículo está sempre lá. Com um aparece assim que o sensor indica \"on\", \"home\" ou \"present\". Um sensor do tipo de veículo (p. ex. de uma análise de câmara com IA) escolhe o modelo: quando o estado corresponde a uma associação, também como palavra no texto, mostra-se esse veículo; caso contrário, o predefinido.", + "parking_too_tall": "O veículo ({car} m) é mais alto do que a divisão ({room} m).", + "furn_lamp_ceiling": "Candeeiro de teto", + "furn_lamp_downlight": "Foco embutido", + "furn_lamp_spot": "Foco saliente", + "furn_lamp_panel": "Painel LED", + "furn_lamp_uplight": "Projetor de chão", + "furn_lamp_bollard": "Baliza de caminho", + "furn_lamp_garden": "Projetor de jardim", + "furn_radiator": "Radiador", + "furn_robot_vacuum": "Robô aspirador", + "furn_entity_vacuum": "Robô aspirador", + "furn_entity_mower": "Robô corta-relva", + "pet_room_sensor": "Sensor de divisão do animal (opcional)", + "pet_room_hint": "Um sensor que diz a divisão onde o animal está – Bermuda ou ESPresense com uma etiqueta na coleira: em 3D passeia por essa divisão.", + "furn_entity_water": "Válvula ou interruptor", + "fridge_temp": "Temperatura do frigorífico", + "freezer_temp": "Temperatura do congelador", + "fridge_temp_hint": "O marcador mostra as temperaturas. Acima de 8 °C no frigorífico ou −12 °C no congelador acende como aviso.", + "spray_reach": "Alcance da água (m)", + "spray_hint": "Enquanto a válvula estiver aberta ou o interruptor ligado, o aspersor lança água em arcos à sua volta.", + "furn_robot_room": "Divisão atual (sensor)", + "robot_hint": "Enquanto o robô limpa no Home Assistant, percorre faixas em 3D pela divisão que indica (um sensor de «divisão atual», comparado com o nome da divisão ou da área), senão pela divisão da sua base. O percurso é simulado: o Home Assistant normalmente não sabe a posição exata. Regressa à base quando volta.", + "furn_lamp_pendant": "Candeeiro suspenso", + "furn_ceiling_fan": "Ventoinha de teto", + "furn_fan_entity": "Ventoinha", + "fan_hint": "A luz é o kit de luz da ventoinha (deixe vazio se não tiver). A ventoinha é encontrada na divisão ou escolhida aqui: em 3D as pás rodam tão depressa quanto ela, o ícone comuta-a, deslizar para cima/baixo muda a velocidade, um toque longo abre o menu rápido. A altura é quanto pende do teto (mais = uma haste mais longa).", + "room_ceiling": "Pé-direito", + "room_ceiling_tip": "Mais baixo que o piso (uma casa de banho sob a escada) ou mais alto (uma sala aberta até ao telhado): candeeiros de teto, ventoinhas, fitas LED e aparelhos de teto ficam pendurados aqui, e as paredes da divisão têm esta altura.", + "room_ceiling_through": "O teto ({ceiling} m) está acima da altura do piso ({floor} m): a divisão entra no piso de cima, as paredes sobem com ela e o piso de cima fica aberto sobre ela. O editor do piso superior mostra a área tracejada.", + "room_floor_offset": "Nível do piso (m)", + "room_floor_offset_hint": "Se o piso desta divisão estiver mais baixo ou mais alto que o andar (uma entrada rebaixada: −0,39), piso, paredes, portas, janelas e o que lá está acompanham; o teto fica. Junta os degraus como escada.", + "room_inner": "Interior {w} × {d}", + "room_inner_hint": "Medido de parede a parede: as paredes interiores tiram metade da espessura, as exteriores ficam fora do contorno.", + "floor_heating": "Piso radiante (opcional)", + "floor_heating_hint": "Enquanto o termóstato aquece (ou a válvula está aberta, o interruptor ligado), o chão da divisão brilha quente em 3D.", + "room_announce_speaker": "Altifalante para anúncios", + "room_announce_quiet": "Período de silêncio para anúncios", + "room_announce_hint": "Sem escolha, fala o altifalante colocado na divisão; senão um assistente de voz, um Echo ou um altifalante da área (nunca uma TV). No período de silêncio, anúncios para várias divisões deixam-na de fora; um só para ela chega na mesma.", + "ceiling_here": "Teto aqui", + "ceiling_here_hint": "Altura do teto exatamente neste ponto, p. ex. num teto inclinado. Vazio = o teto da divisão.", + "ceiling_slope": "Sob a vertente do telhado", + "ceiling_slope_hint": "Aqui o teto fica sob a vertente: o candeeiro pende da sua face inferior, mesmo por cima do seu lugar.", + "furn_lamp_floor": "Candeeiro de pé", + "furn_lamp_table": "Candeeiro de mesa", + "furn_lamp_wall": "Aplique de parede", + "furn_led_strip": "Fita LED", + "furn_group_lights": "Luzes", + "furn_entity_light": "Luz ou interruptor", + "furn_color_entity": "Cor e brilho de (opcional)", + "furn_color_entity_hint": "Para luzes que um relé (Shelly, atuador) liga e desliga enquanto a lâmpada conhece a sua cor e brilho: ligar/desligar vem do interruptor acima, cor e brilho desta entidade.", + "lamp_extra_light": "Lâmpada {n} (opcional)", + "lamp_extra_hint": "Um candeeiro com várias luzes – principal, luz de presença, anel ambiente: com a principal desligada brilha em 3D com a seguinte ligada, um pouco mais fraca. Ligue as luzes uma a uma no painel da divisão.", + "furn_entity_climate": "Aquecimento (termóstato)", + "lamp_hint": "Toque no candeeiro em 3D para o comutar, toque longo para o menu rápido. Também funcionam interruptores (p. ex. um relé para o candeeiro de teto): o candeeiro brilha enquanto está ligado. Os candeeiros de mesa assentam no móvel por baixo.", + "lamp_hint_pendant": "Altura = queda abaixo do teto. Toque em 3D para comutar, toque longo para detalhes.", + "theme": "Aspeto", + "version_hint": "Versão instalada do NextFloor (o frontend); a integração no Home Assistant indica {backend}", + "accent": "Cor de destaque", + "accent_hint": "Uma cor de destaque sua: linhas e arestas luminosas no aspeto néon, botões e marcadores; ↺ repõe o ciano néon", + "accent_reset": "Voltar ao ciano", + "theme_neon": "Néon", + "theme_blueprint": "Planta técnica", + "theme_day": "Dia", + "theme_auto": "Auto", + "clock": "Relógio", + "clock_none": "Nenhum", + "clock_top_left": "Em cima à esquerda", + "clock_top_right": "Em cima à direita", + "clock_bottom_left": "Em baixo à esquerda", + "clock_bottom_right": "Em baixo à direita", + "glass_walls": "Paredes de vidro", + "glass_walls_hint": "Quão opacas são as paredes através das quais se veem as divisões: à esquerda quase invisíveis, à direita opacas. Para este ecrã.", + "screen_name": "Nome deste ecrã", + "screen_name_hint": "Os anúncios aparecem em cada ecrã NextFloor aberto. Com um nome (p. ex. «Corredor»), um anúncio pode ir só para este ecrã. Sem visto, este ecrã fica em silêncio.", + "announce_on": "Anúncios ativos neste ecrã", + "announce_muted": "Anúncios silenciados neste ecrã", + "lock3d_on": "Bloquear o 3D (sem rodar, aproximar ou deslocar; os toques continuam a funcionar)", + "lock3d_off": "Desbloquear o 3D", + "walk": "Passear pela casa", + "travel": "Viagem no tempo: rever as últimas 24 horas ou 7 dias", + "travel_play": "Reproduzir", + "travel_pause": "Pausa", + "travel_loading": "A carregar o histórico …", + "travel_failed": "Não foi possível carregar o histórico.", + "travel_speed": "Velocidade", + "travel_speed_min": "1 min/s", + "travel_speed_10min": "10 min/s", + "travel_speed_hour": "1 h/s", + "travel_days": "dias", + "travel_live": "Em direto", + "card_travel_button": "Botão de viagem no tempo", + "walk_stop": "Parar de passear", + "walk_hint": "Arrastar: olhar em volta · W A S D / setas ou joystick: andar · roda: passo", + "card_walk_button": "Botão para passear", + "card_lock_button": "Botão do bloqueio 3D", + "backdrop": "Fundo próprio", + "backdrop_color": "Cor", + "backdrop_image": "Imagem (/local/… ou https://…)", + "backdrop_dim": "Escurecer", + "backdrop_hint": "Em vez do céu do aspeto, a casa fica à frente de uma cor ou imagem sua. Uma imagem em /config/www está acessível em /local/….", + "furnish": "Mobilar", + "split_3d": "3D ao lado", + "plan_dims": "Medidas", + "plan_dims_hint": "Escreve o comprimento em cada lado da divisão.", + "mount_height": "Altura acima do chão (m)", + "side_open": "Abrir a barra lateral", + "side_close": "Fechar", + "side_details": "Detalhes da seleção", + "side_pin": "Fixar", + "side_pinned": "Fixada", + "side_pin_hint": "Fixada, a barra lateral fica aberta; caso contrário recolhe-se ao lado da vista 3D quando nada está selecionado", + "split_3d_hint": "3D em direto ao lado da planta: arraste e rode móveis e dispositivos ali, com anular, guardado com a planta", + "size_w": "Largura (m)", + "size_d": "Profundidade (m)", + "size_h": "Altura (m)", + "furnish_hint": "Arraste móveis, candeeiros e dispositivos · os móveis encaixam nas paredes · toque num para o rodar, definir a altura e a montagem", + "done": "Concluído", + "heatmap": "Mapa de calor", + "heat_off": "Normal", + "heat_short_temperature": "Temp.", + "heat_short_humidity": "Humidade", + "heat_short_co2": "CO₂", + "heat_short_mould": "Bolor", + "heat_short_power": "Consumo", + "heat_short_comfort": "Conforto", + "heat_short_sun": "Sol", + "heat_short_wifi": "Wi-Fi", + "heat_short_values": "Valores", + "heat_temperature": "Temperatura", + "heat_humidity": "Humidade", + "heat_co2": "CO₂", + "heat_mould": "Bolor", + "heat_power": "Consumo de energia", + "heat_comfort": "Índice de conforto", + "heat_sun": "Sol hoje", + "room_sun_hours": "{h} h de sol hoje ({facing})", + "open_since": "aberto há {time}", + "presence_now": "alguém está", + "presence_last": "visto há {time}", + "comfort_n": "Conforto {n}", + "empty_lights_hint": "{n} luzes acesas, ninguém há {min} min.", + "empty_lights_off": "Apagar luzes", + "open_heating_hint": "{n} janelas abertas com o aquecimento ligado.", + "open_heating_off": "Desligar aquecimento", + "room_clean": "Limpeza (script ou botão)", + "room_clean_hint": "Um script ou botão que envia o robô aspirador para esta divisão (p. ex. a limpeza por divisão da tua integração). O painel da divisão mostra então «🧹 Aspirar».", + "room_clean_run": "Aspirar", + "room_clean_run_hint": "Envia o robô aspirador para esta divisão.", + "shade_hint": "Sol em {n} janelas a {temp} – baixar os estores?", + "shade_close": "Baixar", + "room_sun_year": "Sol ao longo do ano", + "room_sun_year_hint": "As horas de sol pelas janelas exteriores da divisão no dia 15 de cada mês.", + "room_energy": "hoje {today} · mês {month}", + "room_energy_hint": "Das estatísticas dos sensores de potência dos dispositivos da divisão; o custo do mês com a tarifa da casa.", + "heat_summer": "verão", + "heat_winter": "inverno", + "air_co2": "arejar (CO₂)", + "air_humidity": "arejar (húmido)", + "air_mould": "risco de bolor – arejar", + "room_curve_hint": "A temperatura da divisão nas últimas 24 horas", + "heat_values": "Valores junto aos nomes das divisões", + "heat_wifi": "Wi-Fi", + "wifi_aps": "{n} pontos de acesso · {clients} dispositivos", + "wifi_network": "Rede: {online} online · {offline} offline", + "wifi_none": "Coloque pontos de acesso ou routers dos packs (Casa inteligente 2) e ligue-os a uma entidade do seu dispositivo.", + "wifi_clients": "{n} dispositivos", + "heat_none_found": "Não há sensores adequados nas áreas das divisões.", + "markers": "Marcadores", + "markers_none": "Nenhum", + "markers_important": "Importantes", + "markers_all": "Todos", + "furn_stool": "Banco", + "furn_coffee_table": "Mesa de centro", + "furn_tv_wall": "TV (parede)", + "furn_sideboard": "Aparador", + "furn_table_round": "Mesa redonda", + "furn_bench": "Banco corrido", + "furn_corner_bench": "Banco de canto", + "furn_bar_stool": "Banco alto", + "furn_kitchen_wall": "Armário superior", + "furn_kitchen_tall": "Coluna com forno", + "furn_island": "Ilha de cozinha", + "furn_dishwasher": "Máquina de lavar loiça", + "furn_bunk_bed": "Beliche", + "furn_dresser": "Cómoda", + "furn_washer": "Máquina de lavar roupa", + "furn_dryer": "Máquina de secar", + "furn_office_chair": "Cadeira de escritório", + "furn_tall_cabinet": "Armário alto", + "furn_coat_rack": "Bengaleiro", + "furn_group_living": "Estar", + "furn_group_dining": "Jantar", + "furn_group_energy": "Energia e solar", + "energy_devices": "Dispositivos", + "wallbox_charging": "a carregar", + "wallbox_plugged": "ligado", + "furn_soc": "Estado de carga (%)", + "furn_export": "Potência injetada (W, sensor separado, opcional)", + "furn_export_hint": "Se o contador indicar consumo e injeção em dois sensores (p. ex. Growatt, Tibber Pulse), use o sensor de consumo como potência acima e o de injeção aqui. Um sensor com sinal não precisa disto.", + "meter_parent": "Depende do contador", + "meter_parent_none": "nenhum (contador principal)", + "meter_main": "Contador principal", + "meter_unmetered": "{w} não medidos", + "meter_device_hint": "Se o dispositivo estiver atrás de um subcontador (p. ex. uma central de varanda num apartamento), a sua potência conta para esse apartamento. O subcontador tem de medir nos dois sentidos (− = injeção); se só contar o consumo, o consumo do apartamento sai demasiado alto quando há excedente.", + "meter_sub_power": "Potência do circuito (W, + = consumida, − = injetada)", + "meter_floors": "Alimenta os pisos", + "meter_sub_hint": "Um subcontador mede o seu circuito, p. ex. um apartamento. Os dispositivos dos pisos marcados ficam ligados a ele em 3D em vez do contador principal; o que o contador principal conta a mais aparece como «Comum (resto)» no balanço.", + "furn_charge": "Potência de carga (W, sensor separado, opcional)", + "furn_charge_hint": "Se a bateria indicar carga e descarga em dois sensores (p. ex. Anker Solix), use o sensor de descarga como potência acima e o de carga aqui. Um sensor com sinal não precisa disto.", + "furn_wallbox_status": "Estado (a carregar, ligado)", + "energy_only_note": "⚡ Energia: aqui só se podem mover campos solares e dispositivos de energia; divisões e móveis estão bloqueados.", + "roof_only_note": "🏠 Telhado: aqui só se podem mover águas e janelas de telhado; divisões e móveis estão bloqueados.", + "energy_devices_hint": "Contador, inversores, baterias domésticas, wallboxes e a ligação à rede adicionam-se aqui: no piso escolhido acima, móveis na planta. Com um sensor de potência mostram os seus watts; o contador usa o sensor de rede, uma string escolhe o seu inversor. Vários inversores e baterias (p. ex. uma central de varanda adicional) também funcionam: cada um com o seu sensor.", + "energy_routes": "Percursos de cabo", + "energy_routes_hint": "Por onde um cabo passa realmente: o fluxo segue os teus pontos em vez de um arco pela casa. Sem percurso fica o arco. Os consumidores mantêm o seu arco.", + "route_conn_solar": "{name} → inversor", + "route_conn_battery": "Bateria ↔ casa", + "route_conn_inverter": "Inversor → casa", + "route_conn_grid": "Rede ↔ casa", + "route_conn_meter": "{name} ↔ contador superior", + "route_conn_device": "{name} ↔ subcontador", + "route_points": "{n} pontos", + "route_none": "arco direto", + "route_draw": "Desenhar percurso", + "route_redraw": "Redesenhar", + "route_drawing": "Toca na planta nos pontos por onde o cabo passa, de uma ponta à outra; muda de piso onde atravessa um teto. {n} pontos.", + "route_undo": "Último ponto", + "route_done": "Concluído", + "route_cable": "Mostrar como cabo", + "route_cable_hint": "Desenha o percurso como um cabo visível, não só como a linha fina sob as partículas.", + "solar_fields": "Campos solares", + "solar_hint": "Ponha módulos no telhado: ficam na inclinação da água; num telhado plano ficam em estruturas. Arraste um campo na planta para o mover.", + "solar_no_roof": "Os campos solares precisam de um telhado: de duas águas ou plano em Definições, ou águas aqui na ferramenta Telhado.", + "solar_face_gone": "falta a água do telhado", + "solar_summary": "{n} módulos · {kwp} kWp", + "solar_add": "Campo solar", + "solar_field": "Campo solar", + "solar_face": "Água do telhado", + "solar_rows": "Filas", + "solar_cols": "Módulos por fila", + "solar_portrait": "Vertical", + "solar_landscape": "Horizontal", + "solar_u": "Distância à borda (m)", + "solar_v": "Distância ao beiral (m)", + "solar_tilt": "Inclinação das estruturas (°)", + "solar_rack_ew": "Estrutura este-oeste", + "solar_rack_ew_hint": "Cada segunda fila fica virada para o outro lado, os pares costas com costas – baixo e junto, como em muitas coberturas planas.", + "solar_rack_tilt": "Suporte (° de inclinação extra)", + "solar_flip": "Inclinar para o outro lado", + "solar_partial": "só cabem {n} de {total} na água", + "solar_form_hint": "Os módulos que ultrapassariam a água são omitidos. «Preencher água» põe tantos módulos quantos couberem. kWp calculados com 400 W por módulo.", + "solar_fit": "Preencher água", + "roof_windows": "Janelas de telhado", + "roof_window": "Janela de telhado", + "roof_windows_hint": "As janelas de telhado ficam na água, com estore e contactos como as janelas. Arraste-as na planta, também para outra água.", + "roof_window_tilt": "Contacto basculante", + "roof_window_name": "Nome (opcional)", + "roof_window_motor": "Motor da janela (cobertura, opcional)", + "roof_window_motor_hint": "Um motor de janela (Velux, Roto, Fakro) indica a sua posição como cobertura: a folha abre em 3D tanto quanto o motor. Um contacto ou contacto basculante também funciona sem motor.", + "roof_window_hint": "Aberta, a folha abre para fora com dobradiça em cima; basculante, um pouco; o aro brilha quente; o estore desce sobre o vidro a partir de cima. Numa água do telhado a janela corta um buraco na inclinação, para o sótão ver através dela.", + "solar_ground": "Independente (jardim, telhado da garagem …)", + "solar_add_ground": "Independente", + "solar_base": "Altura da superfície (m, 0 = solo)", + "solar_add_wall": "Numa parede", + "solar_wall": "Parede", + "solar_v_wall": "Altura acima do chão (m)", + "solar_tilt_wall": "Inclinação a partir da parede (°, 90 = pala)", + "solar_flip_wall": "Afastado em baixo em vez de em cima", + "solar_rotation": "Rotação (°)", + "solar_name": "Nome", + "solar_name_hint": "p. ex. string 1 sul", + "solar_module_w": "Largura do módulo (m)", + "solar_module_h": "Altura do módulo (m)", + "solar_wp": "Potência do módulo (Wp)", + "solar_string": "String", + "solar_strings": "Strings", + "solar_string_none": "Sem string", + "solar_string_new": "Nova string", + "solar_string_n": "String {n}", + "solar_string_name": "Nome da string", + "solar_string_entity": "Potência FV da string", + "solar_string_inverter": "Inversor", + "solar_string_inverter_none": "Nenhum inversor escolhido", + "inverter_strings": "Strings neste inversor: {names}", + "inverter_strings_none": "Ainda sem string neste inversor; atribua-a num campo solar em String › Inversor.", + "solar_string_inverter_missing": "Ainda sem inversor na planta (adicione um abaixo em Dispositivos)", + "solar_string_hint": "Campos da mesma string pertencem juntos, também em telhados diferentes (p. ex. 5 módulos na casa e 5 na garagem). Sensor e inversor contam para toda a string.", + "solar_string_sum": "{fields} campos · {n} módulos · {kwp} kWp", + "solar_face_size": "Água {w} × {h} m (ao longo do beiral × subindo a inclinação)", + "solar_cols_hint": "Um número para filas de igual comprimento, ou uma lista para filas próprias: «4, 4, 3» (a partir do beiral).", + "solar_align_left": "Esquerda", + "solar_align_center": "Centro", + "solar_align_right": "Direita", + "solar_look_black": "Full black", + "solar_look_blue": "Azul", + "solar_pick": "Módulos ligar/desligar um a um", + "solar_pick_all": "Todos ligados de novo", + "solar_pick_hint": "Toque num módulo na planta para o tirar ou voltar a pôr. Os retirados aparecem tracejados.", + "solar_entity": "Potência FV deste campo (p. ex. a sua string)", + "solar_main": "Telhado principal", + "solar_section": "Água {n}", + "solar_flat": "telhado plano", + "compass_n": "norte", + "compass_ne": "nordeste", + "compass_e": "este", + "compass_se": "sudeste", + "compass_s": "sul", + "compass_sw": "sudoeste", + "compass_w": "oeste", + "compass_nw": "noroeste", + "furn_meter": "Contador de eletricidade", + "furn_grid_point": "Ligação à rede", + "grid_point_hint": "A ligação à rede fica aqui: o ponto de entrega ao distribuidor, p. ex. no fim do acesso. Móvel na planta.", + "furn_model": "Modelo", + "inverter_std": "Padrão (unidade de parede com ecrã)", + "inverter_slim": "Fino e alto (faixa de luz)", + "inverter_hybrid": "Híbrido (mostrador redondo, ventoinhas)", + "battery_std": "Torre (módulos empilhados)", + "battery_wall": "Bateria de parede (plana, suspensa)", + "battery_cube": "Compacta (bateria de varanda)", + "furn_inverter": "Inversor solar", + "furn_home_battery": "Bateria doméstica", + "furn_wallbox": "Wallbox", + "furn_group_kitchen": "Cozinha", + "furn_group_sleeping": "Dormir", + "furn_group_bath": "Banho e lavandaria", + "furn_group_work": "Trabalho e outros", + "furn_entity": "Dispositivo (interruptor, tomada …)", + "furn_state_entity": "Estado de (opcional)", + "furn_state_entity2": "Segundo estado (a outra metade)", + "furn_state_split": "Metades", + "furn_state_left_right": "Esquerda / direita", + "furn_state_top_bottom": "Baixo / cima (beliche)", + "furn_state_hint": "O elemento brilha enquanto a entidade indica ligado, ocupado ou em casa: uma cama com tapete de ocupação, uma poltrona, a sauna. Duas entidades iluminam as metades: esquerda e direita, baixo e cima num beliche.", + "furn_entity_tv": "TV (leitor multimédia ou tomada inteligente)", + "fix": "Fixar", + "unfix": "Soltar", + "fix_hint": "Fixo: já não pode ser movido por engano (tecla L, clique direito ou toque longo)", + "fixed_drag_hint": "🔒 Fixo: solte-o primeiro para o mover (cadeado no formulário, clique direito ou tecla L)", + "fixed_delete_confirm": "Este elemento está fixo. Eliminar mesmo assim?", + "lock_plan": "🔒 Planta", + "lock_plan_hint": "Bloquear a planta: divisões, paredes, portas, janelas e áreas exteriores não podem ser movidas por engano. Móveis e dispositivos ficam livres.", + "start_view": "Vista inicial", + "start_view_hint": "A vista 3D, o cartão e o quiosque abrem a casa com esta vista, p. ex. do lado do jardim. Rode, aproxime e mova a casa no painel 3D à direita até estar bem e depois memorize-a.", + "start_view_card": "Se um cartão tiver de abrir com outra vista, ponha esta linha na sua configuração YAML.", + "start_view_set": "Memorizar a vista 3D atual como inicial", + "start_view_reset": "Predefinida", + "start_view_saved": "Está guardada uma vista inicial própria.", + "ctx_rotate": "Rodar 90°", + "devices_placed_in": "em {room}", + "devices_narrow": "mais {n}: refine a pesquisa", + "climate": "Clima da divisão", + "climate_temperature": "Temperatura", + "climate_humidity": "Humidade", + "climate_co2": "CO₂", + "climate_hint": "Estes sensores contam para o mapa de calor e o painel da divisão. «Automático» usa os sensores da área e os colocados na divisão, mas não temperaturas de dispositivos (impressora 3D, bomba de calor, ida …).", + "climate_more": "… e outro sensor (média)", + "plan_locked": "Planta bloqueada", + "plan_lock": "Bloquear a planta", + "plan_unlock": "Desbloquear a planta", + "opening_mark": "Destacar em 3D", + "opening_mark_open": "Quando aberta", + "opening_mark_closed": "Quando fechada (p. ex. WC)", + "opening_mark_hint": "Uma janela ou porta destacada brilha quente. «Quando fechada» precisa de um contacto; sem sensor nada é destacado.", + "window_opens": "Abre", + "window_opens_turn": "Oscilobatente (para dentro)", + "window_opens_slide": "De correr (janela de correr, porta elevatória)", + "window_opens_top": "Projetante (a parte de baixo abre para fora)", + "window_opens_hint": "De correr: a folha do lado da dobradiça desliza à frente da fixa; com duas folhas, as duas do meio deslizam para fora. As projetantes abrem com o contacto ou um sensor de inclinação.", + "marker_show": "Marcador em 3D", + "marker_show_hint": "Automático segue o interruptor Nenhum / Importantes / Todos da vista 3D. Mostrar sempre e Ocultar aplicam-se na mesma (exceto com Nenhum).", + "pin_shift": "Mover o marcador", + "pin_shift_up": "↑ altura", + "pin_shift_hint": "Quando os dispositivos estão próximos, desloque aqui o marcador um pouco para o lado ou para cima (em metros); o dispositivo fica onde está.", + "marker_show_auto": "Automático", + "marker_show_always": "Mostrar sempre", + "marker_show_no_power": "Sem watts", + "marker_show_active": "Só quando ativo", + "marker_show_never": "Ocultar", + "marker_icon": "Símbolo próprio (ícone Material Design)", + "device_name": "Nome próprio (opcional)", + "show_name": "Mostrar o nome sob o marcador em 3D", + "card_marker_names": "Nomes próprios nos marcadores", + "card_marker_names_hint": "Cada dispositivo com nome próprio mostra-o pequeno sob o marcador: três termómetros no jardim distinguem-se.", + "device_name_hint": "Um nome só para a planta e o painel da divisão, p. ex. \"Luz de destaque da ilha\"; a entidade no Home Assistant fica como está.", + "device_simple": "Só interruptor no painel da divisão", + "device_simple_hint": "O painel da divisão mostra para este candeeiro só o interruptor, sem brilho, temperatura de cor e cores.", + "floor_turn": "Rodar 90°", + "floor_shift_all": "Levar todos os pisos (casa inteira)", + "floor_shift_all_hint": "Deslocar e rodar atuam em todos os pisos com as águas do telhado, áreas exteriores, dispositivos de energia e contador: a casa inteira move-se como um todo.", + "floor_turn_hint": "Roda tudo no piso 90° no sentido horário à volta do centro das suas divisões, quando um piso foi desenhado ao contrário. Três vezes = 270°.", + "marker_icon_hint": "O nome de um ícone Material Design como no Home Assistant, p. ex. mdi:thermometer ou mdi:water-alert. Vazio = o símbolo do tipo de dispositivo.", + "furn_power": "Sensor de potência (W)", + "furn_links_hint": "Com um sensor de potência o elemento mostra os seus watts e participa no fluxo de energia.", + "furn_links_hint_tv": "O ecrã brilha enquanto a TV está ligada, na cor da app (Netflix, YouTube …); a etiqueta mostra a app ou o título.", + "stairs_hint": "A escada sobe para trás (afastando-se da aresta frontal marcada) e abre o teto do piso de cima.", + "floor_lights": "{n} luzes acesas", + "floor_open": "{n} abertas", + "floor_persons": "{n} pessoas", + "energy_consumption": "Consumo", + "energy_grid_import": "Consumo da rede", + "energy_grid_export": "Injeção", + "energy_solar": "Solar", + "energy_battery": "Bateria", + "energy_tariff": "Tarifa", + "energy": "Energia", + "energy_meter": "Contador", + "energy_grid": "Rede (W, + = consumo)", + "energy_solar_sensor": "Produção solar (W)", + "energy_battery_sensor": "Potência da bateria (W, + = descarga)", + "energy_battery_soc": "Carga da bateria (%)", + "energy_tariff_sensor": "Tarifa (p. ex. €/kWh)", + "energy_gas": "Contador de gás (opcional)", + "energy_water": "Contador de água (opcional)", + "energy_meters_hint": "O gás e a água aparecem com o balanço da casa – na barra de energia e no cartão da casa: um sensor com o caudal atual (m³/h, l/min) ou a leitura de hoje.", + "energy_gas_short": "Gás", + "energy_water_short": "Água", + "energy_invert": "Inverter sinal", + "energy_hint": "Os consumidores são dispositivos colocados com um sensor de potência (W): o próprio sensor ou um do mesmo dispositivo.", + "energy_balance": "Balanço energético", + "energy_balance_hint": "Rede, solar e bateria vêm dos dispositivos da planta: contador, inversor e bateria doméstica. Aqui pode escolher outros sensores, inverter sinais e definir o consumo da casa.", + "energy_rest": "Comum (resto)", + "energy_advanced": "Modo de energia avançado", + "energy_advanced_on": "Usar subcontadores", + "energy_show_unmetered": "Mostrar o consumo não medido nos subcontadores", + "energy_show_unmetered_hint": "A etiqueta de um subcontador mostra então o que os seus pisos consomem e quanto disso nenhum dispositivo colocado mede, p. ex. «500 W · 450 W não medidos». Caso contrário mostra a leitura do contador.", + "energy_advanced_hint": "Para subcontadores, p. ex. um por apartamento atrás de um contador principal: um contador pode então depender de outro e alimentar os seus pisos. Desligado = o primeiro contador é a ligação à rede, os restantes são consumidores.", + "energy_consumption_sensor": "Consumo da casa (W, senão a partir do balanço)", + "energy_import_prefs": "Obter do painel de energia", + "energy_import_done": "{n} sensores obtidos; verifique os sinais.", + "energy_import_none": "Não foram encontrados sensores de potência (W) adequados no painel de energia; escolha-os à mão.", + "energy_import_failed": "O painel de energia do Home Assistant não está configurado.", + "tool_meter": "Contador", + "hint_meter": "Toque no local do contador", + "presence": "Presença", + "presence_hint": "Sensor de divisão por pessoa (p. ex. ESPresense, Bermuda): o seu estado indica a divisão ou a área.", + "presence_sensor": "Sensor de divisão", + "no_persons": "Não há pessoas no Home Assistant.", + "packname:nextfloor.a_bad": "Casa de banho", + "pack:nextfloor.a_bad:vanity_60": "Móvel de lavatório 60 com armário", + "pack:nextfloor.a_bad:vanity_80": "Móvel de lavatório 80 com armário", + "pack:nextfloor.a_bad:vanity_100": "Móvel de lavatório 100 com armário", + "pack:nextfloor.a_bad:vanity_double_120": "Lavatório duplo 120", + "pack:nextfloor.a_bad:vanity_double_160": "Lavatório duplo", + "pack:nextfloor.a_bad:pedestal_basin": "Lavatório de coluna", + "pack:nextfloor.a_bad:bathtub_builtin": "Banheira encastrada", + "pack:nextfloor.a_bad:bathtub_corner": "Banheira de canto", + "pack:nextfloor.a_bad:bathtub_corner_compact": "Banheira de canto compacta", + "pack:nextfloor.a_bad:bathtub_free": "Banheira de pousar", + "pack:nextfloor.a_bad:whirlpool_indoor": "Hidromassagem interior", + "pack:nextfloor.a_bad:shower_corner_90": "Duche de canto 90 × 90", + "pack:nextfloor.a_bad:shower_niche_120": "Duche em nicho 120 × 90", + "pack:nextfloor.a_bad:shower_walkin_140": "Duche walk-in 140 × 90", + "pack:nextfloor.a_bad:shower_walkin_120": "Duche walk-in", + "pack:nextfloor.a_bad:shower_rain_led": "Chuveiro de chuva com LED", + "pack:nextfloor.a_bad:toilet_close": "Sanita com autoclismo acoplado", + "pack:nextfloor.a_bad:toilet_hung": "Sanita suspensa", + "pack:nextfloor.a_bad:toilet_hung_compact": "Sanita suspensa (compacta)", + "pack:nextfloor.a_bad:bidet": "Bidé", + "pack:nextfloor.a_bad:cabinet_tall": "Coluna alta de casa de banho", + "pack:nextfloor.a_bad:cabinet_mid": "Armário de casa de banho de meia altura", + "pack:nextfloor.a_bad:mirror_round_light": "Espelho redondo com luz", + "pack:nextfloor.a_bad:mirror_80": "Espelho 80 × 60 com luz", + "pack:nextfloor.a_bad:mirror_led_100": "Espelho LED 100 × 70 com relógio", + "pack:nextfloor.a_bad:mirror_cabinet": "Armário com espelho e luz", + "pack:nextfloor.a_bad:wall_shelf_bath": "Prateleira de parede de casa de banho", + "pack:nextfloor.a_bad:towel_rail": "Toalheiro com toalha", + "pack:nextfloor.a_bad:towel_radiator": "Radiador toalheiro", + "pack:nextfloor.a_bad:towel_heater_electric": "Toalheiro elétrico", + "pack:nextfloor.a_bad:sauna": "Sauna", + "pack:nextfloor.a_bad:bath_fan": "Extrator de casa de banho", + "pack:nextfloor.a_bad:washer_cabinet": "Armário para máquina de lavar", + "pack:nextfloor.a_bad:washer_under_vanity": "Máquina de lavar sob o lavatório", + "pack:nextfloor.a_bad:laundry_basket": "Cesto de roupa", + "pack:nextfloor.a_bad:laundry_cabinet": "Armário de lavandaria com cesto", + "pack:nextfloor.a_bad:ladder_shelf": "Estante escada com toalhas", + "pack:nextfloor.a_bad:plant_stool": "Planta sobre banco", + "packname:nextfloor.a_buero": "Escritório e gaming", + "pack:nextfloor.a_buero:desk_standing": "Secretária regulável", + "pack:nextfloor.a_buero:desk_standing_bare": "Secretária regulável sem monitor", + "pack:nextfloor.a_buero:chair_gaming": "Cadeira gaming", + "pack:nextfloor.a_buero:chair_office": "Cadeira de escritório ergonómica", + "pack:nextfloor.a_buero:sim_cockpit": "Cockpit de sim racing", + "pack:nextfloor.a_buero:server_rack_42u": "Rack de servidores (42U)", + "pack:nextfloor.a_buero:filing_cabinet": "Arquivador", + "pack:nextfloor.a_buero:whiteboard": "Quadro branco", + "pack:nextfloor.a_buero:triple_monitor": "Configuração de três monitores", + "pack:nextfloor.a_buero:bookcase_wall": "Parede de estantes", + "pack:nextfloor.a_buero:desk_lamp": "Candeeiro de secretária", + "pack:nextfloor.a_buero:desk_lamp_led": "Candeeiro de secretária LED", + "pack:nextfloor.a_buero:arcade_cabinet": "Máquina arcade", + "pack:nextfloor.a_buero:office_lounge_sofa": "Sofá lounge de escritório", + "pack:nextfloor.a_buero:monitor_light_bar": "Monitor com barra de luz", + "pack:nextfloor.a_buero:printer_laser": "Impressora laser", + "pack:nextfloor.a_buero:wifi_router": "Router Wi-Fi", + "pack:nextfloor.a_buero:phone_booth": "Cabine telefónica", + "pack:nextfloor.a_buero:printer_3d": "Impressora 3D", + "pack:nextfloor.a_buero:printer_cube": "Impressora 3D fechada tipo cubo", + "pack:nextfloor.a_buero:printer_multi": "Impressora 3D cubo com unidade multicor", + "pack:nextfloor.a_buero:printer_large": "Impressora 3D grande de bico duplo", + "pack:nextfloor.a_buero:printer_open": "Impressora 3D aberta compacta", + "pack:nextfloor.a_buero:printer_resin": "Impressora 3D de resina", + "pack:nextfloor.a_buero:filament_dryer": "Secador de filamento", + "pack:nextfloor.a_buero:filament_rack": "Suporte de parede para filamento", + "packname:nextfloor.a_fitness": "Fitness", + "pack:nextfloor.a_fitness:treadmill": "Passadeira", + "pack:nextfloor.a_fitness:power_rack": "Power rack com banco", + "pack:nextfloor.a_fitness:rowing_machine": "Máquina de remo", + "pack:nextfloor.a_fitness:spin_bike": "Bicicleta de spinning", + "pack:nextfloor.a_fitness:dumbbell_rack": "Suporte de halteres", + "pack:nextfloor.a_fitness:punching_bag": "Saco de boxe", + "pack:nextfloor.a_fitness:yoga_mat": "Tapete de ioga com bloco", + "pack:nextfloor.a_fitness:elliptical": "Elíptica", + "pack:nextfloor.a_fitness:mirror_wall_gym": "Parede de espelhos", + "pack:nextfloor.a_fitness:exercise_ball": "Bola de exercício", + "pack:nextfloor.a_fitness:wall_bars": "Espaldar", + "pack:nextfloor.a_fitness:fitness_mirror_smart": "Espelho de fitness inteligente", + "pack:nextfloor.a_fitness:bike_trainer": "Bicicleta em rolo inteligente", + "pack:nextfloor.a_fitness:sauna_cabin": "Cabine de sauna", + "pack:nextfloor.a_fitness:massage_chair": "Cadeira de massagem", + "pack:nextfloor.a_fitness:kettlebells": "Conjunto de kettlebells", + "pack:nextfloor.a_fitness:water_cooler": "Dispensador de água", + "packname:nextfloor.a_garten": "Jardim e terraço", + "pack:nextfloor.a_garten:grill_gas": "Grelhador a gás", + "pack:nextfloor.a_garten:lounge_set": "Conjunto lounge", + "pack:nextfloor.a_garten:sun_lounger_adj": "Espreguiçadeira", + "pack:nextfloor.a_garten:parasol": "Guarda-sol", + "pack:nextfloor.a_garten:pergola": "Pérgula", + "pack:nextfloor.a_garten:raised_bed": "Canteiro elevado", + "pack:nextfloor.a_garten:greenhouse": "Estufa", + "pack:nextfloor.a_garten:hot_tub": "Jacuzzi exterior", + "pack:nextfloor.a_garten:fire_bowl": "Braseira", + "pack:nextfloor.a_garten:garden_torch": "Tocha de jardim", + "pack:nextfloor.a_garten:play_tower": "Torre de brincar com escorrega", + "pack:nextfloor.a_garten:garden_shed": "Casota de jardim", + "pack:nextfloor.a_garten:trampoline": "Trampolim", + "pack:nextfloor.a_garten:flower_pots": "Vasos de flores (conjunto de 3)", + "pack:nextfloor.a_garten:sprinkler": "Aspersor de relva", + "pack:nextfloor.a_garten:valve_box": "Caixa de válvulas de rega", + "pack:nextfloor.a_garten:rain_barrel": "Depósito de água da chuva", + "pack:nextfloor.a_garten:garden_lantern": "Lanterna de jardim", + "pack:nextfloor.a_garten:outdoor_kitchen": "Cozinha exterior", + "pack:nextfloor.a_garten:hammock": "Rede de descanso com suporte", + "pack:nextfloor.a_garten:patio_heater": "Aquecedor de esplanada", + "pack:nextfloor.a_garten:tree_oak": "Carvalho", + "pack:nextfloor.a_garten:tree_lime": "Tília", + "pack:nextfloor.a_garten:tree_birch": "Bétula", + "pack:nextfloor.a_garten:tree_maple": "Ácer", + "pack:nextfloor.a_garten:tree_fruit": "Árvore de fruto", + "pack:nextfloor.a_garten:tree_spruce": "Abeto", + "pack:nextfloor.a_garten:tree_pine": "Pinheiro", + "pack:nextfloor.a_garten:tree_thuja": "Tuia", + "pack:nextfloor.a_garten:shrub": "Arbusto", + "pack:nextfloor.a_garten:shrub_flowering": "Arbusto florido", + "pack:nextfloor.a_garten:brush_wild": "Mato (zona selvagem)", + "pack:nextfloor.a_garten:tree_group_3": "Grupo de árvores (3)", + "pack:nextfloor.a_garten:bin_rest_120": "Contentor de indiferenciados 120 l", + "pack:nextfloor.a_garten:bin_rest_240": "Contentor de indiferenciados 240 l", + "pack:nextfloor.a_garten:bin_bio_120": "Contentor de orgânicos 120 l", + "pack:nextfloor.a_garten:bin_bio_240": "Contentor de orgânicos 240 l", + "pack:nextfloor.a_garten:bin_paper_120": "Contentor de papel 120 l", + "pack:nextfloor.a_garten:bin_paper_240": "Contentor de papel 240 l", + "pack:nextfloor.a_garten:bin_yellow_120": "Contentor de recicláveis 120 l", + "pack:nextfloor.a_garten:bin_yellow_240": "Contentor de recicláveis 240 l", + "pack:nextfloor.a_garten:mailbox": "Caixa de correio", + "pack:nextfloor.a_garten:mailbox_post": "Caixa de correio em poste", + "pack:nextfloor.a_garten:awning_300": "Toldo 3 m", + "pack:nextfloor.a_garten:awning_400": "Toldo 4 m", + "pack:nextfloor.a_garten:awning_500": "Toldo 5 m", + "pack:nextfloor.a_garten:sliding_gate": "Portão de correr", + "packname:nextfloor.a_haustechnik": "Lavandaria e instalações técnicas", + "pack:nextfloor.a_haustechnik:gas_boiler": "Caldeira de condensação a gás", + "pack:nextfloor.a_haustechnik:heat_pump_tower": "Unidade interior de bomba de calor (torre hidráulica)", + "pack:nextfloor.a_haustechnik:buffer_tank": "Depósito de inércia", + "pack:nextfloor.a_haustechnik:heating_manifold": "Coletor de piso radiante", + "pack:nextfloor.a_haustechnik:ventilation_unit": "Ventilação com recuperação de calor", + "pack:nextfloor.a_haustechnik:split_indoor": "Ar condicionado split (unidade interior, parede)", + "pack:nextfloor.a_haustechnik:split_outdoor": "Ar condicionado split (unidade exterior)", + "pack:nextfloor.a_haustechnik:radiator_tall": "Radiador de design alto", + "pack:nextfloor.a_haustechnik:meter_cabinet": "Quadro de contadores", + "pack:nextfloor.a_haustechnik:water_softener": "Descalcificador", + "pack:nextfloor.a_haustechnik:water_pump": "Bomba de água doméstica", + "pack:nextfloor.a_haustechnik:drip_tray": "Tabuleiro com sensor de fugas", + "pack:nextfloor.a_haustechnik:chest_freezer": "Arca congeladora", + "pack:nextfloor.a_haustechnik:ironing_station": "Ferro com caldeira", + "pack:nextfloor.a_haustechnik:drying_rack": "Estendal", + "pack:nextfloor.a_haustechnik:rotary_line": "Estendal rotativo", + "pack:nextfloor.a_haustechnik:pantry_shelf_util": "Estante de despensa", + "pack:nextfloor.a_haustechnik:utility_sink": "Tanque de lavar", + "pack:nextfloor.a_haustechnik:laundry_basket_util": "Cesto de roupa", + "pack:nextfloor.a_haustechnik:vacuum_station": "Estação de aspirador sem fio", + "packname:nextfloor.a_haustiere": "Animais de estimação", + "pack:nextfloor.a_haustiere:cat_tree_large": "Árvore para gatos (grande)", + "pack:nextfloor.a_haustiere:scratch_post": "Poste arranhador", + "pack:nextfloor.a_haustiere:scratch_board_wall": "Arranhador de parede", + "pack:nextfloor.a_haustiere:cat_cave": "Caverna para gatos", + "pack:nextfloor.a_haustiere:cat_bed_round": "Cama redonda para gatos", + "pack:nextfloor.a_haustiere:cat_wall_shelf": "Prateleira de parede para gatos", + "pack:nextfloor.a_haustiere:cat_steps": "Degraus para gatos", + "pack:nextfloor.a_haustiere:litter_covered": "Caixa de areia coberta", + "pack:nextfloor.a_haustiere:litter_auto": "Caixa de areia autolimpante", + "pack:nextfloor.a_haustiere:dog_bed": "Cama para cães", + "pack:nextfloor.a_haustiere:dog_basket": "Cesto para cães", + "pack:nextfloor.a_haustiere:dog_house": "Casota para cães", + "pack:nextfloor.a_haustiere:pet_bowls": "Taças de comida e água", + "pack:nextfloor.a_haustiere:pet_feeder": "Comedouro automático", + "pack:nextfloor.a_haustiere:pet_fountain": "Fonte para animais", + "pack:nextfloor.a_haustiere:pet_gate": "Barreira para animais", + "pack:nextfloor.a_haustiere:pet_stairs": "Escada para animais", + "pack:nextfloor.a_haustiere:hamster_cage": "Gaiola de hamster", + "pack:nextfloor.a_haustiere:small_animal_cage": "Gaiola para pequenos animais", + "pack:nextfloor.a_haustiere:rabbit_run": "Cercado para coelhos (exterior)", + "pack:nextfloor.a_haustiere:bird_cage": "Gaiola para pássaros", + "pack:nextfloor.a_haustiere:aquarium_100": "Aquário 100 l", + "pack:nextfloor.a_haustiere:aquarium_240": "Aquário 240 l com móvel", + "pack:nextfloor.a_haustiere:terrarium": "Terrário", + "pack:nextfloor.a_haustiere:pet_cat": "Gato (passeia por aí)", + "pack:nextfloor.a_haustiere:pet_dog": "Cão (passeia por aí)", + "pack:nextfloor.a_haustiere:pet_rabbit": "Coelho (salta por aí)", + "packname:nextfloor.a_kinderzimmer": "Quarto de criança", + "pack:nextfloor.a_kinderzimmer:loft_bed_slide": "Cama alta com escorrega", + "pack:nextfloor.a_kinderzimmer:teepee": "Tenda tipi", + "pack:nextfloor.a_kinderzimmer:play_kitchen": "Cozinha de brincar", + "pack:nextfloor.a_kinderzimmer:kids_desk": "Secretária de criança", + "pack:nextfloor.a_kinderzimmer:toy_shelf": "Estante de brinquedos com caixas", + "pack:nextfloor.a_kinderzimmer:cosy_corner": "Cantinho acolhedor", + "pack:nextfloor.a_kinderzimmer:rocking_horse": "Cavalo de baloiço", + "pack:nextfloor.a_kinderzimmer:play_mat_road": "Tapete de estradas", + "pack:nextfloor.a_kinderzimmer:kids_table_2": "Mesa infantil com 2 cadeiras", + "pack:nextfloor.a_kinderzimmer:moon_light": "Luz de presença lua", + "pack:nextfloor.a_kinderzimmer:ball_pit": "Piscina de bolas", + "pack:nextfloor.a_kinderzimmer:house_bed": "Cama casinha", + "pack:nextfloor.a_kinderzimmer:baby_monitor": "Intercomunicador de bebé com câmara", + "pack:nextfloor.a_kinderzimmer:star_projector": "Projetor de estrelas", + "pack:nextfloor.a_kinderzimmer:kids_cot": "Berço", + "pack:nextfloor.a_kinderzimmer:kids_changing_table": "Muda-fraldas", + "pack:nextfloor.a_kinderzimmer:kids_wardrobe": "Roupeiro infantil", + "pack:nextfloor.a_kinderzimmer:toy_boxes_3": "Caixas de brinquedos (3)", + "packname:nextfloor.a_kino": "Cinema em casa e hi-fi", + "pack:nextfloor.a_kino:screen_wall": "Tela de projeção (parede)", + "pack:nextfloor.a_kino:screen_roll": "Tela de projeção enrolável", + "pack:nextfloor.a_kino:projector_ceiling": "Projetor (teto)", + "pack:nextfloor.a_kino:projector_table": "Projetor (mesa)", + "pack:nextfloor.a_kino:speaker_floor": "Coluna de chão", + "pack:nextfloor.a_kino:speaker_shelf": "Coluna de prateleira", + "pack:nextfloor.a_kino:speaker_centre": "Coluna central", + "pack:nextfloor.a_kino:subwoofer": "Subwoofer", + "pack:nextfloor.a_kino:soundbar": "Barra de som", + "pack:nextfloor.a_kino:soundbar_premium": "Barra de som premium", + "pack:nextfloor.a_kino:speaker_wall": "Coluna de parede", + "pack:nextfloor.a_kino:speaker_ceiling": "Coluna de teto", + "pack:nextfloor.a_kino:av_receiver": "Recetor AV", + "pack:nextfloor.a_kino:turntable": "Gira-discos", + "pack:nextfloor.a_kino:record_shelf": "Estante de discos", + "pack:nextfloor.a_kino:game_console": "Consola de jogos", + "pack:nextfloor.a_kino:hifi_rack": "Rack hi-fi", + "pack:nextfloor.a_kino:cinema_seat": "Cadeira de cinema", + "pack:nextfloor.a_kino:cinema_row_3": "Fila de cadeiras de cinema (3)", + "pack:nextfloor.a_kino:acoustic_panel": "Painel acústico", + "pack:nextfloor.a_kino:bass_trap": "Bass trap (canto)", + "pack:nextfloor.a_kino:popcorn_maker": "Máquina de pipocas", + "pack:nextfloor.a_kino:star_ceiling": "Teto de estrelas", + "pack:nextfloor.a_kino:smart_speaker_ball": "Coluna inteligente (esfera)", + "pack:nextfloor.a_kino:smart_speaker_cylinder": "Coluna inteligente (cilindro)", + "pack:nextfloor.a_kino:smart_speaker_puck": "Coluna inteligente (disco)", + "pack:nextfloor.a_kino:smart_speaker_pod": "Coluna inteligente (pod)", + "pack:nextfloor.a_kino:smart_speaker_tall": "Coluna inteligente (alta)", + "pack:nextfloor.a_kino:smart_speaker_oval": "Coluna inteligente (oval)", + "pack:nextfloor.a_kino:multiroom_compact": "Coluna multiroom compacta", + "pack:nextfloor.a_kino:speaker_portable": "Coluna portátil", + "pack:nextfloor.a_kino:display_5": "Ecrã inteligente 5″", + "pack:nextfloor.a_kino:display_8": "Ecrã inteligente 8″", + "pack:nextfloor.a_kino:display_7_float": "Ecrã inteligente 7″ (flutuante)", + "pack:nextfloor.a_kino:display_15_wall": "Ecrã inteligente 15″ (parede)", + "pack:nextfloor.a_kino:speaker_stand": "Suporte de coluna", + "packname:nextfloor.a_kueche": "Cozinha", + "pack:nextfloor.a_kueche:base_30": "Móvel baixo 30", + "pack:nextfloor.a_kueche:base_40": "Móvel baixo 40", + "pack:nextfloor.a_kueche:base_50": "Móvel baixo 50", + "pack:nextfloor.a_kueche:base_60": "Móvel baixo 60", + "pack:nextfloor.a_kueche:base_80": "Móvel baixo 80", + "pack:nextfloor.a_kueche:base_90": "Móvel baixo 90", + "pack:nextfloor.a_kueche:base_100": "Móvel baixo 100", + "pack:nextfloor.a_kueche:base_120": "Móvel baixo 120", + "pack:nextfloor.a_kueche:drawer_40": "Gaveteiro 40", + "pack:nextfloor.a_kueche:drawer_50": "Gaveteiro 50", + "pack:nextfloor.a_kueche:drawer_60": "Gaveteiro 60", + "pack:nextfloor.a_kueche:drawer_80": "Gaveteiro 80", + "pack:nextfloor.a_kueche:drawer_90": "Gaveteiro 90", + "pack:nextfloor.a_kueche:drawer_100": "Gaveteiro 100", + "pack:nextfloor.a_kueche:drawer_120": "Gaveteiro 120", + "pack:nextfloor.a_kueche:sink_60": "Móvel de lava-loiça 60", + "pack:nextfloor.a_kueche:sink_80": "Móvel de lava-loiça 80", + "pack:nextfloor.a_kueche:sink_100": "Móvel de lava-loiça 100", + "pack:nextfloor.a_kueche:hob_60": "Móvel de placa 60", + "pack:nextfloor.a_kueche:hob_80": "Móvel de placa 80", + "pack:nextfloor.a_kueche:cooker_60": "Fogão com forno 60", + "pack:nextfloor.a_kueche:dishwasher_60": "Máquina de lavar loiça encastrável 60", + "pack:nextfloor.a_kueche:dishwasher_45": "Máquina de lavar loiça encastrável 45", + "pack:nextfloor.a_kueche:base_corner": "Móvel baixo de canto", + "pack:nextfloor.a_kueche:wall_40": "Armário superior 40", + "pack:nextfloor.a_kueche:wall_50": "Armário superior 50", + "pack:nextfloor.a_kueche:wall_60": "Armário superior 60", + "pack:nextfloor.a_kueche:wall_80": "Armário superior 80", + "pack:nextfloor.a_kueche:wall_90": "Armário superior 90", + "pack:nextfloor.a_kueche:wall_100": "Armário superior 100", + "pack:nextfloor.a_kueche:wall_120": "Armário superior 120", + "pack:nextfloor.a_kueche:wall_glass_80": "Armário superior de vidro 80", + "pack:nextfloor.a_kueche:wall_corner": "Armário superior de canto", + "pack:nextfloor.a_kueche:hood_wall": "Exaustor de parede", + "pack:nextfloor.a_kueche:hood_island": "Exaustor de ilha", + "pack:nextfloor.a_kueche:tall_pantry": "Coluna despensa", + "pack:nextfloor.a_kueche:tall_oven": "Coluna forno e micro-ondas", + "pack:nextfloor.a_kueche:tall_fridge": "Coluna frigorífico-congelador", + "pack:nextfloor.a_kueche:tall_steam": "Coluna forno a vapor e forno", + "pack:nextfloor.a_kueche:fridge_freezer": "Frigorífico combinado", + "pack:nextfloor.a_kueche:fridge_french": "Frigorífico French door", + "pack:nextfloor.a_kueche:wine_fridge": "Garrafeira climatizada", + "pack:nextfloor.a_kueche:glass_cabinet": "Vitrine", + "pack:nextfloor.a_kueche:row_270": "Cozinha linear 270", + "pack:nextfloor.a_kueche:row_330": "Cozinha linear 330", + "pack:nextfloor.a_kueche:island_bar": "Ilha de cozinha com bar", + "pack:nextfloor.a_kueche:island_hob": "Ilha de cozinha com placa", + "pack:nextfloor.a_kueche:breakfast_bar": "Bar de pequeno-almoço (parede)", + "pack:nextfloor.a_kueche:bar_stools_2": "Bancos altos (conjunto de 2)", + "pack:nextfloor.a_kueche:dining_bench_long": "Mesa de jantar comprida com banco", + "pack:nextfloor.a_kueche:dining_round_4": "Mesa de jantar redonda com 4 cadeiras", + "pack:nextfloor.a_kueche:high_table_2": "Mesa alta com 2 bancos", + "pack:nextfloor.a_kueche:kitchen_trolley": "Carrinho de cozinha", + "pack:nextfloor.a_kueche:pantry_shelf": "Estante de despensa", + "pack:nextfloor.a_kueche:spice_rack": "Porta-especiarias de parede", + "pack:nextfloor.a_kueche:coffee_machine": "Máquina de café automática", + "pack:nextfloor.a_kueche:microwave": "Micro-ondas", + "pack:nextfloor.a_kueche:stand_mixer": "Batedeira planetária", + "pack:nextfloor.a_kueche:kettle": "Chaleira", + "pack:nextfloor.a_kueche:toaster": "Torradeira", + "pack:nextfloor.a_kueche:herb_garden": "Horta inteligente de ervas", + "pack:nextfloor.a_kueche:pendant_trio": "Trio de candeeiros suspensos", + "pack:nextfloor.a_kueche:pendant_linear": "Candeeiro suspenso linear", + "pack:nextfloor.a_kueche:cabinet_light_60": "Luz LED sob armário 60", + "pack:nextfloor.a_kueche:cabinet_light_80": "Luz LED sob armário 80", + "pack:nextfloor.a_kueche:range_cooker_90": "Fogão de grande formato 90", + "packname:nextfloor.a_schlafzimmer": "Quarto", + "pack:nextfloor.a_schlafzimmer:bed_90": "Cama 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_140": "Cama 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_160": "Cama 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_180": "Cama 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_200": "Cama 200 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_180": "Cama estofada 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_140": "Cama estofada 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_boxspring": "Cama boxspring 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_futon": "Cama futon 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_storage": "Cama com arrumação 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_canopy": "Cama com dossel", + "pack:nextfloor.a_schlafzimmer:bed_ambient": "Cama 180 com luz ambiente", + "pack:nextfloor.a_schlafzimmer:bed_bench": "Banco de cama", + "pack:nextfloor.a_schlafzimmer:shoe_bench": "Banco sapateira", + "pack:nextfloor.a_schlafzimmer:wardrobe_2": "Roupeiro de 2 portas", + "pack:nextfloor.a_schlafzimmer:wardrobe_3": "Roupeiro de 3 portas", + "pack:nextfloor.a_schlafzimmer:wardrobe_4": "Roupeiro de 4 portas", + "pack:nextfloor.a_schlafzimmer:wardrobe_6": "Roupeiro de 6 portas", + "pack:nextfloor.a_schlafzimmer:wardrobe_mirror": "Roupeiro com porta de espelho", + "pack:nextfloor.a_schlafzimmer:wardrobe_sliding": "Roupeiro de portas de correr", + "pack:nextfloor.a_schlafzimmer:wardrobe_light": "Roupeiro com luz interior", + "pack:nextfloor.a_schlafzimmer:wardrobe_corner": "Roupeiro de canto", + "pack:nextfloor.a_schlafzimmer:walk_in_closet": "Closet aberto", + "pack:nextfloor.a_schlafzimmer:clothes_rail": "Arara de roupa", + "pack:nextfloor.a_schlafzimmer:nightstand": "Mesa de cabeceira com gaveta", + "pack:nextfloor.a_schlafzimmer:nightstand_slim": "Mesa de cabeceira estreita", + "pack:nextfloor.a_schlafzimmer:nightstand_floating": "Mesa de cabeceira suspensa", + "pack:nextfloor.a_schlafzimmer:dresser_6": "Cómoda de 6 gavetas 140", + "pack:nextfloor.a_schlafzimmer:chest_tall_5": "Cómoda alta de 5 gavetas", + "pack:nextfloor.a_schlafzimmer:chest_tall": "Cómoda alta", + "pack:nextfloor.a_schlafzimmer:chest_80": "Cómoda de 3 gavetas 80", + "pack:nextfloor.a_schlafzimmer:vanity_table": "Toucador com espelho", + "pack:nextfloor.a_schlafzimmer:dressing_table_light": "Toucador com espelho iluminado", + "pack:nextfloor.a_schlafzimmer:cot": "Berço", + "pack:nextfloor.a_schlafzimmer:changing_table": "Muda-fraldas", + "pack:nextfloor.a_schlafzimmer:standing_mirror": "Espelho de pé", + "pack:nextfloor.a_schlafzimmer:reading_nook": "Canto de leitura com cadeira", + "pack:nextfloor.a_schlafzimmer:bedside_lamp": "Candeeiro de cabeceira", + "pack:nextfloor.a_schlafzimmer:touch_lamp": "Candeeiro de cabeceira táctil", + "pack:nextfloor.a_schlafzimmer:humidifier": "Humidificador", + "pack:nextfloor.a_schlafzimmer:sunrise_clock": "Despertador de nascer do sol", + "packname:nextfloor.a_smart": "Casa inteligente e tecnologia", + "pack:nextfloor.a_smart:wallbox": "Wallbox", + "pack:nextfloor.a_smart:electric_car": "Carro elétrico", + "pack:nextfloor.a_smart:heat_pump_outdoor": "Bomba de calor (unidade exterior)", + "pack:nextfloor.a_smart:home_battery": "Bateria doméstica", + "pack:nextfloor.a_smart:inverter_solar": "Inversor solar", + "pack:nextfloor.a_smart:robot_vacuum": "Robô aspirador com base", + "pack:nextfloor.a_smart:mower_garage": "Robô corta-relva com garagem", + "pack:nextfloor.a_smart:washer_dryer_stack": "Coluna máquina de lavar e secar", + "pack:nextfloor.a_smart:network_rack": "Rack de rede", + "pack:nextfloor.a_smart:smart_display": "Ecrã inteligente", + "pack:nextfloor.a_smart:solar_balcony": "Painel solar de varanda", + "pack:nextfloor.a_smart:fuse_box": "Quadro elétrico", + "pack:nextfloor.a_smart:nas_server": "Servidor NAS", + "pack:nextfloor.a_smart:hot_water_tank": "Termoacumulador", + "pack:nextfloor.a_smart:light_pillar": "Coluna de luz em degradê", + "pack:nextfloor.a_smart:light_bars_tv": "Par de barras de luz (TV)", + "pack:nextfloor.a_smart:orb_lamp": "Candeeiro de mesa esfera luminosa", + "pack:nextfloor.a_smart:glow_lamp_portable": "Candeeiro luminoso portátil", + "pack:nextfloor.a_smart:mood_spot": "Foco ambiente de mesa", + "pack:nextfloor.a_smart:cube_lamp": "Candeeiro cubo", + "pack:nextfloor.a_smart:ceiling_panel_round": "Painel de teto redondo", + "pack:nextfloor.a_smart:garden_spots_3": "Projetores de jardim (conjunto de 3)", + "pack:nextfloor.a_smart:wall_light_updown": "Aplique exterior para cima e para baixo", + "pack:nextfloor.a_smart:siren_strobe": "Sirene com estroboscópio", + "pack:nextfloor.a_smart:access_point": "Ponto de acesso Wi-Fi (teto)", + "pack:nextfloor.a_smart:smoke_detector": "Detetor de fumo", + "pack:nextfloor.a_smart:thermostat_wall": "Termóstato de parede", + "pack:nextfloor.a_smart:dehumidifier": "Desumidificador", + "pack:nextfloor.a_smart:ceiling_fan": "Ventoinha de teto", + "pack:nextfloor.a_smart:ceiling_fan_light": "Ventoinha de teto com luz", + "pack:nextfloor.a_smart:light_switch_1": "Interruptor de luz, 1 tecla", + "pack:nextfloor.a_smart:socket_1": "Tomada simples", + "pack:nextfloor.a_smart:light_switch_2": "Interruptor de luz, 2 teclas", + "pack:nextfloor.a_smart:socket_2": "Tomada dupla", + "pack:nextfloor.a_smart:light_switch_3": "Interruptor de luz, 3 teclas", + "pack:nextfloor.a_smart:socket_3": "Tomada tripla", + "pack:nextfloor.a_smart:light_switch_4": "Interruptor de luz, 4 teclas", + "pack:nextfloor.a_smart:socket_4": "Tomada quádrupla", + "pack:nextfloor.a_smart:socket_outdoor": "Tomada exterior com tampa", + "packname:nextfloor.a_wohnzimmer": "Sala de estar", + "pack:nextfloor.a_wohnzimmer:sofa_2": "Sofá de 2 lugares", + "pack:nextfloor.a_wohnzimmer:sofa_3": "Sofá de 3 lugares", + "pack:nextfloor.a_wohnzimmer:sofa_4": "Sofá grande de 4 lugares", + "pack:nextfloor.a_wohnzimmer:sofa_velvet": "Sofá de veludo de 3 lugares", + "pack:nextfloor.a_wohnzimmer:sofa_armless": "Sofá sem braços", + "pack:nextfloor.a_wohnzimmer:sofa_chaise": "Sofá com chaise longue", + "pack:nextfloor.a_wohnzimmer:sofa_chesterfield": "Sofá Chesterfield", + "pack:nextfloor.a_wohnzimmer:sofa_bed": "Sofá-cama", + "pack:nextfloor.a_wohnzimmer:sofa_corner_l": "Sofá de canto (esquerda)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_r": "Sofá de canto (direita)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_xl": "Sofá de canto grande (em L)", + "pack:nextfloor.a_wohnzimmer:sofa_u": "Sofá em U", + "pack:nextfloor.a_wohnzimmer:chaise_longue": "Chaise longue", + "pack:nextfloor.a_wohnzimmer:modular_sofa": "Sofá modular (5 peças)", + "pack:nextfloor.a_wohnzimmer:armchair": "Poltrona", + "pack:nextfloor.a_wohnzimmer:club_chair": "Poltrona club", + "pack:nextfloor.a_wohnzimmer:wingback": "Poltrona de orelhas", + "pack:nextfloor.a_wohnzimmer:cocktail_chair": "Cadeira cocktail", + "pack:nextfloor.a_wohnzimmer:recliner": "Poltrona reclinável com apoio de pés", + "pack:nextfloor.a_wohnzimmer:bean_bag": "Pufe saco", + "pack:nextfloor.a_wohnzimmer:pouf": "Pufe", + "pack:nextfloor.a_wohnzimmer:rocking_chair": "Cadeira de baloiço", + "pack:nextfloor.a_wohnzimmer:coffee_rect": "Mesa de centro retangular", + "pack:nextfloor.a_wohnzimmer:coffee_glass": "Mesa de centro de vidro", + "pack:nextfloor.a_wohnzimmer:coffee_round": "Mesa de centro redonda", + "pack:nextfloor.a_wohnzimmer:coffee_nesting": "Mesas de centro encaixáveis", + "pack:nextfloor.a_wohnzimmer:side_round": "Mesa de apoio redonda", + "pack:nextfloor.a_wohnzimmer:console": "Consola", + "pack:nextfloor.a_wohnzimmer:dining_120": "Mesa de jantar 120 × 90", + "pack:nextfloor.a_wohnzimmer:dining_160": "Mesa de jantar 160 × 90", + "pack:nextfloor.a_wohnzimmer:dining_200": "Mesa de jantar 200 × 90", + "pack:nextfloor.a_wohnzimmer:dining_220": "Mesa de jantar em madeira maciça 220 × 100", + "pack:nextfloor.a_wohnzimmer:chair_wood": "Cadeira de madeira", + "pack:nextfloor.a_wohnzimmer:chair_upholstered": "Cadeira estofada", + "pack:nextfloor.a_wohnzimmer:chair_shell": "Cadeira concha", + "pack:nextfloor.a_wohnzimmer:dining_bench": "Banco de jantar 160", + "pack:nextfloor.a_wohnzimmer:lowboard_120": "Móvel baixo 120", + "pack:nextfloor.a_wohnzimmer:lowboard_160": "Móvel baixo 160", + "pack:nextfloor.a_wohnzimmer:lowboard_200": "Móvel baixo 200", + "pack:nextfloor.a_wohnzimmer:sideboard_160": "Aparador 160", + "pack:nextfloor.a_wohnzimmer:highboard": "Aparador alto", + "pack:nextfloor.a_wohnzimmer:display_cabinet": "Vitrine", + "pack:nextfloor.a_wohnzimmer:chest_3": "Cómoda de 3 gavetas", + "pack:nextfloor.a_wohnzimmer:bookshelf_tall": "Estante alta", + "pack:nextfloor.a_wohnzimmer:bookshelf_wide": "Estante larga", + "pack:nextfloor.a_wohnzimmer:cube_2x2": "Estante de cubos 2 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x2": "Estante de cubos 4 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x4": "Estante de cubos 4 × 4", + "pack:nextfloor.a_wohnzimmer:divider_open": "Estante divisória", + "pack:nextfloor.a_wohnzimmer:wall_shelf": "Prateleira flutuante", + "pack:nextfloor.a_wohnzimmer:coat_stand": "Bengaleiro de pé", + "pack:nextfloor.a_wohnzimmer:wall_unit_vitrines": "Móvel de parede com vitrines", + "pack:nextfloor.a_wohnzimmer:wall_unit_tv": "Móvel de parede com TV", + "pack:nextfloor.a_wohnzimmer:tv_on_stand": "TV em suporte", + "pack:nextfloor.a_wohnzimmer:media_wall": "Parede multimédia com TV", + "pack:nextfloor.a_wohnzimmer:wood_stove": "Salamandra a lenha", + "pack:nextfloor.a_wohnzimmer:fireplace_wall": "Lareira elétrica de parede", + "pack:nextfloor.a_wohnzimmer:piano": "Piano vertical com banco", + "pack:nextfloor.a_wohnzimmer:floor_lamp_arc": "Candeeiro de pé em arco", + "pack:nextfloor.a_wohnzimmer:floor_lamp_tripod": "Candeeiro de pé tripé", + "pack:nextfloor.a_wohnzimmer:table_lamp_ceramic": "Candeeiro de mesa em cerâmica", + "pack:nextfloor.a_wohnzimmer:vase_pampas": "Vaso de chão com erva-das-pampas", + "pack:nextfloor.a_wohnzimmer:monstera": "Monstera grande", + "pack:nextfloor.a_wohnzimmer:rug_round": "Tapete redondo", + "pack:nextfloor.a_wohnzimmer:rug_240": "Tapete 240 × 170", + "pack:nextfloor.a_wohnzimmer:painting_light": "Quadro com luz", + "pack:nextfloor.a_wohnzimmer:shelf_led": "Estante com prateleiras LED", + "pack:nextfloor.a_wohnzimmer:air_purifier": "Purificador de ar", + "pack:nextfloor.a_wohnzimmer:tower_fan": "Ventoinha de torre", + "pack:nextfloor.a_wohnzimmer:smart_speaker_living": "Coluna inteligente", + "packname:nextfloor.ausbau": "Arquitetura e acabamentos", + "pack:nextfloor.ausbau:column_round": "Coluna redonda", + "pack:nextfloor.ausbau:column_square": "Coluna quadrada", + "pack:nextfloor.ausbau:beam": "Viga de teto", + "pack:nextfloor.ausbau:chimney": "Chaminé", + "pack:nextfloor.ausbau:glass_wall": "Divisória de vidro", + "pack:nextfloor.ausbau:sliding_wall": "Parede de correr", + "pack:nextfloor.ausbau:platform": "Estrado", + "pack:nextfloor.ausbau:half_wall": "Meia parede", + "pack:nextfloor.ausbau:divider_shelf": "Estante divisória", + "pack:nextfloor.ausbau:pilaster": "Pilastra", + "pack:nextfloor.ausbau:column_steel": "Pilar de aço", + "pack:nextfloor.ausbau:beams_wood_5": "Vigas de madeira no teto (5)", + "pack:nextfloor.ausbau:beam_downstand": "Viga rebaixada", + "pack:nextfloor.ausbau:fireplace_builtin": "Lareira embutida", + "pack:nextfloor.ausbau:divider_slats": "Divisória de ripas", + "pack:nextfloor.ausbau:curtain_motor": "Cortina motorizada", + "pack:nextfloor.ausbau:niche_shelf": "Estante embutida (nicho)", + "pack:nextfloor.ausbau:niche_led": "Nicho LED", + "pack:nextfloor.ausbau:light_cove": "Sanca de luz (teto)", + "pack:nextfloor.ausbau:gallery_rail_glass": "Guarda do mezanino (vidro)", + "pack:nextfloor.ausbau:window_seat": "Banco de janela", + "pack:nextfloor.ausbau:curtain_pair": "Cortina (abre para os dois lados)", + "pack:nextfloor.ausbau:roller_blind_inside": "Estore de rolo (interior)", + "packname:nextfloor.bad": "Casa de banho extra", + "pack:nextfloor.bad:double_vanity": "Lavatório duplo", + "pack:nextfloor.bad:walkin_shower": "Duche walk-in", + "pack:nextfloor.bad:towel_radiator": "Radiador toalheiro", + "pack:nextfloor.bad:mirror_cabinet": "Armário com espelho e luz", + "pack:nextfloor.bad:washer_tower": "Coluna máquina de lavar e secar", + "pack:nextfloor.bad:laundry_basket": "Cesto de roupa", + "pack:nextfloor.bad:bath_shelf": "Prateleira de casa de banho", + "packname:nextfloor.energie": "Energia e instalações técnicas", + "pack:nextfloor.energie:heat_pump": "Bomba de calor (unidade exterior)", + "pack:nextfloor.energie:pellet_boiler": "Caldeira a pellets", + "pack:nextfloor.energie:buffer_tank": "Depósito de inércia", + "pack:nextfloor.energie:hot_water_tank": "Termoacumulador", + "pack:nextfloor.energie:home_battery": "Bateria doméstica (torre)", + "pack:nextfloor.energie:inverter": "Inversor", + "pack:nextfloor.energie:wallbox": "Wallbox", + "pack:nextfloor.energie:meter_cabinet": "Quadro de contadores", + "pack:nextfloor.energie:ventilation": "Unidade de ventilação", + "pack:nextfloor.energie:solar_carport_pillar": "Pilar de telheiro solar", + "packname:nextfloor.fahrzeuge": "Veículos", + "pack:nextfloor.fahrzeuge:tesla_model_s": "Tesla Model S", + "packname:nextfloor.a_saison": "Estações e decoração", + "packname:nextfloor.a_smart2": "Casa inteligente 2", + "packname:nextfloor.a_haustechnik2": "Instalações 2", + "packname:nextfloor.a_wellness": "Bem-estar", + "packname:nextfloor.a_garten2": "Jardim 2", + "packname:nextfloor.a_kueche2": "Cozinha 2", + "packname:nextfloor.a_fahrzeuge2": "Veículos 2", + "packname:nextfloor.a_aussenkueche": "Cozinha exterior e terraço", + "packname:nextfloor.a_werkstatt2": "Oficina 2", + "packname:nextfloor.a_japandi": "Japandi e escandinavo", + "packname:nextfloor.a_loft": "Loft e industrial", + "packname:nextfloor.a_gruen": "Plantas de interior", + "packname:nextfloor.a_musik": "Música e ateliê", + "pack:nextfloor.a_saison:xmas_tree": "Árvore de Natal com luzes", + "pack:nextfloor.a_saison:advent_wreath": "Coroa do Advento", + "pack:nextfloor.a_saison:lights_outdoor": "Cordão de luzes exterior", + "pack:nextfloor.a_saison:window_star": "Estrela de janela", + "pack:nextfloor.a_saison:candle_arch": "Arco de velas", + "pack:nextfloor.a_saison:reindeer_light": "Rena luminosa", + "pack:nextfloor.a_saison:pumpkin": "Abóbora", + "pack:nextfloor.a_saison:pumpkin_lantern": "Abóbora iluminada", + "pack:nextfloor.a_saison:easter_tree": "Árvore de Páscoa", + "pack:nextfloor.a_saison:snowman": "Boneco de neve", + "pack:nextfloor.a_saison:gift_pile": "Presentes", + "pack:nextfloor.a_smart2:siren": "Sirene", + "pack:nextfloor.a_smart2:access_point": "Ponto de acesso Wi-Fi", + "pack:nextfloor.a_smart2:access_point_wall": "Ponto de acesso Wi-Fi (parede)", + "pack:nextfloor.a_smart2:smoke_detector": "Detetor de fumo", + "pack:nextfloor.a_smart2:co_detector": "Detetor de CO", + "pack:nextfloor.a_smart2:dehumidifier": "Desumidificador", + "pack:nextfloor.a_smart2:cube_lamp": "Candeeiro cubo", + "pack:nextfloor.a_smart2:presence_ceiling": "Sensor de presença (teto)", + "pack:nextfloor.a_smart2:water_leak": "Sensor de fugas", + "pack:nextfloor.a_smart2:air_quality": "Sensor de qualidade do ar", + "pack:nextfloor.a_smart2:doorbell_cam": "Campainha com vídeo", + "pack:nextfloor.a_haustechnik2:water_tank": "Depósito de água", + "pack:nextfloor.a_haustechnik2:oil_tank": "Depósito de gasóleo", + "pack:nextfloor.a_haustechnik2:oil_boiler": "Caldeira a gasóleo", + "pack:nextfloor.a_haustechnik2:water_softener": "Descalcificador", + "pack:nextfloor.a_haustechnik2:buffer_tank": "Depósito de inércia", + "pack:nextfloor.a_haustechnik2:cistern": "Cisterna de água da chuva", + "pack:nextfloor.a_haustechnik2:ventilation_unit": "Unidade de ventilação", + "pack:nextfloor.a_haustechnik2:expansion_vessel": "Vaso de expansão", + "pack:nextfloor.a_haustechnik2:heat_pump_indoor": "Bomba de calor (unidade interior)", + "pack:nextfloor.a_wellness:sauna_cabin": "Sauna", + "pack:nextfloor.a_wellness:sauna_barrel": "Sauna barril", + "pack:nextfloor.a_wellness:infrared_cabin": "Cabine de infravermelhos", + "pack:nextfloor.a_wellness:hot_tub": "Jacuzzi", + "pack:nextfloor.a_wellness:plunge_pool": "Tanque de imersão", + "pack:nextfloor.a_wellness:steam_shower": "Duche de vapor", + "pack:nextfloor.a_wellness:relax_lounger": "Espreguiçadeira", + "pack:nextfloor.a_wellness:cold_bath": "Banho de gelo", + "pack:nextfloor.a_garten2:water_feature": "Fonte com luz", + "pack:nextfloor.a_garten2:pond": "Lago com bomba", + "pack:nextfloor.a_garten2:robot_mower": "Robô corta-relva", + "pack:nextfloor.a_garten2:mower_dock": "Base de carga do robô", + "pack:nextfloor.a_garten2:sandbox": "Caixa de areia", + "pack:nextfloor.a_garten2:beach_chair": "Cadeira de praia", + "pack:nextfloor.a_garten2:wood_pile": "Pilha de lenha", + "pack:nextfloor.a_garten2:bird_house": "Comedouro para pássaros", + "pack:nextfloor.a_garten2:raised_bed": "Canteiro elevado", + "pack:nextfloor.a_garten2:garden_shower": "Chuveiro de jardim", + "pack:nextfloor.a_kueche2:coffee_machine": "Máquina de café automática", + "pack:nextfloor.a_kueche2:espresso": "Máquina de expresso", + "pack:nextfloor.a_kueche2:kettle": "Chaleira elétrica", + "pack:nextfloor.a_kueche2:toaster": "Torradeira", + "pack:nextfloor.a_kueche2:stand_mixer": "Robô de cozinha", + "pack:nextfloor.a_kueche2:thermo_cooker": "Robô de cozinha com cozedura", + "pack:nextfloor.a_kueche2:air_fryer": "Fritadeira de ar", + "pack:nextfloor.a_kueche2:microwave": "Micro-ondas", + "pack:nextfloor.a_kueche2:wine_fridge": "Garrafeira", + "pack:nextfloor.a_kueche2:water_bar": "Máquina de água com gás", + "pack:nextfloor.a_kueche2:dishwasher_slim": "Máquina de lavar loiça 45 cm", + "pack:nextfloor.a_fahrzeuge2:motorbike": "Mota", + "pack:nextfloor.a_fahrzeuge2:scooter": "Scooter", + "pack:nextfloor.a_fahrzeuge2:camper_van": "Autocaravana", + "pack:nextfloor.a_fahrzeuge2:trailer": "Reboque", + "pack:nextfloor.a_fahrzeuge2:e_bike": "Bicicleta elétrica", + "pack:nextfloor.a_fahrzeuge2:cargo_bike": "Bicicleta de carga", + "pack:nextfloor.a_fahrzeuge2:quad": "Moto-quatro", + "pack:nextfloor.a_fahrzeuge2:boat_trailer": "Reboque com barco", + "pack:nextfloor.a_aussenkueche:outdoor_kitchen": "Cozinha exterior", + "pack:nextfloor.a_aussenkueche:kamado": "Grelhador kamado", + "pack:nextfloor.a_aussenkueche:pizza_oven": "Forno de pizza", + "pack:nextfloor.a_aussenkueche:fire_pit": "Braseiro", + "pack:nextfloor.a_aussenkueche:patio_heater": "Aquecedor de esplanada", + "pack:nextfloor.a_aussenkueche:outdoor_fridge": "Frigorífico exterior", + "pack:nextfloor.a_aussenkueche:bar_counter": "Balcão de bar", + "pack:nextfloor.a_aussenkueche:bar_stool_out": "Banco de bar exterior", + "pack:nextfloor.a_aussenkueche:hanging_chair": "Cadeira suspensa", + "pack:nextfloor.a_werkstatt2:workbench_wall": "Bancada com painel perfurado", + "pack:nextfloor.a_werkstatt2:drill_press": "Engenho de furar", + "pack:nextfloor.a_werkstatt2:table_saw": "Serra de bancada", + "pack:nextfloor.a_werkstatt2:compressor": "Compressor", + "pack:nextfloor.a_werkstatt2:welder": "Máquina de soldar", + "pack:nextfloor.a_werkstatt2:heavy_shelf": "Estante de carga pesada", + "pack:nextfloor.a_werkstatt2:parts_cabinet": "Caixa organizadora", + "pack:nextfloor.a_werkstatt2:tool_chest": "Carro de ferramentas", + "pack:nextfloor.a_werkstatt2:ev_bike_charger": "Estação de carga de baterias", + "pack:nextfloor.a_japandi:low_bed": "Cama baixa", + "pack:nextfloor.a_japandi:tatami": "Tatami", + "pack:nextfloor.a_japandi:paper_lamp": "Candeeiro de papel", + "pack:nextfloor.a_japandi:paper_pendant": "Pendente de papel", + "pack:nextfloor.a_japandi:tea_table": "Mesa de chá baixa", + "pack:nextfloor.a_japandi:shoji_screen": "Biombo shoji", + "pack:nextfloor.a_japandi:bonsai": "Bonsai", + "pack:nextfloor.a_japandi:floor_cushion": "Almofada de chão", + "pack:nextfloor.a_japandi:wood_bench": "Banco de madeira", + "pack:nextfloor.a_japandi:rattan_chair": "Poltrona de vime", + "pack:nextfloor.a_loft:steel_shelf": "Estante de aço", + "pack:nextfloor.a_loft:factory_pendant": "Pendente industrial", + "pack:nextfloor.a_loft:leather_sofa": "Sofá de couro", + "pack:nextfloor.a_loft:plank_table": "Mesa de tábuas", + "pack:nextfloor.a_loft:locker": "Cacifo metálico", + "pack:nextfloor.a_loft:edison_floor_lamp": "Candeeiro de pé Edison", + "pack:nextfloor.a_loft:bar_stool_loft": "Banco industrial", + "pack:nextfloor.a_loft:pipe_shelf": "Prateleira de tubos", + "pack:nextfloor.a_gruen:monstera": "Monstera", + "pack:nextfloor.a_gruen:ficus": "Fícus", + "pack:nextfloor.a_gruen:olive_tree": "Oliveira em vaso", + "pack:nextfloor.a_gruen:cactus_group": "Catos", + "pack:nextfloor.a_gruen:hanging_plant": "Planta suspensa", + "pack:nextfloor.a_gruen:plant_shelf": "Estante de plantas com luz", + "pack:nextfloor.a_gruen:vertical_garden": "Jardim vertical", + "pack:nextfloor.a_gruen:grow_light": "Lâmpada de cultivo", + "pack:nextfloor.a_gruen:herb_planter": "Horta de ervas inteligente", + "pack:nextfloor.a_musik:upright_piano": "Piano vertical", + "pack:nextfloor.a_musik:grand_piano": "Piano de cauda", + "pack:nextfloor.a_musik:drum_kit": "Bateria", + "pack:nextfloor.a_musik:guitar_stand": "Guitarras em suporte", + "pack:nextfloor.a_musik:guitar_amp": "Amplificador de guitarra", + "pack:nextfloor.a_musik:mixing_desk": "Mesa de estúdio com mesa de mistura", + "pack:nextfloor.a_musik:studio_monitor": "Monitor de estúdio", + "pack:nextfloor.a_musik:synth": "Sintetizador", + "pack:nextfloor.a_musik:mic_stand": "Microfone com suporte", + "pack:nextfloor.a_musik:easel": "Cavalete", + "pack:nextfloor.a_musik:vinyl_player": "Gira-discos", + "packname:nextfloor.a_bilder": "Quadros e molduras", + "pack:nextfloor.a_bilder:frame_landscape": "Moldura (horizontal)", + "pack:nextfloor.a_bilder:frame_portrait": "Moldura (vertical)", + "pack:nextfloor.a_bilder:frame_square": "Moldura (quadrada)", + "pack:nextfloor.a_bilder:frame_large": "Moldura grande", + "pack:nextfloor.a_bilder:canvas": "Tela", + "pack:nextfloor.a_bilder:poster": "Póster", + "pack:nextfloor.a_bilder:frame_table": "Moldura de mesa", + "pack:nextfloor.a_bilder:frame_digital": "Moldura digital", + "pack:nextfloor.a_bilder:picture_ledge": "Prateleira para quadros", + "color:pearl_white": "Pearl White", + "color:solid_black": "Solid Black", + "color:midnight_silver": "Midnight Silver", + "color:quicksilver": "Quicksilver", + "color:deep_blue": "Deep Blue", + "color:ultra_red": "Ultra Red", + "color:midnight_cherry": "Midnight Cherry Red", + "pack:nextfloor.fahrzeuge:tesla_model_3": "Tesla Model 3", + "color:red": "Red Multi-Coat", + "color:stealth_grey": "Stealth Grey", + "pack:nextfloor.fahrzeuge:tesla_model_x": "Tesla Model X", + "pack:nextfloor.fahrzeuge:tesla_model_y": "Tesla Model Y", + "pack:nextfloor.fahrzeuge:tesla_cybertruck": "Tesla Cybertruck", + "color:stainless": "Stainless Steel", + "color:wrap_black": "Envelopamento Satin Black", + "color:wrap_white": "Envelopamento Satin White", + "color:wrap_grey": "Envelopamento Satin Grey", + "color:wrap_blue": "Envelopamento Satin Blue", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024": "Tesla Model 3 (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024_performance": "Tesla Model 3 Performance (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_s_plaid": "Tesla Model S Plaid", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025": "Tesla Model Y Standard (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_premium": "Tesla Model Y Premium (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_performance": "Tesla Model Y Performance (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_l": "Tesla Model Y L", + "pack:nextfloor.fahrzeuge:tesla_roadster": "Tesla Roadster", + "pack:nextfloor.fahrzeuge:tesla_semi": "Tesla Semi", + "pack:nextfloor.fahrzeuge:ev_suv": "SUV elétrico (tamanho Model Y)", + "pack:nextfloor.fahrzeuge:small_car": "Carro pequeno", + "pack:nextfloor.fahrzeuge:estate_car": "Carrinha", + "pack:nextfloor.fahrzeuge:van": "Furgoneta", + "pack:nextfloor.fahrzeuge:bicycle": "Bicicleta", + "pack:nextfloor.fahrzeuge:ebike": "Bicicleta elétrica", + "pack:nextfloor.fahrzeuge:motorbike": "Mota", + "pack:nextfloor.fahrzeuge:trailer": "Reboque", + "pack:nextfloor.fahrzeuge:sedan": "Sedã", + "pack:nextfloor.fahrzeuge:coupe": "Coupé desportivo", + "pack:nextfloor.fahrzeuge:convertible": "Descapotável (aberto)", + "pack:nextfloor.fahrzeuge:small_ev": "Elétrico pequeno", + "pack:nextfloor.fahrzeuge:suv": "SUV", + "pack:nextfloor.fahrzeuge:family_van": "Monovolume", + "pack:nextfloor.fahrzeuge:minibus": "Minibus", + "pack:nextfloor.fahrzeuge:panel_van": "Furgão", + "pack:nextfloor.fahrzeuge:pickup": "Pick-up", + "pack:nextfloor.fahrzeuge:campervan": "Autocaravana compacta (teto elevável)", + "pack:nextfloor.fahrzeuge:motorhome": "Autocaravana", + "pack:nextfloor.fahrzeuge:caravan": "Caravana", + "packname:nextfloor.fitness": "Fitness (antigo)", + "pack:nextfloor.fitness:treadmill": "Passadeira", + "pack:nextfloor.fitness:bike_trainer": "Bicicleta estática", + "pack:nextfloor.fitness:rower": "Máquina de remo", + "pack:nextfloor.fitness:weight_bench": "Banco de musculação", + "pack:nextfloor.fitness:power_rack": "Power rack", + "pack:nextfloor.fitness:yoga_mat": "Tapete de ioga", + "pack:nextfloor.fitness:dumbbell_rack": "Suporte de halteres", + "packname:nextfloor.garten": "Jardim e terraço (antigo)", + "pack:nextfloor.garten:sun_lounger": "Espreguiçadeira", + "pack:nextfloor.garten:garden_table": "Mesa de jardim", + "pack:nextfloor.garten:garden_chair": "Cadeira de jardim", + "pack:nextfloor.garten:lounge_set": "Lounge exterior", + "pack:nextfloor.garten:parasol": "Guarda-sol", + "pack:nextfloor.garten:gas_grill": "Grelhador a gás", + "pack:nextfloor.garten:fire_bowl": "Braseira", + "pack:nextfloor.garten:pool": "Piscina", + "pack:nextfloor.garten:hot_tub": "Jacuzzi", + "pack:nextfloor.garten:trampoline": "Trampolim", + "pack:nextfloor.garten:greenhouse": "Estufa", + "pack:nextfloor.garten:raised_bed": "Canteiro elevado", + "pack:nextfloor.garten:garden_shed": "Casota de jardim", + "pack:nextfloor.garten:swing_bench": "Baloiço de alpendre", + "pack:nextfloor.garten:mower_robot": "Robô corta-relva", + "pack:nextfloor.garten:tree_oak": "Árvore de folha caduca", + "pack:nextfloor.garten:tree_birch": "Bétula", + "pack:nextfloor.garten:tree_fruit": "Árvore de fruto", + "pack:nextfloor.garten:conifer": "Conífera", + "pack:nextfloor.garten:shrub": "Arbusto", + "pack:nextfloor.garten:shrub_flowering": "Arbusto florido", + "pack:nextfloor.garten:hedge": "Sebe", + "pack:nextfloor.garten:lawn_brush": "Mato", + "pack:nextfloor.garten:bike_rack": "Suporte de bicicletas", + "pack:nextfloor.garten:bin_box": "Abrigo de contentores (4)", + "packname:nextfloor.ikea": "Medidas IKEA", + "pack:nextfloor.ikea:billy": "Estante 80x202 (tamanho Billy)", + "pack:nextfloor.ikea:billy_low": "Estante 80x106 (tamanho Billy)", + "pack:nextfloor.ikea:kallax_2x2": "Estante de cubos 2x2 (tamanho Kallax)", + "pack:nextfloor.ikea:kallax_2x4": "Estante de cubos 2x4 (tamanho Kallax)", + "pack:nextfloor.ikea:kallax_4x4": "Estante de cubos 4x4 (tamanho Kallax)", + "pack:nextfloor.ikea:lack_side": "Mesa de apoio 55x55 (tamanho Lack)", + "pack:nextfloor.ikea:lack_coffee": "Mesa de centro 90x55 (tamanho Lack)", + "pack:nextfloor.ikea:malm_bed_140": "Cama 140x200 (tamanho Malm)", + "pack:nextfloor.ikea:malm_bed_160": "Cama 160x200 (tamanho Malm)", + "pack:nextfloor.ikea:malm_chest_6": "Cómoda de 6 gavetas (tamanho Malm)", + "pack:nextfloor.ikea:malm_chest_4": "Cómoda de 4 gavetas (tamanho Malm)", + "pack:nextfloor.ikea:pax_100": "Roupeiro 100x236 (tamanho Pax)", + "pack:nextfloor.ikea:pax_150": "Roupeiro 150x236 (tamanho Pax)", + "pack:nextfloor.ikea:poang": "Poltrona (tamanho Poäng)", + "pack:nextfloor.ikea:ektorp_2": "Sofá de 2 lugares (tamanho Ektorp)", + "pack:nextfloor.ikea:ektorp_3": "Sofá de 3 lugares (tamanho Ektorp)", + "pack:nextfloor.ikea:bekant": "Secretária 160x80 (tamanho Bekant)", + "pack:nextfloor.ikea:alex": "Gaveteiro (tamanho Alex)", + "pack:nextfloor.ikea:besta_tv": "Móvel de TV 180x42 (tamanho Bestå)", + "pack:nextfloor.ikea:ivar": "Estante de pinho 89x179 (tamanho Ivar)", + "packname:nextfloor.kino": "Cinema em casa e gaming", + "pack:nextfloor.kino:projection_screen": "Tela de projeção", + "pack:nextfloor.kino:projector": "Projetor", + "pack:nextfloor.kino:floor_speaker": "Coluna de chão", + "pack:nextfloor.kino:subwoofer": "Subwoofer", + "pack:nextfloor.kino:soundbar": "Barra de som", + "pack:nextfloor.kino:gaming_desk": "Secretária gaming", + "pack:nextfloor.kino:gaming_chair": "Cadeira gaming", + "pack:nextfloor.kino:game_console": "Consola de jogos", + "pack:nextfloor.kino:arcade": "Máquina arcade", + "pack:nextfloor.kino:media_wall": "Parede multimédia com TV", + "pack:nextfloor.kino:media_rack": "Rack multimédia", + "packname:nextfloor.kueche": "Cozinha extra", + "pack:nextfloor.kueche:coffee_machine": "Máquina de café", + "pack:nextfloor.kueche:microwave": "Micro-ondas", + "pack:nextfloor.kueche:hood_island": "Exaustor de ilha", + "pack:nextfloor.kueche:wine_fridge": "Garrafeira climatizada", + "pack:nextfloor.kueche:stand_mixer": "Batedeira planetária", + "pack:nextfloor.kueche:toaster": "Torradeira", + "pack:nextfloor.kueche:kettle": "Chaleira", + "pack:nextfloor.kueche:long_dining_table": "Mesa de jantar comprida", + "pack:nextfloor.kueche:bar_cart": "Carrinho de bar", + "pack:nextfloor.kueche:trash_station": "Separação de resíduos", + "packname:nextfloor.schlafen": "Dormir e crianças", + "pack:nextfloor.schlafen:boxspring": "Cama boxspring", + "pack:nextfloor.schlafen:baby_crib": "Berço", + "pack:nextfloor.schlafen:changing_table": "Muda-fraldas", + "pack:nextfloor.schlafen:vanity_table": "Toucador", + "pack:nextfloor.schlafen:clothes_rail": "Arara de roupa", + "pack:nextfloor.schlafen:loft_bed_desk": "Cama alta com secretária", + "pack:nextfloor.schlafen:toy_box": "Baú de brinquedos", + "packname:nextfloor.technik": "Escritório e homelab", + "pack:nextfloor.technik:standing_desk": "Secretária regulável", + "pack:nextfloor.technik:server_rack": "Rack de servidores (19 polegadas)", + "pack:nextfloor.technik:nas": "NAS", + "pack:nextfloor.technik:printer_3d": "Impressora 3D", + "pack:nextfloor.technik:office_printer": "Impressora", + "pack:nextfloor.technik:router": "Router / ponto de acesso", + "pack:nextfloor.technik:tower_pc": "PC torre", + "pack:nextfloor.technik:filing_cabinet": "Bloco de gavetas", + "packname:nextfloor.treppen": "Escadas e corrimãos", + "pack:nextfloor.treppen:stairs_straight": "Escada reta", + "pack:nextfloor.treppen:stairs_l": "Escada em L com patamar", + "pack:nextfloor.treppen:stairs_u": "Escada em U", + "pack:nextfloor.treppen:stairs_spiral": "Escada em caracol", + "pack:nextfloor.treppen:stairs_compact": "Escada de poupança de espaço", + "pack:nextfloor.treppen:landing": "Patamar", + "pack:nextfloor.treppen:steps_outdoor": "Degraus exteriores", + "pack:nextfloor.treppen:rail_metal": "Guarda metálica", + "pack:nextfloor.treppen:rail_glass": "Guarda de vidro", + "pack:nextfloor.treppen:rail_wood": "Guarda de madeira", + "pack:nextfloor.treppen:stairs_floating": "Escada flutuante", + "pack:nextfloor.treppen:stairs_u_winder": "Escada em U aberta com degraus em leque", + "pack:nextfloor.treppen:rail_corner": "Guarda de canto", + "packname:nextfloor.werkstatt": "Garagem e oficina", + "pack:nextfloor.werkstatt:workbench": "Bancada de trabalho", + "pack:nextfloor.werkstatt:tool_cabinet": "Armário de ferramentas", + "pack:nextfloor.werkstatt:tool_chest": "Carrinho de ferramentas", + "pack:nextfloor.werkstatt:shelf_rack": "Estante de arrumação", + "pack:nextfloor.werkstatt:tyre_stack": "Pilha de pneus", + "pack:nextfloor.werkstatt:drill_press": "Engenho de furar", + "pack:nextfloor.werkstatt:compressor": "Compressor de ar", + "pack:nextfloor.werkstatt:bike_stand": "Suporte de bicicleta", + "pack:nextfloor.werkstatt:paint_cabinet": "Armário de tintas", + "pack:nextfloor.werkstatt:tool_wall": "Painel de ferramentas", + "pack:nextfloor.werkstatt:heavy_shelf": "Estante de carga pesada", + "pack:nextfloor.werkstatt:chest_freezer_garage": "Arca congeladora", + "pack:nextfloor.werkstatt:tyre_rack": "Suporte de pneus", + "pack:nextfloor.werkstatt:lawn_mower": "Corta-relva", + "pack:nextfloor.werkstatt:bike_stand_2": "Suporte com 2 bicicletas", + "pack:nextfloor.werkstatt:workshop_light": "Luz de oficina", + "pack:nextfloor.werkstatt:garage_opener": "Motor do portão da garagem", + "pack:nextfloor.werkstatt:wallbox_holder": "Wallbox com suporte de cabo", + "pack:nextfloor.werkstatt:wall_bike_holder": "Suporte de parede para bicicletas (2)", + "pack:nextfloor.werkstatt:workshop_vacuum": "Aspirador de oficina", + "pack:nextfloor.werkstatt:workshop_cabinet": "Armário de oficina", + "pack:nextfloor.werkstatt:printer_enclosed": "Impressora 3D fechada", + "packname:nextfloor.wohnen": "Estar e animais", + "pack:nextfloor.wohnen:corner_sofa": "Sofá de canto (em L)", + "pack:nextfloor.wohnen:bean_bag": "Pufe saco", + "pack:nextfloor.wohnen:fireplace": "Lareira", + "pack:nextfloor.wohnen:bookcase_wall": "Estante de parede", + "pack:nextfloor.wohnen:piano": "Piano vertical", + "pack:nextfloor.wohnen:aquarium": "Aquário", + "pack:nextfloor.wohnen:cat_tree": "Árvore para gatos", + "pack:nextfloor.wohnen:dog_bed": "Cama para cães", + "pack:nextfloor.wohnen:hanging_chair": "Cadeira suspensa", + "pack:nextfloor.wohnen:display_cabinet": "Vitrine", + "pack:nextfloor.wohnen:high_table": "Mesa de bar", + "pack:nextfloor.wohnen:floor_mirror": "Espelho de pé", + "furn_tap": "Tocar no item", + "furn_tap_default": "Como habitualmente", + "furn_tap_hint": "Uma ação própria como os botões próprios do menu em estrela, p. ex. um popup do browser_mod com o teu cartão.", + "furn_show_when": "Mostrar apenas enquanto …", + "furn_show_when_state": "… está no estado (vazio = ligado)", + "furn_show_when_invert": "Ao contrário: mostrar enquanto não estiver", + "furn_show_when_hint": "Decoração sazonal que só aparece em dezembro: um auxiliar (input_boolean), um calendário ou um sensor decide se o objeto aparece em 3D. Separe vários estados com vírgulas. O editor mostra-o sempre.", + "picture_upload": "Carregar uma foto", + "picture_replace": "Carregar outra foto", + "picture_stored": "Está guardada uma foto própria.", + "picture_url": "… ou endereço da imagem", + "picture_entity": "… ou a imagem de uma entidade", + "picture_border": "Passe-partout (%)", + "picture_fit": "Foto", + "picture_fit_cover": "preenche a moldura", + "picture_fit_contain": "vê-se inteira", + "picture_hint": "A sua foto na moldura, em 3D e no tablet de parede. As fotos carregadas são guardadas com a planta em tamanho reduzido; uma entidade de imagem (foto do dia) ou uma câmara mostra a imagem atual.", + "card_tap_in_room": "Ligar dispositivos só na divisão aberta", + "card_tap_in_room_hint": "Na vista da casa e do piso, um toque abre o piso ou a divisão, também num dispositivo ou no seu símbolo. Na divisão aberta liga o dispositivo. Um toque longo abre sempre o seu menu ou os detalhes.", + "card_markers_outside": "Escolher os símbolos fora da divisão aberta", + "card_markers_outside_hint": "Na casa, no piso e nas outras divisões só os tipos marcados; na divisão aberta todos, como definido acima. \"Sempre\" e \"Nunca\" no dispositivo têm prioridade.", + "marker_kind_light": "Luzes", + "marker_kind_cover": "Estores", + "marker_kind_climate": "Aquecimento", + "marker_kind_media": "Multimédia", + "marker_kind_switch": "Interruptores", + "marker_kind_fan": "Ventoinhas", + "marker_kind_lock": "Fechaduras", + "marker_kind_binary": "Contactos e detetores", + "marker_kind_sensor": "Sensores", + "marker_kind_tap": "Móveis com ação", + "marker_kind_other": "Outros", + "floor_copy": "Duplicar piso", + "floor_copy_hint": "A cópia vai para o topo da casa com todas as divisões, paredes, portas e janelas. As divisões e o piso perdem a ligação ao Home Assistant, os móveis as suas entidades; os equipamentos de energia ficam no piso antigo.", + "floor_copy_furniture": "Copiar os móveis", + "floor_copy_devices": "Copiar os marcadores de dispositivos", + "floor_copy_devices_hint": "A mesma entidade aparece então nos dois pisos.", + "floor_copy_outdoor": "Copiar as áreas exteriores", + "floor_copy_make": "Criar a cópia", + "floor_copy_name": "{name} (cópia)", + "furn_to_floor": "Mover para o piso", + "furn_to_floor_hint": "O móvel passa para o mesmo sítio no piso escolhido.", + "arc": "Arco", + "arc_hint": "Curva a parede em arco. Uma divisão que partilha a parede curva-se com ela, portas e janelas acompanham; Desfazer retira o arco.", + "arc_bulge": "Curvatura (m)", + "arc_bulge_hint": "Quanto o meio da parede se curva: positivo para fora, negativo para dentro da divisão.", + "arc_apply": "Curvar", + "arc_too_wide": "Uma porta ou janela desta parede é larga demais para esta curva. Torne a curva mais plana ou a abertura mais estreita.", + "time_of_day": "Hora do dia", + "time_of_day_hint": "Mostra sol, luz, sombras e aspeto a outra hora de hoje. Toque de novo para voltar a agora.", + "menu_open": "Menu aberto", + "menu_open_hint": "O menu estrela com favoritos e botões próprios fica aberto desde o início neste dispositivo, um tamanho maior – para um tablet de parede que ativa sobretudo cenas.", + "keep_camera": "Manter câmara", + "keep_camera_hint": "Ao mudar de piso, a câmara mantém o mesmo lado, altura e distância em vez de enquadrar o novo piso a partir do lado inicial.", + "view_zoom": "Zoom", + "view_zoom_hint": "Quão perto chegam as vistas enquadradas – em tablets pequenos a casa parece maior.", + "stair_shape": "Forma", + "stair_shape_straight": "Reta", + "stair_shape_quarter": "Quarto de volta (leque)", + "stair_shape_l": "Em L com patamar", + "stair_shape_half": "Meia volta (leque)", + "stair_shape_u": "Em U com patamar", + "stair_shape_spiral": "Caracol", + "stair_turn": "Sentido de rotação (a subir)", + "stair_turn_left": "Para a esquerda", + "stair_turn_right": "Para a direita", + "stair_build": "Construção", + "stair_build_solid": "Maciça (betão)", + "stair_build_stringer": "Com longarinas", + "stair_build_mono": "Longarina central", + "stair_build_cantilever": "Em consola (flutuantes)", + "stair_risers": "Espelhos", + "stair_steps": "Degraus (número)", + "stair_run_width": "Largura do lanço (m)", + "stair_landing_after": "Degraus até ao patamar", + "stair_landing_hint": "O patamar fica a {h} cm do chão; os outros degraus vêm depois.", + "stair_rail": "Corrimão", + "stair_rail_none": "Nenhum", + "stair_rail_left": "Esquerda", + "stair_rail_right": "Direita", + "stair_rail_both": "Ambos os lados", + "stair_down": "Desce", + "stair_down_hint": "A escada começa neste piso e desce, por exemplo para uma cave que não precisa de ser desenhada. Abre o chão deste piso.", + "stair_measures": "{steps} degraus de {rise} cm · cobertor {going} cm · passo {measure} cm", + "stair_uncomfortable": "desconfortável (passo 59–65 cm, espelho no máximo 21 cm)", + "stair_up_note": "A escada começa no bordo da frente marcado. O piso de cima só abre onde ficam menos de 2,2 m de altura livre sobre os degraus.", + "stair_down_note": "Entra-se na escada pelo bordo da frente marcado e desce-se. A planta desenha-a tracejada; este piso abre por cima dos degraus.", + "stair_upgrade": "Definir a forma", + "stair_upgrade_hint": "Transforma-a numa escada com forma (em leque, L, U, caracol), construção, corrimão e número de degraus.", + "tool_stairs": "Escada", + "hint_stairs": "Arraste onde a escada deve ficar – segue o lado comprido; depois defina forma, sentido e construção à direita", + "stair_opening": "Abertura no piso", + "stair_opening_headroom": "Pela altura livre (só onde é preciso)", + "stair_opening_full": "Sobre toda a escada", + "stair_opening_none": "Nenhuma (alçapão, caixa fechada)", + "stair_opening_hint": "Quanto a escada abre o piso que alcança: o piso de cima, ou o próprio se descer. Pela altura livre só abre sobre os degraus com menos de 2,2 m.", + "stair_up_note_plain": "A escada começa no bordo da frente marcado e sobe para trás." +} diff --git a/custom_components/nextfloor/frontend/lang/ro.json b/custom_components/nextfloor/frontend/lang/ro.json new file mode 100644 index 0000000..24a385b --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/ro.json @@ -0,0 +1,153 @@ +{ + "accent": "Culoare de accent", + "accent_reset": "Înapoi la cyan", + "alert_alarm_by": "Alarmă declanșată de {cause}", + "all_floors": "Toate etajele", + "all_off_done": "Totul oprit.", + "all_off_floor": "Totul oprit pe {floor} ({n} dispozitive), anulare timp de zece secunde", + "all_off_n": "Totul oprit ({n})", + "all_off_undo": "Anulează", + "announce_failed": "Anunțul a eșuat: {error}", + "announce_on": "Anunțurile de pe acest ecran sunt pornite", + "announce_placeholder": "Mesajul tău …", + "announce_send": "Spune-o", + "announce_sent": "Spus: \"{message}\"", + "back": "Înapoi", + "bars_fold": "Ascunde comutatoarele", + "bars_unfold": "Comutatoare", + "battery_low_n": "Baterie slabă: {names}", + "brightness": "Luminozitate", + "card_description": "Casa ta în 3D (neon).", + "card_floor_stack": "Etaje dedesubt", + "card_room_buttons": "Butoane de cameră", + "care_bin_days": "Peste {n} zile", + "care_bin_today": "Se ridică azi", + "care_bin_tomorrow": "Se ridică mâine", + "care_time_left": "{time} rămase", + "central": "Central: toate luminile, jaluzelele și favoritele", + "central_covers": "Jaluzele", + "central_favorites": "Favorite", + "central_house": "Toată casa", + "central_lights": "Lumini", + "central_sure": "Sigur?", + "clock": "Ceas", + "close": "Închide", + "color": "Culoare", + "color_temp": "Temperatura culorii", + "comfort_n": "Confort {n}", + "confirm_switch": "Sigur comuți {name}?", + "cover_close": "Închide", + "cover_my_go": "La poziția favorită ({p} %)", + "cover_open": "Deschide", + "cover_stop": "Stop", + "cover_tilt": "Lamele", + "cover_tilt_close": "Lamele închise", + "cover_tilt_open": "Lamele deschise", + "delete": "Șterge", + "details": "Detalii", + "draft_discard": "Renunță", + "draft_found": "Au fost găsite modificări nesalvate de la {time}.", + "draft_restore": "Restaurează și salvează", + "empty_lights_hint": "{n} lumini aprinse, nimeni aici de {min} min.", + "empty_lights_off": "Stinge luminile", + "energy_battery": "Baterie", + "energy_consumption": "Consum", + "energy_rest": "Comun (rest)", + "energy_solar": "Solar", + "energy_tariff": "Tarif", + "ext_tab": "Extensii", + "find": "Caută", + "find_none": "Nu s-a găsit nimic", + "find_placeholder": "Unde este …? Dispozitiv sau cameră", + "floor_layer": "Strat (poate fi afișat și ascuns)", + "floor_power_share": "{n} % din casă", + "floor_rooms": "{n} camere", + "floor_rooms_one": "1 cameră", + "floors": "Etaje", + "floors_apart": "Separate", + "floors_stacked": "Suprapuse", + "flows": "Flux de energie", + "fps_title": "Afișare performanță (cadre pe secundă)", + "glass_walls": "Pereți de sticlă", + "heat_none_found": "Nu există senzori potriviți în zonele camerelor.", + "heat_wifi": "Wi-Fi", + "heatmap": "Hartă termică", + "holos": "Carduri", + "keep_camera": "Păstrează camera", + "load_error": "Încărcarea a eșuat", + "loading": "Se încarcă …", + "markers": "Marcaje", + "media_next": "Următorul", + "media_previous": "Anteriorul", + "media_sources": "Surse", + "media_volume": "Volum", + "menu_open": "Meniu deschis", + "meter_unmetered": "{w} nemăsurat", + "mood_carry": "Transferă în altă cameră", + "mood_new": "Atmosferă", + "mood_save": "Salvează atmosfera", + "mood_set": "Folosește această atmosferă", + "next": "Următorul", + "no_building": "Încă nu există plan.", + "open_editor": "Deschide editorul", + "open_heating_hint": "{n} ferestre deschise cât timp merge încălzirea.", + "open_heating_off": "Oprește încălzirea", + "open_since": "deschis de {time}", + "outside_area": "Afară", + "panel_all_close": "Toate jos", + "panel_all_off": "Toate oprite", + "panel_all_on": "Toate pornite", + "panel_all_open": "Toate sus", + "panel_less": "Arată mai puțin", + "panel_more": "Mai multe dispozitive din zonă ({n})", + "plain": "Doar planul", + "play_pause": "Redare/pauză", + "pool_pump_on": "pompă pornită", + "position": "Poziție", + "presence_last": "văzut ultima dată acum {time}", + "presence_now": "cineva este aici", + "presets": "Posturi și liste de redare (sunet)", + "previous": "Înapoi", + "qm_off": "Oprit", + "readable": "Ușor de citit", + "reload_page": "Reîncarcă", + "right_back": "Clic dreapta = înapoi", + "roof_keep": "Acoperișul rămâne", + "room_clean_run": "Curăță", + "room_clean_run_hint": "Trimite aspiratorul robot în această cameră.", + "room_curve_hint": "Temperatura camerei în ultimele 24 de ore", + "room_energy": "azi {today} · luna {month}", + "room_sun_hours": "{h} h de soare azi ({facing})", + "room_sun_year": "Soarele peste an", + "save_failed_detail": "Salvarea a eșuat: {error}. Modificările tale rămân în acest browser.", + "screen_name": "Numele acestui ecran", + "shade_close": "Coboară", + "shade_hint": "Soare pe {n} ferestre la {temp} – coborâm jaluzelele?", + "stats_idle": "În repaus (0 fps)", + "stl": "Imprimare 3D (STL)", + "swipe_off": "Oprit", + "target_temp": "Țintă", + "temp_down": "Mai rece", + "temp_up": "Mai cald", + "time_of_day": "Ora din zi", + "today": "Azi", + "today_none": "Nimic azi.", + "travel": "Călătorie în timp: redă ultimele 24 de ore sau 7 zile", + "travel_days": "zile", + "travel_failed": "Istoricul nu a putut fi încărcat.", + "travel_live": "În direct", + "travel_loading": "Se încarcă istoricul …", + "travel_speed": "Viteză", + "view_options": "Vizualizare: calitate, aspect, marcaje, FPS", + "view_zoom": "Zoom", + "volume": "Volum", + "wallbox_charging": "se încarcă", + "wallbox_plugged": "conectat", + "walls_auto": "Pereți înalți", + "walls_cut": "Secțiune", + "walls_slope": "Înclinat", + "walls_solid": "Pline", + "wifi_aps": "{n} puncte de acces · {clients} dispozitive", + "wifi_clients": "{n} dispozitive", + "wifi_network": "Rețea: {online} online · {offline} offline" +} diff --git a/custom_components/nextfloor/frontend/lang/sk.json b/custom_components/nextfloor/frontend/lang/sk.json new file mode 100644 index 0000000..f2effce --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/sk.json @@ -0,0 +1,153 @@ +{ + "accent": "Akcentová farba", + "accent_reset": "Späť na azúrovú", + "alert_alarm_by": "Alarm spustil {cause}", + "all_floors": "Všetky podlažia", + "all_off_done": "Všetko vypnuté.", + "all_off_floor": "Všetko vypnuté na {floor} ({n} zariadení), späť desať sekúnd", + "all_off_n": "Všetko vypnúť ({n})", + "all_off_undo": "Späť", + "announce_failed": "Hlásenie zlyhalo: {error}", + "announce_on": "Hlásenia na tejto obrazovke sú zapnuté", + "announce_placeholder": "Tvoja správa …", + "announce_send": "Povedať", + "announce_sent": "Povedané: \"{message}\"", + "back": "Späť", + "bars_fold": "Skryť prepínače", + "bars_unfold": "Prepínače", + "battery_low_n": "Slabá batéria: {names}", + "brightness": "Jas", + "card_description": "Tvoj domov v 3D (neón).", + "card_floor_stack": "Podlažia pod tým", + "card_room_buttons": "Tlačidlá miestností", + "care_bin_days": "O {n} dní", + "care_bin_today": "Odvoz dnes", + "care_bin_tomorrow": "Odvoz zajtra", + "care_time_left": "Zostáva {time}", + "central": "Centrála: všetky svetlá, žalúzie a obľúbené", + "central_covers": "Žalúzie", + "central_favorites": "Obľúbené", + "central_house": "Celý dom", + "central_lights": "Svetlá", + "central_sure": "Určite?", + "clock": "Hodiny", + "close": "Zavrieť", + "color": "Farba", + "color_temp": "Teplota farby", + "comfort_n": "Komfort {n}", + "confirm_switch": "Naozaj prepnúť {name}?", + "cover_close": "Zavrieť", + "cover_my_go": "Do obľúbenej polohy ({p} %)", + "cover_open": "Otvoriť", + "cover_stop": "Zastaviť", + "cover_tilt": "Lamely", + "cover_tilt_close": "Lamely zatvorené", + "cover_tilt_open": "Lamely otvorené", + "delete": "Odstrániť", + "details": "Podrobnosti", + "draft_discard": "Zahodiť", + "draft_found": "Našli sa neuložené zmeny z {time}.", + "draft_restore": "Obnoviť a uložiť", + "empty_lights_hint": "{n} svetiel svieti, nikto tu nie je {min} min.", + "empty_lights_off": "Vypnúť svetlá", + "energy_battery": "Batéria", + "energy_consumption": "Spotreba", + "energy_rest": "Spoločné (zvyšok)", + "energy_solar": "Slnko", + "energy_tariff": "Tarifa", + "ext_tab": "Rozšírenia", + "find": "Hľadať", + "find_none": "Nič sa nenašlo", + "find_placeholder": "Kde je …? Zariadenie alebo miestnosť", + "floor_layer": "Vrstva (dá sa zobraziť a skryť)", + "floor_power_share": "{n} % domu", + "floor_rooms": "{n} miestností", + "floor_rooms_one": "1 miestnosť", + "floors": "Podlažia", + "floors_apart": "Oddelené", + "floors_stacked": "Naskladané", + "flows": "Tok energie", + "fps_title": "Zobrazenie výkonu (snímky za sekundu)", + "glass_walls": "Sklenené steny", + "heat_none_found": "V oblastiach miestností nie sú vhodné senzory.", + "heat_wifi": "Wi-Fi", + "heatmap": "Teplotná mapa", + "holos": "Karty", + "keep_camera": "Ponechať kameru", + "load_error": "Načítanie zlyhalo", + "loading": "Načítava sa …", + "markers": "Značky", + "media_next": "Ďalší", + "media_previous": "Predchádzajúci", + "media_sources": "Zdroje", + "media_volume": "Hlasitosť", + "menu_open": "Ponuka otvorená", + "meter_unmetered": "{w} nemerané", + "mood_carry": "Preniesť do inej miestnosti", + "mood_new": "Nálada", + "mood_save": "Uložiť náladu", + "mood_set": "Nastaviť túto náladu", + "next": "Ďalej", + "no_building": "Zatiaľ žiadny pôdorys.", + "open_editor": "Otvoriť editor", + "open_heating_hint": "{n} okien je otvorených, kým beží kúrenie.", + "open_heating_off": "Vypnúť kúrenie", + "open_since": "otvorené {time}", + "outside_area": "Vonku", + "panel_all_close": "Všetko dole", + "panel_all_off": "Všetko vypnúť", + "panel_all_on": "Všetko zapnúť", + "panel_all_open": "Všetko hore", + "panel_less": "Zobraziť menej", + "panel_more": "Ďalšie zariadenia oblasti ({n})", + "plain": "Len pôdorys", + "play_pause": "Prehrať/pauza", + "pool_pump_on": "čerpadlo zapnuté", + "position": "Poloha", + "presence_last": "naposledy videný pred {time}", + "presence_now": "niekto je tu", + "presets": "Stanice a zoznamy skladieb (zvuk)", + "previous": "Späť", + "qm_off": "Vypnuté", + "readable": "Dobre čitateľné", + "reload_page": "Načítať znova", + "right_back": "Pravý klik = späť", + "roof_keep": "Strecha ostáva", + "room_clean_run": "Upratať", + "room_clean_run_hint": "Pošle robotický vysávač do tejto miestnosti.", + "room_curve_hint": "Teplota miestnosti za posledných 24 hodín", + "room_energy": "dnes {today} · mesiac {month}", + "room_sun_hours": "{h} h slnka dnes ({facing})", + "room_sun_year": "Slnko počas roka", + "save_failed_detail": "Uloženie zlyhalo: {error}. Zmeny zostanú v tomto prehliadači.", + "screen_name": "Názov tejto obrazovky", + "shade_close": "Spustiť", + "shade_hint": "Slnko na {n} oknách pri {temp} – spustiť žalúzie?", + "stats_idle": "V pokoji (0 fps)", + "stl": "3D tlač (STL)", + "swipe_off": "Vypnúť", + "target_temp": "Cieľ", + "temp_down": "Chladnejšie", + "temp_up": "Teplejšie", + "time_of_day": "Denný čas", + "today": "Dnes", + "today_none": "Dnes nič.", + "travel": "Cestovanie v čase: prehrať posledných 24 hodín alebo 7 dní", + "travel_days": "dní", + "travel_failed": "Históriu sa nepodarilo načítať.", + "travel_live": "Naživo", + "travel_loading": "Načítava sa história …", + "travel_speed": "Rýchlosť", + "view_options": "Zobrazenie: kvalita, vzhľad, značky, FPS", + "view_zoom": "Priblíženie", + "volume": "Hlasitosť", + "wallbox_charging": "nabíja", + "wallbox_plugged": "pripojené", + "walls_auto": "Vysoké steny", + "walls_cut": "Rez", + "walls_slope": "Šikmé", + "walls_solid": "Plné", + "wifi_aps": "{n} prístupových bodov · {clients} zariadení", + "wifi_clients": "{n} zariadení", + "wifi_network": "Sieť: {online} online · {offline} offline" +} diff --git a/custom_components/nextfloor/frontend/lang/sl.json b/custom_components/nextfloor/frontend/lang/sl.json new file mode 100644 index 0000000..ece51f6 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/sl.json @@ -0,0 +1,153 @@ +{ + "accent": "Poudarna barva", + "accent_reset": "Nazaj na cian", + "alert_alarm_by": "Alarm sprožil {cause}", + "all_floors": "Vsa nadstropja", + "all_off_done": "Vse izklopljeno.", + "all_off_floor": "Vse izklopljeno na {floor} ({n} naprav), razveljavitev deset sekund", + "all_off_n": "Vse izklopi ({n})", + "all_off_undo": "Razveljavi", + "announce_failed": "Obvestilo ni uspelo: {error}", + "announce_on": "Obvestila na tem zaslonu so vklopljena", + "announce_placeholder": "Tvoje sporočilo …", + "announce_send": "Povej", + "announce_sent": "Povedano: \"{message}\"", + "back": "Nazaj", + "bars_fold": "Skrij stikala", + "bars_unfold": "Stikala", + "battery_low_n": "Šibka baterija: {names}", + "brightness": "Svetlost", + "card_description": "Tvoj dom v 3D (neon).", + "card_floor_stack": "Nadstropja spodaj", + "card_room_buttons": "Gumbi prostorov", + "care_bin_days": "Čez {n} dni", + "care_bin_today": "Odvoz danes", + "care_bin_tomorrow": "Odvoz jutri", + "care_time_left": "Še {time}", + "central": "Središče: vse luči, žaluzije in priljubljene", + "central_covers": "Žaluzije", + "central_favorites": "Priljubljene", + "central_house": "Celotna hiša", + "central_lights": "Luči", + "central_sure": "Prepričan?", + "clock": "Ura", + "close": "Zapri", + "color": "Barva", + "color_temp": "Barvna temperatura", + "comfort_n": "Udobje {n}", + "confirm_switch": "Res preklopim {name}?", + "cover_close": "Zapri", + "cover_my_go": "V priljubljeni položaj ({p} %)", + "cover_open": "Odpri", + "cover_stop": "Ustavi", + "cover_tilt": "Lamele", + "cover_tilt_close": "Lamele zaprte", + "cover_tilt_open": "Lamele odprte", + "delete": "Izbriši", + "details": "Podrobnosti", + "draft_discard": "Zavrzi", + "draft_found": "Najdene neshranjene spremembe od {time}.", + "draft_restore": "Obnovi in shrani", + "empty_lights_hint": "{n} luči gori, nikogar ni {min} min.", + "empty_lights_off": "Ugasni luči", + "energy_battery": "Baterija", + "energy_consumption": "Poraba", + "energy_rest": "Skupno (ostalo)", + "energy_solar": "Sonce", + "energy_tariff": "Tarifa", + "ext_tab": "Razširitve", + "find": "Iskanje", + "find_none": "Nič ni najdeno", + "find_placeholder": "Kje je …? Naprava ali prostor", + "floor_layer": "Plast (je mogoče prikazati in skriti)", + "floor_power_share": "{n} % hiše", + "floor_rooms": "{n} prostorov", + "floor_rooms_one": "1 prostor", + "floors": "Nadstropja", + "floors_apart": "Narazen", + "floors_stacked": "Naloženo", + "flows": "Tok energije", + "fps_title": "Prikaz zmogljivosti (sličice na sekundo)", + "glass_walls": "Steklene stene", + "heat_none_found": "V območjih prostorov ni ustreznih senzorjev.", + "heat_wifi": "Wi-Fi", + "heatmap": "Toplotna karta", + "holos": "Kartice", + "keep_camera": "Obdrži kamero", + "load_error": "Nalaganje ni uspelo", + "loading": "Nalaganje …", + "markers": "Oznake", + "media_next": "Naslednji", + "media_previous": "Prejšnji", + "media_sources": "Viri", + "media_volume": "Glasnost", + "menu_open": "Meni odprt", + "meter_unmetered": "{w} brez meritve", + "mood_carry": "Prenesi v drug prostor", + "mood_new": "Vzdušje", + "mood_save": "Shrani vzdušje", + "mood_set": "Nastavi to vzdušje", + "next": "Naprej", + "no_building": "Še ni tlorisa.", + "open_editor": "Odpri urejevalnik", + "open_heating_hint": "{n} oken je odprtih, medtem ko deluje ogrevanje.", + "open_heating_off": "Izklopi ogrevanje", + "open_since": "odprto {time}", + "outside_area": "Zunaj", + "panel_all_close": "Vse dol", + "panel_all_off": "Vse izklopi", + "panel_all_on": "Vse vklopi", + "panel_all_open": "Vse gor", + "panel_less": "Pokaži manj", + "panel_more": "Več naprav območja ({n})", + "plain": "Samo tloris", + "play_pause": "Predvajaj/premor", + "pool_pump_on": "črpalka vklopljena", + "position": "Položaj", + "presence_last": "nazadnje viden pred {time}", + "presence_now": "nekdo je tukaj", + "presets": "Postaje in seznami predvajanja (zvok)", + "previous": "Nazaj", + "qm_off": "Izklop", + "readable": "Dobro berljivo", + "reload_page": "Znova naloži", + "right_back": "Desni klik = nazaj", + "roof_keep": "Streha ostane", + "room_clean_run": "Počisti", + "room_clean_run_hint": "Pošlje robotski sesalnik v ta prostor.", + "room_curve_hint": "Temperatura prostora v zadnjih 24 urah", + "room_energy": "danes {today} · mesec {month}", + "room_sun_hours": "{h} h sonca danes ({facing})", + "room_sun_year": "Sonce skozi leto", + "save_failed_detail": "Shranjevanje ni uspelo: {error}. Vaše spremembe ostanejo v tem brskalniku.", + "screen_name": "Ime tega zaslona", + "shade_close": "Spusti", + "shade_hint": "Sonce na {n} oknih pri {temp} – spustim žaluzije?", + "stats_idle": "V mirovanju (0 fps)", + "stl": "3D-tisk (STL)", + "swipe_off": "Izklop", + "target_temp": "Cilj", + "temp_down": "Hladneje", + "temp_up": "Toplejše", + "time_of_day": "Čas dneva", + "today": "Danes", + "today_none": "Danes ni ničesar.", + "travel": "Potovanje v času: predvajaj zadnjih 24 ur ali 7 dni", + "travel_days": "dni", + "travel_failed": "Zgodovine ni bilo mogoče naložiti.", + "travel_live": "V živo", + "travel_loading": "Nalaganje zgodovine …", + "travel_speed": "Hitrost", + "view_options": "Pogled: kakovost, videz, oznake, FPS", + "view_zoom": "Povečava", + "volume": "Glasnost", + "wallbox_charging": "polni", + "wallbox_plugged": "priključeno", + "walls_auto": "Visoke stene", + "walls_cut": "Prerez", + "walls_slope": "Poševno", + "walls_solid": "Polne", + "wifi_aps": "{n} dostopnih točk · {clients} naprav", + "wifi_clients": "{n} naprav", + "wifi_network": "Omrežje: {online} na spletu · {offline} brez povezave" +} diff --git a/custom_components/nextfloor/frontend/lang/sv.json b/custom_components/nextfloor/frontend/lang/sv.json new file mode 100644 index 0000000..751f092 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/sv.json @@ -0,0 +1,2763 @@ +{ + "view": "3D", + "editor": "Redigerare", + "all_floors": "Alla våningar", + "outside_area": "Ute", + "outside_area_hint": "Alla enheter utomhus på en gång: i trädgården, utanför rummen och det som hör till Ute (till exempel väderstationen på taket).", + "device_outside": "Hör till Ute", + "device_outside_hint": "Enheten räknas inte till rummet under den (en väderstation på taket) och visas i panelen Ute.", + "no_building": "Ingen planritning ännu.", + "no_building_admin": "Ingen planritning ännu. Rita din första våning i redigeraren.", + "no_rooms_admin": "Våningarna finns, men det finns inget rum än. Enbart väggar räcker inte: rita minst ett rum i redigeraren med ”Rektangel” eller ”Fri form”.", + "open_editor": "Öppna redigeraren", + "loading": "Laddar …", + "load_error": "Laddningen misslyckades", + "saving": "Sparar …", + "saved": "Sparat", + "save_error": "Sparandet misslyckades", + "save_failed_detail": "Sparandet misslyckades: {error}. Dina ändringar finns kvar i den här webbläsaren.", + "needs_restart": "En ny version av NextFloor ({frontend}) är installerad, men Home Assistant kör fortfarande {version}. Starta om Home Assistant – tills dess kan sparandet misslyckas.", + "needs_reload": "Den här sidan visar fortfarande NextFloor {frontend}, Home Assistant har redan {backend}. Ladda om sidan; i companion-appen: Inställningar → Companion-app → Återställ frontend-cache.", + "reload_page": "Ladda om", + "needs_restart_old": "En ny version av NextFloor är installerad, men Home Assistant kör fortfarande en äldre. Starta om Home Assistant – tills dess misslyckas sparandet.", + "draft_found": "Osparade ändringar från {time} hittades.", + "draft_restore": "Återställ och spara", + "draft_discard": "Kasta", + "walls_auto": "Höga väggar", + "walls_cut": "Snitt", + "walls_slope": "Snett", + "walls_slope_hint": "Väggar snett avskurna: halvhöga framtill, full höjd baktill – som ett dockskåp; vrids med kameran", + "walls_solid": "Massiva", + "walls_solid_hint": "Massiva väggar i sina färger i stället för glas (färger: redigeraren → inställningar, per rum i rummet)", + "wall_paint_outside": "Väggfärg ute", + "wall_paint_inside": "Väggfärg inne", + "wall_paint_room": "Väggfärg inne (det här rummet)", + "wall_paint_hint": "Används i 3D-vyn ”Massiva”.", + "wall_paint_default": "Standard", + "card_solid_walls": "Massiva väggar (i sina färger)", + "reset_view": "Översikt", + "back": "Tillbaka", + "floor": "Våning", + "floors": "Våningar", + "add_floor": "Lägg till våning", + "floor_from_ha": "Våningar från Home Assistant:", + "floor_empty": "Tom våning", + "level": "Nivå {n}", + "ha_floor": "Våning i Home Assistant", + "floor_layer": "Lager (kan visas och döljas)", + "floor_power": "Våningsmätare (effekt)", + "floor_power_hint": "En effektsensor bara för den här våningen (en undermätare, en lägenhet). Värdet visas på våningsetiketten och, i vyn för den här våningen, på huskortet med dess andel av husets förbrukning.", + "floor_power_share": "{n} % av huset", + "living_area": "Boarea {living}", + "room_living": "Räknas som boarea", + "living_area_none": "Ingen boarea · golv {floor}", + "living_area_low": "Boarea {living} (golv {floor}, varav {low} under 2 m)", + "living_area_hint": "Räknat som tyska Wohnflächenverordnung: golvet innanför väggarna, helt från 2 m fri höjd, till hälften mellan 1 och 2 m (under snedtak), inte alls under 1 m. Ett riktvärde, inte en uppmätning.", + "living_area_floor": "Boarea: {floor}", + "living_area_floor_house": "Boarea på våningen: {floor} · hela huset: {house}", + "print_plan": "Skriv ut planen / PDF", + "print_plan_hint": "Varje våning som en ren plan med mått och ytor, plus en ytatabell – att skriva ut eller spara som PDF i utskriftsdialogen.", + "print_title": "Planritning", + "print_room": "Rum", + "print_floor_area": "Golvyta", + "print_living": "Boarea", + "print_low": "under 2 m", + "print_total": "Summa", + "print_blocked": "Utskriftsfönstret blockerades – tillåt popup-fönster för Home Assistant.", + "check_open": "Kontrollera planen", + "note": "Anteckning", + "note_add": "Anteckning här", + "note_text": "Text", + "note_placeholder": "t.ex. ”byt filtret” eller ”säkring 12”", + "note_due": "Förfaller", + "note_due_hint": "Från den dagen blir nålen orange.", + "note_is_due": "Den här anteckningen har förfallit.", + "keys_title": "Tangenter i editorn", + "keys_undo": "Ångra", + "keys_redo": "Gör om", + "keys_duplicate": "Duplicera rummet", + "keys_delete": "Ta bort markeringen", + "keys_nudge": "Flytta markeringen ett rutsteg", + "keys_nudge_10": "… 10 cm", + "keys_nudge_1": "… 1 cm", + "keys_rotate": "Vrid möbeln 90° (Skift: tillbaka)", + "keys_lock": "Lås eller lossa en möbel, en enhet eller en takdel", + "keys_close_shape": "Stäng den fria formen", + "keys_escape": "Avbryt, lämna verktyget, avmarkera", + "keys_straight": "Vid ritning: raka linjer", + "keys_sheet": "Den här översikten", + "tour_title": "Första stegen", + "tour_1_title": "Rita rummen", + "tour_1": "Rita rummen med ”{rect}” eller ”{free}”; väggarna kommer av sig själva. Ge varje rum sitt Home Assistant-område – då hittar NextFloor dess enheter. Har du redan områden lägger ”{rooms}” i våningsformuläret till alla på en gång.", + "tour_2_title": "Dörrar och fönster", + "tour_2": "”{opening}” sätter dem på en vägg. Koppla deras kontakt eller rullgardin – i 3D öppnas och stängs de då med den, och öppna fönster säger till.", + "tour_3_title": "Möbler och enheter", + "tour_3": "”{furniture}” öppnar biblioteket – eller bygg egna i 🛠️ möbelverkstaden. Välj ett rum så listas områdets enheter nedanför, redo att placeras; lampor lyser då i sitt ljus färg.", + "tour_4_title": "Titta och kontrollera", + "tour_4": "”{split}” visar huset medan du ritar; överst byter du till 3D-vyn. ”{check}” listar vad som fortfarande saknas – och ? visar tangenterna när som helst.", + "tour_next": "Nästa", + "tour_back": "Tillbaka", + "tour_done": "Nu kör vi", + "tour_skip": "Hoppa över", + "check_open_hint": "Visar vad som saknas eller är fel i planen, med en lösning i ett tryck.", + "check_title": "Plankontroll", + "check_all_good": "Allt i ordning – inget hittades.", + "check_hint": "{n} punkter hittades. Blå knappar ändrar planen (ångra fungerar som vanligt), de andra visar platsen.", + "check_room_no_area": "”{room}” har inget Home Assistant-område: dess enheter hittas inte.", + "check_room_no_area_named": "”{room}” har inget område – det lediga området ”{area}” heter likadant.", + "check_areas_unplaced": "{n} områden på den här våningen har inget rum än: {names}", + "check_devices_unplaced": "”{room}”: {n} enheter i området finns inte i planen än.", + "check_rooms_overlap": "”{a}” och ”{b}” överlappar.", + "check_opening_off_wall": "En dörr eller ett fönster i ”{room}” sitter inte på någon vägg.", + "check_entity_missing": "{n} enhetsnålar pekar på entiteter som Home Assistant inte längre känner till ({ids}).", + "check_furniture_entity_missing": "En möbel är kopplad till {id} – den entiteten finns inte längre.", + "check_battery_low": "Låg batterinivå: {name} ({level} %)", + "battery_low_n": "Låg batterinivå: {names}", + "check_standby": "{name} drar {w} W fast den är av – ungefär {cost} om året.", + "check_fix_show": "Visa", + "check_fix_set_area": "Koppla ”{area}”", + "check_fix_add_rooms": "Lägg till rummen", + "check_fix_place": "Placera {n}", + "check_fix_remove": "Ta bort {n}", + "floor_layer_hint": "Den här våningen är inget plan utan ett lager – alla träd eller dekorationen. 3D-vyn visar ett öga överst som visar eller döljer det på varje enhet.", + "no_ha_floor": "– ingen –", + "area_rooms": "Lägg till rum från HA-områden ({n})", + "area_rooms_hint": "Lägger till ett rum (4 × 3 m) för varje område på den här våningen – dra det sedan på plats och justera hörnen", + "floor_name": "Namn", + "elevation": "Höjd över mark (m)", + "floor_shift": "Flytta våningen (m)", + "floor_shift_apply": "Flytta", + "floor_shift_hint": "Flyttar alla rum, möbler, enheter, uteytor, fristående väggar och bakgrundsbilden på den här våningen i X och Z. Takfall ligger kvar.", + "height": "Takhöjd (m)", + "cut_height": "Snitthöjd (m)", + "delete_floor": "Ta bort våning", + "delete_floor_confirm": "Ta bort våningen ”{name}” med alla dess rum?", + "move_up": "Flytta upp", + "move_down": "Flytta ner", + "default_floor": "Bottenvåning", + "new_floor": "Våning {n}", + "tool_select": "Välj", + "tool_rect": "Rektangel", + "tool_polygon": "Fri form", + "undo": "Ångra", + "redo": "Gör om", + "fit": "Visa allt", + "room": "Rum", + "rooms": "Rum", + "room_name": "Namn", + "area": "Område", + "no_area": "Inget område", + "sub_area_add": "+ Område i rummet", + "sub_area_hint": "En del av rummet med ett eget Home Assistant-område men utan väggar – en läshörna, en hylla, ett pentry i vardagsrummet. Dess enheter och sensorer hör till det här rummet.", + "material": "Golv", + "x": "X (m)", + "z": "Y (m)", + "width": "Bredd (m)", + "depth": "Djup (m)", + "points": "Hörn", + "delete_point": "Ta bort hörn", + "duplicate": "Duplicera", + "delete": "Ta bort", + "new_room": "Rum {n}", + "settings": "Inställningar", + "pendant_shape": "Form", + "pendant_shade": "Skärm", + "paint_colour": "Målarfärg", + "pendant_globe": "Glob", + "pendant_cone": "Kon", + "pendant_drum": "Trumma", + "sofa_shape": "Form", + "sofa_straight": "Rak", + "sofa_l": "L-form (spegla: andra sidan)", + "sofa_u": "U-form", + "pkg_open": "Möblera …", + "pkg_hint": "Möbler placeras mot rummets väggar; lampor kopplas till områdets lampor. Justera enskilda saker efteråt – Ctrl+Z ångrar allt.", + "pkg_done": "{n} saker placerade – Ctrl+Z ångrar.", + "pkg_kitchen_row": "Rakt kök", + "pkg_kitchen_row_desc": "Rad på bakväggen med kylskåp, ugn, diskho, diskmaskin och spis, väggskåp, matbord med taklampa", + "pkg_kitchen_l": "L-kök", + "pkg_kitchen_l_desc": "Rader baktill och till vänster, köksö med barstolar", + "pkg_bath": "Badrum", + "pkg_bath_desc": "Handfat, toalett, badkar, tvättmaskin, downlight", + "pkg_bedroom": "Sovrum", + "pkg_bedroom_desc": "Dubbelsäng med två nattduksbord, garderob, byrå, taklampa", + "pkg_living": "Vardagsrum", + "pkg_living_desc": "TV-bänk, soffa, soffbord, matta, fåtölj, hylla, golvlampa, växt", + "pkg_dining": "Matsal", + "pkg_dining_desc": "Bord med fyra stolar, skänk, pendellampa", + "pkg_office": "Kontor", + "pkg_office_desc": "Skrivbord med kontorsstol, två hyllor, taklampa", + "pkg_kids": "Barnrum", + "pkg_kids_desc": "Enkelsäng, skrivbord, hylla, matta", + "pkg_hall": "Hall", + "pkg_hall_desc": "Klädhängare, två downlights", + "spots_place": "Placera spotlights", + "spots_type": "Lampa", + "spots_cols": "Kolumner (vänster–höger)", + "spots_rows": "Rader (fram–bak)", + "spots_add": "Placera {n} lampor", + "spots_placed": "{n} lampor placerade.", + "spots_hint": "Alla lampor följer den valda lampan (t.ex. spotlights på en dimmer). Efteråt kan varje lampa flyttas och kopplas till en annan lampa som vilken möbel som helst.", + "cancel": "Avbryt", + "backup": "Säkerhetskopia", + "backup_history": "Återställningspunkter", + "share_view": "Dela en vy", + "share_view_hint": "Sparar huset som en liten fil som öppnas i vilken webbläsare som helst utan Home Assistant (via NextFloors onlinedemo) – för att visa det för familj eller en planerare. Utan enheter och entiteter, som en mall.", + "share_view_title": "Vårt hem i NextFloor", + "share_view_needs_js": "Den här sidan behöver JavaScript och en internetanslutning.", + "share_view_file": "vy", + "share_view_done": "Vy sparad – öppna filen i en webbläsare eller skicka den vidare.", + "version_save": "Spara det här läget …", + "version_save_hint": "Sparar planen under ett namn (”före renoveringen”). Namngivna lägen stannar när de automatiska återställningspunkterna försvinner.", + "version_name_prompt": "Namn på det här läget (t.ex. ”före renoveringen”):", + "version_saved": "Läget ”{name}” sparat.", + "version_compare": "Jämför", + "version_delete_confirm": "Ta bort ”{name}”?", + "version_same": "Ingen skillnad mot planen.", + "version_diff_n": "{n} skillnader mot planen som den är nu:", + "diff_floor_added": "Våning ”{name}” tillagd", + "diff_floor_removed": "Våning ”{name}” borttagen", + "diff_room_added": "Rum ”{name}” tillagt", + "diff_room_removed": "Rum ”{name}” borttaget", + "diff_room_renamed": "”{detail}” heter nu ”{name}”", + "diff_room_reshaped": "”{name}” omformat ({detail} m²)", + "diff_opening_added": "{name} tillagt ({detail})", + "diff_opening_removed": "{name} borttaget ({detail})", + "diff_furniture_added": "{name} tillagd", + "diff_furniture_removed": "{name} borttagen", + "diff_furniture_moved": "{name} flyttad eller ändrad", + "diff_device_added": "Enhet {name} placerad", + "diff_device_removed": "Enhet {name} borttagen", + "diff_device_moved": "Enhet {name} flyttad", + "backup_none": "Inga ännu. Under redigering sparas högst var tionde minut en återställningspunkt.", + "backup_summary": "{rooms} rum, {furniture} saker", + "backup_restore": "Återställ", + "backup_restore_confirm": "Återställa läget från {time}? Det nuvarande läget sparas som återställningspunkt.", + "backup_restored": "Återställt.", + "backup_file": "Fil", + "backup_export": "Exportera", + "backup_export_share": "Dela som mall", + "backup_export_share_hint": "Utan områden, enheter, sensorer och bilder – för att ge vidare till andra.", + "backup_import": "Importera …", + "backup_import_confirm": "Ersätta hela planritningen med filen? Det nuvarande läget sparas som återställningspunkt.", + "backup_import_error": "Filen är ingen NextFloor-planritning ({error}).", + "backup_imported": "Importerat.", + "backup_hint": "Bakgrundsbilder ingår inte i filen.", + "backup_full": "Fullständig säkerhetskopia", + "backup_full_export": "Spara allt (planritning, bilder, paket)", + "backup_full_import": "Återställ en fullständig säkerhetskopia …", + "backup_full_hint": "En fil med planritningen, alla bakgrunds- och skärmbilder och de installerade paketen. Vid återställning kontrolleras varje paket igen; licensnyckeln ingår inte.", + "backup_full_confirm": "Ersätta planritning, bilder och paket med säkerhetskopian? Det nuvarande läget blir en återställningspunkt.", + "backup_full_not_backup": "Det här är ingen fullständig säkerhetskopia av NextFloor.", + "backup_full_restored": "Säkerhetskopia återställd: {packs} paket, {pictures} bilder.", + "backup_full_skipped": "Hoppades över (kunde inte läsas): {packs}.", + "export_name_full": "fullständig", + "device_confirm": "Fråga innan växling", + "device_confirm_hint": "Ett tryck i 3D, snabbmenyn och rumspanelen frågar först. Ett dubbeltryck på rummet utesluter den här enheten.", + "cover_confirm_hint": "Öppna, stäng och positioner frågar först i snabbmenyn och rumspanelen, och ett svep på markören flyttar inte längre persiennen (det vrider vyn). Stopp frågar aldrig.", + "blind_kind": "Typ av solskydd", + "blind_roller": "Rulljalusi utvändig", + "blind_venetian": "Utvändig persienn med lameller", + "blind_inside": "Rullgardin invändig", + "cover2_entity": "Andra jalusin (högra halvan)", + "cover_my": "Favoritläge ”My” (%, 0 = inget)", + "cover_my_go": "Till favoritläget ({p} %)", + "blind_hint": "En utvändig persienn vrider sina lameller i 3D efter jalusins lutning; en invändig rullgardin hänger bakom glaset. Ett brett fönster kan ha en andra jalusi för högra halvan. Favoritläget visas som ”My” i snabbmenyn: en jalusi med lägen åker dit, en Somfy RTS-motor utan återkoppling åker till sitt eget My med Stopp.", + "confirm_switch": "Verkligen växla {name}?", + "lock_confirm_unlock": "Verkligen låsa upp {name}?", + "gang_switch_one": "Strömbrytare", + "furn_cover_entity": "Rör sig med", + "furn_cover_hint": "Gardinen, duken, markisen eller grinden följer den här cover-entiteten (persienn, gardin, markis, grind) och rör sig med den. Ett tryck öppnar dess meny (upp, stopp, ner).", + "furn_cover_inverted": "Vänd riktningen", + "furn_cover_inverted_hint": "För ett markis eller gardin som rör sig åt motsatt håll på planen: utfälld visas som infälld och tvärtom.", + "gang_switch": "Knapp {n} styr", + "gang_socket_one": "Uttag matat av", + "gang_socket": "Uttag {n} matat av", + "gang_switch_hint": "En knapp lyser när dess lampa är tänd (i dess färg). Ett tryck växlar den; med flera knappar frågar en liten meny vilken. Samma entitet kan sitta på flera strömbrytare.", + "gang_socket_hint": "Ett uttag lyser grönt när dess brytare är på – starkare ju mer det drar. Ett tryck växlar det; med flera frågar en liten meny vilket.", + "lock_confirm_lock": "Låsa {name}?", + "opening_lock": "Smart lås", + "opening_lock_hint": "Ett tryck på dörren låser eller låser upp den (frågar alltid först). Medan den är upplåst lyser dess kant.", + "split_handle_hint": "Dra: bredd på planritning och 3D-vy", + "wall_exterior": "Yttervägg (m)", + "wall_interior": "Innervägg (m)", + "grid": "Rutnät (m)", + "units": "Visa längder i", + "units_metric": "Meter", + "units_imperial": "Fot och tum", + "units_hint": "Hur längder och ytor visas i planritningen, formulären och väggvyn. Inmatning sker fortfarande i meter.", + "background": "Mall (bild av planritning)", + "background_upload": "Välj bild …", + "background_width": "Bredd i planritningen (m)", + "background_opacity": "Opacitet", + "background_rotation": "Rotation (°)", + "background_edit": "Flytta, skala och vrid", + "background_edit_done": "Klar", + "background_edit_hint": "Medan läget är på: dra bilden för att flytta den, handtaget nere till höger skalar den. Anpassa först skalan, vrid den sedan.", + "background_remove": "Ta bort mall", + "hint_select": "Tryck på ett rum för att markera · dra hörn · ”+” på en kant lägger till ett hörn · piltangenter flyttar · Del tar bort · Ctrl+Z", + "hint_rect": "Dra för att rita en rektangel", + "hint_polygon": "Placera hörn · tryck på första hörnet eller Enter för att stänga · Esc avbryter", + "hint_empty": "Lägg först till en våning.", + "area_m2": "{a} m²", + "overlap_warning": "Rum överlappar – väggarna är ofullständiga där.", + "read_only": "Endast administratörer kan redigera planritningen.", + "side_failed": "Formuläret kunde inte visas ({error}). Planritningen går fortfarande att använda. Rapportera gärna texten i ett GitHub-ärende.", + "mat_wood": "Trä", + "mat_oak": "Ek", + "mat_tiles": "Kakel", + "mat_carpet": "Heltäckningsmatta", + "mat_stone": "Sten", + "mat_concrete": "Betong", + "card_name": "NextFloor", + "card_description": "Ditt hem i 3D (neon).", + "stats": "{calls} draw calls · {tris} trianglar", + "stats_fps": "{fps} fps (långsammaste bildruta {ms} ms)", + "stats_idle": "I vila (0 fps)", + "stats_busy_floors": "våningar", + "stats_busy_openings": "dörrar/fönster", + "stats_busy_flash": "blixt", + "stats_busy_roof": "tak", + "stats_busy_flow": "energiflöde", + "stats_busy_effect": "färgeffekt", + "stats_busy_robot": "robot", + "stats_busy_orbit": "kameravridning", + "stats_busy_tint": "rumsnyans", + "stats_low": "surfplattenivå, pixelförhållande {r}", + "stats_full": "full nivå, pixelförhållande {r}", + "floors_apart": "Isär", + "floors_stacked": "Staplade", + "roof_keep": "Taket stannar", + "roof_keep_hint": "Taket stannar på huset vid inzoomning i stället för att lyftas och tona bort", + "floor_rooms_one": "1 rum", + "floor_rooms": "{n} rum", + "quality": "Kvalitet", + "quality_auto": "Auto", + "quality_low": "Surfplatta", + "quality_high": "Hög", + "state_on": "På", + "state_off": "Av", + "state_open": "Öppen", + "state_closed": "Stängd", + "state_opening": "Öppnas", + "state_closing": "Stängs", + "state_playing": "Spelar", + "state_paused": "Pausad", + "state_idle": "Inaktiv", + "state_locked": "Låst", + "state_unlocked": "Upplåst", + "state_detected": "Detekterad", + "state_clear": "Fritt", + "state_unavailable": "Ej tillgänglig", + "state_heat": "Värme", + "state_cool": "Kyla", + "state_auto": "Auto", + "state_heat_cool": "Värme/kyla", + "state_dry": "Avfuktning", + "state_fan_only": "Fläkt", + "devices": "Enheter", + "devices_none_area": "Koppla rummet till ett område så visas dess enheter här.", + "devices_none": "Området har inga lämpliga enheter.", + "devices_place_all_n": "Placera alla {n} …", + "devices_place_all_confirm": "Placera {n} enheter i rummet på en gång? (Ctrl+Z eller ”Ångra” tar bort alla i ett steg.)", + "devices_src_area": "Det här området", + "devices_src_other": "Andra områden", + "devices_src_none": "Inget område", + "panel_hide": "Dölj i rumspanelen", + "panel_unhide": "Visa i rumspanelen igen", + "panel_state_hide": "Dölj tillståndet i rumspanelen (t.ex. en cover som bara rapporterar \"unknown\")", + "panel_state_show": "Visa tillståndet i rumspanelen igen", + "devices_place": "Placera", + "devices_remove": "Ta bort", + "devices_hint": "Placerade enheter visas i 3D. Dra dem i planritningen för att flytta dem.", + "panel_lights": "Lampor", + "panel_covers": "Covers", + "panel_climate": "Värme", + "panel_media": "Media", + "panel_switches": "Strömbrytare", + "panel_sensors": "Sensorer", + "panel_scenes": "Scener och skript", + "panel_announce": "📢 Utrop", + "announce_placeholder": "Eget meddelande …", + "announce_send": "Säg det", + "announce_sent": "Sagt: ”{message}”", + "announce_failed": "Utropet misslyckades: {error}", + "announce_phrase_1": "Maten är klar!", + "announce_phrase_2": "Dags att sova!", + "announce_phrase_3": "Kom ner, tack!", + "announce_phrase_4": "Vi åker snart!", + "announce_phrase_5": "Hunden behöver gå ut!", + "state_recording": "Spelar in", + "state_streaming": "Strömmar", + "panel_all_off": "Allt av", + "readable": "Lättläst", + "readable_hint": "Starkare kontrast och större text – för väggplattor och alla som läser bättre så.", + "plain": "Bara planlösning", + "plain_hint": "Visar bara väggar, dörrar, fönster och trappor, utan möbler. Enheter och deras markörer finns kvar.", + "right_back": "Högerklick = tillbaka", + "right_back_hint": "Ett kort högerklick i 3D-vyn går ett steg tillbaka: från rummet till våningen, från våningen till huset (som ett dubbeltryck på tom yta). Att dra med höger knapp flyttar fortfarande vyn.", + "stl": "3D-utskrift (STL)", + "stl_hint": "Sparar huset som STL-fil (väggar, golv, möbler och utomhusytor på alla våningar) för 3D-utskrift i skala 1:100 (en meter blir 10 mm). Fönster, ljus och tak ingår inte; en slicer lagar filen vid behov.", + "card_plain": "Bara planlösning", + "card_rooms": "Bara dessa rum", + "card_rooms_hint": "Kortet visar bara de ibockade rummen med möbler, enheter, dörrar och fönster (till exempel för en surfplatta i köket). Inget ibockat: hela planen.", + "card_templates": "Kortmallar", + "card_templates_hint": "Ställ in ett instrumentpanelkort en gång här (med kortets egna inställningar) och ange bara namnet på varje surfplatta: `template: kitchen_tablet`. Ändringar når alla kort som använder mallen; det som står på själva kortet går före mallen.", + "template_name": "Ny mall (namn)", + "template_add": "Skapa mall", + "template_reload": "Ladda om skärmar med den här mallen", + "template_reload_all": "Ladda om alla skärmar", + "template_use": "På instrumentpanelens kort: `template: {name}`", + "card_template": "Kortmall", + "card_template_none": "ingen (bara det här kortet)", + "card_readable": "Lättläst", + "all_off_n": "Stäng av allt ({n})", + "all_off_hint": "Stänger av rummets lampor, brytare, fläktar och media; kan ångras i tio sekunder.", + "all_off_done": "Allt avstängt.", + "all_off_undo": "Ångra", + "all_off_floor": "Stäng av allt på {floor} ({n} enheter), ångra i tio sekunder", + "mood_save": "Spara stämning", + "mood_save_hint": "Sparar hur rummets lampor lyser just nu som en stämning – ett tryck ställer in den igen senare, ”→” för över den till ett annat rum.", + "mood_new": "Stämning", + "mood_set": "Ställ in stämningen", + "mood_carry": "För över till ett annat rum", + "panel_all_on": "Allt på", + "view_options": "Vy: kvalitet, utseende, markörer, FPS", + "panel_all_open": "Allt upp", + "panel_all_close": "Allt ner", + "central": "Central: alla lampor, persienner och favoriter", + "central_house": "Hela huset", + "central_lights": "Lampor", + "central_covers": "Persienner", + "central_on": "På", + "central_off": "Av", + "central_open": "Upp", + "central_close": "Ner", + "central_sure": "Säker?", + "central_favorites": "Favoriter", + "central_no_favorites": "Inga favoriter ännu. Ställ in scener, skript och strömbrytare i redigeraren under \"Favoriter\".", + "card_central": "Stjärna med centralmenyn", + "card_central_hint": "Alla lampor och persienner på våningen eller i huset samt favoriterna från redigeraren.", + "favorites": "Favoriter", + "favorites_hint": "Scener, skript, automationer, knappar och strömbrytare för centralmenyn (stjärnan) i 3D-vyn – fest, närvarosimulering, solskydd, bevattning.", + "favorites_add": "Lägg till en favorit", + "favorite_floor": "På vilken våning favoriten visas", + "favorite_all_floors": "Alla våningar", + "outside_hidden": "Utomhus: dölj enheter", + "outside_hidden_hint": "Enheter som utomhuspanelen inte ska visa (de finns kvar på planen).", + "outside_hidden_add": "Dölj en enhet", + "room_facts": "Rumspanel: visade uppgifter", + "room_fact_sun": "Soltimmar", + "room_fact_comfort": "Komfort", + "room_fact_air": "Ventilationstips", + "room_fact_circuits": "Kretsar", + "background_handles_hint": "Bilden har nu handtag som en möbel: dra för att flytta, nedre högra hörnet skalar, det runda handtaget överst vrider (Shift för steg om 15°). När den passar, tryck på \"Klar\" – då ligger den still.", + "background_fixed_hint": "Bilden ligger still, du kan rita ovanpå. För att justera den, tryck på \"Flytta, skala och vrid\".", + "bg_level": "Räta upp", + "bg_level_cancel": "Avbryt uppriktning", + "bg_level_first": "Tryck på början av en vägg i bilden som ska gå rakt (vågrätt eller lodrätt).", + "bg_level_second": "Tryck nu på slutet av den väggen – bilden vrids så att den passar.", + "bg_ruler": "Skala med linjal", + "bg_ruler_cancel": "Avbryt linjalen", + "bg_ruler_first": "Tryck på början av en sträcka med känd längd i bilden – t.ex. en måttsatt vägg.", + "bg_ruler_second": "Tryck nu på slutet av sträckan.", + "bg_ruler_length_hint": "Uppmätt i planritningen: {m} m. Ange den verkliga längden så skalas bilden.", + "bg_ruler_length": "Verklig längd (m)", + "bg_ruler_apply": "Använd skalan", + "thumbs_fold": "Fäll ihop våningsbilderna till knappar", + "thumbs_show": "Visa våningsbilderna igen", + "room_start_view": "Vy som start för det här rummet", + "room_start_view_hint": "När du trycker på rummet i 3D flyger kameran exakt till vyn som 3D-rutan till höger visar nu – vinkel, zoom och utsnitt. Slå först på 3D bredvid, vrid och zooma in på rummet, tryck sedan.", + "room_start_view_reset": "Ta bort rummets startvy (uppifrån igen)", + "room_start_view_need_pane": "Slå först på \"3D bredvid\", vrid och zooma rummet som det ska öppnas.", + "floor_start_view": "Vy som start för den här våningen", + "floor_start_view_hint": "Den här våningen öppnas i 3D som 3D-rutan till höger står nu – t.ex. bottenvåningen framifrån och övervåningen bakifrån. Slå först på 3D bredvid, vrid den, tryck sedan.", + "floor_start_view_reset": "Ta bort våningens startvy (som huset igen)", + "floor_start_view_need_pane": "Slå först på \"3D bredvid\" och vrid våningen som den ska öppnas.", + "ambilight": "Sken bakom tv:n (%)", + "ambilight_hint": "Hur starkt det lyser bakom tv:n när den spelar. 0 stänger av det (t.ex. om du har LED-slingor på tv:n), 100 är normal styrka.", + "sound_rings": "Ljudringar (%)", + "sound_rings_hint": "Hur stora ringarna runt högtalaren blir medan den spelar. 0 stänger av dem, bilden och skenet finns kvar; 100 är vanlig storlek. Storleken följer också högtalarens volym: lägre volym ger mindre ringar.", + "glow_scale": "Sken i 3D (%)", + "light_effects": "Effektanimationer i 3D", + "light_effects_hint": "Koppla bara exakta effektnamn från HA. Okopplade effekter behåller den statiska HA-färgen. Ändrar inget i Home Assistant.", + "light_effects_enabled": "Tillåt animationer för den här lampan", + "light_effect_unmapped": "Okopplad (statisk)", + "light_effect_add": "Lägg till exakt effektnamn", + "light_effect_name_limit": "Det exakta effektnamnet måste ha 1 till 255 tecken. Det kortas inte.", + "light_effect_count_limit": "Högst 100 kopplingar. Ta bort en befintlig först.", + "light_effect_exists": "Det här effektnamnet är redan kopplat. Den befintliga kopplingen behålls.", + "light_animation_none": "Statisk", + "light_animation_rainbow": "Regnbåge (ersätter färgen)", + "light_animation_pulse": "Puls (intensitet)", + "light_animation_flicker": "Flimmer (intensitet)", + "glow_scale_hint": "Hur starkt lampan lyser i 3D: under 100 % dämpas starka LED-slingor så att rummet inte bländas; över 100 % lyser en svag lampa mer. Växlar inget i Home Assistant.", + "vehicle_to_spot": "Gör om till parkeringsplats", + "vehicle_to_spot_hint": "Ett fordon som vanlig möbel står alltid där. Som parkeringsplats visas det bara medan en sensor rapporterar bilen, och där kopplas bilens enhet (laddning, räckvidd, lås, klimat).", + "as_furniture": "Visa som möbel", + "as_furniture_hint": "Ersätter markören med en möbel på samma plats, kopplad till den här enheten – en högtalare för en mediaspelare, en lampa för ett ljus. Ctrl+Z ångrar.", + "as_furniture_pick": "Välj möbel …", + "as_device": "Tillbaka till enhetsmarkör", + "as_device_hint": "Ersätter möbeln med dess enhets vanliga markör på samma plats.", + "presets": "Stationer och spellistor (Ljud)", + "presets_hint": "Visas i varje högtalares snabbmeny under \"Spela\", bredvid spelarens källor. För en Echo (Alexa Media Player): skriv SPOTIFY, AMAZON_MUSIC eller TUNEIN och som innehåll det du skulle säga (\"Rock Antenne\"). För Sonos, Music Assistant och andra: skriv music eller url med en strömadress eller en URI.", + "preset_type": "Typ", + "preset_type_hint": "media_content_type för play_media, t.ex. music, url, playlist, SPOTIFY, AMAZON_MUSIC, TUNEIN", + "preset_content": "Innehåll", + "preset_content_hint": "media_content_id: ström-URL, URI (spotify:playlist:…) eller, för Alexa, en sökfras", + "preset_speakers": "Bara på dessa högtalare (ingen = på alla)", + "media_play": "Spela", + "media_pause": "Paus", + "media_previous": "Föregående", + "media_next": "Nästa", + "media_volume": "Volym", + "media_sources": "Källor", + "preset_add": "Station eller spellista", + "own_buttons": "Egna knappar", + "own_buttons_hint": "Visas i centralmenyn (stjärnan) under favoriterna: öppna en dashboardsökväg, visa detaljer för en entitet, anropa en tjänst eller öppna en browser_mod-popup med ditt eget kort.", + "own_alerts": "Egna varningar", + "circuits": "Elcentral", + "circuits_hint": "Säkringsgrupperna med rummen de matar. Rumspanelen nämner dem och sökningen hittar dem (”F12”).", + "circuit_name": "Namn", + "circuit_new": "Ny grupp", + "circuit_add": "Lägg till grupp", + "circuit_add_room": "Lägg till rum", + "own_alerts_hint": "En rad i varningslisten i 3D-vyn medan en entitet har ett tillstånd – ”Vattentank tom” från robotdammsugaren, ”Diskmaskinen klar”. Flera tillstånd med komma; för tal <20 eller >80.", + "own_alert_entity": "När …", + "own_alert_state": "… har tillståndet (tomt = på)", + "own_alert_text": "… då denna varning", + "own_alert_color": "Färg", + "own_alert_tap": "Ett tryck", + "own_alert_tap_info": "öppnar detaljerna", + "own_alert_tap_toggle": "växlar entiteten", + "own_alert_tap_room": "hoppar till rummet", + "own_alert_house": "Hela huset", + "own_alert_new": "Ny varning", + "own_alert_add": "Lägg till varning", + "today": "I dag", + "today_none": "Inget planerat i dag.", + "today_calendars": "Kalendrar för ”I dag”", + "today_calendars_hint": "Händelserna i dessa kalendrar visas uppe till höger i 3D-vyn på kortet ”I dag”, tillsammans med kärlen som töms i dag eller i morgon. Ett tryck på rubriken fäller ihop kortet.", + "own_button_state": "Lyser medan … är på (valfritt)", + "own_button_label": "Etikett", + "own_button_action": "Åtgärd", + "own_button_new": "Ny knapp", + "own_button_add": "Egen knapp", + "own_action_navigate": "Öppna en sökväg", + "own_action_more_info": "Entitetsdetaljer", + "own_action_service": "Anropa en tjänst", + "own_action_fire_dom_event": "fire-dom-event (browser_mod)", + "own_target_navigate": "Sökväg", + "own_target_more_info": "Entitet", + "own_target_service": "Tjänst (domän.tjänst)", + "own_data": "Data (JSON)", + "own_data_hint": "För en tjänst dess data, för fire-dom-event händelsens innehåll, t.ex. {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}.", + "own_data_bad": "Inget giltigt JSON-objekt.", + "panel_no_area": "Det här rummet är inte kopplat till ett område. Du kan koppla det i redigeraren.", + "panel_empty": "Inga enheter från det här rummet finns i planritningen. Placera enheter i redigeraren eller välj dem för rumspanelen med ☆.", + "close": "Stäng", + "panel_fold": "Fäll ihop (rummet syns kvar)", + "panel_unfold": "Öppna igen", + "brightness": "Ljusstyrka", + "color_temp": "Färgtemperatur", + "color": "Färg", + "position": "Position", + "cover_open": "Öppna", + "cover_stop": "Stopp", + "cover_tilt": "Lameller", + "cover_tilt_open": "Lameller öppna", + "cover_tilt_close": "Lameller stängda", + "cover_close": "Stäng", + "target_temp": "Mål", + "current_temp": "Aktuell", + "temp_down": "Svalare", + "temp_up": "Varmare", + "volume": "Volym", + "play_pause": "Spela/paus", + "previous": "Föregående", + "next": "Nästa", + "run": "Kör", + "details": "Detaljer", + "hold_hint": "Tryck växlar · långt tryck öppnar detaljer", + "tool_opening": "Dörrar och fönster", + "tool_furniture": "Möbler", + "qm_off": "Av", + "find": "Sök", + "find_placeholder": "Var är …? Enhet eller rum", + "find_none": "Inget hittades", + "swipe_off": "Av", + "panel_pin": "Visa i rumspanelen", + "panel_unpin": "Visa inte i rumspanelen", + "devices_panel_hint": "Rumspanelen visar enheterna i planritningen. ☆ lägger till en enhet i rumspanelen utan att placera den.", + "card_section_view": "Vy", + "card_size": "Storlek", + "card_size_fixed": "Fast höjd", + "card_size_fill": "Fyll skärmen", + "card_fill_hint": "Fungerar bäst i en dashboardvy av typen ”Panel (enskilt kort)” – kortet tar då hela utrymmet.", + "card_controls": "Strömbrytare i kortet", + "card_floor_thumbs": "Våningar som miniatyrer", + "card_floor_thumbs_hint": "Små bilder av våningarna vid sidan – tryck på en för att byta", + "card_floor_thumbs_hint_start": "Den valda våningen är då där kortet startar – bilderna vid sidan byter till de andra", + "card_room_names": "Visa rumsnamn", + "card_section_kiosk": "Väggplatta (kiosk)", + "card_section_features": "Funktioner", + "card_weather_plan": "som i planritningen", + "card_pro_hint": "Rörelsespår och kameravägg hör till kamerorna: spåret visar den senaste halvtimmen, väggen alla kameror i planritningen.", + "card_idle_return": "Tillbaka till startvyn efter", + "card_idle_off": "Aldrig", + "card_idle_min": "{n} min utan beröring", + "card_idle_hint": "Efter väntetiden stänger kortet rummet och visar startvyn igen.", + "card_night": "Nattdimning", + "card_night_off": "Av", + "card_night_sun": "Efter solen", + "card_night_time": "Tidsintervall", + "card_night_range": "Tidsintervall (t.ex. 22:00-06:00)", + "card_idle_orbit": "Kameravridning som skärmsläckare", + "card_idle_orbit_hint": "Efter återgången vrids vyn långsamt tills någon rör vid plattan", + "card_dashboard": "Knapp till en dashboard (sökväg)", + "card_dashboard_label": "Knappens etikett", + "card_dashboard_hint": "En knapp uppe till höger i kortet öppnar dashboarden eller vyn med den här sökvägen, t.ex. /lovelace/home eller /dashboard-house/0. Utan etikett visar den ⌂.", + "card_alerts": "Visa varningar", + "card_alerts_hint": "Rök, gas, CO, vatten, larm och fönster öppna i regn: rummet pulserar, en notis visas överst", + "card_alert_jump": "Hoppa till rummet för en ny varning", + "card_alert_jump_hint": "Vyn byter själv till varningens våning och rum", + "card_scenes": "Scenknappar i rummet", + "card_scenes_hint": "Områdets scener och skript som knappar under 3D-vyn medan ett rum är markerat", + "card_sensor_bar": "Egna sensorer överst", + "card_sensor_bar_hint": "Sensorerna som valts i redigeraren (Inställningar) uppe till vänster på kortet", + "card_central_open": "Stjärnmeny öppen och stor", + "card_central_open_hint": "Favoriter och egna knappar står öppna från start, en storlek större", + "card_keep_camera": "Behåll kameran vid byte av våning", + "card_keep_camera_hint": "Samma sida, höjd och avstånd på varje våning", + "card_today": "Kortet ”I dag”", + "card_today_hint": "Dagens händelser och kärl som ska ut, uppe till höger", + "card_announcements": "Utrop", + "card_announcements_hint": "Utrop (åtgärden ”NextFloor: Utrop”) visas stort på kortet, med en gong, och läses upp", + "weather_short": "Väder", + "weather_entity": "Väderentitet", + "weather_effects": "Vädereffekter i 3D", + "card_weather_density": "Mängd regn och snö", + "card_weather_density_hint": "Färre droppar och flingor än vädret rapporterar; moln, dimma och blixtar stannar", + "rain_warning": "Varning: fönster öppet när det regnar", + "sun_patches": "Sol och skuggor", + "sun_patches_hint": "Med norr inställt faller solljuset från sun.sun som ljusa fläckar genom fönstren på golvet, och huset kastar sin skugga på tomten. Avmarkera för att hålla golv och tomt fria från solfläckar och skuggor.", + "sun_arc": "Solbåge och kompass", + "sun_arc_hint": "Ritar dagens solbana som en båge över tomten, med en ring och väderstrecken på marken (norr i rött). Kräver hemmets position i Home Assistant.", + "weather_effect_rain": "Regn", + "weather_effect_snow": "Snö", + "weather_effect_fog": "Dimma (gör scenen grå)", + "weather_effect_clouds": "Moln dämpar himlen och solen", + "weather_effect_lightning": "Blixtar vid åska", + "weather_effect_sky": "Sol och måne på himlen", + "weather_entity_hint": "Vilken väderentitet som styr himlen runt huset. Automatiskt använder den första som hittas.", + "weather_hint": "Väder vid huset: regn och snö faller med den verkliga vinden, moln driver över tomten med sina skuggor, blixtar, dimma, sol och måne", + "card_weather": "Väder ute", + "card_weather_hint": "Regn, snö, hagel, moln med skuggor, blixtar och dimma från den första väderentiteten (weather_entity väljer en annan); färre partiklar på surfplattenivå", + "alerts": "Varningar", + "alert_smoke": "Rök: {name}", + "alert_gas": "Gas: {name}", + "alert_co": "Kolmonoxid: {name}", + "alert_water": "Vatten: {name}", + "alert_alarm": "Larm utlöst", + "alert_alarm_by": "Larm utlöst av {cause}", + "alert_alarm_pending": "Larm väntar", + "alert_window_rain": "Fönster öppet i regn: {name}", + "alert_power_outage": "Strömavbrott: {name}", + "alert_contact_lost": "Kontakten svarar inte: {name}", + "rain_sensor": "Regnsensor (egen väderstation)", + "outage_sensor": "Sensor för strömavbrott", + "outage_hint": "En binär sensor av klassen power som är av, en annan binär sensor som är på, ett tillstånd som \"off_grid\" eller \"backup\", eller en spänning under 50 V ger en varning för hela huset.", + "contact_warning": "Varna när en dörr- eller fönsterkontakt inte nås", + "contact_warning_hint": "När en kontakt har varit otillgänglig i 10 minuter (tomt batteri, utom räckvidd) ser fönstret stängt ut i 3D fast ingen vet. Då nämner en notis kontakten. En omstart av Home Assistant varnar inte.", + "night_lock_warning": "Varna på natten när en dörr inte är låst", + "night_lock_warning_hint": "Mellan 22 och 6 nämner en notis planens dörrlås som står olåsta.", + "alert_unlocked_night": "Inte låst: {name}", + "motion_markers_active": "Visa rörelsesensorer bara när de upptäcker något", + "motion_markers_active_hint": "Gäller rörelse-, närvaro- och beläggningssensorer. En sensor vars symbol alltid ska visas syns ändå.", + "room_double_tap": "Dubbeltryck på ett rum", + "room_double_tap_hint": "Ett dubbeltryck på ett rum släcker lamporna om någon är tänd, annars tänds alla. Enheter som frågar först lämnas alltid utanför.", + "room_double_tap_area": "Lampor i planen och alla lampor i området", + "room_double_tap_plan": "Endast lampor i planen", + "room_double_tap_off": "Växla ingenting", + "card_room_double_tap_auto": "Som inställt i planen", + "status_entities": "Egna sensorer överst i 3D-vyn", + "status_add": "Lägg till en sensor", + "status_entities_hint": "Till exempel utetemperatur, larm eller luftkvalitet: de visas uppe till vänster med namn och värde, även i ett öppnat rum. Ett tryck öppnar detaljerna. Upp till 12.", + "announce_tts": "Text till tal för utrop", + "announce_phrases": "Meningar för utrop (en per rad)", + "announce_phrases_hint": "Tomt: de medföljande meningarna. Utrop finns även som åtgärden ”NextFloor: Utrop” för automationer – i rummens högtalare och på varje öppen NextFloor-skärm.", + "opening_rain_warning": "Varna när det regnar", + "opening_light_well": "Ljusschakt framför", + "sill_boards": "Fönsterbänk och bleck", + "sill_boards_auto": "Automatiskt", + "sill_boards_none": "Ingen", + "sill_boards_inside": "Endast inne", + "sill_boards_outside": "Endast ute", + "room_names_short": "Rumsnamn", + "floor_stack_short_dim": "Dämpade", + "floor_stack_short_stacked": "Staplade", + "floor_stack_short_single": "Ensam", + "size_short_w": "B", + "size_short_d": "D", + "size_short_h": "H", + "import_error_not_json": "Filen är ingen JSON.", + "import_error_not_plan": "Filen är ingen NextFloor-planritning.", + "import_other_hint": "Från Sweet Home 3D: importera .sh3d-filen här. Våningar, rum, dörrar, fönster och fristående väggar följer med, möbler inte.", + "import_sh3d_found": "Sweet Home 3D: {floors} våningar, {rooms} rum, {openings} dörrar och fönster, {walls} fristående väggar ({furniture} möbler tas inte med).", + "import_dxf_found": "DXF: {rooms} rum (slutna polylinjer) och {walls} fristående väggar (linjer) på en våning.", + "import_ifc_found": "I IFC-filen: {floors} våningar och {rooms} rum (NextFloor ritar väggarna utifrån rummen).", + "import_roomplan_found": "Rumsskanning (RoomPlan): {rooms} rum, {openings} dörrar och fönster; {skipped} objekt togs inte med (möbler placerar du själv).", + "import_error_roomplan_empty": "Skanningen har inga väggar.", + "import_error_ifc_empty": "IFC-filen har inga utrymmen (IfcSpace) med planform.", + "import_error_dxf_empty": "DXF-filen har inga linjer eller polylinjer.", + "import_error_sh3d": "Det här är ingen läsbar Sweet Home 3D-fil (kräver Sweet Home 3D 5.3 eller senare).", + "import_error_sh3d_empty": "Sweet Home 3D-filen har inga rum eller väggar.", + "export_name_template": "mall", + "export_name_backup": "säkerhetskopia", + "card_floor_stack": "Våningar under", + "floor_stack_dim": "Dämpade", + "floor_stack_stacked": "Staplade (huset hit)", + "floor_stack_single": "Dolda (bara den här våningen)", + "card_control_walls": "Höga väggar/snitt", + "card_control_floors": "Våningar isär", + "card_control_temperature": "Temperatur", + "card_control_humidity": "Luftfuktighet", + "card_control_co2": "CO₂", + "card_controls_hint": "Höga väggar/snitt, våningar isär och temperatur, luftfuktighet, CO₂ att växla", + "controls_hide": "Dölj kontrollerna – bara 3D-vyn finns kvar", + "nav_wrap": "Radbryt fältet: alla våningar och rum på flera rader", + "bars_fold": "Fäll ihop reglagen", + "bars_unfold": "Reglage", + "nav_row": "Fält på en rad (rullar i sidled)", + "controls_show": "Visa kontrollerna igen", + "card_controls_hidden": "Starta med dolda kontroller", + "card_controls_hidden_hint": "Bara 3D-vyn; ett öga nere till vänster tar tillbaka fält, värden och brytare", + "card_controls_hide_after": "Dölj kontrollerna efter", + "card_hide_after_s": "{n} s utan beröring", + "card_fullscreen_button": "Helskärmsknapp", + "card_fullscreen_button_hint": "Döljer dashboarden runt kortet (t.ex. på en väggplatta)", + "fullscreen": "Helskärm", + "fullscreen_exit": "Avsluta helskärm", + "card_section_show": "Visa", + "card_floor": "Våning", + "card_floor_house": "Hela huset (tryck på en våning för att öppna den)", + "card_height": "Höjd (pixlar)", + "card_walls": "Väggar", + "card_quality_hint": "”Surfplatta” är den lättaste inställningen – perfekt för Fire-plattor och andra väggplattor.", + "card_flows_switch": "Brytare i kortet", + "card_flows_on": "Alltid på", + "card_flows_off": "Alltid av", + "holos": "Kort", + "holos_hint": "Visa eller dölj livekorten över huset (energibalans, bil, media)", + "card_energy": "Visa energivärden överst", + "card_room_panel": "Rumsdetaljer vid tryck", + "card_room_buttons": "Rumsknappar", + "card_room_buttons_hint": "En rad med en knapp per rum överst i kortet – tryck på en för att öppna rummet, som när du trycker på det i modellen", + "card_room_panel_hint": "Rummets lampor och persienner i en sidopanel", + "card_explode": "Dra isär våningarna i husvyn", + "card_roof_fade": "Tona bort taket vid inzoomning", + "card_roof_fade_hint": "Av: taket stannar på huset även när kameran kommer nära.", + "card_stats": "Prestandavisning (bildrutor per sekund)", + "card_stats_hint": "För att se hur jämnt kortet går på enheten", + "packs": "Möbelpaket", + "lib_badge_light": "Lampa: kopplas till ett ljus och växlar i 3D", + "lib_badge_electric": "Elektrisk: kopplas till en entitet och en effektsensor (växling, bilder, förbrukning)", + "lib_badge_hint": "Saker med en symbol kopplas till entiteter: lampor växlar, skärmar visar bilder, apparater visar sin förbrukning.", + "care_bin_today": "Töms i dag", + "care_bin_tomorrow": "Töms i morgon", + "care_bin_days": "Om {n} dagar", + "care_mail_yes": "Post har kommit", + "care_mail_no": "Tom", + "care_plant_thirsty": "Törstig", + "care_plant_ok": "Välvattnad", + "care_time_left": "{time} kvar", + "care_entity_bin": "Tömningsdatum (sensor)", + "care_entity_mail": "Postsensor", + "care_entity_plant": "Jordfuktighet (sensor)", + "care_thirsty_below": "Törstig under (%)", + "care_hint_bin": "En sensor med nästa tömning: dagar, ett datum, \"i dag\"/\"i morgon\" eller integrationen Waste Collection Schedule. Kärlet lyser dagen före och på dagen.", + "care_hint_mail": "En sensor som rapporterar post i lådan (t.ex. en kontakt på luckan). Brevlådan lyser då.", + "care_hint_plant": "En fuktsensor i jorden. Under gränsen lyser växten och säger att den är törstig.", + "lib_cat_lights": "Lampor", + "lib_cat_seating": "Sittplatser", + "lib_cat_tables": "Bord", + "lib_cat_storage": "Skåp och hyllor", + "lib_cat_beds": "Sängar", + "lib_cat_kitchen": "Kök", + "lib_cat_appliances": "Vitvaror", + "lib_cat_bath": "Badrum", + "lib_cat_media": "TV och ljud", + "lib_cat_office": "Kontor", + "lib_cat_tech": "Teknik", + "lib_cat_climate": "Värme och klimat", + "lib_cat_energy": "Energi", + "lib_cat_garden": "Trädgård och uteplats", + "lib_cat_plants": "Växter", + "lib_cat_kids": "Barn", + "lib_cat_fitness": "Träning", + "lib_cat_pets": "Husdjur", + "lib_cat_workshop": "Verkstad och garage", + "lib_cat_music": "Musik & ateljé", + "lib_cat_season": "Säsong & dekoration", + "lib_cat_pictures": "Tavlor & ramar", + "lib_cat_vehicles": "Fordon", + "lib_cat_building": "Trappor och byggdelar", + "lib_cat_decor": "Dekoration med mera", + "lib_favourites": "Favoriter", + "lib_recent": "Senast använda", + "lib_for_room": "Passar i {room}", + "lib_all_rooms": "Visa alla rum", + "lib_linkable": "kopplingsbar", + "lib_lit": "lyser", + "lib_outdoor": "utomhus", + "lib_fav_add": "Lägg till i favoriter", + "lib_fav_remove": "Ta bort från favoriter", + "lib_sizes": "Storlekar", + "feature_name_energy": "Energiflöde", + "ext_tab": "Tillägg", + "ext_title": "Tillägg", + "models": "Dina egna 3D-modeller", + "models_hint": "För vissa fordon kan NextFloor visa en riktig 3D-modell om du har en. Välj filen (.glb) här: NextFloor vänder den rätt, gör den lättare, markerar lacken och sparar den i din Home Assistant. Utan modell ser fordonet ut som tidigare.", + "models_licence": "Filerna är dina och stannar i din Home Assistant. NextFloor levererar inga modeller; kontrollera att modellens licens tillåter användning i din egen installation.", + "model_add": "Lägg till en modell …", + "model_replace": "Ersätt modellen …", + "model_remove": "Ta bort", + "model_present": "används", + "model_missing": "inga ännu", + "model_remove_confirm": "Ta bort modellen ”{id}” från Home Assistant?", + "model_removed": "Modellen ”{id}” borttagen.", + "model_uploaded": "Modellen ”{id}” sparad ({size}). Ladda om panelen för att se den.", + "model_upload": "Spara i Home Assistant", + "model_info": "{triangles} trianglar, {size} m", + "model_front": "Framsida", + "model_front_hint": "Vrid modellen tills framsidan pekar mot betraktaren (snett nedåt vänster i bilden).", + "model_paint": "Lack (färgen du väljer i redigeraren)", + "model_paint_preview": "Färg i förhandsvisningen", + "model_detail": "Detaljnivå", + "model_detail_light": "Lätt (surfplatta)", + "model_detail_normal": "Normal", + "model_detail_fine": "Fin", + "model_result": "Resultat: {triangles} trianglar, {size}", + "model_error_not_glb": "Det här är ingen .glb-fil (binär glTF). Exportera modellen som ”glTF binary”.", + "model_error_compressed": "Filen är komprimerad (Draco, Meshopt eller KTX). Exportera den utan komprimering.", + "model_error_empty": "Filen innehåller inget tredimensionellt.", + "model_error_unreadable": "Filen kan inte läsas: {detail}", + "model_error_too_large": "Filen är större än {max}. Välj en lägre detaljnivå.", + "model_upload_forbidden": "Endast administratörer får ladda upp modeller.", + "model_upload_too_large": "Home Assistant tar inte emot filer över {max}. Välj en lägre detaljnivå.", + "model_upload_not_glb": "Home Assistant avvisade filen (ingen binär glTF).", + "model_upload_bad_id": "Modell-id:t är ogiltigt.", + "model_upload_other": "Uppladdningen fungerade inte: {detail}", + "ext_intro": "Importera egna möbelpaket, ladda upp egna 3D-modeller och lägg till tillägg här.", + "plugin": "tillägg", + "plugins_title": "Tillägg", + "plugins_intro": "Tillägg lägger till egna ljusanimationer, enheter och kort i rumspanelen. Ange ett tilläggs adress (en .js-fil i /config/www, alltså /local/…, från HACS /hacsfiles/…, eller https://…).", + "plugins_docs": "Hur man skriver ett tillägg", + "plugins_warning": "Tillägg körs med samma rättigheter som NextFloor i din webbläsare. Använd bara tillägg från källor du litar på.", + "plugins_off": "av", + "plugins_error": "fel", + "plugins_loading": "laddar …", + "plugins_nothing_registered": "laddat, men registrerade inget", + "plugins_loaded": "aktivt", + "plugins_reload_hint": "Gäller efter omladdning av sidan", + "plugins_remove": "Ta bort", + "plugins_none": "Inga tillägg ännu.", + "plugins_from_dashboard": "Registrerat av en dashboardresurs", + "plugins_add": "Lägg till", + "plugins_url_invalid": "Ange en .js-adress under /local/…, /hacsfiles/… eller https://….", + "plugins_exists": "Det här tillägget finns redan i listan.", + "plugins_limit": "Högst 20 tillägg.", + "packs_title": "Möbelpaket", + "packs_intro": "Importera egna möbler som paket (JSON): som fil eller inklistrat nedan. {n} paket följer med NextFloor och finns alltid.", + "packs_docs": "Paketformat", + "packs_none": "Inga egna paket ännu.", + "community_title": "Communitymöbler", + "community_intro": "Möbler som andra har byggt och delat med möbelbyggaren – granskade och gratis. Bygg dina egna:", + "community_builder": "Öppna möbelbyggaren", + "community_how": "Så delar du dina", + "community_load": "Läs in communitymöbler", + "community_none": "Inga communitymöbler än – bli först!", + "community_install": "Installera", + "community_update": "Uppdatera", + "community_installed": "Installerad", + "community_failed": "Communitymöblerna kunde inte läsas in: {detail}", + "pack_import": "Importera paketfiler …", + "pack_paste": "Importera JSON", + "pack_paste_empty": "Klistra först in ett pakets JSON.", + "pack_paste_not_json": "Det här är ingen giltig JSON: {detail}", + "pack_imported": "Importerade ”{name}” från {publisher} – {n} saker", + "packs_imported_n": "{n} av {total} paket importerade", + "pack_by": "från {publisher} · {n} saker", + "pack_remove": "Ta bort", + "pack_remove_confirm": "Ta bort paketet ”{name}”? Dess möbler blir kvar i planritningen som enkla lådor.", + "pack_error_not_a_pack": "Det här är inget möbelpaket (\"format\": \"nfpack\" saknas).", + "pack_error_builtin": "Ett paket som följer med NextFloor har redan detta id.", + "pack_error_invalid_content": "Paketet innehåller ogiltiga möbler: {detail}", + "pack_error_too_large": "Paketet är för stort (högst 1 MB).", + "pack_error_needs_update": "Det här paketet kräver en nyare version av NextFloor. Uppdatera först (HACS › NextFloor › ⋮ › \"Uppdateringsinformation\" › \"Ladda ner\"), starta om Home Assistant och importera igen.", + "pack_error_other": "Importen misslyckades: {detail}", + "store_open": "Öppna tilläggsbutiken", + "store_close": "Stäng tilläggsbutiken", + "store_intro": "Granskade tillägg från communityn. Varje tillägg granskas innan det läggs till och ändras inte efteråt.", + "store_submit": "Skicka in eget tillägg", + "store_empty": "Inga tillägg i butiken ännu.", + "store_failed": "Butiken kunde inte laddas ({error}).", + "store_install": "Installera", + "store_installed": "installerat", + "store_update": "Uppdatera", + "store_confirm": "Installera ”{name}” från {author}?\n\nEtt tillägg körs med samma rättigheter som NextFloor i din webbläsare. Filen har granskats och dess innehåll är låst:\n{url}", + "manual": "Handbok", + "manual_more": "Läs mer", + "feature_text_energy": "Energipartiklar flyger i bågar från solcellsfälten till växelriktaren, mellan hus, batteri, elnät och förbrukare – snabbare och tätare ju mer effekt som flödar. Modulerna gnistrar med sin produktion, ett glaskort över taket visar balansen och hur självförsörjande huset är just nu.", + "live_autarky": "autarki", + "live_day_hint": "De senaste 24 timmarna: sol (yta) och förbrukning (linje)", + "live_week_hint": "De senaste 7 dagarna: sol {solar} kWh, förbrukning {use} kWh (gult: sol, ljust: förbrukning)", + "live_days": "dagar", + "live_car_away": "På resande fot", + "live_car_charging": "Laddar", + "live_car_plugged": "Inkopplad", + "live_car_lock": "Lås", + "live_car_unlock": "Lås upp", + "live_car_unlock_confirm": "Verkligen låsa upp {name}?", + "live_car_climate": "Klimat", + "live_car_charge": "Starta/stoppa laddning", + "live_media_prev": "Föregående", + "live_media_playpause": "Spela/paus", + "live_media_next": "Nästa", + "live_media_volume": "Volym", + "live_car_device": "Bil (vilken entitet som helst i bilen)", + "live_car_device_hint": "Laddnivå, räckvidd, laddning, kontakt, lås och klimat hittar NextFloor på bilens enhet. Utan den används platsens närvarosensor.", + "live_car_departure_entity": "Avresetid (valfritt)", + "live_car_departure": "Avresa {time}", + "live_car_open": "Öppet: {parts}", + "printer_printing": "skriver ut", + "printer_done": "klar", + "printer_paused": "pausad", + "printer_error": "fel", + "printer_idle": "redo", + "printer_done_at": "klar {time}", + "printer_layer": "Lager", + "printer_nozzle": "Munstycke", + "printer_bed": "Bädd", + "heatpump_heating": "värmer", + "heatpump_water": "varmvatten", + "heatpump_cooling": "kyler", + "heatpump_defrost": "avfrostar", + "heatpump_idle": "vilar", + "heatpump_flow_return": "Fram → retur", + "heatpump_heat": "Värme", + "heatpump_power": "El", + "heatpump_outside": "ute", + "pack_missing_item": "Möbel från ett borttaget paket", + "back_to_room": "Tillbaka till {room}", + "back_to_floor": "Tillbaka till våningen", + "hint_furniture": "Tryck på ett rum, välj sedan en sak till höger · dra saker, ändra storlek med hörnen", + "furniture_into": "Nya saker hamnar mitt i ”{room}”.", + "furniture_pick_room": "Tips: tryck först på ett rum – nya saker hamnar då i mitten av det.", + "flows": "Energiflöde", + "flows_hint": "Visa eller dölj energibågarna mellan solcellsfält, växelriktare, batteri, elnät och förbrukare", + "chk_title": "Inställning", + "chk_hint": "Vad energiflödet behöver. Tryck på en rad för att gå dit.", + "chk_solar": "Solcellsfält på plats", + "chk_solar_add": "Lägg ett solcellsfält på taket", + "chk_meter": "Elmätare med nätsensor", + "chk_meter_sensor": "Elmätare: nätsensor (W) saknas", + "chk_meter_add": "Lägg till elmätaren", + "chk_inverter": "Växelriktare med effektsensor", + "chk_inverter_sensor": "Växelriktare: effektsensor saknas", + "chk_inverter_add": "Lägg till en växelriktare", + "chk_battery": "Hembatteri med effekt och laddnivå", + "chk_battery_sensor": "Hembatteri: effekt eller laddnivå saknas", + "chk_battery_opt": "Hembatteri (valfritt)", + "chk_grid": "Nätanslutning inställd", + "chk_grid_opt": "Nätanslutning (valfritt, annars automatiskt)", + "energy_sign_grid": "Huset visar export medan solen inte producerar något. Nätsensorn har troligen omvänt tecken.", + "energy_sign_battery": "Batteriet laddas utan sol och utan nätuttag. Dess sensor har troligen omvänt tecken.", + "energy_sign_flip": "Vänd tecknet", + "help_title": "Hjälp och feedback", + "help_hint": "Rapportera problem som GitHub-issue och önskemål som discussion – inget försvinner och alla ser läget.", + "help_issue": "Rapportera ett problem", + "help_idea": "Föreslå en idé", + "furn_name": "Namn (valfritt)", + "furn_mirror": "Spegla", + "furn_mirror_hint": "Byt vänster och höger – hörnsoffan åt andra hållet, skåpet med dörren på andra sidan, köksraden speglad.", + "hint_opening": "Tryck på en vägg för att lägga till en dörr eller ett fönster – välj typ till höger efteråt", + "preset_door": "Dörr", + "preset_door_double": "Pardörr", + "preset_window": "Fönster", + "preset_window_double": "Dubbelfönster", + "preset_terrace": "Altandörr", + "preset_terrace_double": "Franska dörrar", + "preset_lift_slide": "Lyft-skjutdörr", + "preset_garage": "Garageport", + "preset_front": "Ytterdörr", + "opening_style": "Stil", + "sidelight_auto": "automatisk", + "sidelight_hinge": "Sidoljus på gångjärnssidan", + "sidelight_hinge_hint": "Annars sitter sidoljuset mittemot gångjärnen; markerat sitter det bredvid gångjärnen.", + "sidelight_width": "Sidoljusets bredd (m)", + "sidelight_width_left": "Vänster sidoljus (m)", + "sidelight_width_right": "Höger sidoljus (m)", + "style_auto": "Automatisk ({style})", + "style_interior": "Innerdörr", + "style_front": "Ytterdörr", + "style_front_glass": "Ytterdörr med glas", + "style_sidelight": "Ytterdörr med sidoljus", + "style_sidelights": "Ytterdörr med två sidoljus", + "style_glass": "Glasdörr", + "style_sliding": "Skjutdörr", + "style_passage": "Öppning (utan dörr)", + "style_standard": "Standard", + "style_bars": "Med spröjs", + "style_glass_wall": "Glasvägg (fast)", + "preset_glass_wall": "Glasvägg", + "flip_hinge": "Byt gångjärnssida", + "flip_main_leaf": "Byt huvudblad", + "flip_hinge_hint": "Gångjärn åt andra sidan", + "flip_swing": "Vänd öppningsriktningen", + "flip_swing_hint": "Dörren öppnas in i rummet eller åt andra hållet", + "main_leaf": "Huvudblad (sett från rummet)", + "contact_main": "Kontakt huvudblad", + "contact_second": "Kontakt andra bladet", + "tool_outdoor": "Ute", + "tool_measure": "Efter mått", + "hint_measure": "Tryck på startpunkten och skriv sedan väggarnas längder med riktning till höger", + "measure": "Rum efter mått", + "measure_start": "Tryck på startpunkten i planritningen, t.ex. ett rumshörn.", + "measure_from": "Start vid {x} / {z} m – ett tryck flyttar starten.", + "measure_length": "Längd på nästa vägg (m)", + "measure_close": "Stäng rummet", + "measure_undo": "Ta bort sista väggen", + "measure_gap": "Avstånd till starten: {gap} m (sammanfogas vid stängning)", + "measure_hint": "Tips: skriv en längd och tryck på en piltangent. Med uppmätta innermått använder du sedan ”Stäng glipor”.", + "rect_by_size": "Rektangel efter storlek", + "rect_add": "Lägg till rektangel", + "dir_up": "Upp", + "dir_down": "Ner", + "dir_left": "Vänster", + "dir_right": "Höger", + "hint_outdoor": "Dra för att rita en uteyta (gräsmatta, uteplats, pool …)", + "outdoor": "Uteyta", + "outdoor_type": "Typ", + "outdoor_height": "Höjd (m)", + "outdoor_offset": "Höjdförskjutning (m, − = lägre)", + "outdoor_outline": "Visa konturen", + "outdoor_outline_hint": "Avmarkerad ritar ytan ingen lysande linje längs kanten – för stora tomter av flera gräsmattor.", + "outdoor_corners_hint": "Hörn: ett + på en kant lägger till ett hörn, dra för att forma ytan, × tar bort ett hörn.", + "outdoor_hint": "Utebelysning (pollare, trädgårdsspot, utevägglampa) lyser upp alla uteytor och fasaden.", + "out_lawn": "Gräsmatta", + "out_terrace": "Uteplats", + "out_path": "Gång", + "out_driveway": "Uppfart", + "out_pool": "Pool", + "out_bed": "Rabatt", + "out_hedge": "Häck", + "out_fence": "Staket", + "out_wild": "Vildvuxen yta", + "out_pergola": "Pergola / ram", + "outdoor_open": "Öppen (utelämna sista kanten)", + "outdoor_open_hint": "Kanten från sista punkten tillbaka till den första ritas inte – ett staket eller en pergola mot huset.", + "fence_gates": "Grindar i staketet", + "gate_add": "+ Grind i staketet", + "gate_edge": "Staketsida", + "gate_kind": "Typ", + "gate_single": "Trädgårdsgrind", + "gate_double": "Dubbelgrind", + "gate_sliding": "Skjutgrind", + "gate_offset": "Mitt från början (m)", + "gate_width": "Bredd (m)", + "gate_entity": "Motor eller brytare", + "gate_contact": "Kontakt (på = öppen)", + "fence_gates_hint": "En grind är en lucka i staketet med grindstolpar och en grindfläck. Med en motor (cover, brytare, input_boolean, lås) och/eller en kontakt öppnas den i 3D: trädgårds- och dubbelgrindar svänger inåt, en skjutgrind rullar längs staketet.", + "outdoor_bracing": "Kryssförband", + "outdoor_cut": "Skär ut ur omgivande ytor", + "outdoor_cut_hint": "Varje yta som helt innehåller denna får ett hål här – en pool i uteplatsen, en damm eller vildvuxen yta i gräsmattan. Ritordningen spelar ingen roll. En pool skär ut sig själv.", + "outdoor_area_hint": "Home Assistant-området för den här ytan (trädgård, terrass, pool): dess enheter och sensorer listas under Ute, och en nål på ytan öppnar det.", + "pool_temp": "Vattentemperatur (valfritt)", + "pool_pump": "Pump / filter (valfritt)", + "pool_pump_on": "pump igång", + "outdoor_slope": "Lutning (m)", + "outdoor_slope_hint": "Höjdskillnad från den höga till den låga kanten; den höga kanten ligger på höjdförskjutningen. Lampor på ytan följer med.", + "outdoor_slope_dir": "Lutar mot", + "slope_x": "höger (+X)", + "slope_nx": "vänster (−X)", + "slope_z": "ner (+Z)", + "slope_nz": "upp (−Z)", + "north": "Norr (° medurs från uppåt)", + "north_hint": "Norr behövs för solen (ljus genom fönstren).", + "map_on": "Visa en riktig karta under planritningen", + "map_lat": "Latitud", + "map_lon": "Longitud", + "map_use_ha": "Använd Home Assistants plats", + "map_opacity": "Synlighet (%)", + "map_zoom": "Detaljnivå", + "map_zoom_coarse": "grov", + "map_zoom_fine": "fin", + "map_move": "Flytta kartan under planritningen", + "map_step": "Steg", + "map_url": "Egen kartrutadress (tom = OpenStreetMap)", + "map_hint": "Din webbläsare laddar kartrutorna direkt från kartservern (OpenStreetMap som standard, respektera deras användarvillkor); inget laddas medan kartan är av. Planritningen ligger på kartan som kompassen anger – vrid kompassen eller flytta kartan tills huset passar.", + "compass_title": "Kompass", + "compass_n_short": "N", + "compass_s_short": "S", + "compass_swap": "Byt norr ↔ söder", + "compass_swap_hint": "Vrider kompassen 180°. Ritningen, takfallen och solcellsfälten förblir som de är.", + "compass_hint": "Om kompassen inte stämmer med verkligheten, vrid den här – inget behöver ritas om. Solljus, vind och takfallens väderstreck följer den.", + "roof": "Tak", + "roof_none": "Inget tak", + "roof_flat": "Platt tak", + "roof_gable": "Sadeltak", + "roof_custom": "Takfall (egna)", + "roof_sections": "Takfall", + "roof_sections_hint": "Varje takfall täcker en rektangel av huset, t.ex. huset, ladan eller en tillbyggnad – var och en med egen form, nockriktning, takfotshöjd och lutning. Dra i planritningen för att rita ett nytt; tryck markerar, dra flyttar, hörnen ändrar storleken.", + "roof_sections_start": "Skapa takfall från rummen", + "roof_sections_regen": "Skapa igen från rummen", + "roof_sections_off": "Tillbaka till ett tak", + "roof_regen_confirm": "Ersätta alla takfall med ett nytt förslag från rummen?", + "roof_section": "Takfall", + "roof_section_hint": "Höjder räknas från marken. En sida med lägre takfot når längre ner (catslide); pulpettak stiger från första sidan.", + "roof_shape_gable": "Sadeltak", + "roof_shape_hip": "Valmat tak", + "roof_shape_pent": "Pulpettak", + "roof_shape_flat": "Platt", + "roof_shape_halfhip": "Halvvalm", + "roof_shape_pyramid": "Pyramidtak", + "roof_shape_mansard": "Mansardtak", + "roof_shape_parapet": "Med bröstning", + "roof_shape": "Form", + "roof_end_start": "Avslut vid nockens början", + "roof_end_end": "Avslut vid nockens slut", + "roof_halfhip": "Halvvalmen börjar vid", + "roof_halfhip_hint": "Hur högt upp på gaveln valmen börjar, som andel av gavelns höjd: lågt = en stor valm, högt = bara spetsen.", + "roof_axis_x": "Nock ↔", + "roof_axis_z": "Nock ↕", + "roof_eave": "Takfot (m)", + "roof_pitch_short": "Lutning (°)", + "roof_height": "Höjd (m)", + "roof_base": "Väggkrön (m)", + "roof_rotation": "Vridning (°)", + "roof_on_floor": "Står på våning", + "roof_on_floor_hint": "Sätter takfallet på den här våningens väggkrön; bas och takfötter följer med. I 3D-vyn hör taket till den här våningen.", + "roof_base_hint": "Under takhöjden på våningen under slutar den våningens väggar under taket: knäväggar vid takfötterna, gavlar upp till nocken, innerväggar avskurna av lutningen. Streckade linjer i planritningen visar var 1,5 m och 2 m takhöjd återstår.", + "roof_ridge_height": "Nockhöjd", + "roof_side_top": "överkant", + "roof_side_bottom": "underkant", + "roof_side_left": "vänster", + "roof_side_right": "höger", + "roof_swap": "Byt sidor", + "roof_open": "Skärmtak (stolpar i stället för väggar, genomskinligt)", + "roof_open_short": "Skärmtak", + "roof_dormer": "Takkupa", + "roof_dormer_hint": "En takkupa på den här sidan av taket: 2 m bred, framsidan vid takfotsväggen, takfötter 1,4 m över takets takfot, sadeltak. Flytta den sedan och ändra bredd och höjder som vilket takfall som helst; huvudtakfallet öppnas under den och vindsväggen reser sig till kupan – där får ett fönster plats.", + "roof_outline": "Ta våningens kontur", + "roof_outline_hint": "Ett platt tak i fri form: tar konturen av den visade våningens rum (även L- eller Z-formad) som en yta utan skarvar. Hörnen kan dras efteråt.", + "roof_points_hint": "Fri form: dra hörnen i planritningen, ett + på en kant lägger till ett hörn, × tar bort ett. Tillbaka till rektangeln släpper formen.", + "roof_rect": "Tillbaka till rektangeln", + "roof_open_hint": "För ett altantak eller en carport: stolpar och balkar bär taket i stället för väggar, och det är genomskinligt. Där skärmtaket möter husväggen vilar det på väggen.", + "roof_swap_hint": "Vänder taket: de två sidorna byter takfot och lutning, ett pulpettak stiger åt andra hållet.", + "roof_pitch": "Taklutning (°)", + "roof_overhang": "Takutsprång (m)", + "roof_overhang_sides": "Takutsprång per sida", + "roof_overhang_a": "Utsprång takfot A (m)", + "roof_overhang_b": "Utsprång takfot B (m)", + "roof_overhang_u0": "Utsprång gavel början (m)", + "roof_overhang_u1": "Utsprång gavel slutet (m)", + "roof_overhang_auto": "Tillbaka till automatiskt", + "roof_overhang_sides_hint": "Utan egna värden är utsprånget automatiskt: lika överallt, utom där takdelen möter huset (inget där).", + "roof_ridge": "Nock", + "roof_ridge_long": "Längs långsidan", + "roof_ridge_short": "Längs kortsidan (t.ex. radhus)", + "device": "Enhet", + "lamp_mount": "Lampa", + "lamp_ceiling": "Taklampa", + "lamp_floor": "Golvlampa", + "lamp_table": "Bordslampa", + "lamp_wall": "Vägglampa", + "marker_height": "Markörhöjd (m)", + "height_auto": "Automatisk höjd", + "device_centre": "Till rummets mitt", + "lights_spread": "Fördela taklamporna jämnt", + "devices_search": "Sök enheter …", + "devices_more": "+{n} till", + "devices_less": "mindre", + "panel_more": "Fler enheter i området ({n})", + "panel_less": "Visa mindre", + "gaps_close": "Stäng glipor", + "gaps_hint": "Sammanfogar rum upp till 60 cm isär med en gemensam vägg; glipan blir innerväggens tjocklek.", + "gaps_none": "Inga glipor mellan rum hittades.", + "gaps_closed": "{n} ställen stängda.", + "gaps_closed_wall": "{n} ställen stängda, innervägg nu {t} m.", + "fps": "FPS", + "fps_title": "Prestandavisning (bildrutor per sekund)", + "hint_garage": "Tryck på en vägg för att lägga till en garageport", + "opening_garage": "Garageport", + "garage_hint": "Porten följer en garage-cover (position eller öppen/stängd) eller en garageportkontakt i rummets område.", + "door_hint": "Med en dörrkontakt svänger bladet upp; utan sensor står den halvöppen.", + "hint_door": "Tryck på en vägg för att lägga till en dörr", + "hint_window": "Tryck på en vägg för att lägga till ett fönster", + "opening_door": "Dörr", + "opening_window": "Fönster", + "opening_type": "Typ", + "opening_position": "Mitt från hörnet (m)", + "sill": "Bröstningshöjd (m)", + "opening_height": "Höjd (m)", + "hinge": "Gångjärn (sett från rummet)", + "hinge_left": "Vänster", + "hinge_right": "Höger", + "cover_entity": "Persienn", + "door_cover": "Motor (motoriserad dörr eller grind)", + "cover_position_entity": "Positionssensor (live)", + "cover_position_invert": "Sensorn räknar omvänt (0 = öppen)", + "contact_entity": "Kontakt", + "sensor_kind": "Sensortyp", + "sensor_kind_contact": "Fönsterkontakt (öppen/stängd)", + "sensor_kind_handle": "Handtagssensor (öppen/vädringsläge/stängd)", + "sensor_kind_contact_tilt": "Kontakt + vädringssensor", + "handle_entity": "Handtagssensor", + "handle_main": "Handtagssensor huvudblad", + "leaf_main": "Huvudblad", + "leaf_second": "Andra bladet", + "tilt_entity": "Vädringssensor", + "tilt_angle_entity": "Vinkelsensor för vädring (°, valfri)", + "tilt_angle_max": "Vinkel som räknas som helt vädringsläge (°)", + "tilt_angle_offset": "Förskjutning: vinkel som rapporteras stängd (°)", + "tilt_angle_invert": "Vinkeln räknar omvänt", + "door_shut": "Visa stängd utan sensor", + "door_shut_hint": "En dörr utan kontakt står halvöppen i 3D så att den syns som dörr. Markerat ritas den stängd – ytterdörr, carport, sidodörr.", + "door_angle": "Öppningsvinkel", + "door_angle_default": "Standard", + "door_angle_hint": "Hur långt dörrbladet öppnas. Med sensor öppnas det så långt när den rapporterar öppen; utan sensor står det så långt öppet (i stället för halvvägs). Standard blir som förut.", + "entity_auto": "Automatisk ({name})", + "entity_auto_none": "Automatisk (ingen hittades)", + "entity_none": "Ingen", + "entity_search": "Skriv för att söka …", + "opening_hint": "Sensortyp: fönsterkontakt (rapporterar öppen/stängd), handtagssensor (rapporterar öppen, vädringsläge och stängd – t.ex. ett Homematic-fönsterhandtag) eller kontakt + vädringssensor (en andra sensor som bara rapporterar vädringsläge). Automatiskt använder rummets områdes persienner och kontakter. Positionssensor: en entitet som rapporterar persiennens position medan den rör sig (t.ex. en Homematic-\"level\", 0–100 % eller 0–1, öppen = hög) – persiennen rör sig då live i 3D.", + "furniture": "Möbler", + "furniture_add": "Lägg till möbel", + "studio_new": "Bygg en egen möbel", + "studio_title": "Möbelverkstad", + "studio_title_edit": "Möbelverkstad: ändra", + "studio_hint": "Välj en mall, ställ in mått och fronter och placera möbeln i planen. Den hamnar i paketet ”Egna möbler” och kan ändras här senare.", + "studio_kind": "Mall", + "studio_kind_cabinet": "Skåp", + "studio_kind_shelf": "Hylla", + "studio_kind_lamp": "Lampa", + "studio_kind_device": "Apparat", + "studio_name": "Namn", + "studio_width": "Bredd (cm)", + "studio_depth": "Djup (cm)", + "studio_height": "Höjd (cm)", + "studio_doors": "Dörrar", + "studio_drawers": "Lådor", + "studio_shelves": "Hyllplan", + "studio_handle": "Handtag", + "studio_handle_bar": "Stång", + "studio_handle_knob": "Knopp", + "studio_handle_none": "Inga", + "studio_base": "Underrede", + "studio_base_plinth": "Sockel", + "studio_base_legs": "Ben", + "studio_base_none": "Ingen", + "studio_back": "Bakstycke", + "studio_lamp": "Typ", + "studio_lamp_floor": "Golvlampa", + "studio_lamp_table": "Bordslampa", + "studio_lamp_pendant": "Pendellampa", + "studio_lamp_wall": "Vägglampa", + "studio_display": "Skärm framtill (visar mediaspelaren)", + "studio_mount": "Står", + "studio_mount_floor": "På golvet", + "studio_mount_surface": "På en möbel", + "studio_mount_wall": "På väggen", + "studio_color_body": "Stomme", + "studio_color_lamp_body": "Fot och stativ", + "studio_color_front": "Fronter", + "studio_color_boards": "Hyllplan", + "studio_color_shade": "Skärm", + "studio_color_display": "Skärmram", + "studio_color_white": "Vit", + "studio_color_wood": "Trä", + "studio_color_metal": "Metall", + "studio_color_dark": "Mörk", + "studio_color_glass": "Glas", + "studio_color_accent": "Accent", + "studio_color_own": "Egen färg", + "studio_color_plan": "Planens färg", + "studio_place": "Placera i planen", + "studio_save": "Spara ändringen", + "studio_open": "Ändra i verkstaden", + "studio_error": "Kunde inte spara: {detail}", + "studio_pack_name": "Egna möbler", + "studio_pack_publisher": "Möbelverkstad", + "furniture_search": "Sök möbler …", + "furniture_search_none": "Inget hittades. Prova ett annat ord – på engelska eller tyska.", + "furniture_type": "Sak", + "rotation": "Rotation (°)", + "tilt_x": "Lutning fram/bak (°)", + "tilt_z": "Lutning åt sidan (°)", + "strip_tilt": "Lutning kring längden (°)", + "strip_upright": "Upprätt", + "strip_rise": "Lutning längs längden (°)", + "strip_upright_hint": "Slingan står på högkant: dess längd går uppåt från höjden över golvet – längs ett dörrkarmen, som ljuspelare. Lutningen lägger en liggande slinga mot en sluttning (90° = framsidan pekar åt sidan).", + "rotate_left": "↺ 90°", + "rotate_right": "↻ 90°", + "height_m": "Höjd (m)", + "furn_sofa": "Soffa", + "furn_armchair": "Fåtölj", + "furn_table": "Bord", + "furn_chair": "Stol", + "furn_bed": "Säng", + "furn_nightstand": "Nattduksbord", + "furn_wardrobe": "Garderob", + "furn_shelf": "Hylla", + "furn_kitchen": "Köksskåp", + "furn_worktop": "Bänkskiva", + "furn_fridge": "Kylskåp", + "furn_fridge_smart": "Smart kylskåp (side by side)", + "furn_door_left": "Dörrsensor vänster (frysidan)", + "furn_door_right": "Dörrsensor höger (kylsidan)", + "fridge_hint": "Medan en dörrsensor rapporterar öppen svänger dörren upp i 3D.", + "furn_stove": "Spis", + "furn_sink": "Diskho", + "furn_bathtub": "Badkar", + "furn_shower": "Dusch", + "furn_wc": "Toalett", + "furn_washbasin": "Handfat", + "furn_desk": "Skrivbord", + "furn_tv_board": "TV-bänk", + "furn_plant": "Växt", + "furn_rug": "Matta", + "furn_stairs": "Trappa", + "furn_stairwell": "Bjälklagsöppning", + "stairwell_hint": "Ett hål i den här våningen, till exempel över trappan eller för ett galleri; ovanifrån ser man igenom. Öppningen måste ligga inom ett rum; flera öppningar får överlappa (till exempel för en L-form). Trappor på våningen under som når hit öppnar också golvet av sig själva.", + "tool_hole": "Bjälklagsöppning", + "tool_roof": "Tak", + "tool_energy": "Energi", + "tool_wall": "Vägg", + "hint_wall": "Dra för att rita en fristående vägg (mellanvägg, halvvägg) · Shift håller den rak · Alt utan fästning", + "free_wall": "Vägg", + "wall_length": "Längd (m)", + "wall_thickness": "Väggtjocklek (m)", + "wall_height": "Höjd (m)", + "wall_height_full": "Full rumshöjd", + "wall_slope": "Lutande", + "wall_slope_start": "Höjd vid början (m)", + "wall_slope_end": "Höjd vid slutet (m)", + "wall_slope_hint": "Lutande vägg: överkanten går rakt från höjden vid väggens början (hörnet med lägre nummer) till höjden vid dess slut. Båda får ligga över våningshöjden, till exempel för ett utbyggt rum med höga fönster.", + "wall_slope_off": "Tillbaka till en rak vägg", + "wall_none": "Ingen vägg", + "wall_none_hint": "Utelämna den här väggen helt: för öppna planlösningar där rummen är ett utrymme men separata i Home Assistant.", + "edge_thickness": "Tjocklek (m)", + "wall_thickness_hint": "Den här väggens tjocklek, t.ex. 0,365 på en tjock yttervägg eller 0,115 på en lätt mellanvägg. En vägg mellan två rum får den tjockare inställningen.", + "wall_thickness_reset": "Tjocklek enligt husets inställning", + "wall_heights": "Vägghöjder", + "wall_n": "Vägg {a}–{b}", + "wall_view": "Väggvy", + "wall_view_hint": "Väggen framifrån: dra dess dörrar, fönster och möbler eller skriv in deras avstånd.", + "wall_view_prev": "Föregående vägg", + "wall_view_next": "Nästa vägg", + "wall_view_left": "Från vänster (m)", + "wall_view_height": "Över golvet (m)", + "wall_part": "del {n}", + "wall_split_hint": "Dela väggen här: delen får en egen höjd, t.ex. 2,5 m bredvid 1,7 m i linje", + "wall_split_at": "Delningspunkt från hörnet (m)", + "wall_join_hint": "Ta bort delningspunkten: delen förenas igen med den föregående", + "wall_exterior_short": "yttervägg", + "room_wall_hint": "En lägre höjd gör väggen till en bröstning eller disk. Om två rum delar väggen gäller den lägre inställningen. Fönster och dörrar i den slutar vid vägghöjden.", + "free_wall_hint": "En fristående vägg, t.ex. en mellanvägg. Där den möter en rumsvägg geringsskärs hörnet. Dra handtagen för att flytta ändarna, dra linjen för att flytta hela väggen.", + "free_wall_slope": "◢ Lutande", + "free_wall_slope_hint": "Väggen blir högre eller lägre från ena änden till andra: höjden ovan gäller början, den här slutet.", + "free_wall_height_end": "Höjd i slutet (m)", + "stairwell_outside": "Den här öppningen sträcker sig över en rumsgräns och skärs därför inte ut. Flytta den helt in i ett rum eller gör den mindre.", + "hint_hole": "Dra för att rita en bjälklagsöppning (trapphål, galleri)", + "hint_roof": "Dra för att rita ett takfall · tryck markerar · dra flyttar · hörnen ändrar storlek", + "hint_energy": "Tryck på ett solcellsfält för att markera det · dra för att flytta det, även till ett annat takfall · nya fält med + Solcellsfält till höger", + "furn_parking": "Parkeringsplats", + "furn_group_vehicles": "Parkering", + "parking_entity": "Sensor \"bil närvarande\"", + "parking_vehicle": "Fordon", + "parking_vehicle_none": "Ingen", + "parking_no_pack": "Inget fordonspaket importerat – fordon kommer från paketet \"Fordon\" (Tillägg → Möbelpaket).", + "parking_scale": "Storlek (%)", + "parking_type_entity": "Sensor för fordonstyp (valfri)", + "parking_types": "Tillstånd → fordon", + "parking_type_state": "Tillstånd (t.ex. van)", + "parking_add_type": "+ Koppling", + "parking_hint": "Utan sensor står fordonet alltid där. Med en visas det så snart sensorn rapporterar \"on\", \"home\" eller \"present\". En sensor för fordonstyp (t.ex. från en AI-kameraanalys) väljer modellen: när dess tillstånd matchar en koppling – även som ord i texten – visas det fordonet, annars standardfordonet.", + "parking_too_tall": "Fordonet ({car} m) är högre än rummet ({room} m).", + "furn_lamp_ceiling": "Taklampa", + "furn_lamp_downlight": "Downlight", + "furn_lamp_spot": "Utanpåliggande spot", + "furn_lamp_panel": "LED-panel", + "furn_lamp_uplight": "Markspot", + "furn_lamp_bollard": "Pollare", + "furn_lamp_garden": "Trädgårdsspot", + "furn_radiator": "Element", + "furn_robot_vacuum": "Robotdammsugare", + "furn_entity_vacuum": "Robotdammsugare", + "furn_entity_mower": "Robotgräsklippare", + "pet_room_sensor": "Djurets rumssensor (valfritt)", + "pet_room_hint": "En sensor som anger rummet djuret är i – Bermuda eller ESPresense med en tagg på halsbandet: i 3D strövar det då i det rummet.", + "furn_entity_water": "Ventil eller brytare", + "fridge_temp": "Kylens temperatur", + "freezer_temp": "Frysens temperatur", + "fridge_temp_hint": "Markören visar temperaturerna. Över 8 °C i kylen eller −12 °C i frysen lyser den som varning.", + "spray_reach": "Vattnets räckvidd (m)", + "spray_hint": "Så länge ventilen är öppen eller brytaren på kastar spridaren vatten i bågar runt sig.", + "furn_robot_room": "Aktuellt rum (sensor)", + "robot_hint": "Medan roboten städar i Home Assistant kör den banor i 3D genom rummet den rapporterar (en sensor ”aktuellt rum”, matchad mot rums- eller områdesnamn), annars genom rummet med dess docka. Spåret är simulerat – Home Assistant vet oftast inte den exakta positionen. Den kör tillbaka till dockan när den återvänder.", + "furn_lamp_pendant": "Pendellampa", + "furn_ceiling_fan": "Takfläkt", + "furn_fan_entity": "Fläkt", + "fan_hint": "Lampan är fläktens belysningsdel (lämna tom om den inte har någon). Fläkten hittas i rummet eller väljs här: i 3D snurrar bladen så snabbt som den går, dess ikon växlar den, svep upp/ner ändrar hastigheten, ett långt tryck öppnar snabbmenyn. Höjden är hur långt den hänger under taket (mer = en längre stång).", + "room_ceiling": "Takhöjd", + "room_ceiling_tip": "Lägre än våningen (ett badrum under trappan) eller högre (ett vardagsrum öppet upp till taket): taklampor, fläktar, LED-slingor och takmonterade enheter hänger då härifrån, och rummets väggar är så här höga.", + "room_ceiling_through": "Taket ({ceiling} m) ligger över våningshöjden ({floor} m): rummet når upp i våningen ovanför, dess väggar växer med och våningen ovanför förblir öppen över det. Editorn för den övre våningen visar ytan skrafferad.", + "room_floor_offset": "Golvnivå (m)", + "room_floor_offset_hint": "Ligger rummets golv lägre eller högre än våningen (en nedsänkt entré: −0,39) följer golv, väggar, dörrar, fönster och det som står i rummet med; taket stannar. Lägg till stegen som en trappa.", + "room_inner": "Invändigt {w} × {d}", + "room_inner_hint": "Mätt vägg till vägg: innerväggar tar halva sin tjocklek, ytterväggar står utanför konturen.", + "floor_heating": "Golvvärme (valfritt)", + "floor_heating_hint": "Så länge termostaten värmer (eller ventilen är öppen, brytaren på) glöder rummets golv varmt i 3D.", + "room_announce_speaker": "Högtalare för utrop", + "room_announce_quiet": "Tyst tid för utrop", + "room_announce_hint": "Utan val talar högtalaren som står i rummet, annars en röstassistent, en Echo eller en högtalare i området (aldrig en tv). Under den tysta tiden hoppar utrop till flera rum över detta rum; ett utrop bara till det kommer ändå fram.", + "ceiling_here": "Tak här", + "ceiling_here_hint": "Takets höjd precis på den här platsen, t.ex. under ett snedtak. Tom = rummets tak.", + "ceiling_slope": "Upp mot taksnedden", + "ceiling_slope_hint": "Taket ligger här under taksnedden: lampan hänger från dess undersida, rakt ovanför sin plats.", + "furn_lamp_floor": "Golvlampa", + "furn_lamp_table": "Bordslampa", + "furn_lamp_wall": "Vägglampa", + "furn_led_strip": "LED-slinga", + "furn_group_lights": "Lampor", + "furn_entity_light": "Lampa eller brytare", + "furn_color_entity": "Färg och ljusstyrka från (valfritt)", + "furn_color_entity_hint": "För lampor som ett relä (Shelly, ställdon) tänder och släcker medan lampan själv känner sin färg och ljusstyrka: på/av kommer från brytaren ovan, färg och ljusstyrka från den här entiteten.", + "lamp_extra_light": "Ljuskälla {n} (valfritt)", + "lamp_extra_hint": "En armatur med flera ljus – huvudljus, nattljus, ljusring: när huvudljuset är av lyser den i 3D med nästa ljus som är på, lite svagare. Tänd ljusen ett och ett i rumspanelen.", + "furn_entity_climate": "Värme (termostat)", + "lamp_hint": "Tryck på lampan i 3D för att växla den, långt tryck för snabbmenyn. Brytare fungerar också (t.ex. ett relä för taklampan) – lampan lyser medan den är på. Bordslampor står på möbeln under dem.", + "lamp_hint_pendant": "Höjd = nedhäng under taket. Tryck i 3D för att växla, långt tryck för detaljer.", + "theme": "Utseende", + "version_hint": "Installerad version av NextFloor – frontend; integrationen i Home Assistant rapporterar {backend}", + "accent": "Accentfärg", + "accent_hint": "En egen accentfärg: linjer och lysande kanter i neonutseendet, knappar och markörer – ↺ tar tillbaka neoncyan", + "accent_reset": "Tillbaka till cyan", + "theme_neon": "Neon", + "theme_blueprint": "Ritning", + "theme_day": "Dag", + "theme_auto": "Auto", + "clock": "Klocka", + "clock_none": "Ingen", + "clock_top_left": "Uppe till vänster", + "clock_top_right": "Uppe till höger", + "clock_bottom_left": "Nere till vänster", + "clock_bottom_right": "Nere till höger", + "glass_walls": "Glasväggar", + "glass_walls_hint": "Hur täckande väggarna är som man ser in i rummen genom: till vänster nästan osynliga, till höger ogenomskinliga. För denna skärm.", + "screen_name": "Namn på denna skärm", + "screen_name_hint": "Utrop visas på varje öppen NextFloor-skärm. Med ett namn (t.ex. ”Hall”) kan ett utrop gå bara till denna skärm. Utan bock förblir denna skärm tyst.", + "announce_on": "Utrop på denna skärm på", + "announce_muted": "Utrop på denna skärm avstängda", + "lock3d_on": "Lås 3D (ingen vridning, zoom eller panorering; tryck fungerar fortfarande)", + "lock3d_off": "Lås upp 3D", + "walk": "Gå runt i huset", + "travel": "Tidsresa: spela upp de senaste 24 timmarna eller 7 dagarna", + "travel_play": "Spela", + "travel_pause": "Paus", + "travel_loading": "Laddar historik …", + "travel_failed": "Historiken kunde inte laddas.", + "travel_speed": "Hastighet", + "travel_speed_min": "1 min/s", + "travel_speed_10min": "10 min/s", + "travel_speed_hour": "1 h/s", + "travel_days": "dagar", + "travel_live": "Live", + "card_travel_button": "Knapp för tidsresa", + "walk_stop": "Sluta gå", + "walk_hint": "Dra: se dig omkring · W A S D / pilar eller spak: gå · scrollhjul: steg", + "card_walk_button": "Knapp för att gå runt", + "card_lock_button": "Knapp för 3D-låset", + "backdrop": "Egen bakgrund", + "backdrop_color": "Färg", + "backdrop_image": "Bild (/local/… eller https://…)", + "backdrop_dim": "Dämpa", + "backdrop_hint": "I stället för utseendets himmel står huset framför en egen färg eller bild. En bild i /config/www nås via /local/….", + "furnish": "Möblera", + "split_3d": "3D bredvid", + "plan_dims": "Mått", + "plan_dims_hint": "Skriver ut längden på varje rumskant.", + "mount_height": "Höjd över golvet (m)", + "side_open": "Öppna sidofältet", + "side_close": "Stäng", + "side_details": "Detaljer om markeringen", + "side_pin": "Fäst", + "side_pinned": "Fäst", + "side_pin_hint": "Fäst stannar sidofältet öppet; annars fälls det ihop bredvid 3D-vyn när inget är markerat", + "split_3d_hint": "Live-3D bredvid planritningen: dra och vrid möbler och enheter där – med ångra, sparas med planritningen", + "size_w": "Bredd (m)", + "size_d": "Djup (m)", + "size_h": "Höjd (m)", + "furnish_hint": "Dra möbler, lampor och enheter · möbler fäster mot väggar · tryck på en sak för att vrida den, ställa in höjd och montering", + "done": "Klar", + "heatmap": "Värmekarta", + "heat_off": "Normal", + "heat_short_temperature": "Temp.", + "heat_short_humidity": "Fukt", + "heat_short_co2": "CO₂", + "heat_short_mould": "Mögel", + "heat_short_power": "El", + "heat_short_comfort": "Komfort", + "heat_short_sun": "Sol", + "heat_short_wifi": "Wi-Fi", + "heat_short_values": "Värden", + "heat_temperature": "Temperatur", + "heat_humidity": "Luftfuktighet", + "heat_co2": "CO₂", + "heat_mould": "Mögel", + "heat_power": "Elförbrukning", + "heat_comfort": "Komfortvärde", + "heat_sun": "Sol i dag", + "room_sun_hours": "{h} h sol i dag ({facing})", + "open_since": "öppet i {time}", + "presence_now": "någon är här", + "presence_last": "sågs för {time} sedan", + "comfort_n": "Komfort {n}", + "empty_lights_hint": "{n} lampor tända, ingen här på {min} min.", + "empty_lights_off": "Släck", + "open_heating_hint": "{n} fönster öppna medan värmen är på.", + "open_heating_off": "Värme av", + "room_clean": "Städning (skript eller knapp)", + "room_clean_hint": "Ett skript eller en knapp som skickar robotdammsugaren till rummet (t.ex. rumsstädningen i din robotintegration). Rumspanelen visar då ”🧹 Dammsug”.", + "room_clean_run": "Dammsug", + "room_clean_run_hint": "Skickar robotdammsugaren till rummet.", + "shade_hint": "Sol på {n} fönster vid {temp} – sänka rullgardinerna?", + "shade_close": "Sänk", + "room_sun_year": "Sol över året", + "room_sun_year_hint": "Soltimmarna genom rummets ytterfönster den 15:e varje månad.", + "room_energy": "i dag {today} · månad {month}", + "room_energy_hint": "Från statistiken för effektsensorerna i rummets enheter; månadens kostnad med husets tariff.", + "heat_summer": "sommar", + "heat_winter": "vinter", + "air_co2": "vädra (CO₂)", + "air_humidity": "vädra (fuktigt)", + "air_mould": "mögelrisk – vädra", + "room_curve_hint": "Rummets temperatur de senaste 24 timmarna", + "heat_values": "Värden vid rumsnamnen", + "heat_wifi": "Wi-Fi", + "wifi_aps": "{n} åtkomstpunkter · {clients} enheter", + "wifi_network": "Nätverk: {online} online · {offline} offline", + "wifi_none": "Placera åtkomstpunkter eller routrar från paketen (Smart hem 2) och koppla dem till en entitet på deras enhet.", + "wifi_clients": "{n} enheter", + "heat_none_found": "Inga passande sensorer i rummens områden.", + "markers": "Markörer", + "markers_none": "Inga", + "markers_important": "Viktiga", + "markers_all": "Alla", + "furn_stool": "Pall", + "furn_coffee_table": "Soffbord", + "furn_tv_wall": "TV (vägg)", + "furn_sideboard": "Skänk", + "furn_table_round": "Runt bord", + "furn_bench": "Bänk", + "furn_corner_bench": "Hörnbänk", + "furn_bar_stool": "Barstol", + "furn_kitchen_wall": "Väggskåp", + "furn_kitchen_tall": "Högskåp med ugn", + "furn_island": "Köksö", + "furn_dishwasher": "Diskmaskin", + "furn_bunk_bed": "Våningssäng", + "furn_dresser": "Byrå", + "furn_washer": "Tvättmaskin", + "furn_dryer": "Torktumlare", + "furn_office_chair": "Kontorsstol", + "furn_tall_cabinet": "Högt skåp", + "furn_coat_rack": "Klädhängare", + "furn_group_living": "Vardag", + "furn_group_dining": "Mat", + "furn_group_energy": "Energi och sol", + "energy_devices": "Enheter", + "wallbox_charging": "laddar", + "wallbox_plugged": "inkopplad", + "furn_soc": "Laddnivå (%)", + "furn_export": "Exporteffekt (W, separat sensor, valfri)", + "furn_export_hint": "Om din elmätare rapporterar köp och export i två sensorer (t.ex. Growatt, Tibber Pulse), ta köpsensorn som effekt ovan och exportsensorn här. En sensor med tecken behöver inte detta.", + "meter_parent": "Hänger på elmätare", + "meter_parent_none": "ingen (huvudmätare)", + "meter_main": "Huvudmätare", + "meter_unmetered": "{w} omätt", + "meter_device_hint": "Om enheten sitter bakom en undermätare (t.ex. en balkongsolcell i en lägenhet) räknas dess effekt till den lägenheten. Undermätaren måste då mäta i båda riktningarna (− = inmatning); räknar den bara köp blir lägenhetens förbrukning för hög vid överskott.", + "meter_sub_power": "Gruppens effekt (W, + = köpt, − = inmatad)", + "meter_floors": "Matar våningarna", + "meter_sub_hint": "En undermätare mäter sin grupp, t.ex. en lägenhet. Enheter på de markerade våningarna hänger på den i 3D i stället för på huvudmätaren; det huvudmätaren räknar därutöver visas som ”Gemensamt (rest)” i balansen.", + "furn_charge": "Laddeffekt (W, separat sensor, valfri)", + "furn_charge_hint": "Om ditt batteri rapporterar laddning och urladdning i två sensorer (t.ex. Anker Solix), ta urladdningssensorn som effekt ovan och laddsensorn här. En sensor med tecken behöver inte detta.", + "furn_wallbox_status": "Status (laddar, inkopplad)", + "energy_only_note": "⚡ Energi: här kan bara solcellsfält och energienheter flyttas; rum och möbler är låsta.", + "roof_only_note": "🏠 Tak: här kan bara takfall och takfönster flyttas; rum och möbler är låsta.", + "energy_devices_hint": "Elmätare, växelriktare, hembatterier, laddboxar och nätanslutningen läggs till här: på våningen som valts ovan, flyttbara i planritningen. Med en effektsensor visar de sina watt; elmätaren tar nätsensorn, en sträng väljer sin växelriktare. Flera växelriktare och batterier (t.ex. en extra balkongsolcell) fungerar också: var och en med egen sensor.", + "energy_routes": "Kabeldragningar", + "energy_routes_hint": "Var en kabel verkligen går: flödet följer då dina punkter i stället för en båge genom huset. Utan dragning blir det kvar en båge. Förbrukare behåller sin båge.", + "route_conn_solar": "{name} → växelriktare", + "route_conn_battery": "Batteri ↔ hus", + "route_conn_inverter": "Växelriktare → hus", + "route_conn_grid": "Nät ↔ hus", + "route_conn_meter": "{name} ↔ överordnad mätare", + "route_conn_device": "{name} ↔ undermätare", + "route_points": "{n} punkter", + "route_none": "direkt båge", + "route_draw": "Rita dragning", + "route_redraw": "Rita om", + "route_drawing": "Tryck i planen på punkterna kabeln går genom, från ena änden till den andra; byt våning där den går genom ett bjälklag. {n} punkter.", + "route_undo": "Sista punkten", + "route_done": "Klar", + "route_cable": "Visa som kabel", + "route_cable_hint": "Ritar dragningen som en synlig kabel, inte bara som den tunna linjen under partiklarna.", + "solar_fields": "Solcellsfält", + "solar_hint": "Lägg moduler på taket: de ligger i takfallets lutning; på ett platt tak står de på ställningar. Dra ett fält i planritningen för att flytta det.", + "solar_no_roof": "Solcellsfält behöver ett tak: ett sadel- eller platt tak under Inställningar, eller takfall här i verktyget Tak.", + "solar_face_gone": "takfall saknas", + "solar_summary": "{n} moduler · {kwp} kWp", + "solar_add": "Solcellsfält", + "solar_field": "Solcellsfält", + "solar_face": "Takfall", + "solar_rows": "Rader", + "solar_cols": "Moduler per rad", + "solar_portrait": "Stående", + "solar_landscape": "Liggande", + "solar_u": "Avstånd från kanten (m)", + "solar_v": "Avstånd från takfoten (m)", + "solar_tilt": "Ställningarnas lutning (°)", + "solar_rack_ew": "Öst-väst-ställning", + "solar_rack_ew_hint": "Varannan rad vänd åt andra hållet, paren rygg mot rygg – lågt och tätt, som på många platta tak.", + "solar_rack_tilt": "Ställning (° extra lutning)", + "solar_flip": "Luta åt andra hållet", + "solar_partial": "bara {n} av {total} får plats på takfallet", + "solar_form_hint": "Moduler som skulle sticka ut utanför takfallet utelämnas. ”Fyll takfallet” lägger så många moduler som får plats. kWp räknat med 400 W per modul.", + "solar_fit": "Fyll takfallet", + "roof_windows": "Takfönster", + "roof_window": "Takfönster", + "roof_windows_hint": "Takfönster ligger i takfallet, med persienn och kontakter som fönster. Dra dem i planritningen, även till ett annat takfall.", + "roof_window_tilt": "Vädringskontakt", + "roof_window_name": "Namn (valfritt)", + "roof_window_motor": "Fönstermotor (cover, valfri)", + "roof_window_motor_hint": "En fönstermotor (Velux, Roto, Fakro) rapporterar sin position som cover: bågen öppnas i 3D så långt som motorn står. En kontakt eller vädringskontakt fungerar också utan motor.", + "roof_window_hint": "Öppen svänger bågen utåt, hängd upptill; i vädringsläge lite grann; karmen lyser varmt; persiennen går ner över glaset uppifrån. I ett takfall skär fönstret ett hål i lutningen så att vinden ser ut genom det.", + "solar_ground": "Fristående (trädgård, garagetak …)", + "solar_add_ground": "Fristående", + "solar_base": "Ytans höjd (m, 0 = mark)", + "solar_add_wall": "På en vägg", + "solar_wall": "Vägg", + "solar_v_wall": "Höjd över golvet (m)", + "solar_tilt_wall": "Lutning från väggen (°, 90 = skärmtak)", + "solar_flip_wall": "Utstående nedtill i stället för upptill", + "solar_rotation": "Rotation (°)", + "solar_name": "Namn", + "solar_name_hint": "t.ex. sträng 1 syd", + "solar_module_w": "Modulbredd (m)", + "solar_module_h": "Modulhöjd (m)", + "solar_wp": "Moduleffekt (Wp)", + "solar_string": "Sträng", + "solar_strings": "Strängar", + "solar_string_none": "Ingen sträng", + "solar_string_new": "Ny sträng", + "solar_string_n": "Sträng {n}", + "solar_string_name": "Strängens namn", + "solar_string_entity": "Strängens solcellseffekt", + "solar_string_inverter": "Växelriktare", + "solar_string_inverter_none": "Ingen växelriktare vald", + "inverter_strings": "Strängar på den här växelriktaren: {names}", + "inverter_strings_none": "Ingen sträng på den här växelriktaren ännu – tilldela den vid ett solcellsfält under Sträng › Växelriktare.", + "solar_string_inverter_missing": "Ingen växelriktare i planritningen ännu (lägg till en nedan under Enheter)", + "solar_string_hint": "Fält i samma sträng hör ihop, även på olika tak (t.ex. 5 moduler på huset och 5 på garaget). Sensor och växelriktare gäller för hela strängen.", + "solar_string_sum": "{fields} fält · {n} moduler · {kwp} kWp", + "solar_face_size": "Takfall {w} × {h} m (längs takfoten × uppför lutningen)", + "solar_cols_hint": "Ett tal för lika långa rader, eller en lista för egna rader: ”4, 4, 3” (från takfoten).", + "solar_align_left": "Vänster", + "solar_align_center": "Mitten", + "solar_align_right": "Höger", + "solar_look_black": "Full black", + "solar_look_blue": "Blå", + "solar_pick": "Moduler på/av en och en", + "solar_pick_all": "Alla på igen", + "solar_pick_hint": "Tryck på en modul i planritningen för att ta bort den eller sätta tillbaka den. Borttagna visas streckade.", + "solar_entity": "Solcellseffekt för det här fältet (t.ex. dess sträng)", + "solar_main": "Huvudtak", + "solar_section": "Takfall {n}", + "solar_flat": "platt tak", + "compass_n": "norr", + "compass_ne": "nordost", + "compass_e": "öster", + "compass_se": "sydost", + "compass_s": "söder", + "compass_sw": "sydväst", + "compass_w": "väster", + "compass_nw": "nordväst", + "furn_meter": "Elmätare", + "furn_grid_point": "Nätanslutning", + "grid_point_hint": "Nätanslutningen står här: överlämningspunkten till nätbolaget, t.ex. vid slutet av uppfarten. Flyttbar i planritningen.", + "furn_model": "Modell", + "inverter_std": "Standard (väggenhet med display)", + "inverter_slim": "Smal och hög (ljuslist)", + "inverter_hybrid": "Hybrid (rund ratt, fläktar)", + "battery_std": "Torn (staplade moduler)", + "battery_wall": "Väggbatteri (platt, hängande)", + "battery_cube": "Kompakt (balkongbatteri)", + "furn_inverter": "Solcellsväxelriktare", + "furn_home_battery": "Hembatteri", + "furn_wallbox": "Laddbox", + "furn_group_kitchen": "Kök", + "furn_group_sleeping": "Sova", + "furn_group_bath": "Bad och tvätt", + "furn_group_work": "Arbete och övrigt", + "furn_entity": "Enhet (brytare, kontakt …)", + "furn_state_entity": "Tillstånd från (valfritt)", + "furn_state_entity2": "Andra tillståndet (andra halvan)", + "furn_state_split": "Halvor", + "furn_state_left_right": "Vänster / höger", + "furn_state_top_bottom": "Nere / uppe (våningssäng)", + "furn_state_hint": "Saken lyser medan entiteten rapporterar på, upptagen eller hemma – en säng med närvaromatta, en fåtölj, bastun. Två entiteter lyser upp halvorna: vänster och höger, nere och uppe för en våningssäng.", + "furn_entity_tv": "TV (mediaspelare eller smart uttag)", + "fix": "Fäst", + "unfix": "Lossa", + "fix_hint": "Fäst: kan inte längre flyttas av misstag (tangent L, högerklick eller långt tryck)", + "fixed_drag_hint": "🔒 Fäst – lossa den först för att flytta (lås i formuläret, högerklick eller tangent L)", + "fixed_delete_confirm": "Den här saken är fäst. Ta bort ändå?", + "lock_plan": "🔒 Planritning", + "lock_plan_hint": "Lås planritningen: rum, väggar, dörrar, fönster och uteytor kan inte flyttas av misstag. Möbler och enheter förblir fria.", + "start_view": "Startvy", + "start_view_hint": "3D-vyn, kortet och kiosken öppnar huset med den här vyn, t.ex. från trädgårdssidan. Vrid, zooma och flytta huset i 3D-rutan till höger tills det passar, och spara det sedan.", + "start_view_card": "Om ett kort ska öppnas med en annan vy, lägg den här raden i dess YAML-konfiguration.", + "start_view_set": "Spara den aktuella 3D-vyn som start", + "start_view_reset": "Standard", + "start_view_saved": "En egen startvy är sparad.", + "ctx_rotate": "Vrid 90°", + "devices_placed_in": "i {room}", + "devices_narrow": "{n} till – förfina sökningen", + "climate": "Rumsklimat", + "climate_temperature": "Temperatur", + "climate_humidity": "Luftfuktighet", + "climate_co2": "CO₂", + "climate_hint": "De här sensorerna gäller för värmekartan och rumspanelen. ”Automatiskt” tar områdets sensorer och de som placerats i rummet, men inga enhetstemperaturer (3D-skrivare, värmepump, framledning …).", + "climate_more": "… och en sensor till (medelvärde)", + "plan_locked": "Planritningen låst", + "plan_lock": "Lås planritningen", + "plan_unlock": "Lås upp planritningen", + "opening_mark": "Framhäv i 3D", + "opening_mark_open": "När öppen", + "opening_mark_closed": "När stängd (t.ex. toalett)", + "opening_mark_hint": "Ett framhävt fönster eller en framhävd dörr lyser varmt. ”När stängd” kräver en kontakt; utan sensor framhävs inget.", + "window_opens": "Öppnas", + "window_opens_turn": "Vrid-fäll (inåt)", + "window_opens_slide": "Skjutbart (skjutfönster, lyft-skjutdörr)", + "window_opens_top": "Överkantshängt (nederkanten öppnas utåt)", + "window_opens_hint": "Skjutbart: bågen på gångjärnssidan glider framför den fasta; med två bågar glider de två mittersta utåt. Överkantshängda fönster öppnas med sin kontakt eller en vädringssensor.", + "marker_show": "Markör i 3D", + "marker_show_hint": "Automatiskt följer brytaren Inga / Viktiga / Alla i 3D-vyn. Visa alltid och Dölj gäller oavsett (utom med Inga).", + "pin_shift": "Flytta nålen", + "pin_shift_up": "↑ höjd", + "pin_shift_hint": "När enheter står tätt, flytta nålen här lite åt sidan eller uppåt (i meter); själva enheten stannar där den är.", + "marker_show_auto": "Automatiskt", + "marker_show_always": "Visa alltid", + "marker_show_no_power": "Utan watt", + "marker_show_active": "Bara när aktiv", + "marker_show_never": "Dölj", + "marker_icon": "Egen symbol (Material Design-ikon)", + "device_name": "Eget namn (valfritt)", + "show_name": "Visa namnet under markören i 3D", + "card_marker_names": "Egna namn vid markörerna", + "card_marker_names_hint": "Varje enhet med eget namn visar det litet under markören – tre termometrar i trädgården går att skilja åt.", + "device_name_hint": "Ett namn bara för planritningen och rumspanelen, t.ex. \"Accentljus köksö\" – entiteten i Home Assistant förblir som den är.", + "device_simple": "Bara strömbrytare i rumspanelen", + "device_simple_hint": "Rumspanelen visar för den här lampan bara strömbrytaren, utan ljusstyrka, färgtemperatur och färger.", + "floor_turn": "Vrid 90°", + "floor_shift_all": "Ta med alla våningar (hela huset)", + "floor_shift_all_hint": "Flytta och vrid gäller alla våningar med takfall, uteytor, energienheter och elmätare – hela huset rör sig som en enhet.", + "floor_turn_hint": "Vrider allt på våningen 90° medurs kring mitten av dess rum – när en våning ritats åt fel håll. Tre gånger = 270°.", + "marker_icon_hint": "Namnet på en Material Design-ikon som i Home Assistant, t.ex. mdi:thermometer eller mdi:water-alert. Tom = symbolen för enhetstypen.", + "furn_power": "Effektsensor (W)", + "furn_links_hint": "Med en effektsensor visar saken sina watt och deltar i energiflödet.", + "furn_links_hint_tv": "Skärmen lyser medan tv:n är på, i appens färg (Netflix, YouTube …); etiketten visar appen eller titeln.", + "stairs_hint": "Trappan stiger bakåt (bort från den markerade framkanten) och öppnar taket på våningen ovanför.", + "floor_lights": "{n} lampor tända", + "floor_open": "{n} öppna", + "floor_persons": "{n} personer", + "energy_consumption": "Förbrukning", + "energy_grid_import": "Nätköp", + "energy_grid_export": "Export", + "energy_solar": "Sol", + "energy_battery": "Batteri", + "energy_tariff": "Tariff", + "energy": "Energi", + "energy_meter": "Elmätare", + "energy_grid": "Elnät (W, + = köp)", + "energy_solar_sensor": "Solproduktion (W)", + "energy_battery_sensor": "Batterieffekt (W, + = urladdning)", + "energy_battery_soc": "Batteriladdning (%)", + "energy_tariff_sensor": "Tariff (t.ex. kr/kWh)", + "energy_gas": "Gasmätare (valfritt)", + "energy_water": "Vattenmätare (valfritt)", + "energy_meters_hint": "Gas och vatten visas med husets balans – i energilisten och på huskortet: en sensor med flödet nu (m³/h, l/min) eller dagens mätarställning.", + "energy_gas_short": "Gas", + "energy_water_short": "Vatten", + "energy_invert": "Vänd tecken", + "energy_hint": "Förbrukare är placerade enheter med en effektsensor (W) – sensorn själv eller en från samma enhet.", + "energy_balance": "Energibalans", + "energy_balance_hint": "Elnät, sol och batteri kommer från enheterna i planritningen: elmätare, växelriktare och hembatteri. Här kan du välja andra sensorer, vända tecken och ange husets förbrukning.", + "energy_rest": "Gemensamt (rest)", + "energy_advanced": "Avancerat energiläge", + "energy_advanced_on": "Använd undermätare", + "energy_show_unmetered": "Visa omätt förbrukning vid undermätare", + "energy_show_unmetered_hint": "En undermätares etikett visar då vad dess våningar förbrukar och hur mycket av det ingen placerad enhet mäter, t.ex. ”500 W · 450 W omätt”. Annars visas mätarens värde.", + "energy_advanced_hint": "För undermätare, t.ex. en per lägenhet bakom en huvudmätare: en mätare kan då hänga på en annan och mata egna våningar. Av = den första mätaren är nätanslutningen, ytterligare är förbrukare.", + "energy_consumption_sensor": "Husets förbrukning (W, annars från balansen)", + "energy_import_prefs": "Hämta från energipanelen", + "energy_import_done": "{n} sensorer hämtade – kontrollera tecknen.", + "energy_import_none": "Inga passande effektsensorer (W) hittades i energipanelen – välj dem manuellt.", + "energy_import_failed": "Home Assistants energipanel är inte inställd.", + "tool_meter": "Elmätare", + "hint_meter": "Tryck på elmätarens plats", + "presence": "Närvaro", + "presence_hint": "Rumssensor per person (t.ex. ESPresense, Bermuda): dess tillstånd anger rummet eller området.", + "presence_sensor": "Rumssensor", + "no_persons": "Det finns inga personer i Home Assistant.", + "packname:nextfloor.a_bad": "Badrum", + "pack:nextfloor.a_bad:vanity_60": "Kommod 60 med underskåp", + "pack:nextfloor.a_bad:vanity_80": "Kommod 80 med underskåp", + "pack:nextfloor.a_bad:vanity_100": "Kommod 100 med underskåp", + "pack:nextfloor.a_bad:vanity_double_120": "Dubbelkommod 120", + "pack:nextfloor.a_bad:vanity_double_160": "Dubbelkommod", + "pack:nextfloor.a_bad:pedestal_basin": "Piedestalhandfat", + "pack:nextfloor.a_bad:bathtub_builtin": "Inbyggt badkar", + "pack:nextfloor.a_bad:bathtub_corner": "Hörnbadkar", + "pack:nextfloor.a_bad:bathtub_corner_compact": "Platsbesparande hörnbadkar", + "pack:nextfloor.a_bad:bathtub_free": "Fristående badkar", + "pack:nextfloor.a_bad:whirlpool_indoor": "Bubbelbadkar inomhus", + "pack:nextfloor.a_bad:shower_corner_90": "Hörndusch 90 × 90", + "pack:nextfloor.a_bad:shower_niche_120": "Nischdusch 120 × 90", + "pack:nextfloor.a_bad:shower_walkin_140": "Walk-in-dusch 140 × 90", + "pack:nextfloor.a_bad:shower_walkin_120": "Walk-in-dusch", + "pack:nextfloor.a_bad:shower_rain_led": "Takdusch med LED", + "pack:nextfloor.a_bad:toilet_close": "Golvstående toalett", + "pack:nextfloor.a_bad:toilet_hung": "Vägghängd toalett", + "pack:nextfloor.a_bad:toilet_hung_compact": "Vägghängd toalett (kompakt)", + "pack:nextfloor.a_bad:bidet": "Bidé", + "pack:nextfloor.a_bad:cabinet_tall": "Högt badrumsskåp", + "pack:nextfloor.a_bad:cabinet_mid": "Halvhögt badrumsskåp", + "pack:nextfloor.a_bad:mirror_round_light": "Rund spegel med belysning", + "pack:nextfloor.a_bad:mirror_80": "Spegel 80 × 60 med belysning", + "pack:nextfloor.a_bad:mirror_led_100": "LED-spegel 100 × 70 med klocka", + "pack:nextfloor.a_bad:mirror_cabinet": "Spegelskåp med belysning", + "pack:nextfloor.a_bad:wall_shelf_bath": "Vägghylla för badrum", + "pack:nextfloor.a_bad:towel_rail": "Handdukshängare med handduk", + "pack:nextfloor.a_bad:towel_radiator": "Handdukstork (radiator)", + "pack:nextfloor.a_bad:towel_heater_electric": "Elektrisk handdukstork", + "pack:nextfloor.a_bad:sauna": "Bastu", + "pack:nextfloor.a_bad:bath_fan": "Badrumsfläkt", + "pack:nextfloor.a_bad:washer_cabinet": "Tvättmaskinsskåp", + "pack:nextfloor.a_bad:washer_under_vanity": "Tvättmaskin under kommoden", + "pack:nextfloor.a_bad:laundry_basket": "Tvättkorg", + "pack:nextfloor.a_bad:laundry_cabinet": "Tvättskåp med korg", + "pack:nextfloor.a_bad:ladder_shelf": "Stegehylla med handdukar", + "pack:nextfloor.a_bad:plant_stool": "Växt på pall", + "packname:nextfloor.a_buero": "Kontor och gaming", + "pack:nextfloor.a_buero:desk_standing": "Höj- och sänkbart skrivbord", + "pack:nextfloor.a_buero:desk_standing_bare": "Höj- och sänkbart skrivbord utan skärm", + "pack:nextfloor.a_buero:chair_gaming": "Gamingstol", + "pack:nextfloor.a_buero:chair_office": "Ergonomisk kontorsstol", + "pack:nextfloor.a_buero:sim_cockpit": "Simracing-cockpit", + "pack:nextfloor.a_buero:server_rack_42u": "Serverrack (42U)", + "pack:nextfloor.a_buero:filing_cabinet": "Arkivskåp", + "pack:nextfloor.a_buero:whiteboard": "Whiteboard", + "pack:nextfloor.a_buero:triple_monitor": "Uppställning med tre skärmar", + "pack:nextfloor.a_buero:bookcase_wall": "Bokhyllevägg", + "pack:nextfloor.a_buero:desk_lamp": "Skrivbordslampa", + "pack:nextfloor.a_buero:desk_lamp_led": "LED-skrivbordslampa", + "pack:nextfloor.a_buero:arcade_cabinet": "Arkadmaskin", + "pack:nextfloor.a_buero:office_lounge_sofa": "Loungesoffa för kontor", + "pack:nextfloor.a_buero:monitor_light_bar": "Skärm med ljuslist", + "pack:nextfloor.a_buero:printer_laser": "Laserskrivare", + "pack:nextfloor.a_buero:wifi_router": "Wi-Fi-router", + "pack:nextfloor.a_buero:phone_booth": "Telefonbås", + "pack:nextfloor.a_buero:printer_3d": "3D-skrivare", + "pack:nextfloor.a_buero:printer_cube": "Sluten kub-3D-skrivare", + "pack:nextfloor.a_buero:printer_multi": "Kub-3D-skrivare med flerfärgsenhet", + "pack:nextfloor.a_buero:printer_large": "Stor 3D-skrivare med dubbla munstycken", + "pack:nextfloor.a_buero:printer_open": "Kompakt öppen 3D-skrivare", + "pack:nextfloor.a_buero:printer_resin": "Harts-3D-skrivare", + "pack:nextfloor.a_buero:filament_dryer": "Filamenttork", + "pack:nextfloor.a_buero:filament_rack": "Väggställ för filament", + "packname:nextfloor.a_fitness": "Träning", + "pack:nextfloor.a_fitness:treadmill": "Löpband", + "pack:nextfloor.a_fitness:power_rack": "Powerrack med bänk", + "pack:nextfloor.a_fitness:rowing_machine": "Roddmaskin", + "pack:nextfloor.a_fitness:spin_bike": "Spinningcykel", + "pack:nextfloor.a_fitness:dumbbell_rack": "Hantelställ", + "pack:nextfloor.a_fitness:punching_bag": "Boxningssäck", + "pack:nextfloor.a_fitness:yoga_mat": "Yogamatta med block", + "pack:nextfloor.a_fitness:elliptical": "Crosstrainer", + "pack:nextfloor.a_fitness:mirror_wall_gym": "Spegelvägg", + "pack:nextfloor.a_fitness:exercise_ball": "Träningsboll", + "pack:nextfloor.a_fitness:wall_bars": "Ribbstol", + "pack:nextfloor.a_fitness:fitness_mirror_smart": "Smart träningsspegel", + "pack:nextfloor.a_fitness:bike_trainer": "Cykel på smart trainer", + "pack:nextfloor.a_fitness:sauna_cabin": "Bastukabin", + "pack:nextfloor.a_fitness:massage_chair": "Massagestol", + "pack:nextfloor.a_fitness:kettlebells": "Kettlebellset", + "pack:nextfloor.a_fitness:water_cooler": "Vattenautomat", + "packname:nextfloor.a_garten": "Trädgård och uteplats", + "pack:nextfloor.a_garten:grill_gas": "Gasgrill", + "pack:nextfloor.a_garten:lounge_set": "Loungegrupp", + "pack:nextfloor.a_garten:sun_lounger_adj": "Solsäng", + "pack:nextfloor.a_garten:parasol": "Parasoll", + "pack:nextfloor.a_garten:pergola": "Pergola", + "pack:nextfloor.a_garten:raised_bed": "Odlingslåda", + "pack:nextfloor.a_garten:greenhouse": "Växthus", + "pack:nextfloor.a_garten:hot_tub": "Utomhusspa", + "pack:nextfloor.a_garten:fire_bowl": "Eldskål", + "pack:nextfloor.a_garten:garden_torch": "Trädgårdsfackla", + "pack:nextfloor.a_garten:play_tower": "Lektorn med rutschkana", + "pack:nextfloor.a_garten:garden_shed": "Trädgårdsbod", + "pack:nextfloor.a_garten:trampoline": "Studsmatta", + "pack:nextfloor.a_garten:flower_pots": "Blomkrukor (set om 3)", + "pack:nextfloor.a_garten:sprinkler": "Gräsmattespridare", + "pack:nextfloor.a_garten:valve_box": "Ventilbox för bevattning", + "pack:nextfloor.a_garten:rain_barrel": "Regntunna", + "pack:nextfloor.a_garten:garden_lantern": "Trädgårdslykta", + "pack:nextfloor.a_garten:outdoor_kitchen": "Utekök", + "pack:nextfloor.a_garten:hammock": "Hängmatta med ställning", + "pack:nextfloor.a_garten:patio_heater": "Terrassvärmare", + "pack:nextfloor.a_garten:tree_oak": "Ek", + "pack:nextfloor.a_garten:tree_lime": "Lind", + "pack:nextfloor.a_garten:tree_birch": "Björk", + "pack:nextfloor.a_garten:tree_maple": "Lönn", + "pack:nextfloor.a_garten:tree_fruit": "Fruktträd", + "pack:nextfloor.a_garten:tree_spruce": "Gran", + "pack:nextfloor.a_garten:tree_pine": "Tall", + "pack:nextfloor.a_garten:tree_thuja": "Tuja", + "pack:nextfloor.a_garten:shrub": "Buske", + "pack:nextfloor.a_garten:shrub_flowering": "Blommande buske", + "pack:nextfloor.a_garten:brush_wild": "Sly (vildvuxen yta)", + "pack:nextfloor.a_garten:tree_group_3": "Trädgrupp (3)", + "pack:nextfloor.a_garten:bin_rest_120": "Restavfallskärl 120 l", + "pack:nextfloor.a_garten:bin_rest_240": "Restavfallskärl 240 l", + "pack:nextfloor.a_garten:bin_bio_120": "Matavfallskärl 120 l", + "pack:nextfloor.a_garten:bin_bio_240": "Matavfallskärl 240 l", + "pack:nextfloor.a_garten:bin_paper_120": "Papperskärl 120 l", + "pack:nextfloor.a_garten:bin_paper_240": "Papperskärl 240 l", + "pack:nextfloor.a_garten:bin_yellow_120": "Återvinningskärl 120 l", + "pack:nextfloor.a_garten:bin_yellow_240": "Återvinningskärl 240 l", + "pack:nextfloor.a_garten:mailbox": "Brevlåda", + "pack:nextfloor.a_garten:mailbox_post": "Brevlåda på stolpe", + "pack:nextfloor.a_garten:awning_300": "Markis 3 m", + "pack:nextfloor.a_garten:awning_400": "Markis 4 m", + "pack:nextfloor.a_garten:awning_500": "Markis 5 m", + "pack:nextfloor.a_garten:sliding_gate": "Skjutgrind", + "packname:nextfloor.a_haustechnik": "Hushåll och installationer", + "pack:nextfloor.a_haustechnik:gas_boiler": "Gaskondenserande panna", + "pack:nextfloor.a_haustechnik:heat_pump_tower": "Värmepump inomhusenhet (hydrotorn)", + "pack:nextfloor.a_haustechnik:buffer_tank": "Ackumulatortank", + "pack:nextfloor.a_haustechnik:heating_manifold": "Golvvärmefördelare", + "pack:nextfloor.a_haustechnik:ventilation_unit": "Ventilation med värmeåtervinning", + "pack:nextfloor.a_haustechnik:split_indoor": "Split-luftkonditionering (inomhusenhet, vägg)", + "pack:nextfloor.a_haustechnik:split_outdoor": "Split-luftkonditionering (utomhusenhet)", + "pack:nextfloor.a_haustechnik:radiator_tall": "Hög designradiator", + "pack:nextfloor.a_haustechnik:meter_cabinet": "Mätarskåp", + "pack:nextfloor.a_haustechnik:water_softener": "Vattenavhärdare", + "pack:nextfloor.a_haustechnik:water_pump": "Hydropump", + "pack:nextfloor.a_haustechnik:drip_tray": "Droppskydd med läckagesensor", + "pack:nextfloor.a_haustechnik:chest_freezer": "Frysbox", + "pack:nextfloor.a_haustechnik:ironing_station": "Ångstrykstation", + "pack:nextfloor.a_haustechnik:drying_rack": "Torkställning", + "pack:nextfloor.a_haustechnik:rotary_line": "Tvättkarusell", + "pack:nextfloor.a_haustechnik:pantry_shelf_util": "Skafferihylla", + "pack:nextfloor.a_haustechnik:utility_sink": "Grovdiskho", + "pack:nextfloor.a_haustechnik:laundry_basket_util": "Tvättkorg", + "pack:nextfloor.a_haustechnik:vacuum_station": "Station för sladdlös dammsugare", + "packname:nextfloor.a_haustiere": "Husdjur", + "pack:nextfloor.a_haustiere:cat_tree_large": "Klösträd (stort)", + "pack:nextfloor.a_haustiere:scratch_post": "Klöspelare", + "pack:nextfloor.a_haustiere:scratch_board_wall": "Klösbräda (vägg)", + "pack:nextfloor.a_haustiere:cat_cave": "Kattgrotta", + "pack:nextfloor.a_haustiere:cat_bed_round": "Rund kattbädd", + "pack:nextfloor.a_haustiere:cat_wall_shelf": "Vägghylla för katt", + "pack:nextfloor.a_haustiere:cat_steps": "Klättersteg för katt", + "pack:nextfloor.a_haustiere:litter_covered": "Täckt kattlåda", + "pack:nextfloor.a_haustiere:litter_auto": "Självrengörande kattlåda", + "pack:nextfloor.a_haustiere:dog_bed": "Hundbädd", + "pack:nextfloor.a_haustiere:dog_basket": "Hundkorg", + "pack:nextfloor.a_haustiere:dog_house": "Hundkoja", + "pack:nextfloor.a_haustiere:pet_bowls": "Mat- och vattenskålar", + "pack:nextfloor.a_haustiere:pet_feeder": "Automatisk foderautomat", + "pack:nextfloor.a_haustiere:pet_fountain": "Vattenfontän för husdjur", + "pack:nextfloor.a_haustiere:pet_gate": "Husdjursgrind", + "pack:nextfloor.a_haustiere:pet_stairs": "Husdjurstrappa", + "pack:nextfloor.a_haustiere:hamster_cage": "Hamsterbur", + "pack:nextfloor.a_haustiere:small_animal_cage": "Bur för smådjur", + "pack:nextfloor.a_haustiere:rabbit_run": "Kaninhage (ute)", + "pack:nextfloor.a_haustiere:bird_cage": "Fågelbur", + "pack:nextfloor.a_haustiere:aquarium_100": "Akvarium 100 l", + "pack:nextfloor.a_haustiere:aquarium_240": "Akvarium 240 l med skåp", + "pack:nextfloor.a_haustiere:terrarium": "Terrarium", + "pack:nextfloor.a_haustiere:pet_cat": "Katt (strövar omkring)", + "pack:nextfloor.a_haustiere:pet_dog": "Hund (strövar omkring)", + "pack:nextfloor.a_haustiere:pet_rabbit": "Kanin (skuttar omkring)", + "packname:nextfloor.a_kinderzimmer": "Barnrum", + "pack:nextfloor.a_kinderzimmer:loft_bed_slide": "Loftsäng med rutschkana", + "pack:nextfloor.a_kinderzimmer:teepee": "Tipi", + "pack:nextfloor.a_kinderzimmer:play_kitchen": "Leksakskök", + "pack:nextfloor.a_kinderzimmer:kids_desk": "Barnskrivbord", + "pack:nextfloor.a_kinderzimmer:toy_shelf": "Leksakshylla med lådor", + "pack:nextfloor.a_kinderzimmer:cosy_corner": "Mysig hörna", + "pack:nextfloor.a_kinderzimmer:rocking_horse": "Gunghäst", + "pack:nextfloor.a_kinderzimmer:play_mat_road": "Bilmatta", + "pack:nextfloor.a_kinderzimmer:kids_table_2": "Barnbord med 2 stolar", + "pack:nextfloor.a_kinderzimmer:moon_light": "Nattlampa måne", + "pack:nextfloor.a_kinderzimmer:ball_pit": "Bollhav", + "pack:nextfloor.a_kinderzimmer:house_bed": "Hussäng", + "pack:nextfloor.a_kinderzimmer:baby_monitor": "Babyvakt med kamera", + "pack:nextfloor.a_kinderzimmer:star_projector": "Stjärnprojektor", + "pack:nextfloor.a_kinderzimmer:kids_cot": "Babysäng", + "pack:nextfloor.a_kinderzimmer:kids_changing_table": "Skötbord", + "pack:nextfloor.a_kinderzimmer:kids_wardrobe": "Barngarderob", + "pack:nextfloor.a_kinderzimmer:toy_boxes_3": "Leksakslådor (3)", + "packname:nextfloor.a_kino": "Hemmabio och hifi", + "pack:nextfloor.a_kino:screen_wall": "Projektorduk (vägg)", + "pack:nextfloor.a_kino:screen_roll": "Rullbar projektorduk", + "pack:nextfloor.a_kino:projector_ceiling": "Projektor (tak)", + "pack:nextfloor.a_kino:projector_table": "Projektor (bord)", + "pack:nextfloor.a_kino:speaker_floor": "Golvhögtalare", + "pack:nextfloor.a_kino:speaker_shelf": "Stativhögtalare", + "pack:nextfloor.a_kino:speaker_centre": "Centerhögtalare", + "pack:nextfloor.a_kino:subwoofer": "Subwoofer", + "pack:nextfloor.a_kino:soundbar": "Soundbar", + "pack:nextfloor.a_kino:soundbar_premium": "Premium-soundbar", + "pack:nextfloor.a_kino:speaker_wall": "Vägghögtalare", + "pack:nextfloor.a_kino:speaker_ceiling": "Takhögtalare", + "pack:nextfloor.a_kino:av_receiver": "AV-receiver", + "pack:nextfloor.a_kino:turntable": "Skivspelare", + "pack:nextfloor.a_kino:record_shelf": "Skivhylla", + "pack:nextfloor.a_kino:game_console": "Spelkonsol", + "pack:nextfloor.a_kino:hifi_rack": "Hifi-bänk", + "pack:nextfloor.a_kino:cinema_seat": "Biofåtölj", + "pack:nextfloor.a_kino:cinema_row_3": "Rad biofåtöljer (3)", + "pack:nextfloor.a_kino:acoustic_panel": "Akustikpanel", + "pack:nextfloor.a_kino:bass_trap": "Basfälla (hörn)", + "pack:nextfloor.a_kino:popcorn_maker": "Popcornmaskin", + "pack:nextfloor.a_kino:star_ceiling": "Stjärnhimmel", + "pack:nextfloor.a_kino:smart_speaker_ball": "Smart högtalare (klot)", + "pack:nextfloor.a_kino:smart_speaker_cylinder": "Smart högtalare (cylinder)", + "pack:nextfloor.a_kino:smart_speaker_puck": "Smart högtalare (puck)", + "pack:nextfloor.a_kino:smart_speaker_pod": "Smart högtalare (pod)", + "pack:nextfloor.a_kino:smart_speaker_tall": "Smart högtalare (hög)", + "pack:nextfloor.a_kino:smart_speaker_oval": "Smart högtalare (oval)", + "pack:nextfloor.a_kino:multiroom_compact": "Kompakt multiroom-högtalare", + "pack:nextfloor.a_kino:speaker_portable": "Bärbar högtalare", + "pack:nextfloor.a_kino:display_5": "Smart skärm 5″", + "pack:nextfloor.a_kino:display_8": "Smart skärm 8″", + "pack:nextfloor.a_kino:display_7_float": "Smart skärm 7″ (svävande)", + "pack:nextfloor.a_kino:display_15_wall": "Smart skärm 15″ (vägg)", + "pack:nextfloor.a_kino:speaker_stand": "Högtalarstativ", + "packname:nextfloor.a_kueche": "Kök", + "pack:nextfloor.a_kueche:base_30": "Bänkskåp 30", + "pack:nextfloor.a_kueche:base_40": "Bänkskåp 40", + "pack:nextfloor.a_kueche:base_50": "Bänkskåp 50", + "pack:nextfloor.a_kueche:base_60": "Bänkskåp 60", + "pack:nextfloor.a_kueche:base_80": "Bänkskåp 80", + "pack:nextfloor.a_kueche:base_90": "Bänkskåp 90", + "pack:nextfloor.a_kueche:base_100": "Bänkskåp 100", + "pack:nextfloor.a_kueche:base_120": "Bänkskåp 120", + "pack:nextfloor.a_kueche:drawer_40": "Lådskåp 40", + "pack:nextfloor.a_kueche:drawer_50": "Lådskåp 50", + "pack:nextfloor.a_kueche:drawer_60": "Lådskåp 60", + "pack:nextfloor.a_kueche:drawer_80": "Lådskåp 80", + "pack:nextfloor.a_kueche:drawer_90": "Lådskåp 90", + "pack:nextfloor.a_kueche:drawer_100": "Lådskåp 100", + "pack:nextfloor.a_kueche:drawer_120": "Lådskåp 120", + "pack:nextfloor.a_kueche:sink_60": "Diskbänksskåp 60", + "pack:nextfloor.a_kueche:sink_80": "Diskbänksskåp 80", + "pack:nextfloor.a_kueche:sink_100": "Diskbänksskåp 100", + "pack:nextfloor.a_kueche:hob_60": "Hällskåp 60", + "pack:nextfloor.a_kueche:hob_80": "Hällskåp 80", + "pack:nextfloor.a_kueche:cooker_60": "Spis med ugn 60", + "pack:nextfloor.a_kueche:dishwasher_60": "Inbyggd diskmaskin 60", + "pack:nextfloor.a_kueche:dishwasher_45": "Inbyggd diskmaskin 45", + "pack:nextfloor.a_kueche:base_corner": "Hörnbänkskåp", + "pack:nextfloor.a_kueche:wall_40": "Väggskåp 40", + "pack:nextfloor.a_kueche:wall_50": "Väggskåp 50", + "pack:nextfloor.a_kueche:wall_60": "Väggskåp 60", + "pack:nextfloor.a_kueche:wall_80": "Väggskåp 80", + "pack:nextfloor.a_kueche:wall_90": "Väggskåp 90", + "pack:nextfloor.a_kueche:wall_100": "Väggskåp 100", + "pack:nextfloor.a_kueche:wall_120": "Väggskåp 120", + "pack:nextfloor.a_kueche:wall_glass_80": "Vitrinväggskåp 80", + "pack:nextfloor.a_kueche:wall_corner": "Hörnväggskåp", + "pack:nextfloor.a_kueche:hood_wall": "Väggfläkt", + "pack:nextfloor.a_kueche:hood_island": "Köksöfläkt", + "pack:nextfloor.a_kueche:tall_pantry": "Högskåp skafferi", + "pack:nextfloor.a_kueche:tall_oven": "Högskåp ugn och mikro", + "pack:nextfloor.a_kueche:tall_fridge": "Högskåp kyl-frys", + "pack:nextfloor.a_kueche:tall_steam": "Högskåp ånga och ugn", + "pack:nextfloor.a_kueche:fridge_freezer": "Kyl-frys", + "pack:nextfloor.a_kueche:fridge_french": "French door-kylskåp", + "pack:nextfloor.a_kueche:wine_fridge": "Vinkyl", + "pack:nextfloor.a_kueche:glass_cabinet": "Vitrinskåp", + "pack:nextfloor.a_kueche:row_270": "Köksrad 270", + "pack:nextfloor.a_kueche:row_330": "Köksrad 330", + "pack:nextfloor.a_kueche:island_bar": "Köksö med bar", + "pack:nextfloor.a_kueche:island_hob": "Köksö med häll", + "pack:nextfloor.a_kueche:breakfast_bar": "Frukostbar (vägg)", + "pack:nextfloor.a_kueche:bar_stools_2": "Barstolar (set om 2)", + "pack:nextfloor.a_kueche:dining_bench_long": "Långt matbord med bänk", + "pack:nextfloor.a_kueche:dining_round_4": "Runt matbord med 4 stolar", + "pack:nextfloor.a_kueche:high_table_2": "Barbord med 2 pallar", + "pack:nextfloor.a_kueche:kitchen_trolley": "Köksvagn", + "pack:nextfloor.a_kueche:pantry_shelf": "Skafferihylla", + "pack:nextfloor.a_kueche:spice_rack": "Kryddhylla (vägg)", + "pack:nextfloor.a_kueche:coffee_machine": "Helautomatisk kaffemaskin", + "pack:nextfloor.a_kueche:microwave": "Mikrovågsugn", + "pack:nextfloor.a_kueche:stand_mixer": "Köksmaskin", + "pack:nextfloor.a_kueche:kettle": "Vattenkokare", + "pack:nextfloor.a_kueche:toaster": "Brödrost", + "pack:nextfloor.a_kueche:herb_garden": "Smart örtträdgård", + "pack:nextfloor.a_kueche:pendant_trio": "Trio pendellampor", + "pack:nextfloor.a_kueche:pendant_linear": "Linjär pendellampa", + "pack:nextfloor.a_kueche:cabinet_light_60": "LED-bänkbelysning 60", + "pack:nextfloor.a_kueche:cabinet_light_80": "LED-bänkbelysning 80", + "pack:nextfloor.a_kueche:range_cooker_90": "Stor spis 90", + "packname:nextfloor.a_schlafzimmer": "Sovrum", + "pack:nextfloor.a_schlafzimmer:bed_90": "Säng 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_140": "Säng 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_160": "Säng 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_180": "Säng 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_200": "Säng 200 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_180": "Stoppad säng 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_upholstered_140": "Stoppad säng 140 × 200", + "pack:nextfloor.a_schlafzimmer:bed_boxspring": "Kontinentalsäng 180 × 200", + "pack:nextfloor.a_schlafzimmer:bed_futon": "Futonsäng 160 × 200", + "pack:nextfloor.a_schlafzimmer:bed_storage": "Säng med förvaring 90 × 200", + "pack:nextfloor.a_schlafzimmer:bed_canopy": "Himmelsäng", + "pack:nextfloor.a_schlafzimmer:bed_ambient": "Säng 180 med stämningsljus", + "pack:nextfloor.a_schlafzimmer:bed_bench": "Sängbänk", + "pack:nextfloor.a_schlafzimmer:shoe_bench": "Skobänk", + "pack:nextfloor.a_schlafzimmer:wardrobe_2": "Garderob med 2 dörrar", + "pack:nextfloor.a_schlafzimmer:wardrobe_3": "Garderob med 3 dörrar", + "pack:nextfloor.a_schlafzimmer:wardrobe_4": "Garderob med 4 dörrar", + "pack:nextfloor.a_schlafzimmer:wardrobe_6": "Garderob med 6 dörrar", + "pack:nextfloor.a_schlafzimmer:wardrobe_mirror": "Garderob med spegeldörr", + "pack:nextfloor.a_schlafzimmer:wardrobe_sliding": "Garderob med skjutdörrar", + "pack:nextfloor.a_schlafzimmer:wardrobe_light": "Garderob med invändig belysning", + "pack:nextfloor.a_schlafzimmer:wardrobe_corner": "Hörngarderob", + "pack:nextfloor.a_schlafzimmer:walk_in_closet": "Öppen walk-in-closet", + "pack:nextfloor.a_schlafzimmer:clothes_rail": "Klädställning", + "pack:nextfloor.a_schlafzimmer:nightstand": "Nattduksbord med låda", + "pack:nextfloor.a_schlafzimmer:nightstand_slim": "Smalt nattduksbord", + "pack:nextfloor.a_schlafzimmer:nightstand_floating": "Svävande nattduksbord", + "pack:nextfloor.a_schlafzimmer:dresser_6": "Byrå med 6 lådor 140", + "pack:nextfloor.a_schlafzimmer:chest_tall_5": "Hög byrå med 5 lådor", + "pack:nextfloor.a_schlafzimmer:chest_tall": "Hög byrå", + "pack:nextfloor.a_schlafzimmer:chest_80": "Byrå med 3 lådor 80", + "pack:nextfloor.a_schlafzimmer:vanity_table": "Sminkbord med spegel", + "pack:nextfloor.a_schlafzimmer:dressing_table_light": "Sminkbord med spegelbelysning", + "pack:nextfloor.a_schlafzimmer:cot": "Babysäng", + "pack:nextfloor.a_schlafzimmer:changing_table": "Skötbord", + "pack:nextfloor.a_schlafzimmer:standing_mirror": "Golvspegel", + "pack:nextfloor.a_schlafzimmer:reading_nook": "Läshörna med fåtölj", + "pack:nextfloor.a_schlafzimmer:bedside_lamp": "Sänglampa", + "pack:nextfloor.a_schlafzimmer:touch_lamp": "Touch-sänglampa", + "pack:nextfloor.a_schlafzimmer:humidifier": "Luftfuktare", + "pack:nextfloor.a_schlafzimmer:sunrise_clock": "Väckarklocka med gryningsljus", + "packname:nextfloor.a_smart": "Smart hem och teknik", + "pack:nextfloor.a_smart:wallbox": "Laddbox", + "pack:nextfloor.a_smart:electric_car": "Elbil", + "pack:nextfloor.a_smart:heat_pump_outdoor": "Värmepump (utomhusenhet)", + "pack:nextfloor.a_smart:home_battery": "Hembatteri", + "pack:nextfloor.a_smart:inverter_solar": "Solcellsväxelriktare", + "pack:nextfloor.a_smart:robot_vacuum": "Robotdammsugare med docka", + "pack:nextfloor.a_smart:mower_garage": "Robotgräsklippare med garage", + "pack:nextfloor.a_smart:washer_dryer_stack": "Tvätt- och torkpelare", + "pack:nextfloor.a_smart:network_rack": "Nätverksrack", + "pack:nextfloor.a_smart:smart_display": "Smart skärm", + "pack:nextfloor.a_smart:solar_balcony": "Balkongsolpanel", + "pack:nextfloor.a_smart:fuse_box": "Elcentral", + "pack:nextfloor.a_smart:nas_server": "NAS-server", + "pack:nextfloor.a_smart:hot_water_tank": "Varmvattenberedare", + "pack:nextfloor.a_smart:light_pillar": "Ljuspelare med färgövergång", + "pack:nextfloor.a_smart:light_bars_tv": "Par ljuslister (TV)", + "pack:nextfloor.a_smart:orb_lamp": "Lysande klotbordslampa", + "pack:nextfloor.a_smart:glow_lamp_portable": "Bärbar lysande lampa", + "pack:nextfloor.a_smart:mood_spot": "Stämningsspot för bord", + "pack:nextfloor.a_smart:cube_lamp": "Kublampa", + "pack:nextfloor.a_smart:ceiling_panel_round": "Rund takpanel", + "pack:nextfloor.a_smart:garden_spots_3": "Trädgårdsspotar (set om 3)", + "pack:nextfloor.a_smart:wall_light_updown": "Utevägglampa upp och ner", + "pack:nextfloor.a_smart:siren_strobe": "Siren med blixtljus", + "pack:nextfloor.a_smart:access_point": "Wi-Fi-accesspunkt (tak)", + "pack:nextfloor.a_smart:smoke_detector": "Brandvarnare", + "pack:nextfloor.a_smart:thermostat_wall": "Väggtermostat", + "pack:nextfloor.a_smart:dehumidifier": "Avfuktare", + "pack:nextfloor.a_smart:ceiling_fan": "Takfläkt", + "pack:nextfloor.a_smart:ceiling_fan_light": "Takfläkt med belysning", + "pack:nextfloor.a_smart:light_switch_1": "Ljusströmbrytare, 1-pol", + "pack:nextfloor.a_smart:socket_1": "Uttag, enkelt", + "pack:nextfloor.a_smart:light_switch_2": "Ljusströmbrytare, 2-pol", + "pack:nextfloor.a_smart:socket_2": "Uttag, dubbelt", + "pack:nextfloor.a_smart:light_switch_3": "Ljusströmbrytare, 3-pol", + "pack:nextfloor.a_smart:socket_3": "Uttag, trippel", + "pack:nextfloor.a_smart:light_switch_4": "Ljusströmbrytare, 4-pol", + "pack:nextfloor.a_smart:socket_4": "Uttag, fyrdubbelt", + "pack:nextfloor.a_smart:socket_outdoor": "Utomhusuttag med lock", + "packname:nextfloor.a_wohnzimmer": "Vardagsrum", + "pack:nextfloor.a_wohnzimmer:sofa_2": "2-sitssoffa", + "pack:nextfloor.a_wohnzimmer:sofa_3": "3-sitssoffa", + "pack:nextfloor.a_wohnzimmer:sofa_4": "Stor 4-sitssoffa", + "pack:nextfloor.a_wohnzimmer:sofa_velvet": "Sammets-3-sitssoffa", + "pack:nextfloor.a_wohnzimmer:sofa_armless": "Soffa utan armstöd", + "pack:nextfloor.a_wohnzimmer:sofa_chaise": "Soffa med schäslong", + "pack:nextfloor.a_wohnzimmer:sofa_chesterfield": "Chesterfieldsoffa", + "pack:nextfloor.a_wohnzimmer:sofa_bed": "Bäddsoffa", + "pack:nextfloor.a_wohnzimmer:sofa_corner_l": "Hörnsoffa (vänster)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_r": "Hörnsoffa (höger)", + "pack:nextfloor.a_wohnzimmer:sofa_corner_xl": "Stor hörnsoffa (L-form)", + "pack:nextfloor.a_wohnzimmer:sofa_u": "U-soffa", + "pack:nextfloor.a_wohnzimmer:chaise_longue": "Schäslong", + "pack:nextfloor.a_wohnzimmer:modular_sofa": "Modulsoffa (5 delar)", + "pack:nextfloor.a_wohnzimmer:armchair": "Fåtölj", + "pack:nextfloor.a_wohnzimmer:club_chair": "Klubbfåtölj", + "pack:nextfloor.a_wohnzimmer:wingback": "Öronlappsfåtölj", + "pack:nextfloor.a_wohnzimmer:cocktail_chair": "Cocktailstol", + "pack:nextfloor.a_wohnzimmer:recliner": "Vilfåtölj med fotpall", + "pack:nextfloor.a_wohnzimmer:bean_bag": "Sittsäck", + "pack:nextfloor.a_wohnzimmer:pouf": "Puff", + "pack:nextfloor.a_wohnzimmer:rocking_chair": "Gungstol", + "pack:nextfloor.a_wohnzimmer:coffee_rect": "Rektangulärt soffbord", + "pack:nextfloor.a_wohnzimmer:coffee_glass": "Soffbord i glas", + "pack:nextfloor.a_wohnzimmer:coffee_round": "Runt soffbord", + "pack:nextfloor.a_wohnzimmer:coffee_nesting": "Satsbord", + "pack:nextfloor.a_wohnzimmer:side_round": "Runt sidobord", + "pack:nextfloor.a_wohnzimmer:console": "Avlastningsbord", + "pack:nextfloor.a_wohnzimmer:dining_120": "Matbord 120 × 90", + "pack:nextfloor.a_wohnzimmer:dining_160": "Matbord 160 × 90", + "pack:nextfloor.a_wohnzimmer:dining_200": "Matbord 200 × 90", + "pack:nextfloor.a_wohnzimmer:dining_220": "Matbord i massivt trä 220 × 100", + "pack:nextfloor.a_wohnzimmer:chair_wood": "Trästol", + "pack:nextfloor.a_wohnzimmer:chair_upholstered": "Klädd stol", + "pack:nextfloor.a_wohnzimmer:chair_shell": "Skalstol", + "pack:nextfloor.a_wohnzimmer:dining_bench": "Matbänk 160", + "pack:nextfloor.a_wohnzimmer:lowboard_120": "Lågt sideboard 120", + "pack:nextfloor.a_wohnzimmer:lowboard_160": "Lågt sideboard 160", + "pack:nextfloor.a_wohnzimmer:lowboard_200": "Lågt sideboard 200", + "pack:nextfloor.a_wohnzimmer:sideboard_160": "Skänk 160", + "pack:nextfloor.a_wohnzimmer:highboard": "Högskänk", + "pack:nextfloor.a_wohnzimmer:display_cabinet": "Vitrinskåp", + "pack:nextfloor.a_wohnzimmer:chest_3": "Byrå med 3 lådor", + "pack:nextfloor.a_wohnzimmer:bookshelf_tall": "Hög bokhylla", + "pack:nextfloor.a_wohnzimmer:bookshelf_wide": "Bred bokhylla", + "pack:nextfloor.a_wohnzimmer:cube_2x2": "Kubhylla 2 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x2": "Kubhylla 4 × 2", + "pack:nextfloor.a_wohnzimmer:cube_4x4": "Kubhylla 4 × 4", + "pack:nextfloor.a_wohnzimmer:divider_open": "Rumsavdelande hylla", + "pack:nextfloor.a_wohnzimmer:wall_shelf": "Svävande vägghylla", + "pack:nextfloor.a_wohnzimmer:coat_stand": "Klädhängare (stående)", + "pack:nextfloor.a_wohnzimmer:wall_unit_vitrines": "Vägghylla med vitriner", + "pack:nextfloor.a_wohnzimmer:wall_unit_tv": "Vägghylla med TV", + "pack:nextfloor.a_wohnzimmer:tv_on_stand": "TV på stativ", + "pack:nextfloor.a_wohnzimmer:media_wall": "Mediavägg med TV", + "pack:nextfloor.a_wohnzimmer:wood_stove": "Kamin", + "pack:nextfloor.a_wohnzimmer:fireplace_wall": "Elektrisk väggbrasa", + "pack:nextfloor.a_wohnzimmer:piano": "Piano med pall", + "pack:nextfloor.a_wohnzimmer:floor_lamp_arc": "Båglampa", + "pack:nextfloor.a_wohnzimmer:floor_lamp_tripod": "Golvlampa med trebent stativ", + "pack:nextfloor.a_wohnzimmer:table_lamp_ceramic": "Bordslampa i keramik", + "pack:nextfloor.a_wohnzimmer:vase_pampas": "Golvvas med pampasgräs", + "pack:nextfloor.a_wohnzimmer:monstera": "Stor monstera", + "pack:nextfloor.a_wohnzimmer:rug_round": "Rund matta", + "pack:nextfloor.a_wohnzimmer:rug_240": "Matta 240 × 170", + "pack:nextfloor.a_wohnzimmer:painting_light": "Tavla med tavelbelysning", + "pack:nextfloor.a_wohnzimmer:shelf_led": "Hylla med LED-hyllplan", + "pack:nextfloor.a_wohnzimmer:air_purifier": "Luftrenare", + "pack:nextfloor.a_wohnzimmer:tower_fan": "Pelarfläkt", + "pack:nextfloor.a_wohnzimmer:smart_speaker_living": "Smart högtalare", + "packname:nextfloor.ausbau": "Arkitektur och inredning", + "pack:nextfloor.ausbau:column_round": "Rund pelare", + "pack:nextfloor.ausbau:column_square": "Fyrkantig pelare", + "pack:nextfloor.ausbau:beam": "Takbjälke", + "pack:nextfloor.ausbau:chimney": "Skorstensstock", + "pack:nextfloor.ausbau:glass_wall": "Glasvägg", + "pack:nextfloor.ausbau:sliding_wall": "Skjutvägg", + "pack:nextfloor.ausbau:platform": "Podium", + "pack:nextfloor.ausbau:half_wall": "Halvvägg", + "pack:nextfloor.ausbau:divider_shelf": "Avdelande hylla", + "pack:nextfloor.ausbau:pilaster": "Pilaster", + "pack:nextfloor.ausbau:column_steel": "Stålpelare", + "pack:nextfloor.ausbau:beams_wood_5": "Träbjälkar i taket (5)", + "pack:nextfloor.ausbau:beam_downstand": "Nedhängd balk", + "pack:nextfloor.ausbau:fireplace_builtin": "Inbyggd öppen spis", + "pack:nextfloor.ausbau:divider_slats": "Rumsavdelare med ribbor", + "pack:nextfloor.ausbau:curtain_motor": "Motoriserad gardin", + "pack:nextfloor.ausbau:niche_shelf": "Inbyggd hylla (nisch)", + "pack:nextfloor.ausbau:niche_led": "LED-nisch", + "pack:nextfloor.ausbau:light_cove": "Ljusvoute (tak)", + "pack:nextfloor.ausbau:gallery_rail_glass": "Galleriräcke (glas)", + "pack:nextfloor.ausbau:window_seat": "Fönstersittplats", + "pack:nextfloor.ausbau:curtain_pair": "Gardin (öppnas åt båda håll)", + "pack:nextfloor.ausbau:roller_blind_inside": "Rullgardin (inne)", + "packname:nextfloor.bad": "Badrum extra", + "pack:nextfloor.bad:double_vanity": "Dubbelkommod", + "pack:nextfloor.bad:walkin_shower": "Walk-in-dusch", + "pack:nextfloor.bad:towel_radiator": "Handdukstork (radiator)", + "pack:nextfloor.bad:mirror_cabinet": "Spegelskåp med belysning", + "pack:nextfloor.bad:washer_tower": "Tvätt- och torkpelare", + "pack:nextfloor.bad:laundry_basket": "Tvättkorg", + "pack:nextfloor.bad:bath_shelf": "Badrumshylla", + "packname:nextfloor.energie": "Energi och installationer", + "pack:nextfloor.energie:heat_pump": "Värmepump (utomhusenhet)", + "pack:nextfloor.energie:pellet_boiler": "Pelletspanna", + "pack:nextfloor.energie:buffer_tank": "Ackumulatortank", + "pack:nextfloor.energie:hot_water_tank": "Varmvattenberedare", + "pack:nextfloor.energie:home_battery": "Hembatteri (torn)", + "pack:nextfloor.energie:inverter": "Växelriktare", + "pack:nextfloor.energie:wallbox": "Laddbox", + "pack:nextfloor.energie:meter_cabinet": "Mätarskåp", + "pack:nextfloor.energie:ventilation": "Ventilationsaggregat", + "pack:nextfloor.energie:solar_carport_pillar": "Stolpe för solcellscarport", + "packname:nextfloor.fahrzeuge": "Fordon", + "pack:nextfloor.fahrzeuge:tesla_model_s": "Tesla Model S", + "packname:nextfloor.a_saison": "Säsong & dekoration", + "packname:nextfloor.a_smart2": "Smart hem 2", + "packname:nextfloor.a_haustechnik2": "Installationer 2", + "packname:nextfloor.a_wellness": "Spa & wellness", + "packname:nextfloor.a_garten2": "Trädgård 2", + "packname:nextfloor.a_kueche2": "Kök 2", + "packname:nextfloor.a_fahrzeuge2": "Fordon 2", + "packname:nextfloor.a_aussenkueche": "Utekök & terrass", + "packname:nextfloor.a_werkstatt2": "Verkstad 2", + "packname:nextfloor.a_japandi": "Japandi & skandinaviskt", + "packname:nextfloor.a_loft": "Loft & industriellt", + "packname:nextfloor.a_gruen": "Inomhusgrönt", + "packname:nextfloor.a_musik": "Musik & ateljé", + "pack:nextfloor.a_saison:xmas_tree": "Julgran med ljusslinga", + "pack:nextfloor.a_saison:advent_wreath": "Adventsljusstake", + "pack:nextfloor.a_saison:lights_outdoor": "Ljusslinga utomhus", + "pack:nextfloor.a_saison:window_star": "Adventsstjärna", + "pack:nextfloor.a_saison:candle_arch": "Ljusstake (båge)", + "pack:nextfloor.a_saison:reindeer_light": "Ljusren", + "pack:nextfloor.a_saison:pumpkin": "Pumpa", + "pack:nextfloor.a_saison:pumpkin_lantern": "Pumpalykta", + "pack:nextfloor.a_saison:easter_tree": "Påskris", + "pack:nextfloor.a_saison:snowman": "Snögubbe", + "pack:nextfloor.a_saison:gift_pile": "Julklappar", + "pack:nextfloor.a_smart2:siren": "Siren", + "pack:nextfloor.a_smart2:access_point": "Wi-Fi-åtkomstpunkt", + "pack:nextfloor.a_smart2:access_point_wall": "Wi-Fi-åtkomstpunkt (vägg)", + "pack:nextfloor.a_smart2:smoke_detector": "Brandvarnare", + "pack:nextfloor.a_smart2:co_detector": "Kolmonoxidvarnare", + "pack:nextfloor.a_smart2:dehumidifier": "Avfuktare", + "pack:nextfloor.a_smart2:cube_lamp": "Kublampa", + "pack:nextfloor.a_smart2:presence_ceiling": "Närvarosensor (tak)", + "pack:nextfloor.a_smart2:water_leak": "Vattenläckagesensor", + "pack:nextfloor.a_smart2:air_quality": "Luftkvalitetsmätare", + "pack:nextfloor.a_smart2:doorbell_cam": "Videodörrklocka", + "pack:nextfloor.a_haustechnik2:water_tank": "Vattentank", + "pack:nextfloor.a_haustechnik2:oil_tank": "Oljetank", + "pack:nextfloor.a_haustechnik2:oil_boiler": "Oljepanna", + "pack:nextfloor.a_haustechnik2:water_softener": "Avhärdare", + "pack:nextfloor.a_haustechnik2:buffer_tank": "Ackumulatortank", + "pack:nextfloor.a_haustechnik2:cistern": "Regnvattentank", + "pack:nextfloor.a_haustechnik2:ventilation_unit": "Ventilationsaggregat", + "pack:nextfloor.a_haustechnik2:expansion_vessel": "Expansionskärl", + "pack:nextfloor.a_haustechnik2:heat_pump_indoor": "Värmepump (inomhusdel)", + "pack:nextfloor.a_wellness:sauna_cabin": "Bastu", + "pack:nextfloor.a_wellness:sauna_barrel": "Tunnbastu", + "pack:nextfloor.a_wellness:infrared_cabin": "IR-bastu", + "pack:nextfloor.a_wellness:hot_tub": "Bubbelpool", + "pack:nextfloor.a_wellness:plunge_pool": "Kallbad", + "pack:nextfloor.a_wellness:steam_shower": "Ångdusch", + "pack:nextfloor.a_wellness:relax_lounger": "Vilstol", + "pack:nextfloor.a_wellness:cold_bath": "Isbad", + "pack:nextfloor.a_garten2:water_feature": "Fontän med ljus", + "pack:nextfloor.a_garten2:pond": "Damm med pump", + "pack:nextfloor.a_garten2:robot_mower": "Robotgräsklippare", + "pack:nextfloor.a_garten2:mower_dock": "Laddstation robotklippare", + "pack:nextfloor.a_garten2:sandbox": "Sandlåda", + "pack:nextfloor.a_garten2:beach_chair": "Strandkorg", + "pack:nextfloor.a_garten2:wood_pile": "Vedtrave", + "pack:nextfloor.a_garten2:bird_house": "Fågelholk", + "pack:nextfloor.a_garten2:raised_bed": "Pallkrage", + "pack:nextfloor.a_garten2:garden_shower": "Trädgårdsdusch", + "pack:nextfloor.a_kueche2:coffee_machine": "Helautomatisk kaffemaskin", + "pack:nextfloor.a_kueche2:espresso": "Espressomaskin", + "pack:nextfloor.a_kueche2:kettle": "Vattenkokare", + "pack:nextfloor.a_kueche2:toaster": "Brödrost", + "pack:nextfloor.a_kueche2:stand_mixer": "Köksmaskin", + "pack:nextfloor.a_kueche2:thermo_cooker": "Matberedare med kokfunktion", + "pack:nextfloor.a_kueche2:air_fryer": "Airfryer", + "pack:nextfloor.a_kueche2:microwave": "Mikrovågsugn", + "pack:nextfloor.a_kueche2:wine_fridge": "Vinkyl", + "pack:nextfloor.a_kueche2:water_bar": "Kolsyremaskin", + "pack:nextfloor.a_kueche2:dishwasher_slim": "Diskmaskin 45 cm", + "pack:nextfloor.a_fahrzeuge2:motorbike": "Motorcykel", + "pack:nextfloor.a_fahrzeuge2:scooter": "Skoter", + "pack:nextfloor.a_fahrzeuge2:camper_van": "Husbil", + "pack:nextfloor.a_fahrzeuge2:trailer": "Släpvagn", + "pack:nextfloor.a_fahrzeuge2:e_bike": "Elcykel", + "pack:nextfloor.a_fahrzeuge2:cargo_bike": "Lådcykel", + "pack:nextfloor.a_fahrzeuge2:quad": "Fyrhjuling", + "pack:nextfloor.a_fahrzeuge2:boat_trailer": "Båttrailer med båt", + "pack:nextfloor.a_aussenkueche:outdoor_kitchen": "Utekök", + "pack:nextfloor.a_aussenkueche:kamado": "Kamadogrill", + "pack:nextfloor.a_aussenkueche:pizza_oven": "Pizzaugn", + "pack:nextfloor.a_aussenkueche:fire_pit": "Eldskål", + "pack:nextfloor.a_aussenkueche:patio_heater": "Terrassvärmare", + "pack:nextfloor.a_aussenkueche:outdoor_fridge": "Utomhuskyl", + "pack:nextfloor.a_aussenkueche:bar_counter": "Bardisk", + "pack:nextfloor.a_aussenkueche:bar_stool_out": "Barstol utomhus", + "pack:nextfloor.a_aussenkueche:hanging_chair": "Hängstol", + "pack:nextfloor.a_werkstatt2:workbench_wall": "Arbetsbänk med verktygstavla", + "pack:nextfloor.a_werkstatt2:drill_press": "Pelarborrmaskin", + "pack:nextfloor.a_werkstatt2:table_saw": "Bordsåg", + "pack:nextfloor.a_werkstatt2:compressor": "Kompressor", + "pack:nextfloor.a_werkstatt2:welder": "Svetsaggregat", + "pack:nextfloor.a_werkstatt2:heavy_shelf": "Tunglastställ", + "pack:nextfloor.a_werkstatt2:parts_cabinet": "Sortimentsskåp", + "pack:nextfloor.a_werkstatt2:tool_chest": "Verktygsvagn", + "pack:nextfloor.a_werkstatt2:ev_bike_charger": "Batteriladdningsstation", + "pack:nextfloor.a_japandi:low_bed": "Låg säng", + "pack:nextfloor.a_japandi:tatami": "Tatami", + "pack:nextfloor.a_japandi:paper_lamp": "Papperslampa", + "pack:nextfloor.a_japandi:paper_pendant": "Papperstaklampa", + "pack:nextfloor.a_japandi:tea_table": "Lågt tebord", + "pack:nextfloor.a_japandi:shoji_screen": "Shoji-skärm", + "pack:nextfloor.a_japandi:bonsai": "Bonsai", + "pack:nextfloor.a_japandi:floor_cushion": "Golvkudde", + "pack:nextfloor.a_japandi:wood_bench": "Träbänk", + "pack:nextfloor.a_japandi:rattan_chair": "Rottingfåtölj", + "pack:nextfloor.a_loft:steel_shelf": "Stålhylla", + "pack:nextfloor.a_loft:factory_pendant": "Industripendel", + "pack:nextfloor.a_loft:leather_sofa": "Skinnsoffa", + "pack:nextfloor.a_loft:plank_table": "Plankbord", + "pack:nextfloor.a_loft:locker": "Plåtskåp", + "pack:nextfloor.a_loft:edison_floor_lamp": "Edison-golvlampa", + "pack:nextfloor.a_loft:bar_stool_loft": "Industribarstol", + "pack:nextfloor.a_loft:pipe_shelf": "Rörhylla", + "pack:nextfloor.a_gruen:monstera": "Monstera", + "pack:nextfloor.a_gruen:ficus": "Fikus", + "pack:nextfloor.a_gruen:olive_tree": "Olivträd i kruka", + "pack:nextfloor.a_gruen:cactus_group": "Kaktusar", + "pack:nextfloor.a_gruen:hanging_plant": "Hängväxt", + "pack:nextfloor.a_gruen:plant_shelf": "Växthylla med växtljus", + "pack:nextfloor.a_gruen:vertical_garden": "Växtvägg", + "pack:nextfloor.a_gruen:grow_light": "Växtlampa", + "pack:nextfloor.a_gruen:herb_planter": "Smart örtträdgård", + "pack:nextfloor.a_musik:upright_piano": "Piano", + "pack:nextfloor.a_musik:grand_piano": "Flygel", + "pack:nextfloor.a_musik:drum_kit": "Trumset", + "pack:nextfloor.a_musik:guitar_stand": "Gitarrer på stativ", + "pack:nextfloor.a_musik:guitar_amp": "Gitarrförstärkare", + "pack:nextfloor.a_musik:mixing_desk": "Studiobord med mixer", + "pack:nextfloor.a_musik:studio_monitor": "Studiomonitor", + "pack:nextfloor.a_musik:synth": "Synthesizer", + "pack:nextfloor.a_musik:mic_stand": "Mikrofon på stativ", + "pack:nextfloor.a_musik:easel": "Staffli", + "pack:nextfloor.a_musik:vinyl_player": "Skivspelare", + "packname:nextfloor.a_bilder": "Tavlor & ramar", + "pack:nextfloor.a_bilder:frame_landscape": "Tavelram (liggande)", + "pack:nextfloor.a_bilder:frame_portrait": "Tavelram (stående)", + "pack:nextfloor.a_bilder:frame_square": "Tavelram (kvadratisk)", + "pack:nextfloor.a_bilder:frame_large": "Stor tavelram", + "pack:nextfloor.a_bilder:canvas": "Canvastavla", + "pack:nextfloor.a_bilder:poster": "Affisch", + "pack:nextfloor.a_bilder:frame_table": "Bordsram", + "pack:nextfloor.a_bilder:frame_digital": "Digital fotoram", + "pack:nextfloor.a_bilder:picture_ledge": "Tavelhylla med ramar", + "color:pearl_white": "Pearl White", + "color:solid_black": "Solid Black", + "color:midnight_silver": "Midnight Silver", + "color:quicksilver": "Quicksilver", + "color:deep_blue": "Deep Blue", + "color:ultra_red": "Ultra Red", + "color:midnight_cherry": "Midnight Cherry Red", + "pack:nextfloor.fahrzeuge:tesla_model_3": "Tesla Model 3", + "color:red": "Red Multi-Coat", + "color:stealth_grey": "Stealth Grey", + "pack:nextfloor.fahrzeuge:tesla_model_x": "Tesla Model X", + "pack:nextfloor.fahrzeuge:tesla_model_y": "Tesla Model Y", + "pack:nextfloor.fahrzeuge:tesla_cybertruck": "Tesla Cybertruck", + "color:stainless": "Stainless Steel", + "color:wrap_black": "Satin Black-foliering", + "color:wrap_white": "Satin White-foliering", + "color:wrap_grey": "Satin Grey-foliering", + "color:wrap_blue": "Satin Blue-foliering", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024": "Tesla Model 3 (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_3_2024_performance": "Tesla Model 3 Performance (2024)", + "pack:nextfloor.fahrzeuge:tesla_model_s_plaid": "Tesla Model S Plaid", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025": "Tesla Model Y Standard (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_premium": "Tesla Model Y Premium (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_2025_performance": "Tesla Model Y Performance (2025)", + "pack:nextfloor.fahrzeuge:tesla_model_y_l": "Tesla Model Y L", + "pack:nextfloor.fahrzeuge:tesla_roadster": "Tesla Roadster", + "pack:nextfloor.fahrzeuge:tesla_semi": "Tesla Semi", + "pack:nextfloor.fahrzeuge:ev_suv": "Elektrisk SUV (Model Y-storlek)", + "pack:nextfloor.fahrzeuge:small_car": "Småbil", + "pack:nextfloor.fahrzeuge:estate_car": "Kombi", + "pack:nextfloor.fahrzeuge:van": "Skåpbil", + "pack:nextfloor.fahrzeuge:bicycle": "Cykel", + "pack:nextfloor.fahrzeuge:ebike": "Elcykel", + "pack:nextfloor.fahrzeuge:motorbike": "Motorcykel", + "pack:nextfloor.fahrzeuge:trailer": "Släpvagn", + "pack:nextfloor.fahrzeuge:sedan": "Sedan", + "pack:nextfloor.fahrzeuge:coupe": "Sportcoupé", + "pack:nextfloor.fahrzeuge:convertible": "Cabriolet (öppen)", + "pack:nextfloor.fahrzeuge:small_ev": "Liten elbil", + "pack:nextfloor.fahrzeuge:suv": "SUV", + "pack:nextfloor.fahrzeuge:family_van": "Familjebuss", + "pack:nextfloor.fahrzeuge:minibus": "Minibuss", + "pack:nextfloor.fahrzeuge:panel_van": "Paketbil", + "pack:nextfloor.fahrzeuge:pickup": "Pickup", + "pack:nextfloor.fahrzeuge:campervan": "Campervan (poptak)", + "pack:nextfloor.fahrzeuge:motorhome": "Husbil", + "pack:nextfloor.fahrzeuge:caravan": "Husvagn", + "packname:nextfloor.fitness": "Träning (äldre)", + "pack:nextfloor.fitness:treadmill": "Löpband", + "pack:nextfloor.fitness:bike_trainer": "Motionscykel", + "pack:nextfloor.fitness:rower": "Roddmaskin", + "pack:nextfloor.fitness:weight_bench": "Träningsbänk", + "pack:nextfloor.fitness:power_rack": "Powerrack", + "pack:nextfloor.fitness:yoga_mat": "Yogamatta", + "pack:nextfloor.fitness:dumbbell_rack": "Hantelställ", + "packname:nextfloor.garten": "Trädgård och uteplats (äldre)", + "pack:nextfloor.garten:sun_lounger": "Solsäng", + "pack:nextfloor.garten:garden_table": "Trädgårdsbord", + "pack:nextfloor.garten:garden_chair": "Trädgårdsstol", + "pack:nextfloor.garten:lounge_set": "Utelounge", + "pack:nextfloor.garten:parasol": "Parasoll", + "pack:nextfloor.garten:gas_grill": "Gasgrill", + "pack:nextfloor.garten:fire_bowl": "Eldskål", + "pack:nextfloor.garten:pool": "Pool", + "pack:nextfloor.garten:hot_tub": "Spabad", + "pack:nextfloor.garten:trampoline": "Studsmatta", + "pack:nextfloor.garten:greenhouse": "Växthus", + "pack:nextfloor.garten:raised_bed": "Odlingslåda", + "pack:nextfloor.garten:garden_shed": "Trädgårdsbod", + "pack:nextfloor.garten:swing_bench": "Hammock", + "pack:nextfloor.garten:mower_robot": "Robotgräsklippare", + "pack:nextfloor.garten:tree_oak": "Lövträd", + "pack:nextfloor.garten:tree_birch": "Björk", + "pack:nextfloor.garten:tree_fruit": "Fruktträd", + "pack:nextfloor.garten:conifer": "Barrträd", + "pack:nextfloor.garten:shrub": "Buske", + "pack:nextfloor.garten:shrub_flowering": "Blommande buske", + "pack:nextfloor.garten:hedge": "Häck", + "pack:nextfloor.garten:lawn_brush": "Ris", + "pack:nextfloor.garten:bike_rack": "Cykelställ", + "pack:nextfloor.garten:bin_box": "Sophus (4 kärl)", + "packname:nextfloor.ikea": "IKEA-mått", + "pack:nextfloor.ikea:billy": "Bokhylla 80x202 (Billy-storlek)", + "pack:nextfloor.ikea:billy_low": "Bokhylla 80x106 (Billy-storlek)", + "pack:nextfloor.ikea:kallax_2x2": "Kubhylla 2x2 (Kallax-storlek)", + "pack:nextfloor.ikea:kallax_2x4": "Kubhylla 2x4 (Kallax-storlek)", + "pack:nextfloor.ikea:kallax_4x4": "Kubhylla 4x4 (Kallax-storlek)", + "pack:nextfloor.ikea:lack_side": "Sidobord 55x55 (Lack-storlek)", + "pack:nextfloor.ikea:lack_coffee": "Soffbord 90x55 (Lack-storlek)", + "pack:nextfloor.ikea:malm_bed_140": "Säng 140x200 (Malm-storlek)", + "pack:nextfloor.ikea:malm_bed_160": "Säng 160x200 (Malm-storlek)", + "pack:nextfloor.ikea:malm_chest_6": "Byrå med 6 lådor (Malm-storlek)", + "pack:nextfloor.ikea:malm_chest_4": "Byrå med 4 lådor (Malm-storlek)", + "pack:nextfloor.ikea:pax_100": "Garderob 100x236 (Pax-storlek)", + "pack:nextfloor.ikea:pax_150": "Garderob 150x236 (Pax-storlek)", + "pack:nextfloor.ikea:poang": "Fåtölj (Poäng-storlek)", + "pack:nextfloor.ikea:ektorp_2": "2-sitssoffa (Ektorp-storlek)", + "pack:nextfloor.ikea:ektorp_3": "3-sitssoffa (Ektorp-storlek)", + "pack:nextfloor.ikea:bekant": "Skrivbord 160x80 (Bekant-storlek)", + "pack:nextfloor.ikea:alex": "Lådhurts (Alex-storlek)", + "pack:nextfloor.ikea:besta_tv": "TV-bänk 180x42 (Bestå-storlek)", + "pack:nextfloor.ikea:ivar": "Furuhylla 89x179 (Ivar-storlek)", + "packname:nextfloor.kino": "Hemmabio och gaming", + "pack:nextfloor.kino:projection_screen": "Projektorduk", + "pack:nextfloor.kino:projector": "Projektor", + "pack:nextfloor.kino:floor_speaker": "Golvhögtalare", + "pack:nextfloor.kino:subwoofer": "Subwoofer", + "pack:nextfloor.kino:soundbar": "Soundbar", + "pack:nextfloor.kino:gaming_desk": "Gamingskrivbord", + "pack:nextfloor.kino:gaming_chair": "Gamingstol", + "pack:nextfloor.kino:game_console": "Spelkonsol", + "pack:nextfloor.kino:arcade": "Arkadmaskin", + "pack:nextfloor.kino:media_wall": "Mediavägg med TV", + "pack:nextfloor.kino:media_rack": "Mediarack", + "packname:nextfloor.kueche": "Kök extra", + "pack:nextfloor.kueche:coffee_machine": "Kaffemaskin", + "pack:nextfloor.kueche:microwave": "Mikrovågsugn", + "pack:nextfloor.kueche:hood_island": "Köksöfläkt", + "pack:nextfloor.kueche:wine_fridge": "Vinkyl", + "pack:nextfloor.kueche:stand_mixer": "Köksmaskin", + "pack:nextfloor.kueche:toaster": "Brödrost", + "pack:nextfloor.kueche:kettle": "Vattenkokare", + "pack:nextfloor.kueche:long_dining_table": "Långt matbord", + "pack:nextfloor.kueche:bar_cart": "Barvagn", + "pack:nextfloor.kueche:trash_station": "Sopsortering", + "packname:nextfloor.schlafen": "Sova och barn", + "pack:nextfloor.schlafen:boxspring": "Kontinentalsäng", + "pack:nextfloor.schlafen:baby_crib": "Babysäng", + "pack:nextfloor.schlafen:changing_table": "Skötbord", + "pack:nextfloor.schlafen:vanity_table": "Sminkbord", + "pack:nextfloor.schlafen:clothes_rail": "Klädställning", + "pack:nextfloor.schlafen:loft_bed_desk": "Loftsäng med skrivbord", + "pack:nextfloor.schlafen:toy_box": "Leksakslåda", + "packname:nextfloor.technik": "Kontor och homelab", + "pack:nextfloor.technik:standing_desk": "Höj- och sänkbart skrivbord", + "pack:nextfloor.technik:server_rack": "Serverrack (19 tum)", + "pack:nextfloor.technik:nas": "NAS", + "pack:nextfloor.technik:printer_3d": "3D-skrivare", + "pack:nextfloor.technik:office_printer": "Skrivare", + "pack:nextfloor.technik:router": "Router / accesspunkt", + "pack:nextfloor.technik:tower_pc": "Torndator", + "pack:nextfloor.technik:filing_cabinet": "Lådhurts", + "packname:nextfloor.treppen": "Trappor och räcken", + "pack:nextfloor.treppen:stairs_straight": "Rak trappa", + "pack:nextfloor.treppen:stairs_l": "L-trappa med vilplan", + "pack:nextfloor.treppen:stairs_u": "U-trappa", + "pack:nextfloor.treppen:stairs_spiral": "Spiraltrappa", + "pack:nextfloor.treppen:stairs_compact": "Platsbesparande trappa", + "pack:nextfloor.treppen:landing": "Vilplan", + "pack:nextfloor.treppen:steps_outdoor": "Yttertrappa", + "pack:nextfloor.treppen:rail_metal": "Metallräcke", + "pack:nextfloor.treppen:rail_glass": "Glasräcke", + "pack:nextfloor.treppen:rail_wood": "Träräcke", + "pack:nextfloor.treppen:stairs_floating": "Svävande trappa", + "pack:nextfloor.treppen:stairs_u_winder": "Öppen U-trappa med svängda steg", + "pack:nextfloor.treppen:rail_corner": "Hörnräcke", + "packname:nextfloor.werkstatt": "Garage och verkstad", + "pack:nextfloor.werkstatt:workbench": "Arbetsbänk", + "pack:nextfloor.werkstatt:tool_cabinet": "Verktygsskåp", + "pack:nextfloor.werkstatt:tool_chest": "Verktygsvagn", + "pack:nextfloor.werkstatt:shelf_rack": "Förvaringsställ", + "pack:nextfloor.werkstatt:tyre_stack": "Däckstapel", + "pack:nextfloor.werkstatt:drill_press": "Pelarborrmaskin", + "pack:nextfloor.werkstatt:compressor": "Kompressor", + "pack:nextfloor.werkstatt:bike_stand": "Cykelställ", + "pack:nextfloor.werkstatt:paint_cabinet": "Färgskåp", + "pack:nextfloor.werkstatt:tool_wall": "Verktygsvägg", + "pack:nextfloor.werkstatt:heavy_shelf": "Tungt förvaringsställ", + "pack:nextfloor.werkstatt:chest_freezer_garage": "Frysbox", + "pack:nextfloor.werkstatt:tyre_rack": "Däckställ", + "pack:nextfloor.werkstatt:lawn_mower": "Gräsklippare", + "pack:nextfloor.werkstatt:bike_stand_2": "Cykelställ med 2 cyklar", + "pack:nextfloor.werkstatt:workshop_light": "Verkstadslampa", + "pack:nextfloor.werkstatt:garage_opener": "Garageportöppnare", + "pack:nextfloor.werkstatt:wallbox_holder": "Laddbox med kabelhållare", + "pack:nextfloor.werkstatt:wall_bike_holder": "Väggcykelhållare (2)", + "pack:nextfloor.werkstatt:workshop_vacuum": "Verkstadsdammsugare", + "pack:nextfloor.werkstatt:workshop_cabinet": "Verkstadsskåp", + "pack:nextfloor.werkstatt:printer_enclosed": "Sluten 3D-skrivare", + "packname:nextfloor.wohnen": "Boende och husdjur", + "pack:nextfloor.wohnen:corner_sofa": "Hörnsoffa (L-form)", + "pack:nextfloor.wohnen:bean_bag": "Sittsäck", + "pack:nextfloor.wohnen:fireplace": "Öppen spis", + "pack:nextfloor.wohnen:bookcase_wall": "Väggbokhylla", + "pack:nextfloor.wohnen:piano": "Piano", + "pack:nextfloor.wohnen:aquarium": "Akvarium", + "pack:nextfloor.wohnen:cat_tree": "Klösträd", + "pack:nextfloor.wohnen:dog_bed": "Hundbädd", + "pack:nextfloor.wohnen:hanging_chair": "Hängstol", + "pack:nextfloor.wohnen:display_cabinet": "Vitrinskåp", + "pack:nextfloor.wohnen:high_table": "Barbord", + "pack:nextfloor.wohnen:floor_mirror": "Golvspegel", + "furn_tap": "Tryck på föremålet", + "furn_tap_default": "Som vanligt", + "furn_tap_hint": "En egen åtgärd som stjärnmenyns egna knappar, t.ex. en browser_mod-popup med ditt kort.", + "furn_show_when": "Visa bara medan …", + "furn_show_when_state": "… har tillståndet (tomt = på)", + "furn_show_when_invert": "Tvärtom: visa medan det inte är så", + "furn_show_when_hint": "Säsongsdekoration som bara står framme i december: en hjälpare (input_boolean), en kalender eller en sensor avgör om möbeln syns i 3D. Separera flera tillstånd med komma. Redigeraren visar den alltid.", + "picture_upload": "Ladda upp ett foto", + "picture_replace": "Ladda upp ett annat foto", + "picture_stored": "Ett eget foto är sparat.", + "picture_url": "… eller bildadress", + "picture_entity": "… eller en entitets bild", + "picture_border": "Passepartout (%)", + "picture_fit": "Foto", + "picture_fit_cover": "fyller ramen", + "picture_fit_contain": "syns helt", + "picture_hint": "Ditt foto i ramen, i 3D och på väggplattan. Uppladdade foton sparas förminskade med planen; en bildentitet (dagens foto) eller en kamera visar sin aktuella bild.", + "card_tap_in_room": "Styr enheter bara i det öppnade rummet", + "card_tap_in_room_hint": "I hus- och våningsvyn öppnar ett tryck våningen eller rummet, även på en enhet eller dess symbol. I det öppnade rummet styr det enheten. En lång tryckning öppnar alltid dess meny eller detaljer.", + "card_markers_outside": "Välj symboler utanför det öppnade rummet", + "card_markers_outside_hint": "I huset, på våningen och i de andra rummen bara de markerade sorterna; i det öppnade rummet alla, som ovan. Enhetens \"Alltid\" och \"Aldrig\" går före.", + "marker_kind_light": "Lampor", + "marker_kind_cover": "Rullgardiner", + "marker_kind_climate": "Värme", + "marker_kind_media": "Media", + "marker_kind_switch": "Brytare", + "marker_kind_fan": "Fläktar", + "marker_kind_lock": "Lås", + "marker_kind_binary": "Kontakter och detektorer", + "marker_kind_sensor": "Sensorer", + "marker_kind_tap": "Möbler med åtgärd", + "marker_kind_other": "Övrigt", + "floor_copy": "Duplicera plan", + "floor_copy_hint": "Kopian hamnar överst på huset med alla rum, väggar, dörrar och fönster. Rum och plan förlorar sin koppling till Home Assistant, möbler sina entiteter; energienheter stannar på det gamla planet.", + "floor_copy_furniture": "Ta med möblerna", + "floor_copy_devices": "Ta med enhetsnålarna", + "floor_copy_devices_hint": "Samma entitet visas då på båda planen.", + "floor_copy_outdoor": "Ta med utomhusytorna", + "floor_copy_make": "Skapa kopian", + "floor_copy_name": "{name} (kopia)", + "furn_to_floor": "Flytta till plan", + "furn_to_floor_hint": "Möbeln flyttas till samma plats på det valda planet.", + "arc": "Båge", + "arc_hint": "Böjer väggen till en båge. Ett rum som delar väggen böjs med, dörrar och fönster följer med; Ångra tar bort bågen.", + "arc_bulge": "Böjning (m)", + "arc_bulge_hint": "Hur långt väggens mitt buktar: positivt utåt, negativt in i rummet.", + "arc_apply": "Böj", + "arc_too_wide": "En dörr eller ett fönster i den här väggen är för brett för den här bågen. Gör bågen flackare eller öppningen smalare.", + "time_of_day": "Tid på dagen", + "time_of_day_hint": "Visar sol, ljus, skuggor och utseende vid en annan tid i dag. Tryck igen för att gå tillbaka till nu.", + "menu_open": "Meny öppen", + "menu_open_hint": "Stjärnmenyn med favoriter och egna knappar står öppen från start på den här enheten, en storlek större – för en väggplatta som mest kör scener.", + "keep_camera": "Behåll kameran", + "keep_camera_hint": "Vid byte av våning behåller kameran samma sida, höjd och avstånd i stället för att passa in den nya våningen från startsidan.", + "view_zoom": "Zoom", + "view_zoom_hint": "Hur nära de inpassade vyerna kommer – på små plattor ser huset större ut.", + "stair_shape": "Form", + "stair_shape_straight": "Rak", + "stair_shape_quarter": "Kvartsvängd (vindlad)", + "stair_shape_l": "L-form med vilplan", + "stair_shape_half": "Halvsvängd (vindlad)", + "stair_shape_u": "U-form med vilplan", + "stair_shape_spiral": "Spiraltrappa", + "stair_turn": "Svänger (uppåt)", + "stair_turn_left": "Åt vänster", + "stair_turn_right": "Åt höger", + "stair_build": "Konstruktion", + "stair_build_solid": "Massiv (betong)", + "stair_build_stringer": "Med vangstycken", + "stair_build_mono": "Mittbalk", + "stair_build_cantilever": "Fribärande (svävande)", + "stair_risers": "Sättsteg", + "stair_steps": "Antal steg", + "stair_run_width": "Trappbredd (m)", + "stair_landing_after": "Steg upp till vilplanet", + "stair_landing_hint": "Vilplanet ligger {h} cm över golvet; resten av stegen kommer efter.", + "stair_rail": "Räcke", + "stair_rail_none": "Inget", + "stair_rail_left": "Vänster", + "stair_rail_right": "Höger", + "stair_rail_both": "Båda sidor", + "stair_down": "Leder nedåt", + "stair_down_hint": "Trappan börjar på det här planet och leder nedåt, till exempel till en källare som inte behöver ritas. Den öppnar golvet på det här planet.", + "stair_measures": "{steps} steg à {rise} cm · steglängd {going} cm · stegmått {measure} cm", + "stair_uncomfortable": "obekväm (stegmått 59–65 cm, steghöjd högst 21 cm)", + "stair_up_note": "Trappan börjar vid den markerade framkanten. Bjälklaget ovanför öppnas bara där mindre än 2,2 m fri höjd blir kvar ovanför stegen.", + "stair_down_note": "Man kliver på trappan vid den markerade framkanten och går nedåt. Ritningen visar den streckad; det här planet öppnas ovanför stegen.", + "stair_upgrade": "Välj form", + "stair_upgrade_hint": "Gör den till en trappa med form (vindlad, L, U, spiral), konstruktion, räcke och antal steg.", + "tool_stairs": "Trappa", + "hint_stairs": "Dra där trappan ska stå – den löper längs långsidan; ställ sedan in form, svängning och konstruktion till höger", + "stair_opening": "Bjälklagsöppning", + "stair_opening_headroom": "Efter fri höjd (bara där det behövs)", + "stair_opening_full": "Över hela trappan", + "stair_opening_none": "Ingen (lucka, stängt trapphus)", + "stair_opening_hint": "Hur mycket trappan öppnar golvet den når: planet ovanför, eller sitt eget plan när den leder nedåt. Efter fri höjd öppnar bara över steg där mindre än 2,2 m finns kvar.", + "stair_up_note_plain": "Trappan börjar vid den markerade framkanten och stiger bakåt." +} diff --git a/custom_components/nextfloor/frontend/lang/tr.json b/custom_components/nextfloor/frontend/lang/tr.json new file mode 100644 index 0000000..fb77d90 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/tr.json @@ -0,0 +1,153 @@ +{ + "accent": "Vurgu rengi", + "accent_reset": "Camgöbeğine dön", + "alert_alarm_by": "Alarmı tetikleyen: {cause}", + "all_floors": "Tüm katlar", + "all_off_done": "Hepsi kapalı.", + "all_off_floor": "{floor} katında her şey kapalı ({n} cihaz), on saniye geri alınabilir", + "all_off_n": "Hepsini kapat ({n})", + "all_off_undo": "Geri al", + "announce_failed": "Anons başarısız: {error}", + "announce_on": "Bu ekrandaki anonslar açık", + "announce_placeholder": "Kendi mesajın …", + "announce_send": "Söyle", + "announce_sent": "Söylendi: \"{message}\"", + "back": "Geri", + "bars_fold": "Anahtarları gizle", + "bars_unfold": "Anahtarlar", + "battery_low_n": "Pil zayıf: {names}", + "brightness": "Parlaklık", + "card_description": "Evin 3B (neon).", + "card_floor_stack": "Alttaki katlar", + "card_room_buttons": "Oda düğmeleri", + "care_bin_days": "{n} gün sonra", + "care_bin_today": "Bugün alınıyor", + "care_bin_tomorrow": "Yarın alınıyor", + "care_time_left": "{time} kaldı", + "central": "Merkez: tüm ışıklar, panjurlar ve favoriler", + "central_covers": "Panjurlar", + "central_favorites": "Favoriler", + "central_house": "Tüm ev", + "central_lights": "Işıklar", + "central_sure": "Emin misin?", + "clock": "Saat", + "close": "Kapat", + "color": "Renk", + "color_temp": "Renk sıcaklığı", + "comfort_n": "Konfor {n}", + "confirm_switch": "{name} gerçekten değiştirilsin mi?", + "cover_close": "Kapat", + "cover_my_go": "Favori konuma ({p} %)", + "cover_open": "Aç", + "cover_stop": "Dur", + "cover_tilt": "Lameller", + "cover_tilt_close": "Lameller kapalı", + "cover_tilt_open": "Lameller açık", + "delete": "Sil", + "details": "Ayrıntılar", + "draft_discard": "Vazgeç", + "draft_found": "{time} tarihinden kaydedilmemiş değişiklikler bulundu.", + "draft_restore": "Geri yükle ve kaydet", + "empty_lights_hint": "{n} ışık açık, {min} dk'dır kimse yok.", + "empty_lights_off": "Işıkları kapat", + "energy_battery": "Batarya", + "energy_consumption": "Tüketim", + "energy_rest": "Ortak (kalan)", + "energy_solar": "Güneş", + "energy_tariff": "Tarife", + "ext_tab": "Eklentiler", + "find": "Ara", + "find_none": "Bir şey bulunamadı", + "find_placeholder": "… nerede? Cihaz veya oda", + "floor_layer": "Katman (gösterilip gizlenebilir)", + "floor_power_share": "Evin %{n}'i", + "floor_rooms": "{n} oda", + "floor_rooms_one": "1 oda", + "floors": "Katlar", + "floors_apart": "Ayrık", + "floors_stacked": "Üst üste", + "flows": "Güç akışı", + "fps_title": "Performans göstergesi (saniyedeki kare)", + "glass_walls": "Cam duvarlar", + "heat_none_found": "Odaların alanlarında uygun sensör yok.", + "heat_wifi": "Wi-Fi", + "heatmap": "Isı haritası", + "holos": "Kartlar", + "keep_camera": "Kamerayı koru", + "load_error": "Yükleme başarısız", + "loading": "Yükleniyor …", + "markers": "İşaretler", + "media_next": "Sonraki", + "media_previous": "Önceki", + "media_sources": "Kaynaklar", + "media_volume": "Ses düzeyi", + "menu_open": "Menü açık", + "meter_unmetered": "{w} ölçülmemiş", + "mood_carry": "Başka bir odaya aktar", + "mood_new": "Ortam", + "mood_save": "Ortamı kaydet", + "mood_set": "Bu ortamı uygula", + "next": "İleri", + "no_building": "Henüz kat planı yok.", + "open_editor": "Düzenleyiciyi aç", + "open_heating_hint": "Isıtma çalışırken {n} pencere açık.", + "open_heating_off": "Isıtmayı kapat", + "open_since": "{time} açık", + "outside_area": "Dışarıda", + "panel_all_close": "Hepsi aşağı", + "panel_all_off": "Hepsi kapalı", + "panel_all_on": "Hepsi açık", + "panel_all_open": "Hepsi yukarı", + "panel_less": "Daha az göster", + "panel_more": "Alandaki diğer cihazlar ({n})", + "plain": "Yalnızca kat planı", + "play_pause": "Oynat/duraklat", + "pool_pump_on": "pompa açık", + "position": "Konum", + "presence_last": "en son {time} önce görüldü", + "presence_now": "biri burada", + "presets": "İstasyonlar ve çalma listeleri (ses)", + "previous": "Geri", + "qm_off": "Kapalı", + "readable": "Kolay okunur", + "reload_page": "Yeniden yükle", + "right_back": "Sağ tık = geri", + "roof_keep": "Çatı kalır", + "room_clean_run": "Temizle", + "room_clean_run_hint": "Robot süpürgeyi bu odaya gönderir.", + "room_curve_hint": "Odanın son 24 saatteki sıcaklığı", + "room_energy": "bugün {today} · ay {month}", + "room_sun_hours": "Bugün {h} saat güneş ({facing})", + "room_sun_year": "Yıl boyunca güneş", + "save_failed_detail": "Kaydetme başarısız: {error}. Değişiklikleriniz bu tarayıcıda saklanır.", + "screen_name": "Bu ekranın adı", + "shade_close": "İndir", + "shade_hint": "{n} pencereye güneş vuruyor, {temp} – panjurlar indirilsin mi?", + "stats_idle": "Beklemede (0 fps)", + "stl": "3B baskı (STL)", + "swipe_off": "Kapalı", + "target_temp": "Hedef", + "temp_down": "Daha serin", + "temp_up": "Daha sıcak", + "time_of_day": "Günün saati", + "today": "Bugün", + "today_none": "Bugün bir şey yok.", + "travel": "Zaman yolculuğu: son 24 saati veya 7 günü yeniden oynat", + "travel_days": "gün", + "travel_failed": "Geçmiş yüklenemedi.", + "travel_live": "Canlı", + "travel_loading": "Geçmiş yükleniyor …", + "travel_speed": "Hız", + "view_options": "Görünüm: kalite, tema, işaretler, FPS", + "view_zoom": "Yakınlaştırma", + "volume": "Ses düzeyi", + "wallbox_charging": "şarj oluyor", + "wallbox_plugged": "takılı", + "walls_auto": "Yüksek duvarlar", + "walls_cut": "Kesit", + "walls_slope": "Eğimli", + "walls_solid": "Dolu", + "wifi_aps": "{n} erişim noktası · {clients} cihaz", + "wifi_clients": "{n} cihaz", + "wifi_network": "Ağ: {online} çevrimiçi · {offline} çevrimdışı" +} diff --git a/custom_components/nextfloor/frontend/lang/zh.json b/custom_components/nextfloor/frontend/lang/zh.json new file mode 100644 index 0000000..da1e1b5 --- /dev/null +++ b/custom_components/nextfloor/frontend/lang/zh.json @@ -0,0 +1,1930 @@ +{ + "view": "3D", + "editor": "编辑器", + "all_floors": "所有楼层", + "no_building": "还没有平面图。", + "no_building_admin": "还没有平面图。请在编辑器中绘制第一个楼层。", + "no_rooms_admin": "楼层已创建,但还没有房间。只有墙是不够的:请在编辑器中用“矩形”或“自由形状”至少绘制一个房间。", + "open_editor": "打开编辑器", + "loading": "正在加载…", + "load_error": "加载失败", + "saving": "正在保存…", + "saved": "已保存", + "save_error": "保存失败", + "save_failed_detail": "保存失败:{error}。您的更改已保留在此浏览器中。", + "needs_restart": "已安装新版本的 云上青梧({frontend}),但 Home Assistant 仍在运行 {version}。请重启 Home Assistant——在此之前保存可能会失败。", + "needs_reload": "此页面仍显示 云上青梧 {frontend},而 Home Assistant 已是 {backend}。请重新加载页面;在配套应用中:设置 → 配套应用 → 重置前端缓存。", + "reload_page": "重新加载", + "needs_restart_old": "已安装新版本的 云上青梧,但 Home Assistant 仍在运行旧版本。请重启 Home Assistant——在此之前保存会失败。", + "draft_found": "发现 {time} 的未保存更改。", + "draft_restore": "恢复并保存", + "draft_discard": "丢弃", + "walls_auto": "高墙", + "walls_cut": "剖切", + "reset_view": "总览", + "back": "返回", + "floor": "楼层", + "floors": "楼层", + "add_floor": "添加楼层", + "floor_from_ha": "来自 Home Assistant 的楼层:", + "floor_empty": "空楼层", + "level": "第 {n} 层", + "ha_floor": "Home Assistant 中的楼层", + "no_ha_floor": "– 无 –", + "area_rooms": "从 HA 区域添加房间({n})", + "area_rooms_hint": "为此楼层的每个区域添加一个房间(4 × 3 m)——然后将其拖到位置并调整角点", + "floor_name": "名称", + "elevation": "标高 (m)", + "floor_shift": "平移楼层 (m)", + "floor_shift_apply": "平移", + "floor_shift_hint": "将此楼层的所有房间、家具、设备、室外区域、独立墙体和背景图片按 X 和 Z 移动。屋顶部分和线缆保持不变。", + "height": "层高 (m)", + "cut_height": "剖切高度 (m)", + "delete_floor": "删除楼层", + "delete_floor_confirm": "删除楼层“{name}”及其所有房间?", + "move_up": "上移", + "move_down": "下移", + "default_floor": "一层", + "new_floor": "楼层 {n}", + "tool_select": "选择", + "tool_rect": "矩形", + "tool_polygon": "自由形状", + "undo": "撤销", + "redo": "重做", + "fit": "整个平面图", + "room": "房间", + "rooms": "房间", + "room_name": "名称", + "area": "区域", + "no_area": "无区域", + "material": "地面", + "x": "X (m)", + "z": "Y (m)", + "width": "宽度 (m)", + "depth": "深度 (m)", + "points": "角点", + "delete_point": "删除角点", + "duplicate": "复制", + "delete": "删除", + "new_room": "房间 {n}", + "settings": "设置", + "pendant_shape": "形状", + "pendant_shade": "灯罩", + "pendant_globe": "球形", + "pendant_cone": "锥形", + "pendant_drum": "鼓形", + "pkg_open": "布置家具…", + "pkg_hint": "家具靠房间的墙摆放;灯具关联到该区域的灯光。之后可单独调整每件物品——Ctrl+Z 可全部撤回。", + "pkg_done": "已放置 {n} 个物品——Ctrl+Z 可撤回。", + "pkg_kitchen_row": "一字形厨房", + "pkg_kitchen_row_desc": "后墙一排:冰箱、烤箱、水槽、洗碗机和灶台,吊柜,带吊灯的餐桌", + "pkg_kitchen_l": "L 形厨房", + "pkg_kitchen_l_desc": "后侧和左侧各一排,带吧台凳的厨房中岛", + "pkg_bath": "浴室", + "pkg_bath_desc": "洗手盆、马桶、浴缸、洗衣机、筒灯", + "pkg_bedroom": "卧室", + "pkg_bedroom_desc": "双人床配两个床头柜、衣柜、五斗柜、吸顶灯", + "pkg_living": "客厅", + "pkg_living_desc": "电视柜、沙发、茶几、地毯、扶手椅、书架、落地灯、绿植", + "pkg_dining": "餐厅", + "pkg_dining_desc": "餐桌配四把椅子、餐边柜、吊灯", + "pkg_office": "书房", + "pkg_office_desc": "书桌配办公椅、两个书架、吸顶灯", + "pkg_kids": "儿童房", + "pkg_kids_desc": "单人床、书桌、书架、地毯", + "pkg_hall": "门厅", + "pkg_hall_desc": "衣帽架、两个筒灯", + "spots_place": "放置射灯", + "spots_type": "灯具", + "spots_cols": "列(左–右)", + "spots_rows": "行(前–后)", + "spots_add": "放置 {n} 盏灯", + "spots_placed": "已放置 {n} 盏灯。", + "spots_hint": "所有灯都跟随所选灯光(例如同一调光器上的射灯)。之后每盏灯都可以像其他家具一样移动并关联到其他灯光。", + "cancel": "取消", + "backup": "备份", + "backup_history": "还原点", + "backup_none": "暂无。编辑时最多每 10 分钟保留一个还原点。", + "backup_summary": "{rooms} 个房间,{furniture} 个物品", + "backup_restore": "还原", + "backup_restore_confirm": "还原到 {time} 的状态?当前状态将保留为还原点。", + "backup_restored": "已还原。", + "backup_file": "文件", + "backup_export": "导出", + "backup_export_share": "作为模板分享", + "backup_export_share_hint": "不含区域、设备、传感器和图片——用于分享给他人。", + "backup_import": "导入…", + "backup_import_confirm": "用该文件替换整个平面图?当前状态将保留为还原点。", + "backup_import_error": "该文件不是 云上青梧 平面图({error})。", + "backup_imported": "已导入。", + "backup_hint": "背景图片不包含在文件中。", + "backup_full": "完整备份", + "backup_full_export": "备份全部(平面图、图片、扩展包)", + "backup_full_import": "还原完整备份…", + "backup_full_hint": "一个文件包含平面图、所有背景和屏幕图片以及已安装的扩展包。还原时会重新校验每个扩展包;许可证密钥不包含在内。", + "backup_full_confirm": "用备份替换平面图、图片和扩展包?当前状态将保留为还原点。", + "backup_full_not_backup": "这不是 云上青梧 完整备份。", + "backup_full_restored": "备份已还原:{packs} 个扩展包,{pictures} 张图片。", + "backup_full_skipped": "已跳过(无法验证或绑定到其他安装):{packs}。", + "export_name_full": "full", + "device_confirm": "切换前确认", + "device_confirm_hint": "在 3D 中点击、快捷菜单和房间面板会先询问。双击房间时不包含此设备。", + "cover_confirm_hint": "在快捷菜单和房间面板中打开、关闭和设置位置时会先询问,并且在标记上滑动不再移动卷帘(而是旋转视图)。停止从不询问。", + "confirm_switch": "确定要切换 {name}?", + "gang_switch": "按键 {n} 控制", + "gang_socket": "插座 {n} 由以下供电", + "gang_switch_hint": "每个按键都有自己的实体(灯、开关、风扇),打开时会发光——灯会显示它的颜色。点按即可切换;有多个按键时会打开一个小菜单。", + "gang_socket_hint": "每个插座都有自己的实体(继电器、智能插头),也可以加一个功率传感器;打开时发绿光。同一个实体可以用在多个插座上——一个继电器控制两个插座。", + "split_handle_hint": "拖动:调整平面图和 3D 视图的宽度", + "wall_exterior": "外墙 (m)", + "wall_interior": "内墙 (m)", + "grid": "网格 (m)", + "units": "长度", + "units_metric": "米", + "units_imperial": "英尺和英寸", + "units_hint": "编辑器显示和读取长度的方式。自动将跟随 Home Assistant 的单位制。平面图始终以米存储——英尺和英寸可输入为 8' 2\"、98in 或 8.2ft。", + "background": "模板(平面图图片)", + "background_upload": "选择图片…", + "background_width": "在平面图中的宽度 (m)", + "background_opacity": "不透明度", + "background_rotation": "旋转 (°)", + "background_edit": "移动、缩放和旋转", + "background_edit_done": "完成", + "background_edit_hint": "此模式开启时:拖动图片可移动它,右下角的手柄可缩放它。先将图片调整到正确比例,再旋转。", + "background_remove": "移除模板", + "hint_select": "点击房间以选择 · 拖动角点 · 边上的“+”插入角点 · 方向键微调 · Del 删除 · Ctrl+Z", + "hint_rect": "拖动以绘制矩形", + "hint_polygon": "放置角点 · 点击第一个角点或按 Enter 闭合 · Esc 取消", + "hint_empty": "请先添加楼层。", + "area_m2": "{a} m²", + "overlap_warning": "房间重叠——该处墙体不完整。", + "read_only": "只有管理员可以编辑平面图。", + "mat_wood": "木地板", + "mat_oak": "橡木", + "mat_tiles": "瓷砖", + "mat_carpet": "地毯", + "mat_stone": "石材", + "mat_concrete": "混凝土", + "card_name": "云上青梧", + "card_description": "您的家,3D 霓虹呈现。", + "stats": "{calls} 次绘制调用 · {tris} 个三角形", + "stats_fps": "{fps} fps(最慢帧 {ms} ms)", + "stats_idle": "静止(0 fps)", + "stats_busy_floors": "楼层", + "stats_busy_openings": "门/窗", + "stats_busy_flash": "闪烁", + "stats_busy_roof": "屋顶", + "stats_busy_flow": "能量流", + "stats_busy_effect": "色彩效果", + "stats_busy_robot": "机器人", + "stats_busy_orbit": "相机旋转", + "stats_busy_tint": "房间着色", + "stats_low": "平板级别,像素比 {r}", + "stats_full": "完整级别,像素比 {r}", + "floors_apart": "分开", + "floors_stacked": "叠放", + "roof_keep": "保留屋顶", + "roof_keep_hint": "放大时屋顶保留在房子上,而不是抬起并淡出", + "floor_rooms_one": "1 个房间", + "floor_rooms": "{n} 个房间", + "quality": "画质", + "quality_auto": "自动", + "quality_low": "平板", + "quality_high": "高", + "state_on": "开", + "state_off": "关", + "state_open": "打开", + "state_closed": "关闭", + "state_opening": "正在打开", + "state_closing": "正在关闭", + "state_playing": "正在播放", + "state_paused": "已暂停", + "state_idle": "空闲", + "state_locked": "已锁定", + "state_unlocked": "已解锁", + "state_detected": "已检测到", + "state_clear": "未检测到", + "state_unavailable": "不可用", + "state_heat": "制热", + "state_cool": "制冷", + "state_auto": "自动", + "state_heat_cool": "制热/制冷", + "state_dry": "除湿", + "state_fan_only": "送风", + "devices": "设备", + "devices_none_area": "将房间关联到区域,其设备就会显示在这里。", + "devices_none": "该区域没有合适的设备。", + "devices_place_all_n": "全部放置 {n} 个…", + "devices_place_all_confirm": "一次将 {n} 个设备放入房间?(Ctrl+Z 或“撤销”可一步全部撤回。)", + "devices_src_area": "此区域", + "devices_src_other": "其他区域", + "devices_src_none": "无区域", + "panel_hide": "从房间面板中隐藏", + "panel_unhide": "重新在房间面板中显示", + "panel_state_hide": "在房间面板中隐藏状态(例如只报告“未知”的窗帘)", + "panel_state_show": "重新在房间面板中显示状态", + "devices_place": "放置", + "devices_remove": "移除", + "devices_hint": "已放置的设备会显示在 3D 中。在平面图中拖动即可移动。", + "panel_lights": "灯光", + "panel_covers": "窗帘", + "panel_climate": "供暖", + "panel_media": "媒体", + "panel_switches": "开关", + "panel_sensors": "传感器", + "panel_scenes": "场景和脚本", + "state_recording": "正在录制", + "state_streaming": "正在推流", + "panel_all_off": "全部关闭", + "panel_all_on": "全部打开", + "view_options": "视图:画质、外观、标记、FPS", + "panel_all_open": "全部升起", + "panel_all_close": "全部降下", + "central": "中控:所有灯光、卷帘和收藏", + "central_house": "整栋房子", + "central_lights": "灯光", + "central_covers": "卷帘", + "central_on": "开", + "central_off": "关", + "central_open": "升", + "central_close": "降", + "central_sure": "确定?", + "central_favorites": "收藏", + "central_no_favorites": "还没有收藏。请在编辑器的“收藏”中设置场景、脚本和开关。", + "card_central": "带中控菜单的星标", + "card_central_hint": "楼层或整栋房子的所有灯光和卷帘,以及编辑器中的收藏。", + "favorites": "收藏", + "favorites_hint": "3D 视图中控菜单(星标)的场景、脚本、自动化、按钮和开关——派对、模拟有人在家、遮阳、浇水。", + "favorites_add": "添加收藏", + "favorite_floor": "此收藏项显示在哪一层", + "favorite_all_floors": "所有楼层", + "outside_hidden": "室外:隐藏设备", + "outside_hidden_hint": "“室外”面板不显示的设备(它们仍保留在平面图中)。", + "outside_hidden_add": "隐藏设备", + "room_facts": "房间面板:显示的信息", + "room_fact_sun": "日照时数", + "room_fact_comfort": "舒适度", + "room_fact_air": "通风提示", + "room_fact_circuits": "回路", + "background_handles_hint": "图片现在像家具一样带有手柄:拖动可移动,右下角可缩放,顶部的圆形手柄可旋转(按住 Shift 以 15° 步进)。调整好后点击“完成”——之后它就固定不动了。", + "background_fixed_hint": "图片已固定,您可以在其上绘制。如需调整,请点击“移动、缩放和旋转”。", + "bg_level": "校正水平", + "bg_level_cancel": "取消校正", + "bg_level_first": "点击图片中一面应为水平或垂直的墙的起点。", + "bg_level_second": "再点击这面墙的终点——图片会随之旋转。", + "bg_ruler": "用标尺设置比例", + "bg_ruler_cancel": "取消标尺", + "bg_ruler_first": "点击图片中一段已知长度的起点——例如一面标注了尺寸的墙。", + "bg_ruler_second": "再点击这段的终点。", + "bg_ruler_length_hint": "平面图中测得:{m}。输入实际长度,图片将按比例缩放。", + "bg_ruler_length": "实际长度 (m)", + "bg_ruler_apply": "应用比例", + "thumbs_fold": "将楼层图片收起为按钮", + "thumbs_show": "重新显示楼层图片", + "room_start_view": "设为此房间的起始视图", + "room_start_view_hint": "在 3D 中点击房间时,相机会飞到右侧 3D 窗格当前显示的视图——角度、缩放和取景。请先开启“并排 3D”,旋转并放大房间,然后点击。", + "room_start_view_reset": "移除房间的起始视图(恢复为俯视)", + "room_start_view_need_pane": "请先开启“并排 3D”,然后按房间应打开的样子旋转和缩放。", + "floor_start_view": "设为此楼层的起始视图", + "floor_start_view_hint": "此楼层在 3D 中将按右侧 3D 窗格当前的样子打开——例如一层从正面、二层从背面。请先开启“并排 3D”,旋转后点击。", + "floor_start_view_reset": "移除楼层的起始视图(恢复为与房子相同)", + "floor_start_view_need_pane": "请先开启“并排 3D”,并按楼层应打开的样子旋转。", + "glow_scale": "3D 中的光晕 (%)", + "glow_scale_hint": "灯具在 3D 中的发光强度:低于 100 % 可减弱明亮的 LED 灯带,避免房间过曝;高于 100 % 让较暗的灯更亮。不会切换 Home Assistant 中的任何内容。", + "vehicle_to_spot": "转为停车位", + "vehicle_to_spot_hint": "作为普通家具的车辆会一直停在那里。作为停车位时,只有传感器报告车辆在场时才会显示,汽车 Pro 也在此设置(充电、续航、车锁、空调)。", + "as_furniture": "显示为家具", + "as_furniture_hint": "在同一位置用一件关联到此设备的家具替换标记——媒体播放器用音箱,灯光用灯具。Ctrl+Z 可撤回。 摄像头会保留其标记及所有摄像头设置,模型只是额外添加。", + "as_furniture_pick": "选择家具…", + "as_device": "恢复为设备标记", + "as_device_hint": "在同一位置用其设备的普通标记替换家具。", + "presets": "电台和播放列表(声音与影院)", + "presets_hint": "显示在每个音箱快捷菜单的“播放”下,与播放器的音源并列。对于 Echo(Alexa Media Player):类型填 SPOTIFY、AMAZON_MUSIC 或 TUNEIN,内容填您会说出的话(“Rock Antenne”)。对于 Sonos、Music Assistant 等:类型填 music 或 url,并填写流地址或 URI。", + "preset_type": "类型", + "preset_type_hint": "play_media 的 media_content_type,例如 music、url、playlist、SPOTIFY、AMAZON_MUSIC、TUNEIN", + "preset_content": "内容", + "preset_content_hint": "media_content_id:流 URL、URI(spotify:playlist:…),或用于 Alexa 的搜索短语", + "preset_add": "电台或播放列表", + "own_buttons": "自定义按钮", + "own_buttons_hint": "显示在中控菜单(星标)的收藏下方:打开仪表板路径、显示实体详情、调用服务,或打开带有自定义卡片的 browser_mod 弹窗。", + "own_button_label": "标签", + "own_button_action": "动作", + "own_button_new": "新按钮", + "own_button_add": "自定义按钮", + "own_action_navigate": "打开路径", + "own_action_more_info": "实体详情", + "own_action_service": "调用服务", + "own_action_fire_dom_event": "fire-dom-event (browser_mod)", + "own_target_navigate": "路径", + "own_target_more_info": "实体", + "own_target_service": "服务 (domain.service)", + "own_data": "数据 (JSON)", + "own_data_hint": "服务填写其数据,fire-dom-event 填写事件内容,例如 {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}。", + "own_data_bad": "不是有效的 JSON 对象。", + "panel_no_area": "此房间未关联到区域。您可以在编辑器中关联。", + "panel_empty": "此房间的设备都不在平面图中。请在编辑器中放置设备,或用 ☆ 将其选入房间面板。", + "close": "关闭", + "brightness": "亮度", + "color_temp": "色温", + "color": "颜色", + "position": "位置", + "cover_open": "打开", + "cover_stop": "停止", + "cover_tilt": "叶片", + "cover_tilt_open": "叶片打开", + "cover_tilt_close": "叶片关闭", + "cover_close": "关闭", + "target_temp": "目标", + "current_temp": "当前", + "temp_down": "调低", + "temp_up": "调高", + "volume": "音量", + "play_pause": "播放/暂停", + "previous": "上一首", + "next": "下一首", + "run": "运行", + "details": "详情", + "hold_hint": "点击切换 · 长按打开详情", + "tool_opening": "门窗", + "tool_furniture": "家具", + "qm_off": "关", + "find": "搜索", + "find_placeholder": "…在哪里?设备或房间", + "find_none": "未找到", + "swipe_off": "关", + "panel_pin": "在房间面板中显示", + "panel_unpin": "不在房间面板中显示", + "devices_panel_hint": "房间面板显示平面图中的设备。☆ 可将设备添加到房间面板而无需放置。", + "card_section_view": "视图", + "card_size": "尺寸", + "card_size_fixed": "固定高度", + "card_size_fill": "填满屏幕", + "card_fill_hint": "在“面板(单卡片)”类型的仪表板视图中效果最佳——卡片会占据全部空间。", + "card_controls": "卡片中的开关", + "card_floor_thumbs": "楼层缩略图", + "card_floor_thumbs_hint": "在侧边显示楼层的小图——点击切换", + "card_floor_thumbs_hint_start": "所选楼层即为卡片的起始楼层——侧边的图片用于切换到其他楼层", + "card_room_names": "显示房间名称", + "card_section_kiosk": "墙面平板(Kiosk)", + "card_section_features": "功能", + "card_weather_plan": "与平面图中的设置相同", + "card_pro_hint": "运动轨迹和天气是 Pro 附加功能:没有对应附加功能时,这些开关不起作用。", + "card_idle_return": "多久后返回起始视图", + "card_idle_off": "从不", + "card_idle_min": "{n} 分钟无触摸", + "card_idle_hint": "等待时间过后,卡片会关闭房间并重新显示起始视图。", + "card_night": "夜间调暗", + "card_night_off": "关", + "card_night_sun": "按日出日落", + "card_night_time": "时间段", + "card_night_range": "时间段(例如 22:00-06:00)", + "card_idle_orbit": "相机旋转作为屏保", + "card_idle_orbit_hint": "返回后视图会缓慢旋转,直到有人触摸平板", + "card_dashboard": "跳转到仪表板的按钮(路径)", + "card_dashboard_label": "按钮标签", + "card_dashboard_hint": "卡片右上角的按钮会打开此路径的仪表板或视图,例如 /lovelace/home 或 /dashboard-house/0。不填标签时显示 ⌂。", + "card_alerts": "显示警告", + "card_alerts_hint": "烟雾、燃气、一氧化碳、漏水、警报面板以及下雨时开着的窗户:房间会闪烁,顶部出现提示", + "card_alert_jump": "跳转到新警告所在的房间", + "card_alert_jump_hint": "视图会自动切换到警告所在的楼层和房间", + "card_scenes": "房间内的场景按钮", + "card_scenes_hint": "选中房间时,该区域的场景和脚本以按钮形式显示在 3D 视图下方", + "weather_short": "天气", + "weather_entity": "天气实体", + "weather_effects": "3D 天气效果", + "rain_warning": "警告:下雨时窗户开着", + "sun_patches": "透过窗户的阳光", + "sun_patches_hint": "设置北向后,来自 sun.sun 的阳光会透过窗户在地板上形成明亮光斑。取消勾选则地板上不显示光斑。", + "sun_arc": "太阳轨迹与指南针", + "sun_arc_hint": "在地块上方画出今天太阳的轨迹弧线,地面有圆环和方位标记(北为红色)。需要 Home Assistant 中的家庭位置。", + "weather_effect_rain": "雨", + "weather_effect_snow": "雪", + "weather_effect_fog": "雾(场景变灰)", + "weather_effect_clouds": "云层使天空和太阳变暗", + "weather_effect_lightning": "雷雨时闪电", + "weather_effect_sky": "天空中的太阳和月亮", + "weather_entity_hint": "天气实体为 3D 视图提供雨、雪、雾和云;自动则使用第一个。", + "weather_hint": "室外天气:雨、雪、雾和云来自天气实体,太阳和月亮来自 sun.sun", + "card_weather": "室外天气", + "card_weather_hint": "雨、雪、雾和云来自第一个天气实体(weather_entity 可另选);平板级别仅显示云", + "alerts": "警告", + "alert_smoke": "烟雾:{name}", + "alert_gas": "燃气:{name}", + "alert_co": "一氧化碳:{name}", + "alert_water": "漏水:{name}", + "alert_alarm": "警报已触发", + "alert_alarm_pending": "警报待触发", + "alert_window_rain": "下雨时窗户开着:{name}", + "alert_power_outage": "停电:{name}", + "room_names_short": "房间名称", + "floor_stack_short_dim": "变暗", + "floor_stack_short_stacked": "叠放", + "floor_stack_short_single": "单独", + "size_short_w": "宽", + "size_short_d": "深", + "size_short_h": "高", + "import_error_not_json": "该文件不是 JSON。", + "import_error_not_plan": "该文件不是 云上青梧 平面图。", + "export_name_template": "模板", + "export_name_backup": "备份", + "card_floor_stack": "下方楼层", + "floor_stack_dim": "变暗", + "floor_stack_stacked": "叠放(显示到此层为止的房屋)", + "floor_stack_single": "隐藏(仅此楼层)", + "card_control_walls": "高墙/剖切", + "card_control_floors": "楼层分离", + "card_control_temperature": "温度", + "card_control_humidity": "湿度", + "card_control_co2": "CO₂", + "card_controls_hint": "可切换高墙/剖切、楼层分离以及温度、湿度、CO₂", + "controls_hide": "隐藏控件——仅保留 3D 视图", + "nav_wrap": "栏换行:所有楼层和房间分多行显示", + "nav_row": "栏单行显示(横向滚动)", + "controls_show": "重新显示控件", + "card_controls_hidden": "启动时隐藏控件", + "card_controls_hidden_hint": "仅显示 3D 视图;左下角的眼睛图标可恢复栏、数值和开关", + "card_controls_hide_after": "隐藏控件的时间", + "card_hide_after_s": "{n} 秒无触摸后", + "card_fullscreen_button": "全屏按钮", + "card_fullscreen_button_hint": "隐藏卡片周围的仪表板(例如在壁挂平板上)", + "fullscreen": "全屏", + "fullscreen_exit": "退出全屏", + "card_section_show": "显示", + "card_floor": "楼层", + "card_floor_house": "整栋房屋(点按楼层将其打开)", + "card_height": "高度(像素)", + "card_walls": "墙壁", + "card_quality_hint": "“平板”是最轻量的设置——非常适合 Fire 平板和其他壁挂平板。", + "card_flows_switch": "卡片内开关", + "card_flows_on": "始终开启", + "card_flows_off": "始终关闭", + "holos": "全息图", + "holos_hint": "显示或隐藏发电系统和设备的全息图", + "card_energy": "在顶部显示能源数值(能源 Pro)", + "card_room_panel": "点按显示房间详情", + "card_room_panel_hint": "在侧面板中显示房间的灯光、遮阳帘和摄像头", + "card_explode": "在房屋视图中拉开楼层", + "card_roof_fade": "放大时淡出屋顶", + "card_roof_fade_hint": "关:即使镜头靠近,屋顶也保留在房屋上。", + "card_stats": "性能显示(每秒帧数)", + "card_stats_hint": "用于检查卡片在设备上的运行流畅度", + "packs": "家具包", + "lib_badge_light": "灯具:关联灯光并在 3D 中切换", + "lib_badge_electric": "电器:关联实体和功率传感器(开关、画面、耗电)", + "lib_badge_hint": "带符号的物品会关联实体:灯具可开关,屏幕可显示画面,电器可显示耗电量。", + "lib_recent": "最近使用", + "lib_fav_add": "加入收藏", + "lib_fav_remove": "取消收藏", + "lib_sizes": "尺寸", + "ext_tab": "扩展", + "ext_title": "扩展", + "ext_intro": "家具包、模块与 Pro 附加功能。本分支已解锁全部 Pro 功能,家具包用本地文件导入,无需联网。", + "pack_import": "导入家具包 …", + "pack_imported": "已导入 {publisher} 的“{name}”——{n} 件物品", + "packs_imported_n": "已导入 {n}/{total} 个包", + "pack_by": "{publisher} · {n} 件物品", + "pack_remove": "移除", + "pack_remove_confirm": "移除包“{name}”?其家具会以普通方块形式保留在平面图中。", + "pack_error_not_a_pack": "这不是家具包文件。", + "pack_error_invalid_content": "此包包含无效家具:{detail}", + "pack_error_too_large": "文件过大。", + "pack_error_needs_update": "此附加功能需要更新版本的 云上青梧。请先更新(HACS › 云上青梧 › ⋮ › “更新信息” › “下载”),重启 Home Assistant,然后重新安装。", + "pack_error_other": "导入失败:{detail}", + "manual": "手册", + "manual_more": "了解更多", + "pack_missing_item": "已移除包中的家具", + "back_to_room": "返回 {room}", + "back_to_floor": "返回楼层", + "hint_furniture": "点按房间,然后在右侧选择物品 · 拖动物品,拖动角点调整大小", + "furniture_into": "新物品会放在“{room}”的中间。", + "furniture_pick_room": "提示:先点按房间——新物品会放在其中间。", + "flows": "能量流", + "flows_hint": "显示或隐藏从电表到用电设备的发光线条", + "chk_title": "设置", + "chk_hint": "能源和能源 Pro 所需的内容。点按某行可跳转到该处。", + "chk_solar": "已放置太阳能板区", + "chk_solar_add": "在屋顶放置太阳能板区", + "chk_meter": "带电网传感器的电表", + "chk_meter_sensor": "电表:缺少电网传感器(W)", + "chk_meter_add": "添加电表", + "chk_inverter": "带功率传感器的逆变器", + "chk_inverter_sensor": "逆变器:缺少功率传感器", + "chk_inverter_add": "添加逆变器", + "chk_battery": "带功率和电量的家用电池", + "chk_battery_sensor": "家用电池:缺少功率或电量", + "chk_battery_opt": "家用电池(可选)", + "chk_grid": "已设置电网连接", + "chk_grid_opt": "电网连接(可选,否则自动)", + "energy_sign_grid": "当前在向电网送电,但没有光伏发电:电网传感器的计数方向可能相反。", + "energy_sign_battery": "电池在没有阳光也没有电网取电的情况下充电:其传感器的计数方向可能相反。", + "energy_sign_flip": "反转符号", + "help_title": "帮助与反馈", + "help_hint": "请将问题作为 GitHub issue 报告,将愿望作为讨论提出——这样不会遗漏,每个人都能看到进展。", + "help_issue": "报告问题", + "help_idea": "提出想法", + "furn_name": "名称(可选)", + "furn_mirror": "镜像", + "furn_mirror_hint": "左右互换——L 形沙发反向、柜门换到另一侧、厨房橱柜镜像。", + "hint_opening": "点按墙壁添加门或窗——之后在右侧选择其类型", + "preset_door": "门", + "preset_door_double": "双开门", + "preset_window": "窗", + "preset_window_double": "双扇窗", + "preset_terrace": "露台门", + "preset_terrace_double": "法式双开门", + "preset_garage": "车库门", + "preset_front": "入户门", + "opening_style": "样式", + "sidelight_auto": "自动", + "sidelight_hinge": "侧窗在铰链侧", + "sidelight_hinge_hint": "侧窗默认位于铰链对侧;勾选后,它位于铰链旁边。", + "sidelight_width": "侧窗宽度(m)", + "sidelight_width_left": "左侧窗(m)", + "sidelight_width_right": "右侧窗(m)", + "style_auto": "自动({style})", + "style_interior": "室内门", + "style_front": "入户门", + "style_front_glass": "带玻璃的入户门", + "style_sidelight": "带侧窗的入户门", + "style_sidelights": "带两扇侧窗的入户门", + "style_glass": "玻璃门", + "style_sliding": "推拉门", + "style_passage": "门洞(无门)", + "style_standard": "标准", + "style_bars": "带窗格条", + "style_glass_wall": "玻璃墙(固定)", + "preset_glass_wall": "玻璃墙", + "flip_hinge": "交换铰链侧", + "flip_main_leaf": "交换主扇", + "flip_hinge_hint": "铰链换到另一侧", + "flip_swing": "反转开启方向", + "flip_swing_hint": "门向房间内开启或向另一侧开启", + "main_leaf": "主扇(从房间内看)", + "contact_main": "主扇门磁", + "contact_second": "副扇门磁", + "tool_outdoor": "室外", + "tool_measure": "按尺寸", + "hint_measure": "点按起点,然后在右侧输入墙长及其方向", + "measure": "按尺寸绘制房间", + "measure_start": "在平面图中点按起点,例如房间的一个角。", + "measure_from": "起点 {x} / {z} m——点按可移动起点。", + "measure_length": "下一面墙的长度(m)", + "measure_close": "闭合房间", + "measure_undo": "删除最后一面墙", + "measure_gap": "与起点的间距:{gap} m(闭合时连接)", + "measure_hint": "提示:输入长度后按方向键。如果测量的是内部尺寸,之后请使用“闭合间隙”。", + "rect_by_size": "按尺寸绘制矩形", + "rect_add": "添加矩形", + "dir_up": "上", + "dir_down": "下", + "dir_left": "左", + "dir_right": "右", + "hint_outdoor": "拖动以绘制室外区域(草坪、露台、泳池 …)", + "outdoor": "室外区域", + "outdoor_type": "类型", + "outdoor_height": "高度(m)", + "outdoor_offset": "高度偏移(m,− = 更低)", + "outdoor_outline": "显示轮廓", + "outdoor_outline_hint": "取消勾选后,区域边缘不绘制发光线条——适用于由多块草坪组成的大地块。", + "outdoor_hint": "室外灯(路灯、花园射灯、室外壁灯)会照亮所有室外区域和外墙。", + "out_lawn": "草坪", + "out_terrace": "露台", + "out_path": "小路", + "out_driveway": "车道", + "out_pool": "泳池", + "out_bed": "花坛", + "out_hedge": "树篱", + "out_fence": "围栏", + "out_wild": "野花草地", + "out_pergola": "花架 / 框架", + "outdoor_open": "开放(不绘制最后一条边)", + "outdoor_open_hint": "不绘制从最后一点回到第一点的边——例如靠着房屋的围栏或花架。", + "fence_gates": "围栏上的门", + "gate_add": "+ 围栏门", + "gate_edge": "围栏边", + "gate_kind": "类型", + "gate_single": "花园门", + "gate_double": "双开门", + "gate_sliding": "推拉门", + "gate_offset": "距起点的中心 (m)", + "gate_width": "宽度 (m)", + "gate_entity": "电机或开关", + "gate_contact": "触点(开 = 打开)", + "fence_gates_hint": "门是围栏上带门柱和门扇的缺口。配上电机(cover、开关、input_boolean、锁)和/或触点后,它会在 3D 中打开:花园门和双开门向内摆动,推拉门沿围栏滑动。", + "outdoor_bracing": "X 形斜撑", + "outdoor_cut": "从下方区域中挖除", + "outdoor_cut_hint": "在此之前绘制、且完整包含此区域的每个区域都会在这里挖出一个洞——例如草坪中的池塘或野花草地。", + "outdoor_area_hint": "设置区域后,此表面就像房间:在 3D 中点按会打开它及该区域的设备,它会出现在房间栏中并显示名称。", + "pool_pump": "过滤泵", + "outdoor_slope": "坡度 (m)", + "outdoor_slope_hint": "高边与低边之间的高度差;高边位于高度偏移处。区域上的灯具会随之调整。", + "outdoor_slope_dir": "倾斜方向", + "slope_x": "右 (+X)", + "slope_nx": "左 (−X)", + "slope_z": "下 (+Z)", + "slope_nz": "上 (−Z)", + "north": "北方(从上方顺时针 °)", + "north_hint": "需要北方设置来计算太阳(透过窗户的光线)。", + "roof": "屋顶", + "roof_none": "无屋顶", + "roof_flat": "平屋顶", + "roof_gable": "双坡屋顶", + "roof_custom": "屋顶分段(自定义)", + "roof_sections": "屋顶分段", + "roof_sections_hint": "每个屋顶分段覆盖房屋的一个矩形区域,例如主屋、谷仓或扩建部分——各自有自己的形状、屋脊方向、檐口高度和坡度。在平面图中拖动可绘制新分段;点击选中,拖动移动,拖动角点调整大小。", + "roof_sections_start": "根据房间创建屋顶分段", + "roof_sections_regen": "根据房间重新创建", + "roof_sections_off": "恢复为单一屋顶", + "roof_regen_confirm": "用根据房间生成的新方案替换所有屋顶分段?", + "roof_section": "屋顶分段", + "roof_section_hint": "高度从地面算起。檐口较低的一侧向下延伸得更远(长短坡);单坡屋顶从第一侧开始升高。", + "roof_shape_gable": "双坡", + "roof_shape_hip": "四坡", + "roof_shape_pent": "单坡", + "roof_shape_flat": "平顶", + "roof_shape_halfhip": "半四坡", + "roof_shape_pyramid": "攒尖", + "roof_shape_mansard": "复折式", + "roof_shape_parapet": "女儿墙", + "roof_shape": "形状", + "roof_axis_x": "屋脊 ↔", + "roof_axis_z": "屋脊 ↕", + "roof_eave": "檐口 (m)", + "roof_pitch_short": "坡度 (°)", + "roof_height": "高度 (m)", + "roof_base": "墙顶 (m)", + "roof_on_floor": "位于楼层", + "roof_on_floor_hint": "将该分段放在此楼层的墙顶上;底部和檐口随之移动。在 3D 视图中,该屋顶属于此楼层。", + "roof_base_hint": "若低于下方楼层的层高,该楼层的墙体会止于屋顶之下:檐口处为矮墙,山墙延伸至屋脊,内墙被斜坡截断。平面图中的虚线表示净高仍有 1.5 m 和 2 m 的位置。", + "roof_ridge_height": "屋脊高度", + "roof_side_top": "上", + "roof_side_bottom": "下", + "roof_side_left": "左", + "roof_side_right": "右", + "roof_swap": "交换两侧", + "roof_open": "雨棚(立柱代替墙体,可透视)", + "roof_open_short": "雨棚", + "roof_dormer": "老虎窗", + "roof_dormer_hint": "在屋顶这一侧添加老虎窗:宽 2 m,正面位于檐口墙处,檐口比屋顶檐口高 1.4 m,双坡屋顶。之后可像其他分段一样移动它并修改宽度和高度;主坡面在其下方打开,阁楼墙体升高到老虎窗处——那里可以放一扇窗。", + "roof_outline": "采用楼层轮廓", + "roof_outline_hint": "自由形状的平屋顶:将当前显示楼层的房间轮廓(L 形或 Z 形也可)作为一个无接缝的整体面。之后可以拖动角点。", + "roof_points_hint": "自由形状:在平面图中拖动角点。“恢复为矩形”会放弃该形状。", + "roof_rect": "恢复为矩形", + "roof_open_hint": "用于露台顶棚或车棚:由立柱和横梁而不是墙体支撑屋顶,并且可透视。雨棚与房屋外墙相接处会搭在墙上。", + "roof_swap_hint": "将屋顶翻转:两侧交换檐口和坡度,单坡屋顶改为向另一方向升高。", + "roof_pitch": "屋顶坡度 (°)", + "roof_overhang": "屋檐出挑 (m)", + "roof_overhang_sides": "每侧出檐", + "roof_overhang_a": "檐口 A 出檐 (m)", + "roof_overhang_b": "檐口 B 出檐 (m)", + "roof_overhang_u0": "山墙起点出檐 (m)", + "roof_overhang_u1": "山墙终点出檐 (m)", + "roof_overhang_auto": "恢复自动", + "roof_overhang_sides_hint": "没有自定义值时出檐为自动:各处相同,但屋顶部分与房屋相接处没有出檐。", + "roof_ridge": "屋脊", + "roof_ridge_long": "沿长边", + "roof_ridge_short": "沿短边(例如联排住宅)", + "device": "设备", + "lamp_mount": "灯具", + "lamp_ceiling": "吸顶灯", + "lamp_floor": "落地灯", + "lamp_table": "台灯", + "lamp_wall": "壁灯", + "marker_height": "标记高度 (m)", + "height_auto": "自动高度", + "device_centre": "移到房间中心", + "lights_spread": "均匀分布吸顶灯", + "devices_search": "搜索设备…", + "devices_more": "还有 {n} 个", + "devices_less": "收起", + "panel_more": "该区域的更多设备({n})", + "panel_less": "收起", + "gaps_close": "闭合缝隙", + "gaps_hint": "将相距不超过 60 cm 的房间合并到一面共用墙上;缝隙变为内墙厚度。", + "gaps_none": "房间之间未发现缝隙。", + "gaps_closed": "已闭合 {n} 处。", + "gaps_closed_wall": "已闭合 {n} 处,内墙现为 {t} m。", + "fps": "FPS", + "fps_title": "性能显示(每秒帧数)", + "hint_garage": "点击墙体以添加车库门", + "opening_garage": "车库门", + "garage_hint": "该门跟随房间所在区域的车库卷帘(位置或开/关)或车库门接触传感器。", + "door_hint": "有门磁时门扇会打开;没有传感器时门半开。", + "hint_door": "点击墙体以添加门", + "hint_window": "点击墙体以添加窗户", + "opening_door": "门", + "opening_window": "窗户", + "opening_type": "类型", + "opening_position": "中心距角点 (m)", + "sill": "窗台高度 (m)", + "opening_height": "高度 (m)", + "hinge": "合页(从房间内看)", + "hinge_left": "左", + "hinge_right": "右", + "cover_entity": "卷帘", + "door_cover": "驱动(电动门或大门)", + "cover_position_entity": "位置传感器(实时)", + "cover_position_invert": "传感器方向相反(0 = 打开)", + "contact_entity": "接触传感器", + "sensor_kind": "传感器类型", + "sensor_kind_contact": "窗磁(开/关)", + "sensor_kind_handle": "把手传感器(开/斜开/关)", + "sensor_kind_contact_tilt": "窗磁 + 斜开传感器", + "handle_entity": "把手传感器", + "handle_main": "主窗扇把手传感器", + "leaf_main": "主窗扇", + "leaf_second": "副窗扇", + "tilt_entity": "斜开传感器", + "tilt_angle_entity": "倾斜角度传感器(°,可选)", + "tilt_angle_max": "视为完全斜开的角度 (°)", + "tilt_angle_offset": "偏移:关闭时报告的角度 (°)", + "tilt_angle_invert": "角度方向相反", + "door_shut": "无传感器时显示为关闭", + "door_shut_hint": "没有接触传感器的门在 3D 中半开,以便识别为门。勾选后显示为关闭——适用于入户门、车棚、侧门。", + "door_angle": "开启角度", + "door_angle_default": "默认", + "door_angle_hint": "门在 3D 中打开的角度:无传感器时一直如此,有传感器时在其报告打开时。默认:无传感器时半开,有传感器时全开。", + "entity_auto": "自动({name})", + "entity_auto_none": "自动(未找到)", + "entity_none": "无", + "entity_search": "输入以搜索…", + "opening_hint": "传感器类型:窗磁(报告开/关)、把手传感器(报告开、斜开和关——例如 Homematic 窗把手)或窗磁 + 斜开传感器(第二个仅报告斜开的传感器)。“自动”使用房间所在区域的卷帘和接触传感器。位置传感器:在卷帘移动时报告其位置的实体(例如 Homematic 的“level”,0–100 % 或 0–1,数值高 = 打开)——卷帘随后会在 3D 中实时移动。", + "furniture": "家具", + "furniture_add": "添加家具", + "furniture_search": "搜索家具…", + "furniture_search_none": "未找到。请换个词试试——英语或德语均可。", + "furniture_type": "物品", + "rotation": "旋转 (°)", + "tilt_x": "前后倾斜 (°)", + "tilt_z": "左右倾斜 (°)", + "strip_tilt": "沿长度方向倾斜 (°)", + "strip_upright": "竖立", + "strip_rise": "上升角度(°)", + "strip_upright_hint": "灯带竖立:其长度从离地高度向上延伸——沿门框或作为灯柱。倾斜可让平放的灯带贴合斜面(90° = 正面朝向侧面)。", + "rotate_left": "↺ 90°", + "rotate_right": "↻ 90°", + "height_m": "高度 (m)", + "furn_sofa": "沙发", + "furn_armchair": "扶手椅", + "furn_table": "桌子", + "furn_chair": "椅子", + "furn_bed": "床", + "furn_nightstand": "床头柜", + "furn_wardrobe": "衣柜", + "furn_shelf": "置物架", + "furn_kitchen": "厨柜", + "furn_worktop": "台面", + "furn_fridge": "冰箱", + "furn_fridge_smart": "智能冰箱(对开门)", + "furn_door_left": "左门传感器(冷冻侧)", + "furn_door_right": "右门传感器(冷藏侧)", + "fridge_hint": "门传感器报告打开时,3D 中的门会打开。右门上的屏幕会像电视一样按规则显示图片——在该门关闭时。", + "furn_stove": "灶台", + "furn_sink": "水槽", + "furn_bathtub": "浴缸", + "furn_shower": "淋浴", + "furn_wc": "马桶", + "furn_washbasin": "洗手盆", + "furn_desk": "书桌", + "furn_tv_board": "电视柜", + "furn_plant": "植物", + "furn_rug": "地毯", + "furn_stairs": "楼梯", + "furn_stairwell": "楼板开口", + "stairwell_hint": "此楼层中的一个洞,例如楼梯上方或用于挑空;从上方可以透过它看下去。跨越多个房间时会在每个房间中切开;多个开口可以重叠(例如组成 L 形)。下层楼梯若延伸到此处,也会自动打开楼板。", + "tool_hole": "楼板开口", + "tool_roof": "屋顶", + "tool_energy": "能源", + "tool_wall": "墙体", + "hint_wall": "拖动以绘制单面墙(隔墙、半墙)· Shift 保持水平/垂直 · Alt 不吸附", + "free_wall": "墙体", + "wall_length": "长度 (m)", + "wall_thickness": "墙厚 (m)", + "wall_height": "高度 (m)", + "wall_height_full": "完整房间高度", + "wall_slope": "倾斜", + "wall_slope_start": "起点高度(米)", + "wall_slope_end": "终点高度(米)", + "wall_slope_hint": "倾斜墙:两个角各有自己的高度,顶边在两者之间呈直线——单坡屋顶、坡地、高侧的高窗。门窗保持在顶边以下。", + "wall_none": "无墙", + "wall_none_hint": "完全不绘制这面墙:适用于开放式布局,房间在空间上相连但在 Home Assistant 中是分开的。", + "edge_thickness": "厚度 (m)", + "wall_thickness_hint": "这面墙的厚度,例如厚外墙 0.365,轻质隔墙 0.115。两个房间之间的墙采用较厚的设置。", + "wall_thickness_reset": "使用房屋的厚度设置", + "wall_heights": "墙体高度", + "wall_n": "墙 {a}–{b}", + "wall_view": "墙面视图", + "wall_view_hint": "拖动可沿墙移动,悬挂物品还可上下移动 · 方向键 1 cm,按住 Shift 10 cm · 边缘会吸附到墙端、门、窗和其他家具(Alt:自由放置) · 双击在平面图中打开该物品", + "wall_view_left": "距左侧 (m)", + "wall_part": "第 {n} 段", + "wall_split_hint": "在此处分割墙体:该段获得独立高度,例如同一直线上 2.5 m 紧挨 1.7 m", + "wall_split_at": "分割点距角点 (m)", + "wall_join_hint": "移除分割点:该段重新与前一段合并", + "wall_exterior_short": "外墙", + "room_wall_hint": "降低高度可将墙变为矮墙或吧台。若两个房间共用这面墙,则采用较低的设置。墙中的门窗止于墙高处。", + "free_wall_hint": "独立墙体,例如隔墙。与房间墙相接处会斜接。拖动手柄移动端点,拖动线条移动整面墙。", + "free_wall_slope": "◢ 倾斜", + "free_wall_slope_hint": "墙从一端到另一端逐渐升高或降低:上面的高度是起点,这里是终点。", + "free_wall_height_end": "终点高度 (m)", + "stairwell_outside": "此开口不在任何房间内,因此不会切开。请将其移入房间。", + "hint_hole": "拖动以绘制楼板开口(楼梯井、挑空)", + "hint_roof": "拖动以绘制屋顶分段 · 点击选中 · 拖动移动 · 拖动角点调整大小", + "hint_energy": "点击太阳能阵列以选中 · 拖动移动,也可移到另一屋面 · 在右侧用“+ 太阳能阵列”添加新阵列", + "furn_parking": "停车位", + "furn_group_vehicles": "停车", + "parking_entity": "传感器“车辆在位”", + "parking_vehicle": "车辆", + "parking_vehicle_none": "无", + "parking_no_pack": "未导入车辆包——车辆来自“车辆”包(家具 → 导入家具包)。", + "parking_scale": "大小 (%)", + "parking_type_entity": "车辆类型传感器(可选)", + "parking_types": "状态 → 车辆", + "parking_type_state": "状态(例如 van)", + "parking_add_type": "+ 映射", + "parking_hint": "没有传感器时车辆始终停在那里。有传感器时,只要传感器报告“on”、“home”或“present”就会出现。车辆类型传感器(例如来自 AI 摄像头分析)用于选择车型:当其状态与某个映射匹配时(也可以是文本中的一个词),显示对应车辆,否则显示默认车辆。", + "parking_too_tall": "车辆({car} m)比房间({room} m)高。", + "furn_lamp_ceiling": "吸顶灯", + "furn_lamp_downlight": "筒灯", + "furn_lamp_spot": "明装射灯", + "furn_lamp_panel": "LED 面板灯", + "furn_lamp_uplight": "地面上照灯", + "furn_lamp_bollard": "草坪灯", + "furn_lamp_garden": "花园射灯", + "furn_radiator": "暖气片", + "furn_robot_vacuum": "扫地机器人", + "furn_entity_vacuum": "扫地机器人", + "furn_robot_room": "当前房间(传感器)", + "robot_hint": "机器人在 Home Assistant 中清扫时,会在 3D 中于其报告的房间内(“当前房间”传感器,按房间或区域名称匹配)按路线行驶,否则在其底座所在房间内行驶。下方标定过机器人自己的地图后,会显示它真正走过的轨迹;没标定时路线是编的。返回时它会开回基站。", + "robot_cal_none": "还没标定——没有把机器人的网格绑到平面图上,路线只能继续是编的。", + "robot_cal_done": "已标定:地图一格 = {m} m。", + "robot_cal_do": "用机器人现在的位置标定", + "robot_cal_doing": "在平面图上点一下机器人现在所在的位置。", + "robot_cal_need": "机器人的地图现在没有上报位置——集成在运行吗?", + "robot_cal_hint": "基站是锚点:平面图知道它站在哪,相机知道机器人和基站在各自网格里的坐标。让机器人停在离基站 1.5 m 以外的地方(暂停清扫),然后在平面图上点一下它。如果房间是镜像的,把下面那个勾打上。", + "robot_cal_mirror": "机器人的地图是镜像的(房间会反过来)", + "robot_cal_forget": "移除标定", + "furn_lamp_pendant": "吊灯", + "fan_hint": "上面的灯控制灯具。有风扇时,扇叶按其档位转动,旁边还有它自己的图标:点按开关风扇,长按调节档位。", + "room_ceiling": "天花板高度(m)", + "furn_lamp_floor": "落地灯", + "furn_lamp_table": "台灯", + "furn_lamp_wall": "壁灯", + "furn_led_strip": "LED 灯带", + "furn_group_lights": "灯光", + "furn_entity_light": "灯或开关", + "furn_color_entity": "颜色和亮度来源(可选)", + "furn_color_entity_hint": "适用于由继电器(Shelly、开关执行器)控制开关、而灯泡本身知道颜色和亮度的灯:开/关来自上方的开关,颜色和亮度来自此实体。", + "furn_entity_climate": "暖气(温控器)", + "lamp_hint": "在 3D 中点击灯具可开关,长按打开快捷菜单。开关同样适用(例如控制吸顶灯的继电器)——开启时灯具发光。台灯会放在其下方的家具上。", + "lamp_hint_pendant": "高度 = 距天花板的下垂距离。在 3D 中点击开关,长按查看详情。", + "theme": "外观", + "version_hint": "已安装的 云上青梧 版本——前端;Home Assistant 中的集成报告 {backend}", + "accent": "强调色", + "accent_hint": "自定义强调色:霓虹外观中的线条和发光边缘、按钮和图钉——↺ 恢复霓虹青色", + "accent_reset": "恢复青色", + "theme_neon": "霓虹", + "theme_blueprint": "蓝图", + "theme_day": "日间", + "theme_auto": "自动(按日照切换白天/霓虹)", + "clock": "时钟", + "screen_name": "屏幕名称(用于 Assist)", + "screen_name_hint": "向 Assist 提问(“显示客厅”)或自动化调用服务 neonplan3d.ask 时,每个打开的 云上青梧 视图都会响应。若服务指定了屏幕,只有同名的视图会响应。", + "walk_hint": "拖动:环顾四周 · 点击地面:走过去 · W A S D / 方向键或摇杆:行走 · Esc:结束", + "backdrop": "背景", + "backdrop_color": "单一颜色", + "backdrop_image": "图片", + "backdrop_dim": "调暗", + "backdrop_hint": "把图片放到 Home Assistant 的 config/www 中,地址即为 /local/文件名.jpg。调暗可让霓虹线条保持清晰。不消耗性能——旧平板也一样。", + "furnish": "布置", + "split_3d": "并排 3D", + "mount_height": "离地高度 (m)", + "side_open": "打开侧边栏", + "side_close": "收起", + "side_details": "所选内容详情", + "side_pin": "固定", + "side_pinned": "已固定", + "side_pin_hint": "固定后侧边栏保持打开;否则在未选中任何内容时,它会在 3D 视图旁收起", + "split_3d_hint": "平面图旁的实时 3D:可在其中拖动和旋转家具及设备——支持撤销,随平面图保存", + "size_w": "宽度 (m)", + "size_d": "深度 (m)", + "size_h": "高度 (m)", + "furnish_hint": "拖入家具、灯具和设备 · 家具会吸附到墙上 · 点击某件物品可旋转、设置高度和安装方式", + "done": "完成", + "heatmap": "热力图", + "heat_off": "正常", + "heat_short_temperature": "温度", + "heat_short_humidity": "湿度", + "heat_short_co2": "CO₂", + "heat_short_values": "数值", + "heat_temperature": "温度", + "heat_humidity": "湿度", + "heat_co2": "CO₂", + "heat_values": "在房间名称处显示数值", + "heat_none_found": "房间所在区域中没有匹配的传感器。", + "markers": "标记", + "markers_none": "无", + "markers_important": "重要", + "markers_all": "全部", + "furn_stool": "凳子", + "furn_coffee_table": "茶几", + "furn_tv_wall": "电视(壁挂)", + "furn_sideboard": "餐边柜", + "furn_table_round": "圆桌", + "furn_bench": "长凳", + "furn_corner_bench": "转角长凳", + "furn_bar_stool": "吧台凳", + "furn_kitchen_wall": "吊柜", + "furn_kitchen_tall": "带烤箱的高柜", + "furn_island": "厨房岛台", + "furn_dishwasher": "洗碗机", + "furn_bunk_bed": "双层床", + "furn_dresser": "五斗柜", + "furn_washer": "洗衣机", + "furn_dryer": "烘干机", + "furn_office_chair": "办公椅", + "furn_tall_cabinet": "高柜", + "furn_coat_rack": "衣帽架", + "furn_group_living": "客厅", + "furn_group_dining": "餐厅", + "furn_group_energy": "能源与太阳能", + "energy_devices": "设备", + "wallbox_charging": "充电中", + "wallbox_plugged": "已插枪", + "furn_soc": "电量 (%)", + "furn_export": "馈网功率(W,单独传感器,可选)", + "furn_export_hint": "如果你的电表用两个传感器分别报告取电和馈网(例如 Growatt、Tibber Pulse),请将取电传感器作为上方的功率,馈网传感器填在这里。带正负号的传感器不需要此项。", + "furn_charge": "充电功率(W,单独传感器,可选)", + "furn_charge_hint": "如果你的电池用两个传感器分别报告充电和放电(例如 Anker Solix),请将放电传感器作为上方的功率,充电传感器填在这里。带正负号的传感器不需要此项。", + "furn_wallbox_status": "状态(充电中、已插枪)", + "energy_only_note": "⚡ 能源:此处只能移动太阳能阵列和能源设备;房间和家具已锁定。", + "roof_only_note": "🏠 屋顶:此处只能移动屋顶分段和屋顶窗;房间和家具已锁定。", + "energy_devices_hint": "电表、逆变器、家用电池、充电桩和电网接入点在这里添加:位于上方所选楼层,可在平面图中移动。配有功率传感器时会显示瓦数;电表使用电网传感器,组串选择其逆变器。也支持多个逆变器和电池(例如再加一套阳台光伏):每个都有自己的传感器。", + "solar_fields": "太阳能阵列", + "solar_hint": "在屋顶上放置组件:它们贴合屋面的坡度;在平屋顶上则安装在支架上。在平面图中拖动阵列即可移动。", + "solar_no_roof": "太阳能阵列需要屋顶:在设置中选择双坡或平屋顶,或在此屋顶工具中添加屋顶分段。", + "solar_face_gone": "屋面缺失", + "solar_summary": "{n} 块组件 · {kwp} kWp", + "solar_add": "太阳能阵列", + "solar_field": "太阳能阵列", + "solar_face": "屋面", + "solar_rows": "行数", + "solar_cols": "每行组件数", + "solar_portrait": "竖装", + "solar_landscape": "横装", + "solar_u": "距边缘 (m)", + "solar_v": "距檐口 (m)", + "solar_tilt": "支架倾角 (°)", + "solar_flip": "向另一侧倾斜", + "solar_partial": "屋面上只能放下 {total} 块中的 {n} 块", + "solar_form_hint": "会超出屋面的组件将被省略。“铺满屋面”会在屋顶上放置尽可能多的组件。kWp 按每块 400 W 计算。", + "solar_fit": "铺满屋面", + "roof_windows": "屋顶窗", + "roof_window": "屋顶窗", + "roof_windows_hint": "屋顶窗位于屋面中,像普通窗户一样可配卷帘和接触传感器。可在平面图中拖动,也可拖到另一屋面上。", + "roof_window_tilt": "斜开接触传感器", + "roof_window_name": "名称(可选)", + "roof_window_motor": "开窗电机(卷帘实体,可选)", + "roof_window_motor_hint": "开窗电机(Velux、Roto、Fakro)以卷帘实体报告其位置:3D 中窗扇按电机位置打开。没有电机时,接触传感器或斜开接触传感器同样有效。", + "roof_window_hint": "打开时窗扇以顶部为轴向外摆出;斜开时稍微打开,窗框发出暖光;卷帘从顶部覆盖玻璃。在屋顶分段中,窗户会在斜坡上切出一个洞,阁楼可以透过它向外看。", + "solar_ground": "独立式(花园、车库屋顶…)", + "solar_add_ground": "独立式", + "solar_base": "表面高度(m,0 = 地面)", + "solar_add_wall": "墙面安装", + "solar_wall": "墙体", + "solar_v_wall": "离地高度 (m)", + "solar_tilt_wall": "离墙倾角(°,90 = 雨棚)", + "solar_flip_wall": "底部离墙而不是顶部", + "solar_rotation": "旋转 (°)", + "solar_name": "名称", + "solar_name_hint": "例如 组串 1 南", + "solar_module_w": "组件宽度 (m)", + "solar_module_h": "组件高度 (m)", + "solar_wp": "组件功率 (Wp)", + "solar_string": "组串", + "solar_strings": "组串", + "solar_string_none": "无组串", + "solar_string_new": "新建组串", + "solar_string_n": "组串 {n}", + "solar_string_name": "组串名称", + "solar_string_entity": "组串光伏功率", + "solar_string_inverter": "连接到(逆变器或储能电池)", + "solar_string_inverter_none": "未选择逆变器", + "inverter_strings": "此逆变器上的组串:{names}", + "inverter_strings_none": "此逆变器上还没有组串——请在太阳能阵列的“组串 › 逆变器”中分配。", + "solar_string_inverter_missing": "平面图中还没有逆变器(请在下方“设备”中添加)", + "solar_string_hint": "同一组串中的阵列属于一组,即使位于不同屋顶上(例如房屋上 5 块、车库上 5 块)。传感器和逆变器对整个组串生效。", + "solar_string_sum": "{fields} 个阵列 · {n} 块组件 · {kwp} kWp", + "solar_face_size": "屋面 {w} × {h} m(沿檐口 × 沿坡向上)", + "solar_cols_hint": "每行长度相同时填一个数字,各行不同时填列表:“4, 4, 3”(从檐口起)。", + "solar_align_left": "左", + "solar_align_center": "居中", + "solar_align_right": "右", + "solar_look_black": "全黑", + "solar_look_blue": "蓝色", + "solar_pick": "逐块开/关组件", + "solar_pick_all": "全部重新开启", + "solar_pick_hint": "在平面图中点击组件可将其移除或放回。已移除的显示为虚线。", + "solar_entity": "此阵列的光伏功率(例如其组串)", + "solar_main": "主屋顶", + "solar_section": "分段 {n}", + "solar_flat": "平屋顶", + "compass_n": "北", + "compass_ne": "东北", + "compass_e": "东", + "compass_se": "东南", + "compass_s": "南", + "compass_sw": "西南", + "compass_w": "西", + "compass_nw": "西北", + "furn_meter": "电表", + "furn_grid_point": "电网接入点", + "grid_point_hint": "电网电缆在此终止:即与供电公司的交接点,例如车道尽头。可在平面图中移动;没有电网接入点时,电缆止于室外区域的边缘。", + "furn_model": "型号", + "inverter_std": "标准(带显示屏的壁挂机)", + "inverter_slim": "纤薄高挑(灯带)", + "inverter_hybrid": "混合式(圆形表盘、风扇)", + "battery_std": "塔式(堆叠模块)", + "battery_wall": "壁挂电池(扁平、悬挂)", + "battery_cube": "紧凑型(阳台储能)", + "furn_inverter": "光伏逆变器", + "furn_home_battery": "家用电池", + "furn_wallbox": "充电桩", + "furn_group_kitchen": "厨房", + "furn_group_sleeping": "卧室", + "furn_group_bath": "浴室与洗衣", + "furn_group_work": "工作及其他", + "furn_entity": "设备(开关、插座…)", + "furn_state_entity": "状态来源(可选)", + "furn_state_entity2": "第二状态(另一半)", + "furn_state_split": "两半", + "furn_state_left_right": "左 / 右", + "furn_state_top_bottom": "下 / 上(双层床)", + "furn_state_hint": "当实体报告 on、occupied 或 home 时该物品发光——例如带压力垫的床、扶手椅、桑拿房。两个实体分别点亮两半:左和右,双层床则为下和上。", + "furn_entity_tv": "电视(媒体播放器或智能插座)", + "fix": "固定", + "unfix": "解除固定", + "fix_hint": "固定后:不会再被意外移动(按键 L、右键或长按)", + "fixed_drag_hint": "🔒 已固定——请先解除固定再移动(表单中的锁、右键或按键 L)", + "fixed_delete_confirm": "此物品已固定。仍要删除吗?", + "lock_plan": "🔒 平面图", + "lock_plan_hint": "锁定平面图:房间、墙体、门、窗和室外区域不会被意外移动。家具和设备仍可自由移动。", + "start_view": "起始视角", + "start_view_hint": "3D 视图、卡片和信息亭模式会以此视角打开房屋,例如从花园一侧。在右侧 3D 窗格中旋转、缩放和移动房屋直到合适,然后保存。", + "start_view_card": "如果某张卡片要以不同视角打开,请将这一行添加到其 YAML 配置中。", + "start_view_set": "将当前 3D 视角保存为起始视角", + "start_view_reset": "默认", + "start_view_saved": "已保存自定义起始视角。", + "ctx_rotate": "旋转 90°", + "devices_placed_in": "位于 {room}", + "devices_narrow": "还有 {n} 个——请缩小搜索范围", + "climate": "室内环境", + "climate_temperature": "温度", + "climate_humidity": "湿度", + "climate_co2": "CO₂", + "climate_hint": "这些传感器用于热力图和房间面板。“自动”使用该区域的传感器以及放置在房间中的传感器,但不包括设备温度(3D 打印机、热泵、供水…)。", + "climate_more": "…再加一个传感器(取平均值)", + "plan_locked": "平面图已锁定", + "plan_lock": "锁定平面图", + "plan_unlock": "解锁平面图", + "opening_mark": "在 3D 中突出显示", + "opening_mark_open": "打开时", + "opening_mark_closed": "关闭时(例如卫生间)", + "opening_mark_hint": "突出显示的窗户或门会发出暖光。“关闭时”需要接触传感器;没有传感器时不会突出显示。", + "marker_show": "3D 中的标记", + "marker_show_hint": "“自动”跟随 3D 视图中的“无 / 重要 / 全部”开关。“始终显示”和“隐藏”不受其影响(“无”除外)。", + "marker_show_auto": "自动", + "marker_show_always": "始终显示", + "marker_show_no_power": "不显示瓦数", + "marker_show_never": "隐藏", + "marker_icon": "自定义图标(Material Design 图标)", + "device_name": "自定义名称(可选)", + "show_name": "在 3D 中于标记下方显示名称", + "card_marker_names": "标记处显示自定义名称", + "card_marker_names_hint": "每个设置了自定义名称的设备都会在其标记下方以小字显示名称——花园里的三个温度计也能区分开。", + "device_name_hint": "仅用于平面图和房间面板的名称,例如“岛台氛围灯”——Home Assistant 中的实体保持不变。", + "device_simple": "房间面板中仅显示开关", + "device_simple_hint": "房间面板对这盏灯只显示开关,不显示亮度、色温和颜色。", + "floor_turn": "旋转 90°", + "floor_shift_all": "所有楼层一起(整栋房屋)", + "floor_shift_all_hint": "平移和旋转作用于所有楼层,连同屋顶分段、室外区域、电缆、电表和全息卡片——整栋房屋作为一个整体移动。", + "floor_turn_hint": "将楼层上的所有内容绕其房间中心顺时针旋转 90°——适用于楼层画反了方向的情况。三次 = 270°。", + "marker_icon_hint": "Home Assistant 中的 Material Design 图标名称,例如 mdi:thermometer 或 mdi:water-alert。留空 = 使用设备类型的图标。", + "furn_power": "功率传感器 (W)", + "furn_links_hint": "配有功率传感器时,该物品会显示瓦数并获得一条能量电缆。", + "furn_links_hint_tv": "电视开启时屏幕发光,颜色对应所用应用(Netflix、YouTube…);标签显示应用或标题。", + "stairs_hint": "楼梯向后方升高(远离标记的前缘),并打开上层楼层的天花板。", + "floor_lights": "{n} 盏灯亮着", + "floor_open": "{n} 处打开", + "floor_persons": "{n} 人", + "energy_consumption": "用电", + "energy_grid_import": "电网取电", + "energy_grid_export": "馈网", + "energy_solar": "太阳能", + "energy_battery": "电池", + "energy_tariff": "电价", + "energy": "能源", + "energy_meter": "电表", + "energy_grid": "电网(W,+ = 取电)", + "energy_solar_sensor": "太阳能发电 (W)", + "energy_battery_sensor": "电池功率(W,+ = 放电)", + "energy_battery_soc": "电池电量 (%)", + "energy_tariff_sensor": "电价(例如 €/kWh)", + "energy_meters_hint": "能源 Pro:房屋卡片显示今日的燃气和用水量——来自仪表的统计数据(累计量,例如以 m³ 计)。“从能源仪表板导入”也会同时填写这两项。", + "energy_invert": "反转符号", + "energy_hint": "用电设备是指配有功率传感器 (W) 的已放置设备——传感器本身或同一设备的某个传感器。", + "energy_balance": "能量平衡", + "energy_balance_hint": "电网、太阳能和电池数据来自平面图中的设备:电表、逆变器和家用电池。你可以在这里选择其他传感器、反转符号并设置房屋用电量。", + "energy_consumption_sensor": "房屋用电(W,否则根据平衡计算)", + "energy_import_prefs": "从能源仪表板导入", + "energy_import_done": "已导入 {n} 个传感器——请检查符号。", + "energy_import_none": "在能源仪表板中未找到匹配的功率传感器 (W)——请手动选择。", + "energy_import_failed": "Home Assistant 的能源仪表板尚未设置。", + "tool_meter": "电表", + "hint_meter": "点击电表所在位置", + "presence": "在家状态", + "presence_hint": "每人一个房间传感器(例如 ESPresense、Bermuda):其状态为房间或区域名称。", + "presence_sensor": "房间传感器", + "no_persons": "Home Assistant 中没有人员。", + "picture_url": "或图片 URL", + "air_co2": "通风(CO₂)", + "air_humidity": "通风(潮湿)", + "air_mould": "霉变风险——请通风", + "alert_alarm_by": "由 {cause} 触发的报警", + "alert_contact_lost": "门窗磁无响应:{name}", + "ambilight": "电视背后的光晕(%)", + "ambilight_hint": "播放时电视背后发光的强度。0 表示关闭(例如电视本身带灯带),100 是常规强度。", + "sound_rings": "声波圈 (%)", + "sound_rings_hint": "播放时扬声器周围声波圈的大小。0 表示关闭(画面和光晕保留),100 为默认大小。 大小还会随扬声器音量变化:音量越小,圈越小。", + "announce_failed": "播报失败:{error}", + "announce_muted": "此屏幕的播报已静音", + "announce_on": "此屏幕的播报已开启", + "announce_phrase_1": "开饭了!", + "announce_phrase_2": "该睡觉了!", + "announce_phrase_3": "请下来一下!", + "announce_phrase_4": "我们马上出门!", + "announce_phrase_5": "狗要出去遛了!", + "announce_phrases": "播报句子(一行一句)", + "announce_phrases_hint": "留空:使用内置句子。播报也可以作为动作「NextFloor: 播报」用于自动化——在房间的音箱上,以及每个打开的 NextFloor 屏幕上。", + "announce_placeholder": "你自己的话……", + "announce_send": "说出来", + "announce_sent": "已播报:「{message}」", + "announce_tts": "播报使用的语音合成", + "arc": "弧线", + "arc_apply": "弯曲", + "arc_bulge": "弯曲量(米)", + "arc_bulge_hint": "墙中间鼓出多少:正值向外,负值向房间内。", + "arc_hint": "把墙弯成弧。共墙的房间会跟着弯,门窗随之移动;撤销可以取消弧线。", + "arc_too_wide": "这面墙上的某个门窗对这种弧度来说太宽。把弧度调平缓,或者把洞口改窄。", + "bars_fold": "收起开关栏", + "bars_unfold": "开关", + "blind_hint": "百叶帘在 3D 里会随卷帘的叶片位置转动;室内卷帘挂在玻璃后面。宽窗户的右半边可以配第二个卷帘。「我的位置」在快捷菜单里显示为「My」:带位置的卷帘会走到那里,没有反馈的 Somfy RTS 电机会用停止走到它自己的 My 位置。", + "blind_inside": "室内卷帘", + "blind_kind": "卷帘种类", + "blind_roller": "户外卷帘", + "blind_venetian": "带叶片的百叶帘", + "card_announcements": "播报", + "card_announcements_hint": "播报(动作「NextFloor: 播报」)会大字显示在卡片上,带提示音并朗读", + "card_central_open": "星标菜单默认展开且放大", + "card_central_open_hint": "收藏和自定义按钮一开始就展开,字号大一档", + "card_keep_camera": "切换楼层时保持镜头", + "card_keep_camera_hint": "每层都用同一侧、同一高度和距离", + "card_lock_button": "3D 锁定按钮", + "card_markers_outside": "打开房间外显示哪些标记", + "card_markers_outside_hint": "在整栋房子、当前楼层和其他房间里只显示勾选的类型;在打开的房间内则按上面的设置全部显示。设备上的「始终」和「从不」优先。", + "card_room_buttons": "房间按钮", + "card_room_buttons_hint": "卡片顶部一行,每个房间一个按钮——点一下就打开该房间,和在模型里点击一样", + "card_sensor_bar": "顶部显示自定义传感器", + "card_sensor_bar_hint": "在编辑器(设置)里选定的传感器,显示在卡片左上角", + "card_solid_walls": "实体墙(按各自颜色)", + "card_tap_in_room": "仅在打开的房间内切换设备", + "card_tap_in_room_hint": "在整栋房子和楼层视图里,点击会打开楼层或房间,即使点在设备或标记上。在打开的房间内点击才切换设备。长按总是打开它的菜单或详情。", + "card_today": "「今天」卡片", + "card_today_hint": "今天的日程和待收的垃圾,显示在右上角", + "card_travel_button": "时间回溯按钮", + "card_walk_button": "漫游按钮", + "card_weather_density": "雨雪密度", + "card_weather_density_hint": "比天气报告显示更少的雨滴和雪花;云、雾和闪电保持不变", + "care_bin_days": "{n} 天后", + "care_bin_today": "今天收运", + "care_bin_tomorrow": "明天收运", + "care_entity_bin": "收运日期(传感器)", + "care_entity_mail": "邮件传感器", + "care_entity_plant": "土壤湿度(传感器)", + "care_hint_bin": "一个带下次收运日期的传感器:天数、日期、「今天」/「明天」,或者 Waste Collection Schedule 集成。收运前一天和当天垃圾桶会发光。", + "care_hint_mail": "一个报告信箱里有信的传感器(比如投信口的门磁)。有信时信箱会发光。", + "care_hint_plant": "埋在土里的湿度传感器。低于阈值时植物会发光并提示缺水。", + "care_mail_no": "空的", + "care_mail_yes": "有信", + "care_plant_ok": "水分充足", + "care_plant_thirsty": "缺水", + "care_thirsty_below": "缺水阈值(%)", + "care_time_left": "还剩 {time}", + "ceiling_here": "此处天花高度", + "ceiling_here_hint": "就在这个位置的天花高度,比如斜顶下。留空 = 用房间的天花高度。", + "ceiling_slope": "到屋顶斜面", + "ceiling_slope_hint": "这里的天花在屋顶斜面下方:灯从斜面的下表面悬挂,正好在它所在位置的上方。", + "clock_bottom_left": "左下", + "clock_bottom_right": "右下", + "clock_none": "关闭", + "clock_top_left": "左上", + "clock_top_right": "右上", + "community_builder": "打开家具构建器", + "community_failed": "社区家具加载失败:{detail}", + "community_how": "怎么分享你自己的", + "community_install": "安装", + "community_installed": "已安装", + "community_intro": "别人用家具构建器做好并分享的家具——经过审核,免费。自己也做一个:", + "community_load": "加载社区家具", + "community_none": "还没有社区家具——来做第一个!", + "community_title": "社区家具", + "community_update": "更新", + "compass_hint": "指南针和实际不符时,在这里转它——不用重画。阳光、风和屋顶各面的朝向都会跟着变。", + "compass_n_short": "北", + "compass_s_short": "南", + "compass_swap": "南北互换", + "compass_swap_hint": "把指南针转 180°。图纸、屋顶各面和光伏阵列都保持不动。", + "compass_title": "指南针", + "contact_warning": "门窗磁不可用时预警", + "contact_warning_hint": "门窗磁连续 10 分钟不可用(电池耗尽、超出无线范围)时,3D 里窗户看起来是关的,但实际状态无人知晓。预警会指出该门窗磁。Home Assistant 重启造成的短暂中断不预警。", + "cover2_entity": "第二个卷帘(右半边)", + "cover_my": "我的位置(%,0 = 不用)", + "cover_my_go": "走到我的位置({p} %)", + "device_outside": "属于室外", + "device_outside_hint": "该设备不计入它下方的房间(比如屋顶的气象站),列在室外面板里。", + "energy_advanced": "高级能源模式", + "energy_advanced_hint": "用于子电表,比如总表后面每户一个:这样一块电表可以挂在另一块下面,并给它自己的楼层供电。关闭 = 第一块表是并网点,其余的是用电器。", + "energy_advanced_on": "使用子电表", + "energy_gas": "燃气表(可选)", + "energy_gas_short": "燃气", + "energy_rest": "公共(其余)", + "energy_routes": "电缆走向", + "energy_routes_hint": "电缆实际怎么走:电力流动就沿着你画的点,而不是穿过房子的弧线。没画走向时仍用弧线。用电器保持弧线。", + "energy_show_unmetered": "在子电表上显示未计量的用电", + "energy_show_unmetered_hint": "子电表的标签会显示它供的楼层用了多少,以及其中多少没有被已放置的设备计量,比如「500 W · 450 W 未计量」。否则显示电表的读数。", + "energy_water": "水表(可选)", + "energy_water_short": "水", + "feature_name_energy": "能源流", + "feature_text_energy": "能量粒子沿弧线从光伏阵列飞向逆变器,在房子、电池、电网和用电器之间流动——功率越大越快越密。组件随发电量闪烁,屋顶上方一张玻璃卡显示能量平衡和此刻房子的自给率。", + "floor_copy": "复制楼层", + "floor_copy_devices": "连同设备图钉一起复制", + "floor_copy_devices_hint": "同一个实体会同时显示在两层上。", + "floor_copy_furniture": "连同家具一起复制", + "floor_copy_hint": "副本会放在房子最上面,连同所有房间、墙、门窗。房间和楼层会失去与 Home Assistant 的关联,家具失去实体;能源设备留在原楼层。", + "floor_copy_make": "创建副本", + "floor_copy_name": "{name}(副本)", + "floor_copy_outdoor": "连同户外区域一起复制", + "floor_heating": "地暖(可选)", + "floor_heating_hint": "温控器在加热(或阀门打开、开关开启)时,房间地面在 3D 里发暖光。", + "floor_layer": "图层(可显示和隐藏)", + "floor_layer_hint": "这个楼层不是一个楼层,而是一个图层——比如所有的树或者装饰。3D 视图顶部会出现一只眼睛,在每台设备上控制显示或隐藏。", + "freezer_temp": "冷冻室温度", + "fridge_temp": "冷藏室温度", + "fridge_temp_hint": "图钉显示温度。冷藏室高于 8 °C 或冷冻室高于 −12 °C 时会亮起作为警告。", + "furn_ceiling_fan": "吊扇", + "furn_cover_entity": "跟随", + "furn_cover_hint": "窗帘、幕布、遮阳篷或大门跟随这个 cover 实体(卷帘、窗帘、遮阳篷、大门)一起动作。点一下打开它的菜单(上升、停止、下降)。", + "furn_cover_inverted": "反转方向", + "furn_cover_inverted_hint": "适用于在平面图中运动方向与实际相反的遮阳篷或窗帘:展开显示为收起,反之亦然。", + "furn_entity_mower": "割草机器人", + "furn_entity_water": "阀门或开关", + "furn_fan_entity": "风扇", + "furn_show_when": "仅在……时显示", + "furn_show_when_hint": "只在十二月摆出来的季节性装饰:用一个辅助元素(input_boolean)、日历或传感器决定这件东西在 3D 里是否显示。多个状态用逗号分隔。编辑器里总是显示。", + "furn_show_when_invert": "反过来:不在该状态时显示", + "furn_show_when_state": "……处于该状态(留空 = 开启)", + "furn_tap": "点击该物件时", + "furn_tap_default": "按常规", + "furn_tap_hint": "自定义动作,和星标菜单的自定义按钮一样,比如用 browser_mod 弹出你自己的卡片。", + "furn_to_floor": "移到楼层", + "furn_to_floor_hint": "物件会移到所选楼层的同一位置。", + "gang_socket_one": "插座由以下供电", + "gang_switch_one": "开关", + "glass_walls": "玻璃墙", + "glass_walls_hint": "看进房间时墙体有多不透明:左边几乎透明,右边不透明。仅对本屏幕生效。", + "heat_mould": "霉变", + "heat_short_mould": "霉变", + "heat_short_wifi": "Wi-Fi", + "heat_summer": "夏季", + "heat_wifi": "Wi-Fi", + "heat_winter": "冬季", + "heatpump_cooling": "制冷", + "heatpump_defrost": "除霜", + "heatpump_flow_return": "出水 → 回水", + "heatpump_heat": "制热", + "heatpump_heating": "加热中", + "heatpump_idle": "待机", + "heatpump_outside": "室外", + "heatpump_power": "功率", + "heatpump_water": "制备热水", + "hint_stairs": "在楼梯要放的位置拖动——它沿长边延伸;之后再在右边设置形状、转向和构造", + "import_dxf_found": "DXF:一个楼层上有 {rooms} 个房间(闭合多段线)和 {walls} 面单墙(直线)。", + "import_ifc_found": "IFC 文件中:{floors} 个楼层和 {rooms} 个房间(墙体由 NextFloor 根据房间生成)。", + "import_roomplan_found": "房间扫描(RoomPlan):{rooms} 个房间,{openings} 个门窗;{skipped} 个物体未导入(家具请自行摆放)。", + "import_error_roomplan_empty": "扫描中没有墙。", + "import_error_ifc_empty": "IFC 文件中没有带平面轮廓的空间(IfcSpace)。", + "import_error_dxf_empty": "这个 DXF 文件里没有直线或多段线。", + "import_error_sh3d": "这不是可读取的 Sweet Home 3D 文件(需要 Sweet Home 3D 5.3 或更新版本)。", + "import_error_sh3d_empty": "这个 Sweet Home 3D 文件里没有房间或墙。", + "import_other_hint": "从 Sweet Home 3D 导入:在这里选择 .sh3d 文件。楼层、房间、门窗和单墙会导过来,家具不会。", + "import_sh3d_found": "Sweet Home 3D:{floors} 个楼层、{rooms} 个房间、{openings} 个门窗、{walls} 面单墙({furniture} 件家具不会被导入)。", + "keep_camera": "保持镜头", + "keep_camera_hint": "切换楼层时镜头停在同一侧、同一高度和距离,而不是按新楼层的起始侧重新取景。", + "lamp_extra_hint": "一盏带多个光源的灯具——主灯、夜灯、氛围灯环:主灯关闭时,3D 里会用下一个亮着的光源发光,稍微暗一点。在房间面板里逐个切换光源。", + "lamp_extra_light": "灯泡 {n}(可选)", + "lib_all_rooms": "显示所有房间", + "lib_cat_appliances": "家电", + "lib_cat_bath": "卫浴", + "lib_cat_beds": "床", + "lib_cat_building": "楼梯与建筑构件", + "lib_cat_climate": "采暖与气候", + "lib_cat_decor": "装饰与其他", + "lib_cat_energy": "能源", + "lib_cat_fitness": "健身", + "lib_cat_garden": "花园与露台", + "lib_cat_kids": "儿童房", + "lib_cat_kitchen": "厨房", + "lib_cat_lights": "灯", + "lib_cat_media": "电视与音响", + "lib_cat_music": "音乐与录音", + "lib_cat_office": "办公", + "lib_cat_pets": "宠物", + "lib_cat_pictures": "画与画框", + "lib_cat_plants": "植物", + "lib_cat_season": "季节与装饰", + "lib_cat_seating": "座椅", + "lib_cat_storage": "柜与架", + "lib_cat_tables": "桌", + "lib_cat_tech": "科技", + "lib_cat_vehicles": "车辆", + "lib_cat_workshop": "工坊与车库", + "lib_favourites": "收藏", + "lib_for_room": "适合 {room}", + "lib_linkable": "可关联", + "lib_lit": "会发光", + "lib_outdoor": "户外", + "light_animation_flicker": "闪烁(强度)", + "light_animation_none": "静态", + "light_animation_pulse": "脉动(强度)", + "light_animation_rainbow": "彩虹(替换颜色)", + "light_effect_add": "添加精确的效果名称", + "light_effect_count_limit": "最多 100 条映射。请先删除一条已有的。", + "light_effect_exists": "这个效果名称已经映射过了。原有映射保留。", + "light_effect_name_limit": "精确的效果名称需要 1 到 255 个字符,不会被截短。", + "light_effect_unmapped": "未映射(静态)", + "light_effects": "3D 中的效果动画", + "light_effects_enabled": "允许这盏灯使用动画", + "light_effects_hint": "只映射 Home Assistant 里精确的效果名称。未映射的效果保持 Home Assistant 的静态颜色。不会改动 Home Assistant 里的任何东西。", + "live_autarky": "自给率", + "live_car_away": "外出中", + "live_car_charge": "开始/停止充电", + "live_car_charging": "充电中", + "live_car_climate": "空调", + "live_car_departure": "{time} 出发", + "live_car_departure_entity": "出发时间(可选)", + "live_car_device": "车辆(该车的任意实体)", + "live_car_device_hint": "电量、续航、充电、充电线、锁和空调由 NextFloor 在车辆的设备上自动查找。没有的话,就用车位上的在位传感器。", + "live_car_lock": "上锁", + "live_car_open": "打开:{parts}", + "live_car_plugged": "已插枪", + "live_car_unlock": "解锁", + "live_car_unlock_confirm": "确定要解锁 {name} 吗?", + "live_day_hint": "最近 24 小时:光伏(面积)与用电(曲线)", + "live_days": "天", + "live_media_next": "下一首", + "live_media_playpause": "播放/暂停", + "live_media_prev": "上一首", + "live_media_volume": "音量", + "live_week_hint": "最近 7 天:日照 {solar} kWh,用电 {use} kWh(黄色:日照,浅色:用电)", + "lock3d_off": "解除 3D 锁定", + "lock3d_on": "锁定 3D(不能转动、缩放或平移;点击仍有效)", + "lock_confirm_lock": "确定要锁定 {name} 吗?", + "lock_confirm_unlock": "确定要解锁 {name} 吗?", + "map_hint": "浏览器直接从地图服务器加载瓦片(默认是 OpenStreetMap,请留意其使用政策);关闭地图时不加载任何东西。图纸按指南针的方向铺在地图上——转指南针或移动地图,直到房子对齐。", + "map_lat": "纬度", + "map_lon": "经度", + "map_move": "把地图移到图纸下方", + "map_on": "在图纸下方显示真实地图", + "map_opacity": "可见度(%)", + "map_step": "步长", + "map_url": "自定义瓦片地址(留空 = OpenStreetMap)", + "map_use_ha": "使用 Home Assistant 的位置", + "map_zoom": "细节层级", + "map_zoom_coarse": "粗略", + "map_zoom_fine": "精细", + "marker_kind_binary": "门磁与探测器", + "marker_kind_climate": "采暖", + "marker_kind_cover": "卷帘", + "marker_kind_fan": "风扇", + "marker_kind_light": "灯", + "marker_kind_lock": "锁", + "marker_kind_media": "媒体", + "marker_kind_other": "其他", + "marker_kind_sensor": "传感器", + "marker_kind_switch": "开关", + "marker_kind_tap": "带动作的家具", + "marker_show_active": "仅在活动时", + "media_next": "下一首", + "media_pause": "暂停", + "media_play": "播放", + "media_previous": "上一首", + "media_sources": "来源", + "media_volume": "音量", + "menu_open": "菜单默认展开", + "menu_open_hint": "带收藏和自定义按钮的星标菜单在这台设备上一开始就展开,字号大一档——适合主要用来跑场景的墙面平板。", + "meter_device_hint": "如果设备接在子电表后面(比如公寓里的阳台植物),它的功率会计入那一户。子电表需要双向计量(− = 回馈);如果只计量取电,有盈余时那一户的用电量会偏高。", + "meter_floors": "供电楼层", + "meter_main": "主电表", + "meter_parent": "挂在电表下", + "meter_parent_none": "无(主电表)", + "meter_sub_hint": "子电表计量它这一支路,比如一户。勾选楼层上的设备在 3D 里会挂在它下面而不是主电表上;主电表多出来的部分在能量平衡里显示为「公共(其余)」。", + "meter_sub_power": "支路功率(W,+ = 取电,− = 回馈)", + "meter_unmetered": "{w} 未计量", + "model_add": "添加模型……", + "model_detail": "细节层级", + "model_detail_fine": "精细", + "model_detail_light": "轻量(平板)", + "model_detail_normal": "常规", + "model_error_compressed": "文件被压缩过(Draco、Meshopt 或 KTX)。请导出未压缩的版本。", + "model_error_empty": "文件里没有三维内容。", + "model_error_not_glb": "这不是 .glb 文件(二进制 glTF)。请把模型导出为「glTF 二进制」。", + "model_error_too_large": "文件大于 {max}。请选择更低的细节层级。", + "model_error_unreadable": "文件无法读取:{detail}", + "model_front": "正面", + "model_front_hint": "转动模型,直到它的正面朝向观察者(画面左下方)。", + "model_info": "{triangles} 个三角面,{size} 米", + "model_missing": "还没有", + "model_paint": "漆面(在编辑器里选的颜色)", + "model_paint_preview": "预览中的颜色", + "model_present": "已就位", + "model_remove": "移除", + "model_remove_confirm": "从 Home Assistant 中删除模型「{id}」?", + "model_removed": "模型「{id}」已删除。", + "model_replace": "替换模型……", + "model_result": "结果:{triangles} 个三角面,{size}", + "model_upload": "保存到 Home Assistant", + "model_upload_bad_id": "模型 id 无效。", + "model_upload_forbidden": "只有管理员可以上传模型。", + "model_upload_not_glb": "Home Assistant 拒绝了这个文件(不是二进制 glTF)。", + "model_upload_other": "上传失败:{detail}", + "model_upload_too_large": "Home Assistant 不接受大于 {max} 的文件。请选择更低的细节层级。", + "model_uploaded": "模型「{id}」已保存({size})。刷新面板即可看到。", + "models": "你自己的 3D 模型", + "models_hint": "有些车辆如果你自己有模型,NextFloor 可以显示真实 3D 模型。在这里选择文件(.glb):NextFloor 会把它转正、减轻、标记漆面,并保存到你的 Home Assistant。没有模型时车辆和以前一样。", + "models_licence": "文件属于你,只存在你的 Home Assistant 上。NextFloor 不自带任何模型;请确认你的模型许可允许你在自己的安装里使用。", + "mood_carry": "复制到其他房间", + "mood_new": "氛围", + "mood_save": "保存氛围", + "mood_save_hint": "把房间的灯此刻的亮法保存成一个氛围——点一下就恢复,「→」可以复制到另一个房间。", + "mood_set": "应用这个氛围", + "motion_markers_active": "移动传感器只在检测到东西时显示", + "motion_markers_active_hint": "作用于移动、占用和存在传感器。标记设为「始终显示」的传感器仍然可见。", + "room_double_tap": "双击房间", + "room_double_tap_hint": "双击房间:若有灯亮着则全部关闭,否则全部打开。设为“先询问”的设备始终不受影响。", + "room_double_tap_area": "平面图中的灯及区域内所有灯", + "room_double_tap_plan": "仅平面图中的灯", + "room_double_tap_off": "不切换任何设备", + "card_room_double_tap_auto": "按平面图设置", + "opening_light_well": "前方有采光井", + "opening_lock": "智能锁", + "opening_lock_hint": "点门可以上锁或解锁(总会先询问)。解锁期间门边会发光。", + "opening_rain_warning": "下雨时预警", + "outage_hint": "class 为 power 的二元传感器为 off、其他二元传感器为 on、状态为「off_grid」或「backup」,或者电压低于 50 V,都会触发全屋预警。", + "outage_sensor": "断电传感器", + "outdoor_corners_hint": "角点:边上的 + 可以加一个角,拖动可以改变形状,× 删除一个角。", + "outside_area": "室外", + "outside_area_hint": "所有室外设备一览:花园里的、房间外的,以及属于室外的(比如屋顶的气象站)。", + "own_alert_add": "添加预警", + "own_alert_color": "颜色", + "own_alert_entity": "当……", + "own_alert_house": "整栋房子", + "own_alert_new": "新预警", + "own_alert_state": "……处于该状态(留空 = 开启)", + "own_alert_tap": "点击时", + "own_alert_tap_info": "打开详情", + "own_alert_tap_room": "跳到该房间", + "own_alert_tap_toggle": "切换实体", + "own_alert_text": "……则显示此预警", + "own_alerts": "自定义预警", + "own_alerts_hint": "只要某个实体处于某状态,3D 视图的预警栏就显示一行——扫地机的「水箱空了」、洗衣机的「洗完了」。多个状态用逗号分隔;数值可写 <20 或 >80。", + "own_button_state": "当……开启时发光(可选)", + "pack_error_builtin": "这个 id 已经被 NextFloor 自带的包占用了。", + "pack_paste": "导入 JSON", + "pack_paste_empty": "请先粘贴包的 JSON。", + "pack_paste_not_json": "这不是有效的 JSON:{detail}", + "packs_docs": "包的格式", + "packs_intro": "把你自己的家具作为包(JSON)导入:可以是文件,也可以粘贴到下面。{n} 个包随 NextFloor 自带,始终可用。", + "packs_none": "还没有你自己的包。", + "packs_title": "家具包", + "panel_announce": "📢 播报", + "panel_fold": "收起(房间仍在视野内)", + "panel_unfold": "重新展开", + "pet_room_hint": "一个报告宠物所在房间的传感器——Bermuda 或 ESPresense 配项圈上的标签:3D 里它就会在那个房间活动。", + "pet_room_sensor": "宠物的房间传感器(可选)", + "picture_border": "卡纸(%)", + "picture_entity": "……或者用实体的图片", + "picture_fit": "照片", + "picture_fit_contain": "完整显示", + "picture_fit_cover": "填满画面", + "picture_hint": "画框里的你的照片,在 3D 里和墙面平板上都能看到。上传的照片会以较小的尺寸和户型一起保存;图片实体(比如每日一图)或摄像头则显示它当前的画面。", + "picture_replace": "上传另一张照片", + "picture_stored": "已保存一张自己的照片。", + "picture_upload": "上传照片", + "pin_shift": "移动图钉", + "pin_shift_hint": "设备挨得近时,可以在这里把图钉往旁边或往上挪一点(单位米);设备本身不动。", + "pin_shift_up": "↑ 向上", + "plugin": "插件", + "plugins_add": "添加", + "plugins_docs": "怎么写插件", + "plugins_error": "出错", + "plugins_exists": "这个插件已经在列表里了。", + "plugins_from_dashboard": "由仪表盘资源注册", + "plugins_intro": "插件能给房间面板加上你自己的灯光动画、设备和卡片。填写插件的地址(/config/www 下的 .js 文件,即 /local/……;来自 HACS 的 /hacsfiles/……;或 https://……)。", + "plugins_limit": "最多 20 个插件。", + "plugins_loaded": "已启用", + "plugins_loading": "加载中……", + "plugins_none": "还没有插件。", + "plugins_nothing_registered": "已加载,但没有注册任何东西", + "plugins_off": "关闭", + "plugins_reload_hint": "刷新页面后生效", + "plugins_remove": "移除", + "plugins_title": "插件", + "plugins_url_invalid": "请填写 /local/……、/hacsfiles/…… 或 https://…… 下的 .js 地址。", + "plugins_warning": "插件在你的浏览器里拥有和 NextFloor 相同的权限。只使用你信任的来源的插件。", + "pool_pump_on": "水泵运行中", + "pool_temp": "水温(可选)", + "preset_lift_slide": "提升推拉门", + "preset_speakers": "仅这些音箱(不选 = 全部)", + "printer_bed": "热床", + "printer_done": "已完成", + "printer_done_at": "{time} 完成", + "printer_error": "出错", + "printer_idle": "空闲", + "printer_layer": "层", + "printer_nozzle": "喷嘴", + "printer_paused": "已暂停", + "printer_printing": "打印中", + "rain_sensor": "雨量传感器(自建气象站)", + "roof_end_end": "屋脊末端收口", + "roof_end_start": "屋脊起端收口", + "roof_halfhip": "半歇山起于", + "roof_halfhip_hint": "歇山部分从山墙多高开始,按山墙高度的比例:低 = 大歇山,高 = 只有顶部收成歇山。", + "roof_rotation": "旋转(°)", + "room_announce_hint": "不选的话,优先用放在该房间的音箱,其次是语音助手、Echo 或该区域的音箱(绝不使用电视)。静音时段内,发给多个房间的播报会跳过这个房间;只发给它的播报仍会播出。", + "room_announce_quiet": "播报静音时段", + "room_announce_speaker": "播报用的音箱", + "room_curve_hint": "该房间最近 24 小时的温度曲线", + "room_inner": "内净尺寸 {w} × {d}", + "room_inner_hint": "从墙到墙量的:内墙各算一半厚度,外墙在轮廓之外。", + "route_cable": "显示为电缆", + "route_cable_hint": "把走向画成可见的电缆,而不只是粒子下方那条淡淡的线。", + "route_conn_battery": "电池 ↔ 房子", + "route_conn_device": "{name} ↔ 子电表", + "route_conn_grid": "电网 ↔ 房子", + "route_conn_inverter": "逆变器 → 房子", + "route_conn_meter": "{name} ↔ 上级电表", + "route_conn_solar": "{name} → 逆变器", + "route_done": "完成", + "route_draw": "画走向", + "route_drawing": "在图纸上依次点电缆经过的点,从一端到另一端;穿过楼板的地方切换楼层。已点 {n} 个。", + "route_none": "直线弧", + "route_points": "{n} 个点", + "route_redraw": "重画", + "route_undo": "上一个点", + "side_failed": "这个表单显示不出来({error})。户型仍可使用。请在 GitHub issue 里反馈这段文字。", + "sill_boards": "窗台与窗台板", + "sill_boards_auto": "自动", + "sill_boards_inside": "仅内侧", + "sill_boards_none": "无", + "sill_boards_outside": "仅外侧", + "sofa_l": "L 形(镜像:另一侧)", + "sofa_shape": "形状", + "sofa_straight": "一字形", + "sofa_u": "U 形", + "solar_rack_ew": "东西向支架", + "solar_rack_ew_hint": "每隔一排朝向相反,成对背靠背——低而紧凑,很多平屋顶就是这样。", + "solar_rack_tilt": "支架(再倾斜 °)", + "spray_hint": "阀门打开或开关开启时,喷头会向四周喷出弧形水柱。", + "spray_reach": "喷水射程(米)", + "stair_build": "构造", + "stair_build_cantilever": "悬挑(悬浮)", + "stair_build_mono": "单梁(中脊)", + "stair_build_solid": "实体(混凝土)", + "stair_build_stringer": "侧梁式", + "stair_down": "向下", + "stair_down_hint": "楼梯从这一层开始向下,比如通向一个不用画出来的地下室。它会在这层楼板上开洞。", + "stair_down_note": "从标记的前沿踏上楼梯向下走。图纸上画成虚线;这层在踏步上方开洞。", + "stair_measures": "{steps} 级踏步,踏高 {rise} 厘米 · 踏面 {going} 厘米 · 步距 {measure} 厘米", + "stair_opening": "楼板洞口", + "stair_opening_full": "整部楼梯上方", + "stair_opening_headroom": "按净空(只在需要处)", + "stair_opening_hint": "楼梯够到的楼板要开多大的洞:向上是上面那层,向下是它自己这层。按净空只在不满足 2.2 米的地方开洞。", + "stair_opening_none": "无(检修口、封闭楼梯间)", + "stair_rail": "栏杆", + "stair_rail_both": "两侧", + "stair_rail_left": "左侧", + "stair_rail_none": "无", + "stair_rail_right": "右侧", + "stair_risers": "封闭踢面", + "stair_run_width": "梯段宽度(米)", + "stair_shape": "形状", + "stair_shape_half": "半转(斜踏步)", + "stair_shape_l": "L 形带平台", + "stair_shape_quarter": "四分之一转(斜踏步)", + "stair_shape_spiral": "螺旋", + "stair_shape_straight": "直跑", + "stair_shape_u": "U 形带平台", + "stair_steps": "踏步数", + "stair_turn": "转向(向上走时)", + "stair_turn_left": "向左", + "stair_turn_right": "向右", + "stair_uncomfortable": "不舒适(步距 59–65 厘米,踏高不超过 21 厘米)", + "stair_up_note": "楼梯从标记的前沿开始。只有踏步上方净空不足 2.2 米的地方,上面那层才会开洞。", + "stair_up_note_plain": "楼梯从标记的前沿开始,向后升起。", + "stair_upgrade": "设置形状", + "stair_upgrade_hint": "把它变成带形状的楼梯(斜踏步、L 形、U 形、螺旋),并设置构造、栏杆和踏步数。", + "status_add": "添加传感器", + "status_entities": "3D 视图顶部的自定义传感器", + "status_entities_hint": "比如室外温度、报警或空气质量:它们显示在左上角,带名称和数值,在打开的房间内也显示。点击可打开详情。最多 12 个。", + "store_close": "关闭插件商店", + "store_empty": "插件商店里还没有插件。", + "store_failed": "商店加载失败({error})。", + "store_install": "安装", + "store_installed": "已安装", + "store_intro": "来自社区的、经过审核的插件。每一个在收录前都会检查,之后不再改动。", + "store_open": "打开插件商店", + "store_submit": "提交你自己的插件", + "store_update": "更新", + "sub_area_add": "+ 房间内的区域", + "sub_area_hint": "房间内一块有自己 Home Assistant 区域但没有墙的地方——阅读角、书架、客厅里的小厨房。它的设备和传感器属于这个房间。", + "time_of_day": "一天中的时刻", + "time_of_day_hint": "按今天另一个时刻显示太阳、光线、阴影和外观。再点一下回到现在。", + "today": "今天", + "today_calendars": "「今天」用的日历", + "today_calendars_hint": "这些日历的日程会显示在 3D 视图右上角的「今天」卡片上,连同今天或明天要收的垃圾。点标题可以收起卡片。", + "today_none": "今天没有安排。", + "tool_stairs": "楼梯", + "travel": "时间回溯:回放最近 24 小时或 7 天", + "travel_days": "天", + "travel_failed": "历史数据加载失败。", + "travel_live": "实时", + "travel_loading": "正在加载历史……", + "travel_pause": "暂停", + "travel_play": "播放", + "travel_speed": "速度", + "travel_speed_10min": "10 分钟/秒", + "travel_speed_hour": "1 小时/秒", + "travel_speed_min": "1 分钟/秒", + "view_zoom": "缩放", + "view_zoom_hint": "自动取景时靠得多近——小平板上房子会显得更大。", + "walk": "在房子里行走", + "walk_stop": "停止行走", + "wall_paint_default": "默认", + "wall_paint_hint": "在 3D 视图的「实体」模式下使用。", + "wall_paint_inside": "内侧墙色", + "wall_paint_outside": "外侧墙色", + "wall_paint_room": "内侧墙色(本房间)", + "wall_slope_off": "恢复为平墙", + "wall_view_height": "离地高度(米)", + "wall_view_next": "下一面墙", + "wall_view_prev": "上一面墙", + "walls_slope": "剖切斜面", + "walls_slope_hint": "墙按斜面剖切:前面半高,后面全高——像玩偶屋,随镜头转动", + "walls_solid": "实体", + "walls_solid_hint": "用实体墙代替玻璃墙,按各自颜色显示(颜色:编辑器 → 设置,房间在房间表单里设)", + "wifi_aps": "{n} 个接入点 · {clients} 个设备", + "wifi_clients": "{n} 个设备", + "wifi_network": "网络:{online} 在线 · {offline} 离线", + "wifi_none": "从家具包里放置接入点或路由器(智能家居 2),并把它们关联到其设备的实体。", + "window_opens": "开启方式", + "window_opens_hint": "推拉:合页侧的那扇滑到固定扇前面;双扇时中间两扇向外滑。上悬窗通过门磁或内倒传感器开启。", + "window_opens_slide": "推拉(推拉窗、提升推拉门)", + "window_opens_top": "上悬(下沿外开)", + "window_opens_turn": "内开内倒", + "floor_power": "楼层电表(功率)", + "floor_power_hint": "单独计量本楼层的功率传感器(分表、独立户)。数值显示在楼层标签上;在本楼层视图中,房屋卡片会显示它及其占全屋用电的比例。", + "floor_power_share": "占全屋 {n}%", + "living_area": "居住面积 {living}", + "room_living": "计入居住面积", + "living_area_none": "无居住面积 · 楼层 {floor}", + "living_area_low": "居住面积 {living}(楼层 {floor},其中 {low} 低于 2 m)", + "living_area_hint": "按德国《居住面积条例》计算:墙内侧面积,净高 2 m 以上全计,1–2 m 之间(坡屋顶下)计一半,低于 1 m 不计。仅为参考值,不是测绘结果。", + "living_area_floor": "居住面积:{floor}", + "living_area_floor_house": "本层居住面积:{floor} · 全屋:{house}", + "print_plan": "打印平面图 / PDF", + "print_plan_hint": "把每个楼层输出成带尺寸和面积的干净平面图,并附一张面积表——可直接打印,或在打印对话框里存为 PDF。", + "print_title": "平面图", + "print_room": "房间", + "print_floor_area": "建筑面积", + "print_living": "居住面积", + "print_low": "低于 2 m", + "print_total": "合计", + "print_blocked": "打印窗口被拦截——请允许 Home Assistant 弹出窗口。", + "check_open": "检查平面图", + "note": "便签", + "note_add": "在此添加便签", + "note_text": "文本", + "note_placeholder": "例如“更换滤芯”或“12 号闸”", + "note_due": "到期日", + "note_due_hint": "从那天起标记会变成橙色。", + "note_is_due": "这个便签已到期。", + "keys_title": "编辑器快捷键", + "keys_undo": "撤销", + "keys_redo": "重做", + "keys_duplicate": "复制房间", + "keys_delete": "删除所选", + "keys_nudge": "把所选移动一个网格", + "keys_nudge_10": "…移动 10 cm", + "keys_nudge_1": "…移动 1 cm", + "keys_rotate": "家具旋转 90°(Shift:反向)", + "keys_lock": "固定或解锁家具、设备、屋顶部分", + "keys_close_shape": "闭合自由形状", + "keys_escape": "取消、退出工具、清除选择", + "keys_straight": "绘制时:直线", + "keys_sheet": "本快捷键表", + "tour_title": "新手引导", + "tour_1_title": "绘制房间", + "tour_1": "用「{rect}」或「{free}」绘制房间,墙会自动生成。给每个房间指定 Home Assistant 区域——NextFloor 就能找到它的设备。区域已经建好时,在楼层表单里点「{rooms}」可一次全部添加。", + "tour_2_title": "门窗", + "tour_2": "「{opening}」把门窗放到墙上。关联它们的门磁或卷帘——3D 里就会跟着开关,开着的窗也会提示你。", + "tour_3_title": "家具与设备", + "tour_3": "「{furniture}」打开素材库——也可以在 🛠️ 家具工作室里自己做。选中房间后,它所在区域的设备会列在下面,可直接放置;灯会按自己的光色发亮。", + "tour_4_title": "查看与检查", + "tour_4": "「{split}」让你边画边看房屋;顶部可切换到 3D 视图。「{check}」列出还缺什么——随时按 ? 查看快捷键。", + "tour_next": "下一步", + "tour_back": "上一步", + "tour_done": "开始吧", + "tour_skip": "跳过", + "check_open_hint": "列出平面图中缺失或不合理的地方,一键修复。", + "check_title": "平面图检查", + "check_all_good": "一切正常——没有发现问题。", + "check_hint": "发现 {n} 处问题。蓝色按钮会修改平面图(照常可以撤销),其余按钮只定位到位置。", + "check_room_no_area": "「{room}」没有 Home Assistant 区域:找不到它的设备。", + "check_room_no_area_named": "「{room}」没有区域——空闲区域「{area}」同名。", + "check_areas_unplaced": "本楼层有 {n} 个区域还没有房间:{names}", + "check_devices_unplaced": "「{room}」:该区域有 {n} 个设备还没放进平面图。", + "check_rooms_overlap": "「{a}」和「{b}」重叠。", + "check_opening_off_wall": "「{room}」里有一扇门窗不在墙上。", + "check_entity_missing": "{n} 个设备标记指向 Home Assistant 已不存在的实体({ids})。", + "check_furniture_entity_missing": "有一件家具关联到 {id}——该实体已不存在。", + "check_battery_low": "电量低:{name}({level}%)", + "battery_low_n": "电量低:{names}", + "check_standby": "{name} 关闭时仍耗电 {w} W——一年约 {cost}。", + "check_fix_show": "显示", + "check_fix_set_area": "关联「{area}」", + "check_fix_add_rooms": "添加房间", + "check_fix_place": "放置 {n} 个", + "check_fix_remove": "移除 {n} 个", + "share_view": "分享视图", + "share_view_hint": "把房屋保存成一个小文件,在没有 Home Assistant 的任意浏览器里打开(通过 NextFloor 在线演示)——给家人或设计师看。不含设备与实体,等同模板。", + "share_view_title": "我们家的 NextFloor", + "share_view_needs_js": "此页面需要 JavaScript 和网络连接。", + "share_view_file": "视图", + "share_view_done": "视图已保存——用浏览器打开该文件,或转发出去。", + "version_save": "保存当前状态…", + "version_save_hint": "用名字保存平面图(比如“装修前”)。自动恢复点被清理时,命名的状态会保留下来。", + "version_name_prompt": "给这个状态起个名字(例如“装修前”):", + "version_saved": "状态「{name}」已保存。", + "version_compare": "对比", + "version_delete_confirm": "删除「{name}」?", + "version_same": "与当前平面图没有差异。", + "version_diff_n": "与当前平面图有 {n} 处差异:", + "diff_floor_added": "新增楼层「{name}」", + "diff_floor_removed": "删除楼层「{name}」", + "diff_room_added": "新增房间「{name}」", + "diff_room_removed": "删除房间「{name}」", + "diff_room_renamed": "「{detail}」改名为「{name}」", + "diff_room_reshaped": "「{name}」形状改变({detail} m²)", + "diff_opening_added": "新增 {name}({detail})", + "diff_opening_removed": "删除 {name}({detail})", + "diff_furniture_added": "新增 {name}", + "diff_furniture_removed": "删除 {name}", + "diff_furniture_moved": "{name} 移动或改变", + "diff_device_added": "放置设备 {name}", + "diff_device_removed": "移除设备 {name}", + "diff_device_moved": "移动设备 {name}", + "readable": "易于阅读", + "readable_hint": "更高的对比度和更大的字号——适合墙上平板,以及需要这样看的人。", + "plain": "仅平面图", + "plain_hint": "只显示墙、门、窗和楼梯,不显示家具。设备及其标记保留。", + "right_back": "右键 = 返回", + "right_back_hint": "在 3D 视图中短按右键返回一步:从房间到楼层,从楼层到整栋房子(相当于双击空白处)。按住右键拖动仍然平移视图。", + "stl": "3D 打印 (STL)", + "stl_hint": "将房子保存为 STL 文件(所有楼层的墙、地板、家具和室外区域),用于 3D 打印,比例 1:100(1 米 = 10 毫米)。不含窗、灯和屋顶;切片软件可按需修复文件。", + "card_plain": "仅平面图", + "card_rooms": "仅这些房间", + "card_rooms_hint": "卡片只显示勾选的房间及其家具、设备、门和窗(例如放在厨房的平板)。不勾选则显示整个平面图。", + "card_templates": "卡片模板", + "card_templates_hint": "在此设置一次仪表盘卡片(使用卡片自己的设置),然后在每台平板上只写名称:`template: kitchen_tablet`。这里的修改会传到所有使用该模板的卡片;卡片本身的设置优先于模板。", + "template_name": "新模板(名称)", + "template_add": "创建模板", + "template_reload": "重新加载使用此模板的屏幕", + "template_reload_all": "重新加载所有屏幕", + "template_use": "在仪表盘卡片上:`template: {name}`", + "card_template": "卡片模板", + "card_template_none": "无(仅此卡片)", + "card_readable": "易于阅读", + "all_off_n": "全部关闭({n})", + "all_off_hint": "关闭房间里的灯、开关、风扇和媒体设备;十秒内可撤销。", + "all_off_done": "已全部关闭。", + "all_off_undo": "撤销", + "all_off_floor": "关闭「{floor}」的全部设备({n} 个),十秒内可撤销", + "circuits": "配电箱", + "circuits_hint": "各回路及其供电的房间。房间面板会显示回路名,搜索也能找到(“F12”)。", + "circuit_name": "名称", + "circuit_new": "新回路", + "circuit_add": "添加回路", + "circuit_add_room": "添加房间", + "store_confirm": "安装 {author} 的「{name}」?\n\n插件在你浏览器中拥有与 NextFloor 相同的权限。文件已审核,内容固定:\n{url}", + "studio_new": "自己做一件", + "studio_title": "家具工作室", + "studio_title_edit": "家具工作室:修改", + "studio_hint": "选一个模板,设定尺寸和门板,把成品放进平面图。它会进入「自有家具」包,之后还能在这里再改。", + "studio_kind": "模板", + "studio_kind_cabinet": "柜子", + "studio_kind_shelf": "搁架", + "studio_kind_lamp": "灯", + "studio_kind_device": "设备", + "studio_name": "名称", + "studio_width": "宽(cm)", + "studio_depth": "深(cm)", + "studio_height": "高(cm)", + "studio_doors": "门", + "studio_drawers": "抽屉", + "studio_shelves": "层板", + "studio_handle": "拉手", + "studio_handle_bar": "横杆", + "studio_handle_knob": "圆钮", + "studio_handle_none": "无", + "studio_base": "底座", + "studio_base_plinth": "踢脚", + "studio_base_legs": "支腿", + "studio_base_none": "无", + "studio_back": "背板", + "studio_lamp": "类型", + "studio_lamp_floor": "落地灯", + "studio_lamp_table": "台灯", + "studio_lamp_pendant": "吊灯", + "studio_lamp_wall": "壁灯", + "studio_display": "正面带屏幕(显示媒体播放器)", + "studio_mount": "放置方式", + "studio_mount_floor": "落地", + "studio_mount_surface": "放在家具上", + "studio_mount_wall": "挂墙", + "studio_color_body": "主体", + "studio_color_lamp_body": "底座与支架", + "studio_color_front": "门板", + "studio_color_boards": "层板", + "studio_color_shade": "灯罩", + "studio_color_display": "屏幕边框", + "studio_color_white": "白色", + "studio_color_wood": "木色", + "studio_color_metal": "金属", + "studio_color_dark": "深色", + "studio_color_glass": "玻璃", + "studio_color_accent": "强调色", + "studio_color_own": "自定义颜色", + "studio_color_plan": "平面图配色", + "studio_place": "放入平面图", + "studio_save": "保存修改", + "studio_open": "在工作室中修改", + "studio_error": "保存失败:{detail}", + "studio_pack_name": "自有家具", + "studio_pack_publisher": "家具工作室", + "room_ceiling_tip": "低于楼面(楼梯下的卫生间)或高于楼面(挑高到屋顶的客厅):吊灯、风扇、灯带和吸顶设备都挂在这里,房间的墙也是这个高度。", + "room_ceiling_through": "层高({ceiling} m)高于楼层高度({floor} m):房间通到上一层,墙体随之升高,上一层在它上方保持开敞。上层的编辑器会用斜线标出这块区域。", + "room_floor_offset": "地面高度(米)", + "room_floor_offset_hint": "如果这个房间的地面比楼层低或高(例如下沉式入口:−0.39),地面、墙、门窗和房间里的东西都会随之移动;天花板保持不变。台阶请另外放一段楼梯。", + "plan_dims": "尺寸标注", + "plan_dims_hint": "给每段房间边线标注长度。", + "heat_short_power": "功率", + "heat_short_comfort": "舒适度", + "heat_short_sun": "日照", + "heat_power": "用电功率", + "heat_comfort": "舒适度评分", + "heat_sun": "今日日照", + "room_sun_hours": "今日日照 {h} 小时({facing})", + "open_since": "已开 {time}", + "presence_now": "有人", + "presence_last": "{time}前有人", + "comfort_n": "舒适度 {n}", + "empty_lights_hint": "{n} 盏灯开着,{min} 分钟没人。", + "empty_lights_off": "关灯", + "open_heating_hint": "供暖运行时 {n} 扇窗开着。", + "open_heating_off": "关闭供暖", + "room_clean": "清洁(脚本或按钮)", + "room_clean_hint": "把扫地机叫到这个房间的脚本或按钮(例如扫地机集成里的房间清洁)。房间面板会显示“🧹 清洁”。", + "room_clean_run": "清洁", + "room_clean_run_hint": "把扫地机派到这个房间。", + "shade_hint": "{temp} 时 {n} 扇窗有阳光——要放下卷帘吗?", + "shade_close": "放下", + "room_sun_year": "全年日照", + "room_sun_year_hint": "每月 15 日,房间外窗的日照小时数。", + "room_energy": "今日 {today} · 本月 {month}", + "room_energy_hint": "取自房间内设备功率传感器的统计;本月费用按全屋电价计算。", + "paint_colour": "漆面颜色", + "night_lock_warning": "夜间门未上锁时提醒", + "night_lock_warning_hint": "晚上 10 点到早上 6 点之间,会提示平面图中没有上锁的门锁。", + "alert_unlocked_night": "未上锁:{name}", + "stair_landing_after": "到休息平台的踏步数", + "stair_landing_hint": "休息平台高于楼面 {h} cm,其余踏步在它之后。" +} \ No newline at end of file diff --git a/custom_components/nextfloor/frontend/nextfloor-3d.js b/custom_components/nextfloor/frontend/nextfloor-3d.js new file mode 100644 index 0000000..6cc489c --- /dev/null +++ b/custom_components/nextfloor/frontend/nextfloor-3d.js @@ -0,0 +1,4309 @@ +/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */ +var f0=1.3,d0=(i,e=new Date().toISOString().slice(0,10))=>!!i.due&&i.due<=e;var Ll={lawn:.012,terrace:.12,path:.02,driveway:.02,pool:-.25,bed:.15,wild:.03,hedge:1.2,fence:1,pergola:2.2};function Jr(i){return i==="hedge"||i==="fence"||i==="pergola"}function zh(i,e,t){let n=i.slope??0;if(!n||i.type==="pool")return 0;let r=i.slope_dir??"x",s=(c,u)=>r==="x"?c:r==="-x"?-c:r==="z"?u:-u,o=1/0,a=-1/0;for(let[c,u]of i.points){let h=s(c,u);o=Math.min(o,h),a=Math.max(a,h)}if(a-o<1e-6)return 0;let l=Math.min(1,Math.max(0,(s(e,t)-o)/(a-o)));return n*l}function t1(i,e,t,n){return Ko(i)+(e.offset??0)+Ll[e.type]-zh(e,t,n)}function Ko(i){return i.elevation>.3?0:-.2}function p0(i,e,t){let n=(i.outdoor??[]).filter(s=>!Jr(s.type)&&s.type!=="pool"&&Ve([e,t],s.points)),r=[...n].reverse().find(s=>s.cut)??n[0];return r?t1(i,r,e,t):Ko(i)}var m0=i=>i.cut??i.type==="pool";var n1={type:"none",pitch:35,overhang:.4},g0="#d6cfc2",Vh="#e8e3da",FP={wall_exterior:.24,wall_interior:.12,grid:.05,north:0,roof:{...n1}};var x0=new Set(["lamp_ceiling","lamp_downlight","lamp_spot","lamp_panel","lamp_pendant","ceiling_fan","lamp_floor","lamp_uplight","lamp_table","lamp_wall","led_strip","lamp_bollard","lamp_garden"]),Fl=1.75;function b0(i){return x0.has(i)||!!vt(i)?.light}var i1=new Set(["table","table_round","coffee_table","desk","nightstand","sideboard","dresser","kitchen","island","worktop","tv_board","dishwasher","washer","dryer"]);function jr(i){switch(i.type){case"home_battery":return i.variant==="wall"?.5:0;case"kitchen_wall":return 1.45;case"tv_wall":return Math.max(0,1.3-i.h/2);case"radiator":return .12;case"inverter":return 1.1;case"wallbox":return 1;case"meter":return .4;default:return 0}}var y0=new Set(["lamp_ceiling","lamp_downlight","lamp_spot","lamp_panel","lamp_pendant","ceiling_fan"]);function _0(i,e){return i.filter(t=>t.elevationt.rooms.filter(n=>n.points.length>=3&&n.ceiling!=null&&n.ceiling>t.height+.005&&t.elevation+n.ceiling>e.elevation+.05)).map(t=>t.points)}var Qr=i=>i?.floor_offset&&Number.isFinite(i.floor_offset)?i.floor_offset:0;function v0(i,e,t){let n=i.rooms.find(r=>r.points.length>=3&&r.floor_offset&&Ve([e,t],r.points));return Qr(n)}function Gh(i,e,t){let n=i.rooms.find(r=>r.points.length>=3&&Ve([e,t],r.points));return n?.ceiling!=null&&n.ceiling>0?n.ceiling:i.height}var Ol=(i,e)=>e.ceiling_y!=null&&e.ceiling_y>0?e.ceiling_y:Gh(i,e.x,e.z);function M0(i,e,t){let n=0;for(let r of i.furniture)!(i1.has(r.type)||vt(r.type)?.surface)||!Ve([e,t],ts(r))||(n=Math.max(n,r.h));return n}var r1=new Set([...x0,"radiator","robot_vacuum","inverter","home_battery","wallbox","meter","tv_board","tv_wall","desk","fridge","fridge_smart","stove","kitchen_tall","dishwasher","washer","dryer","kitchen","island","sink"]);var s1=["interior","front","front_glass","sidelight","sidelights","glass","sliding","passage"],o1=["standard","bars","glass_wall"];function _r(i,e){return i.type==="door"?i.style&&s1.includes(i.style)?i.style:e?"front":"interior":i.style&&o1.includes(i.style)?i.style:"standard"}function S0(i,e,t,n){if(e!=="sidelight"&&e!=="sidelights")return null;let r=e==="sidelights",s=i-.04,o=Math.min(1.05,Math.max(.6,s-(r?.6:.3))),a=(s-o)/(r?2:1),l=n.sidelight_width??a,c=r?n.sidelight_width2??n.sidelight_width??a:0;l=Math.max(.1,l),c=r?Math.max(.1,c):0;let u=s-.5;if(l+c>u){let f=Math.max(0,u)/(l+c);l*=f,c*=f}return r?{panels:[[.02,.02+l],[i-.02-c,i-.02]],x0:.02+l,x1:i-.02-c}:(t?!!n.sidelight_hinge:!n.sidelight_hinge)?{panels:[[.02,.02+l]],x0:.02+l,x1:i-.02}:{panels:[[i-.02-l,i-.02]],x0:.02,x1:i-.02-l}}function w0(i){return i==="front"||i==="front_glass"||i==="sidelight"||i==="sidelights"}function es(i){let e=0;for(let t=0;ts+o[0],0)/r,i.reduce((s,o)=>s+o[1],0)/r]}let t=0,n=0;for(let r=0;r1e-6&&Math.abs(n-s)>1e-6)return!1}return!0}function A0(i){let e=1/0,t=1/0,n=-1/0,r=-1/0;for(let[s,o]of i)e=Math.min(e,s),t=Math.min(t,o),n=Math.max(n,s),r=Math.max(r,o);return{x0:e,z0:t,x1:n,z1:r}}function ts(i){let e=i.rotation*Math.PI/180,t=Math.cos(e),n=Math.sin(e),r=i.w/2,s=i.d/2;return[[-r,-s],[r,-s],[r,s],[-r,s]].map(([o,a])=>[i.x+o*t-a*n,i.z+o*n+a*t])}function Ve(i,e){let t=!1;for(let n=0,r=e.length-1;ni[1]!=l>i[1]&&i[0]<(a-s)*(i[1]-o)/(l-o)+s&&(t=!t)}return t}var a1=[],Jo=new Map,l1=0,C0=(i,e)=>`pack:${i}:${e}`,c1=i=>i.startsWith("pack:");function Nl(i){a1=i,Jo=new Map;for(let e of i)for(let t of e.items)Jo.set(C0(e.id,t.id),t);l1+=1}var u1={};function vt(i){if(!c1(i))return;let e=Jo.get(i);if(e)return e;let[,t,...n]=i.split(":"),r=u1[t];return r?Jo.get(C0(r,n.join(":"))):void 0}var h1=.22;function E0(i,e,t,n){let r=Math.min(h1,t/3);if(n<=r*2.4||Math.abs(n-t)<1e-6)return e*(n/t)+(i-e)*(n/t);let s=e*(n/t),o=i-e;return o<=r?s+o:o>=t-r?s+n-(t-o):s+r+(o-r)*(n-2*r)/(t-2*r)}function Zo(i,e,t,n,r){return[E0(i*n,t*n,n,r)/r,E0(e*n,t*n,n,r)/r]}var R0=new WeakMap;function jo(i,e,t,n){let[r,s,o]=i.size;if(i.vehicle||i.stretch||Math.abs(e-r)<1e-4&&Math.abs(t-s)<1e-4&&Math.abs(n-o)<1e-4)return i.parts;let a=`${e.toFixed(4)}|${t.toFixed(4)}|${n.toFixed(4)}`,l=R0.get(i),c=l?.get(a);if(c)return c;let u=i.parts.map(h=>{if(h.shape==="sweep")return h;let[f,d]=Zo(h.x-h.w/2,h.x+h.w/2,-.5,r,e),[p,x]=Zo(h.z-h.d/2,h.z+h.d/2,-.5,s,t),[g,m]=Zo(h.y,h.y+h.h,0,o,n);if(h.rot)return{...h,x:(f+d)/2,z:(p+x)/2,w:h.w*r/e,d:h.d*s/t,y:g,h:m-g};let b={...h,x:(f+d)/2,z:(p+x)/2,w:d-f,d:x-p,y:g,h:m-g};if(h.shape==="loft"){let[v,y,M,S]=[h.tx??h.x,h.tz??h.z,h.tw??h.w,h.td??h.d],[_,w]=Zo(v-M/2,v+M/2,-.5,r,e),[R,A]=Zo(y-S/2,y+S/2,-.5,s,t);Object.assign(b,{tx:(_+w)/2,tz:(R+A)/2,tw:w-_,td:A-R})}return b});return l||R0.set(i,l=new Map),l.size>32&&l.clear(),l.set(a,u),u}var P0=i=>!!i?.parts.some(e=>e.move);function I0(i,e){if(e===null)return Math.min(1,Math.max(0,i.cover_rest??1));let t=Math.min(1,Math.max(0,e/100));return i.cover==="extends"?t:1-t}function L0(i,e){let t=[];for(let n of i){if(!n.move)continue;let r={...n},s=(o,a)=>a+(o-a)*e;if(n.move==="down"){let[o,a]=[s(n.y,1),s(n.y+n.h,1)];Object.assign(r,{y:o,h:a-o})}else if(n.move==="left"||n.move==="right"){let o=n.move==="left"?-.5:.5,[a,l]=[s(n.x-n.w/2,o),s(n.x+n.w/2,o)];if(Object.assign(r,{x:(a+l)/2,w:Math.abs(l-a)}),n.tx!==void 0||n.tw!==void 0){let[c,u]=[s((n.tx??n.x)-(n.tw??n.w)/2,o),s((n.tx??n.x)+(n.tw??n.w)/2,o)];Object.assign(r,{tx:(c+u)/2,tw:Math.abs(u-c)})}}else if(n.move==="out"){let[o,a]=[s(n.z-n.d/2,-.5),s(n.z+n.d/2,-.5)];if(Object.assign(r,{z:(o+a)/2,d:a-o}),n.tz!==void 0||n.td!==void 0){let[l,c]=[s((n.tz??n.z)-(n.td??n.d)/2,-.5),s((n.tz??n.z)+(n.td??n.d)/2,-.5)];Object.assign(r,{tz:(l+c)/2,td:c-l})}}else{let o=(1-e)*n.w*(n.move==="slide_left"?-1:1);Object.assign(r,{x:n.x+o,...n.tx!==void 0?{tx:n.tx+o}:{}})}r.w>.002&&r.d>.002&&r.h>.002&&t.push(r)}return t}function Gt(i,e){return e.mount_y!=null?e.mount_y:d1(i,e)+(f1(e)?0:v0(i,e.x,e.z))}var f1=i=>i.type==="led_strip"||vt(i.type)?.mount==="ceiling";function d1(i,e){if(e.type==="lamp_wall")return Fl;if(e.type==="led_strip")return Math.max(0,Gh(i,e.x,e.z)-.04-Math.max(.02,e.h));let t=vt(e.type);if(!t)return jr(e);switch(t.mount){case"surface":return M0(i,e.x,e.z);case"wall":return t.wall_y??1;case"ceiling":return Math.max(0,Ol(i,e)-e.h);default:return 0}}var F0=null,O0=new Set,N0=i=>{F0=i},D0=()=>F0,U0=i=>{O0.add(i)};function Dl(i){let e=Jo.get(i)?.mesh;return e!==void 0&&O0.has(e)}var Ig=0,If=1,Lg=2;var ka=1,Fg=2,bo=3,Ti=0,un=1,ut=2,ms=0,Ai=1,Ft=2,Lf=3,za=4,Og=5;var gs=100,Ng=101,Dg=102,Ug=103,Bg=104,kg=200,zg=201,Vg=202,Gg=203,Ff=204,Of=205,Hg=206,Wg=207,Xg=208,Yg=209,qg=210,$g=211,Kg=212,Zg=213,Jg=214,mc=0,gc=1,xc=2,ro=3,bc=4,yc=5,_c=6,vc=7,kc=0,jg=1,Qg=2,Ei=0,Nf=1,Df=2,Uf=3,Bf=4,kf=5,zf=6,Vf=7,mf="attached",ex="detached",Gf=300,xs=301,yo=302,zc=303,Vc=304,kn=1e3,ln=1001,Rr=1002,Ut=1003,_o=1004;var ar=1005;var Ht=1006,Dr=1007;var Fn=1008;var On=1009,Hf=1010,Wf=1011,vo=1012,Gc=1013,oi=1014,Vn=1015,ai=1016,Hc=1017,Wc=1018,bs=1020,Xf=35902,Yf=35899,qf=1021,$f=1022,Nn=1023,$i=1026,lr=1027,Xc=1028,Yc=1029,Ur=1030,qc=1031;var $c=1033,Va=33776,Ga=33777,Ha=33778,Wa=33779,Kc=35840,Zc=35841,Jc=35842,jc=35843,Qc=36196,eu=37492,tu=37496,nu=37488,iu=37489,Xa=37490,ru=37491,su=37808,ou=37809,au=37810,lu=37811,cu=37812,uu=37813,hu=37814,fu=37815,du=37816,pu=37817,mu=37818,gu=37819,xu=37820,bu=37821,yu=36492,_u=36494,vu=36495,Mu=36283,Su=36284,Ya=36285,wu=36286;var Ki=2300,Zi=2301,dc=2302,gf=2303,xf=2400,bf=2401,yf=2402,tx=2500;var Kf=0,qa=1,Mo=2,nx=3200;var $a=0,ix=1,li="",ft="srgb",Mn="srgb-linear",pa="linear",Mt="srgb";var pc=7680;var rx=519,sx=512,ox=513,ax=514,Zf=515,lx=516,cx=517,Jf=518,jf=519,Qf=35044,ed=35048;var td="300 es",$n=2e3,so=2001;function p1(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function m1(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function oo(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function ux(){let i=oo("canvas");return i.style.display="block",i}var B0={},ao=null;function ma(...i){let e="THREE."+i.shift();ao?ao("log",e,...i):console.log(e,...i)}function hx(i){let e=i[0];if(typeof e=="string"&&e.startsWith("TSL:")){let t=i[1];t&&t.isStackTrace?i[0]+=" "+t.getLocation():i[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return i}function Le(...i){i=hx(i);let e="THREE."+i.shift();if(ao)ao("warn",e,...i);else{let t=i[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...i)}}function Ge(...i){i=hx(i);let e="THREE."+i.shift();if(ao)ao("error",e,...i);else{let t=i[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...i)}}function os(...i){let e=i.join(" ");e in B0||(B0[e]=!0,Le(...i))}function fx(i,e,t){return new Promise(function(n,r){function s(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:r();break;case i.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:n()}}setTimeout(s,t)})}var dx={[mc]:mc,[xc]:_c,[bc]:bc,[ro]:yc,[gc]:gc,[_c]:xc,[vc]:vc,[yc]:ro},yi=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let r=n.slice(0);for(let s=0,o=r.length;s>8&255]+dn[i>>16&255]+dn[i>>24&255]+"-"+dn[e&255]+dn[e>>8&255]+"-"+dn[e>>16&15|64]+dn[e>>24&255]+"-"+dn[t&63|128]+dn[t>>8&255]+"-"+dn[t>>16&255]+dn[t>>24&255]+dn[n&255]+dn[n>>8&255]+dn[n>>16&255]+dn[n>>24&255]).toLowerCase()}function it(i,e,t){return Math.max(e,Math.min(t,i))}function nd(i,e){return(i%e+e)%e}function g1(i,e,t,n,r){return n+(i-e)*(r-n)/(t-e)}function x1(i,e,t){return i!==e?(t-i)/(e-i):0}function da(i,e,t){return(1-t)*i+t*e}function b1(i,e,t,n){return da(i,e,1-Math.exp(-t*n))}function y1(i,e=1){return e-Math.abs(nd(i,e*2)-e)}function _1(i,e,t){return i<=e?0:i>=t?1:(i=(i-e)/(t-e),i*i*(3-2*i))}function v1(i,e,t){return i<=e?0:i>=t?1:(i=(i-e)/(t-e),i*i*i*(i*(i*6-15)+10))}function M1(i,e){return i+Math.floor(Math.random()*(e-i+1))}function S1(i,e){return i+Math.random()*(e-i)}function w1(i){return i*(.5-Math.random())}function T1(i){i!==void 0&&(k0=i);let e=k0+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function A1(i){return i*fa}function E1(i){return i*as}function R1(i){return i>0&&Number.isInteger(i)&&2**Math.round(Math.log2(i))===i}function C1(i){return Math.pow(2,Math.ceil(Math.log(i)/Math.LN2))}function id(i){return Math.pow(2,Math.floor(Math.log(i)/Math.LN2))}function P1(i,e,t,n,r){let s=Math.cos,o=Math.sin,a=s(t/2),l=o(t/2),c=s((e+n)/2),u=o((e+n)/2),h=s((e-n)/2),f=o((e-n)/2),d=s((n-e)/2),p=o((n-e)/2);switch(r){case"XYX":i.set(a*u,l*h,l*f,a*c);break;case"YZY":i.set(l*f,a*u,l*h,a*c);break;case"ZXZ":i.set(l*h,l*f,a*u,a*c);break;case"XZX":i.set(a*u,l*p,l*d,a*c);break;case"YXY":i.set(l*d,a*u,l*p,a*c);break;case"ZYZ":i.set(l*p,l*d,a*u,a*c);break;default:Le("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}function Tu(i){switch(i.constructor){case Uint32Array:return 4294967295;case Uint16Array:return 65535;case Uint8Array:case Uint8ClampedArray:return 255;case Int32Array:return 2147483647;case Int16Array:return 32767;case Int8Array:return 127;default:return}}function rd(i,e){if(e.constructor===Float32Array)return i;let t=Tu(e);if(t===void 0)throw new Error("THREE.MathUtils: Invalid component type.");return Math.max(i/t,-1)}function sd(i,e){if(e.constructor===Float32Array)return i;let t=Tu(e);if(t===void 0)throw new Error("THREE.MathUtils: Invalid component type.");return Math.round(i*t)}var Br={DEG2RAD:fa,RAD2DEG:as,generateUUID:Ri,clamp:it,euclideanModulo:nd,mapLinear:g1,inverseLerp:x1,lerp:da,damp:b1,pingpong:y1,smoothstep:_1,smootherstep:v1,randInt:M1,randFloat:S1,randFloatSpread:w1,seededRandom:T1,degToRad:A1,radToDeg:E1,isPowerOfTwo:R1,ceilPowerOfTwo:C1,floorPowerOfTwo:id,setQuaternionFromProperEuler:P1,normalize:sd,denormalize:rd},ud=class ud{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=it(this.x,e.x,t.x),this.y=it(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=it(this.x,e,t),this.y=it(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(it(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(it(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),s=this.x-e.x,o=this.y-e.y;return this.x=s*n-o*r+e.x,this.y=s*r+o*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};ud.prototype.isVector2=!0;var De=ud,Sn=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,s,o,a){let l=n[r+0],c=n[r+1],u=n[r+2],h=n[r+3],f=s[o+0],d=s[o+1],p=s[o+2],x=s[o+3];if(h!==x||l!==f||c!==d||u!==p){let g=l*f+c*d+u*p+h*x;g<0&&(f=-f,d=-d,p=-p,x=-x,g=-g);let m=1-a;if(g<.9995){let b=Math.acos(g),v=Math.sin(b);m=Math.sin(m*b)/v,a=Math.sin(a*b)/v,l=l*m+f*a,c=c*m+d*a,u=u*m+p*a,h=h*m+x*a}else{l=l*m+f*a,c=c*m+d*a,u=u*m+p*a,h=h*m+x*a;let b=1/Math.sqrt(l*l+c*c+u*u+h*h);l*=b,c*=b,u*=b,h*=b}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=h}static multiplyQuaternionsFlat(e,t,n,r,s,o){let a=n[r],l=n[r+1],c=n[r+2],u=n[r+3],h=s[o],f=s[o+1],d=s[o+2],p=s[o+3];return e[t]=a*p+u*h+l*d-c*f,e[t+1]=l*p+u*f+c*h-a*d,e[t+2]=c*p+u*d+a*f-l*h,e[t+3]=u*p-a*h-l*f-c*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,s=e._z,o=e._order,a=Math.cos,l=Math.sin,c=a(n/2),u=a(r/2),h=a(s/2),f=l(n/2),d=l(r/2),p=l(s/2);switch(o){case"XYZ":this._x=f*u*h+c*d*p,this._y=c*d*h-f*u*p,this._z=c*u*p+f*d*h,this._w=c*u*h-f*d*p;break;case"YXZ":this._x=f*u*h+c*d*p,this._y=c*d*h-f*u*p,this._z=c*u*p-f*d*h,this._w=c*u*h+f*d*p;break;case"ZXY":this._x=f*u*h-c*d*p,this._y=c*d*h+f*u*p,this._z=c*u*p+f*d*h,this._w=c*u*h-f*d*p;break;case"ZYX":this._x=f*u*h-c*d*p,this._y=c*d*h+f*u*p,this._z=c*u*p-f*d*h,this._w=c*u*h+f*d*p;break;case"YZX":this._x=f*u*h+c*d*p,this._y=c*d*h+f*u*p,this._z=c*u*p-f*d*h,this._w=c*u*h-f*d*p;break;case"XZY":this._x=f*u*h-c*d*p,this._y=c*d*h-f*u*p,this._z=c*u*p+f*d*h,this._w=c*u*h+f*d*p;break;default:Le("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],s=t[8],o=t[1],a=t[5],l=t[9],c=t[2],u=t[6],h=t[10],f=n+a+h;if(f>0){let d=.5/Math.sqrt(f+1);this._w=.25/d,this._x=(u-l)*d,this._y=(s-c)*d,this._z=(o-r)*d}else if(n>a&&n>h){let d=2*Math.sqrt(1+n-a-h);this._w=(u-l)/d,this._x=.25*d,this._y=(r+o)/d,this._z=(s+c)/d}else if(a>h){let d=2*Math.sqrt(1+a-n-h);this._w=(s-c)/d,this._x=(r+o)/d,this._y=.25*d,this._z=(l+u)/d}else{let d=2*Math.sqrt(1+h-n-a);this._w=(o-r)/d,this._x=(s+c)/d,this._y=(l+u)/d,this._z=.25*d}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(it(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,s=e._z,o=e._w,a=t._x,l=t._y,c=t._z,u=t._w;return this._x=n*u+o*a+r*c-s*l,this._y=r*u+o*l+s*a-n*c,this._z=s*u+o*c+n*l-r*a,this._w=o*u-n*a-r*l-s*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,s=e._z,o=e._w,a=this.dot(e);a<0&&(n=-n,r=-r,s=-s,o=-o,a=-a);let l=1-t;if(a<.9995){let c=Math.acos(a),u=Math.sin(c);l=Math.sin(l*c)/u,t=Math.sin(t*c)/u,this._x=this._x*l+n*t,this._y=this._y*l+r*t,this._z=this._z*l+s*t,this._w=this._w*l+o*t,this._onChangeCallback()}else this._x=this._x*l+n*t,this._y=this._y*l+r*t,this._z=this._z*l+s*t,this._w=this._w*l+o*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),s=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},hd=class hd{constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("THREE.Vector3: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(z0.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(z0.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6]*r,this.y=s[1]*t+s[4]*n+s[7]*r,this.z=s[2]*t+s[5]*n+s[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,s=e.elements,o=1/(s[3]*t+s[7]*n+s[11]*r+s[15]);return this.x=(s[0]*t+s[4]*n+s[8]*r+s[12])*o,this.y=(s[1]*t+s[5]*n+s[9]*r+s[13])*o,this.z=(s[2]*t+s[6]*n+s[10]*r+s[14])*o,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,s=e.x,o=e.y,a=e.z,l=e.w,c=2*(o*r-a*n),u=2*(a*t-s*r),h=2*(s*n-o*t);return this.x=t+l*c+o*h-a*u,this.y=n+l*u+a*c-s*h,this.z=r+l*h+s*u-o*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*r,this.y=s[1]*t+s[5]*n+s[9]*r,this.z=s[2]*t+s[6]*n+s[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=it(this.x,e.x,t.x),this.y=it(this.y,e.y,t.y),this.z=it(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=it(this.x,e,t),this.y=it(this.y,e,t),this.z=it(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(it(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,s=e.z,o=t.x,a=t.y,l=t.z;return this.x=r*l-s*a,this.y=s*o-n*l,this.z=n*a-r*o,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Hh.copy(this).projectOnVector(e),this.sub(Hh)}reflect(e){return this.sub(Hh.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(it(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};hd.prototype.isVector3=!0;var U=hd,Hh=new U,z0=new Sn,fd=class fd{constructor(e,t,n,r,s,o,a,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,s,o,a,l,c)}set(e,t,n,r,s,o,a,l,c){let u=this.elements;return u[0]=e,u[1]=r,u[2]=a,u[3]=t,u[4]=s,u[5]=l,u[6]=n,u[7]=o,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,s=this.elements,o=n[0],a=n[3],l=n[6],c=n[1],u=n[4],h=n[7],f=n[2],d=n[5],p=n[8],x=r[0],g=r[3],m=r[6],b=r[1],v=r[4],y=r[7],M=r[2],S=r[5],_=r[8];return s[0]=o*x+a*b+l*M,s[3]=o*g+a*v+l*S,s[6]=o*m+a*y+l*_,s[1]=c*x+u*b+h*M,s[4]=c*g+u*v+h*S,s[7]=c*m+u*y+h*_,s[2]=f*x+d*b+p*M,s[5]=f*g+d*v+p*S,s[8]=f*m+d*y+p*_,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],o=e[4],a=e[5],l=e[6],c=e[7],u=e[8];return t*o*u-t*a*c-n*s*u+n*a*l+r*s*c-r*o*l}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],o=e[4],a=e[5],l=e[6],c=e[7],u=e[8],h=u*o-a*c,f=a*l-u*s,d=c*s-o*l,p=t*h+n*f+r*d;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let x=1/p;return e[0]=h*x,e[1]=(r*c-u*n)*x,e[2]=(a*n-r*o)*x,e[3]=f*x,e[4]=(u*t-r*l)*x,e[5]=(r*s-a*t)*x,e[6]=d*x,e[7]=(n*l-c*t)*x,e[8]=(o*t-n*s)*x,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,s,o,a){let l=Math.cos(s),c=Math.sin(s);return this.set(n*l,n*c,-n*(l*o+c*a)+o+e,-r*c,r*l,-r*(-c*o+l*a)+a+t,0,0,1),this}scale(e,t){return os("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(Wh.makeScale(e,t)),this}rotate(e){return os("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(Wh.makeRotation(-e)),this}translate(e,t){return os("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(Wh.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let r=0;r<9;r++)if(t[r]!==n[r])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}};fd.prototype.isMatrix3=!0;var He=fd,Wh=new He,V0=new He().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),G0=new He().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function I1(){let i={enabled:!0,workingColorSpace:Mn,spaces:{},convert:function(r,s,o){return this.enabled===!1||s===o||!s||!o||(this.spaces[s].transfer===Mt&&(r.r=qi(r.r),r.g=qi(r.g),r.b=qi(r.b)),this.spaces[s].primaries!==this.spaces[o].primaries&&(r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===Mt&&(r.r=io(r.r),r.g=io(r.g),r.b=io(r.b))),r},workingToColorSpace:function(r,s){return this.convert(r,this.workingColorSpace,s)},colorSpaceToWorking:function(r,s){return this.convert(r,s,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===li?pa:this.spaces[r].transfer},getToneMappingMode:function(r){return this.spaces[r].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(r,s=this.workingColorSpace){return r.fromArray(this.spaces[s].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,s,o){return r.copy(this.spaces[o].fromXYZ).multiply(this.spaces[s].toXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[Mn]:{primaries:e,whitePoint:n,transfer:pa,toXYZ:V0,fromXYZ:G0,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:ft},outputColorSpaceConfig:{drawingBufferColorSpace:ft}},[ft]:{primaries:e,whitePoint:n,transfer:Mt,toXYZ:V0,fromXYZ:G0,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:ft}}}),i}var tt=I1();function qi(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function io(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}var ks,lo=class{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{ks===void 0&&(ks=oo("canvas")),ks.width=e.width,ks.height=e.height;let r=ks.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),n=ks}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){let t=oo("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),s=r.data;for(let o=0;o1),this.pmremVersion=0,this.isPMREMTexture=!1,this.normalized=!1}get width(){return this.source.getSize(Yh).x}get height(){return this.source.getSize(Yh).y}get depth(){return this.source.getSize(Yh).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.mipmapsAutoUpdate=e.mipmapsAutoUpdate,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isPMREMTexture=e.isPMREMTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){Le(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){Le(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,mipmapsAutoUpdate:this.mipmapsAutoUpdate,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Gf)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case kn:e.x=e.x-Math.floor(e.x);break;case ln:e.x=e.x<0?0:1;break;case Rr:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case kn:e.y=e.y-Math.floor(e.y);break;case ln:e.y=e.y<0?0:1;break;case Rr:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Kt.DEFAULT_IMAGE=null;Kt.DEFAULT_MAPPING=Gf;Kt.DEFAULT_ANISOTROPY=1;var dd=class dd{constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("THREE.Vector4: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,s=this.w,o=e.elements;return this.x=o[0]*t+o[4]*n+o[8]*r+o[12]*s,this.y=o[1]*t+o[5]*n+o[9]*r+o[13]*s,this.z=o[2]*t+o[6]*n+o[10]*r+o[14]*s,this.w=o[3]*t+o[7]*n+o[11]*r+o[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,s,l=e.elements,c=l[0],u=l[4],h=l[8],f=l[1],d=l[5],p=l[9],x=l[2],g=l[6],m=l[10];if(Math.abs(u-f)<.01&&Math.abs(h-x)<.01&&Math.abs(p-g)<.01){if(Math.abs(u+f)<.1&&Math.abs(h+x)<.1&&Math.abs(p+g)<.1&&Math.abs(c+d+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let v=(c+1)/2,y=(d+1)/2,M=(m+1)/2,S=(u+f)/4,_=(h+x)/4,w=(p+g)/4;return v>y&&v>M?v<.01?(n=0,r=.707106781,s=.707106781):(n=Math.sqrt(v),r=S/n,s=_/n):y>M?y<.01?(n=.707106781,r=0,s=.707106781):(r=Math.sqrt(y),n=S/r,s=w/r):M<.01?(n=.707106781,r=.707106781,s=0):(s=Math.sqrt(M),n=_/s,r=w/s),this.set(n,r,s,t),this}let b=Math.sqrt((g-p)*(g-p)+(h-x)*(h-x)+(f-u)*(f-u));return Math.abs(b)<.001&&(b=1),this.x=(g-p)/b,this.y=(h-x)/b,this.z=(f-u)/b,this.w=Math.acos((c+d+m-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=it(this.x,e.x,t.x),this.y=it(this.y,e.y,t.y),this.z=it(this.z,e.z,t.z),this.w=it(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=it(this.x,e,t),this.y=it(this.y,e,t),this.z=it(this.z,e,t),this.w=it(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(it(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};dd.prototype.isVector4=!0;var _t=dd,Mc=class extends yi{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ht,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new _t(0,0,e,t),this.scissorTest=!1,this.viewport=new _t(0,0,e,t),this.textures=[];let r=n.count;for(let s=0;s1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let n=0;n0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(a=>({...a})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function s(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=s(e.geometries,this.geometry);let a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){let l=a.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c0){r.children=[];for(let a=0;a0){r.animations=[];for(let a=0;a0&&(n.geometries=a),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),u.length>0&&(n.images=u),h.length>0&&(n.shapes=h),f.length>0&&(n.skeletons=f),d.length>0&&(n.animations=d),p.length>0&&(n.nodes=p)}return n.object=r,n;function o(a){let l=[];for(let c in a){let u=a[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot!==null?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;nd+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&f<=d-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,n),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.quaternion,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));a!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&s!==null&&(r=s),r!==null&&(a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.matrixWorldNeedsUpdate=!0,r.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(r.linearVelocity)):a.hasLinearVelocity=!1,r.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(r.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(z1)))}return a!==null&&(a.visible=r!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new ct;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},px={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Sr={h:0,s:0,l:0},kl={h:0,s:0,l:0};function $h(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}var W=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=ft){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,tt.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=tt.workingColorSpace){return this.r=e,this.g=t,this.b=n,tt.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=tt.workingColorSpace){if(e=nd(e,1),t=it(t,0,1),n=it(n,0,1),t===0)this.r=this.g=this.b=n;else{let s=n<=.5?n*(1+t):n+t-n*t,o=2*n-s;this.r=$h(o,s,e+1/3),this.g=$h(o,s,e),this.b=$h(o,s,e-1/3)}return tt.colorSpaceToWorking(this,r),this}setStyle(e,t=ft){function n(s){s!==void 0&&parseFloat(s)<1&&Le("Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let s,o=r[1],a=r[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?|\.\d+)\s*)?$/.exec(a))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+(?:\.\d+)?|\.\d+)\%\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*(?:,\s*(\d+(?:\.\d+)?|\.\d+)\s*)?$/.exec(a))return n(s[4]),this.setRGB(Math.min(100,parseFloat(s[1]))/100,Math.min(100,parseFloat(s[2]))/100,Math.min(100,parseFloat(s[3]))/100,t);break;case"hsl":case"hsla":if(s=/^\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*,\s*(\d+(?:\.\d+)?|\.\d+)\%\s*(?:,\s*(\d+(?:\.\d+)?|\.\d+)\s*)?$/.exec(a))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:Le("Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let s=r[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(s,16),t);Le("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=ft){let n=px[e.toLowerCase()];return n!==void 0?this.setHex(n,t):Le("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=qi(e.r),this.g=qi(e.g),this.b=qi(e.b),this}copyLinearToSRGB(e){return this.r=io(e.r),this.g=io(e.g),this.b=io(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=ft){return tt.workingToColorSpace(pn.copy(this),e),Math.round(it(pn.r*255,0,255))*65536+Math.round(it(pn.g*255,0,255))*256+Math.round(it(pn.b*255,0,255))}getHexString(e=ft){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=tt.workingColorSpace){tt.workingToColorSpace(pn.copy(this),t);let n=pn.r,r=pn.g,s=pn.b,o=Math.max(n,r,s),a=Math.min(n,r,s),l,c,u=(a+o)/2;if(a===o)l=0,c=0;else{let h=o-a;switch(c=u<=.5?h/(o+a):h/(2-o-a),o){case n:l=(r-s)/h+(r0?r.multiplyScalar(1/Math.sqrt(s)):r.set(0,0,0)}static getBarycoord(e,t,n,r,s){ii.subVectors(r,t),Vi.subVectors(n,t),Kh.subVectors(e,t);let o=ii.dot(ii),a=ii.dot(Vi),l=ii.dot(Kh),c=Vi.dot(Vi),u=Vi.dot(Kh),h=o*c-a*a;if(h===0)return s.set(0,0,0),null;let f=1/h,d=(c*l-a*u)*f,p=(o*u-a*l)*f;return s.set(1-d-p,p,d)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Gi)===null?!1:Gi.x>=0&&Gi.y>=0&&Gi.x+Gi.y<=1}static getInterpolation(e,t,n,r,s,o,a,l){return this.getBarycoord(e,t,n,r,Gi)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,Gi.x),l.addScaledVector(o,Gi.y),l.addScaledVector(a,Gi.z),l)}static getInterpolatedAttribute(e,t,n,r,s,o){return Qh.setScalar(0),ef.setScalar(0),tf.setScalar(0),Qh.fromBufferAttribute(e,t),ef.fromBufferAttribute(e,n),tf.fromBufferAttribute(e,r),o.setScalar(0),o.addScaledVector(Qh,s.x),o.addScaledVector(ef,s.y),o.addScaledVector(tf,s.z),o}static isFrontFacing(e,t,n,r){return ii.subVectors(n,t),Vi.subVectors(e,t),ii.cross(Vi).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return ii.subVectors(this.c,this.b),Vi.subVectors(this.a,this.b),ii.cross(Vi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return i.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return i.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,r,s){return i.getInterpolation(e,this.a,this.b,this.c,t,n,r,s)}containsPoint(e){return i.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return i.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,s=this.c,o,a;Hs.subVectors(r,n),Ws.subVectors(s,n),Zh.subVectors(e,n);let l=Hs.dot(Zh),c=Ws.dot(Zh);if(l<=0&&c<=0)return t.copy(n);Jh.subVectors(e,r);let u=Hs.dot(Jh),h=Ws.dot(Jh);if(u>=0&&h<=u)return t.copy(r);let f=l*h-u*c;if(f<=0&&l>=0&&u<=0&&l-u>0)return o=l/(l-u),t.copy(n).addScaledVector(Hs,o);jh.subVectors(e,s);let d=Hs.dot(jh),p=Ws.dot(jh);if(p>=0&&d<=p)return t.copy(s);let x=d*c-l*p;if(x<=0&&c>=0&&p<=0)return a=c/(c-p),t.copy(n).addScaledVector(Ws,a);let g=u*p-d*h;if(g<=0&&h-u>=0&&d-p>=0)return Z0.subVectors(s,r),a=(h-u)/(h-u+(d-p)),t.copy(r).addScaledVector(Z0,a);let m=1/(g+x+f);return o=x*m,a=f*m,t.copy(n).addScaledVector(Hs,o).addScaledVector(Ws,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Ct=class{constructor(e=new U(1/0,1/0,1/0),t=new U(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,ri),ri.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ea),Vl.subVectors(this.max,ea),Xs.subVectors(e.a,ea),Ys.subVectors(e.b,ea),qs.subVectors(e.c,ea),wr.subVectors(Ys,Xs),Tr.subVectors(qs,Ys),ns.subVectors(Xs,qs);let t=[0,-wr.z,wr.y,0,-Tr.z,Tr.y,0,-ns.z,ns.y,wr.z,0,-wr.x,Tr.z,0,-Tr.x,ns.z,0,-ns.x,-wr.y,wr.x,0,-Tr.y,Tr.x,0,-ns.y,ns.x,0];return!nf(t,Xs,Ys,qs,Vl)||(t=[1,0,0,0,1,0,0,0,1],!nf(t,Xs,Ys,qs,Vl))?!1:(Gl.crossVectors(wr,Tr),t=[Gl.x,Gl.y,Gl.z],nf(t,Xs,Ys,qs,Vl))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ri).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ri).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Hi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Hi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Hi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Hi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Hi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Hi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Hi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Hi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Hi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},Hi=[new U,new U,new U,new U,new U,new U,new U,new U],ri=new U,zl=new Ct,Xs=new U,Ys=new U,qs=new U,wr=new U,Tr=new U,ns=new U,ea=new U,Vl=new U,Gl=new U,is=new U;function nf(i,e,t,n,r){for(let s=0,o=i.length-3;s<=o;s+=3){is.fromArray(i,s);let a=r.x*Math.abs(is.x)+r.y*Math.abs(is.y)+r.z*Math.abs(is.z),l=e.dot(is),c=t.dot(is),u=n.dot(is);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>a)return!1}return!0}var $t=new U,Hl=new De,V1=0,wt=class extends yi{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:V1++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Qf,this.updateRanges=[],this.gpuType=Vn,this.version=0,this._normalizationScale=e!==void 0?Tu(e):void 0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this._normalizationScale=e._normalizationScale,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,s=this.itemSize;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;ta.subVectors(e,this.center);let t=ta.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),r=(n-this.radius)*.5;this.center.addScaledVector(ta,r/n),this.radius+=r}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(rf.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ta.copy(e.center).add(rf)),this.expandByPoint(ta.copy(e.center).sub(rf))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},H1=0,qn=new Be,sf=new Et,$s=new U,Bn=new Ct,na=new Ct,rn=new U,Fe=class i extends yi{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:H1++}),this.uuid=Ri(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(p1(e)?cs:xa)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let s=new He().getNormalMatrix(e);n.applyNormalMatrix(s),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return qn.makeRotationFromQuaternion(e),this.applyMatrix4(qn),this}rotateX(e){return qn.makeRotationX(e),this.applyMatrix4(qn),this}rotateY(e){return qn.makeRotationY(e),this.applyMatrix4(qn),this}rotateZ(e){return qn.makeRotationZ(e),this.applyMatrix4(qn),this}translate(e,t,n){return qn.makeTranslation(e,t,n),this.applyMatrix4(qn),this}scale(e,t,n){return qn.makeScale(e,t,n),this.applyMatrix4(qn),this}lookAt(e){return sf.lookAt(e),sf.updateMatrix(),this.applyMatrix4(sf.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter($s).negate(),this.translate($s.x,$s.y,$s.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let n=[];for(let r=0,s=e.length;rt.count&&Le("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Ct);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ge("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new U(-1/0,-1/0,-1/0),new U(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,r=t.length;n0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let l in n){let c=n[l];e.data.attributes[l]=c.toJSON(e.data)}let r={},s=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],u=[];for(let h=0,f=c.length;h0&&(r[l]=u,s=!0)}s&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));let a=this.boundingSphere;return a!==null&&(e.data.boundingSphere=a.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let c in r){let u=r[c];this.setAttribute(c,u.clone(t))}let s=e.morphAttributes;for(let c in s){let u=[],h=s[c];for(let f=0,d=h.length;f1)?null:t.copy(e.start).addScaledVector(r,o)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||X1.getNormalMatrix(e),r=this.coplanarPoint(of).applyMatrix4(e),s=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}},Y1=0,mn=class extends yi{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Y1++}),this.uuid=Ri(),this.name="",this.type="Material",this.blending=Ai,this.side=Ti,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Ff,this.blendDst=Of,this.blendEquation=gs,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new W(0,0,0),this.blendAlpha=0,this.depthFunc=ro,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=rx,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=pc,this.stencilZFail=pc,this.stencilZPass=pc,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){Le(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){Le(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector2&&n&&n.isVector2||r&&r.isEuler&&n&&n.isEuler||r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.diffuseRoughness!==void 0&&(n.diffuseRoughness=this.diffuseRoughness),this.diffuseRoughnessMap&&this.diffuseRoughnessMap.isTexture&&(n.diffuseRoughnessMap=this.diffuseRoughnessMap.toJSON(e).uuid),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessMinimum!==void 0&&(n.iridescenceThicknessMinimum=this.iridescenceThicknessMinimum),this.iridescenceThicknessMaximum!==void 0&&(n.iridescenceThicknessMaximum=this.iridescenceThicknessMaximum),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(s=>s.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(s){let o=[];for(let a in s){let l=s[a];delete l.metadata,o.push(l)}return o}if(t){let s=r(e.textures),o=r(e.images);s.length>0&&(n.textures=s),o.length>0&&(n.images=o)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new W().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.diffuseRoughness!==void 0&&(this.diffuseRoughness=e.diffuseRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.retroreflectivity!==void 0&&(this.retroreflectivity=e.retroreflectivity),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessMinimum!==void 0&&(this.iridescenceThicknessMinimum=e.iridescenceThicknessMinimum),e.iridescenceThicknessMaximum!==void 0&&(this.iridescenceThicknessMaximum=e.iridescenceThicknessMaximum),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],this.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1]),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.clippingPlanes!==void 0&&(this.clippingPlanes=e.clippingPlanes.map(n=>new si().fromJSON(n))),e.clipIntersection!==void 0&&(this.clipIntersection=e.clipIntersection),e.clipShadows!==void 0&&(this.clipShadows=e.clipShadows),e.depthPacking!==void 0&&(this.depthPacking=e.depthPacking),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.linecap!==void 0&&(this.linecap=e.linecap),e.linejoin!==void 0&&(this.linejoin=e.linejoin),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let n=e.normalScale;Array.isArray(n)===!1&&(n=[n,n]),this.normalScale=new De().fromArray(n)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new De().fromArray(e.clearcoatNormalScale)),e.diffuseRoughnessMap!==void 0&&(this.diffuseRoughnessMap=t[e.diffuseRoughnessMap]||null),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let r=t.length;n=new Array(r);for(let s=0;s!==r;++s)n[s]=t[s].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}},vi=class extends mn{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new W(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Ks,ia=new U,Zs=new U,Js=new U,js=new De,ra=new De,mx=new Be,Wl=new U,sa=new U,Xl=new U,j0=new De,af=new De,Q0=new De,ji=class extends Et{constructor(e=new vi){if(super(),this.isSprite=!0,this.type="Sprite",Ks===void 0){Ks=new Fe;let t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),n=new us(t,5);Ks.setIndex([0,1,2,0,2,3]),Ks.setAttribute("position",new Cr(n,3,0,!1)),Ks.setAttribute("uv",new Cr(n,2,3,!1))}this.geometry=Ks,this.material=e,this.center=new De(.5,.5),this.count=1}intersectsFrustum(e){return e.intersectsSprite(this)}raycast(e,t){e.camera===null&&Ge('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),Zs.setFromMatrixScale(this.matrixWorld),mx.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),Js.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Zs.multiplyScalar(-Js.z);let n=this.material.rotation,r,s;n!==0&&(s=Math.cos(n),r=Math.sin(n));let o=this.center;Yl(Wl.set(-.5,-.5,0),Js,o,Zs,r,s),Yl(sa.set(.5,-.5,0),Js,o,Zs,r,s),Yl(Xl.set(.5,.5,0),Js,o,Zs,r,s),j0.set(0,0),af.set(1,0),Q0.set(1,1);let a=e.ray.intersectTriangle(Wl,sa,Xl,!1,ia);if(a===null&&(Yl(sa.set(-.5,.5,0),Js,o,Zs,r,s),af.set(0,1),a=e.ray.intersectTriangle(Wl,Xl,sa,!1,ia),a===null))return;let l=e.ray.origin.distanceTo(ia);le.far||t.push({distance:l,point:ia.clone(),uv:Yi.getInterpolation(ia,Wl,sa,Xl,j0,af,Q0,new De),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}toJSON(e){let t=super.toJSON(e);return t.object.center=this.center.toArray(),t}};function Yl(i,e,t,n,r,s){js.subVectors(i,t).addScalar(.5).multiply(n),r!==void 0?(ra.x=s*js.x-r*js.y,ra.y=r*js.x+s*js.y):ra.copy(js),i.copy(e),i.x+=ra.x,i.y+=ra.y,i.applyMatrix4(mx)}var Wi=new U,lf=new U,ql=new U,$l=new U,Pr=class{constructor(e=new U,t=new U(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Wi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=Wi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Wi.copy(this.origin).addScaledVector(this.direction,t),Wi.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){lf.copy(e).add(t).multiplyScalar(.5),ql.copy(t).sub(e).normalize(),$l.copy(this.origin).sub(lf);let s=e.distanceTo(t)*.5,o=-this.direction.dot(ql),a=$l.dot(this.direction),l=-$l.dot(ql),c=$l.lengthSq(),u=Math.abs(1-o*o),h,f,d,p;if(u>0)if(h=o*l-a,f=o*a-l,p=s*u,h>=0)if(f>=-p)if(f<=p){let x=1/u;h*=x,f*=x,d=h*(h+o*f+2*a)+f*(o*h+f+2*l)+c}else f=s,h=Math.max(0,-(o*f+a)),d=-h*h+f*(f+2*l)+c;else f=-s,h=Math.max(0,-(o*f+a)),d=-h*h+f*(f+2*l)+c;else f<=-p?(h=Math.max(0,-(-o*s+a)),f=h>0?-s:Math.min(Math.max(-s,-l),s),d=-h*h+f*(f+2*l)+c):f<=p?(h=0,f=Math.min(Math.max(-s,-l),s),d=f*(f+2*l)+c):(h=Math.max(0,-(o*s+a)),f=h>0?s:Math.min(Math.max(-s,-l),s),d=-h*h+f*(f+2*l)+c);else f=o>0?-s:s,h=Math.max(0,-(o*f+a)),d=-h*h+f*(f+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,h),r&&r.copy(lf).addScaledVector(ql,f),d}intersectSphere(e,t){if(e.radius<0)return null;Wi.subVectors(e.center,this.origin);let n=Wi.dot(this.direction),r=Wi.dot(Wi)-n*n,s=e.radius*e.radius;if(r>s)return null;let o=Math.sqrt(s-r),a=n-o,l=n+o;return l<0?null:a<0?this.at(l,t):this.at(a,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,s,o,a,l,c=1/this.direction.x,u=1/this.direction.y,h=1/this.direction.z,f=this.origin;return c>=0?(n=(e.min.x-f.x)*c,r=(e.max.x-f.x)*c):(n=(e.max.x-f.x)*c,r=(e.min.x-f.x)*c),u>=0?(s=(e.min.y-f.y)*u,o=(e.max.y-f.y)*u):(s=(e.max.y-f.y)*u,o=(e.min.y-f.y)*u),n>o||s>r||((s>n||isNaN(n))&&(n=s),(o=0?(a=(e.min.z-f.z)*h,l=(e.max.z-f.z)*h):(a=(e.max.z-f.z)*h,l=(e.min.z-f.z)*h),n>l||a>r)||((a>n||n!==n)&&(n=a),(l=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,Wi)!==null}intersectTriangle(e,t,n,r,s){let o=this.origin,a=this.direction,l=a.x,c=a.y,u=a.z,h=e.x-o.x,f=e.y-o.y,d=e.z-o.z,p=t.x-o.x,x=t.y-o.y,g=t.z-o.z,m=n.x-o.x,b=n.y-o.y,v=n.z-o.z,y=Math.abs(l),M=Math.abs(c),S=Math.abs(u),_,w,R,A,C,O,D,P,I,N,F,H;if(y>=M&&y>=S?(R=l,O=h,I=p,H=m,l>=0?(_=c,w=u,A=f,C=d,D=x,P=g,N=b,F=v):(_=u,w=c,A=d,C=f,D=g,P=x,N=v,F=b)):M>=S?(R=c,O=f,I=x,H=b,c>=0?(_=u,w=l,A=d,C=h,D=g,P=p,N=v,F=m):(_=l,w=u,A=h,C=d,D=p,P=g,N=m,F=v)):(R=u,O=d,I=g,H=v,u>=0?(_=l,w=c,A=h,C=f,D=p,P=x,N=m,F=b):(_=c,w=l,A=f,C=h,D=x,P=p,N=b,F=m)),R===0)return null;let B=_/R,X=w/R,V=1/R,re=A-B*O,be=C-X*O,Y=D-B*I,Q=P-X*I,se=N-B*H,Se=F-X*H,le=se*Q-Se*Y,Ie=re*Se-be*se,st=Y*be-Q*re;if(r){if(le<0||Ie<0||st<0)return null}else if((le<0||Ie<0||st<0)&&(le>0||Ie>0||st>0))return null;let Te=le+Ie+st;if(Te===0)return null;let ht=V*(le*O+Ie*I+st*H);return(Te>0?ht<0:ht>0)?null:this.at(ht/Te,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},Ke=class extends mn{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new W(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new _i,this.combine=kc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},eg=new Be,rs=new Pr,Kl=new Cn,tg=new U,Zl=new U,Jl=new U,jl=new U,cf=new U,Ql=new U,ng=new U,ec=new U,we=class extends Et{constructor(e=new Fe,t=new Ke){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0?this.morphTargetInfluences=e.morphTargetInfluences.slice():this.morphTargetInfluences=void 0,e.morphTargetDictionary!==void 0?this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary):this.morphTargetDictionary=void 0,this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let r=t[n[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=r.length;s(e.far-e.near)**2))&&(eg.copy(s).invert(),rs.copy(e.ray).applyMatrix4(eg),!(n.boundingBox!==null&&rs.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,rs)))}_computeIntersections(e,t,n){let r,s=this.geometry,o=this.material,a=s.index,l=s.attributes.position,c=s.attributes.uv,u=s.attributes.uv1,h=s.attributes.normal,f=s.groups,d=s.drawRange;if(a!==null)if(Array.isArray(o))for(let p=0,x=f.length;pt.far?null:{distance:c,point:ec.clone(),object:i}}function tc(i,e,t,n,r,s,o,a,l,c){i.getVertexPosition(a,Zl),i.getVertexPosition(l,Jl),i.getVertexPosition(c,jl);let u=q1(i,e,t,n,Zl,Jl,jl,ng);if(u){let h=new U;Yi.getBarycoord(ng,Zl,Jl,jl,h),r&&(u.uv=Yi.getInterpolatedAttribute(r,a,l,c,h,new De)),s&&(u.uv1=Yi.getInterpolatedAttribute(s,a,l,c,h,new De)),o&&(u.normal=Yi.getInterpolatedAttribute(o,a,l,c,h,new U),u.normal.dot(n.direction)>0&&u.normal.multiplyScalar(-1));let f={a,b:l,c,normal:new U,materialIndex:0};Yi.getNormal(Zl,Jl,jl,f.normal),u.face=f,u.barycoord=h}return u}var oa=new _t,ig=new _t,rg=new _t,$1=new _t,sg=new Be,nc=new U,uf=new Cn,og=new Be,hf=new Pr,ba=class extends we{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=mf,this.bindMatrix=new Be,this.bindMatrixInverse=new Be,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Ct),this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let n=0;n0?e.max.x:e.min.x,rc.y=r.normal.y>0?e.max.y:e.min.y,rc.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(rc)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},ug=new Be,wc=class i{constructor(){this.coordinateSystem=$n,this._frustums=[],this._count=0}setFromArrayCamera(e){let t=e.cameras,n=this._frustums;for(let r=0;r0){let r=t[n[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=r.length;sn)return;ff.applyMatrix4(i.matrixWorld);let c=e.ray.origin.distanceTo(ff);if(!(ce.far))return{distance:c,point:fg.clone().applyMatrix4(i.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:i}}var dg=new U,pg=new U,gn=class extends Pn{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let r=0,s=t.count;r0){let r=t[n[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=r.length;sr.far)return;s.push({distance:c,distanceToRay:Math.sqrt(a),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}var Lr=class extends Kt{constructor(e=[],t,n,r,s,o,a,l,c,u,h,f){super(null,o,a,l,c,u,r,s,h,f),this.isCompressedTexture=!0,this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}};var va=class extends Kt{constructor(e=[],t=xs,n,r,s,o,a,l,c,u){super(e,t,n,r,s,o,a,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},zt=class extends Kt{constructor(e,t,n,r,s,o,a,l,c){super(e,t,n,r,s,o,a,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}};var er=class extends Kt{constructor(e,t,n=oi,r,s,o,a=Ut,l=Ut,c,u=$i,h=1){if(u!==$i&&u!==lr)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let f={width:e,height:t,depth:h};super(f,r,s,o,a,l,u,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Ji(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}},Ma=class extends er{constructor(e,t=oi,n=xs,r,s,o=Ut,a=Ut,l,c=$i){let u={width:e,height:e,depth:1},h=[u,u,u,u,u,u];super(e,e,t,n,r,s,o,a,l,c),this.image=h,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},Sa=class extends Kt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},Fr=class i extends Fe{constructor(e=1,t=1,n=1,r=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:s,depthSegments:o};let a=this;r=Math.floor(r),s=Math.floor(s),o=Math.floor(o);let l=[],c=[],u=[],h=[],f=0,d=0;p("z","y","x",-1,-1,n,t,e,o,s,0),p("z","y","x",1,-1,n,t,-e,o,s,1),p("x","z","y",1,1,e,n,t,r,o,2),p("x","z","y",1,-1,e,n,-t,r,o,3),p("x","y","z",1,-1,e,t,n,r,s,4),p("x","y","z",-1,-1,e,t,-n,r,s,5),this.setIndex(l),this.setAttribute("position",new ke(c,3)),this.setAttribute("normal",new ke(u,3)),this.setAttribute("uv",new ke(h,2));function p(x,g,m,b,v,y,M,S,_,w,R){let A=y/_,C=M/w,O=y/2,D=M/2,P=S/2,I=_+1,N=w+1,F=0,H=0,B=new U;for(let X=0;X0?1:-1,u.push(B.x,B.y,B.z),h.push(re/_),h.push(1-X/w),F+=1}}for(let X=0;X80*t){a=i[0],l=i[1];let u=a,h=l;for(let f=t;fu&&(u=d),p>h&&(h=p)}c=Math.max(u-a,h-l),c=c!==0?32767/c:0}return wa(s,o,t,a,l,c,0),o}function gx(i,e,t,n,r){let s;if(r===pS(i,e,t,n)>0)for(let o=e;o=e;o-=n)s=xg(o/n|0,i[o],i[o+1],s);return s&&po(s,s.next)&&(Aa(s),s=s.next),s}function fs(i,e){if(!i)return i;e||(e=i);let t=i,n;do if(n=!1,!t.steiner&&(po(t,t.next)||Dt(t.prev,t,t.next)===0)){if(Aa(t),t=e=t.prev,t===t.next)break;n=!0}else t=t.next;while(n||t!==e);return e}function wa(i,e,t,n,r,s,o){if(!i)return;!o&&s&&lS(i,n,r,s);let a=i;for(;i.prev!==i.next;){let l=i.prev,c=i.next;if(s?eS(i,n,r,s):Q1(i)){e.push(l.i,i.i,c.i),Aa(i),i=c.next,a=c.next;continue}if(i=c,i===a){o?o===1?(i=tS(fs(i),e),wa(i,e,t,n,r,s,2)):o===2&&nS(i,e,t,n,r,s):wa(fs(i),e,t,n,r,s,1);break}}}function Q1(i){let e=i.prev,t=i,n=i.next;if(Dt(e,t,n)>=0)return!1;let r=e.x,s=t.x,o=n.x,a=e.y,l=t.y,c=n.y,u=Math.min(r,s,o),h=Math.min(a,l,c),f=Math.max(r,s,o),d=Math.max(a,l,c),p=n.next;for(;p!==e;){if(p.x>=u&&p.x<=f&&p.y>=h&&p.y<=d&&ua(r,a,s,l,o,c,p.x,p.y)&&Dt(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function eS(i,e,t,n){let r=i.prev,s=i,o=i.next;if(Dt(r,s,o)>=0)return!1;let a=r.x,l=s.x,c=o.x,u=r.y,h=s.y,f=o.y,d=Math.min(a,l,c),p=Math.min(u,h,f),x=Math.max(a,l,c),g=Math.max(u,h,f),m=vf(d,p,e,t,n),b=vf(x,g,e,t,n),v=i.prevZ,y=i.nextZ;for(;v&&v.z>=m&&y&&y.z<=b;){if(v.x>=d&&v.x<=x&&v.y>=p&&v.y<=g&&v!==r&&v!==o&&ua(a,u,l,h,c,f,v.x,v.y)&&Dt(v.prev,v,v.next)>=0||(v=v.prevZ,y.x>=d&&y.x<=x&&y.y>=p&&y.y<=g&&y!==r&&y!==o&&ua(a,u,l,h,c,f,y.x,y.y)&&Dt(y.prev,y,y.next)>=0))return!1;y=y.nextZ}for(;v&&v.z>=m;){if(v.x>=d&&v.x<=x&&v.y>=p&&v.y<=g&&v!==r&&v!==o&&ua(a,u,l,h,c,f,v.x,v.y)&&Dt(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;y&&y.z<=b;){if(y.x>=d&&y.x<=x&&y.y>=p&&y.y<=g&&y!==r&&y!==o&&ua(a,u,l,h,c,f,y.x,y.y)&&Dt(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function tS(i,e){let t=i;do{let n=t.prev,r=t.next.next;!po(n,r)&&bx(n,t,t.next,r)&&Ta(n,r)&&Ta(r,n)&&(e.push(n.i,t.i,r.i),Aa(t),Aa(t.next),t=i=r),t=t.next}while(t!==i);return fs(t)}function nS(i,e,t,n,r,s){let o=i;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&hS(o,a)){let l=yx(o,a);o=fs(o,o.next),l=fs(l,l.next),wa(o,e,t,n,r,s,0),wa(l,e,t,n,r,s,0);return}a=a.next}o=o.next}while(o!==i)}function iS(i,e,t,n){let r=[];for(let s=0,o=e.length;s=t.next.y&&t.next.y!==t.y){let h=t.x+(r-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(h<=n&&h>s&&(s=h,o=t.x=t.x&&t.x>=l&&n!==t.x&&xx(ro.x||t.x===o.x&&aS(o,t)))&&(o=t,u=h)}t=t.next}while(t!==a);return o}function aS(i,e){return Dt(i.prev,i,e.prev)<0&&Dt(e.next,i,i.next)<0}function lS(i,e,t,n){let r=i;do r.z===0&&(r.z=vf(r.x,r.y,e,t,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==i);r.prevZ.nextZ=null,r.prevZ=null,cS(r)}function cS(i){let e,t=1;do{let n=i,r;i=null;let s=null;for(e=0;n;){e++;let o=n,a=0;for(let c=0;c0||l>0&&o;)a!==0&&(l===0||!o||n.z<=o.z)?(r=n,n=n.nextZ,a--):(r=o,o=o.nextZ,l--),s?s.nextZ=r:i=r,r.prevZ=s,s=r;n=o}s.nextZ=null,t*=2}while(e>1);return i}function vf(i,e,t,n,r){return i=(i-t)*r|0,e=(e-n)*r|0,i=(i|i<<8)&16711935,i=(i|i<<4)&252645135,i=(i|i<<2)&858993459,i=(i|i<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,i|e<<1}function uS(i){let e=i,t=i;do(e.x=(i-o)*(s-a)&&(i-o)*(n-a)>=(t-o)*(e-a)&&(t-o)*(s-a)>=(r-o)*(n-a)}function ua(i,e,t,n,r,s,o,a){return!(i===o&&e===a)&&xx(i,e,t,n,r,s,o,a)}function hS(i,e){return i.next.i!==e.i&&i.prev.i!==e.i&&!fS(i,e)&&(Ta(i,e)&&Ta(e,i)&&dS(i,e)&&(Dt(i.prev,i,e.prev)||Dt(i,e.prev,e))||po(i,e)&&Dt(i.prev,i,i.next)>0&&Dt(e.prev,e,e.next)>0)}function Dt(i,e,t){return(e.y-i.y)*(t.x-e.x)-(e.x-i.x)*(t.y-e.y)}function po(i,e){return i.x===e.x&&i.y===e.y}function bx(i,e,t,n){let r=uc(Dt(i,e,t)),s=uc(Dt(i,e,n)),o=uc(Dt(t,n,i)),a=uc(Dt(t,n,e));return!!(r!==s&&o!==a||r===0&&cc(i,t,e)||s===0&&cc(i,n,e)||o===0&&cc(t,i,n)||a===0&&cc(t,e,n))}function cc(i,e,t){return e.x<=Math.max(i.x,t.x)&&e.x>=Math.min(i.x,t.x)&&e.y<=Math.max(i.y,t.y)&&e.y>=Math.min(i.y,t.y)}function uc(i){return i>0?1:i<0?-1:0}function fS(i,e){let t=i;do{if(t.i!==i.i&&t.next.i!==i.i&&t.i!==e.i&&t.next.i!==e.i&&bx(t,t.next,i,e))return!0;t=t.next}while(t!==i);return!1}function Ta(i,e){return Dt(i.prev,i,i.next)<0?Dt(i,e,i.next)>=0&&Dt(i,i.prev,e)>=0:Dt(i,e,i.prev)<0||Dt(i,i.next,e)<0}function dS(i,e){let t=i,n=!1,r=(i.x+e.x)/2,s=(i.y+e.y)/2;do t.y>s!=t.next.y>s&&t.next.y!==t.y&&r<(t.next.x-t.x)*(s-t.y)/(t.next.y-t.y)+t.x&&(n=!n),t=t.next;while(t!==i);return n}function yx(i,e){let t=Mf(i.i,i.x,i.y),n=Mf(e.i,e.x,e.y),r=i.next,s=e.prev;return i.next=e,e.prev=i,t.next=r,r.prev=t,n.next=t,t.prev=n,s.next=n,n.prev=s,n}function xg(i,e,t,n){let r=Mf(i,e,t);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r}function Aa(i){i.next.prev=i.prev,i.prev.next=i.next,i.prevZ&&(i.prevZ.nextZ=i.nextZ),i.nextZ&&(i.nextZ.prevZ=i.prevZ)}function Mf(i,e,t){return{i,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function pS(i,e,t,n){let r=0;for(let s=e,o=t-n;s2&&i[e-1].equals(i[0])&&i.pop()}function yg(i,e){for(let t=0;t0)&&d.push(v,y,S),(m!==n-1||l0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let r in this.extensions)this.extensions[r]===!0&&(n[r]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let r=e.uniforms[n];switch(this.uniforms[n]={},r.type){case"t":this.uniforms[n].value=t[r.value]||null;break;case"c":this.uniforms[n].value=new W().setHex(r.value);break;case"v2":this.uniforms[n].value=new De().fromArray(r.value);break;case"v3":this.uniforms[n].value=new U().fromArray(r.value);break;case"v4":this.uniforms[n].value=new _t().fromArray(r.value);break;case"m3":this.uniforms[n].value=new He().fromArray(r.value);break;case"m4":this.uniforms[n].value=new Be().fromArray(r.value);break;default:this.uniforms[n].value=r.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let n in e.extensions)this.extensions[n]=e.extensions[n];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},Ec=class extends Mi{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},In=class extends mn{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new W(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new W(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=$a,this.normalScale=new De(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new _i,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},An=class extends In{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new De(1,1),this.clearcoatNormalMap=null,this.diffuseRoughnessMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return it(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessMinimum=100,this.iridescenceThicknessMaximum=400,this.iridescenceThicknessMap=null,this.sheenColor=new W(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new W(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new W(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._diffuseRoughness=0,this._dispersion=0,this._iridescence=0,this._retroreflectivity=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get diffuseRoughness(){return this._diffuseRoughness}set diffuseRoughness(e){this._diffuseRoughness>0!=e>0&&this.version++,this._diffuseRoughness=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get retroreflectivity(){return this._retroreflectivity}set retroreflectivity(e){this._retroreflectivity>0!=e>0&&this.version++,this._retroreflectivity=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}get iridescenceThicknessRange(){return os('MeshPhysicalMaterial: The "iridescenceThicknessRange" property has been replaced by "iridescenceThicknessMinimum" and "iridescenceThicknessMaximum".'),[this.iridescenceThicknessMinimum,this.iridescenceThicknessMaximum]}set iridescenceThicknessRange(e){os('MeshPhysicalMaterial: The "iridescenceThicknessRange" property has been replaced by "iridescenceThicknessMinimum" and "iridescenceThicknessMaximum".'),this.iridescenceThicknessMinimum=e[0],this.iridescenceThicknessMaximum=e[1]}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.diffuseRoughness=e.diffuseRoughness,this.diffuseRoughnessMap=e.diffuseRoughnessMap,this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessMinimum=e.iridescenceThicknessMinimum,this.iridescenceThicknessMaximum=e.iridescenceThicknessMaximum,this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.retroreflectivity=e.retroreflectivity,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}};var Pa=class extends mn{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new W(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new W(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=$a,this.normalScale=new De(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new _i,this.combine=kc,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Rc=class extends mn{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=nx,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},Cc=class extends mn{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function Er(i,e){return!i||i.constructor===e?i:typeof e.BYTES_PER_ELEMENT=="number"?new e(i):Array.prototype.slice.call(i)}function ha(i){return i!==void 0&&i.inTangents!==void 0&&i.outTangents!==void 0}function bS(i){function e(r,s){return i[r]-i[s]}let t=i.length,n=new Array(t);for(let r=0;r!==t;++r)n[r]=r;return n.sort(e),n}function vg(i,e,t){let n=i.length,r=new i.constructor(n);for(let s=0,o=0;o!==n;++s){let a=t[s]*e;for(let l=0;l!==e;++l)r[o++]=i[a+l]}return r}function yS(i,e,t,n){let r=1,s=i[0];for(;s!==void 0&&s[n]===void 0;)s=i[r++];if(s===void 0)return;let o=s[n];if(o!==void 0)if(Array.isArray(o))do o=s[n],o!==void 0&&(e.push(s.time),t.push(...o)),s=i[r++];while(s!==void 0);else if(o.toArray!==void 0)do o=s[n],o!==void 0&&(e.push(s.time),o.toArray(t,t.length)),s=i[r++];while(s!==void 0);else do o=s[n],o!==void 0&&(e.push(s.time),t.push(o)),s=i[r++];while(s!==void 0)}var Si=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r!==void 0?r:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],s=t[n-1];n:{e:{let o;t:{i:if(!(e=s)){let a=t[1];e=s)break e}o=n,n=0;break t}break n}for(;n>>1;et;)--o;if(++o,s!==0||o!==r){s>=o&&(o=Math.max(o,1),s=o-1);let a=this.getValueSize();this.times=n.slice(s,o),this.values=this.values.slice(s*a,o*a)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(Ge("KeyframeTrack: Invalid value size in track.",this),e=!1);let n=this.times,r=this.values,s=n.length;s===0&&(Ge("KeyframeTrack: Track is empty.",this),e=!1);let o=null;for(let a=0;a!==s;a++){let l=n[a];if(typeof l=="number"&&isNaN(l)){Ge("KeyframeTrack: Time is not a valid number.",this,a,l),e=!1;break}if(o!==null&&o>l){Ge("KeyframeTrack: Out of order keys.",this,a,l,o),e=!1;break}o=l}if(r!==void 0&&m1(r))for(let a=0,l=r.length;a!==l;++a){let c=r[a];if(isNaN(c)){Ge("KeyframeTrack: Value is not a valid number.",this,a,c),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===dc,s=e.length-1,o=1;for(let a=1;a0){e[o]=e[s];for(let a=s*n,l=o*n,c=0;c!==n;++c)t[l+c]=t[a+c];++o}return o!==e.length?(this.times=e.slice(0,o),this.values=t.slice(0,o*n)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,ha(this.settings)&&(r.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),r}};function Mg(i,e){for(let t=0,n=i.length;t!==n;t+=2)i[t]+=e}function Sg(i,e){for(let t=0,n=i.length;t!==n;t+=2)i[t]*=e}Ln.prototype.ValueTypeName="";Ln.prototype.TimeBufferType=Float32Array;Ln.prototype.ValueBufferType=Float32Array;Ln.prototype.DefaultInterpolation=Zi;var tr=class extends Ln{constructor(e,t,n){super(e,t,n)}};tr.prototype.ValueTypeName="bool";tr.prototype.ValueBufferType=Array;tr.prototype.DefaultInterpolation=Ki;tr.prototype.InterpolantFactoryMethodLinear=void 0;tr.prototype.InterpolantFactoryMethodSmooth=void 0;var Ia=class extends Ln{constructor(e,t,n,r){super(e,t,n,r)}};Ia.prototype.ValueTypeName="color";var nr=class extends Ln{constructor(e,t,n,r){super(e,t,n,r)}};nr.prototype.ValueTypeName="number";var Oc=class extends Si{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let s=this.resultBuffer,o=this.sampleValues,a=this.valueSize,l=(n-t)/(r-t),c=e*a;for(let u=c+a;c!==u;c+=4)Sn.slerpFlat(s,0,o,c-a,o,c,l);return s}},ir=class extends Ln{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new Oc(this.times,this.values,this.getValueSize(),e)}};ir.prototype.ValueTypeName="quaternion";ir.prototype.InterpolantFactoryMethodSmooth=void 0;var rr=class extends Ln{constructor(e,t,n){super(e,t,n)}};rr.prototype.ValueTypeName="string";rr.prototype.ValueBufferType=Array;rr.prototype.DefaultInterpolation=Ki;rr.prototype.InterpolantFactoryMethodLinear=void 0;rr.prototype.InterpolantFactoryMethodSmooth=void 0;var Or=class extends Ln{constructor(e,t,n,r){super(e,t,n,r)}};Or.prototype.ValueTypeName="vector";var La=class{constructor(e="",t=-1,n=[],r=tx){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=Ri(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,r=1/(e.fps||1);for(let o=0,a=n.length;o!==a;++o)t.push(SS(n[o]).scale(r));let s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s.userData=JSON.parse(e.userData||"{}"),s}static toJSON(e){let t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let s=0,o=n.length;s!==o;++s)t.push(Ln.toJSON(n[s]));return r}static CreateFromMorphTargetSequence(e,t,n,r){let s=t.length,o=[];for(let a=0;a1){let h=u[1],f=r[h];f||(r[h]=f=[]),f.push(c)}}let o=[];for(let a in r)o.push(this.CreateFromMorphTargetSequence(a,r[a],t,n));return o}resetDuration(){let e=this.tracks,t=0;for(let n=0,r=e.length;n!==r;++n){let s=this.tracks[n];t=Math.max(t,s.times[s.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e{t&&t(s),this.manager.itemEnd(e)},0);return}if(Xi[e]!==void 0){Xi[e].push({onLoad:t,onProgress:n,onError:r});return}Xi[e]=[],Xi[e].push({onLoad:t,onProgress:n,onError:r});let o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",priority:this.priority,cache:this.cache,signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),a=this.mimeType,l=this.responseType;fetch(o).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&Le("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;let u=Xi[e],h=c.body.getReader(),f=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),d=f?parseInt(f):0,p=d!==0,x=0,g=new ReadableStream({start(m){b();function b(){h.read().then(({done:v,value:y})=>{if(v)m.close();else{x+=y.byteLength;let M=new ProgressEvent("progress",{lengthComputable:p,loaded:x,total:d});for(let S=0,_=u.length;S<_;S++){let w=u[S];w.onProgress&&w.onProgress(M)}m.enqueue(y),b()}},v=>{m.error(v)})}}});return new Response(g)}else throw new wf(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(u=>new DOMParser().parseFromString(u,a));case"json":return c.json();default:if(a==="")return c.text();{let h=/charset="?([^;"\s]*)"?/i.exec(a),f=h&&h[1]?h[1].toLowerCase():void 0,d=new TextDecoder(f);return c.arrayBuffer().then(p=>d.decode(p))}}}).then(c=>{bi.add(`file:${e}`,c);let u=Xi[e];delete Xi[e];for(let h=0,f=u.length;h{let u=Xi[e];if(u===void 0)throw this.manager.itemError(e),c;delete Xi[e];for(let h=0,f=u.length;h{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}};var eo=new WeakMap,Dc=class extends wi{constructor(e){super(e)}load(e,t,n,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,o=bi.get(`image:${e}`);if(o!==void 0){if(o.complete===!0)s.manager.itemStart(e),setTimeout(function(){t&&t(o),s.manager.itemEnd(e)},0);else{let h=eo.get(o);h===void 0&&(h=[],eo.set(o,h)),h.push({onLoad:t,onError:r})}return o}let a=oo("img");function l(){u(),t&&t(this);let h=eo.get(this)||[];for(let f=0;f"u"&&Le("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&Le("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,r){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,o=bi.get(`image-bitmap:${e}`);if(o!==void 0){if(s.manager.itemStart(e),o.then){o.then(c=>{pf.has(o)===!0?(r&&r(pf.get(o)),s.manager.itemError(e),s.manager.itemEnd(e)):(t&&t(c),s.manager.itemEnd(e))});return}setTimeout(function(){t&&t(o),s.manager.itemEnd(e)},0);return}let a={};a.credentials=this.withCredentials||this.crossOrigin!=="anonymous"?"include":"same-origin",a.headers=this.requestHeader,a.priority=this.priority,a.cache=this.cache,a.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let l=fetch(e,a).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign({},s.options,{colorSpaceConversion:"none"}))}).then(function(c){return bi.add(`image-bitmap:${e}`,c),t&&t(c),s.manager.itemEnd(e),c}).catch(function(c){r&&r(c),pf.set(l,c),bi.remove(`image-bitmap:${e}`),s.manager.itemError(e),s.manager.itemEnd(e)});bi.add(`image-bitmap:${e}`,l),s.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}};var to=-90,no=1,xo=class extends Et{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new Jt(to,no,e,t);r.layers=this.layers,this.add(r);let s=new Jt(to,no,e,t);s.layers=this.layers,this.add(s);let o=new Jt(to,no,e,t);o.layers=this.layers,this.add(o);let a=new Jt(to,no,e,t);a.layers=this.layers,this.add(a);let l=new Jt(to,no,e,t);l.layers=this.layers,this.add(l);let c=new Jt(to,no,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,s,o,a,l]=t;for(let c of t)this.remove(c);if(e===$n)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===so)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(let c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[s,o,a,l,c,u]=this.children,h=e.getRenderTarget(),f=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let x=n.texture.mipmapsAutoUpdate;n.texture.mipmapsAutoUpdate=!1;let g=!1;e.isWebGLRenderer===!0?g=e.state.buffers.depth.getReversed():g=e.reversedDepthBuffer,e.setRenderTarget(n,0,r),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,1,r),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,2,r),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,3,r),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(n,4,r),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.mipmapsAutoUpdate=x,e.setRenderTarget(n,5,r),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,u),e.setRenderTarget(h,f,d),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},Uc=class extends Jt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e,this.perCameraFrustumCulled=!1}};var ad="\\[\\]\\.:\\/",wS=new RegExp("["+ad+"]","g"),ld="[^"+ad+"]",TS="[^"+ad.replace("\\.","")+"]",AS=/((?:WC+[\/:])*)/.source.replace("WC",ld),ES=/(WCOD+)?/.source.replace("WCOD",TS),RS=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",ld),CS=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",ld),PS=new RegExp("^"+AS+ES+RS+CS+"$"),IS=["material","materials","bones","map"],Rf=class{constructor(e,t,n){let r=n||gt.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,s=n.length;r!==s;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},gt=class i{constructor(e,t,n){this.path=t,this.parsedPath=n||i.parseTrackName(t),this.node=i.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new i.Composite(e,t,n):new i(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(wS,"")}static parseTrackName(e){let t=PS.exec(e);if(t===null)throw new Error("THREE.PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(".");if(r!==void 0&&r!==-1){let s=n.nodeName.substring(r+1);IS.indexOf(s)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=s)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("THREE.PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(s){for(let o=0;od.start-p.start);let f=0;for(let d=1;d 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,ZS=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,JS=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,jS=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,QS=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#endif`,ew=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#endif`,tw=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec4 vColor; +#endif`,nw=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec4( 1.0 ); +#endif +#ifdef USE_COLOR_ALPHA + vColor *= color; +#elif defined( USE_COLOR ) + vColor.rgb *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.rgb *= instanceColor.rgb; +#endif +#ifdef USE_BATCHING_COLOR + vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); +#endif`,iw=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +#define inverseTransformDirection transformDirectionByInverseViewMatrix +vec3 transformNormalByInverseViewMatrix( in vec3 normal, in mat4 viewMatrix ) { + return normalize( ( vec4( normal, 0.0 ) * viewMatrix ).xyz ); +} +vec3 transformDirectionByInverseViewMatrix( in vec3 dir, in mat4 viewMatrix ) { + return normalize( ( vec4( dir, 0.0 ) * viewMatrix ).xyz ); +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,rw=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; +#endif`,sw=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,ow=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,aw=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,lw=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,cw="gl_FragColor = linearToOutputTexel( gl_FragColor );",uw=`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,hw=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * reflectVec ); + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif + #endif +#endif`,fw=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform mat3 envMapRotation; + uniform samplerCube envMap; + #ifdef ENVMAP_TYPE_PMREM + float roughnessToMip( const in float roughness ) { + float r = clamp( roughness, 0.0, 1.0 ); + return ENVMAP_MAX_LOD * r * ( 2.0 - r ); + } + #endif +#endif`,dw=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,pw=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,mw=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,gw=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,xw=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,bw=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,yw=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,_w=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,vw=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,Mw=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,Sw=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,ww=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_SUN_LIGHTS > 0 + struct SunLight { + vec3 direction; + vec3 color; + }; + uniform SunLight sunLights[ NUM_SUN_LIGHTS ]; + void getSunLightInfo( const in SunLight sunLight, out IncidentLight light ) { + light.color = sunLight.color; + light.direction = sunLight.direction; + light.visible = true; + } +#endif +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif +#include `,Tw=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_PMREM + vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix ); + vec4 envMapColor = textureLod( envMap, envMapRotation * worldNormal, ENVMAP_MAX_LOD ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_PMREM + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); + reflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix ); + vec4 envMapColor = textureLod( envMap, envMapRotation * reflectVec, roughnessToMip( roughness ) ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_RETROREFLECTION + vec3 getIBLRetroRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_PMREM + vec3 retroVec = normalize( mix( viewDir, normal, pow4( roughness ) ) ); + retroVec = transformDirectionByInverseViewMatrix( retroVec, viewMatrix ); + vec4 envMapColor = textureLod( envMap, envMapRotation * retroVec, roughnessToMip( roughness ) ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #endif + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_PMREM + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_RETROREFLECTION + vec3 getIBLAnisotropyRetroRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_PMREM + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRetroRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif + #endif +#endif`,Aw=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,Ew=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,Rw=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,Cw=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,Pw=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +material.metalness = metalnessFactor; +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.045 ); +material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef USE_DIFFUSE_ROUGHNESS + float diffuseRoughnessFactor = diffuseRoughness; + #ifdef USE_DIFFUSE_ROUGHNESSMAP + diffuseRoughnessFactor *= texture2D( diffuseRoughnessMap, vDiffuseRoughnessMapUv ).r; + #endif + material.diffuseRoughness = saturate( diffuseRoughnessFactor ); +#endif +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; + material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = vec3( 0.04 ); + material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.045 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_RETROREFLECTION + material.retroreflectivity = retroreflectivity; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,Iw=`uniform sampler2D dfgLUT; +struct PhysicalMaterial { + vec3 diffuseColor; + vec3 diffuseContribution; + vec3 specularColor; + vec3 specularColorBlended; + float roughness; + float metalness; + float specularF90; + float dispersion; + vec2 dfg; + vec3 multiScatteringCompensation; + #ifdef USE_DIFFUSE_ROUGHNESS + float diffuseRoughness; + #endif + #ifdef USE_RETROREFLECTION + float retroreflectivity; + #endif + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0Dielectric; + vec3 iridescenceF0Metallic; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +#ifdef USE_DIFFUSE_ROUGHNESS + const float EON_EPSILON = 1e-7; + float FON_DirectionalAlbedo( const in float mu, const in float roughness, const in float A ) { + float muComp = 1.0 - mu; + float gOverPi = muComp * ( 0.0571085289 + muComp * ( 0.491881867 + muComp * ( - 0.332181442 + muComp * 0.0714429953 ) ) ); + return A * ( 1.0 + roughness * gOverPi ); + } + vec3 BRDF_EON( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 diffuseColor, const in float roughness ) { + vec3 rho = saturate( diffuseColor ); + if ( roughness <= EON_EPSILON ) return BRDF_Lambert( rho ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float s = dot( lightDir, viewDir ) - dotNL * dotNV; + float sOverT = ( s > 0.0 ) ? s / max( max( dotNL, dotNV ), EON_EPSILON ) : s; + float A = 1.0 / ( 1.0 + ( 0.5 - 2.0 / ( 3.0 * PI ) ) * roughness ); + vec3 singleScatter = rho * RECIPROCAL_PI * A * ( 1.0 + roughness * sOverT ); + float averageAlbedo = A * ( 1.0 + ( 2.0 / 3.0 - 28.0 / ( 15.0 * PI ) ) * roughness ); + float albedoV = FON_DirectionalAlbedo( dotNV, roughness, A ); + float albedoL = FON_DirectionalAlbedo( dotNL, roughness, A ); + vec3 rhoMultiScatter = rho * rho * averageAlbedo / max( vec3( EON_EPSILON ), vec3( 1.0 ) - rho * ( 1.0 - averageAlbedo ) ); + vec3 multiScatter = rhoMultiScatter * RECIPROCAL_PI + * max( EON_EPSILON, 1.0 - albedoV ) + * max( EON_EPSILON, 1.0 - albedoL ) + / max( EON_EPSILON, 1.0 - averageAlbedo ); + return singleScatter + multiScatter; + } + vec3 EON_DirectionalAlbedo( const in vec3 diffuseColor, const in float roughness, const in float dotNV ) { + vec3 rho = saturate( diffuseColor ); + if ( roughness <= EON_EPSILON ) return rho; + float A = 1.0 / ( 1.0 + ( 0.5 - 2.0 / ( 3.0 * PI ) ) * roughness ); + float directionalAlbedo = FON_DirectionalAlbedo( dotNV, roughness, A ); + float averageAlbedo = A * ( 1.0 + ( 2.0 / 3.0 - 28.0 / ( 15.0 * PI ) ) * roughness ); + vec3 rhoMultiScatter = rho * rho * averageAlbedo / max( vec3( EON_EPSILON ), vec3( 1.0 ) - rho * ( 1.0 - averageAlbedo ) ); + return rho * directionalAlbedo + rhoMultiScatter * ( 1.0 - directionalAlbedo ); + } +#endif +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = max( material.clearcoatRoughness, 0.045 ); + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColorBlended; + float f90 = material.specularF90; + float roughness = max( material.roughness, 0.045 ); + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float alphaT = max( material.alphaT, alpha ); + float V = V_GGX_SmithCorrelated_Anisotropic( alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float rInv = 1.0 / ( roughness + 0.1 ); + float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; + float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; + float DG = exp( a * dotNV + b ); + return saturate( DG ); +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec2 fab, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec2 fab, const in vec3 specularColor, const in float specularF90, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + #ifdef USE_CLEARCOAT + vec3 Ncc = geometryClearcoatNormal; + vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness ); + vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat ); + vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat ); + mat3 mInvClearcoat = mat3( + vec3( t1Clearcoat.x, 0, t1Clearcoat.y ), + vec3( 0, 1, 0 ), + vec3( t1Clearcoat.z, 0, t1Clearcoat.w ) + ); + vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y; + clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords ); + #endif + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + + float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); + + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); + + irradiance *= sheenEnergyComp; + + #endif + vec3 specularBRDF = BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + #ifdef USE_RETROREFLECTION + vec3 retroViewDir = reflect( - geometryViewDir, geometryNormal ); + vec3 retroSpecularBRDF = BRDF_GGX( directLight.direction, retroViewDir, geometryNormal, material ); + specularBRDF = mix( specularBRDF, retroSpecularBRDF, saturate( material.retroreflectivity ) ); + #endif + reflectedLight.directSpecular += irradiance * specularBRDF * material.multiScatteringCompensation; + vec3 halfDir = normalize( directLight.direction + geometryViewDir ); + float dotVH = saturate( dot( geometryViewDir, halfDir ) ); + vec3 F = F_Schlick( material.specularColor, material.specularF90, dotVH ); + #ifdef USE_RETROREFLECTION + vec3 retroHalfDir = normalize( directLight.direction + retroViewDir ); + float dotRetroVH = saturate( dot( retroViewDir, retroHalfDir ) ); + vec3 retroF = F_Schlick( material.specularColor, material.specularF90, dotRetroVH ); + F = mix( F, retroF, saturate( material.retroreflectivity ) ); + #endif + #ifdef USE_DIFFUSE_ROUGHNESS + vec3 diffuseBRDF = BRDF_EON( directLight.direction, geometryViewDir, geometryNormal, material.diffuseColor, material.diffuseRoughness ) * ( 1.0 - material.metalness ); + #else + vec3 diffuseBRDF = BRDF_Lambert( material.diffuseContribution ); + #endif + reflectedLight.directDiffuse += irradiance * diffuseBRDF * ( 1.0 - F ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScattering, multiScattering ); + #else + computeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScattering, multiScattering ); + #endif + #ifdef USE_DIFFUSE_ROUGHNESS + float dotNV = saturate( dot( geometryNormal, geometryViewDir ) ); + vec3 diffuseAlbedo = EON_DirectionalAlbedo( material.diffuseColor, material.diffuseRoughness, dotNV ) * ( 1.0 - material.metalness ); + vec3 diffuse = irradiance * RECIPROCAL_PI * diffuseAlbedo * ( 1.0 - singleScattering - multiScattering ); + #else + vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - singleScattering - multiScattering ); + #endif + #ifdef USE_SHEEN + float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + sheenSpecularIndirect += irradiance * material.sheenColor * sheenAlbedo * RECIPROCAL_PI; + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; + diffuse *= sheenEnergyComp; + #endif + reflectedLight.indirectDiffuse += diffuse; +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; + #endif + vec3 singleScatteringDielectric = vec3( 0.0 ); + vec3 multiScatteringDielectric = vec3( 0.0 ); + vec3 singleScatteringMetallic = vec3( 0.0 ); + vec3 multiScatteringMetallic = vec3( 0.0 ); + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScatteringDielectric, multiScatteringDielectric ); + computeMultiscatteringIridescence( material.dfg, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceF0Metallic, singleScatteringMetallic, multiScatteringMetallic ); + #else + computeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScatteringDielectric, multiScatteringDielectric ); + computeMultiscattering( material.dfg, material.diffuseColor, material.specularF90, singleScatteringMetallic, multiScatteringMetallic ); + #endif + vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); + vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); + vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; + #ifdef USE_DIFFUSE_ROUGHNESS + float dotNV = saturate( dot( geometryNormal, geometryViewDir ) ); + vec3 diffuse = EON_DirectionalAlbedo( material.diffuseColor, material.diffuseRoughness, dotNV ) * ( 1.0 - material.metalness ) * ( 1.0 - totalScatteringDielectric ); + #else + vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); + #endif + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + vec3 indirectSpecular = radiance * singleScattering; + indirectSpecular += multiScattering * cosineWeightedIrradiance; + vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; + #ifdef USE_SHEEN + float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; + indirectSpecular *= sheenEnergyComp; + indirectDiffuse *= sheenEnergyComp; + #endif + reflectedLight.indirectSpecular += indirectSpecular; + reflectedLight.indirectDiffuse += indirectDiffuse; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,Lw=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + vec3 iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + vec3 iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); + material.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, material.metalness ); + material.iridescenceF0Dielectric = Schlick_to_F0( iridescenceFresnelDielectric, 1.0, dotNVi ); + material.iridescenceF0Metallic = Schlick_to_F0( iridescenceFresnelMetallic, 1.0, dotNVi ); + } +#endif +#ifdef STANDARD + float dotNVms = saturate( dot( geometryNormal, geometryViewDir ) ); + material.dfg = texture2D( dfgLUT, vec2( material.roughness, dotNVms ) ).rg; + #if ( NUM_SUN_LIGHTS > 0 || NUM_DIR_LIGHTS > 0 || NUM_POINT_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 ) + float EssMs = material.dfg.x + material.dfg.y; + material.multiScatteringCompensation = 1.0 + material.specularColorBlended * ( 1.0 / EssMs - 1.0 ); + #endif +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SUN_LIGHTS > 0 ) && defined( RE_Direct ) + SunLight sunLight; + #if defined( USE_SHADOWMAP ) && NUM_SUN_LIGHT_SHADOWS > 0 + SunLightShadow sunLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SUN_LIGHTS; i ++ ) { + sunLight = sunLights[ i ]; + getSunLightInfo( sunLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SUN_LIGHT_SHADOWS ) + sunLightShadow = sunLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getSunShadow( sunShadowMap[ i ], sunLightShadow, UNROLLED_LOOP_INDEX ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif + #if NUM_LIGHT_PROBE_GRIDS > 0 + vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz; + vec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix ); + int probeGrid = - 1; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_LIGHT_PROBE_GRIDS; i ++ ) { + if ( isInsideLightProbeGrid( probeWorldPos, probeWorldNormal, probesMin[ i ], probesMax[ i ], probesResolution[ i ] ) ) probeGrid = UNROLLED_LOOP_INDEX; + } + #pragma unroll_loop_end + #pragma unroll_loop_start + for ( int i = 0; i < NUM_LIGHT_PROBE_GRIDS; i ++ ) { + if ( probeGrid == UNROLLED_LOOP_INDEX ) irradiance += getLightProbeGridIrradiance( probesSH[ i ], probesMin[ i ], probesMax[ i ], probesResolution[ i ], probeWorldPos, probeWorldNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,Fw=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_PMREM ) + #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + vec3 iblRadiance = getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + vec3 iblRadiance = getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_RETROREFLECTION + #ifdef USE_ANISOTROPY + vec3 retroIBLRadiance = getIBLAnisotropyRetroRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + vec3 retroIBLRadiance = getIBLRetroRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + iblRadiance = mix( iblRadiance, retroIBLRadiance, saturate( material.retroreflectivity ) ); + #endif + radiance += iblRadiance; + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,Ow=`#if defined( RE_IndirectDiffuse ) + #if defined( LAMBERT ) || defined( PHONG ) + irradiance += iblIrradiance; + #endif + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,Nw=`#if NUM_LIGHT_PROBE_GRIDS > 0 +uniform highp sampler3D probesSH[ NUM_LIGHT_PROBE_GRIDS ]; +uniform vec3 probesMin[ NUM_LIGHT_PROBE_GRIDS ]; +uniform vec3 probesMax[ NUM_LIGHT_PROBE_GRIDS ]; +uniform vec3 probesResolution[ NUM_LIGHT_PROBE_GRIDS ]; +bool isInsideLightProbeGrid( vec3 worldPos, vec3 worldNormal, vec3 probesMin, vec3 probesMax, vec3 probesResolution ) { + vec3 spacing = ( probesMax - probesMin ) / probesResolution; + vec3 samplePos = worldPos + worldNormal * spacing * 0.5; + vec3 margin = spacing * 0.01; + return all( greaterThanEqual( samplePos, probesMin - margin ) ) && all( lessThanEqual( samplePos, probesMax + margin ) ); +} +vec3 getLightProbeGridIrradiance( highp sampler3D probesSH, vec3 probesMin, vec3 probesMax, vec3 probesResolution, vec3 worldPos, vec3 worldNormal ) { + vec3 res = probesResolution; + vec3 gridRange = probesMax - probesMin; + vec3 probeSpacing = gridRange / res; + vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5; + vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.5 / res, 1.0 - 0.5 / res ); + float nz = res.z; + float paddedSlices = nz + 2.0; + float atlasDepth = 7.0 * paddedSlices; + float uvZBase = uvw.z * nz + 1.0; + vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) ); + vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) ); + vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) ); + vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) ); + vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) ); + vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) ); + vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) ); + vec3 c0 = s0.xyz; + vec3 c1 = vec3( s0.w, s1.xy ); + vec3 c2 = vec3( s1.zw, s2.x ); + vec3 c3 = s2.yzw; + vec3 c4 = s3.xyz; + vec3 c5 = vec3( s3.w, s4.xy ); + vec3 c6 = vec3( s4.zw, s5.x ); + vec3 c7 = s5.yzw; + vec3 c8 = s6.xyz; + float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z; + vec3 result = c0 * 0.886227; + result += c1 * 2.0 * 0.511664 * y; + result += c2 * 2.0 * 0.511664 * z; + result += c3 * 2.0 * 0.511664 * x; + result += c4 * 2.0 * 0.429043 * x * y; + result += c5 * 2.0 * 0.429043 * y * z; + result += c6 * ( 0.743125 * z * z - 0.247708 ); + result += c7 * 2.0 * 0.429043 * x * z; + result += c8 * 0.429043 * ( x * x - y * y ); + return max( result, vec3( 0.0 ) ); +} +#endif`,Dw=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,Uw=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,Bw=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + varying float vFragDepth; + varying float vIsPerspective; +#endif`,kw=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,zw=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,Vw=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,Gw=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,Hw=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,Ww=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,Xw=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,Yw=`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,qw=`#if defined( USE_MORPHCOLORS ) + #if defined( USE_COLOR_ALPHA ) + vColor *= morphTargetBaseInfluence; + #elif defined( USE_COLOR ) + vColor.rgb *= morphTargetBaseInfluence; + #endif + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor.rgb += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,$w=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,Kw=`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,Zw=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,Jw=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #ifdef DOUBLE_SIDED + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #ifdef DOUBLE_SIDED + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,jw=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #if defined( USE_PACKED_NORMALMAP ) + mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) ); + #endif + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,Qw=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,e2=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,t2=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #ifdef FLIP_SIDED + vBitangent = - vBitangent; + #endif + #endif +#endif`,n2=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,i2=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,r2=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,s2=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,o2=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,a2=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,l2=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + #ifdef USE_REVERSED_DEPTH_BUFFER + + return depth * ( far - near ) - far; + #else + return depth * ( near - far ) - near; + #endif +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + + #ifdef USE_REVERSED_DEPTH_BUFFER + return ( near * far ) / ( ( near - far ) * depth - near ); + #else + return ( near * far ) / ( ( far - near ) * depth - far ); + #endif +}`,c2=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,u2=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,h2=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,f2=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,d2=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,p2=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,m2=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_SUN_LIGHT_SHADOWS > 0 + #define SUN_LIGHT_CASCADES 2 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform sampler2DShadow sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ]; + #else + uniform sampler2D sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ]; + #endif + uniform mat4 sunShadowMatrix[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ]; + uniform vec4 sunShadowCascade[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ]; + varying vec4 vSunShadowWorldPosition; + varying vec3 vSunShadowWorldNormal; + struct SunLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SunLightShadow sunLightShadows[ NUM_SUN_LIGHT_SHADOWS ]; + #endif + #if NUM_DIR_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + #else + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + #else + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + #elif defined( SHADOWMAP_TYPE_BASIC ) + uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + #if defined( SHADOWMAP_TYPE_PCF ) + float interleavedGradientNoise( vec2 position ) { + return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); + } + vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { + const float goldenAngle = 2.399963229728653; + float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); + float theta = float( sampleIndex ) * goldenAngle + phi; + return vec2( cos( theta ), sin( theta ) ) * r; + } + #endif + #if defined( SHADOWMAP_TYPE_PCF ) + float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadowCoord.z -= shadowBias; + #else + shadowCoord.z += shadowBias; + #endif + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + vec2 radius = shadowRadius * texelSize; + float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; + shadow = ( + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) + ) * 0.2; + } + return mix( 1.0, shadow, shadowIntensity ); + } + #elif defined( SHADOWMAP_TYPE_VSM ) + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadowCoord.z -= shadowBias; + #else + shadowCoord.z += shadowBias; + #endif + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; + float mean = distribution.x; + float variance = distribution.y * distribution.y; + #ifdef USE_REVERSED_DEPTH_BUFFER + float hard_shadow = step( mean, shadowCoord.z ); + #else + float hard_shadow = step( shadowCoord.z, mean ); + #endif + + if ( hard_shadow == 1.0 ) { + shadow = 1.0; + } else { + variance = max( variance, 0.0000001 ); + float d = shadowCoord.z - mean; + float p_max = variance / ( variance + d * d ); + p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); + shadow = max( hard_shadow, p_max ); + } + } + return mix( 1.0, shadow, shadowIntensity ); + } + #else + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadowCoord.z -= shadowBias; + #else + shadowCoord.z += shadowBias; + #endif + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + float depth = texture2D( shadowMap, shadowCoord.xy ).r; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadow = step( depth, shadowCoord.z ); + #else + shadow = step( shadowCoord.z, depth ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + #endif + #if NUM_SUN_LIGHT_SHADOWS > 0 + float getSunShadow( + #if defined( SHADOWMAP_TYPE_PCF ) + sampler2DShadow shadowMap, + #else + sampler2D shadowMap, + #endif + SunLightShadow sunLightShadow, + int shadowIndex + ) { + vec4 shadowWorldPosition = vec4( vSunShadowWorldPosition.xyz + vSunShadowWorldNormal * sunLightShadow.shadowNormalBias, 1.0 ); + float viewDepth = vSunShadowWorldPosition.w; + int cascadeOffset = shadowIndex * SUN_LIGHT_CASCADES; + float shadow = 1.0; + for ( int i = SUN_LIGHT_CASCADES - 1; i >= 0; i -- ) { + vec4 cascade = sunShadowCascade[ cascadeOffset + i ]; + if ( viewDepth >= cascade.x && viewDepth < cascade.y ) { + float cascadeShadow = getShadow( + shadowMap, + sunLightShadow.shadowMapSize, + sunLightShadow.shadowIntensity, + sunLightShadow.shadowBias, + sunLightShadow.shadowRadius, + sunShadowMatrix[ cascadeOffset + i ] * shadowWorldPosition + ); + shadow = mix( cascadeShadow, shadow, smoothstep( cascade.z, cascade.y, viewDepth ) ); + } + } + return shadow; + } + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + vec3 bd3D = normalize( lightToPosition ); + vec3 absVec = abs( lightToPosition ); + float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); + if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { + float lightDistance = length( lightToPosition ); + float depthRange = shadowCameraFar - shadowCameraNear; + #ifdef USE_REVERSED_DEPTH_BUFFER + float depthA = - shadowCameraNear / depthRange - shadowBias; + float depthB = shadowCameraNear * shadowCameraFar / ( depthRange * lightDistance ); + #else + float depthA = shadowCameraFar / depthRange + shadowBias; + float depthB = - shadowCameraNear * shadowCameraFar / ( depthRange * lightDistance ); + #endif + float texelSize = shadowRadius / shadowMapSize.x; + vec3 absDir = abs( bd3D ); + vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); + tangent = normalize( cross( bd3D, tangent ) ); + vec3 bitangent = cross( bd3D, tangent ); + float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; + shadow = 0.0; + for ( int i = 0; i < 5; i ++ ) { + vec2 offset = vogelDiskSample( i, 5, phi ); + vec3 direction = bd3D + ( tangent * offset.x + bitangent * offset.y ) * texelSize; + vec3 absDirection = abs( direction ); + float dp = depthA + depthB / max( max( absDirection.x, absDirection.y ), absDirection.z ); + shadow += texture( shadowMap, vec4( direction, dp ) ); + } + shadow *= 0.2; + } + return mix( 1.0, shadow, shadowIntensity ); + } + #elif defined( SHADOWMAP_TYPE_BASIC ) + float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + vec3 absVec = abs( lightToPosition ); + float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); + if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { + float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); + dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + float depth = textureCube( shadowMap, bd3D ).r; + #ifdef USE_REVERSED_DEPTH_BUFFER + depth = 1.0 - depth; + #endif + shadow = step( dp, depth ); + } + return mix( 1.0, shadow, shadowIntensity ); + } + #endif + #endif +#endif`,g2=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_SUN_LIGHT_SHADOWS > 0 + varying vec4 vSunShadowWorldPosition; + varying vec3 vSunShadowWorldNormal; + #endif + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,x2=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + #ifdef HAS_NORMAL + vec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix ); + #else + vec3 shadowWorldNormal = vec3( 0.0 ); + #endif + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_SUN_LIGHT_SHADOWS > 0 + vSunShadowWorldPosition = vec4( worldPosition.xyz, - mvPosition.z ); + vSunShadowWorldNormal = shadowWorldNormal; + #endif + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,b2=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_SUN_LIGHT_SHADOWS > 0 + SunLightShadow sunLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SUN_LIGHT_SHADOWS; i ++ ) { + sunLight = sunLightShadows[ i ]; + shadow *= receiveShadow ? getSunShadow( sunShadowMap[ i ], sunLight, UNROLLED_LOOP_INDEX ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,y2=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,_2=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,v2=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,M2=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,S2=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,w2=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,T2=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,A2=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,E2=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = transformNormalByInverseViewMatrix( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,R2=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,C2=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_DIFFUSE_ROUGHNESSMAP + varying vec2 vDiffuseRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,P2=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_DIFFUSE_ROUGHNESSMAP + uniform mat3 diffuseRoughnessMapTransform; + varying vec2 vDiffuseRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,I2=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DIFFUSE_ROUGHNESSMAP + vDiffuseRoughnessMapUv = ( diffuseRoughnessMapTransform * vec3( DIFFUSE_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,L2=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`,F2=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,O2=`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,N2=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,D2=`uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_PMREM + vec4 texColor = textureLod( envMap, backgroundRotation * vWorldDirection, roughnessToMip( backgroundBlurriness ) ); + #else + vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,U2=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,B2=`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,k2=`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,z2=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + #ifdef USE_REVERSED_DEPTH_BUFFER + float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; + #else + float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; + #endif + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,V2=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,G2=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); +}`,H2=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,W2=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,X2=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Y2=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,q2=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,$2=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,K2=`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Z2=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,J2=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,j2=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,Q2=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,eT=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,tT=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,nT=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,iT=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,rT=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DIFFUSE_ROUGHNESS + uniform float diffuseRoughness; + #ifdef USE_DIFFUSE_ROUGHNESSMAP + uniform sampler2D diffuseRoughnessMap; + #endif +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_RETROREFLECTION + uniform float retroreflectivity; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + + outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; + + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,sT=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,oT=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,aT=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,lT=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,cT=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,uT=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include + #include +}`,hT=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,fT=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,Qe={alphahash_fragment:OS,alphahash_pars_fragment:NS,alphamap_fragment:DS,alphamap_pars_fragment:US,alphatest_fragment:BS,alphatest_pars_fragment:kS,aomap_fragment:zS,aomap_pars_fragment:VS,batching_pars_vertex:GS,batching_vertex:HS,begin_vertex:WS,beginnormal_vertex:XS,bsdfs:YS,iridescence_fragment:qS,bumpmap_pars_fragment:$S,clipping_planes_fragment:KS,clipping_planes_pars_fragment:ZS,clipping_planes_pars_vertex:JS,clipping_planes_vertex:jS,color_fragment:QS,color_pars_fragment:ew,color_pars_vertex:tw,color_vertex:nw,common:iw,defaultnormal_vertex:rw,displacementmap_pars_vertex:sw,displacementmap_vertex:ow,emissivemap_fragment:aw,emissivemap_pars_fragment:lw,colorspace_fragment:cw,colorspace_pars_fragment:uw,envmap_fragment:hw,envmap_common_pars_fragment:fw,envmap_pars_fragment:dw,envmap_pars_vertex:pw,envmap_physical_pars_fragment:Tw,envmap_vertex:mw,fog_vertex:gw,fog_pars_vertex:xw,fog_fragment:bw,fog_pars_fragment:yw,gradientmap_pars_fragment:_w,lightmap_pars_fragment:vw,lights_lambert_fragment:Mw,lights_lambert_pars_fragment:Sw,lights_pars_begin:ww,lights_toon_fragment:Aw,lights_toon_pars_fragment:Ew,lights_phong_fragment:Rw,lights_phong_pars_fragment:Cw,lights_physical_fragment:Pw,lights_physical_pars_fragment:Iw,lights_fragment_begin:Lw,lights_fragment_maps:Fw,lights_fragment_end:Ow,lightprobes_pars_fragment:Nw,logdepthbuf_fragment:Dw,logdepthbuf_pars_fragment:Uw,logdepthbuf_pars_vertex:Bw,logdepthbuf_vertex:kw,map_fragment:zw,map_pars_fragment:Vw,map_particle_fragment:Gw,map_particle_pars_fragment:Hw,metalnessmap_fragment:Ww,metalnessmap_pars_fragment:Xw,morphinstance_vertex:Yw,morphcolor_vertex:qw,morphnormal_vertex:$w,morphtarget_pars_vertex:Kw,morphtarget_vertex:Zw,normal_fragment_begin:Jw,normal_fragment_maps:jw,normal_pars_fragment:Qw,normal_pars_vertex:e2,normal_vertex:t2,normalmap_pars_fragment:n2,clearcoat_normal_fragment_begin:i2,clearcoat_normal_fragment_maps:r2,clearcoat_pars_fragment:s2,iridescence_pars_fragment:o2,opaque_fragment:a2,packing:l2,premultiplied_alpha_fragment:c2,project_vertex:u2,dithering_fragment:h2,dithering_pars_fragment:f2,roughnessmap_fragment:d2,roughnessmap_pars_fragment:p2,shadowmap_pars_fragment:m2,shadowmap_pars_vertex:g2,shadowmap_vertex:x2,shadowmask_pars_fragment:b2,skinbase_vertex:y2,skinning_pars_vertex:_2,skinning_vertex:v2,skinnormal_vertex:M2,specularmap_fragment:S2,specularmap_pars_fragment:w2,tonemapping_fragment:T2,tonemapping_pars_fragment:A2,transmission_fragment:E2,transmission_pars_fragment:R2,uv_pars_fragment:C2,uv_pars_vertex:P2,uv_vertex:I2,worldpos_vertex:L2,background_vert:F2,background_frag:O2,backgroundCube_vert:N2,backgroundCube_frag:D2,cube_vert:U2,cube_frag:B2,depth_vert:k2,depth_frag:z2,distance_vert:V2,distance_frag:G2,equirect_vert:H2,equirect_frag:W2,linedashed_vert:X2,linedashed_frag:Y2,meshbasic_vert:q2,meshbasic_frag:$2,meshlambert_vert:K2,meshlambert_frag:Z2,meshmatcap_vert:J2,meshmatcap_frag:j2,meshnormal_vert:Q2,meshnormal_frag:eT,meshphong_vert:tT,meshphong_frag:nT,meshphysical_vert:iT,meshphysical_frag:rT,meshtoon_vert:sT,meshtoon_frag:oT,points_vert:aT,points_frag:lT,shadow_vert:cT,shadow_frag:uT,sprite_vert:hT,sprite_frag:fT},ve={common:{diffuse:{value:new W(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new He},alphaMap:{value:null},alphaMapTransform:{value:new He},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new He}},envmap:{envMap:{value:null},envMapRotation:{value:new He},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new He}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new He}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new He},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new He},normalScale:{value:new De(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new He},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new He}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new He}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new He}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new W(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:[]},probesMin:{value:[]},probesMax:{value:[]},probesResolution:{value:[]}},points:{diffuse:{value:new W(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new He},alphaTest:{value:0},uvTransform:{value:new He}},sprite:{diffuse:{value:new W(16777215)},opacity:{value:1},center:{value:new De(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new He},alphaMap:{value:null},alphaMapTransform:{value:new He},alphaTest:{value:0}}},Pi={basic:{uniforms:bn([ve.common,ve.specularmap,ve.envmap,ve.aomap,ve.lightmap,ve.fog]),vertexShader:Qe.meshbasic_vert,fragmentShader:Qe.meshbasic_frag},lambert:{uniforms:bn([ve.common,ve.specularmap,ve.envmap,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.fog,ve.lights,{emissive:{value:new W(0)},envMapIntensity:{value:1}}]),vertexShader:Qe.meshlambert_vert,fragmentShader:Qe.meshlambert_frag},phong:{uniforms:bn([ve.common,ve.specularmap,ve.envmap,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.fog,ve.lights,{emissive:{value:new W(0)},specular:{value:new W(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Qe.meshphong_vert,fragmentShader:Qe.meshphong_frag},standard:{uniforms:bn([ve.common,ve.envmap,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.roughnessmap,ve.metalnessmap,ve.fog,ve.lights,{emissive:{value:new W(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Qe.meshphysical_vert,fragmentShader:Qe.meshphysical_frag},toon:{uniforms:bn([ve.common,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.gradientmap,ve.fog,ve.lights,{emissive:{value:new W(0)}}]),vertexShader:Qe.meshtoon_vert,fragmentShader:Qe.meshtoon_frag},matcap:{uniforms:bn([ve.common,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.fog,{matcap:{value:null}}]),vertexShader:Qe.meshmatcap_vert,fragmentShader:Qe.meshmatcap_frag},points:{uniforms:bn([ve.points,ve.fog]),vertexShader:Qe.points_vert,fragmentShader:Qe.points_frag},dashed:{uniforms:bn([ve.common,ve.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Qe.linedashed_vert,fragmentShader:Qe.linedashed_frag},depth:{uniforms:bn([ve.common,ve.displacementmap]),vertexShader:Qe.depth_vert,fragmentShader:Qe.depth_frag},normal:{uniforms:bn([ve.common,ve.bumpmap,ve.normalmap,ve.displacementmap,{opacity:{value:1}}]),vertexShader:Qe.meshnormal_vert,fragmentShader:Qe.meshnormal_frag},sprite:{uniforms:bn([ve.sprite,ve.fog]),vertexShader:Qe.sprite_vert,fragmentShader:Qe.sprite_frag},background:{uniforms:{uvTransform:{value:new He},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Qe.background_vert,fragmentShader:Qe.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new He}},vertexShader:Qe.backgroundCube_vert,fragmentShader:Qe.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Qe.cube_vert,fragmentShader:Qe.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Qe.equirect_vert,fragmentShader:Qe.equirect_frag},distance:{uniforms:bn([ve.common,ve.displacementmap,{referencePosition:{value:new U},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Qe.distance_vert,fragmentShader:Qe.distance_frag},shadow:{uniforms:bn([ve.lights,ve.fog,{color:{value:new W(0)},opacity:{value:1}}]),vertexShader:Qe.shadow_vert,fragmentShader:Qe.shadow_frag}};Pi.physical={uniforms:bn([Pi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new He},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new He},clearcoatNormalScale:{value:new De(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new He},diffuseRoughness:{value:0},diffuseRoughnessMap:{value:null},diffuseRoughnessMapTransform:{value:new He},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new He},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new He},sheen:{value:0},sheenColor:{value:new W(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new He},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new He},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new He},transmissionSamplerSize:{value:new De},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new He},attenuationDistance:{value:0},attenuationColor:{value:new W(0)},specularColor:{value:new W(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new He},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new He},anisotropyVector:{value:new De},anisotropyMap:{value:null},anisotropyMapTransform:{value:new He}}]),vertexShader:Qe.meshphysical_vert,fragmentShader:Qe.meshphysical_frag};var Au={r:0,b:0,g:0},dT=new Be,Xx=new He;Xx.set(-1,0,0,0,1,0,0,0,1);function pT(i,e,t,n,r,s){let o=new W(0),a=r===!0?0:1,l,c,u=null,h=0,f=null;function d(b){let v=b.isScene===!0?b.background:null;if(v&&v.isTexture){let y=b.backgroundBlurriness>0;v=e.get(v,y)}return v}function p(b){let v=!1,y=d(b);y===null?g(o,a):y&&y.isColor&&(g(y,1),v=!0);let M=i.xr.getEnvironmentBlendMode();M==="additive"?t.buffers.color.setClear(0,0,0,1,s):M==="alpha-blend"&&t.buffers.color.setClear(0,0,0,0,s),(i.autoClear||v)&&(t.buffers.depth.setTest(!0),t.buffers.depth.setMask(!0),t.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function x(b,v){let y=d(v);y&&y.isCubeTexture?(c===void 0&&(c=new we(new Fr(1,1,1),new Mi({name:"BackgroundCubeMaterial",uniforms:ys(Pi.backgroundCube.uniforms),vertexShader:Pi.backgroundCube.vertexShader,fragmentShader:Pi.backgroundCube.fragmentShader,side:un,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(M,S,_){this.matrixWorld.copyPosition(_.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(c)),c.material.uniforms.envMap.value=y,c.material.uniforms.backgroundBlurriness.value=v.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=v.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(dT.makeRotationFromEuler(v.backgroundRotation)).transpose(),y.isRenderTargetTexture===!1&&c.material.uniforms.backgroundRotation.value.premultiply(Xx),c.material.toneMapped=tt.getTransfer(y.colorSpace)!==Mt,(u!==y||h!==y.version||f!==i.toneMapping)&&(c.material.needsUpdate=!0,u=y,h=y.version,f=i.toneMapping),c.layers.enableAll(),b.unshift(c,c.geometry,c.material,0,0,null)):y&&y.isTexture&&(l===void 0&&(l=new we(new sn(2,2),new Mi({name:"BackgroundMaterial",uniforms:ys(Pi.background.uniforms),vertexShader:Pi.background.vertexShader,fragmentShader:Pi.background.fragmentShader,side:Ti,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(l)),l.material.uniforms.t2D.value=y,l.material.uniforms.backgroundIntensity.value=v.backgroundIntensity,l.material.toneMapped=tt.getTransfer(y.colorSpace)!==Mt,y.matrixAutoUpdate===!0&&y.updateMatrix(),l.material.uniforms.uvTransform.value.copy(y.matrix),(u!==y||h!==y.version||f!==i.toneMapping)&&(l.material.needsUpdate=!0,u=y,h=y.version,f=i.toneMapping),l.layers.enableAll(),b.unshift(l,l.geometry,l.material,0,0,null))}function g(b,v){b.getRGB(Au,od(i)),t.buffers.color.setClear(Au.r,Au.g,Au.b,v,s)}function m(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return o},setClearColor:function(b,v=1){o.set(b),a=v,g(o,a)},getClearAlpha:function(){return a},setClearAlpha:function(b){a=b,g(o,a)},render:p,addToRenderList:x,dispose:m}}function mT(i,e){let t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},r=f(null),s=r,o=!1;function a(C,O,D,P,I){let N=!1,F=h(C,P,D,O);s!==F&&(s=F,c(s.object)),N=d(C,P,D,I),N&&p(C,P,D,I),I!==null&&e.update(I,i.ELEMENT_ARRAY_BUFFER),(N||o)&&(o=!1,y(C,O,D,P),I!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(I).buffer))}function l(){return i.createVertexArray()}function c(C){return i.bindVertexArray(C)}function u(C){return i.deleteVertexArray(C)}function h(C,O,D,P){let I=P.wireframe===!0,N=n[O.id];N===void 0&&(N={},n[O.id]=N);let F=C.isInstancedMesh===!0?C.id:0,H=N[F];H===void 0&&(H={},N[F]=H);let B=H[D.id];B===void 0&&(B={},H[D.id]=B);let X=B[I];return X===void 0&&(X=f(l()),B[I]=X),X}function f(C){let O=[],D=[],P=[];for(let I=0;I=0){let V=I[B],re=N[B];if(re===void 0&&(B==="instanceMatrix"&&C.instanceMatrix&&(re=C.instanceMatrix),B==="instanceColor"&&C.instanceColor&&(re=C.instanceColor)),V===void 0||V.attribute!==re||re&&V.data!==re.data)return!0;F++}return s.attributesNum!==F||s.index!==P}function p(C,O,D,P){let I={},N=O.attributes,F=0,H=D.getAttributes();for(let B in H)if(H[B].location>=0){let V=N[B];V===void 0&&(B==="instanceMatrix"&&C.instanceMatrix&&(V=C.instanceMatrix),B==="instanceColor"&&C.instanceColor&&(V=C.instanceColor));let re={};re.attribute=V,V&&V.data&&(re.data=V.data),I[B]=re,F++}s.attributes=I,s.attributesNum=F,s.index=P}function x(){let C=s.newAttributes;for(let O=0,D=C.length;O=0){let X=I[H];if(X===void 0&&(H==="instanceMatrix"&&C.instanceMatrix&&(X=C.instanceMatrix),H==="instanceColor"&&C.instanceColor&&(X=C.instanceColor)),X!==void 0){let V=X.normalized,re=X.itemSize,be=e.get(X);if(be===void 0)continue;let Y=be.buffer,Q=be.type,se=be.bytesPerElement,Se=Q===i.INT||Q===i.UNSIGNED_INT||X.gpuType===Gc;if(X.isInterleavedBufferAttribute){let le=X.data,Ie=le.isInterleavedBuffer===!0?le.stride:le.itemSize,st=X.offset;if(le.isInstancedInterleavedBuffer||le.isInstancedBufferAttribute){for(let Te=0;Te0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";_="mediump"}return _==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp",u=l(c);u!==c&&(Le("WebGLRenderer:",c,"not supported, using",u,"instead."),c=u);let h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=t.logarithmicDepthBuffer===!0&&h===!1;t.reversedDepthBuffer===!0&&h===!1&&Le("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),t.logarithmicDepthBuffer===!0&&h===!0&&Le("WebGLRenderer: Logarithmic depth buffer is ignored when reversed depth buffer is enabled.");let d=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),p=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),x=i.getParameter(i.MAX_TEXTURE_SIZE),g=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),m=i.getParameter(i.MAX_VERTEX_ATTRIBS),b=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),v=i.getParameter(i.MAX_VARYING_VECTORS),y=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),M=i.getParameter(i.MAX_SAMPLES),S=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:l,textureFormatReadable:o,textureTypeReadable:a,precision:c,logarithmicDepthBuffer:f,reversedDepthBuffer:h,maxTextures:d,maxVertexTextures:p,maxTextureSize:x,maxCubemapSize:g,maxAttributes:m,maxVertexUniforms:b,maxVaryings:v,maxFragmentUniforms:y,maxSamples:M,samples:S}}function bT(i){let e=this,t=null,n=0,r=!1,s=!1,o=new si,a=new He,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(h,f){let d=h.length!==0||f||n!==0||r;return r=f,n=h.length,d},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,f){t=u(h,f,0)},this.setState=function(h,f,d){let p=h.clippingPlanes,x=h.clipIntersection,g=h.clipShadows,m=i.get(h);if(!r||p===null||p.length===0||s&&!g)s?u(null):c();else{let b=s?0:n,v=b*4,y=m.clippingState||null;l.value=y,y=u(p,f,v,d);for(let M=0;M!==v;++M)y[M]=t[M];m.clippingState=y,this.numIntersection=x?this.numPlanes:0,this.numPlanes+=b}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function u(h,f,d,p){let x=h!==null?h.length:0,g=null;if(x!==0){if(g=l.value,p!==!0||g===null){let m=d+x*4,b=f.matrixWorldInverse;a.getNormalMatrix(b),(g===null||g.length + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},r=new Fr(5,5,5),s=new Mi({name:"CubemapFromEquirect",uniforms:ys(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:un,blending:ms});s.uniforms.tEquirect.value=t;let o=new we(r,s),a=t.minFilter;return t.minFilter===Fn&&(t.minFilter=Ht),new xo(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,r);e.setRenderTarget(s)}},Sx=256,yT=3,_T=20,Yx=256,qx=16,vT=3,MT=new U,ST=new W,wo=class i{constructor(e){this._renderer=e,this._cubeSize=0,this._sourceTarget=null,this._cubeCamera=new xo(1,10,null),this._boxMesh=new we(new Fr(5,5,5),null),this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null,this._integrationMaterial=null}fromScene(e,t=0,n=.1,r=100,s={}){let{size:o=256,position:a=MT}=s,l=this._renderer;this._setSize(o);let c=this._allocateTarget(),u=this._getSourceTarget(!0);t>0&&(u.texture.mipmapsAutoUpdate=!1);let h=l.autoClear,f=l.autoClearColor,d=l.autoClearDepth,p=l.autoClearStencil,x=e.background;l.autoClear=!0,l.autoClearColor=!0,l.autoClearDepth=!0,l.autoClearStencil=!0,x===null&&(e.background=l.getClearColor(ST));let g=new xo(n,r,u);return g.position.copy(a),g.update(l,e),l.autoClear=h,l.autoClearColor=f,l.autoClearDepth=d,l.autoClearStencil=p,e.background=x,t>0&&(u.texture.mipmapsAutoUpdate=!0,this._blur(c,t)),this._applyPMREM(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Ax(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Tx(),this._compileMaterial(this._equirectMaterial))}dispose(){this._sourceTarget!==null&&this._sourceTarget.dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._integrationMaterial!==null&&this._integrationMaterial.dispose(),this._boxMesh.geometry.dispose()}static lodToRoughness(e,t){return t>0?1-Math.sqrt(1-e/t):0}_setSize(e){this._cubeSize=Math.max(Sx,id(e))}_fromTexture(e,t){e.mapping===xs||e.mapping===yo?this._setSize(e.image.length===0?Sx:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4);let n=t||this._allocateTarget();return this._textureToCubemap(e),this._applyPMREM(n),n}_allocateTarget(){let e=this._cubeSize,t=wx(e,!1,!1),n=Math.log2(e)-yT;for(let r=0;r<=n;r++)t.texture.mipmaps.push({width:e>>r,height:e>>r});return t.texture.name="PMREM",t.texture.isPMREMTexture=!0,t}_getSourceTarget(e=!1){let t=this._cubeSize,n=this._sourceTarget;return(n===null||n.width!==t||e&&n.depthBuffer===!1)&&(n!==null&&n.dispose(),this._sourceTarget=wx(t,!0,e)),this._sourceTarget}_compileMaterial(e){this._boxMesh.material=e,this._renderer.compile(this._boxMesh,this._cubeCamera.children[0])}_renderCube(e,t,n){let r=this._boxMesh,s=this._cubeCamera;r.material=n,s.renderTarget=e,s.activeMipmapLevel=t;let o=e.width>>t;e.viewport.set(0,0,o,o),s.update(this._renderer,r),e.viewport.set(0,0,e.width,e.height)}_textureToCubemap(e){let t;e.mapping===xs||e.mapping===yo?(this._cubemapMaterial===null&&(this._cubemapMaterial=Ax()),t=this._cubemapMaterial,t.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):(this._equirectMaterial===null&&(this._equirectMaterial=Tx()),t=this._equirectMaterial),t.uniforms.envMap.value=e,this._renderCube(this._getSourceTarget(),0,t)}_applyPMREM(e){this._ggxMaterial===null&&(this._ggxMaterial=wT(),this._integrationMaterial=TT());let t=this._cubeSize,n=e.texture.mipmaps.length-1,r=this._ggxMaterial.uniforms;r.envMap.value=this._sourceTarget.texture;let s=this._integrationMaterial.uniforms;s.envMap.value=this._sourceTarget.texture,s.sourceLod.value=Math.log2(t/qx);for(let o=0;o<=n;o++){let a=i.lodToRoughness(o,n);if(o>n-vT)s.roughness.value=a,this._renderCube(e,o,this._integrationMaterial);else{let l=a>0?Math.log2(t)+.5*Math.log2(6/(Yx*Math.pow(a,4)))+.5:0;r.roughness.value=a,r.lodBias.value=l,this._renderCube(e,o,this._ggxMaterial)}}}_blur(e,t){this._blurMaterial===null&&(this._blurMaterial=AT());let n=this._blurMaterial,r=n.uniforms,s=this._sourceTarget;r.sigma.value=Math.min(t,Math.PI)/Math.SQRT2,r.envMap.value=s.texture,this._renderCube(e,0,n),r.envMap.value=e.texture,this._renderCube(s,0,n)}};function wx(i,e,t){return new Ja(i,{minFilter:Fn,generateMipmaps:e,type:ai,colorSpace:Mn,depthBuffer:t})}function ja(i,e,t){return new Mi({name:i,uniforms:e,vertexShader:Qe.cube_vert,fragmentShader:t,side:un,blending:ms,depthTest:!1,depthWrite:!1})}function wT(){return ja("PMREMGGXConvolution",{envMap:{value:null},roughness:{value:0},lodBias:{value:0}},` + + #define GGX_SAMPLES ${Yx}u + + varying vec3 vWorldDirection; + + uniform samplerCube envMap; + uniform float roughness; + uniform float lodBias; + + #include + + // Van der Corput radical inverse + float radicalInverse_VdC( uint bits ) { + + bits = ( bits << 16u ) | ( bits >> 16u ); + bits = ( ( bits & 0x55555555u ) << 1u ) | ( ( bits & 0xAAAAAAAAu ) >> 1u ); + bits = ( ( bits & 0x33333333u ) << 2u ) | ( ( bits & 0xCCCCCCCCu ) >> 2u ); + bits = ( ( bits & 0x0F0F0F0Fu ) << 4u ) | ( ( bits & 0xF0F0F0F0u ) >> 4u ); + bits = ( ( bits & 0x00FF00FFu ) << 8u ) | ( ( bits & 0xFF00FF00u ) >> 8u ); + return float( bits ) * 2.3283064365386963e-10; // / 0x100000000 + + } + + // Hammersley sequence + vec2 hammersley( uint i, uint N ) { + + return vec2( float( i ) / float( N ), radicalInverse_VdC( i ) ); + + } + + void main() { + + vec3 N = normalize( vWorldDirection ); + + // For very low roughness, just sample the environment directly + if ( roughness < 0.001 ) { + + gl_FragColor = vec4( textureLod( envMap, N, 0.0 ).rgb, 1.0 ); + return; + + } + + float alpha = roughness * roughness; + float alpha2 = alpha * alpha; + + // Tangent space basis for VNDF sampling + vec3 up = abs( N.z ) < 0.999 ? vec3( 0.0, 0.0, 1.0 ) : vec3( 1.0, 0.0, 0.0 ); + vec3 tangent = normalize( cross( up, N ) ); + vec3 bitangent = cross( N, tangent ); + + vec3 prefilteredColor = vec3( 0.0 ); + float totalWeight = 0.0; + + for ( uint i = 0u; i < GGX_SAMPLES; i ++ ) { + + vec2 Xi = hammersley( i, GGX_SAMPLES ); + + // With V = N, sample the reflected direction directly. + float invQ = 1.0 / ( 1.0 - Xi.x + alpha2 * Xi.x ); + float NdotL = ( 1.0 - Xi.x - alpha2 * Xi.x ) * invQ; + + if ( NdotL > 0.0 ) { + + float phi = 2.0 * PI * Xi.y; + float sinTheta = 2.0 * alpha * sqrt( Xi.x * ( 1.0 - Xi.x ) ) * invQ; + vec3 L = N * NdotL + ( tangent * cos( phi ) + bitangent * sin( phi ) ) * sinTheta; + + // Match the source mip to the sample's solid angle. The terms + // independent of the sample are precomputed in lodBias. + float d = alpha2 * invQ; + float lod = max( log2( d ) + lodBias, 0.0 ); + + // Weight by NdotL for the split-sum approximation + prefilteredColor += textureLod( envMap, L, lod ).rgb * NdotL; + totalWeight += NdotL; + + } + + } + + gl_FragColor = vec4( prefilteredColor / totalWeight, 1.0 ); + + } + `)}function TT(){return ja("PMREMGGXIntegration",{envMap:{value:null},roughness:{value:0},sourceLod:{value:0},sourceSize:{value:qx}},` + + varying vec3 vWorldDirection; + + uniform samplerCube envMap; + uniform float roughness; + uniform float sourceLod; + uniform int sourceSize; + + void main() { + + vec3 N = normalize( vWorldDirection ); + + float alpha = roughness * roughness; + float alpha2 = alpha * alpha; + + float texelSize = 2.0 / float( sourceSize ); + + vec3 prefilteredColor = vec3( 0.0 ); + float totalWeight = 0.0; + + // Pair opposite texels: only the one in N's hemisphere contributes. + for ( int face = 0; face < 3; face ++ ) { + + for ( int y = 0; y < sourceSize; y ++ ) { + + for ( int x = 0; x < sourceSize; x ++ ) { + + vec2 uv = ( vec2( x, y ) + 0.5 ) * texelSize - 1.0; + vec3 texelDirection = face == 0 ? vec3( 1.0, uv ) : ( face == 1 ? vec3( uv.x, 1.0, uv.y ) : vec3( uv, 1.0 ) ); + + float invDistance = inversesqrt( 1.0 + dot( uv, uv ) ); + float NdotL = dot( N, texelDirection ); + texelDirection *= NdotL < 0.0 ? - 1.0 : 1.0; + NdotL = abs( NdotL ) * invDistance; + + // With V = N, NdotH squared is ( 1 + NdotL ) / 2. Common factors + // in the GGX distribution and texel solid angle cancel when normalized. + float d = 1.0 + alpha2 + ( alpha2 - 1.0 ) * NdotL; + float weight = NdotL * invDistance * invDistance * invDistance / ( d * d ); + + prefilteredColor += textureLod( envMap, texelDirection, sourceLod ).rgb * weight; + totalWeight += weight; + + } + + } + + } + + gl_FragColor = vec4( prefilteredColor / totalWeight, 1.0 ); + + } + `)}function AT(){return ja("PMREMSphericalGaussianBlur",{envMap:{value:null},sigma:{value:0}},` + + #define SAMPLES ${_T} + #define GOLDEN_ANGLE 2.39996322973 + + varying vec3 vWorldDirection; + + uniform samplerCube envMap; + uniform float sigma; + + #include + + void main() { + + vec3 outputDirection = normalize( vWorldDirection ); + + vec3 up = abs( outputDirection.z ) < 0.999 ? vec3( 0.0, 0.0, 1.0 ) : vec3( 1.0, 0.0, 0.0 ); + vec3 tangent = normalize( cross( up, outputDirection ) ); + vec3 bitangent = cross( outputDirection, tangent ); + + // Truncate the kernel at three standard deviations or at the antipode. + float thetaMax = min( 3.0 * sigma, PI ); + float truncation = 1.0 - exp( - 0.5 * thetaMax * thetaMax / ( sigma * sigma ) ); + + vec3 accumColor = vec3( 0.0 ); + float accumWeight = 0.0; + + for ( int i = 0; i < SAMPLES; i ++ ) { + + // Stratified inverse-CDF sampling of the Gaussian, placed on a golden-angle spiral. + float stratum = ( float( i ) + 0.5 ) / float( SAMPLES ); + float theta = sigma * sqrt( - 2.0 * log( 1.0 - stratum * truncation ) ); + float phi = float( i ) * GOLDEN_ANGLE; + + vec3 offset = cos( phi ) * tangent + sin( phi ) * bitangent; + vec3 sampleDirection = cos( theta ) * outputDirection + sin( theta ) * offset; + + // Correct the planar sample density to solid angle. + float weight = sin( theta ) / theta; + + accumColor += weight * textureLod( envMap, sampleDirection, 0.0 ).rgb; + accumWeight += weight; + + } + + gl_FragColor = vec4( accumColor / accumWeight, 1.0 ); + + } + `)}function Tx(){return ja("PMREMEquirectangularToCubemap",{envMap:{value:null}},` + + varying vec3 vWorldDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + // Average four subpixel samples to preserve small, bright features. + vec3 direction = normalize( vWorldDirection ); + vec3 dx = dFdx( direction ) * 0.25; + vec3 dy = dFdy( direction ) * 0.25; + + vec3 color = textureLod( envMap, equirectUv( normalize( direction - dx - dy ) ), 0.0 ).rgb; + color += textureLod( envMap, equirectUv( normalize( direction + dx - dy ) ), 0.0 ).rgb; + color += textureLod( envMap, equirectUv( normalize( direction - dx + dy ) ), 0.0 ).rgb; + color += textureLod( envMap, equirectUv( normalize( direction + dx + dy ) ), 0.0 ).rgb; + gl_FragColor = vec4( color * 0.25, 1.0 ); + + } + `)}function Ax(){return ja("PMREMCubemapToCubemap",{envMap:{value:null},flipEnvMap:{value:-1}},` + + varying vec3 vWorldDirection; + + uniform samplerCube envMap; + uniform float flipEnvMap; + + void main() { + + gl_FragColor = vec4( textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ).rgb, 1.0 ); + + } + `)}function ET(i){let e=new WeakMap,t=new WeakMap,n=null;function r(f,d=!1){return f==null?null:d?o(f):s(f)}function s(f){if(f&&f.isTexture){let d=f.mapping;if(d===zc||d===Vc)if(e.has(f)){let p=e.get(f).texture;return a(p,f.mapping)}else{let p=f.image;if(p&&p.height>0){let x=new Ja(p.height);return x.fromEquirectangularTexture(i,f),e.set(f,x),f.addEventListener("dispose",c),a(x.texture,f.mapping)}else return null}}return f}function o(f){if(f&&f.isTexture&&f.isPMREMTexture!==!0){let d=f.mapping,p=d===zc||d===Vc,x=d===xs||d===yo;if(p||x){let g=t.get(f),m=g!==void 0?g.texture.pmremVersion:0;if(f.isRenderTargetTexture&&f.pmremVersion!==m)return n===null&&(n=new wo(i)),g=p?n.fromEquirectangular(f,g):n.fromCubemap(f,g),g.texture.pmremVersion=f.pmremVersion,t.set(f,g),g.texture;if(g!==void 0)return g.texture;{let b=f.image;return p&&b&&b.height>0||x&&b&&l(b)?(n===null&&(n=new wo(i)),g=p?n.fromEquirectangular(f):n.fromCubemap(f),g.texture.pmremVersion=f.pmremVersion,t.set(f,g),f.addEventListener("dispose",u),g.texture):null}}}return f}function a(f,d){return d===zc?f.mapping=xs:d===Vc&&(f.mapping=yo),f}function l(f){let d=0,p=6;for(let x=0;xdelete r[p]);function a(p){l(p.target)}function l(p){p.index!==null&&e.remove(p.index);for(let g in p.attributes)e.remove(p.attributes[g]);p.removeEventListener("dispose",a),delete r[p.id],o.unregister(p);let x=s.get(p);x&&(e.remove(x),s.delete(p)),n.releaseStatesOfGeometry(p),p.isInstancedBufferGeometry===!0&&delete p._maxInstanceCount,t.memory.geometries--}function c(p,x){return r[x.id]!==void 0||(x.addEventListener("dispose",a),r[x.id]=new WeakRef(x),o.register(x,x.id,x),t.memory.geometries++),x}function u(p){let x=p.attributes;for(let g in x)e.update(x[g],i.ARRAY_BUFFER)}function h(p){let x=p.index,g=p.attributes.position,m=0;if(g===void 0)return;let b=x!==null?x.array.length:g.array.length/3-1,v=g.count>=65535?cs:xa,y=new v(Math.ceil(b/3)*6,1),M=y.array;if(x!==null){let _=x.array;m=x.version;for(let w=0,R=0;we.maxTextureSize&&(M=Math.ceil(y/e.maxTextureSize),y=e.maxTextureSize);let S=new Float32Array(y*M*4*h),_=new ga(S,y,M,h);_.type=Vn,_.needsUpdate=!0;let w=v*4;for(let A=0;A + #include + + void main() { + gl_FragColor = texture2D( tDiffuse, vUv ); + + #ifdef LINEAR_TONE_MAPPING + gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); + #elif defined( REINHARD_TONE_MAPPING ) + gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); + #elif defined( CINEON_TONE_MAPPING ) + gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); + #elif defined( ACES_FILMIC_TONE_MAPPING ) + gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); + #elif defined( AGX_TONE_MAPPING ) + gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); + #elif defined( NEUTRAL_TONE_MAPPING ) + gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); + #elif defined( CUSTOM_TONE_MAPPING ) + gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); + #endif + + #ifdef SRGB_TRANSFER + gl_FragColor = sRGBTransferOETF( gl_FragColor ); + #endif + }`,depthTest:!1,depthWrite:!1}),f=new we(u,h),d=new zn(-1,1,1,-1,0,1),p=null,x=null,g=!1,m,b=null,v=[],y=!1;this.setSize=function(M,S){o.setSize(M,S),a!==null&&a.setSize(M,S),l!==null&&l.setSize(M,S);for(let _=0;_0&&v[0].isRenderPass===!0;let S=o.width,_=o.height;v.length>0&&a===null&&(a=new wn(S,_,{type:ai,depthBuffer:!1,stencilBuffer:!1}),l=new wn(S,_,{type:ai,depthBuffer:!1,stencilBuffer:!1}));let w=r===!0&&v.some(R=>R.needsDepthTexture===!0);w!==(o.depthTexture!==null)&&(w===!0&&c===null&&(c=new er(S,_),s===!0&&(c.format=lr,c.type=bs)),o.dispose(),o.depthTexture=w?c:null,o.resolveDepthBuffer=w,o.storeMultisampledDepthBuffer=w);for(let R=0;R0)return i;let r=e*t,s=Ex[r];if(s===void 0&&(s=new Float32Array(r),Ex[r]=s),e!==0){n.toArray(s,0);for(let o=1,a=0;o!==e;++o)a+=t,i[o].toArray(s,a)}return s}function jt(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t0&&(this.seq=r.concat(s))}setValue(e,t,n,r){let s=this.map[t];s!==void 0&&s.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let s=0,o=t.length;s!==o;++s){let a=t[s],l=n[a.id];l.needsUpdate!==!1&&a.setValue(e,l.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,s=e.length;r!==s;++r){let o=e[r];o.id in t&&n.push(o)}return n}};function Fx(i,e,t){let n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}var SA=37297,wA=0;function TA(i,e){let t=i.split(` +`),n=[],r=Math.max(e-6,0),s=Math.min(e+6,t.length);for(let o=r;o":" "} ${a}: ${t[o]}`)}return n.join(` +`)}var Ox=new He;function AA(i){tt._getMatrix(Ox,tt.workingColorSpace,i);let e=`mat3( ${Ox.elements.map(t=>t.toFixed(4))} )`;switch(tt.getTransfer(i)){case pa:return[e,"LinearTransferOETF"];case Mt:return[e,"sRGBTransferOETF"];default:return Le("WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function Nx(i,e,t){let n=i.getShaderParameter(e,i.COMPILE_STATUS),s=(i.getShaderInfoLog(e)||"").trim();if(n&&s==="")return"";let o=/ERROR: 0:(\d+)/.exec(s);if(o){let a=parseInt(o[1]);return t.toUpperCase()+` + +`+s+` + +`+TA(i.getShaderSource(e),a)}else return s}function EA(i,e){let t=AA(e);return[`vec4 ${i}( vec4 value ) {`,` return ${t[1]}( vec4( ${t[0]} * value.rgb, value.a ) );`,"}"].join(` +`)}var RA={[Nf]:"Linear",[Df]:"Reinhard",[Uf]:"Cineon",[Bf]:"ACESFilmic",[zf]:"AgX",[Vf]:"Neutral",[kf]:"Custom"};function CA(i,e){let t=RA[e];return t===void 0?(Le("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+i+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+i+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}var Eu=new U;function PA(){tt.getLuminanceCoefficients(Eu);let i=Eu.x.toFixed(4),e=Eu.y.toFixed(4),t=Eu.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` +`)}function IA(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Za).join(` +`)}function LA(i){let e=[];for(let t in i){let n=i[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(` +`)}function FA(i,e){let t={},n=i.getProgramParameter(e,i.ACTIVE_ATTRIBUTES);for(let r=0;r/gm;function _d(i){return i.replace(OA,NA)}function NA(i,e){let t=Qe[e];if(t===void 0)throw new Error("THREE.WebGLProgram: Can not resolve #include <"+e+">");return _d(t)}var DA=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Bx(i){return i.replace(DA,UA)}function UA(i,e,t,n){let r="";for(let s=parseInt(e);s0&&(x+=` +`),g=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,d].filter(Za).join(` +`),g.length>0&&(g+=` +`)):(x=[kx(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,d,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.diffuseRoughnessMap?"#define USE_DIFFUSE_ROUGHNESSMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.diffuseRoughnessMapUv?"#define DIFFUSE_ROUGHNESSMAP_UV "+t.diffuseRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexNormals?"#define HAS_NORMAL":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(Za).join(` +`),g=[kx(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,d,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.envMap?"#define "+h:"",t.envMapPMREM?"#define ENVMAP_MAX_LOD "+t.envMapMaxLod+".0":"",t.envMapPMREM?"#define ENVMAP_SIZE "+t.envMapSize+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.diffuseRoughness?"#define USE_DIFFUSE_ROUGHNESS":"",t.diffuseRoughnessMap?"#define USE_DIFFUSE_ROUGHNESSMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.retroreflection?"#define USE_RETROREFLECTION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas||t.batchingColor?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Ei?"#define TONE_MAPPING":"",t.toneMapping!==Ei?Qe.tonemapping_pars_fragment:"",t.toneMapping!==Ei?CA("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Qe.colorspace_pars_fragment,EA("linearToOutputTexel",t.outputColorSpace),PA(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(Za).join(` +`)),o=_d(o),o=Dx(o,t),o=Ux(o,t),a=_d(a),a=Dx(a,t),a=Ux(a,t),o=Bx(o),a=Bx(a),t.isRawShaderMaterial!==!0&&(m=`#version 300 es +`,x=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+x,g=["#define varying in",t.glslVersion===td?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===td?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+g);let b=m+x+o,v=m+g+a,y=Fx(r,r.VERTEX_SHADER,b),M=Fx(r,r.FRAGMENT_SHADER,v);r.attachShader(p,y),r.attachShader(p,M),t.index0AttributeName!==void 0?r.bindAttribLocation(p,0,t.index0AttributeName):t.hasPositionAttribute===!0&&r.bindAttribLocation(p,0,"position"),r.linkProgram(p);function S(A){if(i.debug.checkShaderErrors){let C=r.getProgramInfoLog(p)||"",O=r.getShaderInfoLog(y)||"",D=r.getShaderInfoLog(M)||"",P=C.trim(),I=O.trim(),N=D.trim(),F=!0,H=!0;if(r.getProgramParameter(p,r.LINK_STATUS)===!1)if(F=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(r,p,y,M);else{let B=Nx(r,y,"vertex"),X=Nx(r,M,"fragment");Ge("WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(p,r.VALIDATE_STATUS)+` + +Material Name: `+A.name+` +Material Type: `+A.type+` + +Program Info Log: `+P+` +`+B+` +`+X)}else P!==""?Le("WebGLProgram: Program Info Log:",P):(I===""||N==="")&&(H=!1);H&&(A.diagnostics={runnable:F,programLog:P,vertexShader:{log:I,prefix:x},fragmentShader:{log:N,prefix:g}})}r.deleteShader(y),r.deleteShader(M),_=new So(r,p),w=FA(r,p)}let _;this.getUniforms=function(){return _===void 0&&S(this),_};let w;this.getAttributes=function(){return w===void 0&&S(this),w};let R=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return R===!1&&(R=r.getProgramParameter(p,SA)),R},this.destroy=function(){n.releaseStatesOfProgram(this),r.deleteProgram(p),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=wA++,this.cacheKey=e,this.usedTimes=1,this.program=p,this.vertexShader=y,this.fragmentShader=M,this}var XA=0,vd=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,n){let r=this._getShaderCacheForMaterial(e);return r.has(t)===!1&&(r.add(t),t.usedTimes++),r.has(n)===!1&&(r.add(n),n.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new Md(e),t.set(e,n)),n}},Md=class{constructor(e){this.id=XA++,this.code=e,this.usedTimes=0}};function YA(i){return i===Ur||i===Xa||i===Ya}function qA(i,e,t,n,r,s){let o=new co,a=new vd,l=new Set,c=[],u=new Map,h=n.logarithmicDepthBuffer,f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function d(_){return l.add(_),_===0?"uv":`uv${_}`}function p(_,w,R,A,C,O){let D=A.fog,P=C.geometry,I=_.isMeshStandardMaterial||_.isMeshLambertMaterial||_.isMeshPhongMaterial?A.environment:null,N=_.isMeshStandardMaterial||_.isMeshLambertMaterial&&!_.envMap||_.isMeshPhongMaterial&&!_.envMap,F=e.get(_.envMap||I,N),H=f[_.type],B=n.precision;_.precision!==null&&(B=n.getMaxPrecision(_.precision),B!==_.precision&&Le("WebGLProgram.getParameters:",_.precision,"not supported, using",B,"instead."));let X=P.morphAttributes.position||P.morphAttributes.normal||P.morphAttributes.color,V=X!==void 0?X.length:0,re=0;P.morphAttributes.position!==void 0&&(re=1),P.morphAttributes.normal!==void 0&&(re=2),P.morphAttributes.color!==void 0&&(re=3);let be,Y,Q,se;if(H){let _e=Pi[H];be=_e.vertexShader,Y=_e.fragmentShader}else{be=_.vertexShader,Y=_.fragmentShader;let _e=a.getVertexShaderStage(_),St=a.getFragmentShaderStage(_);a.update(_,_e,St),Q=_e.id,se=St.id}let Se=i.getRenderTarget(),le=i.state.buffers.depth.getReversed(),Ie=C.isInstancedMesh===!0,st=C.isBatchedMesh===!0,Te=!!_.map,ht=!!_.matcap,bt=!!F,et=bt&&F.isPMREMTexture===!0,Yt=!!_.aoMap,kt=!!_.lightMap,on=!!_.bumpMap&&_.wireframe===!1,Ot=!!_.normalMap,gi=!!_.displacementMap,en=!!_.emissiveMap,Hn=!!_.metalnessMap,Wn=!!_.roughnessMap,Xn=_.anisotropy>0,G=_.clearcoat>0,Yn=_.diffuseRoughness>0,Pt=_.dispersion>0,It=_.retroreflectivity>0,ye=_.iridescence>0,Zt=_.sheen>0,ze=_.transmission>0,We=Xn&&!!_.anisotropyMap,L=G&&!!_.clearcoatMap,T=G&&!!_.clearcoatNormalMap,$=G&&!!_.clearcoatRoughnessMap,oe=Yn&&!!_.diffuseRoughnessMap,ie=ye&&!!_.iridescenceMap,ue=ye&&!!_.iridescenceThicknessMap,ge=Zt&&!!_.sheenColorMap,ee=Zt&&!!_.sheenRoughnessMap,te=!!_.specularMap,fe=!!_.specularColorMap,k=!!_.specularIntensityMap,ne=ze&&!!_.transmissionMap,j=ze&&!!_.thicknessMap,de=!!_.gradientMap,ce=!!_.alphaMap,he=_.alphaTest>0,Oe=!!_.alphaHash,je=!!_.extensions,ae=Ei;_.toneMapped&&(Se===null||Se.isXRRenderTarget===!0)&&(ae=i.toneMapping);let Ne=et?F.isCompressedCubeTexture?F.image[0].mipmaps:F.mipmaps:null,Ze={shaderID:H,shaderType:_.type,shaderName:_.name,vertexShader:be,fragmentShader:Y,defines:_.defines,customVertexShaderID:Q,customFragmentShaderID:se,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:B,batching:st,batchingColor:st&&C._colorsTexture!==null,instancing:Ie,instancingColor:Ie&&C.instanceColor!==null,instancingMorph:Ie&&C.morphTexture!==null,outputColorSpace:Se===null?i.outputColorSpace:Se.isXRRenderTarget===!0?Se.texture.colorSpace:tt.workingColorSpace,alphaToCoverage:!!_.alphaToCoverage,map:Te,matcap:ht,envMap:bt,envMapMode:bt&&F.mapping,envMapPMREM:et,envMapMaxLod:et?Ne.length-1:null,envMapSize:et?Ne[0].width:null,aoMap:Yt,lightMap:kt,bumpMap:on,normalMap:Ot,displacementMap:gi,emissiveMap:en,normalMapObjectSpace:Ot&&_.normalMapType===ix,normalMapTangentSpace:Ot&&_.normalMapType===$a,packedNormalMap:Ot&&_.normalMapType===$a&&YA(_.normalMap.format),metalnessMap:Hn,roughnessMap:Wn,anisotropy:Xn,anisotropyMap:We,clearcoat:G,clearcoatMap:L,clearcoatNormalMap:T,clearcoatRoughnessMap:$,diffuseRoughness:Yn,diffuseRoughnessMap:oe,dispersion:Pt,retroreflection:It,iridescence:ye,iridescenceMap:ie,iridescenceThicknessMap:ue,sheen:Zt,sheenColorMap:ge,sheenRoughnessMap:ee,specularMap:te,specularColorMap:fe,specularIntensityMap:k,transmission:ze,transmissionMap:ne,thicknessMap:j,gradientMap:de,opaque:_.transparent===!1&&_.blending===Ai&&_.alphaToCoverage===!1,alphaMap:ce,alphaTest:he,alphaHash:Oe,combine:_.combine,mapUv:Te&&d(_.map.channel),aoMapUv:Yt&&d(_.aoMap.channel),lightMapUv:kt&&d(_.lightMap.channel),bumpMapUv:on&&d(_.bumpMap.channel),normalMapUv:Ot&&d(_.normalMap.channel),displacementMapUv:gi&&d(_.displacementMap.channel),emissiveMapUv:en&&d(_.emissiveMap.channel),metalnessMapUv:Hn&&d(_.metalnessMap.channel),roughnessMapUv:Wn&&d(_.roughnessMap.channel),anisotropyMapUv:We&&d(_.anisotropyMap.channel),clearcoatMapUv:L&&d(_.clearcoatMap.channel),clearcoatNormalMapUv:T&&d(_.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:$&&d(_.clearcoatRoughnessMap.channel),diffuseRoughnessMapUv:oe&&d(_.diffuseRoughnessMap.channel),iridescenceMapUv:ie&&d(_.iridescenceMap.channel),iridescenceThicknessMapUv:ue&&d(_.iridescenceThicknessMap.channel),sheenColorMapUv:ge&&d(_.sheenColorMap.channel),sheenRoughnessMapUv:ee&&d(_.sheenRoughnessMap.channel),specularMapUv:te&&d(_.specularMap.channel),specularColorMapUv:fe&&d(_.specularColorMap.channel),specularIntensityMapUv:k&&d(_.specularIntensityMap.channel),transmissionMapUv:ne&&d(_.transmissionMap.channel),thicknessMapUv:j&&d(_.thicknessMap.channel),alphaMapUv:ce&&d(_.alphaMap.channel),vertexTangents:!!P.attributes.tangent&&(Ot||Xn),vertexNormals:!!P.attributes.normal,vertexColors:_.vertexColors,vertexAlphas:_.vertexColors===!0&&!!P.attributes.color&&P.attributes.color.itemSize===4,pointsUvs:C.isPoints===!0&&!!P.attributes.uv&&(Te||ce),fog:!!D,useFog:_.fog===!0,fogExp2:!!D&&D.isFogExp2,flatShading:_.wireframe===!1&&(_.flatShading===!0||P.attributes.normal===void 0&&Ot===!1&&(_.isMeshLambertMaterial||_.isMeshPhongMaterial||_.isMeshStandardMaterial||_.isMeshPhysicalMaterial)),sizeAttenuation:_.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:le,skinning:C.isSkinnedMesh===!0,hasPositionAttribute:P.attributes.position!==void 0,morphTargets:P.morphAttributes.position!==void 0,morphNormals:P.morphAttributes.normal!==void 0,morphColors:P.morphAttributes.color!==void 0,morphTargetsCount:V,morphTextureStride:re,numSunLights:w.sun.length,numDirLights:w.directional.length,numPointLights:w.point.length,numSpotLights:w.spot.length,numSpotLightMaps:w.spotLightMap.length,numRectAreaLights:w.rectArea.length,numHemiLights:w.hemi.length,numSunLightShadows:w.sunShadowMap.length,numDirLightShadows:w.directionalShadowMap.length,numPointLightShadows:w.pointShadowMap.length,numSpotLightShadows:w.spotShadowMap.length,numSpotLightShadowsWithMaps:w.numSpotLightShadowsWithMaps,numLightProbes:w.numLightProbes,numLightProbeGrids:O.filter(_e=>_e.texture!==null).length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:_.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:ae,decodeVideoTexture:Te&&_.map.isVideoTexture===!0&&tt.getTransfer(_.map.colorSpace)===Mt,decodeVideoTextureEmissive:en&&_.emissiveMap.isVideoTexture===!0&&tt.getTransfer(_.emissiveMap.colorSpace)===Mt,premultipliedAlpha:_.premultipliedAlpha,doubleSided:_.side===ut,flipSided:_.side===un,useDepthPacking:_.depthPacking>=0,depthPacking:_.depthPacking||0,index0AttributeName:_.index0AttributeName,extensionClipCullDistance:je&&_.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(je&&_.extensions.multiDraw===!0||st)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:_.customProgramCacheKey()};return Ze.vertexUv1s=l.has(1),Ze.vertexUv2s=l.has(2),Ze.vertexUv3s=l.has(3),l.clear(),Ze}function x(_){let w=[];if(_.shaderID?w.push(_.shaderID):(w.push(_.customVertexShaderID),w.push(_.customFragmentShaderID)),_.defines!==void 0)for(let R in _.defines)w.push(R),w.push(_.defines[R]);return _.isRawShaderMaterial===!1&&(g(w,_),m(w,_),w.push(i.outputColorSpace)),w.push(_.customProgramCacheKey),w.join()}function g(_,w){_.push(w.precision),_.push(w.outputColorSpace),_.push(w.envMapMode),_.push(w.envMapPMREM),_.push(w.envMapMaxLod),_.push(w.envMapSize),_.push(w.mapUv),_.push(w.alphaMapUv),_.push(w.lightMapUv),_.push(w.aoMapUv),_.push(w.bumpMapUv),_.push(w.normalMapUv),_.push(w.displacementMapUv),_.push(w.emissiveMapUv),_.push(w.metalnessMapUv),_.push(w.roughnessMapUv),_.push(w.anisotropyMapUv),_.push(w.clearcoatMapUv),_.push(w.clearcoatNormalMapUv),_.push(w.clearcoatRoughnessMapUv),_.push(w.diffuseRoughnessMapUv),_.push(w.iridescenceMapUv),_.push(w.iridescenceThicknessMapUv),_.push(w.sheenColorMapUv),_.push(w.sheenRoughnessMapUv),_.push(w.specularMapUv),_.push(w.specularColorMapUv),_.push(w.specularIntensityMapUv),_.push(w.transmissionMapUv),_.push(w.thicknessMapUv),_.push(w.combine),_.push(w.fogExp2),_.push(w.sizeAttenuation),_.push(w.morphTargetsCount),_.push(w.numSunLights),_.push(w.numDirLights),_.push(w.numPointLights),_.push(w.numSpotLights),_.push(w.numSpotLightMaps),_.push(w.numHemiLights),_.push(w.numRectAreaLights),_.push(w.numSunLightShadows),_.push(w.numDirLightShadows),_.push(w.numPointLightShadows),_.push(w.numSpotLightShadows),_.push(w.numSpotLightShadowsWithMaps),_.push(w.numLightProbes),_.push(w.numLightProbeGrids),_.push(w.shadowMapType),_.push(w.toneMapping),_.push(w.numClippingPlanes),_.push(w.numClipIntersection),_.push(w.depthPacking)}function m(_,w){o.disableAll(),w.instancing&&o.enable(0),w.instancingColor&&o.enable(1),w.instancingMorph&&o.enable(2),w.matcap&&o.enable(3),w.envMap&&o.enable(4),w.normalMapObjectSpace&&o.enable(5),w.normalMapTangentSpace&&o.enable(6),w.clearcoat&&o.enable(7),w.iridescence&&o.enable(8),w.alphaTest&&o.enable(9),w.vertexColors&&o.enable(10),w.vertexAlphas&&o.enable(11),w.vertexUv1s&&o.enable(12),w.vertexUv2s&&o.enable(13),w.vertexUv3s&&o.enable(14),w.vertexTangents&&o.enable(15),w.anisotropy&&o.enable(16),w.alphaHash&&o.enable(17),w.batching&&o.enable(18),w.dispersion&&o.enable(19),w.retroreflection&&o.enable(24),w.diffuseRoughness&&o.enable(25),w.batchingColor&&o.enable(20),w.gradientMap&&o.enable(21),w.packedNormalMap&&o.enable(22),w.vertexNormals&&o.enable(23),_.push(o.mask),o.disableAll(),w.fog&&o.enable(0),w.useFog&&o.enable(1),w.flatShading&&o.enable(2),w.logarithmicDepthBuffer&&o.enable(3),w.reversedDepthBuffer&&o.enable(4),w.skinning&&o.enable(5),w.morphTargets&&o.enable(6),w.morphNormals&&o.enable(7),w.morphColors&&o.enable(8),w.premultipliedAlpha&&o.enable(9),w.shadowMapEnabled&&o.enable(10),w.doubleSided&&o.enable(11),w.flipSided&&o.enable(12),w.useDepthPacking&&o.enable(13),w.dithering&&o.enable(14),w.transmission&&o.enable(15),w.sheen&&o.enable(16),w.opaque&&o.enable(17),w.pointsUvs&&o.enable(18),w.decodeVideoTexture&&o.enable(19),w.decodeVideoTextureEmissive&&o.enable(20),w.alphaToCoverage&&o.enable(21),w.numLightProbeGrids>0&&o.enable(22),w.hasPositionAttribute&&o.enable(23),_.push(o.mask)}function b(_){let w=f[_.type],R;if(w){let A=Pi[w];R=_x.clone(A.uniforms)}else R=_.uniforms;return R}function v(_,w){let R=u.get(w);return R!==void 0?++R.usedTimes:(R=new WA(i,w,_,r),c.push(R),u.set(w,R)),R}function y(_){if(--_.usedTimes===0){let w=c.indexOf(_);c[w]=c[c.length-1],c.pop(),u.delete(_.cacheKey),_.destroy()}}function M(_){a.remove(_)}function S(){a.dispose()}return{getParameters:p,getProgramCacheKey:x,getUniforms:b,acquireProgram:v,releaseProgram:y,releaseShaderCache:M,programs:c,dispose:S}}function $A(){let i=new WeakMap;function e(o){return i.has(o)}function t(o){let a=i.get(o);return a===void 0&&(a={},i.set(o,a)),a}function n(o){i.delete(o)}function r(o,a,l){i.get(o)[a]=l}function s(){i=new WeakMap}return{has:e,get:t,remove:n,update:r,dispose:s}}function KA(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.materialVariant!==e.materialVariant?i.materialVariant-e.materialVariant:i.z!==e.z?i.z-e.z:i.id-e.id}function zx(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function Vx(){let i=[],e=0,t=[],n=[],r=[];function s(){e=0,t.length=0,n.length=0,r.length=0}function o(f){let d=0;return f.isInstancedMesh&&(d+=2),f.isSkinnedMesh&&(d+=1),d}function a(f,d,p,x,g,m){let b=i[e];return b===void 0?(b={id:f.id,object:f,geometry:d,material:p,materialVariant:o(f),groupOrder:x,renderOrder:f.renderOrder,z:g,group:m},i[e]=b):(b.id=f.id,b.object=f,b.geometry=d,b.material=p,b.materialVariant=o(f),b.groupOrder=x,b.renderOrder=f.renderOrder,b.z=g,b.group=m),e++,b}function l(f,d,p,x,g,m,b){b.reversedDepth===!0&&(g=-g);let v=a(f,d,p,x,g,m);p.transmission>0?n.push(v):p.transparent===!0?r.push(v):t.push(v)}function c(f,d,p,x,g,m){let b=a(f,d,p,x,g,m);p.transmission>0?n.unshift(b):p.transparent===!0?r.unshift(b):t.unshift(b)}function u(f,d){t.length>1&&t.sort(f||KA),n.length>1&&n.sort(d||zx),r.length>1&&r.sort(d||zx)}function h(){for(let f=e,d=i.length;f=s.length?(o=new Vx,s.push(o)):o=s[r],o}function t(){i=new WeakMap}return{get:e,dispose:t}}function JA(){let i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"SunLight":case"DirectionalLight":t={direction:new U,color:new W};break;case"SpotLight":t={position:new U,direction:new U,color:new W,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new U,color:new W,distance:0,decay:0};break;case"HemisphereLight":t={direction:new U,skyColor:new W,groundColor:new W};break;case"RectAreaLight":t={color:new W,position:new U,halfWidth:new U,halfHeight:new U};break}return i[e.id]=t,t}}}function jA(){let i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"SunLight":case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new De};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new De};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new De,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}var QA=0;function eE(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function tE(i){let e=new JA,t=jA(),n={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)n.probe.push(new U);let r=new U,s=new Be,o=new Be;function a(c){let u=0,h=0,f=0;for(let O=0;O<9;O++)n.probe[O].set(0,0,0);let d=0,p=0,x=0,g=0,m=0,b=0,v=0,y=0,M=0,S=0,_=0,w=0,R=0,A=0;c.sort(eE);for(let O=0,D=c.length;O0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ve.LTC_FLOAT_1,n.rectAreaLTC2=ve.LTC_FLOAT_2):(n.rectAreaLTC1=ve.LTC_HALF_1,n.rectAreaLTC2=ve.LTC_HALF_2)),n.ambient[0]=u,n.ambient[1]=h,n.ambient[2]=f;let C=n.hash;(C.sunLength!==d||C.directionalLength!==g||C.pointLength!==m||C.spotLength!==b||C.rectAreaLength!==v||C.hemiLength!==y||C.numSunShadows!==p||C.numDirectionalShadows!==M||C.numPointShadows!==S||C.numSpotShadows!==_||C.numSpotMaps!==w||C.numLightProbes!==A)&&(n.sun.length=d,n.directional.length=g,n.spot.length=b,n.rectArea.length=v,n.point.length=m,n.hemi.length=y,n.sunShadow.length=p,n.sunShadowMap.length=p,n.sunShadowMatrix.length=x,n.sunShadowCascade.length=x,n.directionalShadow.length=M,n.directionalShadowMap.length=M,n.directionalShadowMatrix.length=M,n.pointShadow.length=S,n.pointShadowMap.length=S,n.pointShadowMatrix.length=S,n.spotShadow.length=_,n.spotShadowMap.length=_,n.spotLightMatrix.length=_+w-R,n.spotLightMap.length=w,n.numSpotLightShadowsWithMaps=R,n.numLightProbes=A,C.sunLength=d,C.directionalLength=g,C.pointLength=m,C.spotLength=b,C.rectAreaLength=v,C.hemiLength=y,C.numSunShadows=p,C.numDirectionalShadows=M,C.numPointShadows=S,C.numSpotShadows=_,C.numSpotMaps=w,C.numLightProbes=A,n.version=QA++)}function l(c,u){let h=0,f=0,d=0,p=0,x=0,g=0,m=u.matrixWorldInverse;for(let b=0,v=c.length;bh.priority-f.priority||h.id-f.id)}function c(h){e.setupView(t,h)}let u={lightsArray:t,shadowsArray:n,lightProbeGridArray:r,camera:null,lights:e,transmissionRenderTarget:{},textureUnits:0};return{init:s,state:u,setupLights:l,setupLightsView:c,pushLight:o,pushShadow:a}}function nE(i){let e=new WeakMap;function t(r,s=0){let o=e.get(r),a;return o===void 0?(a=new Gx(i),e.set(r,[a])):s>=o.length?(a=new Gx(i),o.push(a)):a=o[s],a}function n(){e=new WeakMap}return{get:t,dispose:n}}var iE=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,rE=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg; + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r; + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); + gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); +}`,sE=[new U(1,0,0),new U(-1,0,0),new U(0,1,0),new U(0,-1,0),new U(0,0,1),new U(0,0,-1)],oE=[new U(0,-1,0),new U(0,-1,0),new U(0,0,1),new U(0,0,-1),new U(0,-1,0),new U(0,-1,0)],Hx=new Be,Ka=new U,gd=new U;function aE(i,e,t){let n=new Ir,r=new De,s=new De,o=new _t,a=new Rc,l=new Cc,c={},u=t.maxTextureSize,h={[Ti]:un,[un]:Ti,[ut]:ut},f=new Mi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new De},radius:{value:4}},vertexShader:iE,fragmentShader:rE}),d=f.clone();d.defines.HORIZONTAL_PASS=1;let p=new Fe;p.setAttribute("position",new wt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let x=new we(p,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=ka;let m=this.type;this.render=function(S,_,w){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||S.length===0)return;this.type===Fg&&(Le("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=ka);let R=i.getRenderTarget(),A=i.getActiveCubeFace(),C=i.getActiveMipmapLevel(),O=i.state;O.setBlending(ms),O.buffers.depth.getReversed()===!0?O.buffers.color.setClear(0,0,0,0):O.buffers.color.setClear(1,1,1,1),O.buffers.depth.setTest(!0),O.setScissorTest(!1);let D=m!==this.type;D&&_.traverse(function(P){P.material&&(Array.isArray(P.material)?P.material.forEach(I=>I.needsUpdate=!0):P.material.needsUpdate=!0)});for(let P=0,I=S.length;Pu||r.y>u)&&(r.x>u&&(s.x=Math.floor(u/H.x),r.x=s.x*H.x,F.mapSize.x=s.x),r.y>u&&(s.y=Math.floor(u/H.y),r.y=s.y*H.y,F.mapSize.y=s.y));let B=i.state.buffers.depth.getReversed();if(F.camera._reversedDepth=B,F.map===null||D===!0){if(F.map!==null&&(F.map.depthTexture!==null&&(F.map.depthTexture.dispose(),F.map.depthTexture=null),F.map.dispose()),this.type===bo){if(N.isPointLight){Le("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}F.map=new wn(r.x,r.y,{format:Ur,type:ai,minFilter:Ht,magFilter:Ht,generateMipmaps:!1}),F.map.texture.name=N.name+".shadowMap",F.map.depthTexture=new er(r.x,r.y,Vn),F.map.depthTexture.name=N.name+".shadowMapDepth",F.map.depthTexture.format=$i,F.map.depthTexture.compareFunction=null,F.map.depthTexture.minFilter=Ut,F.map.depthTexture.magFilter=Ut}else N.isPointLight?(F.map=new Ja(r.x),F.map.depthTexture=new Ma(r.x,oi)):(F.map=new wn(r.x,r.y),F.map.depthTexture=new er(r.x,r.y,oi)),F.map.depthTexture.name=N.name+".shadowMap",F.map.depthTexture.format=$i,this.type===ka?(F.map.depthTexture.compareFunction=B?Jf:Zf,F.map.depthTexture.minFilter=Ht,F.map.depthTexture.magFilter=Ht):(F.map.depthTexture.compareFunction=null,F.map.depthTexture.minFilter=Ut,F.map.depthTexture.magFilter=Ut);F.camera.updateProjectionMatrix()}F.map.isWebGLCubeRenderTarget!==!0&&(F.map.width!==r.x||F.map.height!==r.y)&&F.map.setSize(r.x,r.y);let X=F.map.isWebGLCubeRenderTarget?6:F.getViewportCount();N.isPointLight!==!0&&F.updateMatrices(N,w);let V=(F.camera.layers.mask&4294967294)!==0?F.camera.layers:w.layers;for(let re=0;re0||_.map&&_.alphaTest>0||_.alphaToCoverage===!0){let O=A.uuid,D=_.uuid,P=c[O];P===void 0&&(P={},c[O]=P);let I=P[D];I===void 0&&(I=A.clone(),P[D]=I,_.addEventListener("dispose",M)),A=I}if(A.visible=_.visible,A.wireframe=_.wireframe,R===bo?A.side=_.shadowSide!==null?_.shadowSide:_.side:A.side=_.shadowSide!==null?_.shadowSide:h[_.side],A.alphaMap=_.alphaMap,A.alphaTest=_.alphaToCoverage===!0?.5:_.alphaTest,A.map=_.map,A.clipShadows=_.clipShadows,A.clippingPlanes=_.clippingPlanes,A.clipIntersection=_.clipIntersection,A.displacementMap=_.displacementMap,A.displacementScale=_.displacementScale,A.displacementBias=_.displacementBias,A.wireframeLinewidth=_.wireframeLinewidth,A.linewidth=_.linewidth,w.isPointLight===!0&&A.isMeshDistanceMaterial===!0){let O=i.properties.get(A);O.light=w}return A}function y(S,_,w,R,A,C){if(S.visible===!1)return;if(S.layers.test(A)&&(S.isMesh||S.isLine||S.isPoints)&&(S.castShadow||S.receiveShadow&&C===bo)&&(!S.frustumCulled||S.intersectsFrustum(n))){S.modelViewMatrix.multiplyMatrices(w.matrixWorldInverse,S.matrixWorld);let P=e.update(S),I=S.material;if(Array.isArray(I)){let N=P.groups;for(let F=0,H=N.length;F=1):B.indexOf("OpenGL ES")!==-1&&(H=parseFloat(/^OpenGL ES (\d)/.exec(B)[1]),F=H>=2);let X=null,V={},re=i.getParameter(i.SCISSOR_BOX),be=i.getParameter(i.VIEWPORT),Y=new _t().fromArray(re),Q=new _t().fromArray(be);function se(k,ne,j,de){let ce=new Uint8Array(4),he=i.createTexture();i.bindTexture(k,he),i.texParameteri(k,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(k,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let Oe=0;Oe"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new De,u=new WeakMap,h=new Set,f,d=new WeakMap,p=new Set,x=new FinalizationRegistry(L=>p.delete(L)),g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function m(L,T){return g?new OffscreenCanvas(L,T):oo("canvas")}function b(L,T,$){let oe=1,ie=We(L);if((ie.width>$||ie.height>$)&&(oe=$/Math.max(ie.width,ie.height)),oe<1)if(typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&L instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&L instanceof ImageBitmap||typeof VideoFrame<"u"&&L instanceof VideoFrame){let ue=Math.floor(oe*ie.width),ge=Math.floor(oe*ie.height);f===void 0&&(f=m(ue,ge));let ee=T?m(ue,ge):f;return ee.width=ue,ee.height=ge,ee.getContext("2d").drawImage(L,0,0,ue,ge),Le("WebGLRenderer: Texture has been resized from ("+ie.width+"x"+ie.height+") to ("+ue+"x"+ge+")."),ee}else return"data"in L&&Le("WebGLRenderer: Image in DataTexture is too big ("+ie.width+"x"+ie.height+")."),L;return L}function v(L){return L.generateMipmaps}function y(L){i.generateMipmap(L)}function M(L){return L.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:L.isWebGL3DRenderTarget?i.TEXTURE_3D:L.isWebGLArrayRenderTarget||L.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function S(L,T,$,oe,ie,ue=!1){if(L!==null){if(i[L]!==void 0)return i[L];Le("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+L+"'")}let ge;oe&&(ge=e.get("EXT_texture_norm16"),ge||Le("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let ee=T;if(T===i.RED&&($===i.FLOAT&&(ee=i.R32F),$===i.HALF_FLOAT&&(ee=i.R16F),$===i.UNSIGNED_BYTE&&(ee=i.R8),$===i.UNSIGNED_SHORT&&ge&&(ee=ge.R16_EXT),$===i.SHORT&&ge&&(ee=ge.R16_SNORM_EXT)),T===i.RED_INTEGER&&($===i.UNSIGNED_BYTE&&(ee=i.R8UI),$===i.UNSIGNED_SHORT&&(ee=i.R16UI),$===i.UNSIGNED_INT&&(ee=i.R32UI),$===i.BYTE&&(ee=i.R8I),$===i.SHORT&&(ee=i.R16I),$===i.INT&&(ee=i.R32I)),T===i.RG&&($===i.FLOAT&&(ee=i.RG32F),$===i.HALF_FLOAT&&(ee=i.RG16F),$===i.UNSIGNED_BYTE&&(ee=i.RG8),$===i.UNSIGNED_SHORT&&ge&&(ee=ge.RG16_EXT),$===i.SHORT&&ge&&(ee=ge.RG16_SNORM_EXT)),T===i.RG_INTEGER&&($===i.UNSIGNED_BYTE&&(ee=i.RG8UI),$===i.UNSIGNED_SHORT&&(ee=i.RG16UI),$===i.UNSIGNED_INT&&(ee=i.RG32UI),$===i.BYTE&&(ee=i.RG8I),$===i.SHORT&&(ee=i.RG16I),$===i.INT&&(ee=i.RG32I)),T===i.RGB_INTEGER&&($===i.UNSIGNED_BYTE&&(ee=i.RGB8UI),$===i.UNSIGNED_SHORT&&(ee=i.RGB16UI),$===i.UNSIGNED_INT&&(ee=i.RGB32UI),$===i.BYTE&&(ee=i.RGB8I),$===i.SHORT&&(ee=i.RGB16I),$===i.INT&&(ee=i.RGB32I)),T===i.RGBA_INTEGER&&($===i.UNSIGNED_BYTE&&(ee=i.RGBA8UI),$===i.UNSIGNED_SHORT&&(ee=i.RGBA16UI),$===i.UNSIGNED_INT&&(ee=i.RGBA32UI),$===i.BYTE&&(ee=i.RGBA8I),$===i.SHORT&&(ee=i.RGBA16I),$===i.INT&&(ee=i.RGBA32I)),T===i.RGB&&($===i.UNSIGNED_SHORT&&ge&&(ee=ge.RGB16_EXT),$===i.SHORT&&ge&&(ee=ge.RGB16_SNORM_EXT),$===i.UNSIGNED_INT_5_9_9_9_REV&&(ee=i.RGB9_E5),$===i.UNSIGNED_INT_10F_11F_11F_REV&&(ee=i.R11F_G11F_B10F)),T===i.RGBA){let te=ue?pa:tt.getTransfer(ie);$===i.FLOAT&&(ee=i.RGBA32F),$===i.HALF_FLOAT&&(ee=i.RGBA16F),$===i.UNSIGNED_BYTE&&(ee=te===Mt?i.SRGB8_ALPHA8:i.RGBA8),$===i.UNSIGNED_SHORT&&ge&&(ee=ge.RGBA16_EXT),$===i.SHORT&&ge&&(ee=ge.RGBA16_SNORM_EXT),$===i.UNSIGNED_SHORT_4_4_4_4&&(ee=i.RGBA4),$===i.UNSIGNED_SHORT_5_5_5_1&&(ee=i.RGB5_A1)}return(ee===i.R16F||ee===i.R32F||ee===i.RG16F||ee===i.RG32F||ee===i.RGBA16F||ee===i.RGBA32F)&&e.get("EXT_color_buffer_float"),ee}function _(L,T){let $;return L?T===null||T===oi||T===bs?$=i.DEPTH24_STENCIL8:T===Vn?$=i.DEPTH32F_STENCIL8:T===vo&&($=i.DEPTH24_STENCIL8,Le("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):T===null||T===oi||T===bs?$=i.DEPTH_COMPONENT24:T===Vn?$=i.DEPTH_COMPONENT32F:T===vo&&($=i.DEPTH_COMPONENT16),$}function w(L,T){return v(L)===!0||L.isFramebufferTexture&&L.minFilter!==Ut&&L.minFilter!==Ht?Math.log2(Math.max(T.width,T.height))+1:L.mipmaps.length>0?L.mipmaps.length:L.isCompressedTexture&&Array.isArray(L.image)?T.mipmaps.length:1}function R(L){let T=new WeakRef(L);n.get(L).__ref=T,p.add(T),x.register(L,T,T)}function A(L){let T=n.get(L).__ref;T!==void 0&&(p.delete(T),x.unregister(T))}function C(L){D(L.target)}function O(L){P(L.target)}function D(L){L.removeEventListener("dispose",C),A(L),N(L),L.isVideoTexture&&u.delete(L),L.isHTMLTexture&&h.delete(L)}function P(L){L.removeEventListener("dispose",O),A(L),H(L)}function I(){for(let L of p){let T=L.deref();T!==void 0&&(T.isRenderTarget===!0?P(T):D(T))}p.clear(),h.clear()}function N(L){let T=n.get(L);if(T.__webglInit===void 0)return;let $=L.source,oe=d.get($);if(oe){let ie=oe[T.__cacheKey];ie.usedTimes--,ie.usedTimes===0&&F(L),Object.keys(oe).length===0&&d.delete($)}n.remove(L)}function F(L){let T=n.get(L);i.deleteTexture(T.__webglTexture);let $=L.source,oe=d.get($);delete oe[T.__cacheKey],o.memory.textures--}function H(L){let T=n.get(L);T.__depthDisposeCallback&&T.__depthDisposeCallback();let $=L.depthTexture;if($&&$.renderTarget===L&&D($),L.isWebGLCubeRenderTarget)for(let ie=0;ie<6;ie++){if(Array.isArray(T.__webglFramebuffer[ie]))for(let ue=0;ue=r.maxTextures&&Le("WebGLTextures: Trying to use "+(L+1)+" texture units while this GPU supports only "+r.maxTextures),B+=1,L}function Y(L){let T=[];return T.push(L.wrapS),T.push(L.wrapT),T.push(L.wrapR||0),T.push(L.magFilter),T.push(L.minFilter),T.push(L.anisotropy),T.push(L.internalFormat),T.push(L.format),T.push(L.type),T.push(L.generateMipmaps),T.push(L.mipmapsAutoUpdate),T.push(L.premultiplyAlpha),T.push(L.flipY),T.push(L.unpackAlignment),T.push(L.colorSpace),T.join()}function Q(L,T){let $=n.get(L);if(L.isVideoTexture&&Zt(L),L.isRenderTargetTexture===!1&&L.isExternalTexture!==!0&&L.version>0&&$.__version!==L.version){let oe=L.image;if(oe===null)Le("WebGLRenderer: Texture marked for update but no image data found.");else if(oe.complete===!1)Le("WebGLRenderer: Texture marked for update but image is incomplete");else{kt($,L,T);return}}else L.isExternalTexture&&($.__webglTexture=L.sourceTexture?L.sourceTexture:null);t.bindTexture(i.TEXTURE_2D,$.__webglTexture,i.TEXTURE0+T)}function se(L,T){let $=n.get(L);if(L.isRenderTargetTexture===!1&&L.version>0&&$.__version!==L.version){kt($,L,T);return}else L.isExternalTexture&&($.__webglTexture=L.sourceTexture?L.sourceTexture:null);t.bindTexture(i.TEXTURE_2D_ARRAY,$.__webglTexture,i.TEXTURE0+T)}function Se(L,T){let $=n.get(L);if(L.isRenderTargetTexture===!1&&L.version>0&&$.__version!==L.version){kt($,L,T);return}t.bindTexture(i.TEXTURE_3D,$.__webglTexture,i.TEXTURE0+T)}function le(L,T){let $=n.get(L);if(L.version>0&&$.__version!==L.version){on($,L,T);return}t.bindTexture(i.TEXTURE_CUBE_MAP,$.__webglTexture,i.TEXTURE0+T)}let Ie={[kn]:i.REPEAT,[ln]:i.CLAMP_TO_EDGE,[Rr]:i.MIRRORED_REPEAT},st={[Ut]:i.NEAREST,[_o]:i.NEAREST_MIPMAP_NEAREST,[ar]:i.NEAREST_MIPMAP_LINEAR,[Ht]:i.LINEAR,[Dr]:i.LINEAR_MIPMAP_NEAREST,[Fn]:i.LINEAR_MIPMAP_LINEAR},Te={[sx]:i.NEVER,[jf]:i.ALWAYS,[ox]:i.LESS,[Zf]:i.LEQUAL,[ax]:i.EQUAL,[Jf]:i.GEQUAL,[lx]:i.GREATER,[cx]:i.NOTEQUAL};function ht(L,T){if(T.type===Vn&&e.has("OES_texture_float_linear")===!1&&(T.magFilter===Ht||T.magFilter===Dr||T.magFilter===ar||T.magFilter===Fn||T.minFilter===Ht||T.minFilter===Dr||T.minFilter===ar||T.minFilter===Fn)&&Le("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(L,i.TEXTURE_WRAP_S,Ie[T.wrapS]),i.texParameteri(L,i.TEXTURE_WRAP_T,Ie[T.wrapT]),(L===i.TEXTURE_3D||L===i.TEXTURE_2D_ARRAY)&&i.texParameteri(L,i.TEXTURE_WRAP_R,Ie[T.wrapR]),i.texParameteri(L,i.TEXTURE_MAG_FILTER,st[T.magFilter]),i.texParameteri(L,i.TEXTURE_MIN_FILTER,st[T.minFilter]),T.compareFunction&&(i.texParameteri(L,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(L,i.TEXTURE_COMPARE_FUNC,Te[T.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(T.magFilter===Ut||T.minFilter!==ar&&T.minFilter!==Fn||T.type===Vn&&e.has("OES_texture_float_linear")===!1)return;if(T.anisotropy>1||n.get(T).__currentAnisotropy){let $=e.get("EXT_texture_filter_anisotropic");i.texParameterf(L,$.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(T.anisotropy,r.getMaxAnisotropy())),n.get(T).__currentAnisotropy=T.anisotropy}}}function bt(L,T){let $=!1;L.__webglInit===void 0&&(L.__webglInit=!0,T.addEventListener("dispose",C),R(T));let oe=T.source,ie=d.get(oe);ie===void 0&&(ie={},d.set(oe,ie));let ue=Y(T);if(ue!==L.__cacheKey){ie[ue]===void 0&&(ie[ue]={texture:i.createTexture(),usedTimes:0},o.memory.textures++,$=!0),ie[ue].usedTimes++;let ge=ie[L.__cacheKey];ge!==void 0&&(ie[L.__cacheKey].usedTimes--,ge.usedTimes===0&&F(T)),L.__cacheKey=ue,L.__webglTexture=ie[ue].texture}return $}function et(L,T,$){return Math.floor(Math.floor(L/$)/T)}function Yt(L,T,$,oe){let ue=L.updateRanges;if(ue.length===0)t.texSubImage2D(i.TEXTURE_2D,0,0,0,T.width,T.height,$,oe,T.data);else{ue.sort((k,ne)=>k.start-ne.start);let ge=0;for(let k=1;k0){ce&&he&&t.texStorage2D(i.TEXTURE_2D,je,ne,de[0].width,de[0].height);for(let ae=0,Ne=de.length;ae0){let Ze=cd(j.width,j.height,T.format,T.type);for(let _e of T.layerUpdates){let St=j.data.subarray(_e*Ze/j.data.BYTES_PER_ELEMENT,(_e+1)*Ze/j.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,ae,0,0,_e,j.width,j.height,1,fe,St)}}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,ae,0,0,0,j.width,j.height,te.depth,fe,j.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,ae,ne,j.width,j.height,te.depth,0,j.data,0,0);else Le("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else ce?Oe&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,ae,0,0,0,j.width,j.height,te.depth,fe,k,j.data):t.texImage3D(i.TEXTURE_2D_ARRAY,ae,ne,j.width,j.height,te.depth,0,fe,k,j.data);T.layerUpdates.size>0&&T.clearLayerUpdates()}else{ce&&he&&t.texStorage2D(i.TEXTURE_2D,je,ne,de[0].width,de[0].height);for(let ae=0,Ne=de.length;ae0){let ae=cd(te.width,te.height,T.format,T.type);for(let Ne of T.layerUpdates){let Ze=te.data.subarray(Ne*ae/te.data.BYTES_PER_ELEMENT,(Ne+1)*ae/te.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,Ne,te.width,te.height,1,fe,k,Ze)}T.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,te.width,te.height,te.depth,fe,k,te.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,ne,te.width,te.height,te.depth,0,fe,k,te.data);else if(T.isData3DTexture)ce?(he&&t.texStorage3D(i.TEXTURE_3D,je,ne,te.width,te.height,te.depth),Oe&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,te.width,te.height,te.depth,fe,k,te.data)):t.texImage3D(i.TEXTURE_3D,0,ne,te.width,te.height,te.depth,0,fe,k,te.data);else if(T.isFramebufferTexture){if(he)if(ce)t.texStorage2D(i.TEXTURE_2D,je,ne,te.width,te.height);else{let ae=te.width,Ne=te.height;for(let Ze=0;Ze>=1,Ne>>=1}}else if(T.isHTMLTexture){if("texElementImage2D"in i){let ae=i.canvas;if(ae.hasAttribute("layoutsubtree")||ae.setAttribute("layoutsubtree","true"),te.parentNode!==ae){ae.appendChild(te),h.add(T),ae.onpaint=Ne=>{let Ze=Ne.changedElements;for(let _e of h)Ze.includes(_e.image)&&(_e.needsUpdate=!0)},ae.requestPaint();return}if(i.texElementImage2D.length===3)i.texElementImage2D(i.TEXTURE_2D,i.RGBA8,te);else{let Ze=i.RGBA,_e=i.RGBA,St=i.UNSIGNED_BYTE;i.texElementImage2D(i.TEXTURE_2D,0,Ze,_e,St,te)}i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE)}}else if(de.length>0){if(ce&&he){let ae=We(de[0]);t.texStorage2D(i.TEXTURE_2D,je,ne,ae.width,ae.height)}for(let ae=0,Ne=de.length;ae0&&Ne++;let _e=We(ne[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,Ne,he,_e.width,_e.height)}for(let _e=0;_e<6;_e++)if(k){Oe?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+_e,0,0,0,ne[_e].width,ne[_e].height,de,ce,ne[_e].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+_e,0,he,ne[_e].width,ne[_e].height,0,de,ce,ne[_e].data);for(let St=0;St>ue),j=Math.max(1,T.height>>ue);ie===i.TEXTURE_3D||ie===i.TEXTURE_2D_ARRAY?t.texImage3D(ie,ue,te,ne,j,T.depth,0,ge,ee,null):t.texImage2D(ie,ue,te,ne,j,0,ge,ee,null)}t.bindFramebuffer(i.FRAMEBUFFER,L),ye(T)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,oe,ie,k.__webglTexture,0,It(T)):(ie===i.TEXTURE_2D||ie>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&ie<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,oe,ie,k.__webglTexture,ue),t.bindFramebuffer(i.FRAMEBUFFER,null)}function gi(L,T,$){if(i.bindRenderbuffer(i.RENDERBUFFER,L),T.depthBuffer){let oe=T.depthTexture,ie=oe&&oe.isDepthTexture?oe.type:null,ue=_(T.stencilBuffer,ie),ge=T.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;ye(T)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,It(T),ue,T.width,T.height):$?i.renderbufferStorageMultisample(i.RENDERBUFFER,It(T),ue,T.width,T.height):i.renderbufferStorage(i.RENDERBUFFER,ue,T.width,T.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,ge,i.RENDERBUFFER,L)}else{let oe=T.textures;for(let ie=0;ie{delete T.__boundDepthTexture,delete T.__depthDisposeCallback,oe.removeEventListener("dispose",ie)};oe.addEventListener("dispose",ie),T.__depthDisposeCallback=ie}T.__boundDepthTexture=oe}if(L.depthTexture&&!T.__autoAllocateDepthBuffer)if($)for(let oe=0;oe<6;oe++)en(T.__webglFramebuffer[oe],L,oe);else L.texture.mipmaps.length>0?en(T.__webglFramebuffer[0],L,0):en(T.__webglFramebuffer,L,0);else if($){T.__webglDepthbuffer=[];for(let oe=0;oe<6;oe++)if(t.bindFramebuffer(i.FRAMEBUFFER,T.__webglFramebuffer[oe]),T.__webglDepthbuffer[oe]===void 0)T.__webglDepthbuffer[oe]=i.createRenderbuffer(),gi(T.__webglDepthbuffer[oe],L,!1);else{let ie=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ue=T.__webglDepthbuffer[oe];i.bindRenderbuffer(i.RENDERBUFFER,ue),i.framebufferRenderbuffer(i.FRAMEBUFFER,ie,i.RENDERBUFFER,ue)}}else if(L.texture.mipmaps.length>0?t.bindFramebuffer(i.FRAMEBUFFER,T.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,T.__webglFramebuffer),T.__webglDepthbuffer===void 0)T.__webglDepthbuffer=i.createRenderbuffer(),gi(T.__webglDepthbuffer,L,!1);else{let ie=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ue=T.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,ue),i.framebufferRenderbuffer(i.FRAMEBUFFER,ie,i.RENDERBUFFER,ue)}t.bindFramebuffer(i.FRAMEBUFFER,null)}function Wn(L,T,$){let oe=n.get(L);T!==void 0&&Ot(oe.__webglFramebuffer,L,L.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),$!==void 0&&Hn(L)}function Xn(L){let T=L.texture,$=n.get(L),oe=n.get(T);L.addEventListener("dispose",O),R(L);let ie=L.textures,ue=L.isWebGLCubeRenderTarget===!0,ge=ie.length>1;if(ge||(oe.__webglTexture===void 0&&(oe.__webglTexture=i.createTexture()),oe.__version=T.version,o.memory.textures++),ue){$.__webglFramebuffer=[];for(let ee=0;ee<6;ee++)if(T.mipmaps.length>0){$.__webglFramebuffer[ee]=[];for(let te=0;te0){$.__webglFramebuffer=[];for(let ee=0;ee0&&ye(L)===!1){$.__webglMultisampledFramebuffer=i.createFramebuffer(),$.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,$.__webglMultisampledFramebuffer);for(let ee=0;ee0)for(let te=0;te0&&i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,T.mipmaps.length-1),t.unbindTexture()}else if(ge){for(let ee=0,te=ie.length;ee0)for(let te=0;te0&&i.texParameteri(ee,i.TEXTURE_MAX_LEVEL,T.mipmaps.length-1),t.unbindTexture()}L.depthBuffer&&Hn(L)}function G(L){let T=L.textures;for(let $=0,oe=T.length;$0){if(ye(L)===!1){let T=L.textures,$=L.width,oe=L.height,ie=i.COLOR_BUFFER_BIT,ue=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ge=n.get(L),ee=T.length>1;if(ee)for(let fe=0;fe0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ge.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ge.__webglFramebuffer);for(let fe=0;fe0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&T.__useRenderToTexture!==!1}function Zt(L){let T=o.render.frame;u.get(L)!==T&&(u.set(L,T),L.update())}function ze(L,T){let $=L.colorSpace,oe=L.format,ie=L.type;return L.isCompressedTexture===!0||L.isVideoTexture===!0||$!==Mn&&$!==li&&(tt.getTransfer($)===Mt?(oe!==Nn||ie!==On)&&Le("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Ge("WebGLTextures: Unsupported texture color space:",$)),T}function We(L){return typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement?(c.width=L.naturalWidth||L.width,c.height=L.naturalHeight||L.height):typeof VideoFrame<"u"&&L instanceof VideoFrame?(c.width=L.displayWidth,c.height=L.displayHeight):(c.width=L.width,c.height=L.height),c}this.allocateTextureUnit=be,this.resetTextureUnits=X,this.getTextureUnits=V,this.setTextureUnits=re,this.setTexture2D=Q,this.setTexture2DArray=se,this.setTexture3D=Se,this.setTextureCube=le,this.rebindTextures=Wn,this.setupRenderTarget=Xn,this.updateRenderTargetMipmap=G,this.updateMultisampleRenderTarget=Pt,this.setupDepthRenderbuffer=Hn,this.setupFrameBufferTexture=Ot,this.useMultisampledRTT=ye,this.dispose=I}function uE(i,e){function t(n,r=li){let s,o=tt.getTransfer(r);if(n===On)return i.UNSIGNED_BYTE;if(n===Hc)return i.UNSIGNED_SHORT_4_4_4_4;if(n===Wc)return i.UNSIGNED_SHORT_5_5_5_1;if(n===Xf)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===Yf)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===Hf)return i.BYTE;if(n===Wf)return i.SHORT;if(n===vo)return i.UNSIGNED_SHORT;if(n===Gc)return i.INT;if(n===oi)return i.UNSIGNED_INT;if(n===Vn)return i.FLOAT;if(n===ai)return i.HALF_FLOAT;if(n===qf)return i.ALPHA;if(n===$f)return i.RGB;if(n===Nn)return i.RGBA;if(n===$i)return i.DEPTH_COMPONENT;if(n===lr)return i.DEPTH_STENCIL;if(n===Xc)return i.RED;if(n===Yc)return i.RED_INTEGER;if(n===Ur)return i.RG;if(n===qc)return i.RG_INTEGER;if(n===$c)return i.RGBA_INTEGER;if(n===Va||n===Ga||n===Ha||n===Wa)if(o===Mt)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(n===Va)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Ga)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Ha)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Wa)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(n===Va)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Ga)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Ha)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Wa)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Kc||n===Zc||n===Jc||n===jc)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(n===Kc)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===Zc)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Jc)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===jc)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===Qc||n===eu||n===tu||n===nu||n===iu||n===Xa||n===ru)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(n===Qc||n===eu)return o===Mt?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(n===tu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(n===nu)return s.COMPRESSED_R11_EAC;if(n===iu)return s.COMPRESSED_SIGNED_R11_EAC;if(n===Xa)return s.COMPRESSED_RG11_EAC;if(n===ru)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===su||n===ou||n===au||n===lu||n===cu||n===uu||n===hu||n===fu||n===du||n===pu||n===mu||n===gu||n===xu||n===bu)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(n===su)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===ou)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===au)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===lu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===cu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===uu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===hu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===fu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===du)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===pu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===mu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===gu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===xu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===bu)return o===Mt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===yu||n===_u||n===vu)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(n===yu)return o===Mt?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===_u)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===vu)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===Mu||n===Su||n===Ya||n===wu)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(n===Mu)return s.COMPRESSED_RED_RGTC1_EXT;if(n===Su)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Ya)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===wu)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===bs?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}var hE=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,fE=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`,Sd=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new Sa(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new Mi({vertexShader:hE,fragmentShader:fE,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new we(new sn(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},wd=class extends yi{constructor(e,t){super();let n=this,r=null,s=1,o=null,a="local-floor",l=1,c=null,u=null,h=null,f=null,d=null,p=null,x=typeof XRWebGLBinding<"u",g=new Sd,m={},b=t.getContextAttributes(),v=null,y=null,M=[],S=[],_=new De,w=null,R=null,A=new Jt;A.viewport=new _t;let C=new Jt;C.viewport=new _t;let O=[A,C],D=new Uc,P=null,I=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Y){let Q=M[Y];return Q===void 0&&(Q=new uo,M[Y]=Q),Q.getTargetRaySpace()},this.getControllerGrip=function(Y){let Q=M[Y];return Q===void 0&&(Q=new uo,M[Y]=Q),Q.getGripSpace()},this.getHand=function(Y){let Q=M[Y];return Q===void 0&&(Q=new uo,M[Y]=Q),Q.getHandSpace()};function N(Y){let Q=S.indexOf(Y.inputSource);if(Q===-1)return;let se=M[Q];se!==void 0&&(se.update(Y.inputSource,Y.frame,c||o),se.dispatchEvent({type:Y.type,data:Y.inputSource}))}function F(){r.removeEventListener("select",N),r.removeEventListener("selectstart",N),r.removeEventListener("selectend",N),r.removeEventListener("squeeze",N),r.removeEventListener("squeezestart",N),r.removeEventListener("squeezeend",N),r.removeEventListener("end",F),r.removeEventListener("inputsourceschange",H);for(let Y=0;Y=0&&(S[Se]=null,M[Se].disconnect(se))}for(let Q=0;Q=S.length){S.push(se),Se=Ie;break}else if(S[Ie]===null){S[Ie]=se,Se=Ie;break}if(Se===-1)break}let le=M[Se];le&&le.connect(se)}}function B(Y,Q){Q===null?Y.matrixWorld.copy(Y.matrix):Y.matrixWorld.multiplyMatrices(Q.matrixWorld,Y.matrix),Y.matrixWorldInverse.copy(Y.matrixWorld).invert()}this.updateCamera=function(Y){if(r===null)return;let Q=Y.near,se=Y.far;g.texture!==null&&(g.depthNear>0&&(Q=g.depthNear),g.depthFar>0&&(se=g.depthFar)),D.near=C.near=A.near=Q,D.far=C.far=A.far=se,(P!==D.near||I!==D.far)&&(r.updateRenderState({depthNear:D.near,depthFar:D.far}),P=D.near,I=D.far),D.layers.mask=Y.layers.mask|6,A.layers.mask=D.layers.mask&-5,C.layers.mask=D.layers.mask&-3;let Se=Y.parent,le=D.cameras;B(D,Se);for(let Ie=0;Ie0&&(g.alphaTest.value=m.alphaTest);let b=e.get(m),v=b.envMap,y=b.envMapRotation;v&&(g.envMap.value=v,g.envMapRotation.value.setFromMatrix4(dE.makeRotationFromEuler(y)).transpose(),v.isCubeTexture&&v.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(eb),g.reflectivity.value=m.reflectivity,g.ior.value=m.ior,g.refractionRatio.value=m.refractionRatio),m.lightMap&&(g.lightMap.value=m.lightMap,g.lightMapIntensity.value=m.lightMapIntensity,t(m.lightMap,g.lightMapTransform)),m.aoMap&&(g.aoMap.value=m.aoMap,g.aoMapIntensity.value=m.aoMapIntensity,t(m.aoMap,g.aoMapTransform))}function o(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,m.map&&(g.map.value=m.map,t(m.map,g.mapTransform))}function a(g,m){g.dashSize.value=m.dashSize,g.totalSize.value=m.dashSize+m.gapSize,g.scale.value=m.scale}function l(g,m,b,v){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.size.value=m.size*b,g.scale.value=v*.5,m.map&&(g.map.value=m.map,t(m.map,g.uvTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,t(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function c(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.rotation.value=m.rotation,m.map&&(g.map.value=m.map,t(m.map,g.mapTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,t(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function u(g,m){g.specular.value.copy(m.specular),g.shininess.value=Math.max(m.shininess,1e-4)}function h(g,m){m.gradientMap&&(g.gradientMap.value=m.gradientMap)}function f(g,m){g.metalness.value=m.metalness,m.metalnessMap&&(g.metalnessMap.value=m.metalnessMap,t(m.metalnessMap,g.metalnessMapTransform)),g.roughness.value=m.roughness,m.roughnessMap&&(g.roughnessMap.value=m.roughnessMap,t(m.roughnessMap,g.roughnessMapTransform)),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)}function d(g,m,b){g.ior.value=m.ior,m.diffuseRoughness>0&&(g.diffuseRoughness.value=m.diffuseRoughness,m.diffuseRoughnessMap&&(g.diffuseRoughnessMap.value=m.diffuseRoughnessMap,t(m.diffuseRoughnessMap,g.diffuseRoughnessMapTransform))),m.sheen>0&&(g.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),g.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(g.sheenColorMap.value=m.sheenColorMap,t(m.sheenColorMap,g.sheenColorMapTransform)),m.sheenRoughnessMap&&(g.sheenRoughnessMap.value=m.sheenRoughnessMap,t(m.sheenRoughnessMap,g.sheenRoughnessMapTransform))),m.clearcoat>0&&(g.clearcoat.value=m.clearcoat,g.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(g.clearcoatMap.value=m.clearcoatMap,t(m.clearcoatMap,g.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,t(m.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(g.clearcoatNormalMap.value=m.clearcoatNormalMap,t(m.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===un&&g.clearcoatNormalScale.value.negate())),m.dispersion>0&&(g.dispersion.value=m.dispersion),m.retroreflectivity>0&&(g.retroreflectivity.value=m.retroreflectivity),m.iridescence>0&&(g.iridescence.value=m.iridescence,g.iridescenceIOR.value=m.iridescenceIOR,g.iridescenceThicknessMinimum.value=m.iridescenceThicknessMinimum,g.iridescenceThicknessMaximum.value=m.iridescenceThicknessMaximum,m.iridescenceMap&&(g.iridescenceMap.value=m.iridescenceMap,t(m.iridescenceMap,g.iridescenceMapTransform)),m.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=m.iridescenceThicknessMap,t(m.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),m.transmission>0&&(g.transmission.value=m.transmission,g.transmissionSamplerMap.value=b.texture,g.transmissionSamplerSize.value.set(b.width,b.height),m.transmissionMap&&(g.transmissionMap.value=m.transmissionMap,t(m.transmissionMap,g.transmissionMapTransform)),g.thickness.value=m.thickness,m.thicknessMap&&(g.thicknessMap.value=m.thicknessMap,t(m.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=m.attenuationDistance,g.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(g.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(g.anisotropyMap.value=m.anisotropyMap,t(m.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=m.specularIntensity,g.specularColor.value.copy(m.specularColor),m.specularColorMap&&(g.specularColorMap.value=m.specularColorMap,t(m.specularColorMap,g.specularColorMapTransform)),m.specularIntensityMap&&(g.specularIntensityMap.value=m.specularIntensityMap,t(m.specularIntensityMap,g.specularIntensityMapTransform))}function p(g,m){m.matcap&&(g.matcap.value=m.matcap)}function x(g,m){let b=e.get(m).light;g.referencePosition.value.setFromMatrixPosition(b.matrixWorld),g.nearDistance.value=b.shadow.camera.near,g.farDistance.value=b.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:r}}function mE(i,e,t,n){let r={},s={};function o(b,v){let y=v.program;n.uniformBlockBinding(b,y,r[b.id])}function a(b,v){let y=r[b.id];y===void 0&&(p(b),y=l(b),r[b.id]=y,b.addEventListener("dispose",g));let M=v.program;n.updateUBOMapping(b,M);let S=e.render.frame;s[b.id]!==S&&(c(b),s[b.id]=S)}function l(b){let v=i.createBuffer(),y=b.__size,M=b.usage;return i.bindBuffer(i.UNIFORM_BUFFER,v),i.bufferData(i.UNIFORM_BUFFER,y,M),i.bindBuffer(i.UNIFORM_BUFFER,null),v}function c(b){let v=r[b.id],y=b.uniforms,M=b.__cache;i.bindBuffer(i.UNIFORM_BUFFER,v);for(let S=0,_=y.length;S<_;S++){let w=y[S];if(Array.isArray(w))for(let R=0,A=w.length;R0&&(y+=M-S),b.__size=y,b.__cache={},this}function x(b,v){let y={boundary:0,storage:0};return typeof b=="number"||typeof b=="boolean"?(y.boundary=4,y.storage=4):b.isVector2?(y.boundary=8,y.storage=8):b.isVector3||b.isColor?(y.boundary=16,y.storage=12):b.isVector4?(y.boundary=16,y.storage=16):b.isMatrix3?(y.boundary=16,y.storage=48):b.isMatrix4?(y.boundary=16,y.storage=64):b.isTexture?Le("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(b)?(y.boundary=16,y.storage=b.byteLength):Le("WebGLRenderer: Unsupported uniform value type.",b),v===!0&&(y.boundary=16,y.storage=Math.ceil(y.storage/16)*16),y}function g(b){let v=b.target;v.removeEventListener("dispose",g),i.deleteBuffer(r[v.id]),delete r[v.id],delete s[v.id]}function m(){for(let b in r)i.deleteBuffer(r[b]);r={},s={}}return{bind:o,update:a,dispose:m}}var gE=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),Ci=null;function xE(){return Ci===null&&(Ci=new fo(gE,16,16,Ur,ai),Ci.name="DFG_LUT",Ci.minFilter=Ht,Ci.magFilter=Ht,Ci.wrapS=ln,Ci.wrapT=ln,Ci.generateMipmaps=!1,Ci.needsUpdate=!0),Ci}var kr=class{constructor(e={}){let{canvas:t=ux(),context:n=null,depth:r=!0,stencil:s=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:h=!1,reversedDepthBuffer:f=!1,outputBufferType:d=On}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=n.getContextAttributes().alpha}else p=o;let x=d,g=new Set([$c,qc,Yc]),m=new Set([On,oi,vo,bs,Hc,Wc]),b=new Uint32Array(4),v=new Int32Array(4),y={textures:[],min:[],max:[],resolution:[]},M=null,S=null,_=[],w=[],R=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Ei,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let A=this,C=!1,O=null,D=null,P=null,I=null;this._outputColorSpace=ft;let N=0,F=0,H=null,B=-1,X=null,V=new _t,re=new _t,be=null,Y=new W(0),Q=0,se=t.width,Se=t.height,le=1,Ie=null,st=null,Te=new _t(0,0,se,Se),ht=new _t(0,0,se,Se),bt=!1,et=new Ir,Yt=new wc,kt=!1,on=!1,Ot=new Be,gi=new U,en=new _t,Hn={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Wn=!1;function Xn(){return H===null?le:1}let G=n;function Yn(E,z){return t.getContext(E,z)}let Pt,It,ye,Zt,ze,We,L,T,$,oe,ie,ue,ge,ee,te,fe,k,ne,j,de,ce,he,Oe;try{let E={alpha:!0,depth:r,stencil:s,antialias:a,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:u,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${"187"}`),t.addEventListener("webglcontextlost",Ne,!1),t.addEventListener("webglcontextrestored",Ze,!1),t.addEventListener("webglcontextcreationerror",_e,!1),G===null){let z="webgl2";if(G=Yn(z,E),G===null)throw Yn(z)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}je()}catch(E){throw t.removeEventListener("webglcontextlost",Ne,!1),t.removeEventListener("webglcontextrestored",Ze,!1),t.removeEventListener("webglcontextcreationerror",_e,!1),Ge("WebGLRenderer: "+E.message),E}function je(){Pt=new RT(G),Pt.init(),ce=new uE(G,Pt),It=new xT(G,Pt,e,ce),ye=new lE(G,Pt),It.reversedDepthBuffer&&f&&ye.buffers.depth.setReversed(!0),D=G.createFramebuffer(),P=G.createFramebuffer(),I=G.createFramebuffer(),Zt=new IT(G),ze=new $A,We=new cE(G,Pt,ye,ze,It,ce,Zt),L=new ET(A),T=new FS(G),he=new mT(G,T),$=new CT(G,T,Zt,he),oe=new FT(G,$,T,he,Zt),ne=new LT(G,It,We),te=new bT(ze),ie=new qA(A,L,Pt,It,he,te),ue=new pE(A,ze),ge=new ZA,ee=new nE(Pt),k=new pT(A,L,ye,oe,p,l),fe=new aE(A,oe,It),Oe=new mE(G,Zt,It,ye),j=new gT(G,Pt,Zt),de=new PT(G,Pt,Zt),Zt.programs=ie.programs,A.capabilities=It,A.extensions=Pt,A.properties=ze,A.renderLists=ge,A.shadowMap=fe,A.state=ye,A.info=Zt}x!==On&&(R=new NT(x,t.width,t.height,a,r,s));let ae=new wd(A,G);this.xr=ae,this.getContext=function(){return G},this.getContextAttributes=function(){return G.getContextAttributes()},this.forceContextLoss=function(){let E=Pt.get("WEBGL_lose_context");E&&E.loseContext()},this.forceContextRestore=function(){let E=Pt.get("WEBGL_lose_context");E&&E.restoreContext()},this.getPixelRatio=function(){return le},this.setPixelRatio=function(E){E!==void 0&&(le=E,this.setSize(se,Se,!1))},this.getSize=function(E){return E.set(se,Se)},this.setSize=function(E,z,J=!0){if(ae.isPresenting){Le("WebGLRenderer: Can't change size while VR device is presenting.");return}se=E,Se=z,t.width=Math.floor(E*le),t.height=Math.floor(z*le),J===!0&&(t.style.width=E+"px",t.style.height=z+"px"),R!==null&&R.setSize(t.width,t.height),this.setViewport(0,0,E,z)},this.getDrawingBufferSize=function(E){return E.set(se*le,Se*le).floor()},this.setDrawingBufferSize=function(E,z,J){se=E,Se=z,le=J,t.width=Math.floor(E*J),t.height=Math.floor(z*J),this.setViewport(0,0,E,z)},this.setEffects=function(E){if(x===On){Ge("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(E){for(let z=0;z{function xe(){if(q.forEach(function(Ae){let Me=ze.get(Ae).currentProgram;(Me===void 0||Me.isReady())&&q.delete(Ae)}),q.size===0){K(E);return}setTimeout(xe,10)}Pt.get("KHR_parallel_shader_compile")!==null?xe():setTimeout(xe,10)})};let Bh=null;function ZM(E){Bh&&Bh(E)}function n0(){$r.stop()}function i0(){$r.start()}let $r=new Wx;$r.setAnimationLoop(ZM),typeof self<"u"&&$r.setContext(self),this.setAnimationLoop=function(E){Bh=E,ae.setAnimationLoop(E),E===null?$r.stop():$r.start()},ae.addEventListener("sessionstart",n0),ae.addEventListener("sessionend",i0),this.render=function(E,z){if(z!==void 0&&z.isCamera!==!0){Ge("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(C===!0)return;O!==null&&O.renderStart(E,z);let J=ae.enabled===!0&&ae.isPresenting===!0,q=R!==null&&(H===null||J)&&R.begin(A,H);if(E.matrixWorldAutoUpdate===!0&&E.updateMatrixWorld(),z.parent===null&&z.matrixWorldAutoUpdate===!0&&z.updateMatrixWorld(),ae.enabled===!0&&ae.isPresenting===!0&&(R===null||R.isCompositing()===!1)&&(ae.cameraAutoUpdate===!0&&ae.updateCamera(z),z=ae.getCamera()),E.isScene===!0&&E.onBeforeRender(A,E,z,H),S=ee.get(E,w.length),S.init(z),S.state.textureUnits=We.getTextureUnits(),w.push(S),Ot.multiplyMatrices(z.projectionMatrix,z.matrixWorldInverse),z.isArrayCamera?Yt.setFromArrayCamera(z):et.setFromProjectionMatrix(Ot,$n,z.reversedDepth),on=this.localClippingEnabled,kt=te.init(this.clippingPlanes,on),M=ge.get(E,_.length),M.init(),_.push(M),this.info.render.frame++,ae.enabled===!0&&ae.isPresenting===!0){let Ae=A.xr.getDepthSensingMesh();Ae!==null&&kh(Ae,z,-1/0,A.sortObjects)}kh(E,z,0,A.sortObjects),M.finish(),O!==null&&O.updateLights(S.state.lightsArray),A.sortObjects===!0&&M.sort(Ie,st),Wn=ae.enabled===!1||ae.isPresenting===!1||ae.hasDepthSensing()===!1,Wn&&k.addToRenderList(M,E),this.info.autoReset===!0&&this.info.reset(),kt===!0&&te.beginShadows();let K=S.state.shadowsArray;if(fe.render(K,E,z),kt===!0&&te.endShadows(),(q&&R.hasRenderPass())===!1){let Ae=M.opaque,me=M.transmissive;if(S.setupLights(),z.isArrayCamera){let Me=z.cameras;if(me.length>0)for(let Ce=0,Ye=Me.length;Ce0&&s0(Ae,me,E,z),Wn&&k.render(E),r0(M,E,z)}H!==null&&F===0&&(We.updateMultisampleRenderTarget(H),We.updateRenderTargetMipmap(H)),q&&R.end(A),E.isScene===!0&&E.onAfterRender(A,E,z),he.resetDefaultState(),B=-1,X=null,w.pop(),w.length>0?(S=w[w.length-1],We.setTextureUnits(S.state.textureUnits),kt===!0&&te.setGlobalState(A.clippingPlanes,S.state.camera)):S=null,_.pop(),_.length>0?M=_[_.length-1]:M=null,O!==null&&O.renderEnd()};function kh(E,z,J,q){if(E.visible===!1)return;if(E.layers.test(z.layers)){if(E.isGroup)J=E.renderOrder;else if(E.isLOD)E.autoUpdate===!0&&E.update(z);else if(E.isLight)S.pushLight(E),E.castShadow&&S.pushShadow(E);else if(E.isSprite){let Ae=z.isArrayCamera?Yt:et;if(!E.frustumCulled||E.intersectsFrustum(Ae)){q&&en.setFromMatrixPosition(E.matrixWorld).applyMatrix4(Ot);let me=oe.update(E),Me=E.material;Me.visible&&M.push(E,me,Me,J,en.z,null,z)}}else if(E.isMesh||E.isLine||E.isPoints){let Ae=z.isArrayCamera?Yt:et;if(!E.frustumCulled||E.intersectsFrustum(Ae)){let me=oe.update(E),Me=E.material;if(q&&(E.boundingSphere!==void 0?(E.boundingSphere===null&&E.computeBoundingSphere(),en.copy(E.boundingSphere.center)):(me.boundingSphere===null&&me.computeBoundingSphere(),en.copy(me.boundingSphere.center)),en.applyMatrix4(E.matrixWorld).applyMatrix4(Ot)),Array.isArray(Me)){let Ce=me.groups;for(let Ye=0,ot=Ce.length;Ye0&&Pl(K,z,J),xe.length>0&&Pl(xe,z,J),Ae.length>0&&Pl(Ae,z,J),ye.buffers.depth.setTest(!0),ye.buffers.depth.setMask(!0),ye.buffers.color.setMask(!0),ye.setPolygonOffset(!1)}function s0(E,z,J,q){if((J.isScene===!0?J.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[q.id]===void 0){let Ee=Pt.has("EXT_color_buffer_half_float")||Pt.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[q.id]=new wn(1,1,{generateMipmaps:!0,type:Ee?ai:On,minFilter:Fn,samples:Math.max(4,It.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:tt.workingColorSpace})}let xe=S.state.transmissionRenderTarget[q.id],Ae=q.viewport||V;xe.setSize(Ae.z*A.transmissionResolutionScale,Ae.w*A.transmissionResolutionScale);let me=A.getRenderTarget(),Me=A.getActiveCubeFace(),Ce=A.getActiveMipmapLevel();A.setRenderTarget(xe),A.getClearColor(Y),Q=A.getClearAlpha(),Q<1&&A.setClearColor(16777215,.5),A.clear(),Wn&&k.render(J);let Ye=A.toneMapping;A.toneMapping=Ei;let ot=q.viewport;if(q.viewport!==void 0&&(q.viewport=void 0),S.setupLightsView(q),kt===!0&&te.setGlobalState(A.clippingPlanes,q),Pl(E,J,q),We.updateMultisampleRenderTarget(xe),We.updateRenderTargetMipmap(xe),Pt.has("WEBGL_multisampled_render_to_texture")===!1){let Ee=!1;for(let at=0,qt=z.length;at0),Ee=!!J.morphAttributes.position,at=!!J.morphAttributes.normal,qt=!!J.morphAttributes.color,Rt=Ei;q.toneMapped&&(H===null||H.isXRRenderTarget===!0)&&(Rt=A.toneMapping);let At=J.morphAttributes.position||J.morphAttributes.normal||J.morphAttributes.color,hn=At!==void 0?At.length:0,Re=ze.get(q),_n=S.state.lights;if(kt===!0&&(on===!0||E!==X)){let Nt=E===X&&q.id===B;te.setState(q,E,Nt)}let yt=!1,Kr=!1;q.version===Re.__version?Re.needsLights&&Re.lightsStateVersion!==_n.state.version||K.isBatchedMesh&&Re.batching===!1||!K.isBatchedMesh&&Re.batching===!0||K.isBatchedMesh&&Re.batchingColor===!0&&K._colorsTexture===null||K.isBatchedMesh&&Re.batchingColor===!1&&K._colorsTexture!==null||K.isInstancedMesh&&Re.instancing===!1||!K.isInstancedMesh&&Re.instancing===!0||K.isSkinnedMesh&&Re.skinning===!1||!K.isSkinnedMesh&&Re.skinning===!0||K.isInstancedMesh&&Re.instancingColor===!0&&K.instanceColor===null||K.isInstancedMesh&&Re.instancingColor===!1&&K.instanceColor!==null||K.isInstancedMesh&&Re.instancingMorph===!0&&K.morphTexture===null||K.isInstancedMesh&&Re.instancingMorph===!1&&K.morphTexture!==null||Re.envMap!==Ce||q.fog===!0&&Re.fog!==xe||Re.numClippingPlanes!==void 0&&(Re.numClippingPlanes!==te.numPlanes||Re.numIntersection!==te.numIntersection)||Re.vertexAlphas!==Ye||Re.vertexTangents!==ot||Re.morphTargets!==Ee||Re.morphNormals!==at||Re.morphColors!==qt||Re.morphTargetsCount!==hn||Re.numLightProbeGrids!==a0(S.state.lightProbeGridArray)?yt=!0:(Re.outputColorSpace!==me||Re.toneMapping!==Rt)&&(Kr=!0):(yt=!0,Re.__version=q.version);let fn=Re.currentProgram;(yt===!0||Kr===!0)&&(fn=Kr===!0?JM(q,z,K,me,Rt):$o(q,z,K),O&&q.isNodeMaterial&&O.onUpdateProgram(q,fn,Re));let Il=!1,yr=!1,Zr=!1,dt=fn.getUniforms(),an=Re.uniforms;if(ye.useProgram(fn.program)&&(Il=!0,yr=!0,Zr=!0),q.id!==B&&(B=q.id,yr=!0),Il||X!==E){ye.buffers.depth.getReversed()&&E.reversedDepth!==!0&&(E._reversedDepth=!0,E.updateProjectionMatrix()),dt.setValue(G,"projectionMatrix",E.projectionMatrix),dt.setValue(G,"viewMatrix",E.matrixWorldInverse);let nn=dt.map.cameraPosition;nn!==void 0&&nn.setValue(G,gi.setFromMatrixPosition(E.matrixWorld)),It.logarithmicDepthBuffer&&dt.setValue(G,"logDepthBufFC",2/(Math.log(E.far+1)/Math.LN2)),(q.isMeshPhongMaterial||q.isMeshToonMaterial||q.isMeshLambertMaterial||q.isMeshBasicMaterial||q.isMeshStandardMaterial||q.isShaderMaterial)&&dt.setValue(G,"isOrthographic",E.isOrthographicCamera===!0),X!==E&&(X=E,yr=!0,Zr=!0)}if(Re.needsLights&&(_n.state.sunShadowMap.length>0&&dt.setValue(G,"sunShadowMap",_n.state.sunShadowMap,We),_n.state.directionalShadowMap.length>0&&dt.setValue(G,"directionalShadowMap",_n.state.directionalShadowMap,We),_n.state.spotShadowMap.length>0&&dt.setValue(G,"spotShadowMap",_n.state.spotShadowMap,We),_n.state.pointShadowMap.length>0&&dt.setValue(G,"pointShadowMap",_n.state.pointShadowMap,We)),K.isSkinnedMesh){dt.setOptional(G,K,"bindMatrix"),dt.setOptional(G,K,"bindMatrixInverse");let Nt=K.skeleton;Nt&&(Nt.boneTexture===null&&Nt.computeBoneTexture(),dt.setValue(G,"boneTexture",Nt.boneTexture,We))}K.isBatchedMesh&&(dt.setOptional(G,K,"batchingTexture"),dt.setValue(G,"batchingTexture",K._matricesTexture,We),dt.setOptional(G,K,"batchingIdTexture"),dt.setValue(G,"batchingIdTexture",K._indirectTexture,We),dt.setOptional(G,K,"batchingColorTexture"),K._colorsTexture!==null&&dt.setValue(G,"batchingColorTexture",K._colorsTexture,We));let ti=J.morphAttributes;if((ti.position!==void 0||ti.normal!==void 0||ti.color!==void 0)&&ne.update(K,J,fn),(yr||Re.receiveShadow!==K.receiveShadow)&&(Re.receiveShadow=K.receiveShadow,dt.setValue(G,"receiveShadow",K.receiveShadow)),(q.isMeshStandardMaterial||q.isMeshLambertMaterial||q.isMeshPhongMaterial)&&q.envMap===null&&z.environment!==null&&(an.envMapIntensity.value=z.environmentIntensity),an.dfgLUT!==void 0&&(an.dfgLUT.value=xE()),yr){if(dt.setValue(G,"toneMappingExposure",A.toneMappingExposure),Re.needsLights&&QM(an,Zr),xe&&q.fog===!0&&ue.refreshFogUniforms(an,xe),ue.refreshMaterialUniforms(an,q,le,Se,S.state.transmissionRenderTarget[E.id]),Re.needsLights&&Re.numLightProbeGrids>0){let Nt=y,nn=0;for(let ki of S.state.lightProbeGridArray)ki.texture!==null&&(Nt.textures[nn]=ki.texture,Nt.min[nn]=ki.boundingBox.min,Nt.max[nn]=ki.boundingBox.max,Nt.resolution[nn]=ki.resolution,nn++);for(let ki in Nt)Nt[ki].length=nn;an.probesSH.value=Nt.textures,an.probesMin.value=Nt.min,an.probesMax.value=Nt.max,an.probesResolution.value=Nt.resolution}So.upload(G,l0(Re),an,We)}if(q.isShaderMaterial&&q.uniformsNeedUpdate===!0&&(So.upload(G,l0(Re),an,We),q.uniformsNeedUpdate=!1),q.isSpriteMaterial&&dt.setValue(G,"center",K.center),dt.setValue(G,"modelViewMatrix",K.modelViewMatrix),dt.setValue(G,"normalMatrix",K.normalMatrix),dt.setValue(G,"modelMatrix",K.matrixWorld),q.uniformsGroups!==void 0){let Nt=q.uniformsGroups;for(let nn=0,ki=Nt.length;nn0&&We.useMultisampledRTT(E)===!1?q=ze.get(E).__webglMultisampledFramebuffer:Array.isArray(Ce)?q=Ce[J]:q=Ce,V.copy(E.viewport),re.copy(E.scissor),be=E.scissorTest}else V.copy(Te).multiplyScalar(le).floor(),re.copy(ht).multiplyScalar(le).floor(),be=bt;if(J!==0&&(q=D),ye.bindFramebuffer(G.FRAMEBUFFER,q)&&ye.drawBuffers(E,q),ye.viewport(V),ye.scissor(re),ye.setScissorTest(be),K){let me=ze.get(E.texture);G.framebufferTexture2D(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_CUBE_MAP_POSITIVE_X+z,me.__webglTexture,J)}else if(xe){let me=z;for(let Me=0;Me1&&G.readBuffer(G.COLOR_ATTACHMENT0+me);let Ee=u0(Ce);if(Ee.__formatReadable===!1){Ge("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(Ee.__typeReadable===!1){Ge("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}z>=0&&z<=E.width-q&&J>=0&&J<=E.height-K&&G.readPixels(z,J,q,K,ce.convert(Ye),ce.convert(ot),xe)}finally{let Ce=H!==null?ze.get(H).__webglFramebuffer:null;ye.bindFramebuffer(G.FRAMEBUFFER,Ce)}}},this.readRenderTargetPixelsAsync=async function(E,z,J,q,K,xe,Ae,me=0){if(!(E&&E.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Me=ze.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Ae!==void 0&&(Me=Me[Ae],Array.isArray(Me)&&(Me=Me[0])),Me)if(z>=0&&z<=E.width-q&&J>=0&&J<=E.height-K){ye.bindFramebuffer(G.FRAMEBUFFER,Me);let Ce=E.textures[me],Ye=Ce.format,ot=Ce.type;E.textures.length>1&&G.readBuffer(G.COLOR_ATTACHMENT0+me);let Ee=u0(Ce);if(Ee.__formatReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(Ee.__typeReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let at=G.createBuffer();G.bindBuffer(G.PIXEL_PACK_BUFFER,at),G.bufferData(G.PIXEL_PACK_BUFFER,xe.byteLength,G.STREAM_READ),G.readPixels(z,J,q,K,ce.convert(Ye),ce.convert(ot),0),G.bindBuffer(G.PIXEL_PACK_BUFFER,null);let qt=H!==null?ze.get(H).__webglFramebuffer:null;ye.bindFramebuffer(G.FRAMEBUFFER,qt);let Rt=G.fenceSync(G.SYNC_GPU_COMMANDS_COMPLETE,0);return G.flush(),await fx(G,Rt,4),G.bindBuffer(G.PIXEL_PACK_BUFFER,at),G.getBufferSubData(G.PIXEL_PACK_BUFFER,0,xe),G.bindBuffer(G.PIXEL_PACK_BUFFER,null),G.deleteBuffer(at),G.deleteSync(Rt),xe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(E,z=null,J=0){let q=Math.pow(2,-J),K=Math.floor(E.image.width*q),xe=Math.floor(E.image.height*q),Ae=z!==null?z.x:0,me=z!==null?z.y:0;We.setTexture2D(E,0),G.copyTexSubImage2D(G.TEXTURE_2D,J,0,0,Ae,me,K,xe),ye.unbindTexture()},this.copyTextureToTexture=function(E,z,J=null,q=null,K=0,xe=0){let Ae,me,Me,Ce,Ye,ot,Ee,at,qt,Rt=E.isCompressedTexture?E.mipmaps[xe]:E.image;if(J!==null)Ae=J.max.x-J.min.x,me=J.max.y-J.min.y,Me=J.isBox3?J.max.z-J.min.z:1,Ce=J.min.x,Ye=J.min.y,ot=J.isBox3?J.min.z:0;else{let dt=Math.pow(2,-K);Ae=Math.floor(Rt.width*dt),me=Math.floor(Rt.height*dt),E.isDataArrayTexture?Me=Rt.depth:E.isData3DTexture?Me=Math.floor(Rt.depth*dt):Me=1,Ce=0,Ye=0,ot=0}q!==null?(Ee=q.x,at=q.y,qt=q.z):(Ee=0,at=0,qt=0);let At=ce.convert(z.format),hn=ce.convert(z.type),Re;z.isData3DTexture?(We.setTexture3D(z,0),Re=G.TEXTURE_3D):z.isDataArrayTexture||z.isCompressedArrayTexture?(We.setTexture2DArray(z,0),Re=G.TEXTURE_2D_ARRAY):(We.setTexture2D(z,0),Re=G.TEXTURE_2D),ye.activeTexture(G.TEXTURE0),ye.pixelStorei(G.UNPACK_FLIP_Y_WEBGL,z.flipY),ye.pixelStorei(G.UNPACK_PREMULTIPLY_ALPHA_WEBGL,z.premultiplyAlpha),ye.pixelStorei(G.UNPACK_ALIGNMENT,z.unpackAlignment);let _n=ye.getParameter(G.UNPACK_ROW_LENGTH),yt=ye.getParameter(G.UNPACK_IMAGE_HEIGHT),Kr=ye.getParameter(G.UNPACK_SKIP_PIXELS),fn=ye.getParameter(G.UNPACK_SKIP_ROWS),Il=ye.getParameter(G.UNPACK_SKIP_IMAGES);ye.pixelStorei(G.UNPACK_ROW_LENGTH,Rt.width),ye.pixelStorei(G.UNPACK_IMAGE_HEIGHT,Rt.height),ye.pixelStorei(G.UNPACK_SKIP_PIXELS,Ce),ye.pixelStorei(G.UNPACK_SKIP_ROWS,Ye),ye.pixelStorei(G.UNPACK_SKIP_IMAGES,ot);let yr=E.isDataArrayTexture||E.isData3DTexture,Zr=z.isDataArrayTexture||z.isData3DTexture;if(E.isDepthTexture){let dt=ze.get(E),an=ze.get(z),ti=ze.get(dt.__renderTarget),Nt=ze.get(an.__renderTarget);ye.bindFramebuffer(G.READ_FRAMEBUFFER,ti.__webglFramebuffer),ye.bindFramebuffer(G.DRAW_FRAMEBUFFER,Nt.__webglFramebuffer);for(let nn=0;nn.5+.5*Math.min(1,Math.max(0,i/1.6));function Ed(i,e){let t=Math.hypot(i,e);return .8+.28*((e/t*Qa[0]-i/t*Qa[1]+1)/2)}var Xe=-1,tl=16,cr=32,Rd=48,Iu=64,Cd=128,zr=(i,e)=>new ke(i,e),lt=class{p=[];c=[];f=[];uv;tile;constructor(e=!1,t=!1){this.uv=e?[]:null,this.tile=t?[]:null}tri(e,t,n,r,s=r,o=r,a,l=Xe,c=[0,1]){this.p.push(...e,...t,...n);for(let u of[r,s,o])this.c.push(u.r,u.g,u.b);this.f.push(l,l,l),this.uv?.push(...a??[.5,.5,.5,.5,.5,.5]),this.tile?.push(...c,...c,...c)}get count(){return this.p.length/9}geometry(){let e=new Fe;return e.setAttribute("position",zr(this.p,3)),e.setAttribute("color",zr(this.c,3)),e.setAttribute("fold",zr(this.f,1)),this.uv&&e.setAttribute("uv",zr(this.uv,2)),this.tile&&e.setAttribute("tile",zr(this.tile,2)),e.computeBoundingSphere(),e}},Wt=class{p=[];c=[];f=[];seg(e,t,n=Ii,r=Xe){this.p.push(...e,...t),this.c.push(n.r,n.g,n.b,n.r,n.g,n.b),this.f.push(r,r)}segSplit(e,t,n,r,s){let[o,a]=e[1]<=t[1]?[e,t]:[t,e];if(a[1]<=r+1e-6||s<0)return this.seg(o,a,n,Xe);if(o[1]>=r-1e-6)return this.seg(o,a,n,s);let l=(r-o[1])/(a[1]-o[1]),c=[o[0]+(a[0]-o[0])*l,r,o[2]+(a[2]-o[2])*l];this.seg(o,c,n,Xe),this.seg(c,a,n,s)}geometry(){let e=new Fe;return e.setAttribute("position",zr(this.p,3)),e.setAttribute("color",zr(this.c,3)),e.setAttribute("fold",zr(this.f,1)),e}};var Pd=(i,e,t)=>i.map((n,r)=>n+(e[r]-n)*t);function tb(i,e,t){let n=(t-i.p[1])/(e.p[1]-i.p[1]);return{p:Pd(i.p,e.p,n),c:Pd(i.c,e.c,n),uv:i.uv&&e.uv?Pd(i.uv,e.uv,n):null,tile:i.tile}}function bE(i,e){return{p:i.p.slice(e*3,e*3+3),c:i.c.slice(e*3,e*3+3),uv:i.uv?i.uv.slice(e*2,e*2+2):null,tile:i.tile?i.tile.slice(e*2,e*2+2):null}}function yE(i,e,t,n){t.forEach((r,s)=>{let o=e*3+s;r.p.forEach((a,l)=>i.p[o*3+l]=a),r.c.forEach((a,l)=>i.c[o*3+l]=a),i.uv&&r.uv&&r.uv.forEach((a,l)=>i.uv[o*2+l]=a),i.tile&&r.tile&&r.tile.forEach((a,l)=>i.tile[o*2+l]=a),i.f[o]=n})}function nb(i,e,t){for(let n of e)i.p.push(...n.p),i.c.push(...n.c),i.f.push(t),i.uv?.push(...n.uv??[.5,.5]),i.tile?.push(...n.tile??[0,1])}function Id(i,e,t,n){let r=i.count;for(let s=e;sbE(i,s*3+v)),a=o.map(v=>v.p[1]>t+1e-6),l=o.map(v=>v.p[1]=t-1e-6){i.f[s*2]=n,i.f[s*2+1]=n;continue}let u=(t-l[1])/(c[1]-l[1]),h=[l[0]+(c[0]-l[0])*u,t,l[2]+(c[2]-l[2])*u],f=i.c.slice(s*6,s*6+3);i.p.splice(s*6,6,...l,...h),i.p.push(...h,...c),i.c.push(...f,...f),i.f.push(n,n)}}var _E=i=>i.reduce((e,t,n)=>e+t[0]*i[(n+1)%i.length][1]-i[(n+1)%i.length][0]*t[1],0),ib=([i,e])=>new De(i,e);function Vr(i,e=[]){return Ea.triangulateShape(i.map(ib),e.map(t=>t.map(ib)))}var Ao=(i,e)=>[i[0]-e[0],i[1]-e[1],i[2]-e[2]],rb=(i,e)=>[i[1]*e[2]-i[2]*e[1],i[2]*e[0]-i[0]*e[2],i[0]*e[1]-i[1]*e[0]],sb=(i,e)=>i[0]*e[0]+i[1]*e[1]+i[2]*e[2],ob=i=>{let e=Math.hypot(i[0],i[1],i[2])||1;return[i[0]/e,i[1]/e,i[2]/e]};function Fd(i,e,t,n,r,s,o){let a=new W(o);for(let f=0;f<4;f++){let[d,p]=[e[f],e[(f+1)%4]],[x,g]=[t[f],t[(f+1)%4]],[m,b]=[p[0]-d[0],p[1]-d[1]],v=Math.hypot(m,b);if(v<1e-6)continue;let y=(x[0]+g[0]-d[0]-p[0])/2*(-b/v)+(x[1]+g[1]-d[1]-p[1])/2*(m/v),M=Math.max(0,Math.min(1,y/Math.max(1e-6,Math.hypot(y,r-n)))),S=Ed(m,b),_=Ue(s,el(n)*S).lerp(a,M),w=Ue(s,el(r)*S).lerp(a,M);i.tri([d[0],n,d[1]],[x[0],r,x[1]],[g[0],r,g[1]],_,w,w),i.tri([d[0],n,d[1]],[g[0],r,g[1]],[p[0],n,p[1]],_,w,_)}let[l,c,u,h]=t;Math.hypot(u[0]-l[0],u[1]-l[1])>1e-4&&(i.tri([l[0],r,l[1]],[u[0],r,u[1]],[c[0],r,c[1]],a),i.tri([l[0],r,l[1]],[h[0],r,h[1]],[u[0],r,u[1]],a))}function Od(i,e,t,n){let r=e.length;if(r<2)return;let s=e[0].length,o=new W(n),a=e.map(h=>[0,1,2].map(f=>h.reduce((d,p)=>d+p[f],0)/s)),l=e.map((h,f)=>h.map((d,p)=>{let x=Ao(e[Math.min(r-1,f+1)][p],e[Math.max(0,f-1)][p]),g=Ao(h[(p+1)%s],h[(p+s-1)%s]),m=ob(rb(x,g));return sb(m,Ao(d,a[f]))<0?m.map(b=>-b):m})),c=(h,f)=>{let d=(f[0]*Qa[0]+f[2]*Qa[1]+1)/2;return Ue(t,el(h[1])*(.8+.28*d)).lerp(o,Math.max(0,f[1])*.9)},u=(h,f,d,p,x,g,m)=>{sb(rb(Ao(f,h),Ao(d,h)),p)>=0?i.tri(h,f,d,x,g,m):i.tri(h,d,f,x,m,g)};for(let h=0;h+1c(M,x[S])),y=[0,1,2].map(M=>x.reduce((S,_)=>S+_[M],0));u(p[0],p[1],p[2],y,g,m,b),u(p[0],p[2],p[3],y,g,b,v)}for(let[h,f]of[[0,-1],[r-1,1]]){let d=e[h],p=Ao(e[h===0?1:r-2][0],d[0]),x=ob(p.map(m=>m*-f)),g=c(a[h],x);for(let m=0;m{let x=p/c*Math.PI*2;return{y:s+Math.cos(x)*o,across:r+Math.sin(x)*o}}),f=(d,p)=>{let{y:x,across:g}=h[p%c],[m,b]=e(d,g);return[m,x,b]};for(let d=0;dn:x=>Math.max(t+.002,n(x[0],x[1])),l=o.aoFrom??t,c=o.fold??Xe,u=x=>el(x-l),h=(o.holes??[]).map(x=>_E(x)>0?[...x].reverse():x),f=h.length?[...e,...h.flat()]:e,d=o.topFace!==!1,p=!d&&!o.bottom?[]:Vr(e,h);if(d){let x=new W(s);for(let[g,m,b]of p){let[v,y,M]=[f[g],f[m],f[b]];i.tri([v[0],a(v),v[1]],[M[0],a(M),M[1]],[y[0],a(y),y[1]],x,x,x,void 0,o.topFold??c)}}if(o.bottom){let x=Ue(r,.55);for(let[g,m,b]of p){let[v,y,M]=[f[g],f[m],f[b]];i.tri([v[0],t,v[1]],[y[0],t,y[1]],[M[0],t,M[1]],x,x,x,void 0,c)}}for(let x of[e,...h])x.forEach((g,m)=>{let b=x[(m+1)%x.length];if(Math.hypot(b[0]-g[0],b[1]-g[1])<1e-6||o.skipSide?.(g,b))return;let v=Ed(b[0]-g[0],b[1]-g[1]),[y,M]=[a(g),a(b)],S=o.sideColor?o.sideColor(g,b):r,_=Ue(S,u(t)*v),w=Ue(S,u(y)*v),R=Ue(S,u(M)*v);i.tri([g[0],t,g[1]],[g[0],y,g[1]],[b[0],M,b[1]],_,w,R,void 0,c),i.tri([g[0],t,g[1]],[b[0],M,b[1]],[b[0],t,b[1]],_,R,_,void 0,c)})}var _s=i=>{let e=Math.hypot(i[0],i[1])||1;return[i[0]/e,i[1]/e]};function Gr(i){return i.reduce((t,n,r)=>t+n[0]*i[(r+1)%i.length][1]-i[(r+1)%i.length][0]*n[1],0)>=0?i:[...i].reverse()}function ab(i,e){let t=[];return i.forEach((n,r)=>{let s=i[(r+1)%i.length],[o,a]=[e(n),e(s)];if(o>=0&&t.push(n),o>=0!=a>=0){let l=o/(o-a);t.push([n[0]+(s[0]-n[0])*l,n[1]+(s[1]-n[1])*l])}}),t}function Ud(i,e,t,n,r){let s=a=>(a[0]-e[0])*t[0]+(a[1]-e[1])*t[1],o=i;return Number.isFinite(n)&&(o=ab(o,a=>s(a)-n)),Number.isFinite(r)&&(o=ab(o,a=>r-s(a))),o}var lb=i=>Math.round(i*1e3),nl=i=>`${lb(i[0])},${lb(i[1])}`,Dd=(i,e)=>{let[t,n]=[nl(i),nl(e)];return t{let s=i[(r+1)%i.length],[o,a]=[s[0]-n[0],s[1]-n[1]],l=o*o+a*a;if(l<1e-8)return;let c=e.map(h=>({t:((h[0]-n[0])*o+(h[1]-n[1])*a)/l,off:Math.abs((h[0]-n[0])*a-(h[1]-n[1])*o)/Math.sqrt(l)})).filter(({t:h,off:f})=>h>1e-6&&h<1-1e-6&&f<1e-4).map(({t:h})=>h).sort((h,f)=>h-f),u=n;for(let h of c){let f=[n[0]+o*h,n[1]+a*h];nl(f)!==nl(u)&&t.push([u,f]),u=f}t.push([u,s])}),t}function Bd(i,e){let t=i.map(l=>({wall:l,edges:vE(l.footprint,e)})),n=new Map;for(let{edges:l}of t)for(let[c,u]of l)n.set(Dd(c,u),(n.get(Dd(c,u))??0)+1);let r=[],s=new Map,o=(l,c,u)=>{let h=nl(l);s.has(h)||s.set(h,{p:l,wall:c,d:[]}),s.get(h).d.push(u)};for(let{wall:l,edges:c}of t)for(let[u,h]of c){let f=Math.hypot(h[0]-u[0],h[1]-u[1]);if(n.get(Dd(u,h))!==1||f<1e-4)continue;r.push({a:u,b:h,wall:l});let d=[(h[0]-u[0])/f,(h[1]-u[1])/f];o(u,l,d),o(h,l,d)}let a=[...s.values()].filter(({d:l})=>l.some(c=>l.some(u=>Math.abs(c[0]*u[1]-c[1]*u[0])>.05))).map(({p:l,wall:c})=>({p:l,wall:c}));return{edges:r,corners:a}}function Eo(i,e){if(e.length===0)return[[i.a,i.b]];let t=_s([i.wall.b[0]-i.wall.a[0],i.wall.b[1]-i.wall.a[1]]),n=_s([i.b[0]-i.a[0],i.b[1]-i.a[1]]);if(Math.abs(t[0]*n[0]+t[1]*n[1])<.99)return[[i.a,i.b]];let r=c=>(c[0]-i.wall.a[0])*t[0]+(c[1]-i.wall.a[1])*t[1],[s,o]=[r(i.a),r(i.b)],a=[[Math.min(s,o),Math.max(s,o)]];for(let c of e)a=a.flatMap(([u,h])=>{if(c.s1<=u||c.s0>=h)return[[u,h]];let f=[];return c.s0>u&&f.push([u,c.s0]),c.s1{let u=(c-s)/(o-s||1);return[i.a[0]+(i.b[0]-i.a[0])*u,i.a[1]+(i.b[1]-i.a[1])*u]};return a.filter(([c,u])=>u-c>1e-4).map(([c,u])=>s<=o?[l(c),l(u)]:[l(u),l(c)])}var cb=["body","wood","fabric","white","metal","dark"];var Pe={body:1516088,bodyTop:1911623,fabric:1713732,fabricTop:2241114,cushion:2373217,wood:1647420,woodTop:2108747,white:1911110,whiteTop:2504542,metal:2767456,dark:725279,glass:1849938,plant:1191982,plantTop:1721664,pot:1910336,accent:2854835},mt=(i,e=i)=>({side:i,top:e}),Z={body:mt(Pe.body,Pe.bodyTop),fabric:mt(Pe.fabric,Pe.fabricTop),cushion:mt(Pe.cushion),cushionSoft:mt(Pe.cushion,Pe.fabricTop),wood:mt(Pe.wood,Pe.woodTop),white:mt(Pe.white,Pe.whiteTop),worktop:mt(Pe.whiteTop),metal:mt(Pe.metal),dark:mt(Pe.dark),darkBody:mt(Pe.dark,Pe.body),glass:mt(Pe.glass),accent:mt(Pe.accent),pot:mt(Pe.pot),plant:mt(Pe.plant,Pe.plantTop),bedding:mt(Pe.white,Pe.whiteTop),pillow:mt(Pe.whiteTop)};var pe=Ue(5995775,.3),Je=Ue(5995775,.17),qe=Ue(3662079,.45);var kd={...Pe},ub=Object.fromEntries(Object.entries(Z).map(([i,e])=>[i,{...e}])),hb="",ME=i=>typeof i=="string"&&/^#[0-9a-f]{6}$/i.test(i)?Number.parseInt(i.slice(1),16):null;function fb(i){let e=Object.fromEntries(cb.map(s=>[s,ME(i?.[s])]).filter(([,s])=>s!==null)),t=JSON.stringify(e);if(t===hb)return!1;hb=t,Object.assign(Pe,kd);for(let[s,o]of Object.entries(ub))Object.assign(Z[s],o);let n=s=>Ue(s,1.25).getHex(),r=(s,o,a,l)=>{let c=e[s];if(c===void 0)return;for(let h of o)Pe[h]=c;for(let h of a)Pe[h]=n(c);let u=new Map([...o.map(h=>[kd[h],c]),...a.map(h=>[kd[h],n(c)])]);for(let h of l){let f=ub[h];Z[h].side=u.get(f.side)??Z[h].side,Z[h].top=u.get(f.top)??Z[h].top}};return r("body",["body"],["bodyTop"],["body","darkBody"]),r("wood",["wood"],["woodTop"],["wood"]),r("fabric",["fabric","cushion"],["fabricTop"],["fabric","cushion","cushionSoft"]),r("white",["white"],["whiteTop"],["white","worktop","bedding","pillow"]),r("metal",["metal"],[],["metal"]),r("dark",["dark"],[],["dark","darkBody"]),!0}function db(i){let e=i(0,0),t=i(1,0),n=i(0,1);return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])<0}function vs(i,e){let t=(n,r,s)=>{if(n)for(let o=0;othis.plan(e+(o-e)*r-(a-t)*s,t+(o-e)*s+(a-t)*r))}seg(e,t,n,r,s,o,a=pe){this.edge(this.plan(e,n),this.plan(r,o),t,s,a)}edge(e,t,n,r,s){this.lines.seg([e[0],n,e[1]],[t[0],r,t[1]],s,Xe)}block({x:[e,t],y:[n,r],z:[s,o]},a,l=null){if(t-e<1e-4||o-s<1e-4||r-n<1e-4)return;let c=[this.plan(e,s),this.plan(e,o),this.plan(t,o),this.plan(t,s)];Tt(this.buf,Gr(c),n,r,a.side,a.top,{aoFrom:0,bottom:n>.05}),l&&c.forEach((u,h)=>{this.edge(u,c[(h+1)%4],r,r,l),this.edge(u,u,n,r,l)})}prism(e,t,n,r,s=null){if(e.length<3||n-t<1e-4)return;let o=e.map(([a,l])=>this.plan(a,l));Tt(this.buf,Gr(o),t,n,r.side,r.top,{aoFrom:Math.min(0,t),bottom:!0}),s&&o.forEach((a,l)=>this.edge(a,o[(l+1)%o.length],n,n,s))}loft(e,t,n,r,s,o=null){if(r-n<1e-4)return;let a=u=>[this.plan(u[0],u[2]),this.plan(u[0],u[3]),this.plan(u[1],u[3]),this.plan(u[1],u[2])],l=a(e),c=a(t);if(l!==Gr(l)&&(l.reverse(),c.reverse()),Fd(this.buf,l,c,n,r,s.side,s.top),o)for(let u=0;u<4;u++)this.edge(c[u],c[(u+1)%4],r,r,o),this.edge(l[u],c[u],n,r,o)}sweep(e,t,n=16,r=2.6,s=null){if(e.length<2)return;let o=e.map(a=>{let[l,c]=[Math.max(.004,(a.y1-a.y0)/2),Math.max(.004,a.hw)],u=(a.y0+a.y1)/2;return Array.from({length:n},(h,f)=>{let d=f/n*Math.PI*2,[p,x]=[Math.cos(d),Math.sin(d)],[g,m]=this.plan(a.x+c*Math.sign(p)*Math.abs(p)**(2/r),a.z);return[g,u+l*Math.sign(x)*Math.abs(x)**(2/r),m]})});if(Od(this.buf,o,t.side,t.top),s){let a=Math.round(n/4);for(let l=0;l+1.005&&this.block({x:[s,o],y:[a+h,l-h],z:[c,u]},f,r),this.loft([s,o,c,u],[s+h,o-h,c+h,u-h],l-h,l,t)}lyingCylinder(e,t,n,r,s,o,a,l,c=12,u=null){let h=Math.min(a,s-r)/2;if(h<1e-4||o<1e-4)return;let f=(r+s)/2,[d,p]=e==="x"?[t,n]:[n,t],x=(m,b)=>e==="x"?this.plan(m,b):this.plan(b,m),g=this.buf.p.length;if(Nd(this.buf,x,d-o/2,d+o/2,p,f,h,l.side,l.top,c),this.mirrored&&vs(this.buf,g),!!u)for(let m of[d-o/2,d+o/2])for(let b=0;bthis.plan(e+Math.cos(h/a*Math.PI*2)*n,t+Math.sin(h/a*Math.PI*2)*n));Tt(this.buf,Gr(c),r,s,o.side,o.top,{aoFrom:0,bottom:r>.05}),l&&c.forEach((u,h)=>this.edge(u,c[(h+1)%a],s,s,l))}ring(e,t,n,r,s=20,o=pe){for(let a=0;a[e(-t/2-p,-n/2-p),e(t/2+p,-n/2-p),e(t/2+p,n/2+p),e(-t/2-p,n/2+p)],[u,h]=[c(0),c(s)],f=p=>[p[0],l,p[1]],d=i.p.length;i.tri(f(u[0]),f(u[1]),f(u[2]),o),i.tri(f(u[0]),f(u[2]),f(u[3]),o);for(let p=0;p<4;p++){let x=(p+1)%4;i.tri(f(u[p]),f(h[p]),f(h[x]),o,a,a),i.tri(f(u[p]),f(h[x]),f(u[x]),o,a,o)}db(e)&&vs(i,d)}function zd(i,e){if(!i)return null;if(i.startsWith("#"))return Number.parseInt(i.slice(1),16);let t=Pe;return(e?t[`${i}Top`]:void 0)??t[i]??null}function Ms(i,e,t,n,r,s,o,a=null,l=null,c=null){let u=e.colors?.length?(e.colors.find(f=>f.id===l)??e.colors[0]).hex:null,h=jo(e,t,n,r);for(let f of c===null?h:L0(h,c)){if(c===null&&f.move||a&&!a(f))continue;let d=a?{...f,glow:!0,w:f.w+.006/t,d:f.d+.006/n,y:Math.max(0,f.y-.002/r),h:f.h+.004/r}:f,p=d.glow&&o!==null,x=!!(d.paint&&u),g=x?u:d.color,m=p?o:zd(g,!1)??Pe.body,b=p?o:zd(x?void 0:d.top,!1)??zd(g,!0)??Ue(m,1.25).getHex(),v=mt(m,b),[y,M]=[s+d.y*r,s+Math.min(r,(d.y+d.h)*r)],S=d.edges==="glow"?Ii:d.edges==="faint"?Je:d.edges?pe:null,_=d.rot?i.turned(d.x*t,d.z*n,d.rot):i,[w,R]=[d.x*t,d.z*n];if(d.shape==="cyl"&&(d.axis==="x"||d.axis==="z"))_.lyingCylinder(d.axis,w,R,y,M,d.axis==="x"?d.w*t:d.d*n,d.axis==="x"?d.d*n:d.w*t,v,14,S);else if(d.shape==="cyl")_.cylinder(w,R,Math.min(d.w*t,d.d*n)/2,y,M,v,14,S);else if(d.shape==="loft"){let[A,C,O,D]=[d.tx??d.x,d.tz??d.z,d.tw??d.w,d.td??d.d];_.loft([(d.x-d.w/2)*t,(d.x+d.w/2)*t,(d.z-d.d/2)*n,(d.z+d.d/2)*n],[(A-O/2)*t,(A+O/2)*t,(C-D/2)*n,(C+D/2)*n],y,M,v,S)}else if(d.shape==="sweep"){let A=(d.stations??[]).map(([C,O,D,P])=>({x:w,z:C*n,y0:s+O*r,y1:s+D*r,hw:P*t/2}));_.sweep(A,v,d.n??16,d.exp??2.6,S)}else _.block({x:[(d.x-d.w/2)*t,(d.x+d.w/2)*t],y:[y,M],z:[(d.z-d.d/2)*n,(d.z+d.d/2)*n]},v,S)}}function Ss(i){let[e,t]=[Math.cos(i.rotation*pt),Math.sin(i.rotation*pt)],n=i.mirror?-1:1;return(r,s)=>[i.x+n*r*e-s*t,i.z+n*r*t+s*e]}var Vd=i=>[Math.max(.05,i.w),Math.max(.05,i.d),Math.max(.005,i.h)];function il(i,e,t,n,r,s=o=>!!o.glow){Ms(new Li(i,new Wt,Ss(t)),e,...Vd(t),n,r,s)}function Gd(i,e,t,n,r){let s=i.p.length;Ms(new Li(i,new Wt,Ss(t)),e,...Vd(t),n,null,null,t.variant??null,r),t.mirror&&vs(i,s)}function rl(i,e,t,n,r){Ms(new Li(i,new Wt,Ss(t)),e,...Vd(t),n,r)}function mb(i){let e=2166136261;for(let t=0;t(e=Math.imul(e^e>>>15,2246822507),e=Math.imul(e^e>>>13,3266489909),e^=e>>>16,(e>>>0)/4294967296)}var SE=(i,e,t)=>{let[n,r]=[t[0]-e[0],t[1]-e[1]],s=n*n+r*r||1e-9,o=Math.max(0,Math.min(1,((i[0]-e[0])*n+(i[1]-e[1])*r)/s));return Math.hypot(i[0]-e[0]-n*o,i[1]-e[1]-r*o)};function wE(i,e,t=.25){if(!Ve(e,i.points))return!1;let n=i.points;for(let r=0;rVe(e,r))}function TE(i,e,t){let n=i.obstacles.filter(s=>!Ve(e,s)),r=Math.max(1,Math.ceil(Math.hypot(t[0]-e[0],t[1]-e[1])/.1));for(let s=1;s<=r;s++){let o=[e[0]+(t[0]-e[0])*s/r,e[1]+(t[1]-e[1])*s/r];if(n.some(a=>Ve(o,a)))return!1}return!0}function AE(i,e,t){let n=i.points.map(c=>c[0]),r=i.points.map(c=>c[1]),[s,o,a,l]=[Math.min(...n),Math.max(...n),Math.min(...r),Math.max(...r)];for(let c=0;c<24;c++){let u=[s+(o-s)*t(),a+(l-a)*t()];if(Math.hypot(u[0]-e[0],u[1]-e[1])>.6&&wE(i,u)&&TE(i,e,u))return u}return null}function EE(i,e,t,n){if(!i.target){if(i.rest-=t,i.rest>0)return!1;if(i.target=AE(e,i.pos,n),!i.target)return i.rest=2,!1}let[r,s]=[i.target[0]-i.pos[0],i.target[1]-i.pos[1]],o=Math.hypot(r,s),l=Math.atan2(r,s)-i.heading;for(;l>Math.PI;)l-=2*Math.PI;for(;l<-Math.PI;)l+=2*Math.PI;i.heading+=Math.max(-4*t,Math.min(4*t,l));let c=e.speed*t*(Math.abs(l)>1.2?.3:1);return o<=c?(i.pos=[i.target[0],i.target[1]],i.target=null,i.rest=2+n()*6,!0):(i.pos=[i.pos[0]+r/o*c,i.pos[1]+s/o*c],!0)}function gb(i,e,t,n){let r=Math.min(.2,Math.max(0,t));return i.target||(i.rest-=Math.max(0,t)-r),EE(i,e,r,n)}function xb(){let e=navigator.deviceMemory??8,t=navigator.hardwareConcurrency||8;return e<=3||t<=4||/Silk|KF[A-Z]{2,4}\b/.test(navigator.userAgent)}var Lu=class{times=[];settle=30;ratio;lastDown=-1/0;slowAtFloor=0;max;min;constructor(e,t=1){this.max=e,this.min=t,this.ratio=e}get pixelRatio(){return this.ratio}frame(e,t){if(this.settle>0)return this.settle--,null;if(e<=0||e>=100||(this.times.push(e),this.times.length<45))return null;let n=[...this.times].sort((s,o)=>s-o);this.times=[];let r=1e3/n[Math.floor(n.length/2)];return r<26&&this.ratio>this.min+1e-6?(this.ratio=Math.max(this.min,Math.round((this.ratio-.25)*100)/100),this.lastDown=t,this.settle=30,{ratio:this.ratio}):r<16&&this.ratio<=this.min+1e-6?++this.slowAtFloor>=2?{low:!0}:null:(this.slowAtFloor=0,r>55&&this.ratio3e4?(this.ratio=Math.min(this.max,Math.round((this.ratio+.25)*100)/100),this.settle=30,{ratio:this.ratio}):null)}};function bb(i){let e=i.length/3,t=new Float32Array(e);for(let n=0;n0&&(t[n]=r)}return t}function yb(i,e,t,n){for(let r=t.start*3;rMath.tan(Math.min(80,Math.max(0,i))*Fu);function ws(i){return{x0:Math.min(i.x0,i.x1),x1:Math.max(i.x0,i.x1),z0:Math.min(i.z0,i.z1),z1:Math.max(i.z0,i.z1)}}function _b(i){if(!i.rotation)return null;let e=i.rotation*Fu;return{cx:(i.x0+i.x1)/2,cz:(i.z0+i.z1)/2,c:Math.cos(e),sn:Math.sin(e)}}function vb(i,e){let t=_b(i);if(!t)return e;let[n,r]=[e[0]-t.cx,e[1]-t.cz];return[t.cx+n*t.c-r*t.sn,t.cz+n*t.sn+r*t.c]}function Hd(i,e,t){let n=_b(i);if(!n)return[e,t];let[r,s]=[e-n.cx,t-n.cz];return[n.cx+r*n.c+s*n.sn,n.cz-r*n.sn+s*n.c]}function Mb(i,e=0){let{x0:t,x1:n,z0:r,z1:s}=ws(i);return[[t-e,r-e],[n+e,r-e],[n+e,s+e],[t-e,s+e]].map(o=>vb(i,o))}function Dn(i){let{x0:e,x1:t,z0:n,z1:r}=ws(i),s=o=>vb(i,o);return i.axis==="x"?{u0:e,u1:t,w:r-n,at:(o,a)=>s([o,i.flip?r-a:n+a])}:{u0:n,u1:r,w:t-e,at:(o,a)=>s([i.flip?t-a:e+a,o])}}function Fi(i,e,t){let{x0:n,x1:r,z0:s,z1:o}=ws(i),[a,l]=Hd(i,e,t);return i.axis==="x"?[a,i.flip?o-l:l-s]:[l,i.flip?r-a:a-n]}var sl=Math.tan(30*Fu);function ol(i,e,t,n,r){let s=Math.min(i*.3,n>1e-6?2.4/n:i*.3),o=Math.min(i*.3,r>1e-6?2.4/r:i*.3),a=e+s*n,l=t+o*r,c=Math.min(i-o,Math.max(s,(l-a+sl*(i-o+s))/(2*sl))),u=a+(c-s)*sl;return{vla:s,vlb:o,yla:a,ylb:l,vr:c,rh:u,y:f=>f<=s?e+f*n:f<=c?a+(f-s)*sl:f<=i-o?l+(i-o-f)*sl:t+(i-f)*r}}function En(i){let e=Dn(i).w,[t,n]=[i.eave_a,i.eave_b],[r,s]=[ur(i.pitch_a),ur(i.pitch_b)];switch(i.shape){case"flat":case"parapet":return{vr:e/2,rh:t,y:()=>t};case"pent":return{vr:e,rh:t+e*r,y:o=>t+o*r};case"mansard":{let o=ol(e,t,n,r,s);return{vr:o.vr,rh:o.rh,y:o.y}}default:{let o=r+s>1e-6?Math.min(e,Math.max(0,(n-t+e*s)/(r+s))):e/2;return{vr:o,rh:t+o*r,y:a=>a<=o?t+a*r:n+(e-a)*s}}}}var Wd=i=>En(i).rh;var xt=(i,e)=>[i[0]-e[0],i[1]-e[1]],Oi=(i,e)=>[i[0]+e[0],i[1]+e[1]],ui=(i,e)=>[i[0]*e,i[1]*e],yn=(i,e)=>i[0]*e[0]+i[1]*e[1],Rn=(i,e)=>i[0]*e[1]-i[1]*e[0],Kn=i=>Math.hypot(i[0],i[1]),hi=i=>{let e=Kn(i)||1;return[i[0]/e,i[1]/e]},Xd=i=>[-i[1],i[0]],Yd=i=>[i[1],-i[0]];function Sb(i){let e=i.heightEnd!==void 0;return{...i,a:i.b,b:i.a,left:i.right,right:i.left,roomLeft:i.roomRight,roomRight:i.roomLeft,height:e?i.heightEnd:i.height,heightEnd:e?i.height:void 0}}function RE(i,e){let t=i.map(n=>({...n}));for(let n of e){let r=t.find(s=>s.room_id===n.room_id&&s.edge===n.edge&&(Math.abs(s.t1-n.t0)<1e-6||Math.abs(n.t1-s.t0)<1e-6));r?(r.t0=Math.min(r.t0,n.t0),r.t1=Math.max(r.t1,n.t1)):t.push({...n})}return t}function CE(i,e,t){if(i.a===e.b)return!1;let n=hi(xt(t[i.b],t[i.a])),r=hi(xt(t[e.b],t[e.a]));return Math.abs(Rn(n,r))>1e-6||yn(n,r)<=0||i.free||e.free||i.heightEnd!==void 0||e.heightEnd!==void 0?!1:i.height===e.height&&i.exterior===e.exterior&&i.roomLeft===e.roomLeft&&i.roomRight===e.roomRight&&Math.abs(i.left-e.left)<=1e-9&&Math.abs(i.right-e.right)<=1e-9}function wb(i,e,t=new Set){let n=i.slice();for(;;){let r=new Map;n.forEach((o,a)=>{for(let l of[o.a,o.b])r.set(l,[...r.get(l)??[],a])});let s=null;for(let[o,a]of r){if(a.length!==2||t.has(o))continue;let l=n[a[0]].b===o?n[a[0]]:Sb(n[a[0]]),c=n[a[1]].a===o?n[a[1]]:Sb(n[a[1]]);if(!CE(l,c,e))continue;let u={...l,b:c.b,sources:RE(l.sources,c.sources)};s=[...n.filter((h,f)=>f!==a[0]&&f!==a[1]),u];break}if(!s)return n;n=s}}function Tb(i,e){let t=new Map;i.forEach((r,s)=>{let o=hi(xt(e[r.b],e[r.a])),a=[[r.a,{key:`${s}:a`,d:o,left:r.left,right:r.right,angle:Math.atan2(o[1],o[0])}],[r.b,{key:`${s}:b`,d:ui(o,-1),left:r.right,right:r.left,angle:Math.atan2(-o[1],-o[0])}]];for(let[l,c]of a)t.set(l,[...t.get(l)??[],c])});let n=new Map;for(let[r,s]of t){let o=e[r];s.sort((l,c)=>l.angle-c.angle);for(let l of s)n.set(l.key,{left:Oi(o,ui(Xd(l.d),l.left)),right:Oi(o,ui(Yd(l.d),l.right))});if(s.length<2)continue;let a=4*Math.max(...s.map(l=>Math.max(l.left,l.right)))+1e-9;s.forEach((l,c)=>{let u=s[(c+1)%s.length],h=Oi(o,ui(Xd(l.d),l.left)),f=Oi(o,ui(Yd(u.d),u.right)),d=Rn(l.d,u.d);if(Math.abs(d)<1e-4)return;let p=Oi(h,ui(l.d,Rn(xt(f,h),u.d)/d));Kn(xt(p,o))>a||(n.get(l.key).left=p,n.get(u.key).right=p)})}return n}function Ab(i,e){let t=i.filter((n,r)=>Kn(xt(n,i[(r+1)%i.length]))>e);for(;;){if(t.length<=3)return t;let n=t.findIndex((r,s)=>{let o=t[(s+t.length-1)%t.length],a=t[(s+1)%t.length],[l,c]=[xt(r,o),xt(a,r)];return Math.abs(Rn(hi(l),hi(c)))<1e-7&&yn(l,c)>0});if(n===-1)return t;t=t.filter((r,s)=>s!==n)}}function PE(i){let e=[];return{points:e,idOf(t){let n=e.findIndex(r=>Math.abs(r[0]-t[0])<=i&&Math.abs(r[1]-t[1])<=i);return n>=0?n:(e.push([t[0],t[1]]),e.length-1)}}}function IE(i,e){let t=[];for(let n of i){let r=n.points;if(r.length<3||Math.abs(es(r))<1e-6)continue;let s=es(r)>0,o=r.map(a=>e.idOf(a));o.forEach((a,l)=>{let c=o[(l+1)%o.length];a!==c&&t.push(s?{u:a,v:c,room:n.id,edge:l,forward:!0}:{u:c,v:a,room:n.id,edge:l,forward:!1})})}return t}function LE(i,e,t){let n=[];for(let r of i){let[s,o]=[e[r.u],e[r.v]],a=xt(o,s),l=Kn(a),c=ui(a,1/l),u=e.map((f,d)=>({id:d,rel:xt(f,s)})).filter(({id:f,rel:d})=>f!==r.u&&f!==r.v&&yn(d,c)>t&&yn(d,c)({t:yn(d,c),id:f})).sort((f,d)=>f.t-d.t),h=[{t:0,id:r.u},...u,{t:l,id:r.v}];for(let f=0;f+1({room_id:i.room,edge:i.edge,t0:i.t0,t1:i.t1});function FE(i,e){let t=new Map(i.map(a=>[a.id,a])),n=new Map;for(let a of e){let l=`${a.room}:${a.edge}`;n.set(l,[...n.get(l)??[],a.t0].sort((c,u)=>c-u))}let r=a=>{let l=t.get(a.room)?.wall_heights?.[a.edge];return Array.isArray(l)?l[(n.get(`${a.room}:${a.edge}`)??[]).indexOf(a.t0)]??null:l},s=a=>{let l=t.get(a.room),[c,u]=[l?.wall_heights?.[a.edge],l?.wall_slopes?.[a.edge]];if(!l||typeof c!="number"||typeof u!="number"||c<=0||u<=0)return null;let[h,f]=[l.points[a.edge],l.points[(a.edge+1)%l.points.length]];return{from:c,to:u,length:Math.hypot(f[0]-h[0],f[1]-h[1])}},o=a=>{let l=s(a);if(!l||l.length<1e-9){let u=r(a);return typeof u=="number"&&u>0?[u,u]:[null,null]}let c=u=>l.from+(l.to-l.from)*u/l.length;return a.forward?[c(a.t0),c(a.t1)]:[c(a.t1),c(a.t0)]};return{heightsOf(a){let[l,c]=[1/0,1/0];for(let h of a){let[f,d]=o(h),[p,x]=h===a[0]?[f,d]:[d,f];p!==null&&(l=Math.min(l,p)),x!==null&&(c=Math.min(c,x))}let u=a.map(h=>t.get(h.room)?.ceiling);if(u.every(h=>typeof h=="number"&&h>0)){let h=Math.max(...u);l===1/0&&(l=h),c===1/0&&(c=h)}return{...l<1/0?{a:l}:{},...c<1/0?{b:c}:{}}},thicknessOf(a){let l=a.map(c=>{let u=t.get(c.room)?.wall_thickness?.[c.edge];return Array.isArray(u)?u[(n.get(`${c.room}:${c.edge}`)??[]).indexOf(c.t0)]:u}).filter(c=>typeof c=="number"&&c>0);return l.length?Math.max(...l):void 0},hasNoWall:a=>a.some(l=>r(l)===0)}}function Rb(i){let e=t=>Math.round(t*1e6)/1e6;return i.a===void 0||i.b===void 0?i.a!==void 0?{height:e(i.a)}:i.b!==void 0?{height:e(i.b)}:{}:Math.abs(i.a-i.b)<1e-6?{height:e(i.a)}:{height:e(i.a),heightEnd:e(i.b)}}function OE(i,e,t,n){let r=FE(e,i),s=new Map;for(let l of i){let c=l.uf!==c&&f.u===c.v&&f.v===c.u&&f.room!==c.room);for(let f of l)f!==c&&f!==u&&f.room!==c.room&&n.push(`overlap:${c.room}:${f.room}`);let h=u?[c,u]:[c];if(r.hasNoWall(h)){u&&a.push([c.room,u.room]);continue}if(u){let f=r.thicknessOf(h)??t.interior;o.push({a:c.u,b:c.v,left:f/2,right:f/2,exterior:!1,roomLeft:c.room,roomRight:u.room,sources:h.map(Eb),...Rb(r.heightsOf(h))})}else o.push({a:c.u,b:c.v,left:0,right:r.thicknessOf(h)??t.exterior,exterior:!0,roomLeft:c.room,roomRight:null,sources:[Eb(c)],...Rb(r.heightsOf(h))})}return{drafts:o,open:a}}function NE(i,e){let t=s=>hi(xt(e[s.b],e[s.a])),n=i.filter(s=>!s.exterior&&!s.free),r=new Map;for(let s of n){if(r.has(s))continue;let o=[s];r.set(s,o);for(let a=0;a1e-6||l.add(yn(o,d)>0?"left":"right")}if(l.size!==1)continue;let c=[...l][0];for(let u of s){let h=u.left+u.right,f=yn(t(u),o)>0,d=c==="left"===f;[u.left,u.right]=d?[0,h]:[h,0]}}}var DE=(i,e)=>{let t=s=>Math.round(s*100),[n,r]=i[0]Math.hypot(m.b[0]-m.a[0],m.b[1]-m.a[1])>.05),l=a.map(m=>[s.idOf(m.a),s.idOf(m.b)]),c=new Set;for(let m of i){let b=m.points;b.length<3||(m.wall_splits??[]).forEach((v,y)=>{if(!v||y>=b.length)return;let M=b[y],S=xt(b[(y+1)%b.length],M),_=Kn(S);for(let w of v)w>n&&w<_-n&&c.add(s.idOf(Oi(M,ui(S,w/_))))})}let u=LE(o,s.points,n),{drafts:h,open:f}=OE(u,i,e,r);NE(h,s.points);let d=h;a.forEach((m,b)=>{let[v,y]=l[b];if(v===y)return;let M=[(m.a[0]+m.b[0])/2,(m.a[1]+m.b[1])/2],S=i.find(w=>w.points.length>=3&&Ve(M,w.points))?.id??null,_=(m.thickness??e.interior)/2;d.push({free:m.id,a:v,b:y,left:_,right:_,exterior:!1,roomLeft:S,roomRight:S,sources:[],height:typeof m.height=="number"&&m.height>0?m.height:void 0,...typeof m.height=="number"&&m.height>0&&typeof m.height_end=="number"&&m.height_end>0&&Math.abs(m.height_end-m.height)>1e-6?{heightEnd:m.height_end}:{}})});let p=wb(d,s.points,c),x=Tb(p,s.points);return{walls:p.map((m,b)=>{let[v,y]=[s.points[m.a],s.points[m.b]],[M,S]=[x.get(`${b}:a`),x.get(`${b}:b`)],_=Ab([M.right,S.left,y,S.right,M.left,v],1e-6);return{id:DE(v,y),a:[v[0],v[1]],b:[y[0],y[1]],left:m.left,right:m.right,exterior:m.exterior,roomLeft:m.roomLeft,roomRight:m.roomRight,sources:m.sources,footprint:_,...m.free?{free:m.free}:{},...m.height!==void 0?{height:m.height}:{},...m.heightEnd!==void 0?{heightEnd:m.heightEnd}:{}}}),warnings:[...new Set(r)],open:f}}function Cb(i,e,t){let n=i.points[e];return Oi(n,ui(hi(xt(i.points[(e+1)%i.points.length],n)),t))}function Pb(i,e,t){if(i.wall){let r=t.find(a=>a.id===i.wall);if(!r||Math.hypot(r.b[0]-r.a[0],r.b[1]-r.a[1])<.05)return null;let s=hi(xt(r.b,r.a));return{room:{id:i.room_id,name:"",area_id:null,points:[r.a,r.b,Oi(r.a,[-s[1],s[0]])]},edge:0}}let n=e.find(r=>r.id===i.room_id);return n&&i.edgeyn(xt(e,i.a),hi(xt(i.b,i.a)));function Lb(i,e,t){if(!e.wall)return UE(i,t.room,t.edge,e.offset);let n=i.find(r=>r.free===e.wall);return n?{wall:n,s:Ib(n,Cb(t.room,0,e.offset))}:null}function UE(i,e,t,n){for(let r of i)if(r.sources.some(o=>o.room_id===e.id&&o.edge===t&&n>=o.t0-1e-6&&n<=o.t1+1e-6))return{wall:r,s:Ib(r,Cb(e,t,n))};return null}var Fb=([i,e])=>{let t=Math.hypot(i,e)||1;return[i/t,e/t]};function BE(i){return i.reduce((e,t,n)=>e+(t[0]*i[(n+1)%i.length][1]-i[(n+1)%i.length][0]*t[1]),0)/2}function Ou(i,e){let t=i.length;if(t<3||Math.abs(e)<1e-9)return i.map(([r,s])=>[r,s]);let n=BE(i)>=0?1:-1;return i.map((r,s)=>{let o=i[(s+t-1)%t],a=i[(s+1)%t],[l,c]=Fb([r[0]-o[0],r[1]-o[1]]),[u,h]=Fb([a[0]-r[0],a[1]-r[1]]),f=[c*n,-l*n],d=[h*n,-u*n],p=[f[0]+d[0],f[1]+d[1]],x=Math.hypot(p[0],p[1]);if(x<1e-6)return[r[0]+f[0]*e,r[1]+f[1]*e];let g=(p[0]*f[0]+p[1]*f[1])/x,m=Math.min(4,1/Math.max(.25,g));return[r[0]+p[0]/x*e*m,r[1]+p[1]/x*e*m]})}function qd(i,e){if(i.points&&i.points.length>=3)return Ou(i.points,e);if(i.rotation)return Mb(i,e);let t=Math.min(i.x0,i.x1)-e,n=Math.max(i.x0,i.x1)+e,r=Math.min(i.z0,i.z1)-e,s=Math.max(i.z0,i.z1)+e;return[[t,r],[n,r],[n,s],[t,s]]}function Hr(i,e){let t=Dn(i),n=En(i),r=t.w,[s,o]=[Math.max(0,e.a),Math.max(0,e.b)],a=t.u0-Math.max(0,e.u0),l=t.u1+Math.max(0,e.u1),c=(m,b)=>[m,b,n.y(b)],u=c(a,-s),h=c(l,-s),f=c(l,r+o),d=c(a,r+o),[p,x]=[ur(i.pitch_a),ur(i.pitch_b)],g=m=>[m,n.vr,n.rh];if(i.ends&&(i.shape==="gable"||i.shape==="hip"||i.shape==="halfhip")){let m=(t.u1-t.u0)/2,b=Math.min(m,Math.min(n.vr,r-n.vr)||r/2),v=Math.min(n.y(0),n.y(r)),y=v+(n.rh-v)*Math.min(.9,Math.max(.2,i.halfhip??.55)),M=p>1e-6?Math.min(n.vr,(y-i.eave_a)/p):n.vr,S=x>1e-6?Math.max(n.vr,r-(y-i.eave_b)/x):n.vr,_=Math.min(m-.1,(n.rh-y)/Math.max(.2,p)),w=[[0,n.y(0)],[n.vr,n.rh],[r,n.y(r)]],R=[[0,n.y(0)],[M,y],[S,y],[r,n.y(r)]],A=(F,H,B)=>{if(F==="hip")return{upA:[],upB:[],ridge:g(H===a?t.u0+b*B:t.u1-b*B),profile:null};if(F==="halfhip"){let X=g(H===a?t.u0+_:t.u1-_);return{upA:[[H,M,y]],upB:[[H,S,y]],ridge:X,profile:R}}return{upA:[],upB:[],ridge:g(H),profile:w}},C=A(i.ends[0],a,1),O=A(i.ends[1],l,1),D=[[u,h,...O.upA,O.ridge,C.ridge,...[...C.upA].reverse()],[C.ridge,O.ridge,...[...O.upB].reverse(),f,d,...C.upB]],P=[[C.ridge,O.ridge]];for(let[F,H,B]of[[C,u,d],[O,h,f]])F.profile===null?(D.push(F===C?[d,u,F.ridge]:[h,f,F.ridge]),P.push([H,F.ridge],[B,F.ridge])):F.upA.length&&(D.push(F===C?[F.upB[0],F.upA[0],F.ridge]:[F.upA[0],F.upB[0],F.ridge]),P.push([F.upA[0],F.ridge],[F.upB[0],F.ridge]));let I=F=>F.profile===null?[]:F.upA.length?[F.upA[0],F.upB[0]]:[F.ridge],N=[u,h,...I(O),f,d,...[...I(C)].reverse()];return{faces:D,rim:N,ridges:P,gable:w,endProfiles:[C.profile,O.profile]}}switch(i.shape){case"pent":return{faces:[[u,h,f,d]],rim:[u,h,f,d],ridges:[[f,d]],gable:[[0,n.y(0)],[r,n.y(r)]]};case"hip":case"pyramid":{let m=(t.u1-t.u0)/2,b=i.shape==="pyramid"?m:Math.min(m,Math.min(n.vr,r-n.vr)||r/2),v=g(t.u0+b),y=g(t.u1-b);return i.shape==="pyramid"?{faces:[[u,h,v],[h,f,v],[f,d,v],[d,u,v]],rim:[u,h,f,d],ridges:[[u,v],[d,v],[h,v],[f,v]],gable:null}:{faces:[[u,h,y,v],[v,y,f,d],[d,u,v],[h,f,y]],rim:[u,h,f,d],ridges:[[v,y],[u,v],[d,v],[h,y],[f,y]],gable:null}}case"halfhip":{let m=Math.min(n.y(0),n.y(r)),b=m+(n.rh-m)*Math.min(.9,Math.max(.2,i.halfhip??.55)),v=p>1e-6?Math.min(n.vr,(b-i.eave_a)/p):n.vr,y=x>1e-6?Math.max(n.vr,r-(b-i.eave_b)/x):n.vr,M=Math.min((t.u1-t.u0)/2-.1,(n.rh-b)/Math.max(.2,p)),S=g(t.u0+M),_=g(t.u1-M),w=[a,v,b],R=[a,y,b],A=[l,v,b],C=[l,y,b];return{faces:[[u,h,A,_,S,w],[S,_,C,f,d,R],[R,w,S],[A,C,_]],rim:[u,h,A,C,f,d,R,w],ridges:[[S,_],[w,S],[R,S],[A,_],[C,_]],gable:[[0,n.y(0)],[v,b],[y,b],[r,n.y(r)]]}}case"mansard":{let m=ol(r,i.eave_a,i.eave_b,p,x),b=[a,m.vla,m.yla],v=[l,m.vla,m.yla],y=[a,r-m.vlb,m.ylb],M=[l,r-m.vlb,m.ylb],S=[a,m.vr,m.rh],_=[l,m.vr,m.rh];return{faces:[[u,h,v,b],[b,v,_,S],[S,_,M,y],[y,M,f,d]],rim:[u,h,v,_,M,f,d,y,S,b],ridges:[[S,_],[b,v],[y,M]],gable:[[0,n.y(0)],[m.vla,m.yla],[m.vr,m.rh],[r-m.vlb,m.ylb],[r,n.y(r)]]}}default:{let m=g(a),b=g(l);return{faces:[[u,h,b,m],[m,b,f,d]],rim:[u,h,b,f,d,m],ridges:[[m,b]],gable:[[0,n.y(0)],[n.vr,n.rh],[r,n.y(r)]]}}}}function Ts(i,e,t){let n=null;for(let r of i.faces){if(!Ve([e,t],r.map(([f,d])=>[f,d])))continue;let[s,o]=r,a=r.slice(2).find(f=>Math.abs((o[0]-s[0])*(f[1]-s[1])-(o[1]-s[1])*(f[0]-s[0]))>1e-9);if(!a)continue;let l=[o[0]-s[0],o[2]-s[2],o[1]-s[1]],c=[a[0]-s[0],a[2]-s[2],a[1]-s[1]],u=[l[1]*c[2]-l[2]*c[1],l[2]*c[0]-l[0]*c[2],l[0]*c[1]-l[1]*c[0]];if(Math.abs(u[1])<1e-9)continue;let h=s[2]-(u[0]*(e-s[0])+u[2]*(t-s[1]))/u[1];n=n===null?h:Math.min(n,h)}return n}function Ro(i,e,t,n){let r=o=>n?o[e]<=t+1e-9:o[e]>=t-1e-9,s=[];return i.forEach((o,a)=>{let l=i[(a+1)%i.length];if(r(o)&&s.push(o),r(o)!==r(l)){let c=(t-o[e])/(l[e]-o[e]);s.push([o[0]+(l[0]-o[0])*c,o[1]+(l[1]-o[1])*c,o[2]+(l[2]-o[2])*c])}}),s}function Nu(i,e){let t=Ro(Ro(i,0,e.u0,!1),0,e.u1,!0);return[Ro(i,0,e.u0,!0),Ro(i,0,e.u1,!1),Ro(t,1,e.v0,!0),Ro(t,1,e.v1,!1)].filter(r=>r.length>=3&&Math.abs(vr(r.map(([s,o])=>[s,o])))>1e-6)}function ll(i,e,t){let n=Dn(e),r=i.floors.flatMap(h=>h.rooms.filter(f=>f.points.length>=3&&h.elevation+h.height>e.base+.05)),s=h=>h.some(f=>r.some(d=>Ve(f,d.points))),o=.35,a=[.15,.5,.85].map(h=>n.u0+(n.u1-n.u0)*h),l=[.15,.5,.85].map(h=>n.w*h),c=h=>h?0:t,u=(h,f)=>{let d=e.overhang_sides?.[h];return typeof d=="number"&&Number.isFinite(d)?Math.min(2,Math.max(0,d)):f};return{a:u("a",c(s(a.map(h=>n.at(h,-o))))),b:u("b",c(s(a.map(h=>n.at(h,n.w+o))))),u0:u("u0",c(s(l.map(h=>n.at(n.u0-o,h))))),u1:u("u1",c(s(l.map(h=>n.at(n.u1+o,h)))))}}var Co=i=>Math.abs((i.x1-i.x0)*(i.z1-i.z0)),Du=i=>i.shape==="flat"||i.shape==="parapet";function As(i,e){let[t,n]=[(e.x0+e.x1)/2,(e.z0+e.z1)/2];return i.filter(s=>{if(s===e||s.dormer||s.open||Du(s)||Co(s)=o.x0&&t<=o.x1&&n>=o.z0&&n<=o.z1}).reduce((s,o)=>s===null||Co(o){let[s,o]=e.at(r,e.w/2),[a,l]=Fi(i,s,o);return Ts(t,a,l)??n.y(l)}}function cl(i,e){if(Du(e))return e;let t=Dn(e),n=En(e).rh,r=Ob(i,t),s=r(t.u0)<=r(t.u1),[o,a]=s?[t.u0,t.u1]:[t.u1,t.u0],l=s?1:-1,c=a;for(let f=.5;f=n-.02){c=o+l*f;break}if(Math.abs(c-a)<.05)return e;let u={...e},h=a===t.u1;return e.axis==="x"?u[h?"x1":"x0"]=c:u[h?"z1":"z0"]=c,u}function Uu(i,e){let t=cl(i,e),n=Dn(t),r=En(t),s=Ob(i,n),o=s(n.u0)<=s(n.u1),a=n.u1-n.u0,l=Math.max(1,Math.ceil(a/.15)),c=[];for(let u=0;ux+.02&&(g=Math.min(g,M),m=Math.max(m,M))}if(!(m-g>.05))continue;let b=Fi(i,...n.at(d,g)),v=Fi(i,...n.at(p,m));c.push({u0:Math.min(b[0],v[0]),u1:Math.max(b[0],v[0]),v0:Math.min(b[1],v[1]),v1:Math.max(b[1],v[1])})}return c}function ul(i,e){if(e.dormer||e.open||Du(e)||As(i,e))return null;let t=ws(e),n=.35;for(let r of i){if(r===e||r.dormer||r.open||Du(r)||r.axis===e.axis||Co(r)a[3]+.05)continue;let l=(o[2]+o[3])/2,[c,u]=e.axis==="z"?["z0","z1"]:["x0","x1"],h;if(Math.abs(o[0]-o[3])<=n)h=[l,o[1]];else if(Math.abs(o[1]-o[2])<=n)h=[o[0],l];else continue;let f={...e,[c]:h[0],[u]:h[1]};return{parent:r,extended:cl(r,f)}}return null}var Nb=.14,kE=i=>i.shape==="flat"||i.shape==="parapet";function $d(i,e){return!i.open&&Math.min(i.base,i.eave_a,i.eave_b)l+r||fu+r||o.points&&o.points.length>=3&&!Ve([e,t],o.points))continue;let[d,p]=Fi(o,e,t),x=Math.max(0,o.overhang??n),g=kE(o)?null:Ts(Hr(o,{u0:x,u1:x,a:x,b:x}),d,p);s.push((g??En(o).y(p))-Nb)}return s.length?Math.max(...s):null}function Zd(i,e){let t=i.floors.filter(l=>l.rooms.length>0).sort((l,c)=>l.elevation-c.elevation),n=t.filter(l=>l.elevationu.rooms.some(h=>h.points.length>=3&&l.some(f=>Ve(f,h.points))));if(c)return c}return n.at(-1)??t[0]}function Jd(i,e,t){let n=i.settings.roof.sections??[],r=n.filter(l=>t.includes(l.id)).map(l=>As(n,l)??l);if(r.length===0)return e.id;let s=Math.max(...r.map(Wd)),o=l=>l.rooms.some(c=>{if(c.points.length<3)return!1;let u=c.points.reduce((f,d)=>f+d[0],0)/c.points.length,h=c.points.reduce((f,d)=>f+d[1],0)/c.points.length;return r.some(f=>u>=Math.min(f.x0,f.x1)&&u<=Math.max(f.x0,f.x1)&&h>=Math.min(f.z0,f.z1)&&h<=Math.max(f.z0,f.z1))});return i.floors.filter(l=>l.elevation>=e.elevation&&l.elevationc.elevation-l.elevation)[0]?.id??e.id}var Po=new U;function Db(i,e,t,n=1.05){return Po.set(e[0],e[1],e[2]).project(i),{x:(Po.x+1)/2*t.w,y:(1-Po.y)/2*t.h,off:Po.z>1||Math.abs(Po.x)>n||Math.abs(Po.y)>n}}var hl=i=>`translate(${i.x}px, ${i.y}px) translate(-50%, -50%)`,Ub=(i,e)=>`translate(${i}px, ${e}px) translate(0, -50%)`,Bu=class{placed=new WeakMap;place(e,t){let n=t===null;e.hidden!==n&&(e.hidden=n),!(t===null||this.placed.get(e)===t)&&(this.placed.set(e,t),e.style.transform=t)}},zE=8;function Bb(i){let e=[...i].sort((t,n)=>n.rank-t.rank).map(t=>({...t}));for(let t=1;tc.xc.x>l.x?c:l),s=8+t.inset,[o,a]=[n.x-e-14,n.y];return o=.99&&i.o>=.9&&!e}function zb(i){return i.to>0&&Math.abs(i.o-i.to)<.05}function Vb(i,e,t,n){return e===void 0?{y:t?i*2.4:0,opacity:1}:i>e?{y:5+i,opacity:0}:i===e?{y:0,opacity:1}:n==="stacked"?{y:0,opacity:1}:{y:-.4,opacity:n==="single"?0:.22}}function Gb(i,e){let[t,n]=[i.ty-i.y,i.to-i.o];if(Math.abs(t)<.004&&Math.abs(n)<.004){let r=t!==0||n!==0;return r&&([i.y,i.o]=[i.ty,i.to]),{moving:!1,settled:r}}return i.y+=t*e,i.o+=n*e,{moving:!0,settled:!1}}function Hb(i,e){let t=e>.999;for(let n of[i.floor,i.wall,i.frames,i.blinds,i.lamps])n.transparent===t&&(n.transparent=!t,n.depthWrite=t,n.needsUpdate=!0),n.opacity=e;for(let n of i.ghosts)n.material.opacity=n.base*e;for(let n of[i.pattern,i.glow,i.lines,i.glass,i.glassWall,i.halos,i.cones,i.screens])n.opacity=e}var Qd=i=>1-Math.exp(-i/140);var Xb=["open","open2","tilt","tilt2"],ep=i=>1-Math.exp(-i/160),Wb=(i,e)=>(i??null)===(e??null)||typeof i=="number"&&typeof e=="number"&&Math.abs(i-e)<.003;function tp(i,e){return Xb.every(t=>Wb(e[t]??0,i[t]??0))&&Wb(e.cover,i.cover)&&!!e.sensed==!!i.sensed&&!!e.unlocked==!!i.unlocked&&!!e.assumed==!!i.assumed}function Yb(i,e,t){let n={...i,open2:i.open2??0,tilt2:i.tilt2??0,sensed:e.sensed,unlocked:e.unlocked,assumed:e.assumed},r=!1,s=(o,a)=>Math.abs(a-o)<.003?a:(r=!0,o+(a-o)*t);for(let o of Xb)n[o]=s(i[o]??0,e[o]??0);return n.cover=e.cover===null||i.cover===null?e.cover:s(i.cover,e.cover),{state:n,moving:r}}var Es={ceiling:[.4,.4,.08],downlight:[.1,.1,.02],spot:[.1,.1,.14],panel:[.6,.6,.03],uplight:[.35,.35,1.8],bollard:[.16,.16,.8],garden:[.12,.12,.3],pendant:[.4,.4,.8],fan:[1.32,1.32,.32],floor:[.42,.42,1.7],table:[.26,.26,.45],wall:[.22,.12,.2],strip:[2,.04,.03]},ku=new Set(["ceiling","downlight","spot","panel","pendant","fan","strip"]),VE=1;function qb(i,e,t,n){switch(i){case"ceiling":return[e-.12,"ceiling"];case"downlight":return[e-.03,"spot"];case"spot":return[e-n,"spot"];case"panel":return[e-.05,"ceiling"];case"pendant":return[Math.max(.5,e-n),"pendant"];case"fan":return[Math.max(.5,e-n+.02),"ceiling"];case"floor":return[t+n-.15,"omni"];case"uplight":return[t+n,"up"];case"table":return[t+n-.1,"omni"];case"wall":return[t+.1,"wall"];case"strip":return[t+Math.max(.02,n)-.01,tGE&&d=0&&p<=1&&(l=d)}return l}function Jb(i,e,t){let n=i.count,r=e.wedge;if(!r)return{start:n,end:n};let s=(e.rotation??0)*pt,o=[-Math.sin(s),Math.cos(s)],a=r.angle*pt/2,l=new W(...r.color.map(d=>d*r.opacity)),c=new W(0,0,0),u=Math.max(4,Math.round(a/.15)),h=[e.x,e.z],f=(d,p)=>[e.x+(o[0]*Math.cos(d)-o[1]*Math.sin(d))*p,Kb,e.z+(o[1]*Math.cos(d)+o[0]*Math.sin(d))*p];for(let d=0;d{i.positions.push(h,f,d);for(let x of t.color)i.colours.push(x*t.level*HE*p)};if(e.lamp==="strip")for(let h of[-.4,-.13,.13,.4])e.upright?u(e.x,a+r*(.5+h),e.z,.6):u(...zu(e.x,c+Io(e.base,r,e.rise),e.z,l,r,e.rise,h),.6);else e.lamp==="wall"?u(e.x-Math.sin(l)*(s/2+.05),c,e.z+Math.cos(l)*(s/2+.05),1):u(e.x,c,e.z,1)}function ey(i,e,t,n){let[r,,s]=e.size??Es[e.lamp],o=jb(e.lamp,n,e.base??0,s),a=new W(...t.color.map(d=>d*.09*t.level)),l=new W(0,0,0),[c,u]=[Math.max(.03,r/2),.45+.35*t.level],h=16,f=(d,p,x)=>[e.x+Math.cos(d)*p,x,e.z+Math.sin(d)*p];for(let d=0;dku.has(i);var ny=7,WE=.25,XE=.3,YE=2,np=[1,.82,.55],qE=.45;function iy(i,e,t,n){return i?`${i.elevation.toFixed(1)},${i.azimuth.toFixed(1)},${e*pt},${t.toFixed(2)},${[...n].map(r=>(r.cover??0).toFixed(2)).join(",")}`:""}var Lo=(i,e)=>[Math.sin((e+i)*pt),-Math.cos((e+i)*pt)],ip=(i,e)=>Math.min(1,i/12)*(1-.8*e),$E=(i,e)=>-i.toRoom[0]*e[0]+-i.toRoom[1]*e[1];function ry({floor:i,openings:e,states:t,sun:n,northDegrees:r,cloud:s}){let o=new lt;if(!n||n.elevation<=YE||s>=.97)return o;let a=ip(n.elevation,s),l=Lo(n.azimuth,r),c=1/Math.tan(n.elevation*pt);for(let u of e){if(u.opening.type!=="window"||!u.exterior)continue;let h=$E(u,l);if(h<.05)continue;let f=u.top-(t.get(u.opening.id)?.cover??0)*(u.top-u.sill);if(f-u.sill<.05)continue;let d=i.rooms.find(M=>M.id===u.opening.room_id);if(!d||d.points.length<3)continue;let p=(M,S)=>{let _=Math.min(ny,S*c);return[u.start[0]+u.axis[0]*M+u.toRoom[0]*u.faceRoom-l[0]*_,.02,u.start[1]+u.axis[1]*M+u.toRoom[1]*u.faceRoom-l[1]*_]},x=.14*a*Math.min(1,h*1.5),g=new W(np[0]*x,np[1]*x,np[2]*x),m=g.clone().multiplyScalar(qE),b=Math.max(1,Math.ceil(Math.min(ny,f*c)/WE)),v=Math.max(1,Math.ceil(u.width/XE)),y=f-u.sill;for(let M=0;Me+Rn(t,i[(n+1)%i.length]),0)/2}var oy=i=>sy(i)>=0?[...i]:[...i].reverse();function ay(i,e,t,n){let r=xt(e,i),s=xt(n,t),o=Rn(r,s);if(Math.abs(o)<1e-12)return null;let a=Rn(xt(t,i),s)/o,l=Rn(xt(t,i),r)/o;return a>hr&&a<1-hr&&l>-hr&&l<1+hr?a:null}function rp(i,e,t){let n=xt(t,e),r=yn(n,n);if(r<1e-12)return null;let s=yn(xt(i,e),n)/r;return s<=hr||s>=1-hr?null:Math.abs(Rn(xt(i,e),n))/Math.sqrt(r)Kn(xt(i,e))i.map((e,t)=>[e,i[(t+1)%i.length]]);function KE(i,e){for(let[t,n]of dl(i))for(let[r,s]of dl(e))if(ay(t,n,r,s)!==null||rp(r,t,n)!==null||rp(t,r,s)!==null||fl(t,r))return!0;return Ve(i[0],e)||Ve(e[0],i)}function ZE(i){let e=i.map(oy),t=[];e.forEach((s,o)=>{for(let[a,l]of dl(s)){let c=[0,1];e.forEach((u,h)=>{if(h!==o)for(let[f,d]of dl(u)){let p=ay(a,l,f,d)??rp(f,a,l);p!==null&&c.push(p)}}),c.sort((u,h)=>u-h);for(let u=1;ug!==o&&Ve(p,x))||t.some(([x,g])=>fl(x,h)&&fl(g,f))||t.push([h,f])}}});let n=[],r=new Set;return t.forEach(([s,o],a)=>{if(r.has(a))return;r.add(a);let l=[s],c=o;for(let u=0;u!r.has(d)&&fl(f,c,.001));if(h<0)break;r.add(h),l.push(t[h][0]),c=t[h][1]}l.length>=3&&sy(l)>1e-6&&n.push(l)}),n}function fr(i){let e=i.filter(s=>s.length>=3),t=e.map((s,o)=>o),n=s=>t[s]===s?s:t[s]=n(t[s]);e.forEach((s,o)=>{for(let a=o+1;ar.set(n(o),[...r.get(n(o))??[],s])),[...r.values()].flatMap(s=>s.length===1?s:ZE(s))}function JE(i,e,t){let n=xt(t,e),r=yn(n,n),s=r?Math.max(0,Math.min(1,yn(xt(i,e),n)/r)):0;return Kn(xt(i,[e[0]+n[0]*s,e[1]+n[1]*s]))}function ly(i,e,t=.03){return i.every(n=>Ve(n,e)||dl(e).some(([r,s])=>JE(n,r,s)<=t))}function cy(i,e){let t=oy(i),n=(r,s)=>{let o=xt(s,r),a=Kn(o)||1;return[-o[1]/a,o[0]/a]};return t.map((r,s)=>{let o=n(t[(s-1+t.length)%t.length],r),a=n(r,t[(s+1)%t.length]),l=1+yn(o,a);return l<.1?r:[r[0]+(o[0]+a[0])/l*e,r[1]+(o[1]+a[1])/l*e]})}var jE=30,uy=i=>i.reduce((e,t,n)=>e+t[0]*i[(n+1)%i.length][1]-i[(n+1)%i.length][0]*t[1],0)/2;function QE(i,e,t,n){if(!t||t.elevation<=2||e<=0||!i.length)return[];let r=Math.min(jE,e/Math.tan(t.elevation*Math.PI/180)),[s,o]=Lo(t.azimuth,n),a=c=>[c[0]-s*r,c[1]-o*r],l=[];for(let c of i){l.push([...c],c.map(a));let u=Math.sign(uy(c))||1;c.forEach((h,f)=>{let d=c[(f+1)%c.length];if(u*((d[1]-h[1])*-s-(d[0]-h[0])*-o)<=1e-9)return;let x=[h,d,a(d),a(h)];Math.abs(uy(x))>.001&&l.push(x)})}return fr(l)}var Vu=class{mesh;material=new Ke({color:0,side:ut,transparent:!0,opacity:0,depthWrite:!1,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});constructor(){this.mesh=new we(new Fe,this.material),this.mesh.renderOrder=1,this.mesh.visible=!1}update(e,t,n,r,s,o,a){let l=a?[]:QE(e,t,r,s),c=[];for(let h of l){let f=e.filter(p=>Ve([p.reduce((x,g)=>x+g[0],0)/p.length,p.reduce((x,g)=>x+g[1],0)/p.length],h)),d=[...h,...f.flat()];for(let[p,x,g]of Vr(h,f.map(m=>[...m])))for(let m of[d[p],d[x],d[g]])c.push(m[0],n,m[1])}this.mesh.geometry.dispose();let u=new Fe;u.setAttribute("position",new ke(c,3)),this.mesh.geometry=u,this.material.opacity=r?.32*ip(r.elevation,o):0,this.mesh.visible=c.length>0&&this.material.opacity>.02}dispose(){this.mesh.geometry.dispose(),this.material.dispose()}};var pl=i=>es(i)>=0?i:[...i].reverse();function ml(i,[e,t],n,r,s,o,a){Tt(i,pl([[e-n,t-n],[e+n,t-n],[e+n,t+n],[e-n,t+n]]),r,s,o,a)}function Gu(i,e,t,n,r,s,o,a,l=0){let[c,u]=[t[0]-e[0],t[1]-e[1]],h=Math.hypot(c,u);if(h<1e-6)return;let[f,d]=[-u/h*n*.5,c/h*n*.5];if(Math.abs(l)<1e-4){Tt(i,pl([[e[0]+f,e[1]+d],[t[0]+f,t[1]+d],[t[0]-f,t[1]-d],[e[0]-f,e[1]-d]]),r,s,o,a,{aoFrom:r-1});return}let p=(y,M)=>[e[0]+f*M,y,e[1]+d*M],x=(y,M)=>[t[0]+f*M,y+l,t[1]+d*M],g=(y,M)=>{for(let[S,_,w]of[[0,1,2],[0,2,3],[0,2,1],[0,3,2]])i.tri(y[S],y[_],y[w],M,M,M,void 0,Xe)},m=new W(a),b=Ue(o,.9),v=Ue(o,.6);g([p(s,1),x(s,1),x(s,-1),p(s,-1)],m),g([p(r,1),x(r,1),x(r,-1),p(r,-1)],v),g([p(r,1),x(r,1),x(s,1),p(s,1)],b),g([p(r,-1),x(r,-1),x(s,-1),p(s,-1)],b),g([p(r,1),p(r,-1),p(s,-1),p(s,1)],b),g([x(r,1),x(r,-1),x(s,-1),x(s,1)],b)}function hy(i,e,t){let n=(o,a)=>Math.abs(o[0]-a[0])<1e-6&&Math.abs(o[1]-a[1])<1e-6,r=Math.hypot(t[0]-e[0],t[1]-e[1]),s=[];for(let o of i.gates??[]){let a=i.points[o.edge],l=i.points[(o.edge+1)%i.points.length];!a||!l||(n(a,e)&&n(l,t)?s.push({gate:o,offset:o.offset}):n(a,t)&&n(l,e)&&s.push({gate:o,offset:r-o.offset}))}return s.sort((o,a)=>o.offset-a.offset)}function fy(i,e,t,n,r){let s=Math.hypot(e[0]-i[0],e[1]-i[1]);if(s<.3)return null;let o=Math.min(t.width,s-.1);if(o<.3)return null;let a=Math.max(.05,Math.min(s-o-.05,n-o/2)),l=a+o,[c,u]=[(e[0]-i[0])/s,(e[1]-i[1])/s],[h,f]=[-u,c],d=(m,b=0)=>[i[0]+c*m+h*b,i[1]+u*m+f*b],[p,x]=[d(a),d(l)],g=[];if(t.kind==="double"){let m=(a+l)/2;g.push(r?{a:p,b:d(a,o/2)}:{a:p,b:d(m)}),g.push(r?{a:x,b:d(l,o/2)}:{a:x,b:d(m)})}else t.kind==="sliding"?g.push(r?{a:d(l,-.12),b:d(l+o,-.12)}:{a:p,b:x}):g.push(r?{a:p,b:d(a,o)}:{a:p,b:x});return{from:a,to:l,posts:[p,x],leaves:g}}var dy={lawn:{color:927778,side:729115,edge:4121250,edgeAlpha:.16},terrace:{color:1841968,side:1447464,edge:5995775,edgeAlpha:.32},path:{color:1778228,side:1383209,edge:5995775,edgeAlpha:.22},driveway:{color:1514796,side:1185573,edge:5995775,edgeAlpha:.18},pool:{color:736091,side:861497,edge:3662079,edgeAlpha:.6},bed:{color:1775123,side:1380623,edge:4121250,edgeAlpha:.2},wild:{color:1384987,side:1055509,edge:10146383,edgeAlpha:.14},hedge:{color:1524016,side:1126693,edge:4121250,edgeAlpha:.35},fence:{color:1976903,side:1976903,edge:5995775,edgeAlpha:.45},pergola:{color:2827065,side:2104109,edge:5995775,edgeAlpha:.5}};function sp(i,e){return Ko(i)+(e.offset??0)+(Jr(e.type)?.01:Ll[e.type])}function Hu(i,e){let t=i[e];return Jr(t.type)||t.type==="pool"?[]:i.filter((n,r)=>r!==e&&m0(n)&&n.points.length>=3&&n.points.every(s=>Ve(s,t.points))).map(n=>pl(n.points))}var Wu=(i,e)=>i.map((t,n)=>[n,t,i[(n+1)%i.length]]).filter(([t])=>t!==e);function gl(i,e){if(i.area.outline!==!1)for(let[,t,n]of Wu(i.poly,i.openEdge))i.lines.seg([t[0],e(t[0],t[1]),t[1]],[n[0],e(n[0],n[1]),n[1]],i.edge,Xe)}function eR(i){let{buf:e,poly:t,base:n,top:r,look:s}=i,o=new W(s.color);for(let[l,c,u]of Vr(t)){let[h,f,d]=[t[l],t[c],t[u]];e.tri([h[0],n+r,h[1]],[d[0],n+r,d[1]],[f[0],n+r,f[1]],o,o,o,void 0,Xe)}let a=new W(s.side);for(let[,l,c]of Wu(t,-1))e.tri([c[0],n+r,c[1]],[c[0],n+.06,c[1]],[l[0],n+.06,l[1]],a,a,a,void 0,Xe),e.tri([c[0],n+r,c[1]],[l[0],n+.06,l[1]],[l[0],n+r,l[1]],a,a,a,void 0,Xe);gl(i,()=>n+.06),gl(i,()=>n+r+.005)}function tR(i){let{buf:e,lines:t,poly:n,area:r,top:s,look:o,groundAt:a,edge:l,openEdge:c}=i;for(let[u,h,f]of Wu(n,c)){let d=Math.hypot(f[0]-h[0],f[1]-h[1]),p=Math.max(1,Math.round(d/2)),x=hy(r,h,f).map(({gate:M,offset:S})=>({gate:M,layout:fy(h,f,M,S,!!M.open)})).filter(M=>!!M.layout),g=M=>x.some(S=>M>S.layout.from-.15&&M=0&&u===c-1?p:p-1;for(let M=0;M<=m;M++){if(g(d*M/p))continue;let S=h[0]+(f[0]-h[0])*M/p,_=h[1]+(f[1]-h[1])*M/p,w=a(S,_);ml(e,[S,_],.04,w,w+s,o.side,o.color)}let b=[],v=0;for(let M of x)b.push([v,M.layout.from]),v=M.layout.to;b.push([v,d]);let y=M=>[h[0]+(f[0]-h[0])*M/d,h[1]+(f[1]-h[1])*M/d];for(let[M,S]of b){if(S-M<.02)continue;let[_,w]=[y(M),y(S)];for(let R of[.35,.85])t.seg([_[0],a(_[0],_[1])+R*s,_[1]],[w[0],a(w[0],w[1])+R*s,w[1]],l,Xe)}for(let{layout:M}of x){for(let S of M.posts){let _=a(S[0],S[1]);ml(e,S,.07,_,_+s*1.05,o.side,o.color)}for(let S of M.leaves)nR(i,S.a,S.b)}}}function nR(i,e,t){let{buf:n,lines:r,top:s,look:o,groundAt:a,edge:l}=i,c=Math.hypot(t[0]-e[0],t[1]-e[1]);if(c<.05)return;let[u,h]=[a(e[0],e[1]),a(t[0],t[1])],f=h-u;for(let[p,x]of[[.12,.2],[.78,.86]])Gu(n,e,t,.05,u+p*s,u+x*s,o.side,o.color,f);let d=Math.max(2,Math.round(c/.18));for(let p=0;p<=d;p++){let x=p/d,g=e[0]+(t[0]-e[0])*x,m=e[1]+(t[1]-e[1])*x,b=u+f*x;ml(n,[g,m],p===0||p===d?.03:.012,b+.1*s,b+.9*s,o.side,o.color)}r.seg([e[0],u+.2*s,e[1]],[t[0],h+.78*s,t[1]],l,Xe)}function iR(i){let{buf:e,lines:t,poly:n,area:r,top:s,look:o,groundAt:a,edge:l,openEdge:c}=i;for(let u of n){let h=a(u[0],u[1]);ml(e,u,.06,h,h+s,o.side,o.color)}for(let[,u,h]of Wu(n,c)){let[f,d]=[a(u[0],u[1]),a(h[0],h[1])];Gu(e,u,h,.12,f+s-.16,f+s,o.side,o.color,d-f),r.bracing&&(t.seg([u[0],f+.25,u[1]],[h[0],d+s-.25,h[1]],l,Xe),t.seg([h[0],d+.25,h[1]],[u[0],f+s-.25,u[1]],l,Xe))}if(T0(n)){let u=A0(n),h=u.x1-u.x0>=u.z1-u.z0,[f,d]=h?[u.x0,u.x1-u.x0]:[u.z0,u.z1-u.z0],p=Math.max(1,Math.round(d/.6));for(let x=1;xa(u,h)+s+.004)}function rR(i,e,t){let{buf:n,lines:r,poly:s,area:o,top:a,look:l,groundAt:c,base:u,edge:h}=i,f=u-(o.slope??0),d=(x,g)=>c(x,g)+a,p=Hu(e,t);if(Tt(n,s,f,o.slope?d:u+a,l.side,l.color,{aoFrom:f,holes:p}),gl(i,(x,g)=>d(x,g)+.004),o.type==="hedge"&&gl(i,(x,g)=>c(x,g)+.004),o.outline!==!1)for(let x of p)x.forEach((g,m)=>{let b=x[(m+1)%x.length];r.seg([g[0],d(g[0],g[1])+.004,g[1]],[b[0],d(b[0],b[1])+.004,b[1]],h,Xe)})}function py(i){let e=i.opacity;return e==null||!(e<1)?1:Math.max(.1,Math.round(e*20)/20)}function op(i,e,t,n,r){let s=Ko(t),o=t.outdoor??[];o.forEach((a,l)=>{if(a.points.length<3)return;let c=s+(a.offset??0),u=dy[a.type],h=pl(a.points),f=py(a),d=i;f<1&&n&&r&&(n.has(f)||n.set(f,r()),d=n.get(f));let p={buf:d,lines:e,area:a,poly:h,base:c,groundAt:(x,g)=>c-zh(a,x,g),top:Jr(a.type)&&a.height?a.height:Ll[a.type],look:u,edge:Ue(u.edge,u.edgeAlpha),openEdge:a.open&&(a.type==="fence"||a.type==="pergola")?h.length-1:-1};a.type==="pool"?eR(p):a.type==="fence"?tR(p):a.type==="pergola"?iR(p):rR(p,o,l)})}var my=.012,sR=.012;function oR(){let i=[],e=[],t=[],n=[];return{add(r,s,o,a,l,c,u){for(let h of[r,s,o,r,o,a])i.push(h[0],h[1],h[2]),e.push(l[0],l[1],l[2]),t.push(c),n.push(u)},finish:r=>({pos:new Float32Array(i),normal:new Float32Array(e),room:Int16Array.from(t),fold:new Float32Array(n),doors:r})}}function by(i,e){let[t,n]=[i.b[0]-i.a[0],i.b[1]-i.a[1]],r=Math.hypot(t,n)||1;return Math.abs((e.start[0]-i.a[0])*n-(e.start[1]-i.a[1])*t)/r<.02&&Math.abs((e.axis[0]*t+e.axis[1]*n)/r)>.99}function aR(i,e,t,n){let r=[];for(let s of n.filter(o=>by(i,o))){let o=(s.start[0]-i.a[0])*e[0]+(s.start[1]-i.a[1])*e[1],a=s.axis[0]*e[0]+s.axis[1]*e[1]>0?o:o-s.width;a>t||a+s.width<0||r.push({s0:a,s1:a+s.width,y0:s.sill-.01,y1:s.top+.01})}return r}function gy(i,e,t){let n=[e,t,...i.filter(r=>r>e+.005&&rr-s);return n.filter((r,s)=>s===0||r>n[s-1]+.005)}function xy(i,e,t=()=>!1){let n=i.map(u=>u[0]),r=i.map(u=>u[1]),[s,o]=[Math.min(...n),Math.min(...r)],[a,l]=[Math.max(1,Math.ceil((Math.max(...n)-s)/e)),Math.max(1,Math.ceil((Math.max(...r)-o)/e))],c=[];for(let u=0;ua.add([d,x,p],[d,x,p+r],[d+r,x,p+r],[d+r,x,p],[0,1,0],g,-1);i.rooms.forEach((d,p)=>{if(!(d.points.length<3))for(let{a:x,b:g}of xy(d.points,r,(m,b)=>s.some(v=>Ve([m,b],v))))l(x,g,my,p)});let c=i.rooms.length,u=i.outdoor??[];u.forEach((d,p)=>{if(d.points.length<3||Jr(d.type))return;let x=sp(i,d)+my,g=Hu(u,p);for(let{a:m,b}of xy(d.points,r,(v,y)=>g.some(M=>Ve([v,y],M))))l(m,b,x,c)});let h=Math.min(i.cut_height,i.height);e.forEach((d,p)=>{let x=d.heightEnd===void 0?null:[d.height??i.height,d.heightEnd],g=x?Math.max(...x):d.height??i.height,m=Math.min(h,g-.02),[b,v]=[d.b[0]-d.a[0],d.b[1]-d.a[1]],y=Math.hypot(b,v);if(y<.05)return;let M=[b/y,v/y],S=[-M[1],M[0]],_=t[p],w=aR(d,M,y,n),R=gy([m,(m+g)/2,...w.flatMap(C=>[C.y0+.01,C.y1-.01])],.02,g-.02),A=gy(w.flatMap(C=>[C.s0,C.s1]),0,y);for(let C of[1,-1]){let O=C>0?d.roomLeft:d.roomRight,D=O?i.rooms.findIndex(H=>H.id===O):d.exterior?c:-1;if(D<0)continue;let P=(C>0?d.left:d.right)+sR,I=[S[0]*C,S[1]*C],N=(H,B)=>[d.a[0]+M[0]*H+I[0]*P,B,d.a[1]+M[1]*H+I[1]*P],F=H=>{let B=N(H,0),X=o?.(B[0],B[2]),V=x?x[0]+(x[1]-x[0])*H/y-.02:1/0;return Math.min(V,X==null?1/0:X-.02)};for(let H=0;H+1Se>Te.s0&&SeTe.y0&&le=h-1e-6?_:cr+_)}}}}});let f=[];for(let d of n.filter(p=>p.opening.type==="door")){let p=e.find(m=>by(m,d));if(!p?.roomLeft||!p.roomRight)continue;let[x,g]=[i.rooms.findIndex(m=>m.id===p.roomLeft),i.rooms.findIndex(m=>m.id===p.roomRight)];x<0||g<0||f.push({id:d.opening.id,a:x,b:g,x:d.start[0]+d.axis[0]*(d.width/2),y:Math.min(1.1,d.top*.55),z:d.start[1]+d.axis[1]*(d.width/2)})}return a.finish(f)}function lR(i,e){let t=Math.max(0,-e),n=Math.max(0,e);switch(i){case"ceiling":return .3+.7*t;case"spot":return .06+.94*t**5;case"pendant":return .25+.85*t**2+.2*n;case"up":return .25+.75*n;case"wall":return .45+.35*Math.abs(e);default:return 1}}function cR(i){return(i.kind==="spot"?2:i.kind==="wall"?1.4:2.4)*(.55+.45*i.level)}function yy(i,e,t){let[n,r,s]=[e[0]-i.x,e[1]-i.y,e[2]-i.z],o=n*n+r*r+s*s,a=Math.sqrt(o)||1e-6,l=cR(i),c=1/(1+o/(l*l)),u=c*Math.sqrt(c),h=Math.max(0,-(n*t[0]+r*t[1]+s*t[2])/a);return i.level*u*(.2+.8*h)*lR(i.kind,r/a)}function uR(i,e,t){let n=[];return i.doors.forEach((r,s)=>{let o=t[s]??.5;if(!(o<=.01))for(let[a,l]of[[r.a,r.b],[r.b,r.a]]){let c=[0,0,0];for(let h of e.filter(f=>f.room===a)){let f=[h.x-r.x,h.y-r.y,h.z-r.z],d=Math.hypot(...f)||1,p=yy(h,[r.x,r.y,r.z],[f[0]/d,f[1]/d,f[2]/d]);for(let x=0;x<3;x++)c[x]+=h.color[x]*p}let u=Math.max(...c);u<.01||n.push({x:r.x,y:r.y,z:r.z,color:[c[0]/u,c[1]/u,c[2]/u],level:Math.min(1,u*.9*(.35+.65*o)),kind:"wall",room:l})}}),n}function lp(i,e,t=.7,n=[]){let r=new Map;for(let c of[...e,...uR(i,e,n)]){let u={...c,color:c.color.map(h=>h**1.5)};r.set(c.room,[...r.get(c.room)??[],u])}let{pos:s,normal:o,room:a}=i,l=new Float32Array(s.length);for(let c=0;cr.points.length>=3&&Ve([e,t],r.points));return n<0?i.rooms.length:n}var up=(i,e)=>i&&e>=0&&e45,b=d+Io(s.base,l,s.rise);for(let v of dR)if(s.upright)r.push({x:s.x,y:u+l*(.5+v),z:s.z,color:p,level:x*_y,kind:"omni",room:a});else{let[y,M,S]=zu(s.x,b,s.z,g,l,s.rise,v);r.push({x:y,y:M,z:S,color:p,level:x*_y,kind:m?"omni":f,room:a})}}return r}function My(i,e,t="plain"){return i.onBeforeCompile=n=>{n.uniforms.uStanding=e.standing,n.uniforms.uGlass=e.glass,n.uniforms.uSlope=e.slope??{value:{x:0,y:0,z:0,w:0}},n.uniforms.uSlopeY=e.slopeY??{value:{x:0,y:0}},n.uniforms.uGlassAlpha=e.glassAlpha??{value:.2},n.vertexShader=n.vertexShader.replace("#include ",`#include +attribute float fold; +uniform int uStanding; +uniform int uGlass; +uniform vec4 uSlope; +uniform vec2 uSlopeY; +varying float vNfPaint;`).replace("#include ",`#include + vNfPaint = fold > 127.5 ? 1.0 : 0.0; + if (fold > -0.5 && (uSlope.x != 0.0 || uSlope.y != 0.0) && int(mod(fold, 128.0) + 0.5) / 16 != 4) { + float nfAlong = clamp((dot(transformed.xz, uSlope.xy) - uSlope.z) / max(uSlope.w - uSlope.z, 0.001), 0.0, 1.0); + transformed.y = min(transformed.y, mix(uSlopeY.x, uSlopeY.y, nfAlong)); + }`).replace("#include ",`#include + { + bool nfShow = ${t==="glass"?"false":"true"}; + if (fold > -0.5) { + int nfFold = int(mod(fold, 128.0) + 0.5); + int nfKind = nfFold / 16; + int nfBucket = nfFold - nfKind * 16; + bool nfStanding = ((uStanding >> nfBucket) & 1) == 1; + bool nfGlass = ((uGlass >> nfBucket) & 1) == 1; + // kinds: 0 upper part, 1 cut edge, 2 lower part, 3 cap at the cut height, 4 furniture above the cut + nfShow = nfKind == 0 || nfKind == 4 ? nfStanding : nfKind == 1 || nfKind == 3 ? !nfStanding : true; + bool nfWall = nfKind == 0 || nfKind == 2; + ${t==="solid"?"if (nfGlass && nfWall) nfShow = false;":""} + ${t==="glass"?"nfShow = nfShow && nfGlass && nfWall;":""} + } + if (!nfShow) gl_Position = vec4(2.0, 2.0, 2.0, 1.0); + }`),n.fragmentShader=n.fragmentShader.replace("#include ",`#include +varying float vNfPaint; +uniform float uGlassAlpha;`),t!=="glass"&&(n.fragmentShader=n.fragmentShader.replace("#include ",`#include + #ifdef USE_COLOR + if (vNfPaint > 0.5) diffuseColor.rgb = vColor.rgb; + #endif`)),t==="glass"&&(n.fragmentShader=n.fragmentShader.replace("#include ",`#include + diffuseColor.rgb = diffuseColor.rgb * 1.7 + vec3(0.015, 0.05, 0.075); + diffuseColor.a *= uGlassAlpha;`))},i.customProgramCacheKey=()=>`nf-fold-${t}`,i}var hp=["neon","blueprint","day"],eN=["auto",...hp];var Sy=i=>hp.indexOf(i),Xu={value:new U(.22,.88,1)},Yu={value:0};function wy(i){let e=/^#?([0-9a-f]{6})$/i.exec(i?.trim()??"");if(!e)return null;let t=Number.parseInt(e[1],16);return[(t>>16&255)/255,(t>>8&255)/255,(t&255)/255]}var pR=` +uniform int uTheme; +uniform vec3 uAccent; +uniform int uAccentOn; +vec3 nfThemed(vec3 c, bool isLine) { + float strongest = max(c.r, max(c.g, c.b)); + float weakest = min(c.r, min(c.g, c.b)); + float saturation = strongest > 0.0 ? (strongest - weakest) / strongest : 0.0; + if (uTheme == 0) { + // an own accent: every line and every cyan surface takes it, as bright as it was + bool cyanish = saturation > 0.35 && c.r < c.g * 0.8 && c.b > c.g * 0.85 && c.g > c.b * 0.6; + if (uAccentOn == 1 && (isLine || cyanish)) return uAccent * strongest; + return c; + } + // signal colours keep their colour + if (!isLine && strongest > 0.45 && saturation > 0.45) return c; + float luma = dot(c, vec3(0.299, 0.587, 0.114)); + if (uTheme == 1) { + // blueprint: pale lines on shades of blue + if (isLine) return vec3(0.8, 0.9, 1.0) * min(1.0, strongest * 1.15); + return mix(vec3(0.04, 0.13, 0.3), vec3(0.2, 0.42, 0.75), clamp(luma * 5.0, 0.0, 1.0)); + } + // day: light surfaces with a trace of their hue, dark blue lines + if (isLine) return vec3(0.08, 0.17, 0.38) * clamp(strongest * 1.4, 0.4, 1.0); + vec3 grey = vec3(clamp(0.66 + luma * 2.6, 0.0, 0.96)); + return mix(grey, grey * (c / max(strongest, 0.001)), 0.1); +} +`;function Zn(i,e,t=!1){let n=i.onBeforeCompile.bind(i),r=i.customProgramCacheKey.bind(i);return i.onBeforeCompile=(s,o)=>{n(s,o),Object.assign(s.uniforms,{uTheme:e,uAccent:Xu,uAccentOn:Yu}),s.fragmentShader=s.fragmentShader.replace("#include ",`#include +${pR}`).replace("#include ",`#include + diffuseColor.rgb = nfThemed(diffuseColor.rgb, ${t});`)},i.customProgramCacheKey=()=>`${r()}-themed-${t?"l":"s"}`,i}var xl=i=>i==="day"?Ai:Ft;var mR=`#include +attribute vec2 tile; +varying vec2 vNfTile;`,gR=`#include +vNfTile = tile;`,xR=`#ifdef USE_MAP + vec2 nfCell = fract(vMapUv); + vec2 nfUv = (vNfTile + 0.004 + nfCell * 0.992) / vec2(3.0, 2.0); + // gradients of the unwrapped coordinates avoid mip seams at the tile borders + vec4 sampledDiffuseColor = textureGrad(map, nfUv, dFdx(vMapUv) / vec2(3.0, 2.0), dFdy(vMapUv) / vec2(3.0, 2.0)); + diffuseColor *= sampledDiffuseColor; + #endif`;function bR(i){let e=new Ke({map:i,transparent:!0,blending:Ft,depthWrite:!1,polygonOffset:!0,polygonOffsetFactor:-2});return e.onBeforeCompile=t=>{t.vertexShader=t.vertexShader.replace("#include ",mR).replace("#include ",gR),t.fragmentShader=t.fragmentShader.replace("#include ",`#include +varying vec2 vNfTile;`).replace("#include ",xR)},e.customProgramCacheKey=()=>"nf-pattern",e}var qu=(i={})=>new Ke({vertexColors:!0,transparent:!0,blending:Ft,depthWrite:!1,...i});function Ty({mask:i,look:e,theme:t,textures:n}){let r=(o={})=>new Ke({vertexColors:!0,...o}),s=(o,a)=>My(o,i,a);return{floor:Zn(r(),e),pattern:bR(n.pattern),wall:Zn(s(r(),"solid"),e),glassWall:s(r({transparent:!0,depthWrite:!1}),"glass"),shadow:r({blending:za,premultipliedAlpha:!0,transparent:!0,depthWrite:!1,side:ut,polygonOffset:!0,polygonOffsetFactor:-1}),lines:Zn(s(new Lt({vertexColors:!0,transparent:!0,blending:xl(t),depthWrite:!1})),e,!0),glow:s(qu({side:ut,polygonOffset:!0,polygonOffsetFactor:-3}),"solid"),frames:Zn(s(r({side:ut})),e),glass:s(qu({side:ut})),blinds:Zn(s(r({map:n.blinds,side:ut})),e),lamps:Zn(r(),e),halos:new cn({map:n.halo,size:.9,sizeAttenuation:!0,vertexColors:!0,transparent:!0,blending:Ft,depthWrite:!1}),cones:qu({side:ut}),screens:qu({side:ut}),ghosts:[]}}var $u=i=>Object.assign(document.createElement("span"),{className:i});function Ay(i,e){let t=Object.assign(document.createElement("button"),{className:"nf-dev"});t.dataset.entity=i,t.append($u("nf-dev-icon"),$u("nf-dev-text"),$u("nf-dev-watt"),$u("nf-dev-name"));let n,r=!1,s=a=>{let{x:l,y:c}=e.centre(t);a(i,l,c)},o=()=>clearTimeout(n);t.addEventListener("pointerdown",a=>{if(e.furnishing())return e.pressedWhileFurnishing(i);a.stopPropagation(),r=!1,o(),n=setTimeout(()=>{r=!0,s(e.hold)},500)});for(let a of["pointerleave","pointercancel","pointerup"])t.addEventListener(a,o);return t.addEventListener("contextmenu",a=>a.preventDefault()),t.addEventListener("click",a=>{if(a.stopPropagation(),e.furnishing())return e.selectWhileFurnishing(i);r||s(e.tap)}),t.addEventListener("keydown",a=>{(a.key==="Enter"&&a.shiftKey||a.key==="ContextMenu")&&(a.preventDefault(),s(e.hold))}),t}function Ey(i,e=10,t="NextFloor"){let n=[];for(let{positions:o,lift:a}of i)for(let l=0;l+8[o[l+x]*e,-o[l+x+2]*e,(o[l+x+1]+a)*e]),[u,h,f]=c,d=[(h[1]-u[1])*(f[2]-u[2])-(h[2]-u[2])*(f[1]-u[1]),(h[2]-u[2])*(f[0]-u[0])-(h[0]-u[0])*(f[2]-u[2]),(h[0]-u[0])*(f[1]-u[1])-(h[1]-u[1])*(f[0]-u[0])],p=Math.hypot(d[0],d[1],d[2]);p<1e-9||n.push([d[0]/p,d[1]/p,d[2]/p,...u,...h,...f])}let r=new Uint8Array(84+n.length*50),s=new DataView(r.buffer);return r.set(new TextEncoder().encode(`${t} STL`.slice(0,79)),0),s.setUint32(80,n.length,!0),n.forEach((o,a)=>{let l=84+a*50;o.forEach((c,u)=>s.setFloat32(l+u*4,c,!0))}),r}var Rs=Math.PI/180;function Ry(i,e,t){let n=i.getTime()/864e5-10957.5,r=(357.529+.98560028*n)*Rs,o=(280.459+.98564736*n+1.915*Math.sin(r)+.02*Math.sin(2*r))*Rs,a=(23.439-36e-8*n)*Rs,l=Math.atan2(Math.cos(a)*Math.sin(o),Math.cos(o)),c=Math.asin(Math.sin(a)*Math.sin(o)),h=(((18.697374558+24.06570982441908*n)%24+24)%24*15+t)*Rs-l,f=e*Rs,d=Math.asin(Math.sin(f)*Math.sin(c)+Math.cos(f)*Math.cos(c)*Math.cos(h)),p=Math.atan2(Math.sin(h),Math.cos(h)*Math.sin(f)-Math.tan(c)*Math.cos(f))/Rs+180;return{elevation:d/Rs,azimuth:(p%360+360)%360}}function fp(i,e){let t=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}).formatToParts(new Date(i)).map(n=>[n.type,Number(n.value)]));return Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second)}function Cy(i,e,t=new Date){let[n,r]=[Math.floor(i),Math.round(i%1*60)];if(e)try{let o=new Date(fp(t.getTime(),e)),a=Date.UTC(o.getUTCFullYear(),o.getUTCMonth(),o.getUTCDate(),n,r),l=a-(fp(a,e)-a);return l=a-(fp(l,e)-l),new Date(l)}catch{}let s=new Date(t);return s.setHours(n,r,0,0),s}function yR(i,e=new Date){let t=[];for(let n=0;n<=24;n+=.25){let r=Ry(Cy(Math.min(n,23.99),i.zone,e),i.latitude,i.longitude);r.elevation<0||t.push(Py(i,r))}return t}function Py(i,e){let[t,n]=Lo(e.azimuth,i.north),r=Math.max(0,e.elevation)*Math.PI/180;return[i.centre[0]+t*i.radius*Math.cos(r),Math.sin(r)*i.radius*.9,i.centre[1]+n*i.radius*Math.cos(r)]}function _R(i,e){let t=document.createElement("canvas");t.width=t.height=64;let n=t.getContext("2d");n&&(n.font="bold 44px system-ui, sans-serif",n.fillStyle=e,n.textAlign="center",n.textBaseline="middle",n.fillText(i,32,34));let r=new ji(new vi({map:new zt(t),transparent:!0,depthWrite:!1,depthTest:!1}));return r.renderOrder=20,r}var Ku=class{group=new ct;key="";constructor(){this.group.visible=!1,this.group.renderOrder=15}update(e,t,n){let r=e?`${e.centre},${e.radius.toFixed(1)},${e.north},${e.latitude.toFixed(2)},${e.longitude.toFixed(2)},${new Date().toDateString()},${n},${t?`${t.elevation.toFixed(0)},${t.azimuth.toFixed(0)}`:"-"}`:"off";if(r===this.key)return;if(this.key=r,this.clear(),!e){this.group.visible=!1;return}this.group.visible=!0;let s=n+.05,o=[];for(let h=0;h<=96;h++){let f=h/96*Math.PI*2;o.push(e.centre[0]+Math.cos(f)*e.radius,s,e.centre[1]+Math.sin(f)*e.radius)}let a=new Fe;a.setAttribute("position",new ke(o,3)),this.group.add(new Pn(a,new Lt({color:7311304,transparent:!0,opacity:.55,depthWrite:!1})));let l=[];[["N",0],["E",90],["S",180],["W",270]].forEach(([h,f])=>{let[d,p]=Lo(f,e.north);l.push(e.centre[0]+d*e.radius*.94,s,e.centre[1]+p*e.radius*.94,e.centre[0]+d*e.radius*1.04,s,e.centre[1]+p*e.radius*1.04);let x=_R(h,h==="N"?"#ff6b6b":"#9fb4d8");x.position.set(e.centre[0]+d*e.radius*1.12,s+.4,e.centre[1]+p*e.radius*1.12),x.scale.setScalar(Math.max(1.2,e.radius*.12)),this.group.add(x)});let c=new Fe;c.setAttribute("position",new ke(l,3)),this.group.add(new gn(c,new Lt({color:10466520,transparent:!0,opacity:.8,depthWrite:!1})));let u=yR(e).map(([h,f,d])=>[h,n+f,d]);if(u.length>1){let h=new Fe;h.setAttribute("position",new ke(u.flat(),3)),this.group.add(new Pn(h,new Lt({color:16761415,transparent:!0,opacity:.85,depthWrite:!1})))}if(t&&t.elevation>0){let[h,f,d]=Py(e,t),p=new we(new Ca(Math.max(.35,e.radius*.035),12,8),new Ke({color:16765530}));p.position.set(h,n+f,d),this.group.add(p)}}clear(){for(let e of[...this.group.children]){this.group.remove(e);let t=e;t.geometry?.dispose();let n=t.material;n?.map?.dispose(),n?.dispose()}}dispose(){this.clear()}};var vR=["straight","quarter","l","half","u","spiral"],MR=["solid","stringer","mono","cantilever"],SR=["none","left","right","both"],wR=["headroom","full","none"],Zu={shape:"straight",turn:"right",build:"solid",risers:!0,steps:null,run_width:null,down:!1,rail:"none",opening:"headroom",landing_after:null};var Ny=2,Dy=40,TR=2.2,Ju=(i,e)=>typeof e=="string"&&i.includes(e);function dp(i){let e=i.stair??{},t=typeof e.steps=="number"&&Number.isFinite(e.steps)?Math.round(Math.min(Dy,Math.max(Ny,e.steps))):null,n=typeof e.run_width=="number"&&Number.isFinite(e.run_width)&&e.run_width>.2?e.run_width:null;return{shape:Ju(vR,e.shape)?e.shape:Zu.shape,turn:e.turn==="left"?"left":"right",build:Ju(MR,e.build)?e.build:Zu.build,risers:e.risers!==!1,steps:t,run_width:n,down:e.down===!0,rail:Ju(SR,e.rail)?e.rail:Zu.rail,opening:Ju(wR,e.opening)?e.opening:Zu.opening,landing_after:typeof e.landing_after=="number"&&Number.isFinite(e.landing_after)?Math.max(1,Math.round(e.landing_after)):null}}var Qu=i=>i.type==="stairs"&&!!i.stair,yl=(i,e,t)=>[i[0]+(e[0]-i[0])*t,i[1]+(e[1]-i[1])*t],Iy=(i,e)=>Math.abs(i[0]-e[0])<1e-6&&Math.abs(i[1]-e[1])<1e-6;function Uy(i){let e=[];for(let t of i)(!e.length||!Iy(e[e.length-1],t))&&e.push(t);for(;e.length>1&&Iy(e[0],e[e.length-1]);)e.pop();return e}function _l(i,e,t=!1){return{poly:Uy([...i,...[...e].reverse()]),landing:t,left:i,right:e}}function bl(i,e,t,n,r){let s=[];for(let o=0;oe+1e-6&&ri.reduce((e,t,n)=>n?e+Math.hypot(t[0]-i[n-1][0],t[1]-i[n-1][1]):e,0);function Fy(i,e,t,n,r){let s=ER(i),o=[];for(let a=0;a=8?3:2),[f,d]=i.shape==="l"?Oy(i,n)??ju(n-h,t-l,e-l):ju(n-h,t-l,e-l),p=bl([r,a],[r+l,a],[r,o+l],c,f),x=i.shape==="l"?[_l(u,[c],!0)]:Fy(u,c,c,c,h),g=bl([r+l,o],c,[s,o],[s,o+l],d);return{treads:[...p,...x,...g],flight:l,column:0}}case"half":case"u":{let l=Math.min(i.run_width??Math.min(1.1,(e-.1)/2),(e-.02)/2),c=o+l,u=[[r,c],[r,o],[s,o],[s,c]],[h,f]=[[r+l,c],[s-l,c]],d=i.shape==="u"?1:Math.min(n,n>=12?6:n>=8?4:2),[p,x]=i.shape==="u"?Oy(i,n)??ju(n-d,t-l,t-l):ju(n-d,t-l,t-l),g=bl([r,a],[r+l,a],[r,c],h,p),m=i.shape==="u"?[_l(u,[h,f],!0)]:Fy(u,h,[0,c],f,d),b=bl([s,c],f,[s,a],[s-l,a],x);return{treads:[...g,...m,...b],flight:l,column:0}}case"spiral":{let l=Math.min(e,t)/2,c=Math.min(.08,l*.12),u=Math.min(.75,Math.max(.3,.22/(l*.6))),h=(d,p)=>[Math.cos(p)*d,Math.sin(p)*d],f=[];for(let d=0;dh(l,p+(x-p)*m));f.push(_l(g,[h(c,p),h(c,x)]))}return{treads:f,flight:l-c,column:c}}default:return{treads:bl([r,a],[s,a],[r,o],[s,o],n),flight:e,column:0}}}var CR=(i,e)=>i.steps??Math.min(Dy,Math.max(Ny,Math.round(Math.abs(e)/.18)));function pp(i,e,t,n){let r=CR(i,n),s=Math.abs(n)/r,o=RR(i,Math.max(.3,e),Math.max(.3,t),r),a=c=>[-c[0],c[1]];return{treads:o.treads.map((c,u)=>{let h=i.down?-s*(u+1):s*(u+1);return i.turn==="right"?{...c,top:h}:{poly:c.poly.map(a).reverse(),top:h,landing:c.landing,left:c.right.map(a),right:c.left.map(a)}}),rise:s,steps:r,column:o.column,flight:o.flight}}function By(i){let e=i.poly.reduce((t,n)=>[t[0]+n[0],t[1]+n[1]],[0,0]);return[e[0]/i.poly.length,e[1]/i.poly.length]}function PR(i,e,t,n="headroom"){if(n==="none")return[];let r=t?0:Math.abs(e),s=n==="full"?i.treads:i.treads.filter((o,a)=>o.top>r-TR||!t&&a===i.treads.length-1||t&&a===0);return fr(s.map(o=>o.poly).filter(o=>o.length>=3))}function mp(i){let e=dp(i),t=PR(pp(e,i.w,i.d,i.h),i.h,e.down,e.opening),n=i.rotation*Math.PI/180,[r,s]=[Math.cos(n),Math.sin(n)],o=i.mirror?-1:1;return t.map(a=>a.map(([l,c])=>[i.x+o*l*r-c*s,i.z+o*l*s+c*r]))}function Ni(i,e,t,n,r,s,o=Pe.metal,a=!1){let[l,c]=[e/2-s-r,t/2-s-r],u=mt(o);for(let h of[-1,1])for(let f of[-1,1]){let[d,p]=[h*l,f*c];a?i.loft([d-r*.3,d+r*.3,p-r*.3,p+r*.3],[d-r/2,d+r/2,p-r/2,p+r/2],0,n,u):i.block({x:[d-r/2,d+r/2],y:[0,n],z:[p-r/2,p+r/2]},u)}}function Cs(i,e,t,n,r,s,o,a=null,l=!1){let c=(t-e)/o;for(let u=1;u1?h+(u%2?-c/2+.06:c/2-.06):h+c/2-.06;i.seg(d,f-.08,s+.012,d,f+.08,s+.012,qe)}}}function fi(i,e,t,n,r,s=null,o=!1,a=Z.body){i.block({x:[-e/2,e/2],y:[.02,n],z:[-t/2,t/2-.02]},a,pe),i.block({x:[-e/2+.02,e/2-.02],y:[0,.08],z:[-t/2+.02,t/2-.06]},mt(Pe.dark)),Cs(i,-e/2,e/2,.08,n,t/2-.02,r,s,o)}function gp(i,e,t,n,r){let[s,o,a,l]=[-e/2,e/2,-t/2,t/2],c=Math.min(.2,e*.12),u=n*.5,h=Math.min(.24,t*.28);Ni(i,e,t,.07,.05,.05,Pe.wood,!0),i.pad({x:[s,o],y:[.07,u-.08],z:[a+.02,l]},Z.fabric,.04,pe),i.loft([s,o,a,a+h],[s+.01,o-.01,a,a+h*.5],u-.08,n,Z.fabric,pe);for(let[d,p]of[[s,s+c],[o-c,o]])i.pad({x:[d,p],y:[u-.08,n*.72],z:[a+.02,l-.02]},Z.fabric,.04,pe);let f=(o-c-(s+c))/r;for(let d=0;d1.2?2:1,f=(e-.2)/h;for(let d=0;d0?.05:0),o*(e/2)+(o<0?.05:0)],y:[0,n],z:[a*(t/2)-(a>0?.05:0),a*(t/2)+(a<0?.05:0)]},Z.wood);for(let o of[.25,n-.55])i.block({x:[-e/2,e/2],y:[o,o+.08],z:[-t/2,t/2]},Z.wood,pe),i.block({x:[-e/2+.04,e/2-.04],y:[o+.08,o+.24],z:[-t/2+.05,t/2-.05]},Z.bedding,Je),i.block({x:[-e/2+.05,e/2-.05],y:[o+.24,o+.33],z:[-t/2+.08,-t/2+.4]},Z.pillow);i.block({x:[-e/2,e/2],y:[n-.2,n-.15],z:[t/2-.05,t/2]},Z.wood);let s=e/2-.35;for(let o of[s-.18,s+.18])i.seg(o,0,t/2+.02,o,n-.15,t/2+.02,pe);for(let o=.3;oi.block({x:[-e/2,e/2],y:[n-.04,n],z:[-t/2,t/2]},Z.worktop,pe);function Yy(i,e,t,n){fi(i,e,t-.02,n-.04,Math.max(1,Math.round(e/.6)),n-.2),yp(i,e,t,n)}function qy(i,e,t,n){i.block({x:[-e/2,e/2],y:[Math.max(0,n-.04),n],z:[-t/2,t/2]},Z.worktop,pe)}function $y(i,e,t,n){i.block({x:[-e/2,e/2],y:[0,n],z:[-t/2,t/2]},Z.white,pe);let r=n*.62;i.seg(-e/2,r,t/2,e/2,r,t/2,Je);let s=e/2-.06;i.seg(s,r+.08,t/2+.015,s,r+.4,t/2+.015,qe),i.seg(s,r-.4,t/2+.015,s,r-.08,t/2+.015,qe)}var _p=.06;function Ky(i,e,t,n){let r=t/2-_p;i.block({x:[-e/2,e/2],y:[.02,n],z:[-t/2,r]},Z.body,pe),i.block({x:[-e/2+.05,e/2-.05],y:[0,.02],z:[-t/2+.05,r-.05]},Z.dark);for(let s of[.35,.7,1.05,1.4])s>n-.15||(i.seg(-e/2+.03,s,r+.001,-.03,s,r+.001,Je),i.seg(.03,s,r+.001,e/2-.03,s,r+.001,Je))}var bp=1.83;function IR(i,e,t,n,r){let[s,o]=[Math.cos(e.rotation*pt),Math.sin(e.rotation*pt)],a=e.mirror?-1:1,l=(b,v)=>[e.x+a*b*s-v*o,e.z+a*b*o+v*s],[c,u]=[t+.05,t+e.h-.02],h=new W(.75,.1,.14),f=new W(Pe.dark),d=new W(Pe.accent),p=e.w/2-.006,x=(b,v,y)=>{let M=y/bp,S=new W(2043212).lerp(h,M),_=new W(Pe.body).lerp(h,M*.8),[w,R]=[Math.cos(y),Math.sin(y)],A=(D,P)=>l(b+v*(D*w-P*R),e.d/2+D*R+P*w),C=(D,P,I,N)=>{let[F,H,B,X]=D;i.tri([F[0],P,F[1]],[H[0],P,H[1]],[B[0],I,B[1]],N),i.tri([F[0],P,F[1]],[B[0],I,B[1]],[X[0],I,X[1]],N)},O=(D,P,I,N,F,H,B,X=B)=>{let V=[A(D,H),A(P,H),A(P,F),A(D,F)];C([V[0],V[1],V[1],V[0]],I,N,X),C([V[3],V[2],V[2],V[3]],I,N,B),C([V[0],V[3],V[3],V[0]],I,N,B),C([V[1],V[2],V[2],V[1]],I,N,B),C([V[0],V[1],V[2],V[3]],N,N,B),C([V[3],V[2],V[1],V[0]],I,I,B)};return O(0,p,c,u,-_p,0,_,S),O(p-.05,p-.03,t+e.h*.45,t+e.h*.75,.005,.025,d),O};x(-e.w/2,1,n*bp)(.12,.3,t+e.h*.5,t+e.h*.68,.001,.005,f),x(e.w/2,-1,r*bp)(.06,p-.06,t+e.h*.52,t+e.h*.86,.001,.005,f)}function vp(i,e,t,n,r){let s=i.p.length;IR(i,e,t,n,r),e.mirror&&vs(i,s)}function Zy(i,e,t,n){fi(i,e,t-.02,n-.04,1,n-.24,!0),i.block({x:[-e/2,e/2],y:[n-.04,n],z:[-t/2,t/2]},Z.dark,pe);let r=[[-.14,-.13,.09],[.14,-.13,.07],[-.14,.13,.07],[.14,.13,.09]];for(let[s,o,a]of r)i.cylinder(s*e/.6,o*t/.62,a,n,n+.004,mt(Pe.dark,1451583),12,qe)}function Jy(i,e,t,n){fi(i,e,t-.02,n-.04,Math.max(1,Math.round(e/.45)),n-.2);let r=Math.min(.5,e-.2),s=(o,a,l,c,u=!1)=>i.block({x:[o,a],y:[n-.04,n],z:[l,c]},Z.worktop,u?pe:null);s(-e/2,-r/2,-t/2,t/2,!0),s(r/2,e/2,-t/2,t/2,!0),s(-r/2,r/2,-t/2,-t/2+.1),s(-r/2,r/2,t/2-.08,t/2),i.block({x:[-r/2,r/2],y:[n-.2,n-.17],z:[-t/2+.1,t/2-.08]},Z.metal,qe),i.cylinder(0,-t/2+.05,.02,n,n+.28,Z.metal,8),i.block({x:[-.015,.015],y:[n+.24,n+.28],z:[-t/2+.05,-t/2+.22]},Z.metal)}function jy(i,e,t,n){i.block({x:[-e/2,e/2],y:[1.45,1.45+n],z:[-t/2,t/2-.02]},Z.body,pe),Cs(i,-e/2,e/2,1.45,1.45+n,t/2-.02,Math.max(1,Math.round(e/.5)),1.45+.08)}function Qy(i,e,t,n){i.block({x:[-e/2,e/2],y:[.02,n],z:[-t/2,t/2-.02]},Z.body,pe),i.block({x:[-e/2+.02,e/2-.02],y:[0,.08],z:[-t/2+.02,t/2-.06]},Z.dark);let r=t/2-.02;i.block({x:[-e/2+.03,e/2-.03],y:[.85,1.45],z:[r,r+.01]},Z.dark,qe),i.seg(-e/2+.08,1.4,r+.02,e/2-.08,1.4,r+.02,qe);for(let s of[.85,1.45])i.seg(-e/2,s,r,e/2,s,r,Je);i.seg(e/2-.06,.5,r+.012,e/2-.06,.7,r+.012,qe),i.seg(e/2-.06,1.6,r+.012,e/2-.06,1.8,r+.012,qe)}function e_(i,e,t,n){let r=t-.3;i.block({x:[-e/2+.05,e/2-.05],y:[.08,n-.04],z:[-t/2+.02,-t/2+r]},Z.body,pe),i.block({x:[-e/2+.07,e/2-.07],y:[0,.08],z:[-t/2+.04,-t/2+r-.04]},Z.dark),Cs(i,-e/2+.05,e/2-.05,.08,n-.04,-t/2+r,Math.max(2,Math.round(e/.6)),n-.2),yp(i,e,t,n)}function t_(i,e,t,n){i.block({x:[-e/2,e/2],y:[.02,n-.04],z:[-t/2,t/2-.02]},Z.body,pe),i.block({x:[-e/2+.02,e/2-.02],y:[0,.08],z:[-t/2+.02,t/2-.06]},Z.dark),i.seg(-e/2+.08,n-.12,t/2-.008,e/2-.08,n-.12,t/2-.008,qe),yp(i,e,t,n)}function Mp(i,e,t,n,r){i.block({x:[-e/2,e/2],y:[0,n],z:[-t/2,t/2-.02]},Z.white,pe);let s=t/2-.012;i.seg(-e/2,n-.14,s,e/2,n-.14,s,Je),i.seg(e/2-.16,n-.07,s,e/2-.08,n-.07,s,qe);let o=(n-.14)/2+.04,a=Math.min(e*.36,(n-.2)*.42),l=20;for(let c=0;ci.seg(Math.cos(u)*a*d,o+Math.sin(u)*a*d,s,Math.cos(h)*a*d,o+Math.sin(h)*a*d,s,p);f(1,qe),r||f(.72,Je)}}function n_(i,e,t,n){i.block({x:[-e/2,e/2],y:[0,n-.02],z:[-t/2,t/2]},Z.white,pe);let s=(o,a,l,c)=>i.block({x:[o,a],y:[n-.02,n],z:[l,c]},Z.worktop);s(-e/2,e/2,-t/2,-t/2+.07),s(-e/2,e/2,t/2-.07,t/2),s(-e/2,-e/2+.07,-t/2+.07,t/2-.07),s(e/2-.07,e/2,-t/2+.07,t/2-.07),i.block({x:[-e/2+.07,e/2-.07],y:[n-.03,n-.02],z:[-t/2+.07,t/2-.07]},Z.glass,qe),i.cylinder(-e/2+.04,0,.02,n,n+.12,Z.metal,8)}function i_(i,e,t,n){i.block({x:[-e/2,e/2],y:[0,.05],z:[-t/2,t/2]},Z.worktop,pe),i.cylinder(0,0,.04,.05,.052,Z.metal,8);for(let[r,s,o,a]of[[-e/2,t/2,e/2,t/2],[e/2,-t/2,e/2,t/2]])i.seg(r,.05,s,o,.05,a,qe),i.seg(r,n,s,o,n,a,qe),i.seg(o,.05,a,o,n,a,qe);i.cylinder(-e/2+.06,-t/2+.06,.015,.05,n-.05,Z.metal,6),i.cylinder(-e/2+.2,-t/2+.2,.1,n-.08,n-.06,Z.metal,12,qe)}function r_(i,e,t,n){let r=Math.min(.18,t*.3);i.block({x:[-e/2,e/2],y:[.45,n],z:[-t/2,-t/2+r]},Z.white,pe),i.block({x:[-e*.3,e*.3],y:[0,.36],z:[-t/2+r-.02,t/2-.12]},Z.white),i.cylinder(0,t/2-.26,Math.min(e/2,.19),.36,.41,Z.white,12,pe),i.block({x:[-e/2+.02,e/2-.02],y:[.41,.43],z:[-t/2+r,-t/2+r+.05]},Z.worktop)}function s_(i,e,t,n){fi(i,e,t-.02,n-.12,e>.8?2:1,n-.3),i.block({x:[-e/2,e/2],y:[n-.12,n],z:[-t/2,t/2]},Z.white,pe),i.block({x:[-e/2+.07,e/2-.07],y:[n-.005,n],z:[-t/2+.12,t/2-.06]},Z.glass,qe),i.cylinder(0,-t/2+.06,.018,n,n+.2,Z.metal,8),i.block({x:[-e/2+.04,e/2-.04],y:[n+.35,n+1],z:[-t/2,-t/2+.02]},Z.glass,qe)}var vl=.12;function o_(i,e,t,n){let r=vl;i.block({x:[-e/2+.05,-e/2+.08],y:[0,r],z:[-t/2,-t/2+.03]},Z.metal),i.block({x:[e/2-.08,e/2-.05],y:[0,r],z:[-t/2,-t/2+.03]},Z.metal),i.block({x:[-e/2,e/2],y:[r,r+n],z:[-t/2+.02,t/2]},Z.white,pe);let s=Math.max(3,Math.round(e/.1));for(let o=1;oi.block({x:[-e/2,e/2],y:[1.1,1.1+n],z:[-t/2,t/2]},l,pe);if(r==="slim"){a(Z.darkBody),i.seg(-e*.25,1.1+n*.15,o+.004,-e*.25,1.1+n*.85,o+.004,qe),i.block({x:[-e*.1,e*.3],y:[1.1+n*.7,1.1+n*.85],z:[o,o+.005]},Z.dark);return}if(a(Z.white),r==="hybrid"){i.ring(0,1.1+n*.66,Math.min(e,n)*.22,o+.004,20,qe),i.seg(-e*.08,1.1+n*.66,o+.005,e*.08,1.1+n*.66,o+.005,qe);for(let l of[-1,1])i.ring(l*e*.22,1.1+n*.2,Math.min(e,n)*.1,-t/2-.002,12,qe);return}i.block({x:[-e*.28,e*.28],y:[1.1+n*.58,1.1+n*.82],z:[t/2,t/2+.006]},Z.dark),i.seg(-e*.3,1.1+n*.45,t/2+.004,e*.3,1.1+n*.45,t/2+.004,qe);for(let l of[-1,1])for(let c=1;c<6;c++)i.seg(l*e/2+l*.002,1.1+n*c/6,-t/2+.03,l*e/2+l*.002,1.1+n*c/6,t/2-.03,Je)}function M_(i,e,t,n){i.block({x:[-e/2,e/2],y:[0,n],z:[-t/2,t/2]},Z.darkBody,pe),i.block({x:[-e/2-.01,e/2+.01],y:[n,n+.03],z:[-t/2-.01,t/2+.01]},Z.darkBody),i.seg(-e/2,n+.032,t/2+.01,e/2,n+.032,t/2+.01,qe),i.seg(-e*.3,n*.55,t/2+.003,e*.3,n*.55,t/2+.003,Je)}function S_(i,e,t,n){i.block({x:[-e/2,e/2],y:[1,1+n],z:[-t/2,t/2]},Z.darkBody,pe),i.ring(0,1+n*.58,Math.min(e,n)*.28,t/2+.003,16,qe),i.block({x:[-.015,.015],y:[1-.35,1],z:[t/2-.03,t/2]},Z.dark),i.block({x:[-.06,.06],y:[1-.42,1-.35],z:[t/2-.05,t/2]},Z.darkBody)}function w_(i,e,t,n){i.block({x:[-e/2,e/2],y:[.4,.4+n],z:[-t/2,t/2]},Z.white,pe),i.seg(-e/2+.025,.4+.025,t/2+.003,-e/2+.025,.4+n-.025,t/2+.003,Je),i.seg(-e/2+.025,.4+n-.025,t/2+.003,e/2-.025,.4+n-.025,t/2+.003,Je),i.block({x:[e/2-.06,e/2-.035],y:[.4+n*.5-.05,.4+n*.5+.05],z:[t/2,t/2+.012]},Z.dark),i.block({x:[-e*.3,e*.3],y:[.4+n*.6,.4+n*.8],z:[t/2,t/2+.005]},Z.dark),i.seg(-e*.22,.4+n*.7,t/2+.008,e*.22,.4+n*.7,t/2+.008,qe)}function T_(i,e,t,n,r){if(r==="wall"){i.block({x:[-e/2,e/2],y:[.5,.5+n],z:[-t/2,t/2]},Z.white,pe),i.seg(-e*.3,.5+n*.9,t/2+.004,e*.3,.5+n*.9,t/2+.004,qe),i.seg(-e*.3,.5+n*.08,t/2+.003,e*.3,.5+n*.08,t/2+.003,Je);return}if(r==="cube"){i.block({x:[-e/2+.01,e/2-.01],y:[0,.03],z:[-t/2+.01,t/2-.01]},Z.dark),i.block({x:[-e/2,e/2],y:[.03,n],z:[-t/2,t/2]},Z.darkBody,pe),i.seg(-e*.35,n*.85,t/2+.004,e*.35,n*.85,t/2+.004,qe),i.block({x:[-e*.15,e*.15],y:[n,n+.025],z:[-.012,.012]},Z.dark);return}i.block({x:[-e/2+.02,e/2-.02],y:[0,.06],z:[-t/2+.02,t/2-.02]},Z.dark);let s=Math.max(2,Math.round((n-.06)/.3)),o=(n-.06)/s;for(let a=0;a[x[0]+h*g,x[1]+f*g];i.prism([e,t,p(t,o),p(e,o)],r,s,a,Je)}var LR=i=>i.slice(1).map((e,t)=>[i[t],e]).filter(([e,t])=>Math.hypot(t[0]-e[0],t[1]-e[1])>.01);function FR(i,e,t,n,r){let s=e.build==="cantilever"?.07:.05;t.forEach((o,a)=>{let l=By(o),c=a===0?0:t[a-1].top;if(e.build==="solid"){i.prism(o.poly,Math.min(r,o.top),o.top,Z.body,pe);return}if(i.prism(o.poly,o.top-s,o.top,Z.wood,pe),e.risers&&!o.landing){let[u,h]=[Math.min(c,o.top),Math.max(c,o.top)-s];A_(i,o.left[0],o.right[0],l,u,h,.02)}if(e.build==="stringer")for(let u of[o.left,o.right])for(let[h,f]of LR(u))A_(i,h,f,l,o.top-n-.2,o.top+.05,.04);else e.build==="mono"&&i.block({x:[l[0]-.07,l[0]+.07],y:[o.top-n-.12,o.top-s],z:[l[1]-.07,l[1]+.07]},Z.metal)})}function OR(i,e,t){let n=e.rail==="both"?["left","right"]:e.rail==="none"?[]:[e.rail];for(let r of n){let s=[];for(let o of t)for(let a of o[r])s.push([a[0],o.top+eh,a[1]]);for(let[o,a]of t.entries()){if(o%2&&o!==t.length-1)continue;let l=a[r][0];i.cylinder(l[0],l[1],.012,a.top,a.top+eh,Z.metal,6)}for(let o=1;o0&&i.cylinder(0,0,o.column,Math.min(0,a),s.down?0:r,Z.metal,12,pe),FR(i,s,o.treads,o.rise,a),OR(i,s,o.treads)}function NR(i,e,t,n,r,s){switch(e.type){case"sofa":return e.variant==="l"||e.variant==="u"?ky(i,t,n,r,e.variant):gp(i,t,n,r,Math.max(1,Math.round((t-.4)/.62))),"yes";case"armchair":return gp(i,t,n,r,1),"yes";case"bed":return zy(i,t,n,r),"yes";case"chair":return Vy(i,t,n,r),"yes";case"table":return a_(i,t,n,r),"yes";case"desk":return u_(i,t,n,r),"yes";case"nightstand":return h_(i,t,n,r),"yes";case"wardrobe":return fi(i,t,n,r,Math.max(2,Math.round(t/.5)),r*.5),"yes";case"tall_cabinet":return fi(i,t,n,r,1,r*.5),"yes";case"shelf":return f_(i,t,n,r),"yes";case"kitchen":return Yy(i,t,n,r),"yes";case"fridge":return $y(i,t,n,r),"yes";case"fridge_smart":return Ky(i,t,n,r),"yes";case"stove":return Zy(i,t,n,r),"yes";case"sink":return Jy(i,t,n,r),"yes";case"bathtub":return n_(i,t,n,r),"yes";case"shower":return i_(i,t,n,r),"yes";case"wc":return r_(i,t,n,r),"yes";case"washbasin":return s_(i,t,n,r),"yes";case"tv_board":return y_(i,t,n,r,e.ambilight===0?pe:void 0),"yes";case"plant":return g_(i,t,n,r),"yes";case"rug":return x_(i,t,n),"no";case"stairs":return e.stair?(E_(i,e,t,n,r),e.stair.down?"no":"yes"):(b_(i,t,n,r),"yes");case"stairwell":return"no";case"sideboard":return d_(i,t,n,r),"yes";case"dresser":return p_(i,t,n,r),"yes";case"coat_rack":return m_(i,t,n,r),"yes";case"bench":return xp(i,t,n,r,!1),"yes";case"corner_bench":return xp(i,t,n,r,!0),"yes";case"bar_stool":return Gy(i,t,n,r),"yes";case"office_chair":return Hy(i,t,n,r),"yes";case"stool":return Wy(i,t,n,r),"yes";case"kitchen_wall":return jy(i,t,n,r),"no";case"kitchen_tall":return Qy(i,t,n,r),"yes";case"island":return e_(i,t,n,r),"yes";case"worktop":return qy(i,t,n,r),"no";case"dishwasher":return t_(i,t,n,r),"yes";case"washer":return Mp(i,t,n,r,!1),"yes";case"dryer":return Mp(i,t,n,r,!0),"yes";case"bunk_bed":return Xy(i,t,n,r),"yes";case"table_round":return l_(i,t,n,r),"yes";case"coffee_table":return c_(i,t,n,r),"yes";case"tv_wall":return __(i,t,n,r,e.ambilight===0?pe:void 0),"no";case"parking":{let a=[[-t/2,-n/2],[t/2,-n/2],[t/2,n/2],[-t/2,n/2]];return a.forEach(([l,c],u)=>i.seg(l,.012,c,a[(u+1)%4][0],.012,a[(u+1)%4][1],Je)),i.seg(-t*.15,.012,n/2-.45,0,.012,n/2-.2,pe),i.seg(0,.012,n/2-.2,t*.15,.012,n/2-.45,pe),"no"}case"robot_vacuum":return i.block({x:[-t*.45,t*.45],y:[0,r],z:[-n/2,-n/2+n*.3]},Z.white,pe),i.block({x:[-t*.2,t*.2],y:[r*.5,r*.62],z:[-n/2+n*.3,-n/2+n*.31]},Z.accent),"no";case"radiator":return o_(i,t,n,r),"no";case"inverter":return v_(i,t,n,r,e.variant??null),"no";case"grid_point":return M_(i,t,n,r),"yes";case"wallbox":return S_(i,t,n,r),"no";case"meter":return w_(i,t,n,r),"no";case"home_battery":return T_(i,t,n,r,e.variant??null),e.variant==="wall"?"no":"yes";default:{let o=vt(e.type);return o?o.pet?"no":(Ms(i,o,t,n,r,s,null,null,e.variant??null),s>.05?"no":"yes"):(i.block({x:[-t/2,t/2],y:[0,r],z:[-n/2,n/2]},Z.body,pe),"yes")}}}function R_(i,e,t,n,r){let s=Ss(n),o=new Li(i,e,s),[a,l,c]=[Math.max(.05,n.w),Math.max(.05,n.d),Math.max(.005,n.h)];NR(o,n,a,l,c,r)==="yes"&&pb(t,s,a,l,n.type==="plant"?.35:.5)}function C_(i,e,t){let[n,r]=[Math.cos(t),Math.sin(t)],s=e[0]*i[0]+e[1]*i[1]+e[2]*i[2],o=[e[1]*i[2]-e[2]*i[1],e[2]*i[0]-e[0]*i[2],e[0]*i[1]-e[1]*i[0]];return[i[0]*n+o[0]*r+e[0]*s*(1-n),i[1]*n+o[1]*r+e[1]*s*(1-n),i[2]*n+o[2]*r+e[2]*s*(1-n)]}function DR(i,e,t,n,r){let[s,o]=[n.tilt_x??0,n.tilt_z??0];if(!s&&!o)return;let a=n.rotation*Math.PI/180,l=[Math.cos(a),0,Math.sin(a)],c=[-Math.sin(a),0,Math.cos(a)],u=(h,f)=>{for(let d=f;d+2c.screen);if(o){let c=e?Gt(e,i):0,[u,h]=[(o.x-o.w/2)*t,(o.x+o.w/2)*t],f=Math.min(.02,(h-u)*.05);return{x0:u+f,x1:h-f,y0:c+o.y*r+f,y1:c+(o.y+o.h)*r-f,z:(o.z+o.d/2)*n}}let a=e&&i.type!=="fridge_smart"?Gt(e,i)-jr(i):0,l=BR(i,t,n,r,e);return l&&{...l,y0:l.y0+a,y1:l.y1+a}}function th(i,e){let t=kR(i,e);return t&&i.mirror?{...t,x0:-t.x1,x1:-t.x0}:t}function Sp(i,e){let[t,n,r]=[Math.max(.05,i.w),Math.max(.05,i.d),Math.max(.005,i.h)],s=vt(i.type),o=s&&jo(s,t,n,r).find(h=>h.picture);if(!o)return null;let a=e?Gt(e,i):0,[l,c]=[(o.x-o.w/2)*t,(o.x+o.w/2)*t],u={x0:l,x1:c,y0:a+o.y*r,y1:a+(o.y+o.h)*r,z:(o.z+o.d/2)*n};return i.mirror?{...u,x0:-u.x1,x1:-u.x0}:u}function wp(i,e){if(i.type!=="home_battery")return null;let[t,n,r]=[Math.max(.05,i.w),Math.max(.05,i.d),Math.max(.05,i.h)],s=e?Gt(e,i)-jr(i):0,o=n/2+.005;return i.variant==="wall"?{rect:{x0:-t*.3,x1:t*.3,y0:s+.5+r*.84,y1:s+.5+r*.9,z:o},vertical:!1}:i.variant==="cube"?{rect:{x0:-t*.35,x1:t*.35,y0:s+r*.8,y1:s+r*.86,z:o},vertical:!1}:{rect:{x0:-t*.05,x1:t*.05,y0:s+.06+r*.16,y1:s+r-.12,z:o},vertical:!0}}var Jn=Math.PI/180,dr=(i,e)=>[i[0]-e[0],i[1]-e[1],i[2]-e[2]];var Fo=i=>Math.hypot(i[0],i[1],i[2]),Ps=i=>{let e=Fo(i)||1;return[i[0]/e,i[1]/e,i[2]/e]},P_=(i,e)=>[i[1]*e[2]-i[2]*e[1],i[2]*e[0]-i[0]*e[2],i[0]*e[1]-i[1]*e[0]];var L_=.25;function F_(i,e,t,n,r,s,o){let a=r-t>=s-n,l=a?r-t:s-n;return{key:`${i}:top`,section:e,side:"top",flat:!0,o:[t,o,n],eu:a?[1,0,0]:[0,0,1],es:a?[0,0,1]:[1,0,0],n:[0,1,0],lu:l,ls:a?s-n:r-t,pitch:0,span:()=>[0,l],facing:a?[0,1]:[1,0]}}function O_(i,e){let t=Ps(P_(i,e));return t[1]<0?[-t[0],-t[1],-t[2]]:t}var N_=i=>{let e=Ps([-i[0],0,-i[2]]);return[e[0],e[2]]};function pr(i,e,t,n,r,s,o,a){let l=Ps(dr(r,n)),c=Ps(dr(s,n));return{key:i,section:e,side:t,flat:!1,o:n,eu:l,es:c,n:O_(l,c),lu:Fo(dr(r,n)),ls:Fo(dr(s,n)),pitch:o,span:a,facing:N_(c)}}function I_(i,e,t,n,r,s){let o=Fo(dr(r,n));if(o<.3)return null;let a=Ps(dr(r,n)),l=dr(s,n),c=l[0]*a[0]+l[1]*a[1]+l[2]*a[2],u=[l[0]-a[0]*c,l[1]-a[1]*c,l[2]-a[2]*c],h=Fo(u);if(h<.3)return null;let f=Ps(u),d=p=>{let x=Math.min(1,Math.max(0,p/h));return[c*x,o-(o-c)*x]};return{key:i,section:e,side:t,flat:!1,o:n,eu:a,es:f,n:O_(a,f),lu:o,ls:h,pitch:Math.atan2(f[1],Math.hypot(f[0],f[2]))/Jn,span:d,facing:N_(f)}}function zR(i,e){let t=Dn(i),n=En(i),r=(b,v,y)=>{let[M,S]=t.at(b,v);return[M,y,S]},[s,o]=[Math.max(0,e.a),Math.max(0,e.b)],a=t.u0-Math.max(0,e.u0),l=t.u1+Math.max(0,e.u1),c=l-a,u=n.y(-s),h=n.y(t.w+o);if(i.shape==="flat"||i.shape==="parapet"){let[b,v]=[t.at(a,-s),t.at(l,t.w+o)];return[F_(i.id,i.id,Math.min(b[0],v[0]),Math.min(b[1],v[1]),Math.max(b[0],v[0]),Math.max(b[1],v[1]),i.eave_a+L_)]}if(i.shape==="pent")return[pr(`${i.id}:a`,i.id,"a",r(a,-s,u),r(l,-s,u),r(a,t.w+o,h),i.pitch_a,()=>[0,c])];if(i.shape==="mansard")return VR(i,t,a,l,s,o);let f=i.shape==="hip"||i.shape==="pyramid",d=(t.u1-t.u0)/2,p=i.shape==="pyramid"?d:f?Math.min(d,Math.min(n.vr,t.w-n.vr)||t.w/2):0,x=f?t.u0+p-a:0,g=f?l-(t.u1-p):0,m=[];if(n.vr>.3){let b=Math.hypot(n.vr+s,n.rh-u);m.push(pr(`${i.id}:a`,i.id,"a",r(a,-s,u),r(l,-s,u),r(a,n.vr,n.rh),i.pitch_a,v=>[x*(v/b),c-g*(v/b)]))}if(t.w-n.vr>.3){let b=Math.hypot(t.w+o-n.vr,n.rh-h);m.push(pr(`${i.id}:b`,i.id,"b",r(l,t.w+o,h),r(a,t.w+o,h),r(l,n.vr,n.rh),i.pitch_b,v=>[g*(v/b),c-x*(v/b)]))}if(f){let b=I_(`${i.id}:c`,i.id,"c",r(a,t.w+o,h),r(a,-s,u),r(t.u0+p,n.vr,n.rh)),v=I_(`${i.id}:d`,i.id,"d",r(l,-s,u),r(l,t.w+o,h),r(t.u1-p,n.vr,n.rh));m.push(...[b,v].filter(y=>y!==null))}return m}function VR(i,e,t,n,r,s){let o=ol(e.w,i.eave_a,i.eave_b,ur(i.pitch_a),ur(i.pitch_b)),a=(p,x)=>{let[g,m]=e.at(p,x);return[g,o.y(x),m]},l=n-t,c=()=>[0,l],u=(p,x)=>Math.atan2(p,x)/Jn,h=[],[f,d]=[e.w+s,e.w-o.vlb];return o.vla+r>.3&&h.push(pr(`${i.id}:a`,i.id,"a",a(t,-r),a(n,-r),a(t,o.vla),i.pitch_a,c)),o.vr-o.vla>.3&&h.push(pr(`${i.id}:au`,i.id,"a",a(t,o.vla),a(n,o.vla),a(t,o.vr),u(o.rh-o.yla,o.vr-o.vla),c)),o.vlb+s>.3&&h.push(pr(`${i.id}:b`,i.id,"b",a(n,f),a(t,f),a(n,d),i.pitch_b,c)),d-o.vr>.3&&h.push(pr(`${i.id}:bu`,i.id,"b",a(n,d),a(t,d),a(n,o.vr),u(o.rh-o.ylb,d-o.vr),c)),h}function D_(i){return i.floors.filter(t=>t.rooms.some(n=>n.points.length>=3)).sort((t,n)=>n.elevation-t.elevation)[0]??null}function Is(i){let e=i.settings.roof;if(!e||e.type==="none")return[];if(e.type==="custom")return(e.sections??[]).flatMap(v=>zR(v,ll(i,v,v.overhang??e.overhang)));let t=D_(i);if(!t)return[];let n=t.rooms.flatMap(v=>v.points.map(y=>y[0])),r=t.rooms.flatMap(v=>v.points.map(y=>y[1])),s=i.settings.wall_exterior+e.overhang,[o,a]=[Math.min(...n)-s,Math.max(...n)+s],[l,c]=[Math.min(...r)-s,Math.max(...r)+s],u=t.elevation+t.height;if(e.type==="flat")return[F_("main",null,o,l,a,c,u+L_)];let h=a-o>=c-l,f=e.ridge==="short"?!h:h,d=(f?c-l:a-o)/2,p=d*Math.tan(e.pitch*Jn),x=(v,y,M)=>f?[v,u+M,(l+c)/2+y]:[(o+a)/2+y,u+M,v],[g,m]=f?[o,a]:[l,c],b=()=>[0,m-g];return[pr("main:a",null,"a",x(g,-d,0),x(m,-d,0),x(g,0,p),e.pitch,b),pr("main:b",null,"b",x(g,d,0),x(m,d,0),x(g,0,p),e.pitch,b)]}function nh(i,e){let t=[];for(let n of i.floors.filter(r=>!e||r.id===e)){let{walls:r}=al(n.rooms,{exterior:i.settings.wall_exterior,interior:i.settings.wall_interior},n.walls??[]);for(let s of r){if(!s.exterior&&!s.free)continue;let[o,a]=[s.b[0]-s.a[0],s.b[1]-s.a[1]],l=Math.hypot(o,a);if(l<1.2)continue;let[c,u]=[a/l,-o/l],h=Math.min(n.height,s.height??n.height,s.heightEnd??1/0),f=(d,p,x,g)=>t.push({key:d,section:null,side:"top",flat:!1,o:p,eu:x,es:[0,1,0],n:g,lu:l,ls:h,pitch:90,span:()=>[0,l],facing:[g[0],g[2]],wall:{floorId:n.id}});f(`wall:${n.id}:${s.id}`,[s.a[0]+c*s.right,n.elevation,s.a[1]+u*s.right],[o/l,0,a/l],[c,0,u]),s.free&&f(`wall:${n.id}:${s.id}:back`,[s.b[0]-c*s.left,n.elevation,s.b[1]-u*s.left],[-o/l,0,-a/l],[-c,0,-u])}}return t}var Sl="ground";function ih(i){let e=i.floors.filter(t=>t.rooms.some(n=>n.points.length>=3)).sort((t,n)=>t.elevation-n.elevation);return e.find(t=>t.elevation>-.5)??e[0]??i.floors[0]??null}function rh(i,e){let t=(e.rotation??0)*Jn,n=[Math.cos(t),0,Math.sin(t)],r=[-Math.sin(t),0,Math.cos(t)],s=ih(i),o=n[0]*e.u+r[0]*e.v,a=n[2]*e.u+r[2]*e.v,l=s?s.elevation+(e.base!=null?e.base:p0(s,o,a)):e.base??0;return{key:Sl,section:null,side:"top",flat:!0,o:[0,l,0],eu:n,es:r,n:[0,1,0],lu:1e4,ls:1e4,pitch:0,span:()=>[-1e4,1e4],facing:[r[0],r[2]],unbounded:!0}}var Tp=1.13,Ap=1.72,Oo=.025,di=.07;function wl(i){let e=i.module_w||Tp,t=i.module_h||Ap;return i.portrait===!1?[t,e]:[e,t]}function Ep(i){return i.layout?.length?i.layout.map(e=>Math.max(0,Math.min(60,Math.round(e)))):Array.from({length:Math.max(1,i.rows)},()=>Math.max(1,i.cols))}function Rp(i,e){return i.flat?Math.min(45,Math.max(0,e.tilt??15))*Jn:i.wall?Math.min(90,Math.max(0,e.tilt??0))*Jn:Math.min(45,Math.max(0,e.tilt??0))*Jn}function oh(i,e){let[,t]=wl(e),n=Rp(i,e);return i.wall?t*Math.cos(n)+Oo:!i.flat&&n<.001?t+Oo:i.flat&&e.rack==="ew"?t*Math.cos(n)+.08:t*Math.cos(n)+Math.max(.3,2*t*Math.sin(n))}function Cp(i,e){let[t,n]=wl(e),r=Ep(e),s=Math.max(1,...r);return[s*t+(s-1)*Oo,(r.length-1)*oh(i,e)+n*Math.cos(Rp(i,e))]}var GR=i=>i.flat&&!i.unbounded&&!i.wall;function HR(i,e){if(!GR(i)||!e.rotation)return null;let t=e.rotation*Jn,[n,r]=Cp(i,e);return{cos:Math.cos(t),sin:Math.sin(t),u:e.u+n/2,s:e.v+r/2}}function No(i,e,t=!1){let[n,r]=wl(e),s=Rp(i,e),o=r*Math.cos(s),a=oh(i,e),l=Ep(e),c=Math.max(1,...l),u=new Set(e.skip??[]),h=HR(i,e),f=(g,m)=>h?[h.u+(g-h.u)*h.cos-(m-h.s)*h.sin,h.s+(g-h.u)*h.sin+(m-h.s)*h.cos]:[g,m],d=(g,m,b)=>{let[v,y]=f(g,m);return[0,1,2].map(M=>i.o[M]+i.eu[M]*v+i.es[M]*y+i.n[M]*b)},p=(g,m)=>{let[b,v]=f(g,m);if(i.unbounded)return!0;if(v<-1e-6||v>i.ls+1e-6)return!1;let[y,M]=i.span(v);return b>=y-1e-6&&b<=M+1e-6},x=[];return l.forEach((g,m)=>{let b=e.align==="right"?c-g:e.align==="center"?(c-g)/2:0;for(let v=0;v.001?o:r);if([[S,w],[_,w],[_,R],[S,R]].every(([A,C])=>p(A,C)))if(i.wall&&s>.001){let A=di+r*Math.sin(s),[C,O]=e.flip?[A,di]:[di,A],D=[d(S,w,C),d(_,w,C),d(_,R,O),d(S,R,O)],P=e.flip?w:R;x.push({corners:D,posts:[S+.05,_-.05].map(I=>[d(I,P,0),d(I,P,A)]),cell:y,skipped:M})}else if(!i.flat&&s>.001){let A=di+r*Math.sin(s),C=[d(S,w,di),d(_,w,di),d(_,R,A),d(S,R,A)];x.push({corners:C,posts:[S+.05,_-.05].map(O=>[d(O,R,0),d(O,R,A)]),cell:y,skipped:M})}else if(!i.flat)x.push({corners:[d(S,w,di),d(_,w,di),d(_,R,di),d(S,R,di)],posts:[],cell:y,skipped:M});else{let C=.15+r*Math.sin(s),O=e.rack==="ew"&&m%2===1?!e.flip:!!e.flip,[D,P]=O?[R,w]:[w,R],I=[d(S,D,.15),d(_,D,.15),d(_,P,C),d(S,P,C)],N=[S+.05,_-.05].flatMap(F=>[[d(F,D,0),d(F,D,.15)],[d(F,P,0),d(F,P,C)]]);x.push({corners:I,posts:N,cell:y,skipped:M})}}}),x}var Pp=.78,Ip=1.18,U_=i=>({id:i.id,face:i.face,u:i.u,v:i.v,rows:1,cols:1,portrait:!0,module_w:i.w||Pp,module_h:i.h||Ip});function Tl(i,e){let t=No(i,U_(e))[0];if(!t)return null;let n=r=>[r[0]-i.n[0]*.05,r[1]-i.n[1]*.05,r[2]-i.n[2]*.05];return t.corners.map(n)}var sh={brick:{w:.5,d:.5,h:1},round:{w:.4,d:.4,h:1},wide:{w:1,d:.5,h:1},steel:{w:.2,d:.2,h:1.2}};function ah(i){let e=i.shape??"brick",t=sh[e]??sh.brick;return{shape:e,w:i.w||t.w,d:i.d||t.d,h:i.h||t.h}}function Lp(i,e){let{w:t,d:n}=ah(i),r=e&&!e.flat?Math.cos(e.pitch*Jn):1;return{id:i.id,face:i.face,u:i.u,v:i.v,rows:1,cols:1,portrait:!0,module_w:t,module_h:n/Math.max(.2,r),tilt:0}}function Fp(i,e){let t=Lp(e,i),[n,r]=[t.module_w,t.module_h],s=(u,h)=>[i.o[0]+i.eu[0]*u+i.es[0]*h,i.o[1]+i.eu[1]*u+i.es[1]*h,i.o[2]+i.eu[2]*u+i.es[2]*h],[o,a]=[s(e.u+n/2,e.v),s(e.u+n/2,e.v+r)],l=s(e.u+n/2,e.v+r/2),c=u=>{let h=Math.hypot(u[0],u[2])||1;return[u[0]/h,u[2]/h]};return{center:[l[0],l[2]],along:c(i.eu),across:c(i.es),low:Math.min(o[1],a[1]),high:Math.max(o[1],a[1])}}var Ls=1712952,Fs=2239816,lh=1318193,mr=Ue(3662079,.9),gr=Ue(5995775,.45),Xt=.14,B_=9427199,k_=13226982,z_=14936565,V_={black:{glass:new W(329483),edge:Ue(9082544,.32),cells:Ue(2766160,.22)},blue:{glass:new W(1386842),edge:Ue(10467583,.55),cells:Ue(4025599,.35)}},G_=Ue(13226982,.5),H_=Ue(13226982,.85),W_=Ue(16757575,.95),Op=new W(2845583),Np=new W(3818072),Dp=3812144,Up=4864064,ch=2765896,Do=329483,uh=9148333,hh=11845844,X_=Ue(5995775,.4);var Uo=(i,e,t)=>[i[0]+(e[0]-i[0])*t,i[1]+(e[1]-i[1])*t,i[2]+(e[2]-i[2])*t],fh=(i,e,t)=>[i[0]+e[0]*t,i[1]+e[1]*t,i[2]+e[2]*t],Bp=(i,e)=>e.section?i.find(t=>t.sections?.includes(e.section)):i[0];function Y_(i,e,t){let n=i.settings.roof?.windows??[];if(n.length===0||e.length===0)return;let r=new Map(Is(i).map(s=>[s.key,s]));for(let s of n){let o=r.get(s.face),a=o?Tl(o,s):null,l=o&&a?Bp(e,o):void 0;if(!o||!a||!l)continue;let c=l.floor.elevation+l.base,[u,h,f,d]=a.map(R=>[R[0],R[1]-c,R[2]]),p=t.get(s.id)??{open:0,tilt:0,cover:0},x=(R,A)=>fh(R,o.n,A),g=p.open>.02||p.tilt>.02?W_:H_,m=[u,h,f,d].map(R=>x(R,.06));m.forEach((R,A)=>l.lines.seg(R,m[(A+1)%4],g));let b=(p.open>.02?30*Math.min(1,p.open):p.tilt>.5?12:0)*pt,v=Math.hypot(f[0]-h[0],f[1]-h[1],f[2]-h[2]),y=R=>fh(fh(R,o.es,-v*Math.cos(b)),o.n,v*Math.sin(b)),[M,S]=[x(d,.065),x(f,.065)],[_,w]=[y(M),y(S)];l.solid.tri(_,w,S,Op),l.solid.tri(_,S,M,Op);for(let[R,A]of[[_,w],[w,S],[S,M],[M,_]])l.lines.seg(R,A,g);if(p.cover>.02){let R=Math.min(1,p.cover),[A,C]=[x(Uo(M,_,R),.01),x(Uo(S,w,R),.01)],[O,D]=[x(M,.01),x(S,.01)];l.solid.tri(A,C,D,Np),l.solid.tri(A,D,O,Np)}}}function dh(i,e,t,n,r){let s=c=>[c[0],c[1]-r,c[2]],o=V_[n.look==="blue"?"blue":"black"],[a,l]=n.portrait===!1?[10,6]:[6,10];for(let c of No(t,n)){let[u,h,f,d]=c.corners.map(s);for(let[g,m,b]of[[u,h,f],[u,f,d],[u,f,h],[u,d,f]])i.tri(g,m,b,o.glass);let p=g=>fh(g,t.n,.004),x=[u,h,f,d].map(p);x.forEach((g,m)=>e.seg(g,x[(m+1)%4],o.edge));for(let g=1;g[r.key,r]));for(let r of t){let s=n.get(r.face),o=s?Bp(e,s):void 0;s&&o&&dh(o.solid,o.lines,s,r,o.floor.elevation+o.base)}}function $_(i,e){let t=i.settings.roof?.chimneys??[];if(t.length===0||e.length===0)return;let n=new Map(Is(i).map(r=>[r.key,r]));for(let r of t){let s=n.get(r.face),o=s?Bp(e,s):void 0;if(!s||!o)continue;let a=o.floor.elevation+o.base,{shape:l,w:c,d:u,h}=ah(r),f=Fp(s,r),[d,p]=[f.low-a-.1,f.high-a+h],x=(_,w)=>{let{center:R,along:A,across:C}=f,O=(D,P)=>[R[0]+A[0]*_*D+C[0]*w*P,R[1]+A[1]*_*D+C[1]*w*P];return[O(-1,-1),O(1,-1),O(1,1),O(-1,1)]},g=(_,w=16)=>Array.from({length:w},(R,A)=>[f.center[0]+Math.cos(A/w*2*Math.PI)*_,f.center[1]+Math.sin(A/w*2*Math.PI)*_]),m=(_,w)=>_.forEach((R,A)=>o.lines.seg([R[0],w,R[1]],[_[(A+1)%_.length][0],w,_[(A+1)%_.length][1]],X_)),b=(_,w,R,A,C)=>Tt(o.solid,YR(_),w,R,A,C);if(l==="steel"){let _=Math.min(c,u)/2;b(g(_,12),d,p,uh,hh),b(g(_*.75,12),p,p+.001,Do,Do),b(g(_*.25,6),p,p+.1,uh,hh);let w=g(_*1.9,12);b(w,p+.1,p+.13,uh,hh),m(w,p+.13);continue}if(l==="round"){let _=Math.min(c,u)/2,w=g(_);b(w,d,p,Dp,Up),b(g(_*.55),p,p+.002,Do,Do),m(w,p);continue}let v=x(c/2,u/2);b(v,d,p,Dp,Up);let y=x(c/2+.04,u/2+.04);b(y,p,p+.06,ch,ch),m(y,p+.06),m(v,p-.25);let M=Math.min(c,u)*.25,S=l==="wide"?[-c/4,c/4]:[0];for(let _ of S){let w=[f.center[0]+f.along[0]*_,f.center[1]+f.along[1]*_],R=[[-1,-1],[1,-1],[1,1],[-1,1]].map(([A,C])=>[w[0]+f.along[0]*M*A+f.across[0]*M*C,w[1]+f.along[1]*M*A+f.across[1]*M*C]);b(R,p+.06,p+.16,ch,Do)}}}function YR(i){let e=0;for(let t=0;t0,r.b>0,r.u0>0,r.u1>0],f=(p,x,g,m,b,v)=>{let y=[t.at(p,g),t.at(x,g),t.at(x,m),t.at(p,m)],M=(y[1][0]-y[0][0])*(y[2][1]-y[0][1])-(y[2][0]-y[0][0])*(y[1][1]-y[0][1]);Tt(i,M<0?[...y].reverse():y,b-o,v-o,k_,z_,{bottom:!0})};for(let[p,x]of[[0,l],[a,c]]){if(!x)continue;let g=n.y(p)-.03,m=p===0?0:a-jn;f(t.u0,t.u1,m,m+jn,g-Al,g),e.seg(s(t.u0,p,g-Al),s(t.u1,p,g-Al),gr)}for(let[p,x]of[[t.u0,u],[t.u1-jn,h]])if(x)for(let g=0;g<6;g++){let[m,b]=[a*g/6,a*(g+1)/6],v=Math.min(n.y(m),n.y(b))-.03;f(p,p+jn,m,b,v-Al,v)}let d=[];for(let[p,x]of[[0,l],[a-jn,c]]){if(!x)continue;let g=t.u1-t.u0-jn,m=Math.max(1,Math.ceil(g/3.5));for(let b=0;b<=m;b++)b===0&&!u||b===m&&!h||d.push([t.u0+g*b/m,p])}!l&&!c&&(u&&d.push([t.u0,a/2-jn/2]),h&&d.push([t.u1-jn,a/2-jn/2]));for(let[p,x]of d)f(p,p+jn,x,x+jn,o,n.y(x+jn/2)-.03-Al)}function qR(i,e){let t=[];if(i.forEach(([s,o],a)=>{o>=e&&t.push([s,o]);let l=i[a+1];if(l&&(o-e)*(l[1]-e)<0){let c=(e-o)/(l[1]-o);t.push([s+(l[0]-s)*c,e])}}),t.length<2)return[];let[n,r]=[t[0],t[t.length-1]];return r[1]>e&&t.push([r[0],e]),n[1]>e&&t.unshift([n[0],e]),t}var Z_=i=>vr(i)>=0?i:[...i].reverse();function J_(i,e,t,n,r,s=i,o=!1,a=[],l=null){let c=Dn(t),u=En(t),h=typeof n=="number"?{u0:n,u1:n,a:n,b:n}:n,[f,d]=[Math.max(0,h.a),Math.max(0,h.b)],p=c.w,x=c.u0-Math.max(0,h.u0),g=c.u1+Math.max(0,h.u1),m=(I,N,F)=>{let[H,B]=c.at(I,N);return[H,F-r,B]},b=new W(Fs),v=new W(Ls),y=new W(lh),M=(I,N)=>{for(let F=1;F+1m(I,N,F-H),_=[],w=[],R=[],A=null,C=null;if(t.shape==="flat"||t.shape==="parapet"){let I=t.eave_a-r,N=t.shape==="parapet",F=t.points&&t.points.length>=3?qd(t,N?0:Math.max(0,Math.min(h.a,h.b,h.u0,h.u1))):N?[c.at(c.u0,0),c.at(c.u1,0),c.at(c.u1,p),c.at(c.u0,p)]:[c.at(x,-f),c.at(g,-f),c.at(g,p+d),c.at(x,p+d)];if(Tt(i,F,I,I+.25,Ls,Fs,{bottom:!0}),F.forEach((H,B)=>{let X=F[(B+1)%F.length];e.seg([H[0],I+.252,H[1]],[X[0],I+.252,X[1]],mr),e.seg([H[0],I,H[1]],[X[0],I,X[1]],gr)}),N){let H=Z_(F),B=Ou(H,-.2);H.forEach((X,V)=>{let re=(V+1)%H.length;Tt(i,Z_([X,H[re],B[re],B[V]]),I+.25,I+.65,Ls,Fs),e.seg([X[0],I+.652,X[1]],[H[re][0],I+.652,H[re][1]],mr),e.seg([B[V][0],I+.652,B[V][1]],[B[re][0],I+.652,B[re][1]],mr)})}}else{let I=Hr(t,h);_=a.reduce((N,F)=>N.flatMap(H=>Nu(H,F)),I.faces),w=I.rim,R=I.ridges,A=I.gable,C=I.endProfiles??null}let O=!!t.open,D=new W(B_);for(let I of _)if(O)for(let N=1;N+1S(N)),b),M(I.map(N=>S(N,Xt)),v);if(w.forEach((I,N)=>{let F=w[(N+1)%w.length];O||M([S(I),S(F),S(F,Xt),S(I,Xt)],v),e.seg(S(I),S(F),O?mr:gr)}),O){K_(i,e,c,u,h,(I,N,F)=>m(I,N,F),r);return}for(let[I,N]of R)e.seg(S([I[0],I[1],I[2]+.004]),S([N[0],N[1],N[2]+.004]),mr);let P=t.base;if(!o){if(A){let I=l===null?[c.u0,c.u1]:[l===0?c.u0:c.u1];for(let N of I){let F=C?C[N===c.u0?0:1]:A,H=F?qR(F,P-Xt):[];H.length>=3&&M(H.map(([B,X])=>m(N,B,X)),y)}}if(t.shape!=="flat"&&t.shape!=="parapet")for(let I of[0,p]){let N=u.y(I)-Xt;N>P+.02&&M([m(c.u0,I,P),m(c.u1,I,P),m(c.u1,I,N),m(c.u0,I,N)],y)}else if(t.eave_a>P+.02){let I=[[c.u0,0],[c.u1,0],[c.u1,p],[c.u0,p]];I.forEach(([N,F],H)=>{let[B,X]=I[(H+1)%4];M([m(N,F,P),m(B,X,P),m(B,X,t.eave_a),m(N,F,t.eave_a)],y)})}}}function j_(i,e,t){let n=i.floors.filter(o=>o.rooms.length>0).sort((o,a)=>o.elevation-a.elevation);if(n.length===0)return[];let r=new Map,s=new Map(Is(i).map(o=>[o.key,o]));for(let o of e){if(Math.abs(o.x1-o.x0)<.1||Math.abs(o.z1-o.z0)<.1)continue;let a=Zd(i,o)??n[0],l=o.open?`${a.id}:open`:a.id,c=r.get(l);c||r.set(l,c={floor:a,base:0,solid:new lt,lines:new Wt,glass:new lt,sections:[],lift:!o.open}),c.sections.push(o.id);let u=ul(e,o),h=As(e,o)??u?.parent??null,f=a.elevation+a.height>o.base+.05&&!o.dormer&&!h,d=e.filter(g=>g!==o).flatMap(g=>As(e,g)===o?Uu(o,g):ul(e,g)?.parent===o?Uu(o,ul(e,g).extended):[]);for(let g of i.settings.roof.windows??[]){let m=s.get(g.face),b=m&&m.section===o.id?Tl(m,g):null;if(!b)continue;let v=b.map(y=>Fi(o,y[0],y[2]));d.push({u0:Math.min(...v.map(y=>y[0])),u1:Math.max(...v.map(y=>y[0])),v0:Math.min(...v.map(y=>y[1])),v1:Math.max(...v.map(y=>y[1]))})}let p=u?u.extended:h?cl(h,o):o,x=null;if(h){let g=Dn(p),m=Hr(h,{u0:0,u1:0,a:0,b:0}),b=v=>{let[y,M]=g.at(v,g.w/2),[S,_]=Fi(h,y,M);return Ts(m,S,_)??En(h).y(_)};x=b(g.u0)<=b(g.u1)?0:1}J_(c.solid,c.lines,p,ll(i,p,p.overhang??t),a.elevation,c.glass,f,d,x)}return[...r.values()].sort((o,a)=>+(o.lift===!1)-+(a.lift===!1))}function Q_(i){return i.floors.filter(e=>e.rooms.some(t=>t.points.length>=3)).sort((e,t)=>t.elevation-e.elevation)[0]??null}function ev(i){let e=i.settings.roof,t=Q_(i);if(!t||!e||e.type==="none"||e.type==="custom")return null;let n=t.rooms.flatMap(O=>O.points.map(D=>D[0])),r=t.rooms.flatMap(O=>O.points.map(D=>D[1])),s=i.settings.wall_exterior+e.overhang,[o,a]=[Math.min(...n)-s,Math.max(...n)+s],[l,c]=[Math.min(...r)-s,Math.max(...r)+s],u=new lt,h=new Wt,f={floor:t,base:t.height,solid:u,lines:h,glass:new lt};if(e.type==="flat"){let O=[[o,l],[a,l],[a,c],[o,c]];return Tt(u,O,0,.25,Ls,Fs,{bottom:!0}),O.forEach(([D,P],I)=>{let[N,F]=O[(I+1)%4];h.seg([D,.252,P],[N,.252,F],mr),h.seg([D,0,P],[N,0,F],gr)}),f}let d=a-o>=c-l,p=e.ridge==="short"?!d:d,x=(p?c-l:a-o)/2,g=Math.tan(e.pitch*pt),m=x*g,b=(O,D,P)=>p?[O,P,(l+c)/2+D]:[(o+a)/2+D,P,O],[v,y]=p?[o,a]:[l,c],M=new W(Fs),S=new W(Ls),_=(O,D,P,I,N)=>{u.tri(O,D,P,N),u.tri(O,P,I,N)};for(let O of[-1,1]){_(b(v,O*x,0),b(y,O*x,0),b(y,0,m),b(v,0,m),M),_(b(v,O*x,-Xt),b(v,0,m-Xt),b(y,0,m-Xt),b(y,O*x,-Xt),S),_(b(v,O*x,-Xt),b(y,O*x,-Xt),b(y,O*x,0),b(v,O*x,0),S);for(let D of[v,y])_(b(D,O*x,-Xt),b(D,O*x,0),b(D,0,m),b(D,0,m-Xt),S);h.seg(b(v,O*x,0),b(y,O*x,0),gr);for(let D of[v,y])h.seg(b(D,O*x,0),b(D,0,m),gr)}let w=e.overhang,R=new W(lh),A=x-w,C=A*g;for(let O of[v+w,y-w])u.tri(b(O,-A,-Xt),b(O,A,-Xt),b(O,0,C-Xt),R),u.tri(b(O,A,-Xt),b(O,-A,-Xt),b(O,0,C-Xt),R);return h.seg(b(v,0,m+.004),b(y,0,m+.004),mr),f}function kp(i,e=new Map){let t=i.settings.roof,n=t?.type==="custom"?null:ev(i),r=t?.type==="custom"?j_(i,t.sections??[],t.overhang):n?[n]:[];return q_(i,r),Y_(i,r,e),$_(i,r),r}function ph(i){let{start:e,axis:t,width:n}=i.info;return[[e[0],e[1]],[e[0]+t[0]*n,e[1]+t[1]*n]]}var tv=(i,e)=>`${i}|${Math.round(e[0]*50)},${Math.round(e[1]*50)}`;function nv(i,e){let t=[];for(let n of i){let r=n.info.opening.front;if(!r)continue;let[s,o]=ph(n);e.at(r,s)&&t.push(n.s0),e.at(r,o)&&t.push(n.s1)}return t}function iv(i,e){let t=Math.hypot(i.b[0]-i.a[0],i.b[1]-i.a[1])||1;return((e[0]-i.a[0])*(i.b[0]-i.a[0])+(e[1]-i.a[1])*(i.b[1]-i.a[1]))/t}function mh(i){let e=new Map,t=new Map;for(let r of i)for(let s of r){let o=s.info.opening.front;if(o)for(let a of ph(s)){let l=tv(o,a);e.set(l,(e.get(l)??0)+1),t.has(l)||t.set(l,[a[0],a[1]])}}return{points:[...e].filter(([,r])=>r>1).map(([r])=>t.get(r)).filter(r=>!!r),at:(r,s)=>(e.get(tv(r,s))??0)>1}}var Os={floor:923177,slab:659744,wall:1252657,wallTop:1323071,edge:3662079,edgeSoft:5995775},gh={wood:{color:1120814,tile:[0,0]},oak:{color:1252141,tile:[1,0]},tiles:{color:923695,tile:[2,0]},carpet:{color:1053995,tile:[0,1]},stone:{color:988971,tile:[1,1]},concrete:{color:1120295,tile:[2,1]}},pi=.2,Bo=8;var rv=(i,e)=>i.heightEnd===void 0?i.height??e:Math.max(i.height??e,i.heightEnd);function sv(i){let e=new Map,t=[],n=new Map;for(let r of i){let s="interior",o=null;if(r.exterior){let[a,l]=[r.b[0]-r.a[0],r.b[1]-r.a[1]],c=Math.hypot(a,l)||1,u=[l/c,-a/c],h=(Math.round(Math.atan2(u[1],u[0])/(2*Math.PI)*Bo)%Bo+Bo)%Bo;s=`s${h}`;let f=h/Bo*2*Math.PI;o=[Math.cos(f),Math.sin(f)]}e.has(s)||(e.set(s,t.length),t.push(o)),n.set(r,e.get(s))}return{buckets:t,wallBucket:n}}function ov(i){let e=(n,r,s)=>{let o=i?i(n,r):null;return o===null?s:Math.max(.05,Math.min(s,o))};return{topAt:e,lowestTop:(n,r,s,o,a)=>{if(!i)return a;let l=Math.max(2,Math.ceil((o-s)/.25)+1),c=a;for(let u=0;ut.topAt(h,f,n),lowestTop:(h,f)=>t.lowestTop(i.a,s,h,f,n)};let[o,a]=[i.height??e,i.heightEnd],l=(h,f)=>{let d=r>1e-9?((h-i.a[0])*s[0]+(f-i.a[1])*s[1])/r:0;return o+(a-o)*Math.max(0,Math.min(1,d))},c=(h,f)=>t.topAt(h,f,l(h,f));return{H:n,varies:!0,topAt:c,lowestTop:(h,f)=>{let d=Math.max(2,Math.ceil((f-h)/.25)+1),p=1/0;for(let x=0;x0:c.roomLeft===o.room_id,m=[-h[1],h[0]],b=g?m:[-m[0],-m[1]],v=Qr(i.rooms.find(R=>R.id===o.room_id)),y=Math.min(ko(c,i.height,n).lowestTop(p,p+d)-.02,v+o.sill+o.height),M=Math.max(Math.min(0,v),Math.min(v+o.sill,y-.1)),S=[b[1],-b[0]],_=h[0]*S[0]+h[1]*S[1]>0,w={opening:o,bucket:t.get(c),start:[c.a[0]+h[0]*p,c.a[1]+h[1]*p],axis:h,width:d,toRoom:b,faceRoom:g?c.left:c.right,faceOut:g?c.right:c.left,sill:M,top:y,hingeAtStart:o.hinge==="left"===_,exterior:c.exterior};s.push(w),r.set(c,[...r.get(c)??[],{s0:p,s1:p+d,sill:M,top:y,info:w}])}return{openings:s,spans:r}}var lv=i=>`${Math.round(i[0]*50)},${Math.round(i[1]*50)}`;function $R(i,e,t,n=!1,r=!1){let{info:s}=e,o=s.bucket,a=(u,h,f)=>[s.start[0]+s.axis[0]*(u-e.s0)+s.toRoom[0]*h,f,s.start[1]+s.axis[1]*(u-e.s0)+s.toRoom[1]*h],l=u=>u>t+1e-6?o:Xe,c=e.sill<0?e.sill+.004:Math.max(e.sill,.004);for(let u of[s.faceRoom,-s.faceOut])n||i.segSplit(a(e.s0,u,c),a(e.s0,u,e.top),ci,t,o),r||i.segSplit(a(e.s1,u,c),a(e.s1,u,e.top),ci,t,o),i.seg(a(e.s0,u,e.top),a(e.s1,u,e.top),ci,l(e.top)),e.sill>.01&&i.seg(a(e.s0,u,e.sill),a(e.s1,u,e.sill),ci,l(e.sill));for(let[u,h]of[[e.s0,n],[e.s1,r]])h||(i.seg(a(u,s.faceRoom,e.top),a(u,-s.faceOut,e.top),ci,l(e.top)),e.sill>.01&&i.seg(a(u,s.faceRoom,e.sill),a(u,-s.faceOut,e.sill),ci,l(e.sill)),e.sillt&&i.seg(a(u,s.faceRoom,t),a(u,-s.faceOut,t),Pu,tl+o))}function cv(i,e,t,n,r,s,o){let a=Math.min(e.cut_height,e.height),l=(f,d)=>(r.get(f)??[]).filter(d);for(let f of t.edges){let d=n.get(f.wall);for(let[m,b]of Eo(f,l(f.wall,v=>v.sill<=.005)))i.seg([m[0],.004,m[1]],[b[0],.004,b[1]],Ad);for(let[m,b]of Eo(f,l(f.wall,v=>v.silla)))i.seg([m[0],a,m[1]],[b[0],a,b[1]],Pu,tl+d);let p=ko(f.wall,e.height,s),{H:x,topAt:g}=p;for(let[m,b]of Eo(f,l(f.wall,v=>v.top>=x-.021))){if(!o&&!p.varies){i.seg([m[0],x,m[1]],[b[0],x,b[1]],Ii,x<=a+1e-6?cr+d:d);continue}let v=Math.max(1,Math.ceil(Math.hypot(b[0]-m[0],b[1]-m[1])/.3)),y=M=>[m[0]+(b[0]-m[0])*M/v,m[1]+(b[1]-m[1])*M/v];for(let M=0;M!!b.info.opening.front&&d>b.s0+.05&&dMath.abs(b-d)<.06);if(x||g||u.has(lv(f.p)))continue;let m=ko(f.wall,e.height,s).topAt(f.p[0],f.p[1]);i.segSplit([f.p[0],.004,f.p[1]],[f.p[0],m,f.p[1]],ci,Math.min(a,m),n.get(f.wall))}for(let f of r.values())for(let d of f){let p=d.info.opening.front,[x,g]=ph(d);$R(i,d,a,p?c.at(p,x):!1,p?c.at(p,g):!1)}}function uv(i,e){let t=new lt(!0,!0),n=[],r=new Wt,s=[],o=new W(Os.slab),a=(l,c=0,u=c-pi)=>{l.forEach((h,f)=>{let d=l[(f+1)%l.length];t.tri([h[0],u,h[1]],[h[0],c,h[1]],[d[0],c,d[1]],o),t.tri([h[0],u,h[1]],[d[0],c,d[1]],[d[0],u,d[1]],o)})};for(let l of i.rooms){if(l.points.length<3)continue;let c=Gr(l.points),u=gh[l.floor_material]??gh.wood,h=new W(u.color),f=e.filter(g=>ly(g,c)).map(g=>cy(g,.003));s.push(...f);let d=[...c,...f.flat()],p=t.count,x=Qr(l);for(let[g,m,b]of Vr(c,f)){let[v,y,M]=[d[g],d[m],d[b]];t.tri([v[0],x,v[1]],[M[0],x,M[1]],[y[0],x,y[1]],h,h,h,[v[0],v[1],M[0],M[1],y[0],y[1]],Xe,u.tile)}n.push({roomId:l.id,start:p,end:t.count,color:u.color}),a(c,x),Math.abs(x)>.005&&(a(c,Math.max(0,x),Math.min(0,x)),a([...c].reverse(),Math.max(0,x),Math.min(0,x)));for(let g of f)a([...Gr(g)].reverse()),g.forEach((m,b)=>{let v=g[(b+1)%g.length];r.seg([m[0],x+.006,m[1]],[v[0],x+.006,v[1]],Ii),r.seg([m[0],x-pi,m[1]],[v[0],x-pi,v[1]],ci)})}return{buffer:t,roomTris:n,holeLines:r,cutHoles:s}}var xh=.42,zp=.42;function hv(i,e,t){let n=new lt,r=new W(zp,zp,zp),s=new W(1,1,1),o=.002;for(let a of i)for(let[l,c]of Eo(a,(t.get(a.wall)??[]).filter(u=>u.sill<=.005))){let[u,h]=[c[0]-l[0],c[1]-l[1]],f=Math.hypot(u,h);if(f<.05)continue;let d=[h/f,-u/f],p=[(l[0]+c[0])/2+d[0]*.05,(l[1]+c[1])/2+d[1]*.05];if(!e.some(m=>m.points.length>=3&&Ve(p,m.points)))continue;let x=[l[0]+d[0]*xh,l[1]+d[1]*xh],g=[c[0]+d[0]*xh,c[1]+d[1]*xh];n.tri([l[0],o,l[1]],[x[0],o,x[1]],[g[0],o,g[1]],r,s,s),n.tri([l[0],o,l[1]],[g[0],o,g[1]],[c[0],o,c[1]],r,s,r)}return n}var Vp=(i,e)=>Number.parseInt(/^#?([0-9a-f]{6})$/i.exec(i?.trim()??"")?.[1]??e.slice(1),16),KR=i=>/^#?[0-9a-f]{6}$/i.test(i?.trim()??"");function Gp(i,e){return{outside:Vp(KR(e.wall_paint_outside)?e.wall_paint_outside:i.wall_paint_outside,g0),inside:Vp(i.wall_paint_inside,Vh),rooms:e.rooms.filter(t=>t.wall_paint&&t.points.length>=3).map(t=>({points:t.points,color:Vp(t.wall_paint,Vh)}))}}var ZR=14276045;function JR(i,e,t,n,r){let s=Math.hypot(t[0]-e[0],t[1]-e[1])||1,o=[(e[0]+t[0])/2,(e[1]+t[1])/2],a=[(t[1]-e[1])/s,-(t[0]-e[0])/s];Ve([o[0]+a[0]*.01,o[1]+a[1]*.01],i)&&(a=[-a[0],-a[1]]);let l=[o[0]+a[0]*.06,o[1]+a[1]*.06],c=n.rooms.find(u=>Ve(l,u.points));return c?c.color:r.some(u=>u.points.length>=3&&Ve(l,u.points))?n.inside:n.outside}function jR(i,e,t=-pi){let n=[-1/0,...new Set(i.flatMap(s=>[s.s0,s.s1])).values(),1/0].sort((s,o)=>s-o),r=[];for(let s=0;s+1f.s0l).map(f=>[f.sill,f.top]).sort((f,d)=>f[0]-d[0]),u=[],h=t;for(let[f,d]of c)f>h+1e-4&&u.push([h,f]),h=Math.max(h,d);e>h+1e-4&&u.push([h,e]),r.push({t0:o,t1:a,ranges:u})}return r}function fv(i,e,t,n,r,s,o,a){let l=Math.min(e.cut_height,e.height),c=a?Cd:0,u=a?g=>(m,b)=>JR(g,m,b,a,e.rooms):null,h=a?ZR:Os.wallTop,f=mh(r.values()),d=g=>f.points.some(m=>Math.hypot(m[0]-g[0],m[1]-g[1])<.03),p=g=>g&&g.info.opening.front?[g.sill,g.top]:null,x=(g,m)=>{let b=[];for(let[v,y]of g)m[0]>v+1e-4&&b.push([v,Math.min(y,m[0])]),y>m[1]+1e-4&&b.push([Math.max(v,m[1]),y]);return b};for(let g of t){let m=n.get(g),b=_s([g.b[0]-g.a[0],g.b[1]-g.a[1]]),v=(r.get(g)??[]).sort((I,N)=>I.s0-N.s0),y=ko(g,e.height,s),{H:M,topAt:S}=y,_=Math.min(0,...[g.roomLeft,g.roomRight].map(I=>Qr(e.rooms.find(N=>N.id===I)))),w=jR(v,M,_-pi),R=Math.hypot(g.b[0]-g.a[0],g.b[1]-g.a[1]),A=(o||y.varies)&&y.lowestTop(0,R){let N=Math.max(I.t0,-.5),F=Math.min(I.t1,R+.5),H=Math.max(1,Math.ceil((F-N)/.3));return Array.from({length:H},(B,X)=>({t0:X===0?I.t0:N+(F-N)*X/H,t1:X===H-1?I.t1:N+(F-N)*(X+1)/H,ranges:I.ranges,inner0:X>0,inner1:X({...I,inner0:!1,inner1:!1})),O=I=>(I[0]-g.a[0])*b[0]+(I[1]-g.a[1])*b[1],D=d(g.a)?p(v[0]):null,P=d(g.b)?p(v[v.length-1]):null;for(let I of C){let N=Ud(g.footprint,g.a,b,I.t0,I.t1);if(N.length<3)continue;let F=I.t1<=1e-6&&I.t0<0?D:I.t0>=R-1e-6?P:null,H=F?x(I.ranges,F):I.ranges,B=(Y,Q)=>Math.abs(O(Y)-Q)<1e-4,X=(Y,Q)=>I.inner0&&B(Y,I.t0)&&B(Q,I.t0)||I.inner1&&B(Y,I.t1)&&B(Q,I.t1),V=(Y,Q)=>!f.points.length||Math.hypot(Y[0]-Q[0],Y[1]-Q[1])>.5?!1:f.points.some(se=>Math.min(Math.hypot(se[0]-Y[0],se[1]-Y[1]),Math.hypot(se[0]-Q[0],se[1]-Q[1]))<.05),re=(Y,Q)=>X(Y,Q)||V(Y,Q),be=A?Math.min(...N.map(([Y,Q])=>S(Y,Q))):M;for(let[Y,Q]of H){let se=Math.min(Q,A?Math.max(...N.map(([st,Te])=>S(st,Te))):Q);if(se-Y<1e-4||be-Y<.01)continue;let Se=Y>.01,le=A&&Q>be,Ie=(st,Te)=>Math.min(Q,S(st,Te));if(Yl+1e-6?Rd+m:cr+m,Te=le&&beMath.min(l,Ie(ht,bt)):Math.min(se,l);Tt(i,N,Y,Te,Os.wall,h,{aoFrom:0,bottom:Se,fold:c+cr+m,topFold:c+st,skipSide:re,sideColor:u?.(N)})}se>l+1e-6&&be>l+1e-6&&Tt(i,N,Math.max(Y,l),le?Ie:se,Os.wall,h,{aoFrom:0,fold:c+m,bottom:Se&&Y>=l,skipSide:re,sideColor:u?.(N)})}}}}function Hp(i,e,t,n=[],r=[],s,o){let{walls:a,open:l}=al(i.rooms,{exterior:e,interior:t},i.walls??[]),c=ov(s),u=!!s,h=uv(i,n),{buckets:f,wallBucket:d}=sv(a),{openings:p,spans:x}=av(i,a,d,c),g=new lt;fv(g,i,a,d,x,c,u,o);let m=Bd(a,a.flatMap(_=>_.footprint)),b=new Wt;b.p.push(...h.holeLines.p),b.c.push(...h.holeLines.c),b.f.push(...h.holeLines.f),cv(b,i,m,d,x,c,u);let v=hv(m.edges,i.rooms,x),y=new Map;op(g,b,i,y,()=>new lt);for(let _ of r)dh(g,b,_.face,_.field,i.elevation);let M=Math.min(i.cut_height,i.height),S=[];for(let _ of i.furniture.filter(w=>!b0(w.type))){let w=g.count,R=b.p.length/6,A=Gt(i,_);Dl(_.type)||Ml(g,b,v,_,A),A+_.h>M+.05&&(Id(g,w,M,Iu),Ld(b,R,M,Iu)),S.push({id:_.id,start:w,end:g.count})}return{floor:h.buffer.geometry(),roomTris:h.roomTris,holes:h.cutHoles,walls:g.geometry(),ghosts:[...y].map(([_,w])=>({opacity:_,geometry:w.geometry()})),lines:b.geometry(),shadow:v.geometry(),buckets:f,openings:p,walls2d:a,openRooms:l,wallBuckets:a.map(_=>d.get(_)),furnitureTris:S,roofUnder:s}}function Wp(i,e){let t=_0(i,e),n=[...e.furniture.filter(a=>a.type==="stairwell").map(ts),...e.furniture.filter(a=>Qu(a)&&a.stair?.down).flatMap(mp)].filter(a=>a.length>=3),r=i.filter(a=>a.elevationl.elevation-a.elevation)[0];if(!r)return fr([...n,...t]);let o=r.furniture.filter(a=>(a.type==="stairs"||vt(a.type)?.hole)&&!(Qu(a)&&a.stair?.down)&&r.elevation+a.h>=e.elevation-.3).flatMap(a=>Qu(a)?mp(a):[ts(a)]).filter(a=>a.length>=3);return fr([...n,...o,...t])}var dv=.12,pv=1.35,Di=(i,e,t)=>Math.min(t,Math.max(e,i)),QR=i=>i<.5?4*i*i*i:1-(-2*i+2)**3/2,mv=i=>({...i,target:i.target.clone()});function gv({target:i,radius:e,theta:t,phi:n}){return new U(i.x+e*Math.sin(n)*Math.sin(t),i.y+e*Math.cos(n),i.z+e*Math.sin(n)*Math.cos(t))}function xv(i,e,t){let n=QR(t);return{target:new U().lerpVectors(i.target,e.target,n),radius:i.radius+(e.radius-i.radius)*n,theta:i.theta+(e.theta-i.theta)*n,phi:i.phi+(e.phi-i.phi)*n}}function bv(i,e){let t=e.theta??i.theta;for(;t-i.theta>Math.PI;)t-=2*Math.PI;for(;t-i.theta<-Math.PI;)t+=2*Math.PI;return{target:(e.target??i.target).clone(),radius:e.radius??i.radius,theta:t,phi:e.phi??i.phi}}function Xp(i,e,t,n,r){let s=2*i.radius*Math.tan(r*Math.PI/360)/(n||1),o=new U(Math.cos(i.theta),0,-Math.sin(i.theta)),a=new U(-Math.sin(i.theta),0,-Math.cos(i.theta));i.target.addScaledVector(o,-e*s),i.target.addScaledVector(a,t*s/Math.max(.35,Math.cos(i.phi)))}function yv(i,e,t,n){let r=n||1,s={theta:-e/r*3.2,phi:-t/r*2.4};return i.theta+=s.theta,i.phi=Di(i.phi+s.phi,dv,pv),s}function _v(i,e){return Math.abs(e.theta)<=1e-4&&Math.abs(e.phi)<=1e-4?!1:(i.theta+=e.theta,i.phi=Di(i.phi+e.phi,dv,pv),e.theta*=.9,e.phi*=.9,!0)}var eC={KeyW:"w",KeyA:"a",KeyS:"s",KeyD:"d",KeyQ:"q",KeyE:"e"},tC=new Set(["w","a","s","d","q","e","arrowup","arrowdown","arrowleft","arrowright"]);function nC(i){let e=i.code?.startsWith("Key")?eC[i.code]??null:i.key.toLowerCase();return e&&tC.has(e)?e:null}var iC=500,rC=400,sC=320,oC=6,vv=1.5,aC=1.8;function lC(i,e){let t=i.keys,n=(t.has("w")||t.has("arrowup")?1:0)-(t.has("s")||t.has("arrowdown")?1:0)-i.stick[1],r=(t.has("d")?1:0)-(t.has("a")?1:0),s=(t.has("arrowleft")||t.has("q")?1:0)-(t.has("arrowright")||t.has("e")?1:0)-i.stick[0];if(!n&&!r&&!s)return!1;let o=e/1e3;i.yaw+=s*aC*o;let[a,l]=[-Math.sin(i.yaw),-Math.cos(i.yaw)],[c,u]=[Math.cos(i.yaw),-Math.sin(i.yaw)];return i.eye.x=Di(i.eye.x+(a*n+c*r)*vv*o,i.bounds.x0,i.bounds.x1),i.eye.z=Di(i.eye.z+(l*n+u*r)*vv*o,i.bounds.z0,i.bounds.z1),!0}var El=class{view={target:new U,radius:16,theta:-.6,phi:.85};minRadius=2;maxRadius=80;locked=!1;walk=null;pointers=new Map;velocity={theta:0,phi:0};flight=null;press=null;lastTap=0;holdTimer;held=!1;grabbing=!1;swiping=null;pinch=null;listeners=[];el;camera;events;constructor(e,t,n){this.el=e,this.camera=t,this.events=n;let r=(l,c,u)=>{e.addEventListener(l,c,u),this.listeners.push([l,c])};r("pointerdown",l=>this.onDown(l)),r("pointermove",l=>this.onMove(l)),r("pointerup",l=>this.onUp(l)),r("pointercancel",l=>this.onUp(l)),r("wheel",l=>this.onWheel(l),{passive:!1}),r("contextmenu",l=>l.preventDefault());let s=l=>c=>{if(!this.walk||c.target?.closest?.("input, textarea, select"))return;let u=nC(c);u&&(c.preventDefault(),l?this.walk.keys.add(u):this.walk.keys.delete(u),this.events.change())},o=s(!0),a=s(!1);window.addEventListener("keydown",o),window.addEventListener("keyup",a),this.listeners.push(["__window_keydown",o],["__window_keyup",a])}dispose(){clearTimeout(this.holdTimer);for(let[e,t]of this.listeners)e.startsWith("__window_")?window.removeEventListener(e.slice(9),t):this.el.removeEventListener(e,t)}get active(){return this.pointers.size>0||this.flight!==null}get busy(){return this.active}update(e){if(this.walk){let n=this.walk,r=lC(n,n.last?Math.min(100,e-n.last):16);n.last=r?e:0;let s=new U(-Math.sin(n.yaw)*Math.cos(n.pitch),Math.sin(n.pitch),-Math.cos(n.yaw)*Math.cos(n.pitch));return this.view.target.copy(n.eye).add(s),this.camera.position.copy(n.eye),this.camera.lookAt(this.view.target),r}let t=!1;if(this.flight){let{from:n,to:r,start:s,duration:o}=this.flight,a=Math.min(1,(e-s)/o);this.view=xv(n,r,a),a>=1&&(this.flight=null),t=!0}else this.pointers.size===0&&(t=_v(this.view,this.velocity));return this.camera.position.copy(gv(this.view)),this.camera.lookAt(this.view.target),t}flyTo(e,t=700){let n=bv(this.view,e),r=mv(this.view);this.velocity={theta:0,phi:0},t<=0||matchMedia("(prefers-reduced-motion: reduce)").matches?(this.view=n,this.flight=null):this.flight={from:r,to:n,start:performance.now(),duration:t},this.events.change()}local(e){let t=this.el.getBoundingClientRect();return[e.clientX-t.left,e.clientY-t.top]}stopMotion(){this.flight=null,this.velocity={theta:0,phi:0}}onDown(e){this.el.setPointerCapture(e.pointerId);let t=this.pointers.size===0;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button}),this.stopMotion(),t&&e.button===0&&this.events.grab?.(...this.local(e))){this.grabbing=!0;return}if(clearTimeout(this.holdTimer),this.held=!1,this.pointers.size===1){this.press={x:e.clientX,y:e.clientY,time:performance.now(),moved:!1};let[n,r]=this.local(e);this.holdTimer=setTimeout(()=>{!this.press||this.press.moved||this.pointers.size!==1||(this.held=!0,this.events.hold(n,r))},iC)}else this.press=null,this.pinch=this.pinchState()}onMove(e){let t=this.pointers.get(e.pointerId);if(!t)return;if(this.grabbing)return void this.events.drag?.(...this.local(e));if(this.swiping)return void this.events.swipeMove?.(e.clientY-this.swiping.startY);let[n,r]=[e.clientX-t.x,e.clientY-t.y];if(this.press&&!this.press.moved&&Math.hypot(e.clientX-this.press.x,e.clientY-this.press.y)>oC){this.press.moved=!0,clearTimeout(this.holdTimer);let[s,o]=this.local({clientX:this.press.x,clientY:this.press.y});if(this.pointers.size===1&&t.button===0&&!e.shiftKey&&this.events.swipeStart?.(s,o,e.clientX-this.press.x,e.clientY-this.press.y))return this.swiping={startY:this.press.y},this.velocity={theta:0,phi:0},void this.events.swipeMove?.(e.clientY-this.press.y)}if(this.locked){[t.x,t.y]=[e.clientX,e.clientY];return}if(this.walk){if(!(this.press&&!this.press.moved)&&this.pointers.size===1){let s=this.el.clientHeight||1;this.walk.yaw+=n/s*2.4,this.walk.pitch=Di(this.walk.pitch+r/s*1.8,-1.1,1.1),this.events.change()}[t.x,t.y]=[e.clientX,e.clientY];return}if(this.pointers.size===1)this.press&&!this.press.moved||(t.button===1||t.button===2||e.shiftKey?Xp(this.view,n,r,this.el.clientHeight,this.camera.fov):this.velocity=yv(this.view,n,r,this.el.clientHeight)),[t.x,t.y]=[e.clientX,e.clientY];else{[t.x,t.y]=[e.clientX,e.clientY];let s=this.pinchState();this.pinch&&s&&(this.zoom(this.pinch.dist/Math.max(1,s.dist)),Xp(this.view,s.mid[0]-this.pinch.mid[0],s.mid[1]-this.pinch.mid[1],this.el.clientHeight,this.camera.fov)),this.pinch=s}this.pointers.size===1&&this.press&&!this.press.moved||this.events.change()}onUp(e){if(this.pointers.has(e.pointerId)){if(this.pointers.delete(e.pointerId),this.grabbing)return this.grabbing=!1,void this.events.drop?.();if(this.swiping)return this.swiping=null,this.press=null,void this.events.swipeEnd?.();if(this.pointers.size<2&&(this.pinch=null),clearTimeout(this.holdTimer),this.held)this.held=!1,this.press=null;else if(this.press&&!this.press.moved&&e.type==="pointerup"&&performance.now()-this.press.timea*n);return{id:`${i.id}:vehicle`,type:e,x:i.x,z:i.z,rotation:i.rotation,w:r,d:s,h:o,variant:i.variant??null,entity:null,power:null}}function bh(i,e){let t=[],n=!1;for(let r of i.furniture){t.push(r);let s=r.type==="parking"?e.get(r.id):void 0,o=s?cC(r,s):null;o&&(t.push(o),n=!0)}return n?{...i,furniture:t}:i}var uC="https://tile.openstreetmap.org/{z}/{x}/{y}.png";var hC=40075016686e-3,yh=Math.PI/180,fC=18,dC=.5,pC=160;function mC(i,e,t){let n=2**t,r=(e+180)/360*n,s=(1-Math.log(Math.tan(i*yh)+1/Math.cos(i*yh))/Math.PI)/2*n;return[r,s]}var gC=(i,e)=>hC*Math.cos(i*yh)/2**e;function Mv(i,e,t,n=pC){let[r,s]=mC(i,e,t),o=gC(i,t),a=n/o,l=2**t-1,c=[];for(let u=Math.floor(s-a);u<=Math.floor(s+a);u++)for(let h=Math.floor(r-a);h<=Math.floor(r+a);h++){if(u<0||u>l)continue;let f=(h%(l+1)+l+1)%(l+1);c.push({x:f,y:u,z:t,east:(h-r)*o,north:-(u-s)*o,size:o})}return c}function Sv(i,e){return i.replace("{z}",String(e.z)).replace("{x}",String(e.x)).replace("{y}",String(e.y)).replace("{s}","abc"[(e.x+e.y)%3])}var wv=i=>i.url&&i.url.startsWith("https://")?i.url:uC;function Tv(i,e,t,n){let r=t*yh;return[n.x+i*Math.cos(r)+e*Math.sin(r),n.z+i*Math.sin(r)-e*Math.cos(r)]}var Av=i=>!!i&&i.on===!0&&Number.isFinite(i.lat)&&Number.isFinite(i.lon),Ev=i=>({x:i.x??0,z:i.z??0,opacity:i.opacity??dC,zoom:i.zoom??fC});var xC="strict-origin-when-cross-origin",Yp=new Map;function Rv(i){let e=Yp.get(i);return e||(e=fetch(i,{referrerPolicy:xC,mode:"cors",credentials:"omit"}).then(async t=>t.ok&&(t.headers.get("content-type")??"").startsWith("image/")?await t.blob():null).catch(()=>null).then(t=>(t||setTimeout(()=>Yp.delete(i),6e4),t)),Yp.set(i,e)),e}var zo=256,bC=Math.PI/180,_h=class{mesh=new we(new sn(1,1),new Ke({transparent:!0,depthWrite:!1,side:ut}));canvas=null;texture=null;key="";generation=0;centre=[0,0];onChange=()=>{};scene;constructor(e){this.scene=e,this.mesh.rotation.order="YXZ",this.mesh.renderOrder=-2,this.mesh.visible=!1,this.mesh.name="live-map",e.add(this.mesh)}set(e,t,n,r=1){if(!Av(e)){this.mesh.visible=!1,this.generation++,this.key="";return}let s=Ev(e),o=wv(e),a=`${e.lat},${e.lon},${s.zoom},${o}`;a!==this.key&&this.load(a,e,s.zoom,o);let[l,c]=this.centre,[u,h]=Tv(l,c,t,s);this.mesh.position.set(u,n,h),this.mesh.rotation.set(-Math.PI/2,-t*bC,0);let f=this.mesh.material;f.opacity=s.opacity,f.color.setScalar(r),this.mesh.visible=this.canvas!==null}load(e,t,n,r){this.key=e;let s=++this.generation,o=Mv(t.lat,t.lon,n);if(!o.length)return;let a=o[0].size,l=Math.min(...o.map(x=>x.east)),c=Math.max(...o.map(x=>x.north)),u=Math.round((Math.max(...o.map(x=>x.east))-l)/a)+1,h=Math.round((c-Math.min(...o.map(x=>x.north)))/a)+1,f=document.createElement("canvas");f.width=u*zo,f.height=h*zo,this.canvas=f,this.texture?.dispose(),this.texture=new zt(f),this.texture.colorSpace=ft,this.texture.anisotropy=4;let d=this.mesh.material;d.map=this.texture,d.needsUpdate=!0,this.mesh.geometry.dispose(),this.mesh.geometry=new sn(u*a,h*a),this.centre=[l+u*a/2,c-h*a/2];let p=f.getContext("2d");if(p)for(let x of o)this.draw(p,x,r,s,Math.round((x.east-l)/a),Math.round((c-x.north)/a))}draw(e,t,n,r,s,o){Rv(Sv(n,t)).then(a=>a?createImageBitmap(a):null).then(a=>{!a||r!==this.generation||(e.drawImage(a,s*zo,o*zo,zo,zo),this.texture&&(this.texture.needsUpdate=!0),this.onChange())})}dispose(){this.generation++,this.scene.remove(this.mesh),this.mesh.geometry.dispose(),this.mesh.material.dispose(),this.texture?.dispose()}};var yC=globalThis,Cv=yC.__nextfloorPluginStore??={plugins:new Map,listeners:new Set},_C=Cv.plugins,XB=Cv.listeners;var vC=5;function MC(i,e){i.errors.lengthNumber.isFinite(a))&&Number.isFinite(r.level)))return i;let o=a=>Math.max(0,Math.min(1,a));return{color:[o(r.color[0]),o(r.color[1]),o(r.color[2])],level:o(r.level)}}catch(r){return MC(n.status,r),i}}var Iv={rainbow:(i,e)=>{let t=(e*.08%1+1)%1,n=r=>Math.max(0,Math.min(1,Math.abs((t*6+r)%6-3)-1));return{color:[n(0),n(4),n(2)],level:i.level}},flicker:(i,e)=>({...i,level:i.level*(.75+.15*Math.sin(e*17)+.1*Math.sin(e*31+1))}),pulse:(i,e)=>({...i,level:i.level*(.65+.35*Math.sin(e*Math.PI))})};function Lv(i,e,t){return!i||!e?i:Object.prototype.hasOwnProperty.call(Iv,e)?Iv[e]?.(i,t)??i:Pv(i,e,t)}var Vo=2043986,Wr=2769520,Fv=2242399,vh=1845831,Ov=1450554,mi=16758087,Nv=1846349,Dv=2572395,Uv=1120816,Bv=1845831,kv=3662079,zv=5995775,Vv=9085695,Xr=Ue(3662079,.08),Gv=1.2,Hv=1.5,Wv=.2,Xv=.52;function Mh(i,e,t,n,r,s){let o=(x,g,m)=>e(x,g,m),{x0:a,x1:l,n0:c,n1:u,y0:h,y1:f}=t,d=x=>Ue(n.getHex(),x),p=[[o(a,c,f),o(l,c,f),o(l,u,f),o(a,u,f),r],[o(a,c,h),o(l,c,h),o(l,u,h),o(a,u,h),d(.6)],[o(a,u,h),o(l,u,h),o(l,u,f),o(a,u,f),n],[o(a,c,h),o(l,c,h),o(l,c,f),o(a,c,f),d(.85)],[o(a,c,h),o(a,u,h),o(a,u,f),o(a,c,f),d(.92)],[o(l,c,h),o(l,u,h),o(l,u,f),o(l,c,f),d(.92)]];for(let[x,g,m,b,v]of p)i.tri(x,g,m,v,v,v,void 0,s),i.tri(x,m,b,v,v,v,void 0,s)}function Vt(i,e,t,n,r,{cut:s,bucket:o}){if(t.y1<=s+1e-6)return Mh(i,e,t,n,r,Xe);if(t.y0>=s-1e-6)return Mh(i,e,t,n,r,o);Mh(i,e,{...t,y1:s},n,r,Xe),Mh(i,e,{...t,y0:s},n,r,o)}function Qn(i,e,t,n,r,s,o,a,{cut:l,bucket:c},u=0){let h=(f,d,p)=>{let x=y=>u?(o-y)/u:.5,[g,m,b,v]=[e(t,r,f),e(n,r,f),e(n,r,d),e(t,r,d)];i.tri(g,m,b,a,a,a,[0,x(f),1,x(f),1,x(d)],p),i.tri(g,b,v,a,a,a,[0,x(f),1,x(d),0,x(d)],p)};o<=l+1e-6?h(s,o,Xe):s>=l-1e-6?h(s,o,c):(h(s,l,Xe),h(l,o,c))}function Yv(i,e,t,n,r,s,o,a,l,c){let[u,h,f,d]=[e(t,r,o),e(n,r,o),e(n,s,o),e(t,s,o)],p=(s-r)/c;i.tri(u,h,f,a,a,a,[0,0,1,0,1,p],l),i.tri(u,f,d,a,a,a,[0,0,1,p,0,p],l)}var wC=16777215,TC=13225686,AC=15722456,qv=.08,$v=.085;function Kv(i){let{info:e,state:t,frame:n,fold:r}=i;if(t.cover===null)return;let[s,o,a]=[e.width,e.sill,e.top],l=e.opening.blind??"roller",c=-e.faceOut,u=e.faceRoom;l==="inside"?Vt(i.frames,n,{x0:-.03,x1:s+.03,n0:u,n1:u+.07,y0:a-.02,y1:a+.07},new W(15921906),new W(16250871),r):Vt(i.frames,n,{x0:-.05,x1:s+.05,n0:c-.15,n1:c,y0:a,y1:a+.2},new W(Ov),new W(Wr),r);let h=t.cover2!=null?[[0,s/2,t.cover],[s/2,s,t.cover2]]:[[0,s,t.cover]];for(let[f,d,p]of h){let x=Math.min(1,Math.max(0,p));if(x<=.01)continue;let g=a-x*(a-o);l==="inside"?Qn(i.blinds,n,f+.01,d-.01,u+.04,g,a-.02,new W(AC),r):l==="venetian"?EC(i,f,d,c-.07,g,a,t.slats??0):Qn(i.blinds,n,f,d,c-.07,g,a,new W(wC),r,.045)}}function EC(i,e,t,n,r,s,o){let{frame:a,fold:l}=i,c=new W(TC),u=Math.PI/2*(.12+.88*Math.min(1,Math.max(0,o))),h=Math.sin(u)*$v/2,f=Math.cos(u)*$v/2;for(let d=s-qv/2;d>r;d-=qv){let p=d>=l.cut?l.bucket:Xe,[x,g,m,b]=[a(e,n-h,d+f),a(t,n-h,d+f),a(t,n+h,d-f),a(e,n+h,d-f)];i.blinds.tri(x,g,m,c,c,c,[0,.5,1,.5,1,.5],p),i.blinds.tri(x,m,b,c,c,c,[0,.5,1,.5,0,.5],p)}}function Zv(i){let{info:e,state:t,frame:n,fold:r}=i,[s,o,a]=[e.width,e.top,Math.min(0,e.sill)],l=e.opening.type==="garage"&&(i.markClosed?!!t.sensed&&(t.cover??1)>=.95:(t.cover??1)<.95),c=l?Ue(mi,.8):new W(Vo),u=l?Ue(mi,1):new W(Wr),[h,f]=[-e.faceOut-.012,e.faceRoom+.012],d=(p,x,g)=>Vt(i.frames,n,{x0:p,x1:x,n0:h,n1:f,y0:g,y1:o+.045},c,u,r);d(-.045,.02,a),d(s-.02,s+.045,a),d(.02,s-.02,o-.02)}function Jv(i){let{info:e,state:t,frame:n,fold:r,mid:s}=i,[o,a,l]=[e.width,e.top,Math.min(0,e.sill)],c=a-l,u=_r(e.opening,e.exterior),h=u==="passage",f=w0(u),d=e.opening.swing==="out"?-1:1,p=d>0?e.faceRoom:-e.faceOut,x=e.opening.leaves===2,g=new W(Vo),m=new W(Wr),b=.02,v=o-.02,y=S0(o,u,e.hingeAtStart,e.opening);if(y){for(let[R,A]of y.panels){let C=(O,D,P,I)=>Vt(i.frames,n,{x0:O,x1:D,n0:s-.03,n1:s+.03,y0:P,y1:I},g,m,r);C(R,R+.04,l+.02,a-.02),C(A-.04,A,l+.02,a-.02),C(R,A,l+.02,l+.1),Qn(i.glass,n,R+.04,A-.04,s,l+.1,a-.02,Xr,r)}b=y.x0,v=y.x1}let M=x?(v-b)/2-.004:v-b,S=f?.06:.04;f&&(Vt(i.frames,n,{x0:.02,x1:o-.02,n0:-e.faceOut-.02,n1:e.faceRoom,y0:l,y1:l+.02},new W(vh),m,r),e.exterior&&Vt(i.frames,n,{x0:o/2-.08,x1:o/2+.08,n0:-e.faceOut-.1,n1:-e.faceOut,y0:a+.1,y1:a+.17},Ue(mi,.55),Ue(mi,.85),{cut:r.cut,bucket:Xe}));let _=e.opening.open_angle?Math.min(180,Math.max(5,e.opening.open_angle))*pt:Hv,w=h?[]:[[e.hingeAtStart,t.open]];x&&!h&&w.push([!e.hingeAtStart,t.open2??0]);for(let[R,A]of w){let C=Math.min(1,Math.max(0,A)),O=u==="sliding"?0:C*_,D=u==="sliding"?C*M:0,P=(Q,se,Se)=>{let le=Q*Math.cos(O)-se*Math.sin(O)-D,Ie=p+d*(se*Math.cos(O)+Q*Math.sin(O)+(D?.05:0));return n(R?b+le:v-le,Ie,Se)},I={cut:r.cut,bucket:C>.05?Xe:r.bucket},N=i.markClosed?!!t.sensed&&C<.05:C>.9&&!(R===e.hingeAtStart&&t.assumed),F=N?Ue(mi,.7):new W(f?Uv:Nv),H=N?Ue(mi,.9):new W(f?Bv:Dv),B=(Q,se,Se,le,Ie=-S,st=0)=>Vt(i.frames,P,{x0:Q,x1:se,n0:Ie,n1:st,y0:Se,y1:le},F,H,I);u==="glass"?(B(0,.05,l+.01,a-.01),B(M-.05,M,l+.01,a-.01),B(.05,M-.05,l+.01,l+.12),B(.05,M-.05,a-.08,a-.01),Qn(i.glass,P,.05,M-.05,-S/2,l+.12,a-.08,Xr,I)):B(0,M,l+.01,a-.01),u==="front_glass"?Qn(i.glass,P,.12,M-.12,.001,l+c*.55,a-.18,Xr,I):f&&Qn(i.glass,P,.1,.18,.001,l+.3,a-.3,Xr,I);let X=l+Math.min(1.05,c*.5),V=f?.3:.012,[re,be]=f?[M-.11,M-.08]:[M-.16,M-.05],Y=(Q,se)=>Vt(i.frames,P,{x0:re,x1:be,n0:Q,n1:se,y0:X-V,y1:X+V},new W(zv),new W(Vv),I);if(Y(.004,.05),Y(-S-.05,-S-.004),t.unlocked){let Q=new W(kv);Vt(i.frames,P,{x0:M-.012,x1:M+.004,n0:-S-.004,n1:.004,y0:l+.06,y1:a-.06},Q,Q,{cut:r.cut,bucket:Xe})}}}function jv(i){let{info:e,state:t,frame:n,fold:r}=i,[s,o,a]=[e.width,e.top,Math.min(0,e.sill)],l=Math.min(1,Math.max(0,t.cover??1)),c=new W(13951231),u=e.faceRoom-.03;l>.01&&Qn(i.blinds,n,.02,s-.02,u,a+(o-a)*(1-l),o,c,r,.5);let h=(1-l)*(o-a);h>.01&&Yv(i.blinds,n,.02,s-.02,u,u+h,o+.03,c,r.bucket,.5)}var RC=4936290,CC=7041926,Qv=2764860,eM=9082024;function tM(i,e){let{info:t}=i;return t.opening.type!=="window"||!t.exterior||t.opening.light_well===!1?!1:t.opening.light_well===!0||t.sillVt(i.frames,n,{x0:m,x1:b,n0:v,n1:y,y0:c,y1:u},h,f,r);p(s-d,s,a-l,a),p(o,o+d,a-l,a),p(s-d,o+d,a-l-d,a-l),Vt(i.frames,n,{x0:s,x1:o,n0:a-l,n1:a,y0:c-d,y1:c},h,f,r);let x=(m,b)=>Vt(i.frames,n,{x0:m,x1:b,n0:a-l,n1:a,y0:u-.025,y1:u},new W(Qv),new W(eM),r),g=Math.max(3,Math.round((o-s)/.06));for(let m=0;m<=g;m++){let b=s+(o-s)*m/g;x(b-.008,b+.008)}Vt(i.frames,n,{x0:s,x1:o,n0:a-l-.01,n1:a-l+.02,y0:u-.03,y1:u},new W(Qv),new W(eM),r)}var Ns={open:0,open2:0,tilt:0,tilt2:0,cover:null};function iM(i){let{info:e,frame:t,fold:n,mid:r}=i,[s,o,a]=[e.width,e.sill,e.top],[l,c]=[.04,.025],u=new W(Vo),h=new W(Wr),f=(b,v,y,M)=>Vt(i.frames,t,{x0:b,x1:v,n0:r-c,n1:r+c,y0:y,y1:M},u,h,n);i.first&&f(0,l,o,a),i.last&&f(s-l,s,o,a);let[d,p]=[i.first?l:-i.over[0],i.last?s-l:s+i.over[1]];f(d,p,o,o+.03),f(d,p,a-l,a);let x=e.opening.front?0:e.opening.panes,g=Math.max(1,x==null?Math.max(1,Math.round((p-d)/.9)):Math.round(x)),m=(p-d)/g;for(let b=1;bVt(i.frames,n,{x0:A,x1:C,n0:s-u,n1:s+u,y0:O,y1:D},h,f,r),x=a+(a>.05?c:.03);p(0,c,a,l),p(o-c,o,a,l),p(c,o-c,a,x),p(c,o-c,l-c,l);let g=e.opening.sill_boards??"auto";g!=="none"&&(g!=="auto"||a>.3)&&(g!=="outside"&&Vt(i.frames,n,{x0:-.04,x1:o+.04,n0:s+u,n1:e.faceRoom+.07,y0:a-.03,y1:a},d,f,r),e.exterior&&g!=="inside"&&Vt(i.frames,n,{x0:-.03,x1:o+.03,n0:-e.faceOut-.06,n1:s-u,y0:a-.04,y1:a-.02},d,f,r));let m=.055,[b,v]=[x,l-c],[y,M]=[s+u,s+u+.06],S=e.hingeAtStart,_=e.opening.opens??"turn",w=_==="slide"?PC(o,c,S,e.opening.leaves,t.open,t.open2??0):e.opening.leaves===2?[{atStart:S,x0:S?c:o/2,x1:S?o/2:o-c,open:t.open,tilt:t.tilt},{atStart:!S,x0:S?o/2:c,x1:S?o-c:o/2,open:t.open2??0,tilt:t.tilt2??0}]:[{atStart:S,x0:c,x1:o-c,open:t.open,tilt:t.tilt}],R=_r(e.opening,e.exterior);for(let A of w){let C=_==="top"?Math.max(A.open,A.tilt)*Xv:0,D=(_!=="slide"||!!A.slide)&&(A.open>.02||A.tilt>.02),P=i.markClosed?!!t.sensed&&!D:D,I=P?Ue(mi,.75):new W(Fv),N=P?Ue(mi,.95):f,F=A.x1-A.x0,H=_==="turn",B=H?A.open*Gv:0,X=H?A.tilt*Wv:0,V=(A.slide??0)*A.open,re=_==="slide"&&A.track===0?-.065:0,be=(se,Se,le)=>{if(C>0){let[et,Yt]=[Se-y,le-v],[kt,on]=[Math.cos(C),Math.sin(C)];return n(A.atStart?A.x0+se:A.x1-se,y+et*kt+Yt*on,v-et*on+Yt*kt)}let Ie=le-b,st=Se+Ie*Math.sin(X)+re,Te=b+Ie*Math.cos(X),ht=se*Math.cos(B)-(st-y)*Math.sin(B),bt=y+(st-y)*Math.cos(B)+se*Math.sin(B);return n((A.atStart?A.x0+ht:A.x1-ht)+V,bt,Te)},Y={cut:r.cut,bucket:B>.05||C>.05?Xe:r.bucket},Q=(se,Se,le,Ie,st=y,Te=M)=>Vt(i.frames,be,{x0:se,x1:Se,n0:st,n1:Te,y0:le,y1:Ie},I,N,Y);if(Q(0,m,b,v),Q(F-m,F,b,v),Q(m,F-m,b,b+m),Q(m,F-m,v-m,v),Qn(i.glass,be,m,F-m,(y+M)/2,b+m,v-m,P?Ue(mi,.16):Xr,Y),R==="bars"){let[se,Se]=[(b+v)/2,(y+M)/2];Q(m,F-m,se-.012,se+.012,Se-.012,Se+.012),Q(F/2-.012,F/2+.012,b+m,v-m,Se-.012,Se+.012)}}}var qp=i=>i.opening.front??i.opening.id;function $p(i,e,t,n=-1/0){let r=new lt,s=new lt,o=new lt(!0),a=[],l=[],c=[],u=new Map;i.forEach((x,g)=>{let m=qp(x);u.set(m,[...u.get(m)??[],g])});let h=x=>[[x.start[0],x.start[1]],[x.start[0]+x.axis[0]*x.width,x.start[1]+x.axis[1]*x.width]],f=x=>`${Math.round(x[0]*50)},${Math.round(x[1]*50)}`,d=new Map,p=new Map;for(let x of u.values()){let g=new Map,m=new Map;for(let v of x){let[y,M]=h(i[v]);g.set(f(y),[...g.get(f(y))??[],v]),m.set(f(M),[...m.get(f(M))??[],v])}let b=(v,y)=>{if(y==null||y===v)return 0;let M=Math.abs((i[v].faceRoom-i[v].faceOut)/2),[S,_]=[i[v].axis,i[y].axis],w=Math.max(-1,Math.min(1,S[0]*_[0]+S[1]*_[1])),R=Math.acos(w);return Rw!==v),_=(g.get(f(M))??[]).find(w=>w!==v);d.set(v,[S==null,_==null]),p.set(v,[b(v,S),b(v,_)])}}for(let x=0;x[g.start[0]+g.axis[0]*w+g.toRoom[0]*R,A,g.start[1]+g.axis[1]*w+g.toRoom[1]*R],mid:(g.faceRoom-g.faceOut)/2,markClosed:g.opening.mark==="closed",fold:{cut:t,bucket:g.bucket},frames:r,glass:s,blinds:o,first:y,last:M,over:p.get(x)??[0,0]};(b==="door"&&v!=="passage"||b==="garage")&&Zv(S),b==="door"?Jv(S):b==="garage"?jv(S):v==="glass_wall"?iM(S):rM(S),tM(S,n)&&nM(S,n),b!=="garage"&&Kv(S);let _=qp(g);a.push({id:_,start:m.frames,end:r.count}),l.push({id:_,start:m.glass,end:s.count}),c.push({id:_,start:m.blinds,end:o.count})}return{frames:r.geometry(),glass:s.geometry(),blinds:o.geometry(),frameTris:a,glassTris:l,blindTris:c}}var Kp=Math.PI/180,Rl=2400,Go=1600,Zp=9,sM=360;function Sh(i,e=64){let t=document.createElement("canvas");t.width=t.height=e;let n=t.getContext("2d"),r=n.createRadialGradient(e/2,e/2,0,e/2,e/2,e/2);for(let[s,o]of i)r.addColorStop(s,o);return n.fillStyle=r,n.fillRect(0,0,e,e),new zt(t)}function IC(i){let t=document.createElement("canvas");t.width=128,t.height=128/2;let n=t.getContext("2d"),r=i*9301+49297,s=()=>(r=(r*9301+49297)%233280)/233280;for(let o=0;o<7;o++){let a=128*(.2+.6*s()),l=128/2*(.45+.25*s()),c=128*(.12+.14*s()),u=n.createRadialGradient(a,l,0,a,l,c);u.addColorStop(0,"rgba(255,255,255,0.9)"),u.addColorStop(.6,"rgba(255,255,255,0.45)"),u.addColorStop(1,"rgba(255,255,255,0)"),n.fillStyle=u,n.fillRect(0,0,128,128/2)}return new zt(t)}var wh=class{group=new ct;scene;bounds={x0:-10,x1:10,z0:-10,z1:10,y0:0,y1:8};view=null;rain;rainVel=new Float32Array(Rl*3);snow;snowPhase=new Float32Array(Go);hail;clouds=[];bolt;disc;halo;stars;cover;last=0;nextBolt=0;boltUntil=0;onFlash=null;constructor(e){this.scene=e,this.group.name="live-weather",this.group.renderOrder=5;let t=new Fe;t.setAttribute("position",new ke(new Float32Array(Rl*6),3)),this.rain=new gn(t,new Lt({color:11128309,transparent:!0,opacity:.5,depthWrite:!1}));let n=Sh([[0,"rgba(255,255,255,1)"],[.5,"rgba(255,255,255,0.6)"],[1,"rgba(255,255,255,0)"]],32),r=new Fe;r.setAttribute("position",new ke(new Float32Array(Go*3),3)),this.snow=new xn(r,new cn({color:16185855,size:.16,map:n,transparent:!0,opacity:.9,depthWrite:!1}));for(let h=0;h.02,this.stars.position.set((n.x0+n.x1)/2,n.y0,(n.z0+n.z1)/2),this.stars.scale.setScalar(r*3);let a=this.cover.material,l=(t?.snow??0)+(t?.hail??0)*.5,c=t?.rain??0;a.color.setHex(l>.05?16054527:1848656),a.opacity=l>.05?.3+.45*Math.min(1,l):c>.1?.25*Math.min(1,c):0,this.cover.visible=a.opacity>.02,this.cover.position.set((n.x0+n.x1)/2,n.y0-.18,(n.z0+n.z1)/2),this.cover.scale.set(n.x1-n.x0,n.z1-n.z0,1)}set(e){let t=this.view;this.view=e,this.group.visible=!!e;let n=e?.weather??null;if(e&&n&&n.fog>.02&&!e.low){let r=new W(e.sky[0]/255,e.sky[1]/255,e.sky[2]/255);this.scene.fog=new ls(r,.008+.04*n.fog)}else this.scene.fog instanceof ls&&(this.scene.fog=null);(!t||t.low!==e?.low||!!t.weather!=!!n)&&this.seed(),this.placeDisc(),this.placeNight(),n?.lightning||this.endBolt()}windVector(){let e=this.view?.weather;if(!e)return[0,0];let n=((e.windFrom??270)+(this.view?.north??0)+180)*Kp,r=.4+7*e.wind;return[Math.sin(n)*r,-Math.cos(n)*r]}count(e,t){let n=this.view?.low??!1;return Math.round(Math.min(1,e)*t*(n?.3:1))}seed(){let e=this.bounds,t=this.view?.weather,n=()=>e.x0+Math.random()*(e.x1-e.x0),r=()=>e.z0+Math.random()*(e.z1-e.z0),s=()=>e.y0+Math.random()*(e.y1-e.y0),o=this.rain.geometry.getAttribute("position");for(let c=0;c.01,this.snow.visible=!!t&&t.snow>.01,this.hail.visible=!!t&&t.hail>.01,this.clouds.forEach((c,u)=>{c.angle=u/Zp*Math.PI*2+Math.random()*.5,c.ring=1.7+Math.random()*.9,c.lift=.35+Math.random()*.35,c.scale=.55+Math.random()*.45,c.sx=e.x0+Math.random()*(e.x1-e.x0),c.sz=e.z0+Math.random()*(e.z1-e.z0)}),this.placeClouds(0)}placeClouds(e){let t=this.view,n=t?.weather,r=n?.cloud??0,s=this.bounds,o=(s.x0+s.x1)/2,a=(s.z0+s.z1)/2,l=Math.max(s.x1-s.x0,s.z1-s.z0),[c,u]=this.windVector(),h=Math.round(r*Zp),f=t?.sky??[20,28,44],d=(f[0]+f[1]+f[2])/765,p=n?.rain||n?.lightning?.3:0,x=Math.max(.12,Math.min(1,.28+d*.9-p-.25*Math.max(0,r-.6))),g=Math.hypot(c,u)/Math.max(20,l*4)*e*Math.sign(c||1);this.clouds.forEach((m,b)=>{let v=bs.x1+S&&(m.sx=s.x0-S),m.sxs.z1+S&&(m.sz=s.z0-S),m.sz.9||!r&&t.elevation<.5){this.disc.visible=this.halo.visible=!1;return}let s=this.bounds,o=new U((s.x0+s.x1)/2,s.y0,(s.z0+s.z1)/2),a=Math.max(70,Math.max(s.x1-s.x0,s.z1-s.z0)*3.5),l=((r?t.azimuth+180:t.azimuth)+e.north)*Kp,c=Math.max(8,Math.abs(t.elevation))*Kp,u=new U(Math.sin(l)*Math.cos(c),Math.sin(c),-Math.cos(l)*Math.cos(c)),h=o.addScaledVector(u,a),f=a*(r?.07:.1);this.disc.position.copy(h),this.halo.position.copy(h),this.disc.scale.setScalar(f),this.halo.scale.setScalar(f*3.2);let d=this.disc.material,p=this.halo.material,x=r?0:Math.max(0,1-t.elevation/20);d.color.set(r?14016242:new W(1,.9-.25*x,.6-.35*x)),p.color.copy(d.color),d.opacity=(r?.7:.95)*(1-n),p.opacity=(r?.35:.6)*(1-n),this.disc.visible=this.halo.visible=!0}endBolt(){this.bolt.visible&&(this.bolt.visible=!1,this.onFlash?.(!1))}strike(e){let t=this.bounds,r=(Math.random()<.5?-1:1)<0?t.x0-2-Math.random()*6:t.x1+2+Math.random()*6,s=t.z0+Math.random()*(t.z1-t.z0),o=t.y1+4,a=this.bolt.geometry.getAttribute("position"),l=24,c=o;for(let u=0;u.01&&this.placeClouds(r),n.lightning&&!t.low?(this.nextBolt||(this.nextBolt=e+2500+Math.random()*6e3),e>=this.nextBolt&&(this.strike(e),this.nextBolt=e+3500+Math.random()*9e3),this.bolt.visible&&e>this.boltUntil&&this.endBolt()):this.nextBolt=0,this.rain.visible||this.snow.visible||this.hail.visible||n.cloud>.01||n.lightning}dispose(){this.endBolt(),this.group.traverse(e=>{let t=e;t.geometry?.dispose();let n=t.material;n?.map?.dispose(),n?.dispose()}),this.scene.remove(this.group),this.scene.fog instanceof ls&&(this.scene.fog=null)}};var Th=46,Ah=33,Ds=900;function Jp(){let i=document.createElement("canvas");i.width=i.height=32;let e=i.getContext("2d"),t=e.createRadialGradient(16,16,0,16,16,16);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.35,"rgba(255,255,255,0.7)"),t.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=t,e.fillRect(0,0,32,32),new zt(i)}var Eh=class{group=new ct;scene;lift;tex=Jp();arcs=new Map;sparkFields=[];sparks;sparkBase=new Float32Array(Ds*3);sparkField=new Int16Array(Ds);sparkPhase=new Float32Array(Ds);sparkCount=0;last=0;constructor(e,t){this.scene=e,this.lift=t,this.group.name="live-energy";let n=new Fe;n.setAttribute("position",new ke(new Float32Array(Ds*3),3)),n.setAttribute("color",new ke(new Float32Array(Ds*3),3)),this.sparks=new xn(n,new cn({size:.4,map:this.tex,vertexColors:!0,transparent:!0,depthWrite:!1,blending:Ft})),this.sparks.frustumCulled=!1,this.group.add(this.sparks),e.add(this.group)}get active(){return this.arcs.size>0||this.sparkCount>0}setArcs(e){let t=new Set(e.map(n=>n.key));for(let[n,r]of this.arcs)t.has(n)||(this.group.remove(r.line,r.points),r.line.geometry.dispose(),r.line.material.dispose(),r.points.geometry.dispose(),r.points.material.dispose(),this.arcs.delete(n));for(let n of e){let r=this.arcs.get(n.key);if(!r){let o=new Fe;o.setAttribute("position",new ke(new Float32Array(Ah*3),3));let a=new Pn(o,new Lt({transparent:!0,opacity:.4,depthWrite:!1,blending:Ft})),l=new Fe;l.setAttribute("position",new ke(new Float32Array(Th*3),3));let c=new xn(l,new cn({size:.55,map:this.tex,transparent:!0,depthWrite:!1,blending:Ft}));a.frustumCulled=c.frustumCulled=!1;let u=new Float32Array(Th);for(let h=0;hnew U):null,r.points.material.color.copy(s),r.count=n.power<=0?0:Math.max(3,Math.min(Th,Math.round(3+Math.sqrt(n.power)/2.2))),r.speed=.18+Math.min(.5,Math.log10(1+n.power)*.1),r.points.geometry.setDrawRange(0,r.count)}this.place()}setSparks(e){this.sparkFields=e;let t=e.reduce((r,s)=>r+s.quads.length*s.level,0),n=0;t>0&&e.forEach((r,s)=>{if(r.level<=0)return;let o=Math.round(Ds*r.quads.length*r.level/Math.max(t,e.reduce((a,l)=>a+l.quads.length,0)));for(let a=0;a0}world(e,t){let n=this.lift(e.floorId);return t.set(e.x,n.y+e.y,e.z),n.visible}place(){for(let e of this.arcs.values()){if(e.path){this.placeRoute(e,e.path);continue}let t=this.world(e.arc.from,e.a),n=this.world(e.arc.to,e.b),r=e.a.distanceTo(e.b);e.c.copy(e.a).add(e.b).multiplyScalar(.5),e.c.y=Math.max(e.a.y,e.b.y)+.6+r*.22;let s=t&&n;e.line.visible=e.points.visible=s;let o=e.line.geometry.getAttribute("position");for(let a=0;ar=this.world(o,t[a])&&r),e.line.visible=e.points.visible=r,e.along=[0];for(let o=1;os.setXYZ(a,o.x,o.y,o.z)),e.line.geometry.setDrawRange(0,t.length),s.needsUpdate=!0}at(e,t){if(!e.path)return this.bezier(e,t);let n=e.along[e.along.length-1]||1,r=t*n,s=1;for(;s0}set(e,t){let n=new Set(e.map(r=>r.id));for(let[r,s]of this.spots)if(!n.has(r)){for(let o of s.rings)this.group.remove(o),o.material.dispose();this.spots.delete(r)}for(let r of e){let s=this.spots.get(r.id);if(!s){let a=Array.from({length:oM},()=>{let l=new we(this.ringGeo,new Ke({transparent:!0,opacity:0,depthWrite:!1,blending:Ft,side:ut}));return l.rotation.x=-Math.PI/2,l.frustumCulled=!1,this.group.add(l),l});s={spot:r,rings:a},this.spots.set(r.id,s)}s.spot=r;let o=new W(r.color[0]/255,r.color[1]/255,r.color[2]/255);for(let a of s.rings)a.material.color.copy(o)}for(let r of this.links)this.group.remove(r.line),r.line.geometry.dispose(),r.line.material.dispose();this.links=t.map(([r,s])=>{let o=new Fe;o.setAttribute("position",new ke(new Float32Array(51),3));let a=new Pn(o,new Lt({color:12616956,transparent:!0,opacity:.55,depthWrite:!1,blending:Ft}));return a.frustumCulled=!1,this.group.add(a),{a:r,b:s,line:a}})}step(e){if(!this.spots.size&&!this.links.length)return!1;let t=e/1e3;for(let n of this.spots.values()){let r=this.lift(n.spot.at.floorId),s=.9+1.6*n.spot.level;n.rings.forEach((o,a)=>{let l=(t*.55+a/oM)%1;o.visible=r.visible,o.position.set(n.spot.at.x,r.y+n.spot.at.y,n.spot.at.z),o.scale.setScalar((.25+l*s)*(n.spot.size??1)),o.material.opacity=(1-l)*(.35+.5*n.spot.level)})}for(let n of this.links){let r=this.lift(n.a.floorId),s=this.lift(n.b.floorId);n.line.visible=r.visible&&s.visible;let o=n.line.geometry.getAttribute("position"),a=r.y+n.a.y,l=s.y+n.b.y,c=Math.hypot(n.a.x-n.b.x,n.a.z-n.b.z);for(let u=0;u<=16;u++){let h=u/16,f=Math.sin(Math.PI*h)*(.3+c*.12)+Math.sin(t*3+h*12)*.03;o.setXYZ(u,n.a.x+(n.b.x-n.a.x)*h,a+(l-a)*h+f,n.a.z+(n.b.z-n.a.z)*h)}o.needsUpdate=!0}return!0}dispose(){this.set([],[]),this.ringGeo.dispose(),this.scene.remove(this.group)}};var Ch=6,lM=24,aM=Ch*lM;function LC(i,e,t){let n=i%Ch,r=Math.floor(i/Ch),s=(r/lM+e*.7)%1,o=n/Ch*Math.PI*2+e*.35+(r*7%5-2)*.012,a=s*t,l=Math.min(1.2,t/3);return[Math.cos(o)*a,4*l*s*(1-s),Math.sin(o)*a]}var Ph=class{group=new ct;scene;lift;tex=Jp();material=new cn({color:11068159,size:.09,map:this.tex,transparent:!0,opacity:.9,depthWrite:!1});sprays=new Map;constructor(e,t){this.scene=e,this.lift=t,this.group.name="live-water",e.add(this.group)}get active(){return this.sprays.size>0}set(e){let t=new Set(e.map(n=>n.id));for(let[n,r]of this.sprays)t.has(n)||(this.group.remove(r.points),r.points.geometry.dispose(),this.sprays.delete(n));for(let n of e){let r=this.sprays.get(n.id);if(r){r.spot=n;continue}let s=new Fe;s.setAttribute("position",new ke(new Float32Array(aM*3),3));let o=new xn(s,this.material);o.frustumCulled=!1,this.group.add(o),this.sprays.set(n.id,{spot:n,points:o})}}step(e){if(!this.sprays.size)return!1;let t=e/1e3;for(let n of this.sprays.values()){let r=this.lift(n.spot.at.floorId);n.points.visible=r.visible,n.points.position.set(n.spot.at.x,r.y+n.spot.at.y,n.spot.at.z);let s=n.points.geometry.getAttribute("position");for(let o=0;oe.s.playing)}set(e){let t=new Set(e.map(n=>n.id));for(let[n,r]of this.views)t.has(n)||this.drop(n,r);for(let n of e){let r=this.views.get(n.id);if(!r){let o=document.createElement("canvas");o.width=512,o.height=288;let a=new zt(o);a.colorSpace=ft;let l=new we(new sn(1,1),new Ke({map:a,transparent:!0,toneMapped:!1}));l.renderOrder=6;let c=new we(new sn(1,1),new Ke({map:this.glowTex,transparent:!0,depthWrite:!1,blending:Ft,side:ut}));c.renderOrder=2,this.group.add(l,c),r={s:n,sig:"",screen:l,glow:c,canvas:o,texture:a,image:null},this.views.set(n.id,r)}r.s=n;let s=[n.title,n.subtitle,n.app,n.picture,n.color.join(","),n.playing].join("|");if(s!==r.sig){let o=r.sig.split("|")[3]!==(n.picture??"");r.sig=s,o&&this.loadPicture(r),this.draw(r)}this.place(r)}}loadPicture(e){e.image=null;let t=e.s.picture;if(!t)return;let n=new Image;n.crossOrigin="anonymous",n.onload=()=>{e.s.picture!==t||!this.views.has(e.s.id)||(e.image=n,this.draw(e),this.onChange?.())},n.src=t}draw(e){let t=e.s,n=e.canvas.getContext("2d"),r=e.canvas.width,s=e.canvas.height,[o,a,l]=t.color,c=n.createLinearGradient(0,0,r,s);c.addColorStop(0,`rgb(${Math.round(o*.35)},${Math.round(a*.35)},${Math.round(l*.35)})`),c.addColorStop(1,"rgb(6,9,18)"),n.fillStyle=c,n.fillRect(0,0,r,s);let u=22,h=u;if(e.image){let f=s-u*2-30;n.save(),n.shadowColor=`rgba(${o},${a},${l},0.7)`,n.shadowBlur=24;let d=e.image.naturalWidth||1,p=e.image.naturalHeight||1,x=Math.max(f/d,f/p),g=f/x,m=f/x;n.drawImage(e.image,(d-g)/2,(p-m)/2,g,m,u,u,f,f),n.restore(),h=u*2+f}n.fillStyle="#ffffff",n.font="600 34px Figtree, Roboto, sans-serif",this.text(n,t.title||t.app||"",h,s/2-18,r-h-u),n.fillStyle="rgba(230,240,255,0.75)",n.font="26px Figtree, Roboto, sans-serif",this.text(n,t.subtitle,h,s/2+22,r-h-u),t.app&&(n.fillStyle=`rgb(${o},${a},${l})`,n.font="700 22px Figtree, Roboto, sans-serif",this.text(n,(t.playing?"\u25B6 ":"\u275A\u275A ")+t.app,h,s-u-14,r-h-u)),n.fillStyle=`rgba(${o},${a},${l},0.9)`,n.fillRect(0,s-6,r*(t.playing?1:.4),6),e.texture.needsUpdate=!0}text(e,t,n,r,s){let o=t;for(;o.length>1&&e.measureText(o).width>s;)o=o.slice(0,-2);e.fillText(o===t?o:`${o}\u2026`,n,r)}place(e){let t=e.s,n=t.rect,r=t.rotation*FC,s=this.lift(t.floorId),o=(n.x0+n.x1)/2,a=(p,x)=>[t.x+p*Math.cos(r)-x*Math.sin(r),t.z+p*Math.sin(r)+x*Math.cos(r)],l=n.x1-n.x0,c=n.y1-n.y0,[u,h]=a(o,n.z+.012);e.screen.position.set(u,s.y+(n.y0+n.y1)/2,h),e.screen.rotation.set(0,-r,0),e.screen.scale.set(l,c,1);let[f,d]=a(o,n.z-.18);e.glow.position.set(f,s.y+(n.y0+n.y1)/2,d),e.glow.rotation.set(0,-r,0),e.glow.scale.set(l*2.4,c*2.6,1),e.glow.material.color=new W(t.color[0]/255,t.color[1]/255,t.color[2]/255),e.screen.visible=s.visible,e.glow.visible=s.visible&&(t.ambilight??1)>0}step(e){let t=!1;for(let n of this.views.values()){this.place(n);let r=n.glow.material;r.opacity=(n.s.playing?.55+.25*Math.sin(e/900+n.s.x):.25)*Math.min(1.5,n.s.ambilight??1),t||=n.s.playing}return t}drop(e,t){this.group.remove(t.screen,t.glow),t.screen.geometry.dispose(),t.screen.material.dispose(),t.texture.dispose(),t.glow.geometry.dispose(),t.glow.material.dispose(),this.views.delete(e)}dispose(){for(let[e,t]of this.views)this.drop(e,t);this.glowTex.dispose(),this.scene.remove(this.group)}};var NC=Math.PI/180,DC="#f4f1ea",Lh=class{group=new ct;scene;lift;views=new Map;onChange=null;constructor(e,t){this.scene=e,this.lift=t,this.group.name="live-pictures",e.add(this.group)}set(e){let t=new Set(e.map(n=>n.id));for(let[n,r]of this.views)t.has(n)||this.drop(n,r);for(let n of e){let r=this.views.get(n.id);if(!r){let c=document.createElement("canvas"),u=new zt(c);u.colorSpace=ft;let h=new we(new sn(1,1),new Ke({map:u,toneMapped:!1}));h.renderOrder=5,this.group.add(h),r={p:n,sig:"",mesh:h,canvas:c,texture:u,image:null},this.views.set(n.id,r)}let s=r.p.url!==n.url||!r.sig;r.p=n;let o=n.rect.x1-n.rect.x0,a=n.rect.y1-n.rect.y0,l=[n.url,n.border,n.fit,o.toFixed(3),a.toFixed(3)].join("|");l!==r.sig&&(r.sig=l,s&&this.load(r),this.draw(r)),this.place(r)}}load(e){e.image=null;let t=e.p.url,n=new Image;n.crossOrigin="anonymous",n.onload=()=>{e.p.url!==t||!this.views.has(e.p.id)||(e.image=n,this.draw(e),this.onChange?.())},n.src=t}draw(e){let t=e.p,n=Math.max(.01,t.rect.x1-t.rect.x0),r=Math.max(.01,t.rect.y1-t.rect.y0),s=600/Math.max(n,r),o=e.canvas.width=Math.max(16,Math.round(n*s)),a=e.canvas.height=Math.max(16,Math.round(r*s)),l=e.canvas.getContext("2d");l.fillStyle=t.border>0?DC:"#20242c",l.fillRect(0,0,o,a);let c=Math.round(Math.min(o,a)*Math.min(40,Math.max(0,t.border))/100),[u,h,f,d]=[c,c,o-2*c,a-2*c];if(e.image&&f>4&&d>4){let p=e.image.naturalWidth||1,x=e.image.naturalHeight||1;if(t.fit==="contain"){let g=Math.min(f/p,d/x);l.drawImage(e.image,u+(f-p*g)/2,h+(d-x*g)/2,p*g,x*g)}else{let g=Math.max(f/p,d/x),m=f/g,b=d/g;l.drawImage(e.image,(p-m)/2,(x-b)/2,m,b,u,h,f,d)}c>0&&(l.strokeStyle="rgba(0,0,0,0.25)",l.lineWidth=Math.max(1,c*.04),l.strokeRect(u,h,f,d))}else f>4&&d>4&&(l.fillStyle="#3a4250",l.fillRect(u,h,f,d));e.texture.needsUpdate=!0}place(e){let t=e.p,n=t.rect,r=t.rotation*NC,s=this.lift(t.floorId),o=(n.x0+n.x1)/2,a=n.z+.004;e.mesh.position.set(t.x+o*Math.cos(r)-a*Math.sin(r),s.y+(n.y0+n.y1)/2,t.z+o*Math.sin(r)+a*Math.cos(r)),e.mesh.rotation.set(0,-r,0),e.mesh.scale.set(n.x1-n.x0,n.y1-n.y0,1),e.mesh.visible=s.visible}step(){for(let e of this.views.values())this.place(e);return!1}drop(e,t){this.group.remove(t.mesh),t.mesh.geometry.dispose(),t.mesh.material.dispose(),t.texture.dispose(),this.views.delete(e)}dispose(){for(let[e,t]of this.views)this.drop(e,t);this.scene.remove(this.group)}};var Fh=class extends Tn{constructor(){super(),this.name="RoomEnvironment",this.position.y=-3.5;let e=new Fr;e.deleteAttribute("uv");let t=new In({side:un}),n=new In,r=new ps(16777215,900,28,2);r.position.set(.418,16.199,.3),this.add(r);let s=new we(e,t);s.position.set(-.757,13.219,.717),s.scale.set(31.713,28.305,28.591),this.add(s);let o=new hs(e,n,6),a=new Et;a.position.set(-10.906,2.009,1.846),a.rotation.set(0,-.195,0),a.scale.set(2.328,7.905,4.651),a.updateMatrix(),o.setMatrixAt(0,a.matrix),a.position.set(-5.607,-.754,-.758),a.rotation.set(0,.994,0),a.scale.set(1.97,1.534,3.955),a.updateMatrix(),o.setMatrixAt(1,a.matrix),a.position.set(6.167,.857,7.803),a.rotation.set(0,.561,0),a.scale.set(3.927,6.285,3.687),a.updateMatrix(),o.setMatrixAt(2,a.matrix),a.position.set(-2.017,.018,6.124),a.rotation.set(0,.333,0),a.scale.set(2.002,4.566,2.064),a.updateMatrix(),o.setMatrixAt(3,a.matrix),a.position.set(2.291,-.756,-2.621),a.rotation.set(0,-.286,0),a.scale.set(1.546,1.552,1.496),a.updateMatrix(),o.setMatrixAt(4,a.matrix),a.position.set(-2.193,-.369,-5.547),a.rotation.set(0,.516,0),a.scale.set(3.875,3.487,2.986),a.updateMatrix(),o.setMatrixAt(5,a.matrix),this.add(o);let l=new we(e,Ho(50));l.position.set(-16.116,14.37,8.208),l.scale.set(.1,2.428,2.739),this.add(l);let c=new we(e,Ho(50));c.position.set(-16.109,18.021,-8.207),c.scale.set(.1,2.425,2.751),this.add(c);let u=new we(e,Ho(17));u.position.set(14.904,12.198,-1.832),u.scale.set(.15,4.265,6.331),this.add(u);let h=new we(e,Ho(43));h.position.set(-.462,8.89,14.52),h.scale.set(4.38,5.441,.088),this.add(h);let f=new we(e,Ho(20));f.position.set(3.235,11.486,-12.541),f.scale.set(2.5,2,.1),this.add(f);let d=new we(e,Ho(100));d.position.set(0,20,0),d.scale.set(1,.1,1),this.add(d)}dispose(){let e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(let t of e)t.dispose()}};function Ho(i){return new Pa({color:0,emissive:16777215,emissiveIntensity:i})}function jp(i,e){if(e===Kf)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),i;if(e===Mo||e===qa){let t=i.getIndex();if(t===null){let s=[],o=i.getAttribute("position");if(o!==void 0){for(let a=0;ao&&(O+=B,D+=X,P+=V)}let I=1/(Math.sqrt(O*O+D*D+P*P)||1);v[3*A+0]=O*I,v[3*A+1]=D*I,v[3*A+2]=P*I}}return t.setAttribute("normal",new wt(v,3,!1)),t}function uM(i){let e=new Map,t=new Map,n=i.clone();return hM(i,n,function(r,s){e.set(s,r),t.set(r,s)}),n.traverse(function(r){if(!r.isSkinnedMesh)return;let s=r,o=e.get(r),a=o.skeleton.bones;s.skeleton=o.skeleton.clone(),s.bindMatrix.copy(o.bindMatrix),s.skeleton.bones=a.map(function(l){return t.get(l)}),s.bind(s.skeleton,s.bindMatrix)}),n}function hM(i,e,t){t(i,e);for(let n=0;n=2.0 are supported."));return}let c=new Em(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,priority:this.priority,cache:this.cache,withCredentials:this.withCredentials,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u=0&&a[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}c.setExtensions(o),c.setPlugins(a),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,s){n.parse(e,t,r,s)})}};function UC(){let i={};return{get:function(e){return i[e]},add:function(e,t){i[e]=t},remove:function(e){delete i[e]},removeAll:function(){i={}}}}function Bt(i,e,t){let n=i.json.materials[e];return n.extensions&&n.extensions[t]?n.extensions[t]:null}var nt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DIFFUSE_ROUGHNESS:"KHR_materials_diffuse_roughness",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},nm=class{constructor(e){this.parser=e,this.name=nt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,o)}},xm=class{constructor(e){this.parser=e,this.name=nt.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;let o=s.extensions[t],a=r.images[o.source],l=n.textureLoader;if(a.uri){let c=n.options.manager.getHandler(a.uri);c!==null&&(l=c)}return n.loadTextureImage(e,o.source,l)}},bm=class{constructor(e){this.parser=e,this.name=nt.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;let o=s.extensions[t],a=r.images[o.source],l=n.textureLoader;if(a.uri){let c=n.options.manager.getHandler(a.uri);c!==null&&(l=c)}return n.loadTextureImage(e,o.source,l)}},Oh=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let r=n.extensions[this.name],s=this.parser.getDependency("buffer",r.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(a){let l=r.byteOffset||0,c=r.byteLength||0,u=r.count,h=r.byteStride,f=new Uint8Array(a,l,c);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(u,h,f,r.mode,r.filter).then(function(d){return d.buffer}):o.ready.then(function(){let d=new ArrayBuffer(u*h);return o.decodeGltfBuffer(new Uint8Array(d),u,h,f,r.mode,r.filter),d})})}else return null}},ym=class{constructor(e){this.name=nt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let c of r.primitives)if(c.mode!==ei.TRIANGLES&&c.mode!==ei.TRIANGLE_STRIP&&c.mode!==ei.TRIANGLE_FAN&&c.mode!==void 0)return null;let o=n.extensions[this.name].attributes,a=[],l={};for(let c in o)a.push(this.parser.getDependency("accessor",o[c]).then(u=>(l[c]=u,l[c])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(c=>{let u=c.pop(),h=u.isGroup?u.children:[u],f=c[0].count,d=[];for(let p of h){let x=new Be,g=new U,m=new Sn,b=new U(1,1,1),v=new hs(p.geometry,p.material,f);for(let M=0;M0||i.search(/^data\:image\/jpeg/)===0?"image/jpeg":i.search(/\.webp($|\?)/i)>0||i.search(/^data\:image\/webp/)===0?"image/webp":i.search(/\.ktx2($|\?)/i)>0||i.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}var XC=new Be,Em=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new UC,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,s=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){let a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;let l=a.match(/Version\/(\d+)/);r=n&&l?parseInt(l[1],10):-1,s=a.indexOf("Firefox")>-1,o=s?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&r<17||s&&o<98?(this.textureLoader=new Fa(this.options.manager),this.textureLoader.setPriority(this.options.priority),this.textureLoader.setCache(this.options.cache)):(this.textureLoader=new Ua(this.options.manager),this.textureLoader.setPriority(this.options.priority),this.textureLoader.setCache(this.options.cache)),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setWithCredentials(this.options.withCredentials),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new mo(this.options.manager),this.fileLoader.setPriority(this.options.priority),this.fileLoader.setCache(this.options.cache),this.fileLoader.setResponseType("arraybuffer"),(this.options.withCredentials||this.options.crossOrigin==="use-credentials")&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){let a={scene:o[0][r.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:r.asset,parser:n,userData:{}};return Us(s,a,r),Ui(a,r),Promise.all(n._invokeAll(function(l){return l.afterRoot&&l.afterRoot(a)})).then(function(){for(let l of a.scenes)l.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let r=0,s=t.length;r{let l=this.associations.get(o);l!=null&&this.associations.set(a,l);for(let[c,u]of o.children.entries())s(u,a.children[c])};return s(n,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n=2&&g.setY(R,S[_*l+1]),l>=3&&g.setZ(R,S[_*l+2]),l>=4&&g.setW(R,S[_*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=p}return g})}loadTexture(e){let t=this.json,n=this.options,s=t.textures[e].source,o=t.images[s],a=this.textureLoader;if(o.uri){let l=n.manager.getHandler(o.uri);l!==null&&(a=l)}return this.loadTextureImage(e,s,a)}loadTextureImage(e,t,n){let r=this,s=this.json,o=s.textures[e],a=s.images[t],l=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[l])return this.textureCache[l];let c=this.loadImageSource(t,n).then(function(u){u.flipY=!1,u.name=o.name||a.name||"",u.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(u.name=a.uri);let f=(s.samplers||{})[o.sampler]||{};return u.magFilter=dM[f.magFilter]||Ht,u.minFilter=dM[f.minFilter]||Fn,u.wrapS=pM[f.wrapS]||kn,u.wrapT=pM[f.wrapT]||kn,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==Ut&&u.minFilter!==Ht,r.associations.set(u,{textures:e}),u}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){let n=this,r=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(f=>f.clone());let o=r.images[e],a=self.URL||self.webkitURL,l=o.uri||"",c=!1,u;if(t.isKTX2Loader===!0&&o.bufferView!==void 0)u=n.getDependency("bufferView",o.bufferView).then(function(f){return new Promise(function(d,p){t.parse(f,d,p)})});else{if(o.bufferView!==void 0)l=n.getDependency("bufferView",o.bufferView).then(function(f){c=!0;let d=new Blob([f],{type:o.mimeType});return l=a.createObjectURL(d),l});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");u=Promise.resolve(l).then(function(f){return new Promise(function(d,p){let x=d;t.isImageBitmapLoader===!0&&(x=function(g){let m=new Kt(g);m.needsUpdate=!0,d(m)}),t.load(or.resolveURL(f,s.path),x,void 0,p)})})}let h=u.then(function(f){return c===!0&&a.revokeObjectURL(l),Ui(f,o),f.userData.mimeType=o.mimeType||WC(o.uri),f}).catch(function(f){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),f});return this.sourceCache[e]=h,h}assignTexture(e,t,n,r){let s=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),s.extensions[nt.KHR_TEXTURE_TRANSFORM]){let a=n.extensions!==void 0?n.extensions[nt.KHR_TEXTURE_TRANSFORM]:void 0;if(a){let l=s.associations.get(o);o=s.extensions[nt.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),s.associations.set(o,l)}}return r!==void 0&&(o.colorSpace=r),e[t]=o,o})}assignFinalMaterial(e){let t=e.geometry,n=e.material,r=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){let a="PointsMaterial:"+n.uuid,l=this.cache.get(a);l||(l=new cn,mn.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,l.sizeAttenuation=!1,this.cache.add(a,l)),n=l}else if(e.isLine){let a="LineBasicMaterial:"+n.uuid,l=this.cache.get(a);l||(l=new Lt,mn.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,this.cache.add(a,l)),n=l}if(r||s||o){let a="ClonedMaterial:"+n.uuid+":";r&&(a+="derivative-tangents:"),s&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let l=this.cache.get(a);l||(l=n.clone(),s&&(l.vertexColors=!0),o&&(l.flatShading=!0),r&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(a,l),this.associations.set(l,this.associations.get(n))),n=l}e.material=n}getMaterialType(){return In}loadMaterial(e){let t=this,n=this.json,r=this.extensions,s=n.materials[e],o,a={},l=s.extensions||{},c=[];if(l[nt.KHR_MATERIALS_UNLIT]){let h=r[nt.KHR_MATERIALS_UNLIT];o=h.getMaterialType(),c.push(h.extendParams(a,s,t))}else{let h=s.pbrMetallicRoughness||{};if(a.color=new W(1,1,1),a.opacity=1,Array.isArray(h.baseColorFactor)){let f=h.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],Mn),a.opacity=f[3]}h.baseColorTexture!==void 0&&c.push(t.assignTexture(a,"map",h.baseColorTexture,ft)),a.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,a.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(a,"metalnessMap",h.metallicRoughnessTexture)),c.push(t.assignTexture(a,"roughnessMap",h.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,a)})))}s.doubleSided===!0&&(a.side=ut);let u=s.alphaMode||em.OPAQUE;if(u===em.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,u===em.MASK&&(a.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&o!==Ke&&(c.push(t.assignTexture(a,"normalMap",s.normalTexture)),a.normalScale=new De(1,1),s.normalTexture.scale!==void 0)){let h=s.normalTexture.scale;a.normalScale.set(h,h)}if(s.occlusionTexture!==void 0&&o!==Ke&&(c.push(t.assignTexture(a,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&o!==Ke){let h=s.emissiveFactor;a.emissive=new W().setRGB(h[0],h[1],h[2],Mn)}return s.emissiveTexture!==void 0&&o!==Ke&&c.push(t.assignTexture(a,"emissiveMap",s.emissiveTexture,ft)),Promise.all(c).then(function(){let h=new o(a);return s.name&&(h.name=s.name),Ui(h,s),t.associations.set(h,{materials:e}),s.extensions&&Us(r,h,s),h})}createUniqueName(e){let t=gt.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function s(a){return n[nt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(l){return mM(l,a,t)})}let o=[];for(let a=0,l=e.length;ajp(d,qa)):c.mode===ei.TRIANGLE_FAN&&(f=f.then(d=>jp(d,Mo))),r[u]={primitive:c,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){let t=this,n=this.json,r=this.extensions,s=n.meshes[e],o=s.primitives,a=[];for(let l=0,c=o.length;l0&&GC(m,s),m.name=t.createUniqueName(s.name||"mesh_"+e),Ui(m,s),g.extensions&&Us(r,m,g),t.assignFinalMaterial(m),h.push(m)}for(let d=0,p=h.length;d0){let d=u.userData.pivot,p=h[0];u.pivot=new U().fromArray(d),u.position.x-=d[0],u.position.y-=d[1],u.position.z-=d[2],p.position.set(0,0,0),delete u.userData.pivot}return u})}_loadNodeShallow(e){let t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let s=t.nodes[e],o=s.name?r.createUniqueName(s.name):"",a=[],l=r._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&a.push(l),s.camera!==void 0&&a.push(r.getDependency("camera",s.camera).then(function(c){return r._getNodeRef(r.cameraCache,s.camera,c)})),r._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){a.push(c)}),this.nodeCache[e]=Promise.all(a).then(function(c){let u;if(s.isBone===!0?u=new ho:c.length>1?u=new ct:c.length===1?u=c[0]:u=new Et,u!==c[0])for(let h=0,f=c.length;h1){let h=r.associations.get(u);r.associations.set(u,{...h})}return r.associations.get(u).nodes=e,u}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],r=this,s=new ct;n.name&&(s.name=r.createUniqueName(n.name)),Ui(s,n),n.extensions&&Us(t,s,n);let o=n.nodes||[],a=[];for(let l=0,c=o.length;l{let h=new Map;for(let[f,d]of r.associations)(f instanceof mn||f instanceof Kt)&&h.set(f,d);return u.traverse(f=>{let d=r.associations.get(f);d!=null&&h.set(f,d)}),h};return r.associations=c(s),s})}_createAnimationTracks(e,t,n,r,s){let o=[],a=e.name?e.name:e.uuid,l=[];function c(d){d.morphTargetInfluences&&l.push(d.name?d.name:d.uuid)}Yr[s.path]===Yr.weights?(c(e),e.isGroup&&e.children.forEach(c)):l.push(a);let u;switch(Yr[s.path]){case Yr.weights:u=nr;break;case Yr.rotation:u=ir;break;case Yr.translation:case Yr.scale:u=Or;break;default:n.itemSize===1?u=nr:u=Or;break}let h=r.interpolation!==void 0?kC[r.interpolation]:Zi,f=this._getArrayFromAccessor(n);for(let d=0,p=l.length;d{let t=e;if(!t.isMesh)return;let n=t.geometry,r=t.material,s=r.name??"";t.userData.paint=!!r.userData?.paint||/^Paint/.test(s),n.getAttribute("normal")||(t.userData.paint?n.computeVertexNormals():t.geometry=cM(n,qC)),r.flatShading=!1;let o=/glass/i.test(s);r.metalness=t.userData.paint?.55:o?0:Math.min(r.metalness??0,.4),r.roughness=t.userData.paint?.28:o?.05:Math.max(r.roughness??.6,.45),o&&(r.transparent=!0,r.depthWrite=!1,r.opacity=Math.max(r.opacity,.9))})}function yM(i){let e=xM.get(i);if(!e){let t=D0();if(!t)return Promise.resolve(!1);e=t(i).then(n=>n&&new Promise(r=>{new Xo().parse(n,"",s=>{$C(s.scene);let o=new Ct().setFromObject(s.scene),a=[o.max.x-o.min.x,o.max.y-o.min.y,o.max.z-o.min.z];s.scene.position.set(-(o.max.x+o.min.x)/2,-o.min.y,-(o.max.z+o.min.z)/2);let l=new ct;l.add(s.scene),bM.set(i,{root:l,size:a}),U0(i),r({root:l,size:a})},()=>r(null))})).catch(()=>null),xM.set(i,e)}return e.then(t=>!!t)}function _M(i,e){let t=bM.get(i);if(!t)return null;let n=t.root.clone(!0),r=[];n.traverse(o=>{let a=o;if(!a.isMesh)return;let l=a.material.clone();a.userData.paint&&e.paint&&(l.color=new W(e.paint)),a.material=l,r.push(l)});let s=new ct;return s.add(n),s.scale.set((e.mirror?-1:1)*(e.w/t.size[0]),e.h/t.size[1],e.d/t.size[2]),s.position.set(e.x,e.y,e.z),s.rotation.y=-e.rotation*Math.PI/180,s.userData.own=r,s}function Rm(i){for(let e of i.userData.own??[])e.dispose()}function vM(i,e){let t=new wo(e),n=t.fromScene(new Fh,.04).texture;t.dispose();let r=new ds(16777215,9081766,.9),s=new sr(16777215,1.6);return s.position.set(-4,9,6),i.add(r,s),{env:n,dispose:()=>{n.dispose(),r.removeFromParent(),s.removeFromParent()}}}function MM(i,e){for(let t of i.userData.own??[])t.envMap=e,t.envMapIntensity=.9}var KC=.3,SM=2.6,Dh=.05;function ZC(i,e,t,n){let r=n*.7071,s=[i,[i[0]+n,i[1]],[i[0]-n,i[1]],[i[0],i[1]+n],[i[0],i[1]-n]],o=[[i[0]+r,i[1]+r],[i[0]-r,i[1]+r],[i[0]+r,i[1]-r],[i[0]-r,i[1]-r]];return s.every(a=>Ve(a,e))&&!t.some(a=>[...s,...o].some(l=>Ve(l,a)))}function wM(i,e,t){let n=Math.ceil(Math.hypot(e[0]-i[0],e[1]-i[1])/Dh);for(let r=1;rt+1e-6)&&r!==null){let a=o?s:s-Dh;(!n||a-r>n[1]-n[0])&&(n=[r,a]),r=null}}return n}function TM(i,e=.32,t=.22,n=[]){let r=i.map(v=>v[0]),s=i.map(v=>v[1]),[o,a,l,c]=[Math.min(...r),Math.max(...r),Math.min(...s),Math.max(...s)],u=c-l>=a-o,h=v=>ZC(v,i,n,t),f=(v,y)=>u?[v,y]:[y,v],[d,p,x,g]=u?[o,a,l,c]:[l,c,o,a],m=[],b=!0;for(let v=d+t;v<=p-t+1e-6;v+=e){let y=JC(w=>h(f(v,w)),x,g);if(!y||y[1]-y[0]<.2)continue;let M=w=>w?[f(v,y[0]),f(v,y[1])]:[f(v,y[1]),f(v,y[0])],S=M(b),_=m[m.length-1];if(_&&n.length>0&&!wM(_,S[0],h)){let w=M(!b);if(!wM(_,w[0],h))continue;S=w,b=!b}m.push(...S),b=!b}return m}function Pm(i,e=.7,t=12){return Array.from({length:t},(n,r)=>[i[0]+Math.cos(r/t*Math.PI*2)*e,i[1]+Math.sin(r/t*Math.PI*2)*e])}var Cm=i=>Math.atan2(Math.sin(i),Math.cos(i));function AM(i,e,t){let n;if(e.mode==="cleaning"){if(i.path.length===0)return!1;n=i.path[i.next%i.path.length]}else if(e.mode==="returning"||e.mode==="docked")n=e.rest;else return!1;let[r,s]=[n[0]-i.pos[0],n[1]-i.pos[1]],o=Math.hypot(r,s);if(o<.02){if(e.mode==="cleaning")return i.next=(i.next+1)%i.path.length,!0;let l=Cm(e.restHeading-i.heading);return Math.abs(l)<.02?!1:(i.heading+=Math.sign(l)*Math.min(Math.abs(l),SM*t),!0)}let a=Cm(Math.atan2(r,s)-i.heading);if(i.heading=Cm(i.heading+Math.sign(a)*Math.min(Math.abs(a),SM*t)),Math.abs(a)<.35){let l=Math.min(o,KC*t);i.pos=[i.pos[0]+r/o*l,i.pos[1]+s/o*l]}return!0}var Uh=600*1e3,jC=3e3;function EM(i,e){if(i==null)return 1;let t=e-i;return t>Uh?Math.max(0,1-(t-Uh)/jC):1}function Im(i,e,t){let n=e/2,r=[],s=(a,l,c)=>r.push(a[0],t,a[1],l[0],t,l[1],c[0],t,c[1]);for(let a of i){for(let c=0;c+14?o=i.array[r*i.itemSize+s]:(s===0?o=i.getX(r):s===1?o=i.getY(r):s===2?o=i.getZ(r):s===3&&(o=i.getW(r)),i.normalized===!0&&(o=Br.normalize(o,i.array))),n.min[s]=Math.min(n.min[s],o),n.max[s]=Math.max(n.max[s],o)}return n}function FM(i){return Math.ceil(i/4)*4}function Fm(i,e=0){let t=FM(i.byteLength);if(t!==i.byteLength){let n=new Uint8Array(t);if(n.set(new Uint8Array(i)),e!==0)for(let r=i.byteLength;r"u"&&typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")}function aP(i,e){if(typeof OffscreenCanvas<"u"&&i instanceof OffscreenCanvas){let t;return e==="image/jpeg"?t=.92:e==="image/webp"&&(t=.8),i.convertToBlob({type:e,quality:t})}else return new Promise(t=>i.toBlob(t,e))}var Nm=class{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter r187"}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map,normalMaps:new Map},this.textureUtils=null}setPlugins(e){this.plugins=e}setTextureUtils(e){this.textureUtils=e}async writeAsync(e,t,n={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1,copyright:null},n),this.options.animations.length>0&&(this.options.trs=!0),await this.processInputAsync(e),await Promise.all(this.pending);let r=this,s=r.buffers,o=r.json;n=r.options;let a=r.extensionsUsed,l=r.extensionsRequired,c=new Blob(s,{type:"application/octet-stream"}),u=Object.keys(a),h=Object.keys(l);if(u.length>0&&(o.extensionsUsed=u),h.length>0&&(o.extensionsRequired=h),o.buffers&&o.buffers.length>0&&(o.buffers[0].byteLength=c.size),n.copyright&&(o.asset.copyright=n.copyright),n.binary===!0){let f=new FileReader;f.readAsArrayBuffer(c),f.onloadend=function(){let d=Fm(f.result),p=new DataView(new ArrayBuffer(LM));p.setUint32(0,d.byteLength,!0),p.setUint32(4,iP,!0);let x=Fm(rP(JSON.stringify(o)),32),g=new DataView(new ArrayBuffer(LM));g.setUint32(0,x.byteLength,!0),g.setUint32(4,nP,!0);let m=new ArrayBuffer(IM),b=new DataView(m);b.setUint32(0,eP,!0),b.setUint32(4,tP,!0);let v=IM+g.byteLength+x.byteLength+p.byteLength+d.byteLength;b.setUint32(8,v,!0);let y=new Blob([m,g,x,p,d],{type:"application/octet-stream"}),M=new FileReader;M.readAsArrayBuffer(y),M.onloadend=function(){t(M.result)}}}else if(o.buffers&&o.buffers.length>0){let f=new FileReader;f.readAsDataURL(c),f.onloadend=function(){let d=f.result;o.buffers[0].uri=d,t(o)}}else t(o)}serializeUserData(e,t){if(Object.keys(e.userData).length===0)return;let n=this.options,r=this.extensionsUsed;try{let s=JSON.parse(JSON.stringify(e.userData));if(n.includeCustomExtensions&&s.gltfExtensions){t.extensions===void 0&&(t.extensions={});for(let o in s.gltfExtensions)t.extensions[o]=s.gltfExtensions[o],r[o]=!0;delete s.gltfExtensions}Object.keys(s).length>0&&(t.extras=s)}catch(s){console.warn("THREE.GLTFExporter: userData of '"+e.name+"' won't be serialized because of JSON.stringify error - "+s.message)}}getUID(e,t=!1){if(this.uids.has(e)===!1){let r=new Map;r.set(!0,this.uid++),r.set(!1,this.uid++),this.uids.set(e,r)}return this.uids.get(e).get(t)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;let n=new U;for(let r=0,s=e.count;r5e-4)return!1;return!0}createNormalizedNormalAttribute(e){let t=this.cache;if(t.attributesNormalized.has(e))return t.attributesNormalized.get(e);let n=e.clone(),r=new U;for(let s=0,o=n.count;s4?g=e.array[p*e.itemSize+x]:(x===0?g=e.getX(p):x===1?g=e.getY(p):x===2?g=e.getZ(p):x===3&&(g=e.getW(p)),e.normalized===!0&&(g=Br.normalize(g,e.array))),t===rt.FLOAT?u.setFloat32(h,g,!0):t===rt.INT?u.setInt32(h,g,!0):t===rt.UNSIGNED_INT?u.setUint32(h,g,!0):t===rt.SHORT?u.setInt16(h,g,!0):t===rt.UNSIGNED_SHORT?u.setUint16(h,g,!0):t===rt.BYTE?u.setInt8(h,g):t===rt.UNSIGNED_BYTE&&u.setUint8(h,g),h+=a}h%l!==0&&(h+=l-h%l)}let f={buffer:this.processBuffer(u.buffer),byteOffset:this.byteOffset,byteLength:c};return s!==void 0&&(f.target=s),s===rt.ARRAY_BUFFER&&(f.byteStride=l),this.byteOffset+=c,o.bufferViews.push(f),{id:o.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){let t=this,n=t.json;return n.bufferViews||(n.bufferViews=[]),new Promise(function(r){let s=new FileReader;s.readAsArrayBuffer(e),s.onloadend=function(){let o=Fm(s.result),a={buffer:t.processBuffer(o),byteOffset:t.byteOffset,byteLength:o.byteLength};t.byteOffset+=o.byteLength,r(n.bufferViews.push(a)-1)}})}processAccessor(e,t,n,r){let s=this.json,o={1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"},a;if(e.array.constructor===Float32Array)a=rt.FLOAT;else if(e.array.constructor===Int32Array)a=rt.INT;else if(e.array.constructor===Uint32Array)a=rt.UNSIGNED_INT;else if(e.array.constructor===Int16Array)a=rt.SHORT;else if(e.array.constructor===Uint16Array)a=rt.UNSIGNED_SHORT;else if(e.array.constructor===Int8Array)a=rt.BYTE;else if(e.array.constructor===Uint8Array)a=rt.UNSIGNED_BYTE;else throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);if(n===void 0&&(n=0),(r===void 0||r===1/0)&&(r=e.count),r===0)return null;let l=oP(e,n,r),c;t!==void 0&&(c=e===t.index?rt.ELEMENT_ARRAY_BUFFER:rt.ARRAY_BUFFER);let u=this.processBufferView(e,a,n,r,c),h={bufferView:u.id,byteOffset:u.byteOffset,componentType:a,count:r,max:l.max,min:l.min,type:o[e.itemSize]};return e.normalized===!0&&(h.normalized=!0),s.accessors||(s.accessors=[]),s.accessors.push(h)-1}processImage(e,t,n,r="image/png"){if(e!==null){let s=this,o=s.cache,a=s.json,l=s.options,c=s.pending;o.images.has(e)||o.images.set(e,{});let u=o.images.get(e),h=r+":flipY/"+n.toString();if(u[h]!==void 0)return u[h];a.images||(a.images=[]);let f={mimeType:r},d=Om();d.width=Math.min(e.width,l.maxTextureSize),d.height=Math.min(e.height,l.maxTextureSize);let p=d.getContext("2d",{willReadFrequently:!0});if(n===!0&&(p.translate(0,d.height),p.scale(1,-1)),e.data!==void 0){t!==Nn&&console.error("GLTFExporter: Only RGBAFormat is supported.",t),(e.width>l.maxTextureSize||e.height>l.maxTextureSize)&&console.warn("GLTFExporter: Image size is bigger than maxTextureSize",e);let g=new Uint8ClampedArray(e.height*e.width*4);for(let m=0;ms.processBufferViewImage(g)).then(g=>{f.bufferView=g})):f.uri=lo.getDataURL(d,r);let x=a.images.push(f)-1;return u[h]=x,x}else throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){let t=this.json;t.samplers||(t.samplers=[]);let n={magFilter:Gn[e.magFilter],minFilter:Gn[e.minFilter],wrapS:Gn[e.wrapS],wrapT:Gn[e.wrapT]};return t.samplers.push(n)-1}async processTextureAsync(e){let n=this.options,r=this.cache,s=this.json;if(r.textures.has(e))return r.textures.get(e);s.textures||(s.textures=[]),e instanceof Lr&&(e=await this.decompressTextureAsync(e,n.maxTextureSize));let o=e.userData.mimeType,a=this.processImage(e.image,e.format,e.flipY,o),l={sampler:this.processSampler(e)};o==="image/webp"?(l.extensions=l.extensions||{},l.extensions.EXT_texture_webp={source:a},this.extensionsUsed.EXT_texture_webp=!0,this.extensionsRequired.EXT_texture_webp=!0):l.source=a,e.name&&(l.name=e.name),await this._invokeAllAsync(async function(u){u.writeTexture&&await u.writeTexture(e,l)});let c=s.textures.push(l)-1;return r.textures.set(e,c),c}async processMaterialAsync(e,t){let n=this.cache,r=this.json,s=t!==void 0&&t.hasAttribute("tangent"),o=e.normalMap?e.uuid+":"+s:e.uuid;if(n.materials.has(o))return n.materials.get(o);if(e.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;r.materials||(r.materials=[]);let a={pbrMetallicRoughness:{}};e.isMeshStandardMaterial!==!0&&e.isMeshBasicMaterial!==!0&&console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");let l=e.color.toArray().concat([e.opacity]);if(xr(l,[1,1,1,1])||(a.pbrMetallicRoughness.baseColorFactor=l),e.isMeshStandardMaterial?(a.pbrMetallicRoughness.metallicFactor=e.metalness,a.pbrMetallicRoughness.roughnessFactor=e.roughness):(a.pbrMetallicRoughness.metallicFactor=0,a.pbrMetallicRoughness.roughnessFactor=1),e.metalnessMap||e.roughnessMap){let u=await this.buildMetalRoughTextureAsync(e.metalnessMap,e.roughnessMap),h={index:await this.processTextureAsync(u),texCoord:u.channel};this.applyTextureTransform(h,u),a.pbrMetallicRoughness.metallicRoughnessTexture=h}if(e.map){let u={index:await this.processTextureAsync(e.map),texCoord:e.map.channel};this.applyTextureTransform(u,e.map),a.pbrMetallicRoughness.baseColorTexture=u}if(e.emissive){let u=e.emissive;if(Math.max(u.r,u.g,u.b)>0&&(a.emissiveFactor=e.emissive.toArray()),e.emissiveMap){let f={index:await this.processTextureAsync(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(f,e.emissiveMap),a.emissiveTexture=f}}if(e.normalMap){let u=e.normalScale,h=u.x<0,f=s?u.y<0:u.y>0,d=e.normalMap;if(h||f){n.normalMaps.has(e.normalMap)===!1&&n.normalMaps.set(e.normalMap,{});let x=n.normalMaps.get(e.normalMap),g=`${h}:${f}`;x[g]===void 0&&(x[g]=await this.buildNormalMapTextureAsync(e.normalMap,h,f)),d=x[g]}let p={index:await this.processTextureAsync(d),texCoord:e.normalMap.channel};Math.abs(u.x)!==1&&(p.scale=Math.abs(u.x)),this.applyTextureTransform(p,e.normalMap),a.normalTexture=p}if(e.aoMap){let u={index:await this.processTextureAsync(e.aoMap),texCoord:e.aoMap.channel};e.aoMapIntensity!==1&&(u.strength=e.aoMapIntensity),this.applyTextureTransform(u,e.aoMap),a.occlusionTexture=u}e.transparent?a.alphaMode="BLEND":e.alphaTest>0&&(a.alphaMode="MASK",a.alphaCutoff=e.alphaTest),e.side===ut&&(a.doubleSided=!0),e.name!==""&&(a.name=e.name),this.serializeUserData(e,a),await this._invokeAllAsync(async function(u){u.writeMaterialAsync&&await u.writeMaterialAsync(e,a)});let c=r.materials.push(a)-1;return n.materials.set(o,c),c}async processMeshAsync(e){let t=this.cache,n=this.json,r=[e.geometry.uuid];if(Array.isArray(e.material))for(let y=0,M=e.material.length;y0){let y=[],M=[],S={};if(e.morphTargetDictionary!==void 0)for(let _ in e.morphTargetDictionary)S[e.morphTargetDictionary[_]]=_;for(let _=0;_0&&(l.extras={},l.extras.targetNames=M)}let x=Array.isArray(e.material);if(x&&o.groups.length===0)return null;let g=!1;if(x&&o.index===null){let y=[];for(let M=0,S=o.attributes.position.count;M0&&(S.targets=h),o.index!==null){let w=this.getUID(o.index);(b[y].start!==void 0||b[y].count!==void 0)&&(w+=":"+b[y].start+":"+b[y].count),t.attributes.has(w)?S.indices=t.attributes.get(w):(S.indices=this.processAccessor(o.index,o,b[y].start,b[y].count),t.attributes.set(w,S.indices)),S.indices===null&&delete S.indices}let _=await this.processMaterialAsync(m[b[y].materialIndex],o);_!==null&&(S.material=_),u.push(S)}g===!0&&o.setIndex(null),l.primitives=u,n.meshes||(n.meshes=[]),await this._invokeAllAsync(function(y){y.writeMesh&&y.writeMesh(e,l)});let v=n.meshes.push(l)-1;return t.meshes.set(s,v),v}detectMeshQuantization(e,t){if(this.extensionsUsed[Lm])return;let n;switch(t.array.constructor){case Int8Array:n="byte";break;case Uint8Array:n="unsigned byte";break;case Int16Array:n="short";break;case Uint16Array:n="unsigned short";break;default:return}t.normalized&&(n+=" normalized");let r=e.split("_",1)[0];CM[r]&&CM[r].includes(n)&&(this.extensionsUsed[Lm]=!0,this.extensionsRequired[Lm]=!0)}processCamera(e){let t=this.json;t.cameras||(t.cameras=[]);let n=e.isOrthographicCamera,r={type:n?"orthographic":"perspective"};return n?r.orthographic={xmag:e.right,ymag:e.top,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:r.perspective={aspectRatio:e.aspect,yfov:Br.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},e.name!==""&&(r.name=e.type),t.cameras.push(r)-1}processAnimation(e,t){let n=this.json,r=this.nodeMap;n.animations||(n.animations=[]),e=qr.Utils.mergeMorphTargetTracks(e.clone(),t);let s=e.tracks,o=[],a=[];for(let c=0;c0){let a=[];for(let l=0,c=e.children.length;l0&&(s.children=a)}return await this._invokeAllAsync(function(a){a.writeNode&&a.writeNode(e,s)}),o}async _processNodeWithPivotAsync(e){let t=this.json,n=this.options,r=this.nodeMap,s=e.pivot,o={},a=e.quaternion.toArray(),l=[e.position.x+s.x,e.position.y+s.y,e.position.z+s.z],c=e.scale.toArray();xr(a,[0,0,0,1])||(o.rotation=a),xr(l,[0,0,0])||(o.translation=l),xr(c,[1,1,1])||(o.scale=c),o.extras={pivot:s.toArray()},e.name!==""&&(o.name=String(e.name)),this.serializeUserData(e,o);let u=t.nodes.push(o)-1;r.set(e,u);let h={},f=[-s.x,-s.y,-s.z];if(xr(f,[0,0,0])||(h.translation=f),e.isMesh||e.isLine||e.isPoints){let x=await this.processMeshAsync(e);x!==null&&(h.mesh=x)}else e.isCamera&&(h.camera=this.processCamera(e));e.isSkinnedMesh&&this.skins.push(e);let p=[t.nodes.push(h)-1];if(e.children.length>0){let x=[];for(let g=0,m=e.children.length;g0&&(h.children=x)}return o.children=p,await this._invokeAllAsync(function(x){x.writeNode&&x.writeNode(e,o)}),u}async processSceneAsync(e){let t=this.json,n=this.options;t.scenes||(t.scenes=[],t.scene=0);let r={};e.name!==""&&(r.name=e.name),t.scenes.push(r);let s=[];for(let o=0,a=e.children.length;o0&&(r.nodes=s),this.serializeUserData(e,r)}async processObjectsAsync(e){let t=new Tn;t.name="AuxScene";for(let n=0;n0&&await this.processObjectsAsync(n);for(let r=0;r0&&(o.range=e.distance)):e.isSpotLight&&(o.type="spot",e.distance>0&&(o.range=e.distance),o.spot={},o.spot.innerConeAngle=(1-e.penumbra)*e.angle,o.spot.outerConeAngle=e.angle),e.decay!==void 0&&e.decay!==2&&console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2."),e.target&&(e.target.parent!==e||e.target.position.x!==0||e.target.position.y!==0||e.target.position.z!==-1)&&console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1."),s[this.name]||(r.extensions=r.extensions||{},r.extensions[this.name]={lights:[]},s[this.name]=!0);let a=r.extensions[this.name].lights;a.push(o),t.extensions=t.extensions||{},t.extensions[this.name]={light:a.length-1}}},Um=class{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}async writeMaterialAsync(e,t){if(!e.isMeshBasicMaterial)return;let r=this.writer.extensionsUsed;t.extensions=t.extensions||{},t.extensions[this.name]={},r[this.name]=!0,t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=.9}},Bm=class{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||e.clearcoat===0)return;let n=this.writer,r=n.extensionsUsed,s={};if(s.clearcoatFactor=e.clearcoat,e.clearcoatMap){let o={index:await n.processTextureAsync(e.clearcoatMap),texCoord:e.clearcoatMap.channel};n.applyTextureTransform(o,e.clearcoatMap),s.clearcoatTexture=o}if(s.clearcoatRoughnessFactor=e.clearcoatRoughness,e.clearcoatRoughnessMap){let o={index:await n.processTextureAsync(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};n.applyTextureTransform(o,e.clearcoatRoughnessMap),s.clearcoatRoughnessTexture=o}if(e.clearcoatNormalMap){let o={index:await n.processTextureAsync(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};e.clearcoatNormalScale.x!==1&&(o.scale=e.clearcoatNormalScale.x),n.applyTextureTransform(o,e.clearcoatNormalMap),s.clearcoatNormalTexture=o}t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},km=class{constructor(e){this.writer=e,this.name="KHR_materials_dispersion"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||e.dispersion===0)return;let r=this.writer.extensionsUsed,s={};s.dispersion=e.dispersion,t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},zm=class{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||e.iridescence===0)return;let n=this.writer,r=n.extensionsUsed,s={};if(s.iridescenceFactor=e.iridescence,e.iridescenceMap){let o={index:await n.processTextureAsync(e.iridescenceMap),texCoord:e.iridescenceMap.channel};n.applyTextureTransform(o,e.iridescenceMap),s.iridescenceTexture=o}if(s.iridescenceIor=e.iridescenceIOR,s.iridescenceThicknessMinimum=e.iridescenceThicknessMinimum,s.iridescenceThicknessMaximum=e.iridescenceThicknessMaximum,e.iridescenceThicknessMap){let o={index:await n.processTextureAsync(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};n.applyTextureTransform(o,e.iridescenceThicknessMap),s.iridescenceThicknessTexture=o}t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},Vm=class{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||e.transmission===0)return;let n=this.writer,r=n.extensionsUsed,s={};if(s.transmissionFactor=e.transmission,e.transmissionMap){let o={index:await n.processTextureAsync(e.transmissionMap),texCoord:e.transmissionMap.channel};n.applyTextureTransform(o,e.transmissionMap),s.transmissionTexture=o}t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},Gm=class{constructor(e){this.writer=e,this.name="KHR_materials_volume"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||e.transmission===0)return;let n=this.writer,r=n.extensionsUsed,s={};if(s.thicknessFactor=e.thickness,e.thicknessMap){let o={index:await n.processTextureAsync(e.thicknessMap),texCoord:e.thicknessMap.channel};n.applyTextureTransform(o,e.thicknessMap),s.thicknessTexture=o}e.attenuationDistance!==1/0&&(s.attenuationDistance=e.attenuationDistance),s.attenuationColor=e.attenuationColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},Hm=class{constructor(e){this.writer=e,this.name="KHR_materials_ior"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||e.ior===1.5)return;let r=this.writer.extensionsUsed,s={};s.ior=e.ior,t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},Wm=class{constructor(e){this.writer=e,this.name="KHR_materials_specular"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||e.specularIntensity===1&&e.specularColor.equals(QC)&&!e.specularIntensityMap&&!e.specularColorMap)return;let n=this.writer,r=n.extensionsUsed,s={};if(e.specularIntensityMap){let o={index:await n.processTextureAsync(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};n.applyTextureTransform(o,e.specularIntensityMap),s.specularTexture=o}if(e.specularColorMap){let o={index:await n.processTextureAsync(e.specularColorMap),texCoord:e.specularColorMap.channel};n.applyTextureTransform(o,e.specularColorMap),s.specularColorTexture=o}s.specularFactor=e.specularIntensity,s.specularColorFactor=e.specularColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},Xm=class{constructor(e){this.writer=e,this.name="KHR_materials_sheen"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||e.sheen==0)return;let n=this.writer,r=n.extensionsUsed,s={};if(e.sheenRoughnessMap){let o={index:await n.processTextureAsync(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};n.applyTextureTransform(o,e.sheenRoughnessMap),s.sheenRoughnessTexture=o}if(e.sheenColorMap){let o={index:await n.processTextureAsync(e.sheenColorMap),texCoord:e.sheenColorMap.channel};n.applyTextureTransform(o,e.sheenColorMap),s.sheenColorTexture=o}s.sheenRoughnessFactor=e.sheenRoughness,s.sheenColorFactor=e.sheenColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},Ym=class{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||e.anisotropy==0)return;let n=this.writer,r=n.extensionsUsed,s={};if(e.anisotropyMap){let o={index:await n.processTextureAsync(e.anisotropyMap)};n.applyTextureTransform(o,e.anisotropyMap),s.anisotropyTexture=o}s.anisotropyStrength=e.anisotropy,s.anisotropyRotation=e.anisotropyRotation,t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},qm=class{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}async writeMaterialAsync(e,t){if(!e.isMeshStandardMaterial||e.emissiveIntensity===1)return;let r=this.writer.extensionsUsed,s={};s.emissiveStrength=e.emissiveIntensity,t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},$m=class{constructor(e){this.writer=e,this.name="EXT_materials_bump"}async writeMaterialAsync(e,t){if(!e.isMeshStandardMaterial||e.bumpScale===1&&!e.bumpMap)return;let n=this.writer,r=n.extensionsUsed,s={};if(e.bumpMap){let o={index:await n.processTextureAsync(e.bumpMap),texCoord:e.bumpMap.channel};n.applyTextureTransform(o,e.bumpMap),s.bumpTexture=o}s.bumpFactor=e.bumpScale,t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}},Km=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(!e.isInstancedMesh)return;let n=this.writer,r=e,s=new Float32Array(r.count*3),o=new Float32Array(r.count*4),a=new Float32Array(r.count*3),l=new Be,c=new U,u=new Sn,h=new U;for(let d=0;di.times[i.times.length-1]){if(Math.abs(i.times[i.times.length-1]-e)<.001)return i.times.length-1;r[r.length-1]=e,r.set(i.times,0),s.set(i.values,0),s.set(o.evaluate(e),i.values.length),a=r.length-1}else for(let l=0;le){r.set(i.times.slice(0,l+1),0),r[l+1]=e,r.set(i.times.slice(l+1),l+2),s.set(i.values.slice(0,(l+1)*n),0),s.set(o.evaluate(e),(l+1)*n),s.set(i.values.slice((l+1)*n),(l+2)*n),a=l+1;break}}return i.times=r,i.values=s,a},mergeMorphTargetTracks:function(i,e){let t=[],n={},r=i.tracks;for(let s=0;slP.test(r.name)).map(r=>r.name);if(e.length>0)return e;let n=[...i.filter(r=>r.opacity>=.9&&r.lightness>.12&&!/glass|window|light|lamp/i.test(r.name))].sort((r,s)=>s.area-r.area)[0];return n?[n.name]:[]}function NM(i,e){let t=i.reduce((r,s)=>r+s,0);if(t<=e)return[...i];let n=e/t;return i.map(r=>Math.max(1,Math.floor(r*n)))}var DM=i=>/^Paint/.test(i)?i:`Paint_${i||"body"}`;var Yo=i=>i.indices.length/3;function cP(i){let e=[1/0,1/0,1/0],t=[-1/0,-1/0,-1/0];for(let n=0;nMath.floor(o/t)+1),s=new Float64Array(n);for(let o=0;oe?r=l:(s=l,o=c)}return hP(i,o)}var Bi=class extends Error{reason;constructor(e,t){super(t),this.reason=e}},fP=1179937895;function dP(i){if(i.byteLength<20||new DataView(i).getUint32(0,!0)!==fP)throw new Bi("not_glb","not a binary glTF (.glb) file")}async function Zm(i){return dP(i),new Promise((e,t)=>{new Xo().parse(i,"",n=>e(n.scene),n=>{let r=String(n?.message??n);t(/draco|meshopt|ktx/i.test(r)?new Bi("compressed",r):new Bi("unreadable",r))})})}var pP=i=>i instanceof In?i:Object.assign(new In,{color:i.color?.clone()??new W(8947848),name:i.name,opacity:i.opacity,transparent:i.transparent});function kM(i,e){i.updateMatrixWorld(!0);let t=new Map;return i.traverse(n=>{let r=n;if(!r.isMesh)return;let s=r.geometry,o=s.getAttribute("position");if(!o)return;let a=pP(Array.isArray(r.material)?r.material[0]:r.material),l=t.get(a)??{positions:[],indices:[]};t.set(a,l);let c=new Be().multiplyMatrices(e,r.matrixWorld),u=l.positions.length/3,h=new U;for(let p=0;p({material:n,mesh:{positions:Float32Array.from(r.positions),indices:Uint32Array.from(r.indices)}}))}var mP=i=>{let e=0,[t,n,r]=[new U,new U,new U];for(let s=0;s.299*i.r+.587*i.g+.114*i.b;async function xP(i){let e=kM(await Zm(i),new Be);if(e.length===0)throw new Bi("empty","the file has no 3D parts");let t=new Ct;for(let s of e)t.union(new Ct().setFromArray(s.mesh.positions));let n=t.getSize(new U),r=e.map(s=>({name:s.material.name||"material",area:mP(s.mesh),opacity:s.material.opacity,lightness:gP(s.material.color)}));return{triangles:e.reduce((s,o)=>s+Yo(o.mesh),0),size:[n.x,n.y,n.z],materials:r,paint:OM(r)}}async function bP(i,e){let t=new Be().makeRotationY(e.turns*Math.PI/2),n=kM(await Zm(i),t);if(n.length===0)throw new Bi("empty","the file has no 3D parts");let r=NM(n.map(l=>Yo(l.mesh)),e.maxTriangles),s=new Tn,o=0;return n.forEach((l,c)=>{let u=BM(l.mesh,r[c]);if(Yo(u)===0)return;o+=Yo(u);let h=new Fe;h.setAttribute("position",new wt(u.positions,3)),h.setIndex(new wt(u.indices,1));let f=l.material.name||"material",d=e.paint.includes(f),p=new In({color:l.material.color.clone(),name:d?DM(f):f,metalness:l.material.metalness,roughness:l.material.roughness,opacity:l.material.opacity,transparent:l.material.opacity<1});d&&(p.userData.paint=!0),s.add(new we(h,p))}),{glb:await new Promise((l,c)=>{new qr().parse(s,u=>u instanceof ArrayBuffer?l(u):c(new Bi("unreadable","export gave no binary")),u=>c(new Bi("unreadable",String(u))),{binary:!0})}),triangles:o}}async function yP(i,e,t=220){let n=await Zm(i),r=new Ct().setFromObject(n),s=r.getCenter(new U),o=r.getSize(new U);n.traverse(d=>{let p=d;if(!p.isMesh)return;let x=p.material;(x.userData?.paint||/^Paint/.test(x.name))&&x.color.set(e),x.metalness=Math.min(x.metalness??0,.5)});let a=new Tn,l=new sr(16777215,1.6);l.position.set(-4,9,6),a.add(n,new Da(16777215,.5),new ds(16777215,6713480,1.1),l);let c=Math.max(o.x,o.y,o.z)*.75,u=new zn(-c,c,c,-c,.01,100);u.position.copy(s).add(new U(.9,.7,1.2).normalize().multiplyScalar(20)),u.lookAt(s);let h=new kr({alpha:!0,antialias:!0,preserveDrawingBuffer:!0});h.setSize(t,t,!1),h.render(a,u);let f=h.domElement.toDataURL("image/png");return h.dispose(),a.traverse(d=>{let p=d;p.isMesh&&p.geometry.dispose()}),f}var qo=null,zM=new Map,VM=16758087;function _P(i,e,t){let n=vt(i.type);if(n?.light)rl(e,n,{x:0,z:0,rotation:0,w:i.w,d:i.d,h:i.h},0,VM);else if(i.lamp)Jm(e,{x:0,z:0,size:[i.w,i.d,i.h],base:0,rotation:0,variant:i.variant??null,lamp:i.lamp},Math.max(i.h+.15,.6),VM);else{let r={id:"preview",type:i.type,x:0,z:0,rotation:0,w:i.w,d:i.d,h:i.h,variant:i.variant??null,entity:null,power:null};Ml(e,t,new lt,r)}}function vP(i){let e=i.getCenter(new U),t=new zn(-1,1,1,-1,.01,100);t.position.copy(e).add(new U(.9,.75,1.3).normalize().multiplyScalar(20)),t.lookAt(e),t.updateMatrixWorld();let n=.05;for(let s of[i.min.x,i.max.x])for(let o of[i.min.y,i.max.y])for(let a of[i.min.z,i.max.z]){let l=new U(s,o,a).applyMatrix4(t.matrixWorldInverse);n=Math.max(n,Math.abs(l.x),Math.abs(l.y))}let r=n*1.12;return Object.assign(t,{left:-r,right:r,top:r,bottom:-r}),t.updateProjectionMatrix(),t}function MP(i,e=180,t,n=1.3){let r=[i.type,i.w,i.d,i.h,i.variant??"",e,n].join("|"),s=zM.get(r);if(s)return s;t&&Nl(t),qo??=new kr({alpha:!0,antialias:!0,preserveDrawingBuffer:!0}),qo.setPixelRatio(Math.min(2,window.devicePixelRatio||1)),qo.setSize(e,e,!1),qo.setClearColor(0,0);let[o,a]=[new lt,new Wt];_P(i,o,a);let l=new we(o.geometry(),new Ke({vertexColors:!0,color:new W(n,n,n)})),c=new gn(a.geometry(),new Lt({vertexColors:!0,color:new W(n*1.8,n*1.8,n*1.8)})),u=new Tn;u.add(l,c),qo.render(u,vP(new Ct().setFromObject(l)));let h=qo.domElement.toDataURL("image/png");for(let f of[l,c])f.geometry.dispose(),f.material.dispose();return zM.set(r,h),h}var HM={cleaning:3662079,returning:16758087,docked:4310123,idle:5995775,error:16726863},SP=1.4,Qm=32,$e=2767456,WM=4873352,wP=1911110,jm=450,XM=125,TP=1.6,YM=3e4,$M=5,KM=360/$M,AP=new W(1714765),qM=.94;var e0=class{host;options;renderer;scene=new Tn;camera=new Jt(38,1,.1,400);controls;labels;root=new ct;patternTexture;blindTexture;openingTargets=new Map;fridges=new Map;covers=new Map;screens=new Map;pickFurniture=new Map;pickOpenings=new Map;pickOpenings2=new Map;flashes=new Map;surfaceGrab=null;surfaceDragging=!1;furnishTypes=null;roofWindows=new Map;roofWindowsKey="";persons=[];personPins=new Map;floorInfo=new Map;roomInfo=new Map;groundTexture=null;devices=[];devicePins=new Map;ground;floors=[];building=null;furnitureColors=null;notePhoto=null;floorId=null;roomId=null;wallMode="auto";painted=!1;explode;frame=0;lastFrame=0;qualityMode="auto";governor=null;disposed=!1;resizeObserver;fpsFrames=0;worstFrame=0;lastStatsFrame=0;lowQuality=!1;highQuality=!1;effectTime=0;effectTick=!1;tintTick=!1;effectTimer;awakeUntil=0;deviceLook="";haloTexture;roof=null;roofO=0;keepRoof=!1;robots=new Map;pets=new Map;petMat=null;petTimer;robotGeo=null;robotTrails=new Map;trailTimers=new Map;robotMat=null;mowerMat=null;robotLedGeo=null;robotLast=0;petLast=0;meshes=[];meshLight=null;meshAsked=new Set;robotTimer;floorStack="dim";floorMap=new Map;labelsDirty=!0;viewKey=new Float64Array(6);pinMode=new WeakMap;size={w:1,h:1};labelInset=0;effectFloors=new Set;deviceFloor=new Map;statsOn=!1;parked=new Map;parkedSig="";plain=!1;rightBack=!1;rightDown=null;gateOpen=new Map;gateSig="";orbitSpeed=0;orbitLast=0;orbitTimer;onScreen=!0;intersection=null;swipe=null;furnish=!1;selectedFurniture=null;selectedDevice=null;pendingDevice=null;labelPlacer=new Bu;pinHooks={furnishing:()=>this.furnish,pressedWhileFurnishing:e=>this.pendingDevice=e,selectWhileFurnishing:e=>{this.selectDevice(e),this.options.onDeviceSelect?.(e)},centre:e=>{let[t,n]=[e.getBoundingClientRect(),this.host.getBoundingClientRect()];return{x:t.left+t.width/2-n.left,y:t.top+t.height/2-n.top}},tap:(e,t,n)=>{let r=this.tapInRoom?this.devices.find(s=>s.id===e):void 0;if(r&&!this.deviceInReach(r.floorId,r.roomId))return this.options.onRoomTap?.(r.floorId,r.roomId);this.options.onDeviceTap?.(e,t,n)},hold:(e,t,n)=>this.options.onDeviceHold?.(e,t,n)};tapInRoom=!1;deviceGrab=null;grab=null;ghost=null;theme="neon";themeUniform={value:0};sun=null;weatherLayer;houseShadow=new Vu;sunArc=new Ku;sunArcLocation=null;shadowKey="";footprint={key:"",rings:[]};mapLayer;mapSettings=null;mapNorth=0;groundY=0;skyView=null;weatherTimer;energyLayer;soundLayer;waterLayer;glassAlpha={value:.2};screenLayer;pictureLayer;liveAnchors=[];liveAnchorCb=null;roomTint=null;houseRadius=20;startView=null;fpsStart=0;constructor(e,t={}){this.host=e,this.options=t,this.explode=t.explode??!0,this.qualityMode=t.quality??"auto",this.renderer=this.makeRenderer(this.qualityMode),this.labels=document.createElement("div"),this.labels.className="nf-labels",e.append(this.labels),this.patternTexture=EP(),this.blindTexture=RP(),this.haloTexture=PP(),this.ground=new we(new sn(1,1),new Ke({transparent:!0,blending:Ft,depthWrite:!1})),this.ground.rotation.x=-Math.PI/2,this.ground.renderOrder=-1,this.scene.add(this.ground,this.root),this.weatherLayer=new wh(this.scene),this.scene.add(this.houseShadow.mesh),this.scene.add(this.sunArc.group),this.mapLayer=new _h(this.scene),this.mapLayer.onChange=()=>this.invalidate(),this.energyLayer=new Eh(this.scene,this.liftOf),this.soundLayer=new Rh(this.scene,this.liftOf),this.waterLayer=new Ph(this.scene,this.liftOf),this.screenLayer=new Ih(this.scene,this.liftOf),this.screenLayer.onChange=()=>this.invalidate(),this.pictureLayer=new Lh(this.scene,this.liftOf),this.pictureLayer.onChange=()=>this.invalidate(),this.weatherLayer.onFlash=n=>this.host.classList.toggle("live-flash",n),this.controls=this.makeControls(),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e),document.addEventListener("visibilitychange",this.onVisibility),this.host.addEventListener("pointerdown",this.onTouch,{passive:!0}),this.renderer.domElement.addEventListener("pointerdown",this.onRightDown),this.renderer.domElement.addEventListener("pointerup",this.onRightUp),this.renderer.domElement.addEventListener("contextmenu",this.onContext),this.awakeUntil=performance.now()+YM,typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(n=>{let r=n.some(s=>s.isIntersecting);r!==this.onScreen&&(this.onScreen=r,r||(clearTimeout(this.effectTimer),this.effectTimer=void 0),r&&this.invalidate())}),this.intersection.observe(e)),this.resize()}get low(){return this.lowQuality}setRightBack(e){this.rightBack=e}onRightDown=e=>{this.rightDown=this.rightBack&&e.button===2?{x:e.clientX,y:e.clientY,at:performance.now()}:null};onRightUp=e=>{let t=this.rightDown;this.rightDown=null,!(!this.rightBack||!t||e.button!==2)&&Math.hypot(e.clientX-t.x,e.clientY-t.y)<6&&performance.now()-t.at<400&&this.options.onBack?.()};onContext=e=>{this.rightBack&&e.preventDefault()};setPlain(e){e!==this.plain&&(this.plain=e,this.building&&(this.rebuild(),this.invalidate()))}exportStl(e=10){let t=[];for(let n of this.floors)for(let r of[n.wallMesh,n.floorMesh]){let s=r.geometry.getAttribute("position");s&&t.push({positions:s.array,lift:n.floor.elevation})}return Ey(t,e)}setGateStates(e){let t=[...e].map(([n,r])=>`${n}=${r?1:0}`).sort().join("|");t!==this.gateSig&&(this.gateSig=t,this.gateOpen=e,this.building&&(this.rebuild(),this.invalidate()))}setParked(e){let t=[...e].map(([n,r])=>`${n}=${r}`).sort().join("|");t!==this.parkedSig&&(this.parkedSig=t,this.parked=e,this.building&&(this.rebuild(),this.invalidate()))}setStats(e){this.statsOn=e}setLabelInset(e){this.labelInset!==e&&(this.labelInset=e,this.labelsDirty=!0,this.invalidate())}setAutoOrbit(e){this.orbitSpeed=e,this.orbitLast=0,this.invalidate()}setQuality(e){this.qualityMode=e,this.swapRenderer(e)}dropToLow(){this.disposed||this.lowQuality||this.swapRenderer("low")}swapRenderer(e){let t=this.renderer.domElement,n=this.makeRenderer(e);this.rebuildTier(),this.applyTierFlags(),t.replaceWith(n.domElement),this.renderer.dispose(),this.renderer.forceContextLoss(),this.renderer=n;let{view:r,locked:s}=this.controls;this.controls.dispose(),this.controls=this.makeControls(),this.controls.view=r,this.controls.locked=s,this.resize()}setMeshSource(e){N0(e)}setPacks(e){Nl(e),this.building&&(this.rebuild(),this.invalidate())}setBuilding(e){let t=this.building===null;this.building=e,this.rebuild(),t&&this.fit(0),this.invalidate()}get walking(){return this.controls.walk!==null}startWalk(){let e=this.floors.filter(l=>l.floor.rooms.some(c=>c.points.length>=3)),t=(this.floorId?this.floorMap.get(this.floorId):void 0)??[...e].sort((l,c)=>Math.abs(l.floor.elevation)-Math.abs(c.floor.elevation))[0];if(!t||!t.bbox)return null;let n=t.floor.rooms.filter(l=>l.points.length>=3),r=n.find(l=>l.id===this.roomId)??[...n].sort((l,c)=>vr(c.points)-vr(l.points))[0],[s,o]=r?Bs(r.points):[(t.bbox.x0+t.bbox.x1)/2,(t.bbox.z0+t.bbox.z1)/2];this.floorId!==t.floor.id&&this.setFloor(t.floor.id,!1);let a=.3;return this.controls.walk={eye:new U(s,t.floor.elevation+t.ty+TP,o),yaw:this.controls.view.theta,pitch:-.05,stick:[0,0],keys:new Set,bounds:{x0:t.bbox.x0-a,x1:t.bbox.x1+a,z0:t.bbox.z0-a,z1:t.bbox.z1+a},last:0},this.labelsDirty=!0,this.wake(),t.floor.id}stopWalk(){this.controls.walk&&(this.controls.walk=null,this.labelsDirty=!0,this.fit(700))}setWalkStick(e,t){this.controls.walk&&(this.controls.walk.stick=[e,t],this.wake())}setFloor(e,t=!0){let n=this.keepCamera&&this.floorId!==null&&e!==null&&e!==this.floorId?{theta:this.controls.view.theta,phi:this.controls.view.phi,radius:this.controls.view.radius}:null;this.floorId=e,this.roomId=null,this.labelsDirty=!0,this.applyTargets(!t),this.applyHighlight(),this.fit(t?700:0,n)}setKeepCamera(e){this.keepCamera=e}setZoom(e){let t=Math.min(3,Math.max(.5,e||1));t!==this.zoom&&(this.zoom=t,this.building&&this.fit(400))}setFloorStack(e){e!==this.floorStack&&(this.floorStack=e,this.applyTargets(!1))}setKeepRoof(e){e!==this.keepRoof&&(this.keepRoof=e,this.invalidate())}setExplode(e){e!==this.explode&&(this.explode=e,this.applyTargets(!1),this.floorId===null&&this.fit(700))}selectRoom(e){if(this.roomId=e,this.labelsDirty=!0,this.applyHighlight(),!e){this.fit(700);return}let t=this.floors.find(u=>u.floor.rooms.some(h=>h.id===e)),n=t?.floor.rooms.find(u=>u.id===e);if(!t||!n)return;let r=n.start_view;if(r){let u=t.floor.elevation+t.ty,[h,f]=Bs(n.points),d=r.target??{x:h,y:.3,z:f};this.controls.flyTo({target:new U(d.x,d.y+u,d.z),radius:r.radius,phi:r.phi,theta:r.theta});return}let[s,o]=Bs(n.points),a=n.points.map(u=>u[0]),l=n.points.map(u=>u[1]),c=new U(Math.max(...a)-Math.min(...a),t.floor.cut_height,Math.max(...l)-Math.min(...l));this.controls.flyTo({target:new U(s,t.floor.elevation+t.ty+.3,o),radius:Math.max(4,this.distanceFor(c)*1.05),phi:.72})}get lowered(){return this.wallMode!=="auto"}setPaintedWalls(e){e!==this.painted&&(this.painted=e,this.rebuild(),this.invalidate())}wallPaint(e){return this.painted&&this.building?Gp(this.building.settings,e):void 0}setWallMode(e){this.wallMode=e;for(let t of this.floors)this.buildLamps(t);this.invalidate()}setDevices(e){let t=e.map(r=>`${r.id}:${r.active?1:0}:${r.glow?r.glow.level.toFixed(1):"-"}`).join(";");t!==this.deviceLook&&(this.deviceLook=t,this.wake()),this.devices=e,this.labelsDirty=!0,this.effectFloors=new Set(e.filter(r=>r.effect&&r.glow||(r.spin??0)>0).map(r=>r.floorId)),this.deviceFloor=new Map(e.map(r=>[r.id,r.floorId]));let n=new Set;for(let r of e){n.add(r.id);let s=this.devicePins.get(r.id);s||(s={el:Ay(r.id,this.pinHooks),icon:"",text:"",watt:"",label:"",active:!1,unavailable:!1,glow:"",caption:""},this.devicePins.set(r.id,s),this.labels.append(s.el));let o=s.el;s.icon!==r.icon&&(s.icon=r.icon,o.querySelector(".nf-dev-icon").innerHTML=r.icon),s.text!==r.text&&(s.text=r.text,o.querySelector(".nf-dev-text").textContent=r.text);let a=r.caption??"";s.caption!==a&&(s.caption=a,o.querySelector(".nf-dev-name").textContent=a);let l=r.power!==null&&r.power!==void 0&&r.power>=1?r.powerText??`${Math.round(r.power)} W`:"";s.watt!==l&&(s.watt=l,o.querySelector(".nf-dev-watt").textContent=l);let c=`${r.name}: ${r.text}`;s.label!==c&&(s.label=c,o.title=r.name,o.setAttribute("aria-label",c)),s.active!==r.active&&(s.active=r.active,o.classList.toggle("nf-dev-on",r.active)),s.unavailable!==r.unavailable&&(s.unavailable=r.unavailable,o.classList.toggle("nf-dev-na",r.unavailable));let u=r.glow?`rgb(${r.glow.color.map(h=>Math.round(h*255)).join(", ")})`:"";s.glow!==u&&(s.glow=u,u?o.style.setProperty("--nf-glow",u):o.style.removeProperty("--nf-glow"))}for(let[r,s]of this.devicePins)n.has(r)||(s.el.remove(),this.devicePins.delete(r));for(let r of this.floors)this.buildGlow(r),this.buildLamps(r);this.invalidate()}setRoofWindows(e){let t=JSON.stringify([...e]);t!==this.roofWindowsKey&&(this.roofWindowsKey=t,this.roofWindows=e,this.buildRoofMesh(),this.invalidate())}setPersons(e){this.labelsDirty=!0,this.persons=e;let t=new Set;for(let n of e){t.add(n.id);let r=this.personPins.get(n.id);if(r||(r=document.createElement("div"),r.className="nf-person",r.dataset.entity=n.id,this.personPins.set(n.id,r),this.labels.append(r)),r.title=n.name,r.setAttribute("aria-label",n.name),r.dataset.picture!==(n.picture??"")||r.dataset.initials!==n.initials)if(r.dataset.picture=n.picture??"",r.dataset.initials=n.initials,r.replaceChildren(),n.picture){let s=document.createElement("img");s.src=n.picture,s.alt="",s.addEventListener("error",()=>s.replaceWith(document.createTextNode(n.initials))),r.append(s)}else r.textContent=n.initials}for(let[n,r]of this.personPins)t.has(n)||(r.remove(),this.personPins.delete(n));this.invalidate()}setNavigationLocked(e){this.controls.locked=e}setPickTargets(e,t,n=new Map){this.pickFurniture=e,this.pickOpenings=t,this.pickOpenings2=n}setNotePhotos(e){this.notePhoto=e}setFurnitureColors(e){JSON.stringify(e??{})!==JSON.stringify(this.furnitureColors??{})&&(this.furnitureColors=e,this.building&&(this.rebuild(),this.invalidate()))}setAccent(e){let t=wy(e),n=t?1:0;n===Yu.value&&(!t||Xu.value.equals(new U(...t)))||(Yu.value=n,t&&Xu.value.set(...t),this.invalidate())}setTheme(e){if(e===this.theme)return;this.theme=e,this.placeMap(),this.themeUniform.value=Sy(e);let t=xl(e),n=[...this.floors.map(r=>r.materials.lines),...this.roof?[this.roof.lines]:[]];for(let r of n)r.blending=t,r.needsUpdate=!0;this.placeGround(),this.invalidate()}setFurnishMode(e){this.furnish=e,e||this.selectFurniture(null),this.invalidate()}selectFurniture(e){e&&this.selectedDevice&&this.selectDevice(null),this.selectedFurniture=e,this.updateGhost(),this.invalidate()}setSun(e){this.sun=e;for(let t of this.floors)this.buildSun(t);this.buildHouseShadow(),this.buildSunArc(),this.invalidate()}setLocation(e){this.sunArcLocation=e,this.buildSunArc(),this.invalidate()}buildSunArc(){let e=this.building,t=this.sunArcLocation,n=(e?.floors??[]).flatMap(c=>[...c.rooms.flatMap(u=>u.points),...(c.outdoor??[]).flatMap(u=>u.points)]);if(!e||!e.settings.sun_arc||!t||!n.length)return void this.sunArc.update(null,null,0);let r=n.map(c=>c[0]),s=n.map(c=>c[1]),o=[(Math.min(...r)+Math.max(...r))/2,(Math.min(...s)+Math.max(...s))/2],a=Math.max(6,Math.hypot(Math.max(...r)-Math.min(...r),Math.max(...s)-Math.min(...s))/2+3),l=Math.min(0,...e.floors.map(c=>c.elevation));this.sunArc.update({centre:o,radius:a,north:e.settings.north??0,...t},this.sun,l)}buildHouseShadow(){if(!this.houseShadow)return;let e=this.building,t=(e?.floors??[]).filter(u=>u.elevation>=-.01&&u.rooms.length),n=!e||!t.length||e.settings.sun_patches===!1||this.lowQuality,r=this.weatherLayer?.cloud??0,s=e?.settings.north??0,o=t.map(u=>`${u.elevation}:${u.height}:${JSON.stringify(u.rooms.map(h=>h.points))}`).join("|"),a=n?"off":`${this.sun?.elevation.toFixed(1)},${this.sun?.azimuth.toFixed(1)},${s},${r.toFixed(2)},${o}`;if(a===this.shadowKey)return;if(this.shadowKey=a,n){this.houseShadow.update([],0,0,null,0,0,!0);return}let l=Math.min(...t.map(u=>u.elevation)),c=Math.max(...t.map(u=>u.elevation+u.height));this.footprint.key!==o&&(this.footprint={key:o,rings:fr(t.flatMap(u=>u.rooms.map(h=>h.points)))}),this.houseShadow.update(this.footprint.rings,c-l,l+.03,this.sun,s,r,!1)}liftOf=e=>{if(!e)return{y:0,dy:0,visible:!0};let t=this.floorMap.get(e);return t?{y:t.floor.elevation+t.y,dy:t.y,visible:t.group.visible}:{y:0,dy:0,visible:!1}};setLiveEnergy(e,t){this.energyLayer.setArcs(e),this.energyLayer.setSparks(t),this.invalidate()}setLiveSound(e,t){this.soundLayer.set(e,t),this.invalidate()}setGlassWalls(e){let t=Math.min(1,Math.max(0,e));t!==this.glassAlpha.value&&(this.glassAlpha.value=t,this.invalidate())}setLiveWater(e){this.waterLayer.set(e),this.invalidate()}setLiveScreens(e){let t=[];for(let n of e){let r=this.building?.floors.find(a=>a.id===n.floorId),s=r?.furniture.find(a=>a.id===n.furnitureId),o=s&&r?th(s,r):null;!s||!o||t.push({...n,x:s.x,z:s.z,rotation:s.rotation,rect:o})}this.screenLayer.set(t),this.invalidate()}setPictures(e){let t=[];for(let n of e){let r=this.building?.floors.find(a=>a.id===n.floorId),s=r?.furniture.find(a=>a.id===n.furnitureId),o=s&&r?Sp(s,r):null;!s||!o||t.push({id:n.furnitureId,floorId:n.floorId,url:n.url,border:n.border,fit:n.fit,x:s.x,z:s.z,rotation:s.rotation,rect:o})}this.pictureLayer.set(t),this.invalidate()}setLiveAnchors(e,t){this.liveAnchors=e,this.liveAnchorCb=t,this.invalidate()}placeLhAnchors(){let e=this.liveAnchorCb;if(!e||!this.liveAnchors.length)return;let t=new U;this.liveAnchors.forEach((n,r)=>{let s=this.liftOf(n.floorId);t.set(n.x,s.y+n.y,n.z).project(this.camera);let o=s.visible&&t.z<1&&Math.abs(t.x)<1.15&&Math.abs(t.y)<1.15;e(r,(t.x+1)/2*this.size.w,(1-t.y)/2*this.size.h,o)})}setSky(e){this.skyView=e,this.weatherLayer.set(e?{...e,low:e.low||this.lowQuality}:null),this.buildHouseShadow();for(let t of this.floors)this.buildSun(t);this.invalidate()}setRoomTint(e){let t=!!e!=!!this.roomTint;if(this.roomTint=e,this.tintTick=!0,this.applyHighlight(),t)for(let n of this.floors)n.glowSig="",this.buildGlow(n)}setScreens(e){this.screens=e;for(let t of this.floors)this.buildScreens(t);this.invalidate()}fillRoomPin(e,t,n){if(e.textContent=t||"\u2013",n){let r=document.createElement("small");r.textContent=n,e.append(r),e.classList.add("nf-pin-info")}else e.classList.remove("nf-pin-info")}setRoomInfo(e){if(!(e.size===this.roomInfo.size&&[...e].every(([n,r])=>this.roomInfo.get(n)===r))){this.roomInfo=e;for(let n of this.floors)for(let r of n.roomPins)this.fillRoomPin(r.pin,r.room.name,e.get(r.room.id))}}setFloorInfo(e){this.floorInfo=e;for(let t of this.floors){let n=t.label.querySelector("span"),r=e.get(t.floor.id)??this.options.floorInfo?.(t.floor)??"";n&&n.textContent!==r&&(n.textContent=r,t.labelSize=null,this.labelsDirty=!0)}this.invalidate()}setOpeningStates(e){let t=this.openingTargets;this.openingTargets=e,[...e].some(([n,r])=>!tp(t.get(n)??Ns,r))&&this.wake(),this.invalidate()}wake(){this.awakeUntil=performance.now()+YM,this.invalidate()}get resting(){return this.lowQuality&&performance.now()>this.awakeUntil}setFridgeDoors(e){for(let[t,n]of e){let r=this.fridges.get(t)??{l:n.left?1:0,r:n.right?1:0,tl:0,tr:0};r.tl=n.left?1:0,r.tr=n.right?1:0,this.fridges.set(t,r)}for(let t of[...this.fridges.keys()])e.has(t)||this.fridges.delete(t);this.invalidate()}setCovers(e){let t=!1;for(let[n,r]of e){let s=this.covers.get(n);s?s.t!==r&&(s.t=r,t=!0):(this.covers.set(n,{k:r,t:r}),t=!0)}for(let n of[...this.covers.keys()])e.has(n)||this.covers.delete(n);if(t){for(let n of this.floors)this.buildFridges(n);this.wake()}}stepCovers(e){let t=Math.min(1,e/4e3),n=!1;for(let r of this.covers.values()){if(r.k===r.t)continue;let s=r.t-r.k;r.k=Math.abs(s)<=t?r.t:r.k+Math.sign(s)*t,n=!0}if(n)for(let r of this.floors)this.buildFridges(r);return n}stepFridges(e){let t=ep(e),n=new Set;for(let[r,s]of this.fridges)for(let[o,a]of[["l","tl"],["r","tr"]]){let l=s[a]-s[o];if(Math.abs(l)<.004){l!==0&&(s[o]=s[a],n.add(r));continue}s[o]+=l*t,n.add(r)}if(!n.size)return!1;for(let r of this.floors)r.floor.furniture.some(s=>n.has(s.id))&&this.buildFridges(r);return!0}buildFridges(e){let t=new lt;for(let n of e.floor.furniture){let r=vt(n.type);if(r&&P0(r)){Gd(t,r,n,Gt(e.floor,n),this.covers.get(n.id)?.k??I0(r,null));continue}if(n.type!=="fridge_smart")continue;let s=this.fridges.get(n.id);vp(t,n,Gt(e.floor,n),s?.l??0,s?.r??0)}e.fridgeMesh.geometry.dispose(),e.fridgeMesh.geometry=t.geometry(),e.fridgeMesh.visible=t.count>0}resetView(){this.fit(700)}setStartView(e){this.startView=e}currentView(){let e=this.controls.view,t=this.floorBase(this.floorId);return{theta:e.theta,phi:e.phi,radius:e.radius,target:{x:e.target.x,y:e.target.y-t,z:e.target.z}}}floorBase(e){let t=e===null?void 0:this.floorMap.get(e);return t?t.floor.elevation+t.ty:0}dispose(){this.disposed=!0,cancelAnimationFrame(this.frame),clearTimeout(this.effectTimer),clearTimeout(this.robotTimer),clearTimeout(this.orbitTimer),clearTimeout(this.weatherTimer),this.weatherLayer.dispose(),this.sunArc?.dispose(),this.houseShadow?.dispose(),this.mapLayer.dispose(),this.energyLayer.dispose(),this.soundLayer.dispose(),this.waterLayer.dispose(),this.screenLayer.dispose(),this.pictureLayer.dispose(),this.resizeObserver.disconnect(),this.intersection?.disconnect(),document.removeEventListener("visibilitychange",this.onVisibility),this.host?.removeEventListener("pointerdown",this.onTouch),this.renderer?.domElement?.removeEventListener?.("pointerdown",this.onRightDown),this.renderer?.domElement?.removeEventListener?.("pointerup",this.onRightUp),this.renderer?.domElement?.removeEventListener?.("contextmenu",this.onContext),clearTimeout(this.petTimer),this.controls.dispose(),this.clear(),this.building=null,this.buildRoofMesh(),this.ground.geometry.dispose(),this.ground.material.dispose(),this.patternTexture.dispose(),this.blindTexture.dispose(),this.groundTexture?.dispose(),this.haloTexture.dispose();for(let e of this.robots.values())e.led.dispose();this.robots.clear();for(let e of this.robotTrails.values())e.removeFromParent(),e.geometry.dispose(),e.material.dispose();this.robotTrails.clear();for(let e of this.trailTimers.values())clearTimeout(e);this.trailTimers.clear(),this.robotGeo?.dispose(),this.robotLedGeo?.dispose(),this.robotMat?.dispose(),this.mowerMat?.dispose(),this.meshLight?.dispose(),this.renderer.dispose(),this.renderer.forceContextLoss(),this.renderer.domElement.remove(),this.labels.remove()}invalidate(){this.frame||this.disposed||document.hidden||!this.onScreen||(this.frame=requestAnimationFrame(e=>this.render(e)))}makeRenderer(e){let t=e==="low"||e==="auto"&&xb();this.lowQuality=t,this.weatherLayer&&this.skyView&&this.weatherLayer.set({...this.skyView,low:this.skyView.low||t}),this.weatherLayer&&this.buildHouseShadow(),this.highQuality=e==="high";let n=new kr({antialias:!t,alpha:!0,powerPreference:t?"low-power":"default"}),r=Math.min(window.devicePixelRatio||1,t?1:e==="high"?2.5:2);return n.setPixelRatio(r),this.governor=e==="auto"&&!t?new Lu(r,Math.min(1,r)):null,n.setClearColor(0,0),n.outputColorSpace=ft,n.domElement.className="nf-canvas",this.host.prepend(n.domElement),n}makeControls(){return new El(this.renderer.domElement,this.camera,{change:()=>this.wake(),tap:(e,t)=>this.onTap(e,t),hold:(e,t)=>this.onHold(e,t),swipeStart:(e,t,n,r)=>this.swipeStart(e,t,n,r),swipeMove:e=>this.swipe&&this.options.onDeviceSwipe?.(this.swipe.entity,"move",e,this.swipe.x,this.swipe.y),swipeEnd:()=>{this.swipe&&this.options.onDeviceSwipe?.(this.swipe.entity,"end",0,this.swipe.x,this.swipe.y),this.swipe=null},grab:(e,t)=>this.grabFurniture(e,t),drag:(e,t)=>this.dragFurniture(e,t),drop:()=>this.dropFurniture(),doubleTap:(e,t)=>{let n=this.floorId&&this.options.onRoomDoubleTap?this.pick(e,t):null;n&&!("entity"in n)&&n.roomId?this.options.onRoomDoubleTap(n.floorId,n.roomId):this.options.onBack?.()}})}onTouch=()=>this.wake();onVisibility=()=>{document.hidden&&(clearTimeout(this.effectTimer),this.effectTimer=void 0),document.hidden||this.invalidate()};scheduleEffects(){if(!this.hasVisibleEffects(document.hidden)||this.resting){clearTimeout(this.effectTimer),this.effectTimer=void 0;return}if(this.effectTimer!==void 0)return;let e=this.lowQuality?2*XM:XM;this.effectTimer=setTimeout(()=>{if(this.effectTimer=void 0,!!this.hasVisibleEffects(document.hidden)){this.effectTime=performance.now()/1e3,this.effectTick=!0;for(let t of this.floors)t.o<.02||!this.effectFloors.has(t.floor.id)||(this.buildLamps(t),this.buildGlow(t));this.invalidate()}},e)}hasVisibleEffects(e){return!e&&!this.disposed&&this.onScreen&&this.floors.some(t=>t.o>=.02&&this.effectFloors.has(t.floor.id))}resize(){let e=this.host.clientWidth||1,t=this.host.clientHeight||1;this.size={w:e,h:t},this.labelsDirty=!0,this.renderer.setSize(e,t,!1),this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.invalidate()}clear(){for(let e of this.robots.values())e.group.removeFromParent();for(let e of this.meshes)e.group.removeFromParent(),Rm(e.group);this.meshes=[];for(let e of this.floors){e.group.traverse(t=>{t.geometry?.dispose()});for(let t of Object.values(e.materials))Array.isArray(t)||t.dispose();for(let t of e.materials.ghosts)t.material.dispose();this.root.remove(e.group)}this.floors=[],this.floorMap=new Map;for(let e of[...this.labels.children])e.dataset.entity||e.remove()}buildLightSurface(e){let t=this.lowQuality?.5:.25,n=ap(e.floor,e.geo.walls2d,e.geo.wallBuckets,e.geo.openings,t,e.geo.holes,e.geo.roofUnder),r=CP(e.floor,e.geo.openRooms);if(e.lightZones=r.some((a,l)=>a!==l)?r:null,e.lightZones){for(let a=0;a=0&&l=0&&a.a=0&&a.bthis.glowOf(h)),r=t.doors.map(h=>{let f=e.geo.openings.find(p=>p.opening.id===h.id);if(f&&_r(f.opening,f.exterior)==="passage")return 1;let d=e.openings.get(h.id);return d?Math.max(d.open,d.open2??0):.5}),s=n.map(h=>`${h.x.toFixed(2)},${h.y.toFixed(2)},${h.z.toFixed(2)},${h.kind},${h.level.toFixed(3)},${h.color.map(f=>f.toFixed(3)).join("/")}`).join(";")+"|"+r.map(h=>h.toFixed(1)).join(",");if(s===e.glowSig)return;e.glowSig=s;let o=e.glowMesh.geometry,a=o.getAttribute("color");if(!n.length){e.glowMesh.visible=!1,o.setDrawRange(0,0);return}let l=lp(t,n,.42,r);if(this.roomTint){let h=e.floor.rooms.length;for(let f=0;f.004;if(f)for(let d=0;d<6;d++)c[u++]=h*6+d}o.index.needsUpdate=!0,o.setDrawRange(0,u),e.glowMesh.visible=u>0}withoutFurniture(e){if(this.gateOpen.size&&(e.outdoor??[]).some(n=>n.gates?.length)&&(e={...e,outdoor:e.outdoor.map(n=>n.gates?.length?{...n,gates:n.gates.map(r=>({...r,open:this.gateOpen.get(r.id)??!1}))}:n)}),!this.plain)return e;let t=n=>n.type==="stairs"||n.type==="stairwell"||!!vt(n.type)?.hole;return{...e,furniture:e.furniture.filter(t)}}rebuild(){let e=new Map(this.floors.map(s=>[s.floor.id,{y:s.y,o:s.o}])),t=new Map(this.floors.map(s=>[s.floor.id,s.openings]));this.clear();let n=this.building;if(!n)return;fb({...n.settings.furniture_colors,...this.furnitureColors});let r=[...n.floors].sort((s,o)=>s.elevation-o.elevation);for(let s of n.floors){let o=n.settings.roof?.solar??[],a=ih(n)?.id===s.id?o.filter(V=>V.face===Sl).map(V=>({field:V,face:rh(n,V)})):[],l=o.filter(V=>V.face.startsWith(`wall:${s.id}:`));if(l.length){let V=new Map(nh(n,s.id).map(re=>[re.key,re]));for(let re of l){let be=V.get(re.face);be&&a.push({field:re,face:be})}}let u=(n.settings.roof.sections??[]).some(V=>$d(V,s.elevation+s.height))?(V,re)=>{let be=Kd(n,V,re);return be===null?null:be-s.elevation}:void 0,h=Hp(this.withoutFurniture(bh(s,this.parked)),n.settings.wall_exterior,n.settings.wall_interior,Wp(n.floors,s),a,u,this.wallPaint(s)),f={standing:{value:65535},glass:{value:0},slope:{value:new _t},slopeY:{value:new De},glassAlpha:this.glassAlpha},d=Ty({mask:f,look:this.themeUniform,theme:this.theme,textures:{pattern:this.patternTexture,blinds:this.blindTexture,halo:this.haloTexture}}),p=new ct,x=new we(h.floor,d.floor),g=new we(h.shadow,d.shadow);g.renderOrder=1;let m=new we(h.floor,d.pattern);m.renderOrder=2;let b=new we(new Fe,d.glow);b.renderOrder=3,b.visible=!1;let v=new we(new Fe,d.frames),y=new we(new Fe,d.blinds),M=new we(new Fe,d.glass);M.renderOrder=4;let S=new we(new Fe,d.lamps);S.visible=!1;let _=new we(new Fe,d.cones);_.visible=!1,_.renderOrder=3;let w=new xn(new Fe,d.halos);w.visible=!1,w.renderOrder=7;let R=new we(new Fe,d.cones);R.visible=!1,R.renderOrder=7;let A=new we(new Fe,d.lamps);A.visible=!1;let C=new we(new Fe,d.screens);C.visible=!1,C.renderOrder=5;for(let V of[v,y,M])V.frustumCulled=!1;let O=new we(h.walls,d.glassWall),D=new we(h.walls,d.wall);O.renderOrder=6,p.add(x,g,m,b,D,new gn(h.lines,d.lines),v,y,M,S,_,w,R,A,C,O);for(let V of h.ghosts){let re=Zn(new Ke({vertexColors:!0,transparent:!0,opacity:V.opacity,depthWrite:!1,side:ut}),this.themeUniform);d.ghosts.push({material:re,base:V.opacity});let be=new we(V.geometry,re);be.renderOrder=2,p.add(be)}this.root.add(p);let P=document.createElement("button");P.className="nf-pin nf-pin-floor",P.dataset.floor=s.id;let I=document.createElement("b");I.textContent=s.name||"\u2013";let N=document.createElement("span");N.textContent=this.floorInfo.get(s.id)??this.options.floorInfo?.(s)??"",P.append(I,N),P.addEventListener("click",()=>this.options.onFloorTap?.(s.id)),this.labels.append(P);let F=e.get(s.id),H=[],B=null;for(let V of s.rooms){let re=document.createElement("button");re.className="nf-pin",re.dataset.room=V.id,re.dataset.floor=s.id,this.fillRoomPin(re,V.name,this.roomInfo.get(V.id)),re.addEventListener("click",()=>this.options.onRoomTap?.(s.id,V.id)),this.labels.append(re);let[be,Y]=Bs(V.points);H.push({pin:re,room:V,cx:be,cz:Y});for(let[Q,se]of V.points)B??={x0:Q,x1:Q,z0:se,z1:se},B.x0=Math.min(B.x0,Q),B.x1=Math.max(B.x1,Q),B.z0=Math.min(B.z0,se),B.z1=Math.max(B.z1,se)}let X=[];for(let V of s.notes??[]){if(!V.text)continue;let re=document.createElement("button");re.className=`nf-pin nf-note-pin${d0(V)?" nf-note-due":""}`,re.title=V.text;let be=V.text.length>28?`${V.text.slice(0,27)}\u2026`:V.text;re.textContent=`${V.photo?"\u{1F4F7} ":"\u270E "}${be}`,re.addEventListener("click",()=>{let Y=re.classList.toggle("nf-note-open");re.textContent=`${V.photo?"\u{1F4F7} ":"\u270E "}${Y?V.text:be}`;let Q=Y&&V.photo?this.notePhoto?.(V.photo):null;if(Q){let se=document.createElement("img");se.className="nf-note-photo",se.alt="",se.src=Q,se.addEventListener("load",()=>{this.labelsDirty=!0,this.invalidate()}),re.append(se)}this.labelsDirty=!0,this.invalidate()}),this.labels.append(re),X.push({pin:re,note:V})}this.floors.push({floor:s,rank:r.indexOf(s),group:p,geo:h,floorMesh:x,shadowMesh:g,patternMesh:m,glowMesh:b,lightSurface:null,lightZones:null,framesMesh:v,glassMesh:M,blindsMesh:y,lampMesh:S,sunMesh:_,sunSig:"",haloMesh:w,coneMesh:R,wedgeTris:[],fridgeMesh:A,lampTris:[],lampFurnTris:[],frameTris:[],glassTris:[],blindTris:[],wallMesh:D,screenMesh:C,screenSig:"",flowLayout:"",glowSig:"",lampShapeSig:"",lampColorSig:"",lampShade:new Float32Array(0),lampRanges:new Map,bbox:B,roomPins:H,notePins:X,labelSize:null,materials:d,mask:f,openings:new Map,y:F?.y??0,o:F?.o??1,ty:0,to:1,appliedO:-1,label:P})}this.floorMap=new Map(this.floors.map(s=>[s.floor.id,s])),this.buildPets();for(let s of this.floors)this.buildFridges(s);this.labelsDirty=!0,this.floorId&&!n.floors.some(s=>s.id===this.floorId)&&(this.floorId=null);for(let s of this.floors){this.buildLamps(s),this.buildScreens(s);let o=t.get(s.floor.id);for(let a of s.geo.openings)s.openings.set(a.opening.id,o?.get(a.opening.id)??this.openingTargets.get(a.opening.id)??Ns);this.buildOpenings(s),this.buildLightSurface(s),this.buildSun(s)}this.applyTargets(e.size===0),this.applyHighlight(),this.applyTierFlags(),this.buildRoofMesh(),this.updateGhost(),this.placeMeshes()}placeMeshes(){for(let e of this.meshes)e.group.removeFromParent(),Rm(e.group);this.meshes=[];for(let e of this.floors)for(let t of bh(e.floor,this.parked).furniture){let n=vt(t.type);if(!n?.mesh)continue;let r=n.mesh;if(!Dl(t.type)){this.meshAsked.has(r)||(this.meshAsked.add(r),yM(r).then(a=>{a&&!this.disposed&&this.rebuild()}));continue}let s=n.colors?.length?(n.colors.find(a=>a.id===t.variant)??n.colors[0]).hex:null,o=_M(r,{x:t.x,z:t.z,y:Gt(e.floor,t),rotation:t.rotation,mirror:t.mirror,w:t.w,d:t.d,h:t.h,paint:s});o&&(this.meshLight||(this.meshLight=vM(this.root,this.renderer)),MM(o,this.meshLight.env),e.group.add(o),this.meshes.push({group:o,furnitureId:t.id}))}this.invalidate()}buildRoofMesh(){this.roof&&(this.roof.group.traverse(a=>a.geometry?.dispose()),this.roof.solid.dispose(),this.roof.lines.dispose(),this.roof.glass.dispose(),this.scene.remove(this.roof.group),this.roof=null);let e=this.building?kp(this.building,this.roofWindows):[];if(!e.length)return;let t=new ct,n=Zn(new Ke({vertexColors:!0,transparent:!0,side:ut}),this.themeUniform),r=Zn(new Lt({vertexColors:!0,transparent:!0,blending:xl(this.theme),depthWrite:!1}),this.themeUniform,!0),s=Zn(new Ke({vertexColors:!0,transparent:!0,side:ut,depthWrite:!1}),this.themeUniform),o=e.map(a=>{let l=new ct;return l.add(new we(a.solid.geometry(),n),new gn(a.lines.geometry(),r)),a.glass.count&&l.add(new we(a.glass.geometry(),s)),l.renderOrder=8,t.add(l),{group:l,floorId:a.floor.id,rideId:Jd(this.building,a.floor,a.sections??[]),base:a.base,lift:a.lift!==!1}});t.renderOrder=8,this.scene.add(t),this.roof={group:t,parts:o,solid:n,lines:r,glass:s},this.placeRoof()}placeRoof(e=1e3){let t=this.roof;if(!t)return!1;let n=this.keepRoof?1:Math.min(1,Math.max(0,(this.controls.view.radius/this.houseRadius-.62)/.3)),s=(this.floorId===null||this.floors.length===1)&&!this.lowered?qM*n:0,o=Qd(e),a=this.roofO;this.roofO+=(s-this.roofO)*o,Math.abs(s-this.roofO)<.004&&(this.roofO=s),t.group.visible=this.roofO>.02;for(let l of t.parts){let c=this.floorMap.get(l.floorId);if(!c)continue;let u=this.floorMap.get(l.rideId)??c,h=u.ty>0?Math.min(1,u.y/u.ty):this.explode&&this.floorId===null?1:0,f=Math.max(0,1-this.roofO/qM);l.group.position.y=c.floor.elevation+u.y+l.base+f*2.2+(l.lift?h*SP:0)}return t.solid.opacity=this.roofO,t.solid.depthWrite=this.roofO>.5,t.lines.opacity=this.roofO,t.glass.opacity=this.roofO*.28,this.roofO!==a&&this.roofO!==s}applyTierFlags(){let e=this.lowQuality;this.ground.visible=!e&&this.theme!=="day"&&this.floors.some(t=>t.floor.rooms.length>0);for(let t of this.floors)t.patternMesh.visible=!e,t.shadowMesh.visible=!e&&t.o>.98;this.invalidate()}rebuildTier(){for(let e of this.floors)e.flowLayout="",this.buildLightSurface(e),e.lampShapeSig="",this.buildLamps(e)}get houseView(){return this.floorId===null&&this.floors.length>1}applyTargets(e){let t=this.floorId?this.floorMap.get(this.floorId):void 0;for(let n of this.floors){let r=Vb(n.rank,t?.rank,this.explode,this.floorStack);[n.ty,n.to]=[r.y,r.opacity],e&&([n.y,n.o]=[r.y,r.opacity]),this.applyFloor(n)}this.invalidate()}applyFloor(e){e.group.position.y=e.floor.elevation+e.y,e.group.visible=e.o>.02,e.shadowMesh.visible=e.o>.98&&!this.lowQuality,!(Math.abs(e.appliedO-e.o)<.001)&&(e.appliedO=e.o,Hb(e.materials,e.o))}stepFloors(e){let t=!1,n=Qd(e);for(let r of this.floors){let s=Gb(r,n);s.settled&&(this.labelsDirty=!0),(s.moving||s.settled)&&this.applyFloor(r),t||=s.moving}return t}stepOpenings(e){let t=!1,n=ep(e);for(let r of this.floors){let s=!1;for(let[o,a]of r.openings){let l=this.openingTargets.get(o)??Ns;if(tp(a,l))continue;let c=Yb(a,l,n);r.openings.set(o,c.state),s=!0,t||=c.moving}s&&(this.buildOpenings(r),this.buildGlow(r),this.buildSun(r))}return t}fanPhase(e){return e.lamp!=="fan"||!e.spin?0:Math.round(this.effectTime*e.spin*360%KM*10)/10}glowOf(e){return Lv(e.glow,e.effect,this.effectTime)}buildLamps(e){let t=performance.now(),n=h=>{let f=this.flashes.get(h);if(!f||f<=t)return 0;let d=f-t,p=d>jm?.5+.5*Math.sin(d/140):d/jm;return Math.round(p*10)/10},r=this.devices.filter(h=>h.floorId===e.floor.id&&h.lamp),s=this.wallMode+(this.lowQuality?"L":this.highQuality?"H":"M")+r.map(h=>`${h.id},${h.lamp},${h.variant},${h.x},${h.z},${h.y},${h.rotation??0},${h.roll??0},${h.upright?1:0},${h.rise??0},${h.size?.join("/")},${h.base??0},${h.pack??""},${h.mirror?1:0},${h.ceiling??""},${this.fanPhase(h)}`).join(";"),o=r.map(h=>this.glowOf(h)),a=this.devices.filter(h=>h.floorId===e.floor.id&&h.wedge),l=r.map((h,f)=>`${n(h.id)},${o[f]?`${o[f].level.toFixed(3)},${o[f].color.map(d=>d.toFixed(3)).join("/")}`:"off"}`).join(";")+"|"+a.map(h=>`${h.id},${h.x},${h.z},${h.rotation??0},${JSON.stringify(h.wedge)}`).join(";");if(s!==e.lampShapeSig||!e.lampMesh.geometry.getAttribute("position")){e.lampShapeSig=s,e.lampColorSig="";let h=new lt,f=[],d=[],p=new Map,x=e.floor.height;for(let g of r){let m=g.lamp==="strip"?(g.base??x)>Math.min(e.floor.cut_height,g.ceiling??x):g.lamp?ku.has(g.lamp):!1;if(!g.lamp||m&&this.lowered)continue;let b=h.count,v=g.pack?vt(g.pack):void 0,[y,M,S]=g.size??[.3,.3,.3];v?rl(h,v,{x:g.x,z:g.z,rotation:g.rotation??0,w:y,d:M,h:S,mirror:g.mirror},g.base??0,65280):Jm(h,{...g,lamp:g.lamp,phase:this.fanPhase(g)},g.ceiling??x,65280),p.set(g.furnitureId??g.id,{start:b,end:h.count}),g.pickable!==!1&&f.push({id:g.id,start:b,end:h.count}),g.furnitureId&&d.push({id:g.furnitureId,start:b,end:h.count})}e.lampTris=f,e.lampFurnTris=d,e.lampRanges=p,e.lampShade=bb(h.c),e.lampMesh.geometry.dispose(),e.lampMesh.geometry=h.geometry(),e.lampMesh.visible=h.count>0}if(l===e.lampColorSig)return;e.lampColorSig=l;let c=e.lampMesh.geometry.getAttribute("color"),u=c.array;r.forEach((h,f)=>{let d=e.lampRanges.get(h.furnitureId??h.id);if(!d)return;let p=o[f],x=p?.55+.45*p.level:0,g=p?new W(...p.color.map(v=>Math.min(1,v*x))):new W(wP),m=n(h.id);m>0&&g.lerp(new W(1,1,1),.7*m);let b=new W(g.getHex());yb(u,e.lampShade,d,[b.r,b.g,b.b])}),c.needsUpdate=!0,this.buildHalos(e)}buildSun(e){let t=this.building?.settings.sun_patches===!1?null:this.sun,n=this.building?.settings.north??0,r=this.weatherLayer?.cloud??0,s=iy(t,n,r,e.openings.values());if(s===e.sunSig)return;e.sunSig=s;let o=ry({floor:e.floor,openings:e.geo.openings,states:e.openings,sun:t,northDegrees:n,cloud:r});e.sunMesh.geometry.dispose(),e.sunMesh.geometry=o.geometry(),e.sunMesh.visible=o.count>0}buildHalos(e){let t={positions:[],colours:[]},n=new lt,r=[];for(let a of this.devices)if(a.floorId===e.floor.id&&a.wedge){let l=Jb(n,a,e.geo.walls2d);a.wedge.through||r.push({id:a.id,...l})}e.wedgeTris=r;let s=this.lowered;for(let a of this.lowQuality?[]:this.devices){let l=this.glowOf(a);if(a.floorId!==e.floor.id||!a.lamp||!l||s&&ty(a.lamp))continue;let c=a;Qb(t,c,l,a.ceiling??e.floor.height),this.highQuality&&(a.lamp==="downlight"||a.lamp==="spot")&&ey(n,c,l,a.ceiling??e.floor.height)}let o=new Fe;o.setAttribute("position",new ke(t.positions,3)),o.setAttribute("color",new ke(t.colours,3)),e.haloMesh.geometry.dispose(),e.haloMesh.geometry=o,e.haloMesh.visible=!this.lowQuality&&t.positions.length>0,e.coneMesh.geometry.dispose(),e.coneMesh.geometry=n.geometry(),e.coneMesh.visible=n.count>0}buildScreens(e){let t=bh(e.floor,this.parked).furniture.filter(s=>this.screens.has(s.id)),n=t.map(s=>`${s.id}:${s.x},${s.z},${s.rotation},${s.w},${s.d},${s.h},${s.mount_y??""},${s.mirror?1:0}:${JSON.stringify(this.screens.get(s.id))}`).join(";");if(n===e.screenSig&&e.screenMesh.geometry.getAttribute("position"))return;e.screenSig=n;let r=new lt;for(let s of t){let o=this.screens.get(s.id),a=s.rotation*pt,l=Math.cos(a),c=Math.sin(a),u=(y,M,S)=>[s.x+y*l-S*c,M,s.z+y*c+S*l];if(o.gangs){let y=vt(s.type);if(!y)continue;for(let M of o.gangs){let S=new W(...M.color.map(_=>Math.min(1,_*(.45+.55*M.level))));il(r,y,s,Gt(e.floor,s),S.getHex(),_=>_.gang===M.gang)}continue}if(o.print!==void 0){let y=Gt(e.floor,s)+s.h*.2,M=Math.min(s.w,s.d)*.16,S=y+s.h*.38*Math.min(1,Math.max(0,o.print)),_=new W(...o.color.map(C=>Math.min(1,C*(.35+.65*o.level)))),w=_.clone().multiplyScalar(.7),R=[u(-M,y,-M),u(M,y,-M),u(M,y,M),u(-M,y,M)],A=[u(-M,S,-M),u(M,S,-M),u(M,S,M),u(-M,S,M)];r.tri(A[0],A[2],A[1],_),r.tri(A[0],A[3],A[2],_);for(let C=0;C<4;C++){let O=(C+1)%4;r.tri(R[C],R[O],A[O],w),r.tri(R[C],A[O],A[C],w)}continue}if(o.fill!==void 0){let y=wp(s,e.floor);if(!y)continue;let M=y.rect,S=Math.min(1,Math.max(0,o.fill)),_=new W(...o.color.map(C=>Math.min(1,C*(.35+.65*o.level)))),w=new W(.08,.1,.13),R=M.z,A=(C,O,D,P,I)=>{r.tri(u(C,D,R),u(O,D,R),u(O,P,R),I),r.tri(u(C,D,R),u(O,P,R),u(C,P,R),I)};if(y.vertical){let C=M.y0+(M.y1-M.y0)*S;S>0&&A(M.x0,M.x1,M.y0,C,_),S<1&&A(M.x0,M.x1,C,M.y1,w)}else{let C=M.x0+(M.x1-M.x0)*S;S>0&&A(M.x0,C,M.y0,M.y1,_),S<1&&A(C,M.x1,M.y0,M.y1,w)}continue}if(o.leds){let y=vt(s.type);if(!y)continue;let M=new W(...o.color.map(S=>Math.min(1,S*(.35+.65*o.level))));il(r,y,s,Gt(e.floor,s),M.getHex(),S=>!!S.glow||!!S.screen);continue}if(o.heat){let y=vt(s.type);if(!y)continue;let M=new W(...o.color.map(S=>Math.min(1,S*(.35+.65*o.level))));il(r,y,s,Gt(e.floor,s),M.getHex(),()=>!0);continue}if(o.faces){let y=Math.max(.05,s.w)*(s.mirror?-1:1),M=Math.max(.05,s.d),S=Math.max(.005,s.h),_=Gt(e.floor,s);for(let w of o.faces){let R=w.part==="right"?.03:-Math.abs(y)/2+.03,A=w.part==="left"?-.03:Math.abs(y)/2-.03,C=_+(w.part==="bottom"?S*.45:S)+.006,O=new W(...w.color.map(B=>Math.min(1,B*(.35+.65*w.level)))),D=new W(0,0,0),P=(B,X,V=C)=>u(B*Math.sign(y),V,X),I=[P(R,-M/2+.03),P(A,-M/2+.03),P(A,M/2-.03),P(R,M/2-.03)];r.tri(I[0],I[2],I[1],O),r.tri(I[0],I[3],I[2],O);let N=.12+.1*w.level,F=O.clone().multiplyScalar(.5),H=[P(R-N,-M/2-N,C+.004),P(A+N,-M/2-N,C+.004),P(A+N,M/2+N,C+.004),P(R-N,M/2+N,C+.004)];for(let B=0;B<4;B++){let X=(B+1)%4;r.tri(I[B],H[X],H[B],F,D,D),r.tri(I[B],I[X],H[X],F,F,D)}}continue}let h=th(s,e.floor);if(!h)continue;let f=new W(...o.color.map(y=>Math.min(1,y*(.35+.65*o.level)))),d=new W(0,0,0),p=h.z+.004;r.tri(u(h.x0,h.y0,p),u(h.x1,h.y0,p),u(h.x1,h.y1,p),f),r.tri(u(h.x0,h.y0,p),u(h.x1,h.y1,p),u(h.x0,h.y1,p),f);let x=Math.min(1.5,o.halo??1);if(x<=0)continue;let g=(.18+.12*o.level)*Math.min(1,x),m=f.clone().multiplyScalar(.5*x),b=[u(h.x0,h.y0,p),u(h.x1,h.y0,p),u(h.x1,h.y1,p),u(h.x0,h.y1,p)],v=[u(h.x0-g,h.y0-g,p+.01),u(h.x1+g,h.y0-g,p+.01),u(h.x1+g,h.y1+g,p+.01),u(h.x0-g,h.y1+g,p+.01)];for(let y=0;y<4;y++){let M=(y+1)%4;r.tri(b[y],v[y],v[M],m,d,d),r.tri(b[y],v[M],b[M],m,d,m)}}e.screenMesh.geometry.dispose(),e.screenMesh.geometry=r.geometry(),e.screenMesh.visible=r.count>0}buildOpenings(e){let t=$p(e.geo.openings,e.openings,Math.min(e.floor.cut_height,e.floor.height),-.2-e.floor.elevation);e.frameTris=t.frameTris,e.glassTris=t.glassTris,e.blindTris=t.blindTris;for(let[n,r]of[[e.framesMesh,t.frames],[e.glassMesh,t.glass],[e.blindsMesh,t.blinds]])n.geometry.dispose(),n.geometry=r,n.visible=r.getAttribute("position").count>0}activeFloors(){return this.floors.filter(e=>e.to>.99)}applyHighlight(){for(let e of this.floors){let t=e.geo.floor.getAttribute("color");for(let n of e.geo.roomTris){let r=new W(n.color),s=this.roomTint?.get(n.roomId);s&&r.lerp(new W(...s).multiplyScalar(.6),.9),n.roomId===this.roomId&&r.lerp(AP,s?.3:.75);for(let o=n.start*3;oc.group),!0)[0];if(l){let c=l.object;for(;c&&!this.meshes.some(h=>h.group===c);)c=c.parent;let u=c?this.pickFurniture.get(this.meshes.find(h=>h.group===c).furnitureId):void 0;if(u)return{entity:u}}}let o=s.flatMap(l=>[l.lampMesh,l.coneMesh,l.framesMesh,l.glassMesh,l.blindsMesh,l.wallMesh,l.floorMesh].filter(c=>c.visible)),a=(l,c)=>l.find(u=>c>=u.start&&ch.group===l.object.parent);if(!(!n&&(l.object===u.lampMesh||l.object===u.coneMesh||l.object===u.framesMesh||l.object===u.blindsMesh||l.object===u.glassMesh))){if(l.object===u.lampMesh||l.object===u.coneMesh){let h=a(l.object===u.lampMesh?u.lampTris:u.wedgeTris,c);if(h)return{entity:h}}else if(l.object===u.framesMesh||l.object===u.blindsMesh||l.object===u.glassMesh){if(this.lowered&&l.face){let x=l.object.geometry.getAttribute("fold")?.getX(l.face.a)??Xe;if(x!==Xe&&Math.floor(x/16)%8===0)continue}let h=a(l.object===u.framesMesh?u.frameTris:l.object===u.glassMesh?u.glassTris:u.blindTris,c),f=h?this.pickOpenings.get(h):void 0,d=h?this.pickOpenings2.get(h):void 0,p=d?u.geo.openings.find(x=>x.opening.id===h):void 0;if(d&&p&&(l.point.x-p.start[0])*p.axis[0]+(l.point.z-p.start[1])*p.axis[1]>p.width/2&&(f=d),f)return{entity:f}}else if(l.object===u.wallMesh){let h=a(u.geo.furnitureTris,c),f=h&&n?this.pickFurniture.get(h):void 0;if(f)return{entity:f};if(l.face&&!h){let d=u.wallMesh.geometry.getAttribute("fold")?.getX(l.face.a)??32,p=Math.floor(d/16)%8,x=d%16,g=this.lowered&&p===0,m=(u.mask.glass.value&1<S.points.length>=3&&Ve(y,S.points))?.id??null;if(this.roomId!==null){if(M===this.roomId)return{floorId:u.floor.id,roomId:M}}else if(!m&&M)return{floorId:u.floor.id,roomId:M}}}}else if(l.object===u.floorMesh)return{floorId:u.floor.id,roomId:a(u.geo.roomTris.map(h=>({id:h.roomId,start:h.start,end:h.end})),c)??null}}}return null}onTap(e,t){let n=this.furnish?this.pick(e,t):this.pickInReach(e,t);if(n&&"entity"in n&&this.furnish){this.selectDevice(n.entity),this.options.onDeviceSelect?.(n.entity);return}if(n&&"entity"in n){this.flashes.set(n.entity,performance.now()+jm),this.invalidate(),this.options.onDeviceTap?.(n.entity,e,t);return}this.options.onRoomTap?.(n?.floorId??this.floorId??"",n?.roomId??null)}furnitureAt(e,t){let n=this.rayAt(e,t),r=this.activeFloors(),s=r.flatMap(o=>[o.lampMesh,o.wallMesh].filter(a=>a.visible));for(let o of n.intersectObjects(s,!1)){if(o.faceIndex==null)continue;let a=r.find(u=>u.group===o.object.parent),c=(o.object===a.lampMesh?a.lampFurnTris:a.geo.furnitureTris).find(u=>o.faceIndex>=u.start&&o.faceIndexh.id===n)?.furnitureId:void 0,a=o?null:this.furnitureAt(e,t),l=o??a?.id,c=l?this.floors.find(h=>h.floor.furniture.some(f=>f.id===l)):void 0,u=c?.floor.furniture.find(h=>h.id===l)?.type;return!!(c&&l&&u&&r.has(u))&&this.grabItem(c,l,e,t)}if(n){let o=this.devices.find(l=>l.id===n)?.furnitureId,a=o?this.floors.find(l=>l.floor.furniture.some(c=>c.id===o)):void 0;return!o||!a?this.grabDevice(n,e,t):this.grabItem(a,o,e,t)}let s=this.furnitureAt(e,t);if(!s){let o=this.pick(e,t);return o&&"entity"in o?this.grabDevice(o.entity,e,t):(this.selectedFurniture&&(this.selectFurniture(null),this.options.onFurnitureSelect?.(null)),this.selectedDevice&&(this.selectDevice(null),this.options.onDeviceSelect?.(null)),!1)}return this.grabItem(s.fv,s.id,e,t)}grabItem(e,t,n,r){let s=e.floor.furniture.find(a=>a.id===t),o=this.floorPoint(e,n,r);return!s||!o?!1:s.locked?(this.selectFurniture(s.id),this.options.onFurnitureSelect?.(s.id),!1):(this.grab={floorId:e.floor.id,id:s.id,offset:[s.x-o[0],s.z-o[1]],x:s.x,z:s.z,moved:!1},this.selectFurniture(s.id),this.options.onFurnitureSelect?.(s.id),!0)}grabDevice(e,t,n){let r=this.devices.find(a=>a.id===e),s=r&&this.floorMap.get(r.floorId),o=s&&this.floorPoint(s,t,n);return!r||!s||!o?!1:r.fixed?(this.selectDevice(e),this.options.onDeviceSelect?.(e),!1):(this.deviceGrab={id:e,floorId:s.floor.id,offset:[r.x-o[0],r.z-o[1]],x:r.x,z:r.z,moved:!1},this.selectDevice(e),this.options.onDeviceSelect?.(e),!0)}setSelectedDevice(e){e!==this.selectedDevice&&this.selectDevice(e)}selectDevice(e){e&&this.selectedFurniture&&(this.selectFurniture(null),this.options.onFurnitureSelect?.(null)),this.selectedDevice=e;for(let[t,n]of this.devicePins)n.el.classList.toggle("nf-dev-sel",t===e)}dragFurniture(e,t){if(this.surfaceDragging){this.surfaceGrab?.move(this.surfaceRay(e,t));return}let n=this.deviceGrab;if(n){let l=this.floorMap.get(n.floorId),c=this.devices.find(f=>f.id===n.id),u=l&&this.floorPoint(l,e,t);if(!l||!c||!u)return;let h=this.building?.settings.grid??.05;n.x=c.x=Math.round((u[0]+n.offset[0])/h)*h,n.z=c.z=Math.round((u[1]+n.offset[1])/h)*h,n.moved=!0,this.labelsDirty=!0,this.invalidate();return}let r=this.grab,s=r&&this.floorMap.get(r.floorId);if(!r||!s)return;let o=this.floorPoint(s,e,t);if(!o)return;let a=this.building?.settings.grid??.05;r.x=Math.round((o[0]+r.offset[0])/a)*a,r.z=Math.round((o[1]+r.offset[1])/a)*a,r.moved=!0,this.updateGhost(),this.invalidate()}dropFurniture(){if(this.surfaceDragging){this.surfaceDragging=!1,this.surfaceGrab?.end();return}let e=this.deviceGrab;this.deviceGrab=null,e?.moved&&this.options.onDeviceMove?.(e.id,Math.round(e.x*1e3)/1e3,Math.round(e.z*1e3)/1e3);let t=this.grab;this.grab=null,t?.moved&&this.options.onFurnitureMove?.(t.id,Math.round(t.x*1e3)/1e3,Math.round(t.z*1e3)/1e3),this.updateGhost()}updateGhost(){this.ghost&&(this.ghost.geometry.dispose(),this.ghost.material.dispose(),this.scene.remove(this.ghost),this.ghost=null);let e=this.selectedFurniture,t=e?this.floors.find(m=>m.floor.furniture.some(b=>b.id===e)):void 0,n=t?.floor.furniture.find(m=>m.id===e);if(!t||!n)return;let r=this.grab?.id===n.id?this.grab.x:n.x,s=this.grab?.id===n.id?this.grab.z:n.z,o=Ol(t.floor,{...n,x:r,z:s}),a=y0.has(n.type),l=Math.max(.1,n.type==="lamp_pendant"?.3:n.h),c=vt(n.type)||n.type==="lamp_wall"||n.type==="led_strip"?Gt(t.floor,n):a?n.type==="lamp_pendant"||n.type==="ceiling_fan"?o-n.h-.1:o-l:Gt(t.floor,n),u=n.rotation*pt,h=Math.cos(u),f=Math.sin(u),d=(m,b,v)=>[r+m*h-b*f,v,s+m*f+b*h],p=new Wt,x=[[-n.w/2,-n.d/2],[n.w/2,-n.d/2],[n.w/2,n.d/2],[-n.w/2,n.d/2]],g=new W(.25,.9,1);for(let m=0;m<4;m++){let[b,v]=x[m],[y,M]=x[(m+1)%4];p.seg(d(b,v,c+.01),d(y,M,c+.01),g),p.seg(d(b,v,c+l),d(y,M,c+l),g),p.seg(d(b,v,c+.01),d(b,v,c+l),g)}p.seg(d(-n.w/2,n.d/2+.03,c+.02),d(n.w/2,n.d/2+.03,c+.02),new W(1,1,1)),this.ghost=new gn(p.geometry(),new Lt({vertexColors:!0,depthTest:!1,transparent:!0})),this.ghost.position.y=t.floor.elevation+t.y,this.ghost.renderOrder=20,this.scene.add(this.ghost)}onHold(e,t){let n=this.pick(e,t);n&&"entity"in n&&this.options.onDeviceHold?.(n.entity,e,t)}swipeStart(e,t,n,r){if(this.furnish||Math.abs(r)m.floor.rooms.some(b=>b.points.length>=3));if(!n.length)return[];let r=this.lowQuality?1:Math.min(2,window.devicePixelRatio||1),s=Math.round(e*r),o=Math.round(t*r),a=new wn(s,o);a.texture.colorSpace=ft;let l=new zn(-1,1,1,-1,.1,400),c=this.floors.map(m=>({fv:m,visible:m.group.visible,y:m.y,o:m.o,standing:m.mask.standing.value,glass:m.mask.glass.value})),u=this.roof?.group.visible??!1,h=this.ghost?.visible??!1,f=this.renderer.getClearAlpha(),d=new Uint8Array(s*o*4),p=document.createElement("canvas");p.width=s,p.height=o;let x=p.getContext("2d"),g=[];try{this.roof&&(this.roof.group.visible=!1),this.ghost&&(this.ghost.visible=!1),this.renderer.setClearAlpha(0);for(let m of n){for(let D of this.floors)D.group.visible=D===m;m.y=0,m.o=1,this.applyFloor(m),m.group.visible=!0,m.mask.standing.value=0,m.mask.glass.value=0;let b=m.floor.rooms.flatMap(D=>D.points),v=m.floor.elevation,y=new Ct(new U(Math.min(...b.map(D=>D[0]))-.3,v,Math.min(...b.map(D=>D[1]))-.3),new U(Math.max(...b.map(D=>D[0]))+.3,v+Math.min(m.floor.cut_height,m.floor.height),Math.max(...b.map(D=>D[1]))+.3)),M=y.getCenter(new U),S=-.6,_=.8,w=new U(Math.sin(_)*Math.sin(S),Math.cos(_),Math.sin(_)*Math.cos(S));l.position.copy(M).addScaledVector(w,100),l.lookAt(M),l.updateMatrixWorld();let R=.5,A=.5;for(let D of[y.min.x,y.max.x])for(let P of[y.min.y,y.max.y])for(let I of[y.min.z,y.max.z]){let N=new U(D,P,I).applyMatrix4(l.matrixWorldInverse);R=Math.max(R,Math.abs(N.x)),A=Math.max(A,Math.abs(N.y))}let C=s/o;R/A>C?A=R/C:R=A*C,l.left=-R*1.05,l.right=R*1.05,l.top=A*1.05,l.bottom=-A*1.05,l.updateProjectionMatrix(),this.renderer.setRenderTarget(a),this.renderer.clear(),this.renderer.render(this.scene,l),this.renderer.readRenderTargetPixels(a,0,0,s,o,d);let O=x.createImageData(s,o);for(let D=0;D{Math.hypot(u[0]-r.motion.pos[0],u[1]-r.motion.pos[1])o.length?`${o.length}:${o[0].map(a=>a.toFixed(2))}/${o[o.length-1].map(a=>a.toFixed(2))}`:"").join("|"),r=this.robotTrails.get(e.id);if(r&&r.userData.key===n){this.showRobotTrail(e);return}let s=r;if(!s){let o=new Ke({color:3590399,transparent:!0,opacity:.34,depthWrite:!1,side:ut});s=new we(Im([],.16,0),o),s.renderOrder=3,s.name=`robot-trail:${e.id}`,this.robotTrails.set(e.id,s);let a=this.robots.get(e.id)?.group.parent;a&&a.add(s)}s.geometry.dispose(),s.geometry=Im(t,.16,(e.y??0)+.012),s.userData.key=n,this.showRobotTrail(e)}showRobotTrail(e){let t=this.robotTrails.get(e.id);if(!t)return;let n=this.trailTimers.get(e.id);n!==void 0&&(clearTimeout(n),this.trailTimers.delete(e.id));let r=Date.now(),s=EM(e.settledAt,r);if(t.material.opacity=.34*s,t.visible=(e.track?.length??0)>0&&s>.01,s<=0||s>=1&&e.settledAt==null)return;let o=s>=1?Math.max(0,(e.settledAt??r)+Uh-r):250;this.trailTimers.set(e.id,setTimeout(()=>{this.showRobotTrail(e),this.invalidate()},o))}makeRobot(e){if(!this.robotGeo){let s=new lt,o=(l,c,u,h,f)=>{let d=[];for(let p=0;p<20;p++)d.push([Math.cos(p/20*Math.PI*2)*l,Math.sin(p/20*Math.PI*2)*l]);Tt(s,d,c,u,h,f,{aoFrom:0,bottom:!1})};o(.17,.012,.08,2371657,3424863),o(.055,.08,.1,3820138,5070726),this.robotGeo=s.geometry(),this.robotMat=new Ke({vertexColors:!0});let a=new lt;Tt(a,[[-.05,.1],[.05,.1],[.05,.14],[-.05,.14]],.08,.085,16777215,16777215,{aoFrom:0,bottom:!1}),this.robotLedGeo=a.geometry()}let t=new ct,n=new Ke({color:HM[e.mode]}),r=e.mower?this.mowerMat??=new Ke({color:4164170}):this.robotMat;return t.add(new we(this.robotGeo,r),new we(this.robotLedGeo,n)),e.mower&&t.scale.set(1.7,1.6,1.7),{info:e,motion:{pos:[...e.rest],heading:e.restHeading,path:[],next:0},group:t,led:n}}buildPets(){let e=new Map(this.pets);this.pets.clear(),this.petMat??=new Ke({vertexColors:!0});for(let t of this.floors)for(let n of t.floor.furniture){let r=vt(n.type);if(!r?.pet)continue;let s=t.floor.rooms.find(f=>f.points.length>=3&&Ve([n.x,n.z],f.points)),o=e.get(n.id),a=new lt;Ms(new Li(a,new Wt,Ss({x:0,z:0,rotation:0,mirror:n.mirror})),r,Math.max(.05,n.w),Math.max(.05,n.d),Math.max(.05,n.h),0,null,null,n.variant??null),o?.group.removeFromParent();let l=new ct;l.add(new we(a.geometry(),this.petMat));let c=s?t.floor.furniture.filter(f=>f.id!==n.id&&!vt(f.type)?.pet&&f.type!=="rug"&&Gt(t.floor,f)<.5&&Ve([f.x,f.z],s.points)).map(f=>ts(f)):[],u={points:s?.points??[[n.x-.5,n.z-.5],[n.x+.5,n.z-.5],[n.x+.5,n.z+.5],[n.x-.5,n.z+.5]],obstacles:c,speed:n.type.endsWith(":pet_dog")?.7:.45},h=o&&s&&Ve(o.motion.pos,s.points)?o.motion:{pos:[n.x,n.z],heading:n.rotation*Math.PI/180,target:null,rest:1};this.pets.set(n.id,{motion:h,room:u,random:mb(n.id),group:l,floorId:t.floor.id})}for(let[t,n]of e)this.pets.has(t)||n.group.removeFromParent()}setPetRooms(e){for(let[t,n]of this.pets){let r=this.floorMap.get(n.floorId),s=e.get(t);if(!r||s===void 0)continue;let o=s?r.floor.rooms.find(l=>l.id===s&&l.points.length>=3):void 0;if(!o||n.room.points===o.points)continue;let a=r.floor.furniture.filter(l=>!vt(l.type)?.pet&&l.type!=="rug"&&Gt(r.floor,l)<.5&&Ve([l.x,l.z],o.points)).map(l=>ts(l));n.room={...n.room,points:o.points,obstacles:a},Ve(n.motion.pos,o.points)||(n.motion={...n.motion,pos:Bs(o.points),target:null,rest:.5})}this.invalidate()}stepRobots(e){if(!this.robots.size&&!this.pets.size)return!1;let t=this.robotLast?Math.min(.2,(e-this.robotLast)/1e3):0;this.robotLast=e;let n=!1,r=1/0,s=this.petLast?(e-this.petLast)/1e3:0;this.petLast=e;for(let o of this.pets.values()){let a=this.floorMap.get(o.floorId);if(!a)continue;o.group.parent!==a.group&&a.group.add(o.group),gb(o.motion,o.room,s,o.random)||!!o.motion.target?n=!0:r=Math.min(r,Math.max(0,o.motion.rest)),o.group.position.set(o.motion.pos[0],0,o.motion.pos[1]),o.group.rotation.y=o.motion.heading}clearTimeout(this.petTimer),!n&&Number.isFinite(r)&&(this.petTimer=setTimeout(()=>this.invalidate(),r*1e3+50));for(let o of this.robots.values()){let a=this.floorMap.get(o.info.floorId);if(!a)continue;o.group.parent!==a.group&&a.group.add(o.group);let l=this.robotTrails.get(o.info.id);l&&l.parent!==a.group&&a.group.add(l),t>0?n=AM(o.motion,o.info,t)||n:n||=o.info.mode==="cleaning"||o.info.mode==="returning",o.group.position.set(o.motion.pos[0],o.info.y??0,o.motion.pos[1]),o.group.rotation.y=o.motion.heading}return n||(this.robotLast=0),n}getView(){return{...this.controls.view,target:this.controls.view.target.clone()}}showView(e,t=900){let n=e.target??{x:0,y:0,z:0};this.controls.maxRadius=Math.max(this.controls.maxRadius,e.radius*1.5),this.controls.flyTo({target:new U(n.x,n.y,n.z),radius:e.radius,phi:e.phi,theta:e.theta},t)}flyTo(e,t=900){this.controls.flyTo(e,t)}focus(e,t,n,r,s){let o=this.floorMap.get(e);if(o){if(this.controls.flyTo({target:new U(t,o.floor.elevation+o.ty+r,n),radius:5.5,phi:.78},900),s){this.flashes.set(s,performance.now()+2400);let a=this.host.querySelector(`.nf-dev[data-entity="${CSS.escape(s)}"]`);a?.classList.add("nf-dev-found"),setTimeout(()=>a?.classList.remove("nf-dev-found"),2600)}this.invalidate()}}render(e){if(this.frame=0,this.disposed)return;let t=this.lastFrame?Math.min(100,e-this.lastFrame):16,n=!1;this.orbitSpeed&&!this.controls.active?(this.orbitLast&&(this.controls.view.theta+=this.orbitSpeed*Math.min(100,e-this.orbitLast)/1e3),this.orbitLast=e,n=!0):this.orbitLast=0;let r=this.controls.update(e),s=this.stepFloors(t),a=[this.stepOpenings(t),this.stepFridges(t),this.stepCovers(t)].some(Boolean),l=!1;if(this.flashes.size){let g=new Set;for(let[m,b]of this.flashes){let v=this.deviceFloor.get(m);v&&g.add(v),b<=e&&this.flashes.delete(m)}l=this.flashes.size>0;for(let m of this.floors)g.has(m.floor.id)&&this.buildLamps(m)}let c=this.placeRoof(t),u=this.stepRobots(e);this.pictureLayer.step();let f=[this.weatherLayer,this.energyLayer,this.soundLayer,this.screenLayer,this.waterLayer].map(g=>g.step(e)).some(Boolean),d=r||s||a||l||c,p=[];if(r&&p.push("camera"),s&&p.push("floors"),a&&p.push("openings"),l&&p.push("flash"),c&&p.push("roof"),this.effectTick&&p.push("effect"),u&&p.push("robot"),n&&p.push("orbit"),this.tintTick&&p.push("tint"),this.effectTick=this.tintTick=!1,this.lastFrame=d?e:0,d&&this.governor){let g=this.governor.frame(t,e);g&&"ratio"in g?(this.renderer.setPixelRatio(g.ratio),this.resize()):g&&setTimeout(()=>this.dropToLow(),0)}this.updateWalls(),this.renderer.render(this.scene,this.camera),this.placeLhAnchors(),(this.viewChanged()||s||this.labelsDirty)&&(this.labelsDirty=!1,this.updateLabels()),this.reportStats(e,p),d&&this.invalidate(),this.scheduleEffects(),!d&&n&&!this.orbitTimer&&(this.orbitTimer=setTimeout(()=>{this.orbitTimer=void 0,this.invalidate()},this.lowQuality?66:33));let x=this.resting;!d&&f&&!this.weatherTimer&&!x&&(this.weatherTimer=setTimeout(()=>{this.weatherTimer=void 0,this.invalidate()},33)),!d&&u&&!this.robotTimer&&!x&&(this.robotTimer=setTimeout(()=>{this.robotTimer=void 0,this.invalidate()},this.lowQuality?66:33))}updateWalls(){if(this.controls.walk){for(let o of this.floors)o.mask.standing.value=65535,o.mask.glass.value=0,o.mask.slope?.value.set(0,0,0,0);return}let e=this.camera.position,t=this.controls.view.target,n=e.x-t.x,r=e.z-t.z,s=Math.hypot(n,r)||1;for(let o of this.floors){let a=this.roomId!==null&&o.floor.rooms.some(h=>h.id===this.roomId),l=this.wallMode==="cut",c=0,u=0;o.geo.buckets.forEach((h,f)=>{let d=h?h[0]*n/s+h[1]*r/s>=.25:a;this.wallMode!=="auto"||!d||(this.painted?a&&(u|=1<.5&&r)){this.labelPlacer.place(n.label,null);continue}let s=n.floor.elevation+n.y+n.floor.cut_height*.5,o=[r.x0,r.x1].flatMap(l=>[r.z0,r.z1].map(c=>this.screenPoint([l,s,c],1/0)));n.label.hidden&&(n.label.hidden=!1),n.labelSize??={w:n.label.offsetWidth,h:n.label.offsetHeight};let a=kb(o,n.labelSize.w,{width:this.size.w,inset:this.labelInset});t.push({fv:n,rank:n.rank,left:a.left,y:a.y,height:n.labelSize.h})}for(let n of Bb(t))this.labelPlacer.place(n.fv.label,Ub(n.left,n.y));this.updateDevicePins();for(let n of this.floors){let r=n.to<.99||n.o<.9||e||this.roomId!==null||this.otherFloor(n),s=n.floor.elevation+n.y+.05;for(let a of n.roomPins){let l=r?null:this.screenPoint([a.cx,s,a.cz],1.1);this.labelPlacer.place(a.pin,l&&!l.off?hl(l):null)}let o=e||n.o<.9||this.otherFloor(n);for(let{pin:a,note:l}of n.notePins){let c=o?null:this.screenPoint([l.x,n.floor.elevation+n.y+(l.y??f0),l.z]);this.labelPlacer.place(a,c&&!c.off?hl(c):null)}}}otherFloor(e){return this.floorId!==null&&e.floor.id!==this.floorId}updateDevicePins(){let e=this.houseView;for(let t of this.persons){let n=this.personPins.get(t.id),r=this.floorMap.get(t.floorId);if(!n)continue;let s=r&&!e&&jd(r,this.otherFloor(r))?this.screenPoint([t.x,r.floor.elevation+r.y+.9,t.z]):null;this.labelPlacer.place(n,s&&!s.off?hl(s):null)}for(let t of this.devices){let n=this.devicePins.get(t.id)?.el;if(!n)continue;let r=this.floorMap.get(t.floorId),s=t.id.startsWith("detect:"),o=!!t.full&&t.roomId===null,a=!!r&&(o?zb(r):(!e||s)&&jd(r,this.otherFloor(r))),c=!!r&&a&&t.pin!==!1?this.screenPoint([t.x,r.floor.elevation+r.y+t.y,t.z]):null;if(!c||c.off){this.labelPlacer.place(n,null);continue}let u=this.roomId===null?t.full?"full":"":t.roomId===this.roomId?"full":"dim";this.pinMode.get(n)!==u&&(this.pinMode.set(n,u),n.classList.toggle("nf-dev-full",u==="full"),n.classList.toggle("nf-dev-dim",u==="dim")),this.labelPlacer.place(n,hl(c))}}reportStats(e,t){if(!this.statsOn||!this.options.onStats)return;let n=t.length>0;this.fpsStart||(this.fpsStart=e),this.lastStatsFrame&&n&&(this.worstFrame=Math.max(this.worstFrame,e-this.lastStatsFrame)),this.lastStatsFrame=n?e:0,this.fpsFrames++;let r=e-this.fpsStart;if(r>500||!n){let s=this.renderer.info.render;this.options.onStats({fps:n?Math.round(this.fpsFrames*1e3/r):0,busy:t,worstMs:Math.round(this.worstFrame),calls:s.calls,triangles:s.triangles,low:this.lowQuality,pixelRatio:this.renderer.getPixelRatio()}),this.fpsFrames=0,this.fpsStart=e,this.worstFrame=0}}};function EP(){let e=document.createElement("canvas");e.width=256*3,e.height=256*2;let t=e.getContext("2d"),n=(o,a,l,c,u)=>{t.strokeStyle=`rgba(55,224,255,${u})`,t.beginPath(),t.moveTo(o,a),t.lineTo(l,c),t.stroke()};t.lineWidth=1.5;let r=(o,a,l)=>{t.save(),t.beginPath(),t.rect(o*256,a*256,256,256),t.clip(),l(o*256,a*256),t.restore()};r(0,0,(o,a)=>{for(let l=0;l<5;l++){let c=a+l*256/5+.75;n(o,c,o+256,c,.09);let u=o+l*.37%1*256;n(u,c,u,c+256/5,.07)}}),r(1,0,(o,a)=>{for(let l=0;l<7;l++){let c=o+l*256/7+.75;n(c,a,c,a+256,.08);let u=a+l*.53%1*256;n(c,u,c+256/7,u,.06)}}),r(2,0,(o,a)=>{for(let l=0;l<4;l++){let c=l*256/4+.75;n(o+c,a,o+c,a+256,.1),n(o,a+c,o+256,a+c,.1)}}),r(1,1,(o,a)=>{for(let l=0;l<2;l++){let c=a+l*256/2+.75;n(o,c,o+256,c,.09);let u=l?256/4:0;for(let h of[u,u+256/2])n(o+h+.75,c,o+h+.75,c+256/2,.09)}}),r(2,1,(o,a)=>{n(o+.75,a,o+.75,a+256,.08),n(o,a+.75,o+256,a+.75,.08),t.fillStyle="rgba(55,224,255,0.05)";for(let l=0;l<90;l++)t.fillRect(o+l*97%256,a+(l*61+l*l%37)%256,2,2)});let s=new zt(e);return s.flipY=!1,s.wrapS=ln,s.wrapT=ln,s.anisotropy=4,s.colorSpace=ft,s}function RP(){let i=document.createElement("canvas");i.width=8,i.height=32;let e=i.getContext("2d");e.fillStyle="#1a2742",e.fillRect(0,0,8,32),e.fillStyle="#223556",e.fillRect(0,4,8,14),e.fillStyle="rgba(55,224,255,0.45)",e.fillRect(0,29,8,2);let t=new zt(i);return t.wrapS=kn,t.wrapT=kn,t.colorSpace=ft,t}function CP(i,e){let t=i.rooms.map((r,s)=>s),n=r=>t[r]===r?r:t[r]=n(t[r]);for(let[r,s]of e){let o=i.rooms.findIndex(u=>u.id===r),a=i.rooms.findIndex(u=>u.id===s);if(o<0||a<0)continue;let l=n(o),c=n(a);l!==c&&(t[Math.max(l,c)]=Math.min(l,c))}return t.map((r,s)=>n(s))}function PP(){let e=document.createElement("canvas");e.width=64,e.height=64;let t=e.getContext("2d"),n=t.createRadialGradient(64/2,64/2,0,64/2,64/2,64/2);n.addColorStop(0,"rgba(255,255,255,0.9)"),n.addColorStop(.2,"rgba(255,255,255,0.45)"),n.addColorStop(.55,"rgba(255,255,255,0.1)"),n.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=n,t.fillRect(0,0,64,64);let r=new zt(e);return r.colorSpace=ft,r}function IP(){let e=Qm,t=document.createElement("canvas");t.width=1024,t.height=1024;let n=t.getContext("2d");n.strokeStyle="rgba(91,124,255,0.16)",n.lineWidth=1;for(let o=0;o<=e;o++){let a=Math.round(o/e*1024)+.5;n.beginPath(),n.moveTo(a,0),n.lineTo(a,1024),n.moveTo(0,a),n.lineTo(1024,a),n.stroke()}n.globalCompositeOperation="destination-in";let r=n.createRadialGradient(1024/2,1024/2,1024*.12,1024/2,1024/2,1024/2);r.addColorStop(0,"rgba(0,0,0,1)"),r.addColorStop(1,"rgba(0,0,0,0)"),n.fillStyle=r,n.fillRect(0,0,1024,1024);let s=new zt(t);return s.anisotropy=4,s.colorSpace=ft,s}function w5(i,e){return new e0(i,e)}function Jm(i,e,t,n){let[r,s,o]=e.size??Es[e.lamp],a=e.base??0,l=(e.rotation??0)*pt,c=Math.cos(l),u=Math.sin(l),h=(x,g)=>[e.x+x*c-g*u,e.z+x*u+g*c],f=(x,g,m,b,v,y=14)=>{let M=[];for(let S=0;STt(i,[h(x,m),h(g,m),h(g,b),h(x,b)],v,y,M,S,{aoFrom:0,bottom:!0}),p=Math.max(.05,Math.min(r,s)/2);switch(e.lamp){case"ceiling":f(p*.25,t-.04,t,$e,$e,8),f(p,t-Math.max(.04,o)-.035,t-.04,n,n);break;case"pendant":{let x=Math.max(.4,t-o);f(.06,t-.02,t,$e,$e,8);let g=e.variant==="globe"?x+2*p:e.variant==="drum"?x+.24:x+.2;if(f(.008,g,t-.02,$e,$e,5),e.variant==="globe")for(let b=0;b<7;b++){let v=Math.PI*(b/7),y=Math.PI*((b+1)/7);f(p*Math.max(.2,Math.sin((v+y)/2)),x+p-p*Math.cos(v),x+p-p*Math.cos(y),n,n,14)}else if(e.variant==="cone")for(let b=0;b<4;b++)f(p*(.25+.75*(4-b)/4),x+.06*b,x+.06*(b+1),n,n,16);else e.variant==="drum"?f(p,x,x+.24,n,n,18):(f(p*.35,x+.14,x+.2,n,n,12),f(p,x,x+.14,n,n,16));break}case"fan":{let x=Math.max(.05,t-Math.max(.22,o)),g=x+.16;f(.07,t-.05,t,$e,$e,10),g[e.x+w*M-R*S,e.z+w*S+R*M];Tt(i,[_(.1,-.035),_(m,-.075),_(m,.075),_(.1,.035)],b,b+.012,WM,WM,{aoFrom:0,bottom:!0})}break}case"downlight":f(p,t-.012,t,$e,$e,12),f(p*.7,t-.02,t-.012,n,n,12);break;case"spot":f(p*.6,t-.02,t,$e,$e,10),f(p,t-Math.max(.06,o),t-.02,$e,$e,12),f(p*.8,t-Math.max(.06,o)-.008,t-Math.max(.06,o),n,n,12);break;case"panel":d(-r/2,r/2,-s/2,s/2,t-Math.max(.015,o),t,$e,$e),d(-r/2+.02,r/2-.02,-s/2+.02,s/2-.02,t-Math.max(.015,o)-.004,t-Math.max(.015,o),n);break;case"uplight":f(Math.max(.1,p*.6),a,a+.03,$e,$e),f(.014,a+.03,a+o-.12,$e,$e,6),f(p,a+o-.14,a+o-.02,$e,$e),f(p*.92,a+o-.02,a+o,n,n);break;case"bollard":f(p,a,a+o-.14,$e,$e,10),f(p*.9,a+o-.14,a+o-.03,n,n,10),f(p*1.1,a+o-.03,a+o,$e,$e,10);break;case"garden":f(.012,a,a+o-.08,$e,$e,5),f(p,a+o-.08,a+o-.01,$e,$e,10),f(p*.8,a+o-.01,a+o,n,n,10);break;case"floor":f(Math.max(.1,p*.7),a,a+.03,$e,$e),f(.014,a+.03,a+o-.28,$e,$e,6),f(p,a+o-.3,a+o,n,n);break;case"table":f(Math.max(.05,p*.55),a,a+.03,$e,$e),f(.012,a+.03,a+o-.16,$e,$e,6),f(p,a+o-.18,a+o,n,n);break;case"wall":{let x=e.base??Fl;d(-r/2+.03,r/2-.03,-s/2,-s/2+.02,x,x+o,$e),d(-r/2,r/2,-s/2+.02,s/2,x+o*.15,x+o*.85,n);break}case"strip":{let x=Math.max(.02,o),g=e.base!=null?e.base+x:t-.04,m=e.upright?0:(e.rise??0)*pt;if(!e.roll&&!e.upright&&!m){d(-r/2,r/2,-s/2,s/2,g-x,g,n);break}let b=(e.roll??0)*pt,v=Math.cos(b),y=Math.sin(b),[M,S]=[Math.cos(m),Math.sin(m)],_=e.upright?a+r/2:g-x/2+Io(e.base,r,e.rise),w=(D,P,I)=>{let N=D,F=P*v-I*y,H=P*y+I*v;return e.upright?[N,F]=[-F,N]:m&&([N,F]=[N*M-F*S,N*S+F*M]),[e.x+N*c-H*u,_+F,e.z+N*u+H*c]},R=[w(-r/2,-x/2,-s/2),w(r/2,-x/2,-s/2),w(r/2,-x/2,s/2),w(-r/2,-x/2,s/2),w(-r/2,x/2,-s/2),w(r/2,x/2,-s/2),w(r/2,x/2,s/2),w(-r/2,x/2,s/2)],A=new W(n),C=[e.x,_,e.z],O=(D,P,I,N)=>{let[F,H,B]=[R[D],R[P],R[I]],X=[(H[1]-F[1])*(B[2]-F[2])-(H[2]-F[2])*(B[1]-F[1]),(H[2]-F[2])*(B[0]-F[0])-(H[0]-F[0])*(B[2]-F[2]),(H[0]-F[0])*(B[1]-F[1])-(H[1]-F[1])*(B[0]-F[0])],V=[F[0]-C[0],F[1]-C[1],F[2]-C[2]],re=X[0]*V[0]+X[1]*V[1]+X[2]*V[2]<0,[be,Y,Q,se]=re?[R[N],R[I],R[P],R[D]]:[R[D],R[P],R[I],R[N]];i.tri(be,Y,Q,A,A,A),i.tri(be,Q,se,A,A,A)};O(0,1,2,3),O(4,5,6,7),O(0,1,5,4),O(1,2,6,5),O(2,3,7,6),O(3,0,4,7);break}}}export{Bi as ModelError,e0 as NextFloorViewer,w5 as createViewer,MP as furniturePreview,xP as inspectModel,xb as isLowEnd,bP as prepareModel,yP as previewModel,Jm as pushLampModel}; +/*! Bundled license information: + +three/build/three.core.js: +three/build/three.module.js: + (** + * @license + * Copyright 2010-2026 Three.js Authors + * SPDX-License-Identifier: MIT + *) +*/ diff --git a/custom_components/nextfloor/frontend/nextfloor-card-editor.js b/custom_components/nextfloor/frontend/nextfloor-card-editor.js new file mode 100644 index 0000000..c9c869b --- /dev/null +++ b/custom_components/nextfloor/frontend/nextfloor-card-editor.js @@ -0,0 +1,295 @@ +/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */ +var p={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",fr:"6312d0f61ebf",hu:"27ba348531dc",it:"1b705e76dd00",nb:"c5ea24fb9ef6",nl:"b64142c67c2e",pl:"8527a4930402",pt:"31857a2d2277",ro:"e3cb5f449f0f",sk:"320611594db0",sl:"8071691ceda3",sv:"711b911ec8da",tr:"7c83ce1c3372",zh:"50518d9f494e"};var M=globalThis,N=M.ShadowRoot&&(M.ShadyCSS===void 0||M.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,U=Symbol(),me=new WeakMap,R=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==U)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(N&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=me.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&me.set(t,e))}return e}toString(){return this.cssText}},pe=i=>new R(typeof i=="string"?i:i+"",void 0,U),V=(i,...e)=>{let t=i.length===1?i[0]:e.reduce((n,r,o)=>n+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+i[o+1],i[0]);return new R(t,i,U)},fe=(i,e)=>{if(N)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),r=M.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}},j=N?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return pe(t)})(i):i;var{is:Ke,defineProperty:Ge,getOwnPropertyDescriptor:Oe,getOwnPropertyNames:Ie,getOwnPropertySymbols:Ze,getPrototypeOf:Ue}=Object,C=globalThis,ge=C.trustedTypes,Ve=ge?ge.emptyScript:"",je=C.reactiveElementPolyfillSupport,F=(i,e)=>i,q={toAttribute(i,e){switch(e){case Boolean:i=i?Ve:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},we=(i,e)=>!Ke(i,e),be={attribute:!0,type:String,converter:q,reflect:!1,useDefault:!1,hasChanged:we};Symbol.metadata??=Symbol("metadata"),C.litPropertyMetadata??=new WeakMap;var b=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=be){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Ge(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:o}=Oe(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){let s=r?.call(this);o?.call(this,a),this.requestUpdate(e,s,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??be}static _$Ei(){if(this.hasOwnProperty(F("elementProperties")))return;let e=Ue(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(F("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(F("properties"))){let t=this.properties,n=[...Ie(t),...Ze(t)];for(let r of n)this.createProperty(r,t[r])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,r]of t)this.elementProperties.set(n,r)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let r=this._$Eu(t,n);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let r of n)t.unshift(j(r))}else e!==void 0&&t.push(j(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return fe(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&n.reflect===!0){let o=(n.converter?.toAttribute!==void 0?n.converter:q).toAttribute(t,n.type);this._$Em=e,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let o=n.getPropertyOptions(r),a=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:q;this._$Em=r;let s=a.fromAttribute(t,o.type);this[r]=s??this._$Ej?.get(r)??s,this._$Em=null}}requestUpdate(e,t,n,r=!1,o){if(e!==void 0){let a=this.constructor;if(r===!1&&(o=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??we)(o,t)||n.useDefault&&n.reflect&&o===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:o},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),o!==!0||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),r===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}let n=this.constructor.elementProperties;if(n.size>0)for(let[r,o]of n){let{wrapped:a}=o,s=this[r];a!==!0||this._$AL.has(r)||s===void 0||this.C(r,void 0,o,s)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(t)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}};b.elementStyles=[],b.shadowRootOptions={mode:"open"},b[F("elementProperties")]=new Map,b[F("finalized")]=new Map,je?.({ReactiveElement:b}),(C.reactiveElementVersions??=[]).push("2.1.2");var ne=globalThis,ke=i=>i,K=ne.trustedTypes,ve=K?K.createPolicy("lit-html",{createHTML:i=>i}):void 0,Ee="$lit$",v=`lit$${Math.random().toFixed(9).slice(2)}$`,Te="?"+v,qe=`<${Te}>`,D=document,H=()=>D.createComment(""),W=i=>i===null||typeof i!="object"&&typeof i!="function",re=Array.isArray,Je=i=>re(i)||typeof i?.[Symbol.iterator]=="function",J=`[ +\f\r]`,x=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ye=/-->/g,Se=/>/g,S=RegExp(`>|${J}(?:([^\\s"'>=/]+)(${J}*=${J}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),Ae=/'/g,De=/"/g,Re=/^(?:script|style|textarea|title)$/i,ie=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),l=ie(1),ct=ie(2),ut=ie(3),z=Symbol.for("lit-noChange"),d=Symbol.for("lit-nothing"),ze=new WeakMap,A=D.createTreeWalker(D,129);function Fe(i,e){if(!re(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return ve!==void 0?ve.createHTML(e):e}var Xe=(i,e)=>{let t=i.length-1,n=[],r,o=e===2?"":e===3?"":"",a=x;for(let s=0;s"?(a=r??x,_=-1):m[1]===void 0?_=-2:(_=a.lastIndex-m[2].length,u=m[1],a=m[3]===void 0?S:m[3]==='"'?De:Ae):a===De||a===Ae?a=S:a===ye||a===Se?a=x:(a=S,r=void 0);let k=a===S&&i[s+1].startsWith("/>")?" ":"";o+=a===x?h+qe:_>=0?(n.push(u),h.slice(0,_)+Ee+h.slice(_)+v+k):h+v+(_===-2?s:k)}return[Fe(i,o+(i[t]||"")+(e===2?"":e===3?"":"")),n]},B=class i{constructor({strings:e,_$litType$:t},n){let r;this.parts=[];let o=0,a=0,s=e.length-1,h=this.parts,[u,m]=Xe(e,t);if(this.el=i.createElement(u,n),A.currentNode=this.el.content,t===2||t===3){let _=this.el.content.firstChild;_.replaceWith(..._.childNodes)}for(;(r=A.nextNode())!==null&&h.length0){r.textContent=K?K.emptyScript:"";for(let k=0;k2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=d}_$AI(e,t=this,n,r){let o=this.strings,a=!1;if(o===void 0)e=E(this,e,t,0),a=!W(e)||e!==this._$AH&&e!==z,a&&(this._$AH=e);else{let s=e,h,u;for(e=o[0],h=0;h{let n=t?.renderBefore??e,r=n._$litPart$;if(r===void 0){let o=t?.renderBefore??null;n._$litPart$=r=new P(e.insertBefore(H(),o),o,void 0,t??{})}return r._$AI(i),r};var oe=globalThis,y=class extends b{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=xe(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return z}};y._$litElement$=!0,y.finalized=!0,oe.litElementHydrateSupport?.({LitElement:y});var Qe=oe.litElementPolyfillSupport;Qe?.({LitElement:y});(oe.litElementVersions??=[]).push("4.2.2");var et=(i,e,t={})=>i.callWS({type:`nextfloor/${e}`,...t}),He=i=>et(i,"building/get");var G=["light","cover","climate","media","switch","fan","lock","binary","sensor","tap","other"];var We=["body","wood","fabric","white","metal","dark"],Be={body:"#172238",wood:"#19233c",fabric:"#1a2644",white:"#1d2946",metal:"#2a3a60",dark:"#0b111f"};var $=["walls","floors","temperature","humidity","co2"];var ae={height:420,walls:"auto",solid_walls:!1,explode:!0,roof_fade:!0,quality:"auto",stats:!1,markers:"important",heatmap:"none",theme:"neon",energy:!0,room_panel:!0,room_buttons:!1,fill:!1,controls:!1,fullscreen_button:!1,room_names:!0,floor_stack:"dim",alerts:!0,alert_jump:!1,scenes:!0,announcements:!0,sensor_bar:!0,weather:!0,weather_density:1,idle_return:0,controls_hidden:!1,controls_hide_after:0,marker_names:!1,tap_in_room:!1,room_double_tap:"auto",central:!0,central_open:!1,keep_camera:!1,readable:!1,plain:!1,right_back:!1,today:!0,night:"off",idle_orbit:!1},tt=i=>i.target.value,O=i=>i.target.value,nt=i=>i.target.checked;function f(i,e,t,n,r){return l``}var c=(i,e,t,n)=>f(i,i.value[e],t,n,r=>i.set(e,r)),se=(i,e,t,n)=>f(i,i.value[e],t,n,r=>i.set(e,r||void 0));function w(i,e,t,n,r){return l``}function le(i,e,t,n){return l``}function I(i,e,t,n=""){return l``}function he(i,e,t,n){let r=n===void 0?"switch":n?"on":"off",o=[["switch","card_flows_switch"],["on","card_flows_on"],["off","card_flows_off"]];return l``}var Pe=V` + :host { + display: block; + color: var(--primary-text-color); + } + h3 { + margin: 18px 0 8px; + font-size: 14px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--secondary-text-color); + } + h3:first-child { + margin-top: 0; + } + .grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px 12px; + } + [hidden] { + display: none; + } + .wide { + grid-column: 1 / -1; + } + .field { + display: grid; + gap: 4px; + font-size: 13px; + color: var(--secondary-text-color); + } + select, + input[type="number"], + input[type="text"] { + box-sizing: border-box; + width: 100%; + min-height: 40px; + padding: 8px 10px; + border: 1px solid var(--divider-color, rgba(127, 127, 127, 0.4)); + border-radius: 8px; + background: var(--card-background-color, transparent); + color: var(--primary-text-color); + font: inherit; + font-size: 14px; + } + .toggle { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 8px 0; + font-size: 14px; + cursor: pointer; + } + .toggle input { + flex: none; + width: 18px; + height: 18px; + margin: 1px 0 0; + accent-color: var(--primary-color); + } + .sub { + display: flex; + flex-wrap: wrap; + gap: 6px 14px; + margin: -2px 0 6px 28px; + } + .chip { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; + cursor: pointer; + } + .chip input { + width: 16px; + height: 16px; + margin: 0; + accent-color: var(--primary-color); + } + .toggle small, + .hint { + display: block; + margin: 2px 0 0; + font-size: 12px; + color: var(--secondary-text-color); + } + @media (max-width: 450px) { + .grid { + grid-template-columns: 1fr; + } + } +`;var ce=globalThis,de=ce.__nextfloorBuiltin?.de??{},_e=ce.__nextfloorBuiltin?.en??{};ce.__nextfloorBuiltin??={de,en:_e};var $e=()=>typeof p=="object"&&p||{},rt=globalThis,Z=rt.__nextfloorTexts??=new Map;function Le(i){let e=i.toLowerCase().split("-")[0];return e!=="de"&&e!=="en"&&e in $e()?e:void 0}function it(i){let e=Le(i),t=e===void 0?void 0:Z.get(e);return t instanceof Promise?void 0:t}function Me(i,e){let t=Le(i?.language??navigator.language);if(t===void 0)return!1;let n=Z.get(t);return n===void 0&&(n=fetch(new URL(`./lang/${t}.json?v=${$e()[t]}`,import.meta.url)).then(r=>r.ok?r.json():{}).catch(()=>({})).then(r=>{Z.set(t,r&&typeof r=="object"?r:{})}),Z.set(t,n)),n instanceof Promise?(n.then(()=>e.requestUpdate()),!0):!1}function Ne(i,e,t={}){let n=i?.language??navigator.language,r=n.startsWith("de"),o=(r?void 0:it(n)?.[e])??(r?de:_e)[e]??_e[e]??de[e]??e;for(let[a,s]of Object.entries(t))o=o.replace(`{${a}}`,String(s));return o}var ue=class extends y{static properties={hass:{attribute:!1},_config:{state:!0},_floors:{state:!0},_rooms:{state:!0},_templates:{state:!0}};loading=!1;form;constructor(){super(),this._config={type:"custom:nextfloor-card"},this._floors=[],this._rooms=[],this._templates=[];let e=this;this.form={get value(){return{...ae,...e._config}},t:(t,n)=>Ne(e.hass,t,n),set:(t,n)=>e.write(t,n)}}setConfig(e){this._config=e}willUpdate(){this.hass&&!this.loading&&this._floors.length===0&&(this.loading=!0,He(this.hass).then(e=>{this._floors=e.building.floors.map(t=>({id:t.id,name:t.name})),this._templates=Object.keys(e.building.settings.card_templates??{}),this._rooms=e.building.floors.flatMap(t=>t.rooms.map(n=>({id:n.id,name:n.name,floor:t.name})))},()=>{}))}write(e,t){let n={...this._config};t===void 0||t===""||ae[e]===t?delete n[e]:n[e]=t,this.publish(n)}publish(e){this._config=e,this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:e},bubbles:!0,composed:!0}))}roomsChoice(){if(this._rooms.length===0)return l``;let e=new Set(this._config.rooms??[]),t=(n,r)=>{let o=this._rooms.map(a=>a.id).filter(a=>a===n?r:e.has(a));this.form.set("rooms",o.length?o:void 0)};return l`
+ ${this.form.t("card_rooms")} + ${this.form.t("card_rooms_hint")} + ${this._rooms.map(n=>l``)} +
`}floorThumbsToggle(){let e=!this._config.floor,t=this._config.floor?"card_floor_thumbs_hint_start":"card_floor_thumbs_hint";return f(this.form,this._config.floor_thumbs??e,"card_floor_thumbs",t,n=>{let r={...this._config};n===e?delete r.floor_thumbs:r.floor_thumbs=n,this.publish(r)})}controlsSection(){let e=this.form,t=this._config.controls,n=!!t&&(t===!0||t.length>0),r=t===!0?[...$]:Array.isArray(t)?t:[],o=s=>e.set("controls",s.length===$.length?!0:s.length>0?s:void 0),a=[0,10,30,60,120].map(s=>({value:s,text:s?e.t("card_hide_after_s",{n:s}):e.t("card_idle_off")}));return l`${f(e,n,"card_controls","card_controls_hint",s=>e.set("controls",s?!0:void 0))} + ${f(e,e.value.central,"card_central","card_central_hint",s=>e.set("central",s?void 0:!1))} + ${f(e,e.value.lock_button!==!1,"card_lock_button",void 0,s=>e.set("lock_button",s?void 0:!1))} + ${f(e,e.value.walk_button!==!1,"card_walk_button",void 0,s=>e.set("walk_button",s?void 0:!1))} + ${f(e,e.value.time_travel!==!1,"card_travel_button",void 0,s=>e.set("time_travel",s?void 0:!1))} + ${se(e,"marker_names","card_marker_names","card_marker_names_hint")} ${se(e,"controls_hidden","card_controls_hidden","card_controls_hidden_hint")} + ${le(e,"controls_hide_after","card_controls_hide_after",a)} + ${n?l`
+ ${$.map(s=>l``)} +
`:d}`}kioskSection(){let e=this.form,{night:t}=e.value,n=t==="off"||t==="sun"?t:"time",r=[0,1,2,5,10].map(a=>({value:a*60,text:a?e.t("card_idle_min",{n:a}):e.t("card_idle_off")})),o=[["off","card_night_off"],["sun","card_night_sun"],["time","card_night_time"]];return l`

${e.t("card_section_kiosk")}

+
+ ${le(e,"idle_return","card_idle_return",r)} + + ${n==="time"?l``:d} +
+

${e.t("card_idle_hint")}

+ ${c(e,"idle_orbit","card_idle_orbit","card_idle_orbit_hint")} +
${I(e,"dashboard","card_dashboard","/lovelace/home")} ${I(e,"dashboard_label","card_dashboard_label")}
+

${e.t("card_dashboard_hint")}

`}featuresSection(){let e=this.form,t=Object.keys(this.hass?.states??{}).filter(n=>n.startsWith("weather.")).sort();return l`

${e.t("card_section_features")}

+ ${c(e,"alerts","card_alerts","card_alerts_hint")} ${c(e,"alert_jump","card_alert_jump","card_alert_jump_hint")} + ${c(e,"scenes","card_scenes","card_scenes_hint")} + ${c(e,"sensor_bar","card_sensor_bar","card_sensor_bar_hint")} + ${c(e,"central_open","card_central_open","card_central_open_hint")} + ${c(e,"keep_camera","card_keep_camera","card_keep_camera_hint")} + ${c(e,"readable","card_readable","readable_hint")} + ${c(e,"plain","card_plain","plain_hint")} + ${c(e,"right_back","right_back","right_back_hint")} + ${this.roomsChoice()} + ${c(e,"today","card_today","card_today_hint")} + + ${c(e,"announcements","card_announcements","card_announcements_hint")} + ${e.value.announcements!==!1?l`
${I(e,"screen_name","screen_name")}
`:d} + ${c(e,"weather","card_weather","card_weather_hint")} + ${e.value.weather!==!1?l`
+ + +

${e.t("card_weather_density_hint")}

+
`:d} +

${e.t("card_pro_hint")}

`}furnitureColors(e){let t=this._config.furniture_colors??{},n=(r,o)=>{let a={...t,[r]:o};o||delete a[r],e.set("furniture_colors",Object.keys(a).length?a:void 0)};return l`
+ ${e.t("furn_colors_card")}${Object.keys(t).length?` (${Object.keys(t).length})`:""} + ${We.map(r=>l``)} +
`}viewSection(){let e=this.form,t=e.value;return l`

${e.t("card_section_view")}

+
+ ${this._templates.length?l``:d} + + + + ${w(e,"theme","theme",[["auto","theme_auto"],["neon","theme_neon"],["blueprint","theme_blueprint"],["day","theme_day"]],t.theme)} + ${w(e,"clock","clock",[["none","clock_none"],["top_left","clock_top_left"],["top_right","clock_top_right"],["bottom_left","clock_bottom_left"],["bottom_right","clock_bottom_right"]],t.clock??"none")} + + ${this.furnitureColors(e)} + ${w(e,"walls","card_walls",[["auto","walls_auto"],["cut","walls_cut"],["slope","walls_slope"]],t.walls)} + ${c(e,"solid_walls","card_solid_walls")} + + ${w(e,"quality","quality",[["auto","quality_auto"],["low","quality_low"],["high","quality_high"]],t.quality)} + ${w(e,"floor_stack","card_floor_stack",[["dim","floor_stack_dim"],["stacked","floor_stack_stacked"],["single","floor_stack_single"]],t.floor_stack)} +
+ ${t.fill?l`

${e.t("card_fill_hint")}

`:d} +

${e.t("card_quality_hint")}

`}markersOutside(){let e=this.form,t=e.value.markers_outside;return l`${f(e,!!t,"card_markers_outside","card_markers_outside_hint",n=>e.set("markers_outside",n?G.filter(r=>r!=="light"):void 0))} + ${t?l`
+ ${G.map(n=>l``)} +
`:d}`}showSection(){let e=this.form,t=e.value;return l`

${e.t("card_section_show")}

+
+ ${w(e,"markers","markers",[["none","markers_none"],["important","markers_important"],["all","markers_all"]],t.markers)} + ${w(e,"heatmap","heatmap",[["none","heat_off"],["temperature","heat_temperature"],["humidity","heat_humidity"],["co2","heat_co2"],["mould","heat_mould"],["values","heat_values"],["wifi","heat_wifi"]],t.heatmap)} + ${he(e,"flows","flows",t.flows)} ${he(e,"holograms","holos",t.holograms)} +
+ ${c(e,"tap_in_room","card_tap_in_room","card_tap_in_room_hint")} ${w(e,"room_double_tap","room_double_tap",[["auto","card_room_double_tap_auto"],["area","room_double_tap_area"],["plan","room_double_tap_plan"],["off","room_double_tap_off"]],t.room_double_tap)} ${this.markersOutside()} ${this.controlsSection()} ${this.floorThumbsToggle()} ${c(e,"room_names","card_room_names")} ${c(e,"energy","card_energy")} + ${c(e,"room_buttons","card_room_buttons","card_room_buttons_hint")} ${c(e,"room_panel","card_room_panel","card_room_panel_hint")} ${c(e,"fullscreen_button","card_fullscreen_button","card_fullscreen_button_hint")} + ${c(e,"explode","card_explode")} ${c(e,"roof_fade","card_roof_fade","card_roof_fade_hint")} ${c(e,"stats","card_stats","card_stats_hint")}`}render(){return this.hass&&Me(this.hass,this)?d:l`${this.viewSection()} ${this.showSection()} ${this.featuresSection()} ${this.kioskSection()}`}static styles=Pe};customElements.get("nextfloor-card-editor")||customElements.define("nextfloor-card-editor",ue);export{ue as NextFloorCardEditor}; +/*! Bundled license information: + +@lit/reactive-element/css-tag.js: + (** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +@lit/reactive-element/reactive-element.js: +lit-html/lit-html.js: +lit-element/lit-element.js: + (** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +lit-html/is-server.js: + (** + * @license + * Copyright 2022 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) +*/ diff --git a/custom_components/nextfloor/frontend/nextfloor-editor.js b/custom_components/nextfloor/frontend/nextfloor-editor.js new file mode 100644 index 0000000..e1c5ab5 --- /dev/null +++ b/custom_components/nextfloor/frontend/nextfloor-editor.js @@ -0,0 +1,4485 @@ +/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */ +var S={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",fr:"6312d0f61ebf",hu:"27ba348531dc",it:"1b705e76dd00",nb:"c5ea24fb9ef6",nl:"b64142c67c2e",pl:"8527a4930402",pt:"31857a2d2277",ro:"e3cb5f449f0f",sk:"320611594db0",sl:"8071691ceda3",sv:"711b911ec8da",tr:"7c83ce1c3372",zh:"50518d9f494e"};var mo=globalThis,go=mo.ShadowRoot&&(mo.ShadyCSS===void 0||mo.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ui=Symbol(),Fl=new WeakMap,or=class{constructor(e,n,r){if(this._$cssResult$=!0,r!==Ui)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=n}get styleSheet(){let e=this.o,n=this.t;if(go&&e===void 0){let r=n!==void 0&&n.length===1;r&&(e=Fl.get(n)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),r&&Fl.set(n,e))}return e}toString(){return this.cssText}},Tl=t=>new or(typeof t=="string"?t:t+"",void 0,Ui),le=(t,...e)=>{let n=t.length===1?t[0]:e.reduce((r,o,i)=>r+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+t[i+1],t[0]);return new or(n,t,Ui)},zl=(t,e)=>{if(go)t.adoptedStyleSheets=e.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(let n of e){let r=document.createElement("style"),o=mo.litNonce;o!==void 0&&r.setAttribute("nonce",o),r.textContent=n.cssText,t.appendChild(r)}},ji=go?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let n="";for(let r of e.cssRules)n+=r.cssText;return Tl(n)})(t):t;var{is:Dg,defineProperty:Og,getOwnPropertyDescriptor:Hg,getOwnPropertyNames:Lg,getOwnPropertySymbols:Cg,getPrototypeOf:Ng}=Object,_o=globalThis,Pl=_o.trustedTypes,Bg=Pl?Pl.emptyScript:"",Wg=_o.reactiveElementPolyfillSupport,ir=(t,e)=>t,Zi={toAttribute(t,e){switch(e){case Boolean:t=t?Bg:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,e){let n=t;switch(e){case Boolean:n=t!==null;break;case Number:n=t===null?null:Number(t);break;case Object:case Array:try{n=JSON.parse(t)}catch{n=null}}return n}},Dl=(t,e)=>!Dg(t,e),Il={attribute:!0,type:String,converter:Zi,reflect:!1,useDefault:!1,hasChanged:Dl};Symbol.metadata??=Symbol("metadata"),_o.litPropertyMetadata??=new WeakMap;var pt=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,n=Il){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(e,n),!n.noAccessor){let r=Symbol(),o=this.getPropertyDescriptor(e,r,n);o!==void 0&&Og(this.prototype,e,o)}}static getPropertyDescriptor(e,n,r){let{get:o,set:i}=Hg(this.prototype,e)??{get(){return this[n]},set(s){this[n]=s}};return{get:o,set(s){let l=o?.call(this);i?.call(this,s),this.requestUpdate(e,l,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Il}static _$Ei(){if(this.hasOwnProperty(ir("elementProperties")))return;let e=Ng(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(ir("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ir("properties"))){let n=this.properties,r=[...Lg(n),...Cg(n)];for(let o of r)this.createProperty(o,n[o])}let e=this[Symbol.metadata];if(e!==null){let n=litPropertyMetadata.get(e);if(n!==void 0)for(let[r,o]of n)this.elementProperties.set(r,o)}this._$Eh=new Map;for(let[n,r]of this.elementProperties){let o=this._$Eu(n,r);o!==void 0&&this._$Eh.set(o,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let n=[];if(Array.isArray(e)){let r=new Set(e.flat(1/0).reverse());for(let o of r)n.unshift(ji(o))}else e!==void 0&&n.push(ji(e));return n}static _$Eu(e,n){let r=n.attribute;return r===!1?void 0:typeof r=="string"?r:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,n=this.constructor.elementProperties;for(let r of n.keys())this.hasOwnProperty(r)&&(e.set(r,this[r]),delete this[r]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return zl(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,n,r){this._$AK(e,r)}_$ET(e,n){let r=this.constructor.elementProperties.get(e),o=this.constructor._$Eu(e,r);if(o!==void 0&&r.reflect===!0){let i=(r.converter?.toAttribute!==void 0?r.converter:Zi).toAttribute(n,r.type);this._$Em=e,i==null?this.removeAttribute(o):this.setAttribute(o,i),this._$Em=null}}_$AK(e,n){let r=this.constructor,o=r._$Eh.get(e);if(o!==void 0&&this._$Em!==o){let i=r.getPropertyOptions(o),s=typeof i.converter=="function"?{fromAttribute:i.converter}:i.converter?.fromAttribute!==void 0?i.converter:Zi;this._$Em=o;let l=s.fromAttribute(n,i.type);this[o]=l??this._$Ej?.get(o)??l,this._$Em=null}}requestUpdate(e,n,r,o=!1,i){if(e!==void 0){let s=this.constructor;if(o===!1&&(i=this[e]),r??=s.getPropertyOptions(e),!((r.hasChanged??Dl)(i,n)||r.useDefault&&r.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(s._$Eu(e,r))))return;this.C(e,n,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,n,{useDefault:r,reflect:o,wrapped:i},s){r&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,s??n??this[e]),i!==!0||s!==void 0)||(this._$AL.has(e)||(this.hasUpdated||r||(n=void 0),this._$AL.set(e,n)),o===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(n){Promise.reject(n)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[o,i]of this._$Ep)this[o]=i;this._$Ep=void 0}let r=this.constructor.elementProperties;if(r.size>0)for(let[o,i]of r){let{wrapped:s}=i,l=this[o];s!==!0||this._$AL.has(o)||l===void 0||this.C(o,void 0,i,l)}}let e=!1,n=this._$AL;try{e=this.shouldUpdate(n),e?(this.willUpdate(n),this._$EO?.forEach(r=>r.hostUpdate?.()),this.update(n)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(n)}willUpdate(e){}_$AE(e){this._$EO?.forEach(n=>n.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(n=>this._$ET(n,this[n])),this._$EM()}updated(e){}firstUpdated(e){}};pt.elementStyles=[],pt.shadowRootOptions={mode:"open"},pt[ir("elementProperties")]=new Map,pt[ir("finalized")]=new Map,Wg?.({ReactiveElement:pt}),(_o.reactiveElementVersions??=[]).push("2.1.2");var Yi=globalThis,Ol=t=>t,bo=Yi.trustedTypes,Hl=bo?bo.createPolicy("lit-html",{createHTML:t=>t}):void 0,Xi="$lit$",ft=`lit$${Math.random().toFixed(9).slice(2)}$`,Qi="?"+ft,Vg=`<${Qi}>`,Kt=document,ar=()=>Kt.createComment(""),lr=t=>t===null||typeof t!="object"&&typeof t!="function",Ji=Array.isArray,Vl=t=>Ji(t)||typeof t?.[Symbol.iterator]=="function",qi=`[ +\f\r]`,sr=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ll=/-->/g,Cl=/>/g,Wt=RegExp(`>|${qi}(?:([^\\s"'>=/]+)(${qi}*=${qi}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),Nl=/'/g,Bl=/"/g,Kl=/^(?:script|style|textarea|title)$/i,es=t=>(e,...n)=>({_$litType$:t,strings:e,values:n}),m=es(1),R=es(2),ak=es(3),mt=Symbol.for("lit-noChange"),_=Symbol.for("lit-nothing"),Wl=new WeakMap,Vt=Kt.createTreeWalker(Kt,129);function Gl(t,e){if(!Ji(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return Hl!==void 0?Hl.createHTML(e):e}var Ul=(t,e)=>{let n=t.length-1,r=[],o,i=e===2?"":e===3?"":"",s=sr;for(let l=0;l"?(s=o??sr,d=-1):u[1]===void 0?d=-2:(d=s.lastIndex-u[2].length,c=u[1],s=u[3]===void 0?Wt:u[3]==='"'?Bl:Nl):s===Bl||s===Nl?s=Wt:s===Ll||s===Cl?s=sr:(s=Wt,o=void 0);let h=s===Wt&&t[l+1].startsWith("/>")?" ":"";i+=s===sr?a+Vg:d>=0?(r.push(c),a.slice(0,d)+Xi+a.slice(d)+ft+h):a+ft+(d===-2?l:h)}return[Gl(t,i+(t[n]||"")+(e===2?"":e===3?"":"")),r]},cr=class t{constructor({strings:e,_$litType$:n},r){let o;this.parts=[];let i=0,s=0,l=e.length-1,a=this.parts,[c,u]=Ul(e,n);if(this.el=t.createElement(c,r),Vt.currentNode=this.el.content,n===2||n===3){let d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(o=Vt.nextNode())!==null&&a.length0){o.textContent=bo?bo.emptyScript:"";for(let h=0;h2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=_}_$AI(e,n=this,r,o){let i=this.strings,s=!1;if(i===void 0)e=Gt(this,e,n,0),s=!lr(e)||e!==this._$AH&&e!==mt,s&&(this._$AH=e);else{let l=e,a,c;for(e=i[0],a=0;a{let r=n?.renderBefore??e,o=r._$litPart$;if(o===void 0){let i=n?.renderBefore??null;r._$litPart$=o=new mn(e.insertBefore(ar(),i),i,void 0,n??{})}return o._$AI(t),o};var ts=globalThis,oe=class extends pt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let n=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Zl(n,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return mt}};oe._$litElement$=!0,oe.finalized=!0,ts.litElementHydrateSupport?.({LitElement:oe});var Gg=ts.litElementPolyfillSupport;Gg?.({LitElement:oe});(ts.litElementVersions??=[]).push("4.2.2");var Qe=(t,e,n={})=>t.callWS({type:`nextfloor/${e}`,...n});async function $o(t,e){return(await Qe(t,"image/get",{image_id:e})).data}async function St(t,e,n){await Qe(t,"image/set",{image_id:e,data:n})}async function ql(t){return(await Qe(t,"history/list")).snapshots}async function Yl(t,e){return(await Qe(t,"history/snapshot",e?{name:e}:{})).id}async function Xl(t,e){return(await Qe(t,"history/get",{snapshot_id:e})).building}async function Ql(t,e){await Qe(t,"history/delete",{snapshot_id:e})}async function Jl(t,e){return(await Qe(t,"history/restore",{snapshot_id:e})).revision}var ur=(t,e)=>Qe(t,"packs/import",{pack:e});async function ec(t,e){await Qe(t,"packs/remove",{pack_id:e})}var tc=t=>Qe(t,"backup/export"),nc=(t,e,n)=>Qe(t,"backup/import",{building:e,packs:n});var rs=t=>t.slice(0,t.indexOf(".")),Ug={light:"light",switch:"switch",input_boolean:"switch",valve:"switch",fan:"fan",cover:"cover",climate:"climate",media_player:"media",lock:"lock",sensor:"sensor",binary_sensor:"binary",event:"sensor",scene:"scene",script:"script"},X=t=>Ug[rs(t)]??null,os=["light","cover","climate","media","switch","fan","lock","binary","sensor","scene","script"];var rc=new Set(["light","switch","fan"]),Mt=t=>t!==null&&t!=="scene"&&t!=="script",Rt=t=>!t||t.state==="unavailable"||t.state==="unknown"&&!t.entity_id.startsWith("event.");function W(t,e,n){let r=String(t?.states[e]?.attributes.friendly_name??t?.entities?.[e]?.name??e);if(!n||r.length<=n.length+1||!r.toLowerCase().startsWith(`${n.toLowerCase()} `))return r;let o=r.slice(n.length+1);return o[0].toUpperCase()+o.slice(1)}var oc=t=>!!t&&t.entity_id.startsWith("sensor.")&&t.attributes.device_class==="enum";var ic=t=>Math.min(1,Math.max(0,t));function jg(t){let e=ic((t-2200)/4300),n=[1,.66,.26],r=[.78,.9,1];return[0,1,2].map(o=>n[o]+(r[o]-n[o])*e)}function ns(t,e){if(!t||t.state!=="on")return null;let n=e&&!["unavailable","unknown"].includes(e.state)?e.attributes:t.attributes,r=typeof n.brightness=="number"?.2+.8*Math.sqrt(ic(n.brightness/255)):1,o=n.rgb_color;return o&&!["color_temp","brightness","onoff"].includes(String(n.color_mode))?{color:[o[0]/255,o[1]/255,o[2]/255],level:r}:typeof n.color_temp_kelvin=="number"?{color:jg(n.color_temp_kelvin),level:r}:{color:[1,.71,.28],level:r}}function sc(t,e,n){let r=ns(t,n);if(r)return r;for(let o of e){let i=ns(o);if(i)return{color:i.color,level:i.level*.6}}return null}function So(t,e,n=null){if(t==="light"&&n==="floor")return 1.95;if(t==="light"&&n==="table")return 1.25;if(t==="light"&&n==="wall")return 1.95;switch(t){case"light":return Math.max(.5,e-.25);case"cover":return Math.min(2,e-.3);case"climate":return .6;case"media":return .9;case"binary":case"sensor":return 1.4;default:return 1.05}}var uc=[],Mo=new Map,Zg=0,de=(t,e)=>`pack:${t}:${e}`,gt=t=>t.startsWith("pack:");function is(t){uc=t,Mo=new Map;for(let e of t)for(let n of e.items)Mo.set(de(e.id,n.id),n);Zg+=1}var hr=()=>uc;var qg={};function G(t){if(!gt(t))return;let e=Mo.get(t);if(e)return e;let[,n,...r]=t.split(":"),o=qg[n];return o?Mo.get(de(o,r.join(":"))):void 0}var Yg=.22;function ac(t,e,n,r){let o=Math.min(Yg,n/3);if(r<=o*2.4||Math.abs(r-n)<1e-6)return e*(r/n)+(t-e)*(r/n);let i=e*(r/n),s=t-e;return s<=o?i+s:s>=n-o?i+r-(n-s):i+o+(s-o)*(r-2*o)/(n-2*o)}function dr(t,e,n,r,o){return[ac(t*r,n*r,r,o)/o,ac(e*r,n*r,r,o)/o]}var lc=new WeakMap;function dc(t,e,n,r){let[o,i,s]=t.size;if(t.vehicle||t.stretch||Math.abs(e-o)<1e-4&&Math.abs(n-i)<1e-4&&Math.abs(r-s)<1e-4)return t.parts;let l=`${e.toFixed(4)}|${n.toFixed(4)}|${r.toFixed(4)}`,a=lc.get(t),c=a?.get(l);if(c)return c;let u=t.parts.map(d=>{if(d.shape==="sweep")return d;let[p,h]=dr(d.x-d.w/2,d.x+d.w/2,-.5,o,e),[f,g]=dr(d.z-d.d/2,d.z+d.d/2,-.5,i,n),[y,b]=dr(d.y,d.y+d.h,0,s,r);if(d.rot)return{...d,x:(p+h)/2,z:(f+g)/2,w:d.w*o/e,d:d.d*i/n,y,h:b-y};let v={...d,x:(p+h)/2,z:(f+g)/2,w:h-p,d:g-f,y,h:b-y};if(d.shape==="loft"){let[w,x,k,$]=[d.tx??d.x,d.tz??d.z,d.tw??d.w,d.td??d.d],[A,F]=dr(w-k/2,w+k/2,-.5,o,e),[T,I]=dr(x-$/2,x+$/2,-.5,i,n);Object.assign(v,{tx:(A+F)/2,tz:(T+I)/2,tw:F-A,td:I-T})}return v});return a||lc.set(t,a=new Map),a.size>32&&a.clear(),a.set(l,u),u}var ss=t=>!!t?.parts.some(e=>e.move);var hc=t=>G(t)?.parts.find(e=>e.screen),cc=.06;function pc(t){let e=G(t);if(!e)return!1;let[n,r,o]=e.size;return e.parts.filter(i=>i.screen).some(i=>{let[s,l]=[i.w*n,i.d*r,i.h*o].sort((a,c)=>c-a);return l>=cc&&s>=cc})}function st(t){return Je[t]??G(t)?.size??[.6,.6,.8]}function Et(t){let e=G(t);return vc.has(t)||!!e?.electric||!!e?.light||!!e?.climate}var fc=t=>!!G(t)?.parts.some(e=>e.picture),gn=t=>!!G(t)?.climate;function mc(t,e){return t.name[e.split("-")[0]]??t.name.en??Object.values(t.name)[0]??t.id}var Xg={wohnen:"Living & Pets",kino:"Home Cinema & Gaming",kueche:"Kitchen Extras",bad:"Bathroom Extras",schlafen:"Bedroom & Kids",technik:"Office & Homelab",energie:"Energy & Building Services",garten:"Garden & Terrace (older)",fitness:"Fitness (older)",fahrzeuge:"Vehicles",ikea:"IKEA sizes",treppen:"Stairs & railings",ausbau:"Architecture & fit-out",werkstatt:"Garage & workshop",a_wohnzimmer:"Living room",a_schlafzimmer:"Bedroom",a_kueche:"Kitchen",a_bad:"Bathroom",a_kinderzimmer:"Kids' room",a_buero:"Office & gaming",a_fitness:"Fitness",a_haustiere:"Pets",a_garten:"Garden & patio",a_kino:"Home cinema & hi-fi",a_smart:"Smart home & tech",a_haustechnik:"Utility & building services",a_saison:"Season & decoration",a_smart2:"Smart home 2",a_haustechnik2:"Building services 2",a_wellness:"Wellness",a_garten2:"Garden 2",a_kueche2:"Kitchen 2",a_fahrzeuge2:"Vehicles 2",a_aussenkueche:"Outdoor kitchen & terrace",a_werkstatt2:"Workshop 2",a_japandi:"Japandi & Scandi",a_loft:"Loft & industrial",a_gruen:"Indoor greenery",a_musik:"Music & studio",a_bilder:"Pictures & frames"};function gc(t,e){if(e.split("-")[0]==="de")return t.name;let n=/^nextfloor\.(.+)$/.exec(t.id)?.[1];return n&&Xg[n]||t.name}function At(t,e){return e.mount_y!=null?e.mount_y:Jg(t,e)+(Qg(e)?0:yc(t,e.x,e.z))}var Qg=t=>t.type==="led_strip"||G(t.type)?.mount==="ceiling";function Jg(t,e){if(e.type==="lamp_wall")return _c;if(e.type==="led_strip")return Math.max(0,at(t,e.x,e.z)-.04-Math.max(.02,e.h));let n=G(e.type);if(!n)return bc(e);switch(n.mount){case"surface":return wc(t,e.x,e.z);case"wall":return n.wall_y??1;case"ceiling":return Math.max(0,Ro(t,e)-e.h);default:return 0}}function as(t){if(t==="plant")return"plant";let e=G(t);return e?e.household?e.household:/monstera|plant|herb_garden|flower_pots|bonsai|ficus|cactus|kaktus/.test(e.id)?"plant":null:null}var kc=["turn","slide","top"],xc=["always","active","no_power","never"],$c=1.3,Eo=(t,e=new Date().toISOString().slice(0,10))=>!!t.due&&t.due<=e,Sc=["gable","hip","halfhip","pyramid","mansard","pent","flat","parapet"],Mc=["brick","round","wide","steel"],Ao=["navigate","more_info","service","fire_dom_event"];function Fo(t,e,n){return t?e?!!n.lock_plan:!!t.locked:!1}var Rc=["rain","snow","fog","clouds","lightning","sky"],Ec=["rain","snow","clouds","lightning","sky"],Ac=["lawn","terrace","path","driveway","pool","bed","wild","hedge","fence","pergola"],ls={lawn:.012,terrace:.12,path:.02,driveway:.02,pool:-.25,bed:.15,wild:.03,hedge:1.2,fence:1,pergola:2.2};function cs(t){return t==="hedge"||t==="fence"||t==="pergola"}var Fc=["x","-x","z","-z"];function e_(t,e,n){let r=t.slope??0;if(!r||t.type==="pool")return 0;let o=t.slope_dir??"x",i=(c,u)=>o==="x"?c:o==="-x"?-c:o==="z"?u:-u,s=1/0,l=-1/0;for(let[c,u]of t.points){let d=i(c,u);s=Math.min(s,d),l=Math.max(l,d)}if(l-s<1e-6)return 0;let a=Math.min(1,Math.max(0,(i(e,n)-s)/(l-s)));return r*a}function t_(t,e,n,r){return Tc(t)+(e.offset??0)+ls[e.type]-e_(e,n,r)}function Tc(t){return t.elevation>.3?0:-.2}function zc(t,e,n){let r=(t.outdoor??[]).filter(i=>!cs(i.type)&&i.type!=="pool"&&N([e,n],i.points)),o=[...r].reverse().find(i=>i.cut)??r[0];return o?t_(t,o,e,n):Tc(t)}var Pc=t=>t.cut??t.type==="pool",Ic=30,Dc={meter:null,grid:null,grid_invert:!1,solar:null,battery:null,battery_invert:!1,battery_soc:null,consumption:null,tariff:null},Oc=["wood","oak","tiles","carpet","stone","concrete"],Hc={type:"none",pitch:35,overhang:.4},To="#d6cfc2",zo="#e8e3da",Lc={wall_exterior:.24,wall_interior:.12,grid:.05,north:0,roof:{...Hc}};function Ft(){return{version:1,floors:[],settings:{...Lc},energy:{...Dc},presence:[]}}function He(t,e,n){return{id:t,name:e,elevation:n,height:2.5,cut_height:1.15,rooms:[],openings:[],furniture:[],placements:[],background:null,outdoor:[],walls:[],ha_floor:null}}var n_=2.75;function Cc(t,e){if(e!=null&&Number.isFinite(e))return Math.round(e*n_*100)/100;let n=t.reduce((r,o)=>!r||o.elevation>r.elevation?o:r,null);return n?Math.round((n.elevation+n.height+.25)*100)/100:0}function Nc(t,e,n){let r=t.rooms.flatMap(l=>l.points.map(a=>a[0])),o=t.rooms.flatMap(l=>l.points.map(a=>a[1])),i=r.length?Math.ceil(Math.max(...r))+1:0,s=o.length?Math.floor(Math.min(...o)):0;return e.map((l,a)=>{let c=i+a%3*4.5,u=s+Math.floor(a/3)*3.5;return{id:n(),name:l.name,area_id:l.area_id,points:[[c,u],[c+4,u],[c+4,u+3],[c,u+3]],floor_material:"wood"}})}function Bc(t,e,n,r){let o=t.rotation*Math.PI/180,i=Math.cos(o),s=Math.sin(o),[l,a]=e,c=t.x-l*(t.w/2)*i+a*(t.d/2)*s,u=t.z-l*(t.w/2)*s-a*(t.d/2)*i,d=n[0]-c,p=n[1]-u,h=b=>Math.max(.1,Math.round(b/r)*r),f=h((d*i+p*s)*l),g=h((-d*s+p*i)*a),y=b=>Math.round(b*1e3)/1e3;return{x:y(c+l*(f/2)*i-a*(g/2)*s),z:y(u+l*(f/2)*s+a*(g/2)*i),w:y(f),d:y(g)}}var Po=["lamp_ceiling","lamp_downlight","lamp_spot","lamp_panel","lamp_pendant","ceiling_fan","lamp_floor","lamp_table","lamp_wall","led_strip","lamp_uplight","lamp_bollard","lamp_garden","radiator","sofa","armchair","stool","coffee_table","tv_board","tv_wall","sideboard","shelf","plant","rug","table","table_round","chair","bench","corner_bench","bar_stool","kitchen","kitchen_wall","kitchen_tall","island","worktop","sink","stove","dishwasher","fridge","bed","bunk_bed","nightstand","wardrobe","dresser","bathtub","shower","wc","washbasin","washer","dryer","desk","office_chair","tall_cabinet","coat_rack","stairs","robot_vacuum","inverter","home_battery","wallbox","meter","grid_point","parking","fridge_smart","stairwell"],Wc={lights:["lamp_ceiling","lamp_downlight","lamp_spot","lamp_panel","lamp_pendant","ceiling_fan","lamp_floor","lamp_uplight","lamp_table","lamp_wall","led_strip","lamp_bollard","lamp_garden"],living:["sofa","armchair","stool","coffee_table","tv_board","tv_wall","sideboard","shelf","plant","rug"],dining:["table","table_round","chair","bench","corner_bench","bar_stool"],kitchen:["kitchen","kitchen_wall","kitchen_tall","island","worktop","sink","stove","dishwasher","fridge"],sleeping:["bed","bunk_bed","nightstand","wardrobe","dresser"],bath:["bathtub","shower","wc","washbasin","washer","dryer"],work:["desk","worktop","office_chair","tall_cabinet","coat_rack","radiator","stairs","robot_vacuum"],vehicles:["parking"]},Le=["meter","inverter","home_battery","wallbox","grid_point"],Vc=new Set(["lamp_ceiling","lamp_downlight","lamp_spot","lamp_panel","lamp_pendant","ceiling_fan","lamp_floor","lamp_uplight","lamp_table","lamp_wall","led_strip","lamp_bollard","lamp_garden"]),_c=1.75;function Io(t){return us.has(t.type)||["stairwell","parking"].includes(t.type)?!1:G(t.type)?.mount!=="ceiling"}function ce(t){return Vc.has(t)||!!G(t)?.light}var r_=new Set(["table","table_round","coffee_table","desk","nightstand","sideboard","dresser","kitchen","island","worktop","tv_board","dishwasher","washer","dryer"]);function Kc(t,e,n,r=0){let o=ue(t.points),i=o.x1-o.x0-2*r,s=o.z1-o.z0-2*r,l=[];for(let a=0;aMath.round(s*1e3)/1e3,[o,i]={right:[1,0],down:[0,1],left:[-1,0],up:[0,-1]}[n];return[r(t[0]+o*e),r(t[1]+i*e)]}function bc(t){switch(t.type){case"home_battery":return t.variant==="wall"?.5:0;case"kitchen_wall":return 1.45;case"tv_wall":return Math.max(0,1.3-t.h/2);case"radiator":return .12;case"inverter":return 1.1;case"wallbox":return 1;case"meter":return .4;default:return 0}}var us=new Set(["lamp_ceiling","lamp_downlight","lamp_spot","lamp_panel","lamp_pendant","ceiling_fan"]);function Gc(t,e){return t.filter(n=>n.elevationn.rooms.filter(r=>r.points.length>=3&&r.ceiling!=null&&r.ceiling>n.height+.005&&n.elevation+r.ceiling>e.elevation+.05)).map(n=>n.points)}var ds=t=>t?.floor_offset&&Number.isFinite(t.floor_offset)?t.floor_offset:0;function yc(t,e,n){let r=t.rooms.find(o=>o.points.length>=3&&o.floor_offset&&N([e,n],o.points));return ds(r)}function at(t,e,n){let r=t.rooms.find(o=>o.points.length>=3&&N([e,n],o.points));return r?.ceiling!=null&&r.ceiling>0?r.ceiling:t.height}var Ro=(t,e)=>e.ceiling_y!=null&&e.ceiling_y>0?e.ceiling_y:at(t,e.x,e.z);function wc(t,e,n){let r=0;for(let o of t.furniture)!(r_.has(o.type)||G(o.type)?.surface)||!N([e,n],ms(o))||(r=Math.max(r,o.h));return r}var vc=new Set([...Vc,"radiator","robot_vacuum","inverter","home_battery","wallbox","meter","tv_board","tv_wall","desk","fridge","fridge_smart","stove","kitchen_tall","dishwasher","washer","dryer","kitchen","island","sink"]),Je={sofa:[2.2,.9,.82],armchair:[.85,.85,.8],table:[1.6,.9,.75],chair:[.46,.5,.9],bed:[1.6,2.05,.9],nightstand:[.45,.4,.5],wardrobe:[1.8,.6,2.1],shelf:[.9,.35,1.9],kitchen:[2.4,.62,.92],worktop:[1.2,.62,.91],inverter:[.5,.2,.65],home_battery:[.6,.25,1.1],wallbox:[.3,.15,.42],meter:[.55,.21,1.1],grid_point:[.4,.22,.6],fridge:[.6,.65,1.8],fridge_smart:[.91,.73,1.78],stairwell:[1,2.6,.02],stove:[.6,.62,.92],sink:[.9,.62,.92],bathtub:[1.7,.75,.58],shower:[.9,.9,2],wc:[.38,.6,.8],washbasin:[.6,.46,.85],desk:[1.4,.7,.75],tv_board:[1.8,.42,.5],plant:[.45,.45,1.1],rug:[2,1.4,.01],stairs:[1,3.2,2.75],stool:[.55,.55,.42],lamp_ceiling:[.4,.4,.08],lamp_downlight:[.1,.1,.02],lamp_spot:[.1,.1,.14],lamp_panel:[.6,.6,.03],lamp_uplight:[.35,.35,1.8],lamp_bollard:[.16,.16,.8],lamp_garden:[.12,.12,.3],radiator:[1,.1,.6],robot_vacuum:[.36,.5,.1],parking:[2.6,5.2,.02],lamp_pendant:[.4,.4,.8],ceiling_fan:[1.32,1.32,.32],lamp_floor:[.4,.4,1.7],lamp_table:[.28,.28,.45],lamp_wall:[.22,.12,.2],led_strip:[2,.04,.03],coffee_table:[1.1,.6,.42],tv_wall:[1.3,.08,.75],sideboard:[1.6,.45,.8],table_round:[1.1,1.1,.75],bench:[1.4,.45,.85],corner_bench:[2,1.6,.9],bar_stool:[.42,.42,.75],kitchen_wall:[.8,.35,.7],kitchen_tall:[.6,.62,2.1],island:[1.8,.9,.92],dishwasher:[.6,.62,.92],bunk_bed:[1,2.05,1.65],dresser:[1,.5,.9],washer:[.6,.6,.85],dryer:[.6,.6,.85],office_chair:[.65,.65,1.1],tall_cabinet:[.6,.6,2.1],coat_rack:[1,.35,1.9]};var hs=["interior","front","front_glass","sidelight","sidelights","glass","sliding","passage"],ps=["standard","bars","glass_wall"],Do=new Set(["interior","front"]);function jt(t,e){return t.type==="door"?t.style&&hs.includes(t.style)?t.style:e?"front":"interior":t.style&&ps.includes(t.style)?t.style:"standard"}function Uc(t,e,n,r){if(e!=="sidelight"&&e!=="sidelights")return null;let o=e==="sidelights",i=t-.04,s=Math.min(1.05,Math.max(.6,i-(o?.6:.3))),l=(i-s)/(o?2:1),a=r.sidelight_width??l,c=o?r.sidelight_width2??r.sidelight_width??l:0;a=Math.max(.1,a),c=o?Math.max(.1,c):0;let u=i-.5;if(a+c>u){let p=Math.max(0,u)/(a+c);a*=p,c*=p}return o?{panels:[[.02,.02+a],[t-.02-c,t-.02]],x0:.02+a,x1:t-.02-c}:(n?!!r.sidelight_hinge:!r.sidelight_hinge)?{panels:[[.02,.02+a]],x0:.02+a,x1:t-.02}:{panels:[[t-.02-a,t-.02]],x0:.02,x1:t-.02-a}}function fs(t){return t==="front"||t==="front_glass"||t==="sidelight"||t==="sidelights"}var bn={door:{type:"door",leaves:1,width:.9,sill:0,height:2.05,style:"interior"},front:{type:"door",leaves:1,width:1,sill:0,height:2.1,style:"front"},door_double:{type:"door",leaves:2,width:1.6,sill:0,height:2.05},window:{type:"window",leaves:1,width:1.2,sill:.9,height:1.3},window_double:{type:"window",leaves:2,width:1.6,sill:.9,height:1.3},terrace:{type:"window",leaves:1,width:1,sill:0,height:2.1},terrace_double:{type:"window",leaves:2,width:1.8,sill:0,height:2.1},lift_slide:{type:"window",leaves:1,width:2.4,sill:0,height:2.15,opens:"slide"},garage:{type:"garage",leaves:1,width:2.5,sill:0,height:2.1},glass_wall:{type:"window",leaves:1,width:2,sill:0,height:2.4,style:"glass_wall"}};function yn(t){if(t.type==="garage")return"garage";if(t.type==="window"&&t.style==="glass_wall")return"glass_wall";if(t.type==="window"&&t.opens==="slide"&&t.sill<.1)return"lift_slide";let e=t.leaves===2;return t.type==="door"?!e&&t.style&&fs(t.style)?"front":e?"door_double":"door":t.sill<.1?e?"terrace_double":"terrace":e?"window_double":"window"}function Te(t){t.energy={...Dc,...t.energy??{}},t.presence=t.presence??[],t.version=1,t.settings={...Lc,...t.settings,roof:{...Hc,...t.settings?.roof??{}}},t.floors.forEach((e,n)=>{let r=He(e.id,e.name??`Floor ${n+1}`,e.elevation??n*2.8);for(let o of Object.keys(r))e[o]===void 0&&(e[o]=r[o])});for(let e of t.floors){e.outdoor=e.outdoor??[],e.walls=e.walls??[],e.rooms=e.rooms.map(r=>({...r,name:r.name??"",area_id:r.area_id??null,floor_material:r.floor_material??"wood",panel:r.panel??[]})),e.ha_floor=e.ha_floor??null,e.placements=e.placements.map(r=>({...r,mount:r.mount??null,rotation:r.rotation??0})),e.furniture=e.furniture.map(r=>({...r,entity:r.entity??null,power:r.power??null}));let n=e.placements.filter(r=>r.entity_id.startsWith("light."));if(n.length){let r={ceiling:"lamp_ceiling",floor:"lamp_floor",table:"lamp_table",wall:"lamp_wall"};for(let o of n){let i=r[o.mount??"ceiling"],[s,l,a]=Je[i],c=`lamp_${o.entity_id.slice(6).replace(/[^A-Za-z0-9_\-.]/g,"_")}`.slice(0,54),u=c,d=1;for(;e.furniture.some(p=>p.id===u);)u=`${c}_${d++}`;e.furniture.push({id:u,type:i,x:o.x,z:o.z,rotation:0,w:s,d:l,h:a,variant:null,entity:o.entity_id,power:null,animations_enabled:o.animations_enabled,effect_animations:structuredClone(o.effect_animations)})}e.placements=e.placements.filter(o=>!o.entity_id.startsWith("light."))}e.openings=e.openings.map(r=>({...r,type:["door","window","garage"].includes(r.type)?r.type:"door",edge:Number.isInteger(r.edge)?r.edge:0,offset:Number.isFinite(r.offset)?r.offset:.5,width:Number.isFinite(r.width)&&r.width>0?r.width:r.type==="garage"?2.5:r.type==="window"?1.2:.9,height:Number.isFinite(r.height)&&r.height>0?r.height:r.type==="window"?1.3:r.type==="garage"?2.1:2.05,sill:Number.isFinite(r.sill)?r.sill:r.type==="window"?.9:0,hinge:r.hinge??"left",leaves:r.leaves??1,swing:r.swing??"in",style:r.style??null,cover:r.cover??null,contact:r.contact??null,contact2:r.contact2??null,tilt:r.tilt??null}))}return o_(t),t}function o_(t){let e=(n,r)=>{let o=new Set;for(let i of n)(typeof i.id!="string"||!i.id||o.has(i.id))&&(i.id=D(r)),o.add(i.id)};e(t.floors,"floor");for(let n of t.floors){for(let r of n.rooms)(typeof r.id!="string"||!r.id)&&(r.id=D("room"));e(n.openings,"op"),e(n.furniture,"furn"),e(n.outdoor,"out")}}function D(t){return`${t}_${Math.random().toString(36).slice(2,10)}`}function ge(t){let e=0;for(let n=0;ni+s[0],0)/o,t.reduce((i,s)=>i+s[1],0)/o]}let n=0,r=0;for(let o=0;o1e-6&&Math.abs(r-i)>1e-6)return!1}return!0}function ue(t){let e=1/0,n=1/0,r=-1/0,o=-1/0;for(let[i,s]of t)e=Math.min(e,i),n=Math.min(n,s),r=Math.max(r,i),o=Math.max(o,s);return{x0:e,z0:n,x1:r,z1:o}}function ms(t){let e=t.rotation*Math.PI/180,n=Math.cos(e),r=Math.sin(e),o=t.w/2,i=t.d/2;return[[-o,-i],[o,-i],[o,i],[-o,i]].map(([s,l])=>[t.x+s*n-l*r,t.z+s*r+l*n])}function N(t,e){let n=!1;for(let r=0,o=e.length-1;rt[1]!=a>t[1]&&t[0]<(l-i)*(t[1]-s)/(a-s)+i&&(n=!n)}return n}var Oo={lamp_ceiling:"ceiling",lamp_downlight:"downlight",lamp_spot:"spot",lamp_panel:"panel",lamp_uplight:"uplight",lamp_bollard:"bollard",lamp_garden:"garden",lamp_pendant:"pendant",ceiling_fan:"fan",lamp_floor:"floor",lamp_table:"table",lamp_wall:"wall",led_strip:"strip"};var gs=t=>t.trim().replace(/^\/local\/www\//i,"/local/"),_s=t=>/^(https:\/\/|\/local\/|\/hacsfiles\/)\S+\.m?js(\?\S*)?$/i.test(t.trim());var s_=globalThis,Zc=s_.__nextfloorPluginStore??={plugins:new Map,listeners:new Set},bs=Zc.plugins,jc=Zc.listeners;var a_=5;function qc(t,e){t.errors.lengthjc.delete(t)}var ys=()=>[...bs.values()].map(t=>t.status),Yc=()=>[...bs.values()].flatMap(t=>Object.keys(t.plugin.lightAnimations??{}));function*Lo(t,e){for(let{plugin:n,status:r}of bs.values())for(let o of n.devices??[]){let i=!1;try{i=o.match(t,e)}catch(s){qc(r,s)}i&&(yield{device:o,status:r})}}function Co(t,e){for(let{device:n}of Lo(t,e))return n.kind??"sensor";return null}function Xc(t,e){let n=t.states[e];if(!n)return null;let r=l_({hass:t,entityId:e,state:n})?.icon?.trim();return r&&/^mdi:[a-z0-9-]+$/i.test(r)?r:null}function l_(t){let e=null;for(let{device:n,status:r}of Lo(t.entityId,t.state))if(n.marker)try{let o=n.marker(t);if(!o)continue;e={...e??{}},typeof o.icon=="string"&&o.icon&&(e.icon=o.icon),typeof o.text=="string"&&(e.text=o.text.slice(0,60)),typeof o.active=="boolean"&&(e.active=o.active)}catch(o){qc(r,o)}return e}function No(t,e){return t?typeof t=="string"?t:t[e]??t[e.split("-")[0]]??t.en??Object.values(t)[0]??"":""}function Qc(t,e){let n=[];for(let{device:r,status:o}of Lo(t,e))r.settings?.length&&n.push({pluginId:o.id,name:o.name,settings:r.settings});return n}function Jc(t,e){let n={};for(let r of t??[]){let o=e?.[r.key],i=r.type==="number"?typeof o=="number"&&Number.isFinite(o):r.type==="boolean"?typeof o=="boolean":typeof o=="string"&&(r.options??[]).some(([s])=>s===o);n[r.key]=i?o:r.default}return n}function eu(t,e){for(let{device:n}of Lo(t,e))if(n.floorWedge)return!0;return!1}var c_=new Set(["temperature","humidity","power","carbon_dioxide","energy","gas","water","volume","volume_storage","volume_flow_rate","illuminance","pressure","atmospheric_pressure","pm1","pm25","pm10","volatile_organic_compounds","volatile_organic_compounds_parts","carbon_monoxide","nitrogen_dioxide","moisture","sound_pressure"]),u_=new Set(["m\xB3","m3","L","l","kWh","Wh","MWh","lx"]),d_=new Set(["door","window","opening","garage_door","motion","occupancy","presence","smoke","moisture","gas","carbon_monoxide"]),h_=new Set(["battery","signal_strength","timestamp","date","duration","data_rate","data_size","frequency","enum"]);function Tt(t,e){let n=t.entities?.[e];return n&&(n.area_id||(n.device_id?t.devices?.[n.device_id]?.area_id:null))||null}var nu=(t,e)=>{let n=t.entities?.[e];return!!(n?.hidden||n?.entity_category)},Ce=(t,e)=>X(e)??Co(e,t.states[e]);function tu(t,e){let n=t.states[e];if(!n||nu(t,e))return!1;if(Co(e,n)!==null)return!0;let r=X(e);if(!r)return!1;let o=n.attributes.device_class;return e.startsWith("event.")?!o||o==="button"||o==="doorbell":r==="sensor"?o?c_.has(o):u_.has(String(n.attributes.unit_of_measurement??"")):r==="binary"?o?d_.has(o):!!t.entities?.[e]?.area_id:!0}function p_(t,e){let n=t.states[e];return X(e)!=="sensor"||!n?.attributes.unit_of_measurement||nu(t,e)||h_.has(String(n.attributes.device_class??""))?!1:Number.isFinite(Number(n.state))||Rt(n)}var Wo=(t,e)=>e.startsWith("sensor.")&&t.states[e]?.attributes.device_class==="power",ws=null;Ho(()=>ws=null);function vs(t,e){let n=t.get(e);return n||t.set(e,n=[]),n}function f_(t){let e=new Map,n=new Map,r=new Map,o=new Map,i=[],s=u=>{(tu(t,u)||p_(t,u))&&Mt(Ce(t,u))&&i.push(u)};for(let[u,d]of Object.entries(t.entities??{})){let p=d.device_id;p&&d.area_id&&(o.get(p)??o.set(p,new Set).get(p)).add(d.area_id),p&&Wo(t,u)&&vs(n,p).push(u),p&&!d.hidden&&!d.entity_category&&(r.get(p)??r.set(p,new Set).get(p)).add(rs(u));let h=Tt(t,u);h===null?s(u):tu(t,u)&&vs(e,h).push(u)}if(t.entities)for(let u of Object.keys(t.states))t.entities[u]||s(u);let l=os.indexOf("binary")-.5,a=u=>{let d=X(u),p=d?os.indexOf(d):l;return p>l&&Co(u,t.states[u])!==null?l:p};i.sort((u,d)=>a(u)-a(d)||W(t,u).localeCompare(W(t,d)));for(let[u,d]of e){let p=t.areas?.[u]?.name;d.sort((h,f)=>a(h)-a(f)||W(t,h,p).localeCompare(W(t,f,p)))}let c=new Set;for(let[u,d]of o)d.size>1&&c.add(u);return{entities:t.entities,devices:t.devices,states:t.states,stateCount:Object.keys(t.states).length,byArea:e,powerByDevice:n,withoutArea:i,domainsByDevice:r,hubs:c}}function vn(t){let e=ws;return e&&e.entities===t.entities&&e.devices===t.devices&&(e.states===t.states||(e.states=t.states,Object.keys(t.states).length===e.stateCount))?e:ws=f_(t)}function be(t,e){let n=Bo(t,e.area_id);return e.sub_areas?.length?[...new Set([...n,...e.sub_areas.flatMap(r=>Bo(t,r))])]:n}function Bo(t,e){return!e||!t.entities?[]:vn(t).byArea.get(e)??[]}function ru(t,e){if(!t.entities)return[];let n=[];for(let[r,o]of vn(t).byArea){let i=o.filter(s=>Mt(Ce(t,s)));r!==e&&i.length>0&&n.push({areaId:r,name:t.areas?.[r]?.name??r,ids:i})}return n.sort((r,o)=>r.name.localeCompare(o.name))}var ou=t=>t.entities?vn(t).withoutArea:[],ks=(t,e)=>!!t.entities&&vn(t).hubs.has(e),Vo=(t,e)=>t.entities?vn(t).powerByDevice.get(e)??[]:[];function kn(t,e){let n=new Map;for(let o of e)vs(n,t.entities?.[o]?.device_id??`entity:${o}`).push(o);let r=new Map(e.map((o,i)=>[o,i]));return[...n.values()].map(o=>{let i=o.find(s=>!t.entities?.[s]?.name)??o[0];return{primary:i,others:o.filter(s=>s!==i)}}).sort((o,i)=>r.get(o.primary)-r.get(i.primary))}var Ko=(t,e)=>kn(t,e).map(n=>n.primary),xs={temperature:"temperature",humidity:"humidity",co2:"carbon_dioxide"},m_=new Set(["climate","water_heater","switch","button","camera","media_player","vacuum","light","fan","lawn_mower"]),g_=["vorlauf","r(\xFC|ue)cklauf","flow","return","d(\xFC|ue)se","nozzle","hotend","extruder","druckbett","heatbed","(^|[^a-z])bed($|[^a-z])","chamber","cpu","gpu","chip","soc","akku","batter","wasser","water","kessel","boiler","au(\xDF|ss)en","outdoor","outside","abgas","exhaust","sole","brine","verdampfer","kondensat","verdichter","compressor","motor","k(\xFC|ue)hl","freezer","fridge","gefrier"],__=new RegExp(`(${g_.join("|")})`,"i");function $s(t,e){let n=t.entities?.[e]?.device_id,r=n&&!ks(t,n)?vn(t).domainsByDevice.get(n):void 0;return r&&[...r].some(o=>m_.has(o))?!1:!__.test(`${e} ${t.states[e]?.attributes.friendly_name??""}`)}function iu(t,e,n,r){let o=n.climate?.[r];if(o==="none")return[];if(o)return[o].flat().filter(c=>t.states[c]);let i=(e?.placements??[]).filter(c=>c.entity_id.startsWith("sensor.")),s=i.filter(c=>N([c.x,c.z],n.points)).map(c=>c.entity_id),l=new Set(i.filter(c=>!N([c.x,c.z],n.points)).map(c=>c.entity_id));return[...new Set([...be(t,n).filter(c=>!l.has(c)),...s])].filter(c=>c.startsWith("sensor.")&&t.states[c]?.attributes.device_class===xs[r]&&$s(t,c))}var b_=new Set([void 0,"shutter","blind","awning","shade","curtain","window"]),y_=new Set(["garage","gate"]),w_=new Set(["window","opening"]);function pr(t,e,n=!1){let r=new Map;return t.forEach((o,i)=>{let s=n&&e.length===1?e[0]:e[i];s&&r.set(o.id,s)}),r}var su=(t,e)=>t==="none"?null:t??e??null,xn=t=>t&&t!=="none"?t:null;function fr(t,e){let n=new Map;for(let r of e)for(let o of r.rooms){let i=r.openings.filter(g=>g.room_id===o.id).sort((g,y)=>g.edge-y.edge||g.offset-y.offset);if(i.length===0)continue;let s=be(t,o),l=g=>t.states[g]?.attributes.device_class,a=g=>s.filter(y=>X(y)==="binary"&&g(l(y)??"")),c=g=>i.filter(y=>y.type===g),u=pr(c("window"),s.filter(g=>X(g)==="cover"&&b_.has(l(g))),!0),d=pr(c("window"),a(g=>w_.has(g))),p=pr(c("door"),a(g=>g==="door")),h=pr(c("garage"),s.filter(g=>X(g)==="cover"&&y_.has(l(g)??""))),f=pr(c("garage"),a(g=>g==="garage_door"));for(let g of i){let y=g.type==="window"?u:g.type==="garage"?h:null,b=g.type==="window"?d:g.type==="garage"?f:p,v=g.leaves===2;n.set(g.id,{cover:su(g.cover,y?.get(g.id)),contact:g.sensor==="handle"&&g.contact==null?null:su(g.contact,b.get(g.id)),tilt:g.tilt==="none"?null:g.tilt,contact2:v?xn(g.contact2):null,tilt2:v?xn(g.tilt2):null,position:xn(g.position),positionInverted:!!g.position_inverted,tiltAngle:xn(g.tilt_angle),tiltMax:g.tilt_max??null,tiltOffset:g.tilt_offset??null,tiltInvert:!!g.tilt_invert,shut:!!g.shut,angled:g.type==="door"&&!!g.open_angle,lock:g.type==="door"?xn(g.lock):null,cover2:g.type==="garage"?null:xn(g.cover2)})}}return n}var v_=[[/^(tilted|tilt|gekippt|kipp)/i,"tilted"],[/^(open|opened|offen|geöffnet|on)$/i,"open"],[/^(closed|close|geschlossen|zu|off)$/i,"closed"]];function Ss(t){if(!t||Rt(t))return null;let e=t.attributes.window_state;for(let n of[typeof e=="string"?e:"",t.state]){let r=n.trim(),o=r&&v_.find(([i])=>i.test(r));if(o)return o[1]}return null}var au=/\b(tv|fernseh|television|fire ?tv|apple ?tv|chromecast|shield)/i,lu=/(kühl|fridge|gefrier|freezer)/i,cu=/(spülmaschine|geschirrspül|dishwasher)/i,k_=/(kochfeld|herd|induktion|cooktop)/i,x_={robot_vacuum:/(saug|vacuum|robo|roomba|roborock|dreame|ecovacs|deebot)/i,tv_board:au,tv_wall:au,desk:/\b(pc|computer|rechner|desktop|monitor|workstation)/i,fridge:lu,fridge_smart:lu,stove:/(herd|kochfeld|cooktop|stove|induktion)/i,kitchen_tall:/(backofen|oven|ofen)/i,dishwasher:cu,washer:/(waschmaschine|washer|washing)/i,dryer:/(trockner|dryer)/i,kitchen:/(kaffee|coffee|wasserkocher|kettle)/i,island:k_,sink:cu,radiator:/(heiz|radiator|thermostat|climate|hk|trv)/i},uu={lamp_ceiling:/(decke|ceiling|haupt|main)/i,lamp_downlight:/(spot|strahler|downlight|einbau)/i,lamp_spot:/(spot|strahler)/i,lamp_panel:/(panel|decke|ceiling)/i,lamp_uplight:/(fluter|uplight|steh)/i,lamp_bollard:/(weg|garten|garden|path|poller|außen|aussen|outdoor)/i,lamp_garden:/(garten|garden|spot|außen|aussen|outdoor|baum|tree)/i,lamp_pendant:/(pendel|pendant|hänge|esstisch|dining)/i,ceiling_fan:/(ventilator|fan)/i,lamp_floor:/(steh|floor)/i,lamp_table:/(tisch|nacht|table|bedside|lese|reading)/i,lamp_wall:/(wand|wall)/i,led_strip:/(led|strip|streifen|leiste|band)/i},du=new Set(["tv_board","tv_wall"]);var $n=t=>du.has(t)||!!hc(t),Go=t=>!!G(t)?.electric&&/speaker|multiroom|soundbar/.test(t.split(":").pop()??t),gr=t=>$n(t)||t==="desk"||t==="fridge_smart",$_=t=>!!t&&t!=="none";function S_(t,e){if(Wo(t,e))return e;let n=t.entities?.[e]?.device_id;return n?Vo(t,n).find(r=>r!==e)??null:null}var M_=(t,e,n)=>t.rooms.find(r=>r.points.length>=3&&N([e,n],r.points));function mr(t,e,n,r){return t.find(o=>e?.test(n(o)))??(r?t[0]??null:null)}function Ne(t,e){let n=new Map;for(let r of e){let o=new Set([...r.furniture.flatMap(i=>[i.entity,i.power,i.fan_entity]),...r.placements.map(i=>i.entity_id)].filter($_));for(let i of r.furniture){let s=i.type in uu,l=gn(i.type),a=s?uu[i.type]:x_[i.type];if(!a&&!l&&!Go(i.type)&&i.entity==null&&i.power==null)continue;let c=M_(r,i.x,i.z),u=(c?Ko(t,be(t,c)):[]).filter(y=>!o.has(y)),d=y=>`${y} ${W(t,y)}`,p=y=>u.filter(b=>X(b)===y),h=i.entity==="none"?null:i.entity??null;if(i.entity==null){if(i.type==="ceiling_fan"){let y=(c?be(t,c):[]).filter(v=>!o.has(v)),b=new Set(y.filter(v=>X(v)==="fan").map(v=>t.entities?.[v]?.device_id).filter(Boolean));h=y.find(v=>X(v)==="light"&&b.has(t.entities?.[v]?.device_id))??mr(p("light"),a,d,!1)}else if(s)h=mr(p("light"),a,d,!0);else if(i.type==="robot_vacuum"){let y=c?.area_id??null;h=Object.keys(t.entities??{}).find(b=>b.startsWith("vacuum.")&&!o.has(b)&&Tt(t,b)===y)??null}else if(i.type==="radiator"||l)h=mr(p("climate"),a,d,!0);else if($n(i.type)){let y=p("media");h=y.find(b=>t.states[b]?.attributes.device_class==="tv")??mr(y,a,d,du.has(i.type))}else if(Go(i.type)){let y=p("media").filter(b=>t.states[b]?.attributes.device_class!=="tv");h=mr(y,a,d,!1)??(y.length===1?y[0]:null)}else a&&(h=u.find(y=>["switch","media","fan"].includes(X(y)??"")&&a.test(d(y)))??null);h&&o.add(h)}let f=i.power==="none"?null:i.power??null;i.power==null&&(f=h?S_(t,h):null,!f&&a&&c&&!s&&(f=be(t,c).find(y=>Wo(t,y)&&!o.has(y)&&a.test(d(y)))??null),f&&o.add(f));let g=null;if(i.type==="ceiling_fan"&&(g=i.fan_entity==="none"?null:i.fan_entity??null,i.fan_entity==null)){let y=(c?be(t,c):[]).filter(v=>X(v)==="fan"&&!o.has(v)),b=h?t.entities?.[h]?.device_id:void 0;g=(b?y.find(v=>t.entities?.[v]?.device_id===b):void 0)??y[0]??null,g&&o.add(g)}(h||f||g)&&n.set(i.id,{entity:h,power:f,...i.type==="ceiling_fan"?{fan:g}:{}})}}return n}var hu=t=>t==="fridge"||t==="fridge_smart"||/(fridge|freezer|kuehl|gefrier|chest_freezer)/.test(t.slice(t.lastIndexOf(":")+1));function pu(t,e,n=[]){let r=[];for(let o of e){let i=(l,a)=>o.rooms.some(c=>c.points.length>=3&&N([l,a],c.points)),s=Ne(t,[o]);r.push(...o.placements.filter(l=>l.outside||!i(l.x,l.z)).map(l=>l.entity_id)),r.push(...o.furniture.filter(l=>!i(l.x,l.z)).flatMap(l=>[s.get(l.id)?.entity,s.get(l.id)?.power]));for(let l of o.outdoor??[])l.area_id&&r.push(...Ko(t,Bo(t,l.area_id))),r.push(l.pump_entity,l.temp_entity)}return[...new Set(r.filter(o=>!!o&&!!t.states[o]&&!n.includes(o)))]}function R_(t,e){return Math.min(...e.map((n,r)=>{let o=e[(r+1)%e.length],[i,s]=[o[0]-n[0],o[1]-n[1]],l=Math.min(1,Math.max(0,((t[0]-n[0])*i+(t[1]-n[1])*s)/(i*i+s*s||1)));return Math.hypot(t[0]-n[0]-i*l,t[1]-n[1]-s*l)}))}function mu(t,e,n=[]){let r=t.points;if(r.length<3||e.length===0)return[];let o=r.map(b=>b[0]),i=r.map(b=>b[1]),[s,l,a,c]=[Math.min(...o),Math.max(...o),Math.min(...i),Math.max(...i)],u=Math.min(l-s,c-a),d=Math.max(.1,Math.min(.25,u/8)),p=Math.min(.35,u/5),h=Math.min(.7,u/4),f=_e(r),g=[];for(let b=s+d/2;b=p&&g.push({at:w,wallDistance:x})}g.length===0&&g.push({at:f,wallDistance:0});let y=[...n];return e.map(b=>{let v=X(b)==="light",w=g[0].at,x=-1/0;for(let{at:$,wallDistance:A}of g){let F=y.length?Math.min(...y.map(z=>Math.hypot($[0]-z[0],$[1]-z[1]))):3,T=Math.hypot($[0]-f[0],$[1]-f[1]),I=Math.min(F,3)*2;Tx+1e-9&&(x=I,w=$)}let k=[Math.round(w[0]*100)/100,Math.round(w[1]*100)/100];return y.push(k),{entity_id:b,x:k[0],z:k[1],y:null,mount:null}})}var fu=/(^|_)(current_room|current_segment|aktueller_raum|current_area)($|_)/;function gu(t,e,n){if(n==="none")return null;if(n)return n;let r=e?t.entities?.[e]?.device_id:null;return!r||!t.entities?null:Object.values(t.entities).find(i=>i.device_id===r&&i.entity_id.startsWith("sensor.")&&(fu.test(i.translation_key??"")||fu.test(i.entity_id.split(".")[1])))?.entity_id??null}var K=(t,e)=>[t[0]-e[0],t[1]-e[1]],lt=(t,e)=>[t[0]+e[0],t[1]+e[1]],et=(t,e)=>[t[0]*e,t[1]*e],Q=(t,e)=>t[0]*e[0]+t[1]*e[1],$e=(t,e)=>t[0]*e[1]-t[1]*e[0],me=t=>Math.hypot(t[0],t[1]),tt=t=>{let e=me(t)||1;return[t[0]/e,t[1]/e]},Ms=t=>[-t[1],t[0]],Rs=t=>[t[1],-t[0]];var E_=.05,A_=.2,F_=.12;function T_(t){let e=[];return t.forEach((n,r)=>{let o=n.points;if(o.length<3)return;let i=ge(o)>=0;o.forEach((s,l)=>{let a=o[(l+1)%o.length],c=me(K(a,s));if(c<.05)return;let u=[(a[0]-s[0])/c,(a[1]-s[1])/c],d=i?[u[1],-u[0]]:[-u[1],u[0]];(u[1]<-1e-9||Math.abs(u[1])<=1e-9&&u[0]<0)&&(u=[-u[0],-u[1]]);let p=[-u[1],u[0]],[h,f]=[Q(s,u),Q(a,u)];e.push({room:r,index:l,dir:u,normal:p,offset:Q(s,p),outside:Q(d,p)>0?1:-1,from:Math.min(h,f),to:Math.max(h,f)})})}),e}function z_(t,e,n){if(t.room===e.room||Math.abs($e(t.dir,e.dir))>E_||t.outside===e.outside)return null;let r=(e.offset-t.offset)*t.outside;return r>n||r<-F_||Math.abs(r)<1e-4||Math.min(t.to,e.to)-Math.max(t.from,e.from)Math.round(t*1e3)/1e3;function _u(t,e=.6){let n=T_(t),r=n.map((g,y)=>y),o=g=>r[g]===g?g:r[g]=o(r[g]),i=[],s=new Set,l=[];for(let g=0;gMath.abs(g[2])-Math.abs(y[2]));let a=new Map(n.map((g,y)=>[y,[y]])),c=(g,y)=>g.some(b=>y.some(v=>n[b].room===n[v].room&&Math.abs(n[b].offset-n[v].offset)>=.002));for(let[g,y,b]of l){let[v,w]=[o(g),o(y)];if(v!==w){if(c(a.get(v),a.get(w)))continue;r[v]=w,a.set(w,[...a.get(w),...a.get(v)]),a.delete(v)}i.push(Es(b)),s.add(g).add(y)}let u=new Map(n.map((g,y)=>[`${g.room}:${g.index}`,y]));for(let g=s.size>0;g;)g=!1,n.forEach((y,b)=>{let v=u.get(`${y.room}:${(y.index+1)%t[y.room].points.length}`);if(v===void 0||v===b)return;let w=n[v];!(Math.abs($e(y.dir,w.dir))<1e-6&&Math.abs(y.offset-w.offset)<.002&&y.outside===w.outside)||s.has(b)===s.has(v)||(s.add(b).add(v),g=!0)});n.forEach((g,y)=>{let b=u.get(`${g.room}:${(g.index+1)%t[g.room].points.length}`);if(b===void 0||b===y||!s.has(y)||!s.has(b))return;let v=n[b];Math.abs($e(g.dir,v.dir))<1e-6&&Math.abs(g.offset-v.offset)<.002&&g.outside===v.outside&&(r[o(y)]=o(b))});let d=()=>t.map(g=>({...g,points:g.points.map(y=>[y[0],y[1]])}));if(i.length===0)return{rooms:d(),gaps:i};let p=new Map;for(let g of s)p.set(o(g),[...p.get(o(g))??[],g]);let h=t.map(g=>g.points.map(()=>new Map));for(let[g,y]of p){let b=new Map(y.map(w=>[`${n[w].room}:${Math.round(n[w].offset*500)}`,n[w].offset])),v=[...b.values()].reduce((w,x)=>w+x,0)/b.size;for(let w of y){let x=n[w],k=[x.normal[0]*(v-x.offset),x.normal[1]*(v-x.offset)];h[x.room][x.index].set(g,k),h[x.room][(x.index+1)%t[x.room].points.length].set(g,k)}}return{rooms:t.map((g,y)=>({...g,points:g.points.map((b,v)=>{let w=[...h[y][v].values()].reduce((x,k)=>[x[0]+k[0],x[1]+k[1]],[b[0],b[1]]);return[Es(w[0]),Es(w[1])]})})),gaps:i}}function bu(t){let e=t.filter(n=>n>.04).sort((n,r)=>n-r);return e.length===0?null:Math.min(.5,Math.max(.08,Math.round(e[Math.floor(e.length/2)]*100)/100))}var P_=.25,yu=t=>Math.round(t*1e3)/1e3,wu=(t,e,n)=>t.rooms.find(r=>r.points.length>=3&&N([e,n],r.points));function Fs(t,e,n,r,o){let i=wu(t,e,n);if(!i)return[r,o];let s=(l,a)=>N([l,a],i.points);return s(r,o)?[r,o]:s(r,n)?[r,n]:s(e,o)?[e,o]:[e,n]}function I_(t,e,n,r){return t.rooms.some(o=>o.id!==e.id&&o.points.some((i,s)=>{let l=o.points[(s+1)%o.points.length];return Math.abs(Q(K(i,n),r))<.02&&Math.abs(Q(K(l,n),r))<.02}))}var As=(t,e)=>Math.abs((t-e+540)%360-180);function _r(t,e,n,r=P_){let o=wu(t,e.x,e.z);if(!o)return null;let i=o.points,s=ge(i)>=0?1:-1,l=null;return i.forEach((a,c)=>{let u=i[(c+1)%i.length],d=me(K(u,a));if(d<.3)return;let p=[(u[0]-a[0])/d,(u[1]-a[1])/d],h=[-p[1]*s,p[0]*s],f=Q(K([e.x,e.z],a),p);if(f<0||f>d)return;let g=I_(t,o,a,h)?n/2:0,y=Q(K([e.x,e.z],a),h)-g,b=Math.atan2(-h[0],h[1])*180/Math.PI,w=[{rotation:b,extent:e.d/2},{rotation:b+90,extent:e.w/2},{rotation:b-90,extent:e.w/2}].reduce((k,$)=>As(e.rotation,$.rotation)50)return;let x=y-w.extent;Math.abs(x)>r||l&&Math.abs(x)>=Math.abs(l.gap)||(l={x:yu(e.x-h[0]*x),z:yu(e.z-h[1]*x),rotation:(Math.round(w.rotation)%360+360)%360,gap:x})}),l&&{x:l.x,z:l.z,rotation:l.rotation}}var Sn=Math.PI/180,nt=t=>Math.tan(Math.min(80,Math.max(0,t))*Sn);function yr(t){return{x0:Math.min(t.x0,t.x1),x1:Math.max(t.x0,t.x1),z0:Math.min(t.z0,t.z1),z1:Math.max(t.z0,t.z1)}}function vu(t){if(!t.rotation)return null;let e=t.rotation*Sn;return{cx:(t.x0+t.x1)/2,cz:(t.z0+t.z1)/2,c:Math.cos(e),sn:Math.sin(e)}}function ku(t,e){let n=vu(t);if(!n)return e;let[r,o]=[e[0]-n.cx,e[1]-n.cz];return[n.cx+r*n.c-o*n.sn,n.cz+r*n.sn+o*n.c]}function Ts(t,e,n){let r=vu(t);if(!r)return[e,n];let[o,i]=[e-r.cx,n-r.cz];return[r.cx+o*r.c+i*r.sn,r.cz-o*r.sn+i*r.c]}function wr(t,e=0){let{x0:n,x1:r,z0:o,z1:i}=yr(t);return[[n-e,o-e],[r+e,o-e],[r+e,i+e],[n-e,i+e]].map(s=>ku(t,s))}function ve(t){let{x0:e,x1:n,z0:r,z1:o}=yr(t),i=s=>ku(t,s);return t.axis==="x"?{u0:e,u1:n,w:o-r,at:(s,l)=>i([s,t.flip?o-l:r+l])}:{u0:r,u1:o,w:n-e,at:(s,l)=>i([t.flip?n-l:e+l,s])}}function vr(t,e,n){let{x0:r,x1:o,z0:i,z1:s}=yr(t),[l,a]=Ts(t,e,n);return t.axis==="x"?[l,t.flip?s-a:a-i]:[a,t.flip?o-l:l-r]}var br=Math.tan(30*Sn);function kr(t,e,n,r,o){let i=Math.min(t*.3,r>1e-6?2.4/r:t*.3),s=Math.min(t*.3,o>1e-6?2.4/o:t*.3),l=e+i*r,a=n+s*o,c=Math.min(t-s,Math.max(i,(a-l+br*(t-s+i))/(2*br))),u=l+(c-i)*br;return{vla:i,vlb:s,yla:l,ylb:a,vr:c,rh:u,y:p=>p<=i?e+p*r:p<=c?l+(p-i)*br:p<=t-s?a+(t-s-p)*br:n+(t-p)*o}}function ze(t){let e=ve(t).w,[n,r]=[t.eave_a,t.eave_b],[o,i]=[nt(t.pitch_a),nt(t.pitch_b)];switch(t.shape){case"flat":case"parapet":return{vr:e/2,rh:n,y:()=>n};case"pent":return{vr:e,rh:n+e*o,y:s=>n+s*o};case"mansard":{let s=kr(e,n,r,o,i);return{vr:s.vr,rh:s.rh,y:s.y}}default:{let s=o+i>1e-6?Math.min(e,Math.max(0,(r-n+e*i)/(o+i))):e/2;return{vr:s,rh:n+s*o,y:l=>l<=s?n+l*o:r+(e-l)*i}}}}var Zt=t=>ze(t).rh;function xu(t){let e=t.heightEnd!==void 0;return{...t,a:t.b,b:t.a,left:t.right,right:t.left,roomLeft:t.roomRight,roomRight:t.roomLeft,height:e?t.heightEnd:t.height,heightEnd:e?t.height:void 0}}function D_(t,e){let n=t.map(r=>({...r}));for(let r of e){let o=n.find(i=>i.room_id===r.room_id&&i.edge===r.edge&&(Math.abs(i.t1-r.t0)<1e-6||Math.abs(r.t1-i.t0)<1e-6));o?(o.t0=Math.min(o.t0,r.t0),o.t1=Math.max(o.t1,r.t1)):n.push({...r})}return n}function O_(t,e,n){if(t.a===e.b)return!1;let r=tt(K(n[t.b],n[t.a])),o=tt(K(n[e.b],n[e.a]));return Math.abs($e(r,o))>1e-6||Q(r,o)<=0||t.free||e.free||t.heightEnd!==void 0||e.heightEnd!==void 0?!1:t.height===e.height&&t.exterior===e.exterior&&t.roomLeft===e.roomLeft&&t.roomRight===e.roomRight&&Math.abs(t.left-e.left)<=1e-9&&Math.abs(t.right-e.right)<=1e-9}function $u(t,e,n=new Set){let r=t.slice();for(;;){let o=new Map;r.forEach((s,l)=>{for(let a of[s.a,s.b])o.set(a,[...o.get(a)??[],l])});let i=null;for(let[s,l]of o){if(l.length!==2||n.has(s))continue;let a=r[l[0]].b===s?r[l[0]]:xu(r[l[0]]),c=r[l[1]].a===s?r[l[1]]:xu(r[l[1]]);if(!O_(a,c,e))continue;let u={...a,b:c.b,sources:D_(a.sources,c.sources)};i=[...r.filter((d,p)=>p!==l[0]&&p!==l[1]),u];break}if(!i)return r;r=i}}function Su(t,e){let n=new Map;t.forEach((o,i)=>{let s=tt(K(e[o.b],e[o.a])),l=[[o.a,{key:`${i}:a`,d:s,left:o.left,right:o.right,angle:Math.atan2(s[1],s[0])}],[o.b,{key:`${i}:b`,d:et(s,-1),left:o.right,right:o.left,angle:Math.atan2(-s[1],-s[0])}]];for(let[a,c]of l)n.set(a,[...n.get(a)??[],c])});let r=new Map;for(let[o,i]of n){let s=e[o];i.sort((a,c)=>a.angle-c.angle);for(let a of i)r.set(a.key,{left:lt(s,et(Ms(a.d),a.left)),right:lt(s,et(Rs(a.d),a.right))});if(i.length<2)continue;let l=4*Math.max(...i.map(a=>Math.max(a.left,a.right)))+1e-9;i.forEach((a,c)=>{let u=i[(c+1)%i.length],d=lt(s,et(Ms(a.d),a.left)),p=lt(s,et(Rs(u.d),u.right)),h=$e(a.d,u.d);if(Math.abs(h)<1e-4)return;let f=lt(d,et(a.d,$e(K(p,d),u.d)/h));me(K(f,s))>l||(r.get(a.key).left=f,r.get(u.key).right=f)})}return r}function Mu(t,e){let n=t.filter((r,o)=>me(K(r,t[(o+1)%t.length]))>e);for(;;){if(n.length<=3)return n;let r=n.findIndex((o,i)=>{let s=n[(i+n.length-1)%n.length],l=n[(i+1)%n.length],[a,c]=[K(o,s),K(l,o)];return Math.abs($e(tt(a),tt(c)))<1e-7&&Q(a,c)>0});if(r===-1)return n;n=n.filter((o,i)=>i!==r)}}function H_(t){let e=[];return{points:e,idOf(n){let r=e.findIndex(o=>Math.abs(o[0]-n[0])<=t&&Math.abs(o[1]-n[1])<=t);return r>=0?r:(e.push([n[0],n[1]]),e.length-1)}}}function L_(t,e){let n=[];for(let r of t){let o=r.points;if(o.length<3||Math.abs(ge(o))<1e-6)continue;let i=ge(o)>0,s=o.map(l=>e.idOf(l));s.forEach((l,a)=>{let c=s[(a+1)%s.length];l!==c&&n.push(i?{u:l,v:c,room:r.id,edge:a,forward:!0}:{u:c,v:l,room:r.id,edge:a,forward:!1})})}return n}function C_(t,e,n){let r=[];for(let o of t){let[i,s]=[e[o.u],e[o.v]],l=K(s,i),a=me(l),c=et(l,1/a),u=e.map((p,h)=>({id:h,rel:K(p,i)})).filter(({id:p,rel:h})=>p!==o.u&&p!==o.v&&Q(h,c)>n&&Q(h,c)({t:Q(h,c),id:p})).sort((p,h)=>p.t-h.t),d=[{t:0,id:o.u},...u,{t:a,id:o.v}];for(let p=0;p+1({room_id:t.room,edge:t.edge,t0:t.t0,t1:t.t1});function N_(t,e){let n=new Map(t.map(l=>[l.id,l])),r=new Map;for(let l of e){let a=`${l.room}:${l.edge}`;r.set(a,[...r.get(a)??[],l.t0].sort((c,u)=>c-u))}let o=l=>{let a=n.get(l.room)?.wall_heights?.[l.edge];return Array.isArray(a)?a[(r.get(`${l.room}:${l.edge}`)??[]).indexOf(l.t0)]??null:a},i=l=>{let a=n.get(l.room),[c,u]=[a?.wall_heights?.[l.edge],a?.wall_slopes?.[l.edge]];if(!a||typeof c!="number"||typeof u!="number"||c<=0||u<=0)return null;let[d,p]=[a.points[l.edge],a.points[(l.edge+1)%a.points.length]];return{from:c,to:u,length:Math.hypot(p[0]-d[0],p[1]-d[1])}},s=l=>{let a=i(l);if(!a||a.length<1e-9){let u=o(l);return typeof u=="number"&&u>0?[u,u]:[null,null]}let c=u=>a.from+(a.to-a.from)*u/a.length;return l.forward?[c(l.t0),c(l.t1)]:[c(l.t1),c(l.t0)]};return{heightsOf(l){let[a,c]=[1/0,1/0];for(let d of l){let[p,h]=s(d),[f,g]=d===l[0]?[p,h]:[h,p];f!==null&&(a=Math.min(a,f)),g!==null&&(c=Math.min(c,g))}let u=l.map(d=>n.get(d.room)?.ceiling);if(u.every(d=>typeof d=="number"&&d>0)){let d=Math.max(...u);a===1/0&&(a=d),c===1/0&&(c=d)}return{...a<1/0?{a}:{},...c<1/0?{b:c}:{}}},thicknessOf(l){let a=l.map(c=>{let u=n.get(c.room)?.wall_thickness?.[c.edge];return Array.isArray(u)?u[(r.get(`${c.room}:${c.edge}`)??[]).indexOf(c.t0)]:u}).filter(c=>typeof c=="number"&&c>0);return a.length?Math.max(...a):void 0},hasNoWall:l=>l.some(a=>o(a)===0)}}function Eu(t){let e=n=>Math.round(n*1e6)/1e6;return t.a===void 0||t.b===void 0?t.a!==void 0?{height:e(t.a)}:t.b!==void 0?{height:e(t.b)}:{}:Math.abs(t.a-t.b)<1e-6?{height:e(t.a)}:{height:e(t.a),heightEnd:e(t.b)}}function B_(t,e,n,r){let o=N_(e,t),i=new Map;for(let a of t){let c=a.up!==c&&p.u===c.v&&p.v===c.u&&p.room!==c.room);for(let p of a)p!==c&&p!==u&&p.room!==c.room&&r.push(`overlap:${c.room}:${p.room}`);let d=u?[c,u]:[c];if(o.hasNoWall(d)){u&&l.push([c.room,u.room]);continue}if(u){let p=o.thicknessOf(d)??n.interior;s.push({a:c.u,b:c.v,left:p/2,right:p/2,exterior:!1,roomLeft:c.room,roomRight:u.room,sources:d.map(Ru),...Eu(o.heightsOf(d))})}else s.push({a:c.u,b:c.v,left:0,right:o.thicknessOf(d)??n.exterior,exterior:!0,roomLeft:c.room,roomRight:null,sources:[Ru(c)],...Eu(o.heightsOf(d))})}return{drafts:s,open:l}}function W_(t,e){let n=i=>tt(K(e[i.b],e[i.a])),r=t.filter(i=>!i.exterior&&!i.free),o=new Map;for(let i of r){if(o.has(i))continue;let s=[i];o.set(i,s);for(let l=0;l1e-6||a.add(Q(s,h)>0?"left":"right")}if(a.size!==1)continue;let c=[...a][0];for(let u of i){let d=u.left+u.right,p=Q(n(u),s)>0,h=c==="left"===p;[u.left,u.right]=h?[0,d]:[d,0]}}}var V_=(t,e)=>{let n=i=>Math.round(i*100),[r,o]=t[0]Math.hypot(b.b[0]-b.a[0],b.b[1]-b.a[1])>.05),a=l.map(b=>[i.idOf(b.a),i.idOf(b.b)]),c=new Set;for(let b of t){let v=b.points;v.length<3||(b.wall_splits??[]).forEach((w,x)=>{if(!w||x>=v.length)return;let k=v[x],$=K(v[(x+1)%v.length],k),A=me($);for(let F of w)F>r&&F{let[w,x]=a[v];if(w===x)return;let k=[(b.a[0]+b.b[0])/2,(b.a[1]+b.b[1])/2],$=t.find(F=>F.points.length>=3&&N(k,F.points))?.id??null,A=(b.thickness??e.interior)/2;h.push({free:b.id,a:w,b:x,left:A,right:A,exterior:!1,roomLeft:$,roomRight:$,sources:[],height:typeof b.height=="number"&&b.height>0?b.height:void 0,...typeof b.height=="number"&&b.height>0&&typeof b.height_end=="number"&&b.height_end>0&&Math.abs(b.height_end-b.height)>1e-6?{heightEnd:b.height_end}:{}})});let f=$u(h,i.points,c),g=Su(f,i.points);return{walls:f.map((b,v)=>{let[w,x]=[i.points[b.a],i.points[b.b]],[k,$]=[g.get(`${v}:a`),g.get(`${v}:b`)],A=Mu([k.right,$.left,x,$.right,k.left,w],1e-6);return{id:V_(w,x),a:[w[0],w[1]],b:[x[0],x[1]],left:b.left,right:b.right,exterior:b.exterior,roomLeft:b.roomLeft,roomRight:b.roomRight,sources:b.sources,footprint:A,...b.free?{free:b.free}:{},...b.height!==void 0?{height:b.height}:{},...b.heightEnd!==void 0?{heightEnd:b.heightEnd}:{}}}),warnings:[...new Set(o)],open:p}}function Mn(t,e,n){let r=t.points[e];return lt(r,et(tt(K(t.points[(e+1)%t.points.length],r)),n))}function Pe(t,e,n){if(t.wall){let o=n.find(l=>l.id===t.wall);if(!o||Math.hypot(o.b[0]-o.a[0],o.b[1]-o.a[1])<.05)return null;let i=tt(K(o.b,o.a));return{room:{id:t.room_id,name:"",area_id:null,points:[o.a,o.b,lt(o.a,[-i[1],i[0]])]},edge:0}}let r=e.find(o=>o.id===t.room_id);return r&&t.edgeQ(K(e,t.a),tt(K(t.b,t.a)));function zt(t,e,n){if(!e.wall)return K_(t,n.room,n.edge,e.offset);let r=t.find(o=>o.free===e.wall);return r?{wall:r,s:Au(r,Mn(n.room,0,e.offset))}:null}function K_(t,e,n,r){for(let o of t)if(o.sources.some(s=>s.room_id===e.id&&s.edge===n&&r>=s.t0-1e-6&&r<=s.t1+1e-6))return{wall:o,s:Au(o,Mn(e,n,r))};return null}function Fu(t,e){let n=t.points.map(h=>h[0]),r=t.points.map(h=>h[1]);if(t.points.length!==4||new Set(n.map(h=>h.toFixed(3))).size!==2||new Set(r.map(h=>h.toFixed(3))).size!==2)return null;let[o,i,s,l]=[Math.min(...n),Math.max(...n),Math.min(...r),Math.max(...r)],a=h=>Math.max(0,...e.filter(f=>(f.roomLeft===t.id||f.roomRight===t.id)&&h(f)).map(f=>f.roomLeft===t.id?f.left:f.right)),c=(h,f)=>Math.abs(h-f)<.001,u=(h,f,g)=>c(h.a[f],g)&&c(h.b[f],g),d=i-o-a(h=>u(h,0,o))-a(h=>u(h,0,i)),p=l-s-a(h=>u(h,1,s))-a(h=>u(h,1,l));return[Math.round(d*1e3)/1e3,Math.round(p*1e3)/1e3]}var Tu=([t,e])=>{let n=Math.hypot(t,e)||1;return[t/n,e/n]};function G_(t){return t.reduce((e,n,r)=>e+(n[0]*t[(r+1)%t.length][1]-t[(r+1)%t.length][0]*n[1]),0)/2}function zu(t,e){let n=t.length;if(n<3||Math.abs(e)<1e-9)return t.map(([o,i])=>[o,i]);let r=G_(t)>=0?1:-1;return t.map((o,i)=>{let s=t[(i+n-1)%n],l=t[(i+1)%n],[a,c]=Tu([o[0]-s[0],o[1]-s[1]]),[u,d]=Tu([l[0]-o[0],l[1]-o[1]]),p=[c*r,-a*r],h=[d*r,-u*r],f=[p[0]+h[0],p[1]+h[1]],g=Math.hypot(f[0],f[1]);if(g<1e-6)return[o[0]+p[0]*e,o[1]+p[1]*e];let y=(f[0]*p[0]+f[1]*p[1])/g,b=Math.min(4,1/Math.max(.25,y));return[o[0]+f[0]/g*e*b,o[1]+f[1]/g*e*b]})}function Pt(t){let e=t.map(r=>r[0]),n=t.map(r=>r[1]);return{x0:Math.min(...e),z0:Math.min(...n),x1:Math.max(...e),z1:Math.max(...n)}}function U_(t){let e=([i,s])=>`${Math.round(i*1e3)}:${Math.round(s*1e3)}`,n=new Map;for(let i of t)for(let s of[i.a,i.b])n.set(e(s),[...n.get(e(s))??[],i]);let r=new Set,o=null;for(let i of t){if(r.has(i))continue;r.add(i);let s=[i.a,i.b],l=i.b;for(;;){let c=(n.get(e(l))??[]).find(u=>!r.has(u));if(!c||(r.add(c),l=e(c.a)===e(l)?c.b:c.a,e(l)===e(s[0])))break;s.push(l)}s.length>=3&&e(l)===e(s[0])&&(!o||Math.abs(we(s))>Math.abs(we(o)))&&(o=s)}return o}function zs(t,e,n,r){let o=fe(t,{exterior:n,interior:r},e).walls.filter(l=>l.exterior&&!l.free),i=o.length?U_(o.map(l=>({a:l.a,b:l.b}))):null;if(!i)return null;let s=i.filter((l,a)=>{let c=i[(a+i.length-1)%i.length],u=i[(a+1)%i.length];return Math.abs((l[0]-c[0])*(u[1]-l[1])-(l[1]-c[1])*(u[0]-l[0]))>1e-6});return s.length>=3?zu(s,n):null}function qt(t,e){let n=ve(t),r=ze(t),o=n.w,[i,s]=[Math.max(0,e.a),Math.max(0,e.b)],l=n.u0-Math.max(0,e.u0),a=n.u1+Math.max(0,e.u1),c=(b,v)=>[b,v,r.y(v)],u=c(l,-i),d=c(a,-i),p=c(a,o+s),h=c(l,o+s),[f,g]=[nt(t.pitch_a),nt(t.pitch_b)],y=b=>[b,r.vr,r.rh];if(t.ends&&(t.shape==="gable"||t.shape==="hip"||t.shape==="halfhip")){let b=(n.u1-n.u0)/2,v=Math.min(b,Math.min(r.vr,o-r.vr)||o/2),w=Math.min(r.y(0),r.y(o)),x=w+(r.rh-w)*Math.min(.9,Math.max(.2,t.halfhip??.55)),k=f>1e-6?Math.min(r.vr,(x-t.eave_a)/f):r.vr,$=g>1e-6?Math.max(r.vr,o-(x-t.eave_b)/g):r.vr,A=Math.min(b-.1,(r.rh-x)/Math.max(.2,f)),F=[[0,r.y(0)],[r.vr,r.rh],[o,r.y(o)]],T=[[0,r.y(0)],[k,x],[$,x],[o,r.y(o)]],I=(V,Bt,fo)=>{if(V==="hip")return{upA:[],upB:[],ridge:y(Bt===l?n.u0+v*fo:n.u1-v*fo),profile:null};if(V==="halfhip"){let Pg=y(Bt===l?n.u0+A:n.u1-A);return{upA:[[Bt,k,x]],upB:[[Bt,$,x]],ridge:Pg,profile:T}}return{upA:[],upB:[],ridge:y(Bt),profile:F}},z=I(t.ends[0],l,1),C=I(t.ends[1],a,1),B=[[u,d,...C.upA,C.ridge,z.ridge,...[...z.upA].reverse()],[z.ridge,C.ridge,...[...C.upB].reverse(),p,h,...z.upB]],q=[[z.ridge,C.ridge]];for(let[V,Bt,fo]of[[z,u,h],[C,d,p]])V.profile===null?(B.push(V===z?[h,u,V.ridge]:[d,p,V.ridge]),q.push([Bt,V.ridge],[fo,V.ridge])):V.upA.length&&(B.push(V===z?[V.upB[0],V.upA[0],V.ridge]:[V.upA[0],V.upB[0],V.ridge]),q.push([V.upA[0],V.ridge],[V.upB[0],V.ridge]));let ye=V=>V.profile===null?[]:V.upA.length?[V.upA[0],V.upB[0]]:[V.ridge],$t=[u,d,...ye(C),p,h,...[...ye(z)].reverse()];return{faces:B,rim:$t,ridges:q,gable:F,endProfiles:[z.profile,C.profile]}}switch(t.shape){case"pent":return{faces:[[u,d,p,h]],rim:[u,d,p,h],ridges:[[p,h]],gable:[[0,r.y(0)],[o,r.y(o)]]};case"hip":case"pyramid":{let b=(n.u1-n.u0)/2,v=t.shape==="pyramid"?b:Math.min(b,Math.min(r.vr,o-r.vr)||o/2),w=y(n.u0+v),x=y(n.u1-v);return t.shape==="pyramid"?{faces:[[u,d,w],[d,p,w],[p,h,w],[h,u,w]],rim:[u,d,p,h],ridges:[[u,w],[h,w],[d,w],[p,w]],gable:null}:{faces:[[u,d,x,w],[w,x,p,h],[h,u,w],[d,p,x]],rim:[u,d,p,h],ridges:[[w,x],[u,w],[h,w],[d,x],[p,x]],gable:null}}case"halfhip":{let b=Math.min(r.y(0),r.y(o)),v=b+(r.rh-b)*Math.min(.9,Math.max(.2,t.halfhip??.55)),w=f>1e-6?Math.min(r.vr,(v-t.eave_a)/f):r.vr,x=g>1e-6?Math.max(r.vr,o-(v-t.eave_b)/g):r.vr,k=Math.min((n.u1-n.u0)/2-.1,(r.rh-v)/Math.max(.2,f)),$=y(n.u0+k),A=y(n.u1-k),F=[l,w,v],T=[l,x,v],I=[a,w,v],z=[a,x,v];return{faces:[[u,d,I,A,$,F],[$,A,z,p,h,T],[T,F,$],[I,z,A]],rim:[u,d,I,z,p,h,T,F],ridges:[[$,A],[F,$],[T,$],[I,A],[z,A]],gable:[[0,r.y(0)],[w,v],[x,v],[o,r.y(o)]]}}case"mansard":{let b=kr(o,t.eave_a,t.eave_b,f,g),v=[l,b.vla,b.yla],w=[a,b.vla,b.yla],x=[l,o-b.vlb,b.ylb],k=[a,o-b.vlb,b.ylb],$=[l,b.vr,b.rh],A=[a,b.vr,b.rh];return{faces:[[u,d,w,v],[v,w,A,$],[$,A,k,x],[x,k,p,h]],rim:[u,d,w,A,k,p,h,x,$,v],ridges:[[$,A],[v,w],[x,k]],gable:[[0,r.y(0)],[b.vla,b.yla],[b.vr,b.rh],[o-b.vlb,b.ylb],[o,r.y(o)]]}}default:{let b=y(l),v=y(a);return{faces:[[u,d,v,b],[b,v,p,h]],rim:[u,d,v,p,h,b],ridges:[[b,v]],gable:[[0,r.y(0)],[r.vr,r.rh],[o,r.y(o)]]}}}}function xr(t,e,n){let r=null;for(let o of t.faces){if(!N([e,n],o.map(([p,h])=>[p,h])))continue;let[i,s]=o,l=o.slice(2).find(p=>Math.abs((s[0]-i[0])*(p[1]-i[1])-(s[1]-i[1])*(p[0]-i[0]))>1e-9);if(!l)continue;let a=[s[0]-i[0],s[2]-i[2],s[1]-i[1]],c=[l[0]-i[0],l[2]-i[2],l[1]-i[1]],u=[a[1]*c[2]-a[2]*c[1],a[2]*c[0]-a[0]*c[2],a[0]*c[1]-a[1]*c[0]];if(Math.abs(u[1])<1e-9)continue;let d=i[2]-(u[0]*(e-i[0])+u[2]*(n-i[1]))/u[1];r=r===null?d:Math.min(r,d)}return r}function $r(t,e,n){let r=ve(e),o=t.floors.flatMap(d=>d.rooms.filter(p=>p.points.length>=3&&d.elevation+d.height>e.base+.05)),i=d=>d.some(p=>o.some(h=>N(p,h.points))),s=.35,l=[.15,.5,.85].map(d=>r.u0+(r.u1-r.u0)*d),a=[.15,.5,.85].map(d=>r.w*d),c=d=>d?0:n,u=(d,p)=>{let h=e.overhang_sides?.[d];return typeof h=="number"&&Number.isFinite(h)?Math.min(2,Math.max(0,h)):p};return{a:u("a",c(i(l.map(d=>r.at(d,-s))))),b:u("b",c(i(l.map(d=>r.at(d,r.w+s))))),u0:u("u0",c(i(a.map(d=>r.at(r.u0-s,d))))),u1:u("u1",c(i(a.map(d=>r.at(r.u1+s,d)))))}}var Uo=t=>Math.abs((t.x1-t.x0)*(t.z1-t.z0)),Pu=t=>t.shape==="flat"||t.shape==="parapet",Yt=t=>Math.round(t*100)/100;function jo(t,e){let[n,r]=[(e.x0+e.x1)/2,(e.z0+e.z1)/2];return t.filter(i=>{if(i===e||i.dormer||i.open||Pu(i)||Uo(i)=s.x0&&n<=s.x1&&r>=s.z0&&r<=s.z1}).reduce((i,s)=>i===null||Uo(s){let[i,s]=e.at(o,e.w/2),[l,a]=vr(t,i,s);return xr(n,l,a)??r.y(a)}}function Is(t,e){if(Pu(e))return e;let n=ve(e),r=ze(e).rh,o=Z_(t,n),i=o(n.u0)<=o(n.u1),[s,l]=i?[n.u0,n.u1]:[n.u1,n.u0],a=i?1:-1,c=l;for(let p=.5;p=r-.02){c=s+a*p;break}if(Math.abs(c-l)<.05)return e;let u={...e},d=l===n.u1;return e.axis==="x"?u[d?"x1":"x0"]=c:u[d?"z1":"z0"]=c,u}var Ds=.14,Iu=t=>t.shape==="flat"||t.shape==="parapet";function Os(t,e){return!t.open&&Math.min(t.base,t.eave_a,t.eave_b)a+o||pu+o||s.points&&s.points.length>=3&&!N([e,n],s.points))continue;let[h,f]=vr(s,e,n),g=Math.max(0,s.overhang??r),y=Iu(s)?null:xr(qt(s,{u0:g,u1:g,a:g,b:g}),h,f);i.push((y??ze(s).y(f))-Ds)}return i.length?Math.max(...i):null}function Hs(t,e,n){let r=[],o=e+n+Ds;for(let i of t.settings.roof.sections??[]){if(i.open||Iu(i)||i.shape==="mansard")continue;let s=ve(i),l=ze(i),[a,c]=[nt(i.pitch_a),nt(i.pitch_b)],u=[];a>1e-6&&u.push((o-i.eave_a)/a),i.shape==="gable"&&c>1e-6&&u.push(s.w-(o-i.eave_b)/c);for(let d of u)d<=.01||d>=s.w-.01||i.shape==="gable"&&Math.abs(l.y(d)-o)>1e-6||r.push([s.at(s.u0,d),s.at(s.u1,d)])}return r}function Ls(t,e,n,r,o){let i=[];for(let l of[.2,.5,.8])for(let a of[.2,.5,.8])i.push([e+(r-e)*l,n+(o-n)*a]);let s=t.floors.filter(l=>l.rooms.some(a=>a.points.length>=3&&i.some(c=>N(c,a.points)))).map(l=>l.elevation+l.height);return s.length?Math.max(...s):null}function Cs(t,e){let n=t.floors.filter(a=>a.rooms.length>0).sort((a,c)=>a.elevation-c.elevation),r=n.filter(a=>a.elevationu.rooms.some(d=>d.points.length>=3&&a.some(p=>N(p,d.points))));if(c)return c}return r.at(-1)??n[0]}var _t=t=>Math.round(t*1e3)/1e3;function Ns(t,e=n=>`roof_${n+1}`){let n=t.settings.roof?.pitch??35,r=t.settings.wall_exterior,o=t.floors.filter(a=>a.rooms.some(c=>c.points.length>=3)).sort((a,c)=>c.elevation-a.elevation),i=[],s=[],l=(a,c)=>a.some(u=>N(c,u.points));for(let a of o){let c=a.rooms.filter(y=>y.points.length>=3),u=[...new Set(c.flatMap(y=>y.points.map(b=>_t(b[0]))))].sort((y,b)=>y-b),d=[...new Set(c.flatMap(y=>y.points.map(b=>_t(b[1]))))].sort((y,b)=>y-b),p=d.slice(0,-1).map((y,b)=>u.slice(0,-1).map((v,w)=>{let x=[(u[w]+u[w+1])/2,(d[b]+d[b+1])/2];return l(c,x)&&!l(s,x)})),h=p.map(y=>y.map(()=>!1)),f=(y,b)=>p[b][y]&&!h[b][y],g=a.elevation+a.height;for(let y=0;yf(b+T,w+1)).every(Boolean);)w++;for(let F=y;F<=w;F++)for(let T=b;T<=v;T++)h[F][T]=!0;let[x,k]=[u[b]-r,u[v+1]+r],[$,A]=[d[y]-r,d[w+1]+r];Math.min(k-x,A-$)<.8||i.push({id:e(i.length),x0:_t(x),z0:_t($),x1:_t(k),z1:_t(A),shape:"gable",axis:k-x>=A-$?"x":"z",eave_a:_t(g),eave_b:_t(g),pitch_a:n,pitch_b:n,base:_t(g),overhang:null})}s.push(...c)}return i}var Se=Math.PI/180,Be=(t,e)=>[t[0]-e[0],t[1]-e[1],t[2]-e[2]],Xt=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],Rn=t=>Math.hypot(t[0],t[1],t[2]),Qt=t=>{let e=Rn(t)||1;return[t[0]/e,t[1]/e,t[2]/e]},Du=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]],We=t=>Math.round(t*100)/100,Mr=([t,e],n)=>(Math.atan2(t,-e)/Se-n+720)%360;var Hu=.25;function Lu(t,e,n,r,o,i,s){let l=o-n>=i-r,a=l?o-n:i-r;return{key:`${t}:top`,section:e,side:"top",flat:!0,o:[n,s,r],eu:l?[1,0,0]:[0,0,1],es:l?[0,0,1]:[1,0,0],n:[0,1,0],lu:a,ls:l?i-r:o-n,pitch:0,span:()=>[0,a],facing:l?[0,1]:[1,0]}}function Cu(t,e){let n=Qt(Du(t,e));return n[1]<0?[-n[0],-n[1],-n[2]]:n}var Nu=t=>{let e=Qt([-t[0],0,-t[2]]);return[e[0],e[2]]};function bt(t,e,n,r,o,i,s,l){let a=Qt(Be(o,r)),c=Qt(Be(i,r));return{key:t,section:e,side:n,flat:!1,o:r,eu:a,es:c,n:Cu(a,c),lu:Rn(Be(o,r)),ls:Rn(Be(i,r)),pitch:s,span:l,facing:Nu(c)}}function Ou(t,e,n,r,o,i){let s=Rn(Be(o,r));if(s<.3)return null;let l=Qt(Be(o,r)),a=Be(i,r),c=a[0]*l[0]+a[1]*l[1]+a[2]*l[2],u=[a[0]-l[0]*c,a[1]-l[1]*c,a[2]-l[2]*c],d=Rn(u);if(d<.3)return null;let p=Qt(u),h=f=>{let g=Math.min(1,Math.max(0,f/d));return[c*g,s-(s-c)*g]};return{key:t,section:e,side:n,flat:!1,o:r,eu:l,es:p,n:Cu(l,p),lu:s,ls:d,pitch:Math.atan2(p[1],Math.hypot(p[0],p[2]))/Se,span:h,facing:Nu(p)}}function q_(t,e){let n=ve(t),r=ze(t),o=(v,w,x)=>{let[k,$]=n.at(v,w);return[k,x,$]},[i,s]=[Math.max(0,e.a),Math.max(0,e.b)],l=n.u0-Math.max(0,e.u0),a=n.u1+Math.max(0,e.u1),c=a-l,u=r.y(-i),d=r.y(n.w+s);if(t.shape==="flat"||t.shape==="parapet"){let[v,w]=[n.at(l,-i),n.at(a,n.w+s)];return[Lu(t.id,t.id,Math.min(v[0],w[0]),Math.min(v[1],w[1]),Math.max(v[0],w[0]),Math.max(v[1],w[1]),t.eave_a+Hu)]}if(t.shape==="pent")return[bt(`${t.id}:a`,t.id,"a",o(l,-i,u),o(a,-i,u),o(l,n.w+s,d),t.pitch_a,()=>[0,c])];if(t.shape==="mansard")return Y_(t,n,l,a,i,s);let p=t.shape==="hip"||t.shape==="pyramid",h=(n.u1-n.u0)/2,f=t.shape==="pyramid"?h:p?Math.min(h,Math.min(r.vr,n.w-r.vr)||n.w/2):0,g=p?n.u0+f-l:0,y=p?a-(n.u1-f):0,b=[];if(r.vr>.3){let v=Math.hypot(r.vr+i,r.rh-u);b.push(bt(`${t.id}:a`,t.id,"a",o(l,-i,u),o(a,-i,u),o(l,r.vr,r.rh),t.pitch_a,w=>[g*(w/v),c-y*(w/v)]))}if(n.w-r.vr>.3){let v=Math.hypot(n.w+s-r.vr,r.rh-d);b.push(bt(`${t.id}:b`,t.id,"b",o(a,n.w+s,d),o(l,n.w+s,d),o(a,r.vr,r.rh),t.pitch_b,w=>[y*(w/v),c-g*(w/v)]))}if(p){let v=Ou(`${t.id}:c`,t.id,"c",o(l,n.w+s,d),o(l,-i,u),o(n.u0+f,r.vr,r.rh)),w=Ou(`${t.id}:d`,t.id,"d",o(a,-i,u),o(a,n.w+s,d),o(n.u1-f,r.vr,r.rh));b.push(...[v,w].filter(x=>x!==null))}return b}function Y_(t,e,n,r,o,i){let s=kr(e.w,t.eave_a,t.eave_b,nt(t.pitch_a),nt(t.pitch_b)),l=(f,g)=>{let[y,b]=e.at(f,g);return[y,s.y(g),b]},a=r-n,c=()=>[0,a],u=(f,g)=>Math.atan2(f,g)/Se,d=[],[p,h]=[e.w+i,e.w-s.vlb];return s.vla+o>.3&&d.push(bt(`${t.id}:a`,t.id,"a",l(n,-o),l(r,-o),l(n,s.vla),t.pitch_a,c)),s.vr-s.vla>.3&&d.push(bt(`${t.id}:au`,t.id,"a",l(n,s.vla),l(r,s.vla),l(n,s.vr),u(s.rh-s.yla,s.vr-s.vla),c)),s.vlb+i>.3&&d.push(bt(`${t.id}:b`,t.id,"b",l(r,p),l(n,p),l(r,h),t.pitch_b,c)),h-s.vr>.3&&d.push(bt(`${t.id}:bu`,t.id,"b",l(r,h),l(n,h),l(r,s.vr),u(s.rh-s.ylb,h-s.vr),c)),d}function Bs(t){return t.floors.filter(n=>n.rooms.some(r=>r.points.length>=3)).sort((n,r)=>r.elevation-n.elevation)[0]??null}function j(t){let e=t.settings.roof;if(!e||e.type==="none")return[];if(e.type==="custom")return(e.sections??[]).flatMap(w=>q_(w,$r(t,w,w.overhang??e.overhang)));let n=Bs(t);if(!n)return[];let r=n.rooms.flatMap(w=>w.points.map(x=>x[0])),o=n.rooms.flatMap(w=>w.points.map(x=>x[1])),i=t.settings.wall_exterior+e.overhang,[s,l]=[Math.min(...r)-i,Math.max(...r)+i],[a,c]=[Math.min(...o)-i,Math.max(...o)+i],u=n.elevation+n.height;if(e.type==="flat")return[Lu("main",null,s,a,l,c,u+Hu)];let d=l-s>=c-a,p=e.ridge==="short"?!d:d,h=(p?c-a:l-s)/2,f=h*Math.tan(e.pitch*Se),g=(w,x,k)=>p?[w,u+k,(a+c)/2+x]:[(s+l)/2+x,u+k,w],[y,b]=p?[s,l]:[a,c],v=()=>[0,b-y];return[bt("main:a",null,"a",g(y,-h,0),g(b,-h,0),g(y,0,f),e.pitch,v),bt("main:b",null,"b",g(y,h,0),g(b,h,0),g(y,0,f),e.pitch,v)]}function Ve(t,e){let n=[];for(let r of t.floors.filter(o=>!e||o.id===e)){let{walls:o}=fe(r.rooms,{exterior:t.settings.wall_exterior,interior:t.settings.wall_interior},r.walls??[]);for(let i of o){if(!i.exterior&&!i.free)continue;let[s,l]=[i.b[0]-i.a[0],i.b[1]-i.a[1]],a=Math.hypot(s,l);if(a<1.2)continue;let[c,u]=[l/a,-s/a],d=Math.min(r.height,i.height??r.height,i.heightEnd??1/0),p=(h,f,g,y)=>n.push({key:h,section:null,side:"top",flat:!1,o:f,eu:g,es:[0,1,0],n:y,lu:a,ls:d,pitch:90,span:()=>[0,a],facing:[y[0],y[2]],wall:{floorId:r.id}});p(`wall:${r.id}:${i.id}`,[i.a[0]+c*i.right,r.elevation,i.a[1]+u*i.right],[s/a,0,l/a],[c,0,u]),i.free&&p(`wall:${r.id}:${i.id}:back`,[i.b[0]-c*i.left,r.elevation,i.b[1]-u*i.left],[-s/a,0,-l/a],[-c,0,-u])}}return n}var Ie="ground";function Zo(t){let e=t.floors.filter(n=>n.rooms.some(r=>r.points.length>=3)).sort((n,r)=>n.elevation-r.elevation);return e.find(n=>n.elevation>-.5)??e[0]??t.floors[0]??null}function qo(t,e){let n=(e.rotation??0)*Se,r=[Math.cos(n),0,Math.sin(n)],o=[-Math.sin(n),0,Math.cos(n)],i=Zo(t),s=r[0]*e.u+o[0]*e.v,l=r[2]*e.u+o[2]*e.v,a=i?i.elevation+(e.base!=null?e.base:zc(i,s,l)):e.base??0;return{key:Ie,section:null,side:"top",flat:!0,o:[0,a,0],eu:r,es:o,n:[0,1,0],lu:1e4,ls:1e4,pitch:0,span:()=>[-1e4,1e4],facing:[o[0],o[2]],unbounded:!0}}function ke(t,e,n=j(t)){return e.face===Ie?qo(t,e):e.face.startsWith("wall:")?Ve(t,e.face.split(":")[1]).find(r=>r.key===e.face)??null:n.find(r=>r.key===e.face)??null}var Yo=1.13,Er=1.72,Ke=.025,rt=.07;function Jt(t){let e=t.module_w||Yo,n=t.module_h||Er;return t.portrait===!1?[n,e]:[e,n]}function Ar(t){return t.layout?.length?t.layout.map(e=>Math.max(0,Math.min(60,Math.round(e)))):Array.from({length:Math.max(1,t.rows)},()=>Math.max(1,t.cols))}function Ws(t,e){return t.flat?Math.min(45,Math.max(0,e.tilt??15))*Se:t.wall?Math.min(90,Math.max(0,e.tilt??0))*Se:Math.min(45,Math.max(0,e.tilt??0))*Se}function Fr(t,e){let[,n]=Jt(e),r=Ws(t,e);return t.wall?n*Math.cos(r)+Ke:!t.flat&&r<.001?n+Ke:t.flat&&e.rack==="ew"?n*Math.cos(r)+.08:n*Math.cos(r)+Math.max(.3,2*n*Math.sin(r))}function En(t,e){let[n,r]=Jt(e),o=Ar(e),i=Math.max(1,...o);return[i*n+(i-1)*Ke,(o.length-1)*Fr(t,e)+r*Math.cos(Ws(t,e))]}var X_=t=>t.flat&&!t.unbounded&&!t.wall;function Bu(t,e){if(!X_(t)||!e.rotation)return null;let n=e.rotation*Se,[r,o]=En(t,e);return{cos:Math.cos(n),sin:Math.sin(n),u:e.u+r/2,s:e.v+o/2}}function Ge(t,e,n=!1){let[r,o]=Jt(e),i=Ws(t,e),s=o*Math.cos(i),l=Fr(t,e),a=Ar(e),c=Math.max(1,...a),u=new Set(e.skip??[]),d=Bu(t,e),p=(y,b)=>d?[d.u+(y-d.u)*d.cos-(b-d.s)*d.sin,d.s+(y-d.u)*d.sin+(b-d.s)*d.cos]:[y,b],h=(y,b,v)=>{let[w,x]=p(y,b);return[0,1,2].map(k=>t.o[k]+t.eu[k]*w+t.es[k]*x+t.n[k]*v)},f=(y,b)=>{let[v,w]=p(y,b);if(t.unbounded)return!0;if(w<-1e-6||w>t.ls+1e-6)return!1;let[x,k]=t.span(w);return v>=x-1e-6&&v<=k+1e-6},g=[];return a.forEach((y,b)=>{let v=e.align==="right"?c-y:e.align==="center"?(c-y)/2:0;for(let w=0;w.001?s:o);if([[$,F],[A,F],[A,T],[$,T]].every(([I,z])=>f(I,z)))if(t.wall&&i>.001){let I=rt+o*Math.sin(i),[z,C]=e.flip?[I,rt]:[rt,I],B=[h($,F,z),h(A,F,z),h(A,T,C),h($,T,C)],q=e.flip?F:T;g.push({corners:B,posts:[$+.05,A-.05].map(ye=>[h(ye,q,0),h(ye,q,I)]),cell:x,skipped:k})}else if(!t.flat&&i>.001){let I=rt+o*Math.sin(i),z=[h($,F,rt),h(A,F,rt),h(A,T,I),h($,T,I)];g.push({corners:z,posts:[$+.05,A-.05].map(C=>[h(C,T,0),h(C,T,I)]),cell:x,skipped:k})}else if(!t.flat)g.push({corners:[h($,F,rt),h(A,F,rt),h(A,T,rt),h($,T,rt)],posts:[],cell:x,skipped:k});else{let z=.15+o*Math.sin(i),C=e.rack==="ew"&&b%2===1?!e.flip:!!e.flip,[B,q]=C?[T,F]:[F,T],ye=[h($,B,.15),h(A,B,.15),h(A,q,z),h($,q,z)],$t=[$+.05,A-.05].flatMap(V=>[[h(V,B,0),h(V,B,.15)],[h(V,q,0),h(V,q,z)]]);g.push({corners:ye,posts:$t,cell:x,skipped:k})}}}),g}function ct(t,e){if(t.unbounded)return{u:e.u,v:e.v};let[n,r]=En(t,e),o=Bu(t,e);if(o){let[s,l]=[(n*Math.abs(o.cos)+r*Math.abs(o.sin))/2,(n*Math.abs(o.sin)+r*Math.abs(o.cos))/2],a=(d,p,h)=>Math.floor(Math.max(p,Math.min(d,h-p))*100+1e-6)/100,[c,u]=[e.u+n/2,e.v+r/2];return{u:Math.round((a(c,s,t.lu)-n/2)*100)/100,v:Math.round((a(u,l,t.ls)-r/2)*100)/100}}let i=s=>Math.floor(s*100+1e-6)/100;return{u:i(Math.min(Math.max(0,e.u),Math.max(0,t.lu-n))),v:i(Math.min(Math.max(0,e.v),Math.max(0,t.ls-r)))}}function Tr(t,e){let[n,r]=En(t,e),[o,i]=[e.u+n/2,e.v+r/2];return[t.o[0]+t.eu[0]*o+t.es[0]*i,t.o[2]+t.eu[2]*o+t.es[2]*i]}var Xo=.78,zr=1.18,en=t=>({id:t.id,face:t.face,u:t.u,v:t.v,rows:1,cols:1,portrait:!0,module_w:t.w||Xo,module_h:t.h||zr});function Vs(t,e){let n=Ge(t,en(e))[0];if(!n)return null;let r=o=>[o[0]-t.n[0]*.05,o[1]-t.n[1]*.05,o[2]-t.n[2]*.05];return n.corners.map(r)}var Rr={brick:{w:.5,d:.5,h:1},round:{w:.4,d:.4,h:1},wide:{w:1,d:.5,h:1},steel:{w:.2,d:.2,h:1.2}};function tn(t){let e=t.shape??"brick",n=Rr[e]??Rr.brick;return{shape:e,w:t.w||n.w,d:t.d||n.d,h:t.h||n.h}}function yt(t,e){let{w:n,d:r}=tn(t),o=e&&!e.flat?Math.cos(e.pitch*Se):1;return{id:t.id,face:t.face,u:t.u,v:t.v,rows:1,cols:1,portrait:!0,module_w:n,module_h:r/Math.max(.2,o),tilt:0}}function Ks(t,e){let n=yt(e,t),[r,o]=[n.module_w,n.module_h],i=(u,d)=>[t.o[0]+t.eu[0]*u+t.es[0]*d,t.o[1]+t.eu[1]*u+t.es[1]*d,t.o[2]+t.eu[2]*u+t.es[2]*d],[s,l]=[i(e.u+r/2,e.v),i(e.u+r/2,e.v+o)],a=i(e.u+r/2,e.v+o/2),c=u=>{let d=Math.hypot(u[0],u[2])||1;return[u[0]/d,u[2]/d]};return{center:[a[0],a[2]],along:c(t.eu),across:c(t.es),low:Math.min(s[1],l[1]),high:Math.max(s[1],l[1])}}function Gs(t,e){let[n]=Jt(e);return We((t.lu-(e.cols*n+(e.cols-1)*Ke))/2)}var Pr=.4;function An(t,e){let n={id:e,face:t.key,u:0,v:0,rows:1,cols:1,portrait:!0,tilt:t.flat?15:null,flip:!1,entity:null,look:"black"},[r]=Jt(n),[o,i]=t.span(t.ls/2);for(n.cols=Math.max(1,Math.floor((i-o-2*Pr+Ke)/(r+Ke))),n.rows=Math.max(1,Math.min(4,Math.floor((t.ls-2*Pr)/Fr(t,n))));n.cols>1&&Ge(t,{...n,u:Gs(t,n),v:Pr}).lengthl.lu*(1.3+Math.cos((Mr(l.facing,r)-180)*Math.PI/180)),i=Ve(t,n).sort((l,a)=>o(a)-o(l))[0];if(!i)return null;let s={...An(i,e),portrait:!1,rows:1};return s.cols=Math.max(1,Math.floor((i.lu-.8+Ke)/(Er+Ke))),s.u=We((i.lu-(s.cols*Er+(s.cols-1)*Ke))/2),s.v=We(Math.max(0,i.ls-Yo-.3)),s}function Ir(t,e){let n=t.floors.flatMap(i=>i.rooms.flatMap(s=>s.points)),r=n.length?Math.max(...n.map(i=>i[0]))+3:0,o=n.length?Math.min(...n.map(i=>i[1])):0;return{id:e,face:Ie,u:We(r),v:We(o),rows:2,cols:4,portrait:!0,tilt:25,flip:!0,rotation:(t.settings.north??0)||0,look:"black",entity:null}}function Dr(t,e,n){let r=qo(t,e),[o,i]=En(r,e),[s,l]=[e.u+o/2,e.v+i/2],a=[r.eu[0]*s+r.es[0]*l,r.eu[2]*s+r.es[2]*l],c=n*Se,u=a[0]*Math.cos(c)+a[1]*Math.sin(c)-o/2,d=a[0]*-Math.sin(c)+a[1]*Math.cos(c)-i/2;return{u:We(u),v:We(d),rotation:(Math.round(n)%360+360)%360}}function Or(t,e){let[n,r]=t.span(t.ls/2);return{id:e,face:t.key,u:We((n+r-Xo)/2),v:We(Math.max(0,Math.min(t.ls-zr,t.ls*.45-zr/2))),w:null,h:null,cover:null,contact:null,tilt:null}}function Hr(t,e){let n=Rr.brick,[r,o]=t.span(t.ls*.8),i=yt({id:e,face:t.key,u:0,v:0},t).module_h;return{id:e,face:t.key,u:We((r+o-n.w)/2),v:We(Math.max(0,Math.min(t.ls-i,t.ls*.8-i/2))),shape:"brick",w:null,d:null,h:null}}function Fn(t,e){let[n,r]=[e[0]-t.o[0],e[1]-t.o[2]],[o,i,s,l]=[t.eu[0],t.eu[2],t.es[0],t.es[2]],a=o*l-i*s;if(Math.abs(a)<1e-9)return null;let c=(n*l-r*s)/a,u=(o*r-i*n)/a;if(u<0||u>t.ls)return null;let[d,p]=t.span(u);return c>=d&&c<=p?{u:c,s:u}:null}function js(t,e){let n=null;for(let r of t){if(r.wall){let[s,l]=[e[0]-r.o[0],e[1]-r.o[2]],a=s*r.eu[0]+l*r.eu[2],c=s*r.n[0]+l*r.n[2],u=a>=0&&a<=r.lu;if(u&&c>=-.05&&c<=.35)return{face:r,u:a,s:Number.NaN};u&&c>.35&&c<=.8&&!n&&(n={face:r,u:a,s:Number.NaN,y:-1/0});continue}let o=Fn(r,e);if(!o)continue;let i=r.o[1]+r.es[1]*o.s;(!n||i>n.y)&&(n={face:r,...o,y:i})}return n&&{face:n.face,u:n.u,s:n.s}}function Jo(t,e,n){let r=Xt(n,t.n);if(Math.abs(r)<1e-6)return null;let o=Xt(Be(t.o,e),t.n)/r;if(o<=0)return null;let i=Be([e[0]+n[0]*o,e[1]+n[1]*o,e[2]+n[2]*o],t.o);return{t:o,u:Xt(i,t.eu),s:Xt(i,t.es)}}function Zs(t,e,n){if(t.unbounded)return!0;if(n<0||n>t.ls)return!1;let[r,o]=t.span(n);return e>=r&&e<=o}function qs(t,e,n,r){return Ge(t,e).some(i=>{let s=i.corners.map(c=>{let u=Be(c,t.o);return[Xt(u,t.eu),Xt(u,t.es)]}),l=s.map(c=>c[0]),a=s.map(c=>c[1]);return n>=Math.min(...l)-.05&&n<=Math.max(...l)+.05&&r>=Math.min(...a)-.05&&r<=Math.max(...a)+.05})}var Q_=["n","ne","e","se","s","sw","w","nw"],Ys=(t,e)=>Q_[Math.round(Mr(t.facing,e)/45)%8];function Lr(t,e){let n=r=>{if(r.flat)return r.lu*r.ls*.8;let o=Math.cos((Mr(r.facing,e)-180)*Math.PI/180);return r.lu*r.ls*(1.2+o)};return[...t].sort((r,o)=>n(o)-n(r))[0]??null}var Gu=["kitchen_row","kitchen_l","bath","bedroom","living","dining","office","kids","hall"],Wu={kitchen_row:{rows:[["back","start",["fridge","kitchen_tall",["kitchen",[.9,.62,.92]],"sink","dishwasher","stove",["kitchen",[.6,.62,.92]]]],["back","start",[["kitchen_wall",[1.2,.35,.7]]]]],spots:[[["table",[1.2,.8,.75]],.5,.72,0],["lamp_pendant",.5,.72,0],["lamp_ceiling",.5,.3,0]]},kitchen_l:{rows:[["back","start",["fridge",["kitchen",[.9,.62,.92]],"sink","dishwasher","stove"]],["right","start",[["kitchen",[.9,.62,.92]],["kitchen",[.6,.62,.92]],"kitchen_tall"]],["back","start",[["kitchen_wall",[1.2,.35,.7]]]]],spots:[["table",.4,.68,0],["bar_stool",.72,.86,180],["lamp_ceiling",.5,.35,0]]},bath:{rows:[["back","center",["washbasin"]],["back","end",["wc"]],["front","start",["bathtub"]],["left","start",["washer"]]],spots:[["lamp_downlight",.5,.5,0]]},bedroom:{rows:[["back","center",["nightstand","bed","nightstand"]],["left","center",[["wardrobe",[2,.6,2.1]]]],["front","end",["dresser"]]],spots:[["lamp_ceiling",.5,.55,0]]},living:{rows:[["back","center",["tv_board"]],["right","start",["shelf"]]],spots:[["sofa",.5,.72,180],["coffee_table",.5,.52,0],[["rug",[2.2,1.6,.01]],.5,.55,0],["armchair",.14,.5,270],["lamp_floor",.86,.8,0],["plant",.9,.12,0],["lamp_ceiling",.5,.45,0]]},dining:{rows:[["back","center",["sideboard"]]],spots:[["table",.5,.55,0],["chair",.4,.35,0],["chair",.6,.35,0],["chair",.4,.75,180],["chair",.6,.75,180],["lamp_pendant",.5,.55,0]]},office:{rows:[["back","center",["desk"]],["left","center",["shelf","shelf"]]],spots:[["office_chair",.5,.38,180],["lamp_ceiling",.5,.55,0]]},kids:{rows:[["left","start",[["bed",[.9,2,.8]]]],["back","end",[["desk",[1.2,.6,.75]]]],["right","end",["shelf"]]],spots:[[["rug",[1.6,1.2,.01]],.55,.6,0],["lamp_ceiling",.5,.5,0]]},hall:{rows:[["left","start",["coat_rack"]]],spots:[["lamp_downlight",.5,.3,0],["lamp_downlight",.5,.7,0]]}},Vu=t=>typeof t=="string"?t:t[0],ei=t=>typeof t=="string"?Je[t]:t[1],Tn=.05,J_=.02,Ku=t=>Math.round(t*1e3)/1e3;function eb(t,e,n,r){switch(e){case"back":return{x:t.x0+n,z:t.z0+r,turn:0};case"right":return{x:t.x1-r,z:t.z0+n,turn:90};case"front":return{x:t.x1-n,z:t.z1-r,turn:180};case"left":return{x:t.x0+r,z:t.z1-n,turn:270}}}function Uu(t,e,n){let r=ue(t.points),o=r.x1-r.x0,i=r.z1-r.z0,s=[],l=(a,c,u,d,[p,h,f])=>{s.push({id:n(),type:a,x:Ku(c),z:Ku(u),rotation:d,w:p,d:h,h:f,variant:null,entity:null,power:null})};for(let[a,c,u]of Wu[e].rows){let d=a==="back"||a==="front"?o:i,p=0,h=[];for(let g of u){if(p+ei(g)[0]>d-.1)break;h.push(g),p+=ei(g)[0]}let f=c==="start"?Tn:c==="end"?d-p-Tn:(d-p)/2;for(let g of h){let y=ei(g),b=eb(r,a,f+y[0]/2,y[1]/2+J_);l(Vu(g),b.x,b.z,b.turn,y),f+=y[0]}}for(let[a,c,u,d]of Wu[e].spots){let p=ei(a),h=(y,b,v)=>Math.min(v,Math.max(b,y)),f=h(r.x0+o*c,r.x0+p[0]/2+Tn,r.x1-p[0]/2-Tn),g=h(r.z0+i*u,r.z0+p[1]/2+Tn,r.z1-p[1]/2-Tn);l(Vu(a),f,g,d,p)}return s}var tb=30*Math.PI/180,ju=.05;function Xs(t){let e=t.points.length;return t.points.map((n,r)=>{let o=t.points[(r+1)%e];return Math.hypot(o[0]-n[0],o[1]-n[1])})}function Cr(t){return Xs(t).reduce((e,n)=>e+n,0)}function nb(t,e){let n=Xs(t),r=0;for(let o=0;oh+f,0);if(o<3||!(i>0)||!(n>0))return null;let s=Math.min(n,i),l=(e%i+i)%i,a=0,c=0;for(;a=c+r[a];)c+=r[a],a++;let u=l-c,d=s,p=[];for(let h=0;h<=o&&d>1e-9;h++){let f=r[a]-u,g=Math.min(d,f);g>1e-9&&p.push({edge:a,t0:u,t1:u+g}),d-=g,u=0;let y=(a+1)%o;if(d>1e-9&&rb(t,a)>tb)break;a=y}for(;p.length>1&&p[0].t1-p[0].t01&&p[p.length-1].t1-p[p.length-1].t0({edge:h.edge,offset:(h.t0+h.t1)/2,width:h.t1-h.t0})):null}function zn(t,e){let n=e[0];return n?{from:nb(t,n.edge)+n.offset-n.width/2,width:e.reduce((r,o)=>r+o.width,0)}:null}function It(t,e){return e.front?t.filter(n=>n.front===e.front):[e]}function Js(t,e){let n=t.points.length,r=1/0,o=0,i=0;for(let s=0;sD("opening")){let s=Qs(e,r,o);if(!s)return null;let l=It(t,n),a=new Set(l.map(h=>h.id)),c=s.length>1?l[0].front??`front-${l[0].id}`:null,u=s.map((h,f)=>({...n,id:f===0?l[0].id:i(),edge:h.edge,offset:h.offset,width:h.width,front:c})),d=[],p=!1;for(let h of t){if(!a.has(h.id)){d.push(h);continue}p||(d.push(...u),p=!0)}return d}var na=globalThis,ea=na.__nextfloorBuiltin?.de??{},ta=na.__nextfloorBuiltin?.en??{};na.__nextfloorBuiltin??={de:ea,en:ta};var ob=()=>typeof S=="object"&&S||{},ib=globalThis,sb=ib.__nextfloorTexts??=new Map;function ab(t){let e=t.toLowerCase().split("-")[0];return e!=="de"&&e!=="en"&&e in ob()?e:void 0}function Zu(t){let e=ab(t),n=e===void 0?void 0:sb.get(e);return n instanceof Promise?void 0:n}function ti(t,e){return Zu(t)?.[e]}function xe(t,e,n={}){let r=t?.language??navigator.language,o=r.startsWith("de"),i=(o?void 0:Zu(r)?.[e])??(o?ea:ta)[e]??ta[e]??ea[e]??e;for(let[s,l]of Object.entries(n))i=i.replace(`{${s}}`,String(l));return i}function U(t,e,n=2){return e.toLocaleString(t?.language??void 0,{maximumFractionDigits:n})}var Ue=le` + :host { + --nf-text: var(--primary-text-color, #e1e1e1); + --nf-muted: var(--secondary-text-color, #9b9b9b); + --nf-accent: var(--primary-color, #03a9f4); + --nf-accent-text: var(--text-primary-color, #ffffff); + --nf-surface: var(--ha-card-background, var(--card-background-color, #1c1c1c)); + --nf-bg: var(--primary-background-color, #111111); + --nf-bg2: var(--secondary-background-color, #1c1c1c); + /* floating bars and cards over the 3D view: the card colour, a little see-through */ + --nf-chrome: color-mix(in srgb, var(--nf-surface) var(--nf-chrome-mix, 84%), transparent); + --nf-chrome-solid: var(--nf-surface); + --nf-line: var(--divider-color, rgba(255, 255, 255, 0.12)); + /* quiet fills for buttons and fields, and the tonal accent of an active control */ + --nf-fill: color-mix(in srgb, var(--nf-text) 7%, transparent); + --nf-fill-strong: color-mix(in srgb, var(--nf-text) 13%, transparent); + --nf-tonal: color-mix(in srgb, var(--nf-accent) 20%, transparent); + --nf-soft: var(--info-color, #4a90e2); + --nf-warm: var(--state-light-active-color, #ffa726); + --nf-danger: var(--error-color, #db4437); + --nf-good: var(--success-color, #43a047); + --nf-radius: var(--ha-card-border-radius, 12px); + --nf-shadow: var(--ha-card-box-shadow, 0 1px 2px rgba(0, 0, 0, 0.18), 0 6px 20px rgba(0, 0, 0, 0.2)); + --nf-font: var(--primary-font-family, Roboto, "Noto Sans", system-ui, -apple-system, "Segoe UI", sans-serif); + --nf-title-font: var(--nf-font); + font-family: var(--nf-font); + color: var(--nf-text); + } +`,m$=le` + :host([readable]) { + --secondary-text-color: var(--primary-text-color, #e1e1e1); + --divider-color: color-mix(in srgb, var(--primary-text-color, #e1e1e1) 40%, transparent); + --nf-chrome-mix: 97%; + } + :host([readable]) nf-room-panel, + :host([readable]) .nf-nav, + :host([readable]) .nf-overlay { + zoom: 1.2; + } +`,ut=le` + /* a group of switches: one rounded pill, the active one tinted with the accent */ + .nf-seg { + display: inline-flex; + padding: 4px; + gap: 2px; + border-radius: 999px; + background: var(--nf-chrome); + box-shadow: var(--nf-shadow); + backdrop-filter: blur(10px); + } + .nf-seg button, + .nf-chip { + font: inherit; + font-size: 14px; + font-weight: 500; + border: none; + background: none; + color: var(--nf-muted); + padding: 7px 14px; + border-radius: 999px; + cursor: pointer; + white-space: nowrap; + min-height: 36px; + transition: + background 0.15s, + color 0.15s; + } + .nf-seg button:hover:not(:disabled), + .nf-chip:hover { + background: var(--nf-fill); + color: var(--nf-text); + } + /* on a small stage (a small window, a zoomed browser, a dashboard column) the switches at the bottom take less room */ + @container nf ((max-width: 1360px) or (max-height: 640px)) { + :is(.nf-overlay, .nf-card-controls) .nf-seg { + padding: 3px; + } + :is(.nf-overlay, .nf-card-controls) :is(.nf-seg button, .nf-chip) { + font-size: 12.5px; + padding: 5px 10px; + } + } + .nf-time-slider { + display: inline-flex; + align-items: center; + padding: 4px 10px; + } + .nf-time-slider input { + width: 160px; + accent-color: var(--nf-accent); + } + .nf-seg button[aria-pressed="true"], + .nf-chip[aria-pressed="true"] { + background: color-mix(in srgb, var(--nf-accent) 24%, var(--nf-chrome-solid)); + color: var(--nf-accent); + font-weight: 600; + } + .nf-seg button:disabled { + opacity: 0.4; + cursor: default; + } + /* a single pill, like the chips of the Mushroom cards */ + .nf-chip { + background: var(--nf-chrome); + color: var(--nf-text); + box-shadow: var(--nf-shadow); + backdrop-filter: blur(10px); + } + + button:focus-visible, + input:focus-visible, + select:focus-visible { + outline: 2px solid var(--nf-accent); + outline-offset: 2px; + } + /* the round icon badge every row and card starts with */ + .nf-ico { + display: inline-flex; + align-items: center; + justify-content: center; + flex: none; + width: 38px; + height: 38px; + border-radius: 50%; + background: var(--nf-tonal); + color: var(--nf-accent); + --mdc-icon-size: 20px; + } + .nf-ico.nf-warm { + background: color-mix(in srgb, var(--nf-warm) 22%, transparent); + color: var(--nf-warm); + } + .nf-ico.nf-off { + background: var(--nf-fill); + color: var(--nf-muted); + } + .nf-btn { + font: inherit; + font-size: 14px; + font-weight: 500; + border: none; + background: var(--nf-fill); + color: var(--nf-text); + border-radius: var(--nf-radius); + padding: 7px 14px; + cursor: pointer; + min-height: 36px; + transition: background 0.15s; + } + .nf-btn:hover { + background: var(--nf-fill-strong); + } + .nf-btn.nf-danger { + color: var(--nf-danger); + } + .nf-btn.nf-primary { + background: var(--nf-accent); + color: var(--nf-accent-text); + } + .nf-btn.nf-primary:hover { + background: color-mix(in srgb, var(--nf-accent) 88%, var(--nf-text)); + } + .nf-field { + display: grid; + gap: 4px; + font-size: 12px; + color: var(--nf-muted); + } + .nf-field input, + .nf-field select, + .nf-field textarea { + font: inherit; + font-size: 14px; + color: var(--nf-text); + background: var(--nf-fill); + border: none; + border-bottom: 1px solid var(--nf-line); + border-radius: 10px 10px 4px 4px; + padding: 8px 10px; + min-width: 0; + } + .nf-field input:focus, + .nf-field select:focus, + .nf-field textarea:focus { + border-bottom-color: var(--nf-accent); + } + .nf-field input[type="range"] { + padding: 0; + accent-color: var(--nf-accent); + } + .nf-field select option { + background: var(--nf-chrome-solid); + color: var(--nf-text); + } + /* fingers need 40 px */ + @media (pointer: coarse) { + .nf-seg button, + .nf-chip, + .nf-btn { + min-height: 40px; + } + } +`;var he=t=>/^(sensor|input_number|number)\./.test(t),ni=t=>/^(binary_sensor|input_boolean)\./.test(t);function Pn(t,e){if(!he(e))return!1;let n=t?.states[e]?.attributes;return n?.device_class==="power"||n?.unit_of_measurement==="W"||n?.unit_of_measurement==="kW"}function lb(t,e){let n=t?.entities?.[e],r=n?.area_id??(n?.device_id?t?.devices?.[n.device_id]?.area_id:null);return r?t?.areas?.[r]?.name:void 0}function L(t,e){return Object.keys(t?.states??{}).filter(e).map(n=>{let r=lb(t,n),o=t?.states[n],i=typeof o?.attributes.symcon_path=="string"?o.attributes.symcon_path:void 0,s={id:n,label:r?`${W(t,n)} \xB7 ${r}`:W(t,n)};return i&&(s.detail=`Objektbaum: ${i}`),s}).sort((n,r)=>n.label.localeCompare(r.label))}function ri(t,e){return t.power&&t.power!=="none"?t.power:e.get(t.id)?.power??null}var oi={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Br=t=>(...e)=>({_$litDirective$:t,values:e}),In=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,n,r){this._$Ct=e,this._$AM=n,this._$Ci=r}_$AS(e,n){return this.update(e,n)}update(e,n){return this.render(...n)}};var Wr=class extends In{constructor(e){if(super(e),this.it=_,e.type!==oi.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===_||e==null)return this._t=void 0,this.it=e;if(e===mt)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;let n=[e];return n.raw=n,this._t={_$litType$:this.constructor.resultType,strings:n,values:[]}}};Wr.directiveName="unsafeHTML",Wr.resultType=1;var qu=Br(Wr);var Yu=40,ra=class extends oe{static properties={options:{attribute:!1},fixed:{attribute:!1},value:{attribute:!1},disabled:{type:Boolean},placeholder:{attribute:!1},_query:{state:!0},_open:{state:!0},_cursor:{state:!0}};blurTimer;constructor(){super(),this.options=[],this.fixed=[],this.value=null,this.disabled=!1,this.placeholder="",this._query="",this._open=!1,this._cursor=0}get current(){return[...this.fixed,...this.options].find(e=>e.id===this.value)}get hits(){let e=this._query.trim().toLowerCase(),n=e.split(/\s+/).filter(Boolean),r=s=>{let l=`${s.label} ${s.detail??s.id}`.toLowerCase();return n.every(a=>l.includes(a))},o=this.fixed.filter(s=>!e||r(s)),i=e?this.options.filter(r):this.options;return[...o,...i.slice(0,Yu)]}get leftOut(){let e=this._query.trim().toLowerCase(),n=e.split(/\s+/).filter(Boolean),r=e?this.options.filter(o=>n.every(i=>`${o.label} ${o.detail??o.id}`.toLowerCase().includes(i))).length:this.options.length;return Math.max(0,r-Yu)}choose(e){this.value=e,this._query="",this._open=!1,this.dispatchEvent(new CustomEvent("change",{detail:{value:e},bubbles:!0,composed:!0}))}onKey(e){let n=this.hits;e.key==="ArrowDown"?(this._open=!0,this._cursor=Math.min(n.length-1,this._cursor+1),e.preventDefault()):e.key==="ArrowUp"?(this._cursor=Math.max(0,this._cursor-1),e.preventDefault()):e.key==="Enter"?(this._open&&n[this._cursor]&&this.choose(n[this._cursor].id),e.preventDefault()):e.key==="Escape"&&(this._open=!1,this._query="")}render(){let e=this.current,n=this._open?this.hits:[];return m`
+ {clearTimeout(this.blurTimer),this._open=!0,this._query="",this._cursor=0}} + @blur=${()=>{this.blurTimer=setTimeout(()=>this._open=!1,150)}} + @input=${r=>{this._query=r.target.value,this._cursor=0,this._open=!0}} + @keydown=${this.onKey} + /> + ${this._open?m`
    + ${n.length?_:m`
  • –
  • `} + ${n.map((r,o)=>m`
  • i.preventDefault()} + @click=${()=>this.choose(r.id)} + > + ${r.label}${r.detail||r.id.includes(".")?m`${r.detail??r.id}`:_} +
  • `)} + ${this.leftOut>0?m`
  • … +${this.leftOut} · ${this.placeholder}
  • `:_} +
`:_} +
`}static styles=[Ue,le` + :host { + display: block; + position: relative; + } + input { + width: 100%; + box-sizing: border-box; + font: inherit; + color: var(--nf-text); + background: var(--nf-chrome-solid); + border: 1px solid var(--nf-line); + border-radius: 10px; + padding: 8px 10px; + } + input::placeholder { + color: var(--nf-text); + opacity: 0.9; + } + input:focus::placeholder { + color: var(--nf-muted); + } + input:focus { + outline: 2px solid var(--nf-accent); + outline-offset: -1px; + } + .list { + position: absolute; + left: 0; + right: 0; + top: calc(100% + 4px); + z-index: 20; + margin: 0; + padding: 4px; + list-style: none; + max-height: 280px; + overflow-y: auto; + background: var(--nf-chrome-solid); + border: 1px solid var(--nf-line); + border-radius: 10px; + box-shadow: var(--nf-shadow); + } + li { + display: flex; + flex-direction: column; + gap: 1px; + padding: 6px 8px; + border-radius: 6px; + cursor: pointer; + font-size: 13.5px; + } + li small { + color: var(--nf-muted); + font-size: 11px; + } + li.cursor, + li:hover { + background: color-mix(in srgb, var(--nf-accent) 18%, transparent); + } + li.chosen { + color: var(--nf-accent); + } + li.empty { + color: var(--nf-muted); + cursor: default; + } + `]};customElements.get("nf-entity-picker")||customElements.define("nf-entity-picker",ra);var nn=t=>t.target.value,oa=t=>Number.parseFloat(t.replace(",",".")),ie=t=>Math.round(t*1e3)/1e3,Xu=t=>t.wide?"nf-field nf-wide":"nf-field";function E(t,e,n,r,o=.01,i){return m``}function Z(t,e,n,r,o={}){return m``}function O(t,e,n,r,o,i={}){return m``}function H(t,e,n,r,o={}){return m``}function je(t,e,n,r,o){return m``}function P(t,e,n,r,o,i){let s=r===void 0?null:r?t.t("entity_auto",{name:W(t.hass,r)}):t.t("entity_auto_none"),l=[...s!==null?[{id:"__auto",label:s}]:[],{id:"none",label:t.t("entity_none")}];return m``}function Dn(t,e,n){return n?(n.startsWith("mdi:")?n:`mdi:${n}`).replace(/[^a-z0-9:-]/gi,""):t.hass?Xc(t.hass,e):null}function Dt(t,e,n){let r=e?(e.startsWith("mdi:")?e:`mdi:${e}`).replace(/[^a-z0-9:-]/gi,""):"";return m``}function On(t,e,n){return m``}function Hn(t,e,n){let r=e??{},o=i=>s=>{let l={...r,[i]:Math.round(Math.max(-5,Math.min(5,s))*100)/100};n(l.x||l.z||l.y?l:null)};return m`
+ ${t.t("pin_shift")} +
+ ${E(t,"\u2194 x",r.x??0,o("x"),.05)} ${E(t,"\u2195 z",r.z??0,o("z"),.05)} ${E(t,t.t("pin_shift_up"),r.y??0,o("y"),.05)} + ${e?m``:_} +

${t.t("pin_shift_hint")}

+
+
`}var Y=(...t)=>m`
${t}
`,M=(t,e="")=>m`

${t}

`;function rn(t,e,n,r={}){let o=r.lowest??10;return m``}function Qu(t,e,n){let r=t.find(a=>a.person===e),o="sensor"in n?n.sensor&&n.sensor!=="none"?n.sensor:null:r?.sensor??null,i="room"in n?n.room||null:r?.room??null,s=t.filter(a=>a.person!==e);if(!o&&!i)return s;let l=i?{person:e,sensor:o,room:i}:{person:e,sensor:o};return r?t.map(a=>a.person===e?l:a):[...s,l]}function Ju(t,e){let n=e.slice(e.indexOf(".")+1),r=o=>o.id.includes(n)&&/(area|room|raum|bermuda|espresense)/.test(o.id);return[...t.filter(r),...t.filter(o=>!r(o))]}function ed(t){let e=t.target?`, target: { x: ${t.target.x}, y: ${t.target.y}, z: ${t.target.z} }`:"";return`start_view: { theta: ${t.theta}, phi: ${t.phi}, radius: ${t.radius}${e} }`}function td(t){let e=t.trim();if(!e)return{ok:!0,value:null};try{let n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}function ii(t,e,n){let r=[...t],[o]=r.splice(e,1);return r.splice(Math.max(0,Math.min(r.length,e+n)),0,o),r}var Ot=(t,e)=>t.filter((n,r)=>r!==e),Vr=(t,e,n)=>t.map((r,o)=>o===e?{...r,...n}:r),dt=t=>t.length>0?t:void 0;var cb=["scene","script","automation","button","input_button","switch","input_boolean","light","fan","cover","lock"],ub=40,db=20,hb=30,pb=["music","url","playlist","SPOTIFY","AMAZON_MUSIC","TUNEIN","APPLE_MUSIC"],ia={navigate:"/lovelace/rollos",more_info:"cover.wohnzimmer",service:"script.turn_on",fire_dom_event:""},Kr=(t,e,n,r=!1)=>m``;function fb(t){let e=t.doc.settings.favorites??[],n=l=>t.change(a=>a.settings.favorites=dt(l)),r=t.doc.floors,o=t.doc.settings.favorite_floors??{},i=L(t.hass,l=>cb.includes(l.split(".")[0])&&!e.includes(l)),s=(l,a)=>m`
+ ${W(t.hass,l)} + ${r.length>1?m``:_} + ${Kr(t.t("move_up"),"\u2191",()=>n(ii(e,a,-1)),a===0)} + ${Kr(t.t("move_down"),"\u2193",()=>n(ii(e,a,1)),a===e.length-1)} + ${Kr(t.t("delete"),"\u2715",()=>n(Ot(e,a)))} +
`;return m`${t.t("favorites")}${e.length>0?m` ${e.length}`:_} + ${M(t.t("favorites_hint"))} ${e.map(s)} + ${e.length${P(t,t.t("favorites_add"),null,void 0,i,l=>l&&l!=="none"&&!e.includes(l)&&n([...e,l]))}`:_}`}function mb(t,e){let n=t.doc.settings.outside_hidden??[],r=s=>t.change(l=>l.settings.outside_hidden=dt(s)),o=new Set(t.hass?pu(t.hass,t.doc.floors):[]),i=L(t.hass,s=>!n.includes(s)&&o.has(s));return m`${e?gb(t,e):_} +

${t.t("outside_hidden")}${n.length>0?m` ${n.length}`:_}

+ ${M(t.t("outside_hidden_hint"))} + ${n.map((s,l)=>m`
${W(t.hass,s)}${Kr(t.t("delete"),"\u2715",()=>r(Ot(n,l)))}
`)} +
${P(t,t.t("outside_hidden_add"),null,void 0,i,s=>s&&s!=="none"&&!n.includes(s)&&r([...n,s]))}
`}function gb(t,e){let n=t.doc.settings.outside_view??null,r=()=>{let o=e();o&&t.change(i=>i.settings.outside_view=o)};return m`${M(t.t("outside_view_hint"))} + ${Y(m``,n?m``:_)}`}function _b(t){let e=t.doc.settings.own_alerts??[],n=s=>t.change(l=>l.settings.own_alerts=dt(s)),r=(s,l)=>n(Vr(e,s,l)),o=[["",t.t("own_alert_house")],...t.doc.floors.flatMap(s=>s.rooms.map(l=>[l.id,`${l.name} \xB7 ${s.name}`]))],i=(s,l)=>m`
+ ${P(t,t.t("own_alert_entity"),s.entity||null,void 0,L(t.hass,()=>!0),a=>r(l,{entity:a&&a!=="none"?a:""}))} + ${Z(t,t.t("own_alert_state"),s.state??"",a=>r(l,{state:a||null}),{placeholder:t.hass?.states[s.entity]?.state??"on \xB7 <20 \xB7 >80"})} + ${Z(t,t.t("own_alert_text"),s.text,a=>r(l,{text:a||t.t("own_alert_new")}),{wide:!0,maxlength:120})} + ${O(t,t.t("room"),s.room_id??"",o,a=>r(l,{room_id:a||null}),{wide:!0})} + ${je(t,t.t("own_alert_color"),s.color??null,"#ffb547",a=>r(l,{color:a}))} + ${O(t,t.t("own_alert_tap"),s.tap??"",[["",t.t("own_alert_tap_info")],["toggle",t.t("own_alert_tap_toggle")],["room",t.t("own_alert_tap_room")]],a=>r(l,{tap:a||null}))} +
+
`;return m`

⚠ ${t.t("own_alerts")}

+ ${M(t.t("own_alerts_hint"))} ${e.map(i)} + ${e.length<40?Y(m``):_}`}function bb(t){let e=t.doc.settings.circuits??[],n=l=>t.change(a=>a.settings.circuits=dt(l)),r=(l,a)=>n(Vr(e,l,a)),o=t.doc.floors.flatMap(l=>l.rooms.map(a=>({id:a.id,label:t.doc.floors.length>1?`${a.name} \xB7 ${l.name}`:a.name}))),i=l=>o.find(a=>a.id===l)?.label??l,s=(l,a)=>m`
+ ${Z(t,t.t("circuit_name"),l.name,c=>r(a,{name:c||t.t("circuit_new")}),{wide:!0,maxlength:80})} +
${l.rooms.map(c=>m`${i(c)} `)}
+ ${O(t,t.t("circuit_add_room"),"",[["","\u2013"],...o.filter(c=>!l.rooms.includes(c.id)).map(c=>[c.id,c.label])],c=>c&&r(a,{rooms:[...l.rooms,c]}),{wide:!0})} +
+
`;return m`

🔌 ${t.t("circuits")}

+ ${M(t.t("circuits_hint"))} ${e.map(s)} + ${e.length<120?Y(m``):_}`}function yb(t){let e=t.doc.settings.calendars??[],n=l=>t.change(a=>a.settings.calendars=dt(l)),r=L(t.hass,l=>l.startsWith("calendar.")&&!e.includes(l)),o=(l,a)=>m`
+ ${W(t.hass,l)} + ${Kr(t.t("delete"),"\u2715",()=>n(Ot(e,a)))} +
`,i=t.t,s=t.doc.settings.today_days??1;return m`

📅 ${i("today_calendars")}

+ ${M(i("today_calendars_hint"))} ${e.map(o)} + ${e.length<12?m`
${P(t,i("favorites_add"),null,void 0,r,l=>l&&l!=="none"&&!e.includes(l)&&n([...e,l]))}
`:_} + ${e.length?m`
+ ${O(t,i("today_days"),String(s),[1,2,3,5,7].map(l=>[String(l),i(l===1?"today_days_one":"today_days_n",{n:l})]),l=>t.change(a=>a.settings.today_days=Number(l)>1?Number(l):void 0))} +
`:_} + ${wb(t)}`}function wb(t){let e=t.t,n=t.doc.settings.forecast??null,r=o=>t.change(i=>i.settings.forecast=o??void 0);return m`

🌦 ${e("forecast")}

+ ${M(e("forecast_hint"))} +
+ ${O(t,e("forecast_days"),n?String(n.days):"0",[0,3,5,7].map(o=>[String(o),o?e("today_days_n",{n:o}):e("forecast_off")]),o=>r(Number(o)>0?{days:Number(o),corner:n?.corner??"top_right"}:null))} + ${n?O(t,e("forecast_corner"),n.corner,[["top_right",e("clock_top_right")],["top_left",e("clock_top_left")]],o=>r({...n,corner:o==="top_left"?"top_left":"top_right"})):_} +
`}function vb(t){let e=t.doc.settings.media_presets??[],n=s=>t.change(l=>l.settings.media_presets=dt(s)),r=(s,l)=>n(Vr(e,s,l)),o=[...new Set(t.doc.floors.flatMap(s=>[...s.placements.map(l=>l.entity_id),...s.furniture.map(l=>l.entity??"")]).filter(s=>s.startsWith("media_player.")))],i=(s,l)=>m`
+ ${Z(t,t.t("own_button_label"),s.label,a=>r(l,{label:a||"Radio"}),{maxlength:60})} + ${Z(t,t.t("preset_type"),s.type,a=>r(l,{type:a||"music"}),{title:t.t("preset_type_hint")})} + ${Z(t,t.t("preset_content"),s.content,a=>r(l,{content:a}),{wide:!0,title:t.t("preset_content_hint"),placeholder:"https://\u2026 \xB7 spotify:playlist:\u2026 \xB7 Rock Antenne"})} + ${o.length>1?m`
${t.t("preset_speakers")}
+ ${o.map(a=>H(t,W(t.hass,a),!!s.speakers?.includes(a),c=>r(l,{speakers:dt(c?[...s.speakers??[],a]:(s.speakers??[]).filter(u=>u!==a))}),{wide:!1}))}`:_} +
+
`;return m`

${t.t("presets")}

+ ${M(t.t("presets_hint"))} + ${pb.map(s=>m``)} + ${e.map(i)} + ${e.lengthn([...e,{id:D("preset"),label:"Radio",type:"music",content:""}])}>+ ${t.t("preset_add")}`):_}`}function sa(t,e,n){let r=e.action==="fire_dom_event"?'{"browser_mod": {"service": "browser_mod.popup", "data": {"title": "Rollos", "content": {"type": "custom:my-cover-card"}}}}':'{"entity_id": "script.party"}',o=i=>{let s=i.target;s.setCustomValidity("");let l=td(s.value);if(l.ok)return n(l.value);s.setCustomValidity(t.t("own_data_bad")),s.reportValidity()};return m``}function kb(t){let e=t.doc.settings.buttons??[],n=s=>t.change(l=>l.settings.buttons=dt(s)),r=(s,l)=>n(Vr(e,s,l)),o=Ao.map(s=>[s,t.t(`own_action_${s}`)]),i=(s,l)=>m`
+ ${Z(t,t.t("own_button_label"),s.label,a=>r(l,{label:a||t.t("own_button_new")}),{maxlength:60})} + ${O(t,t.t("own_button_action"),s.action,o,a=>r(l,{action:a}))} ${Dt(t,s.icon??null,a=>r(l,{icon:a}))} + ${s.action!=="fire_dom_event"?Z(t,t.t(`own_target_${s.action}`),s.target??"",a=>r(l,{target:a||null}),{wide:!0,placeholder:ia[s.action]}):_} + ${s.action==="service"||s.action==="fire_dom_event"?sa(t,s,a=>r(l,{data:a})):_} + ${P(t,t.t("own_button_state"),s.state_entity??null,void 0,L(t.hass,a=>/^(switch|light|input_boolean|binary_sensor|fan|cover|media_player|climate|lock|person|device_tracker)\./.test(a)),a=>r(l,{state_entity:a&&a!=="none"?a:null}))} +
+ + +
+
`;return m`

${t.t("own_buttons")}

+ ${M(t.t("own_buttons_hint"))} ${e.map(i)} + ${e.lengthn([...e,{id:D("btn"),label:t.t("own_button_new"),action:"navigate",target:null}])}>+ ${t.t("own_button_add")}`):_}`}function xb(t){let e=t.doc.settings.room_facts_off??[],n=["sun","comfort","air","circuits"].map(r=>H(t,t.t(`room_fact_${r}`),!e.includes(r),o=>t.change(i=>i.settings.room_facts_off=dt(o?e.filter(s=>s!==r):[...e,r]))));return m`

${t.t("room_facts")}

${n}
`}function nd(t){return m`
${fb(t)} ${kb(t)} ${_b(t)} ${bb(t)} ${yb(t)} ${vb(t)} ${xb(t)}
`}function rd(t,e){return m`
+ 🌳 ${t.t("outside_area")} + ${mb(t,e)} +
`}function od(t,e){let n=t.doc.settings.start_view??null,r=()=>{let o=e();o&&t.change(i=>i.settings.start_view=o)};return m`
+ ${t.t("start_view")} + ${M(t.t("start_view_hint"))} + ${Y(m``,n?m``:_)} + ${n?m`${M(t.t("start_view_saved"))} ${M(t.t("start_view_card"))}${ed(n)}`:_} +
`}function id(t){let e=t.doc.presence.map(a=>a.person),n=[...new Set([...Object.keys(t.hass?.states??{}).filter(a=>a.startsWith("person.")).sort(),...e])],r=L(t.hass,he),o=t.doc.floors.flatMap(a=>a.rooms.map(c=>({id:c.id,label:t.doc.floors.length>1?`${a.name} \xB7 ${c.name}`:c.name}))),i=(a,c)=>t.replace({...structuredClone(t.doc),presence:Qu(t.doc.presence,a,c)}),s=a=>{let c=t.doc.presence.find(d=>d.person===a),u=!a.startsWith("person.");return m`${P(t,`${W(t.hass,a)} \xB7 ${t.t("presence_sensor")}`,c?.sensor??null,void 0,Ju(r,a),d=>i(a,{sensor:d}))} + + ${u?m``:_}`},l=L(t.hass,a=>/^(input_boolean|binary_sensor|device_tracker)\./.test(a)&&!n.includes(a));return m`
+ ${t.t("presence")} +
${n.length>0?n.map(s):m`

${t.t("no_persons")}

`}
+
${P(t,t.t("presence_add"),null,void 0,l,a=>a&&a!=="none"&&t.replace({...structuredClone(t.doc),presence:[...t.doc.presence,{person:a,sensor:null}]}))}
+ ${M(t.t("presence_hint"))} +
`}function sd(t,e){return m`
+ ${t.t("ble")} + ${M(t.t("ble_hint"))} + +
`}var{I:nS}=jl;var ad=t=>t.strings===void 0;var Gr=(t,e)=>{let n=t._$AN;if(n===void 0)return!1;for(let r of n)r._$AO?.(e,!1),Gr(r,e);return!0},si=t=>{let e,n;do{if((e=t._$AM)===void 0)break;n=e._$AN,n.delete(t),t=e}while(n?.size===0)},ld=t=>{for(let e;e=t._$AM;t=e){let n=e._$AN;if(n===void 0)e._$AN=n=new Set;else if(n.has(t))break;n.add(t),Mb(e)}};function $b(t){this._$AN!==void 0?(si(this),this._$AM=t,ld(this)):this._$AM=t}function Sb(t,e=!1,n=0){let r=this._$AH,o=this._$AN;if(o!==void 0&&o.size!==0)if(e)if(Array.isArray(r))for(let i=n;i{t.type==oi.CHILD&&(t._$AP??=Sb,t._$AQ??=$b)},ai=class extends In{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,n,r){super._$AT(e,n,r),ld(this),this.isConnected=e._$AU}_$AO(e,n=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),n&&(Gr(this,e),si(this))}setValue(e){if(ad(this._$Ct))this._$Ct._$AI(e,this);else{let n=[...this._$Ct._$AH];n[this._$Ci]=e,this._$Ct._$AI(n,this,0)}}disconnected(){}reconnected(){}};var aa=new WeakMap,cd=Br(class extends ai{render(t){return _}update(t,[e]){let n=e!==this.G;return n&&this.rt(void 0),(n||this.lt!==this.ct)&&(this.G=e,this.ht=t.options?.host,this.rt(this.ct=t.element)),_}rt(t){if(this.G!==void 0)if(this.isConnected||(t=void 0),typeof this.G=="function"){let e=this.ht??globalThis,n=aa.get(e);n===void 0&&(n=new WeakMap,aa.set(e,n)),n.get(this.G)!==void 0&&this.G.call(this.ht,void 0),n.set(this.G,t),t!==void 0&&this.G.call(this.ht,t)}else this.G.value=t}get lt(){return typeof this.G=="function"?aa.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var ud=t=>t.trim().toLowerCase().replace(/ä/g,"ae").replace(/ö/g,"oe").replace(/ü/g,"ue").replace(/ß/g,"ss").replace(/[^a-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,40);function dd(t){let e=t.t,n=t.doc.settings.card_templates??{},r=Object.keys(n),o=l=>t.change(a=>{a.settings.card_templates=Object.keys(l).length?l:void 0});t.loadCardEditor?.();let i=l=>{t.hass?.callService("nextfloor","reload_screens",l?{template:l}:{})},s=l=>{let a=ud(l.value);!a||a in n||r.length>=20||(l.value="",o({...n,[a]:{}}))};return m`
+ ${e("card_templates")}${r.length?m` ${r.length}`:_} + ${M(e("card_templates_hint"))} + ${r.map(l=>m`
+ ${l} + a&&a.setConfig({type:"custom:nextfloor-card",...n[l]}))} + @config-changed=${a=>{a.stopPropagation();let{type:c,template:u,...d}=a.detail.config;o({...n,[l]:d})}} + > + ${t.admin?m`
+ + +
`:_} + ${M(e("template_use",{name:l}))} +
`)} + ${t.admin?m`
+ +
+
+ + +
`:_} +
`}var li=.05,Rb=(t,e)=>t.length===e.length&&t.every((n,r)=>Math.abs(n[0]-e[r][0])<.001&&Math.abs(n[1]-e[r][1])<.001),on=t=>new Map(t.map(e=>[e.id,e]));function Eb(t,e,n,r){let o=e.name,[i,s]=[on(t.rooms),on(e.rooms)];for(let h of e.rooms){let f=i.get(h.id);f?(f.name!==h.name&&n.push({kind:"room_renamed",floor:o,name:h.name,detail:f.name}),Rb(f.points,h.points)||n.push({kind:"room_reshaped",floor:o,name:h.name,detail:Math.round((we(h.points)-we(f.points))*10)/10})):n.push({kind:"room_added",floor:o,name:h.name})}for(let h of t.rooms)s.has(h.id)||n.push({kind:"room_removed",floor:o,name:h.name});let[l,a]=[on(t.openings),on(e.openings)];for(let h of e.openings)l.has(h.id)||n.push({kind:"opening_added",floor:o,name:h.type,detail:r(h.room_id)});for(let h of t.openings)a.has(h.id)||n.push({kind:"opening_removed",floor:o,name:h.type,detail:r(h.room_id)});let[c,u]=[on(t.furniture),on(e.furniture)];for(let h of e.furniture){let f=c.get(h.id);f?(Math.hypot(h.x-f.x,h.z-f.z)>li||Math.abs(h.rotation-f.rotation)>1||Math.abs(h.w-f.w)>li||Math.abs(h.d-f.d)>li)&&n.push({kind:"furniture_moved",floor:o,name:h.name||h.type}):n.push({kind:"furniture_added",floor:o,name:h.name||h.type})}for(let h of t.furniture)u.has(h.id)||n.push({kind:"furniture_removed",floor:o,name:h.name||h.type});let[d,p]=[new Map(t.placements.map(h=>[h.entity_id,h])),new Map(e.placements.map(h=>[h.entity_id,h]))];for(let h of e.placements){let f=d.get(h.entity_id);f?Math.hypot(h.x-f.x,h.z-f.z)>li&&n.push({kind:"device_moved",floor:o,name:h.entity_id}):n.push({kind:"device_added",floor:o,name:h.entity_id})}for(let h of t.placements)p.has(h.entity_id)||n.push({kind:"device_removed",floor:o,name:h.entity_id})}function hd(t,e){let n=[],r=on(t.floors),o=new Map([...t.floors,...e.floors].flatMap(l=>l.rooms.map(a=>[a.id,a.name]))),i=l=>o.get(l)??"";for(let l of e.floors){let a=r.get(l.id);a?Eb(a,l,n,i):n.push({kind:"floor_added",floor:l.name,name:l.name})}let s=new Set(e.floors.map(l=>l.id));for(let l of t.floors)s.has(l.id)||n.push({kind:"floor_removed",floor:l.name,name:l.name});return n}var sn=(t,e)=>t.getUint16(e,!0),Ur=(t,e)=>t.getUint32(e,!0);function pd(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=-1;for(let l=t.length-22;l>=Math.max(0,t.length-65557);l--)if(Ur(e,l)===101010256){n=l;break}if(n<0)throw new Error("not_zip");let r=sn(e,n+10),o=Ur(e,n+16),i=[],s=new TextDecoder;for(let l=0;l",quot:'"',apos:"'"},Fb=t=>t.replace(/&(#x?[0-9a-f]+|\w+);/gi,(e,n)=>n[0]==="#"?String.fromCodePoint(Number.parseInt(n.slice(n[1]==="x"?2:1),n[1]==="x"?16:10)):Ab[n]??e);function Tb(t){let e={};for(let n of t.matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g))e[n[1]]=Fb(n[2]??n[3]);return e}function zb(t){let e=[],n=null;for(let r of t.matchAll(/<(\/?)(level|room|point|wall|doorOrWindow|pieceOfFurniture)\b([^>]*?)(\/?)>/g)){let[,o,i,s,l]=r;if(o){i==="room"&&(n=null);continue}let a=Tb(s);if(i==="point"){n&&n.points.push([Number(a.x)/100,Number(a.y)/100]);continue}let c={name:i,attrs:a,...i==="room"?{points:[]}:{}};e.push(c),i==="room"&&!l&&(n=c)}return e}var ne=(t,e,n)=>Number.isFinite(Number(t[e]))&&t[e]!==void 0?Number(t[e]):n,Me=t=>Math.round(t*1e3)/1e3;function md(t,e,n){let[r,o]=[n[0]-e[0],n[1]-e[1]],i=Math.hypot(r,o)||1e-9,s=Math.max(0,Math.min(i,((t[0]-e[0])*r+(t[1]-e[1])*o)/i)),l=[e[0]+r*s/i,e[1]+o*s/i];return{dist:Math.hypot(t[0]-l[0],t[1]-l[1]),along:s,length:i}}function Pb(t){let e=`${t.name??""} ${t.catalogId??""}`.toLowerCase();return/garage|sectional|rolltor/.test(e)?"garage":/door|tür|tuer|porte|puerta|deur|haustür/.test(e)&&!/window|fenster/.test(e)?"door":"window"}function Ib(t,e){let n=t.length,r=t.map((o,i)=>{let s=t[(i+1)%n],[l,a]=[s[0]-o[0],s[1]-o[1]],c=Math.hypot(l,a)||1e-9,u=[l/c,a/c],d=[(o[0]+s[0])/2,(o[1]+s[1])/2],p=[0,0];for(let h of e){let[f,g]=[h.b[0]-h.a[0],h.b[1]-h.a[1]],y=Math.hypot(f,g)||1e-9;if(Math.abs((u[0]*g-u[1]*f)/y)>.05)continue;let b=(h.a[0]-d[0])*-u[1]+(h.a[1]-d[1])*u[0],v=((d[0]-h.a[0])*f+(d[1]-h.a[1])*g)/y;if(!(Math.abs(b)>h.thickness/2+.06||v<-.05||v>y+.05)){p=[-u[1]*b,u[0]*b];break}}return{p:[o[0]+p[0],o[1]+p[1]],dir:u}});return r.map((o,i)=>{let s=r[(i-1+n)%n],l=s.dir[0]*o.dir[1]-s.dir[1]*o.dir[0];if(Math.abs(l)<1e-6)return o.p;let a=((o.p[0]-s.p[0])*o.dir[1]-(o.p[1]-s.p[1])*o.dir[0])/l;return[s.p[0]+s.dir[0]*a,s.p[1]+s.dir[1]*a]})}function Db(t){let e=Ft(),n={floors:0,rooms:0,openings:0,walls:0,furniture:0},r=t.filter(a=>a.name==="level"),o=r.length?r.map(a=>a.attrs.id??""):[""],i=t.filter(a=>a.name==="wall"),s=i.length?Math.max(...i.map(a=>ne(a.attrs,"height",250)))/100:2.5;return(r.length?[...r].sort((a,c)=>ne(a.attrs,"elevation",0)-ne(c.attrs,"elevation",0)||ne(a.attrs,"elevationIndex",0)-ne(c.attrs,"elevationIndex",0)):[{name:"level",attrs:{id:""}}]).forEach((a,c)=>{let u=a.attrs.id??"",d=y=>r.length?(y.attrs.level??o[0])===u:!0,p=He(D("floor"),a.attrs.name||(c===0?"Erdgeschoss":`Etage ${c+1}`),Me(ne(a.attrs,"elevation",0)/100));p.height=Me(ne(a.attrs,"height",s*100)/100);let h=i.filter(d).map(y=>({a:[ne(y.attrs,"xStart",0)/100,ne(y.attrs,"yStart",0)/100],b:[ne(y.attrs,"xEnd",0)/100,ne(y.attrs,"yEnd",0)/100],thickness:ne(y.attrs,"thickness",10)/100})),f=t.filter(y=>y.name==="room"&&d(y)&&(y.points?.length??0)>=3).map((y,b)=>({id:D("room"),name:y.attrs.name||`Raum ${b+1}`,area_id:null,points:Ib(y.points,h).map(([v,w])=>[Me(v),Me(w)]),floor_material:"wood",panel:[]}));p.rooms=f;for(let y of t.filter(b=>b.name==="doorOrWindow"&&d(b))){let b=[ne(y.attrs,"x",0)/100,ne(y.attrs,"y",0)/100],v=Math.max(.6,ne(y.attrs,"depth",30)/100+.3),w=null;for(let I of f)I.points.forEach((z,C)=>{let B=md(b,z,I.points[(C+1)%I.points.length]);B.dist<=v&&(!w||B.dist1.4?2:1,swing:"in",cover:null,contact:null,contact2:null,tilt:null})}let g=[];for(let y of i.filter(d)){let b=[ne(y.attrs,"xStart",0)/100,ne(y.attrs,"yStart",0)/100],v=[ne(y.attrs,"xEnd",0)/100,ne(y.attrs,"yEnd",0)/100];if(Math.hypot(v[0]-b[0],v[1]-b[1])<.1)continue;let w=Math.max(.15,ne(y.attrs,"thickness",10)/100),x=T=>f.some(I=>I.points.some((z,C)=>md(T,z,I.points[(C+1)%I.points.length]).dist[b[0]+(v[0]-b[0])*T/$,b[1]+(v[1]-b[1])*T/$],F=Array.from({length:$+1},(T,I)=>!x(A(I)));for(let T=0;T<=$;){if(!F[T]){T++;continue}let I=T;for(;I+1<=$&&F[I+1];)I++;let[z,C]=[A(Math.max(0,T-1)),A(Math.min($,I+1))];Math.hypot(C[0]-z[0],C[1]-z[1])>=.3&&g.push({id:D("wall"),a:[Me(z[0]),Me(z[1])],b:[Me(C[0]),Me(C[1])],thickness:Me(ne(y.attrs,"thickness",10)/100),height:y.attrs.height?Me(ne(y.attrs,"height",250)/100):null}),T=I+1}}p.walls=g,n.rooms+=f.length,n.openings+=p.openings.length,n.walls+=g.length,(f.length||g.length)&&e.floors.push(p)}),n.floors=e.floors.length,n.furniture=t.filter(a=>a.name==="pieceOfFurniture").length,{building:Te(e),report:n}}async function gd(t){let e=pd(t).find(o=>o.name==="Home.xml");if(!e)throw new Error("sh3d_no_xml");let n=new TextDecoder().decode(await fd(t,e)),r=Db(zb(n));if(r.report.rooms===0&&r.report.walls===0)throw new Error("sh3d_empty");return r}function Ob(t){let e=t.split(/\r?\n/),n=[];for(let r=0;r+1r===9&&o==="$INSUNITS"),n=e>=0?Number(t[e+1]?.[1]):NaN;return{1:.0254,2:.3048,4:.001,5:.01,6:1}[n]??null}function Lb(t){let e=Ob(t),n=Hb(e),r=e.findIndex(([s,l],a)=>s===2&&l==="ENTITIES"&&e[a-1]?.[1]==="SECTION"),o=[];if(r<0)return{shapes:o,unit:n};let i=r+1;for(;iNumber(c.find(([h])=>h===p)?.[1]??NaN),d=[[u(10),u(20)],[u(11),u(21)]];d.every(([p,h])=>Number.isFinite(p)&&Number.isFinite(h))&&o.push({points:d,closed:!1})}else if(l==="LWPOLYLINE"){let u=c.filter(([f])=>f===10).map(([,f])=>Number(f)),d=c.filter(([f])=>f===20).map(([,f])=>Number(f)),p=Number(c.find(([f])=>f===70)?.[1]??0),h=u.map((f,g)=>[f,d[g]]).filter(([f,g])=>Number.isFinite(f)&&Number.isFinite(g));h.length>=2&&o.push({points:h,closed:(p&1)===1})}i=a}return{shapes:o,unit:n}}var _d=t=>Math.round(t*1e3)/1e3;function bd(t){let{shapes:e,unit:n}=Lb(t);if(!e.length)throw new Error("dxf_empty");let r=e.flatMap(h=>h.points),o=Math.max(Math.max(...r.map(h=>h[0]))-Math.min(...r.map(h=>h[0])),Math.max(...r.map(h=>h[1]))-Math.min(...r.map(h=>h[1]))),i=n??(o>2e3?.001:o>200?.01:1),s=Math.min(...r.map(h=>h[0])),l=Math.max(...r.map(h=>h[1])),a=([h,f])=>[_d((h-s)*i),_d((l-f)*i)],c=He(D("floor"),"Erdgeschoss",0),u=[],d=[];for(let h of e){let f=h.points.map(a);if(h.closed&&f.length>=3)u.push({id:D("room"),name:`Raum ${u.length+1}`,area_id:null,points:f,floor_material:"wood",panel:[]});else for(let g=0;g+1.05&&d.push({id:D("wall"),a:f[g],b:f[g+1]})}c.rooms=u,c.walls=d;let p=Ft();return p.floors=[c],{building:Te(p),report:{floors:1,rooms:u.length,openings:0,walls:d.length,furniture:0}}}var Ze=t=>Math.round(t*100)/100;function Cb(t,e){let n=t.category;return typeof n=="string"?n:n&&typeof n=="object"?Object.keys(n)[0]??e:e}function Nb(t,e){let n=t,r=n?.transform,o=n?.dimensions;if(!n||!Array.isArray(r)||r.length<16||!Array.isArray(o)||o.length<3)return null;let i=l=>Number(l),s=Math.hypot(i(r[0]),i(r[2]));return![...r.slice(0,16),...o.slice(0,3)].every(l=>Number.isFinite(i(l)))||s<1e-6?null:{centre:[i(r[12]),i(r[13]),i(r[14])],dir:[i(r[0])/s,i(r[2])/s],size:[i(o[0]),i(o[1]),i(o[2])],kind:Cb(n,e)}}var Ln=(t,e,n)=>(Array.isArray(t[e])?t[e]:[]).map(r=>Nb(r,n)).filter(r=>!!r);function Bb(t){if(t.length<3)return null;let e=t.map(a=>{let c=a.size[0]/2;return[[a.centre[0]-a.dir[0]*c,a.centre[2]-a.dir[1]*c],[a.centre[0]+a.dir[0]*c,a.centre[2]+a.dir[1]*c]]}),n=(a,c)=>Math.hypot(a[0]-c[0],a[1]-c[1]),r=.4,o=new Set([0]),i=[e[0][0]],s=[0],l=e[0][1];for(;o.sizer?null:(i[0]=[(l[0]+i[0][0])/2,(l[1]+i[0][1])/2],{points:i,edgeWall:s})}function yd(t){let e=[],n=[];for(let l of t){let a=l.size[0]/2;for(let c of[-1,1])e.push(l.centre[0]+c*l.dir[0]*a),n.push(l.centre[2]+c*l.dir[1]*a)}let[r,o,i,s]=[Math.min(...e),Math.max(...e),Math.min(...n),Math.max(...n)];return[[r,i],[o,i],[o,s],[r,s]]}function Wb(t,e,n){let[r,o]=[n[0]-e[0],n[1]-e[1]],i=Math.hypot(r,o)||1e-9,s=Math.min(i,Math.max(0,((t[0]-e[0])*r+(t[1]-e[1])*o)/i));return{dist:Math.hypot(t[0]-(e[0]+r/i*s),t[1]-(e[1]+o/i*s)),along:s,length:i}}var Vb={sofa:"sofa",bed:"bed",table:"table",chair:"chair",bathtub:"bathtub",toilet:"wc",sink:"sink",refrigerator:"fridge",stove:"stove",oven:"stove",dishwasher:"dishwasher",washerDryer:"washer",storage:"tall_cabinet",television:"tv_board"};function wd(t){let e=t;return!e||typeof e!="object"||"floors"in e||"settings"in e?!1:(Array.isArray(e.rooms)?e.rooms:[e]).some(r=>r&&Array.isArray(r.walls)&&Ln(r,"walls","wall").length>0)}function vd(t){let e=t,r=(Array.isArray(e.rooms)?e.rooms:[e]).filter(y=>y&&typeof y=="object").map(y=>({walls:Ln(y,"walls","wall"),doors:[...Ln(y,"doors","door"),...Ln(y,"openings","opening")],windows:Ln(y,"windows","window"),objects:Ln(y,"objects","object")})).filter(y=>y.walls.length);if(!r.length)throw new Error("roomplan_empty");let o=r.flatMap(y=>y.walls),i=Math.min(...o.map(y=>y.centre[1]-y.size[1]/2)),s=r.map(y=>Bb(y.walls)),l=r.flatMap((y,b)=>s[b]?.points??yd(y.walls)),[a,c]=[Math.min(...l.map(y=>y[0]))-.5,Math.min(...l.map(y=>y[1]))-.5],u=([y,b])=>[Ze(y-a),Ze(b-c)],d=He(D("floor"),"Erdgeschoss",0);d.height=Ze(Math.max(2.2,Math.min(4,Math.max(...o.map(y=>y.size[1])))));let p=[],h=[];r.forEach((y,b)=>{let w=(s[b]?.points??yd(y.walls)).map(u),x={id:D("room"),name:`Raum ${b+1}`,area_id:null,points:w,floor_material:"wood",panel:[]};p.push(x);for(let k of[...y.doors.map($=>({v:$,window:!1})),...y.windows.map($=>({v:$,window:!0}))]){let $=[k.v.centre[0]-a,k.v.centre[2]-c],A=null;if(w.forEach((z,C)=>{let B=Wb($,z,w[(C+1)%w.length]);B.dist<=.6&&(!A||B.dist1.4?2:1,swing:"in",...I?{style:"passage"}:{},cover:null,contact:null,contact2:null,tilt:null})}for(let k of y.objects){let $=Vb[k.kind];if(!$)continue;let[A,F,T]=[k.size[0],k.size[2],k.size[1]];A<.1||F<.1||h.push({id:D("f"),type:$,x:Ze(k.centre[0]-a),z:Ze(k.centre[2]-c),rotation:Math.round((Math.atan2(k.dir[1],k.dir[0])*180/Math.PI+360)%360),w:Ze(A),d:Ze(F),h:Ze(T),variant:null,entity:null,power:null})}}),d.rooms=p,d.furniture=h;let f=Ft();f.floors=[d];let g=r.reduce((y,b)=>y+b.objects.length,0)-h.length;return{building:Te(f),report:{floors:1,rooms:p.length,openings:d.openings.length,walls:0,furniture:g}}}var jr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&"ref"in t;function Kb(t){let e=0,n=()=>{for(;t[e]===" ";)e++;let o=t[e];if(o==="("){e++;let a=[];for(;eString.fromCharCode(...(n.match(/.{4}/g)??[]).map(r=>parseInt(r,16)))).replace(/\\S\\(.)/g,(e,n)=>String.fromCharCode(n.charCodeAt(0)+128))}function Ub(t){let e=new Map,n=t.slice(Math.max(0,t.indexOf("DATA;")));for(let r of n.matchAll(/#(\d+)\s*=\s*([A-Z0-9_]+)\s*\(([\s\S]*?)\)\s*;(?=\s*(?:#|ENDSEC))/g))e.set(Number(r[1]),{type:r[2],args:Kb(r[3])});return e}var kd={x:0,y:0,z:0,c:1,s:0},xd=(t,e)=>({x:t.x+t.c*e.x-t.s*e.y,y:t.y+t.s*e.x+t.c*e.y,z:t.z+e.z,c:t.c*e.c-t.s*e.s,s:t.s*e.c+t.c*e.s});function $d(t){let e=Ub(t);if(!e.size)throw new Error("ifc_empty");let n=k=>jr(k)?e.get(k.ref):void 0,r=k=>typeof k=="number"?k:NaN,o=k=>(n(k)?.args[0]??[]).map($=>r($)),i=[...e.values()].find(k=>k.type==="IFCSIUNIT"&&k.args[1]===".LENGTHUNIT."),s=i?{".MILLI.":.001,".CENTI.":.01,".DECI.":.1}[String(i.args[2])]??1:1,l=k=>{let $=n(k);if(!$)return kd;let[A=0,F=0,T=0]=o($.args[0]),I=n($.type==="IFCAXIS2PLACEMENT3D"?$.args[2]:$.args[1]),[z=1,C=0]=(I?.args[0]??[]).map(q=>r(q)),B=Math.hypot(z,C)||1;return{x:A||0,y:F||0,z:T||0,c:z/B,s:C/B}},a=(k,$=0)=>{let A=n(k);return!A||A.type!=="IFCLOCALPLACEMENT"||$>30?kd:xd(a(A.args[0],$+1),l(A.args[1]))},c=k=>{for(let $ of n(k)?.args[2]??[])for(let A of n($)?.args[3]??[]){let F=n(A);if(F?.type!=="IFCEXTRUDEDAREASOLID")continue;let T=n(F.args[0]),I=xd(l(F.args[1]),l(T?.args[2])),z=[];if(T?.type==="IFCRECTANGLEPROFILEDEF"){let[C,B]=[r(T.args[3])/2,r(T.args[4])/2];z=[[-C,-B],[C,-B],[C,B],[-C,B]]}else if(T?.type==="IFCARBITRARYCLOSEDPROFILEDEF"){let C=n(T.args[2]);C?.type==="IFCPOLYLINE"&&(z=(C.args[0]??[]).map(B=>o(B)))}if(z=z.filter(C=>Number.isFinite(C[0])&&Number.isFinite(C[1])),z.length>3&&Math.hypot(z[0][0]-z[z.length-1][0],z[0][1]-z[z.length-1][1])<1e-6&&z.pop(),z.length>=3)return z.map(([C,B])=>[I.x+I.c*C-I.s*B,I.y+I.s*C+I.c*B])}return null},u=new Map;for(let[,k]of e){if(k.type==="IFCRELAGGREGATES"&&jr(k.args[4]))for(let $ of k.args[5]??[])jr($)&&u.set($.ref,k.args[4].ref);if(k.type==="IFCRELCONTAINEDINSPATIALSTRUCTURE"&&jr(k.args[5]))for(let $ of k.args[4]??[])jr($)&&u.set($.ref,k.args[5].ref)}let d=[...e].filter(([,k])=>k.type==="IFCBUILDINGSTOREY").map(([k,$])=>({id:k,name:String($.args[7]||$.args[2]||"")||null,elevation:r($.args[9])*s}));d.sort((k,$)=>(k.elevation||0)-($.elevation||0));let p=[];for(let[k,$]of e){if($.type!=="IFCSPACE")continue;let A=c($.args[6]);if(!A)continue;let F=a($.args[5]),T=A.map(([z,C])=>[(F.x+F.c*z-F.s*C)*s,(F.y+F.s*z+F.c*C)*s]),I=String($.args[7]||$.args[2]||"")||`Raum ${p.length+1}`;p.push({storey:u.get(k)??null,name:I,ring:T})}if(!p.length)throw new Error("ifc_empty");let h=p.flatMap(k=>k.ring),f=Math.min(...h.map(k=>k[0])),g=Math.max(...h.map(k=>k[1])),y=k=>Math.round(k*1e3)/1e3,b=[],v=new Map;if(d.filter(k=>p.some($=>$.storey===k.id)).forEach((k,$)=>{let A=He(D("floor"),k.name??`Etage ${$+1}`,Number.isFinite(k.elevation)?y(k.elevation):$*2.8);b.push(A),v.set(k.id,A)}),p.some(k=>k.storey===null||!v.has(k.storey))){let k=He(D("floor"),b.length?"Weitere R\xE4ume":"Erdgeschoss",b.length?b[b.length-1].elevation+2.8:0);b.push(k),v.set(null,k)}b.forEach((k,$)=>{let A=b[$+1];A&&A.elevation-k.elevation>1.8&&(k.height=y(A.elevation-k.elevation-.2))});for(let k of p)v.get(k.storey!==null&&v.has(k.storey)?k.storey:null).rooms.push({id:D("room"),name:k.name,area_id:null,points:k.ring.map(([A,F])=>[y(A-f),y(g-F)]),floor_material:"wood",panel:[]});let x=Ft();return x.floors=b,{building:Te(x),report:{floors:b.length,rooms:p.length,openings:0,walls:0,furniture:0}}}var Md="nextfloor",jb="alarm_control_panel|automation|binary_sensor|button|calendar|camera|climate|conversation|cover|date|datetime|device_tracker|event|fan|group|humidifier|image|input_boolean|input_button|input_datetime|input_number|input_select|input_text|lawn_mower|light|lock|media_player|notify|number|person|remote|scene|script|select|sensor|siren|stt|sun|switch|text|time|timer|todo|tts|update|vacuum|valve|water_heater|weather|zone",Sd=new RegExp(`^(?:${jb})\\.[a-z0-9_]+$`),Zb=/^[0-9a-f]{32}$/,qb=new Set(["area_id","ha_floor"]),Yb=new Set(["sub_areas"]),Xb=new Set(["tap","show_when","pictures","moods"]);function la(t){if(typeof t=="string")return Sd.test(t)||Zb.test(t)?null:t;if(Array.isArray(t))return t.map(e=>la(e)).filter(e=>e!==null);if(t&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))Sd.test(n)||Xb.has(n)||(qb.has(n)||Yb.has(n)?e[n]=null:e[n]=la(r));return e}return t}var Qb=["wall_exterior","wall_interior","wall_paint_outside","wall_paint_inside","grid","north","roof","weather_effects","rain_warning","sun_patches","lock_plan","start_view","units","motion_markers_active","room_double_tap"];function Rd(t){let e=structuredClone(t),n={};for(let o of Qb)e.settings?.[o]!==void 0&&(n[o]=e.settings[o]);let r=e.settings?.backdrop;r&&(r.color||r.dim!=null)&&(n.backdrop={color:r.color??null,dim:r.dim??null}),e.settings=n,e.energy={...e.energy,grid:null,solar:null,battery:null,battery_soc:null,tariff:null,consumption:null,gas:null,water:null},e.presence=[];for(let o of e.floors){o.background=null,o.placements=[],o.power_entity=null,o.ha_floor=null;for(let i of o.rooms)Object.assign(i,{area_id:null,sub_areas:null,panel:[],hidden:[],no_state:[]});o.furniture.forEach(i=>{Object.assign(i,{entity:null,power:null}),delete i.effect_animations,i.picture&&!(i.picture.startsWith("image:")||i.picture.startsWith("https://"))&&(i.picture=null)}),o.openings.forEach(i=>Object.assign(i,{cover:null,contact:null,tilt:null}))}return la(e)}function Ed(t,e){return{format:Md,version:1,exported_at:new Date().toISOString(),building:e?Rd(t):structuredClone(t)}}var Jb=t=>!!t&&(t.version===1||t.version===void 0)&&Array.isArray(t.floors)&&t.floors.every(e=>!!e&&typeof e=="object"),ey="https://therealmrbk.github.io/NextFloor/preview/?shared&noshowcase";function Ad(t,e,n,r,o=ey){let i=new Set(t.floors.flatMap(c=>c.furniture.map(u=>u.type)).filter(c=>c.startsWith("pack:")).map(c=>c.split(":")[1])),s={building:Rd(t),packs:e.filter(c=>!c.builtin&&i.has(c.id))},l=JSON.stringify(s).replace(/c.replace(/[&<>"]/g,u=>({"&":"&","<":"<",">":">",'"':"""})[u]);return` +${a(n)} + + + +`; +} diff --git a/frontend/src/components/editor/roof-controller.test.ts b/frontend/src/components/editor/roof-controller.test.ts new file mode 100644 index 0000000..8b57720 --- /dev/null +++ b/frontend/src/components/editor/roof-controller.test.ts @@ -0,0 +1,190 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, floorWith } from "../../entities/fixtures.ts"; +import type { Building, Floor } from "../../model.ts"; +import type { EditorHost } from "./host.ts"; +import { RoofController } from "./roof-controller.ts"; + +function setup(roof: Record = { type: "gable", pitch: 35, overhang: 0.4 }, admin = true) { + const floor: Floor = floorWith([box("r", 0, 0, 8, 5)], { elevation: 0, height: 2.5 }); + let doc = { version: 1, floors: [floor], settings: { wall_exterior: 0.3, wall_interior: 0.12, north: 0, grid: 0.1, roof }, energy: {}, presence: [] } as unknown as Building; + const calls = { refresh: 0, floor: null as string | null, confirmed: true, changes: 0 }; + const host: EditorHost = { + hass: undefined, + get doc() { + return doc; + }, + floor, + admin, + t: (key, vars) => `${key}${vars ? JSON.stringify(vars) : ""}`, + change: (mutate) => { + const next = structuredClone(doc); + mutate(next, next.floors[0]); + doc = next; + calls.changes++; + }, + pickPoint: () => {}, + replace: (next) => void (doc = next), + }; + const controller = new RoofController({ host, floorId: () => calls.floor, setFloorId: (id) => (calls.floor = id), confirm: () => calls.confirmed, refresh: () => calls.refresh++ }); + return { controller, calls, doc: () => doc }; +} + +test("switching to sections proposes them from the rooms, and a second time only when asked to start over", () => { + const s = setup(); + s.controller.useSections(); + const first = s.doc().settings.roof; + assert.equal(first.type, "custom"); + assert.ok((first.sections ?? []).length > 0); + const ids = first.sections!.map((x) => x.id); + s.controller.useSections(); + assert.deepEqual(s.doc().settings.roof.sections!.map((x) => x.id), ids, "nothing is regenerated"); + s.calls.confirmed = false; + s.controller.useSections(true); + assert.deepEqual(s.doc().settings.roof.sections!.map((x) => x.id), ids, "declined"); + s.calls.confirmed = true; + s.controller.useSections(true); + assert.notDeepEqual(s.doc().settings.roof.sections!.map((x) => x.id), ids); +}); + +test("a section can be drawn, selected, changed, copied and removed", () => { + const s = setup(); + s.controller.addSection([0, 0], [8, 5]); + const id = s.controller.sectionId!; + assert.equal(s.doc().settings.roof.type, "custom"); + assert.equal(s.controller.section?.id, id); + s.controller.patchSection({ pitch_a: 20 }); + assert.equal(s.controller.section?.pitch_a, 20); + s.controller.duplicateSection(); + assert.equal(s.doc().settings.roof.sections!.length, 2); + assert.notEqual(s.controller.sectionId, id, "the copy is selected"); + s.controller.removeSection(); + assert.equal(s.controller.sectionId, null); + assert.deepEqual(s.doc().settings.roof.sections!.map((x) => x.id), [id]); +}); + +test("a dormer is added to the selected section and then selected itself", () => { + const s = setup(); + s.controller.addSection([0, 0], [8, 5]); + const parent = s.controller.sectionId; + s.controller.addDormer("a"); + assert.notEqual(s.controller.sectionId, parent); + assert.equal(s.controller.section?.dormer !== undefined && s.controller.section.dormer !== null, true); +}); + +test("the outline of the floor shown becomes the shape of a section", () => { + const s = setup(); + s.controller.addSection([0, 0], [8, 5]); + s.controller.takeOutline(); + const section = s.controller.section!; + assert.equal(section.shape, "flat"); + assert.ok((section.points ?? []).length >= 4); +}); + +test("a viewer who is no admin cannot change anything", () => { + const s = setup(undefined, false); + s.controller.addSection([0, 0], [8, 5]); + s.controller.useSections(); + s.controller.addField(); + assert.equal(s.calls.changes, 0); +}); + +test("solar fields: one goes on the best face, further ones on the faces left, and removing one takes its empty string with it", () => { + const s = setup(); + s.controller.addField(); + const first = s.controller.field!; + assert.ok(first.face.startsWith("main:")); + assert.equal(s.controller.sectionId, null); + s.controller.addField(); + const second = s.controller.field!; + assert.notEqual(second.face, first.face); + s.controller.setString("new"); + assert.equal(s.doc().settings.roof.strings!.length, 1); + assert.equal(s.controller.field!.string, s.doc().settings.roof.strings![0].id); + s.controller.patchString({ name: "Süd" }); + assert.equal(s.doc().settings.roof.strings![0].name, "Süd"); + s.controller.removeField(); + assert.equal(s.controller.solarId, null); + assert.equal(s.doc().settings.roof.solar!.length, 1); + assert.deepEqual(s.doc().settings.roof.strings, []); +}); + +test("a field's modules can be switched off by cell, and a change keeps the field on its face", () => { + const s = setup(); + s.controller.addField(); + s.controller.toggleCell("0:0"); + assert.deepEqual(s.controller.field!.skip, ["0:0"]); + s.controller.toggleCell("0:0"); + assert.equal(s.controller.field!.skip, null); + s.controller.patchField({ rows: 40, cols: 60, u: 50, v: 50 }); + const face = s.controller.field!; + assert.ok(face.u < 50 && face.v < 50, `pushed back: ${face.u},${face.v}`); +}); + +test("roof windows are added on a sloped face, kept on it when changed, and removed", () => { + const s = setup(); + s.controller.addWindow(); + const win = s.controller.window!; + assert.ok(win.face.startsWith("main:")); + s.controller.patchWindow({ u: 999 }); + assert.ok(s.controller.window!.u < 999); + s.controller.removeWindow(); + assert.equal(s.controller.windowId, null); + assert.deepEqual(s.doc().settings.roof.windows, []); +}); + +test("chimneys are added near the ridge, kept on their face when changed, and removed", () => { + const s = setup(); + s.controller.addChimney(); + const c = s.controller.chimney!; + assert.equal(c.shape, "brick"); + assert.ok(c.face.startsWith("main:")); + s.controller.patchChimney({ v: 999, shape: "wide" }); + assert.ok(s.controller.chimney!.v < 999); + assert.equal(s.controller.chimney!.shape, "wide"); + s.controller.removeChimney(); + assert.equal(s.controller.chimneyId, null); + assert.deepEqual(s.doc().settings.roof.chimneys, []); +}); + +test("selecting a wall field brings up its floor, and the selection changes ask for a redraw", () => { + const s = setup(); + s.controller.addWallField(); + const field = s.controller.field; + if (field) { + s.controller.selectField(field.id); + assert.equal(s.calls.floor, field.face.split(":")[1]); + } + const before = s.calls.refresh; + s.controller.picking = true; + s.controller.sectionId = null; + assert.equal(s.calls.refresh, before + 2); + assert.equal(s.controller.picking, true); +}); + +test("a section is fixed by its own lock or by the lock on the plan", () => { + const s = setup(); + s.controller.addSection([0, 0], [8, 5]); + const section = s.controller.section!; + assert.equal(s.controller.isFixed(section), false); + assert.equal(s.controller.isFixed({ ...section, locked: true }), true); + assert.equal(s.controller.isFixed(undefined), false); +}); + +import { fieldOnFace } from "./ops/solar.ts"; + +test("moving a field to another face keeps its modules; to the ground gives a free-standing field; an unknown face gives nothing", () => { + const s = setup(); + s.controller.addField(); + const field = s.controller.field!; + s.controller.patchField({ name: "Süd", wp: 450 }); + const other = field.face.endsWith(":a") ? field.face.replace(":a", ":b") : field.face.replace(":b", ":a"); + const moved = fieldOnFace(s.doc(), s.controller.field!, other); + assert.equal(moved?.face, other); + assert.equal(moved?.name, "Süd"); + assert.equal(moved?.wp, 450); + const ground = fieldOnFace(s.doc(), s.controller.field!, "ground"); + assert.equal(ground?.face, "ground"); + assert.equal(ground?.rows, s.controller.field!.rows); + assert.equal(fieldOnFace(s.doc(), s.controller.field!, "nowhere"), null); +}); diff --git a/frontend/src/components/editor/roof-controller.ts b/frontend/src/components/editor/roof-controller.ts new file mode 100644 index 0000000..3792d0b --- /dev/null +++ b/frontend/src/components/editor/roof-controller.ts @@ -0,0 +1,346 @@ +// The roof tool's state and actions: which section, roof window or solar field is selected, and everything that adds, changes or +// removes them. The forms and the plan canvas read its selection; the pointer code of the editor sets it. + +import { chimneyAsField, clampField, bestFace, fieldFace, proposeChimney, proposeField, proposeGroundField, proposeWallField, proposeWindow, roofFaces, windowAsField } from "../../solar.ts"; +import { floorOutline, polygonBox, proposeDormer, roofSectionsFromRooms } from "../../roof-sections.ts"; +import { uid, type Building, type Floor, type RoofChimney, type RoofSection, type RoofWindow, type SolarField, type SolarString, type Vec2 } from "../../model.ts"; +import type { EditorHost } from "./host.ts"; +import { copyOfSection, removeRoofCorner, sectionFromRectangle } from "./ops/roof.ts"; +import { assignString, pruneStrings, toggledSkip } from "./ops/solar.ts"; + +export interface RoofContext { + readonly host: EditorHost; + /** The floor the plan shows. */ + floorId(): string | null; + setFloorId(id: string): void; + confirm(text: string): boolean; + /** The selection changed, so the editor should draw again. */ + refresh(): void; +} + +const thousandths = (v: number) => Math.round(v * 1000) / 1000; + +export class RoofController { + private readonly ctx: RoofContext; + private sectionSel: string | null = null; + private windowSel: string | null = null; + private chimneySel: string | null = null; + private fieldSel: string | null = null; + private pickMode = false; + + constructor(ctx: RoofContext) { + this.ctx = ctx; + } + + // selection: the setters ask the editor to draw again + + get sectionId(): string | null { + return this.sectionSel; + } + set sectionId(id: string | null) { + this.sectionSel = id; + this.ctx.refresh(); + } + + get windowId(): string | null { + return this.windowSel; + } + set windowId(id: string | null) { + this.windowSel = id; + this.ctx.refresh(); + } + + get chimneyId(): string | null { + return this.chimneySel; + } + set chimneyId(id: string | null) { + this.chimneySel = id; + if (id) this.windowSel = null; + this.ctx.refresh(); + } + + get solarId(): string | null { + return this.fieldSel; + } + set solarId(id: string | null) { + this.fieldSel = id; + this.ctx.refresh(); + } + + /** Whether clicking a module of the selected field switches it off or on. */ + get picking(): boolean { + return this.pickMode; + } + set picking(on: boolean) { + this.pickMode = on; + this.ctx.refresh(); + } + + private get doc() { + return this.ctx.host.doc; + } + private get settings() { + return this.doc.settings.roof; + } + private get admin() { + return this.ctx.host.admin; + } + + get section(): RoofSection | undefined { + return this.sectionSel ? this.settings.sections?.find((s) => s.id === this.sectionSel) : undefined; + } + get window(): RoofWindow | undefined { + return this.windowSel ? this.settings.windows?.find((w) => w.id === this.windowSel) : undefined; + } + get chimney(): RoofChimney | undefined { + return this.chimneySel ? this.settings.chimneys?.find((c) => c.id === this.chimneySel) : undefined; + } + get field(): SolarField | undefined { + return this.fieldSel ? this.settings.solar?.find((f) => f.id === this.fieldSel) : undefined; + } + + /** A section is fixed by its own lock or by the lock on the whole plan. */ + isFixed(section: RoofSection | undefined): boolean { + return !!section && (!!section.locked || !!this.doc.settings.lock_plan); + } + + // roof sections + + /** Switches to a roof of sections. Without sections yet (or when asked to start over) they are proposed from the rooms. */ + useSections(regenerate = false): void { + if (!this.admin) return; + const had = (this.settings.sections ?? []).length > 0; + if (regenerate && had && !this.ctx.confirm(this.ctx.host.t("roof_regen_confirm"))) return; + this.ctx.host.change((doc) => { + doc.settings.roof.type = "custom"; + if (regenerate || !had) doc.settings.roof.sections = roofSectionsFromRooms(doc, () => uid("roof")); + }); + this.sectionId = null; + } + + addSection(lo: Vec2, hi: Vec2): void { + if (!this.admin) return; + const section = sectionFromRectangle(this.doc, lo, hi); + this.ctx.host.change((doc) => { + doc.settings.roof.type = "custom"; + doc.settings.roof.sections = [...(doc.settings.roof.sections ?? []), section]; + }); + this.sectionId = section.id; + } + + /** A flat section takes the outline of the floor shown (its rooms at the outer wall faces) as its shape. */ + takeOutline(): void { + const floor = this.ctx.host.floor; + if (!floor || !this.sectionSel || !this.admin) return; + const { wall_exterior, wall_interior } = this.doc.settings; + const outline = floorOutline(floor.rooms, floor.walls ?? [], wall_exterior, wall_interior); + if (!outline) return; + const points = outline.map(([x, z]) => [thousandths(x), thousandths(z)] as Vec2); + this.patchSection({ shape: "flat", points, ...polygonBox(points) }); + } + + /** A dormer on one side of the selected section, in its middle. The dormer becomes the selection. */ + addDormer(side: "a" | "b"): void { + const parent = this.section; + if (!parent || !this.admin) return; + const dormer = proposeDormer(parent, side, uid("roof")); + this.ctx.host.change((doc) => { + doc.settings.roof.sections = [...(doc.settings.roof.sections ?? []), dormer]; + }); + this.sectionId = dormer.id; + } + + patchSection(patch: Partial): void { + const id = this.sectionSel; + if (!id || !this.admin) return; + this.ctx.host.change((doc) => { + const section = doc.settings.roof.sections?.find((s) => s.id === id); + if (section) Object.assign(section, patch); + }); + } + + /** Takes a corner of the selected free flat roof away. */ + removeCorner(index: number): void { + const id = this.sectionSel; + if (!id || !this.admin) return; + this.ctx.host.change((doc) => { + const section = doc.settings.roof.sections?.find((s) => s.id === id); + if (section) removeRoofCorner(section, index); + }); + } + + removeSection(): void { + const id = this.sectionSel; + if (!id || !this.admin) return; + this.ctx.host.change((doc) => (doc.settings.roof.sections = (doc.settings.roof.sections ?? []).filter((s) => s.id !== id))); + this.sectionId = null; + } + + duplicateSection(): void { + const original = this.section; + if (!original || !this.admin) return; + const copy = copyOfSection(original); + this.ctx.host.change((doc) => (doc.settings.roof.sections = [...(doc.settings.roof.sections ?? []), copy])); + this.sectionId = copy.id; + } + + // roof windows + + addWindow(): void { + if (!this.admin) return; + const north = this.doc.settings.north ?? 0; + const face = bestFace(roofFaces(this.doc).filter((f) => !f.flat), north) ?? roofFaces(this.doc)[0]; + if (!face) return; + const created = proposeWindow(face, uid("rwin")); + this.ctx.host.change((doc) => (doc.settings.roof.windows = [...(doc.settings.roof.windows ?? []), created])); + this.windowSel = created.id; + this.sectionId = null; + } + + /** Changes the selected roof window. It is moved back onto its face when the change made it overhang. */ + patchWindow(patch: Partial): void { + const id = this.windowSel; + if (!id || !this.admin) return; + this.ctx.host.change((doc) => { + const target = doc.settings.roof.windows?.find((w) => w.id === id); + if (!target) return; + Object.assign(target, patch); + const face = roofFaces(doc).find((f) => f.key === target.face); + if (face) Object.assign(target, clampField(face, windowAsField(target))); + }); + } + + removeWindow(): void { + const id = this.windowSel; + if (!id || !this.admin) return; + this.ctx.host.change((doc) => (doc.settings.roof.windows = (doc.settings.roof.windows ?? []).filter((w) => w.id !== id))); + this.windowId = null; + } + + // chimneys + + /** Adds a brick chimney near the ridge of the first pitched face (else the first face). */ + addChimney(): void { + if (!this.admin) return; + const faces = roofFaces(this.doc); + const face = faces.find((f) => !f.flat) ?? faces[0]; + if (!face) return; + const created = proposeChimney(face, uid("chim")); + this.ctx.host.change((doc) => (doc.settings.roof.chimneys = [...(doc.settings.roof.chimneys ?? []), created])); + this.chimneySel = created.id; + this.windowSel = null; + this.sectionId = null; + } + + /** Changes the selected chimney; it is moved back onto its face when the change made it overhang. */ + patchChimney(patch: Partial): void { + const id = this.chimneySel; + if (!id || !this.admin) return; + this.ctx.host.change((doc) => { + const target = doc.settings.roof.chimneys?.find((c) => c.id === id); + if (!target) return; + Object.assign(target, patch); + const face = roofFaces(doc).find((f) => f.key === target.face); + if (face) Object.assign(target, clampField(face, chimneyAsField(target, face))); + }); + } + + removeChimney(): void { + const id = this.chimneySel; + if (!id || !this.admin) return; + this.ctx.host.change((doc) => (doc.settings.roof.chimneys = (doc.settings.roof.chimneys ?? []).filter((c) => c.id !== id))); + this.chimneyId = null; + } + + // solar fields + + /** Adds a field on the sunniest face that has none yet (else the sunniest one). */ + addField(): void { + if (!this.admin) return; + const faces = roofFaces(this.doc); + const used = new Set((this.settings.solar ?? []).map((f) => f.face)); + const north = this.doc.settings.north ?? 0; + const face = bestFace(faces.filter((f) => !used.has(f.key)), north) ?? bestFace(faces, north); + if (!face) return; + this.appendField(proposeField(face, uid("pv"))); + this.sectionSel = null; + } + + addWallField(): void { + const floorId = this.ctx.floorId() ?? this.doc.floors[0]?.id; + const created = this.admin && floorId ? proposeWallField(this.doc, uid("pv"), floorId) : null; + if (created) this.appendField(created); + } + + addGroundField(): void { + if (this.admin) this.appendField(proposeGroundField(this.doc, uid("pv"))); + } + + private appendField(field: SolarField): void { + this.ctx.host.change((doc) => (doc.settings.roof.solar = [...(doc.settings.roof.solar ?? []), field])); + this.solarId = field.id; + } + + /** Selects a field. One on a house wall brings up its floor in the plan. */ + selectField(id: string): void { + this.fieldSel = id; + this.sectionSel = null; + const field = this.settings.solar?.find((f) => f.id === id); + if (field?.face.startsWith("wall:")) this.ctx.setFloorId(field.face.split(":")[1]); + this.ctx.refresh(); + } + + /** Changes the selected field. A larger one (more rows, landscape) moves back so that it stays on its face. */ + patchField(patch: Partial): void { + this.editField((field, doc) => { + Object.assign(field, patch); + const face = fieldFace(doc, field); + if (face) Object.assign(field, clampField(face, field)); + }); + } + + toggleCell(cell: string): void { + this.editField((field) => (field.skip = toggledSkip(field.skip, cell))); + } + + private editField(edit: (field: SolarField, doc: Building) => void): void { + const id = this.fieldSel; + if (!id || !this.admin) return; + this.ctx.host.change((doc) => { + const field = doc.settings.roof.solar?.find((f) => f.id === id); + if (field) edit(field, doc); + }); + } + + /** Puts the selected field into a string ("new" makes one) or takes it out (null). */ + setString(value: string | null): void { + const id = this.fieldSel; + if (!id || !this.admin) return; + this.ctx.host.change((doc) => assignString(doc.settings.roof, id, value, { id: uid("str"), name: (n) => this.ctx.host.t("solar_string_n", { n }) })); + } + + /** Changes the string of the selected field. */ + patchString(patch: Partial): void { + const stringId = this.field?.string; + if (!stringId || !this.admin) return; + this.ctx.host.change((doc) => { + const target = doc.settings.roof.strings?.find((s) => s.id === stringId); + if (target) Object.assign(target, patch); + }); + } + + removeField(): void { + const id = this.fieldSel; + if (!id || !this.admin) return; + this.ctx.host.change((doc) => { + doc.settings.roof.solar = (doc.settings.roof.solar ?? []).filter((f) => f.id !== id); + pruneStrings(doc.settings.roof); + }); + this.solarId = null; + } + + /** The floors the roof tool offers to look at, top floor first. */ + floorsTopDown(): Floor[] { + return [...this.doc.floors].sort((a, b) => b.elevation - a.elevation); + } +} diff --git a/frontend/src/components/editor/selection.test.ts b/frontend/src/components/editor/selection.test.ts new file mode 100644 index 0000000..946c038 --- /dev/null +++ b/frontend/src/components/editor/selection.test.ts @@ -0,0 +1,77 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { Selection, type SelectionLookup } from "./selection.ts"; + +const lookup: SelectionLookup = { roomOfDevice: (id) => (id === "light.a" ? "kitchen" : null), roomOfOpening: (id) => (id === "door1" ? "hall" : null) }; +const make = () => { + let changes = 0; + const selection = new Selection(() => changes++); + return { selection, changes: () => changes }; +}; + +test("selecting a room selects only it, and its corner is forgotten unless the same room is chosen again", () => { + const { selection } = make(); + selection.select("room", "a", lookup); + selection.corner = 2; + selection.select("room", "a", lookup); + assert.equal(selection.corner, 2); + selection.select("room", "b", lookup); + assert.equal(selection.room, "b"); + assert.equal(selection.corner, null); +}); + +test("an item of a room leaves the room selected and deselects the other kinds", () => { + const { selection } = make(); + selection.select("room", "a", lookup); + selection.select("furniture", "sofa", lookup); + assert.deepEqual([selection.room, selection.furniture, selection.opening], ["a", "sofa", null]); + selection.select("opening", "door2", lookup); + assert.deepEqual([selection.room, selection.furniture, selection.opening], ["a", null, "door2"]); +}); + +test("a device or opening brings up the room it belongs to when it is known", () => { + const { selection } = make(); + selection.select("room", "a", lookup); + selection.select("device", "light.a", lookup); + assert.equal(selection.room, "kitchen"); + selection.select("opening", "door1", lookup); + assert.equal(selection.room, "hall"); + selection.select("device", "light.unplaced", lookup); + assert.equal(selection.room, "hall", "unknown room: the current one stays"); +}); + +test("outdoor areas and free walls belong to no room", () => { + const { selection } = make(); + selection.select("room", "a", lookup); + selection.select("outdoor", "lawn", lookup); + assert.deepEqual([selection.room, selection.outdoor], [null, "lawn"]); + selection.select("wall", "w1", lookup); + assert.deepEqual([selection.outdoor, selection.wall], [null, "w1"]); +}); + +test("selecting nothing of a kind clears it, and the highlighted edge is always cleared", () => { + const { selection } = make(); + selection.select("room", "a", lookup); + selection.edge = 1; + selection.select("furniture", null, lookup); + assert.deepEqual([selection.furniture, selection.room, selection.edge], [null, "a", null]); +}); + +test("the target is the most specific selected item", () => { + const { selection } = make(); + assert.equal(selection.target, null); + selection.select("room", "a", lookup); + assert.deepEqual(selection.target, { kind: "room", id: "a" }); + selection.select("furniture", "sofa", lookup); + assert.deepEqual(selection.target, { kind: "furniture", id: "sofa" }); + selection.device = "light.x"; + assert.deepEqual(selection.target, { kind: "device", id: "light.x" }); +}); + +test("every change asks for a redraw", () => { + const { selection, changes } = make(); + selection.room = "a"; + selection.corner = 1; + selection.select("room", "a", lookup); + assert.equal(changes(), 3); +}); diff --git a/frontend/src/components/editor/selection.ts b/frontend/src/components/editor/selection.ts new file mode 100644 index 0000000..54f4951 --- /dev/null +++ b/frontend/src/components/editor/selection.ts @@ -0,0 +1,112 @@ +// What is selected in the plan. One thing is selected at a time, but a room stays selected while one of its openings, furniture or +// devices is: the form of the item shows below the room. Setters ask the editor to draw again. + +export type ItemKind = "room" | "opening" | "furniture" | "device" | "outdoor" | "wall"; + +/** What choosing an item needs to know about the plan: which room a device or opening belongs to. */ +export interface SelectionLookup { + roomOfDevice(entityId: string): string | null; + roomOfOpening(openingId: string): string | null; +} + +export class Selection { + private readonly onChange: () => void; + private ids: Record = { room: null, opening: null, furniture: null, device: null, outdoor: null, wall: null }; + private cornerSel: number | null = null; + private edgeSel: number | null = null; + + constructor(onChange: () => void) { + this.onChange = onChange; + } + + private set(kind: ItemKind, id: string | null): void { + this.ids[kind] = id; + this.onChange(); + } + + get room(): string | null { + return this.ids.room; + } + set room(id: string | null) { + this.set("room", id); + } + + get opening(): string | null { + return this.ids.opening; + } + set opening(id: string | null) { + this.set("opening", id); + } + + get furniture(): string | null { + return this.ids.furniture; + } + set furniture(id: string | null) { + this.set("furniture", id); + } + + get device(): string | null { + return this.ids.device; + } + set device(id: string | null) { + this.set("device", id); + } + + get outdoor(): string | null { + return this.ids.outdoor; + } + set outdoor(id: string | null) { + this.set("outdoor", id); + } + + get wall(): string | null { + return this.ids.wall; + } + set wall(id: string | null) { + this.set("wall", id); + } + + /** The selected corner of the selected room. */ + get corner(): number | null { + return this.cornerSel; + } + set corner(index: number | null) { + this.cornerSel = index; + this.onChange(); + } + + /** The edge of the room that is highlighted, for instance while its height is edited. */ + get edge(): number | null { + return this.edgeSel; + } + set edge(index: number | null) { + this.edgeSel = index; + this.onChange(); + } + + /** Selects an item of one kind (null selects nothing of it) and deselects everything else, except the room it belongs to. */ + select(kind: ItemKind, id: string | null, lookup: SelectionLookup): void { + const room = this.ids.room; + const ids: Record = { room: null, opening: null, furniture: null, device: null, outdoor: null, wall: null }; + ids[kind] = id; + // areas outside and free walls belong to no room; everything else leaves the room selected + if (kind === "room") ids.room = id; + else if (kind !== "outdoor" && kind !== "wall") ids.room = room; + if (kind === "device" && id) ids.room = lookup.roomOfDevice(id) ?? ids.room; + if (kind === "opening" && id) ids.room = lookup.roomOfOpening(id) ?? ids.room; + // a corner stays selected only when its own room is selected again + if (kind !== "room" || id !== room) this.cornerSel = null; + this.edgeSel = null; + this.ids = ids; + this.onChange(); + } + + /** The selected item for locking and nudging: the most specific one first. */ + get target(): { kind: ItemKind; id: string } | null { + for (const kind of ["device", "opening", "furniture", "wall", "outdoor", "room"] as const) { + const id = this.ids[kind]; + if (id) return { kind, id }; + } + return null; + } +} diff --git a/frontend/src/components/editor/side-state.ts b/frontend/src/components/editor/side-state.ts new file mode 100644 index 0000000..5448084 --- /dev/null +++ b/frontend/src/components/editor/side-state.ts @@ -0,0 +1,131 @@ +// The small bits of state of the side panel's floor and room forms: which folding parts are open, the typed shift of a floor, the +// spot grid being planned, and the line shown after something was done. Setters ask the editor to draw again. + +import type { FurnitureType } from "../../model.ts"; + +/** The plan for a grid of spot lights in a room, before it is placed. */ +export interface SpotDraft { + type: FurnitureType; + rows: number; + cols: number; + /** The light all spots follow, or null for none. */ + entity: string | null; +} + +export class SideState { + private readonly onChange: () => void; + private menuOpen = false; + private packagesOpen = false; + private draft: SpotDraft | null = null; + private shiftXMetres = 0; + private shiftZMetres = 0; + private wholeHouse = false; + private line: string | null = null; + private query = ""; + private source: "area" | "other" | "none" = "area"; + private unfolded = new Set(); + private copyChoice: { furniture: boolean; devices: boolean; outdoor: boolean } | null = null; + + constructor(onChange: () => void) { + this.onChange = onChange; + } + + /** The list of Home Assistant floors to start a new floor from is open. */ + get floorMenu(): boolean { + return this.menuOpen; + } + set floorMenu(open: boolean) { + this.menuOpen = open; + this.onChange(); + } + + /** The choices for copying the floor while that dialog is open, else null. */ + get floorCopy(): { furniture: boolean; devices: boolean; outdoor: boolean } | null { + return this.copyChoice; + } + set floorCopy(choice: { furniture: boolean; devices: boolean; outdoor: boolean } | null) { + this.copyChoice = choice; + this.onChange(); + } + + /** The list of room packages is open. */ + get packages(): boolean { + return this.packagesOpen; + } + set packages(open: boolean) { + this.packagesOpen = open; + this.onChange(); + } + + get spots(): SpotDraft | null { + return this.draft; + } + set spots(draft: SpotDraft | null) { + this.draft = draft; + this.onChange(); + } + + get shiftX(): number { + return this.shiftXMetres; + } + set shiftX(metres: number) { + this.shiftXMetres = metres; + this.onChange(); + } + + get shiftZ(): number { + return this.shiftZMetres; + } + set shiftZ(metres: number) { + this.shiftZMetres = metres; + this.onChange(); + } + + /** Moving and turning apply to every floor together with the roof and meter. */ + get shiftAll(): boolean { + return this.wholeHouse; + } + set shiftAll(all: boolean) { + this.wholeHouse = all; + this.onChange(); + } + + /** The line under the forms that tells what the last action did. */ + get notice(): string | null { + return this.line; + } + set notice(text: string | null) { + this.line = text; + this.onChange(); + } + + /** The text typed into the search box of the device list. */ + get deviceQuery(): string { + return this.query; + } + set deviceQuery(text: string) { + this.query = text; + this.onChange(); + } + + /** Where the device list takes its entities from: the room's area, other areas, or entities without an area. */ + get deviceSource(): "area" | "other" | "none" { + return this.source; + } + set deviceSource(source: "area" | "other" | "none") { + this.source = source; + this.query = ""; + this.onChange(); + } + + /** The devices whose further entities are shown in the list. */ + isUnfolded(id: string): boolean { + return this.unfolded.has(id); + } + toggleUnfolded(id: string): void { + const next = new Set(this.unfolded); + if (!next.delete(id)) next.add(id); + this.unfolded = next; + this.onChange(); + } +} diff --git a/frontend/src/components/editor/styles.ts b/frontend/src/components/editor/styles.ts new file mode 100644 index 0000000..fadc4a4 --- /dev/null +++ b/frontend/src/components/editor/styles.ts @@ -0,0 +1,1999 @@ +import { css } from "lit"; + +/** The editor's own styles: the plan canvas, the side panel with its forms and libraries, the 3D pane and the phone layout. */ +export const editorStyles = css` + :host { + display: block; + height: 100%; + } + .nf-editor { + position: relative; + display: grid; + grid-template-columns: minmax(0, 1fr) 320px; + height: 100%; + min-height: 0; + } + .nf-editor:has(> .nf-side-strip) { + grid-template-columns: minmax(0, 1fr) 52px; + } + .nf-side-strip { + padding: 10px 6px; + gap: 8px; + align-items: center; + } + .nf-strip-btn { + width: 40px; + height: 40px; + border: 1px solid var(--nf-line); + border-radius: 12px; + background: var(--nf-chrome); + color: var(--nf-text); + font-size: 18px; + cursor: pointer; + } + .nf-strip-hot { + border-color: var(--nf-accent); + color: var(--nf-accent); + } + .nf-side-overlay { + position: absolute; + top: 0; + right: 0; + bottom: 0; + width: min(340px, 60%); + z-index: 6; + box-shadow: -12px 0 32px rgba(0, 0, 0, 0.45); + } + .nf-pin-row { + display: flex; + gap: 8px; + justify-content: flex-end; + } + .nf-3d-size { + display: inline-flex; + align-items: center; + gap: 4px; + color: var(--nf-muted); + font-size: 12px; + } + .nf-3d-size input { + width: 58px; + padding: 4px 6px; + font: inherit; + color: var(--nf-text); + background: var(--nf-chrome-solid); + border: 1px solid var(--nf-line); + border-radius: 8px; + } + .nf-3d-select { + font: inherit; + color: var(--nf-text); + background: var(--nf-chrome-solid); + border: 1px solid var(--nf-line); + border-radius: 999px; + padding: 4px 10px; + } + .nf-editor.nf-narrow { + grid-template-columns: 1fr; + grid-template-rows: minmax(360px, 62vh) auto; + height: auto; + } + .nf-main { + display: grid; + grid-template-columns: minmax(0, 1fr); + grid-template-rows: auto 1fr; + min-height: 0; + min-width: 0; + } + /* a row of tools wider than the plan scrolls inside its pill instead of pushing the plan over the side bar (#67) */ + .nf-toolbar .nf-seg { + max-width: 100%; + overflow-x: auto; + scrollbar-width: none; + } + .nf-toolbar .nf-seg > button { + flex: none; + } + .nf-toolbar { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; + padding: 10px 12px; + } + /* phones: the tools as one dropdown instead of a row of eleven buttons */ + .nf-tool-select { + font: inherit; + padding: 8px 10px; + border-radius: 10px; + border: 1px solid var(--nf-line); + background: var(--nf-bg2); + color: var(--nf-text); + } + .nf-warn { + color: var(--nf-warm); + font-size: 12.5px; + } + .nf-picture-group { + display: grid; + gap: 6px; + margin: 6px 0 10px; + padding: 8px; + border: 1px solid var(--nf-line); + border-radius: 10px; + } + .nf-picture-group > select { + min-width: 0; + } + .nf-picture-row { + display: grid; + grid-template-columns: 1fr auto auto; + gap: 6px; + align-items: center; + padding: 6px; + border-radius: 8px; + background: color-mix(in srgb, var(--nf-line) 40%, transparent); + } + .nf-picture-row input[type="url"] { + grid-column: 1 / -1; + min-width: 0; + } + .nf-picture-row > .nf-sub, + .nf-picture-row > .nf-picture-camera { + grid-column: 1 / -1; + } + .nf-picture-row.nf-rule-hit { + outline: 1px solid var(--nf-accent); + } + .nf-rule-now { + grid-column: 1 / -1; + } + .nf-rule-hit { + color: var(--nf-accent); + } + .nf-picture-reuse { + grid-column: 1 / -1; + display: flex; + flex-wrap: wrap; + gap: 4px; + } + .nf-picture-reuse-btn { + padding: 2px; + border: 1px solid var(--nf-line); + border-radius: 6px; + background: var(--nf-chrome-solid); + cursor: pointer; + } + .nf-picture-reuse-btn img { + display: block; + height: 28px; + max-width: 60px; + object-fit: contain; + } + .nf-picture-reuse-btn:hover { + border-color: var(--nf-accent); + } + .nf-picture-thumb { + max-height: 60px; + max-width: 100%; + border-radius: 6px; + justify-self: start; + } + .nf-picture-pick { + justify-self: start; + } + .nf-parking-row { + display: flex; + gap: 6px; + align-items: center; + margin: 4px 0; + } + .nf-parking-row input, + .nf-parking-row select { + flex: 1; + min-width: 0; + } + .nf-stage-pair { + display: flex; + min-height: 0; + min-width: 0; + } + .nf-stage-pair > .nf-canvas-wrap { + flex: 1 1 var(--nf-split, 55%); + min-width: 0; + } + .nf-split > .nf-canvas-wrap { + flex: 0 0 var(--nf-split, 55%); + } + .nf-split-handle { + flex: 0 0 8px; + cursor: col-resize; + background: var(--nf-line); + touch-action: none; + } + .nf-split-handle:hover { + background: var(--nf-accent); + } + .nf-editor-3d { + position: relative; + flex: 1 1 0; + min-width: 240px; + min-height: 0; + border-left: 1px solid var(--nf-line); + container-type: size; + container-name: nf; + } + .nf-editor-3d nf-view3d { + display: block; + height: 100%; + } + .nf-3d-walls { + position: absolute; + top: 10px; + left: 10px; + z-index: 3; + } + .nf-3d-bar { + position: absolute; + left: 50%; + bottom: 12px; + transform: translateX(-50%); + z-index: 3; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 8px; + max-width: calc(100% - 24px); + padding: 6px 8px 6px 14px; + border-radius: 999px; + background: var(--nf-chrome); + box-shadow: var(--nf-shadow); + font-size: 13px; + } + .nf-danger-chip { + color: var(--nf-danger, #ff6b7a); + } + .nf-narrow .nf-stage-pair.nf-split { + flex-direction: column; + } + .nf-narrow .nf-split > .nf-canvas-wrap { + flex: 1 1 auto; + } + .nf-narrow .nf-editor-3d { + flex: 0 0 42%; + min-width: 0; + border-left: none; + border-top: 1px solid var(--nf-line); + } + .nf-canvas-wrap { + position: relative; + min-height: 0; + overflow: hidden; + background: radial-gradient(ellipse at 50% 35%, var(--nf-bg2), var(--nf-bg) 75%); + } + svg.nf-plan { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + touch-action: none; + user-select: none; + -webkit-user-select: none; + cursor: default; + } + svg.nf-tool-rect, + svg.nf-tool-polygon { + cursor: crosshair; + } + .nf-grid-minor { + stroke: color-mix(in srgb, var(--nf-accent) 5%, transparent); + stroke-width: 1; + } + .nf-grid-major { + stroke: color-mix(in srgb, var(--nf-soft) 16%, transparent); + stroke-width: 1; + } + .nf-origin { + fill: color-mix(in srgb, var(--nf-soft) 50%, transparent); + } + .nf-ghost { + fill: none; + stroke: rgba(138, 155, 184, 0.35); + stroke-dasharray: 4 4; + } + .nf-void { + fill: rgba(138, 155, 184, 0.12); + stroke: rgba(138, 155, 184, 0.55); + stroke-dasharray: 2 3; + } + .nf-wall { + fill: #1b2a47; + } + .nf-wall-ext { + fill: #22345a; + } + .nf-room { + fill: color-mix(in srgb, var(--nf-accent) 5%, transparent); + stroke: color-mix(in srgb, var(--nf-accent) 75%, transparent); + stroke-width: 1.5; + stroke-linejoin: round; + cursor: pointer; + } + .nf-room:hover { + fill: color-mix(in srgb, var(--nf-accent) 9%, transparent); + } + .nf-room-sel { + fill: color-mix(in srgb, var(--nf-accent) 14%, transparent); + stroke: var(--nf-accent); + stroke-width: 2.5; + } + .nf-room-name { + fill: var(--nf-text); + font: 600 13px var(--nf-title-font); + text-anchor: middle; + } + .nf-room-area { + fill: var(--nf-muted); + font: 500 11.5px var(--nf-font); + text-anchor: middle; + font-variant-numeric: tabular-nums; + } + .nf-dim { + fill: var(--nf-accent); + font: 600 11.5px var(--nf-font); + text-anchor: middle; + font-variant-numeric: tabular-nums; + paint-order: stroke; + stroke: var(--nf-bg); + stroke-width: 3px; + } + .nf-vertex circle:not(.nf-hit) { + fill: var(--nf-bg); + stroke: var(--nf-accent); + stroke-width: 2; + } + .nf-vertex-sel circle:not(.nf-hit) { + fill: var(--nf-accent); + } + .nf-vertex, + .nf-mid { + cursor: grab; + } + .nf-hit { + fill: transparent; + } + .nf-mid circle:not(.nf-hit) { + fill: color-mix(in srgb, var(--nf-soft) 35%, transparent); + stroke: var(--nf-soft); + } + .nf-mid path { + stroke: var(--nf-text); + stroke-width: 1.5; + } + .nf-draft { + fill: rgba(255, 181, 71, 0.08); + stroke: var(--nf-warm); + stroke-width: 2; + stroke-dasharray: 6 4; + } + polyline.nf-draft { + fill: none; + } + .nf-draft-pt { + fill: var(--nf-warm); + } + .nf-draft-first { + fill: transparent; + stroke: var(--nf-warm); + stroke-width: 2; + } + .nf-cursor { + fill: var(--nf-warm); + } + .nf-guide { + stroke: rgba(255, 95, 210, 0.55); + stroke-dasharray: 3 5; + } + .nf-snap { + fill: none; + stroke: #ff5fd2; + stroke-width: 2; + } + .nf-dim { + font: 600 10px var(--nf-font); + fill: var(--nf-text); + paint-order: stroke; + stroke: rgba(10, 16, 32, 0.85); + stroke-width: 3px; + } + .nf-note rect { + fill: #ffe58a; + stroke: #8a6d00; + stroke-width: 1; + } + .nf-note text { + fill: #3a2e00; + font: 700 13px var(--nf-font); + pointer-events: none; + } + .nf-note-due rect { + fill: #ffa726; + } + .nf-note-sel rect { + stroke: var(--nf-accent, #03a9f4); + stroke-width: 3; + } + .nf-note { + cursor: pointer; + } + .nf-keys-open { + position: absolute; + right: 12px; + bottom: 30px; + width: 30px; + height: 30px; + border-radius: 50%; + border: 1px solid var(--nf-line); + background: var(--nf-chrome, rgba(20, 28, 48, 0.8)); + color: var(--nf-text); + font: 700 15px var(--nf-font); + cursor: pointer; + } + .nf-keys { + position: absolute; + inset: 0; + display: grid; + place-items: center; + background: rgba(0, 0, 0, 0.35); + z-index: 20; + } + .nf-keys-card { + max-width: min(520px, 92%); + max-height: 85%; + overflow: auto; + padding: 14px 18px; + border-radius: 14px; + background: var(--nf-surface, #1c1c1c); + box-shadow: var(--nf-shadow); + } + .nf-keys dl { + display: grid; + grid-template-columns: auto 1fr; + gap: 6px 14px; + margin: 8px 0 0; + font-size: 13px; + } + .nf-keys dt { + white-space: nowrap; + } + .nf-keys dd { + margin: 0; + color: var(--nf-muted); + } + .nf-keys kbd { + display: inline-block; + padding: 1px 6px; + border-radius: 5px; + border: 1px solid var(--nf-line); + font: 600 12px var(--nf-font); + } + .nf-tour { + position: absolute; + left: 16px; + bottom: 36px; + max-width: 340px; + padding: 12px 16px; + border-radius: 14px; + background: var(--nf-surface, #1c1c1c); + border: 1px solid var(--nf-accent, #03a9f4); + box-shadow: var(--nf-shadow); + z-index: 15; + } + .nf-tour h3 { + margin: 2px 0 6px; + } + .nf-tour p { + margin: 0 0 10px; + font-size: 13px; + line-height: 1.45; + } + .nf-tour-step { + font-size: 11px; + color: var(--nf-muted); + } + .nf-hint { + position: absolute; + left: 12px; + right: 12px; + bottom: 8px; + margin: 0; + font-size: 12px; + color: var(--nf-muted); + pointer-events: none; + } + .nf-side { + border-left: 1px solid var(--nf-line); + background: var(--nf-chrome-solid); + overflow-y: auto; + padding: 12px 14px 24px; + display: flex; + flex-direction: column; + gap: 18px; + min-height: 0; + } + .nf-narrow .nf-side { + border-left: none; + border-top: 1px solid var(--nf-line); + } + h3, + summary { + margin: 0 0 8px; + font-size: 11.5px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--nf-muted); + font-weight: 600; + } + summary { + cursor: pointer; + margin: 0; + } + details[open] > summary { + margin-bottom: 8px; + } + .nf-floor-list, + .nf-compass { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 14px; + padding: 10px 12px; + border: 1px solid var(--nf-line); + border-radius: 12px; + } + .nf-compass-dial { + width: 96px; + height: 96px; + flex: none; + } + .nf-compass-ring { + fill: none; + stroke: var(--nf-line); + stroke-width: 1.5; + } + .nf-compass-up { + fill: var(--nf-soft); + } + .nf-compass-n { + fill: var(--nf-accent); + } + .nf-compass-s { + fill: color-mix(in srgb, var(--nf-soft) 55%, transparent); + } + .nf-compass-label { + fill: var(--nf-text); + font-size: 12px; + font-weight: 700; + text-anchor: middle; + } + .nf-compass-label-s { + fill: var(--nf-soft); + } + .nf-map-settings { + display: grid; + gap: 8px; + } + .nf-map-move { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; + } + .nf-map-arrows { + display: flex; + gap: 6px; + } + .nf-compass-side { + display: grid; + gap: 6px; + flex: 1 1 200px; + } + .nf-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; + } + .nf-floor-list .nf-chip { + box-shadow: none; + border: 1px solid var(--nf-line); + } + .nf-version-actions { + display: inline-flex; + gap: 8px; + white-space: nowrap; + } + .nf-diff { + margin: 2px 0 10px 8px; + padding-left: 8px; + border-left: 2px solid color-mix(in srgb, var(--nf-soft, #8a9bb8) 35%, transparent); + } + .nf-diff-list { + list-style: none; + margin: 0; + padding: 0; + font-size: 0.9em; + line-height: 1.5; + } + .nf-check-open { + width: 100%; + margin: 0 0 8px; + } + .nf-check-floor { + margin: 10px 0 4px; + font-size: 0.85em; + color: var(--nf-muted, #8d9bbd); + } + .nf-check-list { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 6px; + } + .nf-check-list li { + display: grid; + grid-template-columns: auto 1fr auto; + gap: 8px; + align-items: center; + padding: 6px 8px; + border-radius: 8px; + background: color-mix(in srgb, var(--nf-soft, #8a9bb8) 10%, transparent); + } + .nf-check-names { + grid-column: 1 / -1; + font-size: 0.85em; + } + .nf-check-names ul { + list-style: none; + margin: 6px 0; + padding: 0; + display: grid; + gap: 4px; + } + .nf-check-names li { + display: flex; + gap: 6px; + align-items: center; + padding: 2px 0; + background: none; + } + .nf-check-names li small { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--nf-muted, #8d9bbd); + } + .nf-check-text { + font-size: 0.9em; + line-height: 1.3; + } + .nf-check-ok { + font-size: 1em; + } + .nf-studio-view { + display: block; + width: 100%; + max-height: 200px; + margin: 6px 0 10px; + background: color-mix(in srgb, var(--nf-soft, #8a9bb8) 10%, transparent); + border-radius: 8px; + } + .nf-studio-glow { + filter: drop-shadow(0 0 4px rgba(255, 214, 120, 0.8)); + } + .nf-lib-studio { + width: 100%; + margin: 4px 0 8px; + } + .nf-form { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px; + margin-top: 10px; + } + .nf-wide { + grid-column: 1 / -1; + } + .nf-room-list { + display: grid; + gap: 2px; + } + .nf-row { + display: flex; + justify-content: space-between; + gap: 8px; + font: inherit; + color: var(--nf-text); + background: none; + border: none; + border-bottom: 1px solid var(--nf-line); + padding: 9px 2px; + cursor: pointer; + text-align: left; + } + .nf-row:hover { + color: var(--nf-accent); + } + .nf-check { + display: flex; + align-items: center; + gap: 8px; + font-size: 13px; + color: var(--nf-muted); + } + .nf-check input { + accent-color: var(--nf-accent); + } + .nf-meter rect { + fill: #2a2a10; + stroke: #ffc633; + stroke-width: 1.5; + } + .nf-meter path { + fill: #ffc633; + } + .nf-packages { + display: grid; + gap: 6px; + margin-top: 10px; + } + .nf-packages .nf-btn { + display: grid; + text-align: left; + gap: 2px; + } + .nf-packages .nf-btn span { + font-weight: 400; + font-size: 12px; + color: var(--nf-muted); + } + .nf-arrows { + display: grid; + grid-template-columns: repeat(3, 52px); + grid-template-areas: ". up ." "left . right" ". down ."; + gap: 6px; + justify-content: center; + } + .nf-arrows .nf-btn { + font-size: 20px; + padding: 6px 0; + } + .nf-arrow-up { + grid-area: up; + } + .nf-arrow-left { + grid-area: left; + } + .nf-arrow-right { + grid-area: right; + } + .nf-arrow-down { + grid-area: down; + } + .nf-measure-list { + margin: 8px 0; + padding-left: 22px; + color: var(--nf-muted); + font-size: 13px; + font-variant-numeric: tabular-nums; + } + .nf-library { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); + gap: 6px; + margin-top: 8px; + } + .nf-library .nf-btn { + font-weight: 500; + font-size: 13px; + } + /* the library cards: a picture, the name, size and source, a star, and size chips for a model in several sizes */ + .nf-cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(86px, 1fr)); + gap: 8px; + margin-top: 8px; + } + .nf-card { + position: relative; + display: flex; + flex-direction: column; + border-radius: 14px; + background: var(--nf-chrome); + box-shadow: 0 0 0 1px var(--nf-line); + } + .nf-card-main { + display: flex; + flex-direction: column; + gap: 3px; + padding: 6px 6px 8px; + border: 0; + border-radius: 14px; + background: none; + color: var(--nf-text); + font: inherit; + text-align: left; + cursor: pointer; + } + .nf-card-main:hover, + .nf-card-main:focus-visible { + background: rgba(127, 127, 127, 0.1); + outline: none; + } + .nf-card-name { + font-size: 12px; + font-weight: 500; + line-height: 1.25; + overflow-wrap: anywhere; + hyphens: auto; + } + .nf-card-meta { + font-size: 11px; + color: var(--nf-muted); + line-height: 1.25; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .nf-card-star { + position: absolute; + top: 3px; + right: 3px; + width: 24px; + height: 24px; + border: 0; + border-radius: 50%; + background: rgba(0, 0, 0, 0.25); + color: var(--nf-muted); + font-size: 15px; + line-height: 1; + cursor: pointer; + } + .nf-card-star[aria-pressed="true"] { + color: var(--nf-warm, #ffb547); + } + .nf-card-sizes { + display: flex; + flex-wrap: wrap; + gap: 4px; + padding: 0 6px 8px; + } + .nf-size { + min-width: 34px; + padding: 3px 6px; + border: 1px solid var(--nf-line); + border-radius: 999px; + background: none; + color: var(--nf-muted); + font: inherit; + font-size: 11px; + font-variant-numeric: tabular-nums; + cursor: pointer; + } + .nf-size[aria-pressed="true"] { + border-color: var(--nf-accent); + color: var(--nf-accent); + } + .nf-lib-chips { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 8px; + } + .nf-lib-chip { + min-height: 30px; + padding: 4px 10px; + font-size: 12px; + box-shadow: 0 0 0 1px var(--nf-line); + } + .nf-lib-chip[aria-pressed="true"] { + color: var(--nf-accent); + box-shadow: 0 0 0 1px var(--nf-accent); + } + .nf-lib-all { + width: 100%; + margin-top: 12px; + } + /* the background picture while it is edited: a dashed frame and a corner handle */ + .nf-bg-frame { + fill: none; + stroke: var(--nf-accent); + stroke-width: 1.5; + stroke-dasharray: 6 4; + pointer-events: none; + } + .nf-bg-handle { + fill: var(--nf-accent); + stroke: #041018; + stroke-width: 2; + cursor: nwse-resize; + } + .nf-furn-body { + fill: color-mix(in srgb, var(--nf-soft) 10%, transparent); + stroke: color-mix(in srgb, var(--nf-soft) 55%, transparent); + stroke-width: 1.2; + vector-effect: non-scaling-stroke; + cursor: grab; + } + .nf-furn-sym * { + fill: none; + stroke: rgba(150, 175, 255, 0.55); + stroke-width: 1; + vector-effect: non-scaling-stroke; + pointer-events: none; + } + .nf-furn-sym .nf-sym-fill { + fill: color-mix(in srgb, var(--nf-soft) 28%, transparent); + } + .nf-furn-sym .nf-sym-dash { + stroke-dasharray: 6 4; + } + .nf-furn-sym .nf-sym-strong { + stroke: var(--nf-accent); + stroke-width: 2; + } + .nf-out polygon { + fill: color-mix(in srgb, var(--nf-soft) 6%, transparent); + stroke: color-mix(in srgb, var(--nf-soft) 40%, transparent); + stroke-width: 1; + stroke-dasharray: 4 3; + cursor: grab; + } + .nf-out-lawn polygon, + .nf-out-bed polygon, + .nf-out-wild polygon, + .nf-out-hedge polygon { + fill: rgba(61, 224, 160, 0.1); + stroke: rgba(61, 224, 160, 0.5); + } + .nf-out-pool 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-free-wall { + cursor: grab; + } + .nf-vertex-no { + fill: var(--nf-accent); + font-size: 11px; + font-weight: 700; + pointer-events: none; + } + .nf-edge-box { + margin: 12px 0; + padding: 10px 12px; + border: 1px solid color-mix(in srgb, var(--nf-accent) 45%, transparent); + border-radius: 12px; + background: color-mix(in srgb, var(--nf-accent) 6%, transparent); + } + .nf-edge-box h4 { + margin: 0 0 4px; + color: var(--nf-accent); + font-size: 13px; + letter-spacing: 0.06em; + text-transform: uppercase; + } + /* a wall row: name and length, the height, then the buttons (full height, no wall, cut) in one line; + a split point gets a line of its own below */ + .nf-edge-height { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: end; + padding: 4px 6px; + margin: 0 -6px; + border-radius: 8px; + } + .nf-edge-height > span:first-child { + flex: 1 1 84px; + min-width: 84px; + } + .nf-ble-bars { + display: grid; + gap: 6px; + margin: 10px 0; + } + .nf-ble-row { + display: grid; + grid-template-columns: minmax(80px, 1fr) 2fr 36px; + align-items: center; + gap: 8px; + font-size: 12px; + } + .nf-ble-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--nf-text); + } + .nf-ble-track { + height: 8px; + border-radius: 4px; + background: rgba(127, 127, 127, 0.25); + overflow: hidden; + } + .nf-ble-fill { + display: block; + height: 100%; + border-radius: 4px; + background: var(--nf-accent, #00e5ff); + transition: width 0.4s ease-out; + } + .nf-ble-db { + text-align: right; + font-variant-numeric: tabular-nums; + color: var(--nf-muted); + } + .nf-ble-now { + margin: 4px 0 10px; + color: var(--nf-text); + } + .nf-ble-learn { + margin: 8px 0 14px; + padding: 10px 12px; + border: 1px solid var(--nf-border, rgba(127, 127, 127, 0.3)); + border-radius: 10px; + } + .nf-chips { + display: flex; + flex-wrap: wrap; + gap: 6px; + } + .nf-chips .nf-chip { + display: inline-flex; + align-items: center; + gap: 4px; + cursor: default; + color: var(--nf-text); + } + .nf-chip-x { + border: 0; + background: none; + color: var(--nf-muted); + font: inherit; + font-size: 16px; + line-height: 1; + padding: 0 2px; + cursor: pointer; + } + .nf-quiet-time > span { + display: flex; + align-items: center; + gap: 6px; + } + .nf-quiet-time input { + flex: 1 1 0; + } + .nf-edge-height > .nf-field { + flex: 1 1 90px; + min-width: 0; + } + .nf-edge-height > .nf-muted { + flex: 1 1 90px; + align-self: center; + } + .nf-edge-height > .nf-btn { + flex: 0 0 auto; + white-space: nowrap; + padding-left: 10px; + padding-right: 10px; + } + .nf-edge-height > .nf-split-row { + flex: 1 1 100%; + display: flex; + gap: 6px; + align-items: end; + } + .nf-edge-height > .nf-split-row > .nf-field { + flex: 1; + } + .nf-edge-on { + background: color-mix(in srgb, var(--nf-accent) 14%, transparent); + } + .nf-edge-low b { + color: var(--nf-accent); + } + .nf-wall-low { + opacity: 0.55; + } + .nf-dev-source { + display: flex; + margin: 8px 0; + } + .nf-dev-source button { + flex: 1 1 0; + min-width: 0; + padding: 6px 4px; + font-size: 12px; + line-height: 1.2; + white-space: normal; + text-align: center; + border-radius: 10px; + } + .nf-place-all { + margin: 10px 0 0; + } + .nf-roof-sec polygon { + fill: color-mix(in srgb, #ffb547 10%, transparent); + stroke: #ffb547; + stroke-width: 2; + stroke-dasharray: 8 6; + cursor: move; + } + .nf-roof-sel polygon { + fill: color-mix(in srgb, var(--nf-accent) 14%, transparent); + stroke: var(--nf-accent); + stroke-dasharray: none; + } + /* solar modules: dark blue panes with a light frame, so they do not look like a selected room */ + .nf-roofwin polygon { + fill: color-mix(in srgb, #2b6b8f 70%, transparent); + stroke: #e3e9f5; + stroke-width: 2; + cursor: move; + } + .nf-chimney polygon { + fill: color-mix(in srgb, #7a4a4a 75%, transparent); + stroke: #e3e9f5; + stroke-width: 2; + cursor: move; + } + .nf-roofwin-sel polygon { + stroke: #ffd75a; + } + .nf-tool-energy .nf-roof-layer { + opacity: 0.45; + } + .nf-tool-energy .nf-energy-item { + pointer-events: auto; + } + .nf-swatches { + display: flex; + flex-wrap: wrap; + gap: 8px; + padding-top: 4px; + } + .nf-stair-shapes { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 6px; + } + .nf-stair-shape { + display: flex; + flex-direction: column; + align-items: center; + gap: 2px; + padding: 6px 4px; + font-size: 11px; + line-height: 1.2; + text-align: center; + } + .nf-stair-shape[aria-checked="true"] { + border-color: var(--nf-accent); + color: var(--nf-accent); + box-shadow: 0 0 0 1px var(--nf-accent) inset; + } + .nf-swatch { + width: 30px; + height: 30px; + padding: 0; + border-radius: 50%; + border: 2px solid var(--nf-line); + background: var(--sw); + cursor: pointer; + } + .nf-swatch[aria-checked="true"] { + border-color: var(--nf-text); + outline: 2px solid var(--nf-accent); + outline-offset: 2px; + } + .nf-energy-marker { + cursor: move; + } + .nf-checklist .nf-chk { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + margin: 2px 0; + padding: 6px 8px; + border: 0; + border-radius: 8px; + background: transparent; + color: inherit; + font: inherit; + text-align: left; + text-decoration: none; + cursor: pointer; + } + .nf-checklist .nf-chk:hover { + background: rgba(127, 127, 127, 0.12); + } + .nf-checklist .nf-chk span { + width: 18px; + text-align: center; + font-weight: 700; + } + .nf-chk-ok span { + color: #59ff8c; + } + .nf-chk-todo span { + color: #ffc633; + } + .nf-chk-opt { + opacity: 0.75; + } + .nf-teaser-on { + border-color: rgba(89, 255, 140, 0.5); + } + .nf-teaser { + margin-top: 12px; + padding: 12px; + border-radius: 14px; + border: 1px solid color-mix(in srgb, #ffd75a 45%, transparent); + background: linear-gradient(160deg, color-mix(in srgb, #ffd75a 10%, transparent), transparent 60%); + } + .nf-teaser-head { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; + margin-bottom: 8px; + } + .nf-teaser-soon { + font-size: 11px; + font-weight: 700; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--nf-chrome-solid); + background: #ffd75a; + border-radius: 999px; + padding: 2px 8px; + white-space: nowrap; + } + .nf-teaser img { + display: block; + width: 100%; + border-radius: 10px; + border: 1px solid color-mix(in srgb, var(--nf-accent) 40%, transparent); + } + .nf-teaser ul { + margin: 8px 0 4px; + padding-left: 18px; + font-size: 13px; + } + /* the roof and energy tools say what can be moved there (everything else is locked) */ + .nf-tool-note { + position: absolute; + top: 8px; + left: 50%; + transform: translateX(-50%); + z-index: 2; + max-width: calc(100% - 24px); + padding: 5px 12px; + border-radius: 999px; + background: color-mix(in srgb, var(--nf-chrome-solid) 85%, transparent); + border: 1px solid color-mix(in srgb, #ffd75a 60%, transparent); + color: #ffe7a3; + font-size: 12px; + text-align: center; + pointer-events: none; + } + .nf-route line { + stroke: var(--nf-warm); + stroke-width: 2; + stroke-dasharray: 6 4; + opacity: 0.7; + } + .nf-route circle { + fill: var(--nf-warm); + opacity: 0.8; + } + .nf-route circle.nf-route-riser { + fill: none; + stroke: var(--nf-warm); + stroke-width: 2; + } + .nf-route-drawing line { + stroke: var(--nf-accent); + stroke-dasharray: none; + opacity: 1; + } + .nf-route-drawing circle { + fill: var(--nf-accent); + opacity: 1; + } + .nf-route-drawing circle.nf-route-riser { + fill: none; + stroke: var(--nf-accent); + } + .nf-route text { + fill: var(--nf-text); + font-size: 11px; + pointer-events: none; + } + .nf-routes { + pointer-events: none; + } + .nf-energy-marker circle { + fill: color-mix(in srgb, var(--nf-chrome-solid) 80%, transparent); + stroke: #ffd75a; + stroke-width: 2; + } + .nf-energy-marker-sel circle { + stroke: var(--nf-accent); + stroke-width: 3; + fill: color-mix(in srgb, var(--nf-accent) 25%, var(--nf-chrome-solid)); + } + .nf-energy-marker text { + text-anchor: middle; + pointer-events: none; + } + .nf-energy-icon { + font-size: 17px; + } + .nf-energy-name { + font-size: 11px; + font-weight: 700; + fill: #ffd75a; + paint-order: stroke; + stroke: rgba(0, 0, 0, 0.65); + stroke-width: 3px; + } + .nf-solar polygon { + fill: color-mix(in srgb, #1b3a8f 75%, transparent); + stroke: #9fb8ff; + stroke-width: 1.5; + cursor: move; + } + .nf-solar-sel polygon { + fill: color-mix(in srgb, #1b3a8f 80%, transparent); + stroke: #ffd75a; + stroke-width: 2; + } + .nf-solar polygon.nf-solar-off { + fill: transparent; + stroke-dasharray: 4 4; + stroke-width: 1.5; + } + .nf-solar-pick polygon { + cursor: pointer; + } + .nf-roof-ridge line { + stroke: #ffb547; + stroke-width: 2.5; + pointer-events: none; + } + .nf-roof-sel .nf-roof-ridge line { + stroke: var(--nf-accent); + } + .nf-roof-sec text { + fill: #ffd28a; + font-size: 12px; + font-weight: 700; + text-anchor: middle; + paint-order: stroke; + stroke: rgba(0, 0, 0, 0.6); + stroke-width: 3px; + pointer-events: none; + } + .nf-tool-energy .nf-room, + .nf-tool-energy [data-furniture], + .nf-tool-energy [data-device], + .nf-tool-energy [data-opening], + .nf-tool-energy [data-free-wall], + .nf-tool-energy [data-outdoor], + .nf-tool-energy .nf-roof-layer, + .nf-tool-roof .nf-room, + .nf-tool-roof [data-furniture], + .nf-tool-roof [data-device], + .nf-tool-roof [data-opening], + .nf-tool-roof [data-free-wall], + .nf-tool-roof [data-outdoor] { + pointer-events: none; + } + .nf-dev-area { + margin: 10px 0 2px; + color: var(--nf-muted); + font-size: 12px; + letter-spacing: 0.06em; + text-transform: uppercase; + } + .nf-h3row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + } + .nf-h3row h3 { + margin-bottom: 0; + } + .nf-fix { + min-height: 30px; + padding: 4px 10px; + font-size: 13px; + } + .nf-fix[aria-pressed="true"] { + border-color: var(--nf-accent); + color: var(--nf-accent); + } + .nf-lock { + font-size: 13px; + text-anchor: middle; + pointer-events: none; + } + .nf-hint-fixed { + color: var(--nf-accent); + } + .nf-ctx { + position: absolute; + z-index: 5; + display: flex; + flex-direction: column; + min-width: 170px; + padding: 4px; + border: 1px solid var(--nf-line); + border-radius: 10px; + background: var(--nf-panel, #111a2e); + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45); + } + .nf-ctx button { + padding: 8px 12px; + border: none; + border-radius: 7px; + background: none; + color: inherit; + font: inherit; + text-align: left; + cursor: pointer; + } + .nf-ctx button:hover:not(:disabled) { + background: color-mix(in srgb, var(--nf-accent) 16%, transparent); + } + .nf-ctx button:disabled { + opacity: 0.45; + cursor: default; + } + .nf-ctx-danger { + color: var(--nf-danger, #ff6b7a) !important; + } + .nf-edge-hi { + stroke: var(--nf-accent); + stroke-width: 6; + stroke-linecap: round; + filter: drop-shadow(0 0 6px var(--nf-accent)); + } + .nf-free-wall .nf-hit { + stroke: transparent; + stroke-width: 18; + } + .nf-free-wall-line { + stroke: transparent; + stroke-width: 1; + } + .nf-free-wall-sel .nf-free-wall-line { + stroke: var(--nf-accent); + stroke-width: 2; + stroke-dasharray: 6 4; + } + .nf-draft-wall { + stroke-width: 4; + } + .nf-open-passage { + stroke-dasharray: 4 4; + } + .nf-out-sel polygon { + stroke: var(--nf-accent); + stroke-width: 2; + stroke-dasharray: none; + } + .nf-out text { + fill: var(--nf-muted); + font-size: 11px; + text-anchor: middle; + pointer-events: none; + } + .nf-furn-lit .nf-furn-body { + fill: rgba(255, 181, 71, 0.35); + stroke: var(--nf-warm); + } + .nf-rotate { + cursor: grab; + } + .nf-preview { + position: fixed; + z-index: 20; + width: 180px; + padding: 8px 8px 10px; + border-radius: 16px; + background: var(--nf-bg2); + box-shadow: var(--nf-shadow), 0 0 0 1px var(--nf-line); + text-align: center; + pointer-events: none; + animation: nf-pop 120ms ease-out; + } + @keyframes nf-pop { + from { + opacity: 0; + transform: translateX(8px); + } + } + .nf-preview img, + .nf-preview-wait { + display: block; + width: 164px; + height: 164px; + } + .nf-preview-wait { + margin: 0 auto; + border-radius: 12px; + background: rgba(127, 127, 127, 0.1); + } + .nf-preview b { + display: block; + margin-top: 2px; + font-size: 13px; + color: #e8eeff; + } + .nf-lib-badge { + margin-left: 4px; + color: var(--nf-accent); + vertical-align: -2px; + } + .nf-pin { + border: 0; + background: none; + padding: 2px 6px; + font-size: 17px; + line-height: 1; + color: var(--nf-muted); + cursor: pointer; + } + .nf-pin-on { + color: var(--nf-warm); + } + .nf-back { + margin-bottom: 12px; + } + .nf-presets { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-bottom: 10px; + } + .nf-resize { + cursor: nwse-resize; + } + .nf-resize rect { + fill: var(--nf-accent); + stroke: var(--nf-chrome-solid); + stroke-width: 1.5; + } + .nf-code { + display: block; + font: 12px/1.4 ui-monospace, Menlo, Consolas, monospace; + padding: 6px 8px; + border-radius: 8px; + background: rgba(127, 127, 127, 0.12); + user-select: all; + word-break: break-all; + } + .nf-shift { + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; + } + .nf-shift input { + width: 5.5em; + } + .nf-headroom { + stroke: rgba(255, 214, 90, 0.55); + stroke-width: 1; + stroke-dasharray: 6 4; + pointer-events: none; + } + .nf-headroom-label { + font-size: 10px; + fill: rgba(255, 214, 90, 0.75); + text-anchor: middle; + pointer-events: none; + } + .nf-split-mark { + stroke: color-mix(in srgb, var(--nf-accent) 90%, transparent); + stroke-width: 2; + pointer-events: none; + } + .nf-floor-menu { + display: flex; + flex-direction: column; + gap: 6px; + margin: 8px 0; + padding: 10px; + border-radius: 12px; + background: rgba(127, 127, 127, 0.1); + max-width: 100%; + box-sizing: border-box; + } + .nf-icon-row { + display: flex; + align-items: center; + gap: 8px; + } + .nf-icon-row input { + flex: 1; + min-width: 0; + } + .nf-icon-row ha-icon { + --mdc-icon-size: 22px; + color: var(--nf-accent); + } + .nf-floor-menu .nf-btn { + text-align: left; + width: 100%; + min-width: 0; + white-space: normal; + overflow-wrap: anywhere; + } + .nf-rotate line { + stroke: var(--nf-accent); + stroke-dasharray: 3 3; + } + .nf-rotate circle:not(.nf-hit) { + fill: var(--nf-chrome-solid); + stroke: var(--nf-accent); + stroke-width: 2; + } + .nf-rotate path { + fill: none; + stroke: var(--nf-accent); + stroke-width: 1.5; + stroke-linecap: round; + } + .nf-lib-toggle { + display: flex; + align-items: center; + gap: 6px; + width: 100%; + padding: 6px 0; + border: 0; + background: none; + font: inherit; + cursor: pointer; + text-align: left; + } + .nf-lib-toggle:hover { + color: var(--nf-text); + } + .nf-lib-caret { + width: 12px; + color: var(--nf-accent); + } + .nf-lib-count { + margin-left: auto; + font-weight: 500; + letter-spacing: 0; + text-transform: none; + opacity: 0.7; + } + .nf-lib-head { + margin: 10px 0 0; + font-size: 11px; + font-weight: 600; + letter-spacing: 0.05em; + text-transform: uppercase; + color: var(--nf-muted); + } + .nf-furn-front { + stroke: var(--nf-accent); + stroke-width: 2.5; + vector-effect: non-scaling-stroke; + opacity: 0.8; + pointer-events: none; + } + .nf-furn text { + fill: var(--nf-muted); + font-size: 11px; + text-anchor: middle; + pointer-events: none; + } + .nf-furn-sel .nf-furn-body { + fill: color-mix(in srgb, var(--nf-accent) 16%, transparent); + stroke: var(--nf-accent); + stroke-width: 2; + } + .nf-open { + cursor: grab; + } + .nf-open-gap { + fill: var(--nf-chrome-solid); + stroke: none; + } + .nf-open path, + .nf-open line { + fill: none; + stroke-width: 1.6; + stroke-linecap: round; + } + .nf-open-door path { + stroke: var(--nf-warm); + stroke-dasharray: 3 3; + } + .nf-open-front path, + .nf-open-door line { + stroke: var(--nf-warm); + stroke-width: 3; + stroke-dasharray: none; + } + .nf-open-door line.nf-open-pane { + stroke: var(--nf-accent); + stroke-width: 2; + } + .nf-open-garage line { + stroke: var(--nf-warm); + stroke-width: 3; + } + .nf-open-track { + stroke: var(--nf-warm); + stroke-dasharray: 4 4; + opacity: 0.6; + } + .nf-open-window line { + stroke: var(--nf-accent); + stroke-width: 2; + } + .nf-open-sel .nf-open-gap { + fill: color-mix(in srgb, var(--nf-accent) 25%, transparent); + } + .nf-open-sel path, + .nf-open-sel line { + stroke-width: 2.4; + } + .nf-bg-rotate { + cursor: grab; + } + .nf-bg-ruler line { + stroke: #ffb020; + stroke-width: 2.5; + stroke-dasharray: 6 4; + } + .nf-bg-ruler circle { + fill: #ffb020; + stroke: #1a1000; + stroke-width: 1.5; + } + .nf-own-button { + padding: 10px 0; + border-top: 1px solid var(--nf-line); + } + .nf-own-button textarea { + font: 12px/1.4 ui-monospace, monospace; + width: 100%; + box-sizing: border-box; + padding: 6px 8px; + color: var(--nf-text); + background: color-mix(in srgb, var(--nf-text) 4%, transparent); + border: 1px solid var(--nf-line); + border-radius: 8px; + } + .nf-search { + position: sticky; + top: 0; + z-index: 2; + background-color: var(--nf-panel, #0d1424); + width: 100%; + box-sizing: border-box; + font: inherit; + font-size: 14px; + color: var(--nf-text); + background: color-mix(in srgb, var(--nf-text) 4%, transparent); + border: 1px solid var(--nf-line); + border-radius: 8px; + padding: 7px 9px; + margin: 2px 0 6px; + } + .nf-more { + font: inherit; + font-size: 12px; + color: var(--nf-muted); + background: none; + border: none; + text-align: left; + padding: 2px 26px 8px; + cursor: pointer; + } + .nf-more:hover { + color: var(--nf-accent); + } + .nf-dev-hidden .nf-dev-name { + opacity: 0.45; + text-decoration: line-through; + } + .nf-dev-extra { + padding-left: 18px; + font-size: 13px; + } + .nf-dev-title { + display: flex; + align-items: center; + gap: 8px; + margin: 0 0 8px; + font-weight: 600; + } + .nf-notice { + color: var(--nf-accent); + } + .nf-device-sel circle:not(.nf-hit) { + stroke: var(--nf-accent); + stroke-width: 3; + } + .nf-dev-row { + align-items: center; + cursor: default; + } + .nf-dev-row:hover { + color: var(--nf-text); + } + .nf-dev-name { + display: inline-flex; + align-items: center; + gap: 8px; + min-width: 0; + font: inherit; + color: inherit; + background: none; + border: none; + padding: 0; + text-align: left; + cursor: pointer; + } + .nf-dev-name:disabled { + cursor: default; + } + .nf-dev-name span { + overflow: hidden; + text-overflow: ellipsis; + } + .nf-dev-name svg { + flex: none; + } + .nf-color-row { + display: flex; + align-items: center; + gap: 8px; + } + .nf-color-row input[type="color"] { + width: 48px; + height: 32px; + padding: 0; + border: none; + background: none; + } + .nf-link { + font: inherit; + font-size: 13px; + font-weight: 600; + color: var(--nf-accent); + background: none; + border: none; + padding: 4px 2px; + cursor: pointer; + white-space: nowrap; + } + .nf-wide-btn { + width: 100%; + margin-bottom: 6px; + } + .nf-device { + cursor: grab; + } + .nf-wedge path, + .nf-wedge circle:not(.nf-hit) { + fill: color-mix(in srgb, var(--nf-accent) 12%, transparent); + stroke: color-mix(in srgb, var(--nf-accent) 45%, transparent); + stroke-width: 1; + pointer-events: none; + } + .nf-wedge-sel path, + .nf-wedge-sel > circle { + fill: color-mix(in srgb, var(--nf-accent) 20%, transparent); + stroke: var(--nf-accent); + } + .nf-wedge .nf-rotate circle { + pointer-events: auto; + } + .nf-device circle:not(.nf-hit) { + fill: #111a2e; + stroke: var(--nf-soft); + stroke-width: 1.5; + vector-effect: non-scaling-stroke; + } + .nf-device path { + fill: none; + stroke: var(--nf-text); + stroke-width: 2.6; + stroke-linecap: round; + stroke-linejoin: round; + } + .nf-device-on circle:not(.nf-hit) { + fill: var(--nf-warm); + stroke: var(--nf-warm); + } + .nf-device-on path { + stroke: #2a1a00; + } + .nf-device-icon { + pointer-events: none; + overflow: visible; + } + .nf-device-icon ha-icon { + display: block; + --mdc-icon-size: 16px; + color: var(--nf-text); + } + .nf-device-on .nf-device-icon ha-icon { + color: #2a1a00; + } + .nf-dev-icon { + --mdc-icon-size: 18px; + flex: none; + } + .nf-muted { + color: var(--nf-muted); + font-variant-numeric: tabular-nums; + } + .nf-points { + margin: 12px 0; + } + .nf-point { + display: grid; + grid-template-columns: 18px 1fr 1fr auto; + gap: 6px; + align-items: end; + padding: 4px 0; + } + .nf-point-sel .nf-muted { + color: var(--nf-accent); + } + .nf-point .nf-btn { + min-height: 34px; + padding: 4px 10px; + } + .nf-upload { + position: relative; + text-align: center; + overflow: hidden; + } + .nf-upload input { + position: absolute; + inset: 0; + opacity: 0; + cursor: pointer; + } + .nf-sub { + margin: 8px 0 0; + font-size: 12.5px; + color: var(--nf-muted); + } + .nf-note { + margin: 0; + font-size: 12.5px; + color: var(--nf-warm); + } +`; diff --git a/frontend/src/components/editor/thumbs.ts b/frontend/src/components/editor/thumbs.ts new file mode 100644 index 0000000..3e44100 --- /dev/null +++ b/frontend/src/components/editor/thumbs.ts @@ -0,0 +1,194 @@ +// Pictures of the furniture for the library cards. They are drawn by the 3D bundle one at a time while the browser is idle, only for +// cards that scroll into view, and kept in IndexedDB so the next visit shows them at once. Weak tablets get no pictures at all. + +import { LitElement, css, html, nothing } from "lit"; +import { isLowEnd } from "../../hardware.ts"; +import { LAMP_MODEL } from "../../model.ts"; +import { load3d } from "../../load3d.ts"; +import { furnitureSize, packItem, type FurniturePack } from "../../packs.ts"; + +const SIZE = 112; +const DB = "nextfloor-thumbs"; + +/** A short hash of a text (FNV-1a), so a changed pack item gets a new picture. */ +function hashOf(text: string): string { + let h = 0x811c9dc5; + for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193); + return (h >>> 0).toString(36); +} + +/** The key a picture is kept under: the type, plus what the item looks like for pack items. */ +export function thumbKey(type: string): string { + const item = packItem(type); + return `${type}|${item ? hashOf(JSON.stringify(item)) : "b"}|${SIZE}`; +} + +function openDb(): Promise { + return new Promise((resolve) => { + try { + const req = indexedDB.open(DB, 1); + req.onupgradeneeded = () => req.result.createObjectStore("thumbs"); + req.onsuccess = () => resolve(req.result); + req.onerror = () => resolve(null); + } catch { + resolve(null); + } + }); +} + +class ThumbStore { + readonly enabled = !isLowEnd(); + private readonly memory = new Map(); + private readonly waiting = new Map void)[]>(); + private readonly queue: string[] = []; + private db: Promise | null = null; + private running = false; + packs: readonly FurniturePack[] = []; + + /** The picture if it is already known, without waiting. */ + cached(type: string): string | undefined { + return this.memory.get(thumbKey(type)); + } + + /** The picture of a type: from memory, from the browser's store, or drawn. */ + get(type: string): Promise { + const key = thumbKey(type); + const known = this.memory.get(key); + if (known) return Promise.resolve(known); + return new Promise((resolve) => { + const list = this.waiting.get(key); + if (list) return void list.push(resolve); + this.waiting.set(key, [resolve]); + void this.lookUp(type, key); + }); + } + + private settle(key: string, url: string | null): void { + if (url) this.memory.set(key, url); + for (const resolve of this.waiting.get(key) ?? []) resolve(url); + this.waiting.delete(key); + } + + private async lookUp(type: string, key: string): Promise { + this.db ??= openDb(); + const db = await this.db; + const stored = db + ? await new Promise((resolve) => { + try { + const req = db.transaction("thumbs").objectStore("thumbs").get(key); + req.onsuccess = () => resolve(typeof req.result === "string" ? req.result : null); + req.onerror = () => resolve(null); + } catch { + resolve(null); + } + }) + : null; + if (stored) return this.settle(key, stored); + this.queue.push(type); + this.pump(); + } + + /** Draws the queued pictures one by one, each in an idle moment, so scrolling stays smooth. */ + private pump(): void { + if (this.running) return; + const type = this.queue.shift(); + if (!type) return; + this.running = true; + const idle = (window as Window & { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number }).requestIdleCallback; + const next = (cb: () => void) => (idle ? idle(cb, { timeout: 300 }) : setTimeout(cb, 16)); + next(async () => { + const key = thumbKey(type); + let url: string | null = null; + try { + const [w, d, h] = furnitureSize(type); + url = (await load3d()).furniturePreview({ type, w, d, h, variant: null, lamp: LAMP_MODEL[type] ?? null }, SIZE, [...this.packs]); + void this.keep(key, url); + } catch { + url = null; + } + this.settle(key, url); + this.running = false; + this.pump(); + }); + } + + private async keep(key: string, url: string): Promise { + const db = await this.db; + try { + db?.transaction("thumbs", "readwrite").objectStore("thumbs").put(url, key); + } catch { + // a full or blocked store only costs drawing the picture again next time + } + } +} + +export const thumbs = new ThumbStore(); + +let observer: IntersectionObserver | null = null; +const seen = (entries: IntersectionObserverEntry[]) => { + for (const entry of entries) if (entry.isIntersecting) (entry.target as NfThumb).visible(); +}; + +/** A furniture picture that is drawn once it scrolls into view; an empty frame until then. */ +export class NfThumb extends LitElement { + static properties = { type: {}, _url: { state: true } }; + declare type: string; + declare _url: string | null; + + static styles = css` + :host { + display: block; + aspect-ratio: 4 / 3; + border-radius: 10px; + background: rgba(127, 127, 127, 0.08); + overflow: hidden; + } + img { + display: block; + width: 100%; + height: 100%; + object-fit: contain; + } + `; + + constructor() { + super(); + this.type = ""; + this._url = null; + } + + connectedCallback(): void { + super.connectedCallback(); + if (!thumbs.enabled) return; + this._url = thumbs.cached(this.type) ?? null; + if (this._url) return; + observer ??= new IntersectionObserver(seen, { rootMargin: "120px" }); + observer.observe(this); + } + + disconnectedCallback(): void { + super.disconnectedCallback(); + observer?.unobserve(this); + } + + updated(changed: Map): void { + if (changed.has("type") && changed.get("type") !== undefined) { + this._url = thumbs.cached(this.type) ?? null; + if (!this._url && thumbs.enabled) observer?.observe(this); + } + } + + visible(): void { + observer?.unobserve(this); + const type = this.type; + void thumbs.get(type).then((url) => { + if (this.type === type) this._url = url; + }); + } + + render() { + return this._url ? html`` : nothing; + } +} + +if (!customElements.get("nf-thumb")) customElements.define("nf-thumb", NfThumb); diff --git a/frontend/src/components/editor/wall-view.ts b/frontend/src/components/editor/wall-view.ts new file mode 100644 index 0000000..144f751 --- /dev/null +++ b/frontend/src/components/editor/wall-view.ts @@ -0,0 +1,296 @@ +// The wall view of the editor: one wall from the front, drawn to scale, with its doors, windows and the furniture against it. Drag a +// piece along the wall (and up or down when it hangs on the wall), or type its distance from the left end and its height; the +// distances to both ends show while something is selected. Every move is one undoable step. + +import { LitElement, css, html, nothing, svg, type PropertyValues } from "lit"; +import { furnitureName } from "../../furniture-names.ts"; +import type { I18nKey } from "../../i18n.ts"; +import { openingPreset } from "../../model.ts"; +import type { EditorHost } from "./host.ts"; +import { furnitureAt, openingAt, wallElevation, wallFrame, type ElevationBox } from "./ops/wall-view.ts"; +import { formatLength } from "../../units.ts"; + +const SNAP = 0.01; +const snap = (v: number) => Math.round(v / SNAP) * SNAP; + +export class NfWallView extends LitElement { + static properties = { host: { attribute: false }, doc: { attribute: false }, roomId: {}, edge: { type: Number }, _sel: { state: true }, _drag: { state: true } }; + /** The plan: a new one after every change makes the view draw again. */ + declare doc: unknown; + declare host: EditorHost; + declare roomId: string; + declare edge: number; + private declare _sel: string | null; + /** The box being dragged and where it is now (wall coordinates), before it is stored. */ + private declare _drag: { id: string; x0: number; y0: number; startU: number; startY: number; fromX: number; fromY: number } | null; + + constructor() { + super(); + this._sel = null; + this._drag = null; + } + + private get room() { + return this.host.floor?.rooms.find((r) => r.id === this.roomId); + } + + private frame() { + const room = this.room; + return room && this.host.floor ? wallFrame(this.host.floor, room, this.edge, this.host.doc.settings.wall_interior) : null; + } + + private boxes(): ElevationBox[] { + const room = this.room; + const frame = this.frame(); + return room && frame && this.host.floor ? wallElevation(this.host.floor, room, frame) : []; + } + + /** Stores a box at a new left end (and bottom) as one undoable step. */ + private place(box: ElevationBox, left: number, bottom: number | null): void { + const room = this.room; + const frame = this.frame(); + if (!room || !frame) return; + this.host.change((_doc, floor) => { + if (box.kind === "furniture") { + const f = floor.furniture.find((it) => it.id === box.id); + if (f) Object.assign(f, furnitureAt(frame, f, left, box.lifts ? bottom : null)); + } else { + const o = floor.openings.find((it) => it.id === box.id); + const owner = floor.rooms.find((r) => r.id === o?.room_id); + if (o && owner) Object.assign(o, openingAt(owner.id === room.id ? frame : wallFrame(floor, owner, o.edge, this.host.doc.settings.wall_interior), owner, o, left, box.lifts ? bottom : null)); + } + }); + } + + private toWall(e: PointerEvent): [number, number] { + const svgEl = this.renderRoot.querySelector("svg") as SVGSVGElement; + const m = svgEl.getScreenCTM()?.inverse(); + if (!m) return [0, 0]; + const p = new DOMPoint(e.clientX, e.clientY).matrixTransform(m); + return [p.x, -p.y]; + } + + private down(e: PointerEvent, box: ElevationBox): void { + this._sel = box.id; + if (!this.host.admin) return; + (e.currentTarget as Element).setPointerCapture(e.pointerId); + const [u, y] = this.toWall(e); + this._drag = { id: box.id, x0: box.x0, y0: box.y0, startU: u, startY: y, fromX: box.x0, fromY: box.y0 }; + } + + private move(e: PointerEvent, box: ElevationBox): void { + const d = this._drag; + if (!d || d.id !== box.id) return; + const [u, y] = this.toWall(e); + const frame = this.frame(); + const width = box.x1 - box.x0; + const x0 = Math.min((frame?.length ?? 0) - width, Math.max(0, snap(d.fromX + u - d.startU))); + const y0 = box.lifts ? Math.max(0, snap(d.fromY + y - d.startY)) : d.fromY; + this._drag = { ...d, x0, y0 }; + } + + private up(box: ElevationBox): void { + const d = this._drag; + this._drag = null; + if (!d || d.id !== box.id || (Math.abs(d.x0 - d.fromX) < 1e-6 && Math.abs(d.y0 - d.fromY) < 1e-6)) return; + this.place(box, d.x0, d.y0); + } + + private nameOf(box: ElevationBox): string { + if (box.kind === "furniture") { + const f = this.host.floor?.furniture.find((it) => it.id === box.id); + return f?.name || furnitureName(this.host.hass, box.type); + } + const o = this.host.floor?.openings.find((it) => it.id === box.id); + return o ? this.host.t(`preset_${openingPreset(o)}` as I18nKey) : box.type; + } + + protected updated(changed: PropertyValues): void { + if (changed.has("edge") || changed.has("roomId")) this._sel = null; + } + + render() { + const t = this.host.t; + const room = this.room; + const frame = this.frame(); + if (!room || !frame) return nothing; + const n = room.points.length; + const fmt = (v: number) => formatLength(this.host.hass, v); + const boxes = this.boxes().map((b) => (this._drag?.id === b.id ? { ...b, x1: this._drag.x0 + (b.x1 - b.x0), y1: this._drag.y0 + (b.y1 - b.y0), x0: this._drag.x0, y0: this._drag.y0 } : b)); + const top = Math.max(frame.heightLeft, frame.heightRight, ...boxes.map((b) => b.y1)); + const pad = 0.35; + const view = `${-pad} ${-(top + pad)} ${frame.length + 2 * pad} ${top + 2 * pad + 0.25}`; + const sel = boxes.find((b) => b.id === this._sel) ?? null; + const label = (b: ElevationBox) => { + const size = Math.min(0.14, Math.max(0.07, (b.x1 - b.x0) / 7)); + return svg`${this.nameOf(b)}`; + }; + const dims = sel + ? svg` + + ${fmt(sel.x0)} + + ${fmt(frame.length - sel.x1)} + ${sel.y0 > 0.005 ? svg`${fmt(sel.y0)}` : nothing} + ` + : nothing; + return html`
e.target === e.currentTarget && this.close()}> + +
`; + } + + private close(): void { + this.dispatchEvent(new CustomEvent("close")); + } + + static styles = css` + .backdrop { + position: fixed; + inset: 0; + z-index: 30; + display: grid; + place-items: center; + background: rgba(0, 0, 0, 0.45); + } + .sheet { + width: min(1100px, calc(100vw - 32px)); + max-height: calc(100vh - 32px); + display: flex; + flex-direction: column; + border-radius: 20px; + background: var(--nf-bg2, #1b2030); + color: var(--nf-text, #e8eeff); + box-shadow: 0 16px 48px rgba(0, 0, 0, 0.5); + overflow: hidden; + } + header, + footer { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 16px; + flex-wrap: wrap; + } + header button { + min-width: 36px; + height: 36px; + border: 0; + border-radius: 50%; + background: rgba(127, 127, 127, 0.16); + color: inherit; + font: inherit; + font-size: 18px; + cursor: pointer; + } + .grow { + flex: 1; + } + .muted { + color: var(--nf-muted, #9aa5bd); + font-size: 13px; + } + svg { + width: 100%; + height: min(60vh, 560px); + touch-action: none; + user-select: none; + } + .wall { + fill: rgba(127, 140, 170, 0.12); + stroke: var(--nf-accent, #37e0ff); + stroke-width: 0.015; + } + .floor { + stroke: var(--nf-muted, #9aa5bd); + stroke-width: 0.02; + } + .box rect { + fill: rgba(91, 124, 255, 0.28); + stroke: #8aa2ff; + stroke-width: 0.012; + } + .box.opening rect { + fill: rgba(10, 14, 24, 0.85); + stroke: var(--nf-muted, #9aa5bd); + } + .box.window rect { + fill: rgba(55, 224, 255, 0.16); + } + .box.sel rect { + stroke: var(--nf-accent, #37e0ff); + stroke-width: 0.025; + } + .box.movable { + cursor: grab; + } + .box text { + fill: var(--nf-text, #e8eeff); + pointer-events: none; + } + .dim line { + stroke: var(--nf-accent, #37e0ff); + stroke-width: 0.01; + stroke-dasharray: 0.04 0.03; + } + .dim text { + fill: var(--nf-accent, #37e0ff); + } + footer label { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; + color: var(--nf-muted, #9aa5bd); + } + footer input { + width: 80px; + padding: 6px 8px; + border-radius: 10px; + border: 1px solid rgba(127, 127, 127, 0.35); + background: rgba(0, 0, 0, 0.2); + color: inherit; + font: inherit; + } + `; +} + +if (!customElements.get("nf-wall-view")) customElements.define("nf-wall-view", NfWallView); diff --git a/frontend/src/components/entity-picker.ts b/frontend/src/components/entity-picker.ts new file mode 100644 index 0000000..b5ae0d1 --- /dev/null +++ b/frontend/src/components/entity-picker.ts @@ -0,0 +1,226 @@ +// A searchable entity picker: a text field that filters the options by name, area or id as you type, +// with a short result list below it. Replaces plain { + clearTimeout(this.blurTimer); + this._open = true; + this._query = ""; + this._cursor = 0; + }} + @blur=${() => { + this.blurTimer = setTimeout(() => (this._open = false), 150); + }} + @input=${(e: Event) => { + this._query = (e.target as HTMLInputElement).value; + this._cursor = 0; + this._open = true; + }} + @keydown=${this.onKey} + /> + ${this._open + ? html`
    + ${hits.length ? nothing : html`
  • –
  • `} + ${hits.map( + (o, i) => html`
  • e.preventDefault()} + @click=${() => this.choose(o.id)} + > + ${o.label}${o.detail || o.id.includes(".") ? html`${o.detail ?? o.id}` : nothing} +
  • `, + )} + ${this.leftOut > 0 ? html`
  • … +${this.leftOut} · ${this.placeholder}
  • ` : nothing} +
` + : nothing} + `; + } + + static styles = [ + tokens, + css` + :host { + display: block; + position: relative; + } + input { + width: 100%; + box-sizing: border-box; + font: inherit; + color: var(--nf-text); + background: var(--nf-chrome-solid); + border: 1px solid var(--nf-line); + border-radius: 10px; + padding: 8px 10px; + } + input::placeholder { + color: var(--nf-text); + opacity: 0.9; + } + input:focus::placeholder { + color: var(--nf-muted); + } + input:focus { + outline: 2px solid var(--nf-accent); + outline-offset: -1px; + } + .list { + position: absolute; + left: 0; + right: 0; + top: calc(100% + 4px); + z-index: 20; + margin: 0; + padding: 4px; + list-style: none; + max-height: 280px; + overflow-y: auto; + background: var(--nf-chrome-solid); + border: 1px solid var(--nf-line); + border-radius: 10px; + box-shadow: var(--nf-shadow); + } + li { + display: flex; + flex-direction: column; + gap: 1px; + padding: 6px 8px; + border-radius: 6px; + cursor: pointer; + font-size: 13.5px; + } + li small { + color: var(--nf-muted); + font-size: 11px; + } + li.cursor, + li:hover { + background: color-mix(in srgb, var(--nf-accent) 18%, transparent); + } + li.chosen { + color: var(--nf-accent); + } + li.empty { + color: var(--nf-muted); + cursor: default; + } + `, + ]; +} + +if (!customElements.get("nf-entity-picker")) customElements.define("nf-entity-picker", EntityPicker); diff --git a/frontend/src/components/extensions.ts b/frontend/src/components/extensions.ts new file mode 100644 index 0000000..8ef689a --- /dev/null +++ b/frontend/src/components/extensions.ts @@ -0,0 +1,88 @@ +// The "Extensions" page of the panel: your own furniture packs, uploading your own 3D models, plugins, plus the links to the project. +// It lives in the editor bundle (loaded with it) and is shown to admins only. + +import { css, html, LitElement } from "lit"; +import { REPO_URL } from "../features.ts"; +import { translate, type I18nKey } from "../i18n.ts"; +import type { FurniturePack } from "../packs.ts"; +import "./model-upload.ts"; +import "./pack-manager.ts"; +import "./plugin-manager.ts"; +import type { PluginRef } from "../plugins/api.ts"; +import { controls, tokens } from "../styles.ts"; +import type { HomeAssistant } from "../types.ts"; + +export class Extensions extends LitElement { + static properties = { + hass: { attribute: false }, + packs: { attribute: false }, + plugins: { attribute: false }, + }; + + declare hass: HomeAssistant | undefined; + declare packs: FurniturePack[] | undefined; + declare plugins: PluginRef[] | undefined; + private t(key: I18nKey, vars?: Record): string { + return translate(this.hass, key, vars); + } + + protected render() { + return html`
+
+

${this.t("ext_title")}

+

${this.t("ext_intro")}

+ +
+ + + +
`; + } + + static styles = [ + tokens, + controls, + css` + :host { + display: block; + overflow: auto; + } + .nf-ext { + max-width: 920px; + margin: 0 auto; + padding: 20px 16px 40px; + display: grid; + gap: 16px; + } + .nf-ext-head { + display: grid; + gap: 8px; + justify-items: start; + } + .nf-ext-head a { + text-decoration: none; + } + .nf-ext-actions, + .nf-ext-links { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; + } + .nf-ext-head h2 { + margin: 0; + font-size: 22px; + } + .nf-sub { + color: var(--nf-soft); + font-size: 13px; + } + `, + ]; +} + +if (!customElements.get("nf-extensions")) customElements.define("nf-extensions", Extensions); diff --git a/frontend/src/components/furniture2d.ts b/frontend/src/components/furniture2d.ts new file mode 100644 index 0000000..57e6805 --- /dev/null +++ b/frontend/src/components/furniture2d.ts @@ -0,0 +1,242 @@ +// Top-view symbols of furniture for the 2D editor, in local metres (x across, z depth, front at +z). +// The editor places them with translate/rotate/scale; strokes keep their width on screen. + +import { nothing, svg, type SVGTemplateResult } from "lit"; +import { fittedParts, packItem, type PackItem } from "../packs.ts"; +import { stairConfig, stairLayout, treadCentre, type StairConfig } from "../geometry/stairs.ts"; + +type Part = SVGTemplateResult; + +const rect = (x0: number, z0: number, x1: number, z1: number, cls = "") => svg``; +const line = (x0: number, z0: number, x1: number, z1: number, cls = "") => svg``; +const poly = (pts: [number, number][], cls = "") => svg` q.join(",")).join(" ")} />`; +const circle = (x: number, z: number, r: number, cls = "") => svg``; +const ellipse = (x: number, z: number, rx: number, rz: number, cls = "") => svg``; + +/** Door or drawer divisions along the front edge. */ +function fronts(w: number, d: number, n: number): Part[] { + const out: Part[] = []; + for (let i = 1; i < n; i++) { + const x = -w / 2 + (w / n) * i; + out.push(line(x, d / 2, x, d / 2 - Math.min(0.12, d * 0.3))); + } + return out; +} + +function seating(w: number, d: number, seats: number, arms: boolean): Part[] { + const back = Math.min(0.24, d * 0.28); + const arm = arms ? Math.min(0.2, w * 0.12) : 0; + const out: Part[] = [rect(-w / 2, -d / 2, w / 2, -d / 2 + back, "nf-sym-fill")]; + if (arms) out.push(rect(-w / 2, -d / 2, -w / 2 + arm, d / 2, "nf-sym-fill"), rect(w / 2 - arm, -d / 2, w / 2, d / 2, "nf-sym-fill")); + const inner = w - 2 * arm; + for (let i = 1; i < seats; i++) { + const x = -w / 2 + arm + (inner / seats) * i; + out.push(line(x, -d / 2 + back, x, d / 2 - 0.02)); + } + return out; +} + +/** Symbol parts for a furniture type of size w × d (metres). */ +export function furnitureSymbol(type: string, w: number, d: number, item?: { h: number; stair?: Partial | null }): Part[] | typeof nothing { + if (type === "stairs" && item?.stair) return shapedStairSymbol(item, w, d); + switch (type) { + case "sofa": + return seating(w, d, Math.max(1, Math.round((w - 0.4) / 0.62)), true); + case "armchair": + return seating(w, d, 1, true); + case "bench": + return [rect(-w / 2, -d / 2, w / 2, -d / 2 + 0.08, "nf-sym-fill")]; + case "corner_bench": { + const depth = Math.min(0.5, d * 0.4); + return [ + rect(-w / 2, -d / 2, w / 2, -d / 2 + 0.08, "nf-sym-fill"), + rect(-w / 2, -d / 2, -w / 2 + 0.08, d / 2, "nf-sym-fill"), + line(-w / 2 + depth, -d / 2 + depth, w / 2, -d / 2 + depth), + line(-w / 2 + depth, -d / 2 + depth, -w / 2 + depth, d / 2), + ]; + } + case "chair": + return [rect(-w / 2, -d / 2, w / 2, -d / 2 + 0.06, "nf-sym-fill")]; + case "office_chair": + return [circle(0, 0.03, Math.min(w, d) * 0.36), rect(-w * 0.35, -d / 2 + 0.02, w * 0.35, -d / 2 + 0.1, "nf-sym-fill")]; + case "bar_stool": + case "table_round": + return [circle(0, 0, Math.min(w, d) * 0.42)]; + case "stool": + return [rect(-w / 2 + 0.04, -d / 2 + 0.04, w / 2 - 0.04, d / 2 - 0.04)]; + case "table": + case "coffee_table": + case "desk": { + const out = [rect(-w / 2 + 0.05, -d / 2 + 0.05, w / 2 - 0.05, d / 2 - 0.05)]; + if (type === "desk") out.push(line(-0.3, -d / 2 + 0.1, 0.3, -d / 2 + 0.1, "nf-sym-strong")); + return out; + } + case "bed": + case "bunk_bed": { + const pillows = w > 1.2 ? 2 : 1; + const pw = (w - 0.2) / pillows; + const out: Part[] = [rect(-w / 2, -d / 2, w / 2, -d / 2 + 0.07, "nf-sym-fill"), line(-w / 2, -d / 2 + (d - 0.1) * 0.36, w / 2, -d / 2 + (d - 0.1) * 0.36)]; + for (let i = 0; i < pillows; i++) out.push(rect(-w / 2 + 0.13 + pw * i, -d / 2 + 0.12, -w / 2 + 0.07 + pw * (i + 1), -d / 2 + 0.12 + Math.min(0.4, d * 0.18))); + return out; + } + case "nightstand": + case "wardrobe": + case "dresser": + case "sideboard": + case "tall_cabinet": + case "kitchen": + case "kitchen_wall": + case "kitchen_tall": + case "shelf": + return fronts(w, d, type === "nightstand" || type === "tall_cabinet" || type === "kitchen_tall" ? 1 : Math.max(2, Math.round(w / 0.5))); + case "coat_rack": + return [rect(-w / 2, -d / 2, w / 2, -d / 2 + 0.03, "nf-sym-fill"), ...fronts(w, d, Math.max(2, Math.round(w / 0.5)))]; + case "island": + // cabinets on the back side, overhanging worktop on the front + return [line(-w / 2, d / 2 - 0.3, w / 2, d / 2 - 0.3)]; + case "fridge": + return [line(-w / 2 + 0.06, d / 2 - 0.04, w / 2 - 0.06, d / 2 - 0.04, "nf-sym-strong")]; + case "stove": { + const r = Math.min(w, d) * 0.14; + return [circle(-w * 0.22, -d * 0.2, r), circle(w * 0.22, -d * 0.2, r * 0.8), circle(-w * 0.22, d * 0.2, r * 0.8), circle(w * 0.22, d * 0.2, r)]; + } + case "sink": { + const bw = Math.min(0.5, w - 0.2); + return [rect(-bw / 2, -d / 2 + 0.1, bw / 2, d / 2 - 0.08), circle(0, -d / 2 + 0.06, 0.025, "nf-sym-fill")]; + } + case "dishwasher": + return [line(-w / 2 + 0.08, d / 2 - 0.05, w / 2 - 0.08, d / 2 - 0.05, "nf-sym-strong")]; + case "washer": + case "dryer": + return [circle(0, 0.05, Math.min(w, d) * 0.3), line(-w / 2, -d / 2 + 0.1, w / 2, -d / 2 + 0.1)]; + case "bathtub": + return [rect(-w / 2 + 0.07, -d / 2 + 0.07, w / 2 - 0.07, d / 2 - 0.07), circle(-w / 2 + 0.14, 0, 0.03, "nf-sym-fill")]; + case "shower": + return [line(-w / 2, -d / 2, w / 2, d / 2), line(w / 2, -d / 2, -w / 2, d / 2), circle(0, 0, 0.04)]; + case "wc": + return [rect(-w / 2, -d / 2, w / 2, -d / 2 + Math.min(0.18, d * 0.3), "nf-sym-fill"), ellipse(0, d * 0.1, w * 0.36, d * 0.3)]; + case "washbasin": + return [ellipse(0, 0.03, w * 0.34, d * 0.3)]; + case "tv_board": + return [line(-Math.min(w * 0.4, 0.72), -d / 2 + 0.14, Math.min(w * 0.4, 0.72), -d / 2 + 0.14, "nf-sym-strong"), ...fronts(w, d, Math.max(2, Math.round(w / 0.6)))]; + case "tv_wall": + return [line(-w / 2, 0, w / 2, 0, "nf-sym-strong")]; + case "lamp_downlight": + case "lamp_spot": + return [circle(0, 0, Math.min(w, d) * 0.45, "nf-sym-fill"), circle(0, 0, Math.min(w, d) * 1.4)]; + case "lamp_bollard": + case "lamp_garden": + return [circle(0, 0, Math.min(w, d) * 0.5, "nf-sym-fill"), circle(0, 0, Math.min(w, d) * 1.6)]; + case "parking": + // the spot's marking with an arrow head at the front + return [rect(-w / 2 + 0.08, -d / 2 + 0.08, w / 2 - 0.08, d / 2 - 0.08), line(-w * 0.15, d / 2 - 0.5, 0, d / 2 - 0.22, "nf-sym-strong"), line(0, d / 2 - 0.22, w * 0.15, d / 2 - 0.5, "nf-sym-strong")]; + case "robot_vacuum": + // dock at the back, the robot resting in front of it + return [rect(-w * 0.45, -d / 2, w * 0.45, -d / 2 + d * 0.3, "nf-sym-fill"), circle(0, d * 0.14, Math.min(w, d) * 0.47)]; + case "radiator": { + // fins along the front + const out: Part[] = []; + const n = Math.max(3, Math.round(w / 0.1)); + for (let i = 1; i < n; i++) out.push(line(-w / 2 + (w / n) * i, -d / 2, -w / 2 + (w / n) * i, d / 2)); + return out; + } + case "lamp_panel": + return [rect(-w / 2 + 0.03, -d / 2 + 0.03, w / 2 - 0.03, d / 2 - 0.03, "nf-sym-fill")]; + case "lamp_uplight": + case "lamp_ceiling": + case "lamp_pendant": + case "lamp_floor": + case "lamp_table": { + // a lamp from above: the shade, and short rays for hanging ones + const r = Math.min(w, d) / 2; + const out: Part[] = [circle(0, 0, r * 0.9, "nf-sym-fill"), circle(0, 0, r * 0.3)]; + if (type === "lamp_ceiling" || type === "lamp_pendant") { + for (let i = 0; i < 8; i++) { + const a = (i / 8) * Math.PI * 2; + out.push(line(Math.cos(a) * r * 1.05, Math.sin(a) * r * 1.05, Math.cos(a) * r * 1.35, Math.sin(a) * r * 1.35)); + } + } + return out; + } + case "ceiling_fan": { + // the motor in the middle and five blades from above + const r = Math.min(w, d) / 2; + const out: Part[] = [circle(0, 0, 0.11, "nf-sym-fill")]; + for (let i = 0; i < 5; i++) { + const a = (i / 5) * Math.PI * 2; + out.push(line(Math.cos(a) * 0.12, Math.sin(a) * 0.12, Math.cos(a) * r * 0.97, Math.sin(a) * r * 0.97, "nf-sym-strong")); + } + return [...out, circle(0, 0, r)]; + } + case "lamp_wall": + return [rect(-w / 2, -d / 2, w / 2, -d / 2 + 0.03, "nf-sym-fill"), ellipse(0, 0.01, w * 0.4, d * 0.4)]; + case "led_strip": + return [line(-w / 2, 0, w / 2, 0, "nf-sym-strong")]; + case "plant": + return [circle(0, 0, Math.min(w, d) * 0.46), circle(0, 0, Math.min(w, d) * 0.25)]; + case "rug": + return [rect(-w / 2 + 0.1, -d / 2 + 0.1, w / 2 - 0.1, d / 2 - 0.1)]; + case "stairs": { + // steps and an arrow pointing up the stair (towards the back) + const n = Math.max(3, Math.round(d / 0.26)); + const out: Part[] = []; + for (let i = 1; i < n; i++) out.push(line(-w / 2, d / 2 - (d / n) * i, w / 2, d / 2 - (d / n) * i)); + out.push(line(0, d / 2 - 0.1, 0, -d / 2 + 0.25, "nf-sym-strong"), line(-0.15, -d / 2 + 0.45, 0, -d / 2 + 0.25, "nf-sym-strong"), line(0.15, -d / 2 + 0.45, 0, -d / 2 + 0.25, "nf-sym-strong")); + return out; + } + default: { + const item = packItem(type); + return item ? packSymbol(item, w, d) : nothing; + } + } +} + +/** + * A shaped stair from above: every tread and landing, and the walking line from the first tread to the arrow at the last. + * Stairs going down are drawn dashed; their arrow points down the stair as well, away from this floor. + */ +function shapedStairSymbol(item: { h: number; stair?: Partial | null }, w: number, d: number): Part[] { + const cfg = stairConfig(item); + const layout = stairLayout(cfg, w, d, item.h); + const cls = cfg.down ? "nf-sym-dash" : ""; + const out: Part[] = layout.treads.map((t) => poly(t.poly, t.landing ? `nf-sym-fill ${cls}` : cls)); + if (layout.column > 0) out.push(circle(0, 0, layout.column, "nf-sym-fill")); + const walk = layout.treads.map(treadCentre); + for (let i = 1; i < walk.length; i++) out.push(line(walk[i - 1][0], walk[i - 1][1], walk[i][0], walk[i][1], "nf-sym-strong")); + if (walk.length) out.unshift(circle(walk[0][0], walk[0][1], 0.05, "nf-sym-fill")); + if (walk.length >= 2) { + const [p, q] = [walk[walk.length - 2], walk[walk.length - 1]]; + const length = Math.hypot(q[0] - p[0], q[1] - p[1]) || 1; + const [ux, uz] = [(q[0] - p[0]) / length, (q[1] - p[1]) / length]; + const size = Math.min(0.2, layout.flight * 0.3); + for (const side of [-1, 1]) out.push(line(q[0], q[1], q[0] - ux * size + uz * size * 0.6 * side, q[1] - uz * size - ux * size * 0.6 * side, "nf-sym-strong")); + } + return out; +} + +/** Plan symbol of a pack item: its own symbol, or its parts seen from above (except the full-size base). */ +function packSymbol(item: PackItem, w: number, d: number): Part[] { + if (item.symbol?.length) { + return item.symbol.map((s) => + s.shape === "rect" + ? rect((s.x - s.w / 2) * w, (s.z - s.d / 2) * d, (s.x + s.w / 2) * w, (s.z + s.d / 2) * d, s.fill ? "nf-sym-fill" : "") + : s.shape === "circle" + ? circle(s.x * w, s.z * d, s.r * Math.min(w, d)) + : line(s.x1 * w, s.z1 * d, s.x2 * w, s.z2 * d), + ); + } + // seen from above, so the height does not matter: the parts as they sit in the resized item + return fittedParts(item, w, d, item.size[2]) + .filter((p) => p.shape === "sweep" || p.w < 0.98 || p.d < 0.98) + .map((p) => + p.shape === "sweep" && p.stations?.length + ? // the outline seen from above: down one side and back up the other + poly([ + ...p.stations.map((st): [number, number] => [(p.x + st[3] / 2) * w, st[0] * d]), + ...[...p.stations].reverse().map((st): [number, number] => [(p.x - st[3] / 2) * w, st[0] * d]), + ]) + : p.shape === "cyl" && (p.axis ?? "y") === "y" + ? circle(p.x * w, p.z * d, Math.min(p.w * w, p.d * d) / 2) + : rect((p.x - p.w / 2) * w, (p.z - p.d / 2) * d, (p.x + p.w / 2) * w, (p.z + p.d / 2) * d), + ); +} diff --git a/frontend/src/components/model-upload.ts b/frontend/src/components/model-upload.ts new file mode 100644 index 0000000..969de00 --- /dev/null +++ b/frontend/src/components/model-upload.ts @@ -0,0 +1,322 @@ +// "Your own 3D models" on the extensions page: pick a binary glTF for an item that names a model, see how it will look, turn its front +// towards the viewer, mark the body paint, choose how detailed it stays, and put it on Home Assistant, all in the browser. + +import { css, html, LitElement, nothing, type TemplateResult } from "lit"; +import { translate, type I18nKey } from "../i18n.ts"; +import { load3d } from "../load3d.ts"; +import { DETAIL_LEVELS, MAX_UPLOAD_BYTES, meshPath, modelSlots, readableSize, trianglesFor, uploadProblem, type DetailKey, type ModelSlot } from "../model-slots.ts"; +import type { FurniturePack } from "../packs.ts"; +import { controls, tokens } from "../styles.ts"; +import type { HomeAssistant } from "../types.ts"; +import type { ModelInfo } from "../viewer/viewer3d.ts"; + +type Present = "unknown" | "yes" | "no"; + +interface Draft { + slot: ModelSlot; + fileName: string; + data: ArrayBuffer; + info: ModelInfo; + turns: 0 | 1 | 2 | 3; + paint: string[]; + detail: DetailKey; + colour: string; + /** The prepared file and the picture of it. */ + result: { glb: ArrayBuffer; triangles: number; picture: string } | null; +} + +export class NfModelUpload extends LitElement { + static properties = { + hass: { attribute: false }, + packs: { attribute: false }, + _present: { state: true }, + _draft: { state: true }, + _busy: { state: true }, + _message: { state: true }, + }; + + declare hass: HomeAssistant | undefined; + declare packs: FurniturePack[] | undefined; + private declare _present: Record; + private declare _draft: Draft | null; + private declare _busy: boolean; + private declare _message: { ok: boolean; text: string } | null; + private checked = new Set(); + private run = 0; + + constructor() { + super(); + this._present = {}; + this._draft = null; + this._busy = false; + this._message = null; + } + + private t(key: I18nKey, vars?: Record): string { + return translate(this.hass, key, vars); + } + + private get slots(): ModelSlot[] { + return modelSlots(this.packs ?? [], this.hass?.language ?? "en"); + } + + protected willUpdate(): void { + // which models are there already: asked once per model + for (const slot of this.slots) { + if (this.checked.has(slot.id) || !this.hass?.fetchWithAuth) continue; + this.checked.add(slot.id); + void this.askPresence(slot.id); + } + } + + private async askPresence(id: string): Promise { + const answer = await this.hass!.fetchWithAuth!(meshPath(id), { method: "HEAD" }).catch(() => null); + // the server answers a GET only: a HEAD may be refused, so fall back to asking for the file + const found = answer && answer.status !== 405 ? answer.ok : await this.hass!.fetchWithAuth!(meshPath(id)).then((r) => r.ok, () => false); + this._present = { ...this._present, [id]: found ? "yes" : "no" }; + } + + // choosing a file + + private async choose(slot: ModelSlot, file: File | undefined): Promise { + if (!file) return; + this._message = null; + this._busy = true; + try { + const data = await file.arrayBuffer(); + const viewer = await load3d(); + const info = await viewer.inspectModel(data); + this._draft = { slot, fileName: file.name, data, info, turns: 0, paint: info.paint, detail: "normal", colour: "#1d5bd6", result: null }; + await this.refresh(); + } catch (err) { + this._draft = null; + this._message = { ok: false, text: this.readError(err) }; + } finally { + this._busy = false; + } + } + + private readError(err: unknown): string { + const reason = (err as { reason?: string })?.reason; + const key = `model_error_${reason}` as I18nKey; + const text = this.t(key); + return text === key ? this.t("model_error_unreadable", { detail: String((err as Error)?.message ?? err) }) : text; + } + + /** Prepares the file with the current choices and draws a picture of the result. */ + private async refresh(): Promise { + const draft = this._draft; + if (!draft) return; + const mine = ++this.run; + this._busy = true; + try { + const viewer = await load3d(); + const { glb, triangles } = await viewer.prepareModel(draft.data, { turns: draft.turns, paint: draft.paint, maxTriangles: trianglesFor(draft.detail) }); + const picture = await viewer.previewModel(glb, draft.colour); + if (mine === this.run && this._draft === draft) this._draft = { ...draft, result: { glb, triangles, picture } }; + } catch (err) { + if (mine === this.run) this._message = { ok: false, text: this.readError(err) }; + } finally { + if (mine === this.run) this._busy = false; + } + } + + private change(patch: Partial): void { + if (!this._draft) return; + this._draft = { ...this._draft, ...patch }; + void this.refresh(); + } + + private turn(delta: 1 | -1): void { + if (this._draft) this.change({ turns: ((this._draft.turns + delta + 4) % 4) as Draft["turns"] }); + } + + private togglePaint(name: string, on: boolean): void { + if (!this._draft) return; + const rest = this._draft.paint.filter((n) => n !== name); + this.change({ paint: on ? [...rest, name] : rest }); + } + + // uploading and removing + + private async upload(): Promise { + const draft = this._draft; + if (!draft?.result || !this.hass?.fetchWithAuth) return; + if (draft.result.glb.byteLength > MAX_UPLOAD_BYTES) { + this._message = { ok: false, text: this.t("model_error_too_large", { max: readableSize(MAX_UPLOAD_BYTES) }) }; + return; + } + this._busy = true; + try { + const answer = await this.hass.fetchWithAuth(meshPath(draft.slot.id), { method: "POST", body: draft.result.glb }); + const problem = uploadProblem(answer.status); + if (problem) { + this._message = { ok: false, text: this.t(`model_upload_${problem}` as I18nKey, { max: readableSize(MAX_UPLOAD_BYTES) }) }; + return; + } + this._present = { ...this._present, [draft.slot.id]: "yes" }; + this._message = { ok: true, text: this.t("model_uploaded", { id: draft.slot.id, size: readableSize(draft.result.glb.byteLength) }) }; + this._draft = null; + } catch (err) { + this._message = { ok: false, text: this.t("model_upload_other", { detail: String((err as Error)?.message ?? err) }) }; + } finally { + this._busy = false; + } + } + + private async removeModel(slot: ModelSlot): Promise { + if (!this.hass?.fetchWithAuth || !confirm(this.t("model_remove_confirm", { id: slot.id }))) return; + const answer = await this.hass.fetchWithAuth(meshPath(slot.id), { method: "DELETE" }); + const problem = uploadProblem(answer.status); + this._present = { ...this._present, [slot.id]: problem ? this._present[slot.id] : "no" }; + this._message = problem ? { ok: false, text: this.t(`model_upload_${problem}` as I18nKey, { max: readableSize(MAX_UPLOAD_BYTES) }) } : { ok: true, text: this.t("model_removed", { id: slot.id }) }; + } + + // drawing + + private row(slot: ModelSlot): TemplateResult { + const present = this._present[slot.id] ?? "unknown"; + const state = present === "yes" ? this.t("model_present") : present === "no" ? this.t("model_missing") : "…"; + return html`
+
+ ${slot.items[0]}${slot.items.length > 1 ? html` +${slot.items.length - 1}` : nothing} + ${slot.id}.glb · ${state} +
+
+ + ${present === "yes" ? html`` : nothing} +
+
`; + } + + private picked(slot: ModelSlot, e: Event): void { + const input = e.target as HTMLInputElement; + const file = input.files?.[0]; + input.value = ""; + void this.choose(slot, file); + } + + private editor(draft: Draft): TemplateResult { + const { info, result } = draft; + const dimensions = info.size.map((v) => v.toFixed(2)).join(" × "); + return html`
+

${draft.slot.items[0]}

+

${draft.fileName} · ${this.t("model_info", { triangles: info.triangles.toLocaleString(this.hass?.language), size: dimensions })}

+
+
${result ? html`` : html`${this.t("loading")}`}
+
+
+ ${this.t("model_front")} +
+ + +
+ ${this.t("model_front_hint")} +
+
+ ${this.t("model_paint")} + ${info.materials.map( + (m) => html``, + )} + +
+
+ ${this.t("model_detail")} +
${DETAIL_LEVELS.map((l) => html``)}
+ ${result ? html`${this.t("model_result", { triangles: result.triangles.toLocaleString(this.hass?.language), size: readableSize(result.glb.byteLength) })}` : nothing} +
+
+
+
+ + +
+
`; + } + + protected render() { + const slots = this.slots; + if (slots.length === 0 || !(this.hass?.user?.is_admin ?? false)) return nothing; + return html`
+

${this.t("models")}

+

${this.t("models_hint")}

+ ${slots.map((slot) => this.row(slot))} + ${this._draft ? this.editor(this._draft) : nothing} + ${this._busy && !this._draft ? html`

${this.t("loading")}

` : nothing} + ${this._message ? html`

${this._message.text}

` : nothing} +

${this.t("models_licence")}

+
`; + } + + static styles = [ + tokens, + controls, + css` + :host { + display: block; + } + .nf-model { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px 12px; + padding: 8px 0; + border-top: 1px solid var(--nf-line); + } + .nf-model > div:first-child { + display: grid; + gap: 2px; + } + .nf-model-actions { + display: flex; + gap: 8px; + } + .nf-model-yes { + color: #41c46b; + } + .nf-model-no { + color: var(--nf-muted); + } + .nf-model-edit { + margin-top: 10px; + padding: 12px; + border: 1px solid var(--nf-line); + border-radius: 12px; + } + .nf-model-body { + display: flex; + flex-wrap: wrap; + gap: 14px; + } + .nf-model-picture { + display: grid; + place-items: center; + width: 220px; + height: 220px; + border-radius: 12px; + background: var(--nf-chrome-solid); + } + .nf-model-picture img { + width: 220px; + height: 220px; + } + .nf-model-options { + display: grid; + flex: 1; + min-width: 220px; + gap: 10px; + align-content: start; + } + .nf-field { + display: grid; + gap: 4px; + } + `, + ]; +} + +if (!customElements.get("nf-model-upload")) customElements.define("nf-model-upload", NfModelUpload); diff --git a/frontend/src/components/pack-manager.ts b/frontend/src/components/pack-manager.ts new file mode 100644 index 0000000..64a219b --- /dev/null +++ b/frontend/src/components/pack-manager.ts @@ -0,0 +1,281 @@ +// The "Furniture packs" block of the Extensions page: the user's own packs, imported from files or pasted +// as JSON, and removing them. The packs that come with NextFloor are always there and are not listed. +// Importing or removing fires `packs-changed`; the panel loads the packs again. + +import { css, html, LitElement, nothing } from "lit"; +import { importPack, removePack } from "../api.ts"; +import { REPO_URL } from "../features.ts"; +import { translate, type I18nKey } from "../i18n.ts"; +import { packLabel } from "../furniture-names.ts"; +import type { FurniturePack } from "../packs.ts"; +import { downloadStorePack, fetchStorePacks, storePackState, STORE_REPO, type StorePack } from "../plugins/store.ts"; + +/** The furniture builder on the project's site. */ +const BUILDER_URL = "https://therealmrbk.github.io/NextFloor/builder/"; +import { controls, tokens } from "../styles.ts"; +import type { HomeAssistant } from "../types.ts"; + +export class PackManager extends LitElement { + static properties = { + hass: { attribute: false }, + packs: { attribute: false }, + _msg: { state: true }, + _busy: { state: true }, + _store: { state: true }, + _storeError: { state: true }, + }; + + declare hass: HomeAssistant | undefined; + declare packs: FurniturePack[] | undefined; + declare _msg: { ok: boolean; text: string } | null; + declare _busy: boolean; + /** The community furniture of the store, once loaded (null: not asked for yet, "loading" while it comes). */ + declare _store: StorePack[] | "loading" | null; + declare _storeError: string | null; + + constructor() { + super(); + this._msg = null; + this._busy = false; + this._store = null; + this._storeError = null; + } + + /** The store's list is fetched only when asked for (no request to GitHub unless the user wants it). */ + private async loadStore(): Promise { + this._store = "loading"; + this._storeError = null; + try { + this._store = await fetchStorePacks(); + } catch (err) { + this._store = null; + this._storeError = this.t("community_failed", { detail: (err as Error)?.message ?? String(err) }); + } + } + + private async installStore(entry: StorePack): Promise { + this._busy = true; + this._msg = null; + try { + const res = await importPack(this.hass!, await downloadStorePack(entry)); + this._msg = { ok: true, text: this.t("pack_imported", { name: res.name, publisher: res.publisher, n: res.items }) }; + this.changed(); + } catch (err) { + this._msg = { ok: false, text: this.errorText(err) }; + } finally { + this._busy = false; + } + } + + private renderStore() { + const installed = this.packs ?? []; + const store = this._store; + return html`

${this.t("community_title")}

+

+ ${this.t("community_intro")} ${this.t("community_builder")} · + ${this.t("community_how")} +

+ ${store === null + ? html`
` + : store === "loading" + ? html`

${this.t("loading")}

` + : store.length + ? html`
    + ${store.map((entry) => { + const state = storePackState(entry, installed); + return html`
  • +
    + ${entry.name} + ${entry.id} · ${this.t("pack_by", { publisher: entry.author, n: entry.items })} + ${entry.description ? html`${entry.description}` : nothing} +
    + +
  • `; + })} +
` + : html`

${this.t("community_none")}

`} + ${this._storeError ? html`` : nothing}`; + } + + private t(key: I18nKey, vars?: Record): string { + return translate(this.hass, key, vars); + } + + private changed(): void { + this.dispatchEvent(new CustomEvent("packs-changed", { bubbles: true, composed: true })); + } + + private errorText(err: unknown): string { + const { code, message } = (err ?? {}) as { code?: string; message?: string }; + const detail = message ?? String(err); + const key = `pack_error_${code}` as I18nKey; + const text = this.t(key, { detail }); + return text === key ? this.t("pack_error_other", { detail }) : text; + } + + /** Imports each text as a pack; labels name the files in the message (empty for pasted JSON). Returns how many went in. */ + private async importTexts(sources: { label: string; text: string }[]): Promise { + if (!this.hass || !sources.length) return 0; + this._busy = true; + const done: string[] = []; + const failed: string[] = []; + for (const { label, text } of sources) { + try { + const res = await importPack(this.hass, text); + done.push(this.t("pack_imported", { name: res.name, publisher: res.publisher, n: res.items })); + } catch (err) { + failed.push(label ? `${label}: ${this.errorText(err)}` : this.errorText(err)); + } + } + this._busy = false; + if (done.length) this.changed(); + const summary = sources.length > 1 ? [this.t("packs_imported_n", { n: done.length, total: sources.length })] : []; + this._msg = { ok: failed.length === 0, text: [...summary, ...done, ...failed].join(" · ") }; + return done.length; + } + + private async importFiles(e: Event): Promise { + const input = e.target as HTMLInputElement; + const files = [...(input.files ?? [])]; + input.value = ""; + await this.importTexts(await Promise.all(files.map(async (f) => ({ label: f.name, text: await f.text() })))); + } + + private async importPasted(): Promise { + const area = this.renderRoot.querySelector("textarea"); + const text = area?.value.trim() ?? ""; + if (!area || !text) return void (this._msg = { ok: false, text: this.t("pack_paste_empty") }); + try { + JSON.parse(text); + } catch (err) { + return void (this._msg = { ok: false, text: this.t("pack_paste_not_json", { detail: err instanceof Error ? err.message : String(err) }) }); + } + if ((await this.importTexts([{ label: "", text }])) > 0) area.value = ""; + } + + private async deletePack(pack: FurniturePack): Promise { + if (!this.hass || !confirm(this.t("pack_remove_confirm", { name: packLabel(pack, this.hass.language ?? "de") }))) return; + try { + await removePack(this.hass, pack.id); + this._msg = null; + this.changed(); + } catch (err) { + this._msg = { ok: false, text: this.errorText(err) }; + } + } + + protected render() { + const own = (this.packs ?? []).filter((p) => !p.builtin); + const builtin = (this.packs ?? []).length - own.length; + const language = this.hass?.language ?? "de"; + return html`
+

${this.t("packs_title")}

+

${this.t("packs_intro", { n: builtin })} ${this.t("packs_docs")}

+ ${own.length + ? html`
    + ${own.map( + (p) => html`
  • +
    + ${packLabel(p, language)} + ${p.id} · ${this.t("pack_by", { publisher: p.publisher, n: p.items.length })} + ${p.description ? html`${p.description}` : nothing} +
    + +
  • `, + )} +
` + : html`

${this.t("packs_none")}

`} + + +
+ +
+ ${this._msg ? html`

${this._msg.text}

` : nothing} + ${this.hass ? this.renderStore() : nothing} +
`; + } + + static styles = [ + tokens, + controls, + css` + .nf-packs { + display: grid; + gap: 10px; + padding: 16px; + border: 1px solid var(--nf-line); + border-radius: 12px; + } + h3 { + margin: 0; + font-size: 17px; + } + .nf-sub, + .nf-ok, + .nf-error { + margin: 0; + font-size: 13px; + } + .nf-sub { + color: var(--nf-soft); + } + .nf-ok { + color: var(--success-color, #2e7d32); + } + .nf-error { + color: var(--error-color, #c62828); + overflow-wrap: anywhere; + } + h4 { + margin: 14px 0 0; + font-size: 15px; + } + ul { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 8px; + } + li { + display: flex; + gap: 10px; + align-items: center; + } + .nf-pack-main { + flex: 1; + min-width: 0; + display: grid; + gap: 2px; + } + .nf-detail { + font-size: 12px; + color: var(--nf-soft); + overflow-wrap: anywhere; + } + .nf-file { + justify-self: start; + cursor: pointer; + } + textarea { + box-sizing: border-box; + width: 100%; + min-height: 110px; + resize: vertical; + padding: 8px 10px; + border: 1px solid var(--nf-line); + border-radius: 8px; + background: transparent; + color: inherit; + font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; + } + `, + ]; +} + +if (!customElements.get("nf-pack-manager")) customElements.define("nf-pack-manager", PackManager); diff --git a/frontend/src/components/plugin-manager.ts b/frontend/src/components/plugin-manager.ts new file mode 100644 index 0000000..fc95c15 --- /dev/null +++ b/frontend/src/components/plugin-manager.ts @@ -0,0 +1,254 @@ +// The "Plugins" block of the Extensions page: the plugin URLs stored in the plan, their load state +// and what each registered. Editing fires `plugins-changed` with the new list; the panel saves it. + +import { css, html, LitElement, nothing } from "lit"; +import { REPO_URL } from "../features.ts"; +import { translate, type I18nKey } from "../i18n.ts"; +import { isAllowedPluginUrl, pluginFetchUrl, type PluginRef } from "../plugins/api.ts"; +import { pluginLoadStates } from "../plugins/loader.ts"; +import { fetchStoreIndex, STORE_REPO, storeState, withStoreEntry, type StoreEntry } from "../plugins/store.ts"; +import { onPluginsChanged, pluginStatuses } from "../plugins/registry.ts"; +import { controls, tokens } from "../styles.ts"; +import type { HomeAssistant } from "../types.ts"; + +export class PluginManager extends LitElement { + static properties = { + hass: { attribute: false }, + plugins: { attribute: false }, + _error: { state: true }, + _store: { state: true }, + _storeError: { state: true }, + _storeOpen: { state: true }, + }; + + declare hass: HomeAssistant | undefined; + declare plugins: PluginRef[] | undefined; + declare _error: string; + declare _store: StoreEntry[] | undefined; + declare _storeError: string; + declare _storeOpen: boolean; + private stop: (() => void) | null = null; + + constructor() { + super(); + this._error = ""; + this._storeError = ""; + this._storeOpen = false; + } + + connectedCallback(): void { + super.connectedCallback(); + this.stop = onPluginsChanged(() => this.requestUpdate()); + } + + disconnectedCallback(): void { + super.disconnectedCallback(); + this.stop?.(); + } + + private t(key: I18nKey, vars?: Record): string { + return translate(this.hass, key, vars); + } + + private emit(next: PluginRef[]): void { + this.dispatchEvent(new CustomEvent("plugins-changed", { detail: next, bubbles: true, composed: true })); + } + + private add(input: HTMLInputElement): void { + const url = pluginFetchUrl(input.value); + const list = this.plugins ?? []; + if (!isAllowedPluginUrl(url)) return void (this._error = this.t("plugins_url_invalid")); + if (list.some((p) => p.url === url)) return void (this._error = this.t("plugins_exists")); + if (list.length >= 20) return void (this._error = this.t("plugins_limit")); + this._error = ""; + input.value = ""; + this.emit([...list, { url, enabled: true }]); + } + + private async toggleStore(): Promise { + this._storeOpen = !this._storeOpen; + if (!this._storeOpen || this._store) return; + this._storeError = ""; + try { + this._store = await fetchStoreIndex(); + } catch (err) { + this._storeError = this.t("store_failed", { error: err instanceof Error ? err.message : String(err) }); + } + } + + private install(entry: StoreEntry): void { + const list = this.plugins ?? []; + const installed = list.some((p) => p.id === entry.id); + if (!installed && list.length >= 20) return void (this._error = this.t("plugins_limit")); + if (!installed && list.some((p) => p.url === entry.url)) return void (this._error = this.t("plugins_exists")); + if (!window.confirm(this.t("store_confirm", { name: entry.name, author: entry.author || "?", url: entry.url }))) return; + this._error = ""; + this.emit(withStoreEntry(list, entry)); + } + + private renderStore() { + return html`
+ + ${this._storeOpen + ? html`

${this.t("store_intro")} ${this.t("store_submit")}

+ ${this._storeError ? html`` : nothing} + ${!this._store && !this._storeError ? html`

${this.t("plugins_loading")}

` : nothing} + ${this._store && !this._store.length ? html`

${this.t("store_empty")}

` : nothing} +
    + ${(this._store ?? []).map((entry) => { + const state = storeState(entry, this.plugins); + return html`
  • +
    + ${entry.name} ${entry.version}${entry.author ? ` · ${entry.author}` : ""} + ${entry.description ? html`${entry.description}` : nothing} + ${entry.homepage ? html`${entry.homepage}` : nothing} +
    + ${state === "installed" + ? html`${this.t("store_installed")}` + : html``} +
  • `; + })} +
` + : nothing} +
`; + } + + private stateOf(url: string): { label: string; tone: "ok" | "warn" | "err"; detail: string } { + const load = pluginLoadStates().find((l) => l.url === url); + const registered = pluginStatuses().filter((s) => s.source === url); + const errors = [...(load?.error ? [load.error] : []), ...registered.flatMap((s) => s.errors)]; + if (load?.state === "error") return { label: this.t("plugins_error"), tone: "err", detail: errors.join(" · ") }; + if (load?.state === "loading") return { label: this.t("plugins_loading"), tone: "warn", detail: "" }; + if (load?.state === "loaded" && !registered.length) return { label: this.t("plugins_nothing_registered"), tone: "warn", detail: "" }; + if (registered.length) { + const names = registered.map((s) => `${s.name}${s.version ? ` ${s.version}` : ""}`).join(", "); + return { label: this.t("plugins_loaded"), tone: errors.length ? "warn" : "ok", detail: errors.length ? `${names} · ${errors.join(" · ")}` : names }; + } + return { label: this.t("plugins_reload_hint"), tone: "warn", detail: "" }; + } + + protected render() { + const list = this.plugins ?? []; + const fromDashboard = pluginStatuses().filter((s) => !s.source); + return html`
+

${this.t("plugins_title")}

+

${this.t("plugins_intro")} ${this.t("plugins_docs")}

+

⚠️ ${this.t("plugins_warning")}

+ ${list.length + ? html`
    + ${list.map((ref, i) => { + const st = ref.enabled ? this.stateOf(ref.url) : { label: this.t("plugins_off"), tone: "warn" as const, detail: "" }; + return html`
  • + +
    + ${ref.id ? `${ref.id}${ref.version ? ` ${ref.version}` : ""}` : ref.url} + ${st.label} + ${st.detail ? html`${st.detail}` : nothing} +
    + +
  • `; + })} +
` + : html`

${this.t("plugins_none")}

`} + ${fromDashboard.length + ? html`

${this.t("plugins_from_dashboard")}: ${fromDashboard.map((s) => `${s.name}${s.version ? ` ${s.version}` : ""}`).join(", ")}

` + : nothing} + ${this.renderStore()} +
+ e.key === "Enter" && this.add(e.target as HTMLInputElement)} /> + +
+ ${this._error ? html`` : nothing} +
`; + } + + static styles = [ + tokens, + controls, + css` + .nf-plugins { + display: grid; + gap: 10px; + padding: 16px; + border: 1px solid var(--nf-line); + border-radius: 12px; + } + h3 { + margin: 0; + font-size: 17px; + } + .nf-sub, + .nf-warn, + .nf-error { + margin: 0; + font-size: 13px; + } + .nf-sub { + color: var(--nf-soft); + } + .nf-warn { + color: var(--warning-color, #b26b00); + } + .nf-error { + color: var(--error-color, #c62828); + } + ul { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 8px; + } + li { + display: flex; + gap: 10px; + align-items: center; + } + .nf-plugin-main { + flex: 1; + min-width: 0; + display: grid; + gap: 2px; + } + code { + overflow-wrap: anywhere; + font-size: 13px; + } + .nf-state { + font-size: 12px; + } + .nf-state.ok { + color: var(--success-color, #2e7d32); + } + .nf-state.warn { + color: var(--nf-soft); + } + .nf-state.err { + color: var(--error-color, #c62828); + } + .nf-detail { + font-size: 12px; + color: var(--nf-soft); + overflow-wrap: anywhere; + } + .nf-store { + display: grid; + gap: 8px; + } + .nf-add { + display: flex; + gap: 8px; + } + .nf-add input { + flex: 1; + min-width: 0; + } + `, + ]; +} + +if (!customElements.get("nf-plugin-manager")) customElements.define("nf-plugin-manager", PluginManager); diff --git a/frontend/src/components/quick-menu.ts b/frontend/src/components/quick-menu.ts new file mode 100644 index 0000000..f23dd21 --- /dev/null +++ b/frontend/src/components/quick-menu.ts @@ -0,0 +1,532 @@ +// Quick menu at a device (long press in 3D): a ring of colours around a power button for lights, +// up/stop/down for blinds, on/off for switches, with a slider and a way to the full details. + +import { css, html, LitElement, nothing } from "lit"; +import { assumedCover, type CarState, entityName, isUnavailable, kindOf } from "../devices.ts"; +import { translate, type I18nKey } from "../i18n.ts"; +import { openMoreInfo, stateText } from "../markers.ts"; +import { tokens } from "../styles.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; + +const COLORS: [number, number, number][] = [ + [255, 181, 71], + [255, 236, 210], + [55, 224, 255], + [91, 124, 255], + [190, 90, 255], + [255, 95, 210], + [255, 70, 70], + [120, 255, 150], +]; +const KELVINS = [2200, 2700, 3200, 4000, 5000, 6500]; +const COLOR_MODES = ["hs", "rgb", "rgbw", "rgbww", "xy"]; +const COVER_SET_POSITION = 4; +const COVER_OPEN_TILT = 16; +const COVER_CLOSE_TILT = 32; +const COVER_SET_TILT = 128; + +/** What a light can do, from its supported colour modes. */ +export function lightAbilities(st: HassEntity): { dim: boolean; color: boolean; temp: boolean } { + const modes = (st.attributes.supported_color_modes as string[] | undefined) ?? []; + const color = modes.some((m) => COLOR_MODES.includes(m)); + return { dim: modes.some((m) => m !== "onoff"), color, temp: modes.includes("color_temp") }; +} + +/** Whether a cover can be moved to a position. */ +export function coverPositionable(st: HassEntity): boolean { + return (((st.attributes.supported_features as number) ?? 0) & COVER_SET_POSITION) !== 0 && typeof st.attributes.current_position === "number"; +} + +export class NfQuickMenu extends LitElement { + static properties = { + hass: { attribute: false }, + entity: { attribute: false }, + car: { attribute: false }, + presets: { attribute: false }, + confirmSwitch: { type: Boolean }, + myPosition: { attribute: false }, + low: { type: Boolean, reflect: true }, + }; + + declare hass: HomeAssistant; + declare entity: string; + /** Auto: the car behind a parking spot's pin – its menu replaces the entity's. */ + declare car: CarState | null; + /** Klang: stations and playlists to start on a speaker. */ + declare presets: { id: string; label: string; type: string; content: string }[]; + /** Ask before the power button switches. */ + declare confirmSwitch: boolean; + /** Blinds: the favourite position (Somfy's "My", %), a button in the ring moves there; null = none. */ + declare myPosition: number | null; + /** Tablet level: no blur behind the menu. */ + declare low: boolean; + private t(key: I18nKey, vars?: Record): string { + return translate(this.hass, key, vars); + } + + /** Ask before switching when the device is marked so (power and lock buttons; sliders and colours never ask). */ + private ask(): boolean { + return !this.confirmSwitch || confirm(this.t("confirm_switch", { name: entityName(this.hass, this.entity) })); + } + + private call(domain: string, service: string, data: Record = {}): void { + void this.hass.callService(domain, service, { entity_id: this.entity, ...data }); + } + + private close(): void { + this.dispatchEvent(new CustomEvent("close", { bubbles: true, composed: true })); + } + + private details(): void { + openMoreInfo(this, this.entity); + this.close(); + } + + /** Buttons spread on a ring around the centre. */ + private ring(items: ReturnType[]) { + const n = items.length; + return items.map((item, i) => { + const a = (i / n) * Math.PI * 2 - Math.PI / 2; + return html`
${item}
`; + }); + } + + private renderLight(st: HassEntity) { + const can = lightAbilities(st); + const on = st.state === "on"; + const pct = on && typeof st.attributes.brightness === "number" ? Math.round((st.attributes.brightness as number) / 2.55) : on ? 100 : 0; + const swatches = can.color + ? COLORS.map( + (c) => html``, + ) + : can.temp + ? KELVINS.map( + (k) => html``, + ) + : []; + return html`
+ ${this.ring(swatches)} + +
+ ${can.dim + ? html` this.call("light", "turn_on", { brightness_pct: Number((e.target as HTMLInputElement).value) })} + />` + : nothing}`; + } + + private renderCover(st: HassEntity) { + const pos = typeof st.attributes.current_position === "number" ? (st.attributes.current_position as number) : null; + const moving = st.state === "opening" || st.state === "closing"; + const setPos = coverPositionable(st); + // like the colour ring of lights: open and close, positions in between and stop around the blind + const slot = (label: string, aria: string, action: () => void, active = false) => + html``; + const at = (p: number) => pos !== null && Math.abs(pos - p) < 3; + const ring = [ + // moving asks first when the blind is marked so; stopping never asks + slot("▲", this.t("cover_open"), () => this.ask() && this.call("cover", "open_cover"), at(100)), + ...(setPos ? [75, 50].map((p) => slot(`${p}`, `${p} %`, () => this.ask() && this.call("cover", "set_cover_position", { position: p }), at(p))) : []), + slot("▼", this.t("cover_close"), () => this.ask() && this.call("cover", "close_cover"), at(0)), + ...(setPos ? [25].map((p) => slot(`${p}`, `${p} %`, () => this.ask() && this.call("cover", "set_cover_position", { position: p }), at(p))) : []), + slot("■", this.t("cover_stop"), () => this.call("cover", "stop_cover"), moving), + // the favourite position: a cover that sets positions goes there; a Somfy RTS motor without feedback goes to its own "My" on stop + ...(this.myPosition != null + ? [slot("My", this.t("cover_my_go", { p: this.myPosition }), () => this.ask() && (setPos ? this.call("cover", "set_cover_position", { position: this.myPosition }) : this.call("cover", "stop_cover")), at(this.myPosition))] + : []), + ]; + // the centre shows the blind: its closed part fills from the top + const closed = pos === null ? (st.state === "closed" ? 100 : 0) : 100 - pos; + // without a known state the centre cannot tell whether to open or close: only the arrows move it + const known = pos !== null || moving || st.state === "open" || st.state === "closed"; + return html`
+ ${this.ring(ring)} + +
+ ${setPos + ? html` this.call("cover", "set_cover_position", { position: Number((e.target as HTMLInputElement).value) })} + />` + : nothing} + ${this.renderTilt(st)}`; + } + + /** Slats of a venetian blind or a Raffstore: a tilt slider when the cover sets a tilt position, else open/close tilt buttons. */ + private renderTilt(st: HassEntity) { + const features = ((st.attributes.supported_features as number) ?? 0) | 0; + const tilt = typeof st.attributes.current_tilt_position === "number" ? (st.attributes.current_tilt_position as number) : null; + if (features & COVER_SET_TILT && tilt !== null) + return html``; + if (features & (COVER_OPEN_TILT | COVER_CLOSE_TILT)) + return html`
+ ${features & COVER_OPEN_TILT ? html`` : nothing} + ${features & COVER_CLOSE_TILT ? html`` : nothing} +
`; + return nothing; + } + + private renderToggle(st: HassEntity) { + const on = st.state === "on" || st.state === "unlocked" || st.state === "playing"; + const domain = st.entity_id.split(".")[0]; + return html`
+ +
`; + } + + /** A speaker or TV: power, play/pause and skip, the volume, its sources, and the stations and playlists it may play. */ + private renderMedia(st: HassEntity) { + const on = !["off", "standby", "unavailable", "unknown"].includes(st.state); + const playing = st.state === "playing"; + const a = st.attributes as Record; + const volume = typeof a.volume_level === "number" ? Math.round(a.volume_level * 100) : null; + const sources = Array.isArray(a.source_list) ? (a.source_list as string[]).slice(0, 24) : []; + const title = [a.media_title, a.media_artist].filter((v) => typeof v === "string" && v).join(" · "); + const icon = (d: string) => html``; + const slot = (label: ReturnType, aria: string, action: () => void, active = false) => + html``; + const ring = on + ? [ + slot(icon(playing ? "M6 5h4v14H6zM14 5h4v14h-4z" : "M8 5v14l11-7z"), this.t(playing ? "media_pause" : "media_play"), () => this.call("media_player", "media_play_pause"), playing), + slot(icon("M6 6h2v12H6zm3.5 6 8.5 6V6z"), this.t("media_previous"), () => this.call("media_player", "media_previous_track")), + slot(icon("M16 6h2v12h-2zM6 18l8.5-6L6 6z"), this.t("media_next"), () => this.call("media_player", "media_next_track")), + ] + : []; + return html`
+ ${this.ring(ring)} + +
+ ${title ? html`
${title}
` : nothing} + ${volume !== null + ? html` this.call("media_player", "volume_set", { volume_level: Number((e.target as HTMLInputElement).value) / 100 })} />` + : nothing} + ${sources.length + ? html`
${this.t("media_sources")}
+
${sources.map((s) => html``)}
` + : nothing} + ${this.presets?.length + ? html`
${this.t("presets")}
+
${this.presets.map((p) => html``)}
` + : nothing}`; + } + + protected render() { + const st = this.hass?.states[this.entity]; + if (!st) return nothing; + const kind = kindOf(this.entity); + // a cover without feedback (a garage remote) stays unknown, but its buttons still work + const body = isUnavailable(st) && !assumedCover(st) + ? html`

${stateText(this.hass, st)}

` + : kind === "light" + ? this.renderLight(st) + : kind === "cover" + ? this.renderCover(st) + : kind === "media" + ? this.renderMedia(st) + : this.renderToggle(st); + return html``; + } + + static styles = [ + tokens, + css` + .qm-play-head { + margin: 10px 0 4px; + font-size: 11px; + letter-spacing: 0.08em; + text-transform: uppercase; + opacity: 0.7; + } + .qm-play { + display: flex; + flex-wrap: wrap; + gap: 6px; + max-height: 110px; + overflow-y: auto; + } + .qm-chip { + border: 1px solid rgba(160, 240, 255, 0.35); + border-radius: 999px; + padding: 5px 10px; + background: rgba(8, 16, 34, 0.55); + color: inherit; + font: inherit; + font-size: 12.5px; + cursor: pointer; + } + .qm-chip-on { + border-color: var(--nf-accent, var(--nf-accent)); + color: var(--nf-accent, var(--nf-accent)); + } + .qm { + width: 232px; + padding: 12px 14px 10px; + border-radius: 22px; + background: var(--nf-chrome); + box-shadow: var(--nf-shadow), 0 0 0 1px var(--nf-line); + backdrop-filter: blur(10px); + } + :host([low]) .qm { + backdrop-filter: none; + box-shadow: 0 0 0 1px var(--nf-line); + animation: none; + color: var(--nf-text); + text-align: center; + animation: qm-in 140ms ease-out; + } + @keyframes qm-in { + from { + opacity: 0; + transform: scale(0.85); + } + } + .qm-title { + font: 700 14.5px var(--nf-title-font); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + .qm-ring { + position: relative; + width: 196px; + height: 196px; + margin: 6px auto 4px; + display: grid; + place-items: center; + } + .qm-ring-small { + height: 110px; + } + .qm-at { + position: absolute; + transform: translate(-50%, -50%); + } + .qm-swatch { + width: 34px; + height: 34px; + border: 2px solid color-mix(in srgb, var(--nf-text) 25%, transparent); + border-radius: 50%; + cursor: pointer; + box-shadow: 0 0 12px rgba(0, 0, 0, 0.35); + } + .qm-swatch:active { + transform: scale(0.9); + } + .qm-power { + display: grid; + place-items: center; + gap: 2px; + width: 88px; + height: 88px; + border: 0; + border-radius: 50%; + background: var(--nf-bg2); + color: var(--nf-muted); + box-shadow: inset 0 0 0 2px var(--nf-line); + cursor: pointer; + font: inherit; + } + .qm-power:disabled { + opacity: 0.45; + cursor: default; + } + .qm-power b { + font: 700 15px var(--nf-title-font); + color: var(--nf-text); + } + .qm-power small { + font-size: 11px; + } + .qm-on { + color: #1a1204; + background: var(--nf-warm); + box-shadow: 0 0 24px rgba(255, 181, 71, 0.55); + } + .qm-on b { + color: #1a1204; + } + .qm-slot { + display: grid; + place-items: center; + border-color: var(--nf-line); + background: var(--nf-bg2); + color: var(--nf-text); + font: 700 12px var(--nf-title-font); + } + .qm-slot-on { + background: var(--nf-accent); + color: var(--nf-accent-text); + border-color: transparent; + box-shadow: var(--nf-shadow); + } + /* the blind: its closed part covers the circle from the top, the open part glows like daylight */ + .qm-blind.qm-on { + background: linear-gradient(to bottom, #1e2c4c var(--closed), #9fd9ff var(--closed)); + box-shadow: 0 0 22px rgba(120, 200, 255, 0.4); + color: #06101f; + } + .qm-blind b { + text-shadow: 0 0 6px rgba(0, 0, 0, 0.6); + color: #fff; + } + .qm-round { + width: 46px; + height: 46px; + border: 0; + border-radius: 50%; + background: var(--nf-accent); + color: var(--nf-accent-text); + font-size: 17px; + cursor: pointer; + } + .qm-car-line { + margin: 2px 0 8px; + text-align: center; + font-weight: 600; + font-variant-numeric: tabular-nums; + } + .qm-car { + display: grid; + gap: 6px; + justify-items: stretch; + } + .qm-car .qm-slot { + width: auto; + padding: 6px 10px; + font-size: 13px; + } + .qm-media { + display: flex; + align-items: center; + justify-content: center; + gap: 12px; + margin: 6px 0; + } + .qm-media-main { + width: 64px; + height: 64px; + border-radius: 50%; + background-size: cover; + background-position: center; + position: relative; + } + .qm-media-main span { + position: absolute; + inset: 0; + display: grid; + place-items: center; + font-size: 22px; + text-shadow: 0 0 6px rgba(0, 0, 0, 0.8); + color: #fff; + } + .qm-media .qm-slot { + width: auto; + padding: 0 10px; + } + .qm-media-title { + margin: 2px 0 4px; + text-align: center; + font-size: 12px; + opacity: 0.85; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + .qm-tilt { + display: grid; + gap: 4px; + margin-top: 8px; + font-size: 12px; + color: var(--nf-muted); + } + .qm-tilt-buttons { + display: flex; + gap: 6px; + justify-content: center; + margin-top: 8px; + } + .qm-tilt-buttons .qm-slot { + width: auto; + padding: 0 10px; + font-size: 12px; + } + .qm-slider { + width: 100%; + margin: 4px 0 6px; + accent-color: var(--nf-accent); + } + .qm-look { + display: block; + width: 100%; + margin-top: -4px; + } + .qm-details { + border: 0; + background: none; + color: var(--nf-accent); + font: inherit; + font-size: 13px; + padding: 6px; + cursor: pointer; + } + .qm-note { + color: var(--nf-muted); + } + `, + ]; +} + +function kelvinCss(k: number): string { + const t = Math.min(1, Math.max(0, (k - 2200) / 4300)); + const mix = (a: number, b: number) => Math.round(a + (b - a) * t); + return `rgb(${mix(255, 200)},${mix(170, 225)},${mix(80, 255)})`; +} + +if (!customElements.get("nf-quick-menu")) customElements.define("nf-quick-menu", NfQuickMenu); diff --git a/frontend/src/components/room-panel.ts b/frontend/src/components/room-panel.ts new file mode 100644 index 0000000..517ce3e --- /dev/null +++ b/frontend/src/components/room-panel.ts @@ -0,0 +1,1270 @@ +// Room panel: controls for the devices of the room's area (lights, covers, heating, media, switches, +// scenes and scripts). Shown next to the 3D view when a room is selected. + +import { css, html, LitElement, nothing, svg, type TemplateResult } from "lit"; +import { assumedCover, entityName, groupByDevice, groupCovers, isActive, isUnavailable, kindOf, roomClimateSensors, roomClimateValue, roomPanelEntities, fromCelsius, tempUnit, type DeviceKind, roomEntities } from "../devices.ts"; +import { formatNumber, translate, type I18nKey } from "../i18n.ts"; +import { iconPath } from "../icons.ts"; +import { openMoreInfo, stateText } from "../markers.ts"; +import { pluginRoomSections } from "../plugins/registry.ts"; +import { canAnnounce, roomHasSpeaker } from "../live/announce.ts"; +import type { Building, Floor, LightMood, LightSetting, Room } from "../model.ts"; +import { roomPower, roomPowerSensors } from "../heatmap.ts"; +import { energyCost, loadRoomEnergy, type RoomEnergy } from "../live/room-energy.ts"; +import { roomSun, roomSunYear, sunnyWindowsNow } from "../live/sun-hours.ts"; +import { LOW_BATTERY, planBatteries } from "../live/batteries.ts"; +import { powerText, sinceText } from "../presence.ts"; +import { carryMood, lightSetting, moodCalls } from "../live/moods.ts"; +import { allOffPlan, type ServiceCall } from "../live/all-off.ts"; +import { airingNeed, comfortScore, isSummer, mouldRisk } from "../live/room-climate.ts"; +import { hassAt, loadHistory } from "../live/time-travel.ts"; +import { curvePath } from "../live/day-curves.ts"; +import { controls, tokens } from "../styles.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; + +const COVER_SET_POSITION = 4; +const COVER_STOP = 8; + +/** Colour presets offered for colour lights (warm white first). */ +const SWATCHES: [number, number, number][] = [ + [255, 181, 71], + [255, 236, 210], + [55, 224, 255], + [91, 124, 255], + [255, 95, 210], + [120, 255, 150], +]; + +const icon = (kind: DeviceKind) => + html``; + +/** Filled transport icons (the Unicode symbols turn into emoji on some systems). */ +const TRANSPORT = { + previous: "M6 6h2v12H6zM20 6v12l-10-6z", + play: "M8 5v14l11-7z", + pause: "M7 5h4v14H7zM13 5h4v14h-4z", + next: "M16 6h2v12h-2zM4 6v12l10-6z", +}; +const transport = (d: string) => + html``; + +/** From this room temperature (°C) on, the sun on its windows is worth a shade hint. */ +const SHADE_FROM = 24; +/** Minutes without anybody seen before lights on count as forgotten. */ +const EMPTY_MINUTES = 10; + +export class NfRoomPanel extends LitElement { + static properties = { + hass: { attribute: false }, + room: { attribute: false }, + floor: { attribute: false }, + confirmEntities: { attribute: false }, + phrases: { attribute: false }, + outside: { attribute: false }, + _showAll: { state: true }, + _said: { state: true }, + _folded: { state: true }, + _curve: { state: true }, + _moodName: { state: true }, + _undo: { state: true }, + _energy: { state: true }, + _sunYear: { state: true }, + rooms: { attribute: false }, + building: { attribute: false }, + }; + + declare hass: HomeAssistant; + declare room: Room | null; + /** Floor of the room: the panel shows what the plan shows in the room. */ + declare floor: Floor | null; + /** Entities that ask before they are switched. */ + declare confirmEntities: Set | null; + /** The sentences offered for an announcement (null: the default ones). */ + declare phrases: string[] | null; + /** Outside instead of a room: the devices it lists (see outsideEntities). */ + declare outside: string[] | null; + /** What the last announcement from this panel did, shown under it for a moment. */ + private declare _said: { text: string; failed: boolean } | null; + private saidTimer: ReturnType | undefined; + /** Show the other devices of the area as well (their main entities). */ + private declare _showAll: boolean; + /** Only the header shows (a small screen: the room stays in view, the devices are out of the way). Starts open for every room. */ + private declare _folded: boolean; + private memo: { entities: HomeAssistant["entities"]; floor: Floor | null; room: Room; shown: string[]; more: string[] } | null = null; + /** Every room of the plan (a mood can be carried over to another one). */ + declare rooms: Room[] | null; + /** The whole plan: its meters stay out of the room's power, its compass turns the room's sun. */ + declare building: Building | null; + /** The name typed for a new mood, while the field shows. */ + private declare _moodName: string | null; + /** The room's temperature over the last 24 hours (°C, quarter hours), loaded when the room opens. */ + private declare _curve: (number | null)[] | null; + private curveFor = ""; + /** What the room used today and this month (from the statistics of its power sensors), loaded when the room opens. */ + private declare _energy: RoomEnergy | null; + /** The curve of the room's sun over the year shows (a tap on the sun hours). */ + private declare _sunYear: boolean; + /** After "everything off": the calls that bring it back, offered for a few seconds. */ + private declare _undo: ServiceCall[] | null; + private undoTimer: ReturnType | undefined; + + constructor() { + super(); + this.room = null; + this.floor = null; + this.phrases = null; + this.outside = null; + this._said = null; + this._showAll = false; + this._folded = false; + this._curve = null; + this._moodName = null; + this._undo = null; + this._energy = null; + this._sunYear = false; + this.rooms = null; + this.building = null; + } + + private fireMoods(room: Room, moods: LightMood[]): void { + this.dispatchEvent(new CustomEvent("mood-change", { detail: { roomId: room.id, moods }, bubbles: true, composed: true })); + } + + private runMood(settings: LightSetting[]): void { + for (const c of moodCalls(settings)) this.call("light", c.service, c.data); + } + + /** The light designer: save the room's lights as a mood, set a mood again, carry it to another room, or drop it. */ + private renderMoods(room: Room, lights: HassEntity[]): TemplateResult | typeof nothing { + const moods = room.moods ?? []; + // saving and dropping change the plan: only in the panel, for admins + const edit = !!this.rooms && !!(this.hass as { user?: { is_admin?: boolean } }).user?.is_admin; + if (!moods.length && !edit) return nothing; + const others = (this.rooms ?? []).filter((r) => r.id !== room.id && r.area_id); + const lightsOf = (r: Room) => roomEntities(this.hass, r).filter((id) => id.startsWith("light.")); + const save = () => { + const name = (this._moodName ?? "").trim() || this.t("mood_new"); + this.fireMoods(room, [...moods, { id: `mood_${Date.now().toString(36)}`, name, lights: lights.map(lightSetting) }]); + this._moodName = null; + }; + return html`
+ ${moods.map( + (m) => html` + + ${others.length + ? html`` + : nothing} + ${edit ? html`` : nothing} + `, + )} + ${!edit + ? nothing + : this._moodName === null + ? html`` + : html` (this._moodName = (e.target as HTMLInputElement).value)} @keydown=${(e: KeyboardEvent) => e.key === "Enter" && save()} /> + `} +
`; + } + + /** Loads the temperature history of the room's sensors (or thermostats) and samples it every quarter hour. */ + private async loadCurve(room: Room): Promise { + const ids = roomClimateSensors(this.hass, this.floor, room, "temperature"); + const sources = ids.length ? ids : roomEntities(this.hass, room).filter((id) => id.startsWith("climate.")); + if (!sources.length) return; + const to = Date.now(); + const from = to - 24 * 3600_000; + try { + const history = await loadHistory(this.hass, sources, from, to, !ids.length ? false : true); + if (this.room?.id !== room.id) return; + const curve: (number | null)[] = []; + for (let i = 1; i <= 96; i++) { + const at = hassAt(this.hass, history, from + ((to - from) * i) / 96); + const values = sources + .map((id) => (id.startsWith("climate.") ? Number(at.states[id]?.attributes.current_temperature) : Number(at.states[id]?.state))) + .filter(Number.isFinite); + curve.push(values.length ? values.reduce((a, b) => a + b, 0) / values.length : null); + } + this._curve = curve.some((v) => v !== null) ? curve : null; + } catch { + this._curve = null; + } + } + + private async loadEnergy(room: Room): Promise { + if (!this.floor || !this.building) return; + const ids = roomPowerSensors(this.hass, this.building, this.floor, room); + try { + const energy = await loadRoomEnergy(this.hass, ids); + if (this.room?.id === room.id) this._energy = energy; + } catch { + this._energy = null; + } + } + + /** + * Lights on, nobody there: the room's motion, occupancy and presence sensors have seen nobody for ten minutes while lights are on – + * say so, and switch them off in one tap. + */ + private renderEmptyLights(room: Room, lightsOn: HassEntity[]) { + if (!lightsOn.length || !this.room) return nothing; + const sensors = roomEntities(this.hass, room) + .map((id) => this.hass.states[id]) + .filter((st): st is HassEntity => !!st && st.entity_id.startsWith("binary_sensor.") && ["motion", "occupancy", "presence"].includes(String(st.attributes.device_class))); + if (!sensors.length || sensors.some((st) => st.state !== "off")) return nothing; + const quietSince = Math.max(...sensors.map((st) => Date.parse(String(st.last_changed ?? "")) || 0)); + const minutes = Math.floor((Date.now() - quietSince) / 60_000); + if (!quietSince || minutes < EMPTY_MINUTES) return nothing; + return html`
+ 💡 ${this.t("empty_lights_hint", { n: lightsOn.length, min: minutes })} + +
`; + } + + /** A window or door of the room stands open while its heating runs: say so, and turn the heating off (or to its lowest) in one tap. */ + private renderOpenWhileHeating(climates: HassEntity[]) { + const room = this.room; + if (!room || !this.floor) return nothing; + const heating = climates.filter((c) => c.attributes.hvac_action === "heating" || (c.state === "heat" && c.attributes.hvac_action === undefined)); + if (!heating.length) return nothing; + const on = (id: string | null | undefined) => !!id && id !== "none" && this.hass.states[id]?.state === "on"; + const open = this.floor.openings.filter((o) => o.room_id === room.id && [o.contact, o.contact2, o.tilt, o.tilt2].some(on)); + if (!open.length) return nothing; + const down = () => { + for (const c of heating) { + const modes = (c.attributes.hvac_modes as string[] | undefined) ?? []; + if (modes.includes("off")) this.call("climate", "set_hvac_mode", { entity_id: c.entity_id, hvac_mode: "off" }); + else if (typeof c.attributes.min_temp === "number") this.call("climate", "set_temperature", { entity_id: c.entity_id, temperature: c.attributes.min_temp }); + } + }; + return html`
+ 🪟 ${this.t("open_heating_hint", { n: open.length })} + +
`; + } + + /** + * The shade hint: the sun stands on some of the room's windows, the room is warm (24 °C or more) and their blinds are open – one + * tap lowers them. + */ + private renderShade() { + const room = this.room; + const { latitude, longitude } = this.hass.config ?? {}; + if (!room || !this.floor || !this.building || latitude === undefined || longitude === undefined) return nothing; + const temp = roomClimateValue(this.hass, this.floor, room, "temperature"); + if (temp === null || temp < SHADE_FROM) return nothing; + const open = (id: string | null | undefined): id is string => { + const st = id && id !== "none" ? this.hass.states[id] : undefined; + if (!st || isUnavailable(st)) return false; + const pos = st.attributes.current_position; + return typeof pos === "number" ? pos > 30 : st.state === "open"; + }; + const covers = [...new Set(sunnyWindowsNow(this.building, this.floor, room, { latitude, longitude }).flatMap((o) => [o.cover, o.cover2].filter(open)))]; + if (!covers.length) return nothing; + return html`
+ ☀ ${this.t("shade_hint", { n: covers.length, temp: `${formatNumber(this.hass, fromCelsius(this.hass, temp), 1)} ${tempUnit(this.hass)}` })} + +
`; + } + + /** The sun over the year: a button with today's hours, and on a tap a bar per month (the 15th of each). */ + private renderSunYear() { + const room = this.room; + const { latitude, longitude } = this.hass.config ?? {}; + if (!room || !this.floor || !this.building || latitude === undefined || longitude === undefined) return nothing; + const place = { latitude, longitude }; + const today = roomSun(this.building, this.floor, room, { ...place, zone: this.hass.config?.time_zone }); + if (!today.facing.length) return nothing; + const toggle = html``; + if (!this._sunYear) return toggle; + const months = roomSunYear(this.building, this.floor, room, place); + const top = Math.max(1, ...months); + const names = Array.from({ length: 12 }, (_, m) => new Date(2026, m, 15).toLocaleDateString(this.hass.language, { month: "narrow" })); + return html`${toggle} + `; + } + + /** Today's and this month's use of the room, with the month's cost at the house's tariff. */ + private renderEnergy() { + const e = this._energy; + if (!e || e.month <= 0) return nothing; + const id = this.building?.energy.tariff; + const st = id ? this.hass.states[id] : undefined; + const tariff = st ? { value: Number(st.state), unit: String(st.attributes.unit_of_measurement ?? "") } : null; + const cost = energyCost(e.month, tariff); + const kwh = (v: number) => `${formatNumber(this.hass, v, v < 10 ? 2 : 1)} kWh`; + return html`

+ ⚡ ${this.t("room_energy", { today: kwh(e.today), month: kwh(e.month) })}${cost ? ` · ${formatNumber(this.hass, cost.value, 2)} ${cost.currency}` : ""} +

`; + } + + /** The heating curve: the room's temperature over the last 24 hours, with its lowest and highest value. */ + private renderCurve() { + const curve = this._curve; + if (!curve) return nothing; + const values = curve.filter((v): v is number => v !== null); + const lo = Math.min(...values); + const hi = Math.max(...values); + const span = Math.max(1, hi - lo); + const shifted = curve.map((v) => (v === null ? null : v - lo + span * 0.1)); + const d = curvePath(shifted, 220, 36, span * 1.2); + const f = (v: number) => `${formatNumber(this.hass, fromCelsius(this.hass, v), 1)}°`; + return html`
+ + 24 h · ${f(lo)} – ${f(hi)} +
`; + } + + protected willUpdate(changed: Map): void { + const before = changed.get("room") as Room | null | undefined; + if (changed.has("room") && before?.id !== this.room?.id) { + this._folded = false; + this._undo = null; + } + if (this.room && this.hass && this.curveFor !== this.room.id) { + this.curveFor = this.room.id; + this._curve = null; + this._energy = null; + void this.loadCurve(this.room); + void this.loadEnergy(this.room); + } + } + + /** The host carries `folded`, so the stage it sits in can move a folded panel out of the way (see panel/styles.ts, card/styles.ts). */ + protected updated(changed: Map): void { + if (changed.has("_folded")) this.toggleAttribute("folded", this._folded); + } + + private t(key: I18nKey, vars?: Record): string { + return translate(this.hass, key, vars); + } + + private call(domain: string, service: string, data: Record): void { + void this.hass.callService(domain, service, data); + } + + /** "Clean": runs the script or presses the button that sends the robot vacuum to this room. */ + private renderClean(room: Room) { + const id = room.clean_entity; + const st = id ? this.hass.states[id] : undefined; + if (!id || !st) return nothing; + const domain = id.slice(0, id.indexOf(".")); + const run = () => (domain === "script" ? this.call("script", "turn_on", { entity_id: id }) : this.call(domain, "press", { entity_id: id })); + return html`
`; + } + + /** Switches off what is on in the room and offers to undo it for ten seconds. */ + private allOff(states: HassEntity[]): void { + const plan = allOffPlan(states); + for (const c of plan.off) this.call(c.domain, c.service, c.data); + this._undo = plan.undo; + clearTimeout(this.undoTimer); + this.undoTimer = setTimeout(() => (this._undo = null), 10_000); + } + + private undoAllOff(): void { + for (const c of this._undo ?? []) this.call(c.domain, c.service, c.data); + this._undo = null; + clearTimeout(this.undoTimer); + } + + /** "Everything off" while something is on, and its undo right after. */ + private renderAllOff(states: HassEntity[]): TemplateResult | typeof nothing { + if (this._undo) return html`
${this.t("all_off_done")}
`; + const { count } = allOffPlan(states); + if (count < 2) return nothing; + return html`
`; + } + + private get areaName(): string | undefined { + return this.room?.area_id ? this.hass.areas?.[this.room.area_id]?.name : undefined; + } + + /** The device as placed in the plan: it can carry an own name and a "switch only" flag. */ + private placedAs(id: string) { + for (const f of this.building?.floors ?? []) for (const p of f.placements) if (p.entity_id === id) return p; + return undefined; + } + + private name(id: string): string { + return this.placedAs(id)?.name?.trim() || entityName(this.hass, id, this.areaName); + } + + private nameButton(id: string) { + return html``; + } + + /** Ask first for devices marked so (a blind that must not move by accident). */ + private askFor(id: string): boolean { + return !this.confirmEntities?.has(id) || confirm(this.t("confirm_switch", { name: this.name(id) })); + } + + private toggle(st: HassEntity, on: boolean, onToggle: () => void) { + const guarded = () => { + if (this.confirmEntities?.has(st.entity_id) && !confirm(this.t("confirm_switch", { name: this.name(st.entity_id) }))) return; + onToggle(); + }; + return html``; + } + + /** Outside, shown like a room without an area. */ + private outsideRoom: Room | null = null; + + protected render() { + const outside = !this.room && this.outside ? this.outside : null; + if (outside && !this.outsideRoom) this.outsideRoom = { id: "nf-outside", name: this.t("outside_area"), area_id: null, points: [], floor_material: "grass" } as unknown as Room; + const room = this.room ?? (outside ? this.outsideRoom : null); + if (!room || !this.hass) return nothing; + const all = outside ?? roomEntities(this.hass, room); + // what the plan shows in the room; the rest of the area on request (each device's main entity); + // worked out once per registry, room and floor (every state change renders the panel again) + const m = this.memo; + const { shown, more } = outside + ? { shown: outside, more: [] as string[] } + : m && m.entities === this.hass.entities && m.floor === this.floor && m.room === room + ? m + : (this.memo = { entities: this.hass.entities, floor: this.floor, room, ...(this.floor ? roomPanelEntities(this.hass, this.floor, room) : { shown: all, more: [] }) }); + const extra = groupByDevice(this.hass, more).map((g) => g.primary); + const hiddenCount = extra.length; + const ids = this._showAll ? [...shown, ...extra] : shown; + const by = (kinds: DeviceKind[]) => ids.filter((id) => kinds.includes(kindOf(id)!)).map((id) => this.hass.states[id]); + const lights = by(["light"]); + const covers = by(["cover"]); + const climates = by(["climate"]); + const media = by(["media"]); + const switches = by(["switch", "fan", "lock"]); + const sensors = by(["sensor", "binary"]); + const scenes = by(["scene", "script"]); + const facts = this.facts(climates); + const lightsOn = lights.filter((l) => l.state === "on"); + return html`
+
+
+

${room.name}

+ ${facts.length ? html`

${facts.join(" · ")}

` : nothing} ${this.renderEnergy()} ${this.renderSunYear()} ${this.renderShade()} + ${this.renderOpenWhileHeating(climates)} ${this.renderEmptyLights(room, lightsOn)} + ${this.renderCurve()} +
+ + +
+
+ ${this.renderAllOff([...lights, ...media, ...switches])} + ${this.renderClean(room)} + ${!room.area_id && !outside + ? html`

${this.t("panel_no_area")}

` + : !ids.length + ? html`

${this.t("panel_empty")}

` + : nothing} + ${scenes.length + ? this.section( + "panel_scenes", + [ + html`
+ ${scenes.map( + (st) => html``, + )} +
`, + ], + ) + : nothing} + ${lights.length + ? this.section( + "panel_lights", + [...lights.map((st) => this.lightRow(st)), ...(room ? [this.renderMoods(room, lights)] : [])], + html`${lightsOn.length < lights.length + ? html`` + : nothing}${lightsOn.length + ? html`` + : nothing}`, + ) + : nothing} + ${covers.length + ? this.section( + "panel_covers", + covers.map((st) => this.coverRow(st)), + covers.length > 1 && groupCovers(covers, this.confirmEntities).length + ? html`` + : nothing, + ) + : nothing} + ${climates.length ? this.section("panel_climate", climates.map((st) => this.climateRow(st))) : nothing} + ${media.length ? this.section("panel_media", media.map((st) => this.mediaRow(st))) : nothing} + ${switches.length ? this.section("panel_switches", switches.map((st) => this.switchRow(st))) : nothing} + ${sensors.length ? this.section("panel_sensors", sensors.map((st) => this.sensorRow(st))) : nothing} + ${canAnnounce(this.hass) && roomHasSpeaker(this.hass, this.floor, room) ? this.announceSection(room) : nothing} + ${this.pluginSections(room, ids)} + ${hiddenCount + ? html`` + : nothing} +
+
`; + } + + /** Header facts: the room's temperature and humidity from its climate sensors (chosen or automatic). */ + private facts(climates: HassEntity[]): string[] { + const out: string[] = []; + const room = this.room; + // Outside has no climate of its own + if (!room) return out; + const value = (key: "temperature" | "humidity", fallbackUnit: string) => { + const v = roomClimateValue(this.hass, this.floor, room, key); + if (v === null) return null; + if (key === "temperature") return `${formatNumber(this.hass, fromCelsius(this.hass, v), 1)} ${tempUnit(this.hass)}`; + const first = roomClimateSensors(this.hass, this.floor, room, key)[0]; + const unit = (this.hass.states[first]?.attributes.unit_of_measurement as string | undefined) ?? fallbackUnit; + return `${formatNumber(this.hass, v, 1)} ${unit}`; + }; + const climateTemp = climates.find((c) => typeof c.attributes.current_temperature === "number"); + const temp = value("temperature", "°C"); + if (temp) out.push(temp); + else if (climateTemp && room.climate?.temperature !== "none") out.push(`${formatNumber(this.hass, climateTemp.attributes.current_temperature as number, 1)} ${tempUnit(this.hass)}`); + const hum = value("humidity", "%"); + if (hum) out.push(hum); + // what the room's devices draw now + const power = this.floor && this.building ? roomPower(this.hass, this.building, this.floor, room) : null; + if (power !== null) out.push(`⚡ ${powerText(this.hass, power)}`); + // how long its windows and doors stand open (the one open longest) + const openSince = this.floor + ? this.floor.openings + .filter((op) => op.room_id === room.id) + .flatMap((op) => [op.contact, op.contact2, op.tilt, op.tilt2]) + .map((id) => (id && id !== "none" ? this.hass.states[id] : undefined)) + .filter((st): st is HassEntity => st?.state === "on") + .map((st) => Date.parse(String(st.last_changed ?? ""))) + .filter(Number.isFinite) + : []; + if (openSince.length) out.push(`🪟 ${this.t("open_since", { time: sinceText(Date.now() - Math.min(...openSince)) })}`); + // someone there now, or when somebody was last seen (motion, occupancy, presence sensors of the room) + const seen = roomEntities(this.hass, room) + .map((id) => this.hass.states[id]) + .filter((st): st is HassEntity => !!st && st.entity_id.startsWith("binary_sensor.") && ["motion", "occupancy", "presence"].includes(String(st.attributes.device_class))); + if (seen.length) { + if (seen.some((st) => st.state === "on")) out.push(`🚶 ${this.t("presence_now")}`); + else { + const last = Math.max(...seen.map((st) => Date.parse(String(st.last_changed ?? "")) || 0)); + if (last > 0) out.push(`🚶 ${this.t("presence_last", { time: sinceText(Date.now() - last) })}`); + } + } + // the room's devices with a low battery + const low = this.building ? planBatteries(this.hass, this.building).filter((b) => b.roomId === room.id && b.level < LOW_BATTERY) : []; + if (low.length) out.push(`🪫 ${this.t("battery_low_n", { n: low.length, names: low.map((b) => `${this.name(b.entity)} ${Math.round(b.level)} %`).join(", ") })}`); + // the circuits of the fuse box that feed it + const circuits = (this.building?.settings.circuits ?? []).filter((c) => c.rooms.includes(room.id)).map((c) => c.name); + const off = this.building?.settings.room_facts_off ?? []; + if (circuits.length && !off.includes("circuits")) out.push(`🔌 ${circuits.join(", ")}`); + // hours of sun through its outside windows today + const { latitude, longitude, time_zone } = this.hass.config ?? {}; + if (this.floor && latitude !== undefined && longitude !== undefined && this.building && !off.includes("sun")) { + const sun = roomSun(this.building, this.floor, room, { latitude, longitude, zone: time_zone }); + if (sun.facing.length) out.push(`☀ ${this.t("room_sun_hours", { h: formatNumber(this.hass, sun.hours, 1), facing: sun.facing.join(", ") })}`); + } + // airing hints: too much CO₂, too damp, or a risk of mould at the coldest wall + const t = roomClimateValue(this.hass, this.floor, room, "temperature"); + const h = roomClimateValue(this.hass, this.floor, room, "humidity"); + const need = airingNeed(roomClimateValue(this.hass, this.floor, room, "co2"), h, mouldRisk(t, h)); + if (need && !off.includes("air")) out.push(`💨 ${this.t(`air_${need}`)}`); + // how comfortable it is (0 … 100) + const comfort = comfortScore(t, h, roomClimateValue(this.hass, this.floor, room, "co2"), isSummer(new Date(), this.hass.config?.latitude)); + if (comfort !== null && (t !== null || h !== null) && !off.includes("comfort")) out.push(`😊 ${this.t("comfort_n", { n: comfort })}`); + return out; + } + + /** Announcements in the room: a tap on a sentence says it on the room's speaker; an own message too. */ + private announceSection(room: Room) { + const phrases = this.phrases?.length ? this.phrases : [1, 2, 3, 4, 5].map((n) => this.t(`announce_phrase_${n}` as I18nKey)); + const say = (message: string) => { + const text = message.trim(); + if (!text) return; + clearTimeout(this.saidTimer); + this.hass.callService("nextfloor", "announce", { message: text, rooms: [room.id], on_screens: false }).then( + () => (this._said = { text: this.t("announce_sent", { message: text }), failed: false }), + (err: unknown) => (this._said = { text: this.t("announce_failed", { error: (err as { message?: string })?.message ?? String(err) }), failed: true }), + ); + this.saidTimer = setTimeout(() => (this._said = null), 6000); + }; + const own = (e: Event) => { + e.preventDefault(); + const input = (e.currentTarget as HTMLFormElement).querySelector("input")!; + say(input.value); + input.value = ""; + }; + return this.section("panel_announce", [ + html`
${phrases.map((p) => html``)}
+
+ + +
+ ${this._said ? html`

${this._said.text}

` : nothing}`, + ]); + } + + /** Blocks plugins add for this room, titled with the plugin's name. */ + private pluginSections(room: { id: string; name: string; area_id?: string | null }, ids: string[]) { + const sections = pluginRoomSections({ hass: this.hass, room: { id: room.id, name: room.name, area_id: room.area_id ?? null }, entities: ids }); + return sections.map( + (sec) => html`
+

${sec.title}

+ ${typeof sec.content === "string" ? html`

${sec.content}

` : sec.content} +
`, + ); + } + + private section(title: I18nKey, rows: unknown[], action: TemplateResult | typeof nothing = nothing) { + return html`
+

${this.t(title)}

${action}
+ ${rows} +
`; + } + + private lightRow(st: HassEntity) { + const a = st.attributes; + const on = st.state === "on"; + const modes = (a.supported_color_modes as string[] | undefined) ?? []; + const dimmable = modes.some((m) => m !== "onoff"); + const temp = modes.includes("color_temp"); + const color = modes.some((m) => ["hs", "rgb", "rgbw", "rgbww", "xy"].includes(m)); + const pct = typeof a.brightness === "number" ? Math.round((a.brightness / 255) * 100) : 100; + const kMin = (a.min_color_temp_kelvin as number | undefined) ?? 2200; + const kMax = (a.max_color_temp_kelvin as number | undefined) ?? 6500; + const id = st.entity_id; + const simple = !!this.placedAs(id)?.simple; + return html`
+ ${icon("light")} + ${this.nameButton(id)} + ${this.stateOf(st)} + ${this.toggle(st, on, () => this.call("light", "toggle", { entity_id: id }))} + ${on && dimmable && !simple + ? html`` + : nothing} + ${on && temp && !simple + ? html`` + : nothing} + ${on && color && !simple + ? html`
+ ${SWATCHES.map( + (c) => html``, + )} +
` + : nothing} +
`; + } + + private coverRow(st: HassEntity) { + const a = st.attributes; + const features = (a.supported_features as number | undefined) ?? 0; + const id = st.entity_id; + // a cover without feedback (a garage remote) stays unknown, but its buttons still work + const na = isUnavailable(st) && !assumedCover(st); + return html`
+ ${icon("cover")} + ${this.nameButton(id)} + ${this.stateOf(st)} +
+ + ${features & COVER_STOP + ? html`` + : nothing} + +
+ ${features & COVER_SET_POSITION && typeof a.current_position === "number" + ? html`` + : nothing} + ${features & 128 && typeof a.current_tilt_position === "number" + ? html`` + : features & 48 + ? html`
+ ${features & 16 ? html`` : nothing} + ${features & 32 ? html`` : nothing} +
` + : nothing} +
`; + } + + private climateRow(st: HassEntity) { + const a = st.attributes; + const id = st.entity_id; + const target = typeof a.temperature === "number" ? a.temperature : null; + const step = (a.target_temp_step as number | undefined) ?? 0.5; + const min = (a.min_temp as number | undefined) ?? 5; + const max = (a.max_temp as number | undefined) ?? 30; + const modes = (a.hvac_modes as string[] | undefined) ?? []; + const set = (v: number) => this.call("climate", "set_temperature", { entity_id: id, temperature: Math.min(max, Math.max(min, Math.round(v / step) * step)) }); + return html`
+ ${icon("climate")} + ${this.nameButton(id)} + ${this.stateOf(st)} + ${target !== null + ? html`
+ + ${this.t("target_temp")} ${formatNumber(this.hass, target, 1)} ${tempUnit(this.hass)} + +
` + : nothing} + ${modes.length > 1 + ? html`
+ ${modes.map( + (m) => html``, + )} +
` + : nothing} +
`; + } + + /** + * The state text of a row: left out when the room says so (D154) or when a device that is not a + * sensor only reports "unknown" (covers without position feedback). + */ + private stateOf(st: HassEntity, text = stateText(this.hass, st)): string { + if (this.room?.no_state?.includes(st.entity_id)) return ""; + const kind = kindOf(st.entity_id); + if (st.state === "unknown" && kind !== "sensor" && kind !== "binary") return ""; + return text; + } + + private stateLabel(state: string): string { + const key = `state_${state}` as I18nKey; + const s = this.t(key); + return s === key ? state : s; + } + + private mediaRow(st: HassEntity) { + const a = st.attributes; + const id = st.entity_id; + const na = isUnavailable(st) || st.state === "off"; + const title = [a.media_title, a.media_artist].filter((x) => typeof x === "string" && x).join(" · "); + return html`
+ ${icon("media")} + ${this.nameButton(id)} + ${this.stateOf(st, this.stateLabel(st.state))} + ${title ? html`

${title}

` : nothing} +
+ + + +
+ ${typeof a.volume_level === "number" + ? html`` + : nothing} +
`; + } + + private switchRow(st: HassEntity) { + const id = st.entity_id; + const kind = kindOf(id)!; + const domain = id.slice(0, id.indexOf(".")); + const on = kind === "lock" ? st.state === "unlocked" || st.state === "open" : isActive(st); + const act = () => (kind === "lock" ? this.call("lock", on ? "lock" : "unlock", { entity_id: id }) : this.call(domain, "toggle", { entity_id: id })); + return html`
+ ${icon(kind)} + ${this.nameButton(id)} + ${this.stateOf(st)} + ${this.toggle(st, on, act)} +
`; + } + + private sensorRow(st: HassEntity) { + const kind = kindOf(st.entity_id)!; + const warn = kind === "binary" && st.state === "on"; + return html`
+ ${icon(kind)} + ${this.nameButton(st.entity_id)} + ${this.stateOf(st)} +
`; + } + + private fire(type: string): void { + this.dispatchEvent(new CustomEvent(type, { bubbles: true, composed: true })); + } + + static styles = [ + tokens, + controls, + css` + :host { + display: block; + } + .nf-rp { + /* the host may be pointer-events: none so the 3D view stays usable around the panel */ + pointer-events: auto; + display: flex; + flex-direction: column; + max-height: 100%; + background: var(--nf-chrome-solid); + border: 1px solid var(--nf-line); + border-radius: 18px; + box-shadow: var(--nf-shadow); + overflow: hidden; + } + .nf-rp-head { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 14px 14px 10px 16px; + border-bottom: 1px solid var(--nf-line); + } + .nf-rp-head > div { + flex: 1; + min-width: 0; + } + h2 { + margin: 0; + font: 700 21px var(--nf-title-font); + letter-spacing: -0.01em; + } + .nf-rp-facts { + margin: 2px 0 0; + color: var(--nf-muted); + font-size: 13px; + font-variant-numeric: tabular-nums; + } + @media (pointer: coarse) { + .nf-rp-close { + width: 40px; + height: 40px; + } + .nf-rp-swatch { + width: 36px; + height: 36px; + } + .nf-rp-small { + min-height: 36px; + } + } + .nf-rp-close { + display: grid; + place-items: center; + width: 34px; + height: 34px; + border-radius: 50%; + border: none; + background: color-mix(in srgb, var(--nf-text) 6%, transparent); + color: var(--nf-text); + cursor: pointer; + } + .nf-rp-body[hidden] { + display: none; + } + .nf-rp-head:has(+ .nf-rp-body[hidden]) { + border-bottom: none; + } + .nf-rp-body { + overflow-y: auto; + padding: 6px 14px 16px 16px; + display: grid; + gap: 14px; + overscroll-behavior: contain; + } + .nf-rp-shade { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin: 4px 0; + padding: 6px 8px; + border-radius: 8px; + font-size: 12px; + background: color-mix(in srgb, var(--nf-warm) 16%, transparent); + } + .nf-rp-sun-year { + border: none; + background: none; + color: var(--nf-muted); + font: inherit; + font-size: 12px; + padding: 2px 0; + cursor: pointer; + } + .nf-rp-sun-bars { + display: grid; + grid-template-columns: repeat(12, 1fr); + gap: 3px; + height: 54px; + margin: 2px 0 6px; + } + .nf-rp-sun-bars span { + display: flex; + flex-direction: column; + justify-content: flex-end; + align-items: center; + gap: 2px; + } + .nf-rp-sun-bars i { + display: block; + width: 100%; + min-height: 2px; + border-radius: 3px 3px 0 0; + background: var(--nf-warm); + } + .nf-rp-sun-bars b { + font-size: 10px; + font-weight: 500; + color: var(--nf-muted); + } + .nf-rp-alloff { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + margin: 6px 0 2px; + font-size: 13px; + color: var(--nf-muted); + } + .nf-rp-note { + color: var(--nf-muted); + font-size: 13px; + margin: 8px 0 0; + } + .nf-rp-sec-head { + display: flex; + align-items: center; + justify-content: space-between; + margin-top: 6px; + } + h3 { + margin: 0; + font-size: 11.5px; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--nf-muted); + } + .nf-rp-row { + display: grid; + grid-template-columns: 28px 1fr auto auto; + align-items: center; + gap: 6px 10px; + padding: 9px 0; + border-bottom: 1px solid var(--nf-line); + } + .nf-rp-row:last-child { + border-bottom: none; + } + .nf-rp-row > :nth-child(n + 5), + .nf-rp-row > .nf-rp-wide { + grid-column: 2 / -1; + } + .nf-rp-icon { + display: grid; + place-items: center; + width: 28px; + height: 28px; + border-radius: 50%; + color: var(--nf-muted); + background: color-mix(in srgb, var(--nf-soft) 12%, transparent); + } + .nf-rp-on { + color: #2a1a00; + background: var(--nf-warm); + box-shadow: 0 0 14px rgba(255, 181, 71, 0.55); + } + .nf-rp-name { + font: inherit; + font-weight: 500; + color: var(--nf-text); + background: none; + border: none; + padding: 0; + text-align: left; + cursor: pointer; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .nf-rp-state { + font-size: 12.5px; + color: var(--nf-muted); + font-variant-numeric: tabular-nums; + white-space: nowrap; + max-width: 110px; + overflow: hidden; + text-overflow: ellipsis; + } + .nf-rp-row > .nf-rp-state:last-child { + grid-column: 3 / -1; + justify-self: end; + } + .nf-switch { + position: relative; + width: 44px; + height: 26px; + border-radius: 999px; + border: none; + background: color-mix(in srgb, var(--nf-text) 10%, transparent); + cursor: pointer; + } + .nf-switch::after { + content: ""; + position: absolute; + top: 3px; + left: 3px; + width: 20px; + height: 20px; + border-radius: 50%; + background: #e6eefc; + transition: transform 0.2s ease; + } + .nf-switch[aria-checked="true"] { + background: var(--nf-warm); + } + .nf-switch[aria-checked="true"]::after { + transform: translateX(18px); + } + .nf-switch:disabled { + opacity: 0.4; + cursor: default; + } + .nf-rp-slider { + display: grid; + grid-template-columns: 110px 1fr; + align-items: center; + gap: 10px; + font-size: 12px; + color: var(--nf-muted); + } + .nf-rp-slider input { + width: 100%; + accent-color: var(--nf-accent); + } + .nf-rp-ct input { + accent-color: var(--nf-warm); + } + .nf-rp-swatches, + .nf-rp-buttons, + .nf-rp-chips, + .nf-rp-say { + display: flex; + gap: 8px; + margin-top: 8px; + } + .nf-rp-say input { + flex: 1; + min-width: 0; + font: inherit; + font-size: 14px; + color: var(--nf-text); + background: var(--nf-fill); + border: none; + border-bottom: 1px solid var(--nf-line); + border-radius: 10px 10px 4px 4px; + padding: 8px 10px; + } + .nf-rp-fail { + color: #ff6b7a; + } + .nf-rp-moods { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 6px; + } + .nf-rp-mood { + display: inline-flex; + gap: 2px; + align-items: center; + } + .nf-rp-mood-to { + width: 38px; + font: inherit; + background: var(--nf-bg2); + color: var(--nf-text); + border: 1px solid var(--nf-line); + border-radius: 8px; + } + .nf-rp-mood input { + width: 120px; + font: inherit; + padding: 4px 8px; + border-radius: 8px; + border: 1px solid var(--nf-line); + background: var(--nf-bg2); + color: var(--nf-text); + } + .nf-rp-curve { + position: relative; + margin-top: 4px; + width: 220px; + max-width: 100%; + } + .nf-rp-curve svg { + display: block; + width: 100%; + height: 30px; + } + .nf-rp-curve path { + fill: none; + stroke: var(--nf-warm, #ff9f43); + stroke-width: 1.5; + vector-effect: non-scaling-stroke; + } + .nf-rp-curve span { + font-size: 10.5px; + color: var(--nf-muted); + } + .nf-rp-scenes { + display: flex; + flex-wrap: wrap; + gap: 6px; + } + .nf-rp-swatch { + width: 26px; + height: 26px; + border-radius: 50%; + border: 1px solid color-mix(in srgb, var(--nf-text) 20%, transparent); + background: var(--c); + box-shadow: 0 0 10px var(--c); + cursor: pointer; + } + .nf-rp-more { + justify-self: start; + } + .nf-rp-small { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 5px 10px; + min-height: 30px; + font-size: 13px; + } + .nf-rp-stepper { + display: flex; + align-items: center; + gap: 10px; + font-variant-numeric: tabular-nums; + font-weight: 600; + } + .nf-rp-stepper small { + color: var(--nf-muted); + font-weight: 500; + margin-right: 4px; + } + .nf-rp-stepper .nf-btn { + width: 36px; + padding: 4px 0; + font-size: 17px; + } + .nf-rp-chips .nf-chip { + box-shadow: none; + border: 1px solid var(--nf-line); + min-height: 30px; + padding: 4px 11px; + font-size: 13px; + } + .nf-rp-media { + margin: 0; + font-size: 12.5px; + color: var(--nf-muted); + } + button:focus-visible, + input:focus-visible { + outline: 2px solid var(--nf-accent); + outline-offset: 2px; + } + `, + ]; +} + +if (!customElements.get("nf-room-panel")) customElements.define("nf-room-panel", NfRoomPanel); diff --git a/frontend/src/components/view3d.ts b/frontend/src/components/view3d.ts new file mode 100644 index 0000000..6d48d24 --- /dev/null +++ b/frontend/src/components/view3d.ts @@ -0,0 +1,4416 @@ +// Lit wrapper around the lazily loaded 3D viewer. + +import { changeMoments, hassAt, loadHistory, replayable, type History } from "../live/time-travel.ts"; +import { sunPosition, todayAt } from "../sun-position.ts"; +import { dayCurves, statesRead, type DayCurves } from "../live/day-curves.ts"; +import { backdropStyle } from "../backdrop.ts"; +import { css, html, LitElement, nothing, svg, type PropertyValues } from "lit"; +import { type CarState, roomClimateValue, entityName, furnitureEntities, isActive, isCooling, isMotionSensor, coverReaches, deviceSiblings, hasPost, minutesText, pickupDays, plantThirst, remainingMinutes, gangGlows, gangEntities, isUnavailable, kindOf, markerKind, type MarkerKind, lightGlow, openingEntities, openingState, isUnlocked, TOGGLE_KINDS, type FurnitureLinks, type OpeningEntities, confirmEntities, coolingTemps, deviceTempOf, DEVICE_HOT, fridgeDoors, hasScreen, fromCelsius, toCelsius, tempUnit, robotRoom, robotRoomSensor, isStatusSensor, floorControls, favoriteCall, runButton, ownButtonOn, roomEntities } from "../devices.ts"; +import { liveScreens, liveSprays, readSun, roofWindowStates, skyLightness } from "./view3d/live-inputs.ts"; +import { watchedEntities } from "./view3d/watch-list.ts"; +import { roomToggleLights, roomToggleMode, type RoomToggle } from "./view3d/room-toggle.ts"; +import { ownTaps } from "./view3d/own-taps.ts"; +import { lightAnimation, lightEffectSource } from "../light-effects.ts"; +import type { PlacementInfo } from "../plugins/api.ts"; +import { onPluginsChanged, pluginTap } from "../plugins/registry.ts"; +import { alertColor, alertSources, alertText, contactsPending, findAlerts, QUIET_ALERTS, type Alert, type AlertSources } from "../alerts.ts"; +import { iconPath, iconSvg, mdiIcon } from "../icons.ts"; +import { deviceSensors, energySummary, findConsumers, powerSensorFor, readPower, subMeterIds, subMeterLabel, type Consumer, type EnergySummary } from "../energy.ts"; +import { mapCredit, mapShown } from "../map-geo.ts"; +import { type CustomButton, type EntityRef } from "../model.ts"; + +import { STAGE, type Theme } from "../themes.ts"; +import { heatColor, heatGradient, roomValues, scaleOf, type HeatMode } from "../heatmap.ts"; +import { airingNeed, isSummer, mouldRisk } from "../live/room-climate.ts"; +import { furnitureName } from "../furniture-names.ts"; +import { formatNumber, translate, type I18nKey } from "../i18n.ts"; +import { getPacks, hasMovingParts, householdKind, mountBase, packItem, packsVersion } from "../packs.ts"; +import { parkedVehicle, parkedVehicles, vehicleFurniture } from "../parking.ts"; +import { gateStates } from "../entities/gates.ts"; +import { weatherEntity } from "../weather.ts"; +import { chosenEffects, readSkyWeather, withDensity } from "../live/sky-weather.ts"; +import { energyPicture, houseHub, type EnergyPicture } from "../live/energy-flow.ts"; +import { loadWeek, type WeekBars } from "../live/week-bars.ts"; +import { binsDue, loadToday, sortDay, type TodayItem } from "../live/today.ts"; +import { forecastDays, loadForecast } from "../live/forecast.ts"; +import { isPrinter3d, readPrinter, type PrinterInfo } from "../live/printer.ts"; +import { isHeatPump, readHeatPump, type HeatPumpInfo } from "../live/heat-pump.ts"; +import { coverageColor, isAccessPoint, networkHealth, readAccessPoint } from "../live/wifi.ts"; +import type { FurnitureColors } from "../furniture-colors.ts"; +import { renderLhCards, liveCardStyles, unstackLhCards, type LiveCard } from "../live/cards.ts"; +import { readCar, type CarInfo } from "../live/car.ts"; +import { mediaNow, multiroom, type MediaNow } from "../live/media.ts"; +import { SHOW_PRESENCE } from "../flags.ts"; +import { searchIndex, searchItems, type SearchItem } from "../search.ts"; +import { coverPositionable, lightAbilities } from "./quick-menu.ts"; +import "./quick-menu.ts"; +import { load3d } from "../load3d.ts"; +import { scaleGlow, buildMarkers, openMoreInfo, stateText, toggleEntity, withPluginPatch } from "../markers.ts"; +import { fanSpin } from "../entities/fans.ts"; +import { fixtureGlow } from "../entities/kinds.ts"; +import { furnitureShown, hiddenFurniture, withoutHidden } from "../entities/visibility.ts"; +import { pictureUrl } from "../entities/pictures.ts"; +import { fetchImage } from "../api.ts"; +import { ceilingOf, centroid, furnitureFootprint, groundLevel, isLamp, LAMP_MODEL, outdoorGround, outdoorTopAt, pointInPolygon, polygonArea, surfaceHeight, type Building, type Furniture, type Placement, type StartView } from "../model.ts"; +import { floorCounts, floorInfoText, personsInRooms, powerText } from "../presence.ts"; +import { controls, tokens } from "../styles.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; +import { claim, forThisScreen, playAnnouncement, showFor, subscribeAnnouncements, type Announcement } from "../live/announce.ts"; +import { mapCamera, readVacuum } from "../live/vacuum-map.ts"; +import type { DeviceMarker, LivePictureInput, NextFloorViewer, FloorStack, RobotInfo, Quality, ScreenState, SurfaceGrab, ViewerStats, WallMode } from "../viewer/viewer3d.ts"; + +/** Which HTML markers are shown: none, only what has no 3D object or shows a value, or all. */ +export type MarkerMode = "none" | "important" | "all"; + + + +/** Where the clock sits in the view. */ +export type ClockCorner = "top_left" | "top_right" | "bottom_left" | "bottom_right"; + +const LOCK_KEY = "nextfloor.lock3d"; + + +/** Below this stage height (px) the floor pictures get small and stop above the buttons at the bottom. */ +const SHORT_STAGE = 520; + +export class NfView3d extends LitElement { + static properties = { + hass: { attribute: false }, + building: { attribute: false }, + floorId: { attribute: false }, + roomId: { attribute: false }, + wallMode: { attribute: false }, + solidWalls: { attribute: false }, + glassWalls: { attribute: false }, + explode: { type: Boolean }, + keepRoof: { attribute: false }, + markerMode: { attribute: false }, + markerNames: { attribute: false }, + markersOutside: { attribute: false }, + tapInRoom: { type: Boolean }, + roomDoubleTap: { attribute: false }, + heatMode: { attribute: false }, + theme: { attribute: false }, + accent: { attribute: false }, + furnitureColors: { attribute: false }, + packs: { attribute: false }, + showEnergy: { attribute: false }, + flows: { attribute: false }, + holograms: { attribute: false }, + furnish: { type: Boolean }, + surfaceGrab: { attribute: false }, + furnishTypes: { attribute: false }, + weather: { type: Boolean }, + weatherEntityId: { attribute: false }, + weatherDensity: { attribute: false }, + timeOfDay: { attribute: false }, + selectedFurniture: { attribute: false }, + selectedDevice: { attribute: false }, + _sky: { state: true }, + quality: { attribute: false }, + showStats: { type: Boolean }, + _stats: { state: true }, + _error: { state: true }, + _energy: { state: true }, + _flows: { state: true }, + _liveEnergy: { state: true }, + _liveCards: { state: true }, + _liveCardOn: { state: true }, + _houseFolded: { state: true }, + _swipe: { state: true }, + _menu: { state: true }, + _pluginWindow: { state: true }, + _plate: { state: true }, + _blend: { state: true }, + _wallBig: { state: true }, + _find: { state: true }, + _central: { state: true }, + _thumbsCompact: { state: true }, + _armed: { state: true }, + central: { attribute: false }, + centralOpen: { attribute: false }, + keepCamera: { attribute: false }, + plain: { attribute: false }, + rightBack: { attribute: false }, + templateName: { attribute: false }, + readable: { type: Boolean, reflect: true }, + today: { attribute: false }, + _todayOpen: { state: true }, + _todayItems: { state: true }, + _forecast: { state: true }, + zoom: { attribute: false }, + buttons: { attribute: false }, + _thumbs: { state: true }, + floorThumbs: { attribute: false }, + clean: { attribute: false }, + cleanButton: { attribute: false }, + clock: { attribute: false }, + lockButton: { attribute: false }, + walkButton: { attribute: false }, + travelButton: { attribute: false }, + _travel: { state: true }, + _walking: { state: true }, + _stick: { state: true }, + _locked: { state: true }, + _now: { state: true }, + roomLabels: { attribute: false }, + floorStack: { attribute: false }, + panelOpen: { attribute: false }, + alerts: { attribute: false }, + alertJump: { attribute: false }, + scenes: { attribute: false }, + announcements: { attribute: false }, + sensorBar: { attribute: false }, + screenName: { attribute: false }, + _announcement: { state: true }, + dimmed: { attribute: false }, + autoOrbit: { attribute: false }, + startView: { attribute: false }, + outsideOpen: { attribute: false }, + _low: { state: true }, + _narrowStage: { state: true }, + _shortStage: { state: true }, + _phoneStage: { state: true }, + _alerts: { state: true }, + _sceneFired: { state: true }, + }; + + declare hass: HomeAssistant; + /** This view is a screen announcements show and speak on (the panel's 3D view and cards, not the editor's). */ + declare announcements: boolean; + /** The plan's own sensors at the top (cards can switch them off). */ + declare sensorBar: boolean; + /** The name of this screen, for announcements meant for some screens only. */ + declare screenName: string | null; + /** The announcement on screen now, and when it goes. */ + private declare _announcement: { message: string; until: number } | null; + private stopAnnouncements: (() => void) | null = null; + private announceTimer: ReturnType | undefined; + declare building: Building | null; + declare floorId: string | null; + declare roomId: string | null; + declare wallMode: WallMode; + /** Solid walls in their paint instead of glass. */ + declare solidWalls: boolean; + /** How opaque the see-through walls are in % (null: the usual 20 %). */ + declare glassWalls: number | null; + declare explode: boolean; + /** The roof stays while zooming in (no lift, no fade). */ + declare keepRoof: boolean; + declare markerMode: MarkerMode; + /** Card option marker_names: every device with an own name shows it under its pin. */ + declare markerNames: boolean; + /** Card option markers_outside: outside the opened room only these kinds of markers show (null: as in the room). */ + declare markersOutside: MarkerKind[] | null; + /** Card option tap_in_room: a tap switches a device only in the opened room, elsewhere it opens the floor or room. */ + declare tapInRoom: boolean; + /** Card option room_double_tap: what a double tap on a room switches (auto = the plan setting). */ + declare roomDoubleTap: RoomToggle | "auto"; + declare heatMode: HeatMode; + /** Imported furniture packs (a new list rebuilds pack furniture). */ + declare packs: unknown; + declare theme: Theme; + /** Accent colour for the neon look ("#rrggbb"), null for the stock cyan. */ + declare accent: string | null; + /** The card's own furniture colours, on top of the house-wide ones (#82). */ + declare furnitureColors: FurnitureColors | null; + /** Show the energy values at the top (cards can switch them off). */ + declare showEnergy: boolean; + /** Power flow lines fixed on or off (cards); null: the viewer's own toggle decides. */ + declare flows: boolean | null; + /** The live cards (house, car, media) always on or off (card option "holograms"); null = the bar's own switch. */ + declare holograms: boolean | null; + + private get liveCardsOn(): boolean { + return this.holograms ?? this._liveCardOn; + } + /** Furnishing: furniture and lamps are dragged in 3D (admins, panel only). */ + declare furnish: boolean; + /** Editor: moves solar fields and roof windows with rays from the camera (null: none). */ + declare surfaceGrab: SurfaceGrab | null; + /** Editor: only these furniture types can be moved in 3D (null: all). */ + declare furnishTypes: readonly string[] | null; + /** Weather outside: rain, snow, fog and clouds from a weather entity, sun and moon from sun.sun. */ + declare weather: boolean; + /** The weather entity to use (null: the first one). */ + declare weatherEntityId: string | null; + /** How much of the rain, hail and snow falls (1: all of it). */ + declare weatherDensity: number; + /** Hours of today whose sun the view shows instead of the real one (the time-of-day slider); null: the real sun. */ + declare timeOfDay: number | null; + /** A lightning flash lights the stage for a moment. */ + private cloud = 0; + /** Entities that ask before a tap switches them. */ + private confirmSet = new Set(); + declare selectedFurniture: string | null; + declare selectedDevice: string | null; + /** How much daylight there is (0 = night, 1 = day), from sun.sun. */ + private declare _sky: number; + declare quality: Quality; + declare showStats: boolean; + private declare _stats: ViewerStats | null; + private declare _error: string | null; + private declare _energy: EnergySummary | null; + /** The start view last handed to the viewer (JSON), to notice a new one. */ + private shownStartView: string | undefined; + /** A running swipe on a lamp or blind: the value shown next to the finger. */ + private declare _swipe: { entity: string; kind: "light" | "cover" | "fan"; start: number; value: number; x: number; y: number } | null; + /** Quick menu at a device (long press). */ + private declare _menu: { entity: string; x: number; y: number; car?: CarState } | null; + /** A window a plugin opened in the lower right corner (a camera's live picture). */ + private declare _pluginWindow: { node: Node; title: string } | null; + /** Where each placed device stands, for plugins that handle its taps. */ + private placementInfo = new Map(); + /** The buttons of a tapped switch plate or socket to pick from. */ + private declare _plate: { ids: string[]; x: number; y: number } | null; + /** Looking through a camera: its live picture lies over the 3D view; `back` is the view to return to. */ + /** Camera wall: the camera shown big (null: all tiles). */ + private declare _wallBig: string | null; + /** The look-through was started from the camera wall: going back reopens the wall. */ + /** Camera wall, big picture: Home Assistant's own stream player (a picture-entity card in live view), one at a time. */ + private live: { id: string; el: (HTMLElement & { hass?: unknown }) | null; failed: boolean } | null = null; + /** How strongly the camera picture covers the 3D view (0 = only 3D, 1 = only the picture). */ + private declare _blend: number; + /** Floor switcher with small pictures of the floors (panel and card; off with a fixed floor). */ + declare floorThumbs: boolean; + /** 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"). */ + declare cleanButton: boolean; + /** A clock in a corner of the view (null: none). */ + declare clock: ClockCorner | null; + /** Show the 🔒 button that locks the camera (a wall tablet nobody should turn by accident). */ + declare lockButton: boolean; + /** Show the 🚶 button that walks through the house at eye level. */ + declare walkButton: boolean; + /** Show the ⏪ button that replays the last day or week. */ + declare travelButton: boolean; + /** Time travel: the loaded history, its span, the moment shown, and whether it plays (null: live). */ + private declare _travel: { history: History; from: number; to: number; t: number; playing: boolean; speed: number; hours: number; moments: number[]; loading: boolean } | null; + private travelTimer: ReturnType | undefined; + /** The house card's day curves and when they were last loaded. */ + private dayCurves: DayCurves | null = null; + private curvesAt = 0; + private declare _walking: boolean; + /** Where the touch stick's knob is (-1 … 1 each way) while a finger holds it. */ + private declare _stick: [number, number] | null; + /** The camera is locked on this device. */ + private declare _locked: boolean; + /** The time the clock shows, refreshed every few seconds while a clock is shown. */ + private declare _now: number; + private clockTimer: ReturnType | undefined; + /** Room names in 3D (cards can switch them off). */ + declare roomLabels: boolean; + /** Floors below an opened floor: dimmed, stacked (the house up to it) or hidden. */ + declare floorStack: FloorStack; + private declare _thumbs: { floorId: string; url: string }[]; + /** The viewer runs at the tablet level: heavy CSS effects are left out as well. */ + private declare _low: boolean; + /** A room panel (or sheet) is open next to the view: on small screens the view's own controls hide. */ + declare panelOpen: boolean; + /** The stage is narrower than 700 px (smaller floor pictures, phone layout). */ + private declare _narrowStage: boolean; + /** The stage is low (a small card): the floor pictures leave room for the buttons below them. */ + private declare _shortStage: boolean; + /** The stage is as narrow as a phone held upright: the floor pictures step aside, the floor tabs above do the job (#70). */ + private declare _phoneStage: boolean; + private stopPlugins: (() => void) | null = null; + private pluginsDirty = false; + private resizeObs: ResizeObserver | null = null; + /** Warnings (smoke, water, alarm, window in the rain): pulsing rooms and a banner; jump to new ones. */ + declare alerts: boolean; + declare alertJump: boolean; + private declare _alerts: Alert[]; + private alertSrc: AlertSources | null = null; + private alertTimer: ReturnType | undefined; + /** Looks again at contacts that went unavailable, until their grace time has passed. */ + private contactTimer: ReturnType | undefined; + private seenAlerts = new Set(); + /** A room briefly lit up after a double tap switched its lights. */ + private roomFlash: { roomId: string; until: number } | null = null; + /** Scene and script chips of the selected room. */ + declare scenes: boolean; + private declare _sceneFired: string | null; + /** Night (kiosk): no effects, cables or floor pictures. */ + declare dimmed: boolean; + /** Screensaver: the view turns slowly by itself. */ + declare autoOrbit: boolean; + /** A start view of the card's own (YAML `start_view`); else the one remembered in the editor. */ + declare startView: StartView | null; + /** Outside is open: the camera flies to Outside's own view, if the plan has one (#83). */ + declare outsideOpen: boolean; + /** Search index (rooms and devices), built when the search opens and reused while it is open. */ + private findIndex: SearchItem[] | null = null; + /** Room colours (heatmap) as last sent to the viewer. */ + private tintSig = ""; + private thumbTimer: ReturnType | undefined; + /** What the floor pictures show of the devices (lamps, blinds): they are drawn again when it changes. */ + private thumbSig = ""; + private thumbsAt = 0; + /** Search ("where is …?"): null = closed. */ + private declare _find: string | null; + /** Floor pictures folded to plain floor buttons (D177), remembered per device. */ + private declare _thumbsCompact: boolean; + /** The central menu (all lights / blinds of the floor or house, favourites) is open (#145). */ + private declare _central: boolean; + /** A house-wide action waiting for its second tap ("sure?"), with the time it was armed. */ + private declare _armed: string | null; + private armTimer: ReturnType | undefined; + /** Show the star with the central menu (card option central; default on). */ + declare central: boolean; + /** The star menu stands open from the start, a size larger (a wall tablet whose main use are its favourites). */ + declare centralOpen: boolean; + /** Switching floors keeps the camera's side, height and distance. */ + declare keepCamera: boolean; + /** Only the floor plan: no furniture in 3D. */ + declare plain: boolean; + /** A short right click goes back one step. */ + declare rightBack: boolean; + /** The card template this card uses (for "reload the screens of this template"). */ + declare templateName: string | null; + /** Easy to read: the pins and labels in the 3D view a size larger. */ + declare readable: boolean; + /** The "Today" card top right: appointments of the plan's calendars and the bins due (default on). */ + declare today: boolean; + private declare _todayOpen: boolean; + private declare _todayItems: TodayItem[]; + /** The weather entity's daily forecast as Home Assistant answered it (see live/forecast.ts). */ + private declare _forecast: unknown; + private forecastAt = 0; + private forecastKey = ""; + private todayAt = 0; + private todayDay = ""; + /** How much closer the fitted views come (1 = fitted). */ + declare zoom: number; + /** Own buttons from the card's YAML (replace the house's buttons when set). */ + declare buttons: CustomButton[] | null; + private swipeSent = 0; + private swipeTimer: ReturnType | undefined; + /** Energy cables from the meter to the consumers (off unless switched on; kept per browser). */ + private declare _flows: boolean; + /** NextFloor's energy picture (flows, house balance) and the floating cards with their plan points. */ + private declare _liveEnergy: EnergyPicture | null; + private declare _liveCards: LiveCard[]; + /** The floating cards show (the viewer's choice, kept in the browser). */ + private declare _liveCardOn: boolean; + /** The house card folded to its ring by the small corner button; remembered in this browser. */ + private declare _houseFolded: boolean; + + private viewer: NextFloorViewer | null = null; + private starting = false; + /** States of the placed entities as last sent to the viewer. */ + private shownStates = new Map(); + private shownPacks = -1; + /** Entities of each door and window, and the registry they were matched with. */ + private openingLinks: Map | null = null; + private linkedRegistry: HomeAssistant["entities"] | undefined; + /** Entities of electric furniture (TV, fridge, …). */ + private furnitureLinks = new Map(); + /** Pins of items with their own tap action (pin id → item id): a tap on them runs the action. */ + private tapPins = new Map(); + /** Room values of the current heatmap (for the legend). */ + private heatValues = new Map(); + /** Entities whose state changes redraw markers, cables, people and floor labels. */ + private watched: string[] = []; + /** Screens showing a camera: their snapshots are refreshed every few seconds (a changing query parameter). */ + /** The look through a camera itself opens this floor: that floor change must not end it. */ + + constructor() { + super(); + this.building = null; + this.floorId = null; + this.roomId = null; + this.wallMode = "auto"; + this.solidWalls = false; + this.glassWalls = null; + this.explode = true; + this.keepRoof = false; + this.markerMode = "important"; + this.markersOutside = null; + this.tapInRoom = false; + this.roomDoubleTap = "auto"; + this.heatMode = "none"; + this.theme = "neon"; + this.accent = null; + this.furnitureColors = null; + this.furnish = false; + this.weather = true; + this.weatherEntityId = null; + this.weatherDensity = 1; + this.showEnergy = true; + this.flows = null; + this._liveEnergy = null; + this._liveCards = []; + this._liveCardOn = localStorage.getItem("nextfloor.cards") !== "0"; + this._houseFolded = localStorage.getItem("nextfloor.house_card_folded") === "1"; + this.selectedFurniture = null; + this.selectedDevice = null; + this._sky = 0; + this.quality = "auto"; + this.showStats = false; + this._stats = null; + this._error = null; + this._energy = null; + this._swipe = null; + this._menu = null; + this._pluginWindow = null; + this._plate = null; + this._wallBig = null; + this._blend = 0.6; + this._find = null; + this._central = false; + try { + this._thumbsCompact = localStorage.getItem("nextfloor.thumbs_compact") === "1"; + } catch { + this._thumbsCompact = false; + } + this._armed = null; + this.central = true; + this.buttons = null; + this._thumbs = []; + this.floorThumbs = true; + this.clean = false; + this.cleanButton = false; + this.clock = null; + this.lockButton = false; + this.walkButton = false; + this.travelButton = false; + this._travel = null; + this._walking = false; + this._stick = null; + this._now = Date.now(); + this._locked = (() => { + try { + return localStorage.getItem(LOCK_KEY) === "1"; + } catch { + return false; + } + })(); + this.roomLabels = true; + this.floorStack = "dim"; + this._low = false; + this.panelOpen = false; + this._narrowStage = false; + this._shortStage = false; + this._phoneStage = false; + this.alerts = true; + this.alertJump = false; + this.announcements = false; + this.sensorBar = true; + this.screenName = null; + this._announcement = null; + this._alerts = []; + this.scenes = true; + this._sceneFired = null; + this.dimmed = false; + this.autoOrbit = false; + this.startView = null; + this.outsideOpen = false; + this.holograms = null; + try { + this._flows = localStorage.getItem("nextfloor.flows") === "1"; + } catch { + this._flows = false; + } + } + + connectedCallback(): void { + super.connectedCallback(); + // a plugin that registers later changes markers: rebuild them in the next update (through updated(), + // like any other forced change), not only on the next state change + this.stopPlugins = onPluginsChanged(() => { + this.pluginsDirty = true; + this.requestUpdate(); + }); + if (this.hasUpdated) { + this.observeStage(); + if (!this.viewer) void this.start(); + } + } + + disconnectedCallback(): void { + super.disconnectedCallback(); + this.stopPlugins?.(); + this.stopPlugins = null; + this.listenToAnnouncements(false); + this.resizeObs?.disconnect(); + this.resizeObs = null; + clearInterval(this.alertTimer); + this.alertTimer = undefined; + clearInterval(this.contactTimer); + this.contactTimer = undefined; + clearInterval(this.clockTimer); + this.clockTimer = undefined; + clearInterval(this.travelTimer); + this.travelTimer = undefined; + this.live = null; + this.viewer?.dispose(); + this.viewer = null; + } + + protected firstUpdated(): void { + this.observeStage(); + void this.start(); + } + + /** Follows the stage's width: the floor pictures shrink on narrow screens. */ + private observeStage(): void { + const stage = this.renderRoot.querySelector(".nf-stage"); + if (!stage || this.resizeObs || typeof ResizeObserver !== "function") return; + this.resizeObs = new ResizeObserver((entries) => { + const rect = entries[0]?.contentRect; + const narrow = (rect?.width ?? 1000) < 700 || (rect?.height ?? 1000) < SHORT_STAGE; + const short = (rect?.height ?? 1000) < SHORT_STAGE; + if (short !== this._shortStage) this._shortStage = short; + const phone = (rect?.width ?? 1000) < 520; + if (phone !== this._phoneStage) this._phoneStage = phone; + if (narrow === this._narrowStage) return; + this._narrowStage = narrow; + this.scheduleThumbs(); + }); + this.resizeObs.observe(stage); + } + + private async start(): Promise { + if (this.starting || this.viewer) return; + this.starting = true; + try { + const mod = await load3d(); + if (!this.isConnected) return; + const host = this.renderRoot.querySelector(".nf-stage") as HTMLElement; + // a tap into the 3D view closes the star menu, like any menu (#220) + host.addEventListener("pointerdown", (e) => { + if (this._central && !this.centralOpen && !(e.target as Element | null)?.closest?.(".nf-central, .nf-central-btn")) this._central = false; + }); + this.viewer = mod.createViewer(host, { + quality: this.quality, + explode: this.explode, + onRoomTap: (floorId, roomId) => this.fire("room-tap", { floorId, roomId }), + onFloorTap: (floorId) => this.fire("floor-tap", { floorId }), + floorInfo: (floor) => + floor.rooms.length === 1 ? translate(this.hass, "floor_rooms_one") : translate(this.hass, "floor_rooms", { n: floor.rooms.length }), + onBack: () => this.fire("back", {}), + onDeviceTap: (id, x, y) => this.onDeviceTap(id, x, y), + onDeviceHold: (id, x, y) => this.onDeviceHold(id, x, y), + onRoomDoubleTap: (floorId, roomId) => this.onRoomDoubleTap(floorId, roomId), + onDeviceSwipe: (id, phase, dy, x, y) => this.onDeviceSwipe(id, phase, dy, x, y), + onFurnitureSelect: (id) => this.fire("furniture-select", { id }), + onFurnitureMove: (id, x, z) => this.fire("furniture-move", { id, x, z }), + onDeviceSelect: (id) => this.fire("device-select", { id }), + onDeviceMove: (id, x, z) => this.fire("device-move", { id, x, z }), + // stats can be switched on at any time; they only cause updates while shown + onStats: (s) => { + if (this.showStats) this._stats = s; + }, + }); + this.viewer.setWallMode(this.wallMode); + this.viewer.setPaintedWalls(this.solidWalls); + this.viewer.setGlassWalls((this.glassWalls ?? 20) / 100); + this.viewer.setTheme(this.theme); + this.viewer.setAccent(this.accent ?? null); + this.viewer.setFurnitureColors(this.furnitureColors ?? null); + this.viewer.setNotePhotos((photo) => (this.hass ? pictureUrl(this.hass, photo, (id) => this.storedPicture(this.hass!, id)) : null)); + this.viewer.setNavigationLocked(this._locked); + this.viewer.setFurnishMode(this.furnish); + this.viewer.setTapInRoom(this.tapInRoom); + this.viewer.setSurfaceGrab(this.surfaceGrab ?? null); + this.viewer.setFurnishTypes(this.furnishTypes ?? null); + this.viewer.setFloorStack(this.floorStack); + this.viewer.setStats(this.showStats); + this.viewer.setAutoOrbit(this.autoOrbit ? 0.06 : 0); + this.viewer.setKeepRoof(this.keepRoof); + this.viewer.setKeepCamera(!!this.keepCamera); + this.viewer.setPlain(!!this.plain); + this.viewer.setRightBack(!!this.rightBack); + this.viewer.setZoom(this.zoom ?? 1); + this._low = this.viewer.low; + // owned 3D models (cars and the like) come from the user's Home Assistant, with the user's login + this.viewer.setMeshSource((id) => + this.hass?.fetchWithAuth ? this.hass.fetchWithAuth(`/api/nextfloor/mesh/${encodeURIComponent(id)}`).then((r) => (r.ok ? r.arrayBuffer() : null)) : Promise.resolve(null), + ); + this.viewer.setPacks([...getPacks()]); + this.shownPacks = packsVersion(); + if (this.building) { + this.shownStartView = JSON.stringify(this.startViewOf()); + this.viewer.setStartView(this.startViewOf()); + this.viewer.setBuilding(this.shownBuilding(this.hass)); + this.viewer.setMap(this.building.settings.map, this.building.settings.north ?? 0); + } + this.scheduleThumbs(); + this.syncDevices(true); + this.viewer.setFloor(this.floorId, false); + if (this.roomId) this.viewer.selectRoom(this.roomId); + } catch (err) { + this._error = String(err); + } finally { + this.starting = false; + } + } + + protected updated(changed: PropertyValues): void { + if (changed.has("announcements") || (changed.has("hass") && this.announcements && !this.stopAnnouncements)) this.listenToAnnouncements(this.announcements && !!this.hass && this.isConnected); + if (changed.has("hass") && this.live?.el) this.live.el.hass = this.hass; + // a plugin window's content (a Home Assistant card) gets every new hass + const windowNode = this._pluginWindow?.node as (Node & { hass?: unknown }) | undefined; + if (changed.has("hass") && windowNode && "hass" in windowNode) windowNode.hass = this.hass; + // the star menu closes when a room or another floor is chosen (#220) + if (this._central && !this.centralOpen && ((changed.has("roomId") && changed.get("roomId") !== undefined) || (changed.has("floorId") && changed.get("floorId") !== undefined))) this._central = false; + if (changed.has("centralOpen") && this.centralOpen) this._central = true; + // before the viewer exists: the card loads it late and `clock` does not change again, so the clock never ticked (#68) + if (changed.has("clock")) { + clearInterval(this.clockTimer); + this.clockTimer = this.clock ? setInterval(() => (this._now = Date.now()), 10000) : undefined; + } + const v = this.viewer; + if (!v) return; + // packs arrive with the building (or after an import): the viewer rebuilds pack furniture + if (this.shownPacks !== packsVersion()) { + this.shownPacks = packsVersion(); + v.setPacks([...getPacks()]); + // vehicles in parking spots come from packs too: look them up again now that the packs are here + if (this.hass && this.building) v.setParked(parkedVehicles(this.hass, this.building)); + // a feature pack may have arrived with them (Energiefluss): the cables and modules follow + this.syncDevices(true); + } + if (changed.has("building") && 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.setMap(this.building?.settings.map, this.building?.settings.north ?? 0); + if (startChanged && this.floorId === null) v.resetView(); + } + if (changed.has("startView") && changed.get("startView") !== undefined) { + 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(); + // 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", ...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("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) { + const view = this.building?.settings.outside_view; + if (this.outsideOpen && view) v.showView(view); + else if (!this.outsideOpen && view && this.floorId === null && !this.roomId) v.resetView(); + } + if (changed.has("tapInRoom")) v.setTapInRoom(this.tapInRoom); + if (changed.has("wallMode")) v.setWallMode(this.wallMode); + if (changed.has("solidWalls")) v.setPaintedWalls(this.solidWalls); + if (changed.has("glassWalls")) v.setGlassWalls((this.glassWalls ?? 20) / 100); + if (changed.has("explode")) v.setExplode(this.explode); + if (changed.has("keepRoof")) v.setKeepRoof(this.keepRoof); + if (changed.has("keepCamera")) v.setKeepCamera(!!this.keepCamera); + if (changed.has("plain")) v.setPlain(!!this.plain); + if (changed.has("rightBack")) v.setRightBack(!!this.rightBack); + if (changed.has("zoom")) v.setZoom(this.zoom ?? 1); + if (changed.has("floorStack")) v.setFloorStack(this.floorStack); + if (changed.has("theme")) v.setTheme(this.theme); + if (changed.has("_locked")) v.setNavigationLocked(this._locked); + if (changed.has("accent")) v.setAccent(this.accent ?? null); + if (changed.has("furnitureColors")) v.setFurnitureColors(this.furnitureColors ?? null); + if (changed.has("surfaceGrab")) v.setSurfaceGrab(this.surfaceGrab ?? null); + if (changed.has("furnishTypes")) v.setFurnishTypes(this.furnishTypes ?? null); + if (changed.has("furnish")) { + v.setFurnishMode(this.furnish); + this.syncDevices(true); + } + if (changed.has("selectedFurniture")) v.selectFurniture(this.selectedFurniture); + if (changed.has("selectedDevice")) v.setSelectedDevice(this.selectedDevice); + if (changed.has("weather") || changed.has("weatherEntityId") || changed.has("weatherDensity") || changed.has("timeOfDay")) this.syncDevices(true); + if (changed.has("quality") && changed.get("quality") !== undefined) { + v.setQuality(this.quality); + this._low = v.low; + } + if (changed.has("showStats")) v.setStats(this.showStats); + if (changed.has("building")) this.findIndex = null; + } + + /** + * Send device markers, door/window states, energy cables, people and floor label texts to the viewer + * when a watched entity changed (or the building). Openings are matched with entities again when + * the building or the entity registry changes. + */ + private shownFor: { building: Building; key: string; shown: Building } | null = null; + /** Stored pictures of frames, loaded once each (image id -> data URL; "" while loading or gone). */ + private framePictureData = new Map(); + + /** The photos of picture frames: stored pictures (loaded once), URLs, and the picture of an image or camera entity. */ + private framePictures(hass: HomeAssistant, b: Building): LivePictureInput[] { + const out: LivePictureInput[] = []; + // the notes' stored photos are loaded ahead, so one shows at once when its note is opened + for (const floor of b.floors) for (const note of floor.notes ?? []) if (note.photo?.startsWith("image:")) this.storedPicture(hass, note.photo.slice(6)); + for (const floor of b.floors) + for (const f of floor.furniture) { + if (!f.picture || !furnitureShown(hass, f)) continue; + const url = pictureUrl(hass, f.picture, (id) => this.storedPicture(hass, id)); + if (url) out.push({ furnitureId: f.id, floorId: floor.id, url, border: f.picture_border ?? 0, fit: f.picture_fit === "contain" ? "contain" : "cover" }); + } + return out; + } + + private storedPicture(hass: HomeAssistant, id: string): string | null { + const known = this.framePictureData.get(id); + if (known !== undefined) return known || null; + this.framePictureData.set(id, ""); + fetchImage(hass, id) + .then((data) => { + this.framePictureData.set(id, data); + this.syncDevices(true); + }) + .catch(() => undefined); + return null; + } + + /** The building as the 3D view draws it: without the pieces whose visibility condition is not met. */ + private shownBuilding(hass: HomeAssistant | undefined): Building { + const b = this.building!; + 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(","); + if (this.shownFor?.building === b && this.shownFor.key === key) return this.shownFor.shown; + const shown = withoutHidden(b, hidden); + this.shownFor = { building: b, key, shown: layers.length ? { ...shown, floors: shown.floors.filter((f) => !layers.includes(f.id)) } : shown }; + return this.shownFor.shown; + } + + /** Layers hidden on this device (the trees, the decoration), remembered in the browser. */ + private hiddenLayers: Set = (() => { + try { + return new Set(JSON.parse(localStorage.getItem("nextfloor.hidden_layers") ?? "[]") as string[]); + } catch { + return new Set(); + } + })(); + + private toggleLayer(id: string): void { + if (this.hiddenLayers.has(id)) this.hiddenLayers.delete(id); + else this.hiddenLayers.add(id); + try { + localStorage.setItem("nextfloor.hidden_layers", JSON.stringify([...this.hiddenLayers])); + } catch { + // without storage the choice lasts until the page reloads + } + if (this.viewer && this.building) this.viewer.setBuilding(this.shownBuilding(this.hass)); + this.requestUpdate(); + } + + /** The eyes of the layers, top middle: a tap shows or hides a layer. */ + private renderLayers() { + const layers = (this.building?.floors ?? []).filter((f) => f.layer); + if (!layers.length || this.clean) return nothing; + return html`
+ ${layers.map((f) => html``)} +
`; + } + + private syncDevices(force: boolean): void { + const v = this.viewer; + const b = this.building; + if (!v || !b || !this.hass) return; + // time travel: the same view, fed with the states of the moment shown + const travel = this._travel; + const hass = travel && !travel.loading ? hassAt(this.hass, travel.history, travel.t) : this.hass; + if (force || !this.openingLinks || this.linkedRegistry !== hass.entities) { + this.openingLinks = openingEntities(hass, b.floors); + this.furnitureLinks = furnitureEntities(hass, b.floors); + this.linkedRegistry = hass.entities; + this.findIndex = null; + this.alertSrc = this.alerts ? alertSources(hass, b, this.weatherEntityId, this.openingLinks) : null; + this.watched = watchedEntities({ + hass, + building: b, + openingLinks: this.openingLinks, + furnitureLinks: this.furnitureLinks, + needsRoomSensors: this.heatMode !== "none" || this.roomLabels, + alertSources: this.alertSrc, + weatherEntityId: this.weatherEntityId, + }); + force = true; + } + 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)); + this.shownStates = new Map(this.watched.map((id) => [id, hass.states[id]])); + this.refreshToday(b); + this.refreshForecast(b); + + const consumers = findConsumers(hass, b); + // hidden layers bring no pins either + const deviceMarkers = buildMarkers(hass, b.floors.some((f) => f.layer && this.hiddenLayers.has(f.id)) ? this.shownBuilding(hass) : b); + this.placementInfo = new Map(deviceMarkers.map((m) => [m.id, { floorId: m.floorId, roomId: m.roomId, x: m.x, z: m.z, y: m.y, rotation: m.rotation ?? 0 }])); + const furniture = this.furnitureMarkers(hass, b, new Set(deviceMarkers.map((m) => m.id)), new Set(consumers.map((c) => c.powerEntity))); + consumers.push(...furniture.consumers); + const summary = energySummary(hass, b, consumers, deviceSensors(b, (f) => this.furnitureLinks?.get(f.id)?.power ?? null)); + // a placed power sensor shows its value as state text already, so only devices get a watt badge + const byDevice = new Map(consumers.filter((c) => c.id !== c.powerEntity).map((c) => [c.id, c.power])); + this.confirmSet = confirmEntities(hass, b.floors); + // under NextFloor's cards (a playing speaker, a car in its spot) the device's own pin steps aside + const carded = new Set(this.liveCardsOn ? this._liveCards.flatMap((c) => (c.kind === "media" ? [c.media.entity] : c.kind === "car" ? [c.spot] : [])) : []); + // gardens, terraces and pools with an area, a thermometer or a pump: a pin of their own (a tap opens Outside) + for (const floor of b.floors) + for (const a of floor.outdoor ?? []) { + if (!a.area_id && !a.temp_entity && !a.pump_entity) continue; + const temp = a.temp_entity ? hass.states[a.temp_entity] : undefined; + const pump = a.pump_entity ? hass.states[a.pump_entity] : undefined; + const [cx, cz] = centroid(a.points); + const t = temp && Number.isFinite(Number(temp.state)) ? `${formatNumber(hass, fromCelsius(hass, toCelsius(Number(temp.state), temp.attributes.unit_of_measurement)), 1)} ${tempUnit(hass)}` : ""; + const running = !!pump && isActive(pump); + deviceMarkers.push({ + id: a.area_id ? `outdoor:${a.id}` : (a.pump_entity ?? a.temp_entity)!, + floorId: floor.id, + roomId: null, + x: cx, + z: cz, + y: outdoorTopAt(floor, a, cx, cz) + 0.7, + icon: mdiIcon(a.type === "pool" ? "pool" : a.type === "terrace" ? "table-chair" : "tree-outline"), + name: (a.area_id && hass.areas?.[a.area_id]?.name) || translate(hass, `out_${a.type}` as I18nKey), + text: [t, running ? translate(hass, "pool_pump_on") : ""].filter(Boolean).join(" · "), + active: running, + unavailable: false, + glow: null, + show: "always", + }); + } + // pins moved by hand (devices that stand close together): shifted in the plan and in height; lamps keep theirs at the lamp + const shifts = new Map>(); + for (const floor of b.floors) { + for (const p of floor.placements) if (p.pin_offset) shifts.set(`${floor.id}:${p.entity_id}`, p.pin_offset); + for (const f of floor.furniture) if (f.pin_offset) shifts.set(`f:${f.id}`, f.pin_offset); + } + const shifted = (m: T): T => { + const s = m.lamp ? undefined : (m.furnitureId ? shifts.get(`f:${m.furnitureId}`) : undefined) ?? shifts.get(`${m.floorId}:${m.id}`); + return s ? { ...m, x: m.x + (s.x ?? 0), z: m.z + (s.z ?? 0), y: m.y + (s.y ?? 0) } : m; + }; + v.setDevices([ + ...[...deviceMarkers, ...furniture.markers].map(shifted).map((m) => { + // "without watts" drops the power badge (a plug shows only on / off) + const power = m.show === "no_power" || ("energyDevice" in m && m.energyDevice) ? null : (byDevice.get(m.id) ?? null); + // at night (kiosk) colour effects rest + const marker = { ...m, power, powerText: power === null ? undefined : formatPower(hass, power), effect: this.dimmed ? undefined : m.effect, text: this.subMeterText(hass, b, summary, m.furnitureId) ?? m.text }; + // the own name under the pin: per device, or for every named device (card option marker_names) + const caption = m.ownName && (m.showName || this.markerNames) ? m.ownName : ""; + const under = carded.has(m.id) || (!!m.furnitureId && carded.has(m.furnitureId)); + return { ...marker, pin: this.showPin(marker) && !under, full: m.show === "always", caption }; + }), + ]); + v.setPickTargets(furniture.targets, this.openingTargets(), this.secondBlinds()); + v.setScreens(furniture.screens); + v.setFridgeDoors(fridgeDoors(hass, b.floors)); + v.setCovers(coverReaches(hass, b)); + v.setRobots(this.robotInfos(hass, b)); + // pets with a room sensor (Bermuda, ESPresense, a tracker tag): they roam the room it names + const petRooms = new Map(); + for (const floor of b.floors) + for (const f of floor.furniture) { + if (!packItem(f.type)?.pet || !f.room_sensor || f.room_sensor === "none") continue; + petRooms.set(f.id, robotRoom(hass, floor.rooms.filter((r) => r.points.length >= 3), null, f.room_sensor)?.id ?? null); + } + if (petRooms.size) v.setPetRooms(petRooms); + // roof windows: sash and blind follow their contact and cover like windows do + v.setRoofWindows(roofWindowStates(hass, b)); + v.setParked(parkedVehicles(hass, b)); + v.setGateStates(gateStates(hass, b)); + const types = new Map(b.floors.flatMap((f) => f.openings.map((o) => [o.id, o.type] as const))); + const openingStates = new Map([...this.openingLinks!].map(([id, e]) => [id, openingState(hass, e, types.get(id))])); + v.setOpeningStates(openingStates); + this.setAlerts(this.alertSrc ? findAlerts(hass, b, this.alertSrc, this.openingLinks!) : []); + this.watchLostContacts(hass); + // the floor pictures follow lamps and blinds (not sensors), at most every few seconds + const lampSig = [...deviceMarkers, ...furniture.markers].map((m) => `${m.id}:${m.glow ? `${m.glow.level.toFixed(1)}/${m.glow.color.map((c) => c.toFixed(1)).join("/")}` : 0}`).join(";") + "|" + [...openingStates].map(([id, o]) => `${id}:${o.open}:${o.cover === null ? "-" : o.cover.toFixed(1)}`).join(";"); + if (lampSig !== this.thumbSig) { + const first = this.thumbSig === ""; + this.thumbSig = lampSig; + if (!first) this.scheduleThumbs(1500); + } + // NextFloor: power flowing between the devices, sparkling modules, the house balance card + // the advanced energy mode also needs the automatically found sensors of the sub-meters + const livePic = energyPicture(hass, b, consumers, b.energy.advanced ? (f) => this.furnitureLinks?.get(f.id)?.power ?? null : undefined); + const liveCars = this.liveCars(hass, b); + // a charging car draws its power from the nearest wallbox (or the house) into the car + for (const c of liveCars) { + if (!c.car.home || (!c.car.charging && !c.car.plugged)) continue; + const near = b.floors.flatMap((f) => f.furniture.filter((m) => m.type === "wallbox").map((m) => ({ floorId: f.id, x: m.x, z: m.z, y: 1 }))) + .sort((p, q) => Math.hypot(p.x - c.at.x, p.z - c.at.z) - Math.hypot(q.x - c.at.x, q.z - c.at.z))[0]; + // a wallbox close to the car: its charging cable hangs down to the car, plugged in or charging + const cable = near && near.floorId === c.at.floorId && Math.hypot(near.x - c.at.x, near.z - c.at.z) < 9; + const from = near ?? houseHub(b); + if (!from || (!c.car.charging && !cable)) continue; + livePic.arcs.push({ + key: `car:${c.spot}`, + from, + to: { ...c.at, y: 0.8 }, + power: c.car.charging ? (c.car.chargingW ?? 7000) : 0, + color: [80, 175, 255], + ...(cable ? { via: [{ ...from, y: 0.35 }, { floorId: c.at.floorId, x: (from.x + c.at.x) / 2, z: (from.z + c.at.z) / 2, y: 0.08 }, { ...c.at, y: 0.5 }], cable: true } : {}), + }); + } + // a heat pump that heats: its heat flows into the house in orange + const hub = houseHub(b); + for (const p of this.liveHeatPumps(b)) { + const heat = p.pump.heat ?? (p.pump.mode === "heating" || p.pump.mode === "water" ? (p.pump.power ?? 0) * (p.pump.cop ?? 3) : 0); + if (hub && heat > 100 && p.pump.mode !== "cooling") livePic.arcs.push({ key: `heat:${p.id}`, from: { floorId: p.floorId, x: p.x, z: p.z, y: 0.8 }, to: hub, power: heat, color: [255, 120, 40] }); + } + const liveFlows = (this.flows ?? this._flows) && !this.dimmed; + v.setLiveEnergy(liveFlows ? livePic.arcs : [], liveFlows ? livePic.sparks : []); + if (JSON.stringify(livePic) !== JSON.stringify(this._liveEnergy)) this._liveEnergy = livePic; + const liveMedia = this.liveMedia(hass, b); + const playing = liveMedia.filter((m) => m.playing && !this.dimmed); + v.setLiveSound( + playing.filter((m) => m.rings > 0).map((m) => ({ id: m.entity, at: m.at, color: m.color, level: m.volume ?? 0.5, size: m.rings })), + multiroom(playing).map(([a, c]) => [a.at, c.at]), + ); + this.syncLhCards(v, b, livePic, liveCars, playing); + // TV screens: a TV or monitor linked to a media player that runs shows what runs + v.setLiveScreens(this.dimmed ? [] : liveScreens(hass, b, this.furnitureLinks)); + v.setPictures(this.framePictures(hass, b)); + // lawn sprinklers that water now (at night on the wall tablet effects rest) + v.setLiveWater(this.dimmed ? [] : liveSprays(hass, b, this.furnitureLinks)); + const persons = SHOW_PRESENCE ? personsInRooms(hass, b) : []; + v.setPersons(persons); + const counts = floorCounts(hass, b, this.openingLinks!, persons); + v.setFloorInfo(new Map([...counts].map(([id, c]) => [id, floorInfoText(hass, c)]))); + // daylight: sun through the windows and a lighter sky + const config = hass.config; + const sunNow = this.timeOfDay != null && config?.latitude !== undefined && config.longitude !== undefined ? sunPosition(todayAt(this.timeOfDay, config.time_zone), config.latitude, config.longitude) : readSun(hass); + v.setSun(sunNow); + v.setLocation(config?.latitude !== undefined && config.longitude !== undefined ? { latitude: config.latitude, longitude: config.longitude, zone: config.time_zone } : null); + // the sky over the plot (NextFloor's own weather layer): clouds darken the stage, rain and snow fall along the wind + const raw = this.weather && !this.dimmed ? readSkyWeather(hass, weatherEntity(hass, this.weatherEntityId ?? b.settings.weather_entity)) : null; + const weather = raw ? withDensity(chosenEffects(raw, b.settings.weather_effects), this.weatherDensity) : null; + this.cloud = weather?.cloud ?? 0; + this._sky = skyLightness(sunNow?.elevation ?? null, this.cloud); + v.setSky( + this.weather && !this.dimmed + ? { + weather, + sun: sunNow, + north: b.settings.north ?? 0, + sky: this.skyColor(), + disc: (b.settings.weather_effects ?? ["sky"]).includes("sky"), + low: this._low, + } + : null, + ); + this.applyTint(); + const hasEnergy = summary.grid !== null || summary.solar !== null || summary.battery !== null || summary.tariff !== null; + const energy = hasEnergy ? summary : null; + // a new object would make Lit render again; only changed values do + if (JSON.stringify(energy) !== JSON.stringify(this._energy)) this._energy = energy; + } + + /** + * A contact that went unavailable warns only after the grace time, which no state change marks: while one is + * unavailable, look again every minute. + */ + private watchLostContacts(hass: HomeAssistant): void { + const waiting = !!this.alertSrc && !this._travel && contactsPending(hass, this.alertSrc); + if (waiting && !this.contactTimer) + this.contactTimer = setInterval(() => { + const b = this.building; + if (this.alertSrc && b && this.hass && this.openingLinks && !this._travel) this.setAlerts(findAlerts(this.hass, b, this.alertSrc, this.openingLinks)); + }, 60_000); + if (!waiting && this.contactTimer) { + clearInterval(this.contactTimer); + this.contactTimer = undefined; + } + } + + /** New warnings start the pulse (and a jump to the room when wanted); none stops it. */ + private setAlerts(alerts: Alert[]): void { + const keys = alerts.map((a) => `${a.kind}:${a.entity}`); + // quiet warnings (a contact that stopped answering) only show in the banner: no pulse, no jump + const fresh = alerts.filter((a, i) => !this.seenAlerts.has(keys[i]) && !QUIET_ALERTS.has(a.kind)); + this.seenAlerts = new Set(keys); + if (keys.join() !== this._alerts.map((a) => `${a.kind}:${a.entity}`).join()) this._alerts = alerts; + const pulsing = alerts.some((a) => !QUIET_ALERTS.has(a.kind)); + if (pulsing && !this.alertTimer) this.alertTimer = setInterval(() => !document.hidden && this.applyTint(), this._low ? 200 : 100); + if (!pulsing && this.alertTimer) { + clearInterval(this.alertTimer); + this.alertTimer = undefined; + } + if (fresh.length && this.alertJump) this.jumpTo(fresh[0]); + } + + /** Show where a warning is: its floor and room, or the house for an alarm. */ + private jumpTo(a: Alert): void { + // an own warning: its details, or what was chosen for it (switch the entity, go to its room) + if (a.kind === "own" && a.tap !== "room") { + if (a.tap === "toggle") void this.hass.callService("homeassistant", "toggle", { entity_id: a.entity }); + else openMoreInfo(this, a.entity); + return; + } + if (!a.floorId) { + this.fire("floor-tap", { floorId: null }); + return; + } + if (this.floorId !== a.floorId) this.fire("floor-tap", { floorId: a.floorId }); + // the host switches the floor first; the room follows once it has rendered + if (a.roomId) setTimeout(() => this.fire("room-tap", { floorId: a.floorId, roomId: a.roomId }), 60); + } + + /** Double tap on a room: all its lights off when one is on, otherwise all on (plan setting / card option room_double_tap). */ + private onRoomDoubleTap(floorId: string, roomId: string): void { + const b = this.building; + const hass = this.hass; + const floor = b?.floors.find((f) => f.id === floorId); + const room = floor?.rooms.find((r) => r.id === roomId); + if (!b || !hass || !floor || !room) return; + const mode = roomToggleMode(b.settings.room_double_tap, this.roomDoubleTap); + const lights = roomToggleLights(hass, floor, room, this.furnitureLinks, this.confirmSet, mode); + if (!lights.length) return; + const anyOn = lights.some((id) => hass.states[id]?.state === "on"); + void hass.callService("homeassistant", anyOn ? "turn_off" : "turn_on", { entity_id: lights }); + this.roomFlash = { roomId, until: performance.now() + 350 }; + this.applyTint(); + setTimeout(() => { + this.roomFlash = null; + this.applyTint(); + }, 380); + } + + private runScene(id: string): void { + void this.hass.callService(id.split(".")[0], "turn_on", { entity_id: id }); + this._sceneFired = id; + setTimeout(() => (this._sceneFired = null), 600); + } + + /** + * Floor colours of the rooms: the heatmap, the pulsing rooms of warnings and the flash of a double + * tap; sent to the viewer only when they changed. + */ + private applyTint(): void { + const v = this.viewer; + const b = this.building; + const hass = this.hass; + if (!v || !b || !hass) return; + let tint: Map | null = null; + if (this.heatMode !== "none" && this.heatMode !== "values" && this.heatMode !== "wifi") { + const mode = this.heatMode; + const values = roomValues(hass, b, mode); + // the legend's "nothing found" line depends on it: render again when that changes + if (!values.size !== !this.heatValues.size) this.requestUpdate(); + this.heatValues = values; + const summer = isSummer(new Date(), hass.config?.latitude ?? 50); + tint = new Map([...values].map(([id, value]) => [id, heatColor(mode, value, summer)])); + } + // "values": the numbers at the room names instead of coloured floors + const info = new Map(); + if (this.heatMode === "values") { + for (const floor of b.floors) + for (const room of floor.rooms) { + const t = roomClimateValue(hass, floor, room, "temperature"); + const h = roomClimateValue(hass, floor, room, "humidity"); + const c = roomClimateValue(hass, floor, room, "co2"); + const need = airingNeed(c, h, mouldRisk(t, h)); + const parts = [ + t !== null ? `${formatNumber(hass, fromCelsius(hass, t), 1)} ${tempUnit(hass)}` : null, + h !== null ? `${formatNumber(hass, h, 0)} %` : null, + c !== null ? `${formatNumber(hass, c, 0)} ppm` : null, + need ? `💨 ${translate(hass, `air_${need}`)}` : null, + ].filter((x): x is string => !!x); + if (parts.length) info.set(room.id, parts.join(" · ")); + } + } + v.setRoomInfo(info); + // underfloor heating: the floor of a room glows warm while its heating runs (under the heat map, which shows values) + if (!tint) { + for (const floor of b.floors) + for (const room of floor.rooms) { + const st = room.floor_heating ? hass.states[room.floor_heating] : undefined; + const heats = st && (st.entity_id.startsWith("climate.") ? st.attributes.hvac_action === "heating" : st.state === "on" || st.state === "open"); + if (heats) (tint ??= new Map()).set(room.id, [0.55, 0.24, 0.08]); + } + } + if (this._alerts.length) { + tint ??= new Map(); + const k = 0.55 + 0.45 * Math.sin(performance.now() / 160); + for (const a of this._alerts) { + if (QUIET_ALERTS.has(a.kind)) continue; + const c = alertColor(a.kind).map((x) => x * k) as [number, number, number]; + if (a.roomId) tint.set(a.roomId, c); + else for (const f of b.floors) for (const r of f.rooms) tint.set(r.id, c); + } + } + if (this.roomFlash && performance.now() < this.roomFlash.until) { + tint ??= new Map(); + tint.set(this.roomFlash.roomId, [0.9, 0.95, 1]); + } + const sig = tint ? [...tint].map(([id, c]) => `${id}:${c.map((x) => x.toFixed(2)).join(",")}`).join(";") : ""; + if (sig === this.tintSig) return; + this.tintSig = sig; + v.setRoomTint(tint); + } + + /** + * Markers, energy consumers and lit screens of furniture with linked entities. Entities that are + * placed as devices as well keep their device marker. + */ + private furnitureMarkers( + hass: HomeAssistant, + b: Building, + taken: Set, + consumerSensors: Set, + ): { markers: (DeviceMarker & { fromFurniture: boolean; energyDevice?: boolean; care?: boolean; readout?: boolean })[]; consumers: Consumer[]; screens: Map; targets: Map } { + const markers: (DeviceMarker & { fromFurniture: boolean; energyDevice?: boolean; care?: boolean; readout?: boolean })[] = []; + const consumers: Consumer[] = []; + const screens = new Map(); + const targets = new Map(); + const subMeters = subMeterIds(b); + for (const floor of b.floors) { + if (floor.layer && this.hiddenLayers.has(floor.id)) continue; + for (const f of floor.furniture) { + if (!furnitureShown(hass, f)) continue; + const linked = this.furnitureLinks.get(f.id); + // furniture with a state: a glowing plate on the item while its entity is on, occupied or home; + // two entities light the halves (left/right of a bed, bottom/top of a bunk bed) + const faces = this.stateFaces(hass, f); + if (faces.length) screens.set(f.id, { color: faces[0].color, level: faces[0].level, faces }); + // a light switch or socket: each button glows with its own entity; a tap switches it (or asks which, with several) + // the household: a bin's pickup, post in the mailbox, a thirsty plant + const care = householdKind(f.type); + if (care && f.care_entity) { + const marker = this.careMarker(hass, floor, f, care, f.care_entity); + if (marker) { + markers.push(marker.marker); + if (marker.glow) screens.set(f.id, { color: marker.glow, level: 0.9, faces: [{ part: "all", color: marker.glow, level: 0.9 }] }); + targets.set(f.id, f.care_entity); + } + continue; + } + const plate = packItem(f.type); + // a curtain, roller screen, awning or gate: a tap opens the menu of the cover it follows + if (f.cover_entity && hasMovingParts(plate)) targets.set(f.id, f.cover_entity); + if (plate?.gangs) { + // a smart plug or measuring switch behind a button: its power counts in the flow like any device's + for (const g of (f.gang_entities ?? []).slice(0, plate.gangs)) { + const sensor = g && g !== "none" ? powerSensorFor(hass, g) : null; + const w = sensor ? readPower(hass.states[sensor]) : null; + if (sensor && w !== null && !consumerSensors.has(sensor)) { + consumerSensors.add(sensor); + consumers.push({ id: g!, powerEntity: sensor, floorId: floor.id, x: f.x, z: f.z, power: Math.max(0, w) }); + } + } + const gangs = gangGlows(hass, (f.gang_entities ?? []).slice(0, plate.gangs), /socket/.test(f.type)); + if (gangs.length) screens.set(f.id, { color: gangs[0].color, level: gangs[0].level, gangs }); + if (gangEntities(f.gang_entities, plate.gangs).length) targets.set(f.id, `gang:${f.id}`); + continue; + } + if (isLamp(f.type)) { + const lamp = this.lampMarker(hass, floor, f, linked?.entity ?? null); + // a lamp with a power sensor (a smart plug, a measuring switch): its watts on the pin and in the house's balance + const lampW = linked?.power ? readPower(hass.states[linked.power]) : null; + if (linked?.power && lampW !== null) { + if (lampW >= 1) lamp.text = lamp.text ? `${lamp.text} · ${powerText(hass, lampW)}` : powerText(hass, lampW); + if (!consumerSensors.has(linked.power)) { + consumerSensors.add(linked.power); + consumers.push({ id: lamp.id, powerEntity: linked.power, floorId: floor.id, x: f.x, z: f.z, power: Math.max(0, lampW) }); + } + } + markers.push(lamp); + if (f.type === "ceiling_fan") { + const fan = linked?.fan ? hass.states[linked.fan] : undefined; + lamp.spin = fanSpin(fan); + if (fan && !taken.has(fan.entity_id)) { + taken.add(fan.entity_id); + // the fan's own pin under the blades: tap switches it, a swipe changes its speed + markers.push({ ...lamp, id: fan.entity_id, y: Math.max(0.5, lamp.y - 0.3), icon: f.icon ? mdiIcon(f.icon) : iconSvg("fan"), name: f.name || entityName(hass, fan.entity_id), text: fanText(hass, fan), active: isActive(fan), unavailable: isUnavailable(fan), glow: null, lamp: null, spin: undefined, pickable: undefined, effect: undefined }); + } + } + continue; + } + // a fridge shows the temperatures of its compartments (and warns when one is too warm) + const temps = isCooling(f.type) ? coolingTemps(hass, f, (c) => `${formatNumber(hass, fromCelsius(hass, c), 1)} ${tempUnit(hass)}`) : null; + // a home battery with only its charge, a wallbox with only its status, a fridge with only its thermometer still gets its marker + // any other device: its own thermometer (an inverter, a battery, a PC; #112) beside what it shows + const deviceTemp = !isCooling(f.type) ? deviceTempOf(hass, f.temp_entity) : null; + const deviceTempText = deviceTemp === null ? "" : `🌡 ${formatNumber(hass, fromCelsius(hass, deviceTemp), 1)} ${tempUnit(hass)}`; + const extraRef = f.type === "home_battery" ? f.soc : f.type === "wallbox" ? f.status : temps ? (f.temp_entity && f.temp_entity !== "none" ? f.temp_entity : f.temp_entity2) : deviceTemp !== null ? f.temp_entity : null; + const extra = extraRef && extraRef !== "none" ? extraRef : null; + const link = linked ?? (extra ? { entity: null, power: null } : undefined); + if (!link) continue; + // a battery goes by its charge first: its power sensor is often placed on its own as well + const id = (f.type === "home_battery" ? (extra ?? link.entity ?? link.power) : (link.entity ?? link.power ?? extra))!; + targets.set(f.id, id); + const st = link.entity ? hass.states[link.entity] : undefined; + // the meter's sensor is the grid (+ = import), the battery's can point the other way as well; + // a sub-meter (advanced energy mode) measures its branch (+ = drawn) with its own sign + const sub = subMeters.has(f.id); + const invert = sub ? !!f.meter_invert : f.type === "meter" ? b.energy.grid_invert && !f.export : f.type === "home_battery" ? b.energy.battery_invert && !f.charge : false; + let power = link.power ? readPower(hass.states[link.power], invert) : null; + // separate second sensors: a battery's charging, a meter's export (then the first one is unsigned) + const second = (f.type === "home_battery" && f.charge && f.charge !== "none" ? f.charge : f.type === "meter" && !sub && f.export && f.export !== "none" ? f.export : null) as string | null; + const secondW = second ? readPower(hass.states[second]) : null; + if (secondW !== null) power = Math.max(0, power ?? 0) - Math.max(0, secondW); + if (link.power && power !== null && !consumerSensors.has(link.power)) { + consumerSensors.add(link.power); + consumers.push({ id, powerEntity: link.power, floorId: floor.id, x: f.x, z: f.z, power: Math.max(0, power), wallbox: f.type === "wallbox" || undefined }); + } + const running = (power ?? 0) > 10 || st?.state === "on" || st?.state === "running" || (isStatusSensor(st) && isActive(st)); + if ((f.type === "radiator" || plate) && st && kindOf(st.entity_id) === "climate") { + // glows while it heats; brighter the further the room is below its target. A pack item glows on its screen + // part (a thermostat's display), or as a whole when it has none (a towel radiator) + const a = st.attributes; + if (a.hvac_action === "heating") { + const gap = typeof a.temperature === "number" && typeof a.current_temperature === "number" ? a.temperature - a.current_temperature : 1; + const heat = !!plate && !plate.parts.some((p) => p.screen); + screens.set(f.id, { color: [1, 0.42, 0.1], level: Math.min(1, 0.45 + 0.25 * Math.max(0, gap)), heat: heat || undefined }); + } + } else if ((f.type === "washer" || f.type === "dryer" || f.type === "dishwasher") && running) { + screens.set(f.id, { color: [0.3, 0.85, 1], level: 0.8 }); + } else if (plate && running && !plate.light && plate.parts.some((p) => p.glow || p.screen)) { + // any other electric pack item that runs: its status lights and display light up, like an appliance's + screens.set(f.id, { color: [0.3, 0.85, 1], level: 0.8, leds: true }); + } + // a 3D printer that prints: the print grows on its bed, in the colour of its filament + if (isPrinter3d(f.type)) { + const pr = readPrinter(hass, link.entity ?? link.power); + if (pr && pr.progress !== null && (pr.printing || /pause/.test(pr.status))) { + const hex = pr.filaments[0] ?? "#38bdf8"; + const rgb = [1, 3, 5].map((k) => parseInt(hex.slice(k, k + 2), 16) / 255) as [number, number, number]; + screens.set(f.id, { color: rgb, level: 0.9, print: Math.max(0.02, pr.progress / 100) }); + } + } + // a home battery shows its charge on its own front: a bar that fills, green when full, red when nearly empty + if (f.type === "home_battery" && extra) { + const soc = Number(hass.states[extra]?.state); + if (Number.isFinite(soc)) screens.set(f.id, { color: soc > 60 ? [0.29, 0.87, 0.5] : soc > 25 ? [0.98, 0.8, 0.08] : [0.97, 0.44, 0.44], level: 0.95, fill: soc / 100 }); + } + if (st && hasScreen(f.type)) { + // a screen is lit or dark (what plays on it is drawn by NextFloor's TV screens); a light (an aquarium, + // a lit panel) glows in its own colour, other entities in the neon cyan + const lit = kindOf(st.entity_id) === "light" ? lightGlow(st) : null; + // many TV integrations (Samsung, LG) only report "on", never "playing": on is lit, dimmed + const tvOn = kindOf(st.entity_id) === "media" && ["playing", "on", "paused", "idle"].includes(st.state); + const color = lit ? lit.color : isActive(st) || tvOn ? ([0.22, 0.88, 1] as [number, number, number]) : null; + if (color) screens.set(f.id, { color, level: st.state === "playing" ? 1 : 0.6, halo: f.ambilight ?? 1 }); + } + if (taken.has(id)) continue; + taken.add(id); + const kind = link.entity ? kindOf(link.entity) : null; + const room = floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([f.x, f.z], r.points)); + markers.push({ + id, + floorId: floor.id, + roomId: room?.id ?? null, + x: f.x, + z: f.z, + y: markerHeight(f) + mountBase(floor, f), + icon: f.icon ? mdiIcon(f.icon) : iconSvg(kind ?? "switch"), + name: f.name || (link.entity ? entityName(hass, link.entity) : furnitureName(hass, f.type)), + ownName: f.name || undefined, + showName: !!f.show_name, + text: [ + temps + ? temps.text + : f.type === "home_battery" + ? this.batteryText(hass, extra, power) + : f.type === "wallbox" + ? this.wallboxText(hass, extra, power) + : f.type === "meter" + ? sub + ? (power === null ? "" : formatPower(hass, power)) + : this.meterText(hass, power) + : st && (f.type === "washer" || f.type === "dryer" || f.type === "dishwasher") && running && remainingMinutes(hass, deviceSiblings(hass, link.entity ?? link.power)) !== null + ? translate(hass, "care_time_left", { time: minutesText(remainingMinutes(hass, deviceSiblings(hass, link.entity ?? link.power))!) }) + : st + ? // every device with a power sensor shows its draw beside its state, the same way + [stateText(hass, st), power !== null && power > 5 && !isStatusSensor(st) ? formatPower(hass, power) : ""].filter(Boolean).join(" · ") + : power !== null + ? formatPower(hass, Math.max(0, power)) + : "", + deviceTempText, + ] + .filter(Boolean) + .join(" · "), + active: temps?.warm || (deviceTemp !== null && deviceTemp >= DEVICE_HOT) || (st ? isActive(st) : (power ?? 0) > 5), + unavailable: st ? isUnavailable(st) : false, + glow: null, + // its pin grabs the item when furnishing + furnitureId: f.id, + // inverter, battery, wallbox: their own text (watts, charge, status) is always worth a pin + energyDevice: f.type === "inverter" || f.type === "home_battery" || f.type === "wallbox" || f.type === "meter", + // a fridge's temperatures are worth a pin, like an energy device's values + readout: !!temps || undefined, + show: f.marker ?? undefined, + fromFurniture: true, + }); + } + } + // the Wi-Fi map: an access point's reach as a disc on the floor (through walls), its pin tells its devices + const wifi = this.heatMode === "wifi"; + for (const m of markers) { + const f = m.furnitureId ? b.floors.flatMap((fl) => fl.furniture).find((x) => x.id === m.furnitureId) : undefined; + if (!f || !isAccessPoint(f.type)) continue; + const ap = readAccessPoint(hass, this.furnitureLinks.get(f.id)?.entity ?? this.furnitureLinks.get(f.id)?.power ?? null); + if (!ap) continue; + if (ap.clients !== null) m.text = translate(hass, "wifi_clients", { n: ap.clients }); + if (wifi) { + m.wedge = { angle: 360, reach: 9, near: 0, color: coverageColor(ap), opacity: 0.4, through: true, walls: false }; + m.show = "always"; + } + } + // an item with its own tap action shows what it shows as usual; a tap on it or on its pin runs the action + const own = ownTaps(b, markers); + this.tapPins = own.pins; + for (const f of b.floors.flatMap((fl) => fl.furniture)) if (f.tap?.action) targets.set(f.id, `tap:${f.id}`); + // one without a pin of its own gets one above it, like a device's, that does the same + for (const { floor, item: f } of own.bare) { + const room = floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([f.x, f.z], r.points)); + const name = f.name || furnitureName(hass, f.type); + markers.push({ id: `tap:${f.id}`, floorId: floor.id, roomId: room?.id ?? null, x: f.x, z: f.z, y: markerHeight(f) + mountBase(floor, f), icon: mdiIcon(f.icon || "gesture-tap-button"), name, ownName: f.name || undefined, showName: !!f.show_name, text: "", active: false, unavailable: false, glow: null, furnitureId: f.id, show: f.marker ?? undefined, fromFurniture: true }); + } + return { markers, consumers, screens, targets }; + } + + /** + * Furniture a robot vacuum drives around: what stands on the floor of the room (cabinets, sofas, + * beds, appliances). It drives under tables, desks, chairs and stools, over rugs and under anything + * hung on the wall. + */ + private robotObstacles(floor: Building["floors"][number], room: [number, number][]): [number, number][][] { + const OPEN_BELOW = new Set(["rug", "worktop", "table", "table_round", "coffee_table", "chair", "office_chair", "stool", "bar_stool", "bench", "desk", "robot_vacuum", "parking", "stairwell", "radiator", "tv_wall", "kitchen_wall", "led_strip"]); + return floor.furniture + .filter((m) => { + if (OPEN_BELOW.has(m.type) || (m.type.startsWith("lamp_") && m.type !== "lamp_floor" && m.type !== "lamp_uplight")) return false; + if (m.h < 0.04 || mountBase(floor, m) > 0.12) return false; + const item = packItem(m.type); + if (item && (item.hole || /table|desk|chair|stool|bench|rug|carpet|mat$/.test(m.type))) return false; + return pointInPolygon([m.x, m.z], room) || furnitureFootprint(m).some((p) => pointInPolygon(p, room)); + }) + .map((m) => furnitureFootprint(m)); + } + + /** Robot vacuums (docks with a vacuum entity): where they rest and what they do. */ + private robotInfos(hass: HomeAssistant, b: Building): RobotInfo[] { + const out: RobotInfo[] = []; + // the robot's own map: a camera that describes one, and the two places that tie its grid to the plan + const camera = mapCamera(hass); + const live = readVacuum(hass, camera, b.settings.vacuum_map ?? null); + let liveTaken = false; + for (const floor of b.floors) { + for (const f of floor.furniture) { + if (f.type !== "robot_vacuum") continue; + const entity = this.furnitureLinks.get(f.id)?.entity ?? null; + const state = entity ? hass.states[entity]?.state : undefined; + const mode: RobotInfo["mode"] = + state === "cleaning" ? "cleaning" : state === "returning" ? "returning" : state === "error" ? "error" : state === "docked" || !state ? "docked" : "idle"; + // the robot rests in front of its dock, facing away from it + const a = (f.rotation * Math.PI) / 180; + const off = f.d * 0.14; + const rest: [number, number] = [f.x - Math.sin(a) * off, f.z + Math.cos(a) * off]; + // the room the robot reports (a "current room" sensor), else the room of its dock + const rooms = floor.rooms.filter((r) => r.points.length >= 3); + const reported = mode === "cleaning" ? robotRoom(hass, rooms, entity, robotRoomSensor(hass, entity, f.room_sensor)) : null; + const room = reported ?? rooms.find((r) => pointInPolygon(rest, r.points)); + const obstacles = mode === "cleaning" && room ? this.robotObstacles(floor, room.points) : []; + // the first robot vacuum takes the map the camera describes: it shows where that robot really is + // and where it has been, instead of the lanes this view invents for the room + // a robot map is only as current as the last frame something asked of the camera: while it cleans, a + // pose from minutes ago would nail it to the wrong spot for good, so an old one is not used at all + const seenAt = camera ? Date.parse(hass.states[camera]?.last_updated ?? "") : Number.NaN; + const fresh = !Number.isFinite(seenAt) || Date.now() - seenAt < 2 * 60 * 1000; + const own = entity?.startsWith("vacuum.") && live && !liveTaken && (fresh || (mode !== "cleaning" && mode !== "returning")) ? live : null; + if (own) liveTaken = true; + // when it stopped cleaning: its pad fades ten minutes later, so a finished clean does not lie on the + // floor all day — the timeline is where the day stays + const stoppedAt = entity ? Date.parse(hass.states[entity]?.last_changed ?? "") : Number.NaN; + const settledAt = mode === "cleaning" || mode === "returning" ? null : Number.isFinite(stoppedAt) ? stoppedAt : null; + out.push({ + id: f.id, + floorId: floor.id, + rest, + restHeading: -a, + mode, + room: room?.points ?? null, + roomId: room?.id ?? null, + obstacles, + track: own?.path ?? null, + pose: own?.pose ?? null, + settledAt, + }); + } + // robot mowers: a mower or its dock from the packs linked to a lawn_mower; it mows lanes over its lawn + for (const f of floor.furniture) { + if (!/:(robot_mower|mower_dock)$/.test(f.type)) continue; + const entity = this.furnitureLinks.get(f.id)?.entity ?? null; + if (!entity?.startsWith("lawn_mower.")) continue; + const state = hass.states[entity]?.state; + const mode: RobotInfo["mode"] = state === "mowing" ? "cleaning" : state === "returning" ? "returning" : state === "error" ? "error" : state === "docked" || !state ? "docked" : "idle"; + const rest: [number, number] = [f.x, f.z]; + const lawns = (floor.outdoor ?? []).filter((o) => o.type === "lawn" && o.points.length >= 3); + const lawn = lawns.find((o) => pointInPolygon(rest, o.points)) ?? [...lawns].sort((p, q) => polygonArea(q.points) - polygonArea(p.points))[0]; + // what stands on the lawn: beds, ponds, pools, terraces cut out of it + const obstacles = lawn ? (floor.outdoor ?? []).filter((o) => o !== lawn && o.type !== "lawn" && o.points.some((p) => pointInPolygon(p, lawn.points))).map((o) => o.points) : []; + out.push({ id: f.id, floorId: floor.id, rest, restHeading: (-f.rotation * Math.PI) / 180, mode, room: lawn?.points ?? null, roomId: lawn?.id ?? null, obstacles, y: lawn ? outdoorTopAt(floor, lawn, rest[0], rest[1]) : groundLevel(floor), mower: true }); + } + } + return out; + } + + /** Home battery: "64 % · ▲ 1,5 kW" (▲ charging, ▼ discharging; its power sensor counts discharging positive). */ + private batteryText(hass: HomeAssistant, soc: string | null, power: number | null): string { + const v = soc ? Number(hass.states[soc]?.state) : Number.NaN; + const parts: string[] = []; + if (Number.isFinite(v)) parts.push(`${formatNumber(hass, v, 0)} %`); + if (power !== null && Math.abs(power) >= 10) parts.push(`${power < 0 ? "▲" : "▼"} ${formatPower(hass, Math.abs(power))}`); + return parts.join(" · "); + } + + /** A sub-meter with "show unmetered" on: what its floors use, and how much of it no placed device measures. */ + private subMeterText(hass: HomeAssistant, b: Building, summary: EnergySummary, furnitureId: string | undefined): string | null { + const label = furnitureId ? subMeterLabel(b, summary, furnitureId) : null; + if (!label) return null; + return formatPower(hass, label.use) + (label.unmetered === null ? "" : ` · ${translate(hass, "meter_unmetered", { w: formatPower(hass, label.unmetered) })}`); + } + + /** Wallbox: "lädt · 11 kW", "angesteckt" or its power, from a status sensor (on/off or a state such as charging). */ + /** The meter: what the house draws from the grid, or feeds into it. */ + private meterText(hass: HomeAssistant, power: number | null): string { + if (power === null) return ""; + if (Math.abs(power) < 5) return formatPower(hass, 0); + return `${translate(hass, power < 0 ? "energy_grid_export" : "energy_grid_import")} ${formatPower(hass, Math.abs(power))}`; + } + + private wallboxText(hass: HomeAssistant, status: string | null, power: number | null): string { + const st = status ? hass.states[status] : undefined; + const raw = String(st?.state ?? "").toLowerCase(); + const charging = (power ?? 0) > 50 || /charg|laden|lädt/.test(raw); + const plugged = st?.entity_id.startsWith("binary_sensor.") ? raw === "on" : /connect|plug|ready|angesteckt|verbunden|wait|paused|suspend/.test(raw); + const label = charging ? translate(hass, "wallbox_charging") : plugged ? translate(hass, "wallbox_plugged") : st && !isUnavailable(st) && !st.entity_id.startsWith("binary_sensor.") ? stateText(hass, st) : ""; + const watts = power !== null && power > 50 ? formatPower(hass, power) : ""; + return [label, watts].filter(Boolean).join(" · "); + } + + /** The glowing faces of an item with a state entity (none while nothing is on). */ + private stateFaces(hass: HomeAssistant, f: Furniture): NonNullable { + const out: NonNullable = []; + const refs: [EntityRef | undefined, "all" | "left" | "right" | "top" | "bottom"][] = f.state_entity2 && f.state_entity2 !== "none" + ? [ + [f.state_entity, f.state_split === "top_bottom" ? "bottom" : "left"], + [f.state_entity2, f.state_split === "top_bottom" ? "top" : "right"], + ] + : [[f.state_entity, "all"]]; + for (const [ref, part] of refs) { + if (!ref || ref === "none") continue; + const st = hass.states[ref]; + if (!st || isUnavailable(st)) continue; + const on = isActive(st) || st.state === "home" || st.state === "occupied" || st.state === "on"; + if (!on) continue; + const lit = kindOf(ref) === "light" ? lightGlow(st) : null; + out.push({ part, color: lit ? lit.color : [1, 0.71, 0.28], level: lit ? lit.level : 0.85 }); + } + return out; + } + + /** The pin of a household item: when the bin is collected, whether there is post, how dry a plant is; and its glow when it is due. */ + private careMarker(hass: HomeAssistant, floor: Building["floors"][number], f: Furniture, care: "bin" | "mail" | "plant", entity: string): { marker: DeviceMarker & { fromFurniture: boolean; care: boolean }; glow: [number, number, number] | null } | null { + const st = hass.states[entity]; + if (!st) return null; + let text = ""; + let due = false; + let glow: [number, number, number] | null = null; + if (care === "bin") { + const days = pickupDays(st); + text = days === null ? stateText(hass, st) : days === 0 ? translate(hass, "care_bin_today") : days === 1 ? translate(hass, "care_bin_tomorrow") : translate(hass, "care_bin_days", { n: days }); + due = days !== null && days <= 1; + if (due) glow = [1, 0.72, 0.28]; + } else if (care === "mail") { + due = hasPost(st); + text = translate(hass, due ? "care_mail_yes" : "care_mail_no"); + if (due) glow = [1, 0.85, 0.3]; + } else { + const thirst = plantThirst(st, f.thirsty_below ?? 20); + due = !!thirst?.thirsty; + text = thirst ? (Number.isFinite(thirst.moisture) ? `${translate(hass, due ? "care_plant_thirsty" : "care_plant_ok")} · ${Math.round(thirst.moisture)} %` : translate(hass, due ? "care_plant_thirsty" : "care_plant_ok")) : stateText(hass, st); + if (due) glow = [1, 0.45, 0.3]; + } + const room = floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([f.x, f.z], r.points)); + const icon = { bin: "mdi:trash-can-outline", mail: "mdi:mailbox-outline", plant: "mdi:sprout-outline" }[care]; + return { + glow, + marker: { + id: entity, + floorId: floor.id, + roomId: room?.id ?? null, + x: f.x, + z: f.z, + y: markerHeight(f) + mountBase(floor, f), + icon: f.icon ? mdiIcon(f.icon) : mdiIcon(icon), + name: f.name || furnitureName(hass, f.type), + ownName: f.name || undefined, + showName: !!f.show_name, + text, + active: due, + unavailable: isUnavailable(st), + glow: null, + furnitureId: f.id, + show: f.marker ?? undefined, + fromFurniture: true, + care: true, + }, + }; + } + + /** A lamp: its 3D model glows with the linked light and is tapped directly. */ + private lampMarker(hass: HomeAssistant, floor: Building["floors"][number], f: Furniture, entity: string | null): DeviceMarker & { fromFurniture: boolean } { + const st = entity ? hass.states[entity] : undefined; + // further bulbs of the same fixture (a night light, an ambient ring): the lamp glows with them while its main light is off + const others = (f.extra_lights ?? []).map((id) => hass.states[id]).filter((s): s is HassEntity => !!s); + const otherOn = others.find((s) => isActive(s)); + const item = packItem(f.type); + const model = LAMP_MODEL[f.type] ?? item?.light ?? "floor"; + // a height above the floor set by hand wins (a table lamp on a shelf, a floor lamp on a platform); + // an LED strip outside the house counts from the ground there (a path light flush with the lawn) + const inRoom = floor.rooms.some((r) => r.points.length >= 3 && pointInPolygon([f.x, f.z], r.points)); + const base = model === "strip" && !inRoom + ? outdoorGround(floor, f.x, f.z) + (f.mount_y ?? 0) + : f.mount_y != null && !item + ? f.mount_y + : item || model === "wall" || model === "strip" + ? mountBase(floor, f) + : model === "table" + ? surfaceHeight(floor, f.x, f.z) + : model === "bollard" || model === "garden" + ? outdoorGround(floor, f.x, f.z) + : 0; + const room = floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([f.x, f.z], r.points)); + // hanging lamps hang from the ceiling right above them: the room's own, or one set on the lamp (a sloping ceiling) + const H = ceilingOf(floor, f); + // pack lamps: the marker sits above the lamp (below it when it hangs from the ceiling) + const y = item + ? item.mount === "ceiling" + ? Math.max(0.5, base - 0.15) + : base + f.h + 0.2 + : { + ceiling: H - 0.3, + downlight: H - 0.25, + spot: H - 0.35, + panel: H - 0.25, + pendant: Math.max(0.6, H - f.h - 0.25), + fan: Math.max(0.6, H - f.h - 0.2), + floor: base + f.h + 0.25, + uplight: base + f.h + 0.25, + table: base + f.h + 0.2, + wall: base + f.h + 0.2, + strip: f.upright ? base + f.w + 0.15 : Math.max(0.3, base - 0.2), + bollard: base + f.h + 0.25, + garden: base + f.h + 0.25, + }[model]; + const marker: DeviceMarker & { fromFurniture: boolean } = { + // a lamp without a light keeps a key of its own (it is drawn, but not tappable) + id: entity ?? `lamp:${f.id}`, + floorId: floor.id, + roomId: room?.id ?? null, + x: f.x, + z: f.z, + y, + icon: iconSvg("light"), + name: f.name || (entity ? entityName(hass, entity) : furnitureName(hass, f.type)), + text: st && (isActive(st) || !otherOn) ? stateText(hass, st) : otherOn ? entityName(hass, otherOn.entity_id) : "", + active: (st ? isActive(st) : false) || !!otherOn, + unavailable: st ? isUnavailable(st) : false, + glow: st || others.length ? scaleGlow(fixtureGlow(st, others, f.color_entity && f.color_entity !== "none" ? hass.states[f.color_entity] : undefined), f.glow_scale) : null, + lamp: model, + rotation: f.rotation, + mirror: !!f.mirror, + roll: f.tilt ?? 0, + upright: !!f.upright, + rise: f.rise ?? 0, + size: [f.w, f.d, f.h], + base, + pickable: !!entity, + furnitureId: f.id, + pack: item ? f.type : null, + lightY: item ? (item.mount === "ceiling" ? base : base + f.h * 0.85) : undefined, + ceiling: H, + effect: st?.state === "on" ? lightAnimation(f, lightEffectSource(hass, f, entity)) : undefined, + variant: f.variant, + show: f.marker ?? undefined, + fromFurniture: true, + }; + return st && entity ? withPluginPatch(hass, marker, st, false) : marker; + } + + /** + * Marker rule: "important" leaves out devices that their 3D object stands for (lamps, a TV that is + * off) and keeps devices without an object (sensors, heating, switches) and values (watts, the app). + */ + private showPin(m: DeviceMarker & { fromFurniture?: boolean; energyDevice?: boolean; care?: boolean; readout?: boolean }): boolean { + // while furnishing every placed device has a pin to grab it by + if (this.furnish && !m.fromFurniture) return true; + // the device's own setting wins over the marker mode (except "none", which hides every marker) + if (m.show === "never" || this.markerMode === "none") return false; + if (m.show === "always") return true; + // only while it is on: a motion sensor while it detects, a door while it is open + if (m.show === "active" || (this.building?.settings.motion_markers_active && isMotionSensor(this.hass, m.id))) { + if (!m.active) return false; + if (m.show === "active") return true; + } + // outside the opened room (the house, a floor, another room): the kinds chosen in the card + if (this.markersOutside && !(this.roomId && m.roomId === this.roomId)) return this.markersOutside.includes(markerKind(m.id, !!m.lamp)); + if (this.markerMode === "all") return true; + if (m.lamp) return false; + const kind = kindOf(m.id); + if (kind === "light") return false; + // a ceiling fan's pin is how it is switched (its blades belong to the light kit) + if (m.fromFurniture && kind === "fan") return true; + // a bin to put out, post in the box, a thirsty plant: important while it is due + if (m.care) return m.active; + // an item with its own tap action: its pin is the way to find it + if (m.id.startsWith("tap:")) return true; + // values worth reading (a fridge's temperatures) + if (m.readout) return true; + if (m.fromFurniture) return (m.power ?? 0) >= 1 || (kind === "media" && m.active) || (!!m.energyDevice && !!m.text); + return true; + } + + /** Tapping a window opens its blind (or contact); a door or garage door its cover or contact. */ + private openingTargets(): Map { + const out = new Map(); + for (const [id, e] of this.openingLinks ?? []) { + // a door with a smart lock is tapped to lock or unlock it + const target = e.lock ?? e.cover ?? e.contact ?? e.tilt; + if (target) out.set(id, target); + } + return out; + } + + /** The second blind of an opening whose tap opens its first one: the right half of the opening is tapped for it. */ + /** Saves the house as an STL file for 3D printing (1:100, millimetres). */ + downloadStl(): void { + const bytes = this.viewer?.exportStl(10); + if (!bytes) return; + const url = URL.createObjectURL(new Blob([bytes as BlobPart], { type: "model/stl" })); + const a = document.createElement("a"); + a.href = url; + a.download = `nextfloor-${new Date().toISOString().slice(0, 10)}.stl`; + a.click(); + setTimeout(() => URL.revokeObjectURL(url), 5000); + } + + private secondBlinds(): Map { + const out = new Map(); + for (const [id, e] of this.openingLinks ?? []) if (e.cover2 && !e.lock && e.cover) out.set(id, e.cover2); + return out; + } + + /** Pictures of the floors, drawn a moment after the plan or the look changed (once, not per frame). */ + 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) { + 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()); + this.thumbTimer = setTimeout(() => { + // at night (kiosk) the pictures are drawn once and then rest + if (!this.viewer || (this.dimmed && this._thumbs.length)) return; + // a hidden tab draws nothing; the pictures follow once it shows again + if (document.hidden) { + this.scheduleThumbs(3000); + return; + } + this.thumbsAt = Date.now(); + this._thumbs = this.viewer.floorThumbnails(this.narrowThumbs ? 104 : 150, this.narrowThumbs ? 78 : 112); + }, wait); + } + + private get narrowThumbs(): boolean { + return this._narrowStage; + } + + private renderThumbs() { + 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 + const order = [...this._thumbs].sort( + (a, b) => (this.building!.floors.find((f) => f.id === b.floorId)?.elevation ?? 0) - (this.building!.floors.find((f) => f.id === a.floorId)?.elevation ?? 0), + ); + const compact = this._thumbsCompact; + const fold = () => { + this._thumbsCompact = !compact; + try { + localStorage.setItem("nextfloor.thumbs_compact", this._thumbsCompact ? "1" : "0"); + } catch { + // private mode: the choice lasts for this page only + } + }; + return html``; + } + + /** Long press: the quick menu at the device, or the details for devices without one. */ + private onDeviceHold(entityId: string, x: number, y: number): void { + const kind = kindOf(entityId); + if (kind === "light" || kind === "cover" || kind === "switch" || kind === "fan" || kind === "lock") this._menu = { entity: entityId, x, y }; + else openMoreInfo(this, entityId); + } + + /** Swipe up or down on a lamp (brightness) or a blind (position). */ + private onDeviceSwipe(entityId: string, phase: "start" | "move" | "end", dy: number, x: number, y: number): boolean { + const st = this.hass?.states[entityId]; + if (phase === "start") { + // devices that ask before switching are not moved by a swipe (it turns the view instead) + if (!st || isUnavailable(st) || this.confirmSet.has(entityId)) return false; + const kind = kindOf(entityId); + if (kind === "light" && lightAbilities(st).dim) { + const pct = st.state === "on" ? (typeof st.attributes.brightness === "number" ? Math.round((st.attributes.brightness as number) / 2.55) : 100) : 0; + this._swipe = { entity: entityId, kind: "light", start: pct, value: pct, x, y }; + return true; + } + // a fan with speeds: up = faster, down to 0 = off + if (kind === "fan" && typeof st.attributes.percentage_step === "number") { + const pct = st.state === "on" && typeof st.attributes.percentage === "number" ? st.attributes.percentage : 0; + this._swipe = { entity: entityId, kind: "fan", start: pct, value: pct, x, y }; + return true; + } + if (kind === "cover" && coverPositionable(st)) { + const pos = st.attributes.current_position as number; + this._swipe = { entity: entityId, kind: "cover", start: pos, value: pos, x, y }; + return true; + } + return false; + } + const s = this._swipe; + if (!s || s.entity !== entityId) return false; + if (phase === "move") { + // the whole range over about 220 pixels; up = brighter / blind up + const value = Math.round(Math.min(100, Math.max(0, s.start - (dy / 220) * 100))); + if (value !== s.value) this._swipe = { ...s, value }; + // at most a few calls per second while the finger moves + const now = performance.now(); + if (now - this.swipeSent > 350) { + this.swipeSent = now; + this.applySwipe(); + } + } else { + this.applySwipe(); + clearTimeout(this.swipeTimer); + this.swipeTimer = setTimeout(() => (this._swipe = null), 700); + } + return true; + } + + private applySwipe(): void { + const s = this._swipe; + if (!s || !this.hass) return; + if (s.kind === "light") { + if (s.value <= 0) void this.hass.callService("light", "turn_off", { entity_id: s.entity }); + else void this.hass.callService("light", "turn_on", { entity_id: s.entity, brightness_pct: s.value }); + } else if (s.kind === "fan") { + if (s.value <= 0) void this.hass.callService("fan", "turn_off", { entity_id: s.entity }); + else void this.hass.callService("fan", "set_percentage", { entity_id: s.entity, percentage: s.value }); + } else void this.hass.callService("cover", "set_cover_position", { entity_id: s.entity, position: s.value }); + } + + /** Fly to a search result: rooms are selected, devices shown on their floor and flashing. */ + /** Opens a room, on another floor too: the floor first, then the room (the host opens one step per tap). */ + private openRoom(floorId: string, roomId: string): void { + if (this.floorId === floorId && this.roomId === roomId) return; + if (this.floorId !== floorId) { + this.fire("floor-tap", { floorId }); + setTimeout(() => this.fire("room-tap", { floorId, roomId }), 60); + } else this.fire("room-tap", { floorId, roomId }); + } + + private goTo(item: SearchItem): void { + this._find = null; + if (item.kind === "room" || item.kind === "circuit") { + if (item.roomId) this.openRoom(item.floorId, item.roomId); + return; + } + if (this.floorId !== item.floorId) this.fire("floor-tap", { floorId: item.floorId }); + // after the host has switched the floor (its own camera flight starts first) + setTimeout(() => this.viewer?.focus(item.floorId, item.x, item.z, item.y, item.entity), 120); + } + + /** Start or stop hearing announcements (once per view; Home Assistant subscribes again after a reconnect by itself). */ + private listenToAnnouncements(on: boolean): void { + if (!on) { + this.stopAnnouncements?.(); + this.stopAnnouncements = null; + clearTimeout(this.announceTimer); + return; + } + if (this.stopAnnouncements) return; + // a placeholder until the subscription stands, so a second update does not subscribe twice + let stopped = false; + this.stopAnnouncements = () => (stopped = true); + void subscribeAnnouncements(this.hass, (a) => this.announce(a)).then((stop) => { + if (stopped) stop(); + else this.stopAnnouncements = stop; + }); + } + + /** An announcement arrived: show it big over the house, chime and speak it (once per page, only if meant for this screen). */ + private announce(a: Announcement): void { + // the action nextfloor.reload_screens: load the page again, some seconds apart so the tablets do not all fetch at once + const reload = a as unknown as { reload?: boolean; template?: string | null }; + if (reload?.reload === true) { + if (!reload.template || reload.template === this.templateName) setTimeout(() => location.reload(), 500 + Math.random() * 6000); + return; + } + // only a real announcement (a message to say); anything else on the subscription is ignored + if (typeof a?.message !== "string" || !a.message.trim()) return; + if (!forThisScreen(a, this.screenName) || !claim(a)) return; + const duration = showFor(a.message); + this._announcement = { message: a.message, until: Date.now() + duration }; + clearTimeout(this.announceTimer); + this.announceTimer = setTimeout(() => (this._announcement = null), duration); + void playAnnouncement(this.hass, a); + } + + private renderAnnouncement() { + const a = this._announcement; + if (!a) return nothing; + return html``; + } + + private renderAlerts() { + const b = this.building; + if (!this._alerts.length || !b) return nothing; + const shown = this._alerts.slice(0, 3); + return html``; + } + + /** Scenes and scripts of the selected room's area as chips (while no panel lists them). */ + private renderScenes() { + const b = this.building; + if (!this.scenes || !this.roomId || this.panelOpen || !b || !this.hass) return nothing; + const room = b.floors.flatMap((f) => f.rooms).find((r) => r.id === this.roomId); + const ids = room ? roomEntities(this.hass, room).filter((id) => kindOf(id) === "scene" || kindOf(id) === "script").slice(0, 6) : []; + if (!ids.length) return nothing; + const areaName = room?.area_id ? this.hass.areas?.[room.area_id]?.name : undefined; + return html`
+ ${ids.map((id) => html``)} +
`; + } + + private renderFind() { + const b = this.building; + if (!b || !this.hass) return nothing; + if (this._find === null) { + return html``; + } + const results = searchItems((this.findIndex ??= searchIndex(this.hass, b)), this._find); + return html`
+ (this._find = (e.target as HTMLInputElement).value)} + @keydown=${(e: KeyboardEvent) => { + if (e.key === "Escape") this._find = null; + if (e.key === "Enter" && results[0]) this.goTo(results[0]); + }} + /> + + ${this._find.trim() + ? html`
+ ${results.length + ? results.map( + (it) => html``, + ) + : html`

${translate(this.hass, "find_none")}

`} +
` + : nothing} +
`; + } + + /** + * The star: a small menu for the floor shown (or the whole house) with all lights on / off, all blinds + * up / down and the house's favourites (#145). House-wide actions want a second tap. + */ + private renderCentral() { + const b = this.building; + const hass = this.hass; + if (!b || !hass || !this.central || this._find !== null) return nothing; + const t = (k: I18nKey, vars?: Record) => translate(hass, k, vars); + const star = html``; + if (!this._central) return star; + const floor = this.floorId ? b.floors.find((f) => f.id === this.floorId) : undefined; + const floors = floor ? [floor] : b.floors; + const lights = floors.flatMap((f) => floorControls(hass, f).lights); + const covers = floors.flatMap((f) => floorControls(hass, f).covers); + const lightsOn = lights.filter((id) => hass.states[id]?.state === "on").length; + const house = !floor; + // house-wide: the first tap arms the button ("sure?"), the second runs it + const act = (key: string, domain: string, service: string, ids: string[]) => { + if (!ids.length) return; + if (house && this._armed !== key) { + this._armed = key; + clearTimeout(this.armTimer); + this.armTimer = setTimeout(() => (this._armed = null), 3500); + return; + } + this._armed = null; + void hass.callService(domain, service, { entity_id: ids }); + }; + const button = (key: string, label: I18nKey, domain: string, service: string, ids: string[]) => + html``; + const onFloor = b.settings.favorite_floors ?? {}; + const favorites = (b.settings.favorites ?? []).filter((id) => hass.states[id] && (!onFloor[id] || !floor || onFloor[id] === floor.id)); + const own = this.buttons ?? b.settings.buttons ?? []; + return html`${star} + `; + } + + /** The eye: one tap hides every bar and overlay so only the stage remains, the next brings them back. */ + private toggleLock(): void { + this._locked = !this._locked; + try { + localStorage.setItem(LOCK_KEY, this._locked ? "1" : "0"); + } catch { + // without storage the lock lasts until the page reloads + } + } + + /** Opens time travel over the last `hours` (24 or 168) at its start, or closes it and shows the house live again. */ + private async openTravel(hours: number | null): Promise { + clearInterval(this.travelTimer); + this.travelTimer = undefined; + if (hours === null || !this.hass) { + this._travel = null; + this.syncDevices(true); + return; + } + const to = Date.now(); + const from = to - hours * 3600_000; + this._travel = { history: new Map(), from, to, t: from, playing: false, speed: hours > 24 ? 3600 : 600, hours, moments: [], loading: true }; + try { + const history = await loadHistory(this.hass, replayable(this.watched), from, to); + if (!this._travel || this._travel.from !== from) return; + this._travel = { ...this._travel, history, moments: changeMoments(history, from, to), loading: false }; + } catch { + this._travel = null; + this._error = translate(this.hass, "travel_failed"); + return; + } + this.syncDevices(true); + } + + private travelTo(t: number): void { + const tr = this._travel; + if (!tr) return; + this._travel = { ...tr, t: Math.min(tr.to, Math.max(tr.from, t)) }; + this.syncDevices(true); + } + + private playTravel(on: boolean): void { + const tr = this._travel; + if (!tr) return; + clearInterval(this.travelTimer); + this.travelTimer = undefined; + this._travel = { ...tr, playing: on, t: on && tr.t >= tr.to ? tr.from : tr.t }; + if (!on) return; + this.travelTimer = setInterval(() => { + const now = this._travel; + if (!now) return; + const t = now.t + 250 * now.speed; + if (t >= now.to) this.playTravel(false); + this.travelTo(t); + }, 250); + } + + private renderTravel() { + if (!this.hass || this.clean) return nothing; + const t = (k: I18nKey) => translate(this.hass, k); + const tr = this._travel; + if (!tr) { + if (!this.travelButton) return nothing; + return html``; + } + const locale = this.hass.language ?? navigator.language; + const when = new Intl.DateTimeFormat(locale, { weekday: "short", hour: "2-digit", minute: "2-digit" }).format(new Date(tr.t)); + const span = tr.to - tr.from || 1; + const speeds: [number, I18nKey][] = [ + [60, "travel_speed_min"], + [600, "travel_speed_10min"], + [3600, "travel_speed_hour"], + ]; + return html`
+ + ${tr.loading ? t("travel_loading") : when} +
+ + this.travelTo(Number((e.target as HTMLInputElement).value))} /> +
+ + + + +
`; + } + + private toggleWalk(): void { + const v = this.viewer; + if (!v) return; + if (this._walking) { + v.stopWalk(); + this._walking = false; + } else this._walking = v.startWalk() !== null; + this._stick = null; + } + + /** The touch stick: drag the knob up to walk, down to step back, sideways to turn. */ + private stickMove(e: PointerEvent, start = false): void { + const pad = e.currentTarget as HTMLElement; + if (start) pad.setPointerCapture(e.pointerId); + else if (!this._stick) return; + const r = pad.getBoundingClientRect(); + const radius = r.width / 2; + let [x, y] = [(e.clientX - r.left - radius) / radius, (e.clientY - r.top - radius) / radius]; + const l = Math.hypot(x, y); + if (l > 1) [x, y] = [x / l, y / l]; + this._stick = [x, y]; + this.viewer?.setWalkStick(Math.abs(x) < 0.12 ? 0 : x, Math.abs(y) < 0.12 ? 0 : y); + } + + private stickEnd(): void { + this._stick = null; + this.viewer?.setWalkStick(0, 0); + } + + private renderWalk() { + if (!this.hass || this.clean || (!this.walkButton && !this._walking)) return nothing; + const t = (k: I18nKey) => translate(this.hass, k); + const knob = this._stick ?? [0, 0]; + return html` + ${this._walking + ? html`
this.stickMove(e, true)} @pointermove=${(e: PointerEvent) => this.stickMove(e)} @pointerup=${() => this.stickEnd()} @pointercancel=${() => this.stickEnd()}> + +
+

${t("walk_hint")}

` + : nothing}`; + } + + private renderLock() { + if (!this.lockButton || !this.hass || this.clean) return nothing; + const label = translate(this.hass, this._locked ? "lock3d_off" : "lock3d_on"); + return html``; + } + + /** The clock in its corner; top left it shares the column with the sensor and energy bar (see renderTopLeft). */ + private renderClock(inColumn = false) { + if (!this.clock || !this.hass || (this.clock === "top_left" && !inColumn)) return nothing; + const locale = this.hass.language ?? navigator.language; + const now = new Date(this._now); + const time = new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit" }).format(now); + const day = new Intl.DateTimeFormat(locale, { weekday: "long", day: "numeric", month: "long" }).format(now); + return html``; + } + + private renderEye() { + // while the search is open its field takes the eye's place (#220) + if (!this.cleanButton || !this.hass || (this._find !== null && !this.clean)) return nothing; + const label = translate(this.hass, this.clean ? "controls_show" : "controls_hide"); + return html``; + } + + private renderSwipe() { + const s = this._swipe; + if (!s || !this.hass) return nothing; + const off = s.kind === "light" && s.value <= 0; + return html`
+ ${entityName(this.hass, s.entity)} + ${off ? translate(this.hass, "swipe_off") : `${s.value} %`} + +
`; + } + + /** A light switch or socket was tapped: one button switches at once, several open a small list to pick from. */ + private tapPlate(furnitureId: string, x: number, y: number): void { + const f = this.building?.floors.flatMap((fl) => fl.furniture).find((it) => it.id === furnitureId); + const ids = f ? gangEntities(f.gang_entities, packItem(f.type)?.gangs ?? 0) : []; + if (ids.length === 1) return this.onDeviceTap(ids[0], x, y); + if (ids.length > 1) this._plate = { ids, x, y }; + } + + private renderPlate() { + const p = this._plate; + if (!p || !this.hass) return nothing; + const hass = this.hass; + const close = () => (this._plate = null); + return html`
+ `; + } + + private renderMenu() { + const m = this._menu; + if (!m || !this.hass) return nothing; + const stage = this.renderRoot.querySelector(".nf-stage") as HTMLElement | null; + const w = stage?.clientWidth ?? 800; + const h = stage?.clientHeight ?? 600; + const left = Math.max(8, Math.min(w - 240, m.x - 116)); + const top = Math.max(8, Math.min(h - 360, m.y - 170)); + return html`
(this._menu = null)}>
+ !p.speakers?.length || p.speakers.includes(m.entity))} + ?confirmSwitch=${this.confirmSet.has(m.entity)} + .myPosition=${this.myPositionOf(m.entity)} + @close=${() => (this._menu = null)} + >`; + } + + /** The favourite position of a blind (Somfy's "My") set on a window it covers, or null. */ + private myPositionOf(entity: string): number | null { + for (const floor of this.building?.floors ?? []) + for (const o of floor.openings) { + const links = this.openingLinks?.get(o.id); + if (o.my_position != null && (links?.cover === entity || links?.cover2 === entity)) return o.my_position; + } + return null; + } + + private onDeviceTap(entityId: string, x = 0, y = 0): void { + // lamps without a light are drawn, but nothing of Home Assistant stands behind them + if (entityId.startsWith("lamp:")) return; + // in the past nothing is switched + if (this._travel) return; + const ownTap = entityId.startsWith("tap:") ? entityId.slice(4) : this.tapPins.get(entityId); + if (ownTap) { + const f = this.building?.floors.flatMap((fl) => fl.furniture).find((it) => it.id === ownTap); + if (f?.tap) runButton(this.hass, this, f.tap); + return; + } + if (this.pluginTapped(entityId)) return; + if (entityId.startsWith("gang:")) return this.tapPlate(entityId.slice(5), x, y); + // an outdoor area's pin opens Outside, with the devices of its area + if (entityId.startsWith("outdoor:")) { + this.fire("room-tap", { floorId: null, roomId: "nf-outside" }); + return; + } + // the street end of the grid cable opens the grid sensor: the balance's, else the meter's (#223) + if (entityId === "grid") { + const b = this.building; + const sensor = b ? (b.energy.grid ?? deviceSensors(b, (f) => this.furnitureLinks?.get(f.id)?.power ?? null).grid) : null; + if (sensor) openMoreInfo(this, sensor); + return; + } + const kind = kindOf(entityId); + // blinds have no single on/off: a tap opens their quick menu (up, positions, stop, down); speakers and TVs open theirs + // (play, skip, volume, sources and the stations set for them) + if (kind === "cover" || kind === "media") { + this._menu = { entity: entityId, x, y }; + return; + } + // a smart lock always asks first, whichever way it goes + if (kind === "lock") { + const unlocked = isUnlocked(this.hass, entityId); + const name = entityName(this.hass, entityId); + if (confirm(translate(this.hass, unlocked ? "lock_confirm_lock" : "lock_confirm_unlock", { name }))) void this.hass.callService("lock", unlocked ? "lock" : "unlock", { entity_id: entityId }); + return; + } + if (kind && TOGGLE_KINDS.has(kind)) { + if (this.confirmSet.has(entityId) && !confirm(translate(this.hass, "confirm_switch", { name: entityName(this.hass, entityId) }))) return; + void toggleEntity(this.hass, entityId); + } else openMoreInfo(this, entityId); + } + + /** Hands a tap on a placed device to the plugins (a camera opens its live picture); true when one took it. */ + private pluginTapped(entityId: string): boolean { + const state = this.hass?.states[entityId]; + const placement = this.placementInfo.get(entityId); + if (!state || !placement) return false; + const placed = this.building?.floors.find((f) => f.id === placement.floorId)?.placements.find((p) => p.entity_id === entityId); + return pluginTap({ hass: this.hass, entityId, state }, placement, placed?.plugin ?? undefined, { + showWindow: (node, options) => { + if (node && "hass" in node) (node as Node & { hass: unknown }).hass = this.hass; + this._pluginWindow = node ? { node, title: options?.title ?? "" } : null; + }, + moreInfo: (id) => openMoreInfo(this, id ?? entityId), + }); + } + + private renderPluginWindow() { + const w = this._pluginWindow; + if (!w) return nothing; + return html`
e.stopPropagation()}> +
${w.title}
+
${w.node}
+
`; + } + + /** The start view: the card's own, else the one remembered in the editor. */ + private startViewOf(): StartView | null { + return this.startView ?? this.building?.settings.start_view ?? null; + } + + /** The camera as it stands (for "remember this view as the start"). */ + currentView(): StartView | null { + return this.viewer?.currentView() ?? null; + } + + resetView(): void { + this.viewer?.resetView(); + } + + private fire(type: string, detail: unknown): void { + this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true })); + } + + private toggleFlows(): void { + this._flows = !this._flows; + try { + localStorage.setItem("nextfloor.flows", this._flows ? "1" : "0"); + } catch { + // private mode: the choice lasts for this page only + } + this.syncDevices(true); + } + + /** The floating cards (house balance; car and music follow) and the points in the plan they hang over. */ + /** The cars of the parking spots: what each reports, and the point over the spot (over the car when it is there). */ + /** Heat pumps in the plan whose device reports temperatures or heat. */ + private liveHeatPumps(b: Building): { id: string; name: string; floorId: string; x: number; z: number; at: { floorId: string; x: number; z: number; y: number }; pump: HeatPumpInfo }[] { + const hass = this.hass; + if (!hass) return []; + const out: ReturnType = []; + for (const floor of b.floors) + for (const f of floor.furniture) { + if (!isHeatPump(f.type)) continue; + const link = this.furnitureLinks?.get(f.id); + const pump = readHeatPump(hass, link?.entity ?? link?.power ?? null); + if (pump) out.push({ id: f.id, name: f.name || furnitureName(hass, f.type), floorId: floor.id, x: f.x, z: f.z, at: { floorId: floor.id, x: f.x, z: f.z, y: mountBase(floor, f) + f.h + 0.5 }, pump }); + } + return out; + } + + /** 3D printers in the plan whose device reports a print (the card shows while it prints, and a while after). */ + private livePrinters(b: Building): { id: string; name: string; at: { floorId: string; x: number; z: number; y: number }; printer: PrinterInfo }[] { + const hass = this.hass; + const out: { id: string; name: string; at: { floorId: string; x: number; z: number; y: number }; printer: PrinterInfo }[] = []; + if (!hass) return out; + for (const floor of b.floors) + for (const f of floor.furniture) { + if (!isPrinter3d(f.type)) continue; + const link = this.furnitureLinks?.get(f.id); + const printer = readPrinter(hass, link?.entity ?? link?.power ?? null); + if (!printer || (!printer.printing && !/pause|finish|complete|error/.test(printer.status))) continue; + out.push({ id: f.id, name: f.name || furnitureName(hass, f.type), at: { floorId: floor.id, x: f.x, z: f.z, y: mountBase(floor, f) + f.h + 0.5 }, printer }); + } + return out; + } + + private liveCars(hass: HomeAssistant, b: Building): { spot: string; name: string; at: { floorId: string; x: number; z: number; y: number }; car: CarInfo }[] { + const out: { spot: string; name: string; at: { floorId: string; x: number; z: number; y: number }; car: CarInfo }[] = []; + for (const floor of b.floors) { + for (const f of floor.furniture) { + if (f.type !== "parking") continue; + const car = readCar(hass, f); + if (!car || (car.soc === null && car.range === null && car.locked === null && car.climateOn === null)) continue; + const vehicle = parkedVehicle(hass, f); + const veh = vehicle ? vehicleFurniture(f, vehicle) : null; + const name = f.name || (vehicle ? furnitureName(hass, vehicle) : furnitureName(hass, f.type)); + out.push({ spot: f.id, name, at: { floorId: floor.id, x: f.x, z: f.z, y: mountBase(floor, f) + (veh?.h ?? 0.2) + 0.6 }, car }); + } + } + return out; + } + + /** Media players in the plan: placed as a device, or linked to furniture (TV, speaker); their point is on top of it. */ + private liveMedia(hass: HomeAssistant, b: Building): MediaNow[] { + const spots: { entity: string; name: string; at: { floorId: string; x: number; z: number; y: number }; rings?: number | null }[] = []; + for (const floor of b.floors) { + for (const f of floor.furniture) { + const e = this.furnitureLinks?.get(f.id)?.entity; + if (e?.startsWith("media_player.")) spots.push({ entity: e, name: f.name || furnitureName(hass, f.type), at: { floorId: floor.id, x: f.x, z: f.z, y: mountBase(floor, f) + f.h + 0.15 }, rings: f.sound_rings }); + } + for (const pl of floor.placements) { + if (pl.entity_id.startsWith("media_player.")) spots.push({ entity: pl.entity_id, name: pl.name || entityName(hass, pl.entity_id), at: { floorId: floor.id, x: pl.x, z: pl.z, y: (pl.y ?? 1.1) + 0.15 }, rings: pl.sound_rings }); + } + } + return mediaNow(hass, spots); + } + + /** Today's appointments, loaded at most every 15 minutes, and again after midnight. */ + private refreshToday(b: Building): void { + const hass = this.hass; + const calendars = b.settings.calendars ?? []; + const days = Math.max(1, Math.min(7, b.settings.today_days ?? 1)); + // a new day or a new number of days loads again at once + const day = `${new Date().toDateString()}|${days}`; + if (!hass || !calendars.length || (Date.now() - this.todayAt < 900_000 && day === this.todayDay)) return; + this.todayAt = Date.now(); + this.todayDay = day; + void loadToday(hass, calendars, days).then((items) => (this._todayItems = items)); + } + + /** The forecast, asked for at most every 30 minutes, and at once when the entity or the day changes. */ + private refreshForecast(b: Building): void { + const hass = this.hass; + const entity = b.settings.forecast && hass ? weatherEntity(hass, this.weatherEntityId ?? b.settings.weather_entity) : null; + if (!hass || !entity) return; + const key = `${entity}|${new Date().toDateString()}`; + if (Date.now() - this.forecastAt < 1_800_000 && key === this.forecastKey) return; + this.forecastAt = Date.now(); + this.forecastKey = key; + void loadForecast(hass, entity).then((raw) => (this._forecast = raw)); + } + + /** The weather forecast card (#84): a row per day with the weather, high and low, and the rain. */ + private renderForecast(corner: "top_left" | "top_right") { + const b = this.building; + const hass = this.hass; + const card = b?.settings.forecast; + if (!b || !hass || !card || card.corner !== corner || this.clean) return nothing; + if (corner === "top_right" && (this.roomId || this.panelOpen)) return nothing; + const days = forecastDays(this._forecast, Math.max(1, Math.min(7, card.days))); + if (!days.length) return nothing; + const entity = weatherEntity(hass, this.weatherEntityId ?? b.settings.weather_entity); + const attrs = entity ? hass.states[entity]?.attributes : undefined; + const unit = String(attrs?.temperature_unit ?? "°"); + const rainUnit = String(attrs?.precipitation_unit ?? "mm"); + const lang = hass.language ?? navigator.language; + const name = new Intl.DateTimeFormat(lang, { weekday: "short" }); + const deg = (v: number | null) => (v === null ? "–" : `${Math.round(v)}°`); + return html`
+
    + ${days.map( + (d, i) => html`
  • + ${i === 0 ? translate(hass, "today") : name.format(new Date(d.day))} + + ${deg(d.high)} ${deg(d.low)} + ${d.rain !== null && d.rain > 0 ? `💧${d.rain.toLocaleString(lang, { maximumFractionDigits: 1 })} ${rainUnit}` : d.chance !== null && d.chance > 0 ? `💧${Math.round(d.chance)} %` : ""} +
  • `, + )} +
+
`; + } + + private renderToday() { + const b = this.building; + const hass = this.hass; + // the room panel (a room, or Outside) takes the right side; the Today card would lie under it and catch its taps (#83) + if (!b || !hass || this.clean || this.roomId || this.panelOpen) return nothing; + const forecast = this.renderForecast("top_right"); + const today = this.today === false ? nothing : this.renderTodayCard(b, hass); + if (today === nothing && forecast === nothing) return nothing; + return html`
${today}${forecast}
`; + } + + private renderTodayCard(b: Building, hass: HomeAssistant) { + const bins = binsDue(hass, b, Date.now(), { today: translate(hass, "care_bin_today"), tomorrow: translate(hass, "care_bin_tomorrow") }); + const items = sortDay([...bins, ...(this._todayItems ?? [])]); + if (!items.length && !(b.settings.calendars ?? []).length) return nothing; + const open = this._todayOpen !== false; + const date = new Intl.DateTimeFormat(hass.language ?? navigator.language, { weekday: "long", day: "numeric", month: "long" }).format(new Date()); + const lang = hass.language ?? navigator.language; + const dayName = (n: number) => { + if (n === 1) return translate(hass, "tomorrow"); + const d = new Date(); + d.setDate(d.getDate() + n); + return new Intl.DateTimeFormat(lang, { weekday: "long", day: "numeric", month: "numeric" }).format(d); + }; + // over several days a heading before the first line of each later day + const lines = items.flatMap((i, k) => [ + (i.day ?? 0) > 0 && (items[k - 1]?.day ?? 0) !== i.day ? html`
  • ${dayName(i.day ?? 0)}
  • ` : nothing, + html`
  • ${i.title}${i.source}
  • `, + ]); + return html`
    + + ${open + ? items.length + ? html`
      + ${lines} +
    ` + : html`

    ${translate(hass, "today_none")}

    ` + : nothing} +
    `; + } + + private week: WeekBars | null = null; + private weekAt = 0; + + /** The last seven days for the house card, from the long-term statistics, loaded at most every hour while the card shows. */ + private refreshWeek(b: Building): void { + const hass = this.hass; + if (!hass || this._travel || Date.now() - this.weekAt < 3_600_000) return; + this.weekAt = Date.now(); + const found = deviceSensors(b, (f) => this.furnitureLinks?.get(f.id)?.power ?? null); + const e = b.energy; + const src = { + solar: e.solar ? [e.solar] : found.solar, + grid: e.grid ?? found.grid, + gridInvert: !!e.grid_invert, + battery: e.battery ? [e.battery] : found.battery, + batteryInvert: !!e.battery_invert, + consumption: e.consumption, + }; + void loadWeek(hass, src) + .then((week) => { + this.week = week; + this.syncDevices(true); + }) + .catch(() => (this.week = null)); + } + + /** The open floor's own meter (with its share of the house's use), then gas and water with the house's balance: what their sensors read now. */ + private meterRows(b: Building, consumption: number | null = null): { icon: string; label: string; value: string }[] { + const hass = this.hass; + const rows: { icon: string; label: string; value: string }[] = []; + const floor = this.floorId ? b.floors.find((f) => f.id === this.floorId) : undefined; + const floorPower = floor?.power_entity ? readPower(hass?.states[floor.power_entity]) : null; + if (floor && floorPower !== null) { + const share = consumption && consumption > 0 ? ` · ${translate(hass, "floor_power_share", { n: Math.round((Math.max(0, floorPower) / consumption) * 100) })}` : ""; + rows.push({ icon: "⚡", label: floor.name, value: `${powerText(hass, floorPower)}${share}` }); + } + for (const [key, icon, label] of [["gas", "🔥", "energy_gas_short"], ["water", "💧", "energy_water_short"]] as const) { + const id = b.energy[key]; + const st = id ? hass?.states[id] : undefined; + if (st && !isUnavailable(st)) rows.push({ icon, label: translate(hass, label), value: stateText(hass, st) }); + } + return rows; + } + + /** Solar and consumption over the last 24 hours for the house card, loaded at most every 10 minutes while the card shows. */ + private refreshDayCurves(b: Building): void { + const hass = this.hass; + if (!hass || this._travel || Date.now() - this.curvesAt < 600_000) return; + this.curvesAt = Date.now(); + const balance = (h: HomeAssistant) => energySummary(h, b, findConsumers(h, b), deviceSensors(b, (f) => this.furnitureLinks?.get(f.id)?.power ?? null)); + const ids = statesRead(hass, balance); + const to = Date.now(); + const from = to - 24 * 3600_000; + void loadHistory(hass, ids, from, to, true) + .then((history) => { + this.dayCurves = dayCurves(hass, history, from, to, balance); + this.syncDevices(true); + }) + .catch(() => (this.dayCurves = null)); + } + + private syncLhCards(v: NextFloorViewer, b: Building, pic: EnergyPicture, cars: ReturnType, media: MediaNow[]): void { + const cards: LiveCard[] = []; + const s = pic.summary; + const hasEnergy = s.solar !== null || s.grid !== null || s.battery !== null || s.consumption !== null; + const hub = houseHub(b); + // over the house, or over the floor that is open (the card stays in the floor views too) + const top = (this.floorId ? b.floors.find((f) => f.id === this.floorId) : undefined) ?? [...b.floors].sort((p, q) => q.elevation - p.elevation)[0]; + if (this.liveCardsOn && !this.dimmed && !this.roomId && hasEnergy && hub && top) { + // over the middle of the house, above the roof + let x = 0, z = 0, n = 0; + for (const r of top.rooms) for (const [px, pz] of r.points) (x += px), (z += pz), n++; + cards.push({ kind: "house", at: { floorId: top.id, x: n ? x / n : hub.x, z: n ? z / n : hub.z, y: top.height + (this.floorId ? 1.2 : 3.2) }, summary: s, autarky: pic.autarky, curves: this.dayCurves ?? undefined, week: this.week ?? undefined, meters: this.meterRows(b, s.consumption) }); + this.refreshDayCurves(b); + this.refreshWeek(b); + } + if (this.liveCardsOn && !this.dimmed && !this.roomId) { + for (const c of cars) cards.push({ kind: "car", at: c.at, spot: c.spot, name: c.name, car: c.car }); + for (const p of this.livePrinters(b)) cards.push({ kind: "printer", at: p.at, name: p.name, printer: p.printer }); + for (const p of this.liveHeatPumps(b)) cards.push({ kind: "heatpump", at: p.at, name: p.name, pump: p.pump }); + for (const m of media) cards.push({ kind: "media", at: { ...m.at, y: m.at.y + 0.5 }, media: m }); + } + if (JSON.stringify(cards) !== JSON.stringify(this._liveCards)) this._liveCards = cards; + v.setLiveAnchors( + cards.map((c) => c.at), + cards.length ? (i, x, y, visible) => this.placeLhCard(i, x, y, visible) : null, + ); + } + + /** Called by the viewer after every frame: moves a card to its point without a Lit render. */ + private placeLhCard(i: number, x: number, y: number, visible: boolean): void { + const el = this.renderRoot.querySelector(`.live-card[data-i="${i}"]`); + if (!el) return; + el.dataset.x = String(x); + el.dataset.y = String(y); + el.style.visibility = visible ? "visible" : "hidden"; + // the last card of the frame: lay them all out so none covers another + if (i === this._liveCards.length - 1) unstackLhCards(this.renderRoot); + } + + private toggleHouseFold(): void { + this._houseFolded = !this._houseFolded; + try { + localStorage.setItem("nextfloor.house_card_folded", this._houseFolded ? "1" : "0"); + } catch { + // private mode: the choice lasts for this page only + } + } + + private toggleLhCards(): void { + this._liveCardOn = !this._liveCardOn; + try { + localStorage.setItem("nextfloor.cards", this._liveCardOn ? "1" : "0"); + } catch { + // private mode: the choice lasts for this page only + } + this.syncDevices(true); + } + + /** Top left: the clock there, with the own sensors and the energy bar below it instead of under it. */ + private renderTopLeft() { + const bar = this.clean ? nothing : this.renderLhEnergy(); + const forecast = this.renderForecast("top_left"); + if ((this.clock !== "top_left" && forecast === nothing) || !this.hass) return bar; + return html`
    ${this.clock === "top_left" ? this.renderClock(true) : nothing}${bar}${forecast}
    `; + } + + /** NextFloor's energy bar: what the house makes, uses, stores and trades, and the switches for flows and cards. */ + private renderLhEnergy() { + const own = this.ownSensors(); + const e = this._liveEnergy?.summary; + const energy = !!e && !this.roomId && this.showEnergy && !!this.hass && !(e.consumption === null && e.grid === null && e.solar === null && e.battery === null); + if (!energy) return own.length ? html`
    ${own}
    ` : nothing; + const t = (k: Parameters[1]) => translate(this.hass, k); + const items: { cls: string; label: string; value: string }[] = []; + if (e.solar !== null) items.push({ cls: "solar", label: t("energy_solar"), value: formatPower(this.hass, e.solar) }); + if (e.consumption !== null) items.push({ cls: "total", label: t("energy_consumption"), value: formatPower(this.hass, e.consumption) }); + if (e.rest !== undefined && e.rest !== null) items.push({ cls: "total", label: t("energy_rest"), value: formatPower(this.hass, e.rest) }); + if (e.battery !== null || e.soc !== null) { + const parts = [e.battery !== null ? formatPower(this.hass, Math.abs(e.battery)) : null, e.soc !== null ? `${Math.round(e.soc)} %` : null].filter(Boolean); + items.push({ cls: "battery", label: t("energy_battery"), value: parts.join(" · ") }); + } + if (e.grid !== null) { + const exporting = e.grid < 0; + items.push({ cls: exporting ? "export" : "grid", label: t(exporting ? "energy_grid_export" : "energy_grid_import"), value: formatPower(this.hass, Math.abs(e.grid)) }); + } + if (e.tariff) items.push({ cls: "tariff", label: t("energy_tariff"), value: `${formatNumber(this.hass, e.tariff.value, 3)} ${e.tariff.unit}`.trim() }); + if (this.building) for (const m of this.meterRows(this.building)) items.push({ cls: "meter", label: `${m.icon} ${m.label}`, value: m.value }); + return html`
    + ${this.liveCardsOn && this._liveCards.some((c) => c.kind === "house") ? nothing : items.map((i) => html`
    ${i.label}${i.value}
    `)} + ${this.flows !== null + ? nothing + : html``} + ${this.holograms !== null + ? nothing + : html``} + ${own} +
    `; + } + + /** The plan's own sensors at the top (outside temperature, the alarm…): their name and state; a tap opens their details. */ + private ownSensors() { + const ids = this.sensorBar && this.hass ? (this.building?.settings.status_entities ?? []) : []; + return ids + .filter((id) => this.hass.states[id]) + .map( + (id) => html``, + ); + } + + /** The map's credit while a real map lies under the plan (OpenStreetMap asks for it). */ + private renderMapCredit() { + const map = this.building?.settings.map; + if (!mapShown(map)) return nothing; + return html`${mapCredit(map).text}`; + } + + private renderLegend() { + if (this.heatMode === "wifi") return this.renderWifiLegend(); + if (this.heatMode === "none" || this.heatMode === "values") return nothing; + const summer = isSummer(new Date(), this.hass?.config?.latitude ?? 50); + const scale = scaleOf(this.heatMode, summer); + // temperatures are coloured in °C and shown in Home Assistant's unit + const temp = this.heatMode === "temperature"; + const lo = temp ? fromCelsius(this.hass, scale.stops[0][0]) : scale.stops[0][0]; + const hi = temp ? fromCelsius(this.hass, scale.stops[scale.stops.length - 1][0]) : scale.stops[scale.stops.length - 1][0]; + const unit = temp ? tempUnit(this.hass) : scale.unit; + const t = (k: Parameters[1]) => translate(this.hass, k); + return html`
    + ${t(`heat_${this.heatMode}`)}${this.heatMode === "temperature" ? html` ${t(summer ? "heat_summer" : "heat_winter")}` : nothing} + + ${formatNumber(this.hass, lo, 0)} ${unit}${formatNumber(this.hass, hi, 0)} ${unit} + ${this.heatValues.size ? nothing : html`${t("heat_none_found")}`} +
    `; + } + + /** The Wi-Fi map's legend: the access points, the devices they carry, and the network devices that are offline. */ + private renderWifiLegend() { + const hass = this.hass; + const b = this.building; + if (!hass || !b) return nothing; + const t = (k: I18nKey, v?: Record) => translate(hass, k, v); + const aps = b.floors.flatMap((f) => f.furniture.filter((m) => isAccessPoint(m.type)).map((m) => readAccessPoint(hass, this.furnitureLinks?.get(m.id)?.entity ?? this.furnitureLinks?.get(m.id)?.power ?? null))); + const known = aps.filter((a): a is NonNullable => !!a); + const clients = known.reduce((s, a) => s + (a.clients ?? 0), 0); + const placed = b.floors.flatMap((f) => f.placements.map((p) => hass.states[p.entity_id])); + const health = networkHealth(placed); + return html`
    + 📶 ${t("heat_wifi")} + ${t("wifi_aps", { n: aps.length, clients })} + ${health.online + health.offline.length ? html`${t("wifi_network", { online: health.online, offline: health.offline.length })}` : nothing} + ${health.offline.length ? html`${health.offline.slice(0, 4).join(", ")}` : nothing} + ${aps.length ? nothing : html`${t("wifi_none")}`} +
    `; + } + + /** The sky colour behind the house right now (night: deep blue-black, day: lighter and bluer, clouds in between). */ + private skyColor(): [number, number, number] { + const stage = STAGE[this.theme] ?? STAGE.neon; + const sky = this._sky; + return stage.night[0].map((v, i) => Math.round(v + (stage.day[0][i] - v) * sky)) as [number, number, number]; + } + + protected render() { + const sky = this._sky; + const mix = (a: number[], b: number[]) => `rgb(${a.map((v, i) => Math.round(v + (b[i] - v) * sky)).join(",")})`; + const stage = STAGE[this.theme] ?? STAGE.neon; + const style = `--nf-sky:${mix(stage.night[0], stage.day[0])};--nf-ground:${mix(stage.night[1], stage.day[1])}` + backdropStyle(this.building?.settings.backdrop); + return html`
    + ${this._error ? html`

    ${this._error}

    ` : nothing} ${this.renderTopLeft()} ${renderLhCards(this.hass, this.roomId || this.panelOpen ? [] : this._liveCards, (domain, service, entity, data) => this.hass?.callService(domain, service, { entity_id: entity, ...data }), { folded: this._houseFolded, toggle: () => this.toggleHouseFold() })} ${this.clean ? nothing : this.renderLegend()} ${this.renderMapCredit()} + ${this.renderAlerts()} ${this.renderAnnouncement()} ${this.clean ? nothing : html`${this.renderThumbs()} ${this.renderScenes()} ${this.renderFind()} ${this.renderCentral()}`} ${this.renderSwipe()} + ${this.renderMenu()} ${this.renderPlate()} ${this.renderEye()} ${this.renderLock()} ${this.renderWalk()} ${this.renderTravel()} ${this.renderClock()} ${this.renderToday()} ${this.renderLayers()} ${this.renderPluginWindow()} + ${this.showStats && this._stats + ? html`${this._stats.fps ? translate(this.hass, "stats_fps", { fps: this._stats.fps, ms: this._stats.worstMs }) : translate(this.hass, "stats_idle")} + ${this._stats.busy.length ? html`(${this._stats.busy.map((b) => translate(this.hass, `stats_busy_${b}` as I18nKey)).join(", ")})` : nothing} · + ${translate(this.hass, "stats", { calls: this._stats.calls, tris: this._stats.triangles.toLocaleString() })} · + ${translate(this.hass, this._stats.low ? "stats_low" : "stats_full", { r: formatNumber(this.hass, this._stats.pixelRatio, 2) })}` + : nothing} +
    `; + } + + static styles = [ + tokens, + controls, + liveCardStyles, + css` + :host { + display: block; + position: relative; + min-height: 200px; + } + .nf-alert-banner { + position: absolute; + left: 50%; + top: 10px; + transform: translateX(-50%); + display: flex; + justify-content: center; + gap: 6px; + max-width: calc(100% - 24px); + z-index: 4; + } + .nf-alert { + flex: 0 1 auto; + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + padding: 7px 14px 7px 12px; + border: 0; + border-left: 4px solid #ff3b4f; + border-radius: 12px; + background: var(--nf-chrome-solid); + color: var(--nf-text); + font: 600 13.5px var(--nf-font); + box-shadow: 0 0 18px rgba(255, 59, 79, 0.35); + cursor: pointer; + animation: nf-alert-pulse 1.2s ease-in-out infinite; + } + .nf-alert-water, + .nf-alert-window_rain { + border-left-color: #4fb3ff; + box-shadow: 0 0 18px rgba(79, 179, 255, 0.35); + } + .nf-alert-alarm_pending { + border-left-color: #ffb547; + box-shadow: 0 0 18px rgba(255, 181, 71, 0.35); + } + .nf-announcement { + position: absolute; + inset: 18% 8% auto; + z-index: 30; + display: flex; + align-items: center; + gap: 18px; + margin: 0 auto; + max-width: 860px; + padding: 22px 28px; + border: 1px solid color-mix(in srgb, var(--nf-accent) 55%, transparent); + border-radius: 22px; + background: var(--nf-chrome-solid); + color: var(--nf-text); + box-shadow: 0 0 40px color-mix(in srgb, var(--nf-accent) 35%, transparent), 0 18px 50px rgba(0, 0, 0, 0.45); + font: 700 clamp(22px, 3.6vw, 40px) / 1.25 var(--nf-font); + text-align: left; + cursor: pointer; + animation: nf-announce-in 0.35s ease-out; + } + .nf-announcement-icon { + font-size: 1.3em; + } + @keyframes nf-announce-in { + from { + opacity: 0; + transform: translateY(-12px) scale(0.98); + } + } + @media (prefers-reduced-motion: reduce) { + .nf-announcement { + animation: none; + } + } + /* a contact that stopped answering is a chore, not an emergency: no glow, no pulse */ + .nf-alert-contact_lost, + .nf-alert-own { + border-left-color: #ffb547; + box-shadow: none; + animation: none; + } + .nf-alert-more { + align-self: center; + color: var(--nf-muted); + font-size: 13px; + } + @keyframes nf-alert-pulse { + 50% { + box-shadow: 0 0 4px transparent; + } + } + .nf-has-alerts .nf-energy, + .nf-has-alerts .nf-topleft { + top: 58px; + } + /* the clock top left stacks above the sensor and energy bar rather than covering it */ + .nf-topleft { + position: absolute; + left: 12px; + top: 10px; + z-index: 3; + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 8px; + max-width: calc(100% - 24px); + pointer-events: none; + } + .nf-topleft > .nf-clock, + .nf-topleft > .nf-energy { + position: static; + max-width: 100%; + } + .nf-scenes { + position: absolute; + left: 60px; + right: 60px; + bottom: calc(10px + var(--nf-bottom-inset, 0px)); + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 6px; + z-index: 2; + pointer-events: none; + } + .nf-scenes .nf-chip { + pointer-events: auto; + } + @media (prefers-reduced-motion: reduce) { + .nf-alert, + .nf-dev-found { + animation: none; + } + } + .nf-stage { + position: absolute; + inset: 0; + overflow: hidden; + container-type: size; + container-name: nf; + background: radial-gradient(ellipse at 50% 35%, var(--nf-sky, var(--nf-bg2)), var(--nf-ground, var(--nf-bg)) 72%); + transition: background 2s ease; + } + .nf-canvas { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + display: block; + touch-action: none; + cursor: grab; + } + .nf-canvas:active { + cursor: grabbing; + } + :host([readable]) .nf-pin { + font-size: 15px; + padding: 6px 12px; + } + :host([readable]) .nf-pin-info small, + :host([readable]) .nf-pin-floor span { + font-size: 14px; + opacity: 1; + } + :host([readable]) .nf-pin-floor b { + font-size: 18px; + } + :host([readable]) .nf-dev { + font-size: 14px; + color: var(--nf-text); + } + .nf-note-pin { + background: #ffe58a; + color: #3a2e00; + border-color: #c9a400; + max-width: 260px; + overflow: hidden; + text-overflow: ellipsis; + } + .nf-note-pin.nf-note-due { + background: #ffa726; + color: #2a1600; + } + .nf-note-pin.nf-note-open { + white-space: normal; + text-align: left; + } + .nf-note-photo { + display: block; + width: 100%; + max-height: 200px; + object-fit: cover; + margin-top: 6px; + border-radius: 6px; + } + .nf-labels { + position: absolute; + inset: 0; + pointer-events: none; + } + .nf-pin-info { + display: grid; + gap: 1px; + text-align: center; + } + .nf-pin-info small { + font-size: 11px; + font-weight: 500; + opacity: 0.9; + font-variant-numeric: tabular-nums; + } + .nf-pin { + position: absolute; + left: 0; + top: 0; + pointer-events: auto; + font: 600 12.5px var(--nf-title-font); + color: var(--nf-text); + background: var(--nf-chrome); + border: 1px solid var(--nf-line); + border-radius: 10px; + padding: 5px 10px; + cursor: pointer; + white-space: nowrap; + backdrop-filter: blur(6px); + box-shadow: var(--nf-shadow); + } + .nf-pin-floor { + display: grid; + justify-items: start; + gap: 1px; + padding: 8px 14px; + border-radius: 12px; + background: var(--nf-accent); + color: var(--nf-accent-text); + border-color: transparent; + box-shadow: var(--nf-shadow); + } + .nf-pin-floor b { + font: 700 15px var(--nf-title-font); + letter-spacing: -0.01em; + } + .nf-pin-floor span { + font: 500 12px var(--nf-font); + opacity: 0.78; + } + .nf-dev { + position: absolute; + left: 0; + top: 0; + pointer-events: auto; + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px; + border-radius: 999px; + border: 1px solid var(--nf-line); + background: var(--nf-chrome); + color: var(--nf-muted); + font: 600 12px var(--nf-font); + cursor: pointer; + white-space: nowrap; + backdrop-filter: blur(6px); + touch-action: manipulation; + -webkit-user-select: none; + user-select: none; + transition: opacity 0.2s ease; + } + .nf-dev-icon { + display: grid; + place-items: center; + width: 24px; + height: 24px; + border-radius: 50%; + background: color-mix(in srgb, var(--nf-soft) 14%, transparent); + } + .nf-dev-text { + display: none; + padding-right: 6px; + color: var(--nf-text); + font-variant-numeric: tabular-nums; + max-width: 160px; + overflow: hidden; + text-overflow: ellipsis; + } + .nf-dev-watt:empty { + display: none; + } + .nf-dev-watt { + padding: 1px 6px 1px 0; + color: var(--nf-accent); + font-variant-numeric: tabular-nums; + font-weight: 700; + } + .nf-dev-on .nf-dev-watt { + color: #2a1a00; + } + .nf-person { + position: absolute; + left: 0; + top: 0; + display: grid; + place-items: center; + width: 30px; + height: 30px; + border-radius: 50%; + overflow: hidden; + background: #ff5fd2; + color: #fff; + font: 700 12px var(--nf-font); + box-shadow: + 0 0 0 2px rgba(255, 95, 210, 0.45), + 0 0 18px #ff5fd2; + pointer-events: auto; + } + .nf-person img { + width: 100%; + height: 100%; + object-fit: cover; + } + .nf-person[hidden] { + display: none; + } + .nf-no-room-names .nf-pin { + display: none !important; + } + /* tablet level: blur over the canvas and glowing shadows are expensive on weak GPUs */ + .nf-stage.nf-low { + transition: none; + } + .nf-low .nf-pin, + .nf-low .nf-dev, + .nf-low .nf-dev-on, + .nf-low .nf-energy-item, + .nf-low .nf-find input, + .nf-low .nf-find-list, + .nf-low .nf-find-btn, + .nf-low .nf-swipe, + .nf-low .nf-thumb { + backdrop-filter: none; + box-shadow: none; + transition: none; + } + .nf-thumbs { + position: absolute; + left: 12px; + top: 50%; + transform: translateY(-50%); + display: flex; + flex-direction: column; + gap: 8px; + max-height: calc(100% - 140px); + overflow-y: auto; + scrollbar-width: none; + z-index: 2; + } + .nf-thumb { + position: relative; + display: grid; + padding: 0; + width: 150px; + border: 1px solid var(--nf-line); + border-radius: 14px; + background: color-mix(in srgb, var(--nf-chrome) 70%, transparent); + color: var(--nf-text); + cursor: pointer; + overflow: hidden; + font: inherit; + box-shadow: var(--nf-shadow); + opacity: 0.72; + transition: opacity 0.15s, border-color 0.15s; + } + .nf-thumb:hover, + .nf-thumb[aria-pressed="true"] { + opacity: 1; + } + .nf-thumb[aria-pressed="true"] { + border-color: var(--nf-accent); + box-shadow: var(--nf-shadow), 0 0 0 2px var(--nf-accent); + } + .nf-thumb img { + display: block; + width: 100%; + aspect-ratio: 4 / 3; + } + .nf-thumb span { + position: absolute; + left: 8px; + bottom: 6px; + font-size: 12px; + font-weight: 600; + } + .nf-thumb img + span { + inset: auto 0 0 0; + padding: 18px 10px 6px; + color: #fff; + background: linear-gradient(transparent, rgba(0, 0, 0, 0.62)); + } + .nf-thumbs-fold { + align-self: flex-start; + width: 26px; + height: 22px; + padding: 0; + border: 1px solid var(--nf-line); + border-radius: 8px; + background: var(--nf-chrome); + color: var(--nf-text); + font-size: 11px; + cursor: pointer; + } + /* folded: plain floor buttons with their names, no pictures (D177) */ + .nf-thumbs-compact .nf-thumb { + padding: 6px 10px; + min-width: 0; + } + .nf-thumbs-compact .nf-thumb span { + position: static; + background: none; + padding: 0; + } + .nf-thumb-house { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 10px; + } + .nf-thumb-house span { + position: static; + text-shadow: none; + } + /* a low stage (a card of 420 px): the pictures start under the top bar and stop above the buttons at the bottom left */ + .nf-thumbs.nf-thumbs-short { + top: 52px; + transform: none; + max-height: calc(100% - 52px - 150px); + } + .nf-thumbs-small .nf-thumb { + width: 104px; + } + .nf-find-btn { + position: absolute; + left: 12px; + bottom: calc(10px + var(--nf-bottom-inset, 0px)); + width: 40px; + height: 40px; + display: grid; + place-items: center; + border: 0; + border-radius: 13px; + background: var(--nf-chrome); + color: var(--nf-text); + box-shadow: var(--nf-shadow); + cursor: pointer; + } + /* the star sits above the search button, its menu opens above it */ + .nf-central-btn { + position: absolute; + left: 12px; + bottom: calc(56px + var(--nf-bottom-inset, 0px)); + width: 40px; + height: 40px; + display: grid; + place-items: center; + border: 0; + border-radius: 13px; + background: var(--nf-chrome); + color: var(--nf-text); + box-shadow: var(--nf-shadow); + cursor: pointer; + z-index: 3; + } + .nf-central-on { + color: var(--nf-accent); + } + .nf-central { + position: absolute; + left: 12px; + bottom: calc(104px + var(--nf-bottom-inset, 0px)); + width: min(320px, calc(100% - 24px)); + max-height: calc(100% - 140px); + overflow-y: auto; + box-sizing: border-box; + display: flex; + flex-direction: column; + gap: 8px; + padding: 12px 14px; + border: 1px solid var(--nf-line); + border-radius: 16px; + background: var(--nf-chrome); + color: var(--nf-text); + box-shadow: var(--nf-shadow); + backdrop-filter: blur(10px); + z-index: 4; + } + .nf-central > b { + font-size: 12px; + letter-spacing: 0.08em; + text-transform: uppercase; + opacity: 0.7; + } + .nf-central-row { + display: grid; + grid-template-columns: 1fr auto auto; + gap: 6px; + align-items: center; + } + .nf-central-row small { + opacity: 0.6; + } + .nf-central .nf-btn { + min-width: 64px; + } + .nf-central-armed { + background: #ff8a3d !important; + color: #1a0d00 !important; + } + .nf-central-favs { + display: flex; + flex-wrap: wrap; + gap: 6px; + } + .nf-own-btn { + display: inline-flex; + align-items: center; + gap: 6px; + } + .nf-own-btn ha-icon { + --mdc-icon-size: 18px; + } + .nf-central-hint { + margin: 0; + font-size: 13px; + opacity: 0.7; + } + .nf-layers { + position: absolute; + top: 12px; + left: 50%; + transform: translateX(-50%); + display: flex; + gap: 6px; + z-index: 3; + } + .nf-has-alerts .nf-layers { + top: 58px; + } + /* top right: "Today" and the forecast below it, one column */ + .nf-right-col { + position: absolute; + top: 12px; + right: 12px; + width: min(280px, calc(100% - 24px)); + max-height: calc(100% - 140px); + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 8px; + z-index: 3; + pointer-events: none; + } + .nf-right-col > * { + pointer-events: auto; + } + .nf-has-alerts .nf-right-col { + top: 58px; + } + /* "Today": the day's appointments and bins, folds to its title */ + .nf-today { + width: 100%; + min-height: 0; + overflow-y: auto; + box-sizing: border-box; + padding: 8px 12px 10px; + border-radius: 16px; + border: 1px solid var(--nf-line); + background: var(--nf-chrome); + box-shadow: var(--nf-shadow); + backdrop-filter: blur(10px); + color: var(--nf-text); + z-index: 3; + } + .nf-low :is(.nf-today, .nf-forecast) { + backdrop-filter: none; + } + .nf-today-day { + display: block !important; + margin-top: 4px; + font-size: 12px; + font-weight: 600; + color: var(--nf-muted); + } + /* the forecast: a row per day */ + .nf-forecast { + box-sizing: border-box; + flex: none; + padding: 6px 12px; + border-radius: 16px; + border: 1px solid var(--nf-line); + background: var(--nf-chrome); + box-shadow: var(--nf-shadow); + backdrop-filter: blur(10px); + color: var(--nf-text); + pointer-events: auto; + } + .nf-forecast ul { + list-style: none; + margin: 0; + padding: 0; + display: grid; + grid-template-columns: auto auto auto auto; + column-gap: 10px; + row-gap: 2px; + align-items: baseline; + font-size: 13px; + } + .nf-forecast li { + display: contents; + } + .nf-fc-day { + color: var(--nf-muted); + } + .nf-fc-temp { + font-variant-numeric: tabular-nums; + white-space: nowrap; + } + .nf-fc-temp small { + color: var(--nf-muted); + } + .nf-fc-rain { + font-size: 12px; + color: var(--nf-soft); + white-space: nowrap; + } + .nf-today-folded { + width: auto; + align-self: flex-end; + padding-bottom: 8px; + } + .nf-today-head { + display: flex; + gap: 8px; + align-items: baseline; + width: 100%; + padding: 0; + border: 0; + background: none; + color: inherit; + font: inherit; + cursor: pointer; + text-align: left; + } + .nf-today-head span { + font-size: 12px; + color: var(--nf-muted); + } + .nf-today ul { + list-style: none; + margin: 8px 0 0; + padding: 0; + display: grid; + gap: 6px; + } + .nf-today li { + display: grid; + grid-template-columns: 44px 1fr; + gap: 8px; + align-items: baseline; + font-size: 14px; + } + .nf-today time { + font-variant-numeric: tabular-nums; + color: var(--nf-accent); + font-weight: 600; + } + .nf-today small { + display: block; + font-size: 11px; + color: var(--nf-muted); + } + .nf-today-past { + opacity: 0.45; + } + .nf-today-none { + margin: 6px 0 0; + font-size: 13px; + color: var(--nf-muted); + } + /* opened from the start on a wall tablet: a size larger, easy to hit */ + .nf-central-big { + width: min(420px, calc(100% - 24px)); + font-size: 16px; + } + .nf-central-big .nf-chip, + .nf-central-big .nf-btn { + min-height: 44px; + padding: 8px 16px; + font-size: 15px; + } + .nf-own-btn[aria-pressed="true"] { + border-color: var(--nf-accent); + color: var(--nf-accent); + box-shadow: 0 0 12px color-mix(in srgb, var(--nf-accent) 45%, transparent); + } + .nf-low .nf-central { + backdrop-filter: none; + } + /* the eye sits beside the search button; alone in the corner once the view is clean */ + .nf-travel-btn { + position: absolute; + left: 188px; + bottom: calc(10px + var(--nf-bottom-inset, 0px)); + width: 36px; + height: 36px; + padding: 0; + border-radius: 50%; + border: 1px solid rgba(160, 240, 255, 0.35); + background: rgba(8, 16, 34, 0.7); + color: var(--nf-text); + font-size: 14px; + cursor: pointer; + z-index: 4; + } + .nf-travel { + position: absolute; + left: 50%; + bottom: calc(62px + var(--nf-bottom-inset, 0px)); + transform: translateX(-50%); + width: min(860px, calc(100% - 24px)); + display: flex; + align-items: center; + gap: 8px; + padding: 8px 10px; + border-radius: 18px; + background: rgba(8, 16, 34, 0.82); + box-shadow: 0 6px 22px rgba(0, 0, 0, 0.4); + color: var(--nf-text); + z-index: 5; + flex-wrap: wrap; + } + .nf-travel button, + .nf-travel select { + min-height: 32px; + border: 0; + border-radius: 999px; + padding: 0 10px; + background: rgba(127, 127, 127, 0.16); + color: inherit; + font: inherit; + font-size: 13px; + cursor: pointer; + } + .nf-travel select option { + color: #111; + } + .nf-travel .nf-travel-play { + width: 36px; + padding: 0; + background: var(--nf-accent); + color: #041018; + } + .nf-travel-span[aria-pressed="true"] { + box-shadow: inset 0 0 0 1px var(--nf-accent); + color: var(--nf-accent); + } + .nf-travel-live { + color: #ff5a6b !important; + } + .nf-travel-when { + min-width: 92px; + font-variant-numeric: tabular-nums; + font-size: 14px; + } + .nf-travel-track { + position: relative; + flex: 1 1 220px; + height: 28px; + } + .nf-travel-track svg { + position: absolute; + inset: 9px 0; + width: 100%; + height: 10px; + fill: var(--nf-accent); + opacity: 0.55; + pointer-events: none; + } + .nf-travel-track input { + position: absolute; + inset: 0; + width: 100%; + margin: 0; + background: transparent; + accent-color: var(--nf-accent); + } + .nf-walk-btn { + position: absolute; + left: 144px; + bottom: calc(10px + var(--nf-bottom-inset, 0px)); + width: 36px; + height: 36px; + display: grid; + place-items: center; + padding: 0; + border-radius: 50%; + border: 1px solid rgba(160, 240, 255, 0.35); + background: rgba(8, 16, 34, 0.7); + color: var(--nf-text); + font-size: 16px; + cursor: pointer; + z-index: 4; + } + .nf-walk-on { + color: #041018; + background: var(--nf-accent); + border-color: var(--nf-accent); + } + .nf-stick { + position: absolute; + right: 28px; + bottom: calc(70px + var(--nf-bottom-inset, 0px)); + width: 120px; + height: 120px; + border-radius: 50%; + background: rgba(8, 16, 34, 0.45); + border: 1px solid rgba(160, 240, 255, 0.35); + display: grid; + place-items: center; + touch-action: none; + z-index: 4; + } + .nf-stick span { + width: 52px; + height: 52px; + border-radius: 50%; + background: var(--nf-accent); + opacity: 0.85; + pointer-events: none; + } + .nf-walk-hint { + position: absolute; + left: 50%; + top: 12px; + transform: translateX(-50%); + margin: 0; + padding: 6px 12px; + border-radius: 999px; + background: rgba(8, 16, 34, 0.6); + color: var(--nf-muted); + font-size: 12px; + pointer-events: none; + z-index: 3; + } + .nf-lock3d { + position: absolute; + left: 100px; + bottom: calc(10px + var(--nf-bottom-inset, 0px)); + width: 36px; + height: 36px; + display: grid; + place-items: center; + padding: 0; + border-radius: 50%; + border: 1px solid rgba(160, 240, 255, 0.35); + background: rgba(8, 16, 34, 0.7); + color: var(--nf-text); + cursor: pointer; + z-index: 4; + } + .nf-lock3d-on { + color: #041018; + background: var(--nf-accent); + border-color: var(--nf-accent); + } + .nf-plugin-window { + position: absolute; + right: 12px; + bottom: 12px; + z-index: 6; + width: min(420px, calc(100% - 24px)); + border-radius: 12px; + overflow: hidden; + background: rgba(10, 16, 22, 0.92); + border: 1px solid rgba(127, 208, 255, 0.35); + box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45); + color: #e6f4fb; + } + .nf-pw-head { + display: flex; + align-items: center; + gap: 8px; + padding: 6px 8px 6px 12px; + font-size: 13px; + } + .nf-pw-head span { + flex: 1; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + .nf-pw-close { + border: 0; + background: transparent; + color: inherit; + font-size: 16px; + cursor: pointer; + padding: 2px 6px; + } + .nf-pw-body { + line-height: 0; + } + .nf-clock { + position: absolute; + z-index: 3; + display: flex; + flex-direction: column; + padding: 8px 14px; + border-radius: 16px; + background: rgba(8, 16, 34, 0.55); + color: var(--nf-text); + pointer-events: none; + line-height: 1.1; + } + .nf-clock b { + font-size: clamp(28px, 6cqmin, 64px); + font-weight: 600; + font-variant-numeric: tabular-nums; + letter-spacing: -0.02em; + } + .nf-clock span { + font-size: clamp(12px, 1.8cqmin, 18px); + color: var(--nf-muted); + } + .nf-clock-top_left { + left: 16px; + top: 16px; + } + .nf-clock-top_right { + right: 16px; + top: 16px; + align-items: flex-end; + } + .nf-clock-bottom_left { + left: 16px; + bottom: calc(60px + var(--nf-bottom-inset, 0px)); + } + .nf-clock-bottom_right { + right: 16px; + bottom: calc(60px + var(--nf-bottom-inset, 0px)); + align-items: flex-end; + } + .nf-eye { + position: absolute; + left: 56px; + bottom: calc(10px + var(--nf-bottom-inset, 0px)); + width: 36px; + height: 36px; + display: grid; + place-items: center; + padding: 0; + border-radius: 50%; + border: 1px solid rgba(160, 240, 255, 0.35); + background: rgba(8, 16, 34, 0.7); + color: var(--nf-text); + cursor: pointer; + z-index: 4; + } + /* in the clean view the button sits at the top: a tablet's taskbar or gesture bar covers the bottom edge and the button was lost there (#75) */ + .nf-eye-clean { + left: auto; + bottom: auto; + right: calc(12px + env(safe-area-inset-right, 0px)); + top: calc(12px + env(safe-area-inset-top, 0px)); + opacity: 0.55; + } + .nf-eye:hover, + .nf-eye-clean:hover { + opacity: 1; + } + .nf-find { + position: absolute; + left: 12px; + bottom: calc(10px + var(--nf-bottom-inset, 0px)); + width: min(340px, calc(100% - 24px)); + display: flex; + flex-direction: column-reverse; + gap: 6px; + z-index: 3; + } + .nf-find input { + box-sizing: border-box; + width: 100%; + height: 42px; + padding: 0 42px 0 14px; + border: 1px solid var(--nf-line); + border-radius: 14px; + background: var(--nf-chrome); + color: var(--nf-text); + font: inherit; + font-size: 15px; + box-shadow: var(--nf-shadow); + backdrop-filter: blur(8px); + } + .nf-find-close { + position: absolute; + right: 6px; + bottom: 6px; + width: 30px; + height: 30px; + border: 0; + border-radius: 10px; + background: none; + color: var(--nf-muted); + cursor: pointer; + } + .nf-find-list { + display: grid; + padding: 6px; + border-radius: 14px; + background: var(--nf-chrome); + box-shadow: var(--nf-shadow); + backdrop-filter: blur(8px); + } + .nf-find-list button { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 10px; + border: 0; + border-radius: 10px; + background: none; + color: var(--nf-text); + text-align: left; + font: inherit; + cursor: pointer; + } + .nf-find-list button:hover, + .nf-find-list button:focus-visible { + background: rgba(127, 127, 127, 0.14); + } + .nf-find-list b { + display: block; + font-weight: 600; + } + .nf-find-list small, + .nf-find-list p { + color: var(--nf-muted); + font-size: 12px; + margin: 0; + } + .nf-find-list p { + padding: 8px 10px; + } + .nf-find-icon { + display: grid; + place-items: center; + width: 30px; + height: 30px; + border-radius: 10px; + background: rgba(127, 127, 127, 0.15); + flex: none; + } + .nf-find-icon svg { + width: 16px; + height: 16px; + } + .nf-swipe { + position: absolute; + transform: translate(-50%, calc(-100% - 28px)); + display: grid; + grid-template-columns: auto auto; + align-items: center; + gap: 2px 12px; + padding: 8px 12px; + border-radius: 14px; + background: var(--nf-chrome); + box-shadow: var(--nf-shadow); + pointer-events: none; + white-space: nowrap; + z-index: 4; + } + .nf-swipe span { + font-size: 12px; + color: var(--nf-muted); + } + .nf-swipe b { + grid-row: 2; + font: 700 22px var(--nf-title-font); + } + .nf-swipe i { + grid-row: 1 / 3; + grid-column: 2; + position: relative; + width: 10px; + height: 44px; + border-radius: 5px; + background: rgba(127, 127, 127, 0.25); + overflow: hidden; + } + .nf-swipe em { + position: absolute; + left: 0; + right: 0; + bottom: 0; + background: var(--nf-warm); + } +.nf-plate-menu { + position: absolute; + z-index: 6; + display: flex; + flex-direction: column; + gap: 4px; + min-width: 220px; + padding: 6px; + border-radius: 16px; + background: var(--nf-bg2, #1c2233); + box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45); + } + .nf-plate-menu button { + display: grid; + grid-template-columns: 24px 1fr auto; + align-items: center; + gap: 8px; + min-height: 42px; + padding: 0 10px; + border: 0; + border-radius: 12px; + background: none; + color: var(--nf-text, #e8eeff); + font: inherit; + text-align: left; + cursor: pointer; + } + .nf-plate-menu button:hover { + background: rgba(127, 127, 127, 0.14); + } + .nf-plate-menu button.on b { + background: var(--nf-accent, #37e0ff); + color: #041018; + } + .nf-plate-menu b { + display: grid; + place-items: center; + width: 24px; + height: 24px; + border-radius: 50%; + background: rgba(127, 127, 127, 0.2); + font-size: 12px; + } + .nf-plate-menu i { + font-style: normal; + color: var(--nf-muted, #9aa5bd); + font-size: 13px; + } + .nf-menu-backdrop { + position: absolute; + inset: 0; + z-index: 5; + } + .nf-through { + position: absolute; + inset: 0; + z-index: 4; + pointer-events: none; + } + /* the camera wall: a glass sheet over the scene with every camera's picture */ + .nf-wall { + position: absolute; + inset: 56px 12px calc(var(--nf-bottom-inset, 0px) + 12px); + z-index: 5; + display: flex; + flex-direction: column; + gap: 8px; + padding: 10px 12px; + border-radius: 16px; + background: rgba(8, 16, 34, 0.86); + border: 1px solid rgba(160, 240, 255, 0.4); + box-shadow: var(--nf-shadow); + overflow: auto; + } + .nf-wall-head { + display: flex; + align-items: center; + justify-content: space-between; + font-weight: 600; + color: var(--nf-text); + } + .nf-wall-head .nf-wall-title { + flex: 1; + text-align: center; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + padding: 0 8px; + } + .nf-wall-title b { + color: #ff6b6b; + font-weight: 600; + } + .nf-wall-tools { + display: flex; + gap: 6px; + } + .nf-wall-big { + flex: 1; + min-height: 0; + display: flex; + align-items: center; + justify-content: center; + border-radius: 12px; + overflow: hidden; + background: #0a1426; + } + .nf-wall-big img { + width: 100%; + height: 100%; + object-fit: contain; + } + /* the stream player: a bare card, as wide as the sheet allows for a 16:9 picture */ + .nf-wall-big > hui-picture-entity-card, + .nf-wall-big > hui-error-card { + width: min(100%, calc((100vh - 200px) * 16 / 9)); + --ha-card-background: transparent; + --ha-card-border-width: 0; + --ha-card-box-shadow: none; + } + .nf-wall-grid { + flex: 1; + display: grid; + align-content: safe center; + justify-content: center; + gap: 12px; + min-height: 0; + overflow-y: auto; + } + .nf-wall-cam { + position: relative; + padding: 0; + border: 1px solid rgba(160, 240, 255, 0.3); + border-radius: 12px; + overflow: hidden; + background: #0a1426; + cursor: pointer; + width: 100%; + height: 100%; + } + .nf-wall-cam img, + .nf-wall-none { + width: 100%; + height: 100%; + object-fit: cover; + display: flex; + align-items: center; + justify-content: center; + color: #8aa; + } + .nf-wall-seen { + border-color: rgba(255, 80, 90, 0.9); + box-shadow: 0 0 14px rgba(255, 60, 70, 0.5); + } + .nf-wall-name { + position: absolute; + left: 0; + right: 0; + bottom: 0; + padding: 4px 8px; + font-size: 12px; + text-align: left; + color: var(--nf-text); + background: linear-gradient(transparent, rgba(0, 0, 0, 0.7)); + } + .nf-wall-name b { + color: #ff6b6b; + font-weight: 600; + } + /* a lightning bolt of the weather layer lights up the whole stage for a moment */ + .live-flash::after { + content: ""; + position: absolute; + inset: 0; + z-index: 3; + background: radial-gradient(circle at 50% 20%, rgba(235, 242, 255, 0.55), rgba(200, 215, 255, 0.18) 70%); + pointer-events: none; + } + .nf-through-img { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: cover; + opacity: var(--nf-blend); + } + .nf-through-bar { + position: absolute; + left: 50%; + bottom: calc(var(--nf-bottom-inset, 0px) + 14px); + transform: translateX(-50%); + display: flex; + align-items: center; + gap: 12px; + max-width: calc(100% - 32px); + padding: 8px 10px 8px 16px; + border-radius: 999px; + background: var(--nf-chrome); + backdrop-filter: blur(12px); + border: 1px solid var(--nf-line); + pointer-events: auto; + } + .nf-through-name { + font-weight: 600; + white-space: nowrap; + } + /* a small note that the picture is a still, so nobody wonders why it does not move */ + .nf-still { + font-size: 11px; + font-weight: 400; + opacity: 0.65; + white-space: nowrap; + margin-left: 6px; + } + .nf-through-bar input[type="range"] { + width: 140px; + accent-color: var(--nf-accent); + } + .nf-through-on :is(.nf-pin, .nf-dev, .nf-energy, .nf-legend, .nf-thumbs, .nf-scenes, .nf-find-btn, .nf-stats) { + display: none; + } + nf-quick-menu { + position: absolute; + z-index: 6; + } + .nf-dev-found { + animation: nf-found 0.6s ease-in-out 4; + } + @keyframes nf-found { + 50% { + scale: 1.35; + filter: drop-shadow(0 0 12px var(--nf-accent)); + } + } + .nf-map-credit { + position: absolute; + right: 8px; + bottom: 4px; + z-index: 2; + padding: 1px 6px; + border-radius: 6px; + background: color-mix(in srgb, var(--nf-chrome) 80%, transparent); + color: var(--nf-soft); + font-size: 10px; + text-decoration: none; + } + .nf-legend { + position: absolute; + left: 12px; + /* above the star button */ + bottom: calc(104px + var(--nf-bottom-inset, 0px)); + display: grid; + gap: 4px; + min-width: 180px; + padding: 8px 11px; + border-radius: 12px; + background: var(--nf-chrome); + box-shadow: var(--nf-shadow); + font-size: 12px; + pointer-events: none; + } + .nf-legend-bar { + height: 8px; + border-radius: 4px; + } + .nf-legend-range { + display: flex; + justify-content: space-between; + color: var(--nf-muted); + font-variant-numeric: tabular-nums; + } + .nf-legend-none { + color: var(--nf-warm); + } + .nf-energy { + position: absolute; + left: 12px; + top: 10px; + display: flex; + flex-wrap: wrap; + gap: 6px; + max-width: calc(100% - 24px); + pointer-events: none; + } + .nf-energy-item { + display: grid; + padding: 5px 11px 6px; + border-radius: 12px; + background: var(--nf-chrome); + border-left: 3px solid var(--nf-line); + box-shadow: var(--nf-shadow); + backdrop-filter: blur(6px); + font-variant-numeric: tabular-nums; + } + .nf-energy-item span { + font-size: 11px; + color: var(--nf-muted); + } + .nf-energy-item b { + font: 700 15px var(--nf-title-font); + } + .nf-energy-total { + border-left-color: #6fd8ff; + } + .nf-energy-grid { + border-left-color: var(--nf-accent); + } + .nf-energy-export, + .nf-energy-solar { + border-left-color: #ffc633; + } + .nf-energy-battery { + border-left-color: #59ff8c; + } + .nf-flow-toggle { + pointer-events: auto; + cursor: pointer; + border: 0; + border-left: 3px solid var(--nf-line); + color: inherit; + text-align: left; + font: inherit; + } + .nf-own-sensor { + pointer-events: auto; + cursor: pointer; + border: 0; + border-left: 3px solid var(--nf-accent); + color: inherit; + text-align: left; + font: inherit; + max-width: 220px; + } + .nf-own-sensor span, + .nf-own-sensor b { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + .nf-flow-toggle[aria-pressed="true"] { + border-left-color: var(--nf-accent); + } + .nf-flow-toggle span { + display: none; + } + .nf-flow-toggle b { + opacity: 0.4; + filter: grayscale(1); + } + .nf-flow-toggle[aria-pressed="true"] b { + opacity: 1; + filter: none; + } + .nf-energy-tariff { + border-left-color: #b98cff; + } + /* narrow stages (portrait tablets, phones): the energy values scroll in one row */ + @container nf (max-width: 900px) { + .nf-energy { + flex-wrap: nowrap; + overflow-x: auto; + scrollbar-width: none; + pointer-events: auto; + } + .nf-legend { + bottom: auto; + top: 62px; + } + .nf-has-alerts .nf-legend { + top: 110px; + } + } + /* a room sheet covers the lower half: the view's own controls step aside */ + @container nf ((max-width: 700px) or ((orientation: portrait) and (max-width: 1000px))) { + .nf-panel-open :is(.nf-find-btn, .nf-find, .nf-thumbs, .nf-legend, .nf-stats, .nf-scenes) { + display: none; + } + } + @media (pointer: coarse) { + .nf-find-close { + width: 40px; + height: 40px; + right: 1px; + bottom: 1px; + } + .nf-dev { + padding: 6px; + } + .nf-pin { + padding: 8px 12px; + } + } + .nf-dev-full .nf-dev-text { + display: inline; + } + .nf-dev-name:empty { + display: none; + } + .nf-dev-name { + position: absolute; + top: calc(100% + 3px); + left: 50%; + transform: translateX(-50%); + max-width: 140px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + padding: 1px 6px; + border-radius: 6px; + font-size: 10.5px; + font-weight: 600; + line-height: 1.35; + /* a fixed dark plate, so a fixed light text: the theme text colour can be dark (day themes, pins that are on) */ + color: #f2f5fb; + background: rgba(10, 16, 32, 0.72); + pointer-events: none; + } + .nf-dev-sel { + outline: 2px solid var(--nf-accent); + outline-offset: 2px; + } + .nf-dev-on { + color: #2a1a00; + border-color: transparent; + background: var(--nf-glow, var(--nf-warm)); + box-shadow: 0 0 16px var(--nf-glow, var(--nf-warm)); + } + .nf-dev-on .nf-dev-icon { + background: color-mix(in srgb, var(--nf-text) 28%, transparent); + } + .nf-dev-on .nf-dev-text { + color: #2a1a00; + } + .nf-dev-na { + opacity: 0.45; + } + .nf-dev-dim { + opacity: 0.35; + } + .nf-dev[hidden], + .nf-pin[hidden] { + display: none; + } + .nf-pin-active { + background: var(--nf-accent); + color: var(--nf-accent-text); + border-color: transparent; + box-shadow: var(--nf-shadow); + } + .nf-stats b { + color: var(--nf-accent); + font-weight: 700; + } + .nf-stats { + padding: 4px 9px; + border-radius: 8px; + background: var(--nf-chrome); + position: absolute; + right: 10px; + bottom: calc(8px + var(--nf-bottom-inset, 0px)); + font-size: 11.5px; + color: var(--nf-muted); + font-variant-numeric: tabular-nums; + pointer-events: none; + } + .nf-error { + position: absolute; + inset: auto 16px 16px; + color: var(--nf-danger); + } + `, + ]; +} + +if (!customElements.get("nf-view3d")) customElements.define("nf-view3d", NfView3d); + +/** Power as "850 W" or "1,2 kW". */ +function formatPower(hass: HomeAssistant | undefined, w: number): string { + return Math.abs(w) >= 1000 ? `${formatNumber(hass, w / 1000, 1)} kW` : `${Math.round(w)} W`; +} + +/** Marker height above furniture: in front of a screen, above wall units, else just above the top. */ +function markerHeight(f: Furniture): number { + if (f.type === "tv_board") return f.h + 0.9; + // wall TV and wall cabinet: above the item (their height above the floor comes from mountBase) + if (f.type === "tv_wall" || f.type === "kitchen_wall") return f.h + 0.25; + return f.h + 0.35; +} + + +/** The text under a fan's pin: its speed in per cent while it runs, its state otherwise. */ +function fanText(hass: HomeAssistant, st: HassEntity): string { + const pct = st.attributes.percentage; + return st.state === "on" && typeof pct === "number" ? `${Math.round(pct)} %` : stateText(hass, st); +} diff --git a/frontend/src/components/view3d/live-inputs.test.ts b/frontend/src/components/view3d/live-inputs.test.ts new file mode 100644 index 0000000..c9fb399 --- /dev/null +++ b/frontend/src/components/view3d/live-inputs.test.ts @@ -0,0 +1,55 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, entity, floorWith, hassOf } from "../../entities/fixtures.ts"; +import type { Building, Furniture } from "../../model.ts"; +import { liveScreens, readSun, roofWindowStates, skyLightness } from "./live-inputs.ts"; + +const tv = (extra: Partial = {}): Furniture => ({ id: "tv", type: "tv_board", x: 2, z: 2, rotation: 0, w: 1.4, d: 0.4, h: 0.5, variant: null, ...extra }); +const house = (furniture: Furniture[], placements: { entity_id: string; x: number; z: number; y: null }[] = [], roofWindows: unknown[] = []): Building => + ({ version: 1, floors: [floorWith([box("r", 0, 0, 5, 5)], { id: "g", furniture, placements })], settings: { roof: { type: "none", pitch: 35, overhang: 0, windows: roofWindows } }, energy: {}, presence: [] }) as unknown as Building; + +test("a screen shows what its linked player plays, with title, artist and app", () => { + const hass = hassOf([entity("media_player.tv", "playing", { media_title: "Blue Train", media_artist: "Coltrane", app_name: "Spotify", entity_picture: "/pic" })]); + const [screen] = liveScreens(hass, house([tv()]), new Map([["tv", { entity: "media_player.tv", power: null }]]) as never); + assert.deepEqual([screen.title, screen.subtitle, screen.app, screen.picture, screen.playing, screen.floorId], ["Blue Train", "Coltrane", "Spotify", "/pic", true, "g"]); +}); + +test("a player placed beside the screen counts, a far one does not, and idle players show nothing", () => { + const hass = hassOf([entity("media_player.near", "paused", { media_title: "x" }), entity("media_player.far", "playing"), entity("media_player.off", "idle")]); + const near = house([tv()], [{ entity_id: "media_player.near", x: 2.5, z: 2, y: null }, { entity_id: "media_player.far", x: 9, z: 9, y: null }]); + assert.deepEqual(liveScreens(hass, near, null).map((s) => [s.title, s.playing]), [["x", false]]); + assert.deepEqual(liveScreens(hass, house([tv()], [{ entity_id: "media_player.off", x: 2, z: 2, y: null }]), null), []); + assert.deepEqual(liveScreens(hass, house([{ ...tv(), type: "sofa" }]), null), [], "only furniture with a screen"); +}); + +test("a TV that only reports 'on' shows its channel or input, a bare 'on' shows nothing", () => { + const live = entity("media_player.tv", "on", { device_class: "tv", media_title: "ITV1 HD", source: "TV/HDMI", entity_picture: "/logo" }); + const [screen] = liveScreens(hassOf([live]), house([tv()]), new Map([["tv", { entity: "media_player.tv", power: null }]]) as never); + assert.deepEqual([screen.title, screen.app, screen.picture, screen.playing], ["ITV1 HD", "TV/HDMI", "/logo", true]); + const bare = hassOf([entity("media_player.tv", "on", { device_class: "tv" })]); + assert.deepEqual(liveScreens(bare, house([tv()]), new Map([["tv", { entity: "media_player.tv", power: null }]]) as never), []); +}); + +test("a roof window motor sets the sash by its position, or open and closed by its state", () => { + const windows = [{ id: "a", face: "main:a", u: 0, v: 0, window: "cover.motor" }, { id: "b", face: "main:a", u: 0, v: 0, window: "cover.plain" }, { id: "c", face: "main:a", u: 0, v: 0, window: "none" }]; + const hass = hassOf([entity("cover.motor", "open", { current_position: 40 }), entity("cover.plain", "opening")]); + const states = roofWindowStates(hass, house([], [], windows)); + assert.equal(states.get("a")!.open, 0.4); + assert.equal(states.get("b")!.open, 1); + assert.equal(states.get("c")!.open, 0); + assert.equal(states.get("c")!.cover, 0); +}); + +test("the sun is read only when it reports both angles", () => { + assert.deepEqual(readSun(hassOf([entity("sun.sun", "above_horizon", { elevation: 30, azimuth: 200 })])), { elevation: 30, azimuth: 200 }); + assert.equal(readSun(hassOf([entity("sun.sun", "above_horizon", { elevation: 30 })])), null); + assert.equal(readSun(hassOf([])), null); +}); + +test("the sky is dark at night, full by day, and clouds take part of it", () => { + assert.equal(skyLightness(-10, 0), 0); + assert.equal(skyLightness(null, 0), 0); + assert.equal(skyLightness(30, 0), 1); + assert.equal(skyLightness(30, 1), 0.55); + assert.equal(skyLightness(4, 0), 0.5); +}); diff --git a/frontend/src/components/view3d/live-inputs.ts b/frontend/src/components/view3d/live-inputs.ts new file mode 100644 index 0000000..1da676e --- /dev/null +++ b/frontend/src/components/view3d/live-inputs.ts @@ -0,0 +1,106 @@ +// What the 3D view reads from Home Assistant each time something changed: the state of roof windows, which screens show what, +// which sprinklers water, and where the sun is. + +import { hasScreen, isActive, isUnavailable, openingState, type FurnitureLinks } from "../../devices.ts"; +import { appColor, isLive, showsSomething } from "../../live/media.ts"; +import type { Building, Floor, Furniture } from "../../model.ts"; +import type { HomeAssistant } from "../../types.ts"; +import { mountBase } from "../../packs.ts"; +import type { LiveScreenInput } from "../../viewer/viewer3d.ts"; +import type { SpraySpot } from "../../viewer/live-water.ts"; + +/** How far a lawn sprinkler reaches when its form does not say (m). */ +export const SPRAY_REACH = 3; + +/** Lawn sprinklers whose valve or switch is on now: where their nozzle is and how far they reach. */ +export function liveSprays(hass: HomeAssistant, building: Building, links: ReadonlyMap | null): SpraySpot[] { + const out: SpraySpot[] = []; + for (const floor of building.floors) { + for (const f of floor.furniture) { + if (!f.type.endsWith(":sprinkler")) continue; + const entity = links?.get(f.id)?.entity ?? null; + if (!entity || !isActive(hass.states[entity])) continue; + out.push({ id: f.id, at: { floorId: floor.id, x: f.x, y: mountBase(floor, f) + f.h, z: f.z }, reach: Math.min(15, Math.max(0.5, f.spray ?? SPRAY_REACH)) }); + } + } + return out; +} + +const real = (id: string | null | undefined): string | null => (id && id !== "none" ? id : null); + +export interface RoofWindowState { + open: number; + tilt: number; + cover: number; +} + +const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); + +/** + * The sash and blind of every roof window. They follow their contact and cover like windows do. A window motor sets the sash by its + * position (0 to 100), or fully open or closed by a plain state. + */ +export function roofWindowStates(hass: HomeAssistant, building: Building): Map { + const states = new Map(); + for (const w of building.settings.roof?.windows ?? []) { + const state = openingState(hass, { cover: real(w.cover), contact: real(w.contact), tilt: real(w.tilt) }, "window"); + const motorId = real(w.window); + const motor = motorId ? hass.states[motorId] : undefined; + let open = state.open; + if (motor && !isUnavailable(motor)) { + const position = motor.attributes.current_position; + open = typeof position === "number" ? clamp01(position / 100) : motor.state === "open" || motor.state === "opening" ? 1 : 0; + } + states.set(w.id, { open, tilt: state.tilt, cover: state.cover ?? 0 }); + } + return states; +} + +/** A media player placed right beside a screen counts as its player (an Apple TV next to the TV): within 2 m or the screen's width. */ +function playerBeside(floor: Floor, screen: Furniture): string | null { + const distance = (p: { x: number; z: number }) => Math.hypot(p.x - screen.x, p.z - screen.z); + const near = floor.placements.filter((p) => p.entity_id.startsWith("media_player.") && distance(p) < Math.max(2, screen.w)); + return near.sort((a, b) => distance(a) - distance(b))[0]?.entity_id ?? null; +} + +const text = (attributes: Record, key: string): string => (typeof attributes[key] === "string" ? (attributes[key] as string) : ""); + +/** What each TV or monitor shows right now: a screen linked to a media player (or with one beside it) that plays, is paused, or is a TV that is on with something showing. */ +export function liveScreens(hass: HomeAssistant, building: Building, links: ReadonlyMap | null): LiveScreenInput[] { + const screens: LiveScreenInput[] = []; + for (const floor of building.floors) { + for (const furniture of floor.furniture) { + if (!hasScreen(furniture.type)) continue; + const linked = links?.get(furniture.id)?.entity ?? null; + const player = linked?.startsWith("media_player.") ? linked : playerBeside(floor, furniture); + const state = player ? hass.states[player] : undefined; + if (!state || !showsSomething(state)) continue; + const attributes = state.attributes as Record; + const app = text(attributes, "app_name") || text(attributes, "source") || null; + screens.push({ + id: furniture.id, + furnitureId: furniture.id, + floorId: floor.id, + color: appColor(app), + title: text(attributes, "media_title") || text(attributes, "media_channel") || app || "", + subtitle: text(attributes, "media_artist") || text(attributes, "media_series_title") || text(attributes, "media_album_name"), + app, + picture: text(attributes, "entity_picture") || null, + playing: isLive(state), + ambilight: furniture.ambilight ?? 1, + }); + } + } + return screens; +} + +/** The sun's position, or null when it is not reported. */ +export function readSun(hass: HomeAssistant): { elevation: number; azimuth: number } | null { + const attributes = hass.states["sun.sun"]?.attributes; + return typeof attributes?.elevation === "number" && typeof attributes.azimuth === "number" ? { elevation: attributes.elevation, azimuth: attributes.azimuth } : null; +} + +/** How light the sky is: dark until the sun is 4° below the horizon, full from 12° above, and clouds take a good part of it. */ +export function skyLightness(elevation: number | null, cloud: number): number { + return (elevation === null ? 0 : clamp01((elevation + 4) / 16)) * (1 - 0.45 * cloud); +} diff --git a/frontend/src/components/view3d/own-taps.test.ts b/frontend/src/components/view3d/own-taps.test.ts new file mode 100644 index 0000000..1f528b7 --- /dev/null +++ b/frontend/src/components/view3d/own-taps.test.ts @@ -0,0 +1,30 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, floorWith } from "../../entities/fixtures.ts"; +import type { Building, Furniture } from "../../model.ts"; +import { ownTaps } from "./own-taps.ts"; + +const item = (id: string, extra: Partial = {}): Furniture => ({ id, type: "meter", x: 1, z: 1, rotation: 0, w: 0.4, d: 0.15, h: 0.5, variant: null, ...extra }); +const house = (furniture: Furniture[]): Building => + ({ version: 1, floors: [floorWith([box("r", 0, 0, 5, 5)], { id: "g", furniture })], settings: {}, energy: {}, presence: [] }) as unknown as Building; +const go = { action: "navigate", target: "/energy", data: null } as Furniture["tap"]; + +test("an item with its own tap keeps its pin, and the pin runs the action", () => { + const b = house([item("meter", { tap: go }), item("plain")]); + const { pins, bare } = ownTaps(b, [{ id: "sensor.grid_power", furnitureId: "meter" }, { id: "sensor.other", furnitureId: "plain" }, { id: "light.placed" }]); + assert.deepEqual([...pins], [["sensor.grid_power", "meter"]]); + assert.deepEqual(bare, []); +}); + +test("every pin of the item runs the action (a ceiling fan has two)", () => { + const b = house([item("fan", { type: "ceiling_fan", tap: go })]); + const { pins } = ownTaps(b, [{ id: "light.fan_light", furnitureId: "fan" }, { id: "fan.fan", furnitureId: "fan" }]); + assert.deepEqual([...pins.keys()], ["light.fan_light", "fan.fan"]); +}); + +test("an item without a pin of its own gets a plain one, an action left empty counts as none", () => { + const b = house([item("bowl", { type: "bowl", tap: go }), item("blank", { tap: { action: "" as never, target: null, data: null } })]); + const { pins, bare } = ownTaps(b, []); + assert.equal(pins.size, 0); + assert.deepEqual(bare.map(({ floor, item }) => [floor.id, item.id]), [["g", "bowl"]]); +}); diff --git a/frontend/src/components/view3d/own-taps.ts b/frontend/src/components/view3d/own-taps.ts new file mode 100644 index 0000000..b406b23 --- /dev/null +++ b/frontend/src/components/view3d/own-taps.ts @@ -0,0 +1,14 @@ +import type { Building, Floor, Furniture } from "../../model.ts"; + +/** + * Items with their own tap action keep what they show (their pin with its state, their glow); + * only a tap runs the action. `pins` maps each such item's pins to the item, `bare` lists the + * items without a pin of their own, which get a plain one to be found by. + */ +export function ownTaps(b: Building, markers: readonly { id: string; furnitureId?: string }[]): { pins: Map; bare: { floor: Floor; item: Furniture }[] } { + const items = b.floors.flatMap((floor) => floor.furniture.filter((f) => f.tap?.action).map((item) => ({ floor, item }))); + const tapped = new Set(items.map(({ item }) => item.id)); + const pins = new Map(markers.filter((m) => m.furnitureId && tapped.has(m.furnitureId)).map((m) => [m.id, m.furnitureId!])); + const pinned = new Set(pins.values()); + return { pins, bare: items.filter(({ item }) => !pinned.has(item.id)) }; +} diff --git a/frontend/src/components/view3d/room-toggle.test.ts b/frontend/src/components/view3d/room-toggle.test.ts new file mode 100644 index 0000000..575fbfb --- /dev/null +++ b/frontend/src/components/view3d/room-toggle.test.ts @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, entity, floorWith, hassOf } from "../../entities/fixtures.ts"; +import type { FurnitureLinks } from "../../devices.ts"; +import type { Furniture, Placement } from "../../model.ts"; +import { roomToggleLights, roomToggleMode } from "./room-toggle.ts"; + +const hass = hassOf([entity("light.ceiling", "off"), entity("light.coffee_plug", "on"), entity("light.lamp", "off")], { + "light.ceiling": { area_id: "kitchen" }, + "light.coffee_plug": { area_id: "kitchen" }, +}); +const room = box("k", 0, 0, 4, 4, "kitchen"); +const pin = { entity_id: "light.ceiling", x: 1, z: 1 } as Placement; +const lamp = { id: "f1", type: "lamp_ceiling", x: 2, z: 2 } as Furniture; +const floor = floorWith([room], { placements: [pin], furniture: [lamp] }); +const links = new Map([["f1", { entity: "light.lamp" } as FurnitureLinks]]); + +test("the card option wins, auto follows the plan, the default takes the whole area", () => { + assert.equal(roomToggleMode(undefined, undefined), "area"); + assert.equal(roomToggleMode("off", "auto"), "off"); + assert.equal(roomToggleMode("off", "plan"), "plan"); + assert.equal(roomToggleMode(null, "off"), "off"); +}); + +test("area mode adds the area's lights, plan mode only the placed lamps, off nothing", () => { + assert.deepEqual(roomToggleLights(hass, floor, room, links, new Set(), "area").sort(), ["light.ceiling", "light.coffee_plug", "light.lamp"]); + assert.deepEqual(roomToggleLights(hass, floor, room, links, new Set(), "plan").sort(), ["light.ceiling", "light.lamp"]); + assert.deepEqual(roomToggleLights(hass, floor, room, links, new Set(), "off"), []); +}); + +test("devices that ask first stay out", () => { + assert.deepEqual(roomToggleLights(hass, floor, room, links, new Set(["light.lamp"]), "plan"), ["light.ceiling"]); +}); diff --git a/frontend/src/components/view3d/room-toggle.ts b/frontend/src/components/view3d/room-toggle.ts new file mode 100644 index 0000000..87b9e95 --- /dev/null +++ b/frontend/src/components/view3d/room-toggle.ts @@ -0,0 +1,25 @@ +// Double tap on a room: which lights it switches, by the plan setting and the card option (#62). +import type { HomeAssistant } from "../../types.ts"; +import { kindOf, roomEntities, type FurnitureLinks } from "../../devices.ts"; +import { isLamp, pointInPolygon, type Floor, type Room } from "../../model.ts"; + +/** area: the lamps of the plan and every light of the room's area (default); plan: only the lamps of the plan; off: nothing. */ +export type RoomToggle = "area" | "plan" | "off"; + +/** The card option wins over the plan setting; "auto" or nothing follows the plan. */ +export function roomToggleMode(setting: RoomToggle | null | undefined, card: RoomToggle | "auto" | null | undefined): RoomToggle { + if (card === "area" || card === "plan" || card === "off") return card; + return setting === "plan" || setting === "off" ? setting : "area"; +} + +/** The lights a double tap on the room switches; devices that ask first stay out. */ +export function roomToggleLights(hass: HomeAssistant, floor: Floor, room: Room, links: ReadonlyMap, confirm: ReadonlySet, mode: RoomToggle): string[] { + if (mode === "off") return []; + const ids = new Set(mode === "area" ? roomEntities(hass, room).filter((id) => kindOf(id) === "light") : []); + for (const p of floor.placements) if (kindOf(p.entity_id) === "light" && pointInPolygon([p.x, p.z], room.points)) ids.add(p.entity_id); + for (const f of floor.furniture) { + const e = links.get(f.id)?.entity; + if (e && isLamp(f.type) && pointInPolygon([f.x, f.z], room.points)) ids.add(e); + } + return [...ids].filter((id) => !confirm.has(id)); +} diff --git a/frontend/src/components/view3d/watch-list.test.ts b/frontend/src/components/view3d/watch-list.test.ts new file mode 100644 index 0000000..e802807 --- /dev/null +++ b/frontend/src/components/view3d/watch-list.test.ts @@ -0,0 +1,43 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, entity, floorWith, hassOf } from "../../entities/fixtures.ts"; +import type { Building, Furniture } from "../../model.ts"; +import { watchedEntities, type WatchInputs } from "./watch-list.ts"; + +const tv: Furniture = { id: "tv1", type: "tv_board", x: 1, z: 1, rotation: 0, w: 1, d: 0.4, h: 0.5, variant: null, state_entity: "binary_sensor.state", door_left: "binary_sensor.left", soc: "sensor.soc", temp_entity: "sensor.fridge_temp", temp_entity2: "sensor.freezer_temp" }; +const building = (extra: Record = {}): Building => + ({ + version: 1, + floors: [floorWith([box("r", 0, 0, 4, 4, "lounge")], { furniture: [tv], placements: [{ entity_id: "light.a", x: 1, z: 1, y: null }] })], + settings: { roof: { type: "none", pitch: 35, overhang: 0, windows: [{ id: "w", face: "main:a", u: 0, v: 0, cover: "cover.roof", contact: "none" }], solar: [{ id: "f", face: "main:a", u: 0, v: 0, rows: 1, cols: 1, portrait: true, entity: "sensor.pv" }], strings: [] } }, + energy: { grid: "sensor.grid", solar: null, battery: null, battery_soc: null, consumption: null, tariff: null }, + presence: [{ person: "person.anna", sensor: "sensor.anna_room" }], + ...extra, + }) as unknown as Building; + +function inputs(extra: Partial = {}): WatchInputs { + const hass = hassOf([entity("light.a", "on"), entity("sensor.room_temp", "20", { device_class: "temperature" })], { "sensor.room_temp": { area_id: "lounge" }, "light.a": { area_id: "lounge" } }, { areas: { lounge: { area_id: "lounge", name: "Lounge" } } }); + return { hass, building: building(), openingLinks: new Map(), furnitureLinks: new Map(), needsRoomSensors: false, alertSources: null, weatherEntityId: null, ...extra }; +} + +test("placed devices, energy sensors, presence, furniture links, the roof and the sun are watched", () => { + const ids = watchedEntities(inputs()); + for (const id of ["light.a", "sensor.grid", "person.anna", "sensor.anna_room", "binary_sensor.state", "binary_sensor.left", "sensor.soc", "sensor.fridge_temp", "sensor.freezer_temp", "cover.roof", "sensor.pv", "sun.sun"]) assert.ok(ids.includes(id), id); +}); + +test("an entity set to 'none' on a roof window is not watched, and nothing appears twice", () => { + const ids = watchedEntities(inputs()); + assert.equal(ids.includes("none"), false); + assert.equal(new Set(ids).size, ids.length); +}); + +test("the sensors of the rooms' areas are only watched when the heat map or room labels need them", () => { + assert.equal(watchedEntities(inputs()).includes("sensor.room_temp"), false); + assert.equal(watchedEntities(inputs({ needsRoomSensors: true })).includes("sensor.room_temp"), true); +}); + +test("opening links bring their blinds, contacts and positions along", () => { + const links = new Map([["o1", { cover: "cover.blind", contact: "binary_sensor.window", tilt: null, contact2: "binary_sensor.second", position: "sensor.pos" }]]); + const ids = watchedEntities(inputs({ openingLinks: links as never })); + for (const id of ["cover.blind", "binary_sensor.window", "binary_sensor.second", "sensor.pos"]) assert.ok(ids.includes(id), id); +}); diff --git a/frontend/src/components/view3d/watch-list.ts b/frontend/src/components/view3d/watch-list.ts new file mode 100644 index 0000000..268d398 --- /dev/null +++ b/frontend/src/components/view3d/watch-list.ts @@ -0,0 +1,91 @@ +// Which Home Assistant entities the 3D view reacts to. The view only redraws when one of them changed, so the list has to cover +// everything it shows: devices and their power sensors, openings and their contacts, energy, presence, heat, weather, and so on. + +import { alertEntities, type AlertSources } from "../../alerts.ts"; +import { carWatched, deviceSiblings, kindOf, robotRoomSensor, type FurnitureLinks, type OpeningEntities, roomEntities } from "../../devices.ts"; +import { powerSensorFor } from "../../energy.ts"; +import { placedEntities } from "../../markers.ts"; +import type { Building } from "../../model.ts"; +import { parkingEntities } from "../../parking.ts"; +import { pluginWatched } from "../../plugins/registry.ts"; +import type { HomeAssistant } from "../../types.ts"; +import { weatherEntity } from "../../weather.ts"; + +export interface WatchInputs { + hass: HomeAssistant; + building: Building; + openingLinks: ReadonlyMap; + furnitureLinks: ReadonlyMap; + /** Heat map or room labels are on, so the sensors of every room's area are needed. */ + needsRoomSensors: boolean; + alertSources: AlertSources | null; + weatherEntityId: string | null; +} + +type MaybeId = string | null | undefined; + +const real = (id: MaybeId): id is string => !!id && id !== "none"; +const roomsOf = (b: Building) => b.floors.flatMap((f) => f.rooms); +const furnitureOf = (b: Building) => b.floors.flatMap((f) => f.furniture); + +/** The sensors and entities behind the openings: blinds, contacts, tilt, positions. */ +function openingIds(links: WatchInputs["openingLinks"]): MaybeId[] { + return [...links.values()].flatMap((e) => [e.cover, e.cover2, e.contact, e.tilt, e.contact2, e.tilt2, e.position, e.tiltAngle]); +} + +/** What furniture is linked to besides its device: state lights, doors and thermometers of a fridge, battery, status, charge, export, pictures. */ +function furnitureIds(inputs: WatchInputs): MaybeId[] { + const { hass, building, furnitureLinks } = inputs; + const pieces = furnitureOf(building); + return [ + ...[...furnitureLinks.values()].flatMap((l) => [l.entity, l.power]), + ...pieces.flatMap((m) => [m.state_entity, m.state_entity2, m.color_entity, ...(m.gang_entities ?? []), ...(m.extra_lights ?? []), m.cover_entity, m.care_entity, m.room_sensor, m.show_when?.entity, m.picture && /^[a-z_]+\.[a-z0-9_]+$/.test(m.picture) ? m.picture : null]), + // a washer's, dryer's or dishwasher's time left comes from a sensor next to its switch + ...pieces.filter((m) => m.type === "washer" || m.type === "dryer" || m.type === "dishwasher").flatMap((m) => deviceSiblings(hass, furnitureLinks.get(m.id)?.entity ?? furnitureLinks.get(m.id)?.power).filter((id) => id.startsWith("sensor."))), + ...pieces.flatMap((m) => [m.door_left, m.door_right, m.soc, m.status, m.charge, m.export, m.temp_entity, m.temp_entity2]), + ...pieces.filter((m) => m.type === "robot_vacuum").map((m) => robotRoomSensor(hass, furnitureLinks.get(m.id)?.entity ?? null, m.room_sensor)), + ...pieces.flatMap((m) => (m.pictures ?? []).flatMap((rule) => [rule.entity, ...(rule.image.startsWith("camera:") ? [rule.image.slice("camera:".length)] : [])])), + ]; +} + +/** The roof: windows with their blinds and contacts, and the sensors of solar fields and strings that feed the cables. */ +function roofIds(b: Building): MaybeId[] { + const roof = b.settings.roof; + return [...(roof?.windows ?? []).flatMap((w) => [w.cover, w.contact, w.tilt]), ...(roof?.solar ?? []).map((f) => f.entity), ...(roof?.strings ?? []).map((s) => s.entity)].filter(real); +} + +export function watchedEntities(inputs: WatchInputs): string[] { + const { hass, building: b } = inputs; + const placed = placedEntities(b); + const energy = b.energy; + const lightsOfRooms = roomsOf(b).flatMap((r) => roomEntities(hass, r).filter((id) => kindOf(id) === "light")); + const sensorsOfRooms = inputs.needsRoomSensors ? roomsOf(b).flatMap((r) => roomEntities(hass, r).filter((id) => id.startsWith("sensor.") || id.startsWith("climate."))) : []; + const ids: MaybeId[] = [ + ...placed, + ...openingIds(inputs.openingLinks), + ...placed.map((id) => powerSensorFor(hass, id)), + // what plugins draw for a device may follow further entities (a camera's motion sensor) + ...placed.flatMap((id) => (hass.states[id] ? pluginWatched({ hass, entityId: id, state: hass.states[id] }) : [])), + ...furnitureIds(inputs), + ...roofIds(b), + energy.grid, + energy.solar, + energy.battery, + energy.battery_soc, + energy.consumption, + energy.tariff, + energy.gas, + energy.water, + ...b.presence.flatMap((p) => [p.person, p.sensor]), + ...lightsOfRooms, + ...roomsOf(b).map((r) => r.floor_heating), + ...b.floors.flatMap((f) => (f.outdoor ?? []).flatMap((a) => [a.temp_entity, a.pump_entity])), + ...sensorsOfRooms, + ...(inputs.alertSources ? alertEntities(inputs.alertSources) : []), + ...parkingEntities(b.floors), + ...carWatched(hass, b.floors), + weatherEntity(hass, inputs.weatherEntityId ?? b.settings.weather_entity), + "sun.sun", + ]; + return [...new Set(ids.filter((id): id is string => !!id))]; +} diff --git a/frontend/src/devices.ts b/frontend/src/devices.ts new file mode 100644 index 0000000..228aa8e --- /dev/null +++ b/frontend/src/devices.ts @@ -0,0 +1,11 @@ +// Everything about the devices of a plan, gathered from the modules in entities/. Other files import from here. + +export * from "./entities/kinds.ts"; +export * from "./entities/registry.ts"; +export * from "./entities/openings.ts"; +export * from "./entities/furniture-links.ts"; +export * from "./entities/car.ts"; +export * from "./entities/misc.ts"; +export * from "./entities/gangs.ts"; +export * from "./entities/household.ts"; +export * from "./entities/covers.ts"; diff --git a/frontend/src/energy.test.ts b/frontend/src/energy.test.ts new file mode 100644 index 0000000..e1b7697 --- /dev/null +++ b/frontend/src/energy.test.ts @@ -0,0 +1,294 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { canHangOff, deviceMeter, deviceSensors, subMeterLabel, energySummary, findConsumers, meterParent, meterPosition, powerSensorFor, proposeEnergySensors, readPower, subMeterIds, suggestGridSpot } from "./energy.ts"; +import { emptyBuilding, newFloor, type Building, type Furniture } from "./model.ts"; +import type { HassEntity, HomeAssistant } from "./types.ts"; + +const sensor = (entity_id: string, state: string, attributes: Record = {}): HassEntity => ({ entity_id, state, attributes }); +const hassOf = (list: HassEntity[], entities: Record> = {}) => + ({ states: Object.fromEntries(list.map((s) => [s.entity_id, s])), entities: Object.fromEntries(Object.entries(entities).map(([id, e]) => [id, { entity_id: id, ...e }])) }) as unknown as HomeAssistant; +const piece = (type: string, extra: Partial = {}): Furniture => ({ id: type + Math.random(), type, x: 1, z: 1, rotation: 0, w: 1, d: 1, h: 1, variant: null, entity: null, power: null, ...extra }); +const house = (...pieces: Furniture[]): Building => { + const b = emptyBuilding(); + const f = newFloor("g", "Ground", 0); + f.furniture = pieces; + f.rooms = [{ id: "r", name: "R", area_id: null, points: [[0, 0], [6, 0], [6, 4], [0, 4]], floor_material: "wood" }]; + b.floors = [f]; + return b; +}; + +test("power is read in watts whatever the unit, and can be flipped", () => { + assert.equal(readPower(sensor("sensor.a", "1.5", { unit_of_measurement: "kW" })), 1500); + assert.equal(readPower(sensor("sensor.a", "2", { unit_of_measurement: "MW" })), 2e6); + assert.equal(readPower(sensor("sensor.a", "300")), 300); + assert.equal(readPower(sensor("sensor.a", "300"), true), -300); + assert.equal(readPower(sensor("sensor.a", "unavailable")), null); + assert.equal(readPower(undefined), null); +}); + +test("energy devices in the plan are collected without duplicates", () => { + const b = house( + piece("meter", { power: "sensor.grid", export: "sensor.feed" }), + piece("inverter", { power: "sensor.pv1" }), + piece("inverter", { power: "sensor.pv1" }), + piece("inverter", { power: "sensor.pv2" }), + piece("home_battery", { power: "sensor.bat", charge: "sensor.bat_in", soc: "sensor.soc" }), + ); + const d = deviceSensors(b); + assert.deepEqual([d.grid, d.gridExport, d.solar, d.soc], ["sensor.grid", "sensor.feed", ["sensor.pv1", "sensor.pv2"], ["sensor.soc"]]); + assert.deepEqual(d.batteries, [{ power: "sensor.bat", charge: "sensor.bat_in" }]); +}); + +test("the meter cabinet in the plan is where cables meet, else the configured spot", () => { + const b = house(piece("meter", { x: 2, z: 3 })); + assert.deepEqual(meterPosition(b), { floor_id: "g", x: 2, z: 3 }); + const none = house(); + none.energy.meter = { floor_id: "g", x: 5, z: 5 }; + assert.deepEqual(meterPosition(none), { floor_id: "g", x: 5, z: 5 }); +}); + +test("the summary balances grid, solar and battery into the house's consumption", () => { + const b = house(); + b.energy = { ...b.energy, grid: "sensor.grid", solar: "sensor.pv", battery: "sensor.bat", battery_soc: "sensor.soc" }; + const hass = hassOf([sensor("sensor.grid", "-500"), sensor("sensor.pv", "2000"), sensor("sensor.bat", "-300"), sensor("sensor.soc", "64")]); + const s = energySummary(hass, b, []); + assert.deepEqual([s.grid, s.solar, s.battery, s.soc], [-500, 2000, -300, 64]); + assert.equal(s.consumption, 1200); // -500 + 2000 - 300 +}); + +test("a consumption sensor wins over the balance, and the consumers are the last resort", () => { + const b = house(); + b.energy = { ...b.energy, consumption: "sensor.use" }; + assert.equal(energySummary(hassOf([sensor("sensor.use", "850")]), b, []).consumption, 850); + const plain = house(); + const consumers = [{ id: "a", powerEntity: "p", floorId: "g", x: 0, z: 0, power: 40 }, { id: "b", powerEntity: "q", floorId: "g", x: 0, z: 0, power: 60 }]; + assert.equal(energySummary(hassOf([]), plain, consumers).consumption, 100); + assert.equal(energySummary(hassOf([]), plain, []).consumption, null); +}); + +test("devices placed in the plan supply the numbers when no balance sensor is set", () => { + const b = house(piece("meter", { power: "sensor.in", export: "sensor.out" }), piece("inverter", { power: "sensor.pv" }), piece("home_battery", { power: "sensor.dis", charge: "sensor.chg" })); + const hass = hassOf([sensor("sensor.in", "100"), sensor("sensor.out", "700"), sensor("sensor.pv", "1500"), sensor("sensor.dis", "0"), sensor("sensor.chg", "400")]); + const s = energySummary(hass, b, []); + assert.equal(s.grid, -600); + assert.equal(s.solar, 1500); + assert.equal(s.battery, -400); +}); + +test("a flipped grid sensor changes the sign", () => { + const b = house(); + b.energy = { ...b.energy, grid: "sensor.grid", grid_invert: true }; + assert.equal(energySummary(hassOf([sensor("sensor.grid", "800")]), b, []).grid, -800); +}); + +test("tariff and charge level are optional", () => { + const b = house(); + b.energy = { ...b.energy, tariff: "sensor.price" }; + const s = energySummary(hassOf([sensor("sensor.price", "0.31", { unit_of_measurement: "€/kWh" })]), b, []); + assert.deepEqual(s.tariff, { value: 0.31, unit: "€/kWh" }); + assert.equal(s.soc, null); +}); + +test("a placed entity's power sensor is itself, or one of its device; hubs only give same-area sensors", () => { + const hass = hassOf( + [sensor("light.a", "on"), sensor("sensor.a_power", "12", { device_class: "power" }), sensor("sensor.hub_power_k", "5", { device_class: "power" }), sensor("sensor.hub_power_b", "7", { device_class: "power" }), sensor("light.k", "on")], + { + "light.a": { device_id: "d1" }, + "sensor.a_power": { device_id: "d1" }, + "light.k": { device_id: "hub", area_id: "kitchen" }, + "sensor.hub_power_k": { device_id: "hub", area_id: "kitchen" }, + "sensor.hub_power_b": { device_id: "hub", area_id: "bath" }, + }, + ); + assert.equal(powerSensorFor(hass, "sensor.a_power"), "sensor.a_power"); + assert.equal(powerSensorFor(hass, "light.a"), "sensor.a_power"); + assert.equal(powerSensorFor(hass, "light.nowhere"), null); + assert.ok(["sensor.hub_power_k", null].includes(powerSensorFor(hass, "light.k"))); +}); + +test("consumers skip the balance sensors and count a shared sensor once", () => { + const b = house(); + b.energy = { ...b.energy, grid: "sensor.grid" }; + b.floors[0].placements = [ + { entity_id: "sensor.grid", x: 0, z: 0, y: null, mount: null }, + { entity_id: "sensor.oven", x: 1, z: 1, y: null, mount: null }, + { entity_id: "sensor.oven", x: 2, z: 2, y: null, mount: null }, + ]; + const hass = hassOf([sensor("sensor.grid", "100", { device_class: "power" }), sensor("sensor.oven", "-5", { device_class: "power" })]); + const consumers = findConsumers(hass, b); + assert.equal(consumers.length, 1); + assert.equal(consumers[0].power, 0, "negative readings count as zero"); +}); + +test("proposals follow the energy dashboard: the device's total power sensor, not a phase", () => { + const hass = hassOf( + [sensor("sensor.meter_energy", "1"), sensor("sensor.meter_power_l1", "1", { device_class: "power" }), sensor("sensor.meter_power", "3", { device_class: "power" })], + { "sensor.meter_energy": { device_id: "m" }, "sensor.meter_power_l1": { device_id: "m" }, "sensor.meter_power": { device_id: "m" } }, + ); + const proposal = proposeEnergySensors(hass, { energy_sources: [{ type: "grid", flow_from: [{ stat_energy_from: "sensor.meter_energy" }] }] }); + assert.equal(proposal.grid, "sensor.meter_power"); + assert.deepEqual(proposeEnergySensors(hass, {}), {}); +}); + +test("the grid connection is suggested outside the wall nearest to the meter", () => { + const b = house(piece("meter", { x: 5.8, z: 2 })); + const spot = suggestGridSpot(b)!; + assert.equal(spot.floorId, "g"); + assert.ok(spot.x > 6, "outside the east wall"); + assert.ok(Math.abs(spot.z - 2) < 0.5); + assert.equal(suggestGridSpot(house()), null); +}); + +// a house with one main meter and a sub-meter for each flat (upper floor, attic) +const flats = (advanced: boolean) => { + const b = house( + piece("meter", { id: "main", x: 1, z: 1, power: "sensor.main" }), + piece("meter", { id: "og", x: 2, z: 1, power: "sensor.og", parent_meter: "main", meter_floors: ["og"] }), + piece("meter", { id: "dg", x: 3, z: 1, power: "sensor.dg", parent_meter: "main", meter_floors: ["dg"], meter_invert: true }), + ); + b.energy.advanced = advanced; + return b; +}; + +test("with the advanced energy mode off, sub-meter fields change nothing", () => { + const plain = house(piece("meter", { id: "main", x: 1, z: 1, power: "sensor.main" }), piece("meter", { id: "og", x: 2, z: 1, power: "sensor.og" }), piece("meter", { id: "dg", x: 3, z: 1, power: "sensor.dg" })); + const hass = hassOf([sensor("sensor.main", "3000"), sensor("sensor.og", "800"), sensor("sensor.dg", "-600")]); + assert.deepEqual(deviceSensors(flats(false)), deviceSensors(plain)); + assert.deepEqual(energySummary(hass, flats(false), []), energySummary(hass, plain, [])); + assert.deepEqual(meterPosition(flats(false)), meterPosition(plain)); + assert.equal(subMeterIds(flats(false)).size, 0); + assert.equal(deviceSensors(plain).subMeters, undefined); +}); + +test("sub-meters hang off the main meter, which stays the grid", () => { + const b = flats(true); + const d = deviceSensors(b); + assert.equal(d.grid, "sensor.main"); + assert.deepEqual(d.subMeters, [ + { id: "og", parent: "main", power: "sensor.og", invert: false, floors: ["og"], solar: [], batteries: [] }, + { id: "dg", parent: "main", power: "sensor.dg", invert: true, floors: ["dg"], solar: [], batteries: [] }, + ]); + // the first meter in the plan may be a sub-meter: the main meter is the first one without a parent + b.floors[0].furniture.reverse(); + assert.equal(deviceSensors(b).grid, "sensor.main"); + assert.deepEqual(meterPosition(b), { floor_id: "g", x: 1, z: 1 }); +}); + +test("a meter cannot hang off itself or a meter below it; a loop counts as no parent", () => { + const b = flats(true); + const [main, og, dg] = b.floors[0].furniture; + dg.parent_meter = "og"; // a cascade: main → og → dg + assert.equal(canHangOff(b, main, og), false, "og hangs off main"); + assert.equal(canHangOff(b, main, dg), false, "dg hangs off og, which hangs off main"); + assert.equal(canHangOff(b, og, og), false); + assert.equal(canHangOff(b, dg, main), true); + assert.equal(meterParent(b, dg), "og"); + og.parent_meter = "dg"; // stored by hand: og ↔ dg + assert.equal(meterParent(b, og), null); + assert.equal(meterParent(b, dg), null); + main.parent_meter = "main"; + assert.equal(meterParent(b, main), null); + og.parent_meter = "gone"; + assert.equal(meterParent(b, og), null); +}); + +test("the rest is the consumption minus the meters directly below the main meter, never below 0", () => { + const b = flats(true); + const s = energySummary(hassOf([sensor("sensor.main", "2000"), sensor("sensor.og", "800"), sensor("sensor.dg", "-600")]), b, []); + assert.deepEqual(s.subMeters, [ + { id: "og", parent: "main", power: 800, solar: 0, battery: 0, use: 800, unmetered: 800 }, + { id: "dg", parent: "main", power: 600, solar: 0, battery: 0, use: 600, unmetered: 600 }, + ]); + assert.equal(s.rest, 600); + // a meter below a sub-meter is already inside that sub-meter's reading + b.floors[0].furniture[2].parent_meter = "og"; + assert.equal(energySummary(hassOf([sensor("sensor.main", "2000"), sensor("sensor.og", "800"), sensor("sensor.dg", "-600")]), b, []).rest, 1200); + // solar behind a sub-meter: the main meter counts less than the flats draw + b.floors[0].furniture[2].parent_meter = "main"; + assert.equal(energySummary(hassOf([sensor("sensor.main", "500"), sensor("sensor.og", "800"), sensor("sensor.dg", "-600")]), b, []).rest, 0); + assert.equal(energySummary(hassOf([]), b, []).rest, null); +}); + +// A multi-family house: main meter in the basement with the roof plant, the upper flat (OG) with a balcony plant and a +// battery behind its own meter, the attic flat (DG) without. OG uses 500 W, DG 200 W, the common parts 100 W. +const withPlants = (advanced: boolean) => { + const b = house( + piece("meter", { id: "main", power: "sensor.main" }), + piece("inverter", { id: "roof", power: "sensor.roof" }), + piece("meter", { id: "og", power: "sensor.og", parent_meter: "main", meter_floors: ["og"] }), + piece("meter", { id: "dg", power: "sensor.dg", parent_meter: "main", meter_floors: ["dg"] }), + piece("inverter", { id: "balcony", power: "sensor.balcony", parent_meter: "og" }), + piece("home_battery", { id: "box", power: "sensor.box", parent_meter: "og" }), + ); + b.energy.advanced = advanced; + return b; +}; +// 1800 W of sun for 800 W of use: 1000 W go to the grid; the OG meter runs backwards by 300 W +const plantHass = (battery = "0") => hassOf([sensor("sensor.main", "-1000"), sensor("sensor.roof", "1000"), sensor("sensor.og", "-300"), sensor("sensor.dg", "200"), sensor("sensor.balcony", "800"), sensor("sensor.box", battery)]); + +test("a balcony plant behind a flat's meter counts towards that flat", () => { + const s = energySummary(plantHass(), withPlants(true), []); + assert.deepEqual([s.grid, s.solar, s.consumption], [-1000, 1800, 800]); + assert.deepEqual(s.subMeters, [ + { id: "og", parent: "main", power: -300, solar: 800, battery: 0, use: 500, unmetered: 500 }, + { id: "dg", parent: "main", power: 200, solar: 0, battery: 0, use: 200, unmetered: 200 }, + ]); + assert.equal(s.rest, 100); + // the flat's battery charges with 200 W of the surplus: the meter feeds back only 100 W, the use stays 500 W + const charging = energySummary(hassOf([...Object.values(plantHass("-200").states)].map((st) => (st.entity_id === "sensor.og" ? sensor("sensor.og", "-100") : st.entity_id === "sensor.main" ? sensor("sensor.main", "-800") : st))), withPlants(true), []); + assert.equal(charging.subMeters?.[0].use, 500); + assert.equal(charging.rest, 100); +}); + +test("an inverter whose meter is gone, or is the main meter, works into the house", () => { + const b = withPlants(true); + const balcony = b.floors[0].furniture[4]; + assert.equal(deviceMeter(b, balcony), "og"); + for (const parent of ["gone", "main", null]) { + balcony.parent_meter = parent; + assert.equal(deviceMeter(b, balcony), null); + const s = energySummary(plantHass(), b, []); + assert.deepEqual([s.subMeters?.[0].solar, s.subMeters?.[0].use, s.rest], [0, 0, 600]); + } +}); + +test("with the advanced energy mode off, a meter chosen at an inverter or battery changes nothing", () => { + const plain = withPlants(false); + for (const f of plain.floors[0].furniture) delete f.parent_meter; + assert.deepEqual(deviceSensors(withPlants(false)), deviceSensors(plain)); + assert.deepEqual(energySummary(plantHass("300"), withPlants(false), []), energySummary(plantHass("300"), plain, [])); + assert.equal(deviceMeter(withPlants(false), withPlants(false).floors[0].furniture[4]), null); +}); + +test("what a flat uses beyond its placed devices is shown, and placed devices go into no total", () => { + const b = withPlants(true); + const pc = [{ id: "switch.pc", powerEntity: "sensor.pc", floorId: "og", x: 1, z: 1, power: 50 }]; + // the balcony inverter's own sensor on the same floor is no consumer + const inverter = [{ id: "sensor.balcony", powerEntity: "sensor.balcony", floorId: "og", x: 2, z: 2, power: 800 }]; + const before = energySummary(plantHass(), b, []); + const after = energySummary(plantHass(), b, [...pc, ...inverter]); + assert.deepEqual([after.subMeters?.[0].use, after.subMeters?.[0].unmetered], [500, 450]); + assert.deepEqual(after.subMeters?.[1].unmetered, 200, "nothing placed in the attic: all of it unmetered"); + const totals = (s: typeof before) => [s.grid, s.solar, s.battery, s.consumption, s.rest, s.subMeters?.map((m) => m.use)]; + assert.deepEqual(totals(after), totals(before)); + // a flat using less than its devices report: 0, not below + pc[0].power = 900; + assert.equal(energySummary(plantHass(), b, pc).subMeters?.[0].unmetered, 0); + // mode off: consumers change nothing beyond what they did before + const off = withPlants(false); + assert.deepEqual(energySummary(plantHass(), off, pc), energySummary(plantHass(), off, [])); +}); + +test("the unmetered part shows on a sub-meter's label only when asked for", () => { + const b = withPlants(true); + const pc = [{ id: "switch.pc", powerEntity: "sensor.pc", floorId: "og", x: 1, z: 1, power: 50 }]; + const s = energySummary(plantHass(), b, pc); + assert.equal(subMeterLabel(b, s, "og"), null, "off by default: the label shows the meter's reading"); + b.energy.show_unmetered = true; + assert.deepEqual(subMeterLabel(b, s, "og"), { use: 500, unmetered: 450 }); + assert.deepEqual(subMeterLabel(b, s, "dg"), { use: 200, unmetered: null }, "nothing measured: only the use"); + assert.equal(subMeterLabel(b, s, "main"), null); + const off = withPlants(false); + off.energy.show_unmetered = true; + assert.equal(subMeterLabel(off, energySummary(plantHass(), off, pc), "og"), null); +}); diff --git a/frontend/src/energy.ts b/frontend/src/energy.ts new file mode 100644 index 0000000..5b2bdd8 --- /dev/null +++ b/frontend/src/energy.ts @@ -0,0 +1,395 @@ +// Energy balance: reads power values from Home Assistant and the consumers placed in the plan, and proposes +// sensors from the energy dashboard. Plain functions, no three.js. The moving particles are in +// live/energy-flow.ts and viewer/live-energy.ts; this file only deals with the numbers. + +import { entityAreaId, isHubDevice, powerSensorsOf } from "./devices.ts"; +import { generateWalls } from "./geometry/walls.ts"; +import type { Building, EnergySettings, Furniture } from "./model.ts"; +import type { HassEntity, HomeAssistant } from "./types.ts"; + +export interface EnergySummary { + /** Grid power in W: positive is import, negative is export. */ + grid: number | null; + solar: number | null; + /** Battery power in W: positive is discharging, negative is charging. */ + battery: number | null; + soc: number | null; + tariff: { value: number; unit: string } | null; + /** What the house uses in W: the consumption sensor, else the balance, else the sum of the consumers. */ + consumption: number | null; + /** Advanced energy mode only: each sub-meter's reading, the solar and battery power behind it, and what its own floors use (see subMeterBalance). */ + subMeters?: SubMeterBalance[]; + /** Advanced energy mode only: what the main meter's own branch uses (the consumption minus the sub-meters' own use, at least 0). */ + rest?: number | null; +} + +export interface Consumer { + /** The placed entity. */ + id: string; + powerEntity: string; + floorId: string; + x: number; + z: number; + power: number; + /** A wallbox: its cable gets its own colour. */ + wallbox?: boolean; +} + +export interface DeviceSensors { + grid: string | null; + /** A meter's separate export sensor (its power sensor then reports import only). */ + gridExport: string | null; + solar: string[]; + battery: string[]; + /** Separate charging sensors, for batteries whose power sensor only reports discharging. */ + charge: string[]; + /** Each battery with its sensors: one signed power sensor, or discharge plus a separate charge sensor. */ + batteries: { power: string | null; charge: string | null }[]; + soc: string[]; + /** Advanced energy mode only: the meters that hang off another meter, with their sensor and the floors they feed. */ + subMeters?: SubMeterSensors[]; +} + +export interface SubMeterSensors { + id: string; + parent: string; + power: string | null; + invert: boolean; + floors: string[]; + /** The inverters and home batteries hanging off this meter (a balcony plant behind a flat's meter). */ + solar: string[]; + batteries: { power: string | null; charge: string | null }[]; +} + +export interface SubMeterBalance { + id: string; + parent: string; + /** The meter's reading in W: + = the branch draws from its parent, − = it feeds back; null without a number. */ + power: number | null; + /** Solar production and battery power (+ = discharging) of the devices hanging off this meter. */ + solar: number; + battery: number; + /** What the floors of this meter use themselves, without the meters below it (at least 0). */ + use: number | null; + /** Of that, what no placed consumer on its floors measures (at least 0); shown only, never added to a total. */ + unmetered: number | null; +} + +const usable = (id: string | null | undefined): string | null => (id && id !== "none" ? id : null); + +const addOnce = (list: string[], id: string | null) => { + if (id && !list.includes(id)) list.push(id); +}; + +const metersOf = (building: Building): Map => + new Map(building.floors.flatMap((floor) => floor.furniture.filter((f) => f.type === "meter").map((f) => [f.id, f] as const))); + +/** + * Advanced energy mode: the meter a meter hangs off, null for a main meter (and always null with the mode off). + * A parent that is gone, the meter itself, or a loop of meters counts as none, so a broken chain never hides the grid. + */ +export function meterParent(building: Building, meter: Furniture): string | null { + if (!building.energy.advanced || meter.type !== "meter" || !meter.parent_meter) return null; + const meters = metersOf(building); + const seen = new Set([meter.id]); + for (let at = meters.get(meter.parent_meter); at; at = meters.get(at.parent_meter ?? "")) { + if (seen.has(at.id)) return null; + seen.add(at.id); + } + return meters.has(meter.parent_meter) ? meter.parent_meter : null; +} + +/** The ids of the meters that hang off another meter (empty with the advanced energy mode off). */ +export function subMeterIds(building: Building): Set { + return new Set([...metersOf(building).values()].filter((m) => meterParent(building, m)).map((m) => m.id)); +} + +/** + * Advanced energy mode: the sub-meter an inverter or home battery hangs off, null for the main meter (also when the + * chosen meter is gone or is no sub-meter). + */ +export function deviceMeter(building: Building, device: Furniture): string | null { + if (!building.energy.advanced || !device.parent_meter) return null; + return subMeterIds(building).has(device.parent_meter) ? device.parent_meter : null; +} + +/** + * A sub-meter's label with "show unmetered" on: what its floors use, and the part no placed device measures (null + * when that is all of it). Null with the option off; the label then shows the meter's reading. + */ +export function subMeterLabel(building: Building, summary: EnergySummary, meterId: string): { use: number; unmetered: number | null } | null { + const m = building.energy.show_unmetered ? summary.subMeters?.find((s) => s.id === meterId) : undefined; + if (!m || m.use === null) return null; + return { use: m.use, unmetered: m.unmetered !== null && m.unmetered < m.use ? m.unmetered : null }; +} + +/** Whether `meter` may hang off `candidate`: another meter that does not itself hang (directly or further down) off `meter`. */ +export function canHangOff(building: Building, meter: Furniture, candidate: Furniture): boolean { + if (candidate.type !== "meter" || candidate.id === meter.id) return false; + const meters = metersOf(building); + const seen = new Set(); + for (let at: Furniture | undefined = candidate; at && !seen.has(at.id); at = meters.get(at.parent_meter ?? "")) { + if (at.id === meter.id) return false; + seen.add(at.id); + } + return true; +} + +/** + * The sensors of the energy devices placed in the plan (meter, inverters, home batteries). `powerOf` says which + * power sensor an item uses: by default its own field. Several inverters add up. + */ +export function deviceSensors(building: Building, powerOf: (f: Furniture) => string | null = (f) => usable(f.power)): DeviceSensors { + const found: DeviceSensors = { grid: null, gridExport: null, solar: [], battery: [], charge: [], batteries: [], soc: [] }; + for (const piece of building.floors.flatMap((floor) => floor.furniture)) { + const power = powerOf(piece); + const parent = piece.type === "meter" ? meterParent(building, piece) : null; + if (parent) { + // advanced energy mode: a sub-meter measures its branch, not the grid + (found.subMeters ??= []).push({ id: piece.id, parent, power, invert: !!piece.meter_invert, floors: piece.meter_floors ?? [], solar: [], batteries: [] }); + } else if (piece.type === "meter") { + found.grid ??= power; + found.gridExport ??= usable(piece.export); + } else if (piece.type === "inverter") { + addOnce(found.solar, power); + } else if (piece.type === "home_battery") { + const charge = usable(piece.charge); + addOnce(found.battery, power); + addOnce(found.charge, charge); + addOnce(found.soc, usable(piece.soc)); + if (power || charge) found.batteries.push({ power, charge }); + } + } + // advanced energy mode: inverters and batteries behind a sub-meter (they still count in the totals above) + for (const piece of found.subMeters ? building.floors.flatMap((floor) => floor.furniture) : []) { + const meter = piece.type === "inverter" || piece.type === "home_battery" ? found.subMeters?.find((m) => m.id === deviceMeter(building, piece)) : undefined; + const power = meter ? powerOf(piece) : null; + if (meter && piece.type === "inverter") addOnce(meter.solar, power); + const charge = usable(piece.charge); + if (meter && piece.type === "home_battery" && (power || charge)) meter.batteries.push({ power, charge }); + } + return found; +} + +/** Where the cables meet: the (main) meter cabinet in the plan, else the spot from the energy settings. */ +export function meterPosition(building: Building): { floor_id: string; x: number; z: number } | null { + for (const floor of building.floors) { + const cabinet = floor.furniture.find((f) => f.type === "meter" && !meterParent(building, f)); + if (cabinet) return { floor_id: floor.id, x: cabinet.x, z: cabinet.z }; + } + return building.energy.meter; +} + +/** The energy dashboard preferences of Home Assistant (`energy/get_prefs`), as far as proposals need them. */ +export interface EnergyPrefs { + energy_sources?: { + type: string; + stat_energy_from?: string; + stat_energy_to?: string; + flow_from?: { stat_energy_from: string }[]; + flow_to?: { stat_energy_to: string }[]; + }[]; +} + +const PHASE_OR_PERIOD = /(phase|_l[123]\b|_[abc]$|today|daily|heute)/; +const ENERGY_WORDS = /_?(energy|energie|total|today|daily|kwh|import|export|consumption|production)/g; + +/** + * The power sensor (W) that goes with an energy statistic: a sensor of the same device. With several, a total + * (not a single phase or a daily value) whose name resembles the statistic's wins. + */ +function powerSensorOfStatistic(hass: HomeAssistant, statistic: string | undefined, deviceClass = "power"): string | null { + const device = statistic ? hass.entities?.[statistic]?.device_id : undefined; + if (!statistic || !device) return null; + const sameDevice = Object.keys(hass.states).filter((id) => id.startsWith("sensor.") && hass.entities?.[id]?.device_id === device && hass.states[id]?.attributes.device_class === deviceClass); + if (sameDevice.length <= 1) return sameDevice[0] ?? null; + const totals = sameDevice.filter((id) => !PHASE_OR_PERIOD.test(id)); + const stem = statistic.replace(/^sensor\./, "").replace(ENERGY_WORDS, ""); + return totals.find((id) => stem && id.includes(stem)) ?? totals[0] ?? sameDevice[0]; +} + +/** Energy balance sensors proposed from the energy dashboard: grid, solar, battery and its charge level. */ +export function proposeEnergySensors(hass: HomeAssistant, prefs: EnergyPrefs): Partial { + const proposal: Partial = {}; + // the first source of each kind that has a matching power sensor decides + const offer = (field: "grid" | "solar" | "battery" | "battery_soc", sensor: string | null) => { + if (sensor && !proposal[field]) proposal[field] = sensor; + }; + for (const source of prefs.energy_sources ?? []) { + if (source.type === "grid") { + offer("grid", powerSensorOfStatistic(hass, source.flow_from?.[0]?.stat_energy_from ?? source.flow_to?.[0]?.stat_energy_to)); + } else if (source.type === "solar") { + offer("solar", powerSensorOfStatistic(hass, source.stat_energy_from)); + } else if (source.type === "battery") { + const statistic = source.stat_energy_from ?? source.stat_energy_to; + offer("battery", powerSensorOfStatistic(hass, statistic)); + offer("battery_soc", powerSensorOfStatistic(hass, statistic, "battery")); + } + } + return proposal; +} + +/** A power state in watts (kW and MW are converted), optionally with the sign flipped. Null when it is no number. */ +export function readPower(st: HassEntity | undefined, invert = false): number | null { + const value = st ? Number(st.state) : NaN; + if (!Number.isFinite(value)) return null; + const factor = { kW: 1e3, MW: 1e6 }[String(st!.attributes.unit_of_measurement ?? "W")] ?? 1; + return invert ? -value * factor : value * factor; +} + +const isPowerSensor = (hass: HomeAssistant, id: string): boolean => id.startsWith("sensor.") && hass.states[id]?.attributes.device_class === "power"; + +/** + * The power sensor of a placed entity: the entity itself, or a power sensor on the same device. A hub (one device + * for the whole house, entities in several areas) only counts a sensor from the entity's own area, otherwise every + * light of the house would get the hub's first meter. + */ +export function powerSensorFor(hass: HomeAssistant, entityId: string): string | null { + if (isPowerSensor(hass, entityId)) return entityId; + const device = hass.entities?.[entityId]?.device_id; + if (!device) return null; + const onHub = isHubDevice(hass, device); + const area = onHub ? entityAreaId(hass, entityId) : null; + const candidates = powerSensorsOf(hass, device).filter((id) => id !== entityId); + return (onHub ? candidates.find((id) => area !== null && entityAreaId(hass, id) === area) : candidates[0]) ?? null; +} + +/** Placed entities that report power, with their position and current draw. */ +export function findConsumers(hass: HomeAssistant, building: Building): Consumer[] { + const { grid, solar, battery } = building.energy; + const taken = new Set([grid, solar, battery].filter((id): id is string => !!id)); + const consumers: Consumer[] = []; + for (const floor of building.floors) { + for (const placed of floor.placements) { + const sensor = powerSensorFor(hass, placed.entity_id); + if (!sensor || taken.has(sensor)) continue; + taken.add(sensor); // a sensor is shown once, even when two entities share it + consumers.push({ id: placed.entity_id, powerEntity: sensor, floorId: floor.id, x: placed.x, z: placed.z, power: Math.max(0, readPower(hass.states[sensor]) ?? 0) }); + } + } + return consumers; +} + +const total = (values: (number | null)[]): number | null => { + const numbers = values.filter((v): v is number => v !== null); + return numbers.length ? numbers.reduce((sum, v) => sum + v, 0) : null; +}; + +function gridPower(hass: HomeAssistant, e: EnergySettings, devices: DeviceSensors): number | null { + const id = e.grid ?? devices.grid; + const imported = id ? readPower(hass.states[id], e.grid_invert) : null; + // a meter with a separate export sensor: its power sensor is the import, the export is subtracted + if (!e.grid && devices.gridExport) { + const exported = Math.max(0, readPower(hass.states[devices.gridExport]) ?? 0); + return Math.max(0, imported ?? 0) - exported; + } + return imported; +} + +function solarPower(hass: HomeAssistant, e: EnergySettings, devices: DeviceSensors): number | null { + if (e.solar) return readPower(hass.states[e.solar]); + return devices.solar.length ? total(devices.solar.map((id) => readPower(hass.states[id]))) : null; +} + +/** One battery: a signed sensor (+ discharging, flipped on request), or discharge minus a separate charge sensor. */ +export function oneBattery(hass: HomeAssistant, b: { power: string | null; charge: string | null }, invert: boolean): number | null { + if (!b.charge) return b.power ? readPower(hass.states[b.power], invert) : null; + const discharging = b.power ? Math.max(0, readPower(hass.states[b.power]) ?? 0) : 0; + return discharging - Math.max(0, readPower(hass.states[b.charge]) ?? 0); +} + +function batteryPower(hass: HomeAssistant, e: EnergySettings, devices: DeviceSensors): number | null { + if (e.battery) return readPower(hass.states[e.battery], e.battery_invert); + return total(devices.batteries.map((b) => oneBattery(hass, b, e.battery_invert))); +} + +/** Everything the energy view shows. Sensors set in the energy settings win over those of placed devices. */ +export function energySummary(hass: HomeAssistant, building: Building, consumers: Consumer[], devices: DeviceSensors = deviceSensors(building)): EnergySummary { + const e = building.energy; + const grid = gridPower(hass, e, devices); + const solar = solarPower(hass, e, devices); + const battery = batteryPower(hass, e, devices); + + // several batteries: the average charge + const socValues = (e.battery_soc ? [e.battery_soc] : devices.soc).map((id) => Number(hass.states[id]?.state)).filter(Number.isFinite); + const soc = socValues.length ? socValues.reduce((a, b) => a + b, 0) / socValues.length : null; + + const tariffState = e.tariff ? hass.states[e.tariff] : undefined; + const tariffValue = Number(tariffState?.state); + + let consumption: number | null = e.consumption ? readPower(hass.states[e.consumption]) : null; + if (consumption === null && (grid !== null || solar !== null || battery !== null)) consumption = (grid ?? 0) + Math.max(0, solar ?? 0) + (battery ?? 0); + if (consumption === null && consumers.length > 0) consumption = consumers.reduce((sum, c) => sum + c.power, 0); + + const summary: EnergySummary = { + grid, + solar: solar === null ? null : Math.max(0, solar), + battery, + soc, + tariff: tariffState && Number.isFinite(tariffValue) ? { value: tariffValue, unit: String(tariffState.attributes.unit_of_measurement ?? "") } : null, + consumption: consumption === null ? null : Math.max(0, consumption), + }; + return devices.subMeters ? { ...summary, ...subMeterBalance(hass, devices, summary.consumption, e.battery_invert, consumers) } : summary; +} + +/** + * Advanced energy mode: the balance of each sub-meter, and the rest of the house (stairs, heating, the owner's flat). + * + * use(M) = reading(M) + solar(M) + battery(M) − Σ reading(C) (C = the meters hanging directly off M) + * rest = consumption − Σ use(M) (over all sub-meters) + * + * The reading is signed (+ = M draws from its parent, − = it feeds back), so a child's own solar is already inside + * its reading; summed over a branch the use telescopes to the readings below the main meter plus the solar and + * batteries behind them, nothing is counted twice. Both are kept at 0 or above: with a meter that only reports + * import (it never goes negative) a branch's surplus is unknown and its use comes out too high, rather than guessed. + * + * unmetered(M) = use(M) − Σ power of the consumers placed on M's floors (at least 0) + * + * The consumers on a floor belong to the first sub-meter naming it (as in the 3D flow); the energy devices' own + * sensors (meters, inverters, batteries) are no consumers here. This is display only and goes into no total. + */ +function subMeterBalance(hass: HomeAssistant, devices: DeviceSensors, consumption: number | null, batteryInvert: boolean, consumers: Consumer[]): Pick { + const meters = devices.subMeters ?? []; + const owner = new Map(); + for (const m of meters) for (const floorId of m.floors) if (!owner.has(floorId)) owner.set(floorId, m.id); + const ownSensors = new Set([devices.grid, devices.gridExport, ...devices.solar, ...devices.battery, ...devices.charge, ...meters.flatMap((m) => [m.power, ...m.solar, ...m.batteries.flatMap((b) => [b.power, b.charge])])]); + const measured = (id: string) => consumers.filter((c) => owner.get(c.floorId) === id && !ownSensors.has(c.powerEntity)).reduce((sum, c) => sum + c.power, 0); + const readings = new Map(meters.map((m) => [m.id, m.power ? readPower(hass.states[m.power], m.invert) : null])); + const subMeters = meters.map((m): SubMeterBalance => { + const power = readings.get(m.id) ?? null; + const solar = m.solar.reduce((sum, id) => sum + Math.max(0, readPower(hass.states[id]) ?? 0), 0); + const battery = m.batteries.reduce((sum, b) => sum + (oneBattery(hass, b, batteryInvert) ?? 0), 0); + const children = meters.filter((c) => c.parent === m.id).reduce((sum, c) => sum + (readings.get(c.id) ?? 0), 0); + const use = power === null ? null : Math.max(0, power + solar + battery - children); + return { id: m.id, parent: m.parent, power, solar, battery, use, unmetered: use === null ? null : Math.max(0, use - measured(m.id)) }; + }); + const used = subMeters.reduce((sum, m) => sum + (m.use ?? 0), 0); + return { subMeters, rest: consumption === null ? null : Math.max(0, consumption - used) }; +} + +/** Closest point on a wall segment to a position, with the segment's unit normal pointing away from `awayFrom`. */ +function nearestOnWall(wall: { a: [number, number]; b: [number, number] }, at: { x: number; z: number }, awayFrom: { x: number; z: number }) { + const dx = wall.b[0] - wall.a[0]; + const dz = wall.b[1] - wall.a[1]; + const length = Math.hypot(dx, dz) || 1; + const along = Math.min(1, Math.max(0, ((at.x - wall.a[0]) * dx + (at.z - wall.a[1]) * dz) / (length * length))); + const x = wall.a[0] + dx * along; + const z = wall.a[1] + dz * along; + const sign = ((dz / length) * (x - awayFrom.x) + (-dx / length) * (z - awayFrom.z)) < 0 ? -1 : 1; + return { x, z, nx: (sign * dz) / length, nz: (-sign * dx) / length, distance: Math.hypot(at.x - x, at.z - z) }; +} + +/** A first spot for the grid connection: a few metres outside the outer wall nearest to the meter, away from the house. */ +export function suggestGridSpot(building: Building): { floorId: string; x: number; z: number } | null { + const meter = meterPosition(building); + const floor = meter ? building.floors.find((f) => f.id === meter.floor_id) : undefined; + if (!meter || !floor) return null; + const thickness = { exterior: building.settings.wall_exterior, interior: building.settings.wall_interior }; + const outerWalls = generateWalls(floor.rooms, thickness, floor.walls ?? []).walls.filter((w) => w.exterior); + const corners = floor.rooms.flatMap((room) => room.points); + if (outerWalls.length === 0 || corners.length === 0) return null; + const centre = { x: corners.reduce((s, p) => s + p[0], 0) / corners.length, z: corners.reduce((s, p) => s + p[1], 0) / corners.length }; + const nearest = outerWalls.map((w) => nearestOnWall(w, meter, centre)).reduce((best, hit) => (hit.distance < best.distance ? hit : best)); + const out = thickness.exterior / 2 + 3; + return { floorId: floor.id, x: nearest.x + nearest.nx * out, z: nearest.z + nearest.nz * out }; +} diff --git a/frontend/src/entities/car.test.ts b/frontend/src/entities/car.test.ts new file mode 100644 index 0000000..84bbaa2 --- /dev/null +++ b/frontend/src/entities/car.test.ts @@ -0,0 +1,101 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, entity, floorWith, hassOf } from "./fixtures.ts"; +import { carEntities, carState, carWatched } from "./car.ts"; + +const vehicle = hassOf( + [ + entity("binary_sensor.car_present", "on"), + entity("sensor.car_battery", "64", { device_class: "battery", unit_of_measurement: "%" }), + entity("sensor.car_range", "310", { unit_of_measurement: "km" }), + entity("sensor.car_charger_power", "7.4", { unit_of_measurement: "kW" }), + entity("binary_sensor.car_cable", "on", { device_class: "plug" }), + entity("lock.car", "locked"), + entity("climate.car", "off"), + entity("device_tracker.car", "home"), + entity("sensor.other_battery", "10", { device_class: "battery" }), + ], + { + "binary_sensor.car_present": { device_id: "tesla" }, + "sensor.car_battery": { device_id: "tesla" }, + "sensor.car_range": { device_id: "tesla" }, + "sensor.car_charger_power": { device_id: "tesla" }, + "binary_sensor.car_cable": { device_id: "tesla" }, + "lock.car": { device_id: "tesla" }, + "climate.car": { device_id: "tesla" }, + "device_tracker.car": { device_id: "tesla" }, + "sensor.other_battery": { device_id: "elsewhere" }, + }, +); +const spot = { entity: "binary_sensor.car_present", car: undefined } as never; + +test("each role is found among the entities of the presence entity's device", () => { + assert.deepEqual(carEntities(vehicle, spot), { + soc: "sensor.car_battery", + range: "sensor.car_range", + charging: "sensor.car_charger_power", + plugged: "binary_sensor.car_cable", + lock: "lock.car", + climate: "climate.car", + tracker: "device_tracker.car", + }); +}); + +test("a chosen entity wins, a device can be chosen, and 'none' means nothing chosen", () => { + const e = carEntities(vehicle, { entity: null, car: { device: "sensor.car_range", soc: "sensor.other_battery", lock: "none" } } as never); + assert.equal(e.soc, "sensor.other_battery"); + assert.equal(e.range, "sensor.car_range"); + assert.equal(e.lock, "lock.car", "'none' falls back to the automatic match"); +}); + +test("without a device nothing is found", () => { + const e = carEntities(vehicle, { entity: "binary_sensor.unknown", car: undefined } as never); + assert.deepEqual(Object.values(e), [null, null, null, null, null, null, null]); +}); + +test("the state reads charge, range, charging power in watts, plug, lock and climate", () => { + const s = carState(vehicle, spot); + assert.equal(s.soc, 64); + assert.equal(s.range, 310); + assert.equal(s.rangeUnit, "km"); + assert.equal(s.chargingW, 7400); + assert.equal(s.charging, true); + assert.equal(s.plugged, true); + assert.equal(s.locked, true); + assert.equal(s.climateOn, false); + assert.equal(s.away, null); +}); + +test("charging below 50 W is not charging, and a charge level is kept between 0 and 100", () => { + const hass = hassOf([entity("sensor.p", "20", { unit_of_measurement: "W" }), entity("sensor.s", "130", { unit_of_measurement: "%" })]); + const s = carState(hass, { entity: null, car: { charging: "sensor.p", soc: "sensor.s" } } as never); + assert.equal(s.charging, false); + assert.equal(s.soc, 100); +}); + +test("a charging switch without power reading counts by its state", () => { + const hass = hassOf([entity("switch.charge", "on")]); + const s = carState(hass, { entity: null, car: { charging: "switch.charge" } } as never); + assert.equal(s.chargingW, null); + assert.equal(s.charging, true); +}); + +test("away says where the car is: its zone, or an empty text for plain away", () => { + const away = (state: string) => carState(hassOf([entity("device_tracker.t", state)]), { entity: null, car: { tracker: "device_tracker.t" } } as never).away; + assert.equal(away("home"), null); + assert.equal(away("not_home"), ""); + assert.equal(away("Work"), "Work"); + assert.equal(away("unavailable"), null); +}); + +test("watched entities come from parking spots that have car settings", () => { + const floor = floorWith([box("r", 0, 0, 4, 3)], { + furniture: [ + { id: "p", type: "parking", x: 1, z: 1, rotation: 0, w: 2, d: 5, h: 0.02, variant: null, entity: "binary_sensor.car_present", power: null, car: {} }, + { id: "q", type: "parking", x: 3, z: 1, rotation: 0, w: 2, d: 5, h: 0.02, variant: null, entity: "binary_sensor.car_present", power: null }, + ], + }); + const watched = carWatched(vehicle, [floor]); + assert.ok(watched.includes("sensor.car_battery")); + assert.equal(new Set(watched).size, 7, "only the first spot, one entry per role"); +}); diff --git a/frontend/src/entities/car.ts b/frontend/src/entities/car.ts new file mode 100644 index 0000000..6dd249f --- /dev/null +++ b/frontend/src/entities/car.ts @@ -0,0 +1,115 @@ +// The car on a parking spot: its entities (found on the car's Home Assistant device unless chosen) and what it reports. + +import type { Floor, Furniture } from "../model.ts"; +import type { HomeAssistant } from "../types.ts"; +import { isUnavailable } from "./kinds.ts"; + +/** Every role of the car, resolved to an entity id (or null). */ +export interface CarEntities { + soc: string | null; + range: string | null; + charging: string | null; + plugged: string | null; + lock: string | null; + climate: string | null; + tracker: string | null; +} + +type Role = keyof CarEntities; + +/** What the name of a car entity (id, friendly name, translation key) looks like for each role. */ +const ROLE_NAME: Record = { + soc: /(^|_)(soc|state_of_charge|battery_level|battery|ladestand|ladezustand|akku)($|_)/, + range: /(^|_)(range|reichweite|remaining_range)($|_)/, + charging: /(charging|charge_power|ladeleistung|laden|charger_power|lade)/, + plugged: /(plug|cable|connected|stecker|kabel|angeschlossen)/, + lock: /(lock|verriegel|schloss)/, + climate: /(climat|preheat|precondition|hvac|heiz|klima|standheizung)/, + tracker: /./, +}; + +const WATTS = /^k?W$/; + +const chosen = (ref: string | null | undefined): string | null => (ref && ref !== "none" ? ref : null); + +/** The car's entities: those chosen in the editor, the rest from the device of the chosen entity (or of the presence entity). */ +export function carEntities(hass: HomeAssistant, spot: Pick): CarEntities { + const choice = spot.car ?? {}; + const seed = chosen(choice.device) ?? chosen(spot.entity); + const deviceId = seed ? hass.entities?.[seed]?.device_id : null; + const siblings = deviceId && hass.entities ? Object.values(hass.entities).filter((e) => e.device_id === deviceId).map((e) => e.entity_id) : []; + + const attribute = (id: string, name: string) => String(hass.states[id]?.attributes[name] ?? ""); + const nameOf = (id: string) => `${id} ${attribute(id, "friendly_name")} ${hass.entities?.[id]?.translation_key ?? ""}`.toLowerCase().replace(/[\s-]+/g, "_"); + const byName = (role: Role, domains: string[], accept: (id: string) => boolean = () => true) => + siblings.find((id) => domains.includes(id.split(".")[0]) && ROLE_NAME[role].test(nameOf(id)) && accept(id)) ?? null; + const byClass = (domain: string, deviceClass: string) => siblings.find((id) => id.startsWith(`${domain}.`) && attribute(id, "device_class") === deviceClass) ?? null; + const firstOf = (domain: string) => siblings.find((id) => id.startsWith(`${domain}.`)) ?? null; + const unit = (id: string) => attribute(id, "unit_of_measurement"); + + return { + soc: chosen(choice.soc) ?? byClass("sensor", "battery") ?? byName("soc", ["sensor"], (id) => unit(id) === "%"), + range: chosen(choice.range) ?? byName("range", ["sensor"], (id) => /km|mi/.test(unit(id))) ?? byName("range", ["sensor"]), + charging: chosen(choice.charging) ?? byName("charging", ["sensor"], (id) => WATTS.test(unit(id))) ?? byName("charging", ["binary_sensor", "switch"]), + plugged: chosen(choice.plugged) ?? byClass("binary_sensor", "plug") ?? byName("plugged", ["binary_sensor"]), + lock: chosen(choice.lock) ?? firstOf("lock") ?? byName("lock", ["binary_sensor"]), + climate: chosen(choice.climate) ?? firstOf("climate") ?? byName("climate", ["switch", "binary_sensor"]), + tracker: chosen(choice.tracker) ?? firstOf("device_tracker"), + }; +} + +/** What the car reports right now; null for anything it does not tell. */ +export interface CarState { + entities: CarEntities; + soc: number | null; + range: number | null; + rangeUnit: string; + /** Charging power in W, when a power sensor reports it. */ + chargingW: number | null; + charging: boolean; + plugged: boolean | null; + locked: boolean | null; + climateOn: boolean | null; + /** The zone the car is in when not at home; "" for plain away, null when at home or unknown. */ + away: string | null; +} + +export function carState(hass: HomeAssistant, spot: Pick): CarState { + const entities = carEntities(hass, spot); + const stateOf = (id: string | null) => (id ? hass.states[id] : undefined); + const numberOf = (id: string | null): number | null => { + const value = Number(stateOf(id)?.state); + return id && Number.isFinite(value) ? value : null; + }; + + const chargeSensor = stateOf(entities.charging); + const chargeUnit = String(chargeSensor?.attributes.unit_of_measurement ?? ""); + const chargingW = chargeSensor && WATTS.test(chargeUnit) ? (numberOf(entities.charging) ?? 0) * (chargeUnit === "kW" ? 1000 : 1) : null; + // over 50 W counts as charging; without a power reading the sensor's own word decides + const charging = chargingW !== null ? chargingW > 50 : !!chargeSensor && ["on", "charging", "laden"].includes(chargeSensor.state.toLowerCase()); + + const soc = numberOf(entities.soc); + const plug = stateOf(entities.plugged); + const lock = stateOf(entities.lock); + const climate = stateOf(entities.climate); + const tracker = stateOf(entities.tracker); + const zone = tracker?.state.toLowerCase() ?? ""; + return { + entities, + soc: soc === null ? null : Math.max(0, Math.min(100, soc)), + range: numberOf(entities.range), + rangeUnit: String(stateOf(entities.range)?.attributes.unit_of_measurement ?? "km"), + chargingW, + charging, + plugged: plug ? plug.state === "on" : null, + locked: lock ? (lock.entity_id.startsWith("lock.") ? lock.state === "locked" : lock.state === "on") : null, + climateOn: climate ? (climate.entity_id.startsWith("climate.") ? !["off", "unavailable"].includes(climate.state) : climate.state === "on") : null, + away: tracker && zone !== "home" && !isUnavailable(tracker) ? (zone === "not_home" ? "" : tracker.state) : null, + }; +} + +/** Every entity the car's state depends on, so changes can be noticed. */ +export function carWatched(hass: HomeAssistant, floors: readonly Floor[]): string[] { + const spots = floors.flatMap((floor) => floor.furniture).filter((f) => f.type === "parking" && f.car); + return spots.flatMap((spot) => Object.values(carEntities(hass, spot))).filter((id): id is string => !!id); +} diff --git a/frontend/src/entities/covers.test.ts b/frontend/src/entities/covers.test.ts new file mode 100644 index 0000000..894f7d6 --- /dev/null +++ b/frontend/src/entities/covers.test.ts @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, hassOf } from "./fixtures.ts"; +import { coverPosition, coverReaches } from "./covers.ts"; +import { emptyBuilding, newFloor, type Furniture } from "../model.ts"; +import { setPacks, type PackItem } from "../packs.ts"; + +test("a cover's position comes from its attribute, else from open / closed", () => { + const hass = hassOf([ + entity("cover.a", "open", { current_position: 40 }), + entity("cover.b", "open"), + entity("cover.c", "closed"), + entity("cover.d", "closing"), + entity("cover.e", "unavailable"), + ]); + assert.equal(coverPosition(hass, "cover.a"), 40); + assert.equal(coverPosition(hass, "cover.b"), 100); + assert.equal(coverPosition(hass, "cover.c"), 0); + assert.equal(coverPosition(hass, "cover.d"), 50); + assert.equal(coverPosition(hass, "cover.e"), null); + assert.equal(coverPosition(hass, null), null); +}); + +test("an awning with the reversed direction extends where the cover reports closed (#100)", () => { + const awning: PackItem = { id: "awning", name: { en: "awning" }, size: [3, 2, 1], cover: "extends", parts: [{ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body", move: "out" }] }; + setPacks([{ id: "p", name: "p", publisher: "p", items: [awning] }]); + const fl = newFloor("f", "F", 0); + const mk = (id: string, extra: Partial): Furniture => ({ id, type: "pack:p:awning", x: 1, z: 1, rotation: 0, w: 3, d: 1, h: 2, variant: null, ...extra } as Furniture); + fl.furniture = [mk("a", { cover_entity: "cover.m" }), mk("b", { cover_entity: "cover.m", cover_inverted: true })]; + const hass = hassOf([entity("cover.m", "open", { current_position: 100 })]); + const reach = coverReaches(hass, { ...emptyBuilding(), floors: [fl] }); + assert.equal(reach.get("a"), 1, "open 100 % extends the awning"); + assert.equal(reach.get("b"), 0, "reversed: open 100 % brings it in"); +}); diff --git a/frontend/src/entities/covers.ts b/frontend/src/entities/covers.ts new file mode 100644 index 0000000..16efd90 --- /dev/null +++ b/frontend/src/entities/covers.ts @@ -0,0 +1,29 @@ +// Pack items with moving parts (curtains, roller screens, awnings, gates) and the cover entity they follow. + +import type { Building } from "../model.ts"; +import { coverReach, hasMovingParts, packItem } from "../packs.ts"; +import type { HomeAssistant } from "../types.ts"; +import { isUnavailable } from "./kinds.ts"; + +/** How far open a cover is in percent: its position, else 100 / 0 from open / closed (moving counts half). Null when unknown. */ +export function coverPosition(hass: HomeAssistant, id: string | null | undefined): number | null { + const st = id ? hass.states[id] : undefined; + if (!st || isUnavailable(st)) return null; + const position = st.attributes.current_position; + if (typeof position === "number") return Math.min(100, Math.max(0, position)); + if (st.state === "open") return 100; + if (st.state === "closed") return 0; + return st.state === "opening" || st.state === "closing" ? 50 : null; +} + +/** How far out the moving parts of every such item are (0 … 1, by furniture id). */ +export function coverReaches(hass: HomeAssistant, b: Building): Map { + const out = new Map(); + for (const f of b.floors.flatMap((floor) => floor.furniture)) { + const item = packItem(f.type); + if (!item || !hasMovingParts(item)) continue; + const position = f.cover_entity ? coverPosition(hass, f.cover_entity) : null; + out.set(f.id, coverReach(item, position !== null && f.cover_inverted ? 100 - position : position)); + } + return out; +} diff --git a/frontend/src/entities/fans.ts b/frontend/src/entities/fans.ts new file mode 100644 index 0000000..c46b070 --- /dev/null +++ b/frontend/src/entities/fans.ts @@ -0,0 +1,8 @@ +// Ceiling fans: how fast their blades turn in 3D. + +/** Turns per second of a ceiling fan's blades: faster with its speed, still while it is off. */ +export function fanSpin(st: { state: string; attributes: Record } | undefined): number { + if (!st || st.state !== "on") return 0; + const pct = typeof st.attributes.percentage === "number" ? st.attributes.percentage : 60; + return pct <= 0 ? 0 : 0.2 + (0.6 * Math.min(100, pct)) / 100; +} diff --git a/frontend/src/entities/fixtures.ts b/frontend/src/entities/fixtures.ts new file mode 100644 index 0000000..1d74b92 --- /dev/null +++ b/frontend/src/entities/fixtures.ts @@ -0,0 +1,44 @@ +// Small builders for the tests of the entities/ modules. + +import { newFloor, type Floor, type Opening, type Room } from "../model.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; + +export const entity = (entity_id: string, state: string, attributes: Record = {}): HassEntity => ({ entity_id, state, attributes }); + +interface RegistryEntry { + area_id?: string | null; + device_id?: string | null; + hidden?: boolean; + entity_category?: string | null; + name?: string | null; + translation_key?: string | null; + platform?: string | null; +} + +/** A Home Assistant with the given states and registry entries (entry key = entity id). */ +export function hassOf(states: HassEntity[], registry: Record = {}, extra: Record = {}): HomeAssistant { + return { + language: "en", + states: Object.fromEntries(states.map((s) => [s.entity_id, s])), + entities: Object.fromEntries(Object.entries(registry).map(([id, e]) => [id, { entity_id: id, ...e }])), + devices: {}, + areas: {}, + callService: async () => undefined, + ...extra, + } as unknown as HomeAssistant; +} + +export const box = (id: string, x0: number, z0: number, x1: number, z1: number, area: string | null = null): Room => ({ + id, + name: id, + area_id: area, + points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]], + floor_material: "wood", +}); + +export function floorWith(rooms: Room[], extra: Partial = {}): Floor { + return { ...newFloor("g", "Ground", 0), rooms, ...extra }; +} + +export const opening = (id: string, room: string, type: Opening["type"], extra: Partial = {}): Opening => + ({ id, room_id: room, edge: 0, offset: 1, width: 1, type, sill: 0.9, height: 1.2, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null, ...extra }) as Opening; diff --git a/frontend/src/entities/furniture-links.test.ts b/frontend/src/entities/furniture-links.test.ts new file mode 100644 index 0000000..9a46852 --- /dev/null +++ b/frontend/src/entities/furniture-links.test.ts @@ -0,0 +1,210 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { setPacks } from "../packs.ts"; +import type { Furniture } from "../model.ts"; +import { box, entity, floorWith, hassOf, opening } from "./fixtures.ts"; +import { confirmEntities, coolingTemps, deviceTempOf, fridgeDoors, furnitureEntities, hasScreen, isCooling, isMediaFurniture, outsideEntities, pictureRuleMatches, roomPanelEntities } from "./furniture-links.ts"; + +const piece = (id: string, type: string, extra: Partial = {}): Furniture => ({ id, type, x: 1, z: 1, rotation: 0, w: 1, d: 1, h: 1, variant: null, entity: null, power: null, ...extra }); +const room = box("r", 0, 0, 4, 3, "area"); +const inRoom = (...ids: string[]) => Object.fromEntries(ids.map((id) => [id, { area_id: "area" }])); + +test("a TV takes the media player of its room, a real TV before another player", () => { + const hass = hassOf([entity("media_player.speaker", "idle"), entity("media_player.living_tv", "off", { device_class: "tv" })], inRoom("media_player.speaker", "media_player.living_tv")); + const floor = floorWith([room], { furniture: [piece("tv", "tv_board")] }); + assert.equal(furnitureEntities(hass, [floor]).get("tv")?.entity, "media_player.living_tv"); +}); + +test("a desk's monitor does not take a smart speaker, but a TV board takes any player", () => { + const hass = hassOf([entity("media_player.speaker", "idle")], inRoom("media_player.speaker")); + assert.equal(furnitureEntities(hass, [floorWith([room], { furniture: [piece("desk", "desk")] })]).get("desk"), undefined); + assert.equal(furnitureEntities(hass, [floorWith([room], { furniture: [piece("tv", "tv_board")] })]).get("tv")?.entity, "media_player.speaker"); +}); + +test("appliances look for a switch or player with a fitting name, and power on the same device or by name", () => { + const hass = hassOf( + [entity("switch.dishwasher_plug", "on"), entity("switch.lamp_plug", "on"), entity("sensor.dishwasher_power", "5", { device_class: "power" })], + { "switch.dishwasher_plug": { area_id: "area", device_id: "dw" }, "switch.lamp_plug": { area_id: "area" }, "sensor.dishwasher_power": { area_id: "area", device_id: "dw" } }, + ); + const links = furnitureEntities(hass, [floorWith([room], { furniture: [piece("dw", "dishwasher")] })]).get("dw"); + assert.deepEqual(links, { entity: "switch.dishwasher_plug", power: "sensor.dishwasher_power" }); +}); + +test("a power sensor can be found by name when the entity has none on its device", () => { + const hass = hassOf([entity("sensor.fridge_power", "40", { device_class: "power" })], inRoom("sensor.fridge_power")); + assert.deepEqual(furnitureEntities(hass, [floorWith([room], { furniture: [piece("f", "fridge")] })]).get("f"), { entity: null, power: "sensor.fridge_power" }); +}); + +test("lamps take a light of the room, preferring a fitting name, and each light is used once", () => { + const hass = hassOf([entity("light.floor_standing", "on"), entity("light.main_ceiling", "on")], inRoom("light.floor_standing", "light.main_ceiling")); + const floor = floorWith([room], { furniture: [piece("a", "lamp_ceiling"), piece("b", "lamp_ceiling")] }); + const links = furnitureEntities(hass, [floor]); + assert.equal(links.get("a")?.entity, "light.main_ceiling"); + assert.equal(links.get("b")?.entity, "light.floor_standing"); +}); + +test("entities set by hand and placed devices are never taken by another piece", () => { + const hass = hassOf([entity("light.one", "on"), entity("light.two", "on")], inRoom("light.one", "light.two")); + const floor = floorWith([room], { furniture: [piece("a", "lamp_ceiling", { entity: "light.one" }), piece("b", "lamp_ceiling")], placements: [] }); + assert.equal(furnitureEntities(hass, [floor]).get("b")?.entity, "light.two"); + const placed = floorWith([room], { furniture: [piece("c", "lamp_ceiling")], placements: [{ entity_id: "light.one", x: 0, z: 0, y: null, mount: null }] }); + assert.equal(furnitureEntities(hass, [placed]).get("c")?.entity, "light.two"); +}); + +test("'none' keeps a piece unlinked and a piece outside every room finds nothing", () => { + const hass = hassOf([entity("light.one", "on")], inRoom("light.one")); + assert.equal(furnitureEntities(hass, [floorWith([room], { furniture: [piece("a", "lamp_ceiling", { entity: "none" })] })]).get("a"), undefined); + assert.equal(furnitureEntities(hass, [floorWith([room], { furniture: [piece("a", "lamp_ceiling", { x: 20, z: 20 })] })]).get("a"), undefined); +}); + +test("a robot vacuum and a radiator find their own kind in the room's area", () => { + const hass = hassOf([entity("vacuum.rob", "docked"), entity("climate.heater", "heat"), entity("climate.other", "off")], { "vacuum.rob": { area_id: "area" }, "climate.heater": { area_id: "area" }, "climate.other": { area_id: "elsewhere" } }); + const links = furnitureEntities(hass, [floorWith([room], { furniture: [piece("v", "robot_vacuum"), piece("r", "radiator")] })]); + assert.equal(links.get("v")?.entity, "vacuum.rob"); + assert.equal(links.get("r")?.entity, "climate.heater"); +}); + +test("a climate pack item finds a climate entity in its room's area", () => { + setPacks([ + { + id: "test.hvac", + name: "HVAC", + publisher: "Test", + items: [ + { + id: "mini_split", + name: { en: "Mini split" }, + size: [0.9, 0.22, 0.28], + climate: true, + parts: [{ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body" }], + }, + ], + }, + ]); + const hass = hassOf( + [entity("climate.ac", "cool"), entity("switch.plug", "on")], + inRoom("climate.ac", "switch.plug"), + ); + const floor = floorWith([room], { + furniture: [piece("ac", "pack:test.hvac:mini_split")], + }); + assert.equal(furnitureEntities(hass, [floor]).get("ac")?.entity, "climate.ac"); + setPacks([]); +}); + +test("screens: built-in TVs and a few devices have one", () => { + assert.equal(isMediaFurniture("tv_wall"), true); + assert.equal(isMediaFurniture("sofa"), false); + assert.equal(hasScreen("desk"), true); + assert.equal(hasScreen("fridge_smart"), true); + assert.equal(hasScreen("sofa"), false); +}); + +test("picture rules: equal, contained (3+ letters), wildcard, attribute, missing", () => { + const hass = hassOf([entity("media_player.tv", "playing", { app_name: "YouTube TV", volume: 0.5 })]); + const rule = (state: string, attribute?: string) => ({ entity: "media_player.tv", state, attribute }); + assert.equal(pictureRuleMatches(hass, rule("playing")), true); + assert.equal(pictureRuleMatches(hass, rule("PLAY")), true); + assert.equal(pictureRuleMatches(hass, rule("pl")), false, "too short to match inside"); + assert.equal(pictureRuleMatches(hass, rule("*")), true); + assert.equal(pictureRuleMatches(hass, rule("youtube", "app_name")), true); + assert.equal(pictureRuleMatches(hass, rule("x", "nothing")), false); + assert.equal(pictureRuleMatches(hass, { entity: "media_player.gone", state: "*" }), false); +}); + +test("entities that ask first: placed devices, linked furniture and marked blinds", () => { + const hass = hassOf([entity("light.a", "on"), entity("cover.blind", "open", { device_class: "shutter" }), entity("switch.s", "on")], { "light.a": { area_id: "area" }, "cover.blind": { area_id: "area" }, "switch.s": { area_id: "area" } }); + const floor = floorWith([room], { + placements: [{ entity_id: "light.a", x: 0, z: 0, y: null, mount: null, confirm: true }], + openings: [opening("w", "r", "window", { confirm: true } as never)], + furniture: [piece("sw", "kitchen", { entity: "switch.s", confirm: true })], + }); + assert.deepEqual([...confirmEntities(hass, [floor])].sort(), ["cover.blind", "light.a", "switch.s"]); +}); + +test("a smart fridge's doors follow their sensors, unset or none means closed", () => { + const hass = hassOf([entity("binary_sensor.l", "on"), entity("binary_sensor.r", "open"), entity("binary_sensor.x", "off")]); + const floor = floorWith([room], { furniture: [piece("f1", "fridge_smart", { door_left: "binary_sensor.l", door_right: "none" }), piece("f2", "fridge_smart", { door_right: "binary_sensor.r" }), piece("f3", "fridge")] }); + const doors = fridgeDoors(hass, [floor]); + assert.deepEqual(doors.get("f1"), { left: true, right: false }); + assert.deepEqual(doors.get("f2"), { left: false, right: true }); + assert.equal(doors.has("f3"), false); +}); + +test("the room panel shows placed and linked entities, own picks and door sensors, minus hidden ones", () => { + const hass = hassOf( + [entity("light.placed", "on"), entity("light.lamp", "on", { friendly_name: "Ceiling lamp" }), entity("light.picked", "on"), entity("light.hidden", "on"), entity("binary_sensor.door", "off", { device_class: "door" }), entity("sensor.rest", "1", { device_class: "temperature" })], + inRoom("light.placed", "light.lamp", "light.picked", "light.hidden", "binary_sensor.door", "sensor.rest"), + ); + const r = { ...room, panel: ["light.picked", "light.gone"], hidden: ["light.hidden"] }; + const floor = floorWith([r], { placements: [{ entity_id: "light.placed", x: 1, z: 1, y: null, mount: null }], furniture: [piece("l", "lamp_ceiling")], openings: [opening("d", "r", "door")] }); + const { shown, more } = roomPanelEntities(hass, floor, r); + assert.deepEqual(shown.sort(), ["binary_sensor.door", "light.lamp", "light.picked", "light.placed"]); + assert.deepEqual(more, ["sensor.rest"]); +}); + +test("a fridge shows its compartments' temperatures and warns when one is too warm", () => { + const fmt = (c: number) => `${c.toFixed(1)} °C`; + const hass = hassOf([ + entity("sensor.fridge", "4.2", { unit_of_measurement: "°C" }), + entity("sensor.freezer", "-18", { unit_of_measurement: "°C" }), + entity("sensor.warm", "9.1", { unit_of_measurement: "°C" }), + entity("sensor.thawing", "-10", { unit_of_measurement: "°C" }), + entity("sensor.fahrenheit", "50", { unit_of_measurement: "°F" }), + entity("sensor.gone", "unavailable"), + ]); + assert.deepEqual(coolingTemps(hass, { temp_entity: "sensor.fridge", temp_entity2: "sensor.freezer" }, fmt), { text: "4.2 °C · -18.0 °C", warm: false }); + assert.equal(coolingTemps(hass, { temp_entity: "sensor.warm" }, fmt)?.warm, true); + assert.equal(coolingTemps(hass, { temp_entity2: "sensor.thawing" }, fmt)?.warm, true); + // 50 °F are 10 °C: too warm for a fridge + assert.deepEqual(coolingTemps(hass, { temp_entity: "sensor.fahrenheit" }, fmt), { text: "10.0 °C", warm: true }); + assert.equal(coolingTemps(hass, { temp_entity: "sensor.gone" }, fmt), null); + assert.equal(coolingTemps(hass, { temp_entity: "none" }, fmt), null); + assert.equal(isCooling("fridge"), true); + assert.equal(isCooling("pack:nextfloor.a_kueche:fridge_freezer"), true); + assert.equal(isCooling("pack:nextfloor.a_kueche:oven"), false); +}); + +test("Outside lists what stands outside the rooms and what belongs to it; the room below no longer counts a roof device", () => { + const hass = hassOf([entity("switch.valve", "off"), entity("sensor.weather", "12"), entity("light.inside", "on")]); + const floor = floorWith([room], { + placements: [ + { entity_id: "switch.valve", x: 9, z: 9, y: null, mount: null }, + { entity_id: "sensor.weather", x: 1, z: 1, y: null, mount: null, outside: true }, + { entity_id: "light.inside", x: 2, z: 2, y: null, mount: null }, + ], + }); + assert.deepEqual(outsideEntities(hass, [floor]).sort(), ["sensor.weather", "switch.valve"]); + assert.deepEqual(outsideEntities(hass, [floor], ["switch.valve"]), ["sensor.weather"], "a hidden device is left out (#83)"); + assert.deepEqual(roomPanelEntities(hass, floor, room).shown, ["light.inside"], "the weather station is not the room's"); +}); + +test("Outside lists the devices of the areas linked to gardens and pools, and a pool's pump", () => { + const hass = hassOf([entity("light.terrace", "on"), entity("switch.pool_pump", "off"), entity("sensor.pool_water", "24", { device_class: "temperature" })], { "light.terrace": { area_id: "terrasse" } }); + const floor = floorWith([box("r", 0, 0, 4, 4)], { + outdoor: [ + { id: "t", type: "terrace", points: [[5, 0], [8, 0], [8, 3], [5, 3]], area_id: "terrasse" }, + { id: "p", type: "pool", points: [[9, 0], [12, 0], [12, 3], [9, 3]], pump_entity: "switch.pool_pump", temp_entity: "sensor.pool_water" }, + ], + }); + assert.deepEqual(outsideEntities(hass, [floor]).sort(), ["light.terrace", "sensor.pool_water", "switch.pool_pump"]); +}); + +test("a smart speaker takes the only free media player of its room, not a TV (#104)", () => { + setPacks([{ id: "test.hifi", name: "Hifi", publisher: "Test", items: [{ id: "smart_speaker_ball", name: { en: "Smart speaker" }, size: [0.12, 0.12, 0.12], electric: true, parts: [{ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body" }] }] }]); + const speaker = piece("sp", "pack:test.hifi:smart_speaker_ball"); + const only = hassOf([entity("media_player.echo", "idle")], inRoom("media_player.echo")); + assert.equal(furnitureEntities(only, [floorWith([room], { furniture: [speaker] })]).get("sp")?.entity, "media_player.echo"); + const two = hassOf([entity("media_player.echo", "idle"), entity("media_player.other", "idle")], inRoom("media_player.echo", "media_player.other")); + assert.equal(furnitureEntities(two, [floorWith([room], { furniture: [speaker] })]).get("sp")?.entity ?? null, null, "two players: no guess"); + setPacks([]); +}); + +test("a device's own thermometer reads in Celsius, Fahrenheit turned over, nothing without a number (#112)", () => { + const hass = hassOf([entity("sensor.inverter_temp", "41.5", { unit_of_measurement: "°C" }), entity("sensor.pc_temp", "122", { unit_of_measurement: "°F" }), entity("sensor.gone", "unavailable")]); + assert.equal(deviceTempOf(hass, "sensor.inverter_temp"), 41.5); + assert.equal(deviceTempOf(hass, "sensor.pc_temp"), 50); + assert.equal(deviceTempOf(hass, "sensor.gone"), null); + assert.equal(deviceTempOf(hass, "none"), null); + assert.equal(deviceTempOf(hass, null), null); +}); diff --git a/frontend/src/entities/furniture-links.ts b/frontend/src/entities/furniture-links.ts new file mode 100644 index 0000000..992a397 --- /dev/null +++ b/frontend/src/entities/furniture-links.ts @@ -0,0 +1,279 @@ +// Electric furniture and the entities it is linked to: TVs, fridges, lamps, a robot vacuum. Links can be set by +// hand; otherwise they are found among the entities of the room the piece stands in, by their names. + +import { pointInPolygon, type EntityRef, type Floor, type Room } from "../model.ts"; +import { isClimateFurniture, packItem, packScreen } from "../packs.ts"; +import type { HomeAssistant } from "../types.ts"; +import { entityName, kindOf } from "./kinds.ts"; +import { openingEntities } from "./openings.ts"; +import { areaEntities, roomEntities, entityAreaId, isPower, powerSensorsOf, primaryEntities } from "./registry.ts"; + +const TV_NAME = /\b(tv|fernseh|television|fire ?tv|apple ?tv|chromecast|shield)/i; +const COOLING_NAME = /(kühl|fridge|gefrier|freezer)/i; +const DISHWASHER_NAME = /(spülmaschine|geschirrspül|dishwasher)/i; +const HOB_NAME = /(kochfeld|herd|induktion|cooktop)/i; + +/** Name patterns of the entities that belong to a piece of electric furniture. */ +const FURNITURE_NAMES: Record = { + robot_vacuum: /(saug|vacuum|robo|roomba|roborock|dreame|ecovacs|deebot)/i, + tv_board: TV_NAME, + tv_wall: TV_NAME, + desk: /\b(pc|computer|rechner|desktop|monitor|workstation)/i, + fridge: COOLING_NAME, + fridge_smart: COOLING_NAME, + stove: /(herd|kochfeld|cooktop|stove|induktion)/i, + kitchen_tall: /(backofen|oven|ofen)/i, + dishwasher: DISHWASHER_NAME, + washer: /(waschmaschine|washer|washing)/i, + dryer: /(trockner|dryer)/i, + kitchen: /(kaffee|coffee|wasserkocher|kettle)/i, + island: HOB_NAME, + sink: DISHWASHER_NAME, + radiator: /(heiz|radiator|thermostat|climate|hk|trv)/i, +}; + +/** Name hints for choosing a lamp's light: one that fits the name wins, else any free one. */ +const LAMP_NAMES: Record = { + lamp_ceiling: /(decke|ceiling|haupt|main)/i, + lamp_downlight: /(spot|strahler|downlight|einbau)/i, + lamp_spot: /(spot|strahler)/i, + lamp_panel: /(panel|decke|ceiling)/i, + lamp_uplight: /(fluter|uplight|steh)/i, + lamp_bollard: /(weg|garten|garden|path|poller|außen|aussen|outdoor)/i, + lamp_garden: /(garten|garden|spot|außen|aussen|outdoor|baum|tree)/i, + lamp_pendant: /(pendel|pendant|hänge|esstisch|dining)/i, + ceiling_fan: /(ventilator|fan)/i, + lamp_floor: /(steh|floor)/i, + lamp_table: /(tisch|nacht|table|bedside|lese|reading)/i, + lamp_wall: /(wand|wall)/i, + led_strip: /(led|strip|streifen|leiste|band)/i, +}; + +const TV_FURNITURE = new Set(["tv_board", "tv_wall"]); + +export interface FurnitureLinks { + entity: string | null; + power: string | null; + /** Ceiling fan: its fan entity. */ + fan?: string | null; +} + +/** Whether a rule of a screen picture holds now: the state or attribute equals the value or contains it (3+ letters); "*" always. */ +export function pictureRuleMatches(hass: HomeAssistant, rule: { entity: string; attribute?: string | null; state: string }): boolean { + const state = hass.states[rule.entity]; + if (!state) return false; + const raw = rule.attribute ? state.attributes[rule.attribute] : state.state; + if (raw === undefined || raw === null) return false; + const wanted = rule.state.trim().toLowerCase(); + const actual = String(raw).toLowerCase(); + return wanted === "*" || actual === wanted || (wanted.length >= 3 && actual.includes(wanted)); +} + +/** Furniture that shows a media player on a screen: the built-in TVs and pack items with a screen part. */ +export const isMediaFurniture = (type: string): boolean => TV_FURNITURE.has(type) || !!packScreen(type); + +/** Speakers without a screen (smart speakers, hi-fi, multiroom): they link to a media player for volume and playback. */ +export const isSpeakerFurniture = (type: string): boolean => !!packItem(type)?.electric && /speaker|multiroom|soundbar/.test(type.split(":").pop() ?? type); + +/** Furniture whose screen can show a media player or a picture rule: media furniture, a desk's monitor, a smart fridge's display. */ +export const hasScreen = (type: string): boolean => isMediaFurniture(type) || type === "desk" || type === "fridge_smart"; + +const isSet = (ref: string | null | undefined): ref is string => !!ref && ref !== "none"; + +/** The power sensor of an entity: itself, or another power sensor on its device. */ +function powerOfDevice(hass: HomeAssistant, id: string): string | null { + if (isPower(hass, id)) return id; + const device = hass.entities?.[id]?.device_id; + return device ? (powerSensorsOf(hass, device).find((e) => e !== id) ?? null) : null; +} + +const roomOf = (floor: Floor, x: number, z: number): Room | undefined => floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([x, z], r.points)); + +/** The best-fitting free entity of a kind for a name pattern; with `fallback`, the first free one when none fits. */ +function pickByName(candidates: string[], pattern: RegExp | undefined, describe: (id: string) => string, fallback: boolean): string | null { + return candidates.find((id) => pattern?.test(describe(id))) ?? (fallback ? (candidates[0] ?? null) : null); +} + +/** + * The entities of electric furniture. Set by hand, or (when unset) found in the area of the room the piece stands in: + * lamps get a light, radiators a thermostat, TVs a media player (a real TV first), other appliances an entity whose + * name fits. The power sensor comes from the same device or from a sensor whose name fits. Every entity is used once. + */ +export function furnitureEntities(hass: HomeAssistant, floors: readonly Floor[]): Map { + const links = new Map(); + for (const floor of floors) { + // entities set by hand and devices placed in the plan (an Echo Show in the corner) are taken already + const used = new Set( + [...floor.furniture.flatMap((f) => [f.entity, f.power, f.fan_entity]), ...floor.placements.map((p) => p.entity_id)].filter(isSet), + ); + for (const piece of floor.furniture) { + const isLamp = piece.type in LAMP_NAMES; + const isClimate = isClimateFurniture(piece.type); + const pattern = isLamp ? LAMP_NAMES[piece.type] : FURNITURE_NAMES[piece.type]; + if (!pattern && !isClimate && !isSpeakerFurniture(piece.type) && piece.entity == null && piece.power == null) continue; + const room = roomOf(floor, piece.x, piece.z); + const free = (room ? primaryEntities(hass, roomEntities(hass, room)) : []).filter((id) => !used.has(id)); + const describe = (id: string) => `${id} ${entityName(hass, id)}`; + const ofKind = (kind: string) => free.filter((id) => kindOf(id) === kind); + + let entity: string | null = piece.entity === "none" ? null : (piece.entity ?? null); + if (piece.entity == null) { + if (piece.type === "ceiling_fan") { + // the fan's light kit: a light on the same device as a free fan, or one whose name fits (a fan without light takes none) + const all = (room ? roomEntities(hass, room) : []).filter((id) => !used.has(id)); + const devices = new Set(all.filter((id) => kindOf(id) === "fan").map((id) => hass.entities?.[id]?.device_id).filter(Boolean)); + entity = all.find((id) => kindOf(id) === "light" && devices.has(hass.entities?.[id]?.device_id)) ?? pickByName(ofKind("light"), pattern, describe, false); + } else if (isLamp) entity = pickByName(ofKind("light"), pattern, describe, true); + else if (piece.type === "robot_vacuum") { + // vacuums are not a device kind of their own, so they are looked up in the room's area directly + const area = room?.area_id ?? null; + entity = Object.keys(hass.entities ?? {}).find((id) => id.startsWith("vacuum.") && !used.has(id) && entityAreaId(hass, id) === area) ?? null; + } else if (piece.type === "radiator" || isClimate) entity = pickByName(ofKind("climate"), pattern, describe, true); + else if (isMediaFurniture(piece.type)) { + const players = ofKind("media"); + // a TV takes the TV (or any player of the room); a monitor or smart speaker only a player whose name fits + entity = players.find((id) => hass.states[id]?.attributes.device_class === "tv") ?? pickByName(players, pattern, describe, TV_FURNITURE.has(piece.type)); + } else if (isSpeakerFurniture(piece.type)) { + // a speaker takes a player whose name fits, else the only free player of its room (#104) + const players = ofKind("media").filter((id) => hass.states[id]?.attributes.device_class !== "tv"); + entity = pickByName(players, pattern, describe, false) ?? (players.length === 1 ? players[0] : null); + } else if (pattern) entity = free.find((id) => ["switch", "media", "fan"].includes(kindOf(id) ?? "") && pattern.test(describe(id))) ?? null; + if (entity) used.add(entity); + } + + let power: string | null = piece.power === "none" ? null : (piece.power ?? null); + if (piece.power == null) { + power = entity ? powerOfDevice(hass, entity) : null; + if (!power && pattern && room && !isLamp) power = roomEntities(hass, room).find((id) => isPower(hass, id) && !used.has(id) && pattern.test(describe(id))) ?? null; + if (power) used.add(power); + } + // a ceiling fan's fan: on the light's device first, else a free fan of the room + let fan: string | null = null; + if (piece.type === "ceiling_fan") { + fan = piece.fan_entity === "none" ? null : (piece.fan_entity ?? null); + if (piece.fan_entity == null) { + // every fan of the area: the light kit's device may count as one device with the light, which only keeps one of them + const fans = (room ? roomEntities(hass, room) : []).filter((id) => kindOf(id) === "fan" && !used.has(id)); + const device = entity ? hass.entities?.[entity]?.device_id : undefined; + fan = (device ? fans.find((id) => hass.entities?.[id]?.device_id === device) : undefined) ?? fans[0] ?? null; + if (fan) used.add(fan); + } + } + if (entity || power || fan) links.set(piece.id, { entity, power, ...(piece.type === "ceiling_fan" ? { fan } : {}) }); + } + } + return links; +} + +/** Entities that ask before they are switched: placed devices, and furniture, blinds and garage doors marked "ask first". */ +export function confirmEntities(hass: HomeAssistant, floors: readonly Floor[]): Set { + const asking = new Set(); + const furnitureLinks = furnitureEntities(hass, floors); + const openingLinks = floors.some((f) => f.openings.some((o) => o.confirm)) ? openingEntities(hass, floors) : null; + for (const floor of floors) { + for (const placed of floor.placements) if (placed.confirm) asking.add(placed.entity_id); + for (const opening of floor.openings) { + const cover = opening.confirm ? openingLinks?.get(opening.id)?.cover : null; + if (isSet(cover)) asking.add(cover); + } + for (const piece of floor.furniture) { + const entity = piece.confirm ? furnitureLinks.get(piece.id)?.entity : null; + if (isSet(entity)) asking.add(entity); + } + } + return asking; +} + +/** Fridges and freezers (also pack items named so): they can show the temperatures of their compartments. */ +export const isCooling = (type: string): boolean => type === "fridge" || type === "fridge_smart" || /(fridge|freezer|kuehl|gefrier|chest_freezer)/.test(type.slice(type.lastIndexOf(":") + 1)); + +/** Above these a fridge and a freezer count as too warm (°C). */ +export const FRIDGE_WARM = 8; +export const FREEZER_WARM = -12; + +/** + * The temperatures a fridge shows: its fridge and freezer compartment ("4.2 °C · −18.0 °C"), and whether one is too warm. + * Null when no sensor is set or none tells a number. + */ +export function coolingTemps(hass: HomeAssistant, piece: { temp_entity?: string | null; temp_entity2?: string | null }, format: (celsius: number) => string): { text: string; warm: boolean } | null { + const read = (id: string | null | undefined): number | null => { + if (!isSet(id)) return null; + const st = hass.states[id]; + const value = st ? Number(st.state) : NaN; + if (!Number.isFinite(value)) return null; + // a sensor in Fahrenheit is turned into Celsius, so the limits hold + return st!.attributes.unit_of_measurement === "°F" ? ((value - 32) * 5) / 9 : value; + }; + const fridge = read(piece.temp_entity); + const freezer = read(piece.temp_entity2); + if (fridge === null && freezer === null) return null; + const parts = [fridge, freezer].filter((v): v is number => v !== null).map(format); + return { text: parts.join(" · "), warm: (fridge !== null && fridge > FRIDGE_WARM) || (freezer !== null && freezer > FREEZER_WARM) }; +} + +/** A device runs hot from this temperature (°C): its pin is marked like a running one (#112). */ +export const DEVICE_HOT = 60; + +/** A device's own thermometer in °C (a sensor in Fahrenheit is turned into Celsius); null when none is set or it tells no number. */ +export function deviceTempOf(hass: HomeAssistant, id: string | null | undefined): number | null { + if (!isSet(id)) return null; + const st = hass.states[id]; + const value = st ? Number(st.state) : NaN; + if (!Number.isFinite(value)) return null; + return st!.attributes.unit_of_measurement === "°F" ? ((value - 32) * 5) / 9 : value; +} + +/** Which doors of each smart fridge stand open now (a door sensor that says "on" or "open"). */ +export function fridgeDoors(hass: HomeAssistant, floors: readonly Floor[]): Map { + const isOpen = (sensor: EntityRef | undefined) => isSet(sensor) && ["on", "open"].includes(hass.states[sensor]?.state ?? ""); + const doors = new Map(); + for (const piece of floors.flatMap((f) => f.furniture)) if (piece.type === "fridge_smart") doors.set(piece.id, { left: isOpen(piece.door_left), right: isOpen(piece.door_right) }); + return doors; +} + +/** + * The entities of a room's panel: what the plan shows in the room (placed devices, linked furniture, the blinds and + * contacts of its doors and windows) plus those picked for the panel. `more` are the other entities of the room's + * area, offered on request. Entities the editor hid for the room never appear. + */ +export function roomPanelEntities(hass: HomeAssistant, floor: Floor, room: Room): { shown: string[]; more: string[] } { + const inside = (x: number, z: number) => pointInPolygon([x, z], room.points); + const furnitureLinks = furnitureEntities(hass, [floor]); + const openingLinks = openingEntities(hass, [floor]); + const hidden = new Set(room.hidden ?? []); + const candidates = [ + ...floor.placements.filter((p) => !p.outside && inside(p.x, p.z)).map((p) => p.entity_id), + ...floor.furniture.filter((f) => inside(f.x, f.z)).flatMap((f) => [furnitureLinks.get(f.id)?.entity, furnitureLinks.get(f.id)?.power]), + ...floor.openings + .filter((o) => o.room_id === room.id) + .flatMap((o) => { + const e = openingLinks.get(o.id); + return e ? [e.cover, e.contact, e.tilt, e.contact2] : []; + }), + ...(room.panel ?? []), + ]; + const shown = [...new Set(candidates.filter((id): id is string => !!id && !!hass.states[id]))].filter((id) => !hidden.has(id)); + const isShown = new Set(shown); + return { shown, more: roomEntities(hass, room).filter((id) => !isShown.has(id) && !hidden.has(id)) }; +} + + +/** + * Outside: the devices placed outside every room outline (the garden's valves and lights, a mower, the grid connection + * outside), and those marked as belonging to Outside wherever they stand (a weather station on the roof), on all floors. + */ +export function outsideEntities(hass: HomeAssistant, floors: readonly Floor[], hidden: readonly string[] = []): string[] { + const out: (string | null | undefined)[] = []; + for (const floor of floors) { + const indoors = (x: number, z: number) => floor.rooms.some((room) => room.points.length >= 3 && pointInPolygon([x, z], room.points)); + const links = furnitureEntities(hass, [floor]); + out.push(...floor.placements.filter((p) => p.outside || !indoors(p.x, p.z)).map((p) => p.entity_id)); + out.push(...floor.furniture.filter((f) => !indoors(f.x, f.z)).flatMap((f) => [links.get(f.id)?.entity, links.get(f.id)?.power])); + // gardens, terraces and pools linked to a Home Assistant area bring that area's devices, and a pool its pump and thermometer + for (const a of floor.outdoor ?? []) { + if (a.area_id) out.push(...primaryEntities(hass, areaEntities(hass, a.area_id))); + out.push(a.pump_entity, a.temp_entity); + } + } + return [...new Set(out.filter((id): id is string => !!id && !!hass.states[id] && !hidden.includes(id)))]; +} diff --git a/frontend/src/entities/gangs.test.ts b/frontend/src/entities/gangs.test.ts new file mode 100644 index 0000000..7c8dcd7 --- /dev/null +++ b/frontend/src/entities/gangs.test.ts @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, hassOf } from "./fixtures.ts"; +import { gangEntities, gangGlows } from "./gangs.ts"; + +const hass = hassOf([ + entity("light.ceiling", "on", { brightness: 255, rgb_color: [255, 0, 0] }), + entity("light.off", "off"), + entity("switch.kettle", "on", { current_power_w: 1600 }), + entity("switch.lamp", "on", { current_power_w: 4 }), + entity("switch.gone", "unavailable"), +]); + +test("a button linked to a light glows in the light's colour; one that is off stays dark", () => { + const glows = gangGlows(hass, ["light.ceiling", "light.off"], false); + assert.equal(glows.length, 1); + assert.equal(glows[0].gang, 0); + assert.deepEqual(glows[0].color.map((c) => Math.round(c * 10) / 10), [1, 0, 0]); +}); + +test("a socket glows green, brighter the more it draws", () => { + const [kettle, lamp] = gangGlows(hass, ["switch.kettle", "switch.lamp"], true); + assert.deepEqual([kettle.gang, lamp.gang], [0, 1]); + assert.ok(kettle.color[1] > kettle.color[0], "green"); + assert.ok(kettle.level > lamp.level); +}); + +test("empty, 'none' and unavailable buttons are left out but keep the others in place", () => { + const glows = gangGlows(hass, [null, "none", "switch.gone", "switch.kettle"], false); + assert.deepEqual(glows.map((g) => g.gang), [3]); + assert.deepEqual(gangEntities([null, "switch.a", "none", "switch.b", "switch.c"], 4), ["switch.a", "switch.b"]); + assert.deepEqual(gangEntities(undefined, 2), []); +}); diff --git a/frontend/src/entities/gangs.ts b/frontend/src/entities/gangs.ts new file mode 100644 index 0000000..ab1aef7 --- /dev/null +++ b/frontend/src/entities/gangs.ts @@ -0,0 +1,47 @@ +// Light switches and sockets with several buttons (gangs): which of them glow, and in what colour. + +import type { HomeAssistant } from "../types.ts"; +import { isActive, isUnavailable, kindOf, lightGlow, type Rgb } from "./kinds.ts"; + +export interface GangGlow { + gang: number; + color: Rgb; + level: number; +} + +const SOCKET_GREEN: Rgb = [0.25, 0.9, 0.45]; +const SWITCH_WARM: Rgb = [1, 0.82, 0.55]; + +/** The power a socket's entity draws, if it reports one (W): its own state for a power sensor, else a power attribute. */ +function drawn(hass: HomeAssistant, id: string): number | null { + const st = hass.states[id]; + const value = Number(st?.attributes.current_power_w ?? st?.attributes.power ?? NaN); + return Number.isFinite(value) ? value : null; +} + +/** + * The glowing buttons of a switch plate or socket. A button linked to a light glows in the light's colour and brightness; anything + * else that is on glows warm on a switch and green on a socket, brighter the more it draws. + */ +export function gangGlows(hass: HomeAssistant, entities: readonly (string | null | undefined)[], socket: boolean): GangGlow[] { + const out: GangGlow[] = []; + entities.forEach((id, gang) => { + if (!id || id === "none") return; + const st = hass.states[id]; + if (!st || isUnavailable(st)) return; + if (kindOf(id) === "light") { + const lit = lightGlow(st); + if (lit) out.push({ gang, color: lit.color, level: lit.level }); + return; + } + if (!isActive(st) && st.state !== "on") return; + const watts = socket ? drawn(hass, id) : null; + const level = watts === null ? 0.8 : Math.min(1, 0.45 + Math.sqrt(Math.max(0, watts)) / 40); + out.push({ gang, color: socket ? SOCKET_GREEN : SWITCH_WARM, level }); + }); + return out; +} + +/** The entities of a plate that can be switched, in button order. */ +export const gangEntities = (entities: readonly (string | null | undefined)[] | undefined, gangs: number): string[] => + (entities ?? []).slice(0, gangs).filter((id): id is string => !!id && id !== "none"); diff --git a/frontend/src/entities/gates.test.ts b/frontend/src/entities/gates.test.ts new file mode 100644 index 0000000..53042d0 --- /dev/null +++ b/frontend/src/entities/gates.test.ts @@ -0,0 +1,19 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, newFloor, type OutdoorArea } from "../model.ts"; +import { entity, hassOf } from "./fixtures.ts"; +import { gateStates } from "./gates.ts"; + +test("a gate is open while its entity says open, on or unlocked, or its contact is on", () => { + const b = emptyBuilding(); + const f = newFloor("g", "G", 0); + f.outdoor = [{ id: "z", type: "fence", points: [[0, 0], [8, 0], [8, 4], [0, 4]], gates: [ + { id: "a", edge: 0, offset: 2, width: 1, kind: "single", entity: "cover.tor" }, + { id: "b", edge: 1, offset: 2, width: 1, kind: "single", contact: "binary_sensor.tor_kontakt" }, + { id: "c", edge: 2, offset: 2, width: 1, kind: "sliding", entity: "switch.schiebetor", contact: "binary_sensor.x" }, + { id: "d", edge: 3, offset: 2, width: 1, kind: "single" }, + ] } as OutdoorArea]; + b.floors = [f]; + const states = gateStates(hassOf([entity("cover.tor", "open"), entity("binary_sensor.tor_kontakt", "on"), entity("switch.schiebetor", "off"), entity("binary_sensor.x", "off")]), b); + assert.deepEqual([...states], [["a", true], ["b", true], ["c", false]], "a gate without any entity has no state"); +}); diff --git a/frontend/src/entities/gates.ts b/frontend/src/entities/gates.ts new file mode 100644 index 0000000..8d731d4 --- /dev/null +++ b/frontend/src/entities/gates.ts @@ -0,0 +1,21 @@ +// Gates in fences: whether each is open, from the entity that drives it (cover open, switch on, lock unlocked) or its contact (on = open). + +import type { Building } from "../model.ts"; +import type { HomeAssistant } from "../types.ts"; + +/** Gate id → open, for every gate of every fence that has an entity or a contact with a state. */ +export function gateStates(hass: HomeAssistant, building: Building): Map { + const out = new Map(); + for (const floor of building.floors) { + for (const area of floor.outdoor ?? []) { + for (const gate of area.gates ?? []) { + const driver = gate.entity ? hass.states[gate.entity]?.state : undefined; + const contact = gate.contact ? hass.states[gate.contact]?.state : undefined; + if (driver === undefined && contact === undefined) continue; + const byDriver = driver === "open" || driver === "opening" || driver === "on" || driver === "unlocked" || driver === "unlocking"; + out.set(gate.id, byDriver || contact === "on"); + } + } + } + return out; +} diff --git a/frontend/src/entities/household.test.ts b/frontend/src/entities/household.test.ts new file mode 100644 index 0000000..5a985d3 --- /dev/null +++ b/frontend/src/entities/household.test.ts @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, hassOf } from "./fixtures.ts"; +import { hasPost, pickupDays, plantThirst, remainingMinutes } from "./household.ts"; + +const now = new Date(2026, 9, 26, 9, 30).getTime(); // Monday 26 October 2026 + +test("a bin's next pickup from all the ways sensors write it", () => { + assert.equal(pickupDays(entity("sensor.bin", "3"), now), 3); + assert.equal(pickupDays(entity("sensor.bin", "irgendwas", { daysTo: 2 }), now), 2, "Waste Collection Schedule's daysTo"); + assert.equal(pickupDays(entity("sensor.bin", "Heute"), now), 0); + assert.equal(pickupDays(entity("sensor.bin", "morgen"), now), 1); + assert.equal(pickupDays(entity("sensor.bin", "Übermorgen"), now), 2); + assert.equal(pickupDays(entity("sensor.bin", "Mo, 02.11.2026"), now), 7, "a date with numbers in it is a date, not 2 days"); + assert.equal(pickupDays(entity("sensor.bin", "2026-10-29"), now), 3); + assert.equal(pickupDays(entity("sensor.bin", "29.10."), now), 3); + assert.equal(pickupDays(entity("sensor.bin", "Restabfall in 4 Tagen"), now), 4); + assert.equal(pickupDays(entity("sensor.bin", "unknown"), now), null); + assert.equal(pickupDays(entity("sensor.bin", "keine Termine"), now), null); +}); + +test("post in the mailbox", () => { + assert.equal(hasPost(entity("binary_sensor.mail", "on")), true); + assert.equal(hasPost(entity("binary_sensor.mail", "off")), false); + assert.equal(hasPost(entity("sensor.mail", "Post")), true); + assert.equal(hasPost(entity("sensor.mail", "unavailable")), false); +}); + +test("a plant is thirsty below its threshold", () => { + assert.deepEqual(plantThirst(entity("sensor.soil", "12")), { moisture: 12, thirsty: true }); + assert.deepEqual(plantThirst(entity("sensor.soil", "35")), { moisture: 35, thirsty: false }); + assert.equal(plantThirst(entity("sensor.soil", "35"), 40)?.thirsty, true); + assert.equal(plantThirst(entity("sensor.soil", "unknown")), null); +}); + +test("an appliance's time left from a duration or an end time on its device", () => { + const hass = hassOf([ + entity("sensor.washer_remaining_time", "25", { unit_of_measurement: "min" }), + entity("sensor.dryer_programmende", new Date(now + 90 * 60000).toISOString(), { device_class: "timestamp" }), + entity("sensor.dish_rest", "1:05:00"), + entity("sensor.washer_power", "1800", { unit_of_measurement: "W" }), + ]); + assert.equal(remainingMinutes(hass, ["sensor.washer_power", "sensor.washer_remaining_time"], now), 25); + assert.equal(remainingMinutes(hass, ["sensor.dryer_programmende"], now), 90); + assert.equal(remainingMinutes(hass, ["sensor.dish_rest"], now), 65); + assert.equal(remainingMinutes(hass, ["sensor.washer_power"], now), null, "a power sensor is no time left"); +}); diff --git a/frontend/src/entities/household.ts b/frontend/src/entities/household.ts new file mode 100644 index 0000000..737453d --- /dev/null +++ b/frontend/src/entities/household.ts @@ -0,0 +1,105 @@ +// The household: waste bins that know their next pickup, a mailbox with post in it, thirsty plants, and the time a washer, dryer or +// dishwasher has left. Pure readings of entity states; the 3D view turns them into pins, texts and glows. + +import type { HassEntity, HomeAssistant } from "../types.ts"; +import { isUnavailable } from "./kinds.ts"; + +const DAY = 86_400_000; +const startOfDay = (t: number) => { + const d = new Date(t); + d.setHours(0, 0, 0, 0); + return d.getTime(); +}; + +/** A date written in a state: ISO (2026-10-29), German (29.10.2026, 29.10.) or US (10/29/2026); null when there is none. */ +function dateIn(text: string, now: number): number | null { + let m = /(\d{4})-(\d{2})-(\d{2})/.exec(text); + if (m) return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])).getTime(); + m = /(\d{1,2})\.(\d{1,2})\.(\d{4}|\d{2})?/.exec(text); + if (m) { + const year = m[3] ? (m[3].length === 2 ? 2000 + Number(m[3]) : Number(m[3])) : new Date(now).getFullYear(); + let t = new Date(year, Number(m[2]) - 1, Number(m[1])).getTime(); + // "29.10." without a year in the past means next year + if (!m[3] && t < startOfDay(now)) t = new Date(year + 1, Number(m[2]) - 1, Number(m[1])).getTime(); + return t; + } + m = /(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(text); + if (m) return new Date(Number(m[3]), Number(m[1]) - 1, Number(m[2])).getTime(); + return null; +} + +/** + * Days until a waste bin is collected (0 = today), from its sensor: a number of days, a daysTo attribute (Waste Collection Schedule), + * "today"/"tomorrow" (also German), a date, or a text with a number of days in it. Null when the sensor says nothing usable. + */ +export function pickupDays(st: HassEntity | undefined, now = Date.now()): number | null { + if (!st || isUnavailable(st)) return null; + const attr = Number(st.attributes.daysTo); + if (st.attributes.daysTo !== undefined && Number.isFinite(attr)) return Math.max(0, Math.round(attr)); + const state = String(st.state).trim(); + if (/^-?\d+(\.\d+)?$/.test(state)) return Math.max(0, Math.round(Number(state))); + const lower = state.toLowerCase(); + if (/\b(heute|today)\b/.test(lower)) return 0; + // (no \b here: for JavaScript, "ü" is no word character) + if (lower.includes("übermorgen") || lower.includes("uebermorgen")) return 2; + if (/\b(morgen|tomorrow)\b/.test(lower)) return 1; + // a date goes before a number in the text ("Mon, 26.10.2026" holds numbers that are no day count) + const date = dateIn(state, now) ?? (st.attributes.device_class === "timestamp" || st.attributes.device_class === "date" ? Date.parse(state) : null); + if (date !== null && Number.isFinite(date)) return Math.max(0, Math.round((startOfDay(date) - startOfDay(now)) / DAY)); + const days = /(\d+)\s*(tag|tage|tagen|day|days)\b/i.exec(state); + return days ? Number(days[1]) : null; +} + +/** Whether there is post in the mailbox: its sensor is on (a binary sensor) or says so. */ +export function hasPost(st: HassEntity | undefined): boolean { + if (!st || isUnavailable(st)) return false; + return st.state === "on" || /^(post|mail|yes|ja|true|voll|full|detected)$/i.test(st.state.trim()); +} + +/** A plant's soil moisture in percent, and whether it is thirsty (below `below`, 20 % by default). */ +export function plantThirst(st: HassEntity | undefined, below = 20): { moisture: number; thirsty: boolean } | null { + if (!st || isUnavailable(st)) return null; + const moisture = Number(st.state); + if (!Number.isFinite(moisture)) return st.entity_id.startsWith("binary_sensor.") ? { moisture: NaN, thirsty: st.state === "on" } : null; + return { moisture, thirsty: moisture < below }; +} + +const REMAINING = /remain|rest|verbleib|time_left|timeleft|finish|end_time|fertig|programmende|program_end|done_at/i; + +/** + * Minutes a washer, dryer or dishwasher has left, from a sensor on its device: a duration (minutes, hours, seconds, or h:mm:ss) or a + * timestamp of the end. Null when the device has no such sensor or it is not running. + */ +export function remainingMinutes(hass: HomeAssistant, deviceEntities: readonly string[], now = Date.now()): number | null { + for (const id of deviceEntities) { + if (!id.startsWith("sensor.") || !REMAINING.test(`${id} ${hass.states[id]?.attributes.friendly_name ?? ""}`)) continue; + const st = hass.states[id]; + if (!st || isUnavailable(st)) continue; + const a = st.attributes; + if (a.device_class === "timestamp") { + const end = Date.parse(st.state); + if (Number.isFinite(end) && end > now) return Math.ceil((end - now) / 60000); + continue; + } + const clock = /^(\d+):(\d{2})(?::(\d{2}))?$/.exec(st.state.trim()); + if (clock) { + const mins = clock[3] !== undefined ? Number(clock[1]) * 60 + Number(clock[2]) + Number(clock[3]) / 60 : Number(clock[1]) * 60 + Number(clock[2]); + if (mins > 0) return Math.ceil(mins); + continue; + } + const value = Number(st.state); + if (!Number.isFinite(value) || value <= 0) continue; + const unit = String(a.unit_of_measurement ?? "min").toLowerCase(); + return Math.ceil(unit === "h" ? value * 60 : unit === "s" ? value / 60 : value); + } + return null; +} + +/** The other entities of an entity's device (its remaining-time sensor sits next to its switch or power sensor). */ +export function deviceSiblings(hass: HomeAssistant, id: string | null | undefined): string[] { + const device = id ? hass.entities?.[id]?.device_id : null; + return device && hass.entities ? Object.values(hass.entities).filter((e) => e.device_id === device).map((e) => e.entity_id) : []; +} + +/** Minutes as "25 min" or "1 h 05 min". */ +export const minutesText = (m: number): string => (m < 60 ? `${m} min` : `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, "0")} min`); diff --git a/frontend/src/entities/kinds.test.ts b/frontend/src/entities/kinds.test.ts new file mode 100644 index 0000000..b20108e --- /dev/null +++ b/frontend/src/entities/kinds.test.ts @@ -0,0 +1,146 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { appColor, assumedCover, defaultHeight, domainOf, entityName, fixtureGlow, groupCovers, fromCelsius, isActive, isPlaceable, isStatusSensor, isUnavailable, kelvinToRgb, kindOf, markerKind, lightGlow, tempUnit, toCelsius } from "./kinds.ts"; +import { entity, hassOf } from "./fixtures.ts"; + +test("the domain decides the kind; unknown domains have none", () => { + assert.equal(domainOf("light.kitchen"), "light"); + assert.equal(kindOf("input_boolean.party"), "switch"); + assert.equal(kindOf("binary_sensor.door"), "binary"); + assert.equal(kindOf("vacuum.robot"), null); + assert.equal(isPlaceable("scene"), false); + assert.equal(isPlaceable("light"), true); + assert.equal(isPlaceable(null), false); +}); + +test("unavailable and unknown count as unavailable, a missing entity too", () => { + assert.equal(isUnavailable(entity("a.b", "unavailable")), true); + assert.equal(isUnavailable(entity("a.b", "unknown")), true); + assert.equal(isUnavailable(undefined), true); + assert.equal(isUnavailable(entity("a.b", "on")), false); +}); + +test("a name loses the area it starts with, but not when nothing would be left", () => { + const hass = hassOf([entity("light.a", "on", { friendly_name: "Lounge ceiling light" }), entity("light.b", "on", { friendly_name: "Lounge" }), entity("light.c", "on", { friendly_name: "Hall lamp" })]); + assert.equal(entityName(hass, "light.a", "Lounge"), "Ceiling light"); + assert.equal(entityName(hass, "light.b", "Lounge"), "Lounge"); + assert.equal(entityName(hass, "light.c", "Lounge"), "Hall lamp"); + assert.equal(entityName(hass, "light.a"), "Lounge ceiling light"); + assert.equal(entityName(hass, "light.missing"), "light.missing"); +}); + +test("a friendly name that is a number (set in YAML) still reads as text", () => { + const hass = hassOf([entity("lock.door", "locked", { friendly_name: 12 })]); + assert.equal(entityName(hass, "lock.door"), "12"); + assert.equal(entityName(hass, "lock.door", "Hall"), "12"); +}); + +test("what counts as active for each kind", () => { + assert.equal(isActive(entity("light.a", "on")), true); + assert.equal(isActive(entity("cover.a", "opening")), true); + assert.equal(isActive(entity("cover.a", "closed")), false); + assert.equal(isActive(entity("climate.a", "heat", { hvac_action: "heating" })), true); + assert.equal(isActive(entity("climate.a", "heat", { hvac_action: "idle" })), false); + assert.equal(isActive(entity("media_player.a", "playing")), true); + assert.equal(isActive(entity("media_player.a", "paused")), false); + assert.equal(isActive(entity("lock.a", "unlocked")), true); + assert.equal(isActive(entity("vacuum.a", "returning")), true); + assert.equal(isActive(entity("vacuum.a", "docked")), false); + assert.equal(isActive(undefined), false); +}); + +test("a status sensor is active while it works, a plain sensor never", () => { + const printer = entity("sensor.printer", "Printing", { device_class: "enum" }); + assert.equal(isStatusSensor(printer), true); + assert.equal(isActive(printer), true); + assert.equal(isActive(entity("sensor.printer", "idle", { device_class: "enum" })), false); + assert.equal(isActive(entity("sensor.temp", "running", { device_class: "temperature" })), false); +}); + +test("a light glows with its colour and a perceptual brightness, off lights do not glow", () => { + assert.equal(lightGlow(entity("light.a", "off")), null); + assert.deepEqual(lightGlow(entity("light.a", "on", { brightness: 255, rgb_color: [255, 0, 0], color_mode: "rgb" })), { color: [1, 0, 0], level: 1 }); + const dim = lightGlow(entity("light.a", "on", { brightness: 26 }))!; + assert.ok(dim.level > 0.4 && dim.level < 0.55, String(dim.level)); + assert.deepEqual(lightGlow(entity("light.a", "on"))!.color, [1, 0.71, 0.28]); +}); + +test("a white light uses its colour temperature, not a stale rgb colour", () => { + const warm = lightGlow(entity("light.a", "on", { color_mode: "color_temp", rgb_color: [0, 0, 255], color_temp_kelvin: 2200 }))!; + assert.deepEqual(warm.color, kelvinToRgb(2200)); + assert.ok(kelvinToRgb(6500)[2] > kelvinToRgb(2200)[2], "cool light has more blue"); + assert.deepEqual(kelvinToRgb(1000), kelvinToRgb(2200), "clamped at the warm end"); +}); + +test("a relay's lamp takes colour and brightness from the bulb, unless the bulb is unavailable", () => { + const relay = entity("switch.relay", "on"); + const bulb = entity("light.bulb", "on", { brightness: 255, rgb_color: [0, 0, 255], color_mode: "rgb" }); + assert.deepEqual(lightGlow(relay, bulb)!.color, [0, 0, 1]); + assert.deepEqual(lightGlow(relay, entity("light.bulb", "unavailable"))!.color, [1, 0.71, 0.28]); + assert.equal(lightGlow(entity("switch.relay", "off"), bulb), null); +}); + +test("default heights: lamps by mount, the rest by kind", () => { + assert.ok(Math.abs(defaultHeight("light", 2.6) - 2.35) < 1e-9); + assert.equal(defaultHeight("light", 2.6, "table"), 1.25); + assert.equal(defaultHeight("cover", 3), 2); + assert.equal(defaultHeight("sensor", 2.6), 1.4); + assert.equal(defaultHeight("lock", 2.6), 1.05); +}); + +test("TV glow follows the running app and is off when the TV is", () => { + assert.deepEqual(appColor(entity("media_player.tv", "playing", { app_name: "Netflix" })), [0.9, 0.04, 0.08]); + assert.deepEqual(appColor(entity("media_player.tv", "playing", { source: "Disney+" })), [0.2, 0.35, 1]); + assert.deepEqual(appColor(entity("media_player.tv", "playing", { app_name: "Something" })), [0.22, 0.88, 1]); + assert.equal(appColor(entity("media_player.tv", "off")), null); + assert.equal(appColor(entity("media_player.tv", "unavailable")), null); +}); + +test("temperature units convert both ways", () => { + assert.equal(toCelsius(212, "°F"), 100); + assert.equal(toCelsius(273.15, "K"), 0); + assert.equal(toCelsius(21, "°C"), 21); + const us = hassOf([], {}, { config: { unit_system: { temperature: "°F" } } }); + assert.equal(tempUnit(us), "°F"); + assert.equal(fromCelsius(us, 100), 212); + assert.equal(tempUnit(hassOf([])), "°C"); + assert.equal(fromCelsius(hassOf([]), 20), 20); +}); + +test("a cover that only sends commands stays unknown but still counts as usable", () => { + assert.equal(assumedCover(entity("cover.garage", "unknown", { assumed_state: true })), true); + assert.equal(assumedCover(entity("cover.garage", "unknown")), false); + assert.equal(assumedCover(entity("cover.garage", "unavailable", { assumed_state: true })), false); + assert.equal(assumedCover(entity("switch.x", "unknown", { assumed_state: true })), false); + assert.equal(assumedCover(undefined), false); +}); + +test("a marker's kind: its entity's, or NextFloor's own markers", () => { + assert.equal(markerKind("light.kitchen"), "light"); + assert.equal(markerKind("lamp:f1"), "light"); + assert.equal(markerKind("sensor.x", true), "light"); + assert.equal(markerKind("tap:f2"), "tap"); + assert.equal(markerKind("gang:f3"), "switch"); + assert.equal(markerKind("grid"), "sensor"); + assert.equal(markerKind("binary_sensor.door"), "binary"); + assert.equal(markerKind("vacuum.robot"), "other"); + assert.equal(markerKind("script.x"), "other"); +}); + +test("open all / close all take a garage remote along, but never a cover that asks first", () => { + const blind = entity("cover.blind", "closed"); + const remote = entity("cover.remote", "unknown", { assumed_state: true }); + const garage = entity("cover.garage", "unknown", { assumed_state: true }); + const lost = entity("cover.lost", "unavailable"); + const silent = entity("cover.silent", "unknown"); + assert.deepEqual(groupCovers([blind, remote, garage, lost, silent], new Set(["cover.garage"])), ["cover.blind", "cover.remote"]); + assert.deepEqual(groupCovers([blind, garage], null), ["cover.blind", "cover.garage"]); +}); + +test("a fixture with several bulbs glows with its main light, else dimmer with another one that is on", () => { + const main = { entity_id: "light.main", state: "off", attributes: {} }; + const night = { entity_id: "light.night", state: "on", attributes: { brightness: 255, rgb_color: [255, 0, 0], color_mode: "rgb" } }; + assert.deepEqual(fixtureGlow(main, [undefined, night]), { color: [1, 0, 0], level: 0.6 }); + assert.equal(fixtureGlow({ ...main, state: "on" }, [night])?.level, 1, "the main light wins"); + assert.equal(fixtureGlow(main, [{ ...night, state: "off" }]), null); +}); diff --git a/frontend/src/entities/kinds.ts b/frontend/src/entities/kinds.ts new file mode 100644 index 0000000..56123c8 --- /dev/null +++ b/frontend/src/entities/kinds.ts @@ -0,0 +1,201 @@ +// What kind of device an entity is, whether it is "on", how a light glows, and a few unit helpers. +// Pure functions: no Lit, no three.js. + +import type { LampMount } from "../model.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; + +export type DeviceKind = "light" | "switch" | "fan" | "cover" | "climate" | "media" | "lock" | "sensor" | "binary" | "scene" | "script"; + +/** The Home Assistant domain, i.e. the part of the id before the dot. */ +export const domainOf = (entityId: string): string => entityId.slice(0, entityId.indexOf(".")); + +const KIND_OF_DOMAIN: Record = { + light: "light", + switch: "switch", + input_boolean: "switch", + // a water valve (irrigation, the main water) opens and closes like a switch turns on and off + valve: "switch", + fan: "fan", + cover: "cover", + climate: "climate", + media_player: "media", + lock: "lock", + sensor: "sensor", + binary_sensor: "binary", + // a wall button or remote: its state is the time of its last press, shown like a reading + event: "sensor", + scene: "scene", + script: "script", +}; + +export const kindOf = (entityId: string): DeviceKind | null => KIND_OF_DOMAIN[domainOf(entityId)] ?? null; + +/** The order kinds are listed in. */ +export const KIND_ORDER: DeviceKind[] = ["light", "cover", "climate", "media", "switch", "fan", "lock", "binary", "sensor", "scene", "script"]; + +/** The kinds of markers one can choose to see outside the opened room: device kinds, furniture with an own tap action, and the rest. */ +export type MarkerKind = Exclude | "tap" | "other"; +export const MARKER_KINDS: MarkerKind[] = ["light", "cover", "climate", "media", "switch", "fan", "lock", "binary", "sensor", "tap", "other"]; + +/** The kind of a marker by its id: an entity, or one of NextFloor's own (a lamp without light, a light switch plate, a tap action, the grid). */ +export function markerKind(id: string, lamp = false): MarkerKind { + if (lamp || id.startsWith("lamp:")) return "light"; + if (id.startsWith("tap:")) return "tap"; + if (id.startsWith("gang:")) return "switch"; + if (id === "grid") return "sensor"; + const kind = kindOf(id); + return kind && kind !== "scene" && kind !== "script" ? kind : "other"; +} + +/** Kinds a tap on the marker can switch. */ +export const TOGGLE_KINDS = new Set(["light", "switch", "fan"]); + +/** Scenes and scripts live in the room panel; they have no place in the room. */ +export const isPlaceable = (kind: DeviceKind | null): boolean => kind !== null && kind !== "scene" && kind !== "script"; + +/** Gone or unknown; an event entity (a wall button) is "unknown" until its first press and is there all the same. */ +export const isUnavailable = (st: HassEntity | undefined): boolean => !st || st.state === "unavailable" || (st.state === "unknown" && !st.entity_id.startsWith("event.")); + +const MOTION_CLASSES = new Set(["motion", "occupancy", "presence", "moving"]); + +/** A binary sensor that tells motion, occupancy or presence. */ +export const isMotionSensor = (hass: HomeAssistant | undefined, entityId: string): boolean => + entityId.startsWith("binary_sensor.") && MOTION_CLASSES.has(String(hass?.states[entityId]?.attributes.device_class ?? "")); + +/** A cover that only sends commands (assumed state, a garage remote) and so stays unknown: its buttons still work. */ +export const assumedCover = (st: HassEntity | undefined): boolean => !!st && st.entity_id.startsWith("cover.") && st.state === "unknown" && st.attributes.assumed_state === true; + +/** The covers "open all" / "close all" move at once: those that answer (a garage remote included), but never one that asks first. */ +export const groupCovers = (covers: readonly HassEntity[], asking: ReadonlySet | null | undefined): string[] => + covers.filter((c) => (!isUnavailable(c) || assumedCover(c)) && !asking?.has(c.entity_id)).map((c) => c.entity_id); + +/** The entity's name without the area in front of it: "Lounge Ceiling light" in the Lounge reads "Ceiling light". */ +export function entityName(hass: HomeAssistant | undefined, entityId: string, areaName?: string): string { + // a friendly_name set in YAML can be a number: the name is always text + const name = String(hass?.states[entityId]?.attributes.friendly_name ?? hass?.entities?.[entityId]?.name ?? entityId); + if (!areaName || name.length <= areaName.length + 1) return name; + if (!name.toLowerCase().startsWith(`${areaName.toLowerCase()} `)) return name; + const rest = name.slice(areaName.length + 1); + return rest[0].toUpperCase() + rest.slice(1); +} + +// ---------------------------------------------------------------- is it on? + +/** Sensor states (a printer, a washing machine) that say the device is at work. */ +const AT_WORK = new Set(["running", "printing", "prepare", "preparing", "slicing", "heating", "busy", "working", "active", "washing", "rinsing", "spinning", "drying", "cleaning", "in_progress", "in progress", "on"]); + +/** A status sensor reports a fixed set of words (running, idle, finished ...) and furniture can follow it. */ +export const isStatusSensor = (st: HassEntity | undefined): boolean => !!st && st.entity_id.startsWith("sensor.") && st.attributes.device_class === "enum"; + +/** "Active" lights a marker up: a lamp that is on, an open cover, a heater heating, a playing player, an open window ... */ +export function isActive(st: HassEntity | undefined): boolean { + if (!st) return false; + // a robot vacuum counts as active while it cleans or drives back to its dock + if (st.entity_id.startsWith("vacuum.")) return ["cleaning", "returning"].includes(st.state); + if (st.entity_id.startsWith("valve.")) return st.state === "open" || st.state === "opening"; + const kind = kindOf(st.entity_id); + if (kind === "light" || kind === "switch" || kind === "fan" || kind === "binary") return st.state === "on"; + if (kind === "cover") return st.state === "open" || st.state === "opening"; + if (kind === "climate") return ["heating", "cooling"].includes(String(st.attributes.hvac_action)); + if (kind === "media") return st.state === "playing"; + if (kind === "lock") return st.state === "unlocked" || st.state === "open"; + if (kind === "sensor") return isStatusSensor(st) && AT_WORK.has(st.state.toLowerCase()); + return false; +} + +// ---------------------------------------------------------------- light colour + +export type Rgb = [number, number, number]; + +const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); + +/** A rough colour for a colour temperature (2200 K warm to 6500 K cool), kept soft on the dark floor. */ +export function kelvinToRgb(kelvin: number): Rgb { + const t = clamp01((kelvin - 2200) / (6500 - 2200)); + const warm: Rgb = [1, 0.66, 0.26]; + const cool: Rgb = [0.78, 0.9, 1]; + return [0, 1, 2].map((i) => warm[i] + (cool[i] - warm[i]) * t) as Rgb; +} + +/** + * Colour (channels 0..1) and strength (0..1) of a lit lamp, or null when it is off. `colorFrom` is the bulb itself + * when a relay switches the light and only the bulb knows its colour and brightness. + */ +export function lightGlow(st: HassEntity | undefined, colorFrom?: HassEntity): { color: Rgb; level: number } | null { + if (!st || st.state !== "on") return null; + const source = colorFrom && !["unavailable", "unknown"].includes(colorFrom.state) ? colorFrom.attributes : st.attributes; + // perceptual curve: a lamp at 10 % still looks on (about 0.45), full brightness is 1 + const level = typeof source.brightness === "number" ? 0.2 + 0.8 * Math.sqrt(clamp01(source.brightness / 255)) : 1; + const rgb = source.rgb_color as Rgb | undefined; + const whiteModes = ["color_temp", "brightness", "onoff"]; + if (rgb && !whiteModes.includes(String(source.color_mode))) return { color: [rgb[0] / 255, rgb[1] / 255, rgb[2] / 255], level }; + if (typeof source.color_temp_kelvin === "number") return { color: kelvinToRgb(source.color_temp_kelvin), level }; + return { color: [1, 0.71, 0.28], level }; // the default warm amber +} + +/** + * A fixture with several bulbs (a main light, a night light, an ambient ring): it glows with its main light, and while that is off + * with the first other light that is on, a little dimmer. + */ +export function fixtureGlow(main: HassEntity | undefined, others: (HassEntity | undefined)[], colorFrom?: HassEntity): { color: Rgb; level: number } | null { + const own = lightGlow(main, colorFrom); + if (own) return own; + for (const st of others) { + const glow = lightGlow(st); + if (glow) return { color: glow.color, level: glow.level * 0.6 }; + } + return null; +} + +/** Default height of a marker above the floor, in metres. */ +export function defaultHeight(kind: DeviceKind, floorHeight: number, mount: LampMount | null = null): number { + if (kind === "light" && mount === "floor") return 1.95; + if (kind === "light" && mount === "table") return 1.25; + if (kind === "light" && mount === "wall") return 1.95; + switch (kind) { + case "light": + return Math.max(0.5, floorHeight - 0.25); + case "cover": + return Math.min(2, floorHeight - 0.3); + case "climate": + return 0.6; + case "media": + return 0.9; + case "binary": + case "sensor": + return 1.4; + default: + return 1.05; + } +} + +/** Glow colour of a TV for the app that is running (the apps' brand colours). */ +export function appColor(st: HassEntity | undefined): Rgb | null { + if (!st || isUnavailable(st) || st.state === "off" || st.state === "standby") return null; + const { app_name, source, app_id } = st.attributes; + const text = `${app_name ?? ""} ${source ?? ""} ${app_id ?? ""}`.toLowerCase(); + const brands: [string[], Rgb][] = [ + [["netflix"], [0.9, 0.04, 0.08]], + [["youtube"], [1, 0.1, 0.15]], + [["prime", "amazon"], [0.1, 0.6, 0.95]], + [["disney"], [0.2, 0.35, 1]], + [["spotify"], [0.12, 0.85, 0.4]], + [["zdf", "ard", "mediathek"], [1, 0.5, 0.1]], + ]; + return brands.find(([words]) => words.some((w) => text.includes(w)))?.[1] ?? [0.22, 0.88, 1]; +} + +// ---------------------------------------------------------------- temperature units + +/** The temperature unit Home Assistant uses: "°F" for US units, else "°C". */ +export const tempUnit = (hass: HomeAssistant): "°C" | "°F" => (hass.config?.unit_system?.temperature === "°F" ? "°F" : "°C"); + +/** A reading in its unit (°F, K, anything else counts as °C) converted to °C. */ +export function toCelsius(value: number, unit: unknown): number { + if (unit === "°F") return ((value - 32) * 5) / 9; + if (unit === "K") return value - 273.15; + return value; +} + +/** °C converted to the unit Home Assistant shows. */ +export const fromCelsius = (hass: HomeAssistant, celsius: number): number => (tempUnit(hass) === "°F" ? (celsius * 9) / 5 + 32 : celsius); diff --git a/frontend/src/entities/misc.test.ts b/frontend/src/entities/misc.test.ts new file mode 100644 index 0000000..d68e391 --- /dev/null +++ b/frontend/src/entities/misc.test.ts @@ -0,0 +1,117 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { centroid, pointInPolygon } from "../model.ts"; +import { box, entity, floorWith, hassOf } from "./fixtures.ts"; +import { autoPlace, favoriteCall, floorControls, ownButtonOn, robotRoom, robotRoomSensor, roomKey, runButton } from "./misc.ts"; + +const ids = (n: number, prefix = "sensor.s") => Array.from({ length: n }, (_, i) => `${prefix}${i}`); + +test("auto placement keeps everything inside the room, apart, and off the label", () => { + const room = box("r", 0, 0, 5, 4); + const placed = autoPlace(room, ids(6)); + assert.equal(placed.length, 6); + const label = centroid(room.points); + for (const p of placed) { + assert.ok(pointInPolygon([p.x, p.z], room.points)); + assert.ok(Math.hypot(p.x - label[0], p.z - label[1]) >= 0.5, "off the label"); + } + for (let i = 0; i < placed.length; i++) for (let j = i + 1; j < placed.length; j++) assert.ok(Math.hypot(placed[i].x - placed[j].x, placed[i].z - placed[j].z) > 0.3); +}); + +test("lights go towards the middle, other devices towards a wall", () => { + const room = box("r", 0, 0, 6, 5); + const [light] = autoPlace(room, ["light.a"]); + const [sensor] = autoPlace(room, ["sensor.a"]); + const label = centroid(room.points); + assert.ok(Math.hypot(light.x - label[0], light.z - label[1]) < Math.hypot(sensor.x - label[0], sensor.z - label[1])); +}); + +test("placement is deterministic, avoids taken spots, and copes with tiny rooms", () => { + const room = box("r", 0, 0, 4, 4); + assert.deepEqual(autoPlace(room, ids(3)), autoPlace(room, ids(3))); + const taken = autoPlace(room, ["sensor.x"])[0]; + const next = autoPlace(room, ["sensor.y"], [[taken.x, taken.z]])[0]; + assert.ok(Math.hypot(next.x - taken.x, next.z - taken.z) > 0.5); + const tiny = autoPlace(box("t", 0, 0, 0.6, 0.6), ids(2)); + assert.equal(tiny.length, 2); + assert.deepEqual(autoPlace({ ...room, points: [[0, 0], [1, 1]] }, ids(1)), []); + assert.deepEqual(autoPlace(room, []), []); +}); + +test("room names compare without case, accents and umlaut spelling", () => { + assert.equal(roomKey("Küche"), roomKey("kueche")); + assert.equal(roomKey("Küche"), roomKey("Kuche")); + assert.equal(roomKey("Straße"), "strasse"); + assert.equal(roomKey("Living-Room 2"), "livingroom2"); +}); + +test("the robot's room sensor: chosen, 'none', or found on the vacuum's device", () => { + const hass = hassOf([entity("vacuum.rob", "cleaning"), entity("sensor.rob_current_room", "Kitchen"), entity("sensor.rob_battery", "80")], { + "vacuum.rob": { device_id: "r" }, + "sensor.rob_current_room": { device_id: "r" }, + "sensor.rob_battery": { device_id: "r" }, + }); + assert.equal(robotRoomSensor(hass, "vacuum.rob", undefined), "sensor.rob_current_room"); + assert.equal(robotRoomSensor(hass, "vacuum.rob", "sensor.mine"), "sensor.mine"); + assert.equal(robotRoomSensor(hass, "vacuum.rob", "none"), null); + assert.equal(robotRoomSensor(hass, null, undefined), null); +}); + +test("the robot's room is matched by room or area name, exactly first, then loosely", () => { + const rooms = [{ name: "Küche", area_id: "kitchen" }, { name: "Bad", area_id: null }, { name: "Wohnzimmer", area_id: "living" }]; + const hass = hassOf([entity("sensor.room", "kitchen"), entity("vacuum.rob", "cleaning", { current_room: "Wohnzimmer unten" })], {}, { areas: { kitchen: { area_id: "kitchen", name: "Kitchen" }, living: { area_id: "living", name: "Living room" } } }); + assert.equal(robotRoom(hass, rooms, null, "sensor.room")?.name, "Küche"); + assert.equal(robotRoom(hass, rooms, "vacuum.rob", null)?.name, "Wohnzimmer"); + hass.states["sensor.room"].state = "unknown"; + assert.equal(robotRoom(hass, rooms, null, "sensor.room"), null); + hass.states["sensor.room"].state = "Garage"; + assert.equal(robotRoom(hass, rooms, null, "sensor.room"), null); +}); + +test("floor controls: lights and blinds of the floor, no garage doors, no hidden entities", () => { + const hass = hassOf( + [entity("light.a", "on"), entity("light.hidden", "on"), entity("cover.blind", "open", { device_class: "shutter" }), entity("cover.garage", "closed", { device_class: "garage" }), entity("light.placed", "on"), entity("light.linked", "off")], + { "light.a": { area_id: "x" }, "light.hidden": { area_id: "x" }, "cover.blind": { area_id: "x" }, "cover.garage": { area_id: "x" } }, + ); + const room = { ...box("r", 0, 0, 4, 3, "x"), hidden: ["light.hidden"] }; + const floor = floorWith([room], { + placements: [{ entity_id: "light.placed", x: 1, z: 1, y: null, mount: null }, { entity_id: "cover.garage", x: 1, z: 1, y: null, mount: null }], + furniture: [{ id: "l", type: "lamp_floor", x: 1, z: 1, rotation: 0, w: 1, d: 1, h: 1, variant: null, entity: "light.linked", power: null }], + }); + const controls = floorControls(hass, floor); + assert.deepEqual(controls.lights.sort(), ["light.a", "light.linked", "light.placed"]); + assert.deepEqual(controls.covers, ["cover.blind"]); +}); + +test("a favourite starts scenes and scripts, triggers automations, presses buttons and toggles the rest", () => { + assert.deepEqual(favoriteCall("scene.movie"), ["scene", "turn_on"]); + assert.deepEqual(favoriteCall("script.go"), ["script", "turn_on"]); + assert.deepEqual(favoriteCall("automation.x"), ["automation", "trigger"]); + assert.deepEqual(favoriteCall("input_button.b"), ["input_button", "press"]); + assert.deepEqual(favoriteCall("light.a"), ["homeassistant", "toggle"]); +}); + +test("own buttons call a service or fire the DOM event, and ignore incomplete ones", () => { + const calls: unknown[][] = []; + const events: { name: string; detail: unknown }[] = []; + const hass = hassOf([], {}, { callService: async (...a: unknown[]) => void calls.push(a) }); + const from = { dispatchEvent: (e: CustomEvent) => void events.push({ name: e.type, detail: e.detail }) } as unknown as HTMLElement; + runButton(hass, from, { action: "service", target: "light.turn_on", data: { entity_id: "light.a" } }); + assert.deepEqual(calls[0], ["light", "turn_on", { entity_id: "light.a" }]); + runButton(hass, from, { action: "fire_dom_event", data: { browser_mod: { command: "popup" } } }); + assert.deepEqual(events[0], { name: "ll-custom", detail: { browser_mod: { command: "popup" } } }); + runButton(hass, from, { action: "more_info", target: "light.a" }); + assert.deepEqual(events[1], { name: "hass-more-info", detail: { entityId: "light.a" } }); + runButton(hass, from, { action: "service", target: "nodot" }); + runButton(hass, from, { action: "more_info", target: "" }); + assert.equal(calls.length, 1); + assert.equal(events.length, 2); +}); + +test("an own button lights up while its entity is on", () => { + const hass = hassOf([entity("switch.party", "on"), entity("light.hall", "off")]); + assert.equal(ownButtonOn(hass, { action: "service", target: "switch.toggle", data: { entity_id: "switch.party" } }), true); + assert.equal(ownButtonOn(hass, { action: "more_info", target: "light.hall" }), false); + assert.equal(ownButtonOn(hass, { action: "navigate", target: "/lovelace/0", state_entity: "switch.party" }), true, "named by hand"); + assert.equal(ownButtonOn(hass, { action: "service", target: "script.x", data: { entity_id: ["switch.party"] } }), false, "several entities tell nothing"); +}); diff --git a/frontend/src/entities/misc.ts b/frontend/src/entities/misc.ts new file mode 100644 index 0000000..2519c56 --- /dev/null +++ b/frontend/src/entities/misc.ts @@ -0,0 +1,195 @@ +// Smaller helpers around devices: automatic placement in a room, the robot vacuum's room, the central "all lights" +// controls of a floor, favourites and own buttons. + +import { centroid, pointInPolygon, type Floor, type Placement, type Room, type Vec2 } from "../model.ts"; +import type { HomeAssistant } from "../types.ts"; +import { kindOf } from "./kinds.ts"; +import { roomEntities, primaryEntities } from "./registry.ts"; + +// ---------------------------------------------------------------- automatic placement + +function distanceToOutline(p: Vec2, outline: readonly Vec2[]): number { + return Math.min( + ...outline.map((a, i) => { + const b = outline[(i + 1) % outline.length]; + const [dx, dz] = [b[0] - a[0], b[1] - a[1]]; + const along = Math.min(1, Math.max(0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / (dx * dx + dz * dz || 1))); + return Math.hypot(p[0] - a[0] - dx * along, p[1] - a[1] - dz * along); + }), + ); +} + +/** + * Places entities in a room without overlapping each other or what is there already. Lights go towards the middle, spread + * apart; everything else along the walls. The room label at the centre stays free. The result is deterministic: the same + * room always gets the same layout. + */ +export function autoPlace(room: Room, entityIds: readonly string[], taken: readonly Vec2[] = []): Placement[] { + const outline = room.points; + if (outline.length < 3 || entityIds.length === 0) return []; + const xs = outline.map((p) => p[0]); + const zs = outline.map((p) => p[1]); + const [minX, maxX, minZ, maxZ] = [Math.min(...xs), Math.max(...xs), Math.min(...zs), Math.max(...zs)]; + const extent = Math.min(maxX - minX, maxZ - minZ); + const step = Math.max(0.1, Math.min(0.25, extent / 8)); + const wallMargin = Math.min(0.35, extent / 5); + const labelClearance = Math.min(0.7, extent / 4); + const label = centroid(outline); + + // a grid of free spots, away from the walls + const spots: { at: Vec2; wallDistance: number }[] = []; + for (let x = minX + step / 2; x < maxX; x += step) { + for (let z = minZ + step / 2; z < maxZ; z += step) { + const at: Vec2 = [x, z]; + if (!pointInPolygon(at, outline)) continue; + const wallDistance = distanceToOutline(at, outline); + if (wallDistance >= wallMargin) spots.push({ at, wallDistance }); + } + } + if (spots.length === 0) spots.push({ at: label, wallDistance: 0 }); + + const occupied: Vec2[] = [...taken]; + return entityIds.map((entity_id) => { + const isLight = kindOf(entity_id) === "light"; + let best = spots[0].at; + let bestScore = -Infinity; + for (const { at, wallDistance } of spots) { + const nearestNeighbour = occupied.length ? Math.min(...occupied.map((o) => Math.hypot(at[0] - o[0], at[1] - o[1]))) : 3; + const fromLabel = Math.hypot(at[0] - label[0], at[1] - label[1]); + // room to breathe is good (up to 3 m); the label's spot is taboo except for lights; lights like the middle, others a wall + let score = Math.min(nearestNeighbour, 3) * 2; + if (fromLabel < labelClearance && !isLight) score -= 10; + score -= isLight ? fromLabel * 0.35 : wallDistance * 1.2; + if (score > bestScore + 1e-9) { + bestScore = score; + best = at; + } + } + const chosen: Vec2 = [Math.round(best[0] * 100) / 100, Math.round(best[1] * 100) / 100]; + occupied.push(chosen); + return { entity_id, x: chosen[0], z: chosen[1], y: null, mount: null }; + }); +} + +// ---------------------------------------------------------------- robot vacuum + +const ROOM_SENSOR_NAME = /(^|_)(current_room|current_segment|aktueller_raum|current_area)($|_)/; + +/** The sensor that names the room a robot vacuum is cleaning: the chosen one, else one on the vacuum's device. */ +export function robotRoomSensor(hass: HomeAssistant, vacuum: string | null, chosen: string | null | undefined): string | null { + if (chosen === "none") return null; + if (chosen) return chosen; + const device = vacuum ? hass.entities?.[vacuum]?.device_id : null; + if (!device || !hass.entities) return null; + const match = Object.values(hass.entities).find((e) => e.device_id === device && e.entity_id.startsWith("sensor.") && (ROOM_SENSOR_NAME.test(e.translation_key ?? "") || ROOM_SENSOR_NAME.test(e.entity_id.split(".")[1]))); + return match?.entity_id ?? null; +} + +/** A name without case, accents or umlaut spelling: "Küche", "kueche" and "Kuche" are the same. */ +export function roomKey(name: string): string { + return name + .toLowerCase() + .replace(/ä/g, "a") + .replace(/ö/g, "o") + .replace(/ü/g, "u") + .replace(/ß/g, "ss") + .replace(/ae/g, "a") + .replace(/oe/g, "o") + .replace(/ue/g, "u") + .normalize("NFD") + .replace(/[^a-z0-9]/g, ""); +} + +/** The room the robot reports (the sensor's state, else the vacuum's current_room attribute), matched by room or area name. */ +export function robotRoom(hass: HomeAssistant, rooms: readonly R[], vacuum: string | null, sensor: string | null): R | null { + const reported = sensor ? hass.states[sensor]?.state : vacuum ? hass.states[vacuum]?.attributes.current_room : undefined; + if (typeof reported !== "string" || ["", "unknown", "unavailable"].includes(reported)) return null; + const wanted = roomKey(reported); + if (!wanted) return null; + const keysOf = (room: R) => [room.name, room.area_id ?? "", (room.area_id && hass.areas?.[room.area_id]?.name) || ""].map(roomKey).filter(Boolean); + const exact = rooms.find((room) => keysOf(room).includes(wanted)); + return exact ?? rooms.find((room) => keysOf(room).some((k) => k.length >= 3 && (k.includes(wanted) || wanted.includes(k)))) ?? null; +} + +// ---------------------------------------------------------------- floor controls, favourites, buttons + +/** Covers that are doors, not blinds: the central "close all" leaves them alone. */ +const DOOR_COVER_CLASSES = new Set(["garage", "gate", "door"]); + +/** + * The lights and blinds of a floor for the central "all on / all off": the main entities of its rooms' areas (except those a + * room hides), placed devices and linked furniture. Garage doors and gates are no blinds and stay out. + */ +export function floorControls(hass: HomeAssistant, floor: Floor): { lights: string[]; covers: string[] } { + const lights = new Set(); + const covers = new Set(); + const consider = (id: string | null | undefined) => { + if (!id || id === "none" || !hass.states[id]) return; + const kind = kindOf(id); + if (kind === "light") lights.add(id); + if (kind === "cover" && !DOOR_COVER_CLASSES.has(String(hass.states[id].attributes.device_class ?? ""))) covers.add(id); + }; + for (const room of floor.rooms) { + const hidden = new Set(room.hidden ?? []); + primaryEntities(hass, roomEntities(hass, room)).filter((id) => !hidden.has(id)).forEach(consider); + } + floor.placements.forEach((p) => consider(p.entity_id)); + floor.furniture.forEach((f) => consider(f.entity)); + return { lights: [...lights], covers: [...covers] }; +} + +/** The service a favourite runs when tapped: scenes and scripts start, buttons are pressed, the rest is toggled. */ +export function favoriteCall(entityId: string): [domain: string, service: string] { + const domain = entityId.split(".")[0]; + switch (domain) { + case "scene": + case "script": + return [domain, "turn_on"]; + case "automation": + return [domain, "trigger"]; + case "button": + case "input_button": + return [domain, "press"]; + default: + return ["homeassistant", "toggle"]; + } +} + +/** + * Runs an own button from an element inside the dashboard: navigate, open more-info, call a service, or fire a DOM + * event ("ll-custom" is what Home Assistant's fire-dom-event sends, and what browser_mod listens for). + */ +export function runButton(hass: HomeAssistant, from: HTMLElement, button: { action: string; target?: string | null; data?: Record | null }): void { + const target = button.target?.trim() ?? ""; + const fire = (name: string, detail: unknown) => from.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true })); + switch (button.action) { + case "navigate": + if (!target) return; + history.pushState(null, "", target); + window.dispatchEvent(new CustomEvent("location-changed", { detail: { replace: false } })); + return; + case "more_info": + if (target) fire("hass-more-info", { entityId: target }); + return; + case "service": { + if (!target.includes(".")) return; + const [domain, service] = target.split(".", 2); + void hass.callService(domain, service, button.data ?? {}); + return; + } + case "fire_dom_event": + fire("ll-custom", button.data ?? {}); + return; + } +} + +/** + * Whether an own button's entity is on, so the button lights up: the entity the button names itself (`state_entity`), else the one + * it opens (more-info) or the single entity its service is called for. Off, unknown, or none to tell: false. + */ +export function ownButtonOn(hass: HomeAssistant | undefined, button: { action: string; target?: string | null; data?: Record | null; state_entity?: string | null }): boolean { + const data = button.data?.entity_id; + const id = button.state_entity || (button.action === "more_info" ? button.target : null) || (button.action === "service" && typeof data === "string" ? data : null); + const st = id ? hass?.states[id] : undefined; + return !!st && ["on", "open", "playing", "home", "heat", "cool", "unlocked"].includes(st.state); +} diff --git a/frontend/src/entities/openings.test.ts b/frontend/src/entities/openings.test.ts new file mode 100644 index 0000000..803119d --- /dev/null +++ b/frontend/src/entities/openings.test.ts @@ -0,0 +1,186 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, entity, floorWith, hassOf, opening } from "./fixtures.ts"; +import { DOOR_DEFAULT_OPEN, isUnlocked, openingEntities, openingState, windowPosition } from "./openings.ts"; + +const sensors = [ + entity("cover.blind", "open", { device_class: "shutter" }), + entity("binary_sensor.win1", "off", { device_class: "window" }), + entity("binary_sensor.win2", "on", { device_class: "window" }), + entity("binary_sensor.door", "off", { device_class: "door" }), + entity("cover.garage", "closed", { device_class: "garage" }), + entity("binary_sensor.garage_contact", "on", { device_class: "garage_door" }), +]; +const registry = Object.fromEntries(sensors.map((s) => [s.entity_id, { area_id: "a" }])); + +test("windows are matched in order with the contacts of their area, one blind serves all", () => { + const hass = hassOf(sensors, registry); + const floor = floorWith([box("r", 0, 0, 5, 4, "a")], { openings: [opening("w2", "r", "window", { offset: 3 }), opening("w1", "r", "window", { offset: 1 })] }); + const links = openingEntities(hass, [floor]); + assert.equal(links.get("w1")?.contact, "binary_sensor.win1"); + assert.equal(links.get("w2")?.contact, "binary_sensor.win2"); + assert.equal(links.get("w1")?.cover, "cover.blind"); + assert.equal(links.get("w2")?.cover, "cover.blind"); +}); + +test("doors and garage doors find their own kind of entity", () => { + const hass = hassOf(sensors, registry); + const floor = floorWith([box("r", 0, 0, 5, 4, "a")], { openings: [opening("d", "r", "door"), opening("g", "r", "garage")] }); + const links = openingEntities(hass, [floor]); + assert.equal(links.get("d")?.contact, "binary_sensor.door"); + assert.equal(links.get("d")?.cover, null); + assert.equal(links.get("g")?.cover, "cover.garage"); + assert.equal(links.get("g")?.contact, "binary_sensor.garage_contact"); +}); + +test("what was set by hand wins, and 'none' switches a link off", () => { + const hass = hassOf(sensors, registry); + const floor = floorWith([box("r", 0, 0, 5, 4, "a")], { + openings: [opening("w", "r", "window", { cover: "none", contact: "binary_sensor.door", tilt: "binary_sensor.win2" }), opening("x", "r", "window", { contact: "none" })], + }); + const links = openingEntities(hass, [floor]); + assert.equal(links.get("w")?.cover, null); + assert.equal(links.get("w")?.contact, "binary_sensor.door"); + assert.equal(links.get("w")?.tilt, "binary_sensor.win2"); + assert.equal(links.get("x")?.contact, null); +}); + +test("a window with a handle sensor gets no automatic plain contact", () => { + const hass = hassOf(sensors, registry); + const floor = floorWith([box("r", 0, 0, 5, 4, "a")], { openings: [opening("w", "r", "window", { sensor: "handle" } as never)] }); + assert.equal(openingEntities(hass, [floor]).get("w")?.contact, null); +}); + +test("only a two-leaf opening has second-leaf sensors", () => { + const hass = hassOf(sensors, registry); + const make = (leaves: number) => floorWith([box("r", 0, 0, 5, 4, "a")], { openings: [opening("w", "r", "window", { leaves, contact2: "binary_sensor.win2", tilt2: "none" } as never)] }); + assert.equal(openingEntities(hass, [make(1)]).get("w")?.contact2, null); + assert.equal(openingEntities(hass, [make(2)]).get("w")?.contact2, "binary_sensor.win2"); + assert.equal(openingEntities(hass, [make(2)]).get("w")?.tilt2, null); +}); + +test("window position from plain contacts, handle words (also German) and a window_state attribute", () => { + assert.equal(windowPosition(entity("binary_sensor.a", "on")), "open"); + assert.equal(windowPosition(entity("binary_sensor.a", "off")), "closed"); + assert.equal(windowPosition(entity("sensor.handle", "tilted")), "tilted"); + assert.equal(windowPosition(entity("sensor.handle", "Gekippt")), "tilted"); + assert.equal(windowPosition(entity("sensor.handle", "geschlossen")), "closed"); + assert.equal(windowPosition(entity("sensor.handle", "offen")), "open"); + assert.equal(windowPosition(entity("binary_sensor.a", "off", { window_state: "tilted" })), "tilted"); + assert.equal(windowPosition(entity("sensor.handle", "banana")), null); + assert.equal(windowPosition(entity("sensor.handle", "unavailable")), null); + assert.equal(windowPosition(undefined), null); +}); + +const plain = (extra: Record = {}) => ({ cover: null, contact: null, tilt: null, ...extra }); + +test("a window: open by contact, tilted by a tilt sensor, and tilting wins over open", () => { + const hass = hassOf([entity("binary_sensor.c", "on"), entity("binary_sensor.t", "on")]); + assert.deepEqual({ ...openingState(hass, plain({ contact: "binary_sensor.c" })) }, { open: 1, open2: 0, tilt: 0, tilt2: 0, cover: null, sensed: true }); + const both = openingState(hass, plain({ contact: "binary_sensor.c", tilt: "binary_sensor.t" })); + assert.deepEqual([both.open, both.tilt], [0, 1]); +}); + +test("a tilt angle sensor tilts as far as it reports, with maximum, offset and sign", () => { + const hass = hassOf([entity("sensor.angle", "7.5")]); + assert.equal(openingState(hass, plain({ tiltAngle: "sensor.angle", tiltMax: 15 })).tilt, 0.5); + assert.equal(openingState(hass, plain({ tiltAngle: "sensor.angle", tiltMax: 15, tiltOffset: 7.5 })).tilt, 0, "offset removes it"); + assert.equal(openingState(hass, plain({ tiltAngle: "sensor.angle", tiltInvert: true })).tilt, 0, "inverted negative clamps to 0"); + assert.equal(openingState(hass, plain({ tiltAngle: "sensor.angle", tiltMax: 5 })).tilt, 1, "more than the maximum is fully tilted"); + assert.equal(openingState(hass, plain({ tiltAngle: "sensor.angle", tiltMax: 15, tiltOffset: 7 })).tilt, 0, "a small angle (under 8 %) counts as closed"); +}); + +test("blinds: position sensor (percent or fraction), else the cover's own position or state", () => { + const hass = hassOf([entity("sensor.pos", "30", { unit_of_measurement: "%" }), entity("sensor.frac", "0.25"), entity("cover.a", "open", { current_position: 80 }), entity("cover.b", "closed"), entity("cover.c", "closing"), entity("cover.d", "open")]); + assert.equal(openingState(hass, plain({ position: "sensor.pos" })).cover, 0.7); + assert.equal(openingState(hass, plain({ position: "sensor.frac" })).cover, 0.75); + assert.equal(openingState(hass, plain({ position: "sensor.pos", positionInverted: true })).cover, 0.3); + assert.ok(Math.abs(openingState(hass, plain({ cover: "cover.a" })).cover! - 0.2) < 1e-9); + assert.equal(openingState(hass, plain({ cover: "cover.b" })).cover, 1); + assert.equal(openingState(hass, plain({ cover: "cover.c" })).cover, 0.5); + assert.equal(openingState(hass, plain({ cover: "cover.d" })).cover, 0); + assert.equal(openingState(hass, plain({ cover: "cover.missing" })).cover, 0); + assert.equal(openingState(hass, plain()).cover, null); +}); + +test("a door follows its contact, or stands half open, or is shut when told so", () => { + const hass = hassOf([entity("binary_sensor.d", "on"), entity("binary_sensor.closed", "off")]); + assert.equal(openingState(hass, plain({ contact: "binary_sensor.d" }), "door").open, 1); + assert.equal(openingState(hass, plain({ contact: "binary_sensor.closed" }), "door").open, 0); + assert.equal(openingState(hass, plain(), "door").open, DOOR_DEFAULT_OPEN); + assert.equal(openingState(hass, plain({ shut: true }), "door").open, 0); +}); + +test("a door with its own opening angle stands at it without a sensor, but is not taken for open", () => { + const hass = hassOf([entity("binary_sensor.closed", "off")]); + const free = openingState(hass, plain({ angled: true }), "door"); + assert.equal(free.open, 1); + assert.equal(free.assumed, true); + assert.equal(openingState(hass, plain({ angled: true, shut: true }), "door").open, 0); + const sensed = openingState(hass, plain({ angled: true, contact: "binary_sensor.closed" }), "door"); + assert.equal(sensed.open, 0); + assert.equal(sensed.assumed, false); +}); + +test("a door with a roller shutter reports the blind as well", () => { + const hass = hassOf([entity("cover.shutter", "open", { current_position: 25 })]); + const state = openingState(hass, plain({ cover: "cover.shutter", shut: true }), "door"); + assert.equal(state.cover, 0.75); + assert.equal(state.sensed, true); +}); + +test("a garage door shows its cover, else its contact, else closed", () => { + const hass = hassOf([entity("cover.g", "open", { current_position: 100 }), entity("binary_sensor.gc", "on")]); + assert.equal(openingState(hass, plain({ cover: "cover.g" }), "garage").cover, 0); + assert.equal(openingState(hass, plain({ contact: "binary_sensor.gc" }), "garage").cover, 0); + assert.equal(openingState(hass, plain(), "garage").cover, 1); + assert.equal(openingState(hass, plain(), "garage").sensed, false); +}); + +test("a garage door whose cover is unknown (a remote without feedback) follows its contact", () => { + const hass = hassOf([entity("cover.remote", "unknown", { assumed_state: true }), entity("binary_sensor.shut", "off"), entity("binary_sensor.gc", "on")]); + assert.equal(openingState(hass, plain({ cover: "cover.remote", contact: "binary_sensor.shut" }), "garage").cover, 1); + assert.equal(openingState(hass, plain({ cover: "cover.remote", contact: "binary_sensor.gc" }), "garage").cover, 0); + assert.equal(openingState(hass, plain({ cover: "cover.remote" }), "garage").cover, 0, "without a contact it stays as before"); +}); + +test("the second leaf of a double window has contact and tilt of its own and stays closed without sensors", () => { + const hass = hassOf([entity("binary_sensor.c2", "on"), entity("binary_sensor.t2", "on")]); + assert.deepEqual([openingState(hass, plain({ contact2: "binary_sensor.c2" })).open2, openingState(hass, plain()).open2], [1, 0]); + const tilted = openingState(hass, plain({ contact2: "binary_sensor.c2", tilt2: "binary_sensor.t2" })); + assert.deepEqual([tilted.open2, tilted.tilt2], [0, 1]); +}); + +test("'sensed' says whether any sensor answered", () => { + const hass = hassOf([entity("binary_sensor.c", "unavailable"), entity("binary_sensor.d", "off")]); + assert.equal(openingState(hass, plain({ contact: "binary_sensor.c" })).sensed, false); + assert.equal(openingState(hass, plain({ contact: "binary_sensor.d" })).sensed, true); + assert.equal(openingState(hass, plain()).sensed, false); +}); + +test("a door's smart lock is linked by hand and says when it stands unlocked", () => { + const locks = [entity("lock.front", "unlocked"), entity("lock.back", "locked"), entity("lock.side", "jammed")]; + const hass = hassOf([...sensors, ...locks], registry); + const floor = floorWith([box("r", 0, 0, 5, 4, "a")], { + openings: [opening("d", "r", "door", { lock: "lock.front" }), opening("e", "r", "door", { lock: "lock.back" }), opening("w", "r", "window", { lock: "lock.front" })], + }); + const links = openingEntities(hass, [floor]); + assert.equal(links.get("d")?.lock, "lock.front"); + assert.equal(links.get("w")?.lock, null, "only doors take a lock"); + assert.equal(openingState(hass, links.get("d")!, "door").unlocked, true); + assert.equal(openingState(hass, links.get("e")!, "door").unlocked, false); + assert.equal(isUnlocked(hass, "lock.side"), false, "a jammed lock does not glow"); + assert.equal(isUnlocked(hass, null), false); +}); + +test("a wide window's second blind and a venetian blind's slats", () => { + const hass = hassOf([ + entity("cover.left", "open", { current_position: 100, current_tilt_position: 30 }), + entity("cover.right", "closed", { current_position: 0 }), + ]); + const state = openingState(hass, { cover: "cover.left", contact: null, tilt: null, cover2: "cover.right" }); + assert.equal(state.cover, 0); + assert.equal(state.cover2, 1); + assert.equal(state.slats, 0.3); + assert.equal(openingState(hass, { cover: "cover.right", contact: null, tilt: null }).cover2, undefined, "no second blind"); +}); diff --git a/frontend/src/entities/openings.ts b/frontend/src/entities/openings.ts new file mode 100644 index 0000000..00b219a --- /dev/null +++ b/frontend/src/entities/openings.ts @@ -0,0 +1,237 @@ +// Doors, windows and garage doors: which entities belong to each opening, and what state they are in. + +import type { Floor, Opening } from "../model.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; +import { isUnavailable, kindOf } from "./kinds.ts"; +import { roomEntities } from "./registry.ts"; + +export interface OpeningEntities { + cover: string | null; + contact: string | null; + tilt: string | null; + /** Contact and tilt sensor of the second leaf of a double door or window. */ + contact2?: string | null; + tilt2?: string | null; + /** A sensor with the blind's position while it moves (0-100 % or 0-1, open is high). */ + position?: string | null; + positionInverted?: boolean; + /** A sensor with the sash's tilt angle in degrees, the angle that counts as fully tilted, an offset and the sign. */ + tiltAngle?: string | null; + tiltMax?: number | null; + tiltOffset?: number | null; + tiltInvert?: boolean; + /** A door without a sensor is drawn closed. */ + shut?: boolean; + /** A door with its own opening angle stands at that angle without a sensor, instead of half open. */ + angled?: boolean; + /** A door's smart lock. */ + lock?: string | null; + /** A second blind of a wide window (its right half, seen from the room). */ + cover2?: string | null; +} + +const BLIND_CLASSES = new Set([undefined, "shutter", "blind", "awning", "shade", "curtain", "window"]); +const GARAGE_COVER_CLASSES = new Set(["garage", "gate"]); +const WINDOW_CONTACT_CLASSES = new Set(["window", "opening"]); + +/** The n-th opening gets the n-th entity. With `shared`, one single entity serves every opening. */ +function assign(openings: Opening[], entities: string[], shared = false): Map { + const result = new Map(); + openings.forEach((opening, i) => { + const entity = shared && entities.length === 1 ? entities[0] : entities[i]; + if (entity) result.set(opening.id, entity); + }); + return result; +} + +/** An explicit choice ("none" switches it off) wins over the automatic match. */ +const chosenOr = (choice: string | null, automatic: string | undefined): string | null => (choice === "none" ? null : (choice ?? automatic ?? null)); +const unlessNone = (ref: string | null | undefined): string | null => (ref && ref !== "none" ? ref : null); + +/** + * The entities of every door and window: those set by hand, otherwise matched automatically with the covers and + * contact sensors of the room's area, in the order the openings sit along the room's outline. + */ +export function openingEntities(hass: HomeAssistant, floors: readonly Floor[]): Map { + const result = new Map(); + for (const floor of floors) { + for (const room of floor.rooms) { + const openings = floor.openings.filter((o) => o.room_id === room.id).sort((a, b) => a.edge - b.edge || a.offset - b.offset); + if (openings.length === 0) continue; + const entities = roomEntities(hass, room); + const deviceClass = (id: string) => hass.states[id]?.attributes.device_class as string | undefined; + const binaries = (classes: (cls: string) => boolean) => entities.filter((id) => kindOf(id) === "binary" && classes(deviceClass(id) ?? "")); + const ofType = (type: Opening["type"]) => openings.filter((o) => o.type === type); + + // one blind for the whole room (a group, say) serves every window; a contact belongs to one window + const windowBlind = assign(ofType("window"), entities.filter((id) => kindOf(id) === "cover" && BLIND_CLASSES.has(deviceClass(id))), true); + const windowContact = assign(ofType("window"), binaries((c) => WINDOW_CONTACT_CLASSES.has(c))); + const doorContact = assign(ofType("door"), binaries((c) => c === "door")); + const garageCover = assign(ofType("garage"), entities.filter((id) => kindOf(id) === "cover" && GARAGE_COVER_CLASSES.has(deviceClass(id) ?? ""))); + const garageContact = assign(ofType("garage"), binaries((c) => c === "garage_door")); + + for (const o of openings) { + const covers = o.type === "window" ? windowBlind : o.type === "garage" ? garageCover : null; + const contacts = o.type === "window" ? windowContact : o.type === "garage" ? garageContact : doorContact; + const secondLeaf = o.leaves === 2; + result.set(o.id, { + cover: chosenOr(o.cover, covers?.get(o.id)), + // a window with a handle sensor gets no plain contact automatically + contact: o.sensor === "handle" && o.contact == null ? null : chosenOr(o.contact, contacts.get(o.id)), + tilt: o.tilt === "none" ? null : o.tilt, + contact2: secondLeaf ? unlessNone(o.contact2) : null, + tilt2: secondLeaf ? unlessNone(o.tilt2) : null, + position: unlessNone(o.position), + positionInverted: !!o.position_inverted, + tiltAngle: unlessNone(o.tilt_angle), + tiltMax: o.tilt_max ?? null, + tiltOffset: o.tilt_offset ?? null, + tiltInvert: !!o.tilt_invert, + shut: !!o.shut, + angled: o.type === "door" && !!o.open_angle, + lock: o.type === "door" ? unlessNone(o.lock) : null, + cover2: o.type === "garage" ? null : unlessNone(o.cover2), + }); + } + } + } + return result; +} + +type SashPosition = "open" | "tilted" | "closed"; + +const POSITION_WORDS: [RegExp, SashPosition][] = [ + [/^(tilted|tilt|gekippt|kipp)/i, "tilted"], + [/^(open|opened|offen|geöffnet|on)$/i, "open"], + [/^(closed|close|geschlossen|zu|off)$/i, "closed"], +]; + +/** + * Whether a window or door is open, tilted or closed, from its contact. Understands plain contacts (on is open), + * handle sensors with three states (also in German), and contacts that report it in a `window_state` attribute. + * Null when the sensor says nothing usable. + */ +export function windowPosition(st: HassEntity | undefined): SashPosition | null { + if (!st || isUnavailable(st)) return null; + const fromAttribute = st.attributes.window_state; + for (const text of [typeof fromAttribute === "string" ? fromAttribute : "", st.state]) { + const word = text.trim(); + const match = word && POSITION_WORDS.find(([pattern]) => pattern.test(word)); + if (match) return match[1]; + } + return null; +} + +/** A door leaf without a contact sensor stands half open, so the doorway stays readable. */ +export const DOOR_DEFAULT_OPEN = 0.5; + +/** How far a blind is open according to a position sensor: a percentage or a 0-1 fraction. Null when unknown. */ +function reportedPosition(hass: HomeAssistant, id: string | null | undefined): number | null { + const st = id ? hass.states[id] : undefined; + const value = st && !isUnavailable(st) ? Number(st.state) : NaN; + if (!Number.isFinite(value)) return null; + const isPercent = st!.attributes.unit_of_measurement === "%" || value > 1; + return Math.min(1, Math.max(0, isPercent ? value / 100 : value)); +} + +/** How closed the blind is (0 open, 1 closed) from the position sensor, else from the cover entity. Null without cover data. */ +/** How far a cover entity is closed (0 up, 1 down), or null without one. */ +function coverClosed(hass: HomeAssistant, id: string | null | undefined): number | null { + const cover = id ? hass.states[id] : undefined; + if (!cover || isUnavailable(cover)) return id ? 0 : null; + const percent = cover.attributes.current_position; + if (typeof percent === "number") return 1 - Math.min(100, Math.max(0, percent)) / 100; + if (cover.state === "closed") return 1; + return cover.state === "opening" || cover.state === "closing" ? 0.5 : 0; +} + +/** How far the slats of a venetian blind are open (0 shut, 1 level), from its tilt position; null when it reports none. */ +function slatsOpen(hass: HomeAssistant, id: string | null | undefined): number | null { + const tilt = id ? hass.states[id]?.attributes.current_tilt_position : undefined; + return typeof tilt === "number" ? Math.min(100, Math.max(0, tilt)) / 100 : null; +} + +function blindClosedFraction(hass: HomeAssistant, e: OpeningEntities): number | null { + const reported = reportedPosition(hass, e.position); + if (reported !== null) return e.positionInverted ? reported : 1 - reported; + const cover = e.cover ? hass.states[e.cover] : undefined; + if (cover && !isUnavailable(cover)) { + const percent = cover.attributes.current_position; + if (typeof percent === "number") return 1 - Math.min(100, Math.max(0, percent)) / 100; + if (cover.state === "closed") return 1; + return cover.state === "opening" || cover.state === "closing" ? 0.5 : 0; + } + return e.cover ? 0 : null; +} + +/** A smart lock that stands unlocked or open (unlocking counts once it has happened, jammed and unknown do not). */ +export function isUnlocked(hass: HomeAssistant, lock: string | null | undefined): boolean { + const state = lock ? hass.states[lock]?.state : undefined; + return state === "unlocked" || state === "open" || state === "opening"; +} + +export interface OpeningState { + open: number; + open2: number; + tilt: number; + tilt2: number; + cover: number | null; + sensed: boolean; + /** A door whose smart lock is unlocked (or open). */ + unlocked?: boolean; + /** A door leaf drawn where it is assumed to stand, as no sensor tells: it does not glow as open. */ + assumed?: boolean; + /** The second blind of a wide window (its right half): how far it is closed. */ + cover2?: number | null; + /** Venetian blinds: how far the slats are open (0 shut, 1 level), from the cover's tilt position. */ + slats?: number | null; +} + +/** + * The look of an opening from its entities. Windows: sash open or tilted, and how far the blind is closed. Doors: leaf + * open (contact) or half open. Garage doors: closed fraction from the cover or the contact. + */ +export function openingState(hass: HomeAssistant, e: OpeningEntities, type: Opening["type"] = "window"): OpeningState { + const isOn = (id: string | null | undefined) => !!id && hass.states[id]?.state === "on"; + const isKnown = (id: string | null | undefined) => !!id && !!hass.states[id] && !isUnavailable(hass.states[id]); + const positionOf = (id: string | null | undefined) => (id ? windowPosition(hass.states[id]) : null); + const cover = blindClosedFraction(hass, e); + + if (type === "door") { + // a door with a roller shutter (front door, patio door): the blind comes down over it + const leaf = positionOf(e.contact); + const open = leaf === null ? (e.shut ? 0 : e.angled ? 1 : DOOR_DEFAULT_OPEN) : leaf === "closed" ? 0 : 1; + return { open, open2: positionOf(e.contact2) === "open" ? 1 : 0, tilt: 0, tilt2: 0, cover, sensed: leaf !== null || cover !== null, unlocked: isUnlocked(hass, e.lock), assumed: leaf === null }; + } + if (type === "garage") { + // a garage door without a cover shows its contact: open or closed; so does one whose cover cannot tell (a remote without + // feedback stays unknown) + const sensed = cover !== null || isKnown(e.contact); + const coverTells = reportedPosition(hass, e.position) !== null || isKnown(e.cover); + const fromContact = isKnown(e.contact) ? (isOn(e.contact) ? 0 : 1) : null; + return { open: 0, open2: 0, tilt: 0, tilt2: 0, cover: (coverTells ? cover : (fromContact ?? cover)) ?? 1, sensed }; + } + + // a window: the second leaf stays closed without a sensor and tilts like the first + const secondTilted = isOn(e.tilt2) || positionOf(e.tilt2) === "tilted" || positionOf(e.contact2) === "tilted"; + let tilted = isOn(e.tilt) || positionOf(e.tilt) === "tilted" || positionOf(e.contact) === "tilted"; + let tiltAmount = tilted ? 1 : 0; + // an angle sensor tilts the sash as far as it reports, as a share of the angle that counts as fully tilted + const rawAngle = e.tiltAngle ? Number(hass.states[e.tiltAngle]?.state) : NaN; + if (Number.isFinite(rawAngle)) { + const degrees = (rawAngle - (e.tiltOffset ?? 0)) * (e.tiltInvert ? -1 : 1); + tiltAmount = Math.min(1, Math.max(0, degrees / (e.tiltMax || 15))); + if (tiltAmount < 0.08) tiltAmount = 0; + tilted = tiltAmount > 0; + } + return { + open: positionOf(e.contact) === "open" && !tilted ? 1 : 0, + open2: positionOf(e.contact2) === "open" && !secondTilted ? 1 : 0, + tilt: tiltAmount, + tilt2: secondTilted ? 1 : 0, + cover, + sensed: isKnown(e.contact) || isKnown(e.tilt) || Number.isFinite(rawAngle), + ...(e.cover2 ? { cover2: coverClosed(hass, e.cover2) } : {}), + ...(slatsOpen(hass, e.cover) !== null ? { slats: slatsOpen(hass, e.cover) } : {}), + }; +} diff --git a/frontend/src/entities/pictures.test.ts b/frontend/src/entities/pictures.test.ts new file mode 100644 index 0000000..83e8d80 --- /dev/null +++ b/frontend/src/entities/pictures.test.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, hassOf } from "./fixtures.ts"; +import { pictureUrl, storedPictureId } from "./pictures.ts"; + +test("a frame's photo from a stored picture, a URL or an entity's picture", () => { + const hass = hassOf([entity("image.photo_of_the_day", "2026-11-02", { entity_picture: "/api/image_proxy/image.photo_of_the_day?token=1" }), entity("camera.door", "idle")]); + const stored = (id: string) => (id === "img_1" ? "data:image/jpeg;base64,AAA" : null); + assert.equal(pictureUrl(hass, "image:img_1", stored), "data:image/jpeg;base64,AAA"); + assert.equal(pictureUrl(hass, "image:img_2", stored), null, "not loaded yet"); + assert.equal(pictureUrl(hass, "/local/holiday.jpg", stored), "/local/holiday.jpg"); + assert.equal(pictureUrl(hass, "https://example.org/a.png", stored), "https://example.org/a.png"); + assert.equal(pictureUrl(hass, "image.photo_of_the_day", stored), "/api/image_proxy/image.photo_of_the_day?token=1"); + assert.equal(pictureUrl(hass, "camera.door", stored), null, "an entity without a picture"); + assert.equal(pictureUrl(hass, "", stored), null); + assert.equal(storedPictureId("image:img_1"), "img_1"); + assert.equal(storedPictureId("/local/a.jpg"), null); +}); diff --git a/frontend/src/entities/pictures.ts b/frontend/src/entities/pictures.ts new file mode 100644 index 0000000..5f8f396 --- /dev/null +++ b/frontend/src/entities/pictures.ts @@ -0,0 +1,23 @@ +// Where a picture frame's photo comes from: a picture stored with the plan ("image:"), a URL (/local/…, https://…), or an +// image, camera or media player entity whose picture it shows (a photo of the day, the doorbell camera, the album cover). + +import type { HomeAssistant } from "../types.ts"; + +/** The prefix of a picture stored with the plan. */ +export const STORED_PICTURE = "image:"; + +/** The URL of a frame's photo, or null when there is none (yet): `stored` turns a stored picture's id into its data. */ +export function pictureUrl(hass: HomeAssistant | undefined, value: string | null | undefined, stored: (id: string) => string | null): string | null { + const v = (value ?? "").trim(); + if (!v) return null; + if (v.startsWith(STORED_PICTURE)) return stored(v.slice(STORED_PICTURE.length)); + if (/^(https?:\/\/|\/)/.test(v)) return v; + if (/^[a-z_]+\.[a-z0-9_]+$/.test(v)) { + const picture = hass?.states[v]?.attributes.entity_picture; + return typeof picture === "string" && picture ? picture : null; + } + return null; +} + +/** The id of a stored picture a frame shows, or null (a URL or an entity is no stored picture). */ +export const storedPictureId = (value: string | null | undefined): string | null => (value?.startsWith(STORED_PICTURE) ? value.slice(STORED_PICTURE.length) : null); diff --git a/frontend/src/entities/registry.test.ts b/frontend/src/entities/registry.test.ts new file mode 100644 index 0000000..792cdae --- /dev/null +++ b/frontend/src/entities/registry.test.ts @@ -0,0 +1,201 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, floorWith, box, hassOf } from "./fixtures.ts"; +import { registerPlugin, resetPlugins } from "../plugins/registry.ts"; +import { areaEntities, entityAreaId, entityKind, groupByDevice, isHubDevice, isRelevant, isRoomClimateSensor, otherAreaEntities, powerSensorsOf, primaryEntities, roomClimateSensors, roomClimateValue, unassignedEntities } from "./registry.ts"; + +const lounge = hassOf( + [ + entity("light.ceiling", "on"), + entity("light.standing", "off"), + entity("switch.hidden", "on"), + entity("switch.firmware", "off"), + entity("sensor.temp", "21", { device_class: "temperature" }), + entity("sensor.battery", "80", { device_class: "battery", unit_of_measurement: "%" }), + entity("vacuum.robot", "docked"), + ], + { + "light.ceiling": { area_id: "lounge" }, + "light.standing": { device_id: "d1" }, + "switch.hidden": { area_id: "lounge", hidden: true }, + "switch.firmware": { area_id: "lounge", entity_category: "config" }, + "sensor.temp": { area_id: "lounge" }, + "sensor.battery": { area_id: "lounge" }, + "vacuum.robot": { area_id: "lounge" }, + }, + { areas: { lounge: { area_id: "lounge", name: "Lounge" } }, devices: { d1: { id: "d1", area_id: "lounge" } } }, +); + +test("an entity's area is its own, else its device's", () => { + assert.equal(entityAreaId(lounge, "light.ceiling"), "lounge"); + assert.equal(entityAreaId(lounge, "light.standing"), "lounge"); + assert.equal(entityAreaId(lounge, "light.unknown"), null); +}); + +test("an area lists visible entities of handled kinds, lights before sensors", () => { + const ids = areaEntities(lounge, "lounge"); + assert.deepEqual(ids, ["light.ceiling", "light.standing", "sensor.temp"]); + assert.deepEqual(areaEntities(lounge, null), []); + assert.deepEqual(areaEntities(lounge, "attic"), []); +}); + +test("meters and air sensors are shown, battery and signal sensors are not", () => { + const hass = hassOf([entity("sensor.gas", "12", { unit_of_measurement: "m³" }), entity("sensor.rssi", "-60", { device_class: "signal_strength" }), entity("sensor.co2", "700", { device_class: "carbon_dioxide" })]); + assert.equal(isRelevant(hass, "sensor.gas"), true); + assert.equal(isRelevant(hass, "sensor.co2"), true); + assert.equal(isRelevant(hass, "sensor.rssi"), false); + assert.equal(isRelevant(hass, "light.missing"), false); +}); + +test("a binary sensor without a class shows only when it was given an area by hand", () => { + const hass = hassOf([entity("binary_sensor.flag", "on"), entity("binary_sensor.noise", "on")], { "binary_sensor.flag": { area_id: "x" }, "binary_sensor.noise": {} }); + assert.equal(isRelevant(hass, "binary_sensor.flag"), true); + assert.equal(isRelevant(hass, "binary_sensor.noise"), false); +}); + +test("entities without an area are offered separately, including ones missing from the registry", () => { + const hass = hassOf( + [entity("light.template", "on"), entity("sensor.counter", "5", { unit_of_measurement: "pcs" }), entity("sensor.rssi", "-60", { device_class: "signal_strength", unit_of_measurement: "dBm" }), entity("scene.movie", "off")], + { "light.template": {}, "sensor.counter": {}, "sensor.rssi": {}, "scene.movie": {} }, + ); + assert.deepEqual(unassignedEntities(hass), ["light.template", "sensor.counter"]); +}); + +test("other areas are listed by name with their placeable entities only", () => { + const hass = hassOf( + [entity("light.a", "on"), entity("scene.a", "off"), entity("light.b", "on")], + { "light.a": { area_id: "kitchen" }, "scene.a": { area_id: "kitchen" }, "light.b": { area_id: "bath" } }, + { areas: { kitchen: { area_id: "kitchen", name: "Kitchen" }, bath: { area_id: "bath", name: "Bath" } } }, + ); + const others = otherAreaEntities(hass, "bath"); + assert.deepEqual(others, [{ areaId: "kitchen", name: "Kitchen", ids: ["light.a"] }]); +}); + +test("devices are grouped: the entity without a name of its own is the main one", () => { + const hass = hassOf( + [entity("light.strip", "on"), entity("sensor.strip_power", "5"), entity("light.solo", "off")], + { "light.strip": { device_id: "d" }, "sensor.strip_power": { device_id: "d", name: "Power" }, "light.solo": {} }, + ); + const groups = groupByDevice(hass, ["sensor.strip_power", "light.strip", "light.solo"]); + assert.deepEqual(groups, [{ primary: "light.strip", others: ["sensor.strip_power"] }, { primary: "light.solo", others: [] }]); + assert.deepEqual(primaryEntities(hass, ["sensor.strip_power", "light.strip", "light.solo"]), ["light.strip", "light.solo"]); +}); + +test("power sensors are found per device, and a device in several areas is a hub", () => { + const hass = hassOf( + [entity("sensor.p1", "1", { device_class: "power" }), entity("light.k", "on"), entity("light.b", "on")], + { "sensor.p1": { device_id: "dev" }, "light.k": { device_id: "hub", area_id: "kitchen" }, "light.b": { device_id: "hub", area_id: "bath" } }, + ); + assert.deepEqual(powerSensorsOf(hass, "dev"), ["sensor.p1"]); + assert.deepEqual(powerSensorsOf(hass, "nothing"), []); + assert.equal(isHubDevice(hass, "hub"), true); + assert.equal(isHubDevice(hass, "dev"), false); +}); + +test("the lookups follow the registry: a new registry is read again, same objects are not", () => { + const first = hassOf([entity("light.a", "on")], { "light.a": { area_id: "x" } }); + assert.deepEqual(areaEntities(first, "x"), ["light.a"]); + const second = { ...first, entities: { "light.a": { entity_id: "light.a", area_id: "y" } } } as typeof first; + assert.deepEqual(areaEntities(second, "x"), []); + assert.deepEqual(areaEntities(second, "y"), ["light.a"]); + // an entity that appears later in the states is noticed + const third = { ...second, states: { ...second.states, "light.b": entity("light.b", "on") }, entities: { ...second.entities, "light.b": { entity_id: "light.b", area_id: "y" } } } as typeof first; + assert.deepEqual(areaEntities(third, "y"), ["light.a", "light.b"]); +}); + +test("room sensors skip device temperatures: by the device's other entities and by name", () => { + const hass = hassOf( + [entity("sensor.room_t", "21", { device_class: "temperature" }), entity("sensor.printer_nozzle", "200", { device_class: "temperature" }), entity("sensor.heater_t", "40", { device_class: "temperature" }), entity("climate.heater", "heat"), entity("sensor.flow_temp", "35", { device_class: "temperature" })], + { "sensor.room_t": { area_id: "a", device_id: "d1" }, "sensor.printer_nozzle": { area_id: "a", device_id: "d2" }, "sensor.heater_t": { area_id: "a", device_id: "d3" }, "climate.heater": { device_id: "d3" }, "sensor.flow_temp": { area_id: "a" } }, + ); + assert.equal(isRoomClimateSensor(hass, "sensor.room_t"), true); + assert.equal(isRoomClimateSensor(hass, "sensor.printer_nozzle"), false, "name says nozzle"); + assert.equal(isRoomClimateSensor(hass, "sensor.heater_t"), false, "its device is a heater"); + assert.equal(isRoomClimateSensor(hass, "sensor.flow_temp"), false, "heating flow"); +}); + +test("a room's climate: automatic from the area, or a chosen sensor, or none", () => { + const room = box("r", 0, 0, 4, 3, "a"); + const hass = hassOf( + [entity("sensor.t1", "20", { device_class: "temperature" }), entity("sensor.t2", "70", { device_class: "temperature", unit_of_measurement: "°F" }), entity("sensor.h", "50", { device_class: "humidity" }), entity("sensor.chosen", "10", { device_class: "temperature" })], + { "sensor.t1": { area_id: "a" }, "sensor.t2": { area_id: "a" }, "sensor.h": { area_id: "a" }, "sensor.chosen": { area_id: "b" } }, + ); + assert.deepEqual(roomClimateSensors(hass, null, room, "temperature"), ["sensor.t1", "sensor.t2"]); + assert.ok(Math.abs(roomClimateValue(hass, null, room, "temperature")! - (20 + (70 - 32) * 5 / 9) / 2) < 1e-9, "Fahrenheit is converted"); + assert.equal(roomClimateValue(hass, null, room, "humidity"), 50); + assert.equal(roomClimateValue(hass, null, room, "co2"), null); + assert.deepEqual(roomClimateSensors(hass, null, { ...room, climate: { temperature: "sensor.chosen" } }, "temperature"), ["sensor.chosen"]); + assert.deepEqual(roomClimateSensors(hass, null, { ...room, climate: { temperature: "none" } }, "temperature"), []); + assert.deepEqual(roomClimateSensors(hass, null, { ...room, climate: { temperature: ["sensor.t1", "sensor.chosen", "sensor.gone"] } }, "temperature"), ["sensor.t1", "sensor.chosen"], "several chosen sensors are all read"); +}); + +test("a sensor of the area placed in another room counts there, one placed inside counts here", () => { + const here = box("here", 0, 0, 4, 3, "a"); + const there = box("there", 5, 0, 9, 3, "a"); + const hass = hassOf( + [entity("sensor.in_area", "20", { device_class: "temperature" }), entity("sensor.placed_here", "22", { device_class: "temperature" })], + { "sensor.in_area": { area_id: "a" }, "sensor.placed_here": { area_id: "other" } }, + ); + const floor = floorWith([here, there], { placements: [{ entity_id: "sensor.in_area", x: 6, z: 1, y: null, mount: null }, { entity_id: "sensor.placed_here", x: 1, z: 1, y: null, mount: null }] }); + assert.deepEqual(roomClimateSensors(hass, floor, here, "temperature"), ["sensor.placed_here"]); + assert.deepEqual(roomClimateSensors(hass, floor, there, "temperature"), ["sensor.in_area"]); +}); + +test("a hub's room sensors still count, although its other entities are lights", () => { + const hass = hassOf( + [entity("sensor.bus_t_k", "21", { device_class: "temperature" }), entity("light.bus_k", "on"), entity("light.bus_b", "on")], + { "sensor.bus_t_k": { area_id: "k", device_id: "bus" }, "light.bus_k": { area_id: "k", device_id: "bus" }, "light.bus_b": { area_id: "b", device_id: "bus" } }, + ); + assert.equal(isRoomClimateSensor(hass, "sensor.bus_t_k"), true); +}); + +test("entities a plugin gives a kind are offered like the others, in their area and without one", () => { + registerPlugin({ id: "robot", apiVersion: 1, devices: [{ match: (id) => id.startsWith("vacuum."), kind: "switch" }] }); + try { + const hass = hassOf( + [entity("vacuum.rob", "docked"), entity("vacuum.loose", "docked"), entity("lawn_mower.x", "docked"), entity("light.a", "on")], + { "vacuum.rob": { area_id: "kitchen" }, "vacuum.loose": {}, "lawn_mower.x": {}, "light.a": { area_id: "kitchen" } }, + { areas: { kitchen: { area_id: "kitchen", name: "Kitchen" } } }, + ); + assert.deepEqual(areaEntities(hass, "kitchen"), ["light.a", "vacuum.rob"]); + assert.deepEqual(unassignedEntities(hass), ["vacuum.loose"]); + assert.equal(entityKind(hass, "vacuum.rob"), "switch"); + assert.equal(entityKind(hass, "lawn_mower.x"), null); + } finally { + resetPlugins(); + } +}); + +test("wall buttons and doorbells (event entities) are offered, other events are not", () => { + const hass = hassOf([entity("event.hall_button", "unknown", { device_class: "button" }), entity("event.bell", "unknown", { device_class: "doorbell" }), entity("event.remote", "unknown"), entity("event.motion", "unknown", { device_class: "motion" })]); + assert.equal(isRelevant(hass, "event.hall_button"), true); + assert.equal(isRelevant(hass, "event.bell"), true); + assert.equal(isRelevant(hass, "event.remote"), true); + assert.equal(isRelevant(hass, "event.motion"), false); +}); + +test("an NVR's camera that a plugin takes on leads its device, before the device's motion sensors", () => { + registerPlugin({ id: "cams-test", name: "Cams", version: "1.0.0", apiVersion: 1, devices: [{ match: (id: string) => id.startsWith("camera."), kind: "sensor" }] } as never); + const nvr = { area_id: "ext", device_id: "nvr" }; + const hass = hassOf( + [entity("binary_sensor.nvr_motion_1", "off", { device_class: "motion" }), entity("binary_sensor.nvr_person_1", "off", { device_class: "occupancy" }), entity("camera.camera_1_live", "idle")], + { "binary_sensor.nvr_motion_1": nvr, "binary_sensor.nvr_person_1": nvr, "camera.camera_1_live": nvr } as never, + ); + const ids = areaEntities(hass, "ext"); + assert.equal(ids[0], "camera.camera_1_live"); + assert.equal(groupByDevice(hass, ids)[0].primary, "camera.camera_1_live"); + resetPlugins(); +}); + +test("a sensor a plugin handles is listed whatever its device class, and leads its device", () => { + registerPlugin({ id: "printer-test", name: "Printer", version: "1.0.0", apiVersion: 1, devices: [{ match: (id: string) => id.endsWith("_current_print_state"), kind: "sensor" }] } as never); + const printer = { area_id: "work", device_id: "voron" }; + const hass = hassOf( + [entity("sensor.voron_current_print_state", "printing", { device_class: "enum" }), entity("sensor.voron_extruder", "210", { device_class: "temperature", unit_of_measurement: "°C" }), entity("sensor.other_status", "ok", { device_class: "enum" })], + { "sensor.voron_current_print_state": printer, "sensor.voron_extruder": printer, "sensor.other_status": { area_id: "work" } } as never, + ); + assert.equal(isRelevant(hass, "sensor.voron_current_print_state"), true); + assert.equal(isRelevant(hass, "sensor.other_status"), false, "an enum sensor no plugin handles stays hidden"); + assert.equal(groupByDevice(hass, areaEntities(hass, "work"))[0].primary, "sensor.voron_current_print_state"); + resetPlugins(); +}); diff --git a/frontend/src/entities/registry.ts b/frontend/src/entities/registry.ts new file mode 100644 index 0000000..72e7e9c --- /dev/null +++ b/frontend/src/entities/registry.ts @@ -0,0 +1,268 @@ +// Lookups over Home Assistant's entity registry: which entities belong to an area, which are worth showing, +// which sensors measure a room, which power sensor goes with a device. The registry is indexed once and the index +// is reused, because every state change would otherwise walk thousands of entities for every room. + +import { pointInPolygon, type Floor, type Room } from "../model.ts"; +import type { HomeAssistant } from "../types.ts"; +import { onPluginsChanged, pluginKind } from "../plugins/registry.ts"; +import { domainOf, entityName, isPlaceable, isUnavailable, KIND_ORDER, kindOf, toCelsius, type DeviceKind } from "./kinds.ts"; + +/** Sensor classes that get a marker: room climate, air quality, power and energy, meters, light. */ +const SHOWN_SENSOR_CLASSES = new Set([ + "temperature", "humidity", "power", "carbon_dioxide", "energy", "gas", "water", "volume", "volume_storage", "volume_flow_rate", "illuminance", + "pressure", "atmospheric_pressure", "pm1", "pm25", "pm10", "volatile_organic_compounds", "volatile_organic_compounds_parts", + "carbon_monoxide", "nitrogen_dioxide", "moisture", "sound_pressure", +]); +/** A sensor without a class still counts when its unit is a meter's. */ +const METER_UNITS = new Set(["m³", "m3", "L", "l", "kWh", "Wh", "MWh", "lx"]); +const SHOWN_BINARY_CLASSES = new Set(["door", "window", "opening", "garage_door", "motion", "occupancy", "presence", "smoke", "moisture", "gas", "carbon_monoxide"]); +/** Sensor classes that describe the device itself and never make a marker. */ +const DIAGNOSTIC_CLASSES = new Set(["battery", "signal_strength", "timestamp", "date", "duration", "data_rate", "data_size", "frequency", "enum"]); + +/** The area an entity is in: its own, else its device's. */ +export function entityAreaId(hass: HomeAssistant, entityId: string): string | null { + const entry = hass.entities?.[entityId]; + if (!entry) return null; + return entry.area_id || (entry.device_id ? hass.devices?.[entry.device_id]?.area_id : null) || null; +} + +const isHiddenOrConfig = (hass: HomeAssistant, entityId: string): boolean => { + const entry = hass.entities?.[entityId]; + return !!(entry?.hidden || entry?.entity_category); +}; + +/** The kind of an entity: by its domain, else the one a plugin gives it (a robot vacuum shown as a switch). */ +export const entityKind = (hass: HomeAssistant, entityId: string): DeviceKind | null => kindOf(entityId) ?? pluginKind(entityId, hass.states[entityId]); + +/** Whether an entity is shown at all: visible, not a configuration entity, and of a kind that is handled. */ +export function isRelevant(hass: HomeAssistant, entityId: string): boolean { + const state = hass.states[entityId]; + if (!state || isHiddenOrConfig(hass, entityId)) return false; + // an entity a plugin takes care of is shown, whatever its domain or class (a printer's enum status sensor) + if (pluginKind(entityId, state) !== null) return true; + const kind = kindOf(entityId); + if (!kind) return false; + const deviceClass = state.attributes.device_class as string | undefined; + // wall buttons, remotes and doorbells (event entities) count, other events are integration internals + if (entityId.startsWith("event.")) return !deviceClass || deviceClass === "button" || deviceClass === "doorbell"; + if (kind === "sensor") return deviceClass ? SHOWN_SENSOR_CLASSES.has(deviceClass) : METER_UNITS.has(String(state.attributes.unit_of_measurement ?? "")); + // a binary sensor without a class is mostly integration noise, unless someone gave that entity an area by hand + if (kind === "binary") return deviceClass ? SHOWN_BINARY_CLASSES.has(deviceClass) : !!hass.entities?.[entityId]?.area_id; + return true; +} + +/** A numeric sensor with a unit: offered for devices without an area even when its class is unknown. */ +function isLooseSensor(hass: HomeAssistant, entityId: string): boolean { + const state = hass.states[entityId]; + if (kindOf(entityId) !== "sensor" || !state?.attributes.unit_of_measurement || isHiddenOrConfig(hass, entityId)) return false; + if (DIAGNOSTIC_CLASSES.has(String(state.attributes.device_class ?? ""))) return false; + return Number.isFinite(Number(state.state)) || isUnavailable(state); +} + +/** A power sensor: a `sensor.` with the device class power. */ +export const isPower = (hass: HomeAssistant, id: string): boolean => id.startsWith("sensor.") && hass.states[id]?.attributes.device_class === "power"; + +interface Index { + entities: HomeAssistant["entities"]; + devices: HomeAssistant["devices"]; + states: HomeAssistant["states"]; + stateCount: number; + byArea: Map; + powerByDevice: Map; + /** Placeable entities that have no area. */ + withoutArea: string[]; + /** Per device: the domains of its visible entities (tells a 3D printer from a thermometer). */ + domainsByDevice: Map>; + /** Devices whose entities sit in several areas, such as one bus device for a whole house. */ + hubs: Set; +} + +let cached: Index | null = null; +// a plugin can give a kind to entities of unknown domains: they are offered from then on +onPluginsChanged(() => (cached = null)); + +function bucket(map: Map, key: K): V[] { + let list = map.get(key); + if (!list) map.set(key, (list = [])); + return list; +} + +function build(hass: HomeAssistant): Index { + const byArea = new Map(); + const powerByDevice = new Map(); + const domainsByDevice = new Map>(); + const areasOfDevice = new Map>(); + const withoutArea: string[] = []; + const offerWithoutArea = (id: string) => { + if ((isRelevant(hass, id) || isLooseSensor(hass, id)) && isPlaceable(entityKind(hass, id))) withoutArea.push(id); + }; + + for (const [id, entry] of Object.entries(hass.entities ?? {})) { + const device = entry.device_id; + if (device && entry.area_id) (areasOfDevice.get(device) ?? areasOfDevice.set(device, new Set()).get(device)!).add(entry.area_id); + if (device && isPower(hass, id)) bucket(powerByDevice, device).push(id); + if (device && !entry.hidden && !entry.entity_category) (domainsByDevice.get(device) ?? domainsByDevice.set(device, new Set()).get(device)!).add(domainOf(id)); + const area = entityAreaId(hass, id); + if (area === null) offerWithoutArea(id); + else if (isRelevant(hass, id)) bucket(byArea, area).push(id); + } + // entities that are not in the registry (YAML without a unique_id, a USB camera) have no area either + if (hass.entities) for (const id of Object.keys(hass.states)) if (!hass.entities[id]) offerWithoutArea(id); + + // an entity a plugin takes on (an NVR's camera, a printer's status) comes before the plain sensors of its device, so it is + // the device's main entry + const pluginRank = KIND_ORDER.indexOf("binary") - 0.5; + const rank = (id: string) => { + const kind = kindOf(id); + const own = kind ? KIND_ORDER.indexOf(kind) : pluginRank; + return own > pluginRank && pluginKind(id, hass.states[id]) !== null ? pluginRank : own; + }; + withoutArea.sort((a, b) => rank(a) - rank(b) || entityName(hass, a).localeCompare(entityName(hass, b))); + for (const [areaId, ids] of byArea) { + const areaName = hass.areas?.[areaId]?.name; + ids.sort((a, b) => rank(a) - rank(b) || entityName(hass, a, areaName).localeCompare(entityName(hass, b, areaName))); + } + const hubs = new Set(); + for (const [device, areas] of areasOfDevice) if (areas.size > 1) hubs.add(device); + return { entities: hass.entities, devices: hass.devices, states: hass.states, stateCount: Object.keys(hass.states).length, byArea, powerByDevice, withoutArea, domainsByDevice, hubs }; +} + +/** + * The index for a registry. Home Assistant swaps `entities`, `devices` and `states` for new objects when they change, + * so object identity is the cache key. A different number of states (entities appearing after the registry) also + * triggers a rebuild. + */ +function indexOf(hass: HomeAssistant): Index { + const hit = cached; + if (hit && hit.entities === hass.entities && hit.devices === hass.devices) { + if (hit.states === hass.states) return hit; + hit.states = hass.states; + if (Object.keys(hass.states).length === hit.stateCount) return hit; + } + return (cached = build(hass)); +} + +/** The shown entities of an area, by kind and name. The array is shared: do not change it. */ +/** The entities of a room: those of its area and of the areas that are parts of it (a corner, a shelf with an area of its own). */ +export function roomEntities(hass: HomeAssistant, room: { area_id: string | null; sub_areas?: string[] | null }): string[] { + const own = areaEntities(hass, room.area_id); + if (!room.sub_areas?.length) return own; + return [...new Set([...own, ...room.sub_areas.flatMap((a) => areaEntities(hass, a))])]; +} + +export function areaEntities(hass: HomeAssistant, areaId: string | null): string[] { + if (!areaId || !hass.entities) return []; + return indexOf(hass).byArea.get(areaId) ?? []; +} + +/** Placeable entities of all areas but one, grouped by area name: for placing a device that lives elsewhere. */ +export function otherAreaEntities(hass: HomeAssistant, exceptArea: string | null): { areaId: string; name: string; ids: string[] }[] { + if (!hass.entities) return []; + const groups: { areaId: string; name: string; ids: string[] }[] = []; + for (const [areaId, all] of indexOf(hass).byArea) { + const ids = all.filter((id) => isPlaceable(entityKind(hass, id))); + if (areaId !== exceptArea && ids.length > 0) groups.push({ areaId, name: hass.areas?.[areaId]?.name ?? areaId, ids }); + } + return groups.sort((a, b) => a.name.localeCompare(b.name)); +} + +/** Placeable entities without an area (templates, groups, helpers, any numeric sensor with a unit). */ +export const unassignedEntities = (hass: HomeAssistant): string[] => (hass.entities ? indexOf(hass).withoutArea : []); + +/** Whether a device is a hub: its entities lie in several areas. */ +export const isHubDevice = (hass: HomeAssistant, deviceId: string): boolean => !!hass.entities && indexOf(hass).hubs.has(deviceId); + +/** The power sensors of a device. The array is shared: do not change it. */ +export const powerSensorsOf = (hass: HomeAssistant, deviceId: string): string[] => (hass.entities ? (indexOf(hass).powerByDevice.get(deviceId) ?? []) : []); + +// ---------------------------------------------------------------- one entity per device + +export interface DeviceGroup { + /** The device's main entity (the one without a name of its own), or the entity itself. */ + primary: string; + /** Other entities of the same device: indicators, effects, extra channels. */ + others: string[]; +} + +/** + * Groups entities by their device. Home Assistant's convention makes the device's main feature the entity without a + * name of its own; failing that, the first one. Groups come in the order of their main entities within `ids`. + */ +export function groupByDevice(hass: HomeAssistant, ids: readonly string[]): DeviceGroup[] { + const members = new Map(); + for (const id of ids) bucket(members, hass.entities?.[id]?.device_id ?? `entity:${id}`).push(id); + const position = new Map(ids.map((id, i) => [id, i])); + return [...members.values()] + .map((list) => { + const primary = list.find((id) => !hass.entities?.[id]?.name) ?? list[0]; + return { primary, others: list.filter((id) => id !== primary) }; + }) + .sort((a, b) => position.get(a.primary)! - position.get(b.primary)!); +} + +/** One entity per device: the main ones. */ +export const primaryEntities = (hass: HomeAssistant, ids: readonly string[]): string[] => groupByDevice(hass, ids).map((g) => g.primary); + +// ---------------------------------------------------------------- room climate + +/** Device classes of the three room values. */ +export const CLIMATE_CLASSES = { temperature: "temperature", humidity: "humidity", co2: "carbon_dioxide" } as const; +export type ClimateKey = keyof typeof CLIMATE_CLASSES; + +/** A device with one of these domains is not a room sensor: a heat pump, a printer, a TV. */ +const APPLIANCE_DOMAINS = new Set(["climate", "water_heater", "switch", "button", "camera", "media_player", "vacuum", "light", "fan", "lawn_mower"]); +/** Words in a name (English and German) that mark a temperature that is not the room's: pipes, printers, chips, outdoors, cold appliances. */ +const NOT_THE_ROOM_WORDS = [ + "vorlauf", "r(ü|ue)cklauf", "flow", "return", // heating pipes + "d(ü|ue)se", "nozzle", "hotend", "extruder", "druckbett", "heatbed", "(^|[^a-z])bed($|[^a-z])", "chamber", // 3D printers + "cpu", "gpu", "chip", "soc", "akku", "batter", // electronics + "wasser", "water", "kessel", "boiler", "au(ß|ss)en", "outdoor", "outside", // water, outdoors + "abgas", "exhaust", "sole", "brine", "verdampfer", "kondensat", "verdichter", "compressor", "motor", // heat pumps + "k(ü|ue)hl", "freezer", "fridge", "gefrier", // cold appliances +]; +const NOT_THE_ROOM = new RegExp(`(${NOT_THE_ROOM_WORDS.join("|")})`, "i"); + +/** Whether a sensor measures the room itself rather than the inside of some device. */ +export function isRoomClimateSensor(hass: HomeAssistant, entityId: string): boolean { + const device = hass.entities?.[entityId]?.device_id; + // a hub's entities are scattered over the house, so what else it offers says nothing about this sensor + const domains = device && !isHubDevice(hass, device) ? indexOf(hass).domainsByDevice.get(device) : undefined; + if (domains && [...domains].some((d) => APPLIANCE_DOMAINS.has(d))) return false; + return !NOT_THE_ROOM.test(`${entityId} ${hass.states[entityId]?.attributes.friendly_name ?? ""}`); +} + +/** + * The sensors a room's temperature, humidity or CO₂ is read from. An explicit choice wins ("none" means no sensor). + * Otherwise: the room sensors of the room's area plus those placed inside the room; a sensor of this area that is + * placed in another room counts there instead. + */ +export function roomClimateSensors(hass: HomeAssistant, floor: Floor | null, room: Room, key: ClimateKey): string[] { + const chosen = room.climate?.[key]; + if (chosen === "none") return []; + // one sensor, or several that are averaged + if (chosen) return [chosen].flat().filter((id) => hass.states[id]); + const placedSensors = (floor?.placements ?? []).filter((p) => p.entity_id.startsWith("sensor.")); + const inside = placedSensors.filter((p) => pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id); + const insideElsewhere = new Set(placedSensors.filter((p) => !pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id)); + const candidates = new Set([...roomEntities(hass, room).filter((id) => !insideElsewhere.has(id)), ...inside]); + return [...candidates].filter((id) => id.startsWith("sensor.") && hass.states[id]?.attributes.device_class === CLIMATE_CLASSES[key] && isRoomClimateSensor(hass, id)); +} + +/** The average of the room's sensors, or null when none reports. Temperatures are always °C, whatever the sensor's unit. */ +export function roomClimateValue(hass: HomeAssistant, floor: Floor | null, room: Room, key: ClimateKey): number | null { + const readings = roomClimateSensors(hass, floor, room, key) + .map((id) => { + const reading = Number(hass.states[id]?.state); + return key === "temperature" ? toCelsius(reading, hass.states[id]?.attributes.unit_of_measurement) : reading; + }) + .filter(Number.isFinite); + if (readings.length) return readings.reduce((sum, v) => sum + v, 0) / readings.length; + // no room sensor: a thermostat of the room's area tells its temperature and humidity (heating curves, the heat map) + if (key === "co2" || room.climate?.[key] === "none") return null; + const attr = key === "temperature" ? "current_temperature" : "current_humidity"; + const climates = roomEntities(hass, room) + .filter((id) => id.startsWith("climate.")) + .map((id) => hass.states[id]?.attributes[attr]) + .filter((v): v is number => typeof v === "number" && Number.isFinite(v)); + return climates.length ? climates.reduce((sum, v) => sum + v, 0) / climates.length : null; +} diff --git a/frontend/src/entities/visibility.test.ts b/frontend/src/entities/visibility.test.ts new file mode 100644 index 0000000..1be8f3e --- /dev/null +++ b/frontend/src/entities/visibility.test.ts @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, newFloor, type Furniture } from "../model.ts"; +import { entity, hassOf } from "./fixtures.ts"; +import { furnitureShown, hiddenFurniture, withoutHidden } from "./visibility.ts"; + +const piece = (id: string, show_when?: Furniture["show_when"]): Furniture => ({ id, type: "plant", x: 0, z: 0, rotation: 0, w: 1, d: 1, h: 1, variant: null, show_when }); + +test("a piece shows while its entity is on, or in the state asked for", () => { + const hass = hassOf([entity("input_boolean.xmas", "on"), entity("input_select.season", "Winter"), entity("switch.off", "off"), entity("sensor.gone", "unavailable")]); + assert.equal(furnitureShown(hass, piece("a")), true, "no condition: always"); + assert.equal(furnitureShown(hass, piece("a", { entity: "input_boolean.xmas" })), true); + assert.equal(furnitureShown(hass, piece("a", { entity: "switch.off" })), false); + assert.equal(furnitureShown(hass, piece("a", { entity: "switch.off", invert: true })), true, "shown while off"); + assert.equal(furnitureShown(hass, piece("a", { entity: "input_select.season", state: "summer, winter" })), true, "one of several states, any case"); + assert.equal(furnitureShown(hass, piece("a", { entity: "input_select.season", state: "summer" })), false); + assert.equal(furnitureShown(hass, piece("a", { entity: "sensor.gone" })), true, "an unavailable entity hides nothing"); + assert.equal(furnitureShown(hass, piece("a", { entity: "sensor.missing" })), true); +}); + +test("hidden pieces are left out of the building, which stays the same object without any", () => { + const b = emptyBuilding(); + const floor = newFloor("f", "F", 0); + floor.furniture = [piece("tree", { entity: "switch.off" }), piece("sofa")]; + b.floors = [floor]; + const hass = hassOf([entity("switch.off", "off")]); + const hidden = hiddenFurniture(hass, b); + assert.deepEqual(hidden, ["tree"]); + assert.deepEqual(withoutHidden(b, hidden).floors[0].furniture.map((f) => f.id), ["sofa"]); + assert.equal(withoutHidden(b, []), b); + assert.equal(b.floors[0].furniture.length, 2, "the plan itself keeps the piece"); +}); diff --git a/frontend/src/entities/visibility.ts b/frontend/src/entities/visibility.ts new file mode 100644 index 0000000..c6af391 --- /dev/null +++ b/frontend/src/entities/visibility.ts @@ -0,0 +1,44 @@ +// Visibility conditions: a piece of furniture that only shows while an entity is in a state (seasonal decoration +// behind an input_boolean, the Christmas tree in December, a tent while a calendar says "camping"). Pure functions; +// the 3D view leaves hidden pieces out of the scene. + +import type { Building, Furniture } from "../model.ts"; +import type { HomeAssistant } from "../types.ts"; +import { isUnavailable } from "./kinds.ts"; + +/** A visibility condition: the piece shows while `entity` is in `state` (null: while it is on), or the other way round. */ +export interface ShowWhen { + entity: string; + /** The state to match (several separated by commas, compared without case); null = "on", "home", "open" or "true". */ + state?: string | null; + /** Shown while the condition is NOT met. */ + invert?: boolean; +} + +const ON = new Set(["on", "home", "open", "true", "active", "playing", "heat", "heating"]); + +/** Whether a piece of furniture is shown now. Without a condition, or while its entity is missing or unavailable, it is shown. */ +export function furnitureShown(hass: HomeAssistant | undefined, f: Pick): boolean { + const cond = f.show_when; + if (!cond?.entity || !hass) return true; + const st = hass.states[cond.entity]; + if (!st || isUnavailable(st)) return true; + const state = String(st.state).toLowerCase(); + const want = (cond.state ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean); + const met = want.length ? want.includes(state) : ON.has(state) || (Number.isFinite(Number(state)) && Number(state) > 0); + return cond.invert ? !met : met; +} + +/** Ids of the pieces hidden by their condition right now, sorted (a key that only changes when one appears or goes). */ +export function hiddenFurniture(hass: HomeAssistant | undefined, b: Building): string[] { + const out: string[] = []; + for (const floor of b.floors) for (const f of floor.furniture) if (!furnitureShown(hass, f)) out.push(f.id); + return out.sort(); +} + +/** The building without the hidden pieces (the same object when nothing is hidden). */ +export function withoutHidden(b: Building, hidden: readonly string[]): Building { + if (!hidden.length) return b; + const set = new Set(hidden); + return { ...b, floors: b.floors.map((floor) => (floor.furniture.some((f) => set.has(f.id)) ? { ...floor, furniture: floor.furniture.filter((f) => !set.has(f.id)) } : floor)) }; +} diff --git a/frontend/src/features.test.ts b/frontend/src/features.test.ts new file mode 100644 index 0000000..2a30931 --- /dev/null +++ b/frontend/src/features.test.ts @@ -0,0 +1,7 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { REPO_URL } from "./features.ts"; + +test("the project link points to GitHub", () => { + assert.ok(REPO_URL.startsWith("https://github.com/")); +}); diff --git a/frontend/src/features.ts b/frontend/src/features.ts new file mode 100644 index 0000000..a80ee06 --- /dev/null +++ b/frontend/src/features.ts @@ -0,0 +1,2 @@ +/** The project's home: issues, discussions and the readme. */ +export const REPO_URL = "https://github.com/therealMRBK/NextFloor"; diff --git a/frontend/src/flags.ts b/frontend/src/flags.ts new file mode 100644 index 0000000..426f7c7 --- /dev/null +++ b/frontend/src/flags.ts @@ -0,0 +1,5 @@ +/** + * Features that exist in the code but are not shown yet (not tested enough for a release). Turning a + * flag on brings back its settings in the editor and the card editor and its display in 3D. + */ +export const SHOW_PRESENCE = true; diff --git a/frontend/src/furniture-colors.ts b/frontend/src/furniture-colors.ts new file mode 100644 index 0000000..56a41ae --- /dev/null +++ b/frontend/src/furniture-colors.ts @@ -0,0 +1,16 @@ +// The furniture roles whose colour can be chosen (#82), without three.js so the editor and the card editor can use it. + +export const FURNITURE_ROLES = ["body", "wood", "fabric", "white", "metal", "dark"] as const; +export type FurnitureRole = (typeof FURNITURE_ROLES)[number]; +/** A chosen colour ("#rrggbb") per role; a missing role keeps the stock colour. House-wide in the settings, per card on top. */ +export type FurnitureColors = Partial>; + +/** The stock colour of each role in the neon look, as the colour picker shows it before a colour is chosen. */ +export const STOCK_ROLE_HEX: Record = { + body: "#172238", + wood: "#19233c", + fabric: "#1a2644", + white: "#1d2946", + metal: "#2a3a60", + dark: "#0b111f", +}; diff --git a/frontend/src/furniture-names.ts b/frontend/src/furniture-names.ts new file mode 100644 index 0000000..28fed25 --- /dev/null +++ b/frontend/src/furniture-names.ts @@ -0,0 +1,31 @@ +// Display names of furniture types, built-in or from packs (kept out of packs.ts, which the 3D +// bundle uses without the UI strings). + +import { languageText, translate } from "./i18n.ts"; +import { isPackType, packItem, packItemName, packName, type PackItem } from "./packs.ts"; +import type { HomeAssistant } from "./types.ts"; + +/** Display name of any furniture type; furniture of a removed pack says so. */ +export function furnitureName(hass: HomeAssistant | undefined, type: string): string { + if (!isPackType(type)) return translate(hass, `furn_${type}` as Parameters[1]); + const item = packItem(type); + return item ? packItemLabel(item, type, hass?.language ?? navigator.language) : translate(hass, "pack_missing_item"); +} + +// The built-in packs carry German and English names; a fetched language file (lang/.json) names +// them in further languages under "packname:", the item's type and "color:". + +/** A pack item's name in the user's language; `type` is its furniture type (packType(pack, item)). */ +export function packItemLabel(item: PackItem, type: string, language: string): string { + return item.name[language.split("-")[0]] ?? languageText(language, type) ?? packItemName(item, language); +} + +/** A pack's name in the user's language. */ +export function packLabel(pack: { id: string; name: string }, language: string): string { + return languageText(language, `packname:${pack.id}`) ?? packName(pack, language); +} + +/** A paint colour's name in the user's language. */ +export function colourLabel(colour: { id: string; name: Record }, language: string): string { + return colour.name[language.split("-")[0]] ?? languageText(language, `color:${colour.id}`) ?? colour.name.en ?? Object.values(colour.name)[0]; +} diff --git a/frontend/src/geometry/arcs.test.ts b/frontend/src/geometry/arcs.test.ts new file mode 100644 index 0000000..4fcb4cc --- /dev/null +++ b/frontend/src/geometry/arcs.test.ts @@ -0,0 +1,25 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { arcPoints, pieceAt, polylineLength } from "./arcs.ts"; + +test("arc corners lie on one circle through both ends and reach the sagitta in the middle", () => { + const pts = arcPoints([0, 0], [4, 0], 1); + assert.ok(pts.length >= 3); + // bulging to the left of a→b (x right, z down): towards -z + assert.ok(pts.every((p) => p[1] < 0)); + const lowest = Math.min(...pts.map((p) => p[1])); + assert.ok(Math.abs(lowest + 1) < 0.05, `apex ${lowest}`); + // radius (c²/4 + s²) / 2s = 2.5, centre at (2, 1.5) + for (const [x, z] of pts) assert.ok(Math.abs(Math.hypot(x - 2, z - 1.5) - 2.5) < 1e-9); +}); + +test("a negative sagitta bulges the other way, nothing for a straight edge", () => { + assert.ok(arcPoints([0, 0], [4, 0], -1).every((p) => p[1] > 0)); + assert.deepEqual(arcPoints([0, 0], [4, 0], 0), []); +}); + +test("pieces of a polyline", () => { + const line: [number, number][] = [[0, 0], [1, 0], [1, 2]]; + assert.equal(polylineLength(line), 3); + assert.deepEqual(pieceAt(line, 1.5), { piece: 1, offset: 0.5 }); +}); diff --git a/frontend/src/geometry/arcs.ts b/frontend/src/geometry/arcs.ts new file mode 100644 index 0000000..7babad2 --- /dev/null +++ b/frontend/src/geometry/arcs.ts @@ -0,0 +1,44 @@ +// Wall arcs: a straight edge bent into a circular arc through `sagitta` (the arc's height over its chord), returned as the +// corners in between. Curved walls are stored as these short straight pieces, so every part of NextFloor that knows +// walls (3D, plan, openings, cut view, the solid walls) draws them without knowing about arcs. + +import type { Vec2 } from "../model.ts"; + +/** Longest piece of an arc in degrees of its turn: fine enough to look round, few enough corners to edit. */ +const PIECE_DEG = 11.25; + +/** The corners strictly between a and b on an arc bulging by `sagitta` to the left of a→b (negative: to the right). */ +export function arcPoints(a: Vec2, b: Vec2, sagitta: number, maxPieces = 24): Vec2[] { + const chord = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (chord < 1e-6 || Math.abs(sagitta) < 1e-4) return []; + const s = Math.max(-chord * 2, Math.min(chord * 2, sagitta)); + const u: Vec2 = [(b[0] - a[0]) / chord, (b[1] - a[1]) / chord]; + // left of a→b in plan coordinates (x right, z down the screen) + const n: Vec2 = [u[1], -u[0]]; + const radius = (chord * chord) / 4 / (2 * Math.abs(s)) + Math.abs(s) / 2; + const half = 2 * Math.atan((2 * Math.abs(s)) / chord); + const pieces = Math.max(2, Math.min(maxPieces, Math.ceil(((2 * half) / Math.PI) * 180 / PIECE_DEG))); + const apex: Vec2 = [n[0] * Math.sign(s), n[1] * Math.sign(s)]; + const mid: Vec2 = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; + const centre: Vec2 = [mid[0] - apex[0] * (radius - Math.abs(s)), mid[1] - apex[1] * (radius - Math.abs(s))]; + const out: Vec2[] = []; + for (let i = 1; i < pieces; i++) { + const phi = -half + (2 * half * i) / pieces; + out.push([centre[0] + radius * (apex[0] * Math.cos(phi) + u[0] * Math.sin(phi)), centre[1] + radius * (apex[1] * Math.cos(phi) + u[1] * Math.sin(phi))]); + } + return out; +} + +/** Length along a polyline. */ +export const polylineLength = (points: readonly Vec2[]): number => points.reduce((sum, p, i) => (i ? sum + Math.hypot(p[0] - points[i - 1][0], p[1] - points[i - 1][1]) : sum), 0); + +/** Which piece of a polyline holds the distance `s` along it, and how far into that piece it lies. */ +export function pieceAt(points: readonly Vec2[], s: number): { piece: number; offset: number } { + let rest = Math.max(0, s); + for (let i = 0; i + 1 < points.length; i++) { + const length = Math.hypot(points[i + 1][0] - points[i][0], points[i + 1][1] - points[i][1]); + if (rest <= length || i + 2 === points.length) return { piece: i, offset: Math.min(rest, length) }; + rest -= length; + } + return { piece: 0, offset: 0 }; +} diff --git a/frontend/src/geometry/gaps.test.ts b/frontend/src/geometry/gaps.test.ts new file mode 100644 index 0000000..c46fb17 --- /dev/null +++ b/frontend/src/geometry/gaps.test.ts @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { Room } from "../model.ts"; +import { closeGaps, suggestedThickness } from "./gaps.ts"; +import { generateWalls } from "./walls.ts"; + +const room = (id: string, x0: number, z0: number, x1: number, z1: number, clockwise = false): Room => { + const points: [number, number][] = [[x0, z0], [x1, z0], [x1, z1], [x0, z1]]; + return { id, name: id, area_id: null, points: clockwise ? points.reverse() : points, floor_material: "wood" }; +}; + +const box = (r: Room) => { + const xs = r.points.map((p) => p[0]); + const zs = r.points.map((p) => p[1]); + return { x0: Math.min(...xs), z0: Math.min(...zs), x1: Math.max(...xs), z1: Math.max(...zs) }; +}; + +test("rooms with a gap meet in the middle of it and share one interior wall", () => { + const { rooms, gaps } = closeGaps([room("a", 0, 0, 5, 3), room("b", 5.4, 0, 9, 3)]); + assert.deepEqual(gaps, [0.4]); + assert.equal(box(rooms[0]).x1, 5.2); + assert.equal(box(rooms[1]).x0, 5.2); + const { walls } = generateWalls(rooms, { exterior: 0.3, interior: 0.4 }); + assert.equal(walls.filter((w) => !w.exterior).length, 1); + assert.equal(suggestedThickness(gaps), 0.4); +}); + +test("the winding of a room does not matter", () => { + const { rooms, gaps } = closeGaps([room("a", 0, 0, 5, 3, true), room("b", 5.4, 0, 9, 3)]); + assert.deepEqual(gaps, [0.4]); + assert.equal(box(rooms[0]).x1, box(rooms[1]).x0); +}); + +test("rooms along one wall all meet on the same line, even with different gaps", () => { + const { rooms } = closeGaps([room("top", 0, 0, 8, 3), room("left", 0, 3.3, 4, 8), room("right", 4, 3.5, 8, 8)]); + const line = box(rooms[0]).z1; + assert.equal(box(rooms[1]).z0, line); + assert.equal(box(rooms[2]).z0, line); + assert.ok(line > 3 && line < 3.5); +}); + +test("a small overlap is pulled apart onto one line and suggests no thickness", () => { + const { rooms, gaps } = closeGaps([room("a", 0, 0, 4, 3), room("b", 3.92, 0, 8, 3)]); + assert.equal(box(rooms[0]).x1, box(rooms[1]).x0); + assert.ok(gaps[0] < 0); + assert.equal(suggestedThickness(gaps), null); +}); + +test("rooms that are too far apart, sit side by side without sharing a stretch of wall, or are alone stay as they were", () => { + assert.deepEqual(closeGaps([room("a", 0, 0, 4, 3), room("b", 6, 0, 9, 3)]).gaps, []); + assert.deepEqual(closeGaps([room("a", 0, 0, 4, 3), room("b", 4.3, 3.3, 8, 6)]).gaps, [], "only a corner in common"); + const alone = closeGaps([room("a", 0, 0, 4, 3)]); + assert.deepEqual(alone.gaps, []); + assert.deepEqual(alone.rooms[0].points, room("a", 0, 0, 4, 3).points); +}); + +test("the input rooms are never changed", () => { + const input = [room("a", 0, 0, 4, 3), room("b", 4.3, 0, 8, 3)]; + const before = JSON.stringify(input); + closeGaps(input); + assert.equal(JSON.stringify(input), before); +}); + +test("a larger maximum gap closes wider gaps", () => { + const rooms = [room("a", 0, 0, 4, 3), room("b", 5, 0, 8, 3)]; + assert.deepEqual(closeGaps(rooms).gaps, []); + assert.deepEqual(closeGaps(rooms, 1.2).gaps, [1]); +}); + +test("the suggested thickness is the median gap, clamped between 8 and 50 cm", () => { + assert.equal(suggestedThickness([0.1, 0.12, 0.3]), 0.12); + assert.equal(suggestedThickness([0.05, 0.05]), 0.08 > 0.05 ? 0.08 : 0.05); + assert.equal(suggestedThickness([0.9, 1.2]), 0.5); + assert.equal(suggestedThickness([]), null); + assert.equal(suggestedThickness([-0.05, 0.02]), null); +}); + +test("a straight wall split into several edges stays straight when only a part of it faces a neighbour", () => { + // room "a" has a vertex in the middle of its right wall; "b" faces only the upper half, "c" the lower half with another gap + const a: Room = { id: "a", name: "a", area_id: null, floor_material: "wood", points: [[0, 0], [5, 0], [5, 3], [5, 6], [0, 6]] }; + const { rooms } = closeGaps([a, room("b", 5.4, 0, 9, 3), room("c", 5.2, 3, 9, 6)]); + const xs = rooms[0].points.filter((p) => p[0] > 1).map((p) => p[0]); + assert.equal(new Set(xs).size, 1, "no corner appears inside the wall"); + assert.equal(rooms[0].points.length, 5); +}); + +test("an unpaired part of a split wall follows the paired part", () => { + const a: Room = { id: "a", name: "a", area_id: null, floor_material: "wood", points: [[0, 0], [5, 0], [5, 3], [5, 6], [0, 6]] }; + const { rooms } = closeGaps([a, room("b", 5.4, 0, 9, 3)]); + const xs = rooms[0].points.filter((p) => p[0] > 1).map((p) => p[0]); + assert.deepEqual(xs, [5.2, 5.2, 5.2]); +}); + +test("a wall that changes its thickness keeps its step: one room's two walls are never pulled onto one line (#65)", () => { + // the bedroom's right wall faces the kitchen's left wall, which steps back by 30 cm halfway (a thicker wall there) + const bedroom = room("bed", 0, 7.65, 3.81, 10.81); + const kitchen: Room = { id: "k", name: "k", area_id: null, floor_material: "wood", points: [[4.28, 8.76], [4.28, 7.68], [6.47, 7.68], [6.47, 10.98], [3.98, 10.98], [3.98, 8.76]] }; + const { rooms } = closeGaps([bedroom, kitchen]); + const xs = new Set(rooms[1].points.map((p) => p[0]).filter((x) => x < 5)); + assert.equal(xs.size, 2, "the kitchen keeps its step"); + assert.ok(xs.has(4.28), "the thick part is left as it is"); + assert.equal(box(rooms[0]).x1, 3.895, "the bedroom meets the near part of the kitchen wall in the middle"); + assert.ok(rooms[1].points.some((p) => p[0] === 3.895)); +}); diff --git a/frontend/src/geometry/gaps.ts b/frontend/src/geometry/gaps.ts new file mode 100644 index 0000000..0dca63c --- /dev/null +++ b/frontend/src/geometry/gaps.ts @@ -0,0 +1,154 @@ +// "Close gaps": rooms drawn with a gap between them (for example from inside measurements) get their facing edges moved +// onto one common centre line, so a single interior wall replaces two exterior walls. The gaps that were closed also +// suggest the thickness of interior walls. + +import { signedArea, type Room, type Vec2 } from "../model.ts"; +import { cross, dot, norm, sub } from "./vec2.ts"; + +export interface GapResult { + rooms: Room[]; + /** The width of every closed gap (negative for small overlaps). */ + gaps: number[]; +} + +/** An edge of a room, put in a canonical orientation so edges of different rooms can be compared. */ +interface Side { + room: number; + index: number; + /** The direction, with a canonical sign (angle in [0, π)). */ + dir: Vec2; + /** The normal belonging to that direction. */ + normal: Vec2; + /** Where the edge's line is along the normal. */ + offset: number; + /** +1 when the room's outside lies on the normal's side, -1 otherwise. */ + outside: 1 | -1; + /** The covered range along the direction. */ + from: number; + to: number; +} + +const PARALLEL_TOLERANCE = 0.05; +const MIN_SHARED_LENGTH = 0.2; +/** Rooms that overlap by up to this much are moved apart onto one line as well. */ +const MAX_OVERLAP = 0.12; + +function sidesOf(rooms: readonly Room[]): Side[] { + const sides: Side[] = []; + rooms.forEach((room, r) => { + const pts = room.points; + if (pts.length < 3) return; + const counterClockwise = signedArea(pts) >= 0; + pts.forEach((a, i) => { + const b = pts[(i + 1) % pts.length]; + const length = norm(sub(b, a)); + if (length < 0.05) return; + let dir: Vec2 = [(b[0] - a[0]) / length, (b[1] - a[1]) / length]; + // counter-clockwise in x/z: the outside is on the right of a to b + const outward: Vec2 = counterClockwise ? [dir[1], -dir[0]] : [-dir[1], dir[0]]; + if (dir[1] < -1e-9 || (Math.abs(dir[1]) <= 1e-9 && dir[0] < 0)) dir = [-dir[0], -dir[1]]; + const normal: Vec2 = [-dir[1], dir[0]]; + const [ta, tb] = [dot(a, dir), dot(b, dir)]; + sides.push({ room: r, index: i, dir, normal, offset: dot(a, normal), outside: dot(outward, normal) > 0 ? 1 : -1, from: Math.min(ta, tb), to: Math.max(ta, tb) }); + }); + }); + return sides; +} + +/** The gap between two sides that face each other across it, or null when they do not form one. */ +function gapBetween(e: Side, f: Side, maxGap: number): number | null { + if (e.room === f.room) return null; + if (Math.abs(cross(e.dir, f.dir)) > PARALLEL_TOLERANCE) return null; + if (e.outside === f.outside) return null; // facing each other means their outsides point at each other + const gap = (f.offset - e.offset) * e.outside; + if (gap > maxGap || gap < -MAX_OVERLAP || Math.abs(gap) < 1e-4) return null; + return Math.min(e.to, f.to) - Math.max(e.from, f.from) < MIN_SHARED_LENGTH ? null : gap; +} + +const thousandths = (v: number) => Math.round(v * 1000) / 1000; + +export function closeGaps(rooms: readonly Room[], maxGap = 0.6): GapResult { + const sides = sidesOf(rooms); + const leader = sides.map((_, i) => i); + const root = (i: number): number => (leader[i] === i ? i : (leader[i] = root(leader[i]))); + const gaps: number[] = []; + const paired = new Set(); + const candidates: [number, number, number][] = []; + for (let i = 0; i < sides.length; i++) { + for (let j = i + 1; j < sides.length; j++) { + const gap = gapBetween(sides[i], sides[j], maxGap); + if (gap !== null) candidates.push([i, j, gap]); + } + } + // narrowest gaps first; a pair that would pull two different walls of one room onto the same line is left out, so a + // wall that changes its thickness keeps its step instead of being flattened to one line (#65) + candidates.sort((a, b) => Math.abs(a[2]) - Math.abs(b[2])); + const members = new Map(sides.map((_, i) => [i, [i]])); + const clash = (a: number[], b: number[]) => a.some((x) => b.some((y) => sides[x].room === sides[y].room && Math.abs(sides[x].offset - sides[y].offset) >= 2e-3)); + for (const [i, j, gap] of candidates) { + const [ri, rj] = [root(i), root(j)]; + if (ri !== rj) { + if (clash(members.get(ri)!, members.get(rj)!)) continue; + leader[ri] = rj; + members.set(rj, [...members.get(rj)!, ...members.get(ri)!]); + members.delete(ri); + } + gaps.push(thousandths(gap)); + paired.add(i).add(j); + } + // a straight wall drawn as several collinear edges moves as one, otherwise a corner would appear inside it + const at = new Map(sides.map((s, i) => [`${s.room}:${s.index}`, i])); + for (let changed = paired.size > 0; changed; ) { + changed = false; + sides.forEach((s, i) => { + const next = at.get(`${s.room}:${(s.index + 1) % rooms[s.room].points.length}`); + if (next === undefined || next === i) return; + const n = sides[next]; + const collinear = Math.abs(cross(s.dir, n.dir)) < 1e-6 && Math.abs(s.offset - n.offset) < 2e-3 && s.outside === n.outside; + if (!collinear || paired.has(i) === paired.has(next)) return; + paired.add(i).add(next); + changed = true; + }); + } + // a paired run joins the group of its neighbour (checked again below, after the groups are known) + sides.forEach((s, i) => { + const next = at.get(`${s.room}:${(s.index + 1) % rooms[s.room].points.length}`); + if (next === undefined || next === i || !paired.has(i) || !paired.has(next)) return; + const n = sides[next]; + if (Math.abs(cross(s.dir, n.dir)) < 1e-6 && Math.abs(s.offset - n.offset) < 2e-3 && s.outside === n.outside) leader[root(i)] = root(next); + }); + const copy = () => rooms.map((r) => ({ ...r, points: r.points.map((p) => [p[0], p[1]] as Vec2) })); + if (gaps.length === 0) return { rooms: copy(), gaps }; + + // every group of facing sides meets on the mean of its lines + const groups = new Map(); + for (const i of paired) groups.set(root(i), [...(groups.get(root(i)) ?? []), i]); + // at most one shift per group and vertex, so collinear neighbours do not move a corner twice + const shifts = rooms.map((r) => r.points.map(() => new Map())); + for (const [group, members] of groups) { + // a wall counts once, however many collinear edges it consists of + const walls = new Map(members.map((i) => [`${sides[i].room}:${Math.round(sides[i].offset * 500)}`, sides[i].offset])); + const target = [...walls.values()].reduce((sum, o) => sum + o, 0) / walls.size; + for (const i of members) { + const s = sides[i]; + const move: Vec2 = [s.normal[0] * (target - s.offset), s.normal[1] * (target - s.offset)]; + shifts[s.room][s.index].set(group, move); + shifts[s.room][(s.index + 1) % rooms[s.room].points.length].set(group, move); + } + } + const moved = rooms.map((room, r) => ({ + ...room, + points: room.points.map((p, k): Vec2 => { + const total = [...shifts[r][k].values()].reduce((sum, d) => [sum[0] + d[0], sum[1] + d[1]], [p[0], p[1]]); + return [thousandths(total[0]), thousandths(total[1])]; + }), + })); + return { rooms: moved, gaps }; +} + +/** The interior wall thickness the closed gaps suggest (their median), or null when there were overlaps only. */ +export function suggestedThickness(gaps: readonly number[]): number | null { + const widths = gaps.filter((g) => g > 0.04).sort((a, b) => a - b); + if (widths.length === 0) return null; + return Math.min(0.5, Math.max(0.08, Math.round(widths[Math.floor(widths.length / 2)] * 100) / 100)); +} diff --git a/frontend/src/geometry/glass-front.test.ts b/frontend/src/geometry/glass-front.test.ts new file mode 100644 index 0000000..1506f1f --- /dev/null +++ b/frontend/src/geometry/glass-front.test.ts @@ -0,0 +1,180 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { Opening, Room, Vec2 } from "../model.ts"; +import { arcOfNearest, edgeStart, frontExtent, frontPieces, spansEdges, withFront } from "./glass-front.ts"; + +/** A wall of `n` edges of `seg` metres, each turning `turn` degrees the same way, closed by one back edge. */ +function arcRoom(n = 10, seg = 1, turn = 10): Room { + const points: Vec2[] = [[0, 0]]; + let [x, z] = [0, 0]; + let a = 0; + for (let i = 0; i < n; i++) { + a += (turn * Math.PI) / 180; + x += Math.cos(a) * seg; + z += Math.sin(a) * seg; + points.push([x, z]); + } + return { id: "r", name: "r", area_id: null, points, floor_material: "wood" }; +} + +const near = (a: number, b: number, eps = 1e-6) => Math.abs(a - b) < eps; + +test("a 6 m pane on a wall of ten 1 m edges is six pieces of one edge each", () => { + const room = arcRoom(); + const pieces = frontPieces(room, 0, 6); + assert.ok(pieces); + assert.deepEqual( + pieces.map((p) => p.edge), + [0, 1, 2, 3, 4, 5], + ); + for (const p of pieces) { + assert.ok(near(p.width, 1), `piece width ${p.width}`); + assert.ok(near(p.offset, 0.5), `piece centre ${p.offset}`); + } + assert.ok(near(pieces.reduce((sum, p) => sum + p.width, 0), 6), "the pieces keep the pane's length"); +}); + +test("a pane that starts in the middle of an edge takes what is left of it", () => { + const pieces = frontPieces(arcRoom(), 0.25, 2.5); + assert.ok(pieces); + assert.deepEqual( + pieces.map((p) => p.edge), + [0, 1, 2], + ); + assert.ok(near(pieces[0].width, 0.75), `first piece ${pieces[0].width}`); + assert.ok(near(pieces[1].width, 1)); + assert.ok(near(pieces[2].width, 0.75), `last piece ${pieces[2].width}`); + assert.ok(near(pieces[0].offset, 0.625), `first centre ${pieces[0].offset}`); +}); + +/** A round room: `n` edges of 1 m, each turning 360/n degrees, so the outline closes without a corner. */ +function roundRoom(n = 36, seg = 1): Room { + const radius = seg / (2 * Math.sin(Math.PI / n)); + const points: Vec2[] = []; + for (let i = 0; i < n; i++) { + const a = (2 * Math.PI * i) / n; + points.push([Math.cos(a) * radius, Math.sin(a) * radius]); + } + return { id: "r", name: "r", area_id: null, points, floor_material: "wood" }; +} + +test("a pane runs on past the last edge to the first one", () => { + const room = roundRoom(); + const pieces = frontPieces(room, 34.5, 2.5); + assert.ok(pieces); + assert.deepEqual( + pieces.map((p) => p.edge), + [34, 35, 0], + ); + assert.ok(near(pieces[0].width, 0.5, 0.02), `first piece ${pieces[0].width}`); + assert.ok(near(pieces[2].width, 1, 0.02), `last piece ${pieces[2].width}`); +}); + +test("a pane stops at a sharp corner instead of bending around it", () => { + // an L-shaped room: 4 m to the right, then 4 m up; the pane would have to turn 90 degrees + const room: Room = { id: "r", name: "r", area_id: null, points: [[0, 0], [4, 0], [4, 4], [0, 4]], floor_material: "wood" }; + const pieces = frontPieces(room, 1, 5); + assert.ok(pieces); + assert.deepEqual( + pieces.map((p) => p.edge), + [0], + "it stays on the first edge", + ); + assert.ok(near(pieces[0].width, 3), `clipped to the corner, got ${pieces[0].width}`); +}); + +test("a sliver of a few centimetres is dropped instead of drawn as frame", () => { + const pieces = frontPieces(arcRoom(), 0, 3.02); + assert.ok(pieces); + assert.equal(pieces.length, 3, "the 2 cm rest is not a piece of its own"); + assert.ok(near(pieces.reduce((sum, p) => sum + p.width, 0), 3)); +}); + +test("a stored front reads back as the arc it covers", () => { + const room = arcRoom(); + const pieces = frontPieces(room, 1.4, 4.2); + assert.ok(pieces); + const stored = pieces.map((p) => ({ edge: p.edge, offset: p.offset, width: p.width }) as never); + const extent = frontExtent(room, stored); + assert.ok(extent); + assert.ok(near(extent.from, 1.4), `from ${extent.from}`); + assert.ok(near(extent.width, 4.2), `width ${extent.width}`); +}); + +test("the arc of the nearest outline point finds the wall a pointer is on", () => { + const room = arcRoom(); + // a metre along the first edge, a little to the side of it + const start = room.points[0]; + const end = room.points[1]; + const at: Vec2 = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2]; + assert.ok(near(arcOfNearest(room, at), 0.5, 1e-6), `got ${arcOfNearest(room, at)}`); + assert.ok(near(edgeStart(room, 3), 3), `edge start ${edgeStart(room, 3)}`); +}); + +test("a pane wider than its own edge is a front, a little wider still fits", () => { + const room = arcRoom(); + assert.equal(spansEdges(room, 0, 1.05), false); + assert.equal(spansEdges(room, 0, 2.0), true); +}); + +const pane = (edge: number, offset: number, width: number, extra: Partial = {}): Opening => + ({ + id: `o${edge}`, + room_id: "r", + edge, + offset, + width, + type: "window", + sill: 0, + height: 2.4, + style: "glass_wall", + hinge: "left", + leaves: 1, + swing: "in", + cover: null, + contact: null, + contact2: null, + tilt: null, + ...extra, + }) as Opening; + +test("one ordinary opening grows into a pane over several edges and keeps its id", () => { + const room = arcRoom(); + const single = pane(0, 0.5, 1); + const list = [single]; + const next = withFront(list, room, single, 0.2, 3.5, () => "new"); + assert.ok(next); + assert.equal(next.length, 4, "0.8 of the first edge, one each on the next two, 0.7 on the fourth"); + assert.equal(next[0].id, single.id, "the piece the user had selected keeps its id"); + assert.ok(next.every((o) => o.front === next[0].front)); + assert.ok(next[0].front, "pieces of several edges share a front id"); + // in the list where the old one stood + assert.equal(next[0].edge, 0); + assert.deepEqual( + next.map((o) => o.edge), + [0, 1, 2, 3], + ); +}); + +test("a pane that fits one edge again loses its front id", () => { + const room = arcRoom(); + const pieces = frontPieces(room, 0, 3)!; + const list = pieces.map((p, k) => pane(p.edge, p.offset, p.width, { id: `p${k}`, front: "f" })); + const next = withFront(list, room, list[1], 0.4, 0.6, () => "new"); + assert.ok(next); + assert.equal(next.length, 1); + assert.equal(next[0].front, null); +}); + +test("re-spreading a pane leaves the other openings where they were", () => { + const room = arcRoom(); + const pieces = frontPieces(room, 0, 2)!; + const front = pieces.map((p, k) => pane(p.edge, p.offset, p.width, { id: `p${k}`, front: "f" })); + const door = pane(5, 0.5, 0.9, { id: "door", type: "door", style: null }); + const list = [...front, door]; + const next = withFront(list, room, front[0], 0, 4, () => "new"); + assert.ok(next); + assert.equal(next.filter((o) => o.id === "door").length, 1, "the door is still there"); + assert.equal(next.length, 5); + assert.ok(near(next.reduce((sum, o) => sum + (o.front ? o.width : 0), 0), 4)); +}); diff --git a/frontend/src/geometry/glass-front.ts b/frontend/src/geometry/glass-front.ts new file mode 100644 index 0000000..6c957a4 --- /dev/null +++ b/frontend/src/geometry/glass-front.ts @@ -0,0 +1,186 @@ +// A glass wall that follows a curved wall. NextFloor stores a curved wall as a chain of short straight +// room edges, and an opening is a straight piece of one edge. A full-width pane therefore becomes one +// opening per edge, all carrying the same `front` id. The 3D view draws them as one pane, without a +// jamb where two of them meet. Each piece is an ordinary opening on its own edge with a legal offset +// and width, so every part of NextFloor that reads openings keeps working without knowing about arcs. + +import { uid, type Opening, type Room, type Vec2 } from "../model.ts"; + +/** Edges that meet at a sharper angle are a corner, not a curve: a front stops there. */ +const MAX_BEND = (30 * Math.PI) / 180; + +/** The shortest piece worth keeping; anything shorter would only show as a sliver of frame. */ +export const MIN_PIECE = 0.05; + +/** Length of every edge of the room outline. */ +export function edgeLengths(room: Room): number[] { + const n = room.points.length; + return room.points.map((a, i) => { + const b = room.points[(i + 1) % n]; + return Math.hypot(b[0] - a[0], b[1] - a[1]); + }); +} + +/** Length of the whole room outline. */ +export function outlineLength(room: Room): number { + return edgeLengths(room).reduce((sum, l) => sum + l, 0); +} + +/** Arc length from points[0] to points[edge], once around the outline. */ +export function edgeStart(room: Room, edge: number): number { + const lengths = edgeLengths(room); + let at = 0; + for (let i = 0; i < edge && i < lengths.length; i++) at += lengths[i]; + return at; +} + +/** The angle the outline turns through from edge `i` to the next one. */ +function bend(room: Room, i: number): number { + const n = room.points.length; + const [a, b, c] = [room.points[i], room.points[(i + 1) % n], room.points[(i + 2) % n]]; + const u: Vec2 = [b[0] - a[0], b[1] - a[1]]; + const v: Vec2 = [c[0] - b[0], c[1] - b[1]]; + const [lu, lv] = [Math.hypot(u[0], u[1]), Math.hypot(v[0], v[1])]; + if (lu < 1e-9 || lv < 1e-9) return 0; + return Math.acos(Math.max(-1, Math.min(1, (u[0] * v[0] + u[1] * v[1]) / (lu * lv)))); +} + +/** One straight piece of a front, as a normal opening on its own edge. */ +export interface FrontPiece { + edge: number; + /** Centre of the piece from points[edge], and its length. */ + offset: number; + width: number; +} + +/** + * The pieces an arc from `from` (arc length from points[0]) of `width` covers, one per edge it runs + * along, in order. Null when the arc is empty. A front stops at a sharp corner instead of bending + * around it, and a sliver at either end is dropped rather than shown as a few centimetres of frame. + */ +export function frontPieces(room: Room, from: number, width: number): FrontPiece[] | null { + const lengths = edgeLengths(room); + const n = lengths.length; + const total = lengths.reduce((sum, l) => sum + l, 0); + if (n < 3 || !(total > 0) || !(width > 0)) return null; + const wanted = Math.min(width, total); + const start = ((from % total) + total) % total; + // the edge the front starts on + let edge = 0; + let at = 0; + while (edge < n - 1 && start >= at + lengths[edge]) { + at += lengths[edge]; + edge++; + } + let local = start - at; + let left = wanted; + const runs: { edge: number; t0: number; t1: number }[] = []; + for (let guard = 0; guard <= n && left > 1e-9; guard++) { + const span = lengths[edge] - local; + const take = Math.min(left, span); + if (take > 1e-9) runs.push({ edge, t0: local, t1: local + take }); + left -= take; + local = 0; + const next = (edge + 1) % n; + if (left > 1e-9 && bend(room, edge) > MAX_BEND) break; + edge = next; + } + // a few millimetres at either end would only show as a sliver of frame + while (runs.length > 1 && runs[0].t1 - runs[0].t0 < MIN_PIECE) runs.shift(); + while (runs.length > 1 && runs[runs.length - 1].t1 - runs[runs.length - 1].t0 < MIN_PIECE) runs.pop(); + if (!runs.length) return null; + return runs.map((run) => ({ edge: run.edge, offset: (run.t0 + run.t1) / 2, width: run.t1 - run.t0 })); +} + +/** + * The arc a stored front covers, read back from its pieces: where it starts, in arc length from + * points[0], and how long it is. Pieces carry their centre, so the first one gives the start. + */ +export function frontExtent(room: Room, pieces: readonly Opening[]): { from: number; width: number } | null { + const first = pieces[0]; + if (!first) return null; + return { + from: edgeStart(room, first.edge) + first.offset - first.width / 2, + width: pieces.reduce((sum, o) => sum + o.width, 0), + }; +} + +/** The pieces of the front an opening belongs to, in order along the wall (just itself for a plain one). */ +export function frontOf(openings: readonly Opening[], o: Opening): Opening[] { + if (!o.front) return [o]; + return openings.filter((x) => x.front === o.front); +} + +/** Arc length from points[0] of the outline point nearest `world`; used to drag a front along a wall. */ +export function arcOfNearest(room: Room, world: Vec2): number { + const n = room.points.length; + let best = Infinity; + let found = 0; + let at = 0; + for (let i = 0; i < n; i++) { + const a = room.points[i]; + const b = room.points[(i + 1) % n]; + const dx = b[0] - a[0]; + const dz = b[1] - a[1]; + const len = Math.hypot(dx, dz); + if (len < 1e-6) continue; + const t = Math.max(0, Math.min(len, ((world[0] - a[0]) * dx + (world[1] - a[1]) * dz) / len)); + const d = Math.hypot(world[0] - (a[0] + (dx * t) / len), world[1] - (a[1] + (dz * t) / len)); + if (d < best) { + best = d; + found = at + t; + } + at += len; + } + return found; +} + +/** Where a front of `width` may start on the outline, so that it stays on it as a whole. */ +export function frontRange(room: Room, width: number): [number, number] { + const total = outlineLength(room); + const w = Math.min(width, total); + return [0, Math.max(0, total - w)]; +} + +/** Whether an opening is wide enough to leave its own edge and become a front of several pieces. */ +export function spansEdges(room: Room, edge: number, width: number): boolean { + const lengths = edgeLengths(room); + const own = lengths[edge] ?? 0; + // a pane a few centimetres wider than its edge still fits once placement clamps it + return width > own + 0.1; +} + +/** + * Replace the front that `o` belongs to with a pane of `width` starting at `from` (arc length from + * points[0]). Every piece keeps the other fields of `o` and the first one keeps its id, so the selection + * survives; the rest get ids from `id`. A pane that fits on one edge again loses its `front` id. + * Returns the new list, or null when the arc is empty. + */ +export function withFront(openings: readonly Opening[], room: Room, o: Opening, from: number, width: number, id: () => string = () => uid("opening")): Opening[] | null { + const pieces = frontPieces(room, from, width); + if (!pieces) return null; + const group = frontOf(openings, o); + const ids = new Set(group.map((x) => x.id)); + const frontId = pieces.length > 1 ? (group[0].front ?? `front-${group[0].id}`) : null; + const made = pieces.map((piece, k) => ({ + ...o, + id: k === 0 ? group[0].id : id(), + edge: piece.edge, + offset: piece.offset, + width: piece.width, + front: frontId, + })); + const out: Opening[] = []; + let placed = false; + for (const x of openings) { + if (!ids.has(x.id)) { + out.push(x); + continue; + } + if (!placed) { + out.push(...made); + placed = true; + } + } + return out; +} diff --git a/frontend/src/geometry/holes.test.ts b/frontend/src/geometry/holes.test.ts new file mode 100644 index 0000000..30b1089 --- /dev/null +++ b/frontend/src/geometry/holes.test.ts @@ -0,0 +1,73 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { Vec2 } from "../model.ts"; +import { holeInRoom, insetHole, mergeHoles } from "./holes.ts"; + +const box = (x0: number, z0: number, x1: number, z1: number): Vec2[] => [[x0, z0], [x1, z0], [x1, z1], [x0, z1]]; +const areaOf = (ring: Vec2[]) => Math.abs(ring.reduce((sum, p, i) => sum + p[0] * ring[(i + 1) % ring.length][1] - ring[(i + 1) % ring.length][0] * p[1], 0)) / 2; +const near = (a: number, b: number) => assert.ok(Math.abs(a - b) < 1e-6, `${a} vs ${b}`); + +test("openings that are apart stay as they are, and rings with fewer than three points are dropped", () => { + const holes = [box(0, 0, 1, 1), box(5, 5, 6, 7)]; + assert.deepEqual(mergeHoles(holes), holes); + assert.deepEqual(mergeHoles([[[0, 0], [1, 1]], box(0, 0, 1, 1)]), [box(0, 0, 1, 1)]); + assert.deepEqual(mergeHoles([]), []); +}); + +test("two openings that overlap become one L-shaped outline", () => { + const merged = mergeHoles([box(0, 0, 4, 1), box(3, 0, 4, 3)]); + assert.equal(merged.length, 1); + near(areaOf(merged[0]), 4 + 3 - 1); +}); + +test("openings that merely touch along an edge are merged too", () => { + const merged = mergeHoles([box(0, 0, 2, 2), box(2, 0, 4, 2)]); + assert.equal(merged.length, 1); + near(areaOf(merged[0]), 8); +}); + +test("a chain is merged when a middle opening links both ends", () => { + const merged = mergeHoles([box(0, 0, 2, 1), box(5, 0, 7, 1), box(1.5, 0.25, 5.5, 0.75)]); + assert.equal(merged.length, 1); + near(areaOf(merged[0]), 2 + 2 + 3 * 0.5); +}); + +test("an opening inside another one vanishes into it", () => { + const merged = mergeHoles([box(0, 0, 5, 5), box(1, 1, 2, 2)]); + assert.equal(merged.length, 1); + near(areaOf(merged[0]), 25); +}); + +test("the order and the winding of the rings do not matter", () => { + const clockwise = box(2, 0, 4, 3).reverse(); + const merged = mergeHoles([clockwise, box(0, 1, 3, 2)]); + assert.equal(merged.length, 1); + near(areaOf(merged[0]), 6 + 3 - 1); + const swapped = mergeHoles([box(0, 1, 3, 2), clockwise]); + near(areaOf(swapped[0]), areaOf(merged[0])); +}); + +test("two separate groups give two outlines", () => { + const merged = mergeHoles([box(0, 0, 2, 2), box(1, 1, 3, 3), box(10, 10, 12, 12), box(11, 11, 13, 13)]); + assert.equal(merged.length, 2); + assert.deepEqual(merged.map(areaOf).sort((a, b) => a - b).map((a) => Math.round(a)), [7, 7]); +}); + +test("an opening lies in a room when its corners are inside or on the edge, within a tolerance", () => { + const room = box(0, 0, 4, 4); + assert.equal(holeInRoom(box(1, 1, 2, 2), room), true); + assert.equal(holeInRoom(box(1, 2, 2, 4), room), true, "snapped to the wall"); + assert.equal(holeInRoom(box(1, 2, 2, 4.2), room), false); + assert.equal(holeInRoom(box(1, 2, 2, 4.02), room), true, "within the 3 cm tolerance"); + assert.equal(holeInRoom(box(1, 2, 2, 4.02), room, 0.01), false); + assert.equal(holeInRoom(box(8, 8, 9, 9), room), false); +}); + +test("an opening is moved inwards by d on every side, whichever way it is wound", () => { + for (const ring of [box(1, 2, 2, 4), box(1, 2, 2, 4).reverse()]) { + const inset = insetHole(ring, 0.1); + assert.ok(inset.every(([x, z]) => x > 1 && x < 2 && z > 2 && z < 4)); + near(areaOf(inset), 0.8 * 1.8); + } + assert.deepEqual(insetHole(box(0, 0, 1, 1), 0).map((p) => p.map((v) => Math.round(v * 1e6) / 1e6)), box(0, 0, 1, 1)); +}); diff --git a/frontend/src/geometry/holes.ts b/frontend/src/geometry/holes.ts new file mode 100644 index 0000000..e0593e4 --- /dev/null +++ b/frontend/src/geometry/holes.ts @@ -0,0 +1,144 @@ +// Floor openings (stairwells and the like) that overlap or touch are merged into one outline, so the floor can be cut +// around them: the triangulation needs holes that do not cross each other. + +import { pointInPolygon, type Vec2 } from "../model.ts"; +import { cross as cross2, dot as dot2, norm, sub } from "./vec2.ts"; + +const EPS = 1e-4; + +/** The shoelace area; positive for counter-clockwise rings. */ +function ringArea(ring: readonly Vec2[]): number { + return ring.reduce((sum, p, i) => sum + cross2(p, ring[(i + 1) % ring.length]), 0) / 2; +} + +const counterClockwise = (ring: readonly Vec2[]): Vec2[] => (ringArea(ring) >= 0 ? [...ring] : [...ring].reverse()); + +/** Where segment a-b is crossed by c-d (strictly inside a-b, not parallel): the parameter on a-b, else null. */ +function crossing(a: Vec2, b: Vec2, c: Vec2, d: Vec2): number | null { + const r = sub(b, a); + const s = sub(d, c); + const denominator = cross2(r, s); + if (Math.abs(denominator) < 1e-12) return null; + const t = cross2(sub(c, a), s) / denominator; + const u = cross2(sub(c, a), r) / denominator; + return t > EPS && t < 1 - EPS && u > -EPS && u < 1 + EPS ? t : null; +} + +/** Where a point lies on the inside of segment a-b: the parameter on it, else null. */ +function touching(p: Vec2, a: Vec2, b: Vec2): number | null { + const d = sub(b, a); + const squared = dot2(d, d); + if (squared < 1e-12) return null; + const t = dot2(sub(p, a), d) / squared; + if (t <= EPS || t >= 1 - EPS) return null; + return Math.abs(cross2(sub(p, a), d)) / Math.sqrt(squared) < EPS ? t : null; +} + +const closeTo = (p: Vec2, q: Vec2, eps = EPS) => norm(sub(p, q)) < eps; + +/** The edges of a ring as [start, end] pairs. */ +const edgesOf = (ring: readonly Vec2[]): [Vec2, Vec2][] => ring.map((p, i) => [p, ring[(i + 1) % ring.length]]); + +/** Whether two rings cross, touch or lie inside each other. */ +function overlap(first: readonly Vec2[], second: readonly Vec2[]): boolean { + for (const [a, b] of edgesOf(first)) { + for (const [c, d] of edgesOf(second)) { + if (crossing(a, b, c, d) !== null || touching(c, a, b) !== null || touching(a, c, d) !== null || closeTo(a, c)) return true; + } + } + return pointInPolygon(first[0], second) || pointInPolygon(second[0], first); +} + +/** The outline of the union of overlapping rings. Islands inside are left out. */ +function unionOutline(polygons: Vec2[][]): Vec2[][] { + const rings = polygons.map(counterClockwise); + const pieces: [Vec2, Vec2][] = []; + rings.forEach((ring, ringIndex) => { + for (const [a, b] of edgesOf(ring)) { + // cut the edge where other outlines cross or touch it + const cuts = [0, 1]; + rings.forEach((other, otherIndex) => { + if (otherIndex === ringIndex) return; + for (const [c, d] of edgesOf(other)) { + const t = crossing(a, b, c, d) ?? touching(c, a, b); + if (t !== null) cuts.push(t); + } + }); + cuts.sort((x, y) => x - y); + for (let k = 1; k < cuts.length; k++) { + if (cuts[k] - cuts[k - 1] < EPS) continue; + const p: Vec2 = [a[0] + (b[0] - a[0]) * cuts[k - 1], a[1] + (b[1] - a[1]) * cuts[k - 1]]; + const q: Vec2 = [a[0] + (b[0] - a[0]) * cuts[k], a[1] + (b[1] - a[1]) * cuts[k]]; + // the piece is on the outline when the spot just outside it (on its right) is inside no other ring + const length = norm(sub(q, p)); + const outside: Vec2 = [(p[0] + q[0]) / 2 + ((q[1] - p[1]) / length) * 1e-3, (p[1] + q[1]) / 2 - ((q[0] - p[0]) / length) * 1e-3]; + if (rings.some((other, otherIndex) => otherIndex !== ringIndex && pointInPolygon(outside, other))) continue; + if (pieces.some(([s, e]) => closeTo(s, p) && closeTo(e, q))) continue; + pieces.push([p, q]); + } + } + }); + // chain the pieces into closed rings + const outlines: Vec2[][] = []; + const used = new Set(); + pieces.forEach(([start, first], s) => { + if (used.has(s)) return; + used.add(s); + const ring: Vec2[] = [start]; + let end = first; + for (let guard = 0; guard < pieces.length && !closeTo(end, ring[0], 1e-3); guard++) { + const next = pieces.findIndex(([p], i) => !used.has(i) && closeTo(p, end, 1e-3)); + if (next < 0) break; + used.add(next); + ring.push(pieces[next][0]); + end = pieces[next][1]; + } + if (ring.length >= 3 && ringArea(ring) > 1e-6) outlines.push(ring); + }); + return outlines; +} + +/** Floor openings, with those that overlap or touch (directly or through others) merged into one outline each. */ +export function mergeHoles(holes: Vec2[][]): Vec2[][] { + const valid = holes.filter((h) => h.length >= 3); + // union-find over the openings + const leader = valid.map((_, i) => i); + const root = (i: number): number => (leader[i] === i ? i : (leader[i] = root(leader[i]))); + valid.forEach((first, i) => { + for (let j = i + 1; j < valid.length; j++) if (root(i) !== root(j) && overlap(first, valid[j])) leader[root(j)] = root(i); + }); + const groups = new Map(); + valid.forEach((hole, i) => groups.set(root(i), [...(groups.get(root(i)) ?? []), hole])); + return [...groups.values()].flatMap((group) => (group.length === 1 ? group : unionOutline(group))); +} + +function distanceToSegment(p: Vec2, a: Vec2, b: Vec2): number { + const d = sub(b, a); + const squared = dot2(d, d); + const t = squared ? Math.max(0, Math.min(1, dot2(sub(p, a), d) / squared)) : 0; + return norm(sub(p, [a[0] + d[0] * t, a[1] + d[1] * t])); +} + +/** Whether an opening lies in a room. Corners on the room's edge (snapped to a wall) count as inside. */ +export function holeInRoom(hole: readonly Vec2[], room: readonly Vec2[], tolerance = 0.03): boolean { + return hole.every((p) => pointInPolygon(p, room) || edgesOf(room).some(([a, b]) => distanceToSegment(p, a, b) <= tolerance)); +} + +/** An opening moved inwards by d on every side, so one on the room's edge stays a hole in the floor. */ +export function insetHole(hole: readonly Vec2[], d: number): Vec2[] { + const ring = counterClockwise(hole); + // the left side of a counter-clockwise edge is the inside + const inward = (a: Vec2, b: Vec2): Vec2 => { + const e = sub(b, a); + const length = norm(e) || 1; + return [-e[1] / length, e[0] / length]; + }; + return ring.map((p, i) => { + const before = inward(ring[(i - 1 + ring.length) % ring.length], p); + const after = inward(p, ring[(i + 1) % ring.length]); + const k = 1 + dot2(before, after); + if (k < 0.1) return p; + return [p[0] + ((before[0] + after[0]) / k) * d, p[1] + ((before[1] + after[1]) / k) * d] as Vec2; + }); +} + diff --git a/frontend/src/geometry/living-area.test.ts b/frontend/src/geometry/living-area.test.ts new file mode 100644 index 0000000..8a93044 --- /dev/null +++ b/frontend/src/geometry/living-area.test.ts @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, floorWith } from "../entities/fixtures.ts"; +import { emptyBuilding } from "../model.ts"; +import { printHtml } from "../components/editor/print.ts"; +import { floorAreas, roomArea, totalOf } from "./living-area.ts"; +import { generateWalls } from "./walls.ts"; + +const near = (a: number, b: number, eps = 0.25) => assert.ok(Math.abs(a - b) <= eps, `${a} ≈ ${b}`); + +test("a room counts its floor inside the walls, in full under a normal ceiling", () => { + const b = emptyBuilding(); + const floor = floorWith([box("a", 0, 0, 4, 3), box("b", 4, 0, 7, 3)], { height: 2.5 }); + b.floors = [floor]; + const walls = generateWalls(floor.rooms, { exterior: b.settings.wall_exterior, interior: b.settings.wall_interior }).walls; + const a = roomArea(b, floor, floor.rooms[0], walls); + // the outline runs along the inner faces of the outer walls and the middle of the shared wall + near(a.floor, 4 * 3 - (b.settings.wall_interior / 2) * 3); + assert.equal(a.living, a.floor); + assert.equal(a.low, 0); + near(totalOf(floorAreas(b, floor)).floor, 7 * 3 - b.settings.wall_interior * 3); +}); + +test("a low ceiling counts half between 1 and 2 m and nothing below", () => { + const b = emptyBuilding(); + const half = floorWith([{ ...box("a", 0, 0, 4, 3), ceiling: 1.5 }], { height: 2.5 }); + b.floors = [half]; + const [h] = floorAreas(b, half); + near(h.living, h.floor / 2, 0.01); + near(h.low, h.floor, 0.01); + const none = floorWith([{ ...box("a", 0, 0, 4, 3), ceiling: 0.9 }], { height: 2.5 }); + const [n] = floorAreas(b, none); + assert.equal(n.living, 0); +}); + +test("the plan on paper has a page per floor and the area table", () => { + const b = emptyBuilding(); + b.floors = [{ ...floorWith([box("a", 0, 0, 4, 3)]), name: "EG <1>" }]; + const html = printHtml(b, { title: "Plan", room: "Room", floorArea: "Floor", living: "Living", low: "Low", total: "Total", note: "note", area: (m) => `${m.toFixed(1)} m²`, length: (m) => `${m.toFixed(2)} m` }); + assert.ok(html.includes("): boolean => room.living ?? !NOT_LIVING.test(room.name); + +/** The grid the rooms are sampled on (m): 10 cm, fine enough for a few cm² per metre of wall. */ +const CELL = 0.1; + +const boxOf = (points: readonly [number, number][]) => ({ + x0: Math.min(...points.map((p) => p[0])), + x1: Math.max(...points.map((p) => p[0])), + z0: Math.min(...points.map((p) => p[1])), + z1: Math.max(...points.map((p) => p[1])), +}); + +/** The areas of one room: sampled on a grid, leaving out the walls, weighted by the clear height above each point. */ +export function roomArea(b: Building, floor: Floor, room: Room, walls: readonly Wall[], cell = CELL): RoomArea { + if (room.points.length < 3) return { roomId: room.id, floor: 0, living: 0, low: 0 }; + const box = boxOf(room.points); + const near = walls.filter((w) => { + const wb = boxOf(w.footprint); + return wb.x1 >= box.x0 && wb.x0 <= box.x1 && wb.z1 >= box.z0 && wb.z0 <= box.z1; + }); + const ceiling = floor.elevation + (room.ceiling != null && room.ceiling > 0 ? room.ceiling : floor.height); + const hasRoof = (b.settings.roof?.sections ?? []).some((s) => !s.open); + const level = roomOffset(room); + let full = 0; + let half = 0; + let under = 0; + for (let x = box.x0 + cell / 2; x < box.x1; x += cell) { + for (let z = box.z0 + cell / 2; z < box.z1; z += cell) { + if (!pointInPolygon([x, z], room.points) || near.some((w) => pointInPolygon([x, z], w.footprint))) continue; + const roof = hasRoof ? roofUnderAt(b, x, z) : null; + // a room on its own level: the clear height counts from its own floor + const clear = Math.min(ceiling, roof ?? Infinity) - floor.elevation - level; + if (clear >= 2) full++; + else if (clear >= 1) half++; + else under++; + } + } + const a = cell * cell; + return { roomId: room.id, floor: (full + half + under) * a, living: countsAsLiving(room) ? (full + half / 2) * a : 0, low: (half + under) * a }; +} + +/** Areas per floor object: the plan is copied on every change, so a floor object stands for one state of it. */ +const memo = new WeakMap(); + +/** The areas of every room of a floor (layers have none). */ +export function floorAreas(b: Building, floor: Floor): RoomArea[] { + if (floor.layer) return []; + const known = memo.get(floor); + if (known && known.roof === b.settings.roof) return known.areas; + const areas = computeFloorAreas(b, floor); + memo.set(floor, { roof: b.settings.roof, areas }); + return areas; +} + +function computeFloorAreas(b: Building, floor: Floor): RoomArea[] { + const walls = generateWalls(floor.rooms, { exterior: b.settings.wall_exterior, interior: b.settings.wall_interior }, floor.walls ?? []).walls; + return floor.rooms.map((r) => roomArea(b, floor, r, walls)); +} + +/** Sums of room areas. */ +export const totalOf = (areas: readonly RoomArea[]): Omit => areas.reduce((t, a) => ({ floor: t.floor + a.floor, living: t.living + a.living, low: t.low + a.low }), { floor: 0, living: 0, low: 0 }); diff --git a/frontend/src/geometry/snap.test.ts b/frontend/src/geometry/snap.test.ts new file mode 100644 index 0000000..e93ca09 --- /dev/null +++ b/frontend/src/geometry/snap.test.ts @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { newFloor, type Floor, type Furniture } from "../model.ts"; +import { keepInRoom, snapToWall, WALL_SNAP } from "./snap.ts"; + +const hall = (): Floor => ({ ...newFloor("f", "F", 0), rooms: [{ id: "r", name: "R", area_id: null, points: [[0, 0], [5, 0], [5, 4], [0, 4]], floor_material: "wood" }] }); +const piece = (x: number, z: number, rotation: number, extra: Partial = {}): Furniture => ({ id: "p", type: "sofa", x, z, rotation, w: 2, d: 1, h: 0.8, variant: null, entity: null, power: null, ...extra }); + +test("a piece close to a wall turns its back to it and sits flush", () => { + const snapped = snapToWall(hall(), piece(2.5, 0.7, 15), 0.1)!; + assert.deepEqual(snapped, { x: 2.5, z: 0.5, rotation: 0 }); +}); + +test("the back turns to whichever wall is near: right wall 90°, bottom wall 180°, left wall 270°", () => { + assert.equal(snapToWall(hall(), piece(4.3, 2, 80), 0.1)?.rotation, 90); + assert.equal(snapToWall(hall(), piece(2.5, 3.3, 170), 0.1)?.rotation, 180); + assert.equal(snapToWall(hall(), piece(0.7, 2, 260), 0.1)?.rotation, 270); +}); + +test("a piece standing sideways puts its side against the wall", () => { + const side = snapToWall(hall(), piece(1.2, 2, 0), 0.1)!; + assert.equal(side.rotation, 0); + assert.ok(Math.abs(side.x - 1) < 1e-9, "half its width from the left wall"); +}); + +test("a piece in the middle of the room, or turned away from every wall, stays put", () => { + assert.equal(snapToWall(hall(), piece(2.5, 2, 0), 0.1), null); + assert.equal(snapToWall(hall(), piece(2.5, 0.7, 135), 0.1), null, "more than 50° off every direction"); +}); + +test("a piece outside every room does not snap", () => { + assert.equal(snapToWall(hall(), piece(20, 20, 0), 0.1), null); +}); + +test("the reach limits how far a wall pulls", () => { + assert.ok(snapToWall(hall(), piece(2.5, 0.5 + WALL_SNAP - 0.01, 0), 0.1)); + assert.equal(snapToWall(hall(), piece(2.5, 0.5 + WALL_SNAP + 0.05, 0), 0.1), null); + assert.ok(snapToWall(hall(), piece(2.5, 0.5 + WALL_SNAP + 0.05, 0), 0.1, 0.5)); +}); + +test("against an interior wall the face is half the wall thickness inside the room", () => { + const floor = hall(); + floor.rooms = [ + { id: "r", name: "R", area_id: null, points: [[0, 0], [5, 0], [5, 4], [0, 4]], floor_material: "wood" }, + { id: "s", name: "S", area_id: null, points: [[5, 0], [9, 0], [9, 4], [5, 4]], floor_material: "wood" }, + ]; + const interior = snapToWall(floor, piece(4.3, 2, 90), 0.2)!; + const exterior = snapToWall({ ...floor, rooms: [floor.rooms[0]] }, piece(4.3, 2, 90), 0.2)!; + assert.ok(Math.abs(interior.x - (5 - 0.1 - 0.5)) < 1e-9); + assert.ok(Math.abs(exterior.x - (5 - 0.5)) < 1e-9); +}); + +test("a drag inside the room is free, through a wall it slides along it, through a corner it stops, outside rooms it is free", () => { + const floor = hall(); + assert.deepEqual(keepInRoom(floor, 2, 2, 3, 3), [3, 3]); + assert.deepEqual(keepInRoom(floor, 4.5, 2, 5.5, 3), [4.5, 3]); + assert.deepEqual(keepInRoom(floor, 2, 0.5, 3, -0.5), [3, 0.5]); + assert.deepEqual(keepInRoom(floor, 4.8, 3.8, 5.5, 4.5), [4.8, 3.8]); + assert.deepEqual(keepInRoom(floor, 9, 9, 10, 10), [10, 10]); +}); diff --git a/frontend/src/geometry/snap.ts b/frontend/src/geometry/snap.ts new file mode 100644 index 0000000..900c527 --- /dev/null +++ b/frontend/src/geometry/snap.ts @@ -0,0 +1,73 @@ +// Snapping furniture to the walls of its room: the back (or a side, when it stands sideways) turns to the nearest wall and +// the piece sits flush with the wall face. Shared by the 2D editor and by furnishing in 3D. + +import { pointInPolygon, signedArea, type Floor, type Furniture, type Room, type Vec2 } from "../model.ts"; +import { dot, norm, sub } from "./vec2.ts"; + +/** Furniture closer than this to a wall snaps against it (metres). */ +export const WALL_SNAP = 0.25; + +const thousandths = (v: number) => Math.round(v * 1000) / 1000; +const roomAt = (floor: Floor, x: number, z: number): Room | undefined => floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([x, z], r.points)); + +/** + * A point dragged from (x0, z0) to (x, z) stays in the room it started in. Outside that room's polygon the move slides + * along the wall (only x or only z changes), or stops. Things that start outside every room move freely. + */ +export function keepInRoom(floor: Floor, x0: number, z0: number, x: number, z: number): [number, number] { + const room = roomAt(floor, x0, z0); + if (!room) return [x, z]; + const inside = (px: number, pz: number) => pointInPolygon([px, pz], room.points); + if (inside(x, z)) return [x, z]; + if (inside(x, z0)) return [x, z0]; + if (inside(x0, z)) return [x0, z]; + return [x0, z0]; +} + +/** Whether another room has an edge lying on the line through `a` with this normal: then the wall between them is an interior wall. */ +function edgeIsShared(floor: Floor, room: Room, a: Vec2, normal: Vec2): boolean { + return floor.rooms.some( + (other) => + other.id !== room.id && + other.points.some((p, k) => { + const q = other.points[(k + 1) % other.points.length]; + return Math.abs(dot(sub(p, a), normal)) < 0.02 && Math.abs(dot(sub(q, a), normal)) < 0.02; + }), + ); +} + +const angleBetween = (a: number, b: number) => Math.abs(((a - b + 540) % 360) - 180); + +/** Where a piece of furniture would stand when snapped to the nearest wall of its room, or null when no wall is close enough. */ +export function snapToWall(floor: Floor, f: Furniture, wallInterior: number, reach = WALL_SNAP): { x: number; z: number; rotation: number } | null { + const room = roomAt(floor, f.x, f.z); + if (!room) return null; + const pts = room.points; + const winding = signedArea(pts) >= 0 ? 1 : -1; + let best: { x: number; z: number; rotation: number; gap: number } | null = null; + pts.forEach((a, i) => { + const b = pts[(i + 1) % pts.length]; + const length = norm(sub(b, a)); + if (length < 0.3) return; + const along: Vec2 = [(b[0] - a[0]) / length, (b[1] - a[1]) / length]; + const normal: Vec2 = [-along[1] * winding, along[0] * winding]; // into the room + const position = dot(sub([f.x, f.z], a), along); + if (position < 0 || position > length) return; + // interior walls stand on the room edge, so their face is half the wall thickness inside + const faceOffset = edgeIsShared(floor, room, a, normal) ? wallInterior / 2 : 0; + const distance = dot(sub([f.x, f.z], a), normal) - faceOffset; + // the rotation that turns the back to the wall (the front looks along the normal) + const back = (Math.atan2(-normal[0], normal[1]) * 180) / Math.PI; + const choices = [ + { rotation: back, extent: f.d / 2 }, + { rotation: back + 90, extent: f.w / 2 }, + { rotation: back - 90, extent: f.w / 2 }, + ]; + const choice = choices.reduce((p, q) => (angleBetween(f.rotation, q.rotation) < angleBetween(f.rotation, p.rotation) ? q : p)); + if (angleBetween(f.rotation, choice.rotation) > 50) return; + const gap = distance - choice.extent; + if (Math.abs(gap) > reach || (best && Math.abs(gap) >= Math.abs(best.gap))) return; + best = { x: thousandths(f.x - normal[0] * gap), z: thousandths(f.z - normal[1] * gap), rotation: ((Math.round(choice.rotation) % 360) + 360) % 360, gap }; + }); + return best && { x: (best as { x: number }).x, z: (best as { z: number }).z, rotation: (best as { rotation: number }).rotation }; +} diff --git a/frontend/src/geometry/stairs.test.ts b/frontend/src/geometry/stairs.test.ts new file mode 100644 index 0000000..9f8ca79 --- /dev/null +++ b/frontend/src/geometry/stairs.test.ts @@ -0,0 +1,117 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { DEFAULT_STAIR, STAIR_SHAPES, STAIR_SIZES, stairConfig, stairLayout, stairOpening, stairOpeningInPlan, type StairConfig } from "./stairs.ts"; + +const cfg = (patch: Partial = {}): StairConfig => ({ ...DEFAULT_STAIR, ...patch }); +const area = (ring: [number, number][]) => Math.abs(ring.reduce((s, p, i) => s + p[0] * ring[(i + 1) % ring.length][1] - ring[(i + 1) % ring.length][0] * p[1], 0) / 2); + +test("stairConfig fills in defaults and rejects nonsense", () => { + assert.deepEqual(stairConfig({}), DEFAULT_STAIR); + const c = stairConfig({ stair: { shape: "spiral", turn: "left", steps: 99, run_width: -1, rail: "both" } }); + assert.equal(c.shape, "spiral"); + assert.equal(c.turn, "left"); + assert.equal(c.steps, 40); + assert.equal(c.run_width, null); + assert.equal(c.rail, "both"); + assert.equal(stairConfig({ stair: { shape: "zigzag" as never } }).shape, "straight"); +}); + +test("every shape has one tread per riser, rising evenly to the full height", () => { + for (const shape of STAIR_SHAPES) { + const [w, d] = STAIR_SIZES[shape]; + const layout = stairLayout(cfg({ shape }), w, d, 2.8); + assert.equal(layout.treads.length, layout.steps, shape); + assert.ok(Math.abs(layout.treads.at(-1)!.top - 2.8) < 1e-9, shape); + assert.ok(Math.abs(layout.rise - 2.8 / layout.steps) < 1e-9, shape); + for (const t of layout.treads) assert.ok(t.poly.length >= 3 && area(t.poly) > 0.005, `${shape}: tread has an area`); + } +}); + +test("treads stay inside the footprint", () => { + for (const shape of STAIR_SHAPES) { + const [w, d] = STAIR_SIZES[shape]; + for (const turn of ["left", "right"] as const) { + for (const t of stairLayout(cfg({ shape, turn }), w, d, 2.8).treads) { + for (const [x, z] of t.poly) assert.ok(Math.abs(x) <= w / 2 + 1e-6 && Math.abs(z) <= d / 2 + 1e-6, `${shape} ${turn}: ${x},${z}`); + } + } + } +}); + +test("turned stairs keep their area: treads plus landings cover the flights", () => { + const [w, d] = [2.2, 2.8]; + const total = (shape: StairConfig["shape"]) => stairLayout(cfg({ shape, run_width: 1 }), w, d, 2.8).treads.reduce((s, t) => s + area(t.poly), 0); + // L and quarter turn: two strips 1 m wide forming an L + const l = 1 * d + 1 * (w - 1); + assert.ok(Math.abs(total("l") - l) < 1e-6); + assert.ok(Math.abs(total("quarter") - l) < 1e-6); +}); + +test("a left turn mirrors a right turn", () => { + const right = stairLayout(cfg({ shape: "l" }), 2.2, 2.8, 2.8); + const left = stairLayout(cfg({ shape: "l", turn: "left" }), 2.2, 2.8, 2.8); + const xsRight = right.treads.flatMap((t) => t.poly.map((p) => p[0])).sort((a, b) => a - b); + const xsLeft = left.treads.flatMap((t) => t.poly.map((p) => -p[0])).sort((a, b) => a - b); + assert.deepEqual(xsLeft.map((v) => v.toFixed(6)), xsRight.map((v) => v.toFixed(6))); +}); + +test("stairs going down fall from the floor to the full depth", () => { + const layout = stairLayout(cfg({ down: true }), 1, 3.2, 2.6); + assert.ok(layout.treads[0].top < 0); + assert.ok(Math.abs(layout.treads.at(-1)!.top + 2.6) < 1e-9); +}); + +test("the opening lies over the top of the stair only, not over its foot", () => { + const layout = stairLayout(cfg(), 1, 4, 2.8); + const opening = stairOpening(layout, 2.8, false).flat(); + const zs = opening.map((p) => p[1]); + assert.ok(Math.min(...zs) <= -1.99, "reaches the top end"); + assert.ok(Math.max(...zs) < 1.9, "leaves the foot closed"); + assert.ok(stairOpening(layout, 2.8, false).reduce((sum, ring) => sum + area(ring), 0) < 4 * 1); + // going down, the opening is in the stair's own floor at its top (front) end + const down = stairOpening(stairLayout(cfg({ down: true }), 1, 4, 2.8), 2.8, true).flat(); + assert.ok(Math.max(...down.map((p) => p[1])) >= 1.99); +}); + +test("the opening follows the item into the plan", () => { + const ring = stairOpeningInPlan({ x: 10, z: 5, rotation: 90, w: 1, d: 4, h: 2.8, stair: {} }).flat(); + for (const [x, z] of ring) assert.ok(x >= 7.99 && x <= 12.01 && z >= 4.49 && z <= 5.51, `${x},${z}`); +}); + +test("the opening can cover the whole stair or nothing", () => { + const layout = stairLayout(cfg({ down: true }), 1, 4, 2.8); + const zs = (ring: [number, number][]) => ring.map((p) => p[1]); + // by headroom a stair going down leaves its lower end under the floor; "full" opens all of it + assert.ok(Math.min(...zs(stairOpening(layout, 2.8, true).flat())) > -1.9); + const full = stairOpening(layout, 2.8, true, "full").flat(); + assert.ok(Math.min(...zs(full)) <= -1.99 && Math.max(...zs(full)) >= 1.99); + assert.deepEqual(stairOpening(layout, 2.8, true, "none"), []); + assert.equal(stairConfig({ stair: { opening: "full" } }).opening, "full"); + assert.equal(stairConfig({ stair: { opening: "wide" as never } }).opening, "headroom"); + assert.deepEqual(stairOpeningInPlan({ x: 0, z: 0, rotation: 0, w: 1, d: 4, h: 2.8, stair: { opening: "none" } }), []); +}); + +test("an L stair opens the floor over its treads only, not over the inside corner", async () => { + const { pointInPolygon } = await import("../model.ts"); + const layout = stairLayout(cfg({ shape: "l" }), 2.2, 2.8, 2.8); + const rings = stairOpening(layout, 2.8, false, "full"); + assert.ok(rings.length >= 1); + // the inside corner of the L (right of the first flight, in front of the second) is floor, not opening + const corner: [number, number] = [0.3, 0]; + assert.ok(!rings.some((ring) => pointInPolygon(corner, ring)), "inside corner stays closed"); + // a point on the landing is open + assert.ok(rings.some((ring) => pointInPolygon([-0.6, -1.0], ring)), "landing is open"); +}); + +test("a U stair can have its landing at a chosen riser (#58)", () => { + const cfg = { ...DEFAULT_STAIR, shape: "u" as const, steps: 19, landing_after: 8 }; + const layout = stairLayout(cfg, 2.2, 2.6, 19 * 0.17); + const at = layout.treads.findIndex((t) => t.landing); + // 7 treads, then the landing on the 8th riser, then 11 more + assert.equal(at, 7); + assert.equal(layout.treads.length - at - 1, 11); + assert.ok(Math.abs(layout.treads[at].top - 8 * 0.17) < 1e-6); + // without it the flights share by length + const even = stairLayout({ ...cfg, landing_after: null }, 2.2, 2.6, 19 * 0.17); + assert.notEqual(even.treads.findIndex((t) => t.landing), 7); +}); diff --git a/frontend/src/geometry/stairs.ts b/frontend/src/geometry/stairs.ts new file mode 100644 index 0000000..ba885a0 --- /dev/null +++ b/frontend/src/geometry/stairs.ts @@ -0,0 +1,280 @@ +// The layout of a staircase: its treads and landings in local coordinates (x across, z in depth with the front at +z), +// worked out from its shape, the turn, the number of steps and its size. The 3D model, the plan symbol and the opening in +// the floor above (or, for stairs going down, in the floor it starts on) are all drawn from this one layout. + +import type { Vec2 } from "../model.ts"; +import { mergeHoles } from "./holes.ts"; + +export const STAIR_SHAPES = ["straight", "quarter", "l", "half", "u", "spiral"] as const; +export type StairShape = (typeof STAIR_SHAPES)[number]; + +/** How the stair is built: a solid mass under the steps, side stringers, one spine under the middle, or steps out of the wall. */ +export const STAIR_BUILDS = ["solid", "stringer", "mono", "cantilever"] as const; +export type StairBuild = (typeof STAIR_BUILDS)[number]; + +export const STAIR_RAILS = ["none", "left", "right", "both"] as const; +export type StairRail = (typeof STAIR_RAILS)[number]; + +export type StairTurn = "left" | "right"; + +/** How much of the floor a stair opens: where its treads lack headroom, over the whole stair, or nothing (a hatch or a closed stairwell). */ +export const STAIR_OPENINGS = ["headroom", "full", "none"] as const; +export type StairOpening = (typeof STAIR_OPENINGS)[number]; + +export interface StairConfig { + shape: StairShape; + /** The way a turned stair turns while walking up it. */ + turn: StairTurn; + build: StairBuild; + /** Closed risers (the boards between the treads). Solid stairs are always closed. */ + risers: boolean; + /** Number of risers; null = from the height (about 18 cm each). */ + steps: number | null; + /** Width of one flight of a turned stair; null = from the size. */ + run_width: number | null; + /** Leads down from this floor (into a cellar that need not be drawn) instead of up. */ + down: boolean; + rail: StairRail; + /** The opening in the floor the stair reaches (the floor above, or its own floor going down). */ + opening: StairOpening; + /** An L or U stair with a landing: the risers from the floor up to the landing (null = the flights share the risers by length). */ + landing_after?: number | null; +} + +export const DEFAULT_STAIR: StairConfig = { shape: "straight", turn: "right", build: "solid", risers: true, steps: null, run_width: null, down: false, rail: "none", opening: "headroom", landing_after: null }; + +/** A good starting size [w, d] for each shape, used when the shape is changed in the editor. */ +export const STAIR_SIZES: Record = { + straight: [1.0, 3.2], + quarter: [2.2, 2.6], + l: [2.2, 2.8], + half: [2.0, 2.6], + u: [2.2, 2.6], + spiral: [1.6, 1.6], +}; + +const MIN_STEPS = 2; +const MAX_STEPS = 40; +/** Height a person needs above a tread: where a tread is lower than this under the floor above, the floor is opened. */ +export const HEADROOM = 2.2; + +const isOneOf = (list: readonly T[], value: unknown): value is T => typeof value === "string" && (list as readonly string[]).includes(value); + +/** The stair settings of an item, with defaults for everything it does not set (older plans have none). */ +export function stairConfig(item: { stair?: Partial | null }): StairConfig { + const s = item.stair ?? {}; + const steps = typeof s.steps === "number" && Number.isFinite(s.steps) ? Math.round(Math.min(MAX_STEPS, Math.max(MIN_STEPS, s.steps))) : null; + const run = typeof s.run_width === "number" && Number.isFinite(s.run_width) && s.run_width > 0.2 ? s.run_width : null; + return { + shape: isOneOf(STAIR_SHAPES, s.shape) ? s.shape : DEFAULT_STAIR.shape, + turn: s.turn === "left" ? "left" : "right", + build: isOneOf(STAIR_BUILDS, s.build) ? s.build : DEFAULT_STAIR.build, + risers: s.risers !== false, + steps, + run_width: run, + down: s.down === true, + rail: isOneOf(STAIR_RAILS, s.rail) ? s.rail : DEFAULT_STAIR.rail, + opening: isOneOf(STAIR_OPENINGS, s.opening) ? s.opening : DEFAULT_STAIR.opening, + landing_after: typeof s.landing_after === "number" && Number.isFinite(s.landing_after) ? Math.max(1, Math.round(s.landing_after)) : null, + }; +} + +/** Whether an item is a stair with its own settings (the shaped stair); plain old stairs keep their simple look and rectangular opening. */ +export const isShapedStair = (item: { type: string; stair?: unknown }): boolean => item.type === "stairs" && !!item.stair; + +export interface Tread { + /** Outline in local coordinates. */ + poly: Vec2[]; + /** Height of the walking surface relative to the floor the stair stands on (negative for stairs going down). */ + top: number; + landing: boolean; + /** Points along the left and right side (walking up), from the front of the tread to its back. */ + left: Vec2[]; + right: Vec2[]; +} + +export interface StairLayout { + treads: Tread[]; + rise: number; + steps: number; + /** A spiral stair's middle column (radius), else 0. */ + column: number; + /** The width of one flight. */ + flight: number; +} + +const lerp = (a: Vec2, b: Vec2, t: number): Vec2 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]; +const same = (a: Vec2, b: Vec2) => Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6; + +function dedupe(points: Vec2[]): Vec2[] { + const out: Vec2[] = []; + for (const p of points) if (!out.length || !same(out[out.length - 1], p)) out.push(p); + while (out.length > 1 && same(out[0], out[out.length - 1])) out.pop(); + return out; +} + +/** A tread from its two sides: the outline goes up the left side and back down the right side. */ +function tread(left: Vec2[], right: Vec2[], landing = false): Omit { + return { poly: dedupe([...left, ...[...right].reverse()]), landing, left, right }; +} + +/** `count` treads of a straight flight from the front edge (fl, fr) to the back edge (bl, br). */ +function flight(fl: Vec2, fr: Vec2, bl: Vec2, br: Vec2, count: number): Omit[] { + const out: Omit[] = []; + for (let i = 0; i < count; i++) { + const [t0, t1] = [i / count, (i + 1) / count]; + out.push(tread([lerp(fl, bl, t0), lerp(fl, bl, t1)], [lerp(fr, br, t0), lerp(fr, br, t1)])); + } + return out; +} + +/** The point at distance `s` along a polyline, and the corners passed between two distances. */ +function along(path: Vec2[], s: number): Vec2 { + let rest = s; + for (let i = 0; i + 1 < path.length; i++) { + const length = Math.hypot(path[i + 1][0] - path[i][0], path[i + 1][1] - path[i][1]); + if (rest <= length || i + 2 === path.length) return lerp(path[i], path[i + 1], length ? Math.min(1, rest / length) : 0); + rest -= length; + } + return path[path.length - 1]; +} + +function stretch(path: Vec2[], s0: number, s1: number): Vec2[] { + const out: Vec2[] = [along(path, s0)]; + let walked = 0; + for (let i = 0; i + 1 < path.length; i++) { + walked += Math.hypot(path[i + 1][0] - path[i][0], path[i + 1][1] - path[i][1]); + if (walked > s0 + 1e-6 && walked < s1 - 1e-6) out.push(path[i + 1]); + } + out.push(along(path, s1)); + return out; +} + +const pathLength = (path: Vec2[]) => path.reduce((sum, p, i) => (i ? sum + Math.hypot(p[0] - path[i - 1][0], p[1] - path[i - 1][1]) : sum), 0); + +/** + * Winders turning around the inner side: `count` treads whose outer (left) side shares the outer path out evenly and whose + * inner (right) side meets in the pivot. `entry` and `exit` are the inner corners of the flights before and after. + */ +function winders(outer: Vec2[], entry: Vec2, pivot: Vec2, exit: Vec2, count: number): Omit[] { + const total = pathLength(outer); + const out: Omit[] = []; + for (let i = 0; i < count; i++) { + const right = dedupe([...(i === 0 ? [entry] : []), pivot, ...(i === count - 1 ? [exit] : [])]); + out.push(tread(stretch(outer, (total * i) / count, (total * (i + 1)) / count), right.length ? right : [pivot])); + } + return out; +} + +/** Splits `count` treads between two flights by their length. */ +function share(count: number, first: number, second: number): [number, number] { + if (count <= 0) return [0, 0]; + if (first <= 1e-3) return [0, count]; + if (second <= 1e-3) return [count, 0]; + const a = Math.min(count, Math.max(0, Math.round((count * first) / (first + second)))); + return [a, count - a]; +} + +/** A landing at a chosen riser: treads before it and after it (the landing itself is one tread); null when it is not set. */ +function landingSplit(cfg: StairConfig, n: number): [number, number] | null { + if (cfg.landing_after == null) return null; + const before = Math.min(n - 1, Math.max(1, Math.round(cfg.landing_after))) - 1; + return [before, n - 1 - before]; +} + +/** Layout for a stair turning right; a left-turning stair is this one mirrored. */ +function rightLayout(cfg: StairConfig, w: number, d: number, n: number): { treads: Omit[]; flight: number; column: number } { + const [x0, x1, zb, zf] = [-w / 2, w / 2, -d / 2, d / 2]; + switch (cfg.shape) { + case "quarter": + case "l": { + const f = Math.min(cfg.run_width ?? Math.min(1.0, Math.min(w, d) / 2), Math.min(w, d) - 0.05); + const corner: Vec2 = [x0 + f, zb + f]; + const outer: Vec2[] = [[x0, zb + f], [x0, zb], [x0 + f, zb]]; + const turn = cfg.shape === "l" ? 1 : Math.min(n, n >= 8 ? 3 : 2); + const [a, b] = cfg.shape === "l" ? landingSplit(cfg, n) ?? share(n - turn, d - f, w - f) : share(n - turn, d - f, w - f); + const first = flight([x0, zf], [x0 + f, zf], [x0, zb + f], corner, a); + const middle = cfg.shape === "l" ? [tread(outer, [corner], true)] : winders(outer, corner, corner, corner, turn); + const second = flight([x0 + f, zb], corner, [x1, zb], [x1, zb + f], b); + return { treads: [...first, ...middle, ...second], flight: f, column: 0 }; + } + case "half": + case "u": { + const f = Math.min(cfg.run_width ?? Math.min(1.1, (w - 0.1) / 2), (w - 0.02) / 2); + const zt = zb + f; + const outer: Vec2[] = [[x0, zt], [x0, zb], [x1, zb], [x1, zt]]; + const [entry, exit]: Vec2[] = [[x0 + f, zt], [x1 - f, zt]]; + const turn = cfg.shape === "u" ? 1 : Math.min(n, n >= 12 ? 6 : n >= 8 ? 4 : 2); + const [a, b] = cfg.shape === "u" ? landingSplit(cfg, n) ?? share(n - turn, d - f, d - f) : share(n - turn, d - f, d - f); + const first = flight([x0, zf], [x0 + f, zf], [x0, zt], entry, a); + const middle = cfg.shape === "u" ? [tread(outer, [entry, exit], true)] : winders(outer, entry, [0, zt], exit, turn); + // the second flight comes back towards the front, its outer (left) side along the right edge + const second = flight([x1, zt], exit, [x1, zf], [x1 - f, zf], b); + return { treads: [...first, ...middle, ...second], flight: f, column: 0 }; + } + case "spiral": { + const r = Math.min(w, d) / 2; + const column = Math.min(0.08, r * 0.12); + // about 22 cm going on the walking line, which runs at 60 % of the radius + const angle = Math.min(0.75, Math.max(0.3, 0.22 / (r * 0.6))); + const at = (radius: number, a: number): Vec2 => [Math.cos(a) * radius, Math.sin(a) * radius]; + const treads: Omit[] = []; + for (let i = 0; i < n; i++) { + // the first tread lies left of the column, entered from the front; turning right is clockwise in the plan + const [a0, a1] = [Math.PI + angle * i, Math.PI + angle * (i + 1)]; + const arc = [0, 0.5, 1].map((t) => at(r, a0 + (a1 - a0) * t)); + treads.push(tread(arc, [at(column, a0), at(column, a1)])); + } + return { treads, flight: r - column, column }; + } + default: + return { treads: flight([x0, zf], [x1, zf], [x0, zb], [x1, zb], n), flight: w, column: 0 }; + } +} + +/** The number of risers of a stair `h` high. */ +export const stairSteps = (cfg: StairConfig, h: number): number => cfg.steps ?? Math.min(MAX_STEPS, Math.max(MIN_STEPS, Math.round(Math.abs(h) / 0.18))); + +/** The treads of a stair of size w × d that climbs (or, going down, falls) by h. */ +export function stairLayout(cfg: StairConfig, w: number, d: number, h: number): StairLayout { + const n = stairSteps(cfg, h); + const rise = Math.abs(h) / n; + const base = rightLayout(cfg, Math.max(0.3, w), Math.max(0.3, d), n); + const mirror = (p: Vec2): Vec2 => [-p[0], p[1]]; + const treads = base.treads.map((t, i): Tread => { + // up: tread i is (i + 1) risers above the floor, the last one level with the floor above; + // down: the first tread is one riser below the floor, the last one level with the floor below + const top = cfg.down ? -rise * (i + 1) : rise * (i + 1); + if (cfg.turn === "right") return { ...t, top }; + return { poly: t.poly.map(mirror).reverse(), top, landing: t.landing, left: t.right.map(mirror), right: t.left.map(mirror) }; + }); + return { treads, rise, steps: n, column: base.column, flight: base.flight }; +} + +/** The centre of a tread (average of its corners): the walking line runs through these. */ +export function treadCentre(t: Tread): Vec2 { + const sum = t.poly.reduce((s, p) => [s[0] + p[0], s[1] + p[1]], [0, 0]); + return [sum[0] / t.poly.length, sum[1] / t.poly.length]; +} + +/** + * The opening a stair needs in the floor it reaches (local coordinates): the outline of every tread that lies less than the + * headroom below that floor, merged into one shape per piece. For stairs going up that floor is the one above (at h), for stairs + * going down the stair's own (at 0). The outline follows the treads, so an L or a spiral stair leaves the floor beside it whole. + */ +export function stairOpening(layout: StairLayout, h: number, down: boolean, opening: StairOpening = "headroom"): Vec2[][] { + if (opening === "none") return []; + const level = down ? 0 : Math.abs(h); + const near = opening === "full" ? layout.treads : layout.treads.filter((t, i) => t.top > level - HEADROOM || (!down && i === layout.treads.length - 1) || (down && i === 0)); + return mergeHoles(near.map((t) => t.poly).filter((poly) => poly.length >= 3)); +} + +/** The floor opening of a shaped stair in plan coordinates (the same transform the 3D model uses, mirror included). */ +export function stairOpeningInPlan(item: { x: number; z: number; rotation: number; w: number; d: number; h: number; mirror?: boolean; stair?: Partial | null }): Vec2[][] { + const cfg = stairConfig(item); + const local = stairOpening(stairLayout(cfg, item.w, item.d, item.h), item.h, cfg.down, cfg.opening); + const a = (item.rotation * Math.PI) / 180; + const [c, s] = [Math.cos(a), Math.sin(a)]; + const mx = item.mirror ? -1 : 1; + return local.map((ring) => ring.map(([x, z]): Vec2 => [item.x + mx * x * c - z * s, item.z + mx * x * s + z * c])); +} diff --git a/frontend/src/geometry/vec2.ts b/frontend/src/geometry/vec2.ts new file mode 100644 index 0000000..94b6a00 --- /dev/null +++ b/frontend/src/geometry/vec2.ts @@ -0,0 +1,18 @@ +// Two-component vector helpers for the plan geometry. + +import type { Vec2 } from "../model.ts"; + +export const sub = (p: Vec2, q: Vec2): Vec2 => [p[0] - q[0], p[1] - q[1]]; +export const add = (p: Vec2, q: Vec2): Vec2 => [p[0] + q[0], p[1] + q[1]]; +export const scale = (p: Vec2, k: number): Vec2 => [p[0] * k, p[1] * k]; +export const dot = (p: Vec2, q: Vec2): number => p[0] * q[0] + p[1] * q[1]; +/** The z component of the 3D cross product: positive when q lies counter-clockwise from p. */ +export const cross = (p: Vec2, q: Vec2): number => p[0] * q[1] - p[1] * q[0]; +export const norm = (p: Vec2): number => Math.hypot(p[0], p[1]); +export const unit = (p: Vec2): Vec2 => { + const l = norm(p) || 1; + return [p[0] / l, p[1] / l]; +}; +/** Normal on the left of a direction (the side of the walls' "left" faces). */ +export const leftOf = (d: Vec2): Vec2 => [-d[1], d[0]]; +export const rightOf = (d: Vec2): Vec2 => [d[1], -d[0]]; diff --git a/frontend/src/geometry/wall-corners.ts b/frontend/src/geometry/wall-corners.ts new file mode 100644 index 0000000..d06d29d --- /dev/null +++ b/frontend/src/geometry/wall-corners.ts @@ -0,0 +1,156 @@ +// Joining wall pieces: merging collinear runs, mitring the corners where walls meet, and tidying footprints. + +import type { Vec2 } from "../model.ts"; +import { add, cross, dot, leftOf, norm, rightOf, scale, sub, unit } from "./vec2.ts"; + +export interface WallSource { + room_id: string; + /** The edge in the room's stored point order (points[edge] to points[edge + 1]). */ + edge: number; + /** The covered range along that edge, in metres from points[edge]. */ + t0: number; + t1: number; +} + +/** A wall before its corners are known: between two nodes (indices into the vertex list). */ +export interface Draft { + free?: string; + /** The height at a; with `heightEnd` the top slopes from this height to that one at b. */ + height?: number; + heightEnd?: number; + a: number; + b: number; + left: number; + right: number; + exterior: boolean; + roomLeft: string | null; + roomRight: string | null; + sources: WallSource[]; +} + +/** The same wall seen from the other end. */ +function reversed(w: Draft): Draft { + const sloped = w.heightEnd !== undefined; + return { ...w, a: w.b, b: w.a, left: w.right, right: w.left, roomLeft: w.roomRight, roomRight: w.roomLeft, height: sloped ? w.heightEnd : w.height, heightEnd: sloped ? w.height : undefined }; +} + +/** Joins source ranges, merging consecutive pieces of the same room edge. */ +function joinSources(first: WallSource[], second: WallSource[]): WallSource[] { + const joined = first.map((s) => ({ ...s })); + for (const s of second) { + const neighbour = joined.find((o) => o.room_id === s.room_id && o.edge === s.edge && (Math.abs(o.t1 - s.t0) < 1e-6 || Math.abs(s.t1 - o.t0) < 1e-6)); + if (neighbour) { + neighbour.t0 = Math.min(neighbour.t0, s.t0); + neighbour.t1 = Math.max(neighbour.t1, s.t1); + } else joined.push({ ...s }); + } + return joined; +} + +/** Two walls that continue each other in a line and are alike in every respect. */ +function continuesInLine(w1: Draft, w2: Draft, verts: Vec2[]): boolean { + if (w1.a === w2.b) return false; // a closed loop of two walls + const d1 = unit(sub(verts[w1.b], verts[w1.a])); + const d2 = unit(sub(verts[w2.b], verts[w2.a])); + if (Math.abs(cross(d1, d2)) > 1e-6 || dot(d1, d2) <= 0) return false; + if (w1.free || w2.free) return false; + // a sloping wall is one piece of its own: merging would bend its slope + if (w1.heightEnd !== undefined || w2.heightEnd !== undefined) return false; + return ( + w1.height === w2.height && + w1.exterior === w2.exterior && + w1.roomLeft === w2.roomLeft && + w1.roomRight === w2.roomRight && + Math.abs(w1.left - w2.left) <= 1e-9 && + Math.abs(w1.right - w2.right) <= 1e-9 + ); +} + +/** Merges runs of collinear walls through nodes where nothing else meets (never across a node in `fixed`). */ +export function mergeCollinear(drafts: Draft[], verts: Vec2[], fixed: ReadonlySet = new Set()): Draft[] { + let walls = drafts.slice(); + for (;;) { + const touching = new Map(); + walls.forEach((w, i) => { + for (const node of [w.a, w.b]) touching.set(node, [...(touching.get(node) ?? []), i]); + }); + let merged: Draft[] | null = null; + for (const [node, ids] of touching) { + if (ids.length !== 2 || fixed.has(node)) continue; + // orient both walls so the first ends and the second starts at the node + const first = walls[ids[0]].b === node ? walls[ids[0]] : reversed(walls[ids[0]]); + const second = walls[ids[1]].a === node ? walls[ids[1]] : reversed(walls[ids[1]]); + if (!continuesInLine(first, second, verts)) continue; + const joined: Draft = { ...first, b: second.b, sources: joinSources(first.sources, second.sources) }; + merged = [...walls.filter((_, i) => i !== ids[0] && i !== ids[1]), joined]; + break; + } + if (!merged) return walls; + walls = merged; + } +} + +export interface EndCorners { + left: Vec2; + right: Vec2; +} + +interface Outgoing { + key: string; + d: Vec2; + left: number; + right: number; + angle: number; +} + +/** The two corner points of every wall end (":a", ":b"), as seen looking away from the node. */ +export function computeCorners(drafts: Draft[], verts: Vec2[]): Map { + const atNode = new Map(); + drafts.forEach((w, i) => { + const d = unit(sub(verts[w.b], verts[w.a])); + const ends: [number, Outgoing][] = [ + [w.a, { key: `${i}:a`, d, left: w.left, right: w.right, angle: Math.atan2(d[1], d[0]) }], + [w.b, { key: `${i}:b`, d: scale(d, -1), left: w.right, right: w.left, angle: Math.atan2(-d[1], -d[0]) }], + ]; + for (const [node, end] of ends) atNode.set(node, [...(atNode.get(node) ?? []), end]); + }); + + const corners = new Map(); + for (const [node, ends] of atNode) { + const p = verts[node]; + ends.sort((x, y) => x.angle - y.angle); + // start with square ends + for (const e of ends) corners.set(e.key, { left: add(p, scale(leftOf(e.d), e.left)), right: add(p, scale(rightOf(e.d), e.right)) }); + if (ends.length < 2) continue; + const reach = 4 * Math.max(...ends.map((e) => Math.max(e.left, e.right))) + 1e-9; + ends.forEach((e, k) => { + // the sector between e (counter-clockwise) and the next end is bounded by e's left face and the next one's right face + const next = ends[(k + 1) % ends.length]; + const onE = add(p, scale(leftOf(e.d), e.left)); + const onNext = add(p, scale(rightOf(next.d), next.right)); + const turn = cross(e.d, next.d); + if (Math.abs(turn) < 1e-4) return; // a straight continuation or an overlap: the square ends stay + const corner = add(onE, scale(e.d, cross(sub(onNext, onE), next.d) / turn)); + if (norm(sub(corner, p)) > reach) return; // a very sharp angle keeps square ends + corners.get(e.key)!.left = corner; + corners.get(next.key)!.right = corner; + }); + } + return corners; +} + +/** Removes repeated points and points in a straight line. */ +export function cleanPolygon(points: Vec2[], eps: number): Vec2[] { + let ring = points.filter((p, i) => norm(sub(p, points[(i + 1) % points.length])) > eps); + for (;;) { + if (ring.length <= 3) return ring; + const straight = ring.findIndex((cur, i) => { + const before = ring[(i + ring.length - 1) % ring.length]; + const after = ring[(i + 1) % ring.length]; + const [d1, d2] = [sub(cur, before), sub(after, cur)]; + return Math.abs(cross(unit(d1), unit(d2))) < 1e-7 && dot(d1, d2) > 0; + }); + if (straight === -1) return ring; + ring = ring.filter((_, j) => j !== straight); + } +} diff --git a/frontend/src/geometry/walls.test.ts b/frontend/src/geometry/walls.test.ts new file mode 100644 index 0000000..0dd576f --- /dev/null +++ b/frontend/src/geometry/walls.test.ts @@ -0,0 +1,244 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { polygonArea, signedArea, type FreeWall, type Room, type Vec2 } from "../model.ts"; +import { generateWalls, innerSize, locateOnWalls, locateOpening, openingHost, pointOnRoomEdge } from "./walls.ts"; + +const OUTER = 0.3; +const INNER = 0.1; +const opts = { exterior: OUTER, interior: INNER }; + +const room = (id: string, x0: number, z0: number, x1: number, z1: number, extra: Partial = {}): Room => ({ + id, + name: id, + area_id: null, + points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]], + floor_material: "wood", + ...extra, +}); + +const near = (a: number, b: number, eps = 1e-6) => assert.ok(Math.abs(a - b) < eps, `${a} vs ${b}`); +const onLine = (w: { a: Vec2; b: Vec2 }, axis: 0 | 1, value: number) => Math.abs(w.a[axis] - value) < 1e-6 && Math.abs(w.b[axis] - value) < 1e-6; + +test("one room: four outer walls with the room on their left, footprints counter-clockwise", () => { + const { walls, warnings, open } = generateWalls([room("a", 0, 0, 5, 3)], opts); + assert.equal(walls.length, 4); + assert.deepEqual([warnings, open], [[], []]); + for (const w of walls) { + assert.deepEqual([w.exterior, w.roomLeft, w.roomRight, w.left, w.right], [true, "a", null, 0, OUTER]); + assert.ok(signedArea(w.footprint) > 0); + } + // together they form the ring around the room + const area = walls.reduce((sum, w) => sum + polygonArea(w.footprint), 0); + near(area, (5 + 2 * OUTER) * (3 + 2 * OUTER) - 15); +}); + +test("a room stored clockwise gets the same walls", () => { + const ccw = generateWalls([room("a", 0, 0, 5, 3)], opts).walls; + const cw = generateWalls([{ ...room("a", 0, 0, 5, 3), points: [[0, 0], [0, 3], [5, 3], [5, 0]] }], opts).walls; + assert.equal(cw.length, ccw.length); + near(cw.reduce((s, w) => s + polygonArea(w.footprint), 0), ccw.reduce((s, w) => s + polygonArea(w.footprint), 0)); + assert.ok(cw.every((w) => w.exterior && w.roomLeft === "a")); +}); + +test("an edge shared by two rooms becomes one interior wall centred on it", () => { + const { walls } = generateWalls([room("a", 0, 0, 4, 3), room("b", 4, 0, 9, 3)], opts); + const shared = walls.filter((w) => !w.exterior); + assert.equal(shared.length, 1); + near(shared[0].left, INNER / 2); + near(shared[0].right, INNER / 2); + assert.deepEqual([shared[0].roomLeft, shared[0].roomRight].sort(), ["a", "b"]); + assert.equal(walls.filter((w) => w.exterior).length, 6); +}); + +test("partly shared edges and T-junctions are split where the other room's corner touches", () => { + const { walls } = generateWalls([room("a", 0, 0, 4, 6), room("b", 4, 0, 8, 2), room("c", 4, 2, 8, 6)], opts); + const shared = walls.filter((w) => !w.exterior && onLine(w, 0, 4)); + assert.equal(shared.length, 2, "a-b and a-c along x = 4"); + assert.equal(walls.filter((w) => !w.exterior).length, 3, "plus b-c"); +}); + +test("vertices a few millimetres apart count as one", () => { + const a = room("a", 0, 0, 4, 3); + const b = room("b", 4.003, 0.002, 8, 3); + assert.equal(generateWalls([a, b], opts).walls.filter((w) => !w.exterior).length, 1); +}); + +test("collinear pieces of a room edge merge into one wall; hand-set splits keep them apart", () => { + const plain = generateWalls([room("a", 0, 0, 6, 4)], opts).walls; + assert.equal(plain.filter((w) => onLine(w, 1, 0)).length, 1); + const split = generateWalls([room("a", 0, 0, 6, 4, { wall_splits: [[2], null, null, null] })], opts).walls; + assert.equal(split.filter((w) => onLine(w, 1, 0)).length, 2); + assert.ok(split.some((w) => Math.abs(Math.max(w.a[0], w.b[0]) - 2) < 1e-9)); +}); + +test("an L-shaped room gets a mitred corner on the inside of the L", () => { + const l: Room = { ...room("l", 0, 0, 6, 6), points: [[0, 0], [6, 0], [6, 3], [3, 3], [3, 6], [0, 6]] }; + const { walls } = generateWalls([l], opts); + assert.equal(walls.length, 6); + const area = walls.reduce((s, w) => s + polygonArea(w.footprint), 0); + // an L of 27 m²: the ring is the outline grown by OUTER, minus the room itself + assert.ok(area > 27 * 0.1 && area < 27, String(area)); + for (const w of walls) assert.ok(w.footprint.length >= 4); +}); + +test("rooms drawn on top of each other are reported; degenerate rooms are ignored", () => { + const overlap = generateWalls([room("a", 0, 0, 4, 3), room("b", 0, 0, 4, 3)], opts); + assert.ok(overlap.warnings.includes("overlap:a:b")); + const ignored = generateWalls([{ ...room("d", 0, 0, 1, 1), points: [[0, 0], [1, 0]] }, { ...room("z", 0, 0, 1, 1), points: [[0, 0], [2, 0], [4, 0]] }], opts); + assert.deepEqual(ignored.walls, []); +}); + +test("a position on a room edge is found on the wall that carries it", () => { + const rooms = [room("a", 0, 0, 4, 3), room("b", 4, 0, 10, 3)]; + const { walls } = generateWalls(rooms, opts); + // b's west edge is its edge 3, from (4, 3) to (4, 0): one metre in is (4, 2) + assert.deepEqual(pointOnRoomEdge(rooms[1], 3, 1), [4, 2]); + const hit = locateOnWalls(walls, rooms[1], 3, 1)!; + assert.equal(hit.wall.exterior, false); + const wallLength = Math.hypot(hit.wall.b[0] - hit.wall.a[0], hit.wall.b[1] - hit.wall.a[1]); + const at: Vec2 = [hit.wall.a[0] + ((hit.wall.b[0] - hit.wall.a[0]) / wallLength) * hit.s, hit.wall.a[1] + ((hit.wall.b[1] - hit.wall.a[1]) / wallLength) * hit.s]; + near(at[0], 4); + near(at[1], 2); + assert.equal(locateOnWalls(walls, rooms[1], 3, 50), null); +}); + +test("a free-standing wall is an interior wall of its room and splits the edge it touches; tiny ones vanish", () => { + const r = room("r", 0, 0, 6, 4); + const free: FreeWall[] = [{ id: "fw", a: [3, 0], b: [3, 2.5], thickness: 0.2 }]; + const { walls } = generateWalls([r], opts, free); + const fw = walls.find((w) => w.free === "fw")!; + assert.deepEqual([fw.exterior, fw.roomLeft, fw.roomRight], [false, "r", "r"]); + near(fw.left + fw.right, 0.2); + assert.equal(walls.filter((w) => !w.free && onLine(w, 1, 0)).length, 2, "the outer wall is cut at x = 3"); + assert.equal(generateWalls([r], opts, [{ id: "t", a: [1, 1], b: [1, 1.01] }]).walls.some((w) => w.free), false); +}); + +test("walls take their own height from the room edge; a shared wall takes the lower one; a free wall has its own", () => { + const a = room("a", 0, 0, 4, 3, { wall_heights: [1.2, 0.9, null, null] }); + const b = room("b", 4, 0, 8, 3, { wall_heights: [null, null, null, 1.5] }); + const { walls } = generateWalls([a, b], opts, [{ id: "f", a: [1, 1], b: [3, 1], height: 1.1 }]); + assert.equal(walls.find((w) => w.exterior && w.sources[0].room_id === "a" && w.sources[0].edge === 0)?.height, 1.2); + assert.equal(walls.find((w) => !w.exterior && !w.free)?.height, 0.9); + assert.equal(walls.find((w) => w.free === "f")?.height, 1.1); + assert.equal(walls.find((w) => w.exterior && w.sources[0].room_id === "b" && w.sources[0].edge === 0)?.height, undefined); +}); + +test("a height of 0 leaves a wall out, and the two rooms are reported as one open space", () => { + const a = room("a", 0, 0, 4, 3, { wall_heights: [null, 0, null, null] }); + const res = generateWalls([a, room("b", 4, 0, 8, 3)], opts); + assert.deepEqual(res.open, [["a", "b"]]); + assert.equal(res.walls.some((w) => !w.exterior), false); +}); + +test("a split edge can carry one height per part", () => { + const a = room("a", 0, 0, 4, 6, { wall_heights: [null, [1, null], null, null] }); + const res = generateWalls([a, room("b", 4, 0, 8, 3), room("c", 4, 3, 8, 6)], opts); + const between = (x: string, y: string) => res.walls.find((w) => !w.exterior && [w.roomLeft, w.roomRight].sort().join() === [x, y].sort().join())!; + assert.equal(between("a", "b").height, 1); + assert.equal(between("a", "c").height, undefined); +}); + +test("a thickness on a room edge wins; a shared wall takes the thicker of the two", () => { + const a = room("a", 0, 0, 4, 3, { wall_thickness: [0.4, null, 0.08, null] }); + const b = room("b", 4, 0, 7, 3, { wall_thickness: [null, null, null, 0.2] }); + const { walls } = generateWalls([a, b], opts); + near(walls.find((w) => w.exterior && w.sources[0].room_id === "a" && w.sources[0].edge === 0)!.right, 0.4); + const shared = walls.find((w) => !w.exterior)!; + near(shared.left + shared.right, 0.2); + near(walls.find((w) => w.exterior && w.sources[0].room_id === "a" && w.sources[0].edge === 2)!.right, 0.08); +}); + +test("an interior wall that continues an outer wall in line sits flush with the outer wall's inner face", () => { + const { walls } = generateWalls([room("a", 0, 0, 4, 3), room("b", 4, 0, 7, 5)], opts); + const inner = walls.find((w) => !w.exterior)!; + const sideOfB = inner.roomLeft === "b" ? inner.left : inner.right; + near(sideOfB, 0); + near(inner.left + inner.right, INNER); +}); + +test("an opening is hosted by its room's edge, or by a free wall; hosts that do not exist give null", () => { + const rooms = [room("a", 0, 0, 4, 3)]; + const free: FreeWall[] = [{ id: "f", a: [1, 1], b: [3, 1] }]; + assert.equal(openingHost({ room_id: "a", edge: 2, wall: undefined }, rooms, free)?.edge, 2); + assert.equal(openingHost({ room_id: "a", edge: 9, wall: undefined }, rooms, free), null); + assert.equal(openingHost({ room_id: "nope", edge: 0, wall: undefined }, rooms, free), null); + const onFree = openingHost({ room_id: "a", edge: 0, wall: "f" }, rooms, free)!; + assert.equal(onFree.edge, 0); + assert.deepEqual(onFree.room.points.slice(0, 2), [[1, 1], [3, 1]]); + assert.equal(openingHost({ room_id: "a", edge: 0, wall: "gone" }, rooms, free), null); +}); + +test("an opening in a free wall is located on that wall, with its room side on the left", () => { + const rooms = [room("a", 0, 0, 6, 4)]; + const free: FreeWall[] = [{ id: "f", a: [1, 2], b: [5, 2] }]; + const { walls } = generateWalls(rooms, opts, free); + const host = openingHost({ room_id: "a", edge: 0, wall: "f" }, rooms, free)!; + const hit = locateOpening(walls, { wall: "f", offset: 1.5 }, host)!; + assert.equal(hit.wall.free, "f"); + near(hit.s, 1.5); + assert.equal(locateOpening(walls, { wall: "other", offset: 1 }, host), null); + const plain = locateOpening(walls, { wall: undefined, offset: 1 }, { room: rooms[0], edge: 0 })!; + assert.equal(plain.wall.exterior, true); +}); + +test("a sloping wall carries the heights at its two ends, whichever way the room is stored", () => { + // the right wall (edge 1, from (4,0) to (4,3)) climbs from 2.5 to 4.7 + const sloped = room("a", 0, 0, 4, 3, { wall_heights: [null, 2.5, null, null], wall_slopes: [null, 4.7, null, null] }); + const right = generateWalls([sloped], opts).walls.find((w) => onLine(w, 0, 4))!; + const [low, high] = right.a[1] < right.b[1] ? [right.a[1], right.b[1]] : [right.b[1], right.a[1]]; + assert.equal([low, high].join(), "0,3"); + assert.deepEqual([right.height, right.heightEnd], right.a[1] < right.b[1] ? [2.5, 4.7] : [4.7, 2.5]); + // stored clockwise the wall still climbs towards z = 3 + const clockwise = { ...sloped, points: [...sloped.points].reverse() as Vec2[], wall_heights: [null, 4.7, null, null], wall_slopes: [null, 2.5, null, null] }; + const again = generateWalls([clockwise], opts).walls.find((w) => onLine(w, 0, 4))!; + const topAtZ3 = again.a[1] === 3 ? again.height : again.heightEnd; + assert.equal(topAtZ3, 4.7); +}); + +test("a sloping shared wall: the other room runs the other way and its level height caps both ends", () => { + const a = room("a", 0, 0, 4, 3, { wall_heights: [null, 2.5, null, null], wall_slopes: [null, 4.7, null, null] }); + const b = room("b", 4, 0, 8, 3, { wall_heights: [null, null, null, 3.5] }); + const shared = generateWalls([a, b], opts).walls.find((w) => !w.exterior)!; + const [atZ0, atZ3] = shared.a[1] < shared.b[1] ? [shared.height, shared.heightEnd] : [shared.heightEnd, shared.height]; + assert.equal(atZ0, 2.5); + assert.equal(atZ3, 3.5, "the lower setting wins at each end"); +}); + +test("a wall with no slope has no end height, and an unset or invalid slope is ignored", () => { + const plain = generateWalls([room("a", 0, 0, 4, 3, { wall_heights: [1.2, null, null, null] })], opts).walls; + assert.ok(plain.every((w) => w.heightEnd === undefined)); + // a slope without a start height, a zero end height, or heights per part do not slope + const odd = generateWalls([room("a", 0, 0, 4, 3, { wall_heights: [null, 2.5, [1, 2], null], wall_slopes: [3, 0, 3, null] })], opts).walls; + assert.ok(odd.every((w) => w.heightEnd === undefined)); +}); + +test("a room's inner size loses half of each inner wall, nothing to the outer walls", () => { + const a: Room = { id: "a", name: "A", area_id: null, points: [[0, 0], [4, 0], [4, 3], [0, 3]], floor_material: "wood" }; + const b: Room = { id: "b", name: "B", area_id: null, points: [[4, 0], [7, 0], [7, 3], [4, 3]], floor_material: "wood" }; + const { walls } = generateWalls([a, b], { exterior: 0.3, interior: 0.12 }); + assert.deepEqual(innerSize(a, walls), [3.94, 3]); +}); + +test("a split edge can have a thickness per part", () => { + const a: Room = { id: "a", name: "A", area_id: null, points: [[0, 0], [4, 0], [4, 3], [0, 3]], floor_material: "wood", wall_splits: [[2]], wall_thickness: [[0.5, 0.2]] }; + const { walls } = generateWalls([a], { exterior: 0.3, interior: 0.12 }); + const top = walls.filter((w) => Math.abs(w.a[1]) < 1e-6 && Math.abs(w.b[1]) < 1e-6).map((w) => w.left + w.right).sort(); + assert.deepEqual(top, [0.2, 0.5]); +}); + +test("one straight interior wall through several rooms keeps straight faces, even when outer walls at its ends disagree (#65)", () => { + // the line z = 3 runs between a, b above and c below; at its left end c sticks out by 1 cm, at its right end b does + const { walls } = generateWalls([room("a", 0.05, 0, 2, 3), room("b", 2, 0, 4.4, 3), room("c", 0.04, 3, 4, 6)], opts); + const line = walls.filter((w) => !w.exterior && Math.abs(w.a[1] - 3) < 1e-9 && Math.abs(w.b[1] - 3) < 1e-9); + assert.equal(line.length, 2); + for (const w of line) near(w.left, w.right); +}); + +test("a free wall with an end height slopes from its height at a to the one at b (#sloping free walls)", () => { + const { walls } = generateWalls([room("a", 0, 0, 6, 4)], opts, [{ id: "f", a: [1, 2], b: [5, 2], height: 2.4, height_end: 1 }]); + const w = walls.find((x) => x.free === "f")!; + assert.equal(w.height, 2.4); + assert.equal(w.heightEnd, 1); + const flat = generateWalls([room("a", 0, 0, 6, 4)], opts, [{ id: "g", a: [1, 2], b: [5, 2], height: 2.4, height_end: 2.4 }]).walls.find((x) => x.free === "g")!; + assert.equal(flat.heightEnd, undefined, "the same height at both ends is a plain wall"); +}); diff --git a/frontend/src/geometry/walls.ts b/frontend/src/geometry/walls.ts new file mode 100644 index 0000000..c322990 --- /dev/null +++ b/frontend/src/geometry/walls.ts @@ -0,0 +1,418 @@ +// Walls from room polygons. +// +// Rooms are drawn along the centre line of interior walls. An edge shared by two rooms becomes one interior wall +// centred on it; an edge with a room on one side only becomes an exterior wall growing outwards. Edges are split wherever +// a vertex of another room lies on them, so partly shared edges and T-junctions work. At every node the ends of the +// walls are mitred by intersecting the face lines of the neighbouring walls. + +import { pointInPolygon, signedArea, type FreeWall, type Opening, type Room, type Vec2 } from "../model.ts"; +import { cleanPolygon, computeCorners, mergeCollinear, type Draft, type WallSource } from "./wall-corners.ts"; +import { add, cross, dot, norm, scale, sub, unit } from "./vec2.ts"; + +export type { WallSource }; + +export interface Wall { + id: string; + a: Vec2; + b: Vec2; + /** Distance of the left face (normal (-dz, dx)) from the line a-b. */ + left: number; + /** Distance of the right face (normal (dz, -dx)) from the line a-b. */ + right: number; + exterior: boolean; + /** The room on the left and right of a to b. Exterior walls have their room on the left. */ + roomLeft: string | null; + roomRight: string | null; + sources: WallSource[]; + /** The footprint, counter-clockwise, mitred at both ends. */ + footprint: Vec2[]; + /** Set for a free-standing wall drawn on its own (its id). */ + free?: string; + /** Its own height in metres (at `a`); absent means the full height of the floor. */ + height?: number; + /** A sloping wall: the height at `b` (the top runs straight from `height` at a to this one at b; it may rise above the floor height). */ + heightEnd?: number; +} + +export interface WallOptions { + exterior: number; + interior: number; + /** Vertices closer than this are merged (metres). */ + eps?: number; +} + +export interface WallResult { + walls: Wall[]; + /** Pairs of rooms that overlap along an edge in the same direction (rooms drawn on top of each other). */ + warnings: string[]; + /** Pairs of rooms whose shared wall is left out ("no wall"): they form one space, also for the light. */ + open: [string, string][]; +} + +/** A stretch of a room edge between two vertices (indices). */ +interface Piece { + u: number; + v: number; + room: string; + edge: number; + t0: number; + t1: number; + /** True when u lies at t0 (the room is stored counter-clockwise), false when u lies at t1. */ + forward: boolean; +} + +interface RoomEdge { + u: number; + v: number; + room: string; + edge: number; + /** True when u is points[edge], false when the room was stored clockwise. */ + forward: boolean; +} + +/** Collects vertices, merging points that are closer than `eps`. */ +function vertexList(eps: number) { + const points: Vec2[] = []; + return { + points, + idOf(p: Vec2): number { + const found = points.findIndex((q) => Math.abs(q[0] - p[0]) <= eps && Math.abs(q[1] - p[1]) <= eps); + if (found >= 0) return found; + points.push([p[0], p[1]]); + return points.length - 1; + }, + }; +} +type VertexList = ReturnType; + +/** Every room edge, running counter-clockwise, remembering the stored edge it came from. */ +function roomEdges(rooms: readonly Room[], vertices: VertexList): RoomEdge[] { + const edges: RoomEdge[] = []; + for (const room of rooms) { + const pts = room.points; + if (pts.length < 3 || Math.abs(signedArea(pts)) < 1e-6) continue; + const counterClockwise = signedArea(pts) > 0; + const ids = pts.map((p) => vertices.idOf(p)); + ids.forEach((start, i) => { + const end = ids[(i + 1) % ids.length]; + if (start === end) return; + edges.push(counterClockwise ? { u: start, v: end, room: room.id, edge: i, forward: true } : { u: end, v: start, room: room.id, edge: i, forward: false }); + }); + } + return edges; +} + +/** Splits every edge at the vertices that lie on it. */ +function splitEdges(edges: RoomEdge[], verts: Vec2[], eps: number): Piece[] { + const pieces: Piece[] = []; + for (const e of edges) { + const [from, to] = [verts[e.u], verts[e.v]]; + const d = sub(to, from); + const length = norm(d); + const dir = scale(d, 1 / length); + const onEdge = verts + .map((v, id) => ({ id, rel: sub(v, from) })) + .filter(({ id, rel }) => id !== e.u && id !== e.v && dot(rel, dir) > eps && dot(rel, dir) < length - eps && Math.abs(cross(dir, rel)) <= eps) + .map(({ id, rel }) => ({ t: dot(rel, dir), id })) + .sort((x, y) => x.t - y.t); + const stops = [{ t: 0, id: e.u }, ...onEdge, { t: length, id: e.v }]; + for (let k = 0; k + 1 < stops.length; k++) { + const [s, n] = [stops[k], stops[k + 1]]; + // distances are measured along the stored edge, from its stored start point + pieces.push({ u: s.id, v: n.id, room: e.room, edge: e.edge, t0: e.forward ? s.t : length - n.t, t1: e.forward ? n.t : length - s.t, forward: e.forward }); + } + } + return pieces; +} + +const sourceOf = (p: Piece): WallSource => ({ room_id: p.room, edge: p.edge, t0: p.t0, t1: p.t1 }); + +/** Reads what the rooms say about heights and thicknesses of their edges. */ +function edgeSettings(rooms: readonly Room[], pieces: Piece[]) { + const roomById = new Map(rooms.map((r) => [r.id, r])); + // a split edge may carry one height per part, in order along the edge + const partStarts = new Map(); + for (const p of pieces) { + const key = `${p.room}:${p.edge}`; + partStarts.set(key, [...(partStarts.get(key) ?? []), p.t0].sort((a, b) => a - b)); + } + const heightSet = (p: Piece): number | null | undefined => { + const h = roomById.get(p.room)?.wall_heights?.[p.edge]; + if (!Array.isArray(h)) return h; + return h[(partStarts.get(`${p.room}:${p.edge}`) ?? []).indexOf(p.t0)] ?? null; + }; + /** The sloping edge of a piece: its start and end height over the whole room edge (both set, a whole edge only). */ + const slopeOf = (p: Piece): { from: number; to: number; length: number } | null => { + const room = roomById.get(p.room); + const [from, to] = [room?.wall_heights?.[p.edge], room?.wall_slopes?.[p.edge]]; + if (!room || typeof from !== "number" || typeof to !== "number" || from <= 0 || to <= 0) return null; + const [a, b] = [room.points[p.edge], room.points[(p.edge + 1) % room.points.length]]; + return { from, to, length: Math.hypot(b[0] - a[0], b[1] - a[1]) }; + }; + /** The heights a piece sets at its two ends (u, v); null where it sets none. */ + const endsOf = (p: Piece): [number | null, number | null] => { + const slope = slopeOf(p); + if (!slope || slope.length < 1e-9) { + const h = heightSet(p); + return typeof h === "number" && h > 0 ? [h, h] : [null, null]; + } + const at = (t: number) => slope.from + ((slope.to - slope.from) * t) / slope.length; + return p.forward ? [at(p.t0), at(p.t1)] : [at(p.t1), at(p.t0)]; + }; + return { + /** + * The wall's own height at its two ends: the lowest one set on its room edges at each end (a shared wall takes the lower + * setting). The list starts with the piece the wall's direction follows; a partner runs the other way. + */ + heightsOf(list: Piece[]): { a?: number; b?: number } { + let [a, b] = [Infinity, Infinity]; + for (const p of list) { + const [u, v] = endsOf(p); + const [atA, atB] = p === list[0] ? [u, v] : [v, u]; + if (atA !== null) a = Math.min(a, atA); + if (atB !== null) b = Math.min(b, atB); + } + // no height set by hand: the rooms' own ceilings – the higher one, so the wall closes the taller room; a room without + // a ceiling of its own stands for the full floor height + const ceilings = list.map((p) => roomById.get(p.room)?.ceiling); + if (ceilings.every((c): c is number => typeof c === "number" && c > 0)) { + const top = Math.max(...ceilings); + if (a === Infinity) a = top; + if (b === Infinity) b = top; + } + return { ...(a < Infinity ? { a } : {}), ...(b < Infinity ? { b } : {}) }; + }, + /** A thickness set on a room edge; a shared wall takes the thicker one of its two rooms. */ + thicknessOf(list: Piece[]): number | undefined { + const values = list + .map((p) => { + const entry = roomById.get(p.room)?.wall_thickness?.[p.edge]; + return Array.isArray(entry) ? entry[(partStarts.get(`${p.room}:${p.edge}`) ?? []).indexOf(p.t0)] : entry; + }) + .filter((t): t is number => typeof t === "number" && t > 0); + return values.length ? Math.max(...values) : undefined; + }, + /** A height of 0 on an edge means no wall at all: an open plan whose rooms share one space. */ + hasNoWall: (list: Piece[]): boolean => list.some((p) => heightSet(p) === 0), + }; +} + +/** Walls between pieces: two rooms in opposite directions make an interior wall, one room an exterior wall. */ +/** The draft fields for a wall's heights: a level wall has one, a sloping one its start and end. */ +function heightFields(h: { a?: number; b?: number }): { height?: number; heightEnd?: number } { + const round = (v: number) => Math.round(v * 1e6) / 1e6; + if (h.a === undefined || h.b === undefined) return h.a !== undefined ? { height: round(h.a) } : h.b !== undefined ? { height: round(h.b) } : {}; + return Math.abs(h.a - h.b) < 1e-6 ? { height: round(h.a) } : { height: round(h.a), heightEnd: round(h.b) }; +} + +function pairPieces(pieces: Piece[], rooms: readonly Room[], options: WallOptions, warnings: string[]): { drafts: Draft[]; open: [string, string][] } { + const settings = edgeSettings(rooms, pieces); + const groups = new Map(); + for (const p of pieces) { + const key = p.u < p.v ? `${p.u}-${p.v}` : `${p.v}-${p.u}`; + groups.set(key, [...(groups.get(key) ?? []), p]); + } + const drafts: Draft[] = []; + const open: [string, string][] = []; + for (const group of groups.values()) { + const first = group[0]; + const partner = group.find((p) => p !== first && p.u === first.v && p.v === first.u && p.room !== first.room); + for (const p of group) if (p !== first && p !== partner && p.room !== first.room) warnings.push(`overlap:${first.room}:${p.room}`); + const pair = partner ? [first, partner] : [first]; + if (settings.hasNoWall(pair)) { + if (partner) open.push([first.room, partner.room]); + continue; + } + if (partner) { + const thickness = settings.thicknessOf(pair) ?? options.interior; + drafts.push({ a: first.u, b: first.v, left: thickness / 2, right: thickness / 2, exterior: false, roomLeft: first.room, roomRight: partner.room, sources: pair.map(sourceOf), ...heightFields(settings.heightsOf(pair)) }); + } else { + drafts.push({ a: first.u, b: first.v, left: 0, right: settings.thicknessOf(pair) ?? options.exterior, exterior: true, roomLeft: first.room, roomRight: null, sources: [sourceOf(first)], ...heightFields(settings.heightsOf(pair)) }); + } + } + return { drafts, open }; +} + +/** + * An interior wall that continues an exterior wall in line sits flush with the exterior wall's inner face on the shared + * room, rather than standing half its thickness into that room. A straight run of interior walls (one line through + * several rooms) is aligned as a whole, so its faces stay straight: it is flush only when the exterior walls at its two + * ends agree on the side, otherwise it stays centred (#65). + */ +function alignWithExterior(drafts: Draft[], verts: Vec2[]): void { + const direction = (d: Draft) => unit(sub(verts[d.b], verts[d.a])); + const inner = drafts.filter((d) => !d.exterior && !d.free); + // runs of collinear interior walls joined end to end + const runOf = new Map(); + for (const wall of inner) { + if (runOf.has(wall)) continue; + const run = [wall]; + runOf.set(wall, run); + for (let k = 0; k < run.length; k++) { + const cur = run[k]; + for (const next of inner) { + if (runOf.has(next)) continue; + const touches = next.a === cur.a || next.a === cur.b || next.b === cur.a || next.b === cur.b; + if (touches && Math.abs(cross(direction(cur), direction(next))) < 1e-6) { + run.push(next); + runOf.set(next, run); + } + } + } + } + for (const run of new Set(runOf.values())) { + const axis = direction(run[0]); + const nodes = new Map(); + for (const w of run) for (const n of [w.a, w.b]) nodes.set(n, (nodes.get(n) ?? 0) + 1); + // which side of the run (seen along `axis`) the rooms of the exterior walls in line at its ends lie on + const sides = new Set<"left" | "right">(); + for (const [node, count] of nodes) { + if (count !== 1) continue; + for (const outer of drafts) { + if (!outer.exterior || outer.free || (outer.a !== node && outer.b !== node)) continue; + const along = direction(outer); + if (Math.abs(cross(axis, along)) > 1e-6) continue; + // an exterior wall has its room on its left + sides.add(dot(axis, along) > 0 ? "left" : "right"); + } + } + if (sides.size !== 1) continue; + const side = [...sides][0]; + for (const wall of run) { + const thickness = wall.left + wall.right; + const same = dot(direction(wall), axis) > 0; + const flushLeft = (side === "left") === same; + [wall.left, wall.right] = flushLeft ? [0, thickness] : [thickness, 0]; + } + } +} + +const wallId = (a: Vec2, b: Vec2): string => { + const cm = (x: number) => Math.round(x * 100); + const [p, q] = a[0] < b[0] || (a[0] === b[0] && a[1] <= b[1]) ? [a, b] : [b, a]; + return `w_${cm(p[0])}_${cm(p[1])}_${cm(q[0])}_${cm(q[1])}`; +}; + +export function generateWalls(rooms: readonly Room[], options: WallOptions, free: readonly FreeWall[] = []): WallResult { + const eps = options.eps ?? 0.005; + const warnings: string[] = []; + const vertices = vertexList(eps); + const edges = roomEdges(rooms, vertices); + + // free walls: their ends are vertices too, so a room edge they touch is split there (a T-junction) + const freeWalls = free.filter((w) => Math.hypot(w.b[0] - w.a[0], w.b[1] - w.a[1]) > 0.05); + const freeEnds = freeWalls.map((w) => [vertices.idOf(w.a), vertices.idOf(w.b)] as const); + // split points set by hand on room edges are vertices as well, and a wall never merges back across them + const handSplits = new Set(); + for (const room of rooms) { + const pts = room.points; + if (pts.length < 3) continue; + (room.wall_splits ?? []).forEach((offsets, i) => { + if (!offsets || i >= pts.length) return; + const start = pts[i]; + const d = sub(pts[(i + 1) % pts.length], start); + const length = norm(d); + for (const t of offsets) if (t > eps && t < length - eps) handSplits.add(vertices.idOf(add(start, scale(d, t / length)))); + }); + } + + const pieces = splitEdges(edges, vertices.points, eps); + const { drafts: paired, open } = pairPieces(pieces, rooms, options, warnings); + alignWithExterior(paired, vertices.points); + + // free walls count as interior walls of the room they stand in (the same room on both sides) + const drafts = paired; + freeWalls.forEach((w, i) => { + const [ia, ib] = freeEnds[i]; + if (ia === ib) return; + const middle: Vec2 = [(w.a[0] + w.b[0]) / 2, (w.a[1] + w.b[1]) / 2]; + const room = rooms.find((r) => r.points.length >= 3 && pointInPolygon(middle, r.points))?.id ?? null; + const half = (w.thickness ?? options.interior) / 2; + drafts.push({ free: w.id, a: ia, b: ib, left: half, right: half, exterior: false, roomLeft: room, roomRight: room, sources: [], height: typeof w.height === "number" && w.height > 0 ? w.height : undefined, ...(typeof w.height === "number" && w.height > 0 && typeof w.height_end === "number" && w.height_end > 0 && Math.abs(w.height_end - w.height) > 1e-6 ? { heightEnd: w.height_end } : {}) }); + }); + + const merged = mergeCollinear(drafts, vertices.points, handSplits); + const corners = computeCorners(merged, vertices.points); + const walls: Wall[] = merged.map((w, i) => { + const [a, b] = [vertices.points[w.a], vertices.points[w.b]]; + const [atA, atB] = [corners.get(`${i}:a`)!, corners.get(`${i}:b`)!]; + // at b the outgoing direction is reversed, so its left corner lies on the wall's right face + const footprint = cleanPolygon([atA.right, atB.left, b, atB.right, atA.left, a], 1e-6); + return { + id: wallId(a, b), + a: [a[0], a[1]], + b: [b[0], b[1]], + left: w.left, + right: w.right, + exterior: w.exterior, + roomLeft: w.roomLeft, + roomRight: w.roomRight, + sources: w.sources, + footprint, + ...(w.free ? { free: w.free } : {}), + ...(w.height !== undefined ? { height: w.height } : {}), + ...(w.heightEnd !== undefined ? { heightEnd: w.heightEnd } : {}), + }; + }); + return { walls, warnings: [...new Set(warnings)], open }; +} + +// ---------------------------------------------------------------- locating things on walls + +/** The point on a stored room edge, `offset` metres from points[edge]. */ +export function pointOnRoomEdge(room: Room, edge: number, offset: number): Vec2 { + const start = room.points[edge]; + return add(start, scale(unit(sub(room.points[(edge + 1) % room.points.length], start)), offset)); +} + +/** + * The line an opening sits on, as a room and an edge: the room's edge, or for an opening in a free wall a virtual + * triangle room whose edge 0 is the free wall (the room side is its left). + */ +export function openingHost(o: Pick, rooms: readonly Room[], free: readonly FreeWall[]): { room: Room; edge: number } | null { + if (o.wall) { + const wall = free.find((x) => x.id === o.wall); + if (!wall || Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]) < 0.05) return null; + const d = unit(sub(wall.b, wall.a)); + const room = { id: o.room_id, name: "", area_id: null, points: [wall.a, wall.b, add(wall.a, [-d[1], d[0]])] } as unknown as Room; + return { room, edge: 0 }; + } + const room = rooms.find((r) => r.id === o.room_id); + return room && o.edge < room.points.length ? { room, edge: o.edge } : null; +} + +const along = (wall: Wall, p: Vec2): number => dot(sub(p, wall.a), unit(sub(wall.b, wall.a))); + +/** Finds an opening in the generated walls (see openingHost): the wall, and the distance from wall.a. */ +export function locateOpening(walls: readonly Wall[], o: Pick, host: { room: Room; edge: number }): { wall: Wall; s: number } | null { + if (!o.wall) return locateOnWalls(walls, host.room, host.edge, o.offset); + const wall = walls.find((w) => w.free === o.wall); + return wall ? { wall, s: along(wall, pointOnRoomEdge(host.room, 0, o.offset)) } : null; +} + +/** Finds a position on a room edge in the generated walls: the wall, and the distance from wall.a. */ +export function locateOnWalls(walls: readonly Wall[], room: Room, edge: number, offset: number): { wall: Wall; s: number } | null { + for (const wall of walls) { + const covers = wall.sources.some((s) => s.room_id === room.id && s.edge === edge && offset >= s.t0 - 1e-6 && offset <= s.t1 + 1e-6); + if (covers) return { wall, s: along(wall, pointOnRoomEdge(room, edge, offset)) }; + } + return null; +} + +/** + * Inner size of a rectangular room from wall face to wall face: its outline runs along the wall centres inside the house (and along + * the inner faces of outer walls), so each side loses what its walls stand into the room. Null for a room that is not a rectangle. + */ +export function innerSize(room: Room, walls: readonly Wall[]): [number, number] | null { + const xs = room.points.map((p) => p[0]); + const zs = room.points.map((p) => p[1]); + if (room.points.length !== 4 || new Set(xs.map((v) => v.toFixed(3))).size !== 2 || new Set(zs.map((v) => v.toFixed(3))).size !== 2) return null; + const [x0, x1, z0, z1] = [Math.min(...xs), Math.max(...xs), Math.min(...zs), Math.max(...zs)]; + const into = (onSide: (w: Wall) => boolean) => + Math.max(0, ...walls.filter((w) => (w.roomLeft === room.id || w.roomRight === room.id) && onSide(w)).map((w) => (w.roomLeft === room.id ? w.left : w.right))); + const near = (a: number, b: number) => Math.abs(a - b) < 1e-3; + const along = (w: Wall, axis: 0 | 1, v: number) => near(w.a[axis], v) && near(w.b[axis], v); + const width = x1 - x0 - into((w) => along(w, 0, x0)) - into((w) => along(w, 0, x1)); + const depth = z1 - z0 - into((w) => along(w, 1, z0)) - into((w) => along(w, 1, z1)); + return [Math.round(width * 1000) / 1000, Math.round(depth * 1000) / 1000]; +} diff --git a/frontend/src/hardware.ts b/frontend/src/hardware.ts new file mode 100644 index 0000000..d6e9e91 --- /dev/null +++ b/frontend/src/hardware.ts @@ -0,0 +1,9 @@ +// What the device can do, for features that would overload a weak wall tablet. + +/** A weak device: little memory, few cores, or an Amazon Fire tablet (Silk browser, KF… models). */ +export function isLowEnd(): boolean { + const nav = navigator as Navigator & { deviceMemory?: number }; + const mem = nav.deviceMemory ?? 8; + const cores = navigator.hardwareConcurrency || 8; + return mem <= 3 || cores <= 4 || /Silk|KF[A-Z]{2,4}\b/.test(navigator.userAgent); +} diff --git a/frontend/src/heatmap.test.ts b/frontend/src/heatmap.test.ts new file mode 100644 index 0000000..407e164 --- /dev/null +++ b/frontend/src/heatmap.test.ts @@ -0,0 +1,79 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, entity, floorWith, hassOf } from "./entities/fixtures.ts"; +import { HEAT_SCALES, heatColor, heatGradient, roomPower, roomValues, type HeatColorMode } from "./heatmap.ts"; +import { emptyBuilding } from "./model.ts"; + +const modes = Object.keys(HEAT_SCALES) as HeatColorMode[]; + +test("values below the first stop and above the last one keep the end colours", () => { + for (const mode of modes) { + const { stops } = HEAT_SCALES[mode]; + assert.deepEqual(heatColor(mode, stops[0][0] - 100), stops[0][1]); + assert.deepEqual(heatColor(mode, stops[stops.length - 1][0] + 100), stops[stops.length - 1][1]); + } +}); + +test("a stop value gives exactly its colour, the middle between two stops the average", () => { + for (const mode of modes) { + const { stops } = HEAT_SCALES[mode]; + stops.forEach(([value, colour]) => heatColor(mode, value).forEach((c, i) => assert.ok(Math.abs(c - colour[i]) < 1e-9))); + const [[v0, c0], [v1, c1]] = stops; + heatColor(mode, (v0 + v1) / 2).forEach((c, i) => assert.ok(Math.abs(c - (c0[i] + c1[i]) / 2) < 1e-9)); + } +}); + +test("the stops of every scale rise strictly, so no division by zero can happen", () => { + for (const mode of modes) { + const values = HEAT_SCALES[mode].stops.map(([v]) => v); + values.slice(1).forEach((v, i) => assert.ok(v > values[i], `${mode} at ${v}`)); + } +}); + +test("warm temperatures are redder than cold ones", () => { + const cold = heatColor("temperature", 15); + const hot = heatColor("temperature", 30); + assert.ok(hot[0] > cold[0] && hot[2] < cold[2]); +}); + +test("the gradient lists every stop, from 0 % to 100 %", () => { + for (const mode of modes) { + const css = heatGradient(mode); + assert.ok(css.startsWith("linear-gradient(90deg, rgb(")); + assert.equal(css.match(/rgb\(/g)?.length, HEAT_SCALES[mode].stops.length); + assert.ok(css.includes(" 0%") && css.endsWith(" 100%)")); + } +}); + +test("a room's power adds up the power sensors of its pins and furniture, the house's meters left out", () => { + const hass = hassOf([ + entity("sensor.tv_power", "120", { device_class: "power", unit_of_measurement: "W" }), + entity("sensor.heater", "1.5", { device_class: "power", unit_of_measurement: "kW" }), + entity("sensor.grid", "900", { device_class: "power", unit_of_measurement: "W" }), + ]); + const room = box("w", 0, 0, 5, 4); + const floor = { + ...floorWith([room]), + placements: [ + { entity_id: "sensor.heater", x: 1, z: 1, y: null, mount: null }, + { entity_id: "sensor.grid", x: 2, z: 1, y: null, mount: null }, + { entity_id: "sensor.tv_power", x: 9, z: 9, y: null, mount: null }, + ], + furniture: [{ id: "tv", type: "tv", x: 3, z: 3, rotation: 0, w: 1, d: 0.1, h: 0.6, variant: null, power: "sensor.tv_power" }], + }; + const b = { ...emptyBuilding(), floors: [floor] }; + b.energy = { ...b.energy, grid: "sensor.grid" }; + assert.equal(roomPower(hass, b, floor, room), 1620); + assert.equal(roomValues(hass, b, "power").get("w"), 1620); + assert.equal(roomPower(hass, b, floor, box("empty", 20, 20, 22, 22)), null); +}); + +test("a socket's smart plug counts in its room's power", () => { + const hass = hassOf( + [entity("switch.plug", "on"), entity("sensor.plug_power", "45", { device_class: "power", unit_of_measurement: "W" })], + { "switch.plug": { device_id: "p" }, "sensor.plug_power": { device_id: "p" } }, + ); + const room = box("w", 0, 0, 5, 4); + const floor = { ...floorWith([room]), furniture: [{ id: "s", type: "pack:nextfloor.switches:socket_1", x: 1, z: 1, rotation: 0, w: 0.08, d: 0.02, h: 0.08, variant: null, gang_entities: ["switch.plug"] }] }; + assert.equal(roomPower(hass, emptyBuilding(), floor, room), 45); +}); diff --git a/frontend/src/heatmap.ts b/frontend/src/heatmap.ts new file mode 100644 index 0000000..6c66352 --- /dev/null +++ b/frontend/src/heatmap.ts @@ -0,0 +1,163 @@ +// Heat map: the floor of a room is coloured by what its sensors say (temperature, humidity, CO₂), or by the power its devices draw. + +import { roomClimateValue } from "./devices.ts"; +import { powerSensorFor, readPower } from "./energy.ts"; +import { roomSun } from "./live/sun-hours.ts"; +import { comfortScore, isSummer, mouldRisk } from "./live/room-climate.ts"; +import { pointInPolygon, type Building, type Floor, type Room } from "./model.ts"; +import type { HomeAssistant } from "./types.ts"; + +export type HeatMode = "none" | "temperature" | "humidity" | "co2" | "mould" | "comfort" | "power" | "sun" | "values" | "wifi"; + +/** The modes that paint floors ("values" prints numbers at the room names instead). */ +export type HeatColorMode = Exclude; + +type Rgb = [number, number, number]; +type Stop = readonly [value: number, colour: Rgb]; + +interface Scale { + deviceClass: string; + unit: string; + stops: Stop[]; +} + +/** Colour ramps, from low to high. Between two stops the colour is blended; outside the range it stays at the end. */ +export const HEAT_SCALES: Record = { + temperature: { + deviceClass: "temperature", + unit: "°C", + stops: [[16, [0.2, 0.45, 1]], [20, [0.15, 0.85, 0.75]], [22.5, [0.95, 0.8, 0.3]], [26, [1, 0.28, 0.18]]], + }, + humidity: { + deviceClass: "humidity", + unit: "%", + stops: [[30, [0.95, 0.6, 0.2]], [45, [0.3, 0.88, 0.5]], [60, [0.2, 0.78, 1]], [75, [0.32, 0.4, 0.98]]], + }, + co2: { + deviceClass: "carbon_dioxide", + unit: "ppm", + stops: [[450, [0.3, 0.88, 0.5]], [800, [0.98, 0.84, 0.3]], [1200, [1, 0.5, 0.2]], [1600, [0.98, 0.25, 0.25]]], + }, + // mould risk at the coldest wall, from temperature and humidity (live/room-climate.ts) + mould: { + deviceClass: "", + unit: "%", + stops: [[0, [0.3, 0.88, 0.5]], [40, [0.98, 0.84, 0.3]], [70, [1, 0.5, 0.2]], [100, [0.75, 0.2, 0.55]]], + }, + // how comfortable the room is, 0 … 100 (live/room-climate.ts) + comfort: { + deviceClass: "", + unit: "", + stops: [[0, [0.98, 0.25, 0.25]], [40, [1, 0.5, 0.2]], [65, [0.98, 0.84, 0.3]], [85, [0.3, 0.88, 0.5]], [100, [0.2, 0.8, 0.7]]], + }, + // what the room's devices draw now (their power sensors added up) + power: { + deviceClass: "power", + unit: "W", + stops: [[0, [0.25, 0.4, 0.6]], [100, [0.3, 0.88, 0.5]], [500, [0.98, 0.84, 0.3]], [1500, [1, 0.5, 0.2]], [3000, [0.98, 0.25, 0.25]]], + }, + // hours of sun through the room's outside windows today (live/sun-hours.ts) + sun: { + deviceClass: "", + unit: "h", + stops: [[0, [0.22, 0.3, 0.55]], [2, [0.35, 0.6, 0.85]], [4, [0.98, 0.84, 0.3]], [7, [1, 0.62, 0.2]], [10, [1, 0.42, 0.25]]], + }, +}; + +/** Summer's temperature scale: rooms count as hot later than in winter (26 °C is fine in July, not in January). */ +const SUMMER_TEMPERATURE: Scale = { + deviceClass: "temperature", + unit: "°C", + stops: [[19, [0.2, 0.45, 1]], [22.5, [0.15, 0.85, 0.75]], [25.5, [0.95, 0.8, 0.3]], [29, [1, 0.28, 0.18]]], +}; + +/** The scale of a mode in a season (only temperatures change with it). */ +export function scaleOf(mode: HeatColorMode, summer = false): Scale { + return mode === "temperature" && summer ? SUMMER_TEMPERATURE : HEAT_SCALES[mode]; +} + +const mix = (a: Rgb, b: Rgb, t: number): Rgb => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; + +/** The colour a value gets on a scale. */ +export function heatColor(mode: HeatColorMode, value: number, summer = false): Rgb { + const { stops } = scaleOf(mode, summer); + const upper = stops.findIndex(([limit]) => value <= limit); + if (upper === -1) return stops[stops.length - 1][1]; + if (upper === 0) return stops[0][1]; + const [lowValue, lowColour] = stops[upper - 1]; + const [highValue, highColour] = stops[upper]; + return mix(lowColour, highColour, (value - lowValue) / (highValue - lowValue)); +} + +/** + * What the devices of a room draw now, in watts: the power sensors of its device pins and of its furniture (a piece's own power + * sensor, else the one on its entity's device), each counted once. Null when the room has none. The house's meters stay out. + */ +export function roomPower(hass: HomeAssistant, building: Pick, floor: Floor, room: Room): number | null { + let sum: number | null = null; + for (const s of roomPowerSensors(hass, building, floor, room)) { + const w = readPower(hass.states[s]); + if (w !== null) sum = (sum ?? 0) + Math.max(0, w); + } + return sum; +} + +/** The power sensors of a room's device pins and furniture, each once, without the house's meters. */ +export function roomPowerSensors(hass: HomeAssistant, building: Pick, floor: Floor, room: Room): string[] { + const { grid, solar, battery } = building.energy; + const meters = new Set([grid, solar, battery].filter(Boolean)); + const sensors = new Set(); + const inside = (x: number, z: number) => room.points.length >= 3 && pointInPolygon([x, z], room.points); + for (const p of floor.placements) { + const s = inside(p.x, p.z) ? powerSensorFor(hass, p.entity_id) : null; + if (s) sensors.add(s); + } + for (const m of floor.furniture) { + if (!inside(m.x, m.z)) continue; + const s = m.power && m.power !== "none" ? m.power : m.entity && m.entity !== "none" ? powerSensorFor(hass, m.entity) : null; + if (s) sensors.add(s); + // a switch plate or socket: the power sensors on the devices of its buttons (a smart plug, a measuring switch) + for (const g of m.gang_entities ?? []) { + const gs = g && g !== "none" ? powerSensorFor(hass, g) : null; + if (gs) sensors.add(gs); + } + } + return [...sensors].filter((s) => !meters.has(s)); +} + +/** The reading of every room that has a fitting sensor, by room id. */ +export function roomValues(hass: HomeAssistant, building: Building, mode: HeatColorMode): Map { + const values = new Map(); + for (const floor of building.floors) { + for (const room of floor.rooms) { + if (mode === "power") { + const w = roomPower(hass, building, floor, room); + if (w !== null) values.set(room.id, w); + continue; + } + if (mode === "comfort") { + const v = comfortScore(roomClimateValue(hass, floor, room, "temperature"), roomClimateValue(hass, floor, room, "humidity"), roomClimateValue(hass, floor, room, "co2"), isSummer(new Date(), hass.config?.latitude)); + if (v !== null) values.set(room.id, v); + continue; + } + if (mode === "sun") { + const { latitude, longitude, time_zone } = hass.config ?? {}; + if (latitude === undefined || longitude === undefined || floor.layer) continue; + values.set(room.id, roomSun(building, floor, room, { latitude, longitude, zone: time_zone }).hours); + continue; + } + const reading = mode === "mould" ? mouldRisk(roomClimateValue(hass, floor, room, "temperature"), roomClimateValue(hass, floor, room, "humidity")) : roomClimateValue(hass, floor, room, mode); + if (reading !== null) values.set(room.id, reading); + } + } + return values; +} + +/** The scale as a CSS gradient, for the legend bar. */ +export function heatGradient(mode: HeatColorMode, summer = false): string { + const { stops } = scaleOf(mode, summer); + const first = stops[0][0]; + const span = stops[stops.length - 1][0] - first; + const parts = stops.map(([value, colour]) => `rgb(${colour.map((c) => Math.round(c * 255)).join(",")}) ${Math.round(((value - first) / span) * 100)}%`); + return `linear-gradient(90deg, ${parts.join(", ")})`; +} diff --git a/frontend/src/i18n.test.ts b/frontend/src/i18n.test.ts new file mode 100644 index 0000000..a3e5437 --- /dev/null +++ b/frontend/src/i18n.test.ts @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { test } from "node:test"; +import { awaitingLanguage, languageText, translate, type I18nKey } from "./i18n.ts"; +import type { HomeAssistant } from "./types.ts"; + +// Language files are community-maintained: a key a file lacks (a new text) stays English, and a key the +// built-in languages no longer have is ignored, so neither fails here. What a file does translate must +// keep the placeholders of the English text. + +const hass = (language: string) => ({ language }) as HomeAssistant; +const placeholders = (s: string) => [...s.matchAll(/\{[a-z0-9_]+\}/g)].map((m) => m[0]).sort(); +const langDir = new URL("../lang/", import.meta.url); +const codes = readdirSync(langDir) + .filter((f) => /^[a-z]{2}\.json$/.test(f)) + .map((f) => f.slice(0, 2)); +const file = (code: string) => JSON.parse(readFileSync(new URL(`${code}.json`, langDir), "utf8")) as Record; + +// pack, item and colour names are keyed by "packname:", "pack::" and "color:" +const isPackKey = (key: string) => /^(packname|pack|color):/.test(key); +function packKeys(): Set { + const dir = new URL("../../custom_components/nextfloor/packs/", import.meta.url); + const keys = new Set(); + for (const f of readdirSync(dir).filter((f) => f.endsWith(".json"))) { + const pack = JSON.parse(readFileSync(new URL(f, dir), "utf8")) as { id: string; items: { id: string; colors?: { id: string }[] }[] }; + keys.add(`packname:${pack.id}`); + for (const item of pack.items) { + keys.add(`pack:${pack.id}:${item.id}`); + for (const c of item.colors ?? []) keys.add(`color:${c.id}`); + } + } + return keys; +} +const isKnown = (key: string) => translate(hass("en"), key as I18nKey) !== key || translate(hass("de"), key as I18nKey) !== key; + +for (const code of codes) { + test(`lang/${code}.json keeps the placeholders of the English texts`, (t) => { + const packs = packKeys(); + const stale: string[] = []; + for (const [key, text] of Object.entries(file(code))) { + assert.ok(typeof text === "string" && text.trim(), `empty text for ${key}`); + if (isPackKey(key) ? !packs.has(key) : !isKnown(key)) { + stale.push(key); + continue; + } + if (isPackKey(key)) continue; + assert.deepEqual(placeholders(text), placeholders(translate(hass("en"), key as I18nKey)), `placeholders of ${key}`); + } + if (stale.length) t.diagnostic(`${stale.length} key(s) no longer used: ${stale.join(", ")}`); + }); +} + +test("German and English need no file", () => { + const element = { requestUpdate: () => assert.fail("nothing to wait for") }; + assert.equal(awaitingLanguage(hass("de-CH"), element), false); + assert.equal(awaitingLanguage(hass("en-GB"), element), false); +}); + +test("a language file is fetched once, used, and English fills its gaps", async () => { + (globalThis as { __NF_LANGS__?: Record }).__NF_LANGS__ = { xx: "abc" }; + const original = globalThis.fetch; + const urls: string[] = []; + globalThis.fetch = (async (url: URL) => { + urls.push(String(url)); + return new Response(JSON.stringify({ editor: "Éditeur", "color:white": "Blanc" })); + }) as typeof fetch; + try { + let updates = 0; + const element = { requestUpdate: () => void updates++ }; + assert.equal(awaitingLanguage(hass("xx-YY"), element), true); + assert.equal(awaitingLanguage(hass("xx"), element), true); + // English until the file is there + assert.equal(translate(hass("xx"), "editor"), translate(hass("en"), "editor")); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.equal(urls.length, 1); + assert.match(urls[0], /\/lang\/xx\.json\?v=abc$/); + assert.ok(updates >= 1); + assert.equal(awaitingLanguage(hass("xx"), element), false); + assert.equal(translate(hass("xx"), "editor"), "Éditeur"); + assert.equal(translate(hass("xx"), "all_floors"), translate(hass("en"), "all_floors")); + assert.equal(languageText("xx", "color:white"), "Blanc"); + assert.equal(languageText("en", "color:white"), undefined); + } finally { + globalThis.fetch = original; + delete (globalThis as { __NF_LANGS__?: unknown }).__NF_LANGS__; + } +}); + +test("a file that cannot be read leaves English", async () => { + (globalThis as { __NF_LANGS__?: Record }).__NF_LANGS__ = { zz: "abc" }; + const original = globalThis.fetch; + globalThis.fetch = (async () => new Response("", { status: 404 })) as typeof fetch; + try { + awaitingLanguage(hass("zz"), { requestUpdate: () => {} }); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.equal(awaitingLanguage(hass("zz"), { requestUpdate: () => {} }), false); + assert.equal(translate(hass("zz"), "editor"), translate(hass("en"), "editor")); + } finally { + globalThis.fetch = original; + delete (globalThis as { __NF_LANGS__?: unknown }).__NF_LANGS__; + } +}); diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts new file mode 100644 index 0000000..33e51c7 --- /dev/null +++ b/frontend/src/i18n.ts @@ -0,0 +1,4114 @@ +// UI strings. German first, English as fallback. + +import type { HomeAssistant } from "./types.ts"; + +const DE = { + view: "3D", + editor: "Editor", + all_floors: "Alle Etagen", + outside_area: "Außen", + outside_area_hint: "Alle Geräte draußen auf einen Blick: im Garten, außerhalb der Räume, und was zu Außen gehört (etwa die Wetterstation auf dem Dach).", + device_outside: "Gehört zu Außen", + device_outside_hint: "Das Gerät zählt nicht zum Raum darunter (eine Wetterstation auf dem Dach) und steht im Außen-Panel.", + no_building: "Noch kein Grundriss vorhanden.", + no_building_admin: "Noch kein Grundriss vorhanden. Im Editor zeichnest du deine erste Etage.", + no_rooms_admin: "Die Etagen sind angelegt, aber es gibt noch keinen Raum. Wände allein reichen nicht: Zeichne im Editor mit „Rechteck“ oder „Freie Form“ mindestens einen Raum.", + open_editor: "Editor öffnen", + loading: "Lädt …", + load_error: "Laden fehlgeschlagen", + saving: "Speichert …", + saved: "Gespeichert", + save_error: "Speichern fehlgeschlagen", + save_failed_detail: "Speichern fehlgeschlagen: {error}. Deine Änderungen bleiben in diesem Browser erhalten.", + needs_restart: "Eine neue Version von NextFloor ({frontend}) ist installiert, aber Home Assistant läuft noch mit {version}. Bitte Home Assistant neu starten – bis dahin kann das Speichern fehlschlagen.", + needs_reload: "Diese Seite zeigt noch NextFloor {frontend}, Home Assistant hat schon {backend}. Bitte die Seite neu laden; in der Companion-App: Einstellungen → Companion-App → Frontend-Cache zurücksetzen.", + reload_page: "Neu laden", + needs_restart_old: "Eine neue Version von NextFloor ist installiert, aber Home Assistant läuft noch mit einer älteren. Bitte Home Assistant neu starten – bis dahin schlägt das Speichern fehl.", + draft_found: "Nicht gespeicherte Änderungen vom {time} gefunden.", + draft_restore: "Übernehmen und speichern", + draft_discard: "Verwerfen", + walls_auto: "Wände hoch", + walls_cut: "Schnitt", + walls_slope: "Schräg", + walls_slope_hint: "Wände schräg abgeschnitten: vorne halbhoch, hinten voll – wie ein Puppenhaus, dreht mit der Kamera", + walls_solid: "Massiv", + walls_solid_hint: "Massive Wände in ihren Farben statt Glas (Farben: Editor → Einstellungen, pro Raum im Raum)", + wall_paint_outside: "Wandfarbe außen", + wall_paint_inside: "Wandfarbe innen", + furn_color_body: "Möbelfarbe Korpus", + furn_color_wood: "Möbelfarbe Holz", + furn_color_fabric: "Möbelfarbe Stoff", + furn_color_white: "Möbelfarbe Weiß", + furn_color_metal: "Möbelfarbe Metall", + furn_color_dark: "Möbelfarbe Dunkel", + furn_color_hint: "Die Möbel sind aus wenigen Materialien gebaut, auch die aus dem Möbelbauer und den Paketen. Hier bekommt jedes Material eine Farbe für das ganze Haus; eine Karte kann eigene Farben setzen. Am stärksten sieht man sie im Look Neon, Tag und Blaupause färben sie nur leicht.", + wall_paint_room: "Wandfarbe innen (dieser Raum)", + wall_paint_floor: "Wandfarbe außen (diese Etage)", + wall_paint_hint: "Gilt in der 3D-Ansicht „Massiv“.", + wall_paint_default: "Standard", + card_solid_walls: "Massive Wände (in ihren Farben)", + reset_view: "Übersicht", + back: "Zurück", + floor: "Etage", + floors: "Etagen", + add_floor: "Etage hinzufügen", + floor_from_ha: "Etagen aus Home Assistant:", + floor_empty: "Leere Etage", + level: "Ebene {n}", + ha_floor: "Etage in Home Assistant", + floor_layer: "Ebene (ein- und ausblendbar)", + floor_power: "Etagen-Zähler (Leistung)", + floor_power_hint: "Ein Leistungssensor nur für diese Etage (ein Unterzähler, eine Wohnung). Sein Wert steht auf dem Etagen-Schild und in der Ansicht dieser Etage auf der Haus-Karte, mit seinem Anteil am Verbrauch des Hauses.", + floor_power_share: "{n} % vom Haus", + living_area: "Wohnfläche {living}", + room_living: "Zählt zur Wohnfläche", + living_area_none: "Keine Wohnfläche · Grundfläche {floor}", + living_area_low: "Wohnfläche {living} (Grundfläche {floor}, davon {low} unter 2 m Höhe)", + living_area_hint: "Gerechnet wie die Wohnflächenverordnung: die Fläche innerhalb der Wände, voll ab 2 m lichter Höhe, zur Hälfte zwischen 1 und 2 m (unter Schrägen), unter 1 m gar nicht. Ein Richtwert, kein Aufmaß.", + living_area_floor: "Wohnfläche: {floor}", + living_area_floor_house: "Wohnfläche dieser Etage: {floor} · ganzes Haus: {house}", + print_plan: "Plan drucken / PDF", + print_plan_hint: "Jede Etage als sauberer Plan mit Maßen und Flächen, dazu eine Flächentabelle – zum Drucken oder im Druckdialog als PDF speichern.", + print_title: "Grundriss", + print_room: "Raum", + print_floor_area: "Grundfläche", + print_living: "Wohnfläche", + print_low: "unter 2 m", + print_total: "Summe", + print_blocked: "Das Druckfenster wurde blockiert – bitte Pop-ups für Home Assistant erlauben.", + check_open: "Plan prüfen", + note: "Notiz", + note_add: "Notiz hier", + note_text: "Text", + note_placeholder: "z. B. „Filter wechseln“ oder „Sicherung 12“", + note_due: "Fällig am", + note_height: "Höhe über dem Boden (m)", + note_height_hint: "Wo der Pin in der 3D-Ansicht schwebt: 1,3 m ist Augenhöhe, mehr für etwas unter der Decke (ein Absperrventil, eine Klappe).", + note_photo_upload: "Foto hinzufügen", + note_photo_hint: "Das Foto erscheint, wenn man die Notiz in der 3D-Ansicht antippt, z. B. wie das Ventil aussieht.", + note_due_hint: "Ab diesem Tag wird der Pin orange.", + note_is_due: "Diese Notiz ist fällig.", + keys_title: "Tasten im Editor", + keys_undo: "Rückgängig", + keys_redo: "Wiederholen", + keys_duplicate: "Raum verdoppeln", + keys_delete: "Auswahl löschen", + keys_nudge: "Auswahl um einen Rasterschritt verschieben", + keys_nudge_10: "… um 10 cm", + keys_nudge_1: "… um 1 cm", + keys_rotate: "Möbel um 90° drehen (Shift: zurück)", + keys_lock: "Möbel, Gerät oder Dachteil festsetzen / lösen", + keys_close_shape: "Freie Form schließen", + keys_escape: "Abbrechen, Werkzeug verlassen, Auswahl aufheben", + keys_straight: "Beim Zeichnen: gerade Linien", + keys_sheet: "Diese Übersicht", + tour_title: "Erste Schritte", + tour_1_title: "Räume zeichnen", + tour_1: "Mit „{rect}“ oder „{free}“ zeichnest du die Räume; die Wände entstehen von selbst. Ordne jedem Raum seinen Home-Assistant-Bereich zu – dann findet NextFloor seine Geräte. Hast du schon Bereiche, legt „{rooms}“ im Etagenformular sie auf einmal an.", + tour_2_title: "Türen und Fenster", + tour_2: "„{opening}“ setzt sie auf eine Wand. Verknüpfe ihren Kontakt oder Rollladen – in 3D gehen sie dann mit auf und zu, und offene Fenster melden sich.", + tour_3_title: "Möbel und Geräte", + tour_3: "„{furniture}“ öffnet die Bibliothek – oder baue eigene Stücke in der 🛠️ Möbel-Werkstatt. Wählst du einen Raum, stehen darunter die Geräte seines Bereichs zum Platzieren bereit; Lampen leuchten dann in der Farbe ihres Lichts.", + tour_4_title: "Ansehen und prüfen", + tour_4: "„{split}“ zeigt dein Haus beim Zeichnen; oben wechselst du in die 3D-Ansicht. „{check}“ listet, was noch fehlt – und mit ? siehst du jederzeit die Tasten.", + tour_next: "Weiter", + tour_back: "Zurück", + tour_done: "Los geht's", + tour_skip: "Überspringen", + check_open_hint: "Listet, was im Plan fehlt oder schief ist, mit einer Lösung per Tipp.", + check_title: "Plan-Prüfung", + check_all_good: "Alles in Ordnung – nichts gefunden.", + check_hint: "{n} Punkte gefunden. Blaue Knöpfe ändern den Plan (Rückgängig geht wie immer), die anderen zeigen die Stelle.", + check_room_no_area: "„{room}“ hat keinen Home-Assistant-Bereich: seine Geräte werden nicht gefunden.", + check_room_no_area_named: "„{room}“ hat keinen Bereich – der freie Bereich „{area}“ heißt genauso.", + check_areas_unplaced: "{n} Bereiche dieser Etage haben noch keinen Raum: {names}", + check_devices_unplaced: "„{room}“: {n} Geräte des Bereichs stehen noch nicht im Plan.", + check_rooms_overlap: "„{a}“ und „{b}“ liegen übereinander.", + check_opening_off_wall: "Eine Tür oder ein Fenster in „{room}“ sitzt auf keiner Wand.", + check_entity_missing: "{n} Geräte-Pins zeigen auf Entitäten, die Home Assistant nicht mehr kennt ({ids}).", + check_furniture_entity_missing: "Ein Möbel ist mit {id} verknüpft – die Entität gibt es nicht mehr.", + check_battery_low: "Batterie schwach: {name} ({level} %)", + battery_low_n: "Batterie schwach: {names}", + check_standby: "{name} zieht {w} W, obwohl aus – etwa {cost} im Jahr.", + check_fix_show: "Zeigen", + check_fix_ignore: "Ignorieren", + check_show_devices: "{n} Geräte ansehen", + check_ignore_all: "Alle {n} ignorieren", + check_reset_ignored: "{n} ignorierte Geräte wieder prüfen", + check_fix_set_area: "„{area}“ zuordnen", + check_fix_add_rooms: "Räume anlegen", + check_fix_place: "{n} setzen", + check_fix_remove: "{n} entfernen", + floor_layer_hint: "Diese Etage ist kein Geschoss, sondern eine Ebene – z. B. alle Bäume oder die Deko. Die 3D-Ansicht zeigt oben ein Auge, mit dem du sie auf jedem Gerät ein- und ausblendest.", + no_ha_floor: "– keine –", + area_rooms: "Räume aus HA-Bereichen anlegen ({n})", + area_rooms_hint: "Legt für jeden Bereich dieser Etage einen Raum an (4 × 3 m) – danach an die richtige Stelle ziehen und die Ecken anpassen", + floor_name: "Name", + elevation: "Höhe über Boden (m)", + floor_shift: "Etage verschieben (m)", + floor_shift_apply: "Verschieben", + floor_shift_hint: "Verschiebt alle Räume, Möbel, Geräte, Außenflächen, freien Wände und das Hintergrundbild dieser Etage um X und Z. Dachflächen bleiben liegen.", + height: "Raumhöhe (m)", + cut_height: "Schnitthöhe (m)", + delete_floor: "Etage löschen", + floor_copy: "Etage duplizieren", + floor_copy_hint: "Die Kopie kommt oben aufs Haus, mit allen Räumen, Wänden, Türen und Fenstern. Räume und Etage verlieren ihre Verknüpfung mit Home Assistant, Möbel ihre Entitäten; Energiegeräte bleiben auf der alten Etage.", + floor_copy_furniture: "Möbel mitnehmen", + floor_copy_devices: "Geräte-Pins mitnehmen", + floor_copy_devices_hint: "Dieselbe Entität steht dann auf beiden Etagen.", + floor_copy_outdoor: "Außenflächen mitnehmen", + floor_copy_make: "Kopie anlegen", + floor_copy_name: "{name} (Kopie)", + furn_to_floor: "Auf Etage verschieben", + furn_to_floor_hint: "Das Möbel wandert an dieselbe Stelle auf der gewählten Etage.", + delete_floor_confirm: "Etage „{name}“ mit allen Räumen löschen?", + move_up: "Nach oben", + move_down: "Nach unten", + default_floor: "Erdgeschoss", + new_floor: "Etage {n}", + tool_select: "Auswählen", + tool_rect: "Rechteck", + tool_polygon: "Freie Form", + undo: "Rückgängig", + redo: "Wiederholen", + fit: "Alles zeigen", + room: "Raum", + rooms: "Räume", + room_name: "Name", + area: "Bereich", + no_area: "Kein Bereich", + sub_area_add: "+ Bereich im Raum", + sub_area_hint: "Ein Teil des Raums mit eigenem Home-Assistant-Bereich, aber ohne eigene Wände – eine Leseecke, ein Regal, eine Küchenzeile im Wohnraum. Seine Geräte und Sensoren gehören zu diesem Raum.", + material: "Boden", + x: "X (m)", + z: "Y (m)", + width: "Breite (m)", + depth: "Tiefe (m)", + points: "Eckpunkte", + delete_point: "Punkt löschen", + duplicate: "Duplizieren", + delete: "Löschen", + new_room: "Raum {n}", + settings: "Einstellungen", + pendant_shape: "Form", + pendant_shade: "Schirm", + paint_colour: "Lackfarbe", + pendant_globe: "Kugel", + pendant_cone: "Kegel", + pendant_drum: "Trommel", + sofa_shape: "Form", + sofa_straight: "Gerade", + sofa_l: "L-Form (Spiegeln: andere Seite)", + sofa_u: "U-Form", + pkg_open: "Einrichten …", + pkg_hint: "Die Möbel kommen an die Wände des Raums; Leuchten verbinden sich mit den Lichtern des Bereichs. Danach einzeln anpassen – Strg+Z nimmt alles zurück.", + pkg_done: "{n} Möbel gesetzt – Strg+Z nimmt es zurück.", + pkg_kitchen_row: "Küchenzeile", + pkg_kitchen_row_desc: "Zeile an der Rückwand mit Kühlschrank, Backofen, Spüle, Spülmaschine und Herd, Oberschrank, Esstisch mit Pendelleuchte", + pkg_kitchen_l: "Küche in L-Form", + pkg_kitchen_l_desc: "Zeile hinten und links, Kochinsel mit Barhockern", + pkg_bath: "Bad", + pkg_bath_desc: "Waschtisch, WC, Badewanne, Waschmaschine, Einbauspot", + pkg_bedroom: "Schlafzimmer", + pkg_bedroom_desc: "Doppelbett mit zwei Nachttischen, Schrank, Kommode, Deckenleuchte", + pkg_living: "Wohnzimmer", + pkg_living_desc: "TV-Board, Sofa, Couchtisch, Teppich, Sessel, Regal, Stehlampe, Pflanze", + pkg_dining: "Esszimmer", + pkg_dining_desc: "Esstisch mit vier Stühlen, Sideboard, Pendelleuchte", + pkg_office: "Büro", + pkg_office_desc: "Schreibtisch mit Bürostuhl, zwei Regale, Deckenleuchte", + pkg_kids: "Kinderzimmer", + pkg_kids_desc: "Einzelbett, Schreibtisch, Regal, Teppich", + pkg_hall: "Flur", + pkg_hall_desc: "Garderobe, zwei Einbauspots", + spots_place: "Spots setzen", + spots_type: "Leuchte", + spots_cols: "Spalten (links–rechts)", + spots_rows: "Reihen (vorne–hinten)", + spots_add: "{n} Leuchten setzen", + spots_placed: "{n} Leuchten gesetzt.", + spots_hint: "Alle Leuchten folgen dem gewählten Licht (z. B. Spots an einem Dimmer). Einzeln verschieben und ein anderes Licht wählen geht danach wie bei jedem Möbel.", + cancel: "Abbrechen", + backup: "Sicherung", + backup_history: "Wiederherstellungspunkte", + share_view: "Ansicht teilen", + share_view_hint: "Speichert das Haus als kleine Datei, die in jedem Browser ohne Home Assistant aufgeht (über die Online-Demo von NextFloor) – zum Zeigen für Familie oder Planer. Ohne Geräte und Entitäten, wie eine Vorlage.", + share_view_title: "Unser Haus in NextFloor", + share_view_needs_js: "Diese Seite braucht JavaScript und eine Internetverbindung.", + share_view_file: "ansicht", + share_view_done: "Ansicht gespeichert – die Datei im Browser öffnen oder weitergeben.", + version_save: "Stand speichern …", + version_save_hint: "Hält den Plan unter einem Namen fest („vor dem Umbau“). Benannte Stände bleiben, wenn die automatischen Wiederherstellungspunkte gehen.", + version_name_prompt: "Name für diesen Stand (z. B. „vor dem Umbau“):", + version_saved: "Stand „{name}“ gespeichert.", + version_compare: "Vergleichen", + version_delete_confirm: "„{name}“ löschen?", + version_same: "Kein Unterschied zum Plan.", + version_diff_n: "{n} Unterschiede zum Plan, wie er jetzt ist:", + diff_floor_added: "Etage „{name}“ neu", + diff_floor_removed: "Etage „{name}“ entfernt", + diff_room_added: "Raum „{name}“ neu", + diff_room_removed: "Raum „{name}“ entfernt", + diff_room_renamed: "„{detail}“ heißt jetzt „{name}“", + diff_room_reshaped: "„{name}“ umgeformt ({detail} m²)", + diff_opening_added: "{name} neu ({detail})", + diff_opening_removed: "{name} entfernt ({detail})", + diff_furniture_added: "{name} neu", + diff_furniture_removed: "{name} entfernt", + diff_furniture_moved: "{name} verschoben oder geändert", + diff_device_added: "Gerät {name} gesetzt", + diff_device_removed: "Gerät {name} entfernt", + diff_device_moved: "Gerät {name} verschoben", + backup_none: "Noch keine. Beim Bearbeiten entsteht höchstens alle 10 Minuten ein Punkt.", + backup_summary: "{rooms} Räume, {furniture} Möbel", + backup_restore: "Wiederherstellen", + backup_restore_confirm: "Den Stand vom {time} wiederherstellen? Der jetzige Stand bleibt als Wiederherstellungspunkt erhalten.", + backup_restored: "Wiederhergestellt.", + backup_file: "Datei", + backup_export: "Exportieren", + backup_export_share: "Als Vorlage teilen", + backup_export_share_hint: "Ohne Bereiche, Geräte, Sensoren und Bilder – zum Weitergeben an andere.", + backup_import: "Importieren …", + backup_import_confirm: "Den ganzen Grundriss durch die Datei ersetzen? Der jetzige Stand bleibt als Wiederherstellungspunkt erhalten.", + backup_import_error: "Die Datei ist kein NextFloor-Plan ({error}).", + backup_imported: "Importiert.", + backup_hint: "Hintergrundbilder sind nicht in der Datei enthalten.", + backup_full: "Komplett-Backup", + backup_full_export: "Alles sichern (Plan, Bilder, Packs)", + backup_full_import: "Komplett-Backup wiederherstellen …", + backup_full_hint: "Eine Datei mit dem Plan, allen Hintergrund- und Bildschirmbildern und den installierten Packs. Beim Wiederherstellen wird jedes Pack erneut geprüft; der Lizenzschlüssel ist nicht enthalten.", + backup_full_confirm: "Plan, Bilder und Packs durch das Backup ersetzen? Der aktuelle Stand bleibt als Wiederherstellungspunkt erhalten.", + backup_full_not_backup: "Das ist kein Komplett-Backup von NextFloor.", + backup_full_restored: "Backup wiederhergestellt: {packs} Packs, {pictures} Bilder.", + backup_full_skipped: "Übersprungen (nicht lesbar): {packs}.", + export_name_full: "komplett", + device_confirm: "Vor dem Schalten nachfragen", + device_confirm_hint: "Beim Antippen in 3D, im Schnellmenü und im Raumfenster erscheint erst eine Rückfrage. Doppeltipp auf den Raum lässt dieses Gerät aus.", + cover_confirm_hint: "Auf, Zu und Positionen fragen im Schnellmenü und im Raumfenster erst nach, und Wischen über das Symbol bewegt den Rollladen nicht mehr (es dreht dann die Ansicht). Stopp fragt nie.", + blind_kind: "Art des Behangs", + blind_roller: "Rollladen außen", + blind_venetian: "Raffstore mit Lamellen", + blind_inside: "Rollo innen", + cover2_entity: "Zweiter Rollladen (rechte Hälfte)", + cover_my: "Lieblingsposition „My“ (%, 0 = keine)", + cover_my_go: "Zur Lieblingsposition ({p} %)", + blind_hint: "Ein Raffstore dreht seine Lamellen in 3D mit der Lamellenstellung des Rollladens; ein Rollo innen hängt hinter dem Glas. Ein breites Fenster kann für seine rechte Hälfte einen zweiten Rollladen haben. Die Lieblingsposition erscheint als „My“ im Schnellmenü: ein Rollladen mit Positionen fährt dorthin, ein Somfy-RTS-Motor ohne Rückmeldung fährt mit Stopp in seine eigene My-Stellung.", + confirm_switch: "{name} wirklich schalten?", + lock_confirm_unlock: "{name} wirklich aufschließen?", + gang_switch_one: "Schaltet", + furn_cover_entity: "Bewegt sich mit", + furn_cover_hint: "Vorhang, Leinwand, Markise oder Tor folgen dieser Cover-Entität (Rollladen, Vorhang, Markise, Tor) und fahren mit ihr. Ein Tipp öffnet ihr Menü (auf, Stopp, zu).", + furn_cover_inverted: "Laufrichtung umkehren", + furn_cover_inverted_hint: "Für eine Markise oder einen Vorhang, die im Plan genau andersherum fahren als in Wirklichkeit: ausgefahren zeigt dann eingefahren und umgekehrt.", + gang_switch: "Taste {n} schaltet", + gang_socket_one: "Steckdose an", + gang_socket: "Steckdose {n} an", + gang_switch_hint: "Eine Taste leuchtet, solange ihr Licht an ist (in seiner Farbe). Ein Tipp schaltet; bei mehreren Tasten fragt ein kleines Menü, welche. Dieselbe Entität darf an mehreren Schaltern sitzen.", + gang_socket_hint: "Eine Steckdose leuchtet grün, solange ihr Schalter an ist – heller, je mehr sie zieht. Ein Tipp schaltet; bei mehreren fragt ein kleines Menü, welche.", + lock_confirm_lock: "{name} abschließen?", + opening_lock: "Smart Lock", + opening_lock_hint: "Ein Tipp auf die Tür schließt ab oder auf (immer mit Rückfrage). Solange sie aufgeschlossen ist, leuchtet ihre Kante.", + split_handle_hint: "Ziehen: Breite von Plan und 3D-Ansicht", + wall_exterior: "Außenwand (m)", + wall_interior: "Innenwand (m)", + grid: "Raster (m)", + units: "Maße anzeigen in", + units_metric: "Meter", + units_imperial: "Fuß und Zoll", + units_hint: "Wie Längen und Flächen im Plan, in den Formularen und in der Wandansicht stehen. Eingaben bleiben in Metern.", + background: "Vorlage (Grundriss-Bild)", + background_upload: "Bild wählen …", + background_width: "Breite im Plan (m)", + background_opacity: "Deckkraft", + background_rotation: "Drehung (°)", + background_edit: "Verschieben, skalieren und drehen", + background_edit_done: "Fertig", + background_edit_hint: "Solange der Modus an ist: Bild ziehen verschiebt es, der Griff unten rechts zieht es größer oder kleiner. Erst das Bild an den Maßstab anpassen, dann drehen.", + background_remove: "Vorlage entfernen", + hint_select: "Raum antippen zum Auswählen · Ecken ziehen · „+“ auf einer Kante fügt einen Punkt ein · Pfeiltasten verschieben · Entf löscht · Strg+Z", + hint_rect: "Ziehen, um ein Rechteck zu zeichnen", + hint_polygon: "Punkte setzen · auf den ersten Punkt tippen oder Enter schließt · Esc bricht ab", + hint_empty: "Lege zuerst eine Etage an.", + area_m2: "{a} m²", + overlap_warning: "Räume überlappen sich – die Wände dort sind unvollständig.", + read_only: "Nur Administratoren können den Grundriss bearbeiten.", + side_failed: "Dieses Formular ließ sich nicht anzeigen ({error}). Der Grundriss bleibt bedienbar. Bitte melde den Text in einem GitHub-Issue.", + mat_wood: "Holz", + mat_oak: "Eiche", + mat_tiles: "Fliesen", + mat_carpet: "Teppich", + mat_stone: "Stein", + mat_concrete: "Beton", + card_name: "NextFloor", + card_description: "Deine Wohnung in 3D (Neon).", + stats: "{calls} Draw-Calls · {tris} Dreiecke", + stats_fps: "{fps} B/s (langsamstes Bild {ms} ms)", + stats_idle: "Ruhe (0 B/s)", + stats_busy_floors: "Etagen", + stats_busy_openings: "Türen/Fenster", + stats_busy_flash: "Blitz", + stats_busy_roof: "Dach", + stats_busy_flow: "Stromfluss", + stats_busy_effect: "Farbeffekt", + stats_busy_robot: "Roboter", + stats_busy_orbit: "Kamerafahrt", + stats_busy_tint: "Raumfarbe", + stats_low: "Stufe Tablet, Pixeldichte {r}", + stats_full: "volle Stufe, Pixeldichte {r}", + floors_apart: "Auseinander", + floors_stacked: "Gestapelt", + roof_keep: "Dach bleibt", + roof_keep_hint: "Das Dach bleibt beim Heranzoomen auf dem Haus, statt sich zu heben und auszublenden", + floor_rooms_one: "1 Raum", + floor_rooms: "{n} Räume", + quality: "Qualität", + quality_auto: "Auto", + quality_low: "Tablet", + quality_high: "Hoch", + state_on: "An", + state_off: "Aus", + state_open: "Offen", + state_closed: "Zu", + state_opening: "Öffnet", + state_closing: "Schließt", + state_playing: "Spielt", + state_paused: "Pause", + state_idle: "Bereit", + state_locked: "Verriegelt", + state_unlocked: "Entriegelt", + state_detected: "Erkannt", + state_clear: "Frei", + state_unavailable: "Nicht verfügbar", + state_heat: "Heizen", + state_cool: "Kühlen", + state_auto: "Automatik", + state_heat_cool: "Heizen/Kühlen", + state_dry: "Entfeuchten", + state_fan_only: "Lüften", + devices: "Geräte", + devices_none_area: "Verknüpfe den Raum mit einem Bereich, dann erscheinen dessen Geräte hier.", + devices_none: "Im Bereich gibt es keine passenden Geräte.", + devices_place_all_n: "Alle {n} platzieren …", + devices_place_all_confirm: "{n} Geräte auf einmal in den Raum setzen? (Strg+Z bzw. „Rückgängig“ nimmt alle in einem Schritt zurück.)", + devices_src_area: "Dieser Bereich", + devices_src_other: "Andere Bereiche", + devices_src_none: "Ohne Bereich", + panel_hide: "Im Raumfenster ausblenden", + panel_unhide: "Im Raumfenster wieder zeigen", + panel_state_hide: "Zustand im Raumfenster ausblenden (z. B. ein Rollladen, der nur „unbekannt“ meldet)", + panel_state_show: "Zustand im Raumfenster wieder zeigen", + devices_place: "Platzieren", + devices_remove: "Entfernen", + devices_hint: "Platzierte Geräte erscheinen in 3D. Im Plan lassen sie sich verschieben.", + panel_lights: "Licht", + panel_covers: "Rollläden", + panel_climate: "Heizung", + panel_media: "Medien", + panel_switches: "Schalter", + panel_sensors: "Sensoren", + panel_scenes: "Szenen & Skripte", + panel_announce: "📢 Durchsage", + announce_placeholder: "Eigene Nachricht …", + announce_send: "Sagen", + announce_sent: "Gesagt: „{message}“", + announce_failed: "Durchsage fehlgeschlagen: {error}", + announce_phrase_1: "Essen ist fertig!", + announce_phrase_2: "Zeit fürs Bett!", + announce_phrase_3: "Bitte runterkommen!", + announce_phrase_4: "Wir fahren gleich los!", + announce_phrase_5: "Der Hund muss raus!", + state_recording: "Nimmt auf", + state_streaming: "Streamt", + panel_all_off: "Alle aus", + readable: "Gut lesbar", + readable_hint: "Kräftigere Kontraste und größere Schrift – für Wandtablets und alle, die so besser lesen.", + plain: "Nur Grundriss", + plain_hint: "Zeigt nur Wände, Türen, Fenster und Treppen, ohne Möbel. Geräte und ihre Pins bleiben.", + right_back: "Rechtsklick = zurück", + right_back_hint: "Ein kurzer Rechtsklick in der 3D-Ansicht geht einen Schritt zurück: vom Raum zur Etage, von der Etage zum Haus (wie ein Doppeltipp auf leere Fläche). Ziehen mit der rechten Taste verschiebt weiter die Ansicht.", + stl: "3D-Druck (STL)", + stl_hint: "Speichert das Haus als STL-Datei (Wände, Böden, Möbel und Außenflächen aller Etagen) zum 3D-Drucken, im Maßstab 1:100 (ein Meter wird zu 10 mm). Fenster, Licht und Dach fehlen; ein Slicer repariert die Datei bei Bedarf.", + card_plain: "Nur Grundriss", + card_rooms: "Nur diese Räume", + card_rooms_hint: "Die Karte zeigt nur die angehakten Räume mit ihren Möbeln, Geräten, Türen und Fenstern (zum Beispiel für ein Tablet in der Küche). Nichts angehakt: der ganze Plan.", + card_templates: "Kartenvorlagen", + card_templates_hint: "Eine Dashboard-Karte einmal hier einrichten (mit den Einstellungen der Karte) und auf jedem Tablet nur noch den Namen angeben: `template: küche_tablet`. Änderungen hier erreichen alle Karten mit dieser Vorlage; was auf der Karte selbst steht, gilt vor der Vorlage.", + template_name: "Neue Vorlage (Name)", + template_add: "Vorlage anlegen", + template_reload: "Bildschirme mit dieser Vorlage neu laden", + template_reload_all: "Alle Bildschirme neu laden", + template_use: "Auf der Dashboard-Karte: `template: {name}`", + card_template: "Kartenvorlage", + card_template_none: "keine (nur diese Karte)", + card_readable: "Gut lesbar", + all_off_n: "Alles aus ({n})", + all_off_hint: "Schaltet Lichter, Schalter, Ventilatoren und Medien des Raums aus; zehn Sekunden lang lässt es sich rückgängig machen.", + all_off_done: "Alles aus.", + all_off_undo: "Rückgängig", + all_off_floor: "Alles aus im {floor} ({n} Geräte), zehn Sekunden lang rückgängig zu machen", + mood_save: "Stimmung speichern", + mood_save_hint: "Speichert, wie die Lampen des Raums gerade leuchten, als Stimmung – ein Tipp darauf stellt sie später wieder her, „→“ überträgt sie auf einen anderen Raum.", + mood_new: "Stimmung", + mood_set: "Stimmung einstellen", + mood_carry: "Auf einen anderen Raum übertragen", + panel_all_on: "Alle an", + view_options: "Ansicht: Qualität, Look, Symbole, FPS", + panel_all_open: "Alle auf", + panel_all_close: "Alle zu", + central: "Zentral: alle Lichter, Rollläden und Favoriten", + central_house: "Ganzes Haus", + central_lights: "Lichter", + central_covers: "Rollläden", + central_on: "An", + central_off: "Aus", + central_open: "Auf", + central_close: "Zu", + central_sure: "Sicher?", + central_favorites: "Favoriten", + central_no_favorites: "Noch keine Favoriten. Im Editor unter „Favoriten“ legst du Szenen, Skripte und Schalter fest.", + card_central: "Stern mit Zentral-Menü", + card_central_hint: "Alle Lichter und Rollläden der Etage oder des Hauses und die Favoriten aus dem Editor.", + favorites: "Favoriten", + favorites_hint: "Szenen, Skripte, Automationen, Tasten und Schalter für das Zentral-Menü (Stern) der 3D-Ansicht – Party, Anwesenheitssimulation, Verschattung, Bewässerung.", + favorites_add: "Favorit hinzufügen", + favorite_floor: "Auf welcher Etage dieser Favorit erscheint", + favorite_all_floors: "Alle Etagen", + outside_hidden: "Draußen: Geräte ausblenden", + outside_hidden_hint: "Geräte, die das Fenster „Draußen“ nicht zeigen soll (sie bleiben im Plan).", + outside_hidden_add: "Gerät ausblenden", + outside_view_hint: "Ansicht für „Draußen“: Dreh die 3D-Vorschau auf den Garten und übernimm sie. Beim Öffnen von „Draußen“ fliegt die Kamera dorthin.", + outside_view_set: "Diese Ansicht für Draußen", + outside_view_reset: "Ansicht für Draußen zurücksetzen", + room_facts: "Raumfenster: angezeigte Angaben", + room_fact_sun: "Sonnenstunden", + room_fact_comfort: "Komfort", + room_fact_air: "Lüftungshinweis", + room_fact_circuits: "Stromkreise", + background_handles_hint: "Das Bild hat jetzt Griffe wie ein Möbel: ziehen verschiebt es, die Ecke unten rechts skaliert, der runde Griff oben dreht (mit Umschalt in 15°-Schritten). Passt es, „Fertig“ tippen – dann liegt es fest.", + background_fixed_hint: "Das Bild liegt fest, du kannst darüber zeichnen. Zum Anpassen „Verschieben, skalieren und drehen“ tippen.", + bg_level: "Gerade ausrichten", + bg_level_cancel: "Ausrichten abbrechen", + bg_level_first: "Tippe auf den Anfang einer Wand im Bild, die gerade (waagerecht oder senkrecht) sein soll.", + bg_level_second: "Jetzt auf das Ende dieser Wand tippen – das Bild dreht sich passend.", + bg_ruler: "Maßstab mit Lineal", + bg_ruler_cancel: "Lineal abbrechen", + bg_ruler_first: "Tippe im Bild auf den Anfang einer Strecke, deren Länge du kennst – etwa eine bemaßte Wand.", + bg_ruler_second: "Jetzt auf das Ende der Strecke tippen.", + bg_ruler_length_hint: "Im Plan gemessen: {m} m. Gib die echte Länge ein, das Bild wird passend skaliert.", + bg_ruler_length: "Echte Länge (m)", + bg_ruler_apply: "Maßstab übernehmen", + thumbs_fold: "Etagenbilder zu Knöpfen einklappen", + thumbs_show: "Etagenbilder wieder zeigen", + room_start_view: "Ansicht als Start des Raums", + room_start_view_hint: "Tippst du den Raum in 3D an, fliegt die Kamera genau so hin, wie die 3D-Ansicht rechts gerade steht – Blickwinkel, Zoom und Bildausschnitt. Erst 3D daneben einschalten, den Raum drehen und heranzoomen, dann tippen.", + room_start_view_reset: "Startansicht des Raums entfernen (wieder von oben)", + room_start_view_need_pane: "Schalte zuerst „3D daneben“ ein und dreh und zoom den Raum so, wie er sich öffnen soll.", + floor_start_view: "Ansicht als Start der Etage", + floor_start_view_hint: "Diese Etage öffnet sich in 3D so, wie die 3D-Ansicht rechts gerade steht – etwa das Erdgeschoss von vorn und das Obergeschoss von hinten. Erst 3D daneben einschalten, drehen, dann tippen.", + floor_start_view_reset: "Startansicht der Etage entfernen (wieder wie das Haus)", + floor_start_view_need_pane: "Schalte zuerst „3D daneben“ ein und dreh die Etage so, wie sie sich öffnen soll.", + ambilight: "Leuchten hinter dem Fernseher (%)", + ambilight_hint: "Wie kräftig es hinter dem Fernseher leuchtet, solange er läuft. 0 schaltet es aus (zum Beispiel wenn du LED-Streifen am Fernseher hast), 100 ist die Standardstärke.", + sound_rings: "Klangringe (%)", + sound_rings_hint: "Wie groß die Ringe um den Lautsprecher werden, solange er spielt. 0 schaltet sie aus, Bild und Leuchten bleiben; 100 ist die Standardgröße. Die Größe folgt außerdem der Lautstärke des Lautsprechers: leiser heißt kleiner.", + glow_scale: "Leuchtstärke in 3D (%)", + light_effects: "Effektanimationen in 3D", + light_effects_hint: "Nur exakte HA-Effektnamen zuordnen. Ohne Zuordnung bleibt die HA-Farbe statisch. Ändert nichts in Home Assistant.", + light_effects_enabled: "Animationen für diese Leuchte erlauben", + light_effect_unmapped: "Nicht zugeordnet (statisch)", + light_effect_add: "Exakten Effektnamen hinzufügen", + light_effect_name_limit: "Der exakte Effektname muss 1 bis 255 Zeichen lang sein. Er wird nicht gekürzt.", + light_effect_count_limit: "Maximal 100 Zuordnungen. Entferne zuerst einen vorhandenen Eintrag.", + light_effect_exists: "Dieser Effektname ist bereits zugeordnet. Die vorhandene Zuordnung bleibt erhalten.", + light_animation_none: "Statisch", + light_animation_rainbow: "Regenbogen (ersetzt Farbe)", + light_animation_pulse: "Pulsieren (Intensität)", + light_animation_flicker: "Flackern (Intensität)", + glow_scale_hint: "Wie kräftig die Leuchte in 3D leuchtet: unter 100 % dämpft helle LED-Streifen, damit der Raum nicht überstrahlt; über 100 % lässt eine schwache Lampe stärker leuchten. Schaltet nichts in Home Assistant.", + vehicle_to_spot: "In Stellplatz umwandeln", + vehicle_to_spot_hint: "Ein Fahrzeug als einfaches Möbel steht immer da. Als Stellplatz erscheint es nur, wenn ein Sensor das Auto meldet, und dort verknüpfst du auch das Auto-Gerät (Ladestand, Reichweite, Schloss, Klima).", + as_furniture: "Als Möbel darstellen", + as_furniture_hint: "Ersetzt den Pin durch ein Möbel an derselben Stelle, das mit diesem Gerät verknüpft ist – etwa ein Lautsprecher für einen Media Player oder eine Leuchte für ein Licht. Strg+Z nimmt es zurück.", + as_furniture_pick: "Möbel wählen …", + as_device: "Wieder als Geräte-Pin", + as_device_hint: "Ersetzt das Möbel durch den einfachen Pin seines Geräts an derselben Stelle.", + presets: "Sender und Playlists (Klang)", + presets_hint: "Erscheinen im Schnellmenü jedes Lautsprechers unter „Abspielen“, neben den Quellen des Players. Für einen Echo (Alexa Media Player): Art SPOTIFY, AMAZON_MUSIC oder TUNEIN und als Inhalt, was du sagen würdest („Rock Antenne“). Für Sonos, Music Assistant und andere: Art music oder url mit einer Stream-Adresse oder einer URI.", + preset_type: "Art", + preset_type_hint: "media_content_type von play_media, z. B. music, url, playlist, SPOTIFY, AMAZON_MUSIC, TUNEIN", + preset_content: "Inhalt", + preset_content_hint: "media_content_id: Stream-URL, URI (spotify:playlist:…) oder bei Alexa ein Suchbegriff", + preset_speakers: "Nur auf diesen Lautsprechern (keiner = auf allen)", + media_play: "Abspielen", + media_pause: "Pause", + media_previous: "Zurück", + media_next: "Weiter", + media_volume: "Lautstärke", + media_sources: "Quellen", + preset_add: "Sender oder Playlist", + own_buttons: "Eigene Knöpfe", + own_buttons_hint: "Erscheinen im Zentral-Menü (Stern) unter den Favoriten: eine Dashboard-Seite öffnen, die Details einer Entität zeigen, einen Dienst aufrufen oder ein browser_mod-Popup mit deiner eigenen Karte öffnen.", + own_alerts: "Eigene Warnungen", + circuits: "Sicherungskasten", + circuits_hint: "Die Stromkreise mit den Räumen, die an ihnen hängen. Das Raum-Panel nennt sie, und die Suche findet sie („F12“).", + circuit_name: "Name", + circuit_new: "Neuer Stromkreis", + circuit_add: "Stromkreis hinzufügen", + circuit_add_room: "Raum hinzufügen", + own_alerts_hint: "Eine Zeile in der Warnleiste der 3D-Ansicht, solange eine Entität in einem Zustand ist – „Wassertank leer“ vom Saugroboter, „Spülmaschine fertig“. Mehrere Zustände mit Komma; bei Zahlen <20 oder >80.", + own_alert_entity: "Wenn …", + own_alert_state: "… im Zustand ist (leer = an)", + own_alert_text: "… dann diese Warnung", + own_alert_color: "Farbe", + own_alert_tap: "Antippen", + own_alert_tap_info: "öffnet die Details", + own_alert_tap_toggle: "schaltet die Entität", + own_alert_tap_room: "springt in den Raum", + own_alert_house: "Ganzes Haus", + own_alert_new: "Neue Warnung", + own_alert_add: "Warnung hinzufügen", + today: "Heute", + tomorrow: "Morgen", + today_days: "Tage auf der Karte „Heute“", + today_days_one: "Nur heute", + today_days_n: "{n} Tage", + forecast: "Wettervorhersage", + forecast_hint: "Eine kleine Karte mit den nächsten Tagen der Wetter-Entität (Einstellungen): Wetter, Höchst- und Tiefstwert, Regen. Sie steht in einer oberen Ecke der 3D-Ansicht, oben rechts unter der Karte „Heute“.", + forecast_days: "Vorhersage", + forecast_off: "Aus", + forecast_corner: "Ecke", + today_none: "Heute steht nichts an.", + today_calendars: "Kalender für „Heute“", + today_calendars_hint: "Die Termine dieser Kalender stehen oben rechts in der 3D-Ansicht auf der Karte „Heute“, zusammen mit den Mülltonnen, die heute oder morgen abgeholt werden. Ein Tipp auf den Titel klappt die Karte ein.", + own_button_state: "Leuchtet, solange … an ist (optional)", + own_button_label: "Beschriftung", + own_button_action: "Aktion", + own_button_new: "Neuer Knopf", + own_button_add: "Eigener Knopf", + own_action_navigate: "Seite öffnen", + own_action_more_info: "Details einer Entität", + own_action_service: "Dienst aufrufen", + own_action_fire_dom_event: "fire-dom-event (browser_mod)", + own_target_navigate: "Pfad", + own_target_more_info: "Entität", + own_target_service: "Dienst (domain.service)", + own_data: "Daten (JSON)", + own_data_hint: "Für einen Dienst seine Daten, für fire-dom-event der Inhalt des Ereignisses, z. B. {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}.", + own_data_bad: "Kein gültiges JSON-Objekt.", + panel_no_area: "Dieser Raum ist mit keinem Bereich verknüpft. Im Editor kannst du ihn verknüpfen.", + panel_empty: "Für diesen Raum sind keine Geräte im Grundriss. Im Editor lassen sich Geräte platzieren oder mit ☆ fürs Raumfenster auswählen.", + close: "Schließen", + panel_fold: "Einklappen (Raum bleibt sichtbar)", + panel_unfold: "Wieder aufklappen", + brightness: "Helligkeit", + color_temp: "Farbtemperatur", + color: "Farbe", + position: "Position", + cover_open: "Auf", + cover_stop: "Stopp", + cover_tilt: "Lamellen", + cover_tilt_open: "Lamellen auf", + cover_tilt_close: "Lamellen zu", + cover_close: "Zu", + target_temp: "Soll", + current_temp: "Ist", + temp_down: "Kälter", + temp_up: "Wärmer", + volume: "Lautstärke", + play_pause: "Wiedergabe/Pause", + previous: "Zurück", + next: "Weiter", + run: "Ausführen", + details: "Details", + hold_hint: "Antippen schaltet · lange drücken öffnet Details", + tool_opening: "Tür & Fenster", + tool_furniture: "Möbel", + qm_off: "Aus", + find: "Suchen", + find_placeholder: "Wo ist …? Gerät oder Raum", + find_none: "Nichts gefunden", + swipe_off: "Aus", + panel_pin: "Im Raumfenster zeigen", + panel_unpin: "Nicht im Raumfenster zeigen", + devices_panel_hint: "Das Raumfenster zeigt die Geräte im Grundriss. ☆ nimmt ein Gerät zusätzlich ins Raumfenster auf, ohne es zu platzieren.", + card_section_view: "Ansicht", + card_size: "Größe", + card_size_fixed: "Feste Höhe", + card_size_fill: "Bildschirm füllen", + card_fill_hint: "Am besten in einer Dashboard-Ansicht vom Typ „Panel (1 Karte)“ – dann nimmt die Karte den ganzen Platz ein.", + card_controls: "Schalter in der Karte", + card_floor_thumbs: "Etagen als Mini-Ansichten", + card_floor_thumbs_hint: "Kleine Bilder der Etagen am Rand – antippen wechselt die Etage", + card_floor_thumbs_hint_start: "Die gewählte Etage ist dann die Start-Etage – mit den Bildern am Rand wechselt man zu den anderen", + card_room_names: "Raumnamen anzeigen", + card_section_kiosk: "Wandtablet (Kiosk)", + card_section_features: "Funktionen", + card_weather_plan: "wie im Plan eingestellt", + card_pro_hint: "Bewegungsspur und Kamerawand gehören zum Kameras: Die Spur zeigt die letzte halbe Stunde, die Wand alle Kameras des Plans.", + card_idle_return: "Zurück zur Startansicht nach", + card_idle_off: "Nie", + card_idle_min: "{n} min ohne Bedienung", + card_idle_hint: "Nach der Wartezeit schließt die Karte den Raum und zeigt wieder die Startansicht.", + card_night: "Nachtdimmung", + card_night_off: "Aus", + card_night_sun: "Nach Sonnenstand", + card_night_time: "Zeitraum", + card_night_range: "Zeitraum (z. B. 22:00-06:00)", + card_idle_orbit: "Kamerafahrt als Bildschirmschoner", + card_idle_orbit_hint: "Nach der Rückkehr dreht sich die Ansicht langsam, bis jemand das Tablet berührt", + card_dashboard: "Knopf zu einem Dashboard (Pfad)", + card_dashboard_label: "Beschriftung des Knopfs", + card_dashboard_hint: "Ein Knopf oben rechts in der Karte öffnet das Dashboard oder die Ansicht mit diesem Pfad, z. B. /lovelace/home oder /dashboard-haus/0. Ohne Beschriftung zeigt er ⌂.", + card_alerts: "Warnungen anzeigen", + card_alerts_hint: "Rauch, Gas, CO, Wasser, Alarmanlage und offene Fenster bei Regen: der Raum pulsiert, oben erscheint ein Hinweis", + card_alert_jump: "Bei neuer Warnung zum Raum springen", + card_alert_jump_hint: "Die Ansicht wechselt selbst zur Etage und zum Raum der Warnung", + card_scenes: "Szenen-Knöpfe im Raum", + card_scenes_hint: "Szenen und Skripte des Bereichs als Knöpfe unter der 3D-Ansicht, wenn ein Raum gewählt ist", + card_sensor_bar: "Eigene Sensoren oben", + card_sensor_bar_hint: "Die im Editor gewählten Sensoren (Einstellungen) oben links auf der Karte", + card_central_open: "Sternmenü offen und groß", + card_central_open_hint: "Favoriten und eigene Knöpfe stehen von Anfang an offen, eine Nummer größer", + card_keep_camera: "Kamera beim Etagenwechsel behalten", + card_keep_camera_hint: "Gleiche Seite, Höhe und Entfernung auf jeder Etage", + card_today: "Karte „Heute“", + card_today_hint: "Termine von heute und fällige Mülltonnen oben rechts", + card_announcements: "Durchsagen", + card_announcements_hint: "Durchsagen (Aktion „NextFloor: Durchsage“) erscheinen groß auf der Karte, mit Gong und gesprochen", + weather_short: "Wetter", + time_of_day: "Tageszeit", + time_of_day_hint: "Zeigt Sonne, Licht, Schatten und Look zu einer anderen Uhrzeit von heute. Noch einmal tippen zeigt wieder das Jetzt.", + menu_open: "Menü offen", + menu_open_hint: "Das Sternmenü mit Favoriten und eigenen Knöpfen steht auf diesem Gerät von Anfang an offen, eine Nummer größer – für ein Wandtablet, das vor allem Szenen schaltet.", + keep_camera: "Kamera behalten", + keep_camera_hint: "Beim Wechsel der Etage bleibt die Kamera auf derselben Seite, Höhe und Entfernung, statt die neue Etage von der Startseite aus einzupassen.", + view_zoom: "Zoom", + view_zoom_hint: "Wie nah die eingepassten Ansichten kommen – auf kleinen Tablets wirkt das Haus größer.", + weather_entity: "Wetter-Entität", + weather_effects: "Wetter-Effekte in 3D", + card_weather_density: "Regen- und Schneemenge", + card_weather_density_hint: "Weniger Tropfen und Flocken als das Wetter meldet; Wolken, Nebel und Blitze bleiben", + weather_effect_rain: "Regen", + weather_effect_snow: "Schnee", + weather_effect_fog: "Nebel (graut die Szene ein)", + weather_effect_clouds: "Wolken dunkeln Himmel und Sonne ab", + weather_effect_lightning: "Blitze bei Gewitter", + weather_effect_sky: "Sonne und Mond am Himmel", + rain_warning: "Warnung: Fenster offen bei Regen", + sun_patches: "Sonnenlicht und Schatten", + sun_patches_hint: "Mit eingestellter Nordrichtung fällt das Sonnenlicht aus sun.sun als helle Flecken durch die Fenster auf den Boden, und das Haus wirft seinen Schatten auf das Grundstück. Ohne Haken bleiben Boden und Grundstück ohne Sonnenflecken und Schatten.", + sun_arc: "Sonnenbogen und Kompass", + sun_arc_hint: "Zeichnet den Weg der Sonne von heute als Bogen über das Grundstück, mit einem Ring und den Himmelsrichtungen am Boden (Norden rot). Braucht die Position deines Zuhauses in Home Assistant.", + weather_entity_hint: "Welche Wetter-Entität den Himmel ums Haus steuert. „Automatisch“ nimmt die erste gefundene.", + weather_hint: "Wetter am Haus: Regen und Schnee fallen mit dem echten Wind, Wolken ziehen mit Schatten übers Grundstück, Blitze, Nebel, Sonne und Mond", + card_weather: "Wetter draußen", + card_weather_hint: "Regen, Schnee, Hagel, Wolken mit Schatten, Blitze und Nebel aus der ersten Wetter-Entität (weather_entity wählt eine andere); auf Stufe Tablet weniger Teilchen", + alerts: "Warnungen", + alert_smoke: "Rauch: {name}", + alert_gas: "Gas: {name}", + alert_co: "Kohlenmonoxid: {name}", + alert_water: "Wasser: {name}", + alert_alarm: "Alarm ausgelöst", + alert_alarm_by: "Alarm ausgelöst durch {cause}", + alert_alarm_pending: "Alarm wird ausgelöst", + alert_window_rain: "Fenster offen bei Regen: {name}", + alert_power_outage: "Stromausfall: {name}", + alert_contact_lost: "Kontakt antwortet nicht: {name}", + rain_sensor: "Regensensor (eigene Wetterstation)", + rain_sensor_inverted: "Regensensor umkehren", + rain_sensor_inverted_hint: "Für Sensoren, die bei Regen „aus“ (oder 0) melden und bei Trockenheit „ein“.", + outage_sensor: "Sensor für Stromausfall", + outage_hint: "Ein Binärsensor der Klasse Strom, der aus ist, ein anderer Binärsensor, der an ist, ein Status wie „off_grid“ oder „backup“ oder eine Spannung unter 50 V lösen eine Warnung fürs ganze Haus aus.", + contact_warning: "Warnen, wenn ein Tür- oder Fensterkontakt nicht erreichbar ist", + contact_warning_hint: "Ist ein Kontakt 10 Minuten lang „nicht verfügbar“ (leere Batterie, außer Funkreichweite), sieht das Fenster in 3D geschlossen aus, obwohl es keiner weiß. Dann nennt ein Hinweis den Kontakt. Ein Neustart von Home Assistant warnt nicht.", + night_lock_warning: "Nachts warnen, wenn eine Tür nicht abgeschlossen ist", + night_lock_warning_hint: "Zwischen 22 und 6 Uhr nennt ein Hinweis die Türschlösser des Plans, die offen stehen.", + alert_unlocked_night: "Nicht abgeschlossen: {name}", + motion_markers_active: "Bewegungsmelder nur zeigen, wenn sie etwas erkennen", + motion_markers_active_hint: "Gilt für Bewegungs-, Anwesenheits- und Präsenzmelder. Ein Melder, dessen Symbol auf immer zeigen steht, bleibt sichtbar.", + room_double_tap: "Doppeltipp auf einen Raum", + room_double_tap_hint: "Ein Doppeltipp auf einen Raum schaltet seine Lichter aus, wenn eins an ist, sonst alle an. Geräte mit „Erst fragen“ bleiben immer außen vor.", + room_double_tap_area: "Lampen im Plan und alle Lichter des Bereichs", + room_double_tap_plan: "Nur Lampen im Plan", + room_double_tap_off: "Nichts schalten", + card_room_double_tap_auto: "Wie im Plan eingestellt", + status_entities: "Eigene Sensoren oben in der 3D-Ansicht", + status_add: "Sensor hinzufügen", + status_entities_hint: "Zum Beispiel Außentemperatur, Alarmanlage oder Luftqualität: Sie stehen oben links mit Name und Wert, auch in einem geöffneten Raum. Antippen öffnet die Details. Bis zu 12.", + announce_tts: "Text-zu-Sprache für Durchsagen", + announce_phrases: "Sätze für Durchsagen (einer pro Zeile)", + announce_phrases_hint: "Leer: die mitgelieferten Sätze. Durchsagen gibt es auch als Aktion „NextFloor: Durchsage“ für Automationen – auf den Lautsprechern der Räume und auf jedem offenen NextFloor-Bildschirm.", + opening_rain_warning: "Bei Regen warnen", + opening_light_well: "Lichtschacht davor", + sill_boards: "Fensterbank", + sill_boards_auto: "Automatisch", + sill_boards_none: "Keine", + sill_boards_inside: "Nur innen", + sill_boards_outside: "Nur außen", + room_names_short: "Raumnamen", + floor_stack_short_dim: "Abgedunkelt", + floor_stack_short_stacked: "Gestapelt", + floor_stack_short_single: "Einzeln", + size_short_w: "B", + size_short_d: "T", + size_short_h: "H", + import_error_not_json: "Die Datei ist kein JSON.", + import_error_not_plan: "Die Datei ist kein NextFloor-Plan.", + import_other_hint: "Aus Sweet Home 3D: die .sh3d-Datei hier importieren. Etagen, Räume, Türen, Fenster und freie Wände werden übernommen, Möbel nicht.", + import_sh3d_found: "Sweet Home 3D: {floors} Etagen, {rooms} Räume, {openings} Türen und Fenster, {walls} freie Wände ({furniture} Möbel werden nicht übernommen).", + import_dxf_found: "DXF: {rooms} Räume (geschlossene Polylinien) und {walls} freie Wände (Linien) auf einer Etage.", + import_ifc_found: "In der IFC-Datei: {floors} Etagen und {rooms} Räume (die Wände zeichnet NextFloor aus den Räumen).", + import_roomplan_found: "Raumscan (RoomPlan): {rooms} Räume, {openings} Türen und Fenster; {skipped} Objekte wurden nicht übernommen (Möbel stellst du selbst).", + import_error_roomplan_empty: "Im Raumscan sind keine Wände.", + import_error_ifc_empty: "In der IFC-Datei sind keine Räume (IfcSpace) mit Grundriss.", + import_error_dxf_empty: "In der DXF-Datei sind keine Linien oder Polylinien.", + import_error_sh3d: "Das ist keine Sweet-Home-3D-Datei, die sich lesen lässt (es braucht Sweet Home 3D 5.3 oder neuer).", + import_error_sh3d_empty: "In der Sweet-Home-3D-Datei sind keine Räume oder Wände.", + export_name_template: "vorlage", + export_name_backup: "sicherung", + card_floor_stack: "Etagen darunter", + floor_stack_dim: "Abgedunkelt", + floor_stack_stacked: "Gestapelt (ganzes Haus bis hier)", + floor_stack_single: "Ausgeblendet (nur diese Etage)", + card_control_walls: "Wände hoch/Schnitt", + card_control_floors: "Etagen auseinander", + card_control_temperature: "Temperatur", + card_control_humidity: "Feuchte", + card_control_co2: "CO₂", + card_controls_hint: "Wände hoch/Schnitt, Etagen auseinander und Temperatur, Feuchte, CO₂ zum Umschalten", + controls_hide: "Bedienelemente ausblenden – nur die 3D-Ansicht bleibt", + nav_wrap: "Leiste umbrechen: alle Etagen und Räume auf mehreren Zeilen", + bars_unfold: "Schalter", + nav_row: "Leiste in einer Zeile (seitlich scrollen)", + controls_show: "Bedienelemente wieder einblenden", + card_controls_hidden: "Mit ausgeblendeten Bedienelementen starten", + card_controls_hidden_hint: "Nur die 3D-Ansicht; ein Auge unten links holt Leisten, Werte und Schalter zurück", + card_controls_hide_after: "Bedienelemente ausblenden nach", + card_hide_after_s: "{n} s ohne Berührung", + card_fullscreen_button: "Vollbild-Taste", + card_fullscreen_button_hint: "Blendet das Dashboard drumherum aus (z. B. am Wandtablet)", + fullscreen: "Vollbild", + fullscreen_exit: "Vollbild beenden", + card_section_show: "Anzeigen", + card_floor: "Etage", + card_floor_house: "Ganzes Haus (Etage antippen zum Öffnen)", + card_height: "Höhe (Pixel)", + card_walls: "Wände", + card_quality_hint: "„Tablet“ ist die sparsamste Stufe – ideal für Fire-Tablets und andere Wandtablets.", + card_flows_switch: "Schalter in der Karte", + card_flows_on: "Immer an", + card_flows_off: "Immer aus", + holos: "Karten", + holos_hint: "Die Live-Karten über dem Haus (Energiebilanz, Auto, Medien) ein- oder ausblenden", + card_energy: "Energiewerte oben anzeigen", + card_room_panel: "Raum-Details beim Antippen", + card_room_buttons: "Raum-Knöpfe", + card_room_buttons_hint: "Eine Reihe mit einem Knopf je Raum oben in der Karte – antippen öffnet den Raum, wie das Antippen im Modell", + card_room_panel_hint: "Lichter und Rollläden des Raums in einem Seitenfenster", + card_explode: "Etagen in der Hausansicht auseinanderziehen", + card_roof_fade: "Dach beim Heranzoomen ausblenden", + card_roof_fade_hint: "Aus: Das Dach bleibt auf dem Haus, auch wenn die Kamera nah herankommt.", + card_stats: "Leistungsanzeige (Bilder pro Sekunde)", + card_stats_hint: "Zum Prüfen, wie flüssig die Karte auf dem Gerät läuft", + packs: "Möbel-Packs", + lib_badge_light: "Leuchte: lässt sich mit einem Licht verknüpfen und in 3D schalten", + lib_badge_electric: "Elektrisch: lässt sich mit Entität und Leistungssensor verknüpfen (schalten, Bild, Verbrauch)", + lib_badge_hint: "Möbel mit Symbol lassen sich mit Entitäten verknüpfen: Leuchten schalten, Bildschirme zeigen Bilder, Geräte ihren Verbrauch.", + care_bin_today: "Heute Abholung", + care_bin_tomorrow: "Morgen Abholung", + care_bin_days: "In {n} Tagen", + care_mail_yes: "Post ist da", + care_mail_no: "Leer", + care_plant_thirsty: "Durst", + care_plant_ok: "Gut versorgt", + care_time_left: "Noch {time}", + care_entity_bin: "Abholtermin (Sensor)", + care_entity_mail: "Post-Sensor", + care_entity_plant: "Bodenfeuchte (Sensor)", + care_thirsty_below: "Durst unter (%)", + care_hint_bin: "Ein Sensor mit dem nächsten Abholtermin: Tage, ein Datum, „heute“/„morgen“ oder die Integration Waste Collection Schedule. Am Tag davor und am Abholtag leuchtet die Tonne.", + care_hint_mail: "Ein Sensor, der meldet, dass Post im Kasten ist (z. B. ein Kontakt an der Klappe). Dann leuchtet der Briefkasten.", + care_hint_plant: "Ein Feuchtesensor in der Erde. Darunter leuchtet die Pflanze und meldet Durst.", + lib_cat_lights: "Leuchten", + lib_cat_seating: "Sitzen", + lib_cat_tables: "Tische", + lib_cat_storage: "Schränke & Regale", + lib_cat_beds: "Betten", + lib_cat_kitchen: "Küche", + lib_cat_appliances: "Haushaltsgeräte", + lib_cat_bath: "Bad", + lib_cat_media: "TV & Audio", + lib_cat_office: "Büro", + lib_cat_tech: "Technik", + lib_cat_climate: "Heizung & Klima", + lib_cat_energy: "Energie", + lib_cat_garden: "Garten & Terrasse", + lib_cat_plants: "Pflanzen", + lib_cat_kids: "Kinder", + lib_cat_fitness: "Fitness", + lib_cat_pets: "Haustiere", + lib_cat_workshop: "Werkstatt & Garage", + lib_cat_music: "Musik & Atelier", + lib_cat_season: "Saison & Deko", + lib_cat_pictures: "Bilder & Rahmen", + lib_cat_vehicles: "Fahrzeuge", + lib_cat_building: "Treppen & Bauteile", + lib_cat_decor: "Deko & Sonstiges", + lib_favourites: "Favoriten", + lib_recent: "Zuletzt benutzt", + lib_for_room: "Passend zu {room}", + lib_all_rooms: "Alle Räume zeigen", + lib_linkable: "verknüpfbar", + lib_lit: "leuchtet", + lib_outdoor: "draußen", + lib_fav_add: "Zu den Favoriten", + lib_fav_remove: "Aus den Favoriten nehmen", + lib_sizes: "Größen", + feature_name_energy: "Energiefluss", + ext_tab: "Erweiterungen", + ext_title: "Erweiterungen", + models: "Eigene 3D-Modelle", + models_hint: "Für manche Fahrzeuge kann NextFloor ein echtes 3D-Modell zeigen, wenn du eins besitzt. Wähle die Datei (.glb) hier aus: NextFloor dreht sie richtig herum, macht sie leichter, markiert den Lack und legt sie auf deinem Home Assistant ab. Ohne Modell sieht das Fahrzeug aus wie bisher.", + models_licence: "Die Dateien gehören dir und bleiben auf deinem Home Assistant. NextFloor liefert keine Modelle mit; bitte prüfe, dass die Lizenz deines Modells die Nutzung in deiner Installation erlaubt.", + model_add: "Modell hochladen …", + model_replace: "Modell ersetzen …", + model_remove: "Entfernen", + model_present: "vorhanden", + model_missing: "noch keins", + model_remove_confirm: "Das Modell „{id}“ von Home Assistant löschen?", + model_removed: "Modell „{id}“ gelöscht.", + model_uploaded: "Modell „{id}“ hochgeladen ({size}). Lade das Panel neu, damit es erscheint.", + model_upload: "Auf Home Assistant ablegen", + model_info: "{triangles} Dreiecke, {size} m", + model_front: "Vorderseite", + model_front_hint: "Drehe das Modell, bis die Front zum Betrachter zeigt (schräg nach unten links in der Vorschau).", + model_paint: "Lack (die Farbe, die du im Editor wählst)", + model_paint_preview: "Farbe in der Vorschau", + model_detail: "Detailgrad", + model_detail_light: "Leicht (Tablet)", + model_detail_normal: "Normal", + model_detail_fine: "Fein", + model_result: "Ergebnis: {triangles} Dreiecke, {size}", + model_error_not_glb: "Das ist keine .glb-Datei (binäres glTF). Exportiere das Modell als „glTF binary“.", + model_error_compressed: "Die Datei ist komprimiert (Draco, Meshopt oder KTX). Exportiere sie ohne Kompression.", + model_error_empty: "In der Datei ist nichts Dreidimensionales zu finden.", + model_error_unreadable: "Die Datei lässt sich nicht lesen: {detail}", + model_error_too_large: "Die Datei ist größer als {max}. Wähle einen geringeren Detailgrad.", + model_upload_forbidden: "Nur Administratoren dürfen Modelle hochladen.", + model_upload_too_large: "Home Assistant nimmt keine Dateien über {max} an. Wähle einen geringeren Detailgrad.", + model_upload_not_glb: "Home Assistant hat die Datei abgelehnt (kein binäres glTF).", + model_upload_bad_id: "Die Modell-Kennung ist ungültig.", + model_upload_other: "Das Hochladen hat nicht geklappt: {detail}", + ext_intro: "Hier importierst du eigene Möbel-Packs, lädst eigene 3D-Modelle hoch und bindest Plugins ein.", + plugin: "Plugin", + plugins_title: "Plugins", + plugins_intro: "Plugins erweitern NextFloor um eigene Licht-Animationen, Geräte und Karten im Raum-Panel. Trag die Adresse eines Plugins ein (eine .js-Datei in /config/www, also /local/…, aus HACS /hacsfiles/… oder https://…).", + plugins_docs: "Wie man ein Plugin schreibt", + plugins_warning: "Plugins laufen mit denselben Rechten wie NextFloor in deinem Browser. Nimm nur Plugins, deren Quelle du vertraust.", + plugins_off: "ausgeschaltet", + plugins_error: "Fehler", + plugins_loading: "wird geladen …", + plugins_nothing_registered: "geladen, hat aber nichts angemeldet", + plugins_loaded: "aktiv", + plugins_reload_hint: "Wirkt nach dem Neuladen der Seite", + plugins_remove: "Entfernen", + plugins_none: "Noch keine Plugins eingetragen.", + plugins_from_dashboard: "Über eine Dashboard-Ressource angemeldet", + plugins_add: "Hinzufügen", + plugins_url_invalid: "Bitte eine .js-Adresse unter /local/…, /hacsfiles/… oder https://… angeben.", + plugins_exists: "Dieses Plugin ist schon eingetragen.", + plugins_limit: "Höchstens 20 Plugins.", + packs_title: "Möbel-Packs", + packs_intro: "Eigene Möbel als Pack (JSON) importieren: als Datei oder unten einfügen. {n} Packs sind mitgeliefert und immer da.", + packs_docs: "Pack-Format", + packs_none: "Noch keine eigenen Packs importiert.", + community_title: "Community-Möbel", + community_intro: "Möbel, die andere mit dem Möbel-Baukasten gebaut und geteilt haben – geprüft und kostenlos. Bau deine eigenen:", + community_builder: "Möbel-Baukasten öffnen", + community_how: "So teilst du deine", + community_load: "Community-Möbel laden", + community_none: "Noch keine Community-Möbel – sei die oder der Erste!", + community_install: "Installieren", + community_update: "Aktualisieren", + community_installed: "Installiert", + community_failed: "Die Community-Möbel ließen sich nicht laden: {detail}", + pack_import: "Pack-Dateien importieren …", + pack_paste: "JSON importieren", + pack_paste_empty: "Füge zuerst das JSON eines Packs ein.", + pack_paste_not_json: "Das ist kein gültiges JSON: {detail}", + pack_imported: "„{name}“ von {publisher} importiert – {n} Möbel", + packs_imported_n: "{n} von {total} Packs importiert", + pack_by: "von {publisher} · {n} Möbel", + pack_remove: "Entfernen", + pack_remove_confirm: "Pack „{name}“ entfernen? Möbel daraus bleiben als einfache Kästen im Plan.", + pack_error_not_a_pack: "Das ist kein Möbel-Pack (es fehlt \"format\": \"nfpack\").", + pack_error_builtin: "Ein mitgeliefertes Pack hat schon diese ID.", + pack_error_invalid_content: "Das Pack enthält ungültige Möbel: {detail}", + pack_error_too_large: "Das Pack ist zu groß (höchstens 1 MB).", + pack_error_needs_update: "Dieses Pack braucht eine neuere Version von NextFloor. Bitte zuerst aktualisieren (HACS › NextFloor › ⋮ › „Informationen aktualisieren“ › „Herunterladen“), Home Assistant neu starten und dann noch einmal importieren.", + pack_error_other: "Import fehlgeschlagen: {detail}", + store_open: "Plugin-Store öffnen", + store_close: "Plugin-Store schließen", + store_intro: "Geprüfte Plugins aus der Community. Jedes wird vor der Aufnahme angesehen und danach nicht mehr verändert.", + store_submit: "Eigenes Plugin einreichen", + store_empty: "Noch keine Plugins im Store.", + store_failed: "Der Store ließ sich nicht laden ({error}).", + store_install: "Installieren", + store_installed: "installiert", + store_update: "Aktualisieren", + store_confirm: "„{name}“ von {author} installieren?\n\nEin Plugin läuft mit denselben Rechten wie NextFloor in deinem Browser. Die Datei wurde geprüft, ihr Inhalt ist festgelegt:\n{url}", + manual: "Anleitung", + manual_more: "Mehr erfahren", + feature_text_energy: "Energieteilchen fliegen in Bögen von den Solarfeldern zum Wechselrichter, zwischen Haus, Akku, Netz und Verbrauchern – schneller und dichter, je mehr Strom fließt. Die Module funkeln mit ihrer Produktion, eine Glaskarte über dem Dach zeigt die Bilanz und wie autark das Haus gerade ist.", + live_autarky: "autark", + live_fold: "Karte verkleinern", + live_unfold: "Karte aufklappen", + live_day_hint: "Die letzten 24 Stunden: Solar (Fläche) und Verbrauch (Linie)", + live_week_hint: "Die letzten 7 Tage: Sonne {solar} kWh, Verbrauch {use} kWh (gelb: Sonne, hell: Verbrauch)", + live_days: "Tage", + live_car_away: "Unterwegs", + live_car_charging: "Lädt", + live_car_plugged: "Eingesteckt", + live_car_lock: "Verriegeln", + live_car_unlock: "Entriegeln", + live_car_unlock_confirm: "{name} wirklich entriegeln?", + live_car_climate: "Klimatisierung", + live_car_charge: "Laden starten/stoppen", + live_media_prev: "Zurück", + live_media_playpause: "Abspielen/Pause", + live_media_next: "Weiter", + live_media_volume: "Lautstärke", + live_car_device: "Auto (eine Entität des Autos)", + live_car_device_hint: "Ladestand, Reichweite, Laden, Stecker, Schloss und Klima findet NextFloor selbst am Gerät des Autos. Ohne Angabe nimmt es den Anwesenheitssensor des Stellplatzes.", + live_car_departure_entity: "Abfahrtszeit (optional)", + live_car_departure: "Abfahrt {time}", + live_car_open: "Offen: {parts}", + printer_printing: "druckt", + printer_done: "fertig", + printer_paused: "pausiert", + printer_error: "Fehler", + printer_idle: "bereit", + printer_done_at: "fertig um {time}", + printer_layer: "Schicht", + printer_nozzle: "Düse", + printer_bed: "Bett", + heatpump_heating: "heizt", + heatpump_water: "macht Warmwasser", + heatpump_cooling: "kühlt", + heatpump_defrost: "taut ab", + heatpump_idle: "in Ruhe", + heatpump_flow_return: "Vor- → Rücklauf", + heatpump_heat: "Wärme", + heatpump_power: "Strom", + heatpump_outside: "außen", + pack_missing_item: "Möbel aus entferntem Pack", + back_to_room: "Zurück zu {room}", + back_to_floor: "Zurück zur Etage", + hint_furniture: "Raum antippen, dann rechts ein Möbelstück wählen · Möbel ziehen, an den Ecken die Größe ändern", + furniture_into: "Neue Möbel kommen in die Mitte von „{room}“.", + furniture_pick_room: "Tipp: Erst einen Raum antippen – dann landen neue Möbel in seiner Mitte.", + flows: "Stromfluss", + flows_hint: "Energiebögen zwischen Solarfeldern, Wechselrichter, Akku, Netz und Verbrauchern ein- oder ausblenden", + chk_title: "Einrichtung", + chk_hint: "Was der Energiefluss braucht. Antippen springt an die Stelle.", + chk_solar: "Solarfeld angelegt", + chk_solar_add: "Ein Solarfeld aufs Dach legen", + chk_meter: "Stromzähler mit Netzsensor", + chk_meter_sensor: "Stromzähler: Netzsensor (W) fehlt", + chk_meter_add: "Stromzähler anlegen", + chk_inverter: "Wechselrichter mit Leistungssensor", + chk_inverter_sensor: "Wechselrichter: Leistungssensor fehlt", + chk_inverter_add: "Wechselrichter anlegen", + chk_battery: "Stromspeicher mit Leistung und Ladestand", + chk_battery_sensor: "Stromspeicher: Leistung oder Ladestand fehlt", + chk_battery_opt: "Stromspeicher (optional)", + chk_grid: "Netzanschluss gesetzt", + chk_grid_opt: "Netzanschluss (optional, sonst automatisch)", + energy_sign_grid: "Das Haus zeigt Einspeisung, obwohl die Sonne nichts liefert. Der Netzsensor hat wahrscheinlich das umgekehrte Vorzeichen.", + energy_sign_battery: "Der Speicher lädt ohne Sonne und ohne Netzbezug. Sein Sensor hat wahrscheinlich das umgekehrte Vorzeichen.", + energy_sign_flip: "Vorzeichen umkehren", + help_title: "Hilfe und Rückmeldung", + help_hint: "Fehler bitte als Issue auf GitHub, Wünsche als Diskussion – so geht nichts verloren, und alle sehen den Stand.", + help_issue: "Problem melden", + help_idea: "Idee vorschlagen", + furn_name: "Name (optional)", + furn_mirror: "Spiegeln", + furn_mirror_hint: "Links und rechts vertauschen – das L-Sofa andersherum, der Schrank mit der Tür auf der anderen Seite, die Küchenzeile gespiegelt.", + hint_opening: "Auf eine Wand tippen, um eine Tür oder ein Fenster einzusetzen – die Art wählst du danach rechts", + preset_door: "Tür", + preset_door_double: "Doppeltür", + preset_window: "Fenster", + preset_window_double: "Fenster 2-flügelig", + preset_terrace: "Terrassentür", + preset_terrace_double: "Terrassentür 2-flügelig", + preset_lift_slide: "Hebe-Schiebetür", + preset_garage: "Garagentor", + preset_front: "Haustür", + opening_style: "Stil", + sidelight_auto: "automatisch", + sidelight_hinge: "Seitenteil an der Anschlagseite", + sidelight_hinge_hint: "Das Seitenteil sitzt sonst gegenüber dem Anschlag; mit Haken neben den Bändern.", + sidelight_width: "Breite Seitenteil (m)", + sidelight_width_left: "Seitenteil links (m)", + sidelight_width_right: "Seitenteil rechts (m)", + style_auto: "Automatisch ({style})", + style_interior: "Zimmertür", + style_front: "Haustür", + style_front_glass: "Haustür mit Glasausschnitt", + style_sidelight: "Haustür mit Seitenteil", + style_sidelights: "Haustür mit 2 Seitenteilen", + style_glass: "Glastür", + style_sliding: "Schiebetür", + style_passage: "Durchbruch (ohne Tür)", + style_standard: "Standard", + style_bars: "Mit Sprossen", + style_glass_wall: "Glaswand (feststehend)", + preset_glass_wall: "Glaswand", + glass_panes: "Glasfelder", + glass_panes_auto: "automatisch (ca. 0,9 m)", + glass_panes_hint: "0 = ein einziges Glas ohne Teilung, leer = Teilung etwa alle 0,9 m", + flip_hinge: "Anschlag wechseln", + flip_main_leaf: "Hauptflügel wechseln", + flip_hinge_hint: "Scharniere auf die andere Seite", + flip_swing: "Öffnungsrichtung umdrehen", + flip_swing_hint: "Die Tür schwenkt in den Raum oder zur anderen Seite", + main_leaf: "Hauptflügel (vom Raum aus)", + contact_main: "Kontakt Hauptflügel", + contact_second: "Kontakt zweiter Flügel", + tool_outdoor: "Außen", + tool_measure: "Nach Maß", + hint_measure: "Startpunkt antippen, dann rechts die Wandlängen mit Richtung eingeben", + measure: "Raum nach Maß", + measure_start: "Tippe im Plan auf den Startpunkt, z. B. eine Raumecke.", + measure_from: "Start bei {x} / {z} m – antippen verschiebt den Start.", + measure_length: "Länge der nächsten Wand (m)", + measure_close: "Raum schließen", + measure_undo: "Letzte Wand weg", + measure_gap: "Lücke zum Start: {gap} m (wird beim Schließen verbunden)", + measure_hint: "Tipp: Länge eintippen und Pfeiltaste drücken. Mit gemessenen Innenmaßen danach „Lücken schließen“.", + rect_by_size: "Rechteck nach Maß", + rect_add: "Rechteck anlegen", + dir_up: "Nach oben", + dir_down: "Nach unten", + dir_left: "Nach links", + dir_right: "Nach rechts", + hint_outdoor: "Ziehen, um eine Außenfläche (Rasen, Terrasse, Pool …) aufzuziehen", + outdoor: "Außenfläche", + outdoor_type: "Art", + outdoor_height: "Höhe (m)", + outdoor_offset: "Höhenversatz (m, − = tiefer)", + outdoor_opacity: "Deckkraft (%)", + 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_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_pool: "Pool", + out_bed: "Beet", + out_hedge: "Hecke", + out_fence: "Zaun", + out_wild: "Wildfläche", + out_pergola: "Pergola / Rahmen", + outdoor_open: "Offen (letzte Kante weglassen)", + outdoor_open_hint: "Die Kante vom letzten zum ersten Punkt wird nicht gezeichnet – ein Zaun oder eine Pergola, die ans Haus lehnt.", + fence_gates: "Tore im Zaun", + gate_add: "+ Tor im Zaun", + gate_edge: "Zaunseite", + gate_kind: "Art", + gate_single: "Gartentor", + gate_double: "Doppeltor", + gate_sliding: "Schiebetor", + gate_offset: "Mitte ab Zaunanfang (m)", + gate_width: "Breite (m)", + gate_entity: "Antrieb oder Schalter", + gate_contact: "Kontakt (an = offen)", + 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_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)", + pool_pump_on: "Pumpe läuft", + outdoor_slope: "Gefälle (m)", + outdoor_slope_hint: "Höhenunterschied von der hohen zur tiefen Kante; die hohe Kante liegt auf dem Höhenversatz. Leuchten auf der Fläche folgen.", + outdoor_slope_dir: "Fällt nach", + slope_x: "rechts (+X)", + slope_nx: "links (−X)", + slope_z: "unten (+Z)", + slope_nz: "oben (−Z)", + north: "Nordrichtung (° im Uhrzeigersinn von oben)", + north_hint: "Die Nordrichtung braucht der Sonnenstand (Licht durch die Fenster).", + map_on: "Echte Karte unter dem Plan anzeigen", + map_lat: "Breitengrad", + map_lon: "Längengrad", + map_use_ha: "Standort von Home Assistant übernehmen", + map_opacity: "Sichtbarkeit (%)", + map_zoom: "Detailstufe", + map_zoom_coarse: "grob", + map_zoom_fine: "fein", + map_move: "Karte unter dem Plan verschieben", + map_step: "Schritt", + map_url: "Eigene Kachel-Adresse (leer = OpenStreetMap)", + map_hint: "Dein Browser lädt die Kartenkacheln direkt vom Kartenserver (standardmäßig OpenStreetMap, bitte deren Nutzungsbedingungen beachten); solange die Karte aus ist, wird nichts geladen. Der Plan liegt auf der Karte, wie der Kompass es sagt – drehe den Kompass oder verschiebe die Karte, bis das Haus passt.", + compass_title: "Kompass", + compass_n_short: "N", + compass_s_short: "S", + compass_swap: "Nord ↔ Süd tauschen", + compass_swap_hint: "Dreht den Kompass um 180°. Zeichnung, Dachflächen und Solarfelder bleiben, wie sie sind.", + compass_hint: "Stimmt der Kompass nicht mit der Wirklichkeit überein, drehst du ihn hier – nichts muss neu gezeichnet werden. Sonnenlicht, Wind und die Himmelsrichtungen der Dachflächen richten sich danach.", + roof: "Dach", + roof_none: "Kein Dach", + roof_flat: "Flachdach", + roof_gable: "Satteldach", + roof_custom: "Dachflächen (frei)", + roof_sections: "Dachflächen", + roof_sections_hint: "Jede Dachfläche deckt ein Rechteck des Hauses ab, etwa das Wohnhaus, die Scheune oder einen Anbau – jede mit eigener Form, Firstrichtung, Traufhöhe und Neigung. Eine neue Fläche ziehst du im Plan auf; antippen wählt sie aus, ziehen verschiebt sie, die Ecken ändern die Größe.", + roof_sections_start: "Dachflächen aus den Räumen erzeugen", + roof_sections_regen: "Neu aus den Räumen erzeugen", + roof_sections_off: "Zurück zu einem Dach", + roof_regen_confirm: "Alle Dachflächen durch einen neuen Vorschlag aus den Räumen ersetzen?", + roof_section: "Dachfläche", + roof_section_hint: "Höhen zählen vom Boden. Eine Seite mit tieferer Traufe zieht weiter herunter (Abschleppdach); Pultdächer steigen von der ersten Seite an.", + roof_shape_gable: "Sattel", + roof_shape_hip: "Walm", + roof_shape_pent: "Pult", + roof_shape_flat: "Flach", + roof_shape_halfhip: "Krüppelwalm", + roof_shape_pyramid: "Zelt", + roof_shape_mansard: "Mansard", + roof_shape_parapet: "Attika", + roof_shape: "Form", + roof_end_start: "Ende am Firstanfang", + roof_end_end: "Ende am Firstende", + roof_halfhip: "Krüppelwalm beginnt bei", + roof_halfhip_hint: "Wie weit oben am Giebel die Walmfläche beginnt, als Anteil der Giebelhöhe: niedrig = ein großer Walm, hoch = nur die Spitze ist abgewalmt.", + roof_axis_x: "First ↔", + roof_axis_z: "First ↕", + roof_eave: "Traufe (m)", + roof_pitch_short: "Neigung (°)", + roof_height: "Höhe (m)", + roof_base: "Wandoberkante (m)", + roof_rotation: "Drehung (°)", + roof_on_floor: "Sitzt auf Etage", + roof_on_floor_hint: "Setzt den Abschnitt auf die Wandoberkante dieser Etage; Grundhöhe und Traufen wandern mit. In der 3D-Ansicht gehört das Dach zu dieser Etage.", + roof_base_hint: "Liegt sie unter der Deckenhöhe des Geschosses darunter, enden dessen Wände an der Dachunterseite: Kniestock an der Traufe, Giebel bis zum First, Innenwände an der Schräge. Im Grundriss zeigen gestrichelte Linien, wo 1,5 m und 2 m Kopfhöhe bleiben.", + roof_ridge_height: "Firsthöhe", + roof_side_top: "oben", + roof_side_bottom: "unten", + roof_side_left: "links", + roof_side_right: "rechts", + roof_swap: "Seiten tauschen", + roof_open: "Überdachung (Pfosten statt Wände, durchsichtig)", + roof_open_short: "Überdachung", + roof_dormer: "Gaube", + roof_dormer_hint: "Eine Gaube auf dieser Dachseite: 2 m breit, Front an der Traufwand, Traufe 1,4 m über der Dachtraufe, Satteldach. Danach verschieben, Breite und Höhen ändern wie bei jeder Dachfläche; die Hauptfläche öffnet sich darunter, die Wand des Dachgeschosses steigt bis zur Gaube – dort passt ein Fenster.", + roof_outline: "Umriss des Geschosses übernehmen", + roof_outline_hint: "Ein Flachdach als freie Form: übernimmt den Umriss der Räume des angezeigten Geschosses (auch L- oder Z-förmig) als eine Fläche ohne Kanten. Die Ecken lassen sich danach ziehen.", + roof_points_hint: "Freie Form: Ziehe die Ecken im Plan, ein + auf einer Kante fügt eine Ecke hinzu, × entfernt eine. Zurück zum Rechteck löscht die Form.", + roof_rect: "Zurück zum Rechteck", + roof_open_hint: "Für Terrassendach oder Carport: Statt Wänden tragen Pfosten und Balken das Dach, die Fläche ist durchsichtig. Wo die Überdachung an die Hauswand stößt, liegt sie auf der Wand auf.", + roof_swap_hint: "Dreht das Dach um: Die beiden Seiten tauschen Traufe und Neigung, ein Pultdach steigt in die andere Richtung.", + roof_pitch: "Dachneigung (°)", + roof_overhang: "Dachüberstand (m)", + roof_overhang_sides: "Überstand je Seite", + roof_overhang_a: "Überstand Traufe A (m)", + roof_overhang_b: "Überstand Traufe B (m)", + roof_overhang_u0: "Überstand Giebel vorn (m)", + roof_overhang_u1: "Überstand Giebel hinten (m)", + roof_overhang_auto: "Wieder automatisch", + roof_overhang_sides_hint: "Ohne eigene Werte ist der Überstand automatisch: überall gleich, außer wo der Dachteil ans Haus stößt (dort keiner).", + roof_ridge: "First", + roof_ridge_long: "Entlang der langen Seite", + roof_ridge_short: "Entlang der kurzen Seite (z. B. Reihenhaus)", + device: "Gerät", + lamp_mount: "Lampe", + lamp_ceiling: "Deckenleuchte", + lamp_floor: "Stehlampe", + lamp_table: "Tischlampe", + lamp_wall: "Wandleuchte", + marker_height: "Höhe des Symbols (m)", + height_auto: "Höhe automatisch", + device_centre: "In Raummitte", + lights_spread: "Deckenlampen gleichmäßig verteilen", + devices_search: "Geräte suchen …", + devices_more: "+{n} weitere", + devices_less: "weniger", + panel_more: "Weitere Geräte des Bereichs ({n})", + panel_less: "Weniger anzeigen", + gaps_close: "Lücken schließen", + gaps_hint: "Räume mit bis zu 60 cm Abstand an einer gemeinsamen Wand zusammenführen; der Abstand wird die Innenwandstärke.", + gaps_none: "Keine Lücken zwischen Räumen gefunden.", + gaps_closed: "{n} Stellen geschlossen.", + gaps_closed_wall: "{n} Stellen geschlossen, Innenwand jetzt {t} m.", + fps: "FPS", + fps_title: "Leistungsanzeige (Bilder pro Sekunde)", + hint_garage: "Auf eine Wand tippen, um ein Garagentor einzusetzen", + opening_garage: "Garagentor", + garage_hint: "Das Tor folgt einem Garagen-Cover (Position oder offen/zu) oder einem Garagentor-Kontakt aus dem Bereich des Raums.", + door_hint: "Mit Türkontakt schwenkt das Türblatt auf, ohne Sensor steht es halb offen.", + hint_door: "Auf eine Wand tippen, um eine Tür einzusetzen", + hint_window: "Auf eine Wand tippen, um ein Fenster einzusetzen", + opening_door: "Tür", + opening_window: "Fenster", + opening_type: "Art", + opening_position: "Mitte ab Ecke (m)", + sill: "Brüstung (m)", + opening_height: "Höhe (m)", + hinge: "Anschlag (vom Raum aus)", + hinge_left: "Links", + hinge_right: "Rechts", + cover_entity: "Rollladen", + door_cover: "Antrieb (Tür oder Tor mit Motor)", + cover_position_entity: "Positions-Sensor (live)", + cover_position_invert: "Sensor zählt umgekehrt (0 = offen)", + contact_entity: "Kontakt", + sensor_kind: "Sensor-Art", + sensor_kind_contact: "Fensterkontakt (offen/zu)", + sensor_kind_handle: "Griff-Sensor (offen/gekippt/zu)", + sensor_kind_contact_tilt: "Kontakt + Kipp-Sensor", + handle_entity: "Griff-Sensor", + handle_main: "Griff-Sensor Hauptflügel", + leaf_main: "Hauptflügel", + leaf_second: "Zweiter Flügel", + tilt_entity: "Kipp-Sensor", + tilt_angle_entity: "Kippwinkel-Sensor (°, optional)", + tilt_angle_max: "Winkel für „ganz gekippt“ (°)", + tilt_angle_offset: "Offset: Winkel bei geschlossenem Fenster (°)", + tilt_angle_invert: "Winkel zählt andersherum", + door_shut: "Ohne Sensor geschlossen zeigen", + door_shut_hint: "Eine Tür ohne Kontakt steht in 3D halb offen, damit man sie als Tür erkennt. Mit Haken wird sie geschlossen gezeichnet – Haustür, Carport, Nebentür.", + door_angle: "Öffnungswinkel", + door_angle_default: "Standard", + door_angle_hint: "Wie weit das Türblatt aufgeht. Mit Sensor öffnet es so weit, sobald er „offen“ meldet; ohne Sensor steht es so weit offen (statt halb). Standard bleibt wie bisher.", + entity_auto: "Automatisch ({name})", + entity_auto_none: "Automatisch (keiner gefunden)", + entity_none: "Keiner", + entity_search: "Tippen zum Suchen …", + opening_hint: "Sensor-Art: Fensterkontakt (meldet offen/zu), Griff-Sensor (meldet offen, gekippt und zu – z. B. Homematic-Fenstergriff) oder Kontakt + Kipp-Sensor (ein zweiter Sensor, der nur „gekippt“ meldet). Automatisch nimmt Rollläden und Kontakte aus dem Bereich des Raums. Positions-Sensor: eine Entität, die die Rollladen-Position auch während der Fahrt meldet (z. B. Homematic „Level“, 0–100 % oder 0–1, offen = hoch) – dann fährt der Rollladen in 3D live.", + furniture: "Möbel", + furniture_add: "Möbel hinzufügen", + studio_new: "Eigenes Möbel bauen", + studio_title: "Möbel-Werkstatt", + studio_title_edit: "Möbel-Werkstatt: ändern", + studio_hint: "Wähle eine Vorlage, stell Maße und Fronten ein und setz das Möbel in den Plan. Es landet im Pack „Eigene Möbel“ und lässt sich später hier wieder ändern.", + studio_kind: "Vorlage", + studio_kind_cabinet: "Schrank", + studio_kind_shelf: "Regal", + studio_kind_lamp: "Lampe", + studio_kind_device: "Gerät", + studio_name: "Name", + studio_width: "Breite (cm)", + studio_depth: "Tiefe (cm)", + studio_height: "Höhe (cm)", + studio_doors: "Türen", + studio_drawers: "Schubladen", + studio_shelves: "Böden", + studio_handle: "Griffe", + studio_handle_bar: "Stangengriff", + studio_handle_knob: "Knopf", + studio_handle_none: "Grifflos", + studio_base: "Unterbau", + studio_base_plinth: "Sockel", + studio_base_legs: "Füße", + studio_base_none: "Ohne", + studio_back: "Rückwand", + studio_lamp: "Art", + studio_lamp_floor: "Stehlampe", + studio_lamp_table: "Tischlampe", + studio_lamp_pendant: "Pendelleuchte", + studio_lamp_wall: "Wandleuchte", + studio_display: "Display vorne (zeigt den Mediaplayer)", + studio_mount: "Steht", + studio_mount_floor: "Auf dem Boden", + studio_mount_surface: "Auf einem Möbel", + studio_mount_wall: "An der Wand", + studio_color_body: "Korpus", + studio_color_lamp_body: "Fuß und Gestell", + studio_color_front: "Fronten", + studio_color_boards: "Böden", + studio_color_shade: "Schirm", + studio_color_display: "Rahmen des Displays", + studio_color_white: "Weiß", + studio_color_wood: "Holz", + studio_color_metal: "Metall", + studio_color_dark: "Dunkel", + studio_color_glass: "Glas", + studio_color_accent: "Akzent", + studio_color_own: "Eigene Farbe", + studio_color_plan: "Farbe des Plans", + studio_place: "In den Plan setzen", + studio_save: "Änderung speichern", + studio_open: "In der Werkstatt ändern", + studio_error: "Speichern ging nicht: {detail}", + studio_pack_name: "Eigene Möbel", + studio_pack_publisher: "Möbel-Werkstatt", + furniture_search: "Möbel suchen …", + furniture_search_none: "Nichts gefunden. Versuch ein anderes Wort – deutsch oder englisch.", + furniture_type: "Möbelstück", + rotation: "Drehung (°)", + tilt_x: "Neigung vorn/hinten (°)", + tilt_z: "Neigung seitlich (°)", + strip_tilt: "Neigung um die Länge (°)", + strip_upright: "Senkrecht", + strip_rise: "Steigung entlang der Länge (°)", + strip_upright_hint: "Der Streifen steht hochkant: Seine Länge läuft von der Höhe über Boden nach oben – am Türrahmen, als Lichtsäule. Die Neigung legt einen liegenden Streifen an die Schräge (90° = Fläche zeigt zur Seite).", + rotate_left: "↺ 90°", + rotate_right: "↻ 90°", + height_m: "Höhe (m)", + furn_sofa: "Sofa", + furn_armchair: "Sessel", + furn_table: "Tisch", + furn_chair: "Stuhl", + furn_bed: "Bett", + furn_nightstand: "Nachttisch", + furn_wardrobe: "Schrank", + furn_shelf: "Regal", + furn_kitchen: "Küchenzeile", + furn_worktop: "Arbeitsplatte", + furn_fridge: "Kühlschrank", + furn_fridge_smart: "Smart-Kühlschrank (Side-by-Side)", + furn_door_left: "Türsensor links (Gefrierseite)", + furn_door_right: "Türsensor rechts (Kühlseite)", + fridge_hint: "Meldet ein Türsensor „offen“, schwingt die Tür in 3D auf.", + furn_stove: "Herd", + furn_sink: "Spüle", + furn_bathtub: "Badewanne", + furn_shower: "Dusche", + furn_wc: "WC", + furn_washbasin: "Waschtisch", + furn_desk: "Schreibtisch", + furn_tv_board: "TV-Board", + furn_plant: "Pflanze", + furn_rug: "Teppich", + furn_stairs: "Treppe", + furn_stairwell: "Bodenöffnung", + stairwell_hint: "Ein Loch im Boden dieser Etage, zum Beispiel über dem Treppenaufgang oder für eine Galerie; von oben sieht man hindurch. Die Öffnung muss ganz in einem Raum liegen; mehrere Öffnungen dürfen sich überlappen (zum Beispiel für eine L-Form). Eine Treppe auf der Etage darunter, die bis hier hinauf reicht, öffnet den Boden auch von selbst.", + tool_hole: "Bodenöffnung", + tool_stairs: "Treppe", + hint_stairs: "Ziehen, wo die Treppe stehen soll – sie läuft entlang der langen Seite; Form, Drehrichtung und Bauart stellst du danach rechts ein", + tool_roof: "Dach", + tool_energy: "Energie", + tool_wall: "Wand", + hint_wall: "Ziehen, um eine einzelne Wand zu zeichnen (Raumteiler, halbe Wand) · Umschalt hält sie gerade · Alt ohne Fangen", + free_wall: "Wand", + wall_length: "Länge (m)", + wall_thickness: "Wandstärke (m)", + wall_height: "Höhe (m)", + wall_height_full: "Volle Raumhöhe", + wall_slope: "Schräg", + wall_slope_start: "Höhe am Anfang (m)", + wall_slope_end: "Höhe am Ende (m)", + wall_slope_hint: "Schräge Wand: die Oberkante läuft gerade von der Höhe am Anfang der Wand (Ecke mit der kleineren Nummer) zur Höhe am Ende. Beide Höhen dürfen über der Geschosshöhe liegen, zum Beispiel für ein Pultdach-Zimmer mit hohen Oberlichtern.", + wall_slope_off: "Wieder eine ebene Wand", + wall_none: "Keine Wand", + wall_none_hint: "Diese Wand ganz weglassen: für offene Grundrisse, bei denen Räume baulich ein Raum sind, in Home Assistant aber getrennt.", + edge_thickness: "Dicke (m)", + wall_thickness_hint: "Dicke dieser Wand, z. B. 0,365 an einer dicken Außenwand oder 0,115 an einer leichten Trennwand. Eine Wand zwischen zwei Räumen nimmt die dickere Angabe.", + wall_thickness_reset: "Dicke wie im Haus eingestellt", + wall_heights: "Wandhöhen", + wall_n: "Wand {a}–{b}", + wall_view: "Wandansicht", + wall_view_hint: "Die Wand von vorne: Türen, Fenster und Möbel an ihr ziehen oder ihren Abstand eintippen.", + wall_view_prev: "Vorige Wand", + wall_view_next: "Nächste Wand", + wall_view_left: "Abstand links (m)", + wall_view_height: "Höhe über Boden (m)", + wall_part: "Teil {n}", + wall_split_hint: "Wand hier teilen: Das Teilstück bekommt eine eigene Höhe, z. B. 2,5 m neben 1,7 m in einer Flucht", + wall_split_at: "Teilpunkt ab Ecke (m)", + wall_join_hint: "Teilpunkt entfernen: Das Teilstück wächst wieder mit dem davor zusammen", + wall_exterior_short: "Außenwand", + room_wall_hint: "Eine niedrigere Höhe macht aus der Wand eine Brüstung oder Theke. Teilen sich zwei Räume die Wand, gilt die niedrigere Einstellung. Fenster und Türen darin enden an der Wandhöhe.", + free_wall_hint: "Eine frei stehende Wand, zum Beispiel ein Raumteiler. Trifft sie auf eine Raumwand, wird die Ecke verschnitten. Die Endpunkte ziehst du an den Griffen, die ganze Wand verschiebst du an der Linie.", + free_wall_slope: "◢ Schräg", + free_wall_slope_hint: "Die Wand wird von einem Ende zum anderen höher oder niedriger: oben die Höhe am Anfang, hier die am Ende.", + free_wall_height_end: "Höhe am Ende (m)", + arc: "Bogen", + arc_hint: "Biegt die Wand zu einem Bogen. Ein Nachbarraum an dieser Wand biegt sich mit, Türen und Fenster wandern mit; Rückgängig nimmt den Bogen zurück.", + arc_bulge: "Wölbung (m)", + arc_bulge_hint: "Wie weit sich die Wand in der Mitte wölbt: positiv nach außen, negativ in den Raum.", + arc_apply: "Biegen", + arc_too_wide: "Eine Tür oder ein Fenster in dieser Wand ist für diesen Bogen zu breit. Mach den Bogen flacher oder die Öffnung schmaler.", + stairwell_outside: "Diese Öffnung ragt über eine Raumgrenze und wird deshalb nicht ausgeschnitten. Ziehe sie ganz in einen Raum oder verkleinere sie.", + hint_hole: "Ziehen, um eine Bodenöffnung aufzuziehen (Treppenaufgang, Galerie)", + hint_roof: "Dachfläche aufziehen · antippen wählt aus · ziehen verschiebt · Ecken ändern die Größe", + hint_energy: "Solarfeld antippen wählt aus · ziehen verschiebt, auch auf eine andere Dachfläche · neue Felder rechts mit + Solarfeld", + furn_parking: "Stellplatz", + furn_group_vehicles: "Stellplätze", + parking_entity: "Sensor „Auto anwesend“", + parking_vehicle: "Fahrzeug", + parking_vehicle_none: "Keins", + parking_no_pack: "Kein Fahrzeug-Pack importiert – Fahrzeuge kommen aus dem Pack „Fahrzeuge“ (Erweiterungen → Möbel-Packs).", + parking_scale: "Größe (%)", + parking_type_entity: "Fahrzeugtyp-Sensor (optional)", + parking_types: "Zustand → Fahrzeug", + parking_type_state: "Zustand (z. B. van)", + parking_add_type: "+ Zuordnung", + parking_hint: + "Ohne Sensor steht das Fahrzeug immer da. Mit Sensor erscheint es, sobald der Sensor „an“, „home“ oder „anwesend“ meldet. Ein Fahrzeugtyp-Sensor (z. B. aus einer KI-Kameraauswertung) wählt das Modell: Passt sein Zustand zu einer Zuordnung – auch als Wort im Text –, wird dieses Fahrzeug gezeigt, sonst das Standard-Fahrzeug.", + parking_too_tall: "Das Fahrzeug ({car} m) ist höher als der Raum ({room} m).", + furn_lamp_ceiling: "Deckenleuchte", + furn_lamp_downlight: "Einbauspot", + furn_lamp_spot: "Aufbau-Spot", + furn_lamp_panel: "LED-Panel", + furn_lamp_uplight: "Deckenfluter", + furn_lamp_bollard: "Wegleuchte", + furn_lamp_garden: "Garten-Spot", + furn_radiator: "Heizkörper", + furn_robot_vacuum: "Saugroboter", + furn_entity_vacuum: "Saugroboter", + furn_entity_mower: "Mähroboter", + pet_room_sensor: "Raum-Sensor des Tiers (optional)", + pet_room_hint: "Ein Sensor, der den Raum nennt, in dem das Tier gerade ist – Bermuda oder ESPresense mit einem Anhänger am Halsband: in 3D läuft es dann in diesem Raum herum.", + furn_entity_water: "Ventil oder Schalter", + device_temp: "Gerätetemperatur", + device_temp_hint: "Ein Temperatursensor des Geräts (Wechselrichter, Akku, PC …): sein Wert steht am Pin in der 3D-Ansicht, ab 60 °C ist der Pin hervorgehoben.", + fridge_temp: "Temperatur Kühlteil", + freezer_temp: "Temperatur Gefrierteil", + fridge_temp_hint: "Der Pin zeigt die Temperaturen. Über 8 °C im Kühlteil oder −12 °C im Gefrierteil leuchtet er als Warnung.", + spray_reach: "Reichweite des Wassers (m)", + spray_hint: "Solange das Ventil offen oder der Schalter an ist, spritzt der Sprenger Wasser in Bögen um sich herum.", + furn_robot_room: "Aktueller Raum (Sensor)", + robot_cal_none: "Noch nicht kalibriert – ohne Bezug zur Karte bleibt die Fahrspur erfunden.", + robot_cal_done: "Kalibriert: eine Rasterzelle misst {m} m.", + robot_cal_do: "Von der jetzigen Position des Roboters kalibrieren", + robot_cal_doing: "Tippe in den Plan, wo der Roboter gerade steht.", + robot_cal_need: "Die Karte des Roboters meldet gerade keine Position – läuft die Integration?", + robot_cal_hint: "Die Station ist der Anker: der Plan weiß, wo sie steht, die Kamera weiß, wo Roboter und Station in ihrem Raster liegen. Kennt die Karte Räume mit denselben Namen wie der Plan, reicht der Knopf „Aus den Räumen kalibrieren“. Sonst: Stell den Roboter mindestens 1,5 m entfernt ab – Reinigung pausieren – und tippe ihn im Plan an. Kommen die Räume spiegelverkehrt heraus, setze den Haken.", + robot_cal_mirror: "Die Karte des Roboters ist gespiegelt (Räume kommen verkehrt heraus)", + robot_cal_forget: "Kalibrierung entfernen", + robot_cal_nudge: "Von Hand nachrücken: Pfeile schieben die Karte um 10 cm, ⟲ ⟳ drehen um 1°, − + ändern die Größe um 1 %.", + robot_cal_nudge_move: "Karte verschieben", + robot_cal_nudge_turn: "Karte drehen", + robot_cal_nudge_grow: "Karte größer oder kleiner", + robot_cal_rooms: "Aus den Räumen kalibrieren (die Karte kennt {n} Räume)", + robot_cal_rooms_none: "Zu wenige Räume heißen im Plan so wie auf der Karte des Roboters ({n} gefunden, mindestens 2 nötig). Benenne die Räume gleich – oder kalibriere über die Position des Roboters.", + robot_cal_rooms_bad: "Die gleichnamigen Räume liegen im Plan anders als auf der Karte des Roboters – ist ein Raum vertauscht? Kalibriere sonst über die Position des Roboters.", + robot_hint: "Saugt der Roboter in Home Assistant, fährt er in 3D in Bahnen durch den Raum, den er meldet (Sensor „Aktueller Raum“, zugeordnet über den Raum- oder Bereichsnamen), sonst durch den Raum seiner Station. Ist die Karte des Roboters unten kalibriert, zeigt die Spur stattdessen, wo er wirklich gefahren ist; ohne sie sind die Bahnen erfunden. Zurück fährt er zur Station.", + furn_lamp_pendant: "Pendelleuchte", + furn_ceiling_fan: "Deckenventilator", + furn_fan_entity: "Ventilator", + fan_hint: "Die Leuchte ist das Licht des Ventilators (leer lassen, wenn er keins hat). Der Ventilator wird im Raum gefunden oder hier gewählt: In 3D drehen sich die Flügel so schnell wie er läuft, sein Symbol schaltet ihn, Wischen hoch/runter ändert die Stufe, lange drücken öffnet das Schnellmenü. Die Höhe ist, wie weit er von der Decke hängt (mehr = längere Stange).", + room_ceiling: "Deckenhöhe", + room_ceiling_tip: "Niedriger als das Stockwerk (ein Bad unter der Treppe) oder höher (ein Wohnzimmer offen bis unters Dach): Deckenleuchten, Ventilatoren, LED-Streifen und Geräte an der Decke hängen dann hier, und die Wände des Raums sind so hoch.", + room_ceiling_through: "Die Decke ({ceiling} m) liegt über der Etagenhöhe ({floor} m): Der Raum reicht in die Etage darüber, seine Wände wachsen mit, und die Etage darüber bleibt über ihm offen (Luftraum). Im Editor der oberen Etage ist die Fläche schraffiert.", + room_floor_offset: "Bodenhöhe (m)", + room_floor_offset_hint: "Liegt der Boden dieses Raums tiefer oder höher als die Etage (ein abgesenkter Eingang: −0,39), wandern Boden, Wände, Türen und Fenster und was im Raum steht mit; die Decke bleibt. Die Stufen stellst du als Treppe dazu.", + room_inner: "Innenmaß {w} × {d}", + room_inner_hint: "Von Wand zu Wand gemessen: Innenwände nehmen die Hälfte ihrer Dicke, Außenwände stehen außerhalb des Umrisses.", + floor_heating: "Fußbodenheizung (optional)", + floor_heating_hint: "Solange der Thermostat heizt (oder das Ventil offen, der Schalter an ist), glüht der Boden des Raums in 3D warm.", + room_announce_speaker: "Lautsprecher für Durchsagen", + room_announce_quiet: "Ruhezeit für Durchsagen", + room_announce_hint: "Ohne Wahl spricht der Lautsprecher, der im Raum steht, sonst ein Sprachassistent, ein Echo oder ein Lautsprecher des Bereichs (nie ein Fernseher). In der Ruhezeit lassen Durchsagen an mehrere Räume diesen Raum aus; eine Durchsage nur für ihn kommt trotzdem an.", + ceiling_here: "Decke hier", + ceiling_here_hint: "Höhe der Decke genau an dieser Stelle, z. B. bei einer Dachschräge. Leer = Decke des Raums.", + ceiling_slope: "An die Dachschräge", + ceiling_slope_hint: "Die Decke liegt hier unter der Dachschräge: die Leuchte hängt an deren Unterseite, genau über ihrem Platz.", + furn_lamp_floor: "Stehlampe", + furn_lamp_table: "Tischlampe", + furn_lamp_wall: "Wandleuchte", + furn_led_strip: "LED-Streifen", + furn_group_lights: "Leuchten", + furn_entity_light: "Licht oder Schalter", + furn_color_entity: "Farbe und Helligkeit von (optional)", + furn_color_entity_hint: "Für Lampen, die ein Relais (Shelly, Schaltaktor) ein- und ausschaltet, während die Leuchte selbst Farbe und Helligkeit kennt: An/Aus kommt vom Schalter oben, Farbe und Helligkeit von dieser Entität.", + lamp_extra_light: "Leuchtmittel {n} (optional)", + lamp_extra_hint: "Eine Leuchte mit mehreren Lichtern – Hauptlicht, Nachtlicht, Lichtring: Ist das Hauptlicht aus, leuchtet sie in 3D mit dem nächsten Licht, das an ist, etwas schwächer. Die Lichter schaltest du im Raumfenster einzeln.", + furn_entity_climate: "Heizung (Thermostat)", + lamp_hint: "Antippen in 3D schaltet die Leuchte, lange drücken öffnet das Schnellmenü. Auch Schalter (z. B. ein Relais fürs Deckenlicht) sind möglich – die Leuchte strahlt dann, solange er an ist. Tischlampen stehen automatisch auf dem Möbel darunter.", + lamp_hint_pendant: "Höhe = Abhängung unter der Decke. Antippen in 3D schaltet, lange drücken öffnet die Details.", + theme: "Look", + version_hint: "Installierte Version von NextFloor – Oberfläche; die Integration in Home Assistant meldet {backend}", + accent: "Akzentfarbe", + accent_hint: "Eigene Akzentfarbe: Linien und Leuchtkanten im Neon-Look, Knöpfe und Pins – ↺ setzt das Neon-Cyan zurück", + accent_reset: "Zurück zu Cyan", + furn_colors_card: "Möbelfarben dieser Karte", + furn_color_house: "Farbe des Hauses", + theme_neon: "Neon", + theme_blueprint: "Blueprint", + theme_day: "Tag", + theme_auto: "Auto", + clock: "Uhr", + clock_none: "Keine", + clock_top_left: "Oben links", + clock_top_right: "Oben rechts", + clock_bottom_left: "Unten links", + clock_bottom_right: "Unten rechts", + glass_walls: "Glaswände", + glass_walls_hint: "Wie deckend die Wände sind, durch die man in die Räume schaut: links fast unsichtbar, rechts undurchsichtig. Gilt für diesen Bildschirm.", + screen_name: "Name dieses Bildschirms", + screen_name_hint: "Durchsagen erscheinen auf jedem offenen NextFloor-Bildschirm. Mit einem Namen (z. B. „Flur“) kann eine Durchsage auch nur an diesen Bildschirm gehen. Ohne Haken bleibt dieser Bildschirm still.", + announce_on: "Durchsagen auf diesem Bildschirm an", + announce_muted: "Durchsagen auf diesem Bildschirm stumm", + lock3d_on: "3D sperren (Drehen, Zoomen und Verschieben aus, Tippen geht weiter)", + lock3d_off: "3D entsperren", + walk: "Durchs Haus gehen", + travel: "Zeitreise: die letzten 24 Stunden oder 7 Tage abspielen", + travel_play: "Abspielen", + travel_pause: "Anhalten", + travel_loading: "Lade Verlauf …", + travel_failed: "Der Verlauf ließ sich nicht laden.", + travel_speed: "Tempo", + travel_speed_min: "1 Min./s", + travel_speed_10min: "10 Min./s", + travel_speed_hour: "1 Std./s", + travel_days: "Tage", + travel_live: "Live", + card_travel_button: "Taste für die Zeitreise", + walk_stop: "Gehen beenden", + walk_hint: "Ziehen: umsehen · W A S D / Pfeile oder Stick: gehen · Mausrad: Schritt", + card_walk_button: "Taste zum Durchgehen", + card_lock_button: "Taste für die 3D-Sperre", + backdrop: "Eigener Hintergrund", + backdrop_color: "Farbe", + backdrop_image: "Bild (/local/… oder https://…)", + backdrop_dim: "Abdunkeln", + backdrop_hint: "Statt des Himmels des Looks steht das Haus vor einer eigenen Farbe oder einem Bild. Ein Bild in /config/www ist unter /local/… erreichbar.", + furnish: "Einrichten", + split_3d: "3D daneben", + plan_dims: "Maße", + plan_dims_hint: "Schreibt an jede Raumkante ihre Länge.", + mount_height: "Höhe über Boden (m)", + side_open: "Seitenleiste öffnen", + side_close: "Schließen", + side_details: "Details zur Auswahl", + side_pin: "Anheften", + side_pinned: "Angeheftet", + side_pin_hint: "Angeheftet bleibt die Seitenleiste immer offen; sonst klappt sie neben der 3D-Ansicht zu, solange nichts ausgewählt ist", + split_3d_hint: "Live-3D neben dem Plan: Möbel und Geräte dort ziehen und drehen – mit Rückgängig, gespeichert wird mit dem Plan", + size_w: "Breite (m)", + size_d: "Tiefe (m)", + size_h: "Höhe (m)", + furnish_hint: "Möbel, Leuchten und Geräte mit dem Finger ziehen · Möbel rasten an Wänden ein · antippen zum Drehen, für Höhe und Montage", + done: "Fertig", + heatmap: "Heatmap", + heat_off: "Normal", + heat_short_temperature: "Temp.", + heat_short_humidity: "Feuchte", + heat_short_co2: "CO₂", + heat_short_mould: "Schimmel", + heat_short_power: "Strom", + heat_short_comfort: "Komfort", + heat_short_sun: "Sonne", + heat_short_wifi: "WLAN", + heat_short_values: "Werte", + heat_temperature: "Temperatur", + heat_humidity: "Luftfeuchtigkeit", + heat_co2: "CO₂", + heat_mould: "Schimmel", + heat_power: "Stromverbrauch", + heat_comfort: "Wohlfühlwert", + heat_sun: "Sonne heute", + room_sun_hours: "{h} h Sonne heute ({facing})", + open_since: "offen seit {time}", + presence_now: "jemand da", + presence_last: "zuletzt vor {time}", + comfort_n: "Komfort {n}", + empty_lights_hint: "{n} Licht an, seit {min} min niemand da.", + empty_lights_off: "Licht aus", + open_heating_hint: "{n} Fenster offen, während die Heizung läuft.", + open_heating_off: "Heizung aus", + room_clean: "Reinigung (Skript oder Knopf)", + room_clean_hint: "Ein Skript oder Knopf, der den Saugroboter in diesen Raum schickt (z. B. die Raumreinigung deiner Roboter-Integration). Das Raum-Panel zeigt dann „🧹 Saugen“.", + room_clean_run: "Saugen", + room_clean_run_hint: "Schickt den Saugroboter in diesen Raum.", + shade_hint: "Sonne auf {n} Fenstern bei {temp} – Rollläden senken?", + shade_close: "Senken", + room_sun_year: "Sonne übers Jahr", + room_sun_year_hint: "Die Sonnenstunden durch die Außenfenster des Raums am 15. jedes Monats.", + room_energy: "heute {today} · Monat {month}", + room_energy_hint: "Aus der Statistik der Leistungssensoren der Geräte im Raum; die Kosten für den Monat mit dem Tarif des Hauses.", + heat_summer: "Sommer", + heat_winter: "Winter", + air_co2: "lüften (CO₂)", + air_humidity: "lüften (feucht)", + air_mould: "Schimmelgefahr – lüften", + room_curve_hint: "Die Temperatur des Raums in den letzten 24 Stunden", + heat_values: "Werte am Raumnamen", + heat_wifi: "WLAN", + wifi_aps: "{n} Access Points · {clients} Geräte", + wifi_network: "Netzwerk: {online} online · {offline} offline", + wifi_none: "Stelle Access Points oder Router aus den Packs (Smart Home 2) auf und verknüpfe sie mit einer Entität ihres Geräts.", + wifi_clients: "{n} Geräte", + heat_none_found: "Keine passenden Sensoren in den Bereichen der Räume.", + markers: "Symbole", + markers_none: "Keine", + markers_important: "Wichtige", + markers_all: "Alle", + furn_stool: "Hocker", + furn_coffee_table: "Couchtisch", + furn_tv_wall: "Fernseher (Wand)", + furn_sideboard: "Sideboard", + furn_table_round: "Runder Tisch", + furn_bench: "Sitzbank", + furn_corner_bench: "Eckbank", + furn_bar_stool: "Barhocker", + furn_kitchen_wall: "Oberschrank", + furn_kitchen_tall: "Hochschrank mit Backofen", + furn_island: "Kochinsel", + furn_dishwasher: "Spülmaschine", + furn_bunk_bed: "Etagenbett", + furn_dresser: "Kommode", + furn_washer: "Waschmaschine", + furn_dryer: "Trockner", + furn_office_chair: "Bürostuhl", + furn_tall_cabinet: "Hochschrank", + furn_coat_rack: "Garderobe", + furn_group_living: "Wohnen", + furn_group_dining: "Essen", + furn_group_kitchen: "Küche", + furn_group_sleeping: "Schlafen", + furn_group_bath: "Bad & Hauswirtschaft", + furn_group_work: "Arbeiten & Sonstiges", + furn_group_energy: "Energie & Solar", + energy_devices: "Geräte", + wallbox_charging: "lädt", + wallbox_plugged: "angesteckt", + furn_soc: "Ladestand (%)", + furn_export: "Einspeiseleistung (W, separater Sensor, optional)", + furn_export_hint: "Meldet dein Zähler Bezug und Einspeisung in zwei Sensoren (z. B. Growatt, Tibber Pulse), nimm oben den Bezugs-Sensor als Leistung und hier den Einspeise-Sensor. Ein Sensor mit Vorzeichen braucht das nicht.", + meter_parent: "Hängt an Zähler", + meter_parent_none: "keinem (Hauptzähler)", + meter_main: "Hauptzähler", + meter_unmetered: "{w} ungemessen", + meter_device_hint: "Steht das Gerät hinter einem Zwischenzähler (z. B. Balkonkraftwerk in einer Wohnung), zählt seine Leistung zu dieser Wohnung. Der Zwischenzähler muss dafür in beide Richtungen messen (− = Rückspeisung); zählt er nur Bezug, fällt der Verbrauch der Wohnung bei Überschuss zu hoch aus.", + meter_sub_power: "Leistung des Zweigs (W, + = Bezug, − = Rückspeisung)", + meter_floors: "Versorgt die Etagen", + meter_sub_hint: "Ein Zwischenzähler misst seinen Zweig, z. B. eine Wohnung. Geräte auf den angehakten Etagen hängen in 3D an ihm statt am Hauptzähler; was der Hauptzähler darüber hinaus zählt, steht als „Allgemein (Rest)“ in der Bilanz.", + furn_charge: "Ladeleistung (W, separater Sensor, optional)", + furn_charge_hint: "Meldet dein Speicher Laden und Entladen in zwei Sensoren (z. B. Anker Solix), nimm oben den Entlade-Sensor als Leistung und hier den Lade-Sensor. Ein Sensor mit Vorzeichen braucht das nicht.", + furn_wallbox_status: "Status (lädt, angesteckt)", + energy_only_note: "⚡ Energie: Hier lassen sich nur Solarfelder und Energiegeräte verschieben, Räume und Möbel sind gesperrt.", + roof_only_note: "🏠 Dach: Hier lassen sich nur Dachflächen und Dachfenster verschieben, Räume und Möbel sind gesperrt.", + energy_devices_hint: "Stromzähler, Wechselrichter, Stromspeicher, Wallbox und Netzanschluss werden hier angelegt: auf der oben gewählten Etage, im Grundriss verschiebbar. Mit Leistungssensor zeigen sie ihre Watt; der Zähler bekommt den Netzsensor, beim Strang wählst du den Wechselrichter. Mehrere Wechselrichter und Speicher (etwa eine Balkonanlage dazu) gehen auch: Jeder bekommt seinen eigenen Sensor.", + energy_routes: "Kabelwege", + energy_routes_hint: "Wo ein Kabel wirklich läuft: Der Fluss folgt dann deinen Punkten statt eines Bogens quer durchs Haus. Ohne Weg bleibt es beim Bogen. Verbraucher behalten ihren Bogen.", + route_conn_solar: "{name} → Wechselrichter", + route_conn_battery: "Batterie ↔ Haus", + route_conn_inverter: "Wechselrichter → Haus", + route_conn_grid: "Netz ↔ Haus", + route_conn_meter: "{name} ↔ übergeordneter Zähler", + route_conn_device: "{name} ↔ Unterzähler", + route_points: "{n} Punkte", + route_none: "direkter Bogen", + route_draw: "Weg zeichnen", + route_redraw: "Neu zeichnen", + route_drawing: "Tippe im Plan die Punkte an, durch die das Kabel läuft, vom einen Ende zum anderen; wechsle dazwischen das Geschoss, wo es durch die Decke geht. {n} Punkte.", + route_undo: "Letzter Punkt", + route_done: "Fertig", + route_cable: "Als Kabel zeigen", + route_cable_hint: "Zeichnet den Weg als sichtbares Kabel, nicht nur als feine Linie unter den Teilchen.", + solar_fields: "Solarfelder", + solar_hint: "Module aufs Dach legen: Sie liegen in der Neigung der Dachfläche, auf einem Flachdach stehen sie aufgeständert. Im Grundriss lässt sich ein Feld mit der Maus verschieben.", + solar_no_roof: "Für Solarfelder braucht das Haus ein Dach: unter Einstellungen ein Sattel- oder Flachdach, oder Dachabschnitte hier im Dach-Werkzeug.", + solar_face_gone: "Dachfläche fehlt", + solar_summary: "{n} Module · {kwp} kWp", + solar_add: "Solarfeld", + solar_field: "Solarfeld", + solar_face: "Dachfläche", + solar_rows: "Reihen", + solar_cols: "Module pro Reihe", + solar_portrait: "Hochformat", + solar_landscape: "Querformat", + solar_u: "Abstand vom Rand (m)", + solar_v: "Abstand von der Traufe (m)", + solar_tilt: "Neigung der Aufständerung (°)", + solar_rack_ew: "Ost-West-Aufständerung", + solar_rack_ew_hint: "Jede zweite Reihe zeigt in die andere Richtung, die Paare stehen Rücken an Rücken – flach und dicht wie auf vielen Flachdächern.", + solar_rack_tilt: "Aufständerung (° zusätzlich)", + solar_flip: "In die andere Richtung neigen", + solar_partial: "nur {n} von {total} passen auf die Fläche", + solar_form_hint: "Module, die über die Dachfläche hinausragen würden, fallen weg. „Fläche füllen“ legt so viele Module aufs Dach, wie passen. kWp gerechnet mit 400 W je Modul.", + solar_fit: "Fläche füllen", + roof_windows: "Dachfenster", + roof_window: "Dachfenster", + chimneys: "Schornsteine", + chimney: "Schornstein", + chimney_shape: "Form", + chimney_brick: "Gemauert", + chimney_round: "Rund", + chimney_wide: "Breit, zwei Züge", + chimney_steel: "Edelstahlrohr", + chimney_diameter: "Durchmesser (m)", + chimney_depth: "Tiefe (m)", + chimney_height: "Höhe über dem Dach (m)", + chimney_hint: "Die Höhe zählt ab der oberen Seite, wo der Schornstein aus dem Dach kommt. Im Grundriss und in der 3D-Ansicht lässt er sich verschieben, auch auf eine andere Dachfläche.", + roof_windows_hint: "Dachfenster liegen in der Dachfläche, mit Rollladen und Kontakt wie normale Fenster. Im Grundriss lassen sie sich verschieben, auch auf eine andere Dachfläche.", + roof_window_tilt: "Kippkontakt", + roof_window_name: "Name (optional)", + roof_window_motor: "Fenstermotor (Cover, optional)", + roof_window_motor_hint: "Ein Fenstermotor (Velux, Roto, Fakro) meldet seine Position als Cover: Der Flügel öffnet in 3D so weit, wie der Motor steht. Ein Kontakt oder Kippkontakt geht weiterhin ohne Motor.", + roof_window_hint: "Offen klappt der Flügel oben angeschlagen nach außen, gekippt ein Stück, und der Rahmen leuchtet warm; der Rollladen fährt von oben über die Scheibe. In einer Dachfläche schneidet das Fenster ein Loch in die Schräge, so sieht das Dachgeschoss hinaus.", + solar_ground: "Frei aufgeständert (Garten, Garagendach …)", + solar_add_ground: "Frei aufgeständert", + solar_base: "Höhe der Aufstellfläche (m, 0 = Boden)", + solar_add_wall: "An der Wand", + solar_wall: "Wand", + solar_v_wall: "Höhe über dem Boden (m)", + solar_tilt_wall: "Neigung von der Wand (°, 90 = Vordach)", + solar_flip_wall: "Unten abstehend statt oben", + solar_rotation: "Drehung (°)", + solar_name: "Name", + solar_name_hint: "z. B. Strang 1 Süd", + solar_module_w: "Modulbreite (m)", + solar_module_h: "Modulhöhe (m)", + solar_wp: "Modulleistung (Wp)", + solar_string: "Strang", + solar_strings: "Stränge", + solar_string_none: "Kein Strang", + solar_string_new: "Neuer Strang", + solar_string_n: "Strang {n}", + solar_string_name: "Name des Strangs", + solar_string_entity: "PV-Leistung des Strangs", + solar_string_inverter: "Wechselrichter", + solar_string_inverter_none: "Kein Wechselrichter gewählt", + inverter_strings: "Stränge an diesem Wechselrichter: {names}", + inverter_strings_none: "Noch kein Strang an diesem Wechselrichter – zuordnen beim Solarfeld unter Strang › Wechselrichter.", + solar_string_inverter_missing: "Noch kein Wechselrichter im Plan (unten bei Geräte anlegen)", + solar_string_hint: "Felder im selben Strang gehören zusammen, auch auf verschiedenen Dächern (z. B. 5 Module auf dem Haus und 5 auf der Garage). Sensor und Wechselrichter gelten für den ganzen Strang.", + solar_string_sum: "{fields} Felder · {n} Module · {kwp} kWp", + solar_face_size: "Dachfläche {w} × {h} m (entlang der Traufe × die Schräge hoch)", + solar_cols_hint: "Eine Zahl für gleich lange Reihen, oder eine Liste für Reihen eigener Länge: „4, 4, 3“ (von der Traufe aus).", + solar_align_left: "Links", + solar_align_center: "Mitte", + solar_align_right: "Rechts", + solar_look_black: "Full Black", + solar_look_blue: "Blau", + solar_pick: "Module einzeln an/aus", + solar_pick_all: "Alle wieder an", + solar_pick_hint: "Tippe im Grundriss auf ein Modul, um es wegzunehmen oder wieder dazuzunehmen. Weggenommene sind gestrichelt.", + solar_entity: "PV-Leistung dieses Feldes (z. B. sein Strang)", + solar_main: "Hauptdach", + solar_section: "Abschnitt {n}", + solar_flat: "Flachdach", + compass_n: "Nord", + compass_ne: "Nordost", + compass_e: "Ost", + compass_se: "Südost", + compass_s: "Süd", + compass_sw: "Südwest", + compass_w: "West", + compass_nw: "Nordwest", + furn_meter: "Stromzähler", + furn_grid_point: "Netzanschluss", + grid_point_hint: "Hier steht der Netzanschluss: der Übergabepunkt zum Stromanbieter, zum Beispiel am Ende der Einfahrt. Im Grundriss verschiebbar.", + furn_model: "Modell", + inverter_std: "Standard (Wandgerät mit Display)", + inverter_slim: "Schmal und hoch (Lichtleiste)", + inverter_hybrid: "Hybrid (Rund-Display, Lüfter)", + battery_std: "Turm (gestapelte Module)", + battery_wall: "Wandspeicher (flach, hängend)", + battery_cube: "Kompakt (Balkonspeicher)", + furn_inverter: "Wechselrichter", + furn_home_battery: "Stromspeicher", + furn_wallbox: "Wallbox", + furn_entity: "Gerät (Schalter, Steckdose …)", + furn_state_entity: "Zustand von (optional)", + furn_state_entity2: "Zweiter Zustand (andere Hälfte)", + furn_tap: "Antippen des Möbels", + furn_tap_default: "Wie üblich", + furn_tap_hint: "Eine eigene Aktion wie bei den eigenen Knöpfen des Sternmenüs, z. B. ein browser_mod-Popup mit deiner Karte.", + furn_show_when: "Nur zeigen, solange …", + furn_show_when_state: "… im Zustand (leer = an)", + furn_show_when_invert: "Umgekehrt: zeigen, solange es nicht so ist", + furn_show_when_hint: "Saison-Deko, die nur im Dezember steht: ein Helfer (input_boolean), ein Kalender oder ein Sensor entscheidet, ob das Möbel in 3D erscheint. Mehrere Zustände mit Komma trennen. Im Editor bleibt es immer sichtbar.", + picture_upload: "Foto hochladen", + picture_replace: "Anderes Foto hochladen", + picture_stored: "Ein eigenes Foto ist gespeichert.", + picture_url: "… oder Bild-Adresse", + picture_entity: "… oder Bild einer Entität", + picture_border: "Passepartout (%)", + picture_fit: "Foto", + picture_fit_cover: "füllt den Rahmen", + picture_fit_contain: "ganz zu sehen", + picture_hint: "Dein Foto im Rahmen, in 3D und auf dem Wandtablet. Hochgeladene Fotos werden verkleinert mit dem Plan gespeichert; eine Bild-Entität (z. B. Foto des Tages) oder eine Kamera zeigt ihr aktuelles Bild.", + furn_state_split: "Hälften", + furn_state_left_right: "Links / rechts", + furn_state_top_bottom: "Unten / oben (Hochbett)", + furn_state_hint: "Das Möbel leuchtet, solange die Entität an, belegt oder zu Hause meldet – ein Bett mit Belegungsmatte, ein Sessel, die Sauna. Zwei Entitäten beleuchten die Hälften: links und rechts, beim Hochbett unten und oben.", + furn_entity_tv: "Fernseher (Media-Player oder Steckdose)", + fix: "Fixieren", + unfix: "Lösen", + fix_hint: "Fixiert: lässt sich nicht mehr versehentlich verschieben (Taste L, Rechtsklick oder langes Drücken)", + fixed_drag_hint: "🔒 Fixiert – zum Verschieben erst lösen (Schloss im Formular, Rechtsklick oder Taste L)", + fixed_delete_confirm: "Dieses Element ist fixiert. Trotzdem löschen?", + lock_plan: "🔒 Grundriss", + lock_plan_hint: "Grundriss sperren: Räume, Wände, Türen, Fenster und Außenflächen lassen sich nicht mehr versehentlich verschieben. Möbel und Geräte bleiben frei.", + start_view: "Startansicht", + start_view_hint: "Mit dieser Ansicht öffnen 3D-Ansicht, Karte und Kiosk das Haus, zum Beispiel von der Gartenseite. Drehe, zoome und verschiebe das Haus in der 3D-Ansicht rechts, bis es passt, und merke sie dir dann.", + start_view_card: "Soll eine Karte eine andere Ansicht haben: diese Zeile in ihre YAML-Konfiguration übernehmen.", + start_view_set: "Aktuelle 3D-Ansicht als Start merken", + start_view_reset: "Standard", + start_view_saved: "Eine eigene Startansicht ist gespeichert.", + ctx_rotate: "Drehen 90°", + devices_placed_in: "in {room}", + devices_narrow: "{n} weitere – Suche eingrenzen", + climate: "Raumklima", + climate_temperature: "Temperatur", + climate_humidity: "Luftfeuchte", + climate_co2: "CO₂", + climate_hint: "Diese Sensoren gelten für die Heatmap und das Raumfenster. „Automatisch“ nimmt die Sensoren des Bereichs und die im Raum platzierten, aber keine Gerätetemperaturen (3D-Drucker, Wärmepumpe, Vorlauf …).", + climate_more: "… und noch ein Sensor (Mittelwert)", + plan_locked: "Grundriss gesperrt", + plan_lock: "Grundriss sperren", + plan_unlock: "Grundriss entsperren", + opening_mark: "Markieren in 3D", + opening_mark_open: "Wenn offen", + opening_mark_closed: "Wenn geschlossen (z. B. WC)", + opening_mark_hint: "Ein markiertes Fenster oder eine markierte Tür leuchtet warm. „Wenn geschlossen“ braucht einen Kontakt; ohne Sensor wird nichts markiert.", + window_opens: "Öffnet", + window_opens_turn: "Dreh-Kipp (nach innen)", + window_opens_slide: "Schiebend (Schiebefenster, Hebe-Schiebetür)", + window_opens_top: "Klappfenster (unten nach außen)", + window_opens_hint: "Schiebend: Der Flügel auf der Seite des Scharniers gleitet vor den festen; zweiflügelig gleiten die beiden mittleren nach außen. Klappfenster öffnen mit dem Kontakt oder einem Kippsensor.", + marker_show: "Symbol in 3D", + marker_show_hint: "Automatisch folgt dem Schalter Keine / Wichtige / Alle in der 3D-Ansicht. Immer zeigen und Ausblenden gelten unabhängig davon (außer bei Keine).", + pin_shift: "Pin verschieben", + pin_shift_up: "↑ Höhe", + pin_shift_hint: "Stehen Geräte dicht beieinander, schiebst du den Pin hier ein Stück zur Seite oder nach oben (in Metern); das Gerät selbst bleibt, wo es ist.", + marker_show_auto: "Automatisch", + marker_show_always: "Immer zeigen", + marker_show_no_power: "Ohne Watt", + marker_show_active: "Nur wenn aktiv", + marker_show_never: "Ausblenden", + marker_icon: "Eigenes Symbol (Material-Design-Icon)", + device_name: "Eigener Name (optional)", + show_name: "Name unter dem Symbol in 3D zeigen", + card_marker_names: "Eigene Namen an den Symbolen", + card_marker_names_hint: "Jedes Gerät mit eigenem Namen zeigt ihn klein unter seinem Symbol – drei Thermometer im Garten bleiben unterscheidbar.", + card_tap_in_room: "Geräte nur im geöffneten Raum schalten", + card_tap_in_room_hint: "In der Haus- und Stockwerksansicht öffnet ein Antippen das Stockwerk oder den Raum, auch auf einem Gerät oder seinem Symbol. Im geöffneten Raum schaltet es das Gerät. Langes Drücken öffnet immer sein Menü oder seine Details.", + card_markers_outside: "Symbole außerhalb des geöffneten Raums wählen", + card_markers_outside_hint: "Im Haus, auf dem Stockwerk und in den anderen Räumen nur die angehakten Arten; im geöffneten Raum alle wie oben eingestellt. „Immer“ und „Nie“ am Gerät gehen vor.", + marker_kind_light: "Lichter", + marker_kind_cover: "Rollläden", + marker_kind_climate: "Heizung", + marker_kind_media: "Medien", + marker_kind_switch: "Schalter", + marker_kind_fan: "Ventilatoren", + marker_kind_lock: "Schlösser", + marker_kind_binary: "Kontakte und Melder", + marker_kind_sensor: "Sensoren", + marker_kind_tap: "Möbel mit Aktion", + marker_kind_other: "Sonstige", + device_name_hint: "Ein Name für den Plan und das Raumfenster, z. B. „Dekolicht Kochinsel“ – die Entität in Home Assistant bleibt, wie sie ist.", + device_simple: "Im Raumfenster nur schalten", + device_simple_hint: "Der Raumdialog zeigt für diese Lampe nur den Schalter, ohne Helligkeit, Farbtemperatur und Farben.", + floor_turn: "90° drehen", + floor_shift_all: "Alle Etagen mitnehmen (ganzes Haus)", + floor_shift_all_hint: "Verschieben und Drehen wirken auf alle Etagen samt Dachflächen, Außenflächen, Energiegeräten und Zähler – das ganze Haus wandert als Ganzes.", + floor_turn_hint: "Dreht alles auf der Etage um 90° im Uhrzeigersinn um die Mitte der Räume – wenn eine Etage verdreht gezeichnet wurde. Dreimal = 270°.", + marker_icon_hint: "Name eines Material-Design-Icons wie bei Home Assistant, z. B. mdi:thermometer oder mdi:water-alert. Leer = Symbol nach Geräteart.", + furn_power: "Leistungssensor (W)", + furn_links_hint: "Mit Leistungssensor zeigt das Möbel seine Watt und nimmt am Energiefluss teil.", + furn_links_hint_tv: "Der Bildschirm leuchtet, solange der Fernseher an ist, in der Farbe der App (Netflix, YouTube …); das Schild zeigt App oder Titel.", + stairs_hint: "Die Treppe steigt nach hinten an (weg von der markierten Vorderkante) und öffnet die Decke der Etage darüber.", + stair_shape: "Form", + stair_shape_straight: "Gerade", + stair_shape_quarter: "Viertelgewendelt", + stair_shape_l: "L mit Podest", + stair_shape_half: "Halbgewendelt", + stair_shape_u: "U mit Podest", + stair_shape_spiral: "Wendeltreppe", + stair_turn: "Laufrichtung (beim Hinaufgehen)", + stair_turn_left: "Links herum", + stair_turn_right: "Rechts herum", + stair_build: "Bauart", + stair_build_solid: "Massiv (Beton)", + stair_build_stringer: "Wangentreppe", + stair_build_mono: "Holmtreppe (Mittelholm)", + stair_build_cantilever: "Kragarm (schwebend)", + stair_risers: "Setzstufen", + stair_steps: "Steigungen", + stair_run_width: "Laufbreite (m)", + stair_landing_after: "Stufen bis zum Podest", + stair_landing_hint: "Das Podest liegt {h} cm über dem Boden; der Rest der Stufen kommt danach.", + stair_rail: "Geländer", + stair_rail_none: "Keins", + stair_rail_left: "Links", + stair_rail_right: "Rechts", + stair_rail_both: "Beidseitig", + stair_down: "Führt nach unten", + stair_down_hint: "Die Treppe beginnt auf dieser Etage und führt hinunter, zum Beispiel in einen Keller, der nicht gezeichnet sein muss. Sie öffnet den Boden dieser Etage.", + stair_measures: "{steps} Steigungen à {rise} cm · Auftritt {going} cm · Schrittmaß {measure} cm", + stair_uncomfortable: "unbequem (Schrittmaß 59–65 cm, Steigung höchstens 21 cm)", + stair_up_note: "Die Treppe beginnt an der markierten Vorderkante. Die Decke der Etage darüber öffnet sich nur dort, wo über den Stufen keine 2,2 m Kopfhöhe bleiben.", + stair_down_note: "Man betritt die Treppe an der markierten Vorderkante und geht hinunter. Im Plan ist sie gestrichelt; der Boden dieser Etage öffnet sich über den Stufen.", + stair_opening: "Deckenöffnung", + stair_opening_headroom: "Nach Kopfhöhe (nur wo nötig)", + stair_opening_full: "Über der ganzen Treppe", + stair_opening_none: "Keine (Luke, geschlossener Schacht)", + stair_opening_hint: "Wie weit die Treppe den Boden öffnet, den sie erreicht: die Etage darüber, oder bei einer Treppe nach unten die eigene. Nach Kopfhöhe öffnet nur über den Stufen, über denen keine 2,2 m bleiben.", + stair_up_note_plain: "Die Treppe beginnt an der markierten Vorderkante und steigt nach hinten an.", + stair_upgrade: "Form einstellen", + stair_upgrade_hint: "Macht daraus eine Treppe mit Form (gewendelt, L, U, Wendel), Bauart, Geländer und Stufenzahl.", + floor_lights: "{n} Licht an", + floor_open: "{n} offen", + floor_persons: "{n} Pers.", + energy_consumption: "Verbrauch", + energy_grid_import: "Netzbezug", + energy_grid_export: "Einspeisung", + energy_solar: "Solar", + energy_battery: "Akku", + energy_tariff: "Tarif", + energy: "Energie", + energy_meter: "Zählerplatz", + energy_grid: "Netz (W, + = Bezug)", + energy_solar_sensor: "Solar-Erzeugung (W)", + energy_battery_sensor: "Akku-Leistung (W, + = Entladen)", + energy_battery_soc: "Akku-Ladestand (%)", + energy_tariff_sensor: "Tarif (z. B. €/kWh)", + energy_gas: "Gaszähler (optional)", + energy_water: "Wasserzähler (optional)", + energy_meters_hint: "Gas und Wasser stehen bei der Hausbilanz – in der Energieleiste und auf der Hauskarte: ein Sensor mit dem Durchfluss jetzt (m³/h, l/min) oder dem Zählerstand von heute.", + energy_gas_short: "Gas", + energy_water_short: "Wasser", + energy_invert: "Vorzeichen umkehren", + energy_hint: "Verbraucher sind platzierte Geräte mit Leistungssensor (W) – der Sensor selbst oder einer vom selben Gerät.", + energy_balance: "Energiebilanz", + energy_balance_hint: "Netz, Solar und Akku kommen von den Geräten im Plan: Stromzähler, Wechselrichter und Stromspeicher. Hier kannst du andere Sensoren wählen, Vorzeichen umkehren und den Hausverbrauch angeben.", + energy_rest: "Allgemein (Rest)", + energy_advanced: "Erweiterter Energiemodus", + energy_advanced_on: "Zwischenzähler nutzen", + energy_show_unmetered: "Ungemessenen Verbrauch am Zwischenzähler zeigen", + energy_show_unmetered_hint: "Das Schild eines Zwischenzählers zeigt dann den Verbrauch seiner Etagen und wie viel davon kein platziertes Gerät misst, z. B. „500 W · 450 W ungemessen“. Sonst zeigt es den Zählerwert.", + energy_advanced_hint: "Für Zwischenzähler, z. B. je Wohnung hinter einem Hauptzähler: Ein Stromzähler kann dann an einem anderen hängen und eigene Etagen versorgen. Aus = der erste Zähler ist der Netzanschluss, weitere sind Verbraucher.", + energy_consumption_sensor: "Hausverbrauch (W, sonst aus der Bilanz)", + energy_import_prefs: "Aus dem Energie-Dashboard übernehmen", + energy_import_done: "{n} Sensoren übernommen – bitte die Vorzeichen prüfen.", + energy_import_none: "Im Energie-Dashboard sind keine passenden Leistungssensoren (W) zu finden – bitte von Hand wählen.", + energy_import_failed: "Das Energie-Dashboard von Home Assistant ist nicht eingerichtet.", + tool_meter: "Zähler", + hint_meter: "Auf die Stelle des Zählers tippen", + presence: "Anwesenheit", + ble: "Bluetooth-Ortung", + ble_hint: "Orte einen Bluetooth-Tag (Schlüsselanhänger, Uhr, Handy) raumgenau: Du läufst mit ihm durch die Räume und nimmst jeden Raum auf. NextFloor vergleicht danach, wie stark ihn die Bluetooth-Scanner von Home Assistant (ESPHome-Proxys, Shelly-Geräte mit eingeschaltetem Bluetooth, Adapter am Server) hören. Je Tag entsteht ein Sensor mit dem Raumnamen als Zustand.", + ble_unavailable: "Die Bluetooth-Integration von Home Assistant läuft nicht. Ohne sie gibt es keine Scanner.", + ble_scanners: "{n} Bluetooth-Scanner in Home Assistant. Je mehr Scanner in verschiedenen Räumen, desto genauer.", + ble_add: "Tag oder Gerät hinzufügen", + ble_trackers: "Handys und Uhren (Private BLE Device)", + ble_devices: "Gefundene Bluetooth-Geräte", + ble_name: "Name (optional)", + ble_refresh: "Liste neu laden", + ble_add_button: "Hinzufügen", + ble_learn: "Räume lernen", + ble_close: "Schließen", + ble_spots: "{n} Aufnahmen", + ble_now: "Jetzt", + ble_unknown: "unbekannt", + ble_none_heard: "Kein Scanner hört den Tag gerade. Halte ihn nah an einen Scanner und warte kurz; ein Tag sendet nur alle paar Sekunden.", + ble_no_address: "Dieses Handy oder diese Uhr hat gerade keine bekannte Adresse. Prüfe in Home Assistant die Integration „Private BLE Device“.", + ble_one_scanner: "Nur ein Scanner hört den Tag. Zum Unterscheiden von Räumen braucht es mindestens zwei, besser drei oder mehr.", + ble_learn_room: "Raum aufnehmen", + ble_record: "Aufnehmen ({s} s)", + ble_recording: "Nimmt auf … noch {s} s", + ble_forget_room: "Raum vergessen", + ble_learn_hint: "Wähle den Raum, drücke Aufnehmen und geh mit dem Tag in der Hand langsam durch den ganzen Raum, auch in die Ecken. Aufnehmen erneut ersetzt den Raum. Lerne alle Räume, in denen du den Tag orten willst.", + ble_sensor_hint: "Der Sensor „{name}“ (Gerät NextFloor) zeigt den Raum. Unter Anwesenheit kannst du ihn als Raum-Sensor einer Person wählen.", + presence_hint: "Raumsensor je Person (z. B. ESPresense, Bermuda): sein Zustand nennt den Raum oder Bereich.", + presence_sensor: "Raumsensor", + presence_room: "Standardraum", + presence_room_none: "– keiner –", + presence_add: "Weitere Entität (Hilfsschalter, Tracker)", + no_persons: "In Home Assistant gibt es keine Personen.", +}; + +type Key = keyof typeof DE; + +const EN: Record = { + view: "3D", + editor: "Editor", + all_floors: "All floors", + outside_area: "Outside", + outside_area_hint: "All devices outside at a glance: in the garden, outside the rooms, and what belongs to Outside (a weather station on the roof, say).", + device_outside: "Belongs to Outside", + device_outside_hint: "The device does not count for the room under it (a weather station on the roof) and is listed in the Outside panel.", + no_building: "No floor plan yet.", + no_building_admin: "No floor plan yet. Draw your first floor in the editor.", + no_rooms_admin: "The floors exist, but there is no room yet. Walls alone are not enough: draw at least one room in the editor with “Rectangle” or “Free form”.", + open_editor: "Open editor", + loading: "Loading …", + load_error: "Loading failed", + saving: "Saving …", + saved: "Saved", + save_error: "Saving failed", + save_failed_detail: "Saving failed: {error}. Your changes are kept in this browser.", + needs_restart: "A new version of NextFloor ({frontend}) is installed, but Home Assistant still runs {version}. Please restart Home Assistant – until then saving may fail.", + needs_reload: "This page still shows NextFloor {frontend}, Home Assistant already has {backend}. Please reload the page; in the companion app: Settings → Companion app → Reset frontend cache.", + reload_page: "Reload", + needs_restart_old: "A new version of NextFloor is installed, but Home Assistant still runs an older one. Please restart Home Assistant – until then saving fails.", + draft_found: "Unsaved changes from {time} found.", + draft_restore: "Restore and save", + draft_discard: "Discard", + walls_auto: "Tall walls", + walls_cut: "Cut", + walls_slope: "Sloped", + walls_slope_hint: "Walls cut on a slope: half height in front, full height at the back – like a doll's house, turns with the camera", + walls_solid: "Solid", + walls_solid_hint: "Solid walls in their colours instead of glass (colours: editor → settings, per room in the room)", + wall_paint_outside: "Wall colour outside", + wall_paint_inside: "Wall colour inside", + furn_color_body: "Furniture colour body", + furn_color_wood: "Furniture colour wood", + furn_color_fabric: "Furniture colour fabric", + furn_color_white: "Furniture colour white", + furn_color_metal: "Furniture colour metal", + furn_color_dark: "Furniture colour dark", + furn_color_hint: "Furniture is built from a few materials, the pieces from the furniture builder and the packs too. Here each material gets a colour for the whole house; a card can set its own. They show most in the Neon look; Day and Blueprint only tint with them.", + wall_paint_room: "Wall colour inside (this room)", + wall_paint_floor: "Wall colour outside (this floor)", + wall_paint_hint: "Used in the 3D view “Solid”.", + wall_paint_default: "Default", + card_solid_walls: "Solid walls (in their colours)", + reset_view: "Overview", + back: "Back", + floor: "Floor", + floors: "Floors", + add_floor: "Add floor", + floor_from_ha: "Floors from Home Assistant:", + floor_empty: "Empty floor", + level: "Level {n}", + ha_floor: "Floor in Home Assistant", + floor_layer: "Layer (can be shown and hidden)", + floor_power: "Floor meter (power)", + floor_power_hint: "A power sensor for this floor alone (a sub-meter, a flat). Its value shows on the floor label and, in this floor's view, on the house card with its share of the house's use.", + floor_power_share: "{n} % of the house", + living_area: "Living area {living}", + room_living: "Counts as living area", + living_area_none: "No living area · floor {floor}", + living_area_low: "Living area {living} (floor {floor}, of which {low} below 2 m)", + living_area_hint: "Counted like the German Wohnflächenverordnung: the floor inside the walls, in full from 2 m clear height, half between 1 and 2 m (under slopes), not at all below 1 m. A guide value, not a survey.", + living_area_floor: "Living area: {floor}", + living_area_floor_house: "Living area of this floor: {floor} · whole house: {house}", + print_plan: "Print plan / PDF", + print_plan_hint: "Every floor as a clean plan with measurements and areas, and a table of the areas – to print, or save as PDF from the print dialog.", + print_title: "Floor plan", + print_room: "Room", + print_floor_area: "Floor area", + print_living: "Living area", + print_low: "below 2 m", + print_total: "Total", + print_blocked: "The print window was blocked – please allow pop-ups for Home Assistant.", + check_open: "Check the plan", + note: "Note", + note_add: "Note here", + note_text: "Text", + note_placeholder: "e.g. \"change the filter\" or \"fuse 12\"", + note_due: "Due on", + note_height: "Height above the floor (m)", + note_height_hint: "Where the pin floats in the 3D view: 1.3 m is eye level, higher for something under the ceiling (a shutoff valve, a hatch).", + note_photo_upload: "Add a photo", + note_photo_hint: "The photo shows when the note is tapped in the 3D view, e.g. what the valve looks like.", + note_due_hint: "From that day on the pin turns orange.", + note_is_due: "This note is due.", + keys_title: "Editor keys", + keys_undo: "Undo", + keys_redo: "Redo", + keys_duplicate: "Duplicate the room", + keys_delete: "Delete the selection", + keys_nudge: "Move the selection one grid step", + keys_nudge_10: "… by 10 cm", + keys_nudge_1: "… by 1 cm", + keys_rotate: "Turn furniture by 90° (Shift: back)", + keys_lock: "Fix or free furniture, a device or a roof section", + keys_close_shape: "Close the free shape", + keys_escape: "Cancel, leave the tool, clear the selection", + keys_straight: "While drawing: straight lines", + keys_sheet: "This sheet", + tour_title: "First steps", + tour_1_title: "Draw the rooms", + tour_1: "Draw the rooms with \"{rect}\" or \"{free}\"; the walls come by themselves. Give each room its Home Assistant area – then NextFloor finds its devices. With areas already set up, \"{rooms}\" in the floor form adds them all at once.", + tour_2_title: "Doors and windows", + tour_2: "\"{opening}\" puts them on a wall. Link their contact or blind – in 3D they then open and close with it, and open windows tell you.", + tour_3_title: "Furniture and devices", + tour_3: "\"{furniture}\" opens the library – or build your own pieces in the 🛠️ furniture studio. Select a room and the devices of its area are listed below, ready to place; lamps then shine in the colour of their light.", + tour_4_title: "Look and check", + tour_4: "\"{split}\" shows your house while you draw; at the top you switch to the 3D view. \"{check}\" lists what is still missing – and ? shows the keys at any time.", + tour_next: "Next", + tour_back: "Back", + tour_done: "Let's go", + tour_skip: "Skip", + check_open_hint: "Lists what is missing or off in the plan, with a fix in one tap.", + check_title: "Plan check", + check_all_good: "All good – nothing found.", + check_hint: "{n} points found. Blue buttons change the plan (undo works as always), the others show the place.", + check_room_no_area: "\"{room}\" has no Home Assistant area: its devices are not found.", + check_room_no_area_named: "\"{room}\" has no area – the free area \"{area}\" has the same name.", + check_areas_unplaced: "{n} areas of this floor have no room yet: {names}", + check_devices_unplaced: "\"{room}\": {n} devices of the area are not in the plan yet.", + check_rooms_overlap: "\"{a}\" and \"{b}\" overlap.", + check_opening_off_wall: "A door or window in \"{room}\" is not on a wall.", + check_entity_missing: "{n} device pins point to entities Home Assistant no longer knows ({ids}).", + check_furniture_entity_missing: "A piece of furniture is linked to {id} – that entity no longer exists.", + check_battery_low: "Battery low: {name} ({level} %)", + battery_low_n: "Battery low: {names}", + check_standby: "{name} draws {w} W while off – about {cost} a year.", + check_fix_show: "Show", + check_fix_ignore: "Ignore", + check_show_devices: "Look at the {n} devices", + check_ignore_all: "Ignore all {n}", + check_reset_ignored: "Check the {n} ignored devices again", + check_fix_set_area: "Link \"{area}\"", + check_fix_add_rooms: "Add the rooms", + check_fix_place: "Place {n}", + check_fix_remove: "Remove {n}", + floor_layer_hint: "This floor is no storey but a layer – all the trees or the decoration, say. The 3D view shows an eye at the top that shows or hides it on each device.", + no_ha_floor: "– none –", + area_rooms: "Add rooms from HA areas ({n})", + area_rooms_hint: "Adds a room (4 × 3 m) for each area of this floor – then drag it into place and adjust the corners", + floor_name: "Name", + elevation: "Elevation (m)", + floor_shift: "Shift the floor (m)", + floor_shift_apply: "Shift", + floor_shift_hint: "Moves every room, furniture item, device, outdoor area, free wall and the background image of this floor by X and Z. Roof sections stay.", + height: "Ceiling height (m)", + cut_height: "Cut height (m)", + delete_floor: "Delete floor", + floor_copy: "Duplicate floor", + floor_copy_hint: "The copy goes on top of the house with all rooms, walls, doors and windows. Rooms and the floor lose their link to Home Assistant, furniture its entities; energy devices stay on the old floor.", + floor_copy_furniture: "Take the furniture along", + floor_copy_devices: "Take the device pins along", + floor_copy_devices_hint: "The same entity then shows on both floors.", + floor_copy_outdoor: "Take the outdoor areas along", + floor_copy_make: "Make the copy", + floor_copy_name: "{name} (copy)", + furn_to_floor: "Move to floor", + furn_to_floor_hint: "The item moves to the same spot on the chosen floor.", + delete_floor_confirm: "Delete floor “{name}” with all its rooms?", + move_up: "Move up", + move_down: "Move down", + default_floor: "Ground floor", + new_floor: "Floor {n}", + tool_select: "Select", + tool_rect: "Rectangle", + tool_polygon: "Free shape", + undo: "Undo", + redo: "Redo", + fit: "Show all", + room: "Room", + rooms: "Rooms", + room_name: "Name", + area: "Area", + no_area: "No area", + sub_area_add: "+ Area within the room", + sub_area_hint: "A part of the room with a Home Assistant area of its own but no walls – a reading corner, a shelf, a kitchenette in the living room. Its devices and sensors belong to this room.", + material: "Floor", + x: "X (m)", + z: "Y (m)", + width: "Width (m)", + depth: "Depth (m)", + points: "Corners", + delete_point: "Delete corner", + duplicate: "Duplicate", + delete: "Delete", + new_room: "Room {n}", + settings: "Settings", + pendant_shape: "Shape", + pendant_shade: "Shade", + paint_colour: "Paint colour", + pendant_globe: "Globe", + pendant_cone: "Cone", + pendant_drum: "Drum", + sofa_shape: "Shape", + sofa_straight: "Straight", + sofa_l: "L-shaped (mirror: other side)", + sofa_u: "U-shaped", + pkg_open: "Furnish …", + pkg_hint: "Furniture goes against the room's walls; lamps link to the area's lights. Adjust single items afterwards – Ctrl+Z takes it all back.", + pkg_done: "{n} items placed – Ctrl+Z takes it back.", + pkg_kitchen_row: "Kitchen row", + pkg_kitchen_row_desc: "Row on the back wall with fridge, oven, sink, dishwasher and stove, wall cabinet, dining table with pendant", + pkg_kitchen_l: "L-shaped kitchen", + pkg_kitchen_l_desc: "Rows at the back and left, kitchen island with bar stools", + pkg_bath: "Bathroom", + pkg_bath_desc: "Washbasin, WC, bathtub, washing machine, downlight", + pkg_bedroom: "Bedroom", + pkg_bedroom_desc: "Double bed with two nightstands, wardrobe, chest of drawers, ceiling light", + pkg_living: "Living room", + pkg_living_desc: "TV board, sofa, coffee table, rug, armchair, shelf, floor lamp, plant", + pkg_dining: "Dining room", + pkg_dining_desc: "Table with four chairs, sideboard, pendant", + pkg_office: "Office", + pkg_office_desc: "Desk with office chair, two shelves, ceiling light", + pkg_kids: "Kids' room", + pkg_kids_desc: "Single bed, desk, shelf, rug", + pkg_hall: "Hall", + pkg_hall_desc: "Coat rack, two downlights", + spots_place: "Place spots", + spots_type: "Lamp", + spots_cols: "Columns (left–right)", + spots_rows: "Rows (front–back)", + spots_add: "Place {n} lamps", + spots_placed: "{n} lamps placed.", + spots_hint: "All lamps follow the chosen light (e.g. spots on one dimmer). Afterwards each can be moved and linked to another light like any furniture.", + cancel: "Cancel", + backup: "Backup", + backup_history: "Restore points", + share_view: "Share a view", + share_view_hint: "Saves the house as a small file that opens in any browser without Home Assistant (through NextFloor's online demo) – to show it to family or a planner. Without devices and entities, like a template.", + share_view_title: "Our home in NextFloor", + share_view_needs_js: "This page needs JavaScript and an internet connection.", + share_view_file: "view", + share_view_done: "View saved – open the file in a browser or pass it on.", + version_save: "Save this state …", + version_save_hint: "Keeps the plan under a name (\"before the renovation\"). Named states stay when the automatic restore points go.", + version_name_prompt: "Name for this state (e.g. \"before the renovation\"):", + version_saved: "State \"{name}\" saved.", + version_compare: "Compare", + version_delete_confirm: "Delete \"{name}\"?", + version_same: "No difference to the plan.", + version_diff_n: "{n} differences to the plan as it is now:", + diff_floor_added: "Floor \"{name}\" added", + diff_floor_removed: "Floor \"{name}\" removed", + diff_room_added: "Room \"{name}\" added", + diff_room_removed: "Room \"{name}\" removed", + diff_room_renamed: "\"{detail}\" is now called \"{name}\"", + diff_room_reshaped: "\"{name}\" reshaped ({detail} m²)", + diff_opening_added: "{name} added ({detail})", + diff_opening_removed: "{name} removed ({detail})", + diff_furniture_added: "{name} added", + diff_furniture_removed: "{name} removed", + diff_furniture_moved: "{name} moved or changed", + diff_device_added: "Device {name} placed", + diff_device_removed: "Device {name} removed", + diff_device_moved: "Device {name} moved", + backup_none: "None yet. While editing, a restore point is kept at most every 10 minutes.", + backup_summary: "{rooms} rooms, {furniture} items", + backup_restore: "Restore", + backup_restore_confirm: "Restore the state of {time}? The current state is kept as a restore point.", + backup_restored: "Restored.", + backup_file: "File", + backup_export: "Export", + backup_export_share: "Share as template", + backup_export_share_hint: "Without areas, devices, sensors and images – for passing on to others.", + backup_import: "Import …", + backup_import_confirm: "Replace the whole plan with the file? The current state is kept as a restore point.", + backup_import_error: "The file is no NextFloor plan ({error}).", + backup_imported: "Imported.", + backup_hint: "Background images are not part of the file.", + backup_full: "Full backup", + backup_full_export: "Back up everything (plan, pictures, packs)", + backup_full_import: "Restore a full backup …", + backup_full_hint: "One file with the plan, every background and screen picture and the installed packs. On restore every pack is checked again; the licence key is not included.", + backup_full_confirm: "Replace the plan, the pictures and the packs with the backup? The current state stays as a restore point.", + backup_full_not_backup: "This is not a full NextFloor backup.", + backup_full_restored: "Backup restored: {packs} packs, {pictures} pictures.", + backup_full_skipped: "Skipped (could not be read): {packs}.", + export_name_full: "full", + device_confirm: "Ask before switching", + device_confirm_hint: "A tap in 3D, the quick menu and the room panel ask first. A double tap on the room leaves this device out.", + cover_confirm_hint: "Open, close and positions ask first in the quick menu and the room panel, and a swipe on the marker no longer moves the blind (it turns the view instead). Stop never asks.", + blind_kind: "Kind of blind", + blind_roller: "Roller shutter outside", + blind_venetian: "Venetian blind with slats", + blind_inside: "Roller blind inside", + cover2_entity: "Second blind (right half)", + cover_my: "Favourite position \"My\" (%, 0 = none)", + cover_my_go: "To the favourite position ({p} %)", + blind_hint: "A venetian blind turns its slats in 3D with the cover's tilt; a roller blind inside hangs behind the glass. A wide window can have a second blind for its right half. The favourite position shows as \"My\" in the quick menu: a blind with positions moves there, a Somfy RTS motor without feedback goes to its own My on stop.", + confirm_switch: "Really switch {name}?", + lock_confirm_unlock: "Really unlock {name}?", + gang_switch_one: "Switches", + furn_cover_entity: "Moves with", + furn_cover_hint: "The curtain, screen, awning or gate follows this cover entity (blind, curtain, awning, gate) and travels with it. A tap opens its menu (up, stop, down).", + furn_cover_inverted: "Reverse the direction", + furn_cover_inverted_hint: "For an awning or curtain that moves the opposite way in the plan than in reality: out then shows in, and the other way round.", + gang_switch: "Button {n} switches", + gang_socket_one: "Socket powered by", + gang_socket: "Socket {n} powered by", + gang_switch_hint: "A button glows while its light is on (in its colour). A tap switches it; with several buttons a small menu asks which. The same entity may sit on several switches.", + gang_socket_hint: "A socket glows green while its switch is on – brighter the more it draws. A tap switches it; with several, a small menu asks which.", + lock_confirm_lock: "Lock {name}?", + opening_lock: "Smart lock", + opening_lock_hint: "A tap on the door locks or unlocks it (always asking first). While it is unlocked, its edge glows.", + split_handle_hint: "Drag: width of the plan and the 3D view", + wall_exterior: "Exterior wall (m)", + wall_interior: "Interior wall (m)", + grid: "Grid (m)", + units: "Show lengths in", + units_metric: "Metres", + units_imperial: "Feet and inches", + units_hint: "How lengths and areas appear in the plan, the forms and the wall view. Inputs stay in metres.", + background: "Template (floor plan image)", + background_upload: "Choose image …", + background_width: "Width in plan (m)", + background_opacity: "Opacity", + background_rotation: "Rotation (°)", + background_edit: "Move, scale and turn", + background_edit_done: "Done", + background_edit_hint: "While the mode is on: dragging the picture moves it, the handle at the bottom right scales it. Fit the picture to the scale first, then turn it.", + background_remove: "Remove template", + hint_select: "Tap a room to select · drag corners · “+” on an edge inserts a corner · arrow keys nudge · Del deletes · Ctrl+Z", + hint_rect: "Drag to draw a rectangle", + hint_polygon: "Place corners · tap the first corner or press Enter to close · Esc cancels", + hint_empty: "Add a floor first.", + area_m2: "{a} m²", + overlap_warning: "Rooms overlap – walls there are incomplete.", + read_only: "Only administrators can edit the floor plan.", + side_failed: "This form could not be shown ({error}). The plan stays usable. Please report the text in a GitHub issue.", + mat_wood: "Wood", + mat_oak: "Oak", + mat_tiles: "Tiles", + mat_carpet: "Carpet", + mat_stone: "Stone", + mat_concrete: "Concrete", + card_name: "NextFloor", + card_description: "Your home in 3D (neon).", + stats: "{calls} draw calls · {tris} triangles", + stats_fps: "{fps} fps (slowest frame {ms} ms)", + stats_idle: "At rest (0 fps)", + stats_busy_floors: "floors", + stats_busy_openings: "doors/windows", + stats_busy_flash: "flash", + stats_busy_roof: "roof", + stats_busy_flow: "power flow", + stats_busy_effect: "colour effect", + stats_busy_robot: "robot", + stats_busy_orbit: "camera turn", + stats_busy_tint: "room tint", + stats_low: "tablet level, pixel ratio {r}", + stats_full: "full level, pixel ratio {r}", + floors_apart: "Apart", + floors_stacked: "Stacked", + roof_keep: "Roof stays", + roof_keep_hint: "The roof stays on the house while zooming in instead of lifting and fading out", + floor_rooms_one: "1 room", + floor_rooms: "{n} rooms", + quality: "Quality", + quality_auto: "Auto", + quality_low: "Tablet", + quality_high: "High", + state_on: "On", + state_off: "Off", + state_open: "Open", + state_closed: "Closed", + state_opening: "Opening", + state_closing: "Closing", + state_playing: "Playing", + state_paused: "Paused", + state_idle: "Idle", + state_locked: "Locked", + state_unlocked: "Unlocked", + state_detected: "Detected", + state_clear: "Clear", + state_unavailable: "Unavailable", + state_heat: "Heat", + state_cool: "Cool", + state_auto: "Auto", + state_heat_cool: "Heat/cool", + state_dry: "Dry", + state_fan_only: "Fan", + devices: "Devices", + devices_none_area: "Link the room to an area and its devices appear here.", + devices_none: "The area has no suitable devices.", + devices_place_all_n: "Place all {n} …", + devices_place_all_confirm: "Put {n} devices into the room at once? (Ctrl+Z or “Undo” takes them all back in one step.)", + devices_src_area: "This area", + devices_src_other: "Other areas", + devices_src_none: "No area", + panel_hide: "Hide from the room panel", + panel_unhide: "Show in the room panel again", + panel_state_hide: "Hide the state in the room panel (e.g. a cover that only reports \"unknown\")", + panel_state_show: "Show the state in the room panel again", + devices_place: "Place", + devices_remove: "Remove", + devices_hint: "Placed devices appear in 3D. Drag them in the plan to move them.", + panel_lights: "Lights", + panel_covers: "Covers", + panel_climate: "Heating", + panel_media: "Media", + panel_switches: "Switches", + panel_sensors: "Sensors", + panel_scenes: "Scenes & scripts", + panel_announce: "📢 Announcement", + announce_placeholder: "Your own message …", + announce_send: "Say it", + announce_sent: "Said: \"{message}\"", + announce_failed: "Announcement failed: {error}", + announce_phrase_1: "Dinner is ready!", + announce_phrase_2: "Time for bed!", + announce_phrase_3: "Please come down!", + announce_phrase_4: "We are leaving soon!", + announce_phrase_5: "The dog needs to go out!", + state_recording: "Recording", + state_streaming: "Streaming", + panel_all_off: "All off", + readable: "Easy to read", + readable_hint: "Stronger contrast and larger text – for wall tablets and anyone who reads better that way.", + plain: "Floor plan only", + plain_hint: "Shows only walls, doors, windows and stairs, without furniture. Devices and their pins stay.", + right_back: "Right click = back", + right_back_hint: "A short right click in the 3D view goes one step back: from the room to the floor, from the floor to the house (like a double tap on empty space). Dragging with the right button still pans the view.", + stl: "3D print (STL)", + stl_hint: "Saves the house as an STL file (walls, floors, furniture and outdoor areas of every floor) for 3D printing, at 1:100 (one metre becomes 10 mm). Windows, lights and the roof are not in it; a slicer repairs the file if needed.", + card_plain: "Floor plan only", + card_rooms: "Only these rooms", + card_rooms_hint: "The card shows only the ticked rooms with their furniture, devices, doors and windows (for a tablet in the kitchen, say). Nothing ticked: the whole plan.", + card_templates: "Card templates", + card_templates_hint: "Set up a dashboard card once here (with the card's own settings) and give just its name on each tablet: `template: kitchen_tablet`. Changes here reach every card that uses the template; what stands on the card itself wins over the template.", + template_name: "New template (name)", + template_add: "Create template", + template_reload: "Reload screens with this template", + template_reload_all: "Reload all screens", + template_use: "On the dashboard card: `template: {name}`", + card_template: "Card template", + card_template_none: "none (this card only)", + card_readable: "Easy to read", + all_off_n: "Everything off ({n})", + all_off_hint: "Switches off the room's lights, switches, fans and media; it can be undone for ten seconds.", + all_off_done: "Everything off.", + all_off_undo: "Undo", + all_off_floor: "Everything off on {floor} ({n} devices), undo for ten seconds", + mood_save: "Save mood", + mood_save_hint: "Keeps how the room's lamps shine right now as a mood – a tap on it sets them again later, \"→\" carries it to another room.", + mood_new: "Mood", + mood_set: "Set this mood", + mood_carry: "Carry over to another room", + panel_all_on: "All on", + view_options: "View: quality, look, markers, FPS", + panel_all_open: "All up", + panel_all_close: "All down", + central: "Central: all lights, blinds and favourites", + central_house: "Whole house", + central_lights: "Lights", + central_covers: "Blinds", + central_on: "On", + central_off: "Off", + central_open: "Up", + central_close: "Down", + central_sure: "Sure?", + central_favorites: "Favourites", + central_no_favorites: "No favourites yet. Set scenes, scripts and switches in the editor under \"Favourites\".", + card_central: "Star with the central menu", + card_central_hint: "All lights and blinds of the floor or the house and the favourites from the editor.", + favorites: "Favourites", + favorites_hint: "Scenes, scripts, automations, buttons and switches for the central menu (star) of the 3D view – party, presence simulation, shading, watering.", + favorites_add: "Add a favourite", + favorite_floor: "Which floor this favourite shows on", + favorite_all_floors: "All floors", + outside_hidden: "Outside: hide devices", + outside_hidden_hint: "Devices the Outside panel should not show (they stay in the plan).", + outside_hidden_add: "Hide a device", + outside_view_hint: "View for Outside: turn the 3D preview to the garden and use it. Opening Outside then flies the camera there.", + outside_view_set: "Use this view for Outside", + outside_view_reset: "Reset the Outside view", + room_facts: "Room panel: facts shown", + room_fact_sun: "Sun hours", + room_fact_comfort: "Comfort", + room_fact_air: "Airing hint", + room_fact_circuits: "Circuits", + background_handles_hint: "The picture now has handles like a piece of furniture: drag moves it, the lower right corner scales it, the round handle on top turns it (Shift for 15° steps). When it fits, tap \"Done\" – then it stays put.", + background_fixed_hint: "The picture stays put, you can draw over it. To adjust it, tap \"Move, scale and turn\".", + bg_level: "Straighten", + bg_level_cancel: "Cancel straightening", + bg_level_first: "Tap the start of a wall in the picture that should run straight (horizontal or vertical).", + bg_level_second: "Now tap the end of that wall – the picture turns to fit.", + bg_ruler: "Scale with a ruler", + bg_ruler_cancel: "Cancel the ruler", + bg_ruler_first: "Tap the start of a stretch of known length in the picture – e.g. a dimensioned wall.", + bg_ruler_second: "Now tap the end of the stretch.", + bg_ruler_length_hint: "Measured in the plan: {m} m. Enter the real length and the picture is scaled to fit.", + bg_ruler_length: "Real length (m)", + bg_ruler_apply: "Apply the scale", + thumbs_fold: "Fold the floor pictures into buttons", + thumbs_show: "Show the floor pictures again", + room_start_view: "View as this room's start", + room_start_view_hint: "When you tap the room in 3D, the camera flies to exactly the view the 3D pane on the right shows now – angle, zoom and framing. Turn on 3D beside first, turn and zoom in on the room, then tap.", + room_start_view_reset: "Remove the room's start view (from above again)", + room_start_view_need_pane: "Turn on \"3D beside\" first, then turn and zoom the room the way it should open.", + floor_start_view: "View as this floor's start", + floor_start_view_hint: "This floor opens in 3D the way the 3D pane on the right stands right now – e.g. the ground floor from the front and the upper floor from the back. Turn on 3D beside first, turn it, then tap.", + floor_start_view_reset: "Remove the floor's start view (like the house again)", + floor_start_view_need_pane: "Turn on \"3D beside\" first and turn the floor the way it should open.", + ambilight: "Glow behind the TV (%)", + ambilight_hint: "How strongly it glows behind the TV while it plays. 0 switches it off (for example if you have LED strips on the TV), 100 is the usual strength.", + sound_rings: "Sound rings (%)", + sound_rings_hint: "How large the rings around the speaker grow while it plays. 0 switches them off, the picture and the glow stay; 100 is the usual size. The size also follows the speaker's volume: quieter means smaller.", + glow_scale: "Glow in 3D (%)", + light_effects: "Effect animations in 3D", + light_effects_hint: "Map exact HA effect names only. Unmapped effects keep the static HA colour. Changes nothing in Home Assistant.", + light_effects_enabled: "Allow animations for this lamp", + light_effect_unmapped: "Unmapped (static)", + light_effect_add: "Add exact effect name", + light_effect_name_limit: "The exact effect name must contain 1 to 255 characters. It will not be shortened.", + light_effect_count_limit: "At most 100 mappings. Remove an existing entry first.", + light_effect_exists: "This effect name is already mapped. Its existing mapping is preserved.", + light_animation_none: "Static", + light_animation_rainbow: "Rainbow (replaces colour)", + light_animation_pulse: "Pulse (intensity)", + light_animation_flicker: "Flicker (intensity)", + glow_scale_hint: "How strongly the lamp glows in 3D: below 100 % tones down bright LED strips so the room does not burn out; above 100 % makes a weak lamp glow more. Switches nothing in Home Assistant.", + vehicle_to_spot: "Turn into a parking spot", + vehicle_to_spot_hint: "A vehicle as plain furniture always stands there. As a parking spot it appears only while a sensor reports the car, and that is where the car device is linked (charge, range, lock, climate).", + as_furniture: "Show as furniture", + as_furniture_hint: "Replaces the pin by a furniture item in the same place, linked to this device – a speaker for a media player, a lamp for a light. Ctrl+Z takes it back.", + as_furniture_pick: "Pick furniture …", + as_device: "Back to a device pin", + as_device_hint: "Replaces the furniture by the plain pin of its device in the same place.", + presets: "Stations and playlists (Sound)", + presets_hint: "Shown in every speaker's quick menu under \"Play\", next to the player's sources. For an Echo (Alexa Media Player): type SPOTIFY, AMAZON_MUSIC or TUNEIN and as content what you would say (\"Rock Antenne\"). For Sonos, Music Assistant and others: type music or url with a stream address or a URI.", + preset_type: "Type", + preset_type_hint: "media_content_type of play_media, e.g. music, url, playlist, SPOTIFY, AMAZON_MUSIC, TUNEIN", + preset_content: "Content", + preset_content_hint: "media_content_id: stream URL, URI (spotify:playlist:…) or, for Alexa, a search phrase", + preset_speakers: "Only on these speakers (none = on all)", + media_play: "Play", + media_pause: "Pause", + media_previous: "Previous", + media_next: "Next", + media_volume: "Volume", + media_sources: "Sources", + preset_add: "Station or playlist", + own_buttons: "Own buttons", + own_buttons_hint: "Shown in the central menu (star) below the favourites: open a dashboard path, show an entity's details, call a service, or open a browser_mod popup with your own card.", + own_alerts: "Own warnings", + circuits: "Fuse box", + circuits_hint: "The circuits with the rooms they feed. The room panel names them, and the search finds them (\"F12\").", + circuit_name: "Name", + circuit_new: "New circuit", + circuit_add: "Add a circuit", + circuit_add_room: "Add a room", + own_alerts_hint: "A line in the warning bar of the 3D view while an entity is in a state – \"Water tank empty\" from the robot vacuum, \"Dishwasher done\". Several states with commas; for numbers <20 or >80.", + own_alert_entity: "When …", + own_alert_state: "… is in state (empty = on)", + own_alert_text: "… then this warning", + own_alert_color: "Colour", + own_alert_tap: "A tap", + own_alert_tap_info: "opens the details", + own_alert_tap_toggle: "switches the entity", + own_alert_tap_room: "jumps to the room", + own_alert_house: "Whole house", + own_alert_new: "New warning", + own_alert_add: "Add a warning", + today: "Today", + tomorrow: "Tomorrow", + today_days: "Days on the \"Today\" card", + today_days_one: "Today only", + today_days_n: "{n} days", + forecast: "Weather forecast", + forecast_hint: "A small card with the next days of the weather entity (settings): the weather, high and low, and rain. It sits in a top corner of the 3D view, top right below the \"Today\" card.", + forecast_days: "Forecast", + forecast_off: "Off", + forecast_corner: "Corner", + today_none: "Nothing on today.", + today_calendars: "Calendars for \"Today\"", + today_calendars_hint: "The appointments of these calendars show top right in the 3D view on the \"Today\" card, with the bins collected today or tomorrow. A tap on its title folds the card.", + own_button_state: "Lights up while … is on (optional)", + own_button_label: "Label", + own_button_action: "Action", + own_button_new: "New button", + own_button_add: "Own button", + own_action_navigate: "Open a path", + own_action_more_info: "Entity details", + own_action_service: "Call a service", + own_action_fire_dom_event: "fire-dom-event (browser_mod)", + own_target_navigate: "Path", + own_target_more_info: "Entity", + own_target_service: "Service (domain.service)", + own_data: "Data (JSON)", + own_data_hint: "For a service its data, for fire-dom-event the event's content, e.g. {\"browser_mod\": {\"service\": \"browser_mod.popup\", \"data\": {…}}}.", + own_data_bad: "Not a valid JSON object.", + panel_no_area: "This room is not linked to an area. You can link it in the editor.", + panel_empty: "No devices of this room are in the plan. In the editor, place devices or pick them for the room panel with ☆.", + close: "Close", + panel_fold: "Fold away (the room stays in view)", + panel_unfold: "Open again", + brightness: "Brightness", + color_temp: "Colour temperature", + color: "Colour", + position: "Position", + cover_open: "Open", + cover_stop: "Stop", + cover_tilt: "Slats", + cover_tilt_open: "Slats open", + cover_tilt_close: "Slats closed", + cover_close: "Close", + target_temp: "Target", + current_temp: "Current", + temp_down: "Cooler", + temp_up: "Warmer", + volume: "Volume", + play_pause: "Play/pause", + previous: "Previous", + next: "Next", + run: "Run", + details: "Details", + hold_hint: "Tap toggles · long press opens details", + tool_opening: "Doors & windows", + tool_furniture: "Furniture", + qm_off: "Off", + find: "Search", + find_placeholder: "Where is …? Device or room", + find_none: "Nothing found", + swipe_off: "Off", + panel_pin: "Show in the room panel", + panel_unpin: "Don't show in the room panel", + devices_panel_hint: "The room panel shows the devices in the plan. ☆ adds a device to the room panel without placing it.", + card_section_view: "View", + card_size: "Size", + card_size_fixed: "Fixed height", + card_size_fill: "Fill the screen", + card_fill_hint: "Works best in a dashboard view of the type “Panel (single card)” – the card then takes all the space.", + card_controls: "Switches in the card", + card_floor_thumbs: "Floors as miniatures", + card_floor_thumbs_hint: "Small pictures of the floors at the side – tap one to switch", + card_floor_thumbs_hint_start: "The chosen floor is then where the card starts – the pictures at the side switch to the others", + card_room_names: "Show room names", + card_section_kiosk: "Wall tablet (kiosk)", + card_section_features: "Features", + card_weather_plan: "as set in the plan", + card_pro_hint: "Motion trail and camera wall belong to the cameras: the trail shows the last half hour, the wall every camera of the plan.", + card_idle_return: "Back to the start view after", + card_idle_off: "Never", + card_idle_min: "{n} min without a touch", + card_idle_hint: "After the wait the card closes the room and shows the start view again.", + card_night: "Night dimming", + card_night_off: "Off", + card_night_sun: "By the sun", + card_night_time: "Time range", + card_night_range: "Time range (e.g. 22:00-06:00)", + card_idle_orbit: "Camera turn as screensaver", + card_idle_orbit_hint: "After the return the view turns slowly until someone touches the tablet", + card_dashboard: "Button to a dashboard (path)", + card_dashboard_label: "Label of the button", + card_dashboard_hint: "A button at the top right of the card opens the dashboard or view with this path, e.g. /lovelace/home or /dashboard-house/0. Without a label it shows ⌂.", + card_alerts: "Show warnings", + card_alerts_hint: "Smoke, gas, CO, water, alarm panel and windows open in the rain: the room pulses, a note appears at the top", + card_alert_jump: "Jump to the room of a new warning", + card_alert_jump_hint: "The view switches to the floor and room of the warning by itself", + card_scenes: "Scene buttons in the room", + card_scenes_hint: "Scenes and scripts of the area as buttons under the 3D view while a room is selected", + card_sensor_bar: "Own sensors at the top", + card_sensor_bar_hint: "The sensors chosen in the editor (Settings) at the top left of the card", + card_central_open: "Star menu open and large", + card_central_open_hint: "Favourites and own buttons stand open from the start, a size larger", + card_keep_camera: "Keep the camera when switching floors", + card_keep_camera_hint: "The same side, height and distance on every floor", + card_today: "\"Today\" card", + card_today_hint: "Today's appointments and the bins due, top right", + card_announcements: "Announcements", + card_announcements_hint: "Announcements (action \"NextFloor: Announcement\") show big on the card, with a chime, and are spoken", + weather_short: "Weather", + time_of_day: "Time of day", + time_of_day_hint: "Shows sun, light, shadows and look at another time of today. Tap again to go back to now.", + menu_open: "Menu open", + menu_open_hint: "The star menu with favourites and own buttons stands open from the start on this device, a size larger – for a wall tablet that mostly runs scenes.", + keep_camera: "Keep camera", + keep_camera_hint: "Switching floors keeps the camera on the same side, height and distance instead of fitting the new floor from the start side.", + view_zoom: "Zoom", + view_zoom_hint: "How close the fitted views come – on small tablets the house looks larger.", + weather_entity: "Weather entity", + weather_effects: "Weather effects in 3D", + card_weather_density: "Amount of rain and snow", + card_weather_density_hint: "Fewer drops and flakes than the weather reports; clouds, fog and lightning stay", + rain_warning: "Warning: window open while it rains", + sun_patches: "Sunlight and shadows", + sun_patches_hint: "With north set, the sunlight from sun.sun falls through the windows as bright patches on the floor, and the house throws its shadow on the plot. Untick it to keep floor and plot free of sun patches and shadows.", + sun_arc: "Sun arc and compass", + sun_arc_hint: "Draws today's path of the sun as an arc over the plot, with a ring and the compass points on the ground (north in red). Needs your home's location in Home Assistant.", + weather_effect_rain: "Rain", + weather_effect_snow: "Snow", + weather_effect_fog: "Fog (greys the scene)", + weather_effect_clouds: "Clouds dim the sky and the sun", + weather_effect_lightning: "Lightning in storms", + weather_effect_sky: "Sun and moon in the sky", + weather_entity_hint: "Which weather entity drives the sky around the house. Automatic uses the first one found.", + weather_hint: "Weather at the house: rain and snow fall with the real wind, clouds drift over the plot with their shadows, lightning, fog, sun and moon", + card_weather: "Weather outside", + card_weather_hint: "Rain, snow, hail, clouds with shadows, lightning and fog from the first weather entity (weather_entity picks another); fewer particles on the tablet level", + alerts: "Warnings", + alert_smoke: "Smoke: {name}", + alert_gas: "Gas: {name}", + alert_co: "Carbon monoxide: {name}", + alert_water: "Water: {name}", + alert_alarm: "Alarm triggered", + alert_alarm_by: "Alarm set off by {cause}", + alert_alarm_pending: "Alarm pending", + alert_window_rain: "Window open in the rain: {name}", + alert_power_outage: "Power outage: {name}", + alert_contact_lost: "Contact not answering: {name}", + rain_sensor: "Rain sensor (own weather station)", + rain_sensor_inverted: "Invert rain sensor", + rain_sensor_inverted_hint: "For sensors that read off (or 0) when it rains and on when it is dry.", + outage_sensor: "Power outage sensor", + outage_hint: "A binary sensor of class power that is off, another binary sensor that is on, a state like \"off_grid\" or \"backup\", or a voltage below 50 V raise a warning for the whole house.", + contact_warning: "Warn when a door or window contact is unavailable", + contact_warning_hint: "When a contact has been unavailable for 10 minutes (empty battery, out of radio reach), the window looks shut in 3D although nobody knows. A note then names the contact. A restart of Home Assistant does not warn.", + night_lock_warning: "Warn at night when a door is not locked", + night_lock_warning_hint: "Between 10 pm and 6 am a note names the plan's door locks that stand unlocked.", + alert_unlocked_night: "Not locked: {name}", + motion_markers_active: "Show motion sensors only while they detect something", + motion_markers_active_hint: "Applies to motion, occupancy and presence sensors. A sensor whose marker is set to always show stays visible.", + room_double_tap: "Double tap on a room", + room_double_tap_hint: "A double tap on a room turns its lights off when one is on, otherwise all on. Devices set to ask first always stay out.", + room_double_tap_area: "Lamps in the plan and every light of the area", + room_double_tap_plan: "Only lamps in the plan", + room_double_tap_off: "Switch nothing", + card_room_double_tap_auto: "As set in the plan", + status_entities: "Own sensors at the top of the 3D view", + status_add: "Add a sensor", + status_entities_hint: "For example the outside temperature, the alarm or the air quality: they show at the top left with name and value, in an opened room too. A tap opens their details. Up to 12.", + announce_tts: "Text-to-speech for announcements", + announce_phrases: "Sentences for announcements (one per line)", + announce_phrases_hint: "Empty: the sentences that come with NextFloor. Announcements also exist as the action \"NextFloor: Announcement\" for automations – on the rooms' speakers and on every open NextFloor screen.", + opening_rain_warning: "Warn when it rains", + opening_light_well: "Light well in front", + sill_boards: "Sill and board", + sill_boards_auto: "Automatic", + sill_boards_none: "None", + sill_boards_inside: "Inside only", + sill_boards_outside: "Outside only", + room_names_short: "Room names", + floor_stack_short_dim: "Dimmed", + floor_stack_short_stacked: "Stacked", + floor_stack_short_single: "Alone", + size_short_w: "W", + size_short_d: "D", + size_short_h: "H", + import_error_not_json: "The file is no JSON.", + import_error_not_plan: "The file is no NextFloor plan.", + import_other_hint: "From Sweet Home 3D: import the .sh3d file here. Floors, rooms, doors, windows and free walls come over, furniture does not.", + import_sh3d_found: "Sweet Home 3D: {floors} floors, {rooms} rooms, {openings} doors and windows, {walls} free walls ({furniture} pieces of furniture are not taken over).", + import_dxf_found: "DXF: {rooms} rooms (closed polylines) and {walls} free walls (lines) on one floor.", + import_ifc_found: "In the IFC file: {floors} floors and {rooms} rooms (NextFloor draws the walls from the rooms).", + import_roomplan_found: "Room scan (RoomPlan): {rooms} rooms, {openings} doors and windows; {skipped} objects were not taken over (you place furniture yourself).", + import_error_roomplan_empty: "The room scan has no walls.", + import_error_ifc_empty: "The IFC file has no spaces (IfcSpace) with a footprint.", + import_error_dxf_empty: "The DXF file has no lines or polylines.", + import_error_sh3d: "This is not a Sweet Home 3D file that can be read (it needs Sweet Home 3D 5.3 or newer).", + import_error_sh3d_empty: "The Sweet Home 3D file has no rooms or walls.", + export_name_template: "template", + export_name_backup: "backup", + card_floor_stack: "Floors below", + floor_stack_dim: "Dimmed", + floor_stack_stacked: "Stacked (the house up to here)", + floor_stack_single: "Hidden (only this floor)", + card_control_walls: "Tall walls/cut", + card_control_floors: "Floors apart", + card_control_temperature: "Temperature", + card_control_humidity: "Humidity", + card_control_co2: "CO₂", + card_controls_hint: "Tall walls/cut, floors apart and temperature, humidity, CO₂ to switch", + controls_hide: "Hide the controls – only the 3D view remains", + nav_wrap: "Wrap the bar: every floor and room on several lines", + bars_unfold: "Switches", + nav_row: "Bar in one line (scrolls sideways)", + controls_show: "Show the controls again", + card_controls_hidden: "Start with the controls hidden", + card_controls_hidden_hint: "Only the 3D view; an eye at the bottom left brings bars, values and switches back", + card_controls_hide_after: "Hide the controls after", + card_hide_after_s: "{n} s without a touch", + card_fullscreen_button: "Full screen button", + card_fullscreen_button_hint: "Hides the dashboard around the card (e.g. on a wall tablet)", + fullscreen: "Full screen", + fullscreen_exit: "Exit full screen", + card_section_show: "Show", + card_floor: "Floor", + card_floor_house: "Whole house (tap a floor to open it)", + card_height: "Height (pixels)", + card_walls: "Walls", + card_quality_hint: "“Tablet” is the lightest setting – ideal for Fire tablets and other wall tablets.", + card_flows_switch: "Switch in the card", + card_flows_on: "Always on", + card_flows_off: "Always off", + holos: "Cards", + holos_hint: "Show or hide the live cards over the house (energy balance, car, media)", + card_energy: "Show energy values at the top", + card_room_panel: "Room details on tap", + card_room_buttons: "Room buttons", + card_room_buttons_hint: "A row with one button per room at the top of the card – tap one to open the room, like tapping it in the model", + card_room_panel_hint: "The room's lights and blinds in a side panel", + card_explode: "Pull floors apart in the house view", + card_roof_fade: "Fade the roof out while zooming in", + card_roof_fade_hint: "Off: the roof stays on the house even when the camera comes close.", + card_stats: "Performance display (frames per second)", + card_stats_hint: "To check how smoothly the card runs on the device", + packs: "Furniture packs", + lib_badge_light: "Lamp: links to a light and switches in 3D", + lib_badge_electric: "Electric: links to an entity and a power sensor (switching, pictures, consumption)", + lib_badge_hint: "Items with a symbol link to entities: lamps switch, screens show pictures, appliances show their consumption.", + care_bin_today: "Collected today", + care_bin_tomorrow: "Collected tomorrow", + care_bin_days: "In {n} days", + care_mail_yes: "Post is in", + care_mail_no: "Empty", + care_plant_thirsty: "Thirsty", + care_plant_ok: "Well watered", + care_time_left: "{time} left", + care_entity_bin: "Pickup date (sensor)", + care_entity_mail: "Post sensor", + care_entity_plant: "Soil moisture (sensor)", + care_thirsty_below: "Thirsty below (%)", + care_hint_bin: "A sensor with the next pickup: days, a date, \"today\"/\"tomorrow\" or the Waste Collection Schedule integration. The bin glows the day before and on the day.", + care_hint_mail: "A sensor that reports post in the box (a contact on the flap, say). The mailbox glows then.", + care_hint_plant: "A moisture sensor in the soil. Below the threshold the plant glows and says it is thirsty.", + lib_cat_lights: "Lights", + lib_cat_seating: "Seating", + lib_cat_tables: "Tables", + lib_cat_storage: "Cabinets & shelves", + lib_cat_beds: "Beds", + lib_cat_kitchen: "Kitchen", + lib_cat_appliances: "Appliances", + lib_cat_bath: "Bathroom", + lib_cat_media: "TV & audio", + lib_cat_office: "Office", + lib_cat_tech: "Tech", + lib_cat_climate: "Heating & climate", + lib_cat_energy: "Energy", + lib_cat_garden: "Garden & terrace", + lib_cat_plants: "Plants", + lib_cat_kids: "Kids", + lib_cat_fitness: "Fitness", + lib_cat_pets: "Pets", + lib_cat_workshop: "Workshop & garage", + lib_cat_music: "Music & studio", + lib_cat_season: "Season & decoration", + lib_cat_pictures: "Pictures & frames", + lib_cat_vehicles: "Vehicles", + lib_cat_building: "Stairs & building parts", + lib_cat_decor: "Decoration & more", + lib_favourites: "Favourites", + lib_recent: "Recently used", + lib_for_room: "Fits {room}", + lib_all_rooms: "Show all rooms", + lib_linkable: "linkable", + lib_lit: "lit", + lib_outdoor: "outdoor", + lib_fav_add: "Add to favourites", + lib_fav_remove: "Remove from favourites", + lib_sizes: "Sizes", + feature_name_energy: "Energy flow", + ext_tab: "Extensions", + ext_title: "Extensions", + models: "Your own 3D models", + models_hint: "For some vehicles NextFloor can show a real 3D model if you own one. Choose the file (.glb) here: NextFloor turns it the right way round, makes it lighter, marks the paint and stores it on your Home Assistant. Without a model the vehicle looks as it did before.", + models_licence: "The files are yours and stay on your Home Assistant. NextFloor ships no models; please make sure your model's licence lets you use it in your own installation.", + model_add: "Add a model …", + model_replace: "Replace the model …", + model_remove: "Remove", + model_present: "in place", + model_missing: "none yet", + model_remove_confirm: "Delete the model “{id}” from Home Assistant?", + model_removed: "Model “{id}” deleted.", + model_uploaded: "Model “{id}” stored ({size}). Reload the panel to see it.", + model_upload: "Store on Home Assistant", + model_info: "{triangles} triangles, {size} m", + model_front: "Front", + model_front_hint: "Turn the model until its front faces the viewer (towards the lower left in the picture).", + model_paint: "Paint (the colour you pick in the editor)", + model_paint_preview: "Colour in the preview", + model_detail: "Level of detail", + model_detail_light: "Light (tablet)", + model_detail_normal: "Normal", + model_detail_fine: "Fine", + model_result: "Result: {triangles} triangles, {size}", + model_error_not_glb: "This is not a .glb file (binary glTF). Export the model as “glTF binary”.", + model_error_compressed: "The file is compressed (Draco, Meshopt or KTX). Export it without compression.", + model_error_empty: "The file contains nothing three-dimensional.", + model_error_unreadable: "The file cannot be read: {detail}", + model_error_too_large: "The file is larger than {max}. Choose a lower level of detail.", + model_upload_forbidden: "Only administrators may upload models.", + model_upload_too_large: "Home Assistant accepts no files over {max}. Choose a lower level of detail.", + model_upload_not_glb: "Home Assistant refused the file (not a binary glTF).", + model_upload_bad_id: "The model id is not valid.", + model_upload_other: "Uploading did not work: {detail}", + ext_intro: "Import your own furniture packs, upload your own 3D models and add plugins here.", + plugin: "plugin", + plugins_title: "Plugins", + plugins_intro: "Plugins add your own light animations, devices and cards in the room panel. Enter a plugin's address (a .js file in /config/www, i.e. /local/…, from HACS /hacsfiles/…, or https://…).", + plugins_docs: "How to write a plugin", + plugins_warning: "Plugins run with the same rights as NextFloor in your browser. Only use plugins from sources you trust.", + plugins_off: "off", + plugins_error: "error", + plugins_loading: "loading …", + plugins_nothing_registered: "loaded, but registered nothing", + plugins_loaded: "active", + plugins_reload_hint: "Takes effect after reloading the page", + plugins_remove: "Remove", + plugins_none: "No plugins yet.", + plugins_from_dashboard: "Registered by a dashboard resource", + plugins_add: "Add", + plugins_url_invalid: "Enter a .js address under /local/…, /hacsfiles/… or https://….", + plugins_exists: "This plugin is already in the list.", + plugins_limit: "At most 20 plugins.", + packs_title: "Furniture packs", + packs_intro: "Import your own furniture as a pack (JSON): as a file or pasted below. {n} packs come with NextFloor and are always there.", + packs_docs: "Pack format", + packs_none: "No packs of your own yet.", + community_title: "Community furniture", + community_intro: "Furniture others built with the furniture builder and shared – checked and free. Build your own:", + community_builder: "Open the furniture builder", + community_how: "How to share yours", + community_load: "Load community furniture", + community_none: "No community furniture yet – be the first!", + community_install: "Install", + community_update: "Update", + community_installed: "Installed", + community_failed: "The community furniture could not be loaded: {detail}", + pack_import: "Import pack files …", + pack_paste: "Import JSON", + pack_paste_empty: "Paste a pack's JSON first.", + pack_paste_not_json: "This is not valid JSON: {detail}", + pack_imported: "Imported “{name}” by {publisher} – {n} items", + packs_imported_n: "{n} of {total} packs imported", + pack_by: "by {publisher} · {n} items", + pack_remove: "Remove", + pack_remove_confirm: "Remove the pack “{name}”? Its furniture stays in the plan as plain boxes.", + pack_error_not_a_pack: "This is not a furniture pack (\"format\": \"nfpack\" is missing).", + pack_error_builtin: "A pack that comes with NextFloor already has this id.", + pack_error_invalid_content: "The pack contains invalid furniture: {detail}", + pack_error_too_large: "The pack is too large (1 MB at most).", + pack_error_needs_update: "This pack needs a newer version of NextFloor. Please update first (HACS › NextFloor › ⋮ › \"Update information\" › \"Download\"), restart Home Assistant, then import again.", + pack_error_other: "Import failed: {detail}", + store_open: "Open plugin store", + store_close: "Close plugin store", + store_intro: "Reviewed plugins from the community. Each one is looked at before it is added and does not change afterwards.", + store_submit: "Submit your own plugin", + store_empty: "No plugins in the store yet.", + store_failed: "The store could not be loaded ({error}).", + store_install: "Install", + store_installed: "installed", + store_update: "Update", + store_confirm: "Install “{name}” by {author}?\n\nA plugin runs with the same rights as NextFloor in your browser. The file has been reviewed and its content is fixed:\n{url}", + manual: "Manual", + manual_more: "Learn more", + feature_text_energy: "Energy particles fly in arcs from the solar fields to the inverter, between house, battery, grid and consumers – faster and denser the more power flows. The modules sparkle with their production, a glass card over the roof shows the balance and how self-sufficient the house is right now.", + live_autarky: "self-sufficient", + live_fold: "Make the card small", + live_unfold: "Open the card", + live_day_hint: "The last 24 hours: solar (area) and consumption (line)", + live_week_hint: "The last 7 days: sun {solar} kWh, use {use} kWh (yellow: sun, light: use)", + live_days: "days", + live_car_away: "On the road", + live_car_charging: "Charging", + live_car_plugged: "Plugged in", + live_car_lock: "Lock", + live_car_unlock: "Unlock", + live_car_unlock_confirm: "Really unlock {name}?", + live_car_climate: "Climate", + live_car_charge: "Start/stop charging", + live_media_prev: "Previous", + live_media_playpause: "Play/pause", + live_media_next: "Next", + live_media_volume: "Volume", + live_car_device: "Car (any entity of the car)", + live_car_device_hint: "Charge, range, charging, plug, lock and climate are found by NextFloor on the car's device. Without one it takes the spot's presence sensor.", + live_car_departure_entity: "Departure time (optional)", + live_car_departure: "Departs {time}", + live_car_open: "Open: {parts}", + printer_printing: "printing", + printer_done: "done", + printer_paused: "paused", + printer_error: "error", + printer_idle: "idle", + printer_done_at: "done at {time}", + printer_layer: "Layer", + printer_nozzle: "Nozzle", + printer_bed: "Bed", + heatpump_heating: "heating", + heatpump_water: "making hot water", + heatpump_cooling: "cooling", + heatpump_defrost: "defrosting", + heatpump_idle: "resting", + heatpump_flow_return: "Flow → return", + heatpump_heat: "Heat", + heatpump_power: "Power", + heatpump_outside: "outside", + pack_missing_item: "Furniture of a removed pack", + back_to_room: "Back to {room}", + back_to_floor: "Back to the floor", + hint_furniture: "Tap a room, then pick an item on the right · drag items, resize them by their corners", + furniture_into: "New items go into the middle of “{room}”.", + furniture_pick_room: "Tip: tap a room first – new items then land in its middle.", + flows: "Power flow", + flows_hint: "Show or hide the energy arcs between solar fields, inverter, battery, grid and consumers", + chk_title: "Setup", + chk_hint: "What the energy flow needs. Tap a row to jump there.", + chk_solar: "Solar field in place", + chk_solar_add: "Put a solar field on the roof", + chk_meter: "Meter with grid sensor", + chk_meter_sensor: "Meter: grid sensor (W) missing", + chk_meter_add: "Add the meter", + chk_inverter: "Inverter with power sensor", + chk_inverter_sensor: "Inverter: power sensor missing", + chk_inverter_add: "Add an inverter", + chk_battery: "Home battery with power and charge", + chk_battery_sensor: "Home battery: power or charge missing", + chk_battery_opt: "Home battery (optional)", + chk_grid: "Grid connection set", + chk_grid_opt: "Grid connection (optional, else automatic)", + energy_sign_grid: "The house shows export while the sun produces nothing. The grid sensor probably has its sign reversed.", + energy_sign_battery: "The battery charges with no sun and no grid draw. Its sensor probably has its sign reversed.", + energy_sign_flip: "Flip the sign", + help_title: "Help and feedback", + help_hint: "Please report problems as a GitHub issue and wishes as a discussion – nothing gets lost, and everyone sees the state.", + help_issue: "Report a problem", + help_idea: "Propose an idea", + furn_name: "Name (optional)", + furn_mirror: "Mirror", + furn_mirror_hint: "Swap left and right – the L-sofa the other way round, the cabinet with its door on the other side, the kitchen run mirrored.", + hint_opening: "Tap a wall to add a door or window – choose its kind on the right afterwards", + preset_door: "Door", + preset_door_double: "Double door", + preset_window: "Window", + preset_window_double: "Double window", + preset_terrace: "Terrace door", + preset_terrace_double: "French doors", + preset_lift_slide: "Lift-and-slide door", + preset_garage: "Garage door", + preset_front: "Front door", + opening_style: "Style", + sidelight_auto: "automatic", + sidelight_hinge: "Sidelight on the hinge side", + sidelight_hinge_hint: "The sidelight sits opposite the hinge otherwise; ticked, it sits next to the hinges.", + sidelight_width: "Sidelight width (m)", + sidelight_width_left: "Left sidelight (m)", + sidelight_width_right: "Right sidelight (m)", + style_auto: "Automatic ({style})", + style_interior: "Room door", + style_front: "Front door", + style_front_glass: "Front door with glass", + style_sidelight: "Front door with sidelight", + style_sidelights: "Front door with two sidelights", + style_glass: "Glass door", + style_sliding: "Sliding door", + style_passage: "Opening (no door)", + style_standard: "Standard", + style_bars: "With glazing bars", + style_glass_wall: "Glass wall (fixed)", + preset_glass_wall: "Glass wall", + glass_panes: "Panes", + glass_panes_auto: "automatic (about 0.9 m)", + glass_panes_hint: "0 = one single pane without mullions, empty = about every 0.9 m", + flip_hinge: "Swap hinge side", + flip_main_leaf: "Swap main leaf", + flip_hinge_hint: "Hinges to the other side", + flip_swing: "Reverse opening direction", + flip_swing_hint: "The door swings into the room or to the other side", + main_leaf: "Main leaf (seen from the room)", + contact_main: "Contact main leaf", + contact_second: "Contact second leaf", + tool_outdoor: "Outdoor", + tool_measure: "By measure", + hint_measure: "Tap the starting point, then type the wall lengths with their direction on the right", + measure: "Room by measure", + measure_start: "Tap the starting point in the plan, e.g. a room corner.", + measure_from: "Start at {x} / {z} m – tapping moves the start.", + measure_length: "Length of the next wall (m)", + measure_close: "Close room", + measure_undo: "Remove last wall", + measure_gap: "Gap to the start: {gap} m (joined when closing)", + measure_hint: "Tip: type a length and press an arrow key. With measured inside dimensions, use “Close gaps” afterwards.", + rect_by_size: "Rectangle by size", + rect_add: "Add rectangle", + dir_up: "Up", + dir_down: "Down", + dir_left: "Left", + dir_right: "Right", + hint_outdoor: "Drag to draw an outdoor area (lawn, terrace, pool …)", + outdoor: "Outdoor area", + outdoor_type: "Type", + outdoor_height: "Height (m)", + outdoor_offset: "Height offset (m, − = lower)", + outdoor_opacity: "Opacity (%)", + 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_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_pool: "Pool", + out_bed: "Flower bed", + out_hedge: "Hedge", + out_fence: "Fence", + out_wild: "Wild patch", + out_pergola: "Pergola / frame", + outdoor_open: "Open (leave out the last edge)", + outdoor_open_hint: "The edge from the last point back to the first is not drawn – a fence or pergola leaning against the house.", + fence_gates: "Gates in the fence", + gate_add: "+ Gate in the fence", + gate_edge: "Fence side", + gate_kind: "Kind", + gate_single: "Garden gate", + gate_double: "Double gate", + gate_sliding: "Sliding gate", + gate_offset: "Middle from the start (m)", + gate_width: "Width (m)", + gate_entity: "Motor or switch", + gate_contact: "Contact (on = open)", + 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_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)", + pool_pump_on: "pump on", + outdoor_slope: "Slope (m)", + outdoor_slope_hint: "Height difference from the high edge to the low edge; the high edge sits at the height offset. Lamps on the area follow.", + outdoor_slope_dir: "Falls towards", + slope_x: "right (+X)", + slope_nx: "left (−X)", + slope_z: "down (+Z)", + slope_nz: "up (−Z)", + north: "North (° clockwise from up)", + north_hint: "North is needed for the sun (light through the windows).", + map_on: "Show a real map under the plan", + map_lat: "Latitude", + map_lon: "Longitude", + map_use_ha: "Use Home Assistant's location", + map_opacity: "Visibility (%)", + map_zoom: "Detail level", + map_zoom_coarse: "coarse", + map_zoom_fine: "fine", + map_move: "Move the map under the plan", + map_step: "Step", + map_url: "Own tile address (empty = OpenStreetMap)", + map_hint: "Your browser loads the map tiles straight from the map server (OpenStreetMap by default, please mind their usage policy); nothing is loaded while the map is off. The plan lies on the map as the compass says – turn the compass or move the map until the house fits.", + compass_title: "Compass", + compass_n_short: "N", + compass_s_short: "S", + compass_swap: "Swap north ↔ south", + compass_swap_hint: "Turns the compass by 180°. The drawing, roof faces and solar fields stay as they are.", + compass_hint: "If the compass does not match reality, turn it here – nothing has to be redrawn. Sunlight, wind and the compass directions of roof faces follow it.", + roof: "Roof", + roof_none: "No roof", + roof_flat: "Flat roof", + roof_gable: "Gable roof", + roof_custom: "Roof sections (custom)", + roof_sections: "Roof sections", + roof_sections_hint: "Each roof section covers a rectangle of the house, e.g. the house, the barn or an extension – each with its own shape, ridge direction, eave height and pitch. Drag in the plan to draw a new one; tap selects it, dragging moves it, the corners resize it.", + roof_sections_start: "Create roof sections from the rooms", + roof_sections_regen: "Create again from the rooms", + roof_sections_off: "Back to one roof", + roof_regen_confirm: "Replace all roof sections with a new proposal from the rooms?", + roof_section: "Roof section", + roof_section_hint: "Heights count from the ground. A side with a lower eave reaches further down (catslide); pent roofs rise from the first side.", + roof_shape_gable: "Gable", + roof_shape_hip: "Hip", + roof_shape_pent: "Pent", + roof_shape_flat: "Flat", + roof_shape_halfhip: "Half-hip", + roof_shape_pyramid: "Pyramid", + roof_shape_mansard: "Mansard", + roof_shape_parapet: "Parapet", + roof_shape: "Shape", + roof_end_start: "End at the ridge start", + roof_end_end: "End at the ridge end", + roof_halfhip: "Half-hip starts at", + roof_halfhip_hint: "How high up the gable the hipped part starts, as a share of the gable's height: low = a large hip, high = only the tip is hipped.", + roof_axis_x: "Ridge ↔", + roof_axis_z: "Ridge ↕", + roof_eave: "Eave (m)", + roof_pitch_short: "Pitch (°)", + roof_height: "Height (m)", + roof_base: "Top of walls (m)", + roof_rotation: "Turn (°)", + roof_on_floor: "Sits on floor", + roof_on_floor_hint: "Puts the section on this floor's wall tops; base and eaves move along. In the 3D view the roof belongs to this floor.", + roof_base_hint: "Below the ceiling height of the floor underneath, that floor's walls end under the roof: knee walls at the eaves, gables up to the ridge, inner walls cut by the slope. Dashed lines in the plan show where 1.5 m and 2 m of headroom remain.", + roof_ridge_height: "Ridge height", + roof_side_top: "top", + roof_side_bottom: "bottom", + roof_side_left: "left", + roof_side_right: "right", + roof_swap: "Swap sides", + roof_open: "Canopy (posts instead of walls, see-through)", + roof_open_short: "Canopy", + roof_dormer: "Dormer", + roof_dormer_hint: "A dormer on this side of the roof: 2 m wide, its front at the eave wall, eaves 1.4 m above the roof's eave, gable roof. Then move it and change its width and heights like any section; the main slope opens under it and the attic wall rises up to the dormer – a window fits there.", + roof_outline: "Take the floor's outline", + roof_outline_hint: "A flat roof as a free shape: takes the outline of the shown floor's rooms (L- or Z-shaped too) as one surface without seams. The corners can be dragged afterwards.", + roof_points_hint: "Free shape: drag the corners in the plan, a + on an edge adds a corner, × removes one. Back to the rectangle drops the shape.", + roof_rect: "Back to the rectangle", + roof_open_hint: "For a terrace roof or a carport: posts and beams carry the roof instead of walls, and it is see-through. Where the canopy meets the house wall, it rests on the wall.", + roof_swap_hint: "Turns the roof round: the two sides swap eave and pitch, a pent roof rises the other way.", + roof_pitch: "Roof pitch (°)", + roof_overhang: "Roof overhang (m)", + roof_overhang_sides: "Overhang per side", + roof_overhang_a: "Overhang eave A (m)", + roof_overhang_b: "Overhang eave B (m)", + roof_overhang_u0: "Overhang gable start (m)", + roof_overhang_u1: "Overhang gable end (m)", + roof_overhang_auto: "Back to automatic", + roof_overhang_sides_hint: "Without values of your own the overhang is automatic: the same everywhere, except where the roof part meets the house (none there).", + roof_ridge: "Ridge", + roof_ridge_long: "Along the long side", + roof_ridge_short: "Along the short side (e.g. terraced house)", + device: "Device", + lamp_mount: "Lamp", + lamp_ceiling: "Ceiling light", + lamp_floor: "Floor lamp", + lamp_table: "Table lamp", + lamp_wall: "Wall light", + marker_height: "Marker height (m)", + height_auto: "Automatic height", + device_centre: "To room centre", + lights_spread: "Spread ceiling lights evenly", + devices_search: "Search devices …", + devices_more: "+{n} more", + devices_less: "less", + panel_more: "More devices of the area ({n})", + panel_less: "Show less", + gaps_close: "Close gaps", + gaps_hint: "Join rooms up to 60 cm apart at one shared wall; the gap becomes the interior wall thickness.", + gaps_none: "No gaps between rooms found.", + gaps_closed: "{n} places closed.", + gaps_closed_wall: "{n} places closed, interior wall now {t} m.", + fps: "FPS", + fps_title: "Performance display (frames per second)", + hint_garage: "Tap a wall to add a garage door", + opening_garage: "Garage door", + garage_hint: "The door follows a garage cover (position or open/closed) or a garage door contact of the room's area.", + door_hint: "With a door contact the leaf swings open; without a sensor it stands half open.", + hint_door: "Tap a wall to add a door", + hint_window: "Tap a wall to add a window", + opening_door: "Door", + opening_window: "Window", + opening_type: "Type", + opening_position: "Centre from corner (m)", + sill: "Sill height (m)", + opening_height: "Height (m)", + hinge: "Hinge (seen from the room)", + hinge_left: "Left", + hinge_right: "Right", + cover_entity: "Blind", + door_cover: "Drive (motorised door or gate)", + cover_position_entity: "Position sensor (live)", + cover_position_invert: "Sensor counts the other way round (0 = open)", + contact_entity: "Contact", + sensor_kind: "Sensor type", + sensor_kind_contact: "Window contact (open/closed)", + sensor_kind_handle: "Handle sensor (open/tilted/closed)", + sensor_kind_contact_tilt: "Contact + tilt sensor", + handle_entity: "Handle sensor", + handle_main: "Handle sensor main leaf", + leaf_main: "Main leaf", + leaf_second: "Second leaf", + tilt_entity: "Tilt sensor", + tilt_angle_entity: "Tilt angle sensor (°, optional)", + tilt_angle_max: "Angle that counts as fully tilted (°)", + tilt_angle_offset: "Offset: angle reported while closed (°)", + tilt_angle_invert: "The angle counts the other way round", + door_shut: "Show closed without a sensor", + door_shut_hint: "A door without a contact stands half open in 3D so it reads as a door. Ticked, it is drawn closed – front door, carport, side door.", + door_angle: "Opening angle", + door_angle_default: "Default", + door_angle_hint: "How far the leaf opens. With a sensor it opens that far once it reports open; without one it stands that far open (instead of half). Default stays as before.", + entity_auto: "Automatic ({name})", + entity_auto_none: "Automatic (none found)", + entity_none: "None", + entity_search: "Type to search …", + opening_hint: "Sensor type: window contact (reports open/closed), handle sensor (reports open, tilted and closed – e.g. a Homematic window handle) or contact + tilt sensor (a second sensor that only reports tilted). Automatic uses the blinds and contacts of the room's area. Position sensor: an entity reporting the blind's position while it moves (e.g. a Homematic \"level\", 0–100 % or 0–1, open = high) – the blind then moves live in 3D.", + furniture: "Furniture", + furniture_add: "Add furniture", + studio_new: "Build your own piece", + studio_title: "Furniture studio", + studio_title_edit: "Furniture studio: change", + studio_hint: "Pick a template, set its measurements and fronts and put the piece into the plan. It goes into the \"Own furniture\" pack and can be changed here again later.", + studio_kind: "Template", + studio_kind_cabinet: "Cabinet", + studio_kind_shelf: "Shelf", + studio_kind_lamp: "Lamp", + studio_kind_device: "Device", + studio_name: "Name", + studio_width: "Width (cm)", + studio_depth: "Depth (cm)", + studio_height: "Height (cm)", + studio_doors: "Doors", + studio_drawers: "Drawers", + studio_shelves: "Shelves", + studio_handle: "Handles", + studio_handle_bar: "Bar", + studio_handle_knob: "Knob", + studio_handle_none: "None", + studio_base: "Base", + studio_base_plinth: "Plinth", + studio_base_legs: "Legs", + studio_base_none: "None", + studio_back: "Back panel", + studio_lamp: "Kind", + studio_lamp_floor: "Floor lamp", + studio_lamp_table: "Table lamp", + studio_lamp_pendant: "Pendant", + studio_lamp_wall: "Wall light", + studio_display: "Display on the front (shows the media player)", + studio_mount: "Stands", + studio_mount_floor: "On the floor", + studio_mount_surface: "On furniture", + studio_mount_wall: "On the wall", + studio_color_body: "Body", + studio_color_lamp_body: "Base and frame", + studio_color_front: "Fronts", + studio_color_boards: "Boards", + studio_color_shade: "Shade", + studio_color_display: "Display frame", + studio_color_white: "White", + studio_color_wood: "Wood", + studio_color_metal: "Metal", + studio_color_dark: "Dark", + studio_color_glass: "Glass", + studio_color_accent: "Accent", + studio_color_own: "Own colour", + studio_color_plan: "Colour of the plan", + studio_place: "Put into the plan", + studio_save: "Save the change", + studio_open: "Change in the studio", + studio_error: "Could not save: {detail}", + studio_pack_name: "Own furniture", + studio_pack_publisher: "Furniture studio", + furniture_search: "Search furniture …", + furniture_search_none: "Nothing found. Try another word – English or German.", + furniture_type: "Item", + rotation: "Rotation (°)", + tilt_x: "Tilt front/back (°)", + tilt_z: "Tilt sideways (°)", + strip_tilt: "Tilt about its length (°)", + strip_upright: "Upright", + strip_rise: "Rise along its length (°)", + strip_upright_hint: "The strip stands on end: its length runs up from the height above the floor – along a door frame, as a light column. The tilt lays a lying strip against a slope (90° = its face points sideways).", + rotate_left: "↺ 90°", + rotate_right: "↻ 90°", + height_m: "Height (m)", + furn_sofa: "Sofa", + furn_armchair: "Armchair", + furn_table: "Table", + furn_chair: "Chair", + furn_bed: "Bed", + furn_nightstand: "Nightstand", + furn_wardrobe: "Wardrobe", + furn_shelf: "Shelf", + furn_kitchen: "Kitchen unit", + furn_worktop: "Worktop", + furn_fridge: "Fridge", + furn_fridge_smart: "Smart fridge (side by side)", + furn_door_left: "Door sensor left (freezer side)", + furn_door_right: "Door sensor right (fridge side)", + fridge_hint: "While a door sensor reports open, the door swings open in 3D.", + furn_stove: "Stove", + furn_sink: "Sink", + furn_bathtub: "Bathtub", + furn_shower: "Shower", + furn_wc: "WC", + furn_washbasin: "Washbasin", + furn_desk: "Desk", + furn_tv_board: "TV board", + furn_plant: "Plant", + furn_rug: "Rug", + furn_stairs: "Stairs", + furn_stairwell: "Floor opening", + stairwell_hint: "A hole in this floor, for example above the staircase or for a gallery; from above you look through it. The opening must lie within one room; several openings may overlap (for an L shape, for example). Stairs on the floor below that reach up here open the floor by themselves as well.", + tool_hole: "Floor opening", + tool_stairs: "Stairs", + hint_stairs: "Drag where the stair should stand – it runs along the long side; set shape, turn and build on the right afterwards", + tool_roof: "Roof", + tool_energy: "Energy", + tool_wall: "Wall", + hint_wall: "Drag to draw a single wall (partition, half wall) · Shift keeps it straight · Alt without snapping", + free_wall: "Wall", + wall_length: "Length (m)", + wall_thickness: "Wall thickness (m)", + wall_height: "Height (m)", + wall_height_full: "Full room height", + wall_slope: "Sloping", + wall_slope_start: "Height at the start (m)", + wall_slope_end: "Height at the end (m)", + wall_slope_hint: "Sloping wall: the top runs straight from the height at the start of the wall (the corner with the lower number) to the height at its end. Both may be above the floor height, for example for a lean-to room with high clerestory windows.", + wall_slope_off: "Back to a level wall", + wall_none: "No wall", + wall_none_hint: "Leave this wall out altogether: for open floor plans whose rooms are one space but separate in Home Assistant.", + edge_thickness: "Thickness (m)", + wall_thickness_hint: "Thickness of this wall, e.g. 0.365 on a thick outer wall or 0.115 on a light partition. A wall between two rooms takes the thicker setting.", + wall_thickness_reset: "Thickness as set for the house", + wall_heights: "Wall heights", + wall_n: "Wall {a}–{b}", + wall_view: "Wall view", + wall_view_hint: "The wall from the front: drag its doors, windows and furniture or type their distance.", + wall_view_prev: "Previous wall", + wall_view_next: "Next wall", + wall_view_left: "From the left (m)", + wall_view_height: "Above the floor (m)", + wall_part: "part {n}", + wall_split_hint: "Split the wall here: the part gets a height of its own, e.g. 2.5 m next to 1.7 m in line", + wall_split_at: "Split point from corner (m)", + wall_join_hint: "Remove the split point: the part joins the one before it again", + wall_exterior_short: "exterior wall", + room_wall_hint: "A lower height turns the wall into a parapet or a counter. If two rooms share the wall, the lower setting applies. Windows and doors in it end at the wall height.", + free_wall_hint: "A free-standing wall, e.g. a partition. Where it meets a room wall, the corner is mitred. Drag the handles to move its ends, drag the line to move the whole wall.", + free_wall_slope: "◢ Sloping", + free_wall_slope_hint: "The wall gets higher or lower from one end to the other: the height above is at its start, the one here at its end.", + free_wall_height_end: "Height at the end (m)", + arc: "Arc", + arc_hint: "Bends the wall into an arc. A room sharing the wall bends along, doors and windows move with it; Undo takes the arc back.", + arc_bulge: "Bulge (m)", + arc_bulge_hint: "How far the middle of the wall bulges: positive outwards, negative into the room.", + arc_apply: "Bend", + arc_too_wide: "A door or window in this wall is too wide for this curve. Make the curve flatter or the opening narrower.", + stairwell_outside: "This opening reaches across a room boundary and is therefore not cut. Move it fully into one room or make it smaller.", + hint_hole: "Drag to draw a floor opening (stairwell, gallery)", + hint_roof: "Drag to draw a roof section · tap selects · drag moves · corners resize", + hint_energy: "Tap a solar field to select it · drag to move it, also onto another roof face · new fields with + Solar field on the right", + furn_parking: "Parking spot", + furn_group_vehicles: "Parking", + parking_entity: "Sensor \"car present\"", + parking_vehicle: "Vehicle", + parking_vehicle_none: "None", + parking_no_pack: "No vehicle pack imported – vehicles come from the \"Vehicles\" pack (Extensions → Furniture packs).", + parking_scale: "Size (%)", + parking_type_entity: "Vehicle type sensor (optional)", + parking_types: "State → vehicle", + parking_type_state: "State (e.g. van)", + parking_add_type: "+ Mapping", + parking_hint: + "Without a sensor the vehicle always stands there. With one it appears as soon as the sensor reports \"on\", \"home\" or \"present\". A vehicle type sensor (e.g. from an AI camera analysis) picks the model: when its state matches a mapping – also as a word in the text – that vehicle is shown, otherwise the default one.", + parking_too_tall: "The vehicle ({car} m) is taller than the room ({room} m).", + furn_lamp_ceiling: "Ceiling light", + furn_lamp_downlight: "Downlight", + furn_lamp_spot: "Surface spot", + furn_lamp_panel: "LED panel", + furn_lamp_uplight: "Floor uplight", + furn_lamp_bollard: "Path light", + furn_lamp_garden: "Garden spot", + furn_radiator: "Radiator", + furn_robot_vacuum: "Robot vacuum", + furn_entity_vacuum: "Robot vacuum", + furn_entity_mower: "Robot mower", + pet_room_sensor: "The pet's room sensor (optional)", + pet_room_hint: "A sensor naming the room the pet is in – Bermuda or ESPresense with a tag on its collar: in 3D it then roams that room.", + furn_entity_water: "Valve or switch", + device_temp: "Device temperature", + device_temp_hint: "A temperature sensor of the device (inverter, battery, PC …): its value shows on the pin in the 3D view, from 60 °C the pin is highlighted.", + fridge_temp: "Fridge temperature", + freezer_temp: "Freezer temperature", + fridge_temp_hint: "The pin shows the temperatures. Above 8 °C in the fridge or −12 °C in the freezer it lights up as a warning.", + spray_reach: "Reach of the water (m)", + spray_hint: "While the valve is open or the switch is on, the sprinkler throws water in arcs around it.", + furn_robot_room: "Current room (sensor)", + robot_cal_none: "Not calibrated yet — with nothing tying the robot's grid to the plan, the lanes stay invented.", + robot_cal_done: "Calibrated: one map cell measures {m} m.", + robot_cal_do: "Calibrate from where the robot is now", + robot_cal_doing: "Tap the plan where the robot is right now.", + robot_cal_need: "The robot's map is not reporting a position — is the integration running?", + robot_cal_hint: "The dock is the anchor: the plan knows where it stands, the camera knows where the robot and its dock lie in their grid. If the map names its rooms like the plan does, “Calibrate from the rooms” is all it takes. Otherwise: stop the robot at least 1.5 m away — pause the clean — and tap it on the plan. If the rooms come out flipped, set the tick.", + robot_cal_mirror: "The robot's map is mirrored (rooms come out flipped)", + robot_cal_forget: "Remove the calibration", + robot_cal_nudge: "Fine-tune by hand: the arrows move the map by 10 cm, ⟲ ⟳ turn it by 1°, − + change its size by 1 %.", + robot_cal_nudge_move: "Move the map", + robot_cal_nudge_turn: "Turn the map", + robot_cal_nudge_grow: "Make the map larger or smaller", + robot_cal_rooms: "Calibrate from the rooms (the map knows {n} rooms)", + robot_cal_rooms_none: "Too few rooms have the same name in the plan as on the robot's map ({n} found, at least 2 needed). Name them alike — or calibrate from the robot's position.", + robot_cal_rooms_bad: "The rooms with matching names lie differently in the plan than on the robot's map — is a room mixed up? Otherwise calibrate from the robot's position.", + robot_hint: "While the robot cleans in Home Assistant it drives lanes in 3D through the room it reports (a “current room” sensor, matched by room or area name), else through the room of its dock. With the robot's own map calibrated below, the track shows where it has really driven instead; without it the lanes are a guess. It drives back to the dock when it returns.", + furn_lamp_pendant: "Pendant light", + furn_ceiling_fan: "Ceiling fan", + furn_fan_entity: "Fan", + fan_hint: "The light is the fan's light kit (leave it empty if it has none). The fan is found in the room or chosen here: in 3D the blades turn as fast as it runs, its icon switches it, swiping up/down changes the speed, a long press opens the quick menu. The height is how far it hangs from the ceiling (more = a longer downrod).", + room_ceiling: "Ceiling height", + room_ceiling_tip: "Lower than the floor (a bathroom under the stairs) or higher (a living room open up to the roof): ceiling lights, fans, LED strips and ceiling devices hang from here, and the room's walls are this high.", + room_ceiling_through: "The ceiling ({ceiling} m) is above the floor height ({floor} m): the room reaches into the floor above, its walls rise with it, and the floor above stays open over it. The editor of the upper floor shows the area hatched.", + room_floor_offset: "Floor level (m)", + room_floor_offset_hint: "When this room's floor lies lower or higher than the floor (a sunken entrance: −0.39), its floor, walls, doors and windows and what stands in it move with it; its ceiling stays. Add the steps as a stair.", + room_inner: "Inside {w} × {d}", + room_inner_hint: "Measured from wall to wall: inner walls take half their thickness, outer walls stand outside the outline.", + floor_heating: "Underfloor heating (optional)", + floor_heating_hint: "While the thermostat heats (or the valve is open, the switch on), the room's floor glows warm in 3D.", + room_announce_speaker: "Speaker for announcements", + room_announce_quiet: "Quiet time for announcements", + room_announce_hint: "Without a choice, the speaker placed in the room talks, else a voice assistant, an Echo or a speaker of its area (never a TV). During the quiet time, announcements to several rooms leave this room out; one meant only for it still gets through.", + ceiling_here: "Ceiling here", + ceiling_here_hint: "Height of the ceiling right at this spot, e.g. in a sloping ceiling. Empty = the room's ceiling.", + ceiling_slope: "Up to the roof slope", + ceiling_slope_hint: "The ceiling here lies under the roof slope: the lamp hangs from its underside, right above where it stands.", + furn_lamp_floor: "Floor lamp", + furn_lamp_table: "Table lamp", + furn_lamp_wall: "Wall light", + furn_led_strip: "LED strip", + furn_group_lights: "Lights", + furn_entity_light: "Light or switch", + furn_color_entity: "Colour and brightness from (optional)", + furn_color_entity_hint: "For lights that a relay (Shelly, switch actuator) turns on and off while the bulb itself knows its colour and brightness: on/off comes from the switch above, colour and brightness from this entity.", + lamp_extra_light: "Bulb {n} (optional)", + lamp_extra_hint: "A fixture with several lights – main light, night light, ambient ring: while the main light is off it glows in 3D with the next light that is on, a little dimmer. Switch the lights one by one in the room panel.", + furn_entity_climate: "Heating (thermostat)", + lamp_hint: "Tap the lamp in 3D to switch it, long press for the quick menu. Switches work too (e.g. a relay for the ceiling light) – the lamp shines while it is on. Table lamps stand on the furniture below them.", + lamp_hint_pendant: "Height = drop below the ceiling. Tap in 3D to switch, long press for details.", + theme: "Look", + version_hint: "Installed version of NextFloor – the frontend; the integration in Home Assistant reports {backend}", + accent: "Accent colour", + accent_hint: "An accent colour of your own: lines and glowing edges in the neon look, buttons and pins – ↺ brings the neon cyan back", + accent_reset: "Back to cyan", + furn_colors_card: "Furniture colours of this card", + furn_color_house: "House colour", + theme_neon: "Neon", + theme_blueprint: "Blueprint", + theme_day: "Day", + theme_auto: "Auto", + clock: "Clock", + clock_none: "None", + clock_top_left: "Top left", + clock_top_right: "Top right", + clock_bottom_left: "Bottom left", + clock_bottom_right: "Bottom right", + glass_walls: "Glass walls", + glass_walls_hint: "How opaque the walls you look through into the rooms are: left almost invisible, right opaque. For this screen.", + screen_name: "Name of this screen", + screen_name_hint: "Announcements show on every open NextFloor screen. With a name (e.g. \"Hallway\"), an announcement can go to this screen only. Unticked, this screen stays silent.", + announce_on: "Announcements on this screen are on", + announce_muted: "Announcements on this screen are muted", + lock3d_on: "Lock 3D (no turning, zooming or panning; taps still work)", + lock3d_off: "Unlock 3D", + walk: "Walk through the house", + travel: "Time travel: replay the last 24 hours or 7 days", + travel_play: "Play", + travel_pause: "Pause", + travel_loading: "Loading history …", + travel_failed: "The history could not be loaded.", + travel_speed: "Speed", + travel_speed_min: "1 min/s", + travel_speed_10min: "10 min/s", + travel_speed_hour: "1 h/s", + travel_days: "days", + travel_live: "Live", + card_travel_button: "Button for time travel", + walk_stop: "Stop walking", + walk_hint: "Drag: look around · W A S D / arrows or stick: walk · wheel: step", + card_walk_button: "Button to walk through", + card_lock_button: "Button for the 3D lock", + backdrop: "Own background", + backdrop_color: "Colour", + backdrop_image: "Picture (/local/… or https://…)", + backdrop_dim: "Dim", + backdrop_hint: "Instead of the look's sky the house stands in front of a colour or a picture of your own. A picture in /config/www is reachable at /local/….", + furnish: "Furnish", + split_3d: "3D beside", + plan_dims: "Measurements", + plan_dims_hint: "Labels every room edge with its length.", + mount_height: "Height above the floor (m)", + side_open: "Open the sidebar", + side_close: "Close", + side_details: "Details of the selection", + side_pin: "Pin", + side_pinned: "Pinned", + side_pin_hint: "Pinned, the sidebar stays open; otherwise it folds away beside the 3D view while nothing is selected", + split_3d_hint: "Live 3D next to the plan: drag and turn furniture and devices there – with undo, saved with the plan", + size_w: "Width (m)", + size_d: "Depth (m)", + size_h: "Height (m)", + furnish_hint: "Drag furniture, lamps and devices · furniture snaps to walls · tap one to turn it, set its height and mount", + done: "Done", + heatmap: "Heatmap", + heat_off: "Normal", + heat_short_temperature: "Temp.", + heat_short_humidity: "Humidity", + heat_short_co2: "CO₂", + heat_short_mould: "Mould", + heat_short_power: "Power", + heat_short_comfort: "Comfort", + heat_short_sun: "Sun", + heat_short_wifi: "Wi-Fi", + heat_short_values: "Values", + heat_temperature: "Temperature", + heat_humidity: "Humidity", + heat_co2: "CO₂", + heat_mould: "Mould", + heat_power: "Power use", + heat_comfort: "Comfort score", + heat_sun: "Sun today", + room_sun_hours: "{h} h of sun today ({facing})", + open_since: "open for {time}", + presence_now: "someone here", + presence_last: "last seen {time} ago", + comfort_n: "Comfort {n}", + empty_lights_hint: "{n} lights on, nobody here for {min} min.", + empty_lights_off: "Lights off", + open_heating_hint: "{n} windows open while the heating runs.", + open_heating_off: "Heating off", + room_clean: "Cleaning (script or button)", + room_clean_hint: "A script or button that sends the robot vacuum to this room (e.g. your robot integration's room cleaning). The room panel then shows \"🧹 Clean\".", + room_clean_run: "Clean", + room_clean_run_hint: "Sends the robot vacuum to this room.", + shade_hint: "Sun on {n} windows at {temp} – lower the blinds?", + shade_close: "Lower", + room_sun_year: "Sun over the year", + room_sun_year_hint: "The hours of sun through the room's outside windows on the 15th of every month.", + room_energy: "today {today} · month {month}", + room_energy_hint: "From the statistics of the power sensors of the room's devices; the month's cost at the house's tariff.", + heat_summer: "summer", + heat_winter: "winter", + air_co2: "air it (CO₂)", + air_humidity: "air it (damp)", + air_mould: "risk of mould – air it", + room_curve_hint: "The room's temperature over the last 24 hours", + heat_values: "Values at the room names", + heat_wifi: "Wi-Fi", + wifi_aps: "{n} access points · {clients} devices", + wifi_network: "Network: {online} online · {offline} offline", + wifi_none: "Place access points or routers from the packs (Smart home 2) and link them to an entity of their device.", + wifi_clients: "{n} devices", + heat_none_found: "No matching sensors in the rooms' areas.", + markers: "Markers", + markers_none: "None", + markers_important: "Important", + markers_all: "All", + furn_stool: "Stool", + furn_coffee_table: "Coffee table", + furn_tv_wall: "TV (wall)", + furn_sideboard: "Sideboard", + furn_table_round: "Round table", + furn_bench: "Bench", + furn_corner_bench: "Corner bench", + furn_bar_stool: "Bar stool", + furn_kitchen_wall: "Wall cabinet", + furn_kitchen_tall: "Tall unit with oven", + furn_island: "Kitchen island", + furn_dishwasher: "Dishwasher", + furn_bunk_bed: "Bunk bed", + furn_dresser: "Chest of drawers", + furn_washer: "Washing machine", + furn_dryer: "Dryer", + furn_office_chair: "Office chair", + furn_tall_cabinet: "Tall cabinet", + furn_coat_rack: "Coat rack", + furn_group_living: "Living", + furn_group_dining: "Dining", + furn_group_energy: "Energy & solar", + energy_devices: "Devices", + wallbox_charging: "charging", + wallbox_plugged: "plugged in", + furn_soc: "State of charge (%)", + furn_export: "Export power (W, separate sensor, optional)", + furn_export_hint: "If your meter reports import and export in two sensors (e.g. Growatt, Tibber Pulse), take the import sensor as power above and the export sensor here. A signed sensor does not need this.", + meter_parent: "Hangs off meter", + meter_parent_none: "none (main meter)", + meter_main: "Main meter", + meter_unmetered: "{w} unmetered", + meter_device_hint: "If the device sits behind a sub-meter (e.g. a balcony plant in a flat), its power counts towards that flat. The sub-meter has to measure both ways for this (− = feeding back); if it only counts import, the flat's consumption comes out too high while there is a surplus.", + meter_sub_power: "Power of the branch (W, + = drawn, − = fed back)", + meter_floors: "Feeds the floors", + meter_sub_hint: "A sub-meter measures its branch, e.g. a flat. Devices on the ticked floors hang off it in 3D instead of the main meter; what the main meter counts beyond that shows as “Common (rest)” in the balance.", + furn_charge: "Charging power (W, separate sensor, optional)", + furn_charge_hint: "If your battery reports charging and discharging in two sensors (e.g. Anker Solix), take the discharging sensor as power above and the charging sensor here. A signed sensor does not need this.", + furn_wallbox_status: "Status (charging, plugged in)", + energy_only_note: "⚡ Energy: only solar fields and energy devices can be moved here; rooms and furniture are locked.", + roof_only_note: "🏠 Roof: only roof sections and roof windows can be moved here; rooms and furniture are locked.", + energy_devices_hint: "Meter, inverters, home batteries, wallboxes and the grid connection are added here: on the floor chosen above, movable in the plan. With a power sensor they show their watts; the meter takes the grid sensor, a string picks its inverter. Several inverters and batteries (say a balcony plant on top) work too: each gets its own sensor.", + energy_routes: "Cable routes", + energy_routes_hint: "Where a cable really runs: the flow then follows your points instead of an arc through the house. Without a route it keeps the arc. Consumers keep their arc.", + route_conn_solar: "{name} → inverter", + route_conn_battery: "Battery ↔ house", + route_conn_inverter: "Inverter → house", + route_conn_grid: "Grid ↔ house", + route_conn_meter: "{name} ↔ parent meter", + route_conn_device: "{name} ↔ sub-meter", + route_points: "{n} points", + route_none: "direct arc", + route_draw: "Draw route", + route_redraw: "Redraw", + route_drawing: "Tap the points the cable runs through on the plan, from one end to the other; switch floors in between where it goes through a ceiling. {n} points.", + route_undo: "Last point", + route_done: "Done", + route_cable: "Show as cable", + route_cable_hint: "Draws the route as a visible cable, not just as the faint line under the particles.", + solar_fields: "Solar fields", + solar_hint: "Put modules on the roof: they lie in the slope of the roof face; on a flat roof they stand on frames. Drag a field in the plan to move it.", + solar_no_roof: "Solar fields need a roof: a gable or flat roof under Settings, or roof sections here in the Roof tool.", + solar_face_gone: "roof face missing", + solar_summary: "{n} modules · {kwp} kWp", + solar_add: "Solar field", + solar_field: "Solar field", + solar_face: "Roof face", + solar_rows: "Rows", + solar_cols: "Modules per row", + solar_portrait: "Portrait", + solar_landscape: "Landscape", + solar_u: "Distance from the edge (m)", + solar_v: "Distance from the eave (m)", + solar_tilt: "Tilt of the frames (°)", + solar_rack_ew: "East-west racks", + solar_rack_ew_hint: "Every second row faces the other way, the pairs stand back to back – low and close, as on many flat roofs.", + solar_rack_tilt: "Rack (° more tilt)", + solar_flip: "Lean the other way", + solar_partial: "only {n} of {total} fit on the face", + solar_form_hint: "Modules that would reach beyond the roof face are left out. “Fill face” puts as many modules on the roof as fit. kWp counted with 400 W per module.", + solar_fit: "Fill face", + roof_windows: "Roof windows", + roof_window: "Roof window", + chimneys: "Chimneys", + chimney: "Chimney", + chimney_shape: "Shape", + chimney_brick: "Brick", + chimney_round: "Round", + chimney_wide: "Wide, two flues", + chimney_steel: "Steel flue pipe", + chimney_diameter: "Diameter (m)", + chimney_depth: "Depth (m)", + chimney_height: "Height above the roof (m)", + chimney_hint: "The height counts from the upper side, where the chimney leaves the roof. Drag it in the plan or in the 3D view, also onto another roof face.", + roof_windows_hint: "Roof windows lie in the roof face, with a blind and contacts like windows. Drag them in the plan, also onto another roof face.", + roof_window_tilt: "Tilt contact", + roof_window_name: "Name (optional)", + roof_window_motor: "Window motor (cover, optional)", + roof_window_motor_hint: "A window motor (Velux, Roto, Fakro) reports its position as a cover: the sash opens in 3D as far as the motor stands. A contact or tilt contact still works without a motor.", + roof_window_hint: "Open, the sash swings out, hinged at the top; tilted, a little; and the frame glows warm; the blind comes down over the glass from the top. In a roof section the window cuts a hole into the slope, so the attic looks out through it.", + solar_ground: "Free-standing (garden, garage roof …)", + solar_add_ground: "Free-standing", + solar_base: "Height of the surface (m, 0 = ground)", + solar_add_wall: "On a wall", + solar_wall: "Wall", + solar_v_wall: "Height above the floor (m)", + solar_tilt_wall: "Tilt away from the wall (°, 90 = canopy)", + solar_flip_wall: "Standing off at the bottom instead of the top", + solar_rotation: "Rotation (°)", + solar_name: "Name", + solar_name_hint: "e.g. string 1 south", + solar_module_w: "Module width (m)", + solar_module_h: "Module height (m)", + solar_wp: "Module power (Wp)", + solar_string: "String", + solar_strings: "Strings", + solar_string_none: "No string", + solar_string_new: "New string", + solar_string_n: "String {n}", + solar_string_name: "Name of the string", + solar_string_entity: "PV power of the string", + solar_string_inverter: "Inverter", + solar_string_inverter_none: "No inverter chosen", + inverter_strings: "Strings on this inverter: {names}", + inverter_strings_none: "No string on this inverter yet – assign it at a solar field under String › Inverter.", + solar_string_inverter_missing: "No inverter in the plan yet (add one below under Devices)", + solar_string_hint: "Fields in the same string belong together, also on different roofs (e.g. 5 modules on the house and 5 on the garage). Sensor and inverter count for the whole string.", + solar_string_sum: "{fields} fields · {n} modules · {kwp} kWp", + solar_face_size: "Roof face {w} × {h} m (along the eave × up the slope)", + solar_cols_hint: "One number for rows of equal length, or a list for rows of their own: “4, 4, 3” (from the eave).", + solar_align_left: "Left", + solar_align_center: "Centre", + solar_align_right: "Right", + solar_look_black: "Full black", + solar_look_blue: "Blue", + solar_pick: "Modules on/off one by one", + solar_pick_all: "All on again", + solar_pick_hint: "Tap a module in the plan to take it away or put it back. Removed ones are dashed.", + solar_entity: "PV power of this field (e.g. its string)", + solar_main: "Main roof", + solar_section: "Section {n}", + solar_flat: "flat roof", + compass_n: "north", + compass_ne: "north-east", + compass_e: "east", + compass_se: "south-east", + compass_s: "south", + compass_sw: "south-west", + compass_w: "west", + compass_nw: "north-west", + furn_meter: "Electricity meter", + furn_grid_point: "Grid connection", + grid_point_hint: "The grid connection stands here: the handover point to the utility, e.g. at the end of the driveway. Movable in the plan.", + furn_model: "Model", + inverter_std: "Standard (wall unit with display)", + inverter_slim: "Slim and tall (light strip)", + inverter_hybrid: "Hybrid (round dial, fans)", + battery_std: "Tower (stacked modules)", + battery_wall: "Wall battery (flat, hanging)", + battery_cube: "Compact (balcony battery)", + furn_inverter: "Solar inverter", + furn_home_battery: "Home battery", + furn_wallbox: "Wallbox", + furn_group_kitchen: "Kitchen", + furn_group_sleeping: "Sleeping", + furn_group_bath: "Bath & laundry", + furn_group_work: "Work & other", + furn_entity: "Device (switch, plug …)", + furn_state_entity: "State from (optional)", + furn_state_entity2: "Second state (the other half)", + furn_tap: "Tapping the item", + furn_tap_default: "As usual", + furn_tap_hint: "An own action like the star menu's own buttons, e.g. a browser_mod popup with your card.", + furn_show_when: "Only show while …", + furn_show_when_state: "… is in state (empty = on)", + furn_show_when_invert: "The other way round: show while it is not", + furn_show_when_hint: "Seasonal decoration that only stands in December: a helper (input_boolean), a calendar or a sensor decides whether the piece shows in 3D. Separate several states with commas. The editor always shows it.", + picture_upload: "Upload a photo", + picture_replace: "Upload another photo", + picture_stored: "An own photo is stored.", + picture_url: "… or picture address", + picture_entity: "… or an entity's picture", + picture_border: "Mat (%)", + picture_fit: "Photo", + picture_fit_cover: "fills the frame", + picture_fit_contain: "shown whole", + picture_hint: "Your photo in the frame, in 3D and on the wall tablet. Uploaded photos are stored with the plan in a smaller size; an image entity (a photo of the day) or a camera shows its current picture.", + furn_state_split: "Halves", + furn_state_left_right: "Left / right", + furn_state_top_bottom: "Bottom / top (bunk bed)", + furn_state_hint: "The item glows while the entity reports on, occupied or home – a bed with an occupancy mat, an armchair, the sauna. Two entities light the halves: left and right, bottom and top for a bunk bed.", + furn_entity_tv: "TV (media player or smart plug)", + fix: "Fix", + unfix: "Release", + fix_hint: "Fixed: cannot be moved by accident any more (key L, right-click or long press)", + fixed_drag_hint: "🔒 Fixed – release it first to move it (lock in the form, right-click or key L)", + fixed_delete_confirm: "This item is fixed. Delete it anyway?", + lock_plan: "🔒 Floor plan", + lock_plan_hint: "Lock the floor plan: rooms, walls, doors, windows and outdoor areas cannot be moved by accident. Furniture and devices stay free.", + start_view: "Start view", + start_view_hint: "The 3D view, the card and the kiosk open the house with this view, e.g. from the garden side. Turn, zoom and move the house in the 3D pane on the right until it fits, then remember it.", + start_view_card: "If a card should open with a different view, put this line into its YAML configuration.", + start_view_set: "Remember the current 3D view as the start", + start_view_reset: "Default", + start_view_saved: "An own start view is saved.", + ctx_rotate: "Turn 90°", + devices_placed_in: "in {room}", + devices_narrow: "{n} more – narrow the search", + climate: "Room climate", + climate_temperature: "Temperature", + climate_humidity: "Humidity", + climate_co2: "CO₂", + climate_hint: "These sensors count for the heatmap and the room panel. “Automatic” takes the sensors of the area and the ones placed in the room, but no device temperatures (3D printer, heat pump, flow …).", + climate_more: "… and another sensor (averaged)", + plan_locked: "Floor plan locked", + plan_lock: "Lock floor plan", + plan_unlock: "Unlock floor plan", + opening_mark: "Highlight in 3D", + opening_mark_open: "When open", + opening_mark_closed: "When closed (e.g. WC)", + opening_mark_hint: "A highlighted window or door glows warm. \u201cWhen closed\u201d needs a contact; without a sensor nothing is highlighted.", + window_opens: "Opens", + window_opens_turn: "Turn and tilt (inwards)", + window_opens_slide: "Sliding (sliding window, lift-and-slide door)", + window_opens_top: "Top-hung (bottom swings out)", + window_opens_hint: "Sliding: the pane on the hinge side slides in front of the fixed one; with two leaves the middle two slide outwards. Top-hung windows open with their contact or a tilt sensor.", + marker_show: "Marker in 3D", + marker_show_hint: "Automatic follows the None / Important / All switch of the 3D view. Always show and Hide apply regardless (except with None).", + pin_shift: "Move the pin", + pin_shift_up: "↑ up", + pin_shift_hint: "When devices stand close together, push the pin a little aside or up here (in metres); the device itself stays where it is.", + marker_show_auto: "Automatic", + marker_show_always: "Always show", + marker_show_no_power: "Without watts", + marker_show_active: "Only while active", + marker_show_never: "Hide", + marker_icon: "Own symbol (Material Design icon)", + device_name: "Own name (optional)", + show_name: "Show the name under the marker in 3D", + card_marker_names: "Own names at the markers", + card_marker_names_hint: "Every device with an own name shows it small under its marker – three thermometers in the garden stay apart.", + card_tap_in_room: "Switch devices only in the opened room", + card_tap_in_room_hint: "In the house and floor views a tap opens the floor or room, even on a device or its marker. In the opened room it switches the device. A long press always opens its menu or details.", + card_markers_outside: "Choose the markers outside the opened room", + card_markers_outside_hint: "In the house, on the floor and in the other rooms only the ticked kinds; in the opened room all, as set above. A device's own \"always\" and \"never\" come first.", + marker_kind_light: "Lights", + marker_kind_cover: "Blinds", + marker_kind_climate: "Heating", + marker_kind_media: "Media", + marker_kind_switch: "Switches", + marker_kind_fan: "Fans", + marker_kind_lock: "Locks", + marker_kind_binary: "Contacts and detectors", + marker_kind_sensor: "Sensors", + marker_kind_tap: "Furniture with an action", + marker_kind_other: "Other", + device_name_hint: "A name for the plan and the room panel only, e.g. \"Island accent light\" – the entity in Home Assistant stays as it is.", + device_simple: "Switch only in the room panel", + device_simple_hint: "The room panel shows only the switch for this lamp, without brightness, colour temperature and colours.", + floor_turn: "Turn 90°", + floor_shift_all: "Take every floor along (whole house)", + floor_shift_all_hint: "Shift and turn act on every floor with the roof sections, outdoor areas, energy devices and meter – the whole house moves as one.", + floor_turn_hint: "Turns everything on the floor by 90° clockwise about the middle of its rooms – when a floor was drawn the wrong way round. Three times = 270°.", + marker_icon_hint: "The name of a Material Design icon as in Home Assistant, e.g. mdi:thermometer or mdi:water-alert. Empty = the symbol of the device kind.", + furn_power: "Power sensor (W)", + furn_links_hint: "With a power sensor the item shows its watts and takes part in the energy flow.", + furn_links_hint_tv: "The screen glows while the TV is on, in the colour of the app (Netflix, YouTube …); the label shows the app or title.", + stairs_hint: "The stair rises towards the back (away from the marked front edge) and opens the ceiling of the floor above.", + stair_shape: "Shape", + stair_shape_straight: "Straight", + stair_shape_quarter: "Quarter turn (winders)", + stair_shape_l: "L with landing", + stair_shape_half: "Half turn (winders)", + stair_shape_u: "U with landing", + stair_shape_spiral: "Spiral", + stair_turn: "Turns (walking up)", + stair_turn_left: "To the left", + stair_turn_right: "To the right", + stair_build: "Build", + stair_build_solid: "Solid (concrete)", + stair_build_stringer: "On stringers", + stair_build_mono: "Mono stringer (spine)", + stair_build_cantilever: "Cantilevered (floating)", + stair_risers: "Closed risers", + stair_steps: "Risers", + stair_run_width: "Flight width (m)", + stair_landing_after: "Risers up to the landing", + stair_landing_hint: "The landing lies {h} cm above the floor; the other risers come after it.", + stair_rail: "Railing", + stair_rail_none: "None", + stair_rail_left: "Left", + stair_rail_right: "Right", + stair_rail_both: "Both sides", + stair_down: "Leads down", + stair_down_hint: "The stair starts on this floor and leads down, for example into a cellar that need not be drawn. It opens the floor of this level.", + stair_measures: "{steps} risers of {rise} cm · going {going} cm · step measure {measure} cm", + stair_uncomfortable: "uncomfortable (step measure 59–65 cm, rise at most 21 cm)", + stair_up_note: "The stair starts at the marked front edge. The floor above opens only where less than 2.2 m of headroom is left above the steps.", + stair_down_note: "You step onto the stair at the marked front edge and walk down. The plan draws it dashed; this floor opens above the steps.", + stair_opening: "Floor opening", + stair_opening_headroom: "By headroom (only where needed)", + stair_opening_full: "Over the whole stair", + stair_opening_none: "None (hatch, closed stairwell)", + stair_opening_hint: "How much of the floor the stair reaches it opens: the floor above, or its own floor for a stair going down. By headroom opens only above the steps that lack 2.2 m.", + stair_up_note_plain: "The stair starts at the marked front edge and rises towards the back.", + stair_upgrade: "Set the shape", + stair_upgrade_hint: "Turns this into a stair with a shape (winding, L, U, spiral), build, railing and number of steps.", + floor_lights: "{n} lights on", + floor_open: "{n} open", + floor_persons: "{n} people", + energy_consumption: "Consumption", + energy_grid_import: "Grid import", + energy_grid_export: "Export", + energy_solar: "Solar", + energy_battery: "Battery", + energy_tariff: "Tariff", + energy: "Energy", + energy_meter: "Meter", + energy_grid: "Grid (W, + = import)", + energy_solar_sensor: "Solar production (W)", + energy_battery_sensor: "Battery power (W, + = discharging)", + energy_battery_soc: "Battery charge (%)", + energy_tariff_sensor: "Tariff (e.g. €/kWh)", + energy_gas: "Gas meter (optional)", + energy_water: "Water meter (optional)", + energy_meters_hint: "Gas and water show with the house's balance – in the energy bar and on the house card: a sensor with the flow now (m³/h, l/min) or today's reading.", + energy_gas_short: "Gas", + energy_water_short: "Water", + energy_invert: "Invert sign", + energy_hint: "Consumers are placed devices with a power sensor (W) – the sensor itself or one of the same device.", + energy_balance: "Energy balance", + energy_balance_hint: "Grid, solar and battery come from the devices in the plan: meter, inverter and home battery. Here you can choose other sensors, flip signs and set the house consumption.", + energy_rest: "Common (rest)", + energy_advanced: "Advanced energy mode", + energy_advanced_on: "Use sub-meters", + energy_show_unmetered: "Show unmetered use at sub-meters", + energy_show_unmetered_hint: "A sub-meter's label then shows what its floors use and how much of it no placed device measures, e.g. “500 W · 450 W unmetered”. Otherwise it shows the meter's reading.", + energy_advanced_hint: "For sub-meters, e.g. one per flat behind a main meter: a meter can then hang off another one and feed its own floors. Off = the first meter is the grid connection, further ones are consumers.", + energy_consumption_sensor: "House consumption (W, else from the balance)", + energy_import_prefs: "Take over from the energy dashboard", + energy_import_done: "{n} sensors taken over – please check the signs.", + energy_import_none: "No matching power sensors (W) were found in the energy dashboard – please choose them by hand.", + energy_import_failed: "Home Assistant's energy dashboard is not set up.", + tool_meter: "Meter", + hint_meter: "Tap the spot of the meter", + presence: "Presence", + ble: "Bluetooth locating", + ble_hint: "Locate a Bluetooth tag (key fob, watch, phone) by room: walk through the rooms with it and record each room. NextFloor then compares how strongly Home Assistant's Bluetooth scanners (ESPHome proxies, Shelly devices with Bluetooth switched on, adapters on the server) hear it. Every tag gets a sensor whose state is the room name.", + ble_unavailable: "Home Assistant's Bluetooth integration is not running. Without it there are no scanners.", + ble_scanners: "{n} Bluetooth scanners in Home Assistant. The more scanners in different rooms, the more exact.", + ble_add: "Add a tag or device", + ble_trackers: "Phones and watches (Private BLE Device)", + ble_devices: "Bluetooth devices found", + ble_name: "Name (optional)", + ble_refresh: "Reload the list", + ble_add_button: "Add", + ble_learn: "Learn rooms", + ble_close: "Close", + ble_spots: "{n} recordings", + ble_now: "Now", + ble_unknown: "unknown", + ble_none_heard: "No scanner hears the tag right now. Hold it near a scanner and wait a moment; a tag only sends every few seconds.", + ble_no_address: "This phone or watch has no known address right now. Check Home Assistant's Private BLE Device integration.", + ble_one_scanner: "Only one scanner hears the tag. Telling rooms apart takes at least two, better three or more.", + ble_learn_room: "Record a room", + ble_record: "Record ({s} s)", + ble_recording: "Recording … {s} s left", + ble_forget_room: "Forget the room", + ble_learn_hint: "Pick the room, press Record and walk slowly through the whole room with the tag in your hand, into the corners too. Recording again replaces the room. Learn every room you want to locate the tag in.", + ble_sensor_hint: "The sensor \"{name}\" (device NextFloor) shows the room. Under Presence you can pick it as a person's room sensor.", + presence_hint: "Room sensor per person (e.g. ESPresense, Bermuda): its state names the room or area.", + presence_sensor: "Room sensor", + presence_room: "Default room", + presence_room_none: "– none –", + presence_add: "Another entity (helper switch, tracker)", + no_persons: "There are no people in Home Assistant.", +}; + +export type I18nKey = Key; + +// The editor and the card editor are only ever loaded by the main bundle, so they take its German and English texts +// instead of carrying a copy of their own (about 200 KB each); the build replaces globalThis.__NF_SHARED_TEXTS__ by true for them, and the +// unused copy is dropped. +type Builtin = { de: typeof DE; en: Record }; +const builtin = globalThis as { __nextfloorBuiltin?: Builtin }; +// written out in place (not through a constant), so the build can drop the branch it does not take; an old main bundle +// still open in the browser after an update has no texts to share, and the editor then shows keys until the page reloads +const de: typeof DE = (globalThis as { __NF_SHARED_TEXTS__?: boolean }).__NF_SHARED_TEXTS__ ? (builtin.__nextfloorBuiltin?.de ?? ({} as typeof DE)) : DE; +const en: Record = (globalThis as { __NF_SHARED_TEXTS__?: boolean }).__NF_SHARED_TEXTS__ ? (builtin.__nextfloorBuiltin?.en ?? ({} as Record)) : EN; +builtin.__nextfloorBuiltin ??= { de, en }; + +// Further languages come as lang/.json beside the bundles. Only a Home Assistant running in such a +// language fetches its file; a key the file lacks stays English. The build tells the bundles which files +// exist, each with a hash of its content for the URL. +declare const __NF_LANGS__: Record | undefined; +const langFiles = (): Record => (typeof __NF_LANGS__ === "object" && __NF_LANGS__) || {}; + +type Texts = Record; +// keyed by language code: the texts, or the fetch still on its way; on globalThis, so the main bundle, +// the editor and the card editor share one fetch +const shared = globalThis as { __nextfloorTexts?: Map> }; +const fetched = (shared.__nextfloorTexts ??= new Map()); + +/** The language file a Home Assistant language reads, or undefined (German, English, or no file for it). */ +function fileOf(language: string): string | undefined { + const code = language.toLowerCase().split("-")[0]; + return code !== "de" && code !== "en" && code in langFiles() ? code : undefined; +} + +function textsOf(language: string): Texts | undefined { + const code = fileOf(language); + const entry = code === undefined ? undefined : fetched.get(code); + return entry instanceof Promise ? undefined : entry; +} + +/** + * True while an element still waits for the texts of its language: the first call fetches the file, and the + * element renders again once it has arrived. A file that cannot be read leaves the element in English. + */ +export function awaitingLanguage(hass: HomeAssistant | undefined, element: { requestUpdate(): void }): boolean { + const code = fileOf(hass?.language ?? navigator.language); + if (code === undefined) return false; + let entry = fetched.get(code); + if (entry === undefined) { + entry = fetch(new URL(`./lang/${code}.json?v=${langFiles()[code]}`, import.meta.url)) + .then((response) => (response.ok ? response.json() : {})) + .catch(() => ({})) + .then((texts: unknown) => void fetched.set(code, texts && typeof texts === "object" ? (texts as Texts) : {})); + fetched.set(code, entry); + } + if (!(entry instanceof Promise)) return false; + void entry.then(() => element.requestUpdate()); + return true; +} + +/** A text of the language file by its own key (names of pack items and paint colours), if it has one. */ +export function languageText(language: string, key: string): string | undefined { + return textsOf(language)?.[key]; +} + +export function translate(hass: HomeAssistant | undefined, key: Key, vars: Record = {}): string { + // German in German, a language file's text in its language, English otherwise + const language = hass?.language ?? navigator.language; + const german = language.startsWith("de"); + let s: string = (german ? undefined : textsOf(language)?.[key]) ?? (german ? de : en)[key] ?? en[key] ?? de[key] ?? key; + for (const [k, v] of Object.entries(vars)) s = s.replace(`{${k}}`, String(v)); + return s; +} + +export function formatNumber(hass: HomeAssistant | undefined, value: number, digits = 2): string { + return value.toLocaleString(hass?.language ?? undefined, { maximumFractionDigits: digits }); +} diff --git a/frontend/src/icons.test.ts b/frontend/src/icons.test.ts new file mode 100644 index 0000000..963bcc2 --- /dev/null +++ b/frontend/src/icons.test.ts @@ -0,0 +1,26 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { DeviceKind } from "./devices.ts"; +import { iconPath, iconSvg, mdiIcon } from "./icons.ts"; + +const KINDS: DeviceKind[] = ["light", "switch", "fan", "cover", "climate", "media", "lock", "sensor", "binary", "scene", "script"]; + +test("every kind of device has a path and an svg that contains it", () => { + for (const kind of KINDS) { + assert.match(iconPath(kind), /^M/, kind); + assert.ok(iconSvg(kind).includes(`d="${iconPath(kind)}"`), kind); + assert.ok(iconSvg(kind).startsWith(" { + assert.equal(new Set(KINDS.map(iconPath)).size, KINDS.length); +}); + +test("a chosen icon name is cleaned before it goes into markup", () => { + assert.ok(mdiIcon("mdi:lamp").includes('icon="mdi:lamp"')); + assert.ok(mdiIcon("lamp").includes('icon="mdi:lamp"')); + const hostile = mdiIcon('x">'); + assert.ok(!hostile.includes(" = { + light: "M8.5 17.5h7M9.5 20.5h5M12 2.5a6.5 6.5 0 0 0-3.5 12v1.5h7V14.5A6.5 6.5 0 0 0 12 2.5z", + switch: "M6 5h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM12 7.5v9M9 12h6", + fan: "M12 11.5c-1-3.5 0-7 2.5-7s2 4-2.5 7zm.5.5c3.5-1 7 0 7 2.5s-4 2-7-2.5zm-.5.5c1 3.5 0 7-2.5 7s-2-4 2.5-7zm-.5-.5c-3.5 1-7 0-7-2.5s4-2 7 2.5z", + cover: "M3.5 3.5h17v3h-17zM6 6.5v12M18 6.5v12M8.5 9.5h7M8.5 12.5h7M8.5 15.5h7", + climate: "M12 15V5.5a2.5 2.5 0 0 0-5 0V15a4.5 4.5 0 1 0 5 0zM9.5 9v7M15 5.5h5M15 9.5h4", + media: "M3.5 5.5h17v11h-17zM8 20.5h8M12 16.5v4M10 8.5v5l4.5-2.5z", + lock: "M5.5 10.5h13v9.5h-13zM8 10.5V7.5a4 4 0 0 1 8 0v3M12 14v3", + sensor: "M12 3.5a8.5 8.5 0 1 0 0 17 8.5 8.5 0 0 0 0-17zM12 7.5v4.5l3.5 2", + binary: "M5.5 20.5v-17h10v17M3.5 20.5h14M9 20.5v-13h4.5v13M12.5 14h.01", + scene: "M5.5 18.5l8-8M14 3.5l1 2.5 2.5 1-2.5 1-1 2.5-1-2.5-2.5-1 2.5-1zM18.5 12l.7 1.8 1.8.7-1.8.7-.7 1.8-.7-1.8-1.8-.7 1.8-.7z", + script: "M8.5 3.5h8.5a2 2 0 0 1 2 2v13a2 2 0 0 1-2 2H7.5a2 2 0 0 1-2-2v-2h9M8.5 3.5a2 2 0 0 0-2 2v10M9.5 8.5h6M9.5 11.5h4", +}; + +/** The path data of a device kind's icon. */ +export const iconPath = (kind: DeviceKind): string => SHAPES[kind]; + +/** Markup for a user-chosen icon: Home Assistant's own icon element, given a Material Design Icons name. */ +export function mdiIcon(name: string): string { + const safe = name.replace(/^mdi:/, "").replace(/[^a-z0-9-]/gi, ""); + return ``; +} + +/** Inline SVG for a device kind. Only static strings go in here. */ +export function iconSvg(kind: DeviceKind): string { + const look = 'fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"'; + return ``; +} diff --git a/frontend/src/import/dxf.test.ts b/frontend/src/import/dxf.test.ts new file mode 100644 index 0000000..555a19f --- /dev/null +++ b/frontend/src/import/dxf.test.ts @@ -0,0 +1,20 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { importDxf } from "./dxf.ts"; + +const dxf = (entities: string, units = "4") => + ["0", "SECTION", "2", "HEADER", "9", "$INSUNITS", "70", units, "0", "ENDSEC", "0", "SECTION", "2", "ENTITIES", entities, "0", "ENDSEC", "0", "EOF"].join("\n"); + +test("closed polylines become rooms, lines free walls, in metres with z down the plan", () => { + const room = ["0", "LWPOLYLINE", "8", "0", "90", "4", "70", "1", "10", "0", "20", "0", "10", "4000", "20", "0", "10", "4000", "20", "3000", "10", "0", "20", "3000"].join("\n"); + const line = ["0", "LINE", "8", "0", "10", "2000", "20", "0", "11", "2000", "21", "3000"].join("\n"); + const { building, report } = importDxf(dxf(`${room}\n${line}`)); + assert.deepEqual([report.rooms, report.walls], [1, 1]); + const r = building.floors[0].rooms[0]; + assert.deepEqual(r.points, [[0, 3], [4, 3], [4, 0], [0, 0]], "y mirrored into z, mm into m"); + assert.deepEqual(building.floors[0].walls![0].a, [2, 3]); +}); + +test("a drawing without shapes is refused", () => { + assert.throws(() => importDxf(dxf("")), /dxf_empty/); +}); diff --git a/frontend/src/import/dxf.ts b/frontend/src/import/dxf.ts new file mode 100644 index 0000000..6f51bd2 --- /dev/null +++ b/frontend/src/import/dxf.ts @@ -0,0 +1,91 @@ +// Import from DXF (AutoCAD, LibreCAD, QCAD, most CAD exports of a floor plan): closed polylines become rooms, lines and open polylines +// become free walls, all on one floor. DXF's y points up the drawing, NextFloor's z down the plan, so y is mirrored; the drawing's +// unit ($INSUNITS) turns into metres (millimetres when it says nothing and the drawing is large). + +import { emptyBuilding, newFloor, normalizeBuilding, uid, type Building, type FreeWall, type Room, type Vec2 } from "../model.ts"; +import type { ImportReport } from "./sweethome.ts"; + +/** The group code / value pairs of a DXF text. */ +function pairs(text: string): [number, string][] { + const lines = text.split(/\r?\n/); + const out: [number, string][] = []; + for (let i = 0; i + 1 < lines.length; i += 2) { + const code = Number(lines[i].trim()); + if (Number.isFinite(code)) out.push([code, lines[i + 1].trim()]); + } + return out; +} + +/** Metres per drawing unit from $INSUNITS (1 inch, 2 foot, 4 mm, 5 cm, 6 m); null when it does not say. */ +function unitOf(p: [number, string][]): number | null { + const at = p.findIndex(([c, v]) => c === 9 && v === "$INSUNITS"); + const value = at >= 0 ? Number(p[at + 1]?.[1]) : NaN; + return ({ 1: 0.0254, 2: 0.3048, 4: 0.001, 5: 0.01, 6: 1 } as Record)[value] ?? null; +} + +interface Shape { + points: Vec2[]; + closed: boolean; +} + +/** The lines and polylines of the ENTITIES section. */ +export function dxfShapes(text: string): { shapes: Shape[]; unit: number | null } { + const p = pairs(text); + const unit = unitOf(p); + const start = p.findIndex(([c, v], i) => c === 2 && v === "ENTITIES" && p[i - 1]?.[1] === "SECTION"); + const shapes: Shape[] = []; + if (start < 0) return { shapes, unit }; + let i = start + 1; + while (i < p.length && !(p[i][0] === 0 && p[i][1] === "ENDSEC")) { + const [code, value] = p[i]; + if (code !== 0) { + i++; + continue; + } + // the entity's own pairs, up to the next entity + let j = i + 1; + while (j < p.length && p[j][0] !== 0) j++; + const body = p.slice(i + 1, j); + if (value === "LINE") { + const get = (c: number) => Number(body.find(([k]) => k === c)?.[1] ?? NaN); + const pts: Vec2[] = [[get(10), get(20)], [get(11), get(21)]]; + if (pts.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y))) shapes.push({ points: pts, closed: false }); + } else if (value === "LWPOLYLINE") { + const xs = body.filter(([k]) => k === 10).map(([, v]) => Number(v)); + const ys = body.filter(([k]) => k === 20).map(([, v]) => Number(v)); + const flags = Number(body.find(([k]) => k === 70)?.[1] ?? 0); + const pts = xs.map((x, k) => [x, ys[k]] as Vec2).filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y)); + if (pts.length >= 2) shapes.push({ points: pts, closed: (flags & 1) === 1 }); + } + i = j; + } + return { shapes, unit }; +} + +const r3 = (v: number) => Math.round(v * 1000) / 1000; + +/** A building from a DXF drawing: one floor, closed polylines as rooms, everything else as free walls. */ +export function importDxf(text: string): { building: Building; report: ImportReport } { + const { shapes, unit: given } = dxfShapes(text); + if (!shapes.length) throw new Error("dxf_empty"); + const all = shapes.flatMap((s) => s.points); + const span = Math.max(Math.max(...all.map((p) => p[0])) - Math.min(...all.map((p) => p[0])), Math.max(...all.map((p) => p[1])) - Math.min(...all.map((p) => p[1]))); + // without a unit: a house drawn in millimetres spans thousands, in centimetres hundreds, in metres a few dozen + const unit = given ?? (span > 2000 ? 0.001 : span > 200 ? 0.01 : 1); + const x0 = Math.min(...all.map((p) => p[0])); + const y1 = Math.max(...all.map((p) => p[1])); + const at = ([x, y]: Vec2): Vec2 => [r3((x - x0) * unit), r3((y1 - y) * unit)]; + const floor = newFloor(uid("floor"), "Erdgeschoss", 0); + const rooms: Room[] = []; + const walls: FreeWall[] = []; + for (const s of shapes) { + const pts = s.points.map(at); + if (s.closed && pts.length >= 3) rooms.push({ id: uid("room"), name: `Raum ${rooms.length + 1}`, area_id: null, points: pts, floor_material: "wood", panel: [] }); + else for (let k = 0; k + 1 < pts.length; k++) if (Math.hypot(pts[k + 1][0] - pts[k][0], pts[k + 1][1] - pts[k][1]) > 0.05) walls.push({ id: uid("wall"), a: pts[k], b: pts[k + 1] }); + } + floor.rooms = rooms; + floor.walls = walls; + const b = emptyBuilding(); + b.floors = [floor]; + return { building: normalizeBuilding(b), report: { floors: 1, rooms: rooms.length, openings: 0, walls: walls.length, furniture: 0 } }; +} diff --git a/frontend/src/import/ifc.test.ts b/frontend/src/import/ifc.test.ts new file mode 100644 index 0000000..4f3257e --- /dev/null +++ b/frontend/src/import/ifc.test.ts @@ -0,0 +1,83 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { polygonArea } from "../model.ts"; +import { ifcEntities, importIfc } from "./ifc.ts"; + +// two storeys in millimetres; a 4 × 3 m kitchen as a rectangle profile, a living room as a polyline, the upper storey's bedroom turned 90° +const SAMPLE = `ISO-10303-21; +HEADER; +FILE_NAME('test.ifc','2026-11-03',(''),(''),'','',''); +ENDSEC; +DATA; +#1=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.); +#10=IFCCARTESIANPOINT((0.,0.,0.)); +#11=IFCAXIS2PLACEMENT3D(#10,$,$); +#12=IFCLOCALPLACEMENT($,#11); +#20=IFCBUILDINGSTOREY('a',$,'EG',$,$,#12,$,'Erdgeschoss',.ELEMENT.,0.); +#21=IFCBUILDINGSTOREY('b',$,'OG',$,$,#12,$,$,.ELEMENT.,2800.); +#30=IFCCARTESIANPOINT((2000.,1500.)); +#31=IFCAXIS2PLACEMENT2D(#30,$); +#32=IFCRECTANGLEPROFILEDEF(.AREA.,$,#31,4000.,3000.); +#33=IFCAXIS2PLACEMENT3D(#10,$,$); +#34=IFCDIRECTION((0.,0.,1.)); +#35=IFCEXTRUDEDAREASOLID(#32,#33,#34,2600.); +#36=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#35)); +#37=IFCPRODUCTDEFINITIONSHAPE($,$,(#36)); +#38=IFCCARTESIANPOINT((1000.,0.,0.)); +#39=IFCAXIS2PLACEMENT3D(#38,$,$); +#40=IFCLOCALPLACEMENT(#12,#39); +#41=IFCSPACE('c',$,'1',$,$,#40,#37,'K\\X2\\00FC\\X0\\che',.ELEMENT.,.INTERNAL.,$); +#50=IFCCARTESIANPOINT((0.,0.)); +#51=IFCCARTESIANPOINT((5000.,0.)); +#52=IFCCARTESIANPOINT((5000.,4000.)); +#53=IFCCARTESIANPOINT((0.,4000.)); +#54=IFCPOLYLINE((#50,#51,#52,#53,#50)); +#55=IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#54); +#56=IFCEXTRUDEDAREASOLID(#55,#33,#34,2600.); +#57=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#56)); +#58=IFCPRODUCTDEFINITIONSHAPE($,$,(#57)); +#59=IFCCARTESIANPOINT((5000.,0.,0.)); +#60=IFCAXIS2PLACEMENT3D(#59,$,$); +#61=IFCLOCALPLACEMENT(#12,#60); +#62=IFCSPACE('d',$,'2',$,$,#61,#58,'Wohnzimmer',.ELEMENT.,.INTERNAL.,$); +#70=IFCDIRECTION((0.,1.,0.)); +#71=IFCAXIS2PLACEMENT3D(#10,$,#70); +#72=IFCLOCALPLACEMENT(#12,#71); +#73=IFCSPACE('e',$,'Schlafen',$,$,#72,#37,$,.ELEMENT.,.INTERNAL.,$); +#80=IFCRELAGGREGATES('f',$,$,$,#20,(#41,#62)); +#81=IFCRELAGGREGATES('g',$,$,$,#21,(#73)); +ENDSEC; +END-ISO-10303-21; +`; + +test("the entities of an IFC file are read with their arguments", () => { + const all = ifcEntities(SAMPLE); + assert.equal(all.get(41)?.type, "IFCSPACE"); + assert.equal(all.get(41)?.args[7], "Küche"); + assert.deepEqual(all.get(1)?.args, [null, ".LENGTHUNIT.", ".MILLI.", ".METRE."]); +}); + +test("storeys become floors and spaces rooms, in metres, with their footprints", () => { + const { building, report } = importIfc(SAMPLE); + assert.equal(report.floors, 2); + assert.equal(report.rooms, 3); + const [eg, og] = building.floors; + assert.equal(eg.name, "Erdgeschoss"); + assert.equal(og.name, "OG"); + assert.equal(og.elevation, 2.8); + assert.deepEqual(eg.rooms.map((r) => r.name), ["Küche", "Wohnzimmer"]); + assert.ok(Math.abs(polygonArea(eg.rooms[0].points) - 12) < 1e-6); + assert.ok(Math.abs(polygonArea(eg.rooms[1].points) - 20) < 1e-6); + // the kitchen (x 1–5 m) and the living room (x 5–10 m) touch along x = 5 m + const maxKitchen = Math.max(...eg.rooms[0].points.map((p) => p[0])); + const minLiving = Math.min(...eg.rooms[1].points.map((p) => p[0])); + assert.ok(Math.abs(maxKitchen - minLiving) < 1e-6); + // the bedroom is the kitchen's rectangle turned 90°: 3 m wide, 4 m deep + const xs = og.rooms[0].points.map((p) => p[0]), zs = og.rooms[0].points.map((p) => p[1]); + assert.ok(Math.abs(Math.max(...xs) - Math.min(...xs) - 3) < 1e-6); + assert.ok(Math.abs(Math.max(...zs) - Math.min(...zs) - 4) < 1e-6); +}); + +test("a file without spaces is refused", () => { + assert.throws(() => importIfc("ISO-10303-21;\nDATA;\n#1=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.);\nENDSEC;"), /ifc_empty/); +}); diff --git a/frontend/src/import/ifc.ts b/frontend/src/import/ifc.ts new file mode 100644 index 0000000..a57aae7 --- /dev/null +++ b/frontend/src/import/ifc.ts @@ -0,0 +1,206 @@ +// Import from IFC (the BIM exchange format of Revit, ArchiCAD, Allplan, Vectorworks …): every storey becomes a floor at its elevation, +// every space (IfcSpace) a room with its name and footprint. Only the plain parts of IFC are read – rectangle and polyline profiles of +// an extruded solid, local placements with a turn about the vertical – which is what common exports write for spaces. Walls are not +// taken over: NextFloor draws its own from the rooms. IFC's y points north up the drawing, NextFloor's z down the plan, so y is mirrored. + +import { emptyBuilding, newFloor, normalizeBuilding, uid, type Building, type Floor, type Vec2 } from "../model.ts"; +import type { ImportReport } from "./sweethome.ts"; + +type Value = string | number | null | Ref | Value[]; +interface Ref { + ref: number; +} +interface Entity { + type: string; + args: Value[]; +} + +const isRef = (v: Value | undefined): v is Ref => typeof v === "object" && v !== null && !Array.isArray(v) && "ref" in v; + +/** The arguments of one entity: numbers, 'strings', #refs, $ (null), enums (.X.) and nested lists. */ +function parseArgs(text: string): Value[] { + let i = 0; + const value = (): Value => { + while (text[i] === " ") i++; + const c = text[i]; + if (c === "(") { + i++; + const list: Value[] = []; + while (i < text.length && text[i] !== ")") { + list.push(value()); + while (text[i] === " ") i++; + if (text[i] === ",") i++; + } + i++; + return list; + } + if (c === "'") { + let s = ""; + i++; + while (i < text.length) { + if (text[i] === "'" && text[i + 1] === "'") { + s += "'"; + i += 2; + } else if (text[i] === "'") { + i++; + break; + } else s += text[i++]; + } + return decodeText(s); + } + if (c === "#") { + const m = /^#(\d+)/.exec(text.slice(i))!; + i += m[0].length; + return { ref: Number(m[1]) }; + } + if (c === "$" || c === "*") { + i++; + return null; + } + // a number, an enum (.T.), or a typed value like IFCLABEL('x') + const m = /^[^,()]+/.exec(text.slice(i)); + const raw = m ? m[0].trim() : ""; + i += m ? m[0].length : 1; + if (text[i] === "(") return value(); + const n = Number(raw); + return Number.isFinite(n) && raw !== "" ? n : raw; + }; + const out: Value[] = []; + while (i < text.length) { + out.push(value()); + while (text[i] === " ") i++; + if (text[i] === ",") i++; + else break; + } + return out; +} + +/** IFC's escapes for letters beyond ASCII: \X2\00E4\X0\ (UTF-16 hex) and \S\ä (the upper half of Latin-1). */ +function decodeText(s: string): string { + return s + .replace(/\\X2\\([0-9A-Fa-f]+)\\X0\\/g, (_, hex: string) => String.fromCharCode(...(hex.match(/.{4}/g) ?? []).map((h) => parseInt(h, 16)))) + .replace(/\\S\\(.)/g, (_, ch: string) => String.fromCharCode(ch.charCodeAt(0) + 128)); +} + +/** The entities of the DATA section by their number. */ +export function ifcEntities(text: string): Map { + const map = new Map(); + const data = text.slice(Math.max(0, text.indexOf("DATA;"))); + for (const m of data.matchAll(/#(\d+)\s*=\s*([A-Z0-9_]+)\s*\(([\s\S]*?)\)\s*;(?=\s*(?:#|ENDSEC))/g)) map.set(Number(m[1]), { type: m[2], args: parseArgs(m[3]) }); + return map; +} + +type Transform = { x: number; y: number; z: number; c: number; s: number }; +const IDENTITY: Transform = { x: 0, y: 0, z: 0, c: 1, s: 0 }; +/** `inner` placed inside `outer`: turned and moved by it. */ +const compose = (outer: Transform, inner: Transform): Transform => ({ + x: outer.x + outer.c * inner.x - outer.s * inner.y, + y: outer.y + outer.s * inner.x + outer.c * inner.y, + z: outer.z + inner.z, + c: outer.c * inner.c - outer.s * inner.s, + s: outer.s * inner.c + outer.c * inner.s, +}); + +export function importIfc(text: string): { building: Building; report: ImportReport } { + const all = ifcEntities(text); + if (!all.size) throw new Error("ifc_empty"); + const get = (v: Value | undefined): Entity | undefined => (isRef(v) ? all.get(v.ref) : undefined); + const num = (v: Value | undefined): number => (typeof v === "number" ? v : NaN); + const point = (v: Value | undefined): number[] => ((get(v)?.args[0] as Value[] | undefined) ?? []).map((c) => num(c)); + + // the length unit: metres, or millimetres (PREFIX .MILLI.) – the most common export + const lengthUnit = [...all.values()].find((e) => e.type === "IFCSIUNIT" && e.args[1] === ".LENGTHUNIT."); + const unit = lengthUnit ? ({ ".MILLI.": 0.001, ".CENTI.": 0.01, ".DECI.": 0.1 } as Record)[String(lengthUnit.args[2])] ?? 1 : 1; + + /** An IfcAxis2Placement2D/3D as a transform (its x axis gives the turn). */ + const axis = (v: Value | undefined): Transform => { + const e = get(v); + if (!e) return IDENTITY; + const [x = 0, y = 0, z = 0] = point(e.args[0]); + const dir = get(e.type === "IFCAXIS2PLACEMENT3D" ? e.args[2] : e.args[1]); + const [dx = 1, dy = 0] = ((dir?.args[0] as Value[] | undefined) ?? []).map((c) => num(c)); + const len = Math.hypot(dx, dy) || 1; + return { x: x || 0, y: y || 0, z: z || 0, c: dx / len, s: dy / len }; + }; + /** An IfcLocalPlacement, through all the placements it is relative to. */ + const placement = (v: Value | undefined, depth = 0): Transform => { + const e = get(v); + if (!e || e.type !== "IFCLOCALPLACEMENT" || depth > 30) return IDENTITY; + return compose(placement(e.args[0], depth + 1), axis(e.args[1])); + }; + /** The footprint of a product's extruded solid in its own placement (rectangles and polylines). */ + const footprint = (shape: Value | undefined): Vec2[] | null => { + for (const rep of (get(shape)?.args[2] as Value[] | undefined) ?? []) { + for (const item of (get(rep)?.args[3] as Value[] | undefined) ?? []) { + const solid = get(item); + if (solid?.type !== "IFCEXTRUDEDAREASOLID") continue; + const profile = get(solid.args[0]); + const at = compose(axis(solid.args[1]), axis(profile?.args[2])); + let ring: Vec2[] = []; + if (profile?.type === "IFCRECTANGLEPROFILEDEF") { + const [w, d] = [num(profile.args[3]) / 2, num(profile.args[4]) / 2]; + ring = [[-w, -d], [w, -d], [w, d], [-w, d]]; + } else if (profile?.type === "IFCARBITRARYCLOSEDPROFILEDEF") { + const curve = get(profile.args[2]); + if (curve?.type === "IFCPOLYLINE") ring = ((curve.args[0] as Value[]) ?? []).map((p) => point(p) as unknown as Vec2); + } + ring = ring.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1])); + if (ring.length > 3 && Math.hypot(ring[0][0] - ring[ring.length - 1][0], ring[0][1] - ring[ring.length - 1][1]) < 1e-6) ring.pop(); + if (ring.length >= 3) return ring.map(([x, y]) => [at.x + at.c * x - at.s * y, at.y + at.s * x + at.c * y]); + } + } + return null; + }; + + // which space belongs to which storey: IfcRelAggregates (storey → spaces) or IfcRelContainedInSpatialStructure + const storeyOf = new Map(); + for (const [, e] of all) { + if (e.type === "IFCRELAGGREGATES" && isRef(e.args[4])) for (const part of (e.args[5] as Value[]) ?? []) if (isRef(part)) storeyOf.set(part.ref, e.args[4].ref); + if (e.type === "IFCRELCONTAINEDINSPATIALSTRUCTURE" && isRef(e.args[5])) for (const part of (e.args[4] as Value[]) ?? []) if (isRef(part)) storeyOf.set(part.ref, e.args[5].ref); + } + const storeys = [...all].filter(([, e]) => e.type === "IFCBUILDINGSTOREY").map(([id, e]) => ({ id, name: String(e.args[7] || e.args[2] || "") || null, elevation: num(e.args[9]) * unit })); + storeys.sort((a, b) => (a.elevation || 0) - (b.elevation || 0)); + + const rooms: { storey: number | null; name: string; ring: Vec2[] }[] = []; + for (const [id, e] of all) { + if (e.type !== "IFCSPACE") continue; + const local = footprint(e.args[6]); + if (!local) continue; + const at = placement(e.args[5]); + const ring = local.map(([x, y]): Vec2 => [(at.x + at.c * x - at.s * y) * unit, (at.y + at.s * x + at.c * y) * unit]); + const name = String(e.args[7] || e.args[2] || "") || `Raum ${rooms.length + 1}`; + rooms.push({ storey: storeyOf.get(id) ?? null, name, ring }); + } + if (!rooms.length) throw new Error("ifc_empty"); + + // plan coordinates: from the drawing's left, y mirrored into z + const pts = rooms.flatMap((r) => r.ring); + const x0 = Math.min(...pts.map((p) => p[0])); + const y1 = Math.max(...pts.map((p) => p[1])); + const r3 = (v: number) => Math.round(v * 1000) / 1000; + const floors: Floor[] = []; + const floorFor = new Map(); + const used = storeys.filter((s) => rooms.some((r) => r.storey === s.id)); + used.forEach((s, i) => { + const f = newFloor(uid("floor"), s.name ?? `Etage ${i + 1}`, Number.isFinite(s.elevation) ? r3(s.elevation) : i * 2.8); + floors.push(f); + floorFor.set(s.id, f); + }); + if (rooms.some((r) => r.storey === null || !floorFor.has(r.storey))) { + const f = newFloor(uid("floor"), floors.length ? "Weitere Räume" : "Erdgeschoss", floors.length ? floors[floors.length - 1].elevation + 2.8 : 0); + floors.push(f); + floorFor.set(null, f); + } + // each storey's height: up to the next one + floors.forEach((f, i) => { + const next = floors[i + 1]; + if (next && next.elevation - f.elevation > 1.8) f.height = r3(next.elevation - f.elevation - 0.2); + }); + for (const r of rooms) { + const f = floorFor.get(r.storey !== null && floorFor.has(r.storey) ? r.storey : null)!; + f.rooms.push({ id: uid("room"), name: r.name, area_id: null, points: r.ring.map(([x, y]) => [r3(x - x0), r3(y1 - y)]), floor_material: "wood", panel: [] }); + } + const b = emptyBuilding(); + b.floors = floors; + return { building: normalizeBuilding(b), report: { floors: floors.length, rooms: rooms.length, openings: 0, walls: 0, furniture: 0 } }; +} diff --git a/frontend/src/import/roomplan.test.ts b/frontend/src/import/roomplan.test.ts new file mode 100644 index 0000000..be04d13 --- /dev/null +++ b/frontend/src/import/roomplan.test.ts @@ -0,0 +1,55 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { importRoomPlan, isRoomPlan } from "./roomplan.ts"; + +/** A column-major 4×4 transform: the width axis points along (dx, dz), the centre is (x, y, z). */ +const tf = (x: number, y: number, z: number, dx = 1, dz = 0) => [dx, 0, dz, 0, 0, 1, 0, 0, -dz, 0, dx, 0, x, y, z, 1]; +const wall = (x: number, z: number, dx: number, dz: number, width: number) => ({ category: { wall: {} }, dimensions: [width, 2.6, 0.1], transform: tf(x, 1.3 - 0.9, z, dx, dz) }); + +// a 4 m × 3 m room whose corner lies at (10, 20), the phone 0.9 m above the floor (origin height) +const room = () => ({ + version: 2, + walls: [wall(12, 20, 1, 0, 4), wall(14, 21.5, 0, 1, 3), wall(12, 23, -1, 0, 4), wall(10, 21.5, 0, -1, 3)], + doors: [{ category: { door: { isOpen: false } }, dimensions: [0.9, 2.05, 0.1], transform: tf(11, 1.025 - 0.9 - 0.4 + 0.4 + 0.0 - 0.0 + (-0.9 + 0.9) - 0.125 + 0.125 - 0.0, 23) }], + windows: [{ category: { window: {} }, dimensions: [1.2, 1.2, 0.1], transform: tf(14, 0.4 + 0.6 + 0.9 - 0.9 - 0.4 + 0.4 - 0.0, 21.5, 0, 1) }], + objects: [{ category: { sofa: {} }, dimensions: [2, 0.9, 0.9], transform: tf(12, 0.2, 21.5) }, { category: { fireplace: {} }, dimensions: [1, 1, 1], transform: tf(12, 0, 22) }], +}); + +test("the walls of a scan become a room whose corner is near the origin", () => { + assert.ok(isRoomPlan(room())); + const { building, report } = importRoomPlan(room()); + const pts = building.floors[0].rooms[0].points; + assert.equal(pts.length, 4); + const xs = pts.map((p) => p[0]); + const zs = pts.map((p) => p[1]); + assert.deepEqual([Math.min(...xs), Math.min(...zs)], [0.5, 0.5]); + assert.ok(Math.abs(Math.max(...xs) - Math.min(...xs) - 4) < 0.05 && Math.abs(Math.max(...zs) - Math.min(...zs) - 3) < 0.05, "4 m × 3 m"); + assert.equal(report.rooms, 1); +}); + +test("doors and windows sit on the wall they are nearest to, windows with their sill", () => { + const { building } = importRoomPlan(room()); + const [door, win] = [building.floors[0].openings.find((o) => o.type === "door")!, building.floors[0].openings.find((o) => o.type === "window")!]; + assert.ok(door && win); + assert.equal(door.width, 0.9); + assert.ok(win.sill > 0.2 && win.sill < 1.5, `sill ${win.sill}`); + assert.notEqual(door.edge, win.edge, "on different walls"); +}); + +test("known objects become furniture and the rest is counted as skipped", () => { + const { building, report } = importRoomPlan(room()); + assert.deepEqual(building.floors[0].furniture.map((f) => f.type), ["sofa"]); + assert.equal(report.furniture, 1, "the fireplace was not taken over"); +}); + +test("a structure with several rooms gives several rooms, and a plan file is not taken for a scan", () => { + assert.equal(importRoomPlan({ rooms: [room(), room()] }).building.floors[0].rooms.length, 2); + assert.ok(!isRoomPlan({ version: 1, floors: [], settings: {} })); + assert.throws(() => importRoomPlan({ walls: [] }), /roomplan_empty/); +}); + +test("walls that do not close fall back to a rectangle round all of them", () => { + const open = { walls: [wall(12, 20, 1, 0, 4), wall(14, 21.5, 0, 1, 3)] }; + const pts = importRoomPlan(open).building.floors[0].rooms[0].points; + assert.equal(pts.length, 4); +}); diff --git a/frontend/src/import/roomplan.ts b/frontend/src/import/roomplan.ts new file mode 100644 index 0000000..5fab0c5 --- /dev/null +++ b/frontend/src/import/roomplan.ts @@ -0,0 +1,167 @@ +// Import of an Apple RoomPlan scan (the JSON of a CapturedRoom or CapturedStructure, as an iPhone or iPad with LiDAR and a scan app +// writes it): walls, doors, windows and openings with their sizes and 4×4 transforms. The walls of a room are chained into its +// outline, doors and windows go onto the nearest wall, and a few objects (sofa, bed, table …) become furniture. All of it on one floor. +// RoomPlan's world has y up; the plan's x and z are RoomPlan's x and z, so nothing is mirrored. + +import { emptyBuilding, newFloor, normalizeBuilding, uid, type Building, type Furniture, type FurnitureType, type Opening, type Room, type Vec2 } from "../model.ts"; +import type { ImportReport } from "./sweethome.ts"; + +interface Surface { + centre: [number, number, number]; + /** Unit vector of the surface's width in the plan, and its size [width, height, depth]. */ + dir: Vec2; + size: [number, number, number]; + kind: string; +} + +const r2 = (v: number) => Math.round(v * 100) / 100; + +/** The case name of a RoomPlan category: {"door": {"isOpen": false}} → "door". */ +function categoryOf(item: Record, fallback: string): string { + const c = item.category; + if (typeof c === "string") return c; + if (c && typeof c === "object") return Object.keys(c)[0] ?? fallback; + return fallback; +} + +function surface(raw: unknown, fallback: string): Surface | null { + const item = raw as Record | null; + const m = item?.transform; + const d = item?.dimensions; + if (!item || !Array.isArray(m) || m.length < 16 || !Array.isArray(d) || d.length < 3) return null; + const n = (v: unknown) => Number(v); + const len = Math.hypot(n(m[0]), n(m[2])); + if (![...m.slice(0, 16), ...d.slice(0, 3)].every((v) => Number.isFinite(n(v))) || len < 1e-6) return null; + return { centre: [n(m[12]), n(m[13]), n(m[14])], dir: [n(m[0]) / len, n(m[2]) / len], size: [n(d[0]), n(d[1]), n(d[2])], kind: categoryOf(item, fallback) }; +} + +const list = (room: Record, key: string, fallback: string) => (Array.isArray(room[key]) ? (room[key] as unknown[]) : []).map((s) => surface(s, fallback)).filter((s): s is Surface => !!s); + +/** The corner points of a closed chain of walls (by centre line), and the wall each edge follows. Null when they do not close. */ +function outline(walls: readonly Surface[]): { points: Vec2[]; edgeWall: number[] } | null { + if (walls.length < 3) return null; + const ends = walls.map((w): [Vec2, Vec2] => { + const h = w.size[0] / 2; + return [[w.centre[0] - w.dir[0] * h, w.centre[2] - w.dir[1] * h], [w.centre[0] + w.dir[0] * h, w.centre[2] + w.dir[1] * h]]; + }); + const dist = (a: Vec2, b: Vec2) => Math.hypot(a[0] - b[0], a[1] - b[1]); + const TOL = 0.4; + const used = new Set([0]); + const points: Vec2[] = [ends[0][0]]; + const edgeWall = [0]; + let tail = ends[0][1]; + while (used.size < walls.length) { + let best: { i: number; flip: boolean; d: number } | null = null; + for (let i = 0; i < walls.length; i++) { + if (used.has(i)) continue; + for (const flip of [false, true]) { + const d = dist(tail, ends[i][flip ? 1 : 0]); + if (d <= TOL && (!best || d < best.d)) best = { i, flip, d }; + } + } + if (!best) break; + const [head, far] = best.flip ? [ends[best.i][1], ends[best.i][0]] : [ends[best.i][0], ends[best.i][1]]; + // the corner lies halfway between where one wall ends and the next begins + points.push([(tail[0] + head[0]) / 2, (tail[1] + head[1]) / 2]); + edgeWall.push(best.i); + used.add(best.i); + tail = far; + } + if (used.size < walls.length || dist(tail, points[0]) > TOL) return null; + points[0] = [(tail[0] + points[0][0]) / 2, (tail[1] + points[0][1]) / 2]; + return { points, edgeWall }; +} + +/** The bounding rectangle of all wall ends, for a scan whose walls do not close into a loop. */ +function boxOf(walls: readonly Surface[]): Vec2[] { + const xs: number[] = []; + const zs: number[] = []; + for (const w of walls) { + const h = w.size[0] / 2; + for (const s of [-1, 1]) { + xs.push(w.centre[0] + s * w.dir[0] * h); + zs.push(w.centre[2] + s * w.dir[1] * h); + } + } + const [x0, x1, z0, z1] = [Math.min(...xs), Math.max(...xs), Math.min(...zs), Math.max(...zs)]; + return [[x0, z0], [x1, z0], [x1, z1], [x0, z1]]; +} + +function toSegment(p: Vec2, a: Vec2, b: Vec2): { dist: number; along: number; length: number } { + const [dx, dz] = [b[0] - a[0], b[1] - a[1]]; + const length = Math.hypot(dx, dz) || 1e-9; + const t = Math.min(length, Math.max(0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / length)); + return { dist: Math.hypot(p[0] - (a[0] + (dx / length) * t), p[1] - (a[1] + (dz / length) * t)), along: t, length }; +} + +/** What a scanned object becomes (RoomPlan category → NextFloor furniture type); everything else is left out. */ +const OBJECTS: Record = { + sofa: "sofa", bed: "bed", table: "table", chair: "chair", bathtub: "bathtub", toilet: "wc", sink: "sink", refrigerator: "fridge", + stove: "stove", oven: "stove", dishwasher: "dishwasher", washerDryer: "washer", storage: "tall_cabinet", television: "tv_board", +}; + +/** True when a parsed JSON looks like a RoomPlan scan (walls with sizes and transforms), not a NextFloor plan. */ +export function isRoomPlan(json: unknown): boolean { + const j = json as Record | null; + if (!j || typeof j !== "object" || "floors" in j || "settings" in j) return false; + const rooms = Array.isArray(j.rooms) ? (j.rooms as Record[]) : [j]; + return rooms.some((r) => r && Array.isArray(r.walls) && list(r, "walls", "wall").length > 0); +} + +/** A building from a RoomPlan scan: one floor, one room per scanned room. */ +export function importRoomPlan(json: unknown): { building: Building; report: ImportReport } { + const j = json as Record; + const scans = (Array.isArray(j.rooms) ? (j.rooms as Record[]) : [j]).filter((r) => r && typeof r === "object"); + const parsed = scans.map((s) => ({ walls: list(s, "walls", "wall"), doors: [...list(s, "doors", "door"), ...list(s, "openings", "opening")], windows: list(s, "windows", "window"), objects: list(s, "objects", "object") })).filter((s) => s.walls.length); + if (!parsed.length) throw new Error("roomplan_empty"); + const allWalls = parsed.flatMap((s) => s.walls); + // the floor is where the lowest wall stands (the scan's origin is the phone at the start of the scan) + const ground = Math.min(...allWalls.map((w) => w.centre[1] - w.size[1] / 2)); + const shape = parsed.map((s) => outline(s.walls)); + const all = parsed.flatMap((s, i) => shape[i]?.points ?? boxOf(s.walls)); + const [x0, z0] = [Math.min(...all.map((p) => p[0])) - 0.5, Math.min(...all.map((p) => p[1])) - 0.5]; + const at = ([x, z]: Vec2): Vec2 => [r2(x - x0), r2(z - z0)]; + const floor = newFloor(uid("floor"), "Erdgeschoss", 0); + floor.height = r2(Math.max(2.2, Math.min(4, Math.max(...allWalls.map((w) => w.size[1]))))); + const rooms: Room[] = []; + const furniture: Furniture[] = []; + parsed.forEach((s, i) => { + const out = shape[i]; + const points = (out?.points ?? boxOf(s.walls)).map(at); + const room: Room = { id: uid("room"), name: `Raum ${i + 1}`, area_id: null, points, floor_material: "wood", panel: [] }; + rooms.push(room); + for (const d of [...s.doors.map((v) => ({ v, window: false })), ...s.windows.map((v) => ({ v, window: true }))]) { + const centre: Vec2 = [d.v.centre[0] - x0, d.v.centre[2] - z0]; + let best: { edge: number; along: number; length: number; dist: number } | null = null; + points.forEach((a, edge) => { + const hit = toSegment(centre, a, points[(edge + 1) % points.length]); + if (hit.dist <= 0.6 && (!best || hit.dist < best.dist)) best = { edge, ...hit }; + }); + if (!best) continue; + const hit = best as { edge: number; along: number; length: number }; + const width = Math.min(hit.length, Math.max(0.3, d.v.size[0])); + const passage = d.v.kind === "opening"; + floor.openings.push({ + id: uid("op"), room_id: room.id, edge: hit.edge, + offset: r2(Math.min(hit.length - width / 2, Math.max(width / 2, hit.along))), width: r2(width), + type: d.window ? "window" : "door", + sill: d.window ? r2(Math.max(0, d.v.centre[1] - d.v.size[1] / 2 - ground)) : 0, + height: r2(d.v.size[1]), hinge: "left", leaves: width > 1.4 ? 2 : 1, swing: "in", ...(passage ? { style: "passage" } : {}), + cover: null, contact: null, contact2: null, tilt: null, + } as Opening); + } + for (const o of s.objects) { + const type = OBJECTS[o.kind]; + if (!type) continue; + const [dw, dd, dh] = [o.size[0], o.size[2], o.size[1]]; + if (dw < 0.1 || dd < 0.1) continue; + furniture.push({ id: uid("f"), type, x: r2(o.centre[0] - x0), z: r2(o.centre[2] - z0), rotation: Math.round(((Math.atan2(o.dir[1], o.dir[0]) * 180) / Math.PI + 360) % 360), w: r2(dw), d: r2(dd), h: r2(dh), variant: null, entity: null, power: null } as unknown as Furniture); + } + }); + floor.rooms = rooms; + floor.furniture = furniture; + const b = emptyBuilding(); + b.floors = [floor]; + const skipped = parsed.reduce((n, s) => n + s.objects.length, 0) - furniture.length; + return { building: normalizeBuilding(b), report: { floors: 1, rooms: rooms.length, openings: floor.openings.length, walls: 0, furniture: skipped } }; +} diff --git a/frontend/src/import/sweethome.test.ts b/frontend/src/import/sweethome.test.ts new file mode 100644 index 0000000..9e55661 --- /dev/null +++ b/frontend/src/import/sweethome.test.ts @@ -0,0 +1,107 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { deflateRawSync } from "node:zlib"; +import { homeToBuilding, importSweetHome, readHomeXml, roomOnWallLines } from "./sweethome.ts"; +import { zipEntries } from "./zip.ts"; + +/** A ZIP file with one deflated entry, built by hand like Sweet Home 3D writes it. */ +function zipOf(name: string, text: string): Uint8Array { + const data = Buffer.from(text, "utf8"); + const packed = deflateRawSync(data); + const nameBytes = Buffer.from(name); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(8, 8); + local.writeUInt32LE(packed.length, 18); + local.writeUInt32LE(data.length, 22); + local.writeUInt16LE(nameBytes.length, 26); + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE(8, 10); + central.writeUInt32LE(packed.length, 20); + central.writeUInt32LE(data.length, 24); + central.writeUInt16LE(nameBytes.length, 28); + central.writeUInt32LE(0, 42); + const centralStart = local.length + nameBytes.length + packed.length; + const end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); + end.writeUInt16LE(1, 8); + end.writeUInt16LE(1, 10); + end.writeUInt32LE(central.length + nameBytes.length, 12); + end.writeUInt32LE(centralStart, 16); + return new Uint8Array(Buffer.concat([local, nameBytes, packed, central, nameBytes, end])); +} + +const HOME = ` + + + + + + + + + + +`; + +test("the ZIP reader finds the entries of a .sh3d file", () => { + assert.deepEqual(zipEntries(zipOf("Home.xml", HOME)).map((e) => e.name), ["Home.xml"]); + assert.throws(() => zipEntries(new Uint8Array(40)), /not_zip/); +}); + +test("attributes in single quotes, as Sweet Home 3D writes them, are read too", () => { + const [room] = readHomeXml(""); + assert.deepEqual(room.points, [[1, 0.5], [3, 0.5], [3, 2.5]]); +}); + +test("Home.xml is read with its rooms' points and the entities in names", () => { + const room = readHomeXml(HOME).find((t) => t.name === "room")!; + assert.equal(room.attrs.name, "Wohnen & Essen"); + assert.deepEqual(room.points, [[0, 0], [5, 0], [5, 4], [0, 4]]); +}); + +test("a Sweet Home 3D plan becomes floors, rooms, doors, windows and free walls", async () => { + const { building, report } = await importSweetHome(zipOf("Home.xml", HOME)); + assert.deepEqual(report, { floors: 2, rooms: 2, openings: 2, walls: 1, furniture: 1 }); + const [ground, upper] = building.floors; + assert.equal(upper.elevation, 2.62); + assert.equal(upper.height, 2.4); + const [door, window] = ground.openings; + assert.equal(door.type, "door"); + assert.equal(door.edge, 2, "the front door sits on the edge from (5,4) to (0,4)"); + assert.equal(door.offset, 2.5); + assert.equal(window.type, "window"); + assert.equal(window.edge, 3); + assert.equal(window.sill, 0.95); + assert.deepEqual(ground.walls?.map((w) => [w.a, w.b, w.height]), [[[2.5, 1], [2.5, 3], 2]], "the wall along the room's edge is left to the room"); +}); + +test("a file without Home.xml or without rooms is refused", async () => { + await assert.rejects(importSweetHome(zipOf("Other.txt", "x")), /sh3d_no_xml/); + await assert.rejects(importSweetHome(zipOf("Home.xml", "")), /sh3d_empty/); +}); + +test("a room drawn along the inner wall faces moves out onto the walls' centre lines", () => { + // a 4 x 3 room inside 20 cm walls whose centre lines run 10 cm further out + const walls = [ + { a: [-0.1, -0.1], b: [4.1, -0.1], thickness: 0.2 }, + { a: [4.1, -0.1], b: [4.1, 3.1], thickness: 0.2 }, + { a: [4.1, 3.1], b: [-0.1, 3.1], thickness: 0.2 }, + ] as { a: [number, number]; b: [number, number]; thickness: number }[]; + const moved = roomOnWallLines([[0, 0], [4, 0], [4, 3], [0, 3]], walls).map(([x, z]) => [Math.round(x * 100) / 100, Math.round(z * 100) / 100]); + assert.deepEqual(moved, [[0, -0.1], [4.1, -0.1], [4.1, 3.1], [0, 3.1]], "three edges move, the edge without a wall stays"); +}); + +test("a wall that is a room edge for part of its length becomes a free wall only beyond the room (#40)", () => { + const tags = readHomeXml(` + + +`); + const { building } = homeToBuilding(tags); + const walls = building.floors[0].walls ?? []; + assert.equal(walls.length, 1, "one free wall, past the room"); + const [w] = walls; + assert.ok(Math.min(w.a[0], w.b[0]) > 3.5 && Math.min(w.a[0], w.b[0]) < 4.4, `it starts at the room's corner, not at 0 (${w.a[0]})`); + assert.equal(Math.max(w.a[0], w.b[0]), 10); +}); diff --git a/frontend/src/import/sweethome.ts b/frontend/src/import/sweethome.ts new file mode 100644 index 0000000..c563883 --- /dev/null +++ b/frontend/src/import/sweethome.ts @@ -0,0 +1,221 @@ +// Import from Sweet Home 3D: a .sh3d file is a ZIP with Home.xml (Sweet Home 3D 5.3 and newer). Levels become floors, rooms become +// rooms, doors and windows go onto the nearest room edge, and walls that are not the edge of a room become free walls. Sweet Home 3D +// works in centimetres with y pointing down the plan, which is NextFloor's z, so coordinates only need dividing by 100. + +import { emptyBuilding, newFloor, normalizeBuilding, uid, type Building, type FreeWall, type Opening, type Room, type Vec2 } from "../model.ts"; +import { zipEntries, zipRead } from "./zip.ts"; + +export interface ImportReport { + floors: number; + rooms: number; + openings: number; + walls: number; + /** Furniture of the file that was not taken over (NextFloor's own models are placed by hand). */ + furniture: number; +} + +type Attrs = Record; +interface Tag { + name: string; + attrs: Attrs; + points?: Vec2[]; +} + +const ENTITIES: Record = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" }; +const decode = (s: string) => s.replace(/&(#x?[0-9a-f]+|\w+);/gi, (m, e: string) => (e[0] === "#" ? String.fromCodePoint(Number.parseInt(e.slice(e[1] === "x" ? 2 : 1), e[1] === "x" ? 16 : 10)) : (ENTITIES[e] ?? m))); + +function attrsOf(text: string): Attrs { + const out: Attrs = {}; + // Sweet Home 3D writes its attributes in single quotes; double quotes are read as well + for (const m of text.matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) out[m[1]] = decode(m[2] ?? m[3]); + return out; +} + +/** The elements of Home.xml that matter here, with the points of each room. */ +export function readHomeXml(xml: string): Tag[] { + const tags: Tag[] = []; + let room: Tag | null = null; + for (const m of xml.matchAll(/<(\/?)(level|room|point|wall|doorOrWindow|pieceOfFurniture)\b([^>]*?)(\/?)>/g)) { + const [, closing, name, rest, selfClosing] = m; + if (closing) { + if (name === "room") room = null; + continue; + } + const attrs = attrsOf(rest); + if (name === "point") { + if (room) room.points!.push([Number(attrs.x) / 100, Number(attrs.y) / 100]); + continue; + } + const tag: Tag = { name, attrs, ...(name === "room" ? { points: [] } : {}) }; + tags.push(tag); + if (name === "room" && !selfClosing) room = tag; + } + return tags; +} + +const num = (a: Attrs, key: string, fallback: number) => (Number.isFinite(Number(a[key])) && a[key] !== undefined ? Number(a[key]) : fallback); +const r2 = (v: number) => Math.round(v * 1000) / 1000; + +/** Distance from p to the segment a-b, and how far along it (metres from a). */ +function toSegment(p: Vec2, a: Vec2, b: Vec2): { dist: number; along: number; length: number } { + const [dx, dz] = [b[0] - a[0], b[1] - a[1]]; + const length = Math.hypot(dx, dz) || 1e-9; + const t = Math.max(0, Math.min(length, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / length)); + const q: Vec2 = [a[0] + (dx * t) / length, a[1] + (dz * t) / length]; + return { dist: Math.hypot(p[0] - q[0], p[1] - q[1]), along: t, length }; +} + +function openingType(a: Attrs): Opening["type"] { + const text = `${a.name ?? ""} ${a.catalogId ?? ""}`.toLowerCase(); + if (/garage|sectional|rolltor/.test(text)) return "garage"; + if (/door|tür|tuer|porte|puerta|deur|haustür/.test(text) && !/window|fenster/.test(text)) return "door"; + return "window"; +} + +interface WallLine { + a: Vec2; + b: Vec2; + thickness: number; +} + +/** + * Sweet Home 3D draws a room along the inner faces of its walls, NextFloor along the walls' middle (neighbours share one edge). + * Each room edge that runs along a wall moves out onto that wall's centre line; the corners are where the moved edges meet. + */ +export function roomOnWallLines(points: readonly Vec2[], walls: readonly WallLine[]): Vec2[] { + const n = points.length; + const lines = points.map((p, i) => { + const q = points[(i + 1) % n]; + const [dx, dz] = [q[0] - p[0], q[1] - p[1]]; + const len = Math.hypot(dx, dz) || 1e-9; + const dir: Vec2 = [dx / len, dz / len]; + const mid: Vec2 = [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2]; + let shift: Vec2 = [0, 0]; + for (const w of walls) { + const [wx, wz] = [w.b[0] - w.a[0], w.b[1] - w.a[1]]; + const wl = Math.hypot(wx, wz) || 1e-9; + if (Math.abs((dir[0] * wz - dir[1] * wx) / wl) > 0.05) continue; // not parallel + // how far the wall's centre line lies from this edge, across it, and whether the wall runs past the edge's middle + const across = ((w.a[0] - mid[0]) * -dir[1] + (w.a[1] - mid[1]) * dir[0]); + const along = ((mid[0] - w.a[0]) * wx + (mid[1] - w.a[1]) * wz) / wl; + if (Math.abs(across) > w.thickness / 2 + 0.06 || along < -0.05 || along > wl + 0.05) continue; + shift = [-dir[1] * across, dir[0] * across]; + break; + } + return { p: [p[0] + shift[0], p[1] + shift[1]] as Vec2, dir }; + }); + return lines.map((cur, i) => { + const prev = lines[(i - 1 + n) % n]; + // the corner: where the previous edge's line meets this one's + const cross = prev.dir[0] * cur.dir[1] - prev.dir[1] * cur.dir[0]; + if (Math.abs(cross) < 1e-6) return cur.p; + const t = ((cur.p[0] - prev.p[0]) * cur.dir[1] - (cur.p[1] - prev.p[1]) * cur.dir[0]) / cross; + return [prev.p[0] + prev.dir[0] * t, prev.p[1] + prev.dir[1] * t] as Vec2; + }); +} + +/** A NextFloor plan from the elements of Home.xml. */ +export function homeToBuilding(tags: readonly Tag[]): { building: Building; report: ImportReport } { + const b = emptyBuilding(); + const report: ImportReport = { floors: 0, rooms: 0, openings: 0, walls: 0, furniture: 0 }; + const levels = tags.filter((t) => t.name === "level"); + const levelIds = levels.length ? levels.map((l) => l.attrs.id ?? "") : [""]; + const walls = tags.filter((t) => t.name === "wall"); + const defaultHeight = walls.length ? Math.max(...walls.map((w) => num(w.attrs, "height", 250))) / 100 : 2.5; + const sorted = levels.length ? [...levels].sort((p, q) => num(p.attrs, "elevation", 0) - num(q.attrs, "elevation", 0) || num(p.attrs, "elevationIndex", 0) - num(q.attrs, "elevationIndex", 0)) : [{ name: "level", attrs: { id: "" } } as Tag]; + sorted.forEach((level, index) => { + const id = level.attrs.id ?? ""; + const onLevel = (t: Tag) => (levels.length ? (t.attrs.level ?? levelIds[0]) === id : true); + const floor = newFloor(uid("floor"), level.attrs.name || (index === 0 ? "Erdgeschoss" : `Etage ${index + 1}`), r2(num(level.attrs, "elevation", 0) / 100)); + floor.height = r2(num(level.attrs, "height", defaultHeight * 100) / 100); + + const wallLines: WallLine[] = walls.filter(onLevel).map((w) => ({ a: [num(w.attrs, "xStart", 0) / 100, num(w.attrs, "yStart", 0) / 100], b: [num(w.attrs, "xEnd", 0) / 100, num(w.attrs, "yEnd", 0) / 100], thickness: num(w.attrs, "thickness", 10) / 100 })); + const rooms: Room[] = tags + .filter((t) => t.name === "room" && onLevel(t) && (t.points?.length ?? 0) >= 3) + .map((t, k) => ({ id: uid("room"), name: t.attrs.name || `Raum ${k + 1}`, area_id: null, points: roomOnWallLines(t.points!, wallLines).map(([x, z]) => [r2(x), r2(z)] as Vec2), floor_material: "wood", panel: [] })); + floor.rooms = rooms; + + // doors and windows: onto the nearest room edge + for (const t of tags.filter((x) => x.name === "doorOrWindow" && onLevel(x))) { + const centre: Vec2 = [num(t.attrs, "x", 0) / 100, num(t.attrs, "y", 0) / 100]; + const reach = Math.max(0.6, num(t.attrs, "depth", 30) / 100 + 0.3); + let best: { room: Room; edge: number; along: number; length: number; dist: number } | null = null; + for (const room of rooms) { + room.points.forEach((a, edge) => { + const hit = toSegment(centre, a, room.points[(edge + 1) % room.points.length]); + if (hit.dist <= reach && (!best || hit.dist < best.dist)) best = { room, edge, ...hit }; + }); + } + if (!best) continue; + const { room, edge, along, length } = best as { room: Room; edge: number; along: number; length: number }; + const type = openingType(t.attrs); + const width = Math.min(length, Math.max(0.3, num(t.attrs, "width", 90) / 100)); + floor.openings.push({ + id: uid("op"), + room_id: room.id, + edge, + offset: r2(Math.min(length - width / 2, Math.max(width / 2, along))), + width: r2(width), + type, + sill: type === "window" ? r2(num(t.attrs, "elevation", 90) / 100) : 0, + height: r2(num(t.attrs, "height", type === "window" ? 130 : 205) / 100), + hinge: "left", + leaves: width > 1.4 ? 2 : 1, + swing: "in", + cover: null, + contact: null, + contact2: null, + tilt: null, + } as Opening); + } + + // walls that are not the edge of a room stand on their own + const free: FreeWall[] = []; + for (const t of walls.filter(onLevel)) { + const a: Vec2 = [num(t.attrs, "xStart", 0) / 100, num(t.attrs, "yStart", 0) / 100]; + const e: Vec2 = [num(t.attrs, "xEnd", 0) / 100, num(t.attrs, "yEnd", 0) / 100]; + if (Math.hypot(e[0] - a[0], e[1] - a[1]) < 0.1) continue; + const tolerance = Math.max(0.15, num(t.attrs, "thickness", 10) / 100); + // a wall that runs along room edges (also one long wall along several rooms) is already built by those rooms + const nearEdge = (p: Vec2) => rooms.some((room) => room.points.some((r, i) => toSegment(p, r, room.points[(i + 1) % room.points.length]).dist < tolerance)); + // only the stretches that run along no room edge become free walls: a wall that is a room edge for part of its + // length would otherwise stand twice there, once as the room's wall and once on its own (#40) + const length = Math.hypot(e[0] - a[0], e[1] - a[1]); + const samples = Math.max(12, Math.ceil(length / 0.1)); + const at = (i: number): Vec2 => [a[0] + ((e[0] - a[0]) * i) / samples, a[1] + ((e[1] - a[1]) * i) / samples]; + const open = Array.from({ length: samples + 1 }, (_, i) => !nearEdge(at(i))); + for (let i = 0; i <= samples; ) { + if (!open[i]) { + i++; + continue; + } + let j = i; + while (j + 1 <= samples && open[j + 1]) j++; + // a stretch reaches to the neighbouring covered sample, where the room's wall takes over + const [from, to] = [at(Math.max(0, i - 1)), at(Math.min(samples, j + 1))]; + if (Math.hypot(to[0] - from[0], to[1] - from[1]) >= 0.3) + free.push({ id: uid("wall"), a: [r2(from[0]), r2(from[1])], b: [r2(to[0]), r2(to[1])], thickness: r2(num(t.attrs, "thickness", 10) / 100), height: t.attrs.height ? r2(num(t.attrs, "height", 250) / 100) : null }); + i = j + 1; + } + } + floor.walls = free; + + report.rooms += rooms.length; + report.openings += floor.openings.length; + report.walls += free.length; + if (rooms.length || free.length) b.floors.push(floor); + }); + report.floors = b.floors.length; + report.furniture = tags.filter((t) => t.name === "pieceOfFurniture").length; + return { building: normalizeBuilding(b), report }; +} + +/** Reads a Sweet Home 3D file (.sh3d) into a plan. */ +export async function importSweetHome(data: Uint8Array): Promise<{ building: Building; report: ImportReport }> { + const entry = zipEntries(data).find((e) => e.name === "Home.xml"); + if (!entry) throw new Error("sh3d_no_xml"); + const xml = new TextDecoder().decode(await zipRead(data, entry)); + const result = homeToBuilding(readHomeXml(xml)); + if (result.report.rooms === 0 && result.report.walls === 0) throw new Error("sh3d_empty"); + return result; +} diff --git a/frontend/src/import/zip.ts b/frontend/src/import/zip.ts new file mode 100644 index 0000000..c00f3d1 --- /dev/null +++ b/frontend/src/import/zip.ts @@ -0,0 +1,55 @@ +// A small ZIP reader for importing plans from other programs (a Sweet Home 3D .sh3d file is a ZIP): finds the entries through the +// central directory and inflates them with the browser's own DecompressionStream. Stored and deflated entries only. + +export interface ZipEntry { + name: string; + /** 0 = stored, 8 = deflated. */ + method: number; + compressedSize: number; + offset: number; +} + +const u16 = (b: DataView, at: number) => b.getUint16(at, true); +const u32 = (b: DataView, at: number) => b.getUint32(at, true); + +/** The entries of a ZIP file, read from its central directory. */ +export function zipEntries(data: Uint8Array): ZipEntry[] { + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + // the end-of-central-directory record sits in the last 64 KiB + 22 bytes + let end = -1; + for (let i = data.length - 22; i >= Math.max(0, data.length - 65557); i--) { + if (u32(view, i) === 0x06054b50) { + end = i; + break; + } + } + if (end < 0) throw new Error("not_zip"); + const count = u16(view, end + 10); + let at = u32(view, end + 16); + const entries: ZipEntry[] = []; + const names = new TextDecoder(); + for (let n = 0; n < count; n++) { + if (u32(view, at) !== 0x02014b50) throw new Error("not_zip"); + const method = u16(view, at + 10); + const compressedSize = u32(view, at + 20); + const nameLength = u16(view, at + 28); + const extraLength = u16(view, at + 30); + const commentLength = u16(view, at + 32); + const localHeader = u32(view, at + 42); + const name = names.decode(data.subarray(at + 46, at + 46 + nameLength)); + // the data starts after the local header, whose name and extra field may differ in length from the central one + const offset = localHeader + 30 + u16(view, localHeader + 26) + u16(view, localHeader + 28); + entries.push({ name, method, compressedSize, offset }); + at += 46 + nameLength + extraLength + commentLength; + } + return entries; +} + +/** The bytes of one entry, inflated. */ +export async function zipRead(data: Uint8Array, entry: ZipEntry): Promise { + const raw = data.subarray(entry.offset, entry.offset + entry.compressedSize); + if (entry.method === 0) return raw; + if (entry.method !== 8) throw new Error("zip_method"); + const stream = new Blob([raw.slice() as Uint8Array]).stream().pipeThrough(new DecompressionStream("deflate-raw")); + return new Uint8Array(await new Response(stream).arrayBuffer()); +} diff --git a/frontend/src/kiosk.test.ts b/frontend/src/kiosk.test.ts new file mode 100644 index 0000000..0e3fd21 --- /dev/null +++ b/frontend/src/kiosk.test.ts @@ -0,0 +1,31 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { nightActive } from "./kiosk.ts"; +import type { HomeAssistant } from "./types.ts"; + +const at = (h: number, m = 0) => new Date(2026, 0, 15, h, m); +const sun = (state: string) => ({ states: { "sun.sun": { entity_id: "sun.sun", state, attributes: {} } } }) as unknown as HomeAssistant; + +test("off, empty and nonsense never dim", () => { + for (const night of [undefined, "", "off", "nonsense", "22-06"]) assert.equal(nightActive(night, undefined, at(23)), false, String(night)); +}); + +test("sun mode follows the sun entity", () => { + assert.equal(nightActive("sun", sun("below_horizon"), at(12)), true); + assert.equal(nightActive("sun", sun("above_horizon"), at(2)), false); + assert.equal(nightActive("sun", undefined, at(2)), false); +}); + +test("a daytime range includes its start and excludes its end", () => { + assert.equal(nightActive("13:00-14:30", undefined, at(13, 0)), true); + assert.equal(nightActive("13:00-14:30", undefined, at(14, 29)), true); + assert.equal(nightActive("13:00-14:30", undefined, at(14, 30)), false); + assert.equal(nightActive("13:00-14:30", undefined, at(12, 59)), false); +}); + +test("a range past midnight covers both sides of it", () => { + assert.equal(nightActive("22:00 - 06:30", undefined, at(23, 15)), true); + assert.equal(nightActive("22:00-06:30", undefined, at(1)), true); + assert.equal(nightActive("22:00-06:30", undefined, at(6, 30)), false); + assert.equal(nightActive("22:00-06:30", undefined, at(12)), false); +}); diff --git a/frontend/src/kiosk.ts b/frontend/src/kiosk.ts new file mode 100644 index 0000000..d34cfe2 --- /dev/null +++ b/frontend/src/kiosk.ts @@ -0,0 +1,23 @@ +// Wall-tablet mode of the dashboard card: decides when the card dims for the night. + +import type { HomeAssistant } from "./types.ts"; + +const RANGE = /^(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})$/; + +const minutesOfDay = (hours: string, minutes: string) => Number(hours) * 60 + Number(minutes); + +/** + * Whether the night dimming is on right now. `night` is "off" (or empty), "sun" (dim while the sun is + * down) or a daily range such as "22:00-06:30", which may run past midnight. Anything else counts as off. + */ +export function nightActive(night: string | undefined, hass: HomeAssistant | undefined, now = new Date()): boolean { + if (!night || night === "off") return false; + if (night === "sun") return hass?.states["sun.sun"]?.state === "below_horizon"; + const range = RANGE.exec(night.trim()); + if (!range) return false; + const start = minutesOfDay(range[1], range[2]); + const end = minutesOfDay(range[3], range[4]); + const current = now.getHours() * 60 + now.getMinutes(); + const overnight = start > end; + return overnight ? current >= start || current < end : current >= start && current < end; +} diff --git a/frontend/src/light-effects-review.test.ts b/frontend/src/light-effects-review.test.ts new file mode 100644 index 0000000..87abbe4 --- /dev/null +++ b/frontend/src/light-effects-review.test.ts @@ -0,0 +1,196 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { lightAnimation, animateGlow } from "./light-effects.ts"; +import { lightEffectFields } from "./components/editor/light-effect-fields.ts"; + +import { emptyBuilding, newFloor } from "./model.ts"; +import { exportFile, parseExport } from "./transfer.ts"; + + test("shareable exports remove private program names while private roundtrips retain prototype keys", () => { + const building = emptyBuilding(); + const floor = newFloor("f", "Synthetic", 0); + const mapping = JSON.parse('{"private-synthetic-evening-program":"future","__proto__":"pulse","constructor":"rainbow","toString":"flicker"}'); + floor.furniture = [{ id: "lamp", type: "lamp_floor", entity: "light.synthetic", x: 1, z: 1, w: 1, d: 1, h: 1, rotation: 0, variant: null, effect_animations: mapping }]; + building.floors = [floor]; + assert.deepEqual(parseExport(JSON.stringify(exportFile(building, false))).floors[0].furniture[0].effect_animations, mapping); + const shared = exportFile(building, true); + assert.equal(JSON.stringify(shared).includes("private-synthetic-evening-program"), false); + assert.equal(shared.building.floors[0].furniture[0].effect_animations, undefined); + assert.deepEqual(building.floors[0].furniture[0].effect_animations, mapping); +}); + + +function editorAction(mapping: Record, name: string, value?: string) { + const patches: any[] = []; + const nodes = templates(lightEffectFields(host, { effect_animations: mapping }, value === undefined ? [] : [name], (p) => patches.push(p))); + const node = value === undefined ? nodes.find((n) => n.strings.join("").includes('type="text"')) : nodes.find((n) => n.strings.join("").includes(" n.strings.join("").includes('data-effect-feedback') && n.strings.join("").includes('role="status"')), "validation feedback must have reserved inline space"); + const input = { value: value ?? name, message: "", reported: false, setCustomValidity(message: string) { this.message = message; }, reportValidity() { this.reported = true; } }; + node.values.filter((v: any) => typeof v === "function").at(-1)({ target: input }); + return { patches, input }; +} + +test("editor enforces exact name length for manual and HA-list additions", () => { + for (const select of [false, true]) { + assert.equal(editorAction({}, "x".repeat(255), select ? "pulse" : undefined).patches.length, 1); + for (const name of ["", "x".repeat(256)]) { + const result = editorAction({}, name, select ? "pulse" : undefined); + assert.equal(result.patches.length, 0); + assert.ok(result.input.message); + assert.equal(result.input.reported, true); + } + } + assert.deepEqual(editorAction({}, " exact ").patches[0], { effect_animations: { " exact ": "none" } }); +}); + +test("editor counts Unicode code points for manual input, HA-list choices and existing mappings", () => { + const accepted = ["💡", "💡".repeat(128), "💡".repeat(255), "a".repeat(127) + "💡".repeat(128), " e\u0301" + "💡".repeat(251) + " "]; + const rejected = ["💡".repeat(256), "a".repeat(128) + "💡".repeat(128), " e\u0301" + "💡".repeat(252) + " "]; + for (const name of accepted) { + for (const select of [false, true]) { + const result = editorAction({}, name, select ? "pulse" : undefined); + assert.deepEqual(result.patches, [{ effect_animations: { [name]: select ? "pulse" : "none" } }]); + assert.equal(result.input.message, ""); + } + const imported = parseExport(JSON.stringify(exportFile((() => { + const building = emptyBuilding(); + const floor = newFloor("unicode", "Synthetic", 0); + floor.furniture = [{ id: "lamp", type: "lamp_floor", x: 1, z: 1, w: 1, d: 1, h: 1, rotation: 0, variant: null, effect_animations: { [name]: "future" } }]; + building.floors = [floor]; + return building; + })(), false))).floors[0].furniture[0].effect_animations!; + assert.deepEqual(editorAction(imported, name, "rainbow").patches, [{ effect_animations: { [name]: "rainbow" } }]); + assert.deepEqual(editorAction(imported, name, "").patches, [{ effect_animations: {} }]); + } + for (const name of rejected) { + for (const mapping of [{}, { [name]: "future" }]) { + for (const select of [false, true]) { + const result = editorAction(mapping, name, select ? "pulse" : undefined); + assert.equal(result.patches.length, 0); + assert.ok(result.input.message); + assert.equal(result.input.reported, true); + } + } + } +}); + +test("manual effect input does not impose an HTML UTF-16 maxlength", () => { + const nodes = templates(lightEffectFields(host, {}, [], () => {})); + const input = nodes.find((n) => n.strings.join("").includes('type="text"')); + assert.ok(input); + assert.doesNotMatch(input.strings.join(""), /maxLength/i); +}); + +test("editor caps additions at 100 but permits existing updates and deletions without losing future entries", () => { + const mapping = Object.fromEntries(Array.from({ length: 100 }, (_, i) => [`program-${i}`, "future"])); + for (const select of [false, true]) { + const result = editorAction(mapping, "new", select ? "rainbow" : undefined); + assert.equal(result.patches.length, 0); + assert.ok(result.input.message); + } + assert.equal(Object.keys(editorAction(Object.fromEntries(Object.entries(mapping).slice(1)), "new").patches[0].effect_animations).length, 100); + const changed = editorAction(mapping, "program-0", "pulse").patches[0].effect_animations; + assert.equal(changed["program-0"], "pulse"); + assert.equal(changed["program-1"], "future"); + assert.equal(Object.keys(editorAction(mapping, "program-0", "").patches[0].effect_animations).length, 99); + assert.equal(editorAction(mapping, "program-0").patches.length, 0, "adding an existing name must not overwrite its mapping"); +}); + +import { furnitureLinks } from "./components/editor/forms/furniture-links.ts"; + +test("relay lamps use their colour source for effects and editor list but retain relay state", async () => { + (globalThis as any).__NF_VIEWER_HASH__ = "synthetic-test"; + const { NfView3d } = await import("./components/view3d.ts"); + const floor = newFloor("f", "Synthetic", 0); + const item = { id: "relay-lamp", type: "lamp_floor", entity: "switch.relay", color_entity: "light.bulb", x: 1, z: 1, w: 0.3, d: 0.3, h: 1, rotation: 0, variant: null, effect_animations: { Demo: "pulse", Other: "rainbow" } } as any; + const hass = { states: { + "switch.relay": { entity_id: "switch.relay", state: "on", attributes: { effect: "Wrong", effect_list: ["Wrong"] } }, + "light.bulb": { entity_id: "light.bulb", state: "on", attributes: { effect: "Demo", effect_list: ["Demo", "Other"], color_mode: "white", brightness: 100 } }, + } } as any; + const view = Object.create(NfView3d.prototype) as any; + const marker = () => view.lampMarker(hass, floor, item, "switch.relay"); + assert.equal(marker().effect, "pulse"); + const base = marker().glow; + assert.ok(base && base.level > 0 && base.level < 1); + assert.deepEqual(animateGlow(base, "pulse", 0.75)?.color, base.color, "white/default colour basis is preserved"); + hass.states["light.bulb"].attributes.effect = "Other"; + assert.equal(marker().effect, "rainbow"); + for (const state of ["off", "unavailable", "unknown"]) { + hass.states["switch.relay"].state = state; + assert.equal(marker().effect, undefined); + assert.equal(marker().glow, null); + } + hass.states["switch.relay"].state = "on"; + for (const state of ["off", "unavailable", "unknown"]) { + hass.states["light.bulb"].state = state; + assert.equal(marker().effect, undefined); + assert.equal(marker().active, true); + assert.equal(marker().unavailable, false); + } + const doc = emptyBuilding(); doc.floors = [floor]; + const nodes = templates(furnitureLinks({ ...host, hass, doc } as any, item, { update() {} })); + assert.ok(nodes.some((n) => n.values.includes("Other"))); + assert.equal(nodes.some((n) => n.values.includes("Wrong")), false); +}); + +import { NextFloorViewer } from "./viewer/viewer3d.ts"; + +test("one shared effect timer stops for no participants, hidden views/document, offscreen and disposal, then resumes", (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + const previous = Object.getOwnPropertyDescriptor(globalThis, "document"); + const doc = { hidden: false, removeEventListener() {} }; + Object.defineProperty(globalThis, "document", { configurable: true, value: doc }); + const viewer = Object.create(NextFloorViewer.prototype) as any; + const floor = { floor: { id: "f" }, o: 1 }; + let lamps = 0, glows = 0, frames = 0; + Object.assign(viewer, { floors: [floor], effectFloors: new Set(["f"]), onScreen: true, disposed: false, lowQuality: false, buildLamps() { lamps++; }, buildGlow() { glows++; }, invalidate() { frames++; } }); + try { + viewer.scheduleEffects(); + const timer = viewer.effectTimer; + for (let i = 0; i < 100; i++) viewer.scheduleEffects(); + assert.equal(viewer.effectTimer, timer); + t.mock.timers.tick(1000); + assert.equal(lamps, 1); assert.equal(glows, 1); assert.equal(frames, 1); + for (const hide of [() => viewer.effectFloors.clear(), () => floor.o = 0, () => doc.hidden = true, () => viewer.onScreen = false, () => viewer.disposed = true]) { + viewer.scheduleEffects(); + hide(); + viewer.scheduleEffects(); + assert.equal(viewer.effectTimer, undefined); + t.mock.timers.tick(1000); + assert.equal(lamps, 1); + viewer.effectFloors.add("f"); floor.o = 1; doc.hidden = false; viewer.onScreen = true; viewer.disposed = false; + } + viewer.scheduleEffects(); t.mock.timers.tick(1000); + assert.equal(lamps, 2); + viewer.scheduleEffects(); + const noop = { dispose() {}, disconnect() {}, remove() {} }; + for (const key of ["weatherLayer", "mapLayer", "energyLayer", "soundLayer", "screenLayer", "pictureLayer", "waterLayer", "resizeObserver", "controls", "patternTexture", "blindTexture", "haloTexture", "labels"]) viewer[key] = noop; + viewer.ground = { geometry: noop, material: noop }; viewer.robots = new Map(); viewer.robotTrails = new Map(); viewer.trailTimers = new Map(); viewer.clear = () => {}; viewer.buildRoofMesh = () => {}; + viewer.renderer = { dispose() {}, forceContextLoss() {}, domElement: noop }; + const previousCancel = globalThis.cancelAnimationFrame; + globalThis.cancelAnimationFrame = () => {}; + try { viewer.dispose(); } finally { if (previousCancel) globalThis.cancelAnimationFrame = previousCancel; else delete (globalThis as any).cancelAnimationFrame; } + t.mock.timers.tick(1000); + assert.equal(lamps, 2); assert.equal(viewer.disposed, true); + } finally { + if (previous) Object.defineProperty(globalThis, "document", previous); else delete (globalThis as any).document; + } +}); + +export const templates = (node: any): any[] => !node || typeof node !== "object" ? [] : Array.isArray(node) ? node.flatMap(templates) : node.values ? [node, ...node.values.flatMap(templates)] : []; +const host = { admin: true, t: (key: string) => key } as any; + +test("resolver, sampler and editor work without Object.hasOwn and accept only explicit prototype-like names", () => { + const original = Object.hasOwn; + Object.hasOwn = undefined as any; + try { + const mapping = JSON.parse('{"__proto__":"pulse","constructor":"rainbow","toString":"flicker"}'); + for (const name of Object.keys(mapping)) { + assert.equal(lightAnimation({ effect_animations: mapping }, { state: "on", attributes: { effect: name } } as any), mapping[name]); + } + assert.equal(lightAnimation({ effect_animations: {} }, { state: "on", attributes: { effect: "constructor" } } as any), undefined); + assert.ok(animateGlow({ color: [1, 1, 1], level: 0.5 }, "pulse", 0)); + const nodes = templates(lightEffectFields(host, { effect_animations: mapping }, [], () => {})); + assert.ok(nodes.some((n) => n.values.includes("__proto__"))); + } finally { Object.hasOwn = original; } +}); diff --git a/frontend/src/light-effects.test.ts b/frontend/src/light-effects.test.ts new file mode 100644 index 0000000..1e125c6 --- /dev/null +++ b/frontend/src/light-effects.test.ts @@ -0,0 +1,162 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { buildMarkers } from "./markers.ts"; +import { emptyBuilding, newFloor } from "./model.ts"; +import type { HomeAssistant } from "./types.ts"; +import * as effects from "./light-effects.ts"; +import { lightAnimation } from "./light-effects.ts"; +import { NextFloorViewer } from "./viewer/viewer3d.ts"; +import { LIGHT_ANIMATIONS } from "./light-effects.ts"; +import { exportFile, parseExport } from "./transfer.ts"; +import { furnitureForDevice, deviceForFurniture } from "./components/editor/ops/items.ts"; +import { readFileSync } from "node:fs"; + +const source = (path: string) => readFileSync(new URL(path, import.meta.url), "utf8"); + +test("furniture lamps resolve explicit mappings just like placed device lamps", () => { + const code = source("./components/view3d.ts"); + assert.match(code, /lightAnimation\(f, lightEffectSource\(hass, f, entity\)\)/); + assert.doesNotMatch(code, /none\|off\|solid\|static\|normal/); +}); + +test("effect changes, disabled animations and invalid identifiers fall back without guessing", () => { + const st = { entity_id: "light.demo", state: "on", attributes: { effect: "White" } }; + const config = { effect_animations: { White: "none", Rainbow: "rainbow", Future: "future" } }; + for (const name of ["White", "white", " Rainbow", "Future", "toString", "__proto__", "unknown"]) { + st.attributes.effect = name; + assert.equal(lightAnimation(config, st), undefined); + } + st.attributes.effect = "Rainbow"; + assert.equal(lightAnimation(config, st), "rainbow"); + assert.equal(lightAnimation({ ...config, animations_enabled: false }, st), undefined); + for (const state of ["off", "unknown", "unavailable"]) assert.equal(lightAnimation(config, { ...st, state }), undefined); +}); + +test("exact per-placement effect mappings are independent for a shared entity", () => { + const building = emptyBuilding(); + const floor = newFloor("f", "Demo", 0); + floor.placements = [ + { entity_id: "light.demo", x: 1, z: 1, y: null, mount: null, effect_animations: { Regenbogen: "rainbow" } }, + { entity_id: "light.demo", x: 2, z: 1, y: null, mount: null, effect_animations: { Regenbogen: "pulse" } }, + { entity_id: "light.demo", x: 3, z: 1, y: null, mount: null }, + ]; + building.floors = [floor]; + const hass = { states: { "light.demo": { entity_id: "light.demo", state: "on", attributes: { effect: "Regenbogen" } } } } as unknown as HomeAssistant; + assert.deepEqual(buildMarkers(hass, building).map((m) => m.effect), ["rainbow", "pulse", undefined]); +}); + +test("pulse preserves base colour and modulates only the existing brightness ceiling", () => { + const glow = { color: [0.8, 0.2, 0.1] as [number, number, number], level: 0.4 }; + assert.equal(typeof effects.animateGlow, "function"); + const a = effects.animateGlow(glow, "pulse", 0); + const b = effects.animateGlow(glow, "pulse", 0.75); + assert.deepEqual(a?.color, glow.color); + assert.deepEqual(b?.color, glow.color); + assert.ok(a && b && a.level > 0 && a.level <= glow.level && b.level > 0 && b.level <= glow.level); + assert.notEqual(a?.level, b?.level); + assert.equal(glow.level, 0.4); +}); + +test("flicker is a deterministic time sample bounded by HA brightness", () => { + const glow = { color: [1, 0.6, 0.2] as [number, number, number], level: 0.3 }; + const samples = [0, 0.1, 0.8, 2, 5].map((time) => effects.animateGlow(glow, "flicker", time)!); + assert.ok(new Set(samples.map((s) => s.level)).size > 1); + for (const sample of samples) { + assert.deepEqual(sample.color, glow.color); + assert.ok(sample.level >= 0 && sample.level <= glow.level); + } + effects.animateGlow(glow, "flicker", 100); + assert.deepEqual(effects.animateGlow(glow, "flicker", 0.8), samples[2]); +}); + +test("rainbow replaces colour explicitly without multiplying brightness again", () => { + const glow = { color: [0.3, 0.3, 0.3] as [number, number, number], level: 0.25 }; + const a = effects.animateGlow(glow, "rainbow", 0)!; + const b = effects.animateGlow(glow, "rainbow", 3)!; + assert.notDeepEqual(a.color, b.color); + assert.equal(a.level, glow.level); + assert.equal(b.level, glow.level); + for (const channel of [...a.color, ...b.color]) assert.ok(channel >= 0 && channel <= 1); +}); + +test("the renderer samples the same animation for its light paths and handles static/null glows", () => { + const renderer = Object.create(NextFloorViewer.prototype) as any; + renderer.effectTime = 0.75; + const glow = { color: [1, 0.6, 0.2] as [number, number, number], level: 0.3 }; + assert.deepEqual(renderer.glowOf({ glow, effect: "pulse" }), effects.animateGlow(glow, "pulse", 0.75)); + assert.equal(renderer.glowOf({ glow }), glow); + assert.equal(renderer.glowOf({ glow: null, effect: "pulse" }), null); + assert.equal(effects.animateGlow(glow, "future", 1), glow); +}); + +test("editor changes only its local mapping and master switch, retaining unknown entries", async () => { + const module = await import("./components/editor/light-effect-fields.ts").catch(() => null); + assert.ok(module, "light effect editor is missing"); + const patches: unknown[] = []; + const config = { animations_enabled: false, effect_animations: { " White ": "future", Regenbogen: "rainbow" } }; + const host = { admin: true, t: (key: string) => key } as any; + const template = module.lightEffectFields(host, config, ["Kerzenlicht"], (patch: unknown) => patches.push(patch)); + // Lit templates keep the real event callbacks as values; exercise them without a DOM implementation. + const templates = (node: any): any[] => !node || typeof node !== "object" ? [] : Array.isArray(node) ? node.flatMap(templates) : node.values ? [node, ...node.values.flatMap(templates)] : []; + const nodes = templates(template); + const toggle = nodes.find((n) => n.strings.join("").includes('type="checkbox"')); + toggle.values.find((v: unknown) => typeof v === "function")({ target: { checked: true } }); + assert.deepEqual(patches[0], { animations_enabled: true }); + const row = nodes.find((n) => n.strings.join("").includes(" typeof v === "function")({ target: { value: "flicker" } }); + assert.deepEqual(patches[1], { effect_animations: { " White ": "future", Regenbogen: "rainbow", Kerzenlicht: "flicker" } }); + assert.deepEqual(config.effect_animations, { " White ": "future", Regenbogen: "rainbow" }); + assert.deepEqual(LIGHT_ANIMATIONS, ["none", "rainbow", "pulse", "flicker"]); +}); + +test("private export/import preserves local mappings and future identifiers without normalization", () => { + const building = emptyBuilding(); + const floor = newFloor("f", "Demo", 0); + floor.placements = [{ entity_id: "light.demo", x: 1, z: 1, y: null, mount: null, animations_enabled: false, effect_animations: { " White ": "future", Regenbogen: "rainbow" } }]; + building.floors = [floor]; + const result = parseExport(JSON.stringify(exportFile(building, false))); + assert.deepEqual(result.floors[0].furniture[0].effect_animations, floor.placements[0].effect_animations); + assert.equal(result.floors[0].furniture[0].animations_enabled, false); +}); + +test("effect scheduling requires a visible animated floor and stops for hidden views", () => { + const renderer = Object.create(NextFloorViewer.prototype) as any; + renderer.effectFloors = new Set(["animated"]); + renderer.floors = [{ floor: { id: "animated" }, o: 0 }, { floor: { id: "static" }, o: 1 }]; + renderer.onScreen = true; + renderer.disposed = false; + assert.equal(typeof renderer.hasVisibleEffects, "function"); + assert.equal(renderer.hasVisibleEffects(false), false); + renderer.floors[0].o = 1; + assert.equal(renderer.hasVisibleEffects(false), true); + assert.equal(renderer.hasVisibleEffects(true), false); + renderer.onScreen = false; + assert.equal(renderer.hasVisibleEffects(false), false); + renderer.onScreen = true; + renderer.disposed = true; + assert.equal(renderer.hasVisibleEffects(false), false); +}); + +test("changing a lamp representation preserves its per-placement animation settings", () => { + const placed = { entity_id: "light.demo", x: 1, z: 2, y: null, mount: null, animations_enabled: false, effect_animations: { Demo: "pulse" } }; + const furniture = furnitureForDevice(placed, "lamp_floor"); + assert.deepEqual(furniture.effect_animations, placed.effect_animations); + assert.equal(furniture.animations_enabled, false); + assert.deepEqual(deviceForFurniture(furniture, placed.entity_id).effect_animations, placed.effect_animations); +}); + +test("legacy shared-entity placements keep distinct lamp identities through import", () => { + const building = emptyBuilding(); + const floor = newFloor("f", "Demo", 0); + floor.placements = ["pulse", "flicker"].map((animation, index) => ({ entity_id: "light.demo", x: index, z: 1, y: null, mount: null, effect_animations: { Demo: animation } })); + building.floors = [floor]; + const lamps = parseExport(JSON.stringify(exportFile(building, false))).floors[0].furniture; + assert.equal(new Set(lamps.map((lamp) => lamp.id)).size, 2); + assert.deepEqual(lamps.map((lamp) => lamp.effect_animations), [{ Demo: "pulse" }, { Demo: "flicker" }]); +}); + +test("both lamp editors expose the same effect mapping control", () => { + for (const file of ["./components/editor/forms/device.ts", "./components/editor/forms/furniture-links.ts"]) { + assert.ok(source(file).includes("lightEffectFields("), `${file} has no animation fields`); + } +}); diff --git a/frontend/src/light-effects.ts b/frontend/src/light-effects.ts new file mode 100644 index 0000000..09bfb77 --- /dev/null +++ b/frontend/src/light-effects.ts @@ -0,0 +1,48 @@ +import type { HassEntity, HomeAssistant } from "./types.ts"; +import { animateWithPlugin, hasPluginAnimation } from "./plugins/registry.ts"; + +/** The explicit colour entity also owns effects; the primary entity still controls on/off. */ +export function lightEffectSource(hass: Pick, config: { color_entity?: string | null }, primary: string | null): HassEntity | undefined { + const id = config.color_entity && config.color_entity !== "none" ? config.color_entity : primary; + return id ? hass.states[id] : undefined; +} + +export const LIGHT_ANIMATIONS = ["none", "rainbow", "pulse", "flicker"] as const; +export type LightAnimation = typeof LIGHT_ANIMATIONS[number]; +export interface LightEffectConfig { + animations_enabled?: boolean; + effect_animations?: Record; +} + +/** HA effect names are opaque, case-sensitive program names, never colour instructions. */ +/** A built-in animation name or one a plugin registered. */ +export type AnimationName = Exclude | (string & {}); + +export function lightAnimation(config: LightEffectConfig, state: HassEntity | undefined): AnimationName | undefined { + if (config.animations_enabled === false || state?.state !== "on") return undefined; + const effect = state.attributes.effect; + if (typeof effect !== "string" || !config.effect_animations || !Object.prototype.hasOwnProperty.call(config.effect_animations, effect)) return undefined; + const animation = config.effect_animations[effect]; + if (animation === "rainbow" || animation === "pulse" || animation === "flicker") return animation; + return hasPluginAnimation(animation) ? animation : undefined; +} + +type Glow = { color: [number, number, number]; level: number }; +type Animation = (glow: Glow, seconds: number) => Glow; +const registry: Partial> = { + rainbow: (glow, seconds) => { + const hue = ((seconds * 0.08) % 1 + 1) % 1; + const channel = (offset: number) => Math.max(0, Math.min(1, Math.abs(((hue * 6 + offset) % 6) - 3) - 1)); + return { color: [channel(0), channel(4), channel(2)], level: glow.level }; + }, + flicker: (glow, seconds) => ({ ...glow, level: glow.level * (0.75 + 0.15 * Math.sin(seconds * 17) + 0.1 * Math.sin(seconds * 31 + 1)) }), + pulse: (glow, seconds) => ({ ...glow, level: glow.level * (0.65 + 0.35 * Math.sin(seconds * Math.PI)) }), +}; + +/** Samples the existing glow; brightness has already been applied by lightGlow. */ +export function animateGlow(glow: Glow | null, animation: string | undefined, seconds: number): Glow | null { + if (!glow || !animation) return glow; + if (!Object.prototype.hasOwnProperty.call(registry, animation)) return animateWithPlugin(glow, animation, seconds); + return registry[animation as LightAnimation]?.(glow, seconds) ?? glow; +} + diff --git a/frontend/src/live/all-off.test.ts b/frontend/src/live/all-off.test.ts new file mode 100644 index 0000000..e2974f2 --- /dev/null +++ b/frontend/src/live/all-off.test.ts @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, floorWith } from "../entities/fixtures.ts"; +import { allOffPlan, floorSwitchables } from "./all-off.ts"; + +test("everything off switches what is on and its undo brings the lights back as they were", () => { + const plan = allOffPlan([ + entity("light.a", "on", { brightness: 120, color_mode: "color_temp", color_temp_kelvin: 2700 }), + entity("light.b", "off"), + entity("switch.tv_socket", "on"), + entity("fan.ceiling", "on"), + entity("media_player.speaker", "playing"), + entity("media_player.tv", "on"), + entity("lock.door", "locked"), + undefined, + ]); + assert.equal(plan.count, 5); + assert.deepEqual(plan.off[0], { domain: "light", service: "turn_off", data: { entity_id: ["light.a"] } }); + assert.deepEqual(plan.undo[0], { domain: "light", service: "turn_on", data: { entity_id: "light.a", brightness: 120, color_temp_kelvin: 2700 } }); + assert.ok(plan.off.some((c) => c.domain === "media_player" && c.service === "media_pause")); + assert.ok(plan.undo.some((c) => c.domain === "media_player" && c.service === "media_play")); + assert.ok(plan.undo.some((c) => c.domain === "fan" && c.service === "turn_on")); + assert.ok(!plan.off.some((c) => c.domain === "lock")); + assert.equal(allOffPlan([entity("light.b", "off")]).count, 0); +}); + +test("a floor offers the switchable entities of its pins and furniture", () => { + const floor = { + ...floorWith([]), + placements: [{ entity_id: "light.ceiling", x: 0, z: 0, y: null, mount: null }, { entity_id: "sensor.temp", x: 0, z: 0, y: null, mount: null }], + furniture: [{ id: "tv", type: "tv", x: 1, z: 1, rotation: 0, w: 1, d: 0.1, h: 0.6, variant: null, entity: "media_player.tv", extra_lights: ["light.ambilight"] }], + }; + assert.deepEqual(floorSwitchables(floor as never).sort(), ["light.ambilight", "light.ceiling", "media_player.tv"]); +}); diff --git a/frontend/src/live/all-off.ts b/frontend/src/live/all-off.ts new file mode 100644 index 0000000..7398002 --- /dev/null +++ b/frontend/src/live/all-off.ts @@ -0,0 +1,65 @@ +// Everything off: the lights, switches, fans and media of a room or a floor in one tap, and the calls that bring them back as they +// were (lights with their brightness and colour), for the few seconds the undo is offered. + +import type { Floor } from "../model.ts"; +import type { HassEntity } from "../types.ts"; +import { lightSetting, moodCalls } from "./moods.ts"; + +export interface ServiceCall { + domain: string; + service: string; + data: Record; +} + +const domainOf = (id: string) => id.slice(0, id.indexOf(".")); +const SWITCHES = new Set(["switch", "fan", "input_boolean"]); + +/** The calls that switch off what is on, and those that undo it. `count` is how many things it switches. */ +export function allOffPlan(states: readonly (HassEntity | undefined)[]): { off: ServiceCall[]; undo: ServiceCall[]; count: number } { + const lights: HassEntity[] = []; + const switches = new Map(); + const pause: string[] = []; + const shut: string[] = []; + for (const st of states) { + if (!st) continue; + const domain = domainOf(st.entity_id); + if (domain === "light" && st.state === "on") lights.push(st); + else if (SWITCHES.has(domain) && st.state === "on") switches.set(domain, [...(switches.get(domain) ?? []), st.entity_id]); + else if (domain === "media_player" && st.state === "playing") pause.push(st.entity_id); + else if (domain === "media_player" && (st.state === "on" || st.state === "idle")) shut.push(st.entity_id); + } + const off: ServiceCall[] = []; + const undo: ServiceCall[] = []; + if (lights.length) { + off.push({ domain: "light", service: "turn_off", data: { entity_id: lights.map((l) => l.entity_id) } }); + undo.push(...moodCalls(lights.map(lightSetting)).map((c) => ({ domain: "light", service: c.service, data: c.data }))); + } + for (const [domain, ids] of switches) { + off.push({ domain, service: "turn_off", data: { entity_id: ids } }); + undo.push({ domain, service: "turn_on", data: { entity_id: ids } }); + } + if (pause.length) { + off.push({ domain: "media_player", service: "media_pause", data: { entity_id: pause } }); + undo.push({ domain: "media_player", service: "media_play", data: { entity_id: pause } }); + } + if (shut.length) { + off.push({ domain: "media_player", service: "turn_off", data: { entity_id: shut } }); + undo.push({ domain: "media_player", service: "turn_on", data: { entity_id: shut } }); + } + const count = lights.length + [...switches.values()].reduce((n, ids) => n + ids.length, 0) + pause.length + shut.length; + return { off, undo, count }; +} + +/** What the plan shows on a floor that "everything off" may switch: device pins and the entities of furniture (lamps, TVs, sockets). */ +export function floorSwitchables(floor: Floor): string[] { + const ids = new Set(); + const take = (id: unknown) => { + if (typeof id === "string" && /^(light|switch|fan|input_boolean|media_player)\./.test(id)) ids.add(id); + }; + for (const p of floor.placements) take(p.entity_id); + for (const m of floor.furniture) { + take(m.entity); + for (const e of m.extra_lights ?? []) take(e); + } + return [...ids]; +} diff --git a/frontend/src/live/announce.test.ts b/frontend/src/live/announce.test.ts new file mode 100644 index 0000000..e31f339 --- /dev/null +++ b/frontend/src/live/announce.test.ts @@ -0,0 +1,58 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, entity, floorWith, hassOf } from "../entities/fixtures.ts"; +import { canAnnounce, claim, forThisScreen, roomHasSpeaker, roomSpeaker, showFor } from "./announce.ts"; + +test("an announcement goes to every screen, or only to the ones named; a muted screen hears none", () => { + assert.equal(forThisScreen({ screens: [] }, null), true); + assert.equal(forThisScreen({ screens: ["Hallway"] }, " hallway "), true); + assert.equal(forThisScreen({ screens: ["Hallway"] }, "Kitchen"), false); + assert.equal(forThisScreen({ screens: ["Hallway"] }, null), false); + assert.equal(forThisScreen({ screens: [] }, "Hallway", true), false); +}); + +test("several views on a page show an announcement once", () => { + const a = { time: "2026-11-01T12:00:00Z", message: "Dinner!" }; + assert.equal(claim(a), true); + assert.equal(claim({ ...a }), false); + assert.equal(claim({ ...a, time: "2026-11-01T12:00:05Z" }), true); +}); + +test("a message stays long enough to read, between 6 and 30 seconds", () => { + assert.equal(showFor("Dinner!"), 6000); + assert.equal(showFor(Array(100).fill("word").join(" ")), 30000); +}); + +test("the room's speaker: chosen, else placed in the room, else a satellite, an Echo or a speaker of the area; never a TV", () => { + const states = [ + entity("media_player.radio", "idle"), + entity("media_player.tv", "on", { device_class: "tv" }), + entity("media_player.off", "off"), + entity("assist_satellite.voice", "idle"), + entity("media_player.placed", "idle"), + entity("notify.echo_announce", "unknown"), + ]; + const hass = hassOf(states, { + "media_player.radio": { area_id: "kitchen" }, + "media_player.tv": { area_id: "living" }, + "media_player.off": { area_id: "living" }, + "assist_satellite.voice": { area_id: "kitchen" }, + "notify.echo_announce": { area_id: "hall", platform: "alexa_devices" }, + }); + const kitchen = box("kitchen", 0, 0, 4, 3, "kitchen"); + const living = box("living", 4, 0, 8, 3, "living"); + const hall = box("hall", 0, 3, 4, 6, "hall"); + const floor = floorWith([kitchen, living, hall]); + assert.equal(roomSpeaker(hass, floor, kitchen), "assist_satellite.voice"); + assert.equal(roomSpeaker(hass, floor, living), null); + assert.equal(roomSpeaker(hass, floor, hall), "notify.echo_announce"); + floor.placements.push({ entity_id: "media_player.placed", x: 6, z: 1, mount: null, rotation: 0 } as (typeof floor.placements)[number]); + assert.equal(roomSpeaker(hass, floor, living), "media_player.placed"); + assert.equal(roomSpeaker(hass, floor, { ...kitchen, announce_speaker: "media_player.off" }), "media_player.off"); + assert.equal(roomHasSpeaker(hass, floor, { ...kitchen, announce_speaker: "none" }), false); +}); + +test("announcements are offered only where Home Assistant knows the action", () => { + assert.equal(canAnnounce(hassOf([])), false); + assert.equal(canAnnounce(hassOf([], {}, { services: { nextfloor: { announce: {} } } })), true); +}); diff --git a/frontend/src/live/announce.ts b/frontend/src/live/announce.ts new file mode 100644 index 0000000..9913360 --- /dev/null +++ b/frontend/src/live/announce.ts @@ -0,0 +1,150 @@ +// Announcements on this screen and from a room: the action nextfloor.announce (announce.py) speaks in the rooms and sends +// every announcement to the open NextFloor screens, which show it big, play a chime and speak it. + +import { pointInPolygon, type Floor, type Room } from "../model.ts"; +import type { HomeAssistant } from "../types.ts"; + +export interface Announcement { + message: string; + /** Only the screens with these names; empty: every screen. */ + screens: string[]; + /** The message spoken by Home Assistant's text-to-speech, or null (the browser's own voice speaks then). */ + audio: string | null; + time: string; +} + +/** Whether an announcement is meant for this screen: every screen, or this one by its name. A muted screen hears none. */ +export function forThisScreen(a: Pick, name: string | null | undefined, muted = false): boolean { + if (muted) return false; + if (!Array.isArray(a.screens) || !a.screens.length) return true; + const own = (name ?? "").trim().toLocaleLowerCase(); + return !!own && a.screens.some((s) => s.trim().toLocaleLowerCase() === own); +} + +/** Several views on one page (the panel and cards) hear the same announcement: only the first one shows and speaks it. */ +const claimed: Set = ((globalThis as Record).__nfAnnounced as Set | undefined) ?? new Set(); +(globalThis as Record).__nfAnnounced = claimed; + +export function claim(a: Pick): boolean { + const key = `${a.time}|${a.message}`; + if (claimed.has(key)) return false; + claimed.add(key); + if (claimed.size > 50) claimed.delete(claimed.values().next().value as string); + return true; +} + +/** How long the message stays on screen: long enough to read it, at least 6 s, at most 30 s. */ +export const showFor = (message: string): number => Math.min(30_000, Math.max(6_000, message.split(/\s+/).length * 600 + 2_000)); + +/** A soft two-tone chime, made by the browser (no sound file). Resolves when it has played (or could not). */ +export function chime(): Promise { + try { + const Ctx = (globalThis as { AudioContext?: typeof AudioContext; webkitAudioContext?: typeof AudioContext }).AudioContext ?? (globalThis as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext; + if (!Ctx) return Promise.resolve(); + const ctx = new Ctx(); + const tone = (freq: number, start: number) => { + const osc = ctx.createOscillator(); + const gain = ctx.createGain(); + osc.type = "sine"; + osc.frequency.value = freq; + gain.gain.setValueAtTime(0.0001, ctx.currentTime + start); + gain.gain.exponentialRampToValueAtTime(0.25, ctx.currentTime + start + 0.03); + gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + start + 0.9); + osc.connect(gain).connect(ctx.destination); + osc.start(ctx.currentTime + start); + osc.stop(ctx.currentTime + start + 1); + }; + tone(880, 0); + tone(660, 0.35); + return new Promise((done) => + setTimeout(() => { + void ctx.close().catch(() => undefined); + done(); + }, 1400), + ); + } catch { + return Promise.resolve(); + } +} + +/** Speak with the browser's own voice in the user's language (when Home Assistant gave no audio). */ +function speakInBrowser(hass: HomeAssistant, message: string): void { + const synth = (globalThis as { speechSynthesis?: SpeechSynthesis }).speechSynthesis; + const Utterance = (globalThis as { SpeechSynthesisUtterance?: typeof SpeechSynthesisUtterance }).SpeechSynthesisUtterance; + if (!synth || !Utterance) return; + const u = new Utterance(message); + u.lang = hass.language || "en"; + synth.cancel(); + synth.speak(u); +} + +/** Chime, then the message: Home Assistant's audio when there is one, else the browser's voice. Browsers may block sound until the page was tapped once. */ +export async function playAnnouncement(hass: HomeAssistant, a: Announcement): Promise { + await chime(); + if (a.audio) { + try { + const url = a.audio.startsWith("/") && hass.hassUrl ? hass.hassUrl(a.audio) : a.audio; + await new Audio(url).play(); + return; + } catch { + // blocked or failed: the browser's voice tries instead + } + } + speakInBrowser(hass, a.message); +} + +/** Subscribes this screen to the announcements; resolves to the unsubscribe function (or a no-op with an older backend). */ +export function subscribeAnnouncements(hass: HomeAssistant, onAnnouncement: (a: Announcement) => void): Promise<() => void> { + return hass.connection.subscribeMessage(onAnnouncement, { type: "nextfloor/announcements/subscribe" }).then( + (stop) => () => void stop().catch(() => undefined), + () => () => undefined, + ); +} + +const SPEAKER_DOMAINS = /^(media_player|assist_satellite)\./; + +/** Every entity of an area, its own or its device's (NextFloor's area lists leave out what it does not draw, like voice satellites). */ +function inArea(hass: HomeAssistant, areaId: string | null | undefined): string[] { + if (!areaId) return []; + return Object.values(hass.entities ?? {}) + .filter((e) => !e.hidden && (e.area_id ?? (e.device_id ? hass.devices?.[e.device_id]?.area_id : null)) === areaId) + .map((e) => e.entity_id); +} + +/** Whether a speaker may speak by itself: no TV, not off or gone (as announce.py decides it). */ +function usable(hass: HomeAssistant, id: string): boolean { + const st = hass.states[id]; + if (!st || st.state === "unavailable") return false; + if (id.startsWith("notify.")) return hass.entities?.[id]?.platform === "alexa_devices" && id.endsWith("_announce"); + if (st.state === "off" || st.state === "unknown") return false; + return st.attributes.device_class !== "tv"; +} + +/** + * The speaker an announcement in the room goes to, picked as announce.py picks it: chosen in the plan, else placed in the + * room, else a voice satellite, an Echo or a speaker of its area (sorted by id). Null: the room cannot speak. + */ +export function roomSpeaker(hass: HomeAssistant, floor: Floor | null, room: Room): string | null { + if (room.announce_speaker === "none") return null; + if (room.announce_speaker) return room.announce_speaker; + if (floor && room.points.length >= 3) { + const placed = [ + ...floor.placements.filter((p) => SPEAKER_DOMAINS.test(p.entity_id)).map((p) => ({ id: p.entity_id, x: p.x, z: p.z })), + ...floor.furniture.filter((f) => f.entity && SPEAKER_DOMAINS.test(f.entity)).map((f) => ({ id: f.entity!, x: f.x, z: f.z })), + ]; + const inside = placed.find((p) => pointInPolygon([p.x, p.z], room.points) && usable(hass, p.id)); + if (inside) return inside.id; + } + const area = inArea(hass, room.area_id); + for (const domain of ["assist_satellite.", "notify.", "media_player."]) { + const found = area.filter((id) => id.startsWith(domain) && usable(hass, id)).sort()[0]; + if (found) return found; + } + return null; +} + +/** Whether the room panel offers announcements for the room. */ +export const roomHasSpeaker = (hass: HomeAssistant, floor: Floor | null, room: Room): boolean => roomSpeaker(hass, floor, room) !== null; + +/** Whether Home Assistant offers the action (NextFloor is set up and its backend knows announcements). */ +export const canAnnounce = (hass: HomeAssistant | undefined): boolean => !!hass?.services?.nextfloor?.announce; diff --git a/frontend/src/live/batteries.test.ts b/frontend/src/live/batteries.test.ts new file mode 100644 index 0000000..91e08fb --- /dev/null +++ b/frontend/src/live/batteries.test.ts @@ -0,0 +1,19 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, entity, floorWith, hassOf, opening } from "../entities/fixtures.ts"; +import { emptyBuilding } from "../model.ts"; +import { batteryOf, planBatteries } from "./batteries.ts"; + +test("a device's battery comes from the battery sensor next to it, else from the entity's attribute", () => { + const hass = hassOf( + [entity("binary_sensor.window", "off"), entity("sensor.window_battery", "12", { device_class: "battery" }), entity("lock.door", "locked", { battery_level: 64 }), entity("light.ceiling", "on")], + { "binary_sensor.window": { device_id: "w" }, "sensor.window_battery": { device_id: "w" } }, + ); + assert.equal(batteryOf(hass, "binary_sensor.window"), 12); + assert.equal(batteryOf(hass, "lock.door"), 64); + assert.equal(batteryOf(hass, "light.ceiling"), null); + const room = box("k", 0, 0, 4, 4); + const floor = { ...floorWith([room]), openings: [opening("o", "k", "window", { contact: "binary_sensor.window" }), opening("d", "k", "door", { lock: "lock.door" })], placements: [{ entity_id: "light.ceiling", x: 1, z: 1, y: null, mount: null }] }; + const list = planBatteries(hass, { ...emptyBuilding(), floors: [floor] }); + assert.deepEqual(list.map((b) => [b.entity, b.level, b.roomId]), [["binary_sensor.window", 12, "k"], ["lock.door", 64, "k"]]); +}); diff --git a/frontend/src/live/batteries.ts b/frontend/src/live/batteries.ts new file mode 100644 index 0000000..3b6b6eb --- /dev/null +++ b/frontend/src/live/batteries.ts @@ -0,0 +1,74 @@ +// Low batteries: the battery level of the devices the plan links – device pins, the sensors of doors and windows, linked furniture – +// from a battery sensor on the same device or the entity's own battery attribute, each device once. + +import { pointInPolygon, type Building, type Floor, type Room } from "../model.ts"; +import type { HomeAssistant } from "../types.ts"; + +/** Below this level (%) a battery counts as low. */ +export const LOW_BATTERY = 20; + +export interface BatteryLevel { + /** The entity of the plan the battery belongs to (its name is shown). */ + entity: string; + level: number; + floorId: string; + roomId: string | null; +} + +/** Battery sensors by device, worked out once per registry (the registry object changes when entities do). */ +const batteryIndex = new WeakMap>(); +function batterySensors(hass: HomeAssistant): Map { + const registry = hass.entities ?? {}; + let index = batteryIndex.get(registry); + if (!index) { + index = new Map(); + for (const [id, entry] of Object.entries(registry)) { + if (entry.device_id && id.startsWith("sensor.") && hass.states[id]?.attributes.device_class === "battery" && !index.has(entry.device_id)) index.set(entry.device_id, id); + } + batteryIndex.set(registry, index); + } + return index; +} + +/** The battery level of an entity's device (a battery sensor next to it), else its own battery attribute; null when it has none. */ +export function batteryOf(hass: HomeAssistant, entityId: string): number | null { + const device = hass.entities?.[entityId]?.device_id; + const sensor = device ? batterySensors(hass).get(device) : undefined; + if (sensor) { + const v = Number(hass.states[sensor]?.state); + if (Number.isFinite(v)) return v; + } + const attr = hass.states[entityId]?.attributes; + if (!attr || (attr.battery_level === undefined && attr.battery === undefined)) return null; + const v = Number(attr.battery_level ?? attr.battery); + return Number.isFinite(v) ? v : null; +} + +/** Every entity of a floor the plan links, with where it is. */ +function linkedEntities(floor: Floor): { entity: string; x: number; z: number; room: string | null }[] { + const out: { entity: string; x: number; z: number; room: string | null }[] = []; + const looks = (v: unknown): v is string => typeof v === "string" && /^[a-z_]+\.[a-z0-9_]+$/.test(v); + for (const p of floor.placements) out.push({ entity: p.entity_id, x: p.x, z: p.z, room: null }); + for (const m of floor.furniture) for (const v of [m.entity, m.power]) if (looks(v)) out.push({ entity: v, x: m.x, z: m.z, room: null }); + for (const o of floor.openings) for (const v of [o.contact, o.contact2, o.tilt, o.tilt2, o.cover, o.cover2, o.lock]) if (looks(v)) out.push({ entity: v, x: NaN, z: NaN, room: o.room_id }); + return out; +} + +const roomAt = (floor: Floor, x: number, z: number): Room | undefined => floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([x, z], r.points)); + +/** The batteries of the plan's devices, lowest first; each device counted once. */ +export function planBatteries(hass: HomeAssistant, building: Building): BatteryLevel[] { + const seen = new Set(); + const out: BatteryLevel[] = []; + for (const floor of building.floors) { + for (const link of linkedEntities(floor)) { + const key = hass.entities?.[link.entity]?.device_id ?? link.entity; + if (seen.has(key)) continue; + const level = batteryOf(hass, link.entity); + if (level === null) continue; + seen.add(key); + out.push({ entity: link.entity, level, floorId: floor.id, roomId: link.room ?? roomAt(floor, link.x, link.z)?.id ?? null }); + } + } + return out.sort((a, b) => a.level - b.level); +} diff --git a/frontend/src/live/car.test.ts b/frontend/src/live/car.test.ts new file mode 100644 index 0000000..57e45f0 --- /dev/null +++ b/frontend/src/live/car.test.ts @@ -0,0 +1,30 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, hassOf } from "../entities/fixtures.ts"; +import { departureText, kmBetween, readCar } from "./car.ts"; + +test("a departure time from the ways cars and helpers write it", () => { + assert.equal(departureText(entity("input_datetime.go", "7:30:00")), "07:30"); + assert.equal(departureText(entity("sensor.dep", "450")), "07:30", "minutes after midnight"); + assert.equal(departureText(entity("sensor.dep", new Date(2026, 10, 3, 6, 45).toISOString())), "06:45"); + assert.equal(departureText(entity("sensor.dep", "unknown")), null); +}); + +test("away, the car tells how far it is and which parts stand open", () => { + assert.ok(Math.abs(kmBetween(50.11, 8.68, 50.04, 8.56) - 11.6) < 0.5, "Frankfurt to its airport"); + const reg = { device_id: "car" }; + const hass = hassOf( + [ + entity("device_tracker.tesla", "not_home", { latitude: 50.04, longitude: 8.56, friendly_name: "Tesla Location" }), + entity("sensor.tesla_battery", "64", { unit_of_measurement: "%", device_class: "battery", friendly_name: "Tesla Battery" }), + entity("binary_sensor.tesla_trunk", "on", { friendly_name: "Tesla Trunk" }), + entity("binary_sensor.tesla_door_fl", "off", { device_class: "door", friendly_name: "Tesla Door" }), + entity("zone.home", "0", { latitude: 50.11, longitude: 8.68 }), + ], + { "device_tracker.tesla": reg, "sensor.tesla_battery": reg, "binary_sensor.tesla_trunk": reg, "binary_sensor.tesla_door_fl": reg }, + ); + const car = readCar(hass, { entity: "device_tracker.tesla", car: null })!; + assert.equal(car.home, false); + assert.ok(car.distance !== null && Math.abs(car.distance - 11.6) < 0.5); + assert.deepEqual(car.open, ["Trunk"]); +}); diff --git a/frontend/src/live/car.ts b/frontend/src/live/car.ts new file mode 100644 index 0000000..ccc156b --- /dev/null +++ b/frontend/src/live/car.ts @@ -0,0 +1,182 @@ +/** + * NextFloor's car: what a parking spot's car reports, found by itself among the entities of the car's device. + * + * The spot names the car through its presence entity (a device_tracker, a binary sensor …) or through the links set + * in the editor (`car` on the spot). Everything else is looked for on the same device: the charge level (a battery + * sensor), the range (a distance sensor), the charging power, whether it charges and is plugged in, the lock, the + * climate and the charge switch. Works with TeslaMate (MQTT), Tesla Fleet, and the car integrations that put their + * entities on one device (VW, BMW, Hyundai/Kia, Renault, Polestar …). + */ +import type { Furniture } from "../model.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; + +export interface CarInfo { + /** The car is in its spot (else it is on the road). */ + home: boolean; + soc: number | null; + range: number | null; + rangeUnit: string; + /** Charging power in W (null: unknown). */ + chargingW: number | null; + charging: boolean; + plugged: boolean | null; + locked: boolean | null; + climateOn: boolean | null; + /** Inside temperature (°C) when the car reports it. */ + inside: number | null; + /** Where it is when it is away: the zone or the tracker's text. */ + where: string | null; + /** Away: how far it is from home (km, as the crow flies), from the tracker's position. */ + distance: number | null; + /** Doors, hatches, windows and the charge port that stand open (their names). */ + open: string[]; + /** The planned departure ("07:30"), from a departure time the car or a helper reports. */ + departure: string | null; + entities: { lock: string | null; climate: string | null; charge: string | null; tracker: string | null }; +} + +const ref = (v: string | null | undefined) => (v && v !== "none" ? v : null); +const num = (st: HassEntity | undefined) => { + const n = Number(st?.state); + return st && Number.isFinite(n) ? n : null; +}; +const attr = (st: HassEntity | undefined, k: string) => st?.attributes?.[k]; +const word = (id: string, ...parts: string[]) => parts.some((p) => id.includes(p)); + +/** All entities on the device of `entity` (the entity itself included). */ +function siblings(hass: HomeAssistant, entity: string | null): string[] { + if (!entity) return []; + const device = hass.entities?.[entity]?.device_id; + if (!device) return [entity]; + return Object.values(hass.entities ?? {}) + .filter((e) => e.device_id === device && !e.hidden) + .map((e) => e.entity_id) + .filter((id) => hass.states[id]); +} + +/** The first entity that matches, preferring one set by hand. */ +function pick(hass: HomeAssistant, set: string | null, list: string[], match: (id: string, st: HassEntity) => boolean): string | null { + if (set && hass.states[set]) return set; + return list.find((id) => match(id, hass.states[id])) ?? null; +} + +/** Distance between two points on the earth in km (haversine). */ +export function kmBetween(lat1: number, lon1: number, lat2: number, lon2: number): number { + const r = Math.PI / 180; + const a = Math.sin(((lat2 - lat1) * r) / 2) ** 2 + Math.cos(lat1 * r) * Math.cos(lat2 * r) * Math.sin(((lon2 - lon1) * r) / 2) ** 2; + return 12742 * Math.asin(Math.min(1, Math.sqrt(a))); +} + +/** "07:30" from a departure entity: a time ("07:30:00"), a date-time or timestamp (today's or tomorrow's), or minutes after midnight. */ +export function departureText(st: HassEntity | undefined): string | null { + if (!st || ["unknown", "unavailable", "", "none", "off"].includes(String(st.state).toLowerCase())) return null; + const s = String(st.state); + let m = /^(\d{1,2}):(\d{2})/.exec(s); + if (m) return `${m[1].padStart(2, "0")}:${m[2]}`; + const t = Date.parse(s); + if (Number.isFinite(t) && /\d{4}-\d{2}-\d{2}/.test(s)) { + const d = new Date(t); + return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`; + } + m = /^(\d{1,4})$/.exec(s); + if (m && Number(m[1]) < 1440) return `${String(Math.floor(Number(m[1]) / 60)).padStart(2, "0")}:${String(Number(m[1]) % 60).padStart(2, "0")}`; + return null; +} + +export function readCar(hass: HomeAssistant, spot: Pick): CarInfo | null { + const links = spot.car ?? {}; + const anchor = ref(links.device) ?? ref(links.tracker) ?? ref(spot.entity); + const all = siblings(hass, anchor); + if (!all.length && !ref(links.soc)) return null; + const domain = (id: string) => id.split(".")[0]; + const dc = (st: HassEntity) => String(attr(st, "device_class") ?? ""); + const unit = (st: HassEntity) => String(attr(st, "unit_of_measurement") ?? ""); + + const socId = pick(hass, ref(links.soc), all, (id, st) => domain(id) === "sensor" && unit(st) === "%" && (dc(st) === "battery" || word(id, "battery_level", "soc", "state_of_charge", "ladezustand")) && !word(id, "usable")); + const rangeId = pick(hass, ref(links.range), all, (id, st) => domain(id) === "sensor" && (dc(st) === "distance" || word(id, "range", "reichweite")) && !word(id, "odometer", "ideal", "elevation", "kilometerstand")); + const powerId = pick(hass, null, all, (id, st) => domain(id) === "sensor" && dc(st) === "power" && word(id, "charg", "lade")); + const chargingSet = ref(links.charging); + const chargingBin = pick(hass, chargingSet && domain(chargingSet) === "binary_sensor" ? chargingSet : null, all, (id, st) => domain(id) === "binary_sensor" && (dc(st) === "battery_charging" || word(id, "charging", "charger", "laden"))); + const pluggedId = pick(hass, ref(links.plugged), all, (id, st) => domain(id) === "binary_sensor" && (dc(st) === "plug" || word(id, "plug", "cable", "kabel"))); + const lockId = pick(hass, ref(links.lock), all, (id) => domain(id) === "lock"); + const climateId = pick(hass, ref(links.climate), all, (id) => domain(id) === "climate"); + const chargeSwitch = pick(hass, chargingSet && /^(switch|input_boolean)\./.test(chargingSet) ? chargingSet : null, all, (id) => domain(id) === "switch" && word(id, "charg", "laden") && !word(id, "port", "klappe")); + const trackerId = pick(hass, ref(links.tracker), all, (id) => domain(id) === "device_tracker") ?? (ref(spot.entity)?.startsWith("device_tracker.") ? ref(spot.entity) : null); + const insideId = pick(hass, null, all, (id, st) => domain(id) === "sensor" && dc(st) === "temperature" && word(id, "inside", "innen", "interior", "cabin")); + const departureId = pick(hass, ref(links.departure), all, (id) => /^(sensor|input_datetime|time|datetime)$/.test(domain(id)) && word(id, "departure", "abfahrt", "depart")); + // doors, trunk, frunk, windows and the charge port: binary sensors of the car that report open + const opened = all.filter((id) => { + const s = hass.states[id]; + return domain(id) === "binary_sensor" && s?.state === "on" && (["door", "opening", "window", "garage_door"].includes(dc(s)) || word(id, "trunk", "frunk", "kofferraum", "tailgate", "hatch", "klappe", "charge_port", "ladeklappe")); + }); + + const st = (id: string | null) => (id ? hass.states[id] : undefined); + const soc = num(st(socId)); + const rangeSt = st(rangeId); + // charging power: a power sensor (W or kW), else a "charging" sensor that reports power + let chargingW: number | null = null; + const p = st(powerId) ?? (chargingSet && domain(chargingSet) === "sensor" ? st(chargingSet) : undefined); + if (p) { + const v = num(p); + if (v !== null) chargingW = Math.max(0, unit(p).toLowerCase() === "kw" ? v * 1000 : v); + } + const chargingState = st(chargingBin)?.state ?? st(chargeSwitch)?.state; + const charging = chargingState === "on" || (chargingW !== null && chargingW > 50); + const pluggedState = st(pluggedId)?.state; + const lockState = st(lockId)?.state; + const climate = st(climateId); + const tracker = st(trackerId); + // home: the spot's presence entity says so (the car stands in the 3D spot); else the tracker + const presence = st(ref(spot.entity)); + const home = presence ? ["on", "home", "true", "present", "occupied", "detected", "parked"].includes(presence.state.toLowerCase()) : tracker?.state === "home"; + const zone = tracker && tracker.state !== "home" && tracker.state !== "not_home" ? tracker.state : null; + const zoneName = zone ? String(st(`zone.${zone}`)?.attributes.friendly_name ?? zone) : null; + return { + home, + soc, + range: num(rangeSt), + rangeUnit: rangeSt ? unit(rangeSt) || "km" : "km", + chargingW, + charging, + plugged: pluggedState === undefined ? null : pluggedState === "on", + locked: lockState === undefined ? null : lockState === "locked", + climateOn: climate ? climate.state !== "off" && climate.state !== "unavailable" : null, + inside: num(st(insideId)), + where: home ? null : zoneName, + distance: home ? null : distanceHome(hass, tracker), + open: opened.map((id) => carPartName(hass, id, all)), + departure: departureText(st(departureId)), + entities: { lock: lockId, climate: climateId, charge: chargeSwitch, tracker: trackerId }, + }; +} + +/** How far a tracker is from home in km, or null without positions. */ +function distanceHome(hass: HomeAssistant, tracker: HassEntity | undefined): number | null { + const home = hass.states["zone.home"]?.attributes; + const lat = Number(tracker?.attributes?.latitude); + const lon = Number(tracker?.attributes?.longitude); + const hl = Number(home?.latitude ?? hass.config?.latitude); + const ho = Number(home?.longitude ?? hass.config?.longitude); + if (![lat, lon, hl, ho].every(Number.isFinite)) return null; + return Math.round(kmBetween(lat, lon, hl, ho) * 10) / 10; +} + +/** The short name of a car's part (the car's name taken off: "Model 3 Trunk" → "Trunk"). */ +function carPartName(hass: HomeAssistant, id: string, all: string[]): string { + const name = String(hass.states[id]?.attributes.friendly_name ?? id.split(".")[1]); + const device = all.map((e) => String(hass.states[e]?.attributes.friendly_name ?? "")).reduce((common, n) => { + let k = 0; + while (k < common.length && k < n.length && common[k] === n[k]) k++; + return common.slice(0, k); + }); + const rest = name.slice(device.length).trim(); + return rest.length >= 2 ? rest : name; +} + +/** The charge level's colour: red when low, amber in the middle, green when well charged. */ +export function socColor(soc: number | null): string { + if (soc === null) return "#8aa0c8"; + if (soc < 20) return "#f87171"; + if (soc < 50) return "#facc15"; + return "#4ade80"; +} diff --git a/frontend/src/live/cards.ts b/frontend/src/live/cards.ts new file mode 100644 index 0000000..f2d6304 --- /dev/null +++ b/frontend/src/live/cards.ts @@ -0,0 +1,628 @@ +/** + * NextFloor's floating glass cards: they hang over a point of the plan (the viewer reports where that point is + * on screen after every frame, see setLiveAnchors) and tell what is going on there. + * + * - "house": the energy balance – sun, house, battery, grid – with the share of the house running on its own power + * - "car": a parked car's charge, range and charging, with buttons for lock, climate and charging; away it tells where + * - "media": what a speaker or TV plays – cover, title, artist – with play/pause, skip and the volume + * + * Cards are rendered by Lit; their position is set directly on the element by the 3D view (no render per frame). + */ +import { css, html, nothing, svg, type TemplateResult } from "lit"; +import type { EnergySummary } from "../energy.ts"; +import { socColor, type CarInfo } from "./car.ts"; +import type { MediaNow } from "./media.ts"; +import { formatNumber, translate } from "../i18n.ts"; +import type { HomeAssistant } from "../types.ts"; +import { curvePath } from "./day-curves.ts"; +import type { PrinterInfo } from "./printer.ts"; +import type { HeatPumpInfo } from "./heat-pump.ts"; +import type { PlanPoint } from "../viewer/live-energy.ts"; + +export interface HouseCard { + kind: "house"; + at: PlanPoint; + summary: EnergySummary; + autarky: number | null; + /** Solar and consumption over the last 24 hours (quarter hours), when the history could be loaded. */ + curves?: { solar: (number | null)[]; use: (number | null)[] }; + /** Solar and consumption per day over the last seven days (kWh), from the long-term statistics. */ + week?: { days: number[]; solar: (number | null)[]; use: (number | null)[] }; + /** Gas and water meters: their icon, name and what they read now. */ + meters?: { icon: string; label: string; value: string }[]; +} + +export interface CarCard { + kind: "car"; + at: PlanPoint; + spot: string; + name: string; + car: CarInfo; +} + +export interface MediaCard { + kind: "media"; + at: PlanPoint; + media: MediaNow; +} + +export interface PrinterCard { + kind: "printer"; + at: PlanPoint; + name: string; + printer: PrinterInfo; +} + +export interface HeatPumpCard { + kind: "heatpump"; + at: PlanPoint; + name: string; + pump: HeatPumpInfo; +} + +export type LiveCard = HouseCard | CarCard | MediaCard | PrinterCard | HeatPumpCard; + +/** A button on a card was pressed: the 3D view calls the service (with extra data such as the volume). */ +export type LiveCardAction = (domain: string, service: string, entity: string, data?: Record) => void; + +function watts(hass: HomeAssistant | undefined, w: number): string { + const a = Math.abs(w); + return a >= 1000 ? `${formatNumber(hass, a / 1000, a >= 10000 ? 1 : 2)} kW` : `${Math.round(a)} W`; +} + +/** A ring that fills with a share (0…1). */ +function ring(share: number, color: string): TemplateResult { + const r = 22; + const c = 2 * Math.PI * r; + return html``; +} + +/** The house card's fold: a small corner button shrinks it to its ring and the sun's power, on desktop and phones. */ +export interface LiveCardFold { + folded: boolean; + toggle: () => void; +} + +function houseCard(hass: HomeAssistant | undefined, c: HouseCard, i: number, fold?: LiveCardFold): TemplateResult { + const s = c.summary; + const t = (k: Parameters[1]) => translate(hass, k); + const own = c.autarky; + const foldBtn = fold + ? html`` + : nothing; + if (fold?.folded) { + const sun = s.solar !== null ? `☀ ${watts(hass, s.solar)}` : s.consumption !== null ? `⌂ ${watts(hass, s.consumption)}` : null; + return html`
    + ${own !== null + ? html`
    ${ring(own, own > 0.95 ? "#4ade80" : own > 0.6 ? "#facc15" : "#f87171")}
    ${Math.round(own * 100)}%
    ` + : nothing} + ${sun ? html`${sun}` : own === null ? html`⌂` : nothing} + ${foldBtn} +
    `; + } + const rows: TemplateResult[] = []; + if (s.solar !== null) rows.push(html`
    ☀ ${t("energy_solar")}${watts(hass, s.solar)}
    `); + if (s.consumption !== null) rows.push(html`
    ⌂ ${t("energy_consumption")}${watts(hass, s.consumption)}
    `); + if (s.rest !== undefined && s.rest !== null) rows.push(html`
    ⌂ ${t("energy_rest")}${watts(hass, s.rest)}
    `); + if (s.battery !== null || s.soc !== null) { + const dir = s.battery === null || Math.abs(s.battery) < 15 ? "" : s.battery > 0 ? " ↓" : " ↑"; + rows.push( + html`
    ▮ ${t("energy_battery")}${dir}${s.soc !== null ? `${Math.round(s.soc)} %` : ""}${s.battery !== null && Math.abs(s.battery) >= 15 ? ` · ${watts(hass, s.battery)}` : ""}
    `, + ); + } + if (s.grid !== null) { + const exporting = s.grid < -15; + rows.push(html`
    ⇄ ${t(exporting ? "energy_grid_export" : "energy_grid_import")}${watts(hass, s.grid)}
    `); + } + for (const m of c.meters ?? []) rows.push(html`
    ${m.icon} ${m.label}${m.value}
    `); + return html`
    + ${foldBtn} + ${own !== null + ? html`
    ${ring(own, own > 0.95 ? "#4ade80" : own > 0.6 ? "#facc15" : "#f87171")}
    ${Math.round(own * 100)} %${t("live_autarky")}
    ` + : nothing} +
    ${rows}
    + ${dayChart(hass, c.curves)} ${weekChart(hass, c.week)} +
    `; +} + +/** The last seven days: a bar per day for solar (filled) and consumption (outlined), in kWh. */ +function weekChart(hass: HomeAssistant | undefined, week: HouseCard["week"]): TemplateResult | typeof nothing { + if (!week) return nothing; + const values = [...week.solar, ...week.use].filter((v): v is number => v !== null && v > 0); + if (!values.length) return nothing; + const top = Math.max(...values) * 1.1 || 1; + const [w, h] = [150, 30]; + const slot = w / 7; + const bar = (v: number | null, x: number, cls: string) => (v === null || v <= 0 ? nothing : svg``); + const total = (list: (number | null)[]) => list.reduce((a, b) => a + (b ?? 0), 0); + return html`
    + + 7 ${translate(hass, "live_days")} +
    `; +} + +/** The day at a glance: solar as a filled curve, consumption as a line, over the last 24 hours. */ +function dayChart(hass: HomeAssistant | undefined, curves: HouseCard["curves"]): TemplateResult | typeof nothing { + if (!curves) return nothing; + const values = [...curves.solar, ...curves.use].filter((v): v is number => v !== null); + if (values.length < 4) return nothing; + const top = Math.max(...values) * 1.08 || 1; + const [w, h] = [150, 34]; + const solar = curvePath(curves.solar, w, h, top); + const use = curvePath(curves.use, w, h, top); + return html`
    + + 24 h +
    `; +} + +function carCard(hass: HomeAssistant | undefined, c: CarCard, i: number, act: LiveCardAction): TemplateResult { + const car = c.car; + const t = (k: Parameters[1], v?: Record) => translate(hass, k, v); + const color = socColor(car.soc); + const status = !car.home + ? `${t("live_car_away")}${car.where ? ` · ${car.where}` : ""}${car.distance !== null ? ` · ${formatNumber(hass, car.distance, car.distance < 10 ? 1 : 0)} km` : ""}` + : car.charging + ? `⚡ ${t("live_car_charging")}${car.chargingW ? ` · ${watts(hass, car.chargingW)}` : ""}` + : car.plugged + ? `🔌 ${t("live_car_plugged")}` + : ""; + const e = car.entities; + const button = (on: boolean | null, label: string, icon: string, run: () => void) => + html``; + return html`
    +
    + ${ring((car.soc ?? 0) / 100, color)} +
    ${car.soc !== null ? `${Math.round(car.soc)} %` : "–"}${car.range !== null ? `${Math.round(car.range)} ${car.rangeUnit}` : ""}
    +
    +
    +
    ${c.name}
    + ${status ? html`
    ${status}
    ` : nothing} + ${car.inside !== null ? html`
    🌡 ${formatNumber(hass, car.inside, 1)} °C
    ` : nothing} + ${car.departure ? html`
    ⏰ ${t("live_car_departure", { time: car.departure })}
    ` : nothing} + ${car.open.length ? html`
    ⚠ ${t("live_car_open", { parts: car.open.join(", ") })}
    ` : nothing} +
    + ${e.lock + ? button(car.locked, t(car.locked ? "live_car_unlock" : "live_car_lock"), car.locked ? "🔒" : "🔓", () => { + if (car.locked && !confirm(t("live_car_unlock_confirm", { name: c.name }))) return; + act("lock", car.locked ? "unlock" : "lock", e.lock!); + }) + : nothing} + ${e.climate ? button(car.climateOn, t("live_car_climate"), "❄", () => act(e.climate!.split(".")[0], car.climateOn ? "turn_off" : "turn_on", e.climate!)) : nothing} + ${e.charge && car.home ? button(car.charging, t("live_car_charge"), "⚡", () => act(e.charge!.split(".")[0], "toggle", e.charge!)) : nothing} +
    +
    +
    `; +} + +function mediaCard(hass: HomeAssistant | undefined, c: MediaCard, i: number, act: LiveCardAction): TemplateResult { + const m = c.media; + const t = (k: Parameters[1]) => translate(hass, k); + const color = `rgb(${m.color.join(",")})`; + const btn = (label: string, icon: string, service: string) => + html``; + // compact (cover and title); a tap opens the controls + return html`
    (ev.currentTarget as HTMLElement).classList.toggle("live-open")}> + ${m.picture ? html`` : html`
    ♪
    `} +
    +
    ${m.title || m.name}
    +
    ${m.artist || m.app || m.name}
    +
    + ${btn(t("live_media_prev"), "⏮", "media_previous_track")} ${btn(t("live_media_playpause"), "⏯", "media_play_pause")} ${btn(t("live_media_next"), "⏭", "media_next_track")} + ${m.volume !== null + ? html` ev.stopPropagation()} + @change=${(ev: Event) => act("media_player", "volume_set", m.entity, { volume_level: Number((ev.target as HTMLInputElement).value) / 100 })} + />` + : nothing} +
    +
    +
    `; +} + +/** + * Keeps the cards from covering each other: after they were placed for a frame, a card that overlaps one placed + * before it (lower on screen first) moves up above it. Its thread to the anchor stretches. + */ +export function unstackLhCards(root: ParentNode): void { + const cards = [...root.querySelectorAll(".live-card")].filter((el) => el.style.visibility !== "hidden"); + const placed: { x0: number; x1: number; y0: number; y1: number }[] = []; + // a card near the edge slides back into the view (on a phone it was cut off); its thread still points home + const width = cards[0]?.parentElement?.clientWidth ?? 0; + const items = cards + .map((el) => { + const [anchor, w] = [Number(el.dataset.x), el.offsetWidth]; + const x = !width ? anchor : width > w + 16 ? Math.min(Math.max(anchor, w / 2 + 8), width - w / 2 - 8) : width / 2; + el.style.setProperty("--live-dx", `${Math.round(anchor - x)}px`); + return { el, x, y: Number(el.dataset.y), w, h: el.offsetHeight }; + }) + .sort((a, b) => b.y - a.y); + for (const it of items) { + let bottom = it.y; + for (let guard = 0; guard < 12; guard++) { + const r = { x0: it.x - it.w / 2, x1: it.x + it.w / 2, y0: bottom - it.h, y1: bottom }; + const hit = placed.find((p) => r.x0 < p.x1 + 6 && r.x1 > p.x0 - 6 && r.y0 < p.y1 + 6 && r.y1 > p.y0 - 6); + if (!hit) break; + bottom = hit.y0 - 8; + } + placed.push({ x0: it.x - it.w / 2, x1: it.x + it.w / 2, y0: bottom - it.h, y1: bottom }); + const lift = it.y - bottom; + it.el.style.transform = `translate(${Math.round(it.x)}px, ${Math.round(bottom)}px) translate(-50%, -100%)`; + it.el.style.setProperty("--live-thread", `${Math.round(18 + lift)}px`); + } +} + +/** A 3D printer's print: the model's picture, progress, when it is done, the layer, temperatures and the filaments. */ +function printerCard(hass: HomeAssistant | undefined, c: PrinterCard, i: number): TemplateResult { + const p = c.printer; + const t = (k: Parameters[1], v?: Record) => translate(hass, k, v); + const pct = p.progress ?? 0; + const clock = (ms: number) => new Intl.DateTimeFormat(hass?.language ?? navigator.language, { hour: "2-digit", minute: "2-digit" }).format(new Date(ms)); + const left = p.remaining !== null ? (p.remaining >= 60 ? `${Math.floor(p.remaining / 60)} h ${Math.round(p.remaining % 60)} min` : `${Math.round(p.remaining)} min`) : null; + const temps = [p.nozzle !== null ? `${t("printer_nozzle")} ${Math.round(p.nozzle)}°` : null, p.bed !== null ? `${t("printer_bed")} ${Math.round(p.bed)}°` : null].filter(Boolean).join(" · "); + return html`
    +
    + ${p.picture ? html`` : ring(pct / 100, p.printing ? "#38bdf8" : "#8aa0c8")} +
    ${p.progress !== null ? `${Math.round(pct)} %` : "–"}${t(`printer_${p.printing ? "printing" : /finish|complete|fertig/.test(p.status) ? "done" : /pause/.test(p.status) ? "paused" : /error|fail/.test(p.status) ? "error" : "idle"}`)}
    +
    +
    +
    ${c.name}
    + ${p.job ? html`
    ${p.job}
    ` : nothing} + ${p.printing && (p.endsAt || left) ? html`
    ⏱ ${[left, p.endsAt ? t("printer_done_at", { time: clock(p.endsAt) }) : null].filter(Boolean).join(" · ")}
    ` : nothing} + ${p.layer !== null ? html`
    ▤ ${t("printer_layer")} ${p.layer}${p.layers ? ` / ${p.layers}` : ""}
    ` : nothing} + ${temps ? html`
    🌡 ${temps}
    ` : nothing} + ${p.filaments.length ? html`
    ${p.filaments.map((f) => html``)}
    ` : nothing} +
    +
    `; +} + +/** A heat pump: what it does, flow and return, the outside, power and heat, and its COP as a ring (6 = full). */ +function heatPumpCard(hass: HomeAssistant | undefined, c: HeatPumpCard, i: number): TemplateResult { + const p = c.pump; + const t = (k: Parameters[1]) => translate(hass, k); + const deg = (v: number | null) => (v === null ? "–" : `${formatNumber(hass, v, 1)}°`); + const icon = { heating: "🔥", water: "🚿", cooling: "❄", defrost: "🧊", idle: "⏸" }[p.mode]; + return html`
    +
    + ${ring(Math.min(1, (p.cop ?? 0) / 6), (p.cop ?? 0) >= 3.5 ? "#4ade80" : (p.cop ?? 0) >= 2.5 ? "#facc15" : "#fb923c")} +
    ${p.cop !== null ? formatNumber(hass, p.cop, 1) : icon}${p.cop !== null ? "COP" : ""}
    +
    +
    +
    ${c.name}
    +
    ${icon} ${t(`heatpump_${p.mode}`)}
    + ${p.flow !== null || p.return !== null ? html`
    ${t("heatpump_flow_return")}${deg(p.flow)} → ${deg(p.return)}
    ` : nothing} + ${p.heat !== null ? html`
    ${t("heatpump_heat")}${watts(hass, p.heat)}
    ` : nothing} + ${p.power !== null ? html`
    ${t("heatpump_power")}${watts(hass, p.power)}
    ` : nothing} + ${p.outside !== null ? html`
    🌡 ${t("heatpump_outside")} ${deg(p.outside)}
    ` : nothing} +
    +
    `; +} + +export function renderLhCards(hass: HomeAssistant | undefined, cards: readonly LiveCard[], act: LiveCardAction, fold?: LiveCardFold): TemplateResult | typeof nothing { + if (!cards.length) return nothing; + return html`
    + ${cards.map((c, i) => (c.kind === "house" ? houseCard(hass, c, i, fold) : c.kind === "car" ? carCard(hass, c, i, act) : c.kind === "printer" ? printerCard(hass, c, i) : c.kind === "heatpump" ? heatPumpCard(hass, c, i) : mediaCard(hass, c, i, act)))} +
    `; +} + +export const liveCardStyles = css` + .live-cards { + position: absolute; + inset: 0; + pointer-events: none; + overflow: hidden; + z-index: 2; + container-type: size; + } + /* a phone: the cards keep to the screen, the house card leaves its week out */ + @container (max-width: 480px) { + .live-card { + gap: 8px; + padding: 8px 10px; + font-size: 11.5px; + } + .live-card-house:not(.live-folded) { + padding-right: 28px; + } + .live-card-house .live-week { + display: none; + } + .live-rows { + min-width: 0; + } + } + .live-card { + position: absolute; + left: 0; + top: 0; + visibility: hidden; + pointer-events: auto; + display: flex; + gap: 12px; + align-items: center; + padding: 10px 14px; + border-radius: calc(var(--nf-radius) + 4px); + background: var(--nf-chrome); + box-shadow: var(--nf-shadow); + backdrop-filter: blur(8px); + -webkit-backdrop-filter: blur(8px); + color: var(--nf-text); + font-size: 12.5px; + line-height: 1.35; + white-space: nowrap; + will-change: transform; + } + .live-card::after { + /* a thin glowing thread down to the point the card belongs to */ + content: ""; + position: absolute; + left: clamp(12px, calc(50% + var(--live-dx, 0px)), calc(100% - 12px)); + bottom: calc(-1 * var(--live-thread, 18px)); + width: 1px; + height: var(--live-thread, 18px); + background: linear-gradient(color-mix(in srgb, var(--nf-text) 45%, transparent), transparent); + } + .live-fold { + position: absolute; + top: 4px; + right: 4px; + width: 20px; + height: 20px; + padding: 0; + border: 0; + border-radius: 50%; + background: color-mix(in srgb, var(--nf-text) 10%, transparent); + color: var(--nf-text); + font: inherit; + font-size: 13px; + line-height: 20px; + cursor: pointer; + opacity: 0.7; + } + .live-fold:hover, + .live-fold:focus-visible { + opacity: 1; + background: color-mix(in srgb, var(--nf-text) 20%, transparent); + } + .live-card-house:not(.live-folded) { + padding-right: 30px; + } + .live-folded { + padding: 6px 30px 6px 8px; + gap: 8px; + } + .live-folded .live-own, + .live-folded .live-ring { + width: 38px; + height: 38px; + } + .live-folded .live-own-text b { + font-size: 11px; + } + .live-rows { + display: grid; + gap: 2px; + min-width: 150px; + } + .live-row { + display: flex; + justify-content: space-between; + gap: 14px; + } + .live-day { + position: relative; + margin-top: 6px; + } + .live-day svg { + display: block; + width: 100%; + height: 34px; + } + .live-day-solar { + fill: rgba(250, 204, 21, 0.35); + stroke: #facc15; + stroke-width: 1; + vector-effect: non-scaling-stroke; + } + .live-week svg { + height: 30px; + } + .live-week-solar { + fill: rgba(250, 204, 21, 0.6); + } + .live-week-use { + fill: rgba(232, 238, 255, 0.18); + stroke: #e8eeff; + stroke-width: 1; + vector-effect: non-scaling-stroke; + } + .live-day-use { + fill: none; + stroke: #e8eeff; + stroke-width: 1.4; + vector-effect: non-scaling-stroke; + } + .live-day span { + position: absolute; + right: 2px; + top: 0; + font-size: 9px; + opacity: 0.6; + } + .live-row span { + opacity: 0.8; + } + .live-solar b { + color: color-mix(in srgb, #ffd166 72%, var(--nf-text)); + } + .live-battery b { + color: color-mix(in srgb, #4ade80 72%, var(--nf-text)); + } + .live-import b { + color: color-mix(in srgb, #f87193 72%, var(--nf-text)); + } + .live-export b { + color: color-mix(in srgb, #38dcf5 72%, var(--nf-text)); + } + .live-house b { + color: color-mix(in srgb, #b6c2ff 72%, var(--nf-text)); + } + .live-title { + font-weight: 600; + font-size: 13px; + } + .live-status { + opacity: 0.85; + } + .live-print-pic { + width: 54px; + height: 54px; + border-radius: 12px; + object-fit: cover; + background: rgba(255, 255, 255, 0.06); + } + .live-filaments { + display: flex; + gap: 4px; + margin-top: 2px; + } + .live-filaments i { + width: 12px; + height: 12px; + border-radius: 50%; + border: 1px solid rgba(255, 255, 255, 0.4); + } + .live-warn { + color: #fbbf24; + opacity: 1; + } + .live-actions { + display: flex; + gap: 6px; + margin-top: 4px; + } + .live-btn { + font: inherit; + font-size: 14px; + width: 32px; + height: 28px; + border-radius: 9px; + border: none; + background: var(--nf-fill); + color: inherit; + cursor: pointer; + } + .live-btn.live-on { + background: color-mix(in srgb, var(--live-soc, #4ade80) 30%, transparent); + border-color: var(--live-soc, #4ade80); + } + .live-card-car { + border-color: color-mix(in srgb, var(--live-soc) 60%, transparent); + box-shadow: 0 0 22px color-mix(in srgb, var(--live-soc) 30%, transparent), inset 0 0 18px rgba(120, 200, 255, 0.06); + } + .live-card-car.live-charging { + animation: live-charge 1.6s ease-in-out infinite; + } + @keyframes live-charge { + 50% { + box-shadow: 0 0 34px color-mix(in srgb, var(--live-soc) 55%, transparent), inset 0 0 18px rgba(120, 200, 255, 0.1); + } + } + .live-card-car.live-away { + opacity: 0.85; + border-style: dashed; + } + /* phones: only the house and the car, the media cards would cover the rooms */ + .nf-narrow .live-card-media { + display: none; + } + .live-card-media { + border-color: color-mix(in srgb, var(--live-soc) 55%, transparent); + box-shadow: 0 0 22px color-mix(in srgb, var(--live-soc) 28%, transparent), inset 0 0 18px rgba(120, 200, 255, 0.06); + } + .live-card-media .live-title { + max-width: 190px; + overflow: hidden; + text-overflow: ellipsis; + } + .live-card-media { + cursor: pointer; + padding: 7px 12px 7px 7px; + } + .live-card-media .live-actions { + display: none; + } + .live-card-media.live-open .live-actions { + display: flex; + } + .live-card-media.live-open { + z-index: 5; + } + .live-cover { + width: 40px; + height: 40px; + border-radius: 10px; + object-fit: cover; + box-shadow: 0 0 14px color-mix(in srgb, var(--live-soc) 40%, transparent); + } + .live-cover-none { + display: grid; + place-items: center; + font-size: 24px; + background: color-mix(in srgb, var(--live-soc) 25%, transparent); + } + .live-volume { + width: 80px; + accent-color: var(--live-soc); + } + .live-own { + position: relative; + width: 54px; + height: 54px; + } + .live-ring { + width: 54px; + height: 54px; + } + .live-ring-bg { + fill: none; + stroke: color-mix(in srgb, var(--nf-text) 10%, transparent); + stroke-width: 5; + } + .live-ring-fg { + fill: none; + stroke-width: 5; + stroke-linecap: round; + transition: stroke-dasharray 0.6s ease; + } + .live-own-text { + position: absolute; + inset: 0; + display: grid; + place-content: center; + text-align: center; + } + .live-own-text b { + font-size: 13px; + } + .live-own-text span { + font-size: 8.5px; + opacity: 0.75; + text-transform: uppercase; + letter-spacing: 0.04em; + } +`; diff --git a/frontend/src/live/day-curves.test.ts b/frontend/src/live/day-curves.test.ts new file mode 100644 index 0000000..8e447c6 --- /dev/null +++ b/frontend/src/live/day-curves.test.ts @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { HomeAssistant } from "../types.ts"; +import { curvePath, dayCurves, statesRead } from "./day-curves.ts"; +import { parseHistory } from "./time-travel.ts"; + +const hass = { + states: { + "sensor.pv": { entity_id: "sensor.pv", state: "800", attributes: {} }, + "sensor.grid": { entity_id: "sensor.grid", state: "200", attributes: {} }, + "sensor.other": { entity_id: "sensor.other", state: "1", attributes: {} }, + }, +} as unknown as HomeAssistant; +const balance = (h: HomeAssistant) => { + const solar = Number(h.states["sensor.pv"].state); + return { solar, consumption: solar + Number(h.states["sensor.grid"].state) }; +}; + +test("the sensors a balance reads are the ones whose history is loaded", () => { + assert.deepEqual(statesRead(hass, balance).sort(), ["sensor.grid", "sensor.pv"]); +}); + +test("the balance is worked out again for every sample of the day", () => { + const history = parseHistory({ + "sensor.pv": [{ s: "0", lu: 0 }, { s: "1000", lu: 50 }], + "sensor.grid": [{ s: "300", lu: 0 }], + }); + const c = dayCurves(hass, history, 0, 100_000, balance, 4); + assert.deepEqual(c.solar, [0, 1000, 1000, 1000]); + assert.deepEqual(c.use, [300, 1300, 1300, 1300]); +}); + +test("a curve is a path scaled to its box; missing values break it", () => { + assert.equal(curvePath([0, 50, 100], 100, 10, 100), "M0.0,10.0L50.0,5.0L100.0,0.0"); + assert.equal(curvePath([0, null, 100], 100, 10, 100), "M0.0,10.0M100.0,0.0"); + assert.equal(curvePath([1, 2], 10, 10, 0), ""); +}); diff --git a/frontend/src/live/day-curves.ts b/frontend/src/live/day-curves.ts new file mode 100644 index 0000000..8c23f6e --- /dev/null +++ b/frontend/src/live/day-curves.ts @@ -0,0 +1,55 @@ +// Day curves for the house's energy card: solar and consumption over the last 24 hours. The history of exactly the sensors the +// live balance reads is loaded, and the balance is worked out again for every quarter hour, so the curves always mean what the +// numbers on the card mean (automatic sensors included). + +import type { HomeAssistant } from "../types.ts"; +import { hassAt, type History } from "./time-travel.ts"; + +/** The entity ids a function reads from hass.states. */ +export function statesRead(hass: HomeAssistant, run: (hass: HomeAssistant) => unknown): string[] { + const seen = new Set(); + const states = new Proxy(hass.states, { + get(target, key: string | symbol) { + if (typeof key === "string") seen.add(key); + return (target as Record)[key]; + }, + }); + run({ ...hass, states } as HomeAssistant); + return [...seen].filter((id) => id.includes(".") && id in hass.states); +} + +export interface DayCurves { + solar: (number | null)[]; + use: (number | null)[]; +} + +/** The balance at `samples` evenly spread moments between from and to, from the history of its sensors. */ +export function dayCurves(hass: HomeAssistant, history: History, from: number, to: number, balance: (hass: HomeAssistant) => { solar: number | null; consumption: number | null }, samples = 96): DayCurves { + const solar: (number | null)[] = []; + const use: (number | null)[] = []; + for (let i = 0; i < samples; i++) { + const t = from + ((to - from) * (i + 1)) / samples; + const s = balance(hassAt(hass, history, t)); + solar.push(s.solar); + use.push(s.consumption); + } + return { solar, use }; +} + +/** An SVG path through the values (missing ones break the line), scaled into width × height with `top` as the highest value. */ +export function curvePath(values: readonly (number | null)[], width: number, height: number, top: number): string { + if (top <= 0 || values.length < 2) return ""; + let d = ""; + let pen = false; + values.forEach((v, i) => { + if (v === null) { + pen = false; + return; + } + const x = (i / (values.length - 1)) * width; + const y = height - (Math.max(0, Math.min(top, v)) / top) * height; + d += `${pen ? "L" : "M"}${x.toFixed(1)},${y.toFixed(1)}`; + pen = true; + }); + return d; +} diff --git a/frontend/src/live/energy-flow.test.ts b/frontend/src/live/energy-flow.test.ts new file mode 100644 index 0000000..f902ba9 --- /dev/null +++ b/frontend/src/live/energy-flow.test.ts @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { findConsumers } from "../energy.ts"; +import { emptyBuilding, newFloor, type Building, type Furniture } from "../model.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; +import { ENERGY_COLORS, energyConnections, energyPicture, houseHub, routed } from "./energy-flow.ts"; + +const sensor = (entity_id: string, state: string): HassEntity => ({ entity_id, state, attributes: { device_class: "power" } }); +const hassOf = (list: HassEntity[]) => ({ states: Object.fromEntries(list.map((s) => [s.entity_id, s])), entities: {} }) as unknown as HomeAssistant; +const meter = (id: string, x: number, extra: Partial = {}): Furniture => ({ id, type: "meter", x, z: 1, rotation: 0, w: 0.5, d: 0.2, h: 1, variant: null, entity: null, power: `sensor.${id}`, ...extra }); + +// ground floor with the main meter and both sub-meters; a consumer on each floor +function flats(advanced: boolean): Building { + const b = emptyBuilding(); + b.floors = ["g", "og", "dg"].map((id, i) => { + const f = newFloor(id, id, i * 3); + f.rooms = [{ id: `r${id}`, name: id, area_id: null, points: [[0, 0], [6, 0], [6, 4], [0, 4]], floor_material: "wood" }]; + f.placements = [{ entity_id: `sensor.use_${id}`, x: 4, z: 3, y: null, mount: null }]; + return f; + }); + b.floors[0].furniture = [meter("og", 2, { parent_meter: "main", meter_floors: ["og"] }), meter("main", 1), meter("dg", 3, { parent_meter: "main", meter_floors: ["dg"] })]; + b.energy.advanced = advanced; + return b; +} + +const hass = hassOf([sensor("sensor.main", "3000"), sensor("sensor.og", "900"), sensor("sensor.dg", "700"), sensor("sensor.use_g", "200"), sensor("sensor.use_og", "300"), sensor("sensor.use_dg", "400")]); +const from = (pic: ReturnType, key: string) => pic.arcs.find((a) => a.key === key)?.from; + +test("with the advanced energy mode off the first meter is the hub and feeds everything", () => { + const b = flats(false); + const plain = flats(false); + for (const f of plain.floors[0].furniture) (delete f.parent_meter, delete f.meter_floors); + assert.deepEqual(energyPicture(hass, b), energyPicture(hass, plain)); + assert.equal(houseHub(b)?.x, 2); + assert.ok(!energyPicture(hass, b).arcs.some((a) => a.key.startsWith("meter:"))); +}); + +test("sub-meters draw from the main meter and feed the consumers on their floors", () => { + const pic = energyPicture(hass, flats(true)); + assert.equal(houseHub(flats(true))?.x, 1); + const og = pic.arcs.find((a) => a.key === "meter:og")!; + assert.deepEqual([og.from.x, og.to.x, og.power], [1, 2, 900]); + assert.equal(from(pic, "use:sensor.use_g")?.x, 1, "unassigned floors stay on the main meter"); + assert.equal(from(pic, "use:sensor.use_og")?.x, 2); + assert.equal(from(pic, "use:sensor.use_dg")?.x, 3); + assert.equal(pic.summary.rest, 3000 - 900 - 700); + // the 3D view adds the meters' own sensors as consumers: a sub-meter gets its cable from its parent only + const b = flats(true); + const withMeter = [...findConsumers(hass, b), { id: "og", powerEntity: "sensor.og", floorId: "g", x: 2, z: 1, power: 900 }]; + assert.ok(!energyPicture(hass, b, withMeter).arcs.some((a) => a.key === "use:og")); +}); + +// A multi-family house: roof plant at the main meter, a balcony plant behind the upper flat's meter (see energy.test.ts) +function withPlants(advanced: boolean): Building { + const b = flats(advanced); + const at = (id: string, type: string, x: number, extra: Partial = {}) => ({ ...meter(id, x, extra), type }); + b.floors[0].furniture.push(at("roof", "inverter", 5)); + b.floors[1].furniture = [at("balcony", "inverter", 4, { parent_meter: "og" })]; + return b; +} +const plantHass = hassOf([sensor("sensor.main", "-1000"), sensor("sensor.roof", "1000"), sensor("sensor.og", "-300"), sensor("sensor.dg", "200"), sensor("sensor.balcony", "800"), sensor("sensor.use_g", "100"), sensor("sensor.use_og", "500"), sensor("sensor.use_dg", "200")]); + +test("a balcony plant feeds its flat first and only the surplus flows back to the main meter", () => { + const pic = energyPicture(plantHass, withPlants(true)); + const arc = (key: string) => pic.arcs.find((a) => a.key === key)!; + assert.deepEqual([arc("inverter:balcony").from.floorId, arc("inverter:balcony").to.x, arc("inverter:balcony").power], ["og", 2, 800]); + assert.deepEqual([arc("meter:og").from.x, arc("meter:og").to.x, arc("meter:og").power], [2, 1, 300]); + assert.deepEqual(arc("meter:og").color, ENERGY_COLORS.solar); + assert.deepEqual([arc("meter:dg").from.x, arc("meter:dg").to.x, arc("meter:dg").power], [1, 3, 200]); + assert.deepEqual([arc("inverter").from.x, arc("inverter").power], [5, 1000], "the roof plant feeds the house"); + assert.deepEqual([arc("grid").from.x, arc("grid").power], [1, 1000], "the rest goes to the grid"); + assert.equal(arc("use:sensor.use_og").from.x, 2); + assert.equal(pic.summary.rest, 100); +}); + +test("with the mode off a balcony plant's meter is ignored", () => { + const plain = withPlants(false); + delete plain.floors[1].furniture[0].parent_meter; + for (const f of plain.floors[0].furniture) (delete f.parent_meter, delete f.meter_floors); + assert.deepEqual(energyPicture(plantHass, withPlants(false)), energyPicture(plantHass, plain)); +}); + +test("a connection with a cable route follows it, walked from the end nearer to where the power starts", () => { + const b = flats(true); + b.floors[0].furniture.push({ ...meter("bat", 5), type: "home_battery", power: "sensor.bat" }); + assert.ok(energyConnections(b).some((c) => c.key === "battery")); + assert.ok(energyConnections(b).some((c) => c.key === "meter:og")); + // the cable runs from the battery (x 5) along the wall to the hub (x 1), drawn starting at the battery's end + b.energy.routes = [{ key: "battery", points: [{ floor_id: "g", x: 5, z: 4 }, { floor_id: "g", x: 1, z: 4 }], cable: true }]; + const hub = houseHub(b)!; + const battery = { floorId: "g", x: 5, z: 1, y: 0.8 }; + const discharging = routed(b, { key: "battery", from: battery, to: hub, power: 500, color: ENERGY_COLORS.battery }); + assert.deepEqual(discharging.via?.map((p) => p.x), [5, 1]); + assert.equal(discharging.cable, true); + const charging = routed(b, { key: "battery", from: hub, to: battery, power: 500, color: ENERGY_COLORS.battery }); + assert.deepEqual(charging.via?.map((p) => p.x), [1, 5], "charging walks the same cable the other way"); + // other connections keep their arc + assert.equal(routed(b, { key: "grid", from: hub, to: battery, power: 1, color: ENERGY_COLORS.import }).via, undefined); +}); diff --git a/frontend/src/live/energy-flow.ts b/frontend/src/live/energy-flow.ts new file mode 100644 index 0000000..e2add4c --- /dev/null +++ b/frontend/src/live/energy-flow.ts @@ -0,0 +1,254 @@ +/** + * Where the power goes right now, as NextFloor draws it (see viewer/live-energy.ts): arcs between the devices + * placed in the plan, sparkling solar modules, and the numbers for the house card. + * + * - every solar field sends its share of the production to the inverter + * - the battery charges from the house or discharges into it + * - the grid connection delivers to the house or takes the export + * - the house feeds every consumer that reports its power (a wallbox in its own colour) + * - advanced energy mode: each sub-meter draws from the meter it hangs off (or feeds back into it) and feeds the + * consumers on its floors; an inverter or battery behind a sub-meter works into that sub-meter + * + * "The house" is where the cables meet: the meter cabinet, else the inverter, else the middle of the ground floor. + */ +import { deviceMeter, deviceSensors, energySummary, findConsumers, oneBattery, readPower, subMeterIds, type Consumer, type EnergySummary } from "../energy.ts"; +import type { Building, EnergyRoute, Floor, Furniture, SolarField } from "../model.ts"; +import { fieldFace, fieldModules, roofFaces, topFloor, wallFaces, GROUND, groundFloor } from "../solar.ts"; +import type { HomeAssistant } from "../types.ts"; +import type { EnergyArc, PlanPoint, SparkField } from "../viewer/live-energy.ts"; + +/** Colours of the particles: sun, battery, grid import and export, the house's own cables, the wallbox. */ +export const ENERGY_COLORS: Record<"solar" | "battery" | "import" | "export" | "house" | "wallbox", [number, number, number]> = { + solar: [255, 196, 46], + battery: [74, 222, 128], + import: [248, 96, 120], + export: [56, 220, 245], + house: [150, 170, 255], + wallbox: [80, 175, 255], +}; + +/** Below this a flow is not drawn (standby noise). */ +const MIN_W = 15; + +type Spot = PlanPoint & { id: string }; + +function spotsOf(b: Building, type: string): Spot[] { + const out: Spot[] = []; + for (const f of b.floors) for (const m of f.furniture) if (m.type === type) out.push({ id: m.id, floorId: f.id, x: m.x, z: m.z, y: Math.max(0.4, Math.min(1.4, m.h * 0.8)) }); + return out; +} + +function centre(floor: Floor | null): PlanPoint | null { + if (!floor?.rooms.length) return null; + let x = 0, z = 0, n = 0; + for (const r of floor.rooms) for (const [px, pz] of r.points) (x += px), (z += pz), n++; + return n ? { floorId: floor.id, x: x / n, z: z / n, y: 1 } : null; +} + +/** The point where the house's cables meet (a sub-meter of the advanced energy mode is not it). */ +export function houseHub(b: Building): PlanPoint | null { + const subs = subMeterIds(b); + return spotsOf(b, "meter").find((m) => !subs.has(m.id)) ?? spotsOf(b, "inverter")[0] ?? centre(groundFloor(b)); +} + +/** Where the grid comes in: the grid connection point, else the meter, else the hub (then no grid arc is drawn). */ +function gridSpot(b: Building, hub: PlanPoint): PlanPoint | null { + const g = spotsOf(b, "grid_point")[0]; + if (g) return g; + // without a connection point the power comes "from the street": a little outside the hub's floor + const floor = b.floors.find((f) => f.id === hub.floorId); + if (!floor?.rooms.length) return null; + let x0 = Infinity, x1 = -Infinity, z1 = -Infinity; + for (const r of floor.rooms) for (const [x, z] of r.points) (x0 = Math.min(x0, x)), (x1 = Math.max(x1, x)), (z1 = Math.max(z1, z)); + return { floorId: hub.floorId, x: Math.max(x0, Math.min(x1, hub.x)), z: z1 + 3, y: 0.2 }; +} + +const modulesOf = (f: SolarField) => Math.max(1, f.rows * f.cols - (f.skip?.length ?? 0)); + +/** How much every solar field makes now: its own sensor, else a share of the plant by module count. */ +export function fieldProduction(hass: HomeAssistant, b: Building, solar: number | null): Map { + const fields = b.settings.roof.solar ?? []; + const out = new Map(); + let known = 0; + const rest: SolarField[] = []; + for (const f of fields) { + const own = f.entity && f.entity !== "none" ? readPower(hass.states[f.entity]) : null; + if (own !== null) { + out.set(f.id, Math.max(0, own)); + known += Math.max(0, own); + } else rest.push(f); + } + const left = Math.max(0, (solar ?? 0) - known); + const total = rest.reduce((n, f) => n + modulesOf(f), 0); + for (const f of rest) out.set(f.id, total ? (left * modulesOf(f)) / total : 0); + return out; +} + +/** The floor a solar field rides on (the roof follows the top floor, garden fields the ground floor). */ +function fieldFloor(b: Building, f: SolarField): string | null { + if (f.face === GROUND) return groundFloor(b)?.id ?? null; + const wall = /^wall:([^:]+):/.exec(f.face); + if (wall) return wall[1]; + return topFloor(b)?.id ?? null; +} + +export interface EnergyPicture { + arcs: EnergyArc[]; + sparks: SparkField[]; + summary: EnergySummary; + /** Share of the house's consumption covered by sun and battery right now (0…1), null without a grid sensor. */ + autarky: number | null; +} + +/** `powerOf` says which power sensor a placed device uses (as in deviceSensors); by default its own field. */ +export function energyPicture(hass: HomeAssistant, b: Building, consumers: Consumer[] = findConsumers(hass, b), powerOf?: (f: Furniture) => string | null): EnergyPicture { + const devices = powerOf ? deviceSensors(b, powerOf) : deviceSensors(b); + const summary = energySummary(hass, b, consumers, devices); + const arcs: EnergyArc[] = []; + const sparks: SparkField[] = []; + const hub = houseHub(b); + const consumption = summary.consumption ?? 0; + const autarky = summary.grid === null || consumption <= 0 ? null : Math.max(0, Math.min(1, 1 - Math.max(0, summary.grid) / consumption)); + if (!hub) return { arcs, sparks, summary, autarky }; + // advanced energy mode: inverters and batteries behind a sub-meter work into it, not into the house + const behind = new Map(b.floors.flatMap((f) => f.furniture).flatMap((m) => (deviceMeter(b, m) ? [[m.id, deviceMeter(b, m)!] as const] : []))); + const inverter = spotsOf(b, "inverter").find((s) => !behind.has(s.id)) ?? hub; + const inverters = new Map(spotsOf(b, "inverter").map((s) => [s.id, s])); + const strings = new Map((b.settings.roof.strings ?? []).map((s) => [s.id, s.inverter ?? null])); + + // the sun: each field to the inverter, and its modules sparkle with what it makes + const faces = [...roofFaces(b), ...wallFaces(b)]; + const production = fieldProduction(hass, b, summary.solar); + for (const f of b.settings.roof.solar ?? []) { + const face = fieldFace(b, f, faces); + if (!face) continue; + const modules = fieldModules(face, f); + if (!modules.length) continue; + const p = production.get(f.id) ?? 0; + const peak = modulesOf(f) * (f.wp ?? 400); + const level = p > MIN_W ? Math.pow(Math.min(1, p / peak), 0.6) : 0; + const floorId = fieldFloor(b, f); + sparks.push({ floorId, quads: modules.map((m) => m.corners), level }); + if (p <= MIN_W) continue; + // the arc starts at the middle of the field (building heights: taken off the floor it rides on) + let x = 0, y = 0, z = 0; + for (const m of modules) for (const c of m.corners) (x += c[0]), (y += c[1]), (z += c[2]); + const n = modules.length * 4; + const base = b.floors.find((fl) => fl.id === floorId)?.elevation ?? 0; + // advanced energy mode: a field goes to the inverter of its string (the balcony field to the balcony inverter) + const own = b.energy.advanced ? inverters.get(strings.get(f.string ?? "") ?? "") : undefined; + arcs.push({ key: `solar:${f.id}`, from: { floorId, x: x / n, y: y / n - base + 0.1, z: z / n }, to: own ?? inverter, power: p, color: ENERGY_COLORS.solar }); + } + + // the battery (without those behind a sub-meter) + const battery = spotsOf(b, "home_battery").find((s) => !behind.has(s.id)); + const houseBattery = summary.battery === null ? null : summary.battery - (summary.subMeters ?? []).reduce((sum, m) => sum + m.battery, 0); + if (battery && houseBattery !== null && Math.abs(houseBattery) > MIN_W) { + const discharging = houseBattery > 0; + arcs.push({ key: "battery", from: discharging ? battery : hub, to: discharging ? hub : battery, power: Math.abs(houseBattery), color: ENERGY_COLORS.battery }); + } + // the inverter feeds the house (when it is not the hub itself) + const houseSolar = (summary.solar ?? 0) - (summary.subMeters ?? []).reduce((sum, m) => sum + m.solar, 0); + if (inverter !== hub && houseSolar > MIN_W) { + arcs.push({ key: "inverter", from: inverter, to: hub, power: houseSolar, color: ENERGY_COLORS.solar }); + } + // the grid + const grid = gridSpot(b, hub); + if (grid && summary.grid !== null && Math.abs(summary.grid) > MIN_W) { + const importing = summary.grid > 0; + arcs.push({ key: "grid", from: importing ? grid : hub, to: importing ? hub : grid, power: Math.abs(summary.grid), color: importing ? ENERGY_COLORS.import : ENERGY_COLORS.export }); + } + // advanced energy mode: each sub-meter draws from the meter it hangs off (or feeds back, with solar behind it), + // and the consumers on its floors draw from it; the first sub-meter naming a floor wins. Its inverters and + // batteries work into it, so its solar reaches its own consumers first and only the surplus flows back. + const meters = new Map(spotsOf(b, "meter").map((m) => [m.id, m])); + const sensorOf = powerOf ?? ((f: Furniture) => (f.power && f.power !== "none" ? f.power : null)); + for (const floor of b.floors) { + for (const f of floor.furniture) { + const at = meters.get(behind.get(f.id) ?? ""); + const spot = spotsOf(b, f.type).find((s) => s.id === f.id); + if (!at || !spot) continue; + const sensor = sensorOf(f); + if (f.type === "inverter") { + const w = Math.max(0, (sensor ? readPower(hass.states[sensor]) : null) ?? 0); + if (w > MIN_W) arcs.push({ key: `inverter:${f.id}`, from: spot, to: at, power: w, color: ENERGY_COLORS.solar }); + } else if (f.type === "home_battery") { + const charge = f.charge && f.charge !== "none" ? f.charge : null; + const w = oneBattery(hass, { power: sensor, charge }, b.energy.battery_invert) ?? 0; + if (Math.abs(w) > MIN_W) arcs.push({ key: `battery:${f.id}`, from: w > 0 ? spot : at, to: w > 0 ? at : spot, power: Math.abs(w), color: ENERGY_COLORS.battery }); + } + } + } + const feeders = new Map(); + const subSensors = new Set(); + for (const m of devices.subMeters ?? []) { + const at = meters.get(m.id); + const parent = meters.get(m.parent); + if (m.power) subSensors.add(m.power); + for (const floorId of m.floors) if (at && !feeders.has(floorId)) feeders.set(floorId, at); + const w = summary.subMeters?.find((s) => s.id === m.id)?.power ?? null; + if (!at || !parent || w === null || Math.abs(w) <= MIN_W) continue; + arcs.push({ key: `meter:${m.id}`, from: w > 0 ? parent : at, to: w > 0 ? at : parent, power: Math.abs(w), color: w > 0 ? ENERGY_COLORS.house : ENERGY_COLORS.solar }); + } + // the house feeds its consumers + const wallboxes = new Set(spotsOf(b, "wallbox").map((w) => `${w.floorId}:${w.x.toFixed(1)}:${w.z.toFixed(1)}`)); + for (const c of consumers) { + if (c.power <= MIN_W || subSensors.has(c.powerEntity)) continue; + const wallbox = c.wallbox || wallboxes.has(`${c.floorId}:${c.x.toFixed(1)}:${c.z.toFixed(1)}`); + arcs.push({ key: `use:${c.id}`, from: feeders.get(c.floorId) ?? hub, to: { floorId: c.floorId, x: c.x, z: c.z, y: 0.9 }, power: c.power, color: wallbox ? ENERGY_COLORS.wallbox : ENERGY_COLORS.house }); + } + return { arcs: arcs.map((arc) => routed(b, arc)), sparks, summary, autarky }; +} + +/** How high above its floor a cable route runs (along the skirting). */ +const CABLE_Y = 0.25; + +/** A connection whose cable can be routed: its key (as the arcs name it) and what it joins. */ +export interface EnergyConnection { + key: string; + kind: "solar" | "battery" | "inverter" | "grid" | "meter"; + /** The solar field, or the device behind a sub-meter, or the sub-meter. */ + id: string | null; +} + +/** + * The connections of the plan that can get a cable route, whether power flows on them right now or not: each solar field to + * its inverter, the battery, the inverter and the grid to the house, and in the advanced energy mode the devices behind a + * sub-meter and the sub-meters. Consumers keep their arc. + */ +export function energyConnections(b: Building): EnergyConnection[] { + const out: EnergyConnection[] = []; + const hub = houseHub(b); + if (!hub) return out; + const behind = new Set(b.floors.flatMap((f) => f.furniture).filter((m) => deviceMeter(b, m)).map((m) => m.id)); + const inverter = spotsOf(b, "inverter").find((s) => !behind.has(s.id)); + for (const f of b.settings.roof.solar ?? []) out.push({ key: `solar:${f.id}`, kind: "solar", id: f.id }); + if (spotsOf(b, "home_battery").some((s) => !behind.has(s.id))) out.push({ key: "battery", kind: "battery", id: null }); + if (inverter && (inverter.floorId !== hub.floorId || inverter.x !== hub.x || inverter.z !== hub.z)) out.push({ key: "inverter", kind: "inverter", id: null }); + if (gridSpot(b, hub)) out.push({ key: "grid", kind: "grid", id: null }); + for (const f of b.floors.flatMap((fl) => fl.furniture)) { + if (!behind.has(f.id)) continue; + if (f.type === "inverter") out.push({ key: `inverter:${f.id}`, kind: "inverter", id: f.id }); + else if (f.type === "home_battery") out.push({ key: `battery:${f.id}`, kind: "battery", id: f.id }); + } + for (const id of subMeterIds(b)) out.push({ key: `meter:${id}`, kind: "meter", id }); + return out; +} + +/** The route of a connection, if one is drawn. */ +export const routeOf = (b: Building, key: string): EnergyRoute | undefined => b.energy.routes?.find((r) => r.key === key && r.points.length > 0); + +/** + * An arc with its cable route: the route's points in the order the power runs. A route is drawn once for a connection whose + * flow can turn round (the battery charges and discharges), so it is walked from whichever end lies nearer to the arc's start. + */ +export function routed(b: Building, arc: EnergyArc): EnergyArc { + const route = routeOf(b, arc.key); + if (!route) return arc; + const via: PlanPoint[] = route.points.map((p) => ({ floorId: p.floor_id, x: p.x, z: p.z, y: CABLE_Y })); + const elevation = (id: string | null) => b.floors.find((f) => f.id === id)?.elevation ?? 0; + const apart = (p: PlanPoint, q: PlanPoint) => Math.hypot(p.x - q.x, p.z - q.z) + Math.abs(elevation(p.floorId) + p.y - elevation(q.floorId) - q.y); + const [first, last] = [via[0], via[via.length - 1]]; + if (apart(arc.from, last) + apart(arc.to, first) < apart(arc.from, first) + apart(arc.to, last)) via.reverse(); + return { ...arc, via, cable: !!route.cable }; +} diff --git a/frontend/src/live/forecast.test.ts b/frontend/src/live/forecast.test.ts new file mode 100644 index 0000000..fc36b21 --- /dev/null +++ b/frontend/src/live/forecast.test.ts @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { conditionIcon, forecastDays } from "./forecast.ts"; + +const NOW = new Date(2026, 10, 8, 15, 0).getTime(); +const at = (day: number, hour = 12) => new Date(2026, 10, day, hour).toISOString(); + +test("the forecast turns into one row per day from today, as many as asked for", () => { + const raw = [ + { datetime: at(7), condition: "sunny", temperature: 9 }, + { datetime: at(8), condition: "rainy", temperature: 11.4, templow: 4, precipitation: 3.2, precipitation_probability: 80 }, + { datetime: at(8, 18), condition: "sunny", temperature: 30 }, + { datetime: at(9), condition: "partlycloudy", temperature: "12", templow: "5" }, + { datetime: at(10), condition: "snowy", temperature: 1 }, + ]; + const days = forecastDays(raw, 2, NOW); + assert.equal(days.length, 2, "yesterday left out, two days asked for"); + assert.deepEqual(days[0], { day: new Date(2026, 10, 8).getTime(), icon: "🌦️", high: 11.4, low: 4, rain: 3.2, chance: 80 }); + assert.equal(days[1].icon, "⛅"); + assert.deepEqual([days[1].high, days[1].low, days[1].rain, days[1].chance], [12, 5, null, null], "numbers as text count, missing ones stay empty"); +}); + +test("an answer without a forecast gives no rows, and an unknown condition a cloud", () => { + assert.deepEqual(forecastDays(undefined, 5, NOW), []); + assert.deepEqual(forecastDays([{ condition: "sunny" }], 5, NOW), [], "a day without a date is left out"); + assert.equal(conditionIcon("tornado"), "☁️"); +}); diff --git a/frontend/src/live/forecast.ts b/frontend/src/live/forecast.ts new file mode 100644 index 0000000..2fed9a2 --- /dev/null +++ b/frontend/src/live/forecast.ts @@ -0,0 +1,92 @@ +// The weather forecast card: a few days from the plan's weather entity, with the high and low and the rain. Home Assistant hands +// the forecast out through the `weather.get_forecasts` action (the state attributes no longer carry it); turning its answer into +// card rows is a pure function. + +import type { HomeAssistant } from "../types.ts"; + +/** One day of the card. */ +export interface ForecastDay { + /** Midnight of the day, local time (ms). */ + day: number; + /** The weather of the day as an emoji. */ + icon: string; + high: number | null; + low: number | null; + /** Precipitation in the entity's unit (mm, in), null when not given. */ + rain: number | null; + /** Chance of precipitation in %, null when not given. */ + chance: number | null; +} + +interface RawForecast { + datetime?: string; + condition?: string; + temperature?: number | string; + templow?: number | string; + precipitation?: number | string; + precipitation_probability?: number | string; +} + +const ICONS: Record = { + "clear-night": "🌙", + cloudy: "☁️", + exceptional: "⚠️", + fog: "🌫️", + hail: "🧊", + lightning: "🌩️", + "lightning-rainy": "⛈️", + partlycloudy: "⛅", + pouring: "🌧️", + rainy: "🌦️", + snowy: "❄️", + "snowy-rainy": "🌨️", + sunny: "☀️", + windy: "💨", + "windy-variant": "💨", +}; + +/** The emoji of a Home Assistant weather condition (a cloud for one it does not know). */ +export const conditionIcon = (condition: string | undefined): string => ICONS[condition ?? ""] ?? "☁️"; + +const numberOr = (v: unknown): number | null => { + const n = typeof v === "string" ? Number.parseFloat(v) : typeof v === "number" ? v : Number.NaN; + return Number.isFinite(n) ? n : null; +}; + +const midnight = (t: number): number => { + const d = new Date(t); + d.setHours(0, 0, 0, 0); + return d.getTime(); +}; + +/** The days of the card, from today on: at most `days`, one row per day (the first entry of a day counts). */ +export function forecastDays(raw: unknown, days: number, now = Date.now()): ForecastDay[] { + const today = midnight(now); + const out: ForecastDay[] = []; + for (const f of Array.isArray(raw) ? (raw as RawForecast[]) : []) { + const at = f.datetime ? Date.parse(f.datetime) : Number.NaN; + if (!Number.isFinite(at)) continue; + const day = midnight(at); + if (day < today || out.some((d) => d.day === day)) continue; + out.push({ day, icon: conditionIcon(f.condition), high: numberOr(f.temperature), low: numberOr(f.templow), rain: numberOr(f.precipitation), chance: numberOr(f.precipitation_probability) }); + if (out.length >= days) break; + } + return out; +} + +/** Asks Home Assistant for the daily forecast of a weather entity; an entity without one gives no days. */ +export async function loadForecast(hass: HomeAssistant, entity: string): Promise { + try { + const answer = await hass.callWS<{ response?: Record }>({ + type: "call_service", + domain: "weather", + service: "get_forecasts", + service_data: { type: "daily" }, + target: { entity_id: entity }, + return_response: true, + }); + return answer?.response?.[entity]?.forecast ?? []; + } catch { + return []; + } +} diff --git a/frontend/src/live/heat-pump.test.ts b/frontend/src/live/heat-pump.test.ts new file mode 100644 index 0000000..b6d6b6a --- /dev/null +++ b/frontend/src/live/heat-pump.test.ts @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, hassOf } from "../entities/fixtures.ts"; +import { isHeatPump, readHeatPump } from "./heat-pump.ts"; + +test("a heat pump's flow, return, power, heat, COP and mode from its device", () => { + const d = { device_id: "hp" }; + const ids = ["climate.hp", "sensor.hp_vorlauftemperatur", "sensor.hp_rucklauftemperatur", "sensor.hp_heat_output", "sensor.hp_power", "sensor.hp_outdoor_temperature"]; + const hass = hassOf( + [ + entity("climate.hp", "heat", { hvac_action: "heating" }), + entity("sensor.hp_vorlauftemperatur", "34.5", { device_class: "temperature" }), + entity("sensor.hp_rucklauftemperatur", "29", { device_class: "temperature" }), + entity("sensor.hp_heat_output", "4.2", { device_class: "power", unit_of_measurement: "kW" }), + entity("sensor.hp_power", "1000", { device_class: "power", unit_of_measurement: "W" }), + entity("sensor.hp_outdoor_temperature", "3", { device_class: "temperature" }), + ], + Object.fromEntries(ids.map((id) => [id, d])), + ); + const hp = readHeatPump(hass, "climate.hp")!; + assert.deepEqual(hp, { mode: "heating", flow: 34.5, return: 29, outside: 3, power: 1000, heat: 4200, cop: 4.2 }); + assert.equal(isHeatPump("pack:nextfloor.a_smart:heat_pump_outdoor"), true); + assert.equal(isHeatPump("pack:nextfloor.kino:heat_pumpkin"), false); +}); diff --git a/frontend/src/live/heat-pump.ts b/frontend/src/live/heat-pump.ts new file mode 100644 index 0000000..5c9bc1d --- /dev/null +++ b/frontend/src/live/heat-pump.ts @@ -0,0 +1,78 @@ +/** + * NextFloor's heat pump: what it reports, found among the entities of its device (like the car and the printer): whether it heats, + * makes hot water, cools or defrosts, the flow and return temperatures, the electric power it draws, the heat it delivers and its + * COP. Works with the integrations that put these on one device (Daikin, Vaillant/myVaillant, Viessmann, Panasonic Aquarea, Nibe, + * Stiebel Eltron, Luxtronik, Mitsubishi Ecodan, ESPHome builds …). + */ +import type { HassEntity, HomeAssistant } from "../types.ts"; + +export interface HeatPumpInfo { + /** heating, water (hot water), cooling, defrost or idle. */ + mode: "heating" | "water" | "cooling" | "defrost" | "idle"; + flow: number | null; + return: number | null; + outside: number | null; + /** Electric power drawn (W). */ + power: number | null; + /** Heat delivered (W). */ + heat: number | null; + cop: number | null; +} + +const num = (st: HassEntity | undefined) => { + const n = Number(st?.state); + return st && Number.isFinite(n) ? n : null; +}; +const has = (id: string, ...words: string[]) => words.some((w) => id.includes(w)); + +/** Watts from a power sensor in W or kW. */ +function watts(st: HassEntity | undefined): number | null { + const v = num(st); + if (v === null) return null; + return String(st!.attributes.unit_of_measurement ?? "W").toLowerCase() === "kw" ? v * 1000 : v; +} + +function siblings(hass: HomeAssistant, entity: string): string[] { + const device = hass.entities?.[entity]?.device_id; + if (!device) return hass.states[entity] ? [entity] : []; + return Object.values(hass.entities ?? {}) + .filter((e) => e.device_id === device && !e.hidden) + .map((e) => e.entity_id) + .filter((id) => hass.states[id]); +} + +export function readHeatPump(hass: HomeAssistant, anchor: string | null): HeatPumpInfo | null { + if (!anchor || !hass.states[anchor]) return null; + const all = siblings(hass, anchor); + const sensors = all.filter((id) => id.startsWith("sensor.")); + const find = (match: (id: string, s: HassEntity) => boolean) => sensors.find((id) => match(id, hass.states[id])); + const temp = (s: HassEntity) => s.attributes.device_class === "temperature"; + const power = (s: HassEntity) => s.attributes.device_class === "power"; + const flowId = find((id, s) => temp(s) && has(id, "flow", "vorlauf", "supply", "leaving", "outlet") && !has(id, "target", "soll", "rate")); + const returnId = find((id, s) => temp(s) && has(id, "return", "rucklauf", "rücklauf", "ruecklauf", "inlet", "entering") && !has(id, "target", "soll")); + const outsideId = find((id, s) => temp(s) && has(id, "outdoor", "outside", "aussen", "außen", "ambient")); + const heatId = find((id, s) => power(s) && has(id, "heat", "warme", "wärme", "thermal", "output", "heizleistung")); + const powerId = find((id, s) => power(s) && id !== heatId && !has(id, "heat_output", "thermal")); + const copId = find((id) => has(id, "cop", "leistungszahl")); + if (!flowId && !returnId && !heatId && !copId) return null; + // the mode: a climate entity's action, else a status sensor's words, else heat delivered + const climate = all.map((id) => hass.states[id]).find((s) => s.entity_id.startsWith("climate.")); + const statusId = find((id, s) => !Number.isFinite(Number(s.state)) && has(id, "status", "mode", "betrieb", "operation", "state")); + const words = `${String(climate?.attributes.hvac_action ?? "")} ${String(statusId ? hass.states[statusId].state : "")}`.toLowerCase(); + const heat = watts(hass.states[heatId ?? ""]); + const mode: HeatPumpInfo["mode"] = /defrost|abtau/.test(words) + ? "defrost" + : /water|dhw|warmwasser|tank/.test(words) + ? "water" + : /cool|kühl/.test(words) + ? "cooling" + : /heat|heiz/.test(words) || (heat ?? 0) > 100 + ? "heating" + : "idle"; + const pw = watts(hass.states[powerId ?? ""]); + const cop = num(hass.states[copId ?? ""]) ?? (heat !== null && pw && pw > 50 ? Math.round((heat / pw) * 10) / 10 : null); + return { mode, flow: num(hass.states[flowId ?? ""]), return: num(hass.states[returnId ?? ""]), outside: num(hass.states[outsideId ?? ""]), power: pw, heat, cop }; +} + +/** Whether a piece of furniture is a heat pump (by its pack item's id). */ +export const isHeatPump = (type: string): boolean => /:heat_pump(_|$)/.test(type); diff --git a/frontend/src/live/media.test.ts b/frontend/src/live/media.test.ts new file mode 100644 index 0000000..847526d --- /dev/null +++ b/frontend/src/live/media.test.ts @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { HomeAssistant } from "../types.ts"; +import { appColor, isLive, mediaNow, multiroom } from "./media.ts"; + +const at = { floorId: "eg", x: 1, y: 1, z: 1 }; +function hass(states: Record }>): HomeAssistant { + return { + language: "de", + connection: {} as HomeAssistant["connection"], + callWS: async () => undefined as never, + callService: async () => undefined, + areas: {}, + devices: {}, + entities: {}, + states: Object.fromEntries(Object.entries(states).map(([id, s]) => [id, { entity_id: id, ...s }])), + }; +} + +test("players in the plan with what they play, in their app's colour", () => { + const h = hass({ + "media_player.kueche": { state: "playing", attributes: { media_title: "Song", media_artist: "Band", app_name: "Spotify", volume_level: 0.4, group_members: ["media_player.kueche", "media_player.bad"] } }, + "media_player.bad": { state: "playing", attributes: { media_title: "Song", app_name: "Spotify" } }, + "media_player.tv": { state: "paused", attributes: { app_name: "Netflix" } }, + "light.x": { state: "on", attributes: {} }, + }); + const list = mediaNow(h, [ + { entity: "media_player.kueche", name: "Küche", at }, + { entity: "media_player.kueche", name: "doppelt", at }, + { entity: "media_player.bad", name: "Bad", at }, + { entity: "media_player.tv", name: "TV", at }, + { entity: "light.x", name: "Licht", at }, + ]); + assert.deepEqual(list.map((m) => m.entity), ["media_player.kueche", "media_player.bad", "media_player.tv"]); + assert.equal(list[0].title, "Song"); + assert.equal(list[0].volume, 0.4); + assert.deepEqual(list[0].color, appColor("Spotify")); + assert.equal(list[2].playing, false); + assert.deepEqual(list[0].group, ["media_player.bad"]); + assert.equal(multiroom(list).length, 1); + assert.deepEqual(appColor("Netflix"), [229, 9, 20]); + assert.deepEqual(appColor(null), appColor("Unbekannt")); +}); + +test("a TV that is 'on' with a channel counts as live, without one it does not", () => { + assert.equal(isLive({ state: "on", attributes: { media_title: "ITV1 HD" } }), true); + assert.equal(isLive({ state: "on", attributes: { source: "HDMI 1" } }), true); + assert.equal(isLive({ state: "on", attributes: {} }), false); + assert.equal(isLive({ state: "paused", attributes: { media_title: "x" } }), false); + assert.equal(isLive({ state: "playing", attributes: {} }), true); +}); + +test("a player keeps the ring size its furniture or marker asks for, 1 when it sets none (#94)", () => { + const h = hass({ "media_player.dot": { state: "playing", attributes: {} }, "media_player.show": { state: "playing", attributes: {} } }); + const list = mediaNow(h, [ + { entity: "media_player.dot", name: "Dot", at, rings: 0 }, + { entity: "media_player.show", name: "Show", at }, + ]); + assert.deepEqual(list.map((m) => m.rings), [0, 1]); +}); diff --git a/frontend/src/live/media.ts b/frontend/src/live/media.ts new file mode 100644 index 0000000..a671711 --- /dev/null +++ b/frontend/src/live/media.ts @@ -0,0 +1,107 @@ +/** + * NextFloor's sound: the media players that play right now, where they stand in the plan, what they play, in the + * colour of their app, and which of them play together (multiroom). + */ +import type { HomeAssistant } from "../types.ts"; +import type { PlanPoint } from "../viewer/live-energy.ts"; + +export interface MediaNow { + entity: string; + name: string; + at: PlanPoint; + playing: boolean; + title: string; + artist: string; + picture: string | null; + /** 0…1, null when the player does not report it. */ + volume: number | null; + color: [number, number, number]; + app: string | null; + /** Other players playing the same (multiroom), as reported by the player. */ + group: string[]; + /** Size of its sound rings (1 = as usual, 0 = none). */ + rings: number; +} + +/** App colours: the ring around a speaker and the card's edge take the colour of what plays. */ +const APPS: [RegExp, [number, number, number]][] = [ + [/spotify/i, [30, 215, 96]], + [/netflix/i, [229, 9, 20]], + [/youtube/i, [255, 0, 51]], + [/prime|amazon/i, [0, 168, 225]], + [/disney/i, [17, 60, 207]], + [/apple ?music|itunes/i, [250, 45, 72]], + [/apple ?tv/i, [200, 200, 210]], + [/plex/i, [229, 160, 13]], + [/tidal/i, [0, 255, 255]], + [/deezer/i, [162, 56, 255]], + [/radio|tunein/i, [255, 140, 60]], +]; +const DEFAULT: [number, number, number] = [34, 211, 238]; + +export function appColor(app: string | null): [number, number, number] { + if (!app) return DEFAULT; + return APPS.find(([re]) => re.test(app))?.[1] ?? DEFAULT; +} + +/** + * Whether a player has something on its screen: it plays or is paused, or it is "on" with a title, input or app – many TV + * integrations (Samsung, LG on live TV) only ever report "on". + */ +export function showsSomething(st: { state: string; attributes: Record }): boolean { + if (st.state === "playing" || st.state === "paused") return true; + const str = (k: string) => typeof st.attributes[k] === "string" && (st.attributes[k] as string) !== ""; + return st.state === "on" && (str("media_title") || str("media_channel") || str("source") || str("app_name")); +} + +/** Whether a player is running now: playing, or a TV that is "on" with something showing (live TV, an input). */ +export const isLive = (st: { state: string; attributes: Record }): boolean => st.state === "playing" || (st.state === "on" && showsSomething(st)); + +/** Media players placed in the plan (as a device, or linked to furniture such as a TV or a speaker). */ +export function mediaNow(hass: HomeAssistant, spots: readonly { entity: string; name: string; at: PlanPoint; rings?: number | null }[]): MediaNow[] { + const out: MediaNow[] = []; + const seen = new Set(); + for (const s of spots) { + if (!s.entity.startsWith("media_player.") || seen.has(s.entity)) continue; + seen.add(s.entity); + const st = hass.states[s.entity]; + if (!st) continue; + const a = st.attributes as Record; + const str = (k: string) => (typeof a[k] === "string" ? (a[k] as string) : ""); + const app = str("app_name") || str("source") || str("app_id") || null; + const vol = typeof a.volume_level === "number" ? a.volume_level : null; + out.push({ + entity: s.entity, + name: s.name, + at: s.at, + playing: isLive(st), + title: str("media_title") || str("media_channel") || app || "", + artist: str("media_artist") || str("media_album_name") || str("media_series_title"), + picture: str("entity_picture") || null, + volume: vol, + color: appColor(app), + app, + group: Array.isArray(a.group_members) ? (a.group_members as unknown[]).filter((g): g is string => typeof g === "string" && g !== s.entity) : [], + rings: s.rings ?? 1, + }); + } + return out; +} + +/** Pairs of playing players that play together (each pair once). */ +export function multiroom(list: readonly MediaNow[]): [MediaNow, MediaNow][] { + const by = new Map(list.filter((m) => m.playing).map((m) => [m.entity, m])); + const pairs: [MediaNow, MediaNow][] = []; + const done = new Set(); + for (const m of by.values()) { + for (const g of m.group) { + const o = by.get(g); + const key = [m.entity, g].sort().join("|"); + if (o && !done.has(key)) { + done.add(key); + pairs.push([m, o]); + } + } + } + return pairs; +} diff --git a/frontend/src/live/moods.test.ts b/frontend/src/live/moods.test.ts new file mode 100644 index 0000000..ff5d661 --- /dev/null +++ b/frontend/src/live/moods.test.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity } from "../entities/fixtures.ts"; +import { carryMood, lightSetting, moodCalls } from "./moods.ts"; + +test("a mood is kept from the lights, set again, and carried over to another room", () => { + const warm = lightSetting(entity("light.a", "on", { brightness: 128, color_mode: "color_temp", color_temp_kelvin: 2700 })); + const red = lightSetting(entity("light.b", "on", { brightness: 255, color_mode: "rgb", rgb_color: [255, 0, 0] })); + const off = lightSetting(entity("light.c", "off")); + assert.deepEqual(warm, { entity: "light.a", on: true, brightness: 128, kelvin: 2700 }); + assert.deepEqual(moodCalls([warm, red, off]), [ + { service: "turn_on", data: { entity_id: "light.a", brightness: 128, color_temp_kelvin: 2700 } }, + { service: "turn_on", data: { entity_id: "light.b", brightness: 255, rgb_color: [255, 0, 0] } }, + { service: "turn_off", data: { entity_id: ["light.c"] } }, + ]); + const carried = carryMood({ lights: [warm, red] }, ["light.x", "light.y", "light.z"]); + assert.deepEqual(carried.map((s) => [s.entity, s.rgb ?? s.kelvin]), [["light.x", 2700], ["light.y", [255, 0, 0]], ["light.z", [255, 0, 0]]], "the extra light takes the brightest one"); +}); diff --git a/frontend/src/live/moods.ts b/frontend/src/live/moods.ts new file mode 100644 index 0000000..2d81ff4 --- /dev/null +++ b/frontend/src/live/moods.ts @@ -0,0 +1,41 @@ +// The light designer: a room's lights as they are now, kept as a mood of the room (in the plan), set again later, or carried over to +// another room. Pure functions from light states to service calls. + +import type { LightMood, LightSetting } from "../model.ts"; +import type { HassEntity } from "../types.ts"; + +/** How a light is now: off, or on with its brightness and colour (as `light.turn_on` takes them). */ +export function lightSetting(st: HassEntity): LightSetting { + if (st.state !== "on") return { entity: st.entity_id, on: false }; + const a = st.attributes; + const out: LightSetting = { entity: st.entity_id, on: true }; + if (typeof a.brightness === "number") out.brightness = a.brightness; + const mode = String(a.color_mode ?? ""); + if (Array.isArray(a.rgb_color) && !["color_temp", "brightness", "onoff"].includes(mode)) out.rgb = (a.rgb_color as number[]).slice(0, 3) as [number, number, number]; + else if (typeof a.color_temp_kelvin === "number") out.kelvin = a.color_temp_kelvin; + return out; +} + +/** The calls that set a mood: one turn_on per light that is on (with its brightness and colour), one turn_off for the rest. */ +export function moodCalls(settings: readonly LightSetting[]): { service: "turn_on" | "turn_off"; data: Record }[] { + const off = settings.filter((s) => !s.on).map((s) => s.entity); + const on = settings + .filter((s) => s.on) + .map((s) => ({ + service: "turn_on" as const, + data: { entity_id: s.entity, ...(s.brightness !== undefined ? { brightness: s.brightness } : {}), ...(s.rgb ? { rgb_color: s.rgb } : s.kelvin ? { color_temp_kelvin: s.kelvin } : {}) }, + })); + return [...on, ...(off.length ? [{ service: "turn_off" as const, data: { entity_id: off } }] : [])]; +} + +/** + * A mood carried over to another room's lights: they take the settings in order (the first light the first setting …); when the + * other room has more lights, the rest takes the setting of the brightest light that is on. + */ +export function carryMood(mood: Pick, targets: readonly string[]): LightSetting[] { + const lit = [...mood.lights].filter((s) => s.on).sort((a, b) => (b.brightness ?? 255) - (a.brightness ?? 255))[0]; + return targets.map((entity, i) => { + const from = mood.lights[i] ?? lit ?? { entity, on: false }; + return { ...from, entity }; + }); +} diff --git a/frontend/src/live/printer.test.ts b/frontend/src/live/printer.test.ts new file mode 100644 index 0000000..fe2367c --- /dev/null +++ b/frontend/src/live/printer.test.ts @@ -0,0 +1,36 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, hassOf } from "../entities/fixtures.ts"; +import { readPrinter } from "./printer.ts"; + +test("a Bambu printer's print: progress, time left, layers, temperatures, picture and filaments", () => { + const d = { device_id: "p1" }; + const hass = hassOf( + [ + entity("sensor.p1s_print_progress", "42", { unit_of_measurement: "%" }), + entity("sensor.p1s_print_status", "running"), + entity("sensor.p1s_remaining_time", "1.5", { unit_of_measurement: "h" }), + entity("sensor.p1s_current_layer", "120"), + entity("sensor.p1s_total_layer_count", "300"), + entity("sensor.p1s_nozzle_temperature", "220", { device_class: "temperature" }), + entity("sensor.p1s_bed_temperature", "60", { device_class: "temperature" }), + entity("sensor.p1s_task_name", "benchy"), + entity("image.p1s_cover_image", "2026-11-02", { entity_picture: "/api/image_proxy/image.p1s_cover_image" }), + entity("sensor.p1s_ams_1_tray_1", "PLA", { color: "#FF0000FF" }), + entity("sensor.p1s_ams_1_tray_2", "PETG", { color: "#00FF00FF", active: true }), + ], + Object.fromEntries(["sensor.p1s_print_progress", "sensor.p1s_print_status", "sensor.p1s_remaining_time", "sensor.p1s_current_layer", "sensor.p1s_total_layer_count", "sensor.p1s_nozzle_temperature", "sensor.p1s_bed_temperature", "sensor.p1s_task_name", "image.p1s_cover_image", "sensor.p1s_ams_1_tray_1", "sensor.p1s_ams_1_tray_2"].map((id) => [id, d])), + ); + const p = readPrinter(hass, "sensor.p1s_print_progress")!; + assert.equal(p.printing, true); + assert.equal(p.progress, 42); + assert.equal(p.remaining, 90); + assert.deepEqual([p.layer, p.layers, p.nozzle, p.bed], [120, 300, 220, 60]); + assert.equal(p.job, "benchy"); + assert.equal(p.picture, "/api/image_proxy/image.p1s_cover_image"); + assert.deepEqual(p.filaments, ["#00ff00", "#ff0000"], "the active tray first"); +}); + +test("a device without a print progress is no printer", () => { + assert.equal(readPrinter(hassOf([entity("switch.plug", "on")]), "switch.plug"), null); +}); diff --git a/frontend/src/live/printer.ts b/frontend/src/live/printer.ts new file mode 100644 index 0000000..cadc693 --- /dev/null +++ b/frontend/src/live/printer.ts @@ -0,0 +1,110 @@ +/** + * NextFloor's 3D printer: what a printer reports, found among the entities of its Home Assistant device – like the car. Works with + * the Bambu Lab, OctoPrint, Moonraker (Klipper) and PrusaLink integrations, which name their sensors alike: a print progress in %, + * the time left or the end time, the current and total layer, nozzle and bed temperatures, a cover picture of the model and, on a + * Bambu printer with an AMS, the colour of each filament tray. + */ +import type { HassEntity, HomeAssistant } from "../types.ts"; + +export interface PrinterInfo { + /** printing, paused, finished, idle, error or offline (lower case, from the print status). */ + status: string; + printing: boolean; + /** 0 … 100. */ + progress: number | null; + /** Minutes left. */ + remaining: number | null; + /** When it will be done (ms). */ + endsAt: number | null; + layer: number | null; + layers: number | null; + nozzle: number | null; + bed: number | null; + /** Name of the file or job. */ + job: string | null; + /** The model's picture (an image entity's or a camera's picture). */ + picture: string | null; + /** Filament colours ("#rrggbb"), the active one first. */ + filaments: string[]; +} + +const num = (st: HassEntity | undefined) => { + const n = Number(st?.state); + return st && Number.isFinite(n) ? n : null; +}; +const has = (id: string, ...words: string[]) => words.some((w) => id.includes(w)); + +/** All entities of the device of `entity`. */ +function siblings(hass: HomeAssistant, entity: string): string[] { + const device = hass.entities?.[entity]?.device_id; + if (!device) return hass.states[entity] ? [entity] : []; + return Object.values(hass.entities ?? {}) + .filter((e) => e.device_id === device && !e.hidden) + .map((e) => e.entity_id) + .filter((id) => hass.states[id]); +} + +/** Minutes from a duration state: minutes, hours (unit h), seconds (unit s), or "1:05:00". */ +function minutes(st: HassEntity | undefined): number | null { + if (!st) return null; + const s = String(st.state); + const m = /^(\d+):(\d{2})(?::(\d{2}))?$/.exec(s); + if (m) return Number(m[1]) * 60 + Number(m[2]); + const v = Number(s); + if (!Number.isFinite(v)) return null; + const unit = String(st.attributes.unit_of_measurement ?? "min").toLowerCase(); + return unit === "h" ? v * 60 : unit === "s" ? v / 60 : unit === "d" ? v * 1440 : v; +} + +const ACTIVE = /print|running|busy|druck/; +const STATUS_WORDS = ["print_status", "current_stage", "print_state", "printer_state", "current_state", "status", "state"]; + +export function readPrinter(hass: HomeAssistant, anchor: string | null): PrinterInfo | null { + if (!anchor || !hass.states[anchor]) return null; + const all = siblings(hass, anchor); + const sensors = all.filter((id) => id.startsWith("sensor.")); + const st = (id: string | undefined) => (id ? hass.states[id] : undefined); + const find = (match: (id: string, s: HassEntity) => boolean) => sensors.find((id) => match(id, hass.states[id])); + const unit = (s: HassEntity) => String(s.attributes.unit_of_measurement ?? ""); + const dc = (s: HassEntity) => String(s.attributes.device_class ?? ""); + + const progressId = find((id, s) => unit(s) === "%" && has(id, "progress", "fortschritt", "completion")); + if (!progressId) return null; + const statusId = STATUS_WORDS.map((w) => find((id, s) => id.endsWith(w) && !Number.isFinite(Number(s.state)))).find(Boolean); + const remainingId = find((id) => has(id, "remaining", "time_left", "restzeit", "print_time_left")); + const endId = find((id, s) => dc(s) === "timestamp" && has(id, "end", "finish", "estimated", "ende")); + const layerId = find((id) => has(id, "current_layer", "layer") && !has(id, "total")); + const layersId = find((id) => has(id, "total_layer", "layer_count", "total_layers")); + const nozzleId = find((id, s) => dc(s) === "temperature" && has(id, "nozzle", "hotend", "extruder", "tool0", "düse") && !has(id, "target")); + const bedId = find((id, s) => dc(s) === "temperature" && has(id, "bed", "heater_bed", "druckbett") && !has(id, "target")); + const jobId = find((id) => has(id, "file", "job", "task_name", "gcode", "print_name", "subtask")); + const pictureId = all.find((id) => id.startsWith("image.") && has(id, "cover", "model", "thumbnail", "preview")) ?? all.find((id) => id.startsWith("camera.") && has(id, "thumbnail", "preview")); + const statusText = String(st(statusId)?.state ?? "").toLowerCase(); + const progress = num(st(progressId)); + const printing = statusText ? ACTIVE.test(statusText) && !/finish|complete|idle|fertig/.test(statusText) : (progress ?? 0) > 0 && (progress ?? 0) < 100; + const end = st(endId) ? Date.parse(String(st(endId)!.state)) : NaN; + const remaining = minutes(st(remainingId)); + // Bambu: one sensor per AMS tray with its colour ("#RRGGBBAA"), the active one marked + const trays = all + .map((id) => hass.states[id]) + .filter((s) => typeof s?.attributes.color === "string" && /^#[0-9a-f]{6}/i.test(String(s.attributes.color)) && has(s.entity_id, "tray", "ams", "filament", "spool", "external")); + trays.sort((a, b) => Number(!!b.attributes.active) - Number(!!a.attributes.active)); + const picture = st(pictureId)?.attributes.entity_picture; + return { + status: statusText || (printing ? "printing" : "idle"), + printing, + progress, + remaining, + endsAt: Number.isFinite(end) ? end : remaining !== null && printing ? Date.now() + remaining * 60_000 : null, + layer: num(st(layerId)), + layers: num(st(layersId)), + nozzle: num(st(nozzleId)), + bed: num(st(bedId)), + job: st(jobId)?.state && !["unknown", "unavailable", ""].includes(String(st(jobId)!.state)) ? String(st(jobId)!.state) : null, + picture: typeof picture === "string" ? picture : null, + filaments: [...new Set(trays.map((s) => String(s.attributes.color).slice(0, 7).toLowerCase()))].slice(0, 8), + }; +} + +/** Whether a piece of furniture is a 3D printer (by its pack item's id). */ +export const isPrinter3d = (type: string): boolean => /printer_(3d|cube|multi|large|open|resin|enclosed)$/.test(type); diff --git a/frontend/src/live/room-climate.test.ts b/frontend/src/live/room-climate.test.ts new file mode 100644 index 0000000..104e338 --- /dev/null +++ b/frontend/src/live/room-climate.test.ts @@ -0,0 +1,31 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { airingNeed, comfortScore, isSummer, mouldRisk } from "./room-climate.ts"; + +test("mould risk grows with humidity at the cold wall", () => { + assert.equal(mouldRisk(21, 45), 0, "a dry living room"); + assert.ok(mouldRisk(18, 70)! > 80, "a cool damp bedroom"); + assert.ok(mouldRisk(21, 60)! > 20 && mouldRisk(21, 60)! < 70); + assert.equal(mouldRisk(null, 60), null); +}); + +test("when to air a room, and the season", () => { + assert.equal(airingNeed(1200, 50, 10), "co2"); + assert.equal(airingNeed(600, 68, 40), "humidity"); + assert.equal(airingNeed(600, 68, 90), "mould"); + assert.equal(airingNeed(600, 50, 0), null); + assert.equal(isSummer(new Date(2026, 6, 1)), true); + assert.equal(isSummer(new Date(2026, 0, 1)), false); + assert.equal(isSummer(new Date(2026, 0, 1), -33), true, "January is summer in Sydney"); +}); + +test("the comfort score: full in the band, one bad value always shows", () => { + assert.equal(comfortScore(21.5, 50, 600), 100); + assert.equal(comfortScore(null, null, null), null); + // 2 °C too cold costs 30 + assert.equal(comfortScore(18, null, null), 70); + // fine air and temperature but 1400 ppm CO₂: never more than 30 above the worst part + assert.equal(comfortScore(21, 50, 1400), 30); + // 25 °C is fine in summer, not in winter + assert.ok(comfortScore(25, 50, null, true)! > comfortScore(25, 50, null, false)!); +}); diff --git a/frontend/src/live/room-climate.ts b/frontend/src/live/room-climate.ts new file mode 100644 index 0000000..ef42c06 --- /dev/null +++ b/frontend/src/live/room-climate.ts @@ -0,0 +1,55 @@ +// Room climate beyond the raw values: the risk of mould on the coldest wall of a room, when to air it, and which temperature scale +// fits the season. Pure functions over °C, % and ppm. + +/** Saturation vapour pressure over water (hPa), Magnus formula. */ +const saturation = (t: number) => 6.112 * Math.exp((17.62 * t) / (243.12 + t)); + +/** How much colder than the air the coldest wall surface is (an outer wall in winter, a corner behind a wardrobe). */ +export const WALL_DROP = 4; + +/** + * Mould risk of a room, 0 … 100: the relative humidity the air would have at its coldest wall (`drop` °C colder). Mould grows from + * about 70 % at the surface and quickly above 80 %; below 65 % there is none. + */ +export function mouldRisk(temp: number | null, humidity: number | null, drop = WALL_DROP): number | null { + if (temp === null || humidity === null) return null; + const surface = Math.min(100, (humidity * saturation(temp)) / saturation(temp - drop)); + return Math.round(Math.min(100, Math.max(0, ((surface - 65) / (85 - 65)) * 100))); +} + +/** Why a room should be aired, if it should: too much CO₂, too damp, or both (null: all fine). */ +export function airingNeed(co2: number | null, humidity: number | null, risk: number | null): "co2" | "humidity" | "mould" | null { + if (risk !== null && risk >= 70) return "mould"; + if (co2 !== null && co2 >= 1000) return "co2"; + if (humidity !== null && humidity >= 65) return "humidity"; + return null; +} + +/** Summer from May to September (in the southern hemisphere the other way round): rooms may be warmer before they count as hot. */ +export function isSummer(now = new Date(), latitude = 50): boolean { + const m = now.getMonth(); + const north = m >= 4 && m <= 8; + return latitude < 0 ? !north : north; +} + +/** + * How comfortable a room is, 0 … 100, from what its sensors say: the temperature in its band (20–23 °C, 22–26 °C in summer), the + * humidity between 40 and 60 %, CO₂ up to 800 ppm. The average of the parts that are known, but never more than 30 above the worst, + * so one bad value always shows. Null without any reading. + */ +export function comfortScore(temp: number | null, humidity: number | null, co2: number | null, summer = false): number | null { + const parts: number[] = []; + if (temp !== null) { + const [lo, hi] = summer ? [22, 26] : [20, 23]; + const off = temp < lo ? lo - temp : temp > hi ? temp - hi : 0; + parts.push(Math.max(0, 100 - off * 15)); + } + if (humidity !== null) { + const off = humidity < 40 ? 40 - humidity : humidity > 60 ? humidity - 60 : 0; + parts.push(Math.max(0, 100 - off * 4)); + } + if (co2 !== null) parts.push(Math.max(0, Math.min(100, 100 - ((co2 - 800) / 600) * 100))); + if (!parts.length) return null; + const mean = parts.reduce((a, b) => a + b, 0) / parts.length; + return Math.round(Math.min(mean, Math.min(...parts) + 30)); +} diff --git a/frontend/src/live/room-energy.test.ts b/frontend/src/live/room-energy.test.ts new file mode 100644 index 0000000..8965c13 --- /dev/null +++ b/frontend/src/live/room-energy.test.ts @@ -0,0 +1,31 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { energyCost, monthStart, roomEnergyFromStats } from "./room-energy.ts"; +import { dayStart } from "./week-bars.ts"; + +test("today and the month come from the daily mean power of the room's sensors", () => { + const now = new Date(2026, 10, 3, 12, 0).getTime(); + const iso = (t: number) => new Date(t).toISOString(); + const stats = { + "sensor.tv": [ + { start: iso(dayStart(now, 2)), mean: 100 }, + { start: iso(dayStart(now, 1)), mean: 50 }, + { start: iso(dayStart(now)), mean: 200 }, + ], + "sensor.lamp": [{ start: iso(dayStart(now)), mean: -5 }], + }; + const e = roomEnergyFromStats(stats, ["sensor.tv", "sensor.lamp"], now)!; + // today: 200 W for the 12 hours gone; the month: 2.4 + 1.2 + 2.4 kWh + assert.equal(e.today, 2.4); + assert.equal(e.month, 6); + assert.equal(roomEnergyFromStats({}, ["sensor.tv"], now), null); + assert.equal(new Date(monthStart(now)).getDate(), 1); +}); + +test("the cost follows the tariff's unit", () => { + assert.deepEqual(energyCost(10, { value: 0.31, unit: "EUR/kWh" }), { value: 3.1, currency: "€" }); + assert.deepEqual(energyCost(10, { value: 31, unit: "ct/kWh" }), { value: 3.1, currency: "€" }); + assert.deepEqual(energyCost(10, { value: 0.25, unit: "CHF/kWh" }), { value: 2.5, currency: "CHF" }); + assert.equal(energyCost(10, { value: 5, unit: "W" }), null); + assert.equal(energyCost(10, null), null); +}); diff --git a/frontend/src/live/room-energy.ts b/frontend/src/live/room-energy.ts new file mode 100644 index 0000000..9e0cb48 --- /dev/null +++ b/frontend/src/live/room-energy.ts @@ -0,0 +1,66 @@ +// What a room used today and this month: from Home Assistant's long-term statistics of the power sensors of its devices (their daily +// mean × the hours of the day), one small request per room panel opening; and what it cost with the house's tariff. + +import type { HomeAssistant } from "../types.ts"; +import { dayStart } from "./week-bars.ts"; + +export interface RoomEnergy { + /** kWh used today so far, and since the first of the month. */ + today: number; + month: number; +} + +type Stats = Record; + +const DAY = 86_400_000; +const HOUR = 3_600_000; + +/** Midnight of the first of the month `now` falls in. */ +export function monthStart(now: number): number { + const d = new Date(dayStart(now)); + d.setDate(1); + return d.getTime(); +} + +/** kWh today and this month from the daily mean power (W) of the sensors; today counts the hours gone so far. Null without data. */ +export function roomEnergyFromStats(stats: Stats, ids: readonly string[], now: number): RoomEnergy | null { + const today = dayStart(now); + let [day, month, any] = [0, 0, false]; + for (const id of ids) { + for (const row of stats[id] ?? []) { + if (typeof row.mean !== "number") continue; + const start = new Date(row.start).getTime(); + const hours = Math.min(24, Math.max(0, (Math.min(now, start + DAY) - start) / HOUR)); + const kwh = (Math.max(0, row.mean) * hours) / 1000; + month += kwh; + if (Math.abs(start - today) < 3 * HOUR) day += kwh; + any = true; + } + } + const round = (v: number) => Math.round(v * 100) / 100; + return any ? { today: round(day), month: round(month) } : null; +} + +export async function loadRoomEnergy(hass: HomeAssistant, ids: readonly string[], now = Date.now()): Promise { + if (!ids.length) return null; + const stats = await hass.callWS({ + type: "recorder/statistics_during_period", + start_time: new Date(monthStart(now)).toISOString(), + end_time: new Date(now).toISOString(), + statistic_ids: [...ids], + period: "day", + types: ["mean"], + units: { power: "W" }, + }); + return roomEnergyFromStats(stats, ids, now); +} + +/** The cost of some kWh with a tariff state ("0.31" in "EUR/kWh", "ct/kWh" …); null when the tariff is not per kWh. */ +export function energyCost(kwh: number, tariff: { value: number; unit: string } | null): { value: number; currency: string } | null { + if (!tariff || !Number.isFinite(tariff.value)) return null; + const m = /^\s*([^/\s]+)\s*\/\s*kWh\s*$/i.exec(tariff.unit); + if (!m) return null; + const cents = /^(ct|cent|cents|c)$/i.test(m[1]); + const currency = cents || /^eur$/i.test(m[1]) ? "€" : m[1]; + return { value: Math.round(kwh * tariff.value * (cents ? 1 : 100)) / 100, currency }; +} diff --git a/frontend/src/live/sky-weather.test.ts b/frontend/src/live/sky-weather.test.ts new file mode 100644 index 0000000..943184f --- /dev/null +++ b/frontend/src/live/sky-weather.test.ts @@ -0,0 +1,82 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { HomeAssistant } from "../types.ts"; +import { bearing, chosenEffects, readSkyWeather, windKmh, withDensity } from "./sky-weather.ts"; + +function hassWith(state: string, attributes: Record = {}): HomeAssistant { + return { + language: "de", + connection: {} as HomeAssistant["connection"], + callWS: async () => undefined as never, + callService: async () => undefined, + areas: {}, + devices: {}, + entities: {}, + states: { "weather.home": { entity_id: "weather.home", state, attributes } }, + }; +} + +test("each condition has a look; missing or unknown states give no weather", () => { + const rain = readSkyWeather(hassWith("pouring"), "weather.home")!; + assert.equal(rain.rain, 1); + assert.ok(rain.cloud >= 0.9); + assert.equal(readSkyWeather(hassWith("lightning-rainy"), "weather.home")!.lightning, true); + assert.equal(readSkyWeather(hassWith("hail"), "weather.home")!.hail > 0, true); + assert.equal(readSkyWeather(hassWith("unavailable"), "weather.home"), null); + assert.equal(readSkyWeather(hassWith("sunny"), null), null); + assert.equal(readSkyWeather(hassWith("something-new"), "weather.home"), null); +}); + +test("cloud coverage, wind speed, gusts and bearing refine the look", () => { + const w = readSkyWeather(hassWith("partlycloudy", { cloud_coverage: 70, wind_speed: 10, wind_speed_unit: "m/s", wind_bearing: 225 }), "weather.home")!; + assert.equal(w.cloud, 0.7); + assert.ok(Math.abs(w.wind - 36 / 70) < 1e-9); + assert.equal(w.windFrom, 225); + const gusty = readSkyWeather(hassWith("sunny", { wind_speed: 5, wind_gust_speed: 90 }), "weather.home")!; + assert.ok(gusty.wind >= 0.9); + // rain under a clear sky report still comes with clouds + assert.ok(readSkyWeather(hassWith("rainy", { cloud_coverage: 10 }), "weather.home")!.cloud >= 0.6); +}); + +test("rain below freezing becomes sleet, heavy precipitation more streaks", () => { + const sleet = readSkyWeather(hassWith("rainy", { temperature: -1 }), "weather.home")!; + assert.ok(sleet.snow > 0 && sleet.rain < 0.5); + const fahrenheit = readSkyWeather(hassWith("rainy", { temperature: 30, temperature_unit: "°F" }), "weather.home")!; + assert.ok(fahrenheit.snow > 0); + assert.equal(readSkyWeather(hassWith("rainy", { temperature: 12 }), "weather.home")!.snow, 0); + assert.equal(readSkyWeather(hassWith("rainy", { precipitation: 8 }), "weather.home")!.rain, 1); +}); + +test("units and compass bearings", () => { + assert.equal(windKmh(10, "m/s"), 36); + assert.ok(Math.abs(windKmh(10, "kn") - 18.52) < 1e-9); + assert.equal(windKmh(20, "km/h"), 20); + assert.equal(bearing("NW"), 315); + assert.equal(bearing("SO"), 135); + assert.equal(bearing(-90), 270); + assert.equal(bearing("x"), null); +}); + +test("only the chosen effects stay", () => { + const storm = readSkyWeather(hassWith("lightning-rainy"), "weather.home")!; + const only = chosenEffects({ ...storm, fog: 0.5 }, ["clouds"]); + assert.equal(only.rain, 0); + assert.equal(only.lightning, false); + assert.equal(only.fog, 0); + assert.ok(only.cloud > 0); + assert.equal(chosenEffects({ ...storm, fog: 0.5 }, null).fog, 0); +}); + +test("the density thins out rain, hail and snow, and leaves clouds and lightning alone", () => { + const storm = readSkyWeather(hassWith("lightning-rainy"), "weather.home")!; + const thin = withDensity(storm, 0.3); + assert.equal(thin.rain, storm.rain * 0.3); + assert.equal(thin.snow, storm.snow * 0.3); + assert.equal(thin.cloud, storm.cloud); + assert.equal(thin.lightning, storm.lightning); + assert.equal(withDensity(storm, 1), storm); + assert.equal(withDensity(storm, undefined), storm); + // out of range: never less than a tenth, never more than the weather says + assert.equal(withDensity(storm, 0).rain, storm.rain * 0.1); + assert.equal(withDensity(storm, 5), storm); +}); diff --git a/frontend/src/live/sky-weather.ts b/frontend/src/live/sky-weather.ts new file mode 100644 index 0000000..8f47208 --- /dev/null +++ b/frontend/src/live/sky-weather.ts @@ -0,0 +1,121 @@ +/** + * Reads a Home Assistant `weather.*` entity into what NextFloor's weather layer draws (see viewer/live-weather.ts). + * + * The condition gives the kind of weather; the entity's attributes refine it where they exist: cloud coverage, + * wind speed and bearing (rain and snow fall at an angle along the real wind), precipitation (more rain, more + * streaks) and temperature (rain below freezing turns into sleet). + */ +import type { WeatherEffect } from "../model.ts"; +import type { SkyWeather } from "../viewer/live-weather.ts"; +import type { HomeAssistant } from "../types.ts"; + +type Base = Partial>; + +/** What each of Home Assistant's conditions looks like before the attributes refine it. */ +const LOOK: Record = { + sunny: { cloud: 0 }, + "clear-night": { cloud: 0 }, + partlycloudy: { cloud: 0.4 }, + cloudy: { cloud: 0.85 }, + fog: { fog: 0.9, cloud: 0.5 }, + rainy: { rain: 0.5, cloud: 0.8 }, + pouring: { rain: 1, cloud: 1, wind: 0.3 }, + "lightning-rainy": { rain: 0.75, cloud: 1, lightning: true, wind: 0.35 }, + lightning: { cloud: 0.85, lightning: true }, + hail: { hail: 0.8, rain: 0.3, cloud: 1 }, + snowy: { snow: 0.7, cloud: 0.85 }, + "snowy-rainy": { snow: 0.45, rain: 0.3, cloud: 0.95 }, + windy: { wind: 0.7, cloud: 0.25 }, + "windy-variant": { wind: 0.7, cloud: 0.65 }, + exceptional: { cloud: 0.6, wind: 0.5 }, +}; + +const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v)) ? Number(v) : null); +const clamp = (v: number) => Math.min(1, Math.max(0, v)); + +/** Wind speed in km/h from the entity's value and unit. */ +export function windKmh(speed: number, unit: unknown): number { + switch (unit) { + case "m/s": + return speed * 3.6; + case "mph": + return speed * 1.609; + case "kn": + return speed * 1.852; + case "ft/s": + return speed * 1.097; + default: + return speed; + } +} + +/** A wind bearing: degrees, or a compass point such as "NW". */ +export function bearing(v: unknown): number | null { + const n = num(v); + if (n !== null) return ((n % 360) + 360) % 360; + if (typeof v !== "string") return null; + const points = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]; + const i = points.indexOf(v.trim().toUpperCase().replace("O", "E")); + return i < 0 ? null : i * 22.5; +} + +/** The weather to draw from an entity, or null when it is missing or reports nothing usable. */ +export function readSkyWeather(hass: HomeAssistant, entity: string | null): SkyWeather | null { + const st = entity ? hass.states[entity] : undefined; + if (!st || st.state === "unavailable" || st.state === "unknown") return null; + const look = LOOK[st.state]; + if (!look) return null; + const a = st.attributes as Record; + const w: SkyWeather = { + rain: look.rain ?? 0, + snow: look.snow ?? 0, + hail: look.hail ?? 0, + fog: look.fog ?? 0, + cloud: look.cloud ?? 0, + wind: look.wind ?? 0, + windFrom: bearing(a.wind_bearing), + lightning: look.lightning ?? false, + }; + const coverage = num(a.cloud_coverage); + if (coverage !== null) w.cloud = Math.max(clamp(coverage / 100), w.rain || w.snow ? 0.6 : 0); + const speed = num(a.wind_speed); + if (speed !== null) w.wind = Math.max(w.wind, clamp(windKmh(speed, a.wind_speed_unit) / 70)); + const gust = num(a.wind_gust_speed); + if (gust !== null) w.wind = Math.max(w.wind, clamp(windKmh(gust, a.wind_speed_unit) / 100)); + // more rain per hour, denser streaks (only when the entity reports it for now) + const precip = num(a.precipitation); + if (precip !== null && precip > 0 && (w.rain > 0 || w.snow > 0)) { + const strength = clamp(0.25 + precip / 8); + if (w.rain > 0) w.rain = Math.max(w.rain * 0.6, strength); + if (w.snow > 0) w.snow = Math.max(w.snow * 0.6, strength); + } + // below freezing, rain comes down as sleet: some of it snow + const temp = num(a.temperature); + const unit = a.temperature_unit ?? hass.config?.unit_system?.temperature; + const celsius = temp === null ? null : unit === "°F" ? ((temp - 32) * 5) / 9 : temp; + if (celsius !== null && celsius <= 0.5 && w.rain > 0 && w.snow === 0) { + w.snow = w.rain * 0.6; + w.rain *= 0.4; + } + return w; +} + +/** Fewer drops and flakes: rain, hail and snow scaled by a density (0.1 … 1); clouds, fog and lightning stay. */ +export function withDensity(w: SkyWeather, density: number | null | undefined): SkyWeather { + const d = density == null || !Number.isFinite(density) ? 1 : Math.min(1, Math.max(0.1, density)); + return d === 1 ? w : { ...w, rain: w.rain * d, hail: w.hail * d, snow: w.snow * d }; +} + +/** Keeps only the effects chosen in the settings (null = the default set: all but fog). */ +export function chosenEffects(w: SkyWeather, effects: readonly WeatherEffect[] | null | undefined): SkyWeather { + const on = new Set(effects ?? ["rain", "snow", "clouds", "lightning", "sky"]); + return { + ...w, + rain: on.has("rain") ? w.rain : 0, + hail: on.has("rain") ? w.hail : 0, + snow: on.has("snow") ? w.snow : 0, + fog: on.has("fog") ? w.fog : 0, + cloud: on.has("clouds") ? w.cloud : 0, + lightning: on.has("lightning") && w.lightning, + }; +} diff --git a/frontend/src/live/sun-hours.test.ts b/frontend/src/live/sun-hours.test.ts new file mode 100644 index 0000000..b6c3a2c --- /dev/null +++ b/frontend/src/live/sun-hours.test.ts @@ -0,0 +1,62 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, floorWith, opening } from "../entities/fixtures.ts"; +import { emptyBuilding } from "../model.ts"; +import { compassOf, roomSun, roomSunYear, sunnyWindowsNow } from "./sun-hours.ts"; + +const BERLIN = { latitude: 52.5, longitude: 13.4, zone: "Europe/Berlin" }; + +function house(edge: number, north = 0) { + const room = box("r", 0, 0, 4, 3); + const floor = { ...floorWith([room]), openings: [opening("w", "r", "window", { edge, offset: edge % 2 ? 1.5 : 2 })] }; + const b = { ...emptyBuilding(), floors: [floor] }; + b.settings = { ...b.settings, north }; + return { b, floor, room }; +} + +test("a south window gets the most sun in winter, a north window only summer mornings and evenings", () => { + const south = house(2); + const north = house(0); + const winter = new Date("2026-12-21T12:00:00Z"); + const summer = new Date("2026-06-21T12:00:00Z"); + const s = roomSun(south.b, south.floor, south.room, BERLIN, winter); + assert.deepEqual(s.facing, ["S"]); + assert.ok(s.hours > 6 && s.hours < 8.5, `south in December: ${s.hours}`); + assert.equal(roomSun(north.b, north.floor, north.room, BERLIN, winter).hours, 0); + const n = roomSun(north.b, north.floor, north.room, BERLIN, summer); + assert.ok(n.hours > 1 && n.hours < 6, `north in June: ${n.hours}`); + // in June the sun stands north of east and west in the morning and evening: about 8½ hours on the south side + assert.ok(roomSun(south.b, south.floor, south.room, BERLIN, summer).hours > 8); +}); + +test("the plan's north turns the compass", () => { + assert.equal(compassOf([0, -1], 0), "N"); + assert.equal(compassOf([1, 0], 0), "E"); + // north pointing to the right of the plan: "up" is west + assert.equal(compassOf([0, -1], 90), "W"); + const turned = house(0, 180); + assert.deepEqual(roomSun(turned.b, turned.floor, turned.room, BERLIN).facing, ["S"]); +}); + +test("a room without outside windows has no sun", () => { + const { b, floor, room } = house(0); + floor.openings = []; + assert.deepEqual(roomSun(b, floor, room, BERLIN), { hours: 0, facing: [] }); +}); + +test("over the year a north room gets sun only around midsummer", () => { + const { b, floor, room } = house(0); + const year = roomSunYear(b, floor, room, BERLIN, 2026); + assert.equal(year.length, 12); + assert.equal(year[11], 0); + assert.ok(year[5] > year[2] && year[5] > year[8]); +}); + +test("the sun stands on a south window at noon, never on a north one, and on none at night", () => { + const noon = new Date("2026-07-15T11:00:00Z"); + const south = house(2); + const north = house(0); + assert.deepEqual(sunnyWindowsNow(south.b, south.floor, south.room, BERLIN, noon).map((o) => o.id), ["w"]); + assert.deepEqual(sunnyWindowsNow(north.b, north.floor, north.room, BERLIN, noon), []); + assert.deepEqual(sunnyWindowsNow(south.b, south.floor, south.room, BERLIN, new Date("2026-07-15T23:00:00Z")), []); +}); diff --git a/frontend/src/live/sun-hours.ts b/frontend/src/live/sun-hours.ts new file mode 100644 index 0000000..829ac29 --- /dev/null +++ b/frontend/src/live/sun-hours.ts @@ -0,0 +1,111 @@ +// Sun in the rooms: how many hours of a day the sun shines in through a room's outside windows, worked out from the plan, its +// compass and the sun's path at the home's place. Neighbours, trees and the overhang of the roof are not counted. + +import { generateWalls, locateOpening, openingHost, type Wall } from "../geometry/walls.ts"; +import type { Building, Floor, Opening, Room } from "../model.ts"; +import { sunPosition, todayAt } from "../sun-position.ts"; + +const DEG = Math.PI / 180; +/** The sun has to stand this high to shine in (degrees), and this square onto the window (cosine of the angle). */ +const MIN_ELEVATION = 3; +const MIN_FACING = 0.1; +const STEP_HOURS = 1 / 6; + +export interface RoomSun { + /** Hours of sun through at least one window. */ + hours: number; + /** The compass directions the room's outside windows look to ("S", "SW" …), each once. */ + facing: string[]; +} + +/** The horizontal direction towards the sun in plan coordinates (x right, z down, "up" is -z), like the 3D view. */ +const toSun = (azimuth: number, north: number): [number, number] => [Math.sin((north + azimuth) * DEG), -Math.cos((north + azimuth) * DEG)]; + +const COMPASS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]; + +/** The outward directions of a room's windows in outside walls, in plan coordinates. */ +export function windowNormals(floor: Floor, room: Room, walls: readonly Wall[]): [number, number][] { + return outsideWindows(floor, room, walls).map((w) => w.normal); +} + +/** A room's windows (and glass doors) in outside walls, each with the direction it looks to. */ +export function outsideWindows(floor: Floor, room: Room, walls: readonly Wall[]): { opening: Opening; normal: [number, number] }[] { + const out: { opening: Opening; normal: [number, number] }[] = []; + for (const o of floor.openings) { + if (o.room_id !== room.id || o.type === "garage") continue; + const host = openingHost(o, floor.rooms, floor.walls ?? []); + const at = host ? locateOpening(walls, o, host) : null; + if (!at || !at.wall.exterior) continue; + const { wall } = at; + const len = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]); + if (len < 1e-6) continue; + // the room lies on the wall's left (its normal (-dz, dx)); the window looks the other way + const left: [number, number] = [-(wall.b[1] - wall.a[1]) / len, (wall.b[0] - wall.a[0]) / len]; + const intoRoom = wall.roomLeft === room.id ? left : ([-left[0], -left[1]] as [number, number]); + out.push({ opening: o, normal: [-intoRoom[0], -intoRoom[1]] }); + } + return out; +} + +/** The compass word of an outward direction in the plan, with the plan's north. */ +export function compassOf(dir: readonly [number, number], north: number): string { + // plan "up" is -z; the bearing is clockwise from the plan's up, then turned by north + const bearing = (((Math.atan2(dir[0], -dir[1]) / DEG - north) % 360) + 360) % 360; + return COMPASS[Math.round(bearing / 45) % 8]; +} + +const wallMemo = new WeakMap(); +function wallsOf(b: Building, floor: Floor): Wall[] { + let walls = wallMemo.get(floor); + if (!walls) { + walls = generateWalls(floor.rooms, { exterior: b.settings.wall_exterior, interior: b.settings.wall_interior }, floor.walls ?? []).walls; + wallMemo.set(floor, walls); + } + return walls; +} + +/** Results per floor object (a new plan state is a new object) and day: the room panel and the heat map ask on every state change. */ +const sunMemo = new WeakMap>(); + +/** Hours of sun of a room on the day of `date` at the home's place (latitude, longitude, time zone). */ +export function roomSun(b: Building, floor: Floor, room: Room, place: { latitude: number; longitude: number; zone?: string | null }, date = new Date()): RoomSun { + const key = `${room.id}|${date.toISOString().slice(0, 10)}|${b.settings.north ?? 0}|${place.latitude},${place.longitude},${place.zone ?? ""}`; + let known = sunMemo.get(floor); + if (!known) sunMemo.set(floor, (known = new Map())); + const hit = known.get(key); + if (hit) return hit; + const result = computeRoomSun(b, floor, room, place, date); + known.set(key, result); + return result; +} + +function computeRoomSun(b: Building, floor: Floor, room: Room, place: { latitude: number; longitude: number; zone?: string | null }, date: Date): RoomSun { + const north = b.settings.north ?? 0; + const normals = windowNormals(floor, room, wallsOf(b, floor)); + const facing = [...new Set(normals.map((n) => compassOf(n, north)))]; + if (!normals.length) return { hours: 0, facing }; + let steps = 0; + for (let h = STEP_HOURS / 2; h < 24; h += STEP_HOURS) { + const sun = sunPosition(todayAt(h, place.zone, date), place.latitude, place.longitude); + if (sun.elevation < MIN_ELEVATION) continue; + const s = toSun(sun.azimuth, north); + // the cosine of the angle between the window's outward direction and the sun, on the ground plane + if (normals.some((n) => n[0] * s[0] + n[1] * s[1] > MIN_FACING)) steps++; + } + return { hours: Math.round(steps * STEP_HOURS * 10) / 10, facing }; +} + +/** Hours of sun of a room on the 15th of every month of `year` (January first), for the curve over the year. */ +export function roomSunYear(b: Building, floor: Floor, room: Room, place: { latitude: number; longitude: number; zone?: string | null }, year = new Date().getFullYear()): number[] { + return Array.from({ length: 12 }, (_, month) => roomSun(b, floor, room, place, new Date(Date.UTC(year, month, 15, 12))).hours); +} + +/** The room's outside windows the sun shines on right now (none at night or with the sun low). */ +export function sunnyWindowsNow(b: Building, floor: Floor, room: Room, place: { latitude: number; longitude: number }, now = new Date()): Opening[] { + const sun = sunPosition(now, place.latitude, place.longitude); + if (sun.elevation < MIN_ELEVATION) return []; + const s = toSun(sun.azimuth, b.settings.north ?? 0); + return outsideWindows(floor, room, wallsOf(b, floor)) + .filter((w) => w.normal[0] * s[0] + w.normal[1] * s[1] > MIN_FACING) + .map((w) => w.opening); +} diff --git a/frontend/src/live/time-travel.test.ts b/frontend/src/live/time-travel.test.ts new file mode 100644 index 0000000..e7aa07f --- /dev/null +++ b/frontend/src/live/time-travel.test.ts @@ -0,0 +1,48 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { HomeAssistant } from "../types.ts"; +import { changeAt, changeMoments, hassAt, parseHistory, replayable } from "./time-travel.ts"; + +const raw = { + "light.kitchen": [ + { s: "off", a: { friendly_name: "Kitchen" }, lu: 1000 }, + { s: "on", a: { friendly_name: "Kitchen", brightness: 200 }, lu: 1100 }, + { s: "off", lu: 1200 }, + ], + "binary_sensor.door": [{ s: "off", a: { device_class: "door" }, lu: 900 }, { s: "on", lu: 1150 }], +}; + +test("the recorder's answer becomes sorted changes; attributes carry on until they change", () => { + const h = parseHistory(raw); + const kitchen = h.get("light.kitchen")!; + assert.deepEqual(kitchen.map((c) => [c.t, c.state]), [[1_000_000, "off"], [1_100_000, "on"], [1_200_000, "off"]]); + assert.equal(kitchen[2].attributes.brightness, 200); +}); + +test("the state at a moment is the last change before it", () => { + const kitchen = parseHistory(raw).get("light.kitchen")!; + assert.equal(changeAt(kitchen, 999_999), null); + assert.equal(changeAt(kitchen, 1_150_000)?.state, "on"); + assert.equal(changeAt(kitchen, 5_000_000)?.state, "off"); +}); + +test("hass at a moment shows the replayed entities as they were and leaves the rest alone", () => { + const hass = { states: { "light.kitchen": { entity_id: "light.kitchen", state: "off", attributes: { friendly_name: "Kitchen", icon: "mdi:x" } }, "sensor.t": { entity_id: "sensor.t", state: "21", attributes: {} } } } as unknown as HomeAssistant; + const then = hassAt(hass, parseHistory(raw), 1_150_000); + assert.equal(then.states["light.kitchen"].state, "on"); + assert.equal(then.states["light.kitchen"].attributes.icon, "mdi:x", "attributes the history lacks stay"); + assert.equal(then.states["binary_sensor.door"].state, "on"); + assert.equal(then.states["sensor.t"].state, "21"); + assert.equal(hass.states["light.kitchen"].state, "off", "the live states are not touched"); +}); + +test("the timeline marks every change of state inside the span", () => { + const h = parseHistory(raw); + assert.deepEqual(changeMoments(h, 0, 2_000_000), [1_100_000, 1_150_000, 1_200_000]); + assert.deepEqual(changeMoments(h, 1_120_000, 2_000_000), [1_150_000, 1_200_000]); + assert.equal(changeMoments(h, 0, 2_000_000, 2).length, 2); +}); + +test("only what switches, opens or moves is replayed", () => { + assert.deepEqual(replayable(["light.a", "sensor.temp", "cover.b", "light.a", "binary_sensor.c", "weather.home"]), ["light.a", "cover.b", "binary_sensor.c"]); +}); diff --git a/frontend/src/live/time-travel.ts b/frontend/src/live/time-travel.ts new file mode 100644 index 0000000..3eb14a4 --- /dev/null +++ b/frontend/src/live/time-travel.ts @@ -0,0 +1,102 @@ +// Time travel: the house as it was at an earlier moment, from Home Assistant's recorder. The history of the entities the 3D view shows +// is loaded once for the chosen span; at any moment the view is fed a copy of hass whose states are the ones of that moment, so +// lamps, blinds, doors and robots replay with the same code that shows them live. + +import type { HassEntity, HomeAssistant } from "../types.ts"; + +/** The kinds of entities worth replaying: what switches, moves or opens. Sensors with values change too often to be useful. */ +const REPLAY = /^(light|switch|cover|binary_sensor|lock|media_player|vacuum|fan|climate|lawn_mower|input_boolean|person|device_tracker|alarm_control_panel)\./; +const MAX_ENTITIES = 200; + +export interface Change { + /** Milliseconds since 1970. */ + t: number; + state: string; + attributes: Record; +} + +export type History = Map; + +interface CompressedState { + s: string; + a?: Record; + /** Last changed / last updated, in seconds since 1970. */ + lc?: number; + lu: number; +} + +/** The entities of the view that are replayed. */ +export const replayable = (ids: Iterable): string[] => [...new Set([...ids].filter((id) => REPLAY.test(id)))].slice(0, MAX_ENTITIES); + +/** Turns the recorder's compressed answer into sorted changes per entity; attributes carry on until they change. */ +export function parseHistory(raw: Record): History { + const out: History = new Map(); + for (const [id, list] of Object.entries(raw)) { + let attributes: Record = {}; + const changes: Change[] = []; + for (const row of list) { + if (row.a) attributes = row.a; + changes.push({ t: Math.round((row.lu ?? row.lc ?? 0) * 1000), state: row.s, attributes }); + } + changes.sort((p, q) => p.t - q.t); + out.set(id, changes); + } + return out; +} + +/** Loads the history of the replayed entities between two moments (ms). */ +export async function loadHistory(hass: HomeAssistant, ids: readonly string[], from: number, to: number, minimal = false): Promise { + if (ids.length === 0) return new Map(); + const raw = await hass.callWS>({ + type: "history/history_during_period", + start_time: new Date(from).toISOString(), + end_time: new Date(to).toISOString(), + entity_ids: ids, + include_start_time_state: true, + significant_changes_only: false, + // values only (day curves) or every attribute (time travel replays colours and positions) + minimal_response: minimal, + no_attributes: minimal, + }); + return parseHistory(raw); +} + +/** The change in effect at moment t: the last one at or before it (null before the first). */ +export function changeAt(changes: readonly Change[], t: number): Change | null { + let [lo, hi] = [0, changes.length - 1]; + let found: Change | null = null; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + if (changes[mid].t <= t) { + found = changes[mid]; + lo = mid + 1; + } else hi = mid - 1; + } + return found; +} + +/** A copy of hass whose replayed entities show their state at moment t; everything else stays as it is now. */ +export function hassAt(hass: HomeAssistant, history: History, t: number): HomeAssistant { + const states: Record = { ...hass.states }; + for (const [id, changes] of history) { + const c = changeAt(changes, t); + if (!c) continue; + const now = hass.states[id]; + states[id] = { ...(now ?? { entity_id: id }), entity_id: id, state: c.state, attributes: { ...(now?.attributes ?? {}), ...c.attributes } } as HassEntity; + } + return { ...hass, states }; +} + +/** The moments something switched, opened or moved, for the marks on the timeline (at most `max`, spread evenly). */ +export function changeMoments(history: History, from: number, to: number, max = 400): number[] { + const moments: number[] = []; + for (const changes of history.values()) { + for (let i = 1; i < changes.length; i++) { + if (changes[i].state !== changes[i - 1].state && changes[i].t >= from && changes[i].t <= to) moments.push(changes[i].t); + } + } + moments.sort((a, b) => a - b); + if (moments.length <= max) return moments; + const step = moments.length / max; + return Array.from({ length: max }, (_, i) => moments[Math.floor(i * step)]); +} diff --git a/frontend/src/live/today.test.ts b/frontend/src/live/today.test.ts new file mode 100644 index 0000000..8a2e46e --- /dev/null +++ b/frontend/src/live/today.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { agenda, sortDay } from "./today.ts"; + +test("the day's events as lines: times, all-day ones first, past ones marked", () => { + const now = new Date(2026, 10, 3, 12, 0).getTime(); + const at = (h: number, m = 0) => new Date(2026, 10, 3, h, m).toISOString(); + const items = sortDay( + agenda( + [ + { summary: "Zahnarzt", start: { dateTime: at(15, 30) }, end: { dateTime: at(16) } }, + { summary: "Frühstück", start: { dateTime: at(8) }, end: { dateTime: at(9) } }, + { summary: "Geburtstag Oma", start: { date: "2026-11-03" }, end: { date: "2026-11-04" } }, + { summary: "", start: { dateTime: at(10) } }, + ], + "Familie", + now, + ), + ); + assert.deepEqual(items.map((i) => [i.time, i.title, !!i.past]), [["", "Geburtstag Oma", false], ["08:00", "Frühstück", true], ["15:30", "Zahnarzt", false]]); +}); + +test("over several days each line knows its day, and the days come in order (#84)", () => { + const now = new Date(2026, 10, 8, 10, 0).getTime(); + const iso = (d: number, h: number) => new Date(2026, 10, d, h).toISOString(); + const items = sortDay( + agenda( + [ + { summary: "Dentist", start: iso(9, 9), end: iso(9, 10) }, + { summary: "Holiday", start: { date: "2026-11-10" } }, + { summary: "Lunch", start: iso(8, 12), end: iso(8, 13) }, + { summary: "Market", start: { date: "2026-11-08" } }, + ], + "Family", + now, + ), + ); + assert.deepEqual( + items.map((i) => [i.day, i.title]), + [[0, "Market"], [0, "Lunch"], [1, "Dentist"], [2, "Holiday"]], + ); +}); diff --git a/frontend/src/live/today.ts b/frontend/src/live/today.ts new file mode 100644 index 0000000..325d4e1 --- /dev/null +++ b/frontend/src/live/today.ts @@ -0,0 +1,106 @@ +// "Today" for the wall tablet: the day's appointments from the calendars chosen in the plan, and the waste bins collected today or +// tomorrow. The events come from Home Assistant's calendar REST API; turning them into lines is a pure function. + +import type { Building } from "../model.ts"; +import type { HomeAssistant } from "../types.ts"; +import { pickupDays } from "../entities/household.ts"; +import { householdKind } from "../packs.ts"; + +/** One line of the day: a time ("09:30", or "" for all day) and what it is. */ +export interface TodayItem { + time: string; + title: string; + /** Where it comes from: a calendar's name, or a bin. */ + source: string; + /** Sorts the day: minutes after midnight (-1 for all-day events and bins). */ + at: number; + kind: "event" | "bin"; + /** Which day it is on: 0 today, 1 tomorrow … (the card can show several days). */ + day?: number; + /** Already over (it stays listed, dimmed). */ + past?: boolean; +} + +interface RawEvent { + summary?: string; + start?: { dateTime?: string; date?: string } | string; + end?: { dateTime?: string; date?: string } | string; +} + +const time = (d: Date) => `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`; +const when = (v: RawEvent["start"]) => (typeof v === "string" ? { dateTime: v } : (v ?? {})); + +const midnight = (t: number): number => { + const d = new Date(t); + d.setHours(0, 0, 0, 0); + return d.getTime(); +}; + +/** Days from today to the day of `t` (0 = today), across a clock change too. */ +const dayOf = (t: number, now: number): number => Math.max(0, Math.round((midnight(t) - midnight(now)) / 86_400_000)); + +/** The events of one calendar as lines of the day, all-day events first. */ +export function agenda(raw: RawEvent[], source: string, now: number): TodayItem[] { + return raw + .map((e): TodayItem | null => { + const s = when(e.start); + const end = when(e.end); + const title = (e.summary ?? "").trim(); + if (!title) return null; + if (s.dateTime) { + const d = new Date(s.dateTime); + const until = end.dateTime ? new Date(end.dateTime).getTime() : d.getTime(); + return { time: time(d), title, source, at: d.getHours() * 60 + d.getMinutes(), kind: "event", past: until < now, day: dayOf(d.getTime(), now) }; + } + // an all-day event is dated "YYYY-MM-DD": that is local midnight, not UTC + const date = s.date ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(s.date) : null; + const day = date ? dayOf(new Date(Number(date[1]), Number(date[2]) - 1, Number(date[3])).getTime(), now) : 0; + return { time: "", title, source, at: -1, kind: "event", day }; + }) + .filter((x): x is TodayItem => !!x); +} + +/** The bins collected today or tomorrow (from the household pieces of the plan). */ +export function binsDue(hass: HomeAssistant, b: Building, now: number, labels: { today: string; tomorrow: string }): TodayItem[] { + const out: TodayItem[] = []; + const seen = new Set(); + for (const floor of b.floors) + for (const f of floor.furniture) { + const id = f.care_entity; + if (!id || seen.has(id) || householdKind(f.type) !== "bin") continue; + seen.add(id); + const days = pickupDays(hass.states[id], now); + if (days === null || days > 1) continue; + const name = f.name || String(hass.states[id]?.attributes.friendly_name ?? id); + out.push({ time: "", title: name, source: days === 0 ? labels.today : labels.tomorrow, at: -1, kind: "bin" }); + } + return out; +} + +/** All lines, sorted: day by day, and in a day all-day things and bins first, then by time. */ +export function sortDay(items: TodayItem[]): TodayItem[] { + return [...items].sort((a, b) => (a.day ?? 0) - (b.day ?? 0) || a.at - b.at || a.title.localeCompare(b.title)); +} + +/** Loads the events of the chosen calendars from today's midnight over `days` days; a calendar that fails is left out. */ +export async function loadToday(hass: HomeAssistant, calendars: string[], days = 1, now = Date.now()): Promise { + if (!hass.fetchWithAuth || !calendars.length) return []; + const start = new Date(now); + start.setHours(0, 0, 0, 0); + const end = new Date(start); + // whole days by the calendar, so a clock change does not cut the last day short + end.setDate(end.getDate() + Math.max(1, days)); + const lists = await Promise.all( + calendars.map(async (id) => { + try { + const r = await hass.fetchWithAuth!(`/api/calendars/${encodeURIComponent(id)}?start=${encodeURIComponent(start.toISOString())}&end=${encodeURIComponent(end.toISOString())}`); + if (!r.ok) return []; + const name = String(hass.states[id]?.attributes.friendly_name ?? id.split(".")[1]); + return agenda((await r.json()) as RawEvent[], name, now); + } catch { + return []; + } + }), + ); + return lists.flat(); +} diff --git a/frontend/src/live/vacuum-map.test.ts b/frontend/src/live/vacuum-map.test.ts new file mode 100644 index 0000000..bf69bbd --- /dev/null +++ b/frontend/src/live/vacuum-map.test.ts @@ -0,0 +1,241 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, hassOf } from "../entities/fixtures.ts"; +import { calibrationFrom, calibrationFromRooms, gridMapper, gridPlaces, gridRooms, gridTurn, mapCamera, nudgeCalibration, readVacuum, type VacuumCalibration } from "./vacuum-map.ts"; + +/** Two decimals, so a test can compare pairs without float noise. */ +const r2 = (v: number) => Math.round(v * 100) / 100; +const pair2 = (p: [number, number]) => p.map(r2); + +/** 10 m of plan over 100 grid units, no turn: 0.1 m per unit. */ +const CAL: VacuumCalibration = { a: [0, 0], ga: [0, 0], b: [10, 0], gb: [100, 0] }; + +test("two places known in both frames tie the grid to the plan", () => { + const map = gridMapper(CAL)!; + assert.deepEqual(pair2(map([0, 0])), [0, 0]); + assert.deepEqual(pair2(map([100, 0])), [10, 0]); + assert.deepEqual(pair2(map([0, 50])), [0, 5], "grid +y runs along plan +z"); + assert.deepEqual(pair2(map([50, 50])), [5, 5], "and in between it scales as well"); +}); + +test("a grid that is turned relative to the plan turns with it", () => { + // grid +x is plan +z: a quarter turn to the left + const cal: VacuumCalibration = { a: [0, 0], ga: [0, 0], b: [0, 10], gb: [100, 0] }; + const map = gridMapper(cal)!; + assert.deepEqual(pair2(map([100, 0])), [0, 10]); + assert.deepEqual(pair2(map([0, 100])), [-10, 0]); + assert.ok(Math.abs(gridTurn(cal)! - Math.PI / 2) < 1e-9); +}); + +test("the plan points do not have to sit at the grid's origin", () => { + // the same shape, shifted: a place at grid (0,0) is at plan (3,-2) + const cal: VacuumCalibration = { a: [3, -2], ga: [0, 0], b: [13, -2], gb: [100, 0] }; + const map = gridMapper(cal)!; + assert.deepEqual(pair2(map([0, 0])), [3, -2]); + assert.deepEqual(pair2(map([100, 100])), [13, 8]); +}); + +test("a mirrored map is met by mirroring its grid", () => { + // the same two places, but this camera's y grows along plan -z: grid +y is plan -z + const cal: VacuumCalibration = { ...CAL, mirror: true }; + const map = gridMapper(cal)!; + assert.deepEqual(pair2(map([0, 0])), [0, 0]); + assert.deepEqual(pair2(map([100, 0])), [10, 0], "the two calibration places still land where they belong"); + assert.deepEqual(pair2(map([0, 50])), [0, -5], "grid +y now runs along plan -z"); + assert.deepEqual(pair2(map([50, 50])), [5, -5]); + assert.equal(gridTurn(cal), gridTurn(CAL), "the turn between the two places is unchanged"); +}); + +test("a mirrored map reads its facings the other way round", () => { + const cal: VacuumCalibration = { ...CAL, mirror: true }; + // facing grid +y, which on this map is plan -z + const hass = hassOf([entity("camera.map", "idle", { vacuum_position: { x: 0, y: 0, a: 90 } })]); + const live = readVacuum(hass, "camera.map", cal)!; + assert.ok(Math.abs(Math.abs(live.pose!.heading) - Math.PI) < 1e-9, `heading ${live.pose!.heading}`); +}); + +test("two places on top of each other say nothing about scale or direction", () => { + assert.equal(gridMapper({ ...CAL, b: [0, 0] }), null, "the same plan point twice"); + assert.equal(gridMapper({ ...CAL, gb: [0, 0] }), null, "the same grid point twice"); + assert.equal(gridMapper(null), null); + assert.equal(gridMapper(undefined), null); +}); + +test("the map camera is found by the attributes it carries, without being configured", () => { + const hass = hassOf([entity("camera.a", "idle"), entity("camera.map", "idle", { vacuum_position: { x: 1, y: 2, a: 0 } })]); + assert.equal(mapCamera(hass), "camera.map"); + assert.equal(mapCamera(hassOf([entity("camera.a", "idle")])), null, "nothing to find"); +}); + +test("the live map reads pose, dock and trail in plan metres", () => { + const hass = hassOf([ + entity("camera.map", "idle", { + vacuum_position: { x: 100, y: 50, a: 90 }, + charger: { x: 0, y: 0 }, + path: [ + [ + [0, 0], + [100, 0], + [100, 50], + ], + ], + }), + ]); + const live = readVacuum(hass, "camera.map", CAL)!; + assert.ok(live, "the attributes are there"); + assert.deepEqual(pair2(live.pose ? [live.pose.x, live.pose.z] : [0, 0]), [10, 5]); + // a heading of 90 in the grid faces grid +y, which is plan +z — and a heading of 0 faces +z + assert.ok(Math.abs(live.pose!.heading) < 1e-9, `heading ${live.pose!.heading}`); + assert.deepEqual(pair2(live.charger!), [0, 0]); + assert.equal(live.path.length, 1, "one segment"); + assert.equal(live.path[0].length, 3, "three points in it"); + assert.deepEqual(pair2(live.path[0][2]), [10, 5], "the trail ends where the robot is"); +}); + +test("facing along the grid's x is a quarter turn on the plan", () => { + const hass = hassOf([entity("camera.map", "idle", { vacuum_position: { x: 0, y: 0, a: 0 } })]); + const live = readVacuum(hass, "camera.map", CAL)!; + assert.ok(Math.abs(live.pose!.heading - Math.PI / 2) < 1e-9, "0 faces +z, so +x is a quarter turn"); +}); + +test("without a camera or without attributes there is nothing to draw", () => { + const hass = hassOf([entity("camera.map", "idle", {})]); + assert.equal(readVacuum(hass, "camera.map", CAL), null, "no attributes at all"); + assert.equal(readVacuum(hass, null, CAL), null, "no camera"); + assert.equal(readVacuum(hass, "camera.gone", CAL), null, "a camera that is not there"); +}); + +test("a trail of one point is no trail", () => { + const hass = hassOf([entity("camera.map", "idle", { path: [[[0, 0]]] })]); + assert.equal(readVacuum(hass, "camera.map", CAL), null, "a single point is nothing to draw"); + // a single point next to a pose still leaves no trail, but the robot itself is drawn + const withPose = hassOf([entity("camera.map", "idle", { vacuum_position: { x: 0, y: 0, a: 0 }, path: [[[0, 0]]] })]); + const live = readVacuum(withPose, "camera.map", CAL)!; + assert.equal(live.path.length, 0, "a single point says nothing about a way"); + assert.ok(live.pose, "but the robot is there"); +}); + +test("a trail is read whether it comes as one run or as several", () => { + // the map card's format: a single run of points + const flat = hassOf([entity("camera.map", "idle", { vacuum_position: { x: 100, y: 50, a: 0 }, path: [[0, 0], [100, 0], [100, 50]] })]); + const one = readVacuum(flat, "camera.map", CAL)!; + assert.equal(one.path.length, 1, "one run"); + assert.equal(one.path[0].length, 3, "with all three points"); + assert.deepEqual(pair2(one.path[0][2]), [10, 5]); + // NarwalIntegration's: two runs, a gap between them + const split = hassOf([ + entity("camera.map", "idle", { + vacuum_position: { x: 100, y: 50, a: 0 }, + path: [ + [[0, 0], [100, 0]], + [[100, 50], [200, 50]], + ], + }), + ]); + const two = readVacuum(split, "camera.map", CAL)!; + assert.equal(two.path.length, 2, "two runs"); + assert.deepEqual(pair2(two.path[1][1]), [20, 5]); +}); + +test("a camera that only knows where the dock is still counts as a robot map", () => { + const hass = hassOf([entity("camera.dock_only", "idle", { charger: { x: 10, y: 10 } })]); + assert.equal(mapCamera(hass), "camera.dock_only"); +}); + +test("the dock and one place the robot is at are enough to calibrate", () => { + const dock = { plan: [0, 0] as [number, number], grid: [100, 100] as [number, number] }; + // the robot is 4 m to plan +x, and its grid says +40 cells: 0.1 m per cell, no turn + const res = calibrationFrom(dock, { plan: [4, 0], grid: [140, 100] }, false); + assert.ok(res.cal, "a workable pair"); + const map = gridMapper(res.cal)!; + assert.deepEqual(pair2(map([100, 100])), [0, 0], "the dock lands on the dock"); + assert.deepEqual(pair2(map([140, 100])), [4, 0], "and the robot where it was tapped"); + assert.deepEqual(pair2(map([140, 140])), [4, 4], "grid +y runs along plan +z without mirror"); +}); + +test("a mirrored map puts the same places on the other side", () => { + const dock = { plan: [0, 0] as [number, number], grid: [100, 100] as [number, number] }; + const res = calibrationFrom(dock, { plan: [4, 0], grid: [140, 100] }, true); + assert.ok(res.cal); + assert.deepEqual(pair2(gridMapper(res.cal)!.call(null, [140, 140])), [4, -4], "grid +y runs along plan -z"); +}); + +test("places too close for the turn, or a scale that makes no sense, are refused", () => { + const dock = { plan: [0, 0] as [number, number], grid: [100, 100] as [number, number] }; + const close = calibrationFrom(dock, { plan: [0.4, 0], grid: [104, 100] }); + assert.equal(close.cal, null, "half a metre apart is guesswork"); + assert.equal(close.cal === null && close.reason, "close"); + const same = calibrationFrom(dock, { plan: [4, 0], grid: [100, 100] }); + assert.equal(same.cal === null && same.reason, "close", "the robot has not moved on its map"); + const wild = calibrationFrom(dock, { plan: [4, 0], grid: [100.001, 100] }); + assert.equal(wild.cal === null && wild.reason, "scale", "4 m in a thousandth of a cell"); +}); + +test("the grid places come from the camera, and are null without one", () => { + const hass = hassOf([entity("camera.map", "idle", { vacuum_position: { x: 12, y: 34, a: 90 }, charger: { x: 1, y: 2 } })]); + assert.deepEqual(gridPlaces(hass, "camera.map"), { at: [12, 34], dock: [1, 2] }); + assert.deepEqual(gridPlaces(hass, null), { at: null, dock: null }); + assert.deepEqual(gridPlaces(hass, "camera.gone"), { at: null, dock: null }); +}); + +test("Dreame's map camera names the dock charger_position and may have no trail (#109)", () => { + const hass = hassOf([entity("camera.dreame_map", "idle", { vacuum_position: { x: 100, y: 50, a: 0 }, charger_position: { x: 20, y: 10 } })]); + assert.equal(mapCamera(hassOf([entity("camera.dreame_map", "idle", { charger_position: { x: 20, y: 10 } })])), "camera.dreame_map", "found by the dock alone"); + assert.deepEqual(gridPlaces(hass, "camera.dreame_map"), { at: [100, 50], dock: [20, 10] }); + const live = readVacuum(hass, "camera.dreame_map", CAL)!; + assert.deepEqual(pair2(live.charger!), [2, 1]); + assert.deepEqual(live.path, [], "no path attribute: no invented trail"); +}); + +/** The rooms of a real Dreame X50 Ultra map camera (#109), boxes in millimetres; the dock sits in the kitchen. */ +const DREAME_ROOMS = { + "2": { x0: 800, y0: 1150, x1: 5700, y1: 4450, name: "Wohnzimmer" }, + "3": { x0: 1950, y0: -1750, x1: 5750, y1: 1150, name: "Flur" }, + "4": { x0: -2000, y0: -1050, x1: 1950, y1: 3900, name: "Küche" }, + "5": { x0: -1850, y0: -2650, x1: 50, y1: -1050, name: "Bad" }, + "6": { x0: 50, y0: -2700, x1: 1200, y1: -1050, name: "Flur 2" }, + "7": { x0: 2000, y0: -9600, x1: 6000, y1: -1750, name: "Büro" }, + "8": { x0: -1900, y0: -5600, x1: 1150, y1: -2700, name: "Schlafzimmer" }, +}; +const DREAME_DOCK = { x: -1752, y: 1556, a: 268 }; + +/** A plan drawn from the robot's boxes: millimetres to metres, y running against plan z, a quarter turn, shifted. */ +function planOf(rooms: typeof DREAME_ROOMS, rename: (n: string) => string = (n) => n) { + const put = (x: number, y: number): [number, number] => [12 + (-y / 1000), 5 + (-x / 1000)]; + return Object.values(rooms).map((r) => ({ name: rename(r.name), points: [put(r.x0, r.y0), put(r.x1, r.y0), put(r.x1, r.y1), put(r.x0, r.y1)] })); +} + +test("a Dreame map is calibrated from the rooms both sides name, mirror and all, without the robot moving", () => { + const hass = hassOf([entity("camera.x50_map", "idle", { rooms: DREAME_ROOMS, vacuum_position: DREAME_DOCK, charger_position: DREAME_DOCK })]); + const robot = gridRooms(hass, "camera.x50_map"); + assert.equal(robot.length, 7); + const res = calibrationFromRooms(planOf(DREAME_ROOMS, (n) => n.toUpperCase().replace(" ", "-")), robot); + assert.ok(res.cal, "matched by name, whatever the case and spacing"); + assert.equal(res.matched.length, 7); + assert.equal(res.cal.mirror, true, "three rooms or more tell a mirrored map from a turned one"); + // the docked robot lands where the plan puts the dock: the kitchen, 12 + -1.556, 5 + 1.752 + const live = readVacuum(hass, "camera.x50_map", res.cal)!; + assert.deepEqual(pair2(live.charger!), [10.44, 6.75]); + assert.deepEqual([r2(live.pose!.x), r2(live.pose!.z)], [10.44, 6.75]); +}); + +test("rooms that do not match, or match the wrong way round, give no calibration", () => { + const hass = hassOf([entity("camera.x50_map", "idle", { rooms: DREAME_ROOMS })]); + const robot = gridRooms(hass, "camera.x50_map"); + assert.deepEqual(calibrationFromRooms(planOf(DREAME_ROOMS, (n) => `${n} OG`), robot), { cal: null, reason: "rooms", matched: [] }); + // the plan's office and bedroom swapped: no fit puts every room where the plan has it + const swapped = planOf(DREAME_ROOMS, (n) => (n === "Büro" ? "Wohnzimmer" : n === "Wohnzimmer" ? "Büro" : n === "Bad" ? "Flur" : n === "Flur" ? "Bad" : n)); + assert.equal(calibrationFromRooms(swapped, robot).cal, null); +}); + +test("a nudge moves, turns and scales the whole map by hand", () => { + const cal: VacuumCalibration = { a: [0, 0], ga: [0, 0], b: [4, 0], gb: [4000, 0] }; + const moved = gridMapper(nudgeCalibration(cal, { move: [0.1, -0.2] }))!; + assert.deepEqual(moved([2000, 0]).map((v) => Math.round(v * 1000) / 1000), [2.1, -0.2]); + const turned = nudgeCalibration(cal, { turn: 90 }); + assert.deepEqual(turned.a, [2, -2]); + assert.deepEqual(turned.b, [2, 2]); + const grown = nudgeCalibration(cal, { grow: 1.5 }); + assert.deepEqual([grown.a, grown.b], [[-1, 0], [5, 0]]); + assert.deepEqual(grown.ga, cal.ga); +}); diff --git a/frontend/src/live/vacuum-map.ts b/frontend/src/live/vacuum-map.ts new file mode 100644 index 0000000..5aaa0f4 --- /dev/null +++ b/frontend/src/live/vacuum-map.ts @@ -0,0 +1,312 @@ +/** + * A robot's own map, put into the plan's coordinates. + * + * A robot reports where it is and where it has been in its map's grid, which has nothing to do with the + * plan's metres: the integration hands that out on the map camera's attributes (`vacuum_position`, + * `charger` or Dreame's `charger_position`, `path` — the vacuum map card's names, shared by NarwalIntegration and the Xiaomi/Roborock map + * extractors). Two places known in both frames are enough to tie the two together, as a similarity transform: + * scale, rotation and shift. Everything else — the pose, the trail, the dock — follows from those two pairs. + * + * A map whose y grows along plan -z needs `mirror`: two places cannot tell a mirror from a turn, since + * both put them exactly where they belong, so the caller has to say which one the map is. + */ +import type { VacuumCalibration } from "../model.ts"; +import type { HomeAssistant } from "../types.ts"; + +export type { VacuumCalibration }; + +export interface VacuumPose { + x: number; + z: number; + /** Facing, in radians, the way the viewer turns a robot: 0 faces +z. */ + heading: number; +} + +export interface VacuumLive { + pose: VacuumPose | null; + /** The dock, in plan metres. */ + charger: [number, number] | null; + /** The trail of the current clean, as segments in plan metres. */ + path: [number, number][][]; +} + +const num = (v: unknown): number => Number(v); + +/** A map position as a pair: the robot writes `{x, y}` for itself and `[x, y]` in its trail. */ +function pair(v: unknown): [number, number] | null { + if (Array.isArray(v)) { + const [px, py] = [num(v[0]), num(v[1])]; + return Number.isFinite(px) && Number.isFinite(py) ? [px, py] : null; + } + if (!v || typeof v !== "object") return null; + const { x, y } = v as { x?: unknown; y?: unknown }; + const [px, py] = [num(x), num(y)]; + return Number.isFinite(px) && Number.isFinite(py) ? [px, py] : null; +} + +/** Where the dock is in the map's grid: `charger` (the map card's name), or `charger_position` (Dreame's map camera, #109). */ +function dockOf(attributes: Record | undefined): [number, number] | null { + return attributes ? (pair(attributes.charger) ?? pair(attributes.charger_position)) : null; +} + +/** + * The camera whose attributes describe a robot map: it reports where the robot is or where it docks, so it can + * be found without being configured. + */ +export function mapCamera(hass: HomeAssistant): string | null { + for (const [id, st] of Object.entries(hass.states)) { + if (!id.startsWith("camera.")) continue; + // where the robot is, or where it docks: either says this camera carries a robot's map + if (pair(st.attributes?.vacuum_position) ?? dockOf(st.attributes)) return id; + } + return null; +} + +/** Whether a value is one grid point: `[x, y]`, or `{x, y}` as the robot writes its own position. */ +const isPoint = (v: unknown): boolean => (Array.isArray(v) ? typeof v[0] === "number" : !!v && typeof v === "object"); + +/** A grid point as the calibration sees it: mirrored onto the plan's side when the map runs backwards. */ +const asSeen = (g: [number, number], mirror: boolean): [number, number] => (mirror ? [g[0], -g[1]] : g); + +/** How the grid turns and scales into the plan, or null while the two points are unusable. */ +export function gridMapper(cal: VacuumCalibration | null | undefined): ((g: [number, number]) => [number, number]) | null { + if (!cal) return null; + const mirror = cal.mirror === true; + const [gax, gay] = asSeen(cal.ga, mirror); + const [gbx, gby] = asSeen(cal.gb, mirror); + const [ax, az] = cal.a; + const [bx, bz] = cal.b; + const [dgx, dgy] = [gbx - gax, gby - gay]; + const [dpx, dpz] = [bx - ax, bz - az]; + const dg = Math.hypot(dgx, dgy); + const dp = Math.hypot(dpx, dpz); + // two points on top of each other say nothing about scale or direction + if (!(dg > 1e-6) || !(dp > 1e-6)) return null; + const scale = dp / dg; + const turn = Math.atan2(dpz, dpx) - Math.atan2(dgy, dgx); + const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; + return (g) => { + const seen = asSeen(g, mirror); + const [x, y] = [seen[0] - gax, seen[1] - gay]; + return [ax + scale * (x * cos - y * sin), az + scale * (x * sin + y * cos)]; + }; +} + +/** The turn of the grid into the plan, in radians (for headings). */ +export function gridTurn(cal: VacuumCalibration | null | undefined): number | null { + if (!cal) return null; + const mirror = cal.mirror === true; + const [gax, gay] = asSeen(cal.ga, mirror); + const [gbx, gby] = asSeen(cal.gb, mirror); + const turn = Math.atan2(cal.b[1] - cal.a[1], cal.b[0] - cal.a[0]) - Math.atan2(gby - gay, gbx - gax); + return Number.isFinite(turn) ? turn : null; +} + +/** + * The robot's live map, in plan metres. `camera` is the map camera (see `mapCamera`); without a + * calibration the grid is passed through unchanged, which is wrong on the plan but keeps the shape. + */ +export function readVacuum(hass: HomeAssistant, camera: string | null, cal: VacuumCalibration | null | undefined): VacuumLive | null { + if (!camera) return null; + const attributes = hass.states[camera]?.attributes; + if (!attributes) return null; + const toPlan = gridMapper(cal) ?? ((g: [number, number]) => g); + const turn = gridTurn(cal) ?? 0; + // a mirrored map turns the other way, so a facing reads the other way too + const facingSign = cal?.mirror === true ? -1 : 1; + + const position = attributes.vacuum_position as { a?: unknown } | undefined; + const at = pair(position); + const pose = at + ? (() => { + const [x, z] = toPlan(at); + // the robot reports its facing in degrees, 0 = +x and 90 = +y; a heading of 0 faces +z here + const facing = num(position?.a) * facingSign; + if (!Number.isFinite(facing)) return { x, z, heading: 0 }; + const angle = (facing * Math.PI) / 180 + turn; + return { x, z, heading: Math.atan2(Math.cos(angle), Math.sin(angle)) }; + })() + : null; + + const dock = dockOf(attributes); + // `path` is one run of points in the map card's format, and a list of runs in NarwalIntegration's, where a + // gap is a new run; take both, or a robot's whole trail would count as a single point and vanish + const rawPath: unknown[] = Array.isArray(attributes.path) ? attributes.path : []; + const runs: unknown[][] = rawPath.length > 0 && isPoint(rawPath[0]) ? [rawPath] : (rawPath as unknown[][]); + const path: [number, number][][] = []; + for (const segment of runs) { + const points: [number, number][] = []; + for (const raw of Array.isArray(segment) ? segment : []) { + const g = pair(raw); + if (g) points.push(toPlan(g)); + } + if (points.length > 1) path.push(points); + } + // a camera that describes nothing (no pose, no dock, no trail) is no map to draw + if (!pose && !dock && !path.length) return null; + return { pose, charger: dock ? toPlan(dock) : null, path }; +} + +/** Two places as a calibration needs them: a point on the plan, and the robot's grid point there. */ +export interface Place { + plan: [number, number]; + grid: [number, number]; +} + +/** Why a pair of places cannot be calibrated: they sit too close together, or the scale makes no sense. */ +export type CalibrationResult = { cal: VacuumCalibration } | { cal: null; reason: "close" | "scale" }; + +/** A believable scale: a robot counts in millimetres, or in cells of a few centimetres. */ +const MIN_SCALE = 0.0005; +const MAX_SCALE = 2; +/** How far apart the two places have to be, in the plan: closer and the turn is guesswork. */ +const MIN_BASELINE = 1.5; + +/** Where the robot and its dock are in the map's grid, which is what a calibration is built from. */ +export function gridPlaces(hass: HomeAssistant, camera: string | null): { at: [number, number] | null; dock: [number, number] | null } { + const attributes = camera ? hass.states[camera]?.attributes : undefined; + return { + at: attributes ? pair(attributes.vacuum_position) : null, + dock: dockOf(attributes), + }; +} + +/** + * The calibration from two places: the dock, which the plan and the robot both know, and a place the robot is + * at now, which is one tap. Two places fix scale and turn; `mirror` has to be given, since a mirror puts them + * exactly where a turn would. + */ +export function calibrationFrom(dock: Place, here: Place, mirror = false): CalibrationResult { + const plan = Math.hypot(here.plan[0] - dock.plan[0], here.plan[1] - dock.plan[1]); + const grid = Math.hypot(here.grid[0] - dock.grid[0], here.grid[1] - dock.grid[1]); + if (!(grid > 1e-6) || !(plan >= MIN_BASELINE)) return { cal: null, reason: "close" }; + const scale = plan / grid; + if (!(scale >= MIN_SCALE && scale <= MAX_SCALE)) return { cal: null, reason: "scale" }; + return { cal: { a: dock.plan, ga: dock.grid, b: here.plan, gb: here.grid, mirror } }; +} + +/** A room on the robot's map: its name and the middle of its box, in the map's grid. */ +export interface GridRoom { + name: string; + center: [number, number]; +} + +/** + * The rooms the robot knows, from the map camera's `rooms`: Dreame writes a box (`x0..y1`) and a name per room; + * a room without a name cannot be matched to the plan, so it is left out. + */ +export function gridRooms(hass: HomeAssistant, camera: string | null): GridRoom[] { + const raw = camera ? hass.states[camera]?.attributes?.rooms : undefined; + if (!raw || typeof raw !== "object") return []; + const out: GridRoom[] = []; + for (const r of Object.values(raw as Record)) { + if (!r || typeof r !== "object") continue; + const room = r as Record; + const name = typeof room.name === "string" ? room.name.trim() : ""; + const box = [room.x0, room.y0, room.x1, room.y1].map(num); + if (!name || !box.every(Number.isFinite)) continue; + out.push({ name, center: [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2] }); + } + return out; +} + +/** A room name as both sides are compared: case, spaces and punctuation do not count. */ +const roomKey = (name: string): string => name.toLocaleLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^\p{L}\p{N}]+/gu, ""); + +/** The least-squares similarity from grid points (already mirrored when the map runs backwards) onto the plan, and how far it misses on average. */ +function fitSimilarity(pairs: { plan: [number, number]; seen: [number, number] }[]): { map: (g: [number, number]) => [number, number]; scale: number; rms: number } | null { + const n = pairs.length; + const [gx, gy] = pairs.reduce((s, p) => [s[0] + p.seen[0] / n, s[1] + p.seen[1] / n], [0, 0]); + const [px, pz] = pairs.reduce((s, p) => [s[0] + p.plan[0] / n, s[1] + p.plan[1] / n], [0, 0]); + // the plan point is (a + ib)(grid point) in complex numbers, around both centroids: a and b by least squares + let [sa, sb, sg] = [0, 0, 0]; + for (const p of pairs) { + const [u, v] = [p.seen[0] - gx, p.seen[1] - gy]; + const [x, z] = [p.plan[0] - px, p.plan[1] - pz]; + sa += u * x + v * z; + sb += u * z - v * x; + sg += u * u + v * v; + } + if (!(sg > 1e-9)) return null; + const [a, b] = [sa / sg, sb / sg]; + const map = (g: [number, number]): [number, number] => { + const [u, v] = [g[0] - gx, g[1] - gy]; + return [px + a * u - b * v, pz + b * u + a * v]; + }; + const rms = Math.sqrt(pairs.reduce((s, p) => s + Math.hypot(map(p.seen)[0] - p.plan[0], map(p.seen)[1] - p.plan[1]) ** 2, 0) / n); + return { map, scale: Math.hypot(a, b), rms }; +} + +export type RoomCalibrationResult = { cal: VacuumCalibration; matched: string[]; rms: number } | { cal: null; reason: "rooms" | "scale" | "fit"; matched: string[] }; + +/** + * The calibration from rooms both sides know by name: the robot's map names its rooms like the plan does, and + * the middles of matching rooms tie the grid to the plan without the robot moving at all. Two rooms fix scale and + * turn (with `mirror` as given); three or more also tell a mirrored map from a turned one, so the better fit wins. + */ +export function calibrationFromRooms(planRooms: { name: string; points: readonly [number, number][] }[], robotRooms: GridRoom[], mirror = false): RoomCalibrationResult { + const byKey = new Map(robotRooms.map((r) => [roomKey(r.name), r] as const)); + const pairs: { name: string; plan: [number, number]; grid: [number, number] }[] = []; + const used = new Set(); + for (const room of planRooms) { + const key = roomKey(room.name); + const robot = byKey.get(key); + if (!robot || used.has(key) || room.points.length < 3) continue; + used.add(key); + const xs = room.points.map((p) => p[0]); + const zs = room.points.map((p) => p[1]); + // the middle of the room's box, as the robot measures its rooms + pairs.push({ name: room.name, plan: [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...zs) + Math.max(...zs)) / 2], grid: robot.center }); + } + const matched = pairs.map((p) => p.name); + if (pairs.length < 2) return { cal: null, reason: "rooms", matched }; + const fits = (pairs.length >= 3 ? [false, true] : [mirror]).flatMap((m) => { + const fit = fitSimilarity(pairs.map((p) => ({ plan: p.plan, seen: asSeen(p.grid, m) }))); + return fit ? [{ mirror: m, ...fit }] : []; + }); + const best = fits.sort((x, y) => x.rms - y.rms)[0]; + if (!best) return { cal: null, reason: "rooms", matched }; + if (!(best.scale >= MIN_SCALE && best.scale <= MAX_SCALE)) return { cal: null, reason: "scale", matched }; + // the plan spread of the rooms: a fit that misses by more than a quarter of it has matched the wrong rooms + const spread = Math.max(...pairs.map((p) => Math.hypot(p.plan[0] - pairs[0].plan[0], p.plan[1] - pairs[0].plan[1]))); + if (!(best.rms <= Math.max(1, spread / 4))) return { cal: null, reason: "fit", matched }; + // stored as two places like a tapped calibration: the two rooms furthest apart, put where the fit puts them + let [i, j, far] = [0, 1, -1]; + for (let p = 0; p < pairs.length; p++) + for (let q = p + 1; q < pairs.length; q++) { + const d = Math.hypot(pairs[p].grid[0] - pairs[q].grid[0], pairs[p].grid[1] - pairs[q].grid[1]); + if (d > far) [i, j, far] = [p, q, d]; + } + const [ga, gb] = [pairs[i].grid, pairs[j].grid]; + return { + cal: { a: best.map(asSeen(ga, best.mirror)), ga, b: best.map(asSeen(gb, best.mirror)), gb, mirror: best.mirror }, + matched, + rms: best.rms, + }; +} + + +/** A hand correction of a calibration: moved in plan metres, turned in degrees, grown by a factor. */ +export interface CalibrationNudge { + move?: [number, number]; + turn?: number; + grow?: number; +} + +/** + * Shifts, turns or scales a calibration around the middle of its two places, for when a fitted map sits a little + * off: both places are moved in the plan, the robot's grid positions stay, so the whole map follows. + */ +export function nudgeCalibration(cal: VacuumCalibration, nudge: CalibrationNudge): VacuumCalibration { + const [mx, mz] = [(cal.a[0] + cal.b[0]) / 2, (cal.a[1] + cal.b[1]) / 2]; + const rad = ((nudge.turn ?? 0) * Math.PI) / 180; + const [cos, sin, grow] = [Math.cos(rad), Math.sin(rad), nudge.grow ?? 1]; + const [dx, dz] = nudge.move ?? [0, 0]; + const at = (p: [number, number]): [number, number] => { + const [x, z] = [(p[0] - mx) * grow, (p[1] - mz) * grow]; + return [round(mx + x * cos - z * sin + dx), round(mz + x * sin + z * cos + dz)]; + }; + return { ...cal, a: at(cal.a), b: at(cal.b) }; +} + +const round = (v: number): number => Math.round(v * 1000) / 1000; diff --git a/frontend/src/live/week-bars.test.ts b/frontend/src/live/week-bars.test.ts new file mode 100644 index 0000000..a5284ec --- /dev/null +++ b/frontend/src/live/week-bars.test.ts @@ -0,0 +1,19 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { dayStart, weekFromStats } from "./week-bars.ts"; + +test("kWh per day from daily mean power, consumption from the balance when no sensor tells", () => { + const now = new Date(2026, 10, 2, 12, 0).getTime(); // noon: today counts 12 hours + const day = (back: number) => new Date(dayStart(now, back)).toISOString(); + const stats = { + "sensor.pv": [{ start: day(1), mean: 500 }, { start: day(0), mean: 1000 }], + "sensor.grid": [{ start: day(1), mean: 250 }, { start: day(0), mean: -400 }], + }; + const week = weekFromStats(stats, { solar: ["sensor.pv"], grid: "sensor.grid", gridInvert: false, battery: [], batteryInvert: false, consumption: null }, now); + assert.equal(week.days.length, 7); + assert.equal(week.solar[5], 12, "500 W all day"); + assert.equal(week.solar[6], 12, "1000 W for the 12 hours so far"); + assert.equal(week.use[5], 18, "500 + 250 W"); + assert.equal(week.use[6], 7.2, "1000 − 400 W for 12 h"); + assert.equal(week.solar[0], null, "no statistics that day"); +}); diff --git a/frontend/src/live/week-bars.ts b/frontend/src/live/week-bars.ts new file mode 100644 index 0000000..17d84c0 --- /dev/null +++ b/frontend/src/live/week-bars.ts @@ -0,0 +1,75 @@ +// The last seven days for the house's energy card: solar and consumption per day in kWh, from Home Assistant's long-term statistics +// of the power sensors (their daily mean × 24 h). One small request a day instead of a week of history. + +import type { HomeAssistant } from "../types.ts"; + +/** The sensors the week is read from, and their signs (grid: + import, battery: + discharging). */ +export interface WeekSources { + solar: string[]; + grid: string | null; + gridInvert: boolean; + battery: string[]; + batteryInvert: boolean; + /** A house consumption sensor; without one the use is solar + grid + battery. */ + consumption: string | null; +} + +export interface WeekBars { + /** Start of each day (ms), oldest first. */ + days: number[]; + solar: (number | null)[]; + use: (number | null)[]; +} + +type Stats = Record; + +const DAY = 86_400_000; + +/** Midnight of the day `t` falls on, `back` days earlier. */ +export function dayStart(t: number, back = 0): number { + const d = new Date(t); + d.setHours(0, 0, 0, 0); + d.setDate(d.getDate() - back); + return d.getTime(); +} + +/** kWh per day from the daily mean power (W) of the sensors; today counts the hours gone so far. */ +export function weekFromStats(stats: Stats, src: WeekSources, now: number): WeekBars { + const days = Array.from({ length: 7 }, (_, i) => dayStart(now, 6 - i)); + const hours = (day: number) => Math.min(24, Math.max(0, (Math.min(now, day + DAY) - day) / 3_600_000)); + const meanOn = (id: string | null, day: number): number | null => { + if (!id) return null; + const row = (stats[id] ?? []).find((r) => Math.abs(new Date(r.start).getTime() - day) < 3 * 3_600_000); + return typeof row?.mean === "number" ? row.mean : null; + }; + const sum = (ids: string[], day: number, sign = 1): number | null => { + const values = ids.map((id) => meanOn(id, day)).filter((v): v is number => v !== null); + return values.length ? values.reduce((a, b) => a + b, 0) * sign : null; + }; + const kwh = (w: number | null, day: number) => (w === null ? null : Math.round(((w * hours(day)) / 1000) * 10) / 10); + const solar = days.map((day) => kwh(sum(src.solar, day), day)); + const use = days.map((day) => { + if (src.consumption) return kwh(meanOn(src.consumption, day), day); + const parts = [sum(src.solar, day), sum(src.grid ? [src.grid] : [], day, src.gridInvert ? -1 : 1), sum(src.battery, day, src.batteryInvert ? -1 : 1)]; + if (parts.every((p) => p === null)) return null; + return kwh(Math.max(0, parts.reduce((a, b) => a + (b ?? 0), 0)), day); + }); + return { days, solar, use }; +} + +/** Loads the week from the recorder's statistics; null when there are no sensors or the recorder has nothing. */ +export async function loadWeek(hass: HomeAssistant, src: WeekSources, now = Date.now()): Promise { + const ids = [...new Set([...src.solar, ...src.battery, src.grid, src.consumption].filter((id): id is string => !!id))]; + if (!ids.length) return null; + const stats = await hass.callWS({ + type: "recorder/statistics_during_period", + start_time: new Date(dayStart(now, 6)).toISOString(), + end_time: new Date(now).toISOString(), + statistic_ids: ids, + period: "day", + types: ["mean"], + units: { power: "W" }, + }); + const week = weekFromStats(stats, src, now); + return week.solar.some((v) => v !== null) || week.use.some((v) => v !== null) ? week : null; +} diff --git a/frontend/src/live/wifi.test.ts b/frontend/src/live/wifi.test.ts new file mode 100644 index 0000000..0e8d7d6 --- /dev/null +++ b/frontend/src/live/wifi.test.ts @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { entity, hassOf } from "../entities/fixtures.ts"; +import { coverageColor, isAccessPoint, networkHealth, readAccessPoint } from "./wifi.ts"; + +test("an access point's clients and state from its device", () => { + const d = { device_id: "ap" }; + const hass = hassOf([entity("sensor.ap_flur_clients", "14"), entity("binary_sensor.ap_flur_online", "on", { device_class: "connectivity" })], { "sensor.ap_flur_clients": d, "binary_sensor.ap_flur_online": d }); + const ap = readAccessPoint(hass, "sensor.ap_flur_clients")!; + assert.deepEqual(ap, { clients: 14, online: true }); + assert.deepEqual(coverageColor(ap), [0.3, 0.7, 1]); + assert.deepEqual(coverageColor({ clients: 2, online: false }), [1, 0.3, 0.3]); + assert.equal(isAccessPoint("pack:nextfloor.a_smart2:access_point"), true); +}); + +test("the network's health: connectivity sensors and router trackers", () => { + const h = networkHealth([ + entity("binary_sensor.nas_online", "on", { device_class: "connectivity" }), + entity("binary_sensor.printer_online", "off", { device_class: "connectivity", friendly_name: "Drucker" }), + entity("device_tracker.phone", "home", { source_type: "router" }), + entity("device_tracker.gps", "home", { source_type: "gps" }), + ]); + assert.deepEqual(h, { online: 2, offline: ["Drucker"] }); +}); diff --git a/frontend/src/live/wifi.ts b/frontend/src/live/wifi.ts new file mode 100644 index 0000000..e613bdf --- /dev/null +++ b/frontend/src/live/wifi.ts @@ -0,0 +1,57 @@ +// The Wi-Fi map: access points and mesh nodes of the plan with how many devices they carry, and how the house's network devices are +// doing. Read from the entities of each access point's device (UniFi, Omada, FRITZ!Box, OpenWrt, Deco …). + +import type { HassEntity, HomeAssistant } from "../types.ts"; + +/** Whether a piece of furniture is an access point, router or mesh node (by its pack item's id). */ +export const isAccessPoint = (type: string): boolean => /access_point|router|mesh|wifi|repeater/.test(type); + +const has = (id: string, ...words: string[]) => words.some((w) => id.includes(w)); + +function siblings(hass: HomeAssistant, entity: string): string[] { + const device = hass.entities?.[entity]?.device_id; + if (!device) return hass.states[entity] ? [entity] : []; + return Object.values(hass.entities ?? {}) + .filter((e) => e.device_id === device && !e.hidden) + .map((e) => e.entity_id) + .filter((id) => hass.states[id]); +} + +export interface AccessPointInfo { + /** Devices connected now (null: it does not tell). */ + clients: number | null; + online: boolean; +} + +/** What an access point reports: its clients (a "clients"/"stations"/"connected" sensor) and whether it is up. */ +export function readAccessPoint(hass: HomeAssistant, anchor: string | null): AccessPointInfo | null { + if (!anchor || !hass.states[anchor]) return null; + const all = siblings(hass, anchor); + const count = all.find((id) => id.startsWith("sensor.") && has(id, "clients", "stations", "connected_devices", "users", "geräte", "wlan_clients") && Number.isFinite(Number(hass.states[id].state))); + const status = all.map((id) => hass.states[id]).find((s) => s.entity_id.startsWith("binary_sensor.") && (s.attributes.device_class === "connectivity" || has(s.entity_id, "online", "connected", "status"))); + const st = hass.states[anchor]; + const down = ["unavailable", "off", "disconnected", "offline"].includes(String(status?.state ?? st.state).toLowerCase()) && (!!status || st.entity_id.startsWith("binary_sensor.")); + return { clients: count ? Number(hass.states[count].state) : null, online: !down && st.state !== "unavailable" }; +} + +/** The coverage colour of an access point: blue while it has room, amber when busy, red when it is down. */ +export function coverageColor(ap: AccessPointInfo): [number, number, number] { + if (!ap.online) return [1, 0.3, 0.3]; + if ((ap.clients ?? 0) >= 30) return [1, 0.72, 0.25]; + return [0.3, 0.7, 1]; +} + +/** Network devices of the house (connectivity sensors and router trackers among the given entities): how many are online. */ +export function networkHealth(states: (HassEntity | undefined)[]): { online: number; offline: string[] } { + let online = 0; + const offline: string[] = []; + for (const s of states) { + if (!s) continue; + const connectivity = s.entity_id.startsWith("binary_sensor.") && s.attributes.device_class === "connectivity"; + const tracker = s.entity_id.startsWith("device_tracker.") && s.attributes.source_type === "router"; + if (!connectivity && !tracker) continue; + if (s.state === "on" || s.state === "home") online++; + else offline.push(String(s.attributes.friendly_name ?? s.entity_id)); + } + return { online, offline }; +} diff --git a/frontend/src/load-card-editor.ts b/frontend/src/load-card-editor.ts new file mode 100644 index 0000000..ff6967a --- /dev/null +++ b/frontend/src/load-card-editor.ts @@ -0,0 +1,12 @@ +// Loads the card's visual editor only when the dashboard opens it (it defines ). + +/** Content hash of the card editor bundle, set by the build (see build.mjs). */ +declare const __NF_CARD_EDITOR_HASH__: string; + +let loading: Promise | undefined; + +export function loadCardEditor(): Promise { + const url = new URL(`./nextfloor-card-editor.js?v=${__NF_CARD_EDITOR_HASH__}`, new URL(import.meta.url)).href; + loading ??= import(/* @vite-ignore */ url); + return loading; +} diff --git a/frontend/src/load-editor.ts b/frontend/src/load-editor.ts new file mode 100644 index 0000000..d1fd314 --- /dev/null +++ b/frontend/src/load-editor.ts @@ -0,0 +1,12 @@ +// Loads the editor bundle only when the editor is opened (it defines ). + +/** Content hash of the editor bundle, set by the build (see build.mjs). */ +declare const __NF_EDITOR_HASH__: string; + +let loading: Promise | undefined; + +export function loadEditor(): Promise { + const url = new URL(`./nextfloor-editor.js?v=${__NF_EDITOR_HASH__}`, new URL(import.meta.url)).href; + loading ??= import(/* @vite-ignore */ url); + return loading; +} diff --git a/frontend/src/load3d.ts b/frontend/src/load3d.ts new file mode 100644 index 0000000..cf739a0 --- /dev/null +++ b/frontend/src/load3d.ts @@ -0,0 +1,18 @@ +// Loads the three.js bundle only when a 3D view is opened. + +import type * as Viewer from "./viewer/viewer3d.ts"; + +export type ViewerModule = typeof Viewer; + +/** Content hash of the 3D bundle, set by the build (see build.mjs). */ +declare const __NF_VIEWER_HASH__: string; + +const base = new URL(import.meta.url); +const url = new URL(`./nextfloor-3d.js?v=${__NF_VIEWER_HASH__}`, base).href; + +let loading: Promise | undefined; + +export function load3d(): Promise { + loading ??= import(/* @vite-ignore */ url) as Promise; + return loading; +} diff --git a/frontend/src/main.ts b/frontend/src/main.ts new file mode 100644 index 0000000..f7ebcaa --- /dev/null +++ b/frontend/src/main.ts @@ -0,0 +1,10 @@ +// Main bundle: sidebar panel, dashboard card and editor. three.js is loaded separately on demand. + +import "./polyfills.ts"; +import "./panel.ts"; +import "./card.ts"; + +import { installPluginGlobal } from "./plugins/loader.ts"; + +// window.NextFloor for plugins; picks up plugins a dashboard resource queued before NextFloor loaded +installPluginGlobal(); diff --git a/frontend/src/map-geo.test.ts b/frontend/src/map-geo.test.ts new file mode 100644 index 0000000..55a332f --- /dev/null +++ b/frontend/src/map-geo.test.ts @@ -0,0 +1,61 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { mapCredit, mapOfPlan, mapShown, mapTiles, planOfMap, templateOf, tileMetres, tileOf, tileUrl, OSM_URL } from "./map-geo.ts"; + +test("a place has the well-known tile number", () => { + // Greenwich Observatory at zoom 10 lies in tile 511 / 340 + const [x, y] = tileOf(51.4779, -0.0015, 10); + assert.equal(Math.floor(x), 511); + assert.equal(Math.floor(y), 340); + const [x0, y0] = tileOf(0, 0, 1); + assert.deepEqual([x0, y0], [1, 1]); +}); + +test("a tile is about 98 m wide at zoom 18 near 50° north", () => { + assert.ok(Math.abs(tileMetres(50, 18) - 98.3) < 0.5); +}); + +test("the tiles around the anchor cover the square, and the anchor's own tile lies around the origin", () => { + const tiles = mapTiles(50.11, 8.68, 18, 160); + assert.ok(tiles.length >= 9 && tiles.length <= 36, String(tiles.length)); + const east = tiles.map((t) => t.east); + assert.ok(Math.min(...east) <= -160 && Math.max(...east.map((e, i) => e + tiles[i].size)) >= 160); + const holder = tiles.find((t) => t.east <= 0 && t.east + t.size > 0 && t.north >= 0 && t.north - t.size < 0); + assert.ok(holder, "one tile contains the anchor"); + assert.equal(new Set(tiles.map((t) => `${t.x}/${t.y}`)).size, tiles.length); +}); + +test("tile addresses fill the template", () => { + assert.equal(tileUrl(OSM_URL, { x: 5, y: 6, z: 7 }), "https://tile.openstreetmap.org/7/5/6.png"); + assert.equal(tileUrl("https://{s}.example/{z}/{x}/{y}.jpg", { x: 1, y: 2, z: 3 }), "https://a.example/3/1/2.jpg"); + assert.equal(templateOf({ url: null }), OSM_URL); + assert.equal(templateOf({ url: "http://insecure/{z}" }), OSM_URL, "only https is used"); +}); + +test("the plan's north turns the map: north up leaves it, 180° swaps north and south", () => { + const anchor = { x: 10, z: 20 }; + assert.deepEqual(planOfMap(0, 5, 0, anchor).map((v) => Math.round(v * 1e6) / 1e6), [10, 15], "5 m north is up (-z)"); + assert.deepEqual(planOfMap(5, 0, 0, anchor).map((v) => Math.round(v * 1e6) / 1e6), [15, 20], "5 m east is right"); + assert.deepEqual(planOfMap(0, 5, 180, anchor).map((v) => Math.round(v * 1e6) / 1e6), [10, 25], "north points down when the plan's north is down"); + assert.deepEqual(planOfMap(0, 5, 90, anchor).map((v) => Math.round(v * 1e6) / 1e6), [15, 20], "north points right"); +}); + +test("plan and map convert back and forth", () => { + const anchor = { x: -3, z: 7 }; + for (const north of [0, 37, 180, 271]) { + const [x, z] = planOfMap(12, -8, north, anchor); + const [e, n] = mapOfPlan(x, z, north, anchor); + assert.ok(Math.abs(e - 12) < 1e-9 && Math.abs(n + 8) < 1e-9, `north ${north}`); + } +}); + +test("a map shows only when it is on and has a place", () => { + assert.equal(mapShown(null), false); + assert.equal(mapShown({ on: false, lat: 1, lon: 1 }), false); + assert.equal(mapShown({ on: true, lat: 1, lon: 1 }), true); +}); + +test("the credit names OpenStreetMap, or the host of a custom address", () => { + assert.equal(mapCredit({ url: null }).text, "© OpenStreetMap contributors"); + assert.equal(mapCredit({ url: "https://tiles.example.org/{z}/{x}/{y}.png" }).text, "Map: tiles.example.org"); +}); diff --git a/frontend/src/map-geo.ts b/frontend/src/map-geo.ts new file mode 100644 index 0000000..6f48e52 --- /dev/null +++ b/frontend/src/map-geo.ts @@ -0,0 +1,98 @@ +// The geometry of the real map under the plan: which map tiles cover the house and where each one lies in the plan. +// The plan has an anchor point (map.x / map.z, metres) that lies at map.lat / map.lon, and the plan's north (settings.north) +// says how the map is turned. Pure functions: no Lit, no three.js, no network. + +import type { MapSettings } from "./model.ts"; + +export const OSM_URL = "https://tile.openstreetmap.org/{z}/{x}/{y}.png"; +export const OSM_ATTRIBUTION = "© OpenStreetMap contributors"; +/** The earth's circumference at the equator (m). */ +const EARTH = 40075016.686; +const DEG = Math.PI / 180; + +export const DEFAULT_MAP_ZOOM = 18; +export const DEFAULT_MAP_OPACITY = 0.5; +/** Half the side of the square the map covers around the anchor (m). */ +export const MAP_RADIUS = 160; + +/** Where a tile lies: its top-left corner in the map frame (metres east and north of the anchor) and its side. */ +export interface MapTile { + x: number; + y: number; + z: number; + east: number; + north: number; + size: number; +} + +/** The tile number (fractional) that holds a place, in Web Mercator at zoom `z`. */ +export function tileOf(lat: number, lon: number, z: number): [number, number] { + const n = 2 ** z; + const x = ((lon + 180) / 360) * n; + const y = ((1 - Math.log(Math.tan(lat * DEG) + 1 / Math.cos(lat * DEG)) / Math.PI) / 2) * n; + return [x, y]; +} + +/** The side of a tile in real metres at the anchor's latitude. */ +export const tileMetres = (lat: number, z: number): number => (EARTH * Math.cos(lat * DEG)) / 2 ** z; + +/** Every tile that touches the square of `radius` metres around the anchor, with its place in the map frame. */ +export function mapTiles(lat: number, lon: number, zoom: number, radius = MAP_RADIUS): MapTile[] { + const [cx, cy] = tileOf(lat, lon, zoom); + const size = tileMetres(lat, zoom); + const span = radius / size; + const last = 2 ** zoom - 1; + const tiles: MapTile[] = []; + for (let y = Math.floor(cy - span); y <= Math.floor(cy + span); y++) { + for (let x = Math.floor(cx - span); x <= Math.floor(cx + span); x++) { + if (y < 0 || y > last) continue; + const wrapped = ((x % (last + 1)) + last + 1) % (last + 1); + tiles.push({ x: wrapped, y, z: zoom, east: (x - cx) * size, north: -(y - cy) * size, size }); + } + } + return tiles; +} + +/** The address of a tile from a template with {z}, {x} and {y} (and {s}: a, b or c). */ +export function tileUrl(template: string, tile: Pick): string { + return template.replace("{z}", String(tile.z)).replace("{x}", String(tile.x)).replace("{y}", String(tile.y)).replace("{s}", "abc"[(tile.x + tile.y) % 3]); +} + +/** The template a map uses: its own, or OpenStreetMap's. */ +export const templateOf = (map: Pick): string => (map.url && map.url.startsWith("https://") ? map.url : OSM_URL); + +/** A point of the map frame (metres east, north of the anchor) in the plan, turned by the plan's north (degrees clockwise from up). */ +export function planOfMap(east: number, north: number, planNorth: number, anchor: { x: number; z: number }): [number, number] { + const a = planNorth * DEG; + return [anchor.x + east * Math.cos(a) + north * Math.sin(a), anchor.z + east * Math.sin(a) - north * Math.cos(a)]; +} + +/** The inverse: a plan point as metres east and north of the anchor. */ +export function mapOfPlan(x: number, z: number, planNorth: number, anchor: { x: number; z: number }): [number, number] { + const a = planNorth * DEG; + const [dx, dz] = [x - anchor.x, z - anchor.z]; + return [dx * Math.cos(a) + dz * Math.sin(a), dx * Math.sin(a) - dz * Math.cos(a)]; +} + +/** A map the settings ask for: switched on and with a place on Earth. */ +export const mapShown = (map: MapSettings | null | undefined): map is MapSettings => !!map && map.on === true && Number.isFinite(map.lat) && Number.isFinite(map.lon); + +/** The anchor, the opacity and the zoom of a map with the defaults filled in. */ +export const mapLook = (map: MapSettings): { x: number; z: number; opacity: number; zoom: number } => ({ + x: map.x ?? 0, + z: map.z ?? 0, + opacity: map.opacity ?? DEFAULT_MAP_OPACITY, + zoom: map.zoom ?? DEFAULT_MAP_ZOOM, +}); + +/** The credit line of a map: OpenStreetMap's own, or the host of a custom tile address. */ +export function mapCredit(map: Pick): { text: string; href: string } { + const template = templateOf(map); + if (template === OSM_URL) return { text: OSM_ATTRIBUTION, href: "https://www.openstreetmap.org/copyright" }; + try { + const host = new URL(template.replace(/\{[a-z]\}/g, "a")).host; + return { text: `Map: ${host}`, href: `https://${host}/` }; + } catch { + return { text: "Map", href: "#" }; + } +} diff --git a/frontend/src/markers.test.ts b/frontend/src/markers.test.ts new file mode 100644 index 0000000..0c50cf4 --- /dev/null +++ b/frontend/src/markers.test.ts @@ -0,0 +1,111 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { buildMarkers, eventText, placedEntities, scaleGlow, stateText, toggleEntity } from "./markers.ts"; +import { emptyBuilding, newFloor } from "./model.ts"; +import type { HassEntity, HomeAssistant } from "./types.ts"; + +const state = (entity_id: string, value: string, attributes: Record = {}): HassEntity => ({ entity_id, state: value, attributes }); + +function hassOf(list: HassEntity[], extra: Record = {}): HomeAssistant { + const calls: unknown[][] = []; + return { + language: "en", + areas: { lounge: { area_id: "lounge", name: "Lounge" } }, + states: Object.fromEntries(list.map((s) => [s.entity_id, s])), + callService: async (...args: unknown[]) => void calls.push(args), + calls, + ...extra, + } as unknown as HomeAssistant; +} + +test("lights show brightness in percent, or on/off", () => { + const hass = hassOf([]); + assert.equal(stateText(hass, state("light.a", "on", { brightness: 255 })), "100 %"); + assert.equal(stateText(hass, state("light.a", "on")), "On"); + assert.equal(stateText(hass, state("light.a", "off")), "Off"); +}); + +test("covers show their position, except while they move", () => { + const hass = hassOf([]); + assert.equal(stateText(hass, state("cover.a", "open", { current_position: 30 })), "30 %"); + assert.notEqual(stateText(hass, state("cover.a", "opening", { current_position: 30 })), "30 %"); +}); + +test("a sensor prints its value with its unit, and a word state stays a word", () => { + const hass = hassOf([]); + assert.equal(stateText(hass, state("sensor.t", "21.44", { unit_of_measurement: "°C" })), "21.4 °C"); + assert.equal(stateText(hass, state("sensor.s", "sunny")), "sunny"); + const precise = hassOf([], { entities: { "sensor.gas": { entity_id: "sensor.gas", display_precision: 3 } } }); + assert.equal(stateText(precise, state("sensor.gas", "1234.5678", { unit_of_measurement: "m³" })), "1,234.568 m³"); +}); + +test("a media player shows what runs, a heater its temperature", () => { + const hass = hassOf([]); + assert.equal(stateText(hass, state("media_player.tv", "playing", { app_name: "Netflix", media_title: "Show" })), "Netflix"); + assert.equal(stateText(hass, state("media_player.tv", "playing", { media_title: "Show" })), "Show"); + assert.equal(stateText(hass, state("climate.h", "heat", { current_temperature: 20.5 })), "20.5 °C"); + assert.equal(stateText(hass, state("climate.h", "off", { current_temperature: 20.5 })), "20.5 °C · Off"); +}); + +test("unknown or unavailable entities read as unavailable", () => { + const hass = hassOf([]); + assert.equal(stateText(hass, undefined), stateText(hass, state("light.a", "unavailable"))); +}); + +test("scaleGlow clamps the level and leaves glows alone when the factor is neutral", () => { + const glow = { level: 1 }; + assert.equal(scaleGlow(glow, 1), glow); + assert.equal(scaleGlow(glow, null), glow); + assert.equal(scaleGlow(null, 2), null); + assert.equal(scaleGlow(glow, 10)?.level, 1.5); + assert.equal(scaleGlow(glow, 0)?.level, 0.02); + assert.equal(scaleGlow(glow, 0.5)?.level, 0.5); +}); + +test("markers: placed entities that exist get one, with their room and a default height", () => { + const building = emptyBuilding(); + const floor = newFloor("g", "Ground", 0); + floor.rooms = [{ id: "r", name: "Lounge room", area_id: "lounge", points: [[0, 0], [4, 0], [4, 3], [0, 3]], floor_material: "wood" }]; + floor.placements = [ + { entity_id: "light.a", x: 1, z: 1, y: null, mount: null }, + { entity_id: "light.gone", x: 1, z: 1, y: null, mount: null }, + { entity_id: "sensor.t", x: 9, z: 9, y: 1.7, mount: null, name: "Own name" }, + ]; + building.floors = [floor]; + const hass = hassOf([state("light.a", "on", { friendly_name: "Lamp" }), state("sensor.t", "20")]); + const markers = buildMarkers(hass, building); + assert.deepEqual(markers.map((m) => m.id), ["light.a", "sensor.t"]); + assert.equal(markers[0].roomId, "r"); + assert.equal(markers[0].lamp, "ceiling"); + assert.equal(markers[0].active, true); + assert.equal(markers[1].roomId, null); + assert.equal(markers[1].y, 1.7); + assert.equal(markers[1].name, "Own name"); + assert.deepEqual(placedEntities(building), ["light.a", "light.gone", "sensor.t"]); +}); + +test("toggling uses the service of the entity's own domain", async () => { + const hass = hassOf([]) as HomeAssistant & { calls: unknown[][] }; + await toggleEntity(hass, "switch.pump"); + assert.deepEqual(hass.calls[0], ["switch", "toggle", { entity_id: "switch.pump" }]); +}); + +test("a wall button (event entity) shows when it was last pressed, and a dash before its first press", () => { + const hass = hassOf([]); + const now = new Date(2026, 10, 1, 18, 0); + const pressed = state("event.hall_button", new Date(2026, 10, 1, 14, 32).toISOString(), { event_type: "press_short" }); + assert.match(eventText(hass, pressed, now), /14:32|2:32/); + assert.match(eventText(hass, state("event.hall_button", new Date(2026, 9, 30, 8, 5).toISOString()), now), /30/); + assert.equal(stateText(hass, state("event.hall_button", "unknown")), "–"); + assert.equal(stateText(hass, state("event.hall_button", "unavailable")), "Unavailable"); +}); + +test("a placed wall button gets a marker", () => { + const building = emptyBuilding(); + const floor = newFloor("g", "Ground", 0); + floor.placements = [{ entity_id: "event.hall_button", x: 1, z: 1, y: null, mount: null }]; + building.floors = [floor]; + const markers = buildMarkers(hassOf([state("event.hall_button", "unknown")]), building); + assert.equal(markers.length, 1); + assert.equal(markers[0].unavailable, false); +}); diff --git a/frontend/src/markers.ts b/frontend/src/markers.ts new file mode 100644 index 0000000..780b705 --- /dev/null +++ b/frontend/src/markers.ts @@ -0,0 +1,175 @@ +// Device markers for the 3D view, built from placed entities and their states, plus the short state +// texts that markers and the room panel share. + +import { defaultHeight, entityName, isActive, isUnavailable, kindOf, lightGlow, tempUnit } from "./devices.ts"; +import { formatNumber, translate, type I18nKey } from "./i18n.ts"; +import { iconSvg, mdiIcon } from "./icons.ts"; +import { ceilingAt, offsetAt, pointInPolygon, type Building, type Floor, type Placement, type Room } from "./model.ts"; +import type { HassEntity, HomeAssistant } from "./types.ts"; +import type { DeviceMarker } from "./viewer/viewer3d.ts"; +import { lightAnimation } from "./light-effects.ts"; +import { pluginFloorWedge, pluginKind, pluginMarkerPatch } from "./plugins/registry.ts"; + +type Hass = HomeAssistant | undefined; + +const say = (hass: Hass, key: I18nKey) => translate(hass, key); +const onOff = (hass: Hass, on: boolean) => say(hass, on ? "state_on" : "state_off"); + +/** A state word translated when there is a translation, else shown as it is. */ +function stateWord(hass: Hass, state: string): string { + const key = `state_${state}` as I18nKey; + const word = translate(hass, key); + return word === key ? state : word; +} + +const OPENING_CLASSES = new Set(["door", "window", "opening", "garage_door"]); +const MEDIA_RUNNING = new Set(["playing", "paused", "on", "idle"]); + +function lightText(hass: Hass, st: HassEntity): string { + if (st.state !== "on") return say(hass, "state_off"); + const brightness = st.attributes.brightness; + return typeof brightness === "number" ? `${Math.round((brightness / 255) * 100)} %` : say(hass, "state_on"); +} + +function coverText(hass: Hass, st: HassEntity): string { + const position = st.attributes.current_position; + const moving = st.state === "opening" || st.state === "closing"; + return typeof position === "number" && !moving ? `${position} %` : stateWord(hass, st.state); +} + +function climateText(hass: Hass, st: HassEntity): string { + const current = st.attributes.current_temperature; + const reading = typeof current === "number" ? `${formatNumber(hass, current, 1)} ${hass ? tempUnit(hass) : "°C"}` : null; + if (st.state === "off") return reading ? `${reading} · ${say(hass, "state_off")}` : say(hass, "state_off"); + return reading ?? stateWord(hass, st.state); +} + +function mediaText(hass: Hass, st: HassEntity): string { + // while something runs: the app (Netflix ...), else the title, else the input source + const label = [st.attributes.app_name, st.attributes.media_title, st.attributes.source].find((v): v is string => typeof v === "string" && v !== ""); + return MEDIA_RUNNING.has(st.state) && label ? label : stateWord(hass, st.state); +} + +function binaryText(hass: Hass, st: HassEntity): string { + const on = st.state === "on"; + if (OPENING_CLASSES.has(String(st.attributes.device_class))) return say(hass, on ? "state_open" : "state_closed"); + return say(hass, on ? "state_detected" : "state_clear"); +} + +/** When a wall button (event entity) was last pressed: the time today, else the day and time; a dash before its first press. */ +export function eventText(hass: Hass, st: HassEntity, now = new Date()): string { + const when = new Date(st.state); + if (Number.isNaN(when.getTime())) return "–"; + const locale = hass?.language ?? navigator.language; + const today = when.toDateString() === now.toDateString(); + const options: Intl.DateTimeFormatOptions = today ? { hour: "2-digit", minute: "2-digit" } : { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }; + return new Intl.DateTimeFormat(locale, options).format(when); +} + +function sensorText(hass: Hass, st: HassEntity): string { + if (st.entity_id.startsWith("event.")) return eventText(hass, st); + const value = Number(st.state); + if (!Number.isFinite(value)) return st.state; + // the decimals chosen in Home Assistant win (a gas meter reads 1234.567 m³) + const digits = hass?.entities?.[st.entity_id]?.display_precision ?? 1; + const unit = st.attributes.unit_of_measurement; + return `${formatNumber(hass, value, digits)}${typeof unit === "string" && unit ? ` ${unit}` : ""}`; +} + +/** Short state text, in the user's language, for a marker or a row of the room panel. */ +export function stateText(hass: Hass, st: HassEntity | undefined): string { + if (!st || isUnavailable(st)) return say(hass, "state_unavailable"); + switch (kindOf(st.entity_id)) { + case "light": + return lightText(hass, st); + case "switch": + case "fan": + // a valve says open or closed, like a blind + if (st.entity_id.startsWith("valve.")) return coverText(hass, st); + return onOff(hass, st.state === "on"); + case "cover": + return coverText(hass, st); + case "climate": + return climateText(hass, st); + case "media": + return mediaText(hass, st); + case "lock": + return stateWord(hass, st.state); + case "binary": + return binaryText(hass, st); + case "sensor": + return sensorText(hass, st); + default: + return ""; + } +} + +const roomAt = (floor: Floor, x: number, z: number): Room | null => floor.rooms.find((room) => room.points.length >= 3 && pointInPolygon([x, z], room.points)) ?? null; + +/** A lamp's glow made stronger or weaker by its own factor, so a row of LED strips need not outshine a room. */ +export function scaleGlow(glow: T | null, factor: number | null | undefined): T | null { + if (!glow || factor == null || factor === 1) return glow; + return { ...glow, level: Math.min(1.5, Math.max(0.02, glow.level * factor)) }; +} + +function markerFor(hass: HomeAssistant, floor: Floor, placed: Placement): DeviceMarker | null { + const st = hass.states[placed.entity_id]; + // a plugin may take on entities of domains NextFloor does not know + const kind = kindOf(placed.entity_id) ?? pluginKind(placed.entity_id, st); + if (!kind || !st) return null; + // a device that belongs to Outside never counts for the room under it + const room = placed.outside ? null : roomAt(floor, placed.x, placed.z); + const areaName = room?.area_id ? hass.areas?.[room.area_id]?.name : undefined; + const marker: DeviceMarker = { + id: placed.entity_id, + floorId: floor.id, + roomId: room?.id ?? null, + x: placed.x, + z: placed.z, + // a pin in a room on its own level moves with its floor; a ceiling light keeps to the ceiling + y: placed.y ?? defaultHeight(kind, ceilingAt(floor, placed.x, placed.z), placed.mount ?? null) + (kind === "light" && (placed.mount ?? "ceiling") === "ceiling" ? 0 : offsetAt(floor, placed.x, placed.z)), + lamp: kind === "light" ? (placed.mount ?? "ceiling") : null, + ceiling: ceilingAt(floor, placed.x, placed.z), + rotation: placed.rotation ?? 0, + icon: placed.icon ? mdiIcon(placed.icon) : iconSvg(kind), + name: placed.name || entityName(hass, placed.entity_id, areaName), + ownName: placed.name || undefined, + showName: !!placed.show_name, + text: stateText(hass, st), + active: isActive(st), + unavailable: isUnavailable(st), + glow: kind === "light" ? scaleGlow(lightGlow(st), placed.glow_scale) : null, + effect: kind === "light" ? lightAnimation(placed, st) : undefined, + show: placed.marker ?? undefined, + fixed: !!placed.locked, + }; + // a plugin may draw a shape on the floor from the device (a camera's field of view) + marker.wedge = pluginFloorWedge({ hass, entityId: placed.entity_id, state: st }, { floorId: floor.id, roomId: marker.roomId, x: marker.x, z: marker.z, y: marker.y, rotation: marker.rotation ?? 0 }, placed.plugin ?? undefined); + return withPluginPatch(hass, marker, st, !!placed.icon); +} + +/** Applies what plugins change on a marker; an icon the user picked in the plan stays. */ +export function withPluginPatch>(hass: HomeAssistant, marker: M, st: HassEntity, ownIcon: boolean): M { + const patch = pluginMarkerPatch({ hass, entityId: marker.id, state: st }); + if (!patch) return marker; + const icon = patch.icon && !ownIcon ? (patch.icon.trimStart().startsWith(" floor.placements.map((placed) => markerFor(hass, floor, placed)).filter((m): m is DeviceMarker => m !== null)); +} + +/** Every entity that is placed somewhere in the building. */ +export const placedEntities = (building: Building): string[] => building.floors.flatMap((floor) => floor.placements.map((p) => p.entity_id)); + +/** Opens the more-info dialog of Home Assistant for an entity. */ +export function openMoreInfo(from: HTMLElement, entityId: string): void { + from.dispatchEvent(new CustomEvent("hass-more-info", { detail: { entityId }, bubbles: true, composed: true })); +} + +/** Switches an entity with the toggle service of its own domain. */ +export function toggleEntity(hass: HomeAssistant, entityId: string): Promise { + return hass.callService(entityId.split(".")[0], "toggle", { entity_id: entityId }); +} diff --git a/frontend/src/model-slots.test.ts b/frontend/src/model-slots.test.ts new file mode 100644 index 0000000..2da77e7 --- /dev/null +++ b/frontend/src/model-slots.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { BYTES_PER_TRIANGLE, DETAIL_LEVELS, MAX_UPLOAD_BYTES, maxTrianglesForLimit, meshPath, modelSlots, readableSize, trianglesFor, uploadProblem } from "./model-slots.ts"; +import type { FurniturePack } from "./packs.ts"; + +const pack = (id: string, name: string, items: { id: string; name: string; mesh?: string }[]): FurniturePack => + ({ id, name, publisher: "x", items: items.map((i) => ({ id: i.id, name: { en: i.name }, size: [1, 1, 1], parts: [], mesh: i.mesh })) }) as unknown as FurniturePack; + +test("the slots are the models the packs ask for, once each, with the items that use them", () => { + const slots = modelSlots([pack("cars", "Cars", [{ id: "a", name: "Model Y", mesh: "tesla_y" }, { id: "b", name: "Model Y Long", mesh: "tesla_y" }, { id: "c", name: "Truck", mesh: "truck" }, { id: "d", name: "Plain" }]), pack("more", "More", [{ id: "e", name: "Apple", mesh: "apple" }])], "en"); + assert.deepEqual(slots.map((s) => s.id), ["apple", "tesla_y", "truck"]); + assert.equal(slots[1].items.length, 2); + assert.ok(slots[1].items[0].includes("Model Y") && slots[1].items[0].includes("Cars")); + assert.deepEqual(modelSlots([], "en"), []); +}); + +test("the path names the model and escapes odd ids", () => { + assert.equal(meshPath("tesla_y"), "/api/nextfloor/mesh/tesla_y"); + assert.equal(meshPath("a b"), "/api/nextfloor/mesh/a%20b"); +}); + +test("sizes read like people say them", () => { + assert.equal(readableSize(100), "1 KB"); + assert.equal(readableSize(840 * 1024), "840 KB"); + assert.equal(readableSize(3.2 * 1024 * 1024), "3.2 MB"); +}); + +test("the answers of the upload map to a reason, and success to nothing", () => { + for (const ok of [200, 201, 204]) assert.equal(uploadProblem(ok), null); + assert.equal(uploadProblem(401), "forbidden"); + assert.equal(uploadProblem(413), "too_large"); + assert.equal(uploadProblem(400), "not_glb"); + assert.equal(uploadProblem(404), "bad_id"); + assert.equal(uploadProblem(500), "other"); +}); + +test("the detail levels never ask for more triangles than the file limit allows", () => { + assert.equal(maxTrianglesForLimit(120_000), 2400); + assert.ok(maxTrianglesForLimit() * BYTES_PER_TRIANGLE <= MAX_UPLOAD_BYTES); + assert.equal(trianglesFor("light"), 30_000); + assert.ok(DETAIL_LEVELS.every((l) => trianglesFor(l.key) <= maxTrianglesForLimit())); +}); diff --git a/frontend/src/model-slots.ts b/frontend/src/model-slots.ts new file mode 100644 index 0000000..584c4e4 --- /dev/null +++ b/frontend/src/model-slots.ts @@ -0,0 +1,61 @@ +// The 3D models a user can add: which items of the packs name one, where it lives on Home Assistant, and what the answers of the +// upload mean in words. + +import { packItemLabel, packLabel } from "./furniture-names.ts"; +import { packType, type FurniturePack } from "./packs.ts"; + +/** Where a model lives on the user's Home Assistant. */ +export const meshPath = (id: string): string => `/api/nextfloor/mesh/${encodeURIComponent(id)}`; + +/** The largest file Home Assistant takes, as the server limits it. */ +export const MAX_UPLOAD_BYTES = 12 * 1024 * 1024; + +export interface ModelSlot { + /** The id the file is stored under. */ + id: string; + /** Item names that use this model, with their packs: several items can share one. */ + items: string[]; +} + +/** The models the packs ask for, each once, with the items that use it, sorted by what they are called. */ +export function modelSlots(packs: readonly FurniturePack[], language: string): ModelSlot[] { + const byId = new Map(); + for (const pack of packs) { + for (const item of pack.items) { + if (!item.mesh) continue; + const names = byId.get(item.mesh) ?? []; + byId.set(item.mesh, [...names, `${packItemLabel(item, packType(pack.id, item.id), language)} · ${packLabel(pack, language)}`]); + } + } + return [...byId].map(([id, items]) => ({ id, items })).sort((a, b) => a.items[0].localeCompare(b.items[0])); +} + +/** A size as people read it: 840 KB, 3.2 MB. */ +export function readableSize(bytes: number): string { + return bytes < 1024 * 1024 ? `${Math.max(1, Math.round(bytes / 1024))} KB` : `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +export type UploadProblem = "forbidden" | "too_large" | "not_glb" | "bad_id" | "other"; + +/** What an answer of the upload means. Null when it went through. */ +export function uploadProblem(status: number): UploadProblem | null { + if (status === 201 || status === 200 || status === 204) return null; + if (status === 401 || status === 403) return "forbidden"; + if (status === 413) return "too_large"; + if (status === 400) return "not_glb"; + if (status === 404) return "bad_id"; + return "other"; +} + +/** How many triangles a model may keep so that the prepared file stays under the limit: a plain glTF costs about 15 to 20 bytes each, so 40 is a safe allowance. */ +export const BYTES_PER_TRIANGLE = 40; +export const maxTrianglesForLimit = (bytes = MAX_UPLOAD_BYTES): number => Math.floor((bytes * 0.8) / BYTES_PER_TRIANGLE); + +/** The levels of detail offered, as the most triangles each allows. */ +export const DETAIL_LEVELS = [{ key: "light", triangles: 30_000 }, { key: "normal", triangles: 80_000 }, { key: "fine", triangles: 150_000 }] as const; +export type DetailKey = (typeof DETAIL_LEVELS)[number]["key"]; + +/** The triangles for a level, never more than the file limit allows. */ +export function trianglesFor(level: DetailKey): number { + return Math.min(DETAIL_LEVELS.find((l) => l.key === level)!.triangles, maxTrianglesForLimit()); +} diff --git a/frontend/src/model.test.ts b/frontend/src/model.test.ts new file mode 100644 index 0000000..f1c4361 --- /dev/null +++ b/frontend/src/model.test.ts @@ -0,0 +1,172 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, floorElevation, newFloor, openingPreset, openingStyle, normalizeBuilding, outdoorDrop, outdoorGround, resizeFurniture, roomTiles, sidelightLayout, spotGrid, surfaceHeight, type Furniture } from "./model.ts"; + +test("a sidelight sits opposite the hinge, on the hinge side when asked, and keeps the leaf at least half a metre", () => { + const none = {}; + // hinge at the start: the panel at the end, the leaf from the start + let l = sidelightLayout(1.6, "sidelight", true, none)!; + assert.equal(l.panels.length, 1); + assert.ok(l.panels[0][0] > 0.8 && Math.abs(l.panels[0][1] - 1.58) < 1e-9); + assert.equal(l.x0, 0.02); + // on the hinge side instead + l = sidelightLayout(1.6, "sidelight", true, { sidelight_hinge: true })!; + assert.equal(l.panels[0][0], 0.02); + assert.ok(l.x0 > 0.3); + // own widths, left and right, with two sidelights + l = sidelightLayout(2.4, "sidelights", false, { sidelight_width: 0.3, sidelight_width2: 0.6 })!; + assert.ok(Math.abs(l.panels[0][1] - 0.32) < 1e-9 && Math.abs(l.panels[1][0] - 1.78) < 1e-9); + assert.ok(Math.abs(l.x1 - l.x0 - (2.4 - 0.04 - 0.9)) < 1e-9); + // too wide: both shrink so the leaf keeps 0.5 m + l = sidelightLayout(1.4, "sidelights", false, { sidelight_width: 1, sidelight_width2: 1 })!; + assert.ok(Math.abs(l.x1 - l.x0 - 0.5) < 1e-9); + assert.equal(sidelightLayout(1.0, "front", true, none), null); +}); + +test("a door without a style is a front door in an exterior wall and a room door inside", () => { + assert.equal(openingStyle({ type: "door", style: null }, true), "front"); + assert.equal(openingStyle({ type: "door", style: null }, false), "interior"); + assert.equal(openingStyle({ type: "door", style: "sidelight" }, false), "sidelight"); + assert.equal(openingStyle({ type: "window", style: null }, true), "standard"); + // a window style on a door (or garbage) falls back to the automatic choice + assert.equal(openingStyle({ type: "door", style: "bars" }, true), "front"); + assert.equal(openingPreset({ type: "door", leaves: 1, sill: 0, style: "front_glass" }), "front"); + assert.equal(openingPreset({ type: "door", leaves: 1, sill: 0, style: null }), "door"); +}); + +const item = (type: string, x: number, z: number, h: number, extra: Partial = {}): Furniture => ({ + id: `${type}_${x}`, + type, + x, + z, + rotation: 0, + w: 1, + d: 0.6, + h, + variant: null, + ...extra, +}); + +test("lights placed as devices become lamps of their mount type", () => { + const b = emptyBuilding(); + const floor = newFloor("eg", "EG", 0); + floor.placements = [ + { entity_id: "light.decke", x: 1, z: 2, y: null, mount: null }, + { entity_id: "light.lese", x: 3, z: 1, y: null, mount: "floor" }, + { entity_id: "switch.tv", x: 2, z: 2, y: null }, + ]; + b.floors = [floor]; + const out = normalizeBuilding(b).floors[0]; + assert.deepEqual( + out.placements.map((p) => p.entity_id), + ["switch.tv"], + ); + assert.deepEqual( + out.furniture.map((f) => [f.type, f.entity, f.x, f.z]), + [ + ["lamp_ceiling", "light.decke", 1, 2], + ["lamp_floor", "light.lese", 3, 1], + ], + ); + // normalising again changes nothing + assert.equal(normalizeBuilding(b).floors[0].furniture.length, 2); +}); + +test("a table lamp stands on the furniture below it", () => { + const floor = newFloor("eg", "EG", 0); + floor.furniture = [item("nightstand", 1, 1, 0.5), item("table", 4, 1, 0.75), item("sofa", 7, 1, 0.8)]; + assert.equal(surfaceHeight(floor, 1.1, 1), 0.5); + assert.equal(surfaceHeight(floor, 4, 1.2), 0.75); + assert.equal(surfaceHeight(floor, 7, 1), 0, "no lamps on the sofa"); + assert.equal(surfaceHeight(floor, 10, 10), 0); +}); + +test("a spot grid spreads lamps evenly and leaves out cells outside an L-shaped room", () => { + const square = { id: "r", name: "R", area_id: null, points: [[0, 0], [4, 0], [4, 2], [0, 2]] as [number, number][], floor_material: "wood" }; + assert.deepEqual(spotGrid(square, 1, 2), [ + [1, 1], + [3, 1], + ]); + const l = { ...square, points: [[0, 0], [4, 0], [4, 2], [2, 2], [2, 4], [0, 4]] as [number, number][] }; + // 2 × 2 cells, the one at the bottom right lies outside the L + assert.equal(spotGrid(l, 2, 2).length, 3); +}); + +test("outdoor lamps stand on the ground, or on a terrace", () => { + const floor = newFloor("eg", "EG", 0); + floor.outdoor = [{ id: "t", type: "terrace", points: [[0, 0], [4, 0], [4, 3], [0, 3]] }]; + assert.equal(outdoorGround(floor, 10, 10), -0.2); + assert.ok(Math.abs(outdoorGround(floor, 2, 1) - (-0.2 + 0.12)) < 1e-9); + assert.equal(outdoorGround({ ...newFloor("og", "OG", 2.75), outdoor: [] }, 1, 1), 0); +}); + +test("resizing drags one corner while the opposite corner stays", () => { + const f: Furniture = { id: "f", type: "table", x: 1, z: 1, rotation: 0, w: 1, d: 1, h: 0.75, variant: null, entity: null, power: null }; + // pull the front-right corner from (1.5, 1.5) to (2.5, 2) + assert.deepEqual(resizeFurniture(f, [1, 1], [2.5, 2], 0.05), { x: 1.5, z: 1.25, w: 2, d: 1.5 }); + // turned by 90°: local x points along +z in the plan, so dragging along +z makes it wider + const turned = resizeFurniture({ ...f, rotation: 90 }, [1, 1], [0.5, 2.5], 0.05); + assert.equal(turned.w, 2); + assert.equal(turned.d, 1); + // never smaller than 10 cm + assert.equal(resizeFurniture(f, [1, 1], [0, 0], 0.05).w, 0.1); +}); + +test("floors from Home Assistant levels are stacked by level", () => { + assert.equal(floorElevation([], 0), 0); + assert.equal(floorElevation([], 1), 2.75); + assert.equal(floorElevation([], -1), -2.75); + // without a level, the new floor goes on top + assert.equal(floorElevation([newFloor("eg", "EG", 0)], null), 2.75); +}); + +test("rooms for areas are laid out beside the existing rooms", () => { + const floor = newFloor("eg", "EG", 0); + floor.rooms = [{ id: "r", name: "R", area_id: null, points: [[0, 0], [5, 0], [5, 4], [0, 4]], floor_material: "wood" }]; + let n = 0; + const rooms = roomTiles(floor, [{ area_id: "a", name: "Küche" }, { area_id: "b", name: "Bad" }, { area_id: "c", name: "Flur" }, { area_id: "d", name: "Büro" }], () => `t${n++}`); + assert.equal(rooms.length, 4); + assert.equal(rooms[0].name, "Küche"); + assert.equal(rooms[0].area_id, "a"); + assert.deepEqual(rooms[0].points[0], [6, 0]); + // three per row + assert.deepEqual(rooms[3].points[0], [6, 3.5]); +}); + +test("opening kinds: terrace doors are windows down to the floor, double ones have two leaves", () => { + assert.equal(openingPreset({ type: "window", leaves: 2, sill: 0 }), "terrace_double"); + assert.equal(openingPreset({ type: "window", leaves: 1, sill: 0.9 }), "window"); + assert.equal(openingPreset({ type: "door", leaves: 2, sill: 0 }), "door_double"); + assert.equal(openingPreset({ type: "garage", leaves: 1, sill: 0 }), "garage"); +}); + +test("a sloped area falls from its high edge to its low edge, lamps follow", () => { + const floor = newFloor("eg", "EG", 0); + floor.outdoor = [{ id: "d", type: "driveway", points: [[0, 0], [10, 0], [10, 3], [0, 3]], slope: 1.2, slope_dir: "-x" }]; + const a = floor.outdoor[0]; + assert.equal(outdoorDrop(a, 10, 1), 0); + assert.ok(Math.abs(outdoorDrop(a, 0, 1) - 1.2) < 1e-9); + assert.ok(Math.abs(outdoorDrop(a, 5, 1) - 0.6) < 1e-9); + assert.ok(Math.abs(outdoorGround(floor, 5, 1) - (-0.2 + 0.02 - 0.6)) < 1e-9); +}); + +test("a patch cut out of a lawn decides the ground inside it", () => { + const floor = newFloor("eg", "EG", 0); + floor.outdoor = [ + { id: "l", type: "lawn", points: [[0, 0], [10, 0], [10, 10], [0, 10]] }, + { id: "w", type: "wild", points: [[2, 2], [4, 2], [4, 4], [2, 4]], cut: true }, + ]; + assert.ok(Math.abs(outdoorGround(floor, 3, 3) - (-0.2 + 0.03)) < 1e-9); + assert.ok(Math.abs(outdoorGround(floor, 8, 8) - (-0.2 + 0.012)) < 1e-9); +}); + +test("a glass wall is a preset of its own (#163)", () => { + assert.equal(openingPreset({ type: "window", leaves: 1, sill: 0, style: "glass_wall" }), "glass_wall"); + assert.equal(openingPreset({ type: "window", leaves: 1, sill: 0, style: null }), "terrace"); +}); + +test("a sliding window down to the floor is a lift-and-slide door; with a sill it stays a window", () => { + assert.equal(openingPreset({ type: "window", leaves: 1, sill: 0, style: null, opens: "slide" }), "lift_slide"); + assert.equal(openingPreset({ type: "window", leaves: 2, sill: 0.02, style: null, opens: "slide" }), "lift_slide"); + assert.equal(openingPreset({ type: "window", leaves: 1, sill: 0.9, style: null, opens: "slide" }), "window"); +}); diff --git a/frontend/src/model.ts b/frontend/src/model.ts new file mode 100644 index 0000000..3538050 --- /dev/null +++ b/frontend/src/model.ts @@ -0,0 +1,1728 @@ +// Data model shared by editor, 3D view and backend (see custom_components/nextfloor/schema.py). +// Units are metres; x grows to the right, z grows downwards (as in the 2D editor). + +import type { PluginRef } from "./plugins/api.ts"; +import { packItem } from "./packs.ts"; +import type { LightEffectConfig } from "./light-effects.ts"; +import type { StairConfig } from "./geometry/stairs.ts"; +import type { LampModel } from "./viewer/viewer3d.ts"; +import type { FurnitureColors } from "./furniture-colors.ts"; +import type { ShowWhen } from "./entities/visibility.ts"; + +export type Vec2 = [number, number]; + +/** Sensors a room's climate is read from (null = automatic, "none" = no value). */ +export interface RoomClimate { + temperature?: string | string[] | null; + humidity?: string | string[] | null; + co2?: string | string[] | null; +} + +/** A wall height on a room edge, or one per part of a split edge. */ +export type WallHeight = number | null | (number | null)[]; + +export interface Room { + /** Room temperature, humidity and CO2: chosen sensors instead of the automatic pick. */ + climate?: RoomClimate | null; + id: string; + name: string; + area_id: string | null; + /** Home Assistant areas that are parts of this room without walls of their own (a reading corner, a shelf): their devices belong to it. */ + sub_areas?: string[] | null; + /** The camera the room opens with when it is tapped in 3D (null: framed from above). */ + start_view?: StartView | null; + points: Vec2[]; + floor_material: string; + /** Paint of the room's walls on its inside in the solid wall view ("#rrggbb"; null = the building's inside colour). */ + wall_paint?: string | null; + /** Entities shown in the room's panel although they are not in the plan. */ + panel?: string[]; + /** Entities of the room's area kept out of the room panel. */ + hidden?: string[]; + /** Entities whose state text the room panel leaves out (a cover that only reports "unknown", D154). */ + no_state?: string[]; + /** + * Height of the wall on each edge (index = edge points[i] -> points[i + 1]); null = full floor height, 0 = no + * wall. An edge that other rooms split into parts may carry a list instead: one height per part, in order. + */ + wall_heights?: WallHeight[]; + /** + * A sloping wall: the height at the END of each edge (index = edge). The edge's `wall_heights` entry is then its height at the START; the + * top runs straight between the two (a lean-to, a clerestory), and both may be above the floor height. null = a level wall. Whole edges only. + */ + wall_slopes?: (number | null)[]; + /** + * Thickness of the wall on each edge in m (index = edge); null = the building's exterior or interior + * thickness. A wall two rooms share takes the thicker of their settings (D149). A split edge may carry one thickness per part. + */ + wall_thickness?: (number | null | (number | null)[])[]; + /** + * Split points on each edge (index = edge): distances in metres from points[i] where the wall is cut + * into parts of their own (each with its own height), e.g. a 2.5 m wall next to a 1.7 m one in line. + */ + wall_splits?: (number[] | null)[]; + /** + * Height of this room's ceiling in m (null = the floor height): a low bathroom on a high floor. Ceiling lights, LED strips and ceiling-mounted + * items hang from it, and its walls default to it (a wall shared with a room without a ceiling of its own keeps the floor height). + */ + ceiling?: number | null; + /** Light moods saved in the room panel (the light designer): the lights as they were, to set again. */ + moods?: LightMood[]; + /** Whether the room counts as living area (null: by its name – a garage, cellar or utility room does not). */ + living?: boolean | null; + /** Cleaning: the script or button that sends the robot vacuum to this room (its panel shows "Clean"). */ + clean_entity?: string | null; + /** + * The room's floor lies this much below (negative) or above its floor's level, in m (a sunken entrance, a split level; #57). Its + * floor, the bottom of its walls, its doors and windows and what stands in it move with it; its ceiling stays where it is. + */ + floor_offset?: number | null; + /** Underfloor heating: the thermostat, valve or switch of the room's floor heating; its floor glows warm while it heats. */ + floor_heating?: string | null; + /** Announcements: the room's speaker (null = automatic, "none" = the room never speaks). */ + announce_speaker?: string | null; + /** Announcements to several rooms leave this room out from `from` to `to` ("HH:MM", may run over midnight). */ + announce_quiet?: { from: string; to: string } | null; +} + +export type OpeningType = "door" | "window" | "garage"; + +/** How a window's sash opens: turn (and tilt) into the room, slide along the wall, or swing out from its top edge. */ +export const WINDOW_OPENINGS = ["turn", "slide", "top"] as const; +export type WindowOpening = (typeof WINDOW_OPENINGS)[number]; + +/** Entity link of an opening: null = assigned automatically by area, "none" = no entity. */ +export type EntityRef = string | null; + +export interface Opening { + id: string; + room_id: string; + /** Room edge the opening sits on (points[edge] -> points[edge + 1]); 0 in a free wall. */ + edge: number; + /** Distance of the opening's centre from points[edge], or from the free wall's start (metres). */ + offset: number; + /** Free wall the opening sits in (its id); room_id is then the room the wall stands in. */ + wall?: string | null; + width: number; + type: OpeningType; + /** Height of the bottom above the floor; 0 for doors, garage doors and terrace doors. */ + sill: number; + height: number; + /** Hinge as seen from the room; with two leaves, the side of the main leaf. */ + hinge: "left" | "right"; + /** One leaf, or two (double door, French window) opening from the middle. */ + leaves: 1 | 2; + /** Doors swing into their room ("in") or to the other side ("out"). */ + swing: "in" | "out"; + /** Look of the door or window (null = automatic: a front door in an exterior wall, else a room door). */ + style?: OpeningStyle | null; + /** One sidelight: on the hinge side instead of opposite the hinge. */ + sidelight_hinge?: boolean; + /** Width of the sidelight(s) in m (null = automatic); with two, `sidelight_width2` is the right one (seen from the room). */ + sidelight_width?: number | null; + sidelight_width2?: number | null; + /** + * Glass walls: how many panes the mullions divide the wall into (null = one about every 0.9 m, as it always was; + * 0 = one single pane without a mullion, for the large glazing modern houses have). + */ + panes?: number | null; + /** + * Glass walls: the pieces of one pane that follows a curved wall share this id. Each piece is a normal opening on its own + * edge with a legal offset and width, stored in order along the wall; the 3D view draws them as one pane without a jamb + * where two of them meet. Null for a pane that fits on a single edge. + */ + front?: string | null; + /** Contact of the second leaf (null = none). */ + contact2: string | null; + /** Windows: which sensors report the sash (null: a contact, plus a tilt sensor when one is set). */ + sensor?: "contact" | "handle" | "contact_tilt" | null; + /** The same for the second leaf of a double window, with its own tilt sensor. */ + sensor2?: "contact" | "handle" | "contact_tilt" | null; + tilt2?: string | null; + /** A sensor reporting the blind's position while it moves (covers that only report at the end). */ + position?: string | null; + /** The position sensor counts the other way round (0 = open). */ + position_inverted?: boolean; + /** Windows: a sensor with the sash's tilt angle (degrees); the sash tilts in 3D as far as it reports. */ + tilt_angle?: EntityRef; + /** Angle that counts as fully tilted (default 15°), an offset the sensor reports when closed, and the other sign. */ + tilt_max?: number | null; + tilt_offset?: number | null; + tilt_invert?: boolean; + /** Door: drawn closed when no sensor says otherwise (default: half open, so the door is seen). */ + shut?: boolean; + /** Door: how far the leaf opens, in degrees (null = the usual swing, a door without a sensor half of it). Set, a door without a sensor stands that far open. */ + open_angle?: number | null; + /** Highlight in 3D while open (null, default) or while closed (a WC or a child's room door). */ + mark?: "closed" | null; + /** Ask before moving the blind or garage door; it then does not follow a swipe either. */ + confirm?: boolean; + cover: EntityRef; + /** Windows and doors: a second blind for the right half (seen from the room) of a wide window. */ + cover2?: string | null; + /** The kind of blind: a roller shutter outside (null, default), a venetian blind (Raffstore) outside with slats, or a roller blind inside. */ + blind?: "roller" | "venetian" | "inside" | null; + /** The favourite position of the blind (%, open = 100) – Somfy's "My": a button in its menu moves it there. */ + my_position?: number | null; + contact: EntityRef; + /** Windows: how the sash opens – turns and tilts into the room (null), slides behind the fixed pane, or swings out at the bottom (top-hung). */ + opens?: WindowOpening | null; + /** Windows: the board inside and the sill outside – automatic (both when the sill is above 30 cm), none, or only one of them. */ + sill_boards?: "auto" | "none" | "inside" | "outside" | null; + /** Windows below the ground: their light well (null = by itself when the sill lies below the ground, false = none, true = always). */ + light_well?: boolean | null; + /** Windows: false leaves this window out of the rain warning (a window under a roof or an awning). */ + rain_warning?: boolean; + /** Doors: a smart lock (lock.*). A tap on the door locks or unlocks it after asking; while unlocked, its free edge glows. */ + lock?: string | null; + tilt: EntityRef; +} + +/** A picture rule of a screen: while `entity` is in `state`, the stored image (or a URL) is shown. */ +export interface ScreenPicture { + entity: string; + /** Compare this attribute (e.g. app_name) instead of the state. */ + attribute?: string | null; + /** The value to match: exact, or contained in the value's text ("youtube" in "com.google.android.youtube.tv"); "*" = any. */ + state: string; + /** An image id of the image store, or an http(s) URL. */ + image: string; +} + +export interface Furniture extends LightEffectConfig { + /** A tap on the item runs this own action (open a path, an entity's details, a service, a browser_mod popup); null = the item's usual tap. */ + tap?: Pick | null; + /** Fixed against moving by accident. */ + locked?: boolean | null; + /** Shown only while an entity is in a state (seasonal decoration behind a helper); null = always. */ + show_when?: ShowWhen | null; + /** Its pin moved by hand (m in the plan and up), for pieces that stand close together. */ + pin_offset?: PinOffset | null; + id: string; + type: string; + x: number; + z: number; + rotation: number; + /** Tilted about its own axes (degrees): `tilt_x` nose up or down (about the width axis), `tilt_z` rolled sideways (about the depth axis); null = upright. */ + tilt_x?: number | null; + tilt_z?: number | null; + w: number; + d: number; + h: number; + variant: string | null; + /** Own name (e.g. "Wechselrichter Nord"); null = the type's name. */ + name?: string | null; + /** The own name shows as a small label under its marker in 3D. */ + show_name?: boolean; + /** Lamps: how strongly the lamp glows in 3D, 0.1–1.5 (1 = as bright as the light reports) – #181. */ + glow_scale?: number | null; + /** Screens: how strongly the glow behind a playing TV shines, 0 to 1.5 (null = 1, 0 = off). */ + ambilight?: number | null; + /** Speakers (a linked media player): size of the sound rings while it plays, 0 to 1.5 (null = 1, 0 = none) – #94. */ + sound_rings?: number | null; + /** An own symbol for the marker: a Material Design icon name without "mdi:" (null = by kind). */ + icon?: string | null; + /** Linked entity, e.g. the TV's media player (null = automatic, "none" = none). */ + entity?: EntityRef; + /** Power sensor (null = automatic: the linked entity's device or a matching name). */ + power?: EntityRef; + /** Fridges and freezers: a temperature sensor of the fridge (temp_entity) and one of the freezer compartment; the marker shows them and warns when too warm. Any other device: its own thermometer, shown on its pin (#112). */ + temp_entity?: string | null; + temp_entity2?: string | null; + /** Smart fridge: door sensors of the left (freezer) and right (fridge) door; the doors open in 3D while they report open. */ + door_left?: EntityRef; + door_right?: EntityRef; + /** Home battery: its state of charge (%). Wallbox: a status sensor (charging, car plugged in). */ + soc?: EntityRef; + /** Home battery: a separate sensor with the charging power (W) when the power sensor only reports discharging. */ + charge?: EntityRef; + /** Meter: a separate sensor with the export power (W) when the power sensor only reports import. */ + export?: EntityRef; + /** Meter in the advanced energy mode: the meter it hangs off (a sub-meter; null = a main meter). */ + parent_meter?: string | null; + /** Sub-meter: its power sensor counts the other way round (+ has to mean drawn). */ + meter_invert?: boolean; + /** Sub-meter: the floors it feeds; consumers placed there draw from it instead of the house. */ + meter_floors?: string[]; + status?: EntityRef; + /** Robot vacuum: sensor naming the room it cleans right now (null = automatic, "none" = the dock's room). */ + room_sensor?: EntityRef; + /** Ask before switching the linked entity. */ + confirm?: boolean; + /** Its marker in 3D: automatic (null), always shown, shown without watts, or hidden. */ + marker?: MarkerShow | null; + /** Height of the bottom edge above the floor (null = default: the floor, a pack item's mount, a surface below). */ + mount_y?: number | null; + /** Ceiling lights, fans and ceiling-mounted items: the height of the ceiling right there (a sloping ceiling, a high spot); null = the room's ceiling. */ + ceiling_y?: number | null; + /** Ceiling fan: its fan entity (null = found in the room, "none" = none). The linked light is its light kit. */ + fan_entity?: EntityRef; + /** Any furniture: an entity whose state the item shows – it glows while on, occupied or home (a bed with an occupancy mat, a chair, a sauna). */ + state_entity?: EntityRef; + /** A second state entity for the other half: left/right (a double bed) or bottom/top (a bunk bed). */ + state_entity2?: EntityRef; + state_split?: "left_right" | "top_bottom" | null; + /** Household items: the sensor they show – a bin's pickup, a mailbox's post, a plant's soil moisture (null = none). */ + care_entity?: string | null; + /** Plants: the soil moisture below which they are thirsty (%, default 20). */ + thirsty_below?: number | null; + /** Light switches and sockets: the entity of each button or socket, in order (null = none). */ + /** Items with moving parts (curtain, roller screen, awning, gate): the cover entity they follow (null = none, they rest). */ + cover_entity?: string | null; + /** The cover reports its position the other way round (0 = open): an awning that runs the opposite way – #100. */ + cover_inverted?: boolean; + gang_entities?: (string | null)[]; + /** Lamps: a second entity whose colour and brightness the lamp shows while the linked switch is on (a relay switches the light, the bulb itself knows its colour). */ + color_entity?: EntityRef; + /** Lamps: further lights of the same fixture (a night light, an ambient ring), switched on their own; the lamp glows with them while its main light is off. */ + extra_lights?: string[]; + /** Lawn sprinkler: how far its water reaches in m (null = 3 m). */ + spray?: number | null; + /** Mirrored (left-right) – an L-sofa the other way round, a cabinet with its door on the other side. */ + mirror?: boolean; + /** Stairs: shape, turn, build, steps and direction (missing on older plans: the simple straight stair). */ + stair?: Partial | null; + /** LED strip: tilt about its length (°; 0 = lying flat, 90 = its face points sideways, e.g. along a roof slope). */ + tilt?: number; + /** LED strip: standing upright – its length runs up from the mount height (door frame, light column). */ + upright?: boolean; + /** LED strip: how steeply its length rises (°, -80 to 80), e.g. up a sloped ceiling or along a stair. Its low end sits at the mount height, or its high end under the ceiling. */ + rise?: number; + /** Picture frames: the photo – a stored picture ("image:"), a URL (/local/…, https://…) or an image, camera or media player entity. */ + picture?: string | null; + /** Picture frames: the white mat around the photo, in % of the shorter side (0 or null = none). */ + picture_border?: number | null; + /** Picture frames: the photo fills the opening (cropped, default) or shows whole on the mat. */ + picture_fit?: "cover" | "contain" | null; + /** Screens: pictures shown while an entity is in a state (first match wins; "*" = any state). */ + pictures?: ScreenPicture[]; + /** Screens: what shows around a rule picture – a dark screen (default) or a white one (for dark logos). */ + screen_bg?: "black" | "white"; + /** Parking spots: the vehicle shown (a pack item type) while `entity` reports a car. */ + vehicle?: string | null; + /** Auto: the car's entities (each null = found on the device of `device`, or of the presence entity). */ + car?: CarLinks | null; + /** Parking spots: size factor of the vehicle (1 = the pack item's size). */ + scale?: number; + /** Parking spots: a sensor naming the kind of vehicle, and which vehicle each state means. */ + type_entity?: string | null; + types?: { state: string; vehicle: string }[]; +} + +export type LampMount = "ceiling" | "floor" | "table" | "wall"; + +/** How a device's marker shows in 3D (null = automatic by the marker mode); "active": only while it is on (motion detected, door open). */ +export const MARKER_SHOWS = ["always", "active", "no_power", "never"] as const; +export type MarkerShow = (typeof MARKER_SHOWS)[number]; + +export interface Placement extends LightEffectConfig { + /** Fixed against moving by accident. */ + locked?: boolean | null; + entity_id: string; + x: number; + z: number; + /** Height above the floor; null = default for the device kind (and lamp mount). */ + y: number | null; + /** Lights: how the lamp is mounted; null = ceiling. */ + mount?: LampMount | null; + /** Turn around the vertical axis (degrees): wall lamps, spots, displays face that way. */ + rotation?: number; + /** Cameras: opening angle of the field of view (degrees) and how far it reaches (m); null = default. */ + fov?: number | null; + reach?: number | null; + /** Cameras: how far it looks down (degrees below the horizon; null = 20° on a wall, 65° as a dome). */ + tilt?: number | null; + /** Ask before switching this device (3D tap, quick menu, room panel). */ + confirm?: boolean; + /** Lights: only the switch in the room panel, without brightness, colour temperature and colours. */ + simple?: boolean; + /** Its marker in 3D: automatic (null), always shown, shown without watts, or hidden. */ + marker?: MarkerShow | null; + /** An own symbol for the marker: a Material Design icon name without "mdi:" (null = by kind). */ + icon?: string | null; + /** An own name in the plan (null = the entity's name), without renaming the entity in Home Assistant. */ + name?: string | null; + /** The own name shows as a small label under its marker in 3D. */ + show_name?: boolean; + /** Lights: how strongly the light glows in 3D, 0.1–1.5 (1 = as bright as the light reports) – #181. */ + glow_scale?: number | null; + /** Media players: size of the sound rings while it plays, 0 to 1.5 (null = 1, 0 = none) – #94. */ + sound_rings?: number | null; + /** Cameras: show the field-of-view wedge on the floor (null = yes). */ + cone?: boolean | null; + /** Settings plugins added to the device's form: per plugin id, the values by key. */ + plugin?: Record> | null; + /** Belongs to Outside: never to the room under it (a weather station on the roof), listed in the Outside panel. */ + outside?: boolean; + /** Its pin moved by hand from where it would stand (m in the plan and up), so pins of devices close together do not cover each other. */ + pin_offset?: PinOffset | null; +} + +/** A pin moved by hand: metres along x and z of the plan, and up. */ +export interface PinOffset { + x?: number; + z?: number; + y?: number; +} + +export interface Background { + image_id: string; + x: number; + z: number; + width: number; + opacity: number; + /** Turn about the picture's middle (degrees, clockwise in the plan). */ + rotation?: number; +} + +export interface Floor { + id: string; + name: string; + elevation: number; + height: number; + cut_height: number; + rooms: Room[]; + openings: Opening[]; + furniture: Furniture[]; + placements: Placement[]; + background: Background | null; + outdoor: OutdoorArea[]; + /** Free-standing walls (a partition through half a room); room walls come from the room edges. */ + walls?: FreeWall[]; + /** Linked floor of Home Assistant's floor registry. */ + ha_floor: string | null; + /** The camera this floor opens with (#182): another side than the house view; null = the house view's side. */ + start_view?: StartView | null; + /** A layer rather than a storey (all the trees, the decoration): the 3D view can show or hide it with an eye. */ + layer?: boolean; + /** The floor's own meter: a power sensor whose use shows on the floor label and, in this floor's view, on the house card. */ + power_entity?: string | null; + /** Notes pinned to a spot of the floor ("filter due in March", "fuse 12"), shown in 3D and found by the search. */ + notes?: PlanNote[]; + /** Paint of this floor's outer walls in the solid wall view ("#rrggbb"; null = the building's outside colour): a plinth, a garage (#110). */ + wall_paint_outside?: string | null; +} + +/** A note pinned to a spot of a floor. */ +export interface PlanNote { + id: string; + x: number; + z: number; + text: string; + /** When it is due ("YYYY-MM-DD"): from that day on its pin turns orange. */ + due?: string | null; + /** Height of its pin above the floor in metres (null = 1.3, eye level): a valve under the ceiling, a fuse box (#113). */ + y?: number | null; + /** A photo shown when the note is opened: a picture stored with the plan ("image:") or a URL (#113). */ + photo?: string | null; +} + +/** The height of a note's pin above its floor when none is set (eye level). */ +export const NOTE_Y = 1.3; + +/** Whether a note is due on a day ("YYYY-MM-DD", today by default). */ +export const noteDue = (note: Pick, today = new Date().toISOString().slice(0, 10)): boolean => !!note.due && note.due <= today; + +/** A wall drawn on its own, from a to b along its centre line. */ +export interface FreeWall { + id: string; + a: Vec2; + b: Vec2; + /** Thickness in metres (null = the interior wall thickness of the settings). */ + thickness?: number | null; + /** Height in metres (null = full floor height), e.g. a half-height wall or a counter. */ + height?: number | null; + /** A sloping wall: the height at the end b (the height at a stays `height`); null = the same height all along. */ + height_end?: number | null; +} + +/** "custom": the roof is made of sections (wings of an L- or T-shaped house, a barn, a lean-to …). */ +export type RoofType = "none" | "flat" | "gable" | "custom"; + +/** Shapes of a roof section. */ +export const ROOF_SHAPES = ["gable", "hip", "halfhip", "pyramid", "mansard", "pent", "flat", "parapet"] as const; +export type RoofShape = (typeof ROOF_SHAPES)[number]; + +/** + * One roof section over a rectangle of the plan (at the outer wall faces; the overhang comes on top). + * Heights are above the ground. Across the ridge, side "a" is the low coordinate (z for a ridge along + * x, x for a ridge along z), side "b" the high one; each side has its own eave height and pitch, so one + * slope can reach further down (a catslide over a lower part). A pent roof rises from side a. + */ +export interface RoofSection { + id: string; + x0: number; + z0: number; + x1: number; + z1: number; + shape: RoofShape; + /** The ridge runs along x or along z. */ + axis: "x" | "z"; + eave_a: number; + eave_b: number; + /** Slopes in degrees. */ + pitch_a: number; + pitch_b: number; + /** Top of the walls below: gable and knee walls are built from here up to the roof. */ + base: number; + /** Overhang beyond the walls (null = the roof setting). */ + overhang?: number | null; + /** + * Overhang of single sides by hand (m): the ends of the ridge (`u0`, `u1`) and the eaves (`a`, `b`); a side that is not listed + * keeps the automatic value (none where the section meets the house). + */ + overhang_sides?: Partial> | null; + /** Sides a and b swapped: side a is the high coordinate (a pent roof then rises the other way). */ + flip?: boolean; + /** + * A flat roof as a free shape: its footprint polygon (plan coordinates at the outer wall faces, the + * overhang comes on top); x0 … z1 then hold the polygon's bounding box. + */ + points?: Vec2[] | null; + /** A dormer: a small section on the slope of another one, open towards that slope at its rear. */ + dormer?: boolean; + /** Fixed: cannot be moved or resized by accident (the plan lock fixes every section too). */ + locked?: boolean; + /** A canopy (terrace roof, carport): posts and beams instead of walls, a see-through roof. */ + open?: boolean; + /** Gable, hip and half-hip sections: their own shape at the start and at the end of the ridge (null: both as the shape says). */ + ends?: [RoofEnd, RoofEnd] | null; + /** Turned about the middle of its rectangle, degrees clockwise in the plan (a wing at an angle); null = straight. */ + rotation?: number | null; + /** Half-hips: how high up the gable the hip starts, as a share of the gable's height (null = 0.55). */ + halfhip?: number | null; +} + +/** The end of a ridge: an upright gable, a hip, or a half-hip. */ +export type RoofEnd = "gable" | "hip" | "halfhip"; + +export interface RoofSettings { + type: RoofType; + /** Slope of a gable roof in degrees. */ + pitch: number; + /** How far the roof reaches beyond the outer walls (metres). */ + overhang: number; + /** Gable roof: ridge along the long side (default) or across, along the short side (terraced houses). */ + ridge?: "long" | "short" | null; + /** Roof sections of a "custom" roof. */ + sections?: RoofSection[]; + /** Solar fields on the roof faces. */ + solar?: SolarField[]; + /** Strings that fields belong to. */ + strings?: SolarString[]; + /** Roof windows on the roof faces. */ + windows?: RoofWindow[]; + /** Chimneys on the roof faces. */ + chimneys?: RoofChimney[]; +} + +/** Shapes of a chimney: brick (square), round, wide with two flues, or a thin steel flue pipe with a rain cap. */ +export const CHIMNEY_SHAPES = ["brick", "round", "wide", "steel"] as const; +export type ChimneyShape = (typeof CHIMNEY_SHAPES)[number]; + +/** + * A chimney on a roof face: placed like a roof window (u along the eave, v up the slope, in metres, at its lower + * left corner), `w` wide along the eave and `d` deep in the plan; it rises `h` above the roof at its upper side. + */ +export interface RoofChimney { + id: string; + face: string; + u: number; + v: number; + shape?: ChimneyShape | null; + /** Size in metres (null = the shape's usual size). */ + w?: number | null; + d?: number | null; + h?: number | null; + name?: string | null; + /** Fixed: cannot be moved by accident. */ + locked?: boolean; +} + +/** + * A field of solar modules on a roof face (see solar.ts): rows × columns from its lower left corner (u along + * the eave, v up the slope, in metres). On a flat roof the modules stand on frames, tilted by `tilt`. + */ +export interface SolarField { + id: string; + /** Roof face: "main:a" / "main:b" / "main:top" (single roof) or "
    :a" / ":b" / ":top"; hip ends ":c" / ":d". */ + face: string; + u: number; + v: number; + rows: number; + cols: number; + /** Portrait (default) or landscape modules. */ + portrait: boolean; + /** Flat roofs: tilt of the frames in degrees (null = 15°); pitched roofs: a rack tilting the modules further (null = lying on the roof). */ + tilt?: number | null; + /** Flat roofs: the modules lean the other way. */ + flip?: boolean; + /** Flat roofs: rows facing one way (default), or east-west racks – every second row turned, the pairs back to back. */ + rack?: "ew" | null; + /** PV power sensor of this field, e.g. its string (null = the plant's sensor from the energy settings). */ + entity?: string | null; + /** Name, e.g. "String 1 south". */ + name?: string | null; + /** Modules per row when the rows differ (e.g. [4, 4, 3]); null = `cols` in every row. */ + layout?: number[] | null; + /** Shorter rows sit left, centred or right. */ + align?: "left" | "center" | "right" | null; + /** Modules left out, as "row:column" (row 0 at the eave). */ + skip?: string[] | null; + /** Look: full black (default) or classic blue. */ + look?: "black" | "blue" | null; + /** Module size in portrait, width × height in metres (null = 1.13 × 1.72). */ + module_w?: number | null; + module_h?: number | null; + /** Peak power of one module (Wp); null = 400. */ + wp?: number | null; + /** The string the field belongs to (see RoofSettings.strings); fields on several roofs can share one. */ + string?: string | null; + /** Free-standing fields (face "ground"): rotation of the rows in the plan, degrees. */ + rotation?: number | null; + /** Free-standing fields: height of the surface they stand on above the ground floor (a garage roof); null = the ground. */ + base?: number | null; + /** Fixed: cannot be moved by accident. */ + locked?: boolean; +} + +/** + * A roof window on a roof face (u along the eave, v up the slope, in metres, at its lower left corner). Like a + * window it follows a contact (open or tilted: the sash swings out at the top) and a blind (cover). + */ +export interface RoofWindow { + id: string; + face: string; + u: number; + v: number; + /** Size in metres (null = 0.78 × 1.18, a common size). */ + w?: number | null; + h?: number | null; + cover?: EntityRef; + contact?: EntityRef; + tilt?: EntityRef; + /** A window motor (a cover whose position opens the sash that far). */ + window?: EntityRef; + name?: string | null; + /** Fixed: cannot be moved by accident. */ + locked?: boolean; +} + +/** A string of solar modules: one or more fields wired together to one inverter. */ +export interface SolarString { + id: string; + name: string; + /** PV power sensor of the string. */ + entity?: string | null; + /** The inverter it feeds (an "inverter" furniture item). */ + inverter?: string | null; +} + +export const BUTTON_ACTIONS = ["navigate", "more_info", "service", "fire_dom_event"] as const; +export type ButtonAction = (typeof BUTTON_ACTIONS)[number]; + +/** + * An own button in the central menu (D143): opens a dashboard path, the more-info dialog of an entity, + * calls a service, or fires a DOM event (a browser_mod popup with your own card). + */ +export interface CustomButton { + id: string; + label: string; + /** Material Design icon name without "mdi:". */ + icon?: string | null; + action: ButtonAction; + /** navigate: the path ("/lovelace/rollos"); more_info: the entity; service: "domain.service". */ + target?: string | null; + /** service: its data; fire_dom_event: the event's detail (e.g. { browser_mod: { service, data } }). */ + data?: Record | null; + /** The entity whose state lights the button up while it is on (null: the entity it opens or switches, when there is one). */ + state_entity?: string | null; +} + +/** + * Something to play on a speaker from its quick menu (Klang): media_player.play_media with this + * content type and id – a radio stream URL, a Music Assistant or Sonos URI, or for an Echo (Alexa Media + * Player) the type SPOTIFY / AMAZON_MUSIC / TUNEIN with what you would say ("Rock Antenne"). + */ +export interface MediaPreset { + id: string; + label: string; + type: string; + content: string; + /** The speakers it is offered on (media_player ids); empty or missing = every speaker. */ + speakers?: string[]; +} + +/** What a Bluetooth tag's signal looked like at the scanners while it was in a room (dBm per scanner source). */ +export interface BleFingerprint { + room: string; + rssi: Record; +} + +/** A Bluetooth tag located by room: a fixed address, or a Private BLE Device tracker for phones and watches (their address changes). */ +export interface BleTag { + id: string; + name: string; + address?: string | null; + entity?: string | null; + prints: BleFingerprint[]; + /** Scanner source → its name, for showing the signals. */ + scanners?: Record; +} + +export interface BuildingSettings { + /** Bluetooth tags located by room (the sensor and the editor's learning by walking). */ + ble?: { tags: BleTag[] } | null; + /** Stations and playlists for the speakers' quick menu (Klang). */ + media_presets?: MediaPreset[]; + /** Favourites of the house: scenes, scripts, automations, buttons and switches in the central menu of the 3D view (#145). */ + favorites?: string[]; + /** Devices Outside leaves out of its panel (they stay in the plan) – #83. */ + outside_hidden?: string[]; + /** The camera Outside opens with (the garden behind the house, #83); null = the house view. The point it looks at is counted from the ground. */ + outside_view?: StartView | null; + /** Facts the room panel leaves out of its header: sun hours, comfort, airing, fuse-box circuits. */ + room_facts_off?: ("sun" | "comfort" | "air" | "circuits")[]; + /** A favourite that shows on one floor only (entity id → floor id); the others show everywhere. */ + favorite_floors?: Record; + /** Own buttons in the central menu (D143). */ + buttons?: CustomButton[]; + wall_exterior: number; + wall_interior: number; + /** Paint of the walls in the solid wall view ("#rrggbb"): outside, and inside where a room has no colour of its own (null = default). */ + wall_paint_outside?: string | null; + wall_paint_inside?: string | null; + /** Furniture colours per role ("#rrggbb"; body, wood, fabric, white, metal, dark), house-wide (#82). */ + furniture_colors?: FurnitureColors | null; + grid: number; + /** Direction of north in the plan, degrees clockwise from "up" (for the sun). */ + north: number; + roof: RoofSettings; + /** The weather entity shown outside the house (null = the first one). */ + weather_entity?: string | null; + /** Which weather effects the 3D view shows (null = all but fog). */ + weather_effects?: WeatherEffect[] | null; + /** Warning for a window open while it rains (default on). */ + rain_warning?: boolean; + /** Sunlight falls through the windows as patches on the floor (default on, #266). */ + sun_patches?: boolean; + /** The sun's path of today as an arc over the plot, with a compass ring (default off). */ + sun_arc?: boolean; + /** Dashboard card options set up once in the editor, by name; a card with `template: name` uses them. */ + card_templates?: Record> | null; + /** Plan lock: rooms, walls, doors, windows and outdoor areas cannot be moved by accident. */ + lock_plan?: boolean; + /** The camera the house view opens with (3D view, card, kiosk); null = fitted from the front left. */ + start_view?: StartView | null; + /** + * A robot vacuum's own map, tied to the plan: two places known in both the plan (m) and the robot's + * map grid. Without it the robot's trail and pose cannot be placed, and the 3D view keeps the lanes + * it invents for the room (see live/vacuum-map.ts). + */ + vacuum_map?: VacuumCalibration | null; + /** A real map under the plan (null = none). */ + map?: MapSettings | null; + /** How lengths and areas are shown in the editor: metres or feet and inches (inputs stay in metres). */ + units?: "metric" | "imperial" | null; + /** The rain warning asks this sensor (a weather station: on, or a rain rate above 0) instead of the weather entity. */ + rain_sensor?: string | null; + /** Devices the plan check no longer lists as "not in the plan yet" (entity ids). */ + check_ignore?: string[] | null; + /** The rain sensor reads the other way round: on (or above zero) means dry. */ + rain_sensor_inverted?: boolean; + /** A sensor that tells a power outage: a warning for the whole house while the grid is gone. */ + outage_sensor?: string | null; + /** Warn when a door or window contact has been unavailable for 10 minutes (empty battery, out of reach); default off. */ + contact_warning?: boolean; + /** Warn at night (22:00–6:00) about the plan's door locks that stand unlocked. */ + night_lock_warning?: boolean; + /** Motion, occupancy and presence sensors show their marker only while they detect something (default off). */ + motion_markers_active?: boolean; + /** What a double tap on a room switches: null = its plan lamps and every light of its area, plan = only the plan's lamps, off = nothing (#62). */ + room_double_tap?: "plan" | "off" | null; + /** Announcements: the text-to-speech entity (null = the first one) and the sentences a room offers (null = the default ones). */ + announce_tts?: string | null; + announce_phrases?: string[] | null; + /** Own warnings: a line in the warning bar while an entity is in a state ("Water tank empty", "Dishwasher done"). */ + own_alerts?: OwnAlert[] | null; + /** Calendars whose appointments of the day show on the "Today" card of the 3D view. */ + calendars?: string[] | null; + /** How many days the "Today" card lists, from today on (null = today only). */ + today_days?: number | null; + /** The weather forecast card in a top corner of the 3D view (null = none, #84). */ + forecast?: ForecastCard | null; + /** The fuse box: its circuits with the rooms on them ("F12 kitchen"); the room panel names them and the search finds them. */ + circuits?: Circuit[] | null; + /** Own sensors shown at the top of the 3D view (outside temperature, the alarm…), at most 12. */ + status_entities?: string[] | null; + /** An own background behind the house instead of the look's sky: a colour and/or a picture (/local/… or https), dimmed. */ + backdrop?: { color?: string | null; image?: string | null; dim?: number | null } | null; + /** Plugin modules to load (Extensions page); see docs/plugins.md. */ + plugins?: PluginRef[]; +} + +/** Two places, each known in the plan (m) and in a robot's map grid. */ +/** The weather forecast card: how many days, and which top corner it sits in. The weather entity is `weather_entity`. */ +export interface ForecastCard { + days: number; + corner: "top_left" | "top_right"; +} + +export interface VacuumCalibration { + /** Plan position of the first place. */ + a: [number, number]; + /** The robot's grid position there. */ + ga: [number, number]; + /** Plan position of the second place. */ + b: [number, number]; + /** The robot's grid position there. */ + gb: [number, number]; + /** + * The robot's grid runs the other way round than the plan does: its y grows along plan -z. Two places + * cannot tell a mirror from a turn (both put them exactly where they belong), so it has to be stated. + */ + mirror?: boolean; +} + +/** A real map as the base of the plan: the plan point (x, z in metres) that lies at lat / lon, turned by the plan's north. */ +export interface MapSettings { + on: boolean; + lat: number; + lon: number; + x?: number; + z?: number; + /** How strongly the map shows, 0.05 to 1 (default 0.5). */ + opacity?: number; + /** Tile zoom, 15 (coarse) to 19 (fine; default 18). */ + zoom?: number; + /** Tile address with {z}, {x} and {y}; null = OpenStreetMap. */ + url?: string | null; +} + +/** How one light of a mood is: off, or on with its brightness (0–255) and colour. */ +export interface LightSetting { + entity: string; + on: boolean; + brightness?: number; + rgb?: [number, number, number]; + kelvin?: number; +} + +/** A light mood of a room. */ +export interface LightMood { + id: string; + name: string; + lights: LightSetting[]; +} + +/** An own warning: shown in the warning bar while `entity` is in `state` (comma separated, or "<20" / ">80" for numbers). */ +export interface OwnAlert { + id: string; + entity: string; + state?: string | null; + text: string; + /** The room it belongs to (its floor pulses softly); null = the whole house. */ + room_id?: string | null; + /** The colour of its stripe ("#rrggbb"; null = amber). */ + color?: string | null; + /** What a tap on it does: open the entity's details (null), switch the entity, or go to its room. */ + tap?: "toggle" | "room" | null; +} + +/** A camera position around the house: azimuth and polar angle (radians) and the distance (m). */ +export interface StartView { + theta: number; + phi: number; + radius: number; + /** The point the camera looks at (m; null: the middle). For a floor or a room y counts from that floor. */ + target?: { x: number; y: number; z: number } | null; +} + +/** + * Whether an item is fixed: rooms, walls, doors, windows and outdoor areas follow the plan lock alone, + * furniture and devices their own lock. + */ +export function isFixed(item: object | null | undefined, structural: boolean, settings: Pick): boolean { + if (!item) return false; + return structural ? !!settings.lock_plan : !!(item as { locked?: boolean | null }).locked; +} + +export const WEATHER_EFFECTS = ["rain", "snow", "fog", "clouds", "lightning", "sky"] as const; +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 type OutdoorType = (typeof OUTDOOR_TYPES)[number]; + +/** Top of each kind of outdoor area above ground level (pool: its water, below). */ +export const OUTDOOR_TOP: Record = { + lawn: 0.012, + terrace: 0.12, + path: 0.02, + driveway: 0.02, + pool: -0.25, + bed: 0.15, + wild: 0.03, + hedge: 1.2, + fence: 1.0, + pergola: 2.2, +}; + +/** Types that stand on the ground as structures (no surface to stand on, no light pool). */ +export function outdoorStanding(type: OutdoorType): boolean { + return type === "hedge" || type === "fence" || type === "pergola"; +} + +/** The directions an area can fall towards: +x (right in the plan), −x, +z (down in the plan), −z. */ +export const SLOPE_DIRS = ["x", "-x", "z", "-z"] as const; +export type SlopeDir = (typeof SLOPE_DIRS)[number]; + +/** + * How far the surface of an area has dropped at a point (m, ≥ 0): zero on the high edge, the full + * slope on the low edge, along the slope direction across the extent of the polygon. + */ +export function outdoorDrop(a: OutdoorArea, x: number, z: number): number { + const slope = a.slope ?? 0; + if (!slope || a.type === "pool") return 0; + const dir = a.slope_dir ?? "x"; + const proj = (px: number, pz: number) => (dir === "x" ? px : dir === "-x" ? -px : dir === "z" ? pz : -pz); + let lo = Infinity; + let hi = -Infinity; + for (const [px, pz] of a.points) { + const v = proj(px, pz); + lo = Math.min(lo, v); + hi = Math.max(hi, v); + } + if (hi - lo < 1e-6) return 0; + const t = Math.min(1, Math.max(0, (proj(x, z) - lo) / (hi - lo))); + return slope * t; +} + +/** Height of the surface of an area at a point, in floor coordinates (offset and slope included). */ +export function outdoorTopAt(floor: Floor, a: OutdoorArea, x: number, z: number): number { + return groundLevel(floor) + (a.offset ?? 0) + OUTDOOR_TOP[a.type] - outdoorDrop(a, x, z); +} + +/** Ground level in floor coordinates: below the ground floor slab (0.2 m), the floor itself further up. */ +export function groundLevel(floor: Floor): number { + return floor.elevation > 0.3 ? 0 : -0.2; +} + +/** Height outdoor lamps stand on at a point: ground level, or the top of a terrace or bed there. */ +export function outdoorGround(floor: Floor, x: number, z: number): number { + const inside = (floor.outdoor ?? []).filter((o) => !outdoorStanding(o.type) && o.type !== "pool" && pointInPolygon([x, z], o.points)); + // an area cut out of the one beneath it wins over that one + const a = [...inside].reverse().find((o) => o.cut) ?? inside[0]; + return a ? outdoorTopAt(floor, a, x, z) : groundLevel(floor); +} + +/** Auto: which entities tell the car's state; null = automatic (an entity of the car's Home Assistant device). */ +export interface CarLinks { + /** Any entity of the car's device: the others are found beside it. */ + device?: EntityRef; + soc?: EntityRef; + range?: EntityRef; + /** Charging power (W/kW), a charging binary sensor, or the charge switch. */ + charging?: EntityRef; + plugged?: EntityRef; + lock?: EntityRef; + climate?: EntityRef; + tracker?: EntityRef; + /** The planned departure time (a sensor, input_datetime or time entity). */ + departure?: EntityRef; +} + +/** Area outside the house (lawn, terrace, pool, hedge …), drawn like a room. */ +export interface OutdoorArea { + id: string; + type: OutdoorType; + points: Vec2[]; + /** The Home Assistant area of this garden, terrace or pool: its devices and sensors are listed under Outside, and a pin opens it. */ + area_id?: string | null; + /** Pools and ponds: the water temperature and the pump (or filter) shown on the area's pin. */ + temp_entity?: string | null; + pump_entity?: string | null; + /** Hedges and fences: their height in m (null = 1.2 m / 1.0 m). */ + height?: number | null; + /** False hides the neon outline (a plot of several lawns without lines crossing it). */ + outline?: boolean; + /** Height offset in m: a driveway piece in front of a lower garage sits below the ground (negative), a raised terrace above. */ + offset?: number | null; + /** Fall in m across the area along slope_dir (a driveway down to the garage, a sloping lawn); the high edge sits at the offset. */ + slope?: number | null; + slope_dir?: SlopeDir; + /** Fences and pergolas: the closing edge (last point back to the first) is left out, so a fence can lean against the house. */ + 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. */ + cut?: boolean; + /** Fences: gates in the fence (gaps with a leaf that follows an entity). */ + gates?: FenceGate[]; + /** How opaque the area is drawn, 0.1 … 1 (null = fully): a driveway above a cellar can be seen through. The outline stays. */ + opacity?: number | null; +} + +/** A gate in a fence: a gap in one edge of its outline with a garden gate (one leaf), a double gate or a sliding gate. */ +export interface FenceGate { + id: string; + /** The edge of the area's outline (points[edge] → points[edge + 1]) and the gate's middle along it (m from the first point). */ + edge: number; + offset: number; + width: number; + kind: "single" | "double" | "sliding"; + /** What opens it: a cover, switch, input_boolean or lock (open / on / unlocked), and/or a contact (binary_sensor, on = open). */ + entity?: string | null; + contact?: string | null; + /** Set while building the 3D view from the entities' states; never stored. */ + 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"; + +/** Energy flow: meter position and power sensors (W). Grid positive = import, battery positive = discharging. */ +export interface EnergySettings { + meter: { floor_id: string; x: number; z: number } | null; + grid: string | null; + grid_invert: boolean; + solar: string | null; + battery: string | null; + battery_invert: boolean; + battery_soc: string | null; + /** House consumption (W); null = from the balance of grid, solar and battery. */ + consumption: string | null; + tariff: string | null; + /** Advanced energy mode: meters can hang off another meter (sub-meters of flats). Off = the first meter is the grid, others are consumers. */ + advanced?: boolean; + /** Advanced energy mode: a sub-meter's label also shows how much of its use no placed device measures. */ + show_unmetered?: boolean; + /** Where the cable of an energy connection really runs (the flow follows it instead of an arc). */ + routes?: EnergyRoute[]; + /** Gas and water meters shown with the house's balance: a sensor with the flow now (m³/h, l/min) or today's reading. */ + gas?: string | null; + water?: string | null; +} + +/** A point a cable runs through: on a floor, in plan coordinates. */ +export interface RoutePoint { + floor_id: string; + x: number; + z: number; +} + +/** The cable of one energy connection (`key` as the flow names it: "grid", "battery", "solar:" …). */ +export interface EnergyRoute { + key: string; + points: RoutePoint[]; + /** Draw the route as a visible cable, not just the faint line the flow follows. */ + cable?: boolean; +} + +/** The most points a cable route can have. */ +export const MAX_ROUTE_POINTS = 30; + +/** A circuit of the fuse box and the rooms it feeds. */ +export interface Circuit { + id: string; + name: string; + rooms: string[]; +} + +/** A person and the sensor whose state names the room they are in (ESPresense, Bermuda, …). */ +export interface PresenceLink { + /** A person, or any entity that is "home" / "on" while someone is in (an input_boolean, a device tracker). */ + person: string; + sensor: string | null; + /** The room (its id) they stand in while they are in and no room sensor names one – #71. */ + room?: string | null; +} + +export interface Building { + version: 1; + floors: Floor[]; + settings: BuildingSettings; + energy: EnergySettings; + presence: PresenceLink[]; +} + +export const DEFAULT_ENERGY: EnergySettings = { + meter: null, + grid: null, + grid_invert: false, + solar: null, + battery: null, + battery_invert: false, + battery_soc: null, + consumption: null, + tariff: null, +}; + +export const FLOOR_MATERIALS = ["wood", "oak", "tiles", "carpet", "stone", "concrete"] as const; + +export const DEFAULT_ROOF: RoofSettings = { type: "none", pitch: 35, overhang: 0.4 }; + +/** Default wall paints of the solid wall view: a light plaster outside, a warm white inside. */ +export const DEFAULT_PAINT_OUTSIDE = "#d6cfc2"; +export const DEFAULT_PAINT_INSIDE = "#e8e3da"; + +export const DEFAULT_SETTINGS: BuildingSettings = { wall_exterior: 0.24, wall_interior: 0.12, grid: 0.05, north: 0, roof: { ...DEFAULT_ROOF } }; + +export function emptyBuilding(): Building { + return { version: 1, floors: [], settings: { ...DEFAULT_SETTINGS }, energy: { ...DEFAULT_ENERGY }, presence: [] }; +} + +export function newFloor(id: string, name: string, elevation: number): Floor { + return { + id, + name, + elevation, + height: 2.5, + cut_height: 1.15, + rooms: [], + openings: [], + furniture: [], + placements: [], + background: null, + outdoor: [], + walls: [], + ha_floor: null, + }; +} + +/** Storey height used to place floors created from Home Assistant levels. */ +export const LEVEL_HEIGHT = 2.75; + +/** Where a new floor goes: at its Home Assistant level if known, otherwise on top. */ +export function floorElevation(floors: Floor[], level: number | null | undefined): number { + if (level != null && Number.isFinite(level)) return Math.round(level * LEVEL_HEIGHT * 100) / 100; + const top = floors.reduce((t, f) => (!t || f.elevation > t.elevation ? f : t), null); + return top ? Math.round((top.elevation + top.height + 0.25) * 100) / 100 : 0; +} + +/** + * Rooms for areas as 4 × 3 m tiles in rows beside a floor's existing rooms, to be dragged into place + * and resized. + */ +export function roomTiles(floor: Floor, areas: { area_id: string; name: string }[], id: () => string): Room[] { + const xs = floor.rooms.flatMap((r) => r.points.map((p) => p[0])); + const zs = floor.rooms.flatMap((r) => r.points.map((p) => p[1])); + const x0 = xs.length ? Math.ceil(Math.max(...xs)) + 1 : 0; + const z0 = zs.length ? Math.floor(Math.min(...zs)) : 0; + return areas.map((a, i) => { + const x = x0 + (i % 3) * 4.5; + const z = z0 + Math.floor(i / 3) * 3.5; + return { id: id(), name: a.name, area_id: a.area_id, points: [[x, z], [x + 4, z], [x + 4, z + 3], [x, z + 3]] as Vec2[], floor_material: "wood" }; + }); +} + +/** + * Resizes a furniture item by dragging one corner (`corner`: signs of the corner in the item's own + * frame) to a plan point; the opposite corner stays in place. Sizes snap to `grid`. + */ +export function resizeFurniture(f: Furniture, corner: [1 | -1, 1 | -1], p: Vec2, grid: number): Pick { + const a = (f.rotation * Math.PI) / 180; + const c = Math.cos(a); + const s = Math.sin(a); + const [sx, sz] = corner; + // item axes in the plan: local x → (c, s), local z → (-s, c) + const ax = f.x - sx * (f.w / 2) * c + sz * (f.d / 2) * s; + const az = f.z - sx * (f.w / 2) * s - sz * (f.d / 2) * c; + const dx = p[0] - ax; + const dz = p[1] - az; + const snapSize = (v: number) => Math.max(0.1, Math.round(v / grid) * grid); + const w = snapSize((dx * c + dz * s) * sx); + const d = snapSize((-dx * s + dz * c) * sz); + const r = (v: number) => Math.round(v * 1000) / 1000; + return { x: r(ax + sx * (w / 2) * c - sz * (d / 2) * s), z: r(az + sx * (w / 2) * s + sz * (d / 2) * c), w: r(w), d: r(d) }; +} + +export const FURNITURE_TYPES = [ + "lamp_ceiling", + "lamp_downlight", + "lamp_spot", + "lamp_panel", + "lamp_pendant", + "ceiling_fan", + "lamp_floor", + "lamp_table", + "lamp_wall", + "led_strip", + "lamp_uplight", + "lamp_bollard", + "lamp_garden", + "radiator", + "sofa", + "armchair", + "stool", + "coffee_table", + "tv_board", + "tv_wall", + "sideboard", + "shelf", + "plant", + "rug", + "table", + "table_round", + "chair", + "bench", + "corner_bench", + "bar_stool", + "kitchen", + "kitchen_wall", + "kitchen_tall", + "island", + "worktop", + "sink", + "stove", + "dishwasher", + "fridge", + "bed", + "bunk_bed", + "nightstand", + "wardrobe", + "dresser", + "bathtub", + "shower", + "wc", + "washbasin", + "washer", + "dryer", + "desk", + "office_chair", + "tall_cabinet", + "coat_rack", + "stairs", + "robot_vacuum", + "inverter", + "home_battery", + "wallbox", + "meter", + "grid_point", + "parking", + "fridge_smart", + "stairwell", +] as const; + +/** Furniture library sections (the editor lists them in this order). */ +export const FURNITURE_GROUPS: Record = { + lights: ["lamp_ceiling", "lamp_downlight", "lamp_spot", "lamp_panel", "lamp_pendant", "ceiling_fan", "lamp_floor", "lamp_uplight", "lamp_table", "lamp_wall", "led_strip", "lamp_bollard", "lamp_garden"], + living: ["sofa", "armchair", "stool", "coffee_table", "tv_board", "tv_wall", "sideboard", "shelf", "plant", "rug"], + dining: ["table", "table_round", "chair", "bench", "corner_bench", "bar_stool"], + kitchen: ["kitchen", "kitchen_wall", "kitchen_tall", "island", "worktop", "sink", "stove", "dishwasher", "fridge"], + sleeping: ["bed", "bunk_bed", "nightstand", "wardrobe", "dresser"], + bath: ["bathtub", "shower", "wc", "washbasin", "washer", "dryer"], + work: ["desk", "worktop", "office_chair", "tall_cabinet", "coat_rack", "radiator", "stairs", "robot_vacuum"], + vehicles: ["parking"], +}; + +/** Energy devices: placed and set up in the Energy tool (stored like furniture, not in the library). */ +export const ENERGY_DEVICES = ["meter", "inverter", "home_battery", "wallbox", "grid_point"] as const; + +/** Furniture that can show a linked entity (TV state, power, …). */ +/** Lamps: drawn live (they glow with their light) and tapped directly in 3D. */ +export const LAMP_TYPES = new Set([ + "lamp_ceiling", + "lamp_downlight", + "lamp_spot", + "lamp_panel", + "lamp_pendant", + "ceiling_fan", + "lamp_floor", + "lamp_uplight", + "lamp_table", + "lamp_wall", + "led_strip", + "lamp_bollard", + "lamp_garden", +]); + +/** Default height of the bottom of a wall light above the floor (metres). */ +export const WALL_LAMP_Y = 1.75; + +/** Items that can be lifted off the floor (a wall cabinet, a shelf, a wall light, an LED strip): everything but lamps hung from the ceiling and the ceiling-mounted pack items. */ +export function canLift(f: Pick): boolean { + // stairs can stand on a landing or a step (the upper flight of a staircase), so they have a mount height too (#58) + if (CEILING_TYPES.has(f.type) || ["stairwell", "parking"].includes(f.type)) return false; + return packItem(f.type)?.mount !== "ceiling"; +} + +export function isLamp(type: string): boolean { + return LAMP_TYPES.has(type) || !!packItem(type)?.light; +} + +/** Furniture a table lamp can stand on. */ +const SURFACES = new Set([ + "table", + "table_round", + "coffee_table", + "desk", + "nightstand", + "sideboard", + "dresser", + "kitchen", + "island", + "worktop", + "tv_board", + "dishwasher", + "washer", + "dryer", +]); + +/** + * Positions of a rows × cols grid of lamps in a room: cells of equal size over the room's bounding box, + * one lamp per cell centre that lies inside the room (L-shaped rooms simply leave cells out). + */ +export function spotGrid(room: Room, rows: number, cols: number, inset = 0): Vec2[] { + const b = bounds(room.points); + const w = b.x1 - b.x0 - 2 * inset; + const d = b.z1 - b.z0 - 2 * inset; + const out: Vec2[] = []; + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + const p: Vec2 = [Math.round((b.x0 + inset + (w / cols) * (c + 0.5)) * 1000) / 1000, Math.round((b.z0 + inset + (d / rows) * (r + 0.5)) * 1000) / 1000]; + if (pointInPolygon(p, room.points)) out.push(p); + } + } + return out; +} + +export type Direction = "right" | "down" | "left" | "up"; + +/** Point `length` metres from `p` in a plan direction (right = +x, down = +z, as in the editor). */ +export function step(p: Vec2, length: number, dir: Direction): Vec2 { + const r = (v: number) => Math.round(v * 1000) / 1000; + const [dx, dz] = { right: [1, 0], down: [0, 1], left: [-1, 0], up: [0, -1] }[dir]; + return [r(p[0] + dx * length), r(p[1] + dz * length)]; +} + +/** Height of the highest furniture top under a point (0 = the floor). */ +/** + * Height of the bottom of a built-in model as drawn (a wall cabinet hangs at 1.45 m, a wall TV is + * centred at 1.3 m, a radiator stands on short brackets); the mount height replaces it. + */ +export function builtinBase(f: Pick & { variant?: string | null }): number { + switch (f.type) { + case "home_battery": + // a wall battery hangs at hip height + return f.variant === "wall" ? 0.5 : 0; + case "kitchen_wall": + return 1.45; + case "tv_wall": + return Math.max(0, 1.3 - f.h / 2); + case "radiator": + return 0.12; + case "inverter": + return 1.1; + case "wallbox": + return 1.0; + case "meter": + return 0.4; + default: + return 0; + } +} + +/** Furniture that hangs from the ceiling: its height comes from the ceiling above it (the room's, or its own ceiling_y). */ +export const CEILING_TYPES = new Set(["lamp_ceiling", "lamp_downlight", "lamp_spot", "lamp_panel", "lamp_pendant", "ceiling_fan"]); + +/** Rooms of lower floors whose own ceiling reaches above this floor's level (a living room open to the floor above, #55): this floor stays open over them. */ +export function roomsReachingUp(floors: readonly Floor[], floor: Floor): Vec2[][] { + return floors + .filter((f) => f.elevation < floor.elevation) + .flatMap((f) => f.rooms.filter((r) => r.points.length >= 3 && r.ceiling != null && r.ceiling > f.height + 0.005 && f.elevation + r.ceiling > floor.elevation + 0.05)) + .map((r) => r.points); +} + +/** How far a room's floor lies below or above its floor's level (m; 0 for a room without one). */ +export const roomOffset = (room: Pick | undefined): number => (room?.floor_offset && Number.isFinite(room.floor_offset) ? room.floor_offset : 0); + +/** The level of the floor at a point of a floor: the offset of the room it lies in (0 outside every room). */ +export function offsetAt(floor: Pick, x: number, z: number): number { + const room = floor.rooms.find((r) => r.points.length >= 3 && r.floor_offset && pointInPolygon([x, z], r.points)); + return roomOffset(room); +} + +/** The height of the ceiling above a point of a floor: the room's own ceiling, else the floor height. */ +export function ceilingAt(floor: Pick, x: number, z: number): number { + const room = floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([x, z], r.points)); + return room?.ceiling != null && room.ceiling > 0 ? room.ceiling : floor.height; +} + +/** The ceiling a piece hangs from: its own ceiling height set by hand, else the ceiling above it. */ +export const ceilingOf = (floor: Pick, f: Pick & { ceiling_y?: number | null }): number => + f.ceiling_y != null && f.ceiling_y > 0 ? f.ceiling_y : ceilingAt(floor, f.x, f.z); + +export function surfaceHeight(floor: Floor, x: number, z: number): number { + let top = 0; + for (const f of floor.furniture) { + if (!(SURFACES.has(f.type) || packItem(f.type)?.surface) || !pointInPolygon([x, z], furnitureFootprint(f))) continue; + top = Math.max(top, f.h); + } + return top; +} + +export const ELECTRIC_FURNITURE = new Set([ + ...LAMP_TYPES, + "radiator", + "robot_vacuum", + "inverter", + "home_battery", + "wallbox", + "meter", + "tv_board", + "tv_wall", + "desk", + "fridge", + "fridge_smart", + "stove", + "kitchen_tall", + "dishwasher", + "washer", + "dryer", + "kitchen", + "island", + "sink", +]); + +export type FurnitureType = (typeof FURNITURE_TYPES)[number]; + +/** Default size (width x, depth z, height) of new furniture in metres. */ +export const FURNITURE_SIZE: Record = { + sofa: [2.2, 0.9, 0.82], + armchair: [0.85, 0.85, 0.8], + table: [1.6, 0.9, 0.75], + chair: [0.46, 0.5, 0.9], + bed: [1.6, 2.05, 0.9], + nightstand: [0.45, 0.4, 0.5], + wardrobe: [1.8, 0.6, 2.1], + shelf: [0.9, 0.35, 1.9], + kitchen: [2.4, 0.62, 0.92], + // a worktop on its own (over a gap, on self-built desk pedestals): the height is its top edge + worktop: [1.2, 0.62, 0.91], + // solar inverter and wallbox hang on the wall, the home battery stands on the floor + inverter: [0.5, 0.2, 0.65], + home_battery: [0.6, 0.25, 1.1], + wallbox: [0.3, 0.15, 0.42], + // the meter cabinet hangs on the wall as well + meter: [0.55, 0.21, 1.1], + // the grid connection: a small street cabinet at the edge of the plot + grid_point: [0.4, 0.22, 0.6], + fridge: [0.6, 0.65, 1.8], + fridge_smart: [0.91, 0.73, 1.78], + stairwell: [1.0, 2.6, 0.02], + stove: [0.6, 0.62, 0.92], + sink: [0.9, 0.62, 0.92], + bathtub: [1.7, 0.75, 0.58], + shower: [0.9, 0.9, 2.0], + wc: [0.38, 0.6, 0.8], + washbasin: [0.6, 0.46, 0.85], + desk: [1.4, 0.7, 0.75], + tv_board: [1.8, 0.42, 0.5], + plant: [0.45, 0.45, 1.1], + rug: [2.0, 1.4, 0.01], + stairs: [1.0, 3.2, 2.75], + stool: [0.55, 0.55, 0.42], + lamp_ceiling: [0.4, 0.4, 0.08], + lamp_downlight: [0.1, 0.1, 0.02], + lamp_spot: [0.1, 0.1, 0.14], + lamp_panel: [0.6, 0.6, 0.03], + lamp_uplight: [0.35, 0.35, 1.8], + lamp_bollard: [0.16, 0.16, 0.8], + lamp_garden: [0.12, 0.12, 0.3], + radiator: [1.0, 0.1, 0.6], + robot_vacuum: [0.36, 0.5, 0.1], + parking: [2.6, 5.2, 0.02], + lamp_pendant: [0.4, 0.4, 0.8], + // a 52" fan; its height is how far it hangs down from the ceiling (more = on a downrod) + ceiling_fan: [1.32, 1.32, 0.32], + lamp_floor: [0.4, 0.4, 1.7], + lamp_table: [0.28, 0.28, 0.45], + lamp_wall: [0.22, 0.12, 0.2], + led_strip: [2.0, 0.04, 0.03], + coffee_table: [1.1, 0.6, 0.42], + tv_wall: [1.3, 0.08, 0.75], + sideboard: [1.6, 0.45, 0.8], + table_round: [1.1, 1.1, 0.75], + bench: [1.4, 0.45, 0.85], + corner_bench: [2.0, 1.6, 0.9], + bar_stool: [0.42, 0.42, 0.75], + kitchen_wall: [0.8, 0.35, 0.7], + kitchen_tall: [0.6, 0.62, 2.1], + island: [1.8, 0.9, 0.92], + dishwasher: [0.6, 0.62, 0.92], + bunk_bed: [1.0, 2.05, 1.65], + dresser: [1.0, 0.5, 0.9], + washer: [0.6, 0.6, 0.85], + dryer: [0.6, 0.6, 0.85], + office_chair: [0.65, 0.65, 1.1], + tall_cabinet: [0.6, 0.6, 2.1], + coat_rack: [1.0, 0.35, 1.9], +}; + +export const OPENING_DEFAULTS = { + door: { width: 0.9, sill: 0, height: 2.05 }, + window: { width: 1.2, sill: 0.9, height: 1.3 }, + garage: { width: 2.5, sill: 0, height: 2.1 }, +} as const; + +/** Kinds of openings offered when placing one; a terrace door is a window down to the floor. */ +/** Door looks: room doors, front doors (with glass, one or two sidelights), a glass door, a sliding door. */ +export const DOOR_STYLES = ["interior", "front", "front_glass", "sidelight", "sidelights", "glass", "sliding", "passage"] as const; +/** "glass_wall": fixed floor-to-ceiling glazing without sashes, slim mullions (an indoor glass wall, #163). */ +export const WINDOW_STYLES = ["standard", "bars", "glass_wall"] as const; +export type OpeningStyle = (typeof DOOR_STYLES)[number] | (typeof WINDOW_STYLES)[number]; + +/** Looks a door gets by itself from its wall (a front door in an outer wall, a room door inside): new doors leave them unset. */ +export const AUTO_STYLES: ReadonlySet = new Set(["interior", "front"]); + +/** The style an opening is drawn with: its own, or the automatic one for its wall. */ +export function openingStyle(o: Pick, exterior: boolean): OpeningStyle { + if (o.type === "door") return o.style && (DOOR_STYLES as readonly string[]).includes(o.style) ? o.style : exterior ? "front" : "interior"; + return o.style && (WINDOW_STYLES as readonly string[]).includes(o.style) ? o.style : "standard"; +} + +/** + * Where the fixed glass beside a front door's leaf sits, along the opening (0 … W, 2 cm margins): the + * panels and the leaf's span. One sidelight sits opposite the hinge unless `sidelight_hinge`; the widths + * come from the opening (null = automatic) and shrink together so the leaf keeps at least 0.5 m. + */ +export function sidelightLayout( + W: number, + style: OpeningStyle, + hingeAtStart: boolean, + o: Pick, +): { panels: [number, number][]; x0: number; x1: number } | null { + if (style !== "sidelight" && style !== "sidelights") return null; + const both = style === "sidelights"; + const total = W - 0.04; + const autoLeaf = Math.min(1.05, Math.max(0.6, total - (both ? 0.6 : 0.3))); + const autoSide = (total - autoLeaf) / (both ? 2 : 1); + let s1 = o.sidelight_width ?? autoSide; + let s2 = both ? (o.sidelight_width2 ?? o.sidelight_width ?? autoSide) : 0; + s1 = Math.max(0.1, s1); + s2 = both ? Math.max(0.1, s2) : 0; + const room = total - 0.5; + if (s1 + s2 > room) { + const k = Math.max(0, room) / (s1 + s2); + s1 *= k; + s2 *= k; + } + if (both) return { panels: [[0.02, 0.02 + s1], [W - 0.02 - s2, W - 0.02]], x0: 0.02 + s1, x1: W - 0.02 - s2 }; + // one panel: at the start when the hinge is at the end (opposite), or at the hinge when asked for + const atStart = hingeAtStart ? !!o.sidelight_hinge : !o.sidelight_hinge; + return atStart ? { panels: [[0.02, 0.02 + s1]], x0: 0.02 + s1, x1: W - 0.02 } : { panels: [[W - 0.02 - s1, W - 0.02]], x0: 0.02, x1: W - 0.02 - s1 }; +} + +/** A front door look (thick leaf, threshold, light above it). */ +export function isFrontDoor(style: OpeningStyle): boolean { + return style === "front" || style === "front_glass" || style === "sidelight" || style === "sidelights"; +} + +export const OPENING_PRESETS = { + door: { type: "door", leaves: 1, width: 0.9, sill: 0, height: 2.05, style: "interior" }, + front: { type: "door", leaves: 1, width: 1.0, sill: 0, height: 2.1, style: "front" }, + door_double: { type: "door", leaves: 2, width: 1.6, sill: 0, height: 2.05 }, + window: { type: "window", leaves: 1, width: 1.2, sill: 0.9, height: 1.3 }, + window_double: { type: "window", leaves: 2, width: 1.6, sill: 0.9, height: 1.3 }, + terrace: { type: "window", leaves: 1, width: 1.0, sill: 0, height: 2.1 }, + terrace_double: { type: "window", leaves: 2, width: 1.8, sill: 0, height: 2.1 }, + lift_slide: { type: "window", leaves: 1, width: 2.4, sill: 0, height: 2.15, opens: "slide" }, + garage: { type: "garage", leaves: 1, width: 2.5, sill: 0, height: 2.1 }, + glass_wall: { type: "window", leaves: 1, width: 2.0, sill: 0, height: 2.4, style: "glass_wall" }, +} as const satisfies Record; + +export type OpeningPreset = keyof typeof OPENING_PRESETS; + +/** The preset an opening matches (by type, leaves, style and whether it reaches the floor). */ +export function openingPreset(o: Pick): OpeningPreset { + if (o.type === "garage") return "garage"; + if (o.type === "window" && o.style === "glass_wall") return "glass_wall"; + if (o.type === "window" && o.opens === "slide" && o.sill < 0.1) return "lift_slide"; + const two = o.leaves === 2; + if (o.type === "door") { + if (!two && o.style && isFrontDoor(o.style)) return "front"; + return two ? "door_double" : "door"; + } + if (o.sill < 0.1) return two ? "terrace_double" : "terrace"; + return two ? "window_double" : "window"; +} + +/** Fill fields added in later versions so older saved buildings keep working. */ +export function normalizeBuilding(b: Building): Building { + b.energy = { ...DEFAULT_ENERGY, ...(b.energy ?? {}) }; + b.presence = b.presence ?? []; + b.version = 1; + b.settings = { ...DEFAULT_SETTINGS, ...b.settings, roof: { ...DEFAULT_ROOF, ...(b.settings?.roof ?? {}) } }; + b.floors.forEach((f, index) => { + const blank = newFloor(f.id, f.name ?? `Floor ${index + 1}`, f.elevation ?? index * 2.8); + for (const key of Object.keys(blank) as (keyof Floor)[]) if (f[key] === undefined) (f as unknown as Record)[key] = blank[key]; + }); + for (const f of b.floors) { + f.outdoor = f.outdoor ?? []; + f.walls = f.walls ?? []; + f.rooms = f.rooms.map((r) => ({ ...r, name: r.name ?? "", area_id: r.area_id ?? null, floor_material: r.floor_material ?? "wood", panel: r.panel ?? [] })); + f.ha_floor = f.ha_floor ?? null; + f.placements = f.placements.map((p) => ({ ...p, mount: p.mount ?? null, rotation: p.rotation ?? 0 })); + f.furniture = f.furniture.map((m) => ({ ...m, entity: m.entity ?? null, power: m.power ?? null })); + // lights placed as devices (before lamps existed) become lamps of their mount type + const lights = f.placements.filter((p) => p.entity_id.startsWith("light.")); + if (lights.length) { + const type: Record = { ceiling: "lamp_ceiling", floor: "lamp_floor", table: "lamp_table", wall: "lamp_wall" }; + for (const p of lights) { + const t = type[p.mount ?? "ceiling"]; + const [w, d, h] = FURNITURE_SIZE[t]; + const baseId = `lamp_${p.entity_id.slice(6).replace(/[^A-Za-z0-9_\-.]/g, "_")}`.slice(0, 54); + let id = baseId; + let suffix = 1; + while (f.furniture.some((item) => item.id === id)) id = `${baseId}_${suffix++}`; + f.furniture.push({ id, type: t, x: p.x, z: p.z, rotation: 0, w, d, h, variant: null, entity: p.entity_id, power: null, animations_enabled: p.animations_enabled, effect_animations: structuredClone(p.effect_animations) }); + } + f.placements = f.placements.filter((p) => !p.entity_id.startsWith("light.")); + } + f.openings = f.openings.map((o) => ({ + ...o, + type: (["door", "window", "garage"] as const).includes(o.type) ? o.type : "door", + edge: Number.isInteger(o.edge) ? o.edge : 0, + offset: Number.isFinite(o.offset) ? o.offset : 0.5, + width: Number.isFinite(o.width) && o.width > 0 ? o.width : o.type === "garage" ? 2.5 : o.type === "window" ? 1.2 : 0.9, + height: Number.isFinite(o.height) && o.height > 0 ? o.height : o.type === "window" ? 1.3 : o.type === "garage" ? 2.1 : 2.05, + sill: Number.isFinite(o.sill) ? o.sill : o.type === "window" ? 0.9 : 0, + hinge: o.hinge ?? "left", + leaves: o.leaves ?? 1, + swing: o.swing ?? "in", + style: o.style ?? null, + cover: o.cover ?? null, + contact: o.contact ?? null, + contact2: o.contact2 ?? null, + tilt: o.tilt ?? null, + })); + } + uniqueIds(b); + return b; +} + +/** Hand-written or AI-written plans often leave ids out or repeat them; the editor selects by id, so every piece needs its own. */ +function uniqueIds(b: Building): void { + const fix = (list: T[], prefix: string) => { + const seen = new Set(); + for (const item of list) { + if (typeof item.id !== "string" || !item.id || seen.has(item.id)) item.id = uid(prefix); + seen.add(item.id); + } + }; + fix(b.floors, "floor"); + for (const f of b.floors) { + // rooms are referenced by openings and walls, so only missing room ids are filled in + for (const r of f.rooms) if (typeof r.id !== "string" || !r.id) r.id = uid("room"); + fix(f.openings, "op"); + fix(f.furniture, "furn"); + fix(f.outdoor, "out"); + } +} + +export function uid(prefix: string): string { + return `${prefix}_${Math.random().toString(36).slice(2, 10)}`; +} + +/** Signed area (positive = counter-clockwise in x/z maths orientation). */ +export function signedArea(points: readonly Vec2[]): number { + let a = 0; + for (let i = 0; i < points.length; i++) { + const [x0, z0] = points[i]; + const [x1, z1] = points[(i + 1) % points.length]; + a += x0 * z1 - x1 * z0; + } + return a / 2; +} + +export function polygonArea(points: readonly Vec2[]): number { + return Math.abs(signedArea(points)); +} + +/** Area-weighted centroid; falls back to the vertex average for degenerate polygons. */ +export function centroid(points: readonly Vec2[]): Vec2 { + const a = signedArea(points); + if (Math.abs(a) < 1e-9) { + const n = points.length || 1; + return [points.reduce((s, p) => s + p[0], 0) / n, points.reduce((s, p) => s + p[1], 0) / n]; + } + let cx = 0; + let cz = 0; + for (let i = 0; i < points.length; i++) { + const [x0, z0] = points[i]; + const [x1, z1] = points[(i + 1) % points.length]; + const f = x0 * z1 - x1 * z0; + cx += (x0 + x1) * f; + cz += (z0 + z1) * f; + } + return [cx / (6 * a), cz / (6 * a)]; +} + +/** True when the polygon is an axis-aligned rectangle (so the editor can offer x/z/width/depth fields). */ +export function isAxisRect(points: readonly Vec2[]): boolean { + if (points.length !== 4) return false; + for (let i = 0; i < 4; i++) { + const [x0, z0] = points[i]; + const [x1, z1] = points[(i + 1) % 4]; + if (Math.abs(x0 - x1) > 1e-6 && Math.abs(z0 - z1) > 1e-6) return false; + } + return true; +} + +export function bounds(points: readonly Vec2[]): { x0: number; z0: number; x1: number; z1: number } { + let x0 = Infinity; + let z0 = Infinity; + let x1 = -Infinity; + let z1 = -Infinity; + for (const [x, z] of points) { + x0 = Math.min(x0, x); + z0 = Math.min(z0, z); + x1 = Math.max(x1, x); + z1 = Math.max(z1, z); + } + return { x0, z0, x1, z1 }; +} + +/** Corners of a furniture item in world x/z (rotated rectangle). */ +export function furnitureFootprint(f: Furniture): Vec2[] { + const a = (f.rotation * Math.PI) / 180; + const c = Math.cos(a); + const s = Math.sin(a); + const hw = f.w / 2; + const hd = f.d / 2; + return [ + [-hw, -hd], + [hw, -hd], + [hw, hd], + [-hw, hd], + ].map(([x, z]) => [f.x + x * c - z * s, f.z + x * s + z * c] as Vec2); +} + +export function pointInPolygon(p: Vec2, points: readonly Vec2[]): boolean { + let inside = false; + for (let i = 0, j = points.length - 1; i < points.length; j = i++) { + const [xi, zi] = points[i]; + const [xj, zj] = points[j]; + if (zi > p[1] !== zj > p[1] && p[0] < ((xj - xi) * (p[1] - zi)) / (zj - zi) + xi) inside = !inside; + } + return inside; +} + +/** 3D model of each lamp type. */ +export const LAMP_MODEL: Record = { + lamp_ceiling: "ceiling", + lamp_downlight: "downlight", + lamp_spot: "spot", + lamp_panel: "panel", + lamp_uplight: "uplight", + lamp_bollard: "bollard", + lamp_garden: "garden", + lamp_pendant: "pendant", + ceiling_fan: "fan", + lamp_floor: "floor", + lamp_table: "table", + lamp_wall: "wall", + led_strip: "strip", +}; diff --git a/frontend/src/packages.test.ts b/frontend/src/packages.test.ts new file mode 100644 index 0000000..d1f130d --- /dev/null +++ b/frontend/src/packages.test.ts @@ -0,0 +1,77 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { furnitureFootprint, type Furniture, type Room } from "./model.ts"; +import { furnishRoom, PACKAGES, type PackageId } from "./packages.ts"; + +const box = (w: number, d: number): Room => ({ id: "r", name: "R", area_id: null, points: [[0, 0], [w, 0], [w, d], [0, d]], floor_material: "wood" }); + +function furnish(pkg: PackageId, w: number, d: number): Furniture[] { + let n = 0; + return furnishRoom(box(w, d), pkg, () => `f${n++}`); +} + +test("every package stays inside a normal room and gets unique ids", () => { + for (const pkg of PACKAGES) { + const pieces = furnish(pkg, 4.4, 3.8); + assert.ok(pieces.length > 1, pkg); + assert.equal(new Set(pieces.map((p) => p.id)).size, pieces.length, `${pkg}: ids`); + for (const piece of pieces) { + for (const [x, z] of furnitureFootprint(piece)) { + assert.ok(x > -0.01 && x < 4.41 && z > -0.01 && z < 3.81, `${pkg}: ${piece.type} corner ${x}/${z}`); + } + } + } +}); + +test("pieces on a wall face into the room: back 0°, right 90°, front 180°, left 270°", () => { + const byType = (pkg: PackageId, type: string) => furnish(pkg, 4.5, 4).find((p) => p.type === type)!; + assert.equal(byType("bedroom", "bed").rotation, 0); // back wall + assert.equal(byType("living", "shelf").rotation, 90); // right wall + assert.equal(byType("bath", "bathtub").rotation, 180); // front wall + assert.equal(byType("hall", "coat_rack").rotation, 270); // left wall +}); + +test("pieces touch their wall (2 cm of air) and keep to it", () => { + const room = { w: 4.5, d: 4 }; + const tub = furnish("bath", room.w, room.d).find((p) => p.type === "bathtub")!; + assert.ok(Math.abs(tub.z - (room.d - tub.d / 2 - 0.02)) < 1e-6, "front wall"); + const rack = furnish("hall", room.w, room.d).find((p) => p.type === "coat_rack")!; + assert.ok(Math.abs(rack.x - (rack.d / 2 + 0.02)) < 1e-6, "left wall"); +}); + +test("a row is laid out side by side without overlapping, in the order of the recipe", () => { + const row = furnish("kitchen_row", 6, 3.5).filter((p) => p.z < 1 && p.type !== "kitchen_wall"); + const sorted = [...row].sort((a, b) => a.x - b.x); + assert.deepEqual(sorted.map((p) => p.type).slice(0, 2), ["fridge", "kitchen_tall"]); + sorted.slice(1).forEach((p, i) => assert.ok(p.x - p.w / 2 >= sorted[i].x + sorted[i].w / 2 - 1e-6, `${p.type} overlaps its neighbour`)); +}); + +test("what does not fit on a wall is dropped, the later pieces first", () => { + const small = furnish("kitchen_row", 2, 2).filter((p) => p.z < 0.8); + const large = furnish("kitchen_row", 6, 3.5).filter((p) => p.z < 0.8); + assert.ok(small.length < large.length); + assert.equal(small[0].type, "fridge"); +}); + +test("a row can start at the wall's end or centred", () => { + const tubRoom = furnish("bath", 4, 3); + const wc = tubRoom.find((p) => p.type === "wc")!; + const basin = tubRoom.find((p) => p.type === "washbasin")!; + assert.ok(wc.x > 4 - wc.w - 0.2, "wc at the right end"); + assert.ok(Math.abs(basin.x - 2) < 0.01, "basin in the middle"); +}); + +test("free pieces are pulled inside a tiny room instead of poking out", () => { + for (const piece of furnish("living", 2.4, 2.4)) { + if (["rug", "sofa", "coffee_table"].includes(piece.type)) { + assert.ok(piece.x - piece.w / 2 >= -0.2 && piece.x + piece.w / 2 <= 2.6, `${piece.type} x`); + } + } +}); + +test("positions are rounded to a millimetre", () => { + for (const piece of furnish("dining", 4.1237, 3.3331)) { + assert.equal(piece.x, Math.round(piece.x * 1000) / 1000); + assert.equal(piece.z, Math.round(piece.z * 1000) / 1000); + } +}); diff --git a/frontend/src/packages.ts b/frontend/src/packages.ts new file mode 100644 index 0000000..b5778f1 --- /dev/null +++ b/frontend/src/packages.ts @@ -0,0 +1,187 @@ +// Room packages: a ready-made set of furniture for a kind of room. Pieces stand against the walls of +// the room's bounding box in rows (the "back" wall is the top edge of the plan), the rest is placed freely. +// It is a starting point that the editor then adjusts. + +import { bounds, FURNITURE_SIZE, type Furniture, type FurnitureType, type Room } from "./model.ts"; + +export const PACKAGES = ["kitchen_row", "kitchen_l", "bath", "bedroom", "living", "dining", "office", "kids", "hall"] as const; +export type PackageId = (typeof PACKAGES)[number]; + +type Wall = "back" | "front" | "left" | "right"; +type Size = [width: number, depth: number, height: number]; + +/** A piece, optionally with its own size instead of the standard one. */ +type Piece = FurnitureType | [FurnitureType, Size]; + +/** Pieces side by side along a wall, starting at one end or centred. */ +type Row = [wall: Wall, align: "start" | "center" | "end", pieces: Piece[]]; + +/** A piece somewhere in the room: [piece, share of the width, share of the depth, turn in degrees]. */ +type Spot = [piece: Piece, fx: number, fz: number, turn: number]; + +interface Recipe { + rows: Row[]; + spots: Spot[]; +} + +const RECIPES: Record = { + kitchen_row: { + rows: [ + ["back", "start", ["fridge", "kitchen_tall", ["kitchen", [0.9, 0.62, 0.92]], "sink", "dishwasher", "stove", ["kitchen", [0.6, 0.62, 0.92]]]], + ["back", "start", [["kitchen_wall", [1.2, 0.35, 0.7]]]], + ], + spots: [ + [["table", [1.2, 0.8, 0.75]], 0.5, 0.72, 0], + ["lamp_pendant", 0.5, 0.72, 0], + ["lamp_ceiling", 0.5, 0.3, 0], + ], + }, + kitchen_l: { + rows: [ + ["back", "start", ["fridge", ["kitchen", [0.9, 0.62, 0.92]], "sink", "dishwasher", "stove"]], + ["right", "start", [["kitchen", [0.9, 0.62, 0.92]], ["kitchen", [0.6, 0.62, 0.92]], "kitchen_tall"]], + ["back", "start", [["kitchen_wall", [1.2, 0.35, 0.7]]]], + ], + spots: [ + ["table", 0.4, 0.68, 0], + ["bar_stool", 0.72, 0.86, 180], + ["lamp_ceiling", 0.5, 0.35, 0], + ], + }, + bath: { + rows: [ + ["back", "center", ["washbasin"]], + ["back", "end", ["wc"]], + ["front", "start", ["bathtub"]], + ["left", "start", ["washer"]], + ], + spots: [["lamp_downlight", 0.5, 0.5, 0]], + }, + bedroom: { + rows: [ + ["back", "center", ["nightstand", "bed", "nightstand"]], + ["left", "center", [["wardrobe", [2, 0.6, 2.1]]]], + ["front", "end", ["dresser"]], + ], + spots: [["lamp_ceiling", 0.5, 0.55, 0]], + }, + living: { + rows: [ + ["back", "center", ["tv_board"]], + ["right", "start", ["shelf"]], + ], + spots: [ + ["sofa", 0.5, 0.72, 180], + ["coffee_table", 0.5, 0.52, 0], + [["rug", [2.2, 1.6, 0.01]], 0.5, 0.55, 0], + ["armchair", 0.14, 0.5, 270], + ["lamp_floor", 0.86, 0.8, 0], + ["plant", 0.9, 0.12, 0], + ["lamp_ceiling", 0.5, 0.45, 0], + ], + }, + dining: { + rows: [["back", "center", ["sideboard"]]], + spots: [ + ["table", 0.5, 0.55, 0], + ["chair", 0.4, 0.35, 0], + ["chair", 0.6, 0.35, 0], + ["chair", 0.4, 0.75, 180], + ["chair", 0.6, 0.75, 180], + ["lamp_pendant", 0.5, 0.55, 0], + ], + }, + office: { + rows: [ + ["back", "center", ["desk"]], + ["left", "center", ["shelf", "shelf"]], + ], + spots: [ + ["office_chair", 0.5, 0.38, 180], + ["lamp_ceiling", 0.5, 0.55, 0], + ], + }, + kids: { + rows: [ + ["left", "start", [["bed", [0.9, 2, 0.8]]]], + ["back", "end", [["desk", [1.2, 0.6, 0.75]]]], + ["right", "end", ["shelf"]], + ], + spots: [ + [["rug", [1.6, 1.2, 0.01]], 0.55, 0.6, 0], + ["lamp_ceiling", 0.5, 0.5, 0], + ], + }, + hall: { + rows: [["left", "start", ["coat_rack"]]], + spots: [ + ["lamp_downlight", 0.5, 0.3, 0], + ["lamp_downlight", 0.5, 0.7, 0], + ], + }, +}; + +const typeOf = (piece: Piece): FurnitureType => (typeof piece === "string" ? piece : piece[0]); +const sizeOf = (piece: Piece): Size => (typeof piece === "string" ? FURNITURE_SIZE[piece] : piece[1]); + +const MARGIN = 0.05; // distance to a wall end or the room's edge +const WALL_CLEARANCE = 0.02; // air between a piece and the wall + +const thousandths = (n: number) => Math.round(n * 1000) / 1000; + +/** + * Where a piece stands when it is `along` metres from the start of a wall and `depth` metres deep. + * A wall's start is its left end seen from inside the room, so the back wall runs towards +x, the right wall + * towards +z, the front wall towards -x and the left wall towards -z. The turn makes the piece face the room. + */ +function atWall(box: { x0: number; x1: number; z0: number; z1: number }, wall: Wall, along: number, depth: number): { x: number; z: number; turn: number } { + switch (wall) { + case "back": + return { x: box.x0 + along, z: box.z0 + depth, turn: 0 }; + case "right": + return { x: box.x1 - depth, z: box.z0 + along, turn: 90 }; + case "front": + return { x: box.x1 - along, z: box.z1 - depth, turn: 180 }; + case "left": + return { x: box.x0 + depth, z: box.z1 - along, turn: 270 }; + } +} + +/** The furniture of a package for a room; `nextId` supplies the ids of the new pieces. */ +export function furnishRoom(room: Room, pkg: PackageId, nextId: () => string): Furniture[] { + const box = bounds(room.points); + const width = box.x1 - box.x0; + const depth = box.z1 - box.z0; + const made: Furniture[] = []; + const put = (type: FurnitureType, x: number, z: number, rotation: number, [w, d, h]: Size) => { + made.push({ id: nextId(), type, x: thousandths(x), z: thousandths(z), rotation, w, d, h, variant: null, entity: null, power: null }); + }; + + for (const [wall, align, pieces] of RECIPES[pkg].rows) { + const room_along = wall === "back" || wall === "front" ? width : depth; + // pieces that no longer fit on the wall are left out + let used = 0; + const fitting: Piece[] = []; + for (const piece of pieces) { + if (used + sizeOf(piece)[0] > room_along - 0.1) break; + fitting.push(piece); + used += sizeOf(piece)[0]; + } + let cursor = align === "start" ? MARGIN : align === "end" ? room_along - used - MARGIN : (room_along - used) / 2; + for (const piece of fitting) { + const size = sizeOf(piece); + const spot = atWall(box, wall, cursor + size[0] / 2, size[1] / 2 + WALL_CLEARANCE); + put(typeOf(piece), spot.x, spot.z, spot.turn, size); + cursor += size[0]; + } + } + + for (const [piece, fx, fz, turn] of RECIPES[pkg].spots) { + const size = sizeOf(piece); + const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); + const x = clamp(box.x0 + width * fx, box.x0 + size[0] / 2 + MARGIN, box.x1 - size[0] / 2 - MARGIN); + const z = clamp(box.z0 + depth * fz, box.z0 + size[1] / 2 + MARGIN, box.z1 - size[1] / 2 - MARGIN); + put(typeOf(piece), x, z, turn, size); + } + return made; +} diff --git a/frontend/src/packs.test.ts b/frontend/src/packs.test.ts new file mode 100644 index 0000000..4c1d800 --- /dev/null +++ b/frontend/src/packs.test.ts @@ -0,0 +1,175 @@ +import assert from "node:assert/strict"; +import { beforeEach, test } from "node:test"; +import { newFloor, type Furniture } from "./model.ts"; +import { coverReach, fittedParts, furnitureSize, hasMovingParts, movedParts, getPacks, hasMesh, isElectric, isClimateFurniture, isPackType, markMeshReady, mountBase, packDisplay, packItem, packItemName, packName, packScreen, packsVersion, packType, setPacks, type PackItem, type PackPart } from "./packs.ts"; + +const part = (extra: Partial = {}): PackPart => ({ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body", ...extra }); +const item = (id: string, extra: Partial = {}): PackItem => ({ id, name: { en: id }, size: [1, 1, 1], parts: [part()], ...extra }); + +beforeEach(() => + setPacks([ + { + id: "demo.pack", + name: "Demopaket", + publisher: "demo", + items: [ + item("plain"), + item("tv", { size: [1.2, 0.1, 0.7], parts: [part(), part({ screen: true, w: 0.9, d: 1, h: 0.8 })] }), + item("status", { size: [0.3, 0.1, 0.2], parts: [part({ screen: true, w: 0.1, d: 1, h: 0.2 })] }), + item("shelf", { mount: "wall", wall_y: 1.4 }), + item("hanging", { mount: "ceiling" }), + item("lampy", { light: "pendant" as never }), + item("climate", { climate: true }), + item("modelled", { mesh: "m1" }), + ], + }, + ]), +); + +const furniture = (type: string, extra: Partial = {}): Pick => ({ type, x: 1, z: 1, h: 0.5, ...extra }); + +test("pack types are built from ids and recognised by their prefix", () => { + assert.equal(packType("a", "b"), "pack:a:b"); + assert.ok(isPackType("pack:a:b")); + assert.ok(!isPackType("sofa")); +}); + +test("setPacks replaces the registry and counts a new version", () => { + const before = packsVersion(); + setPacks([]); + assert.equal(getPacks().length, 0); + assert.equal(packsVersion(), before + 1); + assert.equal(packItem("pack:demo.pack:plain"), undefined); +}); + +test("items are found by type; built-in types and unknown packs are not pack items", () => { + assert.equal(packItem("pack:demo.pack:plain")?.id, "plain"); + assert.equal(packItem("sofa"), undefined); + assert.equal(packItem("pack:other:plain"), undefined); +}); + +test("a screen part is found, and a status light is told apart from a real display", () => { + assert.ok(packScreen("pack:demo.pack:tv")); + assert.equal(packScreen("pack:demo.pack:plain"), undefined); + assert.equal(packDisplay("pack:demo.pack:tv"), true); + assert.equal(packDisplay("pack:demo.pack:status"), false); + assert.equal(packDisplay("sofa"), false); +}); + +test("sizes: built-in table, pack item, else a small default", () => { + assert.deepEqual(furnitureSize("pack:demo.pack:tv"), [1.2, 0.1, 0.7]); + assert.deepEqual(furnitureSize("pack:gone:x"), [0.6, 0.6, 0.8]); + assert.equal(furnitureSize("sofa").length, 3); +}); + +test("light and climate pack items count as electric, a plain one does not", () => { + assert.equal(isElectric("pack:demo.pack:lampy"), true); + assert.equal(isElectric("pack:demo.pack:climate"), true); + assert.equal(isClimateFurniture("pack:demo.pack:climate"), true); + assert.equal(isClimateFurniture("pack:demo.pack:plain"), false); + assert.equal(isElectric("pack:demo.pack:plain"), false); +}); + +test("names fall back from the language to English to anything to the id", () => { + assert.equal(packItemName(item("x", { name: { de: "Hallo", en: "Hello" } }), "de-AT"), "Hallo"); + assert.equal(packItemName(item("x", { name: { de: "Hallo", en: "Hello" } }), "fr"), "Hello"); + assert.equal(packItemName(item("x", { name: { de: "Hallo" } }), "fr"), "Hallo"); + assert.equal(packItemName(item("x", { name: {} }), "fr"), "x"); +}); + +test("built-in packs are English outside German, other packs keep their name", () => { + assert.equal(packName({ id: "nextfloor.garten", name: "Garten & Terrasse" }, "en"), "Garden & Terrace (older)"); + assert.equal(packName({ id: "nextfloor.garten", name: "Garten & Terrasse (älter)" }, "de-CH"), "Garten & Terrasse (älter)"); + assert.equal(packName({ id: "someone.else", name: "Mine" }, "en"), "Mine"); +}); + +test("the underside of a piece depends on how it is mounted", () => { + const floor = newFloor("g", "G", 0); + floor.height = 2.6; + assert.equal(mountBase(floor, furniture("pack:demo.pack:shelf")), 1.4); + assert.ok(Math.abs(mountBase(floor, furniture("pack:demo.pack:hanging", { h: 0.5 })) - 2.1) < 1e-9); + assert.equal(mountBase(floor, furniture("pack:demo.pack:plain")), 0); + assert.equal(mountBase(floor, { ...furniture("pack:demo.pack:plain"), mount_y: 0.9 }), 0.9); + assert.ok(mountBase(floor, furniture("led_strip", { h: 0.02 })) > 2.4); +}); + +test("a model counts only after it has loaded", () => { + assert.equal(hasMesh("pack:demo.pack:modelled"), false); + markMeshReady("m1"); + assert.equal(hasMesh("pack:demo.pack:modelled"), true); + assert.equal(hasMesh("pack:demo.pack:plain"), false); +}); + +test("a resized pack item keeps its arms, legs and plates at their size; the middle stretches", () => { + const sofa = item("sofa", { + size: [2, 0.9, 0.8], + parts: [ + part({ x: -0.45, w: 0.1, h: 0.75 }), // left arm, 20 cm + part({ x: 0.45, w: 0.1, h: 0.75 }), // right arm + part({ x: 0, w: 0.8, y: 0.3, h: 0.2 }), // seat between the arms + part({ x: -0.47, z: -0.4, w: 0.03, d: 0.05, y: 0, h: 0.1, shape: "cyl" }), // a leg, 6 cm + ], + }); + const [armL, armR, seat, leg] = fittedParts(sofa, 3, 0.9, 0.8); + const m = (frac: number, size: number) => Math.round(frac * size * 1000) / 1000; + assert.equal(m(armL.w, 3), 0.2, "the arm stays 20 cm wide"); + assert.equal(m(armL.x - armL.w / 2, 3), -1.5, "and sits at the left end"); + assert.equal(m(armR.x + armR.w / 2, 3), 1.5); + assert.equal(m(seat.w, 3), 2.6, "the seat fills the rest"); + assert.equal(m(leg.w, 3), 0.06, "the leg keeps its size"); + assert.equal(m(leg.x - leg.w / 2, 3), -1.47, "and its 3 cm from the end"); +}); + +test("a taller table gets longer legs but keeps its top plate", () => { + const table = item("table", { size: [1.2, 0.8, 0.75], parts: [part({ y: 0.95, h: 0.05 }), part({ x: -0.45, w: 0.05, d: 0.05, y: 0, h: 0.95 })] }); + const [top, legPart] = fittedParts(table, 1.2, 0.8, 1.05); + const cm = (frac: number) => Math.round(frac * 1.05 * 1000) / 10; + assert.equal(cm(top.h), 3.8, "the plate stays 3.75 cm thick"); + assert.equal(cm(top.y + top.h), 105); + assert.equal(cm(legPart.h), 101.3, "the legs reach up to the plate"); +}); + +test("unchanged sizes, vehicles and items marked stretch scale as before", () => { + const plain = item("p", { size: [1, 1, 1] }); + assert.equal(fittedParts(plain, 1, 1, 1), plain.parts); + const car = item("car", { vehicle: true }); + assert.equal(fittedParts(car, 2, 2, 2), car.parts); + const even = item("even", { stretch: true }); + assert.equal(fittedParts(even, 2, 2, 2), even.parts); +}); + +test("a much smaller item falls back to even scaling instead of folding its parts over", () => { + const box = item("box", { size: [1, 1, 1], parts: [part({ x: -0.4, w: 0.2 }), part({ x: 0.4, w: 0.2 })] }); + const [a, b] = fittedParts(box, 0.3, 1, 1); + assert.ok(a.x + a.w / 2 <= b.x - b.w / 2 + 1e-9, "parts stay side by side"); + assert.equal(Math.round(a.w * 1000) / 1000, 0.2); +}); + +test("moving parts roll up, gather to a side, reach out or slide with the cover", () => { + const cloth = part({ x: 0, w: 1, y: 0, h: 1, move: "down" }); + const [rolled] = movedParts([cloth, part()], 0.25); + assert.equal(rolled.y, 0.75, "rolled up three quarters: hangs from the top"); + assert.equal(rolled.h, 0.25); + const [left] = movedParts([part({ x: 0, w: 1, move: "left" })], 0.5); + assert.equal(left.x - left.w / 2, -0.5, "gathers at the left end"); + assert.equal(left.w, 0.5); + const [out] = movedParts([part({ z: 0, d: 1, move: "out" })], 0.4); + assert.equal(Math.round((out.z - out.d / 2) * 100) / 100, -0.5, "reaches out from the back"); + assert.equal(Math.round(out.d * 100) / 100, 0.4); + const [gate] = movedParts([part({ x: 0, w: 0.8, move: "slide_left" })], 0); + assert.equal(Math.round(gate.x * 100) / 100, -0.8, "an open gate has slid its whole width"); + assert.deepEqual(movedParts([part({ move: "down" })], 0), [], "a fully rolled-up part is gone"); +}); + +test("a cover's open position pulls a curtain in and an awning out; without an entity the parts rest", () => { + const curtain = item("curtain", { cover: "retracts", cover_rest: 0.25 }); + const awning = item("awning", { cover: "extends", cover_rest: 0 }); + assert.equal(coverReach(curtain, 100), 0); + assert.equal(coverReach(curtain, 0), 1); + assert.equal(coverReach(awning, 100), 1); + assert.equal(coverReach(awning, 30), 0.3); + assert.equal(coverReach(curtain, null), 0.25); + assert.equal(coverReach(item("plain"), null), 1); + assert.ok(hasMovingParts(item("m", { parts: [part({ move: "left" })] }))); + assert.ok(!hasMovingParts(item("plain"))); +}); diff --git a/frontend/src/packs.ts b/frontend/src/packs.ts new file mode 100644 index 0000000..0b354ce --- /dev/null +++ b/frontend/src/packs.ts @@ -0,0 +1,412 @@ +// Furniture packs. A pack is a file with items made of simple parts (format: custom_components/nextfloor/packs.py). +// Placed pack furniture has the type "pack::". Each bundle (main, editor, 3D) holds its own +// registry, filled through setPacks() with what the backend returned. + +import type { StudioRecipe } from "./studio/recipes.ts"; +import { builtinBase, ceilingAt, ceilingOf, ELECTRIC_FURNITURE, FURNITURE_SIZE, offsetAt, surfaceHeight, WALL_LAMP_Y, type Floor, type Furniture } from "./model.ts"; +import type { LampModel } from "./viewer/viewer3d.ts"; + +/** One building block of an item. Positions and extents are fractions of the item's own size. */ +export type PartMove = "down" | "left" | "right" | "out" | "slide_left" | "slide_right"; + +export interface PackPart { + /** box, cylinder, loft (a box whose top face is a different rectangle) or sweep (a smooth body along z). */ + shape: "box" | "cyl" | "loft" | "sweep"; + /** Centre across and in depth, -0.5..0.5 of width and depth; the front is +z. */ + x: number; + z: number; + /** Extent in fractions of width and depth (a cylinder's diameter is the smaller of the two). */ + w: number; + d: number; + /** Underside and height, as fractions of the item's height. */ + y: number; + h: number; + /** "#rrggbb", or the name of a palette role such as "body", "fabric" or "wood". */ + color: string; + top?: string; + /** Edge lines: true (soft blue), "glow" (cyan, like the walls) or "faint". */ + edges?: boolean | "glow" | "faint"; + /** A lamp part: lights up in the colour and brightness of the linked light. */ + glow?: boolean; + /** A screen: shows the colour and picture of the linked media player on its front face. */ + screen?: boolean; + /** A picture frame's opening: shows the item's own photo. */ + picture?: boolean; + /** A button or socket of a switch plate (0 = the first): glows while the entity of that gang is on. */ + gang?: number; + /** + * Moves with the item's cover entity: "down" rolls towards the item's top (a blind, a screen), "left"/"right" gather towards that side + * (a curtain), "out" reaches out from the back (an awning), "slide_left"/"slide_right" slide the part away (a gate). + */ + move?: PartMove; + /** Loft: centre and size of the top rectangle (default: same as the base). */ + tx?: number; + tz?: number; + tw?: number; + td?: number; + /** Cylinder axis: upright (y, the default) or lying along x or z (wheels, pipes, rollers). */ + axis?: "x" | "y" | "z"; + /** Sweep: cross sections along z as [z, bottom, top, width], as fractions of depth, height and width. */ + stations?: [number, number, number, number][]; + /** Sweep: how boxy a cross section is (2 is an ellipse) and how many points go around it. */ + exp?: number; + n?: number; + /** Drawn in the colour the owner picked for the item (see PackItem.colors). */ + paint?: boolean; + /** Turn around the part's own vertical axis, in degrees. */ + rot?: number; +} + +/** A line drawing of an item for the 2D plan. */ +export type PackSymbol = + | { shape: "rect"; x: number; z: number; w: number; d: number; fill?: boolean } + | { shape: "circle"; x: number; z: number; r: number } + | { shape: "line"; x1: number; z1: number; x2: number; z2: number }; + +export interface PackItem { + id: string; + /** Names by language code. */ + name: Record; + /** Standard width, depth and height in metres. */ + size: [number, number, number]; + electric?: boolean; + /** A thermostat / heat pump / A/C item linked to a Home Assistant climate entity. */ + climate?: boolean; + /** Stands on the floor, on furniture below it, on a wall (from wall_y up) or hangs from the ceiling. */ + mount?: "floor" | "surface" | "wall" | "ceiling"; + wall_y?: number; + /** Other items can stand on its top. */ + surface?: boolean; + /** A 3D model the owner uploaded (the id of a .glb on their Home Assistant). The parts remain the fallback. */ + mesh?: string; + /** A vehicle; offered for parking spots. */ + vehicle?: boolean; + /** An animal that roams its room in 3D (drawn apart from the furniture and walked around by the view). */ + pet?: boolean; + /** The household: a waste bin (pickup day), a mailbox (post) or a plant (soil moisture), shown from a sensor of the item. */ + household?: "bin" | "mail" | "plant"; + /** Light switches and sockets: how many buttons (gangs) it has, each linked to its own entity. */ + gangs?: number; + /** Items with moving parts: an open cover pulls them in ("retracts": curtain, screen, gate) or out ("extends": an awning). */ + cover?: "retracts" | "extends"; + /** Where the moving parts rest without a cover entity: 0 drawn in … 1 all the way out (default 1). */ + cover_rest?: number; + /** Scale every part evenly when the item is resized, instead of keeping legs, arms and plates at their size. */ + stretch?: boolean; + /** Stairs: cut a stairwell into the floor above where they reach it. */ + hole?: boolean; + /** A lamp: the way its light spreads. */ + light?: LampModel; + parts: PackPart[]; + symbol?: PackSymbol[]; + /** Colours to choose from, stored as the furniture's variant. The first is the default. */ + colors?: { id: string; name: Record; hex: string }[]; + /** Built in the editor's furniture studio: its settings, so it can be opened there again. */ + recipe?: StudioRecipe; +} + +export interface FurniturePack { + id: string; + name: string; + publisher: string; + description?: string; + /** A newer release of an installed id replaces it. */ + release?: number; + /** Ships with NextFloor and cannot be removed. */ + builtin?: boolean; + items: PackItem[]; + imported_at?: number; +} + +// ---------------------------------------------------------------- registry + +let installed: FurniturePack[] = []; +let byType = new Map(); +let generation = 0; + +export const packType = (packId: string, itemId: string): string => `pack:${packId}:${itemId}`; +export const isPackType = (type: string): boolean => type.startsWith("pack:"); + +/** Replaces the registry. */ +export function setPacks(packs: FurniturePack[]): void { + installed = packs; + byType = new Map(); + for (const pack of packs) for (const item of pack.items) byType.set(packType(pack.id, item.id), item); + generation += 1; +} + +export const getPacks = (): readonly FurniturePack[] => installed; + +/** Increases with every setPacks(), so callers can tell that packs changed. */ +export const packsVersion = (): number => generation; + +/** Old pack ids that were merged into another pack; furniture placed from them keeps working. */ +const MERGED_PACKS: Record = {}; + +/** The item behind a pack type, or undefined for built-in types and removed packs. */ +export function packItem(type: string): PackItem | undefined { + if (!isPackType(type)) return undefined; + const direct = byType.get(type); + if (direct) return direct; + const [, packId, ...itemParts] = type.split(":"); + const successor = MERGED_PACKS[packId]; + return successor ? byType.get(packType(successor, itemParts.join(":"))) : undefined; +} + +// ---------------------------------------------------------------- what an item is + +// ---------------------------------------------------------------- resizing + +/** How far from each end of an axis parts keep their real size (legs, arms, plates, handles), at most a third of the axis. */ +const KEEP = 0.22; + +/** + * Where a coordinate of the item's standard size `from` lands in a resized item of size `to`, along one axis that runs from `lo` + * to `lo + from` (x and z are centred, y starts at 0). Near either end it keeps its distance from that end; in the middle it stretches. + */ +function fitAxis(u: number, lo: number, from: number, to: number): number { + const keep = Math.min(KEEP, from / 3); + if (to <= keep * 2.4 || Math.abs(to - from) < 1e-6) return lo * (to / from) + (u - lo) * (to / from); + const newLo = lo * (to / from); + const t = u - lo; + if (t <= keep) return newLo + t; + if (t >= from - keep) return newLo + to - (from - t); + return newLo + keep + ((t - keep) * (to - 2 * keep)) / (from - 2 * keep); +} + +/** A part's extent [a, b] (fractions of `from`) on a resized axis, as fractions of `to`. */ +function fitSpan(a: number, b: number, lo: number, from: number, to: number): [number, number] { + return [fitAxis(a * from, lo * from, from, to) / to, fitAxis(b * from, lo * from, from, to) / to]; +} + +const fitted = new WeakMap>(); + +/** + * The parts of an item resized to w × d × h, with what should stay staying: within 22 cm of each end of an axis a part keeps its real + * size and its distance from that end (a sofa's 20 cm arms, a table's legs and its top plate), the middle stretches. Turned parts keep + * their own size and only move; vehicles and items marked `stretch` scale evenly. + */ +export function fittedParts(item: PackItem, w: number, d: number, h: number): PackPart[] { + const [sw, sd, sh] = item.size; + if (item.vehicle || item.stretch || (Math.abs(w - sw) < 1e-4 && Math.abs(d - sd) < 1e-4 && Math.abs(h - sh) < 1e-4)) return item.parts; + const key = `${w.toFixed(4)}|${d.toFixed(4)}|${h.toFixed(4)}`; + let cache = fitted.get(item); + const known = cache?.get(key); + if (known) return known; + const parts = item.parts.map((p): PackPart => { + if (p.shape === "sweep") return p; + const [x0, x1] = fitSpan(p.x - p.w / 2, p.x + p.w / 2, -0.5, sw, w); + const [z0, z1] = fitSpan(p.z - p.d / 2, p.z + p.d / 2, -0.5, sd, d); + const [y0, y1] = fitSpan(p.y, p.y + p.h, 0, sh, h); + if (p.rot) { + // a turned part keeps its own size: only its centre moves + return { ...p, x: (x0 + x1) / 2, z: (z0 + z1) / 2, w: (p.w * sw) / w, d: (p.d * sd) / d, y: y0, h: y1 - y0 }; + } + const next: PackPart = { ...p, x: (x0 + x1) / 2, z: (z0 + z1) / 2, w: x1 - x0, d: z1 - z0, y: y0, h: y1 - y0 }; + if (p.shape === "loft") { + const [tx, tz, tw, td] = [p.tx ?? p.x, p.tz ?? p.z, p.tw ?? p.w, p.td ?? p.d]; + const [ta, tb] = fitSpan(tx - tw / 2, tx + tw / 2, -0.5, sw, w); + const [tc, te] = fitSpan(tz - td / 2, tz + td / 2, -0.5, sd, d); + Object.assign(next, { tx: (ta + tb) / 2, tz: (tc + te) / 2, tw: tb - ta, td: te - tc }); + } + return next; + }); + if (!cache) fitted.set(item, (cache = new Map())); + if (cache.size > 32) cache.clear(); + cache.set(key, parts); + return parts; +} + +/** Whether an item has parts that move with a cover entity. */ +export const hasMovingParts = (item: PackItem | undefined): boolean => !!item?.parts.some((p) => p.move); + +/** How far the moving parts are out (0 … 1) for a cover at `position` percent open (null: no entity, they rest). */ +export function coverReach(item: PackItem, position: number | null): number { + if (position === null) return Math.min(1, Math.max(0, item.cover_rest ?? 1)); + const open = Math.min(1, Math.max(0, position / 100)); + return item.cover === "extends" ? open : 1 - open; +} + +/** Moving parts placed for a reach k (0 drawn in … 1 out); parts that have all but vanished are left out. */ +export function movedParts(parts: readonly PackPart[], k: number): PackPart[] { + const out: PackPart[] = []; + for (const p of parts) { + if (!p.move) continue; + const q: PackPart = { ...p }; + // an edge at `v` gathered towards the anchor `a` of the item (fractions): it keeps k of its distance + const toward = (v: number, a: number) => a + (v - a) * k; + if (p.move === "down") { + const [lo, hi] = [toward(p.y, 1), toward(p.y + p.h, 1)]; + Object.assign(q, { y: lo, h: hi - lo }); + } else if (p.move === "left" || p.move === "right") { + const a = p.move === "left" ? -0.5 : 0.5; + const [x0, x1] = [toward(p.x - p.w / 2, a), toward(p.x + p.w / 2, a)]; + Object.assign(q, { x: (x0 + x1) / 2, w: Math.abs(x1 - x0) }); + if (p.tx !== undefined || p.tw !== undefined) { + const [t0, t1] = [toward((p.tx ?? p.x) - (p.tw ?? p.w) / 2, a), toward((p.tx ?? p.x) + (p.tw ?? p.w) / 2, a)]; + Object.assign(q, { tx: (t0 + t1) / 2, tw: Math.abs(t1 - t0) }); + } + } else if (p.move === "out") { + const [z0, z1] = [toward(p.z - p.d / 2, -0.5), toward(p.z + p.d / 2, -0.5)]; + Object.assign(q, { z: (z0 + z1) / 2, d: z1 - z0 }); + if (p.tz !== undefined || p.td !== undefined) { + const [t0, t1] = [toward((p.tz ?? p.z) - (p.td ?? p.d) / 2, -0.5), toward((p.tz ?? p.z) + (p.td ?? p.d) / 2, -0.5)]; + Object.assign(q, { tz: (t0 + t1) / 2, td: t1 - t0 }); + } + } else { + // a sliding part moves by its own width times how far it is open + const shift = (1 - k) * p.w * (p.move === "slide_left" ? -1 : 1); + Object.assign(q, { x: p.x + shift, ...(p.tx !== undefined ? { tx: p.tx + shift } : {}) }); + } + if (q.w > 0.002 && q.d > 0.002 && q.h > 0.002) out.push(q); + } + return out; +} + +/** The screen part of an item, if it has one. */ +export const packScreen = (type: string): PackPart | undefined => packItem(type)?.parts.find((part) => part.screen); + +const MIN_DISPLAY = 0.06; // metres + +/** A real display (TV, monitor) as opposed to a status light: some screen part is at least 6 cm in both directions. */ +export function packDisplay(type: string): boolean { + const item = packItem(type); + if (!item) return false; + const [width, depth, height] = item.size; + return item.parts + .filter((part) => part.screen) + .some((part) => { + const [longest, middle] = [part.w * width, part.d * depth, part.h * height].sort((a, b) => b - a); + return middle >= MIN_DISPLAY && longest >= MIN_DISPLAY; + }); +} + +/** The standard size of any furniture type; an unknown type gets a small default. */ +export function furnitureSize(type: string): [number, number, number] { + return (FURNITURE_SIZE as Record)[type] ?? packItem(type)?.size ?? [0.6, 0.6, 0.8]; +} + +/** Whether entities (power sensor, switch ...) can be linked. A pack item that only lights counts: it links a light like a lamp. */ +export function isElectric(type: string): boolean { + const item = packItem(type); + return ELECTRIC_FURNITURE.has(type) || !!item?.electric || !!item?.light || !!item?.climate; +} +/** Whether a piece can show an own photo (a picture frame: a pack item with a picture part). */ +export const hasPicture = (type: string): boolean => !!packItem(type)?.parts.some((p) => p.picture); + +/** Whether a pack item is specifically a Home Assistant climate device. */ +export const isClimateFurniture = (type: string): boolean => !!packItem(type)?.climate; + +/** An item's name in a language: that language, else English, else whatever is there, else its id. */ +export function packItemName(item: PackItem, language: string): string { + return item.name[language.split("-")[0]] ?? item.name.en ?? Object.values(item.name)[0] ?? item.id; +} + +// Pack files carry one name (German). The packs that ship with NextFloor get English names here. +const ENGLISH_NAMES: Record = { + wohnen: "Living & Pets", + kino: "Home Cinema & Gaming", + kueche: "Kitchen Extras", + bad: "Bathroom Extras", + schlafen: "Bedroom & Kids", + technik: "Office & Homelab", + energie: "Energy & Building Services", + garten: "Garden & Terrace (older)", + fitness: "Fitness (older)", + fahrzeuge: "Vehicles", + ikea: "IKEA sizes", + treppen: "Stairs & railings", + ausbau: "Architecture & fit-out", + werkstatt: "Garage & workshop", + a_wohnzimmer: "Living room", + a_schlafzimmer: "Bedroom", + a_kueche: "Kitchen", + a_bad: "Bathroom", + a_kinderzimmer: "Kids' room", + a_buero: "Office & gaming", + a_fitness: "Fitness", + a_haustiere: "Pets", + a_garten: "Garden & patio", + a_kino: "Home cinema & hi-fi", + a_smart: "Smart home & tech", + a_haustechnik: "Utility & building services", + a_saison: "Season & decoration", + a_smart2: "Smart home 2", + a_haustechnik2: "Building services 2", + a_wellness: "Wellness", + a_garten2: "Garden 2", + a_kueche2: "Kitchen 2", + a_fahrzeuge2: "Vehicles 2", + a_aussenkueche: "Outdoor kitchen & terrace", + a_werkstatt2: "Workshop 2", + a_japandi: "Japandi & Scandi", + a_loft: "Loft & industrial", + a_gruen: "Indoor greenery", + a_musik: "Music & studio", + a_bilder: "Pictures & frames", +}; + +/** The pack's name for the user's language: built-in packs are English outside German, other packs keep their own name. */ +export function packName(pack: { id: string; name: string }, language: string): string { + if (language.split("-")[0] === "de") return pack.name; + const short = /^nextfloor\.(.+)$/.exec(pack.id)?.[1]; + return (short && ENGLISH_NAMES[short]) || pack.name; +} + +/** How high above the floor the underside of a piece is: pack items by their mount, wall lights, LED strips and own heights included. */ +export function mountBase(floor: Floor, piece: Pick & { mount_y?: number | null; ceiling_y?: number | null }): number { + if (piece.mount_y != null) return piece.mount_y; + // a room on its own level (a sunken entrance): what stands or hangs on its walls moves with its floor; ceiling items stay + return levelledBase(floor, piece) + (hangsFromCeiling(piece) ? 0 : offsetAt(floor, piece.x, piece.z)); +} + +const hangsFromCeiling = (piece: Pick): boolean => piece.type === "led_strip" || packItem(piece.type)?.mount === "ceiling"; + +function levelledBase(floor: Floor, piece: Pick & { ceiling_y?: number | null }): number { + if (piece.type === "lamp_wall") return WALL_LAMP_Y; + // LED strips sit just below the ceiling of their room + if (piece.type === "led_strip") return Math.max(0, ceilingAt(floor, piece.x, piece.z) - 0.04 - Math.max(0.02, piece.h)); + const item = packItem(piece.type); + if (!item) return builtinBase(piece); + switch (item.mount) { + case "surface": + return surfaceHeight(floor, piece.x, piece.z); + case "wall": + return item.wall_y ?? 1; + case "ceiling": + return Math.max(0, ceilingOf(floor, piece) - piece.h); + default: + return 0; + } +} + +// ---------------------------------------------------------------- owned 3D models + +/** Fetches a model file by id, or null. Set by the host, which has Home Assistant's login. */ +export type MeshSource = (id: string) => Promise; + +let meshSource: MeshSource | null = null; +const loadedMeshes = new Set(); + +export const setMeshSource = (source: MeshSource | null): void => { + meshSource = source; +}; +export const getMeshSource = (): MeshSource | null => meshSource; + +/** Records that a model has loaded and is drawn in place of its item's parts. */ +export const markMeshReady = (id: string): void => void loadedMeshes.add(id); + +/** Whether the item's own model has loaded (then its parts stay out of the merged geometry). */ +export function hasMesh(type: string): boolean { + const id = byType.get(type)?.mesh; + return id !== undefined && loadedMeshes.has(id); +} + +/** The household kind of a piece of furniture: the pack's flag, else the built-in plant, else a pack plant by its id. */ +export function householdKind(type: string): "bin" | "mail" | "plant" | null { + if (type === "plant") return "plant"; + const item = packItem(type); + if (!item) return null; + if (item.household) return item.household; + return /monstera|plant|herb_garden|flower_pots|bonsai|ficus|cactus|kaktus/.test(item.id) ? "plant" : null; +} diff --git a/frontend/src/panel.ts b/frontend/src/panel.ts new file mode 100644 index 0000000..3f94044 --- /dev/null +++ b/frontend/src/panel.ts @@ -0,0 +1,637 @@ +// The sidebar page of Home Assistant: the 3D view, the editor, and the extensions page. + +import { html, LitElement, nothing, type PropertyValues, type TemplateResult } from "lit"; +import { sunPosition, todayAt } from "./sun-position.ts"; +import { loadCardEditor } from "./load-card-editor.ts"; +import { BuildingController } from "./building-controller.ts"; +import type { PluginRef } from "./plugins/api.ts"; +import type { MarkerMode } from "./components/view3d.ts"; +import "./components/room-panel.ts"; +import "./components/view3d.ts"; +import { confirmEntities, outsideEntities } from "./devices.ts"; +import type { HeatMode } from "./heatmap.ts"; +import { awaitingLanguage, translate, type I18nKey } from "./i18n.ts"; +import { loadEditor } from "./load-editor.ts"; +import type { Building, Floor, LightMood } from "./model.ts"; +import { changeFurniture, changePlacement, dragDevice, dragFurniture, turned, withoutFurniture, withoutPlacement } from "./panel/edits.ts"; +import { furnishBar, type FurnishHost } from "./panel/furnish-bar.ts"; +import { NEXTFLOOR_MARK } from "./panel/mark.ts"; +import { browserStorage, PrefStore, type DevicePrefs } from "./panel/prefs.ts"; +import { panelStyles } from "./panel/styles.ts"; +import { colorSchemeOf, controls, readableStyles, tokens } from "./styles.ts"; +import { LOOKS, lookNow, type Look } from "./themes.ts"; +import type { HomeAssistant } from "./types.ts"; +import { allOffPlan, floorSwitchables, type ServiceCall } from "./live/all-off.ts"; +import type { FloorStack, Quality, WallMode } from "./viewer/viewer3d.ts"; + +type Mode = "view" | "editor" | "extensions"; +type Key = I18nKey; + +export class NextFloorPanel extends LitElement { + static properties = { + hass: { attribute: false }, + narrow: { type: Boolean }, + route: { attribute: false }, + panel: { attribute: false }, + _mode: { state: true }, + _editorReady: { state: true }, + _floorId: { state: true }, + _roomId: { state: true }, + _wallMode: { state: true }, + _prefs: { state: true }, + _furnish: { state: true }, + _selFurniture: { state: true }, + _selDevice: { state: true }, + _optsOpen: { state: true }, + _switchesOpen: { state: true }, + _timeOfDay: { state: true }, + _outside: { state: true }, + _timeDrag: { state: true }, + _floorUndo: { state: true }, + }; + + declare hass: HomeAssistant; + declare narrow: boolean; + declare route: unknown; + declare panel: unknown; + 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 _floorId: string | null; + private declare _roomId: string | null; + private declare _wallMode: WallMode; + /** The view settings that are remembered on this device. */ + private declare _prefs: DevicePrefs; + private declare _furnish: boolean; + private declare _selFurniture: string | null; + private declare _selDevice: string | null; + /** Phones fold the view options behind a gear button. */ + private declare _optsOpen: boolean; + /** The menu of view switches above the stage is open. */ + private declare _switchesOpen: boolean; + /** The time-of-day slider: hours shown instead of now (null: the slider is closed and the view shows the real sun). */ + private declare _timeOfDay: number | null; + /** The Outside panel is open (the house view with the garden's and the roof's devices). */ + private declare _outside: boolean; + private outsideMemo: { building: Building; entities: unknown; ids: string[] } | null = null; + /** The hour under the finger while the slider is dragged: the view follows only when it is let go (old tablets). */ + private declare _timeDrag: number | null; + /** After "everything off" on a floor: the calls that bring it back, offered for a few seconds. */ + private declare _floorUndo: ServiceCall[] | null; + private floorUndoTimer: ReturnType | undefined; + + private readonly data = new BuildingController(this); + private readonly store = new PrefStore(browserStorage()); + + constructor() { + super(); + this.narrow = false; + this._mode = "view"; + this._editorReady = !!customElements.get("nf-editor"); + this._floorId = null; + this._roomId = null; + this._wallMode = "auto"; + this._prefs = this.store.load(location.search); + this._furnish = false; + this._selFurniture = null; + this._selDevice = null; + this._optsOpen = false; + this._switchesOpen = false; + this._timeOfDay = null; + this._outside = false; + this._timeDrag = null; + this._floorUndo = null; + } + + /** Shows or hides the time-of-day switch; hiding it goes back to the real sun. */ + private toggleTimeSlider(on: boolean): void { + this.setPref("timeSlider", on); + if (!on) [this._timeOfDay, this._timeDrag] = [null, null]; + } + + /** The sun state the look follows: the real one, or the one of the hour on the time-of-day slider. */ + private sunState(): string | undefined { + const config = this.hass?.config; + if (this._timeOfDay === null || config?.latitude === undefined || config.longitude === undefined) return this.hass?.states["sun.sun"]?.state; + return sunPosition(todayAt(this._timeOfDay, config.time_zone), config.latitude, config.longitude).elevation > 0 ? "above_horizon" : "below_horizon"; + } + + /** The time-of-day chip, and while it is on the slider over the hours of today with a button back to now. */ + private renderTimeOfDay() { + const t = this.t; + if (this.hass?.config?.latitude === undefined) return nothing; + const hours = this._timeDrag ?? this._timeOfDay; + const label = (h: number) => `${String(Math.floor(h)).padStart(2, "0")}:${String(Math.round((h % 1) * 60)).padStart(2, "0")}`; + const now = () => { + const d = new Date(); + return Math.round((d.getHours() + d.getMinutes() / 60) * 4) / 4; + }; + return html` + ${hours !== null + ? html`` + : nothing}`; + } + + private readonly t = (key: Key, vars?: Record): string => translate(this.hass, key, vars); + + /** Changes one remembered setting and keeps it on this device. */ + private setPref(key: K, value: DevicePrefs[K]): void { + this._prefs = { ...this._prefs, [key]: value }; + this.store.save(key, value); + } + + protected willUpdate(changed: PropertyValues): void { + this.toggleAttribute("readable", !!this._prefs?.readable); + if (changed.has("hass") && this.hass) { + this.style.colorScheme = colorSchemeOf(this.hass); + this.data.setHass(this.hass); + } + // a floor that no longer exists (the plan was edited elsewhere) closes + const building = this.data.building; + if (building && this._floorId && !building.floors.some((f) => f.id === this._floorId)) { + this._floorId = null; + this._roomId = null; + } + } + + private get isAdmin(): boolean { + return this.hass?.user?.is_admin ?? false; + } + + private setMode(mode: Mode): void { + if (mode === this._mode) return; + if (mode === "view") void this.data.flush(); + this._mode = mode; + } + + private openFloor(floorId: string | null): void { + this._floorId = floorId; + this._roomId = null; + this._outside = false; + } + + /** The devices of Outside, worked out again only when the plan or the registry changes. */ + private outsideIds(building: Building): string[] { + 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); + this.outsideMemo = { building, entities: this.hass.entities, ids }; + return ids; + } + + /** Opens Outside over the house view (or closes it again). */ + private openOutside(): void { + const open = !this._outside; + this.openFloor(null); + this._outside = open; + } + + 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(); + // 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) { + this._roomId = roomId === this._roomId ? null : roomId; + this._outside = false; + } + } + + // furnishing in 3D: every change builds a changed copy of the plan and saves it + + private readonly furnishHost: FurnishHost = { + hass: undefined as unknown as HomeAssistant, + building: undefined as unknown as Building, + t: this.t, + editFurniture: (id, change) => this.applyEdit((b) => changeFurniture(b, id, change)), + editDevice: (entityId, change) => this.applyEdit((b) => changePlacement(b, entityId, change)), + turnFurniture: (id, delta) => this.applyEdit((b) => changeFurniture(b, id, (f) => (f.rotation = turned(f.rotation, delta)))), + turnDevice: (entityId, delta) => this.applyEdit((b) => changePlacement(b, entityId, (p) => (p.rotation = turned(p.rotation ?? 0, delta)))), + removeFurniture: (id) => { + this.applyEdit((b) => withoutFurniture(b, id)); + this._selFurniture = null; + }, + removeDevice: (entityId) => { + this.applyEdit((b) => withoutPlacement(b, entityId)); + this._selDevice = null; + }, + finish: () => { + this._furnish = false; + this._selFurniture = null; + this._selDevice = null; + }, + }; + + /** The light designer's moods of a room, saved with the plan. */ + private saveMoods(roomId: string, moods: LightMood[]): void { + this.applyEdit((b) => ({ ...b, floors: b.floors.map((f) => ({ ...f, rooms: f.rooms.map((r) => (r.id === roomId ? { ...r, moods: moods.length ? moods : undefined } : r)) })) })); + } + + private applyEdit(edit: (building: Building) => Building): void { + const building = this.data.building; + if (building) this.data.edit(edit(building)); + } + + private view3d() { + return this.renderRoot.querySelector("nf-view3d") as (HTMLElement & { resetView(): void; lookThrough(entityId: string): void }) | null; + } + + /** Escape and the back button: close the room, then the floor, and finally reset the camera. */ + private back(): void { + if (this._outside) this._outside = false; + else if (this._roomId) this._roomId = null; + else if (this._floorId && (this.data.building?.floors.length ?? 0) > 1) this._floorId = null; + else this.view3d()?.resetView(); + } + + private readonly onKey = (e: KeyboardEvent) => { + if (e.key !== "Escape" || this._mode !== "view") return; + if (this._prefs.clean) this.setPref("clean", false); + else this.back(); + }; + + connectedCallback(): void { + super.connectedCallback(); + window.addEventListener("keydown", this.onKey); + } + + disconnectedCallback(): void { + super.disconnectedCallback(); + window.removeEventListener("keydown", this.onKey); + } + + protected render() { + // a language beyond German and English: its texts are fetched first, and then everything renders + if (this.hass && awaitingLanguage(this.hass, this)) return nothing; + const building = this.data.building; + const cleanView = this._prefs.clean && this._mode === "view"; + let body: TemplateResult | typeof nothing = nothing; + if (building) { + if (this._mode === "editor" && this.isAdmin) body = this.renderEditor(building); + else if (this._mode === "extensions" && this.isAdmin) body = this.renderExtensions(); + else body = this.renderView(building); + } + return html`
    + ${cleanView ? nothing : html`${this.renderHeader(building)}${this.renderNotices()}`} + ${this.data.error && !building ? html`

    ${this.t("load_error")}: ${this.data.error}

    ` : nothing} + ${!building && !this.data.error ? html`

    ${this.t("loading")}

    ` : nothing} + ${body} +
    `; + } + + /** A row of buttons of which exactly one is pressed. */ + private choiceRow(label: Key | null, options: readonly T[], current: T, text: (option: T) => string, pick: (option: T) => void, extra: TemplateResult | typeof nothing = nothing) { + return html`
    + ${options.map((o) => html``)}${extra} +
    `; + } + + /** The accent colour well beside the looks, with a reset arrow once a colour is chosen. */ + private accentPicker() { + const accent = this._prefs.accent; + return html``; + } + + /** Quality, look, markers and the performance display; phones fold them behind the gear. */ + private renderViewOptions() { + const p = this._prefs; + return html` +
    + ${this.choiceRow("quality", ["auto", "low", "high"] as Quality[], p.quality, (q) => this.t(`quality_${q}`), (q) => this.setPref("quality", q))} + ${this.choiceRow("theme", LOOKS as readonly Look[], p.theme, (th) => this.t(`theme_${th}`), (th) => this.setPref("theme", th), this.accentPicker())} + ${this.choiceRow("markers", ["none", "important", "all"] as MarkerMode[], p.markers, (m) => this.t(`markers_${m}`), (m) => this.setPref("markers", m))} + + + +
    + ${p.announceMuted ? "🔇" : "📢"} +
    + + +

    ${this.t("screen_name_hint")}

    +
    +
    +
    + + + + + + + + +
    +
    `; + } + + private renderHeader(building: Building | null) { + const saveState = this.data.saveState; + const tab = (mode: Mode, label: string, extra = "") => + html``; + const saveLabel: Key = saveState === "saving" ? "saving" : saveState === "saved" ? "saved" : "save_error"; + return html`
    + +

    ${NEXTFLOOR_MARK}NextFloor

    + ${this.isAdmin ? html`
    ${tab("view", this.t("view"))}${tab("editor", this.t("editor"))}${tab("extensions", `✦ ${this.t("ext_tab")}`, "nf-tab-ext")}
    ` : nothing} + + ${this._mode === "view" && building?.floors.some((f) => f.rooms.length) ? this.renderViewOptions() : nothing} + ${this._mode === "editor" && saveState !== "idle" ? html`${this.t(saveLabel)}` : nothing} + v${this.data.frontendVersion} +
    `; + } + + /** Restart hint, save errors and unsaved edits left from an earlier session. */ + private renderNotices() { + const d = this.data; + const notices: TemplateResult[] = []; + if (d.needsRestart) { + // an old bundle in the browser or the companion app is cured by a reload, not by a restart + notices.push( + d.versionGap === "frontend" + ? html`
    + ${this.t("needs_reload", { frontend: d.frontendVersion, backend: d.backendVersion ?? "?" })} + +
    ` + : html`
    ${d.backendVersion ? this.t("needs_restart", { version: d.backendVersion, frontend: d.frontendVersion }) : this.t("needs_restart_old")}
    `, + ); + } + if (d.saveState === "error" && d.saveError) notices.push(html`
    ${this.t("save_failed_detail", { error: d.saveError })}
    `); + if (d.draft && this.isAdmin) { + const time = new Date(d.draft.savedAt).toLocaleString(this.hass?.language); + notices.push(html`
    + ${this.t("draft_found", { time })} + + +
    `); + } + return notices.length > 0 ? html`
    ${notices}
    ` : nothing; + } + + /** The editor and the extensions page come in one bundle that is loaded when one of them is first opened. */ + private whenEditorLoaded(show: () => TemplateResult): TemplateResult { + if (this._editorReady) return show(); + loadEditor().then( + () => (this._editorReady = true), + (err: unknown) => (this.data.error = String(err)), + ); + return html`

    ${this.t("loading")}

    `; + } + + private renderExtensions() { + return this.whenEditorLoaded(() => html` void this.data.reloadPacks()} + @plugins-changed=${(e: CustomEvent) => this.applyEdit((b) => ({ ...b, settings: { ...b.settings, plugins: e.detail } }))}>`); + } + + private renderEditor(building: Building) { + return this.whenEditorLoaded( + () => html` void this.data.reloadPacks()} + @building-changed=${(e: CustomEvent<{ building: Building }>) => this.data.edit(e.detail.building)} + >`, + ); + } + + /** A single-row bar scrolls sideways with the mouse wheel, as a desktop has no swipe. */ + private readonly onNavWheel = (e: WheelEvent) => { + if (this._prefs.navWrap || !e.deltaY || e.deltaX) return; + const nav = e.currentTarget as HTMLElement; + if (nav.scrollWidth <= nav.clientWidth) return; + nav.scrollLeft += e.deltaY; + e.preventDefault(); + }; + + /** Everything off on the open floor (the house when it has one floor), then its undo for ten seconds. */ + private allOffChip(building: Building) { + const floor = this._floorId ? building.floors.find((f) => f.id === this._floorId) : building.floors.length === 1 ? building.floors[0] : undefined; + if (!floor || !this.hass) return nothing; + if (this._floorUndo) { + const undo = this._floorUndo; + return html``; + } + const plan = allOffPlan(floorSwitchables(floor).map((id) => this.hass.states[id])); + if (plan.count < 2) return nothing; + return html``; + } + + /** The bar of floors and rooms above the stage. */ + private renderNav(building: Building) { + const shown: Floor[] = building.floors.filter((f) => !this._floorId || f.id === this._floorId); + const several = building.floors.length > 1; + const wrap = this._prefs.navWrap; + // Outside: its own chip next to the floors as soon as a device stands outside the rooms or belongs to it + const outside = this.outsideIds(building).length + ? html`` + : nothing; + const floorChips = several + ? html` + ${[...building.floors].reverse().map((f) => html``)} + ${outside} ${this.allOffChip(building)} + ` + : html`${outside} ${this.allOffChip(building)}`; + const roomChips = shown.flatMap((floor) => [ + // in the house view a small floor label comes before the rooms of each floor + shown.length > 1 && floor.rooms.length ? html`${floor.name}` : nothing, + ...floor.rooms.map( + (room) => html``, + ), + ]); + const wrapLabel = this.t(wrap ? "nav_row" : "nav_wrap"); + return html``; + } + + /** A chip that toggles one remembered setting. */ + private toggleChip(key: "roomNames" | "weather", label: Key, hint?: Key) { + return html``; + } + + /** The switches at the bottom of the stage: walls, floors, roof, floor stacking, heat map, and the chips. */ + private renderOverlay(building: Building) { + const p = this._prefs; + const t = this.t; + const pair = (a: [boolean, () => void, string], b: [boolean, () => void, string]) => + html`
    ${[a, b].map(([on, act, text]) => html``)}
    `; + const heats: HeatMode[] = ["none", "temperature", "humidity", "co2", "mould", "comfort", "power", "sun", "values", "wifi"]; + const stacks: FloorStack[] = ["dim", "stacked", "single"]; + const several = building.floors.length > 1; + const back = this._roomId || (this._floorId && several) ? html`` : nothing; + // one button for all switches, opening a menu upwards: the stage keeps the house in view, on a phone above all + const toggle = html``; + if (!this._switchesOpen) return html`
    ${toggle}${back}
    `; + return html`
    +
    (this._switchesOpen = false)}>
    +
    e.key === "Escape" && (this._switchesOpen = false)}> +
    + ${(["auto", "cut", "slope"] as const).map( + (m) => html``, + )} +
    +
    + ${several && !this._floorId ? pair([p.explode, () => this.setPref("explode", true), t("floors_apart")], [!p.explode, () => this.setPref("explode", false), t("floors_stacked")]) : nothing} + ${!this._floorId && building.settings.roof.type !== "none" + ? html`
    ` + : nothing} + ${several && this._floorId + ? html`
    + ${stacks.map((m) => html``)} +
    ` + : nothing} +
    + ${heats.map((m) => html``)} +
    + ${this.toggleChip("roomNames", "room_names_short")} + + ${this.toggleChip("weather", "weather_short", "weather_hint")} + ${p.timeSlider ? this.renderTimeOfDay() : nothing} +
    + ${toggle}${back} +
    `; + } + + private renderView(building: Building) { + if (!building.floors.some((f) => f.rooms.length)) { + return html`
    +

    ${this.t(this.isAdmin ? (building.floors.length ? "no_rooms_admin" : "no_building_admin") : "no_building")}

    + ${this.isAdmin ? html`` : nothing} +
    `; + } + const p = this._prefs; + const room = building.floors.flatMap((f) => f.rooms).find((r) => r.id === this._roomId) ?? null; + this.furnishHost.hass = this.hass; + this.furnishHost.building = building; + return html` + ${p.clean ? nothing : this.renderNav(building)} +
    + 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)} + .roomId=${this._roomId} + .outsideOpen=${this._outside} + .wallMode=${this._wallMode} + .solidWalls=${p.solidWalls} + .explode=${p.explode} + .keepRoof=${p.keepRoof} + .markerMode=${p.markers} + .heatMode=${p.heat} + .theme=${lookNow(p.theme, this.sunState())} + .timeOfDay=${this._timeOfDay} + .clock=${p.clock === "none" ? null : p.clock} + .announcements=${!p.announceMuted} + .glassWalls=${p.glassWalls} + .screenName=${p.screenName || null} + .lockButton=${true} + .walkButton=${true} + .travelButton=${true} + .accent=${p.accent} + .centralOpen=${p.menuOpen} + .keepCamera=${p.keepCamera} + .plain=${p.plain} + .rightBack=${p.rightBack} + .readable=${p.readable} + .zoom=${p.zoom / 100} + ?furnish=${this._furnish} + .selectedFurniture=${this._selFurniture} + @furniture-select=${(e: CustomEvent<{ id: string | null }>) => (this._selFurniture = e.detail.id)} + @furniture-move=${(e: CustomEvent<{ id: string; x: number; z: number }>) => this.applyEdit((b) => dragFurniture(b, e.detail.id, e.detail.x, e.detail.z))} + @device-select=${(e: CustomEvent<{ id: string | null }>) => (this._selDevice = e.detail.id)} + @device-move=${(e: CustomEvent<{ id: string; x: number; z: number }>) => this.applyEdit((b) => dragDevice(b, e.detail.id, e.detail.x, e.detail.z))} + .quality=${p.quality} + ?showStats=${p.stats} + @room-tap=${this.onRoomTap} + @floor-tap=${(e: CustomEvent<{ floorId: string | null }>) => this.openFloor(e.detail.floorId)} + @back=${() => this.back()} + > + ${room + ? html` f.rooms.some((r) => r.id === this._roomId)) ?? null} + .confirmEntities=${confirmEntities(this.hass, building.floors)} + .phrases=${building.settings.announce_phrases ?? null} + .rooms=${building.floors.flatMap((f) => f.rooms)} + @mood-change=${(e: CustomEvent<{ roomId: string; moods: LightMood[] }>) => this.saveMoods(e.detail.roomId, e.detail.moods)} + @close=${() => (this._roomId = null)} + >` + : this._outside + ? html` (this._outside = false)} + >` + : nothing} + ${p.clean ? nothing : this.renderOverlay(building)} + ${this._furnish ? furnishBar(this.furnishHost, this._selFurniture, this._selDevice) : nothing} +
    + `; + } + + static styles = [tokens, controls, panelStyles, readableStyles]; +} + +if (!customElements.get("nextfloor-panel")) customElements.define("nextfloor-panel", NextFloorPanel); diff --git a/frontend/src/panel/edits.test.ts b/frontend/src/panel/edits.test.ts new file mode 100644 index 0000000..6bbc79a --- /dev/null +++ b/frontend/src/panel/edits.test.ts @@ -0,0 +1,68 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, floorWith } from "../entities/fixtures.ts"; +import type { Building, Furniture, Placement } from "../model.ts"; +import { changeFurniture, changePlacement, dragDevice, dragFurniture, parseTyped, rounded, turned, withoutFurniture, withoutPlacement } from "./edits.ts"; + +const sofa = (extra: Partial = {}): Furniture => ({ id: "s", type: "sofa", x: 1, z: 1, rotation: 0, w: 2, d: 0.9, h: 0.8, variant: null, ...extra }); +const lamp = (extra: Partial = {}): Placement => ({ entity_id: "light.a", x: 1, z: 1, y: null, ...extra }); + +function house(): Building { + const ground = floorWith([box("r", 0, 0, 4, 4), box("q", 4, 0, 8, 3)], { furniture: [sofa()], placements: [lamp()] }); + return { version: 1, floors: [ground], settings: { wall_interior: 0.12 }, energy: {}, presence: [] } as unknown as Building; +} + +test("changing an item gives a changed copy and leaves the original alone", () => { + const before = house(); + const after = changeFurniture(before, "s", (f) => (f.w = 3)); + assert.equal(after.floors[0].furniture[0].w, 3); + assert.equal(before.floors[0].furniture[0].w, 2); + const lit = changePlacement(before, "light.a", (p, floor) => Object.assign(p, { y: 2, mount: floor.rooms.length ? "wall" : null })); + assert.deepEqual([lit.floors[0].placements[0].y, lit.floors[0].placements[0].mount], [2, "wall"]); + assert.equal(before.floors[0].placements[0].y, null); +}); + +test("an unknown id changes nothing", () => { + const after = changeFurniture(house(), "nope", () => assert.fail("must not be called")); + assert.deepEqual(after, house()); +}); + +test("removing takes out exactly that item or device", () => { + assert.equal(withoutFurniture(house(), "s").floors[0].furniture.length, 0); + assert.equal(withoutFurniture(house(), "other").floors[0].furniture.length, 1); + assert.equal(withoutPlacement(house(), "light.a").floors[0].placements.length, 0); +}); + +test("a dragged device stays in its room and slides along the wall", () => { + const inside = dragDevice(house(), "light.a", 3, 2).floors[0].placements[0]; + assert.deepEqual([inside.x, inside.z], [3, 2]); + const through = dragDevice(house(), "light.a", 6, 2).floors[0].placements[0]; + assert.deepEqual([through.x, through.z], [1, 2], "the target is in the other room, so only the free direction follows"); + const slide = dragDevice(house(), "light.a", 6, 2.5).floors[0].placements[0]; + assert.deepEqual([slide.x, slide.z], [1, 2.5], "only the free direction moves"); +}); + +test("dragged furniture sits flush at a wall with its back to it", () => { + // a sofa already facing into the room, dropped 15 cm from the south wall + const start = house(); + start.floors[0].furniture[0].rotation = 180; + const moved = dragFurniture(start, "s", 2, 3.4).floors[0].furniture[0]; + assert.ok(Math.abs(moved.z - (4 - 0.45)) < 1e-9, `z ${moved.z}`); + assert.equal(moved.rotation, 180); + const free = dragFurniture(start, "s", 2, 2).floors[0].furniture[0]; + assert.deepEqual([free.x, free.z], [2, 2]); +}); + +test("turning wraps around, in both directions", () => { + assert.equal(turned(350, 45), 35); + assert.equal(turned(10, -45), 325); + assert.equal(turned(0, 0), 0); +}); + +test("typed numbers accept a decimal comma, and rounding keeps what a field shows short", () => { + assert.equal(parseTyped("1,25"), 1.25); + assert.equal(parseTyped("0.5"), 0.5); + assert.ok(Number.isNaN(parseTyped("abc"))); + assert.equal(rounded(1.23456, 2), 1.23); + assert.equal(rounded(1.23456, 3), 1.235); +}); diff --git a/frontend/src/panel/edits.ts b/frontend/src/panel/edits.ts new file mode 100644 index 0000000..5ae30a2 --- /dev/null +++ b/frontend/src/panel/edits.ts @@ -0,0 +1,65 @@ +// Changes the panel makes to the plan while furnishing in 3D. Each one takes a building and returns a changed copy, so the caller +// only has to hand the result on to be saved. + +import { keepInRoom, snapToWall } from "../geometry/snap.ts"; +import type { Building, Floor, Furniture, Placement } from "../model.ts"; + +type FloorOf = (item: T, floor: Floor) => void; + +/** A copy of the building in which the furniture item with this id has been changed. */ +export function changeFurniture(building: Building, id: string, change: FloorOf): Building { + const next = structuredClone(building); + for (const floor of next.floors) { + const item = floor.furniture.find((f) => f.id === id); + if (item) change(item, floor); + } + return next; +} + +/** A copy of the building in which the placed device of this entity has been changed. */ +export function changePlacement(building: Building, entityId: string, change: FloorOf): Building { + const next = structuredClone(building); + for (const floor of next.floors) { + const placed = floor.placements.find((p) => p.entity_id === entityId); + if (placed) change(placed, floor); + } + return next; +} + +export function withoutFurniture(building: Building, id: string): Building { + const next = structuredClone(building); + for (const floor of next.floors) floor.furniture = floor.furniture.filter((f) => f.id !== id); + return next; +} + +export function withoutPlacement(building: Building, entityId: string): Building { + const next = structuredClone(building); + for (const floor of next.floors) floor.placements = floor.placements.filter((p) => p.entity_id !== entityId); + return next; +} + +/** A device dragged to (x, z) stays in the room it was in: no dragging through walls. */ +export function dragDevice(building: Building, entityId: string, x: number, z: number): Building { + return changePlacement(building, entityId, (placed, floor) => { + [placed.x, placed.z] = keepInRoom(floor, placed.x, placed.z, x, z); + }); +} + +/** Furniture dragged to (x, z) stays in its room, and near a wall it turns its back to it and sits flush, as in the editor. */ +export function dragFurniture(building: Building, id: string, x: number, z: number): Building { + const wall = building.settings.wall_interior ?? 0.12; + return changeFurniture(building, id, (item, floor) => { + [item.x, item.z] = keepInRoom(floor, item.x, item.z, x, z); + const snapped = snapToWall(floor, item, wall); + if (snapped) Object.assign(item, snapped); + }); +} + +/** An angle in degrees turned by `delta`, kept within 0 to 360. */ +export const turned = (degrees: number, delta: number): number => (((degrees + delta) % 360) + 360) % 360; + +/** A number typed into a size field: a decimal comma works too. NaN when it is not a number. */ +export const parseTyped = (text: string): number => Number.parseFloat(text.replace(",", ".")); + +/** Rounded to the given number of decimals, for what a size field shows and stores. */ +export const rounded = (value: number, decimals: number): number => Math.round(value * 10 ** decimals) / 10 ** decimals; diff --git a/frontend/src/panel/furnish-bar.ts b/frontend/src/panel/furnish-bar.ts new file mode 100644 index 0000000..77adf9e --- /dev/null +++ b/frontend/src/panel/furnish-bar.ts @@ -0,0 +1,132 @@ +// The bar at the bottom of the 3D view while furnishing: what is selected (a piece of furniture or a placed device), its size or +// height and mount fields, and the turn, mirror and delete buttons. + +import { html, nothing, type TemplateResult } from "lit"; +import { defaultHeight, entityName, kindOf } from "../devices.ts"; +import { furnitureName } from "../furniture-names.ts"; +import type { I18nKey } from "../i18n.ts"; +import { canLift, ceilingAt, type Building, type Floor, type Furniture, type LampMount, type Placement } from "../model.ts"; +import { mountBase } from "../packs.ts"; +import type { HomeAssistant } from "../types.ts"; +import { parseTyped, rounded } from "./edits.ts"; + +/** What the bar needs from the panel: the plan, translation, and the ways to change it. */ +export interface FurnishHost { + hass: HomeAssistant; + building: Building; + t(key: I18nKey, vars?: Record): string; + editFurniture(id: string, change: (item: Furniture, floor: Floor) => void): void; + editDevice(entityId: string, change: (placed: Placement, floor: Floor) => void): void; + turnFurniture(id: string, delta: number): void; + turnDevice(entityId: string, delta: number): void; + removeFurniture(id: string): void; + removeDevice(entityId: string): void; + /** Leaves furnishing. */ + finish(): void; +} + +interface NumberField { + label: string; + title: string; + value: number; + step: number; + min: number; + /** Values are clamped into this range; sizes just have to be valid. */ + max?: number; + /** Whether a typed number is taken (sizes must be above zero, heights may be zero). */ + accepts?: (value: number) => boolean; + apply(value: number): void; +} + +function numberField(field: NumberField): TemplateResult { + const { min, max, accepts = () => true } = field; + const onChange = (e: Event) => { + const typed = parseTyped((e.target as HTMLInputElement).value); + if (!Number.isFinite(typed) || !accepts(typed)) return; + field.apply(max === undefined ? typed : Math.min(max, Math.max(min, typed))); + }; + return html``; +} + +const autoButton = (host: FurnishHost, onClick: () => void) => html``; + +const turnButtons = (step: number, turn: (delta: number) => void) => + html``; + +/** Width, depth and height of a piece of furniture, and for wall-mounted ones the height it hangs at. */ +function furnitureFields(host: FurnishHost, id: string): TemplateResult | typeof nothing { + const floor = host.building.floors.find((fl) => fl.furniture.some((f) => f.id === id)); + const item = floor?.furniture.find((f) => f.id === id); + if (!floor || !item) return nothing; + const size = (key: "w" | "d" | "h", short: I18nKey) => + numberField({ + label: host.t(short), + title: host.t(`size_${key}` as I18nKey), + value: item[key], + step: 0.05, + min: 0.05, + accepts: (v) => v > 0, + apply: (v) => host.editFurniture(id, (f) => (f[key] = rounded(v, 3))), + }); + const mount = canLift(item) + ? html`${numberField({ + label: "↕", + title: host.t("mount_height"), + value: item.mount_y ?? mountBase(floor, item), + step: 0.05, + min: 0, + accepts: (v) => v >= 0, + apply: (v) => host.editFurniture(id, (f) => (f.mount_y = rounded(v, 3))), + })} + ${item.mount_y != null ? autoButton(host, () => host.editFurniture(id, (f) => (f.mount_y = null))) : nothing}` + : nothing; + return html`${size("w", "size_short_w")}${size("d", "size_short_d")}${size("h", "size_short_h")} ${mount}`; +} + +/** Height of a placed device; for lights the mount. */ +function deviceFields(host: FurnishHost, entityId: string): TemplateResult | typeof nothing { + const floor = host.building.floors.find((fl) => fl.placements.some((p) => p.entity_id === entityId)); + const placed = floor?.placements.find((p) => p.entity_id === entityId); + if (!floor || !placed) return nothing; + const kind = kindOf(entityId); + const mountSelect = (title: I18nKey, options: [LampMount, string][], current: LampMount) => + html``; + const lampMounts = (["ceiling", "floor", "table", "wall"] as const).map((m): [LampMount, string] => [m, host.t(`lamp_${m}`)]); + const automatic = kind ? defaultHeight(kind, ceilingAt(floor, placed.x, placed.z), kind === "light" ? (placed.mount ?? "ceiling") : null) : 1; + return html`${kind === "light" ? mountSelect("lamp_mount", lampMounts, placed.mount ?? "ceiling") : nothing} + ${numberField({ + label: host.t("size_short_h"), + title: host.t("marker_height"), + value: placed.y ?? automatic, + step: 0.05, + min: 0, + accepts: (v) => v >= 0, + apply: (v) => host.editDevice(entityId, (d) => (d.y = rounded(v, 3))), + })} + ${placed.y !== null ? autoButton(host, () => host.editDevice(entityId, (d) => (d.y = null))) : nothing}`; +} + +/** The whole bar, for whatever is selected (furniture first, then a device), or a hint when nothing is. */ +export function furnishBar(host: FurnishHost, furnitureId: string | null, deviceId: string | null): TemplateResult { + const t = host.t; + let body: TemplateResult; + if (furnitureId) { + const type = host.building.floors.flatMap((fl) => fl.furniture).find((f) => f.id === furnitureId)?.type; + body = html`${type ? furnitureName(host.hass, type) : ""} + ${furnitureFields(host, furnitureId)} ${turnButtons(45, (delta) => host.turnFurniture(furnitureId, delta))} + + `; + } else if (deviceId) { + body = html`${entityName(host.hass, deviceId)} + ${deviceFields(host, deviceId)} ${turnButtons(45, (delta) => host.turnDevice(deviceId, delta))} + `; + } else { + body = html`${t("furnish_hint")}`; + } + return html`
    ${body}
    `; +} diff --git a/frontend/src/panel/mark.ts b/frontend/src/panel/mark.ts new file mode 100644 index 0000000..c3fdf95 --- /dev/null +++ b/frontend/src/panel/mark.ts @@ -0,0 +1,10 @@ +import { svg } from "lit"; + +/** The NextFloor mark: three floors with the next one dashed above, and the light on. */ +export const NEXTFLOOR_MARK = svg``; diff --git a/frontend/src/panel/prefs.test.ts b/frontend/src/panel/prefs.test.ts new file mode 100644 index 0000000..7b04a76 --- /dev/null +++ b/frontend/src/panel/prefs.test.ts @@ -0,0 +1,97 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { PrefStore, screenMuted, screenName, type PrefsStorage } from "./prefs.ts"; + +function memory(initial: Record = {}): PrefsStorage & { data: Record } { + const data = { ...initial }; + return { data, getItem: (k) => data[k] ?? null, setItem: (k, v) => void (data[k] = v) }; +} + +test("nothing stored gives the defaults", () => { + const prefs = new PrefStore(memory()).load(); + assert.deepEqual(prefs, { + explode: true, keepRoof: false, solidWalls: false, quality: "auto", stats: false, markers: "important", heat: "none", theme: "neon", accent: null, + floorStack: "dim", roomNames: true, clean: false, navWrap: false, weather: true, timeSlider: false, menuOpen: false, keepCamera: false, readable: false, plain: false, rightBack: false, zoom: 100, clock: "none", screenName: "", announceMuted: false, glassWalls: 20, + }); +}); + +test("a screen's name and mute switch are kept, and cards read them too", () => { + const storage = memory(); + const store = new PrefStore(storage); + store.save("screenName", " Hallway "); + store.save("announceMuted", true); + const prefs = new PrefStore(storage).load(); + assert.equal(prefs.screenName, "Hallway"); + assert.equal(prefs.announceMuted, true); + assert.equal(screenName(storage), "Hallway"); + assert.equal(screenMuted(storage), true); + assert.equal(screenName(memory()), null); +}); + +test("the auto look and a clock corner are kept", () => { + const storage = memory(); + const store = new PrefStore(storage); + store.save("theme", "auto"); + store.save("clock", "top_right"); + const prefs = new PrefStore(storage).load(); + assert.equal(prefs.theme, "auto"); + assert.equal(prefs.clock, "top_right"); +}); + +test("saved values come back, under the key names earlier versions used", () => { + const storage = memory(); + const store = new PrefStore(storage); + store.save("explode", false); + store.save("keepRoof", true); + store.save("floorStack", "single"); + store.save("navWrap", true); + store.save("accent", "#12ab34"); + assert.equal(storage.data["nextfloor.explode"], "0"); + assert.equal(storage.data["nextfloor.roof"], "1"); + assert.equal(storage.data["nextfloor.floor_stack"], "single"); + assert.equal(storage.data["nextfloor.nav_wrap"], "1"); + const back = store.load(); + assert.deepEqual([back.explode, back.keepRoof, back.floorStack, back.navWrap, back.accent], [false, true, "single", true, "#12ab34"]); +}); + +test("unknown words and malformed colours fall back, and an empty accent means the stock one", () => { + const store = new PrefStore(memory({ "nextfloor.quality": "ultra", "nextfloor.theme": "sepia", "nextfloor.accent": "teal", "nextfloor.heat": "co2" })); + const prefs = store.load(); + assert.equal(prefs.quality, "auto"); + assert.equal(prefs.theme, "neon"); + assert.equal(prefs.accent, null); + assert.equal(prefs.heat, "co2"); + store.save("accent", null); + assert.equal(store.load().accent, null); +}); + +test("?nf_stats turns the performance display on", () => { + const store = new PrefStore(memory()); + assert.equal(store.load("").stats, false); + assert.equal(store.load("?a=1&nf_stats").stats, true); +}); + +test("a storage that is missing or throws never breaks anything", () => { + const broken: PrefsStorage = { + getItem: () => { + throw new Error("blocked"); + }, + setItem: () => { + throw new Error("blocked"); + }, + }; + for (const storage of [null, broken]) { + const store = new PrefStore(storage); + assert.doesNotThrow(() => store.save("theme", "day")); + assert.equal(store.load().theme, "neon"); + } +}); + +test("the glass walls' opacity is kept in whole percent between 0 and 100", () => { + const storage = memory(); + new PrefStore(storage).save("glassWalls", 135); + assert.equal(new PrefStore(storage).load().glassWalls, 100); + new PrefStore(storage).save("glassWalls", 0); + assert.equal(new PrefStore(storage).load().glassWalls, 0); + assert.equal(new PrefStore(memory({ "nextfloor.glass_walls": "abc" })).load().glassWalls, 20); +}); diff --git a/frontend/src/panel/prefs.ts b/frontend/src/panel/prefs.ts new file mode 100644 index 0000000..595d583 --- /dev/null +++ b/frontend/src/panel/prefs.ts @@ -0,0 +1,175 @@ +// What the panel remembers per device: a wall tablet wants other view settings than a desktop. Each preference is a small codec +// (storage name, fallback, how to read and write it), so loading and saving are the same few lines for all of them. + +import type { MarkerMode } from "../components/view3d.ts"; +import type { HeatMode } from "../heatmap.ts"; +import { LOOKS, type Look } from "../themes.ts"; +import type { FloorStack, Quality } from "../viewer/viewer3d.ts"; + +export interface DevicePrefs { + explode: boolean; + keepRoof: boolean; + /** Solid painted walls instead of glass. */ + solidWalls: boolean; + quality: Quality; + stats: boolean; + markers: MarkerMode; + heat: HeatMode; + theme: Look; + /** "#rrggbb", or null for the stock accent. */ + accent: string | null; + floorStack: FloorStack; + roomNames: boolean; + clean: boolean; + navWrap: boolean; + weather: boolean; + /** The ☀ time-of-day switch under the 3D view (off: the view always shows the real sun). */ + timeSlider: boolean; + /** The star menu (favourites) stands open from the start, a size larger. */ + menuOpen: boolean; + /** Switching floors keeps the camera's side, height and distance. */ + keepCamera: boolean; + /** Easy to read: stronger contrast and larger text for wall tablets. */ + readable: boolean; + /** Only the floor plan: walls, doors, windows and stairs without furniture (devices and pins stay). */ + plain: boolean; + /** A short right click goes one step back (like a double tap on empty space). */ + rightBack: boolean; + /** How much closer the fitted views come, in % (100 = fitted). */ + zoom: number; + /** A clock in a corner of the 3D view, or none. */ + clock: "none" | "top_left" | "top_right" | "bottom_left" | "bottom_right"; + /** How opaque the see-through walls are, in % (20: faint glass). */ + glassWalls: number; + /** The name of this screen for announcements meant for some screens only ("" = none). */ + screenName: string; + /** Announcements are not shown or spoken on this device. */ + announceMuted: boolean; +} + +interface Codec { + /** The key in the browser's storage (below the "nextfloor." prefix). */ + name: string; + fallback: T; + read(raw: string): T; + write(value: T): string; +} + +/** A yes/no switch stored as "1" and "0". What is on by default only turns off on an explicit "0". */ +const flag = (name: string, fallback: boolean): Codec => ({ + name, + fallback, + read: (raw) => (fallback ? raw !== "0" : raw === "1"), + write: (value) => (value ? "1" : "0"), +}); + +/** One of a fixed list of words; anything else counts as unset. */ +const word = (name: string, allowed: readonly T[], fallback: T): Codec => ({ + name, + fallback, + read: (raw) => allowed.find((w) => w === raw) ?? fallback, + write: (value) => value, +}); + +const CODECS: { [K in keyof DevicePrefs]: Codec } = { + explode: flag("explode", true), + keepRoof: flag("roof", false), + solidWalls: flag("solid_walls", false), + quality: word("quality", ["auto", "low", "high"], "auto"), + stats: flag("stats", false), + markers: word("markers", ["none", "important", "all"], "important"), + heat: word("heat", ["none", "temperature", "humidity", "co2", "mould", "comfort", "power", "sun", "values", "wifi"], "none"), + theme: word("theme", LOOKS, "neon"), + clock: word("clock", ["none", "top_left", "top_right", "bottom_left", "bottom_right"], "none"), + accent: { name: "accent", fallback: null, read: (raw) => (/^#[0-9a-f]{6}$/i.test(raw) ? raw : null), write: (value) => value ?? "" }, + floorStack: word("floor_stack", ["dim", "stacked", "single"], "dim"), + roomNames: flag("room_names", true), + clean: flag("clean", false), + navWrap: flag("nav_wrap", false), + weather: flag("weather", true), + timeSlider: flag("time_slider", false), + menuOpen: flag("menu_open", false), + keepCamera: flag("keep_camera", false), + readable: flag("readable", false), + plain: flag("plain", false), + rightBack: flag("right_back", false), + zoom: { + name: "zoom", + fallback: 100, + read: (raw) => (/^\d{2,3}$/.test(raw) ? Math.min(250, Math.max(60, Number(raw))) : 100), + write: (value) => String(Math.round(Math.min(250, Math.max(60, value)))), + }, + screenName: { name: "screen_name", fallback: "", read: (raw) => raw.slice(0, 60), write: (value) => value.trim().slice(0, 60) }, + announceMuted: flag("announce_muted", false), + glassWalls: { + name: "glass_walls", + fallback: 20, + read: (raw) => (/^\d{1,3}$/.test(raw) ? Math.min(100, Number(raw)) : 20), + write: (value) => String(Math.round(Math.min(100, Math.max(0, value)))), + }, +}; + +/** This device's screen name and mute switch, also for cards (which have no preferences of their own). */ +export function screenName(storage: PrefsStorage | null = browserStorage()): string | null { + try { + return storage?.getItem("nextfloor.screen_name")?.trim() || null; + } catch { + return null; + } +} + +export function screenMuted(storage: PrefsStorage | null = browserStorage()): boolean { + try { + return storage?.getItem("nextfloor.announce_muted") === "1"; + } catch { + return false; + } +} + +export type PrefsStorage = Pick; + +/** The browser's local storage, or null where it is not available (private mode, blocked site data). */ +export function browserStorage(): PrefsStorage | null { + try { + return localStorage; + } catch { + return null; + } +} + +export class PrefStore { + private readonly storage: PrefsStorage | null; + + constructor(storage: PrefsStorage | null) { + this.storage = storage; + } + + private raw(name: string): string | null { + try { + return this.storage?.getItem(`nextfloor.${name}`) ?? null; + } catch { + return null; + } + } + + /** All preferences. `?nf_stats` in the page's URL switches the performance display on whatever was stored. */ + load(search = ""): DevicePrefs { + const prefs = {} as Record; + for (const key of Object.keys(CODECS) as (keyof DevicePrefs)[]) { + const codec = CODECS[key] as Codec; + const raw = this.raw(codec.name); + prefs[key] = raw === null ? codec.fallback : codec.read(raw); + } + if (new URLSearchParams(search).has("nf_stats")) prefs.stats = true; + return prefs as unknown as DevicePrefs; + } + + save(key: K, value: DevicePrefs[K]): void { + const codec = CODECS[key] as Codec; + try { + this.storage?.setItem(`nextfloor.${codec.name}`, codec.write(value)); + } catch { + // storage unavailable: the choice just is not remembered + } + } +} diff --git a/frontend/src/panel/styles.ts b/frontend/src/panel/styles.ts new file mode 100644 index 0000000..2f51c54 --- /dev/null +++ b/frontend/src/panel/styles.ts @@ -0,0 +1,489 @@ +import { css } from "lit"; + +/** The panel's own styles: header, floor and room bar, the stage with its overlay and room panel, the furnish bar, and the phone layout. */ +export const panelStyles = css` + .nf-dot { + display: inline-block; + width: 8px; + height: 8px; + margin-left: 6px; + border-radius: 50%; + background: #ffb547; + box-shadow: 0 0 8px #ffb547; + vertical-align: middle; + } + :host { + display: block; + /* HA gives the custom panel's parent no explicit height, so 100% collapses. */ + height: 100vh; + height: 100dvh; + background: var(--nf-bg); + } + .nf-app { + display: flex; + flex-direction: column; + height: 100%; + min-height: 0; + } + .nf-header { + display: flex; + align-items: center; + gap: 12px; + padding: 6px 14px 6px 4px; + min-height: 56px; + border-bottom: var(--app-header-border-bottom, 1px solid var(--nf-line)); + background: var(--app-header-background-color, var(--nf-chrome-solid)); + color: var(--app-header-text-color, var(--nf-text)); + flex-wrap: wrap; + /* above the room bar, so a menu opened from the header (the screen's announcements) is not covered */ + position: relative; + z-index: 30; + } + ha-menu-button { + color: var(--app-header-text-color, var(--nf-text)); + } + h1 { + display: flex; + align-items: center; + gap: 10px; + font-weight: 400; + font-size: 20px; + margin: 0 4px 0 8px; + white-space: nowrap; + } + .nf-mark { + width: 26px; + height: 28px; + color: var(--nf-accent); + } + .nf-notices { + display: grid; + gap: 6px; + padding: 8px 14px 0; + } + .nf-notice { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 12px; + padding: 9px 12px; + border-radius: 10px; + border: 1px solid var(--nf-line); + background: var(--nf-chrome-solid); + font-size: 13.5px; + } + .nf-notice span { + flex: 1; + min-width: 200px; + } + .nf-notice-warn { + border-color: color-mix(in srgb, var(--nf-warm) 60%, transparent); + color: var(--nf-warm); + } + .nf-notice-error { + border-color: color-mix(in srgb, var(--nf-danger) 60%, transparent); + color: var(--nf-danger); + word-break: break-word; + } + .nf-chip-on { + background: var(--nf-accent); + color: var(--nf-accent-text); + } + .nf-furnish-bar { + position: absolute; + left: 50%; + bottom: 16px; + transform: translateX(-50%); + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 8px; + max-width: calc(100% - 24px); + padding: 8px 10px 8px 16px; + border-radius: 999px; + background: var(--nf-chrome); + box-shadow: var(--nf-shadow); + font-size: 13.5px; + } + .nf-size-select { + font: inherit; + color: var(--nf-text); + background: var(--nf-chrome-solid); + border: 1px solid var(--nf-line); + border-radius: 999px; + padding: 4px 10px; + } + .nf-size { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: 12px; + color: var(--nf-muted); + } + .nf-size input { + width: 58px; + padding: 5px 6px; + border: 1px solid rgba(127, 127, 127, 0.35); + border-radius: 8px; + background: transparent; + color: inherit; + font: inherit; + font-size: 13px; + } + .nf-danger-chip { + color: var(--nf-danger); + } + .nf-grow { + flex: 1; + } + .nf-save { + font-size: 12.5px; + color: var(--nf-muted); + } + .nf-view-opts { + display: contents; + } + .nf-opts-btn { + display: none; + } + /* phones: the view options fold behind ⚙ (one header row instead of three) */ + @media (max-width: 700px) { + .nf-opts-btn { + display: grid; + place-items: center; + order: 3; + width: 36px; + height: 36px; + border: 1px solid var(--nf-line); + border-radius: 10px; + background: transparent; + color: var(--nf-text); + font-size: 17px; + cursor: pointer; + } + .nf-opts-btn[aria-expanded="true"] { + color: var(--nf-accent); + border-color: var(--nf-accent); + } + .nf-view-opts { + display: none; + } + .nf-view-opts.nf-opts-open { + display: flex; + flex-wrap: wrap; + gap: 8px; + order: 5; + width: 100%; + } + .nf-version { + order: 4; + } + .nf-header .nf-grow { + display: none; + } + } + /* the installed version, at the far right of the header */ + .nf-version { + margin-left: auto; + font-size: 11.5px; + color: var(--nf-muted); + white-space: nowrap; + opacity: 0.8; + } + .nf-save-error { + color: var(--nf-danger); + } + .nf-body { + flex: 1; + min-height: 0; + } + /* the colour well beside the look: a small round swatch, the reset arrow next to it */ + .nf-accent-pick { + display: inline-flex; + align-items: center; + gap: 2px; + padding: 0 4px; + } + .nf-clock-pick { + display: inline-flex; + align-items: center; + gap: 2px; + padding: 0 4px 0 10px; + font-size: 14px; + } + .nf-clock-pick select { + border: 0; + background: none; + color: var(--nf-text); + font: inherit; + font-size: 13px; + padding: 6px 2px; + cursor: pointer; + } + .nf-clock-pick option { + color: #111; + } + .nf-glass-pick { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 0 10px; + font-size: 13px; + } + .nf-glass-pick input { + width: 80px; + accent-color: var(--nf-accent); + } + .nf-screen-pick { + position: relative; + display: inline-flex; + align-items: center; + } + .nf-screen-pick > summary { + list-style: none; + cursor: pointer; + padding: 6px 10px; + font-size: 14px; + } + .nf-screen-pick > summary::-webkit-details-marker { + display: none; + } + .nf-screen-menu { + position: absolute; + top: calc(100% + 6px); + right: 0; + z-index: 20; + display: grid; + gap: 10px; + width: 260px; + padding: 12px; + border: 1px solid var(--nf-line); + border-radius: 14px; + background: var(--nf-chrome-solid); + box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35); + } + .nf-screen-menu .nf-check { + display: flex; + align-items: center; + gap: 8px; + font-size: 14px; + color: var(--nf-text); + } + .nf-screen-hint { + margin: 0; + font-size: 12px; + color: var(--nf-muted); + } + .nf-accent-pick input[type="color"] { + width: 22px; + height: 22px; + padding: 0; + border: 1px solid var(--nf-line); + border-radius: 50%; + background: none; + cursor: pointer; + } + .nf-accent-pick input[type="color"]::-webkit-color-swatch-wrapper { + padding: 2px; + } + .nf-accent-pick input[type="color"]::-webkit-color-swatch { + border: none; + border-radius: 50%; + } + .nf-accent-reset { + border: none; + background: none; + color: var(--nf-muted); + cursor: pointer; + font-size: 14px; + padding: 0 2px; + } + .nf-nav { + display: flex; + align-items: center; + gap: 6px; + padding: 10px 14px; + overflow-x: auto; + scrollbar-width: none; + flex: none; + } + /* a desktop shows a thin scrollbar while the pointer rests on the bar */ + .nf-nav:hover { + scrollbar-width: thin; + } + /* wrapped: several lines, at most about three before the bar itself scrolls */ + .nf-nav-wrap { + flex-wrap: wrap; + overflow-x: visible; + overflow-y: auto; + max-height: 132px; + } + .nf-nav-floor { + flex: none; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--nf-muted); + margin-left: 6px; + } + .nf-nav-toggle { + flex: none; + margin-left: auto; + position: sticky; + right: 0; + min-width: 34px; + padding-left: 8px; + padding-right: 8px; + } + .nf-nav .nf-chip { + box-shadow: none; + border: 1px solid var(--nf-line); + } + .nf-sep { + flex: none; + width: 1px; + margin: 4px 4px; + background: var(--nf-line); + } + .nf-stage-wrap { + position: relative; + flex: 1; + min-height: 0; + display: flex; + container-type: size; + container-name: nf; + } + .nf-stage-wrap nf-view3d { + flex: 1; + } + .nf-room-panel { + position: absolute; + top: 58px; + right: 14px; + bottom: 14px; + width: min(360px, calc(100% - 28px)); + display: flex; + flex-direction: column; + justify-content: flex-start; + pointer-events: none; + } + /* folded, the panel is only its title bar: on a wide stage it drops to the bottom edge, above the switches, instead of hanging in the picture */ + .nf-room-panel[folded] { + justify-content: flex-end; + bottom: 62px; + } + .nf-clean .nf-room-panel[folded] { + bottom: 14px; + } + /* the switches sit at the bottom (as in the card), where they never meet the energy values or warnings */ + nf-view3d { + --nf-bottom-inset: 52px; + } + .nf-clean nf-view3d { + --nf-bottom-inset: 0px; + } + .nf-furnish-bar { + bottom: 68px; + } + /* small landscape tablets: the room panel gets a little more of the width, its rows stay easy to hit */ + @container nf ((min-width: 701px) and (max-width: 1180px)) { + .nf-room-panel { + width: min(420px, 44%); + } + } + /* phones and portrait tablets: panel as a sheet at the bottom, the switches step aside */ + @container nf ((max-width: 700px) or ((orientation: portrait) and (max-width: 1000px))) { + .nf-room-panel { + top: auto; + left: 8px; + right: 8px; + bottom: 8px; + width: auto; + height: 55%; + justify-content: flex-end; + } + .nf-room-open .nf-overlay { + display: none; + } + } + .nf-overlay { + position: absolute; + right: 12px; + bottom: 12px; + /* room for the search button and the row beside it (eye, lock, walk, time travel) */ + left: 236px; + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 8px; + align-items: center; + pointer-events: none; + } + .nf-overlay > * { + pointer-events: auto; + } + /* phones: the bar only holds the switches button and "back", so it can span the bottom; the buttons of the view sit above it */ + @container nf (max-width: 700px) { + .nf-overlay { + left: 12px; + } + .nf-switches { + left: 0; + width: auto; + } + } + /* the switches: a menu that opens upwards from the bar, over the stage, closed by a tap beside it or Escape */ + .nf-switches-veil { + position: fixed; + inset: 0; + z-index: 4; + } + .nf-switches { + position: absolute; + right: 0; + bottom: calc(100% + 8px); + z-index: 5; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + width: min(520px, calc(100cqw - 24px)); + max-height: min(60vh, 420px); + overflow-y: auto; + overscroll-behavior: contain; + padding: 12px; + border: 1px solid var(--nf-line); + border-radius: 14px; + background: var(--nf-chrome-solid); + box-shadow: var(--nf-shadow); + } + .nf-switches .nf-seg { + flex-wrap: wrap; + } + .nf-switches .nf-chip { + box-shadow: none; + } + .nf-caret { + font-size: 0.75em; + opacity: 0.7; + } + .nf-quality button { + padding: 5px 11px; + min-height: 30px; + font-size: 13px; + } + .nf-message, + .nf-empty { + padding: 32px 20px; + color: var(--nf-muted); + text-align: center; + } + .nf-empty { + display: grid; + justify-items: center; + gap: 12px; + margin: auto; + } +`; diff --git a/frontend/src/parking.test.ts b/frontend/src/parking.test.ts new file mode 100644 index 0000000..862f71a --- /dev/null +++ b/frontend/src/parking.test.ts @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import { beforeEach, test } from "node:test"; +import { emptyBuilding, newFloor, type Furniture } from "./model.ts"; +import { setPacks } from "./packs.ts"; +import { parkedVehicle, parkedVehicles, parkingEntities, vehicleFurniture, withVehicles } from "./parking.ts"; +import type { HomeAssistant } from "./types.ts"; + +const COMPACT = "pack:test.garage:compact"; +const TRUCK = "pack:test.garage:truck"; + +const part = { shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body" } as const; + +beforeEach(() => { + setPacks([ + { + id: "test.garage", + name: "Garage", + publisher: "test", + items: [ + { id: "compact", name: { en: "Compact" }, size: [1.7, 3.6, 1.5], vehicle: true, parts: [part] }, + { id: "truck", name: { en: "Truck" }, size: [2.4, 6, 2.8], vehicle: true, parts: [part] }, + ], + }, + ]); +}); + +const hassWith = (states: Record) => + ({ states: Object.fromEntries(Object.entries(states).map(([id, state]) => [id, { entity_id: id, state, attributes: {} }])) }) as unknown as HomeAssistant; + +const spot = (extra: Partial = {}): Furniture => ({ id: "spot", type: "parking", x: 1, z: 2, rotation: 45, w: 2.5, d: 5, h: 0.02, variant: null, entity: null, vehicle: COMPACT, ...extra }); + +test("without a presence entity the vehicle is always there", () => { + assert.equal(parkedVehicle(hassWith({}), spot()), COMPACT); + assert.equal(parkedVehicle(hassWith({}), spot({ vehicle: null })), null); +}); + +test("with a presence entity the vehicle follows it, and an unknown entity means no car", () => { + const s = spot({ entity: "device_tracker.car" }); + assert.equal(parkedVehicle(hassWith({ "device_tracker.car": "home" }), s), COMPACT); + assert.equal(parkedVehicle(hassWith({ "device_tracker.car": "not_home" }), s), null); + assert.equal(parkedVehicle(hassWith({}), s), null); + assert.equal(parkedVehicle(hassWith({ "device_tracker.car": "HOME" }), s), COMPACT); +}); + +test("furniture that is not a parking spot never shows a vehicle", () => { + assert.equal(parkedVehicle(hassWith({}), spot({ type: "sofa" })), null); +}); + +test("a type sensor picks the model: exact word first, then a word inside the text", () => { + const s = spot({ + type_entity: "sensor.camera_vehicle", + types: [ + { state: "van", vehicle: TRUCK }, + { state: "compact", vehicle: COMPACT }, + ], + }); + assert.equal(parkedVehicle(hassWith({ "sensor.camera_vehicle": "van" }), s), TRUCK); + assert.equal(parkedVehicle(hassWith({ "sensor.camera_vehicle": "a red Van parked" }), s), TRUCK); + // nothing matches: keep the spot's own vehicle + assert.equal(parkedVehicle(hassWith({ "sensor.camera_vehicle": "bicycle" }), s), COMPACT); + assert.equal(parkedVehicle(hassWith({ "sensor.camera_vehicle": "" }), s), COMPACT); +}); + +test("a vehicle that is not in any pack is ignored", () => { + assert.equal(parkedVehicle(hassWith({}), spot({ vehicle: "pack:missing:x" })), null); +}); + +test("parkedVehicles collects the spots of all floors by id", () => { + const building = emptyBuilding(); + const a = newFloor("a", "A", 0); + const b = newFloor("b", "B", 3); + a.furniture = [spot({ id: "one" })]; + b.furniture = [spot({ id: "two", vehicle: TRUCK }), spot({ id: "three", type: "sofa" })]; + building.floors = [a, b]; + assert.deepEqual([...parkedVehicles(hassWith({}), building)], [["one", COMPACT], ["two", TRUCK]]); +}); + +test("parkingEntities lists the presence and type entities of parking spots only", () => { + const floor = newFloor("a", "A", 0); + floor.furniture = [spot({ entity: "binary_sensor.car", type_entity: "sensor.kind" }), spot({ id: "x", entity: "none" }), spot({ id: "y", type: "sofa", entity: "light.lamp" })]; + assert.deepEqual(parkingEntities([floor]), ["binary_sensor.car", "sensor.kind"]); +}); + +test("the vehicle takes the spot's position and turn, and its size times the scale", () => { + const car = vehicleFurniture(spot({ scale: 2 }), COMPACT); + assert.ok(car); + assert.deepEqual([car.id, car.x, car.z, car.rotation], ["spot:vehicle", 1, 2, 45]); + assert.deepEqual([car.w, car.d, car.h], [3.4, 7.2, 3]); + assert.equal(vehicleFurniture(spot(), "pack:missing:x"), null); +}); + +test("withVehicles adds the cars after their spot and leaves a floor without cars untouched", () => { + const floor = newFloor("a", "A", 0); + floor.furniture = [spot({ id: "s1" }), spot({ id: "s2", type: "sofa" })]; + assert.equal(withVehicles(floor, new Map()), floor); + const out = withVehicles(floor, new Map([["s1", TRUCK]])); + assert.deepEqual(out.furniture.map((f) => f.id), ["s1", "s1:vehicle", "s2"]); + assert.equal(floor.furniture.length, 2, "the original floor is not changed"); +}); diff --git a/frontend/src/parking.ts b/frontend/src/parking.ts new file mode 100644 index 0000000..6be025a --- /dev/null +++ b/frontend/src/parking.ts @@ -0,0 +1,89 @@ +// Parking spots. A furniture piece of type "parking" marks where a vehicle can stand. A presence entity +// makes the vehicle appear only while a car is reported, and a type sensor (for example the result of an +// AI camera) can choose which vehicle model shows up. + +import type { Building, Floor, Furniture } from "./model.ts"; +import { packItem } from "./packs.ts"; +import type { HomeAssistant } from "./types.ts"; + +/** Presence-entity states that mean "a car is there". */ +export const PRESENT_STATES = new Set(["on", "home", "true", "present", "occupied", "detected", "parked", "yes", "1"]); + +/** An entity reference of a spot, or null when it is unset or "none". */ +const entityRef = (id: string | null | undefined): string | null => (id && id !== "none" ? id : null); + +const clean = (text: string) => text.trim().toLowerCase(); + +/** The vehicle named by a type sensor: the mapping whose word equals the state, else one contained in it. */ +function vehicleFromSensor(spot: Furniture, sensorState: string): string | null { + const wanted = clean(sensorState); + if (!wanted || !spot.types) return null; + const mappings = spot.types.map((m) => ({ word: clean(m.state), vehicle: m.vehicle })); + const exact = mappings.find((m) => m.word === wanted); + const partial = mappings.find((m) => m.word !== "" && wanted.includes(m.word)); + return (exact ?? partial)?.vehicle ?? null; +} + +/** + * The vehicle (a pack item type) standing in a spot right now. Null while the presence entity reports + * no car; otherwise the one the type sensor names, falling back to the spot's own vehicle. A spot + * without a presence entity always shows its vehicle. + */ +export function parkedVehicle(hass: HomeAssistant, spot: Furniture): string | null { + if (spot.type !== "parking") return null; + const presence = entityRef(spot.entity); + if (presence !== null) { + const state = hass.states[presence]?.state; + if (state === undefined || !PRESENT_STATES.has(state.toLowerCase())) return null; + } + let vehicle = spot.vehicle ?? null; + const sensor = entityRef(spot.type_entity); + if (sensor !== null && spot.types && spot.types.length > 0) { + vehicle = vehicleFromSensor(spot, hass.states[sensor]?.state ?? "") ?? vehicle; + } + return vehicle !== null && packItem(vehicle) ? vehicle : null; +} + +/** Vehicles currently parked, keyed by the id of their spot. */ +export function parkedVehicles(hass: HomeAssistant, building: Building): Map { + const parked = new Map(); + for (const spot of building.floors.flatMap((floor) => floor.furniture)) { + const vehicle = parkedVehicle(hass, spot); + if (vehicle) parked.set(spot.id, vehicle); + } + return parked; +} + +/** Entities whose change can bring a vehicle into a spot or remove it. */ +export function parkingEntities(floors: readonly Floor[]): string[] { + const refs: (string | null)[] = []; + for (const spot of floors.flatMap((floor) => floor.furniture)) { + if (spot.type === "parking") refs.push(entityRef(spot.entity), entityRef(spot.type_entity)); + } + return refs.filter((id): id is string => id !== null); +} + +/** The vehicle as a furniture piece in its spot: the model's size times the spot's scale, same turn. */ +export function vehicleFurniture(spot: Furniture, vehicle: string): Furniture | null { + const item = packItem(vehicle); + if (!item) return null; + const scale = spot.scale ?? 1; + const [w, d, h] = item.size.map((n) => n * scale); + return { id: `${spot.id}:vehicle`, type: vehicle, x: spot.x, z: spot.z, rotation: spot.rotation, w, d, h, variant: spot.variant ?? null, entity: null, power: null }; +} + +/** The floor with its parked vehicles added as furniture, ready for the 3D builder. */ +export function withVehicles(floor: Floor, parked: Map): Floor { + const furniture: Furniture[] = []; + let added = false; + for (const piece of floor.furniture) { + furniture.push(piece); + const vehicle = piece.type === "parking" ? parked.get(piece.id) : undefined; + const car = vehicle ? vehicleFurniture(piece, vehicle) : null; + if (car) { + furniture.push(car); + added = true; + } + } + return added ? { ...floor, furniture } : floor; +} diff --git a/frontend/src/plugins/api.ts b/frontend/src/plugins/api.ts new file mode 100644 index 0000000..18ba595 --- /dev/null +++ b/frontend/src/plugins/api.ts @@ -0,0 +1,162 @@ +// The public plugin API (version 1). Plugins are plain ES modules that call +// `window.NextFloor.register({...})`; nothing here may import Lit or three.js, so the +// contract stays small and stable. Documented in docs/plugins.md. + +import type { DeviceKind } from "../entities/kinds.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; + +export const PLUGIN_API_VERSION = 1; + +/** A light's glow as NextFloor draws it: colour channels 0–1 and the brightness level 0–1. */ +export interface Glow { + color: [number, number, number]; + level: number; +} + +/** Turns the current glow into the animated one at `seconds` since the page loaded. */ +export type LightAnimationFn = (glow: Glow, seconds: number) => Glow; + +export interface MarkerContext { + hass: HomeAssistant; + entityId: string; + state: HassEntity; +} + +/** What a plugin may change on a device's marker; leave a field out to keep NextFloor's own value. */ +export interface MarkerPatch { + /** "mdi:icon-name" or inline SVG markup. */ + icon?: string; + /** The short state text under the pin, e.g. "3 Pakete". */ + text?: string; + /** Highlights the marker the way an "on" device is highlighted. */ + active?: boolean; +} + +/** A value of a plugin setting on a placed device. */ +export type SettingValue = string | number | boolean; + +/** A text in one language, or by language code ("en", "de", …; English is the fallback). */ +export type PluginText = string | Record; + +/** A field the plugin adds to a placed device's form in the editor; the value is stored with the placement. */ +export interface DeviceSetting { + /** 1–32 letters, digits or "_". */ + key: string; + label: PluginText; + type: "number" | "select" | "boolean"; + default: SettingValue; + /** Numbers: limits and step. */ + min?: number; + max?: number; + step?: number; + /** Selects: the choices as [value, label]. */ + options?: [string, PluginText][]; + hint?: PluginText; +} + +/** Where a device stands in the plan. */ +export interface PlacementInfo { + floorId: string; + roomId: string | null; + x: number; + z: number; + /** Height above the floor (m). */ + y: number; + /** Turn around the vertical axis (degrees), as set in the editor. */ + rotation: number; +} + +export interface DeviceContext extends MarkerContext { + placement: PlacementInfo; + /** This plugin's settings of the device, defaults filled in. */ + settings: Record; +} + +/** A field of view (or a range) drawn flat on the floor from the device; it stops at walls. */ +export interface FloorWedge { + /** Opening angle in degrees (360: all around). */ + angle: number; + /** How far it reaches (m), and where it starts (m, default 0). */ + reach: number; + near?: number; + /** "#rrggbb"; default a faint teal. */ + color?: string; + /** 0–1, default 0.6. */ + opacity?: number; + /** A tap on the wedge goes through to the room instead of tapping the device. */ + tapThrough?: boolean; +} + +export interface TapContext extends DeviceContext { + /** + * Shows a node in a small window in the lower right corner of the 3D view (null closes it). A node with a `hass` + * property gets every new hass object. + */ + showWindow(node: Node | null, options?: { title?: string }): void; + /** Opens Home Assistant's more-info dialog (default: this device). */ + moreInfo(entityId?: string): void; +} + +export interface DeviceExtension { + /** Which entities this extension handles. Runs for every placed entity, so keep it cheap. */ + match: (entityId: string, state: HassEntity | undefined) => boolean; + /** + * Lets NextFloor show entities of domains it does not know (e.g. `vacuum`, `lawn_mower`, `todo`). + * The kind decides the default icon and how the device behaves; default "sensor". + */ + kind?: DeviceKind; + marker?: (ctx: MarkerContext) => MarkerPatch | null | undefined; + /** Further entities whose changes redraw this device (a camera's motion sensor that colours its wedge). */ + watch?: (ctx: MarkerContext) => string[] | null | undefined; + /** Extra fields in the device's form in the editor. */ + settings?: DeviceSetting[]; + /** A shape on the floor from the device, worked out again on every state change. */ + floorWedge?: (ctx: DeviceContext) => FloorWedge | null | undefined; + /** A tap on the device (its marker or its wedge). Return true when the plugin handled it, so NextFloor does nothing else. */ + tap?: (ctx: TapContext) => boolean | void; +} + +export interface RoomSectionContext { + hass: HomeAssistant; + room: { id: string; name: string; area_id: string | null }; + /** The entities NextFloor lists for this room. */ + entities: string[]; +} + +/** An extra block at the end of a room's panel (a small custom card). */ +export interface RoomSection { + id: string; + /** Return a DOM node, a plain-text string, or null to show nothing for this room. */ + render: (ctx: RoomSectionContext) => Node | string | null | undefined; +} + +export interface NextFloorPlugin { + /** Unique, e.g. "garage-door-plus". Registering the same id again replaces the plugin. */ + id: string; + name?: string; + version?: string; + /** The API version the plugin was written for; must be 1. */ + apiVersion: number; + lightAnimations?: Record; + devices?: DeviceExtension[]; + roomSections?: RoomSection[]; +} + +/** A plugin source stored in the plan's settings. */ +export interface PluginRef { + url: string; + enabled: boolean; + /** Set for plugins installed from the store: the plugin's store id, its version and the file's SHA-256. */ + id?: string; + version?: string; + sha256?: string; +} + +/** Where plugin modules may be loaded from: Home Assistant's own www folder, HACS, or HTTPS. */ +/** + * The URL Home Assistant serves a file at: the folder config/www is served as /local/, so a path typed with the folder + * in it (/local/www/…) never loads; it becomes /local/… (#78). + */ +export const pluginFetchUrl = (url: string): string => url.trim().replace(/^\/local\/www\//i, "/local/"); + +export const isAllowedPluginUrl = (url: string): boolean => /^(https:\/\/|\/local\/|\/hacsfiles\/)\S+\.m?js(\?\S*)?$/i.test(url.trim()); diff --git a/frontend/src/plugins/loader.ts b/frontend/src/plugins/loader.ts new file mode 100644 index 0000000..81f4e64 --- /dev/null +++ b/frontend/src/plugins/loader.ts @@ -0,0 +1,107 @@ +// Loads plugin modules and exposes `window.NextFloor` for them. Two ways in: +// 1. URLs in the plan's settings (Extensions page) are imported by the panel and the card. +// 2. A dashboard resource (e.g. installed by HACS) that loads before NextFloor pushes its plugin +// onto `window.__nextfloorPlugins`; it is picked up when NextFloor starts. + +import { sha256Hex } from "./sha256.ts"; +import { PLUGIN_API_VERSION, isAllowedPluginUrl, pluginFetchUrl, type NextFloorPlugin, type PluginRef } from "./api.ts"; +import { registerPlugin } from "./registry.ts"; + +export interface LoadState { + url: string; + state: "loading" | "loaded" | "error"; + error?: string; +} + +const loads = new Map(); +/** The module URL currently being evaluated, so register() calls can be attributed to it. */ +let currentSource = ""; + +declare global { + interface Window { + NextFloor?: { apiVersion: number; register: (plugin: NextFloorPlugin) => void }; + __nextfloorPlugins?: NextFloorPlugin[]; + } +} + +/** Installs `window.NextFloor` once and registers plugins queued by earlier scripts. */ +export function installPluginGlobal(): void { + // globalThis is window in the browser + const w = globalThis as unknown as Window; + if (w.NextFloor) return; + w.NextFloor = { + apiVersion: PLUGIN_API_VERSION, + register: (plugin) => registerPlugin(plugin, currentSource), + }; + const queued = w.__nextfloorPlugins ?? []; + w.__nextfloorPlugins = []; + for (const plugin of queued) { + try { + registerPlugin(plugin); + } catch (err) { + console.warn("NextFloor: plugin rejected", err); + } + } +} + +const toHex = (buf: ArrayBuffer): string => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join(""); + +/** + * What to import for a plugin. Plugins from the store carry the SHA-256 of their file: the file is + * fetched, checked and imported from memory, so it cannot differ from the one that was reviewed. + * Browsers without `crypto.subtle` (Home Assistant over plain http) check the file with a hash written in + * JavaScript: importing a store address directly fails anyway, as GitHub serves it as plain text (#78). + */ +export async function resolveModuleUrl(ref: PluginRef, fetcher: typeof fetch = (...args) => fetch(...args)): Promise<{ url: string; revoke?: () => void }> { + if (!ref.sha256) return { url: ref.url }; + const subtle = globalThis.crypto?.subtle; + const res = await fetcher(ref.url, { cache: "no-store" }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const bytes = await res.arrayBuffer(); + const sum = subtle ? toHex(await subtle.digest("SHA-256", bytes)) : sha256Hex(bytes); + if (sum !== ref.sha256.toLowerCase()) throw new Error("checksum mismatch: the file is not the one that was reviewed"); + const blobUrl = URL.createObjectURL(new Blob([bytes], { type: "text/javascript" })); + return { url: blobUrl, revoke: () => URL.revokeObjectURL(blobUrl) }; +} + +export const pluginLoadStates = (): LoadState[] => [...loads.values()]; + +/** + * Imports every enabled plugin URL that was not imported yet. Modules are cached by the browser, + * so turning a plugin off takes effect after a reload (the Extensions page says so). + */ +export async function loadPlugins( + refs: PluginRef[] | undefined, + importer: (url: string) => Promise = (url) => import(/* @vite-ignore */ url), + fetcher?: typeof fetch, +): Promise { + installPluginGlobal(); + for (const ref of refs ?? []) { + if (!ref.enabled || loads.has(ref.url)) continue; + if (!isAllowedPluginUrl(ref.url)) { + loads.set(ref.url, { url: ref.url, state: "error", error: "not allowed: use /local/…, /hacsfiles/… or https://…" }); + continue; + } + const entry: LoadState = { url: ref.url, state: "loading" }; + loads.set(ref.url, entry); + let resolved: { url: string; revoke?: () => void } | undefined; + try { + resolved = await resolveModuleUrl({ ...ref, url: pluginFetchUrl(ref.url) }, fetcher); + currentSource = ref.url; + await importer(resolved.url); + entry.state = "loaded"; + } catch (err) { + entry.state = "error"; + entry.error = err instanceof Error ? err.message : String(err); + console.warn(`NextFloor: plugin ${ref.url} failed to load`, err); + } finally { + currentSource = ""; + resolved?.revoke?.(); + } + } +} + +/** Test helper. */ +export function resetLoads(): void { + loads.clear(); +} diff --git a/frontend/src/plugins/plugins.test.ts b/frontend/src/plugins/plugins.test.ts new file mode 100644 index 0000000..87b0205 --- /dev/null +++ b/frontend/src/plugins/plugins.test.ts @@ -0,0 +1,273 @@ +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { animateGlow, lightAnimation } from "../light-effects.ts"; +import { buildMarkers } from "../markers.ts"; +import { emptyBuilding, newFloor } from "../model.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; +import { isAllowedPluginUrl, pluginFetchUrl, type NextFloorPlugin } from "./api.ts"; +import { installPluginGlobal, loadPlugins, pluginLoadStates, resetLoads } from "./loader.ts"; +import { + onPluginsChanged, + pluginDeviceSettings, + pluginDrawsWedge, + pluginFloorWedge, + pluginKind, + pluginLightAnimationNames, + pluginMarkerPatch, + pluginMdiIcon, + pluginRoomSections, + pluginStatuses, + pluginTap, + pluginText, + pluginWatched, + registerPlugin, + resetPlugins, + settingsWithDefaults, +} from "./registry.ts"; + +afterEach(() => { + resetPlugins(); + resetLoads(); +}); + +const entity = (entity_id: string, state: string, attributes: Record = {}): HassEntity => + ({ entity_id, state, attributes, last_changed: "", last_updated: "", context: { id: "" } }) as unknown as HassEntity; + +const hassWith = (...states: HassEntity[]): HomeAssistant => + ({ states: Object.fromEntries(states.map((s) => [s.entity_id, s])), language: "en", locale: { language: "en" }, areas: {}, entities: {}, devices: {} }) as unknown as HomeAssistant; + +const plugin = (extra: Partial = {}): NextFloorPlugin => ({ id: "demo", apiVersion: 1, ...extra }); + +test("plugin urls: only www, HACS and https JavaScript modules", () => { + for (const ok of ["/local/nf/a.js", "/hacsfiles/x/b.mjs", "https://example.org/p.js?v=3"]) assert.ok(isAllowedPluginUrl(ok), ok); + for (const bad of ["http://example.org/p.js", "/config/secrets.js", "javascript:alert(1)", "/local/readme.txt", ""]) assert.equal(isAllowedPluginUrl(bad), false, bad); +}); + +test("register validates id, API version and the shape of every extension", () => { + assert.throws(() => registerPlugin({ id: "bad id!", apiVersion: 1 }), /id/); + assert.throws(() => registerPlugin(plugin({ apiVersion: 2 })), /API 2/); + assert.throws(() => registerPlugin(plugin({ lightAnimations: { rainbow: (g) => g } })), /built in/); + assert.throws(() => registerPlugin(plugin({ devices: [{} as never] })), /match/); + assert.throws(() => registerPlugin(plugin({ roomSections: [{ id: "x" } as never] })), /render/); + registerPlugin(plugin({ name: "Demo", version: "1.2.0" })); + assert.deepEqual(pluginStatuses().map((s) => [s.id, s.name, s.version]), [["demo", "Demo", "1.2.0"]]); +}); + +test("registering the same id again replaces the plugin and notifies listeners", () => { + let calls = 0; + const stop = onPluginsChanged(() => calls++); + registerPlugin(plugin({ version: "1" })); + registerPlugin(plugin({ version: "2" })); + stop(); + registerPlugin(plugin({ version: "3" })); + assert.equal(calls, 2); + assert.equal(pluginStatuses().length, 1); + assert.equal(pluginStatuses()[0].version, "3"); +}); + +test("a plugin light animation can be mapped to an effect and animates the glow", () => { + registerPlugin(plugin({ lightAnimations: { strobe: (glow, seconds) => ({ ...glow, level: seconds % 1 < 0.5 ? glow.level : 0 }) } })); + assert.deepEqual(pluginLightAnimationNames(), ["strobe"]); + const lamp = entity("light.desk", "on", { effect: "Party" }); + assert.equal(lightAnimation({ effect_animations: { Party: "strobe" } }, lamp), "strobe"); + const glow = { color: [1, 1, 1] as [number, number, number], level: 0.8 }; + assert.equal(animateGlow(glow, "strobe", 0.2)?.level, 0.8); + assert.equal(animateGlow(glow, "strobe", 0.7)?.level, 0); +}); + +test("an unknown or removed animation stays inert", () => { + const lamp = entity("light.desk", "on", { effect: "Party" }); + assert.equal(lightAnimation({ effect_animations: { Party: "strobe" } }, lamp), undefined); + const glow = { color: [1, 0, 0] as [number, number, number], level: 0.5 }; + assert.deepEqual(animateGlow(glow, "strobe", 1), glow); +}); + +test("a throwing or malformed animation keeps the glow and records the error", () => { + registerPlugin(plugin({ lightAnimations: { boom: () => { throw new Error("kaputt"); }, nan: (g) => ({ ...g, level: Number.NaN }) } })); + const glow = { color: [0.2, 0.4, 0.6] as [number, number, number], level: 0.5 }; + assert.deepEqual(animateGlow(glow, "boom", 1), glow); + assert.deepEqual(animateGlow(glow, "nan", 1), glow); + assert.deepEqual(pluginStatuses()[0].errors, ["kaputt"]); +}); + +test("animation output is clamped to the 0–1 range", () => { + registerPlugin(plugin({ lightAnimations: { loud: () => ({ color: [2, -1, 0.5], level: 9 }) } })); + assert.deepEqual(animateGlow({ color: [1, 1, 1], level: 0.3 }, "loud", 0), { color: [1, 0, 0.5], level: 1 }); +}); + +test("a plugin can claim entities of unknown domains and they get a marker", () => { + registerPlugin(plugin({ + devices: [{ match: (id) => id.startsWith("vacuum."), kind: "switch", marker: ({ state }) => ({ icon: "mdi:robot-vacuum", text: state.state === "cleaning" ? "putzt" : "parkt", active: state.state === "cleaning" }) }], + })); + const robot = entity("vacuum.rob", "cleaning"); + assert.equal(pluginKind("vacuum.rob", robot), "switch"); + assert.equal(pluginKind("lawn_mower.x", undefined), null); + const building = emptyBuilding(); + const floor = newFloor("eg", "EG", 0); + floor.placements.push({ entity_id: "vacuum.rob", x: 1, z: 1 } as never); + building.floors.push(floor); + const [m] = buildMarkers(hassWith(robot), building); + assert.equal(m.id, "vacuum.rob"); + assert.equal(m.text, "putzt"); + assert.equal(m.active, true); + assert.match(m.icon, /mdi:robot-vacuum/); +}); + +test("without a plugin unknown domains still get no marker", () => { + const building = emptyBuilding(); + const floor = newFloor("eg", "EG", 0); + floor.placements.push({ entity_id: "vacuum.rob", x: 1, z: 1 } as never); + building.floors.push(floor); + assert.deepEqual(buildMarkers(hassWith(entity("vacuum.rob", "docked")), building), []); +}); + +test("marker patches: an icon picked in the plan wins, text is capped, a throwing plugin is skipped", () => { + registerPlugin(plugin({ id: "a", devices: [{ match: (id) => id === "sensor.post", marker: () => ({ icon: "mdi:mailbox", text: "x".repeat(200) }) }] })); + registerPlugin(plugin({ id: "b", devices: [{ match: () => { throw new Error("match broke"); } }] })); + const post = entity("sensor.post", "2"); + const patch = pluginMarkerPatch({ hass: hassWith(post), entityId: "sensor.post", state: post }); + assert.equal(patch?.text?.length, 60); + const building = emptyBuilding(); + const floor = newFloor("eg", "EG", 0); + floor.placements.push({ entity_id: "sensor.post", x: 0, z: 0, icon: "mdi:post-lamp" } as never); + building.floors.push(floor); + const [m] = buildMarkers(hassWith(post), building); + assert.match(m.icon, /mdi:post-lamp/); + assert.equal(pluginStatuses().find((s) => s.id === "b")?.errors[0], "match broke"); +}); + +test("the editor gets a plugin's Material Design icon, not inline SVG or a throwing plugin's", () => { + registerPlugin(plugin({ id: "a", devices: [{ match: (id) => id === "camera.yard", marker: () => ({ icon: "mdi:cctv" }) }] })); + registerPlugin(plugin({ id: "b", devices: [{ match: (id) => id === "vacuum.robot", marker: () => ({ icon: "" }) }] })); + registerPlugin(plugin({ id: "c", devices: [{ match: (id) => id === "lawn_mower.m", marker: () => { throw new Error("broke"); } }] })); + const hass = hassWith(entity("camera.yard", "idle"), entity("vacuum.robot", "docked"), entity("lawn_mower.m", "docked")); + assert.equal(pluginMdiIcon(hass, "camera.yard"), "mdi:cctv"); + assert.equal(pluginMdiIcon(hass, "vacuum.robot"), null); + assert.equal(pluginMdiIcon(hass, "lawn_mower.m"), null); + assert.equal(pluginMdiIcon(hass, "camera.gone"), null); +}); + +test("room sections render per room and skip empty or failing ones", () => { + registerPlugin(plugin({ + name: "Post", + roomSections: [ + { id: "count", render: ({ room, entities }) => (room.name === "Flur" ? `${entities.length} Geräte` : null) }, + { id: "broken", render: () => { throw new Error("nope"); } }, + ], + })); + const ctx = (name: string) => ({ hass: hassWith(), room: { id: "r", name, area_id: null }, entities: ["light.a", "light.b"] }); + assert.deepEqual(pluginRoomSections(ctx("Flur")).map((s) => [s.key, s.title, s.content]), [["demo/count", "Post", "2 Geräte"]]); + assert.deepEqual(pluginRoomSections(ctx("Bad")), []); +}); + +test("loader imports enabled allowed urls once, attributes registrations and records failures", async () => { + installPluginGlobal(); + const imported: string[] = []; + const importer = async (url: string) => { + imported.push(url); + if (url.endsWith("broken.js")) throw new Error("404"); + (globalThis as unknown as Window).NextFloor!.register(plugin({ id: url.includes("one") ? "one" : "two" })); + }; + const refs = [ + { url: "/local/one.js", enabled: true }, + { url: "/local/two.js", enabled: false }, + { url: "/local/broken.js", enabled: true }, + { url: "http://evil.example/x.js", enabled: true }, + ]; + await loadPlugins(refs, importer); + await loadPlugins(refs, importer); + assert.deepEqual(imported, ["/local/one.js", "/local/broken.js"]); + assert.deepEqual(pluginStatuses().map((s) => [s.id, s.source]), [["one", "/local/one.js"]]); + const states = Object.fromEntries(pluginLoadStates().map((l) => [l.url, l.state])); + assert.deepEqual(states, { "/local/one.js": "loaded", "/local/broken.js": "error", "http://evil.example/x.js": "error" }); +}); + +// ---- cameras and the like: settings, a wedge on the floor, taps and watched entities ---- + +const AT = { floorId: "f1", roomId: null, x: 1, z: 2, y: 2.2, rotation: 90 }; +const cameraPlugin = (extra: Partial[number]> = {}) => + plugin({ + id: "cams", + name: "Cameras", + devices: [ + { + match: (id) => id.startsWith("camera."), + settings: [ + { key: "fov", label: { en: "Field of view", de: "Blickwinkel" }, type: "number", default: 90, min: 10, max: 360 }, + { key: "mount", label: "Mount", type: "select", default: "wall", options: [["wall", "Wall"], ["dome", "Dome"]] }, + { key: "wedge", label: "Wedge", type: "boolean", default: true }, + ], + ...extra, + }, + ], + }); + +test("a setting needs a proper key and type", () => { + assert.throws(() => registerPlugin(plugin({ devices: [{ match: () => true, settings: [{ key: "bad key", label: "x", type: "number", default: 1 }] }] })), /key/); + assert.throws(() => registerPlugin(plugin({ devices: [{ match: () => true, settings: [{ key: "a", label: "x", type: "colour" as never, default: 1 }] }] })), /type/); + assert.throws(() => registerPlugin(plugin({ devices: [{ match: () => true, tap: "no" as never }] })), /tap/); +}); + +test("plugin settings: listed per plugin, stored values that fit win over the defaults", () => { + registerPlugin(cameraPlugin()); + const found = pluginDeviceSettings("camera.hall", entity("camera.hall", "idle")); + assert.deepEqual(found.map((f) => [f.pluginId, f.name, f.settings.length]), [["cams", "Cameras", 3]]); + assert.deepEqual(pluginDeviceSettings("light.x", entity("light.x", "on")), []); + const values = settingsWithDefaults(found[0].settings, { fov: 120, mount: "ceiling", wedge: "yes" as never }); + assert.deepEqual(values, { fov: 120, mount: "wall", wedge: true }); + assert.equal(pluginText({ en: "Field of view", de: "Blickwinkel" }, "de-AT"), "Blickwinkel"); + assert.equal(pluginText({ en: "Field of view", de: "Blickwinkel" }, "fr"), "Field of view"); +}); + +test("a floor wedge gets the device's place and settings and is kept within limits", () => { + registerPlugin(cameraPlugin({ floorWedge: ({ placement, settings }) => ({ angle: settings.fov as number, reach: placement.y * 100, near: -1, color: "#ff0000", opacity: 3 }) })); + const ctx = { hass: hassWith(entity("camera.hall", "idle")), entityId: "camera.hall", state: entity("camera.hall", "idle") }; + const wedge = pluginFloorWedge(ctx, AT, { cams: { fov: 60 } }); + assert.deepEqual(wedge, { angle: 60, reach: 30, near: 0, color: [1, 0, 0], opacity: 1, through: false }); + assert.equal(pluginDrawsWedge("camera.hall", ctx.state), true); + assert.equal(pluginDrawsWedge("light.x", undefined), false); +}); + +test("a throwing wedge or a wedge without reach draws nothing", () => { + registerPlugin(cameraPlugin({ floorWedge: () => ({ angle: 90, reach: 0 }) })); + const ctx = { hass: hassWith(), entityId: "camera.a", state: entity("camera.a", "idle") }; + assert.equal(pluginFloorWedge(ctx, AT, undefined), null); + registerPlugin(cameraPlugin({ floorWedge: () => { throw new Error("boom"); } })); + assert.equal(pluginFloorWedge(ctx, AT, undefined), null); + assert.deepEqual(pluginStatuses()[0].errors, ["boom"]); +}); + +test("a tap goes to the plugin, which can open a window; false lets NextFloor handle it", () => { + const shown: (Node | null)[] = []; + registerPlugin(cameraPlugin({ tap: ({ settings, showWindow }) => settings.mount === "dome" && (showWindow(null, { title: "x" }), true) })); + const ctx = { hass: hassWith(), entityId: "camera.hall", state: entity("camera.hall", "idle") }; + const tools = { showWindow: (node: Node | null) => void shown.push(node), moreInfo: () => undefined }; + assert.equal(pluginTap(ctx, AT, { cams: { mount: "dome" } }, tools), true); + assert.deepEqual(shown, [null]); + assert.equal(pluginTap(ctx, AT, undefined, tools), false); +}); + +test("plugins name further entities to watch for a device", () => { + registerPlugin(cameraPlugin({ watch: ({ entityId }) => [entityId.replace("camera.", "binary_sensor.") + "_motion", 7 as never] })); + assert.deepEqual(pluginWatched({ hass: hassWith(), entityId: "camera.hall", state: entity("camera.hall", "idle") }), ["binary_sensor.hall_motion"]); +}); + +test("a placed camera's marker carries the plugin's wedge", () => { + registerPlugin(cameraPlugin({ kind: "sensor", floorWedge: ({ placement }) => ({ angle: 90, reach: 4, color: "#000000", opacity: 0.5 + placement.rotation / 1000 }) })); + const b = emptyBuilding(); + const f = newFloor("eg", "EG", 0); + f.placements.push({ entity_id: "camera.hall", x: 1, z: 1, y: 2.4, rotation: 100 }); + b.floors.push(f); + const [m] = buildMarkers(hassWith(entity("camera.hall", "idle")), b); + assert.deepEqual(m.wedge, { angle: 90, reach: 4, near: 0, color: [0, 0, 0], opacity: 0.6, through: false }); +}); + +test("a plugin path typed with the www folder in it loads from where Home Assistant serves it (#78)", async () => { + assert.equal(pluginFetchUrl(" /local/www/nextfloor/nextfloor-cameras.js "), "/local/nextfloor/nextfloor-cameras.js"); + assert.equal(pluginFetchUrl("/local/nextfloor/x.js"), "/local/nextfloor/x.js"); + assert.equal(pluginFetchUrl("https://example.com/local/www/x.js"), "https://example.com/local/www/x.js"); + resetLoads(); + const asked: string[] = []; + await loadPlugins([{ url: "/local/www/nextfloor/nextfloor-cameras.js", enabled: true }], async (url) => void asked.push(url)); + assert.deepEqual(asked, ["/local/nextfloor/nextfloor-cameras.js"]); +}); diff --git a/frontend/src/plugins/registry.ts b/frontend/src/plugins/registry.ts new file mode 100644 index 0000000..af9c187 --- /dev/null +++ b/frontend/src/plugins/registry.ts @@ -0,0 +1,302 @@ +// Registered plugins and the lookups the rest of NextFloor uses. A broken plugin must never break +// the house view: every call into plugin code is guarded and failures are recorded per plugin. + +import type { DeviceKind } from "../entities/kinds.ts"; +import type { HassEntity, HomeAssistant } from "../types.ts"; +import { + PLUGIN_API_VERSION, + type DeviceSetting, + type Glow, + type LightAnimationFn, + type MarkerContext, + type MarkerPatch, + type NextFloorPlugin, + type PlacementInfo, + type PluginText, + type RoomSectionContext, + type SettingValue, + type TapContext, +} from "./api.ts"; + +export interface PluginStatus { + id: string; + name: string; + version: string; + /** The module URL it came from (empty when registered by a dashboard resource). */ + source: string; + errors: string[]; +} + +// The main bundle and the lazily loaded 3D bundle each carry their own copy of this module, so the +// state lives on globalThis: both copies must see the same plugins. +interface Store { + plugins: Map; + listeners: Set<() => void>; +} +const g = globalThis as typeof globalThis & { __nextfloorPluginStore?: Store }; +const store: Store = (g.__nextfloorPluginStore ??= { plugins: new Map(), listeners: new Set() }); +const plugins = store.plugins; +const listeners = store.listeners; + +const BUILT_IN_ANIMATIONS = new Set(["none", "rainbow", "pulse", "flicker"]); +const MAX_ERRORS = 5; + +function note(status: PluginStatus, err: unknown): void { + if (status.errors.length < MAX_ERRORS) status.errors.push(err instanceof Error ? err.message : String(err)); +} + +function changed(): void { + for (const listener of listeners) listener(); +} + +/** Called whenever a plugin is added, replaced or fails; returns the unsubscribe function. */ +export function onPluginsChanged(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** Validates and stores a plugin. Throws with a readable message when the plugin cannot be used. */ +export function registerPlugin(plugin: NextFloorPlugin, source = ""): void { + if (!plugin || typeof plugin !== "object") throw new Error("register() needs a plugin object"); + if (typeof plugin.id !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(plugin.id)) throw new Error("plugin id must be 1–64 letters, digits, '.', '_' or '-'"); + if (plugin.apiVersion !== PLUGIN_API_VERSION) throw new Error(`plugin "${plugin.id}" wants API ${String(plugin.apiVersion)}, NextFloor offers ${PLUGIN_API_VERSION}`); + for (const name of Object.keys(plugin.lightAnimations ?? {})) { + if (BUILT_IN_ANIMATIONS.has(name)) throw new Error(`plugin "${plugin.id}": light animation "${name}" is built in`); + if (typeof plugin.lightAnimations?.[name] !== "function") throw new Error(`plugin "${plugin.id}": light animation "${name}" is not a function`); + } + for (const device of plugin.devices ?? []) { + if (typeof device?.match !== "function") throw new Error(`plugin "${plugin.id}": every device extension needs match()`); + for (const key of ["floorWedge", "tap", "watch"] as const) if (device[key] !== undefined && typeof device[key] !== "function") throw new Error(`plugin "${plugin.id}": ${key} must be a function`); + for (const s of device.settings ?? []) { + if (!s || typeof s.key !== "string" || !/^\w{1,32}$/.test(s.key)) throw new Error(`plugin "${plugin.id}": a setting needs a key of 1–32 letters, digits or "_"`); + if (!["number", "select", "boolean"].includes(s.type)) throw new Error(`plugin "${plugin.id}": setting "${s.key}" has an unknown type`); + } + } + for (const section of plugin.roomSections ?? []) if (typeof section?.render !== "function" || typeof section.id !== "string") throw new Error(`plugin "${plugin.id}": every room section needs id and render()`); + plugins.set(plugin.id, { + plugin, + status: { id: plugin.id, name: plugin.name || plugin.id, version: plugin.version || "", source, errors: [] }, + }); + changed(); +} + +export function unregisterPlugin(id: string): void { + if (plugins.delete(id)) changed(); +} + +export const pluginStatuses = (): PluginStatus[] => [...plugins.values()].map((p) => p.status); + +// ---- light animations --------------------------------------------------------------------------- + +/** Names of the light animations plugins add, for the editor's effect mapping. */ +export const pluginLightAnimationNames = (): string[] => [...plugins.values()].flatMap((p) => Object.keys(p.plugin.lightAnimations ?? {})); + +function findAnimation(name: string): { fn: LightAnimationFn; status: PluginStatus } | null { + for (const { plugin, status } of plugins.values()) { + const fn = plugin.lightAnimations?.[name]; + if (fn) return { fn, status }; + } + return null; +} + +export const hasPluginAnimation = (name: string): boolean => findAnimation(name) !== null; + +/** Runs a plugin animation; a throwing or malformed one leaves the glow as it was. */ +export function animateWithPlugin(glow: Glow, name: string, seconds: number): Glow { + const found = findAnimation(name); + if (!found) return glow; + try { + const out = found.fn({ color: [...glow.color] as Glow["color"], level: glow.level }, seconds); + const ok = out && Array.isArray(out.color) && out.color.length === 3 && out.color.every((c) => Number.isFinite(c)) && Number.isFinite(out.level); + if (!ok) return glow; + const clamp = (v: number) => Math.max(0, Math.min(1, v)); + return { color: [clamp(out.color[0]), clamp(out.color[1]), clamp(out.color[2])], level: clamp(out.level) }; + } catch (err) { + note(found.status, err); + return glow; + } +} + +// ---- devices ------------------------------------------------------------------------------------ + +function* matchingDevices(entityId: string, state: HassEntity | undefined) { + for (const { plugin, status } of plugins.values()) { + for (const device of plugin.devices ?? []) { + let hit = false; + try { + hit = device.match(entityId, state); + } catch (err) { + note(status, err); + } + if (hit) yield { device, status }; + } + } +} + +/** The kind a plugin gives an entity NextFloor does not know itself (null: no plugin claims it). */ +export function pluginKind(entityId: string, state: HassEntity | undefined): DeviceKind | null { + for (const { device } of matchingDevices(entityId, state)) return device.kind ?? "sensor"; + return null; +} + +/** The Material Design icon ("mdi:…") plugins give the entity's marker, for the editor, which shows no inline SVG; null: none. */ +export function pluginMdiIcon(hass: HomeAssistant, entityId: string): string | null { + const state = hass.states[entityId]; + if (!state) return null; + const icon = pluginMarkerPatch({ hass, entityId, state })?.icon?.trim(); + return icon && /^mdi:[a-z0-9-]+$/i.test(icon) ? icon : null; +} + +/** Collected marker changes of every matching plugin; later plugins win on the same field. */ +export function pluginMarkerPatch(ctx: MarkerContext): MarkerPatch | null { + let patch: MarkerPatch | null = null; + for (const { device, status } of matchingDevices(ctx.entityId, ctx.state)) { + if (!device.marker) continue; + try { + const p = device.marker(ctx); + if (!p) continue; + patch = { ...(patch ?? {}) }; + if (typeof p.icon === "string" && p.icon) patch.icon = p.icon; + if (typeof p.text === "string") patch.text = p.text.slice(0, 60); + if (typeof p.active === "boolean") patch.active = p.active; + } catch (err) { + note(status, err); + } + } + return patch; +} + +/** The further entities plugins want watched for a placed device. */ +export function pluginWatched(ctx: MarkerContext): string[] { + const out: string[] = []; + for (const { device, status } of matchingDevices(ctx.entityId, ctx.state)) { + if (!device.watch) continue; + try { + const ids = device.watch(ctx); + if (Array.isArray(ids)) out.push(...ids.filter((id): id is string => typeof id === "string").slice(0, 20)); + } catch (err) { + note(status, err); + } + } + return out; +} + +/** A plugin text in the given language: the language's own, else English, else the first one. */ +export function pluginText(text: PluginText | undefined, language: string): string { + if (!text) return ""; + if (typeof text === "string") return text; + return text[language] ?? text[language.split("-")[0]] ?? text.en ?? Object.values(text)[0] ?? ""; +} + +/** What plugins store on a placement: per plugin id, its settings by key. */ +export type PluginData = Record>; + +/** The settings plugins add to a device's form, with the plugin they belong to. */ +export function pluginDeviceSettings(entityId: string, state: HassEntity | undefined): { pluginId: string; name: string; settings: DeviceSetting[] }[] { + const out: { pluginId: string; name: string; settings: DeviceSetting[] }[] = []; + for (const { device, status } of matchingDevices(entityId, state)) if (device.settings?.length) out.push({ pluginId: status.id, name: status.name, settings: device.settings }); + return out; +} + +/** A plugin's settings of a device: the stored values that fit the setting, the defaults for the rest. */ +export function settingsWithDefaults(settings: readonly DeviceSetting[] | undefined, stored: Record | undefined): Record { + const out: Record = {}; + for (const s of settings ?? []) { + const v = stored?.[s.key]; + const fits = s.type === "number" ? typeof v === "number" && Number.isFinite(v) : s.type === "boolean" ? typeof v === "boolean" : typeof v === "string" && (s.options ?? []).some(([o]) => o === v); + out[s.key] = fits ? v! : s.default; + } + return out; +} + +/** A wedge as the 3D view draws it. */ +export interface DrawnWedge { + angle: number; + reach: number; + near: number; + color: [number, number, number]; + opacity: number; + through: boolean; +} + +const hexColor = (value: unknown): [number, number, number] | null => { + const m = typeof value === "string" ? /^#([0-9a-f]{6})$/i.exec(value.trim()) : null; + if (!m) return null; + const n = Number.parseInt(m[1], 16); + return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; +}; +const finite = (v: unknown, fallback: number, lo: number, hi: number): number => (typeof v === "number" && Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : fallback); + +/** Whether a plugin draws a wedge for this entity (the editor then offers a handle to turn it). */ +export function pluginDrawsWedge(entityId: string, state: HassEntity | undefined): boolean { + for (const { device } of matchingDevices(entityId, state)) if (device.floorWedge) return true; + return false; +} + +/** The floor wedge of a placed device, from the first plugin that draws one; null for none. */ +export function pluginFloorWedge(ctx: MarkerContext, placement: PlacementInfo, data: PluginData | undefined): DrawnWedge | null { + for (const { device, status } of matchingDevices(ctx.entityId, ctx.state)) { + if (!device.floorWedge) continue; + try { + const w = device.floorWedge({ ...ctx, placement, settings: settingsWithDefaults(device.settings, data?.[status.id]) }); + if (!w) continue; + const reach = finite(w.reach, 0, 0, 30); + if (reach <= 0) continue; + return { + angle: finite(w.angle, 90, 1, 360), + reach, + near: finite(w.near, 0, 0, reach), + color: hexColor(w.color) ?? [0.04, 0.22, 0.28], + opacity: finite(w.opacity, 0.6, 0, 1), + through: w.tapThrough === true, + }; + } catch (err) { + note(status, err); + } + } + return null; +} + +/** Hands a tap on a device to the plugins; true when one of them handled it. */ +export function pluginTap(ctx: MarkerContext, placement: PlacementInfo, data: PluginData | undefined, tools: Pick): boolean { + for (const { device, status } of matchingDevices(ctx.entityId, ctx.state)) { + if (!device.tap) continue; + try { + if (device.tap({ ...ctx, ...tools, placement, settings: settingsWithDefaults(device.settings, data?.[status.id]) }) === true) return true; + } catch (err) { + note(status, err); + } + } + return false; +} + +// ---- room sections ------------------------------------------------------------------------------ + +export interface RenderedSection { + key: string; + title: string; + content: Node | string; +} + +export function pluginRoomSections(ctx: RoomSectionContext): RenderedSection[] { + const out: RenderedSection[] = []; + for (const { plugin, status } of plugins.values()) { + for (const section of plugin.roomSections ?? []) { + try { + const content = section.render(ctx); + if (content === null || content === undefined || content === "") continue; + if (typeof content !== "string" && !(content instanceof Node)) continue; + out.push({ key: `${plugin.id}/${section.id}`, title: status.name, content }); + } catch (err) { + note(status, err); + } + } + } + return out; +} + +/** Test helper: forget every plugin. */ +export function resetPlugins(): void { + plugins.clear(); + changed(); +} diff --git a/frontend/src/plugins/sha256.ts b/frontend/src/plugins/sha256.ts new file mode 100644 index 0000000..bd1406b --- /dev/null +++ b/frontend/src/plugins/sha256.ts @@ -0,0 +1,42 @@ +// SHA-256 in plain JavaScript, for browsers without crypto.subtle (Home Assistant opened over plain http on the +// local network): store plugins are still checked against the hash that was reviewed (#78). + +const K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]); + +/** The SHA-256 of the bytes, as lowercase hex. */ +export function sha256Hex(data: ArrayBuffer | Uint8Array): string { + const bytes = data instanceof Uint8Array ? data : new Uint8Array(data); + const bitLength = bytes.length * 8; + const padded = new Uint8Array((((bytes.length + 9 + 63) >> 6) << 6)); + padded.set(bytes); + padded[bytes.length] = 0x80; + const view = new DataView(padded.buffer); + view.setUint32(padded.length - 8, Math.floor(bitLength / 0x100000000)); + view.setUint32(padded.length - 4, bitLength >>> 0); + const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]); + const w = new Uint32Array(64); + const rotr = (x: number, n: number) => (x >>> n) | (x << (32 - n)); + for (let off = 0; off < padded.length; off += 64) { + for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4); + for (let i = 16; i < 64; i++) { + const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3); + const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10); + w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0; + } + let [a, b, c, d, e, f, g, hh] = h; + for (let i = 0; i < 64; i++) { + const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) >>> 0; + const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0; + [hh, g, f, e, d, c, b, a] = [g, f, e, (d + t1) >>> 0, c, b, a, (t1 + t2) >>> 0]; + } + h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; + } + return [...h].map((x) => x.toString(16).padStart(8, "0")).join(""); +} diff --git a/frontend/src/plugins/store.test.ts b/frontend/src/plugins/store.test.ts new file mode 100644 index 0000000..da9ef7f --- /dev/null +++ b/frontend/src/plugins/store.test.ts @@ -0,0 +1,123 @@ +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { loadPlugins, resetLoads, resolveModuleUrl } from "./loader.ts"; +import { downloadStorePack, isStoreFileUrl, parseStoreIndex, parseStorePacks, storePackState, storeState, withStoreEntry, type StoreEntry } from "./store.ts"; + +afterEach(resetLoads); + +const SHA = "a".repeat(64); +const COMMIT = "0123456789abcdef0123456789abcdef01234567"; +const FILE = `https://raw.githubusercontent.com/someone/plugin/${COMMIT}/plugin.js`; +const raw = (extra: Record = {}) => ({ id: "demo", name: "Demo", version: "1.0.0", author: "someone", description: "d", homepage: "https://github.com/someone/plugin", url: FILE, sha256: SHA, ...extra }); +const entry = (extra: Partial = {}): StoreEntry => ({ ...(raw() as StoreEntry), ...extra }); + +test("store files must be pinned to a commit on raw.githubusercontent.com", () => { + assert.ok(isStoreFileUrl(FILE)); + for (const bad of [ + "https://raw.githubusercontent.com/someone/plugin/main/plugin.js", + `https://example.org/someone/plugin/${COMMIT}/plugin.js`, + `http://raw.githubusercontent.com/someone/plugin/${COMMIT}/plugin.js`, + `https://raw.githubusercontent.com/someone/plugin/${COMMIT}/plugin.txt`, + ]) + assert.equal(isStoreFileUrl(bad), false, bad); +}); + +test("the index keeps valid entries and drops broken or duplicate ones", () => { + const list = parseStoreIndex({ + plugins: [raw(), raw({ name: "Again" }), raw({ id: "no-hash", sha256: "xyz" }), raw({ id: "loose", url: "https://example.org/p.js" }), raw({ id: "x y" }), null, raw({ id: "b", homepage: "javascript:1" })], + }); + assert.deepEqual(list.map((e) => e.id), ["demo", "b"]); + assert.equal(list[1].homepage, ""); + assert.deepEqual(parseStoreIndex(undefined), []); + assert.deepEqual(parseStoreIndex({ plugins: "no" }), []); +}); + +test("an entry is available, installed or has an update", () => { + assert.equal(storeState(entry(), []), "available"); + assert.equal(storeState(entry(), [{ url: "/local/x.js", enabled: true }]), "available"); + assert.equal(storeState(entry(), [{ url: FILE, enabled: true, id: "demo", sha256: SHA }]), "installed"); + assert.equal(storeState(entry({ sha256: "b".repeat(64) }), [{ url: FILE, enabled: true, id: "demo", sha256: SHA }]), "update"); +}); + +test("installing adds the entry; updating replaces it and keeps the on/off switch", () => { + const first = withStoreEntry([{ url: "/local/mine.js", enabled: true }], entry()); + assert.equal(first.length, 2); + assert.deepEqual(first[1], { url: FILE, enabled: true, id: "demo", version: "1.0.0", sha256: SHA }); + const off = first.map((r, i) => (i === 1 ? { ...r, enabled: false } : r)); + const next = withStoreEntry(off, entry({ version: "2.0.0", sha256: "c".repeat(64) })); + assert.equal(next.length, 2); + assert.deepEqual([next[1].version, next[1].sha256, next[1].enabled], ["2.0.0", "c".repeat(64), false]); +}); + +const bytes = new TextEncoder().encode("export default 1;"); +const hex = async (b: Uint8Array) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", b as BufferSource))].map((x) => x.toString(16).padStart(2, "0")).join(""); +const serving = (body: Uint8Array, ok = true): typeof fetch => (async () => ({ ok, status: ok ? 200 : 404, arrayBuffer: async () => body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) })) as unknown as typeof fetch; + +test("a plugin without a checksum is imported from its address", async () => { + assert.deepEqual(await resolveModuleUrl({ url: "/local/a.js", enabled: true }), { url: "/local/a.js" }); +}); + +test("a plugin with a checksum is fetched, checked and imported from memory", async () => { + const r = await resolveModuleUrl({ url: FILE, enabled: true, sha256: await hex(bytes) }, serving(bytes)); + assert.match(r.url, /^blob:/); + r.revoke?.(); +}); + +test("a file that does not match its checksum is refused and never imported", async () => { + let imported = 0; + await loadPlugins([{ url: FILE, enabled: true, sha256: SHA }], async () => void imported++, serving(bytes)); + assert.equal(imported, 0); +}); + +test("community furniture: only packs from the store's own folder, with a checksum, no reserved ids", () => { + const ok = { id: "anna.kitchen", name: "Kitchen", author: "Anna", release: 2, items: 5, url: "https://raw.githubusercontent.com/therealMRBK/NextFloor-Plugins/main/packs/anna.kitchen.json", sha256: "a".repeat(64) }; + const packs = parseStorePacks({ + packs: [ + ok, + { ...ok, id: "elsewhere", url: "https://example.com/elsewhere.json" }, + { ...ok, id: "nextfloor.fake", url: "https://raw.githubusercontent.com/therealMRBK/NextFloor-Plugins/main/packs/nextfloor.fake.json" }, + { ...ok, id: "other.pack", url: "https://raw.githubusercontent.com/therealMRBK/NextFloor-Plugins/main/packs/anna.kitchen.json" }, + { ...ok, id: "no.sum", url: "https://raw.githubusercontent.com/therealMRBK/NextFloor-Plugins/main/packs/no.sum.json", sha256: "x" }, + ok, + ], + }); + assert.deepEqual(packs.map((p) => p.id), ["anna.kitchen"]); + assert.deepEqual(parseStorePacks({ plugins: [] }), []); + assert.equal(storePackState(packs[0], []), "available"); + assert.equal(storePackState(packs[0], [{ id: "anna.kitchen", release: 2 }]), "installed"); + assert.equal(storePackState(packs[0], [{ id: "anna.kitchen", release: 1 }]), "update"); + assert.equal(storePackState(packs[0], [{ id: "anna.kitchen" }]), "update"); +}); + +test("a store pack is refused when it is not the reviewed file", async () => { + const body = new TextEncoder().encode('{"format":"nfpack"}'); + const sum = [...new Uint8Array(await crypto.subtle.digest("SHA-256", body))].map((b) => b.toString(16).padStart(2, "0")).join(""); + const entry = { id: "a.b", name: "A", description: "", author: "", release: 1, items: 1, url: "https://raw.githubusercontent.com/therealMRBK/NextFloor-Plugins/main/packs/a.b.json", sha256: sum }; + const fetcher = (async () => new Response(body)) as unknown as typeof fetch; + assert.equal(await downloadStorePack(entry, fetcher), '{"format":"nfpack"}'); + await assert.rejects(downloadStorePack({ ...entry, sha256: "0".repeat(64) }, fetcher), /checksum/); +}); + +test("the JavaScript SHA-256 matches the browser's for empty, short and multi-block input", async () => { + const { sha256Hex } = await import("./sha256.ts"); + for (const text of ["", "abc", "export default 1;", "x".repeat(55), "x".repeat(56), "y".repeat(1000)]) { + const b = new TextEncoder().encode(text); + assert.equal(sha256Hex(b), await hex(b), `length ${b.length}`); + } +}); + +test("without crypto.subtle (Home Assistant over plain http) a store plugin is still checked and imported from memory (#78)", async () => { + const subtle = Object.getOwnPropertyDescriptor(globalThis.crypto, "subtle"); + const sum = await hex(bytes); + Object.defineProperty(globalThis.crypto, "subtle", { value: undefined, configurable: true }); + try { + assert.equal(globalThis.crypto.subtle, undefined); + const r = await resolveModuleUrl({ url: FILE, enabled: true, sha256: sum }, serving(bytes)); + assert.match(r.url, /^blob:/); + r.revoke?.(); + await assert.rejects(resolveModuleUrl({ url: FILE, enabled: true, sha256: SHA }, serving(bytes)), /checksum/); + } finally { + if (subtle) Object.defineProperty(globalThis.crypto, "subtle", subtle); + else delete (globalThis.crypto as { subtle?: unknown }).subtle; + } +}); diff --git a/frontend/src/plugins/store.ts b/frontend/src/plugins/store.ts new file mode 100644 index 0000000..a9bc73a --- /dev/null +++ b/frontend/src/plugins/store.ts @@ -0,0 +1,139 @@ +// The plugin store: a list of reviewed plugins kept in a public GitHub repository +// (therealMRBK/NextFloor-Plugins, `index.json`). Authors add theirs with a pull request; nothing +// listed there changes afterwards, because every entry points at a file pinned to a commit and +// carries that file's SHA-256, which the loader checks before the plugin runs. + +import type { PluginRef } from "./api.ts"; + +export const STORE_REPO = "therealMRBK/NextFloor-Plugins"; +export const STORE_INDEX_URL = `https://raw.githubusercontent.com/${STORE_REPO}/main/index.json`; + +export interface StoreEntry { + id: string; + name: string; + description: string; + author: string; + version: string; + /** Link to the plugin's page or source. */ + homepage: string; + /** A file on raw.githubusercontent.com, pinned to a 40-character commit. */ + url: string; + sha256: string; +} + +/** Only files pinned to a commit on raw.githubusercontent.com, so a listed file can never change. */ +export const isStoreFileUrl = (url: string): boolean => /^https:\/\/raw\.githubusercontent\.com\/[\w.-]+\/[\w.-]+\/[0-9a-f]{40}\/[\w./-]+\.m?js$/.test(url); + +const text = (v: unknown, max: number): string => (typeof v === "string" ? v.trim().slice(0, max) : ""); + +/** Turns the downloaded index into entries; anything malformed is dropped instead of breaking the list. */ +export function parseStoreIndex(json: unknown): StoreEntry[] { + const list = (json as { plugins?: unknown } | null)?.plugins; + if (!Array.isArray(list)) return []; + const seen = new Set(); + const out: StoreEntry[] = []; + for (const raw of list as Record[]) { + if (!raw || typeof raw !== "object") continue; + const id = text(raw.id, 64); + const url = text(raw.url, 300); + const sha256 = text(raw.sha256, 64).toLowerCase(); + const name = text(raw.name, 60); + const version = text(raw.version, 40); + const homepage = text(raw.homepage, 200); + if (!/^[\w.-]+$/.test(id) || seen.has(id) || !name || !version) continue; + if (!isStoreFileUrl(url) || !/^[0-9a-f]{64}$/.test(sha256)) continue; + seen.add(id); + out.push({ id, name, description: text(raw.description, 300), author: text(raw.author, 60), version, homepage: /^https:\/\//.test(homepage) ? homepage : "", url, sha256 }); + } + return out; +} + +export async function fetchStoreIndex(fetcher: typeof fetch = (...args) => fetch(...args)): Promise { + const res = await fetcher(STORE_INDEX_URL, { cache: "no-store" }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return parseStoreIndex(await res.json()); +} + +export type StoreState = "available" | "installed" | "update"; + +/** Where an entry stands against the plugins in the plan: not installed, installed, or a newer version listed. */ +export function storeState(entry: StoreEntry, refs: PluginRef[] | undefined): StoreState { + const ref = (refs ?? []).find((r) => r.id === entry.id); + if (!ref) return "available"; + return ref.sha256 === entry.sha256 && ref.url === entry.url ? "installed" : "update"; +} + +/** The plan's plugin list after installing or updating `entry` (an update keeps the on/off switch). */ +export function withStoreEntry(refs: PluginRef[] | undefined, entry: StoreEntry): PluginRef[] { + const list = refs ?? []; + const next: PluginRef = { url: entry.url, enabled: true, id: entry.id, version: entry.version, sha256: entry.sha256 }; + const at = list.findIndex((r) => r.id === entry.id); + if (at < 0) return [...list, next]; + return list.map((r, i) => (i === at ? { ...next, enabled: r.enabled } : r)); +} + +// ---------------------------------------------------------------- community furniture + +/** A furniture pack of the store: a data file in the store's repository (packs/.json), with its checksum. */ +export interface StorePack { + id: string; + name: string; + description: string; + author: string; + release: number; + items: number; + url: string; + sha256: string; +} + +/** Furniture packs come only from the store's own packs folder. */ +export const isStorePackUrl = (url: string, id: string): boolean => url === `https://raw.githubusercontent.com/${STORE_REPO}/main/packs/${id}.json`; + +/** The furniture packs of the downloaded index; anything malformed is dropped. */ +export function parseStorePacks(json: unknown): StorePack[] { + const list = (json as { packs?: unknown } | null)?.packs; + if (!Array.isArray(list)) return []; + const seen = new Set(); + const out: StorePack[] = []; + for (const raw of list as Record[]) { + if (!raw || typeof raw !== "object") continue; + const id = text(raw.id, 40); + const url = text(raw.url, 300); + const sha256 = text(raw.sha256, 64).toLowerCase(); + const name = text(raw.name, 80); + if (!/^[a-z0-9][a-z0-9_.-]{0,39}$/.test(id) || id.startsWith("nextfloor.") || seen.has(id) || !name) continue; + if (!isStorePackUrl(url, id) || !/^[0-9a-f]{64}$/.test(sha256)) continue; + seen.add(id); + const num = (v: unknown, fallback: number) => (typeof v === "number" && Number.isInteger(v) && v > 0 ? v : fallback); + out.push({ id, name, description: text(raw.description, 400), author: text(raw.author, 80), release: num(raw.release, 1), items: num(raw.items, 0), url, sha256 }); + } + return out.sort((a, b) => a.name.localeCompare(b.name)); +} + +export async function fetchStorePacks(fetcher: typeof fetch = (...args) => fetch(...args)): Promise { + const res = await fetcher(STORE_INDEX_URL, { cache: "no-store" }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return parseStorePacks(await res.json()); +} + +/** Where a store pack stands against the installed packs: not there, there in this release, or a newer release listed. */ +export function storePackState(entry: StorePack, installed: readonly { id: string; release?: number }[]): StoreState { + const own = installed.find((p) => p.id === entry.id); + if (!own) return "available"; + return (own.release ?? 1) >= entry.release ? "installed" : "update"; +} + +const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join(""); + +/** + * Downloads a store pack and checks it against its checksum. Browsers without `crypto.subtle` (plain http) cannot check; + * the integration checks every pack's content again when it imports it. + */ +export async function downloadStorePack(entry: StorePack, fetcher: typeof fetch = (...args) => fetch(...args)): Promise { + const res = await fetcher(entry.url, { cache: "no-store" }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const bytes = await res.arrayBuffer(); + const subtle = globalThis.crypto?.subtle; + if (subtle && hex(await subtle.digest("SHA-256", bytes)) !== entry.sha256) throw new Error("checksum mismatch: the file is not the one that was reviewed"); + return new TextDecoder().decode(bytes); +} diff --git a/frontend/src/polyfills.ts b/frontend/src/polyfills.ts new file mode 100644 index 0000000..1bd0ea8 --- /dev/null +++ b/frontend/src/polyfills.ts @@ -0,0 +1,19 @@ +// Small stand-ins for the two newer browser functions NextFloor uses that Safari only has since 15.4 +// (older iPads on iOS 15.0–15.3). They only step in when the browser lacks them. The lazily loaded +// 3D and editor bundles come after the main bundle, so they find them as well. + +if (!Array.prototype.at) { + Object.defineProperty(Array.prototype, "at", { + configurable: true, + writable: true, + value: function at(this: T[], index: number): T | undefined { + const i = Math.trunc(index) || 0; + return this[i < 0 ? this.length + i : i]; + }, + }); +} + +if (typeof globalThis.structuredClone !== "function") { + // NextFloor only clones plain JSON data (plans, settings), so a JSON round trip is enough + (globalThis as { structuredClone: unknown }).structuredClone = (value: T): T => (value === undefined ? value : JSON.parse(JSON.stringify(value))); +} diff --git a/frontend/src/presence.test.ts b/frontend/src/presence.test.ts new file mode 100644 index 0000000..fd6ddb3 --- /dev/null +++ b/frontend/src/presence.test.ts @@ -0,0 +1,121 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, newFloor, type Building, type Room } from "./model.ts"; +import { floorCounts, floorInfoText, initials, personsInRooms, roomForState, sinceText } from "./presence.ts"; +import type { HomeAssistant } from "./types.ts"; + +type Attrs = Record; +const entity = (entity_id: string, state: string, attributes: Attrs = {}) => ({ entity_id, state, attributes }); + +const room = (id: string, name: string, area: string | null, x: number): Room => ({ id, name, area_id: area, points: [[x, 0], [x + 4, 0], [x + 4, 3], [x, 3]], floor_material: "wood" }); + +function home(states: Record) { + const building: Building = emptyBuilding(); + const floor = newFloor("g", "Ground", 0); + floor.rooms = [room("lr", "Living Room", "living_room", 0), room("ki", "Kitchen", "kitchen", 4)]; + building.floors = [floor]; + building.presence = [ + { person: "person.ann", sensor: "sensor.ann_room" }, + { person: "person.bob", sensor: "sensor.bob_room" }, + { person: "person.cy", sensor: null }, + ]; + const hass = { + language: "en", + areas: { living_room: { area_id: "living_room", name: "Lounge" }, kitchen: { area_id: "kitchen", name: "Kitchen" } }, + states: Object.fromEntries(Object.entries(states).map(([id, [state, attrs]]) => [id, entity(id, state, attrs)])), + } as unknown as HomeAssistant; + return { hass, building }; +} + +test("a sensor state finds a room by its name, its area name or its area id, ignoring case and dashes", () => { + const { hass, building } = home({}); + assert.equal(roomForState(hass, building, "kitchen")?.room.id, "ki"); + assert.equal(roomForState(hass, building, "LIVING-ROOM")?.room.id, "lr"); + assert.equal(roomForState(hass, building, "living_room")?.room.id, "lr"); + assert.equal(roomForState(hass, building, "Lounge")?.room.id, "lr"); + assert.equal(roomForState(hass, building, "Garage"), null); +}); + +test("states that name no room never match", () => { + const { hass, building } = home({}); + for (const state of ["", "unknown", "unavailable", "not_home", "Away"]) assert.equal(roomForState(hass, building, state), null, state); +}); + +test("initials of one, two and many words", () => { + assert.equal(initials("ann"), "AN"); + assert.equal(initials("Ann Bell"), "AB"); + assert.equal(initials("Ann Marie van Bell"), "AB"); + assert.equal(initials(" "), "?"); +}); + +test("people at home are placed in their room, those away or without a sensor are not", () => { + const { hass, building } = home({ + "person.ann": ["home", { friendly_name: "Ann Bell", entity_picture: "/ann.png" }], + "sensor.ann_room": ["kitchen"], + "person.bob": ["not_home", { friendly_name: "Bob" }], + "sensor.bob_room": ["kitchen"], + "person.cy": ["home"], + }); + const people = personsInRooms(hass, building); + assert.equal(people.length, 1); + assert.deepEqual([people[0].id, people[0].name, people[0].initials, people[0].picture, people[0].roomId], ["person.ann", "Ann Bell", "AB", "/ann.png", "ki"]); + // the marker stands inside the kitchen (x 4..8, z 0..3) + assert.ok(people[0].x > 4 && people[0].x < 8 && people[0].z > 0 && people[0].z < 3); +}); + +test("two people in one room do not stand on the same spot", () => { + const { hass, building } = home({ + "person.ann": ["home"], "sensor.ann_room": ["kitchen"], + "person.bob": ["home"], "sensor.bob_room": ["Kitchen"], + }); + const [a, b] = personsInRooms(hass, building); + assert.notDeepEqual([a.x, a.z], [b.x, b.z]); +}); + +test("floor counts and their text leave out what is zero", () => { + const { hass, building } = home({ + "person.ann": ["home"], "sensor.ann_room": ["kitchen"], + "light.one": ["on"], "light.two": ["off"], + }); + building.floors[0].placements = [ + { entity_id: "light.one", x: 1, z: 1, y: null, mount: null }, + { entity_id: "light.two", x: 2, z: 1, y: null, mount: null }, + ]; + const counts = floorCounts(hass, building, new Map(), personsInRooms(hass, building)).get("g"); + assert.deepEqual(counts, { rooms: 2, lightsOn: 1, open: 0, persons: 1, power: null, temps: null }); + const text = floorInfoText(hass, counts!); + assert.equal(text.split(" · ").length, 3, text); + assert.equal(floorInfoText(hass, { rooms: 2, lightsOn: 0, open: 0, persons: 0, power: null }).includes(" · "), false); + // the floor's own meter joins the label + assert.ok(floorInfoText(hass, { rooms: 2, lightsOn: 0, open: 0, persons: 0, power: 1250 }).endsWith("⚡ 1.25 kW") || floorInfoText(hass, { rooms: 2, lightsOn: 0, open: 0, persons: 0, power: 1250 }).endsWith("⚡ 1,25 kW")); + assert.ok(floorInfoText(hass, { rooms: 2, lightsOn: 0, open: 0, persons: 0, power: 640 }).endsWith("⚡ 640 W")); +}); + +test("a span of time reads as minutes, then hours", () => { + assert.equal(sinceText(30_000), "0 min"); + assert.equal(sinceText(12 * 60_000), "12 min"); + assert.equal(sinceText(125 * 60_000), "2:05 h"); +}); + +test("the floor label shows the coolest and the warmest room", () => { + const hass = { language: "en", states: {}, entities: {}, areas: {}, config: { unit_system: { temperature: "°C" } } } as unknown as HomeAssistant; + const text = floorInfoText(hass, { rooms: 3, lightsOn: 0, open: 0, persons: 0, power: null, temps: [19.4, 22.2] }); + assert.ok(text.endsWith("19–22 °C"), text); + assert.ok(floorInfoText(hass, { rooms: 3, lightsOn: 0, open: 0, persons: 0, power: null, temps: [21.1, 21.3] }).endsWith(" 21 °C")); +}); + +test("a person without a room sensor, or whose sensor names no room, stands in their own room while they are home (#71)", () => { + const { hass, building } = home({ + "person.ann": ["home"], + "sensor.ann_room": ["not_home"], + "input_boolean.toni": ["on"], + "input_boolean.gast": ["off"], + }); + building.presence = [ + { person: "person.ann", sensor: "sensor.ann_room", room: "ki" }, + { person: "input_boolean.toni", sensor: null, room: "lr" }, + { person: "input_boolean.gast", sensor: null, room: "lr" }, + ]; + const at = Object.fromEntries(personsInRooms(hass, building).map((p) => [p.id, p.roomId])); + assert.deepEqual(at, { "person.ann": "ki", "input_boolean.toni": "lr" }, "away (off) is nowhere"); +}); diff --git a/frontend/src/presence.ts b/frontend/src/presence.ts new file mode 100644 index 0000000..af8db77 --- /dev/null +++ b/frontend/src/presence.ts @@ -0,0 +1,174 @@ +// People and floor summaries. A room sensor (ESPresense, Bermuda ...) reports the room a person is in as +// its state; this finds that room in the plan. Also the counts on the floor labels of the house view. + +import { fromCelsius, kindOf, openingState, primaryEntities, roomClimateValue, tempUnit, type OpeningEntities, roomEntities } from "./devices.ts"; +import { readPower } from "./energy.ts"; +import { formatNumber, translate } from "./i18n.ts"; +import { centroid, type Building, type Floor, type Room } from "./model.ts"; +import type { HomeAssistant } from "./types.ts"; + +export interface PersonMarker { + id: string; + name: string; + initials: string; + picture: string | null; + floorId: string; + roomId: string; + x: number; + z: number; +} + +/** Spelling-insensitive form of a room name: underscores and dashes read as spaces. */ +const canonical = (text: string) => text.toLowerCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim(); + +/** A sensor state that names no room. */ +const NO_ROOM = new Set(["", "unknown", "unavailable", "not home", "away"]); + +/** The room whose name, area name or area id equals a room sensor's state. */ +export function roomForState(hass: HomeAssistant, building: Building, state: string): { floorId: string; room: Room } | null { + const wanted = canonical(state); + if (NO_ROOM.has(wanted)) return null; + for (const floor of building.floors) { + for (const room of floor.rooms) { + const areaName = room.area_id ? hass.areas?.[room.area_id]?.name : undefined; + const labels = [room.name, room.area_id, areaName].map((label) => canonical(label ?? "")); + if (labels.includes(wanted)) return { floorId: floor.id, room }; + } + } + return null; +} + +function roomById(building: Building, id: string | null | undefined): { floorId: string; room: Room } | null { + if (!id) return null; + for (const floor of building.floors) { + const room = floor.rooms.find((r) => r.id === id); + if (room) return { floorId: floor.id, room }; + } + return null; +} + +/** Up to two letters for an avatar: first and last word's initials, or the first two letters of one word. */ +export function initials(name: string): string { + const words = name.split(/\s+/).filter(Boolean); + if (words.length === 0) return "?"; + const letters = words.length === 1 ? words[0].slice(0, 2) : words[0][0] + words[words.length - 1][0]; + return letters.toUpperCase(); +} + +/** Where the n-th person of a room stands: on a small circle around the centre, next to the room label. */ +function spotInRoom(room: Room, n: number): [number, number] { + const [cx, cz] = centroid(room.points); + const angle = n * 1.15 - Math.PI / 2 + 0.9; + return [cx + 0.75 * Math.cos(angle), cz + 0.75 * Math.sin(angle)]; +} + +/** People who are home and whose room sensor names a room of the plan. */ +export function personsInRooms(hass: HomeAssistant, building: Building): PersonMarker[] { + const markers: PersonMarker[] = []; + const inRoom = new Map(); + for (const { person: personId, sensor: sensorId, room: defaultRoom } of building.presence) { + const person = hass.states[personId]; + const sensor = sensorId ? hass.states[sensorId] : undefined; + // someone who is away is in no room, whatever the room sensor still says + if (!person || (person.state !== "home" && person.state !== "on")) continue; + // the room sensor names the room; without one (or when it names none) the person's own room of the plan counts + const found = (sensor ? roomForState(hass, building, sensor.state) : null) ?? roomById(building, defaultRoom); + if (!found) continue; + const n = inRoom.get(found.room.id) ?? 0; + inRoom.set(found.room.id, n + 1); + const [x, z] = spotInRoom(found.room, n); + const name = String(person.attributes.friendly_name ?? personId); + const picture = person.attributes.entity_picture; + markers.push({ id: personId, name, initials: initials(name), picture: typeof picture === "string" ? picture : null, floorId: found.floorId, roomId: found.room.id, x, z }); + } + return markers; +} + +export interface FloorCounts { + rooms: number; + lightsOn: number; + open: number; + persons: number; + /** What the floor's own meter reads now, in watts (null: no meter or no number). */ + power: number | null; + /** The coolest and the warmest room of the floor (°C), when at least two rooms have a temperature. */ + temps?: [number, number] | null; +} + +function lightsOnFloor(hass: HomeAssistant, floor: Floor): number { + const lights = new Set(); + // only the main entity of a device counts: an LED strip with 30 segment entities is one light + for (const room of floor.rooms) { + for (const id of primaryEntities(hass, roomEntities(hass, room))) if (kindOf(id) === "light") lights.add(id); + } + for (const placed of floor.placements) if (kindOf(placed.entity_id) === "light") lights.add(placed.entity_id); + return [...lights].filter((id) => hass.states[id]?.state === "on").length; +} + +function openingsOnFloor(hass: HomeAssistant, floor: Floor, links: Map): number { + const isOn = (id: string | null | undefined) => !!id && hass.states[id]?.state === "on"; + let count = 0; + for (const opening of floor.openings) { + const link = links.get(opening.id); + if (!link) continue; + if (opening.type === "garage") { + // open while the door is not (nearly) all the way down + if ((openingState(hass, link, "garage").cover ?? 1) < 0.95) count++; + } else if (opening.type === "door") { + if (isOn(link.contact) || isOn(link.contact2)) count++; + } else { + const s = openingState(hass, link, "window"); + if (Math.max(s.open, s.tilt, s.open2, s.tilt2) > 0.5) count++; + } + } + return count; +} + +/** Room, light, open-window and person counts per floor, for the floor labels. */ +export function floorCounts(hass: HomeAssistant, building: Building, links: Map, persons: PersonMarker[]): Map { + return new Map( + building.floors.map((floor) => [ + floor.id, + { + rooms: floor.rooms.length, + lightsOn: lightsOnFloor(hass, floor), + open: openingsOnFloor(hass, floor, links), + persons: persons.filter((p) => p.floorId === floor.id).length, + power: floor.power_entity ? readPower(hass.states[floor.power_entity]) : null, + temps: tempRange(hass, floor), + }, + ]), + ); +} + +/** The coolest and the warmest room of a floor, when two or more rooms report a temperature. */ +function tempRange(hass: HomeAssistant, floor: Floor): [number, number] | null { + const values = floor.rooms.map((r) => roomClimateValue(hass, floor, r, "temperature")).filter((v): v is number => v !== null); + return values.length >= 2 ? [Math.min(...values), Math.max(...values)] : null; +} + +/** The label text: "3 rooms · 2 lights on · 1 open · 1 person", leaving out what is zero. */ +export function floorInfoText(hass: HomeAssistant | undefined, c: FloorCounts): string { + const parts = [c.rooms === 1 ? translate(hass, "floor_rooms_one") : translate(hass, "floor_rooms", { n: c.rooms })]; + if (c.lightsOn > 0) parts.push(translate(hass, "floor_lights", { n: c.lightsOn })); + if (c.open > 0) parts.push(translate(hass, "floor_open", { n: c.open })); + if (c.persons > 0) parts.push(translate(hass, "floor_persons", { n: c.persons })); + if (c.temps && hass) { + const [lo, hi] = c.temps.map((t) => formatNumber(hass, fromCelsius(hass, t), 0)); + parts.push(lo === hi ? `${lo} ${tempUnit(hass)}` : `${lo}–${hi} ${tempUnit(hass)}`); + } + if (c.power != null) parts.push(`⚡ ${powerText(hass, c.power)}`); + return parts.join(" · "); +} + +/** Watts as "640 W" or "1,25 kW". */ +export function powerText(hass: HomeAssistant | undefined, w: number): string { + const a = Math.abs(w); + return a >= 1000 ? `${formatNumber(hass, w / 1000, a >= 10000 ? 1 : 2)} kW` : `${Math.round(w)} W`; +} + +/** A span of time as "12 min" or "2:05 h". */ +export function sinceText(ms: number): string { + const minutes = Math.max(0, Math.floor(ms / 60_000)); + return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")} h`; +} diff --git a/frontend/src/roof-sections.ts b/frontend/src/roof-sections.ts new file mode 100644 index 0000000..0ec7971 --- /dev/null +++ b/frontend/src/roof-sections.ts @@ -0,0 +1,7 @@ +// Roof sections: the plain geometry of a section and the proposal of sections from the rooms, split into modules in roof/. + +export { sectionFrame, sectionProfile, sectionUV, ridgeHeight, type SectionFrame, type SectionProfile } from "./roof/frame.ts"; +export { offsetPolygon, sectionPolygon, polygonBox, floorOutline } from "./roof/polygons.ts"; +export { sectionGeometry, sectionHeightAt, cutHole, sectionOverhang, type Q, type SectionGeometry, type SectionOverhang } from "./roof/geometry.ts"; +export { dormerParent, dormerHole, dormerHoles, proposeDormer, effectiveDormer, wingOf } from "./roof/dormers.ts"; +export { ROOF_THICK, headroomLines, roofRider, roofSectionsFromRooms, roofUnderAt, sectionCutsBelow, sectionFloor, wallTopUnder, type RoofHolder } from "./roof/proposal.ts"; diff --git a/frontend/src/roof/dormers.test.ts b/frontend/src/roof/dormers.test.ts new file mode 100644 index 0000000..43d9177 --- /dev/null +++ b/frontend/src/roof/dormers.test.ts @@ -0,0 +1,100 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { gableSection, near } from "./fixtures.ts"; +import { dormerHole, dormerHoles, dormerParent, effectiveDormer, proposeDormer, wingOf } from "./dormers.ts"; +import { sectionProfile } from "./frame.ts"; + +test("a dormer is proposed on the chosen side, 2 m wide, 35° gable, eaves 1.4 m above the section's", () => { + const parent = gableSection(); + const d = proposeDormer(parent, "a", "dormer", 6); + assert.equal(d.dormer, true); + assert.equal(d.shape, "gable"); + assert.equal(d.axis, "z", "its ridge runs across the parent's ridge"); + assert.equal(d.eave_a, 4.4); + assert.equal(d.pitch_a, 35); + near(d.x1 - d.x0, 2, 0.01); + assert.ok(d.z0 === 0, "its front is flush with the eave wall"); + const other = proposeDormer(parent, "b", "other", 6); + assert.equal(other.z1, 8); +}); + +test("a dormer stays inside the ends of the section even when asked for a spot near them", () => { + const d = proposeDormer(gableSection(), "a", "d", -50); + assert.ok(d.x0 >= 0.3 - 0.01); + const e = proposeDormer(gableSection(), "a", "e", 500); + assert.ok(e.x1 <= 12 - 0.3 + 0.01); +}); + +test("a dormer's base is the parent's roof height at the eave it sits on", () => { + const parent = gableSection({ eave_a: 3, eave_b: 2.5 }); + const a = proposeDormer(parent, "a", "d"); + const b = proposeDormer(parent, "b", "d"); + near(a.base, sectionProfile(parent).y(0), 0.01); + near(b.base, sectionProfile(parent).y(8), 0.01); +}); + +test("the parent is the smallest clearly bigger sloped section holding the dormer's centre", () => { + const big = gableSection({ id: "big", x1: 20, z1: 12 }); + const mid = gableSection({ id: "mid" }); + const dormer = proposeDormer(mid, "a", "d", 6); + assert.equal(dormerParent([big, mid, dormer], dormer)?.id, "mid"); + assert.equal(dormerParent([big, dormer], dormer)?.id, "big"); + assert.equal(dormerParent([dormer], dormer), null); + const lonely = gableSection({ id: "far", x0: 50, x1: 52, z0: 50, z1: 52 }); + assert.equal(dormerParent([big, mid, lonely], lonely), null); +}); + +test("flat roofs and other dormers are no parents", () => { + const dormer = gableSection({ id: "d", x0: 5, x1: 7, z0: 1, z1: 3, dormer: true }); + assert.equal(dormerParent([gableSection({ shape: "flat" }), gableSection({ dormer: true, id: "x" })], dormer), null); +}); + +test("a dormer's footprint in the parent's frame, or null when it is a speck", () => { + const parent = gableSection(); + const d = proposeDormer(parent, "a", "d", 6); + const hole = dormerHole(parent, d)!; + near(hole.u1 - hole.u0, d.x1 - d.x0, 1e-6); + assert.equal(dormerHole(parent, { ...d, x1: d.x0 + 0.05 }), null); +}); + +test("a dormer's depth ends where its ridge meets the slope", () => { + const parent = gableSection(); + const d = proposeDormer(parent, "a", "d", 6); + const deeper = { ...d, z1: 8 }; + const effective = effectiveDormer(parent, deeper); + assert.ok(effective.z1 < 8, "cut back to the slope"); + assert.ok(effective.z1 > d.z0); + // flat dormers are left alone + const flat = { ...deeper, shape: "flat" as const }; + assert.equal(effectiveDormer(parent, flat), flat); +}); + +test("a dormer that already ends at the slope stays as it is", () => { + const parent = gableSection(); + const d = proposeDormer(parent, "a", "d", 6); + const effective = effectiveDormer(parent, d); + assert.ok(Math.abs(effective.z1 - d.z1) < 0.2); +}); + +test("the slope opens in strips that follow the dormer's roof", () => { + const parent = gableSection(); + const holes = dormerHoles(parent, proposeDormer(parent, "a", "d", 6)); + assert.ok(holes.length >= 3); + for (const h of holes) { + assert.ok(h.u1 > h.u0 && h.v1 > h.v0); + assert.ok(h.u0 >= 4.9 && h.u1 <= 7.1, "inside the dormer's width"); + } +}); + +test("a wing butting against the eave of a bigger roof reaches into it to form the valleys", () => { + const main = gableSection({ id: "main", x0: 0, z0: 0, x1: 10, z1: 6, axis: "x", eave_a: 2.6, eave_b: 2.6, pitch_a: 40, pitch_b: 40, base: 2.6 }); + const wing = gableSection({ id: "wing", x0: 6, z0: 6, x1: 10, z1: 12, axis: "z", eave_a: 2.6, eave_b: 2.6, pitch_a: 40, pitch_b: 40, base: 2.6 }); + const found = wingOf([main, wing], wing); + assert.equal(found?.parent.id, "main"); + // the wing reaches back into the main roof, but not past the middle (its ridge meets the slope before that) + assert.ok(found!.extended.z0 < 6 && found!.extended.z0 >= 3, `reaches to ${found!.extended.z0}`); + assert.equal(found!.extended.z1, 12); + assert.equal(wingOf([main, wing], main), null, "the bigger roof is no wing"); + const apart = gableSection({ id: "apart", x0: 6, z0: 8, x1: 10, z1: 14, axis: "z" }); + assert.equal(wingOf([main, apart], apart), null, "a section that does not touch stands on its own"); +}); diff --git a/frontend/src/roof/dormers.ts b/frontend/src/roof/dormers.ts new file mode 100644 index 0000000..d2dfb20 --- /dev/null +++ b/frontend/src/roof/dormers.ts @@ -0,0 +1,172 @@ +// Dormers and cross gables: the section one sits on, where it opens the slope, and how deep it really goes. + +import type { RoofSection } from "../model.ts"; +import { DEG, orderedRect, sectionFrame, sectionProfile, sectionUV } from "./frame.ts"; +import { cutHole, sectionGeometry, sectionHeightAt, type Hole } from "./geometry.ts"; + +const area = (s: RoofSection) => Math.abs((s.x1 - s.x0) * (s.z1 - s.z0)); +const isFlat = (s: RoofSection) => s.shape === "flat" || s.shape === "parapet"; +const round2 = (v: number) => Math.round(v * 100) / 100; + +/** + * The section a dormer (or any much smaller section, such as a cross gable) sits on: the clearly bigger sloped one + * that holds its centre, the smallest such one when there are several. Null when it stands on its own. + */ +export function dormerParent(sections: readonly RoofSection[], dormer: RoofSection): RoofSection | null { + const [cx, cz] = [(dormer.x0 + dormer.x1) / 2, (dormer.z0 + dormer.z1) / 2]; + const candidates = sections.filter((s) => { + if (s === dormer || s.dormer || s.open || isFlat(s) || area(s) < area(dormer) * 1.5) return false; + const box = orderedRect(s); + return cx >= box.x0 && cx <= box.x1 && cz >= box.z0 && cz <= box.z1; + }); + return candidates.reduce((best, s) => (best === null || area(s) < area(best) ? s : best), null); +} + +/** A dormer's footprint in its parent's frame (u along the parent's ridge, v across), or null when it lies outside. */ +export function dormerHole(parent: RoofSection, dormer: RoofSection): Hole | null { + const box = orderedRect(dormer); + const [p, q] = [sectionUV(parent, box.x0, box.z0), sectionUV(parent, box.x1, box.z1)]; + const hole = { u0: Math.min(p[0], q[0]), u1: Math.max(p[0], q[0]), v0: Math.min(p[1], q[1]), v1: Math.max(p[1], q[1]) }; + return hole.u1 - hole.u0 < 0.1 || hole.v1 - hole.v0 < 0.1 ? null : hole; +} + +/** + * A new dormer on one side of a section: 2 m wide, its front flush with the eave wall, its eaves 1.4 m above the + * section's eave, a 35° gable, and as deep as its ridge needs to meet the slope. + */ +export function proposeDormer(parent: RoofSection, side: "a" | "b", id: string, along?: number): RoofSection { + const frame = sectionFrame(parent); + const profile = sectionProfile(parent); + const width = 2; + const left = Math.max(frame.u0 + 0.3, Math.min(frame.u1 - width - 0.3, (along ?? (frame.u0 + frame.u1) / 2) - width / 2)); + const [eave, pitch] = side === "a" ? [parent.eave_a, parent.pitch_a] : [parent.eave_b, parent.pitch_b]; + const dormerEave = eave + 1.4; + const dormerRidge = dormerEave + (width / 2) * Math.tan(35 * DEG); + // the dormer's ridge meets the slope this far in from the eave + const depth = Math.max(0.8, Math.min(frame.w / 2 - 0.2, (dormerRidge - eave) / Math.max(0.15, Math.tan(Math.min(80, pitch) * DEG)))); + const [v0, v1] = side === "a" ? [0, depth] : [frame.w - depth, frame.w]; + const p = frame.at(left, v0); + const q = frame.at(left + width, v1); + return { + id, + x0: round2(Math.min(p[0], q[0])), + z0: round2(Math.min(p[1], q[1])), + x1: round2(Math.max(p[0], q[0])), + z1: round2(Math.max(p[1], q[1])), + shape: "gable", + // its ridge runs into the slope: across the parent's ridge + axis: parent.axis === "x" ? "z" : "x", + eave_a: round2(dormerEave), + eave_b: round2(dormerEave), + pitch_a: 35, + pitch_b: 35, + base: round2(profile.y(side === "a" ? 0 : frame.w)), + overhang: 0.15, + dormer: true, + }; +} + +/** The parent's roof height under a dormer's centre line at u; falls back to the profile outside every plane. */ +function slopeUnder(parent: RoofSection, dormerFrame: ReturnType) { + const geometry = sectionGeometry(parent, { u0: 0, u1: 0, a: 0, b: 0 }); + const profile = sectionProfile(parent); + return (u: number) => { + const [x, z] = dormerFrame.at(u, dormerFrame.w / 2); + const [pu, pv] = sectionUV(parent, x, z); + return sectionHeightAt(geometry, pu, pv) ?? profile.y(pv); + }; +} + +/** + * A dormer as the 3D view draws it: its depth ends where its ridge meets the parent's slope, deeper its roof would lie + * under the slope. Lower eaves or a flatter pitch shorten it by themselves, so nothing has to be measured again. + */ +export function effectiveDormer(parent: RoofSection, dormer: RoofSection): RoofSection { + if (isFlat(dormer)) return dormer; + const frame = sectionFrame(dormer); + const ridge = sectionProfile(dormer).rh; + const slope = slopeUnder(parent, frame); + const frontIsU0 = slope(frame.u0) <= slope(frame.u1); + const [front, rear] = frontIsU0 ? [frame.u0, frame.u1] : [frame.u1, frame.u0]; + const direction = frontIsU0 ? 1 : -1; + let meeting = rear; + for (let t = 0.5; t < Math.abs(rear - front); t += 0.05) { + if (slope(front + direction * t) >= ridge - 0.02) { + meeting = front + direction * t; + break; + } + } + if (Math.abs(meeting - rear) < 0.05) return dormer; + const shortened = { ...dormer }; + // u runs along the dormer's own axis: x for an "x" axis, z for a "z" axis + const rearIsHigh = rear === frame.u1; + if (dormer.axis === "x") shortened[rearIsHigh ? "x1" : "x0"] = meeting; + else shortened[rearIsHigh ? "z1" : "z0"] = meeting; + return shortened; +} + +/** + * Where the slope opens under a dormer: only where the dormer's roof lies above the slope, a shape that narrows towards + * the rear (the valleys), cut as strips across the dormer's depth and expressed in the parent's frame. + */ +export function dormerHoles(parent: RoofSection, dormer: RoofSection): Hole[] { + const effective = effectiveDormer(parent, dormer); + const frame = sectionFrame(effective); + const dormerProfile = sectionProfile(effective); + const slope = slopeUnder(parent, frame); + const frontIsU0 = slope(frame.u0) <= slope(frame.u1); + const depth = frame.u1 - frame.u0; + const strips = Math.max(1, Math.ceil(depth / 0.15)); + const holes: Hole[] = []; + for (let i = 0; i < strips; i++) { + const [t0, t1] = [(depth * i) / strips, (depth * (i + 1)) / strips]; + const [uA, uB] = frontIsU0 ? [frame.u0 + t0, frame.u0 + t1] : [frame.u1 - t0, frame.u1 - t1]; + // the slope at the strip's rear end; the dormer's roof across the strip decides how wide it is + const level = slope(uB); + let first = Infinity; + let last = -Infinity; + for (let k = 0; k <= 40; k++) { + const v = (frame.w * k) / 40; + if (dormerProfile.y(v) > level + 0.02) { + first = Math.min(first, v); + last = Math.max(last, v); + } + } + if (!(last - first > 0.05)) continue; + const a = sectionUV(parent, ...frame.at(uA, first)); + const b = sectionUV(parent, ...frame.at(uB, last)); + holes.push({ u0: Math.min(a[0], b[0]), u1: Math.max(a[0], b[0]), v0: Math.min(a[1], b[1]), v1: Math.max(a[1], b[1]) }); + } + return holes; +} + +export { cutHole }; + +/** + * A wing that butts against the eave side of a bigger roof at a right angle (an L- or T-shaped house): its parent, and the wing + * reaching into the parent as far as the parent's ridge, so its slopes run into the parent's slope and form the valleys there. + * Null for a section that stands on its own or already sits on another (a dormer or cross gable). + */ +export function wingOf(sections: readonly RoofSection[], wing: RoofSection): { parent: RoofSection; extended: RoofSection } | null { + if (wing.dormer || wing.open || isFlat(wing) || dormerParent(sections, wing)) return null; + const w = orderedRect(wing); + const touch = 0.35; + for (const p of sections) { + if (p === wing || p.dormer || p.open || isFlat(p) || p.axis === wing.axis || area(p) < area(wing)) continue; + const r = orderedRect(p); + // the wing's ridge runs across the parent's ridge: along z when the parent's runs along x, and the other way round + const along = wing.axis === "z" ? ([w.z0, w.z1, r.z0, r.z1] as const) : ([w.x0, w.x1, r.x0, r.x1] as const); + const across = wing.axis === "z" ? ([w.x0, w.x1, r.x0, r.x1] as const) : ([w.z0, w.z1, r.z0, r.z1] as const); + // it lies alongside the parent's eave, within the parent's length + if (across[0] < across[2] - 0.05 || across[1] > across[3] + 0.05) continue; + const middle = (along[2] + along[3]) / 2; + const [lo, hi] = wing.axis === "z" ? (["z0", "z1"] as const) : (["x0", "x1"] as const); + let range: [number, number]; + if (Math.abs(along[0] - along[3]) <= touch) range = [middle, along[1]]; // it starts at the parent's far eave: reach back + else if (Math.abs(along[1] - along[2]) <= touch) range = [along[0], middle]; // it ends at the parent's near eave: reach on + else continue; + const extended = { ...wing, [lo]: range[0], [hi]: range[1] }; + return { parent: p, extended: effectiveDormer(p, extended) }; + } + return null; +} diff --git a/frontend/src/roof/fixtures.ts b/frontend/src/roof/fixtures.ts new file mode 100644 index 0000000..f6457eb --- /dev/null +++ b/frontend/src/roof/fixtures.ts @@ -0,0 +1,26 @@ +// Builders for the roof tests. + +import type { Room, RoofSection } from "../model.ts"; + +export const near = (a: number, b: number, eps = 1e-6) => { + if (Math.abs(a - b) >= eps) throw new Error(`${a} is not close to ${b}`); +}; + +export const rectRoom = (id: string, x0: number, z0: number, x1: number, z1: number): Room => ({ id, name: id, area_id: null, points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]], floor_material: "wood" }); + +/** A 12 × 8 m gable with 45° slopes and its eaves at 3 m; the ridge runs along x. */ +export const gableSection = (patch: Partial = {}): RoofSection => ({ + id: "s", + x0: 0, + z0: 0, + x1: 12, + z1: 8, + shape: "gable", + axis: "x", + eave_a: 3, + eave_b: 3, + pitch_a: 45, + pitch_b: 45, + base: 3, + ...patch, +}); diff --git a/frontend/src/roof/frame.test.ts b/frontend/src/roof/frame.test.ts new file mode 100644 index 0000000..6855c3b --- /dev/null +++ b/frontend/src/roof/frame.test.ts @@ -0,0 +1,82 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { gableSection, near } from "./fixtures.ts"; +import { gradient, orderedRect, ridgeHeight, sectionFrame, sectionProfile, sectionUV, turnedPoint } from "./frame.ts"; + +test("pitches become gradients and are kept between 0° and 80°", () => { + near(gradient(45), 1); + near(gradient(0), 0); + near(gradient(-10), 0); + near(gradient(120), Math.tan((80 * Math.PI) / 180)); +}); + +test("a rectangle is put in order whichever corners were given", () => { + assert.deepEqual(orderedRect({ x0: 5, z0: 4, x1: 1, z1: 2 }), { x0: 1, x1: 5, z0: 2, z1: 4 }); +}); + +test("the frame: u runs along the ridge, v across from side a, and flipping swaps the sides", () => { + const f = sectionFrame(gableSection()); + assert.deepEqual([f.u0, f.u1, f.w], [0, 12, 8]); + assert.deepEqual(f.at(2, 3), [2, 3]); + const flipped = sectionFrame(gableSection({ flip: true })); + assert.deepEqual(flipped.at(2, 3), [2, 5]); + const along = sectionFrame(gableSection({ axis: "z" })); + assert.deepEqual([along.u0, along.u1, along.w], [0, 8, 12]); + assert.deepEqual(along.at(2, 3), [3, 2]); +}); + +test("a plan point maps to the same (u, v) the frame maps back from", () => { + for (const s of [gableSection(), gableSection({ flip: true }), gableSection({ axis: "z" }), gableSection({ axis: "z", flip: true })]) { + const f = sectionFrame(s); + const [x, z] = f.at(3.5, 1.25); + const [u, v] = sectionUV(s, x, z); + near(u, 3.5); + near(v, 1.25); + } +}); + +test("a symmetric gable peaks in the middle at half the width", () => { + const p = sectionProfile(gableSection()); + near(p.vr, 4); + near(p.rh, 7); + near(p.y(0), 3); + near(p.y(8), 3); + near(p.y(2), 5); + near(ridgeHeight(gableSection()), 7); +}); + +test("a lower eave on side b moves the ridge towards side a and keeps both slopes", () => { + const p = sectionProfile(gableSection({ eave_b: 2 })); + near(p.vr, 3.5); + near(p.y(p.vr), p.rh); + near(p.y(8), 2); +}); + +test("a pent roof climbs from side a to its high edge, flat and parapet roofs stay at their eave", () => { + const pent = sectionProfile(gableSection({ shape: "pent", pitch_a: 20 })); + near(pent.vr, 8); + near(pent.rh, 3 + 8 * Math.tan((20 * Math.PI) / 180)); + assert.equal(sectionProfile(gableSection({ shape: "flat" })).y(3), 3); + assert.equal(sectionProfile(gableSection({ shape: "parapet" })).rh, 3); +}); + +test("a mansard breaks into a steeper lower and a 30° upper slope and is continuous", () => { + const p = sectionProfile(gableSection({ shape: "mansard", pitch_a: 70, pitch_b: 70 })); + assert.ok(p.rh > 3); + let last = p.y(0); + for (let v = 0.25; v <= 8; v += 0.25) { + assert.ok(Math.abs(p.y(v) - last) < 3, `no jump at ${v}`); + last = p.y(v); + } + near(p.y(p.vr), p.rh, 1e-6); +}); + +test("a turned section maps its frame to the plan and back", () => { + const s = { x0: 0, z0: 0, x1: 8, z1: 4, axis: "x" as const, flip: false, rotation: 30 }; + const f = sectionFrame(s); + const p = f.at(2, 1); + const [u, v] = sectionUV(s, p[0], p[1]); + assert.ok(Math.abs(u - 2) < 1e-9 && Math.abs(v - 1) < 1e-9); + assert.notDeepEqual(p, [2, 1], "it really turns"); + assert.ok(Math.abs(turnedPoint(s, [4, 2])[0] - 4) < 1e-9, "about its middle"); +}); diff --git a/frontend/src/roof/frame.ts b/frontend/src/roof/frame.ts new file mode 100644 index 0000000..145dedc --- /dev/null +++ b/frontend/src/roof/frame.ts @@ -0,0 +1,129 @@ +// The local frame of a roof section and its height profile across the ridge. Plain geometry, no three.js: +// the editor draws with it as well. + +import type { RoofSection, Vec2 } from "../model.ts"; + +export const DEG = Math.PI / 180; + +/** The slope of a pitch in degrees as a gradient; pitches are kept between 0° and 80°. */ +export const gradient = (pitchDeg: number): number => Math.tan(Math.min(80, Math.max(0, pitchDeg)) * DEG); + +type Rect = Pick; + +/** The rectangle of a section with its corners put in order. */ +export function orderedRect(s: Rect): { x0: number; x1: number; z0: number; z1: number } { + return { x0: Math.min(s.x0, s.x1), x1: Math.max(s.x0, s.x1), z0: Math.min(s.z0, s.z1), z1: Math.max(s.z0, s.z1) }; +} + +/** u runs along the ridge (u0 to u1 at the wall faces), v across it from side a (v = 0) to side b (v = w). */ +export interface SectionFrame { + u0: number; + u1: number; + w: number; + /** The plan point of a local (u, v). */ + at(u: number, v: number): Vec2; +} + +type FrameInput = Rect & Pick & { rotation?: number | null }; + +/** A section turned about the middle of its rectangle (a wing at an angle): the middle and the turn, or null when it stands straight. */ +function turnOf(s: Rect & { rotation?: number | null }): { cx: number; cz: number; c: number; sn: number } | null { + if (!s.rotation) return null; + const r = s.rotation * DEG; + return { cx: (s.x0 + s.x1) / 2, cz: (s.z0 + s.z1) / 2, c: Math.cos(r), sn: Math.sin(r) }; +} + +/** A point of the section's own (unturned) rectangle in the plan: turned clockwise about the middle by the section's rotation. */ +export function turnedPoint(s: Rect & { rotation?: number | null }, p: Vec2): Vec2 { + const t = turnOf(s); + if (!t) return p; + const [dx, dz] = [p[0] - t.cx, p[1] - t.cz]; + return [t.cx + dx * t.c - dz * t.sn, t.cz + dx * t.sn + dz * t.c]; +} + +/** A plan point in the section's own (unturned) rectangle. */ +export function unturnedPoint(s: Rect & { rotation?: number | null }, x: number, z: number): Vec2 { + const t = turnOf(s); + if (!t) return [x, z]; + const [dx, dz] = [x - t.cx, z - t.cz]; + return [t.cx + dx * t.c + dz * t.sn, t.cz - dx * t.sn + dz * t.c]; +} + +/** The four corners of a section's rectangle in the plan, turned with it. */ +export function sectionCorners(s: Rect & { rotation?: number | null }, grow = 0): Vec2[] { + const { x0, x1, z0, z1 } = orderedRect(s); + return ([[x0 - grow, z0 - grow], [x1 + grow, z0 - grow], [x1 + grow, z1 + grow], [x0 - grow, z1 + grow]] as Vec2[]).map((p) => turnedPoint(s, p)); +} + +export function sectionFrame(s: FrameInput): SectionFrame { + const { x0, x1, z0, z1 } = orderedRect(s); + const turn = (p: Vec2) => turnedPoint(s, p); + // flipped: v counts from the high coordinate, so side a is the bottom (or right) side + if (s.axis === "x") return { u0: x0, u1: x1, w: z1 - z0, at: (u, v) => turn([u, s.flip ? z1 - v : z0 + v]) }; + return { u0: z0, u1: z1, w: x1 - x0, at: (u, v) => turn([s.flip ? x1 - v : x0 + v, u]) }; +} + +/** A plan point as (u, v) in the section's frame: along the ridge and across from side a. */ +export function sectionUV(s: FrameInput, px: number, pz: number): [number, number] { + const { x0, x1, z0, z1 } = orderedRect(s); + const [x, z] = unturnedPoint(s, px, pz); + if (s.axis === "x") return [x, s.flip ? z1 - z : z - z0]; + return [z, s.flip ? x1 - x : x - x0]; +} + +/** Where the ridge is and how high the roof is at any v. */ +export interface SectionProfile { + /** Ridge position across (0 to w); a pent roof has its high edge at w. */ + vr: number; + /** Height of the ridge (or the high edge) above the ground. */ + rh: number; + /** Roof height above the ground at v, also beyond the walls (the overhang). */ + y(v: number): number; +} + +const UPPER_MANSARD = Math.tan(30 * DEG); + +/** A mansard: steep lower slopes up to a break (2.4 m of rise or 30 % of the width), then 30° slopes to the ridge. */ +export function mansardParts(w: number, eaveA: number, eaveB: number, gradA: number, gradB: number) { + const runA = Math.min(w * 0.3, gradA > 1e-6 ? 2.4 / gradA : w * 0.3); + const runB = Math.min(w * 0.3, gradB > 1e-6 ? 2.4 / gradB : w * 0.3); + const breakA = eaveA + runA * gradA; + const breakB = eaveB + runB * gradB; + // the upper slopes meet where they are equally high + const ridgeV = Math.min(w - runB, Math.max(runA, (breakB - breakA + UPPER_MANSARD * (w - runB + runA)) / (2 * UPPER_MANSARD))); + const ridgeY = breakA + (ridgeV - runA) * UPPER_MANSARD; + const y = (v: number) => { + if (v <= runA) return eaveA + v * gradA; + if (v <= ridgeV) return breakA + (v - runA) * UPPER_MANSARD; + if (v <= w - runB) return breakB + (w - runB - v) * UPPER_MANSARD; + return eaveB + (w - v) * gradB; + }; + return { vla: runA, vlb: runB, yla: breakA, ylb: breakB, vr: ridgeV, rh: ridgeY, y }; +} + +type ProfileInput = FrameInput & Pick; + +export function sectionProfile(s: ProfileInput): SectionProfile { + const w = sectionFrame(s).w; + const [eaveA, eaveB] = [s.eave_a, s.eave_b]; + const [gradA, gradB] = [gradient(s.pitch_a), gradient(s.pitch_b)]; + switch (s.shape) { + case "flat": + case "parapet": + return { vr: w / 2, rh: eaveA, y: () => eaveA }; + case "pent": + return { vr: w, rh: eaveA + w * gradA, y: (v) => eaveA + v * gradA }; + case "mansard": { + const m = mansardParts(w, eaveA, eaveB, gradA, gradB); + return { vr: m.vr, rh: m.rh, y: m.y }; + } + default: { + // the slopes meet where they are equally high: a lower eave or a flatter slope moves the ridge + const vr = gradA + gradB > 1e-6 ? Math.min(w, Math.max(0, (eaveB - eaveA + w * gradB) / (gradA + gradB))) : w / 2; + return { vr, rh: eaveA + vr * gradA, y: (v) => (v <= vr ? eaveA + v * gradA : eaveB + (w - v) * gradB) }; + } + } +} + +/** Height of the ridge (or of a pent roof's high edge) above the ground. */ +export const ridgeHeight = (s: RoofSection): number => sectionProfile(s).rh; diff --git a/frontend/src/roof/geometry.test.ts b/frontend/src/roof/geometry.test.ts new file mode 100644 index 0000000..e809099 --- /dev/null +++ b/frontend/src/roof/geometry.test.ts @@ -0,0 +1,118 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, newFloor, ROOF_SHAPES, type RoofSection } from "../model.ts"; +import { gableSection, near, rectRoom } from "./fixtures.ts"; +import { cutHole, sectionGeometry, sectionHeightAt, sectionOverhang, type Q } from "./geometry.ts"; + +const none = { u0: 0, u1: 0, a: 0, b: 0 }; + +test("every roof shape builds faces, a rim and ridges", () => { + for (const shape of ROOF_SHAPES) { + const g = sectionGeometry(gableSection({ shape }), none); + assert.ok(g.faces.length >= 1, shape); + assert.ok(g.rim.length >= 4, shape); + assert.ok(g.faces.every((f) => f.length >= 3), shape); + } +}); + +test("gable: two faces and a three-point gable end; hip and pyramid have no gable end", () => { + const gable = sectionGeometry(gableSection(), none); + assert.equal(gable.faces.length, 2); + assert.equal(gable.gable?.length, 3); + assert.equal(sectionGeometry(gableSection({ shape: "hip" }), none).gable, null); + assert.equal(sectionGeometry(gableSection({ shape: "pyramid" }), none).gable, null); +}); + +test("a pyramid has its apex in the middle of the rectangle at the ridge height", () => { + const g = sectionGeometry(gableSection({ x1: 8, shape: "pyramid" }), none); + assert.equal(g.faces.length, 4); + const apex = g.faces[0][2]; + near(apex[0], 4); + near(apex[1], 4); + near(apex[2], 7); +}); + +test("a hip's ridge is shorter than the house by the run of the end slopes", () => { + const [ridge] = sectionGeometry(gableSection({ shape: "hip" }), none).ridges; + near(Math.abs(ridge[1][0] - ridge[0][0]), 12 - 2 * 4); +}); + +test("a half-hip's gable end is cut at 55 % of the roof's height", () => { + const g = sectionGeometry(gableSection({ shape: "halfhip" }), none); + assert.equal(g.gable?.length, 4); + near(g.gable![1][1], 3 + 4 * 0.55); +}); + +test("a mansard has four faces and a five-point gable end", () => { + const g = sectionGeometry(gableSection({ shape: "mansard", pitch_a: 70, pitch_b: 70 }), none); + assert.equal(g.faces.length, 4); + assert.equal(g.gable?.length, 5); +}); + +test("the overhang widens the roof on exactly the edges it is given", () => { + const g = sectionGeometry(gableSection(), { u0: 0.5, u1: 1, a: 0.25, b: 0 }); + const us = g.rim.map((q) => q[0]); + const vs = g.rim.map((q) => q[1]); + near(Math.min(...us), -0.5); + near(Math.max(...us), 13); + near(Math.min(...vs), -0.25); + near(Math.max(...vs), 8); +}); + +test("the planes know their height anywhere over them, and nothing outside", () => { + const g = sectionGeometry(gableSection(), none); + near(sectionHeightAt(g, 6, 0)!, 3); + near(sectionHeightAt(g, 6, 2)!, 5); + near(sectionHeightAt(g, 6, 4)!, 7); + near(sectionHeightAt(g, 6, 6)!, 5); + assert.equal(sectionHeightAt(g, 20, 4), null); + assert.equal(sectionHeightAt(g, 6, -3), null); +}); + +test("cutting a hole leaves pieces around it and none inside", () => { + const face: Q[] = [[0, 0, 3], [10, 0, 3], [10, 6, 7], [0, 6, 7]]; + const pieces = cutHole(face, { u0: 3, u1: 6, v0: 2, v1: 4 }); + assert.equal(pieces.length, 4); + for (const piece of pieces) for (const q of piece) assert.ok(!(q[0] > 3 + 1e-6 && q[0] < 6 - 1e-6 && q[1] > 2 + 1e-6 && q[1] < 4 - 1e-6), "no corner inside the hole"); + // heights follow the slope on the cut edges + const lower = pieces.find((p) => p.every((q) => q[1] <= 2 + 1e-9))!; + assert.ok(lower.every((q) => Math.abs(q[2] - (3 + (q[1] / 6) * 4)) < 1e-9)); +}); + +test("a hole at the edge of a face leaves fewer pieces", () => { + const face: Q[] = [[0, 0, 3], [10, 0, 3], [10, 6, 7], [0, 6, 7]]; + assert.equal(cutHole(face, { u0: 0, u1: 10, v0: 0, v1: 3 }).length, 1); +}); + +test("a lean-to has no overhang where it meets the taller house", () => { + const b = emptyBuilding(); + const upper = newFloor("o", "Upper", 3); + upper.rooms = [rectRoom("house", 0, 0, 6, 8)]; + const ground = newFloor("g", "Ground", 0); + ground.rooms = [rectRoom("annex", 6, 0, 10, 8)]; + b.floors = [ground, upper]; + const annex: RoofSection = gableSection({ shape: "pent", x0: 6, x1: 10, z0: 0, z1: 8, axis: "z", base: 3, eave_a: 3, eave_b: 3 }); + const ov = sectionOverhang(b, annex, 0.5); + assert.equal(ov.a, 0, "the house stands next to side a"); + assert.equal(ov.b, 0.5); + assert.equal(ov.u0, 0.5); + assert.equal(ov.u1, 0.5); +}); + +test("a section can have a hip at one end and an upright gable at the other", () => { + const g = sectionGeometry(gableSection({ ends: ["hip", "gable"] }), none); + assert.equal(g.faces.length, 3, "two slopes and the hip's triangle"); + assert.equal(g.endProfiles?.[0], null, "no gable wall under the hip"); + assert.ok(g.endProfiles?.[1] && g.endProfiles[1].length === 3); + assert.equal(g.ridges.length, 3, "the ridge and the two hip lines"); +}); + +test("an overhang set by hand for one side replaces the automatic value of that side only", () => { + const b = emptyBuilding(); + b.floors = [newFloor("g", "G", 0)]; + const s = { id: "s", x0: 0, z0: 0, x1: 6, z1: 4, shape: "gable", axis: "x", eave_a: 2.5, eave_b: 2.5, pitch_a: 35, pitch_b: 35, base: 2.5, overhang: null } as RoofSection; + const auto = sectionOverhang(b, s, 0.4); + assert.deepEqual(auto, { a: 0.4, b: 0.4, u0: 0.4, u1: 0.4 }); + const own = sectionOverhang(b, { ...s, overhang_sides: { u1: 1.2, a: 0 } }, 0.4); + assert.deepEqual(own, { a: 0, b: 0.4, u0: 0.4, u1: 1.2 }); +}); diff --git a/frontend/src/roof/geometry.ts b/frontend/src/roof/geometry.ts new file mode 100644 index 0000000..23c9811 --- /dev/null +++ b/frontend/src/roof/geometry.ts @@ -0,0 +1,230 @@ +// The roof planes of a section as polygons in (u, v, height): what the 3D view builds, the editor draws the ridges of, +// and the attic walls end under. + +import { pointInPolygon, polygonArea, type Building, type RoofEnd, type RoofSection, type Vec2 } from "../model.ts"; +import { gradient, mansardParts, sectionFrame, sectionProfile } from "./frame.ts"; + +/** A point of a roof plane: along the ridge (u), across (v), and its height. */ +export type Q = [number, number, number]; + +export interface SectionGeometry { + faces: Q[][]; + /** The outer edge of the roof. */ + rim: Q[]; + ridges: [Q, Q][]; + /** The profile of the gable ends, or null when the ends are hipped. */ + gable: [number, number][] | null; + /** A section with a different end at each end: the profile under each end (start u0, end u1), null under a hip. */ + endProfiles?: [[number, number][] | null, [number, number][] | null]; +} + +/** Overhang per edge: along the ridge at both ends (u0, u1) and across at both sides (a, b). */ +export interface SectionOverhang { + u0: number; + u1: number; + a: number; + b: number; +} + +/** The roof planes of a section, each edge with its own overhang. */ +export function sectionGeometry(s: RoofSection, overhang: SectionOverhang): SectionGeometry { + const frame = sectionFrame(s); + const profile = sectionProfile(s); + const w = frame.w; + const [ovA, ovB] = [Math.max(0, overhang.a), Math.max(0, overhang.b)]; + const U0 = frame.u0 - Math.max(0, overhang.u0); + const U1 = frame.u1 + Math.max(0, overhang.u1); + const onRoof = (u: number, v: number): Q => [u, v, profile.y(v)]; + // the four eave corners (overhang included) + const a0 = onRoof(U0, -ovA); + const a1 = onRoof(U1, -ovA); + const b1 = onRoof(U1, w + ovB); + const b0 = onRoof(U0, w + ovB); + const [gradA, gradB] = [gradient(s.pitch_a), gradient(s.pitch_b)]; + const ridgeAt = (u: number): Q => [u, profile.vr, profile.rh]; + + // a gable, hip or half-hip with its own shape at each end (a hip at one end, an upright gable at the other) + if (s.ends && (s.shape === "gable" || s.shape === "hip" || s.shape === "halfhip")) { + const halfLength = (frame.u1 - frame.u0) / 2; + const run = Math.min(halfLength, Math.min(profile.vr, w - profile.vr) || w / 2); + const eaveLow = Math.min(profile.y(0), profile.y(w)); + const hipY = eaveLow + (profile.rh - eaveLow) * Math.min(0.9, Math.max(0.2, s.halfhip ?? 0.55)); + const hipVA = gradA > 1e-6 ? Math.min(profile.vr, (hipY - s.eave_a) / gradA) : profile.vr; + const hipVB = gradB > 1e-6 ? Math.max(profile.vr, w - (hipY - s.eave_b) / gradB) : profile.vr; + const hipRun = Math.min(halfLength - 0.1, (profile.rh - hipY) / Math.max(0.2, gradA)); + const gableProfile: [number, number][] = [[0, profile.y(0)], [profile.vr, profile.rh], [w, profile.y(w)]]; + const halfProfile: [number, number][] = [[0, profile.y(0)], [hipVA, hipY], [hipVB, hipY], [w, profile.y(w)]]; + // per end: the points above the eave corner on side a and b, the ridge's end, and the profile under it + const end = (kind: RoofEnd, edge: number, inward: number) => { + if (kind === "hip") return { upA: [] as Q[], upB: [] as Q[], ridge: ridgeAt(edge === U0 ? frame.u0 + run * inward : frame.u1 - run * inward), profile: null }; + if (kind === "halfhip") { + const ridge = ridgeAt(edge === U0 ? frame.u0 + hipRun : frame.u1 - hipRun); + return { upA: [[edge, hipVA, hipY] as Q], upB: [[edge, hipVB, hipY] as Q], ridge, profile: halfProfile }; + } + return { upA: [] as Q[], upB: [] as Q[], ridge: ridgeAt(edge), profile: gableProfile }; + }; + const first = end(s.ends[0], U0, 1); + const last = end(s.ends[1], U1, 1); + const faces: Q[][] = [ + [a0, a1, ...last.upA, last.ridge, first.ridge, ...[...first.upA].reverse()], + [first.ridge, last.ridge, ...[...last.upB].reverse(), b1, b0, ...first.upB], + ]; + const ridges: [Q, Q][] = [[first.ridge, last.ridge]]; + for (const [e, a, b] of [[first, a0, b0], [last, a1, b1]] as const) { + if (e.profile === null) { + faces.push(e === first ? [b0, a0, e.ridge] : [a1, b1, e.ridge]); + ridges.push([a, e.ridge], [b, e.ridge]); + } else if (e.upA.length) { + faces.push(e === first ? [e.upB[0], e.upA[0], e.ridge] : [e.upA[0], e.upB[0], e.ridge]); + ridges.push([e.upA[0], e.ridge], [e.upB[0], e.ridge]); + } + } + const rimEnd = (e: typeof first) => (e.profile === null ? [] : e.upA.length ? [e.upA[0], e.upB[0]] : [e.ridge]); + const rim: Q[] = [a0, a1, ...rimEnd(last), b1, b0, ...[...rimEnd(first)].reverse()]; + return { faces, rim, ridges, gable: gableProfile, endProfiles: [first.profile, last.profile] }; + } + + switch (s.shape) { + case "pent": + return { faces: [[a0, a1, b1, b0]], rim: [a0, a1, b1, b0], ridges: [[b1, b0]], gable: [[0, profile.y(0)], [w, profile.y(w)]] }; + + case "hip": + case "pyramid": { + // hips rise from the corners: the ridge is shorter by the run of the slopes at both ends (none left on a pyramid) + const half = (frame.u1 - frame.u0) / 2; + const run = s.shape === "pyramid" ? half : Math.min(half, Math.min(profile.vr, w - profile.vr) || w / 2); + const start = ridgeAt(frame.u0 + run); + const end = ridgeAt(frame.u1 - run); + if (s.shape === "pyramid") { + return { faces: [[a0, a1, start], [a1, b1, start], [b1, b0, start], [b0, a0, start]], rim: [a0, a1, b1, b0], ridges: [[a0, start], [b0, start], [a1, start], [b1, start]], gable: null }; + } + return { + faces: [[a0, a1, end, start], [start, end, b1, b0], [b0, a0, start], [a1, b1, end]], + rim: [a0, a1, b1, b0], + ridges: [[start, end], [a0, start], [b0, start], [a1, end], [b1, end]], + gable: null, + }; + } + + case "halfhip": { + // a gable whose top is hipped: the hip starts at 55 % of the gable's height and slopes like side a + const eaveLow = Math.min(profile.y(0), profile.y(w)); + const hipY = eaveLow + (profile.rh - eaveLow) * Math.min(0.9, Math.max(0.2, s.halfhip ?? 0.55)); + const hipVA = gradA > 1e-6 ? Math.min(profile.vr, (hipY - s.eave_a) / gradA) : profile.vr; + const hipVB = gradB > 1e-6 ? Math.max(profile.vr, w - (hipY - s.eave_b) / gradB) : profile.vr; + const hipRun = Math.min((frame.u1 - frame.u0) / 2 - 0.1, (profile.rh - hipY) / Math.max(0.2, gradA)); + const r0 = ridgeAt(frame.u0 + hipRun); + const r1 = ridgeAt(frame.u1 - hipRun); + const ha0: Q = [U0, hipVA, hipY]; + const hb0: Q = [U0, hipVB, hipY]; + const ha1: Q = [U1, hipVA, hipY]; + const hb1: Q = [U1, hipVB, hipY]; + return { + faces: [[a0, a1, ha1, r1, r0, ha0], [r0, r1, hb1, b1, b0, hb0], [hb0, ha0, r0], [ha1, hb1, r1]], + rim: [a0, a1, ha1, hb1, b1, b0, hb0, ha0], + ridges: [[r0, r1], [ha0, r0], [hb0, r0], [ha1, r1], [hb1, r1]], + gable: [[0, profile.y(0)], [hipVA, hipY], [hipVB, hipY], [w, profile.y(w)]], + }; + } + + case "mansard": { + const m = mansardParts(w, s.eave_a, s.eave_b, gradA, gradB); + const la0: Q = [U0, m.vla, m.yla]; + const la1: Q = [U1, m.vla, m.yla]; + const lb0: Q = [U0, w - m.vlb, m.ylb]; + const lb1: Q = [U1, w - m.vlb, m.ylb]; + const r0: Q = [U0, m.vr, m.rh]; + const r1: Q = [U1, m.vr, m.rh]; + return { + faces: [[a0, a1, la1, la0], [la0, la1, r1, r0], [r0, r1, lb1, lb0], [lb0, lb1, b1, b0]], + rim: [a0, a1, la1, r1, lb1, b1, b0, lb0, r0, la0], + ridges: [[r0, r1], [la0, la1], [lb0, lb1]], + gable: [[0, profile.y(0)], [m.vla, m.yla], [m.vr, m.rh], [w - m.vlb, m.ylb], [w, profile.y(w)]], + }; + } + + default: { + const r0 = ridgeAt(U0); + const r1 = ridgeAt(U1); + return { + faces: [[a0, a1, r1, r0], [r0, r1, b1, b0]], + rim: [a0, a1, r1, b1, b0, r0], + ridges: [[r0, r1]], + gable: [[0, profile.y(0)], [profile.vr, profile.rh], [w, profile.y(w)]], + }; + } + } +} + +/** The height of the roof planes at (u, v): the lowest plane over that point, null outside all planes. */ +export function sectionHeightAt(geometry: SectionGeometry, u: number, v: number): number | null { + let lowest: number | null = null; + for (const face of geometry.faces) { + if (!pointInPolygon([u, v], face.map(([fu, fv]) => [fu, fv] as Vec2))) continue; + // the plane through the first corners that do not lie on a line + const [p0, p1] = face; + const p2 = face.slice(2).find((q) => Math.abs((p1[0] - p0[0]) * (q[1] - p0[1]) - (p1[1] - p0[1]) * (q[0] - p0[0])) > 1e-9); + if (!p2) continue; + // normal = (p1 - p0) x (p2 - p0), with the axes taken as (u, height, v) + const e1 = [p1[0] - p0[0], p1[2] - p0[2], p1[1] - p0[1]]; + const e2 = [p2[0] - p0[0], p2[2] - p0[2], p2[1] - p0[1]]; + const normal = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; + if (Math.abs(normal[1]) < 1e-9) continue; + const y = p0[2] - (normal[0] * (u - p0[0]) + normal[2] * (v - p0[1])) / normal[1]; + lowest = lowest === null ? y : Math.min(lowest, y); + } + return lowest; +} + +/** A polygon in (u, v, y) cut by a half-plane parallel to an axis; heights follow the edges, as the polygon is flat. */ +function clipHalf(polygon: Q[], axis: 0 | 1, limit: number, keepBelow: boolean): Q[] { + const kept = (p: Q) => (keepBelow ? p[axis] <= limit + 1e-9 : p[axis] >= limit - 1e-9); + const result: Q[] = []; + polygon.forEach((p, i) => { + const q = polygon[(i + 1) % polygon.length]; + if (kept(p)) result.push(p); + if (kept(p) !== kept(q)) { + const t = (limit - p[axis]) / (q[axis] - p[axis]); + result.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t]); + } + }); + return result; +} + +export interface Hole { + u0: number; + u1: number; + v0: number; + v1: number; +} + +/** A roof plane with a rectangular hole (a dormer's footprint): up to four pieces around it. */ +export function cutHole(face: Q[], hole: Hole): Q[][] { + const band = clipHalf(clipHalf(face, 0, hole.u0, false), 0, hole.u1, true); + const pieces = [clipHalf(face, 0, hole.u0, true), clipHalf(face, 0, hole.u1, false), clipHalf(band, 1, hole.v0, true), clipHalf(band, 1, hole.v1, false)]; + return pieces.filter((piece) => piece.length >= 3 && Math.abs(polygonArea(piece.map(([u, v]) => [u, v] as Vec2))) > 1e-6); +} + +/** + * Overhang per edge: none where the section meets a taller part of the house (a room just outside that edge whose + * walls rise above the section's wall tops), so a lean-to ends at the wall and does not run into the house. + */ +export function sectionOverhang(building: Building, s: RoofSection, overhang: number): SectionOverhang { + const frame = sectionFrame(s); + const tallRooms = building.floors.flatMap((f) => f.rooms.filter((r) => r.points.length >= 3 && f.elevation + f.height > s.base + 0.05)); + const blockedAt = (spots: Vec2[]) => spots.some((p) => tallRooms.some((r) => pointInPolygon(p, r.points))); + const probe = 0.35; + const alongRidge = [0.15, 0.5, 0.85].map((t) => frame.u0 + (frame.u1 - frame.u0) * t); + const acrossRidge = [0.15, 0.5, 0.85].map((t) => frame.w * t); + const free = (blocked: boolean) => (blocked ? 0 : overhang); + const own = (side: "u0" | "u1" | "a" | "b", automatic: number): number => { + const v = s.overhang_sides?.[side]; + return typeof v === "number" && Number.isFinite(v) ? Math.min(2, Math.max(0, v)) : automatic; + }; + return { + a: own("a", free(blockedAt(alongRidge.map((u) => frame.at(u, -probe))))), + b: own("b", free(blockedAt(alongRidge.map((u) => frame.at(u, frame.w + probe))))), + u0: own("u0", free(blockedAt(acrossRidge.map((v) => frame.at(frame.u0 - probe, v))))), + u1: own("u1", free(blockedAt(acrossRidge.map((v) => frame.at(frame.u1 + probe, v))))), + }; +} diff --git a/frontend/src/roof/polygons.test.ts b/frontend/src/roof/polygons.test.ts new file mode 100644 index 0000000..b88f271 --- /dev/null +++ b/frontend/src/roof/polygons.test.ts @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { polygonArea } from "../model.ts"; +import { near, rectRoom } from "./fixtures.ts"; +import { floorOutline, offsetPolygon, polygonBox, sectionPolygon } from "./polygons.ts"; + +const square = [[0, 0], [4, 0], [4, 4], [0, 4]] as [number, number][]; + +test("a polygon grows by d on every side, whichever way round it runs", () => { + for (const ring of [square, [...square].reverse()]) { + const grown = offsetPolygon(ring, 1); + near(Math.abs(polygonArea(grown)), 36); + near(Math.min(...grown.map((p) => p[0])), -1); + } +}); + +test("no offset, or too few points, gives a copy", () => { + assert.deepEqual(offsetPolygon(square, 0), square); + assert.notEqual(offsetPolygon(square, 0), square); + assert.deepEqual(offsetPolygon([[0, 0], [1, 1]], 3), [[0, 0], [1, 1]]); +}); + +test("shrinking works with a negative offset", () => { + near(Math.abs(polygonArea(offsetPolygon(square, -1))), 4); +}); + +test("an L-shaped polygon keeps its corners (mitres)", () => { + const l: [number, number][] = [[0, 0], [6, 0], [6, 3], [3, 3], [3, 6], [0, 6]]; + const grown = offsetPolygon(l, 0.5); + assert.equal(grown.length, 6); + assert.ok(Math.abs(polygonArea(grown)) > 27 + 0.5 * 24, "larger than the plain strip around it"); +}); + +test("a section's footprint is its rectangle or its free polygon, plus the overhang", () => { + const rect = sectionPolygon({ x0: 4, z0: 3, x1: 0, z1: 0, points: null as never }, 0.5); + assert.deepEqual(rect, [[-0.5, -0.5], [4.5, -0.5], [4.5, 3.5], [-0.5, 3.5]]); + const free = sectionPolygon({ x0: 0, z0: 0, x1: 4, z1: 4, points: square }, 1); + near(Math.abs(polygonArea(free)), 36); +}); + +test("the box of a polygon", () => { + assert.deepEqual(polygonBox([[1, 5], [4, 2], [3, 9]]), { x0: 1, z0: 2, x1: 4, z1: 9 }); +}); + +test("the outline of a floor is its outer wall face loop; collinear splits disappear", () => { + const rooms = [rectRoom("a", 0, 0, 4, 4), rectRoom("b", 4, 0, 8, 4)]; + const outline = floorOutline(rooms, [], 0.3, 0.1)!; + assert.equal(outline.length, 4, "the shared wall adds no corner"); + near(Math.min(...outline.map((p) => p[0])), -0.3, 0.2); + assert.equal(floorOutline([], [], 0.3, 0.1), null); +}); diff --git a/frontend/src/roof/polygons.ts b/frontend/src/roof/polygons.ts new file mode 100644 index 0000000..b43bc23 --- /dev/null +++ b/frontend/src/roof/polygons.ts @@ -0,0 +1,101 @@ +// Outlines for roofs: growing a polygon outwards and finding the outline of a floor's outer walls. + +import { sectionCorners } from "./frame.ts"; +import { generateWalls } from "../geometry/walls.ts"; +import { polygonArea, type FreeWall, type Room, type RoofSection, type Vec2 } from "../model.ts"; + +const unit = ([x, z]: Vec2): Vec2 => { + const length = Math.hypot(x, z) || 1; + return [x / length, z / length]; +}; + +/** The shoelace area: positive for the winding of a plan rectangle listed as (0,0) (w,0) (w,d) (0,d). */ +function windingArea(points: readonly Vec2[]): number { + return points.reduce((sum, p, i) => sum + (p[0] * points[(i + 1) % points.length][1] - points[(i + 1) % points.length][0] * p[1]), 0) / 2; +} + +/** A polygon grown outwards by `d` with mitred corners. Works for simple polygons whichever way round they run. */ +export function offsetPolygon(points: readonly Vec2[], d: number): Vec2[] { + const count = points.length; + if (count < 3 || Math.abs(d) < 1e-9) return points.map(([x, z]) => [x, z]); + // outward is on the right of a counter-clockwise edge (z down the plan) and on the left of a clockwise one + const side = windingArea(points) >= 0 ? 1 : -1; + return points.map((corner, i) => { + const before = points[(i + count - 1) % count]; + const after = points[(i + 1) % count]; + const [ax, az] = unit([corner[0] - before[0], corner[1] - before[1]]); + const [bx, bz] = unit([after[0] - corner[0], after[1] - corner[1]]); + const n1: Vec2 = [az * side, -ax * side]; + const n2: Vec2 = [bz * side, -bx * side]; + // the mitre follows the bisector of both edge normals, stretched so that both edges move by d + const bisector: Vec2 = [n1[0] + n2[0], n1[1] + n2[1]]; + const length = Math.hypot(bisector[0], bisector[1]); + if (length < 1e-6) return [corner[0] + n1[0] * d, corner[1] + n1[1] * d]; + const cosHalf = (bisector[0] * n1[0] + bisector[1] * n1[1]) / length; + const stretch = Math.min(4, 1 / Math.max(0.25, cosHalf)); + return [corner[0] + (bisector[0] / length) * d * stretch, corner[1] + (bisector[1] / length) * d * stretch]; + }); +} + +/** The footprint of a section including its overhang: its free polygon, or its rectangle. */ +export function sectionPolygon(s: Pick, overhang: number): Vec2[] { + if (s.points && s.points.length >= 3) return offsetPolygon(s.points, overhang); + if (s.rotation) return sectionCorners(s, overhang); + const x0 = Math.min(s.x0, s.x1) - overhang; + const x1 = Math.max(s.x0, s.x1) + overhang; + const z0 = Math.min(s.z0, s.z1) - overhang; + const z1 = Math.max(s.z0, s.z1) + overhang; + return [[x0, z0], [x1, z0], [x1, z1], [x0, z1]]; +} + +/** The bounding box of a polygon, in the section's x0 to z1 terms. */ +export function polygonBox(points: readonly Vec2[]): Pick { + const xs = points.map((p) => p[0]); + const zs = points.map((p) => p[1]); + return { x0: Math.min(...xs), z0: Math.min(...zs), x1: Math.max(...xs), z1: Math.max(...zs) }; +} + +type Segment = { a: Vec2; b: Vec2 }; + +/** Walks chains of segments joined at shared end points; returns the largest closed loop. */ +function largestLoop(segments: Segment[]): Vec2[] | null { + const keyOf = ([x, z]: Vec2) => `${Math.round(x * 1000)}:${Math.round(z * 1000)}`; + const touching = new Map(); + for (const seg of segments) for (const end of [seg.a, seg.b]) touching.set(keyOf(end), [...(touching.get(keyOf(end)) ?? []), seg]); + const visited = new Set(); + let best: Vec2[] | null = null; + for (const first of segments) { + if (visited.has(first)) continue; + visited.add(first); + const loop: Vec2[] = [first.a, first.b]; + let at: Vec2 = first.b; + for (;;) { + const next = (touching.get(keyOf(at)) ?? []).find((seg) => !visited.has(seg)); + if (!next) break; + visited.add(next); + at = keyOf(next.a) === keyOf(at) ? next.b : next.a; + if (keyOf(at) === keyOf(loop[0])) break; + loop.push(at); + } + const closed = loop.length >= 3 && keyOf(at) === keyOf(loop[0]); + if (closed && (!best || Math.abs(polygonArea(loop)) > Math.abs(polygonArea(best)))) best = loop; + } + return best; +} + +/** + * The outline of a floor's rooms at the outer faces of its walls: the exterior walls chained into a loop (the + * largest, for a house with a courtyard), grown by the wall thickness. Null without rooms. + */ +export function floorOutline(rooms: readonly Room[], free: readonly FreeWall[], exterior: number, interior: number): Vec2[] | null { + const outer = generateWalls(rooms, { exterior, interior }, free).walls.filter((w) => w.exterior && !w.free); + const loop = outer.length ? largestLoop(outer.map((w) => ({ a: w.a, b: w.b }))) : null; + if (!loop) return null; + // corners in a straight line (a room edge split by its neighbour) go, so the roof keeps clean corners + const corners = loop.filter((q, i) => { + const p = loop[(i + loop.length - 1) % loop.length]; + const r = loop[(i + 1) % loop.length]; + return Math.abs((q[0] - p[0]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[0] - q[0])) > 1e-6; + }); + return corners.length >= 3 ? offsetPolygon(corners, exterior) : null; +} diff --git a/frontend/src/roof/proposal.test.ts b/frontend/src/roof/proposal.test.ts new file mode 100644 index 0000000..245e7f3 --- /dev/null +++ b/frontend/src/roof/proposal.test.ts @@ -0,0 +1,153 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, newFloor, type RoofSection } from "../model.ts"; +import { proposeDormer } from "./dormers.ts"; +import { gableSection, near, rectRoom } from "./fixtures.ts"; +import { ROOF_THICK, headroomLines, roofRider, roofSectionsFromRooms, roofUnderAt, sectionCutsBelow, sectionFloor, wallTopUnder } from "./proposal.ts"; + +const withRoof = (...sections: RoofSection[]) => { + const b = emptyBuilding(); + b.settings.roof.sections = sections; + return b; +}; + +test("a low eave or wall top under the ceiling cuts the walls, an open canopy does not", () => { + assert.equal(sectionCutsBelow({ open: false, base: 3, eave_a: 3, eave_b: 3 }, 3), false); + assert.equal(sectionCutsBelow({ open: false, base: 3, eave_a: 2, eave_b: 3 }, 3), true); + assert.equal(sectionCutsBelow({ open: false, base: 2.5, eave_a: 3, eave_b: 3 }, 3), true); + assert.equal(sectionCutsBelow({ open: true, base: 1, eave_a: 1, eave_b: 1 }, 3), false); +}); + +test("the underside of a roof: slab thickness below the plane, null outside or under a canopy", () => { + const b = withRoof(gableSection()); + near(roofUnderAt(b, 6, 4)!, 7 - ROOF_THICK); + near(roofUnderAt(b, 6, 2)!, 5 - ROOF_THICK); + assert.equal(roofUnderAt(b, 30, 4), null); + assert.equal(roofUnderAt(withRoof(gableSection({ open: true })), 6, 4), null); + assert.equal(roofUnderAt(emptyBuilding(), 1, 1), null); +}); + +test("where roofs overlap, the higher one is the ceiling", () => { + const low = gableSection({ id: "low", pitch_a: 10, pitch_b: 10 }); + const high = gableSection({ id: "high" }); + near(roofUnderAt(withRoof(low, high), 6, 4)!, 7 - ROOF_THICK); +}); + +test("a flat roof in a free shape covers only its polygon", () => { + const flat = gableSection({ shape: "flat", points: [[0, 0], [4, 0], [4, 4], [0, 4]] }); + const b = withRoof(flat); + near(roofUnderAt(b, 2, 2)!, 3 - ROOF_THICK); + assert.equal(roofUnderAt(b, 10, 4), null); +}); + +test("headroom lines run across a sloped section where the roof leaves that height", () => { + const b = withRoof(gableSection()); + const lines = headroomLines(b, 3, 2); + // 45° slopes: 2 m of head room + the slab means 2.14 m in from each eave + assert.equal(lines.length, 2); + for (const [p, q] of lines) near(p[1], q[1]); + const zs = lines.map((l) => l[0][1]).sort((a, c) => a - c); + near(zs[0], 2 + ROOF_THICK); + near(zs[1], 8 - 2 - ROOF_THICK); + assert.deepEqual(headroomLines(withRoof(gableSection({ shape: "flat" }), gableSection({ open: true })), 3, 2), []); +}); + +test("the wall top under a rectangle is the highest floor that has a room under it", () => { + const b = emptyBuilding(); + const g = newFloor("g", "G", 0); + g.rooms = [rectRoom("a", 0, 0, 10, 10)]; + g.height = 2.6; + const o = newFloor("o", "O", 2.7); + o.rooms = [rectRoom("b", 0, 0, 4, 10)]; + o.height = 2.5; + b.floors = [g, o]; + near(wallTopUnder(b, 0, 0, 10, 10)!, 5.2); + near(wallTopUnder(b, 6, 0, 10, 10)!, 2.6); + assert.equal(wallTopUnder(b, 20, 20, 25, 25), null); +}); + +test("an upper floor with a hole in its middle still carries the roof drawn over it", () => { + const b = emptyBuilding(); + const g = newFloor("g", "G", 0); + g.rooms = [rectRoom("a", 0, 0, 10, 10)]; + g.height = 2.6; + const o = newFloor("o", "O", 2.7); + o.rooms = [rectRoom("left", 0, 0, 4, 10), rectRoom("right", 6, 0, 10, 10)]; + o.height = 2.5; + b.floors = [g, o]; + near(wallTopUnder(b, 0, 0, 10, 10)!, 5.2); +}); + +test("a section sits on the highest floor with rooms that starts below its base", () => { + const b = emptyBuilding(); + const g = newFloor("g", "G", 0); + g.rooms = [rectRoom("a", 0, 0, 4, 4)]; + const o = newFloor("o", "O", 3); + o.rooms = [rectRoom("b", 0, 0, 4, 4)]; + const empty = newFloor("e", "E", 6); + b.floors = [empty, o, g]; + assert.equal(sectionFloor(b, { base: 6 })?.id, "o"); + assert.equal(sectionFloor(b, { base: 2 })?.id, "g"); + assert.equal(sectionFloor(b, { base: 0 })?.id, "g", "nothing lower: the lowest floor"); + assert.equal(sectionFloor(emptyBuilding(), { base: 3 }), undefined); +}); + +test("sections proposed from an L-shaped house: one roof per floor part, ridge along the longer side", () => { + const b = emptyBuilding(); + b.settings.wall_exterior = 0.3; + const g = newFloor("g", "G", 0); + g.height = 2.6; + g.rooms = [rectRoom("a", 0, 0, 10, 5), rectRoom("b", 0, 5, 5, 10)]; + b.floors = [g]; + const sections = roofSectionsFromRooms(b); + assert.ok(sections.length >= 2); + assert.ok(sections.every((s) => s.shape === "gable" && s.base === 2.6 && s.eave_a === 2.6)); + assert.equal(sections[0].axis, "x"); + assert.deepEqual(sections.map((s) => s.id), sections.map((_, i) => `roof_${i + 1}`)); + assert.equal(roofSectionsFromRooms(b, (i) => `r${i}`)[0].id, "r0"); +}); + +test("a house with an upper floor over part of it gets a roof up there and one over the rest", () => { + const b = emptyBuilding(); + const g = newFloor("g", "G", 0); + g.height = 2.6; + g.rooms = [rectRoom("a", 0, 0, 5, 6), rectRoom("c", 5, 0, 10, 6)]; + const o = newFloor("o", "O", 2.7); + o.height = 2.5; + o.rooms = [rectRoom("b", 0, 0, 5, 6)]; + b.floors = [g, o]; + const sections = roofSectionsFromRooms(b); + assert.equal(sections.length, 2); + assert.ok(sections[0].base > sections[1].base, "the upper roof first"); + assert.ok(sections[1].x0 >= 5 - 0.5, "the lower roof covers only what the upper floor leaves free"); + assert.deepEqual(roofSectionsFromRooms(emptyBuilding()), []); +}); + +test("pulled apart, a roof moves with the floor that has a loft under its slopes, dormers with their roof", () => { + const b = emptyBuilding(); + const g = newFloor("g", "G", 0); + g.height = 2.6; + g.rooms = [rectRoom("a", 0, 0, 12, 8)]; + const loft = newFloor("l", "Loft", 2.7); + loft.height = 2.2; + loft.rooms = [rectRoom("b", 2, 2, 10, 6)]; + b.floors = [g, loft]; + const roof = gableSection({ id: "main", base: 2.7, eave_a: 2.7, eave_b: 2.7 }); + const dormer = proposeDormer(roof, "a", "dormer", 6); + b.settings.roof.sections = [roof, dormer]; + assert.equal(roofRider(b, g, ["main"]), "l"); + assert.equal(roofRider(b, g, ["dormer"]), "l"); + assert.equal(roofRider(b, g, ["unknown"]), "g"); +}); + +test("a roof section belongs to the floor whose rooms lie under it, not to a higher floor beside it (#42)", () => { + const b = emptyBuilding(); + const garage = { ...newFloor("garage", "Garage", 0), height: 2.5 }; + garage.rooms = [{ id: "gar", name: "Garage", area_id: null, points: [[0.1, 7.12], [7.9, 7.12], [7.9, 10.5], [0.1, 10.5]], floor_material: "concrete" }]; + const eg = { ...newFloor("eg", "EG", 1.32), height: 2.72 }; + eg.rooms = [{ id: "wohnen", name: "Wohnen", area_id: null, points: [[0.14, 0.14], [10.06, 0.14], [10.06, 6.86], [0.14, 6.86]], floor_material: "concrete" }]; + b.floors = [garage, eg]; + assert.equal(sectionFloor(b, { base: 2.5, x0: 0, z0: 7.02, x1: 8, z1: 10.6 })?.id, "garage"); + assert.equal(sectionFloor(b, { base: 4.04, x0: 0, z0: 0, x1: 10.2, z1: 7 })?.id, "eg"); + assert.equal(sectionFloor(b, { base: 2.5 })?.id, "eg", "without its rectangle: the highest floor below, as before"); +}); diff --git a/frontend/src/roof/proposal.ts b/frontend/src/roof/proposal.ts new file mode 100644 index 0000000..b6ce1d9 --- /dev/null +++ b/frontend/src/roof/proposal.ts @@ -0,0 +1,182 @@ +// Roof questions about a whole building: what lies under a roof, where the headroom ends, which floor a roof sits on, +// and a first set of roof sections proposed from the rooms. + +import { pointInPolygon, type Building, type Floor, type Room, type RoofSection, type Vec2 } from "../model.ts"; +import { dormerParent } from "./dormers.ts"; +import { gradient, ridgeHeight, sectionFrame, sectionProfile, sectionUV, unturnedPoint } from "./frame.ts"; +import { sectionGeometry, sectionHeightAt } from "./geometry.ts"; + +/** Anything that carries roof sections: a building, or just its settings in a test. */ +export type RoofHolder = { settings: { roof: { sections?: readonly RoofSection[] | null; overhang?: number } } }; + +/** Thickness of the roof slab: the walls below end this far under the profile. */ +export const ROOF_THICK = 0.14; + +const isFlat = (s: Pick) => s.shape === "flat" || s.shape === "parapet"; + +/** + * Whether a section can reach down below a floor's ceiling: its wall top or one of its eaves lies lower. A low eave + * over a full-height floor cuts the walls too, not only a wall top that was set below the ceiling. + */ +export function sectionCutsBelow(s: Pick, ceiling: number): boolean { + return !s.open && Math.min(s.base, s.eave_a, s.eave_b) < ceiling - 0.05; +} + +/** + * The underside of the roof over a plan point, as an absolute height: the lowest covered section's. Null outside every + * section (open canopies do not count, and a single roof does not either, it rests on the top floor's walls anyway). + */ +export function roofUnderAt(holder: RoofHolder, x: number, z: number): number | null { + const defaultOverhang = Math.max(0, holder.settings.roof.overhang ?? 0); + const eps = 1e-6; + const heights: number[] = []; + for (const s of holder.settings.roof.sections ?? []) { + if (s.open) continue; + const [x0, x1, z0, z1] = [Math.min(s.x0, s.x1), Math.max(s.x0, s.x1), Math.min(s.z0, s.z1), Math.max(s.z0, s.z1)]; + // a turned section: the point in its own rectangle + const [lx, lz] = unturnedPoint(s, x, z); + if (lx < x0 - eps || lx > x1 + eps || lz < z0 - eps || lz > z1 + eps) continue; + // a free-shaped flat roof covers its polygon only + if (s.points && s.points.length >= 3 && !pointInPolygon([x, z], s.points)) continue; + const [u, v] = sectionUV(s, x, z); + // hipped ends and broken slopes: the planes decide, the profile across is the fallback + const own = Math.max(0, s.overhang ?? defaultOverhang); + const fromPlanes = isFlat(s) ? null : sectionHeightAt(sectionGeometry(s, { u0: own, u1: own, a: own, b: own }), u, v); + heights.push((fromPlanes ?? sectionProfile(s).y(v)) - ROOF_THICK); + } + // where sections overlap the higher roof is the ceiling (a dormer or cross gable over the main slope, a low annex under a high roof) + return heights.length ? Math.max(...heights) : null; +} + +/** + * Where a sloped section leaves `headroom` metres over a floor at `level`: lines across the section in plan + * coordinates, one per slope crossing that height. The editor draws them in attic rooms. + */ +export function headroomLines(holder: RoofHolder, level: number, headroom: number): [Vec2, Vec2][] { + const lines: [Vec2, Vec2][] = []; + const target = level + headroom + ROOF_THICK; + for (const s of holder.settings.roof.sections ?? []) { + if (s.open || isFlat(s) || s.shape === "mansard") continue; + const frame = sectionFrame(s); + const profile = sectionProfile(s); + const [gradA, gradB] = [gradient(s.pitch_a), gradient(s.pitch_b)]; + const crossings: number[] = []; + if (gradA > 1e-6) crossings.push((target - s.eave_a) / gradA); + if (s.shape === "gable" && gradB > 1e-6) crossings.push(frame.w - (target - s.eave_b) / gradB); + for (const v of crossings) { + // only where the line really runs under the slope, between eave and ridge + if (v <= 0.01 || v >= frame.w - 0.01) continue; + if (s.shape === "gable" && Math.abs(profile.y(v) - target) > 1e-6) continue; + lines.push([frame.at(frame.u0, v), frame.at(frame.u1, v)]); + } + } + return lines; +} + +/** The highest wall top below a rectangle: the highest floor with a room under any of nine sample points (null = none). */ +export function wallTopUnder(b: Building, x0: number, z0: number, x1: number, z1: number): number | null { + // not the centre alone: an upper floor with a stairwell or hall cut out of the middle would leave the roof on the ground floor + const samples: Vec2[] = []; + for (const fu of [0.2, 0.5, 0.8]) for (const fv of [0.2, 0.5, 0.8]) samples.push([x0 + (x1 - x0) * fu, z0 + (z1 - z0) * fv]); + const tops = b.floors.filter((f) => f.rooms.some((r) => r.points.length >= 3 && samples.some((p) => pointInPolygon(p, r.points)))).map((f) => f.elevation + f.height); + return tops.length ? Math.max(...tops) : null; +} + +/** + * The floor a roof section sits on: the highest floor that starts below the section's base and has rooms under it. A floor + * with no room under the section (a house beside a garage on a slope) does not count; without any, the highest floor below. + */ +export function sectionFloor(b: Building, section: Pick & Partial>): Floor | undefined { + const withRooms = b.floors.filter((f) => f.rooms.length > 0).sort((p, q) => p.elevation - q.elevation); + const below = withRooms.filter((f) => f.elevation < section.base - 0.05); + const { x0, z0, x1, z1 } = section; + if (x0 !== undefined && z0 !== undefined && x1 !== undefined && z1 !== undefined) { + const samples: Vec2[] = []; + for (const fu of [0.2, 0.5, 0.8]) for (const fv of [0.2, 0.5, 0.8]) samples.push([x0 + (x1 - x0) * fu, z0 + (z1 - z0) * fv]); + const under = below.findLast((f) => f.rooms.some((r) => r.points.length >= 3 && samples.some((p) => pointInPolygon(p, r.points)))); + if (under) return under; + } + return below.at(-1) ?? withRooms[0]; +} + +const round3 = (v: number) => Math.round(v * 1000) / 1000; + +/** + * Roof sections proposed from the rooms. Per floor, highest first: the area of its rooms that no higher floor covers is + * cut into as few rectangles as possible, and each gets a gable roof on its walls with the ridge along its longer side. + * A house with an upper floor over part of it so gets a roof up there and one over the single-storey rest. + */ +export function roofSectionsFromRooms(b: Building, makeId: (i: number) => string = (i) => `roof_${i + 1}`): RoofSection[] { + const pitch = b.settings.roof?.pitch ?? 35; + const wall = b.settings.wall_exterior; + const floors = b.floors.filter((f) => f.rooms.some((r) => r.points.length >= 3)).sort((p, q) => q.elevation - p.elevation); + const sections: RoofSection[] = []; + const higherRooms: Room[] = []; + const insideAny = (rooms: Room[], p: Vec2) => rooms.some((r) => pointInPolygon(p, r.points)); + + for (const floor of floors) { + const rooms = floor.rooms.filter((r) => r.points.length >= 3); + const columns = [...new Set(rooms.flatMap((r) => r.points.map((p) => round3(p[0]))))].sort((p, q) => p - q); + const rows = [...new Set(rooms.flatMap((r) => r.points.map((p) => round3(p[1]))))].sort((p, q) => p - q); + // the cells of the grid spanned by all corners that belong to this floor but not to a higher one + const open = rows.slice(0, -1).map((_, j) => columns.slice(0, -1).map((__, i) => { + const middle: Vec2 = [(columns[i] + columns[i + 1]) / 2, (rows[j] + rows[j + 1]) / 2]; + return insideAny(rooms, middle) && !insideAny(higherRooms, middle); + })); + const taken = open.map((row) => row.map(() => false)); + const available = (i: number, j: number) => open[j][i] && !taken[j][i]; + const top = floor.elevation + floor.height; + // greedy rectangles: as wide as possible, then as deep as the whole row allows + for (let j = 0; j < open.length; j++) { + for (let i = 0; i < (open[j]?.length ?? 0); i++) { + if (!available(i, j)) continue; + let right = i; + while (right + 1 < open[j].length && available(right + 1, j)) right++; + let bottom = j; + while (bottom + 1 < open.length && Array.from({ length: right - i + 1 }, (_, k) => available(i + k, bottom + 1)).every(Boolean)) bottom++; + for (let jj = j; jj <= bottom; jj++) for (let ii = i; ii <= right; ii++) taken[jj][ii] = true; + const [x0, x1] = [columns[i] - wall, columns[right + 1] + wall]; + const [z0, z1] = [rows[j] - wall, rows[bottom + 1] + wall]; + if (Math.min(x1 - x0, z1 - z0) < 0.8) continue; + sections.push({ + id: makeId(sections.length), + x0: round3(x0), + z0: round3(z0), + x1: round3(x1), + z1: round3(z1), + shape: "gable", + axis: x1 - x0 >= z1 - z0 ? "x" : "z", + eave_a: round3(top), + eave_b: round3(top), + pitch_a: pitch, + pitch_b: pitch, + base: round3(top), + overhang: null, + }); + } + } + higherRooms.push(...rooms); + } + return sections; +} + +/** + * The floor a roof part moves with when the floors are pulled apart: the highest floor with rooms under its sections + * (between the floor it sits on and its ridge), so a loft under the same slopes counts, not just the floor the roof + * stands on. Dormers move with their main roof, as they sit in its slope. + */ +export function roofRider(b: Building, floor: Floor, sectionIds: readonly string[]): string { + const all = b.settings.roof.sections ?? []; + const mine = all.filter((s) => sectionIds.includes(s.id)).map((s) => dormerParent(all, s) ?? s); + if (mine.length === 0) return floor.id; + const ridge = Math.max(...mine.map(ridgeHeight)); + const hasRoomUnder = (f: Floor) => + f.rooms.some((r) => { + if (r.points.length < 3) return false; + const cx = r.points.reduce((sum, p) => sum + p[0], 0) / r.points.length; + const cz = r.points.reduce((sum, p) => sum + p[1], 0) / r.points.length; + return mine.some((s) => cx >= Math.min(s.x0, s.x1) && cx <= Math.max(s.x0, s.x1) && cz >= Math.min(s.z0, s.z1) && cz <= Math.max(s.z0, s.z1)); + }); + const riders = b.floors.filter((f) => f.elevation >= floor.elevation && f.elevation < ridge - 0.3 && hasRoomUnder(f)).sort((p, q) => q.elevation - p.elevation); + return riders[0]?.id ?? floor.id; +} diff --git a/frontend/src/rooms-only.test.ts b/frontend/src/rooms-only.test.ts new file mode 100644 index 0000000..6e68690 --- /dev/null +++ b/frontend/src/rooms-only.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, newFloor, type Building, type Furniture, type OutdoorArea, type Room } from "./model.ts"; +import { roomsOnly } from "./rooms-only.ts"; + +const room = (id: string, x0: number, x1: number): Room => ({ id, name: id, area_id: null, points: [[x0, 0], [x1, 0], [x1, 4], [x0, 4]], floor_material: "wood" }); +const sofa = (id: string, x: number): Furniture => ({ id, type: "sofa", x, z: 2, rotation: 0, w: 2, d: 1, h: 0.8, variant: null }); + +function house(): Building { + const b = emptyBuilding(); + const g = newFloor("g", "G", 0); + g.rooms = [room("a", 0, 4), room("b", 4, 8), room("c", 8, 12)]; + g.furniture = [sofa("s1", 2), sofa("s2", 6), sofa("s3", 10)]; + g.placements = [{ entity_id: "light.a", x: 1, z: 1, y: null }, { entity_id: "light.c", x: 11, z: 1, y: null }]; + g.openings = [{ id: "o1", room_id: "a", edge: 0, offset: 1, width: 1, type: "door", sill: 0, height: 2, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null } as never, { id: "o2", room_id: "c", edge: 0, offset: 1, width: 1, type: "door", sill: 0, height: 2, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null } as never]; + g.outdoor = [{ id: "lawn", type: "lawn", points: [[0, 5], [3, 5], [3, 8]] } as OutdoorArea]; + const up = newFloor("u", "U", 3); + up.rooms = [room("d", 0, 4)]; + b.floors = [g, up]; + return b; +} + +test("only the chosen rooms stay, with their furniture, devices and openings, and no outdoor areas or roof", () => { + const r = roomsOnly(house(), ["a", "c"]); + assert.equal(r.floors.length, 1, "a floor without a chosen room is dropped"); + const g = r.floors[0]; + assert.deepEqual(g.rooms.map((x) => x.id), ["a", "c"]); + assert.deepEqual(g.furniture.map((f) => f.id), ["s1", "s3"]); + assert.deepEqual(g.placements.map((p) => p.entity_id), ["light.a", "light.c"]); + assert.deepEqual(g.openings.map((o) => o.id), ["o1", "o2"]); + assert.equal(g.outdoor.length, 0); + assert.equal(r.settings.roof.type, "none"); +}); + +test("rooms of several floors keep their floors; unknown ids are ignored; the plan itself is not changed", () => { + const b = house(); + const r = roomsOnly(b, ["b", "d", "nope"]); + assert.deepEqual(r.floors.map((f) => f.id), ["g", "u"]); + assert.equal(r.floors[0].rooms.length, 1); + assert.equal(b.floors[0].rooms.length, 3, "the original keeps all its rooms"); + assert.equal(roomsOnly(b, ["zzz"]).floors.length, 0); +}); diff --git a/frontend/src/rooms-only.ts b/frontend/src/rooms-only.ts new file mode 100644 index 0000000..58b625c --- /dev/null +++ b/frontend/src/rooms-only.ts @@ -0,0 +1,27 @@ +// A card for a few chosen rooms: the plan reduced to those rooms with what stands in them (their furniture, devices, doors and windows), +// no other rooms, no outdoor areas, no roof. + +import { pointInPolygon, type Building, type Floor, type Furniture, type Placement, type Room } from "./model.ts"; + +/** The building as the chosen rooms alone; floors without a chosen room are dropped. The ids that match no room are ignored. */ +export function roomsOnly(building: Building, ids: readonly string[]): Building { + const wanted = new Set(ids); + const floors: Floor[] = []; + for (const floor of building.floors) { + const rooms: Room[] = floor.rooms.filter((r) => wanted.has(r.id)); + if (!rooms.length) continue; + const inside = (x: number, z: number) => rooms.some((r) => r.points.length >= 3 && pointInPolygon([x, z], r.points)); + const keep = new Set(rooms.map((r) => r.id)); + floors.push({ + ...floor, + rooms, + openings: floor.openings.filter((o) => keep.has(o.room_id)), + furniture: floor.furniture.filter((f: Furniture) => inside(f.x, f.z)), + placements: floor.placements.filter((p: Placement) => inside(p.x, p.z)), + walls: (floor.walls ?? []).filter((w) => inside((w.a[0] + w.b[0]) / 2, (w.a[1] + w.b[1]) / 2)), + outdoor: [], + }); + } + const roof = { ...building.settings.roof, type: "none" as const, sections: [], solar: [] }; + return { ...building, floors, settings: { ...building.settings, roof } }; +} diff --git a/frontend/src/search.test.ts b/frontend/src/search.test.ts new file mode 100644 index 0000000..48ca883 --- /dev/null +++ b/frontend/src/search.test.ts @@ -0,0 +1,94 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, newFloor } from "./model.ts"; +import { box, floorWith, hassOf } from "./entities/fixtures.ts"; +import { searchIndex, searchItems } from "./search.ts"; +import type { HomeAssistant } from "./types.ts"; + +function demo() { + const hass = { + language: "en", + states: { + "light.ceiling": { entity_id: "light.ceiling", state: "on", attributes: { friendly_name: "Ceiling light Kitchen" } }, + "sensor.temp": { entity_id: "sensor.temp", state: "21", attributes: { friendly_name: "Temperature" } }, + "sensor.hall": { entity_id: "sensor.hall", state: "5", attributes: { friendly_name: "Hall sensor" } }, + }, + } as unknown as HomeAssistant; + const building = emptyBuilding(); + const ground = newFloor("g", "Ground", 0); + ground.rooms = [ + { id: "k", name: "Kitchen", area_id: null, points: [[0, 0], [4, 0], [4, 3], [0, 3]], floor_material: "wood" }, + { id: "bad", name: "Broken", area_id: null, points: [[0, 0], [1, 1]], floor_material: "wood" }, + ]; + ground.placements = [ + { entity_id: "sensor.temp", x: 1, z: 1, y: null, mount: null }, + { entity_id: "sensor.temp", x: 2, z: 2, y: null, mount: null }, + { entity_id: "sensor.missing", x: 1, z: 1, y: null, mount: null }, + { entity_id: "sensor.hall", x: 9, z: 9, y: null, mount: null }, + ]; + ground.furniture = [{ id: "l", type: "lamp_ceiling", x: 2, z: 2, rotation: 0, w: 0.4, d: 0.4, h: 0.1, variant: null, entity: "light.ceiling", power: null }]; + building.floors = [ground]; + return { hass, building }; +} + +test("the index lists valid rooms and each known entity once", () => { + const { hass, building } = demo(); + const index = searchIndex(hass, building); + assert.deepEqual(index.map((i) => i.name).sort(), ["Ceiling light Kitchen", "Hall sensor", "Kitchen", "Temperature"]); + assert.equal(index.filter((i) => i.entity === "sensor.temp").length, 1); +}); + +test("a device knows the room it stands in, a device outside every room has none", () => { + const { hass, building } = demo(); + const index = searchIndex(hass, building); + assert.equal(index.find((i) => i.entity === "sensor.temp")?.where, "Kitchen"); + assert.equal(index.find((i) => i.entity === "sensor.hall")?.roomId, null); +}); + +test("the place also names the floor once the building has several", () => { + const { hass, building } = demo(); + building.floors.push(newFloor("o", "Upstairs", 3)); + const index = searchIndex(hass, building); + assert.equal(index.find((i) => i.entity === "sensor.temp")?.where, "Kitchen · Ground"); + assert.equal(index.find((i) => i.kind === "room")?.where, "Ground"); +}); + +test("accents and case do not matter, every word has to match", () => { + const { hass, building } = demo(); + building.floors[0].rooms[0].name = "Küche"; + const index = searchIndex(hass, building); + assert.equal(searchItems(index, "KUCHE")[0].kind, "room"); + assert.equal(searchItems(index, "ceiling kuche").length, 1); + assert.equal(searchItems(index, "ceiling garage").length, 0); +}); + +test("best matches first: prefix before contains, rooms before devices, and the limit holds", () => { + const { hass, building } = demo(); + const index = searchIndex(hass, building); + const hits = searchItems(index, "kitchen"); + assert.equal(hits[0].name, "Kitchen"); + assert.equal(hits[1].name, "Ceiling light Kitchen"); + assert.equal(searchItems(index, "e", 2).length, 2); +}); + +test("an empty query finds nothing", () => { + const { hass, building } = demo(); + assert.deepEqual(searchItems(searchIndex(hass, building), " "), []); +}); + +test("notes are found by their text", () => { + const floor = { ...floorWith([box("k", 0, 0, 4, 4)]), notes: [{ id: "n1", x: 1, z: 1, text: "Sicherung 12 ist der Herd" }] }; + const found = searchItems(searchIndex(hassOf([]), { ...emptyBuilding(), floors: [floor] }), "herd"); + assert.equal(found.length, 1); + assert.equal(found[0].kind, "note"); + assert.equal(found[0].roomId, "k"); +}); + +test("a circuit of the fuse box is found and leads to its first room", () => { + const b = { ...emptyBuilding(), floors: [{ ...floorWith([box("k", 0, 0, 4, 4), box("b", 4, 0, 6, 4)]) }] }; + b.settings = { ...b.settings, circuits: [{ id: "c", name: "F12 Küche und Bad", rooms: ["k", "b"] }] }; + const [found] = searchItems(searchIndex(hassOf([]), b), "f12"); + assert.equal(found.kind, "circuit"); + assert.equal(found.roomId, "k"); + assert.equal(found.where, "k, b"); +}); diff --git a/frontend/src/search.ts b/frontend/src/search.ts new file mode 100644 index 0000000..e317fdf --- /dev/null +++ b/frontend/src/search.ts @@ -0,0 +1,108 @@ +// Quick find: rooms, devices and notes of the plan, looked up by name, room, entity id or the note's text. + +import { defaultHeight, entityName, furnitureEntities, kindOf, type DeviceKind } from "./devices.ts"; +import { ceilingAt, centroid, pointInPolygon, type Building, type Floor, type Room } from "./model.ts"; +import type { HomeAssistant } from "./types.ts"; + +export interface SearchItem { + kind: "room" | "device" | "note" | "circuit"; + name: string; + /** Where it is: room (and floor, when the building has several). Empty for a room on a single-floor plan. */ + where: string; + floorId: string; + roomId: string | null; + entity: string | null; + icon: DeviceKind | null; + x: number; + z: number; + /** Height above the floor the camera should aim at. */ + y: number; +} + +/** Lower case without accents, so "kuche" finds "Küche". */ +function fold(text: string): string { + return text.toLocaleLowerCase().normalize("NFD").replace(/\p{M}/gu, ""); +} + +const hasArea = (room: Room) => room.points.length >= 3; + +/** The room of a floor that contains a plan position. */ +function roomContaining(floor: Floor, x: number, z: number): Room | undefined { + return floor.rooms.filter(hasArea).find((room) => pointInPolygon([x, z], room.points)); +} + +function indexFloor(hass: HomeAssistant, floor: Floor, links: ReturnType, multiFloor: boolean): SearchItem[] { + const items: SearchItem[] = []; + + for (const room of floor.rooms.filter(hasArea)) { + const [x, z] = centroid(room.points); + items.push({ kind: "room", name: room.name, where: multiFloor ? floor.name : "", floorId: floor.id, roomId: room.id, entity: null, icon: null, x, z, y: 0 }); + } + + // an entity is listed once per floor, even when it is placed and also linked to a piece of furniture + const listed = new Set(); + const push = (entity: string, x: number, z: number, y: number) => { + if (listed.has(entity) || !(entity in hass.states)) return; + listed.add(entity); + const room = roomContaining(floor, x, z); + const label = [room?.name, multiFloor ? floor.name : undefined].filter((part): part is string => !!part).join(" · "); + items.push({ kind: "device", name: entityName(hass, entity), where: label, floorId: floor.id, roomId: room?.id ?? null, entity, icon: kindOf(entity), x, z, y }); + }; + + for (const p of floor.placements) { + const height = p.y ?? defaultHeight(kindOf(p.entity_id) ?? "sensor", ceilingAt(floor, p.x, p.z), p.mount); + push(p.entity_id, p.x, p.z, height); + } + for (const piece of floor.furniture) { + const link = links.get(piece.id); + const entity = link?.entity ?? link?.power; + if (!entity) continue; + const ceiling = ceilingAt(floor, piece.x, piece.z) - 0.3; + push(entity, piece.x, piece.z, Math.min(ceiling, Math.max(0.5, piece.h))); + } + for (const note of floor.notes ?? []) { + if (!note.text) continue; + const room = roomContaining(floor, note.x, note.z); + const where = [room?.name, multiFloor ? floor.name : undefined].filter((part): part is string => !!part).join(" · "); + items.push({ kind: "note", name: `✎ ${note.text.length > 60 ? `${note.text.slice(0, 59)}…` : note.text}`, where, floorId: floor.id, roomId: room?.id ?? null, entity: null, icon: null, x: note.x, z: note.z, y: 1.3 }); + } + return items; +} + +/** Everything findable: rooms, placed devices, furniture or lamps that are linked to an entity, notes, and the fuse box's circuits. */ +export function searchIndex(hass: HomeAssistant, building: Building): SearchItem[] { + const links = furnitureEntities(hass, building.floors); + const multiFloor = building.floors.length > 1; + const items = building.floors.flatMap((floor) => indexFloor(hass, floor, links, multiFloor)); + // a circuit leads to the first of its rooms; the place lists all of them + for (const c of building.settings.circuits ?? []) { + const rooms = building.floors.flatMap((f) => f.rooms.filter((r) => c.rooms.includes(r.id) && hasArea(r)).map((r) => ({ f, r }))); + if (!rooms.length) continue; + const [{ f, r }] = rooms; + const [x, z] = centroid(r.points); + items.push({ kind: "circuit", name: `🔌 ${c.name}`, where: rooms.map((x) => x.r.name).join(", "), floorId: f.id, roomId: r.id, entity: null, icon: null, x, z, y: 0 }); + } + return items; +} + +/** Lower is better: a name that starts with the query beats one that merely contains it; rooms beat devices. */ +function penalty(item: SearchItem, query: string): number { + const startsWith = fold(item.name).startsWith(query) ? 0 : 2; + return startsWith + (item.kind === "room" ? 0 : 1); +} + +/** Items that contain every word of the query (in name, place or entity id), best first, at most `limit`. */ +export function searchItems(items: SearchItem[], query: string, limit = 8): SearchItem[] { + const words = fold(query).split(/\s+/).filter(Boolean); + if (words.length === 0) return []; + const whole = fold(query.trim()); + return items + .filter((item) => { + const haystack = fold([item.name, item.where, item.entity].filter(Boolean).join(" ")); + return words.every((word) => haystack.includes(word)); + }) + .map((item) => ({ item, cost: penalty(item, whole) })) + .sort((a, b) => a.cost - b.cost || a.item.name.localeCompare(b.item.name)) + .slice(0, limit) + .map((entry) => entry.item); +} diff --git a/frontend/src/solar.ts b/frontend/src/solar.ts new file mode 100644 index 0000000..ecb1052 --- /dev/null +++ b/frontend/src/solar.ts @@ -0,0 +1,12 @@ +// Solar fields on the roof, the walls and in the garden, split into modules in solar/. Plain geometry without three.js, +// so the editor (plan) and the viewer (3D) share it. + +export type { V3 } from "./solar/vec.ts"; +export { GROUND, fieldFace, groundFace, groundFloor, roofFaces, topFloor, wallFaces, type RoofFace } from "./solar/faces.ts"; +export { + LIFT, MODULE_GAP, MODULE_H, MODULE_W, ROOF_WINDOW_H, ROOF_WINDOW_W, + CHIMNEY_SIZE, chimneyAsField, chimneyPlace, chimneySize, clampField, fieldCenter, fieldModules, fieldPlan, fieldSize, moduleSize, rowCounts, rowPitch, windowAsField, windowCorners, + type SolarModule, +} from "./solar/fields.ts"; +export { moveField, proposeChimney, proposeField, proposeGroundField, proposeWallField, proposeWindow, turnGroundField } from "./solar/placing.ts"; +export { bestFace, faceAt, faceCompass, onFace, onField, pointOnFace, rayOnFace } from "./solar/picking.ts"; diff --git a/frontend/src/solar/faces.test.ts b/frontend/src/solar/faces.test.ts new file mode 100644 index 0000000..1dc60d4 --- /dev/null +++ b/frontend/src/solar/faces.test.ts @@ -0,0 +1,129 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, newFloor, type RoofSection } from "../model.ts"; +import { sectionProfile, sectionUV } from "../roof/frame.ts"; +import { GROUND, fieldFace, groundFace, groundFloor, roofFaces, topFloor, wallFaces } from "./faces.ts"; +import { cottage, field, near } from "./fixtures.ts"; + +const section = (patch: Partial = {}): RoofSection => ({ id: "s", x0: 0, z0: 0, x1: 12, z1: 8, shape: "gable", axis: "x", eave_a: 3, eave_b: 3, pitch_a: 40, pitch_b: 40, base: 3, overhang: 0, ...patch }); + +test("no roof, no faces", () => { + assert.deepEqual(roofFaces(cottage({ type: "none", pitch: 35, overhang: 0.4 })), []); + assert.deepEqual(roofFaces(emptyBuilding()), []); +}); + +test("a gable roof has two slopes with the roof's pitch that face away from each other", () => { + const faces = roofFaces(cottage({ type: "gable", pitch: 30, overhang: 0.5 })); + assert.deepEqual(faces.map((f) => f.key), ["main:a", "main:b"]); + for (const f of faces) { + near(f.pitch, 30); + assert.ok(f.n[1] > 0, "normals point up"); + assert.equal(f.flat, false); + } + assert.ok(faces[0].facing[1] * faces[1].facing[1] < 0, "opposite directions across the ridge"); + // each slope reaches the ridge: half of 7 + 2 × 0.8 m of depth, along the slope + near(faces[0].ls, (7 + 2 * 0.8) / 2 / Math.cos((30 * Math.PI) / 180)); +}); + +test("the ridge of the single roof can run along the short side", () => { + const long = roofFaces(cottage({ type: "gable", pitch: 30, overhang: 0.5 }))[0]; + const short = roofFaces(cottage({ type: "gable", pitch: 30, overhang: 0.5, ridge: "short" }))[0]; + assert.ok(long.lu > short.lu); +}); + +test("a flat roof is one level face sitting on the slab", () => { + const [face] = roofFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 })); + assert.equal(face.key, "main:top"); + assert.equal(face.flat, true); + near(face.o[1], 2.6 + 0.25); + near(face.lu, 12 + 2 * 0.8); +}); + +test("a mansard has a lower and an upper face per side, and both lie on the roof as it is drawn", () => { + for (const patch of [{ shape: "mansard" as const, pitch_a: 70, pitch_b: 70 }, { shape: "mansard" as const, pitch_a: 75, pitch_b: 60, eave_b: 2.5, flip: true, overhang: 0.4 }]) { + const s = section(patch); + const faces = roofFaces(cottage({ type: "custom", pitch: 35, overhang: 0, sections: [s] })); + assert.deepEqual(faces.map((f) => f.key), ["s:a", "s:au", "s:b", "s:bu"]); + near(faces[0].pitch, s.pitch_a); + near(faces[1].pitch, 30, 1e-3); + const profile = sectionProfile(s); + for (const f of faces) { + assert.ok(f.n[1] > 0, "normals point up"); + for (const [ku, ks] of [[0.1, 0], [0.5, 0.5], [0.9, 1]]) { + const p = [0, 1, 2].map((i) => f.o[i] + f.eu[i] * f.lu * ku + f.es[i] * f.ls * ks); + const [, v] = sectionUV(s, p[0], p[2]); + near(p[1], profile.y(v), 1e-6); + } + } + } +}); + +test("sections of a custom roof give their own faces: a hip adds two end triangles, a pyramid has four faces in all", () => { + const roof = (s: RoofSection) => { + const b = cottage({ type: "custom", pitch: 35, overhang: 0, sections: [s] }); + return roofFaces(b); + }; + assert.deepEqual(roof(section()).map((f) => f.key), ["s:a", "s:b"]); + assert.deepEqual(roof(section({ shape: "hip" })).map((f) => f.key), ["s:a", "s:b", "s:c", "s:d"]); + assert.equal(roof(section({ shape: "pyramid", x1: 8 })).length, 4); + assert.deepEqual(roof(section({ shape: "pent" })).map((f) => f.key), ["s:a"]); + assert.deepEqual(roof(section({ shape: "flat" })).map((f) => f.key), ["s:top"]); +}); + +test("a hip slope narrows towards the ridge", () => { + const b = cottage({ type: "custom", pitch: 35, overhang: 0, sections: [section({ shape: "hip", x1: 14 })] }); + const slope = roofFaces(b)[0]; + const [low0, low1] = slope.span(0); + const [high0, high1] = slope.span(slope.ls * 0.9); + assert.ok(high1 - high0 < low1 - low0); +}); + +test("walls: outer faces of an outer wall, both faces of a free wall, nothing for short walls", () => { + const b = cottage({ type: "none", pitch: 0, overhang: 0 }); + const faces = wallFaces(b); + assert.equal(faces.length, 4); + assert.ok(faces.every((f) => f.wall?.floorId === "g" && f.pitch === 90 && f.n[1] === 0)); + assert.equal(wallFaces(b, "nothing").length, 0); + // the outer face looks away from the house centre + for (const f of faces) { + const centre: [number, number] = [6, 3.5]; + const middle: [number, number] = [f.o[0] + f.eu[0] * f.lu / 2, f.o[2] + f.eu[2] * f.lu / 2]; + const away = (middle[0] - centre[0]) * f.n[0] + (middle[1] - centre[1]) * f.n[2]; + assert.ok(away > 0, f.key); + } +}); + +test("the top floor is the highest with rooms; the ground floor skips a cellar", () => { + const b = emptyBuilding(); + const cellar = newFloor("c", "Cellar", -2.6); + const ground = newFloor("g", "Ground", 0); + const upper = newFloor("u", "Upper", 2.7); + const empty = newFloor("e", "Empty", 5.4); + const room = { id: "r", name: "R", area_id: null, points: [[0, 0], [4, 0], [4, 4], [0, 4]] as [number, number][], floor_material: "wood" as const }; + [cellar, ground, upper].forEach((f) => (f.rooms = [room])); + b.floors = [cellar, ground, upper, empty]; + assert.equal(topFloor(b)?.id, "u"); + assert.equal(groundFloor(b)?.id, "g"); + assert.equal(topFloor(emptyBuilding()), null); +}); + +test("the ground face is level, unbounded and turns with the field", () => { + const b = cottage({ type: "none", pitch: 0, overhang: 0 }); + const face = groundFace(b, { u: 3, v: 2, rotation: 90, base: null }); + assert.equal(face.unbounded, true); + assert.equal(face.key, GROUND); + near(face.eu[2], 1); + near(face.es[0], -1); + assert.deepEqual(face.n, [0, 1, 0]); + // a field on its own surface height sits there + assert.equal(groundFace(b, { u: 0, v: 0, rotation: null, base: 2.6 }).o[1], 2.6); +}); + +test("a field's face is found by its key; a vanished roof face gives null", () => { + const b = cottage({ type: "gable", pitch: 30, overhang: 0.5 }); + assert.equal(fieldFace(b, field("main:b"))?.key, "main:b"); + assert.equal(fieldFace(b, field("gone:a")), null); + assert.equal(fieldFace(b, field(GROUND))?.unbounded, true); + const wall = wallFaces(b)[0]; + assert.equal(fieldFace(b, field(wall.key))?.key, wall.key); +}); diff --git a/frontend/src/solar/faces.ts b/frontend/src/solar/faces.ts new file mode 100644 index 0000000..9dab76b --- /dev/null +++ b/frontend/src/solar/faces.ts @@ -0,0 +1,268 @@ +// The surfaces solar fields can lie on: the faces of roof sections, a single roof, house walls, and the garden ground. +// +// A face has a local frame. u runs along the eave (0 to lu), s up the slope from the eave (0 to ls, true length); on a +// flat roof s runs across, level. A field's u and v place its lower left corner on the face. + +import { generateWalls } from "../geometry/walls.ts"; +import { outdoorGround, type Building, type Floor, type RoofSection, type SolarField } from "../model.ts"; +import { sectionFrame, sectionOverhang, sectionProfile } from "../roof-sections.ts"; +import { gradient, mansardParts } from "../roof/frame.ts"; +import { cross, DEG, length, normalize, sub, type V3 } from "./vec.ts"; + +/** Thickness of a flat roof slab as the roof draws it. */ +export const FLAT_SLAB = 0.25; + +export interface RoofFace { + /** + * "main:a", "main:b", "main:top" for the single roof; "
    :a", ":b", ":top" for sections; hip ends are ":c" + * (start) and ":d" (end). A mansard's ":a"/":b" are the steep lower slopes, ":au"/":bu" the upper ones above the break. + */ + key: string; + /** The section the face belongs to (null: the single roof). */ + section: string | null; + side: "a" | "b" | "c" | "d" | "top"; + flat: boolean; + /** The eave corner (heights above the ground), unit vectors along the eave and up the slope, and the normal. */ + o: V3; + eu: V3; + es: V3; + n: V3; + lu: number; + ls: number; + /** Slope in degrees (0 on a flat roof). */ + pitch: number; + /** The usable range along the eave at a distance up the slope (hip roofs narrow towards the ridge). */ + span(s: number): [number, number]; + /** The plan direction the face looks to (down the slope); for a flat roof the direction of +s. */ + facing: [number, number]; + /** The garden ground: no edges, a field goes where it is put. */ + unbounded?: boolean; + /** A house wall: upright, on this floor. Modules hang flat on the facade. */ + wall?: { floorId: string }; +} + +/** A face made of a flat slab, as seen from above. */ +function flatFace(id: string, section: string | null, x0: number, z0: number, x1: number, z1: number, y: number): RoofFace { + // u along the longer side, s across + const alongX = x1 - x0 >= z1 - z0; + const lu = alongX ? x1 - x0 : z1 - z0; + return { + key: `${id}:top`, + section, + side: "top", + flat: true, + o: [x0, y, z0], + eu: alongX ? [1, 0, 0] : [0, 0, 1], + es: alongX ? [0, 0, 1] : [1, 0, 0], + n: [0, 1, 0], + lu, + ls: alongX ? z1 - z0 : x1 - x0, + pitch: 0, + span: () => [0, lu], + facing: alongX ? [0, 1] : [1, 0], + }; +} + +/** The upward normal of the plane spanned by two edge directions. */ +function upwardNormal(eu: V3, es: V3): V3 { + const n = normalize(cross(eu, es)); + return n[1] < 0 ? [-n[0], -n[1], -n[2]] : n; +} + +/** The plan direction a slope looks to, from its up-the-slope direction. */ +const lookingDown = (es: V3): [number, number] => { + const down = normalize([-es[0], 0, -es[2]]); + return [down[0], down[2]]; +}; + +function slopeFace(key: string, section: string | null, side: "a" | "b", o: V3, eaveEnd: V3, ridge: V3, pitch: number, span: (s: number) => [number, number]): RoofFace { + const eu = normalize(sub(eaveEnd, o)); + const es = normalize(sub(ridge, o)); + return { key, section, side, flat: false, o, eu, es, n: upwardNormal(eu, es), lu: length(sub(eaveEnd, o)), ls: length(sub(ridge, o)), pitch, span, facing: lookingDown(es) }; +} + +/** + * A triangular face (a hip end): the eave from `o` to `eaveEnd`, rising to `apex`. The slope frame is the plane's own, + * with s at a right angle to the eave, and the usable span narrows linearly towards the apex. + */ +function triangleFace(key: string, section: string, side: "c" | "d", o: V3, eaveEnd: V3, apex: V3): RoofFace | null { + const lu = length(sub(eaveEnd, o)); + if (lu < 0.3) return null; + const eu = normalize(sub(eaveEnd, o)); + const toApex = sub(apex, o); + const along = toApex[0] * eu[0] + toApex[1] * eu[1] + toApex[2] * eu[2]; + const rise: V3 = [toApex[0] - eu[0] * along, toApex[1] - eu[1] * along, toApex[2] - eu[2] * along]; + const ls = length(rise); + if (ls < 0.3) return null; + const es = normalize(rise); + const span = (s: number): [number, number] => { + const k = Math.min(1, Math.max(0, s / ls)); + return [along * k, lu - (lu - along) * k]; + }; + return { key, section, side, flat: false, o, eu, es, n: upwardNormal(eu, es), lu, ls, pitch: Math.atan2(es[1], Math.hypot(es[0], es[2])) / DEG, span, facing: lookingDown(es) }; +} + +type Overhang = { u0: number; u1: number; a: number; b: number }; + +/** The faces of one section as the roof draws them, with overhang at the eaves and gable ends (none where a taller part of the house stands). */ +function sectionFaces(s: RoofSection, overhang: Overhang): RoofFace[] { + const frame = sectionFrame(s); + const profile = sectionProfile(s); + const at = (u: number, v: number, y: number): V3 => { + const [x, z] = frame.at(u, v); + return [x, y, z]; + }; + const [ovA, ovB] = [Math.max(0, overhang.a), Math.max(0, overhang.b)]; + const U0 = frame.u0 - Math.max(0, overhang.u0); + const U1 = frame.u1 + Math.max(0, overhang.u1); + const width = U1 - U0; + const yA = profile.y(-ovA); + const yB = profile.y(frame.w + ovB); + + if (s.shape === "flat" || s.shape === "parapet") { + const [p, q] = [frame.at(U0, -ovA), frame.at(U1, frame.w + ovB)]; + return [flatFace(s.id, s.id, Math.min(p[0], q[0]), Math.min(p[1], q[1]), Math.max(p[0], q[0]), Math.max(p[1], q[1]), s.eave_a + FLAT_SLAB)]; + } + if (s.shape === "pent") return [slopeFace(`${s.id}:a`, s.id, "a", at(U0, -ovA, yA), at(U1, -ovA, yA), at(U0, frame.w + ovB, yB), s.pitch_a, () => [0, width])]; + + if (s.shape === "mansard") return mansardFaces(s, frame, U0, U1, ovA, ovB); + + // a pyramid is a hip whose ridge has no length; a half-hip places its modules like a gable + const isHip = s.shape === "hip" || s.shape === "pyramid"; + const half = (frame.u1 - frame.u0) / 2; + const run = s.shape === "pyramid" ? half : isHip ? Math.min(half, Math.min(profile.vr, frame.w - profile.vr) || frame.w / 2) : 0; + // a hip slope narrows from the full eave (overhang included) to the ridge, which starts `run` in from the walls + const inset0 = isHip ? frame.u0 + run - U0 : 0; + const inset1 = isHip ? U1 - (frame.u1 - run) : 0; + const faces: RoofFace[] = []; + if (profile.vr > 0.3) { + const slope = Math.hypot(profile.vr + ovA, profile.rh - yA); + faces.push(slopeFace(`${s.id}:a`, s.id, "a", at(U0, -ovA, yA), at(U1, -ovA, yA), at(U0, profile.vr, profile.rh), s.pitch_a, (t) => [inset0 * (t / slope), width - inset1 * (t / slope)])); + } + if (frame.w - profile.vr > 0.3) { + const slope = Math.hypot(frame.w + ovB - profile.vr, profile.rh - yB); + // side b: the eave at v = w + overhang, running the other way so the face looks outwards + faces.push(slopeFace(`${s.id}:b`, s.id, "b", at(U1, frame.w + ovB, yB), at(U0, frame.w + ovB, yB), at(U1, profile.vr, profile.rh), s.pitch_b, (t) => [inset1 * (t / slope), width - inset0 * (t / slope)])); + } + if (isHip) { + const startEnd = triangleFace(`${s.id}:c`, s.id, "c", at(U0, frame.w + ovB, yB), at(U0, -ovA, yA), at(frame.u0 + run, profile.vr, profile.rh)); + const finishEnd = triangleFace(`${s.id}:d`, s.id, "d", at(U1, -ovA, yA), at(U1, frame.w + ovB, yB), at(frame.u1 - run, profile.vr, profile.rh)); + faces.push(...[startEnd, finishEnd].filter((f): f is RoofFace => f !== null)); + } + return faces; +} + +/** + * A mansard breaks each side at a kink: the steep lower slope from the eave to the break, then the flatter upper slope + * to the ridge. One plane from eave to ridge would cut under the break, so each part is a face of its own. + */ +function mansardFaces(s: RoofSection, frame: ReturnType, U0: number, U1: number, ovA: number, ovB: number): RoofFace[] { + const m = mansardParts(frame.w, s.eave_a, s.eave_b, gradient(s.pitch_a), gradient(s.pitch_b)); + const at = (u: number, v: number): V3 => { + const [x, z] = frame.at(u, v); + return [x, m.y(v), z]; + }; + const width = U1 - U0; + const span = (): [number, number] => [0, width]; + const upperPitch = (rise: number, run: number) => Math.atan2(rise, run) / DEG; + const faces: RoofFace[] = []; + const [wb, bb] = [frame.w + ovB, frame.w - m.vlb]; + if (m.vla + ovA > 0.3) faces.push(slopeFace(`${s.id}:a`, s.id, "a", at(U0, -ovA), at(U1, -ovA), at(U0, m.vla), s.pitch_a, span)); + if (m.vr - m.vla > 0.3) faces.push(slopeFace(`${s.id}:au`, s.id, "a", at(U0, m.vla), at(U1, m.vla), at(U0, m.vr), upperPitch(m.rh - m.yla, m.vr - m.vla), span)); + // side b: eaves at v = w + overhang, running the other way so the faces look outwards + if (m.vlb + ovB > 0.3) faces.push(slopeFace(`${s.id}:b`, s.id, "b", at(U1, wb), at(U0, wb), at(U1, bb), s.pitch_b, span)); + if (bb - m.vr > 0.3) faces.push(slopeFace(`${s.id}:bu`, s.id, "b", at(U1, bb), at(U0, bb), at(U1, m.vr), upperPitch(m.rh - m.ylb, bb - m.vr), span)); + return faces; +} + +/** The floor the single roof sits on: the highest with rooms. */ +export function topFloor(b: Building): Floor | null { + const withRooms = b.floors.filter((f) => f.rooms.some((r) => r.points.length >= 3)); + return withRooms.sort((p, q) => q.elevation - p.elevation)[0] ?? null; +} + +/** Every roof face modules can lie on. */ +export function roofFaces(b: Building): RoofFace[] { + const roof = b.settings.roof; + if (!roof || roof.type === "none") return []; + if (roof.type === "custom") return (roof.sections ?? []).flatMap((s) => sectionFaces(s, sectionOverhang(b, s, s.overhang ?? roof.overhang))); + const floor = topFloor(b); + if (!floor) return []; + const xs = floor.rooms.flatMap((r) => r.points.map((p) => p[0])); + const zs = floor.rooms.flatMap((r) => r.points.map((p) => p[1])); + const margin = b.settings.wall_exterior + roof.overhang; + const [x0, x1] = [Math.min(...xs) - margin, Math.max(...xs) + margin]; + const [z0, z1] = [Math.min(...zs) - margin, Math.max(...zs) + margin]; + const top = floor.elevation + floor.height; + if (roof.type === "flat") return [flatFace("main", null, x0, z0, x1, z1, top + FLAT_SLAB)]; + // a gable, as the roof builds it: the ridge along the longer side (or the shorter one) + const longerAlongX = x1 - x0 >= z1 - z0; + const alongX = roof.ridge === "short" ? !longerAlongX : longerAlongX; + const halfWidth = (alongX ? z1 - z0 : x1 - x0) / 2; + const rise = halfWidth * Math.tan(roof.pitch * DEG); + const point = (u: number, v: number, y: number): V3 => (alongX ? [u, top + y, (z0 + z1) / 2 + v] : [(x0 + x1) / 2 + v, top + y, u]); + const [u0, u1] = alongX ? [x0, x1] : [z0, z1]; + const span = () => [0, u1 - u0] as [number, number]; + return [ + slopeFace("main:a", null, "a", point(u0, -halfWidth, 0), point(u1, -halfWidth, 0), point(u0, 0, rise), roof.pitch, span), + slopeFace("main:b", null, "b", point(u0, halfWidth, 0), point(u1, halfWidth, 0), point(u0, 0, rise), roof.pitch, span), + ]; +} + +/** The outer faces of the house walls per floor: modules can hang on a facade or balcony. */ +export function wallFaces(b: Building, floorId?: string): RoofFace[] { + const faces: RoofFace[] = []; + for (const floor of b.floors.filter((f) => !floorId || f.id === floorId)) { + const { walls } = generateWalls(floor.rooms, { exterior: b.settings.wall_exterior, interior: b.settings.wall_interior }, floor.walls ?? []); + for (const wall of walls) { + // outer walls: the outer face; free-standing walls (garden wall, fence wall): both faces + if (!wall.exterior && !wall.free) continue; + const [dx, dz] = [wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]; + const l = Math.hypot(dx, dz); + if (l < 1.2) continue; + // outer walls have their room on the left, so the outer face is on the right + const [nx, nz] = [dz / l, -dx / l]; + // a sloping wall offers its lower end + const height = Math.min(floor.height, wall.height ?? floor.height, wall.heightEnd ?? Infinity); + const addFace = (key: string, o: V3, eu: V3, n: V3) => + faces.push({ key, section: null, side: "top", flat: false, o, eu, es: [0, 1, 0], n, lu: l, ls: height, pitch: 90, span: () => [0, l], facing: [n[0], n[2]], wall: { floorId: floor.id } }); + addFace(`wall:${floor.id}:${wall.id}`, [wall.a[0] + nx * wall.right, floor.elevation, wall.a[1] + nz * wall.right], [dx / l, 0, dz / l], [nx, 0, nz]); + // the back of a free wall runs the other way, so its modules face outwards too + if (wall.free) addFace(`wall:${floor.id}:${wall.id}:back`, [wall.b[0] - nx * wall.left, floor.elevation, wall.b[1] - nz * wall.left], [-dx / l, 0, -dz / l], [-nx, 0, -nz]); + } + } + return faces; +} + +/** The face key of fields standing in the garden. */ +export const GROUND = "ground"; + +/** The floor whose garden ground-mounted fields stand in: the lowest with rooms at ground level (a cellar is passed over), else the lowest with rooms. */ +export function groundFloor(b: Building): Floor | null { + const withRooms = b.floors.filter((f) => f.rooms.some((r) => r.points.length >= 3)).sort((p, q) => p.elevation - q.elevation); + return withRooms.find((f) => f.elevation > -0.5) ?? withRooms[0] ?? b.floors[0] ?? null; +} + +/** + * The ground under a garden field: level, turned by the field's rotation. u and v are plan coordinates along the turned + * axes, so the corner of a field lies at u * (cos r, sin r) + v * (-sin r, cos r). + */ +export function groundFace(b: Building, f: Pick): RoofFace { + const r = (f.rotation ?? 0) * DEG; + const eu: V3 = [Math.cos(r), 0, Math.sin(r)]; + const es: V3 = [-Math.sin(r), 0, Math.cos(r)]; + const floor = groundFloor(b); + const x = eu[0] * f.u + es[0] * f.v; + const z = eu[2] * f.u + es[2] * f.v; + // on a surface of its own height (a flat garage roof), else on the ground (a terrace raises it) + const y = floor ? floor.elevation + (f.base != null ? f.base : outdoorGround(floor, x, z)) : (f.base ?? 0); + return { key: GROUND, section: null, side: "top", flat: true, o: [0, y, 0], eu, es, n: [0, 1, 0], lu: 1e4, ls: 1e4, pitch: 0, span: () => [-1e4, 1e4], facing: [es[0], es[2]], unbounded: true }; +} + +/** The face a field lies on: a roof face, a wall, or the ground in the garden. Null when its roof face is gone. */ +export function fieldFace(b: Building, f: SolarField, faces: readonly RoofFace[] = roofFaces(b)): RoofFace | null { + if (f.face === GROUND) return groundFace(b, f); + if (f.face.startsWith("wall:")) return wallFaces(b, f.face.split(":")[1]).find((x) => x.key === f.face) ?? null; + return faces.find((x) => x.key === f.face) ?? null; +} + diff --git a/frontend/src/solar/fields.test.ts b/frontend/src/solar/fields.test.ts new file mode 100644 index 0000000..9526706 --- /dev/null +++ b/frontend/src/solar/fields.test.ts @@ -0,0 +1,165 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { roofFaces, wallFaces, type RoofFace } from "./faces.ts"; +import { MODULE_GAP, MODULE_H, MODULE_W, LIFT, clampField, fieldCenter, fieldModules, fieldPlan, fieldSize, moduleSize, rowCounts, rowPitch, windowAsField, windowCorners } from "./fields.ts"; +import { cottage, field, near } from "./fixtures.ts"; +import { GROUND, groundFace } from "./faces.ts"; + +const slope = (): RoofFace => roofFaces(cottage({ type: "gable", pitch: 35, overhang: 0.5 }))[1]; +const flat = (): RoofFace => roofFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 }))[0]; + +test("modules are portrait by default and turn when landscape, own sizes win", () => { + assert.deepEqual(moduleSize({ portrait: true }), [MODULE_W, MODULE_H]); + assert.deepEqual(moduleSize({ portrait: false }), [MODULE_H, MODULE_W]); + assert.deepEqual(moduleSize({ portrait: true, module_w: 1, module_h: 2 }), [1, 2]); +}); + +test("rows: the same count in each, or the layout's own lengths, kept within limits", () => { + assert.deepEqual(rowCounts({ rows: 3, cols: 2 }), [2, 2, 2]); + assert.deepEqual(rowCounts({ rows: 0, cols: 0 }), [1]); + assert.deepEqual(rowCounts({ rows: 9, cols: 9, layout: [4, 4, 3, 99, -2] }), [4, 4, 3, 60, 0]); +}); + +test("on a slope the rows follow each other module by module; on flat ground they leave space against shading", () => { + near(rowPitch(slope(), field("x")), MODULE_H + MODULE_GAP); + assert.ok(rowPitch(flat(), field("x", { tilt: 20 })) > rowPitch(slope(), field("x")) * 0.9); + assert.ok(rowPitch(flat(), field("x", { tilt: 30 })) > rowPitch(flat(), field("x", { tilt: 10 }))); +}); + +test("a field's size grows with its longest row and its row count", () => { + const f = slope(); + const [w1, d1] = fieldSize(f, field("x", { rows: 1, cols: 2 })); + near(w1, 2 * MODULE_W + MODULE_GAP); + near(d1, MODULE_H); + const [w2, d2] = fieldSize(f, field("x", { rows: 3, cols: 2, layout: [2, 4, 3] })); + near(w2, 4 * MODULE_W + 3 * MODULE_GAP); + assert.ok(d2 > d1 * 2.5); +}); + +test("modules lie 7 cm above the slope", () => { + const face = slope(); + const [first] = fieldModules(face, field(face.key)); + for (const corner of first.corners) { + const q = [corner[0] - face.o[0], corner[1] - face.o[1], corner[2] - face.o[2]]; + const above = q[0] * face.n[0] + q[1] * face.n[1] + q[2] * face.n[2]; + near(above, LIFT, 1e-9); + } + assert.deepEqual(first.posts, []); +}); + +test("a module that would leave the face is left out; switched-off cells only show when asked for", () => { + const face = slope(); + assert.equal(fieldModules(face, field(face.key, { u: face.lu - MODULE_W, cols: 2 })).length, 1); + const switched = field(face.key, { cols: 3, skip: ["0:1"] }); + assert.equal(fieldModules(face, switched).length, 2); + const all = fieldModules(face, switched, true); + assert.equal(all.length, 3); + assert.deepEqual(all.filter((m) => m.skipped).map((m) => m.cell), ["0:1"]); +}); + +test("shorter rows sit left, centred or right under the longest one", () => { + const face = slope(); + const first = (align: "left" | "center" | "right") => fieldModules(face, field(face.key, { layout: [4, 2], align, u: 0 })) + .filter((m) => m.cell.startsWith("1:"))[0].corners[0]; + const [left, centre, right] = [first("left"), first("center"), first("right")]; + const delta = (a: number[], b: number[]) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); + near(delta(left, centre), MODULE_W + MODULE_GAP, 1e-6); + near(delta(centre, right), MODULE_W + MODULE_GAP, 1e-6); +}); + +test("on flat ground the modules lean up on a frame with posts", () => { + const face = groundFace(cottage({ type: "none", pitch: 0, overhang: 0 }), { u: 20, v: 0, rotation: null, base: null }); + const [m] = fieldModules(face, field(GROUND, { tilt: 30, u: 20, v: 0 })); + assert.ok(m.corners[2][1] > m.corners[0][1] + 0.5, "the upper edge is higher"); + assert.ok(m.corners[2][2] > m.corners[0][2], "and lies towards +z"); + assert.equal(m.posts.length, 4); + const [flipped] = fieldModules(face, field(GROUND, { tilt: 30, u: 20, v: 0, flip: true })); + assert.ok(flipped.corners[2][1] > flipped.corners[0][1] + 0.5, "flipped: still the upper edge is higher"); + assert.ok(flipped.corners[2][2] < flipped.corners[0][2], "but it lies towards -z"); +}); + +test("on a wall the modules hang flat, or stand off when tilted", () => { + const wall = wallFaces(cottage({ type: "none", pitch: 0, overhang: 0 }))[0]; + const [flatOne] = fieldModules(wall, field(wall.key, { tilt: 0 })); + assert.equal(flatOne.posts.length, 0); + const [tilted] = fieldModules(wall, field(wall.key, { tilt: 30 })); + assert.equal(tilted.posts.length, 2); +}); + +test("a field is kept on the face, rounded down to centimetres, and the ground has no limits", () => { + const face = slope(); + const [w, d] = fieldSize(face, field(face.key)); + const kept = clampField(face, field(face.key, { u: 999, v: 999 })); + near(kept.u, Math.floor((face.lu - w) * 100) / 100, 1e-9); + near(kept.v, Math.floor((face.ls - d) * 100) / 100, 1e-9); + assert.deepEqual(clampField(face, field(face.key, { u: -5, v: -5 })), { u: 0, v: 0 }); + const ground = groundFace(cottage({ type: "none", pitch: 0, overhang: 0 }), { u: 0, v: 0, rotation: null, base: null }); + assert.deepEqual(clampField(ground, field(GROUND, { u: 500, v: -500 })), { u: 500, v: -500 }); +}); + +test("the plan shows each module's corners as plan points; the centre is the middle of the field", () => { + const face = slope(); + const f = field(face.key, { cols: 2 }); + const plan = fieldPlan(face, f); + assert.equal(plan.length, 2); + assert.ok(plan.every((corners) => corners.length === 4 && corners.every((p) => p.length === 2))); + const centre = fieldCenter(face, f); + const xs = plan.flat().map((p) => p[0]); + const zs = plan.flat().map((p) => p[1]); + assert.ok(centre[0] >= Math.min(...xs) - 0.01 && centre[0] <= Math.max(...xs) + 0.01); + assert.ok(centre[1] >= Math.min(...zs) - 0.01 && centre[1] <= Math.max(...zs) + 0.01); +}); + +test("a roof window is a field of one module of its size, sunk into the roof", () => { + const face = slope(); + const win = { id: "w", face: face.key, u: 1, v: 1, w: null, h: null, cover: null, contact: null, tilt: null }; + assert.deepEqual(moduleSize(windowAsField(win)), [0.78, 1.18]); + assert.deepEqual(moduleSize(windowAsField({ ...win, w: 1, h: 2 })), [1, 2]); + const corners = windowCorners(face, win)!; + const above = (c: number[]) => (c[0] - face.o[0]) * face.n[0] + (c[1] - face.o[1]) * face.n[1] + (c[2] - face.o[2]) * face.n[2]; + near(above(corners[0]), LIFT - 0.05, 1e-9); + assert.equal(windowCorners(face, { ...win, u: 999 }), null); +}); + +test("a field on a flat roof turns about its middle, the modules swing with it", () => { + const face = flat(); + const sized = field("x", { rows: 1, cols: 4 }); + const [w, d] = fieldSize(face, sized); + const base = { ...sized, u: face.lu / 2 - w / 2, v: face.ls / 2 - d / 2 }; + const centre = fieldCenter(face, base); + const plan = (f: typeof base) => fieldPlan(face, f).flat(); + const spread = (points: number[][], axis: 0 | 1) => Math.max(...points.map((p) => p[axis])) - Math.min(...points.map((p) => p[axis])); + const straight = plan(base); + const turned = plan({ ...base, rotation: 90 }); + assert.equal(turned.length, straight.length); + // a row that ran along the eave now runs across it: the extents swap + near(spread(turned, 0), spread(straight, 1), 1e-6); + near(spread(turned, 1), spread(straight, 0), 1e-6); + const middle = (points: number[][]) => [0, 1].map((i) => (Math.max(...points.map((p) => p[i])) + Math.min(...points.map((p) => p[i]))) / 2); + near(middle(turned)[0], centre[0], 1e-6); + near(middle(turned)[1], centre[1], 1e-6); +}); + +test("a turned field is kept on its face by its middle, and a full turn changes nothing", () => { + const face = flat(); + const base = field("x", { rows: 1, cols: 3, u: 0, v: 0 }); + const full = field("x", { rows: 1, cols: 3, u: 0, v: 0, rotation: 360 }); + fieldPlan(face, full).flat(2).forEach((v, i) => near(v, fieldPlan(face, base).flat(2)[i], 1e-9)); + const turned = field("x", { rows: 1, cols: 3, u: 0, v: 0, rotation: 90 }); + const moved = { ...turned, ...clampField(face, turned) }; + assert.equal(fieldModules(face, moved).length, 3, "all modules are on the roof after the clamp"); + // garden fields and wall fields do not use the field turn + const wall = wallFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 }))[0]; + assert.deepEqual(fieldPlan(wall, field("x", { rotation: 90 })), fieldPlan(wall, field("x"))); +}); + +test("east-west racks turn every second row and stand the pairs close; a rack on a slope lifts the upper edge", () => { + const face = flat(); + const ew = fieldModules(face, field("x", { rows: 2, cols: 1, tilt: 10, rack: "ew" })); + // which way a module leans: from its low edge to its high edge, along the face + const lean = (m: (typeof ew)[number]) => [0, 1, 2].reduce((s, i) => s + (m.corners[2][i] - m.corners[0][i]) * face.es[i], 0); + assert.ok(lean(ew[0]) > 0 && lean(ew[1]) < 0, "the second row leans the other way"); + assert.ok(rowPitch(flat(), field("x", { tilt: 10, rack: "ew" })) < rowPitch(flat(), field("x", { tilt: 10 }))); + const racked = fieldModules(slope(), field("x", { rows: 1, cols: 1, tilt: 20 }))[0]; + assert.equal(racked.posts.length, 2, "brackets under the raised edge"); +}); diff --git a/frontend/src/solar/fields.ts b/frontend/src/solar/fields.ts new file mode 100644 index 0000000..aec607e --- /dev/null +++ b/frontend/src/solar/fields.ts @@ -0,0 +1,231 @@ +// The modules of a solar field on its face: size, layout, tilt, and the 3D corners of every module. + +import type { ChimneyShape, RoofChimney, RoofWindow, SolarField, Vec2 } from "../model.ts"; +import type { RoofFace } from "./faces.ts"; +import { DEG, type V3 } from "./vec.ts"; + +/** A common 400 W module: width and height in portrait (m), and the gap between modules. */ +export const MODULE_W = 1.13; +export const MODULE_H = 1.72; +export const MODULE_GAP = 0.025; +/** The modules ride this high above the roof surface on mounting rails. */ +export const LIFT = 0.07; + +/** One module: its four corners (lower left, lower right, upper right, upper left) and, on a flat roof, its stand. */ +export interface SolarModule { + corners: [V3, V3, V3, V3]; + /** Flat roofs: the feet of the raised upper edge (posts from the roof up to the module). */ + posts: [V3, V3][]; + /** The cell in the field ("row:column") and whether it is switched off (only listed when asked for). */ + cell: string; + skipped: boolean; +} + +/** The size of a module along the eave and up the slope. */ +export function moduleSize(f: Pick): [number, number] { + const w = f.module_w || MODULE_W; + const h = f.module_h || MODULE_H; + return f.portrait === false ? [h, w] : [w, h]; +} + +/** How many modules each row has: the layout (rows of their own length) or `cols` in every row. */ +export function rowCounts(f: Pick): number[] { + if (f.layout?.length) return f.layout.map((n) => Math.max(0, Math.min(60, Math.round(n)))); + return Array.from({ length: Math.max(1, f.rows) }, () => Math.max(1, f.cols)); +} + +/** The tilt of a field's modules in radians: frames on flat ground (15° by default), standing off a wall (0 by default). */ +function tiltOf(face: RoofFace, f: Pick): number { + if (face.flat) return Math.min(45, Math.max(0, f.tilt ?? 15)) * DEG; + if (face.wall) return Math.min(90, Math.max(0, f.tilt ?? 0)) * DEG; + // a pitched roof: modules lie on it, or stand on a rack that tilts them further (a roof too flat for the sun) + return Math.min(45, Math.max(0, f.tilt ?? 0)) * DEG; +} + +/** The distance from one row to the next: on a flat roof the module's depth plus a gap against shading. */ +export function rowPitch(face: RoofFace, f: Pick & { rack?: SolarField["rack"] }): number { + const [, height] = moduleSize(f); + const tilt = tiltOf(face, f); + // a wall: rows one above the other, as high as a tilted module reaches + if (face.wall) return height * Math.cos(tilt) + MODULE_GAP; + if (!face.flat && tilt < 0.001) return height + MODULE_GAP; + // east-west: the rows stand back to back in pairs, no gap against shading needed + if (face.flat && (f as Pick).rack === "ew") return height * Math.cos(tilt) + 0.08; + return height * Math.cos(tilt) + Math.max(0.3, 2 * height * Math.sin(tilt)); +} + +/** Width (the longest row) and depth (all rows) of a field on its face. */ +export function fieldSize(face: RoofFace, f: SolarField): [number, number] { + const [width, height] = moduleSize(f); + const counts = rowCounts(f); + const longest = Math.max(1, ...counts); + return [longest * width + (longest - 1) * MODULE_GAP, (counts.length - 1) * rowPitch(face, f) + height * Math.cos(tiltOf(face, f))]; +} + +/** Whether a field on this face may be turned about its middle: flat roofs only (garden fields turn their whole face instead). */ +const turnable = (face: RoofFace): boolean => face.flat && !face.unbounded && !face.wall; + +/** A field's turn in radians (clockwise in the plan, like the garden fields) and the point it turns about, in face coordinates; null when it stands straight. */ +function turnOf(face: RoofFace, f: SolarField): { cos: number; sin: number; u: number; s: number } | null { + if (!turnable(face) || !f.rotation) return null; + const r = f.rotation * DEG; + const [width, depth] = fieldSize(face, f); + return { cos: Math.cos(r), sin: Math.sin(r), u: f.u + width / 2, s: f.v + depth / 2 }; +} + +/** + * The modules of a field on its face. Modules that would leave the face (a hip, the ridge) are left out, and so are the + * ones switched off, unless `withSkipped` asks for them (the editor shows them). + */ +export function fieldModules(face: RoofFace, f: SolarField, withSkipped = false): SolarModule[] { + const [width, height] = moduleSize(f); + const tilt = tiltOf(face, f); + const depth = height * Math.cos(tilt); + const pitch = rowPitch(face, f); + const counts = rowCounts(f); + const longest = Math.max(1, ...counts); + const switchedOff = new Set(f.skip ?? []); + const turn = turnOf(face, f); + // a turned field: every point of it swings about the field's middle + const turned = (u: number, s: number): [number, number] => (turn ? [turn.u + (u - turn.u) * turn.cos - (s - turn.s) * turn.sin, turn.s + (u - turn.u) * turn.sin + (s - turn.s) * turn.cos] : [u, s]); + const at = (u0: number, s0: number, up: number): V3 => { + const [u, s] = turned(u0, s0); + return [0, 1, 2].map((i) => face.o[i] + face.eu[i] * u + face.es[i] * s + face.n[i] * up) as V3; + }; + const onFace = (u0: number, s0: number) => { + const [u, s] = turned(u0, s0); + if (face.unbounded) return true; + if (s < -1e-6 || s > face.ls + 1e-6) return false; + const [from, to] = face.span(s); + return u >= from - 1e-6 && u <= to + 1e-6; + }; + + const modules: SolarModule[] = []; + counts.forEach((count, row) => { + // a shorter row sits left, centred or right under the longest one + const shift = f.align === "right" ? longest - count : f.align === "center" ? (longest - count) / 2 : 0; + for (let col = 0; col < count; col++) { + const cell = `${row}:${col}`; + const skipped = switchedOff.has(cell); + if (skipped && !withSkipped) continue; + const u0 = f.u + (col + shift) * (width + MODULE_GAP); + const u1 = u0 + width; + const s0 = f.v + row * pitch; + const s1 = s0 + (face.flat || face.wall || tilt > 0.001 ? depth : height); + if (![[u0, s0], [u1, s0], [u1, s1], [u0, s1]].every(([u, s]) => onFace(u, s))) continue; + + if (face.wall && tilt > 0.001) { + // tilted on a wall: the upper edge stands off the wall (the lower edge when flipped), on brackets + const away = LIFT + height * Math.sin(tilt); + const [lowLift, highLift] = f.flip ? [away, LIFT] : [LIFT, away]; + const corners: [V3, V3, V3, V3] = [at(u0, s0, lowLift), at(u1, s0, lowLift), at(u1, s1, highLift), at(u0, s1, highLift)]; + const edge = f.flip ? s0 : s1; + modules.push({ corners, posts: [u0 + 0.05, u1 - 0.05].map((u) => [at(u, edge, 0), at(u, edge, away)] as [V3, V3]), cell, skipped }); + } else if (!face.flat && tilt > 0.001) { + // a rack on a pitched roof: the upper edge stands off the roof, on brackets + const away = LIFT + height * Math.sin(tilt); + const corners: [V3, V3, V3, V3] = [at(u0, s0, LIFT), at(u1, s0, LIFT), at(u1, s1, away), at(u0, s1, away)]; + modules.push({ corners, posts: [u0 + 0.05, u1 - 0.05].map((u) => [at(u, s1, 0), at(u, s1, away)] as [V3, V3]), cell, skipped }); + } else if (!face.flat) { + modules.push({ corners: [at(u0, s0, LIFT), at(u1, s0, LIFT), at(u1, s1, LIFT), at(u0, s1, LIFT)], posts: [], cell, skipped }); + } else { + // flat roof or ground: the module leans up towards +s (towards -s when flipped), on a low frame; east-west racks turn every + // second row the other way, so each pair stands back to back + const low = 0.15; + const high = low + height * Math.sin(tilt); + const flipped = f.rack === "ew" && row % 2 === 1 ? !f.flip : !!f.flip; + const [sLow, sHigh] = flipped ? [s1, s0] : [s0, s1]; + const corners: [V3, V3, V3, V3] = [at(u0, sLow, low), at(u1, sLow, low), at(u1, sHigh, high), at(u0, sHigh, high)]; + const posts = [u0 + 0.05, u1 - 0.05].flatMap((u) => [[at(u, sLow, 0), at(u, sLow, low)], [at(u, sHigh, 0), at(u, sHigh, high)]] as [V3, V3][]); + modules.push({ corners, posts, cell, skipped }); + } + } + }); + return modules; +} + +/** The corners of every module of a field in the plan, for the editor. */ +export const fieldPlan = (face: RoofFace, f: SolarField): Vec2[][] => fieldModules(face, f).map((m) => m.corners.map((p) => [p[0], p[2]] as Vec2)); + +/** Keeps a field on its face: its corner moves so the whole field stays on the face where it can. */ +export function clampField(face: RoofFace, f: SolarField): { u: number; v: number } { + if (face.unbounded) return { u: f.u, v: f.v }; + const [width, depth] = fieldSize(face, f); + const turn = turnOf(face, f); + if (turn) { + // a turned field: its middle stays where the turned outline still fits on the face + const [halfU, halfS] = [(width * Math.abs(turn.cos) + depth * Math.abs(turn.sin)) / 2, (width * Math.abs(turn.sin) + depth * Math.abs(turn.cos)) / 2]; + const inside = (centre: number, half: number, size: number) => Math.floor(Math.max(half, Math.min(centre, size - half)) * 100 + 1e-6) / 100; + const [cu, cs] = [f.u + width / 2, f.v + depth / 2]; + return { u: Math.round((inside(cu, halfU, face.lu) - width / 2) * 100) / 100, v: Math.round((inside(cs, halfS, face.ls) - depth / 2) * 100) / 100 }; + } + // rounded down to centimetres, so a field pushed to the far edge still fits completely + const down = (x: number) => Math.floor(x * 100 + 1e-6) / 100; + return { u: down(Math.min(Math.max(0, f.u), Math.max(0, face.lu - width))), v: down(Math.min(Math.max(0, f.v), Math.max(0, face.ls - depth))) }; +} + +/** The middle of a field in the plan. */ +export function fieldCenter(face: RoofFace, f: SolarField): Vec2 { + const [width, depth] = fieldSize(face, f); + const [u, s] = [f.u + width / 2, f.v + depth / 2]; + return [face.o[0] + face.eu[0] * u + face.es[0] * s, face.o[2] + face.eu[2] * u + face.es[2] * s]; +} + +// ---------------------------------------------------------------- roof windows + +/** The usual roof window size, 78 × 118 cm. */ +export const ROOF_WINDOW_W = 0.78; +export const ROOF_WINDOW_H = 1.18; + +/** A roof window as a field of one module of its own size, so that placing, moving and keeping it on the face work alike. */ +export const windowAsField = (w: RoofWindow): SolarField => ({ id: w.id, face: w.face, u: w.u, v: w.v, rows: 1, cols: 1, portrait: true, module_w: w.w || ROOF_WINDOW_W, module_h: w.h || ROOF_WINDOW_H }); + +/** The four corners of a roof window, sunk 5 cm into the roof (lower left, lower right, upper right, upper left). Null off the face. */ +export function windowCorners(face: RoofFace, w: RoofWindow): [V3, V3, V3, V3] | null { + const module = fieldModules(face, windowAsField(w))[0]; + if (!module) return null; + // modules ride 7 cm above the roof on rails; a roof window sits nearly flush + const sink = (p: V3): V3 => [p[0] - face.n[0] * 0.05, p[1] - face.n[1] * 0.05, p[2] - face.n[2] * 0.05]; + return module.corners.map(sink) as [V3, V3, V3, V3]; +} + +// ---------------------------------------------------------------- chimneys + +/** The usual size of each chimney shape: width along the eave, depth in the plan, height above the roof (m). */ +export const CHIMNEY_SIZE: Record = { + brick: { w: 0.5, d: 0.5, h: 1 }, + round: { w: 0.4, d: 0.4, h: 1 }, + wide: { w: 1, d: 0.5, h: 1 }, + steel: { w: 0.2, d: 0.2, h: 1.2 }, +}; + +/** A chimney's shape and size, the shape's usual size where none is set. */ +export function chimneySize(c: RoofChimney): { shape: ChimneyShape; w: number; d: number; h: number } { + const shape = c.shape ?? "brick"; + const usual = CHIMNEY_SIZE[shape] ?? CHIMNEY_SIZE.brick; + return { shape, w: c.w || usual.w, d: c.d || usual.d, h: c.h || usual.h }; +} + +/** A chimney as a field of one module the size of its footprint on the slope, so placing and moving work like a roof window's. */ +export function chimneyAsField(c: RoofChimney, face: RoofFace | null | undefined): SolarField { + const { w, d } = chimneySize(c); + const slope = face && !face.flat ? Math.cos(face.pitch * DEG) : 1; + return { id: c.id, face: c.face, u: c.u, v: c.v, rows: 1, cols: 1, portrait: true, module_w: w, module_h: d / Math.max(0.2, slope), tilt: 0 }; +} + +/** + * Where a chimney stands: the middle of its footprint in the plan, the plan directions along the eave and across it, + * and the roof's lowest and highest point under it (heights above the ground). + */ +export function chimneyPlace(face: RoofFace, c: RoofChimney): { center: Vec2; along: Vec2; across: Vec2; low: number; high: number } { + const f = chimneyAsField(c, face); + const [w, slope] = [f.module_w!, f.module_h!]; + const at = (u: number, s: number): V3 => [face.o[0] + face.eu[0] * u + face.es[0] * s, face.o[1] + face.eu[1] * u + face.es[1] * s, face.o[2] + face.eu[2] * u + face.es[2] * s]; + const [p0, p1] = [at(c.u + w / 2, c.v), at(c.u + w / 2, c.v + slope)]; + const mid = at(c.u + w / 2, c.v + slope / 2); + const flat = (v: readonly number[]): Vec2 => { + const n = Math.hypot(v[0], v[2]) || 1; + return [v[0] / n, v[2] / n]; + }; + return { center: [mid[0], mid[2]], along: flat(face.eu), across: flat(face.es), low: Math.min(p0[1], p1[1]), high: Math.max(p0[1], p1[1]) }; +} diff --git a/frontend/src/solar/fixtures.ts b/frontend/src/solar/fixtures.ts new file mode 100644 index 0000000..62c20d8 --- /dev/null +++ b/frontend/src/solar/fixtures.ts @@ -0,0 +1,17 @@ +// Builders for the solar tests. + +import { emptyBuilding, newFloor, type Building, type SolarField } from "../model.ts"; + +export const near = (a: number, b: number, eps = 1e-6) => { + if (Math.abs(a - b) >= eps) throw new Error(`${a} is not close to ${b}`); +}; + +/** A one-floor house of 12 × 7 m with 2.6 m high walls and the given roof. */ +export function cottage(roof: Building["settings"]["roof"], elevation = 0): Building { + const b = emptyBuilding(); + b.floors = [{ ...newFloor("g", "G", elevation), height: 2.6, rooms: [{ id: "r", name: "R", area_id: null, points: [[0, 0], [12, 0], [12, 7], [0, 7]], floor_material: "wood" }] }]; + b.settings = { ...b.settings, wall_exterior: 0.3, roof }; + return b; +} + +export const field = (face: string, extra: Partial = {}): SolarField => ({ id: "f", face, u: 0.5, v: 0.5, rows: 1, cols: 2, portrait: true, ...extra }); diff --git a/frontend/src/solar/picking.test.ts b/frontend/src/solar/picking.test.ts new file mode 100644 index 0000000..d491b02 --- /dev/null +++ b/frontend/src/solar/picking.test.ts @@ -0,0 +1,88 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { roofFaces, wallFaces } from "./faces.ts"; +import { cottage, field, near } from "./fixtures.ts"; +import { fieldModules } from "./fields.ts"; +import { bestFace, faceAt, faceCompass, onField, onFace, pointOnFace, rayOnFace } from "./picking.ts"; + +const house = () => cottage({ type: "gable", pitch: 35, overhang: 0.5 }); + +test("a plan point is found on the slope it lies under, with face coordinates that map back", () => { + const faces = roofFaces(house()); + const hit = faceAt(faces, [6, 1])!; + assert.equal(hit.face.key, "main:a"); + const back = [hit.face.o[0] + hit.face.eu[0] * hit.u + hit.face.es[0] * hit.s, hit.face.o[2] + hit.face.eu[2] * hit.u + hit.face.es[2] * hit.s]; + near(back[0], 6, 1e-9); + near(back[1], 1, 1e-9); + assert.equal(faceAt(faces, [6, 6])!.face.key, "main:b"); + assert.equal(faceAt(faces, [50, 50]), null); + assert.equal(pointOnFace(faces[0], [50, 50]), null); +}); + +test("where roofs overlap the highest one is picked", () => { + const b = cottage({ type: "custom", pitch: 35, overhang: 0, sections: [ + { id: "low", x0: 0, z0: 0, x1: 12, z1: 7, shape: "pent", axis: "x", eave_a: 2.6, eave_b: 2.6, pitch_a: 5, pitch_b: 5, base: 2.6, overhang: 0 }, + { id: "high", x0: 0, z0: 0, x1: 12, z1: 7, shape: "pent", axis: "x", eave_a: 5, eave_b: 5, pitch_a: 5, pitch_b: 5, base: 5, overhang: 0 }, + ] }); + assert.equal(faceAt(roofFaces(b), [6, 3])!.face.section, "high"); +}); + +test("right in front of a wall the wall wins, a little further out only where there is no roof", () => { + const b = house(); + const faces = [...roofFaces(b), ...wallFaces(b)]; + const wall = wallFaces(b)[0]; + const mid = [wall.o[0] + wall.eu[0] * wall.lu / 2, wall.o[2] + wall.eu[2] * wall.lu / 2]; + const near1 = faceAt(faces, [mid[0] + wall.n[0] * 0.2, mid[1] + wall.n[2] * 0.2])!; + assert.equal(near1.face.key, wall.key); + assert.ok(Number.isNaN(near1.s)); + const far = faceAt(wallFaces(b), [mid[0] + wall.n[0] * 0.6, mid[1] + wall.n[2] * 0.6])!; + assert.equal(far.face.key, wall.key); + assert.equal(faceAt(wallFaces(b), [mid[0] + wall.n[0] * 2, mid[1] + wall.n[2] * 2]), null); +}); + +test("a ray from above meets a face at the right distance and coordinates", () => { + const face = roofFaces(house())[0]; + const target = [face.o[0] + face.eu[0] * 3 + face.es[0] * 2, face.o[1] + face.eu[1] * 3 + face.es[1] * 2, face.o[2] + face.eu[2] * 3 + face.es[2] * 2] as [number, number, number]; + const origin: [number, number, number] = [target[0], target[1] + 10, target[2]]; + const hit = rayOnFace(face, origin, [0, -1, 0])!; + near(hit.u, 3, 1e-9); + near(hit.s, 2, 1e-9); + assert.ok(hit.t > 9 && hit.t < 11); + assert.equal(rayOnFace(face, origin, [0, 1, 0]), null, "away from the face"); + assert.equal(rayOnFace(face, origin, [face.eu[0], face.eu[1], face.eu[2]]), null, "parallel to the face"); +}); + +test("points are on a face inside its edges; the ground has no edges", () => { + const face = roofFaces(house())[0]; + assert.equal(onFace(face, 1, 1), true); + assert.equal(onFace(face, -1, 1), false); + assert.equal(onFace(face, 1, face.ls + 1), false); + assert.equal(onFace({ ...face, unbounded: true }, 1e6, 1e6), true); +}); + +test("a point is on a field when it lies over one of its modules, with a little slack", () => { + const face = roofFaces(house())[0]; + const f = field(face.key, { u: 1, v: 1, cols: 2 }); + assert.equal(onField(face, f, 1.5, 1.5), true); + assert.equal(onField(face, f, 0.97, 1.5), true, "5 cm slack"); + assert.equal(onField(face, f, 0.5, 1.5), false); + assert.equal(onField(face, f, 6, 6), false); + assert.equal(fieldModules(face, f).length, 2); +}); + +test("a face's compass direction follows the plan's north", () => { + const [a, b] = roofFaces(house()); + assert.equal(faceCompass(a, 0), "n"); + assert.equal(faceCompass(b, 0), "s"); + assert.equal(faceCompass(b, 90), "e", "north turned 90° clockwise: a south-looking face reads as east"); + assert.equal(faceCompass(a, 180), "s"); +}); + +test("the best face looks south and is big; flat roofs score a bit lower than a south slope", () => { + const faces = roofFaces(house()); + assert.equal(bestFace(faces, 0)?.key, "main:b"); + assert.equal(bestFace(faces, 180)?.key, "main:a"); + assert.equal(bestFace([], 0), null); + const flat = roofFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 })); + assert.equal(bestFace(flat, 0)?.key, "main:top"); +}); diff --git a/frontend/src/solar/picking.ts b/frontend/src/solar/picking.ts new file mode 100644 index 0000000..6a7a6d8 --- /dev/null +++ b/frontend/src/solar/picking.ts @@ -0,0 +1,94 @@ +// Finding where a pointer or a ray meets a face and its fields, and which way a face looks. + +import type { SolarField, Vec2 } from "../model.ts"; +import type { RoofFace } from "./faces.ts"; +import { fieldModules } from "./fields.ts"; +import { bearingOf, dot, sub, type V3 } from "./vec.ts"; + +/** Where a plan point lies on a face (u along the eave, s up the slope), or null when it is not on it. */ +export function pointOnFace(face: RoofFace, p: Vec2): { u: number; s: number } | null { + // solve p = o + eu * u + es * s in the plan; eu and es are not parallel there + const [d0, d1] = [p[0] - face.o[0], p[1] - face.o[2]]; + const [a0, a1, b0, b1] = [face.eu[0], face.eu[2], face.es[0], face.es[2]]; + const det = a0 * b1 - a1 * b0; + if (Math.abs(det) < 1e-9) return null; + const u = (d0 * b1 - d1 * b0) / det; + const s = (a0 * d1 - a1 * d0) / det; + if (s < 0 || s > face.ls) return null; + const [from, to] = face.span(s); + return u >= from && u <= to ? { u, s } : null; +} + +type Hit = { face: RoofFace; u: number; s: number }; + +/** + * The face under a plan point: the highest one there (an upper roof hides a lower one). A wall is hit by a pointer just + * outside it; the height stays open then (s is NaN). + */ +export function faceAt(faces: readonly RoofFace[], p: Vec2): Hit | null { + let best: (Hit & { y: number }) | null = null; + for (const face of faces) { + if (face.wall) { + const [dx, dz] = [p[0] - face.o[0], p[1] - face.o[2]]; + const u = dx * face.eu[0] + dz * face.eu[2]; + const outward = dx * face.n[0] + dz * face.n[2]; + const alongWall = u >= 0 && u <= face.lu; + // right in front of the wall it wins over a roof overhang above it; further out only where there is no roof + if (alongWall && outward >= -0.05 && outward <= 0.35) return { face, u, s: Number.NaN }; + if (alongWall && outward > 0.35 && outward <= 0.8 && !best) best = { face, u, s: Number.NaN, y: -Infinity }; + continue; + } + const hit = pointOnFace(face, p); + if (!hit) continue; + const y = face.o[1] + face.es[1] * hit.s; + if (!best || y > best.y) best = { face, ...hit, y }; + } + return best && { face: best.face, u: best.u, s: best.s }; +} + +/** Where a ray (origin, direction, building coordinates) meets a face: the distance t and the face coordinates. */ +export function rayOnFace(face: RoofFace, origin: V3, direction: V3): { t: number; u: number; s: number } | null { + const facing = dot(direction, face.n); + if (Math.abs(facing) < 1e-6) return null; + const t = dot(sub(face.o, origin), face.n) / facing; + if (t <= 0) return null; + const local = sub([origin[0] + direction[0] * t, origin[1] + direction[1] * t, origin[2] + direction[2] * t], face.o); + return { t, u: dot(local, face.eu), s: dot(local, face.es) }; +} + +/** Whether a point (u, s) lies on the face itself: inside its edges. The ground has none. */ +export function onFace(face: RoofFace, u: number, s: number): boolean { + if (face.unbounded) return true; + if (s < 0 || s > face.ls) return false; + const [from, to] = face.span(s); + return u >= from && u <= to; +} + +/** Whether a point (u, s) lies on one of the field's modules (their outlines on the face, with 5 cm to spare). */ +export function onField(face: RoofFace, f: SolarField, u: number, s: number): boolean { + const slack = 0.05; + return fieldModules(face, f).some((module) => { + const local = module.corners.map((corner) => { + const q = sub(corner, face.o); + return [dot(q, face.eu), dot(q, face.es)]; + }); + const us = local.map((c) => c[0]); + const ss = local.map((c) => c[1]); + return u >= Math.min(...us) - slack && u <= Math.max(...us) + slack && s >= Math.min(...ss) - slack && s <= Math.max(...ss) + slack; + }); +} + +const COMPASS = ["n", "ne", "e", "se", "s", "sw", "w", "nw"] as const; + +/** The compass direction a face looks to (n, ne, e ...), given the plan's north in degrees clockwise from up. */ +export const faceCompass = (face: RoofFace, north: number): (typeof COMPASS)[number] => COMPASS[Math.round(bearingOf(face.facing, north) / 45) % 8]; + +/** The face that suits a new field best: towards the south, and the bigger the better. */ +export function bestFace(faces: readonly RoofFace[], north: number): RoofFace | null { + const score = (face: RoofFace) => { + if (face.flat) return face.lu * face.ls * 0.8; + const southness = Math.cos(((bearingOf(face.facing, north) - 180) * Math.PI) / 180); + return face.lu * face.ls * (1.2 + southness); + }; + return [...faces].sort((p, q) => score(q) - score(p))[0] ?? null; +} diff --git a/frontend/src/solar/placing.test.ts b/frontend/src/solar/placing.test.ts new file mode 100644 index 0000000..3f39f25 --- /dev/null +++ b/frontend/src/solar/placing.test.ts @@ -0,0 +1,101 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { GROUND, fieldFace, roofFaces, wallFaces } from "./faces.ts"; +import { fieldModules, ROOF_WINDOW_H, ROOF_WINDOW_W } from "./fields.ts"; +import { cottage, near } from "./fixtures.ts"; +import { moveField, proposeField, proposeGroundField, proposeWallField, proposeWindow, turnGroundField } from "./placing.ts"; + +const gable = () => cottage({ type: "gable", pitch: 35, overhang: 0.5 }); + +test("a proposed field fits its face completely, with every module on it", () => { + for (const face of roofFaces(gable())) { + const f = proposeField(face, "p"); + assert.equal(f.face, face.key); + assert.equal(fieldModules(face, f).length, f.rows * f.cols, face.key); + assert.ok(f.cols >= 1 && f.rows >= 1 && f.rows <= 4); + } +}); + +test("on a flat roof the proposal is tilted on frames, on a slope it lies flat", () => { + const flat = roofFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 }))[0]; + assert.equal(proposeField(flat, "p").tilt, 15); + assert.equal(proposeField(roofFaces(gable())[0], "p").tilt, null); +}); + +test("a hip face narrows towards the ridge, so the proposal has fewer columns until all modules fit", () => { + const b = cottage({ type: "custom", pitch: 35, overhang: 0, sections: [{ id: "h", x0: 0, z0: 0, x1: 9, z1: 8, shape: "hip", axis: "x", eave_a: 2.6, eave_b: 2.6, pitch_a: 35, pitch_b: 35, base: 2.6, overhang: 0 }] }); + for (const face of roofFaces(b)) { + const f = proposeField(face, "p"); + assert.equal(fieldModules(face, f).length, f.rows * f.cols, face.key); + } +}); + +test("a field moved to another face keeps its modules and is centred inside the new face", () => { + const [a, b] = roofFaces(gable()); + const original = { ...proposeField(a, "m"), rows: 2, cols: 3, portrait: false }; + const moved = moveField(b, original); + assert.equal(moved.face, b.key); + assert.deepEqual([moved.rows, moved.cols, moved.portrait], [2, 3, false]); + assert.equal(moved.rotation, null); + assert.equal(fieldModules(b, moved).length, 6); + const flat = roofFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 }))[0]; + assert.equal(moveField(flat, { ...original, tilt: null }).tilt, 15, "a flat roof brings a tilt"); +}); + +test("the wall field goes on the wall that gets the most sun; none without walls", () => { + const b = gable(); + b.settings.north = 0; + const f = proposeWallField(b, "w", "g")!; + const face = fieldFace(b, f)!; + assert.ok(face.wall); + assert.equal(f.portrait, false); + assert.equal(f.rows, 1); + assert.ok(f.cols >= 1); + // the sunny side looks south: +z in the plan with north up + assert.ok(face.facing[1] > 0.5, `faces ${face.facing}`); + assert.equal(proposeWallField(b, "w", "nowhere"), null); + assert.ok(wallFaces(b, "g").length > 1); +}); + +test("a garden field stands east of the house on frames, tilted 25°, as two rows of four, looking south", () => { + const b = gable(); + const f = proposeGroundField(b, "g"); + assert.equal(f.face, GROUND); + assert.equal(f.rows * f.cols, 8); + assert.equal(f.tilt, 25); + assert.ok(f.u >= 12 + 2.9, "beside the house"); + assert.equal(f.rotation, 0); + const north = cottage({ type: "none", pitch: 0, overhang: 0 }); + north.settings.north = 40; + assert.equal(proposeGroundField(north, "g").rotation, 40); + assert.equal(proposeGroundField({ ...north, floors: [] }, "g").u, 0); +}); + +test("turning a garden field about its middle keeps the middle where it was", () => { + const b = gable(); + const f = { ...proposeGroundField(b, "g"), rotation: 0 }; + const middle = (g: typeof f) => { + const mods = fieldModules(fieldFace(b, g)!, g); + const xs = mods.flatMap((m) => m.corners.map((c) => c[0])); + const zs = mods.flatMap((m) => m.corners.map((c) => c[2])); + return [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...zs) + Math.max(...zs)) / 2]; + }; + const before = middle(f); + const turned = { ...f, ...turnGroundField(b, f, 90) }; + assert.equal(turned.rotation, 90); + const after = middle(turned); + // the box of modules turns too, but its centre stays within a field's depth of where it was + assert.ok(Math.hypot(after[0] - before[0], after[1] - before[1]) < 1.5); + assert.equal(turnGroundField(b, f, -90).rotation, 270); + assert.equal(turnGroundField(b, f, 450).rotation, 90); +}); + +test("a roof window is proposed in the middle of a face, fully on it", () => { + const face = roofFaces(gable())[0]; + const w = proposeWindow(face, "win"); + assert.equal(w.face, face.key); + assert.deepEqual([w.w, w.h], [null, null]); + assert.ok(w.u > 0 && w.u + ROOF_WINDOW_W < face.lu); + assert.ok(w.v >= 0 && w.v + ROOF_WINDOW_H <= face.ls + 1e-9); + near(w.u, Math.round(w.u * 100) / 100, 1e-9); +}); diff --git a/frontend/src/solar/placing.ts b/frontend/src/solar/placing.ts new file mode 100644 index 0000000..0a8a4f8 --- /dev/null +++ b/frontend/src/solar/placing.ts @@ -0,0 +1,99 @@ +// Proposals for new fields and windows, moving a field to another face, and turning a garden field. + +import type { Building, RoofChimney, RoofWindow, SolarField } from "../model.ts"; +import { GROUND, groundFace, wallFaces, type RoofFace } from "./faces.ts"; +import { CHIMNEY_SIZE, chimneyAsField, clampField, fieldModules, fieldSize, MODULE_GAP, MODULE_H, MODULE_W, moduleSize, ROOF_WINDOW_H, ROOF_WINDOW_W, rowPitch } from "./fields.ts"; +import { bearingOf, cm, DEG } from "./vec.ts"; + +/** The u that centres a field of its column count along the eave of a face. */ +function centredU(face: RoofFace, f: SolarField): number { + const [width] = moduleSize(f); + return cm((face.lu - (f.cols * width + (f.cols - 1) * MODULE_GAP)) / 2); +} + +const FIRST_ROW_OFFSET = 0.4; + +/** A field that fits: as many modules as the face holds, centred along the eave, starting a little above it. */ +export function proposeField(face: RoofFace, id: string): SolarField { + const field: SolarField = { id, face: face.key, u: 0, v: 0, rows: 1, cols: 1, portrait: true, tilt: face.flat ? 15 : null, flip: false, entity: null, look: "black" }; + const [width] = moduleSize(field); + const [from, to] = face.span(face.ls / 2); + field.cols = Math.max(1, Math.floor((to - from - 2 * FIRST_ROW_OFFSET + MODULE_GAP) / (width + MODULE_GAP))); + field.rows = Math.max(1, Math.min(4, Math.floor((face.ls - 2 * FIRST_ROW_OFFSET) / rowPitch(face, field)))); + // hip faces narrow towards the ridge: fewer columns until every module fits + while (field.cols > 1 && fieldModules(face, { ...field, u: centredU(face, field), v: FIRST_ROW_OFFSET }).length < field.rows * field.cols) field.cols--; + field.u = centredU(face, field); + field.v = FIRST_ROW_OFFSET; + return field; +} + +/** A field moved to another face: it keeps its modules (rows, columns, format, and tilt where the face allows one), centred along the new eave and inside its edges. */ +export function moveField(face: RoofFace, f: SolarField): SolarField { + const moved: SolarField = { ...f, face: face.key, tilt: face.flat ? (f.tilt ?? 15) : null, rotation: null, flip: false }; + moved.u = centredU(face, moved); + moved.v = FIRST_ROW_OFFSET; + return { ...moved, ...clampField(face, moved) }; +} + +/** A new wall field: on the wall that gets the most sun for its length, one row of landscape modules at head height. */ +export function proposeWallField(b: Building, id: string, floorId: string): SolarField | null { + const north = b.settings.north ?? 0; + // long walls facing south score best + const score = (face: RoofFace) => face.lu * (1.3 + Math.cos(((bearingOf(face.facing, north) - 180) * Math.PI) / 180)); + const face = wallFaces(b, floorId).sort((p, q) => score(q) - score(p))[0]; + if (!face) return null; + const field = { ...proposeField(face, id), portrait: false, rows: 1 }; + field.cols = Math.max(1, Math.floor((face.lu - 0.8 + MODULE_GAP) / (MODULE_H + MODULE_GAP))); + field.u = cm((face.lu - (field.cols * MODULE_H + (field.cols - 1) * MODULE_GAP)) / 2); + field.v = cm(Math.max(0, face.ls - MODULE_W - 0.3)); + return field; +} + +/** A new garden field beside the house: two rows of four, tilted 25°, looking south. */ +export function proposeGroundField(b: Building, id: string): SolarField { + const corners = b.floors.flatMap((floor) => floor.rooms.flatMap((r) => r.points)); + const x = corners.length ? Math.max(...corners.map((p) => p[0])) + 3 : 0; + const z = corners.length ? Math.min(...corners.map((p) => p[1])) : 0; + // rows run along x and the modules lean up towards -z: with north up in the plan they look south + return { id, face: GROUND, u: cm(x), v: cm(z), rows: 2, cols: 4, portrait: true, tilt: 25, flip: true, rotation: (b.settings.north ?? 0) || 0, look: "black", entity: null }; +} + +/** + * A garden field turned about its middle: u and v are measured along the turned axes, so they are worked out again from + * the field's centre in the plan (otherwise the field would jump away). + */ +export function turnGroundField(b: Building, f: SolarField, rotation: number): { u: number; v: number; rotation: number } { + const face = groundFace(b, f); + const [width, depth] = fieldSize(face, f); + const [halfU, halfV] = [f.u + width / 2, f.v + depth / 2]; + const centre = [face.eu[0] * halfU + face.es[0] * halfV, face.eu[2] * halfU + face.es[2] * halfV]; + const r = rotation * DEG; + // the centre stays put: the corner is half the size back along the new axes + const u = centre[0] * Math.cos(r) + centre[1] * Math.sin(r) - width / 2; + const v = centre[0] * -Math.sin(r) + centre[1] * Math.cos(r) - depth / 2; + return { u: cm(u), v: cm(v), rotation: ((Math.round(rotation) % 360) + 360) % 360 }; +} + +/** A new roof window in the middle of a face, around head height above the floor below. */ +export function proposeWindow(face: RoofFace, id: string): RoofWindow { + const [from, to] = face.span(face.ls / 2); + return { + id, + face: face.key, + u: cm((from + to - ROOF_WINDOW_W) / 2), + v: cm(Math.max(0, Math.min(face.ls - ROOF_WINDOW_H, face.ls * 0.45 - ROOF_WINDOW_H / 2))), + w: null, + h: null, + cover: null, + contact: null, + tilt: null, + }; +} + +/** A new chimney: a brick one near the ridge, in the middle of the face. */ +export function proposeChimney(face: RoofFace, id: string): RoofChimney { + const size = CHIMNEY_SIZE.brick; + const [from, to] = face.span(face.ls * 0.8); + const depth = chimneyAsField({ id, face: face.key, u: 0, v: 0 }, face).module_h!; + return { id, face: face.key, u: cm((from + to - size.w) / 2), v: cm(Math.max(0, Math.min(face.ls - depth, face.ls * 0.8 - depth / 2))), shape: "brick", w: null, d: null, h: null }; +} diff --git a/frontend/src/solar/vec.ts b/frontend/src/solar/vec.ts new file mode 100644 index 0000000..0beccde --- /dev/null +++ b/frontend/src/solar/vec.ts @@ -0,0 +1,20 @@ +// Three-component vector helpers for the solar geometry. + +export type V3 = [number, number, number]; + +export const DEG = Math.PI / 180; + +export const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; +export const dot = (a: V3, b: V3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +export const length = (a: V3): number => Math.hypot(a[0], a[1], a[2]); +export const normalize = (a: V3): V3 => { + const l = length(a) || 1; + return [a[0] / l, a[1] / l, a[2] / l]; +}; +export const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + +/** Rounded to centimetres. */ +export const cm = (v: number): number => Math.round(v * 100) / 100; + +/** Bearing of a plan direction in degrees clockwise from up (-z), turned by the plan's north, in 0..360. */ +export const bearingOf = ([dx, dz]: [number, number], north: number): number => (Math.atan2(dx, -dz) / DEG - north + 720) % 360; diff --git a/frontend/src/studio/recipes.test.ts b/frontend/src/studio/recipes.test.ts new file mode 100644 index 0000000..d08291f --- /dev/null +++ b/frontend/src/studio/recipes.test.ts @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { PackPart } from "../packs.ts"; +import { buildItem, cleanRecipe, newRecipe, STUDIO_KINDS, studioId, switchKind } from "./recipes.ts"; + +/** What the backend accepts for a part (packs.py): centres within the item, extents and levels as fractions. */ +function fits(part: PackPart): boolean { + const inside = (v: number) => v >= -0.5 && v <= 0.5; + const span = (v: number) => v >= 0.001 && v <= 1; + return inside(part.x) && inside(part.z) && span(part.w) && span(part.d) && span(part.h) && part.y >= 0 && part.y <= 1 && part.y + part.h <= 1.0001; +} + +test("every studio template builds parts the backend accepts, also at its limits", () => { + for (const kind of STUDIO_KINDS) { + for (const patch of [{}, { w: 5, d: 2, h: 2 }, { w: 400, d: 200, h: 300, doors: 6, drawers: 6, shelves: 12 }]) { + const item = buildItem({ ...newRecipe(kind, "Test"), ...patch }, "test", "de"); + assert.ok(item.parts.length >= 1 && item.parts.length <= 60, `${kind}: ${item.parts.length} parts`); + for (const part of item.parts) assert.ok(fits(part), `${kind} ${JSON.stringify(patch)}: ${JSON.stringify(part)}`); + } + } +}); + +test("a cabinet gets one front per door and drawer, and a handle on each", () => { + const item = buildItem({ ...newRecipe("cabinet", "Sideboard"), doors: 3, drawers: 2, handle: "bar", base: "none" }, "sideboard", "de"); + const fronts = item.parts.filter((p) => p.edges === "faint"); + assert.equal(fronts.length, 5); + assert.equal(item.parts.filter((p) => p.color === "metal").length, 5); + assert.equal(item.surface, true); + assert.deepEqual(item.size, [1.2, 0.45, 0.8]); + assert.equal(item.recipe?.doors, 3); + assert.deepEqual(item.name, { de: "Sideboard", en: "Sideboard" }); +}); + +test("a cabinet without fronts is open with its boards", () => { + const item = buildItem({ ...newRecipe("cabinet", ""), doors: 0, drawers: 0, shelves: 3 }, "open", "en"); + // two sides, the back, bottom, three boards and the top + assert.equal(item.parts.filter((p) => p.edges === "faint").length, 5); +}); + +test("lamps and devices carry what makes them light up or link", () => { + const pendant = buildItem({ ...newRecipe("lamp", ""), lamp: "pendant" }, "p", "en"); + assert.equal(pendant.light, "pendant"); + assert.equal(pendant.mount, "ceiling"); + assert.ok(pendant.parts.some((p) => p.glow)); + const tv = buildItem({ ...newRecipe("device", "TV"), mount: "wall", display: true }, "tv", "en"); + assert.equal(tv.electric, true); + assert.equal(tv.mount, "wall"); + assert.ok(tv.parts.some((p) => p.screen)); + assert.ok(!buildItem({ ...newRecipe("device", ""), display: false }, "box", "en").parts.some((p) => p.screen)); +}); + +test("recipes are kept within the studio's limits and switching the kind keeps name and colours", () => { + const r = cleanRecipe({ ...newRecipe("shelf", " Bücher "), w: 9999, shelves: 40, doors: -3 }); + assert.equal(r.name, "Bücher"); + assert.equal(r.w, 400); + assert.equal(r.shelves, 12); + assert.equal(r.doors, 0); + const lamp = switchKind({ ...r, front: "#112233" }, "lamp"); + assert.equal(lamp.kind, "lamp"); + assert.equal(lamp.name, "Bücher"); + assert.equal(lamp.front, "#112233"); + assert.equal(lamp.h, 160); +}); + +test("studio item ids come from the name and stay unique", () => { + assert.equal(studioId("Schuhschrank Flur", []), "schuhschrank_flur"); + assert.equal(studioId("Größe", []), "grosse"); + assert.equal(studioId("Regal", ["regal"]), "regal_2"); + assert.equal(studioId("Regal", ["regal", "regal_2"]), "regal_3"); + assert.equal(studioId("!!!", []), "piece"); +}); diff --git a/frontend/src/studio/recipes.ts b/frontend/src/studio/recipes.ts new file mode 100644 index 0000000..5df938f --- /dev/null +++ b/frontend/src/studio/recipes.ts @@ -0,0 +1,249 @@ +// The furniture studio in the editor: a few templates (cabinet, shelf, lamp, device) whose measurements and fronts are set in a form +// and turned into pack parts here. The recipe is kept on the item, so the piece can be opened in the studio again and changed. + +import type { PackItem, PackPart } from "../packs.ts"; + +export type StudioKind = "cabinet" | "shelf" | "lamp" | "device"; +export type StudioBase = "none" | "legs" | "plinth"; +export type StudioHandle = "bar" | "knob" | "none"; +export type StudioLamp = "floor" | "table" | "pendant" | "wall"; +export type StudioMount = "floor" | "surface" | "wall"; + +/** What the studio form holds. Sizes in centimetres; colours are palette roles or "#rrggbb". */ +export interface StudioRecipe { + kind: StudioKind; + name: string; + w: number; + d: number; + h: number; + /** Cabinet: doors side by side above the drawers. */ + doors: number; + /** Cabinet: drawers stacked at the bottom (all of the front when there are no doors). */ + drawers: number; + /** Shelf, and a cabinet without fronts: boards between bottom and top. */ + shelves: number; + base: StudioBase; + handle: StudioHandle; + /** Shelf: a back panel. */ + back: boolean; + lamp: StudioLamp; + /** Device: a display on its front that shows the linked media player. */ + display: boolean; + mount: StudioMount; + body: string; + front: string; +} + +export const STUDIO_KINDS: readonly StudioKind[] = ["cabinet", "shelf", "lamp", "device"]; +export const STUDIO_PACK = "own_studio"; +const MAX_FRONTS = 6; + +const DEFAULTS: Record> = { + cabinet: { w: 120, d: 45, h: 80, doors: 2, drawers: 1, shelves: 2, base: "plinth", handle: "bar", back: true, lamp: "floor", display: false, mount: "floor", body: "white", front: "wood" }, + shelf: { w: 80, d: 35, h: 180, doors: 0, drawers: 0, shelves: 4, base: "none", handle: "none", back: true, lamp: "floor", display: false, mount: "floor", body: "wood", front: "wood" }, + lamp: { w: 40, d: 40, h: 160, doors: 0, drawers: 0, shelves: 0, base: "none", handle: "none", back: false, lamp: "floor", display: false, mount: "floor", body: "metal", front: "white" }, + device: { w: 60, d: 60, h: 85, doors: 0, drawers: 0, shelves: 0, base: "none", handle: "none", back: false, lamp: "floor", display: true, mount: "floor", body: "white", front: "dark" }, +}; + +/** A fresh recipe of a kind, with the measurements of a common piece. */ +export const newRecipe = (kind: StudioKind, name: string): StudioRecipe => ({ kind, name, ...DEFAULTS[kind] }); + +/** A recipe switched to another kind keeps its name and colours, and takes that kind's measurements. */ +export const switchKind = (r: StudioRecipe, kind: StudioKind): StudioRecipe => ({ ...newRecipe(kind, r.name), body: r.body, front: r.front }); + +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, Number.isFinite(v) ? v : lo)); +const r4 = (v: number) => Math.round(v * 10000) / 10000; + +/** The recipe with every value inside what the studio builds (sizes 5 cm … 4 m, up to six fronts each). */ +export function cleanRecipe(r: StudioRecipe): StudioRecipe { + return { + ...r, + name: r.name.trim().slice(0, 60), + w: clamp(Math.round(r.w), 5, 400), + d: clamp(Math.round(r.d), 2, 200), + h: clamp(Math.round(r.h), 2, 300), + doors: clamp(Math.round(r.doors), 0, MAX_FRONTS), + drawers: clamp(Math.round(r.drawers), 0, MAX_FRONTS), + shelves: clamp(Math.round(r.shelves), 0, 12), + }; +} + +/** + * A box part from metres inside the item (x and z from the centre, y from the floor), turned into fractions of its size. A part that + * would stick out (a very small piece) is trimmed to the item. + */ +function boxIn(size: [number, number, number], x: number, z: number, w: number, d: number, y: number, h: number, color: string, extra: Partial = {}): PackPart { + const [W, D, H] = size; + const span = (centre: number, extent: number, half: number): [number, number] => { + const lo = Math.max(-half, centre - extent / 2); + const hi = Math.min(half, centre + extent / 2); + return hi - lo < 1e-4 ? [Math.max(-half, Math.min(half, centre)), 1e-3 * half * 2] : [(lo + hi) / 2, hi - lo]; + }; + const [cx, ex] = span(x, w, W / 2); + const [cz, ez] = span(z, d, D / 2); + const bottom = Math.max(0, Math.min(H * 0.999, y)); + const height = Math.max(H * 0.001, Math.min(H - bottom, h)); + const frac = (v: number) => r4(Math.max(0.001, Math.min(1, v))); + return { shape: "box", x: r4(cx / W), z: r4(cz / D), w: frac(ex / W), d: frac(ez / D), y: r4(bottom / H), h: frac(height / H), color, ...extra }; +} + +/** The legs or plinth under a cabinet or a device, and the height it leaves above them. */ +function baseParts(size: [number, number, number], base: StudioBase, out: PackPart[]): number { + const [W, D, H] = size; + if (base === "legs") { + const leg = Math.min(0.1, H * 0.25); + const s = Math.min(0.04, W / 6, D / 6); + for (const [sx, sz] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) out.push(boxIn(size, sx * (W / 2 - s), sz * (D / 2 - s), s, s, 0, leg, "metal")); + return leg; + } + if (base === "plinth") { + const plinth = Math.min(0.08, H * 0.2); + out.push(boxIn(size, 0, -0.02, W - 0.02, D - 0.04, 0, plinth, "dark")); + return plinth; + } + return 0; +} + +function cabinet(r: StudioRecipe, size: [number, number, number]): PackPart[] { + const [W, D, H] = size; + const parts: PackPart[] = []; + const y0 = baseParts(size, r.base, parts); + const fronts = r.doors + r.drawers > 0; + const handleDepth = r.handle === "none" || !fronts ? 0 : Math.min(0.025, D * 0.08); + const frontDepth = fronts ? Math.min(0.02, D * 0.1) : 0; + const bodyDepth = D - frontDepth - handleDepth; + const bodyZ = -D / 2 + bodyDepth / 2; + const height = H - y0; + if (!fronts) { + // an open cabinet: sides, top, bottom, back and boards + const t = Math.min(0.018, W / 10, height / 10); + parts.push(boxIn(size, -W / 2 + t / 2, 0, t, D, y0, height, r.body, { edges: true })); + parts.push(boxIn(size, W / 2 - t / 2, 0, t, D, y0, height, r.body, { edges: true })); + parts.push(boxIn(size, 0, -D / 2 + 0.005, W - 2 * t, 0.01, y0, height, r.body)); + for (let i = 0; i <= r.shelves + 1; i++) parts.push(boxIn(size, 0, 0.005, W - 2 * t, D - 0.01, y0 + ((height - t) * i) / (r.shelves + 1), t, r.front, { edges: "faint" })); + return parts; + } + parts.push(boxIn(size, 0, bodyZ, W, bodyDepth, y0, height, r.body, { edges: true })); + const gap = 0.004; + const frontZ = -D / 2 + bodyDepth + frontDepth / 2; + // drawers at the bottom, about 18 cm each, but always leaving 30 cm for doors + const drawerH = r.doors > 0 ? Math.min(0.18, Math.max(0.08, (height - 0.3) / Math.max(1, r.drawers))) : height / r.drawers; + const drawersTop = y0 + (r.drawers > 0 ? drawerH * r.drawers : 0); + const handle = (cx: number, cy: number, upright: boolean) => { + if (r.handle === "none") return; + const z = D / 2 - handleDepth / 2; + if (r.handle === "knob") parts.push(boxIn(size, cx, z, 0.025, handleDepth, cy - 0.0125, 0.025, "metal")); + else if (upright) parts.push(boxIn(size, cx, z, 0.015, handleDepth, cy - 0.08, 0.16, "metal")); + else parts.push(boxIn(size, cx, z, Math.min(0.16, W * 0.4), handleDepth, cy - 0.0075, 0.015, "metal")); + }; + for (let i = 0; i < r.drawers; i++) { + const y = y0 + drawerH * i; + parts.push(boxIn(size, 0, frontZ, W - 2 * gap, frontDepth, y + gap, drawerH - 2 * gap, r.front, { edges: "faint" })); + handle(0, y + drawerH * (r.drawers === 1 && r.doors === 0 ? 0.5 : 0.7), false); + } + if (r.doors > 0) { + const doorW = W / r.doors; + const doorH = H - drawersTop; + for (let i = 0; i < r.doors; i++) { + const cx = -W / 2 + doorW * (i + 0.5); + parts.push(boxIn(size, cx, frontZ, doorW - 2 * gap, frontDepth, drawersTop + gap, doorH - 2 * gap, r.front, { edges: "faint" })); + // the handle sits on the edge where the door opens: pairs meet in the middle + const side = r.doors === 1 ? 1 : i % 2 === 0 ? 1 : -1; + const hy = drawersTop + doorH * (H > 1.2 ? 0.45 : 0.8); + handle(cx + side * (doorW / 2 - 0.04), Math.min(hy, H - 0.1), true); + } + } + return parts; +} + +function shelf(r: StudioRecipe, size: [number, number, number]): PackPart[] { + const [W, D, H] = size; + const t = Math.min(0.02, W / 10, H / 10); + const parts: PackPart[] = [boxIn(size, -W / 2 + t / 2, 0, t, D, 0, H, r.body, { edges: true }), boxIn(size, W / 2 - t / 2, 0, t, D, 0, H, r.body, { edges: true })]; + if (r.back) parts.push(boxIn(size, 0, -D / 2 + 0.005, W - 2 * t, 0.01, 0, H, r.body)); + const boards = r.shelves + 2; + for (let i = 0; i < boards; i++) parts.push(boxIn(size, 0, r.back ? 0.005 : 0, W - 2 * t, r.back ? D - 0.01 : D, ((H - t) * i) / (boards - 1), t, r.front, { edges: true })); + return parts; +} + +function lamp(r: StudioRecipe, size: [number, number, number]): PackPart[] { + const [W, D, H] = size; + const shadeW = Math.min(W, D); + const cyl = (x: number, z: number, w: number, y: number, h: number, color: string, extra: Partial = {}): PackPart => ({ ...boxIn(size, x, z, w, w, y, h, color, extra), shape: "cyl" }); + const shade = (y: number, h: number, topScale: number): PackPart => ({ ...boxIn(size, 0, 0, shadeW, shadeW, y, h, r.front, { glow: true, edges: "faint" }), shape: "loft", tw: r4(Math.min(1, (shadeW * topScale) / W)), td: r4(Math.min(1, (shadeW * topScale) / D)) }); + switch (r.lamp) { + case "pendant": { + const shadeH = Math.min(0.3, H * 0.4); + return [cyl(0, 0, Math.min(0.12, shadeW), H - 0.03, 0.03, r.body), cyl(0, 0, Math.min(0.01, shadeW / 4), shadeH, H - shadeH - 0.03, "dark"), shade(0, shadeH, 0.35)]; + } + case "wall": { + const plate = Math.min(0.02, D * 0.2); + return [boxIn(size, 0, -D / 2 + plate / 2, Math.min(0.1, W), plate, H * 0.3, H * 0.4, r.body), boxIn(size, 0, 0, Math.min(0.02, W), D - plate, H * 0.45, Math.min(0.02, H * 0.1), r.body), shade(H * 0.15, H * 0.7, 0.7)]; + } + default: { + // floor and table lamps: a foot, a stem and a shade on top + const shadeH = Math.min(r.lamp === "table" ? 0.25 : 0.35, H * 0.4); + return [cyl(0, 0, shadeW * 0.6, 0, Math.min(0.03, H * 0.05), r.body, { edges: true }), cyl(0, 0, Math.min(0.03, shadeW / 6), 0.02, H - shadeH - 0.02, r.body), shade(H - shadeH, shadeH, 0.7)]; + } + } +} + +function device(r: StudioRecipe, size: [number, number, number]): PackPart[] { + const [W, D, H] = size; + const parts: PackPart[] = []; + const y0 = r.mount === "floor" ? baseParts(size, r.base, parts) : 0; + const frontDepth = r.display ? Math.min(0.01, D * 0.1) : 0; + parts.push(boxIn(size, 0, -frontDepth / 2, W, D - frontDepth, y0, H - y0, r.body, { edges: true })); + if (r.display) { + const m = Math.min(0.02, W * 0.08, (H - y0) * 0.08); + parts.push(boxIn(size, 0, D / 2 - frontDepth / 2, W - 2 * m, frontDepth, y0 + m, H - y0 - 2 * m, r.front, { screen: true })); + } + return parts; +} + +/** The pack item a recipe builds: its parts, size and kind flags, with the recipe kept for the studio. */ +export function buildItem(recipe: StudioRecipe, id: string, language: string): PackItem { + const r = cleanRecipe(recipe); + const size: [number, number, number] = [r.w / 100, r.d / 100, r.h / 100]; + const name = r.name || id; + const names = language === "en" ? { en: name } : { [language.slice(0, 5)]: name, en: name }; + const item: PackItem = { id, name: names, size, parts: [], recipe: r }; + switch (r.kind) { + case "cabinet": + item.parts = cabinet(r, size); + item.surface = true; + break; + case "shelf": + item.parts = shelf(r, size); + break; + case "lamp": + item.parts = lamp(r, size); + item.light = r.lamp; + item.mount = r.lamp === "pendant" ? "ceiling" : r.lamp === "wall" ? "wall" : r.lamp === "table" ? "surface" : "floor"; + if (r.lamp === "wall") item.wall_y = 1.6; + break; + case "device": + item.parts = device(r, size); + item.electric = true; + item.mount = r.mount; + if (r.mount === "wall") item.wall_y = 1.2; + break; + } + return item; +} + +/** A new item id inside the studio pack, from the name ("Schuhschrank" -> "schuhschrank", then "schuhschrank_2"). */ +export function studioId(name: string, taken: readonly string[]): string { + const base = + name + .toLowerCase() + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") + .replace(/ß/g, "ss") + .replace(/[^a-z0-9]+/g, "_") + .replace(/^_+|_+$/g, "") + .slice(0, 32) || "piece"; + const start = /^[a-z0-9]/.test(base) ? base : `p${base}`; + if (!taken.includes(start)) return start; + for (let n = 2; ; n++) if (!taken.includes(`${start}_${n}`)) return `${start}_${n}`; +} diff --git a/frontend/src/styles.ts b/frontend/src/styles.ts new file mode 100644 index 0000000..f0c0207 --- /dev/null +++ b/frontend/src/styles.ts @@ -0,0 +1,226 @@ +import { css } from "lit"; + +/** + * Design tokens shared by panel, card and editor. + * + * Everything points at Home Assistant's own theme variables, so NextFloor looks like the rest of the dashboard + * and follows its light or dark theme. The fallbacks are Home Assistant's default dark theme, used when a + * component runs outside Home Assistant (the preview, the online demo). + */ +export const tokens = css` + :host { + --nf-text: var(--primary-text-color, #e1e1e1); + --nf-muted: var(--secondary-text-color, #9b9b9b); + --nf-accent: var(--primary-color, #03a9f4); + --nf-accent-text: var(--text-primary-color, #ffffff); + --nf-surface: var(--ha-card-background, var(--card-background-color, #1c1c1c)); + --nf-bg: var(--primary-background-color, #111111); + --nf-bg2: var(--secondary-background-color, #1c1c1c); + /* floating bars and cards over the 3D view: the card colour, a little see-through */ + --nf-chrome: color-mix(in srgb, var(--nf-surface) var(--nf-chrome-mix, 84%), transparent); + --nf-chrome-solid: var(--nf-surface); + --nf-line: var(--divider-color, rgba(255, 255, 255, 0.12)); + /* quiet fills for buttons and fields, and the tonal accent of an active control */ + --nf-fill: color-mix(in srgb, var(--nf-text) 7%, transparent); + --nf-fill-strong: color-mix(in srgb, var(--nf-text) 13%, transparent); + --nf-tonal: color-mix(in srgb, var(--nf-accent) 20%, transparent); + --nf-soft: var(--info-color, #4a90e2); + --nf-warm: var(--state-light-active-color, #ffa726); + --nf-danger: var(--error-color, #db4437); + --nf-good: var(--success-color, #43a047); + --nf-radius: var(--ha-card-border-radius, 12px); + --nf-shadow: var(--ha-card-box-shadow, 0 1px 2px rgba(0, 0, 0, 0.18), 0 6px 20px rgba(0, 0, 0, 0.2)); + --nf-font: var(--primary-font-family, Roboto, "Noto Sans", system-ui, -apple-system, "Segoe UI", sans-serif); + --nf-title-font: var(--nf-font); + font-family: var(--nf-font); + color: var(--nf-text); + } +`; + +/** + * Easy to read (a host with the `readable` attribute): the quiet greys of Home Assistant's theme become the text colour, lines and + * floating bars get stronger, and the bars and the room panel a size larger. Custom properties reach into the inner components. + */ +export const readableStyles = css` + :host([readable]) { + --secondary-text-color: var(--primary-text-color, #e1e1e1); + --divider-color: color-mix(in srgb, var(--primary-text-color, #e1e1e1) 40%, transparent); + --nf-chrome-mix: 97%; + } + :host([readable]) nf-room-panel, + :host([readable]) .nf-nav, + :host([readable]) .nf-overlay { + zoom: 1.2; + } +`; + +/** Pills, chips, buttons and form controls in the style of Home Assistant's own cards. */ +export const controls = css` + /* a group of switches: one rounded pill, the active one tinted with the accent */ + .nf-seg { + display: inline-flex; + padding: 4px; + gap: 2px; + border-radius: 999px; + background: var(--nf-chrome); + box-shadow: var(--nf-shadow); + backdrop-filter: blur(10px); + } + .nf-seg button, + .nf-chip { + font: inherit; + font-size: 14px; + font-weight: 500; + border: none; + background: none; + color: var(--nf-muted); + padding: 7px 14px; + border-radius: 999px; + cursor: pointer; + white-space: nowrap; + min-height: 36px; + transition: + background 0.15s, + color 0.15s; + } + .nf-seg button:hover:not(:disabled), + .nf-chip:hover { + background: var(--nf-fill); + color: var(--nf-text); + } + /* on a small stage (a small window, a zoomed browser, a dashboard column) the switches at the bottom take less room */ + @container nf ((max-width: 1360px) or (max-height: 640px)) { + :is(.nf-overlay, .nf-card-controls) .nf-seg { + padding: 3px; + } + :is(.nf-overlay, .nf-card-controls) :is(.nf-seg button, .nf-chip) { + font-size: 12.5px; + padding: 5px 10px; + } + } + .nf-time-slider { + display: inline-flex; + align-items: center; + padding: 4px 10px; + } + .nf-time-slider input { + width: 160px; + accent-color: var(--nf-accent); + } + .nf-seg button[aria-pressed="true"], + .nf-chip[aria-pressed="true"] { + background: color-mix(in srgb, var(--nf-accent) 24%, var(--nf-chrome-solid)); + color: var(--nf-accent); + font-weight: 600; + } + .nf-seg button:disabled { + opacity: 0.4; + cursor: default; + } + /* a single pill, like the chips of the Mushroom cards */ + .nf-chip { + background: var(--nf-chrome); + color: var(--nf-text); + box-shadow: var(--nf-shadow); + backdrop-filter: blur(10px); + } + + button:focus-visible, + input:focus-visible, + select:focus-visible { + outline: 2px solid var(--nf-accent); + outline-offset: 2px; + } + /* the round icon badge every row and card starts with */ + .nf-ico { + display: inline-flex; + align-items: center; + justify-content: center; + flex: none; + width: 38px; + height: 38px; + border-radius: 50%; + background: var(--nf-tonal); + color: var(--nf-accent); + --mdc-icon-size: 20px; + } + .nf-ico.nf-warm { + background: color-mix(in srgb, var(--nf-warm) 22%, transparent); + color: var(--nf-warm); + } + .nf-ico.nf-off { + background: var(--nf-fill); + color: var(--nf-muted); + } + .nf-btn { + font: inherit; + font-size: 14px; + font-weight: 500; + border: none; + background: var(--nf-fill); + color: var(--nf-text); + border-radius: var(--nf-radius); + padding: 7px 14px; + cursor: pointer; + min-height: 36px; + transition: background 0.15s; + } + .nf-btn:hover { + background: var(--nf-fill-strong); + } + .nf-btn.nf-danger { + color: var(--nf-danger); + } + .nf-btn.nf-primary { + background: var(--nf-accent); + color: var(--nf-accent-text); + } + .nf-btn.nf-primary:hover { + background: color-mix(in srgb, var(--nf-accent) 88%, var(--nf-text)); + } + .nf-field { + display: grid; + gap: 4px; + font-size: 12px; + color: var(--nf-muted); + } + .nf-field input, + .nf-field select, + .nf-field textarea { + font: inherit; + font-size: 14px; + color: var(--nf-text); + background: var(--nf-fill); + border: none; + border-bottom: 1px solid var(--nf-line); + border-radius: 10px 10px 4px 4px; + padding: 8px 10px; + min-width: 0; + } + .nf-field input:focus, + .nf-field select:focus, + .nf-field textarea:focus { + border-bottom-color: var(--nf-accent); + } + .nf-field input[type="range"] { + padding: 0; + accent-color: var(--nf-accent); + } + .nf-field select option { + background: var(--nf-chrome-solid); + color: var(--nf-text); + } + /* fingers need 40 px */ + @media (pointer: coarse) { + .nf-seg button, + .nf-chip, + .nf-btn { + min-height: 40px; + } + } +`; + +/** `color-scheme` for native controls (selects, scrollbars) from Home Assistant's own light or dark mode. */ +export function colorSchemeOf(hass: { themes?: { darkMode?: boolean } } | undefined | null): "light" | "dark" { + return hass?.themes?.darkMode === false ? "light" : "dark"; +} diff --git a/frontend/src/sun-position.test.ts b/frontend/src/sun-position.test.ts new file mode 100644 index 0000000..313c09e --- /dev/null +++ b/frontend/src/sun-position.test.ts @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { sunPosition, todayAt } from "./sun-position.ts"; + +test("midsummer noon in Dresden: the sun stands high in the south", () => { + // 21 June 2026, 11:05 UTC is about solar noon at 13.7° east + const { elevation, azimuth } = sunPosition(new Date(Date.UTC(2026, 5, 21, 11, 5)), 51.05, 13.74); + assert.ok(Math.abs(elevation - 62.4) < 1, `elevation ${elevation}`); + assert.ok(Math.abs(azimuth - 180) < 3, `azimuth ${azimuth}`); +}); + +test("winter morning: low in the south east; midnight: below the horizon", () => { + const morning = sunPosition(new Date(Date.UTC(2026, 11, 21, 8, 0)), 51.05, 13.74); + assert.ok(morning.elevation > 0 && morning.elevation < 10, `elevation ${morning.elevation}`); + assert.ok(morning.azimuth > 120 && morning.azimuth < 160, `azimuth ${morning.azimuth}`); + assert.ok(sunPosition(new Date(Date.UTC(2026, 11, 21, 23, 0)), 51.05, 13.74).elevation < -40); +}); + +test("the slider's hour is the home's hour, whatever zone the browser is in", () => { + const now = new Date(Date.UTC(2026, 10, 2, 20, 0)); + // 10:00 in Berlin (winter time, UTC+1) is 09:00 UTC; in Bangkok (UTC+7) 03:00 UTC + assert.equal(todayAt(10, "Europe/Berlin", now).toISOString(), "2026-11-02T09:00:00.000Z"); + assert.equal(todayAt(10, "Asia/Bangkok", now).toISOString(), "2026-11-03T03:00:00.000Z", "already the 3rd in Bangkok"); + // summer time: 10:00 in Berlin on 21 June is 08:00 UTC + assert.equal(todayAt(10.5, "Europe/Berlin", new Date(Date.UTC(2026, 5, 21, 12))).toISOString(), "2026-06-21T08:30:00.000Z"); + // an unknown zone falls back to the browser's + assert.ok(Number.isFinite(todayAt(10, "Nowhere/Land", now).getTime())); +}); diff --git a/frontend/src/sun-position.ts b/frontend/src/sun-position.ts new file mode 100644 index 0000000..28bd3aa --- /dev/null +++ b/frontend/src/sun-position.ts @@ -0,0 +1,55 @@ +// Where the sun stands at any moment and place (a short form of the NOAA formulas, good to a fraction of a degree), so the 3D view can +// show the light of another time of day than now: the time-of-day slider. + +const RAD = Math.PI / 180; + +/** Elevation above the horizon and azimuth clockwise from north, in degrees, as sun.sun reports them. */ +export function sunPosition(date: Date, latitude: number, longitude: number): { elevation: number; azimuth: number } { + // days since 1 January 2000, 12:00 UTC + const d = date.getTime() / 86400000 - 10957.5; + const anomaly = (357.529 + 0.98560028 * d) * RAD; + const meanLongitude = 280.459 + 0.98564736 * d; + const ecliptic = (meanLongitude + 1.915 * Math.sin(anomaly) + 0.02 * Math.sin(2 * anomaly)) * RAD; + const tilt = (23.439 - 0.00000036 * d) * RAD; + const ascension = Math.atan2(Math.cos(tilt) * Math.sin(ecliptic), Math.cos(ecliptic)); + const declination = Math.asin(Math.sin(tilt) * Math.sin(ecliptic)); + const sidereal = (((18.697374558 + 24.06570982441908 * d) % 24) + 24) % 24; + const hourAngle = (sidereal * 15 + longitude) * RAD - ascension; + const phi = latitude * RAD; + const elevation = Math.asin(Math.sin(phi) * Math.sin(declination) + Math.cos(phi) * Math.cos(declination) * Math.cos(hourAngle)); + const azimuth = Math.atan2(Math.sin(hourAngle), Math.cos(hourAngle) * Math.sin(phi) - Math.tan(declination) * Math.cos(phi)) / RAD + 180; + return { elevation: elevation / RAD, azimuth: ((azimuth % 360) + 360) % 360 }; +} + +/** The wall clock of `zone` at an instant, as if it were UTC (its difference to the instant is the zone's offset). */ +function wallClock(instant: number, zone: string): number { + const parts = Object.fromEntries( + new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" }) + .formatToParts(new Date(instant)) + .map((p) => [p.type, Number(p.value)]), + ); + return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second); +} + +/** + * Today at `hours` o'clock in `zone` (Home Assistant's time zone, so a tablet set to another zone, or a kiosk on UTC, + * still shows the home's light); without a zone, or with one the browser does not know, in the browser's own zone. + */ +export function todayAt(hours: number, zone?: string | null, now = new Date()): Date { + const [h, m] = [Math.floor(hours), Math.round((hours % 1) * 60)]; + if (zone) { + try { + const today = new Date(wallClock(now.getTime(), zone)); + const wanted = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), h, m); + // the zone's offset at the wanted time, checked once more across a change to or from summer time + let at = wanted - (wallClock(wanted, zone) - wanted); + at = wanted - (wallClock(at, zone) - at); + return new Date(at); + } catch { + // an unknown zone: fall back to the browser's + } + } + const at = new Date(now); + at.setHours(h, m, 0, 0); + return at; +} diff --git a/frontend/src/symcon-bridge.ts b/frontend/src/symcon-bridge.ts new file mode 100644 index 0000000..8bc68fd --- /dev/null +++ b/frontend/src/symcon-bridge.ts @@ -0,0 +1,200 @@ +// IP-Symcon adapter for the existing NextFloor web components. +// +// The viewer and editor intentionally keep the small HomeAssistant-shaped data surface they already use. +// Symcon variables are exposed as named synthetic entities (for example `light.12345`), while the browser +// only ever shows and selects their object-tree path. The numeric object id stays an implementation detail. + +import type { HassArea, HassEntity, HassEntityEntry, HomeAssistant } from "./types.ts"; + +interface SymconConfig { + endpoint: string; + token: string; + language?: string; + title?: string; +} + +interface SymconVariable { + entity_id: string; + name: string; + path: string; + state: string; + attributes: Record; + area_id?: string | null; + device_id?: string | null; +} + +interface Bootstrap { + state_revision: number; + building_revision: number; + variables: SymconVariable[]; + areas: HassArea[]; +} + +interface VariableSnapshot { + state_revision: number; + building_revision: number; + variables?: SymconVariable[]; + areas?: HassArea[]; +} + +type Listener = () => void; +type BuildingListener = (revision: number) => void; + +declare global { + interface Window { + __NEXTFLOOR_SYMCON__?: SymconConfig; + } +} + +function config(): SymconConfig { + const settings = window.__NEXTFLOOR_SYMCON__; + if (!settings?.endpoint || !settings.token) throw new Error("NextFloor Symcon host configuration is missing"); + return settings; +} + +/** Same-origin JSON call to the instance's protected WebHook. */ +async function call(settings: SymconConfig, action: string, payload: Record = {}): Promise { + const response = await fetch(`${settings.endpoint}/api?token=${encodeURIComponent(settings.token)}`, { + method: "POST", + headers: { "Content-Type": "application/json", Accept: "application/json" }, + credentials: "same-origin", + body: JSON.stringify({ action, ...payload }), + }); + const body: unknown = await response.json().catch(() => ({ error: `HTTP ${response.status}` })); + if (!response.ok || !body || typeof body !== "object" || "error" in body) { + const error = body && typeof body === "object" && "error" in body ? (body as { error?: unknown }).error : `HTTP ${response.status}`; + throw new Error(String(error)); + } + return body as T; +} + +/** + * Turns the instance WebHook into the interface used by the NextFloor UI. Polling is deliberate here: it + * works in the designer tab, an iframe in the Tile visualization and a remote WebFront without exposing an + * unauthenticated JSON-RPC port to the browser. The module returns only variables from the object tree. + */ +export class SymconBridge { + private readonly settings = config(); + private readonly changeListeners = new Set(); + private readonly buildingListeners = new Set(); + private timer: ReturnType | undefined; + private stateRevision = -1; + private buildingRevision = -1; + private states: Record = {}; + private entities: Record = {}; + private areas: Record = {}; + + private readonly facade: HomeAssistant = { + language: this.settings.language || navigator.language || "de", + user: { is_admin: true, name: this.settings.title || "IP-Symcon" }, + states: this.states, + entities: this.entities, + areas: this.areas, + config: { unit_system: { temperature: "°C" } }, + themes: { darkMode: window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? true }, + services: {}, + connection: { + subscribeMessage: async (callback: (message: T) => void, message: Record) => { + if (message.type === "nextfloor/building/subscribe") { + const listener: BuildingListener = (revision) => callback({ revision } as T); + this.buildingListeners.add(listener); + return async () => void this.buildingListeners.delete(listener); + } + // Announcements and the Home Assistant-only subscriptions simply have no Symcon equivalent. + return async () => undefined; + }, + }, + callWS: (message: Record) => this.callWS(message), + callService: (domain, service, data) => this.callService(domain, service, data), + fetchWithAuth: (path, init) => this.fetchWithToken(path, init), + hassUrl: (path = "") => new URL(path, window.location.origin).href, + }; + + /** Read the initial object tree and begin refreshing changed values. */ + async start(): Promise { + const initial = await call(this.settings, "bootstrap"); + this.apply(initial); + this.stateRevision = initial.state_revision; + this.buildingRevision = initial.building_revision; + this.timer = setInterval(() => void this.refresh(), 800); + return this.snapshot(); + } + + stop(): void { + if (this.timer) clearInterval(this.timer); + this.timer = undefined; + } + + onChange(listener: Listener): () => void { + this.changeListeners.add(listener); + return () => this.changeListeners.delete(listener); + } + + /** A new object identity makes Lit propagate a state refresh through all nested components. */ + snapshot(): HomeAssistant { + return { ...this.facade, states: { ...this.states }, entities: { ...this.entities }, areas: { ...this.areas } }; + } + + private async refresh(): Promise { + try { + const next = await call(this.settings, "variables/snapshot", { revision: this.stateRevision }); + if (next.state_revision !== this.stateRevision && next.variables) { + this.stateRevision = next.state_revision; + this.apply({ variables: next.variables, areas: next.areas }); + for (const listener of this.changeListeners) listener(); + } + if (next.building_revision !== this.buildingRevision) { + this.buildingRevision = next.building_revision; + for (const listener of this.buildingListeners) listener(next.building_revision); + } + } catch { + // A temporary unavailable WebHook must not blank a running visualization. The next poll retries. + } + } + + private apply(data: { variables: SymconVariable[]; areas?: HassArea[] }): void { + this.states = Object.fromEntries( + data.variables.map((variable) => [ + variable.entity_id, + { + entity_id: variable.entity_id, + state: variable.state, + attributes: { ...variable.attributes, friendly_name: variable.name, symcon_path: variable.path }, + } satisfies HassEntity, + ]), + ); + this.entities = Object.fromEntries( + data.variables.map((variable) => [ + variable.entity_id, + { + entity_id: variable.entity_id, + name: variable.name, + area_id: variable.area_id ?? null, + device_id: variable.device_id ?? null, + } satisfies HassEntityEntry, + ]), + ); + if (data.areas) this.areas = Object.fromEntries(data.areas.map((area) => [area.area_id, area])); + this.facade.states = this.states; + this.facade.entities = this.entities; + this.facade.areas = this.areas; + } + + private async callWS(message: Record): Promise { + const type = String(message.type ?? ""); + if (!type.startsWith("nextfloor/")) throw new Error(`Unsupported Symcon websocket command: ${type}`); + const { type: _ignored, ...payload } = message; + return call(this.settings, type.slice("nextfloor/".length), payload); + } + + private async callService(domain: string, service: string, data: Record = {}): Promise { + return call(this.settings, "variables/action", { domain, service, data }); + } + + /** Mesh uploads are intentionally not exposed until the Symcon asset store exists. Other paths stay same-origin. */ + private fetchWithToken(path: string, init: Record = {}): Promise { + const url = new URL(path, window.location.origin); + url.searchParams.set("token", this.settings.token); + return fetch(url, { ...init, credentials: "same-origin" }); + } +} diff --git a/frontend/src/symcon-host.ts b/frontend/src/symcon-host.ts new file mode 100644 index 0000000..cff23e3 --- /dev/null +++ b/frontend/src/symcon-host.ts @@ -0,0 +1,36 @@ +// Entry point served by the IP-Symcon WebHook. It mounts the existing panel in the console designer and +// the existing dashboard card inside the HTML-SDK tile iframe. + +import "./main.ts"; +import { SymconBridge } from "./symcon-bridge.ts"; +import type { HomeAssistant } from "./types.ts"; + +type SymconPanel = HTMLElement & { hass: HomeAssistant; narrow: boolean }; +type SymconCard = HTMLElement & { hass: HomeAssistant; setConfig(config: Record): void }; + +function pageMode(): "designer" | "tile" { + return new URLSearchParams(window.location.search).get("mode") === "tile" ? "tile" : "designer"; +} + +async function mount(): Promise { + const bridge = new SymconBridge(); + const hass = await bridge.start(); + const tile = pageMode() === "tile"; + const app = (tile ? document.createElement("nextfloor-card") : document.createElement("nextfloor-panel")) as SymconCard & SymconPanel; + app.className = tile ? "nf-symcon-tile" : "nf-symcon-designer"; + app.hass = hass; + if (tile) { + (app as SymconCard).setConfig({ type: "custom:nextfloor-card", fill: true, room_buttons: true, controls: true, weather: false, announcements: false }); + } else { + (app as SymconPanel).narrow = false; + } + document.body.replaceChildren(app); + bridge.onChange(() => { + app.hass = bridge.snapshot(); + }); + window.addEventListener("pagehide", () => bridge.stop(), { once: true }); +} + +void mount().catch((error: unknown) => { + document.body.textContent = `NextFloor konnte nicht geladen werden: ${error instanceof Error ? error.message : String(error)}`; +}); diff --git a/frontend/src/themes.ts b/frontend/src/themes.ts new file mode 100644 index 0000000..3c65029 --- /dev/null +++ b/frontend/src/themes.ts @@ -0,0 +1,50 @@ +// Looks of the 3D view, shared by the main bundle (settings, stage background) and the 3D bundle. + +export type Theme = "neon" | "blueprint" | "day"; + +export const THEMES: Theme[] = ["neon", "blueprint", "day"]; + +/** A look to pick: one of the looks, or "auto" – day while the sun is up, neon after sunset. */ +export type Look = Theme | "auto"; + +export const LOOKS: Look[] = ["auto", ...THEMES]; + +/** The look to draw now: "auto" follows sun.sun (day above the horizon, else neon; neon when there is no sun entity). */ +export function lookNow(look: Look | undefined, sunState: string | undefined): Theme { + if (look !== "auto") return look ?? "neon"; + return sunState === "above_horizon" ? "day" : "neon"; +} + +/** Background of the 3D stage per look (sky in the middle, ground at the edges), night and day. */ +export const STAGE: Record = { + neon: { + night: [ + [11, 17, 32], + [7, 11, 20], + ], + day: [ + [26, 44, 78], + [12, 20, 36], + ], + }, + blueprint: { + night: [ + [26, 70, 130], + [10, 38, 78], + ], + day: [ + [34, 86, 150], + [14, 48, 96], + ], + }, + day: { + night: [ + [214, 224, 238], + [176, 190, 210], + ], + day: [ + [242, 246, 251], + [205, 216, 230], + ], + }, +}; diff --git a/frontend/src/tiles.test.ts b/frontend/src/tiles.test.ts new file mode 100644 index 0000000..7c0455a --- /dev/null +++ b/frontend/src/tiles.test.ts @@ -0,0 +1,23 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { tileBlob } from "./tiles.ts"; + +test("every tile is fetched with an explicit referrer policy, once, and a refused tile gives null", async () => { + const calls: { url: string; init: RequestInit }[] = []; + const real = globalThis.fetch; + globalThis.fetch = (async (url: string, init: RequestInit) => { + calls.push({ url, init }); + return url.endsWith("/ok.png") ? new Response(new Uint8Array([1, 2, 3]), { status: 200, headers: { "content-type": "image/png" } }) : new Response("blocked", { status: 403, headers: { "content-type": "text/html" } }); + }) as typeof fetch; + try { + const a = await tileBlob("https://tiles.example/1/ok.png"); + const again = await tileBlob("https://tiles.example/1/ok.png"); + assert.equal((a as Blob).size, 3); + assert.equal(again, a, "the same promise: one request"); + assert.equal(await tileBlob("https://tiles.example/2/refused.png"), null); + assert.equal(calls.length, 2); + assert.ok(calls.every((c) => c.init.referrerPolicy === "strict-origin-when-cross-origin" && c.init.credentials === "omit")); + } finally { + globalThis.fetch = real; + } +}); diff --git a/frontend/src/tiles.ts b/frontend/src/tiles.ts new file mode 100644 index 0000000..ee32864 --- /dev/null +++ b/frontend/src/tiles.ts @@ -0,0 +1,49 @@ +// Map tiles for the real map under the plan. OpenStreetMap's tile servers refuse requests without a Referer, and Home Assistant's pages ask +// the browser to send none to other sites (`referrer: same-origin`). So every tile is fetched with an explicit referrer policy: the browser +// sends the page's origin (not the full address), which is what the usage policy asks for. + +const POLICY: ReferrerPolicy = "strict-origin-when-cross-origin"; +const blobs = new Map>(); +const objectUrls = new Map(); +const waiting = new Map void>>(); + +/** The tile as a picture, or null when the server refused it (retried after a minute). */ +export function tileBlob(url: string): Promise { + let p = blobs.get(url); + if (!p) { + p = fetch(url, { referrerPolicy: POLICY, mode: "cors", credentials: "omit" }) + .then(async (res) => (res.ok && (res.headers.get("content-type") ?? "").startsWith("image/") ? await res.blob() : null)) + .catch(() => null) + .then((blob) => { + if (!blob) setTimeout(() => blobs.delete(url), 60000); + return blob; + }); + blobs.set(url, p); + } + return p; +} + +/** A tile for an `` or SVG ``: its object URL once loaded, otherwise null (and `onReady` is called when it has arrived). */ +export function tileObjectUrl(url: string, onReady: () => void): string | null { + const have = objectUrls.get(url); + if (have) return have; + let set = waiting.get(url); + if (!set) { + set = new Set(); + waiting.set(url, set); + void tileBlob(url).then((blob) => { + if (blob) objectUrls.set(url, URL.createObjectURL(blob)); + const callbacks = waiting.get(url) ?? new Set(); + waiting.delete(url); + if (blob) for (const cb of callbacks) cb(); + }); + } + set.add(onReady); + return null; +} + +/** Frees the pictures (the map was switched off or moved elsewhere). */ +export function forgetTiles(): void { + for (const u of objectUrls.values()) URL.revokeObjectURL(u); + objectUrls.clear(); +} diff --git a/frontend/src/transfer.test.ts b/frontend/src/transfer.test.ts new file mode 100644 index 0000000..17cf9c6 --- /dev/null +++ b/frontend/src/transfer.test.ts @@ -0,0 +1,207 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, newFloor, type Building } from "./model.ts"; +import { exportFile, EXPORT_FORMAT, parseExport, shareViewHtml, storedImageIds, withoutEntities } from "./transfer.ts"; + +function linked(): Building { + const b = emptyBuilding(); + const floor = newFloor("g", "Ground", 0); + floor.rooms = [{ id: "r", name: "Room", area_id: "living", points: [[0, 0], [4, 0], [4, 3], [0, 3]], floor_material: "wood" }]; + floor.placements = [{ entity_id: "light.a", x: 1, z: 1, y: null, mount: null }]; + floor.furniture = [{ id: "tv", type: "tv", x: 1, z: 1, rotation: 0, w: 1, d: 0.1, h: 0.6, variant: null, entity: "media_player.tv", power: "sensor.tv_power", pictures: [{ entity: "", state: "", image: "abc123" }, { entity: "", state: "", image: "https://example.org/a.png" }, { entity: "", state: "", image: "camera:front" }] }]; + floor.background = { image_id: "bg1", x: 0, z: 0, width: 10, rotation: 0, opacity: 0.5 } as never; + b.floors = [floor]; + b.presence = [{ person: "person.a", sensor: "sensor.a" }]; + b.energy = { ...b.energy, grid: "sensor.grid", solar: "sensor.solar" }; + return b; +} + +test("a shareable copy has no entity, area, person or background left", () => { + const original = linked(); + const copy = withoutEntities(original); + assert.equal(copy.floors[0].placements.length, 0); + assert.equal(copy.floors[0].rooms[0].area_id, null); + assert.equal(copy.floors[0].furniture[0].entity, null); + assert.equal(copy.floors[0].furniture[0].power, null); + assert.equal(copy.floors[0].background, null); + assert.deepEqual([copy.presence, copy.energy.grid, copy.energy.solar], [[], null, null]); + // the original stays as it was + assert.equal(original.floors[0].rooms[0].area_id, "living"); + assert.equal(original.energy.grid, "sensor.grid"); +}); + +test("exportFile wraps the plan and shareable or not decides about the links", () => { + const full = exportFile(linked(), false); + assert.equal(full.format, EXPORT_FORMAT); + assert.equal(full.building.floors[0].placements.length, 1); + assert.equal(exportFile(linked(), true).building.floors[0].placements.length, 0); + assert.ok(!Number.isNaN(Date.parse(full.exported_at))); +}); + +test("a written file reads back, with or without the wrapper", () => { + const wrapped = parseExport(JSON.stringify(exportFile(linked(), false))); + assert.equal(wrapped.floors[0].name, "Ground"); + assert.equal(wrapped.floors[0].background, null, "pictures do not travel"); + assert.equal(parseExport(JSON.stringify(linked())).floors.length, 1); +}); + +test("garbage is told apart: not JSON versus JSON that is no plan", () => { + assert.throws(() => parseExport("{oops"), /not_json/); + assert.throws(() => parseExport("[1,2]"), /not_plan/); + assert.throws(() => parseExport(JSON.stringify({ version: 2, floors: [], settings: {} })), /not_plan/); + assert.throws(() => parseExport("null"), /not_plan/); +}); + +test("stored picture ids come from backgrounds and screens, once, never URLs or cameras", () => { + const b = linked(); + b.floors[0].furniture[0].pictures!.push({ entity: "", state: "", image: "abc123" }); + assert.deepEqual(storedImageIds(b).sort(), ["abc123", "bg1"]); +}); + +test("a hand- or AI-written plan without ids gets one per piece, so its doors and windows can be selected", () => { + const plan = { + floors: [ + { + name: "Ground", + elevation: 0, + height: 2.6, + rooms: [{ name: "Garage", points: [[0, 0], [6, 0], [6, 4], [0, 4]] }], + openings: [ + { room_id: "r1", edge: 0, offset: 2, type: "door" }, + { id: "o", room_id: "r1", edge: 1, offset: 1, type: "window", width: 1 }, + { id: "o", room_id: "r1", edge: 2, offset: 3, type: "garage_door" }, + ], + furniture: [], + placements: [], + }, + ], + }; + const floor = parseExport(JSON.stringify(plan)).floors[0]; + const ids = floor.openings.map((o) => o.id); + assert.equal(new Set(ids).size, 3); + assert.ok(ids.every((id) => typeof id === "string" && id.length > 0)); + assert.equal(floor.openings[1].id, "o", "the first of a repeated id keeps it"); + assert.ok(floor.rooms[0].id); + assert.ok(floor.openings[0].width > 0 && floor.openings[0].height > 0); + assert.equal(floor.openings[2].type, "door", "an unknown kind becomes a door the form can change"); +}); + +test("the smallest plan in docs/plan-format.md imports", async () => { + const { readFileSync } = await import("node:fs"); + const doc = readFileSync(new URL("../../docs/plan-format.md", import.meta.url), "utf8"); + const json = doc.split("```json\n")[1].split("```")[0]; + const b = parseExport(json); + assert.equal(b.floors[0].rooms.length, 2); + assert.deepEqual(b.floors[0].openings.map((o) => o.type), ["door", "window", "garage"]); + assert.equal(b.floors[0].openings[2].width, 2.5); + assert.equal(b.floors[0].rooms[0].floor_material, "wood"); +}); + +test("a shared view embeds the plan without entities and only the packs it uses", () => { + const b = emptyBuilding(); + b.floors = [{ ...newFloor("g", "EG ", 0), placements: [{ entity_id: "light.x", x: 1, z: 1, y: null, mount: null }], furniture: [{ id: "f", type: "pack:own_studio:shelf", x: 1, z: 1, rotation: 0, w: 1, d: 1, h: 1, variant: null }] }]; + const own = { id: "own_studio", name: "Own", publisher: "Me", items: [] }; + const other = { id: "other", name: "Other", publisher: "Me", items: [] }; + const html = shareViewHtml(b, [own, other, { ...own, id: "nextfloor.ikea", builtin: true }], "Our home", "needs js", "https://example.org/preview/?shared"); + const json = html.match(/")); + const data = JSON.parse(json); + assert.equal(data.building.floors[0].name, "EG "); + assert.equal(data.building.floors[0].placements.length, 0); + assert.deepEqual(data.packs.map((p: { id: string }) => p.id), ["own_studio"]); + assert.ok(html.includes('src="https://example.org/preview/?shared"')); +}); + +// A plan with a link to Home Assistant in every place the model has one: nothing of it may stay in a shared copy. +function leaky(): Building { + const b = linked(); + b.settings = { + ...b.settings, + map: { on: true, lat: 52.52, lon: 13.405 }, + favorites: ["scene.movie", "script.goodnight"], + buttons: [{ id: "b1", label: "Blinds", icon: "", action: "more_info", target: "cover.living", data: null } as never], + own_alerts: [{ id: "a1", name: "Tank", entity: "sensor.tank", state: "<20" } as never], + calendars: ["calendar.family"], + status_entities: ["sensor.outside_temp"], + circuits: [{ id: "c1", name: "F12 kitchen", rooms: ["r"] }], + weather_entity: "weather.home", + rain_sensor: "binary_sensor.rain", + outage_sensor: "binary_sensor.grid_lost", + announce_tts: "tts.cloud", + announce_phrases: ["Dinner at 6, the code is 1234"], + media_presets: [{ id: "m1", label: "Radio", type: "music", content: "x", speakers: ["media_player.kitchen"] }], + backdrop: { color: "#112233", image: "/local/private/garden.jpg", dim: 0.3 }, + plugins: [{ url: "/local/nextfloor/my-plugin.js" } as never], + wall_exterior: 0.3, + north: 40, + }; + b.energy = { ...b.energy, consumption: "sensor.house_w", gas: "sensor.gas", water: "sensor.water", battery: "sensor.bat", battery_soc: "sensor.soc", tariff: "sensor.tariff" }; + const floor = b.floors[0]; + floor.ha_floor = "ground_floor"; + floor.power_entity = "sensor.floor_power"; + Object.assign(floor.rooms[0], { sub_areas: ["reading_corner"], panel: ["sensor.x"], hidden: ["light.y"], no_state: ["cover.z"], clean_entity: "script.clean_living", floor_heating: "climate.floor", announce_speaker: "media_player.living", moods: [{ id: "m", name: "Movie", lights: [{ entity_id: "light.a", on: true }] }], climate: { temperature: "sensor.t", humidity: "sensor.h" } }); + Object.assign(floor.furniture[0], { + temp_entity: "sensor.fridge_t", + cover_entity: "cover.curtain", + state_entity: "binary_sensor.bed", + gang_entities: ["switch.a", null], + show_when: { entity: "input_boolean.xmas", state: "on" }, + tap: { action: "service", target: "light.turn_on", data: null }, + picture: "/local/family.jpg", + car: { device: "0123456789abcdef0123456789abcdef", soc: "sensor.car_soc" }, + types: [{ state: "home", vehicle: "car" }], + }); + floor.furniture.push({ id: "frame", type: "picture_frame", x: 2, z: 2, rotation: 0, w: 0.5, d: 0.05, h: 0.4, variant: null, picture: "image:abc123" } as never); + floor.furniture.push({ id: "cam", type: "picture_frame", x: 3, z: 2, rotation: 0, w: 0.5, d: 0.05, h: 0.4, variant: null, picture: "camera.front_door" } as never); + floor.openings = [{ id: "o", type: "door", room_id: "r", edge: 0, offset: 0.5, width: 0.9, height: 2, cover: "cover.a", contact: "binary_sensor.d", tilt: "sensor.tilt", lock: "lock.front" } as never]; + floor.outdoor = [{ id: "pool", type: "pool", points: [[0, 0], [1, 0], [1, 1]], area_id: "garden", temp_entity: "sensor.pool_t", pump_entity: "switch.pump" } as never]; + return b; +} + +test("a shared copy keeps nothing that names, locates or controls this Home Assistant", () => { + const copy = withoutEntities(leaky()); + const text = JSON.stringify(copy); + // no entity id as a value or as a key anywhere, no device id + assert.doesNotMatch(text, /"(?:alarm_control_panel|binary_sensor|button|calendar|camera|climate|cover|fan|input_[a-z]+|light|lock|media_player|person|scene|script|sensor|switch|tts|weather)\.[a-z0-9_]+"/); + assert.doesNotMatch(text, /[0-9a-f]{32}/); + // the map position, favourites, buttons, alerts, calendars, fuse box, plugins and phrases are gone, the look stays + const s = copy.settings as unknown as Record; + for (const k of ["map", "favorites", "buttons", "own_alerts", "calendars", "status_entities", "circuits", "weather_entity", "rain_sensor", "outage_sensor", "announce_tts", "announce_phrases", "media_presets", "plugins"]) assert.equal(s[k], undefined, k); + assert.equal(s.wall_exterior, 0.3); + assert.equal(s.north, 40); + assert.deepEqual(s.backdrop, { color: "#112233", dim: 0.3 }); + assert.doesNotMatch(text, /52\.52|13\.405|\/local\/|Dinner|F12 kitchen|garden\.jpg/); + // areas, the Home Assistant floor, room links, moods and own actions are cleared + const floor = copy.floors[0]; + assert.equal(floor.ha_floor, null); + assert.equal(floor.outdoor[0].area_id, null); + assert.deepEqual([floor.rooms[0].sub_areas, floor.rooms[0].panel, floor.rooms[0].hidden, floor.rooms[0].no_state], [null, [], [], []]); + assert.equal(floor.rooms[0].moods, undefined); + assert.equal(floor.furniture[0].tap, undefined); + assert.equal(floor.furniture[0].show_when, undefined); + assert.equal(floor.furniture[0].pictures, undefined); + // a stored picture travels, a /local file or a camera does not + assert.equal(floor.furniture.find((f) => f.id === "frame")!.picture, "image:abc123"); + assert.equal(floor.furniture.find((f) => f.id === "cam")!.picture, null); + assert.equal(floor.furniture[0].picture, null); + // what makes the house the house stays + assert.equal(floor.rooms[0].points.length, 4); + assert.equal(floor.furniture[0].type, "tv"); + assert.equal(floor.openings[0].type, "door"); +}); + +test("the share view embeds the cleaned plan only", () => { + const html = shareViewHtml(leaky(), [], "House", "needs JS"); + assert.doesNotMatch(html, /sensor\.|light\.|52\.52|calendar\.family|scene\.movie/); +}); + +test("withoutEntities leaves the original untouched and its result still reads back", () => { + const original = leaky(); + const before = JSON.stringify(original); + const copy = withoutEntities(original); + assert.equal(JSON.stringify(original), before); + const back = parseExport(JSON.stringify(exportFile(original, true))); + assert.equal(back.floors[0].rooms[0].points.length, 4); + assert.equal(back.settings.wall_exterior, 0.3); + assert.ok(copy.settings); +}); diff --git a/frontend/src/transfer.ts b/frontend/src/transfer.ts new file mode 100644 index 0000000..c68e888 --- /dev/null +++ b/frontend/src/transfer.ts @@ -0,0 +1,176 @@ +// Plan files: save the building as JSON and load it again. A shareable copy has every link to this Home Assistant +// removed (entities, areas, energy sensors, people, the map position, favourites, own buttons), so it can go to someone else. + +import { normalizeBuilding, type Building } from "./model.ts"; +import type { FurniturePack } from "./packs.ts"; + +export const EXPORT_FORMAT = "nextfloor"; + +export interface ExportFile { + format: typeof EXPORT_FORMAT; + version: 1; + exported_at: string; + building: Building; +} + +// Home Assistant entity ids ("light.kitchen", "sensor.grid_power"): a known domain, a dot, a slug. +const ENTITY_DOMAINS = + "alarm_control_panel|automation|binary_sensor|button|calendar|camera|climate|conversation|cover|date|datetime|device_tracker|event|fan|group|humidifier|image|input_boolean|input_button|input_datetime|input_number|input_select|input_text|lawn_mower|light|lock|media_player|notify|number|person|remote|scene|script|select|sensor|siren|stt|sun|switch|text|time|timer|todo|tts|update|vacuum|valve|water_heater|weather|zone"; +const ENTITY_ID = new RegExp(`^(?:${ENTITY_DOMAINS})\\.[a-z0-9_]+$`); +const DEVICE_ID = /^[0-9a-f]{32}$/; +/** Keys whose value is a Home Assistant area or floor, whatever it looks like. */ +const AREA_KEYS = new Set(["area_id", "ha_floor"]); +const AREA_LIST_KEYS = new Set(["sub_areas"]); +/** Whole fields that only work with a Home Assistant behind them and are dropped from a shared copy. */ +const DROPPED_KEYS = new Set(["tap", "show_when", "pictures", "moods"]); + +/** + * Cuts every remaining link to this Home Assistant out of a value, whatever field it sits in: strings that are entity or device ids become + * null (or leave a list), object keys that are entity ids go, areas and the Home Assistant floor are cleared. It runs on top of the + * explicit clean-up in `withoutEntities`, so a field that is added to the model later cannot leak through by being forgotten there. + */ +function scrub(value: unknown): unknown { + if (typeof value === "string") return ENTITY_ID.test(value) || DEVICE_ID.test(value) ? null : value; + if (Array.isArray(value)) return value.map((v) => scrub(v)).filter((v) => v !== null); + if (value && typeof value === "object") { + const out: Record = {}; + for (const [k, v] of Object.entries(value)) { + if (ENTITY_ID.test(k) || DROPPED_KEYS.has(k)) continue; + if (AREA_KEYS.has(k)) out[k] = null; + else if (AREA_LIST_KEYS.has(k)) out[k] = null; + else out[k] = scrub(v); + } + return out; + } + return value; +} + +/** The only building settings a shared copy keeps: how the house looks, nothing that names, locates or controls anything of the original. */ +const SHARED_SETTINGS = [ + "wall_exterior", + "wall_interior", + "wall_paint_outside", + "wall_paint_inside", + "grid", + "north", + "roof", + "weather_effects", + "rain_warning", + "sun_patches", + "lock_plan", + "start_view", + "units", + "motion_markers_active", + "room_double_tap", +] as const; + +/** + * The building with all links to Home Assistant cut: entities, areas, energy sensors, people, the map position, favourites, own buttons and + * alerts, calendars, status entities, the fuse box and plugins. Background pictures are dropped as well. Settings are built from an + * allowlist; floors, energy and the rest are cleaned explicitly and then scrubbed of anything that still looks like an entity. + */ +export function withoutEntities(source: Building): Building { + const copy = structuredClone(source); + const settings: Record = {}; + for (const k of SHARED_SETTINGS) if (copy.settings?.[k] !== undefined) settings[k] = copy.settings[k]; + // the backdrop keeps its colour, but its picture may be a file of this Home Assistant + const backdrop = copy.settings?.backdrop; + if (backdrop && (backdrop.color || backdrop.dim != null)) settings.backdrop = { color: backdrop.color ?? null, dim: backdrop.dim ?? null }; + copy.settings = settings as unknown as Building["settings"]; + copy.energy = { ...copy.energy, grid: null, solar: null, battery: null, battery_soc: null, tariff: null, consumption: null, gas: null, water: null }; + copy.presence = []; + for (const floor of copy.floors) { + floor.background = null; + floor.placements = []; + floor.power_entity = null; + floor.ha_floor = null; + for (const room of floor.rooms) { + Object.assign(room, { area_id: null, sub_areas: null, panel: [], hidden: [], no_state: [] }); + } + floor.furniture.forEach((piece) => { + Object.assign(piece, { entity: null, power: null }); + delete piece.effect_animations; // HA program names are private, like entity links. + // a picture frame's photo: only a stored picture or an https address travels, not /local files, cameras or media players + if (piece.picture && !(piece.picture.startsWith("image:") || piece.picture.startsWith("https://"))) piece.picture = null; + }); + floor.openings.forEach((opening) => Object.assign(opening, { cover: null, contact: null, tilt: null })); + } + return scrub(copy) as Building; +} + +export function exportFile(building: Building, shareable: boolean): ExportFile { + return { + format: EXPORT_FORMAT, + version: 1, + exported_at: new Date().toISOString(), + building: shareable ? withoutEntities(building) : structuredClone(building), + }; +} + +// a plan written by hand or by an AI may leave out the version and the settings; normalizeBuilding fills them in +const looksLikePlan = (b: Building | undefined): b is Building => !!b && (b.version === 1 || b.version === undefined) && Array.isArray(b.floors) && b.floors.every((f) => !!f && typeof f === "object"); + +/** Where shared views open: the online demo of the released version, which takes the plan by message. */ +export const SHARE_VIEWER = "https://therealmrbk.github.io/NextFloor/preview/?shared&noshowcase"; + +/** + * The house as a small page of its own: it embeds the online demo and hands it the plan (without the entities, like a template) and + * the furniture packs it uses, so it opens in any browser without Home Assistant. + */ +export function shareViewHtml(building: Building, packs: readonly FurniturePack[], title: string, note: string, viewer = SHARE_VIEWER): string { + const used = new Set(building.floors.flatMap((f) => f.furniture.map((m) => m.type)).filter((t) => t.startsWith("pack:")).map((t) => t.split(":")[1])); + const data = { building: withoutEntities(building), packs: packs.filter((p) => !p.builtin && used.has(p.id)) }; + const json = JSON.stringify(data).replace(/ s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]!); + return ` +${esc(title)} + + + + + +`; +} + +/** Reads an export file (or a bare building). Throws Error("not_json") or Error("not_plan"). */ +export function parseExport(text: string): Building { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + throw new Error("not_json"); + } + const wrapped = parsed as Partial | null; + const candidate = (wrapped?.format === EXPORT_FORMAT ? wrapped.building : parsed) as Building | undefined; + if (!looksLikePlan(candidate)) throw new Error("not_plan"); + candidate.floors.forEach((floor) => (floor.background = null)); // pictures never travel with a file + return normalizeBuilding(candidate); +} + +const isStoredImage = (ref: string) => !/^https?:\/\//.test(ref) && !ref.startsWith("camera:"); + +/** Ids of the uploaded pictures a plan uses: floor backgrounds and pictures on screens (not URLs, not cameras). */ +export function storedImageIds(building: Building): string[] { + const ids = new Set(); + for (const floor of building.floors) { + if (floor.background?.image_id) ids.add(floor.background.image_id); + const refs = floor.furniture.flatMap((piece) => piece.pictures ?? []); + for (const { image } of refs) if (image && isStoredImage(image)) ids.add(image); + } + return [...ids]; +} + +/** Offers a text as a file download. */ +export function download(filename: string, text: string, type = "application/json"): void { + const link = document.createElement("a"); + const href = URL.createObjectURL(new Blob([text], { type })); + Object.assign(link, { href, download: filename }); + link.click(); + setTimeout(() => URL.revokeObjectURL(href), 1000); +} diff --git a/frontend/src/types.ts b/frontend/src/types.ts new file mode 100644 index 0000000..f2f97b1 --- /dev/null +++ b/frontend/src/types.ts @@ -0,0 +1,72 @@ +// The parts of the Home Assistant frontend object this integration uses. + +/** Floor of Home Assistant's floor registry (hass.floors). */ +export interface HassFloor { + floor_id: string; + name: string; + level?: number | null; +} + +export interface HassArea { + area_id: string; + name: string; + floor_id?: string | null; +} + +/** Entry of the entity registry as the frontend sees it (hass.entities). */ +export interface HassEntityEntry { + entity_id: string; + name?: string | null; + device_id?: string | null; + area_id?: string | null; + hidden?: boolean; + entity_category?: "config" | "diagnostic" | null; + /** The integration's key for the entity (e.g. "current_room"). */ + translation_key?: string | null; + /** Decimals set for a sensor in Home Assistant (null = default). */ + display_precision?: number | null; + /** The integration that provides the entity (e.g. "alexa_devices"). */ + platform?: string | null; +} + +export interface HassDevice { + id: string; + area_id?: string | null; + name?: string | null; + name_by_user?: string | null; +} + +export interface HassEntity { + entity_id: string; + state: string; + attributes: Record; + last_changed?: string; + /** Last time the state or any attribute changed: a map camera's attributes only move when it renders. */ + last_updated?: string; +} + +export interface HassConnection { + subscribeMessage(callback: (msg: T) => void, msg: Record): Promise<() => Promise>; +} + +export interface HomeAssistant { + language: string; + user?: { is_admin: boolean; name: string }; + areas?: Record; + floors?: Record; + entities?: Record; + devices?: Record; + states: Record; + config?: { unit_system?: { temperature?: string }; latitude?: number; longitude?: number; time_zone?: string }; + /** Home Assistant's theme state: `darkMode` is false in a light theme. */ + themes?: { darkMode?: boolean }; + connection: HassConnection; + callWS(msg: Record): Promise; + /** fetch() with the logged-in user's token (Home Assistant's frontend provides it). */ + fetchWithAuth?(path: string, init?: Record): Promise; + callService(domain: string, service: string, data?: Record): Promise; + /** The actions Home Assistant offers, by domain (to show a button only where its action exists). */ + services?: Record>; + /** A path on the Home Assistant server as a full URL (Home Assistant's frontend provides it). */ + hassUrl?(path?: string): string; +} diff --git a/frontend/src/units.test.ts b/frontend/src/units.test.ts new file mode 100644 index 0000000..b15763f --- /dev/null +++ b/frontend/src/units.test.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { formatArea, formatLength } from "./units.ts"; + +const de = { language: "de" } as Parameters[0]; + +test("lengths in metres or in feet and inches to the half inch", () => { + assert.equal(formatLength(de, 3.456, 2, "metric"), "3,46 m"); + assert.equal(formatLength(de, 3.456, 2, "imperial"), "11′ 4″"); + assert.equal(formatLength(de, 0.9, 2, "imperial"), "2′ 11½″"); + assert.equal(formatLength(de, 0.1, 2, "imperial"), "4″"); + assert.equal(formatLength(de, 0.3048, 2, "imperial"), "1′ 0″"); +}); + +test("areas in square metres or square feet", () => { + assert.equal(formatArea(de, 18.42, "metric"), "18,4 m²"); + assert.equal(formatArea(de, 18.42, "imperial"), "198 ft²"); +}); diff --git a/frontend/src/units.ts b/frontend/src/units.ts new file mode 100644 index 0000000..3ce46f4 --- /dev/null +++ b/frontend/src/units.ts @@ -0,0 +1,32 @@ +// Lengths and areas as the plan wants them shown: metres, or feet and inches. Inputs stay in metres; only what is shown changes. + +import { formatNumber } from "./i18n.ts"; +import type { HomeAssistant } from "./types.ts"; + +export type Units = "metric" | "imperial"; + +let current: Units = "metric"; + +/** The units of the plan being shown (the editor sets them from the plan's settings). */ +export const setUnits = (units: Units | null | undefined): void => { + current = units === "imperial" ? "imperial" : "metric"; +}; +export const getUnits = (): Units => current; + +const FOOT = 0.3048; + +/** A length: "3,45 m", or 11′ 4½″ (feet and inches to the half inch). */ +export function formatLength(hass: HomeAssistant | undefined, metres: number, digits = 2, units: Units = current): string { + if (units === "metric") return `${formatNumber(hass, metres, digits)} m`; + const sign = metres < 0 ? "−" : ""; + const halves = Math.round((Math.abs(metres) / 0.0254) * 2); + const feet = Math.floor(halves / 24); + const inchHalves = halves - feet * 24; + const inches = `${Math.floor(inchHalves / 2)}${inchHalves % 2 ? "½" : ""}`; + return feet ? `${sign}${feet}′ ${inches}″` : `${sign}${inches}″`; +} + +/** An area: "18,4 m²" or "198 ft²". */ +export function formatArea(hass: HomeAssistant | undefined, squareMetres: number, units: Units = current): string { + return units === "metric" ? `${formatNumber(hass, squareMetres, 1)} m²` : `${formatNumber(hass, squareMetres / (FOOT * FOOT), 0)} ft²`; +} diff --git a/frontend/src/viewer/build.ts b/frontend/src/viewer/build.ts new file mode 100644 index 0000000..4b748cb --- /dev/null +++ b/frontend/src/viewer/build.ts @@ -0,0 +1,10 @@ +// The merged geometry of one floor, split into modules in build/. + +export { buildFloorGeometry, stairHoles } from "./build/build.ts"; +export { FLOOR_LOOK, NEON, SLAB } from "./build/look.ts"; +export { clipAlong, outlineOf } from "./build/outline.ts"; +export { wallHeight } from "./build/placement.ts"; +export type { FloorGeometry, OpeningInfo } from "./build/types.ts"; +export type { WallPaint } from "./build/build.ts"; +export { wallPaintOf } from "./build/solids.ts"; +export { ALWAYS, CUT_OFFSET, GeoBuffer, LineBuffer, pushPrism, shade } from "./geo.ts"; diff --git a/frontend/src/viewer/build/build.test.ts b/frontend/src/viewer/build/build.test.ts new file mode 100644 index 0000000..2c53ed1 --- /dev/null +++ b/frontend/src/viewer/build/build.test.ts @@ -0,0 +1,271 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { BufferGeometry } from "three"; +import { generateWalls } from "../../geometry/walls.ts"; +import { newFloor, offsetAt, type Floor, type Furniture, type Opening, type Room, type Vec2 } from "../../model.ts"; +import { ALWAYS, CUT_OFFSET, LOWER_OFFSET } from "../geo.ts"; +import { buildFloorGeometry, stairHoles } from "./build.ts"; +import { bucketWalls, placeOpenings, roofLimits, wallHeight, wallTops } from "./placement.ts"; +import { clipAlong, counterClockwise, outlineOf, subtractSpans } from "./outline.ts"; +import { mountBase } from "../../packs.ts"; + +const OUTER = 0.3; +const INNER = 0.1; + +const room = (id: string, x0: number, z0: number, x1: number, z1: number): Room => ({ id, name: id, area_id: null, points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]], floor_material: "wood" }); +const floorOf = (rooms: Room[], openings: Opening[] = [], furniture: Furniture[] = []): Floor => ({ ...newFloor("f", "F", 0), height: 2.6, cut_height: 1.2, rooms, openings, furniture }); +const opening = (type: "door" | "window", roomId: string, edge: number, offset: number, width = 1): Opening => + ({ id: `${type}${edge}`, room_id: roomId, edge, offset, width, type, sill: type === "door" ? 0 : 0.9, height: type === "door" ? 2.05 : 1.3, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null }) as Opening; +const near = (a: number, b: number, eps = 1e-6) => assert.ok(Math.abs(a - b) < eps, `${a} vs ${b}`); + +type Seg = { from: number[]; to: number[]; fold: number }; +const segments = (g: BufferGeometry): Seg[] => { + const p = g.getAttribute("position").array; + const f = g.getAttribute("fold").array; + return Array.from({ length: p.length / 6 }, (_, s) => ({ from: [p[s * 6], p[s * 6 + 1], p[s * 6 + 2]], to: [p[s * 6 + 3], p[s * 6 + 4], p[s * 6 + 5]], fold: f[s * 2] })); +}; +const triangles = (g: BufferGeometry) => g.getAttribute("position").count / 3; +const horizontal = (s: Seg, y: number) => Math.abs(s.from[1] - y) < 1e-6 && Math.abs(s.to[1] - y) < 1e-6; // positions are 32-bit floats +const length = (s: Seg) => Math.hypot(s.to[0] - s.from[0], s.to[2] - s.from[2]); + +test("walls fall into buckets: all interior walls in one, exterior walls by the direction they face", () => { + const { walls } = generateWalls([room("a", 0, 0, 4, 3), room("b", 4, 0, 8, 3)], { exterior: OUTER, interior: INNER }); + const { buckets, wallBucket } = bucketWalls(walls); + const interior = walls.filter((w) => !w.exterior); + assert.equal(new Set(interior.map((w) => wallBucket.get(w))).size, 1); + const outside = walls.filter((w) => w.exterior); + assert.equal(buckets.filter((b) => b === null).length, 1); + assert.ok(new Set(outside.map((w) => wallBucket.get(w))).size >= 3, "north, south, east and west"); + for (const b of buckets) if (b) near(Math.hypot(b[0], b[1]), 1); + assert.equal(buckets.length, new Set([...wallBucket.values()]).size); +}); + +test("a wall stands at the floor height, a low wall keeps its own height, a tall room's wall rises above the floor", () => { + const { walls } = generateWalls([room("a", 0, 0, 4, 3)], { exterior: OUTER, interior: INNER }); + assert.equal(wallHeight(walls[0], 2.6), 2.6); + assert.equal(wallHeight({ ...walls[0], height: 1 }, 2.6), 1); + assert.equal(wallHeight({ ...walls[0], height: 5 }, 2.6), 5); +}); + +test("roof limits: the top of a wall is its height unless a lower roof is above", () => { + const free = roofLimits(undefined); + assert.equal(free.topAt(0, 0, 2.6), 2.6); + assert.equal(free.lowestTop([0, 0], [1, 0], 0, 3, 2.6), 2.6); + const under = roofLimits((x) => (x < 2 ? 1.8 : null)); + assert.equal(under.topAt(1, 0, 2.6), 1.8); + assert.equal(under.topAt(3, 0, 2.6), 2.6); + assert.equal(roofLimits(() => 0.01).topAt(0, 0, 2.6), 0.05, "never below 5 cm"); + assert.equal(under.lowestTop([0, 0], [1, 0], 0, 4, 2.6), 1.8); +}); + +test("an opening is placed on its wall: width, side of the room, sill and top", () => { + const f = floorOf([room("a", 0, 0, 6, 4)], [opening("window", "a", 0, 3, 1.2), opening("door", "a", 3, 2, 0.9)]); + const { walls } = generateWalls(f.rooms, { exterior: OUTER, interior: INNER }); + const { wallBucket } = bucketWalls(walls); + const { openings, spans } = placeOpenings(f, walls, wallBucket, roofLimits(undefined)); + assert.equal(openings.length, 2); + const win = openings.find((o) => o.opening.type === "window")!; + near(win.width, 1.2); + near(win.sill, 0.9); + near(win.top, 2.2); + assert.equal(win.exterior, true); + // the room is on the side the wall's normal points to + const towardsCentre = [3 - win.start[0], 2 - win.start[1]]; + assert.ok(win.toRoom[0] * towardsCentre[0] + win.toRoom[1] * towardsCentre[1] > 0); + assert.equal([...spans.values()].flat().length, 2); + for (const list of spans.values()) for (const sp of list) assert.ok(sp.s1 - sp.s0 > 0.85); +}); + +test("an opening wider than its wall is shortened, one with no wall is dropped", () => { + const f = floorOf([room("a", 0, 0, 2, 2)], [opening("window", "a", 0, 1, 5), opening("window", "ghost", 0, 1)]); + const { walls } = generateWalls(f.rooms, { exterior: OUTER, interior: INNER }); + const { openings } = placeOpenings(f, walls, bucketWalls(walls).wallBucket, roofLimits(undefined)); + assert.equal(openings.length, 1); + assert.ok(openings[0].width <= 2 + 1e-9); +}); + +test("under a roof an opening's top stays below the roof", () => { + const f = floorOf([room("a", 0, 0, 6, 4)], [opening("window", "a", 0, 3, 1.2)]); + const { walls } = generateWalls(f.rooms, { exterior: OUTER, interior: INNER }); + const { openings } = placeOpenings(f, walls, bucketWalls(walls).wallBucket, roofLimits(() => 1.6)); + assert.ok(openings[0].top <= 1.6 - 0.02 + 1e-9); + assert.ok(openings[0].sill <= openings[0].top - 0.1 + 1e-9); +}); + +test("a polygon is clipped between two lines across a wall's axis", () => { + const square: Vec2[] = [[0, 0], [4, 0], [4, 1], [0, 1]]; + const piece = clipAlong(square, [0, 0], [1, 0], 1, 3); + assert.deepEqual(piece.map((p) => p[0]).sort(), [1, 1, 3, 3]); + assert.equal(clipAlong(square, [0, 0], [1, 0], -Infinity, Infinity).length, 4); + assert.equal(clipAlong(square, [0, 0], [1, 0], 5, 6).length, 0); + assert.equal(clipAlong(square, [0, 0], [1, 0], -Infinity, 2).length, 4); +}); + +test("a ring is turned counter-clockwise", () => { + const ring: Vec2[] = [[0, 0], [0, 1], [1, 1], [1, 0]]; + assert.deepEqual(counterClockwise(ring), [...ring].reverse()); + assert.equal(counterClockwise([...ring].reverse()).length, 4); +}); + +test("a single room has corner lines at all eight corners of its walls' outline", () => { + const f = floorOf([room("a", 0, 0, 4, 3)]); + const g = buildFloorGeometry(f, OUTER, INNER); + const { walls } = generateWalls(f.rooms, { exterior: OUTER, interior: INNER }); + assert.equal(outlineOf(walls, walls.flatMap((w) => w.footprint)).corners.length, 8); + const verticals = segments(g.lines).filter((s) => Math.abs(s.from[0] - s.to[0]) < 1e-9 && Math.abs(s.from[2] - s.to[2]) < 1e-9); + assert.ok(verticals.length >= 8); +}); + +test("a straight outer face across a T-joint gets no corner line", () => { + const { walls } = generateWalls([room("a", 0, 0, 4, 3), room("b", 4, 0, 8, 3)], { exterior: OUTER, interior: INNER }); + const outline = outlineOf(walls, walls.flatMap((w) => w.footprint)); + const onTopFace = outline.corners.filter((c) => Math.abs(c.p[0] - 4) < 1e-6 && c.p[1] < -0.1); + assert.equal(onTopFace.length, 0); +}); + +test("the baked shadow covers wall faces inside rooms and nothing outside", () => { + const g = buildFloorGeometry(floorOf([room("a", 0, 0, 4, 3)]), OUTER, INNER); + const p = Array.from(g.shadow.getAttribute("position").array); + const xs = p.filter((_, i) => i % 3 === 0); + const zs = p.filter((_, i) => i % 3 === 2); + assert.ok(Math.min(...xs) >= -1e-6 && Math.max(...xs) <= 4 + 1e-6, "inside the room"); + assert.ok(Math.min(...zs) >= -1e-6 && Math.max(...zs) <= 3 + 1e-6); + assert.ok(triangles(g.shadow) >= 8); +}); + +test("a door interrupts the base line and the shadow; a window does not", () => { + const plain = buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)]), OUTER, INNER); + const withDoor = buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [opening("door", "a", 0, 3, 1)]), OUTER, INNER); + const withWindow = buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [opening("window", "a", 0, 3, 1)]), OUTER, INNER); + const baseLength = (g: ReturnType) => segments(g.lines).filter((s) => horizontal(s, 0.004)).reduce((sum, s) => sum + length(s), 0); + assert.ok(baseLength(plain) - baseLength(withDoor) > 0.9); + near(baseLength(plain), baseLength(withWindow), 1e-6); + assert.ok(triangles(plain.shadow) < triangles(withDoor.shadow) + 4); + const strip = (g: ReturnType) => Array.from(g.shadow.getAttribute("position").array).filter((_, i) => i % 3 === 0); + assert.ok(strip(withDoor).length > 0); +}); + +test("a window above the cut height keeps the cut line, one across it interrupts it", () => { + const cutLine = (g: ReturnType) => segments(g.lines).filter((s) => horizontal(s, 1.2) && s.fold >= CUT_OFFSET && s.fold < LOWER_OFFSET); + const high = { ...opening("window", "a", 0, 3, 1), sill: 1.5, height: 0.8 }; + const across = opening("window", "a", 0, 3, 1); + const total = (g: ReturnType) => cutLine(g).reduce((sum, s) => sum + length(s), 0); + const plain = total(buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)]), OUTER, INNER)); + near(total(buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [high]), OUTER, INNER)), plain, 1e-6); + assert.ok(plain - total(buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [across]), OUTER, INNER)) > 0.9); +}); + +test("an opening makes the wall around it: pieces beside, below and above, but none in the opening", () => { + const plain = triangles(buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)]), OUTER, INNER).walls); + const holed = triangles(buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [opening("window", "a", 0, 3, 1)]), OUTER, INNER).walls); + assert.ok(holed > plain, "a window cuts the wall into more pieces"); +}); + +test("furniture is built into the walls buffer with its triangle range; lamps are left to the viewer", () => { + const sofa: Furniture = { id: "s", type: "sofa", x: 3, z: 2, rotation: 0, w: 2, d: 0.9, h: 0.8, variant: null, entity: null, power: null }; + const lamp: Furniture = { ...sofa, id: "l", type: "lamp_ceiling" }; + const g = buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [], [sofa, lamp]), OUTER, INNER); + assert.deepEqual(g.furnitureTris.map((t) => t.id), ["s"]); + assert.ok(g.furnitureTris[0].end > g.furnitureTris[0].start); + assert.equal(g.furnitureTris[0].end <= triangles(g.walls), true); +}); + +test("furniture reaching above the cut height is cut with the walls", () => { + const wardrobe: Furniture = { id: "w", type: "wardrobe", x: 3, z: 2, rotation: 0, w: 1, d: 0.6, h: 2.2, variant: null, entity: null, power: null }; + const g = buildFloorGeometry(floorOf([room("a", 0, 0, 6, 4)], [], [wardrobe]), OUTER, INNER); + const folds = Array.from(g.walls.getAttribute("fold").array); + assert.ok(folds.some((f) => f >= 64), "pieces above the cut fold away"); + assert.ok(folds.includes(ALWAYS)); +}); + +test("a floor opening cuts a hole into the room floor and gets a rim line", () => { + const f = floorOf([room("a", 0, 0, 6, 4)]); + const whole = buildFloorGeometry(f, OUTER, INNER); + const holed = buildFloorGeometry(f, OUTER, INNER, [[[1, 1], [2, 1], [2, 2], [1, 2]]]); + assert.equal(whole.holes.length, 0); + assert.equal(holed.holes.length, 1); + assert.ok(triangles(holed.floor) > triangles(whole.floor)); + assert.ok(segments(holed.lines).length > segments(whole.lines).length); +}); + +test("every room gets a range of floor triangles for picking, with its colour", () => { + const g = buildFloorGeometry(floorOf([room("a", 0, 0, 3, 3), { ...room("b", 3, 0, 6, 3), floor_material: "tiles" }]), OUTER, INNER); + assert.deepEqual(g.roomTris.map((r) => r.roomId), ["a", "b"]); + assert.ok(g.roomTris.every((r) => r.end > r.start)); + assert.notEqual(g.roomTris[0].color, g.roomTris[1].color); +}); + +test("stairs and stairwells cut holes into the floor above", () => { + const stairs: Furniture = { id: "st", type: "stairs", x: 2, z: 2, rotation: 0, w: 1, d: 3, h: 2.6, variant: null, entity: null, power: null }; + const lower = { ...floorOf([room("a", 0, 0, 6, 4)], [], [stairs]), id: "g", elevation: 0 }; + const upper = { ...floorOf([room("b", 0, 0, 6, 4)]), id: "u", elevation: 2.7 }; + assert.equal(stairHoles([lower, upper], upper).length, 1); + assert.equal(stairHoles([lower, upper], lower).length, 0); + const well: Furniture = { ...stairs, id: "w", type: "stairwell", h: 0.1 }; + const withWell = { ...upper, furniture: [well] }; + assert.equal(stairHoles([lower, withWell], withWell).length, 1, "a stairwell on its own floor"); + assert.equal(stairHoles([lower, { ...withWell, furniture: [well, { ...well, id: "w2", x: 2.5 }] }], { ...withWell, furniture: [well, { ...well, id: "w2", x: 2.5 }] }).length, 1, "overlapping ones merge"); +}); + +test("subtracting spans from an edge leaves the free parts, in the edge's direction", () => { + const { walls } = generateWalls([room("a", 0, 0, 6, 4)], { exterior: OUTER, interior: INNER }); + const outline = outlineOf(walls, walls.flatMap((w) => w.footprint)); + const edge = outline.edges.find((e) => Math.abs(e.a[1] - e.b[1]) < 1e-9 && Math.abs(Math.abs(e.a[0] - e.b[0]) - 6) < 0.7)!; + const fake = (s0: number, s1: number) => ({ s0, s1, sill: 0, top: 2, info: {} as never }); + assert.equal(subtractSpans(edge, []).length, 1); + const parts = subtractSpans(edge, [fake(2, 3)]); + assert.equal(parts.length, 2); + const total = parts.reduce((sum, [a, b]) => sum + Math.hypot(b[0] - a[0], b[1] - a[1]), 0); + near(total, Math.hypot(edge.b[0] - edge.a[0], edge.b[1] - edge.a[1]) - 1, 1e-6); + assert.equal(subtractSpans(edge, [fake(-10, 100)]).length, 0, "everything covered"); +}); + +test("a sloping wall: its top follows the slope, above the floor height too; openings stay under it", () => { + const sloped: Room = { ...room("a", 0, 0, 4, 3), wall_heights: [null, 2.5, null, null], wall_slopes: [null, 4.7, null, null] }; + const f = floorOf([sloped]); + const { walls } = generateWalls(f.rooms, { exterior: OUTER, interior: INNER }); + const wall = walls.find((w) => Math.abs(w.a[0] - 4) < 1e-6 && Math.abs(w.b[0] - 4) < 1e-6)!; + assert.equal(wallHeight(wall, 2.6), 4.7, "the highest point counts, even above the floor height"); + const [lowEnd, highEnd] = wall.a[1] < wall.b[1] ? [wall.a, wall.b] : [wall.b, wall.a]; + const tops = wallTops(wall, 2.6, roofLimits(undefined)); + near(tops.topAt(lowEnd[0], lowEnd[1]), 2.5); + near(tops.topAt(highEnd[0], highEnd[1]), 4.7); + near(tops.topAt((lowEnd[0] + highEnd[0]) / 2, (lowEnd[1] + highEnd[1]) / 2), 3.6); + near(tops.lowestTop(0, 3), 2.5); + // a roof lower than the slope still wins + near(wallTops(wall, 2.6, roofLimits(() => 3)).topAt(highEnd[0], highEnd[1]), 3); + // a window near the high end may be taller than one near the low end + const windowOf = (offset: number) => ({ ...opening("window", "a", 1, offset, 0.8), sill: 1, height: 2.5 }) as Opening; + const { openings } = placeOpenings({ ...f, openings: [windowOf(0.5), windowOf(2.5)] }, walls, bucketWalls(walls).wallBucket, roofLimits(undefined)); + const [first, second] = openings; + assert.ok(first.top < second.top, "the one at the high end reaches higher"); + assert.ok(first.top <= 2.6 + 1e-6 && second.top <= 4.7); + // and the walls build without error + const geo = buildFloorGeometry(f, OUTER, INNER); + const ys = Array.from(geo.walls.getAttribute("position").array).filter((_, i) => i % 3 === 1); + assert.ok(Math.max(...ys) > 4.6, "the wall is drawn up to its high end"); +}); + +test("a room on its own level: its floor, its walls' bottom and its doors move with it (#57)", () => { + const hall = { ...room("h", 0, 0, 3, 3), floor_offset: -0.39 }; + const living = room("l", 3, 0, 7, 3); + const floor = { ...newFloor("g", "G", 0), rooms: [hall, living], openings: [{ id: "d", room_id: "h", edge: 3, offset: 1.5, width: 1, type: "door", sill: 0, height: 2.1, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null } as Opening] }; + const walls = generateWalls(floor.rooms, { exterior: OUTER, interior: INNER }).walls; + const { openings } = placeOpenings(floor, walls, new Map(walls.map((w, i) => [w, i])), roofLimits(undefined)); + assert.equal(openings[0].sill, -0.39); + assert.ok(Math.abs(openings[0].top - (2.1 - 0.39)) < 1e-9); + assert.equal(offsetAt(floor, 1, 1), -0.39); + assert.equal(offsetAt(floor, 5, 1), 0); + assert.equal(mountBase(floor, { type: "sofa", x: 1, z: 1, h: 0.8 }), -0.39); +}); + +test("the floor of a room on its own level is drawn at its level, with the step to the rooms around it", () => { + const hall = { ...room("h", 0, 0, 3, 3), floor_offset: -0.39 }; + const floor = { ...newFloor("g", "G", 0), rooms: [hall, room("l", 3, 0, 7, 3)] }; + const g = buildFloorGeometry(floor, OUTER, INNER, []); + const pos = g.floor.getAttribute("position"); + const hallTris = g.roomTris.find((r) => r.roomId === "h")!; + for (let i = hallTris.start * 3; i < hallTris.end * 3; i++) assert.ok(Math.abs(pos.getY(i) + 0.39) < 1e-6); + const living = g.roomTris.find((r) => r.roomId === "l")!; + assert.ok(Math.abs(pos.getY(living.start * 3)) < 1e-6); +}); diff --git a/frontend/src/viewer/build/build.ts b/frontend/src/viewer/build/build.ts new file mode 100644 index 0000000..9192dff --- /dev/null +++ b/frontend/src/viewer/build/build.ts @@ -0,0 +1,121 @@ +// Builds the merged, vertex-coloured geometry of one floor: room floors with material patterns, walls with door and window +// openings, edge lines and baked wall shadows. +// +// Walls are grouped into buckets by the direction they face. Every vertex carries a "fold" value and a shader patch (see +// fold.ts) decides per bucket: in the cut view the upper parts disappear; in the tall view the walls turned towards the +// camera are drawn as tinted glass instead. +// fold = -1 always visible, never glass (furniture, lines of the lower part) +// fold = b upper wall part: visible while bucket b stands +// fold = 16 + b cut edge: visible while bucket b is cut +// fold = 32 + b lower wall part: always visible, glass when the bucket is +// fold = 48 + b top face of the lower part at the cut height: visible while bucket b is cut + +import { generateWalls } from "../../geometry/walls.ts"; +import { mergeHoles } from "../../geometry/holes.ts"; +import { isShapedStair, stairOpeningInPlan } from "../../geometry/stairs.ts"; +import { furnitureFootprint, isLamp, roomsReachingUp, type Floor, type SolarField, type Vec2 } from "../../model.ts"; +import { hasMesh, mountBase, packItem } from "../../packs.ts"; +import type { RoofFace } from "../../solar.ts"; +import { cutAbove, cutLinesAbove, FURN_OFFSET, GeoBuffer, LineBuffer } from "../geo.ts"; +import { pushFurniture } from "../furniture.ts"; +import { pushOutdoor } from "../outdoor.ts"; +import { pushModules } from "../roof.ts"; +import { pushEdgeLines } from "./edges.ts"; +import { buildFloors } from "./floors.ts"; +import { outlineOf } from "./outline.ts"; +import { bucketWalls, placeOpenings, roofLimits } from "./placement.ts"; +import { buildShadow } from "./shadow.ts"; +import { buildWallSolids, type WallPaint } from "./solids.ts"; +import type { FloorGeometry } from "./types.ts"; + +export function buildFloorGeometry( + floor: Floor, + wallExterior: number, + wallInterior: number, + holes: Vec2[][] = [], + /** Solar fields standing in this floor's garden, with their ground. */ + solar: { face: RoofFace; field: SolarField }[] = [], + /** + * The roof's underside above a plan point, relative to this floor (null = no roof there). Walls end there: knee walls + * at the eaves, gables up to the ridge, inner walls cut by the slope. + */ + roofUnder?: (x: number, z: number) => number | null, + /** Painted walls for the solid wall view (see WallPaint). */ + paint?: WallPaint, +): FloorGeometry { + const { walls, open: openRooms } = generateWalls(floor.rooms, { exterior: wallExterior, interior: wallInterior }, floor.walls ?? []); + const limits = roofLimits(roofUnder); + const hasRoof = !!roofUnder; + + const floors = buildFloors(floor, holes); + const { buckets, wallBucket } = bucketWalls(walls); + const { openings, spans } = placeOpenings(floor, walls, wallBucket, limits); + + const wallBuf = new GeoBuffer(); + buildWallSolids(wallBuf, floor, walls, wallBucket, spans, limits, hasRoof, paint); + + const outline = outlineOf(walls, walls.flatMap((w) => w.footprint)); + const lines = new LineBuffer(); + lines.p.push(...floors.holeLines.p); + lines.c.push(...floors.holeLines.c); + lines.f.push(...floors.holeLines.f); + pushEdgeLines(lines, floor, outline, wallBucket, spans, limits, hasRoof); + + const shadow = buildShadow(outline.edges, floor.rooms, spans); + const ghosts = new Map(); + pushOutdoor(wallBuf, lines, floor, ghosts, () => new GeoBuffer()); + for (const s of solar) pushModules(wallBuf, lines, s.face, s.field, floor.elevation); + + // lamps are drawn live by the viewer: they glow with their light + const cut = Math.min(floor.cut_height, floor.height); + const furnitureTris: FloorGeometry["furnitureTris"] = []; + for (const piece of floor.furniture.filter((f) => !isLamp(f.type))) { + const start = wallBuf.count; + const firstLine = lines.p.length / 6; + const base = mountBase(floor, piece); + // an owned 3D model replaces the parts: the viewer adds it as its own object + if (!hasMesh(piece.type)) pushFurniture(wallBuf, lines, shadow, piece, base); + // a wardrobe or a stair reaching above the cut height is cut with the walls, so it hides nothing behind it + if (base + piece.h > cut + 0.05) { + cutAbove(wallBuf, start, cut, FURN_OFFSET); + cutLinesAbove(lines, firstLine, cut, FURN_OFFSET); + } + furnitureTris.push({ id: piece.id, start, end: wallBuf.count }); + } + + return { + floor: floors.buffer.geometry(), + roomTris: floors.roomTris, + holes: floors.cutHoles, + walls: wallBuf.geometry(), + ghosts: [...ghosts].map(([opacity, buffer]) => ({ opacity, geometry: buffer.geometry() })), + lines: lines.geometry(), + shadow: shadow.geometry(), + buckets, + openings, + walls2d: walls, + openRooms, + wallBuckets: walls.map((w) => wallBucket.get(w)!), + furnitureTris, + roofUnder, + }; +} + +/** The ceiling openings of a floor: stairwells placed on it, stairs on the floor below that reach up to it, and rooms below that rise through it. */ +export function stairHoles(floors: readonly Floor[], floor: Floor): Vec2[][] { + const voids = roomsReachingUp(floors, floor); + // stairwells, and the shaped stairs that lead down from this floor + const own = [ + ...floor.furniture.filter((f) => f.type === "stairwell").map(furnitureFootprint), + ...floor.furniture.filter((f) => isShapedStair(f) && f.stair?.down).flatMap(stairOpeningInPlan), + ].filter((ring) => ring.length >= 3); + const below = floors.filter((f) => f.elevation < floor.elevation).sort((p, q) => q.elevation - p.elevation)[0]; + if (!below) return mergeHoles([...own, ...voids]); + const reaching = below.furniture.filter((f) => (f.type === "stairs" || packItem(f.type)?.hole) && !(isShapedStair(f) && f.stair?.down) && below.elevation + f.h >= floor.elevation - 0.3); + // a shaped stair opens the floor only where its treads lack headroom; old stairs and pack stairs open their whole footprint + const stairs = reaching.flatMap((f) => (isShapedStair(f) ? stairOpeningInPlan(f) : [furnitureFootprint(f)])).filter((ring) => ring.length >= 3); + // overlapping openings become one outline (an L-shaped stairwell made of two) + return mergeHoles([...own, ...stairs, ...voids]); +} + +export type { WallPaint } from "./solids.ts"; diff --git a/frontend/src/viewer/build/edges.ts b/frontend/src/viewer/build/edges.ts new file mode 100644 index 0000000..e4c4b1e --- /dev/null +++ b/frontend/src/viewer/build/edges.ts @@ -0,0 +1,100 @@ +// The edge lines of the walls and openings: base line, cut line, top line (following a roof), corner verticals, and the +// jambs, sills and lintels of openings on both wall faces. + +import type { Wall } from "../../geometry/walls.ts"; +import type { Floor, Vec2 } from "../../model.ts"; +import { ALWAYS, CUT_OFFSET, EDGE_BASE, EDGE_CUT, EDGE_SOFT, EDGE_TOP, LOWER_OFFSET, type LineBuffer } from "../geo.ts"; +import type { Outline } from "./outline.ts"; +import { subtractSpans } from "./outline.ts"; +import { alongWall, glassJoins, joinPositions, spanEnds } from "./glass-joins.ts"; +import { wallTops, type roofLimits } from "./placement.ts"; +import type { Span } from "./types.ts"; + +/** A 2 cm grid, so an outline corner and a glass join meet at the same key despite rounding. */ +const pointKey = (p: readonly [number, number]) => `${Math.round(p[0] * 50)},${Math.round(p[1] * 50)}`; + +/** + * Jambs, sill and lintel edges of an opening on both wall faces, split at the cut height. A piece that joins + * another piece of the same pane has no jamb at that end: the glass runs on. + */ +function pushOpeningLines(lines: LineBuffer, sp: Span, cut: number, hideStart = false, hideEnd = false): void { + const { info } = sp; + const bucket = info.bucket; + const at = (s: number, n: number, y: number) => [info.start[0] + info.axis[0] * (s - sp.s0) + info.toRoom[0] * n, y, info.start[1] + info.axis[1] * (s - sp.s0) + info.toRoom[1] * n]; + const foldAt = (y: number) => (y > cut + 1e-6 ? bucket : ALWAYS); + // just above the floor the opening stands on (below 0 in a lowered room) + const bottom = sp.sill < 0 ? sp.sill + 0.004 : Math.max(sp.sill, 0.004); + for (const n of [info.faceRoom, -info.faceOut]) { + if (!hideStart) lines.segSplit(at(sp.s0, n, bottom), at(sp.s0, n, sp.top), EDGE_SOFT, cut, bucket); + if (!hideEnd) lines.segSplit(at(sp.s1, n, bottom), at(sp.s1, n, sp.top), EDGE_SOFT, cut, bucket); + lines.seg(at(sp.s0, n, sp.top), at(sp.s1, n, sp.top), EDGE_SOFT, foldAt(sp.top)); + if (sp.sill > 0.01) lines.seg(at(sp.s0, n, sp.sill), at(sp.s1, n, sp.sill), EDGE_SOFT, foldAt(sp.sill)); + } + // edges across the wall thickness (the reveals), and the cut section of the jambs + for (const [s, hide] of [[sp.s0, hideStart], [sp.s1, hideEnd]] as const) { + if (hide) continue; + lines.seg(at(s, info.faceRoom, sp.top), at(s, -info.faceOut, sp.top), EDGE_SOFT, foldAt(sp.top)); + if (sp.sill > 0.01) lines.seg(at(s, info.faceRoom, sp.sill), at(s, -info.faceOut, sp.sill), EDGE_SOFT, foldAt(sp.sill)); + if (sp.sill < cut && sp.top > cut) lines.seg(at(s, info.faceRoom, cut), at(s, -info.faceOut, cut), EDGE_CUT, CUT_OFFSET + bucket); + } +} + +export function pushEdgeLines( + lines: LineBuffer, + floor: Floor, + outline: Outline, + wallBucket: Map, + spans: Map, + limits: ReturnType, + hasRoof: boolean, +): void { + const cut = Math.min(floor.cut_height, floor.height); + const spansOf = (wall: Wall, keep: (sp: Span) => boolean) => (spans.get(wall) ?? []).filter(keep); + for (const edge of outline.edges) { + const bucket = wallBucket.get(edge.wall)!; + // the base line along the floor: not across doorways + for (const [p, q] of subtractSpans(edge, spansOf(edge.wall, (sp) => sp.sill <= 0.005))) lines.seg([p[0], 0.004, p[1]], [q[0], 0.004, q[1]], EDGE_BASE); + // the cut line: not where an opening crosses the cut height + for (const [p, q] of subtractSpans(edge, spansOf(edge.wall, (sp) => sp.sill < cut && sp.top > cut))) lines.seg([p[0], cut, p[1]], [q[0], cut, q[1]], EDGE_CUT, CUT_OFFSET + bucket); + // the top line: not where an opening reaches the top; a wall below the cut height keeps its top line; under a roof it follows the slope in short steps + const tops = wallTops(edge.wall, floor.height, limits); + const { H, topAt } = tops; + for (const [p, q] of subtractSpans(edge, spansOf(edge.wall, (sp) => sp.top >= H - 0.021))) { + if (!hasRoof && !tops.varies) { + lines.seg([p[0], H, p[1]], [q[0], H, q[1]], EDGE_TOP, H <= cut + 1e-6 ? LOWER_OFFSET + bucket : bucket); + continue; + } + const steps = Math.max(1, Math.ceil(Math.hypot(q[0] - p[0], q[1] - p[1]) / 0.3)); + const at = (i: number): Vec2 => [p[0] + ((q[0] - p[0]) * i) / steps, p[1] + ((q[1] - p[1]) * i) / steps]; + for (let i = 0; i < steps; i++) { + const [a, c] = [at(i), at(i + 1)]; + const [ya, yc] = [topAt(a[0], a[1]), topAt(c[0], c[1])]; + lines.seg([a[0], ya, a[1]], [c[0], yc, c[1]], EDGE_TOP, Math.max(ya, yc) <= cut + 1e-6 ? LOWER_OFFSET + bucket : bucket); + } + } + } + // where two pieces of one pane meet, the corner is not a jamb (glass-joins.ts is shared with the wall solids) + const joins = glassJoins(spans.values()); + const insidePane = new Set(joins.points.map(pointKey)); + // internal joins in wall coordinates: a footprint corner off the axis is not a point to compare with + const joinAt = new Map(); + for (const [wall, list] of spans) joinAt.set(wall, joinPositions(list, joins)); + for (const corner of outline.corners) { + // a corner inside a continuous pane has no wall vertical running through the glass: the pane runs on + // over the bend, so the wall only turns behind it + const s = alongWall(corner.wall, corner.p); + const list = spans.get(corner.wall) ?? []; + const inPane = list.some((sp) => !!sp.info.opening.front && s > sp.s0 + 0.05 && s < sp.s1 - 0.05); + const atJoin = (joinAt.get(corner.wall) ?? []).some((j) => Math.abs(j - s) < 0.06); + if (inPane || atJoin || insidePane.has(pointKey(corner.p))) continue; + const height = wallTops(corner.wall, floor.height, limits).topAt(corner.p[0], corner.p[1]); + lines.segSplit([corner.p[0], 0.004, corner.p[1]], [corner.p[0], height, corner.p[1]], EDGE_SOFT, Math.min(cut, height), wallBucket.get(corner.wall)!); + } + for (const list of spans.values()) { + for (const sp of list) { + const front = sp.info.opening.front; + const [p0, p1] = spanEnds(sp); + pushOpeningLines(lines, sp, cut, front ? joins.at(front, p0) : false, front ? joins.at(front, p1) : false); + } + } +} diff --git a/frontend/src/viewer/build/floors.ts b/frontend/src/viewer/build/floors.ts new file mode 100644 index 0000000..d1f214c --- /dev/null +++ b/frontend/src/viewer/build/floors.ts @@ -0,0 +1,71 @@ +// Room floors with their material pattern, the slab below them, and the rims of openings cut into the floor (stairwells). + +import { Color } from "three"; +import { holeInRoom, insetHole } from "../../geometry/holes.ts"; +import { roomOffset, type Floor, type Vec2 } from "../../model.ts"; +import { ALWAYS, EDGE_SOFT, EDGE_TOP, GeoBuffer, LineBuffer, triangulate } from "../geo.ts"; +import { counterClockwise } from "./outline.ts"; +import { FLOOR_LOOK, NEON, SLAB } from "./look.ts"; +import type { FloorGeometry } from "./types.ts"; + +export interface FloorParts { + buffer: GeoBuffer; + roomTris: FloorGeometry["roomTris"]; + /** The rims of the openings, to be added to the line buffer first. */ + holeLines: LineBuffer; + /** The openings that were actually cut into some room. */ + cutHoles: Vec2[][]; +} + +export function buildFloors(floor: Floor, holes: Vec2[][]): FloorParts { + const buffer = new GeoBuffer(true, true); + const roomTris: FloorGeometry["roomTris"] = []; + const holeLines = new LineBuffer(); + const cutHoles: Vec2[][] = []; + const slab = new Color(NEON.slab); + + /** The slab's side faces along a ring, from `y0` up to `y1`. */ + const slabSides = (ring: Vec2[], y1 = 0, y0 = y1 - SLAB) => { + ring.forEach((a, i) => { + const b = ring[(i + 1) % ring.length]; + buffer.tri([a[0], y0, a[1]], [a[0], y1, a[1]], [b[0], y1, b[1]], slab); + buffer.tri([a[0], y0, a[1]], [b[0], y1, b[1]], [b[0], y0, b[1]], slab); + }); + }; + + for (const room of floor.rooms) { + if (room.points.length < 3) continue; + const outline = counterClockwise(room.points); + const look = FLOOR_LOOK[room.floor_material] ?? FLOOR_LOOK.wood; + const top = new Color(look.color); + // an opening snapped to the room's edge is still cut, a few millimetres in from it + const inside = holes.filter((h) => holeInRoom(h, outline)).map((h) => insetHole(h, 0.003)); + cutHoles.push(...inside); + const corners = [...outline, ...inside.flat()]; + const start = buffer.count; + // a room on its own level (a sunken entrance, a split level): its floor lies lower or higher + const y = roomOffset(room); + for (const [i, j, k] of triangulate(outline, inside)) { + const [a, b, c] = [corners[i], corners[j], corners[k]]; + buffer.tri([a[0], y, a[1]], [c[0], y, c[1]], [b[0], y, b[1]], top, top, top, [a[0], a[1], c[0], c[1], b[0], b[1]], ALWAYS, look.tile); + } + roomTris.push({ roomId: room.id, start, end: buffer.count, color: look.color }); + slabSides(outline, y); + // the step between it and the floor's level, seen from both sides (from the lower room and from the rooms around it) + if (Math.abs(y) > 0.005) { + slabSides(outline, Math.max(0, y), Math.min(0, y)); + slabSides([...outline].reverse(), Math.max(0, y), Math.min(0, y)); + } + for (const hole of inside) { + // the hole's inner faces look into the hole + slabSides([...counterClockwise(hole)].reverse()); + hole.forEach((a, i) => { + const b = hole[(i + 1) % hole.length]; + // a bright rim like the walls' tops, so the opening reads from above + holeLines.seg([a[0], y + 0.006, a[1]], [b[0], y + 0.006, b[1]], EDGE_TOP); + holeLines.seg([a[0], y - SLAB, a[1]], [b[0], y - SLAB, b[1]], EDGE_SOFT); + }); + } + } + return { buffer, roomTris, holeLines, cutHoles }; +} diff --git a/frontend/src/viewer/build/glass-joins.test.ts b/frontend/src/viewer/build/glass-joins.test.ts new file mode 100644 index 0000000..206f536 --- /dev/null +++ b/frontend/src/viewer/build/glass-joins.test.ts @@ -0,0 +1,219 @@ +// The joins between the pieces of one pane: no jamb, no wall vertical and no wall surface may stand there, +// or the pane reads as several windows again. The same fixture without a `front` is the control: it must +// still show those, so the test can fail. +// +// What used to stand there is a mitre wedge: a wall's footprint runs up to the mitre line, a few centimetres +// past the wall's own end, so cutting the wall into pieces leaves a full-height wedge piece beyond the last +// opening. Its end face, outer sliver and mitre face are the bright vertical line seen through the glass. + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { generateWalls } from "../../geometry/walls.ts"; +import { newFloor, type Floor, type Opening, type Room, type Vec2 } from "../../model.ts"; +import { GeoBuffer, LineBuffer } from "../geo.ts"; +import { pushEdgeLines } from "./edges.ts"; +import { alongWall, glassJoins, joinPositions } from "./glass-joins.ts"; +import { outlineOf } from "./outline.ts"; +import { bucketWalls, placeOpenings, roofLimits } from "./placement.ts"; +import { buildWallSolids } from "./solids.ts"; + +const OUTER = 0.3; +const INNER = 0.1; +/** The height band a glass wall leaves empty: nothing solid may stand in it at a join. */ +const BAND: [number, number] = [0.1, 2.3]; + +/** A room whose outer side is an arc of `n` edges of `seg` metres, each turning `turn` degrees, closed by one straight edge. */ +function arcRoom(n = 8, seg = 1, turn = 30): Room { + const points: Vec2[] = [[0, 0]]; + let [x, z] = [0, 0]; + let a = 0; + for (let i = 0; i < n; i++) { + a += (turn * Math.PI) / 180; + x += Math.cos(a) * seg; + z += Math.sin(a) * seg; + points.push([x, z]); + } + return { id: "r", name: "r", area_id: null, points, floor_material: "wood" }; +} + +const glass = (id: string, edge: number, front: string | null): Opening => + ({ + id, + room_id: "r", + edge, + offset: 0.5, + width: 1, + type: "window", + style: "glass_wall", + sill: 0, + height: 2.4, + hinge: "left", + leaves: 1, + swing: "in", + cover: null, + contact: null, + contact2: null, + tilt: null, + ...(front ? { front } : {}), + }) as Opening; + +/** Three 1 m pieces on the first three edges of the arc, either one pane (a shared front) or three windows. */ +function scene(front: string | null) { + const room = arcRoom(); + const floor: Floor = { + ...newFloor("f", "F", 0), + height: 2.6, + cut_height: 1.2, + rooms: [room], + openings: [glass("a", 0, front), glass("b", 1, front), glass("c", 2, front)], + furniture: [], + }; + const { walls } = generateWalls(floor.rooms, { exterior: OUTER, interior: INNER }, []); + const limits = roofLimits(() => null); + const { wallBucket } = bucketWalls(walls); + const { spans } = placeOpenings(floor, walls, wallBucket, limits); + const outline = outlineOf(walls, walls.flatMap((w) => w.footprint)); + const lines = new LineBuffer(); + pushEdgeLines(lines, floor, outline, wallBucket, spans, limits, false); + const solids = new GeoBuffer(); + buildWallSolids(solids, floor, walls, wallBucket, spans, limits, false); + return { room, floor, walls, spans, lines, solids }; +} + +/** Vertical line segments whose plan position is within 5 cm of `p`. */ +function verticalLinesAt(lines: LineBuffer, p: Vec2): number { + const v: number[] = (lines as unknown as { p: number[] }).p; + let found = 0; + for (let i = 0; i + 5 < v.length; i += 6) { + const [x0, y0, z0, x1, y1, z1] = [v[i], v[i + 1], v[i + 2], v[i + 3], v[i + 4], v[i + 5]]; + if (Math.abs(y1 - y0) < 0.6) continue; + if (Math.hypot(x0 - p[0], z0 - p[1]) > 0.05 && Math.hypot(x1 - p[0], z1 - p[1]) > 0.05) continue; + found++; + } + return found; +} + +/** Distance in plan from `p` to the triangle `abc`, zero inside it. */ +function planDistance(p: Vec2, a: Vec2, b: Vec2, c: Vec2): number { + const cross = (o: Vec2, u: Vec2, v: Vec2) => (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0]); + const [s1, s2, s3] = [cross(a, b, p), cross(b, c, p), cross(c, a, p)]; + if ((s1 >= 0 && s2 >= 0 && s3 >= 0) || (s1 <= 0 && s2 <= 0 && s3 <= 0)) return 0; + const toSegment = (u: Vec2, w: Vec2) => { + const [dx, dz] = [w[0] - u[0], w[1] - u[1]]; + const len2 = dx * dx + dz * dz; + const t = len2 < 1e-12 ? 0 : Math.max(0, Math.min(1, ((p[0] - u[0]) * dx + (p[1] - u[1]) * dz) / len2)); + return Math.hypot(p[0] - (u[0] + dx * t), p[1] - (u[1] + dz * t)); + }; + return Math.min(toSegment(a, b), toSegment(b, c), toSegment(c, a)); +} + +/** The axis of the wall that ends at `p`: a face is a divider when it runs across that wall. */ +function axisAt(walls: { a: Vec2; b: Vec2 }[], p: Vec2): Vec2 { + const w = walls.find((x) => Math.hypot(x.b[0] - p[0], x.b[1] - p[1]) < 1e-6) ?? walls.find((x) => Math.hypot(x.a[0] - p[0], x.a[1] - p[1]) < 1e-6)!; + const len = Math.hypot(w.b[0] - w.a[0], w.b[1] - w.a[1]) || 1; + return [(w.b[0] - w.a[0]) / len, (w.b[1] - w.a[1]) / len]; +} + +/** + * Wall faces that read as a divider in the glass at `p`: the face runs across the wall — a jamb, or the + * seam beside a mitre — its plan projection covers `p`, and it reaches into the height band the pane + * leaves empty. A face along the wall is the wall surface and no divider, a sliver of no length is no + * surface, and the wall above a 2.4 m pane is out of the band. + */ +function facesInGlass(solids: GeoBuffer, p: Vec2, axis: Vec2, band: [number, number] = BAND): number { + const v: number[] = (solids as unknown as { p: number[] }).p; + let found = 0; + for (let i = 0; i + 8 < v.length; i += 9) { + const ys = [v[i + 1], v[i + 4], v[i + 7]]; + const [lo, hi] = [Math.min(...ys), Math.max(...ys)]; + if (lo > band[1] || hi < band[0] || hi - lo < 0.05) continue; + const [a, b, c]: Vec2[] = [ + [v[i], v[i + 2]], + [v[i + 3], v[i + 5]], + [v[i + 6], v[i + 8]], + ]; + const across = Math.max(Math.hypot(b[0] - a[0], b[1] - a[1]), Math.hypot(c[0] - b[0], c[1] - b[1]), Math.hypot(c[0] - a[0], c[1] - a[1])); + if (across < 0.01) continue; + if (Math.abs(((c[0] - a[0]) * axis[0] + (c[1] - a[1]) * axis[1]) / across) > 0.5) continue; + if (planDistance(p, a, b, c) > 0.02) continue; + found++; + } + return found; +} + +/** + * How much wall surface stands in the glass band around `p`, in square metres. Unlike `facesInGlass` + * this counts every face, whatever way it runs: the strip that shows from outside at a bend runs along + * the wall, so a test that only looks at cross-sections cannot see it. + */ +function wallInGlass(solids: GeoBuffer, p: Vec2, radius = 0.35, band: [number, number] = BAND): number { + const v: number[] = (solids as unknown as { p: number[] }).p; + let area = 0; + for (let i = 0; i + 8 < v.length; i += 9) { + const ys = [v[i + 1], v[i + 4], v[i + 7]]; + const [lo, hi] = [Math.min(...ys), Math.max(...ys)]; + if (lo > band[1] || hi < band[0] || hi - lo < 0.05) continue; + const pts: Vec2[] = [ + [v[i], v[i + 2]], + [v[i + 3], v[i + 5]], + [v[i + 6], v[i + 8]], + ]; + const cx = (pts[0][0] + pts[1][0] + pts[2][0]) / 3; + const cz = (pts[0][1] + pts[1][1] + pts[2][1]) / 3; + if (Math.hypot(cx - p[0], cz - p[1]) > radius) continue; + const across = Math.max( + Math.hypot(pts[1][0] - pts[0][0], pts[1][1] - pts[0][1]), + Math.hypot(pts[2][0] - pts[1][0], pts[2][1] - pts[1][1]), + Math.hypot(pts[2][0] - pts[0][0], pts[2][1] - pts[0][1]), + ); + if (across < 0.01) continue; // a degenerate sliver is no surface at all + area += across * (hi - lo); + } + return area; +} + +test("where two pieces of one pane meet, no jamb and no wall surface stand in the glass", () => { + const { room, walls, spans, lines, solids } = scene("F"); + const joins = glassJoins(spans.values()); + assert.equal(joins.points.length, 2, "two internal joins for three pieces"); + for (const p of joins.points) { + assert.equal(verticalLinesAt(lines, p), 0, `no vertical line at ${p}`); + assert.equal(facesInGlass(solids, p, axisAt(walls, p)), 0, `no wall face in the glass at ${p}`); + // the mitre of a bend leaves a strip of wall on the outer face, a few centimetres wide and full + // height: from outside it stands in front of the glass and reads as a white line at every bend + assert.ok(wallInGlass(solids, p) < 0.02, `no wall surface in the glass at ${p}`); + } + // the same points in wall coordinates, which is what the solids and the corner filter use + for (const wall of [...spans.keys()]) { + const positions = joinPositions(spans.get(wall)!, joins); + for (const s of positions) assert.ok(s >= -0.001 && s <= 1.5, `join at ${s} m on its wall`); + } + assert.ok(room.points.length > 3); +}); + +test("the control: three separate glass walls do show a jamb and a wall surface at the same points", () => { + const { room, walls, lines, solids } = scene(null); + const corner = room.points[1]; + assert.ok(verticalLinesAt(lines, corner) > 0, "a separate glass wall keeps its jamb"); + assert.ok(facesInGlass(solids, corner, axisAt(walls, corner)) > 0, "and the wall end stands in the glass"); + assert.ok(wallInGlass(solids, corner) > 1, "lots of it, so the measure above can fail"); +}); + +test("joinPosition is the wall coordinate of a piece end, not a guessed distance", () => { + const { walls, spans } = scene("F"); + const joins = glassJoins(spans.values()); + let seen = 0; + for (const [wall, list] of spans) { + const at = joinPositions(list, joins); + seen += at.length; + for (const sp of list) { + for (const s of at) { + // a join is either the span's start or its end on this wall + assert.ok(Math.abs(s - sp.s0) < 1e-9 || Math.abs(s - sp.s1) < 1e-9, "a join sits on a span end"); + assert.ok(alongWall(wall, wall.a) < 1e-9, "wall coordinates start at wall.a"); + } + } + } + assert.equal(seen, 4, "two joints, each seen from both of its walls"); + assert.equal(walls.length, 9, "eight arc edges and the closing one"); +}); diff --git a/frontend/src/viewer/build/glass-joins.ts b/frontend/src/viewer/build/glass-joins.ts new file mode 100644 index 0000000..3953b2e --- /dev/null +++ b/frontend/src/viewer/build/glass-joins.ts @@ -0,0 +1,74 @@ +// Pieces of one glass pane that follows a curved wall are placed as separate spans that share a `front` id. +// Where two of them meet, the wall must not draw a jamb or a solid end face: the glass is continuous there. +// The edge-line layer and the wall-solid layer both use this one definition, so they cannot disagree about +// which corners are internal. + +import type { Vec2 } from "../../model.ts"; +import type { Wall } from "../../geometry/walls.ts"; +import type { Span } from "./types.ts"; + +type Point = readonly [number, number]; + +/** The two ends of an opening span in plan coordinates. */ +export function spanEnds(sp: Span): [Point, Point] { + const { start, axis, width } = sp.info; + return [ + [start[0], start[1]], + [start[0] + axis[0] * width, start[1] + axis[1] * width], + ]; +} + +/** A 2 cm grid, so two pieces of one pane meet at the same key despite rounding. */ +const key = (front: string, p: Point): string => `${front}|${Math.round(p[0] * 50)},${Math.round(p[1] * 50)}`; + +export interface GlassJoins { + /** World positions where two pieces of the same pane meet. */ + points: Vec2[]; + /** Whether this end of a span is an internal join of its own pane. */ + at(front: string, p: Point): boolean; +} + +/** + * Where along `wall` a piece of a pane ends at an internal join. The wall solids and the edge lines work + * in wall coordinates (`s` from `wall.a`), so they use this instead of comparing world points: the corner + * of a footprint sits half a wall thickness off the axis, and a distance test there is a guess. + */ +export function joinPositions(list: readonly Span[], joins: GlassJoins): number[] { + const out: number[] = []; + for (const sp of list) { + const front = sp.info.opening.front; + if (!front) continue; + const [p0, p1] = spanEnds(sp); + if (joins.at(front, p0)) out.push(sp.s0); + if (joins.at(front, p1)) out.push(sp.s1); + } + return out; +} + +/** How far `p` lies along `wall` from its start, in metres. */ +export function alongWall(wall: Wall, p: Vec2): number { + const length = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]) || 1; + return ((p[0] - wall.a[0]) * (wall.b[0] - wall.a[0]) + (p[1] - wall.a[1]) * (wall.b[1] - wall.a[1])) / length; +} + +/** Every place where two spans of the same pane share an end. */ +export function glassJoins(lists: Iterable>): GlassJoins { + const count = new Map(); + const pos = new Map(); + for (const list of lists) { + for (const sp of list) { + const front = sp.info.opening.front; + if (!front) continue; + for (const p of spanEnds(sp)) { + const k = key(front, p); + count.set(k, (count.get(k) ?? 0) + 1); + if (!pos.has(k)) pos.set(k, [p[0], p[1]]); + } + } + } + const points = [...count] + .filter(([, n]) => n > 1) + .map(([k]) => pos.get(k)) + .filter((p): p is Vec2 => !!p); + return { points, at: (front, p) => (count.get(key(front, p)) ?? 0) > 1 }; +} diff --git a/frontend/src/viewer/build/look.ts b/frontend/src/viewer/build/look.ts new file mode 100644 index 0000000..a7931f1 --- /dev/null +++ b/frontend/src/viewer/build/look.ts @@ -0,0 +1,26 @@ +// Colours and sizes of the floor geometry. + +/** The base colours of the neon look. */ +export const NEON = { + floor: 0x0e1629, + slab: 0x0a1120, + wall: 0x131d31, + wallTop: 0x14303f, + edge: 0x37e0ff, + edgeSoft: 0x5b7cff, +}; + +/** The floor tint and the pattern tile (column, row in the pattern atlas) per floor material. */ +export const FLOOR_LOOK: Record = { + wood: { color: 0x111a2e, tile: [0, 0] }, + oak: { color: 0x131b2d, tile: [1, 0] }, + tiles: { color: 0x0e182f, tile: [2, 0] }, + carpet: { color: 0x10152b, tile: [0, 1] }, + stone: { color: 0x0f172b, tile: [1, 1] }, + concrete: { color: 0x111827, tile: [2, 1] }, +}; + +/** The thickness of the floor slab below the floor. */ +export const SLAB = 0.2; +/** Exterior walls are sorted into this many compass sectors; each sector is one fold bucket. */ +export const SECTORS = 8; diff --git a/frontend/src/viewer/build/outline.ts b/frontend/src/viewer/build/outline.ts new file mode 100644 index 0000000..f41d3f2 --- /dev/null +++ b/frontend/src/viewer/build/outline.ts @@ -0,0 +1,141 @@ +// The outline of the walls' footprints, and helpers to cut and clip along a wall. + +import type { Wall } from "../../geometry/walls.ts"; +import type { Vec2 } from "../../model.ts"; +import type { Span } from "./types.ts"; + +export const unit = (v: Vec2): Vec2 => { + const length = Math.hypot(v[0], v[1]) || 1; + return [v[0] / length, v[1] / length]; +}; + +/** A ring running counter-clockwise, whichever way it was given. */ +export function counterClockwise(points: Vec2[]): Vec2[] { + const area = points.reduce((sum, p, i) => sum + p[0] * points[(i + 1) % points.length][1] - points[(i + 1) % points.length][0] * p[1], 0); + return area >= 0 ? points : [...points].reverse(); +} + +/** Keeps the part of a polygon on the positive side of a line (Sutherland-Hodgman against one half-plane). */ +function clipHalfPlane(poly: Vec2[], distance: (p: Vec2) => number): Vec2[] { + const kept: Vec2[] = []; + poly.forEach((a, i) => { + const b = poly[(i + 1) % poly.length]; + const [da, db] = [distance(a), distance(b)]; + if (da >= 0) kept.push(a); + if (da >= 0 !== db >= 0) { + const k = da / (da - db); + kept.push([a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k]); + } + }); + return kept; +} + +/** The part of a polygon between two lines perpendicular to `axis` (t is measured from `origin`). */ +export function clipAlong(poly: Vec2[], origin: Vec2, axis: Vec2, t0: number, t1: number): Vec2[] { + const t = (p: Vec2) => (p[0] - origin[0]) * axis[0] + (p[1] - origin[1]) * axis[1]; + let kept = poly; + if (Number.isFinite(t0)) kept = clipHalfPlane(kept, (p) => t(p) - t0); + if (Number.isFinite(t1)) kept = clipHalfPlane(kept, (p) => t1 - t(p)); + return kept; +} + +export interface OutlineEdge { + a: Vec2; + b: Vec2; + wall: Wall; +} + +export interface Outline { + /** The edges of the merged wall footprints (joints between walls left out), counter-clockwise per wall. */ + edges: OutlineEdge[]; + /** The vertices where the outline turns a corner, with a wall they belong to. */ + corners: { p: Vec2; wall: Wall }[]; +} + +const millimetres = (v: number) => Math.round(v * 1000); +const vertexKey = (p: Vec2) => `${millimetres(p[0])},${millimetres(p[1])}`; +const edgeKey = (a: Vec2, b: Vec2) => { + const [s, t] = [vertexKey(a), vertexKey(b)]; + return s < t ? `${s}|${t}` : `${t}|${s}`; +}; + +/** The edges of a polygon, split wherever one of `points` lies on them, so T-joints line up. */ +function splitAtPoints(poly: Vec2[], points: Vec2[]): [Vec2, Vec2][] { + const pieces: [Vec2, Vec2][] = []; + poly.forEach((a, i) => { + const b = poly[(i + 1) % poly.length]; + const [dx, dz] = [b[0] - a[0], b[1] - a[1]]; + const squared = dx * dx + dz * dz; + if (squared < 1e-8) return; + const cuts = points + .map((p) => ({ t: ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / squared, off: Math.abs((p[0] - a[0]) * dz - (p[1] - a[1]) * dx) / Math.sqrt(squared) })) + .filter(({ t, off }) => t > 1e-6 && t < 1 - 1e-6 && off < 1e-4) + .map(({ t }) => t) + .sort((p, q) => p - q); + let previous = a; + for (const t of cuts) { + const cut: Vec2 = [a[0] + dx * t, a[1] + dz * t]; + if (vertexKey(cut) !== vertexKey(previous)) pieces.push([previous, cut]); + previous = cut; + } + pieces.push([previous, b]); + }); + return pieces; +} + +/** + * The outline of the walls' footprints: the edges no other footprint shares, and the vertices where those edges change + * direction. Edges are split at `points` first, so an edge partly covered by another wall (a T-joint) keeps only its free part. + */ +export function outlineOf(walls: Wall[], points: Vec2[]): Outline { + const pieces = walls.map((wall) => ({ wall, edges: splitAtPoints(wall.footprint, points) })); + const uses = new Map(); + for (const { edges } of pieces) for (const [a, b] of edges) uses.set(edgeKey(a, b), (uses.get(edgeKey(a, b)) ?? 0) + 1); + + const edges: OutlineEdge[] = []; + const directions = new Map(); + const note = (p: Vec2, wall: Wall, d: Vec2) => { + const key = vertexKey(p); + if (!directions.has(key)) directions.set(key, { p, wall, d: [] }); + directions.get(key)!.d.push(d); + }; + for (const { wall, edges: list } of pieces) { + for (const [a, b] of list) { + const length = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (uses.get(edgeKey(a, b)) !== 1 || length < 1e-4) continue; + edges.push({ a, b, wall }); + const d: Vec2 = [(b[0] - a[0]) / length, (b[1] - a[1]) / length]; + note(a, wall, d); + note(b, wall, d); + } + } + // a vertex where the outline just continues straight (a T-joint seen from outside) is no corner + const corners = [...directions.values()].filter(({ d }) => d.some((u) => d.some((v) => Math.abs(u[0] * v[1] - u[1] * v[0]) > 0.05))).map(({ p, wall }) => ({ p, wall })); + return { edges, corners }; +} + +/** The parts of an outline edge outside the given opening spans (only for edges along the wall axis). */ +export function subtractSpans(edge: OutlineEdge, spans: Span[]): [Vec2, Vec2][] { + if (spans.length === 0) return [[edge.a, edge.b]]; + const axis = unit([edge.wall.b[0] - edge.wall.a[0], edge.wall.b[1] - edge.wall.a[1]]); + const along = unit([edge.b[0] - edge.a[0], edge.b[1] - edge.a[1]]); + if (Math.abs(axis[0] * along[0] + axis[1] * along[1]) < 0.99) return [[edge.a, edge.b]]; + const t = (p: Vec2) => (p[0] - edge.wall.a[0]) * axis[0] + (p[1] - edge.wall.a[1]) * axis[1]; + const [ta, tb] = [t(edge.a), t(edge.b)]; + let parts: [number, number][] = [[Math.min(ta, tb), Math.max(ta, tb)]]; + for (const span of spans) { + parts = parts.flatMap(([p, q]): [number, number][] => { + if (span.s1 <= p || span.s0 >= q) return [[p, q]]; + const remaining: [number, number][] = []; + if (span.s0 > p) remaining.push([p, span.s0]); + if (span.s1 < q) remaining.push([span.s1, q]); + return remaining; + }); + } + const pointAt = (value: number): Vec2 => { + const k = (value - ta) / (tb - ta || 1); + return [edge.a[0] + (edge.b[0] - edge.a[0]) * k, edge.a[1] + (edge.b[1] - edge.a[1]) * k]; + }; + // keep the edge's direction: its normal tells which side the room is on + return parts.filter(([p, q]) => q - p > 1e-4).map(([p, q]) => (ta <= tb ? [pointAt(p), pointAt(q)] : [pointAt(q), pointAt(p)])); +} diff --git a/frontend/src/viewer/build/paint.test.ts b/frontend/src/viewer/build/paint.test.ts new file mode 100644 index 0000000..f93d543 --- /dev/null +++ b/frontend/src/viewer/build/paint.test.ts @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { Vec2 } from "../../model.ts"; +import { paintOfSide, wallPaintOf, type WallPaint } from "./solids.ts"; + +// a wall 0.2 m thick along z = 0 (from x = 0 to 4): the room "a" lies north of it (z < 0), the room "b" south (z > 0) +const wall: Vec2[] = [[0, -0.1], [4, -0.1], [4, 0.1], [0, 0.1]]; +const roomA = { points: [[0, -3], [4, -3], [4, 0], [0, 0]] as Vec2[] }; +const roomB = { points: [[0, 0], [4, 0], [4, 3], [0, 3]] as Vec2[] }; + +test("a wall face takes the paint of the room in front of it, the inside colour without one, the outside colour outdoors", () => { + const paint: WallPaint = { outside: 0x111111, inside: 0x222222, rooms: [{ points: roomB.points, color: 0x333333 }] }; + const north = paintOfSide(wall, [0, -0.1], [4, -0.1], paint, [roomA, roomB]); + const south = paintOfSide(wall, [4, 0.1], [0, 0.1], paint, [roomA, roomB]); + assert.equal(north, 0x222222, "room a has no colour of its own: the inside colour"); + assert.equal(south, 0x333333, "room b has its own colour"); + // the same wall with only room a: its south face looks outdoors + assert.equal(paintOfSide(wall, [4, 0.1], [0, 0.1], { ...paint, rooms: [] }, [roomA]), 0x111111); + // the face direction does not depend on how the polygon edge is walked + assert.equal(paintOfSide(wall, [4, -0.1], [0, -0.1], paint, [roomA, roomB]), 0x222222); +}); + +test("a floor with an outside colour of its own paints its outer walls in it, the others keep the building's (#110)", () => { + const settings = { wall_paint_outside: "#aa0000", wall_paint_inside: "#eeeeee" }; + assert.equal(wallPaintOf(settings, { rooms: [], wall_paint_outside: "#808080" }).outside, 0x808080, "the plinth in grey"); + assert.equal(wallPaintOf(settings, { rooms: [] }).outside, 0xaa0000, "the storeys above stay red"); + assert.equal(wallPaintOf(settings, { rooms: [], wall_paint_outside: "nonsense" }).outside, 0xaa0000, "no colour is no override"); +}); + +test("only the floor's own rooms paint its walls: a room upstairs leaves the wall below it alone (#110)", () => { + const upstairs = { rooms: [{ ...roomB, wall_paint: "#00ff00" }] }; + const downstairs = { rooms: [roomB] }; + const settings = { wall_paint_inside: "#222222" }; + assert.deepEqual(wallPaintOf(settings, upstairs).rooms.map((r) => r.color), [0x00ff00]); + const below = wallPaintOf(settings, downstairs); + assert.equal(paintOfSide(wall, [0, 0.1], [4, 0.1], below, downstairs.rooms), 0x222222, "the inside colour, not the green from upstairs"); +}); diff --git a/frontend/src/viewer/build/placement.ts b/frontend/src/viewer/build/placement.ts new file mode 100644 index 0000000..c143a1a --- /dev/null +++ b/frontend/src/viewer/build/placement.ts @@ -0,0 +1,134 @@ +// Fold buckets of the walls, and the openings resolved onto their walls. + +import { locateOpening, openingHost, type Wall } from "../../geometry/walls.ts"; +import { roomOffset, type Floor, type Vec2 } from "../../model.ts"; +import { SECTORS } from "./look.ts"; +import { unit } from "./outline.ts"; +import type { OpeningInfo, Span } from "./types.ts"; + +/** + * How tall a wall stands: its own height (a low wall, a counter), else the floor height. It may rise above the floor height: + * the wall of a room whose ceiling reaches into the floor above (#55), or a sloping wall, whose highest point this is. + */ +export const wallHeight = (wall: Wall, floorHeight: number): number => + wall.heightEnd === undefined ? (wall.height ?? floorHeight) : Math.max(wall.height ?? floorHeight, wall.heightEnd); + +/** + * Sorts the walls into buckets by the direction they face: all interior walls are one bucket, exterior walls fall into + * compass sectors. A bucket is what folds away together. + */ +export function bucketWalls(walls: Wall[]): { buckets: (Vec2 | null)[]; wallBucket: Map } { + const indexOfKey = new Map(); + const buckets: (Vec2 | null)[] = []; + const wallBucket = new Map(); + for (const wall of walls) { + let key = "interior"; + let normal: Vec2 | null = null; + if (wall.exterior) { + const [dx, dz] = [wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]; + const length = Math.hypot(dx, dz) || 1; + const out: Vec2 = [dz / length, -dx / length]; // the right normal: away from the room + const sector = ((Math.round((Math.atan2(out[1], out[0]) / (2 * Math.PI)) * SECTORS) % SECTORS) + SECTORS) % SECTORS; + key = `s${sector}`; + const angle = (sector / SECTORS) * 2 * Math.PI; + normal = [Math.cos(angle), Math.sin(angle)]; + } + if (!indexOfKey.has(key)) { + indexOfKey.set(key, buckets.length); + buckets.push(normal); + } + wallBucket.set(wall, indexOfKey.get(key)!); + } + return { buckets, wallBucket }; +} + +/** The roof limits of a floor's walls: the top of a wall at a point, and the lowest top along a stretch of a wall. */ +export function roofLimits(roofUnder?: (x: number, z: number) => number | null) { + /** The top of a wall at a point: its own height, or the roof above when that is lower. */ + const topAt = (x: number, z: number, height: number): number => { + const roof = roofUnder ? roofUnder(x, z) : null; + return roof === null ? height : Math.max(0.05, Math.min(height, roof)); + }; + /** The lowest wall top along a stretch of a wall (sampled), for openings and the top edge line. */ + const lowestTop = (a: Vec2, axis: Vec2, s0: number, s1: number, height: number): number => { + if (!roofUnder) return height; + const samples = Math.max(2, Math.ceil((s1 - s0) / 0.25) + 1); + let lowest = height; + for (let i = 0; i < samples; i++) { + const s = s0 + ((s1 - s0) * i) / (samples - 1); + lowest = Math.min(lowest, topAt(a[0] + axis[0] * s, a[1] + axis[1] * s, height)); + } + return lowest; + }; + return { topAt, lowestTop }; +} + +/** The tops of one wall: its highest point, the top at a point, and the lowest top along a stretch, with a sloping wall's slope and the roof above both counted. */ +export function wallTops(wall: Wall, floorHeight: number, limits: ReturnType) { + const H = wallHeight(wall, floorHeight); + const length = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]); + const axis = unit([wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]); + if (wall.heightEnd === undefined) return { H, varies: false, topAt: (x: number, z: number) => limits.topAt(x, z, H), lowestTop: (s0: number, s1: number) => limits.lowestTop(wall.a, axis, s0, s1, H) }; + const [h0, h1] = [wall.height ?? floorHeight, wall.heightEnd]; + /** The height of the sloping top above a point: straight from h0 at a to h1 at b. */ + const slopeAt = (x: number, z: number): number => { + const t = length > 1e-9 ? ((x - wall.a[0]) * axis[0] + (z - wall.a[1]) * axis[1]) / length : 0; + return h0 + (h1 - h0) * Math.max(0, Math.min(1, t)); + }; + const topAt = (x: number, z: number) => limits.topAt(x, z, slopeAt(x, z)); + const lowestTop = (s0: number, s1: number): number => { + const samples = Math.max(2, Math.ceil((s1 - s0) / 0.25) + 1); + let lowest = Infinity; + for (let i = 0; i < samples; i++) { + const s = s0 + ((s1 - s0) * i) / (samples - 1); + lowest = Math.min(lowest, topAt(wall.a[0] + axis[0] * s, wall.a[1] + axis[1] * s)); + } + return lowest; + }; + return { H, varies: true, topAt, lowestTop }; +} + +/** Puts every opening onto its wall: its span along the wall, the side the room is on, its sill and top. */ +export function placeOpenings(floor: Floor, walls: Wall[], wallBucket: Map, limits: ReturnType): { openings: OpeningInfo[]; spans: Map } { + const spans = new Map(); + const openings: OpeningInfo[] = []; + for (const o of floor.openings) { + const host = openingHost(o, floor.rooms, floor.walls ?? []); + const hit = host && locateOpening(walls, o, host); + if (!host || !hit) continue; + const { wall, s } = hit; + const axis = unit([wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]); + const length = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]); + const width = Math.min(o.width, length); + const s0 = Math.max(0, Math.min(length - width, s - width / 2)); + // in a free wall the "room" side is the left of the wall as drawn + const hp = host.room.points; + const roomOnLeft = wall.free ? axis[0] * (hp[1][0] - hp[0][0]) + axis[1] * (hp[1][1] - hp[0][1]) > 0 : wall.roomLeft === o.room_id; + const leftNormal: Vec2 = [-axis[1], axis[0]]; + const toRoom: Vec2 = roomOnLeft ? leftNormal : [-leftNormal[0], -leftNormal[1]]; + // sill and top count from the floor of the opening's room, which may lie on its own level (#57) + const level = roomOffset(floor.rooms.find((r) => r.id === o.room_id)); + const top = Math.min(wallTops(wall, floor.height, limits).lowestTop(s0, s0 + width) - 0.02, level + o.sill + o.height); + const sill = Math.max(Math.min(0, level), Math.min(level + o.sill, top - 0.1)); + // looking at the wall from the room, "right" is (toRoom.z, -toRoom.x) + const right: Vec2 = [toRoom[1], -toRoom[0]]; + const startIsLeft = axis[0] * right[0] + axis[1] * right[1] > 0; + const info: OpeningInfo = { + opening: o, + bucket: wallBucket.get(wall)!, + start: [wall.a[0] + axis[0] * s0, wall.a[1] + axis[1] * s0], + axis, + width, + toRoom, + faceRoom: roomOnLeft ? wall.left : wall.right, + faceOut: roomOnLeft ? wall.right : wall.left, + sill, + top, + hingeAtStart: (o.hinge === "left") === startIsLeft, + exterior: wall.exterior, + }; + openings.push(info); + spans.set(wall, [...(spans.get(wall) ?? []), { s0, s1: s0 + width, sill, top, info }]); + } + return { openings, spans }; +} diff --git a/frontend/src/viewer/build/shadow.ts b/frontend/src/viewer/build/shadow.ts new file mode 100644 index 0000000..f7e8397 --- /dev/null +++ b/frontend/src/viewer/build/shadow.ts @@ -0,0 +1,35 @@ +// The baked shadow on the floor: strips along every wall face that borders a room (not across doorways). + +import { Color } from "three"; +import { pointInPolygon, type Room, type Vec2 } from "../../model.ts"; +import type { Wall } from "../../geometry/walls.ts"; +import { GeoBuffer } from "../geo.ts"; +import { subtractSpans, type OutlineEdge } from "./outline.ts"; +import type { Span } from "./types.ts"; + +const SHADOW_WIDTH = 0.42; +const SHADOW_DARK = 0.42; + +export function buildShadow(edges: OutlineEdge[], rooms: readonly Room[], spans: Map): GeoBuffer { + const buf = new GeoBuffer(); + const dark = new Color(SHADOW_DARK, SHADOW_DARK, SHADOW_DARK); + const clear = new Color(1, 1, 1); + const y = 0.002; + for (const edge of edges) { + for (const [a, b] of subtractSpans(edge, (spans.get(edge.wall) ?? []).filter((sp) => sp.sill <= 0.005))) { + const [dx, dz] = [b[0] - a[0], b[1] - a[1]]; + const length = Math.hypot(dx, dz); + if (length < 0.05) continue; + // footprints are counter-clockwise, so the right normal points away from the wall + const n: Vec2 = [dz / length, -dx / length]; + const probe: Vec2 = [(a[0] + b[0]) / 2 + n[0] * 0.05, (a[1] + b[1]) / 2 + n[1] * 0.05]; + if (!rooms.some((r) => r.points.length >= 3 && pointInPolygon(probe, r.points))) continue; + const a2: Vec2 = [a[0] + n[0] * SHADOW_WIDTH, a[1] + n[1] * SHADOW_WIDTH]; + const b2: Vec2 = [b[0] + n[0] * SHADOW_WIDTH, b[1] + n[1] * SHADOW_WIDTH]; + // the layer is drawn double-sided, so the winding does not matter + buf.tri([a[0], y, a[1]], [a2[0], y, a2[1]], [b2[0], y, b2[1]], dark, clear, clear); + buf.tri([a[0], y, a[1]], [b2[0], y, b2[1]], [b[0], y, b[1]], dark, clear, dark); + } + } + return buf; +} diff --git a/frontend/src/viewer/build/solids.ts b/frontend/src/viewer/build/solids.ts new file mode 100644 index 0000000..8591524 --- /dev/null +++ b/frontend/src/viewer/build/solids.ts @@ -0,0 +1,186 @@ +// The wall solids: every wall cut into pieces at its openings, built as prisms that fold away above the cut height. + +import type { Wall } from "../../geometry/walls.ts"; +import { DEFAULT_PAINT_INSIDE, DEFAULT_PAINT_OUTSIDE, pointInPolygon, roomOffset, type BuildingSettings, type Floor, type Vec2 } from "../../model.ts"; +import { CAP_OFFSET, LOWER_OFFSET, PAINT_OFFSET, pushPrism, type GeoBuffer } from "../geo.ts"; +import { NEON, SLAB } from "./look.ts"; +import { clipAlong, unit } from "./outline.ts"; +import { glassJoins } from "./glass-joins.ts"; +import { wallTops, type roofLimits } from "./placement.ts"; +import type { Span } from "./types.ts"; + +interface Piece { + t0: number; + t1: number; + /** The height ranges the wall fills at this piece (between and around openings). */ + ranges: [number, number][]; +} + +/** Wall paint for the solid wall view: outside, inside, and the rooms with a colour of their own. */ +export interface WallPaint { + outside: number; + inside: number; + rooms: { points: Vec2[]; color: number }[]; +} + +/** A "#rrggbb" paint as a number, or the fallback when it is missing or not a colour. */ +const paintHex = (v: string | null | undefined, fallback: string): number => Number.parseInt(/^#?([0-9a-f]{6})$/i.exec(v?.trim() ?? "")?.[1] ?? fallback.slice(1), 16); +const isPaint = (v: string | null | undefined): v is string => /^#?[0-9a-f]{6}$/i.test(v?.trim() ?? ""); + +/** + * The paint of one floor's walls: the floor's own outside colour if it has one (a plinth, a garage, #110), else the + * building's; and only this floor's rooms, so a room upstairs does not paint the wall below it in the same spot. + */ +export function wallPaintOf(settings: Pick, floor: { rooms: readonly { points: Vec2[]; wall_paint?: string | null }[]; wall_paint_outside?: string | null }): WallPaint { + return { + outside: paintHex(isPaint(floor.wall_paint_outside) ? floor.wall_paint_outside : settings.wall_paint_outside, DEFAULT_PAINT_OUTSIDE), + inside: paintHex(settings.wall_paint_inside, DEFAULT_PAINT_INSIDE), + rooms: floor.rooms.filter((r) => r.wall_paint && r.points.length >= 3).map((r) => ({ points: r.points, color: paintHex(r.wall_paint, DEFAULT_PAINT_INSIDE) })), + }; +} + +/** The top of a painted wall, where it is cut or ends: a plain light grey, like plaster seen in section. */ +const PAINT_TOP = 0xd9d5cd; + +/** + * The paint of one side face of a wall: the colour of the room in front of it, the inside colour when a room without one + * of its own is there, the outside colour when no room is. + */ +export function paintOfSide(poly: Vec2[], a: Vec2, b: Vec2, paint: WallPaint, rooms: { points: Vec2[] }[]): number { + const len = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1; + const m: Vec2 = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; + let n: Vec2 = [(b[1] - a[1]) / len, -(b[0] - a[0]) / len]; + // the normal that points away from the wall body + if (pointInPolygon([m[0] + n[0] * 0.01, m[1] + n[1] * 0.01], poly)) n = [-n[0], -n[1]]; + const front: Vec2 = [m[0] + n[0] * 0.06, m[1] + n[1] * 0.06]; + const own = paint.rooms.find((r) => pointInPolygon(front, r.points)); + if (own) return own.color; + return rooms.some((r) => r.points.length >= 3 && pointInPolygon(front, r.points)) ? paint.inside : paint.outside; +} + +/** + * Pieces along the wall's axis, cut at every opening edge. Each piece leaves out all openings above it (two windows one + * above the other, a window over a door), and the wall fills what remains. + */ +function piecesOf(spans: Span[], height: number, bottom = -SLAB): Piece[] { + const stops = [-Infinity, ...new Set(spans.flatMap((sp) => [sp.s0, sp.s1])).values(), Infinity].sort((a, b) => a - b); + const pieces: Piece[] = []; + for (let i = 0; i + 1 < stops.length; i++) { + const [t0, t1] = [stops[i], stops[i + 1]]; + if (t1 - t0 < 1e-6) continue; + const middle = Number.isFinite(t0) && Number.isFinite(t1) ? (t0 + t1) / 2 : Number.isFinite(t0) ? t0 + 1 : t1 - 1; + const covering = spans.filter((sp) => sp.s0 < middle && sp.s1 > middle).map((sp) => [sp.sill, sp.top] as [number, number]).sort((a, b) => a[0] - b[0]); + const ranges: [number, number][] = []; + let y = bottom; + for (const [lower, upper] of covering) { + if (lower > y + 1e-4) ranges.push([y, lower]); + y = Math.max(y, upper); + } + if (height > y + 1e-4) ranges.push([y, height]); + pieces.push({ t0, t1, ranges }); + } + return pieces; +} + +export function buildWallSolids( + buf: GeoBuffer, + floor: Floor, + walls: Wall[], + wallBucket: Map, + spans: Map, + limits: ReturnType, + hasRoof: boolean, + /** Painted walls (solid wall view): each face in its colour, and marked so every look keeps that colour. */ + paint?: WallPaint, +): void { + const cut = Math.min(floor.cut_height, floor.height); + const offset = paint ? PAINT_OFFSET : 0; + const sideColor = paint ? (poly: Vec2[]) => (a: Vec2, b: Vec2) => paintOfSide(poly, a, b, paint, floor.rooms) : null; + const top = paint ? PAINT_TOP : NEON.wallTop; + // the two wall ends at an internal join of one pane are not a jamb: without this, a full-height wall + // face stays there, which reads as a frame across the glass + const joins = glassJoins(spans.values()); + // At a join the pane runs on to the next wall, so what stands beyond the end of the opening is the + // mitre overflow of the footprint only — a few centimetres of wall, full height. In the height band of + // the pane it stands in front of the glass, on the outer face: that strip, 1 to 5 cm wide and as tall + // as the room, is the white line seen at a bend from outside. The band stays empty there, exactly as it + // does between two openings; above and below the pane the overflow is still the wall that fills the + // corner of the mitre, so the bend does not open into a hole. + const nearJoin = (p: Vec2) => joins.points.some((j) => Math.hypot(j[0] - p[0], j[1] - p[1]) < 0.03); + const bandOf = (sp: Span | undefined) => (sp && sp.info.opening.front ? ([sp.sill, sp.top] as [number, number]) : null); + const cutBand = (ranges: [number, number][], band: [number, number]): [number, number][] => { + const out: [number, number][] = []; + for (const [a, b] of ranges) { + if (band[0] > a + 1e-4) out.push([a, Math.min(b, band[0])]); + if (b > band[1] + 1e-4) out.push([Math.max(a, band[1]), b]); + } + return out; + }; + for (const wall of walls) { + const bucket = wallBucket.get(wall)!; + const axis = unit([wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]); + const list = (spans.get(wall) ?? []).sort((p, q) => p.s0 - q.s0); + const tops = wallTops(wall, floor.height, limits); + const { H, topAt } = tops; + // a wall beside a room on a lower level reaches down to that room's floor + const lowest = Math.min(0, ...[wall.roomLeft, wall.roomRight].map((id) => roomOffset(floor.rooms.find((r) => r.id === id)))); + const pieces = piecesOf(list, H, lowest - SLAB); + // under a roof the pieces are cut into short steps, so each step's top lies in one roof plane + const length = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]); + // (a sloping wall is cut into steps the same way: its top then lies in one plane per step) + const underRoof = (hasRoof || tops.varies) && tops.lowestTop(0, length) < H - 1e-3; + const steps = underRoof + ? pieces.flatMap((piece) => { + const from = Math.max(piece.t0, -0.5); + const to = Math.min(piece.t1, length + 0.5); + const count = Math.max(1, Math.ceil((to - from) / 0.3)); + return Array.from({ length: count }, (_, i) => ({ + t0: i === 0 ? piece.t0 : from + ((to - from) * i) / count, + t1: i === count - 1 ? piece.t1 : from + ((to - from) * (i + 1)) / count, + ranges: piece.ranges, + inner0: i > 0, + inner1: i < count - 1, + })); + }) + : pieces.map((piece) => ({ ...piece, inner0: false, inner1: false })); + + const along = (p: Vec2) => (p[0] - wall.a[0]) * axis[0] + (p[1] - wall.a[1]) * axis[1]; + // the overflow before the start of the wall, and beyond its end, only where the pane runs on + const bandStart = nearJoin(wall.a) ? bandOf(list[0]) : null; + const bandEnd = nearJoin(wall.b) ? bandOf(list[list.length - 1]) : null; + for (const step of steps) { + const poly = clipAlong(wall.footprint, wall.a, axis, step.t0, step.t1); + if (poly.length < 3) continue; + const overflow = step.t1 <= 1e-6 && step.t0 < 0 ? bandStart : step.t0 >= length - 1e-6 ? bandEnd : null; + const ranges = overflow ? cutBand(step.ranges, overflow) : step.ranges; + // the faces between two steps of one piece lie inside the wall: leave them out, or they show as stripes through see-through walls + const at = (p: Vec2, t: number) => Math.abs(along(p) - t) < 1e-4; + const roofSide = (p: Vec2, q: Vec2) => (step.inner0 && at(p, step.t0) && at(q, step.t0)) || (step.inner1 && at(p, step.t1) && at(q, step.t1)); + // a short end face that starts at an internal join is the wall showing through the bend; a real wall + // face is longer than half a metre, so it is never taken for one + const paneSide = (p: Vec2, q: Vec2) => { + if (!joins.points.length || Math.hypot(p[0] - q[0], p[1] - q[1]) > 0.5) return false; + return joins.points.some((j) => Math.min(Math.hypot(j[0] - p[0], j[1] - p[1]), Math.hypot(j[0] - q[0], j[1] - q[1])) < 0.05); + }; + const skipSide = (p: Vec2, q: Vec2) => roofSide(p, q) || paneSide(p, q); + // the roof over this step: the lowest point of its footprint decides what is left of each range + const roofTop = underRoof ? Math.min(...poly.map(([x, z]) => topAt(x, z))) : H; + for (const [y0, y1raw] of ranges) { + const y1 = Math.min(y1raw, underRoof ? Math.max(...poly.map(([x, z]) => topAt(x, z))) : y1raw); + if (y1 - y0 < 1e-4 || roofTop - y0 < 0.01) continue; + const lintel = y0 > 0.01; + const sloped = underRoof && y1raw > roofTop; + const topOf = (x: number, z: number) => Math.min(y1raw, topAt(x, z)); + if (y0 < cut - 1e-6) { + // the top face at the cut height is only seen while the wall is cut + const topFold = y1 > cut + 1e-6 ? CAP_OFFSET + bucket : LOWER_OFFSET + bucket; + const capped = sloped && roofTop < cut ? (x: number, z: number) => Math.min(cut, topOf(x, z)) : Math.min(y1, cut); + pushPrism(buf, poly, y0, capped, NEON.wall, top, { aoFrom: 0, bottom: lintel, fold: offset + LOWER_OFFSET + bucket, topFold: offset + topFold, skipSide, sideColor: sideColor?.(poly) }); + } + if (y1 > cut + 1e-6 && roofTop > cut + 1e-6) { + pushPrism(buf, poly, Math.max(y0, cut), sloped ? topOf : y1, NEON.wall, top, { aoFrom: 0, fold: offset + bucket, bottom: lintel && y0 >= cut, skipSide, sideColor: sideColor?.(poly) }); + } + } + } + } +} diff --git a/frontend/src/viewer/build/types.ts b/frontend/src/viewer/build/types.ts new file mode 100644 index 0000000..ec75daa --- /dev/null +++ b/frontend/src/viewer/build/types.ts @@ -0,0 +1,60 @@ +import type { BufferGeometry } from "three"; +import type { Wall } from "../../geometry/walls.ts"; +import type { Opening, Vec2 } from "../../model.ts"; + +/** An opening resolved onto its wall, as frames, sashes and blinds need it. */ +export interface OpeningInfo { + opening: Opening; + /** The fold bucket of the wall it sits in. */ + bucket: number; + /** The start of the opening on the wall axis, and the axis direction (x, z). */ + start: Vec2; + axis: Vec2; + width: number; + /** The unit normal pointing into the opening's room. */ + toRoom: Vec2; + /** The distance from the wall axis to the room-side face and to the other face. */ + faceRoom: number; + faceOut: number; + sill: number; + top: number; + /** True when the sash hinge is at the start of the opening (as seen along the axis). */ + hingeAtStart: boolean; + exterior: boolean; +} + +export interface FloorGeometry { + floor: BufferGeometry; + /** Triangle ranges of room tops (for picking and highlighting) with their base colour. */ + roomTris: { roomId: string; start: number; end: number; color: number }[]; + /** Openings cut into the floor (stairwells, galleries): the light surface leaves them out. */ + holes: Vec2[][]; + /** Walls (with folding upper parts) and furniture. */ + walls: BufferGeometry; + /** Outdoor areas drawn see-through, one geometry per opacity (0.1 … 0.95). */ + ghosts: { opacity: number; geometry: BufferGeometry }[]; + lines: BufferGeometry; + /** A multiply layer darkening the floor along walls and under furniture (baked occlusion). */ + shadow: BufferGeometry; + /** The outward direction (x, z) of each fold bucket; null for interior walls. The index is the bucket id. */ + buckets: (Vec2 | null)[]; + openings: OpeningInfo[]; + walls2d: Wall[]; + /** Pairs of rooms joined by "no wall": one space, also for the light. */ + openRooms: [string, string][]; + /** The fold bucket of each wall in walls2d. */ + wallBuckets: number[]; + /** Triangle ranges of furniture in `walls`, for tapping furniture in 3D. */ + furnitureTris: { id: string; start: number; end: number }[]; + /** Under roof slopes: the roof's underside above a plan point in floor coordinates (null: no roof there). */ + roofUnder?: (x: number, z: number) => number | null; +} + +/** An opening on a wall as a span along its axis (metres from wall.a). */ +export interface Span { + s0: number; + s1: number; + sill: number; + top: number; + info: OpeningInfo; +} diff --git a/frontend/src/viewer/controls.ts b/frontend/src/viewer/controls.ts new file mode 100644 index 0000000..42e86fc --- /dev/null +++ b/frontend/src/viewer/controls.ts @@ -0,0 +1,4 @@ +// The orbit camera, split into modules in controls/: the view maths and the pointer handling. + +export { OrbitControls, type ControlEvents } from "./controls/controls.ts"; +export type { OrbitView } from "./controls/view.ts"; diff --git a/frontend/src/viewer/controls/controls.test.ts b/frontend/src/viewer/controls/controls.test.ts new file mode 100644 index 0000000..013a6eb --- /dev/null +++ b/frontend/src/viewer/controls/controls.test.ts @@ -0,0 +1,19 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { walkKey } from "./controls.ts"; + +test("walking keys go by their place on the keyboard, so AZERTY walks with Z Q S D", () => { + // QWERTY and QWERTZ + assert.equal(walkKey({ code: "KeyW", key: "w" }), "w"); + assert.equal(walkKey({ code: "KeyA", key: "a" }), "a"); + // AZERTY: Z sits where W is, Q where A is, A where Q is + assert.equal(walkKey({ code: "KeyW", key: "z" }), "w"); + assert.equal(walkKey({ code: "KeyA", key: "q" }), "a"); + assert.equal(walkKey({ code: "KeyQ", key: "a" }), "q"); + // arrows, and a browser without code + assert.equal(walkKey({ code: "ArrowUp", key: "ArrowUp" }), "arrowup"); + assert.equal(walkKey({ key: "D" }), "d"); + // other keys + assert.equal(walkKey({ code: "KeyZ", key: "w" }), null); + assert.equal(walkKey({ code: "Space", key: " " }), null); +}); diff --git a/frontend/src/viewer/controls/controls.ts b/frontend/src/viewer/controls/controls.ts new file mode 100644 index 0000000..fdbd0d1 --- /dev/null +++ b/frontend/src/viewer/controls/controls.ts @@ -0,0 +1,339 @@ +// The orbit camera's pointer handling: turning, panning, pinch zoom, taps, holds, and handing pointers over to objects. +// The owner calls update() each frame; it returns true while something still moves. + +import type { PerspectiveCamera } from "three"; +import { Vector3 } from "three"; +import { blendViews, cameraPosition, clamp, coast, copyView, flightGoal, orbitView, panView, type OrbitView } from "./view.ts"; + +export interface ControlEvents { + change(): void; + tap(x: number, y: number): void; + doubleTap(x: number, y: number): void; + /** A press without moving for HOLD_MS; the release that follows is no tap. */ + hold(x: number, y: number): void; + /** A pointer went down: return true to take it (drag an object instead of turning the view). */ + grab?(x: number, y: number): boolean; + drag?(x: number, y: number): void; + drop?(): void; + /** + * A one-finger drag starts at (x, y) and moves by (dx, dy): return true to take it as a swipe on an object (dimming a + * lamp, moving a blind) rather than turning the view. Moves then report the vertical distance from the start (pixels, + * down is positive). + */ + swipeStart?(x: number, y: number, dx: number, dy: number): boolean; + swipeMove?(dy: number): void; + swipeEnd?(): void; +} + +/** Walking keys by their place on the keyboard (W A S D on QWERTY is Z Q S D on AZERTY), and the arrows. */ +const WALK_CODES: Record = { KeyW: "w", KeyA: "a", KeyS: "s", KeyD: "d", KeyQ: "q", KeyE: "e" }; +const WALK_KEYS = new Set(["w", "a", "s", "d", "q", "e", "arrowup", "arrowdown", "arrowleft", "arrowright"]); + +/** The walking key a key press stands for (null: none). The place of the key wins over its letter. */ +export function walkKey(e: { code?: string; key: string }): string | null { + // a letter key is known by its place; other keys (the arrows), and browsers without a code, by their name + const name = e.code?.startsWith("Key") ? (WALK_CODES[e.code] ?? null) : e.key.toLowerCase(); + return name && WALK_KEYS.has(name) ? name : null; +} + +const HOLD_MS = 500; +const TAP_MAX_MS = 400; +const DOUBLE_TAP_MS = 320; +const DRAG_THRESHOLD = 6; + +interface PointerInfo { + x: number; + y: number; + button: number; +} + +/** Walking speed (m/s) and turning speed (rad/s). */ +const WALK_SPEED = 1.5; +const TURN_SPEED = 1.8; + +export interface Walk { + eye: Vector3; + /** Heading like the orbit's theta: the eye looks along (-sin yaw, 0, -cos yaw). */ + yaw: number; + /** Up (+) or down (-) from the horizon, radians. */ + pitch: number; + /** The touch stick: x turns or steps sideways, y walks (-1 … 1 each). */ + stick: [number, number]; + keys: Set; + bounds: { x0: number; x1: number; z0: number; z1: number }; + last: number; +} + +/** One step of walking: moves the eye by keys and stick over dt milliseconds, kept in its bounds. Returns whether it moved. */ +export function stepWalk(w: Walk, dt: number): boolean { + const k = w.keys; + const ahead = (k.has("w") || k.has("arrowup") ? 1 : 0) - (k.has("s") || k.has("arrowdown") ? 1 : 0) - w.stick[1]; + const side = (k.has("d") ? 1 : 0) - (k.has("a") ? 1 : 0); + const turn = (k.has("arrowleft") || k.has("q") ? 1 : 0) - (k.has("arrowright") || k.has("e") ? 1 : 0) - w.stick[0]; + if (!ahead && !side && !turn) return false; + const s = dt / 1000; + w.yaw += turn * TURN_SPEED * s; + const [fx, fz] = [-Math.sin(w.yaw), -Math.cos(w.yaw)]; + const [rx, rz] = [Math.cos(w.yaw), -Math.sin(w.yaw)]; + w.eye.x = clamp(w.eye.x + (fx * ahead + rx * side) * WALK_SPEED * s, w.bounds.x0, w.bounds.x1); + w.eye.z = clamp(w.eye.z + (fz * ahead + rz * side) * WALK_SPEED * s, w.bounds.z0, w.bounds.z1); + return true; +} + +export class OrbitControls { + view: OrbitView = { target: new Vector3(), radius: 16, theta: -0.6, phi: 0.85 }; + minRadius = 2; + maxRadius = 80; + /** A wall tablet's 3D lock: the camera does not turn, pan or zoom by hand; taps, holds and swipes on devices still work. */ + locked = false; + /** Walking at eye level: where the eye is, which way it looks, the stick and keys that move it, and the area it stays in. Null while orbiting. */ + walk: Walk | null = null; + + private readonly pointers = new Map(); + private velocity = { theta: 0, phi: 0 }; + private flight: { from: OrbitView; to: OrbitView; start: number; duration: number } | null = null; + private press: { x: number; y: number; time: number; moved: boolean } | null = null; + private lastTap = 0; + private holdTimer: ReturnType | undefined; + private held = false; + /** An object is being dragged: moves go to events.drag and not to the camera. */ + private grabbing = false; + /** A swipe on an object is going on: vertical moves go to events.swipeMove. */ + private swiping: { startY: number } | null = null; + private pinch: { dist: number; mid: [number, number] } | null = null; + private readonly listeners: [string, EventListener][] = []; + private readonly el: HTMLElement; + private readonly camera: PerspectiveCamera; + private readonly events: ControlEvents; + + constructor(el: HTMLElement, camera: PerspectiveCamera, events: ControlEvents) { + this.el = el; + this.camera = camera; + this.events = events; + const listen = (type: K, handler: (e: HTMLElementEventMap[K]) => void, options?: AddEventListenerOptions) => { + el.addEventListener(type, handler as EventListener, options); + this.listeners.push([type, handler as EventListener]); + }; + listen("pointerdown", (e) => this.onDown(e)); + listen("pointermove", (e) => this.onMove(e)); + listen("pointerup", (e) => this.onUp(e)); + listen("pointercancel", (e) => this.onUp(e)); + listen("wheel", (e) => this.onWheel(e), { passive: false }); + listen("contextmenu", (e) => e.preventDefault()); + // keys walk while walking (not while typing into a field) + const key = (down: boolean) => (e: KeyboardEvent) => { + if (!this.walk || (e.target as HTMLElement | null)?.closest?.("input, textarea, select")) return; + const name = walkKey(e); + if (!name) return; + e.preventDefault(); + if (down) this.walk.keys.add(name); + else this.walk.keys.delete(name); + this.events.change(); + }; + const keydown = key(true); + const keyup = key(false); + window.addEventListener("keydown", keydown); + window.addEventListener("keyup", keyup); + this.listeners.push(["__window_keydown", keydown as EventListener], ["__window_keyup", keyup as EventListener]); + } + + dispose(): void { + clearTimeout(this.holdTimer); + for (const [type, handler] of this.listeners) { + if (type.startsWith("__window_")) window.removeEventListener(type.slice("__window_".length), handler); + else this.el.removeEventListener(type, handler); + } + } + + /** A finger or the mouse holds the view, or a flight runs (an automatic orbit waits meanwhile). */ + get active(): boolean { + return this.pointers.size > 0 || this.flight !== null; + } + + get busy(): boolean { + return this.active; + } + + /** Applies the view to the camera. Returns true while inertia or a flight is running. */ + update(now: number): boolean { + if (this.walk) { + const w = this.walk; + const moved = stepWalk(w, w.last ? Math.min(100, now - w.last) : 16); + w.last = moved ? now : 0; + const dir = new Vector3(-Math.sin(w.yaw) * Math.cos(w.pitch), Math.sin(w.pitch), -Math.cos(w.yaw) * Math.cos(w.pitch)); + // the orbit view follows, so labels and anything that asks for the target still work + this.view.target.copy(w.eye).add(dir); + this.camera.position.copy(w.eye); + this.camera.lookAt(this.view.target); + return moved; + } + let moving = false; + if (this.flight) { + const { from, to, start, duration } = this.flight; + const fraction = Math.min(1, (now - start) / duration); + this.view = blendViews(from, to, fraction); + if (fraction >= 1) this.flight = null; + moving = true; + } else if (this.pointers.size === 0) { + moving = coast(this.view, this.velocity); + } + this.camera.position.copy(cameraPosition(this.view)); + this.camera.lookAt(this.view.target); + return moving; + } + + flyTo(to: Partial, duration = 700): void { + const goal = flightGoal(this.view, to); + const from = copyView(this.view); + this.velocity = { theta: 0, phi: 0 }; + if (duration <= 0 || matchMedia("(prefers-reduced-motion: reduce)").matches) { + this.view = goal; + this.flight = null; + } else { + this.flight = { from, to: goal, start: performance.now(), duration }; + } + this.events.change(); + } + + private local(e: { clientX: number; clientY: number }): [number, number] { + const rect = this.el.getBoundingClientRect(); + return [e.clientX - rect.left, e.clientY - rect.top]; + } + + private stopMotion(): void { + this.flight = null; + this.velocity = { theta: 0, phi: 0 }; + } + + private onDown(e: PointerEvent): void { + this.el.setPointerCapture(e.pointerId); + const first = this.pointers.size === 0; + this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY, button: e.button }); + this.stopMotion(); + if (first && e.button === 0 && this.events.grab?.(...this.local(e))) { + this.grabbing = true; + return; + } + clearTimeout(this.holdTimer); + this.held = false; + if (this.pointers.size === 1) { + this.press = { x: e.clientX, y: e.clientY, time: performance.now(), moved: false }; + const [x, y] = this.local(e); + this.holdTimer = setTimeout(() => { + if (!this.press || this.press.moved || this.pointers.size !== 1) return; + this.held = true; + this.events.hold(x, y); + }, HOLD_MS); + } else { + this.press = null; + this.pinch = this.pinchState(); + } + } + + private onMove(e: PointerEvent): void { + const pointer = this.pointers.get(e.pointerId); + if (!pointer) return; + if (this.grabbing) return void this.events.drag?.(...this.local(e)); + if (this.swiping) return void this.events.swipeMove?.(e.clientY - this.swiping.startY); + + const [dx, dy] = [e.clientX - pointer.x, e.clientY - pointer.y]; + if (this.press && !this.press.moved && Math.hypot(e.clientX - this.press.x, e.clientY - this.press.y) > DRAG_THRESHOLD) { + this.press.moved = true; + clearTimeout(this.holdTimer); + const [sx, sy] = this.local({ clientX: this.press.x, clientY: this.press.y }); + const swipe = this.pointers.size === 1 && pointer.button === 0 && !e.shiftKey && this.events.swipeStart?.(sx, sy, e.clientX - this.press.x, e.clientY - this.press.y); + if (swipe) { + this.swiping = { startY: this.press.y }; + this.velocity = { theta: 0, phi: 0 }; + return void this.events.swipeMove?.(e.clientY - this.press.y); + } + } + + if (this.locked) { + [pointer.x, pointer.y] = [e.clientX, e.clientY]; + return; + } + if (this.walk) { + // walking: a drag looks around + if (!(this.press && !this.press.moved) && this.pointers.size === 1) { + const h = this.el.clientHeight || 1; + this.walk.yaw += (dx / h) * 2.4; + this.walk.pitch = clamp(this.walk.pitch + (dy / h) * 1.8, -1.1, 1.1); + this.events.change(); + } + [pointer.x, pointer.y] = [e.clientX, e.clientY]; + return; + } + if (this.pointers.size === 1) { + if (!(this.press && !this.press.moved)) { + if (pointer.button === 1 || pointer.button === 2 || e.shiftKey) panView(this.view, dx, dy, this.el.clientHeight, this.camera.fov); + else this.velocity = orbitView(this.view, dx, dy, this.el.clientHeight); + } + [pointer.x, pointer.y] = [e.clientX, e.clientY]; + } else { + [pointer.x, pointer.y] = [e.clientX, e.clientY]; + const now = this.pinchState(); + if (this.pinch && now) { + this.zoom(this.pinch.dist / Math.max(1, now.dist)); + panView(this.view, now.mid[0] - this.pinch.mid[0], now.mid[1] - this.pinch.mid[1], this.el.clientHeight, this.camera.fov); + } + this.pinch = now; + } + if (!(this.pointers.size === 1 && this.press && !this.press.moved)) this.events.change(); + } + + private onUp(e: PointerEvent): void { + if (!this.pointers.has(e.pointerId)) return; + this.pointers.delete(e.pointerId); + if (this.grabbing) { + this.grabbing = false; + return void this.events.drop?.(); + } + if (this.swiping) { + this.swiping = null; + this.press = null; + return void this.events.swipeEnd?.(); + } + if (this.pointers.size < 2) this.pinch = null; + clearTimeout(this.holdTimer); + if (this.held) { + this.held = false; + this.press = null; + } else if (this.press && !this.press.moved && e.type === "pointerup" && performance.now() - this.press.time < TAP_MAX_MS) { + const [x, y] = this.local(e); + const now = performance.now(); + const isDouble = now - this.lastTap < DOUBLE_TAP_MS; + this.lastTap = isDouble ? 0 : now; + if (isDouble) this.events.doubleTap(x, y); + else this.events.tap(x, y); + } + if (this.pointers.size === 0) this.press = null; + this.events.change(); + } + + private onWheel(e: WheelEvent): void { + e.preventDefault(); + if (this.locked) return; + if (this.walk) { + // the wheel takes a step forward or back + const step = clamp(-e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.002), -0.6, 0.6); + const w = this.walk; + w.eye.x = clamp(w.eye.x - Math.sin(w.yaw) * step, w.bounds.x0, w.bounds.x1); + w.eye.z = clamp(w.eye.z - Math.cos(w.yaw) * step, w.bounds.z0, w.bounds.z1); + this.events.change(); + return; + } + this.flight = null; + this.zoom(Math.exp(e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.0015))); + this.events.change(); + } + + private zoom(factor: number): void { + this.view.radius = clamp(this.view.radius * factor, this.minRadius, this.maxRadius); + } + + private pinchState(): { dist: number; mid: [number, number] } | null { + const [a, b] = [...this.pointers.values()]; + return b ? { dist: Math.hypot(a.x - b.x, a.y - b.y), mid: [(a.x + b.x) / 2, (a.y + b.y) / 2] } : null; + } +} diff --git a/frontend/src/viewer/controls/view.test.ts b/frontend/src/viewer/controls/view.test.ts new file mode 100644 index 0000000..4010440 --- /dev/null +++ b/frontend/src/viewer/controls/view.test.ts @@ -0,0 +1,111 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { Vector3 } from "three"; +import { blendViews, cameraPosition, clamp, coast, copyView, ease, flightGoal, MAX_PHI, MIN_PHI, orbitView, panView, type OrbitView } from "./view.ts"; + +const near = (a: number, b: number, eps = 1e-9) => assert.ok(Math.abs(a - b) < eps, `${a} vs ${b}`); +const view = (extra: Partial = {}): OrbitView => ({ target: new Vector3(1, 2, 3), radius: 10, theta: 0, phi: Math.PI / 2, ...extra }); + +test("clamp keeps a value inside its limits", () => { + assert.equal(clamp(5, 0, 3), 3); + assert.equal(clamp(-1, 0, 3), 0); + assert.equal(clamp(2, 0, 3), 2); +}); + +test("easing starts at 0, ends at 1, is slow at both ends and symmetric", () => { + near(ease(0), 0); + near(ease(1), 1); + near(ease(0.5), 0.5); + assert.ok(ease(0.1) < 0.1 && ease(0.9) > 0.9); + near(ease(0.25) + ease(0.75), 1); +}); + +test("the camera sits at the radius from the target, in the direction the angles say", () => { + const p = cameraPosition(view()); + near(p.distanceTo(new Vector3(1, 2, 3)), 10); + near(p.y, 2, 1e-9); // phi = 90°: level with the target + near(p.z, 13); // theta = 0: in front, along +z + const above = cameraPosition(view({ phi: 0 })); + near(above.y, 12); + const side = cameraPosition(view({ theta: Math.PI / 2 })); + near(side.x, 11); +}); + +test("a blend between two views runs from the first to the second", () => { + const a = view(); + const b = view({ target: new Vector3(5, 6, 7), radius: 20, theta: 1, phi: 1 }); + const start = blendViews(a, b, 0); + const end = blendViews(a, b, 1); + near(start.radius, 10); + near(end.radius, 20); + assert.ok(end.target.equals(b.target)); + const middle = blendViews(a, b, 0.5); + near(middle.radius, 15); + near(middle.theta, 0.5); +}); + +test("a flight turns the short way round and keeps what it is not told to change", () => { + const from = view({ theta: 3 }); + assert.ok(Math.abs(flightGoal(from, { theta: -3 }).theta - 3) < 1, "from 3 to -3 goes through π, not back through 0"); + const goal = flightGoal(from, { radius: 4 }); + assert.equal(goal.radius, 4); + assert.equal(goal.theta, 3); + assert.equal(goal.phi, from.phi); + assert.notEqual(goal.target, from.target, "the target is copied"); +}); + +test("copying a view copies its target", () => { + const a = view(); + const b = copyView(a); + b.target.x = 99; + assert.equal(a.target.x, 1); +}); + +test("dragging turns the view, limits the tilt, and reports the turn for inertia", () => { + const v = view({ phi: 1 }); + const turn = orbitView(v, 100, 0, 500); + assert.ok(v.theta < 0 && turn.theta < 0, "dragging right turns the view clockwise"); + near(turn.theta, (-100 / 500) * 3.2); + orbitView(v, 0, 10000, 500); + assert.equal(v.phi, MIN_PHI); + orbitView(v, 0, -10000, 500); + assert.equal(v.phi, MAX_PHI); +}); + +test("inertia fades out and then stops", () => { + const v = view(); + const velocity = { theta: 0.1, phi: 0 }; + let steps = 0; + while (coast(v, velocity) && steps < 1000) steps++; + assert.ok(steps > 20 && steps < 200); + assert.ok(v.theta > 0.3 && v.theta < 1.1, "keeps turning a little"); + assert.equal(coast(v, { theta: 0, phi: 0 }), false); +}); + +test("panning moves the target sideways, and further when zoomed out", () => { + const close = view({ radius: 5 }); + const far = view({ radius: 20 }); + panView(close, 100, 0, 500, 50); + panView(far, 100, 0, 500, 50); + assert.ok(close.target.x < 1 && far.target.x < close.target.x, "dragging right moves the scene right, so the target left"); + const forward = view(); + panView(forward, 0, 100, 500, 50); + assert.ok(forward.target.z < 3 || forward.target.z > 3, "dragging down moves the target along the view direction"); + near(forward.target.x, 1); +}); + +test("walking moves the eye along its heading, turns with the stick and stays inside the floor", async () => { + const { stepWalk } = await import("./controls.ts"); + const { Vector3 } = await import("three"); + const walk = { eye: new Vector3(0, 1.6, 0), yaw: 0, pitch: 0, stick: [0, 0] as [number, number], keys: new Set(["w"]), bounds: { x0: -1, x1: 1, z0: -1, z1: 1 }, last: 0 }; + assert.ok(stepWalk(walk, 400)); + assert.equal(Math.round(walk.eye.z * 100) / 100, -0.6, "yaw 0 looks towards -z, 1.5 m/s for 0.4 s"); + walk.keys = new Set(); + assert.equal(stepWalk(walk, 400), false, "no key, no stick: no step"); + walk.stick = [-1, 0]; + stepWalk(walk, 500); + assert.ok(walk.yaw > 0.8, "the stick to the left turns left"); + walk.stick = [0, -1]; + for (let i = 0; i < 50; i++) stepWalk(walk, 100); + assert.ok(Math.abs(walk.eye.x) <= 1 && Math.abs(walk.eye.z) <= 1, "never leaves the floor"); +}); diff --git a/frontend/src/viewer/controls/view.ts b/frontend/src/viewer/controls/view.ts new file mode 100644 index 0000000..929adb5 --- /dev/null +++ b/frontend/src/viewer/controls/view.ts @@ -0,0 +1,73 @@ +// The camera's orbit view and the maths that moves it: flights, inertia, panning, zooming. No DOM in here. + +import { Vector3 } from "three"; + +export interface OrbitView { + target: Vector3; + radius: number; + /** The azimuth around +y, in radians. */ + theta: number; + /** The polar angle from +y, in radians. */ + phi: number; +} + +export const MIN_PHI = 0.12; +export const MAX_PHI = 1.35; +export const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v)); + +/** Ease in and out (cubic). */ +export const ease = (t: number): number => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2); + +export const copyView = (v: OrbitView): OrbitView => ({ ...v, target: v.target.clone() }); + +/** The camera position that looks at the target from the view's angles and distance. */ +export function cameraPosition({ target, radius, theta, phi }: OrbitView): Vector3 { + return new Vector3(target.x + radius * Math.sin(phi) * Math.sin(theta), target.y + radius * Math.cos(phi), target.z + radius * Math.sin(phi) * Math.cos(theta)); +} + +/** A view blended between two views by an eased fraction. */ +export function blendViews(from: OrbitView, to: OrbitView, fraction: number): OrbitView { + const k = ease(fraction); + return { + target: new Vector3().lerpVectors(from.target, to.target, k), + radius: from.radius + (to.radius - from.radius) * k, + theta: from.theta + (to.theta - from.theta) * k, + phi: from.phi + (to.phi - from.phi) * k, + }; +} + +/** The goal of a flight, turning the short way round in azimuth. */ +export function flightGoal(from: OrbitView, to: Partial): OrbitView { + let theta = to.theta ?? from.theta; + while (theta - from.theta > Math.PI) theta -= 2 * Math.PI; + while (theta - from.theta < -Math.PI) theta += 2 * Math.PI; + return { target: (to.target ?? from.target).clone(), radius: to.radius ?? from.radius, theta, phi: to.phi ?? from.phi }; +} + +/** Moves the target sideways and forwards by a drag of (dx, dy) pixels on a viewport of the given height. */ +export function panView(view: OrbitView, dx: number, dy: number, viewportHeight: number, fovDegrees: number): void { + const perPixel = (2 * view.radius * Math.tan((fovDegrees * Math.PI) / 360)) / (viewportHeight || 1); + const right = new Vector3(Math.cos(view.theta), 0, -Math.sin(view.theta)); + const forward = new Vector3(-Math.sin(view.theta), 0, -Math.cos(view.theta)); + view.target.addScaledVector(right, -dx * perPixel); + view.target.addScaledVector(forward, (dy * perPixel) / Math.max(0.35, Math.cos(view.phi))); +} + +/** Turns the view by a one-finger drag; returns the turn so it can carry on as inertia. */ +export function orbitView(view: OrbitView, dx: number, dy: number, viewportHeight: number): { theta: number; phi: number } { + const h = viewportHeight || 1; + const turn = { theta: (-dx / h) * 3.2, phi: (-dy / h) * 2.4 }; + view.theta += turn.theta; + view.phi = clamp(view.phi + turn.phi, MIN_PHI, MAX_PHI); + return turn; +} + +/** One step of inertia: the turn continues and fades. Returns whether anything still moves. */ +export function coast(view: OrbitView, velocity: { theta: number; phi: number }): boolean { + if (Math.abs(velocity.theta) <= 1e-4 && Math.abs(velocity.phi) <= 1e-4) return false; + view.theta += velocity.theta; + view.phi = clamp(view.phi + velocity.phi, MIN_PHI, MAX_PHI); + velocity.theta *= 0.9; + velocity.phi *= 0.9; + return true; +} diff --git a/frontend/src/viewer/export/stl.test.ts b/frontend/src/viewer/export/stl.test.ts new file mode 100644 index 0000000..da77099 --- /dev/null +++ b/frontend/src/viewer/export/stl.test.ts @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { buildStl } from "./stl.ts"; + +test("a triangle becomes 84 header bytes and one 50-byte record, scaled and lifted, z mirrored into y", () => { + const bytes = buildStl([{ positions: [0, 0, 0, 2, 0, 0, 0, 0, 1], lift: 3 }], 10); + assert.equal(bytes.length, 84 + 50); + const view = new DataView(bytes.buffer); + assert.equal(view.getUint32(80, true), 1); + const f = (o: number) => Math.round(view.getFloat32(o, true) * 1000) / 1000 + 0; + // vertices after the normal: (0,0,30) (0,-10,30) (20,0,30) – all at height (0 + 3) m × 10 + const verts = [0, 1, 2].map((k) => [f(96 + k * 12), f(100 + k * 12), f(104 + k * 12)]); + assert.ok(verts.every((v) => v[2] === 30), JSON.stringify(verts)); + assert.deepEqual(new Set(verts.map((v) => `${v[0]},${v[1]}`)), new Set(["0,0", "20,0", "0,-10"])); + assert.deepEqual(verts[0].slice(0, 2), [0, 0], "the corners keep their order"); + assert.ok(f(92) < -0.99, "the winding is kept: this one faces down, as it did in the plan"); + const n = [f(84), f(88), f(92)]; + assert.ok(Math.abs(Math.hypot(...n) - 1) < 0.01 && Math.abs(n[2]) > 0.99, "a flat triangle has an up or down normal"); +}); + +test("degenerate triangles are skipped and an empty house gives only the header", () => { + assert.equal(buildStl([{ positions: [1, 1, 1, 1, 1, 1, 2, 2, 2], lift: 0 }]).length, 84); + assert.equal(buildStl([]).length, 84); +}); diff --git a/frontend/src/viewer/export/stl.ts b/frontend/src/viewer/export/stl.ts new file mode 100644 index 0000000..69d759e --- /dev/null +++ b/frontend/src/viewer/export/stl.ts @@ -0,0 +1,37 @@ +// A binary STL of the house for 3D printing or a slicer: the triangles of every floor's walls (which carry furniture and outdoor +// areas as well) and floors, lifted to the floor's height and scaled; the glass, lights and blinds are left out. + +/** One batch of triangles: positions (three numbers per vertex) and the height the batch stands at. */ +export interface StlPart { + positions: ArrayLike; + /** Added to every y, in metres. */ + lift: number; +} + +/** + * The bytes of a binary STL. Plan x/z become x/y of the print (z down the plan becomes y towards the back), the height stays the + * height; `scale` multiplies metres (10 = 1:100 when a slicer reads millimetres). Degenerate triangles are skipped. + */ +export function buildStl(parts: readonly StlPart[], scale = 10, name = "NextFloor"): Uint8Array { + const tris: number[][] = []; + for (const { positions, lift } of parts) { + for (let i = 0; i + 8 < positions.length; i += 9) { + const v = [0, 3, 6].map((o) => [positions[i + o] * scale, -positions[i + o + 2] * scale, (positions[i + o + 1] + lift) * scale]); + const [a, b, c] = v; + const n = [(b[1] - a[1]) * (c[2] - a[2]) - (b[2] - a[2]) * (c[1] - a[1]), (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2]), (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])]; + const length = Math.hypot(n[0], n[1], n[2]); + if (length < 1e-9) continue; + // (x, y, z) → (x, -z, y) is a turn, not a mirror, so the winding and the normal stay as they were + tris.push([n[0] / length, n[1] / length, n[2] / length, ...a, ...b, ...c]); + } + } + const out = new Uint8Array(84 + tris.length * 50); + const view = new DataView(out.buffer); + out.set(new TextEncoder().encode(`${name} STL`.slice(0, 79)), 0); + view.setUint32(80, tris.length, true); + tris.forEach((t, k) => { + const o = 84 + k * 50; + t.forEach((n, j) => view.setFloat32(o + j * 4, n, true)); + }); + return out; +} diff --git a/frontend/src/viewer/fold.ts b/frontend/src/viewer/fold.ts new file mode 100644 index 0000000..0591c0f --- /dev/null +++ b/frontend/src/viewer/fold.ts @@ -0,0 +1,94 @@ +// Shader patch that shows or hides wall parts on the GPU. Geometry carries a "fold" attribute (see +// build.ts); per floor, one bit mask says which wall buckets stand (the others are cut) and another +// which buckets are drawn as glass. Hidden vertices are moved outside the clip volume, so their +// triangles and lines are dropped before rasterising. +// +// Roles: "plain" (lines, window and door parts) only follows standing/cut; "solid" (walls) also leaves +// out glass buckets; "glass" draws only the wall parts of glass buckets, as tinted glass. +// +// The sloped view lowers every wall part (not furniture) to a plane that leans away from the camera: low on the near +// side, full height on the far side. Painted wall parts (fold value + 128) keep their own colour in every look. + +import type { Material, Vector2, Vector4 } from "three"; + +export interface FoldMask { + value: number; +} + +export interface FoldMasks { + standing: FoldMask; + glass: FoldMask; + /** + * The sloped view: x, z = the direction away from the camera, then the plan distance along it where the walls are lowest + * and where they are full height; and the lowest and the highest wall top (floor coordinates). Off while the first two are 0. + */ + slope?: { value: Vector4 }; + slopeY?: { value: Vector2 }; + /** How opaque glass walls are (0 … 1, default 0.2); one object shared by every floor, so one setting changes them all. */ + glassAlpha?: { value: number }; +} + +export type FoldRole = "plain" | "solid" | "glass"; + +export function makeFoldable(material: T, masks: FoldMasks, role: FoldRole = "plain"): T { + material.onBeforeCompile = (shader) => { + shader.uniforms.uStanding = masks.standing; + shader.uniforms.uGlass = masks.glass; + shader.uniforms.uSlope = masks.slope ?? { value: { x: 0, y: 0, z: 0, w: 0 } }; + shader.uniforms.uSlopeY = masks.slopeY ?? { value: { x: 0, y: 0 } }; + shader.uniforms.uGlassAlpha = masks.glassAlpha ?? { value: 0.2 }; + shader.vertexShader = shader.vertexShader + .replace("#include ", "#include \nattribute float fold;\nuniform int uStanding;\nuniform int uGlass;\nuniform vec4 uSlope;\nuniform vec2 uSlopeY;\nvarying float vNfPaint;") + .replace( + "#include ", + `#include + vNfPaint = fold > 127.5 ? 1.0 : 0.0; + if (fold > -0.5 && (uSlope.x != 0.0 || uSlope.y != 0.0) && int(mod(fold, 128.0) + 0.5) / 16 != 4) { + float nfAlong = clamp((dot(transformed.xz, uSlope.xy) - uSlope.z) / max(uSlope.w - uSlope.z, 0.001), 0.0, 1.0); + transformed.y = min(transformed.y, mix(uSlopeY.x, uSlopeY.y, nfAlong)); + }`, + ) + .replace( + "#include ", + `#include + { + bool nfShow = ${role === "glass" ? "false" : "true"}; + if (fold > -0.5) { + int nfFold = int(mod(fold, 128.0) + 0.5); + int nfKind = nfFold / 16; + int nfBucket = nfFold - nfKind * 16; + bool nfStanding = ((uStanding >> nfBucket) & 1) == 1; + bool nfGlass = ((uGlass >> nfBucket) & 1) == 1; + // kinds: 0 upper part, 1 cut edge, 2 lower part, 3 cap at the cut height, 4 furniture above the cut + nfShow = nfKind == 0 || nfKind == 4 ? nfStanding : nfKind == 1 || nfKind == 3 ? !nfStanding : true; + bool nfWall = nfKind == 0 || nfKind == 2; + ${role === "solid" ? "if (nfGlass && nfWall) nfShow = false;" : ""} + ${role === "glass" ? "nfShow = nfShow && nfGlass && nfWall;" : ""} + } + if (!nfShow) gl_Position = vec4(2.0, 2.0, 2.0, 1.0); + }`, + ); + shader.fragmentShader = shader.fragmentShader.replace("#include ", "#include \nvarying float vNfPaint;\nuniform float uGlassAlpha;"); + if (role !== "glass") { + // painted walls: their own colour, after the look has mapped everything else (see theme.ts) + shader.fragmentShader = shader.fragmentShader.replace( + "#include ", + `#include + #ifdef USE_COLOR + if (vNfPaint > 0.5) diffuseColor.rgb = vColor.rgb; + #endif`, + ); + } + if (role === "glass") { + // dark walls become a faint cyan-tinted glass, as opaque as the setting says + shader.fragmentShader = shader.fragmentShader.replace( + "#include ", + `#include + diffuseColor.rgb = diffuseColor.rgb * 1.7 + vec3(0.015, 0.05, 0.075); + diffuseColor.a *= uGlassAlpha;`, + ); + } + }; + material.customProgramCacheKey = () => `nf-fold-${role}`; + return material; +} diff --git a/frontend/src/viewer/furniture.ts b/frontend/src/viewer/furniture.ts new file mode 100644 index 0000000..b1577ff --- /dev/null +++ b/frontend/src/viewer/furniture.ts @@ -0,0 +1,7 @@ +// Procedural low-poly furniture in the neon look, split into modules in furniture/. + +export { flipWinding } from "./furniture/builder.ts"; +export { pushFurniture } from "./furniture/furniture.ts"; +export { FRIDGE_DOOR, RADIATOR_Y, pushFridgeDoors } from "./furniture/kitchen.ts"; +export { pushPackGlow, pushPackLamp, pushPackMoving } from "./furniture/packs.ts"; +export { batteryBar, pictureRect, screenRect } from "./furniture/screens.ts"; diff --git a/frontend/src/viewer/furniture/builder.ts b/frontend/src/viewer/furniture/builder.ts new file mode 100644 index 0000000..d735453 --- /dev/null +++ b/frontend/src/viewer/furniture/builder.ts @@ -0,0 +1,206 @@ +// The drawing tool for furniture models. A model is built from boxes, lofts, cylinders and sweeps in local coordinates (x +// across, z in depth with the front at +z, y up), which the builder turns and moves into the plan. + +import { Color } from "three"; +import type { Vec2 } from "../../model.ts"; +import { ALWAYS, DEG, pushLoft, pushLyingCyl, pushPrism, pushSkin, type GeoBuffer, type LineBuffer } from "../geo.ts"; +import { counterClockwise } from "../build/outline.ts"; +import { EDGE_FURN, type Material } from "./palette.ts"; + +/** Maps a local (x, z) to a plan point. */ +export type Plan = (x: number, z: number) => Vec2; + +/** A box as ranges along the three local axes. */ +export interface Block { + x: [number, number]; + y: [number, number]; + z: [number, number]; +} + +/** Whether a plan transform mirrors (its determinant is negative). */ +export function mirrors(plan: Plan): boolean { + const origin = plan(0, 0); + const ex = plan(1, 0); + const ez = plan(0, 1); + return (ex[0] - origin[0]) * (ez[1] - origin[1]) - (ex[1] - origin[1]) * (ez[0] - origin[0]) < 0; +} + +/** Swaps the second and third vertex of every triangle from `from` on (positions, colours, folds, uvs, tiles). */ +export function flipWinding(buf: GeoBuffer, from: number): void { + const swapped = (values: number[] | null, start: number, size: number) => { + if (!values) return; + for (let k = 0; k < size; k++) { + const [i, j] = [start + size + k, start + 2 * size + k]; + [values[i], values[j]] = [values[j], values[i]]; + } + }; + for (let i = from; i < buf.p.length; i += 9) { + const tri = i / 9; + swapped(buf.p, i, 3); + swapped(buf.c, i, 3); + swapped(buf.f, tri * 3, 1); + swapped(buf.uv, tri * 6, 2); + swapped(buf.tile, tri * 6, 2); + } +} + +export class Builder { + /** The transform mirrors: parts that do not wind themselves counter-clockwise come out inside out. */ + readonly mirrored: boolean; + + private readonly buf: GeoBuffer; + private readonly lines: LineBuffer; + readonly plan: Plan; + + constructor(buf: GeoBuffer, lines: LineBuffer, plan: Plan) { + this.buf = buf; + this.lines = lines; + this.plan = plan; + this.mirrored = mirrors(plan); + } + + /** The same buffers with the local coordinates turned by `deg` around (cx, cz): turned parts of pack items. */ + turned(cx: number, cz: number, deg: number): Builder { + const [c, s] = [Math.cos(deg * DEG), Math.sin(deg * DEG)]; + return new Builder(this.buf, this.lines, (x, z) => this.plan(cx + (x - cx) * c - (z - cz) * s, cz + (x - cx) * s + (z - cz) * c)); + } + + /** A line between two local points at the heights ya and yb. */ + seg(xa: number, ya: number, za: number, xb: number, yb: number, zb: number, color: Color = EDGE_FURN): void { + this.edge(this.plan(xa, za), this.plan(xb, zb), ya, yb, color); + } + + private edge(a: Vec2, b: Vec2, ya: number, yb: number, color: Color): void { + this.lines.seg([a[0], ya, a[1]], [b[0], yb, b[1]], color, ALWAYS); + } + + /** An axis-aligned box. `edges` draws its outline. */ + block({ x: [x0, x1], y: [y0, y1], z: [z0, z1] }: Block, material: Material, edges: Color | null = null): void { + if (x1 - x0 < 1e-4 || z1 - z0 < 1e-4 || y1 - y0 < 1e-4) return; + const footprint = [this.plan(x0, z0), this.plan(x0, z1), this.plan(x1, z1), this.plan(x1, z0)]; + pushPrism(this.buf, counterClockwise(footprint), y0, y1, material.side, material.top, { aoFrom: 0, bottom: y0 > 0.05 }); + if (edges) { + footprint.forEach((a, i) => { + this.edge(a, footprint[(i + 1) % 4], y1, y1, edges); + this.edge(a, a, y0, y1, edges); + }); + } + } + + /** An upright prism over any outline given in local coordinates (stair treads, winders, landings). */ + prism(outline: readonly Vec2[], y0: number, y1: number, material: Material, edges: Color | null = null): void { + if (outline.length < 3 || y1 - y0 < 1e-4) return; + const footprint = outline.map(([x, z]) => this.plan(x, z)); + pushPrism(this.buf, counterClockwise(footprint), y0, y1, material.side, material.top, { aoFrom: Math.min(0, y0), bottom: true }); + if (edges) footprint.forEach((a, i) => this.edge(a, footprint[(i + 1) % footprint.length], y1, y1, edges)); + } + + /** A box whose top face is another rectangle (sloped sides): hoods, windscreens, tapered shades. Rectangles are [x0, x1, z0, z1]. */ + loft(base: [number, number, number, number], top: [number, number, number, number], y0: number, y1: number, material: Material, edges: Color | null = null): void { + if (y1 - y0 < 1e-4) return; + const corners = (r: [number, number, number, number]): Vec2[] => [this.plan(r[0], r[2]), this.plan(r[0], r[3]), this.plan(r[1], r[3]), this.plan(r[1], r[2])]; + const lo = corners(base); + const hi = corners(top); + if (lo !== counterClockwise(lo)) { + lo.reverse(); + hi.reverse(); + } + pushLoft(this.buf, lo, hi, y0, y1, material.side, material.top); + if (edges) { + for (let i = 0; i < 4; i++) { + this.edge(hi[i], hi[(i + 1) % 4], y1, y1, edges); + this.edge(lo[i], hi[i], y0, y1, edges); + } + } + } + + /** + * A smooth body swept along z: at every station a rounded cross section from y0 to y1, `hw` wide to each side of the centre + * x (cars, boats, anything with a curved hull). `exp` shapes the section: 2 is an ellipse, higher is boxier. `edges` draws + * the ridge along the top. + */ + sweep(stations: { x: number; z: number; y0: number; y1: number; hw: number }[], material: Material, sides = 16, exp = 2.6, edges: Color | null = null): void { + if (stations.length < 2) return; + const rings = stations.map((st) => { + const [halfHeight, halfWidth] = [Math.max(0.004, (st.y1 - st.y0) / 2), Math.max(0.004, st.hw)]; + const middle = (st.y0 + st.y1) / 2; + return Array.from({ length: sides }, (_, i) => { + const angle = (i / sides) * Math.PI * 2; + const [c, s] = [Math.cos(angle), Math.sin(angle)]; + const [wx, wz] = this.plan(st.x + halfWidth * Math.sign(c) * Math.abs(c) ** (2 / exp), st.z); + return [wx, middle + halfHeight * Math.sign(s) * Math.abs(s) ** (2 / exp), wz]; + }); + }); + pushSkin(this.buf, rings, material.side, material.top); + if (edges) { + const ridge = Math.round(sides / 4); + for (let s = 0; s + 1 < rings.length; s++) this.lines.seg(rings[s][ridge], rings[s + 1][ridge], edges, ALWAYS); + } + } + + /** A box with bevelled top and bottom edges (cushions, mattresses, arm rests). */ + pad(block: Block, material: Material, radius = 0.03, edges: Color | null = null): void { + const { x: [x0, x1], y: [y0, y1], z: [z0, z1] } = block; + const r = Math.min(radius, (x1 - x0) / 2 - 0.005, (z1 - z0) / 2 - 0.005, (y1 - y0) / 2); + if (r < 0.008) return this.block(block, material, edges); + const side = { side: material.side, top: material.side }; + this.loft([x0 + r, x1 - r, z0 + r, z1 - r], [x0, x1, z0, z1], y0, y0 + r, side); + if (y1 - y0 - 2 * r > 0.005) this.block({ x: [x0, x1], y: [y0 + r, y1 - r], z: [z0, z1] }, side, edges); + this.loft([x0, x1, z0, z1], [x0 + r, x1 - r, z0 + r, z1 - r], y1 - r, y1, material); + } + + /** A cylinder lying along x or z (wheels, rollers). `edges` draws both rims. */ + lyingCylinder(axis: "x" | "z", cx: number, cz: number, y0: number, y1: number, length: number, diameter: number, material: Material, sides = 12, edges: Color | null = null): void { + const r = Math.min(diameter, y1 - y0) / 2; + if (r < 1e-4 || length < 1e-4) return; + const cy = (y0 + y1) / 2; + const [along, across] = axis === "x" ? [cx, cz] : [cz, cx]; + const at = (a: number, c: number): Vec2 => (axis === "x" ? this.plan(a, c) : this.plan(c, a)); + const first = this.buf.p.length; + pushLyingCyl(this.buf, at, along - length / 2, along + length / 2, across, cy, r, material.side, material.top, sides); + if (this.mirrored) flipWinding(this.buf, first); + if (!edges) return; + for (const a of [along - length / 2, along + length / 2]) { + for (let i = 0; i < sides; i++) { + const [t0, t1] = [(i / sides) * Math.PI * 2, ((i + 1) / sides) * Math.PI * 2]; + this.edge(at(a, across + Math.sin(t0) * r), at(a, across + Math.sin(t1) * r), cy + Math.cos(t0) * r, cy + Math.cos(t1) * r, edges); + } + } + } + + /** An upright cylinder with `sides` sides. */ + cylinder(cx: number, cz: number, r: number, y0: number, y1: number, material: Material, sides = 10, edges: Color | null = null): void { + const footprint = Array.from({ length: sides }, (_, i) => this.plan(cx + Math.cos((i / sides) * Math.PI * 2) * r, cz + Math.sin((i / sides) * Math.PI * 2) * r)); + pushPrism(this.buf, counterClockwise(footprint), y0, y1, material.side, material.top, { aoFrom: 0, bottom: y0 > 0.05 }); + if (edges) footprint.forEach((a, i) => this.edge(a, footprint[(i + 1) % sides], y1, y1, edges)); + } + + /** A ring of line on a front face (z = front): dials, fans, door outlines. */ + ring(cx: number, cy: number, r: number, z: number, segments = 20, color: Color = EDGE_FURN): void { + for (let i = 0; i < segments; i++) { + const [a0, a1] = [(i / segments) * Math.PI * 2, ((i + 1) / segments) * Math.PI * 2]; + this.seg(cx + Math.cos(a0) * r, cy + Math.sin(a0) * r, z, cx + Math.cos(a1) * r, cy + Math.sin(a1) * r, z, color); + } + } +} + +/** The soft contact shadow under an item: a dark core that fades out beyond its footprint. */ +export function contactShadow(shadow: GeoBuffer, plan: Plan, w: number, d: number, strength: number): void { + const grow = Math.min(0.14, Math.max(0.06, Math.min(w, d) * 0.15)); + const dark = new Color(1 - strength, 1 - strength, 1 - strength); + const clear = new Color(1, 1, 1); + const y = 0.003; + const ring = (g: number): Vec2[] => [plan(-w / 2 - g, -d / 2 - g), plan(w / 2 + g, -d / 2 - g), plan(w / 2 + g, d / 2 + g), plan(-w / 2 - g, d / 2 + g)]; + const [inner, outer] = [ring(0), ring(grow)]; + const at = (p: Vec2) => [p[0], y, p[1]]; + const first = shadow.p.length; + shadow.tri(at(inner[0]), at(inner[1]), at(inner[2]), dark); + shadow.tri(at(inner[0]), at(inner[2]), at(inner[3]), dark); + for (let i = 0; i < 4; i++) { + const j = (i + 1) % 4; + shadow.tri(at(inner[i]), at(outer[i]), at(outer[j]), dark, clear, clear); + shadow.tri(at(inner[i]), at(outer[j]), at(inner[j]), dark, clear, dark); + } + if (mirrors(plan)) flipWinding(shadow, first); +} + diff --git a/frontend/src/viewer/furniture/furniture.test.ts b/frontend/src/viewer/furniture/furniture.test.ts new file mode 100644 index 0000000..3c8fd49 --- /dev/null +++ b/frontend/src/viewer/furniture/furniture.test.ts @@ -0,0 +1,227 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { Color } from "three"; +import { FURNITURE_SIZE, FURNITURE_TYPES, newFloor, type Furniture } from "../../model.ts"; +import { setPacks } from "../../packs.ts"; +import { GeoBuffer, LineBuffer } from "../geo.ts"; +import { Builder, contactShadow, flipWinding, mirrors, type Plan } from "./builder.ts"; +import { pushFurniture } from "./furniture.ts"; +import { FRIDGE_DOOR, pushFridgeDoors, RADIATOR_Y } from "./kitchen.ts"; +import { M } from "./palette.ts"; +import { pushPackGlow, pushPackLamp } from "./packs.ts"; +import { legs } from "./parts.ts"; +import { screenRect } from "./screens.ts"; + +const identity: Plan = (x, z) => [x, z]; +const mirrored: Plan = (x, z) => [-x, z]; +const tools = (plan: Plan = identity) => { + const buf = new GeoBuffer(); + const lines = new LineBuffer(); + return { buf, lines, b: new Builder(buf, lines, plan) }; +}; +const ys = (buf: GeoBuffer) => buf.p.filter((_, i) => i % 3 === 1); +const piece = (type: string, extra: Partial = {}): Furniture => { + const size = (FURNITURE_SIZE as Record)[type] ?? [1, 0.6, 0.8]; + return { id: "f", type, x: 2, z: 1, rotation: 0, w: size[0], d: size[1], h: size[2], variant: null, entity: null, power: null, ...extra }; +}; +function draw(f: Furniture, base = 0) { + const [buf, lines, shadow] = [new GeoBuffer(), new LineBuffer(), new GeoBuffer()]; + pushFurniture(buf, lines, shadow, f, base); + return { buf, lines, shadow }; +} + +test("a mirroring transform is told apart from a plain one", () => { + assert.equal(mirrors(identity), false); + assert.equal(mirrors(mirrored), true); + assert.equal(mirrors((x, z) => [z, x]), true); + assert.equal(mirrors((x, z) => [z, -x]), false); +}); + +test("a box adds a prism with a top, an outline when asked, and nothing when it is flat", () => { + const { buf, lines, b } = tools(); + b.block({ x: [0, 1], y: [0, 1], z: [0, 1] }, M.wood); + assert.equal(buf.count, 10); + assert.equal(lines.p.length, 0); + const withEdges = tools(); + withEdges.b.block({ x: [0, 1], y: [0, 1], z: [0, 1] }, M.wood, new Color(1, 1, 1)); + assert.equal(withEdges.lines.p.length / 6, 8, "four top edges and four verticals"); + const flat = tools(); + flat.b.block({ x: [0, 1], y: [0.5, 0.5], z: [0, 1] }, M.wood); + assert.equal(flat.buf.count, 0); +}); + +test("a box above the floor also gets a bottom face", () => { + const low = tools(); + low.b.block({ x: [0, 1], y: [0, 1], z: [0, 1] }, M.wood); + const lifted = tools(); + lifted.b.block({ x: [0, 1], y: [0.5, 1.5], z: [0, 1] }, M.wood); + assert.equal(lifted.buf.count, low.buf.count + 2); +}); + +test("a turned builder rotates its parts around the given centre", () => { + const { buf, b } = tools(); + b.turned(0, 0, 90).block({ x: [1, 2], y: [0, 1], z: [0, 0.5] }, M.wood); + const xs = buf.p.filter((_, i) => i % 3 === 0); + const zs = buf.p.filter((_, i) => i % 3 === 2); + assert.ok(Math.min(...zs) >= 0.99 && Math.max(...zs) <= 2.01, "x along became z"); + assert.ok(Math.min(...xs) >= -0.51 && Math.max(...xs) <= 0.01); +}); + +test("a loft, a pad and a sweep add geometry; a pad too small to bevel is a plain box", () => { + const loft = tools(); + loft.b.loft([0, 1, 0, 1], [0.2, 0.8, 0.2, 0.8], 0, 1, M.wood); + assert.ok(loft.buf.count > 8); + const pad = tools(); + pad.b.pad({ x: [0, 1], y: [0, 0.3], z: [0, 1] }, M.fabric, 0.05); + const box = tools(); + box.b.block({ x: [0, 1], y: [0, 0.3], z: [0, 1] }, M.fabric); + assert.ok(pad.buf.count > box.buf.count); + const tiny = tools(); + tiny.b.pad({ x: [0, 1], y: [0, 0.3], z: [0, 1] }, M.fabric, 0.001); + assert.equal(tiny.buf.count, box.buf.count); + const sweep = tools(); + sweep.b.sweep([{ x: 0, z: -1, y0: 0, y1: 1, hw: 0.4 }, { x: 0, z: 1, y0: 0, y1: 0.5, hw: 0.3 }], M.metal); + assert.ok(sweep.buf.count > 16); + const none = tools(); + none.b.sweep([{ x: 0, z: 0, y0: 0, y1: 1, hw: 1 }], M.metal); + assert.equal(none.buf.count, 0); +}); + +test("cylinders: upright with n sides, lying along either axis, flipped when mirrored", () => { + const upright = tools(); + upright.b.cylinder(0, 0, 0.5, 0, 1, M.metal, 8); + assert.equal(upright.buf.count, 8 - 2 + 8 * 2, "a top fan and two triangles per side"); + for (const axis of ["x", "z"] as const) { + const lying = tools(); + lying.b.lyingCylinder(axis, 0, 0, 0, 0.5, 1, 0.5, M.metal, 8); + assert.equal(lying.buf.count, 8 * 2 + 8 * 2); + const span = (i: number) => Math.max(...lying.buf.p.filter((_, k) => k % 3 === i)) - Math.min(...lying.buf.p.filter((_, k) => k % 3 === i)); + assert.ok(Math.abs(span(axis === "x" ? 0 : 2) - 1) < 1e-9, "the length along its axis"); + } + const normal = tools(identity); + const flipped = tools(mirrored); + normal.b.lyingCylinder("x", 0, 0, 0, 0.5, 1, 0.5, M.metal, 6); + flipped.b.lyingCylinder("x", 0, 0, 0, 0.5, 1, 0.5, M.metal, 6); + assert.equal(normal.buf.count, flipped.buf.count); +}); + +test("flipping the winding swaps the second and third vertex of each triangle", () => { + const buf = new GeoBuffer(true); + buf.tri([0, 0, 0], [1, 0, 0], [0, 0, 1], new Color(0.1, 0.2, 0.3), new Color(0.4, 0.5, 0.6), new Color(0.7, 0.8, 0.9), [0, 0, 1, 0, 0, 1], 5); + flipWinding(buf, 0); + assert.deepEqual(buf.p, [0, 0, 0, 0, 0, 1, 1, 0, 0]); + assert.ok(Math.abs(buf.c[3] - 0.7) < 1e-6 && Math.abs(buf.c[5] - 0.9) < 1e-6); + assert.deepEqual(buf.uv, [0, 0, 0, 1, 1, 0]); +}); + +test("a ring draws its segments, and a contact shadow fades out beyond the footprint", () => { + const { lines, b } = tools(); + b.ring(0, 1, 0.3, 0, 16); + assert.equal(lines.p.length / 6, 16); + const shadow = new GeoBuffer(); + contactShadow(shadow, identity, 1, 1, 0.5); + assert.equal(shadow.count, 2 + 8); + assert.ok(shadow.c.some((v) => v === 0.5) && shadow.c.some((v) => v === 1)); +}); + +test("legs stand in the corners of the footprint", () => { + const { buf, b } = tools(); + legs(b, 2, 1, 0.5, 0.1, 0.05); + assert.equal(buf.count / 10, 4); + assert.ok(Math.max(...buf.p.filter((_, i) => i % 3 === 0)) <= 1 + 1e-9); +}); + +test("every built-in type draws something, except the stairwell opening", () => { + for (const type of FURNITURE_TYPES) { + const { buf, lines } = draw(piece(type)); + if (type === "stairwell") assert.equal(buf.count + lines.p.length, 0); + else assert.ok(buf.count + lines.p.length > 0, type); + } +}); + +test("free-standing furniture casts a contact shadow, wall-mounted and flat things do not", () => { + for (const type of ["sofa", "table", "fridge", "plant", "bed"]) assert.ok(draw(piece(type)).shadow.count > 0, type); + for (const type of ["rug", "kitchen_wall", "tv_wall", "radiator", "parking", "wallbox", "meter", "inverter"]) assert.equal(draw(piece(type)).shadow.count, 0, type); +}); + +test("an item lifted by its mount height moves up as a whole and loses its floor shadow", () => { + const onFloor = draw(piece("shelf"), 0); + const lifted = draw(piece("shelf"), 1.0); + assert.equal(lifted.shadow.count, 0); + assert.ok(Math.min(...ys(lifted.buf)) > Math.min(...ys(onFloor.buf)) + 0.5); +}); + +test("mirroring keeps the model but turns it around its own axis", () => { + const plain = draw(piece("sofa", { x: 0, z: 0 })); + const flipped = draw(piece("sofa", { x: 0, z: 0, mirror: true })); + assert.equal(plain.buf.count, flipped.buf.count); + const xs = (buf: GeoBuffer) => buf.p.filter((_, i) => i % 3 === 0); + assert.ok(Math.abs(Math.min(...xs(plain.buf)) + Math.max(...xs(flipped.buf))) < 1e-9); +}); + +test("a sofa gets one more seat for every 62 cm of width", () => { + const small = draw(piece("sofa", { w: 1.2 })).buf.count; + const large = draw(piece("sofa", { w: 2.8 })).buf.count; + assert.ok(large > small); +}); + +test("a smart fridge's doors swing open and turn red", () => { + const f = { x: 0, z: 0, rotation: 0, w: 0.9, d: 0.7, h: 1.8 }; + const closed = new GeoBuffer(); + const open = new GeoBuffer(); + pushFridgeDoors(closed, f, 0, 0, 0); + pushFridgeDoors(open, f, 0, 1, 0); + assert.equal(closed.count, open.count); + assert.ok(closed.count > 20); + const redness = (buf: GeoBuffer) => buf.c.filter((_, i) => i % 3 === 0).reduce((a, c) => a + c, 0) - buf.c.filter((_, i) => i % 3 === 1).reduce((a, c) => a + c, 0); + assert.ok(redness(open) > redness(closed)); + const zs = (buf: GeoBuffer) => Math.max(...buf.p.filter((_, i) => i % 3 === 2)); + assert.ok(zs(open) > zs(closed), "an open door reaches out into the room"); + assert.ok(FRIDGE_DOOR > 0 && RADIATOR_Y > 0); +}); + +test("screens: where a TV or an appliance's glowing front is, with and without a mount, mirrored or not", () => { + const floor = newFloor("f", "F", 0); + const board = screenRect(piece("tv_board", { w: 1.6, d: 0.4, h: 0.5 }), floor)!; + assert.ok(board.x1 > board.x0 && board.y1 > board.y0); + const mirroredBoard = screenRect(piece("tv_board", { w: 1.6, d: 0.4, h: 0.5, mirror: true }), floor)!; + assert.ok(Math.abs(mirroredBoard.x0 + board.x1) < 1e-9); + assert.equal(screenRect(piece("sofa"), floor), null); + assert.ok(screenRect(piece("washer"), floor)!.y1 > 0); + assert.ok(screenRect(piece("radiator"), floor)!.y0 > RADIATOR_Y); + const wall = screenRect(piece("tv_wall", { w: 1.2, d: 0.1, h: 0.7 }), floor)!; + assert.ok(wall.y0 > 0.9 && wall.y1 < 1.7); +}); + +test("pack items: parts scaled to the size, a chosen colour for painted parts, lamps and glow layers", () => { + const part = (extra: object) => ({ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body", ...extra }); + setPacks([{ id: "t", name: "T", publisher: "t", items: [ + { id: "thing", name: { en: "Thing" }, size: [1, 1, 1], colors: [{ id: "red", name: { en: "r" }, hex: "#ff0000" }, { id: "blue", name: { en: "b" }, hex: "#0000ff" }], parts: [part({ paint: true }), part({ shape: "cyl", w: 0.4, d: 0.4 }), part({ shape: "sweep", stations: [[-0.5, 0, 1, 1], [0.5, 0, 0.5, 0.5]] })] }, + { id: "lamp", name: { en: "Lamp" }, size: [0.3, 0.3, 0.5], light: "pendant", parts: [part({ glow: true }), part({ color: "#445566" })] }, + ] } as never]); + const red = draw(piece("pack:t:thing", { variant: "red", w: 2, d: 1, h: 1 })); + const blue = draw(piece("pack:t:thing", { variant: "blue", w: 2, d: 1, h: 1 })); + assert.notDeepEqual(red.buf.c, blue.buf.c); + assert.ok(Math.max(...red.buf.p.filter((_, i) => i % 3 === 0)) - Math.min(...red.buf.p.filter((_, i) => i % 3 === 0)) >= 2 - 1e-9, "scaled to 2 m wide"); + assert.equal(draw(piece("pack:t:thing"), 1).shadow.count, 0, "above the floor: no shadow"); + assert.ok(draw(piece("pack:t:thing"), 0).shadow.count > 0); + const lit = new GeoBuffer(); + const dark = new GeoBuffer(); + const item = { id: "lamp", name: {}, size: [0.3, 0.3, 0.5], parts: [part({ glow: true }), part({ color: "#445566" })] } as never; + pushPackLamp(lit, item, piece("x", { w: 0.3, d: 0.3, h: 0.5 }), 0, 0xffee88); + pushPackGlow(dark, item, piece("x", { w: 0.3, d: 0.3, h: 0.5 }), 0, 0xff0000); + assert.ok(lit.count > dark.count, "a lamp draws all parts, a glow layer only the glowing ones"); + assert.ok(lit.c.some((v) => Math.abs(v - 1) < 1e-6) || lit.c.length > 0); + const unknown = draw(piece("pack:gone:thing")); + assert.ok(unknown.buf.count > 0, "a missing pack item stays a plain box"); +}); + +test("a TV set to no glow loses its bright blue rim, with the same shape", () => { + const brightest = (l: LineBuffer) => (l as unknown as { c: number[] }).c.reduce((a, v) => a + v, 0); + for (const type of ["tv_board", "tv_wall"]) { + const lit = draw(piece(type, { w: 1.6, d: 0.4, h: 0.5 })); + const dark = draw(piece(type, { w: 1.6, d: 0.4, h: 0.5, ambilight: 0 })); + assert.equal(dark.buf.count, lit.buf.count, type); + assert.ok(brightest(dark.lines) < brightest(lit.lines), type); + } +}); diff --git a/frontend/src/viewer/furniture/furniture.ts b/frontend/src/viewer/furniture/furniture.ts new file mode 100644 index 0000000..c4db31c --- /dev/null +++ b/frontend/src/viewer/furniture/furniture.ts @@ -0,0 +1,266 @@ +// Procedural low-poly furniture in the neon look. Every model is built from boxes and cylinders in local coordinates (x +// across, z in depth with the front at +z, y up) scaled to the item's size, then turned and moved into place. Solids go into +// the floor's wall buffer, main outlines into its line buffer and a soft contact shadow into the shadow layer, so furniture +// adds no draw calls. + +import { builtinBase, type Furniture } from "../../model.ts"; +import { packItem } from "../../packs.ts"; +import { GeoBuffer, type LineBuffer } from "../geo.ts"; +import { Builder, contactShadow } from "./builder.ts"; +import { bunkBed, barStool, bed, bench, chair, officeChair, shapedSofa, sofa, stool } from "./seating.ts"; +import { bathtub, dishwasher, fridge, fridgeSmart, island, kitchenTall, kitchenUnit, kitchenWall, laundry, radiator, shower, sink, stove, washbasin, wc, worktopOnly } from "./kitchen.ts"; +import { coatRack, coffeeTable, desk, dresser, nightstand, plant, roundTable, rug, shelf, sideboard, stairs, table, tvBoard, tvWall } from "./living.ts"; +import { gridCabinet, homeBattery, inverter, meterCabinet, wallbox } from "./technical.ts"; +import { packModel, placement } from "./packs.ts"; +import { shapedStairs } from "./stairs.ts"; +import { cabinet } from "./parts.ts"; +import { EDGE_FAINT, EDGE_FURN, M } from "./palette.ts"; + +/** What a model returns to say whether it casts a contact shadow on the floor. */ +type Shadow = "yes" | "no"; + +/** Draws one built-in model. Returns "no" for items that hang on a wall or lie flat, "yes" for those standing on the floor. */ +function drawBuiltIn(b: Builder, f: Furniture, w: number, d: number, h: number, base: number): Shadow { + switch (f.type) { + case "sofa": + if (f.variant === "l" || f.variant === "u") shapedSofa(b, w, d, h, f.variant); + else sofa(b, w, d, h, Math.max(1, Math.round((w - 0.4) / 0.62))); + return "yes"; + case "armchair": + sofa(b, w, d, h, 1); + return "yes"; + case "bed": + bed(b, w, d, h); + return "yes"; + case "chair": + chair(b, w, d, h); + return "yes"; + case "table": + table(b, w, d, h); + return "yes"; + case "desk": + desk(b, w, d, h); + return "yes"; + case "nightstand": + nightstand(b, w, d, h); + return "yes"; + case "wardrobe": + cabinet(b, w, d, h, Math.max(2, Math.round(w / 0.5)), h * 0.5); + return "yes"; + case "tall_cabinet": + cabinet(b, w, d, h, 1, h * 0.5); + return "yes"; + case "shelf": + shelf(b, w, d, h); + return "yes"; + case "kitchen": + kitchenUnit(b, w, d, h); + return "yes"; + case "fridge": + fridge(b, w, d, h); + return "yes"; + case "fridge_smart": + fridgeSmart(b, w, d, h); + return "yes"; + case "stove": + stove(b, w, d, h); + return "yes"; + case "sink": + sink(b, w, d, h); + return "yes"; + case "bathtub": + bathtub(b, w, d, h); + return "yes"; + case "shower": + shower(b, w, d, h); + return "yes"; + case "wc": + wc(b, w, d, h); + return "yes"; + case "washbasin": + washbasin(b, w, d, h); + return "yes"; + case "tv_board": + tvBoard(b, w, d, h, f.ambilight === 0 ? EDGE_FURN : undefined); + return "yes"; + case "plant": + plant(b, w, d, h); + return "yes"; + case "rug": + rug(b, w, d); + return "no"; + case "stairs": + if (f.stair) { + shapedStairs(b, f, w, d, h); + return f.stair.down ? "no" : "yes"; + } + stairs(b, w, d, h); + return "yes"; + case "stairwell": + return "no"; // only a hole in the floor (see stairHoles in build.ts), nothing to draw + case "sideboard": + sideboard(b, w, d, h); + return "yes"; + case "dresser": + dresser(b, w, d, h); + return "yes"; + case "coat_rack": + coatRack(b, w, d, h); + return "yes"; + case "bench": + bench(b, w, d, h, false); + return "yes"; + case "corner_bench": + bench(b, w, d, h, true); + return "yes"; + case "bar_stool": + barStool(b, w, d, h); + return "yes"; + case "office_chair": + officeChair(b, w, d, h); + return "yes"; + case "stool": + stool(b, w, d, h); + return "yes"; + case "kitchen_wall": + kitchenWall(b, w, d, h); + return "no"; // hangs on the wall + case "kitchen_tall": + kitchenTall(b, w, d, h); + return "yes"; + case "island": + island(b, w, d, h); + return "yes"; + case "worktop": + worktopOnly(b, w, d, h); + return "no"; + case "dishwasher": + dishwasher(b, w, d, h); + return "yes"; + case "washer": + laundry(b, w, d, h, false); + return "yes"; + case "dryer": + laundry(b, w, d, h, true); + return "yes"; + case "bunk_bed": + bunkBed(b, w, d, h); + return "yes"; + case "table_round": + roundTable(b, w, d, h); + return "yes"; + case "coffee_table": + coffeeTable(b, w, d, h); + return "yes"; + case "tv_wall": + tvWall(b, w, d, h, f.ambilight === 0 ? EDGE_FURN : undefined); + return "no"; + case "parking": { + // only the marking of the spot: a vehicle standing in it is added by the viewer + const y = 0.012; + const corners: [number, number][] = [[-w / 2, -d / 2], [w / 2, -d / 2], [w / 2, d / 2], [-w / 2, d / 2]]; + corners.forEach(([x, z], i) => b.seg(x, y, z, corners[(i + 1) % 4][0], y, corners[(i + 1) % 4][1], EDGE_FAINT)); + // an arrow head at the front: the direction the vehicle faces + b.seg(-w * 0.15, y, d / 2 - 0.45, 0, y, d / 2 - 0.2, EDGE_FURN); + b.seg(0, y, d / 2 - 0.2, w * 0.15, y, d / 2 - 0.45, EDGE_FURN); + return "no"; + } + case "robot_vacuum": + // only the dock: the robot itself is drawn (and moved) by the viewer + b.block({ x: [-w * 0.45, w * 0.45], y: [0, h], z: [-d / 2, -d / 2 + d * 0.3] }, M.white, EDGE_FURN); + b.block({ x: [-w * 0.2, w * 0.2], y: [h * 0.5, h * 0.62], z: [-d / 2 + d * 0.3, -d / 2 + d * 0.31] }, M.accent); + return "no"; + case "radiator": + radiator(b, w, d, h); + return "no"; // on the wall + case "inverter": + inverter(b, w, d, h, f.variant ?? null); + return "no"; + case "grid_point": + gridCabinet(b, w, d, h); + return "yes"; + case "wallbox": + wallbox(b, w, d, h); + return "no"; + case "meter": + meterCabinet(b, w, d, h); + return "no"; + case "home_battery": + homeBattery(b, w, d, h, f.variant ?? null); + return f.variant === "wall" ? "no" : "yes"; + default: { + const item = packItem(f.type); + if (!item) { + b.block({ x: [-w / 2, w / 2], y: [0, h], z: [-d / 2, d / 2] }, M.body, EDGE_FURN); + return "yes"; + } + // a pet is drawn by the view's own layer, where it walks around + if (item.pet) return "no"; + packModel(b, item, w, d, h, base, null, null, f.variant ?? null); + // items on furniture, walls or ceilings cast no shadow on the floor + return base > 0.05 ? "no" : "yes"; + } + } +} + +function buildFurniture(buf: GeoBuffer, lines: LineBuffer, shadow: GeoBuffer, f: Furniture, base: number): void { + const plan = placement(f); + const b = new Builder(buf, lines, plan); + const [w, d, h] = [Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.005, f.h)]; + if (drawBuiltIn(b, f, w, d, h, base) === "yes") contactShadow(shadow, plan, w, d, f.type === "plant" ? 0.35 : 0.5); +} + +/** + * Draws a piece of furniture. A mirrored item needs no rewinding here: boxes, lofts and upright cylinders wind themselves + * counter-clockwise, and lying cylinders and the contact shadow rewind themselves when the transform mirrors. + */ +/** Turns a vector about a unit axis by `angle` radians (Rodrigues). */ +function turn(v: [number, number, number], k: [number, number, number], angle: number): [number, number, number] { + const [c, s] = [Math.cos(angle), Math.sin(angle)]; + const dot = k[0] * v[0] + k[1] * v[1] + k[2] * v[2]; + const cross: [number, number, number] = [k[1] * v[2] - k[2] * v[1], k[2] * v[0] - k[0] * v[2], k[0] * v[1] - k[1] * v[0]]; + return [v[0] * c + cross[0] * s + k[0] * dot * (1 - c), v[1] * c + cross[1] * s + k[1] * dot * (1 - c), v[2] * c + cross[2] * s + k[2] * dot * (1 - c)]; +} + +/** + * Tilts what was just built (the vertices and lines from the given starts on) about the item's own axes, round the middle of its + * underside: `tilt_x` about its width axis, `tilt_z` about its depth axis, both after its turn about the vertical axis. + */ +export function tiltBuilt(buf: GeoBuffer, lines: LineBuffer, from: { vertex: number; line: number }, f: Pick, y: number): void { + const [px, pz] = [f.tilt_x ?? 0, f.tilt_z ?? 0]; + if (!px && !pz) return; + const yaw = (f.rotation * Math.PI) / 180; + const widthAxis: [number, number, number] = [Math.cos(yaw), 0, Math.sin(yaw)]; + const depthAxis: [number, number, number] = [-Math.sin(yaw), 0, Math.cos(yaw)]; + const move = (p: number[], start: number) => { + for (let i = start; i + 2 < p.length; i += 3) { + let v: [number, number, number] = [p[i] - f.x, p[i + 1] - y, p[i + 2] - f.z]; + if (px) v = turn(v, widthAxis, (px * Math.PI) / 180); + if (pz) v = turn(v, depthAxis, (pz * Math.PI) / 180); + p[i] = f.x + v[0]; + p[i + 1] = y + v[1]; + p[i + 2] = f.z + v[2]; + } + }; + move(buf.p, from.vertex); + move(lines.p, from.line); +} + +export function pushFurniture(buf: GeoBuffer, lines: LineBuffer, shadow: GeoBuffer, f: Furniture, base = 0): void { + const start = { vertex: buf.p.length, line: lines.p.length }; + pushUpright(buf, lines, shadow, f, base); + tiltBuilt(buf, lines, start, f, base); +} + +function pushUpright(buf: GeoBuffer, lines: LineBuffer, shadow: GeoBuffer, f: Furniture, base = 0): void { + // pack items place their parts at `base` themselves; built-in models are drawn on the floor and lifted as a whole (a dryer on the + // washer, a shelf on the wall), without a shadow on the floor. The mount height is absolute: a wall cabinet drawn at 1.45 m + // moves by the difference, up or down. + const lift = packItem(f.type) ? 0 : base - builtinBase(f); + if (packItem(f.type) || Math.abs(lift) < 0.001) return buildFurniture(buf, lines, shadow, f, base); + const [firstVertex, firstLine] = [buf.p.length, lines.p.length]; + buildFurniture(buf, lines, base < 0.05 ? shadow : new GeoBuffer(), f, 0); + for (let i = firstVertex + 1; i < buf.p.length; i += 3) buf.p[i] += lift; + for (let i = firstLine + 1; i < lines.p.length; i += 3) lines.p[i] += lift; +} + diff --git a/frontend/src/viewer/furniture/kitchen.ts b/frontend/src/viewer/furniture/kitchen.ts new file mode 100644 index 0000000..5c09ce0 --- /dev/null +++ b/frontend/src/viewer/furniture/kitchen.ts @@ -0,0 +1,237 @@ +// Kitchen units, appliances, bathroom fittings and radiators. + +import { Color } from "three"; +import type { Furniture } from "../../model.ts"; +import { DEG, type GeoBuffer } from "../geo.ts"; +import { flipWinding, type Builder } from "./builder.ts"; +import { cabinet, fronts } from "./parts.ts"; +import { C, EDGE_FAINT, EDGE_FURN, EDGE_GLOW, M, material } from "./palette.ts"; + +const worktop = (b: Builder, w: number, d: number, h: number) => b.block({ x: [-w / 2, w / 2], y: [h - 0.04, h], z: [-d / 2, d / 2] }, M.worktop, EDGE_FURN); + +/** A base unit with a worktop. */ +export function kitchenUnit(b: Builder, w: number, d: number, h: number): void { + cabinet(b, w, d - 0.02, h - 0.04, Math.max(1, Math.round(w / 0.6)), h - 0.2); + worktop(b, w, d, h); +} + +/** Just the worktop, 4 cm thick at its height, with nothing below it. */ +export function worktopOnly(b: Builder, w: number, d: number, h: number): void { + b.block({ x: [-w / 2, w / 2], y: [Math.max(0, h - 0.04), h], z: [-d / 2, d / 2] }, M.worktop, EDGE_FURN); +} + +export function fridge(b: Builder, w: number, d: number, h: number): void { + b.block({ x: [-w / 2, w / 2], y: [0, h], z: [-d / 2, d / 2] }, M.white, EDGE_FURN); + const split = h * 0.62; + b.seg(-w / 2, split, d / 2, w / 2, split, d / 2, EDGE_FAINT); + const x = w / 2 - 0.06; + b.seg(x, split + 0.08, d / 2 + 0.015, x, split + 0.4, d / 2 + 0.015, EDGE_GLOW); + b.seg(x, split - 0.4, d / 2 + 0.015, x, split - 0.08, d / 2 + 0.015, EDGE_GLOW); +} + +/** The thickness of a smart fridge's doors. */ +export const FRIDGE_DOOR = 0.06; + +/** A smart side-by-side fridge without its doors (they move, see pushFridgeDoors): the body and, behind the doors, shelves. */ +export function fridgeSmart(b: Builder, w: number, d: number, h: number): void { + const front = d / 2 - FRIDGE_DOOR; + b.block({ x: [-w / 2, w / 2], y: [0.02, h], z: [-d / 2, front] }, M.body, EDGE_FURN); + b.block({ x: [-w / 2 + 0.05, w / 2 - 0.05], y: [0, 0.02], z: [-d / 2 + 0.05, front - 0.05] }, M.dark); + // shelves of both compartments, seen when a door stands open + for (const y of [0.35, 0.7, 1.05, 1.4]) { + if (y > h - 0.15) continue; + b.seg(-w / 2 + 0.03, y, front + 0.001, -0.03, y, front + 0.001, EDGE_FAINT); + b.seg(0.03, y, front + 0.001, w / 2 - 0.03, y, front + 0.001, EDGE_FAINT); + } +} + +type DoorGeometry = Pick; + +const OPENING_ANGLE = 1.83; // about 105° + +function fridgeDoorsUnflipped(buf: GeoBuffer, f: DoorGeometry, base: number, left: number, right: number): void { + const [c, s] = [Math.cos(f.rotation * DEG), Math.sin(f.rotation * DEG)]; + const mx = f.mirror ? -1 : 1; + const plan = (lx: number, lz: number): [number, number] => [f.x + mx * lx * c - lz * s, f.z + mx * lx * s + lz * c]; + const [y0, y1] = [base + 0.05, base + f.h - 0.02]; + const red = new Color(0.75, 0.1, 0.14); + const dark = new Color(C.dark); + const accent = new Color(C.accent); + const doorWidth = f.w / 2 - 0.006; + + // a door: u runs from the hinge along the door (positive to the right), v through its thickness (0 = front face) + const door = (hingeX: number, sign: 1 | -1, angle: number) => { + const open = angle / OPENING_ANGLE; + const frontColor = new Color(0x1f2d4c).lerp(red, open); + const sideColor = new Color(C.body).lerp(red, open * 0.8); + const [ca, sa] = [Math.cos(angle), Math.sin(angle)]; + const at = (u: number, v: number): [number, number] => plan(hingeX + sign * (u * ca - v * sa), f.d / 2 + u * sa + v * ca); + const quad = (p: [number, number][], ya: number, yb: number, color: Color) => { + const [p0, p1, p2, p3] = p; + buf.tri([p0[0], ya, p0[1]], [p1[0], ya, p1[1]], [p2[0], yb, p2[1]], color); + buf.tri([p0[0], ya, p0[1]], [p2[0], yb, p2[1]], [p3[0], yb, p3[1]], color); + }; + const box = (u0: number, u1: number, ya: number, yb: number, v0: number, v1: number, color: Color, face = color) => { + const q = [at(u0, v1), at(u1, v1), at(u1, v0), at(u0, v0)]; + // the front (v1 side), the back, the sides, the top and the bottom + quad([q[0], q[1], q[1], q[0]], ya, yb, face); + quad([q[3], q[2], q[2], q[3]], ya, yb, color); + quad([q[0], q[3], q[3], q[0]], ya, yb, color); + quad([q[1], q[2], q[2], q[1]], ya, yb, color); + quad([q[0], q[1], q[2], q[3]], yb, yb, color); + quad([q[3], q[2], q[1], q[0]], ya, ya, color); + }; + box(0, doorWidth, y0, y1, -FRIDGE_DOOR, 0, sideColor, frontColor); + // the handle at the free edge + box(doorWidth - 0.05, doorWidth - 0.03, base + f.h * 0.45, base + f.h * 0.75, 0.005, 0.025, accent); + return box; + }; + + const leftDoor = door(-f.w / 2, 1, left * OPENING_ANGLE); + // the water dispenser: a dark recess in the left door + leftDoor(0.12, 0.3, base + f.h * 0.5, base + f.h * 0.68, 0.001, 0.005, dark); + const rightDoor = door(f.w / 2, -1, right * OPENING_ANGLE); + // the screen: a dark panel on the right door (a picture rule puts its picture over it) + rightDoor(0.06, doorWidth - 0.06, base + f.h * 0.52, base + f.h * 0.86, 0.001, 0.005, dark); +} + +/** + * The two doors of a smart fridge, each swung open by a fraction (0 closed to 1 wide open) around its outer hinge: the left + * one carries the water dispenser, the right one the screen. An open door turns red, as it should not stay open for long. + */ +export function pushFridgeDoors(buf: GeoBuffer, f: DoorGeometry, base: number, left: number, right: number): void { + const first = buf.p.length; + fridgeDoorsUnflipped(buf, f, base, left, right); + if (f.mirror) flipWinding(buf, first); +} + +export function stove(b: Builder, w: number, d: number, h: number): void { + cabinet(b, w, d - 0.02, h - 0.04, 1, h - 0.24, true); + b.block({ x: [-w / 2, w / 2], y: [h - 0.04, h], z: [-d / 2, d / 2] }, M.dark, EDGE_FURN); + const plates: [number, number, number][] = [[-0.14, -0.13, 0.09], [0.14, -0.13, 0.07], [-0.14, 0.13, 0.07], [0.14, 0.13, 0.09]]; + for (const [x, z, r] of plates) b.cylinder((x * w) / 0.6, (z * d) / 0.62, r, h, h + 0.004, material(C.dark, 0x16263f), 12, EDGE_GLOW); +} + +export function sink(b: Builder, w: number, d: number, h: number): void { + cabinet(b, w, d - 0.02, h - 0.04, Math.max(1, Math.round(w / 0.45)), h - 0.2); + const basin = Math.min(0.5, w - 0.2); + const top = (x0: number, x1: number, z0: number, z1: number, edges = false) => b.block({ x: [x0, x1], y: [h - 0.04, h], z: [z0, z1] }, M.worktop, edges ? EDGE_FURN : null); + top(-w / 2, -basin / 2, -d / 2, d / 2, true); + top(basin / 2, w / 2, -d / 2, d / 2, true); + top(-basin / 2, basin / 2, -d / 2, -d / 2 + 0.1); + top(-basin / 2, basin / 2, d / 2 - 0.08, d / 2); + b.block({ x: [-basin / 2, basin / 2], y: [h - 0.2, h - 0.17], z: [-d / 2 + 0.1, d / 2 - 0.08] }, M.metal, EDGE_GLOW); + b.cylinder(0, -d / 2 + 0.05, 0.02, h, h + 0.28, M.metal, 8); + b.block({ x: [-0.015, 0.015], y: [h + 0.24, h + 0.28], z: [-d / 2 + 0.05, -d / 2 + 0.22] }, M.metal); +} + +export function kitchenWall(b: Builder, w: number, d: number, h: number): void { + // hangs above the worktop + const y0 = 1.45; + b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2, d / 2 - 0.02] }, M.body, EDGE_FURN); + fronts(b, -w / 2, w / 2, y0, y0 + h, d / 2 - 0.02, Math.max(1, Math.round(w / 0.5)), y0 + 0.08); +} + +export function kitchenTall(b: Builder, w: number, d: number, h: number): void { + b.block({ x: [-w / 2, w / 2], y: [0.02, h], z: [-d / 2, d / 2 - 0.02] }, M.body, EDGE_FURN); + b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0, 0.08], z: [-d / 2 + 0.02, d / 2 - 0.06] }, M.dark); + const z = d / 2 - 0.02; + // an oven with a dark glass door and a glowing handle, fronts above and below + b.block({ x: [-w / 2 + 0.03, w / 2 - 0.03], y: [0.85, 1.45], z: [z, z + 0.01] }, M.dark, EDGE_GLOW); + b.seg(-w / 2 + 0.08, 1.4, z + 0.02, w / 2 - 0.08, 1.4, z + 0.02, EDGE_GLOW); + for (const y of [0.85, 1.45]) b.seg(-w / 2, y, z, w / 2, y, z, EDGE_FAINT); + b.seg(w / 2 - 0.06, 0.5, z + 0.012, w / 2 - 0.06, 0.7, z + 0.012, EDGE_GLOW); + b.seg(w / 2 - 0.06, 1.6, z + 0.012, w / 2 - 0.06, 1.8, z + 0.012, EDGE_GLOW); +} + +export function island(b: Builder, w: number, d: number, h: number): void { + const inner = d - 0.3; + b.block({ x: [-w / 2 + 0.05, w / 2 - 0.05], y: [0.08, h - 0.04], z: [-d / 2 + 0.02, -d / 2 + inner] }, M.body, EDGE_FURN); + b.block({ x: [-w / 2 + 0.07, w / 2 - 0.07], y: [0, 0.08], z: [-d / 2 + 0.04, -d / 2 + inner - 0.04] }, M.dark); + fronts(b, -w / 2 + 0.05, w / 2 - 0.05, 0.08, h - 0.04, -d / 2 + inner, Math.max(2, Math.round(w / 0.6)), h - 0.2); + // the worktop overhangs at the front, for bar stools + worktop(b, w, d, h); +} + +export function dishwasher(b: Builder, w: number, d: number, h: number): void { + b.block({ x: [-w / 2, w / 2], y: [0.02, h - 0.04], z: [-d / 2, d / 2 - 0.02] }, M.body, EDGE_FURN); + b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0, 0.08], z: [-d / 2 + 0.02, d / 2 - 0.06] }, M.dark); + b.seg(-w / 2 + 0.08, h - 0.12, d / 2 - 0.008, w / 2 - 0.08, h - 0.12, d / 2 - 0.008, EDGE_GLOW); + worktop(b, w, d, h); +} + +/** A washing machine, or a dryer (`dryer`): a control panel line and a round door drawn on the front. */ +export function laundry(b: Builder, w: number, d: number, h: number, dryer: boolean): void { + b.block({ x: [-w / 2, w / 2], y: [0, h], z: [-d / 2, d / 2 - 0.02] }, M.white, EDGE_FURN); + const z = d / 2 - 0.012; + b.seg(-w / 2, h - 0.14, z, w / 2, h - 0.14, z, EDGE_FAINT); + b.seg(w / 2 - 0.16, h - 0.07, z, w / 2 - 0.08, h - 0.07, z, EDGE_GLOW); + const cy = (h - 0.14) / 2 + 0.04; + const r = Math.min(w * 0.36, (h - 0.2) * 0.42); + // the door ring (and an inner ring on a washer), drawn segment by segment + const sides = 20; + for (let i = 0; i < sides; i++) { + const [a0, a1] = [(i / sides) * Math.PI * 2, ((i + 1) / sides) * Math.PI * 2]; + const arc = (scale: number, color: typeof EDGE_GLOW) => b.seg(Math.cos(a0) * r * scale, cy + Math.sin(a0) * r * scale, z, Math.cos(a1) * r * scale, cy + Math.sin(a1) * r * scale, z, color); + arc(1, EDGE_GLOW); + if (!dryer) arc(0.72, EDGE_FAINT); + } +} + +export function bathtub(b: Builder, w: number, d: number, h: number): void { + const rim = 0.07; + b.block({ x: [-w / 2, w / 2], y: [0, h - 0.02], z: [-d / 2, d / 2] }, M.white, EDGE_FURN); + const lip = (x0: number, x1: number, z0: number, z1: number) => b.block({ x: [x0, x1], y: [h - 0.02, h], z: [z0, z1] }, M.worktop); + lip(-w / 2, w / 2, -d / 2, -d / 2 + rim); + lip(-w / 2, w / 2, d / 2 - rim, d / 2); + lip(-w / 2, -w / 2 + rim, -d / 2 + rim, d / 2 - rim); + lip(w / 2 - rim, w / 2, -d / 2 + rim, d / 2 - rim); + b.block({ x: [-w / 2 + rim, w / 2 - rim], y: [h - 0.03, h - 0.02], z: [-d / 2 + rim, d / 2 - rim] }, M.glass, EDGE_GLOW); + b.cylinder(-w / 2 + 0.04, 0, 0.02, h, h + 0.12, M.metal, 8); +} + +export function shower(b: Builder, w: number, d: number, h: number): void { + b.block({ x: [-w / 2, w / 2], y: [0, 0.05], z: [-d / 2, d / 2] }, M.worktop, EDGE_FURN); + b.cylinder(0, 0, 0.04, 0.05, 0.052, M.metal, 8); + // glass walls at the front and one side: only edges, the glass itself stays clear + for (const [xa, za, xb, zb] of [[-w / 2, d / 2, w / 2, d / 2], [w / 2, -d / 2, w / 2, d / 2]]) { + b.seg(xa, 0.05, za, xb, 0.05, zb, EDGE_GLOW); + b.seg(xa, h, za, xb, h, zb, EDGE_GLOW); + b.seg(xb, 0.05, zb, xb, h, zb, EDGE_GLOW); + } + b.cylinder(-w / 2 + 0.06, -d / 2 + 0.06, 0.015, 0.05, h - 0.05, M.metal, 6); + b.cylinder(-w / 2 + 0.2, -d / 2 + 0.2, 0.1, h - 0.08, h - 0.06, M.metal, 12, EDGE_GLOW); +} + +export function wc(b: Builder, w: number, d: number, h: number): void { + const tank = Math.min(0.18, d * 0.3); + b.block({ x: [-w / 2, w / 2], y: [0.45, h], z: [-d / 2, -d / 2 + tank] }, M.white, EDGE_FURN); + b.block({ x: [-w * 0.3, w * 0.3], y: [0, 0.36], z: [-d / 2 + tank - 0.02, d / 2 - 0.12] }, M.white); + b.cylinder(0, d / 2 - 0.26, Math.min(w / 2, 0.19), 0.36, 0.41, M.white, 12, EDGE_FURN); + b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0.41, 0.43], z: [-d / 2 + tank, -d / 2 + tank + 0.05] }, M.worktop); +} + +export function washbasin(b: Builder, w: number, d: number, h: number): void { + cabinet(b, w, d - 0.02, h - 0.12, w > 0.8 ? 2 : 1, h - 0.3); + b.block({ x: [-w / 2, w / 2], y: [h - 0.12, h], z: [-d / 2, d / 2] }, M.white, EDGE_FURN); + b.block({ x: [-w / 2 + 0.07, w / 2 - 0.07], y: [h - 0.005, h], z: [-d / 2 + 0.12, d / 2 - 0.06] }, M.glass, EDGE_GLOW); + b.cylinder(0, -d / 2 + 0.06, 0.018, h, h + 0.2, M.metal, 8); + // the mirror above + b.block({ x: [-w / 2 + 0.04, w / 2 - 0.04], y: [h + 0.35, h + 1], z: [-d / 2, -d / 2 + 0.02] }, M.glass, EDGE_GLOW); +} + +/** The height of the underside of a radiator. */ +export const RADIATOR_Y = 0.12; + +/** A radiator on the wall (back at -z): a panel with vertical fins, standing on short brackets. */ +export function radiator(b: Builder, w: number, d: number, h: number): void { + const y0 = RADIATOR_Y; + b.block({ x: [-w / 2 + 0.05, -w / 2 + 0.08], y: [0, y0], z: [-d / 2, -d / 2 + 0.03] }, M.metal); + b.block({ x: [w / 2 - 0.08, w / 2 - 0.05], y: [0, y0], z: [-d / 2, -d / 2 + 0.03] }, M.metal); + b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2 + 0.02, d / 2] }, M.white, EDGE_FURN); + const fins = Math.max(3, Math.round(w / 0.1)); + for (let i = 1; i < fins; i++) { + const x = -w / 2 + (w / fins) * i; + b.seg(x, y0 + 0.03, d / 2 + 0.002, x, y0 + h - 0.03, d / 2 + 0.002, EDGE_FAINT); + } +} diff --git a/frontend/src/viewer/furniture/living.ts b/frontend/src/viewer/furniture/living.ts new file mode 100644 index 0000000..2bacbf1 --- /dev/null +++ b/frontend/src/viewer/furniture/living.ts @@ -0,0 +1,158 @@ +// Tables, storage, decoration and stairs. + +import type { Builder } from "./builder.ts"; +import { cabinet, fronts, legs } from "./parts.ts"; +import { C, EDGE_FAINT, EDGE_FURN, EDGE_GLOW, M, material } from "./palette.ts"; + +export function table(b: Builder, w: number, d: number, h: number): void { + legs(b, w, d, h - 0.04, 0.06, 0.05, C.wood, true); + b.block({ x: [-w / 2, w / 2], y: [h - 0.04, h], z: [-d / 2, d / 2] }, M.wood, EDGE_GLOW); + b.block({ x: [-w / 2 + 0.08, w / 2 - 0.08], y: [h - 0.1, h - 0.04], z: [-d / 2 + 0.08, d / 2 - 0.08] }, material(C.body)); +} + +export function roundTable(b: Builder, w: number, d: number, h: number): void { + const r = Math.min(w, d) / 2; + b.cylinder(0, 0, r * 0.4, 0, 0.03, M.metal, 12); + b.cylinder(0, 0, 0.05, 0.03, h - 0.04, material(C.wood), 8); + b.cylinder(0, 0, r, h - 0.04, h, M.wood, 20, EDGE_FURN); +} + +export function coffeeTable(b: Builder, w: number, d: number, h: number): void { + legs(b, w, d, h - 0.03, 0.04, 0.03, C.wood); + b.block({ x: [-w / 2, w / 2], y: [h - 0.03, h], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN); + b.block({ x: [-w / 2 + 0.05, w / 2 - 0.05], y: [0.1, 0.13], z: [-d / 2 + 0.05, d / 2 - 0.05] }, M.body, EDGE_FAINT); +} + +export function desk(b: Builder, w: number, d: number, h: number): void { + const [x0, x1] = [-w / 2, w / 2]; + b.block({ x: [x0, x1], y: [h - 0.035, h], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN); + b.block({ x: [x0, x0 + 0.03], y: [0, h - 0.035], z: [-d / 2 + 0.03, d / 2 - 0.03] }, M.metal); + const drawers = Math.min(0.42, w * 0.32); + b.block({ x: [x1 - drawers, x1], y: [0, h - 0.035], z: [-d / 2 + 0.03, d / 2 - 0.02] }, M.body, EDGE_FURN); + const front = d / 2 - 0.02; + for (const y of [h * 0.35, h * 0.66]) b.seg(x1 - drawers, y, front, x1, y, front, EDGE_FAINT); + for (const y of [h * 0.2, h * 0.5, h * 0.82]) b.seg(x1 - drawers / 2 - 0.07, y, front + 0.012, x1 - drawers / 2 + 0.07, y, front + 0.012, EDGE_GLOW); + // the screen on its foot + b.block({ x: [-0.3, 0.3], y: [h + 0.08, h + 0.42], z: [-d / 2 + 0.08, -d / 2 + 0.11] }, M.dark, EDGE_GLOW); + b.block({ x: [-0.03, 0.03], y: [h, h + 0.1], z: [-d / 2 + 0.09, -d / 2 + 0.13] }, M.metal); +} + +export function nightstand(b: Builder, w: number, d: number, h: number): void { + cabinet(b, w, d, h, 1, h * 0.72, true); + b.seg(-w / 2, h * 0.5, d / 2 - 0.02, w / 2, h * 0.5, d / 2 - 0.02, EDGE_FAINT); +} + +export function shelf(b: Builder, w: number, d: number, h: number): void { + const t = 0.025; + b.block({ x: [-w / 2, -w / 2 + t], y: [0, h], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN); + b.block({ x: [w / 2 - t, w / 2], y: [0, h], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN); + b.block({ x: [-w / 2 + t, w / 2 - t], y: [0, h], z: [-d / 2, -d / 2 + 0.015] }, material(C.body)); + const boards = Math.max(2, Math.round(h / 0.38)); + for (let i = 0; i <= boards; i++) { + const y = Math.min(h - t, (h / boards) * i); + b.block({ x: [-w / 2 + t, w / 2 - t], y: [y, y + t], z: [-d / 2 + 0.015, d / 2] }, M.wood, EDGE_FAINT); + if (i === boards) continue; // no books on the top board + // a few books on every other shelf, in varying widths and heights + let x = -w / 2 + t + 0.04; + let k = i * 3; + while (x < w / 2 - t - 0.12) { + const bookWidth = 0.03 + ((k * 7) % 5) * 0.008; + const bookHeight = h / boards - t - 0.08 - ((k * 5) % 4) * 0.025; + if ((k * 11) % 7 !== 0) b.block({ x: [x, x + bookWidth], y: [y + t, y + t + bookHeight], z: [-d / 2 + 0.04, d / 2 - 0.05] }, k % 3 ? M.fabric : material(C.cushion, C.fabricTop)); + x += bookWidth + 0.006; + k++; + } + } +} + +export function sideboard(b: Builder, w: number, d: number, h: number): void { + legs(b, w, d, 0.12, 0.03, 0.04, C.metal); + b.block({ x: [-w / 2, w / 2], y: [0.12, h], z: [-d / 2, d / 2 - 0.02] }, M.wood, EDGE_FURN); + fronts(b, -w / 2, w / 2, 0.12, h, d / 2 - 0.02, Math.max(2, Math.round(w / 0.45)), h - 0.1, true); +} + +export function dresser(b: Builder, w: number, d: number, h: number): void { + b.block({ x: [-w / 2, w / 2], y: [0.06, h], z: [-d / 2, d / 2 - 0.02] }, M.wood, EDGE_FURN); + b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0, 0.06], z: [-d / 2 + 0.02, d / 2 - 0.06] }, M.dark); + const drawers = Math.max(3, Math.round((h - 0.06) / 0.22)); + const front = d / 2 - 0.02; + const step = (h - 0.06) / drawers; + for (let i = 1; i < drawers; i++) b.seg(-w / 2, 0.06 + step * i, front, w / 2, 0.06 + step * i, front, EDGE_FAINT); + for (let i = 0; i < drawers; i++) b.seg(-0.08, 0.06 + step * (i + 0.5), front + 0.012, 0.08, 0.06 + step * (i + 0.5), front + 0.012, EDGE_GLOW); +} + +/** A shoe bench with a back panel, hooks and a hat shelf. */ +export function coatRack(b: Builder, w: number, d: number, h: number): void { + b.block({ x: [-w / 2, w / 2], y: [0, 0.45], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN); + fronts(b, -w / 2, w / 2, 0.02, 0.45, d / 2, Math.max(2, Math.round(w / 0.5)), 0.38, true); + b.block({ x: [-w / 2, w / 2], y: [0.45, h], z: [-d / 2, -d / 2 + 0.03] }, M.body, EDGE_FURN); + b.block({ x: [-w / 2, w / 2], y: [h - 0.04, h], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN); + const hooks = Math.max(2, Math.round(w / 0.25)); + for (let i = 0; i < hooks; i++) { + const x = -w / 2 + (w / hooks) * (i + 0.5); + b.block({ x: [x - 0.015, x + 0.015], y: [h - 0.32, h - 0.28], z: [-d / 2 + 0.03, -d / 2 + 0.1] }, M.metal); + } +} + +/** A potted plant: a pot, a stem and foliage as stacked, slightly shifted octagonal layers. */ +export function plant(b: Builder, w: number, d: number, h: number): void { + const r = Math.min(w, d) / 2; + const pot = Math.min(0.4, h * 0.34); + b.cylinder(0, 0, r * 0.62, 0, pot, M.pot, 10, EDGE_FURN); + b.cylinder(0, 0, r * 0.08, pot, h * 0.55, material(C.wood), 6); + const layers = 4; + for (let i = 0; i < layers; i++) { + const radius = r * (0.95 - 0.55 * (i / (layers - 1))); + const y0 = pot + (h - pot) * (0.18 + 0.2 * i); + b.cylinder(Math.sin(i * 2.1) * 0.03, Math.cos(i * 1.7) * 0.03, radius, y0, y0 + (h - pot) * 0.16, M.plant, 8, i === layers - 1 ? EDGE_FAINT : null); + } +} + +/** A flat rug with a line inset from its edge. */ +export function rug(b: Builder, w: number, d: number): void { + b.block({ x: [-w / 2, w / 2], y: [0, 0.012], z: [-d / 2, d / 2] }, M.fabric); + const i = Math.min(0.12, Math.min(w, d) * 0.08); + const [x0, x1, z0, z1] = [-w / 2 + i, w / 2 - i, -d / 2 + i, d / 2 - i]; + for (const [xa, za, xb, zb] of [[x0, z0, x1, z0], [x1, z0, x1, z1], [x1, z1, x0, z1], [x0, z1, x0, z0]]) b.seg(xa, 0.014, za, xb, 0.014, zb, EDGE_FURN); +} + +/** A straight stair rising towards -z (the back), with a handrail on the +x side. */ +export function stairs(b: Builder, w: number, d: number, h: number): void { + const steps = Math.max(3, Math.round(h / 0.18)); + const rise = h / steps; + const run = d / steps; + for (let i = 0; i < steps; i++) { + const z1 = d / 2 - run * i; + const y1 = rise * (i + 1); + b.block({ x: [-w / 2, w / 2], y: [0, y1], z: [z1 - run, z1] }, M.wood); + b.seg(-w / 2, y1, z1, w / 2, y1, z1, EDGE_FURN); + } + b.seg(-w / 2, 0, d / 2, -w / 2, rise, d / 2, EDGE_FURN); + // stringer lines along both sides + for (const x of [-w / 2, w / 2]) b.seg(x, rise, d / 2, x, h, -d / 2 + run, EDGE_FAINT); + // the handrail and its posts; the rail ends where the stair passes through the ceiling opening + const railHeight = 0.9; + const x = w / 2 - 0.03; + const last = Math.max(1, steps - 4); + b.seg(x, rise + railHeight, d / 2 - run / 2, x, rise * last + railHeight, d / 2 - run * (last - 0.5), EDGE_GLOW); + for (let i = 0; i < last; i += 3) { + const z = d / 2 - run * (i + 0.5); + b.seg(x, rise * (i + 1), z, x, rise * (i + 1) + railHeight, z, EDGE_FAINT); + } +} + +/** A TV on a low unit with a stand. */ +export function tvBoard(b: Builder, w: number, d: number, h: number, rim: Parameters[2] = EDGE_GLOW): void { + cabinet(b, w, d, h, Math.max(2, Math.round(w / 0.6)), h * 0.55, true); + const screen = Math.min(w * 0.8, 1.45); + b.block({ x: [-0.1, 0.1], y: [h, h + 0.02], z: [-d / 2 + 0.08, -d / 2 + 0.24] }, M.metal); + b.block({ x: [-0.02, 0.02], y: [h + 0.02, h + 0.12], z: [-d / 2 + 0.14, -d / 2 + 0.18] }, M.metal); + b.block({ x: [-screen / 2, screen / 2], y: [h + 0.1, h + 0.1 + screen * 0.56], z: [-d / 2 + 0.12, -d / 2 + 0.16] }, M.dark, rim); +} + +/** A flat screen on a wall bracket, centred at 1.3 m. */ +export function tvWall(b: Builder, w: number, d: number, h: number, rim: Parameters[2] = EDGE_GLOW): void { + const y0 = 1.3 - h / 2; + b.block({ x: [-0.12, 0.12], y: [y0 + h * 0.3, y0 + h * 0.7], z: [-d / 2, -d / 2 + 0.03] }, M.metal); + b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2 + 0.03, d / 2] }, M.dark, rim); +} diff --git a/frontend/src/viewer/furniture/packs.ts b/frontend/src/viewer/furniture/packs.ts new file mode 100644 index 0000000..0919133 --- /dev/null +++ b/frontend/src/viewer/furniture/packs.ts @@ -0,0 +1,82 @@ +// Furniture from packs: the parts of a pack item scaled to the item's size, as lamps with glowing parts, and as glow layers. + +import type { Furniture } from "../../model.ts"; +import { fittedParts, movedParts, type PackItem, type PackPart } from "../../packs.ts"; +import { DEG, EDGE_TOP, LineBuffer, shade, type GeoBuffer } from "../geo.ts"; +import { Builder, flipWinding, type Plan } from "./builder.ts"; +import { C, EDGE_FAINT, EDGE_FURN, material } from "./palette.ts"; + +/** The colour of a pack part: a palette role (so packs follow the look) or "#rrggbb". */ +function partColor(value: string | undefined, top: boolean): number | null { + if (!value) return null; + if (value.startsWith("#")) return Number.parseInt(value.slice(1), 16); + const palette = C as Record; + return (top ? palette[`${value}Top`] : undefined) ?? palette[value] ?? null; +} + +/** The model of a pack item: its parts scaled to the item's size. Glowing parts take `glow` (a lit lamp). */ +export function packModel(b: Builder, item: PackItem, w: number, d: number, h: number, base: number, glow: number | null, only: ((p: PackPart) => boolean) | null = null, variant: string | null = null, reach: number | null = null): void { + // the colour picked for the item (its first by default), for the parts that carry paint + const paint = item.colors?.length ? (item.colors.find((c) => c.id === variant) ?? item.colors[0]).hex : null; + // moving parts (a curtain, an awning) are drawn apart, at their reach; the item itself leaves them out + const fitted = fittedParts(item, w, d, h); + for (const raw of reach === null ? fitted : movedParts(fitted, reach)) { + if (reach === null && raw.move) continue; + if (only && !only(raw)) continue; + // selected parts (the glowing ones of a speaker, a car's windows) come out a hair larger, so they cover the item's own + const part = only ? { ...raw, glow: true, w: raw.w + 0.006 / w, d: raw.d + 0.006 / d, y: Math.max(0, raw.y - 0.002 / h), h: raw.h + 0.004 / h } : raw; + const lit = part.glow && glow !== null; + const painted = !!(part.paint && paint); + const body = painted ? paint! : part.color; + const side = lit ? glow : (partColor(body, false) ?? C.body); + // without a top colour, the top is the role's top shade or a little lighter + const top = lit ? glow : (partColor(painted ? undefined : part.top, false) ?? partColor(body, true) ?? shade(side, 1.25).getHex()); + const look = material(side, top); + const [y0, y1] = [base + part.y * h, base + Math.min(h, (part.y + part.h) * h)]; + // "glow" lines are as bright as the wall lines, so a pack item can be drawn like the walls + const edges = part.edges === "glow" ? EDGE_TOP : part.edges === "faint" ? EDGE_FAINT : part.edges ? EDGE_FURN : null; + // a turned part draws through a builder whose coordinates turn around the part's centre + const target = part.rot ? b.turned(part.x * w, part.z * d, part.rot) : b; + const [cx, cz] = [part.x * w, part.z * d]; + if (part.shape === "cyl" && (part.axis === "x" || part.axis === "z")) { + target.lyingCylinder(part.axis, cx, cz, y0, y1, part.axis === "x" ? part.w * w : part.d * d, part.axis === "x" ? part.d * d : part.w * w, look, 14, edges); + } else if (part.shape === "cyl") { + target.cylinder(cx, cz, Math.min(part.w * w, part.d * d) / 2, y0, y1, look, 14, edges); + } else if (part.shape === "loft") { + const [tx, tz, tw, td] = [part.tx ?? part.x, part.tz ?? part.z, part.tw ?? part.w, part.td ?? part.d]; + target.loft([(part.x - part.w / 2) * w, (part.x + part.w / 2) * w, (part.z - part.d / 2) * d, (part.z + part.d / 2) * d], [(tx - tw / 2) * w, (tx + tw / 2) * w, (tz - td / 2) * d, (tz + td / 2) * d], y0, y1, look, edges); + } else if (part.shape === "sweep") { + const stations = (part.stations ?? []).map(([z, sy0, sy1, sw]) => ({ x: cx, z: z * d, y0: base + sy0 * h, y1: base + sy1 * h, hw: (sw * w) / 2 })); + target.sweep(stations, look, part.n ?? 16, part.exp ?? 2.6, edges); + } else target.block({ x: [(part.x - part.w / 2) * w, (part.x + part.w / 2) * w], y: [y0, y1], z: [(part.z - part.d / 2) * d, (part.z + part.d / 2) * d] }, look, edges); + } +} + +type Placed = Pick; + +/** The plan transform of a placed item: turned by its rotation, and mirrored when asked (its own x runs the other way). */ +export function placement(f: Pick): Plan { + const [c, s] = [Math.cos(f.rotation * DEG), Math.sin(f.rotation * DEG)]; + const mx = f.mirror ? -1 : 1; + return (x, z) => [f.x + mx * x * c - z * s, f.z + mx * x * s + z * c]; +} + +const sizeOf = (f: Placed): [number, number, number] => [Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.005, f.h)]; + +/** The glowing parts of a pack item that is no lamp (a smart speaker's light ring) in `color`, for the screen layer. */ +export function pushPackGlow(buf: GeoBuffer, item: PackItem, f: Placed, base: number, color: number, pick: (p: PackPart) => boolean = (p) => !!p.glow): void { + packModel(new Builder(buf, new LineBuffer(), placement(f)), item, ...sizeOf(f), base, color, pick); +} + +/** The moving parts of a pack item (curtain, roller screen, awning, gate) at their reach (0 drawn in … 1 out). */ +export function pushPackMoving(buf: GeoBuffer, item: PackItem, f: Placed & { variant?: string | null }, base: number, reach: number): void { + const first = buf.p.length; + packModel(new Builder(buf, new LineBuffer(), placement(f)), item, ...sizeOf(f), base, null, null, f.variant ?? null, reach); + if (f.mirror) flipWinding(buf, first); +} + +/** A pack lamp into the lamp buffer: glowing parts in the light's colour (`glow`), or dark when off. Lamps have no outlines. */ +export function pushPackLamp(buf: GeoBuffer, item: PackItem, f: Placed, base: number, glow: number): void { + packModel(new Builder(buf, new LineBuffer(), placement(f)), item, ...sizeOf(f), base, glow); +} + diff --git a/frontend/src/viewer/furniture/palette.test.ts b/frontend/src/viewer/furniture/palette.test.ts new file mode 100644 index 0000000..cce9aef --- /dev/null +++ b/frontend/src/viewer/furniture/palette.test.ts @@ -0,0 +1,21 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { applyFurnitureColors, C, M } from "./palette.ts"; +import { FURNITURE_ROLES, STOCK_ROLE_HEX } from "../../furniture-colors.ts"; + +test("chosen role colours reach the palette and its materials, and go back to stock", () => { + const stockBody = C.body; + for (const role of FURNITURE_ROLES) assert.equal(STOCK_ROLE_HEX[role], `#${C[role].toString(16).padStart(6, "0")}`); + assert.equal(applyFurnitureColors({ body: "#804020", fabric: "#00ff00", metal: "nope" }), true); + assert.equal(C.body, 0x804020); + assert.equal(M.body.side, 0x804020); + assert.notEqual(M.body.top, 0x804020); + assert.equal(M.cushion.side, 0x00ff00); + assert.equal(M.cushionSoft.top, C.fabricTop); + assert.equal(C.metal, 0x2a3a60); + // the same colours again change nothing + assert.equal(applyFurnitureColors({ body: "#804020", fabric: "#00ff00" }), false); + assert.equal(applyFurnitureColors(null), true); + assert.equal(C.body, stockBody); + assert.equal(M.body.side, stockBody); +}); diff --git a/frontend/src/viewer/furniture/palette.ts b/frontend/src/viewer/furniture/palette.ts new file mode 100644 index 0000000..9863123 --- /dev/null +++ b/frontend/src/viewer/furniture/palette.ts @@ -0,0 +1,98 @@ +// Colours of the furniture in the neon look. + +import { shade } from "../geo.ts"; +import { FURNITURE_ROLES, type FurnitureColors, type FurnitureRole } from "../../furniture-colors.ts"; + +/** The palette roles furniture and pack items are painted with. */ +export const C = { + body: 0x172238, + bodyTop: 0x1d2b47, + fabric: 0x1a2644, + fabricTop: 0x22325a, + cushion: 0x243661, + wood: 0x19233c, + woodTop: 0x202d4b, + white: 0x1d2946, + whiteTop: 0x26375e, + metal: 0x2a3a60, + dark: 0x0b111f, + glass: 0x1c3a52, + plant: 0x12302e, + plantTop: 0x1a4540, + pot: 0x1d2640, + accent: 0x2b8fb3, +}; + +/** A surface material: the colour of the sides and of the top. */ +export interface Material { + side: number; + top: number; +} + +const material = (side: number, top = side): Material => ({ side, top }); + +export const M = { + body: material(C.body, C.bodyTop), + fabric: material(C.fabric, C.fabricTop), + cushion: material(C.cushion), + cushionSoft: material(C.cushion, C.fabricTop), + wood: material(C.wood, C.woodTop), + white: material(C.white, C.whiteTop), + worktop: material(C.whiteTop), + metal: material(C.metal), + dark: material(C.dark), + darkBody: material(C.dark, C.body), + glass: material(C.glass), + accent: material(C.accent), + pot: material(C.pot), + plant: material(C.plant, C.plantTop), + bedding: material(C.white, C.whiteTop), + pillow: material(C.whiteTop), +}; +export { material }; + +export const EDGE_FURN = shade(0x5b7cff, 0.3); +export const EDGE_FAINT = shade(0x5b7cff, 0.17); +export const EDGE_GLOW = shade(0x37e0ff, 0.45); + +export { FURNITURE_ROLES, type FurnitureColors, type FurnitureRole }; + +const STOCK_C = { ...C }; +const stockMaterials = Object.fromEntries(Object.entries(M).map(([k, m]) => [k, { ...m }])) as Record; +let appliedKey = ""; + +const hexOf = (v: string | null | undefined): number | null => (typeof v === "string" && /^#[0-9a-f]{6}$/i.test(v) ? Number.parseInt(v.slice(1), 16) : null); + +/** + * Sets the colours of the roles before furniture is built: every builder and pack item reads `C` and `M` while it + * builds, so the next rebuild takes them. Returns whether anything changed. The top of a role is a shade lighter. + */ +export function applyFurnitureColors(colors: FurnitureColors | null | undefined): boolean { + const own = Object.fromEntries(FURNITURE_ROLES.map((r) => [r, hexOf(colors?.[r])]).filter(([, v]) => v !== null)) as Partial>; + const key = JSON.stringify(own); + if (key === appliedKey) return false; + appliedKey = key; + Object.assign(C, STOCK_C); + for (const [k, m] of Object.entries(stockMaterials)) Object.assign(M[k as keyof typeof M], m); + const top = (v: number) => shade(v, 1.25).getHex(); + const set = (role: FurnitureRole, entries: (keyof typeof C)[], tops: (keyof typeof C)[], mats: (keyof typeof M)[]) => { + const v = own[role]; + if (v === undefined) return; + for (const e of entries) C[e] = v; + for (const e of tops) C[e] = top(v); + // a material whose side or top was one of the role's stock colours takes the new one + const swap = new Map([...entries.map((e) => [STOCK_C[e], v] as [number, number]), ...tops.map((e) => [STOCK_C[e], top(v)] as [number, number])]); + for (const m of mats) { + const stock = stockMaterials[m]; + M[m].side = swap.get(stock.side) ?? M[m].side; + M[m].top = swap.get(stock.top) ?? M[m].top; + } + }; + set("body", ["body"], ["bodyTop"], ["body", "darkBody"]); + set("wood", ["wood"], ["woodTop"], ["wood"]); + set("fabric", ["fabric", "cushion"], ["fabricTop"], ["fabric", "cushion", "cushionSoft"]); + set("white", ["white"], ["whiteTop"], ["white", "worktop", "bedding", "pillow"]); + set("metal", ["metal"], [], ["metal"]); + set("dark", ["dark"], [], ["dark", "darkBody"]); + return true; +} diff --git a/frontend/src/viewer/furniture/parts.ts b/frontend/src/viewer/furniture/parts.ts new file mode 100644 index 0000000..da8d049 --- /dev/null +++ b/frontend/src/viewer/furniture/parts.ts @@ -0,0 +1,44 @@ +// Parts that many models share: legs, door and drawer fronts. + +import { Builder } from "./builder.ts"; +import { C, EDGE_FAINT, EDGE_FURN, EDGE_GLOW, M, material, type Material } from "./palette.ts"; + +/** Four legs inside a w × d footprint; `taper` makes them narrower at the foot. */ +export function legs(b: Builder, w: number, d: number, h: number, thickness: number, inset: number, color = C.metal, taper = false): void { + const [x, z] = [w / 2 - inset - thickness, d / 2 - inset - thickness]; + const leg = material(color); + for (const sx of [-1, 1]) { + for (const sz of [-1, 1]) { + const [cx, cz] = [sx * x, sz * z]; + if (taper) b.loft([cx - thickness * 0.3, cx + thickness * 0.3, cz - thickness * 0.3, cz + thickness * 0.3], [cx - thickness / 2, cx + thickness / 2, cz - thickness / 2, cz + thickness / 2], 0, h, leg); + else b.block({ x: [cx - thickness / 2, cx + thickness / 2], y: [0, h], z: [cz - thickness / 2, cz + thickness / 2] }, leg); + } + } +} + +/** Door or drawer fronts on the front face (+z): division lines and small glowing handles. */ +export function fronts(b: Builder, x0: number, x1: number, y0: number, y1: number, z: number, count: number, handleY: number | null = null, horizontal = false): void { + const width = (x1 - x0) / count; + for (let i = 1; i < count; i++) b.seg(x0 + width * i, y0, z, x0 + width * i, y1, z, EDGE_FAINT); + for (let i = 0; i < count; i++) { + const centre = x0 + width * (i + 0.5); + const y = handleY ?? y1 - 0.08; + if (horizontal) { + const half = Math.min(0.1, width / 4); + b.seg(centre - half, y, z + 0.012, centre + half, y, z + 0.012, EDGE_GLOW); + } else { + // vertical handles alternate sides, so neighbouring doors have theirs next to each other + const x = count > 1 ? centre + (i % 2 ? -width / 2 + 0.06 : width / 2 - 0.06) : centre + width / 2 - 0.06; + b.seg(x, y - 0.08, z + 0.012, x, y + 0.08, z + 0.012, EDGE_GLOW); + } + } +} + +/** A carcass with a plinth and fronts: the basis of cabinets, kitchen units and wardrobes. */ +export function cabinet(b: Builder, w: number, d: number, h: number, doors: number, handleY: number | null = null, horizontal = false, body: Material = M.body): void { + b.block({ x: [-w / 2, w / 2], y: [0.02, h], z: [-d / 2, d / 2 - 0.02] }, body, EDGE_FURN); + b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0, 0.08], z: [-d / 2 + 0.02, d / 2 - 0.06] }, material(C.dark)); + fronts(b, -w / 2, w / 2, 0.08, h, d / 2 - 0.02, doors, handleY, horizontal); +} + + diff --git a/frontend/src/viewer/furniture/screens.ts b/frontend/src/viewer/furniture/screens.ts new file mode 100644 index 0000000..33c71f9 --- /dev/null +++ b/frontend/src/viewer/furniture/screens.ts @@ -0,0 +1,92 @@ +// Where the screen of a TV or monitor is, for the glow shown while the linked device is on. + +import { builtinBase, type Floor, type Furniture } from "../../model.ts"; +import { fittedParts, mountBase, packItem } from "../../packs.ts"; +import { RADIATOR_Y } from "./kitchen.ts"; + +export interface ScreenRect { + x0: number; + x1: number; + y0: number; + y1: number; + z: number; +} + +function builtInScreen(f: Furniture, w: number, d: number, h: number, floor?: Floor): ScreenRect | null { + switch (f.type) { + case "tv_board": { + const width = Math.min(w * 0.8, 1.45); + return { x0: -width / 2 + 0.02, x1: width / 2 - 0.02, y0: h + 0.12, y1: h + 0.08 + width * 0.56, z: -d / 2 + 0.165 }; + } + case "tv_wall": { + const y0 = 1.3 - h / 2; + return { x0: -w / 2 + 0.02, x1: w / 2 - 0.02, y0: y0 + 0.02, y1: y0 + h - 0.02, z: d / 2 + 0.003 }; + } + case "desk": + return { x0: -0.28, x1: 0.28, y0: h + 0.1, y1: h + 0.4, z: -d / 2 + 0.115 }; + case "fridge_smart": { + // the screen sits on the right door (mirrored: the door's u runs to the left from its hinge at +w/2) + const base = floor ? mountBase(floor, f) : 0; + return { x0: 0.06, x1: w / 2 - 0.06, y0: base + h * 0.52 + 0.01, y1: base + h * 0.86 - 0.01, z: d / 2 + 0.006 }; + } + // glowing fronts of appliances that run, and of a radiator that heats + case "radiator": + return { x0: -w / 2 + 0.02, x1: w / 2 - 0.02, y0: RADIATOR_Y + 0.02, y1: RADIATOR_Y + h - 0.02, z: d / 2 + 0.004 }; + case "washer": + case "dryer": { + const cy = (h - 0.14) / 2 + 0.04; + const r = Math.min(w * 0.36, (h - 0.2) * 0.42) * 0.8; + return { x0: -r, x1: r, y0: cy - r, y1: cy + r, z: d / 2 - 0.004 }; + } + case "dishwasher": + return { x0: -w / 2 + 0.06, x1: w / 2 - 0.06, y0: h - 0.16, y1: h - 0.08, z: d / 2 - 0.004 }; + default: + return null; + } +} + +function unmirrored(f: Furniture, floor?: Floor): ScreenRect | null { + const [w, d, h] = [Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.005, f.h)]; + const item = packItem(f.type); + const part = item && fittedParts(item, w, d, h).find((p) => p.screen); + if (part) { + // the screen part's front face, at the item's mount height + const base = floor ? mountBase(floor, f) : 0; + const [x0, x1] = [(part.x - part.w / 2) * w, (part.x + part.w / 2) * w]; + const inset = Math.min(0.02, (x1 - x0) * 0.05); + return { x0: x0 + inset, x1: x1 - inset, y0: base + part.y * h + inset, y1: base + (part.y + part.h) * h - inset, z: (part.z + part.d / 2) * d }; + } + // built-in models are lifted as a whole by their mount height + const lift = floor && f.type !== "fridge_smart" ? mountBase(floor, f) - builtinBase(f) : 0; + const rect = builtInScreen(f, w, d, h, floor); + return rect && { ...rect, y0: rect.y0 + lift, y1: rect.y1 + lift }; +} + +/** The screen of a TV or monitor in local coordinates (x across, y up, z = its front face). Null for furniture without one. */ +export function screenRect(f: Furniture, floor?: Floor): ScreenRect | null { + const rect = unmirrored(f, floor); + return rect && f.mirror ? { ...rect, x0: -rect.x1, x1: -rect.x0 } : rect; +} + +/** The picture part of a frame (a pack item's part marked `picture`) in local coordinates, mirrored like the item; null without one. */ +export function pictureRect(f: Furniture, floor?: Floor): ScreenRect | null { + const [w, d, h] = [Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.005, f.h)]; + const item = packItem(f.type); + const part = item && fittedParts(item, w, d, h).find((p) => p.picture); + if (!part) return null; + const base = floor ? mountBase(floor, f) : 0; + const [x0, x1] = [(part.x - part.w / 2) * w, (part.x + part.w / 2) * w]; + const rect = { x0, x1, y0: base + part.y * h, y1: base + (part.y + part.h) * h, z: (part.z + part.d / 2) * d }; + return f.mirror ? { ...rect, x0: -rect.x1, x1: -rect.x0 } : rect; +} + +/** The charge bar on the front of a home battery (local coordinates) and whether it fills upwards (a tower) or sideways (wall unit, cube). */ +export function batteryBar(f: Furniture, floor?: Floor): { rect: ScreenRect; vertical: boolean } | null { + if (f.type !== "home_battery") return null; + const [w, d, h] = [Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.05, f.h)]; + const lift = floor ? mountBase(floor, f) - builtinBase(f) : 0; + const z = d / 2 + 0.005; + if (f.variant === "wall") return { rect: { x0: -w * 0.3, x1: w * 0.3, y0: lift + 0.5 + h * 0.84, y1: lift + 0.5 + h * 0.9, z }, vertical: false }; + if (f.variant === "cube") return { rect: { x0: -w * 0.35, x1: w * 0.35, y0: lift + h * 0.8, y1: lift + h * 0.86, z }, vertical: false }; + return { rect: { x0: -w * 0.05, x1: w * 0.05, y0: lift + 0.06 + h * 0.16, y1: lift + h - 0.12, z }, vertical: true }; +} diff --git a/frontend/src/viewer/furniture/seating.ts b/frontend/src/viewer/furniture/seating.ts new file mode 100644 index 0000000..97b3db3 --- /dev/null +++ b/frontend/src/viewer/furniture/seating.ts @@ -0,0 +1,159 @@ +// Seating and beds. + +import type { Builder } from "./builder.ts"; +import { legs } from "./parts.ts"; +import { C, EDGE_FAINT, EDGE_FURN, M, material } from "./palette.ts"; + +/** A sofa (`seats` cushions across) or, with one seat, an armchair. */ +export function sofa(b: Builder, w: number, d: number, h: number, seats: number): void { + const [x0, x1, z0, z1] = [-w / 2, w / 2, -d / 2, d / 2]; + const arm = Math.min(0.2, w * 0.12); + const seat = h * 0.5; + const back = Math.min(0.24, d * 0.28); + legs(b, w, d, 0.07, 0.05, 0.05, C.wood, true); + b.pad({ x: [x0, x1], y: [0.07, seat - 0.08], z: [z0 + 0.02, z1] }, M.fabric, 0.04, EDGE_FURN); + // the back leans a little: its top is thinner than its base + b.loft([x0, x1, z0, z0 + back], [x0 + 0.01, x1 - 0.01, z0, z0 + back * 0.5], seat - 0.08, h, M.fabric, EDGE_FURN); + for (const [a, c] of [[x0, x0 + arm], [x1 - arm, x1]]) b.pad({ x: [a, c], y: [seat - 0.08, h * 0.72], z: [z0 + 0.02, z1 - 0.02] }, M.fabric, 0.04, EDGE_FURN); + // seat cushions with a small gap, and back cushions leaning against the back + const cushionWidth = (x1 - arm - (x0 + arm)) / seats; + for (let i = 0; i < seats; i++) { + const from = x0 + arm + cushionWidth * i + 0.02; + const to = from + cushionWidth - 0.04; + b.pad({ x: [from, to], y: [seat - 0.08, seat + 0.05], z: [z0 + back + 0.02, z1 - 0.06] }, M.cushion, 0.04); + b.loft([from + 0.01, to - 0.01, z0 + back * 0.55, z0 + back + 0.14], [from + 0.03, to - 0.03, z0 + back * 0.4, z0 + back * 0.4 + 0.06], seat + 0.03, h * 0.93, M.cushion); + } +} + +/** + * An L- or U-shaped sofa: the back runs along the rear, a chaise reaches forward at the right end (an L; mirrored, the left) or at + * both ends (a U). The seat depth stays that of a sofa, whatever the depth of the whole. + */ +export function shapedSofa(b: Builder, w: number, d: number, h: number, shape: "l" | "u"): void { + const [x0, x1, z0, z1] = [-w / 2, w / 2, -d / 2, d / 2]; + const seat = h * 0.5; + const back = Math.min(0.24, d * 0.2); + const depth = Math.min(0.95, d * 0.55); + const chaise = Math.min(0.9, w * (shape === "u" ? 0.28 : 0.34)); + const arm = 0.16; + legs(b, w, d, 0.07, 0.05, 0.05, C.wood, true); + // the main bench along the back, and the chaise(s) reaching forward + b.pad({ x: [x0, x1], y: [0.07, seat - 0.08], z: [z0 + 0.02, z0 + depth] }, M.fabric, 0.04, EDGE_FURN); + const ends: [number, number][] = shape === "u" ? [[x0, x0 + chaise], [x1 - chaise, x1]] : [[x1 - chaise, x1]]; + for (const [a, c] of ends) b.pad({ x: [a, c], y: [0.07, seat - 0.08], z: [z0 + depth - 0.04, z1] }, M.fabric, 0.04, EDGE_FURN); + b.loft([x0, x1, z0, z0 + back], [x0 + 0.01, x1 - 0.01, z0, z0 + back * 0.5], seat - 0.08, h, M.fabric, EDGE_FURN); + // arms: on the open end of an L, and along the outer sides of the chaises + if (shape === "l") b.pad({ x: [x0, x0 + arm], y: [seat - 0.08, h * 0.72], z: [z0 + 0.02, z0 + depth - 0.02] }, M.fabric, 0.04, EDGE_FURN); + for (const [a, c] of ends) { + const outer = a <= x0 + 1e-6 ? [a, a + arm] : [c - arm, c]; + b.pad({ x: [outer[0], outer[1]], y: [seat - 0.08, h * 0.62], z: [z0 + 0.02, z1 - 0.02] }, M.fabric, 0.04, EDGE_FURN); + } + // cushions on the bench between the chaises, and one long cushion on each chaise + const from = shape === "u" ? x0 + chaise : x0 + arm; + const to = x1 - chaise; + const seats = Math.max(1, Math.round((to - from) / 0.62)); + const cw = (to - from) / seats; + for (let i = 0; i < seats; i++) { + const a = from + cw * i + 0.02; + const c = a + cw - 0.04; + b.pad({ x: [a, c], y: [seat - 0.08, seat + 0.05], z: [z0 + back + 0.02, z0 + depth - 0.06] }, M.cushion, 0.04); + b.loft([a + 0.01, c - 0.01, z0 + back * 0.55, z0 + back + 0.14], [a + 0.03, c - 0.03, z0 + back * 0.4, z0 + back * 0.4 + 0.06], seat + 0.03, h * 0.93, M.cushion); + } + for (const [a, c] of ends) { + const inner = a <= x0 + 1e-6 ? [a + arm + 0.02, c - 0.02] : [a + 0.02, c - arm - 0.02]; + b.pad({ x: [inner[0], inner[1]], y: [seat - 0.08, seat + 0.05], z: [z0 + back + 0.02, z1 - 0.06] }, M.cushion, 0.04); + } +} + +export function bed(b: Builder, w: number, d: number, h: number): void { + const [x0, x1, z0, z1] = [-w / 2, w / 2, -d / 2, d / 2]; + const frame = Math.min(0.32, h * 0.36); + legs(b, w, d, 0.08, 0.06, 0.03, C.wood, true); + b.block({ x: [x0, x1], y: [0.08, frame], z: [z0 + 0.06, z1] }, M.wood, EDGE_FURN); + b.pad({ x: [x0 + 0.03, x1 - 0.03], y: [frame, frame + 0.2], z: [z0 + 0.08, z1 - 0.03] }, M.bedding, 0.03); + // head board, and its cap + b.block({ x: [x0, x1], y: [0.08, h - 0.05], z: [z0, z0 + 0.07] }, M.wood, EDGE_FURN); + b.block({ x: [x0, x1], y: [h - 0.05, h], z: [z0, z0 + 0.09] }, M.wood, EDGE_FAINT); + // a duvet over the lower two thirds with a folded-back edge, puffy pillows at the head + const mattress = frame + 0.2; + const fold = z0 + (d - 0.1) * 0.36; + b.pad({ x: [x0 + 0.01, x1 - 0.01], y: [mattress - 0.1, mattress + 0.05], z: [fold, z1 - 0.01] }, M.cushionSoft, 0.025, EDGE_FAINT); + b.lyingCylinder("x", 0, fold + 0.05, mattress - 0.02, mattress + 0.09, w - 0.02, 0.1, M.cushionSoft, 8); + const pillows = w > 1.2 ? 2 : 1; + const pillowWidth = (w - 0.2) / pillows; + for (let i = 0; i < pillows; i++) { + const px = x0 + 0.1 + pillowWidth * i; + const pz = z0 + 0.12; + const depth = Math.min(0.42, d * 0.2); + const k = 0.1; + b.loft([px + 0.03 + k, px + pillowWidth - 0.03 - k, pz + k * 0.5, pz + depth - k * 0.5], [px + 0.03, px + pillowWidth - 0.03, pz, pz + depth], mattress, mattress + 0.06, M.pillow); + b.loft([px + 0.03, px + pillowWidth - 0.03, pz, pz + depth], [px + 0.03 + k, px + pillowWidth - 0.03 - k, pz + k * 0.5, pz + depth - k * 0.5], mattress + 0.06, mattress + 0.12, M.pillow, EDGE_FAINT); + } +} + +export function chair(b: Builder, w: number, d: number, h: number): void { + const seat = Math.min(0.46, h * 0.52); + legs(b, w, d, seat - 0.04, 0.035, 0.02, C.wood, true); + b.block({ x: [-w / 2, w / 2], y: [seat - 0.04, seat], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN); + b.pad({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [seat, seat + 0.04], z: [-d / 2 + 0.05, d / 2 - 0.03] }, M.cushion, 0.015); + b.loft([-w / 2, w / 2, -d / 2 + 0.02, -d / 2 + 0.07], [-w / 2 + 0.02, w / 2 - 0.02, -d / 2, -d / 2 + 0.03], seat, h, M.wood, EDGE_FURN); +} + +export function barStool(b: Builder, w: number, d: number, h: number): void { + const r = Math.min(w, d) / 2; + b.cylinder(0, 0, r * 0.8, 0, 0.02, M.metal, 12); + b.cylinder(0, 0, 0.025, 0.02, h - 0.05, M.metal, 6); + b.cylinder(0, 0, r * 0.75, h * 0.35, h * 0.35 + 0.015, M.metal, 12, EDGE_FAINT); + b.cylinder(0, 0, r, h - 0.05, h, M.cushionSoft, 14, EDGE_FURN); +} + +export function officeChair(b: Builder, w: number, d: number, h: number): void { + const r = Math.min(w, d) / 2; + // a star base as two crossed bars and a hub, a gas lift, seat and back + b.block({ x: [-r, r], y: [0.04, 0.08], z: [-0.03, 0.03] }, M.metal); + b.block({ x: [-0.03, 0.03], y: [0.04, 0.08], z: [-r, r] }, M.metal); + b.cylinder(0, 0, 0.06, 0.02, 0.1, M.dark, 8); + b.cylinder(0, 0, 0.025, 0.1, 0.44, M.metal, 6); + b.block({ x: [-r * 0.75, r * 0.75], y: [0.44, 0.52], z: [-r * 0.7, r * 0.75] }, material(C.fabric, C.cushion), EDGE_FURN); + b.block({ x: [-r * 0.7, r * 0.7], y: [0.58, h], z: [-r * 0.78, -r * 0.62] }, M.fabric, EDGE_FURN); + b.block({ x: [-0.03, 0.03], y: [0.5, 0.62], z: [-r * 0.72, -r * 0.62] }, M.metal); +} + +export function stool(b: Builder, w: number, d: number, h: number): void { + legs(b, w, d, 0.08, 0.04, 0.05, C.wood); + b.block({ x: [-w / 2, w / 2], y: [0.08, h], z: [-d / 2, d / 2] }, material(C.fabric, C.cushion), EDGE_FURN); +} + +/** A bench with a back along the rear; `corner` adds the second arm along -x. */ +export function bench(b: Builder, w: number, d: number, h: number, corner: boolean): void { + const seat = 0.45; + const depth = Math.min(0.5, corner ? d * 0.4 : d); + const back = 0.08; + const cushion = material(C.cushion); + // the rear arm + b.block({ x: [-w / 2, w / 2], y: [0, seat - 0.06], z: [-d / 2, -d / 2 + depth] }, M.wood, EDGE_FURN); + b.block({ x: [-w / 2, w / 2], y: [0, h], z: [-d / 2, -d / 2 + back] }, M.wood, EDGE_FURN); + b.block({ x: [-w / 2 + (corner ? depth : 0.02), w / 2 - 0.02], y: [seat - 0.06, seat + 0.02], z: [-d / 2 + back, -d / 2 + depth] }, cushion, EDGE_FAINT); + if (!corner) return; + // the side arm along -x, meeting the rear arm in the corner + b.block({ x: [-w / 2, -w / 2 + depth], y: [0, seat - 0.06], z: [-d / 2 + depth, d / 2] }, M.wood, EDGE_FURN); + b.block({ x: [-w / 2, -w / 2 + back], y: [0, h], z: [-d / 2 + back, d / 2] }, M.wood, EDGE_FURN); + b.block({ x: [-w / 2 + back, -w / 2 + depth], y: [seat - 0.06, seat + 0.02], z: [-d / 2 + back, d / 2 - 0.02] }, cushion, EDGE_FAINT); +} + +export function bunkBed(b: Builder, w: number, d: number, h: number): void { + const t = 0.05; + for (const sx of [-1, 1]) { + for (const sz of [-1, 1]) b.block({ x: [sx * (w / 2) - (sx > 0 ? t : 0), sx * (w / 2) + (sx < 0 ? t : 0)], y: [0, h], z: [sz * (d / 2) - (sz > 0 ? t : 0), sz * (d / 2) + (sz < 0 ? t : 0)] }, M.wood); + } + for (const y of [0.25, h - 0.55]) { + b.block({ x: [-w / 2, w / 2], y: [y, y + 0.08], z: [-d / 2, d / 2] }, M.wood, EDGE_FURN); + b.block({ x: [-w / 2 + 0.04, w / 2 - 0.04], y: [y + 0.08, y + 0.24], z: [-d / 2 + 0.05, d / 2 - 0.05] }, M.bedding, EDGE_FAINT); + b.block({ x: [-w / 2 + 0.05, w / 2 - 0.05], y: [y + 0.24, y + 0.33], z: [-d / 2 + 0.08, -d / 2 + 0.4] }, M.pillow); + } + // a guard rail on top and a ladder at the front + b.block({ x: [-w / 2, w / 2], y: [h - 0.2, h - 0.15], z: [d / 2 - t, d / 2] }, M.wood); + const ladder = w / 2 - 0.35; + for (const x of [ladder - 0.18, ladder + 0.18]) b.seg(x, 0, d / 2 + 0.02, x, h - 0.15, d / 2 + 0.02, EDGE_FURN); + for (let y = 0.3; y < h - 0.2; y += 0.28) b.seg(ladder - 0.18, y, d / 2 + 0.02, ladder + 0.18, y, d / 2 + 0.02, EDGE_FAINT); +} diff --git a/frontend/src/viewer/furniture/stairs.ts b/frontend/src/viewer/furniture/stairs.ts new file mode 100644 index 0000000..04b3a00 --- /dev/null +++ b/frontend/src/viewer/furniture/stairs.ts @@ -0,0 +1,80 @@ +// Shaped stairs: straight, winding (a quarter or half turn), L and U with a landing, and spiral stairs, built as a solid +// mass, on two stringers, on one spine or as steps out of the wall, going up or down. The treads come from the layout in +// geometry/stairs.ts, so the 3D model, the plan symbol and the floor opening always agree. + +import type { Vec2 } from "../../model.ts"; +import { stairConfig, stairLayout, treadCentre, type StairConfig, type Tread } from "../../geometry/stairs.ts"; +import type { Builder } from "./builder.ts"; +import { EDGE_FAINT, EDGE_FURN, EDGE_GLOW, M } from "./palette.ts"; + +const RAIL_HEIGHT = 0.9; + +/** A thin upright plate along the segment a-b, moved `inset` towards `inside`: risers and stringers. */ +function plate(b: Builder, a: Vec2, c: Vec2, inside: Vec2, y0: number, y1: number, thickness: number, material = M.wood): void { + const [dx, dz] = [c[0] - a[0], c[1] - a[1]]; + const length = Math.hypot(dx, dz); + if (length < 0.01 || y1 - y0 < 0.005) return; + let [nx, nz] = [-dz / length, dx / length]; + // the normal points into the tread + const mid: Vec2 = [(a[0] + c[0]) / 2, (a[1] + c[1]) / 2]; + if ((inside[0] - mid[0]) * nx + (inside[1] - mid[1]) * nz < 0) [nx, nz] = [-nx, -nz]; + const off = (p: Vec2, s: number): Vec2 => [p[0] + nx * s, p[1] + nz * s]; + b.prism([a, c, off(c, thickness), off(a, thickness)], y0, y1, material, EDGE_FAINT); +} + +/** Pairs of neighbouring points of a side, leaving out the zero-length ones of a winder's pivot. */ +const segments = (side: Vec2[]): [Vec2, Vec2][] => + side.slice(1).map((p, i): [Vec2, Vec2] => [side[i], p]).filter(([p, q]) => Math.hypot(q[0] - p[0], q[1] - p[1]) > 0.01); + +function treadsAndBody(b: Builder, cfg: StairConfig, treads: Tread[], rise: number, floor: number): void { + const thick = cfg.build === "cantilever" ? 0.07 : 0.05; + treads.forEach((t, i) => { + const centre = treadCentre(t); + const previous = i === 0 ? 0 : treads[i - 1].top; + if (cfg.build === "solid") { + // a solid (concrete) stair: every tread is a block down to the floor the stair stands on + b.prism(t.poly, Math.min(floor, t.top), t.top, M.body, EDGE_FURN); + return; + } + b.prism(t.poly, t.top - thick, t.top, M.wood, EDGE_FURN); + if (cfg.risers && !t.landing) { + const [lo, hi] = [Math.min(previous, t.top), Math.max(previous, t.top) - thick]; + plate(b, t.left[0], t.right[0], centre, lo, hi, 0.02); + } + if (cfg.build === "stringer") { + for (const side of [t.left, t.right]) for (const [p, q] of segments(side)) plate(b, p, q, centre, t.top - rise - 0.2, t.top + 0.05, 0.04); + } else if (cfg.build === "mono") { + const s = 0.07; + b.block({ x: [centre[0] - s, centre[0] + s], y: [t.top - rise - 0.12, t.top - thick], z: [centre[1] - s, centre[1] + s] }, M.metal); + } + }); +} + +function rails(b: Builder, cfg: StairConfig, treads: Tread[]): void { + const sides: ("left" | "right")[] = cfg.rail === "both" ? ["left", "right"] : cfg.rail === "none" ? [] : [cfg.rail]; + for (const side of sides) { + const nodes: [number, number, number][] = []; + for (const t of treads) for (const p of t[side]) nodes.push([p[0], t.top + RAIL_HEIGHT, p[1]]); + // a post at the start of every second tread and of the top one (one per tread is a fence on a spiral) + for (const [i, t] of treads.entries()) { + if (i % 2 && i !== treads.length - 1) continue; + const p = t[side][0]; + b.cylinder(p[0], p[1], 0.012, t.top, t.top + RAIL_HEIGHT, M.metal, 6); + } + for (let i = 1; i < nodes.length; i++) { + const [p, q] = [nodes[i - 1], nodes[i]]; + b.seg(p[0], p[1], p[2], q[0], q[1], q[2], EDGE_GLOW); + b.seg(p[0], p[1] - RAIL_HEIGHT * 0.55, p[2], q[0], q[1] - RAIL_HEIGHT * 0.55, q[2], EDGE_FAINT); + } + } +} + +/** Draws a shaped stair of size w × d that climbs h (or goes down h, then everything lies below the floor). */ +export function shapedStairs(b: Builder, item: { stair?: Partial | null }, w: number, d: number, h: number): void { + const cfg = stairConfig(item); + const layout = stairLayout(cfg, w, d, h); + const floor = cfg.down ? -h : 0; + if (layout.column > 0) b.cylinder(0, 0, layout.column, Math.min(0, floor), cfg.down ? 0 : h, M.metal, 12, EDGE_FURN); + treadsAndBody(b, cfg, layout.treads, layout.rise, floor); + rails(b, cfg, layout.treads); +} diff --git a/frontend/src/viewer/furniture/technical.ts b/frontend/src/viewer/furniture/technical.ts new file mode 100644 index 0000000..84aeca1 --- /dev/null +++ b/frontend/src/viewer/furniture/technical.ts @@ -0,0 +1,92 @@ +// Energy and building technology: inverters, batteries, wallboxes, meters, the grid cabinet. + +import { Builder } from "./builder.ts"; +import { EDGE_FAINT, EDGE_FURN, EDGE_GLOW, M } from "./palette.ts"; + +/** + * A solar inverter on the wall (from 1.1 m): a flat box with a display and a status line. "slim" is a tall narrow one with a + * vertical light strip, "hybrid" one with a round dial and two fans below. + */ +export function inverter(b: Builder, w: number, d: number, h: number, variant: string | null): void { + const y0 = 1.1; + const z = d / 2; + const housing = (side: typeof M.white) => b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2, d / 2] }, side, EDGE_FURN); + if (variant === "slim") { + housing(M.darkBody); + b.seg(-w * 0.25, y0 + h * 0.15, z + 0.004, -w * 0.25, y0 + h * 0.85, z + 0.004, EDGE_GLOW); + b.block({ x: [-w * 0.1, w * 0.3], y: [y0 + h * 0.7, y0 + h * 0.85], z: [z, z + 0.005] }, M.dark); + return; + } + housing(M.white); + if (variant === "hybrid") { + b.ring(0, y0 + h * 0.66, Math.min(w, h) * 0.22, z + 0.004, 20, EDGE_GLOW); + b.seg(-w * 0.08, y0 + h * 0.66, z + 0.005, w * 0.08, y0 + h * 0.66, z + 0.005, EDGE_GLOW); + for (const s of [-1, 1]) b.ring(s * w * 0.22, y0 + h * 0.2, Math.min(w, h) * 0.1, -d / 2 - 0.002, 12, EDGE_GLOW); + return; + } + b.block({ x: [-w * 0.28, w * 0.28], y: [y0 + h * 0.58, y0 + h * 0.82], z: [d / 2, d / 2 + 0.006] }, M.dark); + b.seg(-w * 0.3, y0 + h * 0.45, d / 2 + 0.004, w * 0.3, y0 + h * 0.45, d / 2 + 0.004, EDGE_GLOW); + // cooling fins at the sides + for (const s of [-1, 1]) for (let i = 1; i < 6; i++) b.seg((s * w) / 2 + s * 0.002, y0 + (h * i) / 6, -d / 2 + 0.03, (s * w) / 2 + s * 0.002, y0 + (h * i) / 6, d / 2 - 0.03, EDGE_FAINT); +} + +/** The grid connection at the edge of the plot: a small dark street cabinet with a glowing lid edge. */ +export function gridCabinet(b: Builder, w: number, d: number, h: number): void { + b.block({ x: [-w / 2, w / 2], y: [0, h], z: [-d / 2, d / 2] }, M.darkBody, EDGE_FURN); + b.block({ x: [-w / 2 - 0.01, w / 2 + 0.01], y: [h, h + 0.03], z: [-d / 2 - 0.01, d / 2 + 0.01] }, M.darkBody); + b.seg(-w / 2, h + 0.032, d / 2 + 0.01, w / 2, h + 0.032, d / 2 + 0.01, EDGE_GLOW); + b.seg(-w * 0.3, h * 0.55, d / 2 + 0.003, w * 0.3, h * 0.55, d / 2 + 0.003, EDGE_FAINT); +} + +/** A wallbox (from 1.0 m): a compact box with a glowing ring and the charging cable hanging below. */ +export function wallbox(b: Builder, w: number, d: number, h: number): void { + const y0 = 1; + b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2, d / 2] }, M.darkBody, EDGE_FURN); + b.ring(0, y0 + h * 0.58, Math.min(w, h) * 0.28, d / 2 + 0.003, 16, EDGE_GLOW); + // the cable below the box, and its holster + b.block({ x: [-0.015, 0.015], y: [y0 - 0.35, y0], z: [d / 2 - 0.03, d / 2] }, M.dark); + b.block({ x: [-0.06, 0.06], y: [y0 - 0.42, y0 - 0.35], z: [d / 2 - 0.05, d / 2] }, M.darkBody); +} + +/** A meter cabinet on the wall (from 0.4 m): a tall box with the meter window and the glowing pulse LED. */ +export function meterCabinet(b: Builder, w: number, d: number, h: number): void { + const y0 = 0.4; + b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2, d / 2] }, M.white, EDGE_FURN); + // the door's edge and handle + b.seg(-w / 2 + 0.025, y0 + 0.025, d / 2 + 0.003, -w / 2 + 0.025, y0 + h - 0.025, d / 2 + 0.003, EDGE_FAINT); + b.seg(-w / 2 + 0.025, y0 + h - 0.025, d / 2 + 0.003, w / 2 - 0.025, y0 + h - 0.025, d / 2 + 0.003, EDGE_FAINT); + b.block({ x: [w / 2 - 0.06, w / 2 - 0.035], y: [y0 + h * 0.5 - 0.05, y0 + h * 0.5 + 0.05], z: [d / 2, d / 2 + 0.012] }, M.dark); + // the meter behind its window, with the display line + b.block({ x: [-w * 0.3, w * 0.3], y: [y0 + h * 0.6, y0 + h * 0.8], z: [d / 2, d / 2 + 0.005] }, M.dark); + b.seg(-w * 0.22, y0 + h * 0.7, d / 2 + 0.008, w * 0.22, y0 + h * 0.7, d / 2 + 0.008, EDGE_GLOW); +} + +/** + * A home battery: a tower of stacked modules with a charge bar. "wall" is a flat battery hanging at hip height with a light + * bar, "cube" a compact box (a balcony battery) with a light bar and a handle. + */ +export function homeBattery(b: Builder, w: number, d: number, h: number, variant: string | null): void { + if (variant === "wall") { + const y0 = 0.5; + b.block({ x: [-w / 2, w / 2], y: [y0, y0 + h], z: [-d / 2, d / 2] }, M.white, EDGE_FURN); + b.seg(-w * 0.3, y0 + h * 0.9, d / 2 + 0.004, w * 0.3, y0 + h * 0.9, d / 2 + 0.004, EDGE_GLOW); + b.seg(-w * 0.3, y0 + h * 0.08, d / 2 + 0.003, w * 0.3, y0 + h * 0.08, d / 2 + 0.003, EDGE_FAINT); + return; + } + if (variant === "cube") { + b.block({ x: [-w / 2 + 0.01, w / 2 - 0.01], y: [0, 0.03], z: [-d / 2 + 0.01, d / 2 - 0.01] }, M.dark); + b.block({ x: [-w / 2, w / 2], y: [0.03, h], z: [-d / 2, d / 2] }, M.darkBody, EDGE_FURN); + b.seg(-w * 0.35, h * 0.85, d / 2 + 0.004, w * 0.35, h * 0.85, d / 2 + 0.004, EDGE_GLOW); + b.block({ x: [-w * 0.15, w * 0.15], y: [h, h + 0.025], z: [-0.012, 0.012] }, M.dark); + return; + } + b.block({ x: [-w / 2 + 0.02, w / 2 - 0.02], y: [0, 0.06], z: [-d / 2 + 0.02, d / 2 - 0.02] }, M.dark); + const modules = Math.max(2, Math.round((h - 0.06) / 0.3)); + const height = (h - 0.06) / modules; + for (let i = 0; i < modules; i++) b.block({ x: [-w / 2, w / 2], y: [0.06 + i * height + 0.004, 0.06 + (i + 1) * height], z: [-d / 2, d / 2] }, M.white, EDGE_FURN); + // the charge bar: five short segments + for (let k = 0; k < 5; k++) { + const y = 0.06 + h * 0.18 + k * ((h - 0.3) / 5); + b.seg(-w * 0.04, y, d / 2 + 0.003, w * 0.04, y, d / 2 + 0.003, EDGE_GLOW); + } +} diff --git a/frontend/src/viewer/furniture/tilt.test.ts b/frontend/src/viewer/furniture/tilt.test.ts new file mode 100644 index 0000000..8b4f211 --- /dev/null +++ b/frontend/src/viewer/furniture/tilt.test.ts @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { GeoBuffer, LineBuffer } from "../geo.ts"; +import { pushFurniture, tiltBuilt } from "./furniture.ts"; +import type { Furniture } from "../../model.ts"; + +const piece = (extra: Partial = {}): Furniture => ({ id: "t", type: "table", x: 2, z: 3, rotation: 0, w: 1.6, d: 0.8, h: 0.75, variant: null, ...extra }); +const topOf = (buf: GeoBuffer) => Math.max(...buf.p.filter((_, i) => i % 3 === 1)); + +test("without a tilt nothing moves; a tilt about the width axis leans the top towards the front", () => { + const upright = new GeoBuffer(); + pushFurniture(upright, new LineBuffer(), new GeoBuffer(), piece()); + const same = new GeoBuffer(); + pushFurniture(same, new LineBuffer(), new GeoBuffer(), piece({ tilt_x: 0, tilt_z: null })); + assert.deepEqual(same.p, upright.p); + const leaning = new GeoBuffer(); + pushFurniture(leaning, new LineBuffer(), new GeoBuffer(), piece({ tilt_x: 30 })); + assert.notDeepEqual(leaning.p, upright.p); + const zs = (b: GeoBuffer) => b.p.filter((_, i) => i % 3 === 2); + assert.ok(Math.max(...zs(leaning)) - Math.min(...zs(leaning)) > Math.max(...zs(upright)) - Math.min(...zs(upright)) - 1e-9 || topOf(leaning) < topOf(upright), "its top is no longer straight above its base"); + assert.ok(Math.abs(topOf(leaning) - topOf(upright)) > 0.01, "the height changed"); +}); + +test("tilting turns about the middle of the underside and keeps lengths", () => { + const buf = new GeoBuffer(); + const lines = new LineBuffer(); + buf.p.push(2, 0, 3, 3, 0, 3, 2, 1, 3); + lines.p.push(2, 1, 3, 2, 0, 3); + tiltBuilt(buf, lines, { vertex: 0, line: 0 }, { x: 2, z: 3, rotation: 0, tilt_x: 0, tilt_z: 90 }, 0); + // a roll of 90° about the depth axis (z) lays the up direction onto the width direction: (2,1,3) → (1,0,3) + assert.ok(Math.abs(buf.p[6] - 1) < 1e-9 && Math.abs(buf.p[7]) < 1e-9 && Math.abs(buf.p[8] - 3) < 1e-9, `${buf.p.slice(6, 9)}`); + assert.ok(Math.abs(lines.p[0] - 1) < 1e-9, "lines turn with the geometry"); + assert.deepEqual(buf.p.slice(0, 3), [2, 0, 3], "the pivot stays"); +}); diff --git a/frontend/src/viewer/geo.ts b/frontend/src/viewer/geo.ts new file mode 100644 index 0000000..466fbb8 --- /dev/null +++ b/frontend/src/viewer/geo.ts @@ -0,0 +1,7 @@ +// Geometry primitives for walls, furniture and opening parts: merged vertex-coloured buffers with a per-vertex fold value +// (see build.ts), line buffers, cutting at a height, and shapes. Split into modules in geo/. + +export { DEG, EDGE_BASE, EDGE_CUT, EDGE_SOFT, EDGE_TOP, shade } from "./geo/colors.ts"; +export { ALWAYS, CAP_OFFSET, CUT_OFFSET, FURN_OFFSET, GeoBuffer, LineBuffer, LOWER_OFFSET, PAINT_OFFSET } from "./geo/buffers.ts"; +export { cutAbove, cutLinesAbove } from "./geo/cut.ts"; +export { pushLoft, pushLyingCyl, pushPrism, pushSkin, triangulate, type PrismOptions } from "./geo/shapes.ts"; diff --git a/frontend/src/viewer/geo/buffers.ts b/frontend/src/viewer/geo/buffers.ts new file mode 100644 index 0000000..8f13b3c --- /dev/null +++ b/frontend/src/viewer/geo/buffers.ts @@ -0,0 +1,90 @@ +// Growing vertex buffers for merged geometry. Every vertex carries a colour and a "fold" value that tells the shader when +// to hide it (see build.ts). + +import { BufferGeometry, Color, Float32BufferAttribute } from "three"; +import { EDGE_TOP } from "./colors.ts"; + +/** Fold value of geometry that is always shown. */ +export const ALWAYS = -1; +/** Fold kinds: the value is kind * 16 + bucket (see build.ts). */ +export const CUT_OFFSET = 16; +export const LOWER_OFFSET = 32; +export const CAP_OFFSET = 48; +/** The part of tall furniture above the cut height: it folds away with the walls. */ +export const FURN_OFFSET = 64; +/** Added to the fold value of painted wall parts (solid wall view): the shader shows their own colour in every look. */ +export const PAINT_OFFSET = 128; + +const attribute = (values: number[], size: number) => new Float32BufferAttribute(values, size); + +export class GeoBuffer { + /** Positions, colours (three numbers per vertex), and one fold value per vertex. */ + p: number[] = []; + c: number[] = []; + f: number[] = []; + /** Texture coordinates; only kept when asked for. */ + uv: number[] | null; + /** The pattern atlas tile per vertex (floors only). */ + tile: number[] | null; + + constructor(uvs = false, tiles = false) { + this.uv = uvs ? [] : null; + this.tile = tiles ? [] : null; + } + + /** Adds a triangle. Without uvs it points at an empty spot of the texture. */ + tri(a: number[], b: number[], c: number[], ca: Color, cb: Color = ca, cc: Color = ca, uv?: number[], fold = ALWAYS, tile: [number, number] = [0, 1]): void { + this.p.push(...a, ...b, ...c); + for (const color of [ca, cb, cc]) this.c.push(color.r, color.g, color.b); + this.f.push(fold, fold, fold); + this.uv?.push(...(uv ?? [0.5, 0.5, 0.5, 0.5, 0.5, 0.5])); + this.tile?.push(...tile, ...tile, ...tile); + } + + /** The number of triangles. */ + get count(): number { + return this.p.length / 9; + } + + geometry(): BufferGeometry { + const geometry = new BufferGeometry(); + geometry.setAttribute("position", attribute(this.p, 3)); + geometry.setAttribute("color", attribute(this.c, 3)); + geometry.setAttribute("fold", attribute(this.f, 1)); + if (this.uv) geometry.setAttribute("uv", attribute(this.uv, 2)); + if (this.tile) geometry.setAttribute("tile", attribute(this.tile, 2)); + geometry.computeBoundingSphere(); + return geometry; + } +} + +export class LineBuffer { + p: number[] = []; + c: number[] = []; + f: number[] = []; + + seg(a: number[], b: number[], color: Color = EDGE_TOP, fold = ALWAYS): void { + this.p.push(...a, ...b); + this.c.push(color.r, color.g, color.b, color.r, color.g, color.b); + this.f.push(fold, fold); + } + + /** A vertical or sloped segment split at the cut height: below it always shown, above it with the bucket (negative bucket: never split). */ + segSplit(a: number[], b: number[], color: Color, cut: number, bucket: number): void { + const [low, high] = a[1] <= b[1] ? [a, b] : [b, a]; + if (high[1] <= cut + 1e-6 || bucket < 0) return this.seg(low, high, color, ALWAYS); + if (low[1] >= cut - 1e-6) return this.seg(low, high, color, bucket); + const t = (cut - low[1]) / (high[1] - low[1]); + const middle = [low[0] + (high[0] - low[0]) * t, cut, low[2] + (high[2] - low[2]) * t]; + this.seg(low, middle, color, ALWAYS); + this.seg(middle, high, color, bucket); + } + + geometry(): BufferGeometry { + const geometry = new BufferGeometry(); + geometry.setAttribute("position", attribute(this.p, 3)); + geometry.setAttribute("color", attribute(this.c, 3)); + geometry.setAttribute("fold", attribute(this.f, 1)); + return geometry; + } +} diff --git a/frontend/src/viewer/geo/colors.ts b/frontend/src/viewer/geo/colors.ts new file mode 100644 index 0000000..686ed39 --- /dev/null +++ b/frontend/src/viewer/geo/colors.ts @@ -0,0 +1,30 @@ +// Colours and the fake light of the 3D scene. + +import { Color } from "three"; +import type { Vec2 } from "../../model.ts"; + +export const DEG = Math.PI / 180; + +/** A colour scaled by k, each channel capped at 1 (Color.multiplyScalar alone can overflow). */ +export function shade(hex: number, k: number): Color { + const c = new Color(hex).multiplyScalar(k); + return c.setRGB(Math.min(1, c.r), Math.min(1, c.g), Math.min(1, c.b)); +} + +/** Edge lines are added on top of the scene, so their colours are pre-scaled to the strength they should end up at. */ +export const EDGE_TOP = shade(0x37e0ff, 0.95); +export const EDGE_CUT = shade(0x37e0ff, 1); +export const EDGE_SOFT = shade(0x5b7cff, 0.34); +export const EDGE_BASE = shade(0x5b7cff, 0.22); + +/** The direction (x, z) the fake light comes from: faces turned towards it come out a bit brighter. */ +export const LIGHT: Vec2 = [-0.55, 0.83]; + +/** Brightness of a wall side by height: dark at the foot (baked occlusion), full from 1.6 m up. */ +export const heightShade = (y: number): number => 0.5 + 0.5 * Math.min(1, Math.max(0, y / 1.6)); + +/** How strongly a vertical face along (dx, dz) is lit, between 0.8 and 1.08. Neighbouring faces differ a little, so they separate. */ +export function sideLight(dx: number, dz: number): number { + const length = Math.hypot(dx, dz); + return 0.8 + 0.28 * (((dz / length) * LIGHT[0] - (dx / length) * LIGHT[1] + 1) / 2); +} diff --git a/frontend/src/viewer/geo/cut.ts b/frontend/src/viewer/geo/cut.ts new file mode 100644 index 0000000..cd971af --- /dev/null +++ b/frontend/src/viewer/geo/cut.ts @@ -0,0 +1,106 @@ +// Cutting finished buffers at a height: what lies above the cut gets another fold value, so it can fold away. + +import type { GeoBuffer, LineBuffer } from "./buffers.ts"; + +const EPS = 1e-6; + +/** One vertex read back from a buffer. */ +interface Vertex { + p: number[]; + c: number[]; + uv: number[] | null; + tile: number[] | null; +} + +const blend = (a: number[], b: number[], t: number) => a.map((x, i) => x + (b[i] - x) * t); + +/** The point where an edge crosses the height `cut`; colours and uvs are interpolated. */ +function crossing(a: Vertex, b: Vertex, cut: number): Vertex { + const t = (cut - a.p[1]) / (b.p[1] - a.p[1]); + return { p: blend(a.p, b.p, t), c: blend(a.c, b.c, t), uv: a.uv && b.uv ? blend(a.uv, b.uv, t) : null, tile: a.tile }; +} + +function readVertex(buf: GeoBuffer, v: number): Vertex { + return { + p: buf.p.slice(v * 3, v * 3 + 3), + c: buf.c.slice(v * 3, v * 3 + 3), + uv: buf.uv ? buf.uv.slice(v * 2, v * 2 + 2) : null, + tile: buf.tile ? buf.tile.slice(v * 2, v * 2 + 2) : null, + }; +} + +function overwriteTriangle(buf: GeoBuffer, tri: number, corners: Vertex[], fold: number): void { + corners.forEach((corner, k) => { + const v = tri * 3 + k; + corner.p.forEach((x, i) => (buf.p[v * 3 + i] = x)); + corner.c.forEach((x, i) => (buf.c[v * 3 + i] = x)); + if (buf.uv && corner.uv) corner.uv.forEach((x, i) => (buf.uv![v * 2 + i] = x)); + if (buf.tile && corner.tile) corner.tile.forEach((x, i) => (buf.tile![v * 2 + i] = x)); + buf.f[v] = fold; + }); +} + +function appendTriangle(buf: GeoBuffer, corners: Vertex[], fold: number): void { + for (const corner of corners) { + buf.p.push(...corner.p); + buf.c.push(...corner.c); + buf.f.push(fold); + buf.uv?.push(...(corner.uv ?? [0.5, 0.5])); + buf.tile?.push(...(corner.tile ?? [0, 1])); + } +} + +/** + * Cuts the triangles from `fromTri` on at the height `cut`: pieces above get `fold`, pieces below keep theirs, and a + * triangle across the plane is split. New triangles go to the end of the buffer, so the range stays contiguous. + * Meant for tall furniture in the cut view. + */ +export function cutAbove(buf: GeoBuffer, fromTri: number, cut: number, fold: number): void { + const total = buf.count; + for (let tri = fromTri; tri < total; tri++) { + const corners = [0, 1, 2].map((k) => readVertex(buf, tri * 3 + k)); + const isAbove = corners.map((v) => v.p[1] > cut + EPS); + const isBelow = corners.map((v) => v.p[1] < cut - EPS); + if (!isAbove.some(Boolean)) continue; + if (!isBelow.some(Boolean)) { + for (let k = 0; k < 3; k++) buf.f[tri * 3 + k] = fold; + continue; + } + const kept = buf.f[tri * 3]; + const upCount = isAbove.filter(Boolean).length; + // rotate so the odd vertex out comes first, keeping the cyclic order (and so the winding) + const odd = upCount === 1 ? isAbove.indexOf(true) : isAbove.indexOf(false); + const [a, b, c] = [corners[odd], corners[(odd + 1) % 3], corners[(odd + 2) % 3]]; + const onAB = crossing(a, b, cut); + const onCA = crossing(c, a, cut); + // the small triangle at the odd vertex goes on the side it lies on, the quad (two triangles) on the other + const [small, quad] = upCount === 1 ? [fold, kept] : [kept, fold]; + overwriteTriangle(buf, tri, [a, onAB, onCA], small); + appendTriangle(buf, [onAB, b, c], quad); + appendTriangle(buf, [onAB, c, onCA], quad); + } +} + +/** The same for edge lines: segments from `fromSeg` on are split at the cut height, and the upper part gets `fold`. */ +export function cutLinesAbove(lines: LineBuffer, fromSeg: number, cut: number, fold: number): void { + const total = lines.p.length / 6; + for (let s = fromSeg; s < total; s++) { + const a = lines.p.slice(s * 6, s * 6 + 3); + const b = lines.p.slice(s * 6 + 3, s * 6 + 6); + const [low, high] = a[1] <= b[1] ? [a, b] : [b, a]; + if (high[1] <= cut + EPS) continue; + if (low[1] >= cut - EPS) { + lines.f[s * 2] = fold; + lines.f[s * 2 + 1] = fold; + continue; + } + const t = (cut - low[1]) / (high[1] - low[1]); + const middle = [low[0] + (high[0] - low[0]) * t, cut, low[2] + (high[2] - low[2]) * t]; + const color = lines.c.slice(s * 6, s * 6 + 3); + // the lower part stays in place, the upper part is appended + lines.p.splice(s * 6, 6, ...low, ...middle); + lines.p.push(...middle, ...high); + lines.c.push(...color, ...color); + lines.f.push(fold, fold); + } +} diff --git a/frontend/src/viewer/geo/geo.test.ts b/frontend/src/viewer/geo/geo.test.ts new file mode 100644 index 0000000..e66e878 --- /dev/null +++ b/frontend/src/viewer/geo/geo.test.ts @@ -0,0 +1,163 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { Color } from "three"; +import type { Vec2 } from "../../model.ts"; +import { ALWAYS, FURN_OFFSET, GeoBuffer, LineBuffer } from "./buffers.ts"; +import { heightShade, shade, sideLight } from "./colors.ts"; +import { cutAbove, cutLinesAbove } from "./cut.ts"; +import { pushLoft, pushLyingCyl, pushPrism, pushSkin, triangulate } from "./shapes.ts"; + +const grey = new Color(0x808080); +const heights = (buf: GeoBuffer) => Array.from({ length: buf.p.length / 3 }, (_, v) => buf.p[v * 3 + 1]); +const square: Vec2[] = [[0, 0], [2, 0], [2, 2], [0, 2]]; + +test("a triangle adds three vertices with their colours and fold values", () => { + const buf = new GeoBuffer(); + buf.tri([0, 0, 0], [1, 0, 0], [0, 0, 1], grey, new Color(1, 0, 0)); + assert.equal(buf.count, 1); + assert.equal(buf.p.length, 9); + assert.deepEqual(buf.f, [ALWAYS, ALWAYS, ALWAYS]); + assert.equal(buf.c[3], 1, "the second corner's own red"); + assert.equal(buf.uv, null); +}); + +test("uvs and tiles are only kept when asked for, and show up in the geometry", () => { + const buf = new GeoBuffer(true, true); + buf.tri([0, 0, 0], [1, 0, 0], [0, 0, 1], grey, grey, grey, [0, 0, 1, 0, 0, 1], 5, [2, 3]); + const g = buf.geometry(); + assert.ok(g.getAttribute("uv") && g.getAttribute("tile") && g.getAttribute("fold")); + assert.equal(g.getAttribute("position").count, 3); + assert.deepEqual(buf.tile, [2, 3, 2, 3, 2, 3]); + assert.equal(new GeoBuffer().geometry().getAttribute("uv"), undefined); +}); + +test("shading never exceeds 1 per channel, and light and height change the brightness", () => { + const bright = shade(0xffffff, 3); + assert.deepEqual([bright.r, bright.g, bright.b], [1, 1, 1]); + assert.ok(heightShade(0) < heightShade(0.8) && heightShade(0.8) < heightShade(1.6)); + assert.equal(heightShade(5), heightShade(1.6)); + const faces = [sideLight(1, 0), sideLight(0, 1), sideLight(-1, 0), sideLight(0, -1)]; + assert.ok(Math.max(...faces) <= 1.08 + 1e-9 && Math.min(...faces) >= 0.8 - 1e-9); + assert.ok(new Set(faces.map((f) => f.toFixed(3))).size > 1, "faces in different directions differ"); +}); + +test("line segments are split at the cut height only when they cross it", () => { + const lines = new LineBuffer(); + lines.segSplit([0, 0, 0], [0, 3, 0], grey, 1, 7); + assert.equal(lines.f.length, 4); + assert.deepEqual(lines.f, [ALWAYS, ALWAYS, 7, 7]); + lines.segSplit([0, 0, 0], [0, 0.5, 0], grey, 1, 7); + assert.deepEqual(lines.f.slice(4), [ALWAYS, ALWAYS], "wholly below: always shown"); + lines.segSplit([0, 2, 0], [1, 2, 0], grey, 1, 7); + assert.deepEqual(lines.f.slice(6), [7, 7], "wholly above: the bucket"); + lines.segSplit([0, 0, 0], [0, 3, 0], grey, 1, -1); + assert.deepEqual(lines.f.slice(8), [ALWAYS, ALWAYS], "a negative bucket never splits"); +}); + +test("cutAbove: pieces above get the fold, a crossing triangle is split, the rest is left alone", () => { + const buf = new GeoBuffer(); + buf.tri([0, 0, 0], [1, 0, 0], [1, 0.5, 0], grey); // below + buf.tri([0, 2, 0], [1, 2, 0], [1, 2.5, 0], grey); // above + buf.tri([0, 0, 0], [1, 0, 0], [1, 2, 0], grey); // one corner above + buf.tri([0, 2, 0], [1, 2, 0], [1, 0, 0], grey); // two corners above + cutAbove(buf, 0, 1.2, FURN_OFFSET); + assert.deepEqual(buf.f.slice(0, 3), [ALWAYS, ALWAYS, ALWAYS]); + assert.deepEqual(buf.f.slice(3, 6), [FURN_OFFSET, FURN_OFFSET, FURN_OFFSET]); + assert.equal(buf.count, 4 + 2 + 2, "each crossing triangle became three"); + heights(buf).forEach((y, v) => { + if (buf.f[v] === FURN_OFFSET) assert.ok(y >= 1.2 - 1e-9, `upper vertex at ${y}`); + else assert.ok(y <= 1.2 + 1e-9, `lower vertex at ${y}`); + }); +}); + +test("cutAbove keeps colours and uvs along the new edge", () => { + const buf = new GeoBuffer(true); + buf.tri([0, 0, 0], [0, 2, 0], [1, 0, 0], new Color(0, 0, 0), new Color(1, 1, 1), new Color(0, 0, 0), [0, 0, 0, 1, 1, 0]); + cutAbove(buf, 0, 1, 64); + const cutVertex = Array.from({ length: buf.count * 3 }, (_, v) => v).find((v) => Math.abs(buf.p[v * 3 + 1] - 1) < 1e-9 && buf.p[v * 3] === 0)!; + assert.ok(Math.abs(buf.c[cutVertex * 3] - 0.5) < 1e-9, "halfway colour"); + assert.ok(Math.abs(buf.uv![cutVertex * 2 + 1] - 0.5) < 1e-9, "halfway uv"); +}); + +test("cutAbove only touches triangles from the given one on", () => { + const buf = new GeoBuffer(); + buf.tri([0, 2, 0], [1, 2, 0], [1, 3, 0], grey); + buf.tri([0, 2, 0], [1, 2, 0], [1, 3, 0], grey); + cutAbove(buf, 1, 1, 64); + assert.deepEqual(buf.f, [ALWAYS, ALWAYS, ALWAYS, 64, 64, 64]); +}); + +test("cutLinesAbove splits a vertical edge at the cut and leaves low ones alone", () => { + const lines = new LineBuffer(); + lines.seg([0, 0, 0], [0, 2, 0]); + lines.seg([0, 0, 0], [1, 0, 0]); + lines.seg([0, 2, 0], [1, 2, 0]); + cutLinesAbove(lines, 0, 1.2, FURN_OFFSET); + assert.equal(lines.p.length / 6, 4); + assert.deepEqual(lines.p.slice(0, 6), [0, 0, 0, 0, 1.2, 0]); + assert.deepEqual(lines.f, [ALWAYS, ALWAYS, ALWAYS, ALWAYS, FURN_OFFSET, FURN_OFFSET, FURN_OFFSET, FURN_OFFSET]); + assert.deepEqual(lines.p.slice(18, 24), [0, 1.2, 0, 0, 2, 0]); +}); + +test("triangulating a square gives two triangles, with a hole it gives more", () => { + assert.equal(triangulate(square).length, 2); + const hole: Vec2[] = [[0.5, 0.5], [0.5, 1.5], [1.5, 1.5], [1.5, 0.5]]; + assert.ok(triangulate(square, [hole]).length > 4); +}); + +test("a prism has a top, four sides of two triangles each, and optionally a bottom", () => { + const plain = new GeoBuffer(); + pushPrism(plain, square, 0, 1, 0x888888, 0xcccccc); + assert.equal(plain.count, 2 + 8); + const closed = new GeoBuffer(); + pushPrism(closed, square, 0, 1, 0x888888, 0xcccccc, { bottom: true }); + assert.equal(closed.count, 2 + 8 + 2); + const open = new GeoBuffer(); + pushPrism(open, square, 0, 1, 0x888888, 0xcccccc, { topFace: false }); + assert.equal(open.count, 8); +}); + +test("a prism's top can follow a height function and its sides can be skipped or folded", () => { + const sloped = new GeoBuffer(); + pushPrism(sloped, square, 0, (x) => 1 + x, 0x888888, 0xcccccc); + assert.equal(Math.max(...heights(sloped)), 3); + const skipped = new GeoBuffer(); + pushPrism(skipped, square, 0, 1, 0x888888, 0xcccccc, { skipSide: (a, b) => a[1] === 0 && b[1] === 0 }); + assert.equal(skipped.count, 2 + 6); + const folded = new GeoBuffer(); + pushPrism(folded, square, 0, 1, 0x888888, 0xcccccc, { fold: 20, topFold: 33 }); + assert.ok(folded.f.includes(33) && folded.f.includes(20)); +}); + +test("a prism with a hole gets inner sides facing the hole", () => { + const hole: Vec2[] = [[0.5, 0.5], [1.5, 0.5], [1.5, 1.5], [0.5, 1.5]]; + const buf = new GeoBuffer(); + pushPrism(buf, square, 0, 1, 0x888888, 0xcccccc, { holes: [hole] }); + assert.ok(buf.count > 2 + 8 + 8 - 1); +}); + +test("a loft has sloped sides and a top of the smaller rectangle", () => { + const buf = new GeoBuffer(); + pushLoft(buf, square, [[0.5, 0.5], [1.5, 0.5], [1.5, 1.5], [0.5, 1.5]], 0, 1, 0x888888, 0xcccccc); + assert.equal(buf.count, 8 + 2); + const flatTop = new GeoBuffer(); + pushLoft(flatTop, square, square.map(([x, z]) => [x, z] as Vec2), 0, 1, 0x888888, 0xcccccc); + assert.equal(flatTop.count, 8 + 2); +}); + +test("a skin joins rings into a closed body", () => { + const ring = (z: number, r: number) => [0, 1, 2, 3, 4, 5].map((i) => [Math.cos((i / 6) * 6.2832) * r, 1 + Math.sin((i / 6) * 6.2832) * r, z]); + const buf = new GeoBuffer(); + pushSkin(buf, [ring(0, 0.5), ring(1, 0.8), ring(2, 0.5)], 0x888888, 0xcccccc); + assert.equal(buf.count, 2 * 6 * 2 + 2 * 6); + const none = new GeoBuffer(); + pushSkin(none, [ring(0, 1)], 0x888888, 0xcccccc); + assert.equal(none.count, 0); +}); + +test("a lying cylinder has n sides of two triangles and n triangles per end cap", () => { + const buf = new GeoBuffer(); + pushLyingCyl(buf, (along, across) => [along, across], 0, 1, 0, 0.5, 0.5, 0x333333, 0x666666, 8); + assert.equal(buf.count, 8 * 2 + 8 * 2); + assert.ok(Math.max(...heights(buf)) <= 1 + 1e-9 && Math.min(...heights(buf)) >= -1e-9); +}); diff --git a/frontend/src/viewer/geo/shapes.ts b/frontend/src/viewer/geo/shapes.ts new file mode 100644 index 0000000..26f7e34 --- /dev/null +++ b/frontend/src/viewer/geo/shapes.ts @@ -0,0 +1,192 @@ +// Solid shapes pushed into a buffer: prisms, lofts, smooth skins and lying cylinders. + +import { Color, ShapeUtils, Vector2 } from "three"; +import type { Vec2 } from "../../model.ts"; +import { ALWAYS, type GeoBuffer } from "./buffers.ts"; +import { heightShade, LIGHT, shade, sideLight } from "./colors.ts"; + +/** The signed area of a ring in (x, z), doubled: positive when counter-clockwise. */ +const ringArea = (ring: Vec2[]): number => ring.reduce((sum, p, i) => sum + p[0] * ring[(i + 1) % ring.length][1] - ring[(i + 1) % ring.length][0] * p[1], 0); + +const toVector = ([x, z]: Vec2) => new Vector2(x, z); + +/** Triangles (index triples into the outline followed by the holes) that fill a polygon with holes. */ +export function triangulate(outline: Vec2[], holes: Vec2[][] = []): number[][] { + return ShapeUtils.triangulateShape(outline.map(toVector), holes.map((h) => h.map(toVector))); +} + +type Rgb3 = number[]; + +const subtract = (a: Rgb3, b: Rgb3): Rgb3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; +const crossProduct = (a: Rgb3, b: Rgb3): Rgb3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; +const dotProduct = (a: Rgb3, b: Rgb3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const normalized = (a: Rgb3): Rgb3 => { + const length = Math.hypot(a[0], a[1], a[2]) || 1; + return [a[0] / length, a[1] / length, a[2] / length]; +}; + +/** + * A box whose top rectangle differs from its bottom one (sloped sides). `lo` and `hi` are the four corners in the same + * order. Faces that lean upwards blend towards the top colour. + */ +export function pushLoft(buf: GeoBuffer, lo: Vec2[], hi: Vec2[], y0: number, y1: number, side: number, top: number): void { + const topColor = new Color(top); + for (let i = 0; i < 4; i++) { + const [a, b] = [lo[i], lo[(i + 1) % 4]]; + const [A, B] = [hi[i], hi[(i + 1) % 4]]; + const [dx, dz] = [b[0] - a[0], b[1] - a[1]]; + const length = Math.hypot(dx, dz); + if (length < 1e-6) continue; + // how far the face leans back: its top edge moved inwards (the outward normal is (dz, -dx)) + const lean = ((A[0] + B[0] - a[0] - b[0]) / 2) * (-dz / length) + ((A[1] + B[1] - a[1] - b[1]) / 2) * (dx / length); + const blendUp = Math.max(0, Math.min(1, lean / Math.max(1e-6, Math.hypot(lean, y1 - y0)))); + const light = sideLight(dx, dz); + const lower = shade(side, heightShade(y0) * light).lerp(topColor, blendUp); + const upper = shade(side, heightShade(y1) * light).lerp(topColor, blendUp); + buf.tri([a[0], y0, a[1]], [A[0], y1, A[1]], [B[0], y1, B[1]], lower, upper, upper); + buf.tri([a[0], y0, a[1]], [B[0], y1, B[1]], [b[0], y0, b[1]], lower, upper, lower); + } + const [h0, h1, h2, h3] = hi; + if (Math.hypot(h2[0] - h0[0], h2[1] - h0[1]) > 1e-4) { + buf.tri([h0[0], y1, h0[1]], [h2[0], y1, h2[1]], [h1[0], y1, h1[1]], topColor); + buf.tri([h0[0], y1, h0[1]], [h3[0], y1, h3[1]], [h2[0], y1, h2[1]], topColor); + } +} + +/** + * A smooth body: `rings` are cross sections along it (the same number of points each, going round the section), joined + * into a skin with a shade per point taken from its own surface direction, so curves look round. Both ends are closed. + * The winding follows from the geometry, so mirrored items need no extra care. + */ +export function pushSkin(buf: GeoBuffer, rings: number[][][], side: number, top: number): void { + const count = rings.length; + if (count < 2) return; + const around = rings[0].length; + const topColor = new Color(top); + const centres = rings.map((ring) => [0, 1, 2].map((k) => ring.reduce((sum, p) => sum + p[k], 0) / around)); + + // an outward normal for every point of every ring + const normals = rings.map((ring, s) => + ring.map((p, i) => { + const lengthways = subtract(rings[Math.min(count - 1, s + 1)][i], rings[Math.max(0, s - 1)][i]); + const roundAbout = subtract(ring[(i + 1) % around], ring[(i + around - 1) % around]); + const normal = normalized(crossProduct(lengthways, roundAbout)); + return dotProduct(normal, subtract(p, centres[s])) < 0 ? normal.map((v) => -v) : normal; + }), + ); + const colorAt = (p: Rgb3, normal: Rgb3) => { + const lit = (normal[0] * LIGHT[0] + normal[2] * LIGHT[1] + 1) / 2; + return shade(side, heightShade(p[1]) * (0.8 + 0.28 * lit)).lerp(topColor, Math.max(0, normal[1]) * 0.9); + }; + // a triangle turned so that it faces `outward` (the average outward normal) + const faceOut = (a: Rgb3, b: Rgb3, c: Rgb3, outward: Rgb3, ca: Color, cb: Color, cc: Color) => { + if (dotProduct(crossProduct(subtract(b, a), subtract(c, a)), outward) >= 0) buf.tri(a, b, c, ca, cb, cc); + else buf.tri(a, c, b, ca, cc, cb); + }; + + for (let s = 0; s + 1 < count; s++) { + for (let i = 0; i < around; i++) { + const j = (i + 1) % around; + const corners = [rings[s][i], rings[s][j], rings[s + 1][j], rings[s + 1][i]]; + const cornerNormals = [normals[s][i], normals[s][j], normals[s + 1][j], normals[s + 1][i]]; + const [ca, cb, cc, cd] = corners.map((p, k) => colorAt(p, cornerNormals[k])); + const outward = [0, 1, 2].map((k) => cornerNormals.reduce((sum, n) => sum + n[k], 0)); + faceOut(corners[0], corners[1], corners[2], outward, ca, cb, cc); + faceOut(corners[0], corners[2], corners[3], outward, ca, cc, cd); + } + } + // close both ends with a fan around the centre + for (const [s, direction] of [[0, -1], [count - 1, 1]] as const) { + const ring = rings[s]; + const lengthways = subtract(rings[s === 0 ? 1 : count - 2][0], ring[0]); + const outward = normalized(lengthways.map((v) => v * -direction)); + const color = colorAt(centres[s], outward); + for (let i = 0; i < around; i++) faceOut(ring[i], ring[(i + 1) % around], centres[s], outward, color, color, color); + } +} + +/** + * A cylinder lying along the x or z axis (wheels, rollers, pipes). `at` maps an along-axis value and an across value to + * world (x, z); `c` is the centre across, `cy` the centre height, `n` the number of sides. + */ +export function pushLyingCyl(buf: GeoBuffer, at: (along: number, across: number) => Vec2, a0: number, a1: number, c: number, cy: number, r: number, side: number, cap: number, n: number): void { + const capColor = new Color(cap); + const round = Array.from({ length: n }, (_, i) => { + const angle = (i / n) * Math.PI * 2; + return { y: cy + Math.cos(angle) * r, across: c + Math.sin(angle) * r }; + }); + const point = (along: number, i: number): Rgb3 => { + const { y, across } = round[i % n]; + const [x, z] = at(along, across); + return [x, y, z]; + }; + for (let i = 0; i < n; i++) { + const color = shade(side, 0.62 + 0.4 * Math.max(0, Math.cos(((i + 0.5) / n) * Math.PI * 2))); + buf.tri(point(a0, i), point(a1, i + 1), point(a1, i), color); + buf.tri(point(a0, i), point(a0, i + 1), point(a1, i + 1), color); + } + for (const along of [a0, a1]) { + const [x, z] = at(along, c); + for (let i = 0; i < n; i++) buf.tri([x, cy, z], point(along, i), point(along, i + 1), capColor); + } +} + +export interface PrismOptions { + /** Height from which the baked darkening towards the floor starts (default: the bottom). */ + aoFrom?: number; + fold?: number; + topFold?: number; + bottom?: boolean; + topFace?: boolean; + /** Cut-outs in the area: their rings are turned so the inner sides face the hole. */ + holes?: Vec2[][]; + skipSide?: (a: Vec2, b: Vec2) => boolean; + /** The colour of each side face instead of `side` (painted walls: each face in the colour of the room it faces). */ + sideColor?: (a: Vec2, b: Vec2) => number; +} + +/** + * A vertical prism over a counter-clockwise polygon. The side colours darken towards the floor (baked occlusion) and + * vary slightly with the direction the face points to. The top can follow a height function (a wall ending under a roof + * slope), which stays flat for a wall piece inside one roof plane. + */ +export function pushPrism(buf: GeoBuffer, poly: Vec2[], y0: number, y1: number | ((x: number, z: number) => number), side: number, top: number, opts: PrismOptions = {}): void { + const topAt = typeof y1 === "number" ? () => y1 : (p: Vec2) => Math.max(y0 + 0.002, y1(p[0], p[1])); + const aoFrom = opts.aoFrom ?? y0; + const fold = opts.fold ?? ALWAYS; + const occlusion = (y: number) => heightShade(y - aoFrom); + const holes = (opts.holes ?? []).map((h) => (ringArea(h) > 0 ? [...h].reverse() : h)); + const corners = holes.length ? [...poly, ...holes.flat()] : poly; + const withTop = opts.topFace !== false; + const triangles = !withTop && !opts.bottom ? [] : triangulate(poly, holes); + + if (withTop) { + const color = new Color(top); + for (const [i, j, k] of triangles) { + // the polygon is counter-clockwise in (x, z), which is clockwise seen from above (+y): swap two corners + const [a, b, c] = [corners[i], corners[j], corners[k]]; + buf.tri([a[0], topAt(a), a[1]], [c[0], topAt(c), c[1]], [b[0], topAt(b), b[1]], color, color, color, undefined, opts.topFold ?? fold); + } + } + if (opts.bottom) { + const color = shade(side, 0.55); + for (const [i, j, k] of triangles) { + const [a, b, c] = [corners[i], corners[j], corners[k]]; + buf.tri([a[0], y0, a[1]], [b[0], y0, b[1]], [c[0], y0, c[1]], color, color, color, undefined, fold); + } + } + for (const ring of [poly, ...holes]) { + ring.forEach((a, i) => { + const b = ring[(i + 1) % ring.length]; + if (Math.hypot(b[0] - a[0], b[1] - a[1]) < 1e-6 || opts.skipSide?.(a, b)) return; + const light = sideLight(b[0] - a[0], b[1] - a[1]); + const [ya, yb] = [topAt(a), topAt(b)]; + const own = opts.sideColor ? opts.sideColor(a, b) : side; + const foot = shade(own, occlusion(y0) * light); + const headA = shade(own, occlusion(ya) * light); + const headB = shade(own, occlusion(yb) * light); + buf.tri([a[0], y0, a[1]], [a[0], ya, a[1]], [b[0], yb, b[1]], foot, headA, headB, undefined, fold); + buf.tri([a[0], y0, a[1]], [b[0], yb, b[1]], [b[0], y0, b[1]], foot, headB, foot, undefined, fold); + }); + } +} diff --git a/frontend/src/viewer/lamp-colors.test.ts b/frontend/src/viewer/lamp-colors.test.ts new file mode 100644 index 0000000..3618694 --- /dev/null +++ b/frontend/src/viewer/lamp-colors.test.ts @@ -0,0 +1,26 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { recolorLamps, shadeFactors } from "./lamp-colors.ts"; + +test("sentinel vertices become shade factors, body vertices stay at 0", () => { + // two triangles: a shaded side (factor 0.7), a top (factor 1), a body vertex and a dark body vertex + const colors = [0, 0.7, 0, 0, 1, 0, 0.16, 0.22, 0.38, 0, 0, 0, 0.04, 0.1, 0.2, 0, 0.55, 0]; + const f = shadeFactors(colors); + assert.deepEqual([...f].map((v) => Math.round(v * 100) / 100), [0.7, 1, 0, 0, 0, 0.55]); +}); + +test("recolouring writes the light's colour times the factor into the lamp's range only", () => { + const colors = new Float32Array([0, 0.5, 0, 0, 1, 0, 0.1, 0.1, 0.1, 0, 1, 0, 0, 1, 0, 0, 1, 0]); + const factors = shadeFactors(colors); + // range in triangles: the first triangle (vertices 0..2) belongs to the lamp, the second to another + recolorLamps(colors, factors, { start: 0, end: 1 }, [1, 0.5, 0.2]); + assert.deepEqual([...colors.slice(0, 3)].map((v) => Math.round(v * 100) / 100), [0.5, 0.25, 0.1]); + assert.deepEqual([...colors.slice(3, 6)].map((v) => Math.round(v * 100) / 100), [1, 0.5, 0.2]); + // the body vertex keeps its colour + assert.deepEqual([...colors.slice(6, 9)].map((v) => Math.round(v * 100) / 100), [0.1, 0.1, 0.1]); + // the other lamp is untouched + assert.deepEqual([...colors.slice(9, 12)], [0, 1, 0]); + // channels never exceed 1 + recolorLamps(colors, factors, { start: 1, end: 2 }, [1.5, 1.2, 1]); + assert.deepEqual([...colors.slice(9, 12)], [1, 1, 1]); +}); diff --git a/frontend/src/viewer/lamp-colors.ts b/frontend/src/viewer/lamp-colors.ts new file mode 100644 index 0000000..baf8983 --- /dev/null +++ b/frontend/src/viewer/lamp-colors.ts @@ -0,0 +1,27 @@ +// Lamp shades are built with a sentinel colour, so the colour of the light can be written into the +// merged lamp mesh later without rebuilding it (colour effects change several times per second). + +/** Pure green: no body colour has r = b = 0, so sentinel vertices are told apart by that. */ +export const SHADE_SENTINEL = 0x00ff00; + +/** Shade factor per vertex: the green channel of sentinel-coloured vertices (r = b = 0), else 0. */ +export function shadeFactors(colors: ArrayLike): Float32Array { + const n = colors.length / 3; + const out = new Float32Array(n); + for (let v = 0; v < n; v++) { + const g = colors[v * 3 + 1]; + if (colors[v * 3] === 0 && colors[v * 3 + 2] === 0 && g > 0) out[v] = g; + } + return out; +} + +/** Write a shade colour into a lamp's triangle range, scaled by each vertex's factor; bodies stay. */ +export function recolorLamps(colors: Float32Array, factors: Float32Array, range: { start: number; end: number }, color: [number, number, number]): void { + for (let v = range.start * 3; v < range.end * 3; v++) { + const f = factors[v]; + if (f <= 0) continue; + colors[v * 3] = Math.min(1, color[0] * f); + colors[v * 3 + 1] = Math.min(1, color[1] * f); + colors[v * 3 + 2] = Math.min(1, color[2] * f); + } +} diff --git a/frontend/src/viewer/lighting.ts b/frontend/src/viewer/lighting.ts new file mode 100644 index 0000000..9202f6a --- /dev/null +++ b/frontend/src/viewer/lighting.ts @@ -0,0 +1,5 @@ +// Room lighting without real-time lights, split into modules in lighting/: the surface the light is painted on, and the +// light that falls on it. + +export { buildLightSurface, type LightSurface } from "./lighting/surface.ts"; +export { lightColors, roomIndexAt, zoneOf, type LightKind, type LightSource } from "./lighting/light.ts"; diff --git a/frontend/src/viewer/lighting/light.ts b/frontend/src/viewer/lighting/light.ts new file mode 100644 index 0000000..74c225d --- /dev/null +++ b/frontend/src/viewer/lighting/light.ts @@ -0,0 +1,125 @@ +// The light itself: how much light a lamp sends to a point, and the colours of the light surface for a set of lamps. + +import { pointInPolygon, type Floor } from "../../model.ts"; +import type { LightSurface } from "./surface.ts"; + +/** How a lamp spreads its light. */ +export type LightKind = "omni" | "ceiling" | "spot" | "pendant" | "up" | "wall"; + +export interface LightSource { + x: number; + y: number; + z: number; + /** Linear colour, 0..1 per channel. */ + color: [number, number, number]; + /** Brightness, 0..1. */ + level: number; + kind: LightKind; + /** The index of the room (floor.rooms) the lamp is in. */ + room: number; +} + +/** The share of its light a lamp sends in a direction; dy is the vertical part of the unit vector from the lamp to the point. */ +function characteristic(kind: LightKind, dy: number): number { + const down = Math.max(0, -dy); + const up = Math.max(0, dy); + switch (kind) { + case "ceiling": + return 0.3 + 0.7 * down; + case "spot": + return 0.06 + 0.94 * down ** 5; + case "pendant": + return 0.25 + 0.85 * down ** 2 + 0.2 * up; + case "up": + return 0.25 + 0.75 * up; + case "wall": + return 0.45 + 0.35 * Math.abs(dy); + default: + return 1; + } +} + +/** The distance at which a lamp's light has fallen to half. */ +function reachOf(lamp: { level: number; kind: LightKind }): number { + const base = lamp.kind === "spot" ? 2 : lamp.kind === "wall" ? 1.4 : 2.4; + return base * (0.55 + 0.45 * lamp.level); +} + +type Triple = readonly [number, number, number]; + +/** The brightness one lamp gives a surface point with a normal. */ +function contribution(lamp: LightSource, at: Triple, normal: Triple): number { + const [dx, dy, dz] = [at[0] - lamp.x, at[1] - lamp.y, at[2] - lamp.z]; + const squared = dx * dx + dy * dy + dz * dz; + const distance = Math.sqrt(squared) || 1e-6; + const reach = reachOf(lamp); + // a squared falloff keeps a bright pool under the lamp and dark corners: the neon look lives on contrast + const falloff = 1 / (1 + squared / (reach * reach)); + const attenuation = falloff * Math.sqrt(falloff); + // surfaces facing the lamp get more light; a floor right below a lamp faces it fully + const facing = Math.max(0, -(dx * normal[0] + dy * normal[1] + dz * normal[2]) / distance); + return lamp.level * attenuation * (0.2 + 0.8 * facing) * characteristic(lamp.kind, dy / distance); +} + +/** Light a room passes on through an open door: the doorway acts as a lamp for the room on the other side. */ +function lampsThroughDoors(surface: LightSurface, sources: LightSource[], doorOpen: number[]): LightSource[] { + const passed: LightSource[] = []; + surface.doors.forEach((door, i) => { + const open = doorOpen[i] ?? 0.5; + if (open <= 0.01) return; + for (const [from, to] of [[door.a, door.b], [door.b, door.a]]) { + const sum: [number, number, number] = [0, 0, 0]; + for (const lamp of sources.filter((s) => s.room === from)) { + // the doorway takes the light as if it faced the lamp + const toLamp: Triple = [lamp.x - door.x, lamp.y - door.y, lamp.z - door.z]; + const length = Math.hypot(...toLamp) || 1; + const k = contribution(lamp, [door.x, door.y, door.z], [toLamp[0] / length, toLamp[1] / length, toLamp[2] / length]); + for (let c = 0; c < 3; c++) sum[c] += lamp.color[c] * k; + } + const level = Math.max(...sum); + if (level < 0.01) continue; + passed.push({ x: door.x, y: door.y, z: door.z, color: [sum[0] / level, sum[1] / level, sum[2] / level], level: Math.min(1, level * 0.9 * (0.35 + 0.65 * open)), kind: "wall", room: to }); + } + }); + return passed; +} + +/** + * The colours (r, g, b per vertex) of the light surface for the lamps. A lamp lights its own room; through a door a room + * passes on part of the light that reaches the doorway (`doorOpen` is 0..1 per door index, default half open). + */ +export function lightColors(surface: LightSurface, sources: LightSource[], strength = 0.7, doorOpen: number[] = []): Float32Array { + const lampsByRoom = new Map(); + for (const lamp of [...sources, ...lampsThroughDoors(surface, sources, doorOpen)]) { + // warm light stays warm on the blue floor + const curved = { ...lamp, color: lamp.color.map((v) => v ** 1.5) as [number, number, number] }; + lampsByRoom.set(lamp.room, [...(lampsByRoom.get(lamp.room) ?? []), curved]); + } + const { pos, normal, room } = surface; + const colors = new Float32Array(pos.length); + for (let v = 0; v < room.length; v++) { + const lamps = lampsByRoom.get(room[v]); + if (!lamps) continue; + const i = v * 3; + const sum = [0, 0, 0]; + for (const lamp of lamps) { + const k = contribution(lamp, [pos[i], pos[i + 1], pos[i + 2]], [normal[i], normal[i + 1], normal[i + 2]]); + for (let c = 0; c < 3; c++) sum[c] += lamp.color[c] * k; + } + // soft saturation: several lamps add up without clipping to flat white + for (let c = 0; c < 3; c++) colors[i + c] = 1 - Math.exp(-sum[c] * strength * 1.6); + } + return colors; +} + +/** The index of the room a point lies in; outside every room it is the outside zone (rooms.length). */ +export function roomIndexAt(floor: Floor, x: number, z: number): number { + const index = floor.rooms.findIndex((r) => r.points.length >= 3 && pointInPolygon([x, z], r.points)); + return index < 0 ? floor.rooms.length : index; +} + +/** + * The light zone a room index belongs to. Indices past the zone list (the outside zone, rooms.length) and -1 keep their + * own number, so outdoor lamps still light the lawn when rooms are joined. + */ +export const zoneOf = (zones: number[] | null, room: number): number => (zones && room >= 0 && room < zones.length ? zones[room] : room); diff --git a/frontend/src/viewer/lighting/lighting.test.ts b/frontend/src/viewer/lighting/lighting.test.ts new file mode 100644 index 0000000..99339a9 --- /dev/null +++ b/frontend/src/viewer/lighting/lighting.test.ts @@ -0,0 +1,126 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { newFloor, type Floor, type Opening, type Room } from "../../model.ts"; +import { buildFloorGeometry } from "../build.ts"; +import { lightColors, roomIndexAt, zoneOf, type LightSource } from "./light.ts"; +import { buildLightSurface, type LightSurface } from "./surface.ts"; + +const room = (id: string, x0: number, z0: number, x1: number, z1: number): Room => ({ id, name: id, area_id: null, points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]], floor_material: "wood" }); +const door = (id: string, roomId: string, edge: number, offset: number): Opening => + ({ id, room_id: roomId, edge, offset, width: 0.9, type: "door", sill: 0, height: 2.05, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null }) as Opening; + +function surfaceOf(floor: Floor, cell = 0.5, holes: [number, number][][] = []): LightSurface { + const geometry = buildFloorGeometry(floor, 0.3, 0.1); + return buildLightSurface(floor, geometry.walls2d, geometry.wallBuckets, geometry.openings, cell, holes); +} + +const lamp = (x: number, z: number, color: [number, number, number], roomIndex = 0, extra: Partial = {}): LightSource => ({ x, y: 2.4, z, color, level: 1, kind: "ceiling", room: roomIndex, ...extra }); + +/** The colour of the floor vertex nearest to (x, z). */ +function floorColor(surface: LightSurface, colors: Float32Array, x: number, z: number): number[] { + let best = -1; + let bestDistance = Infinity; + for (let v = 0; v < surface.room.length; v++) { + if (surface.normal[v * 3 + 1] !== 1) continue; + const distance = Math.hypot(surface.pos[v * 3] - x, surface.pos[v * 3 + 2] - z); + if (distance < bestDistance) [best, bestDistance] = [v, distance]; + } + return [colors[best * 3], colors[best * 3 + 1], colors[best * 3 + 2]]; +} + +const quadCount = (s: LightSurface) => s.room.length / 6; +const floorQuads = (s: LightSurface) => [...Array(quadCount(s)).keys()].filter((q) => s.normal[q * 18 + 1] === 1).length; + +test("the surface covers the floor in cells and puts strips on the room side of the walls", () => { + const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3)] }; + const s = surfaceOf(floor); + assert.equal(floorQuads(s), 8 * 6); + assert.ok(quadCount(s) > floorQuads(s)); + assert.ok(s.room.every((r) => r === 0 || r === 1), "room 0 and the outside zone (index 1) only"); + assert.equal(s.pos.length, s.room.length * 3); + assert.equal(s.fold.length, s.room.length); +}); + +test("a floor opening leaves no light under it", () => { + const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3)] }; + const whole = floorQuads(surfaceOf(floor)); + const holed = floorQuads(surfaceOf(floor, 0.5, [[[1, 1], [2, 1], [2, 2], [1, 2]]])); + assert.equal(whole - holed, 4); +}); + +/** The total area of the wall quads (those not facing up). */ +function wallArea(s: LightSurface): number { + let area = 0; + for (let t = 0; t < s.room.length / 3; t++) { + if (s.normal[t * 9 + 1] === 1) continue; + const p = (k: number) => [s.pos[t * 9 + k * 3], s.pos[t * 9 + k * 3 + 1], s.pos[t * 9 + k * 3 + 2]]; + const [a, b, c] = [p(0), p(1), p(2)]; + const [u, v] = [[b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]]; + area += 0.5 * Math.hypot(u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]); + } + return area; +} + +test("a door leaves a hole in the lit face of its wall: about its width times its height less light surface", () => { + const plain = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3)] }; + const withDoor = { ...plain, openings: [door("d", "a", 0, 1.5)] }; + const lost = wallArea(surfaceOf(plain)) - wallArea(surfaceOf(withDoor)); + // an exterior wall is lit on both faces, so the door is missing twice + assert.ok(Math.abs(lost - 2 * 0.9 * 2.05) < 0.4, String(lost)); +}); + +test("a lamp lights its own room only, brightest below it, with its own colour", () => { + const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3), room("b", 6, 0, 10, 3)] }; + const s = surfaceOf(floor); + const colors = lightColors(s, [lamp(2, 1.5, [1, 0, 0])]); + const below = floorColor(s, colors, 2, 1.5); + const corner = floorColor(s, colors, 0.3, 0.3); + assert.ok(below[0] > corner[0] && corner[0] > 0); + assert.ok(below[1] === 0 && below[2] === 0, "a red lamp gives red light"); + assert.deepEqual(floorColor(s, colors, 8, 1.5), [0, 0, 0], "the other room stays dark"); +}); + +test("lamps add up without exceeding 1", () => { + const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3)] }; + const s = surfaceOf(floor); + const many = Array.from({ length: 12 }, () => lamp(2, 1.5, [1, 1, 1])); + const colors = lightColors(s, many, 1); + assert.ok(Math.max(...colors) < 1 && Math.max(...colors) > 0.9); + const one = lightColors(s, [lamp(2, 1.5, [1, 1, 1])], 1); + assert.ok(floorColor(s, colors, 2, 1.5)[0] > floorColor(s, one, 2, 1.5)[0]); +}); + +test("the lamp kinds spread differently: a spot is narrow, an up-light points up", () => { + const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 8, 6)] }; + const s = surfaceOf(floor); + const spread = (kind: LightSource["kind"]) => { + const colors = lightColors(s, [lamp(4, 3, [1, 1, 1], 0, { kind })]); + return floorColor(s, colors, 4, 3)[0] / floorColor(s, colors, 6.5, 3)[0]; + }; + assert.ok(spread("spot") > spread("ceiling")); + assert.ok(spread("ceiling") >= spread("omni") * 0.5); +}); + +test("light leaks into the next room through an open door, not through a closed one", () => { + const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3), room("b", 4, 0, 8, 3)], openings: [door("d", "a", 1, 1.5)] }; + const s = surfaceOf(floor); + assert.equal(s.doors.length, 1); + assert.deepEqual([s.doors[0].a, s.doors[0].b].sort(), [0, 1]); + const sources = [lamp(2, 1.5, [1, 1, 1], 0)]; + const closed = floorColor(s, lightColors(s, sources, 0.7, [0]), 6, 1.5); + const open = floorColor(s, lightColors(s, sources, 0.7, [1]), 6, 1.5); + const half = floorColor(s, lightColors(s, sources), 6, 1.5); + assert.equal(closed[0], 0); + assert.ok(open[0] > half[0] && half[0] > 0); +}); + +test("the room under a point, and the zone a room belongs to", () => { + const floor = { ...newFloor("f", "F", 0), rooms: [room("a", 0, 0, 4, 3), room("b", 4, 0, 8, 3)] }; + assert.equal(roomIndexAt(floor, 1, 1), 0); + assert.equal(roomIndexAt(floor, 5, 1), 1); + assert.equal(roomIndexAt(floor, 20, 20), 2, "outside every room: the outside zone"); + assert.equal(zoneOf(null, 1), 1); + assert.equal(zoneOf([0, 0], 1), 0, "joined rooms share a zone"); + assert.equal(zoneOf([0, 0], 2), 2, "the outside zone keeps its own number"); + assert.equal(zoneOf([0, 0], -1), -1); +}); diff --git a/frontend/src/viewer/lighting/surface.ts b/frontend/src/viewer/lighting/surface.ts new file mode 100644 index 0000000..d87d30d --- /dev/null +++ b/frontend/src/viewer/lighting/surface.ts @@ -0,0 +1,193 @@ +// The light surface: floors and the room side of wall faces are covered by a fine grid of quads. Every vertex knows its +// room and the direction it faces. The surface is built once per floor plan; the light colours are recomputed when a lamp +// changes (see light.ts). + +import type { Wall } from "../../geometry/walls.ts"; +import { outdoorStanding, pointInPolygon, type Floor, type Vec2 } from "../../model.ts"; +import type { OpeningInfo } from "../build.ts"; +import { LOWER_OFFSET } from "../geo.ts"; +import { outdoorHoles, outdoorSurface } from "../outdoor.ts"; + +export interface LightSurface { + /** Vertex positions (x, y, z), six vertices per quad. */ + pos: Float32Array; + /** The direction each vertex faces (x, y, z). */ + normal: Float32Array; + /** The room index of each vertex. */ + room: Int16Array; + /** The fold value of each vertex (see build.ts), so light on walls follows the cut and glass walls. */ + fold: Float32Array; + /** Doors between two rooms: light leaks through them. */ + doors: { id: string; a: number; b: number; x: number; y: number; z: number }[]; +} + +/** Floor quads lie this high above the floor, wall quads this far in front of the wall face. */ +const FLOOR_LIFT = 0.012; +const FACE_GAP = 0.012; + +/** Collects quads (two triangles each) with their attributes. */ +function quadCollector() { + const pos: number[] = []; + const normal: number[] = []; + const room: number[] = []; + const fold: number[] = []; + return { + add(a: number[], b: number[], c: number[], d: number[], n: number[], roomIndex: number, foldValue: number) { + for (const v of [a, b, c, a, c, d]) { + pos.push(v[0], v[1], v[2]); + normal.push(n[0], n[1], n[2]); + room.push(roomIndex); + fold.push(foldValue); + } + }, + finish: (doors: LightSurface["doors"]): LightSurface => ({ pos: new Float32Array(pos), normal: new Float32Array(normal), room: Int16Array.from(room), fold: new Float32Array(fold), doors }), + }; +} + +/** Whether a door or window stands on a wall: on its line and running along it. */ +function standsOn(wall: Wall, o: OpeningInfo): boolean { + const [dx, dz] = [wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]; + const length = Math.hypot(dx, dz) || 1; + const offLine = Math.abs((o.start[0] - wall.a[0]) * dz - (o.start[1] - wall.a[1]) * dx) / length; + return offLine < 0.02 && Math.abs((o.axis[0] * dx + o.axis[1] * dz) / length) > 0.99; +} + +interface Span { + s0: number; + s1: number; + y0: number; + y1: number; +} + +/** The areas of doors and windows on a wall: along it (s from wall.a) and in height. */ +function openingSpans(wall: Wall, along: Vec2, length: number, openings: OpeningInfo[]): Span[] { + const spans: Span[] = []; + for (const o of openings.filter((candidate) => standsOn(wall, candidate))) { + const s = (o.start[0] - wall.a[0]) * along[0] + (o.start[1] - wall.a[1]) * along[1]; + const s0 = o.axis[0] * along[0] + o.axis[1] * along[1] > 0 ? s : s - o.width; + if (s0 > length || s0 + o.width < 0) continue; + spans.push({ s0, s1: s0 + o.width, y0: o.sill - 0.01, y1: o.top + 0.01 }); + } + return spans; +} + +/** Sorted, de-duplicated break points between `lo` and `hi`, including both ends. */ +function breaks(values: number[], lo: number, hi: number): number[] { + const sorted = [lo, hi, ...values.filter((v) => v > lo + 0.005 && v < hi - 0.005)].sort((a, b) => a - b); + return sorted.filter((v, i) => i === 0 || v > sorted[i - 1] + 0.005); +} + +/** Floor quads over a polygon, one per grid cell whose centre lies inside it. */ +function gridCells(points: Vec2[], cell: number, isOff: (cx: number, cz: number) => boolean = () => false): { a: number; b: number }[] { + const xs = points.map((p) => p[0]); + const zs = points.map((p) => p[1]); + const [x0, z0] = [Math.min(...xs), Math.min(...zs)]; + const [columns, rows] = [Math.max(1, Math.ceil((Math.max(...xs) - x0) / cell)), Math.max(1, Math.ceil((Math.max(...zs) - z0) / cell))]; + const cells: { a: number; b: number }[] = []; + for (let i = 0; i < columns; i++) { + for (let j = 0; j < rows; j++) { + const [cx, cz] = [x0 + (i + 0.5) * cell, z0 + (j + 0.5) * cell]; + if (pointInPolygon([cx, cz], points) && !isOff(cx, cz)) cells.push({ a: x0 + i * cell, b: z0 + j * cell }); + } + } + return cells; +} + +/** + * Builds the light surface of a floor: a grid of `cell` metres on every room floor, and strips on the room side of every + * wall face, split at the cut height and left out where doors and windows are. + */ +export function buildLightSurface( + floor: Floor, + walls: Wall[], + wallBuckets: number[], + openings: OpeningInfo[], + cell: number, + holes: Vec2[][] = [], + roofUnder?: (x: number, z: number) => number | null, +): LightSurface { + const quads = quadCollector(); + const flatQuad = (a: number, b: number, y: number, roomIndex: number) => quads.add([a, y, b], [a, y, b + cell], [a + cell, y, b + cell], [a + cell, y, b], [0, 1, 0], roomIndex, -1); + + // room floors; no light over a floor opening, one looks through it + floor.rooms.forEach((room, ri) => { + if (room.points.length < 3) return; + for (const { a, b } of gridCells(room.points, cell, (cx, cz) => holes.some((h) => pointInPolygon([cx, cz], h)))) flatQuad(a, b, FLOOR_LIFT, ri); + }); + + // outside is one zone (index rooms.length) for all outdoor areas and the outer faces of the walls + const outside = floor.rooms.length; + const areas = floor.outdoor ?? []; + areas.forEach((area, ai) => { + if (area.points.length < 3 || outdoorStanding(area.type)) return; + const y = outdoorSurface(floor, area) + FLOOR_LIFT; + // the patches cut out of an area (a pool in a terrace) carry no light of this area + const holes = outdoorHoles(areas, ai); + for (const { a, b } of gridCells(area.points, cell, (cx, cz) => holes.some((h) => pointInPolygon([cx, cz], h)))) flatQuad(a, b, y, outside); + }); + + const cut = Math.min(floor.cut_height, floor.height); + walls.forEach((wall, wi) => { + // a sloping wall reaches its higher end here; its lit face is trimmed along the slope below + const slope = wall.heightEnd === undefined ? null : ([wall.height ?? floor.height, wall.heightEnd] as const); + const top = slope ? Math.max(...slope) : (wall.height ?? floor.height); + const cutAt = Math.min(cut, top - 0.02); + const [dx, dz] = [wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]; + const length = Math.hypot(dx, dz); + if (length < 0.05) return; + const along: Vec2 = [dx / length, dz / length]; + const leftNormal: Vec2 = [-along[1], along[0]]; + const bucket = wallBuckets[wi]; + const spans = openingSpans(wall, along, length, openings); + // cells break at the cut and at every sill, top and side of an opening, so the hole a window leaves in the lit face + // matches the window (a cell is lit or dark as a whole) + const heights = breaks([cutAt, (cutAt + top) / 2, ...spans.flatMap((g) => [g.y0 + 0.01, g.y1 - 0.01])], 0.02, top - 0.02); + const stations = breaks(spans.flatMap((g) => [g.s0, g.s1]), 0, length); + + for (const side of [1, -1] as const) { + const roomId = side > 0 ? wall.roomLeft : wall.roomRight; + // the outer face of an exterior wall belongs to the outside zone (facade lighting) + const ri = roomId ? floor.rooms.findIndex((r) => r.id === roomId) : wall.exterior ? outside : -1; + if (ri < 0) continue; + const faceDistance = (side > 0 ? wall.left : wall.right) + FACE_GAP; + const normal: Vec2 = [leftNormal[0] * side, leftNormal[1] * side]; + const point = (s: number, y: number) => [wall.a[0] + along[0] * s + normal[0] * faceDistance, y, wall.a[1] + along[1] * s + normal[1] * faceDistance]; + // under a roof slope the lit face ends where the wall does + const ceilingAt = (s: number) => { + const p = point(s, 0); + const roof = roofUnder?.(p[0], p[2]); + const sloped = slope ? slope[0] + ((slope[1] - slope[0]) * s) / length - 0.02 : Infinity; + return Math.min(sloped, roof == null ? Infinity : roof - 0.02); + }; + for (let p = 0; p + 1 < stations.length; p++) { + const span = stations[p + 1] - stations[p]; + const steps = Math.max(1, Math.ceil(span / cell)); + for (let k = 0; k < steps; k++) { + const s0 = stations[p] + (span / steps) * k; + const s1 = stations[p] + (span / steps) * (k + 1); + for (let h = 0; h + 1 < heights.length; h++) { + const [y0, y1] = [heights[h], heights[h + 1]]; + if (y1 - y0 < 0.01) continue; + const [sm, ym] = [(s0 + s1) / 2, (y0 + y1) / 2]; + if (spans.some((g) => sm > g.s0 && sm < g.s1 && ym > g.y0 && ym < g.y1)) continue; + const [topA, topB] = [Math.min(y1, ceilingAt(s0)), Math.min(y1, ceilingAt(s1))]; + if (topA <= y0 + 0.005 && topB <= y0 + 0.005) continue; + quads.add(point(s0, y0), point(s1, y0), point(s1, Math.max(y0, topB)), point(s0, Math.max(y0, topA)), [normal[0], 0, normal[1]], ri, y0 >= cut - 1e-6 ? bucket : LOWER_OFFSET + bucket); + } + } + } + } + }); + + // doors between two rooms let light through + const doors: LightSurface["doors"] = []; + for (const o of openings.filter((candidate) => candidate.opening.type === "door")) { + const wall = walls.find((w) => standsOn(w, o)); + if (!wall?.roomLeft || !wall.roomRight) continue; + const [a, b] = [floor.rooms.findIndex((r) => r.id === wall.roomLeft), floor.rooms.findIndex((r) => r.id === wall.roomRight)]; + if (a < 0 || b < 0) continue; + doors.push({ id: o.opening.id, a, b, x: o.start[0] + o.axis[0] * (o.width / 2), y: Math.min(1.1, o.top * 0.55), z: o.start[1] + o.axis[1] * (o.width / 2) }); + } + return quads.finish(doors); +} + diff --git a/frontend/src/viewer/live-energy.ts b/frontend/src/viewer/live-energy.ts new file mode 100644 index 0000000..ac728db --- /dev/null +++ b/frontend/src/viewer/live-energy.ts @@ -0,0 +1,298 @@ +/** + * NextFloor's energy layer: where the power goes, drawn as glowing particles flying in arcs between the + * devices (solar fields, inverter, battery, grid connection, house, consumers), and solar modules that sparkle + * with their production. + * + * Each arc joins two points of the plan (each on its floor, so it follows when the floors are pulled apart). The + * particles fly in the direction the power flows; more power means more and faster particles. A faint line shows + * the arc itself. A connection with a cable route follows its points instead of the arc (a cable shown as such is drawn + * stronger). + */ +import { AdditiveBlending, BufferGeometry, CanvasTexture, Color, Float32BufferAttribute, Group, Line, LineBasicMaterial, Points, PointsMaterial, Vector3, type Scene } from "three"; + +/** A point of the plan: floor (null = the ground / the roof above the top floor), plan x/z, height above that floor. */ +export interface PlanPoint { + floorId: string | null; + x: number; + y: number; + z: number; +} + +export interface EnergyArc { + key: string; + from: PlanPoint; + to: PlanPoint; + /** Power carried (W, > 0); the particles fly from `from` to `to`. */ + power: number; + /** Particle colour (r, g, b 0…255). */ + color: [number, number, number]; + /** Where the cable runs between `from` and `to` (the flow follows these points instead of an arc). */ + via?: PlanPoint[]; + /** The route is drawn as a visible cable. */ + cable?: boolean; +} + +/** A solar field's modules (corners in building coordinates) and how much it produces right now (0…1). */ +export interface SparkField { + floorId: string | null; + quads: [number, number, number][][]; + level: number; +} + +/** Where a floor is right now: the height of its floor (elevation plus how far it is pulled apart), that pull + * alone (for points given in building heights), and whether it shows. */ +export type FloorLift = (floorId: string | null) => { y: number; dy: number; visible: boolean }; + +const MAX_PER_ARC = 46; +/** Points of an arc's line: the arc's samples, or a route's points (at most 30 between its ends). */ +const LINE_POINTS = 33; +const SPARKS = 900; + +/** A soft round dot for point sprites (sparks, droplets). */ +export function dotTexture(): CanvasTexture { + const c = document.createElement("canvas"); + c.width = c.height = 32; + const g = c.getContext("2d")!; + const r = g.createRadialGradient(16, 16, 0, 16, 16, 16); + r.addColorStop(0, "rgba(255,255,255,1)"); + r.addColorStop(0.35, "rgba(255,255,255,0.7)"); + r.addColorStop(1, "rgba(255,255,255,0)"); + g.fillStyle = r; + g.fillRect(0, 0, 32, 32); + return new CanvasTexture(c); +} + +interface ArcView { + arc: EnergyArc; + line: Line; + points: Points; + phase: Float32Array; + count: number; + speed: number; + a: Vector3; + b: Vector3; + c: Vector3; + /** A routed arc: its corners in the world and how far along it each one lies; null for an arc. */ + path: Vector3[] | null; + along: number[]; +} + +export class EnergyLayer { + readonly group = new Group(); + private readonly scene: Scene; + private readonly lift: FloorLift; + private readonly tex = dotTexture(); + private arcs = new Map(); + private sparkFields: SparkField[] = []; + private readonly sparks: Points; + private readonly sparkBase = new Float32Array(SPARKS * 3); + private readonly sparkField = new Int16Array(SPARKS); + private readonly sparkPhase = new Float32Array(SPARKS); + private sparkCount = 0; + private last = 0; + + constructor(scene: Scene, lift: FloorLift) { + this.scene = scene; + this.lift = lift; + this.group.name = "live-energy"; + const g = new BufferGeometry(); + g.setAttribute("position", new Float32BufferAttribute(new Float32Array(SPARKS * 3), 3)); + g.setAttribute("color", new Float32BufferAttribute(new Float32Array(SPARKS * 3), 3)); + this.sparks = new Points(g, new PointsMaterial({ size: 0.4, map: this.tex, vertexColors: true, transparent: true, depthWrite: false, blending: AdditiveBlending })); + this.sparks.frustumCulled = false; + this.group.add(this.sparks); + scene.add(this.group); + } + + get active(): boolean { + return this.arcs.size > 0 || this.sparkCount > 0; + } + + setArcs(list: EnergyArc[]): void { + const keep = new Set(list.map((a) => a.key)); + for (const [key, v] of this.arcs) { + if (keep.has(key)) continue; + this.group.remove(v.line, v.points); + v.line.geometry.dispose(); + (v.line.material as LineBasicMaterial).dispose(); + v.points.geometry.dispose(); + (v.points.material as PointsMaterial).dispose(); + this.arcs.delete(key); + } + for (const arc of list) { + let v = this.arcs.get(arc.key); + if (!v) { + const lg = new BufferGeometry(); + lg.setAttribute("position", new Float32BufferAttribute(new Float32Array(LINE_POINTS * 3), 3)); + const line = new Line(lg, new LineBasicMaterial({ transparent: true, opacity: 0.4, depthWrite: false, blending: AdditiveBlending })); + const pg = new BufferGeometry(); + pg.setAttribute("position", new Float32BufferAttribute(new Float32Array(MAX_PER_ARC * 3), 3)); + const points = new Points(pg, new PointsMaterial({ size: 0.55, map: this.tex, transparent: true, depthWrite: false, blending: AdditiveBlending })); + line.frustumCulled = points.frustumCulled = false; + const phase = new Float32Array(MAX_PER_ARC); + for (let i = 0; i < MAX_PER_ARC; i++) phase[i] = Math.random(); + v = { arc, line, points, phase, count: 0, speed: 0, a: new Vector3(), b: new Vector3(), c: new Vector3(), path: null, along: [] }; + this.arcs.set(arc.key, v); + this.group.add(line, points); + } + v.arc = arc; + const col = new Color(arc.color[0] / 255, arc.color[1] / 255, arc.color[2] / 255); + (v.line.material as LineBasicMaterial).color.copy(col); + (v.line.material as LineBasicMaterial).opacity = arc.via?.length && arc.cable ? 0.9 : 0.4; + v.path = arc.via?.length ? Array.from({ length: arc.via.length + 2 }, () => new Vector3()) : null; + (v.points.material as PointsMaterial).color.copy(col); + // more power: more particles, a bit faster (a kettle and a heat pump look different, a 10 kW car still fits) + // a cable without power (a car plugged in that does not charge) shows the cable alone + v.count = arc.power <= 0 ? 0 : Math.max(3, Math.min(MAX_PER_ARC, Math.round(3 + Math.sqrt(arc.power) / 2.2))); + v.speed = 0.18 + Math.min(0.5, Math.log10(1 + arc.power) * 0.1); + v.points.geometry.setDrawRange(0, v.count); + } + this.place(); + } + + setSparks(fields: SparkField[]): void { + this.sparkFields = fields; + // spread the sparks over the modules in proportion to each field's production + const total = fields.reduce((s, f) => s + f.quads.length * f.level, 0); + let n = 0; + if (total > 0) { + fields.forEach((f, fi) => { + if (f.level <= 0) return; + const share = Math.round((SPARKS * f.quads.length * f.level) / Math.max(total, fields.reduce((s, x) => s + x.quads.length, 0))); + for (let k = 0; k < share && n < SPARKS; k++, n++) { + const q = f.quads[Math.floor(Math.random() * f.quads.length)]; + const u = Math.random(), w = Math.random(); + // a point on the module: bilinear between its corners, a hand above the surface + for (let i = 0; i < 3; i++) { + const top = q[0][i] + (q[1][i] - q[0][i]) * u; + const bot = q[3][i] + (q[2][i] - q[3][i]) * u; + this.sparkBase[n * 3 + i] = top + (bot - top) * w + (i === 1 ? 0.12 : 0); + } + this.sparkField[n] = fi; + this.sparkPhase[n] = Math.random() * Math.PI * 2; + } + }); + } + this.sparkCount = n; + this.sparks.geometry.setDrawRange(0, n); + this.sparks.visible = n > 0; + } + + /** World position of a plan point right now. */ + private world(p: PlanPoint, out: Vector3): boolean { + const l = this.lift(p.floorId); + out.set(p.x, l.y + p.y, p.z); + return l.visible; + } + + /** The arcs' start, end and bend for where the floors are now. */ + private place(): void { + for (const v of this.arcs.values()) { + if (v.path) { + this.placeRoute(v, v.path); + continue; + } + const va = this.world(v.arc.from, v.a); + const vb = this.world(v.arc.to, v.b); + const len = v.a.distanceTo(v.b); + v.c.copy(v.a).add(v.b).multiplyScalar(0.5); + v.c.y = Math.max(v.a.y, v.b.y) + 0.6 + len * 0.22; + const show = va && vb; + v.line.visible = v.points.visible = show; + const pos = v.line.geometry.getAttribute("position") as Float32BufferAttribute; + for (let i = 0; i < LINE_POINTS; i++) { + const t = i / (LINE_POINTS - 1); + pos.setXYZ(i, ...this.bezier(v, t)); + } + v.line.geometry.setDrawRange(0, LINE_POINTS); + pos.needsUpdate = true; + } + } + + /** A routed connection: from its start through the route's points to its end; hidden while any of them is on a hidden floor. */ + private placeRoute(v: ArcView, path: Vector3[]): void { + const plan = [v.arc.from, ...(v.arc.via ?? []), v.arc.to]; + let show = true; + plan.forEach((p, i) => (show = this.world(p, path[i]) && show)); + v.line.visible = v.points.visible = show; + v.along = [0]; + for (let i = 1; i < path.length; i++) v.along.push(v.along[i - 1] + path[i].distanceTo(path[i - 1])); + const pos = v.line.geometry.getAttribute("position") as Float32BufferAttribute; + path.forEach((p, i) => pos.setXYZ(i, p.x, p.y, p.z)); + v.line.geometry.setDrawRange(0, path.length); + pos.needsUpdate = true; + } + + /** Where a particle `t` (0…1) of the way along an arc or a route is. */ + private at(v: ArcView, t: number): [number, number, number] { + if (!v.path) return this.bezier(v, t); + const total = v.along[v.along.length - 1] || 1; + const s = t * total; + let i = 1; + while (i < v.along.length - 1 && v.along[i] < s) i++; + const [p, q] = [v.path[i - 1], v.path[i]]; + const span = v.along[i] - v.along[i - 1] || 1; + const k = Math.max(0, Math.min(1, (s - v.along[i - 1]) / span)); + return [p.x + (q.x - p.x) * k, p.y + (q.y - p.y) * k, p.z + (q.z - p.z) * k]; + } + + private bezier(v: ArcView, t: number): [number, number, number] { + const u = 1 - t; + return [ + u * u * v.a.x + 2 * u * t * v.c.x + t * t * v.b.x, + u * u * v.a.y + 2 * u * t * v.c.y + t * t * v.b.y, + u * u * v.a.z + 2 * u * t * v.c.z + t * t * v.b.z, + ]; + } + + /** One frame. True while anything moves. */ + step(now: number): boolean { + if (!this.active || !this.group.visible) { + this.last = 0; + return false; + } + const dt = this.last ? Math.min(0.1, (now - this.last) / 1000) : 0; + this.last = now; + this.place(); + for (const v of this.arcs.values()) { + if (!v.points.visible) continue; + const pos = v.points.geometry.getAttribute("position") as Float32BufferAttribute; + for (let i = 0; i < v.count; i++) { + v.phase[i] = (v.phase[i] + v.speed * dt) % 1; + pos.setXYZ(i, ...this.at(v, v.phase[i])); + } + pos.needsUpdate = true; + } + if (this.sparkCount) { + const pos = this.sparks.geometry.getAttribute("position") as Float32BufferAttribute; + const col = this.sparks.geometry.getAttribute("color") as Float32BufferAttribute; + const t = now / 1000; + for (let i = 0; i < this.sparkCount; i++) { + const f = this.sparkFields[this.sparkField[i]]; + const l = this.lift(f?.floorId ?? null); + // sparks of a hidden floor's field are put far below the ground (dark points would still show) + pos.setXYZ(i, this.sparkBase[i * 3], l.visible ? this.sparkBase[i * 3 + 1] + l.dy : -1000, this.sparkBase[i * 3 + 2]); + // each spark twinkles on its own beat, brighter on a strong field + const tw = Math.max(0, Math.sin(t * 2.4 + this.sparkPhase[i] * 3)) ** 6; + // a field whose floor is hidden (another floor opened) goes dark + const b = l.visible ? (0.15 + 0.85 * tw) * (0.4 + 0.6 * (f?.level ?? 0)) : 0; + col.setXYZ(i, b, b * 0.86, b * 0.35); + } + pos.needsUpdate = true; + col.needsUpdate = true; + } + return true; + } + + setVisible(on: boolean): void { + this.group.visible = on; + } + + dispose(): void { + this.setArcs([]); + this.sparks.geometry.dispose(); + (this.sparks.material as PointsMaterial).dispose(); + this.tex.dispose(); + this.scene.remove(this.group); + } +} diff --git a/frontend/src/viewer/live-map.ts b/frontend/src/viewer/live-map.ts new file mode 100644 index 0000000..eda76db --- /dev/null +++ b/frontend/src/viewer/live-map.ts @@ -0,0 +1,108 @@ +/** + * The real map under the plan: map tiles drawn into one canvas and laid on the ground as a dimmed plane, turned by the plan's north. + * The tiles come from a tile server through the browser (plain image requests); nothing is loaded while the map is off. + */ +import { CanvasTexture, DoubleSide, Mesh, MeshBasicMaterial, PlaneGeometry, SRGBColorSpace, type Scene } from "three"; +import { mapLook, mapShown, mapTiles, planOfMap, templateOf, tileUrl, type MapTile } from "../map-geo.ts"; +import { tileBlob } from "../tiles.ts"; +import type { MapSettings } from "../model.ts"; + +const TILE_PX = 256; +const DEG = Math.PI / 180; + +export class MapLayer { + private readonly mesh = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ transparent: true, depthWrite: false, side: DoubleSide })); + private canvas: HTMLCanvasElement | null = null; + private texture: CanvasTexture | null = null; + /** What the loaded tiles are for: place, zoom and tile address. */ + private key = ""; + /** A newer set of tiles makes the pictures of an older one that still arrive be dropped. */ + private generation = 0; + /** The centre of the tile grid in the map frame (metres east / north of the anchor). */ + private centre: [number, number] = [0, 0]; + /** Called when more tiles have arrived, so the view draws again. */ + onChange: () => void = () => {}; + + private readonly scene: Scene; + + constructor(scene: Scene) { + this.scene = scene; + this.mesh.rotation.order = "YXZ"; + this.mesh.renderOrder = -2; + this.mesh.visible = false; + this.mesh.name = "live-map"; + scene.add(this.mesh); + } + + /** Shows, moves or hides the map: `y` is the height of the ground, `north` the plan's north in degrees, `brightness` dims the tiles. */ + set(map: MapSettings | null | undefined, north: number, y: number, brightness = 1): void { + if (!mapShown(map)) { + this.mesh.visible = false; + this.generation++; + this.key = ""; + return; + } + const look = mapLook(map); + const template = templateOf(map); + const key = `${map.lat},${map.lon},${look.zoom},${template}`; + if (key !== this.key) this.load(key, map, look.zoom, template); + const [east, northM] = this.centre; + const [x, z] = planOfMap(east, northM, north, look); + this.mesh.position.set(x, y, z); + // the texture's right is east and its top is north; a plan turned by `north` clockwise turns the plane the other way round about +y + this.mesh.rotation.set(-Math.PI / 2, -north * DEG, 0); + const material = this.mesh.material as MeshBasicMaterial; + material.opacity = look.opacity; + // on the dark themes the pale tiles are dimmed as well, so the neon plan stays the brightest thing + material.color.setScalar(brightness); + this.mesh.visible = this.canvas !== null; + } + + private load(key: string, map: MapSettings, zoom: number, template: string): void { + this.key = key; + const generation = ++this.generation; + const tiles = mapTiles(map.lat, map.lon, zoom); + if (!tiles.length) return; + const size = tiles[0].size; + const minEast = Math.min(...tiles.map((t) => t.east)); + const maxNorth = Math.max(...tiles.map((t) => t.north)); + const columns = Math.round((Math.max(...tiles.map((t) => t.east)) - minEast) / size) + 1; + const rows = Math.round((maxNorth - Math.min(...tiles.map((t) => t.north))) / size) + 1; + const canvas = document.createElement("canvas"); + canvas.width = columns * TILE_PX; + canvas.height = rows * TILE_PX; + this.canvas = canvas; + this.texture?.dispose(); + this.texture = new CanvasTexture(canvas); + this.texture.colorSpace = SRGBColorSpace; + this.texture.anisotropy = 4; + const material = this.mesh.material as MeshBasicMaterial; + material.map = this.texture; + material.needsUpdate = true; + this.mesh.geometry.dispose(); + this.mesh.geometry = new PlaneGeometry(columns * size, rows * size); + this.centre = [minEast + (columns * size) / 2, maxNorth - (rows * size) / 2]; + const ctx = canvas.getContext("2d"); + if (!ctx) return; + for (const tile of tiles) this.draw(ctx, tile, template, generation, Math.round((tile.east - minEast) / size), Math.round((maxNorth - tile.north) / size)); + } + + private draw(ctx: CanvasRenderingContext2D, tile: MapTile, template: string, generation: number, col: number, row: number): void { + void tileBlob(tileUrl(template, tile)) + .then((blob) => (blob ? createImageBitmap(blob) : null)) + .then((bitmap) => { + if (!bitmap || generation !== this.generation) return; + ctx.drawImage(bitmap, col * TILE_PX, row * TILE_PX, TILE_PX, TILE_PX); + if (this.texture) this.texture.needsUpdate = true; + this.onChange(); + }); + } + + dispose(): void { + this.generation++; + this.scene.remove(this.mesh); + this.mesh.geometry.dispose(); + (this.mesh.material as MeshBasicMaterial).dispose(); + this.texture?.dispose(); + } +} diff --git a/frontend/src/viewer/live-pictures.ts b/frontend/src/viewer/live-pictures.ts new file mode 100644 index 0000000..a706578 --- /dev/null +++ b/frontend/src/viewer/live-pictures.ts @@ -0,0 +1,164 @@ +/** + * Picture frames: an own photo (a stored picture, a URL, an image or camera entity) shown in a frame's picture part, with an + * adjustable white mat around it. The picture is cropped to fill the opening, or fitted whole on the mat. + */ +import { CanvasTexture, Group, Mesh, MeshBasicMaterial, PlaneGeometry, SRGBColorSpace, type Scene } from "three"; +import type { FloorLift } from "./live-energy.ts"; + +export interface LivePicture { + id: string; + floorId: string; + x: number; + z: number; + rotation: number; + /** The picture part in the furniture's frame (x across, y up from the floor, z its front face). */ + rect: { x0: number; x1: number; y0: number; y1: number; z: number }; + url: string; + /** Mat around the picture in % of the shorter side (0 = none). */ + border: number; + /** "contain": the whole picture on the mat; "cover" (default): it fills the opening. */ + fit: "cover" | "contain"; +} + +const DEG = Math.PI / 180; +const MAT = "#f4f1ea"; + +interface PictureView { + p: LivePicture; + sig: string; + mesh: Mesh; + canvas: HTMLCanvasElement; + texture: CanvasTexture; + image: HTMLImageElement | null; +} + +export class PictureLayer { + readonly group = new Group(); + private readonly scene: Scene; + private readonly lift: FloorLift; + private views = new Map(); + /** Called when a picture has loaded (the host renders a frame). */ + onChange: (() => void) | null = null; + + constructor(scene: Scene, lift: FloorLift) { + this.scene = scene; + this.lift = lift; + this.group.name = "live-pictures"; + scene.add(this.group); + } + + set(list: LivePicture[]): void { + const keep = new Set(list.map((p) => p.id)); + for (const [id, v] of this.views) if (!keep.has(id)) this.drop(id, v); + for (const p of list) { + let v = this.views.get(p.id); + if (!v) { + const canvas = document.createElement("canvas"); + const texture = new CanvasTexture(canvas); + texture.colorSpace = SRGBColorSpace; + const mesh = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ map: texture, toneMapped: false })); + mesh.renderOrder = 5; + this.group.add(mesh); + v = { p, sig: "", mesh, canvas, texture, image: null }; + this.views.set(p.id, v); + } + const urlChanged = v.p.url !== p.url || !v.sig; + v.p = p; + const w = p.rect.x1 - p.rect.x0; + const h = p.rect.y1 - p.rect.y0; + const sig = [p.url, p.border, p.fit, w.toFixed(3), h.toFixed(3)].join("|"); + if (sig !== v.sig) { + v.sig = sig; + if (urlChanged) this.load(v); + this.draw(v); + } + this.place(v); + } + } + + private load(v: PictureView): void { + v.image = null; + const url = v.p.url; + const img = new Image(); + img.crossOrigin = "anonymous"; + img.onload = () => { + if (v.p.url !== url || !this.views.has(v.p.id)) return; + v.image = img; + this.draw(v); + this.onChange?.(); + }; + img.src = url; + } + + /** The mat, and the picture cropped (or fitted) into the opening the mat leaves. */ + private draw(v: PictureView): void { + const p = v.p; + const w = Math.max(0.01, p.rect.x1 - p.rect.x0); + const h = Math.max(0.01, p.rect.y1 - p.rect.y0); + // about 600 px on the longer side: sharp enough on a wall, light on old tablets + const k = 600 / Math.max(w, h); + const W = (v.canvas.width = Math.max(16, Math.round(w * k))); + const H = (v.canvas.height = Math.max(16, Math.round(h * k))); + const g = v.canvas.getContext("2d")!; + g.fillStyle = p.border > 0 ? MAT : "#20242c"; + g.fillRect(0, 0, W, H); + const m = Math.round((Math.min(W, H) * Math.min(40, Math.max(0, p.border))) / 100); + const [ox, oy, ow, oh] = [m, m, W - 2 * m, H - 2 * m]; + if (v.image && ow > 4 && oh > 4) { + const iw = v.image.naturalWidth || 1; + const ih = v.image.naturalHeight || 1; + if (p.fit === "contain") { + const s = Math.min(ow / iw, oh / ih); + g.drawImage(v.image, ox + (ow - iw * s) / 2, oy + (oh - ih * s) / 2, iw * s, ih * s); + } else { + const s = Math.max(ow / iw, oh / ih); + const sw = ow / s; + const sh = oh / s; + g.drawImage(v.image, (iw - sw) / 2, (ih - sh) / 2, sw, sh, ox, oy, ow, oh); + } + if (m > 0) { + // a thin shadow line where the mat's bevel would be + g.strokeStyle = "rgba(0,0,0,0.25)"; + g.lineWidth = Math.max(1, m * 0.04); + g.strokeRect(ox, oy, ow, oh); + } + } else if (ow > 4 && oh > 4) { + g.fillStyle = "#3a4250"; + g.fillRect(ox, oy, ow, oh); + } + v.texture.needsUpdate = true; + } + + /** Puts the picture onto the front face of the frame's picture part. */ + private place(v: PictureView): void { + const p = v.p; + const r = p.rect; + const a = p.rotation * DEG; + const l = this.lift(p.floorId); + const cx = (r.x0 + r.x1) / 2; + const lz = r.z + 0.004; + v.mesh.position.set(p.x + cx * Math.cos(a) - lz * Math.sin(a), l.y + (r.y0 + r.y1) / 2, p.z + cx * Math.sin(a) + lz * Math.cos(a)); + v.mesh.rotation.set(0, -a, 0); + v.mesh.scale.set(r.x1 - r.x0, r.y1 - r.y0, 1); + v.mesh.visible = l.visible; + } + + /** Follows the floors as they lift and hide; pictures never animate on their own. */ + step(): boolean { + for (const v of this.views.values()) this.place(v); + return false; + } + + private drop(id: string, v: PictureView): void { + this.group.remove(v.mesh); + v.mesh.geometry.dispose(); + (v.mesh.material as MeshBasicMaterial).dispose(); + v.texture.dispose(); + this.views.delete(id); + } + + dispose(): void { + for (const [id, v] of this.views) this.drop(id, v); + this.scene.remove(this.group); + } +} diff --git a/frontend/src/viewer/live-screens.ts b/frontend/src/viewer/live-screens.ts new file mode 100644 index 0000000..87d2974 --- /dev/null +++ b/frontend/src/viewer/live-screens.ts @@ -0,0 +1,218 @@ +/** + * NextFloor's TV screens: a TV or monitor that plays shows a picture of what runs – the cover art, the title and + * the artist or series, and the app – drawn onto its screen, on a gradient in the app's colour. Behind it an + * ambilight glows on the wall in the same colour, breathing slowly while it plays. + */ +import { AdditiveBlending, CanvasTexture, Color, DoubleSide, Group, Mesh, MeshBasicMaterial, PlaneGeometry, SRGBColorSpace, type Scene } from "three"; +import type { FloorLift } from "./live-energy.ts"; + +export interface LiveScreen { + id: string; + floorId: string; + /** Where the furniture stands and how it is turned (degrees), mirrored or not. */ + x: number; + z: number; + rotation: number; + /** The screen's rectangle in the furniture's frame (x across, y up from the floor, z the front face). */ + rect: { x0: number; x1: number; y0: number; y1: number; z: number }; + color: [number, number, number]; + title: string; + subtitle: string; + app: string | null; + picture: string | null; + playing: boolean; + /** Strength of the glow on the wall behind the screen: 1 is the usual, 0 switches it off. */ + ambilight?: number; +} + +const DEG = Math.PI / 180; + +interface ScreenView { + s: LiveScreen; + sig: string; + screen: Mesh; + glow: Mesh; + canvas: HTMLCanvasElement; + texture: CanvasTexture; + image: HTMLImageElement | null; +} + +function glowTexture(): CanvasTexture { + const c = document.createElement("canvas"); + c.width = c.height = 64; + const g = c.getContext("2d")!; + const r = g.createRadialGradient(32, 32, 4, 32, 32, 32); + r.addColorStop(0, "rgba(255,255,255,0.9)"); + r.addColorStop(0.5, "rgba(255,255,255,0.35)"); + r.addColorStop(1, "rgba(255,255,255,0)"); + g.fillStyle = r; + g.fillRect(0, 0, 64, 64); + return new CanvasTexture(c); +} + +export class ScreenLayer { + readonly group = new Group(); + private readonly scene: Scene; + private readonly lift: FloorLift; + private readonly glowTex = glowTexture(); + private views = new Map(); + /** Called when a picture has loaded (the host renders a frame). */ + onChange: (() => void) | null = null; + + constructor(scene: Scene, lift: FloorLift) { + this.scene = scene; + this.lift = lift; + this.group.name = "live-screens"; + scene.add(this.group); + } + + get active(): boolean { + return [...this.views.values()].some((v) => v.s.playing); + } + + set(list: LiveScreen[]): void { + const keep = new Set(list.map((s) => s.id)); + for (const [id, v] of this.views) if (!keep.has(id)) this.drop(id, v); + for (const s of list) { + let v = this.views.get(s.id); + if (!v) { + const canvas = document.createElement("canvas"); + canvas.width = 512; + canvas.height = 288; + const texture = new CanvasTexture(canvas); + texture.colorSpace = SRGBColorSpace; + const screen = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ map: texture, transparent: true, toneMapped: false })); + screen.renderOrder = 6; + const glow = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ map: this.glowTex, transparent: true, depthWrite: false, blending: AdditiveBlending, side: DoubleSide })); + glow.renderOrder = 2; + this.group.add(screen, glow); + v = { s, sig: "", screen, glow, canvas, texture, image: null }; + this.views.set(s.id, v); + } + v.s = s; + const sig = [s.title, s.subtitle, s.app, s.picture, s.color.join(","), s.playing].join("|"); + if (sig !== v.sig) { + const pictureChanged = v.sig.split("|")[3] !== (s.picture ?? ""); + v.sig = sig; + if (pictureChanged) this.loadPicture(v); + this.draw(v); + } + this.place(v); + } + } + + private loadPicture(v: ScreenView): void { + v.image = null; + const url = v.s.picture; + if (!url) return; + const img = new Image(); + img.crossOrigin = "anonymous"; + img.onload = () => { + if (v.s.picture !== url || !this.views.has(v.s.id)) return; + v.image = img; + this.draw(v); + this.onChange?.(); + }; + img.src = url; + } + + /** The screen's picture: a gradient in the app's colour, the cover, title, artist and the app's name. */ + private draw(v: ScreenView): void { + const s = v.s; + const g = v.canvas.getContext("2d")!; + const W = v.canvas.width, H = v.canvas.height; + const [r, gr, b] = s.color; + const bg = g.createLinearGradient(0, 0, W, H); + bg.addColorStop(0, `rgb(${Math.round(r * 0.35)},${Math.round(gr * 0.35)},${Math.round(b * 0.35)})`); + bg.addColorStop(1, "rgb(6,9,18)"); + g.fillStyle = bg; + g.fillRect(0, 0, W, H); + const pad = 22; + let tx = pad; + if (v.image) { + // the cover, square, on the left, with a soft shadow in the app's colour + const size = H - pad * 2 - 30; + g.save(); + g.shadowColor = `rgba(${r},${gr},${b},0.7)`; + g.shadowBlur = 24; + const iw = v.image.naturalWidth || 1, ih = v.image.naturalHeight || 1; + const k = Math.max(size / iw, size / ih); + const sw = size / k, sh = size / k; + g.drawImage(v.image, (iw - sw) / 2, (ih - sh) / 2, sw, sh, pad, pad, size, size); + g.restore(); + tx = pad * 2 + size; + } + g.fillStyle = "#ffffff"; + g.font = "600 34px Figtree, Roboto, sans-serif"; + this.text(g, s.title || s.app || "", tx, H / 2 - 18, W - tx - pad); + g.fillStyle = "rgba(230,240,255,0.75)"; + g.font = "26px Figtree, Roboto, sans-serif"; + this.text(g, s.subtitle, tx, H / 2 + 22, W - tx - pad); + // the app's name in its colour, and a thin bar in the colour along the bottom + if (s.app) { + g.fillStyle = `rgb(${r},${gr},${b})`; + g.font = "700 22px Figtree, Roboto, sans-serif"; + this.text(g, (s.playing ? "▶ " : "❚❚ ") + s.app, tx, H - pad - 14, W - tx - pad); + } + g.fillStyle = `rgba(${r},${gr},${b},0.9)`; + g.fillRect(0, H - 6, W * (s.playing ? 1 : 0.4), 6); + v.texture.needsUpdate = true; + } + + private text(g: CanvasRenderingContext2D, text: string, x: number, y: number, max: number): void { + let t = text; + while (t.length > 1 && g.measureText(t).width > max) t = t.slice(0, -2); + g.fillText(t === text ? t : `${t}…`, x, y); + } + + /** Puts the picture on the screen's front and the glow on the wall behind the TV. */ + private place(v: ScreenView): void { + const s = v.s; + const r = s.rect; + const a = s.rotation * DEG; + const l = this.lift(s.floorId); + const cx = (r.x0 + r.x1) / 2; + const at = (lx: number, lz: number): [number, number] => [s.x + lx * Math.cos(a) - lz * Math.sin(a), s.z + lx * Math.sin(a) + lz * Math.cos(a)]; + const w = r.x1 - r.x0, h = r.y1 - r.y0; + const [sx, sz] = at(cx, r.z + 0.012); + v.screen.position.set(sx, l.y + (r.y0 + r.y1) / 2, sz); + v.screen.rotation.set(0, -a, 0); + v.screen.scale.set(w, h, 1); + // the glow sits a little behind the screen, larger than it + const [gx, gz] = at(cx, r.z - 0.18); + v.glow.position.set(gx, l.y + (r.y0 + r.y1) / 2, gz); + v.glow.rotation.set(0, -a, 0); + v.glow.scale.set(w * 2.4, h * 2.6, 1); + (v.glow.material as MeshBasicMaterial).color = new Color(s.color[0] / 255, s.color[1] / 255, s.color[2] / 255); + v.screen.visible = l.visible; + v.glow.visible = l.visible && (s.ambilight ?? 1) > 0; + } + + step(now: number): boolean { + let moving = false; + for (const v of this.views.values()) { + this.place(v); + // the ambilight breathes while it plays, and rests dim while paused + const m = v.glow.material as MeshBasicMaterial; + m.opacity = (v.s.playing ? 0.55 + 0.25 * Math.sin(now / 900 + v.s.x) : 0.25) * Math.min(1.5, v.s.ambilight ?? 1); + moving ||= v.s.playing; + } + return moving; + } + + private drop(id: string, v: ScreenView): void { + this.group.remove(v.screen, v.glow); + v.screen.geometry.dispose(); + (v.screen.material as MeshBasicMaterial).dispose(); + v.texture.dispose(); + v.glow.geometry.dispose(); + (v.glow.material as MeshBasicMaterial).dispose(); + this.views.delete(id); + } + + dispose(): void { + for (const [id, v] of this.views) this.drop(id, v); + this.glowTex.dispose(); + this.scene.remove(this.group); + } +} diff --git a/frontend/src/viewer/live-sound.ts b/frontend/src/viewer/live-sound.ts new file mode 100644 index 0000000..62e97b3 --- /dev/null +++ b/frontend/src/viewer/live-sound.ts @@ -0,0 +1,125 @@ +/** + * NextFloor's sound layer: rings of sound spreading from every speaker that plays (in the colour of the app that + * plays, wider and brighter the louder it is), and glowing threads between speakers that play together + * (multiroom groups). + */ +import { AdditiveBlending, BufferGeometry, Color, DoubleSide, Float32BufferAttribute, Group, Line, LineBasicMaterial, Mesh, MeshBasicMaterial, RingGeometry, type Scene } from "three"; +import type { FloorLift, PlanPoint } from "./live-energy.ts"; + +export interface SoundSpot { + id: string; + at: PlanPoint; + /** Ring colour (r, g, b 0…255). */ + color: [number, number, number]; + /** Volume 0…1. */ + level: number; + /** Size of the rings (1 = as usual; a small speaker can have smaller ones). */ + size?: number; +} + +const RINGS = 3; + +interface SpotView { + spot: SoundSpot; + rings: Mesh[]; +} + +export class SoundLayer { + readonly group = new Group(); + private readonly scene: Scene; + private readonly lift: FloorLift; + private readonly ringGeo = new RingGeometry(0.92, 1, 48); + private spots = new Map(); + private links: { a: PlanPoint; b: PlanPoint; line: Line }[] = []; + + constructor(scene: Scene, lift: FloorLift) { + this.scene = scene; + this.lift = lift; + this.group.name = "live-sound"; + scene.add(this.group); + } + + get active(): boolean { + return this.spots.size > 0; + } + + set(spots: SoundSpot[], groups: [PlanPoint, PlanPoint][]): void { + const keep = new Set(spots.map((s) => s.id)); + for (const [id, v] of this.spots) { + if (keep.has(id)) continue; + for (const r of v.rings) { + this.group.remove(r); + (r.material as MeshBasicMaterial).dispose(); + } + this.spots.delete(id); + } + for (const spot of spots) { + let v = this.spots.get(spot.id); + if (!v) { + const rings = Array.from({ length: RINGS }, () => { + const m = new Mesh(this.ringGeo, new MeshBasicMaterial({ transparent: true, opacity: 0, depthWrite: false, blending: AdditiveBlending, side: DoubleSide })); + m.rotation.x = -Math.PI / 2; + m.frustumCulled = false; + this.group.add(m); + return m; + }); + v = { spot, rings }; + this.spots.set(spot.id, v); + } + v.spot = spot; + const c = new Color(spot.color[0] / 255, spot.color[1] / 255, spot.color[2] / 255); + for (const r of v.rings) (r.material as MeshBasicMaterial).color.copy(c); + } + for (const l of this.links) { + this.group.remove(l.line); + l.line.geometry.dispose(); + (l.line.material as LineBasicMaterial).dispose(); + } + this.links = groups.map(([a, b]) => { + const g = new BufferGeometry(); + g.setAttribute("position", new Float32BufferAttribute(new Float32Array(17 * 3), 3)); + const line = new Line(g, new LineBasicMaterial({ color: 0xc084fc, transparent: true, opacity: 0.55, depthWrite: false, blending: AdditiveBlending })); + line.frustumCulled = false; + this.group.add(line); + return { a, b, line }; + }); + } + + step(now: number): boolean { + if (!this.spots.size && !this.links.length) return false; + const t = now / 1000; + for (const v of this.spots.values()) { + const l = this.lift(v.spot.at.floorId); + const reach = 0.9 + 1.6 * v.spot.level; + v.rings.forEach((r, i) => { + // each ring grows from the speaker and fades, the next one follows a third of a beat later + const k = (t * 0.55 + i / RINGS) % 1; + r.visible = l.visible; + r.position.set(v.spot.at.x, l.y + v.spot.at.y, v.spot.at.z); + r.scale.setScalar((0.25 + k * reach) * (v.spot.size ?? 1)); + (r.material as MeshBasicMaterial).opacity = (1 - k) * (0.35 + 0.5 * v.spot.level); + }); + } + for (const link of this.links) { + const la = this.lift(link.a.floorId), lb = this.lift(link.b.floorId); + link.line.visible = la.visible && lb.visible; + const pos = link.line.geometry.getAttribute("position") as Float32BufferAttribute; + const ay = la.y + link.a.y, by = lb.y + link.b.y; + const dist = Math.hypot(link.a.x - link.b.x, link.a.z - link.b.z); + for (let i = 0; i <= 16; i++) { + const s = i / 16; + // a soft sag between the two, with a slow shimmer along it + const lift = Math.sin(Math.PI * s) * (0.3 + dist * 0.12) + Math.sin(t * 3 + s * 12) * 0.03; + pos.setXYZ(i, link.a.x + (link.b.x - link.a.x) * s, ay + (by - ay) * s + lift, link.a.z + (link.b.z - link.a.z) * s); + } + pos.needsUpdate = true; + } + return true; + } + + dispose(): void { + this.set([], []); + this.ringGeo.dispose(); + this.scene.remove(this.group); + } +} diff --git a/frontend/src/viewer/live-water.test.ts b/frontend/src/viewer/live-water.test.ts new file mode 100644 index 0000000..8c5309d --- /dev/null +++ b/frontend/src/viewer/live-water.test.ts @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { DROPS, dropAt, JETS } from "./live-water.ts"; + +test("droplets fly out on arcs within the reach, start at the nozzle and land on its height", () => { + for (let i = 0; i < DROPS; i++) { + for (const t of [0, 0.4, 1.3, 7.9]) { + const [x, y, z] = dropAt(i, t, 3); + assert.ok(Math.hypot(x, z) <= 3 + 1e-9, "inside the reach"); + assert.ok(y >= 0 && y <= 1 + 1e-9, "the arc peaks at a third of the reach"); + } + } + // a short reach keeps the arc low, a long one at most 1.2 m + assert.ok(Math.max(...Array.from({ length: 50 }, (_, k) => dropAt(0, k / 50 / 0.7, 0.9)[1])) <= 0.3 + 1e-9); + assert.ok(Math.max(...Array.from({ length: 50 }, (_, k) => dropAt(0, k / 50 / 0.7, 12)[1])) <= 1.2 + 1e-9); +}); + +test("the jets spread all round the sprinkler, each a stream of droplets along one direction", () => { + const angles = Array.from({ length: DROPS }, (_, i) => { + const [x, , z] = dropAt(i, 0.5, 3); + return Math.atan2(z, x); + }); + const quadrants = new Set(angles.map((a) => Math.floor(((a + Math.PI) / (Math.PI / 2)) % 4))); + assert.equal(quadrants.size, 4); + // the droplets of one jet point the same way (within a small spread) + const jet0 = angles.filter((_, i) => i % JETS === 0); + assert.ok(Math.max(...jet0) - Math.min(...jet0) < 0.1); +}); diff --git a/frontend/src/viewer/live-water.ts b/frontend/src/viewer/live-water.ts new file mode 100644 index 0000000..0917950 --- /dev/null +++ b/frontend/src/viewer/live-water.ts @@ -0,0 +1,106 @@ +/** + * NextFloor's water layer: lawn sprinklers that water while their valve or switch is on throw droplets in arcs around + * them, turning slowly, as far as the sprinkler reaches. Points only, so a wall tablet keeps up. + */ +import { BufferGeometry, Float32BufferAttribute, Group, Points, PointsMaterial, type Scene } from "three"; +import { dotTexture, type FloorLift, type PlanPoint } from "./live-energy.ts"; + +export interface SpraySpot { + id: string; + at: PlanPoint; + /** How far the water reaches (m). */ + reach: number; +} + +/** A sprinkler throws its water in a few jets; each jet is a stream of droplets along its arc. */ +export const JETS = 6; +const PER_JET = 24; +/** Droplets per sprinkler: enough to read as water, few enough for old tablets. */ +export const DROPS = JETS * PER_JET; + +interface SprayView { + spot: SpraySpot; + points: Points; +} + +/** + * Where droplet `i` of a sprinkler is at time `t` (seconds), relative to the nozzle: droplets follow each other along their + * jet's arc, which peaks at a third of the reach (at most 1.2 m); the jets turn slowly round the sprinkler. + */ +export function dropAt(i: number, t: number, reach: number): [number, number, number] { + const jet = i % JETS; + const k = Math.floor(i / JETS); + const s = (k / PER_JET + t * 0.7) % 1; + // a little spread across the jet, so a stream is not a thin line + const angle = (jet / JETS) * Math.PI * 2 + t * 0.35 + (((k * 7) % 5) - 2) * 0.012; + const d = s * reach; + const peak = Math.min(1.2, reach / 3); + return [Math.cos(angle) * d, 4 * peak * s * (1 - s), Math.sin(angle) * d]; +} + +export class WaterLayer { + readonly group = new Group(); + private readonly scene: Scene; + private readonly lift: FloorLift; + private readonly tex = dotTexture(); + private readonly material = new PointsMaterial({ color: 0xa8e2ff, size: 0.09, map: this.tex, transparent: true, opacity: 0.9, depthWrite: false }); + private sprays = new Map(); + + constructor(scene: Scene, lift: FloorLift) { + this.scene = scene; + this.lift = lift; + this.group.name = "live-water"; + scene.add(this.group); + } + + get active(): boolean { + return this.sprays.size > 0; + } + + set(spots: SpraySpot[]): void { + const keep = new Set(spots.map((s) => s.id)); + for (const [id, v] of this.sprays) { + if (keep.has(id)) continue; + this.group.remove(v.points); + v.points.geometry.dispose(); + this.sprays.delete(id); + } + for (const spot of spots) { + const v = this.sprays.get(spot.id); + if (v) { + v.spot = spot; + continue; + } + const g = new BufferGeometry(); + g.setAttribute("position", new Float32BufferAttribute(new Float32Array(DROPS * 3), 3)); + const points = new Points(g, this.material); + points.frustumCulled = false; + this.group.add(points); + this.sprays.set(spot.id, { spot, points }); + } + } + + step(now: number): boolean { + if (!this.sprays.size) return false; + const t = now / 1000; + for (const v of this.sprays.values()) { + const l = this.lift(v.spot.at.floorId); + v.points.visible = l.visible; + v.points.position.set(v.spot.at.x, l.y + v.spot.at.y, v.spot.at.z); + const pos = v.points.geometry.getAttribute("position") as Float32BufferAttribute; + for (let i = 0; i < DROPS; i++) { + const [x, y, z] = dropAt(i, t, v.spot.reach); + pos.setXYZ(i, x, y, z); + } + pos.needsUpdate = true; + } + return true; + } + + dispose(): void { + this.set([]); + this.material.dispose(); + this.tex.dispose(); + this.scene.remove(this.group); + } +} diff --git a/frontend/src/viewer/live-weather.ts b/frontend/src/viewer/live-weather.ts new file mode 100644 index 0000000..0a436a6 --- /dev/null +++ b/frontend/src/viewer/live-weather.ts @@ -0,0 +1,516 @@ +/** + * NextFloor's weather layer: what the sky does over the plot, drawn into the 3D scene. + * + * - rain as streaks and snow as drifting flakes, falling at an angle along the real wind (direction and strength) + * - a band of clouds on the horizon around the plot, turning slowly with the wind, and their soft shadows + * travelling over the ground and the house (clouds above the house would hide it from the raised camera) + * - fog that thickens with distance + * - lightning: a jagged bolt from the clouds down beside the house, with a short flash of the whole stage + * - the sun by day and the moon by night as a glowing disc in their real direction, paler behind clouds + * - stars on a clear night, and the ground under the house white with snow or dark and wet after rain + * + * Everything sits in one group; the layer only animates while something moves (rain, snow, clouds, a bolt), + * and draws fewer particles on the tablet level. + */ +import { + AdditiveBlending, + BufferGeometry, + CanvasTexture, + Color, + Float32BufferAttribute, + FogExp2, + Group, + LineBasicMaterial, + LineSegments, + Mesh, + MeshBasicMaterial, + NormalBlending, + PlaneGeometry, + Points, + PointsMaterial, + Sprite, + SpriteMaterial, + Vector3, + type Scene, +} from "three"; + +/** The weather to show, each amount 0…1. */ +export interface SkyWeather { + rain: number; + snow: number; + hail: number; + fog: number; + cloud: number; + /** Wind strength 0…1 (about 0 = calm, 1 = storm). */ + wind: number; + /** Where the wind comes from, degrees clockwise from north (null = unknown: it blows from the west). */ + windFrom: number | null; + lightning: boolean; +} + +export interface SkyView { + weather: SkyWeather | null; + /** Sun from sun.sun (null = unknown). */ + sun: { elevation: number; azimuth: number } | null; + /** The plan's north (degrees, as in the building settings). */ + north: number; + /** Background colour of the stage (fog melts into it). */ + sky: [number, number, number]; + /** The sun or moon disc shows. */ + disc: boolean; + /** Fewer particles (tablet level). */ + low: boolean; +} + +export interface Bounds { + x0: number; + x1: number; + z0: number; + z1: number; + y0: number; + y1: number; +} + +const DEG = Math.PI / 180; +const RAIN_MAX = 2400; +const SNOW_MAX = 1600; +const CLOUDS = 9; +const STARS = 360; + +function softTexture(stops: [number, string][], size = 64): CanvasTexture { + const c = document.createElement("canvas"); + c.width = c.height = size; + const g = c.getContext("2d")!; + const r = g.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2); + for (const [at, col] of stops) r.addColorStop(at, col); + g.fillStyle = r; + g.fillRect(0, 0, size, size); + return new CanvasTexture(c); +} + +/** A cloud: a few overlapping soft blobs, so no two clouds look the same. */ +function cloudTexture(seed: number): CanvasTexture { + const size = 128; + const c = document.createElement("canvas"); + c.width = size; + c.height = size / 2; + const g = c.getContext("2d")!; + let s = seed * 9301 + 49297; + const rnd = () => ((s = (s * 9301 + 49297) % 233280) / 233280); + for (let i = 0; i < 7; i++) { + const x = size * (0.2 + 0.6 * rnd()); + const y = size / 2 * (0.45 + 0.25 * rnd()); + const r = size * (0.12 + 0.14 * rnd()); + const grad = g.createRadialGradient(x, y, 0, x, y, r); + grad.addColorStop(0, "rgba(255,255,255,0.9)"); + grad.addColorStop(0.6, "rgba(255,255,255,0.45)"); + grad.addColorStop(1, "rgba(255,255,255,0)"); + g.fillStyle = grad; + g.fillRect(0, 0, size, size / 2); + } + return new CanvasTexture(c); +} + +interface CloudPuff { + sprite: Sprite; + shadow: Mesh; + /** Place on the horizon ring: angle (radians), distance factor and height factor. */ + angle: number; + ring: number; + lift: number; + scale: number; + speed: number; + /** Its shadow on the plot (plan coordinates). */ + sx: number; + sz: number; +} + +export class WeatherLayer { + readonly group = new Group(); + private readonly scene: Scene; + private bounds: Bounds = { x0: -10, x1: 10, z0: -10, z1: 10, y0: 0, y1: 8 }; + private view: SkyView | null = null; + private readonly rain: LineSegments; + private readonly rainVel = new Float32Array(RAIN_MAX * 3); + private readonly snow: Points; + private readonly snowPhase = new Float32Array(SNOW_MAX); + private readonly hail: Points; + private readonly clouds: CloudPuff[] = []; + private readonly bolt: LineSegments; + private readonly disc: Sprite; + private readonly halo: Sprite; + private readonly stars: Points; + private readonly cover: Mesh; + private last = 0; + private nextBolt = 0; + private boltUntil = 0; + /** The stage flashes with a bolt (the host listens). */ + onFlash: ((on: boolean) => void) | null = null; + + constructor(scene: Scene) { + this.scene = scene; + this.group.name = "live-weather"; + this.group.renderOrder = 5; + + const rg = new BufferGeometry(); + rg.setAttribute("position", new Float32BufferAttribute(new Float32Array(RAIN_MAX * 6), 3)); + this.rain = new LineSegments(rg, new LineBasicMaterial({ color: 0xa9cdf5, transparent: true, opacity: 0.5, depthWrite: false })); + + const flake = softTexture([[0, "rgba(255,255,255,1)"], [0.5, "rgba(255,255,255,0.6)"], [1, "rgba(255,255,255,0)"]], 32); + const sg = new BufferGeometry(); + sg.setAttribute("position", new Float32BufferAttribute(new Float32Array(SNOW_MAX * 3), 3)); + this.snow = new Points(sg, new PointsMaterial({ color: 0xf6f9ff, size: 0.16, map: flake, transparent: true, opacity: 0.9, depthWrite: false })); + for (let i = 0; i < SNOW_MAX; i++) this.snowPhase[i] = Math.random() * Math.PI * 2; + + const hg = new BufferGeometry(); + hg.setAttribute("position", new Float32BufferAttribute(new Float32Array(600 * 3), 3)); + this.hail = new Points(hg, new PointsMaterial({ color: 0xe9f1ff, size: 0.09, transparent: true, opacity: 0.95, depthWrite: false })); + + const shadowTex = softTexture([[0, "rgba(0,0,0,0.55)"], [0.7, "rgba(0,0,0,0.25)"], [1, "rgba(0,0,0,0)"]]); + for (let i = 0; i < CLOUDS; i++) { + const sprite = new Sprite(new SpriteMaterial({ map: cloudTexture(i + 1), transparent: true, opacity: 0, depthWrite: false, fog: false })); + const shadow = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ map: shadowTex, transparent: true, opacity: 0, depthWrite: false, blending: NormalBlending })); + shadow.rotation.x = -Math.PI / 2; + shadow.renderOrder = -1; + this.clouds.push({ sprite, shadow, angle: 0, ring: 1, lift: 1, scale: 1, speed: 0.6 + Math.random() * 0.8, sx: 0, sz: 0 }); + this.group.add(sprite, shadow); + } + + const bg = new BufferGeometry(); + bg.setAttribute("position", new Float32BufferAttribute(new Float32Array(24 * 6), 3)); + this.bolt = new LineSegments(bg, new LineBasicMaterial({ color: 0xdfe8ff, transparent: true, opacity: 1, blending: AdditiveBlending, depthWrite: false })); + this.bolt.visible = false; + + const glow = softTexture([[0, "rgba(255,255,255,1)"], [0.25, "rgba(255,255,255,0.9)"], [0.32, "rgba(255,255,255,0.35)"], [1, "rgba(255,255,255,0)"]]); + this.disc = new Sprite(new SpriteMaterial({ map: glow, transparent: true, depthWrite: false, blending: AdditiveBlending, fog: false })); + this.halo = new Sprite(new SpriteMaterial({ map: softTexture([[0, "rgba(255,255,255,0.35)"], [1, "rgba(255,255,255,0)"]]), transparent: true, depthWrite: false, blending: AdditiveBlending, fog: false })); + + // stars on a dome over the plot (unit sphere, scaled to the plot), dimmer towards the horizon + const starAt = new Float32Array(STARS * 3); + for (let i = 0; i < STARS; i++) { + const a = i * 2.39996; + const up = 0.08 + 0.92 * ((i * 0.618034) % 1); + const r = Math.sqrt(1 - up * up); + starAt.set([Math.cos(a) * r, up, Math.sin(a) * r], i * 3); + } + const stg = new BufferGeometry(); + stg.setAttribute("position", new Float32BufferAttribute(starAt, 3)); + this.stars = new Points(stg, new PointsMaterial({ color: 0xeef3ff, size: 1.6, sizeAttenuation: false, transparent: true, opacity: 0, depthWrite: false, fog: false })); + this.cover = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0, depthWrite: false })); + this.cover.rotation.x = -Math.PI / 2; + this.cover.renderOrder = -1; + + for (const o of [this.rain, this.snow, this.hail, this.bolt, this.disc, this.halo, this.stars, this.cover]) { + o.frustumCulled = false; + this.group.add(o); + } + this.group.visible = false; + scene.add(this.group); + } + + /** How cloudy it is (0…1): the sunlight through the windows dims with it. */ + get cloud(): number { + return this.view?.weather?.cloud ?? 0; + } + + /** The area the weather covers: the plot and a margin around it. */ + setBounds(b: Bounds): void { + this.bounds = b; + this.seed(); + this.placeNight(); + } + + /** Stars when the sun is well below the horizon and the sky is clear; snow lying or wet ground under the house. */ + private placeNight(): void { + const v = this.view; + const w = v?.weather; + const b = this.bounds; + const span = Math.max(b.x1 - b.x0, b.z1 - b.z0); + const night = v?.sun && v.disc ? Math.min(1, Math.max(0, (-v.sun.elevation - 4) / 8)) : 0; + const starMaterial = this.stars.material as PointsMaterial; + starMaterial.opacity = night * (1 - (w?.cloud ?? 0)) * 0.9; + this.stars.visible = starMaterial.opacity > 0.02; + this.stars.position.set((b.x0 + b.x1) / 2, b.y0, (b.z0 + b.z1) / 2); + this.stars.scale.setScalar(span * 3); + const coverMaterial = this.cover.material as MeshBasicMaterial; + const snowy = (w?.snow ?? 0) + (w?.hail ?? 0) * 0.5; + const wet = w?.rain ?? 0; + coverMaterial.color.setHex(snowy > 0.05 ? 0xf4f8ff : 0x1c3550); + coverMaterial.opacity = snowy > 0.05 ? 0.3 + 0.45 * Math.min(1, snowy) : wet > 0.1 ? 0.25 * Math.min(1, wet) : 0; + this.cover.visible = coverMaterial.opacity > 0.02; + this.cover.position.set((b.x0 + b.x1) / 2, b.y0 - 0.18, (b.z0 + b.z1) / 2); + this.cover.scale.set(b.x1 - b.x0, b.z1 - b.z0, 1); + } + + set(view: SkyView | null): void { + const before = this.view; + this.view = view; + this.group.visible = !!view; + const w = view?.weather ?? null; + // fog thickens with distance and melts into the stage colour + if (view && w && w.fog > 0.02 && !view.low) { + const color = new Color(view.sky[0] / 255, view.sky[1] / 255, view.sky[2] / 255); + this.scene.fog = new FogExp2(color, 0.008 + 0.04 * w.fog); + } else if (this.scene.fog instanceof FogExp2) this.scene.fog = null; + if (!before || before.low !== view?.low || !!before.weather !== !!w) this.seed(); + this.placeDisc(); + this.placeNight(); + if (!w?.lightning) this.endBolt(); + } + + /** Wind as a horizontal velocity in plan coordinates (x right, z down), metres per second. */ + private windVector(): [number, number] { + const w = this.view?.weather; + if (!w) return [0, 0]; + const from = (w.windFrom ?? 270) + (this.view?.north ?? 0); + // the wind blows towards the opposite side of where it comes from + const to = (from + 180) * DEG; + const speed = 0.4 + 7 * w.wind; + return [Math.sin(to) * speed, -Math.cos(to) * speed]; + } + + private count(amount: number, max: number): number { + const low = this.view?.low ?? false; + return Math.round(Math.min(1, amount) * max * (low ? 0.3 : 1)); + } + + /** New random positions for everything that falls or drifts (after a change of the area or of the amounts). */ + private seed(): void { + const b = this.bounds; + const w = this.view?.weather; + const rx = () => b.x0 + Math.random() * (b.x1 - b.x0); + const rz = () => b.z0 + Math.random() * (b.z1 - b.z0); + const ry = () => b.y0 + Math.random() * (b.y1 - b.y0); + const rp = this.rain.geometry.getAttribute("position") as Float32BufferAttribute; + for (let i = 0; i < RAIN_MAX; i++) { + const x = rx(), y = ry(), z = rz(); + rp.setXYZ(i * 2, x, y, z); + rp.setXYZ(i * 2 + 1, x, y - 0.4, z); + this.rainVel[i * 3 + 1] = 8.5 + Math.random() * 3; + } + rp.needsUpdate = true; + const sp = this.snow.geometry.getAttribute("position") as Float32BufferAttribute; + for (let i = 0; i < SNOW_MAX; i++) sp.setXYZ(i, rx(), ry(), rz()); + sp.needsUpdate = true; + const hp = this.hail.geometry.getAttribute("position") as Float32BufferAttribute; + for (let i = 0; i < hp.count; i++) hp.setXYZ(i, rx(), ry(), rz()); + hp.needsUpdate = true; + this.rain.geometry.setDrawRange(0, this.count(w?.rain ?? 0, RAIN_MAX) * 2); + this.snow.geometry.setDrawRange(0, this.count(w?.snow ?? 0, SNOW_MAX)); + this.hail.geometry.setDrawRange(0, this.count(w?.hail ?? 0, 600)); + this.rain.visible = !!w && w.rain > 0.01; + this.snow.visible = !!w && w.snow > 0.01; + this.hail.visible = !!w && w.hail > 0.01; + // clouds on a ring around the plot, their shadows anywhere over it + this.clouds.forEach((c, i) => { + c.angle = (i / CLOUDS) * Math.PI * 2 + Math.random() * 0.5; + c.ring = 1.7 + Math.random() * 0.9; + c.lift = 0.35 + Math.random() * 0.35; + c.scale = 0.55 + Math.random() * 0.45; + c.sx = b.x0 + Math.random() * (b.x1 - b.x0); + c.sz = b.z0 + Math.random() * (b.z1 - b.z0); + }); + this.placeClouds(0); + } + + private placeClouds(dt: number): void { + const v = this.view; + const w = v?.weather; + const amount = w?.cloud ?? 0; + const b = this.bounds; + const cx = (b.x0 + b.x1) / 2, cz = (b.z0 + b.z1) / 2; + const span = Math.max(b.x1 - b.x0, b.z1 - b.z0); + const [vx, vz] = this.windVector(); + const shown = Math.round(amount * CLOUDS); + // the clouds take the colour of the stage: dark slate on a night stage, white on a bright one + const sky = v?.sky ?? [20, 28, 44]; + const bright = (sky[0] + sky[1] + sky[2]) / (3 * 255); + const storm = w?.rain || w?.lightning ? 0.3 : 0; + const tone = Math.max(0.12, Math.min(1, 0.28 + bright * 0.9 - storm - 0.25 * Math.max(0, amount - 0.6))); + // the ring turns slowly in the direction the wind blows + const turn = (Math.hypot(vx, vz) / Math.max(20, span * 4)) * dt * Math.sign(vx || 1); + this.clouds.forEach((c, i) => { + const on = i < shown; + c.angle += turn * c.speed; + const r = span * c.ring; + const sm = c.sprite.material as SpriteMaterial; + sm.color.setRGB(tone, tone * 1.02, Math.min(1, tone * 1.12)); + sm.opacity = on ? 0.3 + 0.45 * amount : 0; + c.sprite.visible = on; + c.sprite.position.set(cx + Math.cos(c.angle) * r, b.y0 + span * c.lift, cz + Math.sin(c.angle) * r); + c.sprite.scale.set(span * c.scale * 1.6, span * c.scale * 0.6, 1); + // the shadows drift over the plot with the wind and come back on the far side + c.sx += vx * 0.45 * c.speed * dt; + c.sz += vz * 0.45 * c.speed * dt; + const m = span * 0.4; + if (c.sx > b.x1 + m) c.sx = b.x0 - m; + if (c.sx < b.x0 - m) c.sx = b.x1 + m; + if (c.sz > b.z1 + m) c.sz = b.z0 - m; + if (c.sz < b.z0 - m) c.sz = b.z1 + m; + const shm = c.shadow.material as MeshBasicMaterial; + shm.opacity = on ? 0.12 + 0.2 * amount : 0; + c.shadow.visible = on; + c.shadow.position.set(c.sx, b.y0 + 0.03, c.sz); + c.shadow.scale.set(span * c.scale * 0.55, span * c.scale * 0.35, 1); + }); + } + + /** The sun by day, the moon by night, far out in their direction; paler (or gone) behind clouds. */ + private placeDisc(): void { + const v = this.view; + const sun = v?.sun; + const cloud = v?.weather?.cloud ?? 0; + const night = !sun || sun.elevation < -3; + if (!v || !sun || !v.disc || cloud > 0.9 || (!night && sun.elevation < 0.5)) { + this.disc.visible = this.halo.visible = false; + return; + } + const b = this.bounds; + const center = new Vector3((b.x0 + b.x1) / 2, b.y0, (b.z0 + b.z1) / 2); + const r = Math.max(70, Math.max(b.x1 - b.x0, b.z1 - b.z0) * 3.5); + // the moon stands roughly opposite the sun + const az = ((night ? sun.azimuth + 180 : sun.azimuth) + v.north) * DEG; + const el = Math.max(8, Math.abs(sun.elevation)) * DEG; + const dir = new Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), -Math.cos(az) * Math.cos(el)); + const pos = center.addScaledVector(dir, r); + const size = r * (night ? 0.07 : 0.1); + this.disc.position.copy(pos); + this.halo.position.copy(pos); + this.disc.scale.setScalar(size); + this.halo.scale.setScalar(size * 3.2); + const dm = this.disc.material as SpriteMaterial; + const hm = this.halo.material as SpriteMaterial; + // a low sun is orange, a high one pale yellow + const low = !night ? Math.max(0, 1 - sun.elevation / 20) : 0; + dm.color.set(night ? 0xd5def2 : new Color(1, 0.9 - 0.25 * low, 0.6 - 0.35 * low)); + hm.color.copy(dm.color); + dm.opacity = (night ? 0.7 : 0.95) * (1 - cloud); + hm.opacity = (night ? 0.35 : 0.6) * (1 - cloud); + this.disc.visible = this.halo.visible = true; + } + + private endBolt(): void { + if (this.bolt.visible) { + this.bolt.visible = false; + this.onFlash?.(false); + } + } + + /** A jagged bolt from the cloud base down to the ground somewhere beside the house. */ + private strike(now: number): void { + const b = this.bounds; + const side = Math.random() < 0.5 ? -1 : 1; + let x = side < 0 ? b.x0 - 2 - Math.random() * 6 : b.x1 + 2 + Math.random() * 6; + let z = b.z0 + Math.random() * (b.z1 - b.z0); + const top = b.y1 + 4; + const p = this.bolt.geometry.getAttribute("position") as Float32BufferAttribute; + const steps = 24; + let y = top; + for (let i = 0; i < steps; i++) { + const ny = top - ((i + 1) / steps) * (top - b.y0); + const nx = x + (Math.random() - 0.5) * 1.6; + const nz = z + (Math.random() - 0.5) * 1.6; + p.setXYZ(i * 2, x, y, z); + p.setXYZ(i * 2 + 1, nx, ny, nz); + x = nx; + z = nz; + y = ny; + } + p.needsUpdate = true; + this.bolt.visible = true; + this.boltUntil = now + 90 + Math.random() * 120; + this.onFlash?.(true); + } + + /** One frame: let it rain, snow, drift and flash. True while anything moves. */ + step(now: number): boolean { + const v = this.view; + const w = v?.weather; + if (!v || !w) { + this.last = 0; + return false; + } + const dt = this.last ? Math.min(0.1, (now - this.last) / 1000) : 0; + this.last = now; + const b = this.bounds; + const height = b.y1 - b.y0; + const [vx, vz] = this.windVector(); + if (this.rain.visible && dt) { + const p = this.rain.geometry.getAttribute("position") as Float32BufferAttribute; + const a = p.array as Float32Array; + const n = this.count(w.rain, RAIN_MAX); + for (let i = 0; i < n; i++) { + const k = i * 6; + const fall = this.rainVel[i * 3 + 1]; + let x = a[k] + vx * dt, y = a[k + 1] - fall * dt, z = a[k + 2] + vz * dt; + if (y < b.y0) { + y += height; + x = b.x0 + Math.random() * (b.x1 - b.x0) - vx * 0.4; + z = b.z0 + Math.random() * (b.z1 - b.z0) - vz * 0.4; + } + // the streak points back along the drop's path: slanted in the wind + const len = 0.05; + a[k] = x; a[k + 1] = y; a[k + 2] = z; + a[k + 3] = x - vx * len; a[k + 4] = y + fall * len; a[k + 5] = z - vz * len; + } + p.needsUpdate = true; + } + if (this.snow.visible && dt) { + const p = this.snow.geometry.getAttribute("position") as Float32BufferAttribute; + const a = p.array as Float32Array; + const n = this.count(w.snow, SNOW_MAX); + const t = now / 1000; + for (let i = 0; i < n; i++) { + const k = i * 3; + const ph = this.snowPhase[i]; + let x = a[k] + (vx * 0.35 + Math.sin(t * 1.3 + ph) * 0.35) * dt; + let y = a[k + 1] - (0.7 + 0.5 * ((ph * 7) % 1)) * dt; + let z = a[k + 2] + (vz * 0.35 + Math.cos(t * 1.1 + ph) * 0.35) * dt; + if (y < b.y0) { + y += height; + x = b.x0 + Math.random() * (b.x1 - b.x0); + z = b.z0 + Math.random() * (b.z1 - b.z0); + } + a[k] = x; a[k + 1] = y; a[k + 2] = z; + } + p.needsUpdate = true; + } + if (this.hail.visible && dt) { + const p = this.hail.geometry.getAttribute("position") as Float32BufferAttribute; + const a = p.array as Float32Array; + const n = this.count(w.hail, 600); + for (let i = 0; i < n; i++) { + const k = i * 3; + let y = a[k + 1] - 14 * dt; + if (y < b.y0) y += height; + a[k] += vx * 0.5 * dt; + a[k + 1] = y; + a[k + 2] += vz * 0.5 * dt; + } + p.needsUpdate = true; + } + if (w.cloud > 0.01) this.placeClouds(dt); + if (w.lightning && !v.low) { + if (!this.nextBolt) this.nextBolt = now + 2500 + Math.random() * 6000; + if (now >= this.nextBolt) { + this.strike(now); + this.nextBolt = now + 3500 + Math.random() * 9000; + } + if (this.bolt.visible && now > this.boltUntil) this.endBolt(); + } else this.nextBolt = 0; + return this.rain.visible || this.snow.visible || this.hail.visible || w.cloud > 0.01 || w.lightning; + } + + dispose(): void { + this.endBolt(); + this.group.traverse((o) => { + const m = o as Mesh; + m.geometry?.dispose(); + const mat = m.material as MeshBasicMaterial | undefined; + mat?.map?.dispose(); + mat?.dispose(); + }); + this.scene.remove(this.group); + if (this.scene.fog instanceof FogExp2) this.scene.fog = null; + } +} diff --git a/frontend/src/viewer/meshes.ts b/frontend/src/viewer/meshes.ts new file mode 100644 index 0000000..e482d0b --- /dev/null +++ b/frontend/src/viewer/meshes.ts @@ -0,0 +1,174 @@ +// Owned 3D models (binary glTF) shown instead of a pack item's simple parts. +// +// The files live on the user's Home Assistant, never in NextFloor. A model is loaded once per page and shared +// by all viewers; every placed item gets a light copy of its own, so its paint colour can differ. + +import { + Box3, + Color, + DirectionalLight, + Group, + HemisphereLight, + Mesh, + MeshStandardMaterial, + PMREMGenerator, + type BufferGeometry, + type Material, + type Object3D, + type Texture, + type WebGLRenderer, +} from "three"; +import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js"; +import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"; +import { toCreasedNormals } from "three/examples/jsm/utils/BufferGeometryUtils.js"; +import { getMeshSource, markMeshReady } from "../packs.ts"; + +interface LoadedMesh { + root: Object3D; + /** Size of the model as it is (width, height, depth in metres). */ + size: [number, number, number]; +} + +const cache = new Map>(); +const loaded = new Map(); + +/** Smooth shading with creases: the model comes without normals (they are cheap to recompute and keep the file small). */ +const CREASE = (50 * Math.PI) / 180; + +function prepare(root: Object3D): void { + root.traverse((o) => { + const mesh = o as Mesh; + if (!mesh.isMesh) return; + const g = mesh.geometry as BufferGeometry; + const m = mesh.material as MeshStandardMaterial; + const name = m.name ?? ""; + // paint: the body colour is swapped per item + mesh.userData.paint = !!m.userData?.paint || /^Paint/.test(name); + if (!g.getAttribute("normal")) { + // the body is one smooth skin; everything else keeps its edges + if (mesh.userData.paint) g.computeVertexNormals(); + else mesh.geometry = toCreasedNormals(g, CREASE); + } + // the loader flags models without normals as flat-shaded: ours get smooth ones below + m.flatShading = false; + const glass = /glass/i.test(name); + m.metalness = mesh.userData.paint ? 0.55 : glass ? 0 : Math.min(m.metalness ?? 0, 0.4); + m.roughness = mesh.userData.paint ? 0.28 : glass ? 0.05 : Math.max(m.roughness ?? 0.6, 0.45); + if (glass) { + m.transparent = true; + m.depthWrite = false; + m.opacity = Math.max(m.opacity, 0.9); + } + }); +} + +/** Load a model (once); false when the host has none or it is broken. */ +export function loadMesh(id: string): Promise { + let p = cache.get(id); + if (!p) { + const source = getMeshSource(); + if (!source) return Promise.resolve(false); + p = source(id) + .then( + (data) => + data && + new Promise((resolve) => { + new GLTFLoader().parse( + data, + "", + (gltf) => { + prepare(gltf.scene); + const box = new Box3().setFromObject(gltf.scene); + const size: [number, number, number] = [box.max.x - box.min.x, box.max.y - box.min.y, box.max.z - box.min.z]; + // feet on the floor, centred on its footprint + gltf.scene.position.set(-(box.max.x + box.min.x) / 2, -box.min.y, -(box.max.z + box.min.z) / 2); + const root = new Group(); + root.add(gltf.scene); + loaded.set(id, { root, size }); + markMeshReady(id); + resolve({ root, size }); + }, + () => resolve(null), + ); + }), + ) + .catch(() => null); + cache.set(id, p); + } + return p.then((m) => !!m); +} + +/** Forget models that could not be loaded, to try again (the host's login may have changed). */ +export function retryMeshes(): void { + for (const [id, p] of cache) if (!loaded.has(id)) void p.then(() => cache.delete(id)); +} + +export interface MeshPlacement { + x: number; + z: number; + y: number; + /** Turn around the vertical axis in degrees (as furniture.rotation). */ + rotation: number; + mirror?: boolean; + w: number; + d: number; + h: number; + /** Colour of the body paint (hex like "#c01020"), or null for the model's own. */ + paint: string | null; +} + +/** A copy of a loaded model for one placed item (null while it is not loaded). */ +export function instantiateMesh(id: string, at: MeshPlacement): Group | null { + const m = loaded.get(id); + if (!m) return null; + const root = m.root.clone(true); + const own: Material[] = []; + root.traverse((o) => { + const mesh = o as Mesh; + if (!mesh.isMesh) return; + const mat = (mesh.material as MeshStandardMaterial).clone(); + if (mesh.userData.paint && at.paint) mat.color = new Color(at.paint); + mesh.material = mat; + own.push(mat); + }); + const g = new Group(); + g.add(root); + // the item's box is the model's: it stretches to the width, depth and height of the furniture + g.scale.set((at.mirror ? -1 : 1) * (at.w / m.size[0]), at.h / m.size[1], at.d / m.size[2]); + g.position.set(at.x, at.y, at.z); + g.rotation.y = (-at.rotation * Math.PI) / 180; + g.userData.own = own; + return g; +} + +/** Free the materials of a copy made by instantiateMesh (geometry and textures belong to the shared model). */ +export function disposeMeshInstance(g: Object3D): void { + for (const m of (g.userData.own ?? []) as Material[]) m.dispose(); +} + +/** Light and reflections for the models; the rest of the scene is unlit, so they only touch these. */ +export function addMeshLighting(parent: Object3D, renderer: WebGLRenderer): { env: Texture; dispose: () => void } { + const pmrem = new PMREMGenerator(renderer); + const env = pmrem.fromScene(new RoomEnvironment(), 0.04).texture; + pmrem.dispose(); + const sky = new HemisphereLight(0xffffff, 0x8a93a6, 0.9); + const sun = new DirectionalLight(0xffffff, 1.6); + sun.position.set(-4, 9, 6); + parent.add(sky, sun); + return { + env, + dispose: () => { + env.dispose(); + sky.removeFromParent(); + sun.removeFromParent(); + }, + }; +} + +/** Set the reflection map on every material of a copy. */ +export function applyEnvironment(g: Object3D, env: Texture): void { + for (const m of (g.userData.own ?? []) as MeshStandardMaterial[]) { + m.envMap = env; + m.envMapIntensity = 0.9; + } +} diff --git a/frontend/src/viewer/models/choices.test.ts b/frontend/src/viewer/models/choices.test.ts new file mode 100644 index 0000000..c3883fd --- /dev/null +++ b/frontend/src/viewer/models/choices.test.ts @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { guessPaint, paintName, shareBudget, turnsToFront, type MaterialSummary } from "./choices.ts"; + +const material = (name: string, area: number, extra: Partial = {}): MaterialSummary => ({ name, area, opacity: 1, lightness: 0.5, ...extra }); + +test("materials named like paint are the paint", () => { + assert.deepEqual(guessPaint([material("Glass", 2, { opacity: 0.3 }), material("Paint_Body", 5), material("Carpaint2", 1), material("Tyre", 3, { lightness: 0.05 })]), ["Paint_Body", "Carpaint2"]); +}); + +test("without a telling name the largest solid, not-dark material is guessed", () => { + assert.deepEqual(guessPaint([material("Tyre", 9, { lightness: 0.05 }), material("Glass", 8, { opacity: 0.2 }), material("m1", 6), material("m2", 2)]), ["m1"]); + assert.deepEqual(guessPaint([material("Window_glass", 9), material("lamp", 7), material("m3", 1)]), ["m3"]); + assert.deepEqual(guessPaint([]), []); +}); + +test("a model within budget keeps everything, a heavier one is cut in proportion", () => { + assert.deepEqual(shareBudget([100, 50], 200), [100, 50]); + assert.deepEqual(shareBudget([300, 100], 200), [150, 50]); + assert.deepEqual(shareBudget([1, 1000], 10), [1, 9]); +}); + +test("paint names get the prefix once", () => { + assert.equal(paintName("Body"), "Paint_Body"); + assert.equal(paintName("Paint_Body"), "Paint_Body"); + assert.equal(paintName("PaintMetal"), "PaintMetal"); + assert.equal(paintName(""), "Paint_body"); +}); + +test("the turns bring the front to +z", () => { + assert.deepEqual(["+z", "-x", "-z", "+x"].map((f) => turnsToFront(f as never)), [0, 1, 2, 3]); +}); diff --git a/frontend/src/viewer/models/choices.ts b/frontend/src/viewer/models/choices.ts new file mode 100644 index 0000000..fee3769 --- /dev/null +++ b/frontend/src/viewer/models/choices.ts @@ -0,0 +1,45 @@ +// The decisions made while preparing a model that need no 3D: how the triangle budget is shared between materials, and which +// material is most likely the body paint. + +export interface MaterialSummary { + name: string; + /** Surface area in square metres. */ + area: number; + opacity: number; + /** Brightness of its colour from 0 (black) to 1 (white). */ + lightness: number; +} + +/** Names that body paint usually has in models of cars and appliances. */ +const PAINT_NAME = /^paint|carpaint|body|lack|lacquer|exterior/i; + +/** + * The materials that are most likely the body paint: those named like paint, else the one with the largest surface among the solid + * ones that are not nearly black (tyres, trim) or see-through (glass). + */ +export function guessPaint(materials: readonly MaterialSummary[]): string[] { + const named = materials.filter((m) => PAINT_NAME.test(m.name)).map((m) => m.name); + if (named.length > 0) return named; + const solid = materials.filter((m) => m.opacity >= 0.9 && m.lightness > 0.12 && !/glass|window|light|lamp/i.test(m.name)); + const largest = [...solid].sort((a, b) => b.area - a.area)[0]; + return largest ? [largest.name] : []; +} + +/** + * How many triangles each part may keep so that all together stay within `total`. Parts that already fit keep all of theirs, and what + * they leave over is shared among the larger ones in proportion to their size. + */ +export function shareBudget(counts: readonly number[], total: number): number[] { + const sum = counts.reduce((a, b) => a + b, 0); + if (sum <= total) return [...counts]; + const share = total / sum; + return counts.map((n) => Math.max(1, Math.floor(n * share))); +} + +/** A name for a paint material so that NextFloor recognises it: the original name behind a "Paint_" prefix, once. */ +export const paintName = (name: string): string => (/^Paint/.test(name) ? name : `Paint_${name || "body"}`); + +/** The quarter turns (0 to 3) that bring a model whose front points along the given axis direction to +z. */ +export function turnsToFront(front: "+x" | "-x" | "+z" | "-z"): 0 | 1 | 2 | 3 { + return { "+z": 0, "-x": 1, "-z": 2, "+x": 3 }[front] as 0 | 1 | 2 | 3; +} diff --git a/frontend/src/viewer/models/decimate.test.ts b/frontend/src/viewer/models/decimate.test.ts new file mode 100644 index 0000000..7ada0ba --- /dev/null +++ b/frontend/src/viewer/models/decimate.test.ts @@ -0,0 +1,76 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { decimate, triangleCount, type Mesh3 } from "./decimate.ts"; + +/** A flat grid of n × n squares, two triangles each, in the x-z plane. */ +function grid(n: number): Mesh3 { + const positions = new Float32Array((n + 1) * (n + 1) * 3); + for (let z = 0; z <= n; z++) for (let x = 0; x <= n; x++) positions.set([x / n, 0, z / n], (z * (n + 1) + x) * 3); + const indices: number[] = []; + for (let z = 0; z < n; z++) { + for (let x = 0; x < n; x++) { + const a = z * (n + 1) + x; + indices.push(a, a + n + 1, a + 1, a + 1, a + n + 1, a + n + 2); + } + } + return { positions, indices: Uint32Array.from(indices) }; +} + +/** A box made of 12 triangles, subdivided by repeating its faces as grids. */ +function sphere(rings: number, segments: number): Mesh3 { + const positions: number[] = []; + for (let r = 0; r <= rings; r++) { + for (let s = 0; s < segments; s++) { + const [phi, theta] = [(r / rings) * Math.PI, (s / segments) * Math.PI * 2]; + positions.push(Math.sin(phi) * Math.cos(theta), Math.cos(phi), Math.sin(phi) * Math.sin(theta)); + } + } + const indices: number[] = []; + for (let r = 0; r < rings; r++) { + for (let s = 0; s < segments; s++) { + const [a, b] = [r * segments + s, r * segments + ((s + 1) % segments)]; + const [c, d] = [a + segments, b + segments]; + indices.push(a, c, b, b, c, d); + } + } + return { positions: Float32Array.from(positions), indices: Uint32Array.from(indices) }; +} + +test("a mesh that is light enough comes back as it is", () => { + const mesh = grid(4); + assert.equal(decimate(mesh, 100), mesh); + assert.equal(decimate(mesh, 32), mesh); +}); + +test("a heavy mesh gets close to the target without going over it", () => { + const mesh = grid(60); + assert.equal(triangleCount(mesh), 7200); + const light = decimate(mesh, 1000); + assert.ok(triangleCount(light) <= 1000, `${triangleCount(light)}`); + assert.ok(triangleCount(light) > 500, `too much taken away: ${triangleCount(light)}`); +}); + +test("the lighter mesh stays in the shape of the original", () => { + const light = decimate(sphere(40, 60), 600); + assert.ok(triangleCount(light) <= 600); + for (let v = 0; v < light.positions.length; v += 3) { + const r = Math.hypot(light.positions[v], light.positions[v + 1], light.positions[v + 2]); + assert.ok(r > 0.75 && r <= 1.0001, `a vertex off the sphere: ${r}`); + } +}); + +test("every triangle refers to existing vertices and has three different corners", () => { + const light = decimate(sphere(30, 40), 300); + const vertices = light.positions.length / 3; + for (let i = 0; i < light.indices.length; i += 3) { + const [a, b, c] = [light.indices[i], light.indices[i + 1], light.indices[i + 2]]; + assert.ok(a < vertices && b < vertices && c < vertices); + assert.ok(a !== b && b !== c && a !== c); + } + assert.equal(light.indices.length % 3, 0); +}); + +test("an empty mesh is left alone", () => { + const empty: Mesh3 = { positions: new Float32Array(0), indices: new Uint32Array(0) }; + assert.equal(decimate(empty, 10), empty); +}); diff --git a/frontend/src/viewer/models/decimate.ts b/frontend/src/viewer/models/decimate.ts new file mode 100644 index 0000000..148f4d9 --- /dev/null +++ b/frontend/src/viewer/models/decimate.ts @@ -0,0 +1,112 @@ +// Making a heavy 3D model lighter by vertex clustering: the model is laid over a grid, every grid cell becomes one vertex (the average +// of the vertices in it), and triangles that fall into a single cell or two disappear. A coarser grid gives fewer triangles, so the +// grid is chosen to land just under the wanted number. It is fast, needs no extra libraries, and keeps the shape of a car or a sofa. + +export interface Mesh3 { + /** x, y, z of every vertex. */ + positions: Float32Array; + /** Three vertex numbers per triangle. */ + indices: Uint32Array; +} + +/** The number of triangles. */ +export const triangleCount = (mesh: Mesh3): number => mesh.indices.length / 3; + +interface Bounds { + min: [number, number, number]; + size: [number, number, number]; +} + +function boundsOf(positions: Float32Array): Bounds { + const min: [number, number, number] = [Infinity, Infinity, Infinity]; + const max: [number, number, number] = [-Infinity, -Infinity, -Infinity]; + for (let i = 0; i < positions.length; i += 3) { + for (let k = 0; k < 3; k++) { + min[k] = Math.min(min[k], positions[i + k]); + max[k] = Math.max(max[k], positions[i + k]); + } + } + return { min, size: [max[0] - min[0], max[1] - min[1], max[2] - min[2]] }; +} + +/** The cell number of every vertex for a grid of cells `cell` wide. Cells are numbered by their coordinates, packed into one number. */ +function cellsOf(positions: Float32Array, bounds: Bounds, cell: number): Float64Array { + const count = positions.length / 3; + const counts = bounds.size.map((s) => Math.floor(s / cell) + 1); + const cells = new Float64Array(count); + for (let v = 0; v < count; v++) { + const x = Math.floor((positions[v * 3] - bounds.min[0]) / cell); + const y = Math.floor((positions[v * 3 + 1] - bounds.min[1]) / cell); + const z = Math.floor((positions[v * 3 + 2] - bounds.min[2]) / cell); + cells[v] = (x * counts[1] + y) * counts[2] + z; + } + return cells; +} + +/** The triangles that survive clustering: all three corners in different cells. Counted without building anything. */ +function survivors(indices: Uint32Array, cells: Float64Array): number { + let kept = 0; + for (let i = 0; i < indices.length; i += 3) { + const [a, b, c] = [cells[indices[i]], cells[indices[i + 1]], cells[indices[i + 2]]]; + if (a !== b && b !== c && a !== c) kept++; + } + return kept; +} + +/** Builds the lighter mesh for a given grid: one vertex per used cell, and the surviving triangles without duplicates. */ +function cluster(mesh: Mesh3, cells: Float64Array): Mesh3 { + const vertexOfCell = new Map(); + const sums: number[] = []; + const members: number[] = []; + const mapped = new Uint32Array(cells.length); + for (let v = 0; v < cells.length; v++) { + let id = vertexOfCell.get(cells[v]); + if (id === undefined) { + id = members.length; + vertexOfCell.set(cells[v], id); + members.push(0); + sums.push(0, 0, 0); + } + mapped[v] = id; + members[id]++; + for (let k = 0; k < 3; k++) sums[id * 3 + k] += mesh.positions[v * 3 + k]; + } + const positions = new Float32Array(members.length * 3); + for (let id = 0; id < members.length; id++) for (let k = 0; k < 3; k++) positions[id * 3 + k] = sums[id * 3 + k] / members[id]; + const seen = new Set(); + const indices: number[] = []; + for (let i = 0; i < mesh.indices.length; i += 3) { + const [a, b, c] = [mapped[mesh.indices[i]], mapped[mesh.indices[i + 1]], mapped[mesh.indices[i + 2]]]; + if (a === b || b === c || a === c) continue; + // the same triangle with the same winding, written starting at its smallest corner, is a duplicate + const start = Math.min(a, b, c); + const key = start === a ? `${a},${b},${c}` : start === b ? `${b},${c},${a}` : `${c},${a},${b}`; + if (seen.has(key)) continue; + seen.add(key); + indices.push(a, b, c); + } + return { positions, indices: Uint32Array.from(indices) }; +} + +/** + * A lighter copy of the mesh with at most `target` triangles. A mesh that is light enough is returned as it is. The grid is found by + * halving the search between a very fine and a very coarse one. + */ +export function decimate(mesh: Mesh3, target: number): Mesh3 { + if (triangleCount(mesh) <= target || mesh.positions.length === 0) return mesh; + const bounds = boundsOf(mesh.positions); + const longest = Math.max(...bounds.size, 1e-9); + let fine = longest / 4096; + let coarse = longest; + let best = cellsOf(mesh.positions, bounds, coarse); + for (let step = 0; step < 14; step++) { + const middle = Math.sqrt(fine * coarse); + const cells = cellsOf(mesh.positions, bounds, middle); + if (survivors(mesh.indices, cells) > target) fine = middle; + else { + coarse = middle; + best = cells; + } + } + return cluster(mesh, best); +} diff --git a/frontend/src/viewer/models/prepare.ts b/frontend/src/viewer/models/prepare.ts new file mode 100644 index 0000000..2c4ea2f --- /dev/null +++ b/frontend/src/viewer/models/prepare.ts @@ -0,0 +1,195 @@ +// Getting a 3D model you own ready for NextFloor, in the browser: a binary glTF is read, its parts are merged by material, turned so +// that the front points to +z, made lighter, the body paint is marked, and the result is written again as plain binary glTF without +// textures. This is what tools/prepare-model.mjs did by hand. + +import { + AmbientLight, + Box3, + BufferAttribute, + BufferGeometry, + Color, + DirectionalLight, + HemisphereLight, + Matrix4, + Mesh, + MeshStandardMaterial, + OrthographicCamera, + Scene, + Vector3, + WebGLRenderer, + type Material, + type Object3D, +} from "three"; +import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js"; +import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"; +import { guessPaint, paintName, shareBudget, type MaterialSummary } from "./choices.ts"; +import { decimate, triangleCount, type Mesh3 } from "./decimate.ts"; + +export interface ModelInfo { + triangles: number; + /** Width, height and depth in metres as the model comes. */ + size: [number, number, number]; + materials: MaterialSummary[]; + /** The materials that are probably the body paint. */ + paint: string[]; +} + +export interface PrepareOptions { + /** Quarter turns about the vertical axis that bring the front to +z. */ + turns: 0 | 1 | 2 | 3; + /** Names of the materials that are body paint. */ + paint: readonly string[]; + /** Most triangles the result may have. */ + maxTriangles: number; +} + +/** What goes wrong when a file cannot be used, so the page can say it in words. */ +export class ModelError extends Error { + readonly reason: "not_glb" | "compressed" | "empty" | "unreadable"; + constructor(reason: ModelError["reason"], message: string) { + super(message); + this.reason = reason; + } +} + +const MAGIC = 0x46546c67; // "glTF" + +/** The whole file is read as binary glTF; anything else is refused before three.js sees it. */ +function check(data: ArrayBuffer): void { + if (data.byteLength < 20 || new DataView(data).getUint32(0, true) !== MAGIC) throw new ModelError("not_glb", "not a binary glTF (.glb) file"); +} + +async function parse(data: ArrayBuffer): Promise { + check(data); + return new Promise((resolve, reject) => { + new GLTFLoader().parse( + data, + "", + (gltf) => resolve(gltf.scene), + (error) => { + const message = String((error as { message?: string })?.message ?? error); + reject(/draco|meshopt|ktx/i.test(message) ? new ModelError("compressed", message) : new ModelError("unreadable", message)); + }, + ); + }); +} + +/** One material's share of the model: its triangles with the placement of the parts already applied. */ +interface Part { + material: MeshStandardMaterial; + mesh: Mesh3; +} + +const asStandard = (m: Material): MeshStandardMaterial => (m instanceof MeshStandardMaterial ? m : Object.assign(new MeshStandardMaterial(), { color: (m as { color?: Color }).color?.clone() ?? new Color(0x888888), name: m.name, opacity: m.opacity, transparent: m.transparent })); + +/** Every mesh of the scene in world coordinates, grouped by material. */ +function collect(root: Object3D, extra: Matrix4): Part[] { + root.updateMatrixWorld(true); + const byMaterial = new Map(); + root.traverse((object) => { + const mesh = object as Mesh; + if (!mesh.isMesh) return; + const geometry = mesh.geometry as BufferGeometry; + const position = geometry.getAttribute("position"); + if (!position) return; + const material = asStandard(Array.isArray(mesh.material) ? mesh.material[0] : mesh.material); + const target = byMaterial.get(material) ?? { positions: [], indices: [] }; + byMaterial.set(material, target); + const placement = new Matrix4().multiplyMatrices(extra, mesh.matrixWorld); + const first = target.positions.length / 3; + const v = new Vector3(); + for (let i = 0; i < position.count; i++) { + v.fromBufferAttribute(position, i).applyMatrix4(placement); + target.positions.push(v.x, v.y, v.z); + } + const index = geometry.getIndex(); + const count = index ? index.count : position.count; + for (let i = 0; i < count; i++) target.indices.push(first + (index ? index.getX(i) : i)); + }); + return [...byMaterial].map(([material, g]) => ({ material, mesh: { positions: Float32Array.from(g.positions), indices: Uint32Array.from(g.indices) } })); +} + +const surfaceArea = (m: Mesh3): number => { + let area = 0; + const [a, b, c] = [new Vector3(), new Vector3(), new Vector3()]; + for (let i = 0; i < m.indices.length; i += 3) { + a.fromArray(m.positions, m.indices[i] * 3); + b.fromArray(m.positions, m.indices[i + 1] * 3); + c.fromArray(m.positions, m.indices[i + 2] * 3); + area += b.sub(a).cross(c.sub(a)).length() / 2; + } + return area; +}; + +const lightness = (c: Color): number => 0.299 * c.r + 0.587 * c.g + 0.114 * c.b; + +/** What is in the model: size, triangles, materials with their area, and a guess at the paint. */ +export async function inspectModel(data: ArrayBuffer): Promise { + const parts = collect(await parse(data), new Matrix4()); + if (parts.length === 0) throw new ModelError("empty", "the file has no 3D parts"); + const box = new Box3(); + for (const p of parts) box.union(new Box3().setFromArray(p.mesh.positions as unknown as number[])); + const size = box.getSize(new Vector3()); + const materials = parts.map((p): MaterialSummary => ({ name: p.material.name || "material", area: surfaceArea(p.mesh), opacity: p.material.opacity, lightness: lightness(p.material.color) })); + return { triangles: parts.reduce((n, p) => n + triangleCount(p.mesh), 0), size: [size.x, size.y, size.z], materials, paint: guessPaint(materials) }; +} + +/** The model lighter, turned and marked, as plain binary glTF. */ +export async function prepareModel(data: ArrayBuffer, options: PrepareOptions): Promise<{ glb: ArrayBuffer; triangles: number }> { + const turn = new Matrix4().makeRotationY((options.turns * Math.PI) / 2); + const parts = collect(await parse(data), turn); + if (parts.length === 0) throw new ModelError("empty", "the file has no 3D parts"); + const budgets = shareBudget(parts.map((p) => triangleCount(p.mesh)), options.maxTriangles); + const scene = new Scene(); + let triangles = 0; + parts.forEach((part, i) => { + const light = decimate(part.mesh, budgets[i]); + if (triangleCount(light) === 0) return; + triangles += triangleCount(light); + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new BufferAttribute(light.positions, 3)); + geometry.setIndex(new BufferAttribute(light.indices, 1)); + const name = part.material.name || "material"; + const isPaint = options.paint.includes(name); + const material = new MeshStandardMaterial({ color: part.material.color.clone(), name: isPaint ? paintName(name) : name, metalness: part.material.metalness, roughness: part.material.roughness, opacity: part.material.opacity, transparent: part.material.opacity < 1 }); + if (isPaint) material.userData.paint = true; + scene.add(new Mesh(geometry, material)); + }); + const glb = await new Promise((resolve, reject) => { + new GLTFExporter().parse(scene, (result) => (result instanceof ArrayBuffer ? resolve(result) : reject(new ModelError("unreadable", "export gave no binary"))), (e) => reject(new ModelError("unreadable", String(e))), { binary: true }); + }); + return { glb, triangles }; +} + +/** A picture of a prepared model from the front right, with the paint in the given colour, as a PNG data URL. */ +export async function previewModel(glb: ArrayBuffer, paint: string, size = 220): Promise { + const root = await parse(glb); + const box = new Box3().setFromObject(root); + const centre = box.getCenter(new Vector3()); + const extent = box.getSize(new Vector3()); + root.traverse((o) => { + const mesh = o as Mesh; + if (!mesh.isMesh) return; + const material = mesh.material as MeshStandardMaterial; + if (material.userData?.paint || /^Paint/.test(material.name)) material.color.set(paint); + material.metalness = Math.min(material.metalness ?? 0, 0.5); + }); + const scene = new Scene(); + const sun = new DirectionalLight(0xffffff, 1.6); + sun.position.set(-4, 9, 6); + scene.add(root, new AmbientLight(0xffffff, 0.5), new HemisphereLight(0xffffff, 0x667088, 1.1), sun); + const half = Math.max(extent.x, extent.y, extent.z) * 0.75; + const camera = new OrthographicCamera(-half, half, half, -half, 0.01, 100); + camera.position.copy(centre).add(new Vector3(0.9, 0.7, 1.2).normalize().multiplyScalar(20)); + camera.lookAt(centre); + const renderer = new WebGLRenderer({ alpha: true, antialias: true, preserveDrawingBuffer: true }); + renderer.setSize(size, size, false); + renderer.render(scene, camera); + const url = renderer.domElement.toDataURL("image/png"); + renderer.dispose(); + scene.traverse((o) => { + const mesh = o as Mesh; + if (mesh.isMesh) mesh.geometry.dispose(); + }); + return url; +} diff --git a/frontend/src/viewer/openings.ts b/frontend/src/viewer/openings.ts new file mode 100644 index 0000000..06cea5c --- /dev/null +++ b/frontend/src/viewer/openings.ts @@ -0,0 +1,4 @@ +// Moving and state-dependent parts of doors and windows, split into modules in openings/. + +export { buildOpeningParts } from "./openings/parts.ts"; +export { CLOSED, type OpeningParts, type OpeningState } from "./openings/types.ts"; diff --git a/frontend/src/viewer/openings/blinds.ts b/frontend/src/viewer/openings/blinds.ts new file mode 100644 index 0000000..0a69ac4 --- /dev/null +++ b/frontend/src/viewer/openings/blinds.ts @@ -0,0 +1,54 @@ +// The blind of a window: a roller shutter outside (a box above the opening and slats down to the closed fraction), a venetian blind +// outside whose slats turn with the cover's tilt, or a roller blind inside the room. A wide window can have a second blind for its +// right half. + +import { Color } from "three"; +import { ALWAYS } from "../geo.ts"; +import type { Ctx } from "./context.ts"; +import { BLIND_BOX, FRAME_TOP } from "./palette.ts"; +import { panel, splitBox } from "./primitives.ts"; + +/** Colours of the kinds of blinds: the white shutter, the aluminium of a venetian blind, the light fabric of an inside blind. */ +const SHUTTER = 0xffffff; +const VENETIAN = 0xc9ced6; +const FABRIC = 0xefe7d8; +/** Spacing and depth of venetian slats (m). */ +const SLAT_STEP = 0.08; +const SLAT_DEPTH = 0.085; + +export function blind(c: Ctx): void { + const { info, state, frame, fold } = c; + if (state.cover === null) return; + const [W, S, T] = [info.width, info.sill, info.top]; + const kind = info.opening.blind ?? "roller"; + const outside = -info.faceOut; + const inside = info.faceRoom; + // the cassette above the opening: a big box outside, a slim one on the room side for an inside blind + if (kind === "inside") splitBox(c.frames, frame, { x0: -0.03, x1: W + 0.03, n0: inside, n1: inside + 0.07, y0: T - 0.02, y1: T + 0.07 }, new Color(0xf2f2f2), new Color(0xf7f7f7), fold); + else splitBox(c.frames, frame, { x0: -0.05, x1: W + 0.05, n0: outside - 0.15, n1: outside, y0: T, y1: T + 0.2 }, new Color(BLIND_BOX), new Color(FRAME_TOP), fold); + const halves: [number, number, number][] = state.cover2 != null ? [[0, W / 2, state.cover], [W / 2, W, state.cover2]] : [[0, W, state.cover]]; + for (const [x0, x1, cover] of halves) { + const closed = Math.min(1, Math.max(0, cover)); + if (closed <= 0.01) continue; + const bottom = T - closed * (T - S); + if (kind === "inside") panel(c.blinds, frame, x0 + 0.01, x1 - 0.01, inside + 0.04, bottom, T - 0.02, new Color(FABRIC), fold); + else if (kind === "venetian") slats(c, x0, x1, outside - 0.07, bottom, T, state.slats ?? 0); + else panel(c.blinds, frame, x0, x1, outside - 0.07, bottom, T, new Color(SHUTTER), fold, 0.045); + } +} + +/** Venetian slats from the top down to `bottom`, turned by how far they are open: level (1) shows the gaps, shut (0) a closed face. */ +function slats(c: Ctx, x0: number, x1: number, n: number, bottom: number, top: number, open: number): void { + const { frame, fold } = c; + const color = new Color(VENETIAN); + // the slat's angle from upright: shut slats hang almost upright and overlap, open ones lie level + const a = (Math.PI / 2) * (0.12 + 0.88 * Math.min(1, Math.max(0, open))); + const dn = (Math.sin(a) * SLAT_DEPTH) / 2; + const dy = (Math.cos(a) * SLAT_DEPTH) / 2; + for (let y = top - SLAT_STEP / 2; y > bottom; y -= SLAT_STEP) { + const bucket = y >= fold.cut ? fold.bucket : ALWAYS; + const [p, q, r, s] = [frame(x0, n - dn, y + dy), frame(x1, n - dn, y + dy), frame(x1, n + dn, y - dy), frame(x0, n + dn, y - dy)]; + c.blinds.tri(p, q, r, color, color, color, [0, 0.5, 1, 0.5, 1, 0.5], bucket); + c.blinds.tri(p, r, s, color, color, color, [0, 0.5, 1, 0.5, 0, 0.5], bucket); + } +} diff --git a/frontend/src/viewer/openings/context.ts b/frontend/src/viewer/openings/context.ts new file mode 100644 index 0000000..4e2b8a8 --- /dev/null +++ b/frontend/src/viewer/openings/context.ts @@ -0,0 +1,28 @@ +import type { OpeningInfo } from "../build.ts"; +import type { GeoBuffer } from "../geo.ts"; +import type { Fold, Frame } from "./primitives.ts"; +import type { OpeningState } from "./types.ts"; + +/** Everything the builders of one opening need. */ +export interface Ctx { + info: OpeningInfo; + state: OpeningState; + frame: Frame; + /** The middle between the room face and the outer face of the wall (in n). */ + mid: number; + /** Highlighted while closed (and a sensor knows), instead of while open. */ + markClosed: boolean; + fold: Fold; + frames: GeoBuffer; + glass: GeoBuffer; + blinds: GeoBuffer; + /** For a piece of a pane over several edges: whether it is the first or the last one, which carry the jambs. */ + first: boolean; + last: boolean; + /** + * How far the glass runs past each end of the piece, in metres, to meet the next piece of the pane: + * `[at its start, at its end]`. The glass sits in the middle of the wall, and two walls at an angle have + * two different middles, so the ends would otherwise stand a few centimetres apart and leave a slot. + */ + over: [number, number]; +} diff --git a/frontend/src/viewer/openings/doors.ts b/frontend/src/viewer/openings/doors.ts new file mode 100644 index 0000000..fe1d954 --- /dev/null +++ b/frontend/src/viewer/openings/doors.ts @@ -0,0 +1,118 @@ +// Doors and garage doors: the door frame, leaves that turn on their hinges or slide, sidelights, handles, sectional garage doors. + +import { Color } from "three"; +import { isFrontDoor, openingStyle, sidelightLayout } from "../../model.ts"; +import { ALWAYS, DEG, shade } from "../geo.ts"; +import type { Ctx } from "./context.ts"; +import { DOOR_ANGLE, FRAME, FRAME_TOP, GLASS, HANDLE, HANDLE_TOP, LEAF, LEAF_FRONT, LEAF_FRONT_TOP, LEAF_TOP, OPEN_WARM, SILL, UNLOCKED } from "./palette.ts"; +import { flatPanel, panel, splitBox, type Frame } from "./primitives.ts"; + +/** The frame (Zarge) around a door or garage opening, covering the reveal on both faces. An open garage door glows warm. */ +export function doorFrame(c: Ctx): void { + const { info, state, frame, fold } = c; + // B: the floor the door stands on – below 0 in a room set lower than its floor (floor_offset) + const [W, T, B] = [info.width, info.top, Math.min(0, info.sill)]; + const garageOpen = info.opening.type === "garage" && (c.markClosed ? !!state.sensed && (state.cover ?? 1) >= 0.95 : (state.cover ?? 1) < 0.95); + const side = garageOpen ? shade(OPEN_WARM, 0.8) : new Color(FRAME); + const top = garageOpen ? shade(OPEN_WARM, 1) : new Color(FRAME_TOP); + const [n0, n1] = [-info.faceOut - 0.012, info.faceRoom + 0.012]; + const piece = (x0: number, x1: number, y0: number) => splitBox(c.frames, frame, { x0, x1, n0, n1, y0, y1: T + 0.045 }, side, top, fold); + piece(-0.045, 0.02, B); + piece(W - 0.02, W + 0.045, B); + piece(0.02, W - 0.02, T - 0.02); +} + +/** A door: one leaf or two, each turning around its hinge (or sliding), with sidelights, a threshold and handles. */ +export function doorLeaves(c: Ctx): void { + const { info, state, frame, fold, mid } = c; + const [W, T, B] = [info.width, info.top, Math.min(0, info.sill)]; + const H = T - B; + const style = openingStyle(info.opening, info.exterior); + const passage = style === "passage"; + const front = isFrontDoor(style); + const swing = info.opening.swing === "out" ? -1 : 1; + // the leaves are flush with the face they swing towards (the room, or the other side) + const face = swing > 0 ? info.faceRoom : -info.faceOut; + const double = info.opening.leaves === 2; + const frameColor = new Color(FRAME); + const frameTop = new Color(FRAME_TOP); + + // fixed glass beside the leaf: one sidelight opposite the hinge, or one on each side + let x0 = 0.02; + let x1 = W - 0.02; + const lights = sidelightLayout(W, style, info.hingeAtStart, info.opening); + if (lights) { + for (const [a, b] of lights.panels) { + const post = (xa: number, xb: number, ya: number, yb: number) => splitBox(c.frames, frame, { x0: xa, x1: xb, n0: mid - 0.03, n1: mid + 0.03, y0: ya, y1: yb }, frameColor, frameTop, fold); + post(a, a + 0.04, B + 0.02, T - 0.02); + post(b - 0.04, b, B + 0.02, T - 0.02); + post(a, b, B + 0.02, B + 0.1); + panel(c.glass, frame, a + 0.04, b - 0.04, mid, B + 0.1, T - 0.02, GLASS, fold); + } + x0 = lights.x0; + x1 = lights.x1; + } + const leafWidth = double ? (x1 - x0) / 2 - 0.004 : x1 - x0; + const thickness = front ? 0.06 : 0.04; + if (front) { + // a threshold across the wall, and a small light over the door outside + splitBox(c.frames, frame, { x0: 0.02, x1: W - 0.02, n0: -info.faceOut - 0.02, n1: info.faceRoom, y0: B, y1: B + 0.02 }, new Color(SILL), frameTop, fold); + if (info.exterior) splitBox(c.frames, frame, { x0: W / 2 - 0.08, x1: W / 2 + 0.08, n0: -info.faceOut - 0.1, n1: -info.faceOut, y0: T + 0.1, y1: T + 0.17 }, shade(OPEN_WARM, 0.55), shade(OPEN_WARM, 0.85), { cut: fold.cut, bucket: ALWAYS }); + } + + // the leaf's full swing: its own opening angle, else the usual one + const swingAngle = info.opening.open_angle ? Math.min(180, Math.max(5, info.opening.open_angle)) * DEG : DOOR_ANGLE; + const leaves: [boolean, number][] = passage ? [] : [[info.hingeAtStart, state.open]]; + if (double && !passage) leaves.push([!info.hingeAtStart, state.open2 ?? 0]); + for (const [atStart, openness] of leaves) { + const open = Math.min(1, Math.max(0, openness)); + const theta = style === "sliding" ? 0 : open * swingAngle; + // a sliding leaf runs along the wall face past the hinge side instead of turning + const slide = style === "sliding" ? open * leafWidth : 0; + const leafFrame: Frame = (u, n, y) => { + const along = u * Math.cos(theta) - n * Math.sin(theta) - slide; + const across = face + swing * (n * Math.cos(theta) + u * Math.sin(theta) + (slide ? 0.05 : 0)); + return frame(atStart ? x0 + along : x1 - along, across, y); + }; + // an open leaf has left its wall: keep it visible when the wall folds away + const leafFold = { cut: fold.cut, bucket: open > 0.05 ? ALWAYS : fold.bucket }; + const warm = c.markClosed ? !!state.sensed && open < 0.05 : open > 0.9 && !(atStart === info.hingeAtStart && state.assumed); + const side = warm ? shade(OPEN_WARM, 0.7) : new Color(front ? LEAF_FRONT : LEAF); + const top = warm ? shade(OPEN_WARM, 0.9) : new Color(front ? LEAF_FRONT_TOP : LEAF_TOP); + const part = (xa: number, xb: number, ya: number, yb: number, na = -thickness, nb = 0) => splitBox(c.frames, leafFrame, { x0: xa, x1: xb, n0: na, n1: nb, y0: ya, y1: yb }, side, top, leafFold); + if (style === "glass") { + // a glass door: slim stiles and rails around a pane + part(0, 0.05, B + 0.01, T - 0.01); + part(leafWidth - 0.05, leafWidth, B + 0.01, T - 0.01); + part(0.05, leafWidth - 0.05, B + 0.01, B + 0.12); + part(0.05, leafWidth - 0.05, T - 0.08, T - 0.01); + panel(c.glass, leafFrame, 0.05, leafWidth - 0.05, -thickness / 2, B + 0.12, T - 0.08, GLASS, leafFold); + } else part(0, leafWidth, B + 0.01, T - 0.01); + if (style === "front_glass") panel(c.glass, leafFrame, 0.12, leafWidth - 0.12, 0.001, B + H * 0.55, T - 0.18, GLASS, leafFold); + else if (front) panel(c.glass, leafFrame, 0.1, 0.18, 0.001, B + 0.3, T - 0.3, GLASS, leafFold); + // a handle on both sides: a knob on a room door, a bar on a front door + const height = B + Math.min(1.05, H * 0.5); + const half = front ? 0.3 : 0.012; + const [hx0, hx1] = front ? [leafWidth - 0.11, leafWidth - 0.08] : [leafWidth - 0.16, leafWidth - 0.05]; + const handle = (na: number, nb: number) => splitBox(c.frames, leafFrame, { x0: hx0, x1: hx1, n0: na, n1: nb, y0: height - half, y1: height + half }, new Color(HANDLE), new Color(HANDLE_TOP), leafFold); + handle(0.004, 0.05); + handle(-thickness - 0.05, -thickness - 0.004); + // an unlocked smart lock: the leaf's free edge glows in the accent (cyan follows the user's accent colour) + if (state.unlocked) { + const glow = new Color(UNLOCKED); + splitBox(c.frames, leafFrame, { x0: leafWidth - 0.012, x1: leafWidth + 0.004, n0: -thickness - 0.004, n1: 0.004, y0: B + 0.06, y1: T - 0.06 }, glow, glow, { cut: fold.cut, bucket: ALWAYS }); + } + } +} + +/** A sectional garage door: the closed part hangs in the opening, the open part lies under the ceiling. */ +export function garageDoor(c: Ctx): void { + const { info, state, frame, fold } = c; + const [W, T, B] = [info.width, info.top, Math.min(0, info.sill)]; + const closed = Math.min(1, Math.max(0, state.cover ?? 1)); + const color = new Color(0xd4e0ff); + const plane = info.faceRoom - 0.03; + if (closed > 0.01) panel(c.blinds, frame, 0.02, W - 0.02, plane, B + (T - B) * (1 - closed), T, color, fold, 0.5); + const lifted = (1 - closed) * (T - B); + if (lifted > 0.01) flatPanel(c.blinds, frame, 0.02, W - 0.02, plane, plane + lifted, T + 0.03, color, fold.bucket, 0.5); +} diff --git a/frontend/src/viewer/openings/light-well.ts b/frontend/src/viewer/openings/light-well.ts new file mode 100644 index 0000000..1dc6314 --- /dev/null +++ b/frontend/src/viewer/openings/light-well.ts @@ -0,0 +1,46 @@ +// The light well in front of a cellar window: a concrete pit outside the window from below its sill up to the ground, with a grating +// on top at ground level. It comes by itself for an outer window whose sill lies below the ground, and can be switched off per window. + +import { Color } from "three"; +import { ALWAYS } from "../geo.ts"; +import type { Ctx } from "./context.ts"; +import { splitBox } from "./primitives.ts"; + +const CONCRETE = 0x4b5262; +const CONCRETE_TOP = 0x6b7386; +const GRATING = 0x2a303c; +const GRATING_TOP = 0x8a94a8; + +/** Whether a window gets a light well: outside, its sill below the ground (ground is in the floor's own coordinates). */ +export function needsLightWell(ctx: Pick, ground: number): boolean { + const { info } = ctx; + if (info.opening.type !== "window" || !info.exterior || info.opening.light_well === false) return false; + return info.opening.light_well === true || info.sill < ground - 0.02; +} + +/** A light well outside the window: three concrete walls, a floor and a grating at ground level. */ +export function lightWell(c: Ctx, ground: number): void { + const { info, frame } = c; + const fold = { cut: c.fold.cut, bucket: ALWAYS }; + const [w0, w1] = [-0.12, info.width + 0.12]; + const outer = -info.faceOut; + const depth = 0.7; + const bottom = Math.min(info.sill - 0.25, ground - 0.3); + const top = ground; + const side = new Color(CONCRETE); + const cap = new Color(CONCRETE_TOP); + const t = 0.07; + const wall = (x0: number, x1: number, n0: number, n1: number) => splitBox(c.frames, frame, { x0, x1, n0, n1, y0: bottom, y1: top }, side, cap, fold); + wall(w0 - t, w0, outer - depth, outer); + wall(w1, w1 + t, outer - depth, outer); + wall(w0 - t, w1 + t, outer - depth - t, outer - depth); + splitBox(c.frames, frame, { x0: w0, x1: w1, n0: outer - depth, n1: outer, y0: bottom - t, y1: bottom }, side, cap, fold); + // the grating: bars across the pit at ground level + const bar = (x0: number, x1: number) => splitBox(c.frames, frame, { x0, x1, n0: outer - depth, n1: outer, y0: top - 0.025, y1: top }, new Color(GRATING), new Color(GRATING_TOP), fold); + const bars = Math.max(3, Math.round((w1 - w0) / 0.06)); + for (let i = 0; i <= bars; i++) { + const x = w0 + ((w1 - w0) * i) / bars; + bar(x - 0.008, x + 0.008); + } + splitBox(c.frames, frame, { x0: w0, x1: w1, n0: outer - depth - 0.01, n1: outer - depth + 0.02, y0: top - 0.03, y1: top }, new Color(GRATING), new Color(GRATING_TOP), fold); +} diff --git a/frontend/src/viewer/openings/openings.test.ts b/frontend/src/viewer/openings/openings.test.ts new file mode 100644 index 0000000..1f2abeb --- /dev/null +++ b/frontend/src/viewer/openings/openings.test.ts @@ -0,0 +1,301 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { newFloor, type Opening } from "../../model.ts"; +import { buildFloorGeometry } from "../build.ts"; +import { buildOpeningParts, CLOSED, type OpeningState } from "../openings.ts"; +import { slidingPanes } from "./windows.ts"; +import { frontPieces } from "../../geometry/glass-front.ts"; + +const room = { id: "a", name: "a", area_id: null, points: [[0, 0], [6, 0], [6, 5], [0, 5]] as [number, number][], floor_material: "wood" as const }; + +function infosFor(opening: Partial) { + const full = { id: "o", room_id: "a", edge: 0, offset: 1.5, width: 1.2, type: "window", sill: 0.9, height: 1.3, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null, ...opening } as Opening; + return buildFloorGeometry({ ...newFloor("f", "F", 0), rooms: [room], openings: [full] }, 0.3, 0.1).openings; +} + +const triangles = (g: { getAttribute(n: string): { count: number } | undefined }) => (g.getAttribute("position")?.count ?? 0) / 3; +const build = (opening: Partial, state: Partial = {}, cut = 1.2) => buildOpeningParts(infosFor(opening), new Map([["o", { ...CLOSED, ...state }]]), cut); +const positions = (g: { getAttribute(n: string): { array: ArrayLike } | undefined }) => Array.from(g.getAttribute("position")?.array ?? []); + +test("a window has frame parts and glass, and no blind without a cover", () => { + const parts = build({}); + assert.ok(triangles(parts.frames) > 20); + assert.ok(triangles(parts.glass) >= 2); + assert.equal(triangles(parts.blinds), 0); +}); + +test("a blind adds a box above the window and slats down to the closed fraction", () => { + const without = build({}); + const up = build({}, { cover: 0 }); + const half = build({}, { cover: 0.5 }); + assert.ok(triangles(up.frames) > triangles(without.frames), "the blind box"); + assert.equal(triangles(up.blinds), 0, "raised: no slats"); + assert.ok(triangles(half.blinds) > 0); + const lowest = (parts: ReturnType) => Math.min(...positions(parts.blinds).filter((_, i) => i % 3 === 1)); + assert.ok(lowest(build({}, { cover: 1 })) < lowest(half), "further down when more closed"); +}); + +test("an open window swings its sash into the room, and a tilted one leans", () => { + const closed = positions(build({}).frames); + const open = positions(build({}, { open: 1 }).frames); + const tilted = positions(build({}, { tilt: 1 }).frames); + assert.equal(closed.length, open.length); + assert.notDeepEqual(closed, open); + assert.notDeepEqual(closed, tilted); + // the swung-open sash reaches into the room: further from the wall than any part of the closed window + const depth = (p: number[]) => Math.max(...p.filter((_, i) => i % 3 === 2)); + assert.ok(depth(open) > depth(closed)); +}); + +test("a double window has two sashes that move on their own", () => { + const single = triangles(build({ leaves: 1 }).frames); + const double = triangles(build({ leaves: 2 }).frames); + assert.ok(double > single); + assert.notDeepEqual(positions(build({ leaves: 2 }, { open: 1, open2: 0 }).frames), positions(build({ leaves: 2 }, { open: 0, open2: 1 }).frames)); +}); + +test("glazing bars add to the sash, a glass wall has mullions instead of sashes", () => { + assert.ok(triangles(build({ style: "bars" }).frames) > triangles(build({}).frames)); + const wall = build({ style: "glass_wall", width: 2.7, sill: 0, height: 2.4 }); + assert.ok(triangles(wall.glass) >= 3 * 2, "three panes"); +}); + +test("a door has a frame, a leaf and handles; a passage only a gap", () => { + const door = build({ type: "door", width: 0.9, sill: 0, height: 2.05 }); + assert.ok(triangles(door.frames) > 50); + const passage = build({ type: "door", style: "passage", width: 0.9, sill: 0, height: 2.05 }); + assert.equal(triangles(passage.frames), 0); + assert.equal(triangles(passage.glass), 0); +}); + +test("a door leaf swings around its hinge, a sliding one slides along the wall", () => { + const door = (state: Partial, extra: Partial = {}) => positions(build({ type: "door", width: 0.9, sill: 0, height: 2.05, ...extra }, state).frames); + assert.notDeepEqual(door({ open: 0 }), door({ open: 1 })); + const closed = door({ open: 0 }, { style: "sliding" }); + const slid = door({ open: 1 }, { style: "sliding" }); + const depth = (p: number[]) => Math.max(...p.filter((_, i) => i % 3 === 2)) - Math.min(...p.filter((_, i) => i % 3 === 2)); + assert.ok(Math.abs(depth(closed) - depth(slid)) < 0.1, "a sliding leaf stays in the wall's depth"); +}); + +test("front doors and glass doors have glass; room doors have none", () => { + const glassOf = (style: string) => triangles(build({ type: "door", style: style as never, width: 0.9, sill: 0, height: 2.05 }).glass); + assert.equal(glassOf("interior"), 0); + assert.ok(glassOf("front") > 0); + assert.ok(glassOf("front_glass") >= glassOf("front")); + assert.ok(glassOf("glass") > 0); + assert.ok(glassOf("sidelight") > 0, "a fixed pane beside the leaf"); +}); + +test("a garage door shows panels while closed and lifts them under the ceiling when open", () => { + const garage = (cover: number) => build({ type: "garage", width: 2.5, sill: 0, height: 2.1 }, { cover }); + assert.ok(triangles(garage(1).blinds) > 0); + assert.ok(triangles(garage(0).blinds) > 0, "the lifted part lies flat under the ceiling"); + assert.ok(triangles(garage(1).frames) > 0); +}); + +test("the triangle ranges say which opening each part belongs to", () => { + const infos = infosFor({}); + const parts = buildOpeningParts(infos, new Map(), 1.2); + assert.deepEqual(parts.frameTris.map((r) => r.id), ["o"]); + assert.equal(parts.frameTris[0].start, 0); + assert.equal(parts.frameTris[0].end, triangles(parts.frames)); + assert.equal(parts.glassTris[0].end, triangles(parts.glass)); +}); + +test("parts above the cut height carry the wall's fold bucket, the rest are always shown", () => { + const folds = (cut: number) => Array.from(build({}, {}, cut).frames.getAttribute("fold")!.array); + assert.ok(new Set(folds(10)).size === 1, "everything below the cut: always shown"); + assert.ok(new Set(folds(0.1)).size >= 1); + assert.ok(folds(1.2).includes(-1)); + assert.ok(folds(1.2).some((f) => f !== -1), "the part above the cut folds with the wall"); +}); + +test("an open window glows warm; with 'mark closed' the closed one does", () => { + const colorSum = (parts: ReturnType) => Array.from(parts.frames.getAttribute("color")!.array).reduce((a, b) => a + b, 0); + assert.ok(colorSum(build({}, { open: 1 })) > colorSum(build({}))); + const marked = (open: number) => colorSum(build({ mark: "closed" } as never, { open, sensed: true })); + assert.ok(marked(0) > marked(1)); +}); + +test("a sliding window: the pane at the hinge side slides in front of the fixed one; four panes with two leaves", () => { + const one = slidingPanes(2.4, 0.06, true, 1, 1, 0); + assert.equal(one.length, 2); + assert.ok(one[0].slide! > 1, "the moving pane runs about half the width"); + assert.equal(one[1].slide, 0); + assert.ok(one[0].x1 > one[1].x0, "the panes overlap in the middle"); + const four = slidingPanes(3.2, 0.06, true, 2, 1, 1); + assert.deepEqual(four.map((p) => Math.sign(p.slide!)), [0, -1, 1, 0]); + const mirrored = slidingPanes(2.4, 0.06, false, 1, 1, 0); + assert.ok(mirrored[1].slide! < 0 && mirrored[0].slide === 0); +}); + +test("an open sliding door stays in the wall and moves along it; a top-hung window swings out at the bottom", () => { + const door = { opens: "slide" as const, sill: 0, height: 2.15, width: 2.4 }; + const closed = positions(build(door).frames); + const open = positions(build(door, { open: 1 }).frames); + const depth = (p: number[]) => Math.max(...p.filter((_, i) => i % 3 === 2)); + assert.notDeepEqual(closed, open); + assert.ok(depth(open) <= depth(closed) + 1e-6, "no part reaches into the room"); + const top = { opens: "top" as const }; + const out = (p: number[]) => Math.min(...p.filter((_, i) => i % 3 === 2)); + assert.ok(out(positions(build(top, { open: 1 }).frames)) < out(positions(build(top).frames)) - 0.1, "the bottom leaves the wall towards outside"); + // a tilt sensor opens a top-hung window as well + assert.notDeepEqual(positions(build(top, { tilt: 1 }).frames), positions(build(top).frames)); +}); + +test("a door in a lowered room stands on that room's floor, not on the floor level", () => { + const lowered = { ...room, floor_offset: -0.39 }; + const opening = { id: "o", room_id: "a", edge: 0, offset: 1.5, width: 0.9, type: "door", sill: 0, height: 1.87, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null } as Opening; + const infos = buildFloorGeometry({ ...newFloor("f", "F", 0), rooms: [lowered], openings: [opening] }, 0.3, 0.1).openings; + const parts = buildOpeningParts(infos, new Map([["o", CLOSED]]), 1.2); + const ys = positions(parts.frames).filter((_, i) => i % 3 === 1); + assert.ok(Math.abs(Math.min(...ys) - -0.39) < 0.02, `lowest part at ${Math.min(...ys)}`); +}); + +test("a glass wall divides into about 0.9 m panes unless it is told how many", () => { + const wall = (panes?: number | null) => build({ type: "window", sill: 0, height: 2.4, width: 3.6, style: "glass_wall", ...(panes === undefined ? {} : { panes }) }); + const auto = wall(); + const one = wall(0); + const three = wall(3); + // one pane: no mullion at all, so fewer frame boxes and a single sheet of glass + assert.ok(triangles(one.frames) < triangles(auto.frames), "a single pane has no mullions"); + assert.equal(triangles(one.glass), 4, "one pane is one quad, glazed on both sides"); + // a number of its own wins over the automatic spacing + assert.ok(triangles(three.frames) < triangles(auto.frames)); + assert.ok(triangles(three.frames) > triangles(one.frames), "three panes have two mullions"); + assert.equal(triangles(three.glass), 12, "three panes"); + // an unchanged plan keeps exactly what it drew before: the automatic spacing + assert.equal(triangles(auto.glass), 16, "3.6 m gives four panes of about 0.88 m"); +}); + +/** A curved wall: ten edges of 1 m, each turning 10 degrees the same way, closed by one back edge. */ +function curvedRoom() { + const points: [number, number][] = [[0, 0]]; + let [x, z, a] = [0, 0, 0]; + for (let i = 0; i < 10; i++) { + a += (10 * Math.PI) / 180; + x += Math.cos(a); + z += Math.sin(a); + points.push([x, z]); + } + return { ...room, points }; +} + +/** Six pieces of one pane on that wall, in the order the plan lists them. */ +function pane(backwards = false) { + const curved = curvedRoom(); + const pieces = frontPieces(curved, 0, 6)!; + const list = pieces.map( + (p, k) => + ({ + id: `g${k}`, + room_id: "a", + edge: p.edge, + offset: p.offset, + width: p.width, + front: "f", + type: "window", + sill: 0, + height: 2.4, + style: "glass_wall", + hinge: "left", + leaves: 1, + swing: "in", + cover: null, + contact: null, + contact2: null, + tilt: null, + }) as Opening, + ); + // the order the openings are listed in is the order the plan happens to hold them, which on a curved + // wall is not necessarily the order along the outline + return buildFloorGeometry({ ...newFloor("f", "F", 0), rooms: [curved], openings: backwards ? list.reverse() : list }, 0.3, 0.1).openings; +} + +/** The plan points where two pieces of one pane meet, and the two outer ends of the pane. */ +function paneEnds(infos: readonly { start: [number, number]; axis: [number, number]; width: number }[]) { + const key = (p: [number, number]) => `${Math.round(p[0] * 50)},${Math.round(p[1] * 50)}`; + const end = (i: number): [number, number] => [infos[i].start[0] + infos[i].axis[0] * infos[i].width, infos[i].start[1] + infos[i].axis[1] * infos[i].width]; + const count = new Map(); + const at = new Map(); + infos.forEach((_, i) => { + for (const p of [infos[i].start as [number, number], end(i)]) { + count.set(key(p), (count.get(key(p)) ?? 0) + 1); + at.set(key(p), p); + } + }); + const joins = [...count].filter(([, n]) => n > 1).map(([k]) => at.get(k)!); + const outer = [...count].filter(([, n]) => n === 1).map(([k]) => at.get(k)!); + return { joins, outer }; +} + +/** One pane must be one sheet: no slot between its pieces and no frame standing in it. */ +function assertOneSheet(infos: ReturnType) { + const joined = buildOpeningParts(infos, new Map([["f", CLOSED]]), 1.2); + const gp = positions(joined.glass); + const fp = positions(joined.frames); + const { joins, outer } = paneEnds(infos); + assert.equal(joins.length, infos.length - 1, "one join between each two pieces, and none at the outer ends"); + assert.equal(outer.length, 2, "a pane has two outer ends"); + for (const [jx, jz] of joins) { + // the glass sits in the middle of the wall, so two walls at an angle have two different middles, and + // ends that stop at their own middle stand 2.6 cm apart on a 10 degree bend — a slot through the pane + const near: [number, number, number][] = []; + // the glass stands in the middle of the wall, half a thickness off the axis the join sits on + for (let i = 0; i + 2 < gp.length; i += 3) if (Math.hypot(gp[i] - jx, gp[i + 2] - jz) < 0.2) near.push([gp[i], gp[i + 1], gp[i + 2]]); + let worst = 0; + // in plan only: two vertices on one vertical line are the same point of the sheet, whatever their height + for (const a of near) for (const b of near) worst = Math.max(worst, Math.hypot(a[0] - b[0], a[2] - b[2])); + assert.ok(near.length > 0, "the pieces reach the join"); + assert.ok(worst < 0.002, `the two pieces meet at (${jx.toFixed(2)},${jz.toFixed(2)}), not ${worst.toFixed(3)} m apart`); + // a jamb drawn at a join is a 4 cm post standing in the middle of the glass + let post = 0; + for (let i = 0; i + 2 < fp.length; i += 3) { + if (fp[i + 1] < 0.1 || fp[i + 1] > 2.3) continue; + if (Math.hypot(fp[i] - jx, fp[i + 2] - jz) < 0.2) post++; + } + assert.equal(post, 0, "no frame stands in the glass at a join"); + } + for (const [ox, oz] of outer) { + let jamb = 0; + for (let i = 0; i + 2 < fp.length; i += 3) { + if (fp[i + 1] < 0.1 || fp[i + 1] > 2.3) continue; + if (Math.hypot(fp[i] - ox, fp[i + 2] - oz) < 0.2) jamb++; + } + assert.ok(jamb > 0, "the outer ends of a pane do carry a jamb"); + } +} + +test("a pane over several edges is glazed as one, without jambs where its pieces meet", () => { + const infos = pane(); + // every piece finds its own wall: none is dropped + assert.equal(infos.length, 6); + const joined = buildOpeningParts(infos, new Map([["f", CLOSED]]), 1.2); + const apart = buildOpeningParts( + infos.map((i) => ({ ...i, opening: { ...i.opening, front: null } })), + new Map(), + 1.2, + ); + assert.ok(triangles(joined.frames) < triangles(apart.frames), "no jamb where two pieces of one pane meet"); + // the glass itself stays the same, however the pieces are grouped + assert.equal(triangles(joined.glass), triangles(apart.glass)); + assertOneSheet(infos); +}); + +test("the order the plan lists the pieces in does not decide where the jambs go", () => { + // the openings of a curved wall are stored in the order the plan holds them, which is not always the + // order along the outline. Taking the first and the last of that list as the pane's ends puts both + // jambs of a two-piece pane right where the two pieces meet. + const infos = pane(true); + assert.equal(infos.length, 6); + assertOneSheet(infos); +}); + +test("a garage door with a cover gets no roller blind in front of it (#85)", () => { + const door = build({ type: "garage", width: 2.5, sill: 0, height: 2.1 }, { cover: 1 }); + const panelOnly = build({ type: "garage", width: 2.5, sill: 0, height: 2.1 }, { cover: 1, cover2: null }); + assert.equal(triangles(door.blinds), triangles(panelOnly.blinds)); + // the outside blind box (cassette above the opening) is not drawn: no frame part reaches 0.2 m above the top + const ys = positions(door.frames).filter((_, i) => i % 3 === 1); + assert.ok(Math.max(...ys) < 2.1 + 0.15, "no blind cassette above a garage door"); +}); diff --git a/frontend/src/viewer/openings/palette.ts b/frontend/src/viewer/openings/palette.ts new file mode 100644 index 0000000..91c5afb --- /dev/null +++ b/frontend/src/viewer/openings/palette.ts @@ -0,0 +1,27 @@ +// Colours and angles of doors and windows. + +import { shade } from "../geo.ts"; + +export const FRAME = 0x1f3052; +export const FRAME_TOP = 0x2a4270; +export const SASH = 0x22375f; +export const SILL = 0x1c2a47; +export const BLIND_BOX = 0x16223a; +/** The warm glow of a window or door that is open, or that should be closed. */ +export const OPEN_WARM = 0xffb547; +export const LEAF = 0x1c2c4d; +export const LEAF_TOP = 0x27406b; +export const LEAF_FRONT = 0x111a30; +export const LEAF_FRONT_TOP = 0x1c2a47; +/** The free edge of a door whose smart lock is unlocked: the stock cyan, which the neon look turns into the user's accent. */ +export const UNLOCKED = 0x37e0ff; +export const HANDLE = 0x5b7cff; +export const HANDLE_TOP = 0x8aa2ff; +export const GLASS = shade(0x37e0ff, 0.08); + +/** How far a window sash swings open, how far a door leaf, and how far a tilted sash leans (radians). */ +export const OPEN_ANGLE = 1.2; +export const DOOR_ANGLE = 1.5; +export const TILT_ANGLE = 0.2; +/** How far a top-hung sash swings out at the bottom when open (about 30°). */ +export const TOP_HUNG_ANGLE = 0.52; diff --git a/frontend/src/viewer/openings/parts.ts b/frontend/src/viewer/openings/parts.ts new file mode 100644 index 0000000..26f8688 --- /dev/null +++ b/frontend/src/viewer/openings/parts.ts @@ -0,0 +1,114 @@ +// The moving and state-dependent parts of doors and windows: fixed frames, sashes with glass (open or tilted, from contact +// sensors), window sills, door frames, blind boxes and blind slats. They are rebuilt as merged geometry whenever a state +// changes (and during the short open/close animation), so all windows of a floor stay three draw calls: frames, glass and blinds. + +import { openingStyle, type Vec2 } from "../../model.ts"; +import type { OpeningInfo } from "../build.ts"; +import { GeoBuffer } from "../geo.ts"; +import { blind } from "./blinds.ts"; +import type { Ctx } from "./context.ts"; +import { doorFrame, doorLeaves, garageDoor } from "./doors.ts"; +import { lightWell, needsLightWell } from "./light-well.ts"; +import { CLOSED, type OpeningParts, type OpeningState, type TriRange } from "./types.ts"; +import { glassWall, window } from "./windows.ts"; + +/** The id that groups the pieces of one glass pane; a normal opening is a group of its own. */ +const paneOf = (info: OpeningInfo): string => info.opening.front ?? info.opening.id; + +export function buildOpeningParts(infos: readonly OpeningInfo[], states: ReadonlyMap, cut: number, ground = -Infinity): OpeningParts { + const frames = new GeoBuffer(); + const glass = new GeoBuffer(); + const blinds = new GeoBuffer(true); + const frameTris: TriRange[] = []; + const glassTris: TriRange[] = []; + const blindTris: TriRange[] = []; + + // pieces of one pane that follows a curved wall: only the two outer ends get a jamb, so the glass is + // continuous where two of them meet. Every other opening is a group of one and keeps both jambs. + const groups = new Map(); + infos.forEach((info, i) => { + const key = paneOf(info); + groups.set(key, [...(groups.get(key) ?? []), i]); + }); + // Which end is an outer end does not follow from the order of the plan: the pieces of one pane are + // stored in whatever order the openings happen to be listed, and on a curved wall that is often not the + // order along the outline. It follows from the geometry instead — an end that another piece of the same + // pane meets is a join, not the end of the pane. Getting this wrong draws both jambs of a two-piece + // pane right at the join between them, which is a 4 cm post standing in the middle of the glass. + const endsOf = (info: OpeningInfo): [Vec2, Vec2] => [ + [info.start[0], info.start[1]], + [info.start[0] + info.axis[0] * info.width, info.start[1] + info.axis[1] * info.width], + ]; + const keyOf = (p: Vec2) => `${Math.round(p[0] * 50)},${Math.round(p[1] * 50)}`; + const ends = new Map(); + // Two walls at an angle have two different middles, so the ends of two pieces of one pane stand + // 2 * mid * sin(angle/2) apart — 2.6 cm on a 10 degree bend, which reads as a slot through the glass. + // Running each piece into the bisector of the bend (mid * tan(angle/2)) puts both end edges on the same + // vertical line, and the pane is one surface again. A real corner is left alone: there the miter would + // be longer than the wall is thick, and a corner is allowed to look like a corner. + const over = new Map(); + for (const list of groups.values()) { + const startsAt = new Map(); + const endsAt = new Map(); + for (const i of list) { + const [s, e] = endsOf(infos[i]); + startsAt.set(keyOf(s), [...(startsAt.get(keyOf(s)) ?? []), i]); + endsAt.set(keyOf(e), [...(endsAt.get(keyOf(e)) ?? []), i]); + } + const reach = (i: number, other: number | undefined) => { + if (other == null || other === i) return 0; + const mid = Math.abs((infos[i].faceRoom - infos[i].faceOut) / 2); + const [a, b] = [infos[i].axis, infos[other].axis]; + const cos = Math.max(-1, Math.min(1, a[0] * b[0] + a[1] * b[1])); + const angle = Math.acos(cos); + return angle < Math.PI / 2 ? Math.min(mid * Math.tan(angle / 2), mid) : 0; + }; + for (const i of list) { + const [s, e] = endsOf(infos[i]); + const before = (endsAt.get(keyOf(s)) ?? []).find((j) => j !== i); + const after = (startsAt.get(keyOf(e)) ?? []).find((j) => j !== i); + ends.set(i, [before == null, after == null]); + over.set(i, [reach(i, before), reach(i, after)]); + } + } + + for (let i = 0; i < infos.length; i++) { + const info = infos[i]; + const starts = { frames: frames.count, glass: glass.count, blinds: blinds.count }; + const type = info.opening.type; + const style = openingStyle(info.opening, info.exterior); + const [first, last] = ends.get(i) ?? [true, true]; + const ctx: Ctx = { + info, + state: states.get(paneOf(info)) ?? CLOSED, + // local frame: x from the opening's start along the wall, n from the wall axis towards the room + frame: (x, n, y) => [info.start[0] + info.axis[0] * x + info.toRoom[0] * n, y, info.start[1] + info.axis[1] * x + info.toRoom[1] * n], + mid: (info.faceRoom - info.faceOut) / 2, + // highlighted while open, or while closed when the opening asks for it (and a sensor knows) + markClosed: info.opening.mark === "closed", + fold: { cut, bucket: info.bucket }, + frames, + glass, + blinds, + first, + last, + over: over.get(i) ?? [0, 0], + }; + // a passage (a wall opening without a door) shows nothing but the gap in the wall + if ((type === "door" && style !== "passage") || type === "garage") doorFrame(ctx); + if (type === "door") doorLeaves(ctx); + else if (type === "garage") garageDoor(ctx); + else if (style === "glass_wall") glassWall(ctx); + else window(ctx); + // a cellar window below the ground gets its light well + if (needsLightWell(ctx, ground)) lightWell(ctx, ground); + // a garage door's cover moves the door itself; it has no blind in front of it (#85) + if (type !== "garage") blind(ctx); + // picking returns the id the model knows, not a piece id + const id = paneOf(info); + frameTris.push({ id, start: starts.frames, end: frames.count }); + glassTris.push({ id, start: starts.glass, end: glass.count }); + blindTris.push({ id, start: starts.blinds, end: blinds.count }); + } + return { frames: frames.geometry(), glass: glass.geometry(), blinds: blinds.geometry(), frameTris, glassTris, blindTris }; +} diff --git a/frontend/src/viewer/openings/primitives.ts b/frontend/src/viewer/openings/primitives.ts new file mode 100644 index 0000000..bcd6bc4 --- /dev/null +++ b/frontend/src/viewer/openings/primitives.ts @@ -0,0 +1,74 @@ +// Building blocks for the moving parts of doors and windows. Everything is placed in a local frame of an opening: x runs +// along the opening from its start, n points from the wall axis towards the room, y is up. + +import { Color } from "three"; +import { ALWAYS, shade, type GeoBuffer } from "../geo.ts"; + +/** Maps a local (x, n, y) to world coordinates. */ +export type Frame = (x: number, n: number, y: number) => number[]; + +export interface Box { + x0: number; + x1: number; + n0: number; + n1: number; + y0: number; + y1: number; +} + +/** A box with all six faces; the lower, near and side faces are a little darker than the top and the far face. */ +export function box(buf: GeoBuffer, frame: Frame, b: Box, side: Color, top: Color, fold: number): void { + const p = (x: number, n: number, y: number) => frame(x, n, y); + const { x0, x1, n0, n1, y0, y1 } = b; + const tint = (k: number) => shade(side.getHex(), k); + const faces: [number[], number[], number[], number[], Color][] = [ + [p(x0, n0, y1), p(x1, n0, y1), p(x1, n1, y1), p(x0, n1, y1), top], + [p(x0, n0, y0), p(x1, n0, y0), p(x1, n1, y0), p(x0, n1, y0), tint(0.6)], + [p(x0, n1, y0), p(x1, n1, y0), p(x1, n1, y1), p(x0, n1, y1), side], + [p(x0, n0, y0), p(x1, n0, y0), p(x1, n0, y1), p(x0, n0, y1), tint(0.85)], + [p(x0, n0, y0), p(x0, n1, y0), p(x0, n1, y1), p(x0, n0, y1), tint(0.92)], + [p(x1, n0, y0), p(x1, n1, y0), p(x1, n1, y1), p(x1, n0, y1), tint(0.92)], + ]; + for (const [a, b2, c, d, color] of faces) { + buf.tri(a, b2, c, color, color, color, undefined, fold); + buf.tri(a, c, d, color, color, color, undefined, fold); + } +} + +/** The cut height and the fold bucket of the wall a part sits in: what lies above the cut folds away with the wall. */ +export interface Fold { + cut: number; + bucket: number; +} + +/** A box split at the cut height: the part above folds away with its wall. */ +export function splitBox(buf: GeoBuffer, frame: Frame, b: Box, side: Color, top: Color, { cut, bucket }: Fold): void { + if (b.y1 <= cut + 1e-6) return box(buf, frame, b, side, top, ALWAYS); + if (b.y0 >= cut - 1e-6) return box(buf, frame, b, side, top, bucket); + box(buf, frame, { ...b, y1: cut }, side, top, ALWAYS); + box(buf, frame, { ...b, y0: cut }, side, top, bucket); +} + +/** A flat upright quad in a local plane (glass, slats), split at the cut height, with optional uvs (`vScale` metres per texture repeat). */ +export function panel(buf: GeoBuffer, frame: Frame, x0: number, x1: number, n: number, y0: number, y1: number, color: Color, { cut, bucket }: Fold, vScale = 0): void { + const piece = (ya: number, yb: number, fold: number) => { + const v = (y: number) => (vScale ? (y1 - y) / vScale : 0.5); + const [a, b, c, d] = [frame(x0, n, ya), frame(x1, n, ya), frame(x1, n, yb), frame(x0, n, yb)]; + buf.tri(a, b, c, color, color, color, [0, v(ya), 1, v(ya), 1, v(yb)], fold); + buf.tri(a, c, d, color, color, color, [0, v(ya), 1, v(yb), 0, v(yb)], fold); + }; + if (y1 <= cut + 1e-6) piece(y0, y1, ALWAYS); + else if (y0 >= cut - 1e-6) piece(y0, y1, bucket); + else { + piece(y0, cut, ALWAYS); + piece(cut, y1, bucket); + } +} + +/** A horizontal quad in the local frame at height y (the open part of a garage door). */ +export function flatPanel(buf: GeoBuffer, frame: Frame, x0: number, x1: number, n0: number, n1: number, y: number, color: Color, fold: number, vScale: number): void { + const [a, b, c, d] = [frame(x0, n0, y), frame(x1, n0, y), frame(x1, n1, y), frame(x0, n1, y)]; + const v1 = (n1 - n0) / vScale; + buf.tri(a, b, c, color, color, color, [0, 0, 1, 0, 1, v1], fold); + buf.tri(a, c, d, color, color, color, [0, 0, 1, v1, 0, v1], fold); +} diff --git a/frontend/src/viewer/openings/types.ts b/frontend/src/viewer/openings/types.ts new file mode 100644 index 0000000..82c2ab2 --- /dev/null +++ b/frontend/src/viewer/openings/types.ts @@ -0,0 +1,42 @@ +import type { BufferGeometry } from "three"; + +export interface OpeningState { + /** A window sash or door leaf: 0 closed, 1 swung open. */ + open: number; + /** The second leaf of a double door or window. */ + open2?: number; + /** 0 closed, 1 tilted. */ + tilt: number; + /** The second leaf tilted. */ + tilt2?: number; + /** The closed fraction of the blind or garage door (0 up, 1 down); null: no blind. */ + cover: number | null; + /** A sensor reports the state (contact, tilt sensor or cover); without one "closed" is a guess. */ + sensed?: boolean; + /** A door with a smart lock that stands unlocked: its free edge glows. */ + unlocked?: boolean; + /** The door leaf stands where it is assumed to, as no sensor tells: it does not glow as open. */ + assumed?: boolean; + /** The second blind of a wide window (its right half): its closed fraction. */ + cover2?: number | null; + /** Venetian blinds: how far the slats are open (0 shut, 1 level). */ + slats?: number | null; +} + +export const CLOSED: OpeningState = { open: 0, open2: 0, tilt: 0, tilt2: 0, cover: null }; + +export interface TriRange { + id: string; + start: number; + end: number; +} + +export interface OpeningParts { + frames: BufferGeometry; + glass: BufferGeometry; + blinds: BufferGeometry; + /** The triangle ranges per opening in frames, glass and blinds, so they can be tapped in 3D. */ + frameTris: TriRange[]; + glassTris: TriRange[]; + blindTris: TriRange[]; +} diff --git a/frontend/src/viewer/openings/windows.ts b/frontend/src/viewer/openings/windows.ts new file mode 100644 index 0000000..04a0271 --- /dev/null +++ b/frontend/src/viewer/openings/windows.ts @@ -0,0 +1,169 @@ +// Windows: the fixed frame, sill and board, sashes that turn into the room or tilt, slide (a lift-and-slide door) or swing out +// at the bottom (top-hung), glazing bars, and indoor glass walls. + +import { Color } from "three"; +import { openingStyle } from "../../model.ts"; +import { ALWAYS, shade } from "../geo.ts"; +import type { Ctx } from "./context.ts"; +import { FRAME, FRAME_TOP, GLASS, OPEN_ANGLE, OPEN_WARM, SASH, SILL, TILT_ANGLE, TOP_HUNG_ANGLE } from "./palette.ts"; +import { panel, splitBox, type Frame } from "./primitives.ts"; + +/** + * An indoor glass wall: a slim frame, glass from the floor up, no sashes. The mullions divide it into as many panes as the + * opening asks for; without a number they come about every 0.9 m, and none at all for a single full pane. + */ +export function glassWall(c: Ctx): void { + const { info, frame, fold, mid } = c; + const [W, S, T] = [info.width, info.sill, info.top]; + const [fw, fd] = [0.04, 0.025]; + const frameColor = new Color(FRAME); + const frameTop = new Color(FRAME_TOP); + const bar = (x0: number, x1: number, y0: number, y1: number) => splitBox(c.frames, frame, { x0, x1, n0: mid - fd, n1: mid + fd, y0, y1 }, frameColor, frameTop, fold); + // a pane over several edges has jambs only at its two outer ends; where two pieces meet, the glass runs on + if (c.first) bar(0, fw, S, T); + if (c.last) bar(W - fw, W, S, T); + // the 4 cm at each end is the rebate of a jamb. A piece of a pane that does not end here has no jamb, so + // its rails and its glass reach the wall end — and run past it into the bisector of the bend, where the + // next piece begins: two pieces whose ends stop at their own wall's middle stand a slot apart. + const [xa, xb] = [c.first ? fw : -c.over[0], c.last ? W - fw : W + c.over[1]]; + bar(xa, xb, S, S + 0.03); + bar(xa, xb, T - fw, T); + // a piece of a pane over several edges is part of one sheet: it gets no mullions of its own, and a pane + // that is to be divided is placed as separate openings instead (their jambs are the divisions) + const asked = info.opening.front ? 0 : info.opening.panes; + const panes = Math.max(1, asked == null ? Math.max(1, Math.round((xb - xa) / 0.9)) : Math.round(asked)); + const paneWidth = (xb - xa) / panes; + for (let k = 1; k < panes; k++) bar(xa + k * paneWidth - 0.02, xa + k * paneWidth + 0.02, S + 0.03, T - fw); + for (let k = 0; k < panes; k++) { + const x0 = xa + k * paneWidth + (k ? 0.02 : 0); + const x1 = xa + (k + 1) * paneWidth - (k < panes - 1 ? 0.02 : 0); + panel(c.glass, frame, x0, x1, mid, S + 0.03, T - fw, GLASS, fold); + } +} + +interface Sash { + atStart: boolean; + x0: number; + x1: number; + open: number; + tilt: number; + /** A sliding window's pane: how far it moves along the wall when fully open, and its track (0: the fixed panes, further out). */ + slide?: number; + track?: 0 | 1; +} + +/** + * The panes of a sliding window or lift-and-slide door. One leaf: the pane at the hinge side slides in front of the fixed one. + * Two leaves: four panes, the middle two slide outwards in front of the fixed outer ones, each on its own contact. + */ +export function slidingPanes(W: number, fw: number, hingeAtStart: boolean, leaves: 1 | 2, open: number, open2: number): Sash[] { + const inner = W - 2 * fw; + const overlap = 0.04; + if (leaves === 2) { + const pane = inner / 4 + overlap / 2; + const run = pane - overlap - 0.02; + return [ + { atStart: true, x0: fw, x1: fw + pane, open: 0, tilt: 0, slide: 0, track: 0 }, + { atStart: true, x0: fw + inner / 4 - overlap / 2, x1: fw + inner / 2, open: hingeAtStart ? open : open2, tilt: 0, slide: -run, track: 1 }, + { atStart: false, x0: fw + inner / 2, x1: W - fw - inner / 4 + overlap / 2, open: hingeAtStart ? open2 : open, tilt: 0, slide: run, track: 1 }, + { atStart: false, x0: W - fw - pane, x1: W - fw, open: 0, tilt: 0, slide: 0, track: 0 }, + ]; + } + const half = inner / 2; + const run = half - overlap - 0.02; + // the moving pane at the hinge side slides towards the fixed one + return hingeAtStart + ? [ + { atStart: true, x0: fw, x1: fw + half + overlap / 2, open, tilt: 0, slide: run, track: 1 }, + { atStart: false, x0: fw + half - overlap / 2, x1: W - fw, open: 0, tilt: 0, slide: 0, track: 0 }, + ] + : [ + { atStart: true, x0: fw, x1: fw + half + overlap / 2, open: 0, tilt: 0, slide: 0, track: 0 }, + { atStart: false, x0: fw + half - overlap / 2, x1: W - fw, open, tilt: 0, slide: -run, track: 1 }, + ]; +} + +/** A normal window: the fixed frame in the middle of the wall, a board inside and a sill outside, and one or two sashes. */ +export function window(c: Ctx): void { + const { info, state, frame, fold, mid } = c; + const [W, S, T] = [info.width, info.sill, info.top]; + const [fw, fd] = [0.06, 0.035]; + const frameColor = new Color(FRAME); + const frameTop = new Color(FRAME_TOP); + const sillColor = new Color(SILL); + const bar = (x0: number, x1: number, y0: number, y1: number) => splitBox(c.frames, frame, { x0, x1, n0: mid - fd, n1: mid + fd, y0, y1 }, frameColor, frameTop, fold); + const lowerBar = S + (S > 0.05 ? fw : 0.03); + bar(0, fw, S, T); + bar(W - fw, W, S, T); + bar(fw, W - fw, S, lowerBar); + bar(fw, W - fw, T - fw, T); + // a window board inside and a sill outside (automatic: both above 30 cm; or as chosen for this window) + const boards = info.opening.sill_boards ?? "auto"; + if (boards !== "none" && (boards !== "auto" || S > 0.3)) { + if (boards !== "outside") splitBox(c.frames, frame, { x0: -0.04, x1: W + 0.04, n0: mid + fd, n1: info.faceRoom + 0.07, y0: S - 0.03, y1: S }, sillColor, frameTop, fold); + if (info.exterior && boards !== "inside") splitBox(c.frames, frame, { x0: -0.03, x1: W + 0.03, n0: -info.faceOut - 0.06, n1: mid - fd, y0: S - 0.04, y1: S - 0.02 }, sillColor, frameTop, fold); + } + + // sashes rotate into the room around their hinge, or tilt around their bottom edge; a double window (or French door) has + // two sashes meeting in the middle, each tilting on its own + const barWidth = 0.055; + const [sy0, sy1] = [lowerBar, T - fw]; + const [n0, n1] = [mid + fd, mid + fd + 0.06]; + const hinge = info.hingeAtStart; + const opens = info.opening.opens ?? "turn"; + const sashes: Sash[] = + opens === "slide" + ? slidingPanes(W, fw, hinge, info.opening.leaves, state.open, state.open2 ?? 0) + : info.opening.leaves === 2 + ? [ + { atStart: hinge, x0: hinge ? fw : W / 2, x1: hinge ? W / 2 : W - fw, open: state.open, tilt: state.tilt }, + { atStart: !hinge, x0: hinge ? W / 2 : fw, x1: hinge ? W - fw : W / 2, open: state.open2 ?? 0, tilt: state.tilt2 ?? 0 }, + ] + : [{ atStart: hinge, x0: fw, x1: W - fw, open: state.open, tilt: state.tilt }]; + const style = openingStyle(info.opening, info.exterior); + for (const sash of sashes) { + // a top-hung sash opens with its contact or a tilt sensor alike; a fixed pane never glows + const swingOut = opens === "top" ? Math.max(sash.open, sash.tilt) * TOP_HUNG_ANGLE : 0; + const moves = opens !== "slide" || !!sash.slide; + const ajar = moves && (sash.open > 0.02 || sash.tilt > 0.02); + const alert = c.markClosed ? !!state.sensed && !ajar : ajar; + const side = alert ? shade(OPEN_WARM, 0.75) : new Color(SASH); + const top = alert ? shade(OPEN_WARM, 0.95) : frameTop; + const sashWidth = sash.x1 - sash.x0; + const turning = opens === "turn"; + const theta = turning ? sash.open * OPEN_ANGLE : 0; + const lean = turning ? sash.tilt * TILT_ANGLE : 0; + // a sliding pane runs in the sash plane; the fixed panes of a sliding window sit one track further out, so it passes in front of them + const shift = (sash.slide ?? 0) * sash.open; + const track = opens === "slide" && sash.track === 0 ? -0.065 : 0; + // sash coordinates: u from the hinge across the sash, then n and y + const sashFrame: Frame = (u, n, y) => { + if (swingOut > 0) { + // top-hung: turned about the sash's top edge, so its bottom swings out of the wall (towards -n) + const [dn, dy] = [n - n0, y - sy1]; + const [c, s] = [Math.cos(swingOut), Math.sin(swingOut)]; + return frame(sash.atStart ? sash.x0 + u : sash.x1 - u, n0 + dn * c + dy * s, sy1 - dn * s + dy * c); + } + const dy = y - sy0; + const tilted = n + dy * Math.sin(lean) + track; + const yy = sy0 + dy * Math.cos(lean); + const along = u * Math.cos(theta) - (tilted - n0) * Math.sin(theta); + const across = n0 + (tilted - n0) * Math.cos(theta) + u * Math.sin(theta); + return frame((sash.atStart ? sash.x0 + along : sash.x1 - along) + shift, across, yy); + }; + // a sash that has swung into the room (or out of the wall) belongs to no wall: keep it visible + const sashFold = { cut: fold.cut, bucket: theta > 0.05 || swingOut > 0.05 ? ALWAYS : fold.bucket }; + const part = (xa: number, xb: number, ya: number, yb: number, na = n0, nb = n1) => splitBox(c.frames, sashFrame, { x0: xa, x1: xb, n0: na, n1: nb, y0: ya, y1: yb }, side, top, sashFold); + part(0, barWidth, sy0, sy1); + part(sashWidth - barWidth, sashWidth, sy0, sy1); + part(barWidth, sashWidth - barWidth, sy0, sy0 + barWidth); + part(barWidth, sashWidth - barWidth, sy1 - barWidth, sy1); + panel(c.glass, sashFrame, barWidth, sashWidth - barWidth, (n0 + n1) / 2, sy0 + barWidth, sy1 - barWidth, alert ? shade(OPEN_WARM, 0.16) : GLASS, sashFold); + if (style === "bars") { + // glazing bars: a cross over the pane + const [ym, nm] = [(sy0 + sy1) / 2, (n0 + n1) / 2]; + part(barWidth, sashWidth - barWidth, ym - 0.012, ym + 0.012, nm - 0.012, nm + 0.012); + part(sashWidth / 2 - 0.012, sashWidth / 2 + 0.012, sy0 + barWidth, sy1 - barWidth, nm - 0.012, nm + 0.012); + } + } +} diff --git a/frontend/src/viewer/outdoor.ts b/frontend/src/viewer/outdoor.ts new file mode 100644 index 0000000..44c1867 --- /dev/null +++ b/frontend/src/viewer/outdoor.ts @@ -0,0 +1,3 @@ +// Areas outside the house in the neon look, split into modules in outdoor/. + +export { outdoorHoles, outdoorOpacity, outdoorSurface, pushOutdoor } from "./outdoor/outdoor.ts"; diff --git a/frontend/src/viewer/outdoor/beams.ts b/frontend/src/viewer/outdoor/beams.ts new file mode 100644 index 0000000..baf238b --- /dev/null +++ b/frontend/src/viewer/outdoor/beams.ts @@ -0,0 +1,44 @@ +// Posts and beams for fences and pergolas. + +import { Color } from "three"; +import type { Vec2 } from "../../model.ts"; +import { signedArea } from "../../model.ts"; +import { ALWAYS, pushPrism, shade, type GeoBuffer } from "../geo.ts"; + +/** A ring running counter-clockwise, whichever way it was given. */ +export const counterClockwise = (points: Vec2[]): Vec2[] => (signedArea(points) >= 0 ? points : [...points].reverse()); + +/** An upright square post of the given half width, from y0 up to y1. */ +export function pushPost(buf: GeoBuffer, [x, z]: Vec2, half: number, y0: number, y1: number, side: number, top: number): void { + pushPrism(buf, counterClockwise([[x - half, z - half], [x + half, z - half], [x + half, z + half], [x - half, z + half]]), y0, y1, side, top); +} + +/** + * A thin box along the segment p to q (a beam, a rafter), `width` wide, from y0 up to y1 at p. `rise` lifts the q end by that + * much, so a beam on a sloped pergola follows the slope. + */ +export function pushBeam(buf: GeoBuffer, p: Vec2, q: Vec2, width: number, y0: number, y1: number, side: number, top: number, rise = 0): void { + const [dx, dz] = [q[0] - p[0], q[1] - p[1]]; + const length = Math.hypot(dx, dz); + if (length < 1e-6) return; + const [nx, nz] = [(-dz / length) * width * 0.5, (dx / length) * width * 0.5]; + if (Math.abs(rise) < 1e-4) { + pushPrism(buf, counterClockwise([[p[0] + nx, p[1] + nz], [q[0] + nx, q[1] + nz], [q[0] - nx, q[1] - nz], [p[0] - nx, p[1] - nz]]), y0, y1, side, top, { aoFrom: y0 - 1 }); + return; + } + // a sloped box: both faces of every quad, so it shows from any side without caring about the winding + const nearEnd = (y: number, s: number): number[] => [p[0] + nx * s, y, p[1] + nz * s]; + const farEnd = (y: number, s: number): number[] => [q[0] + nx * s, y + rise, q[1] + nz * s]; + const face = (v: number[][], color: Color) => { + for (const [a, b, c] of [[0, 1, 2], [0, 2, 3], [0, 2, 1], [0, 3, 2]]) buf.tri(v[a], v[b], v[c], color, color, color, undefined, ALWAYS); + }; + const topColor = new Color(top); + const sideColor = shade(side, 0.9); + const underColor = shade(side, 0.6); + face([nearEnd(y1, 1), farEnd(y1, 1), farEnd(y1, -1), nearEnd(y1, -1)], topColor); + face([nearEnd(y0, 1), farEnd(y0, 1), farEnd(y0, -1), nearEnd(y0, -1)], underColor); + face([nearEnd(y0, 1), farEnd(y0, 1), farEnd(y1, 1), nearEnd(y1, 1)], sideColor); + face([nearEnd(y0, -1), farEnd(y0, -1), farEnd(y1, -1), nearEnd(y1, -1)], sideColor); + face([nearEnd(y0, 1), nearEnd(y0, -1), nearEnd(y1, -1), nearEnd(y1, 1)], sideColor); + face([farEnd(y0, 1), farEnd(y0, -1), farEnd(y1, -1), farEnd(y1, 1)], sideColor); +} diff --git a/frontend/src/viewer/outdoor/gates.test.ts b/frontend/src/viewer/outdoor/gates.test.ts new file mode 100644 index 0000000..95a2a3d --- /dev/null +++ b/frontend/src/viewer/outdoor/gates.test.ts @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { gateLayout, gatesOnEdge } from "./gates.ts"; +import type { OutdoorArea } from "../../model.ts"; + +const fence = (gates: OutdoorArea["gates"]): OutdoorArea => ({ id: "f", type: "fence", points: [[0, 0], [8, 0], [8, 4], [0, 4]], gates }) as OutdoorArea; +const near = (a: number, b: number) => Math.abs(a - b) < 1e-9; + +test("a gate on an edge is found whichever way the outline runs, with its offset from the walking start", () => { + const area = fence([{ id: "g", edge: 0, offset: 2, width: 1, kind: "single" }]); + assert.deepEqual(gatesOnEdge(area, [0, 0], [8, 0]).map((g) => g.offset), [2]); + assert.deepEqual(gatesOnEdge(area, [8, 0], [0, 0]).map((g) => g.offset), [6], "from the other end it is 6 m in"); + assert.equal(gatesOnEdge(area, [8, 0], [8, 4]).length, 0); +}); + +test("a closed single gate has one leaf across the gap; an open one swings 90° to the inside", () => { + const closed = gateLayout([0, 0], [8, 0], { width: 1.2, kind: "single" }, 4, false)!; + assert.ok(near(closed.from, 3.4) && near(closed.to, 4.6)); + assert.deepEqual(closed.leaves.map((l) => [l.a, l.b]), [[[3.4, 0], [4.6, 0]]]); + const open = gateLayout([0, 0], [8, 0], { width: 1.2, kind: "single" }, 4, true)!; + assert.deepEqual(open.leaves[0].a, [3.4, 0]); + assert.ok(near(open.leaves[0].b[0], 3.4) && near(open.leaves[0].b[1], 1.2), "inside of a counter-clockwise outline is to the left of the walking direction"); +}); + +test("a double gate meets in the middle when closed and opens both leaves; a sliding gate runs behind the far post", () => { + const closed = gateLayout([0, 0], [8, 0], { width: 3, kind: "double" }, 4, false)!; + assert.equal(closed.leaves.length, 2); + assert.deepEqual(closed.leaves.map((l) => l.b), [[4, 0], [4, 0]]); + const open = gateLayout([0, 0], [8, 0], { width: 3, kind: "double" }, 4, true)!; + assert.deepEqual(open.leaves.map((l) => l.b[1]), [1.5, 1.5]); + const slid = gateLayout([0, 0], [8, 0], { width: 3, kind: "sliding" }, 4, true)!; + assert.ok(near(slid.leaves[0].a[0], 5.5) && near(slid.leaves[0].a[1], -0.12) && near(slid.leaves[0].b[0], 8.5)); +}); + +test("a gate that does not fit the edge is left out or narrowed", () => { + assert.equal(gateLayout([0, 0], [0.2, 0], { width: 1, kind: "single" }, 0.1, false), null); + const wide = gateLayout([0, 0], [2, 0], { width: 5, kind: "single" }, 1, false)!; + assert.ok(wide.to - wide.from <= 1.9 + 1e-9); +}); diff --git a/frontend/src/viewer/outdoor/gates.ts b/frontend/src/viewer/outdoor/gates.ts new file mode 100644 index 0000000..e9fbd5e --- /dev/null +++ b/frontend/src/viewer/outdoor/gates.ts @@ -0,0 +1,61 @@ +// Gates in fences: a gap in one edge of the fence, the gate posts at its ends and the leaf or leaves, closed in the gap or swung +// open (single and double gates swing 90° to the inside, a sliding gate runs along the fence behind the gap's far end). + +import type { FenceGate, OutdoorArea, Vec2 } from "../../model.ts"; + +export interface GateLeaf { + /** The hinge (or the fixed end) and the free end of one leaf, in plan metres. */ + a: Vec2; + b: Vec2; +} + +export interface GateLayout { + /** The gap along the edge p → q, in metres from p. */ + from: number; + to: number; + /** Where the two gate posts stand. */ + posts: Vec2[]; + leaves: GateLeaf[]; +} + +/** The gates of an area that sit on the edge p → q (whichever way the outline runs), with their offset counted from p. */ +export function gatesOnEdge(area: OutdoorArea, p: Vec2, q: Vec2): { gate: FenceGate; offset: number }[] { + const same = (a: Vec2, b: Vec2) => Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6; + const length = Math.hypot(q[0] - p[0], q[1] - p[1]); + const out: { gate: FenceGate; offset: number }[] = []; + for (const gate of area.gates ?? []) { + const a = area.points[gate.edge]; + const b = area.points[(gate.edge + 1) % area.points.length]; + if (!a || !b) continue; + if (same(a, p) && same(b, q)) out.push({ gate, offset: gate.offset }); + else if (same(a, q) && same(b, p)) out.push({ gate, offset: length - gate.offset }); + } + return out.sort((x, y) => x.offset - y.offset); +} + +/** The gap, posts and leaves of one gate on the edge p → q. `offset` is the gate's middle from p; `open` swings or slides it. */ +export function gateLayout(p: Vec2, q: Vec2, gate: Pick, offset: number, open: boolean): GateLayout | null { + const length = Math.hypot(q[0] - p[0], q[1] - p[1]); + if (length < 0.3) return null; + const width = Math.min(gate.width, length - 0.1); + if (width < 0.3) return null; + const from = Math.max(0.05, Math.min(length - width - 0.05, offset - width / 2)); + const to = from + width; + const [ux, uz] = [(q[0] - p[0]) / length, (q[1] - p[1]) / length]; + // the inside of a counter-clockwise outline lies to the left of the walking direction p → q + const [nx, nz] = [-uz, ux]; + const at = (t: number, side = 0): Vec2 => [p[0] + ux * t + nx * side, p[1] + uz * t + nz * side]; + const [pa, pb] = [at(from), at(to)]; + const leaves: GateLeaf[] = []; + if (gate.kind === "double") { + const mid = (from + to) / 2; + leaves.push(open ? { a: pa, b: at(from, width / 2) } : { a: pa, b: at(mid) }); + leaves.push(open ? { a: pb, b: at(to, width / 2) } : { a: pb, b: at(mid) }); + } else if (gate.kind === "sliding") { + // open: it rolls along the fence behind the far post, a hand's breadth outside the line + leaves.push(open ? { a: at(to, -0.12), b: at(to + width, -0.12) } : { a: pa, b: pb }); + } else { + leaves.push(open ? { a: pa, b: at(from, width) } : { a: pa, b: pb }); + } + return { from, to, posts: [pa, pb], leaves }; +} diff --git a/frontend/src/viewer/outdoor/looks.ts b/frontend/src/viewer/outdoor/looks.ts new file mode 100644 index 0000000..0f9b39e --- /dev/null +++ b/frontend/src/viewer/outdoor/looks.ts @@ -0,0 +1,24 @@ +// How each kind of outdoor area looks in the neon scene: colours of the top, the sides, and the outline. + +import type { OutdoorType } from "../../model.ts"; + +export interface Look { + color: number; + side: number; + edge: number; + /** How strong the outline is (its colour is scaled by this). */ + edgeAlpha: number; +} + +export const LOOKS: Record = { + lawn: { color: 0x0e2822, side: 0x0b201b, edge: 0x3ee2a2, edgeAlpha: 0.16 }, + terrace: { color: 0x1c1b30, side: 0x161628, edge: 0x5b7cff, edgeAlpha: 0.32 }, + path: { color: 0x1b2234, side: 0x151b29, edge: 0x5b7cff, edgeAlpha: 0.22 }, + driveway: { color: 0x171d2c, side: 0x121725, edge: 0x5b7cff, edgeAlpha: 0.18 }, + pool: { color: 0x0b3b5b, side: 0x0d2539, edge: 0x37e0ff, edgeAlpha: 0.6 }, + bed: { color: 0x1b1613, side: 0x15110f, edge: 0x3ee2a2, edgeAlpha: 0.2 }, + wild: { color: 0x15221b, side: 0x101b15, edge: 0x9ad24f, edgeAlpha: 0.14 }, + hedge: { color: 0x174130, side: 0x113125, edge: 0x3ee2a2, edgeAlpha: 0.35 }, + fence: { color: 0x1e2a47, side: 0x1e2a47, edge: 0x5b7cff, edgeAlpha: 0.45 }, + pergola: { color: 0x2b2339, side: 0x201b2d, edge: 0x5b7cff, edgeAlpha: 0.5 }, +}; diff --git a/frontend/src/viewer/outdoor/outdoor.test.ts b/frontend/src/viewer/outdoor/outdoor.test.ts new file mode 100644 index 0000000..150fd97 --- /dev/null +++ b/frontend/src/viewer/outdoor/outdoor.test.ts @@ -0,0 +1,160 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { newFloor, OUTDOOR_TOP, type Floor, type OutdoorArea, type Vec2 } from "../../model.ts"; +import { GeoBuffer, LineBuffer } from "../geo.ts"; +import { counterClockwise, pushBeam, pushPost } from "./beams.ts"; +import { outdoorHoles, outdoorOpacity, outdoorSurface, pushOutdoor } from "./outdoor.ts"; + +const square = (x0: number, z0: number, x1: number, z1: number): Vec2[] => [[x0, z0], [x1, z0], [x1, z1], [x0, z1]]; +const area = (type: OutdoorArea["type"], points: Vec2[], extra: Partial = {}): OutdoorArea => ({ id: type, type, points, ...extra }) as OutdoorArea; +const floorWith = (...areas: OutdoorArea[]): Floor => ({ ...newFloor("g", "G", 0), outdoor: areas }); + +function build(...areas: OutdoorArea[]) { + const buf = new GeoBuffer(); + const lines = new LineBuffer(); + pushOutdoor(buf, lines, floorWith(...areas)); + return { buf, lines, top: Math.max(...buf.p.filter((_, i) => i % 3 === 1), -Infinity) }; +} + +test("a ring is turned counter-clockwise whichever way it comes", () => { + const ring = square(0, 0, 2, 2); + assert.deepEqual(counterClockwise(ring), ring); + assert.deepEqual(counterClockwise([...ring].reverse()), ring); +}); + +test("a post and a beam add geometry; a beam of no length adds none", () => { + const buf = new GeoBuffer(); + pushPost(buf, [1, 1], 0.05, 0, 2, 0x333333, 0x555555); + assert.equal(buf.count, 10); + pushBeam(buf, [0, 0], [3, 0], 0.1, 2, 2.2, 0x333333, 0x555555); + const level = buf.count; + assert.ok(level > 10); + pushBeam(buf, [0, 0], [0, 0], 0.1, 2, 2.2, 0x333333, 0x555555); + assert.equal(buf.count, level); + pushBeam(buf, [0, 0], [3, 0], 0.1, 2, 2.2, 0x333333, 0x555555, 0.5); + assert.equal(buf.count, level + 6 * 4, "a sloped beam: six faces, each drawn from both sides (four triangles)"); +}); + +test("a lawn is a flat block at ground level with an outline", () => { + const { buf, lines, top } = build(area("lawn", square(0, 0, 4, 3))); + assert.ok(buf.count > 0); + assert.equal(lines.p.length / 6, 4); + const ground = Math.min(...buf.p.filter((_, i) => i % 3 === 1)); + assert.ok(Math.abs(top - ground - OUTDOOR_TOP.lawn) < 0.3, "a thin layer on the ground"); +}); + +test("the outline can be switched off", () => { + const { lines } = build(area("lawn", square(0, 0, 4, 3), { outline: false })); + assert.equal(lines.p.length, 0); +}); + +test("a hedge takes its own height", () => { + const low = build(area("hedge", square(0, 0, 4, 1))); + const tall = build(area("hedge", square(0, 0, 4, 1), { height: 2.5 })); + assert.ok(Math.abs(tall.top - low.top - (2.5 - OUTDOOR_TOP.hedge)) < 0.01); +}); + +test("a slope tilts the top of an area and lowers its base", () => { + const flat = build(area("terrace", square(0, 0, 4, 3))); + const sloped = build(area("terrace", square(0, 0, 4, 3), { slope: 0.5, slope_dir: "x" } as Partial)); + const lowest = (b: ReturnType) => Math.min(...b.buf.p.filter((_, i) => i % 3 === 1)); + assert.ok(lowest(sloped) < lowest(flat)); +}); + +test("a pool has water below the rim and inner sides", () => { + const { buf } = build(area("pool", square(0, 0, 4, 3))); + assert.ok(buf.count >= 2 + 8); + const ys = buf.p.filter((_, i) => i % 3 === 1); + assert.ok(Math.max(...ys) > Math.min(...ys)); +}); + +test("a fence has posts about every two metres and two rails per edge", () => { + const { buf, lines } = build(area("fence", square(0, 0, 8, 4))); + assert.equal(lines.p.length / 6, 4 * 2, "two rails on each of the four edges"); + const posts = buf.count / 10; + assert.ok(posts >= 8 && posts <= 14, String(posts)); +}); + +test("a fence that is open leaves its closing edge out, but gets a post at the far end", () => { + const closed = build(area("fence", square(0, 0, 8, 4))); + const open = build(area("fence", square(0, 0, 8, 4), { open: true })); + assert.equal(open.lines.p.length / 6, 3 * 2); + assert.ok(open.buf.count > 0 && open.buf.count <= closed.buf.count + 10); +}); + +test("a pergola has corner posts and beams, rafters across a rectangle, and optional bracing", () => { + const plain = build(area("pergola", square(0, 0, 4, 3))); + const braced = build(area("pergola", square(0, 0, 4, 3), { bracing: true })); + assert.ok(plain.buf.count > 4 * 10 + 4 * 10, "posts and beams"); + assert.equal(braced.lines.p.length / 6, plain.lines.p.length / 6 + 4 * 2); + const triangle = build(area("pergola", [[0, 0], [4, 0], [2, 3]])); + assert.ok(triangle.buf.count < plain.buf.count, "no rafters across a triangle"); +}); + +test("areas marked cut inside another become holes in it, in either drawing order; standing areas and pools have none", () => { + const areas = [area("lawn", square(0, 0, 10, 10)), area("bed", square(2, 2, 3, 3), { cut: true }), area("bed", square(20, 20, 21, 21), { cut: true }), area("path", square(4, 4, 5, 5))]; + assert.equal(outdoorHoles(areas, 0).length, 1); + assert.deepEqual(outdoorHoles([area("hedge", square(0, 0, 10, 10)), area("bed", square(2, 2, 3, 3), { cut: true })], 0), []); + assert.deepEqual(outdoorHoles([area("pool", square(0, 0, 10, 10)), area("bed", square(2, 2, 3, 3), { cut: true })], 0), []); + // a bed drawn before the lawn that contains it still leaves its hole + assert.equal(outdoorHoles([area("bed", square(2, 2, 3, 3), { cut: true }), area("lawn", square(0, 0, 10, 10))], 1).length, 1); + // a pool cuts itself out of a terrace, drawn before or after, unless cut is switched off + const terrace = area("terrace", square(0, 0, 10, 10)); + assert.equal(outdoorHoles([terrace, area("pool", square(2, 2, 5, 5))], 0).length, 1); + assert.equal(outdoorHoles([area("pool", square(2, 2, 5, 5)), terrace], 1).length, 1); + assert.equal(outdoorHoles([terrace, area("pool", square(2, 2, 5, 5), { cut: false })], 0).length, 0); + const withHole = build(areas[0], areas[1]); + const without = build(areas[0]); + assert.ok(withHole.buf.count > without.buf.count); + // the terrace around a pool gets walls round the hole (more geometry) unless the pool does not cut itself out + const cutPool = build(terrace, area("pool", square(2, 2, 5, 5))); + const keptPool = build(terrace, area("pool", square(2, 2, 5, 5), { cut: false })); + assert.ok(cutPool.buf.count > keptPool.buf.count); +}); + +test("the surface height of an area follows its offset and type", () => { + const floor = floorWith(); + const plain = outdoorSurface(floor, area("lawn", square(0, 0, 1, 1))); + assert.ok(Math.abs(outdoorSurface(floor, area("lawn", square(0, 0, 1, 1), { offset: 0.3 })) - plain - 0.3) < 1e-9); + assert.ok(outdoorSurface(floor, area("terrace", square(0, 0, 1, 1))) > plain); + assert.ok(outdoorSurface(floor, area("hedge", square(0, 0, 1, 1))) - plain < 0.1, "standing things count their base"); +}); + +test("an area with fewer than three corners is skipped", () => { + const { buf, lines } = build(area("lawn", [[0, 0], [1, 1]])); + assert.equal(buf.count + lines.p.length, 0); +}); + +test("a gate cuts a gap into a fence: no rail across it, gate posts at its ends, and a leaf that moves when it opens", () => { + const plain = build(area("fence", square(0, 0, 8, 4))); + const gate = (open: boolean) => build(area("fence", square(0, 0, 8, 4), { gates: [{ id: "g", edge: 0, offset: 4, width: 1.2, kind: "single", open }] })); + const closed = gate(false); + assert.ok(closed.lines.p.length / 6 >= plain.lines.p.length / 6 + 2, "the long edge's two rails now come in two parts, plus the leaf's brace"); + assert.ok(closed.buf.count > plain.buf.count, "gate posts and leaf geometry"); + const open = gate(true); + assert.notDeepEqual(open.buf.p, closed.buf.p, "an open leaf stands somewhere else"); + const zs = open.buf.p.filter((_, i) => i % 3 === 2); + assert.ok(Math.max(...zs) > 1.0, "it swings into the plot"); +}); + +test("a see-through area goes into a buffer of its own per opacity, the outline stays in the lines", () => { + const solid = new GeoBuffer(); + const lines = new LineBuffer(); + const ghosts = new Map(); + const floor = floorWith(area("lawn", square(0, 0, 4, 4)), area("driveway", square(5, 0, 9, 4), { opacity: 0.4 }), area("terrace", square(10, 0, 12, 2), { opacity: 0.4 }), area("bed", square(13, 0, 14, 1), { opacity: 0.12 })); + pushOutdoor(solid, lines, floor, ghosts, () => new GeoBuffer()); + assert.deepEqual([...ghosts.keys()].sort(), [0.1, 0.4]); + assert.ok(ghosts.get(0.4)!.count > 0 && solid.count > 0); + // without ghost buffers everything is drawn solid, as before + const all = new GeoBuffer(); + pushOutdoor(all, new LineBuffer(), floor); + assert.equal(all.count, solid.count + ghosts.get(0.4)!.count + ghosts.get(0.1)!.count); +}); + +test("opacity of 1 or none means solid; very low values stop at 10 %", () => { + assert.equal(outdoorOpacity(area("lawn", square(0, 0, 1, 1))), 1); + assert.equal(outdoorOpacity(area("lawn", square(0, 0, 1, 1), { opacity: 1 })), 1); + assert.equal(outdoorOpacity(area("lawn", square(0, 0, 1, 1), { opacity: null })), 1); + assert.equal(outdoorOpacity(area("lawn", square(0, 0, 1, 1), { opacity: 0.02 })), 0.1); + assert.equal(outdoorOpacity(area("lawn", square(0, 0, 1, 1), { opacity: 0.43 })), 0.45); +}); diff --git a/frontend/src/viewer/outdoor/outdoor.ts b/frontend/src/viewer/outdoor/outdoor.ts new file mode 100644 index 0000000..e12edd3 --- /dev/null +++ b/frontend/src/viewer/outdoor/outdoor.ts @@ -0,0 +1,227 @@ +// Areas outside the house: lawn, terrace, path, driveway, pool, bed, wild patch, hedge, fence and pergola, in the neon look. +// Flat areas lie at ground level (the underside of the ground floor slab), the terrace a little higher, the pool water +// below. Hedges are dark green blocks, fences posts with rails along the outline, a pergola corner posts with beams, +// rafters and optional X-bracing. An area can sit higher or lower (offset), fall along one direction (slope) and have +// patches cut out of it. + +import { Color } from "three"; +import { bounds, cutsOut, groundLevel, isAxisRect, OUTDOOR_TOP, outdoorDrop, outdoorStanding, pointInPolygon, type Floor, type OutdoorArea, type Vec2 } from "../../model.ts"; +import { ALWAYS, pushPrism, shade, triangulate, type GeoBuffer, type LineBuffer } from "../geo.ts"; +import { counterClockwise, pushBeam, pushPost } from "./beams.ts"; +import { gateLayout, gatesOnEdge } from "./gates.ts"; +import { LOOKS } from "./looks.ts"; + +/** The height of the visible surface of an area (for the lighting layer), at its high edge. */ +export function outdoorSurface(floor: Floor, area: OutdoorArea): number { + return groundLevel(floor) + (area.offset ?? 0) + (outdoorStanding(area.type) ? 0.01 : OUTDOOR_TOP[area.type]); +} + +/** The holes of an area: the other areas that cut themselves out (marked "cut", and pools) and lie entirely inside it, whatever order they were drawn in. */ +export function outdoorHoles(areas: OutdoorArea[], index: number): Vec2[][] { + const area = areas[index]; + if (outdoorStanding(area.type) || area.type === "pool") return []; + return areas + .filter((other, i) => i !== index && cutsOut(other) && other.points.length >= 3 && other.points.every((p) => pointInPolygon(p, area.points))) + .map((other) => counterClockwise(other.points)); +} + +/** What an area builder needs to know. */ +interface Context { + buf: GeoBuffer; + lines: LineBuffer; + area: OutdoorArea; + /** The outline, counter-clockwise. */ + poly: Vec2[]; + /** The area's base height, and the ground height at a point (it falls along the slope). */ + base: number; + groundAt: (x: number, z: number) => number; + /** The top height of the type, or the area's own for hedges, fences and pergolas. */ + top: number; + look: (typeof LOOKS)[keyof typeof LOOKS]; + edge: Color; + /** The index of the closing edge to leave out (a fence or pergola leaning on the house), or -1. */ + openEdge: number; +} + +const edgesOf = (poly: Vec2[], openEdge: number): [number, Vec2, Vec2][] => poly.map((p, i) => [i, p, poly[(i + 1) % poly.length]] as [number, Vec2, Vec2]).filter(([i]) => i !== openEdge); + +function outline(c: Context, heightAt: (x: number, z: number) => number): void { + if (c.area.outline === false) return; + for (const [, p, q] of edgesOf(c.poly, c.openEdge)) c.lines.seg([p[0], heightAt(p[0], p[1]), p[1]], [q[0], heightAt(q[0], q[1]), q[1]], c.edge, ALWAYS); +} + +function buildPool(c: Context): void { + const { buf, poly, base, top, look } = c; + const water = new Color(look.color); + // the water surface, below the rim + for (const [i, j, k] of triangulate(poly)) { + const [p, q, r] = [poly[i], poly[j], poly[k]]; + buf.tri([p[0], base + top, p[1]], [r[0], base + top, r[1]], [q[0], base + top, q[1]], water, water, water, undefined, ALWAYS); + } + // the inner sides from the water up to the rim, seen from inside the pool + const sideColor = new Color(look.side); + for (const [, p, q] of edgesOf(poly, -1)) { + buf.tri([q[0], base + top, q[1]], [q[0], base + 0.06, q[1]], [p[0], base + 0.06, p[1]], sideColor, sideColor, sideColor, undefined, ALWAYS); + buf.tri([q[0], base + top, q[1]], [p[0], base + 0.06, p[1]], [p[0], base + top, p[1]], sideColor, sideColor, sideColor, undefined, ALWAYS); + } + outline(c, () => base + 0.06); + outline(c, () => base + top + 0.005); +} + +function buildFence(c: Context): void { + const { buf, lines, poly, area, top, look, groundAt, edge, openEdge } = c; + // posts about every 2 m and two rails along the outline, following the ground + for (const [i, p, q] of edgesOf(poly, openEdge)) { + const length = Math.hypot(q[0] - p[0], q[1] - p[1]); + const sections = Math.max(1, Math.round(length / 2)); + // gates cut gaps into the edge: no posts and no rails there, a gate post at each end and the leaves in between + const gates = gatesOnEdge(area, p, q) + .map(({ gate, offset }) => ({ gate, layout: gateLayout(p, q, gate, offset, !!gate.open) })) + .filter((g): g is { gate: typeof g.gate; layout: NonNullable } => !!g.layout); + const inGap = (t: number) => gates.some((g) => t > g.layout.from - 0.15 && t < g.layout.to + 0.15); + // an open fence also gets the post at its far end + const lastPost = openEdge >= 0 && i === openEdge - 1 ? sections : sections - 1; + for (let k = 0; k <= lastPost; k++) { + if (inGap((length * k) / sections)) continue; + const x = p[0] + ((q[0] - p[0]) * k) / sections; + const z = p[1] + ((q[1] - p[1]) * k) / sections; + const ground = groundAt(x, z); + pushPost(buf, [x, z], 0.04, ground, ground + top, look.side, look.color); + } + // the rails run between the gaps + const cuts: [number, number][] = []; + let at = 0; + for (const g of gates) { + cuts.push([at, g.layout.from]); + at = g.layout.to; + } + cuts.push([at, length]); + const along = (t: number): Vec2 => [p[0] + ((q[0] - p[0]) * t) / length, p[1] + ((q[1] - p[1]) * t) / length]; + for (const [t0, t1] of cuts) { + if (t1 - t0 < 0.02) continue; + const [a, b] = [along(t0), along(t1)]; + for (const rail of [0.35, 0.85]) lines.seg([a[0], groundAt(a[0], a[1]) + rail * top, a[1]], [b[0], groundAt(b[0], b[1]) + rail * top, b[1]], edge, ALWAYS); + } + for (const { layout } of gates) { + for (const post of layout.posts) { + const ground = groundAt(post[0], post[1]); + pushPost(buf, post, 0.07, ground, ground + top * 1.05, look.side, look.color); + } + for (const leaf of layout.leaves) pushGateLeaf(c, leaf.a, leaf.b); + } + } +} + +/** One gate leaf: two rails, pickets and a diagonal brace between a (the hinge) and b. */ +function pushGateLeaf(c: Context, a: Vec2, b: Vec2): void { + const { buf, lines, top, look, groundAt, edge } = c; + const length = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (length < 0.05) return; + const [ga, gb] = [groundAt(a[0], a[1]), groundAt(b[0], b[1])]; + const rise = gb - ga; + for (const [lo, hi] of [[0.12, 0.2], [0.78, 0.86]]) pushBeam(buf, a, b, 0.05, ga + lo * top, ga + hi * top, look.side, look.color, rise); + const pickets = Math.max(2, Math.round(length / 0.18)); + for (let k = 0; k <= pickets; k++) { + const t = k / pickets; + const x = a[0] + (b[0] - a[0]) * t; + const z = a[1] + (b[1] - a[1]) * t; + const ground = ga + rise * t; + pushPost(buf, [x, z], k === 0 || k === pickets ? 0.03 : 0.012, ground + 0.1 * top, ground + 0.9 * top, look.side, look.color); + } + lines.seg([a[0], ga + 0.2 * top, a[1]], [b[0], gb + 0.78 * top, b[1]], edge, ALWAYS); +} + +function buildPergola(c: Context): void { + const { buf, lines, poly, area, top, look, groundAt, edge, openEdge } = c; + // corner posts, beams along the edges, rafters across a rectangle, optional X-bracing on the sides + for (const corner of poly) { + const ground = groundAt(corner[0], corner[1]); + pushPost(buf, corner, 0.06, ground, ground + top, look.side, look.color); + } + for (const [, p, q] of edgesOf(poly, openEdge)) { + const [gp, gq] = [groundAt(p[0], p[1]), groundAt(q[0], q[1])]; + pushBeam(buf, p, q, 0.12, gp + top - 0.16, gp + top, look.side, look.color, gq - gp); + if (area.bracing) { + lines.seg([p[0], gp + 0.25, p[1]], [q[0], gq + top - 0.25, q[1]], edge, ALWAYS); + lines.seg([q[0], gq + 0.25, q[1]], [p[0], gp + top - 0.25, p[1]], edge, ALWAYS); + } + } + if (isAxisRect(poly)) { + const box = bounds(poly); + const alongX = box.x1 - box.x0 >= box.z1 - box.z0; + const [start, span] = alongX ? [box.x0, box.x1 - box.x0] : [box.z0, box.z1 - box.z0]; + const rafters = Math.max(1, Math.round(span / 0.6)); + for (let k = 1; k < rafters; k++) { + const t = start + (span * k) / rafters; + const p: Vec2 = alongX ? [t, box.z0 + 0.06] : [box.x0 + 0.06, t]; + const q: Vec2 = alongX ? [t, box.z1 - 0.06] : [box.x1 - 0.06, t]; + const gp = groundAt(p[0], p[1]); + pushBeam(buf, p, q, 0.06, gp + top - 0.04, gp + top + 0.08, look.side, look.color, groundAt(q[0], q[1]) - gp); + } + } + outline(c, (x, z) => groundAt(x, z) + top + 0.004); +} + +/** Everything else: a flat area is a thin prism; terrace, bed and hedge are raised blocks. A slope tilts the top and the block reaches down to the lowest point. */ +function buildBlock(c: Context, areas: OutdoorArea[], index: number): void { + const { buf, lines, poly, area, top, look, groundAt, base, edge } = c; + const lowest = base - (area.slope ?? 0); + const topAt = (x: number, z: number) => groundAt(x, z) + top; + const holes = outdoorHoles(areas, index); + pushPrism(buf, poly, lowest, area.slope ? topAt : base + top, look.side, look.color, { aoFrom: lowest, holes }); + outline(c, (x, z) => topAt(x, z) + 0.004); + if (area.type === "hedge") outline(c, (x, z) => groundAt(x, z) + 0.004); + if (area.outline === false) return; + for (const hole of holes) { + hole.forEach((p, i) => { + const q = hole[(i + 1) % hole.length]; + lines.seg([p[0], topAt(p[0], p[1]) + 0.004, p[1]], [q[0], topAt(q[0], q[1]) + 0.004, q[1]], edge, ALWAYS); + }); + } +} + +/** The opacity an area is drawn with, in whole percent steps (100 = solid). */ +export function outdoorOpacity(area: OutdoorArea): number { + const o = area.opacity; + return o == null || !(o < 1) ? 1 : Math.max(0.1, Math.round(o * 20) / 20); +} + +/** + * Builds the outdoor areas of a floor. Areas that are drawn see-through go into a buffer of their own per opacity (`ghosts`), the others + * into `buf`; the outlines always stay solid. + */ +export function pushOutdoor(buf: GeoBuffer, lines: LineBuffer, floor: Floor, ghosts?: Map, makeBuffer?: () => GeoBuffer): void { + const ground = groundLevel(floor); + const areas = floor.outdoor ?? []; + areas.forEach((area, index) => { + if (area.points.length < 3) return; + // an area may sit above or below the ground (a driveway down to a lower garage) and fall along one direction + const base = ground + (area.offset ?? 0); + const look = LOOKS[area.type]; + const poly = counterClockwise(area.points); + const opacity = outdoorOpacity(area); + let target = buf; + if (opacity < 1 && ghosts && makeBuffer) { + if (!ghosts.has(opacity)) ghosts.set(opacity, makeBuffer()); + target = ghosts.get(opacity)!; + } + const context: Context = { + buf: target, + lines, + area, + poly, + base, + groundAt: (x, z) => base - outdoorDrop(area, x, z), + // hedges, fences and pergolas take their own height; the outline can be switched off per area + top: outdoorStanding(area.type) && area.height ? area.height : OUTDOOR_TOP[area.type], + look, + edge: shade(look.edge, look.edgeAlpha), + // fences and pergolas may leave their closing edge out (leaning against the house) + openEdge: area.open && (area.type === "fence" || area.type === "pergola") ? poly.length - 1 : -1, + }; + if (area.type === "pool") buildPool(context); + else if (area.type === "fence") buildFence(context); + else if (area.type === "pergola") buildPergola(context); + else buildBlock(context, areas, index); + }); +} diff --git a/frontend/src/viewer/pets.test.ts b/frontend/src/viewer/pets.test.ts new file mode 100644 index 0000000..cea2ee4 --- /dev/null +++ b/frontend/src/viewer/pets.test.ts @@ -0,0 +1,64 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { advancePet, freeSpot, nextTarget, seededRandom, stepPet, type PetMotion, type PetRoom } from "./pets.ts"; + +const room: PetRoom = { + points: [[0, 0], [5, 0], [5, 4], [0, 4]], + obstacles: [[[2, 1], [3, 1], [3, 3], [2, 3]]], // a table in the middle + speed: 0.5, +}; + +test("free spots are inside the room, off the walls and outside the furniture", () => { + assert.ok(freeSpot(room, [1, 1])); + assert.ok(!freeSpot(room, [2.5, 2]), "under the table"); + assert.ok(!freeSpot(room, [0.1, 2]), "against the wall"); + assert.ok(!freeSpot(room, [6, 2]), "outside"); +}); + +test("the next spot is free and the way there does not cross the furniture", () => { + const random = seededRandom("cat"); + for (let i = 0; i < 40; i++) { + const t = nextTarget(room, [1, 2], random); + assert.ok(t && freeSpot(room, t)); + assert.ok(t![0] < 2 || t![1] < 1 || t![1] > 3, "never straight through the table"); + } +}); + +test("a pet walks to its spot, rests there and walks on, never leaving the room", () => { + const random = seededRandom("dog"); + const m: PetMotion = { pos: [1, 1], heading: 0, target: null, rest: 0 }; + let walked = 0; + for (let i = 0; i < 2000; i++) { + if (stepPet(m, room, 0.1, random)) walked++; + assert.ok(freeSpot(room, m.pos, 0.2) || Math.hypot(m.pos[0] - 1, m.pos[1] - 1) < 1e-9, `left the free floor at ${m.pos}`); + } + assert.ok(walked > 200 && walked < 1990, "it walks, and it rests in between"); +}); + +test("the same pet walks the same way after a reload", () => { + const a = seededRandom("rabbit-1"); + const b = seededRandom("rabbit-1"); + assert.deepEqual([a(), a(), a()], [b(), b(), b()]); +}); + +test("a pet placed under the table walks out of it", () => { + const t = nextTarget(room, [2.5, 2], seededRandom("under")); + assert.ok(t && freeSpot(room, t)); +}); + +test("a resting pet walks on after its rest, whether frames come every 16 ms or after one long sleep (#97)", () => { + const random = seededRandom("cat"); + const busy: PetMotion = { pos: [1, 1], heading: 0, target: null, rest: 3 }; + let t = 0; + while (!busy.target && t < 10) { + advancePet(busy, room, 0.016, random); + t += 0.016; + } + assert.ok(busy.target, "frames of other animations count the rest down"); + assert.ok(t > 2.9 && t < 3.1, `walked on after about 3 s, not ${t.toFixed(2)} s`); + const asleep: PetMotion = { pos: [1, 1], heading: 0, target: null, rest: 3 }; + const before = [...asleep.pos]; + advancePet(asleep, room, 3.05, random); + assert.ok(asleep.target, "a frame after a 3 s sleep counts the whole sleep"); + assert.ok(Math.hypot(asleep.pos[0] - before[0], asleep.pos[1] - before[1]) <= room.speed * 0.2 + 1e-9, "but walks at most 0.2 s at once"); +}); diff --git a/frontend/src/viewer/pets.ts b/frontend/src/viewer/pets.ts new file mode 100644 index 0000000..ba10d83 --- /dev/null +++ b/frontend/src/viewer/pets.ts @@ -0,0 +1,111 @@ +// Pets that roam their room: a cat, a dog or a rabbit walks to a free spot of the room, looks around for a few seconds, and walks +// on. They keep away from the walls and walk round the furniture. Pure motion; the viewer draws them and moves their group. + +import { pointInPolygon, type Vec2 } from "../model.ts"; + +export interface PetMotion { + pos: Vec2; + heading: number; + target: Vec2 | null; + /** Seconds left to rest before the next walk. */ + rest: number; +} + +export interface PetRoom { + points: Vec2[]; + /** Footprints of the furniture standing in the room, which the pet walks round. */ + obstacles: Vec2[][]; + /** Walking speed in m/s. */ + speed: number; +} + +/** A tiny seeded random generator, so every pet walks its own but repeatable way. */ +export function seededRandom(seed: string): () => number { + let h = 2166136261; + for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 16777619); + return () => { + h = Math.imul(h ^ (h >>> 15), 2246822507); + h = Math.imul(h ^ (h >>> 13), 3266489909); + h ^= h >>> 16; + return (h >>> 0) / 4294967296; + }; +} + +const distToSegment = (p: Vec2, a: Vec2, b: Vec2) => { + const [dx, dz] = [b[0] - a[0], b[1] - a[1]]; + const l2 = dx * dx + dz * dz || 1e-9; + const t = Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / l2)); + return Math.hypot(p[0] - a[0] - dx * t, p[1] - a[1] - dz * t); +}; + +/** Whether a pet can stand at p: inside the room, a little off the walls, not inside furniture. */ +export function freeSpot(room: PetRoom, p: Vec2, margin = 0.25): boolean { + if (!pointInPolygon(p, room.points)) return false; + const pts = room.points; + for (let i = 0; i < pts.length; i++) if (distToSegment(p, pts[i], pts[(i + 1) % pts.length]) < margin) return false; + return !room.obstacles.some((o) => pointInPolygon(p, o)); +} + +/** The way from a to b is free of furniture (checked every 10 cm). */ +function clearWay(room: PetRoom, a: Vec2, b: Vec2): boolean { + // a pet placed under a table walks out of it: only the other furniture blocks its way + const blocking = room.obstacles.filter((o) => !pointInPolygon(a, o)); + const steps = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 0.1)); + for (let i = 1; i <= steps; i++) { + const p: Vec2 = [a[0] + ((b[0] - a[0]) * i) / steps, a[1] + ((b[1] - a[1]) * i) / steps]; + if (blocking.some((o) => pointInPolygon(p, o))) return false; + } + return true; +} + +/** A free spot of the room the pet can walk to in a straight line, or null after a few tries. */ +export function nextTarget(room: PetRoom, from: Vec2, random: () => number): Vec2 | null { + const xs = room.points.map((p) => p[0]); + const zs = room.points.map((p) => p[1]); + const [x0, x1, z0, z1] = [Math.min(...xs), Math.max(...xs), Math.min(...zs), Math.max(...zs)]; + for (let i = 0; i < 24; i++) { + const p: Vec2 = [x0 + (x1 - x0) * random(), z0 + (z1 - z0) * random()]; + if (Math.hypot(p[0] - from[0], p[1] - from[1]) > 0.6 && freeSpot(room, p) && clearWay(room, from, p)) return p; + } + return null; +} + +/** One step of dt seconds: walk towards the target and turn into the way, or rest and then pick the next spot. True while it walks. */ +export function stepPet(m: PetMotion, room: PetRoom, dt: number, random: () => number): boolean { + if (!m.target) { + m.rest -= dt; + if (m.rest > 0) return false; + m.target = nextTarget(room, m.pos, random); + if (!m.target) { + m.rest = 2; + return false; + } + } + const [dx, dz] = [m.target[0] - m.pos[0], m.target[1] - m.pos[1]]; + const dist = Math.hypot(dx, dz); + // the heading turns smoothly towards the way (the pet's nose points along +z of its model) + const want = Math.atan2(dx, dz); + let turn = want - m.heading; + while (turn > Math.PI) turn -= 2 * Math.PI; + while (turn < -Math.PI) turn += 2 * Math.PI; + m.heading += Math.max(-4 * dt, Math.min(4 * dt, turn)); + const step = room.speed * dt * (Math.abs(turn) > 1.2 ? 0.3 : 1); + if (dist <= step) { + m.pos = [m.target[0], m.target[1]]; + m.target = null; + m.rest = 2 + random() * 6; + return true; + } + m.pos = [m.pos[0] + (dx / dist) * step, m.pos[1] + (dz / dist) * step]; + return true; +} + +/** + * One frame of a pet with the real time since its last frame: the walk moves by at most 0.2 s at once (no jumps after + * a pause), but a rest counts the whole time down, so a pet walks on whether the view draws every frame or slept (#97). + */ +export function advancePet(m: PetMotion, room: PetRoom, elapsed: number, random: () => number): boolean { + const dt = Math.min(0.2, Math.max(0, elapsed)); + if (!m.target) m.rest -= Math.max(0, elapsed) - dt; + return stepPet(m, room, dt, random); +} diff --git a/frontend/src/viewer/preview.ts b/frontend/src/viewer/preview.ts new file mode 100644 index 0000000..8ddb337 --- /dev/null +++ b/frontend/src/viewer/preview.ts @@ -0,0 +1,90 @@ +// Small pictures of furniture and lamps for the editor's library. One offscreen renderer draws the same low-poly models as the 3D +// view, seen from the front at an angle, into a PNG data URL. + +import { Box3, Color, LineBasicMaterial, LineSegments, Mesh, MeshBasicMaterial, OrthographicCamera, Scene, Vector3, WebGLRenderer } from "three"; +import type { Furniture } from "../model.ts"; +import { packItem, setPacks, type FurniturePack } from "../packs.ts"; +import { pushFurniture, pushPackLamp } from "./furniture.ts"; +import { GeoBuffer, LineBuffer } from "./geo.ts"; +import { pushLampModel, type LampModel } from "./viewer3d.ts"; + +let renderer: WebGLRenderer | null = null; +const cache = new Map(); + +export interface PreviewItem { + type: string; + w: number; + d: number; + h: number; + variant?: string | null; + /** The lamp model for lamp types: they are drawn by the lamp code, lit. */ + lamp?: LampModel | null; +} + +const LAMP_LIGHT = 0xffb547; + +/** Draws the item into the buffers: a pack lamp, a built-in lamp, or ordinary furniture. */ +function drawItem(item: PreviewItem, solids: GeoBuffer, lines: LineBuffer): void { + const packed = packItem(item.type); + if (packed?.light) { + pushPackLamp(solids, packed, { x: 0, z: 0, rotation: 0, w: item.w, d: item.d, h: item.h }, 0, LAMP_LIGHT); + } else if (item.lamp) { + // hanging lamps hang from a ceiling just above them + pushLampModel(solids, { x: 0, z: 0, size: [item.w, item.d, item.h], base: 0, rotation: 0, variant: item.variant ?? null, lamp: item.lamp }, Math.max(item.h + 0.15, 0.6), LAMP_LIGHT); + } else { + const piece: Furniture = { id: "preview", type: item.type, x: 0, z: 0, rotation: 0, w: item.w, d: item.d, h: item.h, variant: item.variant ?? null, entity: null, power: null }; + pushFurniture(solids, lines, new GeoBuffer(), piece); + } +} + +/** A camera that looks from the front right, a little from above, with the item's box fitted into the picture. */ +function fitCamera(box: Box3): OrthographicCamera { + const centre = box.getCenter(new Vector3()); + const camera = new OrthographicCamera(-1, 1, 1, -1, 0.01, 100); + camera.position.copy(centre).add(new Vector3(0.9, 0.75, 1.3).normalize().multiplyScalar(20)); + camera.lookAt(centre); + camera.updateMatrixWorld(); + // the camera looks at the centre, so the corners' distances in view space give the picture's extent + let reach = 0.05; + for (const x of [box.min.x, box.max.x]) { + for (const y of [box.min.y, box.max.y]) { + for (const z of [box.min.z, box.max.z]) { + const p = new Vector3(x, y, z).applyMatrix4(camera.matrixWorldInverse); + reach = Math.max(reach, Math.abs(p.x), Math.abs(p.y)); + } + } + } + const half = reach * 1.12; + Object.assign(camera, { left: -half, right: half, top: half, bottom: -half }); + camera.updateProjectionMatrix(); + return camera; +} + +/** A PNG data URL of an item (cached per type and size). `packs` are needed for pack furniture. */ +export function furniturePreview(item: PreviewItem, size = 180, packs?: FurniturePack[], brightness = 1.3): string { + const key = [item.type, item.w, item.d, item.h, item.variant ?? "", size, brightness].join("|"); + const cached = cache.get(key); + if (cached) return cached; + if (packs) setPacks(packs); + renderer ??= new WebGLRenderer({ alpha: true, antialias: true, preserveDrawingBuffer: true }); + renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1)); + renderer.setSize(size, size, false); + renderer.setClearColor(0x000000, 0); + + const [solids, lines] = [new GeoBuffer(), new LineBuffer()]; + drawItem(item, solids, lines); + // the neon palette is made for a dark room: pictures get a little more light and brighter edges + const mesh = new Mesh(solids.geometry(), new MeshBasicMaterial({ vertexColors: true, color: new Color(brightness, brightness, brightness) })); + const edges = new LineSegments(lines.geometry(), new LineBasicMaterial({ vertexColors: true, color: new Color(brightness * 1.8, brightness * 1.8, brightness * 1.8) })); + const scene = new Scene(); + scene.add(mesh, edges); + renderer.render(scene, fitCamera(new Box3().setFromObject(mesh))); + const url = renderer.domElement.toDataURL("image/png"); + + for (const part of [mesh, edges]) { + part.geometry.dispose(); + (part.material as MeshBasicMaterial | LineBasicMaterial).dispose(); + } + cache.set(key, url); + return url; +} diff --git a/frontend/src/viewer/quality-governor.test.ts b/frontend/src/viewer/quality-governor.test.ts new file mode 100644 index 0000000..810ac52 --- /dev/null +++ b/frontend/src/viewer/quality-governor.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { QualityGovernor } from "./quality-governor.ts"; + +/** Feeds `n` frames of `dt` ms and collects the steps asked for. */ +function run(g: QualityGovernor, dt: number, n: number, start = 0) { + const steps = []; + for (let i = 0; i < n; i++) { + const s = g.frame(dt, start + i * dt); + if (s) steps.push(s); + } + return steps; +} + +test("a fast tablet keeps its pixels", () => { + assert.deepEqual(run(new QualityGovernor(2), 16, 600), []); +}); + +test("a slow tablet loses pixels step by step, then gets the simple look", () => { + const g = new QualityGovernor(2); + // 80 ms frames: 12 frames a second + const steps = run(g, 80, 2000); + assert.deepEqual(steps.slice(0, 4), [{ ratio: 1.75 }, { ratio: 1.5 }, { ratio: 1.25 }, { ratio: 1 }]); + assert.deepEqual(steps.at(-1), { low: true }); +}); + +test("a tablet that is only a bit slow stays at fewer pixels, and gets them back when it is fast again", () => { + const g = new QualityGovernor(2); + // 30 ms frames (33 fps) are fine: nothing changes + assert.deepEqual(run(g, 30, 500), []); + run(g, 45, 200); + assert.ok(g.pixelRatio < 2); + const lowered = g.pixelRatio; + // fast again, but only after half a minute + assert.deepEqual(run(g, 10, 200, 1_000_000)[0], { ratio: lowered + 0.25 }); +}); + +test("one hiccup does not count", () => { + const g = new QualityGovernor(2); + const frames = Array.from({ length: 300 }, (_, i) => (i % 20 === 0 ? 90 : 16)); + assert.deepEqual(frames.map((dt, i) => g.frame(dt, i * 16)).filter(Boolean), []); +}); diff --git a/frontend/src/viewer/quality-governor.ts b/frontend/src/viewer/quality-governor.ts new file mode 100644 index 0000000..e25de51 --- /dev/null +++ b/frontend/src/viewer/quality-governor.ts @@ -0,0 +1,68 @@ +// Quality by itself: while the picture moves, the frame times are watched; a tablet that keeps drawing too slowly gets fewer pixels, +// step by step, and the simple look when even one pixel per point is too much. With plenty of room left the pixels come back slowly. + +/** What the governor asks for: another pixel ratio, or the low quality level. */ +export type QualityStep = { ratio: number } | { low: true } | null; + +const WINDOW = 45; +const SLOW_FPS = 26; +const VERY_SLOW_FPS = 16; +const FAST_FPS = 55; +const STEP = 0.25; +/** Frames after a change before the next measurement counts (the new size settles). */ +const SETTLE = 30; +/** No step up within this long after a step down (ms): no flicker between two levels. */ +const UP_DELAY = 30_000; + +export class QualityGovernor { + private times: number[] = []; + private settle = SETTLE; + private ratio: number; + private lastDown = -Infinity; + private slowAtFloor = 0; + private readonly max: number; + private readonly min: number; + + constructor(max: number, min = 1) { + this.max = max; + this.min = min; + this.ratio = max; + } + + get pixelRatio(): number { + return this.ratio; + } + + /** One frame while something moves (`dt` in ms, `now` the frame's time). Returns a step when one is due. */ + frame(dt: number, now: number): QualityStep { + if (this.settle > 0) { + this.settle--; + return null; + } + if (dt <= 0 || dt >= 100) return null; + this.times.push(dt); + if (this.times.length < WINDOW) return null; + const sorted = [...this.times].sort((a, b) => a - b); + this.times = []; + // the median frame: one hiccup (a garbage collection) does not count + const fps = 1000 / sorted[Math.floor(sorted.length / 2)]; + if (fps < SLOW_FPS && this.ratio > this.min + 1e-6) { + this.ratio = Math.max(this.min, Math.round((this.ratio - STEP) * 100) / 100); + this.lastDown = now; + this.settle = SETTLE; + return { ratio: this.ratio }; + } + if (fps < VERY_SLOW_FPS && this.ratio <= this.min + 1e-6) { + // two slow windows in a row at the lowest ratio: the simple look + if (++this.slowAtFloor >= 2) return { low: true }; + return null; + } + this.slowAtFloor = 0; + if (fps > FAST_FPS && this.ratio < this.max - 1e-6 && now - this.lastDown > UP_DELAY) { + this.ratio = Math.min(this.max, Math.round((this.ratio + STEP) * 100) / 100); + this.settle = SETTLE; + return { ratio: this.ratio }; + } + return null; + } +} diff --git a/frontend/src/viewer/robot-trail.test.ts b/frontend/src/viewer/robot-trail.test.ts new file mode 100644 index 0000000..050ab45 --- /dev/null +++ b/frontend/src/viewer/robot-trail.test.ts @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { TRAIL_FADE_MS, TRAIL_HOLD_MS, trailGeometry, trailOpacity } from "./robot-trail.ts"; + +const positions = (g: ReturnType) => Array.from(g.getAttribute("position").array as ArrayLike); + +test("a straight trail of one segment is a quad at the given width and height", () => { + const g = trailGeometry([[[0, 0], [2, 0]]], 0.16, 0.01); + const p = positions(g); + assert.equal(p.length / 3, 6, "two triangles"); + // a float32 buffer, so every comparison here allows for its rounding + assert.ok(p.filter((_, i) => i % 3 === 1).every((y) => Math.abs(y - 0.01) < 1e-6), "every vertex at the given height"); + const zs = p.filter((_, i) => i % 3 === 2); + assert.ok(Math.abs(Math.min(...zs) + 0.08) < 1e-6 && Math.abs(Math.max(...zs) - 0.08) < 1e-6, "0.16 m wide"); + const xs = p.filter((_, i) => i % 3 === 0); + assert.ok(Math.abs(Math.min(...xs)) < 1e-6 && Math.abs(Math.max(...xs) - 2) < 1e-6, "from end to end"); +}); + +test("a bend gets a disc, a joint that barely turns does not", () => { + const quad = positions(trailGeometry([[[0, 0], [1, 0]]], 0.16, 0)).length; + const straight = positions(trailGeometry([[[0, 0], [1, 0], [2, 0]]], 0.16, 0)).length; + assert.equal(straight, quad * 2, "two steps, and a joint that does not turn adds nothing"); + const bent = trailGeometry([[[0, 0], [1, 0], [1, 1]]], 0.16, 0); + assert.ok(positions(bent).length > straight, "a real bend adds the disc that fills the notch"); + const slight = trailGeometry([[[0, 0], [1, 0], [2, 0.1]]], 0.16, 0); + assert.equal(positions(slight).length, straight, "five degrees is not a notch worth a disc"); +}); + +test("a trail of dots leaves nothing to draw", () => { + assert.equal(positions(trailGeometry([[[0, 0], [0, 0]]], 0.16, 0)).length, 0, "a zero-length step"); + assert.equal(positions(trailGeometry([], 0.16, 0)).length, 0, "no segments at all"); + assert.equal(positions(trailGeometry([[[1, 1]]], 0.16, 0)).length, 0, "one point is no way"); +}); + +test("several segments are drawn one after another", () => { + const one = positions(trailGeometry([[[0, 0], [1, 0]]], 0.16, 0)).length; + const two = positions(trailGeometry([[[0, 0], [1, 0]], [[2, 0], [3, 0]]], 0.16, 0)).length; + assert.equal(two, one * 2); +}); + +test("the pad stays full for ten minutes after the robot stops, then fades", () => { + const docked = 1_000_000; + assert.equal(trailOpacity(null, docked), 1, "still cleaning: full"); + assert.equal(trailOpacity(docked, docked), 1, "just docked"); + assert.equal(trailOpacity(docked, docked + TRAIL_HOLD_MS - 1), 1, "one millisecond before the hold ends"); + assert.equal(trailOpacity(docked, docked + TRAIL_HOLD_MS), 1, "the hold ends where the fade starts"); + const half = trailOpacity(docked, docked + TRAIL_HOLD_MS + TRAIL_FADE_MS / 2); + assert.ok(Math.abs(half - 0.5) < 1e-9, `halfway through the fade: ${half}`); + assert.equal(trailOpacity(docked, docked + TRAIL_HOLD_MS + TRAIL_FADE_MS), 0, "gone at the end"); + assert.equal(trailOpacity(docked, docked + 10 * TRAIL_HOLD_MS), 0, "and stays gone"); +}); diff --git a/frontend/src/viewer/robot-trail.ts b/frontend/src/viewer/robot-trail.ts new file mode 100644 index 0000000..b26ccc6 --- /dev/null +++ b/frontend/src/viewer/robot-trail.ts @@ -0,0 +1,71 @@ +/** + * The pad a robot has driven on, drawn flat on the floor: a ribbon along its trail, with a disc at every + * bend so the turns do not fray. The robot's own app draws the same thing, and it is what makes "where has + * it been" readable in the plan rather than a hairline. + */ +import { BufferGeometry, Float32BufferAttribute } from "three"; +import type { Vec2 } from "../model.ts"; + +/** How long the pad stays after the robot stopped cleaning: ten minutes, then it fades. */ +export const TRAIL_HOLD_MS = 10 * 60 * 1000; +/** How long the fade itself takes. */ +export const TRAIL_FADE_MS = 3000; + +/** + * How strongly the pad still shows, 1 while it drives and for ten minutes after it stopped, then fading to + * 0. The timeline is where the day's cleans stay, so the floor does not keep last night's pad forever. + */ +export function trailOpacity(settledAt: number | null | undefined, now: number): number { + if (settledAt == null) return 1; + const settled = now - settledAt; + if (!(settled > TRAIL_HOLD_MS)) return 1; + return Math.max(0, 1 - (settled - TRAIL_HOLD_MS) / TRAIL_FADE_MS); +} + +/** + * A flat ribbon along `segments`, `width` metres wide, lying at height `y`. One quad per segment and a + * disc at every interior joint; a trail shorter than a millimetre leaves an empty geometry. + */ +export function trailGeometry(segments: readonly (readonly Vec2[])[], width: number, y: number): BufferGeometry { + const half = width / 2; + const pos: number[] = []; + const tri = (a: Vec2, b: Vec2, c: Vec2) => pos.push(a[0], y, a[1], b[0], y, b[1], c[0], y, c[1]); + for (const line of segments) { + for (let i = 0; i + 1 < line.length; i++) { + const [p, q] = [line[i], line[i + 1]]; + const [dx, dz] = [q[0] - p[0], q[1] - p[1]]; + const len = Math.hypot(dx, dz); + if (len < 1e-4) continue; + const [nx, nz] = [(-dz / len) * half, (dx / len) * half]; + const [a, b]: [Vec2, Vec2] = [ + [p[0] + nx, p[1] + nz], + [p[0] - nx, p[1] - nz], + ]; + const [c, d]: [Vec2, Vec2] = [ + [q[0] + nx, q[1] + nz], + [q[0] - nx, q[1] - nz], + ]; + tri(a, b, c); + tri(b, d, c); + } + // a joint: a disc as wide as the ribbon, so two segments meeting at an angle leave no notch — a joint that + // barely turns needs none, and a dense trail is nearly all such joints + const steps = 6; + for (let i = 1; i + 1 < line.length; i++) { + const [b0, b1, b2] = [line[i - 1], line[i], line[i + 1]]; + const [ax, az] = [b1[0] - b0[0], b1[1] - b0[1]]; + const [bx, bz] = [b2[0] - b1[0], b2[1] - b1[1]]; + const [la, lb] = [Math.hypot(ax, az), Math.hypot(bx, bz)]; + // the sine of the angle between the two steps: below this the quads already meet + if (la < 1e-9 || lb < 1e-9 || Math.abs(ax * bz - az * bx) / (la * lb) < 0.2) continue; + const [cx, cz] = line[i]; + for (let k = 0; k < steps; k++) { + const [a0, a1] = [(k / steps) * Math.PI * 2, ((k + 1) / steps) * Math.PI * 2]; + tri([cx, cz], [cx + Math.cos(a0) * half, cz + Math.sin(a0) * half], [cx + Math.cos(a1) * half, cz + Math.sin(a1) * half]); + } + } + } + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute(pos, 3)); + return geometry; +} diff --git a/frontend/src/viewer/robot.test.ts b/frontend/src/viewer/robot.test.ts new file mode 100644 index 0000000..4ba771b --- /dev/null +++ b/frontend/src/viewer/robot.test.ts @@ -0,0 +1,87 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { pointInPolygon, type Vec2 } from "../model.ts"; +import { circlePath, cleaningPath, ROBOT_SPEED, stepRobot, type RobotInfo, type RobotMotion } from "./robot.ts"; + +const hall: Vec2[] = [[0, 0], [6, 0], [6, 3], [0, 3]]; +const info = (mode: RobotInfo["mode"], extra: Partial = {}): RobotInfo => ({ id: "r", floorId: "f", rest: [0, 0], restHeading: 0, mode, room: hall, ...extra }); +const motion = (pos: Vec2, extra: Partial = {}): RobotMotion => ({ pos, heading: 0, path: [], next: 0, ...extra }); + +test("lanes run along the longer side, back and forth, and stay inside the room", () => { + const path = cleaningPath(hall); + assert.ok(path.length >= 16); + assert.ok(path.every((p) => pointInPolygon(p, hall))); + // along x: both ends of a lane share their z, and the next lane runs the other way + for (let i = 0; i + 1 < path.length; i += 2) assert.equal(path[i][1], path[i + 1][1]); + assert.ok(path[1][0] > path[0][0] && path[3][0] < path[2][0]); + // a tall room is cleaned along z + const tall: Vec2[] = [[0, 0], [3, 0], [3, 6], [0, 6]]; + const lane = cleaningPath(tall); + assert.equal(lane[0][0], lane[1][0]); +}); + +test("a narrow room gives fewer lanes than a wide one, and a closet gives none", () => { + assert.ok(cleaningPath([[0, 0], [6, 0], [6, 1], [0, 1]]).length < cleaningPath(hall).length); + assert.deepEqual(cleaningPath([[0, 0], [0.3, 0], [0.3, 0.3], [0, 0.3]]), []); +}); + +test("lanes keep out of the missing corner of an L-shaped room", () => { + const l: Vec2[] = [[0, 0], [4, 0], [4, 2], [2, 2], [2, 4], [0, 4]]; + assert.ok(cleaningPath(l).every((p) => pointInPolygon(p, l))); +}); + +test("lanes keep clear of furniture and never cross it when changing lanes", () => { + const room: Vec2[] = [[0, 0], [5, 0], [5, 4], [0, 4]]; + const wardrobe: Vec2[] = [[0, 0], [2, 0], [2, 0.6], [0, 0.6]]; + const sofa: Vec2[] = [[2, 1.8], [4, 1.8], [4, 2.7], [2, 2.7]]; + const path = cleaningPath(room, 0.32, 0.22, [wardrobe, sofa]); + assert.ok(path.length >= 4); + for (let i = 1; i < path.length; i++) { + const [a, b] = [path[i - 1], path[i]]; + for (let t = 0; t <= 1; t += 0.02) { + const p: Vec2 = [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]; + assert.ok(!pointInPolygon(p, wardrobe) && !pointInPolygon(p, sofa), `segment ${i} crosses furniture`); + } + } +}); + +test("the circle path surrounds its centre at the given radius", () => { + const circle = circlePath([1, 2], 0.5, 8); + assert.equal(circle.length, 8); + for (const p of circle) assert.ok(Math.abs(Math.hypot(p[0] - 1, p[1] - 2) - 0.5) < 1e-9); + assert.equal(circlePath([0, 0]).length, 12); +}); + +test("a returning robot turns on the spot first, then drives home and faces away from the dock", () => { + const m = motion([2, 0]); + const robot = info("returning"); + stepRobot(m, robot, 0.1); + assert.deepEqual(m.pos, [2, 0], "facing +z while the dock lies at -x: only turning"); + let steps = 0; + while (stepRobot(m, robot, 0.05) && steps++ < 600); + assert.ok(Math.hypot(...m.pos) < 0.03); + assert.ok(Math.abs(m.heading - robot.restHeading) < 0.05); + assert.equal(stepRobot(m, robot, 0.05), false, "at rest it stays"); +}); + +test("it never drives faster than its speed", () => { + const m = motion([3, 0], { heading: -Math.PI / 2 }); + const before = m.pos[0]; + stepRobot(m, info("returning"), 1); + assert.ok(before - m.pos[0] <= ROBOT_SPEED + 1e-9); +}); + +test("a cleaning robot follows its path round and round; idle, error and path-less robots stay put", () => { + const path: Vec2[] = [[1, 1], [1, 2]]; + const m = motion([1, 1], { path, heading: 0 }); + const robot = info("cleaning"); + const seen = new Set(); + for (let i = 0; i < 400; i++) { + stepRobot(m, robot, 0.05); + seen.add(m.next); + } + assert.deepEqual([...seen].sort(), [0, 1], "it keeps going between its two points"); + assert.equal(stepRobot(motion([1, 1]), robot, 0.05), false, "no path: nothing to do"); + assert.equal(stepRobot(motion([1, 1]), info("idle"), 0.05), false); + assert.equal(stepRobot(motion([1, 1]), info("error"), 0.05), false); +}); diff --git a/frontend/src/viewer/robot.ts b/frontend/src/viewer/robot.ts new file mode 100644 index 0000000..d699c5d --- /dev/null +++ b/frontend/src/viewer/robot.ts @@ -0,0 +1,153 @@ +// Robot vacuums in 3D. Home Assistant reports the state (cleaning, returning, docked ...) but usually not where the robot is. +// So while it cleans it drives lanes through the room its dock stands in, returns to the dock when it goes home, and waits in +// front of the dock otherwise. + +import { pointInPolygon, type Vec2 } from "../model.ts"; + +export type RobotMode = "cleaning" | "returning" | "docked" | "idle" | "error"; + +export interface RobotInfo { + /** The furniture item (the dock). */ + id: string; + floorId: string; + /** Where the robot rests: in front of its dock, facing away from it (radians). */ + rest: Vec2; + restHeading: number; + mode: RobotMode; + /** The outline of the room it cleans; null means circles near the dock. */ + room: Vec2[] | null; + /** The id of that room: a new room starts new lanes. */ + roomId?: string | null; + /** Footprints of the furniture in its way (cabinets, sofas, beds; not tables or chairs). */ + obstacles?: Vec2[][]; + /** Height it drives at above its floor (a robot mower on the lawn below the ground floor). */ + y?: number; + /** The pad it has driven on, from its own map (segments in the plan); null keeps the drawn lanes. */ + track?: Vec2[][] | null; + /** Where it really is, from its own map; null lets it drive the drawn lanes. */ + pose?: { x: number; z: number; heading: number } | null; + /** When it stopped cleaning (ms since the epoch), so its pad can fade; null while it still drives. */ + settledAt?: number | null; + /** A robot mower: a larger, green body. */ + mower?: boolean; +} + +/** Driving speed in m/s and turning speed in rad/s. */ +export const ROBOT_SPEED = 0.3; +export const ROBOT_TURN = 2.6; + +const SAMPLE = 0.05; + +/** Whether a spot is free for the robot: clear of the walls on all four sides, and of furniture also on the diagonals. */ +function spotIsFree(p: Vec2, room: Vec2[], obstacles: readonly Vec2[][], inset: number): boolean { + const diagonal = inset * 0.7071; + const sides: Vec2[] = [p, [p[0] + inset, p[1]], [p[0] - inset, p[1]], [p[0], p[1] + inset], [p[0], p[1] - inset]]; + const corners: Vec2[] = [[p[0] + diagonal, p[1] + diagonal], [p[0] - diagonal, p[1] + diagonal], [p[0] + diagonal, p[1] - diagonal], [p[0] - diagonal, p[1] - diagonal]]; + return sides.every((q) => pointInPolygon(q, room)) && !obstacles.some((o) => [...sides, ...corners].some((q) => pointInPolygon(q, o))); +} + +/** Whether a straight drive from p to q stays free all the way. */ +function driveIsClear(p: Vec2, q: Vec2, free: (spot: Vec2) => boolean): boolean { + const steps = Math.ceil(Math.hypot(q[0] - p[0], q[1] - p[1]) / SAMPLE); + for (let i = 1; i < steps; i++) if (!free([p[0] + ((q[0] - p[0]) * i) / steps, p[1] + ((q[1] - p[1]) * i) / steps])) return false; + return true; +} + +/** The longest stretch of free samples across the room along one lane, or null. */ +function longestRun(isFree: (b: number) => boolean, from: number, to: number): [number, number] | null { + let best: [number, number] | null = null; + let start: number | null = null; + for (let b = from; b <= to + 1e-6; b += SAMPLE) { + const free = isFree(b); + if (free) start ??= b; + if ((!free || b + SAMPLE > to + 1e-6) && start !== null) { + const end = free ? b : b - SAMPLE; + if (!best || end - start > best[1] - best[0]) best = [start, end]; + start = null; + } + } + return best; +} + +/** + * Lanes through a room, back and forth along its longer side, keeping `inset` from the walls and from furniture in the way. + * Each lane takes the longest free stretch; a lane that cannot be reached from the previous one without crossing furniture is + * left out. + */ +export function cleaningPath(room: Vec2[], lane = 0.32, inset = 0.22, obstacles: readonly Vec2[][] = []): Vec2[] { + const xs = room.map((p) => p[0]); + const zs = room.map((p) => p[1]); + const [x0, x1, z0, z1] = [Math.min(...xs), Math.max(...xs), Math.min(...zs), Math.max(...zs)]; + // lanes run along the longer side, which means fewer turns + const alongZ = z1 - z0 >= x1 - x0; + const free = (p: Vec2) => spotIsFree(p, room, obstacles, inset); + const at = (a: number, b: number): Vec2 => (alongZ ? [a, b] : [b, a]); + const [a0, a1, b0, b1] = alongZ ? [x0, x1, z0, z1] : [z0, z1, x0, x1]; + + const path: Vec2[] = []; + let forward = true; + for (let a = a0 + inset; a <= a1 - inset + 1e-6; a += lane) { + const run = longestRun((b) => free(at(a, b)), b0, b1); + if (!run || run[1] - run[0] < 0.2) continue; + const ends = (towardsEnd: boolean): [Vec2, Vec2] => (towardsEnd ? [at(a, run[0]), at(a, run[1])] : [at(a, run[1]), at(a, run[0])]); + let lanePoints = ends(forward); + const previous = path[path.length - 1]; + if (previous && obstacles.length > 0 && !driveIsClear(previous, lanePoints[0], free)) { + // the other way round, or leave the lane out when furniture is in the way either way + const reversed = ends(!forward); + if (!driveIsClear(previous, reversed[0], free)) continue; + lanePoints = reversed; + forward = !forward; + } + path.push(...lanePoints); + forward = !forward; + } + return path; +} + +/** A small circle in front of the dock, for robots outside any room. */ +export function circlePath(center: Vec2, radius = 0.7, points = 12): Vec2[] { + return Array.from({ length: points }, (_, i): Vec2 => [center[0] + Math.cos((i / points) * Math.PI * 2) * radius, center[1] + Math.sin((i / points) * Math.PI * 2) * radius]); +} + +/** The moving state of one robot. */ +export interface RobotMotion { + pos: Vec2; + heading: number; + path: Vec2[]; + next: number; +} + +const wrapAngle = (a: number) => Math.atan2(Math.sin(a), Math.cos(a)); + +/** Advances a robot by `dt` seconds: it turns towards the next target and drives when it faces it. Returns whether it still moves. */ +export function stepRobot(m: RobotMotion, info: RobotInfo, dt: number): boolean { + let target: Vec2; + if (info.mode === "cleaning") { + if (m.path.length === 0) return false; + target = m.path[m.next % m.path.length]; + } else if (info.mode === "returning" || info.mode === "docked") target = info.rest; + else return false; + + const [dx, dz] = [target[0] - m.pos[0], target[1] - m.pos[1]]; + const distance = Math.hypot(dx, dz); + if (distance < 0.02) { + if (info.mode === "cleaning") { + m.next = (m.next + 1) % m.path.length; + return true; + } + // at home: turn to face away from the dock + const off = wrapAngle(info.restHeading - m.heading); + if (Math.abs(off) < 0.02) return false; + m.heading += Math.sign(off) * Math.min(Math.abs(off), ROBOT_TURN * dt); + return true; + } + // heading 0 faces +z; the robot turns on the spot before it drives + const off = wrapAngle(Math.atan2(dx, dz) - m.heading); + m.heading = wrapAngle(m.heading + Math.sign(off) * Math.min(Math.abs(off), ROBOT_TURN * dt)); + if (Math.abs(off) < 0.35) { + const step = Math.min(distance, ROBOT_SPEED * dt); + m.pos = [m.pos[0] + (dx / distance) * step, m.pos[1] + (dz / distance) * step]; + } + return true; +} diff --git a/frontend/src/viewer/roof.ts b/frontend/src/viewer/roof.ts new file mode 100644 index 0000000..7b82918 --- /dev/null +++ b/frontend/src/viewer/roof.ts @@ -0,0 +1,7 @@ +// The roof, split into modules in roof/: the single roof, roof sections, canopy frames, and what sits in a roof. + +export { buildRoof } from "./roof/roof.ts"; +export { roofFloor } from "./roof/single.ts"; +export { pushSection } from "./roof/sections.ts"; +export { pushModules, type RoofWindowState } from "./roof/fittings.ts"; +export type { RoofGeometry } from "./roof/types.ts"; diff --git a/frontend/src/viewer/roof/canopy.ts b/frontend/src/viewer/roof/canopy.ts new file mode 100644 index 0000000..0ae4538 --- /dev/null +++ b/frontend/src/viewer/roof/canopy.ts @@ -0,0 +1,64 @@ +// The frame of a canopy: a beam under each free edge of the roof, posts at its corners and at most 3.5 m apart along the free sides. +// An edge against the house (no overhang) rests on the wall. + +import type { SectionOverhang } from "../../roof-sections.ts"; +import type { sectionFrame, sectionProfile } from "../../roof-sections.ts"; +import { EAVE, FRAME, FRAME_TOP } from "./palette.ts"; +import { pushPrism, type GeoBuffer, type LineBuffer } from "../geo.ts"; + +const POST = 0.12; +const BEAM = 0.16; + +export function pushCanopyFrame( + solid: GeoBuffer, + lines: LineBuffer, + frame: ReturnType, + profile: ReturnType, + overhang: SectionOverhang, + point: (u: number, v: number, y: number) => number[], + levelOffset: number, +): void { + const w = frame.w; + const [freeA, freeB, freeStart, freeEnd] = [overhang.a > 0, overhang.b > 0, overhang.u0 > 0, overhang.u1 > 0]; + const box = (u0: number, u1: number, v0: number, v1: number, y0: number, y1: number) => { + const ring = [frame.at(u0, v0), frame.at(u1, v0), frame.at(u1, v1), frame.at(u0, v1)]; + // the frame may be flipped: keep the outline counter-clockwise + const turn = (ring[1][0] - ring[0][0]) * (ring[2][1] - ring[0][1]) - (ring[2][0] - ring[0][0]) * (ring[1][1] - ring[0][1]); + pushPrism(solid, turn < 0 ? [...ring].reverse() : ring, y0 - levelOffset, y1 - levelOffset, FRAME, FRAME_TOP, { bottom: true }); + }; + + // beams along the free long sides, under the roof at its height there + for (const [v, free] of [[0, freeA], [w, freeB]] as const) { + if (!free) continue; + const y = profile.y(v) - 0.03; + const start = v === 0 ? 0 : w - POST; + box(frame.u0, frame.u1, start, start + POST, y - BEAM, y); + lines.seg(point(frame.u0, v, y - BEAM), point(frame.u1, v, y - BEAM), EAVE); + } + // beams along the free ends, following the slope in six steps + for (const [u, free] of [[frame.u0, freeStart], [frame.u1 - POST, freeEnd]] as const) { + if (!free) continue; + for (let i = 0; i < 6; i++) { + const [v0, v1] = [(w * i) / 6, (w * (i + 1)) / 6]; + const y = Math.min(profile.y(v0), profile.y(v1)) - 0.03; + box(u, u + POST, v0, v1, y - BEAM, y); + } + } + // posts: at corners where both edges are free (a corner at the house wall rests on the wall), and along a free long side at most 3.5 m apart + const posts: [number, number][] = []; + for (const [v, free] of [[0, freeA], [w - POST, freeB]] as const) { + if (!free) continue; + const span = frame.u1 - frame.u0 - POST; + const count = Math.max(1, Math.ceil(span / 3.5)); + for (let i = 0; i <= count; i++) { + if ((i === 0 && !freeStart) || (i === count && !freeEnd)) continue; + posts.push([frame.u0 + (span * i) / count, v]); + } + } + // a pent roof against the house with only its ends free still needs posts at its outer corners + if (!freeA && !freeB) { + if (freeStart) posts.push([frame.u0, w / 2 - POST / 2]); + if (freeEnd) posts.push([frame.u1 - POST, w / 2 - POST / 2]); + } + for (const [u, v] of posts) box(u, u + POST, v, v + POST, levelOffset, profile.y(v + POST / 2) - 0.03 - BEAM); +} diff --git a/frontend/src/viewer/roof/fittings.ts b/frontend/src/viewer/roof/fittings.ts new file mode 100644 index 0000000..a815f60 --- /dev/null +++ b/frontend/src/viewer/roof/fittings.ts @@ -0,0 +1,165 @@ +// What sits in a roof: solar modules and roof windows. + +import type { Building, SolarField } from "../../model.ts"; +import { chimneyPlace, chimneySize, fieldModules, roofFaces, windowCorners, type RoofFace } from "../../solar.ts"; +import { DEG, pushPrism, type GeoBuffer, type LineBuffer } from "../geo.ts"; +import type { Vec2 } from "../../model.ts"; +import { CHIMNEY, CHIMNEY_CAP, CHIMNEY_EDGE, CHIMNEY_FLUE, CHIMNEY_STEEL, CHIMNEY_STEEL_TOP, CHIMNEY_TOP, PANEL_LOOKS, PANEL_POST, WINDOW_BLIND, WINDOW_FRAME, WINDOW_GLASS, WINDOW_WARM } from "./palette.ts"; +import type { RoofGeometry } from "./types.ts"; + +/** How far a roof window's sash is open (1 = open, a tilt counts less) and how far its blind is down. */ +export interface RoofWindowState { + open: number; + tilt: number; + cover: number; +} + +type P3 = number[]; +const lerp3 = (p: P3, q: P3, t: number): P3 => [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t]; +const along = (p: P3, direction: readonly number[], k: number): P3 => [p[0] + direction[0] * k, p[1] + direction[1] * k, p[2] + direction[2] * k]; + +/** The part of the roof a face belongs to: the one carrying its section, or the first part for the single roof. */ +const partOf = (parts: RoofGeometry[], face: RoofFace): RoofGeometry | undefined => (face.section ? parts.find((p) => p.sections?.includes(face.section!)) : parts[0]); + +/** Roof windows: frame and glass in the slope; the sash swings out at the top when open, and the blind comes down. */ +export function pushRoofWindows(b: Building, parts: RoofGeometry[], states: ReadonlyMap): void { + const windows = b.settings.roof?.windows ?? []; + if (windows.length === 0 || parts.length === 0) return; + const faces = new Map(roofFaces(b).map((f) => [f.key, f])); + for (const w of windows) { + const face = faces.get(w.face); + const corners = face ? windowCorners(face, w) : null; + const part = face && corners ? partOf(parts, face) : undefined; + if (!face || !corners || !part) continue; + const shift = part.floor.elevation + part.base; + const [a, c, d, e] = corners.map((p): P3 => [p[0], p[1] - shift, p[2]]); + const state = states.get(w.id) ?? { open: 0, tilt: 0, cover: 0 }; + const raised = (p: P3, k: number) => along(p, face.n, k); + + // the fixed frame in the roof, glowing warm while the window is open or tilted + const frame = state.open > 0.02 || state.tilt > 0.02 ? WINDOW_WARM : WINDOW_FRAME; + const ring = [a, c, d, e].map((p) => raised(p, 0.06)); + ring.forEach((p, i) => part.lines.seg(p, ring[(i + 1) % 4], frame)); + + // the sash is hinged at the top: its lower edge swings out along the normal (up to 30° open, as far as a motor reports; 12° tilted) + const angle = (state.open > 0.02 ? 30 * Math.min(1, state.open) : state.tilt > 0.5 ? 12 : 0) * DEG; + const height = Math.hypot(d[0] - c[0], d[1] - c[1], d[2] - c[2]); + const swing = (top: P3): P3 => along(along(top, face.es, -height * Math.cos(angle)), face.n, height * Math.sin(angle)); + const [top0, top1] = [raised(e, 0.065), raised(d, 0.065)]; + const [bottom0, bottom1] = [swing(top0), swing(top1)]; + part.solid.tri(bottom0, bottom1, top1, WINDOW_GLASS); + part.solid.tri(bottom0, top1, top0, WINDOW_GLASS); + for (const [p, q] of [[bottom0, bottom1], [bottom1, top1], [top1, top0], [top0, bottom0]]) part.lines.seg(p, q, frame); + + // the blind comes down from the top over the sash + if (state.cover > 0.02) { + const k = Math.min(1, state.cover); + const [b0, b1] = [raised(lerp3(top0, bottom0, k), 0.01), raised(lerp3(top1, bottom1, k), 0.01)]; + const [t0, t1] = [raised(top0, 0.01), raised(top1, 0.01)]; + part.solid.tri(b0, b1, t1, WINDOW_BLIND); + part.solid.tri(b0, t1, t0, WINDOW_BLIND); + } + } +} + +/** The modules of a field (glass, frame, cell grid, stands on flat ground), lowered by `dy` into local coordinates. */ +export function pushModules(solid: GeoBuffer, lines: LineBuffer, face: RoofFace, field: SolarField, dy: number): void { + const lower = (p: P3): P3 => [p[0], p[1] - dy, p[2]]; + const look = PANEL_LOOKS[field.look === "blue" ? "blue" : "black"]; + const [cellsAcross, cellsUp] = field.portrait === false ? [10, 6] : [6, 10]; + for (const module of fieldModules(face, field)) { + const [a, c, d, e] = module.corners.map(lower); + // both sides: on a floor (garden, walls) only front faces are drawn, and a module may lean either way + for (const [p, q, r] of [[a, c, d], [a, d, e], [a, d, c], [a, e, d]]) solid.tri(p, q, r, look.glass); + // the frame a hair above the glass, and the cell grid + const lifted = (p: P3) => along(p, face.n, 0.004); + const ring = [a, c, d, e].map(lifted); + ring.forEach((p, i) => lines.seg(p, ring[(i + 1) % 4], look.edge)); + for (let i = 1; i < cellsAcross; i++) lines.seg(lifted(lerp3(a, c, i / cellsAcross)), lifted(lerp3(e, d, i / cellsAcross)), look.cells); + for (let j = 1; j < cellsUp; j++) lines.seg(lifted(lerp3(a, e, j / cellsUp)), lifted(lerp3(c, d, j / cellsUp)), look.cells); + for (const [p, q] of module.posts) lines.seg(lower(p), lower(q), PANEL_POST); + } +} + +/** Solar fields on the roof: every module on its face, in the coordinates of the roof part the face belongs to. */ +export function pushSolar(b: Building, parts: RoofGeometry[]): void { + const fields = b.settings.roof?.solar ?? []; + if (fields.length === 0 || parts.length === 0) return; + const faces = new Map(roofFaces(b).map((f) => [f.key, f])); + for (const field of fields) { + const face = faces.get(field.face); + const part = face ? partOf(parts, face) : undefined; + // faces have heights above the ground; parts count from their floor's level plus their base + if (face && part) pushModules(part.solid, part.lines, face, field, part.floor.elevation + part.base); + } +} + +/** + * Chimneys: upright from inside the roof to `h` above its upper side. Brick and wide ones get a cap and their black flues on + * top, a round one a flue in its middle, a steel pipe a rain cap held a little above it. + */ +export function pushChimneys(b: Building, parts: RoofGeometry[]): void { + const chimneys = b.settings.roof?.chimneys ?? []; + if (chimneys.length === 0 || parts.length === 0) return; + const faces = new Map(roofFaces(b).map((f) => [f.key, f])); + for (const c of chimneys) { + const face = faces.get(c.face); + const part = face ? partOf(parts, face) : undefined; + if (!face || !part) continue; + const shift = part.floor.elevation + part.base; + const { shape, w, d, h } = chimneySize(c); + const place = chimneyPlace(face, c); + const [y0, y1] = [place.low - shift - 0.1, place.high - shift + h]; + const rect = (hw: number, hd: number): Vec2[] => { + const { center: m, along: a, across: x } = place; + const p = (su: number, sd: number): Vec2 => [m[0] + a[0] * hw * su + x[0] * hd * sd, m[1] + a[1] * hw * su + x[1] * hd * sd]; + return [p(-1, -1), p(1, -1), p(1, 1), p(-1, 1)]; + }; + const circle = (r: number, n = 16): Vec2[] => Array.from({ length: n }, (_, i) => [place.center[0] + Math.cos((i / n) * 2 * Math.PI) * r, place.center[1] + Math.sin((i / n) * 2 * Math.PI) * r] as Vec2); + const outline = (poly: Vec2[], y: number) => poly.forEach((p, i) => part.lines.seg([p[0], y, p[1]], [poly[(i + 1) % poly.length][0], y, poly[(i + 1) % poly.length][1]], CHIMNEY_EDGE)); + const prism = (poly: Vec2[], from: number, to: number, side: number, top: number) => pushPrism(part.solid, ensureCcw(poly), from, to, side, top); + if (shape === "steel") { + const r = Math.min(w, d) / 2; + prism(circle(r, 12), y0, y1, CHIMNEY_STEEL, CHIMNEY_STEEL_TOP); + prism(circle(r * 0.75, 12), y1, y1 + 0.001, CHIMNEY_FLUE, CHIMNEY_FLUE); + // the rain cap on its little stand + prism(circle(r * 0.25, 6), y1, y1 + 0.1, CHIMNEY_STEEL, CHIMNEY_STEEL_TOP); + const hat = circle(r * 1.9, 12); + prism(hat, y1 + 0.1, y1 + 0.13, CHIMNEY_STEEL, CHIMNEY_STEEL_TOP); + outline(hat, y1 + 0.13); + continue; + } + if (shape === "round") { + const r = Math.min(w, d) / 2; + const body = circle(r); + prism(body, y0, y1, CHIMNEY, CHIMNEY_TOP); + prism(circle(r * 0.55), y1, y1 + 0.002, CHIMNEY_FLUE, CHIMNEY_FLUE); + outline(body, y1); + continue; + } + // brick and wide: the shaft, a cap a little wider, and the flues on top + const body = rect(w / 2, d / 2); + prism(body, y0, y1, CHIMNEY, CHIMNEY_TOP); + const cap = rect(w / 2 + 0.04, d / 2 + 0.04); + prism(cap, y1, y1 + 0.06, CHIMNEY_CAP, CHIMNEY_CAP); + outline(cap, y1 + 0.06); + outline(body, y1 - 0.25); + const flue = Math.min(w, d) * 0.25; + const flues = shape === "wide" ? [-w / 4, w / 4] : [0]; + for (const off of flues) { + const m: Vec2 = [place.center[0] + place.along[0] * off, place.center[1] + place.along[1] * off]; + const pipe: Vec2[] = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([su, sd]) => [m[0] + place.along[0] * flue * su + place.across[0] * flue * sd, m[1] + place.along[1] * flue * su + place.across[1] * flue * sd]); + prism(pipe, y1 + 0.06, y1 + 0.16, CHIMNEY_CAP, CHIMNEY_FLUE); + } + } +} + +/** pushPrism wants its ring counter-clockwise in the plan (seen from above). */ +function ensureCcw(poly: Vec2[]): Vec2[] { + let area = 0; + for (let i = 0; i < poly.length; i++) { + const [p, q] = [poly[i], poly[(i + 1) % poly.length]]; + area += p[0] * q[1] - q[0] * p[1]; + } + return area < 0 ? [...poly].reverse() : poly; +} diff --git a/frontend/src/viewer/roof/palette.ts b/frontend/src/viewer/roof/palette.ts new file mode 100644 index 0000000..0075c97 --- /dev/null +++ b/frontend/src/viewer/roof/palette.ts @@ -0,0 +1,39 @@ +// Colours of the roof scene. + +import { Color } from "three"; +import { shade } from "../geo.ts"; + +export const ROOF = 0x1a2338; +export const ROOF_TOP = 0x222d48; +export const GABLE = 0x141d31; +export const RIDGE = shade(0x37e0ff, 0.9); +export const EAVE = shade(0x5b7cff, 0.45); +/** The thickness of the roof covering. */ +export const THICK = 0.14; + +/** A canopy has see-through panels and a light frame of posts and beams. */ +export const GLASS = 0x8fd8ff; +export const FRAME = 0xc9d3e6; +export const FRAME_TOP = 0xe3e9f5; + +/** Solar modules: all black (glass, frame, barely visible cells) or the classic blue. */ +export const PANEL_LOOKS = { + black: { glass: new Color(0x05070b), edge: shade(0x8a96b0, 0.32), cells: shade(0x2a3550, 0.22) }, + blue: { glass: new Color(0x15295a), edge: shade(0x9fb8ff, 0.55), cells: shade(0x3d6cff, 0.35) }, +}; +export const PANEL_POST = shade(0xc9d3e6, 0.5); + +/** Roof windows: a light frame, glass and the blind. The frame of an open or tilted window glows warm, like a wall window. */ +export const WINDOW_FRAME = shade(0xc9d3e6, 0.85); +export const WINDOW_WARM = shade(0xffb347, 0.95); +export const WINDOW_GLASS = new Color(0x2b6b8f); +export const WINDOW_BLIND = new Color(0x3a4258); + +/** Chimneys: brick or render, a darker cap, the black flue, and steel for a flue pipe. */ +export const CHIMNEY = 0x3a2b30; +export const CHIMNEY_TOP = 0x4a3840; +export const CHIMNEY_CAP = 0x2a3448; +export const CHIMNEY_FLUE = 0x05070b; +export const CHIMNEY_STEEL = 0x8b97ad; +export const CHIMNEY_STEEL_TOP = 0xb4c0d4; +export const CHIMNEY_EDGE = shade(0x5b7cff, 0.4); diff --git a/frontend/src/viewer/roof/roof.test.ts b/frontend/src/viewer/roof/roof.test.ts new file mode 100644 index 0000000..5cc0c06 --- /dev/null +++ b/frontend/src/viewer/roof/roof.test.ts @@ -0,0 +1,139 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { emptyBuilding, newFloor, type Building, type RoofSection, type Room } from "../../model.ts"; +import { proposeChimney, proposeField } from "../../solar/placing.ts"; +import { chimneyPlace, roofFaces } from "../../solar.ts"; +import { buildRoof, pushModules, roofFloor, pushSection } from "../roof.ts"; +import { GeoBuffer, LineBuffer } from "../geo.ts"; + +const room = (id: string, x0: number, z0: number, x1: number, z1: number): Room => ({ id, name: id, area_id: null, points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]], floor_material: "wood" }); + +function house(roof: Building["settings"]["roof"], floors: [string, number, Room[]][] = [["g", 0, [room("a", 0, 0, 10, 6)]]]): Building { + const b = emptyBuilding(); + b.floors = floors.map(([id, elevation, rooms]) => ({ ...newFloor(id, id, elevation), height: 2.6, rooms })); + b.settings = { ...b.settings, wall_exterior: 0.3, roof }; + return b; +} + +const topOf = (buf: GeoBuffer) => Math.max(...buf.p.filter((_, i) => i % 3 === 1)); +const section = (patch: Partial = {}): RoofSection => ({ id: "s", x0: 0, z0: 0, x1: 10, z1: 6, shape: "gable", axis: "x", eave_a: 2.6, eave_b: 2.6, pitch_a: 35, pitch_b: 35, base: 2.6, overhang: 0.4, ...patch }); + +test("no roof gives no parts", () => { + assert.deepEqual(buildRoof(house({ type: "none", pitch: 35, overhang: 0.4 })), []); + assert.deepEqual(buildRoof(emptyBuilding()), []); +}); + +test("the roof sits on the highest floor with rooms", () => { + const b = house({ type: "gable", pitch: 35, overhang: 0.4 }, [["g", 0, [room("a", 0, 0, 5, 5)]], ["u", 2.7, [room("b", 0, 0, 5, 5)]], ["empty", 5.4, []]]); + assert.equal(roofFloor(b)?.id, "u"); + const [part] = buildRoof(b); + assert.equal(part.floor.id, "u"); + assert.equal(part.base, 2.6); +}); + +test("a gable rises to half the roof's depth times its slope, with the ridge along the longer side", () => { + const [part] = buildRoof(house({ type: "gable", pitch: 40, overhang: 0.5 })); + const depth = 6 + 2 * 0.8; + assert.ok(Math.abs(topOf(part.solid) - (depth / 2) * Math.tan((40 * Math.PI) / 180)) < 0.01); + const ridgeLine = [...Array(part.lines.p.length / 6).keys()].find((s) => part.lines.p[s * 6 + 1] > 1 && part.lines.p[s * 6 + 4] === part.lines.p[s * 6 + 1] && part.lines.p[s * 6 + 2] === part.lines.p[s * 6 + 5])!; + assert.ok(ridgeLine !== undefined, "a ridge line along x at constant z"); +}); + +test("the ridge can run along the short side", () => { + const along = (ridge?: "short") => { + const [part] = buildRoof(house({ type: "gable", pitch: 40, overhang: 0.5, ridge })); + return topOf(part.solid); + }; + assert.ok(along("short") > along(undefined), "a longer span across means a higher ridge"); +}); + +test("a flat roof is a slab of 25 cm with an outline", () => { + const [part] = buildRoof(house({ type: "flat", pitch: 0, overhang: 0.4 })); + assert.ok(Math.abs(topOf(part.solid) - 0.25) < 1e-9); + assert.equal(part.lines.p.length / 6, 8); +}); + +test("sections: every shape draws something, and a canopy has glass instead of tiles", () => { + for (const shape of ["gable", "hip", "halfhip", "pyramid", "mansard", "pent", "flat", "parapet"] as const) { + const [part] = buildRoof(house({ type: "custom", pitch: 35, overhang: 0.4, sections: [section({ shape, pitch_a: shape === "mansard" ? 70 : 35, pitch_b: shape === "mansard" ? 70 : 35 })] })); + assert.ok(part.solid.count > 0, shape); + } + const [canopy] = buildRoof(house({ type: "custom", pitch: 35, overhang: 0.4, sections: [section({ open: true, shape: "pent", pitch_a: 5, pitch_b: 5, overhang: 0.5 })] })); + assert.ok(canopy.glass.count > 0); + assert.equal(canopy.lift, false); + assert.ok(canopy.solid.count > 0, "a frame of posts and beams"); +}); + +test("sections are grouped by the floor they sit on, closed roofs before canopies", () => { + const sections = [section({ id: "low", base: 2.6 }), section({ id: "canopy", open: true, shape: "pent" }), section({ id: "high", base: 5.3, eave_a: 5.3, eave_b: 5.3, x0: 0, x1: 5 })]; + const b = house({ type: "custom", pitch: 35, overhang: 0.4, sections }, [["g", 0, [room("a", 0, 0, 10, 6)]], ["u", 2.7, [room("b", 0, 0, 5, 6)]]]); + const parts = buildRoof(b); + assert.ok(parts.length >= 2); + assert.equal(parts[parts.length - 1].lift, false, "the canopy part last"); + assert.ok(parts.some((p) => p.sections?.includes("high"))); +}); + +test("tiny sections are ignored", () => { + assert.deepEqual(buildRoof(house({ type: "custom", pitch: 35, overhang: 0.4, sections: [section({ x1: 0.05 })] })), []); +}); + +test("a dormer on a section opens the slope and adds its own roof", () => { + const main = section({ id: "main" }); + const dormer = section({ id: "dormer", x0: 4, x1: 6, z0: 0, z1: 2.5, axis: "z", eave_a: 4, eave_b: 4, pitch_a: 35, pitch_b: 35, base: 3.5, dormer: true, overhang: 0.15 }); + const alone = buildRoof(house({ type: "custom", pitch: 35, overhang: 0.4, sections: [main] }))[0].solid.count; + const both = buildRoof(house({ type: "custom", pitch: 35, overhang: 0.4, sections: [main, dormer] }))[0].solid.count; + assert.ok(both > alone); +}); + +test("solar modules appear on the roof and a roof window draws its frame, glass and blind", () => { + const b = house({ type: "gable", pitch: 35, overhang: 0.4 }); + const face = roofFaces(b)[1]; + const field = proposeField(face, "f"); + b.settings.roof.solar = [field]; + const without = buildRoof(house({ type: "gable", pitch: 35, overhang: 0.4 }))[0].solid.count; + assert.ok(buildRoof(b)[0].solid.count > without); + b.settings.roof.windows = [{ id: "w", face: face.key, u: 2, v: 1, w: null, h: null, cover: null, contact: null, tilt: null }]; + const closed = buildRoof(b, new Map([["w", { open: 0, tilt: 0, cover: 0 }]]))[0].solid.count; + const shaded = buildRoof(b, new Map([["w", { open: 1, tilt: 0, cover: 1 }]]))[0].solid.count; + assert.ok(closed > buildRoof(house({ type: "gable", pitch: 35, overhang: 0.4 }))[0].solid.count); + assert.equal(shaded, closed + 2, "the blind adds one quad"); +}); + +test("the black and the blue module look differ, and modules use the part's level", () => { + const b = house({ type: "gable", pitch: 35, overhang: 0.4 }); + const face = roofFaces(b)[1]; + const field = { ...proposeField(face, "f") }; + const black = new GeoBuffer(); + const blue = new GeoBuffer(); + pushModules(black, new LineBuffer(), face, field, 0); + pushModules(blue, new LineBuffer(), face, { ...field, look: "blue" }, 0); + assert.notDeepEqual(black.c.slice(0, 3), blue.c.slice(0, 3)); + const lowered = new GeoBuffer(); + pushModules(lowered, new LineBuffer(), face, field, 2); + assert.ok(Math.abs(black.p[1] - lowered.p[1] - 2) < 1e-9); +}); + +test("a section's attic leaves the walls under the roof to the floor", () => { + const solid = new GeoBuffer(); + const solidAttic = new GeoBuffer(); + pushSection(solid, new LineBuffer(), section({ base: 1.0, eave_a: 3, eave_b: 3 }), 0.4, 0); + pushSection(solidAttic, new LineBuffer(), section({ base: 1.0, eave_a: 3, eave_b: 3 }), 0.4, 0, undefined, true); + assert.ok(solid.count > solidAttic.count, "gable ends are drawn without an attic"); +}); + +test("a chimney stands on the roof near the ridge and rises above it, in every shape", () => { + const plain = house({ type: "gable", pitch: 35, overhang: 0.4 }); + const before = buildRoof(plain)[0]; + const b = house({ type: "gable", pitch: 35, overhang: 0.4 }); + const face = roofFaces(b)[0]; + const chimney = proposeChimney(face, "c"); + const place = chimneyPlace(face, chimney); + assert.ok(place.high > place.low, "the roof slopes under it"); + assert.ok(place.high > 2.6 + 1.5, "near the ridge, well above the eave"); + for (const shape of ["brick", "round", "wide", "steel"] as const) { + b.settings.roof.chimneys = [{ ...chimney, shape }]; + const part = buildRoof(b)[0]; + assert.ok(part.solid.count > before.solid.count, shape); + assert.ok(topOf(part.solid) > topOf(before.solid), `${shape} rises above the ridge`); + } +}); diff --git a/frontend/src/viewer/roof/roof.ts b/frontend/src/viewer/roof/roof.ts new file mode 100644 index 0000000..fceb566 --- /dev/null +++ b/frontend/src/viewer/roof/roof.ts @@ -0,0 +1,19 @@ +// The roof as the viewer draws it: either one roof over the top floor, or roof sections at their own heights. Drawn in the +// house view only; the viewer lifts it and fades it out when the camera zooms in. + +import type { Building } from "../../model.ts"; +import { pushChimneys, pushRoofWindows, pushSolar, type RoofWindowState } from "./fittings.ts"; +import { buildSections } from "./sections.ts"; +import { buildSingleRoof } from "./single.ts"; +import type { RoofGeometry } from "./types.ts"; + +/** The roof in parts per floor; each part moves with its floor when the floors are pulled apart. */ +export function buildRoof(b: Building, windows: ReadonlyMap = new Map()): RoofGeometry[] { + const roof = b.settings.roof; + const single = roof?.type === "custom" ? null : buildSingleRoof(b); + const parts = roof?.type === "custom" ? buildSections(b, roof.sections ?? [], roof.overhang) : single ? [single] : []; + pushSolar(b, parts); + pushRoofWindows(b, parts, windows); + pushChimneys(b, parts); + return parts; +} diff --git a/frontend/src/viewer/roof/sections.ts b/frontend/src/viewer/roof/sections.ts new file mode 100644 index 0000000..e0da769 --- /dev/null +++ b/frontend/src/viewer/roof/sections.ts @@ -0,0 +1,218 @@ +// Roofs made of sections: wings of an L- or T-shaped house, a barn with a catslide, a lean-to, canopies. Each section is +// drawn at its own height, and the sections are grouped by the floor they sit on. + +import { Color } from "three"; +import { polygonArea, type Building, type RoofSection, type Vec2 } from "../../model.ts"; +import { + cutHole, dormerHoles, dormerParent, effectiveDormer, wingOf, offsetPolygon, sectionFloor, sectionFrame, sectionGeometry, sectionHeightAt, sectionOverhang, sectionPolygon, sectionProfile, sectionUV, + type Q, type SectionOverhang, +} from "../../roof-sections.ts"; +import { roofFaces, windowCorners } from "../../solar.ts"; +import { GeoBuffer, LineBuffer, pushPrism } from "../geo.ts"; +import { pushCanopyFrame } from "./canopy.ts"; +import { EAVE, GABLE, GLASS, RIDGE, ROOF, ROOF_TOP, THICK } from "./palette.ts"; +import type { RoofGeometry } from "./types.ts"; + +type P3 = number[]; +type Hole = { u0: number; u1: number; v0: number; v1: number }; + +/** The part of a roof profile (points across, with heights) above a level, as a closed polygon. */ +function profileAbove(profile: [number, number][], level: number): [number, number][] { + const out: [number, number][] = []; + profile.forEach(([v, y], i) => { + if (y >= level) out.push([v, y]); + const next = profile[i + 1]; + if (next && (y - level) * (next[1] - level) < 0) { + const t = (level - y) / (next[1] - y); + out.push([v + (next[0] - v) * t, level]); + } + }); + if (out.length < 2) return []; + // close along the level + const [first, last] = [out[0], out[out.length - 1]]; + if (last[1] > level) out.push([last[0], level]); + if (first[1] > level) out.unshift([first[0], level]); + return out; +} + +const counterClockwise = (ring: Vec2[]): Vec2[] => (polygonArea(ring) >= 0 ? ring : [...ring].reverse()); + +/** + * One section: its slopes with their thickness and rim, the ridge (and hips), and the walls from the section's base up + * under the roof (gable ends and knee walls). `yOff` is the level of its floor. + */ +export function pushSection( + solid: GeoBuffer, + lines: LineBuffer, + s: RoofSection, + overhang: SectionOverhang | number, + yOff: number, + glass: GeoBuffer = solid, + attic = false, + holes: Hole[] = [], + /** A dormer: its gable only at this end (0 = u0, 1 = u1); null for an ordinary section. */ + frontEnd: 0 | 1 | null = null, +): void { + const frame = sectionFrame(s); + const profile = sectionProfile(s); + const ov = typeof overhang === "number" ? { u0: overhang, u1: overhang, a: overhang, b: overhang } : overhang; + const [ovA, ovB] = [Math.max(0, ov.a), Math.max(0, ov.b)]; + const w = frame.w; + const U0 = frame.u0 - Math.max(0, ov.u0); + const U1 = frame.u1 + Math.max(0, ov.u1); + const at = (u: number, v: number, y: number): P3 => { + const [x, z] = frame.at(u, v); + return [x, y - yOff, z]; + }; + const topColor = new Color(ROOF_TOP); + const underColor = new Color(ROOF); + const gableColor = new Color(GABLE); + const fan = (points: P3[], color: Color) => { + for (let i = 1; i + 1 < points.length; i++) solid.tri(points[0], points[i], points[i + 1], color); + }; + const place = ([u, v, y]: Q, lower = 0) => at(u, v, y - lower); + + // the roof planes as polygons in (u, v, height), the rim and the ridge lines; a flat roof is a slab + let faces: Q[][] = []; + let rim: Q[] = []; + let ridges: [Q, Q][] = []; + let gableProfile: [number, number][] | null = null; + let endProfiles: [[number, number][] | null, [number, number][] | null] | null = null; + if (s.shape === "flat" || s.shape === "parapet") { + const y = s.eave_a - yOff; + const parapet = s.shape === "parapet"; + // a free shape takes its polygon (grown by the overhang), a plain section its rectangle; a parapet roof has no overhang + const outline = + s.points && s.points.length >= 3 + ? sectionPolygon(s, parapet ? 0 : Math.max(0, Math.min(ov.a, ov.b, ov.u0, ov.u1))) + : parapet + ? [frame.at(frame.u0, 0), frame.at(frame.u1, 0), frame.at(frame.u1, w), frame.at(frame.u0, w)] + : [frame.at(U0, -ovA), frame.at(U1, -ovA), frame.at(U1, w + ovB), frame.at(U0, w + ovB)]; + pushPrism(solid, outline, y, y + 0.25, ROOF, ROOF_TOP, { bottom: true }); + outline.forEach((a, i) => { + const c = outline[(i + 1) % outline.length]; + lines.seg([a[0], y + 0.252, a[1]], [c[0], y + 0.252, c[1]], RIDGE); + lines.seg([a[0], y, a[1]], [c[0], y, c[1]], EAVE); + }); + if (parapet) { + // a 0.4 m high, 0.2 m thick wall ring along the edge, on the slab + const outer = counterClockwise(outline); + const inner = offsetPolygon(outer, -0.2); + outer.forEach((a, i) => { + const next = (i + 1) % outer.length; + pushPrism(solid, counterClockwise([a, outer[next], inner[next], inner[i]]), y + 0.25, y + 0.65, ROOF, ROOF_TOP); + lines.seg([a[0], y + 0.652, a[1]], [outer[next][0], y + 0.652, outer[next][1]], RIDGE); + lines.seg([inner[i][0], y + 0.652, inner[i][1]], [inner[next][0], y + 0.652, inner[next][1]], RIDGE); + }); + } + } else { + const geometry = sectionGeometry(s, ov); + // dormers: the slope opens under them (a plane with a hole becomes pieces around it) + faces = holes.reduce((planes, hole) => planes.flatMap((plane) => cutHole(plane, hole)), geometry.faces); + rim = geometry.rim; + ridges = geometry.ridges; + gableProfile = geometry.gable; + endProfiles = geometry.endProfiles ?? null; + } + + // a canopy has thin see-through panels; a closed roof its tiles with their thickness below + const open = !!s.open; + const pane = new Color(GLASS); + for (const face of faces) { + if (open) { + for (let i = 1; i + 1 < face.length; i++) glass.tri(place(face[0]), place(face[i]), place(face[i + 1]), pane); + } else { + fan(face.map((q) => place(q)), topColor); + fan(face.map((q) => place(q, THICK)), underColor); + } + } + // the rim: eaves and rakes with the roof's thickness + rim.forEach((a, i) => { + const b = rim[(i + 1) % rim.length]; + if (!open) fan([place(a), place(b), place(b, THICK), place(a, THICK)], underColor); + lines.seg(place(a), place(b), open ? RIDGE : EAVE); + }); + if (open) { + pushCanopyFrame(solid, lines, frame, profile, ov, (u, v, y) => at(u, v, y), yOff); + return; + } + for (const [a, b] of ridges) lines.seg(place([a[0], a[1], a[2] + 0.004]), place([b[0], b[1], b[2] + 0.004]), RIDGE); + + // walls up under the roof from the section's base: the gable ends (not under a hip) ... + const base = s.base; + if (attic) return; + if (gableProfile) { + const ends = frontEnd === null ? [frame.u0, frame.u1] : [frontEnd === 0 ? frame.u0 : frame.u1]; + for (const u of ends) { + // with an own shape per end, each end has its own wall under it (none under a hip) + const own = endProfiles ? endProfiles[u === frame.u0 ? 0 : 1] : gableProfile; + const polygon = own ? profileAbove(own, base - THICK) : []; + if (polygon.length >= 3) fan(polygon.map(([v, y]) => at(u, v, y)), gableColor); + } + } + // ... and the knee walls along the eaves where the roof starts above the walls (the high back wall of a pent roof) + if (s.shape !== "flat" && s.shape !== "parapet") { + for (const v of [0, w]) { + const y = profile.y(v) - THICK; + if (y > base + 0.02) fan([at(frame.u0, v, base), at(frame.u1, v, base), at(frame.u1, v, y), at(frame.u0, v, y)], gableColor); + } + } else if (s.eave_a > base + 0.02) { + const corners: [number, number][] = [[frame.u0, 0], [frame.u1, 0], [frame.u1, w], [frame.u0, w]]; + corners.forEach(([ua, va], i) => { + const [ub, vb] = corners[(i + 1) % 4]; + fan([at(ua, va, base), at(ub, vb, base), at(ub, vb, s.eave_a), at(ua, va, s.eave_a)], gableColor); + }); + } +} + +/** Roof sections, grouped by the floor whose wall tops are nearest below each section's base. */ +export function buildSections(b: Building, sections: readonly RoofSection[], overhang: number): RoofGeometry[] { + const floors = b.floors.filter((f) => f.rooms.length > 0).sort((p, q) => p.elevation - q.elevation); + if (floors.length === 0) return []; + const parts = new Map(); + const faceByKey = new Map(roofFaces(b).map((f) => [f.key, f])); + for (const section of sections) { + if (Math.abs(section.x1 - section.x0) < 0.1 || Math.abs(section.z1 - section.z0) < 0.1) continue; + // the floor the section sits on: the highest one that starts below the top of its walls + const floor = sectionFloor(b, section) ?? floors[0]; + // canopies get a part of their own: it rides with the floor but never lifts off like a roof + const key = section.open ? `${floor.id}:open` : floor.id; + let part = parts.get(key); + if (!part) parts.set(key, (part = { floor, base: 0, solid: new GeoBuffer(), lines: new LineBuffer(), glass: new GeoBuffer(), sections: [], lift: !section.open })); + part.sections!.push(section.id); + + // a dormer or cross gable (a smaller section on a bigger one) keeps its cheeks and front gable. An attic: the floor's + // walls rise above the section's base, so they end under the slopes themselves and the roof draws none of its own. + // a wing butting against a bigger roof at a right angle reaches into it like a cross gable, so the valleys form there + const wing = wingOf(sections, section); + const parent = dormerParent(sections, section) ?? wing?.parent ?? null; + const attic = floor.elevation + floor.height > section.base + 0.05 && !section.dormer && !parent; + // the slope opens under every dormer and cross gable sitting on this section, and under its roof windows + const holes: Hole[] = sections + .filter((d) => d !== section) + .flatMap((d) => (dormerParent(sections, d) === section ? dormerHoles(section, d) : wingOf(sections, d)?.parent === section ? dormerHoles(section, wingOf(sections, d)!.extended) : [])); + for (const w of b.settings.roof.windows ?? []) { + const face = faceByKey.get(w.face); + const corners = face && face.section === section.id ? windowCorners(face, w) : null; + if (!corners) continue; + const uv = corners.map((p) => sectionUV(section, p[0], p[2])); + holes.push({ u0: Math.min(...uv.map((q) => q[0])), u1: Math.max(...uv.map((q) => q[0])), v0: Math.min(...uv.map((q) => q[1])), v1: Math.max(...uv.map((q) => q[1])) }); + } + // a dormer only goes as deep as its ridge needs to meet the slope; its gable is only at the front (the lower end of the slope) + const drawn = wing ? wing.extended : parent ? effectiveDormer(parent, section) : section; + let frontEnd: 0 | 1 | null = null; + if (parent) { + const frame = sectionFrame(drawn); + const parentPlanes = sectionGeometry(parent, { u0: 0, u1: 0, a: 0, b: 0 }); + const heightAt = (u: number) => { + const [x, z] = frame.at(u, frame.w / 2); + const [pu, pv] = sectionUV(parent, x, z); + return sectionHeightAt(parentPlanes, pu, pv) ?? sectionProfile(parent).y(pv); + }; + frontEnd = heightAt(frame.u0) <= heightAt(frame.u1) ? 0 : 1; + } + pushSection(part.solid, part.lines, drawn, sectionOverhang(b, drawn, drawn.overhang ?? overhang), floor.elevation, part.glass, attic, holes, frontEnd); + } + // the closed roofs first: the first part is the one the main roof's solar fields belong to + return [...parts.values()].sort((p, q) => Number(p.lift === false) - Number(q.lift === false)); +} diff --git a/frontend/src/viewer/roof/single.ts b/frontend/src/viewer/roof/single.ts new file mode 100644 index 0000000..f80527f --- /dev/null +++ b/frontend/src/viewer/roof/single.ts @@ -0,0 +1,76 @@ +// The single roof over the top floor: flat or gable, over the bounding box of its rooms plus the outer walls and the overhang. + +import { Color } from "three"; +import type { Building, Floor } from "../../model.ts"; +import { DEG, GeoBuffer, LineBuffer, pushPrism } from "../geo.ts"; +import { EAVE, GABLE, RIDGE, ROOF, ROOF_TOP, THICK } from "./palette.ts"; +import type { RoofGeometry } from "./types.ts"; + +/** The floor the single roof sits on: the highest one with rooms. */ +export function roofFloor(b: Building): Floor | null { + return b.floors.filter((f) => f.rooms.some((r) => r.points.length >= 3)).sort((p, q) => q.elevation - p.elevation)[0] ?? null; +} + +type P3 = number[]; + +/** One roof over the top floor, in floor coordinates with y = 0 at the top of the floor's walls. */ +export function buildSingleRoof(b: Building): RoofGeometry | null { + const roof = b.settings.roof; + const floor = roofFloor(b); + if (!floor || !roof || roof.type === "none" || roof.type === "custom") return null; + const xs = floor.rooms.flatMap((r) => r.points.map((p) => p[0])); + const zs = floor.rooms.flatMap((r) => r.points.map((p) => p[1])); + const margin = b.settings.wall_exterior + roof.overhang; + const [x0, x1] = [Math.min(...xs) - margin, Math.max(...xs) + margin]; + const [z0, z1] = [Math.min(...zs) - margin, Math.max(...zs) + margin]; + const solid = new GeoBuffer(); + const lines = new LineBuffer(); + const result: RoofGeometry = { floor, base: floor.height, solid, lines, glass: new GeoBuffer() }; + + if (roof.type === "flat") { + const corners: [number, number][] = [[x0, z0], [x1, z0], [x1, z1], [x0, z1]]; + pushPrism(solid, corners, 0, 0.25, ROOF, ROOF_TOP, { bottom: true }); + corners.forEach(([ax, az], i) => { + const [bx, bz] = corners[(i + 1) % 4]; + lines.seg([ax, 0.252, az], [bx, 0.252, bz], RIDGE); + lines.seg([ax, 0, az], [bx, 0, bz], EAVE); + }); + return result; + } + + // a gable: the ridge runs along the longer side, or along the shorter one (terraced houses) + const longerAlongX = x1 - x0 >= z1 - z0; + const alongX = roof.ridge === "short" ? !longerAlongX : longerAlongX; + const half = (alongX ? z1 - z0 : x1 - x0) / 2; + const slope = Math.tan(roof.pitch * DEG); + const rise = half * slope; + // coordinates: u along the ridge, v across (from -half to +half) + const at = (u: number, v: number, y: number): P3 => (alongX ? [u, y, (z0 + z1) / 2 + v] : [(x0 + x1) / 2 + v, y, u]); + const [u0, u1] = alongX ? [x0, x1] : [z0, z1]; + const topColor = new Color(ROOF_TOP); + const underColor = new Color(ROOF); + const quad = (a: P3, b2: P3, c: P3, d: P3, color: Color) => { + solid.tri(a, b2, c, color); + solid.tri(a, c, d, color); + }; + for (const side of [-1, 1]) { + // the upper and lower face of the slope, and the eave and rake faces of its thickness + quad(at(u0, side * half, 0), at(u1, side * half, 0), at(u1, 0, rise), at(u0, 0, rise), topColor); + quad(at(u0, side * half, -THICK), at(u0, 0, rise - THICK), at(u1, 0, rise - THICK), at(u1, side * half, -THICK), underColor); + quad(at(u0, side * half, -THICK), at(u1, side * half, -THICK), at(u1, side * half, 0), at(u0, side * half, 0), underColor); + for (const u of [u0, u1]) quad(at(u, side * half, -THICK), at(u, side * half, 0), at(u, 0, rise), at(u, 0, rise - THICK), underColor); + lines.seg(at(u0, side * half, 0), at(u1, side * half, 0), EAVE); + for (const u of [u0, u1]) lines.seg(at(u, side * half, 0), at(u, 0, rise), EAVE); + } + // gable walls above the outer walls, set back by the overhang + const inset = roof.overhang; + const gableColor = new Color(GABLE); + const gableHalf = half - inset; + const gableRise = gableHalf * slope; + for (const u of [u0 + inset, u1 - inset]) { + solid.tri(at(u, -gableHalf, -THICK), at(u, gableHalf, -THICK), at(u, 0, gableRise - THICK), gableColor); + solid.tri(at(u, gableHalf, -THICK), at(u, -gableHalf, -THICK), at(u, 0, gableRise - THICK), gableColor); + } + lines.seg(at(u0, 0, rise + 0.004), at(u1, 0, rise + 0.004), RIDGE); + return result; +} diff --git a/frontend/src/viewer/roof/types.ts b/frontend/src/viewer/roof/types.ts new file mode 100644 index 0000000..f57b711 --- /dev/null +++ b/frontend/src/viewer/roof/types.ts @@ -0,0 +1,16 @@ +import type { Floor } from "../../model.ts"; +import type { GeoBuffer, LineBuffer } from "../geo.ts"; + +/** Roof geometry that sits on a floor: y = 0 is `base` above the floor's own level. */ +export interface RoofGeometry { + floor: Floor; + base: number; + solid: GeoBuffer; + lines: LineBuffer; + /** See-through roof panels of canopies, drawn with their own, fainter material. */ + glass: GeoBuffer; + /** The roof sections in this part (sections roofs only). */ + sections?: string[]; + /** False for canopies: they stand on posts on their floor and do not lift off with the roof when the floors are pulled apart. */ + lift?: boolean; +} diff --git a/frontend/src/viewer/scene/floor-motion.test.ts b/frontend/src/viewer/scene/floor-motion.test.ts new file mode 100644 index 0000000..88ce452 --- /dev/null +++ b/frontend/src/viewer/scene/floor-motion.test.ts @@ -0,0 +1,43 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { MeshBasicMaterial, LineBasicMaterial, PointsMaterial } from "three"; +import { BELOW_OPACITY, EXPLODE_GAP, easeFloor, fadeMaterials, floorTarget } from "./floor-motion.ts"; +import type { FloorMaterials } from "./materials.ts"; + +test("in the house view floors are pulled apart or stacked", () => { + assert.deepEqual(floorTarget(2, undefined, true, "dim"), { y: 2 * EXPLODE_GAP, opacity: 1 }); + assert.deepEqual(floorTarget(2, undefined, false, "dim"), { y: 0, opacity: 1 }); +}); + +test("a chosen floor stays, the floors above fly away, those below depend on the stack mode", () => { + assert.deepEqual(floorTarget(1, 1, true, "dim"), { y: 0, opacity: 1 }); + assert.deepEqual(floorTarget(2, 1, true, "dim"), { y: 7, opacity: 0 }); + assert.deepEqual(floorTarget(0, 1, true, "dim"), { y: -0.4, opacity: BELOW_OPACITY }); + assert.deepEqual(floorTarget(0, 1, true, "single"), { y: -0.4, opacity: 0 }); + assert.deepEqual(floorTarget(0, 1, true, "stacked"), { y: 0, opacity: 1 }); +}); + +test("a floor eases towards its target and settles exactly", () => { + const pose = { y: 0, o: 1, ty: 2, to: 0 }; + const first = easeFloor(pose, 0.5); + assert.deepEqual(first, { moving: true, settled: false }); + assert.deepEqual([pose.y, pose.o], [1, 0.5]); + let last = first; + for (let i = 0; i < 30 && last.moving; i++) last = easeFloor(pose, 0.5); + assert.deepEqual(last, { moving: false, settled: true }); + assert.deepEqual([pose.y, pose.o], [2, 0]); + assert.deepEqual(easeFloor(pose, 0.5), { moving: false, settled: false }, "nothing more to do"); +}); + +test("fading switches see-through materials off again at full opacity", () => { + const mesh = () => new MeshBasicMaterial(); + const m = { floor: mesh(), wall: mesh(), frames: mesh(), blinds: mesh(), lamps: mesh(), pattern: mesh(), glow: mesh(), glass: mesh(), glassWall: mesh(), cones: mesh(), screens: mesh(), lines: new LineBasicMaterial(), halos: new PointsMaterial(), shadow: mesh(), ghosts: [] } as unknown as FloorMaterials; + fadeMaterials(m, 0.5); + assert.equal(m.floor.transparent, true); + assert.equal(m.floor.depthWrite, false); + assert.equal(m.halos.opacity, 0.5); + fadeMaterials(m, 1); + assert.equal(m.floor.transparent, false); + assert.equal(m.floor.depthWrite, true); + assert.equal(m.lines.opacity, 1); +}); diff --git a/frontend/src/viewer/scene/floor-motion.ts b/frontend/src/viewer/scene/floor-motion.ts new file mode 100644 index 0000000..2294677 --- /dev/null +++ b/frontend/src/viewer/scene/floor-motion.ts @@ -0,0 +1,72 @@ +// Where each floor goes in the 3D view and how it gets there: the house view pulls floors apart (or stacks them), a chosen floor +// lets those above fly away and keeps those below as a dim reference. + +import type { FloorMaterials } from "./materials.ts"; +import type { FloorStack } from "./types.ts"; + +/** Gap between floors in the exploded house view (metres). */ +export const EXPLODE_GAP = 2.4; +/** How visible the floors below a chosen floor stay when they are a dim reference. */ +export const BELOW_OPACITY = 0.22; +/** Time constant of the floor movement (ms): about 0.7 s until settled. */ +export const FLOOR_TAU = 140; +/** Floors below a chosen floor sink a little. */ +const SINK = -0.4; +/** How far above the house floors fly when another floor is chosen. */ +const FLY_AWAY = 5; +const ARRIVED = 0.004; + +export interface FloorTarget { + /** Height offset on top of the floor's elevation. */ + y: number; + opacity: number; +} + +/** + * Where a floor of this rank (0 is the lowest) belongs. `chosen` is the rank of the selected floor, or undefined for the house view. + */ +export function floorTarget(rank: number, chosen: number | undefined, explode: boolean, below: FloorStack): FloorTarget { + if (chosen === undefined) return { y: explode ? rank * EXPLODE_GAP : 0, opacity: 1 }; + if (rank > chosen) return { y: FLY_AWAY + rank, opacity: 0 }; + if (rank === chosen) return { y: 0, opacity: 1 }; + if (below === "stacked") return { y: 0, opacity: 1 }; + return { y: SINK, opacity: below === "single" ? 0 : BELOW_OPACITY }; +} + +export interface FloorPose { + y: number; + o: number; + ty: number; + to: number; +} + +/** One frame of a floor towards its target. Returns whether it is still moving, and whether it just settled. */ +export function easeFloor(pose: FloorPose, share: number): { moving: boolean; settled: boolean } { + const [dy, dO] = [pose.ty - pose.y, pose.to - pose.o]; + if (Math.abs(dy) < ARRIVED && Math.abs(dO) < ARRIVED) { + const settled = dy !== 0 || dO !== 0; + if (settled) [pose.y, pose.o] = [pose.ty, pose.to]; + return { moving: false, settled }; + } + pose.y += dy * share; + pose.o += dO * share; + return { moving: true, settled: false }; +} + +/** Fades every material of a floor to an opacity. Solid materials write depth, see-through ones do not. */ +export function fadeMaterials(materials: FloorMaterials, opacity: number): void { + const solid = opacity > 0.999; + for (const material of [materials.floor, materials.wall, materials.frames, materials.blinds, materials.lamps]) { + if (material.transparent === solid) { + material.transparent = !solid; + material.depthWrite = solid; + material.needsUpdate = true; + } + material.opacity = opacity; + } + for (const ghost of materials.ghosts) ghost.material.opacity = ghost.base * opacity; + for (const material of [materials.pattern, materials.glow, materials.lines, materials.glass, materials.glassWall, materials.halos, materials.cones, materials.screens]) material.opacity = opacity; +} + +/** The share of the remaining way a floor covers in a frame of `dt` milliseconds. */ +export const floorShare = (dt: number): number => 1 - Math.exp(-dt / FLOOR_TAU); diff --git a/frontend/src/viewer/scene/halos.test.ts b/frontend/src/viewer/scene/halos.test.ts new file mode 100644 index 0000000..213551f --- /dev/null +++ b/frontend/src/viewer/scene/halos.test.ts @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { GeoBuffer } from "../geo.ts"; +import { addFloorWedge, addLampHalo, addSpotCone, haloHeight, viewReach } from "./halos.ts"; +import type { DeviceMarker } from "./types.ts"; + +const marker = (extra: Partial): DeviceMarker => ({ id: "x", floorId: "g", roomId: null, x: 0, z: 0, y: 1, icon: "", name: "", text: "", active: true, unavailable: false, glow: null, ...extra }) as DeviceMarker; + +test("halo heights follow the lamp model", () => { + assert.equal(haloHeight("ceiling", 2.5, 0, 0.08), 2.43); + assert.equal(haloHeight("wall", 2.5, 1.5, 0.2), 1.6); + assert.ok(Math.abs(haloHeight("pendant", 2.5, 0, 3) - 0.48) < 1e-9); +}); + +test("a strip gets four glow points, a wall lamp one in front of its wall, any other one", () => { + const glow = { color: [1, 1, 1] as [number, number, number], level: 1 }; + const points = { positions: [] as number[], colours: [] as number[] }; + addLampHalo(points, marker({ lamp: "strip", size: [2, 0.04, 0.03], rotation: 0, base: 2.4 }) as never, glow, 2.5); + assert.equal(points.positions.length / 3, 4); + assert.ok(points.colours.every((c) => Math.abs(c - 0.42) < 1e-9)); + const wall = { positions: [] as number[], colours: [] as number[] }; + addLampHalo(wall, marker({ lamp: "wall", size: [0.2, 0.12, 0.2], rotation: 0, z: 1 }) as never, glow, 2.5); + assert.equal(wall.positions.length, 3); + assert.ok(Math.abs(wall.positions[2] - 1.11) < 1e-9); +}); + +test("a spot's cone is a ring of triangles", () => { + const buffer = new GeoBuffer(); + addSpotCone(buffer, marker({ lamp: "spot", size: [0.1, 0.1, 0.14] }) as never, { color: [1, 1, 1], level: 1 }, 2.5); + assert.equal(buffer.count, 16 * 2); +}); + +test("a plugin wedge adds triangles and stops at a wall in the way, not at the wall it hangs on", () => { + const wedge = { angle: 90, reach: 4, near: 0, color: [0, 1, 1] as [number, number, number], opacity: 0.5, through: false }; + const open = new GeoBuffer(); + const range = addFloorWedge(open, marker({ wedge, rotation: 0 }), []); + assert.ok(range.end > range.start); + // looking along +z: a wall 1 m ahead cuts the view, a wall 0.2 m ahead is the one it hangs on + assert.equal(viewReach([{ a: [-9, 1], b: [9, 1] }], [0, 0], [0, 1], 0, 4), 1); + assert.equal(viewReach([{ a: [-9, 0.2], b: [9, 0.2] }], [0, 0], [0, 1], 0, 4), 4); + const near = new GeoBuffer(); + const r2 = addFloorWedge(near, marker({ wedge: { ...wedge, near: 1 }, rotation: 0 }), []); + assert.equal(r2.end - r2.start, 2 * (range.end - range.start)); + assert.deepEqual(addFloorWedge(new GeoBuffer(), marker({}), []), { start: 0, end: 0 }); +}); diff --git a/frontend/src/viewer/scene/halos.ts b/frontend/src/viewer/scene/halos.ts new file mode 100644 index 0000000..54e1797 --- /dev/null +++ b/frontend/src/viewer/scene/halos.ts @@ -0,0 +1,141 @@ +// Soft glow points at lit lamps, light cones under spots (quality "High"), and the wedges plugins draw on the floor. + +import { Color } from "three"; +import { DEG, GeoBuffer } from "../geo.ts"; +import { HANGING_LAMPS, LAMP_SIZE } from "./lamp-data.ts"; +import type { DeviceMarker, LampModel } from "./types.ts"; +import { stripPoint, stripRiseLift } from "./strip.ts"; + +type Wall2d = { a: readonly [number, number]; b: readonly [number, number] }; + +/** Height above the floor at which a wedge is drawn. */ +const WEDGE_Y = 0.015; +/** A wall closer than this to the device is the one it hangs on, and does not block the view. */ +const OWN_WALL = 0.45; + +/** + * How far a device at `origin` sees along the direction turned `turn` radians from `heading`: up to `reach`, or to the + * first wall in the way. + */ +export function viewReach(walls: readonly Wall2d[], origin: readonly [number, number], heading: readonly [number, number], turn: number, reach: number): number { + const [c, s] = [Math.cos(turn), Math.sin(turn)]; + const ray: [number, number] = [heading[0] * c - heading[1] * s, heading[1] * c + heading[0] * s]; + let nearest = reach; + for (const wall of walls) { + const edge: [number, number] = [wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]]; + const denominator = ray[0] * edge[1] - ray[1] * edge[0]; + if (Math.abs(denominator) < 1e-9) continue; + const toStart: [number, number] = [wall.a[0] - origin[0], wall.a[1] - origin[1]]; + const along = (toStart[0] * edge[1] - toStart[1] * edge[0]) / denominator; + const across = (toStart[0] * ray[1] - toStart[1] * ray[0]) / denominator; + // a device just inside an outer wall looks out through it, so the wall it hangs on does not count + if (along > OWN_WALL && along < nearest && across >= 0 && across <= 1) nearest = along; + } + return nearest; +} + +/** A plugin's wedge on the floor: from `near` to the reach (or the first wall), fading out. Returns the triangles it added. */ +export function addFloorWedge(buffer: GeoBuffer, device: DeviceMarker, walls: readonly Wall2d[]): { start: number; end: number } { + const start = buffer.count; + const wedge = device.wedge; + if (!wedge) return { start, end: start }; + const turn = (device.rotation ?? 0) * DEG; + const heading: [number, number] = [-Math.sin(turn), Math.cos(turn)]; + const half = (wedge.angle * DEG) / 2; + const inner = new Color(...(wedge.color.map((c) => c * wedge.opacity) as [number, number, number])); + const outer = new Color(0, 0, 0); + const steps = Math.max(4, Math.round(half / 0.15)); + const origin: [number, number] = [device.x, device.z]; + const at = (t: number, r: number): [number, number, number] => [device.x + (heading[0] * Math.cos(t) - heading[1] * Math.sin(t)) * r, WEDGE_Y, device.z + (heading[1] * Math.cos(t) + heading[0] * Math.sin(t)) * r]; + for (let i = 0; i < steps; i++) { + const [t0, t1] = [-half + (2 * half * i) / steps, -half + (2 * half * (i + 1)) / steps]; + // a radio's reach (Wi-Fi) goes through walls; a camera's view stops at them + const [r0, r1] = wedge.walls === false ? [wedge.reach, wedge.reach] : [viewReach(walls, origin, heading, t0, wedge.reach), viewReach(walls, origin, heading, t1, wedge.reach)]; + const [n0, n1] = [Math.min(wedge.near, r0), Math.min(wedge.near, r1)]; + if (wedge.near <= 0) buffer.tri([device.x, WEDGE_Y, device.z], at(t1, r1), at(t0, r0), inner, outer, outer); + else { + buffer.tri(at(t0, n0), at(t1, r1), at(t0, r0), inner, outer, outer); + buffer.tri(at(t0, n0), at(t1, n1), at(t1, r1), inner, inner, outer); + } + } + return { start, end: buffer.count }; +} + +/** The height of the glow point of a lamp model, for a room of height `ceiling`. */ +export function haloHeight(model: LampModel, ceiling: number, base: number, height: number): number { + switch (model) { + case "ceiling": + return ceiling - 0.07; + case "downlight": + return ceiling - 0.03; + case "spot": + return ceiling - height; + case "panel": + return ceiling - 0.03; + case "pendant": + return Math.max(0.4, ceiling - height) + 0.08; + case "fan": + return Math.max(0.5, ceiling - height + 0.03); + case "floor": + return base + height - 0.15; + case "uplight": + return base + height; + case "table": + return base + height - 0.09; + case "wall": + return base + height / 2; + case "strip": + return base + Math.max(0.02, height) - 0.01; + case "bollard": + return base + height - 0.08; + case "garden": + return base + height - 0.03; + } +} + +export interface HaloPoints { + positions: number[]; + colours: number[]; +} + +/** How bright a halo is compared to the lamp's level. */ +const HALO_LEVEL = 0.7; + +/** Adds the glow points of a lit lamp: a strip gets four along its length, a wall lamp one in front of the wall, others one. */ +export function addLampHalo(points: HaloPoints, lamp: DeviceMarker & { lamp: LampModel }, glow: NonNullable, ceiling: number): void { + const [width, depth, height] = lamp.size ?? LAMP_SIZE[lamp.lamp]; + const base = lamp.base ?? 0; + const turn = (lamp.rotation ?? 0) * DEG; + const y = haloHeight(lamp.lamp, ceiling, base, height); + const add = (x: number, yy: number, z: number, share: number) => { + points.positions.push(x, yy, z); + for (const c of glow.color) points.colours.push(c * glow.level * HALO_LEVEL * share); + }; + if (lamp.lamp === "strip") { + for (const along of [-0.4, -0.13, 0.13, 0.4]) { + // an upright strip glows up its length + if (lamp.upright) add(lamp.x, base + width * (0.5 + along), lamp.z, 0.6); + else add(...stripPoint(lamp.x, y + stripRiseLift(lamp.base, width, lamp.rise), lamp.z, turn, width, lamp.rise, along), 0.6); + } + } else if (lamp.lamp === "wall") add(lamp.x - Math.sin(turn) * (depth / 2 + 0.05), y, lamp.z + Math.cos(turn) * (depth / 2 + 0.05), 1); + else add(lamp.x, y, lamp.z, 1); +} + +/** A soft cone from a downlight or spot to the floor, fading out towards the floor. */ +export function addSpotCone(buffer: GeoBuffer, lamp: DeviceMarker & { lamp: LampModel }, glow: NonNullable, ceiling: number): void { + const [width, , height] = lamp.size ?? LAMP_SIZE[lamp.lamp]; + const y = haloHeight(lamp.lamp, ceiling, lamp.base ?? 0, height); + const top = new Color(...(glow.color.map((c) => c * 0.09 * glow.level) as [number, number, number])); + const bottom = new Color(0, 0, 0); + const [r0, r1] = [Math.max(0.03, width / 2), 0.45 + 0.35 * glow.level]; + const sides = 16; + const ring = (angle: number, radius: number, yy: number): [number, number, number] => [lamp.x + Math.cos(angle) * radius, yy, lamp.z + Math.sin(angle) * radius]; + for (let i = 0; i < sides; i++) { + const [a0, a1] = [(i / sides) * Math.PI * 2, ((i + 1) / sides) * Math.PI * 2]; + buffer.tri(ring(a0, r0, y), ring(a0, r1, 0.02), ring(a1, r1, 0.02), top, bottom, bottom); + buffer.tri(ring(a0, r0, y), ring(a1, r1, 0.02), ring(a1, r0, y), top, bottom, top); + } +} + +/** Whether a lamp is hidden by the cut view (hanging lamps are, while the walls are cut). */ +export const hiddenInCut = (model: LampModel): boolean => HANGING_LAMPS.has(model); diff --git a/frontend/src/viewer/scene/house-shadow.test.ts b/frontend/src/viewer/scene/house-shadow.test.ts new file mode 100644 index 0000000..38e592e --- /dev/null +++ b/frontend/src/viewer/scene/house-shadow.test.ts @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { shadowOutline } from "./house-shadow.ts"; + +const square: [number, number][] = [[0, 0], [10, 0], [10, 10], [0, 10]]; + +test("the shadow falls away from the sun and grows as the sun sinks", () => { + // sun in the south (azimuth 180) with north up: south is +z, so the shadow falls towards -z + const high = shadowOutline([square], 6, { elevation: 45, azimuth: 180 }, 0); + assert.equal(high.length, 1); + const zs = high[0].map((p) => p[1]); + assert.ok(Math.abs(Math.min(...zs) + 6) < 1e-6, `reaches ${Math.min(...zs)}`); + const low = shadowOutline([square], 6, { elevation: 10, azimuth: 180 }, 0); + assert.ok(Math.min(...low[0].map((p) => p[1])) < -20); +}); + +test("no shadow at night or for a sun on the horizon", () => { + assert.deepEqual(shadowOutline([square], 6, { elevation: -5, azimuth: 180 }, 0), []); + assert.deepEqual(shadowOutline([square], 6, null, 0), []); +}); + +test("sweeping only the shadow-side edges gives the same shadow as sweeping every edge (an L-shaped house)", async () => { + const { mergeHoles } = await import("../../geometry/holes.ts"); + const { directionToSun } = await import("./sunlight.ts"); + const area = (r: [number, number][]) => Math.abs(r.reduce((s, p, i) => s + p[0] * r[(i + 1) % r.length][1] - r[(i + 1) % r.length][0] * p[1], 0) / 2); + const l: [number, number][] = [[0, 0], [10, 0], [10, 4], [4, 4], [4, 10], [0, 10]]; + for (const azimuth of [30, 135, 200, 290]) { + for (const ring of [l, [...l].reverse()]) { + const sun = { elevation: 35, azimuth }; + const length = 6 / Math.tan((35 * Math.PI) / 180); + const [sx, sz] = directionToSun(azimuth, 0); + const move = (p: [number, number]): [number, number] => [p[0] - sx * length, p[1] - sz * length]; + const every = mergeHoles([ring, ring.map(move), ...ring.map((a, i) => [a, ring[(i + 1) % ring.length], move(ring[(i + 1) % ring.length]), move(a)])]); + const quick = shadowOutline([ring], 6, sun, 0); + const total = (rings: [number, number][][]) => rings.reduce((s, r) => s + area(r), 0); + assert.ok(Math.abs(total(quick as [number, number][][]) - total(every as [number, number][][])) < 1e-6, `azimuth ${azimuth}`); + } + } +}); diff --git a/frontend/src/viewer/scene/house-shadow.ts b/frontend/src/viewer/scene/house-shadow.ts new file mode 100644 index 0000000..0912882 --- /dev/null +++ b/frontend/src/viewer/scene/house-shadow.ts @@ -0,0 +1,70 @@ +// The shadow the house throws on the ground: its footprint swept away from the sun by its height, laid flat on the plot. +// It is one soft, see-through shape, rebuilt only when the sun moves, so old tablets pay nothing per frame. + +import { BufferGeometry, DoubleSide, Float32BufferAttribute, Mesh, MeshBasicMaterial } from "three"; +import { mergeHoles } from "../../geometry/holes.ts"; +import { pointInPolygon, type Vec2 } from "../../model.ts"; +import { triangulate } from "../geo.ts"; +import { daylight, directionToSun } from "./sunlight.ts"; +import type { SunState } from "./types.ts"; + +/** The longest a shadow gets (metres), so a setting sun does not throw one across the map. */ +const MAX_LENGTH = 30; + +const area = (ring: readonly Vec2[]) => ring.reduce((sum, p, i) => sum + p[0] * ring[(i + 1) % ring.length][1] - ring[(i + 1) % ring.length][0] * p[1], 0) / 2; + +/** The outline of the shadow on the ground: the footprint, its copy moved away from the sun, and the band between them. */ +export function shadowOutline(footprint: readonly Vec2[][], height: number, sun: SunState | null, northDegrees: number): Vec2[][] { + if (!sun || sun.elevation <= 2 || height <= 0 || !footprint.length) return []; + const length = Math.min(MAX_LENGTH, height / Math.tan((sun.elevation * Math.PI) / 180)); + const [sx, sz] = directionToSun(sun.azimuth, northDegrees); + const move = (p: Vec2): Vec2 => [p[0] - sx * length, p[1] - sz * length]; + const rings: Vec2[][] = []; + for (const ring of footprint) { + rings.push([...ring], ring.map(move)); + // only the edges on the shadow side sweep a band outside the house; the others lie inside the union already + const turn = Math.sign(area(ring)) || 1; + ring.forEach((a, i) => { + const b = ring[(i + 1) % ring.length]; + const outward = turn * ((b[1] - a[1]) * -sx - (b[0] - a[0]) * -sz); + if (outward <= 1e-9) return; + const band = [a, b, move(b), move(a)]; + if (Math.abs(area(band)) > 1e-3) rings.push(band); + }); + } + return mergeHoles(rings); +} + +export class HouseShadow { + readonly mesh: Mesh; + private readonly material = new MeshBasicMaterial({ color: 0x000000, side: DoubleSide, transparent: true, opacity: 0, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 }); + + constructor() { + this.mesh = new Mesh(new BufferGeometry(), this.material); + this.mesh.renderOrder = 1; + this.mesh.visible = false; + } + + /** Lays the shadow of a footprint `height` high on the ground at `y`; null sun or `off` hides it. */ + update(footprint: readonly Vec2[][], height: number, y: number, sun: SunState | null, northDegrees: number, cloud: number, off: boolean): void { + const outline = off ? [] : shadowOutline(footprint, height, sun, northDegrees); + const positions: number[] = []; + for (const ring of outline) { + // the house stands on its own footprint: only the ground around it is shaded + const holes = footprint.filter((h) => pointInPolygon([h.reduce((s, p) => s + p[0], 0) / h.length, h.reduce((s, p) => s + p[1], 0) / h.length], ring)); + const corners = [...ring, ...holes.flat()]; + for (const [a, b, c] of triangulate(ring, holes.map((h) => [...h]))) for (const p of [corners[a], corners[b], corners[c]]) positions.push(p[0], y, p[1]); + } + this.mesh.geometry.dispose(); + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + this.mesh.geometry = geometry; + this.material.opacity = sun ? 0.32 * daylight(sun.elevation, cloud) : 0; + this.mesh.visible = positions.length > 0 && this.material.opacity > 0.02; + } + + dispose(): void { + this.mesh.geometry.dispose(); + this.material.dispose(); + } +} diff --git a/frontend/src/viewer/scene/labels.test.ts b/frontend/src/viewer/scene/labels.test.ts new file mode 100644 index 0000000..dc49de7 --- /dev/null +++ b/frontend/src/viewer/scene/labels.test.ts @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { OrthographicCamera } from "three"; +import { LabelPlacer, centredAt, floorLabelPosition, floorShowsMarkers, floorShowsOutdoorMarkers, leftAt, project, stackFloorLabels } from "./labels.ts"; + +test("a point in front of the camera lands on the screen, one behind it is off", () => { + const camera = new OrthographicCamera(-5, 5, 5, -5, 0.1, 100); + camera.position.set(0, 0, 10); + camera.lookAt(0, 0, 0); + camera.updateMatrixWorld(); + const middle = project(camera, [0, 0, 0], { w: 200, h: 100 }); + assert.deepEqual([middle.x, middle.y, middle.off], [100, 50, false]); + const corner = project(camera, [5, 5, 0], { w: 200, h: 100 }); + assert.deepEqual([corner.x, corner.y], [200, 0]); + assert.equal(project(camera, [20, 0, 0], { w: 200, h: 100 }).off, true); + assert.equal(project(camera, [5.2, 0, 0], { w: 200, h: 100 }, 1.1).off, false); +}); + +test("transforms centre an element at a point, or align its left edge", () => { + assert.equal(centredAt({ x: 10, y: 20 }), "translate(10px, 20px) translate(-50%, -50%)"); + assert.equal(leftAt(5, 6), "translate(5px, 6px) translate(0, -50%)"); +}); + +test("an element is only written when its place changes, and hidden follows null", () => { + const writes: string[] = []; + const element = { hidden: false, style: { set transform(v: string) { writes.push(v); } } } as unknown as HTMLElement; + const placer = new LabelPlacer(); + placer.place(element, "a"); + placer.place(element, "a"); + placer.place(element, "b"); + assert.deepEqual(writes, ["a", "b"]); + placer.place(element, null); + assert.equal(element.hidden, true); + placer.place(element, "b"); + assert.equal(element.hidden, false); + assert.deepEqual(writes, ["a", "b"], "b is where it still is"); +}); + +test("floor labels are stacked from the top floor down without covering each other", () => { + const labels = stackFloorLabels([ + { rank: 0, left: 0, y: 100, height: 20 }, + { rank: 1, left: 0, y: 105, height: 20 }, + { rank: 2, left: 0, y: 300, height: 20 }, + ]); + assert.deepEqual(labels.map((l) => l.rank), [2, 1, 0]); + assert.equal(labels[0].y, 300); + assert.equal(labels[1].y, 328, "pushed down from the label above: half of each height plus the gap"); + assert.equal(labels[2].y, 356); +}); + +test("a floor label sits left of the floor, moves to the right when the left is taken, and stays in view", () => { + const corners = [{ x: 200, y: 50 }, { x: 600, y: 60 }]; + assert.deepEqual(floorLabelPosition(corners, 100, { width: 800, inset: 0 }), { left: 86, y: 50 }); + assert.deepEqual(floorLabelPosition([{ x: 60, y: 50 }, { x: 600, y: 60 }], 100, { width: 800, inset: 0 }), { left: 8, y: 50 }, "kept at the margin"); + assert.deepEqual(floorLabelPosition([{ x: 130, y: 50 }, { x: 600, y: 60 }], 100, { width: 800, inset: 120 }), { left: 614, y: 60 }, "the left is taken by pictures"); + assert.equal(floorLabelPosition([{ x: 700, y: 1 }], 100, { width: 800, inset: 0 }).left, 586); +}); + +test("markers show only for a floor that is fully in view and not another floor", () => { + assert.equal(floorShowsMarkers({ to: 1, o: 1 }, false), true); + assert.equal(floorShowsMarkers({ to: 0.2, o: 0.2 }, false), false); + assert.equal(floorShowsMarkers({ to: 1, o: 1 }, true), false); + assert.equal(floorShowsMarkers({ to: 1, o: 0.5 }, false), false); +}); + +test("outdoor markers show wherever their floor is drawn and settled", () => { + assert.equal(floorShowsOutdoorMarkers({ to: 1, o: 1 }), true); + assert.equal(floorShowsOutdoorMarkers({ to: 0.22, o: 0.22 }), true, "a dimmed floor below the opened one"); + assert.equal(floorShowsOutdoorMarkers({ to: 0, o: 0 }), false, "a hidden floor"); + assert.equal(floorShowsOutdoorMarkers({ to: 1, o: 0.5 }), false, "still fading in"); +}); diff --git a/frontend/src/viewer/scene/labels.ts b/frontend/src/viewer/scene/labels.ts new file mode 100644 index 0000000..1d75ae5 --- /dev/null +++ b/frontend/src/viewer/scene/labels.ts @@ -0,0 +1,90 @@ +// Text and pins that float over the 3D view are HTML elements placed by projecting points of the scene onto the screen. Writing a +// style forces the browser to work, so a label is only touched when its place changes. + +import { Vector3, type Camera } from "three"; + +export interface ScreenSize { + w: number; + h: number; +} + +export interface ScreenPoint { + x: number; + y: number; + /** Behind the camera, or outside the view by more than the margin. */ + off: boolean; +} + +const scratch = new Vector3(); + +/** Where a point of the scene appears on the screen. `margin` is how far outside the view (1 = the edge) it may be and still count. */ +export function project(camera: Camera, point: readonly [number, number, number], size: ScreenSize, margin = 1.05): ScreenPoint { + scratch.set(point[0], point[1], point[2]).project(camera); + return { x: ((scratch.x + 1) / 2) * size.w, y: ((1 - scratch.y) / 2) * size.h, off: scratch.z > 1 || Math.abs(scratch.x) > margin || Math.abs(scratch.y) > margin }; +} + +/** The style that puts the middle of an element at a screen point. */ +export const centredAt = (p: { x: number; y: number }): string => `translate(${p.x}px, ${p.y}px) translate(-50%, -50%)`; + +/** The style that puts an element left-aligned at `left`, vertically centred on `y`. */ +export const leftAt = (left: number, y: number): string => `translate(${left}px, ${y}px) translate(0, -50%)`; + +/** Moves elements, and remembers where they are, so nothing is written twice. */ +export class LabelPlacer { + private readonly placed = new WeakMap(); + + /** Puts an element at a transform, or hides it (null). Hidden state and transform are only written when they changed. */ + place(element: HTMLElement, transform: string | null): void { + const hide = transform === null; + if (element.hidden !== hide) element.hidden = hide; + if (transform === null || this.placed.get(element) === transform) return; + this.placed.set(element, transform); + element.style.transform = transform; + } +} + +export interface FloorLabel { + rank: number; + left: number; + y: number; + height: number; +} + +/** Gap between stacked floor labels. */ +const LABEL_GAP = 8; + +/** Top floor first, each lower label is kept below the one above it, so that labels never cover each other. */ +export function stackFloorLabels(labels: readonly T[]): T[] { + const sorted = [...labels].sort((a, b) => b.rank - a.rank).map((l) => ({ ...l })); + for (let i = 1; i < sorted.length; i++) { + const above = sorted[i - 1]; + sorted[i].y = Math.max(sorted[i].y, above.y + (above.height + sorted[i].height) / 2 + LABEL_GAP); + } + return sorted; +} + +/** + * Where a floor's label goes: left of the floor's leftmost corner, or right of its rightmost one when the floor pictures on the left + * take that space. Kept inside the view. + */ +export function floorLabelPosition(corners: readonly { x: number; y: number }[], labelWidth: number, view: { width: number; inset: number }): { left: number; y: number } { + const leftmost = corners.reduce((best, c) => (c.x < best.x ? c : best)); + const rightmost = corners.reduce((best, c) => (c.x > best.x ? c : best)); + const minLeft = 8 + view.inset; + let [left, y] = [leftmost.x - labelWidth - 14, leftmost.y]; + if (left < minLeft && view.inset) [left, y] = [rightmost.x + 14, rightmost.y]; + return { left: Math.max(minLeft, Math.min(view.width - labelWidth - 8, left)), y }; +} + +/** Whether markers of a floor may show: it is fully in view, and the opened floor or no floor is opened. */ +export function floorShowsMarkers(floor: { to: number; o: number }, otherFloor: boolean): boolean { + return floor.to >= 0.99 && floor.o >= 0.9 && !otherFloor; +} + +/** + * Whether outdoor markers set to "always" may show: their floor is drawn and has settled, in the house view and below an opened + * floor too (the garden belongs to no storey). + */ +export function floorShowsOutdoorMarkers(floor: { to: number; o: number }): boolean { + return floor.to > 0 && Math.abs(floor.o - floor.to) < 0.05; +} diff --git a/frontend/src/viewer/scene/lamp-data.ts b/frontend/src/viewer/scene/lamp-data.ts new file mode 100644 index 0000000..dcdf5cd --- /dev/null +++ b/frontend/src/viewer/scene/lamp-data.ts @@ -0,0 +1,65 @@ +// What the viewer knows about each lamp model: its size when the plan gives none, where its light comes from, and how it hangs. + +import type { LightKind } from "../lighting.ts"; +import type { LampModel } from "./types.ts"; + +/** Width, depth and height of a lamp model in metres. */ +export const LAMP_SIZE: Record = { + ceiling: [0.4, 0.4, 0.08], + downlight: [0.1, 0.1, 0.02], + spot: [0.1, 0.1, 0.14], + panel: [0.6, 0.6, 0.03], + uplight: [0.35, 0.35, 1.8], + bollard: [0.16, 0.16, 0.8], + garden: [0.12, 0.12, 0.3], + pendant: [0.4, 0.4, 0.8], + fan: [1.32, 1.32, 0.32], + floor: [0.42, 0.42, 1.7], + table: [0.26, 0.26, 0.45], + wall: [0.22, 0.12, 0.2], + strip: [2, 0.04, 0.03], +}; + +/** Models that hang from the ceiling, which the cut view hides. */ +export const HANGING_LAMPS: ReadonlySet = new Set(["ceiling", "downlight", "spot", "panel", "pendant", "fan", "strip"]); + +/** LED strips mounted lower than this (metres) wash the wall upwards instead of lighting down. */ +export const LOW_STRIP = 1.0; + +/** + * Where a lamp's light starts (height above the floor) and what kind of light it is, for a room of height `ceiling`. `base` is the + * height the lamp stands or hangs at, `height` its own height. + */ +export function lightOrigin(model: LampModel, ceiling: number, base: number, height: number): [number, LightKind] { + switch (model) { + case "ceiling": + return [ceiling - 0.12, "ceiling"]; + case "downlight": + return [ceiling - 0.03, "spot"]; + case "spot": + return [ceiling - height, "spot"]; + case "panel": + return [ceiling - 0.05, "ceiling"]; + case "pendant": + return [Math.max(0.5, ceiling - height), "pendant"]; + // the light kit under the motor shines down + case "fan": + return [Math.max(0.5, ceiling - height + 0.02), "ceiling"]; + case "floor": + return [base + height - 0.15, "omni"]; + case "uplight": + return [base + height, "up"]; + case "table": + return [base + height - 0.1, "omni"]; + case "wall": + return [base + 0.1, "wall"]; + // a strip under the ceiling or the wall cabinets shines down; one low down (skirting, behind a cabinet) washes the wall and + // the floor around it from below + case "strip": + return [base + Math.max(0.02, height) - 0.01, base < LOW_STRIP ? "up" : "ceiling"]; + case "bollard": + return [base + height - 0.08, "ceiling"]; + case "garden": + return [base + height, "up"]; + } +} diff --git a/frontend/src/viewer/scene/light-sources.test.ts b/frontend/src/viewer/scene/light-sources.test.ts new file mode 100644 index 0000000..31887bc --- /dev/null +++ b/frontend/src/viewer/scene/light-sources.test.ts @@ -0,0 +1,69 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { box, floorWith } from "../../entities/fixtures.ts"; +import { HANGING_LAMPS, lightOrigin } from "./lamp-data.ts"; +import { lightSourcesOf } from "./light-sources.ts"; +import type { DeviceMarker } from "./types.ts"; + +const marker = (extra: Partial): DeviceMarker => + ({ id: "light.a", floorId: "g", roomId: "r", x: 1, z: 1, y: 1, icon: "", name: "", text: "", active: true, unavailable: false, glow: { color: [1, 0.5, 0], level: 1 }, ...extra }) as DeviceMarker; +const floor = floorWith([box("r", 0, 0, 4, 4)], { height: 2.5 }); +const on = (m: DeviceMarker) => m.glow; + +test("a ceiling lamp lights from just under the ceiling, a floor lamp from near its top", () => { + assert.deepEqual(lightOrigin("ceiling", 2.5, 0, 0.08), [2.38, "ceiling"]); + const [y, kind] = lightOrigin("floor", 2.5, 0, 1.7); + assert.equal(kind, "omni"); + assert.ok(Math.abs(y - 1.55) < 1e-9); + assert.deepEqual(lightOrigin("pendant", 2.5, 0, 3), [0.5, "pendant"], "a long pendant never hangs lower than 50 cm"); +}); + +test("only lamps that are on and on this floor give light", () => { + const sources = lightSourcesOf(floor, null, [marker({ lamp: "ceiling" }), marker({ id: "light.b", glow: null }), marker({ id: "light.c", floorId: "other" })], on); + assert.equal(sources.length, 1); + assert.deepEqual([sources[0].kind, sources[0].color, sources[0].level], ["ceiling", [1, 0.5, 0], 1]); +}); + +test("a marker without a lamp model is an all-round light at its own height, and a given light height wins", () => { + const [plain] = lightSourcesOf(floor, null, [marker({ y: 0.8 })], on); + assert.deepEqual([plain.kind, plain.y], ["omni", 0.8]); + const [fixed] = lightSourcesOf(floor, null, [marker({ lamp: "ceiling", lightY: 1.1 })], on); + assert.equal(fixed.y, 1.1); +}); + +test("a strip is three lights along its length with a share of the level; standing up it climbs", () => { + const strip = lightSourcesOf(floor, null, [marker({ lamp: "strip", size: [2, 0.04, 0.03], rotation: 0, base: 2.4 })], on); + assert.equal(strip.length, 3); + assert.deepEqual(strip.map((s) => Math.round(s.x * 100) / 100), [0.33, 1, 1.67]); + assert.ok(strip.every((s) => Math.abs(s.level - 0.55) < 1e-9 && s.kind === "ceiling")); + const upright = lightSourcesOf(floor, null, [marker({ lamp: "strip", size: [1.2, 0.04, 0.03], upright: true, base: 0 })], on); + assert.deepEqual(upright.map((s) => s.kind), ["omni", "omni", "omni"]); + assert.ok(upright[0].y < upright[1].y && upright[1].y < upright[2].y); + const low = lightSourcesOf(floor, null, [marker({ lamp: "strip", base: 0.2, size: [1, 0.04, 0.03] })], on); + assert.equal(low[0].kind, "up", "a low strip washes the wall upwards"); + const rolled = lightSourcesOf(floor, null, [marker({ lamp: "strip", base: 2.4, roll: 90, size: [1, 0.04, 0.03] })], on); + assert.equal(rolled[0].kind, "omni"); +}); + +test("rooms joined by an open wall share one light zone", () => { + const [s] = lightSourcesOf(floor, [5], [marker({ lamp: "ceiling" })], on); + assert.equal(s.room, 5); +}); + +test("hanging lamps are the ceiling kinds", () => { + assert.equal(HANGING_LAMPS.has("pendant"), true); + assert.equal(HANGING_LAMPS.has("floor"), false); +}); + +test("a rising strip climbs along its length from its mount height, and one under the ceiling falls away from it", () => { + const level = lightSourcesOf(floor, null, [marker({ lamp: "strip", size: [2, 0.04, 0.03], rotation: 0, base: 1 })], on); + const rising = lightSourcesOf(floor, null, [marker({ lamp: "strip", size: [2, 0.04, 0.03], rotation: 0, base: 1, rise: 30 })], on); + assert.ok(rising[0].y < rising[1].y && rising[1].y < rising[2].y, "climbs towards its +x end"); + // the low end stays at the mount height: the middle is half the strip's rise above the level strip's + assert.ok(Math.abs(rising[1].y - level[1].y - Math.sin(Math.PI / 6)) < 1e-9); + // the run along the floor is shorter than the strip + assert.ok(rising[2].x - rising[0].x < level[2].x - level[0].x); + const underCeiling = lightSourcesOf(floor, null, [marker({ lamp: "strip", size: [2, 0.04, 0.03], rotation: 0, rise: 30 })], on); + const flatCeiling = lightSourcesOf(floor, null, [marker({ lamp: "strip", size: [2, 0.04, 0.03], rotation: 0 })], on); + assert.ok(underCeiling[2].y <= flatCeiling[2].y + 1e-9, "its high end stays under the ceiling"); +}); diff --git a/frontend/src/viewer/scene/light-sources.ts b/frontend/src/viewer/scene/light-sources.ts new file mode 100644 index 0000000..83f6100 --- /dev/null +++ b/frontend/src/viewer/scene/light-sources.ts @@ -0,0 +1,48 @@ +// The point lights of a floor that are on: one per lit lamp (three along a strip), with the height and kind of light of their model. + +import type { Floor } from "../../model.ts"; +import { roomIndexAt, zoneOf, type LightKind, type LightSource } from "../lighting.ts"; +import { LAMP_SIZE, lightOrigin } from "./lamp-data.ts"; +import { stripPoint, stripRiseLift } from "./strip.ts"; +import type { DeviceMarker } from "./types.ts"; + +const RADIANS = Math.PI / 180; +const FALLBACK_SIZE = [0.3, 0.3, 0.3] as const; + +/** A strip lights along its whole length, so it counts as three lights each giving a little over half of its level. */ +const STRIP_SHARES = [-1 / 3, 0, 1 / 3]; +const STRIP_LEVEL = 0.55; + +/** The glow of a marker (its colour and level) when it is on; null for lamps that are off. */ +export type GlowOf = (marker: DeviceMarker) => DeviceMarker["glow"]; + +/** The light sources on a floor. `zones` joins rooms that have no wall between them, so a lamp lights its open neighbour. */ +export function lightSourcesOf(floor: Floor, zones: readonly number[] | null, markers: readonly DeviceMarker[], glowOf: GlowOf): LightSource[] { + const sources: LightSource[] = []; + for (const marker of markers) { + const glow = glowOf(marker); + if (marker.floorId !== floor.id || !glow) continue; + const room = zoneOf(zones as number[] | null, roomIndexAt(floor, marker.x, marker.z)); + const [width, , height] = marker.size ?? (marker.lamp ? LAMP_SIZE[marker.lamp] : FALLBACK_SIZE); + const base = marker.base ?? 0; + const [fallbackY, kind]: [number, LightKind] = marker.lamp ? lightOrigin(marker.lamp, marker.ceiling ?? floor.height, base, height) : [marker.y, "omni"]; + const y = marker.lightY ?? fallbackY; + const { color, level } = glow; + if (marker.lamp !== "strip") { + sources.push({ x: marker.x, y, z: marker.z, color, level, kind, room }); + continue; + } + // standing upright a strip climbs; one turned on its side (or standing) lights all around rather than up or down + const heading = (marker.rotation ?? 0) * RADIANS; + const sideways = !!marker.upright || Math.abs(marker.roll ?? 0) > 45; + const middle = y + stripRiseLift(marker.base, width, marker.rise); + for (const along of STRIP_SHARES) { + if (marker.upright) sources.push({ x: marker.x, y: base + width * (0.5 + along), z: marker.z, color, level: level * STRIP_LEVEL, kind: "omni", room }); + else { + const [px, py, pz] = stripPoint(marker.x, middle, marker.z, heading, width, marker.rise, along); + sources.push({ x: px, y: py, z: pz, color, level: level * STRIP_LEVEL, kind: sideways ? "omni" : kind, room }); + } + } + } + return sources; +} diff --git a/frontend/src/viewer/scene/materials.ts b/frontend/src/viewer/scene/materials.ts new file mode 100644 index 0000000..fa1a60f --- /dev/null +++ b/frontend/src/viewer/scene/materials.ts @@ -0,0 +1,82 @@ +// The materials of one floor. Every floor gets its own set so that its opacity can change without touching the others. Surfaces and +// lines pass through the look (neon, blueprint, day), and the ones that follow the cut view are made foldable. + +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"; + +export interface FloorMaterials { + floor: MeshBasicMaterial; + pattern: MeshBasicMaterial; + wall: MeshBasicMaterial; + glassWall: MeshBasicMaterial; + shadow: MeshBasicMaterial; + lines: LineBasicMaterial; + glow: MeshBasicMaterial; + frames: MeshBasicMaterial; + glass: MeshBasicMaterial; + blinds: MeshBasicMaterial; + lamps: MeshBasicMaterial; + halos: PointsMaterial; + cones: MeshBasicMaterial; + screens: MeshBasicMaterial; + /** See-through outdoor areas: one material per opacity, added while the floor is built; `base` is the opacity before the floor fades. */ + ghosts: { material: MeshBasicMaterial; base: number }[]; +} + +export interface MaterialInputs { + mask: FoldMasks; + look: ThemeUniform; + theme: Theme; + textures: { pattern: CanvasTexture; blinds: CanvasTexture; halo: CanvasTexture }; +} + +/** Shader patch for the floor pattern: picks the atlas tile per vertex and repeats it every metre. */ +const PATTERN_VERTEX_DECLARATIONS = "#include \nattribute vec2 tile;\nvarying vec2 vNfTile;"; +const PATTERN_TILE_PASS = "#include \nvNfTile = tile;"; +const PATTERN_SAMPLE = `#ifdef USE_MAP + vec2 nfCell = fract(vMapUv); + vec2 nfUv = (vNfTile + 0.004 + nfCell * 0.992) / vec2(3.0, 2.0); + // gradients of the unwrapped coordinates avoid mip seams at the tile borders + vec4 sampledDiffuseColor = textureGrad(map, nfUv, dFdx(vMapUv) / vec2(3.0, 2.0), dFdy(vMapUv) / vec2(3.0, 2.0)); + diffuseColor *= sampledDiffuseColor; + #endif`; + +/** Additive floor pattern. */ +export function patternMaterial(texture: CanvasTexture): MeshBasicMaterial { + const material = new MeshBasicMaterial({ map: texture, transparent: true, blending: AdditiveBlending, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2 }); + material.onBeforeCompile = (shader) => { + shader.vertexShader = shader.vertexShader.replace("#include ", PATTERN_VERTEX_DECLARATIONS).replace("#include ", PATTERN_TILE_PASS); + shader.fragmentShader = shader.fragmentShader.replace("#include ", "#include \nvarying vec2 vNfTile;").replace("#include ", PATTERN_SAMPLE); + }; + material.customProgramCacheKey = () => "nf-pattern"; + return material; +} + +/** A glowing, see-through material drawn on top of what is under it. */ +const overlay = (extra: ConstructorParameters[0] = {}) => + new MeshBasicMaterial({ vertexColors: true, transparent: true, blending: AdditiveBlending, depthWrite: false, ...extra }); + +export function makeFloorMaterials({ mask, look, theme, textures }: MaterialInputs): FloorMaterials { + const solid = (extra: ConstructorParameters[0] = {}) => new MeshBasicMaterial({ vertexColors: true, ...extra }); + const foldable = (m: T, glass?: "solid" | "glass") => makeFoldable(m as never, mask, glass) as unknown as T; + return { + floor: themed(solid(), look), + pattern: patternMaterial(textures.pattern), + wall: 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 }), + lines: themed(foldable(new LineBasicMaterial({ vertexColors: true, transparent: true, blending: lineBlending(theme), depthWrite: false })), look, true), + // light on floors and walls follows the cut and the glass walls like the walls themselves + glow: foldable(overlay({ side: DoubleSide, polygonOffset: true, polygonOffsetFactor: -3 }), "solid"), + frames: themed(foldable(solid({ side: DoubleSide })), look), + glass: foldable(overlay({ side: DoubleSide })), + blinds: themed(foldable(solid({ map: textures.blinds, side: DoubleSide })), look), + lamps: themed(solid(), look), + halos: new PointsMaterial({ map: textures.halo, size: 0.9, sizeAttenuation: true, vertexColors: true, transparent: true, blending: AdditiveBlending, depthWrite: false }), + cones: overlay({ side: DoubleSide }), + screens: overlay({ side: DoubleSide }), + ghosts: [], + }; +} diff --git a/frontend/src/viewer/scene/opening-motion.test.ts b/frontend/src/viewer/scene/opening-motion.test.ts new file mode 100644 index 0000000..1418efd --- /dev/null +++ b/frontend/src/viewer/scene/opening-motion.test.ts @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { atTarget, stepOpening, stepShare } from "./opening-motion.ts"; +import type { OpeningState } from "../openings.ts"; + +const closed: OpeningState = { open: 0, open2: 0, tilt: 0, tilt2: 0, cover: null }; + +test("the share of the way covered grows with the frame time", () => { + assert.equal(stepShare(0), 0); + assert.ok(stepShare(16) > 0 && stepShare(16) < stepShare(160)); + assert.ok(Math.abs(stepShare(160) - (1 - Math.exp(-1))) < 1e-12); +}); + +test("an opening at its target needs nothing, whatever small differences remain", () => { + assert.equal(atTarget(closed, closed), true); + assert.equal(atTarget({ ...closed, open: 0.001 }, closed), true); + assert.equal(atTarget({ ...closed, open: 0.5 }, closed), false); + assert.equal(atTarget(closed, { ...closed, sensed: true }), false); + assert.equal(atTarget({ ...closed, cover: 0.2 }, { ...closed, cover: null }), false); +}); + +test("a sash moves a share of the way each frame and arrives exactly", () => { + const target: OpeningState = { ...closed, open: 1 }; + let { state, moving } = stepOpening(closed, target, 0.5); + assert.equal(state.open, 0.5); + assert.equal(moving, true); + for (let i = 0; i < 20; i++) ({ state, moving } = stepOpening(state, target, 0.5)); + assert.equal(state.open, 1); + assert.equal(moving, false); +}); + +test("a blind that appears or goes jumps; one that moves is eased", () => { + assert.equal(stepOpening(closed, { ...closed, cover: 0.8 }, 0.5).state.cover, 0.8); + assert.equal(stepOpening({ ...closed, cover: 0.8 }, closed, 0.5).state.cover, null); + const eased = stepOpening({ ...closed, cover: 0 }, { ...closed, cover: 1 }, 0.25); + assert.equal(eased.state.cover, 0.25); + assert.equal(eased.moving, true); +}); + +test("the second leaf and the sensed flag follow the target", () => { + const step = stepOpening({ ...closed, open2: 0 }, { ...closed, open2: 0.4, sensed: true }, 1); + assert.equal(step.state.open2, 0.4); + assert.equal(step.state.sensed, true); +}); + +test("a door leaf no sensor reports keeps that mark while it moves, and losing it is a change", () => { + const step = stepOpening(closed, { ...closed, open: 1, assumed: true }, 0.5); + assert.equal(step.state.assumed, true); + assert.equal(atTarget({ ...closed, assumed: true }, closed), false); +}); diff --git a/frontend/src/viewer/scene/opening-motion.ts b/frontend/src/viewer/scene/opening-motion.ts new file mode 100644 index 0000000..4340eb0 --- /dev/null +++ b/frontend/src/viewer/scene/opening-motion.ts @@ -0,0 +1,40 @@ +// Doors, windows and blinds move smoothly towards what Home Assistant reports. One step of that: how far each part got in a frame. + +import type { OpeningState } from "../openings.ts"; + +/** Time constant of the movement in milliseconds: about 0.8 s until a window has settled. */ +export const OPENING_TAU = 160; +/** Closer than this (as a fraction of the way), a part counts as arrived. */ +const ARRIVED = 0.003; + +const PARTS = ["open", "open2", "tilt", "tilt2"] as const; + +/** The share of the remaining way covered in a frame of `dt` milliseconds. */ +export const stepShare = (dt: number): number => 1 - Math.exp(-dt / OPENING_TAU); + +const sameNumber = (a: number | null | undefined, b: number | null | undefined): boolean => (a ?? null) === (b ?? null) || (typeof a === "number" && typeof b === "number" && Math.abs(a - b) < ARRIVED); + +/** Whether the opening already shows what it should: nothing to do for it (the usual case). */ +export function atTarget(now: OpeningState, target: OpeningState): boolean { + return PARTS.every((part) => sameNumber(target[part] ?? 0, now[part] ?? 0)) && sameNumber(target.cover, now.cover) && !!target.sensed === !!now.sensed && !!target.unlocked === !!now.unlocked && !!target.assumed === !!now.assumed; +} + +export interface Step { + state: OpeningState; + /** Some part has not arrived yet, so another frame is needed. */ + moving: boolean; +} + +/** One frame towards the target. The blind jumps when it appears or goes (no blind is null), and otherwise moves like the rest. */ +export function stepOpening(now: OpeningState, target: OpeningState, share: number): Step { + const state: OpeningState = { ...now, open2: now.open2 ?? 0, tilt2: now.tilt2 ?? 0, sensed: target.sensed, unlocked: target.unlocked, assumed: target.assumed }; + let moving = false; + const approach = (from: number, to: number): number => { + if (Math.abs(to - from) < ARRIVED) return to; + moving = true; + return from + (to - from) * share; + }; + for (const part of PARTS) state[part] = approach(now[part] ?? 0, target[part] ?? 0); + state.cover = target.cover === null || now.cover === null ? target.cover : approach(now.cover, target.cover); + return { state, moving }; +} diff --git a/frontend/src/viewer/scene/pins.ts b/frontend/src/viewer/scene/pins.ts new file mode 100644 index 0000000..d8bbbe3 --- /dev/null +++ b/frontend/src/viewer/scene/pins.ts @@ -0,0 +1,60 @@ +// The round markers for devices that float over the 3D view: an icon, a state text, a power reading and a caption. They are plain +// buttons, so they can be tapped, held (details) and reached with the keyboard. + +/** What a pin needs to know of the viewer, and what it tells it. */ +export interface PinHooks { + /** Furnishing is on: a press starts dragging the device instead of acting on it. */ + furnishing(): boolean; + /** The device was pressed while furnishing; the controls see the pointer as well and start the drag. */ + pressedWhileFurnishing(entityId: string): void; + selectWhileFurnishing(entityId: string): void; + /** The pin's centre relative to the viewer, in pixels. */ + centre(pin: HTMLElement): { x: number; y: number }; + tap(entityId: string, x: number, y: number): void; + hold(entityId: string, x: number, y: number): void; +} + +/** How long a press must last to count as a hold. */ +export const HOLD_MS = 500; + +const part = (klass: string) => Object.assign(document.createElement("span"), { className: klass }); + +export function createDevicePin(entityId: string, hooks: PinHooks): HTMLButtonElement { + const pin = Object.assign(document.createElement("button"), { className: "nf-dev" }); + pin.dataset.entity = entityId; + pin.append(part("nf-dev-icon"), part("nf-dev-text"), part("nf-dev-watt"), part("nf-dev-name")); + + let holdTimer: ReturnType | undefined; + let wasHeld = false; + const reportAt = (report: (id: string, x: number, y: number) => void) => { + const { x, y } = hooks.centre(pin); + report(entityId, x, y); + }; + const stopTimer = () => clearTimeout(holdTimer); + + pin.addEventListener("pointerdown", (e) => { + if (hooks.furnishing()) return hooks.pressedWhileFurnishing(entityId); + e.stopPropagation(); + wasHeld = false; + stopTimer(); + holdTimer = setTimeout(() => { + wasHeld = true; + reportAt(hooks.hold); + }, HOLD_MS); + }); + for (const ending of ["pointerleave", "pointercancel", "pointerup"] as const) pin.addEventListener(ending, stopTimer); + pin.addEventListener("contextmenu", (e) => e.preventDefault()); + pin.addEventListener("click", (e) => { + e.stopPropagation(); + if (hooks.furnishing()) return hooks.selectWhileFurnishing(entityId); + if (!wasHeld) reportAt(hooks.tap); + }); + // from the keyboard Enter acts like a tap, and Shift+Enter or the context-menu key opens the details + pin.addEventListener("keydown", (e) => { + if ((e.key === "Enter" && e.shiftKey) || e.key === "ContextMenu") { + e.preventDefault(); + reportAt(hooks.hold); + } + }); + return pin; +} diff --git a/frontend/src/viewer/scene/strip.ts b/frontend/src/viewer/scene/strip.ts new file mode 100644 index 0000000..29a7c0a --- /dev/null +++ b/frontend/src/viewer/scene/strip.ts @@ -0,0 +1,24 @@ +// LED strips that rise along their length (up a sloped ceiling or a stair): where their middle and their points lie. + +const DEG = Math.PI / 180; + +/** + * How much higher (or lower) the middle of a rising strip sits than that of a level one: a strip on a mount height keeps its low + * end there and rises from it, one under the ceiling keeps its high end there and falls away from it. + */ +export function stripRiseLift(base: number | null | undefined, width: number, rise: number | null | undefined): number { + const up = Math.abs(rise ?? 0) * DEG; + if (!up) return 0; + const half = (width / 2) * Math.sin(up); + return base != null ? half : -half; +} + +/** + * A point `along` a strip (-0.5 at one end, 0.5 at the other) of `width`, turned by `heading` (radians) around its middle at + * (x, y, z): level strips stay at y, rising ones climb by `rise` degrees towards the +along end. + */ +export function stripPoint(x: number, y: number, z: number, heading: number, width: number, rise: number | null | undefined, along: number): [number, number, number] { + const r = (rise ?? 0) * DEG; + const run = width * along * Math.cos(r); + return [x + Math.cos(heading) * run, y + width * along * Math.sin(r), z + Math.sin(heading) * run]; +} diff --git a/frontend/src/viewer/scene/sun-arc.test.ts b/frontend/src/viewer/scene/sun-arc.test.ts new file mode 100644 index 0000000..8425c42 --- /dev/null +++ b/frontend/src/viewer/scene/sun-arc.test.ts @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { arcPoints, pointOnDome, type SunArcPlace } from "./sun-arc.ts"; + +const place: SunArcPlace = { centre: [10, 20], radius: 10, north: 0, latitude: 50.9, longitude: 8.2, zone: "Europe/Berlin" }; + +test("a point of the dome: the horizon lies on the ring, the zenith above the middle", () => { + const [x, y, z] = pointOnDome(place, { elevation: 0, azimuth: 0 }); + assert.deepEqual([Math.round(x * 100) / 100, y, Math.round(z * 100) / 100], [10, 0, 10], "north is up the plan, so z shrinks"); + const [ex, , ez] = pointOnDome(place, { elevation: 0, azimuth: 90 }); + assert.deepEqual([Math.round(ex * 100) / 100, Math.round(ez * 100) / 100], [20, 20], "east is to the right"); + const [zx, zy, zz] = pointOnDome(place, { elevation: 90, azimuth: 123 }); + assert.ok(Math.abs(zx - 10) < 1e-9 && Math.abs(zz - 20) < 1e-9 && Math.abs(zy - 9) < 1e-9); + const [rx, , rz] = pointOnDome({ ...place, north: 90 }, { elevation: 0, azimuth: 0 }); + assert.deepEqual([Math.round(rx * 100) / 100, Math.round(rz * 100) / 100], [20, 20], "north turned a quarter clockwise points right"); +}); + +test("today's arc rises in the east, peaks in the south and sets in the west, higher in summer than in winter", () => { + const summer = arcPoints(place, new Date("2026-06-21T10:00:00Z")); + const winter = arcPoints(place, new Date("2026-12-21T10:00:00Z")); + assert.ok(summer.length > winter.length && winter.length > 10); + const top = (pts: number[][]) => Math.max(...pts.map((p) => p[1])); + assert.ok(top(summer) > top(winter) + 2); + assert.ok(summer[0][0] > place.centre[0] - 1 && summer[0][2] < place.centre[1], "the first point lies north-east"); + assert.ok(summer[summer.length - 1][0] < place.centre[0] + 1, "the last lies in the west half"); + const noon = summer.reduce((best, p) => (p[1] > best[1] ? p : best)); + assert.ok(noon[2] > place.centre[1], "the highest point lies south of the middle (z grows to the south)"); +}); diff --git a/frontend/src/viewer/scene/sun-arc.ts b/frontend/src/viewer/scene/sun-arc.ts new file mode 100644 index 0000000..123a95c --- /dev/null +++ b/frontend/src/viewer/scene/sun-arc.ts @@ -0,0 +1,124 @@ +// The sun's path over the plot: a ring on the ground with the four points of the compass, and the arc the sun draws today with a +// bead where it stands now. Drawn from lines only, rebuilt when the sun or the plot moves a little, so it costs nothing per frame. + +import { BufferGeometry, CanvasTexture, Float32BufferAttribute, Group, Line, LineBasicMaterial, LineSegments, Mesh, MeshBasicMaterial, Sprite, SpriteMaterial, SphereGeometry } from "three"; +import { sunPosition, todayAt } from "../../sun-position.ts"; +import { directionToSun } from "./sunlight.ts"; +import type { SunState } from "./types.ts"; + +export interface SunArcPlace { + /** The middle of the plot and the ring's radius, in plan metres. */ + centre: [number, number]; + radius: number; + /** Where north lies in the plan (degrees clockwise from up). */ + north: number; + latitude: number; + longitude: number; + zone?: string | null; +} + +/** The points of today's arc: where the sun stands every quarter of an hour while it is above the horizon, on a ring of `radius`. */ +export function arcPoints(place: SunArcPlace, now = new Date()): [number, number, number][] { + const points: [number, number, number][] = []; + for (let h = 0; h <= 24; h += 0.25) { + const sun = sunPosition(todayAt(Math.min(h, 23.99), place.zone, now), place.latitude, place.longitude); + if (sun.elevation < 0) continue; + points.push(pointOnDome(place, sun)); + } + return points; +} + +/** A sun position as a point of the dome over the plot: the horizon on the ring, the zenith at 0.9 of its radius above the middle. */ +export function pointOnDome(place: SunArcPlace, sun: SunState): [number, number, number] { + const [dx, dz] = directionToSun(sun.azimuth, place.north); + const e = (Math.max(0, sun.elevation) * Math.PI) / 180; + return [place.centre[0] + dx * place.radius * Math.cos(e), Math.sin(e) * place.radius * 0.9, place.centre[1] + dz * place.radius * Math.cos(e)]; +} + +function label(text: string, colour: string): Sprite { + const c = document.createElement("canvas"); + c.width = c.height = 64; + const ctx = c.getContext("2d"); + if (ctx) { + ctx.font = "bold 44px system-ui, sans-serif"; + ctx.fillStyle = colour; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(text, 32, 34); + } + const sprite = new Sprite(new SpriteMaterial({ map: new CanvasTexture(c), transparent: true, depthWrite: false, depthTest: false })); + sprite.renderOrder = 20; + return sprite; +} + +export class SunArc { + readonly group = new Group(); + private key = ""; + + constructor() { + this.group.visible = false; + this.group.renderOrder = 15; + } + + /** Draws (or hides, with `place` null) the ring, the compass letters, today's arc and the sun's bead. */ + update(place: SunArcPlace | null, sun: SunState | null, groundY: number): void { + const key = place ? `${place.centre},${place.radius.toFixed(1)},${place.north},${place.latitude.toFixed(2)},${place.longitude.toFixed(2)},${new Date().toDateString()},${groundY},${sun ? `${sun.elevation.toFixed(0)},${sun.azimuth.toFixed(0)}` : "-"}` : "off"; + if (key === this.key) return; + this.key = key; + this.clear(); + if (!place) { + this.group.visible = false; + return; + } + this.group.visible = true; + const y = groundY + 0.05; + const ring: number[] = []; + for (let i = 0; i <= 96; i++) { + const a = (i / 96) * Math.PI * 2; + ring.push(place.centre[0] + Math.cos(a) * place.radius, y, place.centre[1] + Math.sin(a) * place.radius); + } + const ringGeo = new BufferGeometry(); + ringGeo.setAttribute("position", new Float32BufferAttribute(ring, 3)); + this.group.add(new Line(ringGeo, new LineBasicMaterial({ color: 0x6f8fc8, transparent: true, opacity: 0.55, depthWrite: false }))); + // four ticks and the letters; north (red) comes from the plan's own north + const ticks: number[] = []; + [["N", 0], ["E", 90], ["S", 180], ["W", 270]].forEach(([text, az]) => { + const [dx, dz] = directionToSun(az as number, place.north); + ticks.push(place.centre[0] + dx * place.radius * 0.94, y, place.centre[1] + dz * place.radius * 0.94, place.centre[0] + dx * place.radius * 1.04, y, place.centre[1] + dz * place.radius * 1.04); + const sprite = label(text as string, text === "N" ? "#ff6b6b" : "#9fb4d8"); + sprite.position.set(place.centre[0] + dx * place.radius * 1.12, y + 0.4, place.centre[1] + dz * place.radius * 1.12); + sprite.scale.setScalar(Math.max(1.2, place.radius * 0.12)); + this.group.add(sprite); + }); + const tickGeo = new BufferGeometry(); + tickGeo.setAttribute("position", new Float32BufferAttribute(ticks, 3)); + this.group.add(new LineSegments(tickGeo, new LineBasicMaterial({ color: 0x9fb4d8, transparent: true, opacity: 0.8, depthWrite: false }))); + const arc = arcPoints(place).map(([x, py, z]) => [x, groundY + py, z]); + if (arc.length > 1) { + const arcGeo = new BufferGeometry(); + arcGeo.setAttribute("position", new Float32BufferAttribute(arc.flat(), 3)); + this.group.add(new Line(arcGeo, new LineBasicMaterial({ color: 0xffc247, transparent: true, opacity: 0.85, depthWrite: false }))); + } + if (sun && sun.elevation > 0) { + const [x, py, z] = pointOnDome(place, sun); + const bead = new Mesh(new SphereGeometry(Math.max(0.35, place.radius * 0.035), 12, 8), new MeshBasicMaterial({ color: 0xffd25a })); + bead.position.set(x, groundY + py, z); + this.group.add(bead); + } + } + + private clear(): void { + for (const child of [...this.group.children]) { + this.group.remove(child); + const m = child as Mesh; + m.geometry?.dispose(); + const mat = m.material as { map?: { dispose(): void }; dispose(): void } | undefined; + mat?.map?.dispose(); + mat?.dispose(); + } + } + + dispose(): void { + this.clear(); + } +} diff --git a/frontend/src/viewer/scene/sunlight.test.ts b/frontend/src/viewer/scene/sunlight.test.ts new file mode 100644 index 0000000..7cf2869 --- /dev/null +++ b/frontend/src/viewer/scene/sunlight.test.ts @@ -0,0 +1,62 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { newFloor, type Floor, type Opening, type Room } from "../../model.ts"; +import { buildFloorGeometry } from "../build.ts"; +import { daylight, directionToSun, sunlightPatches, sunSignature } from "./sunlight.ts"; + +const room: Room = { id: "r", name: "r", area_id: null, points: [[0, 0], [6, 0], [6, 5], [0, 5]], floor_material: "wood" }; +// edge 0 runs along the top of the plan (z = 0), a window on the outer north wall +const window: Opening = { id: "w", room_id: "r", edge: 0, offset: 3, width: 1.5, type: "window", sill: 0.9, height: 1.3, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null } as Opening; +const floor: Floor = { ...newFloor("f", "F", 0), height: 2.6, rooms: [room], openings: [window] }; +const geometry = buildFloorGeometry(floor, 0.3, 0.1); +const inputs = (sun: { elevation: number; azimuth: number } | null, extra = {}) => ({ floor, openings: geometry.openings, states: new Map(), sun, northDegrees: 0, cloud: 0, ...extra }); +const cells = (buffer: ReturnType) => buffer.count / 6; + +test("the sun's direction in the plan follows its azimuth and the house's north", () => { + const [x, z] = directionToSun(0, 0); + assert.ok(Math.abs(x) < 1e-9 && Math.abs(z + 1) < 1e-9, "from the north: up in the plan"); + const [east] = directionToSun(90, 0); + assert.ok(Math.abs(east - 1) < 1e-9); + const [turned] = directionToSun(0, 90); + assert.ok(Math.abs(turned - 1) < 1e-9, "north turned a quarter"); +}); + +test("daylight grows to full at 12° and clouds take most of it", () => { + assert.equal(daylight(6, 0), 0.5); + assert.equal(daylight(40, 0), 1); + assert.ok(Math.abs(daylight(40, 1) - 0.2) < 1e-9); +}); + +test("a window facing the sun gets a patch on the floor, inside the room", () => { + // the window is in the north wall (z = 0), so the sun must stand in the north, outside it + const buffer = sunlightPatches(inputs({ elevation: 30, azimuth: 0 })); + assert.ok(cells(buffer) > 0); + const positions = buffer.geometry().getAttribute("position"); + for (let i = 0; i < positions.count; i++) { + assert.ok(positions.getX(i) >= -1 && positions.getX(i) <= 7 && positions.getZ(i) >= -1 && positions.getZ(i) <= 6); + assert.ok(Math.abs(positions.getY(i) - 0.02) < 1e-6); + } +}); + +test("no patch when the sun is low, behind clouds, or on the other side of the house", () => { + assert.equal(cells(sunlightPatches(inputs({ elevation: 1, azimuth: 0 }))), 0); + assert.equal(cells(sunlightPatches(inputs({ elevation: 30, azimuth: 0 }, { cloud: 0.98 }))), 0); + assert.equal(cells(sunlightPatches(inputs({ elevation: 30, azimuth: 180 }))), 0); + assert.equal(cells(sunlightPatches(inputs(null))), 0); +}); + +test("a blind pulled all the way down leaves no patch, a half-closed one a smaller one", () => { + const open = cells(sunlightPatches(inputs({ elevation: 30, azimuth: 0 }))); + const half = cells(sunlightPatches(inputs({ elevation: 30, azimuth: 0 }, { states: new Map([["w", { open: 0, cover: 0.5 }]]) }))); + const shut = cells(sunlightPatches(inputs({ elevation: 30, azimuth: 0 }, { states: new Map([["w", { open: 0, cover: 1 }]]) }))); + assert.ok(half < open && half > 0); + assert.equal(shut, 0); +}); + +test("the signature changes with the sun, the clouds and the blinds, and is empty without sun", () => { + const a = sunSignature({ elevation: 30, azimuth: 10 }, 0, 0, [{ open: 0, cover: 0 }] as never); + assert.notEqual(a, sunSignature({ elevation: 31, azimuth: 10 }, 0, 0, [{ open: 0, cover: 0 }] as never)); + assert.notEqual(a, sunSignature({ elevation: 30, azimuth: 10 }, 0, 0.5, [{ open: 0, cover: 0 }] as never)); + assert.notEqual(a, sunSignature({ elevation: 30, azimuth: 10 }, 0, 0, [{ open: 0, cover: 0.5 }] as never)); + assert.equal(sunSignature(null, 0, 0, []), ""); +}); diff --git a/frontend/src/viewer/scene/sunlight.ts b/frontend/src/viewer/scene/sunlight.ts new file mode 100644 index 0000000..81bea91 --- /dev/null +++ b/frontend/src/viewer/scene/sunlight.ts @@ -0,0 +1,92 @@ +// Patches of sunlight that fall through the windows onto the floor of the room behind them. A patch is laid in small cells and only +// the cells whose centre lies in the room are drawn, so it never crosses a wall or leaves the house. + +import { Color } from "three"; +import { pointInPolygon, type Floor } from "../../model.ts"; +import type { FloorGeometry } from "../build.ts"; +import { DEG, GeoBuffer } from "../geo.ts"; +import type { OpeningState } from "../openings.ts"; +import type { SunState } from "./types.ts"; + +/** Longest a patch reaches into the room (metres). */ +const MAX_REACH = 7; +const CELL_DEPTH = 0.25; +const CELL_WIDTH = 0.3; +/** The sun must be this many degrees above the horizon to shine in. */ +const MIN_ELEVATION = 2; +/** Colour of the patch next to the window; the far end is 45 % of it. */ +const PATCH_COLOUR: [number, number, number] = [1, 0.82, 0.55]; +const FAR_SHARE = 0.45; + +type OpeningInfo = FloorGeometry["openings"][number]; + +/** A signature of what the patches depend on, so they are rebuilt only when it changes. */ +export function sunSignature(sun: SunState | null, northDegrees: number, cloud: number, states: Iterable): string { + if (!sun) return ""; + return `${sun.elevation.toFixed(1)},${sun.azimuth.toFixed(1)},${northDegrees * DEG},${cloud.toFixed(2)},${[...states].map((o) => (o.cover ?? 0).toFixed(2)).join(",")}`; +} + +/** The horizontal direction towards the sun in plan coordinates (x right, z down, "up" is -z). */ +export const directionToSun = (azimuthDegrees: number, northDegrees: number): [number, number] => [Math.sin((northDegrees + azimuthDegrees) * DEG), -Math.cos((northDegrees + azimuthDegrees) * DEG)]; + +/** How much sun gets through: full from 12° up, and clouds take most of it. */ +export const daylight = (elevationDegrees: number, cloud: number): number => Math.min(1, elevationDegrees / 12) * (1 - 0.8 * cloud); + +/** Whether a window faces the sun, and how directly. */ +export const facingSun = (info: OpeningInfo, toSun: readonly [number, number]): number => -info.toRoom[0] * toSun[0] + -info.toRoom[1] * toSun[1]; + +export interface SunInputs { + floor: Floor; + openings: readonly OpeningInfo[]; + states: ReadonlyMap; + sun: SunState | null; + northDegrees: number; + cloud: number; +} + +export function sunlightPatches({ floor, openings, states, sun, northDegrees, cloud }: SunInputs): GeoBuffer { + const buffer = new GeoBuffer(); + if (!sun || sun.elevation <= MIN_ELEVATION || cloud >= 0.97) return buffer; + const day = daylight(sun.elevation, cloud); + const toSun = directionToSun(sun.azimuth, northDegrees); + // a sun low in the sky throws a patch far into the room + const reach = 1 / Math.tan(sun.elevation * DEG); + for (const info of openings) { + if (info.opening.type !== "window" || !info.exterior) continue; + const facing = facingSun(info, toSun); + if (facing < 0.05) continue; + // a blind lowered over the window shortens the lit part of it + const top = info.top - (states.get(info.opening.id)?.cover ?? 0) * (info.top - info.sill); + if (top - info.sill < 0.05) continue; + const room = floor.rooms.find((r) => r.id === info.opening.room_id); + if (!room || room.points.length < 3) continue; + // where a point of the window (along it at `along`, at height `y`) lands on the floor + const landing = (along: number, y: number): [number, number, number] => { + const d = Math.min(MAX_REACH, y * reach); + return [ + info.start[0] + info.axis[0] * along + info.toRoom[0] * info.faceRoom - toSun[0] * d, + 0.02, + info.start[1] + info.axis[1] * along + info.toRoom[1] * info.faceRoom - toSun[1] * d, + ]; + }; + const strength = 0.14 * day * Math.min(1, facing * 1.5); + const near = new Color(PATCH_COLOUR[0] * strength, PATCH_COLOUR[1] * strength, PATCH_COLOUR[2] * strength); + const far = near.clone().multiplyScalar(FAR_SHARE); + const rows = Math.max(1, Math.ceil(Math.min(MAX_REACH, top * reach) / CELL_DEPTH)); + const columns = Math.max(1, Math.ceil(info.width / CELL_WIDTH)); + const height = top - info.sill; + for (let row = 0; row < rows; row++) { + const [y0, y1] = [info.sill + (height * row) / rows, info.sill + (height * (row + 1)) / rows]; + const [colourA, colourB] = [near.clone().lerp(far, row / rows), near.clone().lerp(far, (row + 1) / rows)]; + for (let column = 0; column < columns; column++) { + const [s0, s1] = [(info.width * column) / columns, (info.width * (column + 1)) / columns]; + const middle = landing((s0 + s1) / 2, (y0 + y1) / 2); + if (!pointInPolygon([middle[0], middle[2]], room.points)) continue; + const [a, b, c, d] = [landing(s0, y0), landing(s1, y0), landing(s1, y1), landing(s0, y1)]; + buffer.tri(a, b, c, colourA, colourA, colourB); + buffer.tri(a, c, d, colourA, colourB, colourB); + } + } + } + return buffer; +} diff --git a/frontend/src/viewer/scene/types.ts b/frontend/src/viewer/scene/types.ts new file mode 100644 index 0000000..5a9152d --- /dev/null +++ b/frontend/src/viewer/scene/types.ts @@ -0,0 +1,179 @@ +// The types of the 3D viewer's public interface: what the main bundle hands in (devices, screens, persons) and what the viewer +// reports back (taps, drags, statistics). + +import type { Floor } from "../../model.ts"; +import type { LiveScreen } from "../live-screens.ts"; +import type { AnimationName } from "../../light-effects.ts"; + +export type { Theme } from "../theme.ts"; +export type { RobotInfo } from "../robot.ts"; +export type { OpeningState } from "../openings.ts"; +export type { SkyView, SkyWeather } from "../live-weather.ts"; +export type { EnergyArc, PlanPoint, SparkField } from "../live-energy.ts"; +export type { SoundSpot } from "../live-sound.ts"; + +export type Quality = "auto" | "low" | "high"; +export type WallMode = "auto" | "cut" | "slope"; +/** How the floors above and below the chosen one are shown. */ +export type FloorStack = "dim" | "stacked" | "single"; + +export type LampModel = "ceiling" | "downlight" | "spot" | "panel" | "pendant" | "fan" | "floor" | "uplight" | "table" | "wall" | "strip" | "bollard" | "garden"; + +export interface ViewerOptions { + quality?: Quality; + /** Pull the floors apart in the house view (default true). */ + explode?: boolean; + onRoomTap?: (floorId: string, roomId: string | null) => void; + onFloorTap?: (floorId: string) => void; + onBack?: () => void; + /** A short tap on a device marker. */ + onDeviceTap?: (entityId: string, x: number, y: number) => void; + /** A double tap on a room of the opened floor (without it, a double tap goes one level back). */ + onRoomDoubleTap?: (floorId: string, roomId: string) => void; + /** A long press on a device marker. */ + onDeviceHold?: (entityId: string, x: number, y: number) => void; + /** + * A vertical swipe on a device (dim a lamp, move a blind). "start" returns whether the device takes it; "move" reports the + * distance from the start (pixels, down is positive). + */ + onDeviceSwipe?: (entityId: string, phase: "start" | "move" | "end", dy: number, x: number, y: number) => boolean | void; + /** Furnishing in 3D: a device was selected (null: none) or dragged to a new place. */ + onDeviceSelect?: (entityId: string | null) => void; + onDeviceMove?: (entityId: string, x: number, z: number) => void; + /** Furnishing in 3D: a piece of furniture was selected (null: none) or dragged to a new place. */ + onFurnitureSelect?: (furnitureId: string | null) => void; + onFurnitureMove?: (furnitureId: string, x: number, z: number) => void; + onStats?: (stats: ViewerStats) => void; + /** The text for the floor labels in the house view, for example "5 rooms". */ + floorInfo?: (floor: Floor) => string; +} + +/** A device shown in the 3D view, prepared by the main bundle from placements and states. */ +export interface DeviceMarker { + /** The entity id. */ + id: string; + /** A small label under the pin: the device's own name. Empty for none. */ + caption?: string; + /** The device's own name from the plan (the card option marker_names shows it as the caption). */ + ownName?: string; + /** The own name is shown under the pin (per device). */ + showName?: boolean; + floorId: string; + roomId: string | null; + x: number; + z: number; + /** The height above the floor. */ + y: number; + /** The icon as inline SVG markup. */ + icon: string; + name: string; + /** A short state text such as "60 %" or "21,5 °C". */ + text: string; + active: boolean; + /** The text shows on the floor as well (a marker set to "always"); otherwise only in its room or while active. */ + full?: boolean; + unavailable: boolean; + /** A light cone on the floor for lights that are on. */ + glow: { color: [number, number, number]; level: number } | null; + /** The power drawn (W), when the device reports it. */ + power?: number | null; + /** Lights: the lamp model drawn at the device's position. */ + lamp?: LampModel | null; + /** A mirrored lamp furniture: its pack model is drawn mirrored. */ + mirror?: boolean; + /** A lamp: turn around y (degrees), size (w, d, h) and the height of what it stands on. */ + rotation?: number; + size?: [number, number, number]; + base?: number; + /** An LED strip: roll about its length (degrees), and standing upright (its length runs up from the base). */ + roll?: number; + upright?: boolean; + /** An LED strip: how steeply its length rises (degrees). */ + rise?: number; + /** Show the HTML marker. False: the 3D object alone stands for the device. */ + pin?: boolean; + /** A placed device fixed against moving. */ + fixed?: boolean; + /** The marker setting of its placement or furniture item (undefined means automatic). */ + show?: "always" | "active" | "no_power" | "never"; + /** The 3D lamp can be tapped: it has an entity. */ + pickable?: boolean; + /** The furniture item this lamp is, so it can be moved in 3D. */ + furnitureId?: string; + /** A lamp from a furniture pack (its type): drawn from the pack's parts. */ + pack?: string | null; + /** The height its light comes from (pack lamps). */ + lightY?: number; + /** Hanging lamps and fans: the ceiling they hang from (null = the floor height). */ + ceiling?: number; + /** Ceiling fan: turns of its blades per second (0 or unset = standing still). */ + spin?: number; + /** A colour effect runs (colour loop and the like): the colour is animated in 3D. */ + effect?: AnimationName; + /** The pendant shape: shade (default), globe, cone or drum. */ + variant?: string | null; + /** The formatted power, for example "85 W". */ + powerText?: string; + /** A plugin's shape on the floor from the device (a camera's field of view): stops at walls; `through` lets taps pass. */ + wedge?: { angle: number; reach: number; near: number; color: [number, number, number]; opacity: number; through: boolean; walls?: boolean } | null; +} + +/** A ray from the camera through the pointer, in building coordinates (heights above the ground). */ +export interface SurfaceRay { + o: [number, number, number]; + d: [number, number, number]; +} + +/** Grabbing and moving things on surfaces with rays; `start` says whether something was grabbed. */ +export interface SurfaceGrab { + start(ray: SurfaceRay): boolean; + move(ray: SurfaceRay): void; + end(): void; +} + +/** A lit TV or monitor screen: the colour (the light of a lit item) and the brightness (0..1). */ +export interface ScreenState { + color: [number, number, number]; + level: number; + /** Strength of the glow frame around the screen: 1 is the usual, 0 draws none (the item's own *Glow behind the TV*). */ + halo?: number; + /** Furniture with a state: glowing faces on top of the item instead of a screen, the whole top or a half of it. */ + faces?: { part: "all" | "left" | "right" | "top" | "bottom"; color: [number, number, number]; level: number }[]; +} + +/** The position of the sun (from sun.sun): degrees above the horizon and clockwise from north. */ +export interface SunState { + elevation: number; + azimuth: number; +} + +/** What a TV shows (NextFloor TV screens): the viewer finds the screen of the furniture itself. */ +export type LiveScreenInput = Omit & { furnitureId: string }; + +/** Called after every frame for each card anchor: where it is on screen (CSS pixels) and whether it shows. */ +export type LiveAnchorCallback = (index: number, x: number, y: number, visible: boolean) => void; + +export interface PersonPin { + id: string; + name: string; + initials: string; + picture: string | null; + floorId: string; + roomId: string; + x: number; + z: number; +} + +export interface ViewerStats { + /** Frames per second while something moves; 0 at rest, when nothing is drawn. */ + fps: number; + /** What keeps the picture moving: camera, floors, openings, flash, roof, flow, effect, robot, orbit, tint. */ + busy: string[]; + /** The slowest frame of the last measuring window (ms). */ + worstMs: number; + calls: number; + triangles: number; + /** The low quality level is active (tablet). */ + low: boolean; + pixelRatio: number; +} diff --git a/frontend/src/viewer/tap-reach.test.ts b/frontend/src/viewer/tap-reach.test.ts new file mode 100644 index 0000000..3911a02 --- /dev/null +++ b/frontend/src/viewer/tap-reach.test.ts @@ -0,0 +1,20 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { inReach } from "./tap-reach.ts"; + +const lamp = { floorId: "ground", roomId: "kitchen" }; +const hallSensor = { floorId: "ground", roomId: null }; + +test("a device in a room is in reach only while that room is open", () => { + assert.equal(inReach(lamp, { floorId: null, roomId: null }), false, "house view"); + assert.equal(inReach(lamp, { floorId: "ground", roomId: null }), false, "floor view"); + assert.equal(inReach(lamp, { floorId: "ground", roomId: "living" }), false, "another room"); + assert.equal(inReach(lamp, { floorId: "ground", roomId: "kitchen" }), true); +}); + +test("a device outside any room is in reach once its floor is open", () => { + assert.equal(inReach(hallSensor, { floorId: null, roomId: null }), false); + assert.equal(inReach(hallSensor, { floorId: "upstairs", roomId: null }), false); + assert.equal(inReach(hallSensor, { floorId: "ground", roomId: null }), true); + assert.equal(inReach(hallSensor, { floorId: "ground", roomId: "kitchen" }), true); +}); diff --git a/frontend/src/viewer/tap-reach.ts b/frontend/src/viewer/tap-reach.ts new file mode 100644 index 0000000..72a6b09 --- /dev/null +++ b/frontend/src/viewer/tap-reach.ts @@ -0,0 +1,12 @@ +// tap_in_room: which devices a tap may switch, by where they stand and what is opened. + +/** Where a device stands, or what is opened in the view (null: the whole house, or the whole floor). */ +export interface Place { + floorId: string | null; + roomId: string | null; +} + +/** A device in a room can be switched once that room is open; one outside any room once its floor is open. */ +export function inReach(device: Place, opened: Place): boolean { + return device.roomId ? device.roomId === opened.roomId : device.floorId === opened.floorId; +} diff --git a/frontend/src/viewer/theme.test.ts b/frontend/src/viewer/theme.test.ts new file mode 100644 index 0000000..1aa7a62 --- /dev/null +++ b/frontend/src/viewer/theme.test.ts @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { AdditiveBlending, MeshBasicMaterial, NormalBlending } from "three"; +import { lineBlending, parseAccent, themed, themeIndex } from "./theme.ts"; + +test("an accent colour is read from #rrggbb, with or without the hash, and nothing else", () => { + assert.deepEqual(parseAccent("#ff0000"), [1, 0, 0]); + assert.deepEqual(parseAccent("00ff00"), [0, 1, 0]); + const grey = parseAccent(" #808080 ")!; + assert.ok(grey.every((c) => Math.abs(c - 128 / 255) < 1e-9)); + for (const bad of ["#fff", "red", "#gg0000", "", null, undefined, "#1234567"]) assert.equal(parseAccent(bad as string), null, String(bad)); +}); + +test("looks have indexes in the order of the list, and the day look draws lines without glow", () => { + assert.equal(themeIndex("neon"), 0); + assert.equal(themeIndex("blueprint"), 1); + assert.equal(themeIndex("day"), 2); + assert.equal(lineBlending("neon"), AdditiveBlending); + assert.equal(lineBlending("blueprint"), AdditiveBlending); + assert.equal(lineBlending("day"), NormalBlending); +}); + +test("a themed material patches its shader and tells line and surface programs apart", () => { + const uniform = { value: 0 }; + const surface = themed(new MeshBasicMaterial(), uniform); + const line = themed(new MeshBasicMaterial(), uniform, true); + assert.notEqual(surface.customProgramCacheKey(), line.customProgramCacheKey()); + const shader = { uniforms: {} as Record, fragmentShader: "#include \nvoid main() {\n#include \n}" }; + line.onBeforeCompile(shader as never, undefined as never); + assert.equal(shader.uniforms.uTheme, uniform); + assert.ok(shader.fragmentShader.includes("nfThemed(diffuseColor.rgb, true)")); + assert.ok(shader.fragmentShader.includes("vec3 nfThemed")); + const shader2 = { uniforms: {} as Record, fragmentShader: shader.fragmentShader.replace("true", "false") }; + surface.onBeforeCompile(shader2 as never, undefined as never); + assert.ok(shader2.fragmentShader.includes("nfThemed(diffuseColor.rgb, false)")); +}); + +test("theming keeps an earlier patch of the same material", () => { + const material = new MeshBasicMaterial(); + let called = false; + material.onBeforeCompile = () => void (called = true); + themed(material, { value: 0 }); + material.onBeforeCompile({ uniforms: {}, fragmentShader: "" } as never, undefined as never); + assert.ok(called); +}); diff --git a/frontend/src/viewer/theme.ts b/frontend/src/viewer/theme.ts new file mode 100644 index 0000000..242f366 --- /dev/null +++ b/frontend/src/viewer/theme.ts @@ -0,0 +1,78 @@ +// The looks of the 3D view. Geometry keeps its neon colours; a small shader patch maps them to the chosen look, so switching is +// instant and nothing has to be rebuilt. Signal colours (lit lamps, open windows, glowing screens) are bright and saturated and +// stay as they are in every look. + +import { AdditiveBlending, NormalBlending, Vector3, type Material } from "three"; +import { THEMES, type Theme } from "../themes.ts"; + +export type { Theme } from "../themes.ts"; + +export interface ThemeUniform { + value: number; +} + +export const themeIndex = (theme: Theme): number => THEMES.indexOf(theme); + +/** The accent of the neon look (lines and cyan surfaces): the stock cyan, or a colour of the user's choice. */ +export const accentUniform = { value: new Vector3(0.22, 0.88, 1) }; +export const accentOnUniform = { value: 0 }; + +/** "#rrggbb" as the 0..1 colour the shader uses; null for anything else. */ +export function parseAccent(hex: string | null | undefined): [number, number, number] | null { + const match = /^#?([0-9a-f]{6})$/i.exec(hex?.trim() ?? ""); + if (!match) return null; + const value = Number.parseInt(match[1], 16); + return [((value >> 16) & 255) / 255, ((value >> 8) & 255) / 255, (value & 255) / 255]; +} + +// The fragment shader function that turns a neon colour into the current look. Look 0 is neon itself (only an own accent +// changes anything), 1 is blueprint, 2 is day. +const LOOK_FUNCTION = /* glsl */ ` +uniform int uTheme; +uniform vec3 uAccent; +uniform int uAccentOn; +vec3 nfThemed(vec3 c, bool isLine) { + float strongest = max(c.r, max(c.g, c.b)); + float weakest = min(c.r, min(c.g, c.b)); + float saturation = strongest > 0.0 ? (strongest - weakest) / strongest : 0.0; + if (uTheme == 0) { + // an own accent: every line and every cyan surface takes it, as bright as it was + bool cyanish = saturation > 0.35 && c.r < c.g * 0.8 && c.b > c.g * 0.85 && c.g > c.b * 0.6; + if (uAccentOn == 1 && (isLine || cyanish)) return uAccent * strongest; + return c; + } + // signal colours keep their colour + if (!isLine && strongest > 0.45 && saturation > 0.45) return c; + float luma = dot(c, vec3(0.299, 0.587, 0.114)); + if (uTheme == 1) { + // blueprint: pale lines on shades of blue + if (isLine) return vec3(0.8, 0.9, 1.0) * min(1.0, strongest * 1.15); + return mix(vec3(0.04, 0.13, 0.3), vec3(0.2, 0.42, 0.75), clamp(luma * 5.0, 0.0, 1.0)); + } + // day: light surfaces with a trace of their hue, dark blue lines + if (isLine) return vec3(0.08, 0.17, 0.38) * clamp(strongest * 1.4, 0.4, 1.0); + vec3 grey = vec3(clamp(0.66 + luma * 2.6, 0.0, 0.96)); + return mix(grey, grey * (c / max(strongest, 0.001)), 0.1); +} +`; + +/** + * Maps a material's colours to the look in `uniform` (0 neon, 1 blueprint, 2 day). Composes with an existing onBeforeCompile (the + * fold patch, say). With `line`, edges are mapped as lines. + */ +export function themed(material: T, uniform: ThemeUniform, line = false): T { + const previous = material.onBeforeCompile.bind(material); + const previousKey = material.customProgramCacheKey.bind(material); + material.onBeforeCompile = (shader, renderer) => { + previous(shader, renderer); + Object.assign(shader.uniforms, { uTheme: uniform, uAccent: accentUniform, uAccentOn: accentOnUniform }); + shader.fragmentShader = shader.fragmentShader + .replace("#include ", `#include \n${LOOK_FUNCTION}`) + .replace("#include ", `#include \n diffuseColor.rgb = nfThemed(diffuseColor.rgb, ${line});`); + }; + material.customProgramCacheKey = () => `${previousKey()}-themed-${line ? "l" : "s"}`; + return material; +} + +/** Additive glow vanishes on light backgrounds, so lines are drawn normally in the day look. */ +export const lineBlending = (theme: Theme): typeof AdditiveBlending | typeof NormalBlending => (theme === "day" ? NormalBlending : AdditiveBlending); diff --git a/frontend/src/viewer/viewer3d.ts b/frontend/src/viewer/viewer3d.ts new file mode 100644 index 0000000..c6d1910 --- /dev/null +++ b/frontend/src/viewer/viewer3d.ts @@ -0,0 +1,3885 @@ +// 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 +// (floors above fly up and fade out, floors below stay as a dim reference) and one room (camera +// flight into it). Each floor is a group with its own materials so its height and opacity can be +// animated independently. + +import { packModel, placement } from "./furniture/packs.ts"; +import { Builder } from "./furniture/builder.ts"; +import { advancePet, seededRandom, type PetMotion, type PetRoom } from "./pets.ts"; +import { isLowEnd } from "../hardware.ts"; +import { QualityGovernor } from "./quality-governor.ts"; +import { + AdditiveBlending, + Box3, + type Object3D, + CanvasTexture, + ClampToEdgeWrapping, + Color, + DoubleSide, + Group, + LineBasicMaterial, + LineSegments, + Mesh, + MeshBasicMaterial, + OrthographicCamera, + PerspectiveCamera, + Points, + PlaneGeometry, + Raycaster, + RepeatWrapping, + Scene, + SRGBColorSpace, + Float32BufferAttribute, + Uint32BufferAttribute, + DynamicDrawUsage, + BufferGeometry as Geometry, + Vector2, + Vector3, + Vector4, + WebGLRenderer, + WebGLRenderTarget, + type BufferGeometry, + type Material, +} from "three"; +import type { Building, Floor, PlanNote, Room, StartView } from "../model.ts"; +import { recolorLamps, SHADE_SENTINEL, shadeFactors } from "./lamp-colors.ts"; +import { CEILING_TYPES, ceilingOf, centroid, NOTE_Y, noteDue, furnitureFootprint, pointInPolygon, polygonArea, openingStyle, WALL_LAMP_Y } from "../model.ts"; +import { roofRider, roofUnderAt, sectionCutsBelow } from "../roof-sections.ts"; +import { centredAt, floorLabelPosition, floorShowsMarkers, floorShowsOutdoorMarkers, LabelPlacer, leftAt, project, stackFloorLabels, type FloorLabel, type ScreenPoint } from "./scene/labels.ts"; +import { easeFloor, fadeMaterials, floorShare, floorTarget } from "./scene/floor-motion.ts"; +import { atTarget, stepOpening, stepShare } from "./scene/opening-motion.ts"; +import { addFloorWedge, addLampHalo, addSpotCone, hiddenInCut, type HaloPoints } from "./scene/halos.ts"; +import { sunlightPatches, sunSignature } from "./scene/sunlight.ts"; +import { stripRiseLift } from "./scene/strip.ts"; +import { HouseShadow } from "./scene/house-shadow.ts"; +import { mergeHoles } from "../geometry/holes.ts"; +import type { Vec2 } from "../model.ts"; +import { LAMP_SIZE, HANGING_LAMPS } from "./scene/lamp-data.ts"; +import { lightSourcesOf } from "./scene/light-sources.ts"; +import { makeFloorMaterials, type FloorMaterials } from "./scene/materials.ts"; +import { createDevicePin, type PinHooks } from "./scene/pins.ts"; +import { buildStl, type StlPart } from "./export/stl.ts"; +import { SunArc } from "./scene/sun-arc.ts"; +import { buildFloorGeometry, SLAB, stairHoles, wallPaintOf, type FloorGeometry, type WallPaint } from "./build.ts"; +import { OrbitControls, type OrbitView } from "./controls.ts"; +import { type FoldMasks } from "./fold.ts"; +import { batteryBar, pictureRect, pushPackGlow, pushPackLamp, pushPackMoving, screenRect, pushFridgeDoors } from "./furniture.ts"; +import { coverReach, hasMesh, hasMovingParts, mountBase, packItem, setMeshSource, setPacks, type FurniturePack, type MeshSource } from "../packs.ts"; +import { withVehicles } from "../parking.ts"; +import { buildRoof, type RoofWindowState } from "./roof.ts"; +import { GROUND, groundFace, groundFloor, wallFaces } from "../solar.ts"; +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"; + +export type { Theme } from "./theme.ts"; +import { ALWAYS, DEG, GeoBuffer, LineBuffer, pushPrism } from "./geo.ts"; +import { buildLightSurface, lightColors, type LightSurface } from "./lighting.ts"; +import { animateGlow } from "../light-effects.ts"; +import { buildOpeningParts, CLOSED, type OpeningState } from "./openings.ts"; +import { WeatherLayer, type SkyView } from "./live-weather.ts"; +import { EnergyLayer, type EnergyArc, type PlanPoint, type SparkField } from "./live-energy.ts"; +import { SoundLayer, type SoundSpot } from "./live-sound.ts"; +import { WaterLayer, type SpraySpot } from "./live-water.ts"; +import { ScreenLayer, type LiveScreen } from "./live-screens.ts"; +import { PictureLayer, type LivePicture } from "./live-pictures.ts"; +import { addMeshLighting, applyEnvironment, disposeMeshInstance, instantiateMesh, loadMesh } from "./meshes.ts"; +import { circlePath, cleaningPath, stepRobot, type RobotInfo, type RobotMotion } from "./robot.ts"; +import { TRAIL_HOLD_MS, trailGeometry, trailOpacity } from "./robot-trail.ts"; +import { inReach } from "./tap-reach.ts"; +import type { AnimationName } from "../light-effects.ts"; + +export type { RobotInfo } from "./robot.ts"; +export { inspectModel, ModelError, prepareModel, previewModel, type ModelInfo, type PrepareOptions } from "./models/prepare.ts"; + +/** Colour of a robot's light by what it does. */ +const ROBOT_LED: Record = { cleaning: 0x37e0ff, returning: 0xffb547, docked: 0x41c46b, idle: 0x5b7cff, error: 0xff3b4f }; + +export type { OpeningState } from "./openings.ts"; + +export type Quality = "auto" | "low" | "high"; +export type WallMode = "auto" | "cut" | "slope"; + +export interface ViewerOptions { + quality?: Quality; + /** Pull floors apart in the house view (default true). */ + explode?: boolean; + onRoomTap?: (floorId: string, roomId: string | null) => void; + onFloorTap?: (floorId: string) => void; + onBack?: () => void; + /** Short tap on a device marker. */ + onDeviceTap?: (entityId: string, x: number, y: number) => void; + /** Double tap on a room of the opened floor (without it, a double tap goes one level back). */ + onRoomDoubleTap?: (floorId: string, roomId: string) => void; + /** Long press on a device marker. */ + onDeviceHold?: (entityId: string, x: number, y: number) => void; + /** + * Vertical swipe on a device (dim a lamp, move a blind): "start" returns whether the device takes + * it; "move" reports the distance from the start (pixels, down positive). + */ + onDeviceSwipe?: (entityId: string, phase: "start" | "move" | "end", dy: number, x: number, y: number) => boolean | void; + /** Furnishing in 3D: a device was selected (null: none) or dragged to a new place. */ + onDeviceSelect?: (entityId: string | null) => void; + onDeviceMove?: (entityId: string, x: number, z: number) => void; + /** Furnishing in 3D: an item was selected (null: none) or dragged to a new place. */ + onFurnitureSelect?: (furnitureId: string | null) => void; + onFurnitureMove?: (furnitureId: string, x: number, z: number) => void; + onStats?: (stats: ViewerStats) => void; + /** Text for the floor labels in the house view, e.g. "5 rooms". */ + floorInfo?: (floor: Floor) => string; +} + +/** A device shown in the 3D view (prepared by the main bundle from placements and states). */ +export interface DeviceMarker { + /** entity_id */ + id: string; + /** A small label under the pin (the device's own name, #156); empty = none. */ + caption?: string; + /** The device's own name from the plan (the card option marker_names shows it as caption). */ + ownName?: string; + /** The own name is shown under the pin (per device). */ + showName?: boolean; + floorId: string; + roomId: string | null; + x: number; + z: number; + /** Height above the floor. */ + y: number; + /** Inline SVG markup of the icon. */ + icon: string; + name: string; + /** Short state text, e.g. "60 %" or "21,5 °C". */ + text: string; + active: boolean; + /** The text shows on the floor as well (a marker set to "always"); otherwise only in its room or while active. */ + full?: boolean; + unavailable: boolean; + /** Light cone on the floor for lights that are on. */ + glow: { color: [number, number, number]; level: number } | null; + /** Power drawn (W) when the device reports it. */ + power?: number | null; + /** Lights: lamp model drawn at the device position. */ + lamp?: LampModel | null; + /** Lamp: turn around y (degrees), size (w, d, h) and height of what it stands on. */ + /** A mirrored lamp furniture (its pack model is drawn mirrored). */ + mirror?: boolean; + rotation?: number; + size?: [number, number, number]; + base?: number; + /** LED strip: roll about its length (degrees) and standing upright (its length runs up from the base). */ + roll?: number; + upright?: boolean; + /** LED strip: how steeply its length rises (degrees). */ + rise?: number; + /** Show the HTML marker (false: the 3D object alone stands for the device). */ + pin?: boolean; + /** A placed device fixed against moving. */ + fixed?: boolean; + /** The marker setting of its placement or furniture item (undefined = automatic). */ + show?: "always" | "active" | "no_power" | "never"; + /** The 3D lamp can be tapped (it has an entity). */ + pickable?: boolean; + /** Furniture item this lamp is (for moving it in 3D). */ + furnitureId?: string; + /** Lamp from a furniture pack (its type): drawn from the pack's parts. */ + pack?: string | null; + /** Height its light comes from (pack lamps). */ + lightY?: number; + /** Hanging lamps and fans: the ceiling they hang from (null = the floor height). */ + ceiling?: number; + /** Ceiling fan: turns of its blades per second (0 or unset = standing still). */ + spin?: number; + /** A colour effect runs (colour loop …): the colour is animated in 3D. */ + effect?: AnimationName; + /** Pendant shape: shade (default), globe, cone or drum. */ + variant?: string | null; + /** Formatted power, e.g. "85 W". */ + powerText?: string; + /** A plugin's shape on the floor from the device (a camera's field of view): stops at walls; `through` lets taps pass. */ + wedge?: { angle: number; reach: number; near: number; color: [number, number, number]; opacity: number; through: boolean; walls?: boolean } | null; +} + +export type FloorStack = "dim" | "stacked" | "single"; + + +export type LampModel = "ceiling" | "downlight" | "spot" | "panel" | "pendant" | "fan" | "floor" | "uplight" | "table" | "wall" | "strip" | "bollard" | "garden"; + +/** A ray from the camera through the pointer, in building coordinates (heights above the ground). */ +export interface SurfaceRay { + o: [number, number, number]; + d: [number, number, number]; +} + +/** Grab and move things on surfaces with rays: start says whether something was grabbed. */ +export interface SurfaceGrab { + start(ray: SurfaceRay): boolean; + move(ray: SurfaceRay): void; + end(): void; +} + + +/** A lit TV or monitor screen: colour (the light of a lit item) and brightness (0..1). */ + +export interface ScreenState { + color: [number, number, number]; + level: number; + /** Strength of the glow frame around the screen: 1 is the usual, 0 draws none (the item's own *Glow behind the TV*). */ + halo?: number; + /** Furniture with a state: glowing faces on top of the item instead of a screen – the whole top, or a half of it. */ + faces?: { part: "all" | "left" | "right" | "top" | "bottom"; color: [number, number, number]; level: number }[]; + /** Light switches and sockets: the buttons (gangs) that are on glow in their colour. */ + gangs?: { gang: number; color: [number, number, number]; level: number }[]; + /** A heater from a pack without a screen part (a towel radiator): the whole item glows in the colour while it heats. */ + heat?: boolean; + /** An electric pack item that runs (a coffee machine, a compressor): its status lights and display light up. */ + leds?: boolean; + /** A home battery: its charge (0…1) fills the bar on its front. */ + fill?: number; + /** A 3D printer: how far the print has grown (0…1) on its bed, in the colour. */ + print?: number; +} + +/** Position of the sun (from sun.sun): degrees above the horizon and clockwise from north. */ +export interface SunState { + elevation: number; + azimuth: number; +} + +export type { SkyView, SkyWeather } from "./live-weather.ts"; +export type { EnergyArc, PlanPoint, SparkField } from "./live-energy.ts"; +export type { SoundSpot } from "./live-sound.ts"; + +/** A frame's photo: the viewer finds the frame's picture part itself. */ +export interface LivePictureInput { + furnitureId: string; + floorId: string; + url: string; + border: number; + fit: "cover" | "contain"; +} + +/** What a TV shows (NextFloor TV screens): the viewer finds the screen of the furniture itself. */ +export type LiveScreenInput = Omit & { furnitureId: string }; + +/** Called after every frame for each card anchor: where it is on screen (CSS pixels) and whether it shows. */ +export type LiveAnchorCallback = (index: number, x: number, y: number, visible: boolean) => void; + +export interface PersonPin { + id: string; + name: string; + initials: string; + picture: string | null; + floorId: string; + roomId: string; + x: number; + z: number; +} + +export interface ViewerStats { + /** Frames per second while something moves; 0 at rest (nothing is drawn then). */ + fps: number; + /** What keeps the picture moving: camera, floors, openings, flash, roof, flow, effect, robot, orbit, tint. */ + busy: string[]; + /** Slowest frame of the last measuring window (ms). */ + worstMs: number; + calls: number; + triangles: number; + /** The low quality level is active (tablet). */ + low: boolean; + pixelRatio: number; +} + +/** How far the roof lifts off the top floor while the floors are pulled apart. */ +const ROOF_GAP = 1.4; +/** Grid cells across the ground texture. */ +const GROUND_CELLS = 32; +const LAMP_BODY = 0x2a3a60; +/** Fan blades: a little lighter than the lamp bodies, so they read against the motor. */ +const FAN_BLADE = 0x4a5c88; +const LAMP_SHADE = 0x1d2946; +/** Lamps that hang from the ceiling (hidden in the cut view). */ +const FLASH_MS = 450; +const EFFECT_MS = 125; +/** Eye height above the floor while walking (metres). */ +const EYE_HEIGHT = 1.6; +/** On the tablet level, decorations (colour effects, rain, robots, the energy flow) come to rest this long after the last touch or change. */ +const REST_AFTER_MS = 30000; +/** A ceiling fan's blades and the angle between them. */ +const FAN_BLADES = 5; +const FAN_SPACING = 360 / FAN_BLADES; + + +interface FloorView { + floor: Floor; + /** Position in the stack, ordered by elevation. */ + rank: number; + group: Group; + geo: FloorGeometry; + floorMesh: Mesh; + shadowMesh: Mesh; + patternMesh: Mesh; + /** Room lighting on floors and wall faces (see lighting.ts). */ + glowMesh: Mesh; + lightSurface: LightSurface | null; + /** Light zone per room index (rooms joined by "no wall" share one); null when every room is its own. */ + lightZones: number[] | null; + framesMesh: Mesh; + glassMesh: Mesh; + blindsMesh: Mesh; + lampMesh: Mesh; + /** Sunlight falling through the windows onto the floor. */ + sunMesh: Mesh; + sunSig: string; + /** Soft glow around lit lamps, and light cones under spots (quality "High"). */ + haloMesh: Points; + coneMesh: Mesh; + /** Triangle ranges of the wedges plugins draw on the floor, by device id (a tap on one taps the device). */ + wedgeTris: { id: string; start: number; end: number }[]; + /** Motion trail on the floor (discs and ribbons). */ + /** Doors of smart fridges (they swing open with their sensors). */ + fridgeMesh: Mesh; + /** Triangle ranges of lamps (entity ids), furniture walls mesh and openings, for tapping. */ + lampTris: { id: string; start: number; end: number }[]; + /** The same lamp ranges, keyed by furniture id (for moving lamps). */ + lampFurnTris: { id: string; start: number; end: number }[]; + frameTris: { id: string; start: number; end: number }[]; + glassTris: { id: string; start: number; end: number }[]; + blindTris: { id: string; start: number; end: number }[]; + wallMesh: Mesh; + screenMesh: Mesh; + screenSig: string; + /** Klang: rings around playing speakers and lines between grouped ones (made when first needed). */ + soundGroup?: Group; + /** Pictures shown on lit screens, by furniture id. */ + /** Content signatures: meshes are only rebuilt when these change. */ + flowLayout: string; + glowSig: string; + /** Lamp shapes (rebuilt when they change) and lamp colours (written into the mesh in place). */ + lampShapeSig: string; + lampColorSig: string; + /** Shade factor per lamp vertex (0 = body) and the triangle range of every lamp, by device id. */ + lampShade: Float32Array; + lampRanges: Map; + /** Room box and room labels with their centres, so labels are placed without recomputing them. */ + bbox: { x0: number; x1: number; z0: number; z1: number } | null; + roomPins: { pin: HTMLButtonElement; room: Room; cx: number; cz: number }[]; + /** The floor's notes as pins; a tap opens the whole text. */ + notePins: { pin: HTMLButtonElement; note: PlanNote }[]; + /** Size of the floor label, measured once per text (reading it every frame forces a layout). */ + labelSize: { w: number; h: number } | null; + materials: FloorMaterials; + /** Bit masks of the wall buckets that stand and that are drawn as glass (read by the fold shader). */ + mask: FoldMasks; + /** Shown opening states (animated towards the targets set from Home Assistant). */ + openings: Map; + /** Current and target height offset and opacity. */ + y: number; + o: number; + ty: number; + to: number; + appliedO: number; + label: HTMLButtonElement; +} + +const ACTIVE_FLOOR = new Color(0x1a2a4d); + +/** The roof's opacity at rest in the house view: a touch see-through, so what lies under it can be guessed. */ +const ROOF_REST = 0.94; + +export { isLowEnd }; + +export class NextFloorViewer { + private readonly host: HTMLElement; + private readonly options: ViewerOptions; + private renderer: WebGLRenderer; + private readonly scene = new Scene(); + private readonly camera = new PerspectiveCamera(38, 1, 0.1, 400); + private controls: OrbitControls; + private readonly labels: HTMLDivElement; + private readonly root = new Group(); + private readonly patternTexture: CanvasTexture; + private readonly blindTexture: CanvasTexture; + private openingTargets = new Map(); + /** Smart fridge doors: how far each stands open (0…1) and where it is going. */ + private fridges = new Map(); + /** Pack items with moving parts (curtains, roller screens, awnings, gates): how far out they are now and where they are going. */ + private covers = new Map(); + private screens = new Map(); + /** Entities behind furniture (TV, …) and openings (blind, contact), for tapping them in 3D. */ + private pickFurniture = new Map(); + private pickOpenings = new Map(); + /** The second blind of an opening (the right half of a wide one). */ + private pickOpenings2 = new Map(); + /** Lamps flashing after a tap (entity id -> end time). */ + private flashes = new Map(); + /** Editor: things on surfaces (solar fields, roof windows) are grabbed and moved with a ray from the camera. */ + private surfaceGrab: SurfaceGrab | null = null; + private surfaceDragging = false; + /** Furnishing limited to these furniture types (the editor's energy tool); null = all. */ + private furnishTypes: ReadonlySet | null = null; + /** Live state of the roof windows (the roof is rebuilt when it changes). */ + private roofWindows = new Map(); + private roofWindowsKey = ""; + private persons: PersonPin[] = []; + private readonly personPins = new Map(); + private floorInfo = new Map(); + /** Text behind the room names (the "values" heat mode: temperature, humidity, CO₂ per room). */ + private roomInfo = new Map(); + /** Ground grid texture, made when the ground first shows (the tablet level never shows it). */ + private groundTexture: CanvasTexture | null = null; + private devices: DeviceMarker[] = []; + /** Device markers with the last written fields, so unchanged fields are not written again. */ + private readonly devicePins = new Map(); + private readonly ground: Mesh; + private floors: FloorView[] = []; + private building: Building | null = null; + private furnitureColors: FurnitureColors | null = null; + /** Turns a note's photo ("image:" or a URL) into what an shows; null while a stored picture is still loading. */ + private notePhoto: ((photo: string) => string | null) | null = null; + private floorId: string | null = null; + private roomId: string | null = null; + private wallMode: WallMode = "auto"; + /** Solid painted walls: no glass, every wall in its paint (see setPaintedWalls). */ + private painted = false; + private explode: boolean; + private frame = 0; + private lastFrame = 0; + /** The quality chosen (auto, low, high); auto may still step down by itself. */ + private qualityMode: Quality = "auto"; + /** Watches the frame times in auto quality and asks for fewer pixels or the simple look (null: not auto, or already low). */ + private governor: QualityGovernor | null = null; + private disposed = false; + private readonly resizeObserver: ResizeObserver; + private fpsFrames = 0; + private worstFrame = 0; + private lastStatsFrame = 0; + private lowQuality = false; + private highQuality = false; + /** Seconds used for animated colour effects (advanced in steps while an effect runs). */ + private effectTime = 0; + /** The frame was asked for by the effect timer or a room tint (shown in the statistics). */ + private effectTick = false; + private tintTick = false; + private effectTimer: ReturnType | undefined; + /** Until when decorations keep moving on the tablet level (a touch or a visible change wakes them). */ + private awakeUntil = 0; + /** What the devices looked like at the last change (on/off and colour), to tell a real change from a new sensor value. */ + private deviceLook = ""; + private readonly haloTexture: CanvasTexture; + /** Roof over the top floor (house view only), its opacity and the camera distance of the house view. */ + /** The roof: one group with a part per floor it sits on (each part follows its floor). */ + private roof: { group: Group; parts: { group: Group; floorId: string; rideId: string; base: number; lift: boolean }[]; solid: MeshBasicMaterial; lines: LineBasicMaterial; glass: MeshBasicMaterial } | null = null; + private roofO = 0; + /** The roof stays put while the camera comes close (no lift, no fade): the editor's roof tool, or a choice of the viewer. */ + private keepRoof = false; + /** Robot vacuums: their info from Home Assistant, how they move, and their meshes. */ + private robots = new Map(); + /** Pets roaming their rooms: their motion, the room they keep to, and the group that carries their model. */ + private pets = new Map number; group: Group; floorId: string }>(); + private petMat: MeshBasicMaterial | null = null; + private petTimer: ReturnType | undefined; + private robotGeo: BufferGeometry | null = null; + /** The pad each robot has driven, by robot id: the ribbon of its own map's trail. */ + private readonly robotTrails = new Map(); + /** The timer that next changes how strong a pad shows (it fades out after the clean). */ + private readonly trailTimers = new Map>(); + private robotMat: MeshBasicMaterial | null = null; + private mowerMat: MeshBasicMaterial | null = null; + private robotLedGeo: BufferGeometry | null = null; + private robotLast = 0; + private petLast = 0; + /** Owned 3D models standing in the floors (see meshes.ts), and the light they need. */ + private meshes: { group: Group; furnitureId: string }[] = []; + private meshLight: ReturnType | null = null; + private meshAsked = new Set(); + private robotTimer: ReturnType | undefined; + private floorStack: FloorStack = "dim"; + /** Floors by id, and per-frame bookkeeping so labels are only placed when something moved. */ + private floorMap = new Map(); + private labelsDirty = true; + private readonly viewKey = new Float64Array(6); + private readonly pinMode = new WeakMap(); + private size = { w: 1, h: 1 }; + /** Width taken on the left by the host (the floor pictures); floor labels keep clear of it. */ + private labelInset = 0; + /** Floors with lamps that run a colour effect, and the floor of every device (for flashes). */ + private effectFloors = new Set(); + private deviceFloor = new Map(); + private statsOn = false; + /** Vehicles standing in parking spots (spot id -> pack item type); they join the floor geometry. */ + private parked = new Map(); + private parkedSig = ""; + /** Only the floor plan: the furniture is left out of the build (stairs and the like stay). */ + private plain = false; + /** A short right click goes back one step. */ + private rightBack = false; + private rightDown: { x: number; y: number; at: number } | null = null; + /** Gate id → open (from the entities that drive the gates); a change rebuilds the floors. */ + private gateOpen = new Map(); + private gateSig = ""; + /** Slow automatic turn of the view (kiosk screensaver), in radians per second. */ + private orbitSpeed = 0; + private orbitLast = 0; + private orbitTimer: ReturnType | undefined; + /** The host is inside the viewport (a card scrolled away renders nothing). */ + private onScreen = true; + private intersection: IntersectionObserver | null = null; + /** The device a running swipe acts on. */ + private swipe: { entity: string; x: number; y: number } | null = null; + /** Furnishing in 3D: items can be dragged; the selected one shows a wireframe box. */ + private furnish = false; + private selectedFurniture: string | null = null; + /** Furnishing: the selected device, the pin a pointer just went down on, and a device being dragged. */ + private selectedDevice: string | null = null; + private pendingDevice: string | null = null; + private readonly labelPlacer = new LabelPlacer(); + /** What the device pins ask of this viewer. */ + private readonly pinHooks: PinHooks = { + furnishing: () => this.furnish, + pressedWhileFurnishing: (id) => (this.pendingDevice = id), + selectWhileFurnishing: (id) => { + this.selectDevice(id); + this.options.onDeviceSelect?.(id); + }, + centre: (pin) => { + const [box, area] = [pin.getBoundingClientRect(), this.host.getBoundingClientRect()]; + return { x: box.left + box.width / 2 - area.left, y: box.top + box.height / 2 - area.top }; + }, + tap: (id, x, y) => { + // away from the opened room a marker opens its floor or room (tap_in_room) + const d = this.tapInRoom ? this.devices.find((m) => m.id === id) : undefined; + if (d && !this.deviceInReach(d.floorId, d.roomId)) return this.options.onRoomTap?.(d.floorId, d.roomId); + this.options.onDeviceTap?.(id, x, y); + }, + hold: (id, x, y) => this.options.onDeviceHold?.(id, x, y), + }; + /** A tap switches devices only in the opened room (outside any room: once their floor is open). */ + private tapInRoom = false; + private deviceGrab: { id: string; floorId: string; offset: [number, number]; x: number; z: number; moved: boolean } | null = null; + private grab: { floorId: string; id: string; offset: [number, number]; x: number; z: number; moved: boolean } | null = null; + private ghost: LineSegments | null = null; + private theme: Theme = "neon"; + private readonly themeUniform: ThemeUniform = { value: 0 }; + private sun: SunState | null = null; + /** The sky over the plot: rain, snow, clouds, fog, lightning, sun and moon (live-weather.ts). */ + private readonly weatherLayer: WeatherLayer; + /** The house's shadow on the ground, and what it was last built from. */ + private readonly houseShadow = new HouseShadow(); + private readonly sunArc = new SunArc(); + private sunArcLocation: { latitude: number; longitude: number; zone?: string | null } | null = null; + private shadowKey = ""; + /** The merged footprint of the floors above ground, kept until the rooms change (merging is the costly part). */ + private footprint: { key: string; rings: Vec2[][] } = { key: "", rings: [] }; + /** The real map under the plan (live-map.ts). */ + private readonly mapLayer: MapLayer; + private mapSettings: MapSettings | null = null; + private mapNorth = 0; + private groundY = 0; + private skyView: SkyView | null = null; + private weatherTimer: ReturnType | undefined; + /** Power flowing between the devices, sparkling solar modules (live-energy.ts). */ + private readonly energyLayer: EnergyLayer; + /** Sound rings around playing speakers and multiroom threads (live-sound.ts). */ + private readonly soundLayer: SoundLayer; + private readonly waterLayer: WaterLayer; + /** How opaque the glass walls are, shared by every floor's materials (0.2: faint glass). */ + private readonly glassAlpha = { value: 0.2 }; + /** Pictures on TVs that play, with an ambilight behind (live-screens.ts). */ + private readonly screenLayer: ScreenLayer; + /** Own photos in picture frames (live-pictures.ts). */ + private readonly pictureLayer: PictureLayer; + /** NextFloor's floating cards: their points in the plan and who is told where they are on screen. */ + private liveAnchors: PlanPoint[] = []; + private liveAnchorCb: LiveAnchorCallback | null = null; + /** Heatmap colour per room id (null: normal floors). */ + private roomTint: Map | null = null; + private houseRadius = 20; + private startView: StartView | null = null; + private fpsStart = 0; + + constructor(host: HTMLElement, options: ViewerOptions = {}) { + this.host = host; + this.options = options; + this.explode = options.explode ?? true; + this.qualityMode = options.quality ?? "auto"; + this.renderer = this.makeRenderer(this.qualityMode); + this.labels = document.createElement("div"); + this.labels.className = "nf-labels"; + host.append(this.labels); + this.patternTexture = makePatternTexture(); + this.blindTexture = makeBlindTexture(); + this.haloTexture = makeHaloTexture(); + this.ground = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ transparent: true, blending: AdditiveBlending, depthWrite: false })); + this.ground.rotation.x = -Math.PI / 2; + this.ground.renderOrder = -1; + this.scene.add(this.ground, this.root); + this.weatherLayer = new WeatherLayer(this.scene); + this.scene.add(this.houseShadow.mesh); + this.scene.add(this.sunArc.group); + this.mapLayer = new MapLayer(this.scene); + this.mapLayer.onChange = () => this.invalidate(); + this.energyLayer = new EnergyLayer(this.scene, this.liftOf); + this.soundLayer = new SoundLayer(this.scene, this.liftOf); + this.waterLayer = new WaterLayer(this.scene, this.liftOf); + this.screenLayer = new ScreenLayer(this.scene, this.liftOf); + this.screenLayer.onChange = () => this.invalidate(); + this.pictureLayer = new PictureLayer(this.scene, this.liftOf); + this.pictureLayer.onChange = () => this.invalidate(); + this.weatherLayer.onFlash = (on) => this.host.classList.toggle("live-flash", on); + this.controls = this.makeControls(); + this.resizeObserver = new ResizeObserver(() => this.resize()); + this.resizeObserver.observe(host); + document.addEventListener("visibilitychange", this.onVisibility); + // any touch on the view (canvas, pins, labels) wakes resting decorations + this.host.addEventListener("pointerdown", this.onTouch, { passive: true }); + this.renderer.domElement.addEventListener("pointerdown", this.onRightDown); + this.renderer.domElement.addEventListener("pointerup", this.onRightUp); + this.renderer.domElement.addEventListener("contextmenu", this.onContext); + this.awakeUntil = performance.now() + REST_AFTER_MS; + if (typeof IntersectionObserver === "function") { + this.intersection = new IntersectionObserver((entries) => { + const on = entries.some((e) => e.isIntersecting); + if (on === this.onScreen) return; + this.onScreen = on; + if (!on) { + clearTimeout(this.effectTimer); + this.effectTimer = undefined; + } + if (on) this.invalidate(); + }); + this.intersection.observe(host); + } + this.resize(); + } + + /** Whether the tablet level is active (hosts lighten their own work with it). */ + get low(): boolean { + return this.lowQuality; + } + + /** A short right click (no drag) goes back one step, like a double tap on empty space; off by default. */ + setRightBack(on: boolean): void { + this.rightBack = on; + } + + private readonly onRightDown = (e: PointerEvent) => { + this.rightDown = this.rightBack && e.button === 2 ? { x: e.clientX, y: e.clientY, at: performance.now() } : null; + }; + + private readonly onRightUp = (e: PointerEvent) => { + const down = this.rightDown; + this.rightDown = null; + if (!this.rightBack || !down || e.button !== 2) return; + if (Math.hypot(e.clientX - down.x, e.clientY - down.y) < 6 && performance.now() - down.at < 400) this.options.onBack?.(); + }; + + private readonly onContext = (e: Event) => { + if (this.rightBack) e.preventDefault(); + }; + + /** Only the floor plan: no furniture in 3D (stairs, stairwells and pieces that cut holes stay); a change rebuilds the floors. */ + setPlain(on: boolean): void { + if (on === this.plain) return; + this.plain = on; + if (this.building) { + this.rebuild(); + this.invalidate(); + } + } + + /** The house as a binary STL (walls, floors, furniture and outdoor areas of every floor), for printing; `scale` 10 is 1:100 in millimetres. */ + exportStl(scale = 10): Uint8Array { + const parts: StlPart[] = []; + for (const fv of this.floors) { + for (const mesh of [fv.wallMesh, fv.floorMesh]) { + const position = mesh.geometry.getAttribute("position"); + if (position) parts.push({ positions: position.array, lift: fv.floor.elevation }); + } + } + return buildStl(parts, scale); + } + + /** Which gates of the fences are open (gate id → open); a change rebuilds the floors. */ + setGateStates(states: Map): void { + const sig = [...states] + .map(([id, v]) => `${id}=${v ? 1 : 0}`) + .sort() + .join("|"); + if (sig === this.gateSig) return; + this.gateSig = sig; + this.gateOpen = states; + if (this.building) { + this.rebuild(); + this.invalidate(); + } + } + + /** Vehicles in the parking spots (spot id -> pack item type); a change rebuilds the floors. */ + setParked(parked: Map): void { + const sig = [...parked] + .map(([id, v]) => `${id}=${v}`) + .sort() + .join("|"); + if (sig === this.parkedSig) return; + this.parkedSig = sig; + this.parked = parked; + if (this.building) { + this.rebuild(); + this.invalidate(); + } + } + + /** Frame statistics are only gathered while something shows them. */ + setStats(on: boolean): void { + this.statsOn = on; + } + + /** Space on the left the floor labels leave free (the floor pictures of the host). */ + setLabelInset(px: number): void { + if (this.labelInset === px) return; + this.labelInset = px; + this.labelsDirty = true; + this.invalidate(); + } + + /** Turn the view slowly by itself (0 stops); a touch pauses it. */ + setAutoOrbit(speed: number): void { + this.orbitSpeed = speed; + this.orbitLast = 0; + this.invalidate(); + } + + setQuality(quality: Quality): void { + this.qualityMode = quality; + this.swapRenderer(quality); + } + + /** Auto quality found the tablet too slow even at one pixel per point: the simple look, while the choice stays "auto". */ + private dropToLow(): void { + if (this.disposed || this.lowQuality) return; + this.swapRenderer("low"); + } + + private swapRenderer(quality: Quality): void { + const canvas = this.renderer.domElement; + const next = this.makeRenderer(quality); + this.rebuildTier(); + this.applyTierFlags(); + canvas.replaceWith(next.domElement); + this.renderer.dispose(); + this.renderer.forceContextLoss(); + this.renderer = next; + const { view, locked } = this.controls; + this.controls.dispose(); + this.controls = this.makeControls(); + this.controls.view = view; + this.controls.locked = locked; + this.resize(); + } + + /** Furniture packs (models of pack furniture); set before the building that uses them. */ + /** Where owned 3D models come from (the host knows Home Assistant's login). */ + setMeshSource(source: MeshSource | null): void { + setMeshSource(source); + } + + setPacks(packs: FurniturePack[]): void { + setPacks(packs); + if (this.building) { + this.rebuild(); + this.invalidate(); + } + } + + setBuilding(building: Building): void { + const first = this.building === null; + this.building = building; + this.rebuild(); + if (first) this.fit(0); + this.invalidate(); + } + + /** Walking through the house at eye level (null: orbiting as usual). */ + get walking(): boolean { + return this.controls.walk !== null; + } + + /** + * Starts walking on the open floor (else the ground floor), in the open room (else the largest), at eye height, looking the way the + * camera looked. Walls stand whole while walking. Returns the floor it walks on. + */ + startWalk(): string | null { + const floors = this.floors.filter((fv) => fv.floor.rooms.some((r) => r.points.length >= 3)); + const fv = (this.floorId ? this.floorMap.get(this.floorId) : undefined) ?? [...floors].sort((a, b) => Math.abs(a.floor.elevation) - Math.abs(b.floor.elevation))[0]; + if (!fv || !fv.bbox) return null; + const rooms = fv.floor.rooms.filter((r) => r.points.length >= 3); + const room = rooms.find((r) => r.id === this.roomId) ?? [...rooms].sort((a, b) => polygonArea(b.points) - polygonArea(a.points))[0]; + const [x, z] = room ? centroid(room.points) : [(fv.bbox.x0 + fv.bbox.x1) / 2, (fv.bbox.z0 + fv.bbox.z1) / 2]; + if (this.floorId !== fv.floor.id) this.setFloor(fv.floor.id, false); + const margin = 0.3; + this.controls.walk = { + eye: new Vector3(x, fv.floor.elevation + fv.ty + EYE_HEIGHT, z), + yaw: this.controls.view.theta, + pitch: -0.05, + stick: [0, 0], + keys: new Set(), + bounds: { x0: fv.bbox.x0 - margin, x1: fv.bbox.x1 + margin, z0: fv.bbox.z0 - margin, z1: fv.bbox.z1 + margin }, + last: 0, + }; + this.labelsDirty = true; + this.wake(); + return fv.floor.id; + } + + stopWalk(): void { + if (!this.controls.walk) return; + this.controls.walk = null; + this.labelsDirty = true; + this.fit(700); + } + + /** The touch stick while walking: x turns, y walks (-1 … 1; up is negative like the screen). */ + setWalkStick(x: number, y: number): void { + if (!this.controls.walk) return; + this.controls.walk.stick = [x, y]; + this.wake(); + } + + /** Show one floor (null = the whole house). */ + setFloor(floorId: string | null, animate = true): void { + // from one floor to another the camera may keep its side, height and distance (a tablet set up to look one way) + const keep = this.keepCamera && this.floorId !== null && floorId !== null && floorId !== this.floorId ? { theta: this.controls.view.theta, phi: this.controls.view.phi, radius: this.controls.view.radius } : null; + this.floorId = floorId; + this.roomId = null; + this.labelsDirty = true; + this.applyTargets(!animate); + this.applyHighlight(); + this.fit(animate ? 700 : 0, keep); + } + + /** Switching floors keeps the camera's side, height and distance instead of fitting the new floor from the start view's side. */ + setKeepCamera(on: boolean): void { + this.keepCamera = on; + } + + /** How much closer the fitted views come (1 = fitted, 2 = twice as close): small tablets see the house larger. */ + setZoom(zoom: number): void { + const z = Math.min(3, Math.max(0.5, zoom || 1)); + if (z === this.zoom) return; + this.zoom = z; + if (this.building) this.fit(400); + } + + /** Pull the floors apart in the house view, or stack them. */ + /** What shows below an opened floor: the floors dimmed, the whole house up to it, or nothing. */ + setFloorStack(mode: FloorStack): void { + if (mode === this.floorStack) return; + this.floorStack = mode; + this.applyTargets(false); + } + + setKeepRoof(on: boolean): void { + if (on === this.keepRoof) return; + this.keepRoof = on; + this.invalidate(); + } + + setExplode(explode: boolean): void { + if (explode === this.explode) return; + this.explode = explode; + this.applyTargets(false); + if (this.floorId === null) this.fit(700); + } + + /** Highlight a room and fly into it (null = back to the floor overview). */ + selectRoom(roomId: string | null): void { + this.roomId = roomId; + this.labelsDirty = true; + this.applyHighlight(); + if (!roomId) { + this.fit(700); + return; + } + const fv = this.floors.find((f) => f.floor.rooms.some((r) => r.id === roomId)); + const room = fv?.floor.rooms.find((r) => r.id === roomId); + if (!fv || !room) return; + // a room may open with a camera of its own (#282) + const own = room.start_view; + if (own) { + const base = fv.floor.elevation + fv.ty; + const [mx, mz] = centroid(room.points); + const t = own.target ?? { x: mx, y: 0.3, z: mz }; + this.controls.flyTo({ target: new Vector3(t.x, t.y + base, t.z), radius: own.radius, phi: own.phi, theta: own.theta }); + return; + } + const [cx, cz] = centroid(room.points); + const xs = room.points.map((p) => p[0]); + const zs = room.points.map((p) => p[1]); + const size = new Vector3(Math.max(...xs) - Math.min(...xs), fv.floor.cut_height, Math.max(...zs) - Math.min(...zs)); + this.controls.flyTo({ target: new Vector3(cx, fv.floor.elevation + fv.ty + 0.3, cz), radius: Math.max(4, this.distanceFor(size) * 1.05), phi: 0.72 }); + } + + /** Walls lowered in this mode (cut flat, or sloped): ceiling lamps and the roof would float above them. */ + private get lowered(): boolean { + return this.wallMode !== "auto"; + } + + /** Solid walls painted in the building's colours (outside, inside, per room) instead of the look's walls and glass. */ + setPaintedWalls(on: boolean): void { + if (on === this.painted) return; + this.painted = on; + this.rebuild(); + this.invalidate(); + } + + /** The paint one floor's walls get in the solid view (see `wallPaintOf`). */ + private wallPaint(floor: Floor): WallPaint | undefined { + return this.painted && this.building ? wallPaintOf(this.building.settings, floor) : undefined; + } + + setWallMode(mode: WallMode): void { + this.wallMode = mode; + // ceiling lamps would float above cut walls + for (const fv of this.floors) this.buildLamps(fv); + this.invalidate(); + } + + /** Replace the device markers; pins are reused per entity, light cones rebuilt per floor. */ + setDevices(devices: DeviceMarker[]): void { + // a light switched or a device that started or stopped wakes resting decorations; a sensor value does not + const look = devices.map((d) => `${d.id}:${d.active ? 1 : 0}:${d.glow ? d.glow.level.toFixed(1) : "-"}`).join(";"); + if (look !== this.deviceLook) { + this.deviceLook = look; + this.wake(); + } + this.devices = devices; + this.labelsDirty = true; + // colour effects and turning fans are drawn in steps by the shared effect timer + this.effectFloors = new Set(devices.filter((d) => (d.effect && d.glow) || (d.spin ?? 0) > 0).map((d) => d.floorId)); + this.deviceFloor = new Map(devices.map((d) => [d.id, d.floorId])); + const seen = new Set(); + for (const d of devices) { + seen.add(d.id); + let pin = this.devicePins.get(d.id); + if (!pin) { + pin = { el: createDevicePin(d.id, this.pinHooks), icon: "", text: "", watt: "", label: "", active: false, unavailable: false, glow: "", caption: "" }; + this.devicePins.set(d.id, pin); + this.labels.append(pin.el); + } + // every write below invalidates style or layout: only fields that changed are written + const el = pin.el; + if (pin.icon !== d.icon) { + pin.icon = d.icon; + el.querySelector(".nf-dev-icon")!.innerHTML = d.icon; + } + if (pin.text !== d.text) { + pin.text = d.text; + el.querySelector(".nf-dev-text")!.textContent = d.text; + } + const caption = d.caption ?? ""; + if (pin.caption !== caption) { + pin.caption = caption; + el.querySelector(".nf-dev-name")!.textContent = caption; + } + const watt = d.power !== null && d.power !== undefined && d.power >= 1 ? (d.powerText ?? `${Math.round(d.power)} W`) : ""; + if (pin.watt !== watt) { + pin.watt = watt; + el.querySelector(".nf-dev-watt")!.textContent = watt; + } + const label = `${d.name}: ${d.text}`; + if (pin.label !== label) { + pin.label = label; + el.title = d.name; + el.setAttribute("aria-label", label); + } + if (pin.active !== d.active) { + pin.active = d.active; + el.classList.toggle("nf-dev-on", d.active); + } + if (pin.unavailable !== d.unavailable) { + pin.unavailable = d.unavailable; + el.classList.toggle("nf-dev-na", d.unavailable); + } + const glow = d.glow ? `rgb(${d.glow.color.map((c) => Math.round(c * 255)).join(", ")})` : ""; + if (pin.glow !== glow) { + pin.glow = glow; + if (glow) el.style.setProperty("--nf-glow", glow); + else el.style.removeProperty("--nf-glow"); + } + } + for (const [id, pin] of this.devicePins) { + if (seen.has(id)) continue; + pin.el.remove(); + this.devicePins.delete(id); + } + for (const fv of this.floors) { + this.buildGlow(fv); + this.buildLamps(fv); + } + this.invalidate(); + } + + /** Roof windows open, tilted or with the blind down: the roof is rebuilt when that changes. */ + setRoofWindows(states: Map): void { + const key = JSON.stringify([...states]); + if (key === this.roofWindowsKey) return; + this.roofWindowsKey = key; + this.roofWindows = states; + this.buildRoofMesh(); + this.invalidate(); + } + + /** People in their rooms (pink markers in the floor and room views). */ + setPersons(persons: PersonPin[]): void { + this.labelsDirty = true; + this.persons = persons; + const seen = new Set(); + for (const p of persons) { + seen.add(p.id); + let pin = this.personPins.get(p.id); + if (!pin) { + pin = document.createElement("div"); + pin.className = "nf-person"; + pin.dataset.entity = p.id; + this.personPins.set(p.id, pin); + this.labels.append(pin); + } + pin.title = p.name; + pin.setAttribute("aria-label", p.name); + if (pin.dataset.picture !== (p.picture ?? "") || pin.dataset.initials !== p.initials) { + pin.dataset.picture = p.picture ?? ""; + pin.dataset.initials = p.initials; + pin.replaceChildren(); + if (p.picture) { + const img = document.createElement("img"); + img.src = p.picture; + img.alt = ""; + img.addEventListener("error", () => img.replaceWith(document.createTextNode(p.initials))); + pin.append(img); + } else pin.textContent = p.initials; + } + } + for (const [id, pin] of this.personPins) { + if (seen.has(id)) continue; + pin.remove(); + this.personPins.delete(id); + } + this.invalidate(); + } + + /** The 3D lock of a wall tablet: no turning, panning or zooming by hand (flights to rooms and taps still work). */ + setNavigationLocked(on: boolean): void { + this.controls.locked = on; + } + + /** Entities opened by tapping furniture or openings in 3D (by furniture / opening id). */ + setPickTargets(furniture: Map, openings: Map, second = new Map()): void { + this.pickFurniture = furniture; + this.pickOpenings = openings; + this.pickOpenings2 = second; + } + + /** Look of the 3D view: neon, blueprint or day. Instant: colours are mapped in the shaders. */ + /** An accent colour of the user's choice for the neon look ("#rrggbb"), null for the stock cyan. */ + setNotePhotos(resolve: ((photo: string) => string | null) | null): void { + this.notePhoto = resolve; + } + + /** Furniture colours of this view (the card's own), on top of the house-wide ones in the settings (#82). */ + setFurnitureColors(colors: FurnitureColors | null): void { + if (JSON.stringify(colors ?? {}) === JSON.stringify(this.furnitureColors ?? {})) return; + this.furnitureColors = colors; + if (this.building) { + this.rebuild(); + this.invalidate(); + } + } + + setAccent(hex: string | null): void { + const rgb = parseAccent(hex); + const on = rgb ? 1 : 0; + if (on === accentOnUniform.value && (!rgb || accentUniform.value.equals(new Vector3(...rgb)))) return; + accentOnUniform.value = on; + if (rgb) accentUniform.value.set(...rgb); + this.invalidate(); + } + + setTheme(theme: Theme): void { + if (theme === this.theme) return; + this.theme = theme; + this.placeMap(); + this.themeUniform.value = themeIndex(theme); + const blending = lineBlending(theme); + const lineMats = [...this.floors.map((f) => f.materials.lines), ...(this.roof ? [this.roof.lines] : [])]; + for (const m of lineMats) { + m.blending = blending; + m.needsUpdate = true; + } + // the neon ground grid would vanish on the light background anyway + this.placeGround(); + this.invalidate(); + } + + /** Furnishing mode: dragging furniture and lamps moves them instead of turning the view. */ + setFurnishMode(on: boolean): void { + this.furnish = on; + if (!on) this.selectFurniture(null); + this.invalidate(); + } + + /** Select a furniture item (wireframe box), or none. */ + selectFurniture(id: string | null): void { + if (id && this.selectedDevice) this.selectDevice(null); + this.selectedFurniture = id; + this.updateGhost(); + this.invalidate(); + } + + /** Position of the sun; sunlight falls through windows facing it. */ + setSun(sun: SunState | null): void { + this.sun = sun; + for (const fv of this.floors) this.buildSun(fv); + this.buildHouseShadow(); + this.buildSunArc(); + this.invalidate(); + } + + /** Where the home is on the globe (for the sun's arc); null while it is not known. */ + setLocation(location: { latitude: number; longitude: number; zone?: string | null } | null): void { + this.sunArcLocation = location; + this.buildSunArc(); + this.invalidate(); + } + + /** The ring, compass letters and today's arc of the sun round the plot (building setting `sun_arc`, default off). */ + private buildSunArc(): void { + const b = this.building; + const loc = this.sunArcLocation; + const rooms = (b?.floors ?? []).flatMap((f) => [...f.rooms.flatMap((r) => r.points), ...(f.outdoor ?? []).flatMap((o) => o.points)]); + if (!b || !b.settings.sun_arc || !loc || !rooms.length) return void this.sunArc.update(null, null, 0); + const xs = rooms.map((p) => p[0]); + const zs = rooms.map((p) => p[1]); + const centre: [number, number] = [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...zs) + Math.max(...zs)) / 2]; + const radius = Math.max(6, Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...zs) - Math.min(...zs)) / 2 + 3); + const ground = Math.min(0, ...b.floors.map((f) => f.elevation)); + this.sunArc.update({ centre, radius, north: b.settings.north ?? 0, ...loc }, this.sun, ground); + } + + /** + * The house's shadow on the ground: the footprint of the floors above ground, swept away from the sun by the height of the house. + * Off with the sun patches and on the tablet level. + * A known simplification: the whole footprint sweeps by the full height of the house, so a one-storey garage beside a + * two-storey house throws a two-storey shadow. + */ + private buildHouseShadow(): void { + if (!this.houseShadow) return; + const b = this.building; + const above = (b?.floors ?? []).filter((f) => f.elevation >= -0.01 && f.rooms.length); + const off = !b || !above.length || b.settings.sun_patches === false || this.lowQuality; + const cloud = this.weatherLayer?.cloud ?? 0; + const north = b?.settings.north ?? 0; + const plan = above.map((f) => `${f.elevation}:${f.height}:${JSON.stringify(f.rooms.map((r) => r.points))}`).join("|"); + const key = off ? "off" : `${this.sun?.elevation.toFixed(1)},${this.sun?.azimuth.toFixed(1)},${north},${cloud.toFixed(2)},${plan}`; + if (key === this.shadowKey) return; + this.shadowKey = key; + if (off) { + this.houseShadow.update([], 0, 0, null, 0, 0, true); + return; + } + const ground = Math.min(...above.map((f) => f.elevation)); + const top = Math.max(...above.map((f) => f.elevation + f.height)); + if (this.footprint.key !== plan) this.footprint = { key: plan, rings: mergeHoles(above.flatMap((f) => f.rooms.map((r) => r.points))) }; + this.houseShadow.update(this.footprint.rings, top - ground, ground + 0.03, this.sun, north, cloud, false); + } + + /** Where a floor stands right now (for NextFloor's layers): its height, how far it is pulled apart, whether it shows. */ + private readonly liftOf = (floorId: string | null): { y: number; dy: number; visible: boolean } => { + if (!floorId) return { y: 0, dy: 0, visible: true }; + const fv = this.floorMap.get(floorId); + return fv ? { y: fv.floor.elevation + fv.y, dy: fv.y, visible: fv.group.visible } : { y: 0, dy: 0, visible: false }; + }; + + /** Power arcs between the devices and the sparkling solar modules (empty lists: nothing). */ + setLiveEnergy(arcs: EnergyArc[], sparks: SparkField[]): void { + this.energyLayer.setArcs(arcs); + this.energyLayer.setSparks(sparks); + this.invalidate(); + } + + /** Speakers that play (rings) and the speakers that play together (threads). */ + setLiveSound(spots: SoundSpot[], groups: [PlanPoint, PlanPoint][]): void { + this.soundLayer.set(spots, groups); + this.invalidate(); + } + + /** How opaque the see-through walls are: 0 … 1 (0.2 is the usual faint glass). */ + setGlassWalls(alpha: number): void { + const value = Math.min(1, Math.max(0, alpha)); + if (value === this.glassAlpha.value) return; + this.glassAlpha.value = value; + this.invalidate(); + } + + /** Lawn sprinklers that water now: droplets in arcs around each one. */ + setLiveWater(spots: SpraySpot[]): void { + this.waterLayer.set(spots); + this.invalidate(); + } + + /** TVs and monitors that play: their picture and the ambilight behind them. */ + setLiveScreens(list: LiveScreenInput[]): void { + const out: LiveScreen[] = []; + for (const s of list) { + const floor = this.building?.floors.find((f) => f.id === s.floorId); + const f = floor?.furniture.find((m) => m.id === s.furnitureId); + const rect = f && floor ? screenRect(f, floor) : null; + if (!f || !rect) continue; + out.push({ ...s, x: f.x, z: f.z, rotation: f.rotation, rect }); + } + this.screenLayer.set(out); + this.invalidate(); + } + + /** Own photos in picture frames: the viewer finds the frame's picture part itself. */ + setPictures(list: LivePictureInput[]): void { + const out: LivePicture[] = []; + for (const p of list) { + const floor = this.building?.floors.find((f) => f.id === p.floorId); + const f = floor?.furniture.find((m) => m.id === p.furnitureId); + const rect = f && floor ? pictureRect(f, floor) : null; + if (!f || !rect) continue; + out.push({ id: p.furnitureId, floorId: p.floorId, url: p.url, border: p.border, fit: p.fit, x: f.x, z: f.z, rotation: f.rotation, rect }); + } + this.pictureLayer.set(out); + this.invalidate(); + } + + /** Points in the plan the host floats cards over; the callback learns their screen position after every frame. */ + setLiveAnchors(points: PlanPoint[], cb: LiveAnchorCallback | null): void { + this.liveAnchors = points; + this.liveAnchorCb = cb; + this.invalidate(); + } + + private placeLhAnchors(): void { + const cb = this.liveAnchorCb; + if (!cb || !this.liveAnchors.length) return; + const v = new Vector3(); + this.liveAnchors.forEach((p, i) => { + const l = this.liftOf(p.floorId); + v.set(p.x, l.y + p.y, p.z).project(this.camera); + const visible = l.visible && v.z < 1 && Math.abs(v.x) < 1.15 && Math.abs(v.y) < 1.15; + cb(i, ((v.x + 1) / 2) * this.size.w, ((1 - v.y) / 2) * this.size.h, visible); + }); + } + + /** The sky over the plot (null = no weather layer): see live-weather.ts. */ + setSky(view: SkyView | null): void { + this.skyView = view; + this.weatherLayer.set(view ? { ...view, low: view.low || this.lowQuality } : null); + this.buildHouseShadow(); + for (const fv of this.floors) this.buildSun(fv); + this.invalidate(); + } + + /** Heatmap: floor colour per room id, or null for the normal look. */ + setRoomTint(tint: Map | null): void { + const changed = !!tint !== !!this.roomTint; + this.roomTint = tint; + this.tintTick = true; + this.applyHighlight(); + if (changed) { + for (const fv of this.floors) { + fv.glowSig = ""; + this.buildGlow(fv); + } + } + } + + /** Screens of TVs and monitors that are on (by furniture id). */ + setScreens(screens: Map): void { + this.screens = screens; + for (const fv of this.floors) this.buildScreens(fv); + this.invalidate(); + } + + /** The room name, with a line of values below it when there is one. */ + private fillRoomPin(pin: HTMLElement, name: string, info: string | undefined): void { + pin.textContent = name || "–"; + if (info) { + const small = document.createElement("small"); + small.textContent = info; + pin.append(small); + pin.classList.add("nf-pin-info"); + } else pin.classList.remove("nf-pin-info"); + } + + /** Values behind the room names (the "values" heat mode); an empty map clears them. */ + setRoomInfo(info: Map): void { + const same = info.size === this.roomInfo.size && [...info].every(([k, v]) => this.roomInfo.get(k) === v); + if (same) return; + this.roomInfo = info; + for (const fv of this.floors) for (const rp of fv.roomPins) this.fillRoomPin(rp.pin, rp.room.name, info.get(rp.room.id)); + } + + /** Text under the floor names in the house view, e.g. "5 rooms · 3 lights on · 1 open". */ + setFloorInfo(info: Map): void { + this.floorInfo = info; + for (const fv of this.floors) { + const span = fv.label.querySelector("span"); + const text = info.get(fv.floor.id) ?? this.options.floorInfo?.(fv.floor) ?? ""; + if (span && span.textContent !== text) { + span.textContent = text; + fv.labelSize = null; + this.labelsDirty = true; + } + } + this.invalidate(); + } + + /** Target states of doors and windows (sashes and blinds move there smoothly). */ + setOpeningStates(states: Map): void { + const before = this.openingTargets; + this.openingTargets = states; + if ([...states].some(([id, s]) => !atTarget(before.get(id) ?? CLOSED, s))) this.wake(); + this.invalidate(); + } + + /** Something happened: decorations move again (for the rest time on the tablet level). */ + wake(): void { + this.awakeUntil = performance.now() + REST_AFTER_MS; + this.invalidate(); + } + + /** The tablet level has seen nothing happen for a while: decorations stand still until the next touch or change. */ + private get resting(): boolean { + return this.lowQuality && performance.now() > this.awakeUntil; + } + + /** Which doors of the smart fridges stand open; the doors swing there over a few frames. */ + setFridgeDoors(doors: Map): void { + for (const [id, d] of doors) { + const st = this.fridges.get(id) ?? { l: d.left ? 1 : 0, r: d.right ? 1 : 0, tl: 0, tr: 0 }; + st.tl = d.left ? 1 : 0; + st.tr = d.right ? 1 : 0; + this.fridges.set(id, st); + } + for (const id of [...this.fridges.keys()]) if (!doors.has(id)) this.fridges.delete(id); + this.invalidate(); + } + + /** How far the moving parts of pack items should be out (0 … 1, by furniture id); they travel there over a few seconds. */ + setCovers(reach: Map): void { + let changed = false; + for (const [id, t] of reach) { + const st = this.covers.get(id); + if (!st) { + // a cover seen for the first time starts where it is, without travelling there + this.covers.set(id, { k: t, t }); + changed = true; + } else if (st.t !== t) { + st.t = t; + changed = true; + } + } + for (const id of [...this.covers.keys()]) if (!reach.has(id)) this.covers.delete(id); + if (changed) { + for (const fv of this.floors) this.buildFridges(fv); + this.wake(); + } + } + + private stepCovers(dt: number): boolean { + // a slow, even travel like a motor: the whole way in about four seconds + const step = Math.min(1, dt / 4000); + let moving = false; + for (const st of this.covers.values()) { + if (st.k === st.t) continue; + const d = st.t - st.k; + st.k = Math.abs(d) <= step ? st.t : st.k + Math.sign(d) * step; + moving = true; + } + if (moving) for (const fv of this.floors) this.buildFridges(fv); + return moving; + } + + private stepFridges(dt: number): boolean { + const k = stepShare(dt); + const touched = new Set(); + for (const [id, st] of this.fridges) { + for (const [cur, to] of [["l", "tl"], ["r", "tr"]] as const) { + const d = st[to] - st[cur]; + if (Math.abs(d) < 0.004) { + if (d !== 0) { + st[cur] = st[to]; + touched.add(id); + } + continue; + } + st[cur] += d * k; + touched.add(id); + } + } + if (!touched.size) return false; + for (const fv of this.floors) if (fv.floor.furniture.some((f) => touched.has(f.id))) this.buildFridges(fv); + return true; + } + + private buildFridges(fv: FloorView): void { + const buf = new GeoBuffer(); + for (const f of fv.floor.furniture) { + const item = packItem(f.type); + if (item && hasMovingParts(item)) { + pushPackMoving(buf, item, f, mountBase(fv.floor, f), this.covers.get(f.id)?.k ?? coverReach(item, null)); + continue; + } + if (f.type !== "fridge_smart") continue; + const st = this.fridges.get(f.id); + pushFridgeDoors(buf, f, mountBase(fv.floor, f), st?.l ?? 0, st?.r ?? 0); + } + fv.fridgeMesh.geometry.dispose(); + fv.fridgeMesh.geometry = buf.geometry(); + fv.fridgeMesh.visible = buf.count > 0; + } + + resetView(): void { + this.fit(700); + } + + /** The camera the house view opens with (null: fitted from the front left). */ + setStartView(view: StartView | null): void { + this.startView = view; + } + + /** + * The camera as it stands: angles, distance and the point it looks at – with a floor opened, that + * point's height counts from the floor (it opens there however the floors are stacked). + */ + currentView(): StartView { + const v = this.controls.view; + const base = this.floorBase(this.floorId); + return { theta: v.theta, phi: v.phi, radius: v.radius, target: { x: v.target.x, y: v.target.y - base, z: v.target.z } }; + } + + /** Height of a floor as it is shown now (0 for the house view). */ + private floorBase(floorId: string | null): number { + const fv = floorId === null ? undefined : this.floorMap.get(floorId); + return fv ? fv.floor.elevation + fv.ty : 0; + } + + dispose(): void { + this.disposed = true; + cancelAnimationFrame(this.frame); + clearTimeout(this.effectTimer); + clearTimeout(this.robotTimer); + clearTimeout(this.orbitTimer); + clearTimeout(this.weatherTimer); + this.weatherLayer.dispose(); + this.sunArc?.dispose(); + this.houseShadow?.dispose(); + this.mapLayer.dispose(); + this.energyLayer.dispose(); + this.soundLayer.dispose(); + this.waterLayer.dispose(); + this.screenLayer.dispose(); + this.pictureLayer.dispose(); + this.resizeObserver.disconnect(); + this.intersection?.disconnect(); + document.removeEventListener("visibilitychange", this.onVisibility); + this.host?.removeEventListener("pointerdown", this.onTouch); + this.renderer?.domElement?.removeEventListener?.("pointerdown", this.onRightDown); + this.renderer?.domElement?.removeEventListener?.("pointerup", this.onRightUp); + this.renderer?.domElement?.removeEventListener?.("contextmenu", this.onContext); + clearTimeout(this.petTimer); + this.controls.dispose(); + this.clear(); + this.building = null; + this.buildRoofMesh(); + this.ground.geometry.dispose(); + (this.ground.material as Material).dispose(); + this.patternTexture.dispose(); + this.blindTexture.dispose(); + this.groundTexture?.dispose(); + this.haloTexture.dispose(); + for (const r of this.robots.values()) r.led.dispose(); + this.robots.clear(); + for (const trail of this.robotTrails.values()) { + trail.removeFromParent(); + trail.geometry.dispose(); + (trail.material as Material).dispose(); + } + this.robotTrails.clear(); + for (const timer of this.trailTimers.values()) clearTimeout(timer); + this.trailTimers.clear(); + this.robotGeo?.dispose(); + this.robotLedGeo?.dispose(); + this.robotMat?.dispose(); + this.mowerMat?.dispose(); + this.meshLight?.dispose(); + this.renderer.dispose(); + // frees the GPU context now instead of when the garbage collector gets to it + this.renderer.forceContextLoss(); + this.renderer.domElement.remove(); + this.labels.remove(); + } + + invalidate(): void { + if (this.frame || this.disposed || document.hidden || !this.onScreen) return; + this.frame = requestAnimationFrame((t) => this.render(t)); + } + + // ------------------------------------------------------------------ internals + + private makeRenderer(quality: Quality): WebGLRenderer { + const low = quality === "low" || (quality === "auto" && isLowEnd()); + this.lowQuality = low; + // (the weather layer does not exist yet while the first renderer is made) + if (this.weatherLayer && this.skyView) this.weatherLayer.set({ ...this.skyView, low: this.skyView.low || low }); + if (this.weatherLayer) this.buildHouseShadow(); + this.highQuality = quality === "high"; + const renderer = new WebGLRenderer({ antialias: !low, alpha: true, powerPreference: low ? "low-power" : "default" }); + const ratio = Math.min(window.devicePixelRatio || 1, low ? 1 : quality === "high" ? 2.5 : 2); + renderer.setPixelRatio(ratio); + this.governor = quality === "auto" && !low ? new QualityGovernor(ratio, Math.min(1, ratio)) : null; + renderer.setClearColor(0x000000, 0); + renderer.outputColorSpace = SRGBColorSpace; + renderer.domElement.className = "nf-canvas"; + this.host.prepend(renderer.domElement); + return renderer; + } + + private makeControls(): OrbitControls { + return new OrbitControls(this.renderer.domElement, this.camera, { + change: () => this.wake(), + tap: (x, y) => this.onTap(x, y), + hold: (x, y) => this.onHold(x, y), + swipeStart: (x, y, dx, dy) => this.swipeStart(x, y, dx, dy), + swipeMove: (dy) => this.swipe && this.options.onDeviceSwipe?.(this.swipe.entity, "move", dy, this.swipe.x, this.swipe.y), + swipeEnd: () => { + if (this.swipe) this.options.onDeviceSwipe?.(this.swipe.entity, "end", 0, this.swipe.x, this.swipe.y); + this.swipe = null; + }, + grab: (x, y) => this.grabFurniture(x, y), + drag: (x, y) => this.dragFurniture(x, y), + drop: () => this.dropFurniture(), + doubleTap: (x, y) => { + const hit = this.floorId && this.options.onRoomDoubleTap ? this.pick(x, y) : null; + if (hit && !("entity" in hit) && hit.roomId) this.options.onRoomDoubleTap!(hit.floorId, hit.roomId); + else this.options.onBack?.(); + }, + }); + } + + private readonly onTouch = () => this.wake(); + + private readonly onVisibility = () => { + if (document.hidden) { + clearTimeout(this.effectTimer); + this.effectTimer = undefined; + } + if (!document.hidden) this.invalidate(); + }; + + /** One shared timer, independent of the number of animated lamps. */ + private scheduleEffects(): void { + if (!this.hasVisibleEffects(document.hidden) || this.resting) { + clearTimeout(this.effectTimer); + this.effectTimer = undefined; + return; + } + if (this.effectTimer !== undefined) return; + const ms = this.lowQuality ? 2 * EFFECT_MS : EFFECT_MS; + this.effectTimer = setTimeout(() => { + this.effectTimer = undefined; + if (!this.hasVisibleEffects(document.hidden)) return; + this.effectTime = performance.now() / 1000; + this.effectTick = true; + for (const fv of this.floors) { + if (fv.o < 0.02 || !this.effectFloors.has(fv.floor.id)) continue; + this.buildLamps(fv); + this.buildGlow(fv); + } + this.invalidate(); + }, ms); + } + + private hasVisibleEffects(hidden: boolean): boolean { + return !hidden && !this.disposed && this.onScreen && this.floors.some((fv) => fv.o >= 0.02 && this.effectFloors.has(fv.floor.id)); + } + + private resize(): void { + const w = this.host.clientWidth || 1; + const h = this.host.clientHeight || 1; + this.size = { w, h }; + this.labelsDirty = true; + this.renderer.setSize(w, h, false); + this.camera.aspect = w / h; + this.camera.updateProjectionMatrix(); + this.invalidate(); + } + + private clear(): void { + // robots share one geometry: keep them out of the floor groups while those are disposed + for (const r of this.robots.values()) r.group.removeFromParent(); + // owned models are shared: only their own materials go + for (const m of this.meshes) { + m.group.removeFromParent(); + disposeMeshInstance(m.group); + } + this.meshes = []; + for (const fv of this.floors) { + fv.group.traverse((o) => { + const g = (o as Mesh).geometry as BufferGeometry | undefined; + g?.dispose(); + }); + for (const m of Object.values(fv.materials)) if (!Array.isArray(m)) m.dispose(); + for (const g of fv.materials.ghosts) g.material.dispose(); + this.root.remove(fv.group); + } + this.floors = []; + this.floorMap = new Map(); + // device pins survive a rebuild; only floor and room labels are recreated + for (const el of [...this.labels.children]) if (!(el as HTMLElement).dataset.entity) el.remove(); + } + + /** Light cones of the lights that are on, merged into one mesh per floor. */ + /** Light surface of a floor (rebuilt with the floor plan and when the detail level changes). */ + private buildLightSurface(fv: FloorView): void { + const cell = this.lowQuality ? 0.5 : 0.25; + const surface = buildLightSurface(fv.floor, fv.geo.walls2d, fv.geo.wallBuckets, fv.geo.openings, cell, fv.geo.holes, fv.geo.roofUnder); + // rooms joined by "no wall" form one zone: a lamp lights the open neighbour as if it stood in the same room + const zones = lightZonesOf(fv.floor, fv.geo.openRooms); + fv.lightZones = zones.some((z, i) => z !== i) ? zones : null; + if (fv.lightZones) { + for (let i = 0; i < surface.room.length; i++) { + const r = surface.room[i]; + if (r >= 0 && r < zones.length) surface.room[i] = zones[r]; + } + for (const door of surface.doors) { + if (door.a >= 0 && door.a < zones.length) door.a = zones[door.a]; + if (door.b >= 0 && door.b < zones.length) door.b = zones[door.b]; + } + } + fv.lightSurface = surface; + const g = new Geometry(); + g.setAttribute("position", new Float32BufferAttribute(surface.pos, 3)); + g.setAttribute("color", new Float32BufferAttribute(new Float32Array(surface.pos.length), 3)); + g.setAttribute("fold", new Float32BufferAttribute(surface.fold, 1)); + // the index lists the lit quads; it is filled in place (a new index every change would leak) + const index = new Uint32BufferAttribute(new Uint32Array(surface.pos.length / 3), 1); + index.setUsage(DynamicDrawUsage); + g.setIndex(index); + g.setDrawRange(0, 0); + g.computeBoundingSphere(); + fv.glowMesh.geometry.dispose(); + fv.glowMesh.geometry = g; + fv.glowSig = ""; + this.buildGlow(fv); + } + + /** Colours of the light surface for the current lights and doors. */ + private buildGlow(fv: FloorView): void { + const surface = fv.lightSurface; + if (!surface) return; + const sources = lightSourcesOf(fv.floor, fv.lightZones, this.devices, (d) => this.glowOf(d)); + const doorOpen = surface.doors.map((d) => { + const info = fv.geo.openings.find((i) => i.opening.id === d.id); + if (info && openingStyle(info.opening, info.exterior) === "passage") return 1; + const o = fv.openings.get(d.id); + return o ? Math.max(o.open, o.open2 ?? 0) : 0.5; + }); + const sig = + sources.map((l) => `${l.x.toFixed(2)},${l.y.toFixed(2)},${l.z.toFixed(2)},${l.kind},${l.level.toFixed(3)},${l.color.map((c) => c.toFixed(3)).join("/")}`).join(";") + + "|" + + doorOpen.map((o) => o.toFixed(1)).join(","); + if (sig === fv.glowSig) return; + fv.glowSig = sig; + const g = fv.glowMesh.geometry; + const attr = g.getAttribute("color") as Float32BufferAttribute; + if (!sources.length) { + fv.glowMesh.visible = false; + g.setDrawRange(0, 0); + return; + } + const colors = lightColors(surface, sources, 0.42, doorOpen); + if (this.roomTint) { + // the heatmap is an analysis view: inside the rooms the light is only a hint, so their colours read; + // outside (garden, outer walls) it stays as it is (D205) + const outside = fv.floor.rooms.length; + for (let v = 0; v < surface.room.length; v++) { + if (surface.room[v] === outside) continue; + for (let k = 0; k < 3; k++) colors[v * 3 + k] *= 0.12; + } + } + (attr.array as Float32Array).set(colors); + attr.needsUpdate = true; + // only quads that receive light are drawn (dark ones would cost fill rate for nothing) + const index = g.index!.array as Uint32Array; + let n = 0; + for (let q = 0; q < colors.length / 18; q++) { + let lit = false; + for (let k = q * 18; k < q * 18 + 18 && !lit; k++) lit = colors[k] > 0.004; + if (lit) for (let v = 0; v < 6; v++) index[n++] = q * 6 + v; + } + g.index!.needsUpdate = true; + g.setDrawRange(0, n); + fv.glowMesh.visible = n > 0; + } + + /** The floor without its furniture in the plain view; what builds the floor itself (stairs, stairwells, hole makers) stays. */ + private withoutFurniture(floor: Floor): Floor { + if (this.gateOpen.size && (floor.outdoor ?? []).some((a) => a.gates?.length)) { + // the gates' states go into the build as a copy; the plan itself never holds them + floor = { ...floor, outdoor: floor.outdoor.map((a) => (a.gates?.length ? { ...a, gates: a.gates.map((g) => ({ ...g, open: this.gateOpen.get(g.id) ?? false })) } : a)) }; + } + if (!this.plain) return floor; + const keep = (f: Floor["furniture"][number]) => f.type === "stairs" || f.type === "stairwell" || !!packItem(f.type)?.hole; + return { ...floor, furniture: floor.furniture.filter(keep) }; + } + + private rebuild(): void { + const previous = new Map(this.floors.map((f) => [f.floor.id, { y: f.y, o: f.o }])); + const previousOpenings = new Map(this.floors.map((f) => [f.floor.id, f.openings])); + this.clear(); + const b = this.building; + if (!b) return; + applyFurnitureColors({ ...b.settings.furniture_colors, ...this.furnitureColors }); + const ordered = [...b.floors].sort((p, q) => p.elevation - q.elevation); + for (const floor of b.floors) { + // solar fields in the garden stand on the ground floor, wall fields hang on their floor's walls + const fields = b.settings.roof?.solar ?? []; + const garden = groundFloor(b)?.id === floor.id ? fields.filter((f) => f.face === GROUND).map((field) => ({ field, face: groundFace(b, field) })) : []; + const onWalls = fields.filter((f) => f.face.startsWith(`wall:${floor.id}:`)); + if (onWalls.length) { + const walls = new Map(wallFaces(b, floor.id).map((w) => [w.key, w])); + for (const field of onWalls) { + const face = walls.get(field.face); + if (face) garden.push({ field, face }); + } + } + // an attic floor: its walls end under the roof sections above it + // every floor whose ceiling lies above a section's base is cut by the slopes – the attic, and the + // floor below it when the slope already starts there (a roof that reaches down past the ceiling) + const sloped = (b.settings.roof.sections ?? []).some((s) => sectionCutsBelow(s, floor.elevation + floor.height)); + const roofUnder = sloped + ? (x: number, z: number) => { + const y = roofUnderAt(b, x, z); + return y === null ? null : y - floor.elevation; + } + : undefined; + const geo = buildFloorGeometry(this.withoutFurniture(withVehicles(floor, this.parked)), b.settings.wall_exterior, b.settings.wall_interior, stairHoles(b.floors, floor), garden, roofUnder, this.wallPaint(floor)); + const mask: FoldMasks = { standing: { value: 0xffff }, glass: { value: 0 }, slope: { value: new Vector4() }, slopeY: { value: new Vector2() }, glassAlpha: this.glassAlpha }; + const materials = makeFloorMaterials({ mask, look: this.themeUniform, theme: this.theme, textures: { pattern: this.patternTexture, blinds: this.blindTexture, halo: this.haloTexture } }); + const group = new Group(); + const floorMesh = new Mesh(geo.floor, materials.floor); + const shadowMesh = new Mesh(geo.shadow, materials.shadow); + shadowMesh.renderOrder = 1; + const pattern = new Mesh(geo.floor, materials.pattern); + pattern.renderOrder = 2; + const glowMesh = new Mesh(new Geometry(), materials.glow); + glowMesh.renderOrder = 3; + glowMesh.visible = false; + const framesMesh = new Mesh(new Geometry(), materials.frames); + const blindsMesh = new Mesh(new Geometry(), materials.blinds); + const glassMesh = new Mesh(new Geometry(), materials.glass); + glassMesh.renderOrder = 4; + const lampMesh = new Mesh(new Geometry(), materials.lamps); + lampMesh.visible = false; + const sunMesh = new Mesh(new Geometry(), materials.cones); + sunMesh.visible = false; + sunMesh.renderOrder = 3; + const haloMesh = new Points(new Geometry(), materials.halos); + haloMesh.visible = false; + haloMesh.renderOrder = 7; + const coneMesh = new Mesh(new Geometry(), materials.cones); + coneMesh.visible = false; + coneMesh.renderOrder = 7; + const fridgeMesh = new Mesh(new Geometry(), materials.lamps); + fridgeMesh.visible = false; + const screenMesh = new Mesh(new Geometry(), materials.screens); + screenMesh.visible = false; + screenMesh.renderOrder = 5; + // the fold shader moves hidden parts, so the bounding spheres must not cull them early + for (const m of [framesMesh, blindsMesh, glassMesh]) m.frustumCulled = false; + // glass walls are drawn after everything opaque in the room, so doors and furniture show through + const glassWalls = new Mesh(geo.walls, materials.glassWall); + const wallMesh = new Mesh(geo.walls, materials.wall); + glassWalls.renderOrder = 6; + group.add( + floorMesh, + shadowMesh, + pattern, + glowMesh, + wallMesh, + new LineSegments(geo.lines, materials.lines), + framesMesh, + blindsMesh, + glassMesh, + lampMesh, + sunMesh, + haloMesh, + coneMesh, + fridgeMesh, + screenMesh, + glassWalls, + ); + // 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); + materials.ghosts.push({ material, base: ghost.opacity }); + const mesh = new Mesh(ghost.geometry, material); + mesh.renderOrder = 2; + group.add(mesh); + } + this.root.add(group); + + const label = document.createElement("button"); + label.className = "nf-pin nf-pin-floor"; + label.dataset.floor = floor.id; + const name = document.createElement("b"); + name.textContent = floor.name || "–"; + const info = document.createElement("span"); + info.textContent = this.floorInfo.get(floor.id) ?? this.options.floorInfo?.(floor) ?? ""; + label.append(name, info); + label.addEventListener("click", () => this.options.onFloorTap?.(floor.id)); + this.labels.append(label); + + const prev = previous.get(floor.id); + const roomPins: FloorView["roomPins"] = []; + let bbox: FloorView["bbox"] = null; + for (const room of floor.rooms) { + const pin = document.createElement("button"); + pin.className = "nf-pin"; + pin.dataset.room = room.id; + pin.dataset.floor = floor.id; + this.fillRoomPin(pin, room.name, this.roomInfo.get(room.id)); + pin.addEventListener("click", () => this.options.onRoomTap?.(floor.id, room.id)); + this.labels.append(pin); + const [cx, cz] = centroid(room.points); + roomPins.push({ pin, room, cx, cz }); + for (const [x, z] of room.points) { + bbox ??= { x0: x, x1: x, z0: z, z1: z }; + bbox.x0 = Math.min(bbox.x0, x); + bbox.x1 = Math.max(bbox.x1, x); + bbox.z0 = Math.min(bbox.z0, z); + bbox.z1 = Math.max(bbox.z1, z); + } + } + const notePins: FloorView["notePins"] = []; + for (const note of floor.notes ?? []) { + if (!note.text) continue; + const pin = document.createElement("button"); + pin.className = `nf-pin nf-note-pin${noteDue(note) ? " nf-note-due" : ""}`; + pin.title = note.text; + const short = note.text.length > 28 ? `${note.text.slice(0, 27)}…` : note.text; + pin.textContent = `${note.photo ? "📷 " : "✎ "}${short}`; + pin.addEventListener("click", () => { + const open = pin.classList.toggle("nf-note-open"); + pin.textContent = `${note.photo ? "📷 " : "✎ "}${open ? note.text : short}`; + // opened, a note shows its photo under the text (#113) + const photo = open && note.photo ? this.notePhoto?.(note.photo) : null; + if (photo) { + const img = document.createElement("img"); + img.className = "nf-note-photo"; + img.alt = ""; + img.src = photo; + img.addEventListener("load", () => { + this.labelsDirty = true; + this.invalidate(); + }); + pin.append(img); + } + this.labelsDirty = true; + this.invalidate(); + }); + this.labels.append(pin); + notePins.push({ pin, note }); + } + this.floors.push({ + floor, + rank: ordered.indexOf(floor), + group, + geo, + floorMesh, + shadowMesh, + patternMesh: pattern, + glowMesh, + lightSurface: null, + lightZones: null, + framesMesh, + glassMesh, + blindsMesh, + lampMesh, + sunMesh, + sunSig: "", + haloMesh, + coneMesh, + wedgeTris: [], + fridgeMesh, + lampTris: [], + lampFurnTris: [], + frameTris: [], + glassTris: [], + blindTris: [], + wallMesh, + screenMesh, + screenSig: "", + flowLayout: "", + glowSig: "", + lampShapeSig: "", + lampColorSig: "", + lampShade: new Float32Array(0), + lampRanges: new Map(), + bbox, + roomPins, + notePins, + labelSize: null, + materials, + mask, + openings: new Map(), + y: prev?.y ?? 0, + o: prev?.o ?? 1, + ty: 0, + to: 1, + appliedO: -1, + label, + }); + } + this.floorMap = new Map(this.floors.map((f) => [f.floor.id, f])); + this.buildPets(); + for (const fv of this.floors) this.buildFridges(fv); + this.labelsDirty = true; + if (this.floorId && !b.floors.some((f) => f.id === this.floorId)) this.floorId = null; + for (const fv of this.floors) { + this.buildLamps(fv); + this.buildScreens(fv); + const prev = previousOpenings.get(fv.floor.id); + for (const info of fv.geo.openings) fv.openings.set(info.opening.id, prev?.get(info.opening.id) ?? this.openingTargets.get(info.opening.id) ?? CLOSED); + this.buildOpenings(fv); + this.buildLightSurface(fv); + this.buildSun(fv); + } + this.applyTargets(previous.size === 0); + this.applyHighlight(); + this.applyTierFlags(); + this.buildRoofMesh(); + this.updateGhost(); + this.placeMeshes(); + } + + /** Put the owned 3D models of the furniture in place; models not loaded yet are fetched, and the floors rebuilt when they arrive. */ + private placeMeshes(): void { + for (const m of this.meshes) { + m.group.removeFromParent(); + disposeMeshInstance(m.group); + } + this.meshes = []; + for (const fv of this.floors) { + for (const f of withVehicles(fv.floor, this.parked).furniture) { + const item = packItem(f.type); + if (!item?.mesh) continue; + const id = item.mesh; + if (!hasMesh(f.type)) { + if (!this.meshAsked.has(id)) { + this.meshAsked.add(id); + void loadMesh(id).then((ok) => { + if (ok && !this.disposed) this.rebuild(); + }); + } + continue; + } + const colour = item.colors?.length ? (item.colors.find((c) => c.id === f.variant) ?? item.colors[0]).hex : null; + const group = instantiateMesh(id, { x: f.x, z: f.z, y: mountBase(fv.floor, f), rotation: f.rotation, mirror: f.mirror, w: f.w, d: f.d, h: f.h, paint: colour }); + if (!group) continue; + if (!this.meshLight) this.meshLight = addMeshLighting(this.root, this.renderer); + applyEnvironment(group, this.meshLight.env); + fv.group.add(group); + this.meshes.push({ group, furnitureId: f.id }); + } + } + this.invalidate(); + } + + private buildRoofMesh(): void { + if (this.roof) { + this.roof.group.traverse((o) => ((o as Mesh).geometry as BufferGeometry | undefined)?.dispose()); + this.roof.solid.dispose(); + this.roof.lines.dispose(); + this.roof.glass.dispose(); + this.scene.remove(this.roof.group); + this.roof = null; + } + const geos = this.building ? buildRoof(this.building, this.roofWindows) : []; + if (!geos.length) return; + const group = new Group(); + const solid = themed(new MeshBasicMaterial({ vertexColors: true, transparent: true, side: DoubleSide }), this.themeUniform); + const lines = themed(new LineBasicMaterial({ vertexColors: true, transparent: true, blending: lineBlending(this.theme), depthWrite: false }), this.themeUniform, true); + // canopies: faint see-through panels that do not hide what is below + const glass = themed(new MeshBasicMaterial({ vertexColors: true, transparent: true, side: DoubleSide, depthWrite: false }), this.themeUniform); + const parts = geos.map((geo) => { + const part = new Group(); + part.add(new Mesh(geo.solid.geometry(), solid), new LineSegments(geo.lines.geometry(), lines)); + if (geo.glass.count) part.add(new Mesh(geo.glass.geometry(), glass)); + part.renderOrder = 8; + group.add(part); + return { group: part, floorId: geo.floor.id, rideId: roofRider(this.building!, geo.floor, geo.sections ?? []), base: geo.base, lift: geo.lift !== false }; + }); + group.renderOrder = 8; + this.scene.add(group); + this.roof = { group, parts, solid, lines, glass }; + this.placeRoof(); + } + + /** + * The roof shows in the house view and sits on its floor; zooming in lifts and fades it, so the top + * floor opens up. Returns true while it still moves. + */ + private placeRoof(dt = 1000): boolean { + const roof = this.roof; + if (!roof) return false; + const zoom = this.keepRoof ? 1 : Math.min(1, Math.max(0, (this.controls.view.radius / this.houseRadius - 0.62) / 0.3)); + // a house with a single floor shows that floor as its house view, roof included (D208) + const house = this.floorId === null || this.floors.length === 1; + const target = house && !this.lowered ? ROOF_REST * zoom : 0; + const k = floorShare(dt); + const before = this.roofO; + this.roofO += (target - this.roofO) * k; + if (Math.abs(target - this.roofO) < 0.004) this.roofO = target; + roof.group.visible = this.roofO > 0.02; + // each part rides on its floor (pulled apart or stacked), lifted while it fades in or out + for (const part of roof.parts) { + const fv = this.floorMap.get(part.floorId); + if (!fv) continue; + // floors pulled apart: the roof rides with the highest floor beneath it (an attic or a loft under + // the same slopes, #202) and lifts off it the same way (it follows that floor's own glide) + const ride = this.floorMap.get(part.rideId) ?? fv; + const apart = ride.ty > 0 ? Math.min(1, ride.y / ride.ty) : this.explode && this.floorId === null ? 1 : 0; + // at rest (fully shown) it sits exactly on its walls: the lift counts from the resting opacity, not from 1 (#41) + const fade = Math.max(0, 1 - this.roofO / ROOF_REST); + part.group.position.y = fv.floor.elevation + ride.y + part.base + fade * 2.2 + (part.lift ? apart * ROOF_GAP : 0); + } + roof.solid.opacity = this.roofO; + // the roof keeps hiding the walls under it until it is mostly faded, so they do not show through it while zooming in (#41) + roof.solid.depthWrite = this.roofO > 0.5; + roof.lines.opacity = this.roofO; + roof.glass.opacity = this.roofO * 0.28; + return this.roofO !== before && this.roofO !== target; + } + + /** + * Tablet level: leave out the passes that cover the whole picture but add little (floor patterns, + * baked floor shadows, the ground grid, the wide glow around cables). + */ + private applyTierFlags(): void { + const low = this.lowQuality; + this.ground.visible = !low && this.theme !== "day" && this.floors.some((f) => f.floor.rooms.length > 0); + for (const fv of this.floors) { + fv.patternMesh.visible = !low; + fv.shadowMesh.visible = !low && fv.o > 0.98; + } + this.invalidate(); + } + + /** The meshes that depend on the level (cable glow, light surface cell, lamp halos). */ + private rebuildTier(): void { + for (const fv of this.floors) { + fv.flowLayout = ""; + this.buildLightSurface(fv); + fv.lampShapeSig = ""; + this.buildLamps(fv); + } + } + + /** True when the house view shows several floors (floor labels instead of room labels). */ + private get houseView(): boolean { + return this.floorId === null && this.floors.length > 1; + } + + /** Where every floor belongs in the current view. */ + private applyTargets(immediate: boolean): void { + const chosen = this.floorId ? this.floorMap.get(this.floorId) : undefined; + for (const fv of this.floors) { + const target = floorTarget(fv.rank, chosen?.rank, this.explode, this.floorStack); + [fv.ty, fv.to] = [target.y, target.opacity]; + if (immediate) [fv.y, fv.o] = [target.y, target.opacity]; + this.applyFloor(fv); + } + this.invalidate(); + } + + /** Moves a floor group to its current offset and fades its materials. */ + private applyFloor(fv: FloorView): void { + fv.group.position.y = fv.floor.elevation + fv.y; + fv.group.visible = fv.o > 0.02; + // a multiply layer cannot fade, so it goes with the first step; the tablet level leaves it out + fv.shadowMesh.visible = fv.o > 0.98 && !this.lowQuality; + if (Math.abs(fv.appliedO - fv.o) < 1e-3) return; + fv.appliedO = fv.o; + fadeMaterials(fv.materials, fv.o); + } + + /** One frame of the floor animation; true while something still moves. */ + private stepFloors(dt: number): boolean { + let moving = false; + const share = floorShare(dt); + for (const fv of this.floors) { + const step = easeFloor(fv, share); + if (step.settled) this.labelsDirty = true; + if (step.moving || step.settled) this.applyFloor(fv); + moving ||= step.moving; + } + return moving; + } + + /** Move sashes and blinds towards their targets; returns true while something still moves. */ + private stepOpenings(dt: number): boolean { + let moving = false; + const share = stepShare(dt); + for (const fv of this.floors) { + let changed = false; + for (const [id, now] of fv.openings) { + const target = this.openingTargets.get(id) ?? CLOSED; + if (atTarget(now, target)) continue; + const step = stepOpening(now, target, share); + fv.openings.set(id, step.state); + changed = true; + moving ||= step.moving; + } + if (changed) { + this.buildOpenings(fv); + this.buildGlow(fv); + this.buildSun(fv); + } + } + return moving; + } + + /** The turn of a fan's blades now (degrees, one blade spacing at most): turning fans move on with the effect timer. */ + private fanPhase(d: DeviceMarker): number { + if (d.lamp !== "fan" || !d.spin) return 0; + return Math.round(((this.effectTime * d.spin * 360) % FAN_SPACING) * 10) / 10; + } + + /** One sampler for lamp shades, halos, cones and room light surfaces. */ + private glowOf(d: DeviceMarker): DeviceMarker["glow"] { + return animateGlow(d.glow, d.effect, this.effectTime); + } + + /** + * Lamp models of the lights on a floor, merged into one mesh. The shapes are rebuilt only when a + * lamp moves or changes; the shade colours (light colour, brightness, tap flash) are written into + * the mesh in place, so colour effects cost no geometry. + */ + private buildLamps(fv: FloorView): void { + const now = performance.now(); + const flash = (id: string) => { + const until = this.flashes.get(id); + if (!until || until <= now) return 0; + // a tap flashes once; a found device (search) pulses until the time is up + const left = until - now; + const k = left > FLASH_MS ? 0.5 + 0.5 * Math.sin(left / 140) : left / FLASH_MS; + return Math.round(k * 10) / 10; + }; + const lamps = this.devices.filter((d) => d.floorId === fv.floor.id && d.lamp); + const shapeSig = + this.wallMode + + (this.lowQuality ? "L" : this.highQuality ? "H" : "M") + + lamps.map((d) => `${d.id},${d.lamp},${d.variant},${d.x},${d.z},${d.y},${d.rotation ?? 0},${d.roll ?? 0},${d.upright ? 1 : 0},${d.rise ?? 0},${d.size?.join("/")},${d.base ?? 0},${d.pack ?? ""},${d.mirror ? 1 : 0},${d.ceiling ?? ""},${this.fanPhase(d)}`).join(";"); + const glows = lamps.map((d) => this.glowOf(d)); + const wedges = this.devices.filter((d) => d.floorId === fv.floor.id && d.wedge); + const colorSig = + lamps.map((d, i) => `${flash(d.id)},${glows[i] ? `${glows[i]!.level.toFixed(3)},${glows[i]!.color.map((c) => c.toFixed(3)).join("/")}` : "off"}`).join(";") + + "|" + + wedges.map((d) => `${d.id},${d.x},${d.z},${d.rotation ?? 0},${JSON.stringify(d.wedge)}`).join(";"); + if (shapeSig !== fv.lampShapeSig || !fv.lampMesh.geometry.getAttribute("position")) { + fv.lampShapeSig = shapeSig; + fv.lampColorSig = ""; + const buf = new GeoBuffer(); + const tris: FloorView["lampTris"] = []; + const furnTris: FloorView["lampFurnTris"] = []; + const ranges = new Map(); + const H = fv.floor.height; + for (const d of lamps) { + // hanging lamps would float above cut walls + const hanging = d.lamp === "strip" ? (d.base ?? H) > Math.min(fv.floor.cut_height, d.ceiling ?? H) : d.lamp ? HANGING_LAMPS.has(d.lamp) : false; + if (!d.lamp || (hanging && this.lowered)) continue; + const start = buf.count; + const packed = d.pack ? packItem(d.pack) : undefined; + const [pw, pd, ph] = d.size ?? [0.3, 0.3, 0.3]; + // shades get the sentinel colour and are recoloured below + if (packed) pushPackLamp(buf, packed, { x: d.x, z: d.z, rotation: d.rotation ?? 0, w: pw, d: pd, h: ph, mirror: d.mirror }, d.base ?? 0, SHADE_SENTINEL); + else pushLampModel(buf, { ...d, lamp: d.lamp!, phase: this.fanPhase(d) }, d.ceiling ?? H, SHADE_SENTINEL); + // keyed by the furniture: two lamps may share one light (one switch for two strips) + ranges.set(d.furnitureId ?? d.id, { start, end: buf.count }); + if (d.pickable !== false) tris.push({ id: d.id, start, end: buf.count }); + if (d.furnitureId) furnTris.push({ id: d.furnitureId, start, end: buf.count }); + } + fv.lampTris = tris; + fv.lampFurnTris = furnTris; + fv.lampRanges = ranges; + fv.lampShade = shadeFactors(buf.c); + fv.lampMesh.geometry.dispose(); + fv.lampMesh.geometry = buf.geometry(); + fv.lampMesh.visible = buf.count > 0; + } + if (colorSig === fv.lampColorSig) return; + fv.lampColorSig = colorSig; + const attr = fv.lampMesh.geometry.getAttribute("color") as Float32BufferAttribute; + const colors = attr.array as Float32Array; + lamps.forEach((d, i) => { + const range = fv.lampRanges.get(d.furnitureId ?? d.id); + if (!range) return; + const glow = glows[i]; + // a lit shade glows in the light's colour, brighter with more brightness; a tap flashes it white + const k = glow ? 0.55 + 0.45 * glow.level : 0; + const shadeC = glow ? new Color(...(glow.color.map((c) => Math.min(1, c * k)) as [number, number, number])) : new Color(LAMP_SHADE); + const f = flash(d.id); + if (f > 0) shadeC.lerp(new Color(1, 1, 1), 0.7 * f); + // the model's colours come from hex values: convert the same way (colour management) + const c = new Color(shadeC.getHex()); + recolorLamps(colors, fv.lampShade, range, [c.r, c.g, c.b]); + }); + attr.needsUpdate = true; + this.buildHalos(fv); + } + + /** + * Sunlight through windows that face the sun: each window's opening (reduced by its blind) is + * projected along the sun's rays onto the floor as a warm, soft patch. + */ + private buildSun(fv: FloorView): void { + // the patches of sunlight can be switched off in the settings + const sun = this.building?.settings.sun_patches === false ? null : this.sun; + const north = this.building?.settings.north ?? 0; + const cloud = this.weatherLayer?.cloud ?? 0; + const signature = sunSignature(sun, north, cloud, fv.openings.values()); + if (signature === fv.sunSig) return; + fv.sunSig = signature; + const patches = sunlightPatches({ floor: fv.floor, openings: fv.geo.openings, states: fv.openings, sun, northDegrees: north, cloud }); + fv.sunMesh.geometry.dispose(); + fv.sunMesh.geometry = patches.geometry(); + fv.sunMesh.visible = patches.count > 0; + } + + /** Glow points at lit shades (not at the tablet level) and light cones under spots (level "High"). */ + private buildHalos(fv: FloorView): void { + const points: HaloPoints = { positions: [], colours: [] }; + const cones = new GeoBuffer(); + // plugin wedges on the floor are drawn at every quality: they are also what one taps + const wedges: FloorView["wedgeTris"] = []; + for (const marker of this.devices) if (marker.floorId === fv.floor.id && marker.wedge) { + const range = addFloorWedge(cones, marker, fv.geo.walls2d); + if (!marker.wedge.through) wedges.push({ id: marker.id, ...range }); + } + fv.wedgeTris = wedges; + const cut = this.lowered; + for (const marker of this.lowQuality ? [] : this.devices) { + const glow = this.glowOf(marker); + if (marker.floorId !== fv.floor.id || !marker.lamp || !glow) continue; + if (cut && hiddenInCut(marker.lamp)) continue; + const lamp = marker as DeviceMarker & { lamp: LampModel }; + addLampHalo(points, lamp, glow, marker.ceiling ?? fv.floor.height); + if (this.highQuality && (marker.lamp === "downlight" || marker.lamp === "spot")) addSpotCone(cones, lamp, glow, marker.ceiling ?? fv.floor.height); + } + const geometry = new Geometry(); + geometry.setAttribute("position", new Float32BufferAttribute(points.positions, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(points.colours, 3)); + fv.haloMesh.geometry.dispose(); + fv.haloMesh.geometry = geometry; + fv.haloMesh.visible = !this.lowQuality && points.positions.length > 0; + fv.coneMesh.geometry.dispose(); + fv.coneMesh.geometry = cones.geometry(); + fv.coneMesh.visible = cones.count > 0; + } + + /** Lit screens of a floor: a bright panel in the app colour and a faint glow around it. */ + private buildScreens(fv: FloorView): void { + // the vehicles in the parking spots count as furniture here too + const items = withVehicles(fv.floor, this.parked).furniture.filter((f) => this.screens.has(f.id)); + const sig = items.map((f) => `${f.id}:${f.x},${f.z},${f.rotation},${f.w},${f.d},${f.h},${f.mount_y ?? ""},${f.mirror ? 1 : 0}:${JSON.stringify(this.screens.get(f.id))}`).join(";"); + if (sig === fv.screenSig && fv.screenMesh.geometry.getAttribute("position")) return; + fv.screenSig = sig; + const buf = new GeoBuffer(); + for (const f of items) { + const st = this.screens.get(f.id)!; + const a = f.rotation * DEG; + const c = Math.cos(a); + const s = Math.sin(a); + const P = (x: number, y: number, z: number) => [f.x + x * c - z * s, y, f.z + x * s + z * c]; + if (st.gangs) { + // a switch plate or socket: each button that is on glows in its light's colour (green for a socket) + const item = packItem(f.type); + if (!item) continue; + for (const g of st.gangs) { + const col = new Color(...g.color.map((v) => Math.min(1, v * (0.45 + 0.55 * g.level))) as [number, number, number]); + pushPackGlow(buf, item, f, mountBase(fv.floor, f), col.getHex(), (p) => p.gang === g.gang); + } + continue; + } + if (st.print !== undefined) { + // the print on the bed: a block in the middle of the printer that grows with the progress + const base = mountBase(fv.floor, f) + f.h * 0.2; + const s = Math.min(f.w, f.d) * 0.16; + const top = base + f.h * 0.38 * Math.min(1, Math.max(0, st.print)); + const col = new Color(...st.color.map((v) => Math.min(1, v * (0.35 + 0.65 * st.level))) as [number, number, number]); + const side = col.clone().multiplyScalar(0.7); + const c4 = [P(-s, base, -s), P(s, base, -s), P(s, base, s), P(-s, base, s)]; + const t4 = [P(-s, top, -s), P(s, top, -s), P(s, top, s), P(-s, top, s)]; + buf.tri(t4[0], t4[2], t4[1], col); + buf.tri(t4[0], t4[3], t4[2], col); + for (let k = 0; k < 4; k++) { + const j = (k + 1) % 4; + buf.tri(c4[k], c4[j], t4[j], side); + buf.tri(c4[k], t4[j], t4[k], side); + } + continue; + } + if (st.fill !== undefined) { + // a home battery's charge bar, filled up to its charge (sideways on a wall unit), the rest dim + const bar = batteryBar(f, fv.floor); + if (!bar) continue; + const r = bar.rect; + const k = Math.min(1, Math.max(0, st.fill)); + const lit = new Color(...st.color.map((v) => Math.min(1, v * (0.35 + 0.65 * st.level))) as [number, number, number]); + const dim = new Color(0.08, 0.1, 0.13); + const z = r.z; + const quad = (x0: number, x1: number, y0: number, y1: number, col: Color) => { + buf.tri(P(x0, y0, z), P(x1, y0, z), P(x1, y1, z), col); + buf.tri(P(x0, y0, z), P(x1, y1, z), P(x0, y1, z), col); + }; + if (bar.vertical) { + const y = r.y0 + (r.y1 - r.y0) * k; + if (k > 0) quad(r.x0, r.x1, r.y0, y, lit); + if (k < 1) quad(r.x0, r.x1, y, r.y1, dim); + } else { + const x = r.x0 + (r.x1 - r.x0) * k; + if (k > 0) quad(r.x0, x, r.y0, r.y1, lit); + if (k < 1) quad(x, r.x1, r.y0, r.y1, dim); + } + continue; + } + if (st.leds) { + const item = packItem(f.type); + if (!item) continue; + const col = new Color(...st.color.map((v) => Math.min(1, v * (0.35 + 0.65 * st.level))) as [number, number, number]); + pushPackGlow(buf, item, f, mountBase(fv.floor, f), col.getHex(), (p) => !!p.glow || !!p.screen); + continue; + } + if (st.heat) { + const item = packItem(f.type); + if (!item) continue; + const col = new Color(...st.color.map((v) => Math.min(1, v * (0.35 + 0.65 * st.level))) as [number, number, number]); + pushPackGlow(buf, item, f, mountBase(fv.floor, f), col.getHex(), () => true); + continue; + } + if (st.faces) { + // a state on the item itself: a glowing plate on its top (a half of it for a bed's side or a bunk) + const w = Math.max(0.05, f.w) * (f.mirror ? -1 : 1); + const d = Math.max(0.05, f.d); + const h = Math.max(0.005, f.h); + const base = mountBase(fv.floor, f); + for (const face of st.faces) { + const x0 = face.part === "right" ? 0.03 : -Math.abs(w) / 2 + 0.03; + const x1 = face.part === "left" ? -0.03 : Math.abs(w) / 2 - 0.03; + const y = base + (face.part === "bottom" ? h * 0.45 : h) + 0.006; + const col = new Color(...face.color.map((v) => Math.min(1, v * (0.35 + 0.65 * face.level))) as [number, number, number]); + const edge = new Color(0, 0, 0); + const Q = (x: number, z: number, yy = y) => P(x * Math.sign(w), yy, z); + const inner = [Q(x0, -d / 2 + 0.03), Q(x1, -d / 2 + 0.03), Q(x1, d / 2 - 0.03), Q(x0, d / 2 - 0.03)]; + buf.tri(inner[0], inner[2], inner[1], col); + buf.tri(inner[0], inner[3], inner[2], col); + const g = 0.12 + 0.1 * face.level; + const halo = col.clone().multiplyScalar(0.5); + const outer = [Q(x0 - g, -d / 2 - g, y + 0.004), Q(x1 + g, -d / 2 - g, y + 0.004), Q(x1 + g, d / 2 + g, y + 0.004), Q(x0 - g, d / 2 + g, y + 0.004)]; + for (let i = 0; i < 4; i++) { + const j = (i + 1) % 4; + buf.tri(inner[i], outer[j], outer[i], halo, edge, edge); + buf.tri(inner[i], inner[j], outer[j], halo, halo, edge); + } + } + continue; + } + const r = screenRect(f, fv.floor); + if (!r) continue; + const core = new Color(...st.color.map((v) => Math.min(1, v * (0.35 + 0.65 * st.level))) as [number, number, number]); + const edge = new Color(0, 0, 0); + const z = r.z + 0.004; + buf.tri(P(r.x0, r.y0, z), P(r.x1, r.y0, z), P(r.x1, r.y1, z), core); + buf.tri(P(r.x0, r.y0, z), P(r.x1, r.y1, z), P(r.x0, r.y1, z), core); + // glow frame fading out around the screen + const strength = Math.min(1.5, st.halo ?? 1); + if (strength <= 0) continue; + const g = (0.18 + 0.12 * st.level) * Math.min(1, strength); + const halo = core.clone().multiplyScalar(0.5 * strength); + const inner = [P(r.x0, r.y0, z), P(r.x1, r.y0, z), P(r.x1, r.y1, z), P(r.x0, r.y1, z)]; + const outer = [P(r.x0 - g, r.y0 - g, z + 0.01), P(r.x1 + g, r.y0 - g, z + 0.01), P(r.x1 + g, r.y1 + g, z + 0.01), P(r.x0 - g, r.y1 + g, z + 0.01)]; + for (let i = 0; i < 4; i++) { + const j = (i + 1) % 4; + buf.tri(inner[i], outer[i], outer[j], halo, edge, edge); + buf.tri(inner[i], outer[j], inner[j], halo, edge, halo); + } + } + fv.screenMesh.geometry.dispose(); + fv.screenMesh.geometry = buf.geometry(); + fv.screenMesh.visible = buf.count > 0; + } + + private buildOpenings(fv: FloorView): void { + // the ground in this floor's own heights (it lies just below the ground floor's slab) + const parts = buildOpeningParts(fv.geo.openings, fv.openings, Math.min(fv.floor.cut_height, fv.floor.height), -0.2 - fv.floor.elevation); + fv.frameTris = parts.frameTris; + fv.glassTris = parts.glassTris; + fv.blindTris = parts.blindTris; + for (const [mesh, geo] of [ + [fv.framesMesh, parts.frames], + [fv.glassMesh, parts.glass], + [fv.blindsMesh, parts.blinds], + ] as const) { + mesh.geometry.dispose(); + mesh.geometry = geo; + mesh.visible = geo.getAttribute("position").count > 0; + } + } + + /** Floors that can be tapped and are framed by the camera: the whole house or the selected floor. */ + private activeFloors(): FloorView[] { + return this.floors.filter((f) => f.to > 0.99); + } + + private applyHighlight(): void { + for (const fv of this.floors) { + const colors = fv.geo.floor.getAttribute("color"); + for (const r of fv.geo.roomTris) { + const c = new Color(r.color); + const tint = this.roomTint?.get(r.roomId); + // heatmap: a clear, saturated floor colour (the room light is dimmed meanwhile) + if (tint) c.lerp(new Color(...tint).multiplyScalar(0.6), 0.9); + if (r.roomId === this.roomId) c.lerp(ACTIVE_FLOOR, tint ? 0.3 : 0.75); + for (let v = r.start * 3; v < r.end * 3; v++) colors.setXYZ(v, c.r, c.g, c.b); + } + colors.needsUpdate = true; + } + for (const pin of this.labels.querySelectorAll(".nf-pin")) { + pin.classList.toggle("nf-pin-active", !!pin.dataset.room && pin.dataset.room === this.roomId); + } + this.invalidate(); + } + + private keepCamera = false; + private zoom = 1; + + private fit(duration: number, keep: { theta: number; phi: number; radius: number } | null = null): void { + const box = new Box3(); + for (const fv of this.activeFloors()) { + const y0 = fv.floor.elevation + fv.ty; + for (const room of fv.floor.rooms) { + for (const [x, z] of room.points) { + box.expandByPoint(new Vector3(x, y0, z)); + box.expandByPoint(new Vector3(x, y0 + fv.floor.height, z)); + } + } + } + if (box.isEmpty()) box.set(new Vector3(-4, 0, -4), new Vector3(4, 2.5, 4)); + this.placeGround(); + this.buildHouseShadow(); + // the weather falls over the plot and a margin around it + this.weatherLayer.setBounds({ x0: box.min.x - 8, x1: box.max.x + 8, z0: box.min.z - 8, z1: box.max.z + 8, y0: box.min.y, y1: box.max.y + 6 }); + const center = box.getCenter(new Vector3()); + const size = box.getSize(new Vector3()); + // perspective widens the near corners; portrait screens need a little more room for that + const radius = Math.max(8, this.distanceFor(size) * (this.camera.aspect < 1 ? 1.16 : 1.02)); + this.controls.maxRadius = Math.max(40, radius * 3); + center.y = box.min.y + size.y * (this.houseView ? 0.45 : 0.3); + if (this.floorId === null || this.floors.length === 1) this.houseRadius = radius; + // the house view opens as set up (from the garden side, closer …); an opened floor keeps the fitted + // distance but looks from the same side, so the house never turns round when a floor is opened + const house = this.floorId === null; + // a floor may have a start view of its own (#182): it opens from that side and distance + const own = !house ? (this.floorMap.get(this.floorId!)?.floor.start_view ?? null) : null; + const start = own ?? this.startView; + const useRadius = !!start && (house || !!own); + if (start && useRadius) this.controls.maxRadius = Math.max(this.controls.maxRadius, start.radius * 1.5); + // the start view's framing (#206): the point it looks at, counted from the opened floor + const at = useRadius ? start!.target : null; + if (at) center.set(at.x, at.y + (own ? this.floorBase(this.floorId) : 0), at.z); + if (keep) { + this.controls.flyTo({ target: center, radius: keep.radius, phi: keep.phi, theta: keep.theta }, duration); + return; + } + this.controls.flyTo({ target: center, radius: (useRadius ? start!.radius : radius) / this.zoom, phi: start ? start.phi : 0.85, theta: start ? start.theta : -0.6 }, duration); + } + + /** The ground grid lies under the lowest floor and reaches well beyond the building. */ + private placeGround(): void { + const box = new Box3(); + let y = Infinity; + for (const fv of this.floors) { + y = Math.min(y, fv.floor.elevation + Math.min(0, fv.ty)); + for (const room of fv.floor.rooms) for (const [x, z] of room.points) box.expandByPoint(new Vector3(x, 0, z)); + for (const a of fv.floor.outdoor ?? []) for (const [x, z] of a.points) box.expandByPoint(new Vector3(x, 0, z)); + } + this.ground.visible = !box.isEmpty() && !this.lowQuality && this.theme !== "day"; + if (box.isEmpty()) return; + if (this.ground.visible && !this.groundTexture) { + this.groundTexture = makeGroundTexture(); + const m = this.ground.material as MeshBasicMaterial; + m.map = this.groundTexture; + m.needsUpdate = true; + } + const c = box.getCenter(new Vector3()); + const s = box.getSize(new Vector3()); + // the texture has 32 cells: 1 m each for a normal house, 2 m for a very large one + const span = GROUND_CELLS * Math.ceil((Math.max(s.x, s.z) + 16) / GROUND_CELLS); + this.ground.scale.set(span, span, 1); + this.ground.position.set(c.x, y - SLAB - 0.02, c.z); + this.groundY = y - SLAB - 0.04; + this.placeMap(); + } + + /** The real map under the plan: shown while the settings switch it on, turned by the plan's north. */ + setMap(map: MapSettings | null | undefined, north: number): void { + this.mapSettings = map ?? null; + this.mapNorth = north; + this.placeMap(); + this.invalidate(); + } + + private placeMap(): void { + this.mapLayer.set(this.mapSettings, this.mapNorth, this.groundY, this.theme === "day" ? 1 : 0.55); + } + + /** Camera distance at which a box of this size fits the view (bounding sphere against the narrower field of view). */ + private distanceFor(size: Vector3): number { + const vfov = this.camera.fov * DEG; + const hfov = 2 * Math.atan(Math.tan(vfov / 2) * this.camera.aspect); + return size.length() / 2 / Math.sin(Math.min(vfov, hfov) / 2); + } + + /** + * What lies under a screen point: a lamp, a linked piece of furniture or opening (their entity), or + * a room. Walls are looked through (the ones in front are glass), furniture without an entity too. + */ + /** A ray from the camera through a screen point of the stage. */ + private rayAt(x: number, y: number): Raycaster { + const rect = this.renderer.domElement.getBoundingClientRect(); + const ray = new Raycaster(); + ray.setFromCamera(new Vector2((x / rect.width) * 2 - 1, -(y / rect.height) * 2 + 1), this.camera); + return ray; + } + + /** A tap on devices only acts in the opened room (or, outside any room, on the opened floor). */ + setTapInRoom(on: boolean): void { + this.tapInRoom = on; + } + + /** Whether a device at this place can be switched by a tap now (tap_in_room). */ + private deviceInReach(floorId: string, roomId: string | null): boolean { + return !this.tapInRoom || inReach({ floorId, roomId }, { floorId: this.floorId, roomId: this.roomId }); + } + + /** With tap_in_room, an entity under the tap away from the opened room gives way to the room behind it. */ + private pickInReach(x: number, y: number): { entity: string } | { floorId: string; roomId: string | null } | null { + const hit = this.pick(x, y); + if (!this.tapInRoom || !hit || !("entity" in hit)) return hit; + const place = this.pick(x, y, false); + if (place && "floorId" in place && this.deviceInReach(place.floorId, place.roomId)) return hit; + return place; + } + + private pick(x: number, y: number, devices = true): { entity: string } | { floorId: string; roomId: string | null } | null { + const ray = this.rayAt(x, y); + const floors = this.activeFloors(); + // an owned 3D model that stands for a device: a tap on it is a tap on the device + if (devices && this.meshes.length) { + const hit = ray.intersectObjects(this.meshes.map((m) => m.group), true)[0]; + if (hit) { + let o: Object3D | null = hit.object; + while (o && !this.meshes.some((m) => m.group === o)) o = o.parent; + const entity = o ? this.pickFurniture.get(this.meshes.find((m) => m.group === o)!.furnitureId) : undefined; + if (entity) return { entity }; + } + } + const meshes = floors.flatMap((f) => [f.lampMesh, f.coneMesh, f.framesMesh, f.glassMesh, f.blindsMesh, f.wallMesh, f.floorMesh].filter((m) => m.visible)); + const inRange = (list: { id: string; start: number; end: number }[], tri: number) => list.find((r) => tri >= r.start && tri < r.end)?.id; + for (const hit of ray.intersectObjects(meshes, false)) { + if (hit.faceIndex == null) continue; + const tri = hit.faceIndex; + const fv = floors.find((f) => f.group === hit.object.parent)!; + // only the place is asked for: lamps, light cones and windows are looked through + if (!devices && (hit.object === fv.lampMesh || hit.object === fv.coneMesh || hit.object === fv.framesMesh || hit.object === fv.blindsMesh || hit.object === fv.glassMesh)) continue; + if (hit.object === fv.lampMesh || hit.object === fv.coneMesh) { + // a plugin's wedge on the floor is a far bigger target than the device itself + const id = inRange(hit.object === fv.lampMesh ? fv.lampTris : fv.wedgeTris, tri); + if (id) return { entity: id }; + } else if (hit.object === fv.framesMesh || hit.object === fv.blindsMesh || hit.object === fv.glassMesh) { + // the part above the cut is folded away with its wall: a tap there is meant for what lies behind + if (this.lowered && hit.face) { + const fold = ((hit.object as Mesh).geometry.getAttribute("fold") as Float32BufferAttribute | undefined)?.getX(hit.face.a) ?? ALWAYS; + if (fold !== ALWAYS && Math.floor(fold / 16) % 8 === 0) continue; + } + // the whole window counts, glass included: a small blind is a poor target + const id = inRange(hit.object === fv.framesMesh ? fv.frameTris : hit.object === fv.glassMesh ? fv.glassTris : fv.blindTris, tri); + let entity = id ? this.pickOpenings.get(id) : undefined; + // a wide opening with two blinds: the right half belongs to the second one + const second = id ? this.pickOpenings2.get(id) : undefined; + const info = second ? fv.geo.openings.find((i) => i.opening.id === id) : undefined; + if (second && info && (hit.point.x - info.start[0]) * info.axis[0] + (hit.point.z - info.start[1]) * info.axis[1] > info.width / 2) entity = second; + if (entity) return { entity }; + } else if (hit.object === fv.wallMesh) { + const id = inRange(fv.geo.furnitureTris, tri); + const entity = id && devices ? this.pickFurniture.get(id) : undefined; + if (entity) return { entity }; + // a wall: the tap stops at it unless it is see-through (cut away, or glass in the floor view) + if (hit.face && !id) { + const fold = (fv.wallMesh.geometry.getAttribute("fold") as Float32BufferAttribute | undefined)?.getX(hit.face.a) ?? 32; + // (a painted wall's fold carries PAINT_OFFSET, a multiple of 16 * 8) + const part = Math.floor(fold / 16) % 8; + const bucket = fold % 16; + const cutAway = this.lowered && part === 0; + const glass = (fv.mask.glass.value & (1 << bucket)) !== 0; + if (!cutAway) { + // the room on the camera's side of the wall is what the tap means + const dir = ray.ray.direction; + const l = Math.hypot(dir.x, dir.z) || 1; + const p: [number, number] = [hit.point.x - (dir.x / l) * 0.3, hit.point.z - (dir.z / l) * 0.3]; + const beside = fv.floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon(p, r.points))?.id ?? null; + if (this.roomId !== null) { + // in a room: its own walls catch the tap (nothing behind them is meant), other walls let it through + if (beside === this.roomId) return { floorId: fv.floor.id, roomId: beside }; + } else if (!glass && beside) return { floorId: fv.floor.id, roomId: beside }; + } + } + } else if (hit.object === fv.floorMesh) { + return { floorId: fv.floor.id, roomId: inRange(fv.geo.roomTris.map((r) => ({ id: r.roomId, start: r.start, end: r.end })), tri) ?? null }; + } + } + return null; + } + + private onTap(x: number, y: number): void { + const hit = this.furnish ? this.pick(x, y) : this.pickInReach(x, y); + if (hit && "entity" in hit && this.furnish) { + this.selectDevice(hit.entity); + this.options.onDeviceSelect?.(hit.entity); + return; + } + if (hit && "entity" in hit) { + this.flashes.set(hit.entity, performance.now() + FLASH_MS); + this.invalidate(); + this.options.onDeviceTap?.(hit.entity, x, y); + return; + } + this.options.onRoomTap?.(hit?.floorId ?? this.floorId ?? "", hit?.roomId ?? null); + } + + /** Furniture item (or lamp) under a screen point, with the floor it is on. */ + private furnitureAt(x: number, y: number): { fv: FloorView; id: string } | null { + const ray = this.rayAt(x, y); + const floors = this.activeFloors(); + const meshes = floors.flatMap((f) => [f.lampMesh, f.wallMesh].filter((m) => m.visible)); + for (const hit of ray.intersectObjects(meshes, false)) { + if (hit.faceIndex == null) continue; + const fv = floors.find((f) => f.group === hit.object.parent)!; + const list = hit.object === fv.lampMesh ? fv.lampFurnTris : fv.geo.furnitureTris; + const id = list.find((r) => hit.faceIndex! >= r.start && hit.faceIndex! < r.end)?.id; + if (id) return { fv, id }; + } + return null; + } + + /** Point on a floor's plane under a screen point. */ + private floorPoint(fv: FloorView, x: number, y: number): [number, number] | null { + const ray = this.rayAt(x, y); + const h = fv.floor.elevation + fv.y; + const dir = ray.ray.direction; + if (Math.abs(dir.y) < 1e-4) return null; + const t = (h - ray.ray.origin.y) / dir.y; + if (t <= 0) return null; + return [ray.ray.origin.x + dir.x * t, ray.ray.origin.z + dir.z * t]; + } + + /** Only these furniture types can be grabbed while furnishing (null: all); placed devices then cannot. */ + setFurnishTypes(types: readonly string[] | null): void { + this.furnishTypes = types ? new Set(types) : null; + } + + /** The editor's handler for things on roof faces and walls (null: none). */ + setSurfaceGrab(grab: SurfaceGrab | null): void { + this.surfaceGrab = grab; + } + + private surfaceRay(x: number, y: number): { o: [number, number, number]; d: [number, number, number] } { + const r = this.rayAt(x, y).ray; + return { o: [r.origin.x, r.origin.y, r.origin.z], d: [r.direction.x, r.direction.y, r.direction.z] }; + } + + private grabFurniture(x: number, y: number): boolean { + // the editor's surface handler first: a solar field or roof window under the pointer is moved by it + if (this.surfaceGrab?.start(this.surfaceRay(x, y))) { + this.surfaceDragging = true; + return true; + } + if (!this.furnish) return false; + // a device whose pin was pressed; the pin of a furniture item (the washer's watts) moves the item + const pending = this.pendingDevice; + this.pendingDevice = null; + // a tool that only moves some furniture (energy devices): everything else stays where it is + const only = this.furnishTypes; + if (only) { + const owner = pending ? this.devices.find((m) => m.id === pending)?.furnitureId : undefined; + const hit = owner ? null : this.furnitureAt(x, y); + const id = owner ?? hit?.id; + const fv = id ? this.floors.find((v) => v.floor.furniture.some((m) => m.id === id)) : undefined; + const type = fv?.floor.furniture.find((m) => m.id === id)?.type; + return !!(fv && id && type && only.has(type)) && this.grabItem(fv, id, x, y); + } + if (pending) { + const owner = this.devices.find((m) => m.id === pending)?.furnitureId; + const fv = owner ? this.floors.find((v) => v.floor.furniture.some((m) => m.id === owner)) : undefined; + if (!owner || !fv) return this.grabDevice(pending, x, y); + return this.grabItem(fv, owner, x, y); + } + // furniture first: a washing machine or a lamp with a linked entity is still furniture to move + // (its entity would otherwise be grabbed like a placed device, and nothing would move) + const hit = this.furnitureAt(x, y); + if (!hit) { + // a placed device's model (a camera) under the pointer + const picked = this.pick(x, y); + if (picked && "entity" in picked) return this.grabDevice(picked.entity, x, y); + // a tap on empty space clears the selection, a drag still turns the view + if (this.selectedFurniture) { + this.selectFurniture(null); + this.options.onFurnitureSelect?.(null); + } + if (this.selectedDevice) { + this.selectDevice(null); + this.options.onDeviceSelect?.(null); + } + return false; + } + return this.grabItem(hit.fv, hit.id, x, y); + } + + private grabItem(fv: FloorView, id: string, x: number, y: number): boolean { + const f = fv.floor.furniture.find((m) => m.id === id); + const p = this.floorPoint(fv, x, y); + if (!f || !p) return false; + if (f.locked) { + // fixed: selected, but a drag turns the view instead of moving it + this.selectFurniture(f.id); + this.options.onFurnitureSelect?.(f.id); + return false; + } + this.grab = { floorId: fv.floor.id, id: f.id, offset: [f.x - p[0], f.z - p[1]], x: f.x, z: f.z, moved: false }; + this.selectFurniture(f.id); + this.options.onFurnitureSelect?.(f.id); + return true; + } + + private grabDevice(id: string, x: number, y: number): boolean { + const d = this.devices.find((m) => m.id === id); + const fv = d && this.floorMap.get(d.floorId); + const p = fv && this.floorPoint(fv, x, y); + if (!d || !fv || !p) return false; + if (d.fixed) { + this.selectDevice(id); + this.options.onDeviceSelect?.(id); + return false; + } + this.deviceGrab = { id, floorId: fv.floor.id, offset: [d.x - p[0], d.z - p[1]], x: d.x, z: d.z, moved: false }; + this.selectDevice(id); + this.options.onDeviceSelect?.(id); + return true; + } + + /** Select a device (its pin is marked), or none. */ + setSelectedDevice(id: string | null): void { + if (id === this.selectedDevice) return; + this.selectDevice(id); + } + + /** Mark the selected device's pin; selecting a device drops the furniture selection and vice versa. */ + private selectDevice(id: string | null): void { + if (id && this.selectedFurniture) { + this.selectFurniture(null); + this.options.onFurnitureSelect?.(null); + } + this.selectedDevice = id; + for (const [entity, pin] of this.devicePins) pin.el.classList.toggle("nf-dev-sel", entity === id); + } + + private dragFurniture(x: number, y: number): void { + if (this.surfaceDragging) { + this.surfaceGrab?.move(this.surfaceRay(x, y)); + return; + } + const dg = this.deviceGrab; + if (dg) { + const fv = this.floorMap.get(dg.floorId); + const d = this.devices.find((m) => m.id === dg.id); + const p = fv && this.floorPoint(fv, x, y); + if (!fv || !d || !p) return; + const grid = this.building?.settings.grid ?? 0.05; + dg.x = d.x = Math.round((p[0] + dg.offset[0]) / grid) * grid; + dg.z = d.z = Math.round((p[1] + dg.offset[1]) / grid) * grid; + dg.moved = true; + this.labelsDirty = true; + this.invalidate(); + return; + } + const g = this.grab; + const fv = g && this.floorMap.get(g.floorId); + if (!g || !fv) return; + const p = this.floorPoint(fv, x, y); + if (!p) return; + const grid = this.building?.settings.grid ?? 0.05; + g.x = Math.round((p[0] + g.offset[0]) / grid) * grid; + g.z = Math.round((p[1] + g.offset[1]) / grid) * grid; + g.moved = true; + this.updateGhost(); + this.invalidate(); + } + + private dropFurniture(): void { + if (this.surfaceDragging) { + this.surfaceDragging = false; + this.surfaceGrab?.end(); + return; + } + const dg = this.deviceGrab; + this.deviceGrab = null; + if (dg?.moved) this.options.onDeviceMove?.(dg.id, Math.round(dg.x * 1000) / 1000, Math.round(dg.z * 1000) / 1000); + const g = this.grab; + this.grab = null; + if (g?.moved) this.options.onFurnitureMove?.(g.id, Math.round(g.x * 1000) / 1000, Math.round(g.z * 1000) / 1000); + this.updateGhost(); + } + + /** Wireframe box around the selected item, at its drag position while it is dragged. */ + private updateGhost(): void { + if (this.ghost) { + this.ghost.geometry.dispose(); + (this.ghost.material as Material).dispose(); + this.scene.remove(this.ghost); + this.ghost = null; + } + const id = this.selectedFurniture; + const fv = id ? this.floors.find((f) => f.floor.furniture.some((m) => m.id === id)) : undefined; + const f = fv?.floor.furniture.find((m) => m.id === id); + if (!fv || !f) return; + const x = this.grab?.id === f.id ? this.grab.x : f.x; + const z = this.grab?.id === f.id ? this.grab.z : f.z; + const H = ceilingOf(fv.floor, { ...f, x, z }); + const hanging = CEILING_TYPES.has(f.type); + const h = Math.max(0.1, f.type === "lamp_pendant" ? 0.3 : f.h); + const y0 = packItem(f.type) || f.type === "lamp_wall" || f.type === "led_strip" + ? mountBase(fv.floor, f) + : hanging + ? f.type === "lamp_pendant" || f.type === "ceiling_fan" + ? H - f.h - 0.1 + : H - h + : mountBase(fv.floor, f); + const a = f.rotation * DEG; + const c = Math.cos(a); + const sn = Math.sin(a); + const corner = (lx: number, lz: number, y: number) => [x + lx * c - lz * sn, y, z + lx * sn + lz * c]; + const lines = new LineBuffer(); + const pts = [ + [-f.w / 2, -f.d / 2], + [f.w / 2, -f.d / 2], + [f.w / 2, f.d / 2], + [-f.w / 2, f.d / 2], + ]; + const color = new Color(0.25, 0.9, 1); + for (let i = 0; i < 4; i++) { + const [ax, az] = pts[i]; + const [bx, bz] = pts[(i + 1) % 4]; + lines.seg(corner(ax, az, y0 + 0.01), corner(bx, bz, y0 + 0.01), color); + lines.seg(corner(ax, az, y0 + h), corner(bx, bz, y0 + h), color); + lines.seg(corner(ax, az, y0 + 0.01), corner(ax, az, y0 + h), color); + } + // the front edge a little brighter at floor level, so the direction is clear + lines.seg(corner(-f.w / 2, f.d / 2 + 0.03, y0 + 0.02), corner(f.w / 2, f.d / 2 + 0.03, y0 + 0.02), new Color(1, 1, 1)); + this.ghost = new LineSegments(lines.geometry(), new LineBasicMaterial({ vertexColors: true, depthTest: false, transparent: true })); + this.ghost.position.y = fv.floor.elevation + fv.y; + this.ghost.renderOrder = 20; + this.scene.add(this.ghost); + } + + private onHold(x: number, y: number): void { + const hit = this.pick(x, y); + if (hit && "entity" in hit) this.options.onDeviceHold?.(hit.entity, x, y); + } + + /** A mostly vertical drag on a lamp or blind becomes a swipe (unless furnishing). */ + private swipeStart(x: number, y: number, dx: number, dy: number): boolean { + if (this.furnish || Math.abs(dy) < Math.abs(dx) * 1.2) return false; + const hit = this.pickInReach(x, y); + if (!hit || !("entity" in hit)) return false; + if (this.options.onDeviceSwipe?.(hit.entity, "start", 0, x, y) !== true) return false; + this.swipe = { entity: hit.entity, x, y }; + return true; + } + + /** + * Small pictures of every floor with rooms (for the floor switcher): each floor alone, walls cut, + * seen from above at the usual angle, as PNG data URLs. Rendered once into an offscreen target of + * 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 }[] = []; + try { + if (this.roof) this.roof.group.visible = false; + if (this.ghost) this.ghost.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") }); + } + } 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(); + } + return out; + } + + /** Robot vacuums and their states; robots that clean drive lanes through their room. */ + setRobots(list: RobotInfo[]): void { + const seen = new Set(); + for (const info of list) { + seen.add(info.id); + let r = this.robots.get(info.id); + if (!r) { + r = this.makeRobot(info); + this.robots.set(info.id, r); + } + const was = r.info.mode; + const moved = + info.mode === "cleaning" && + was === "cleaning" && + ((r.info.roomId ?? null) !== (info.roomId ?? null) || JSON.stringify(r.info.obstacles ?? []) !== JSON.stringify(info.obstacles ?? [])); + r.info = info; + this.setRobotTrail(info); + // a robot that reports where it is needs no lanes invented for it: it stands there, facing where it faces + if (info.pose) { + r.motion.pos = [info.pose.x, info.pose.z]; + r.motion.heading = info.pose.heading; + r.motion.path = []; + } else if (info.mode === "cleaning" && (was !== "cleaning" || moved || !r.motion.path.length)) { + // start the lanes at the point nearest to where the robot is + const path = info.room ? cleaningPath(info.room, undefined, undefined, info.obstacles) : circlePath(info.rest); + const path2 = path.length ? path : circlePath(info.rest); + let best = 0; + path2.forEach((p, i) => { + if (Math.hypot(p[0] - r!.motion.pos[0], p[1] - r!.motion.pos[1]) < Math.hypot(path2[best][0] - r!.motion.pos[0], path2[best][1] - r!.motion.pos[1])) best = i; + }); + r.motion.path = path2; + r.motion.next = best; + // a robot reported in another room appears there instead of driving through the walls + if (info.room && !pointInPolygon(r.motion.pos, info.room)) r.motion.pos = [path2[best][0], path2[best][1]]; + } + r.led.color.setHex(ROBOT_LED[info.mode]); + } + for (const [id, r] of this.robots) { + if (seen.has(id)) continue; + r.group.removeFromParent(); + r.led.dispose(); + this.robots.delete(id); + const gone = this.robotTrails.get(id); + gone?.removeFromParent(); + gone?.geometry.dispose(); + (gone?.material as Material | undefined)?.dispose(); + this.robotTrails.delete(id); + const trailTimer = this.trailTimers.get(id); + if (trailTimer !== undefined) { + clearTimeout(trailTimer); + this.trailTimers.delete(id); + } + } + this.robotLast = 0; + this.invalidate(); + } + + /** + * The pad the robot has driven: its own map's trail, laid flat on the floor of its floor. It is rebuilt + * only when the trail changes, so a camera that repeats the same path every frame costs nothing. + */ + private setRobotTrail(info: RobotInfo): void { + const segments = info.track ?? []; + const key = segments.map((s) => (s.length ? `${s.length}:${s[0].map((v) => v.toFixed(2))}/${s[s.length - 1].map((v) => v.toFixed(2))}` : "")).join("|"); + const old = this.robotTrails.get(info.id); + if (old && old.userData.key === key) { + // the same pad, but time passes: it may have to fade now + this.showRobotTrail(info); + return; + } + let mesh = old; + if (!mesh) { + const material = new MeshBasicMaterial({ color: 0x36c8ff, transparent: true, opacity: 0.34, depthWrite: false, side: DoubleSide }); + mesh = new Mesh(trailGeometry([], 0.16, 0), material); + mesh.renderOrder = 3; + mesh.name = `robot-trail:${info.id}`; + this.robotTrails.set(info.id, mesh); + const parent = this.robots.get(info.id)?.group.parent; + if (parent) parent.add(mesh); + } + mesh.geometry.dispose(); + mesh.geometry = trailGeometry(segments, 0.16, (info.y ?? 0) + 0.012); + mesh.userData.key = key; + this.showRobotTrail(info); + } + + /** + * How strong the pad is right now, and a timer for the moment that next changes: full while the robot + * drives and for ten minutes after, then fading out. The timeline is where a finished clean stays, so + * the floor is not covered in last night's pad. + */ + private showRobotTrail(info: RobotInfo): void { + const mesh = this.robotTrails.get(info.id); + if (!mesh) return; + const pending = this.trailTimers.get(info.id); + if (pending !== undefined) { + clearTimeout(pending); + this.trailTimers.delete(info.id); + } + const now = Date.now(); + const strength = trailOpacity(info.settledAt, now); + (mesh.material as MeshBasicMaterial).opacity = 0.34 * strength; + mesh.visible = (info.track?.length ?? 0) > 0 && strength > 0.01; + // still driving, or already gone: nothing to wait for + if (strength <= 0 || (strength >= 1 && info.settledAt == null)) return; + const wait = strength >= 1 ? Math.max(0, (info.settledAt ?? now) + TRAIL_HOLD_MS - now) : 250; + this.trailTimers.set( + info.id, + setTimeout(() => { + this.showRobotTrail(info); + this.invalidate(); + }, wait), + ); + } + + private makeRobot(info: RobotInfo): { info: RobotInfo; motion: RobotMotion; group: Group; led: MeshBasicMaterial } { + if (!this.robotGeo) { + const buf = new GeoBuffer(); + const disc = (r: number, y0: number, y1: number, side: number, top: number) => { + const poly: [number, number][] = []; + for (let i = 0; i < 20; i++) poly.push([Math.cos((i / 20) * Math.PI * 2) * r, Math.sin((i / 20) * Math.PI * 2) * r]); + pushPrism(buf, poly, y0, y1, side, top, { aoFrom: 0, bottom: false }); + }; + disc(0.17, 0.012, 0.08, 0x243049, 0x34425f); + disc(0.055, 0.08, 0.1, 0x3a4a6a, 0x4d5f86); + this.robotGeo = buf.geometry(); + this.robotMat = new MeshBasicMaterial({ vertexColors: true }); + const led = new GeoBuffer(); + pushPrism(led, [[-0.05, 0.1], [0.05, 0.1], [0.05, 0.14], [-0.05, 0.14]], 0.08, 0.085, 0xffffff, 0xffffff, { aoFrom: 0, bottom: false }); + this.robotLedGeo = led.geometry(); + } + const group = new Group(); + const ledMat = new MeshBasicMaterial({ color: ROBOT_LED[info.mode] }); + // a robot mower is the same robot, larger and in garden green + const body = info.mower ? (this.mowerMat ??= new MeshBasicMaterial({ color: 0x3f8a4a })) : this.robotMat!; + group.add(new Mesh(this.robotGeo, body), new Mesh(this.robotLedGeo!, ledMat)); + if (info.mower) group.scale.set(1.7, 1.6, 1.7); + return { info, motion: { pos: [...info.rest] as [number, number], heading: info.restHeading, path: [], next: 0 }, group, led: ledMat }; + } + + /** The pets of the plan: a model each, standing where it was placed, ready to roam its room. */ + private buildPets(): void { + const keep = new Map(this.pets); + this.pets.clear(); + this.petMat ??= new MeshBasicMaterial({ vertexColors: true }); + for (const fv of this.floors) { + for (const f of fv.floor.furniture) { + const item = packItem(f.type); + if (!item?.pet) continue; + const room = fv.floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([f.x, f.z], r.points)); + const old = keep.get(f.id); + const buf = new GeoBuffer(); + packModel(new Builder(buf, new LineBuffer(), placement({ x: 0, z: 0, rotation: 0, mirror: f.mirror })), item, Math.max(0.05, f.w), Math.max(0.05, f.d), Math.max(0.05, f.h), 0, null, null, f.variant ?? null); + old?.group.removeFromParent(); + const group = new Group(); + group.add(new Mesh(buf.geometry(), this.petMat)); + // the furniture of the room is what it walks round (not rugs, lamps on the ceiling or things on the walls) + const obstacles = room ? fv.floor.furniture.filter((o) => o.id !== f.id && !packItem(o.type)?.pet && o.type !== "rug" && mountBase(fv.floor, o) < 0.5 && pointInPolygon([o.x, o.z], room.points)).map((o) => furnitureFootprint(o)) : []; + const petRoom: PetRoom = { points: room?.points ?? [[f.x - 0.5, f.z - 0.5], [f.x + 0.5, f.z - 0.5], [f.x + 0.5, f.z + 0.5], [f.x - 0.5, f.z + 0.5]], obstacles, speed: f.type.endsWith(":pet_dog") ? 0.7 : 0.45 }; + const motion: PetMotion = old && room && pointInPolygon(old.motion.pos, room.points) ? old.motion : { pos: [f.x, f.z], heading: (f.rotation * Math.PI) / 180, target: null, rest: 1 }; + this.pets.set(f.id, { motion, room: petRoom, random: seededRandom(f.id), group, floorId: fv.floor.id }); + } + } + for (const [id, old] of keep) if (!this.pets.has(id)) old.group.removeFromParent(); + } + + /** + * Where the pets are now, as their room sensors tell (pet id -> room id on the pet's floor; null: the room it was placed in). A pet + * reported in another room appears there and roams it. + */ + setPetRooms(rooms: Map): void { + for (const [id, p] of this.pets) { + const fv = this.floorMap.get(p.floorId); + const roomId = rooms.get(id); + if (!fv || roomId === undefined) continue; + const room = roomId ? fv.floor.rooms.find((r) => r.id === roomId && r.points.length >= 3) : undefined; + if (!room || p.room.points === room.points) continue; + const obstacles = fv.floor.furniture.filter((o) => !packItem(o.type)?.pet && o.type !== "rug" && mountBase(fv.floor, o) < 0.5 && pointInPolygon([o.x, o.z], room.points)).map((o) => furnitureFootprint(o)); + p.room = { ...p.room, points: room.points, obstacles }; + if (!pointInPolygon(p.motion.pos, room.points)) p.motion = { ...p.motion, pos: centroid(room.points), target: null, rest: 0.5 }; + } + this.invalidate(); + } + + /** Move the robots; true while one of them drives. */ + private stepRobots(now: number): boolean { + if (!this.robots.size && !this.pets.size) return false; + const dt = this.robotLast ? Math.min(0.2, (now - this.robotLast) / 1000) : 0; + this.robotLast = now; + let active = false; + // the pets roam with the robots (same frames, and they rest with them on the tablet level); while every pet sits, no frames + // are drawn and a timer wakes the view when the first one walks on + let nextWalk = Infinity; + // the pets keep their own clock: the robots' one restarts whenever nothing of theirs moves, which froze a resting pet (#97) + const petElapsed = this.petLast ? (now - this.petLast) / 1000 : 0; + this.petLast = now; + for (const p of this.pets.values()) { + const fv = this.floorMap.get(p.floorId); + if (!fv) continue; + if (p.group.parent !== fv.group) fv.group.add(p.group); + const walking = advancePet(p.motion, p.room, petElapsed, p.random) || !!p.motion.target; + if (walking) active = true; + else nextWalk = Math.min(nextWalk, Math.max(0, p.motion.rest)); + p.group.position.set(p.motion.pos[0], 0, p.motion.pos[1]); + p.group.rotation.y = p.motion.heading; + } + clearTimeout(this.petTimer); + if (!active && Number.isFinite(nextWalk)) { + this.petTimer = setTimeout(() => this.invalidate(), nextWalk * 1000 + 50); + } + for (const r of this.robots.values()) { + const fv = this.floorMap.get(r.info.floorId); + if (!fv) continue; + if (r.group.parent !== fv.group) fv.group.add(r.group); + const trail = this.robotTrails.get(r.info.id); + if (trail && trail.parent !== fv.group) fv.group.add(trail); + if (dt > 0) active = stepRobot(r.motion, r.info, dt) || active; + else active ||= r.info.mode === "cleaning" || r.info.mode === "returning"; + r.group.position.set(r.motion.pos[0], r.info.y ?? 0, r.motion.pos[1]); + r.group.rotation.y = r.motion.heading; + } + if (!active) this.robotLast = 0; + return active; + } + + /** The current view (a copy), to come back to it later with flyTo. */ + getView(): OrbitView { + return { ...this.controls.view, target: this.controls.view.target.clone() }; + } + + /** Flies to a stored view whose target counts from the ground (Outside's own camera, #83). */ + showView(view: StartView, duration = 900): void { + const t = view.target ?? { x: 0, y: 0, z: 0 }; + this.controls.maxRadius = Math.max(this.controls.maxRadius, view.radius * 1.5); + this.controls.flyTo({ target: new Vector3(t.x, t.y, t.z), radius: view.radius, phi: view.phi, theta: view.theta }, duration); + } + + flyTo(view: OrbitView, duration = 900): void { + this.controls.flyTo(view, duration); + } + + /** Fly to a point of a floor (search) and let the device there flash. */ + focus(floorId: string, x: number, z: number, y: number, entityId: string | null): void { + const fv = this.floorMap.get(floorId); + if (!fv) return; + this.controls.flyTo({ target: new Vector3(x, fv.floor.elevation + fv.ty + y, z), radius: 5.5, phi: 0.78 }, 900); + if (entityId) { + this.flashes.set(entityId, performance.now() + 2400); + const pin = this.host.querySelector(`.nf-dev[data-entity="${CSS.escape(entityId)}"]`); + pin?.classList.add("nf-dev-found"); + setTimeout(() => pin?.classList.remove("nf-dev-found"), 2600); + } + this.invalidate(); + } + + private render(now: number): void { + this.frame = 0; + if (this.disposed) return; + const dt = this.lastFrame ? Math.min(100, now - this.lastFrame) : 16; + let orbiting = false; + if (this.orbitSpeed && !this.controls.active) { + if (this.orbitLast) this.controls.view.theta += (this.orbitSpeed * Math.min(100, now - this.orbitLast)) / 1000; + this.orbitLast = now; + orbiting = true; + } else this.orbitLast = 0; + const cameraMoving = this.controls.update(now); + const floorsMoving = this.stepFloors(dt); + // all three step every frame: a door swinging must not hold up a curtain + const steps = [this.stepOpenings(dt), this.stepFridges(dt), this.stepCovers(dt)]; + const openingsMoving = steps.some(Boolean); + let flashing = false; + if (this.flashes.size) { + // only the floors with a flashing lamp are recoloured (an expired flash needs one last pass) + const touched = new Set(); + for (const [id, until] of this.flashes) { + const floorId = this.deviceFloor.get(id); + if (floorId) touched.add(floorId); + if (until <= now) this.flashes.delete(id); + } + flashing = this.flashes.size > 0; + for (const fv of this.floors) if (touched.has(fv.floor.id)) this.buildLamps(fv); + } + const roofMoving = this.placeRoof(dt); + const robotsMoving = this.stepRobots(now); + // NextFloor's layers: each one steps every frame (no short-circuit), any of them moving keeps the frames coming + this.pictureLayer.step(); + const liveMoving = [this.weatherLayer, this.energyLayer, this.soundLayer, this.screenLayer, this.waterLayer].map((l) => l.step(now)); + const weatherMoving = liveMoving.some(Boolean); + const moving = cameraMoving || floorsMoving || openingsMoving || flashing || roofMoving; + const busy: string[] = []; + if (cameraMoving) busy.push("camera"); + if (floorsMoving) busy.push("floors"); + if (openingsMoving) busy.push("openings"); + if (flashing) busy.push("flash"); + if (roofMoving) busy.push("roof"); + if (this.effectTick) busy.push("effect"); + if (robotsMoving) busy.push("robot"); + if (orbiting) busy.push("orbit"); + if (this.tintTick) busy.push("tint"); + this.effectTick = this.tintTick = false; + this.lastFrame = moving ? now : 0; + if (moving && this.governor) { + const step = this.governor.frame(dt, now); + if (step && "ratio" in step) { + this.renderer.setPixelRatio(step.ratio); + this.resize(); + } else if (step) setTimeout(() => this.dropToLow(), 0); + } + this.updateWalls(); + this.renderer.render(this.scene, this.camera); + this.placeLhAnchors(); + // labels are placed only when the view or something on it moved (style writes cost layout) + if (this.viewChanged() || floorsMoving || this.labelsDirty) { + this.labelsDirty = false; + this.updateLabels(); + } + // everything that keeps drawing (also the energy flow, effects, robots) shows in the frame rate + this.reportStats(now, busy); + if (moving) this.invalidate(); + this.scheduleEffects(); + if (!moving && orbiting && !this.orbitTimer) { + // the screensaver turn: about 30 frames per second, 15 on the tablet level + this.orbitTimer = setTimeout(() => { + this.orbitTimer = undefined; + this.invalidate(); + }, this.lowQuality ? 66 : 33); + } + const resting = this.resting; + if (!moving && weatherMoving && !this.weatherTimer && !resting) { + // falling rain or snow: about 30 frames per second + this.weatherTimer = setTimeout(() => { + this.weatherTimer = undefined; + this.invalidate(); + }, 33); + } + if (!moving && robotsMoving && !this.robotTimer && !resting) { + // a driving robot: about 30 frames per second, 15 on the tablet level + this.robotTimer = setTimeout(() => { + this.robotTimer = undefined; + this.invalidate(); + }, this.lowQuality ? 66 : 33); + } + } + + /** + * Walls facing the camera: in the tall view they turn into glass (rooms stay whole, doors and windows + * stay visible); in the cut view every wall is cut at the cut height. + */ + private updateWalls(): void { + if (this.controls.walk) { + // walking among the walls: they stand whole, none turns to glass or is cut + for (const fv of this.floors) { + fv.mask.standing.value = 0xffff; + fv.mask.glass.value = 0; + fv.mask.slope?.value.set(0, 0, 0, 0); + } + return; + } + const cam = this.camera.position; + const t = this.controls.view.target; + const dx = cam.x - t.x; + const dz = cam.z - t.z; + const l = Math.hypot(dx, dz) || 1; + for (const fv of this.floors) { + // in a room, its floor's interior walls turn into glass as well + const inRoom = this.roomId !== null && fv.floor.rooms.some((r) => r.id === this.roomId); + const cut = this.wallMode === "cut"; + let glass = 0; + let lowered = 0; + fv.geo.buckets.forEach((normal, b) => { + const facing = normal ? (normal[0] * dx) / l + (normal[1] * dz) / l >= 0.25 : inRoom; + if (this.wallMode !== "auto" || !facing) return; + // solid walls never turn into glass: in a room, the walls in front of it are cut down instead (like a doll's house) + if (!this.painted) glass |= 1 << b; + else if (inRoom) lowered |= 1 << b; + }); + fv.mask.standing.value = cut ? 0 : 0xffff & ~lowered; + fv.mask.glass.value = glass; + this.slopeWalls(fv, -dx / l, -dz / l); + } + } + + /** + * The sloped view: the walls of a floor are lowered to a plane that rises away from the camera, from the cut height on + * the floor's near edge to the full height on its far edge, so the rooms in front open up and the far walls frame them. + */ + private slopeWalls(fv: FloorView, fx: number, fz: number): void { + const slope = fv.mask.slope!.value; + if (this.wallMode !== "slope" || !fv.bbox || this.controls.walk) { + slope.set(0, 0, 0, 0); + return; + } + const { x0, x1, z0, z1 } = fv.bbox; + const along = [x0 * fx + z0 * fz, x1 * fx + z0 * fz, x0 * fx + z1 * fz, x1 * fx + z1 * fz]; + // a little inside the outline, so the near wall really sits at the low end and the far wall at the high end + const [near, far] = [Math.min(...along), Math.max(...along)]; + const inset = (far - near) * 0.08; + slope.set(fx, fz, near + inset, far - inset); + fv.mask.slopeY!.value.set(Math.min(fv.floor.cut_height, fv.floor.height), fv.floor.height); + } + + /** True when the camera view differs from the last frame's. */ + private viewChanged(): boolean { + const v = this.controls.view; + const k = this.viewKey; + if (k[0] === v.target.x && k[1] === v.target.y && k[2] === v.target.z && k[3] === v.radius && k[4] === v.theta && k[5] === v.phi) return false; + k[0] = v.target.x; + k[1] = v.target.y; + k[2] = v.target.z; + k[3] = v.radius; + k[4] = v.theta; + k[5] = v.phi; + return true; + } + + /** The screen place of a point of a floor, which moves with the floor while it animates. */ + private screenPoint(point: [number, number, number], margin = 1.05): ScreenPoint { + return project(this.camera, point, this.size, margin); + } + + /** Places the floor labels (house view), the room labels, and the pins of devices and persons. */ + private updateLabels(): void { + const house = this.houseView; + const labels: (FloorLabel & { fv: FloorView })[] = []; + for (const fv of this.floors) { + const box = fv.bbox; + if (!(house && fv.o > 0.5 && box)) { + this.labelPlacer.place(fv.label, null); + continue; + } + // the corners of the floor's box at half the cut height + const y = fv.floor.elevation + fv.y + fv.floor.cut_height * 0.5; + const corners = [box.x0, box.x1].flatMap((x) => [box.z0, box.z1].map((z) => this.screenPoint([x, y, z], Infinity))); + if (fv.label.hidden) fv.label.hidden = false; + fv.labelSize ??= { w: fv.label.offsetWidth, h: fv.label.offsetHeight }; + const spot = floorLabelPosition(corners, fv.labelSize.w, { width: this.size.w, inset: this.labelInset }); + labels.push({ fv, rank: fv.rank, left: spot.left, y: spot.y, height: fv.labelSize.h }); + } + for (const label of stackFloorLabels(labels)) this.labelPlacer.place(label.fv.label, leftAt(label.left, label.y)); + this.updateDevicePins(); + for (const fv of this.floors) { + // in the house view room labels would pile up between the floors, in a room its panel names it, and floors stacked below an + // opened floor carry none + const hide = fv.to < 0.99 || fv.o < 0.9 || house || this.roomId !== null || this.otherFloor(fv); + const y = fv.floor.elevation + fv.y + 0.05; + for (const roomPin of fv.roomPins) { + const spot = hide ? null : this.screenPoint([roomPin.cx, y, roomPin.cz], 1.1); + this.labelPlacer.place(roomPin.pin, spot && !spot.off ? centredAt(spot) : null); + } + // notes stand on their floor's views (and in a room), not in the house view + const noNotes = house || fv.o < 0.9 || this.otherFloor(fv); + for (const { pin, note } of fv.notePins) { + const spot = noNotes ? null : this.screenPoint([note.x, fv.floor.elevation + fv.y + (note.y ?? NOTE_Y), note.z]); + this.labelPlacer.place(pin, spot && !spot.off ? centredAt(spot) : null); + } + } + } + + /** A floor other than the opened one (shown below it when floors are stacked). */ + private otherFloor(fv: FloorView): boolean { + return this.floorId !== null && fv.floor.id !== this.floorId; + } + + private updateDevicePins(): void { + const house = this.houseView; + for (const person of this.persons) { + const pin = this.personPins.get(person.id); + const fv = this.floorMap.get(person.floorId); + if (!pin) continue; + const spot = fv && !house && floorShowsMarkers(fv, this.otherFloor(fv)) ? this.screenPoint([person.x, fv.floor.elevation + fv.y + 0.9, person.z]) : null; + this.labelPlacer.place(pin, spot && !spot.off ? centredAt(spot) : null); + } + for (const marker of this.devices) { + const pin = this.devicePins.get(marker.id)?.el; + if (!pin) continue; + const fv = this.floorMap.get(marker.floorId); + // device markers belong to the floor and room views; the house view only shows floor labels, except what a camera detects + // right now, which deserves a pin on the whole house too, and devices outside every room set to "always" (garden valves), + // which show wherever their floor is drawn + const alert = marker.id.startsWith("detect:"); + const outdoor = !!marker.full && marker.roomId === null; + const floorOk = !!fv && (outdoor ? floorShowsOutdoorMarkers(fv) : (!house || alert) && floorShowsMarkers(fv, this.otherFloor(fv))); + const shown = !!fv && floorOk && marker.pin !== false; + const spot = shown ? this.screenPoint([marker.x, fv.floor.elevation + fv.y + marker.y, marker.z]) : null; + if (!spot || spot.off) { + this.labelPlacer.place(pin, null); + continue; + } + const mode = this.roomId === null ? (marker.full ? "full" : "") : marker.roomId === this.roomId ? "full" : "dim"; + if (this.pinMode.get(pin) !== mode) { + this.pinMode.set(pin, mode); + pin.classList.toggle("nf-dev-full", mode === "full"); + pin.classList.toggle("nf-dev-dim", mode === "dim"); + } + this.labelPlacer.place(pin, centredAt(spot)); + } + } + + private reportStats(now: number, busy: string[]): void { + if (!this.statsOn || !this.options.onStats) return; + const moving = busy.length > 0; + if (!this.fpsStart) this.fpsStart = now; + if (this.lastStatsFrame && moving) this.worstFrame = Math.max(this.worstFrame, now - this.lastStatsFrame); + this.lastStatsFrame = moving ? now : 0; + this.fpsFrames++; + const elapsed = now - this.fpsStart; + if (elapsed > 500 || !moving) { + const info = this.renderer.info.render; + this.options.onStats({ + fps: moving ? Math.round((this.fpsFrames * 1000) / elapsed) : 0, + busy, + worstMs: Math.round(this.worstFrame), + calls: info.calls, + triangles: info.triangles, + low: this.lowQuality, + pixelRatio: this.renderer.getPixelRatio(), + }); + this.fpsFrames = 0; + this.fpsStart = now; + this.worstFrame = 0; + } + } +} + +/** Pattern atlas: 3 × 2 tiles of 1 m each (wood, oak, tiles / carpet, stone, concrete), faint cyan lines. */ +function makePatternTexture(): CanvasTexture { + const T = 256; + const canvas = document.createElement("canvas"); + canvas.width = T * 3; + canvas.height = T * 2; + const ctx = canvas.getContext("2d")!; + const line = (x0: number, y0: number, x1: number, y1: number, alpha: number) => { + ctx.strokeStyle = `rgba(55,224,255,${alpha})`; + ctx.beginPath(); + ctx.moveTo(x0, y0); + ctx.lineTo(x1, y1); + ctx.stroke(); + }; + ctx.lineWidth = 1.5; + const tile = (col: number, row: number, draw: (ox: number, oy: number) => void) => { + ctx.save(); + ctx.beginPath(); + ctx.rect(col * T, row * T, T, T); + ctx.clip(); + draw(col * T, row * T); + ctx.restore(); + }; + // wood: planks 0.2 m wide along x with staggered joints + tile(0, 0, (ox, oy) => { + for (let i = 0; i < 5; i++) { + const y = oy + (i * T) / 5 + 0.75; + line(ox, y, ox + T, y, 0.09); + const j = ox + ((i * 0.37) % 1) * T; + line(j, y, j, y + T / 5, 0.07); + } + }); + // oak: narrower planks along z + tile(1, 0, (ox, oy) => { + for (let i = 0; i < 7; i++) { + const x = ox + (i * T) / 7 + 0.75; + line(x, oy, x, oy + T, 0.08); + const j = oy + ((i * 0.53) % 1) * T; + line(x, j, x + T / 7, j, 0.06); + } + }); + // tiles: 0.25 m grid + tile(2, 0, (ox, oy) => { + for (let i = 0; i < 4; i++) { + const p = (i * T) / 4 + 0.75; + line(ox + p, oy, ox + p, oy + T, 0.1); + line(ox, oy + p, ox + T, oy + p, 0.1); + } + }); + // carpet: plain (also used for slab sides) + // stone: 0.5 m slabs in a running bond + tile(1, 1, (ox, oy) => { + for (let r = 0; r < 2; r++) { + const y = oy + (r * T) / 2 + 0.75; + line(ox, y, ox + T, y, 0.09); + const shift = r ? T / 4 : 0; + for (const x of [shift, shift + T / 2]) line(ox + x + 0.75, y, ox + x + 0.75, y + T / 2, 0.09); + } + }); + // concrete: 1 m grid and a faint speckle + tile(2, 1, (ox, oy) => { + line(ox + 0.75, oy, ox + 0.75, oy + T, 0.08); + line(ox, oy + 0.75, ox + T, oy + 0.75, 0.08); + ctx.fillStyle = "rgba(55,224,255,0.05)"; + for (let i = 0; i < 90; i++) ctx.fillRect(ox + ((i * 97) % T), oy + ((i * 61 + (i * i) % 37) % T), 2, 2); + }); + const tex = new CanvasTexture(canvas); + tex.flipY = false; + tex.wrapS = ClampToEdgeWrapping; + tex.wrapT = ClampToEdgeWrapping; + tex.anisotropy = 4; + tex.colorSpace = SRGBColorSpace; + return tex; +} + +/** Blind slats: dark stripes with a faint cyan edge, repeated along v. */ +function makeBlindTexture(): CanvasTexture { + const canvas = document.createElement("canvas"); + canvas.width = 8; + canvas.height = 32; + const ctx = canvas.getContext("2d")!; + ctx.fillStyle = "#1a2742"; + ctx.fillRect(0, 0, 8, 32); + ctx.fillStyle = "#223556"; + ctx.fillRect(0, 4, 8, 14); + ctx.fillStyle = "rgba(55,224,255,0.45)"; + ctx.fillRect(0, 29, 8, 2); + const tex = new CanvasTexture(canvas); + tex.wrapS = RepeatWrapping; + tex.wrapT = RepeatWrapping; + tex.colorSpace = SRGBColorSpace; + return tex; +} + + + + +/** Zone per room index: rooms joined by "no wall" (pairs of room ids) share the lowest index among them. */ +function lightZonesOf(floor: Floor, open: [string, string][]): number[] { + const zone = floor.rooms.map((_, i) => i); + const find = (i: number): number => (zone[i] === i ? i : (zone[i] = find(zone[i]))); + for (const [a, b] of open) { + const ia = floor.rooms.findIndex((r) => r.id === a); + const ib = floor.rooms.findIndex((r) => r.id === b); + if (ia < 0 || ib < 0) continue; + const ra = find(ia); + const rb = find(ib); + if (ra !== rb) zone[Math.max(ra, rb)] = Math.min(ra, rb); + } + return zone.map((_, i) => find(i)); +} + +/** Soft round glow for the halos around lamps. */ +function makeHaloTexture(): CanvasTexture { + const size = 64; + const canvas = document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext("2d")!; + const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2); + g.addColorStop(0, "rgba(255,255,255,0.9)"); + g.addColorStop(0.2, "rgba(255,255,255,0.45)"); + g.addColorStop(0.55, "rgba(255,255,255,0.1)"); + g.addColorStop(1, "rgba(255,255,255,0)"); + ctx.fillStyle = g; + ctx.fillRect(0, 0, size, size); + const tex = new CanvasTexture(canvas); + tex.colorSpace = SRGBColorSpace; + return tex; +} + +/** Ground below the house: a wide 1 m grid that fades out towards the edges. */ +function makeGroundTexture(): CanvasTexture { + const size = 1024; + const cells = GROUND_CELLS; + const canvas = document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext("2d")!; + ctx.strokeStyle = "rgba(91,124,255,0.16)"; + ctx.lineWidth = 1; + for (let i = 0; i <= cells; i++) { + const p = Math.round((i / cells) * size) + 0.5; + ctx.beginPath(); + ctx.moveTo(p, 0); + ctx.lineTo(p, size); + ctx.moveTo(0, p); + ctx.lineTo(size, p); + ctx.stroke(); + } + // fade out radially so the grid has no hard border + ctx.globalCompositeOperation = "destination-in"; + const g = ctx.createRadialGradient(size / 2, size / 2, size * 0.12, size / 2, size / 2, size / 2); + g.addColorStop(0, "rgba(0,0,0,1)"); + g.addColorStop(1, "rgba(0,0,0,0)"); + ctx.fillStyle = g; + ctx.fillRect(0, 0, size, size); + const tex = new CanvasTexture(canvas); + tex.anisotropy = 4; + tex.colorSpace = SRGBColorSpace; + return tex; +} + +export { furniturePreview, type PreviewItem } from "./preview.ts"; + +export function createViewer(host: HTMLElement, options?: ViewerOptions): NextFloorViewer { + return new NextFloorViewer(host, options); +} + +/** Model of a lamp into a buffer (3D view and furniture previews); `H` is the ceiling height. */ +export function pushLampModel( + buf: GeoBuffer, + d: Pick & { lamp: LampModel; phase?: number }, + H: number, + shadeCol: number, +): void { + const [w, dd, h] = d.size ?? LAMP_SIZE[d.lamp]; + const base = d.base ?? 0; + const ang = (d.rotation ?? 0) * DEG; + const ca = Math.cos(ang); + const sa = Math.sin(ang); + const L = (x: number, z: number): [number, number] => [d.x + x * ca - z * sa, d.z + x * sa + z * ca]; + const cyl = (r: number, y0: number, y1: number, side: number, top: number, n = 14) => { + const poly: [number, number][] = []; + for (let i = 0; i < n; i++) { + const a = (i / n) * Math.PI * 2; + poly.push([d.x + Math.cos(a) * r, d.z + Math.sin(a) * r]); + } + pushPrism(buf, poly, y0, y1, side, top, { aoFrom: 0, bottom: true }); + }; + const box = (x0: number, x1: number, z0: number, z1: number, y0: number, y1: number, side: number, top = side) => + pushPrism(buf, [L(x0, z0), L(x1, z0), L(x1, z1), L(x0, z1)], y0, y1, side, top, { aoFrom: 0, bottom: true }); + const r = Math.max(0.05, Math.min(w, dd) / 2); + switch (d.lamp) { + case "ceiling": + cyl(r * 0.25, H - 0.04, H, LAMP_BODY, LAMP_BODY, 8); + cyl(r, H - Math.max(0.04, h) - 0.035, H - 0.04, shadeCol, shadeCol); + break; + case "pendant": { + const bottom = Math.max(0.4, H - h); + cyl(0.06, H - 0.02, H, LAMP_BODY, LAMP_BODY, 8); + const shapeTop = d.variant === "globe" ? bottom + 2 * r : d.variant === "drum" ? bottom + 0.24 : bottom + 0.2; + cyl(0.008, shapeTop, H - 0.02, LAMP_BODY, LAMP_BODY, 5); + if (d.variant === "globe") { + // stacked rings approximate a ball + const n = 7; + for (let i = 0; i < n; i++) { + const a0 = Math.PI * (i / n); + const a1 = Math.PI * ((i + 1) / n); + cyl(r * Math.max(0.2, Math.sin((a0 + a1) / 2)), bottom + r - r * Math.cos(a0), bottom + r - r * Math.cos(a1), shadeCol, shadeCol, 14); + } + } else if (d.variant === "cone") { + const n = 4; + for (let i = 0; i < n; i++) cyl(r * (0.25 + (0.75 * (n - i)) / n), bottom + 0.06 * i, bottom + 0.06 * (i + 1), shadeCol, shadeCol, 16); + } else if (d.variant === "drum") { + cyl(r, bottom, bottom + 0.24, shadeCol, shadeCol, 18); + } else { + cyl(r * 0.35, bottom + 0.14, bottom + 0.2, shadeCol, shadeCol, 12); + cyl(r, bottom, bottom + 0.14, shadeCol, shadeCol, 16); + } + break; + } + case "fan": { + // canopy at the ceiling, a downrod when it hangs lower, the motor with the blades and the light kit underneath + const bottom = Math.max(0.05, H - Math.max(0.22, h)); + const motorTop = bottom + 0.16; + cyl(0.07, H - 0.05, H, LAMP_BODY, LAMP_BODY, 10); + if (motorTop < H - 0.05) cyl(0.014, motorTop, H - 0.05, LAMP_BODY, LAMP_BODY, 6); + cyl(0.11, bottom + 0.06, motorTop, LAMP_BODY, LAMP_BODY, 14); + cyl(0.1, bottom, bottom + 0.06, shadeCol, shadeCol, 14); + const reach = Math.max(0.2, Math.min(w, dd) / 2); + const bladeY = bottom + 0.1; + for (let i = 0; i < FAN_BLADES; i++) { + const a = ((d.phase ?? 0) + i * FAN_SPACING) * DEG; + const [c, s] = [Math.cos(a), Math.sin(a)]; + // a blade: narrow at the motor, wider towards its tip + const at = (along: number, across: number): [number, number] => [d.x + along * c - across * s, d.z + along * s + across * c]; + pushPrism(buf, [at(0.1, -0.035), at(reach, -0.075), at(reach, 0.075), at(0.1, 0.035)], bladeY, bladeY + 0.012, FAN_BLADE, FAN_BLADE, { aoFrom: 0, bottom: true }); + } + break; + } + case "downlight": + // flush ring in the ceiling with a glowing lens + cyl(r, H - 0.012, H, LAMP_BODY, LAMP_BODY, 12); + cyl(r * 0.7, H - 0.02, H - 0.012, shadeCol, shadeCol, 12); + break; + case "spot": + cyl(r * 0.6, H - 0.02, H, LAMP_BODY, LAMP_BODY, 10); + cyl(r, H - Math.max(0.06, h), H - 0.02, LAMP_BODY, LAMP_BODY, 12); + cyl(r * 0.8, H - Math.max(0.06, h) - 0.008, H - Math.max(0.06, h), shadeCol, shadeCol, 12); + break; + case "panel": + box(-w / 2, w / 2, -dd / 2, dd / 2, H - Math.max(0.015, h), H, LAMP_BODY, LAMP_BODY); + box(-w / 2 + 0.02, w / 2 - 0.02, -dd / 2 + 0.02, dd / 2 - 0.02, H - Math.max(0.015, h) - 0.004, H - Math.max(0.015, h), shadeCol); + break; + case "uplight": + cyl(Math.max(0.1, r * 0.6), base, base + 0.03, LAMP_BODY, LAMP_BODY); + cyl(0.014, base + 0.03, base + h - 0.12, LAMP_BODY, LAMP_BODY, 6); + // bowl open to the top: dark outside, glowing rim + cyl(r, base + h - 0.14, base + h - 0.02, LAMP_BODY, LAMP_BODY); + cyl(r * 0.92, base + h - 0.02, base + h, shadeCol, shadeCol); + break; + case "bollard": + // path light: post with a glowing band under its cap + cyl(r, base, base + h - 0.14, LAMP_BODY, LAMP_BODY, 10); + cyl(r * 0.9, base + h - 0.14, base + h - 0.03, shadeCol, shadeCol, 10); + cyl(r * 1.1, base + h - 0.03, base + h, LAMP_BODY, LAMP_BODY, 10); + break; + case "garden": + // spike in the ground, head pointing up + cyl(0.012, base, base + h - 0.08, LAMP_BODY, LAMP_BODY, 5); + cyl(r, base + h - 0.08, base + h - 0.01, LAMP_BODY, LAMP_BODY, 10); + cyl(r * 0.8, base + h - 0.01, base + h, shadeCol, shadeCol, 10); + break; + case "floor": + cyl(Math.max(0.1, r * 0.7), base, base + 0.03, LAMP_BODY, LAMP_BODY); + cyl(0.014, base + 0.03, base + h - 0.28, LAMP_BODY, LAMP_BODY, 6); + cyl(r, base + h - 0.3, base + h, shadeCol, shadeCol); + break; + case "table": + cyl(Math.max(0.05, r * 0.55), base, base + 0.03, LAMP_BODY, LAMP_BODY); + cyl(0.012, base + 0.03, base + h - 0.16, LAMP_BODY, LAMP_BODY, 6); + cyl(r, base + h - 0.18, base + h, shadeCol, shadeCol); + break; + case "wall": { + // plate on the wall (back at -z) and a glowing shade in front of it + const y0 = d.base ?? WALL_LAMP_Y; + box(-w / 2 + 0.03, w / 2 - 0.03, -dd / 2, -dd / 2 + 0.02, y0, y0 + h, LAMP_BODY); + box(-w / 2, w / 2, -dd / 2 + 0.02, dd / 2, y0 + h * 0.15, y0 + h * 0.85, shadeCol); + break; + } + case "strip": { + // a thin bar along the wall: under the ceiling (cove light) or at its mount height; tilted about its + // length it lies against a slope, standing upright it climbs from its mount height + const t = Math.max(0.02, h); + const y1 = d.base != null ? d.base + t : H - 0.04; + const rise = d.upright ? 0 : (d.rise ?? 0) * DEG; + if (!d.roll && !d.upright && !rise) { + box(-w / 2, w / 2, -dd / 2, dd / 2, y1 - t, y1, shadeCol); + break; + } + const roll = (d.roll ?? 0) * DEG; + const cr = Math.cos(roll); + const sr = Math.sin(roll); + const [ce, se] = [Math.cos(rise), Math.sin(rise)]; + const cy = d.upright ? base + w / 2 : y1 - t / 2 + stripRiseLift(d.base, w, d.rise); + // local: x along the length, y through the thickness, z across the depth + const P = (lx: number, ly: number, lz: number): number[] => { + let x = lx; + let y = ly * cr - lz * sr; + const z = ly * sr + lz * cr; + if (d.upright) [x, y] = [-y, x]; + else if (rise) [x, y] = [x * ce - y * se, x * se + y * ce]; + return [d.x + x * ca - z * sa, cy + y, d.z + x * sa + z * ca]; + }; + const c = [P(-w / 2, -t / 2, -dd / 2), P(w / 2, -t / 2, -dd / 2), P(w / 2, -t / 2, dd / 2), P(-w / 2, -t / 2, dd / 2), P(-w / 2, t / 2, -dd / 2), P(w / 2, t / 2, -dd / 2), P(w / 2, t / 2, dd / 2), P(-w / 2, t / 2, dd / 2)]; + const col = new Color(shadeCol); + const centre = [d.x, cy, d.z]; + const quad = (i: number, j: number, k: number, l: number) => { + // wound so the face looks outward + const [a, b, e] = [c[i], c[j], c[k]]; + const n = [(b[1] - a[1]) * (e[2] - a[2]) - (b[2] - a[2]) * (e[1] - a[1]), (b[2] - a[2]) * (e[0] - a[0]) - (b[0] - a[0]) * (e[2] - a[2]), (b[0] - a[0]) * (e[1] - a[1]) - (b[1] - a[1]) * (e[0] - a[0])]; + const out = [a[0] - centre[0], a[1] - centre[1], a[2] - centre[2]]; + const flip = n[0] * out[0] + n[1] * out[1] + n[2] * out[2] < 0; + const [p, q, r, s] = flip ? [c[l], c[k], c[j], c[i]] : [c[i], c[j], c[k], c[l]]; + buf.tri(p, q, r, col, col, col); + buf.tri(p, r, s, col, col, col); + }; + quad(0, 1, 2, 3); + quad(4, 5, 6, 7); + quad(0, 1, 5, 4); + quad(1, 2, 6, 5); + quad(2, 3, 7, 6); + quad(3, 0, 4, 7); + break; + } + } +} diff --git a/frontend/src/weather.test.ts b/frontend/src/weather.test.ts new file mode 100644 index 0000000..a78ef7f --- /dev/null +++ b/frontend/src/weather.test.ts @@ -0,0 +1,26 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { HomeAssistant } from "./types.ts"; +import { weatherEntity } from "./weather.ts"; + +function hassWith(state: string, attributes: Record = {}): HomeAssistant { + return { + language: "de", + connection: {} as HomeAssistant["connection"], + callWS: async () => undefined as never, + callService: async () => undefined, + areas: {}, + devices: {}, + entities: {}, + states: { + "weather.zuhause": { entity_id: "weather.zuhause", state, attributes }, + "weather.arbeit": { entity_id: "weather.arbeit", state: "sunny", attributes: {} }, + }, + }; +} + +test("the preferred weather entity wins, otherwise the first one by id", () => { + assert.equal(weatherEntity(hassWith("sunny")), "weather.arbeit"); + assert.equal(weatherEntity(hassWith("sunny"), "weather.zuhause"), "weather.zuhause"); + assert.equal(weatherEntity(hassWith("sunny"), "weather.missing"), "weather.arbeit"); +}); diff --git a/frontend/src/weather.ts b/frontend/src/weather.ts new file mode 100644 index 0000000..29fe684 --- /dev/null +++ b/frontend/src/weather.ts @@ -0,0 +1,12 @@ +/** Which `weather.*` entity the house uses (the 3D weather layer, the rain warning). */ +import type { HomeAssistant } from "./types.ts"; + +/** The weather entity to show: the preferred one when it exists, otherwise the first `weather.*`. */ +export function weatherEntity(hass: HomeAssistant, preferred?: string | null): string | null { + if (preferred && hass.states[preferred]) return preferred; + return ( + Object.keys(hass.states) + .filter((id) => id.startsWith("weather.")) + .sort()[0] ?? null + ); +} diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json new file mode 100644 index 0000000..44b35d6 --- /dev/null +++ b/frontend/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "types": ["node"], + "strict": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "erasableSyntaxOnly": true, + "verbatimModuleSyntax": true, + "useDefineForClassFields": true, + "skipLibCheck": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src/**/*.ts"] +} diff --git a/frontend/tutorial/README.md b/frontend/tutorial/README.md new file mode 100644 index 0000000..75abff6 --- /dev/null +++ b/frontend/tutorial/README.md @@ -0,0 +1,28 @@ +# Tutorial recorder + +Records a step-by-step video of setting up NextFloor from the empty start, in the online demo (invented devices, nothing real is touched), +together with a German and an English transcript. The video is silent; the transcript is meant for a voice-over. + +How it works: a headless Chrome drives the demo like a user would (real mouse and keys), and a screenshot is taken after each small step. +The video is a list of stills with durations, so slow work costs nothing in the video. The narration is a list of segments; each lasts at +least as long as its text takes to speak. + +``` +cd frontend +node tutorial/record.mjs all # every episode in order (about half an hour) +node tutorial/record.mjs 5 # one episode again (it starts from the plan the one before left in state/) +node tutorial/build.mjs # video, subtitles, transcripts, chapters, narration.json, narration..txt +LANG_UI=de node tutorial/record.mjs all && LANG_UI=de node tutorial/build.mjs # the app in German in the picture +``` + +Output (default `frontend/tutorial/out//`, set `OUT` to change it): `nextfloor-tutorial..mp4`, `nextfloor-tutorial.{de,en}.{srt,vtt}`, +`transcript.{de,en}.md`, `narration.{de,en}.txt` (one numbered text per segment, for text-to-speech), `narration.json`, `chapters.txt`. + +Voice-over: make one audio file per segment named by its number (`001.mp3` …), then +`node tutorial/voiceover.mjs [de|en]`. Segments that are spoken longer than planned hold the picture a little longer. + +Writing an episode: `episodes/NN-name.mjs` exports `title`, optionally `query` (extra demo parameters) and `keepState`, and `run(r)`. +Use `r.say({de, en})` for narration, `r.click / drag / typeInto / choose / pick`, `r.show(seconds)` to let the picture stand, `r.spotAt` to +frame something. Texts of the app are looked up by their i18n key (`python3 tutorial/key.py "Add floor"` finds the key), so the same script +records the app in either language. For development: `SCRATCH=/tmp/x.mjs FROM= node tutorial/record.mjs scratch` runs a throw-away +episode from the plan an episode left, and `r.dump()` prints what is on screen. diff --git a/frontend/tutorial/build.mjs b/frontend/tutorial/build.mjs new file mode 100644 index 0000000..24e59a8 --- /dev/null +++ b/frontend/tutorial/build.mjs @@ -0,0 +1,55 @@ +// Puts the recorded episodes together: one video (silent), subtitles and a transcript in German and English, the chapter list, and +// narration.json (every segment with its start, end and both texts) for the voice-over. +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +const lang = process.env.LANG_UI === "de" ? "de" : "en"; +const root = process.env.OUT ?? `${import.meta.dirname}/out/${lang}`; +const ffmpeg = execFileSync("python3", ["-c", "import imageio_ffmpeg;print(imageio_ffmpeg.get_ffmpeg_exe())"]).toString().trim(); +const episodes = readdirSync(root).filter((d) => /^ep\d+$/.test(d)).sort(); + +const clock = (s, comma) => { + const ms = Math.round(s * 1000); + const p = (n, w = 2) => String(n).padStart(w, "0"); + return `${p(Math.floor(ms / 3600000))}:${p(Math.floor(ms / 60000) % 60)}:${p(Math.floor(ms / 1000) % 60)}${comma ? "," : "."}${p(ms % 1000, 3)}`; +}; +const short = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`; + +let offset = 0; +const concat = []; +const segments = []; +const chapters = []; +for (const ep of episodes) { + const data = JSON.parse(readFileSync(join(root, ep, `${ep}.segments.json`), "utf8")); + for (const line of readFileSync(join(root, ep, `${ep}.concat.txt`), "utf8").split("\n")) { + concat.push(line.startsWith("file '") ? `file '${join(root, ep, line.slice(6, -1))}'` : line); + } + for (const s of data.segments) segments.push({ ...s, start: s.start + offset, end: s.end + offset, episode: ep }); + for (const c of data.chapters) chapters.push({ ...c, start: c.start + offset, episode: ep }); + offset += data.seconds; +} +// ffmpeg's concat needs the last file twice and no duplicate trailing duration +writeFileSync(join(root, "all.concat.txt"), concat.join("\n") + "\n"); +const mp4 = join(root, `nextfloor-tutorial.${lang}.mp4`); +execFileSync(ffmpeg, ["-y", "-f", "concat", "-safe", "0", "-i", join(root, "all.concat.txt"), "-vf", "fps=30,format=yuv420p", "-c:v", "libx264", "-preset", "medium", "-crf", "20", "-movflags", "+faststart", mp4], { stdio: "ignore" }); + +for (const l of ["de", "en"]) { + writeFileSync(join(root, `nextfloor-tutorial.${l}.srt`), segments.map((s, i) => `${i + 1}\n${clock(s.start, true)} --> ${clock(s.end, true)}\n${s[l]}\n`).join("\n")); + writeFileSync(join(root, `nextfloor-tutorial.${l}.vtt`), "WEBVTT\n\n" + segments.map((s) => `${clock(s.start)} --> ${clock(s.end)}\n${s[l]}\n`).join("\n")); + const lines = [`# ${l === "de" ? "NextFloor von Grund auf einrichten – Transkript" : "Setting up NextFloor from scratch – transcript"}`, ""]; + let chapter = -1; + for (const s of segments) { + const c = chapters.filter((x) => x.start <= s.start + 0.01).length - 1; + if (c !== chapter && chapters[c]) { + chapter = c; + lines.push("", `## ${chapters[c].title[l]} (${short(chapters[c].start)})`, ""); + } + lines.push(`**[${short(s.start)}]** ${s[l]}`, ""); + } + writeFileSync(join(root, `transcript.${l}.md`), lines.join("\n")); +} +for (const l of ["de", "en"]) writeFileSync(join(root, `narration.${l}.txt`), segments.map((s, i) => `${String(i + 1).padStart(3, "0")}: ${s[l]}`).join("\n\n") + "\n"); +writeFileSync(join(root, "chapters.txt"), chapters.map((c) => `${short(c.start)} ${c.title.en}`).join("\n") + "\n"); +writeFileSync(join(root, "narration.json"), JSON.stringify({ seconds: offset, segments: segments.map((s, i) => ({ id: i + 1, start: +s.start.toFixed(2), end: +s.end.toFixed(2), de: s.de, en: s.en })) }, null, 1)); +console.log(`${mp4}: ${short(offset)} (${segments.length} segments, ${chapters.length} chapters)`); diff --git a/frontend/tutorial/episodes/01-first-steps.mjs b/frontend/tutorial/episodes/01-first-steps.mjs new file mode 100644 index 0000000..20ee228 --- /dev/null +++ b/frontend/tutorial/episodes/01-first-steps.mjs @@ -0,0 +1,125 @@ +export const title = { en: "First steps: the interface and the first floor", de: "Erste Schritte: Oberfläche und die erste Etage" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + // ------------------------------------------------------------------ 1. the empty start + await r.chapter({ en: "Welcome to NextFloor", de: "Willkommen bei NextFloor" }, { en: "Setting up a home from scratch", de: "Ein Zuhause von Grund auf einrichten" }); + r.say(S( + "Willkommen! In diesem Video richten wir NextFloor komplett von Grund auf ein. Wir starten genau dort, wo du nach der Installation zum ersten Mal das Panel öffnest: Es ist noch nichts gezeichnet, die Seite ist leer.", + "Welcome! In this video we set up NextFloor completely from scratch. We start exactly where you are after the installation, the first time you open the panel: nothing is drawn yet, the page is empty.", + )); + await r.show(1); + r.say(S( + "NextFloor zeichnet dein Zuhause direkt in Home Assistant und zeigt es als lebendiges 3D-Modell. Lichter leuchten in ihrer Farbe, Rollläden bewegen sich, und du kannst alles direkt im Modell bedienen. Dafür brauchst du nur deinen Grundriss und ein paar Minuten.", + "NextFloor draws your home right inside Home Assistant and shows it as a living 3D model. Lights glow in their colours, blinds move, and you can control everything straight in the model. All it needs is your floor plan and a few minutes.", + )); + await r.show(1); + + // ------------------------------------------------------------------ 2. the three tabs + r.say(S( + "Oben links findest du drei Reiter. Der erste ist die 3D-Ansicht: Das ist das Modell deines Hauses, so wie du es später jeden Tag benutzt.", + "Top left there are three tabs. The first is the 3D view: the model of your house, the way you will use it every day.", + )); + await r.spotAt({ text: "3D" }); + await r.point({ text: "3D" }); + await r.show(0.5); + r.say(S( + "Der zweite Reiter ist der Editor. Hier zeichnest du Räume, setzt Türen, Fenster und Möbel und verbindest alles mit deinen Geräten. Den Editor sehen nur Administratoren.", + "The second tab is the editor. This is where you draw rooms, place doors, windows and furniture, and connect everything to your devices. Only administrators see the editor.", + )); + await r.spotAt({ key: "ext_tab" === "" ? "x" : undefined, text: "Editor" }); + await r.point({ text: "Editor" }); + await r.show(0.5); + r.say(S( + "Der dritte Reiter heißt Erweiterungen. Dort lädst du später eigene 3D-Modelle hoch, zum Beispiel für dein Auto. Dazu kommen wir in einem eigenen Kapitel.", + "The third tab is called Extensions. That is where you upload your own 3D models later, for example for your car. We will get to that in a chapter of its own.", + )); + await r.spotAt({ text: "✦ Extensions" }); + await r.point({ text: "✦ Extensions" }); + await r.show(0.5); + await r.spot(null); + + // ------------------------------------------------------------------ 3. open the editor + r.say(S( + "Mitten auf der Seite steht der Hinweis, dass es noch keinen Grundriss gibt. Mit einem Klick auf „Editor öffnen“ geht es los.", + "In the middle of the page a note says there is no floor plan yet. One click on “Open editor” gets us started.", + )); + await r.show(0.8); + await r.click({ key: "open_editor" }); + await r.show(1); + + await r.chapter({ en: "The editor at a glance", de: "Der Editor im Überblick" }, { en: "Tools, floors and settings", de: "Werkzeuge, Etagen und Einstellungen" }); + r.say(S( + "So sieht der Editor aus. Oben links ist die Werkzeugleiste: Auswählen, Rechteck, Freie Form, Wand, Türen und Fenster, Möbel, Außen, Bodenöffnung, Dach und Energie. Jedes Werkzeug lernen wir der Reihe nach kennen.", + "This is the editor. Top left is the toolbar: Select, Rectangle, Free shape, Wall, Doors and windows, Furniture, Outdoor, Floor opening, Roof and Energy. We get to know each tool in turn.", + )); + await r.spotUnion([{ key: "tool_select" }, { key: "tool_rect" }, { text: "Energy" }]); + await r.show(1); + r.say(S( + "Die zweite Leiste enthält Rückgängig und Wiederholen, „Alles zeigen“ passt den Plan ins Fenster, „3D daneben“ blendet die 3D-Ansicht neben dem Plan ein, und mit dem Schloss sperrst du den Grundriss gegen versehentliches Verschieben.", + "The second bar holds Undo and Redo; “Show all” fits the plan into the window, “3D beside” shows the 3D view next to the plan, and the lock protects the floor plan against accidental moves.", + )); + await r.spotUnion([{ key: "undo" }, { key: "lock_plan" }]); + await r.show(1); + await r.spot(null); + r.say(S( + "Rechts steht die Seitenleiste. Sie zeigt immer das, was gerade ausgewählt ist, und ganz oben die Etagen deines Hauses. Da der Plan leer ist, sehen wir hier noch nicht viel.", + "On the right is the side panel. It always shows whatever is selected, and at the very top the floors of your house. Since the plan is empty, there is not much to see yet.", + )); + await r.show(1); + + // ------------------------------------------------------------------ 4. the first floor + await r.chapter({ en: "The first floor", de: "Die erste Etage" }, { en: "Floors from Home Assistant", de: "Etagen aus Home Assistant" }); + r.say(S( + "Alle Werkzeuge sind noch ausgegraut, denn zuerst brauchen wir eine Etage. Wir klicken auf „Etage hinzufügen“.", + "All tools are greyed out because we need a floor first. We click “Add floor”.", + )); + await r.show(0.6); + await r.click({ key: "add_floor" }); + await r.show(0.8); + r.say(S( + "NextFloor zeigt dir jetzt die Etagen, die in Home Assistant angelegt sind. Wenn du eine davon wählst, bleiben Plan und Home Assistant verbunden: Die Räume können später ihren Bereichen zugeordnet werden. Alternativ legst du mit „Leere Etage“ eine Etage ohne Verbindung an.", + "NextFloor now lists the floors that exist in Home Assistant. If you pick one of them, the plan and Home Assistant stay connected: rooms can be assigned to their areas later. Alternatively “Empty floor” creates a floor with no connection.", + )); + await r.show(1); + r.say(S( + "Wir nehmen das Erdgeschoss aus Home Assistant.", + "We take the ground floor from Home Assistant.", + )); + await r.click({ text: "Erdgeschoss" }); + await r.show(1); + + r.say(S( + "Die Etage ist da, und die Werkzeuge sind jetzt aktiv. Rechts siehst du die Einstellungen der Etage. Oben steht der Name. Du kannst ihn jederzeit ändern, auch wenn er mit dem Namen in Home Assistant übereinstimmt.", + "The floor is there and the tools are active. On the right you see the settings of the floor. At the top is the name. You can change it any time, even if it matches the name in Home Assistant.", + )); + await r.spotAt({ css: "nf-editor input[type=text]", nth: 0 }).catch(() => {}); + await r.show(1); + await r.spot(null); + r.say(S( + "Die Höhe über dem Boden legt fest, wo die Etage im Haus steht. Das Erdgeschoss steht auf null, das Obergeschoss später auf etwa 2,8 Meter. Mit „Etage verschieben“ schiebst du die ganze Etage um einen Betrag, und „90° drehen“ dreht sie.", + "The elevation sets where the floor stands in the house. The ground floor stands at zero, the upper floor later at about 2.8 metres. “Shift the floor” moves the whole floor by an amount, and “Turn 90°” rotates it.", + )); + await r.spotAt({ key: "elevation" }); + await r.show(1.2); + await r.spotAt({ key: "floor_turn" }); + await r.show(0.8); + await r.spot(null); + r.say(S( + "Die Raumhöhe gilt für alle Wände der Etage. Standard sind zwei Komma fünf Meter. Für einzelne Wände kannst du sie später anpassen.", + "The ceiling height applies to all walls of the floor. The default is two point five metres. You can adjust it for single walls later.", + )); + await r.spotAt({ key: "height" }); + await r.show(1); + await r.spot(null); + r.say(S( + "Mit „Etage in Home Assistant“ legst du fest, zu welcher Etage in Home Assistant diese Etage gehört. Und mit „Räume aus HA-Bereichen anlegen“ erzeugt NextFloor für jeden Bereich einen Raum. Das ist praktisch, wir zeichnen die Räume aber selbst, damit du siehst, wie es geht.", + "“Floor in Home Assistant” sets which Home Assistant floor this floor belongs to. And “Add rooms from HA areas” creates a room for every area. That is handy, but we will draw the rooms ourselves so you can see how it works.", + )); + await r.spotAt({ key: "ha_floor" }); + await r.show(1); + await r.spotAt({ key: "area_rooms", vars: { n: 6 } }); + await r.show(1); + await r.spot(null); +} diff --git a/frontend/tutorial/episodes/02-rooms.mjs b/frontend/tutorial/episodes/02-rooms.mjs new file mode 100644 index 0000000..c85a11d --- /dev/null +++ b/frontend/tutorial/episodes/02-rooms.mjs @@ -0,0 +1,169 @@ +export const title = { en: "Drawing rooms", de: "Räume zeichnen" }; + +const S = (de, en) => ({ de, en }); +const NAMES = { + en: { living: "Living room", kitchen: "Kitchen", bedroom: "Bedroom", bath: "Bathroom", hall: "Hallway" }, + de: { living: "Wohnzimmer", kitchen: "Küche", bedroom: "Schlafzimmer", bath: "Bad", hall: "Flur" }, +}; + +export async function run(r) { + const n = NAMES[r.lang]; + const plan = (x, z) => r.planPoint(x, z); + const rect = async (x1, z1, x2, z2) => r.drag(await plan(x1, z1), await plan(x2, z2)); + const nameIt = (name) => r.typeInto({ label: "room_name" }, name); + + // the previous episode ended in the editor with the floor selected; a new page starts in 3D, so we go back (not filmed) + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + await r.chapter({ en: "Drawing rooms", de: "Räume zeichnen" }, { en: "The rectangle tool", de: "Das Rechteck-Werkzeug" }); + r.say(S( + "Jetzt zeichnen wir die Räume. Das schnellste Werkzeug ist das Rechteck. Wir wählen es in der Werkzeugleiste aus.", + "Now we draw the rooms. The fastest tool is the rectangle. We pick it in the toolbar.", + )); + await r.click({ key: "tool_rect" }); + await r.show(0.5); + r.say(S( + "Unten links steht immer ein kurzer Hinweis zum aktiven Werkzeug. Beim Rechteck heißt er: Ziehen, um ein Rechteck zu zeichnen.", + "At the bottom left there is always a short hint for the active tool. For the rectangle it says: drag to draw a rectangle.", + )); + await r.spotAt({ css: "nf-editor .nf-hint, nf-editor [class*=hint]" }).catch(() => {}); + await r.show(1); + await r.spot(null); + + r.say(S( + "Wir beginnen mit dem Wohnzimmer. Wir drücken an der linken oberen Ecke, ziehen zur rechten unteren Ecke und lassen los. Während des Ziehens zeigt NextFloor die Seitenlängen an. Die Maße rasten auf das Raster ein, standardmäßig auf fünf Zentimeter.", + "We start with the living room. We press at the top left corner, drag to the bottom right corner and let go. While dragging, NextFloor shows the side lengths. The sizes snap to the grid, by default to five centimetres.", + )); + await rect(0, 0, 6, 4.6); + await r.show(1); + + r.say(S( + "Der Raum ist gezeichnet und gleich ausgewählt. Das Werkzeug ist wieder auf „Auswählen“ gesprungen. Rechts erscheinen die Eigenschaften des Raums. Als Erstes geben wir ihm einen Namen.", + "The room is drawn and selected right away. The tool has jumped back to “Select”. On the right the properties of the room appear. First we give it a name.", + )); + await r.show(0.8); + await nameIt(n.living); + r.say(S( + "Mit dem Bereich verbindest du den Raum mit Home Assistant. Alle Geräte, die in Home Assistant diesem Bereich zugeordnet sind, kann NextFloor dann automatisch in diesem Raum anzeigen. Wir wählen den Bereich Wohnzimmer.", + "With the area you connect the room to Home Assistant. All devices assigned to this area in Home Assistant can then be shown in this room automatically. We choose the area Wohnzimmer.", + )); + await r.choose({ label: "area" }, "Wohnzimmer"); + r.say(S( + "Das Material bestimmt, wie der Boden in 3D aussieht: Holz, Eiche, Fliesen, Teppich, Stein oder Beton. Das Wohnzimmer bekommt Eichenparkett.", + "The material decides how the floor looks in 3D: wood, oak, tiles, carpet, stone or concrete. The living room gets oak parquet.", + )); + await r.choose({ label: "floor" }, r.lang === "de" ? "Eiche" : "Oak"); + await r.show(0.8); + + r.say(S( + "Darunter stehen Position und Größe des Raums in Metern. Du kannst die Zahlen direkt eintippen, wenn du es genau haben willst. Wir lassen sie, wie sie sind: sechs mal vier Komma sechs Meter.", + "Below are the position and size of the room in metres. You can type the numbers directly if you want it exact. We leave them as they are: six by four point six metres.", + )); + await r.spotUnion([{ label: "width" }, { label: "depth" }]); + await r.show(1.2); + await r.spot(null); + + // ------------------------------------------------------------------ corners + await r.chapter({ en: "Corners and edges", de: "Ecken und Kanten" }, { en: "Reshaping a room", de: "Einen Raum umformen" }); + r.say(S( + "Jede Ecke des ausgewählten Raums hat einen Griff. Wenn du an einem Griff ziehst, wandert die Ecke. Probieren wir es aus: Wir ziehen die rechte obere Ecke ein Stück nach oben.", + "Every corner of the selected room has a handle. Dragging a handle moves the corner. Let us try it: we drag the top right corner up a little.", + )); + const corner = await plan(6, 0); + await r.drag(corner, { x: corner.x + 30, y: corner.y - 40 }); + await r.show(1); + r.say(S( + "Das war nur ein Versuch, deshalb machen wir es mit „Rückgängig“ ungeschehen. Fast alles im Editor lässt sich rückgängig machen, auch mit Strg plus Z.", + "That was only a test, so we undo it with “Undo”. Almost everything in the editor can be undone, also with Ctrl plus Z.", + )); + await r.click({ key: "undo" }); + await r.show(1); + r.say(S( + "In der Mitte jeder Kante sitzt ein Plus. Ein Klick darauf fügt eine zusätzliche Ecke ein, mit der du Räume mit Nischen oder schrägen Wänden formst. Auch das nehmen wir gleich wieder zurück.", + "In the middle of every edge there is a plus. A click on it inserts an additional corner, with which you shape rooms with niches or slanted walls. We take that back as well.", + )); + const mid = await plan(3, 0); + await r.click({ x: mid.x, y: mid.y }); + await r.show(1); + await r.click({ key: "undo" }); + await r.show(0.8); + + // ------------------------------------------------------------------ the next rooms + await r.chapter({ en: "More rooms", de: "Weitere Räume" }, { en: "Walls are shared", de: "Wände werden geteilt" }); + r.say(S( + "Jetzt kommt die Küche rechts neben das Wohnzimmer. Wir wählen wieder das Rechteck und ziehen. Die Ecken rasten an den vorhandenen Wänden ein, und die Wand dazwischen gehört beiden Räumen.", + "Now the kitchen goes to the right of the living room. We pick the rectangle again and drag. The corners snap to the existing walls, and the wall in between belongs to both rooms.", + )); + await r.click({ key: "tool_rect" }); + await rect(6, 0, 10, 4.6); + await nameIt(n.kitchen); + await r.choose({ label: "area" }, "Küche"); + await r.choose({ label: "floor" }, r.lang === "de" ? "Fliesen" : "Tiles"); + await r.show(0.8); + + r.say(S( + "Unter dem Wohnzimmer liegt das Schlafzimmer. Es bekommt den Bereich Schlafzimmer und einen Teppichboden.", + "Below the living room is the bedroom. It gets the area Schlafzimmer and a carpet floor.", + )); + await r.click({ key: "tool_rect" }); + await rect(0, 4.6, 4.4, 8); + await nameIt(n.bedroom); + await r.choose({ label: "area" }, "Schlafzimmer"); + await r.choose({ label: "floor" }, r.lang === "de" ? "Teppich" : "Carpet"); + await r.show(0.8); + + r.say(S( + "Daneben das Bad, wieder mit Fliesen.", + "Next to it the bathroom, with tiles again.", + )); + await r.click({ key: "tool_rect" }); + await rect(4.4, 4.6, 6.8, 8); + await nameIt(n.bath); + await r.choose({ label: "area" }, "Bad"); + await r.choose({ label: "floor" }, r.lang === "de" ? "Fliesen" : "Tiles"); + await r.show(0.8); + + // ------------------------------------------------------------------ free shape + await r.chapter({ en: "Free shapes", de: "Freie Form" }, { en: "Rooms that are not rectangles", de: "Räume, die kein Rechteck sind" }); + r.say(S( + "Nicht jeder Raum ist ein Rechteck. Der Flur bekommt eine L-Form. Dafür gibt es das Werkzeug „Freie Form“.", + "Not every room is a rectangle. The hallway gets an L shape. For that there is the “Free shape” tool.", + )); + await r.click({ key: "tool_polygon" }); + r.say(S( + "Hier setzt du Punkt für Punkt die Ecken des Raums. Zum Schließen tippst du auf den ersten Punkt oder drückst Enter. Mit Escape brichst du ab.", + "Here you place the corners of the room one by one. To close it, tap the first corner or press Enter. Escape cancels.", + )); + for (const [x, z] of [[6.8, 4.6], [10, 4.6], [10, 8], [8.4, 8], [8.4, 9.2], [6.8, 9.2]]) { + const p = await plan(x, z); + await r.click({ x: p.x, y: p.y }, { settle: 300, after: 0.2 }); + } + await r.key("Enter", { frames: 3 }); + await r.show(1); + await nameIt(n.hall); + await r.choose({ label: "area" }, "Flur"); + await r.choose({ label: "floor" }, r.lang === "de" ? "Eiche" : "Oak"); + await r.show(1); + + // ------------------------------------------------------------------ walls + await r.chapter({ en: "Walls", de: "Wände" }, { en: "Heights and thickness", de: "Höhe und Dicke" }); + r.say(S( + "Die Wände entstehen automatisch aus den Raumkanten. Außenwände sind standardmäßig vierundzwanzig Zentimeter dick, Innenwände zwölf. Das stellst du unter Einstellungen ein. Für einzelne Wände findest du im Raum-Formular einen Bereich „Wandhöhen“.", + "The walls are created automatically from the room edges. Exterior walls are twenty-four centimetres thick by default, interior walls twelve. You set that under Settings. For single walls the room form has a section called “Wall heights”.", + )); + r.say(S("Zuerst passen wir die Ansicht an: „Alles zeigen“ rückt den ganzen Plan ins Fenster.", "First we adjust the view: “Show all” fits the whole plan into the window.")); + await r.click({ key: "fit" }); + await r.show(0.8); + const inside = await plan(3, 2.3); + await r.click({ x: inside.x, y: inside.y }); + await r.show(0.8); + await r.spotAt({ css: ".nf-wallbox, [class*=wall]", nth: 0 }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(1.5); + await r.spot(null); + r.say(S( + "Dort hat jede Wand eine Höhe, eine Dicke und eine Schere, mit der du eine Wand in Teile schneidest. Setzt du die Höhe niedriger, wird aus der Wand eine Brüstung oder eine Theke. „Keine Wand“ lässt die Kante offen, zum Beispiel zwischen Wohnzimmer und Essbereich.", + "There every wall has a height, a thickness and a pair of scissors with which you cut a wall into parts. A lower height turns the wall into a parapet or a counter. “No wall” leaves the edge open, for example between living room and dining area.", + )); + await r.show(2); +} diff --git a/frontend/tutorial/episodes/02b-drawing-aids.mjs b/frontend/tutorial/episodes/02b-drawing-aids.mjs new file mode 100644 index 0000000..b05a879 --- /dev/null +++ b/frontend/tutorial/episodes/02b-drawing-aids.mjs @@ -0,0 +1,70 @@ +export const title = { en: "Drawing aids: partitions, gaps and templates", de: "Zeichenhilfen: Trennwände, Lücken und Vorlagen" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const plan = (x, z) => r.planPoint(x, z); + const L = (de, en) => (r.lang === "de" ? de : en); + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + + await r.chapter({ en: "Free-standing walls", de: "Freistehende Wände" }, { en: "Partitions and half walls", de: "Trennwände und halbe Wände" }); + r.say(S( + "Nicht jede Wand gehört zu einem Raum. Eine Trennwand mitten im Wohnzimmer, eine halbe Wand zum Essbereich oder eine Brüstung zeichnest du mit dem Werkzeug „Wand“.", + "Not every wall belongs to a room. A partition in the middle of the living room, a half wall towards the dining area or a parapet you draw with the “Wall” tool.", + )); + await r.click({ key: "tool_wall" }); + r.say(S( + "Der Hinweis unten: Ziehen, um eine einzelne Wand zu zeichnen. Mit der Umschalt-Taste bleibt sie gerade, mit Alt rastet sie nicht ein. Wir ziehen eine kurze Wand.", + "The hint at the bottom: drag to draw a single wall. With the Shift key it stays straight, with Alt it does not snap. We drag a short wall.", + )); + await r.drag(await plan(1, 2.3), await plan(1, 4.5)); + await r.show(1); + r.say(S( + "Die Wand ist ausgewählt. Im Formular stellst du Länge, Dicke und Höhe ein. Eine niedrigere Höhe macht aus ihr eine halbe Wand oder Brüstung. Wo sie auf eine Raumwand trifft, wird die Ecke sauber verbunden. An den Griffen verschiebst du die Enden, und an der Linie die ganze Wand.", + "The wall is selected. In the form you set length, thickness and height. A lower height turns it into a half wall or parapet. Where it meets a room wall, the corner is joined cleanly. At the handles you move the ends, and at the line the whole wall.", + )); + await r.spotUnion([{ label: "wall_thickness" }, { label: "height_m" }]).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); + r.say(S( + "Für unser Haus brauchen wir sie nicht, deshalb löschen wir sie mit „Löschen“ wieder.", + "We do not need it for our house, so we delete it again with “Delete”.", + )); + await r.click({ text: L("Löschen", "Delete") }); + await r.show(1); + + await r.chapter({ en: "Gaps and the lock", de: "Lücken und die Sperre" }, { en: "Keeping the plan tidy", de: "Den Plan sauber halten" }); + r.say(S( + "Zeichnest du Räume von Hand, bleiben manchmal winzige Lücken zwischen zwei Wänden, die man kaum sieht, in 3D aber als Spalt auftauchen. Dafür gibt es im Etagen-Formular „Lücken schließen“. NextFloor sucht solche Stellen und zieht die Wände zusammen.", + "If you draw rooms by hand, tiny gaps sometimes remain between two walls, hardly visible but showing up as a slit in 3D. For that there is “Close gaps” in the floor form. NextFloor looks for such places and pulls the walls together.", + )); + await r.click({ key: "back_to_floor" }).catch(() => {}); + await r.spotAt({ text: L("Lücken schließen", "Close gaps") }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); + r.say(S( + "Ist der Plan fertig, sperrst du ihn mit dem Schloss „Grundriss“, damit Räume, Wände, Türen, Fenster und Außenflächen nicht aus Versehen verschoben werden. Einzelne Stücke lassen sich auch mit „Fixieren“ sperren.", + "When the plan is done, you lock it with the “Floor plan” lock so that rooms, walls, doors, windows and outdoor areas are not moved by accident. Single pieces can also be locked with “Fix”.", + )); + await r.click({ key: "lock_plan" }); + await r.show(2.5, 800); + await r.click({ key: "lock_plan" }); + await r.show(1.5, 800); + + await r.chapter({ en: "A floor plan as a template", de: "Ein Grundriss als Vorlage" }, { en: "Tracing a drawing or photo", de: "Eine Zeichnung oder ein Foto nachzeichnen" }); + r.say(S( + "Hast du schon einen Grundriss als Bild, etwa vom Bauplan oder als Foto, kannst du ihn als Vorlage hinter den Plan legen und nachzeichnen. Das findest du unter „Vorlage“ in der Seitenleiste.", + "If you already have a floor plan as a picture, say from the building plans or as a photo, you can put it behind the plan as a template and trace it. You find that under “Template” in the side panel.", + )); + await r.spotAt({ key: "background" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); + r.say(S( + "Nach dem Hochladen schiebst du das Bild mit der Maus, skalierst es an der Ecke und drehst es am Griff darüber. Mit zwei Punkten richtest du es gerade, und mit einer bekannten Länge, etwa einer Wand, stellst du den Maßstab ein. Dann zeichnest du die Räume direkt darauf.", + "After uploading, you move the picture with the mouse, scale it at the corner and turn it at the handle above it. With two points you straighten it, and with a known length, such as a wall, you set the scale. Then you draw the rooms right on top.", + )); + await r.show(2.5); +} diff --git a/frontend/tutorial/episodes/03-doors-windows.mjs b/frontend/tutorial/episodes/03-doors-windows.mjs new file mode 100644 index 0000000..e87a007 --- /dev/null +++ b/frontend/tutorial/episodes/03-doors-windows.mjs @@ -0,0 +1,142 @@ +export const title = { en: "Doors and windows", de: "Türen und Fenster" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const plan = (x, z) => r.planPoint(x, z); + const tap = async (x, z) => { + const p = await plan(x, z); + await r.click({ x: p.x, y: p.y }, { settle: 700 }); + }; + const type = (name) => r.click({ text: name }); + const L = (de, en) => (r.lang === "de" ? de : en); + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + + await r.chapter({ en: "Doors and windows", de: "Türen und Fenster" }, { en: "Placing openings in the walls", de: "Öffnungen in die Wände setzen" }); + r.say(S( + "Unsere Räume haben noch keine Öffnungen. Dafür gibt es das Werkzeug „Türen und Fenster“. Wir wählen es aus.", + "Our rooms have no openings yet. For that there is the “Doors and windows” tool. We select it.", + )); + await r.click({ key: "tool_opening" }); + r.say(S( + "Der Hinweis unten sagt es schon: Tippe auf eine Wand, um eine Tür oder ein Fenster einzusetzen. Die Art wählst du danach rechts. Wir beginnen mit der Haustür an der unteren Wand des Flurs.", + "The hint at the bottom says it already: tap a wall to add a door or window. You choose the kind afterwards on the right. We begin with the front door on the lower wall of the hallway.", + )); + await r.show(0.8); + await tap(7.6, 9.2); + r.say(S( + "Die Öffnung sitzt in der Wand und ist ausgewählt. Das Werkzeug ist wieder auf „Auswählen“ gesprungen. Rechts siehst du alle Arten: Tür, Haustür, Doppeltür, Fenster, Doppelfenster, Terrassentür, Balkontür, Garagentor und Glaswand. Als Haustür nehmen wir die Haustür.", + "The opening sits in the wall and is selected. The tool has jumped back to “Select”. On the right you see all kinds: door, front door, double door, window, double window, terrace door, French doors, garage door and glass wall. For the entrance we take the front door.", + )); + await r.show(0.8); + await type(L("Haustür", "Front door")); + await r.show(1); + + r.say(S( + "Breite, Position und Höhe stellst du darunter in Metern ein. „Mitte von der Ecke“ ist der Abstand der Türmitte von der Raumecke. Die Haustür soll genau mittig in der Wand sitzen, das sind null Komma acht Meter.", + "Width, position and height are set below in metres. “Centre from corner” is the distance of the door centre from the room corner. The front door should sit exactly in the middle of the wall, that is zero point eight metres.", + )); + await r.spotUnion([{ label: "width" }, { label: "opening_position" }]).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(1.5); + await r.spot(null); + r.say(S( + "Mit „Anschlag wechseln“ drehst du die Seite, an der die Tür angeschlagen ist, und „Öffnungsrichtung umkehren“ lässt sie nach außen statt nach innen aufgehen. Beides siehst du sofort im Plan.", + "“Swap hinge side” changes the side the door is hinged on, and “Reverse opening direction” makes it open outwards instead of inwards. You see both immediately in the plan.", + )); + await r.click({ key: "flip_hinge" }); + await r.show(1); + + // ------------------------------------------------------------------ interior doors + await r.chapter({ en: "Interior doors", de: "Innentüren" }, { en: "Doors between rooms", de: "Türen zwischen den Räumen" }); + r.say(S( + "Jetzt die Türen im Haus. Zwischen Flur und Küche setzen wir eine normale Tür. Wir wählen wieder das Werkzeug und tippen auf die gemeinsame Wand.", + "Now the doors inside the house. Between the hallway and the kitchen we place a normal door. We pick the tool again and tap the shared wall.", + )); + await r.click({ key: "tool_opening" }); + await tap(9.2, 4.6); + await r.show(0.8); + r.say(S( + "Standardmäßig wird eine normale Tür eingesetzt. Das passt hier, also lassen wir es dabei. Der Stil steht auf „Automatisch“: In einer Außenwand wird daraus eine Haustür, innen eine Zimmertür.", + "A normal door is placed by default. That fits here, so we leave it. The style is on “Automatic”: in an exterior wall it becomes a front door, inside a room door.", + )); + await r.spotAt({ label: "opening_style" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(1.5); + await r.spot(null); + + r.say(S("Dasselbe machen wir vom Flur ins Bad…", "We do the same from the hallway into the bathroom…")); + await r.click({ key: "tool_opening" }); + await tap(6.8, 6.3); + await r.show(0.6); + r.say(S("…und vom Wohnzimmer ins Schlafzimmer.", "…and from the living room into the bedroom.")); + await r.click({ key: "tool_opening" }); + await tap(2.2, 4.6); + await r.show(0.6); + + // ------------------------------------------------------------------ windows + await r.chapter({ en: "Windows", de: "Fenster" }, { en: "Kinds, sill and blinds", de: "Arten, Brüstung und Rollläden" }); + r.say(S( + "Fenster funktionieren genauso. Wir setzen ein Doppelfenster in die obere Wand des Wohnzimmers.", + "Windows work the same way. We place a double window in the upper wall of the living room.", + )); + await r.click({ key: "tool_opening" }); + await tap(3, 0); + await type(L("Doppelfenster", "Double window")); + await r.show(1); + r.say(S( + "Bei Fenstern gibt es zusätzlich die Brüstungshöhe, also wie hoch die Fensterunterkante über dem Boden liegt. Das Doppelfenster hat zwei Flügel, und mit „Hauptflügel wechseln“ bestimmst du, welcher davon der Hauptflügel ist.", + "Windows also have a sill height, how high the lower edge of the window sits above the floor. The double window has two leaves, and “Swap main leaf” decides which of them is the main leaf.", + )); + await r.spotAt({ label: "sill" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(1.5); + await r.spot(null); + + r.say(S( + "Jetzt wird es spannend: Weiter unten kannst du dem Fenster Geräte zuordnen. Der Rollladen steht auf „Automatisch“. NextFloor hat im Bereich Wohnzimmer einen Rollladen gefunden und nimmt ihn. Genauso den Fensterkontakt, den Terrassentür-Sensor. Damit bewegt sich der Rollladen im Modell mit, und das Fenster zeigt, ob es offen ist.", + "Now it gets interesting: further down you can assign devices to the window. The blind is on “Automatic”. NextFloor found a blind in the area Wohnzimmer and uses it. The same for the window contact, the terrace door sensor. With that the blind moves along in the model, and the window shows whether it is open.", + )); + await r.spotAt({ css: "input[type=text]", nth: 0 }); + await r.show(2); + await r.spot(null); + r.say(S( + "Willst du ein anderes Gerät zuweisen, klickst du in das Feld und tippst einen Teil des Namens. Die Liste zeigt passende Geräte mit ihrem Bereich und der Entity-ID. Ein Klick wählt das Gerät aus. Wir tippen „Roll“.", + "To assign a different device, click into the field and type part of its name. The list shows matching devices with their area and entity ID. A click picks the device. We type “Roll”.", + )); + await r.click({ css: "input[type=text]", nth: 0 }); + await r.page.keyboard.type("Roll", { delay: 90 }); + await r.show(1.5); + await r.click({ text: "Wohnzimmer Rollladen" }); + await r.show(1); + r.say(S( + "Wichtig: NextFloor schaltet dabei nichts. Die Zuordnung sagt nur, welches Gerät zu diesem Fenster gehört.", + "Important: NextFloor does not switch anything here. The assignment only says which device belongs to this window.", + )); + await r.show(1); + + // ------------------------------------------------------------------ more windows + r.say(S( + "Die restlichen Fenster setzen wir ohne viele Worte: ein Fenster in die Küche, eines ins Schlafzimmer und ein kleines ins Bad.", + "The remaining windows we place without many words: one in the kitchen, one in the bedroom and a small one in the bathroom.", + )); + await r.click({ key: "tool_opening" }); + await tap(8, 0); + await type(L("Fenster", "Window")); + await r.click({ key: "tool_opening" }); + await tap(0, 6.3); + await type(L("Fenster", "Window")); + await r.click({ key: "tool_opening" }); + await tap(5.6, 8); + await type(L("Fenster", "Window")); + await r.show(1); + + r.say(S( + "Eine Tür oder ein Fenster entfernst du, indem du es auswählst und unten auf „Löschen“ klickst oder die Entf-Taste drückst.", + "To remove a door or window, select it and click “Delete” at the bottom, or press the Delete key.", + )); + await r.show(1.5); + + await r.click({ key: "fit" }); + await r.show(1.5); +} diff --git a/frontend/tutorial/episodes/04-furniture.mjs b/frontend/tutorial/episodes/04-furniture.mjs new file mode 100644 index 0000000..2e885e4 --- /dev/null +++ b/frontend/tutorial/episodes/04-furniture.mjs @@ -0,0 +1,122 @@ +export const title = { en: "Furnishing rooms", de: "Räume einrichten" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const plan = (x, z) => r.planPoint(x, z); + const L = (de, en) => (r.lang === "de" ? de : en); + /** Picks an item of the library and puts it at a place by typing its position and turn in the form. */ + const place = async (key, x, z, rotation = 0, size) => { + await r.click({ key }); + await r.typeInto({ label: "x" }, String(x)); + await r.typeInto({ label: "z" }, String(z)); + if (size) { + await r.typeInto({ label: "width" }, String(size[0])); + await r.typeInto({ label: "depth" }, String(size[1])); + } + if (rotation) await r.typeInto({ label: "rotation" }, String(rotation)); + }; + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + + await r.chapter({ en: "Furnishing rooms", de: "Räume einrichten" }, { en: "The furniture library", de: "Die Möbelbibliothek" }); + r.say(S( + "Ein Raum ohne Möbel wirkt leer, deshalb richten wir ihn jetzt ein. Dafür gibt es das Werkzeug „Möbel“.", + "A room without furniture looks empty, so now we furnish it. For that there is the “Furniture” tool.", + )); + await r.click({ key: "tool_furniture" }); + r.say(S( + "Der Hinweis unten sagt: Tippe auf einen Raum, dann wähle rechts ein Möbelstück. Wir tippen auf das Wohnzimmer.", + "The hint at the bottom says: tap a room, then pick an item on the right. We tap the living room.", + )); + const room = await plan(1, 1); + await r.click({ x: room.x, y: room.y }); + await r.show(1); + r.say(S( + "Rechts steht jetzt die Möbelbibliothek. Neue Möbel landen in der Mitte des gewählten Raums, das steht oben darüber. Die Bibliothek ist in Bereiche gegliedert: Leuchten, Wohnen, Essen, Küche, Schlafen, Bad und Wäsche, Arbeiten und Sonstiges, Parken. Ein Klick auf eine Überschrift klappt den Bereich auf oder zu.", + "On the right is now the furniture library. New items land in the middle of the chosen room, as it says above. The library is divided into sections: lights, living, dining, kitchen, sleeping, bath and laundry, work and other, parking. A click on a heading folds the section open or closed.", + )); + await r.spotAt({ key: "furniture_add" }); + await r.show(2); + await r.spot(null); + r.say(S( + "Unter den eingebauten Möbeln folgen die mitgelieferten Packs. Das sind große Sammlungen mit hunderten weiteren Möbelstücken, etwa ein Wohnzimmer-Pack, eine Küche oder ein Heimkino. Sie lassen sich genauso benutzen.", + "Below the built-in furniture follow the packs that come with NextFloor. These are large collections with hundreds more pieces, for example a living room pack, a kitchen or a home cinema. They are used in just the same way.", + )); + await r.click({ text: L("Wohnzimmer", "Living room") }).catch((e) => console.log(" [skipped]", e.message)); + await r.show(2); + await r.click({ text: L("Wohnzimmer", "Living room") }).catch(() => {}); + r.say(S( + "Wenn du etwas Bestimmtes suchst, tippst du es einfach ins Suchfeld. Die Suche findet deutsche und englische Namen, den Namen des Packs und auch mehrere Wörter in beliebiger Reihenfolge. Wir suchen ein Ecksofa.", + "If you are looking for something specific, just type it into the search field. The search finds German and English names, the name of the pack, and even several words in any order. We look for a corner sofa.", + )); + await r.typeInto({ css: "input[type=search]" }, L("ecksofa", "corner sofa")); + await r.show(2); + await r.click({ css: "input[type=search]" }); + await r.key("Escape"); + await r.show(0.8); + + // ------------------------------------------------------------------ the first piece + await r.chapter({ en: "Placing and moving", de: "Platzieren und verschieben" }, { en: "The sofa", de: "Das Sofa" }); + r.say(S( + "Wir beginnen mit einem einfachen Sofa aus dem Bereich Wohnen. Ein Klick darauf setzt es in die Mitte des Raums.", + "We start with a simple sofa from the living section. One click puts it in the middle of the room.", + )); + await r.click({ key: "furn_sofa" }); + await r.show(1); + r.say(S( + "Das Sofa ist ausgewählt. An den vier Ecken sitzen Griffe, mit denen du die Größe änderst, und unten ein Griff zum Drehen. Wir ziehen das Sofa mit der Maus an die obere Wand unter das Fenster.", + "The sofa is selected. At its four corners there are handles for changing the size, and at the bottom a handle for turning. We drag the sofa with the mouse to the upper wall under the window.", + )); + const centre = await plan(3, 2.3); + const target = await plan(4, 1); + await r.drag(centre, target); + await r.show(1); + r.say(S( + "Rechts im Formular siehst du alle Werte des Stücks. Der Name ist optional und hilft dir später bei der Suche. Darunter stehen die Position, die Größe in Metern und die Drehung in Grad. Du kannst jeden Wert eintippen, wenn du es genau haben willst.", + "In the form on the right you see all values of the piece. The name is optional and helps you search later. Below are the position, the size in metres and the rotation in degrees. You can type any value if you want it exact.", + )); + await r.spotAt({ label: "furn_name" }); + await r.show(1.2); + await r.spotUnion([{ label: "x" }, { label: "rotation" }]); + await r.show(1.8); + await r.spot(null); + r.say(S( + "Mit den Knöpfen „90° links“ und „90° rechts“ drehst du das Stück in Viertelschritten, „Spiegeln“ vertauscht links und rechts, zum Beispiel bei einem Ecksofa. „Duplizieren“ legt eine Kopie an, und „Löschen“ entfernt das Stück. „Fixieren“ sperrt es gegen versehentliches Verschieben.", + "With the buttons “90° left” and “90° right” you turn the piece in quarter steps, “Mirror” swaps left and right, for example for a corner sofa. “Duplicate” makes a copy, and “Delete” removes the piece. “Fix” locks it against accidental moves.", + )); + await r.spotAt({ key: "ctx_rotate", nth: 0 }).catch(() => {}); + await r.show(1); + await r.spot(null); + await r.spotAt({ key: "fix" }); + await r.show(1.2); + await r.spot(null); + + // ------------------------------------------------------------------ the rest of the room + await r.chapter({ en: "Finishing the living room", de: "Das Wohnzimmer fertig einrichten" }, { en: "Position by numbers", de: "Position per Zahlen" }); + r.say(S( + "Den Rest des Wohnzimmers richten wir jetzt zügig ein und geben die Positionen als Zahlen ein. Zuerst der Teppich, damit er unter den anderen Möbeln liegt.", + "We furnish the rest of the living room quickly now and enter the positions as numbers. First the rug, so that it lies under the other furniture.", + )); + await r.click({ key: "tool_furniture" }); + await r.click({ x: room.x, y: room.y }); + await place("furn_rug", 4, 2.4, 0, [2.4, 1.6]); + r.say(S("Dann der Couchtisch auf dem Teppich.", "Then the coffee table on the rug.")); + await place("furn_coffee_table", 4, 2.4); + r.say(S( + "Der Fernseher steht auf einem TV-Board an der gegenüberliegenden Wand. Das Board schaut standardmäßig nach unten, deshalb drehen wir es um hundertachtzig Grad, damit es zum Sofa zeigt.", + "The TV stands on a TV board against the opposite wall. By default the board faces down, so we turn it by one hundred and eighty degrees to face the sofa.", + )); + await place("furn_tv_board", 4.1, 4.2, 180); + r.say(S("Ein Sessel links vom Couchtisch, zur Mitte gedreht…", "An armchair to the left of the coffee table, turned towards the middle…")); + await place("furn_armchair", 1.8, 2.4, 270); + r.say(S("…ein Regal in der Ecke und eine Pflanze am Fenster.", "…a shelf in the corner and a plant by the window.")); + await place("furn_shelf", 0.45, 3.4, 90); + await place("furn_plant", 0.7, 0.7); + await r.show(1.5); + await r.click({ key: "tool_select" }); + await r.click({ key: "fit" }); + await r.show(2); +} diff --git a/frontend/tutorial/episodes/05-devices.mjs b/frontend/tutorial/episodes/05-devices.mjs new file mode 100644 index 0000000..af2e59c --- /dev/null +++ b/frontend/tutorial/episodes/05-devices.mjs @@ -0,0 +1,136 @@ +export const title = { en: "Devices and entities", de: "Geräte und Entities" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const plan = (x, z) => r.planPoint(x, z); + const L = (de, en) => (r.lang === "de" ? de : en); + const selectRoom = async () => { + const p = await plan(1.0, 3.9); + await r.click({ x: p.x, y: p.y }); + }; + /** Scrolls the side panel until the devices section stands at the top (a person would scroll with the wheel). */ + const toDevices = async () => { + await r.eval(`(() => { const d = (root) => { for (const el of root.querySelectorAll("*")) { if (el.tagName === "H3" && /^(Devices|Geräte)$/.test(el.textContent.trim())) { el.scrollIntoView({ block: "start" }); return true; } if (el.shadowRoot && d(el.shadowRoot)) return true; } return false; }; return d(document); })()`); + await r.show(0.6); + }; + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + + await r.chapter({ en: "Devices from Home Assistant", de: "Geräte aus Home Assistant" }, { en: "Lights, blinds, heating and more", de: "Lichter, Rollläden, Heizung und mehr" }); + r.say(S( + "Jetzt wird das Modell lebendig: Wir bringen die Geräte aus Home Assistant in den Plan. Dazu wählen wir mit „Auswählen“ den Raum, zum Beispiel das Wohnzimmer.", + "Now the model comes alive: we bring the devices from Home Assistant into the plan. For that we select the room with “Select”, for example the living room.", + )); + await r.click({ key: "tool_select" }); + await selectRoom(); + await r.show(0.8); + r.say(S( + "Ganz unten im Raum-Formular steht der Abschnitt „Geräte“. Er zeigt die Geräte, die in Home Assistant zu diesem Bereich gehören, hier zwölf.", + "At the very bottom of the room form is the “Devices” section. It shows the devices that belong to this area in Home Assistant, twelve here.", + )); + await toDevices(); + await r.spotAt({ key: "devices_src_area" }); + await r.show(1.5); + await r.spot(null); + r.say(S( + "Mit den Reitern darüber wechselst du die Quelle: „Dieser Bereich“, „Andere Bereiche“ für Geräte, die in einem anderen Raum stehen, und „Ohne Bereich“ für Geräte, die in Home Assistant noch keinem Bereich zugeordnet sind, zum Beispiel die Gartenbeleuchtung. Im Suchfeld findest du ein Gerät über seinen Namen.", + "With the tabs above you change the source: “This area”, “Other areas” for devices that stand in another room, and “No area” for devices that are not assigned to an area in Home Assistant yet, for example the garden lights. In the search field you find a device by its name.", + )); + await r.click({ text: L("Andere Bereiche", "Other areas") }); + await r.show(1.2); + await r.click({ text: L("Ohne Bereich", "No area") }); + await r.show(1.2); + await r.click({ key: "devices_src_area" }); + await r.show(0.8); + r.say(S( + "Jede Zeile hat vier Knöpfe: Das Auge blendet das Gerät im Raum-Fenster der 3D-Ansicht aus, „Aa“ gibt ihm einen eigenen Namen, der Stern fügt es dem Raum-Fenster hinzu, ohne es zu platzieren, und „Platzieren“ setzt es in den Plan.", + "Every row has four buttons: the eye hides the device in the room panel of the 3D view, “Aa” gives it a name of its own, the star adds it to the room panel without placing it, and “Place” puts it into the plan.", + )); + await r.show(2); + + // ------------------------------------------------------------------ lamps + await r.chapter({ en: "Placing a light", de: "Eine Leuchte platzieren" }, { en: "Lamps are furniture with a light", de: "Leuchten sind Möbel mit einem Licht" }); + r.say(S( + "Wir platzieren das Deckenlicht. Ein Klick auf „Platzieren“ neben „Deckenlicht“.", + "We place the ceiling light. One click on “Place” next to “Deckenlicht”.", + )); + await r.click({ key: "devices_place", near: "Deckenlicht" }); + await r.show(1); + r.say(S( + "NextFloor hat daraus eine Deckenleuchte gemacht, die mit dem Licht verbunden ist. Wir wählen sie im Plan aus, indem wir sie antippen.", + "NextFloor has turned it into a ceiling lamp that is connected to the light. We select it in the plan by tapping it.", + )); + const lamp = await plan(3, 2.3); + await r.click({ x: lamp.x, y: lamp.y }); + await r.show(1); + r.say(S( + "Im Formular steht bei „Licht oder Schalter“ das verbundene Gerät, das Wohnzimmer-Deckenlicht. Darunter kannst du für Farbe und Helligkeit ein anderes Gerät angeben, falls ein Relais nur ein- und ausschaltet, während die Lampe selbst Farbe und Helligkeit kennt.", + "In the form, “Light or switch” holds the connected device, the living room ceiling light. Below it you can name another device for colour and brightness, in case a relay only switches on and off while the bulb itself knows colour and brightness.", + )); + await r.spotAt({ label: "furn_entity_light" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2); + await r.spot(null); + r.say(S( + "Mit „Leuchten in 3D“ regelst du, wie stark das Licht im Modell glüht. Hundert Prozent sind so hell, wie das Gerät meldet. Wer LED-Streifen hat, die zu hell wirken, stellt hier weniger ein. „Vor dem Schalten fragen“ verhindert, dass ein Antippen in 3D das Licht versehentlich schaltet.", + "With “Glow in 3D” you set how strongly the light glows in the model. One hundred percent is as bright as the device reports. If you have LED strips that look too bright, set less here. “Ask before switching” prevents a tap in 3D from switching the light by accident.", + )); + await r.spotAt({ label: "glow_scale" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2); + await r.spot(null); + r.say(S( + "Die Markierung in 3D bestimmt, ob zusätzlich ein kleines Symbol mit dem Gerätezustand über der Leuchte schwebt: automatisch, immer, ohne Watt oder gar nicht. Du kannst dem Symbol auch ein eigenes Icon geben.", + "The marker in 3D decides whether a small symbol with the device state also floats above the lamp: automatic, always, without watts, or not at all. You can also give the symbol an icon of your own.", + )); + await r.spotAt({ label: "marker_show" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2); + await r.spot(null); + + r.say(S( + "Das war die erste Leuchte. Genauso setzen wir die Stehlampe und das LED-Band aus der Liste.", + "That was the first light. In the same way we place the floor lamp and the LED strip from the list.", + )); + await r.click({ text: L("‹ Zurück zu Wohnzimmer", "‹ Back to Living room") }).catch(() => {}); + await toDevices(); + await r.click({ key: "devices_place", near: "Stehlampe" }); + await r.show(1.2); + await r.click({ key: "devices_place", near: "LED Band" }); + await r.show(1.5); + + await r.click({ key: "tool_select" }); + await r.click({ key: "fit" }); + await r.show(2); + + // ------------------------------------------------------------------ electric furniture + await r.chapter({ en: "Furniture linked to devices", de: "Möbel mit Geräten verbinden" }, { en: "The TV as an example", de: "Der Fernseher als Beispiel" }); + r.say(S( + "Nicht nur Leuchten lassen sich verbinden, auch Möbel. Wir wählen das TV-Board im Wohnzimmer aus.", + "It is not only lights that can be connected, furniture can be too. We select the TV board in the living room.", + )); + const board = await plan(4.1, 4.2); + await r.click({ x: board.x, y: board.y }); + await r.show(1); + r.say(S( + "Unter der Position steht „TV, Media Player oder Steckdose“. NextFloor hat im Bereich Wohnzimmer einen Fernseher gefunden und ihn automatisch verbunden, das siehst du an „Automatisch“. Läuft der Fernseher, leuchtet der Bildschirm im Modell in der Farbe der App, etwa Netflix rot oder YouTube, und zeigt Titel oder Cover.", + "Under the position there is “TV, media player or smart plug”. NextFloor found a TV in the area Wohnzimmer and connected it automatically, you can tell by “Automatic”. While the TV plays, the screen in the model glows in the colour of the app, for example Netflix red or YouTube, and shows the title or cover.", + )); + await r.spotAt({ label: "furn_entity_tv" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); + r.say(S( + "„Leuchten hinter dem TV“ ist das Ambilight an der Wand hinter dem Fernseher. Hundert Prozent ist die volle Stärke. Passt es nicht zu deinem Wohnzimmer, zum Beispiel weil du hinter dem Fernseher eigene LED-Streifen hast, senkst du den Wert oder stellst ihn auf null, dann ist das Leuchten ganz aus.", + "“Glow behind the TV” is the ambilight on the wall behind the television. One hundred percent is full strength. If it does not suit your living room, for example because you have LED strips of your own behind the TV, lower the value or set it to zero, and the glow is off completely.", + )); + await r.spotAt({ label: "ambilight" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); + r.say(S( + "Und der Leistungssensor, ebenfalls automatisch gefunden, zeigt später, wie viele Watt der Fernseher gerade zieht. Genauso funktionieren Kühlschränke, Waschmaschinen, Drucker und viele andere Möbel aus den Packs.", + "And the power sensor, also found automatically, later shows how many watts the TV draws right now. Fridges, washing machines, printers and many other pieces from the packs work the same way.", + )); + await r.spotAt({ label: "furn_power" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); +} diff --git a/frontend/tutorial/episodes/06-outdoor.mjs b/frontend/tutorial/episodes/06-outdoor.mjs new file mode 100644 index 0000000..ea871f2 --- /dev/null +++ b/frontend/tutorial/episodes/06-outdoor.mjs @@ -0,0 +1,78 @@ +export const title = { en: "Outdoor areas", de: "Außenflächen" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const plan = (x, z) => r.planPoint(x, z); + const t = (key) => r.t(key); + const area = async (x1, z1, x2, z2, type) => { + await r.click({ key: "tool_outdoor" }); + await r.drag(await plan(x1, z1), await plan(x2, z2)); + if (type) await r.choose({ label: "outdoor_type" }, t(type)); + }; + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + + await r.chapter({ en: "Outdoor areas", de: "Außenflächen" }, { en: "Garden, terrace, path and pool", de: "Garten, Terrasse, Weg und Pool" }); + r.say(S( + "Ein Haus steht nicht im Leeren. Mit dem Werkzeug „Außen“ zeichnest du die Flächen rund ums Haus: Rasen, Terrasse, Wege, Einfahrt, Pool, Beete, Hecken und Zäune.", + "A house does not stand in an empty space. With the “Outdoor” tool you draw the areas around the house: lawn, terrace, paths, driveway, pool, flower beds, hedges and fences.", + )); + await r.click({ key: "tool_outdoor" }); + r.say(S( + "Der Hinweis unten: Ziehen, um eine Außenfläche aufzuziehen. Wir beginnen mit dem Rasen links neben dem Haus.", + "The hint at the bottom: drag to draw an outdoor area. We start with the lawn to the left of the house.", + )); + await r.drag(await plan(-3, 0), await plan(-0.4, 8)); + await r.show(0.8); + r.say(S( + "Die Fläche ist ausgewählt, und rechts steht ihr Formular. Oben wählst du die Art. Die Standardart ist Rasen, das passt. Darunter stehen Position und Größe.", + "The area is selected and its form is on the right. At the top you choose the kind. The default kind is lawn, which fits. Below are position and size.", + )); + await r.spotAt({ label: "outdoor_type" }); + await r.show(1.5); + await r.spot(null); + r.say(S( + "„Höhenversatz“ senkt eine Fläche unter den Boden oder hebt sie an, zum Beispiel eine Einfahrt, die zu einer tiefer liegenden Garage führt, oder eine erhöhte Terrasse. „Gefälle“ neigt eine Fläche: Du gibst den Höhenunterschied ein und die Richtung, in die sie abfällt. „Umriss zeigen“ blendet die leuchtende Kante ein oder aus, und „Aus den Flächen darunter ausschneiden“ macht aus der Fläche ein Loch in den Flächen darunter, praktisch für einen Teich mitten im Rasen.", + "“Height offset” lowers an area below the ground or raises it, for example a driveway leading to a lower garage, or a raised terrace. “Slope” tilts an area: you enter the height difference and the direction it falls towards. “Show the outline” turns the glowing edge on or off, and “Cut out of the areas beneath” makes the area a hole in the areas below it, handy for a pond in the middle of a lawn.", + )); + await r.spotUnion([{ label: "outdoor_offset" }, { label: "outdoor_slope" }]); + await r.show(2); + await r.spot(null); + + r.say(S( + "Oberhalb des Hauses kommt die Terrasse. Wir ziehen sie auf und stellen die Art um.", + "Above the house comes the terrace. We drag it out and change the kind.", + )); + await area(0.2, -3.2, 6, -0.4, "out_terrace"); + await r.show(0.8); + r.say(S( + "Vor der Haustür führt ein Weg entlang. Ein Weg ist schmal, deshalb ziehen wir ihn schmal auf.", + "In front of the front door a path leads along. A path is narrow, so we draw it narrow.", + )); + await area(7.1, 9.3, 8.1, 12, "out_path"); + await r.show(0.8); + r.say(S( + "Rechts neben dem Haus legen wir einen Pool an.", + "To the right of the house we lay out a pool.", + )); + await area(10.6, 5.2, 14.6, 9.2, "out_pool"); + await r.show(0.8); + r.say(S( + "Außerdem ein Beet vor dem Rasen und eine Hecke, die den Garten begrenzt. Bei Hecken und Zäunen kannst du im Formular die Höhe einstellen, zum Beispiel zweieinhalb Meter für eine Thuja-Hecke.", + "Also a flower bed in front of the lawn and a hedge that borders the garden. For hedges and fences you can set the height in the form, for example two and a half metres for a thuja hedge.", + )); + await area(-2.8, 8.4, -0.6, 9.4, "out_bed"); + await r.show(0.6); + await r.click({ key: "tool_select" }); + await r.click({ key: "fit" }); + await r.show(1.5); + + r.say(S( + "Außenflächen werden in 3D mit Rasen, Holz, Wasser und Stein dargestellt. Wie du Außenleuchten, zum Beispiel Wegleuchten und Gartenspots, aus der Möbelbibliothek dazusetzt, siehst du später im Kapitel über Leuchten.", + "In 3D outdoor areas are shown with grass, wood, water and stone. How to add outdoor lights, for example path lights and garden spots, from the furniture library you will see later in the chapter about lights.", + )); + await r.show(2); +} diff --git a/frontend/tutorial/episodes/07-second-floor.mjs b/frontend/tutorial/episodes/07-second-floor.mjs new file mode 100644 index 0000000..ae957cd --- /dev/null +++ b/frontend/tutorial/episodes/07-second-floor.mjs @@ -0,0 +1,137 @@ +export const title = { en: "A second floor, stairs and 3D beside", de: "Obergeschoss, Treppe und 3D daneben" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const plan = (x, z) => r.planPoint(x, z); + const L = (de, en) => (r.lang === "de" ? de : en); + const names = { child: L("Kinderzimmer", "Kids' room"), study: L("Arbeitszimmer", "Study"), bath: L("Bad oben", "Upstairs bathroom"), guest: L("Gästezimmer", "Guest room") }; + /** The floor tabs live in the floor form; with a room selected we step back to it first. */ + const floorTab = async (name) => { + for (let i = 0; i < 4; i++) { + const tab = await r.locate({ text: name, css: undefined }).catch(() => null); + if (tab) return r.click({ text: name }); + const back = await r.locate({ text: "‹" }).catch(() => null); + if (!back) break; + await r.click({ text: "‹" }); + } + return r.click({ text: name }); + }; + const rect = async (x1, z1, x2, z2) => { + await r.click({ key: "tool_rect" }); + await r.drag(await plan(x1, z1), await plan(x2, z2)); + }; + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + + await r.chapter({ en: "A second floor", de: "Das Obergeschoss" }, { en: "Floors on top of each other", de: "Etagen übereinander" }); + r.say(S( + "Ein Haus hat meist mehr als eine Etage. Wir legen das Obergeschoss an: „Etage hinzufügen“ und diesmal das Obergeschoss aus Home Assistant.", + "A house usually has more than one floor. We add the upper floor: “Add floor” and this time the Obergeschoss from Home Assistant.", + )); + await r.click({ key: "add_floor" }); + await r.click({ text: "Obergeschoss" }); + await r.show(1); + r.say(S( + "NextFloor stellt die neue Etage automatisch auf die richtige Höhe, hier zwei Komma sieben fünf Meter über dem Erdgeschoss. Im Plan siehst du gestrichelt die Umrisse der Etage darunter. Daran richtest du die neuen Wände aus.", + "NextFloor puts the new floor at the right height automatically, here two point seven five metres above the ground floor. In the plan you see the outlines of the floor below, dashed. You align the new walls with them.", + )); + await r.spotAt({ label: "elevation" }); + await r.show(2); + await r.spot(null); + r.say(S( + "Mit den Etagen-Reitern oben wechselst du zwischen den Etagen. Die Reihenfolge ändern „Nach oben“ und „Nach unten“.", + "With the floor tabs at the top you switch between the floors. “Move up” and “Move down” change the order.", + )); + await floorTab("Erdgeschoss"); + await r.show(1); + await floorTab("Obergeschoss"); + await r.show(0.8); + + r.say(S( + "Jetzt zeichnen wir die Räume des Obergeschosses mit dem Rechteck, wie im Erdgeschoss: ein Kinderzimmer oben links, ein Arbeitszimmer daneben, ein Bad und ein Gästezimmer darunter.", + "Now we draw the rooms of the upper floor with the rectangle, as on the ground floor: a kids' room at the top left, a study next to it, a bathroom and a guest room below.", + )); + await rect(0, 0, 4.4, 4.2); + await r.typeInto({ label: "room_name" }, names.child); + await r.choose({ label: "area" }, "Kinderzimmer"); + await r.choose({ label: "floor" }, L("Teppich", "Carpet")); + await rect(4.4, 0, 10, 4.2); + await r.typeInto({ label: "room_name" }, names.study); + await r.choose({ label: "area" }, "Arbeitszimmer"); + await r.choose({ label: "floor" }, L("Eiche", "Oak")); + await rect(0, 4.2, 3.4, 8); + await r.typeInto({ label: "room_name" }, names.bath); + await r.choose({ label: "floor" }, L("Fliesen", "Tiles")); + await rect(3.4, 4.2, 10, 8); + await r.typeInto({ label: "room_name" }, names.guest); + await r.show(1); + r.say(S( + "Das Bad oben und das Gästezimmer haben in Home Assistant keinen eigenen Bereich. Das ist kein Problem: Räume ohne Bereich funktionieren genauso, du kannst ihnen Geräte aber nur über „Andere Bereiche“ oder „Ohne Bereich“ zuordnen.", + "The bathroom upstairs and the guest room have no area of their own in Home Assistant. That is no problem: rooms without an area work the same way, you can only assign devices to them through “Other areas” or “No area”.", + )); + await r.click({ key: "tool_select" }); + await r.click({ key: "fit" }); + await r.show(1.5); + + // ------------------------------------------------------------------ stairs + await r.chapter({ en: "Stairs and floor openings", de: "Treppe und Bodenöffnung" }, { en: "Getting from floor to floor", de: "Von Etage zu Etage" }); + r.say(S( + "Damit man nach oben kommt, brauchen wir eine Treppe. Wir wechseln ins Erdgeschoss, wählen den Flur und öffnen die Möbelbibliothek.", + "To get upstairs we need a staircase. We switch to the ground floor, choose the hallway and open the furniture library.", + )); + await floorTab("Erdgeschoss"); + await r.click({ key: "tool_furniture" }); + const hall = await plan(9.3, 6.6); + await r.click({ x: hall.x, y: hall.y }); + await r.show(0.8); + r.say(S( + "Im Pack „Treppen und Geländer“ finden wir gerade, L-förmige, U-förmige und Wendeltreppen, Raumspartreppen, eine Außentreppe und Geländer aus Metall, Glas und Holz. Wir nehmen die gerade Treppe.", + "In the pack “Stairs and railings” we find straight, L-shaped, U-shaped and spiral staircases, space-saving stairs, outdoor steps and railings in metal, glass and wood. We take the straight staircase.", + )); + await r.click({ text: L("Treppen & Geländer", "Stairs & railings") }); + await r.show(0.8); + await r.click({ text: L("Gerade Treppe", "Straight staircase") }); + await r.show(1); + await r.typeInto({ label: "x" }, "9.2"); + await r.typeInto({ label: "z" }, "6.5"); + r.say(S( + "Die Stufen steigen von der Vorderkante nach hinten an. Reicht die Treppe bis zur Etage darüber, schneidet sie dort die Treppenöffnung automatisch in den Boden. Wir schauen im Obergeschoss nach.", + "The steps rise from the front edge towards the back. If the stairs reach the floor above, they cut the stairwell into the floor there automatically. We take a look at the upper floor.", + )); + await r.click({ key: "tool_select" }); + await floorTab("Obergeschoss"); + await r.show(1.5); + r.say(S( + "Ein Loch im Boden brauchst du auch ohne Treppe, zum Beispiel für eine Galerie oder einen Schacht. Dafür gibt es das Werkzeug „Bodenöffnung“: Du ziehst die Öffnung einfach auf, wo der Boden fehlen soll.", + "You also need a hole in the floor without stairs, for example for a gallery or a shaft. For that there is the “Floor opening” tool: you simply drag out the opening where the floor should be missing.", + )); + await r.click({ key: "tool_hole" }); + await r.show(1.5); + await r.click({ key: "tool_select" }); + await r.show(0.5); + + // ------------------------------------------------------------------ 3D beside + await r.chapter({ en: "3D beside the plan", de: "3D neben dem Plan" }, { en: "Seeing the model while you draw", de: "Das Modell beim Zeichnen sehen" }); + r.say(S( + "Wer beim Zeichnen sehen will, wie das Haus in 3D aussieht, schaltet „3D daneben“ ein. Der Editor zeigt dann links den Plan und rechts das 3D-Modell.", + "If you want to see how the house looks in 3D while you draw, switch on “3D beside”. The editor then shows the plan on the left and the 3D model on the right.", + )); + await r.click({ key: "split_3d" }); + await r.show(3); + r.say(S( + "Das Modell dreht sich mit der Maus: Ziehen dreht, das Mausrad zoomt, und mit rechter Maustaste oder zwei Fingern verschiebst du die Ansicht. Alles, was du im Plan änderst, siehst du sofort im Modell.", + "The model turns with the mouse: dragging rotates, the wheel zooms, and with the right mouse button or two fingers you move the view. Whatever you change in the plan you see in the model right away.", + )); + await r.show(2.5); + r.say(S( + "Mit den Knöpfen „Ansicht als Start der Etage“ und „Ansicht als Start des Raums“ merkst du dir die aktuelle Blickrichtung. Tippst du die Etage oder den Raum später in 3D an, fliegt die Kamera genau dorthin.", + "With the buttons “View as this floor's start” and “View as this room's start” you remember the current viewing direction. When you tap the floor or the room in 3D later, the camera flies exactly there.", + )); + await floorTab("Erdgeschoss"); + await r.show(1.5); + await r.click({ key: "split_3d" }); + await r.show(1); +} diff --git a/frontend/tutorial/episodes/08-lights.mjs b/frontend/tutorial/episodes/08-lights.mjs new file mode 100644 index 0000000..7b704f5 --- /dev/null +++ b/frontend/tutorial/episodes/08-lights.mjs @@ -0,0 +1,82 @@ +export const title = { en: "Lights in detail", de: "Leuchten im Detail" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const plan = (x, z) => r.planPoint(x, z); + const L = (de, en) => (r.lang === "de" ? de : en); + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + + await r.chapter({ en: "Lights in detail", de: "Leuchten im Detail" }, { en: "Lamp types, spots and outdoor lights", de: "Leuchtentypen, Spots und Außenleuchten" }); + r.say(S( + "Leuchten sind in NextFloor eigene Möbelstücke mit einem Licht dahinter. In der Möbelbibliothek gibt es dafür einen eigenen Bereich mit zwölf Typen: Deckenleuchte, Einbauspot, Aufbauspot, LED-Panel, Pendelleuchte, Stehlampe, Deckenfluter, Tischlampe, Wandleuchte, LED-Streifen, Wegeleuchte und Gartenspot.", + "In NextFloor lights are pieces of furniture of their own with a light behind them. In the furniture library there is a section of its own with twelve types: ceiling light, downlight, surface spot, LED panel, pendant light, floor lamp, floor uplight, table lamp, wall light, LED strip, path light and garden spot.", + )); + await r.click({ key: "tool_furniture" }); + const room = await plan(1, 1); + await r.click({ x: room.x, y: room.y }); + await r.spotAt({ text: L("Leuchten", "Lights") }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); + r.say(S( + "Jeder Typ hat seine eigene Bauform und leuchtet anders. Die Deckenleuchte und der Spot sitzen an der Decke, die Stehlampe steht auf dem Boden, die Tischlampe auf einem Möbel, die Wandleuchte an der Wand. Pendelleuchten hängen an einer Schnur. Die Höhe stellst du im Formular ein, bei der Pendelleuchte ist sie die Abhängung unter der Decke.", + "Every type has its own shape and glows differently. The ceiling light and the spot sit on the ceiling, the floor lamp stands on the floor, the table lamp on a piece of furniture, the wall light on the wall. Pendant lights hang on a cord. You set the height in the form; for the pendant light it is the drop below the ceiling.", + )); + await r.show(2); + + // ------------------------------------------------------------------ spots + await r.chapter({ en: "A grid of spots", de: "Ein Raster aus Spots" }, { en: "Many lamps, one light", de: "Viele Leuchten, ein Licht" }); + r.say(S( + "Oft hängen mehrere Einbauspots an einem Dimmer. Dafür musst du sie nicht einzeln setzen. Wir wählen die Küche aus und klicken auf „Spots setzen“.", + "Often several downlights hang on one dimmer. You do not have to place them one by one. We select the kitchen and click “Place spots”.", + )); + await r.click({ key: "tool_select" }); + const kitchen = await plan(8, 2); + await r.click({ x: kitchen.x, y: kitchen.y }); + await r.click({ key: "spots_place" }); + await r.show(1); + r.say(S( + "Du wählst die Art der Leuchte, die Zahl der Spalten und Reihen und das Licht, dem alle folgen sollen. NextFloor verteilt die Leuchten gleichmäßig im Raum. Wir nehmen Einbauspots, drei Spalten, zwei Reihen und das Küchenlicht.", + "You choose the kind of lamp, the number of columns and rows, and the light that all of them follow. NextFloor spreads the lamps evenly across the room. We take downlights, three columns, two rows and the kitchen light.", + )); + await r.typeInto({ label: "spots_cols" }, "3"); + await r.typeInto({ label: "spots_rows" }, "2"); + await r.pick("furn_entity_light", "Küchenl", L("Küchenlicht · Küche", "Küchenlicht · Küche")); + await r.show(1); + await r.click({ text: r.t("spots_add", { n: 6 }) }); + await r.show(1.5); + r.say(S( + "Sechs Spots, ein Licht: Schaltest du das Küchenlicht, leuchten alle sechs. Mit „Rückgängig“ nimmst du die Aktion auf einen Schlag zurück, falls das Raster nicht passt.", + "Six spots, one light: when you switch the kitchen light, all six glow. With “Undo” you take the action back in one go if the grid does not fit.", + )); + await r.show(1.5); + + // ------------------------------------------------------------------ outdoor + await r.chapter({ en: "Outdoor lights", de: "Außenleuchten" }, { en: "Path lights and garden spots", de: "Wegeleuchten und Gartenspots" }); + r.say(S( + "Außenleuchten gehören nicht zu einem Raum. Wir holen sie über den Raum-Abschnitt „Geräte“ mit dem Reiter „Ohne Bereich“, denn Gartenlichter haben in Home Assistant meist keinen Bereich. Dazu wählen wir einen beliebigen Raum aus, zum Beispiel das Wohnzimmer.", + "Outdoor lights do not belong to a room. We fetch them through the “Devices” section of the room with the “No area” tab, because garden lights usually have no area in Home Assistant. For that we select any room, for example the living room.", + )); + const living = await plan(1, 4); + await r.click({ x: living.x, y: living.y }); + await r.eval(`(() => { const d = (root) => { for (const el of root.querySelectorAll("*")) { if (el.tagName === "H3" && /^(Devices|Geräte)$/.test(el.textContent.trim())) { el.scrollIntoView({ block: "start" }); return true; } if (el.shadowRoot && d(el.shadowRoot)) return true; } return false; }; return d(document); })()`); + await r.click({ text: L("Ohne Bereich", "No area") }); + await r.show(1); + r.say(S( + "Hier stehen die Wegeleuchten und der Pool-Spot. Wir platzieren die Wegeleuchten und ziehen sie danach an den Weg vor der Haustür.", + "Here are the path lights and the pool spot. We place the path lights and then drag them to the path in front of the front door.", + )); + await r.click({ key: "devices_place", near: "Garten Wegleuchten" }); + await r.show(1); + await r.show(0.5); + r.say(S( + "Außenleuchten beleuchten die Außenflächen und die Fassade. Das ist in 3D besonders schön, wenn es dunkel wird.", + "Outdoor lights light the outdoor areas and the facade. That looks especially good in 3D when it gets dark.", + )); + await r.click({ key: "tool_select" }); + await r.click({ key: "fit" }); + await r.show(2); +} diff --git a/frontend/tutorial/episodes/09-roof-energy.mjs b/frontend/tutorial/episodes/09-roof-energy.mjs new file mode 100644 index 0000000..a023750 --- /dev/null +++ b/frontend/tutorial/episodes/09-roof-energy.mjs @@ -0,0 +1,97 @@ +export const title = { en: "The roof and solar power", de: "Dach und Solarstrom" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const plan = (x, z) => r.planPoint(x, z); + const L = (de, en) => (r.lang === "de" ? de : en); + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + + await r.chapter({ en: "The roof", de: "Das Dach" }, { en: "From the rooms to a roof", de: "Von den Räumen zum Dach" }); + r.say(S( + "Ein Haus braucht ein Dach, und für Solarmodule ganz besonders. Das Werkzeug „Dach“ baut es aus deinen Räumen. Wir wählen es aus.", + "A house needs a roof, and for solar modules especially. The “Roof” tool builds it from your rooms. We select it.", + )); + await r.click({ key: "tool_roof" }); + await r.show(1.2); + r.say(S( + "Der Editor schaltet dabei von selbst die 3D-Ansicht daneben dazu, denn ein Dach beurteilt man am besten in 3D. Im Plan sind Räume und Möbel gesperrt, damit du nichts verschiebst: Du bearbeitest nur Dachflächen.", + "The editor switches on the 3D view beside the plan by itself, because a roof is best judged in 3D. In the plan, rooms and furniture are locked so that you do not move anything: you only edit roof sections.", + )); + await r.show(2); + r.say(S( + "Wir klicken auf „Dachflächen aus den Räumen erzeugen“. NextFloor schlägt zu jeder zusammenhängenden Gebäudeteil-Fläche ein Dach vor, hier ein großes Satteldach über dem Haus und ein kleines über dem Anbau.", + "We click “Create roof sections from the rooms”. NextFloor proposes a roof for every connected part of the building, here a large gable roof over the house and a small one over the extension.", + )); + await r.click({ key: "roof_sections_start" }); + await r.show(2); + r.say(S( + "Jede Dachfläche hat Form, Firstrichtung, Traufhöhe und Neigung. Ein Klick auf einen Eintrag in der Liste wählt sie aus, ziehen verschiebt sie, und an den Ecken änderst du die Größe. Mit „Zurück zu einem Dach“ gehst du zur einfachen Dachform aus den Einstellungen zurück, und „Erneut aus den Räumen erzeugen“ beginnt von vorn.", + "Every section has a shape, ridge direction, eave height and pitch. A click on an entry in the list selects it, dragging moves it, and at the corners you change the size. “Back to one roof” returns to the simple roof shape from the settings, and “Create again from the rooms” starts over.", + )); + await r.spotAt({ key: "roof_sections_off" }); + await r.show(2.5); + await r.spot(null); + r.say(S( + "Dachfenster setzt du mit „Dachfenster“ auf eine Dachfläche. Sie bekommen wie normale Fenster einen Rollladen und einen Kontakt.", + "You put roof windows on a roof section with “Roof window”. Like normal windows they get a blind and a contact.", + )); + await r.spotAt({ text: "+ Roof window" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2); + await r.spot(null); + + // ------------------------------------------------------------------ energy + await r.chapter({ en: "Solar power and energy", de: "Solarstrom und Energie" }, { en: "Fields, meter and inverter", de: "Felder, Zähler und Wechselrichter" }); + r.say(S( + "Jetzt kommt die Energie. Das Werkzeug „Energie“ zeigt oben eine Einrichtungs-Checkliste: Solarfeld auf das Dach setzen, Zähler hinzufügen, Wechselrichter hinzufügen. Home-Batterie und Netzanschluss sind optional.", + "Now for the energy. The “Energy” tool shows a setup checklist at the top: put a solar field on the roof, add the meter, add an inverter. Home battery and grid connection are optional.", + )); + await r.click({ key: "tool_energy" }); + await r.show(2); + r.say(S( + "Wir beginnen mit dem Solarfeld. „Solarfeld“ legt ein Feld auf die am besten passende Dachfläche, nämlich die größte, die nach Süden schaut. Dafür nutzt NextFloor den Kompass aus den Einstellungen. Stimmt der Kompass nicht, wird das Feld auf der falschen Seite angelegt. Dazu kommen wir gleich.", + "We begin with the solar field. “Solar field” puts a field on the best-fitting roof section, the largest one that looks south. For this NextFloor uses the compass from the settings. If the compass is wrong, the field is placed on the wrong side. We will get to that in a moment.", + )); + await r.click({ text: "+ Solar field" }); + await r.show(2.5); + r.say(S( + "Das Feld liegt in der Dachneigung. Du ziehst es im Plan an eine andere Stelle, auch auf eine andere Dachfläche. Rechts stellst du Reihen und Spalten, Hoch- oder Querformat und die Zahl der Module ein. Für Felder auf Flachdächern oder im Garten gibt es „Freistehend“ mit Neigung, und „An der Wand“ für Fassadenmodule.", + "The field lies in the slope of the roof. You drag it in the plan to another place, even onto another roof section. On the right you set rows and columns, portrait or landscape and the number of modules. For fields on flat roofs or in the garden there is “Free-standing” with a tilt, and “On a wall” for facade modules.", + )); + await r.show(2.5); + r.say(S( + "Jetzt der Stromzähler und der Wechselrichter. Beide sind Geräte und stehen unter „Geräte“ der Energie-Seite. Wir fügen den Zähler und den Wechselrichter hinzu.", + "Now the electricity meter and the inverter. Both are devices and are listed under “Devices” on the energy page. We add the meter and the inverter.", + )); + const back = await r.locate({ text: "‹" }).catch(() => null); + if (back) await r.click({ text: "‹" }); + await r.click({ text: "+ " + r.t("furn_meter") }); + await r.show(1.5); + const back2 = await r.locate({ text: "‹" }).catch(() => null); + if (back2) await r.click({ text: "‹" }); + await r.click({ text: "+ " + r.t("furn_inverter") }); + await r.show(1.5); + r.say(S( + "Die Geräte stehen in der Etage, die oben gewählt ist, und lassen sich im Plan verschieben. Mit einem Leistungssensor zeigen sie ihre Watt, der Zähler nimmt den Netzsensor, und ein Wechselrichter bekommt seine Strings.", + "The devices stand on the floor chosen at the top and can be moved in the plan. With a power sensor they show their watts, the meter takes the grid sensor, and an inverter gets its strings.", + )); + await r.show(2); + r.say(S( + "Ganz unten steht die Energiebilanz mit Feldern für Netz, Solarproduktion, Batterie, Verbrauch und Tarif. Alle stehen auf „Automatisch“. Mit „Aus dem Energie-Dashboard übernehmen“ liest NextFloor die Sensoren, die du in Home Assistant schon für das Energie-Dashboard eingerichtet hast.", + "At the bottom is the energy balance with fields for grid, solar production, battery, consumption and tariff. All are on “Automatic”. “Take over from the energy dashboard” reads the sensors you have already set up for the energy dashboard in Home Assistant.", + )); + const back3 = await r.locate({ text: "‹" }).catch(() => null); + if (back3) await r.click({ text: "‹" }); + await r.spotAt({ text: "Take over from the energy dashboard" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); + r.say(S( + "In der 3D-Ansicht fliegen später Energieteilchen von den Solarmodulen zum Wechselrichter, zum Haus, zum Akku und zum Netz, schneller und dichter, je mehr Strom fließt.", + "In the 3D view, energy particles later fly from the solar modules to the inverter, the house, the battery and the grid, faster and denser the more power flows.", + )); + await r.show(2); + await r.click({ key: "tool_select" }); +} diff --git a/frontend/tutorial/episodes/10-settings.mjs b/frontend/tutorial/episodes/10-settings.mjs new file mode 100644 index 0000000..c7839fb --- /dev/null +++ b/frontend/tutorial/episodes/10-settings.mjs @@ -0,0 +1,109 @@ +export const title = { en: "Settings, compass and map", de: "Einstellungen, Kompass und Karte" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const L = (de, en) => (r.lang === "de" ? de : en); + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + const backToFloor = async () => { + for (let i = 0; i < 3; i++) { + const back = await r.locate({ text: "‹" }).catch(() => null); + if (!back) break; + await r.click({ text: "‹" }); + } + }; + await backToFloor(); + + await r.chapter({ en: "Settings", de: "Einstellungen" }, { en: "Walls, grid, compass and map", de: "Wände, Raster, Kompass und Karte" }); + r.say(S( + "In der Seitenleiste stehen weiter unten die Einstellungen für das ganze Haus. Wir klappen sie auf.", + "Further down the side panel are the settings for the whole house. We unfold them.", + )); + await r.click({ key: "settings" }); + await r.show(1); + r.say(S( + "Zuerst die Wanddicken. Außenwände sind standardmäßig vierundzwanzig Zentimeter dick, Innenwände zwölf. Das Raster ist die Schrittweite, auf die beim Zeichnen eingerastet wird, fünf Zentimeter. Mit der Alt-Taste zeichnest du einmalig ohne Einrasten.", + "First the wall thicknesses. Exterior walls are twenty-four centimetres thick by default, interior walls twelve. The grid is the step the drawing snaps to, five centimetres. With the Alt key you draw without snapping for a moment.", + )); + await r.spotUnion([{ label: "wall_exterior" }, { label: "grid" }]); + await r.show(2.5); + await r.spot(null); + + // ------------------------------------------------------------------ compass + await r.chapter({ en: "The compass", de: "Der Kompass" }, { en: "Fixing north and south", de: "Nord und Süd richtigstellen" }); + r.say(S( + "Jetzt der Kompass, ein wichtiger Punkt. Die Scheibe zeigt, wo Norden im Plan liegt. Der Plan hat kein eigenes Norden: Standardmäßig zeigt Norden im Plan nach oben. Davon hängen drei Dinge ab: das Sonnenlicht, das durch die Fenster fällt, die Windrichtung bei Wetter und die Himmelsrichtungen der Dachflächen. Und damit auch, wo ein neues Solarfeld hinkommt.", + "Now the compass, an important point. The dial shows where north lies in the plan. The plan has no north of its own: by default north points up in the plan. Three things depend on it: the sunlight falling through the windows, the wind direction in the weather, and the compass directions of the roof sections. And with that, where a new solar field goes.", + )); + await r.spotAt({ css: ".nf-compass" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(3); + await r.spot(null); + r.say(S( + "Hast du den Plan so gezeichnet, dass oben nicht Norden ist, oder stimmen Nord und Süd nicht mit der Wirklichkeit überein, musst du nichts neu zeichnen und keine Solarfelder neu anlegen. Du drehst einfach den Kompass. „Nord und Süd tauschen“ dreht ihn um hundertachtzig Grad. Wir probieren es.", + "If you drew the plan with north not at the top, or if north and south do not match reality, you do not have to redraw anything or place the solar fields again. You simply turn the compass. “Swap north and south” turns it by one hundred and eighty degrees. We try it.", + )); + await r.click({ key: "compass_swap" }); + await r.show(2.5); + r.say(S( + "Der Pfeil zeigt jetzt nach unten. Zeichnung, Dachflächen und Solarfelder sind unverändert. Geändert haben sich nur die Himmelsrichtungen: Was eben noch Süden war, ist jetzt Norden. Mit den Knöpfen für neunzig Grad drehst du in kleineren Schritten, und im Feld darüber gibst du jeden beliebigen Winkel ein.", + "The arrow now points down. The drawing, roof sections and solar fields are unchanged. Only the compass directions have changed: what was south a moment ago is now north. With the ninety degree buttons you turn in smaller steps, and in the field above you enter any angle you like.", + )); + await r.show(2); + await r.click({ key: "compass_swap" }); + await r.show(1.5); + r.say(S( + "Wir drehen den Kompass für unser Haus wieder zurück, denn hier stimmt er.", + "We turn the compass back for our house, because here it is right.", + )); + await r.show(0.5); + + // ------------------------------------------------------------------ map + await r.chapter({ en: "A real map under the plan", de: "Eine echte Karte unter dem Plan" }, { en: "Placing the house on its plot", de: "Das Haus auf sein Grundstück setzen" }); + r.say(S( + "Darunter kannst du eine echte Landkarte hinter den Plan legen, um das Haus genau auf sein Grundstück zu setzen. Die Karte ist standardmäßig aus und lädt dann auch nichts aus dem Internet. Wir schalten sie ein.", + "Below that you can put a real map behind the plan, to place the house exactly on its plot. The map is off by default and then loads nothing from the internet. We switch it on.", + )); + await r.click({ key: "map_on" }); + await r.show(3); + r.say(S( + "Die Karte startet am Standort von Home Assistant, im Plan und im 3D-Modell. Dein Browser lädt die Kartenkacheln direkt vom Kartenserver, standardmäßig OpenStreetMap. Unten rechts steht der Quellenhinweis. Die Karte ist gedimmt, damit der Plan im Vordergrund bleibt.", + "The map starts at the location of Home Assistant, in the plan and in the 3D model. Your browser loads the map tiles straight from the map server, OpenStreetMap by default. The credit is shown at the bottom right. The map is dimmed so that the plan stays in the foreground.", + )); + await r.show(2); + r.say(S( + "Mit „Sichtbarkeit“ stellst du ein, wie stark die Karte durchscheint, und die Detailstufe bestimmt die Schärfe. Mit den Pfeilknöpfen verschiebst du die Karte unter dem Plan, bis das Haus auf seinem Grundstück sitzt. Der Schritt darunter legt fest, wie weit ein Klick schiebt. Mit dem Kompass drehst du die Karte, falls das Haus schräg steht.", + "With “Visibility” you set how much the map shows through, and the detail level decides the sharpness. With the arrow buttons you move the map under the plan until the house sits on its plot. The step below sets how far one click moves it. With the compass you turn the map if the house is at an angle.", + )); + await r.spotAt({ key: "map_move" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(1.5); + await r.spot(null); + await r.click({ text: "▶" }); + await r.click({ text: "▼" }); + await r.show(1); + r.say(S( + "Du kannst auch eine eigene Kachel-Adresse eintragen, wenn du eine andere Kartenquelle nutzen darfst. Für unser Beispiel schalten wir die Karte wieder aus.", + "You can also enter a tile address of your own if you may use another map source. For our example we switch the map off again.", + )); + await r.click({ key: "map_on" }); + await r.show(1.5); + + // ------------------------------------------------------------------ more settings + await r.chapter({ en: "Roof, weather and more", de: "Dach, Wetter und mehr" }, { en: "The rest of the settings", de: "Der Rest der Einstellungen" }); + r.say(S( + "Weiter unten wählst du die Dachform für das ganze Haus, kein Dach, Flachdach, Satteldach oder eigene Dachflächen, mit Neigung und Überstand.", + "Further down you pick the roof shape for the whole house: no roof, flat roof, gable roof or sections of your own, with pitch and overhang.", + )); + await r.spotAt({ label: "roof" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2); + await r.spot(null); + r.say(S( + "Das Wetter-Gerät bestimmt, welche Wetter-Entity das Wetter am Haus steuert, und darunter schaltest du die Effekte einzeln ein oder aus: Regen, Schnee, Nebel, Wolken, Blitze, Sonne und Mond. Die Warnung „Fenster offen bei Regen“ und die Sonnenflecken durch die Fenster stellst du hier ebenfalls ein.", + "The weather entity decides which weather entity drives the weather at the house, and below it you switch the effects on or off one by one: rain, snow, fog, clouds, lightning, sun and moon. The warning “window open while it rains” and the sunlight patches through the windows are also set here.", + )); + await r.spotAt({ label: "weather_entity" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); +} diff --git a/frontend/tutorial/episodes/10b-favourites.mjs b/frontend/tutorial/episodes/10b-favourites.mjs new file mode 100644 index 0000000..e4402bb --- /dev/null +++ b/frontend/tutorial/episodes/10b-favourites.mjs @@ -0,0 +1,67 @@ +export const title = { en: "Favourites, own buttons and warnings", de: "Favoriten, eigene Knöpfe und Warnungen" }; +export const query = "alerts"; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const L = (de, en) => (r.lang === "de" ? de : en); + const wait = (ms) => new Promise((ok) => setTimeout(ok, ms)); + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + for (let i = 0; i < 3; i++) { + const back = await r.locate({ text: "‹" }).catch(() => null); + if (!back) break; + await r.quietClick({ text: "‹" }); + } + + await r.chapter({ en: "Favourites and own buttons", de: "Favoriten und eigene Knöpfe" }, { en: "The central menu", de: "Das Zentralmenü" }); + r.say(S( + "Im Zentralmenü der 3D-Ansicht stehen unter den Sammelschaltern deine Favoriten. Welche das sind, legst du in den Editor-Einstellungen unter „Favoriten“ fest. Wir klappen den Abschnitt auf.", + "In the central menu of the 3D view your favourites stand below the group switches. Which ones they are you set in the editor settings under “Favourites”. We unfold the section.", + )); + await r.click({ key: "favorites" }); + await r.show(1.5, 800); + r.say(S( + "Favoriten können Szenen, Skripte, Automationen, Schalter und Buttons sein, zum Beispiel „Gute Nacht“. Du suchst sie im Feld „Favorit hinzufügen“ und klickst auf einen Treffer.", + "Favourites can be scenes, scripts, automations, switches and buttons, for example “Gute Nacht”. You search for them in the field “Add a favourite” and click a hit.", + )); + await r.pick("favorites_add", "Gute", null).catch((e) => console.log(" [skipped]", e.message)); + await r.show(2, 800); + r.say(S( + "Mit „Eigener Knopf“ legst du einen Knopf an, der einen Dashboard-Pfad öffnet, die Details einer Entity zeigt, einen Dienst aufruft oder ein browser_mod-Popup mit deiner eigenen Karte öffnet. Du gibst ihm einen Namen, ein Symbol und das Ziel, zum Beispiel einen Pfad zum Rollladen-Dashboard.", + "With “Own button” you create a button that opens a dashboard path, shows the details of an entity, calls a service or opens a browser_mod popup with your own card. You give it a name, a symbol and the target, for example a path to the blinds dashboard.", + )); + await r.click({ text: "+ " + L("Eigener Knopf", "Own button") }).catch((e) => console.log(" [skipped]", e.message)); + await r.show(2.5, 800); + r.say(S( + "„Station oder Playlist“ im Abschnitt Klang legt Radiosender und Playlists fest, die im Schnellmenü eines Lautsprechers zum Starten stehen.", + "“Station or playlist” in the Sound section sets radio stations and playlists that are offered for starting in the quick menu of a speaker.", + )); + await r.spotAt({ text: "+ " + L("Sender oder Playlist", "Station or playlist") }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); + + await r.chapter({ en: "Warnings and scenes", de: "Warnungen und Szenen" }, { en: "When something needs your attention", de: "Wenn etwas deine Aufmerksamkeit braucht" }); + await r.click({ text: "3D" }); + await wait(4000); + r.say(S( + "Wechseln wir in die 3D-Ansicht. Oben stehen jetzt Warnungen. NextFloor überwacht Rauch, Gas, CO, Wasser, Alarmanlage und Fenster, die bei Regen offen stehen. Hier meldet die Küche Rauch, und mehrere Fenster stehen offen, während es regnet.", + "Let us switch to the 3D view. Warnings now show at the top. NextFloor watches smoke, gas, CO, water, alarm panel and windows that are open in the rain. Here the kitchen reports smoke, and several windows are open while it rains.", + )); + await r.show(4, 2500); + r.say(S( + "Der betroffene Raum pulsiert rot. Ein Tippen auf die Warnung springt in den Raum. So siehst du sofort, wo etwas los ist, auch in einem großen Haus.", + "The room concerned pulses red. A tap on the warning jumps into the room. That way you see at once where something is going on, even in a big house.", + )); + await r.show(2.5); + r.say(S( + "Im Raum-Fenster stehen außerdem Szenen und Skripte des Bereichs als Knöpfe, zum Beispiel „Kino“ oder „Lesen“ im Wohnzimmer. Ein Klick startet die Szene, und das Haus verändert sich sofort.", + "In the room panel scenes and scripts of the area also stand as buttons, for example “Kino” or “Lesen” in the living room. One click starts the scene, and the house changes at once.", + )); + await r.click({ text: "Erdgeschoss", nth: 0 }); + await r.show(1.5, 1500); + await r.click({ text: L("Wohnzimmer", "Living room") }); + await r.show(3, 2500); +} diff --git a/frontend/tutorial/episodes/11-the-3d-view.mjs b/frontend/tutorial/episodes/11-the-3d-view.mjs new file mode 100644 index 0000000..ab8d62d --- /dev/null +++ b/frontend/tutorial/episodes/11-the-3d-view.mjs @@ -0,0 +1,129 @@ +export const title = { en: "The 3D view", de: "Die 3D-Ansicht" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const L = (de, en) => (r.lang === "de" ? de : en); + + await r.chapter({ en: "The 3D view", de: "Die 3D-Ansicht" }, { en: "Your house, alive", de: "Dein Haus, lebendig" }); + r.say(S( + "Der Plan ist fertig. Wir wechseln jetzt auf den Reiter „3D“ und sehen uns an, was daraus geworden ist.", + "The plan is done. Now we switch to the “3D” tab and look at what has become of it.", + )); + await r.click({ text: "3D" }); + await r.show(3, 3500); + r.say(S( + "Das ist dein Haus als lebendiges Modell: das Dach mit den Solarmodulen, die Terrasse, der Pool und der Weg. In den Räumen leuchten die Lampen, und im Wohnzimmer läuft gerade der Fernseher mit einer Serie. Alles, was du in Home Assistant einrichtest, siehst du hier live.", + "This is your house as a living model: the roof with the solar modules, the terrace, the pool and the path. In the rooms the lamps glow, and in the living room the TV is playing a series right now. Everything you set up in Home Assistant you see here, live.", + )); + await r.show(2); + + // ------------------------------------------------------------------ moving around + await r.chapter({ en: "Moving around", de: "Sich bewegen" }, { en: "Turning, zooming, flying to a room", de: "Drehen, Zoomen, zu einem Raum fliegen" }); + r.say(S( + "Du bewegst dich mit der Maus. Ziehen mit der linken Taste dreht das Haus. Wir drehen es einmal ein Stück.", + "You move around with the mouse. Dragging with the left button turns the house. We turn it a little.", + )); + await r.drag({ x: 760, y: 520 }, { x: 560, y: 470 }, { frames: 14 }); + await r.show(1); + r.say(S( + "Das Mausrad zoomt hinein und heraus, und mit der rechten Maustaste, oder auf dem Touchscreen mit zwei Fingern, verschiebst du die Ansicht. Auf einem Tablet zoomst du mit zwei Fingern.", + "The mouse wheel zooms in and out, and with the right mouse button, or with two fingers on a touch screen, you move the view. On a tablet you zoom with two fingers.", + )); + await r.page.mouse.move(640, 400); + for (let i = 0; i < 4; i++) { + await r.page.mouse.wheel({ deltaY: -250 }); + await new Promise((ok) => setTimeout(ok, 500)); + await r.frame(); + } + await r.show(1); + for (let i = 0; i < 4; i++) { + await r.page.mouse.wheel({ deltaY: 250 }); + await new Promise((ok) => setTimeout(ok, 500)); + await r.frame(); + } + await r.show(0.8); + r.say(S( + "Oben stehen die Etagen und Räume als Knöpfe. „Alle Etagen“ zeigt das ganze Haus. Ein Klick auf eine Etage lässt die Kamera dorthin fliegen und blendet die Etagen darüber aus. Wir wählen das Erdgeschoss.", + "At the top the floors and rooms are shown as buttons. “All floors” shows the whole house. A click on a floor makes the camera fly there and hides the floors above it. We choose the ground floor.", + )); + await r.click({ text: "Erdgeschoss", nth: 0, css: undefined }); + await r.show(2.5, 1500); + r.say(S( + "Ein Klick auf einen Raum fliegt hinein. Wir nehmen das Wohnzimmer. Rechts öffnet sich das Raum-Fenster mit den Geräten dieses Raums. Dazu gleich mehr.", + "A click on a room flies in. We take the living room. On the right the room panel opens with the devices of this room. More on that in a moment.", + )); + await r.click({ text: L("Wohnzimmer", "Living room") }); + await r.show(3, 2000); + r.say(S( + "Links am Rand siehst du kleine Bilder der Etagen. Ein Klick darauf wechselt die Etage, auch ohne die Leiste oben. „Zurück“ unten bringt dich eine Ebene hoch, und die Escape-Taste tut dasselbe.", + "On the left edge you see small pictures of the floors. A click on them switches the floor, even without the bar at the top. “Back” at the bottom takes you one level up, and the Escape key does the same.", + )); + await r.click({ text: L("Zurück", "Back") }).catch(() => {}); + await r.show(2, 1500); + await r.click({ text: L("Alle Etagen", "All floors"), nth: 0 }); + await r.show(2, 1500); + + // ------------------------------------------------------------------ the looks + await r.chapter({ en: "Looks and display", de: "Aussehen und Anzeige" }, { en: "Themes, quality and markers", de: "Themen, Qualität und Symbole" }); + r.say(S( + "Oben rechts stellst du das Aussehen ein. Die Qualität ist „Automatisch“: NextFloor wählt selbst, was dein Gerät schafft. Für Wandtablets gibt es „Tablet“ mit weniger Effekten und für starke Rechner „Hoch“ mit Lichtkegeln und weichen Schatten. Ganz rechts zeigt „FPS“ die Bildrate.", + "At the top right you set the look. The quality is “Auto”: NextFloor decides by itself what your device can handle. For wall tablets there is “Tablet” with fewer effects, and for powerful computers “High” with light cones and soft shadows. Far right “FPS” shows the frame rate.", + )); + await r.spotUnion([{ text: "Auto" }, { text: "High" }]); + await r.show(2.5); + await r.spot(null); + r.say(S( + "Daneben die Themen: „Neon“ ist der leuchtende Look, „Blueprint“ wirkt wie ein Bauplan, und „Tag“ ist hell und eignet sich für helle Räume. Der Farbpunkt dahinter ändert die Akzentfarbe. Wir sehen uns alle drei an.", + "Next to it the themes: “Neon” is the glowing look, “Blueprint” looks like a construction plan, and “Day” is bright and suits light rooms. The colour dot behind it changes the accent colour. We look at all three.", + )); + await r.click({ text: "Blueprint" }); + await r.show(2.5, 1200); + await r.click({ text: "Day" }); + await r.show(2.5, 1200); + await r.click({ text: "Neon" }); + await r.show(1.5, 1200); + r.say(S( + "Die drei Knöpfe daneben bestimmen, welche Symbole über den Geräten schweben. „Keine“ blendet sie aus, „Wichtige“ zeigt nur die wichtigen, zum Beispiel offene Fenster, und „Alle“ zeigt alle Geräte mit ihrem Zustand.", + "The three buttons next to it decide which symbols float above the devices. “None” hides them, “Important” shows only the important ones, for example open windows, and “All” shows all devices with their state.", + )); + await r.click({ text: L("Alle", "All"), nth: 0 }); + await r.show(2.5, 1200); + await r.click({ text: L("Wichtige", "Important") }); + await r.show(1.2, 1000); + + // ------------------------------------------------------------------ bottom switches + await r.chapter({ en: "The switches at the bottom", de: "Die Schalter unten" }, { en: "Walls, floors, roof and heat map", de: "Wände, Etagen, Dach und Heatmap" }); + r.say(S( + "Unten sitzen die wichtigsten Schalter. „Hohe Wände“ und „Schnitt“ legen fest, ob du die Wände ganz siehst oder in Brüsthöhe abgeschnitten, damit du in die Räume hineinsehen kannst.", + "At the bottom are the most important switches. “Tall walls” and “Cut” decide whether you see the walls complete or cut off at chest height so that you can see into the rooms.", + )); + await r.click({ text: "Cut" }); + await r.show(2.5, 1500); + await r.click({ text: L("Hohe Wände", "Tall walls") }); + await r.show(1.2, 1200); + r.say(S( + "„Auseinander“ zieht die Etagen für den Überblick auseinander, „Gestapelt“ setzt sie wieder aufeinander, und „Dach bleibt“ hält das Dach auch dann, wenn du in eine Etage hineinzoomst.", + "“Apart” pulls the floors apart for an overview, “Stacked” puts them on top of each other again, and “Roof stays” keeps the roof even when you zoom into a floor.", + )); + await r.click({ text: "Stacked" }); + await r.show(2.5, 1500); + await r.click({ text: "Apart" }); + await r.show(1.5, 1500); + r.say(S( + "Die Heatmap färbt die Räume nach Messwerten ein: „Temperatur“, „Feuchte“ und „CO₂“. „Werte“ schreibt die Zahlen in die Räume. Eine Legende zeigt die Farbskala. Wir sehen uns die Temperatur an.", + "The heat map colours the rooms by measured values: “Temp.”, “Humidity” and “CO₂”. “Values” writes the numbers into the rooms. A legend shows the colour scale. We look at the temperature.", + )); + await r.click({ text: "Temp." }); + await r.show(3, 1500); + await r.click({ text: "Normal" }); + await r.show(1, 1000); + r.say(S( + "„Raumnamen“ blendet die Namen der Räume ein, und „Wetter“ schaltet die Wettereffekte am Haus ein oder aus. Darauf kommen wir bei den Live-Funktionen zurück.", + "“Room names” shows the names of the rooms, and “Weather” switches the weather effects at the house on or off. We come back to that with the live features.", + )); + await r.click({ text: "Room names" }); + await r.show(2, 1000); + await r.click({ text: "Room names" }); + await r.show(1, 800); +} diff --git a/frontend/tutorial/episodes/12-controlling.mjs b/frontend/tutorial/episodes/12-controlling.mjs new file mode 100644 index 0000000..09b069d --- /dev/null +++ b/frontend/tutorial/episodes/12-controlling.mjs @@ -0,0 +1,104 @@ +export const title = { en: "Controlling the house", de: "Das Haus bedienen" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const L = (de, en) => (r.lang === "de" ? de : en); + + await r.quietClick({ text: "3D" }); + await new Promise((ok) => setTimeout(ok, 3000)); + await r.quietClick({ text: "Erdgeschoss", nth: 0 }); + await new Promise((ok) => setTimeout(ok, 2500)); + + await r.chapter({ en: "The room panel", de: "Das Raum-Fenster" }, { en: "Lights, blinds and media of a room", de: "Lichter, Rollläden und Medien eines Raums" }); + r.say(S( + "Jetzt bedienen wir das Haus. Dazu fliegen wir ins Wohnzimmer.", + "Now we control the house. To do that we fly into the living room.", + )); + await r.click({ text: L("Wohnzimmer", "Living room") }); + await r.show(3, 2500); + r.say(S( + "Rechts steht das Raum-Fenster. Es zeigt alle Geräte des Raums nach Art geordnet: Lichter, Rollläden, Medien und Sensoren. Wichtig für dieses Video: Wir arbeiten hier in der Demo mit erfundenen Geräten, deshalb darf alles geschaltet werden. In deinem echten Home Assistant schaltet ein Klick das echte Gerät.", + "On the right is the room panel. It shows all devices of the room sorted by kind: lights, blinds, media and sensors. Important for this video: here in the demo we work with invented devices, so everything may be switched. In your real Home Assistant a click switches the real device.", + )); + await r.show(2); + r.say(S( + "Bei den Lichtern schaltet ein Klick auf den Namen das Licht ein oder aus. Wir schalten die Stehlampe aus.", + "For the lights a click on the name switches the light on or off. We switch the floor lamp off.", + )); + await r.click({ css: "button", text: "Stehlampe", nth: 0 }); + await r.show(2, 1200); + r.say(S( + "Darunter stellst du die Helligkeit und die Farbtemperatur mit Reglern ein, und die Farbpunkte setzen schnell eine Farbe, vom warmen Orange bis zu Blau, Pink und Grün. Wir schalten die Lampe wieder ein und färben sie.", + "Below that you set the brightness and the colour temperature with sliders, and the colour dots quickly set a colour, from warm orange to blue, pink and green. We switch the lamp on again and colour it.", + )); + await r.click({ css: "button", text: "Stehlampe", nth: 0 }); + await r.show(1, 1000); + await r.click({ css: "button[title='rgb(91, 124, 255)'], button[aria-label='rgb(91, 124, 255)']", nth: 1 }); + await r.show(2.5, 1500); + r.say(S( + "Die Lampe leuchtet im Modell jetzt blau, und der Lichtschein fällt auf Boden und Möbel. „Alle aus“ schaltet alle Lichter des Raums auf einmal aus.", + "The lamp now glows blue in the model, and the light falls on the floor and the furniture. “All off” switches off all lights of the room at once.", + )); + await r.spotAt({ text: L("Alle aus", "All off") }); + await r.show(2); + await r.spot(null); + r.say(S( + "Rollläden haben die Knöpfe Auf, Stopp und Zu und einen Positionsregler. Medien haben Zurück, Wiedergabe oder Pause, Weiter und die Lautstärke. Darunter stehen die Sensoren des Raums, hier der Stromverbrauch des Fernsehers und der Terrassentür-Kontakt.", + "Blinds have the buttons Open, Stop and Close and a position slider. Media have Previous, Play or Pause, Next and the volume. Below are the sensors of the room, here the power draw of the TV and the terrace door contact.", + )); + await r.click({ text: L("Rollladen", "Rollladen"), nth: 0 }).catch(() => {}); + await r.show(2.5, 800); + r.say(S( + "Mit „Weitere Geräte des Bereichs“ blendest du die übrigen Geräte ein, die nicht im Plan platziert sind. Welche Geräte im Raum-Fenster erscheinen, steuerst du im Editor mit dem Auge und dem Stern in der Geräteliste.", + "With “More devices of the area” you show the remaining devices that are not placed in the plan. Which devices appear in the room panel you control in the editor with the eye and the star in the device list.", + )); + await r.click({ text: L("Weitere Geräte des Bereichs", "More devices of the area") }).catch((e) => console.log(" [skipped]", e.message)); + await r.show(2.5, 800); + + // ------------------------------------------------------------------ in the model + await r.chapter({ en: "Controlling in the model", de: "Direkt im Modell bedienen" }, { en: "Tap, long press and the quick menu", de: "Antippen, lange drücken und das Schnellmenü" }); + r.say(S( + "Du kannst die Geräte auch direkt im 3D-Modell bedienen. Ein Antippen einer Lampe schaltet sie. Wir tippen die Deckenlampe an.", + "You can also control the devices straight in the 3D model. A tap on a lamp switches it. We tap the ceiling lamp.", + )); + await r.click({ text: L("Alle", "All"), nth: 0 }); + await r.show(1, 1000); + await r.click({ css: ".nf-dev[data-entity='light.wohnzimmer_decke']" }).catch((e) => console.log(" [skipped]", e.message)); + await r.show(2.5, 1200); + r.say(S( + "Ein langer Druck öffnet das Schnellmenü: Helligkeit, Farbe und die Details des Geräts, ohne dass du das Raum-Fenster brauchst. Auch bei Rollläden öffnet schon ein Antippen ihr Schnellmenü mit Auf, Zu und Positionen.", + "A long press opens the quick menu: brightness, colour and the details of the device, without needing the room panel. For blinds a tap is enough to open their quick menu with open, close and positions.", + )); + await r.longPress({ css: ".nf-dev[data-entity='light.stehlampe']" }).catch((e) => console.log(" [skipped]", e.message)); + await r.show(3, 800); + await r.key("Escape"); + await r.show(1, 600); + + // ------------------------------------------------------------------ central + await r.chapter({ en: "The central menu", de: "Das Zentralmenü" }, { en: "All lights, all blinds, favourites", de: "Alle Lichter, alle Rollläden, Favoriten" }); + r.say(S( + "Der Stern links unten ist das Zentralmenü: alle Lichter und alle Rollläden der Etage oder des ganzen Hauses auf einmal, dazu deine Favoriten. Favoriten sind Szenen, Skripte, Automationen und Schalter, die du in den Editor-Einstellungen festlegst.", + "The star at the bottom left is the central menu: all lights and all blinds of the floor or the whole house at once, plus your favourites. Favourites are scenes, scripts, automations and switches that you set in the editor settings.", + )); + await r.click({ text: L("Alle Etagen", "All floors"), nth: 0 }); + await r.show(1.5, 1500); + await r.click({ css: "button[aria-label^='Central'], button[title^='Central'], button[aria-label^='Zentral'], button[title^='Zentral']" }).catch((e) => console.log(" [skipped]", e.message)); + await r.show(3, 800); + await r.key("Escape"); + await r.show(1); + // ------------------------------------------------------------------ search + await r.chapter({ en: "Search", de: "Suche" }, { en: "Where is …?", de: "Wo ist …?" }); + r.say(S( + "Die Lupe unten links öffnet die Suche „Wo ist …?“. Du tippst den Namen eines Geräts oder Raums, und ein Treffer lässt die Kamera hinfliegen, während das Gerät aufblinkt. Praktisch in großen Häusern.", + "The magnifier at the bottom left opens the “Where is …?” search. You type the name of a device or room, and a hit makes the camera fly there while the device flashes. Handy in big houses.", + )); + await r.click({ text: L("Suche", "Search") }).catch(async () => r.click({ css: "button[aria-label*='earch'], button[title*='earch']" })); + await r.show(1, 800); + await r.page.keyboard.type("Fern", { delay: 120 }); + await r.show(2, 800); + await r.key("Enter"); + await r.show(2.5, 1500); + await r.key("Escape"); + +} diff --git a/frontend/tutorial/episodes/13-garage-car.mjs b/frontend/tutorial/episodes/13-garage-car.mjs new file mode 100644 index 0000000..15847d2 --- /dev/null +++ b/frontend/tutorial/episodes/13-garage-car.mjs @@ -0,0 +1,68 @@ +export const title = { en: "Garage, parking spot and the car", de: "Garage, Stellplatz und das Auto" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const plan = (x, z) => r.planPoint(x, z); + const L = (de, en) => (r.lang === "de" ? de : en); + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + + await r.chapter({ en: "A garage", de: "Eine Garage" }, { en: "One more room and a door", de: "Noch ein Raum und ein Tor" }); + r.say(S( + "Zum Haus gehört noch eine Garage. Wir zeichnen sie mit dem Rechteck rechts neben die Küche.", + "The house also has a garage. We draw it with the rectangle to the right of the kitchen.", + )); + await r.click({ key: "tool_rect" }); + await r.drag(await plan(10, 0), await plan(13.6, 5.2)); + await r.typeInto({ label: "room_name" }, L("Garage", "Garage")); + await r.choose({ label: "area" }, "Garage"); + await r.choose({ label: "floor" }, L("Beton", "Concrete")); + await r.show(1); + r.say(S( + "Das Tor setzen wir mit „Türen und Fenster“ an die rechte Außenwand und wählen als Art „Garagentor“. Ein Garagentor kann mit einem Antrieb verbunden werden. In 3D fährt es dann hoch und runter und zeigt, ob es offen ist.", + "We place the door with “Doors and windows” on the right exterior wall and choose “Garage door” as the kind. A garage door can be connected to a drive. In 3D it then moves up and down and shows whether it is open.", + )); + await r.click({ key: "tool_opening" }); + const wall = await plan(13.6, 3.0); + await r.click({ x: wall.x, y: wall.y }); + await r.click({ text: L("Garagentor", "Garage door") }); + await r.show(2); + + await r.chapter({ en: "The parking spot", de: "Der Stellplatz" }, { en: "Showing the car in 3D", de: "Das Auto in 3D zeigen" }); + r.say(S( + "Jetzt der Stellplatz. In der Möbelbibliothek gibt es den Bereich „Parken“ mit dem Stellplatz. Wir wählen die Garage aus und setzen den Stellplatz hinein.", + "Now the parking spot. In the furniture library there is the section “Parking” with the parking spot. We select the garage and put the parking spot into it.", + )); + await r.click({ key: "tool_furniture" }); + const garage = await plan(11.8, 2.6); + await r.click({ x: garage.x, y: garage.y }); + await r.click({ text: L("Parken", "Parking") }); + await r.click({ text: L("Stellplatz", "Parking spot") }); + await r.show(1.5); + r.say(S( + "Der Stellplatz zeigt in 3D ein Fahrzeug, solange dein Auto da ist. Du wählst bei „Fahrzeug“ das Modell, zum Beispiel einen Transporter aus dem Pack „Fahrzeuge“, und mit „Größe“ passt du es an. Ohne Fahrzeug-Pack bleibt die Liste leer.", + "The parking spot shows a vehicle in 3D while your car is there. Under “Vehicle” you choose the model, for example a van from the “Vehicles” pack, and with “Size” you adapt it. Without the vehicle pack the list stays empty.", + )); + await r.choose({ label: "parking_vehicle" }, L("Transporter · Fahrzeuge", "Van · Vehicles")).catch(async (e) => { + console.log(" [vehicle option]", e.message); + }); + await r.show(2); + r.say(S( + "Der Sensor „Auto da“ sagt, wann das Fahrzeug im Stellplatz steht, zum Beispiel ein Ortungssensor oder ein Bewegungsmelder. Erscheint das Auto nicht, stimmt meist dieser Sensor nicht. Ohne Sensor steht das Fahrzeug immer da.", + "The sensor “car present” says when the vehicle stands in the spot, for example a tracker or a motion sensor. If the car does not appear, this sensor is usually the reason. Without a sensor the vehicle always stands there.", + )); + await r.pick("parking_entity", "Auto in", null).catch((e) => console.log(" [car present]", e.message)); + await r.show(2); + r.say(S( + "Unten wählst du eine beliebige Entity deines Autos. NextFloor findet über das Gerät des Autos alles andere von selbst: Ladestand, Reichweite, Stecker, Innentemperatur und die Knöpfe für Schloss, Klima und Laden. Daraus entsteht in 3D eine Karte über dem Stellplatz, die wir uns im Kapitel über die Live-Funktionen ansehen.", + "At the bottom you choose any entity of your car. NextFloor finds everything else by itself through the device of the car: charge level, range, plug, inside temperature and the buttons for lock, climate and charging. From that a card over the parking spot is made in 3D, which we look at in the chapter about the live features.", + )); + await r.pick("live_car_device", "Van Lade", null).catch((e) => console.log(" [car entity]", e.message)); + await r.show(2); + await r.click({ key: "tool_select" }); + await r.click({ key: "fit" }); + await r.show(1.5); +} diff --git a/frontend/tutorial/episodes/14-live-features.mjs b/frontend/tutorial/episodes/14-live-features.mjs new file mode 100644 index 0000000..a8d4b13 --- /dev/null +++ b/frontend/tutorial/episodes/14-live-features.mjs @@ -0,0 +1,115 @@ +export const title = { en: "Live features", de: "Live-Funktionen" }; +export const query = "pv=5400"; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const L = (de, en) => (r.lang === "de" ? de : en); + const set = (id, state, attrs = {}) => r.eval((a, b, c) => window.nfDemoSet(a, b, c), id, state, attrs); + const wait = (ms) => new Promise((ok) => setTimeout(ok, ms)); + + await r.quietClick({ text: "3D" }); + await wait(3500); + + await r.chapter({ en: "Live features", de: "Live-Funktionen" }, { en: "What happens in the house", de: "Was im Haus passiert" }); + r.say(S( + "Jetzt kommen die Live-Funktionen. Sie holen in die 3D-Ansicht, was im Haus gerade passiert: das Wetter, den Stromfluss, laufende Fernseher und Musik und das Auto. Sie sind eingebaut, kostenlos und brauchen keine Einrichtung außer den Geräten, die du schon hast.", + "Now come the live features. They bring into the 3D view what is happening in the house right now: the weather, the power flow, TVs and music that are playing, and the car. They are built in, free, and need no setup beyond the devices you already have.", + )); + await r.show(2, 800); + + // ------------------------------------------------------------------ weather + await r.chapter({ en: "Weather at the house", de: "Wetter am Haus" }, { en: "Rain, snow, fog and lightning", de: "Regen, Schnee, Nebel und Blitze" }); + r.say(S( + "Mit dem Schalter „Wetter“ unten zeigt die 3D-Ansicht das Wetter über deinem Grundstück. Dafür liest NextFloor eine Wetter-Entity aus Home Assistant. Gerade scheint die Sonne. Wir lassen es regnen.", + "With the “Weather” switch at the bottom the 3D view shows the weather over your plot. For that NextFloor reads a weather entity from Home Assistant. Right now the sun is shining. We make it rain.", + )); + await r.show(2, 1000); + await set("weather.zuhause", "rainy", { cloud_coverage: 85, wind_speed: 25, wind_speed_unit: "km/h" }); + await r.show(4, 2500); + r.say(S( + "Der Regen fällt schräg mit dem echten Wind, die Wolken ziehen mit ihren Schatten über das Grundstück und verdunkeln die Szene. Die Windrichtung hängt vom Kompass ab, den wir vorhin eingestellt haben.", + "The rain falls at an angle with the real wind, the clouds drift over the plot with their shadows and darken the scene. The wind direction depends on the compass we set earlier.", + )); + await r.orbit({ theta: 0.5, frames: 10 }); + await r.show(2, 800); + await set("weather.zuhause", "snowy", { cloud_coverage: 70, wind_speed: 8, wind_speed_unit: "km/h" }); + await r.show(4, 2500); + r.say(S( + "Bei Schnee schneit es leise. Genauso gibt es Hagel, Schneeregen, Nebel, Gewitter mit Blitzen, die neben dem Haus einschlagen, und bei klarem Wetter stehen Sonne und Mond in ihrer echten Richtung am Himmel.", + "With snow it snows quietly. There is hail, sleet, fog, thunderstorms with lightning that strikes beside the house, and in clear weather the sun and moon stand in the sky in their real direction.", + )); + await set("weather.zuhause", "lightning-rainy", { cloud_coverage: 95, wind_speed: 40, wind_speed_unit: "km/h" }); + await r.show(4, 2500); + await set("weather.zuhause", "sunny", { cloud_coverage: 5, wind_speed: 6, wind_speed_unit: "km/h" }); + await r.show(2.5, 2000); + r.say(S( + "Wer es ruhiger mag, schaltet den Schalter „Wetter“ aus oder wählt in den Editor-Einstellungen einzelne Effekte ab.", + "If you prefer it calmer, switch the “Weather” switch off or pick single effects in the editor settings.", + )); + await r.show(1.5); + + // ------------------------------------------------------------------ energy + await r.chapter({ en: "Energy flow", de: "Energiefluss" }, { en: "Sun, house, battery and grid", de: "Sonne, Haus, Akku und Netz" }); + r.say(S( + "Der Schalter „Stromfluss“ blendet die Energie ein. Die Solarmodule funkeln mit ihrer Produktion, und Energieteilchen fliegen in Bögen zum Wechselrichter und weiter zu den Verbrauchern.", + "The “Power flow” switch shows the energy. The solar modules sparkle with their production, and energy particles fly in arcs to the inverter and on to the consumers.", + )); + await r.click({ text: "Power flow", css: undefined }).catch((e) => console.log(" [skipped]", e.message)); + await r.show(4, 2500); + r.say(S( + "Je mehr Strom fließt, desto schneller und dichter sind die Teilchen. Eine Glaskarte über dem Dach zeigt die Bilanz: Solar, Verbrauch, Akku und Netzbezug, und wie autark das Haus gerade ist.", + "The more power flows, the faster and denser the particles are. A glass card over the roof shows the balance: solar, consumption, battery and grid draw, and how self-sufficient the house is right now.", + )); + await r.orbit({ theta: -0.6, frames: 12 }); + await r.show(2.5, 1500); + + // ------------------------------------------------------------------ TV and sound + await r.chapter({ en: "TV screens and sound", de: "Fernseher und Klang" }, { en: "What plays, in the model", de: "Was läuft, im Modell" }); + r.say(S( + "Fliegen wir ins Wohnzimmer. Der Fernseher läuft: Auf dem Bildschirm im Modell steht in der Farbe der App, was gerade läuft, hier Netflix. Dahinter leuchtet ein sanftes Ambilight an der Wand.", + "Let us fly into the living room. The TV is on: on the screen in the model, in the colour of the app, is what is playing right now, here Netflix. Behind it a soft ambilight glows on the wall.", + )); + await r.click({ text: "Erdgeschoss", nth: 0 }); + await r.show(1.5, 1500); + await r.click({ text: L("Wohnzimmer", "Living room") }); + await r.show(3, 2500); + await set("media_player.fernseher", "playing", { app_name: "YouTube", media_title: "Rooftop Sessions", media_artist: "Live" }); + await r.show(3, 2000); + r.say(S( + "Wechselt der Fernseher die App, wechselt die Farbe und der Titel. Das Ambilight lässt sich pro Fernseher in der Stärke einstellen oder ganz abschalten, wenn du hinter dem Fernseher eigene LED-Streifen hast.", + "When the TV changes the app, the colour and title change. The ambilight can be set in strength per TV or switched off completely if you have LED strips of your own behind the TV.", + )); + await r.show(1.5); + r.say(S( + "Laufen Lautsprecher oder Fernseher, schwebt über ihnen eine Karte mit Cover, Titel und Interpret. Antippen gibt dir Zurück, Wiedergabe oder Pause, Weiter und die Lautstärke. Schallringe in der Farbe der App breiten sich aus, lauter heißt weiter.", + "When speakers or TVs play, a card floats over them with cover, title and artist. Tapping gives you previous, play or pause, next and the volume. Sound rings in the colour of the app spread out, louder reaches further.", + )); + await set("media_player.lautsprecher", "playing", { app_name: "Spotify", media_title: "Blue Train", media_artist: "John Coltrane", volume_level: 0.5 }); + await r.click({ text: L("Alle Etagen", "All floors"), nth: 0 }); + await r.show(4, 3000); + await r.orbit({ theta: 0.4, frames: 8 }); + await r.show(1.5, 800); + r.say(S( + "Lautsprecher einer Multiroom-Gruppe verbindet ein leuchtender Faden. Mit dem Schalter „Karten“ blendest du alle schwebenden Karten gemeinsam aus oder ein.", + "Speakers of a multiroom group are joined by a glowing thread. With the “Cards” switch you hide or show all floating cards together.", + )); + await r.show(1.5); + + // ------------------------------------------------------------------ car + await r.chapter({ en: "The car", de: "Das Auto" }, { en: "Charge, range and controls", de: "Ladestand, Reichweite und Bedienung" }); + r.say(S( + "Zuletzt das Auto in der Garage. Über dem Stellplatz zeigt eine Glaskarte den Ladestand mit Farbring, die Reichweite, ob und mit wie viel Leistung geladen wird, den Stecker und die Innentemperatur. Dazu kommen Knöpfe für Schloss, Klima und Laden.", + "Last the car in the garage. Over the parking spot a glass card shows the charge with a colour ring, the range, whether and with how much power it is charging, the plug and the inside temperature. There are also buttons for lock, climate and charging.", + )); + await r.click({ text: L("Alle Etagen", "All floors"), nth: 0 }); + await r.show(4, 3000); + await r.spotAt({ css: ".live-card-car" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(3); + await r.spot(null); + r.say(S( + "Lädt das Auto, fliegen Energieteilchen von der Wallbox hinein. Ist das Auto weg, steht auf der Karte, wo es gerade ist. Die passenden Entitäten findet NextFloor selbst am Gerät des Autos.", + "While the car charges, energy particles fly into it from the wallbox. When the car is away, the card says where it is. NextFloor finds the matching entities on the device of the car by itself.", + )); + await r.show(2.5); +} diff --git a/frontend/tutorial/episodes/15-extensions.mjs b/frontend/tutorial/episodes/15-extensions.mjs new file mode 100644 index 0000000..becb580 --- /dev/null +++ b/frontend/tutorial/episodes/15-extensions.mjs @@ -0,0 +1,67 @@ +import { DEEP } from "../lib.mjs"; +import { writeSampleGlb } from "../sample-model.mjs"; + +export const title = { en: "Extensions: own models and packs", de: "Erweiterungen: eigene Modelle und Packs" }; + +export const keepState = true; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const L = (de, en) => (r.lang === "de" ? de : en); + const glb = writeSampleGlb("/tmp/tutorial-sample.glb"); + + await r.chapter({ en: "Your own 3D models", de: "Eigene 3D-Modelle" }, { en: "The Extensions tab", de: "Der Reiter Erweiterungen" }); + r.say(S( + "Der dritte Reiter heißt Erweiterungen. Hier lädst du eigene 3D-Modelle hoch, ohne etwas von Hand auf den Server kopieren zu müssen.", + "The third tab is called Extensions. Here you upload 3D models of your own, without having to copy anything to the server by hand.", + )); + await r.click({ text: "Extensions" }); + await r.show(3, 1200); + r.say(S( + "Für einige Fahrzeuge kann NextFloor ein echtes 3D-Modell zeigen, wenn du eines besitzt, zum Beispiel für dein eigenes Auto. Jede Zeile ist ein Platz: Sie nennt das Fahrzeug und den Dateinamen, und daneben steht, ob schon ein Modell vorhanden ist.", + "For some vehicles NextFloor can show a real 3D model if you own one, for example of your own car. Every row is a slot: it names the vehicle and the file name, and next to it says whether a model is present already.", + )); + await r.show(2.5); + r.say(S( + "Wir wählen beim Tesla Model 3 „Modell hinzufügen“ und eine Datei im glb-Format aus. NextFloor bereitet das Modell direkt im Browser auf: Es dreht es richtig herum, macht es leichter, entfernt Texturen und markiert den Lack, damit er sich später umfärben lässt. Dann legt es die Datei auf deinem Home Assistant ab.", + "For the Tesla Model 3 we choose “Add a model” and a file in glb format. NextFloor prepares the model right in the browser: it turns it the right way round, makes it lighter, removes textures and marks the paint so that it can be recoloured later. Then it stores the file on your Home Assistant.", + )); + const at = await r.point({ text: L("Modell hinzufügen …", "Add a model …"), nth: 1 }); + await r.page.evaluate((x, y) => window.__tut.ripple(x, y), at.x, at.y); + await r.frame(); + // the file dialog of the system cannot be filmed: the chosen file is handed to the page's file field directly + const input = await r.page.evaluateHandle(`(() => { ${DEEP} return all("input[type=file]")[1]; })()`); + await input.uploadFile(glb); + await r.show(3, 3500); + r.say(S( + "Fertig: Bei diesem Platz steht jetzt „vorhanden“, und du kannst das Modell ersetzen oder entfernen. Nur Administratoren können Modelle hochladen. Modelle bis zwölf Megabyte werden angenommen. Ein Fahrzeug ohne Modell sieht aus wie bisher.", + "Done: this slot now says “in place”, and you can replace or remove the model. Only administrators can upload models. Models up to twelve megabytes are accepted. A vehicle without a model looks as it did before.", + )); + await r.show(2.5); + r.say(S( + "Die Möbel-Packs brauchen keine Einrichtung: Sie sind alle schon da und stehen in der Möbelbibliothek des Editors. Wenn du sehen möchtest, wie jedes einzelne Modell aussieht, gibt es in der Online-Demo eine Modellschau.", + "The furniture packs need no setup: they are all there already and are listed in the furniture library of the editor. If you want to see what every single model looks like, the online demo has a model showcase.", + )); + await r.show(1.5); + + // ------------------------------------------------------------------ showcase + await r.chapter({ en: "The model showcase", de: "Die Modellschau" }, { en: "Every model, live", de: "Jedes Modell, live" }); + await r.navigate("showcase&set=pack%3Aa_wohnzimmer"); + await r.show(3, 2500); + r.say(S( + "Die Modellschau zeigt alle Modelle in einem Raum, zehn pro Seite, in der Reihenfolge, in der sie stehen. Die Namen stehen in der Liste unten links.", + "The model showcase shows all models in one room, ten per page, in the order in which they stand. The names are listed at the bottom left.", + )); + await r.show(2.5); + r.say(S( + "Über die Auswahl wechselst du die Gruppe, grundlegende Modelle oder eines der Packs. Mit „weiter“ und „zurück“ blätterst du, und das 3D-Modell lässt sich wie immer drehen und zoomen.", + "With the selection you change the group, basic models or one of the packs. With “next” and “previous” you page through, and the 3D model can be turned and zoomed as always.", + )); + await r.click({ text: L("weiter ›", "next ›") }); + await r.reinject(); + await r.show(3, 3000); + await r.click({ text: L("weiter ›", "next ›") }); + await r.reinject(); + await r.show(3, 3000); +} diff --git a/frontend/tutorial/episodes/16-dashboard-card.mjs b/frontend/tutorial/episodes/16-dashboard-card.mjs new file mode 100644 index 0000000..7c0bda6 --- /dev/null +++ b/frontend/tutorial/episodes/16-dashboard-card.mjs @@ -0,0 +1,81 @@ +export const title = { en: "The dashboard card", de: "Die Dashboard-Karte" }; +export const keepState = true; +export const query = "card"; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const L = (de, en) => (r.lang === "de" ? de : en); + const wait = (ms) => new Promise((ok) => setTimeout(ok, ms)); + + await r.chapter({ en: "The dashboard card", de: "Die Dashboard-Karte" }, { en: "Your house on any dashboard", de: "Dein Haus auf jedem Dashboard" }); + r.say(S( + "Das Modell musst du nicht im Panel öffnen: NextFloor bringt eine Dashboard-Karte mit, die das Haus auf jedem Home-Assistant-Dashboard zeigt. Hier siehst du links den visuellen Editor der Karte, so wie ihn Home Assistant im Karten-Dialog zeigt, und rechts die Karte selbst.", + "You do not have to open the model in the panel: NextFloor brings a dashboard card that shows the house on any Home Assistant dashboard. On the left you see the visual editor of the card, just as Home Assistant shows it in the card dialog, and on the right the card itself.", + )); + await r.show(3, 2500); + r.say(S( + "Du fügst die Karte in einem Dashboard über „Karte hinzufügen“ hinzu und suchst nach NextFloor. Eine Zeile Konfiguration reicht: Typ „custom:nextfloor-card“. Alles Weitere stellst du bequem im Editor ein, und die Karte rechts folgt sofort.", + "You add the card to a dashboard with “Add card” and search for NextFloor. One line of configuration is enough: type “custom:nextfloor-card”. Everything else you set conveniently in the editor, and the card on the right follows immediately.", + )); + await r.show(2.5); + + r.say(S( + "Oben legst du fest, was die Karte zeigt. „Etage“ wählt das ganze Haus oder eine einzelne Etage, mit der die Karte startet. „Größe“ legt fest, ob sie eine feste Höhe hat oder den Bildschirm füllt. Wir wählen das ganze Haus.", + "At the top you decide what the card shows. “Floor” picks the whole house or a single floor that the card starts with. “Size” decides whether it has a fixed height or fills the screen. We choose the whole house.", + )); + await r.choose({ label: "card_floor" }, L("Ganzes Haus (Etage antippen öffnet sie)", "Whole house (tap a floor to open it)")).catch((e) => console.log(" [skipped]", e.message)); + await r.show(3, 2500); + r.say(S( + "„Aussehen“ wechselt zwischen Neon, Blueprint und Tag, und die Akzentfarbe färbt Linien und Knöpfe um. „Wände“ stellt Hohe Wände oder Schnitt ein, die Qualität kennst du schon, und „Etagen darunter“ bestimmt, ob die Etagen unter der gewählten gedimmt, gestapelt oder ausgeblendet erscheinen.", + "“Look” switches between Neon, Blueprint and Day, and the accent colour recolours lines and buttons. “Walls” sets Tall walls or Cut, you know the quality already, and “Floors below” decides whether the floors below the chosen one appear dimmed, stacked or hidden.", + )); + await r.choose({ label: "theme" }, "Blueprint"); + await r.show(2.5, 2000); + await r.choose({ label: "theme" }, "Neon"); + await r.show(1.5, 1500); + r.say(S( + "Im Abschnitt „Anzeige“ stellst du Symbole, Heatmap, Stromfluss und Karten ein. Stromfluss und Karten können dem Betrachter überlassen werden, mit einem Schalter in der Karte, oder immer an oder immer aus sein. Wir schalten die Symbole auf „Alle“.", + "In the “Show” section you set markers, heat map, power flow and cards. Power flow and cards can be left to the viewer, with a switch in the card, or be always on or always off. We set the markers to “All”.", + )); + await r.choose({ label: "markers" }, L("Alle", "All")); + await r.show(3, 2500); + await r.choose({ label: "markers" }, L("Wichtige", "Important")); + await r.show(1, 1000); + r.say(S( + "Darunter sitzen Kästchen für die Schalter in der Karte, den Stern mit dem Zentralmenü, eigene Namen an den Symbolen und die Option, mit versteckten Bedienelementen zu starten, damit nur das 3D-Bild bleibt. Weitere Optionen: Etagen als Miniaturen, Raumnamen, Energiewerte oben, Raumdetails beim Antippen, ein Vollbild-Knopf und das Auseinanderziehen der Etagen.", + "Below are checkboxes for the switches in the card, the star with the central menu, own names at the markers, and the option to start with the controls hidden so that only the 3D picture remains. More options: floors as miniatures, room names, energy values at the top, room details on tap, a full-screen button and the pulling apart of the floors.", + )); + await r.eval(() => { + const walk = (root) => { for (const el of root.querySelectorAll("*")) { if (el.tagName === "H3" && /Features|Funktionen/.test(el.textContent)) { el.scrollIntoView({ block: "start" }); return true; } if (el.shadowRoot && walk(el.shadowRoot)) return true; } return false; }; + walk(document); + }); + await r.show(3, 800); + r.say(S( + "Unter „Funktionen“ schaltest du Warnungen, den Sprung in den Raum einer neuen Warnung, Szenen-Knöpfe im Raum und das Wetter am Haus ein oder aus. Warnungen zeigen Rauch, Gas, CO, Wasser, Alarmanlage und offene Fenster bei Regen als Banner über der Karte.", + "Under “Features” you switch warnings, the jump into the room of a new warning, scene buttons in the room and the weather at the house on or off. Warnings show smoke, gas, CO, water, alarm panel and open windows in the rain as a banner over the card.", + )); + await r.show(2.5); + + // ------------------------------------------------------------------ kiosk + await r.chapter({ en: "A wall tablet", de: "Ein Wandtablet" }, { en: "Kiosk mode", de: "Der Kiosk-Modus" }); + r.say(S( + "Ganz unten steht der Abschnitt „Wandtablet“. Damit wird die Karte zum Dauerbetrieb an der Wand: Nach einer Zeit ohne Berührung kehrt sie von selbst zur Startansicht zurück, damit niemand in einem Raum hängen bleibt.", + "At the very bottom is the section “Wall tablet”. It turns the card into a permanent display on the wall: after a time without a touch it returns to the start view by itself, so that nobody stays stuck in a room.", + )); + await r.eval(() => { + const walk = (root) => { for (const el of root.querySelectorAll("*")) { if (el.tagName === "H3" && /kiosk|Wandtablet/i.test(el.textContent)) { el.scrollIntoView({ block: "start" }); return true; } if (el.shadowRoot && walk(el.shadowRoot)) return true; } return false; }; + walk(document); + }); + await r.show(3, 800); + r.say(S( + "Die Nachtabdunkelung dimmt die Karte nachts, entweder nach der Sonne oder in einem Zeitraum, den du angibst. Dabei ruhen Farbeffekte, und die Anzeige wird dunkel, damit das Tablet im Schlafzimmer nicht blendet. Als Bildschirmschoner dreht sich nach der Rückkehr die Kamera langsam um das Haus. Ein Knopf kann außerdem zu einem anderen Dashboard führen.", + "Night dimming darkens the card at night, either by the sun or in a time range you give. Colour effects rest, and the display goes dark so that the tablet in the bedroom does not dazzle. As a screensaver the camera turns slowly around the house after the return. A button can also lead to another dashboard.", + )); + await r.show(3); + r.say(S( + "Für Tablets stellst du die Qualität auf „Tablet“. Das ist die leichteste Einstellung und ideal für Fire-Tablets und andere Wandtablets.", + "For tablets you set the quality to “Tablet”. That is the lightest setting and ideal for Fire tablets and other wall tablets.", + )); + await r.show(2.5); +} diff --git a/frontend/tutorial/episodes/17-backup-outro.mjs b/frontend/tutorial/episodes/17-backup-outro.mjs new file mode 100644 index 0000000..d3d4bb7 --- /dev/null +++ b/frontend/tutorial/episodes/17-backup-outro.mjs @@ -0,0 +1,62 @@ +export const title = { en: "Backup, moving and wrap-up", de: "Sicherung, Umzug und Abschluss" }; + +const S = (de, en) => ({ de, en }); + +export async function run(r) { + const L = (de, en) => (r.lang === "de" ? de : en); + const wait = (ms) => new Promise((ok) => setTimeout(ok, ms)); + + await r.quietClick({ text: "Editor" }); + await r.quietClick({ text: "Erdgeschoss" }); + await r.page.mouse.move(640, 360); + + await r.chapter({ en: "Backup and moving", de: "Sicherung und Umzug" }, { en: "Keeping your plan safe", de: "Deinen Plan sicher aufbewahren" }); + r.say(S( + "Dein Plan ist jetzt viel Arbeit wert. Damit er nicht verloren geht, gibt es im Editor ganz unten den Abschnitt „Sicherung“. Wir klappen ihn auf.", + "Your plan is worth a lot of work now. So that it is not lost, the editor has a “Backup” section at the very bottom. We unfold it.", + )); + await r.click({ key: "backup" }); + await r.show(1.5, 800); + r.say(S( + "„Exportieren“ speichert den Plan als Datei, „Importieren“ liest ihn wieder ein, auch in einer anderen Installation. „Als Vorlage teilen“ erzeugt eine Datei ohne persönliche Angaben wie Geräte, die du mit anderen teilen kannst.", + "“Export” saves the plan as a file, “Import” reads it in again, also in another installation. “Share as template” makes a file without personal details such as devices, which you can share with others.", + )); + await r.spotAt({ text: "Export" }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(2.5); + await r.spot(null); + r.say(S( + "„Alles sichern“ packt zusätzlich alle Hintergrund- und Bildschirmbilder und die installierten Packs in eine einzige Datei. Mit „Vollsicherung wiederherstellen“ spielst du sie in dieselbe oder eine andere Installation zurück. Der Plan, die Bilder und die Packs liegen in Home Assistant unter „.storage“, und nichts davon verlässt deine Installation.", + "“Back up everything” also packs all background and screen pictures and the installed packs into a single file. With “Restore a full backup” you play it back into the same or another installation. The plan, the pictures and the packs live in Home Assistant under “.storage”, and none of it leaves your installation.", + )); + await r.spotAt({ text: L("Alles sichern (Plan, Bilder, Packs)", "Back up everything (plan, pictures, packs)") }).catch((e) => console.log(" [skipped spot]", e.message)); + await r.show(3); + await r.spot(null); + r.say(S( + "Vor größeren Änderungen lohnt sich eine Sicherung. Und falls doch etwas schiefgeht: „Rückgängig“ im Editor und die Tastenkombination Strg plus Z machen die letzten Schritte ungeschehen.", + "Before bigger changes a backup is worth it. And if something does go wrong: “Undo” in the editor and the key combination Ctrl plus Z take back the last steps.", + )); + await r.show(2); + + await r.chapter({ en: "That's it", de: "Das war's" }, { en: "Your home, in NextFloor", de: "Dein Zuhause in NextFloor" }); + await r.click({ text: "3D" }); + await wait(3500); + await r.frame(); + r.say(S( + "Das war die komplette Einrichtung von NextFloor von Grund auf: Etagen, Räume, Türen und Fenster, Möbel, Geräte, Außenflächen, Treppe, Dach und Solarstrom, Kompass und Karte, und dazu die Bedienung in 3D, die Live-Funktionen, eigene Modelle, die Dashboard-Karte und die Sicherung.", + "That was the complete setup of NextFloor from scratch: floors, rooms, doors and windows, furniture, devices, outdoor areas, stairs, roof and solar power, compass and map, plus operating it in 3D, the live features, own models, the dashboard card and the backup.", + )); + await r.show(3, 1000); + await r.orbit({ theta: 1.2, frames: 24 }); + await r.show(2, 800); + r.say(S( + "Nimm dir für dein eigenes Haus ruhig Zeit. Wichtig sind zuerst die Räume und die Wände, alles Weitere kannst du jederzeit ergänzen. Und denk daran: Rückgängig ist immer nur einen Klick entfernt.", + "Take your time with your own house. What matters first are the rooms and walls, everything else you can add at any time. And remember: undo is always only a click away.", + )); + await r.show(2, 800); + r.say(S( + "Wenn du Fragen hast, etwas nicht funktioniert oder dir eine Funktion fehlt, melde dich auf GitHub. Über „Problem melden“ und „Idee vorschlagen“ im Editor kommst du direkt dorthin. NextFloor ist kostenlos und Open Source. Viel Spaß mit deinem Zuhause in 3D!", + "If you have questions, something does not work or you miss a feature, get in touch on GitHub. “Report a problem” and “Propose an idea” in the editor take you straight there. NextFloor is free and open source. Have fun with your home in 3D!", + )); + await r.orbit({ theta: -1.2, frames: 24 }); + await r.show(4, 1500); +} diff --git a/frontend/tutorial/explore.mjs b/frontend/tutorial/explore.mjs new file mode 100644 index 0000000..f315bfa --- /dev/null +++ b/frontend/tutorial/explore.mjs @@ -0,0 +1,23 @@ +import { launch, serve, DEEP } from "./lib.mjs"; +const { server, base } = await serve(); +const { browser, page } = await launch(1280, 720); +await page.evaluateOnNewDocument(() => localStorage.clear()); +await page.goto(`${base}/preview/index.html?${process.env.QUERY ?? "empty"}&noshowcase&lang=en&ha=dark`, { waitUntil: "networkidle0", timeout: 120000 }); +await new Promise((r) => setTimeout(r, 1500)); +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); +const click = (text) => page.evaluate(`(() => { ${DEEP} const el = all("button, summary").filter(visible).find((e) => textOf(e) === ${JSON.stringify(text)} || textOf(e).startsWith(${JSON.stringify(text)})); if (el) el.click(); return !!el; })()`); +const dump = (name) => page.evaluate(`(() => { ${DEEP} return all("button, select, input, summary, label, h3").filter(visible).map((el) => el.tagName.toLowerCase() + ":" + (textOf(el).slice(0,50) || el.getAttribute("aria-label") || el.title || el.placeholder || el.type)); })()`); +for (const step of (process.env.STEPS ?? "Open editor").split("|")) { + if (step.startsWith("@")) { // @x,y click at coordinates; @drag x1,y1,x2,y2 + const [kind, rest] = step.slice(1).split(" "); + const n = rest.split(",").map(Number); + if (kind === "click") await page.mouse.click(n[0], n[1]); + if (kind === "wheel") { await page.mouse.move(n[0], n[1]); await page.mouse.wheel({ deltaY: n[2] }); } + if (kind === "key") await page.keyboard.press(rest); + if (kind === "drag") { await page.mouse.move(n[0], n[1]); await page.mouse.down(); for (let i = 1; i <= 12; i++) { await page.mouse.move(n[0] + ((n[2] - n[0]) * i) / 12, n[1] + ((n[3] - n[1]) * i) / 12); await wait(30); } await page.mouse.up(); } + } else console.log("click", step, await click(step)); + await wait(900); +} +await page.screenshot({ path: "/tmp/tut-x.png" }); +console.log((await dump()).join("\n")); +await browser.close(); server.close(); diff --git a/frontend/tutorial/key.py b/frontend/tutorial/key.py new file mode 100644 index 0000000..652c381 --- /dev/null +++ b/frontend/tutorial/key.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Finds the i18n keys of UI texts: python3 tutorial/key.py "Add floor" "Rectangle" (case-insensitive, substring).""" +import os,re,sys +src=open(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..","src","i18n.ts")).read() +en=src[src.index("const en:"):] +de=src[:src.index("const en:")] +pairs=re.findall(r'^ ([a-z0-9_]+): (?:"((?:[^"\\]|\\.)*)"|`([^`]*)`),?$',en,flags=re.M) +dpairs=dict((k,a or b) for k,a,b in re.findall(r'^ ([a-z0-9_]+): (?:"((?:[^"\\]|\\.)*)"|`([^`]*)`),?$',de,flags=re.M)) +for q in sys.argv[1:]: + for k,a,b in pairs: + v=a or b + if q.lower() in v.lower(): + print(f"{k:32} | {v[:60]:60} | {dpairs.get(k,'')[:50]}") diff --git a/frontend/tutorial/lib.mjs b/frontend/tutorial/lib.mjs new file mode 100644 index 0000000..dc792e6 --- /dev/null +++ b/frontend/tutorial/lib.mjs @@ -0,0 +1,36 @@ +// Shared helpers of the tutorial recorder: a static server for the repository, a headless Chrome, and shadow-DOM aware finders. +import { createServer } from "node:http"; +import { existsSync, readFileSync } from "node:fs"; +import { extname, join, normalize, resolve } from "node:path"; +import puppeteer from "puppeteer-core"; + +export const root = resolve(import.meta.dirname, "..", ".."); +const TYPES = { ".html": "text/html", ".js": "text/javascript", ".mjs": "text/javascript", ".css": "text/css", ".png": "image/png", ".json": "application/json", ".svg": "image/svg+xml" }; + +export async function serve() { + const server = createServer((req, res) => { + const path = normalize(decodeURIComponent(new URL(req.url, "http://x").pathname)).replace(/^([/\\])+/, ""); + const file = join(root, path); + if (!file.startsWith(root) || !existsSync(file)) return void res.writeHead(404).end(); + res.writeHead(200, { "content-type": TYPES[extname(file)] ?? "application/octet-stream" }).end(readFileSync(file)); + }); + await new Promise((ok) => server.listen(0, "127.0.0.1", ok)); + return { server, base: `http://127.0.0.1:${server.address().port}` }; +} + +export async function launch(width = 1280, height = 720) { + const exe = [process.env.CHROME_PATH, "/usr/bin/chromium", "/usr/bin/google-chrome", `${process.env.HOME}/.cache/ms-playwright/chromium-1234/chrome-linux64/chrome`].filter(Boolean).find((p) => existsSync(p)); + const args = ["--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist", ...(process.getuid?.() === 0 ? ["--no-sandbox"] : [])]; + const browser = await puppeteer.launch({ executablePath: exe, headless: true, args }); + const page = await browser.newPage(); + await page.setViewport({ width, height, deviceScaleFactor: 1 }); + return { browser, page }; +} + +/** Runs code in the page with a deep finder (through shadow roots) at hand: find(text) → button, findAll(selector) → elements. */ +export const DEEP = ` + const deep = (root, visit) => { for (const el of root.querySelectorAll("*")) { visit(el); if (el.shadowRoot) deep(el.shadowRoot, visit); } }; + const all = (selector) => { const out = []; const walk = (root) => { out.push(...root.querySelectorAll(selector)); for (const el of root.querySelectorAll("*")) if (el.shadowRoot) walk(el.shadowRoot); }; walk(document); return out; }; + const visible = (el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0 && getComputedStyle(el).visibility !== "hidden"; }; + const textOf = (el) => (el.textContent || "").replace(/\\s+/g, " ").trim(); +`; diff --git a/frontend/tutorial/rec.mjs b/frontend/tutorial/rec.mjs new file mode 100644 index 0000000..0ec89fc --- /dev/null +++ b/frontend/tutorial/rec.mjs @@ -0,0 +1,402 @@ +// The recorder: drives the demo like a user would and writes a video as a list of stills with durations. +// +// Time in the video is made, not measured: every `frame()` adds 1/FPS, and `hold(s)` makes the last still last longer. So an +// action that needs a second to settle costs nothing in the video, and a gliding mouse is as smooth as the frames we take of it. +// Narration is a list of segments (German and English text); a segment lasts at least as long as its text takes to speak. +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { DEEP, launch, serve } from "./lib.mjs"; + +export const FPS = 10; +const WORDS_PER_SECOND = { en: 2.5, de: 2.2 }; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const easing = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2); + +/** How long a text takes to speak, in seconds (slow and clear: this is a tutorial). */ +export function speechSeconds(text, lang) { + const words = String(text).trim().split(/\s+/).filter(Boolean).length; + return words / WORDS_PER_SECOND[lang] + 0.5; +} + +export class Recorder { + constructor({ out, lang, t }) { + this.out = out; + this.lang = lang; + this.t = t; // (key, vars) → the UI text in the recording's language + this.frames = []; + this.segments = []; + this.chapters = []; + this.open = null; // the segment being filled + this.cursor = { x: 640, y: 360 }; + mkdirSync(join(out, "frames"), { recursive: true }); + } + + async start({ query, width = 1280, height = 720 }) { + this.width = width; + this.height = height; + const { server, base } = await serve(); + this.server = server; + const { browser, page } = await launch(width, height); + this.browser = browser; + this.page = page; + page.on("pageerror", (e) => console.log(" [page error]", e.message)); + await page.evaluateOnNewDocument(() => localStorage.clear()); + await page.goto(`${base}/preview/index.html?noshowcase&lang=${this.lang}&ha=dark${query ? "&" + query : ""}`, { waitUntil: "networkidle0", timeout: 180000 }); + await sleep(2000); + await page.evaluate(OVERLAY); + this.base = base; + } + + get time() { + return this.frames.reduce((a, f) => a + f.dur, 0); + } + + // ------------------------------------------------------------------ frames and time + async frame() { + const file = `frames/f${String(this.frames.length).padStart(6, "0")}.jpg`; + await this.page.screenshot({ path: join(this.out, file), type: "jpeg", quality: 88 }); + this.frames.push({ file, dur: 1 / FPS }); + } + + /** Waits until the page has settled, takes a frame, and lets it stand for `seconds`. */ + async show(seconds = 1.5, settle = 500) { + await sleep(settle); + await this.frame(); + this.hold(seconds - 1 / FPS); + } + + hold(seconds) { + if (seconds > 0 && this.frames.length) this.frames.at(-1).dur += seconds; + } + + // ------------------------------------------------------------------ narration + /** Starts a narration segment; the following actions belong to it until the next `say`. */ + say(text) { + this.endSegment(); + this.open = { start: this.time, de: text.de, en: text.en, chapter: this.chapters.length }; + } + + endSegment() { + const s = this.open; + if (!s) return; + const need = Math.max(speechSeconds(s.de, "de"), speechSeconds(s.en, "en")); + const have = this.time - s.start; + if (have < need) this.hold(need - have); + s.end = this.time; + this.segments.push(s); + this.open = null; + } + + /** A title card between two chapters. */ + async chapter(title, subtitle) { + this.endSegment(); + const label = title[this.lang]; + await this.page.evaluate((a, b) => window.__tut.card(a, b), label, subtitle?.[this.lang] ?? ""); + await sleep(300); + this.chapters.push({ start: this.time, title }); + await this.frame(); + this.hold(2.4); + await this.page.evaluate(() => window.__tut.card(null)); + await sleep(200); + } + + // ------------------------------------------------------------------ finding things + /** The centre of a thing on screen: { key } a UI text by its i18n key, { text }, { css }, or { x, y }. */ + async locate(target) { + if (typeof target === "function") target = await target(); + if (target.x !== undefined) return { x: target.x, y: target.y }; + const text = target.key ? this.t(target.key, target.vars) : target.label ? this.t(target.label, target.vars) : target.text; + const asLabel = !!target.label; + const found = await this.page.evaluate( + `(() => { ${DEEP} + const want = ${JSON.stringify(text ?? null)}; const asLabel = ${asLabel}; const css = ${JSON.stringify(target.css ?? null)}; const nth = ${target.nth ?? 0}; const near = ${JSON.stringify(target.near ?? null)}; const within = ${JSON.stringify(target.within ?? null)}; + let list; + if (css) list = all(css); + else if (asLabel) { const own = (el) => [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent).join("").replace(/\\s+/g, " ").trim(); list = all("label").filter(visible).filter((el) => own(el) === want || own(el).startsWith(want + " (")); } + else { + const pool = all("button, summary, label, a, [role=tab], [role=option], option, h3, .nf-chip").filter(visible); + const tiers = [(el) => textOf(el) === want || (el.firstElementChild && textOf(el.firstElementChild) === want), (el) => textOf(el).startsWith(want), (el) => textOf(el).replace(/^[^\\p{L}\\p{N}]+/u, "").startsWith(want), (el) => want.length > 2 && textOf(el).includes(want)]; + list = []; + for (const tier of tiers) { list = pool.filter(tier); if (list.length) break; } + } + list = list.filter(visible); + if (near) list = list.filter((el) => { let a = el; for (let i = 0; i < 4 && a; i++) { a = a.parentElement || (a.getRootNode && a.getRootNode().host); if (a && textOf(a).length < 90 && textOf(a).startsWith(near)) return true; } return false; }); + if (within) { const root = all(within)[0]; if (root) list = list.filter((el) => root.contains(el) || (root.shadowRoot && root.shadowRoot.contains(el))); } + const el = list[nth]; if (!el) return null; + el.scrollIntoView({ block: "center", inline: "nearest" }); + const r = el.getBoundingClientRect(); + return { x: Math.round(r.left + (el.tagName === "INPUT" || el.tagName === "SELECT" ? Math.min(r.width / 2, 120) : r.width / 2)), y: Math.round(r.top + r.height / 2), w: Math.round(r.width), h: Math.round(r.height), left: r.left, top: r.top }; + })()`, + ); + if (!found) throw new Error(`not found on screen: ${JSON.stringify(target)} (${text ?? ""})`); + return found; + } + + // ------------------------------------------------------------------ the mouse + async glide(x, y, { frames = 10, hover = true } = {}) { + const from = { ...this.cursor }; + const steps = Math.max(2, Math.round(frames * Math.min(1, Math.hypot(x - from.x, y - from.y) / 300 + 0.3))); + for (let i = 1; i <= steps; i++) { + const k = easing(i / steps); + const px = from.x + (x - from.x) * k; + const py = from.y + (y - from.y) * k; + this.cursor = { x: px, y: py }; + await this.page.evaluate((a, b) => window.__tut.move(a, b), px, py); + if (hover) await this.page.mouse.move(px, py); + await this.frame(); + } + } + + async point(target, opts) { + const at = await this.locate(target); + await this.glide(at.x, at.y, opts); + return at; + } + + /** A click that is not filmed (setting the stage between episodes). */ + async quietClick(target) { + const at = await this.locate(target); + await this.page.mouse.click(at.x, at.y); + await sleep(700); + } + + async click(target, { settle = 600, after = 0.6 } = {}) { + const at = await this.point(target); + await this.page.evaluate((a, b) => window.__tut.ripple(a, b), at.x, at.y); + await this.frame(); + await this.page.mouse.click(at.x, at.y); + await sleep(settle); + await this.frame(); + this.hold(after); + return at; + } + + /** Presses and holds (the quick menu opens on a long press). */ + async longPress(target, { hold = 0.9 } = {}) { + const at = await this.point(target); + await this.page.evaluate((a, b) => window.__tut.ripple(a, b), at.x, at.y); + await this.page.mouse.move(at.x, at.y); + await this.page.mouse.down(); + await sleep(hold * 1000); + await this.page.mouse.up(); + await sleep(700); + await this.frame(); + this.hold(0.6); + } + + /** Presses and drags between two points, with a frame on the way every few pixels. */ + async drag(from, to, { frames = 14, up = true } = {}) { + await this.glide(from.x, from.y); + await this.page.mouse.move(from.x, from.y); + await this.page.mouse.down(); + for (let i = 1; i <= frames; i++) { + const k = easing(i / frames); + const x = from.x + (to.x - from.x) * k; + const y = from.y + (to.y - from.y) * k; + this.cursor = { x, y }; + await this.page.evaluate((a, b) => window.__tut.move(a, b), x, y); + await this.page.mouse.move(x, y); + await this.frame(); + } + if (up) await this.page.mouse.up(); + await sleep(500); + await this.frame(); + } + + async typeInto(target, text, { clear = true } = {}) { + const at = await this.click(target, { after: 0.1 }); + if (clear) { + await this.page.keyboard.down("Control"); + await this.page.keyboard.press("KeyA"); + await this.page.keyboard.up("Control"); + } + let i = 0; + for (const ch of text) { + await this.page.keyboard.type(ch, { delay: 20 }); + if (++i % 3 === 0 || i === text.length) await this.frame(); + } + await this.page.keyboard.press("Enter"); + await this.page.keyboard.press("Tab"); + await sleep(400); + await this.frame(); + this.hold(0.4); + return at; + } + + async key(name, { frames = 1 } = {}) { + await this.page.keyboard.press(name); + await sleep(500); + for (let i = 0; i < frames; i++) await this.frame(); + } + + /** Where a point of the plan (metres) lies on the screen, in the editor's drawing. */ + async planPoint(x, z) { + const at = await this.page.evaluate( + `(() => { ${DEEP} const e = all("nf-editor")[0]; const svg = e.renderRoot.querySelector("svg"); const r = svg.getBoundingClientRect(); const p = e.toScreen([${x}, ${z}]); return { x: r.left + p[0], y: r.top + p[1] }; })()`, + ); + return at; + } + + /** Sets a drop-down: the pointer goes to it, the choice is made and shown. */ + async choose(target, optionText) { + const at = await this.point(target); + await this.page.evaluate((a, b) => window.__tut.ripple(a, b), at.x, at.y); + await this.frame(); + const ok = await this.page.evaluate( + `(() => { ${DEEP} const label = ${JSON.stringify(target.label ? this.t(target.label) : target.text ?? (target.key ? this.t(target.key) : null))}; const own = (el) => [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent).join("").replace(/\\s+/g, " ").trim(); const select = all("select").filter(visible).find((s) => { const l = s.closest("label"); return l && (own(l) === label || own(l).startsWith(label + " (")); }); if (!select) return false; const o = [...select.options].find((o) => o.textContent.trim() === ${JSON.stringify(optionText)}); if (!o) return false; select.value = o.value; select.dispatchEvent(new Event("input", { bubbles: true })); select.dispatchEvent(new Event("change", { bubbles: true })); return true; })()`, + ); + if (!ok) throw new Error(`no drop-down option: ${optionText}`); + await sleep(500); + await this.frame(); + this.hold(0.5); + } + + // ------------------------------------------------------------------ pointing things out + /** A pulsing frame around an area of the screen (null removes it). */ + async spot(rect, { pad = 6 } = {}) { + if (rect && rect.w === undefined && rect.x !== undefined) rect = null; + await this.page.evaluate((r, p) => window.__tut.spot(r, p), rect, pad); + } + + async spotAt(target, opts) { + const at = await this.locate(target); + await this.spot({ left: at.left, top: at.top, w: at.w, h: at.h }, opts); + return at; + } + + /** A frame around several things at once (a toolbar). */ + async spotUnion(targets, opts) { + const rects = []; + for (const t of targets) rects.push(await this.locate(t)); + const left = Math.min(...rects.map((r) => r.left)); + const top = Math.min(...rects.map((r) => r.top)); + const right = Math.max(...rects.map((r) => r.left + r.w)); + const bottom = Math.max(...rects.map((r) => r.top + r.h)); + await this.spot({ left, top, w: right - left, h: bottom - top }, opts); + } + + /** A small note in the picture (a keyboard shortcut, a value). */ + async note(text) { + await this.page.evaluate((t) => window.__tut.note(t), text); + } + + /** Picks a device in an entity field: the pointer goes to the field under the label, the search text is typed and the entry clicked. */ + async pick(labelKey, query, optionText) { + const label = this.t(labelKey); + const at = await this.page.evaluate( + `(() => { ${DEEP} const want = ${JSON.stringify(label)}; const lab = all("label, div, span").filter(visible).find((el) => { const own = [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent).join("").replace(/\\s+/g, " ").trim(); return own === want; }); if (!lab) return null; lab.scrollIntoView({ block: "center" }); const lr = lab.getBoundingClientRect(); const input = all("input").filter(visible).filter((i) => { const q = i.getBoundingClientRect(); return q.top >= lr.top + 4 && q.top - lr.bottom < 90 && q.left < lr.right + 40 && q.right > lr.left - 40; }).sort((x, y) => x.getBoundingClientRect().top - y.getBoundingClientRect().top)[0]; if (!input) return null; input.scrollIntoView({ block: "center" }); const r = input.getBoundingClientRect(); return { x: Math.round(r.left + Math.min(r.width / 2, 140)), y: Math.round(r.top + r.height / 2) }; })()`, + ); + if (!at) throw new Error(`no entity field under: ${label}`); + await this.click(at, { after: 0.2 }); + await this.page.keyboard.down("Control"); + await this.page.keyboard.press("KeyA"); + await this.page.keyboard.up("Control"); + for (const ch of query) { + await this.page.keyboard.type(ch, { delay: 30 }); + } + await this.show(1.2, 400); + try { + await this.click(optionText ? { text: optionText } : { css: "[role=option]", nth: 0 }); + } catch (e) { + const seen = await this.page.evaluate(`(() => { ${DEEP} return all("li, [role=option], [role=listbox]").filter(visible).map((el) => textOf(el).slice(0, 50)).slice(0, 10); })()`); + console.log(" [pick] options seen:", JSON.stringify(seen)); + await this.page.screenshot({ path: "/tmp/tut-dump.png" }); + throw e; + } + } + + /** Turns the 3D camera in small steps (a frame after each): angles in radians, distance as a factor. */ + async orbit({ theta = 0, phi = 0, zoom = 1, frames = 20 } = {}) { + for (let i = 1; i <= frames; i++) { + await this.page.evaluate( + (k, t, p, z) => { + const v = document.querySelector("nextfloor-panel").shadowRoot.querySelector("nf-view3d"); + if (!window.__orbit0) window.__orbit0 = v.viewer.getView(); + const w = { ...window.__orbit0 }; + w.theta = window.__orbit0.theta + t * k; + w.phi = Math.min(1.3, Math.max(0.15, window.__orbit0.phi + p * k)); + w.radius = window.__orbit0.radius * (1 + (z - 1) * k); + v.viewer.flyTo(w, 1); + }, + i / frames, + theta, + phi, + zoom, + ); + await sleep(80); + await this.frame(); + } + await this.page.evaluate(() => { + const v = document.querySelector("nextfloor-panel").shadowRoot.querySelector("nf-view3d"); + window.__orbit0 = v.viewer.getView(); + }); + } + + /** Opens another page of the demo (the overlay is put on again). */ + async navigate(query) { + await this.page.goto(`${this.base}/preview/index.html?noshowcase&lang=${this.lang}&ha=dark${query ? "&" + query : ""}`, { waitUntil: "networkidle0", timeout: 180000 }); + await sleep(1800); + await this.page.evaluate(OVERLAY); + const ok = await this.page.evaluate(() => !!window.__tut); + if (!ok) throw new Error("overlay missing after navigation"); + this.cursor = { x: 640, y: 360 }; + } + + /** After a click that reloads the page (the showcase pages): waits for it and puts the overlay on again. */ + async reinject(ms = 3500) { + await sleep(ms); + await this.page.evaluate(OVERLAY); + await this.page.evaluate((x, y) => window.__tut.move(x, y), this.cursor.x, this.cursor.y); + } + + /** For writing episodes: what is on screen right now (buttons, fields) and a screenshot at /tmp/tut-dump.png. */ + async dump(label = "") { + const list = await this.page.evaluate(`(() => { ${DEEP} return all("button, select, input, summary, label, h3").filter(visible).map((el) => el.tagName.toLowerCase() + ":" + (textOf(el).slice(0, 60) || el.getAttribute("aria-label") || el.title || el.placeholder || el.type)); })()`); + console.log(`--- ${label}\n` + list.join("\n")); + await this.page.screenshot({ path: "/tmp/tut-dump.png" }); + } + + // ------------------------------------------------------------------ the page + eval(code, ...args) { + return this.page.evaluate(code, ...args); + } + + async stateJson() { + return this.page.evaluate(() => window.nfDemoState()); + } + + // ------------------------------------------------------------------ writing the results + async finish(name) { + this.endSegment(); + await this.browser.close(); + this.server.close(); + const dir = this.out; + const concat = this.frames.map((f) => `file '${f.file}'\nduration ${f.dur.toFixed(4)}`).join("\n") + `\nfile '${this.frames.at(-1).file}'\n`; + writeFileSync(join(dir, `${name}.concat.txt`), concat); + writeFileSync(join(dir, `${name}.segments.json`), JSON.stringify({ lang: this.lang, seconds: this.time, chapters: this.chapters, segments: this.segments }, null, 1)); + return { seconds: this.time, frames: this.frames.length, segments: this.segments.length }; + } +} + +/** The things drawn over the page: the mouse pointer, a click ripple, a spotlight frame, a note and the chapter card. */ +const OVERLAY = `(() => { + if (window.__tut) return; + const layer = document.createElement("div"); + layer.style.cssText = "position:fixed;inset:0;pointer-events:none;z-index:2147483647;font-family:Roboto,system-ui,sans-serif"; + layer.innerHTML = \` + + + + + \`; + document.body.appendChild(layer); + const $ = (id) => layer.querySelector("#" + id); + window.__tut = { + move(x, y) { $("t-cursor").style.transform = "translate(" + (x - 5) + "px," + (y - 3) + "px)"; }, + ripple(x, y) { const r = $("t-ripple"); r.style.left = x + "px"; r.style.top = y + "px"; r.style.display = "block"; r.animate([{ transform: "scale(.4)", opacity: 1 }, { transform: "scale(1.6)", opacity: 0 }], { duration: 450 }).onfinish = () => (r.style.display = "none"); }, + spot(rect, pad) { const s = $("t-spot"); if (!rect) { s.style.display = "none"; return; } s.style.display = "block"; s.style.left = rect.left - pad + "px"; s.style.top = rect.top - pad + "px"; s.style.width = rect.w + 2 * pad + "px"; s.style.height = rect.h + 2 * pad + "px"; }, + note(text) { const n = $("t-note"); if (!text) { n.style.display = "none"; return; } n.textContent = text; n.style.display = "block"; }, + card(title, sub) { const c = $("t-card"); if (title === null) { c.style.display = "none"; return; } $("t-card-title").textContent = title; $("t-card-sub").textContent = sub || ""; c.style.display = "grid"; }, + }; + window.__tut.move(640, 360); +})()`; diff --git a/frontend/tutorial/record.mjs b/frontend/tutorial/record.mjs new file mode 100644 index 0000000..ccd359f --- /dev/null +++ b/frontend/tutorial/record.mjs @@ -0,0 +1,79 @@ +// Records the tutorial episode by episode. Each episode starts where the one before it ended (its plan is handed on as JSON), so one +// episode can be recorded again without redoing the others. +// node tutorial/record.mjs 1 records episode 1 (the empty start) +// node tutorial/record.mjs 3 4 records 3 and 4 (needs the plan left by episode 2) +// node tutorial/record.mjs all +// Env: LANG_UI=en|de (language of the app in the picture), OUT= (default frontend/tutorial/out/) +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { translate } from "../src/i18n.ts"; +import { Recorder } from "./rec.mjs"; + +const lang = process.env.LANG_UI === "de" ? "de" : "en"; +const outRoot = process.env.OUT ?? `${import.meta.dirname}/out/${lang}`; +const files = readdirSync(join(import.meta.dirname, "episodes")).filter((f) => f.endsWith(".mjs")).sort(); +const wanted = process.argv.slice(2); +// development: SCRATCH=/path/to/episode.mjs FROM= node tutorial/record.mjs scratch +if (wanted[0] === "scratch") { + const t = (key, vars) => translate({ language: lang }, key, vars); + const episode = await import(pathToFileURL(process.env.SCRATCH).href); + const dir = "/tmp/tut-scratch"; + mkdirSync(dir, { recursive: true }); + const from = join(outRoot, "state", `ep${String(process.env.FROM ?? 1).padStart(2, "0")}.json`); + const served = join(import.meta.dirname, "..", "..", "preview", ".tutorial-state.json"); + writeFileSync(served, readFileSync(from)); + const r = new Recorder({ out: dir, lang, t }); + await r.start({ query: "state=/preview/.tutorial-state.json" }); + try { + await episode.run(r); + } catch (e) { + console.log("FAILED:", e.message); + await r.page.screenshot({ path: "/tmp/tut-dump.png" }); + } + await r.browser.close(); + r.server.close(); + process.exit(0); +} +const numbers = wanted.includes("all") || !wanted.length ? files.map((_, i) => i + 1) : wanted.map(Number); +mkdirSync(join(outRoot, "state"), { recursive: true }); + +const t = (key, vars) => translate({ language: lang }, key, vars); +for (const n of numbers) { + const file = files[n - 1]; + if (!file) throw new Error(`no episode ${n}`); + const episode = await import(pathToFileURL(join(import.meta.dirname, "episodes", file)).href); + const name = `ep${String(n).padStart(2, "0")}`; + const dir = join(outRoot, name); + mkdirSync(dir, { recursive: true }); + const previous = join(outRoot, "state", `ep${String(n - 1).padStart(2, "0")}.json`); + let query = "empty"; + if (n > 1) { + if (!existsSync(previous)) throw new Error(`episode ${n} needs ${previous} (record episode ${n - 1} first)`); + query = `state=/${join("nextfloor-launch-state", String(n))}`; // replaced below + } + const r = new Recorder({ out: dir, lang, t }); + if (n > 1) { + // the page can only fetch from the static server: copy the state into the repository's tmp folder, which is served + const served = join(import.meta.dirname, "..", "..", "preview", ".tutorial-state.json"); + writeFileSync(served, readFileSync(previous)); + query = "state=/preview/.tutorial-state.json"; + } + console.log(`\n=== episode ${n}: ${episode.title.en} (${lang})`); + const t0 = Date.now(); + await r.start({ query: [query, episode.query].filter(Boolean).join("&") }); + try { + await episode.run(r); + } catch (e) { + console.log("FAILED at", r.time.toFixed(1), "s:", e.message, "\n", String(e.stack).split("\n").slice(0, 5).join("\n")); + await r.page.screenshot({ path: join(dir, "failure.png") }); + await r.browser.close(); + r.server.close(); + process.exit(1); + } + // an episode that leaves for another page (the model showcase) hands on the plan it was given + if (episode.keepState) writeFileSync(join(outRoot, "state", `${name}.json`), readFileSync(previous)); + else writeFileSync(join(outRoot, "state", `${name}.json`), JSON.stringify(await r.stateJson(), null, 1)); + const done = await r.finish(name); + console.log(`episode ${n}: ${done.seconds.toFixed(0)} s of video, ${done.frames} frames, ${done.segments} narration segments, recorded in ${Math.round((Date.now() - t0) / 1000)} s`); +} diff --git a/frontend/tutorial/sample-model.mjs b/frontend/tutorial/sample-model.mjs new file mode 100644 index 0000000..9591b4e --- /dev/null +++ b/frontend/tutorial/sample-model.mjs @@ -0,0 +1,71 @@ +// A small binary glTF made by hand (a stretched sphere and a flat box), for showing the model upload. +import { writeFileSync } from "node:fs"; + +export function writeSampleGlb(path) { + writeFileSync(path, Uint8Array.from(makeGlb())); + return path; +} + +function makeGlb() { + const sphere = { positions: [], indices: [] }; + const rings = 60; + const segments = 80; + for (let r = 0; r <= rings; r++) { + for (let s = 0; s < segments; s++) { + const phi = (r / rings) * Math.PI; + const theta = (s / segments) * Math.PI * 2; + // stretched along x like a car, so the front can be told from the side + sphere.positions.push(2 * Math.sin(phi) * Math.cos(theta), 0.7 * Math.cos(phi) + 0.7, Math.sin(phi) * Math.sin(theta)); + } + } + for (let r = 0; r < rings; r++) { + for (let s = 0; s < segments; s++) { + const a = r * segments + s; + const b = r * segments + ((s + 1) % segments); + sphere.indices.push(a, a + segments, b, b, a + segments, b + segments); + } + } + const box = { positions: [-0.5, 1.5, -0.5, 0.5, 1.5, -0.5, 0.5, 1.5, 0.5, -0.5, 1.5, 0.5, -0.5, 1.8, -0.5, 0.5, 1.8, -0.5, 0.5, 1.8, 0.5, -0.5, 1.8, 0.5], indices: [0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6, 0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0] }; + const chunks = []; + const views = []; + const accessors = []; + const add = (typed, target, type, componentType, count, extra = {}) => { + const bytes = new Uint8Array(typed.buffer); + const offset = chunks.reduce((n, c) => n + c.length, 0); + views.push({ buffer: 0, byteOffset: offset, byteLength: bytes.length, target }); + accessors.push({ bufferView: views.length - 1, componentType, count, type, ...extra }); + chunks.push(bytes); + return accessors.length - 1; + }; + const prims = [sphere, box].map((m, i) => { + const p = Float32Array.from(m.positions); + const x = [0, 0, 0]; + const lo = [Infinity, Infinity, Infinity]; + const hi = [-Infinity, -Infinity, -Infinity]; + for (let k = 0; k < p.length; k += 3) for (let j = 0; j < 3; j++) { lo[j] = Math.min(lo[j], p[k + j]); hi[j] = Math.max(hi[j], p[k + j]); } + const pos = add(p, 34962, "VEC3", 5126, p.length / 3, { min: lo, max: hi }); + const idx = add(Uint32Array.from(m.indices), 34963, "SCALAR", 5125, m.indices.length); + return { attributes: { POSITION: pos }, indices: idx, material: i }; + }); + const total = chunks.reduce((n, c) => n + c.length, 0); + const bin = new Uint8Array(total); + let at = 0; + for (const c of chunks) { bin.set(c, at); at += c.length; } + const json = { asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0 }], meshes: [{ primitives: prims }], materials: [{ name: "Body", pbrMetallicRoughness: { baseColorFactor: [0.8, 0.1, 0.1, 1] } }, { name: "Glass", alphaMode: "BLEND", pbrMetallicRoughness: { baseColorFactor: [0.6, 0.8, 0.9, 0.3] } }], buffers: [{ byteLength: total }], bufferViews: views, accessors }; + let text = new TextEncoder().encode(JSON.stringify(json)); + const padded = new Uint8Array(Math.ceil(text.length / 4) * 4).fill(0x20); + padded.set(text); + const out = new Uint8Array(12 + 8 + padded.length + 8 + bin.length); + const view = new DataView(out.buffer); + view.setUint32(0, 0x46546c67, true); + view.setUint32(4, 2, true); + view.setUint32(8, out.length, true); + view.setUint32(12, padded.length, true); + view.setUint32(16, 0x4e4f534a, true); + out.set(padded, 20); + const o = 20 + padded.length; + view.setUint32(o, bin.length, true); + view.setUint32(o + 4, 0x004e4942, true); + out.set(bin, o + 8); + return Array.from(out); +} diff --git a/frontend/tutorial/trim-silence.mjs b/frontend/tutorial/trim-silence.mjs new file mode 100644 index 0000000..134cabb --- /dev/null +++ b/frontend/tutorial/trim-silence.mjs @@ -0,0 +1,54 @@ +// Shortens every stretch without speech that is longer than MAX seconds, in picture and sound, and moves the subtitles along. +// Keeps the start and the end of such a stretch (so actions on screen stay smooth) and cuts out the middle. +// node tutorial/trim-silence.mjs [max-seconds=2] +// Writes