From ef6ed355a9036b71cbcc7366bd5b941afbdc04ce Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:21:45 +0000 Subject: [PATCH 001/146] Home Assistant's live reading is asked for every 30 s, not 5 s The gateway reports about once a minute, so a 5-second poll mostly found nothing new. A reading now reaches the gauges, "weather now" and the rain alert within 30 s of Home Assistant having it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/configuration.md | 2 +- docs/how-it-works.md | 2 +- docs/storage-plan.md | 2 +- lib/alerts/weather.py | 4 ++-- lib/ecowitt/hass_api.py | 2 +- lib/ecowitt/source.py | 6 +++--- lib/mcp_server.py | 2 +- lib/weather.py | 2 +- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 4d86edc1..0735d4e8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -37,7 +37,7 @@ At least one of Ecowitt (cloud or Home Assistant) or AirGradient (cloud, local o | `MCP_AIRGRADIENT_API_TOKEN`, `MCP_AIRGRADIENT_LOCATION_ID` | – | Enables AirGradient via cloud API: history and gap fill | | `MCP_AIRGRADIENT_LOCAL_URL` | – | Sensor's local server, e.g. `http://airgradient_.local` or an IP. Live reading polled every 60 s, recorded as 5-min means (`pm02Compensated` over `pm02`). Cloud, if configured, only fills gaps. Without cloud vars: sensor + SQLite only, no cloud requests. `.local` resolved in-process (mDNS); in Docker needs the host network (README: Docker networking) or an IP. Sensor down → cloud fallback, retry after 5 min | | `MCP_AIRGRADIENT_SOURCE` | `auto` | `auto`: each that is set, the sensor itself first, then Home Assistant (if it has the sensor), then the cloud; `local`, `homeassistant` or `cloud`: that one alone | -| `MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN` | – | Home Assistant (e.g. `http://192.168.1.219:8123`) and a long-lived access token (your profile page there). With its Ecowitt and AirGradient integrations the readings are read back to shade the recent charts between each 5 minutes' lowest and highest, for the days ecobot was not watching too (the last 31 days at most; Home Assistant keeps 10 unless its recorder says otherwise). Both needed. They also make Home Assistant a source of the station's readings (see `MCP_ECOWITT_SOURCE`): minute lines, a live reading every few seconds and rain alerts as the gauge reports; without them the shading comes from ecobot's own readings | +| `MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN` | – | Home Assistant (e.g. `http://192.168.1.219:8123`) and a long-lived access token (your profile page there). With its Ecowitt and AirGradient integrations the readings are read back to shade the recent charts between each 5 minutes' lowest and highest, for the days ecobot was not watching too (the last 31 days at most; Home Assistant keeps 10 unless its recorder says otherwise). Both needed. They also make Home Assistant a source of the station's readings (see `MCP_ECOWITT_SOURCE`): minute lines, a live reading every 30 seconds and rain alerts as the gauge reports; without them the shading comes from ecobot's own readings | | `MCP_AIRGRADIENT_DASHBOARD_URL` | – | "live chart" link in air replies and alerts | | `MCP_PLACE` | `Melbourne` | Name in the Pollen & asthma and Forecast headings | | `MCP_POLLEN` | `off` | Melbourne grass pollen + thunderstorm asthma (melbournepollen.com.au): report, `pollen_asthma` tool, alert at High. Oct–Dec only | diff --git a/docs/how-it-works.md b/docs/how-it-works.md index f509b033..e3e16378 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -96,5 +96,5 @@ The system prompt starts with what never changes (the model provider caches the - `MCP_ECOWITT_SOURCE` picks where the readings come from (`auto` is Home Assistant if it is set, the cloud filling in if its keys are set too; `MCP_AIRGRADIENT_SOURCE` does the same for the air sensor, see above). `lib/ecowitt/hass_api.py` answers the three calls the bot makes of Ecowitt's cloud (`devices`, `realtime`, `history`) from Home Assistant, in the cloud's shapes and units, so the cache, archive, charts and alerts are the same code whichever answers. `lib/ecowitt/hass_map.py` is the table of entities (`sensor._`, found by name) and `hass_history.py` tells Home Assistant's recorded changes as the cloud's buckets (1 minute, 5, 30, 4 hours, a day), time-weighted means, the highest gust, the last rain counter, with the true lowest and highest of each bucket as `_low`/`_high`. - Both set: `lib/ecowitt/fallback.py`. Home Assistant answers; a live reading older than 10 minutes, or none, is replaced by the cloud's if newer; the buckets Home Assistant has none of (before it began recording, while it was down) are asked of the cloud in one request for the span they cover. A failure of either is logged once, with its recovery. -- Faster: the live reading is polled every 5 seconds (`Ecowitt.watch_live`), a reading newer than the last is kept for "weather now", the report and the gauges, and the rain alert looks at it at once (`WeatherMonitor.check_rain`) instead of at the next minute's refresh. The gateway itself reports about every minute, so the alert is within seconds of that. A chart of up to 8 hours is drawn a reading a minute (`1min`, Home Assistant only). The bot takes the minutes as they come (the last 9 hours at start, then at each new live reading) into the storage's `1min` rows (`lib/ecowitt/query.py` holds the constants) and drops what is older, so such a chart is drawn without asking Home Assistant; if the minutes don't reach back to its start it uses the 5-minute readings, as longer charts do. +- Faster: the live reading is polled every 30 seconds (`Ecowitt.watch_live`), a reading newer than the last is kept for "weather now", the report and the gauges, and the rain alert looks at it at once (`WeatherMonitor.check_rain`) instead of at the next minute's refresh. The gateway itself reports about every minute, so the alert is within 30 seconds of that. A chart of up to 8 hours is drawn a reading a minute (`1min`, Home Assistant only). The bot takes the minutes as they come (the last 9 hours at start, then at each new live reading) into the storage's `1min` rows (`lib/ecowitt/query.py` holds the constants) and drops what is older, so such a chart is drawn without asking Home Assistant; if the minutes don't reach back to its start it uses the 5-minute readings, as longer charts do. - Caveats: Home Assistant keeps 10 days of states unless its recorder is set otherwise, so older history comes from the cache the bot built, or from the cloud where it is set. An answer with nothing in it from Home Assistant alone is not recorded as fetched. diff --git a/docs/storage-plan.md b/docs/storage-plan.md index dd22ef73..0a27bd00 100644 --- a/docs/storage-plan.md +++ b/docs/storage-plan.md @@ -213,7 +213,7 @@ CREATE TABLE climate_day ( Every band is in the rows, so a chart's band comes with its line: - **Ecowitt's own lows and highs** (30 minutes and coarser) go in `_lo` and `_hi` when the readings are written. -- **The bot's live readings** (every few seconds from Home Assistant, once a minute from the cloud) are gathered per 5 minutes in +- **The bot's live readings** (every 30 seconds from Home Assistant, once a minute from the cloud) are gathered per 5 minutes in memory, as the AirGradient's are now (`AirGradient._average`), and each 5 minutes with two or more readings widens that 5-minute row's range when the bucket closes. This replaces `LiveRanges.add` and its `ranges` table. - **Home Assistant's ranges**, the station's and the AirGradient's, widen the same 5-minute rows. diff --git a/lib/alerts/weather.py b/lib/alerts/weather.py index bf92d636..1c3e9ba2 100644 --- a/lib/alerts/weather.py +++ b/lib/alerts/weather.py @@ -108,8 +108,8 @@ async def check(self): self.state.save() async def check_rain(self): - """Look at the rain alone, on a live reading that has just come in (the station is polled every few seconds, so this is the alert - within a few seconds of the gauge, not at the next minute's check).""" + """Look at the rain alone, on a live reading that has just come in (the station is polled every 30 seconds, so this is the alert + within 30 seconds of the gauge's report, not at the next minute's check).""" rows = await self.station.recent(3) live = await self.station.live_rain() if rows else None if rows and live and live[0] > rows[-1][0]: diff --git a/lib/ecowitt/hass_api.py b/lib/ecowitt/hass_api.py index b8db4549..cd9ff1b4 100644 --- a/lib/ecowitt/hass_api.py +++ b/lib/ecowitt/hass_api.py @@ -2,7 +2,7 @@ The rest of the bot never knows the difference: the cache, the archive, the charts and the alerts all take what `EcowittAPI` gives, in the shapes it gives them (api.py; hass_history.py tells how the history is cut). What differs: its live reading is a request to a machine -on the network, so it is asked for every few seconds, not once a minute (source.watch_live); it has a "1min" history cycle (Ecowitt has +on the network, so it is asked for every 30 seconds, not once a minute (source.watch_live); it has a "1min" history cycle (Ecowitt has none); and empty_is_final is False, since Home Assistant only has what it recorded, so an answer with nothing in it does not prove there was nothing to know (the cloud may have it): the storage does not remember such a range as fetched, and a fallback asks the cloud for it. It is up as long as Home Assistant is: a failure is an EcowittError, as the cloud's are, passing (a network error, a restart) or not (a diff --git a/lib/ecowitt/source.py b/lib/ecowitt/source.py index 871cfe85..77cb7a33 100644 --- a/lib/ecowitt/source.py +++ b/lib/ecowitt/source.py @@ -34,7 +34,7 @@ LIVE_GROUPS = list(READING_GROUPS) # what the once-a-minute live reading asks for: everything "weather now" and the report show HA_IMPORT_SECONDS = 900 # how often Home Assistant's readings are folded into the 5-minute ranges ... HA_RECENT_SECONDS = 3 * 3600 # ... the last few hours each time (the whole RANGE_KEEP_DAYS the first time) -LIVE_POLL_SECONDS = 5 # Home Assistant's live reading is asked for this often (a request to a machine on the network) +LIVE_POLL_SECONDS = 30 # Home Assistant's live reading is asked for this often (the gateway reports about once a minute) LIVE_RECORD_SECONDS = 30 # ... and counted into the ranges this often LIVE_FRESH_SECONDS = 90 # a question is answered from that reading while it is this young @@ -97,7 +97,7 @@ def __init__(self, cfg: Config, transport=None, ha_transport=None, storage: Stor self.api = FallbackAPI(home, cloud, cfg.tz) if home and cloud else home or cloud self.via = "HA/cloud" if home and cloud else "HA" if home else "cloud" self.has_minutes = home is not None # (only Home Assistant has minutes) - self.fast = home # the API that can be asked every few seconds, if any + self.fast = home # the API that can be asked every LIVE_POLL_SECONDS, if any self.ha = home.ha if home else HomeAssistant(cfg.homeassistant_url, cfg.homeassistant_token) if cfg.homeassistant else None # (shared with the air sensor) self._ha_ok: bool | None = None self.live_marks = LiveMarks() # the live readings' lows and highs, for the recent charts' bands @@ -213,7 +213,7 @@ async def _record_live(self, data: dict): log.warning("Couldn't keep the live readings' ranges: %s", e) async def watch_live(self): - """Ask Home Assistant for the live reading every few seconds, for ever. A reading newer than the last one found is kept for "weather + """Ask Home Assistant for the live reading every LIVE_POLL_SECONDS, for ever. A reading newer than the last one found is kept for "weather now", the report and the rain alert (which is called at once, not at the next minute's refresh). A failure is logged once, with its recovery; the cloud, where there is one, answers the questions meanwhile.""" if self.fast is None: diff --git a/lib/mcp_server.py b/lib/mcp_server.py index de0ddaa9..2b598ffa 100644 --- a/lib/mcp_server.py +++ b/lib/mcp_server.py @@ -89,7 +89,7 @@ "label, unit) and the words people use for them; each source's mode and how far back its history goes; the alert " "kinds, each with its rule and thresholds; the AirGradient dashboard link. Pushed when the readings change.", None), WEATHER_URI: ("now/weather", "The weather now", "The weather station's live reading: {as_of, sensors: {sensor: {reading: {value, " - "unit, text, [emoji], [compass]}}}, lines, heading}. Pushed on each new reading (every 5 s with Home Assistant, 60 s " + "unit, text, [emoji], [compass]}}}, lines, heading}. Pushed on each new reading (polled every 30 s with Home Assistant, 60 s " "from the cloud).", "eco"), AIR_URI: ("now/air", "The air now", "The air sensor's latest reading, with each reading's rating, PM2.5's and PM10's US AQI and band (the US AQI is the higher): {as_of, " "sensors: {air: {reading: {value, unit, text, [rating], [aqi_us, band]}}}, lines, heading}. Pushed on each new reading.", diff --git a/lib/weather.py b/lib/weather.py index c54fef85..3c206f71 100644 --- a/lib/weather.py +++ b/lib/weather.py @@ -43,7 +43,7 @@ STATION_URI, ALERTS_URI = "ecobot://station", "ecobot://alerts" # (as lib/mcp_server.py's) STATUS_URI = "ecobot://status" # the Status picture (lib/status.py) -LISTENED = (STATION_URI, ALERTS_URI) # what the bot listens to (not the live readings, pushed every few seconds) +LISTENED = (STATION_URI, ALERTS_URI) # what the bot listens to (not the live readings, pushed with each new reading) CALL_WAIT = 5.0 # how long a question's call waits for the service while it is being reached again, before it is refused BACKGROUND = "background" # request _meta priority of a call nobody waits for (lib/service/common.py): refused at once while down AIR_LINK_LABEL = "live chart" # the AirGradient dashboard link's words (lib/airgradient/source.py) From c164db46917782294d57bc4cc7b4c0c8160648e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 17:15:51 +0000 Subject: [PATCH 002/146] Web dashboard: tiles dragged to reorder, hidden by their x or a remove zone, reset; fewer grow to fill; see-through tiles The page's tiles can be arranged in the browser, kept in localStorage under one versioned key ("ecobot.dashboard.v1": order and hidden, by the tiles' titles; missing, corrupt or blocked storage: the defaults, nothing saved; keys it doesn't know kept): - dragged from anywhere on the gauge but its title, reading and table (those stay selectable), with Pointer Events: a mouse or pen press that moves, or a touch long press (450 ms, a 15 ms buzz where navigator.vibrate exists); the others make room with transforms, and the dropped tile glides into place; a short tap and every click but the one ending a drag are left alone; - a small grip and x on mouseover (or after a long press let go in place); the x hides the tile, as does a drop on the "remove" zone sliding down from the top while dragging; "reset preferences" beside the time while any is hidden puts every tile back in the default order; - a tile new to the saved order takes its usual place (after the tile before it by default); - fewer tiles grow evenly to fill the window, a single one filling it, never smaller than the full dashboard's (a phone's scrolling tiles keep their size); - each tile's own background clear, its foreground opaque, a thin opaque inset frame keeping the tiles distinct. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- README.md | 8 + lib/web_dashboard.html | 363 ++++++++++++++++++++++++++++++--- lib/web_dashboard.py | 3 +- tests/slow_tests.txt | 3 + tests/test_web_dashboard.py | 112 +++++++++- tests/web_dashboard_browser.js | 210 ++++++++++++++++++- 6 files changed, 670 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index ada6cd1a..748ec31d 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,14 @@ A tile whose reading is missing just now (the station or the air sensor not send scale's low end where 0 isn't on it: pressure 950 hPa, CO₂ 400 ppm) with its highs and lows still beside it; when the reading comes back the tile brightens and its gauge rises in place. A reading the station or the monitor has never sent has no tile. +The tiles can be arranged to taste. Drag a tile by its gauge to move it (with a mouse, from anywhere on it but its title, its reading +and its table, which stay selectable for copying; on a touch screen, a long press picks it up, with a short buzz on Android); the +others make room. Its ×, shown on mouseover (or after a long press), hides it, as does dropping it on the "remove" zone that slides +down from the top while dragging. With a tile hidden, "reset preferences" beside the time at the bottom brings every tile back in the +usual order. Fewer tiles grow to fill the window (a single one fills it), never smaller than the whole dashboard's. The arrangement +is kept in the browser (its local storage, per browser and device); nothing is sent to ecobot-mcp. A gauge added later takes its +usual place among yours. + It is read-only (the weather and air readings, nothing else), so it is open to anyone on your network: no token, and any name or address in the URL (`MCP_ALLOWED_HOSTS` is only for `/mcp`, which keeps its token). ecobot-mcp has to listen beyond the machine itself: Docker publishes port 8765 already; under systemd set `MCP_BIND=0.0.0.0:8765`. It is plain HTTP: keep it on your own network. To diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index f69abf98..fe2caa30 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -8,7 +8,9 @@ Weather Dashboard + colours and sizes (lib/gauge_look.py, sent with the data); redrawn on each /dashboard/events event, and every minute regardless. + The tiles can be rearranged in the browser: dragged to reorder (a long press on a touch screen), hidden with their × or the + remove zone, all put back with "reset preferences"; kept in localStorage ("ecobot.dashboard.v1"), nothing sent to the server. -->
+
loading…
+ + + +
test:
+ + diff --git a/lib/web_dashboard.py b/lib/web_dashboard.py index 1647adb6..83b8be9a 100644 --- a/lib/web_dashboard.py +++ b/lib/web_dashboard.py @@ -14,7 +14,9 @@ for it. Only link previews fetch og:image: a browser opening the page fetches nothing from elsewhere; - GET /dashboard/data: the tiles as JSON: the gauges' sheet (lib/gauge_sheet.py) from the service's `current` with context, answered from what is held (fetch off: a request never asks the station; the keep-warm keeps the live reading), as the Status picture's, each - tile's specs.Tile fields and whether it is dimmed, with the time of the reading (`as_of`) and the look; + tile's specs.Tile fields and whether it is dimmed, with the time of the reading (`as_of`), the look, and the station's rain rate now + (`rain_rate`, mm/h: its rain gauge's, or its piezo gauge's where that's the one reporting, which no tile shows; null with + neither), for the page's rain behind the tiles; - GET /dashboard/events: Server-Sent Events, a `readings` event whenever the gauges' readings in the station's kept live reading or the air sensor's latest change, told by the server's own change detection for ecobot://now/weather and ecobot://now/air (EcobotServer.publish_changes: nothing is fetched for it), so the page fetches the data again and moves its gauges in place. A @@ -53,14 +55,28 @@ RETRY_MS = 5000 # how soon a browser connects again after its stream ends QUEUED = 4 # events waiting on a stream that isn't read: more are dropped (one says it all: fetch again) NOT_ANSWERING = "The weather station isn't answering right now." +RAIN_RATES = ("rainfall", "rainfall_piezo") # where the station's rain rate is (current's groups): its rain gauge's first, then the piezo's def readings_of(live: dict | None) -> tuple | None: - """What the gauges show now of a live reading ({group: {field: {value, ...}}}): each gauge's reading, and the gust counted into the - wind's Max. None without one.""" + """What the gauges show now of a live reading ({group: {field: {value, ...}}}): each gauge's reading, the gust counted into the + wind's Max, and the piezo gauge's rain rate (the page's rain behind the tiles). None without one.""" if not live: return None - return tuple(live_value(live, where) for g in GAUGES for where in (g.live, *([g.counted] if g.counted else []))) + return (*(live_value(live, where) for g in GAUGES for where in (g.live, *([g.counted] if g.counted else []))), + live_value(live, ("rainfall_piezo", "rain_rate"))) # (the piezo gauge's rain rate: the page's rain, with no gauge of its own) + + +def rain_rate_of(result: dict, live: dict | None = None) -> float | None: + """The station's rain rate now (mm/h): in current's result, its rain gauge's, or, with no reading there, its piezo gauge's; then the + piezo gauge's in the station's kept live reading (`live`), which current gives only when it is named. None with none of them.""" + sensors = result.get("sensors") or {} + for group in RAIN_RATES: + try: + return float(((sensors.get(group) or {}).get("rain_rate") or {})["value"]) + except (KeyError, TypeError, ValueError): + continue + return live_value(live or {}, ("rainfall_piezo", "rain_rate")) def air_readings_of(row: dict | None) -> tuple | None: @@ -84,23 +100,27 @@ def __init__(self, server, uris: tuple[str, ...] = ("ecobot://now/weather", "eco # ---------- the data ---------- async def data(self) -> dict: - """{as_of, tiles, look}, or with `unavailable` (and no tiles) when the station gives nothing. From what is held, whatever its age + """{as_of, tiles, look, rain_rate}, or with `unavailable` (and no tiles) when the station gives nothing. From what is held, whatever its age (fetch off): an open request on the LAN never asks the station (the keep-warm keeps the live reading, and the events come from it).""" tool = self.server.service.get("current") result = json.loads(await tool.call(gauge_sheet.call(), {"fetch": False})) if tool else {"error": "no current"} sheet = gauge_sheet.sheet(result) - out = {"as_of": result.get("as_of"), "tiles": [tile_json(t) for t in sheet.tiles] if sheet else [], "look": look()} + out = {"as_of": result.get("as_of"), "tiles": [tile_json(t) for t in sheet.tiles] if sheet else [], "look": look(), + "rain_rate": rain_rate_of(result, self._kept_live())} if sheet is None: out["unavailable"] = (result.get("unavailable") or {}).get("station") or NOT_ANSWERING return out + def _kept_live(self) -> dict | None: + kept = getattr(self.server.ctx.eco, "_live", None) + return kept[1] if kept else None + # ---------- the events ---------- def _readings(self): """(the station's gauges' readings, the air sensor's) as they are kept.""" try: - kept = getattr(self.server.ctx.eco, "_live", None) air = getattr(self.server.ctx.air, "_current", None) - return readings_of(kept[1] if kept else None), air_readings_of(air[0] if air else None) + return readings_of(self._kept_live()), air_readings_of(air[0] if air else None) except Exception as e: # (never stops the publishing) log.warning("Dashboard: couldn't read the live reading: %s: %s", type(e).__name__, e) return None @@ -185,4 +205,4 @@ def routes(self, path: str = "/dashboard") -> list[Route]: Route(f"{path}/events", self.events, methods=["GET"])] -__all__ = ["WebDashboard", "air_readings_of", "readings_of"] +__all__ = ["WebDashboard", "air_readings_of", "rain_rate_of", "readings_of"] diff --git a/tests/slow_tests.txt b/tests/slow_tests.txt index f3f7fcc1..c3a2553c 100644 --- a/tests/slow_tests.txt +++ b/tests/slow_tests.txt @@ -62,4 +62,5 @@ tests/test_web_dashboard.py::test_fewer_tiles_grow_evenly_to_fill_the_window_and tests/test_web_dashboard.py::test_on_a_touch_screen_a_long_press_picks_a_tile_up_and_a_tap_or_a_swipe_is_left_alone tests/test_web_dashboard.py::test_on_a_touch_screen_a_tap_zooms_a_swipe_pages_from_anywhere_and_a_tap_goes_back_where_the_page_was tests/test_web_dashboard.py::test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error +tests/test_web_dashboard.py::test_the_weather_behind_the_tiles_comes_with_its_reading_frames_its_tile_in_red_and_can_be_stopped tests/test_web_dashboard.py::test_tiles_are_dragged_to_reorder_hidden_by_the_x_or_the_remove_zone_kept_across_reloads_and_reset diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index d36c5d48..fb740e17 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -6,7 +6,8 @@ console error; the tiles rearranged (dragged with a mouse and with a touch's long press, hidden by the × and the remove zone, kept across reloads, reset), the drag's text left selectable, the fill of fewer tiles, and the tiles' clear backgrounds; a tile zoomed to fill the window and the gallery through the others (keys, mouse drags, a trackpad's swipe, touch swipes, both ends, the text still -selectable, live readings). With +selectable, live readings); the weather behind the tiles (each effect at its reading's mark, its tile framed in red, several at once on +one canvas behind the tiles, "stop animations", reduced motion, the temporary test links and ?fx=), and the data's rain rate. With ECOBOT_SCREENSHOTS set, its screenshots are kept in that folder.""" import asyncio @@ -31,7 +32,7 @@ from lib.mcp_server import AIR_URI, EcobotServer, WEATHER_URI, http_app from lib.service.context import Context from lib.service.names import Catalogue -from lib.web_dashboard import DESCRIPTION, ICON, ICON_URL, PAGE, WebDashboard, air_readings_of, readings_of +from lib.web_dashboard import DESCRIPTION, ICON, ICON_URL, PAGE, WebDashboard, air_readings_of, rain_rate_of, readings_of from tests.chart_samples import _air, _station from tests.fakes import TZ, StandInService, gauges_result from tests.test_mcp_listen import Serving, free_port, until @@ -131,6 +132,26 @@ async def test_the_page_and_its_data_are_served_without_a_token_to_any_host_and_ assert mcp.status_code == 421 and no_token.status_code == 401 # /mcp: the Host, then the token, as before +async def test_the_data_carries_the_stations_rain_rate_now_its_rain_gauges_or_else_its_piezo_gauges(server, station): + """The page's rain behind the tiles: the rain rate now (mm/h), the rain gauge's, or the piezo gauge's where that's the one reporting + (in current's result, or in the kept live reading, where current gives it only when it is named); null with neither.""" + page = WebDashboard(server) + assert (await page.data())["rain_rate"] == 0.0 # (the October evening: dry) + station.reads("rainfall", "rain_rate", "2.4") + assert (await page.data())["rain_rate"] == 2.4 + station.live = {**station.live, "rainfall": {"daily": {"value": "0.2"}}, "rainfall_piezo": {"rain_rate": {"value": "0.6"}}} + station.eco._live = (time.time(), station.live) # no rain gauge's rate: the piezo's, as kept + assert (await page.data())["rain_rate"] == 0.6 + station.live = {k: v for k, v in station.live.items() if k != "rainfall_piezo"} + station.eco._live = (time.time(), station.live) + assert (await page.data())["rain_rate"] is None + piezo = {"sensors": {"rainfall": {"rain": {"value": 1.0}}, "rainfall_piezo": {"rain_rate": {"value": 3.2, "unit": "mm/h"}}}} + assert rain_rate_of(piezo) == 3.2 and rain_rate_of({"sensors": {"rainfall": {"rain_rate": {"value": None}}}}) is None + assert rain_rate_of({"sensors": {"rainfall": {"rain_rate": {"value": 0.0}}, "rainfall_piezo": {"rain_rate": {"value": 3.2}}}}) == 0.0 + live = {"rainfall_piezo": {"rain_rate": {"value": "1.5"}}} + assert readings_of({**station.live, **live}) != readings_of(station.live) # the piezo's rate changing: an event, the page fetches it + + async def test_the_page_answers_at_dashboard_slash_too_so_a_proxy_mapping_a_sites_root_there_gets_no_redirect_to_the_lan(server): # nginx's `location / { proxy_pass http://deb1:8765/dashboard/; }` sends the site's root as /dashboard/ with ecobot-mcp's own Host: # a redirect to /dashboard would be built from that Host, the LAN address, and break the page from the internet @@ -347,7 +368,7 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl got = report[name] assert got["errors"] == [], (name, got["errors"]) assert got["tiles"] == n and got["scrollWidth"] <= width, (name, got) - assert got["status"] == "updated 18:42", (name, got) + assert got["status"] == "updated 18:42 · stop animations", (name, got) # (the US AQI's 56, Moderate: smog behind the tiles) assert all(r["right"] <= width + 0.5 and r["left"] >= -0.5 for r in got["rects"]), (name, got) assert (shots / f"dashboard-{name}.png").exists() for name in ("tablet-landscape", "tablet-portrait", "desktop"): # these fit every tile without scrolling @@ -470,13 +491,13 @@ async def test_tiles_are_dragged_to_reorder_hidden_by_the_x_or_the_remove_zone_k "table": {"same": True, "dragging": False, "selected": "85"}, "reading": {"same": True, "dragging": False, "selected": "70"}} # the ×, then the remove zone, hide; the reset link shows beside the time - assert got["closed"] == {"titles": [t for t in reordered if t != "Rain"], "status": "updated 18:42 · reset preferences"} + assert got["closed"] == {"titles": [t for t in reordered if t != "Rain"], "status": "updated 18:42 · stop animations · reset preferences"} assert got["removing"]["over"] and got["removing"]["zone"] == "none" shown = [t for t in reordered if t not in ("Rain", "Wind")] assert got["removed"] == {"titles": shown, "stored": {"order": reordered, "hidden": ["Rain", "Wind"]}} - assert got["reloaded"] == {"titles": shown, "status": "updated 18:42 · reset preferences"} + assert got["reloaded"] == {"titles": shown, "status": "updated 18:42 · stop animations · reset preferences"} # reset: every tile, in the default order, nothing kept, no link - assert got["reset"] == {"titles": default, "status": "updated 18:42", "stored": None} + assert got["reset"] == {"titles": default, "status": "updated 18:42 · stop animations", "stored": None} # unreadable preferences: the defaults; a tile new to the saved order (Rain) in its usual place, after Atmospheric pressure; an # absent tile's place and a later stage's keys kept assert got["corrupt"] == default @@ -513,7 +534,7 @@ async def test_on_a_touch_screen_a_long_press_picks_a_tile_up_and_a_tap_or_a_swi assert got["dropped"]["titles"] == reordered and not got["dropped"]["zone"] and got["dropped"]["clicks"] == 1 # held and let go in place: the grip and × stay, and a tap on the × hides it assert got["armed"]["armed"] == ["Humidity"] and got["armed"]["close"] == "1" - assert got["closed"] == {"titles": [t for t in reordered if t != "Humidity"], "status": "updated 18:42 · reset preferences"} + assert got["closed"] == {"titles": [t for t in reordered if t != "Humidity"], "status": "updated 18:42 · stop animations · reset preferences"} # held at the bottom edge: the page scrolls to its end, never past it, and stays there once let go edge = got["edge"] assert edge["seen"][-1] == pytest.approx(edge["end"], abs=1) and max(edge["seen"]) <= edge["end"] + 1, edge @@ -670,3 +691,72 @@ async def test_on_a_touch_screen_a_tap_zooms_a_swipe_pages_from_anywhere_and_a_t assert got["held"] == {"zoomed": True, "shown": default[t + 2], "track": got["vertical"]["track"], "buzz": [], "zone": False} assert got["backAt"]["shown"] == default[t - 1] assert not got["out"]["zoomed"] and got["out"]["titles"] == default and got["out"]["lastShown"], got["out"] + + +# ---------- the weather behind the tiles ---------- +EFFECTS = {"rain": "Rain", "smog": "US AQI", "radiation": "UV index", "drips": "Humidity", "leaves": "Wind", "heat": "Temperature", + "ice": "Temperature"} + + +@pytest.mark.skipif(not browser_there(), reason="needs node with Playwright's Chromium") +async def test_the_weather_behind_the_tiles_comes_with_its_reading_frames_its_tile_in_red_and_can_be_stopped(server, station): + got = await run_page(server, "--weather", timeout=180) + assert got["errors"] == [], got["errors"] + # nothing called for (the US AQI Good): no effect, no frame, no link, no loop, nothing drawn + assert got["nothing"] == {"effects": [], "levels": {k: 0 for k in got["nothing"]["levels"]}, "running": False, "framed": [], + "link": None, "frames": 0, "ink": 0} + # each effect at its mark and not just short of it (rain above 0 mm/h, the AQI's Moderate band from 51, UV 11, 95 %, wind above + # 50 km/h, 40 °C, below 0 °C, not at it), its tile framed in red, the strip's link with it + for name, mark in got["marks"].items(): + effect = "ice" if name == "iceAtZero" else name + assert mark["below"] | {"levels": None} == {"effects": [], "levels": None, "running": mark["below"]["running"], "framed": [], + "link": None}, (name, mark) + assert mark["at"]["effects"] == [effect] and mark["at"]["framed"] == [EFFECTS[effect]], (name, mark) + assert mark["at"]["link"] == "stop animations" and mark["at"]["running"], (name, mark) + assert got["smogBands"] == [2, 3, 4, 5, 5] # thicker with each band: USG to Hazardous + assert got["rainStrength"][0] < 0.4 and got["rainStrength"][1:] == [1, 1] # light at 0.5 mm/h, heavy from 8 + assert got["iceDepth"] == [0.5, 5] # further in the colder + # several at once: one canvas, one loop, at most 30 frames drawn a second + several = got["several"] + assert several["effects"] == ["smog", "radiation", "rain", "leaves", "drips", "ice"] and several["canvases"] == 1, several + assert sorted(several["framed"]) == sorted({EFFECTS[k] for k in several["effects"]}) and several["ink"] > 0, several + assert 20 <= several["drawn"] <= 32 and several["frames"] <= 64, several # (one request a display frame, every other one drawn) + # the canvas: filling the window, fixed, first, behind the tiles, never in the pointer's way, its pixels crisp + assert got["canvas"] == {"rect": [0, 0, 1024, 768], "canvas": [True, True], "position": "fixed", "z": "0", "events": "none", + "first": True, "pixelated": "pixelated", "under": True} + # the tiles see-through (what's behind shows in a tile's margin), their foreground opaque; zoomed too + assert got["through"] == {"differs": True, "still": True} + assert got["look"] == {"background": "rgba(0, 0, 0, 0)", "opacity": "1", "title": "rgb(232, 234, 237)", "frame": "rgb(38, 46, 52)", + "alertFrame": "rgb(217, 54, 62)"} + assert got["zoomed"] == {"zoomed": True, "title": "UV index", "background": "rgba(0, 0, 0, 0)", "grid": "rgba(0, 0, 0, 0)", + "alert": True, "running": True} + # "stop animations": nothing drawn, no loop, the frame stays, kept across a reload; "start animations" and the reset put them back + assert got["stopped"] | {"levels": None} == {"effects": ["radiation"], "levels": None, "running": False, "framed": ["UV index"], + "link": "start animations", "frames": 0, "ink": 0, "stored": False}, got["stopped"] + assert got["reloaded"]["link"] == "start animations" and got["reloaded"]["frames"] == 0 and not got["reloaded"]["running"] + for step in ("restarted", "reset"): + assert got[step]["link"] == "stop animations" and got[step]["running"] and got[step]["frames"] > 10, (step, got[step]) + # the temporary test links: each its effect and frame (the gauges keep their readings), the URL following; smog steps through its + # bands, rain light then heavy; ice melts back; "clear" ends them all; "all" and ?fx= when the page opens + links = got["links"] + on = [] + for name in ("radiation", "drips", "leaves", "heat", "ice"): + on.append(name) + assert set(links[name]["effects"]) == set(on) and EFFECTS[name] in links[name]["framed"], (name, links[name]) + assert links[name]["url"] == "?fx=" + ",".join(on) + assert links["label"] == "UV index 0.0" # (the stand-in's reading, not the simulated one) + assert links["smog"] == [1, 2, 3, 4, 5, 0] and links["rain"] == [0.35, 1, 0] + melting = links["melting"] + assert melting["grown"] > 2 and 0 < melting["reach"] < melting["grown"] and "ice" not in melting["effects"] and melting["running"], melting + assert links["cleared"] | {"levels": None, "running": None} == {"effects": [], "levels": None, "running": None, "framed": [], + "link": None, "url": ""} + every = ["smog", "heat", "radiation", "rain", "leaves", "drips", "ice"] + assert links["all"]["effects"] == every and links["all"]["url"] == "?fx=rain2,smog3,radiation,drips,leaves,heat,ice" + assert got["param"]["levels"] == {"smog": 3, "heat": 0, "radiation": 0, "rain": 0, "leaves": 1, "drips": 0, "ice": 5} + assert sorted(got["param"]["framed"]) == ["Temperature", "US AQI", "Wind"] and got["param"]["errors"] == [] + assert got["paramAll"]["effects"] == every and got["paramRain"]["levels"]["rain"] == 1 + # reduced motion: no loop, one still, faint frame (the ice as it would be), the frames and the link as ever + still = got["still"] + assert still["effects"] == ["radiation", "ice"] and not still["running"] and still["frames"] == 0 and still["stateFrames"] == 0, still + assert still["ink"] > 0 and sorted(still["framed"]) == ["Temperature", "UV index"] and still["link"] == "stop animations", still + assert got["cost"] < 8, got["cost"] # (ms of script a frame, every effect on) diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 13fbab6a..e7c745f7 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -19,6 +19,10 @@ // was seen}; with a single tile, no zoom. // node web_dashboard_browser.js URL --zoom-touch: the page at 390x844 with touch: a tap zooms, swipes (slow, a flick, on the text) // page, a vertical swipe and a long press do nothing, a tap goes back where the page was scrolled; prints {step: what was seen}. +// node web_dashboard_browser.js URL --weather: the page at 1024x768, its data altered on the way (each reading at, and just short of, the +// mark that calls up its effect behind the tiles), the canvas behind the tiles, the tiles' red frames, "stop animations", reduced +// motion, no loop with nothing called for, the temporary test links and ?fx=, the frame time with every effect on; prints {step: what +// was seen}. // node web_dashboard_browser.js URL --fill CASES: for each case {name: [width, height, hidden titles]}, the page with those hidden; // prints {name: {rects, columns, scroll}}. "use strict"; @@ -634,6 +638,194 @@ async function fillMode(browser, url, cases) { process.stdout.write(JSON.stringify(out)); } +// ---------- the weather behind the tiles ---------- +// The page with its data altered on the way: `readings` {title: value} for the tiles' readings, rain_rate as it is; the US AQI Good +// unless given (the stand-in's is Moderate) +async function weatherPage(browser, url, options = {}) { + const state = { readings: {} }; + const context = await browser.newContext({ viewport: { width: 1024, height: 768 }, deviceScaleFactor: 1, ...(options.context || {}) }); + await context.addInitScript(() => { // (every frame the page asks for, counted) + window.__frames = 0; + const ask = window.requestAnimationFrame.bind(window); + window.requestAnimationFrame = (f) => { window.__frames++; return ask(f); }; + }); + await context.route(/\/dashboard\/data$/, async (route) => { + const response = await route.fetch(), data = await response.json(); + const readings = { "US AQI": 40, ...state.readings }; + for (const t of data.tiles) if (t.title in readings) t.value = readings[t.title]; + if ("rain_rate" in readings) data.rain_rate = readings.rain_rate; + await route.fulfill({ response, json: data }); + }); + const page = await context.newPage(); + const errors = []; + page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); }); + page.on("pageerror", (e) => errors.push(String(e))); + await page.goto(url + (options.query || ""), { waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /updated/.test(document.getElementById("status").textContent)); + // The readings now these (fetched again: the page fetches when it's shown again) + const reads = async (readings) => { + state.readings = readings; + const was = await page.evaluate(() => JSON.stringify(Sky.state().levels) + document.querySelectorAll(".tile.alert").length); + await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))); + await page.waitForTimeout(250); + return was; + }; + return { context, page, errors, reads }; +} +const weatherSeen = (page) => page.evaluate(() => { + const s = Sky.state(), link = document.querySelector("#status .animations"); + return { effects: s.effects, levels: s.levels, running: s.running, + framed: [...document.querySelectorAll("#grid .tile.alert .title")].map((t) => t.textContent), + link: link ? link.textContent : null }; +}); +const canvasInk = (page) => page.evaluate(() => { // how many of the canvas's pixels have anything drawn + const c = document.querySelector("#sky canvas"), d = c.getContext("2d").getImageData(0, 0, c.width, c.height).data; + let n = 0; + for (let i = 3; i < d.length; i += 4) if (d[i]) n++; + return n; +}); +const framesIn = async (page, ms) => { // the frames the page asked for in this long + const before = await page.evaluate(() => window.__frames); + await page.waitForTimeout(ms); + return (await page.evaluate(() => window.__frames)) - before; +}; + +async function weatherMode(browser, url) { + const out = {}; + const { context, page, errors, reads } = await weatherPage(browser, url); + await page.waitForTimeout(1300); // (the gauges' rise) + out.nothing = { ...await weatherSeen(page), frames: await framesIn(page, 800), ink: await canvasInk(page) }; + // each mark: just short of it, then at it + const marks = { rain: [{ rain_rate: 0 }, { rain_rate: 0.1 }], smog: [{ "US AQI": 50 }, { "US AQI": 51 }], + radiation: [{ "UV index": 10.9 }, { "UV index": 11 }], drips: [{ Humidity: 94.9 }, { Humidity: 95 }], + leaves: [{ Wind: 50 }, { Wind: 50.1 }], heat: [{ Temperature: 39.9 }, { Temperature: 40 }], + ice: [{ Temperature: 0.1 }, { Temperature: -0.1 }], iceAtZero: [{ Temperature: 0 }, { Temperature: -0.1 }] }; + out.marks = {}; + for (const [name, [below, at]] of Object.entries(marks)) { + await reads(below); + const short = await weatherSeen(page); + await reads(at); + out.marks[name] = { below: short, at: await weatherSeen(page) }; + } + out.smogBands = []; + for (const aqi of [101, 151, 201, 301, 500]) { await reads({ "US AQI": aqi }); out.smogBands.push((await weatherSeen(page)).levels.smog); } + out.rainStrength = []; + for (const rate of [0.5, 8, 20]) { await reads({ rain_rate: rate }); out.rainStrength.push((await weatherSeen(page)).levels.rain); } + out.iceDepth = []; + for (const t of [-0.5, -5]) { await reads({ Temperature: t }); out.iceDepth.push((await weatherSeen(page)).levels.ice); } + // several at once: one canvas, one loop (at most 30 frames a second) + await reads({ "UV index": 11, Wind: 60, Temperature: -3, rain_rate: 2, Humidity: 97, "US AQI": 160 }); + await page.waitForTimeout(1200); // (the gauges' move to their new readings, MOVE_MS: frames of their own) + const drawnBefore = await page.evaluate(() => Sky.state().frames); + out.several = { ...await weatherSeen(page), canvases: await page.evaluate(() => document.querySelectorAll("canvas").length), + frames: await framesIn(page, 1000), ink: await canvasInk(page) }; + out.several.drawn = (await page.evaluate(() => Sky.state().frames)) - drawnBefore; + // the canvas: the window's size, fixed, first in the page, behind the tiles (which come after it), clicks through it + out.canvas = await page.evaluate(() => { + const sky = document.getElementById("sky"), c = sky.querySelector("canvas"), r = sky.getBoundingClientRect(), cr = c.getBoundingClientRect(); + const st = getComputedStyle(sky); + return { rect: [r.left, r.top, r.width, r.height], canvas: [cr.width >= innerWidth, cr.height >= innerHeight], + position: st.position, z: st.zIndex, events: st.pointerEvents, first: document.body.firstElementChild === sky, + pixelated: getComputedStyle(c).imageRendering, + under: document.elementFromPoint(innerWidth / 2, innerHeight / 2).closest("#grid") !== null }; + }); + // the tiles see-through: a tile's blank margin shows what's drawn behind it (smog, Hazardous, over the bottom row) + await reads({ "US AQI": 500 }); + await page.waitForTimeout(1800); + const margin = async () => { + const r = await tileOf(page, "PM10").boundingBox(); + return page.screenshot({ clip: { x: r.x + r.width * 0.04, y: r.y + r.height * 0.45, width: r.width * 0.12, height: r.height * 0.15 } }); + }; + const smoggy = await margin(); + await reads({}); + await page.waitForTimeout(1800); // (faded out) + const clear1 = await margin(), clear2 = await margin(); + out.through = { differs: !smoggy.equals(clear1), still: clear1.equals(clear2) }; + out.look = await page.evaluate(() => { + const tile = document.querySelector(".tile"), before = getComputedStyle(tile, "::before"); + return { background: getComputedStyle(tile).backgroundColor, opacity: getComputedStyle(tile).opacity, + title: getComputedStyle(tile.querySelector(".title")).color, frame: before.borderTopColor }; + }); + await reads({ "UV index": 11 }); + out.look.alertFrame = await page.evaluate(() => getComputedStyle(document.querySelector(".tile.alert"), "::before").borderTopColor); + // zoomed: the tile still see-through, its frame still red, the effect still behind it + const [zx, zy] = await at(page, "UV index", 0.85, 0.3); + await page.mouse.click(zx, zy); + await page.waitForTimeout(400); + out.zoomed = await page.evaluate(() => { + const shown = [...document.querySelectorAll("#grid .tile")].find((t) => !t.inert); + return { zoomed: document.body.classList.contains("zoomed"), title: shown.querySelector(".title").textContent, + background: getComputedStyle(shown).backgroundColor, grid: getComputedStyle(document.getElementById("grid")).backgroundColor, + alert: shown.classList.contains("alert"), running: Sky.state().running }; + }); + await page.keyboard.press("Escape"); + await page.waitForTimeout(300); + // "stop animations": nothing drawn, no loop, the frames stay; kept; "reset preferences" starts them again + await page.locator("#status .animations").click(); + await page.waitForTimeout(200); + out.stopped = { ...await weatherSeen(page), frames: await framesIn(page, 600), ink: await canvasInk(page), + stored: JSON.parse(await page.evaluate((key) => localStorage.getItem(key), KEY)).animations }; + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile.alert").length > 0); + await page.waitForTimeout(1300); // (the gauges' rise) + out.reloaded = { ...await weatherSeen(page), frames: await framesIn(page, 500) }; + await page.locator("#status .animations").click(); + await page.waitForTimeout(300); + out.restarted = { ...await weatherSeen(page), frames: await framesIn(page, 500) }; + await page.locator("#status .animations").click(); // (stopped again: reset puts them back) + await page.mouse.move(...await at(page, "Rain", 0.5, 0.4)); + await page.waitForTimeout(250); + await tileOf(page, "Rain").locator(".close").click(); + await page.waitForTimeout(300); + await page.getByText("reset preferences").click(); + await page.waitForTimeout(400); + out.reset = { ...await weatherSeen(page), frames: await framesIn(page, 500) }; + // the temporary test links: each turns its effect and frame on (the gauges keep their readings), "clear" ends them; the URL follows + await reads({}); + await page.waitForTimeout(1700); + const fx = (name) => page.locator("#fxtest button", { hasText: new RegExp(`^${name}`) }).first().click(); + const label = () => page.evaluate(() => document.querySelector(".tile[data-id='UV index']").getAttribute("aria-label")); + out.links = {}; + for (const name of ["radiation", "drips", "leaves", "heat", "ice"]) { + await fx(name); + out.links[name] = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; + } + out.links.label = await label(); + out.links.smog = []; + for (let i = 0; i < 6; i++) { await fx("smog"); out.links.smog.push((await weatherSeen(page)).levels.smog); } + out.links.rain = []; + for (let i = 0; i < 3; i++) { await fx("rain"); out.links.rain.push((await weatherSeen(page)).levels.rain); } + await page.waitForTimeout(2500); // (the ice grown in a little) + const grown = await page.evaluate(() => Sky.state().iceReach); + await fx("ice"); // (off: it melts back, the loop running on until it's gone) + await page.waitForTimeout(300); + out.links.melting = { grown, reach: await page.evaluate(() => Sky.state().iceReach), ...await weatherSeen(page) }; + await fx("clear"); + await page.waitForTimeout(100); + out.links.cleared = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; + await fx("all"); + out.links.all = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; + await page.waitForTimeout(3000); + out.cost = await page.evaluate(() => Sky.state().cost); // (ms of script a frame, with every effect on) + out.errors = errors; + await context.close(); + // ?fx= when the page opens + for (const [name, query] of [["param", "?fx=smog3,leaves,ice"], ["paramAll", "?fx=all"], ["paramRain", "?fx=rain2"]]) { + const opened = await weatherPage(browser, url, { query }); + await opened.page.waitForTimeout(200); + out[name] = { ...await weatherSeen(opened.page), errors: opened.errors }; + await opened.context.close(); + } + // reduced motion: no loop, one still, faint frame; the frames as ever + const still = await weatherPage(browser, url, { context: { reducedMotion: "reduce" } }); + await still.reads({ "UV index": 11, Temperature: -4 }); + await still.page.waitForTimeout(500); + out.still = { ...await weatherSeen(still.page), frames: await framesIn(still.page, 800), ink: await canvasInk(still.page), + stateFrames: await still.page.evaluate(() => Sky.state().frames), errors: still.errors }; + await still.context.close(); + process.stdout.write(JSON.stringify(out)); +} + (async () => { const [url, second, third] = process.argv.slice(2); const browser = await chromium.launch(); @@ -645,6 +837,7 @@ async function fillMode(browser, url, cases) { else if (second === "--fill") await fillMode(browser, url, JSON.parse(third)); else if (second === "--zoom") await zoomMode(browser, url); else if (second === "--zoom-touch") await zoomTouchMode(browser, url); + else if (second === "--weather") await weatherMode(browser, url); else await sizes(browser, url, second, JSON.parse(third)); } finally { await browser.close(); From ba82f3249d213d20b19e52e50f96472198079720 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:51:37 +0000 Subject: [PATCH 007/146] Web dashboard: fainter, shorter ice; a framed tile's drag frames; the test row clear of the strip on phones; tests for the canvas behind and the combined brightness MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Ice drawn at 0.4 (its glints brighter), reaching 6 % of the window's shorter side at -5 °C (9 % at -10), the corners about 1.8 times that: the tables at the window's edges stay readable. - The red frame's rules come before the drag's: a framed tile lifted shows the lifted grey, over the remove zone the remove red. - The temporary test row fits the room the strip leaves, or sits just above it where that's too little; role="group", aria-pressed. - Tests: the canvas behind a tile with hit-testing on; every effect at once no brighter than Hazardous smog alone; the drag frames on a framed tile; the test row and the strip apart on a phone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 34 +++++++++++++++++------- tests/test_web_dashboard.py | 12 +++++++-- tests/web_dashboard_browser.js | 47 ++++++++++++++++++++++++++++++++-- 3 files changed, 80 insertions(+), 13 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 8c87900a..b2b98532 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -51,6 +51,10 @@ .tile:focus { outline: none; } .tile:focus-visible::before { border-color: var(--soft); } body.dragging .tile:not(.lifted) .grip, body.dragging .tile:not(.lifted) .close { opacity: 0; } + /* A tile whose reading calls up an effect behind the tiles (Sky): framed in red, its frame alone (thin, as the others'); before the + drag's frames below, so a framed tile lifted, or over the remove zone, shows those as any other */ + .tile.alert::before { border-color: #D9363E; } + .tile.alert:focus-visible:not(.lifted)::before { border-color: #FF9EA1; } .tile.lifted { z-index: 2; transition: opacity 0.9s ease; } /* follows the pointer: no easing of its own */ .tile.lifted::before { border-color: #5A6670; } .tile.doomed::before { border-color: #E5484D; } @@ -64,9 +68,6 @@ /* The weather behind everything (Sky, below): one canvas, the window's size, fixed, first in the page; its pixels scaled up crisply */ #sky { position: fixed; inset: 0; z-index: 0; overflow: hidden; pointer-events: none; } #sky canvas { position: absolute; left: 0; top: 0; image-rendering: crisp-edges; image-rendering: pixelated; } - /* A tile whose reading calls up an effect behind the tiles (Sky): framed in red, its frame alone (thin, as the others') */ - .tile.alert::before { border-color: #D9363E; } - .tile.alert:focus-visible::before { border-color: #FF9EA1; } #status { position: fixed; right: 0; bottom: 0; height: var(--status, 18px); padding: 0 10px; font-size: 12px; line-height: var(--status, 18px); color: var(--soft); background: rgba(20, 25, 29, 0.85); border-top-left-radius: 6px; z-index: 1; } #status .link { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; text-decoration: underline; @@ -596,9 +597,11 @@ mapped(["..3..", "..4..", "34543", "..4..", "..3.."], {3: ICE[3], 4: ICE[4], 5: ICE[5]})]; let extent = 0, shownAt = -1, layer = null, img = null; let crystals = null, crystalReach = null, crystalShade = null, rim = null, rimReach = null, glints = []; - const most = () => Math.min(W, H) * 0.13; + const most = () => Math.min(W, H) * 0.1; // (a little past the furthest reach, -10 °C) + // How far in (art px, along the edges; the corners about 1.8 times that): a thin rim just below 0 °C, 6 % of the window's shorter + // side at -5 °C, 9 % at -10 °C and colder (no further: the tables at the window's edges stay readable) const reachFor = (degrees) => degrees <= 0 ? 0 : - Math.min(W, H) * (0.025 + 0.065 * Math.min(1, degrees / 5) + 0.03 * clamp((degrees - 5) / 5, 0, 1)); + Math.min(W, H) * (0.02 + 0.04 * Math.min(1, degrees / 5) + 0.03 * clamp((degrees - 5) / 5, 0, 1)); function grow() { const reach = new Float32Array(W * H).fill(Infinity), shade = new Uint8Array(W * H), r = seeded(4242), m = Math.min(W, H); const mark = (x, y, far, s) => { @@ -624,7 +627,7 @@ const edges = [[W, (p) => [p, 0], Math.PI / 2], [W, (p) => [p, H - 1], -Math.PI / 2], [H, (p) => [0, p], 0], [H, (p) => [W - 1, p], Math.PI]]; for (const [span, at, inward] of edges) { for (let p = r() * 5; p < span; p += 5 + r() * 7) { - const corner = Math.pow(clamp(1 - Math.min(p, span - p) / (0.4 * m), 0, 1), 1.5), k = 1 + 1.1 * corner; + const corner = Math.pow(clamp(1 - Math.min(p, span - p) / (0.4 * m), 0, 1), 1.5), k = 1 + 0.8 * corner; const toward = p < span / 2 ? -1 : 1; // (in a corner, leaning along the diagonal, away from the other edge) const tilt = (r() - 0.5) * 1.1 + corner * 0.55 * toward * (inward === Math.PI || inward === Math.PI / 2 ? -1 : 1); const [x, y] = at(p); @@ -666,7 +669,7 @@ layer.getContext("2d").putImageData(img, 0, 0); } return { - strength: () => 0.6, + strength: () => 0.4, // (faint: crystals cross the tiles at the window's edges; the glints brighter) want(v) { e.level = v; if (STILL) extent = reachFor(v); }, fade() { e.amount = extent > 0 ? 1 : 0; }, alive: () => e.level > 0 || extent > 0, @@ -693,6 +696,7 @@ if (shownAt !== extent) show(); g.globalAlpha = alpha; g.drawImage(layer, 0, 0); + g.globalAlpha = Math.min(1, alpha * 1.8); for (const gl of glints) { const p = gl.age / gl.life, sprite = GLINT[p < 0.25 || p > 0.75 ? 0 : p < 0.4 || p > 0.6 ? 1 : 2]; g.drawImage(sprite, gl.x - (sprite.width >> 1), gl.y - (sprite.height >> 1)); @@ -1724,7 +1728,7 @@ ?fx=smog3,leaves,ice, ?fx=all (rain light, rain2 heavy, smog1-smog5, radiation, drips, leaves, heat, ice; "all"). To remove: delete from here to "END TEMPORARY" (this style, the row and its script). The page's own listener for "ecobot-fx" then simply hears nothing. --> -
test:
+
test:
diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index fb740e17..bc789139 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -727,7 +727,9 @@ async def test_the_weather_behind_the_tiles_comes_with_its_reading_frames_its_ti # the tiles see-through (what's behind shows in a tile's margin), their foreground opaque; zoomed too assert got["through"] == {"differs": True, "still": True} assert got["look"] == {"background": "rgba(0, 0, 0, 0)", "opacity": "1", "title": "rgb(232, 234, 237)", "frame": "rgb(38, 46, 52)", - "alertFrame": "rgb(217, 54, 62)"} + "alertFrame": "rgb(217, 54, 62)", + # dragged, a framed tile shows the drag's frames as any other: lifted grey, then the remove zone's red + "dragFrames": {"lifted": "rgb(90, 102, 112)", "doomed": "rgb(229, 72, 77)", "after": "rgb(217, 54, 62)"}} assert got["zoomed"] == {"zoomed": True, "title": "UV index", "background": "rgba(0, 0, 0, 0)", "grid": "rgba(0, 0, 0, 0)", "alert": True, "running": True} # "stop animations": nothing drawn, no loop, the frame stays, kept across a reload; "start animations" and the reset put them back @@ -754,9 +756,15 @@ async def test_the_weather_behind_the_tiles_comes_with_its_reading_frames_its_ti assert links["all"]["effects"] == every and links["all"]["url"] == "?fx=rain2,smog3,radiation,drips,leaves,heat,ice" assert got["param"]["levels"] == {"smog": 3, "heat": 0, "radiation": 0, "rain": 0, "leaves": 1, "drips": 0, "ice": 5} assert sorted(got["param"]["framed"]) == ["Temperature", "US AQI", "Wind"] and got["param"]["errors"] == [] + assert links["role"] == "group" and links["pressed"] == {"rain": "false", "smog": "false", "radiation": "true", "drips": "true", + "leaves": "true", "heat": "true", "ice": "false"}, links["pressed"] + # on a phone, the strip with both its links: the test row beside it or above it, never over it + assert got["phone"]["strip"].endswith("reset preferences") and got["phone"]["apart"] and got["phone"]["onScreen"], got["phone"] assert got["paramAll"]["effects"] == every and got["paramRain"]["levels"]["rain"] == 1 # reduced motion: no loop, one still, faint frame (the ice as it would be), the frames and the link as ever still = got["still"] assert still["effects"] == ["radiation", "ice"] and not still["running"] and still["frames"] == 0 and still["stateFrames"] == 0, still assert still["ink"] > 0 and sorted(still["framed"]) == ["Temperature", "UV index"] and still["link"] == "stop animations", still - assert got["cost"] < 8, got["cost"] # (ms of script a frame, every effect on) + assert got["cost"] < 8, got["cost"] + # several at once no brighter than one strong one: every effect on, against Hazardous smog alone + assert 0 < got["light"]["all"] <= got["light"]["smog5"], got["light"] diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index e7c745f7..fa2fa95b 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -649,6 +649,7 @@ async function weatherPage(browser, url, options = {}) { const ask = window.requestAnimationFrame.bind(window); window.requestAnimationFrame = (f) => { window.__frames++; return ask(f); }; }); + if (options.init) await context.addInitScript(options.init.fn, options.init.arg); await context.route(/\/dashboard\/data$/, async (route) => { const response = await route.fetch(), data = await response.json(); const readings = { "US AQI": 40, ...state.readings }; @@ -684,6 +685,12 @@ const canvasInk = (page) => page.evaluate(() => { // how many of the canvas's for (let i = 3; i < d.length; i += 4) if (d[i]) n++; return n; }); +const canvasLight = (page) => page.evaluate(() => { // how bright the canvas is, all told: its pixels' luminance by their alpha, averaged + const c = document.querySelector("#sky canvas"), d = c.getContext("2d").getImageData(0, 0, c.width, c.height).data; + let sum = 0; + for (let i = 0; i < d.length; i += 4) sum += (0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2]) * d[i + 3] / 255; + return sum / (d.length / 4); +}); const framesIn = async (page, ms) => { // the frames the page asked for in this long const before = await page.evaluate(() => window.__frames); await page.waitForTimeout(ms); @@ -720,14 +727,21 @@ async function weatherMode(browser, url) { out.several = { ...await weatherSeen(page), canvases: await page.evaluate(() => document.querySelectorAll("canvas").length), frames: await framesIn(page, 1000), ink: await canvasInk(page) }; out.several.drawn = (await page.evaluate(() => Sky.state().frames)) - drawnBefore; - // the canvas: the window's size, fixed, first in the page, behind the tiles (which come after it), clicks through it + // the canvas: the window's size, fixed, first in the page, behind the tiles (which come after it), clicks through it. (Behind: its + // pointer-events on for a moment, so hit-testing sees it, a tile's middle is still the tile's) out.canvas = await page.evaluate(() => { const sky = document.getElementById("sky"), c = sky.querySelector("canvas"), r = sky.getBoundingClientRect(), cr = c.getBoundingClientRect(); const st = getComputedStyle(sky); return { rect: [r.left, r.top, r.width, r.height], canvas: [cr.width >= innerWidth, cr.height >= innerHeight], position: st.position, z: st.zIndex, events: st.pointerEvents, first: document.body.firstElementChild === sky, pixelated: getComputedStyle(c).imageRendering, - under: document.elementFromPoint(innerWidth / 2, innerHeight / 2).closest("#grid") !== null }; + under: (() => { + const r = [...document.querySelectorAll("#grid .tile")][3].getBoundingClientRect(); + sky.style.pointerEvents = "auto"; + const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); + sky.style.pointerEvents = ""; + return hit !== null && hit.closest(".tile") !== null; + })() }; }); // the tiles see-through: a tile's blank margin shows what's drawn behind it (smog, Hazardous, over the bottom row) await reads({ "US AQI": 500 }); @@ -748,6 +762,15 @@ async function weatherMode(browser, url) { }); await reads({ "UV index": 11 }); out.look.alertFrame = await page.evaluate(() => getComputedStyle(document.querySelector(".tile.alert"), "::before").borderTopColor); + out.look.dragFrames = await page.evaluate(() => { // a framed tile dragged: lifted, then over the remove zone, its frame as any other's + const tile = document.querySelector(".tile.alert"), frame = () => getComputedStyle(tile, "::before").borderTopColor; + tile.classList.add("lifted"); + const lifted = frame(); + tile.classList.add("doomed"); + const doomed = frame(); + tile.classList.remove("lifted", "doomed"); + return { lifted, doomed, after: frame() }; + }); // zoomed: the tile still see-through, its frame still red, the effect still behind it const [zx, zy] = await at(page, "UV index", 0.85, 0.3); await page.mouse.click(zx, zy); @@ -800,6 +823,9 @@ async function weatherMode(browser, url) { await fx("ice"); // (off: it melts back, the loop running on until it's gone) await page.waitForTimeout(300); out.links.melting = { grown, reach: await page.evaluate(() => Sky.state().iceReach), ...await weatherSeen(page) }; + out.links.pressed = await page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#fxtest button[data-fx]")] + .map((b) => [b.dataset.fx, b.getAttribute("aria-pressed")]))); + out.links.role = await page.evaluate(() => document.getElementById("fxtest").getAttribute("role")); await fx("clear"); await page.waitForTimeout(100); out.links.cleared = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; @@ -807,6 +833,8 @@ async function weatherMode(browser, url) { out.links.all = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; await page.waitForTimeout(3000); out.cost = await page.evaluate(() => Sky.state().cost); // (ms of script a frame, with every effect on) + await page.waitForTimeout(5000); // (the ice grown all the way in) + out.light = { all: await canvasLight(page) }; out.errors = errors; await context.close(); // ?fx= when the page opens @@ -816,6 +844,21 @@ async function weatherMode(browser, url) { out[name] = { ...await weatherSeen(opened.page), errors: opened.errors }; await opened.context.close(); } + // the strongest single effect (Hazardous smog), as bright as "all" may be + const strongest = await weatherPage(browser, url, { query: "?fx=smog5" }); + await strongest.page.waitForTimeout(2500); // (faded in) + out.light.smog5 = await canvasLight(strongest.page); + await strongest.context.close(); + // a phone, a tile hidden, an effect on: the test row and the strip (updated · stop animations · reset preferences) not over each other + const phone = await weatherPage(browser, url, { query: "?fx=rain", context: { viewport: { width: 360, height: 740 }, hasTouch: true, isMobile: true }, + init: { fn: (key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: ["Rain"] })), arg: KEY } }); + await phone.page.waitForTimeout(300); + out.phone = await phone.page.evaluate(() => { + const a = document.getElementById("fxtest").getBoundingClientRect(), b = document.getElementById("status").getBoundingClientRect(); + return { strip: document.getElementById("status").textContent, + apart: a.right <= b.left || b.right <= a.left || a.bottom <= b.top || b.bottom <= a.top, onScreen: a.left >= 0 && a.bottom <= innerHeight }; + }); + await phone.context.close(); // reduced motion: no loop, one still, faint frame; the frames as ever const still = await weatherPage(browser, url, { context: { reducedMotion: "reduce" } }); await still.reads({ "UV index": 11, Temperature: -4 }); From 5ec6b97ea073c63dcff55f6bc8c8487fb8e6fa44 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 22:02:49 +0000 Subject: [PATCH 008/146] Web dashboard: the strip's time at the bottom right, its links to its left; uv just its beams; the wind's leaves caught in eddies and gusts; the test links renamed (wind, uv, humidity), no "all" link MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The bottom strip reads "reset preferences · stop animations · updated 18:42": the links first, the time (or "reconnecting…") last, at the far bottom right. - uv (was radiation): the shimmering motes and their sprites gone; each shaft drawn as a wide faint halo and a narrow core breathing out of step, sliding slowly, the glow along the top as before. No particles. - wind (was leaves): the leaves follow the air: a steady wind to the right pulsing with gusts, turbulence from the curl of two drifting waves, and a few eddies that spring up, draw nearby leaves onto a ring round their eye, sweep them round, and fling them off as they die away; a leaf eases toward the air's speed and turns over faster where the air turns; the wind's wisps trace the same air. Still within the shared particle budget. - humidity (was drips), and the test links and ?fx= values: wind, uv, humidity. The "all" link is gone; ?fx=all still works. - Sky.state() reports each effect's particles and the budget, for the tests: uv none, the wind alone and everything together within it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 242 +++++++++++++++++++++------------ tests/test_web_dashboard.py | 49 ++++--- tests/web_dashboard_browser.js | 29 ++-- 3 files changed, 204 insertions(+), 116 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index b2b98532..6d7b5493 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -12,7 +12,7 @@ The tiles can be rearranged in the browser: dragged to reorder (a long press on a touch screen), hidden with their × or the remove zone, all put back with "reset preferences"; kept in localStorage ("ecobot.dashboard.v1"), nothing sent to the server. A click or tap on a gauge zooms its tile to fill the window, a gallery paged through by keys, swipes and drags; Esc goes back. - Behind everything, the weather as pixel art on one canvas (Sky): rain, smog, radiation, drips, leaves, heat and ice, each while the + Behind everything, the weather as pixel art on one canvas (Sky): rain, smog, uv, humidity, wind, heat and ice, each while the readings call for it, its tile framed in red; "stop animations" in the strip stops them. --> @@ -885,7 +892,8 @@ const TOUCH_SLOP = 10, MOUSE_SLOP = 5; // moved further (CSS px) first: a touch scrolls instead, a mouse press becomes a drag const BUZZ_MS = 15; // the vibration as a long press picks a tile up (where navigator.vibrate exists: not iOS) const LIFT = 1.04; // a picked-up tile, a little larger - const TABLE_TOP = 372; // where the Daily/Monthly/Yearly table starts, in the tile's own pixels (table(): 378) + const TABLE_TOP = 372; // where the Daily/Monthly/Yearly table starts, in the tile's own pixels (table(): 378); above + // it, the title and the gauge (a dial's band name ends at 370): all the zoomed view shows const EDGE = 48, EDGE_SPEED = 10; // a drag this near the window's top or bottom scrolls a scrolling page, this many px a frame const ZOOM_MS = 200; // a tile zooming to fill the window, and back const STEP_MS = 200; // the zoomed view: a key's step to the next or previous tile @@ -1016,12 +1024,12 @@ const DRAW = {thermometer, dial, beaker}; - // ---------- HTML: the title and the table, placed in the tile's own pixels (480 x 575), sized with it ---------- + // ---------- HTML: the title and the table, placed in the tile's own pixels (480 x 575), sized with it (by its width: cqw) ---------- function place(parent, x, y, w, h, size, words, cls, style) { - const [W, H] = L.cell; + const W = L.cell[0], u = (v) => `${v / W * 100}cqw`; const d = document.createElement("div"); d.className = "at " + (cls || ""); - Object.assign(d.style, {left: `${x / W * 100}%`, top: `${y / H * 100}%`, width: `${w / W * 100}%`, height: `${h / H * 100}%`, + Object.assign(d.style, {left: u(x), top: u(y), width: u(w), height: u(h), fontSize: `${size / W * 100}cqw`}, style || {}); d.textContent = words; parent.appendChild(d); @@ -1063,6 +1071,7 @@ box.setAttribute("aria-label", label(tile)); box.tabIndex = 0; // (focused, Enter or Space zooms it) const svg = el("svg", {viewBox: `0 0 ${L.cell[0]} ${L.cell[1]}`, preserveAspectRatio: "xMidYMid meet", "aria-hidden": "true"}); + svg.style.height = `${L.cell[1] / L.cell[0] * 100}cqw`; // (by the width: zoomed, the tile's box is only its top) box.appendChild(svg); const at = DRAW[tile.kind](svg, tile, ink, `clip${clips++}`); place(box, 0, 38 - 25, L.cell[0], 50, 38, tile.title, "title", {color: ink(L.ink)}); @@ -1322,7 +1331,7 @@ function draggable(e, box) { if (e.target.closest(".close, .title, .unit, .chip, .figure")) return false; const r = box.getBoundingClientRect(); - if ((e.clientY - r.top) / r.height * L.cell[1] >= TABLE_TOP) return false; // (the table, gaps between its chips too) + if ((e.clientY - r.top) / r.width * L.cell[0] >= TABLE_TOP) return false; // (the table, gaps between its chips too) const reading = box.querySelector("svg text.reading"); const t = reading && reading.getBoundingClientRect(); return !(t && t.width && e.clientX >= t.left - 2 && e.clientX <= t.right + 2 && e.clientY >= t.top - 2 && e.clientY <= t.bottom + 2); @@ -1472,8 +1481,8 @@ } // ---------- the zoomed view: one tile filling the window, and a gallery through the others ---------- - // A click or tap on a tile's gauge (not its text) zooms the whole tile to fill the window; a click or tap without moving (with a mouse, - // not on the text) or Esc goes back. Both are a FLIP: the tiles laid out where they end, then each eased by its transform from where + // A click or tap on a tile's gauge (not its text) zooms its title and gauge (its table hidden) to fill the window; a click or tap + // without moving (with a mouse, not on the text) or Esc goes back. Both are a FLIP: the tiles laid out where they end, then each eased by its transform from where // it was (the tile shown grows from, or shrinks to, its place; the others fade out where they were, or in where they are). // Zoomed, the visible tiles stand side by side in #grid, one window-width apart, and #grid slides sideways (its transform only) to // page through them, in the saved order, stopping at the first and the last: ←/→, Space and Backspace step; a drag on the gauge (a @@ -1542,10 +1551,11 @@ } } - // The gallery's places for the window's size now: each tile as large as fits beside the status strip, centred in its place + // The gallery's places for the window's size now: each tile's title and gauge (its top, to TABLE_TOP: the table hidden) as large as + // fits beside the status strip, centred in its place function galleryLayout() { const boxes = [...grid.children], n = boxes.length; - const aspect = L.cell[0] / L.cell[1], W = window.innerWidth, H = window.innerHeight - 2 * PAD - STATUS; + const aspect = L.cell[0] / TABLE_TOP, W = window.innerWidth, H = window.innerHeight - 2 * PAD - STATUS; const w = Math.min(W - 2 * PAD, H * aspect), h = w / aspect; for (const [k, v] of Object.entries({"--zw": w, "--zh": h, "--zx": (W - w) / 2, "--zy": PAD + (H - h) / 2, "--pitch": W})) grid.style.setProperty(k, `${v}px`); diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index fcd1137f..cb7ab739 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -370,7 +370,9 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl assert got["tiles"] == n and got["scrollWidth"] <= width, (name, got) assert got["status"] == "stop animations · updated 18:42", (name, got) # (the US AQI's 56, Moderate: smog behind the tiles) assert all(r["right"] <= width + 0.5 and r["left"] >= -0.5 for r in got["rects"]), (name, got) - assert (shots / f"dashboard-{name}.png").exists() + assert (shots / f"dashboard-{name}.png").exists() and (shots / f"dashboard-{name}-zoomed.png").exists() + assert got["zoomed"]["zoomed"], (name, got["zoomed"]) + fills(got["zoomed"], width, height) # zoomed: its title and gauge fill the window, no table for name in ("tablet-landscape", "tablet-portrait", "desktop"): # these fit every tile without scrolling got = report[name] assert got["scroll"] == "no" and got["scrollHeight"] <= SIZES[name][1], (name, got) @@ -574,11 +576,13 @@ async def test_fewer_tiles_grow_evenly_to_fill_the_window_and_never_shrink_below # ---------- the zoomed view and its gallery ---------- ZOOM_MS = 200 +TABLE_TOP = 372 # (the web page's: where a tile's table starts, in its own pixels; above it the title and gauge, all a zoomed tile shows) def zoomed_rect(width, height): - """The zoomed tile's place at this window size: as large as fits beside the margins and the status strip, centred.""" - aspect = look()["cell"][0] / look()["cell"][1] + """The zoomed tile's place at this window size: its title and gauge (no table) as large as fits beside the margins and the status + strip, centred.""" + aspect = look()["cell"][0] / TABLE_TOP w = min(width - 16, (height - 16 - 18) * aspect) h = w / aspect return {"left": (width - w) / 2, "top": 8 + (height - 16 - 18 - h) / 2, "width": w, "height": h} @@ -588,6 +592,20 @@ def near(rect, want, tolerance=1.0): return all(abs(rect[k] - want[k]) <= tolerance for k in ("left", "top", "width", "height")) +def fills(zl, width, height): + """A zoomed tile's look (__look) at this window size: no table; its box (the title and gauge) as large as fits, its limiting axis + within a few px of the window's room (less the margins and the status strip), centred, clear of the strip; its text inside it.""" + box, room = zl["box"], (width - 16, height - 16 - 18) + assert zl["table"] == ["hidden 0"], zl + assert box["width"] <= room[0] + 1 and box["height"] <= room[1] + 1, zl + assert room[0] - box["width"] <= 3 or room[1] - box["height"] <= 3, zl # (one axis filled) + assert box["width"] / box["height"] == pytest.approx(look()["cell"][0] / TABLE_TOP, rel=0.01), zl # (its proportions kept) + assert (box["left"] + box["right"]) / 2 == pytest.approx(width / 2, abs=1), zl + assert (box["top"] + box["bottom"]) / 2 == pytest.approx(8 + room[1] / 2, abs=1) and box["bottom"] <= height - 18, zl + for r in [zl["title"], *zl["texts"]]: # (the reading, a dial's band word) + assert box["left"] - 1 <= r["left"] and r["right"] <= box["right"] + 1 and box["top"] - 1 <= r["top"] and r["bottom"] <= box["bottom"] + 1, (r, zl) + + @pytest.mark.skipif(not browser_there(), reason="needs node with Playwright's Chromium") async def test_a_click_on_a_gauge_zooms_its_tile_and_the_gallery_pages_by_keys_drags_and_swipes_stopping_at_both_ends(server, station): port = free_port() @@ -610,12 +628,20 @@ async def test_a_click_on_a_gauge_zooms_its_tile_and_the_gallery_pages_by_keys_d # the cursor: a magnifier with + over a gauge, the usual one over the text; zoomed, a magnifier with − (around the tile too) assert got["cursor"] == {"gauge": "zoom-in", "title": "auto", "figure": "auto", "reading": "auto"} assert got["zoomedCursor"] == {"gauge": "zoom-out", "margin": "zoom-out", "title": "auto"} - # a click on the gauge: the whole tile grows from its place to fill the window, in 200 ms (a FLIP: transforms only) + # a click on the gauge: its title and gauge (the grid tile's top part) grow from their place to fill the window, in 200 ms (a FLIP: + # transforms only), ending exactly there; the title moving with the tile all the way (no jump); the table gone from the start zoom_in = got["zoomIn"] assert zoom_in["zoomed"] and zoom_in["shown"] == "Humidity" and ZOOM_MS in zoom_in["anims"], zoom_in - assert near(zoom_in["first"], got["gridRect"] | {"left": got["gridRect"]["x"], "top": got["gridRect"]["y"]}, 2), zoom_in + grid_rect = got["gridRect"] | {"left": got["gridRect"]["x"], "top": got["gridRect"]["y"]} + assert near(zoom_in["first"], grid_rect | {"height": grid_rect["width"] * TABLE_TOP / look()["cell"][0]}, 2), zoom_in assert near(zoom_in["last"], full) and zoom_in["between"] and 150 <= zoom_in["settledMs"] <= 330, zoom_in + assert all(t == pytest.approx(zoom_in["titles"][0], abs=0.002) for t in zoom_in["titles"]), zoom_in["titles"] # (in the tile's terms) + tables = zoom_in["tables"] + assert tables and set(tables) == {0}, tables assert got["grip"] == "none" # (no grip or × in the zoomed view) + # zoomed: no table (the gallery's others neither); the title and gauge fill the window, centred, clear of the strip + fills(got["zoomedLook"], 1024, 768) + assert got["neighbourTable"] == ["hidden 0"], got["neighbourTable"] # live: the tile beside it, off the screen, takes the new reading in place, and shows it as it slides in assert got["live"] == {"label": "Temperature 21.5 °C", "sameTile": True, "zoomed": True, "shown": "Humidity", "track": -1024} keys = got["keys"] @@ -648,14 +674,16 @@ async def test_a_click_on_a_gauge_zooms_its_tile_and_the_gallery_pages_by_keys_d # a drag on the text selects it: no paging, still zoomed text = got["text"] assert {k: (v["selected"], v["shown"], v["zoomed"]) for k, v in text.items()} == { - "title": (default[-1], default[-1], True), "reading": (text["reading"]["selected"], default[-1], True), - "table": (text["table"]["selected"], default[-1], True)}, text - assert text["reading"]["selected"].strip() and text["table"]["selected"].strip(), text + "title": (default[-1], default[-1], True), "reading": (text["reading"]["selected"], default[-1], True)}, text + assert text["reading"]["selected"].strip(), text # a click without moving: back to the dashboard in 200 ms, the tile in its place in the grid zoom_out = got["zoomOut"] - assert not zoom_out["zoomed"] and near(zoom_out["first"], full) and zoom_out["between"] and 150 <= zoom_out["settledMs"] <= 330, zoom_out + whole = full | {"height": full["width"] * look()["cell"][1] / look()["cell"][0]} # (the whole tile, from there: its row height rounded, scaled up) + assert not zoom_out["zoomed"] and near(zoom_out["first"], whole, 3) and zoom_out["between"] and 150 <= zoom_out["settledMs"] <= 330, zoom_out assert near(zoom_out["last"], got["outRect"] | {"left": got["outRect"]["x"], "top": got["outRect"]["y"]}) assert zoom_out["last"]["width"] == pytest.approx(got["gridRect"]["width"], abs=0.5) + tables = zoom_out["tables"] # (its table back: hidden as it shrinks, then fading in) + assert tables[0] == 0 and tables[-1] == 1 and all(a <= b for a, b in zip(tables, tables[1:])) and got["outTable"] == ["visible 1"], (tables, got["outTable"]) # Esc: back too, the order as it was assert got["esc"]["before"]["zoomed"] and got["esc"]["before"]["shown"] == "Wind" and not got["esc"]["after"]["zoomed"] assert got["esc"]["titles"] == default @@ -689,6 +717,7 @@ async def test_on_a_touch_screen_a_tap_zooms_a_swipe_pages_from_anywhere_and_a_t assert got["zoomed"]["zoomed"] and got["zoomed"]["shown"] == got["tapped"] assert not got["backStraight"]["zoomed"] and abs(got["backStraight"]["scrollY"] - got["scrolled"]) <= 2, got["backStraight"] assert near(got["zoomed"]["rect"] | {"left": got["zoomed"]["rect"]["x"], "top": got["zoomed"]["rect"]["y"]}, zoomed_rect(390, 844)) + fills(got["zoomed"]["look"], 390, 844) assert [got[k]["shown"] for k in ("next", "previous", "flick", "fromTitle")] == [default[t + 1], default[t], default[t + 1], default[t + 2]], got assert got["vertical"]["shown"] == default[t + 2] and got["vertical"]["zoomed"] assert got["held"] == {"zoomed": True, "shown": default[t + 2], "track": got["vertical"]["track"], "buzz": [], "zone": False} diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 1c062318..a6fa2af7 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1,6 +1,7 @@ // The dashboard page in Playwright's Chromium, for tests/test_web_dashboard.py. // node web_dashboard_browser.js URL SHOTS SIZES: the page at each size ({name: [width, height]}): a screenshot of each (SHOTS/dashboard- -// NAME.png, device scale factor 2) and, on stdout, {name: {tiles, rects, columns, scroll, scrollWidth, scrollHeight, status, errors}}. +// NAME.png, device scale factor 2) and, on stdout, {name: {tiles, rects, columns, scroll, scrollWidth, scrollHeight, status, errors, +// zoomed}}; then the first tile zoomed (Enter): its look, and a screenshot (SHOTS/dashboard-NAME-zoomed.png). // node web_dashboard_browser.js URL --live: the page open at 800x600; prints {label} (the first tile's), waits for a line on stdin // (the test has changed the reading), then prints {label, same_page, errors} once the tile shows it, or after 15 s. // node web_dashboard_browser.js URL --arrive TITLE: the page open at 1024x768; prints the tile's state ({label, faded, opacity, shown, @@ -58,6 +59,18 @@ async function sizes(browser, url, shots, wanted) { scrollHeight: document.documentElement.scrollHeight, status: document.getElementById("status").textContent, })), errors }; + // zoomed (Enter on the first tile): its look (box, title, text, table) and a screenshot (SHOTS/dashboard-NAME-zoomed.png) + await page.focus(".tile"); + await page.keyboard.press("Enter"); + await page.waitForTimeout(400); + await page.screenshot({ path: `${shots}/dashboard-${name}-zoomed.png` }); + report[name].zoomed = await page.evaluate(() => { + const t = document.querySelector("#grid .tile"), rect = (e) => e.getBoundingClientRect().toJSON(); + const table = [...t.querySelectorAll(".unit, .chip, .figure, .tablearea")].map((e) => getComputedStyle(e)); + return { zoomed: document.body.classList.contains("zoomed"), box: rect(t), title: rect(t.querySelector(".title")), + texts: [...t.querySelectorAll("svg text")].map(rect).filter((r) => r.width), + table: [...new Set(table.map((c) => `${c.visibility} ${c.opacity}`))] }; + }); await context.close(); } process.stdout.write(JSON.stringify(report)); @@ -357,7 +370,12 @@ const ZOOM_HELPERS = () => { window.__record = (title, ms) => new Promise((resolve) => { const frames = [], start = performance.now(); const step = (now) => { - if (title) { const r = window.__tile(title).getBoundingClientRect(); frames.push({ t: now, left: r.left, top: r.top, width: r.width, height: r.height }); } + if (title) { // (and its title's place, and its table's opacity: a figure's, as drawn) + const t = window.__tile(title), r = t.getBoundingClientRect(), h = t.querySelector(".title").getBoundingClientRect(); + const f = getComputedStyle(t.querySelector(".figure")); + frames.push({ t: now, left: r.left, top: r.top, width: r.width, height: r.height, titleTop: h.top, titleSize: h.height, + table: f.visibility === "hidden" ? 0 : +f.opacity }); + } else frames.push({ t: now, x: window.__track() }); if (now - start < ms) requestAnimationFrame(step); else resolve({ frames, at: window.__at }); }; @@ -368,6 +386,14 @@ const ZOOM_HELPERS = () => { addEventListener("keydown", (e) => { window.__at = performance.now(); setTimeout(() => window.__keys.push([e.key, e.defaultPrevented])); }); addEventListener("wheel", (e) => { setTimeout(() => window.__wheels.push(e.defaultPrevented)); }, { passive: true }); window.__keys = []; window.__wheels = []; + // A tile's look: its box; its title, reading and (a dial's) band word, each on the screen; its table's visibility and opacity + window.__look = (title) => { + const t = window.__tile(title), rect = (e) => e && e.getBoundingClientRect().toJSON(); + const table = [...t.querySelectorAll(".unit, .chip, .figure, .tablearea")].map((e) => getComputedStyle(e)); + return { box: rect(t), title: rect(t.querySelector(".title")), reading: rect(t.querySelector("svg text.reading")), + texts: [...t.querySelectorAll("svg text")].map(rect).filter((r) => r.width), + table: [...new Set(table.map((c) => `${c.visibility} ${c.opacity}`))] }; + }; }; // A recording summed up: where it started and ended, whether it passed through between, and how long after the click or key it came to rest function motion(rec, key) { @@ -382,7 +408,9 @@ async function zoomClick(page, title, point) { // a click, the tile's rect rec await page.waitForTimeout(50); await page.mouse.click(...point); const rec = await recording; - return { ...motion(rec, ["left", "top", "width", "height"]), anims: await page.evaluate(() => window.__anims), ...await page.evaluate(() => window.__state()) }; + const after = rec.frames.filter((x) => x.t >= rec.at); + return { ...motion(rec, ["left", "top", "width", "height"]), anims: await page.evaluate(() => window.__anims), ...await page.evaluate(() => window.__state()), + tables: after.map((x) => x.table), titles: after.map((x) => [(x.titleTop - x.top) / x.width, x.titleSize / x.width]) }; } async function keyStep(page, key, wait = 400) { // a key, the strip recorded as it slides const recording = page.evaluate(() => window.__record(null, 450)); @@ -419,6 +447,8 @@ async function zoomMode(browser, url) { out.zoomedCursor = { gauge: await cursorAt(page, await at(page, "Humidity", 0.85, 0.3)), margin: await cursorAt(page, [20, 384]), title: await cursorAt(page, await textPoint("Humidity", ".title")) }; out.grip = await page.evaluate(() => getComputedStyle(window.__tile("Humidity").querySelector(".close")).display); + out.zoomedLook = await page.evaluate(() => window.__look("Humidity")); // (its title and gauge filling the window, no table) + out.neighbourTable = await page.evaluate(() => window.__look("Temperature").table); // (the gallery's others: no table either) // live: a new reading for Temperature, the tile beside it off the screen, reaches it in place await page.evaluate(() => { window.__mark = window.__tile("Temperature"); }); process.stdout.write(JSON.stringify({ label: await page.evaluate(() => window.__mark.getAttribute("aria-label")) }) + "\n"); @@ -474,7 +504,7 @@ async function zoomMode(browser, url) { // a drag on the text selects it: no paging, still zoomed const shown = out.last.reached.shown; out.text = {}; - for (const [name, selector] of [["title", ".title"], ["reading", "svg text.reading"], ["table", ".figure"]]) { + for (const [name, selector] of [["title", ".title"], ["reading", "svg text.reading"]]) { const r = await tileOf(page, shown).locator(selector).first().boundingBox(), y = r.y + r.height / 2; await mouseDrag(page, [r.x + 2, y], [r.x + r.width - 1, y + 1]); out.text[name] = { selected: await selection(page), ...await page.evaluate(() => window.__state()) }; @@ -482,6 +512,7 @@ async function zoomMode(browser, url) { // a click without moving on the gauge: back to the dashboard, in 200 ms, the tile in its place out.zoomOut = await zoomClick(page, shown, await at(page, shown, 0.85, 0.3)); out.outRect = await tileOf(page, shown).boundingBox(); + out.outTable = await page.evaluate((shown) => window.__look(shown).table, shown); // (its table back) // a double-click (its clicks 300 ms apart, slower than the zoom): zoomed, not zoomed and straight back out const wind = await at(page, "Wind", 0.85, 0.3); await page.mouse.move(...wind); @@ -590,7 +621,8 @@ async function zoomTouchMode(browser, url) { out.scrolled = scrolled; out.tapped = await page.evaluate(() => document.elementFromPoint(100, 150).closest(".tile").querySelector(".title").textContent); await tap(await at(page, out.tapped, 0.85, 0.3)); - out.zoomed = { ...await page.evaluate(() => window.__state()), rect: await tileOf(page, out.tapped).boundingBox() }; + out.zoomed = { ...await page.evaluate(() => window.__state()), rect: await tileOf(page, out.tapped).boundingBox(), + look: await page.evaluate((title) => window.__look(title), out.tapped) }; // a tap straight back: the page scrolled where it was; then zoomed again await page.waitForTimeout(400); // (not a double tap) await tap([200, 300]); From 36ef44617f27b8fe9a451fc69fc3af3ac1bdb875 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 23:04:19 +0000 Subject: [PATCH 013/146] Web dashboard: Esc mid-zoom goes back from where the tile is drawn (its table hidden until it's in place); the others keep their tables as they fade out flip() cancels a tile's running zoom animation before measuring, so a new one starts where the tile is drawn (no jump to the full size), and only a tile's newest animation ends its `zooming` (a cancelled one's `finished` rejects): the table never fades in on a tile still drawn large. Zooming in, the other tiles are marked `fading` (whole, their table kept) while they fade out in their grid places, so the grid's tables no longer blink off on the first frame. Test: Esc 100 ms into a zoom-in. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 35 +++++++++++++++++++++++++--------- tests/test_web_dashboard.py | 7 +++++++ tests/web_dashboard_browser.js | 17 +++++++++++++++++ 3 files changed, 50 insertions(+), 9 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 046748e1..b02b4f9b 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -103,7 +103,8 @@ Yearly table hidden: gone at once as the tile grows, and while it shrinks back (never drawn large over the others), then fading in, in its place */ .unit, .chip, .figure, .tablearea { transition: opacity 0.15s ease; } - body.zoomed .tile :is(.unit, .chip, .figure, .tablearea), .tile.zooming :is(.unit, .chip, .figure, .tablearea) + body.zoomed .tile.fading { height: var(--zfull); } /* (fading out where they were: whole, their table too) */ + body.zoomed .tile:not(.fading) :is(.unit, .chip, .figure, .tablearea), .tile.zooming :is(.unit, .chip, .figure, .tablearea) { opacity: 0; visibility: hidden; transition: none; } .tile.zooming { z-index: 2; } /* (the tile zooming in or out, over the others) */ body.paging, body.paging * { cursor: grabbing !important; -webkit-user-select: none !important; user-select: none !important; } @@ -1502,6 +1503,7 @@ const boxes = [...grid.children]; const before = new Map(boxes.map((b) => [b, b.getBoundingClientRect()])); zoom = {id: box.dataset.id, index: 0, pitch: 0, x: 0, scrollY: window.scrollY}; + if (!STILL) for (const b of boxes) b.classList.toggle("fading", b !== box); // (before `zoomed`: their tables never hidden meanwhile) document.documentElement.classList.add("zoomed"); document.body.classList.add("zoomed"); layout(); // (the gallery's places, the strip at this tile) @@ -1534,20 +1536,35 @@ if (animate && box) flip(box, before, true); } - // The zoom's animation: `box` from its place before to its place now, the others fading out (zooming in) or in (zooming out) + // The zoom's animation: `box` from its place before to its place now, the others fading out (zooming in) or in (zooming out). + // Each tile's running zoom animation is cancelled first (Esc mid-zoom: `before` was taken mid-way, so the new one starts from where + // the tile is drawn, no jump), and only a tile's newest animation, on finishing, ends its `zooming` (the table hidden, over the + // others) or `fading` (the others, fading out in their grid places, set by zoomIn(): their table kept, fading with them, not gone at + // once) function flip(box, before, out) { - if (STILL) return; + const drawn = new Map(); // (a tile's opacity mid-way through the zoom cancelled: the fade back in from there) + for (const b of before.keys()) { + const running = b.getAnimations().filter((a) => a.id === "zoom"); + if (running.length) drawn.set(b, getComputedStyle(b).opacity); + for (const a of running) a.cancel(); + if (out) b.classList.remove("fading"); + } + if (STILL) { box.classList.remove("zooming"); return; } zoomUntil = performance.now() + ZOOM_MS; - const timing = {duration: ZOOM_MS, easing: "ease-out"}; + const timing = {duration: ZOOM_MS, easing: "ease-out", id: "zoom"}; + const shown = new Map([...before.keys()].map((b) => [b, getComputedStyle(b).opacity])); for (const [b, was] of before) { const now = b.getBoundingClientRect(); const from = `translate(${was.left - now.left}px, ${was.top - now.top}px) scale(${was.width / now.width})`; - const opacity = getComputedStyle(b).opacity; + const opacity = shown.get(b); + let anim; if (b === box) { b.classList.add("zooming"); - b.animate([{transform: from}, {transform: "none"}], timing).finished.then(() => b.classList.remove("zooming"), () => {}); - } else if (out) b.animate([{opacity: 0}, {opacity}], timing); - else b.animate([{transform: from, opacity}, {transform: from, opacity: 0}], timing); + anim = b.animate([{transform: from}, {transform: "none"}], timing); + } else if (out) anim = b.animate([{opacity: drawn.get(b) ?? 0}, {opacity}], timing); + else anim = b.animate([{transform: from, opacity}, {transform: from, opacity: 0}], timing); + b._zoomAnim = anim; + anim.finished.then(() => { if (b._zoomAnim === anim) b.classList.remove("zooming", "fading"); }, () => {}); } } @@ -1557,7 +1574,7 @@ const boxes = [...grid.children], n = boxes.length; const aspect = L.cell[0] / TABLE_TOP, W = window.innerWidth, H = window.innerHeight - 2 * PAD - STATUS; const w = Math.min(W - 2 * PAD, H * aspect), h = w / aspect; - for (const [k, v] of Object.entries({"--zw": w, "--zh": h, "--zx": (W - w) / 2, "--zy": PAD + (H - h) / 2, "--pitch": W})) + for (const [k, v] of Object.entries({"--zw": w, "--zh": h, "--zfull": w * L.cell[1] / L.cell[0], "--zx": (W - w) / 2, "--zy": PAD + (H - h) / 2, "--pitch": W})) grid.style.setProperty(k, `${v}px`); grid.style.setProperty("--n", n); boxes.forEach((b, i) => b.style.setProperty("--i", i)); diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index cb7ab739..76ab20a3 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -704,6 +704,13 @@ async def test_a_click_on_a_gauge_zooms_its_tile_and_the_gallery_pages_by_keys_d assert not kb["esc"]["zoomed"] and kb["esc"]["focus"] == "Humidity" and kb["esc"]["reachable"] == default, kb assert kb["space"]["zoomed"] and kb["space"]["shown"] == "Humidity" == kb["space"]["focus"], kb # one tile: no zoom cursor, no zoom + # Esc mid-way through a zoom-in: back from where the tile is drawn (no jump on to the full size), its table hidden until it's in its + # grid place; the others keep their tables while they fade out (not all gone at once on the first frame) + esc = got["escMid"] + assert esc["others"] == ["visible 1"] and not esc["zoomed"], esc + assert esc["atEsc"] < full["width"] - 50 and esc["peakAfter"] < esc["atEsc"] * 1.15, esc + assert esc["tableWhileLarge"] == 0 and esc["tableEnd"] == 1, esc + assert esc["last"]["width"] == pytest.approx(got["gridRect"]["width"], abs=0.5), esc assert got["single"] == {"cursor": "auto", "zoomed": False} diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index a6fa2af7..b7d50f0d 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -579,6 +579,23 @@ async function zoomMode(browser, url) { out.keyboard.space = await focusState(); await page.keyboard.press("Escape"); await page.waitForTimeout(400); + // Esc 100 ms into a zoom-in: back from where the tile is drawn (no jump to the full size), its table hidden until it's in its grid place + // (never drawn large); the others keep their tables as they fade out, gone only once they're in the gallery + await page.waitForTimeout(300); + { + const recording = page.evaluate(() => window.__record("Humidity", 700)); + await page.waitForTimeout(50); + await page.mouse.click(...await at(page, "Humidity", 0.85, 0.3)); + await page.waitForTimeout(30); + const others = await page.evaluate(() => window.__look("Temperature").table); + await page.waitForTimeout(70); + await page.keyboard.press("Escape"); + const { frames: f, at: esc } = await recording, last = f[f.length - 1], after = f.filter((x) => x.t >= esc); + out.escMid = { others, last, zoomed: await page.evaluate(() => document.body.classList.contains("zoomed")), + atEsc: f.filter((x) => x.t < esc).pop().width, peakAfter: Math.max(...after.map((x) => x.width)), + tableWhileLarge: Math.max(...after.filter((x) => x.width > last.width + 1).map((x) => x.table)), tableEnd: last.table }; + await page.waitForTimeout(300); + } // one tile only: no zoom cursor, a click zooms nothing await page.evaluate((key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: [...document.querySelectorAll(".tile .title")].map((t) => t.textContent).filter((t) => t !== "Rain") })), KEY); await page.reload({ waitUntil: "load" }); From ac88b0e122437546d223eee90da3e5e88cd8b067 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:40:40 +0000 Subject: [PATCH 014/146] Tests: the whole suite in about 53 s, down from about 100 (every check kept) - The browser tests' availability (a node launch) asked once per worker as a test runs, not by every worker as it collects: collection 6.7 s down to 1.5 s a worker. - The weather test split into six (marks, several, stop, links, all, opened), the mouse zoom test into four (in, pager, last, out): each its own page and process, run side by side; sizes' pages opened side by side. - Fixed waits for animations replaced by waiting on the page at rest (calm: no DOM change for 50 ms and no animation running; capped at the old wait where that was a margin); the weather's data waits on its fetch, the ice on its reach; waits for timers (long press, double tap, a swipe's end) kept. - conftest: -n auto is 1.5 workers a CPU; the browser tests dealt out first, at most one per CPU at a time; a worker past its browser tests runs the rest at nice 10, so pages timing their animations get a CPU when they ask. - slow_tests.txt: the new test names. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- DEVELOPMENT.md | 3 +- pytest.ini | 3 +- tests/conftest.py | 52 +- tests/slow_tests.txt | 12 +- tests/test_web_dashboard.py | 122 ++++- tests/web_dashboard_browser.js | 883 ++++++++++++++++++--------------- 6 files changed, 647 insertions(+), 428 deletions(-) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 257f4985..f4238a5d 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -10,7 +10,8 @@ python -m pytest -m "" # every test, the slow ones too (as CI ru python -m pytest -m slow # the slow ones alone python scripts/eval_prompts.py # the saved questions: the reasoning effort (made in code) and the tools' expectations, no key needed ``` -Plain `pytest` takes about 19 s on four cores; everything (`-m ""`) about 45 s. The slow tests, 0.5 s or more each run alone (the browser +Plain `pytest` takes about 19 s on four cores; everything (`-m ""`) about 53 s, and must stay under a minute: the browser tests are split +into parts that run side by side, and wait on the page (`calm` in `tests/web_dashboard_browser.js`) rather than for fixed times. The slow tests, 0.5 s or more each run alone (the browser tests of the web page, the service evals over every tool, the tests that start servers, the archive's own), are listed in `tests/slow_tests.txt` and marked `slow` by `tests/conftest.py`; `python scripts/slow_tests.py` measures every test again and rewrites the list (about two and a half minutes). The slowest fixture, the fake station's 18-month archive (`archived_cache` in `tests/conftest.py`), diff --git a/pytest.ini b/pytest.ini index c38ecf35..f3887d2a 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,7 +1,8 @@ [pytest] asyncio_mode = auto testpaths = tests -# run in parallel, each worker taking the next test as it frees up (pytest-xdist 3.2+, see requirements-dev.txt); `pytest -n0` runs in one process +# run in parallel, each worker taking the next test as it frees up (pytest-xdist 3.2+, see requirements-dev.txt); `pytest -n0` runs in one process; +# `auto`: one and a half workers a CPU (tests/conftest.py: the browser tests mostly wait), the browser tests dealt out first # plain `pytest` leaves out the slow tests (tests/slow_tests.txt, scripts/slow_tests.py): `pytest -m slow` runs them, `pytest -m ""` all addopts = -n auto --dist worksteal -m "not slow" # a test that hangs fails after 60 s with every thread's stack (pytest-timeout), rather than hold the run up until it is killed diff --git a/tests/conftest.py b/tests/conftest.py index 5fe0c254..ba0da703 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -24,11 +24,61 @@ @pytest.hookimpl(tryfirst=True) # (before -m deselects by the marks) def pytest_collection_modifyitems(items): """The slow tests (tests/slow_tests.txt, every parameter of one) marked `slow`: plain `pytest` leaves them out (pytest.ini). Then the - files with the slowest tests go first, so with several workers (pytest-xdist) none is left running one of them at the end.""" + files with the slowest tests go first, so with several workers (pytest-xdist) none is left running one of them at the end; and the + browser's (BROWSER) dealt out ahead of them, one at the head of each worker's share.""" for item in items: if item.nodeid.split("[")[0] in SLOW: item.add_marker(pytest.mark.slow) items.sort(key=lambda item: (item.path.name not in HEAVY, HEAVY.index(item.path.name) if item.path.name in HEAVY else 0)) + deal_out(items, [item for item in items if browser_test(item)]) + + +def pytest_xdist_auto_num_workers(config): + """`-n auto` (pytest.ini): half as many workers again as there are CPUs. The browser's tests mostly wait on the page (its + animations, a long press, a swipe's end), so a worker in one leaves its CPU mostly free for the extra workers' tests.""" + return max(2, (os.cpu_count() or 1) * 3 // 2) + + +BROWSER = "test_web_dashboard.py" # its slow tests drive the page in Chromium: seconds each, mostly waiting on the page + + +def browser_test(item) -> bool: + return item.path.name == BROWSER and item.nodeid.split("[")[0] in SLOW + + +_niced = False + + +def pytest_runtest_setup(item): + """With several workers, a worker done with its browser tests (dealt out first) runs the rest at a lower priority (nice 10, for + good: a process can't raise its own again), so the pages still being driven, whose tests time their animations frame by frame, + get a CPU when they ask while the others keep every CPU busy. The run takes as long; only who waits changes.""" + global _niced + if not _niced and not browser_test(item) and os.environ.get("PYTEST_XDIST_WORKER") and hasattr(os, "nice"): + os.nice(10) + _niced = True + + +def deal_out(items: list, first: list) -> None: + """`first` dealt out across the workers (as many as there are CPUs), one at the head of each worker's share of the run in turn, the + rest after them: so they start together, each on its own worker, rather than queue on one. (pytest-xdist's worksteal gives each worker a run of the list + as it starts, the first len // workers to the first and so on, and a worker with nothing left takes from the end of another's.)""" + workers = int(os.environ.get("PYTEST_XDIST_WORKER_COUNT", "0")) # (set in each worker; all of them collect the same order) + if workers < 2 or not first: + return + taken = set(map(id, first)) + rest = [item for item in items if id(item) not in taken] + shares, left = [], len(items) + for w in range(workers): # (each share's length, as worksteal cuts them) + shares.append(left // (workers - w)) + left -= shares[-1] + browsers = min(workers, os.cpu_count() or 1) # (no more pages driven at once than there are CPUs: their timings stay true) + heads = [first[w::browsers] for w in range(browsers)] + [[]] * (workers - browsers) + out = [] + for size, head in zip(shares, heads): + out += head + rest[:size - len(head)] + rest = rest[size - len(head):] + items[:] = out + rest @pytest.fixture(autouse=True) diff --git a/tests/slow_tests.txt b/tests/slow_tests.txt index c3a2553c..39e127f0 100644 --- a/tests/slow_tests.txt +++ b/tests/slow_tests.txt @@ -56,11 +56,19 @@ tests/test_startup.py::test_a_failed_first_refresh_does_not_stop_the_alerts_or_t tests/test_startup.py::test_ecobot_mcp_starts_warms_archives_and_shuts_down_cleanly tests/test_startup.py::test_main_starts_as_ecobot_mcps_client_and_shuts_down_cleanly tests/test_startup.py::test_the_weather_alerts_that_could_not_start_are_named_as_not_running -tests/test_web_dashboard.py::test_a_click_on_a_gauge_zooms_its_tile_and_the_gallery_pages_by_keys_drags_and_swipes_stopping_at_both_ends +tests/test_web_dashboard.py::test_a_click_on_a_gauge_zooms_its_tile_to_fill_the_window_the_tile_beside_it_live_and_the_keys_page +tests/test_web_dashboard.py::test_a_double_click_esc_the_bounce_cut_short_the_keyboard_and_esc_mid_zoom_and_one_tile_no_zoom tests/test_web_dashboard.py::test_a_tile_with_no_reading_is_dimmed_at_its_floor_and_a_reading_coming_brightens_it_and_moves_it_up_in_place +tests/test_web_dashboard.py::test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_reduced_motion +tests/test_web_dashboard.py::test_every_effect_at_once_is_cheap_no_brighter_than_the_strongest_alone_and_within_the_particle_budget tests/test_web_dashboard.py::test_fewer_tiles_grow_evenly_to_fill_the_window_and_never_shrink_below_the_full_dashboards_size tests/test_web_dashboard.py::test_on_a_touch_screen_a_long_press_picks_a_tile_up_and_a_tap_or_a_swipe_is_left_alone tests/test_web_dashboard.py::test_on_a_touch_screen_a_tap_zooms_a_swipe_pages_from_anywhere_and_a_tap_goes_back_where_the_page_was +tests/test_web_dashboard.py::test_several_effects_share_one_canvas_behind_the_see_through_tiles_zoomed_too tests/test_web_dashboard.py::test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error -tests/test_web_dashboard.py::test_the_weather_behind_the_tiles_comes_with_its_reading_frames_its_tile_in_red_and_can_be_stopped +tests/test_web_dashboard.py::test_the_temporary_test_links_turn_each_effect_on_and_clear_them_the_url_following +tests/test_web_dashboard.py::test_the_weather_behind_the_tiles_comes_with_its_reading_at_its_mark_and_frames_its_tile_in_red +tests/test_web_dashboard.py::test_the_weather_can_be_stopped_kept_stopped_across_a_reload_and_started_again_or_reset tests/test_web_dashboard.py::test_tiles_are_dragged_to_reorder_hidden_by_the_x_or_the_remove_zone_kept_across_reloads_and_reset +tests/test_web_dashboard.py::test_zoomed_the_gallery_pages_by_mouse_drags_and_a_trackpads_swipes_springing_back_at_the_first +tests/test_web_dashboard.py::test_zoomed_the_last_tile_stops_a_key_a_swipe_and_a_drag_its_text_is_selectable_and_a_click_goes_back diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 76ab20a3..e7805023 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -12,6 +12,7 @@ import asyncio import base64 +import functools import html import io import json @@ -333,15 +334,26 @@ def test_mcp_dashboard_is_read_as_on_or_off(monkeypatch, tmp_path): "desktop": (1920, 1080)} +@functools.cache def browser_there() -> bool: if not shutil.which("node"): return False return subprocess.run(["node", "-e", "require('playwright')"], capture_output=True, timeout=60).returncode == 0 -async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error(server, station, tmp_path): - if not browser_there(): # (asked here, by the one worker that runs it, not by every worker as it collects the tests) +@pytest.fixture +def chromium(): + """Skips the test without node and Playwright's Chromium: asked as a test runs, once in a worker (not as every worker collects the + tests: a node each, a third of a second).""" + if not browser_there(): pytest.skip("needs node with Playwright's Chromium") + + +needs_browser = pytest.mark.usefixtures("chromium") + + +@needs_browser +async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error(server, station, tmp_path): shots = Path(os.getenv("ECOBOT_SCREENSHOTS") or tmp_path) shots.mkdir(parents=True, exist_ok=True) port = free_port() @@ -385,7 +397,7 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl assert after["same_tile"] and "21.5 °C" in after["shown"], after # the gauge moved in place to the new reading -@pytest.mark.skipif(not browser_there(), reason="needs node with Playwright's Chromium") +@needs_browser @pytest.mark.parametrize("comes", [True, False]) async def test_a_tile_with_no_reading_is_dimmed_at_its_floor_and_a_reading_coming_brightens_it_and_moves_it_up_in_place(server, station, comes): @@ -476,7 +488,7 @@ def moved(titles, title, after): return out -@pytest.mark.skipif(not browser_there(), reason="needs node with Playwright's Chromium") +@needs_browser async def test_tiles_are_dragged_to_reorder_hidden_by_the_x_or_the_remove_zone_kept_across_reloads_and_reset(server, station): got = await run_page(server, "--arrange") default = titles_of(station) @@ -524,7 +536,7 @@ async def test_tiles_are_dragged_to_reorder_hidden_by_the_x_or_the_remove_zone_k assert got["hoverFrames"] == ["rgba(0, 0, 0, 0)", "rgb(38, 46, 52)", "rgba(0, 0, 0, 0)"], got["hoverFrames"] -@pytest.mark.skipif(not browser_there(), reason="needs node with Playwright's Chromium") +@needs_browser async def test_on_a_touch_screen_a_long_press_picks_a_tile_up_and_a_tap_or_a_swipe_is_left_alone(server, station): got = await run_page(server, "--touch") default = titles_of(station) @@ -546,7 +558,7 @@ async def test_on_a_touch_screen_a_long_press_picks_a_tile_up_and_a_tap_or_a_swi assert edge["after"] <= edge["end"] + 1, edge -@pytest.mark.skipif(not browser_there(), reason="needs node with Playwright's Chromium") +@needs_browser async def test_fewer_tiles_grow_evenly_to_fill_the_window_and_never_shrink_below_the_full_dashboards_size(server, station): every = titles_of(station) but = lambda *keep: [t for t in every if t not in keep] @@ -606,11 +618,11 @@ def fills(zl, width, height): assert box["left"] - 1 <= r["left"] and r["right"] <= box["right"] + 1 and box["top"] - 1 <= r["top"] and r["bottom"] <= box["bottom"] + 1, (r, zl) -@pytest.mark.skipif(not browser_there(), reason="needs node with Playwright's Chromium") -async def test_a_click_on_a_gauge_zooms_its_tile_and_the_gallery_pages_by_keys_drags_and_swipes_stopping_at_both_ends(server, station): +@needs_browser +async def test_a_click_on_a_gauge_zooms_its_tile_to_fill_the_window_the_tile_beside_it_live_and_the_keys_page(server, station): port = free_port() async with Serving(http_app(server, tokens=(TOKEN,)), port): - page = await asyncio.create_subprocess_exec("node", str(BROWSER), f"http://127.0.0.1:{port}/dashboard", "--zoom", stdin=subprocess.PIPE, + page = await asyncio.create_subprocess_exec("node", str(BROWSER), f"http://127.0.0.1:{port}/dashboard", "--zoom", "in", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) before = json.loads(await asyncio.wait_for(page.stdout.readline(), 60)) station.reads("outdoor", "temperature", "21.5") # Temperature: beside the tile shown, off the screen @@ -653,6 +665,20 @@ async def test_a_click_on_a_gauge_zooms_its_tile_and_the_gallery_pages_by_keys_d assert [keys[k]["shown"] for k in ("space", "right", "backspace")] == default[1:3] + default[1:2], keys assert all(k["zoomed"] for k in keys.values() if isinstance(k, dict)) and keys["url"] # (Backspace: still this page) assert keys["prevented"] == [["ArrowLeft", True], ["ArrowLeft", True], [" ", True], ["ArrowRight", True], ["Backspace", True]], keys + + +async def zoomed(server, station, part: str) -> tuple[dict, list[str], dict]: + """A part of the zoom at 1024x768 (its own page in its own browser: the parts run side by side): its report, no error; the tiles' + titles; a tile's rect zoomed.""" + got = await run_page(server, "--zoom", part) + default = titles_of(station) + assert got["errors"] == [] and got["initial"] == default, got["errors"] + return got, default, zoomed_rect(1024, 768) + + +@needs_browser +async def test_zoomed_the_gallery_pages_by_mouse_drags_and_a_trackpads_swipes_springing_back_at_the_first(server, station): + got, default, full = await zoomed(server, station, "pager") # mouse drags on the gauge: followed directly; let go past halfway, the next; a short slow one back; a quick short flick on drag = got["drag"] assert drag["start"]["shown"] == default[1] @@ -666,6 +692,11 @@ async def test_a_click_on_a_gauge_zooms_its_tile_and_the_gallery_pages_by_keys_d wheel = got["wheel"] assert [wheel[k]["shown"] for k in ("far", "short", "back")] == [default[1], default[1], default[0]], wheel assert wheel["prevented"] and all(wheel["prevented"]), wheel + + +@needs_browser +async def test_zoomed_the_last_tile_stops_a_key_a_swipe_and_a_drag_its_text_is_selectable_and_a_click_goes_back(server, station): + got, default, full = await zoomed(server, station, "last") # the last: → past it nudges and stays, as do a swipe and a drag on last = got["last"] assert last["reached"]["shown"] == default[-1] and last["pastLast"]["shown"] == default[-1] and last["pastLast"]["extreme"] >= 20, last @@ -684,6 +715,11 @@ async def test_a_click_on_a_gauge_zooms_its_tile_and_the_gallery_pages_by_keys_d assert zoom_out["last"]["width"] == pytest.approx(got["gridRect"]["width"], abs=0.5) tables = zoom_out["tables"] # (its table back: hidden as it shrinks, then fading in) assert tables[0] == 0 and tables[-1] == 1 and all(a <= b for a, b in zip(tables, tables[1:])) and got["outTable"] == ["visible 1"], (tables, got["outTable"]) + + +@needs_browser +async def test_a_double_click_esc_the_bounce_cut_short_the_keyboard_and_esc_mid_zoom_and_one_tile_no_zoom(server, station): + got, default, full = await zoomed(server, station, "out") # Esc: back too, the order as it was assert got["esc"]["before"]["zoomed"] and got["esc"]["before"]["shown"] == "Wind" and not got["esc"]["after"]["zoomed"] assert got["esc"]["titles"] == default @@ -714,7 +750,7 @@ async def test_a_click_on_a_gauge_zooms_its_tile_and_the_gallery_pages_by_keys_d assert got["single"] == {"cursor": "auto", "zoomed": False} -@pytest.mark.skipif(not browser_there(), reason="needs node with Playwright's Chromium") +@needs_browser async def test_on_a_touch_screen_a_tap_zooms_a_swipe_pages_from_anywhere_and_a_tap_goes_back_where_the_page_was(server, station): got = await run_page(server, "--zoom-touch") default = titles_of(station) @@ -737,10 +773,16 @@ async def test_on_a_touch_screen_a_tap_zooms_a_swipe_pages_from_anywhere_and_a_t "ice": "Temperature"} -@pytest.mark.skipif(not browser_there(), reason="needs node with Playwright's Chromium") -async def test_the_weather_behind_the_tiles_comes_with_its_reading_frames_its_tile_in_red_and_can_be_stopped(server, station): - got = await run_page(server, "--weather", timeout=180) +async def weather(server, part: str) -> dict: + """One part of the weather behind the tiles, its own page in its own browser (the parts run side by side): its report, no error.""" + got = await run_page(server, "--weather", part) assert got["errors"] == [], got["errors"] + return got + + +@needs_browser +async def test_the_weather_behind_the_tiles_comes_with_its_reading_at_its_mark_and_frames_its_tile_in_red(server, station): + got = await weather(server, "marks") # nothing called for (the US AQI Good): no effect, no frame, no link, no loop, nothing drawn assert got["nothing"] == {"effects": [], "levels": {k: 0 for k in got["nothing"]["levels"]}, "running": False, "framed": [], "link": None, "frames": 0, "ink": 0} @@ -755,6 +797,11 @@ async def test_the_weather_behind_the_tiles_comes_with_its_reading_frames_its_ti assert got["smogBands"] == [2, 3, 4, 5, 5] # thicker with each band: USG to Hazardous assert got["rainStrength"][0] < 0.4 and got["rainStrength"][1:] == [1, 1] # light at 0.5 mm/h, heavy from 8 assert got["iceDepth"] == [0.5, 5] # further in the colder + + +@needs_browser +async def test_several_effects_share_one_canvas_behind_the_see_through_tiles_zoomed_too(server, station): + got = await weather(server, "several") # several at once: one canvas, one loop, at most 30 frames drawn a second several = got["several"] assert several["effects"] == ["smog", "uv", "rain", "wind", "humidity", "ice"] and several["canvases"] == 1, several @@ -771,14 +818,24 @@ async def test_the_weather_behind_the_tiles_comes_with_its_reading_frames_its_ti "dragFrames": {"lifted": "rgb(90, 102, 112)", "doomed": "rgb(229, 72, 77)", "after": "rgba(0, 0, 0, 0)"}} assert got["zoomed"] == {"zoomed": True, "title": "UV index", "background": "rgba(0, 0, 0, 0)", "grid": "rgba(0, 0, 0, 0)", "alert": True, "running": True} + + +@needs_browser +async def test_the_weather_can_be_stopped_kept_stopped_across_a_reload_and_started_again_or_reset(server, station): + got = await weather(server, "stop") # "stop animations": nothing drawn, no loop, the frame stays, kept across a reload; "start animations" and the reset put them back assert got["stopped"] | {"levels": None} == {"effects": ["uv"], "levels": None, "running": False, "framed": ["UV index"], "link": "start animations", "frames": 0, "ink": 0, "stored": False}, got["stopped"] assert got["reloaded"]["link"] == "start animations" and got["reloaded"]["frames"] == 0 and not got["reloaded"]["running"] for step in ("restarted", "reset"): assert got[step]["link"] == "stop animations" and got[step]["running"] and got[step]["frames"] > 10, (step, got[step]) + + +@needs_browser +async def test_the_temporary_test_links_turn_each_effect_on_and_clear_them_the_url_following(server, station): + got = await weather(server, "links") # the temporary test links: each its effect and frame (the gauges keep their readings), the URL following; smog steps through its - # bands, rain light then heavy; ice melts back; "clear" ends them all; no "all" link, but ?fx=all, and ?fx= when the page opens + # bands, rain light then heavy; ice melts back; "clear" ends them all; no "all" link, but ?fx=all links = got["links"] assert links["buttons"] == ["rain", "smog", "uv", "humidity", "wind", "heat", "ice", "clear"], links["buttons"] on = [] @@ -792,31 +849,44 @@ async def test_the_weather_behind_the_tiles_comes_with_its_reading_frames_its_ti assert melting["grown"] > 2 and 0 < melting["reach"] < melting["grown"] and "ice" not in melting["effects"] and melting["running"], melting assert links["cleared"] | {"levels": None, "running": None} == {"effects": [], "levels": None, "running": None, "framed": [], "link": None, "url": ""} - every = ["smog", "heat", "uv", "rain", "wind", "humidity", "ice"] - assert links["all"]["effects"] == every and links["all"]["url"] == "?fx=rain2,smog3,uv,humidity,wind,heat,ice" + assert links["all"]["effects"] == EVERY and links["all"]["url"] == "?fx=rain2,smog3,uv,humidity,wind,heat,ice" + assert links["role"] == "group" and links["pressed"] == {"rain": "false", "smog": "false", "uv": "true", "humidity": "true", + "wind": "true", "heat": "true", "ice": "false"}, links["pressed"] + + +EVERY = ["smog", "heat", "uv", "rain", "wind", "humidity", "ice"] + + +@needs_browser +async def test_every_effect_at_once_is_cheap_no_brighter_than_the_strongest_alone_and_within_the_particle_budget(server, station): + got = await weather(server, "all") + assert got["cost"] < 8, got["cost"] + # several at once no brighter than one strong one: every effect on (the ice grown all the way in), against Hazardous smog alone + assert 0 < got["light"]["all"] <= got["light"]["smog5"], got["light"] + together = got["particles"]["all"] + assert together["uv"] == 0 and together["wind"] > 0 and together["rain"] > 0, together + assert sum(v for k, v in together.items() if k != "budget") <= together["budget"] + 3, together # (each rounded) + + +@needs_browser +async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_reduced_motion(server, station): + got = await weather(server, "opened") + # ?fx= when the page opens assert got["param"]["levels"] == {"smog": 3, "heat": 0, "uv": 0, "rain": 0, "wind": 1, "humidity": 0, "ice": 5} assert sorted(got["param"]["framed"]) == ["Temperature", "US AQI", "Wind"] and got["param"]["errors"] == [] # (the effects' earlier names, in links saved before, still work: as wind, uv, humidity) assert got["paramOld"]["effects"] == ["uv", "wind", "humidity"] and got["paramOld"]["errors"] == [], got["paramOld"] - assert links["role"] == "group" and links["pressed"] == {"rain": "false", "smog": "false", "uv": "true", "humidity": "true", - "wind": "true", "heat": "true", "ice": "false"}, links["pressed"] - # the particles: uv's beams none (no motes); the wind's leaves alone, and every effect's together, within the shared budget + assert got["paramAll"]["effects"] == EVERY and got["paramRain"]["levels"]["rain"] == 1 + # the particles: uv's beams none (no motes); the wind's leaves alone within the shared budget assert got["particles"]["uv"] == {"uv": 0, "budget": got["particles"]["uv"]["budget"]}, got["particles"] wind = got["particles"]["wind"] assert 0 < wind["wind"] <= wind["budget"], wind - together = got["particles"]["all"] - assert together["uv"] == 0 and together["wind"] > 0 and together["rain"] > 0, together - assert sum(v for k, v in together.items() if k != "budget") <= together["budget"] + 3, together # (each rounded) # the strip at the bottom right: its links, then the time at the far right; on a phone with both its links, the test row # beside it or above it, never over it phone = got["phone"] assert phone["strip"] == "reset preferences · stop animations · updated 18:42" and phone["right"], phone assert phone["apart"] and phone["onScreen"], phone - assert got["paramAll"]["effects"] == every and got["paramRain"]["levels"]["rain"] == 1 # reduced motion: no loop, one still, faint frame (the ice as it would be), the frames and the link as ever still = got["still"] assert still["effects"] == ["uv", "ice"] and not still["running"] and still["frames"] == 0 and still["stateFrames"] == 0, still assert still["ink"] > 0 and sorted(still["framed"]) == ["Temperature", "UV index"] and still["link"] == "stop animations", still - assert got["cost"] < 8, got["cost"] - # several at once no brighter than one strong one: every effect on, against Hazardous smog alone - assert 0 < got["light"]["all"] <= got["light"]["smog5"], got["light"] diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index b7d50f0d..8ddb4b22 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -14,16 +14,17 @@ // node web_dashboard_browser.js URL --touch: the page at 390x844 with touch (CDP touch events): a long press picks a tile up (buzz, // grip and ×, remove zone) and moves it; a short tap is a click; a swipe scrolls; held at the bottom edge it scrolls to the page's // end only; prints {step: what was seen}. -// node web_dashboard_browser.js URL --zoom: the page at 1024x768 with a mouse and keys: the zoom cursors, a click zooming a tile and -// back, Esc; zoomed, prints {label} (Temperature's, beside the tile shown), waits for a line on stdin (the test has changed its -// reading), then pages with the keys, mouse drags and wheel deltaX, past both ends, and drags across the text; prints {step: what -// was seen}; with a single tile, no zoom. +// node web_dashboard_browser.js URL --zoom PART: the page at 1024x768 with a mouse and keys, a part of the zoom (zoomMode): "in" (the +// zoom cursors, a click zooming a tile; zoomed, prints {label} (Temperature's, beside the tile shown), waits for a line on stdin (the +// test has changed its reading), then pages with the keys past the first), "pager" (mouse drags and wheel deltaX), "last" (past the +// last, drags across the text, a click back), "out" (a double-click, Esc, the bounce cut short, the keyboard, Esc mid-zoom, a single +// tile: no zoom); prints {step: what was seen}. // node web_dashboard_browser.js URL --zoom-touch: the page at 390x844 with touch: a tap zooms, swipes (slow, a flick, on the text) // page, a vertical swipe and a long press do nothing, a tap goes back where the page was scrolled; prints {step: what was seen}. -// node web_dashboard_browser.js URL --weather: the page at 1024x768, its data altered on the way (each reading at, and just short of, the -// mark that calls up its effect behind the tiles), the canvas behind the tiles, the tiles' red frames, "stop animations", reduced -// motion, no loop with nothing called for, the temporary test links and ?fx=, the frame time with every effect on; prints {step: what -// was seen}. +// node web_dashboard_browser.js URL --weather PART: the page at 1024x768, its data altered on the way, a part of the weather behind the +// tiles (WEATHER): each reading at, and just short of, the mark that calls up its effect; the canvas behind the tiles and the tiles' +// red frames; "stop animations"; the temporary test links; every effect at once (?fx=all: the frame time, the light, the particles); +// ?fx= as the page opens, a phone, reduced motion; prints {step: what was seen}. // node web_dashboard_browser.js URL --fill CASES: for each case {name: [width, height, hidden titles]}, the page with those hidden; // prints {name: {rects, columns, scroll}}. "use strict"; @@ -45,10 +46,10 @@ async function open(browser, url, width, height, options = {}) { async function sizes(browser, url, shots, wanted) { const report = {}; - for (const [name, [width, height]] of Object.entries(wanted)) { + await Promise.all(Object.entries(wanted).map(async ([name, [width, height]]) => { // (side by side, a page each) const { context, page, errors } = await open(browser, url, width, height); await page.evaluate(() => document.fonts.ready); - await page.waitForTimeout(1200); // (the gauges' rise from their floor when the page opens, RISE_MS) + await calm(page, 5000); // (the gauges' rise from their floor when the page opens, RISE_MS) await page.screenshot({ path: `${shots}/dashboard-${name}.png`, fullPage: true }); report[name] = { ...await page.evaluate(() => ({ tiles: document.querySelectorAll(".tile").length, @@ -62,7 +63,7 @@ async function sizes(browser, url, shots, wanted) { // zoomed (Enter on the first tile): its look (box, title, text, table) and a screenshot (SHOTS/dashboard-NAME-zoomed.png) await page.focus(".tile"); await page.keyboard.press("Enter"); - await page.waitForTimeout(400); + await calm(page, 400); await page.screenshot({ path: `${shots}/dashboard-${name}-zoomed.png` }); report[name].zoomed = await page.evaluate(() => { const t = document.querySelector("#grid .tile"), rect = (e) => e.getBoundingClientRect().toJSON(); @@ -72,8 +73,8 @@ async function sizes(browser, url, shots, wanted) { table: [...new Set(table.map((c) => `${c.visibility} ${c.opacity}`))] }; }); await context.close(); - } - process.stdout.write(JSON.stringify(report)); + })); + process.stdout.write(JSON.stringify(Object.fromEntries(Object.keys(wanted).map((name) => [name, report[name]])))); } async function live(browser, url) { @@ -130,7 +131,22 @@ async function arrive(browser, url, title) { const KEY = "ecobot.dashboard.v1"; const titles = (page) => page.evaluate(() => [...document.querySelectorAll("#grid .tile .title")].map((t) => t.textContent)); const tileOf = (page, title) => page.locator(".tile", { has: page.locator(".title", { hasText: new RegExp(`^${title}$`) }) }); -const settle = (page) => page.waitForTimeout(350); // (the reflow's easing, 220 ms) +// The page at rest, rather than a fixed wait: nothing in its document changed (a gauge's needle, a tile's transform, a class) for 50 ms +// and no animation or transition running (an endless one aside); at most `cap` ms: the fixed wait it stands for where that was a margin, +// longer for the gauges' rise and moves (which the frames counted after them must not include, however slow the machine is just then). +// (Not for what a timer starts later, a long press or a swipe's end: a wait for that.) +const calm = (page, cap = 450) => page.evaluate((cap) => new Promise((resolve) => { + const start = performance.now(); + let changed = start; + const seen = new MutationObserver(() => { changed = performance.now(); }); + seen.observe(document.documentElement, { subtree: true, attributes: true, childList: true, characterData: true }); + const moving = () => document.getAnimations().some((a) => a.playState === "running" && a.effect.getComputedTiming().endTime !== Infinity); + const check = (now) => { + if (moving()) changed = Math.max(changed, now); + if (performance.now() - changed >= 50 || now - start >= cap) { seen.disconnect(); resolve(); } else requestAnimationFrame(check); + }; + requestAnimationFrame(check); +}), cap); async function at(page, title, fx, fy) { // a point of a tile, as fractions of it const r = await tileOf(page, title).boundingBox(); @@ -144,10 +160,10 @@ async function mouseDrag(page, [x0, y0], [x1, y1], during) { await page.mouse.move(x0, y0); await page.mouse.down(); for (let i = 1; i <= 12; i++) await page.mouse.move(x0 + (x1 - x0) * i / 12, y0 + (y1 - y0) * i / 12); - await page.waitForTimeout(300); + await calm(page); // (the others made room) const seen = during ? await during() : null; await page.mouse.up(); - await settle(page); + await calm(page); return seen; } const selection = (page) => page.evaluate(() => { const s = String(window.getSelection()); window.getSelection().removeAllRanges(); return s; }); @@ -162,7 +178,7 @@ const midDrag = (page) => page.evaluate(() => ({ async function arrangeMode(browser, url) { const out = {}; const { context, page, errors } = await open(browser, url, 1024, 768); - await page.waitForTimeout(1200); + await calm(page, 5000); // (the gauges' rise) out.initial = await titles(page); // the look: the tile's own background clear, its foreground opaque out.look = await page.evaluate(() => { @@ -174,7 +190,7 @@ async function arrangeMode(browser, url) { }); // mouseover: the grip and the × show on the tile under the mouse only await page.mouse.move(...await at(page, "Humidity", 0.5, 0.4)); - await page.waitForTimeout(300); + await calm(page); // mouseover: the frame too, on the tile under the mouse only (unseen otherwise) out.hoverFrames = await page.evaluate(() => [...document.querySelectorAll(".tile")].slice(0, 3).map((t) => getComputedStyle(t, "::before").borderTopColor)); out.hover = await page.evaluate(() => [...document.querySelectorAll(".tile")].slice(0, 3).map((t) => ({ @@ -195,9 +211,9 @@ async function arrangeMode(browser, url) { } // the ×: Rain hidden, the reset link shown await page.mouse.move(...await at(page, "Rain", 0.5, 0.4)); - await page.waitForTimeout(250); + await calm(page); await tileOf(page, "Rain").locator(".close").click(); - await settle(page); + await calm(page); out.closed = { titles: await titles(page), status: await statusText(page) }; // dropped on the remove zone: Wind hidden out.removing = await mouseDrag(page, await at(page, "Wind", 0.5, 0.3), [500, 20], () => midDrag(page)); @@ -205,11 +221,11 @@ async function arrangeMode(browser, url) { // reloaded: the same order and hidden tiles await page.reload({ waitUntil: "load" }); await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0); - await page.waitForTimeout(300); + await calm(page, 300); out.reloaded = { titles: await titles(page), status: await statusText(page) }; // reset: every tile back in the default order, the link gone, nothing kept await page.getByText("reset preferences").click(); - await settle(page); + await calm(page); out.reset = { titles: await titles(page), status: await statusText(page), stored: await stored(page) }; // preferences corrupt: the defaults; a tile new to the saved order: in its usual place (after the tile before it by default) await page.evaluate((key) => localStorage.setItem(key, "{not json"), KEY); @@ -230,20 +246,20 @@ async function arrangeMode(browser, url) { await page.mouse.up(); await page.waitForTimeout(150); await page.mouse.click(...await at(page, "Wind", 0.5, 0.3)); - await settle(page); + await calm(page); out.clickAfterDrop = await page.evaluate(() => window.__clicks); out.zoomedAfterDrop = await page.evaluate(() => document.body.classList.contains("zoomed")); // (that click zoomed Wind: back) await page.keyboard.press("Escape"); - await settle(page); + await calm(page); out.keptOthers = JSON.parse(await stored(page)); // the × pressed from the keyboard: the focus goes on to the next tile's ×; with the last tile hidden, to the reset link - await settle(page); + await calm(page); await page.keyboard.press("Shift"); // (the keyboard in use: the first tile's × focused as by the keyboard) await page.evaluate(() => document.querySelector(".close").focus()); const focused = () => page.evaluate(() => document.activeElement.getAttribute("aria-label") || document.activeElement.textContent); out.keyboardHide = [await focused()]; await page.keyboard.press("Enter"); - await settle(page); + await calm(page); out.keyboardHide.push(await focused()); const allBut = out.initial.filter((t) => t !== "Rain"); await page.evaluate(([key, hidden]) => localStorage.setItem(key, JSON.stringify({ order: [], hidden })), [KEY, allBut]); @@ -254,7 +270,7 @@ async function arrangeMode(browser, url) { await page.keyboard.press("Tab"); out.keyboardHide.push(await focused()); await page.keyboard.press("Enter"); - await settle(page); + await calm(page); out.keyboardHide.push(await focused()); out.errors = errors; await context.close(); @@ -262,12 +278,12 @@ async function arrangeMode(browser, url) { const blocked = await open(browser, url, 1024, 768, { init: { fn: () => { Object.defineProperty(window, "localStorage", { get() { throw new DOMException("blocked", "SecurityError"); } }); } } }); - await blocked.page.waitForTimeout(300); + await calm(blocked.page, 300); await mouseDrag(blocked.page, await at(blocked.page, "Temperature", 0.85, 0.3), await at(blocked.page, "Humidity", 0.5, 0.4)); await blocked.page.mouse.move(...await at(blocked.page, "Rain", 0.5, 0.4)); - await blocked.page.waitForTimeout(250); + await calm(blocked.page); await tileOf(blocked.page, "Rain").locator(".close").click(); - await settle(blocked.page); + await calm(blocked.page); out.blocked = { titles: await titles(blocked.page), errors: blocked.errors }; await blocked.context.close(); process.stdout.write(JSON.stringify(out)); @@ -293,7 +309,7 @@ async function touchMode(browser, url) { armed: [...document.querySelectorAll(".tile.armed")].map((t) => t.querySelector(".title").textContent), close: (() => { const c = document.querySelector(".tile.armed .close"); return c ? getComputedStyle(c).opacity : null; })(), })); - await page.waitForTimeout(1200); + await calm(page, 5000); // (the gauges' rise) out.initial = await titles(page); // a short tap: a click, nothing picked up const t0 = await at(page, "Temperature", 0.85, 0.3); @@ -303,7 +319,7 @@ async function touchMode(browser, url) { await page.waitForTimeout(600); out.tap = { ...await state(), titles: await titles(page), zoomed: await page.evaluate(() => document.body.classList.contains("zoomed")) }; await page.keyboard.press("Escape"); // (the tap zoomed the tile: back) - await page.waitForTimeout(400); + await calm(page, 400); // a swipe up before the long press: the page scrolls, nothing picked up const s0 = await at(page, "Humidity", 0.5, 0.3); await touch("touchStart", [s0]); @@ -319,23 +335,23 @@ async function touchMode(browser, url) { await page.waitForTimeout(700); out.held = await state(); for (let i = 1; i <= 12; i++) { await touch("touchMove", [[p0[0] + (p1[0] - p0[0]) * i / 12, p0[1] + (p1[1] - p0[1]) * i / 12]]); await page.waitForTimeout(16); } - await page.waitForTimeout(300); + await calm(page, 300); // (the others made room) out.moving = { ...await state(), during: await midDrag(page) }; await touch("touchEnd", []); - await settle(page); + await calm(page); out.dropped = { ...await state(), titles: await titles(page) }; // a long press let go in place: its grip and × stay; a tap on the × hides it const h0 = await at(page, "Humidity", 0.85, 0.3); await touch("touchStart", [h0]); await page.waitForTimeout(700); await touch("touchEnd", []); - await page.waitForTimeout(300); + await calm(page, 300); out.armed = await state(); const c = await centreOf(page, tileOf(page, "Humidity").locator(".close")); await touch("touchStart", [c]); await page.waitForTimeout(50); await touch("touchEnd", []); - await settle(page); + await calm(page); out.closed = { titles: await titles(page), status: await statusText(page) }; // held near the bottom edge: the page scrolls to its end and no further (the lifted tile mustn't stretch it without end) await page.evaluate(() => window.scrollTo(0, 0)); @@ -348,7 +364,7 @@ async function touchMode(browser, url) { const seen = []; for (let i = 0; i < 12; i++) { await page.waitForTimeout(250); seen.push(await page.evaluate(() => window.scrollY)); } await touch("touchEnd", []); - await settle(page); + await calm(page); out.edge = { end, seen, after: await page.evaluate(() => window.scrollY) }; out.errors = errors; await context.close(); @@ -404,7 +420,7 @@ function motion(rec, key) { extreme: key[0] === "x" ? Math.max(...after.map((x) => Math.abs(x.x - last.x))) : null }; } async function zoomClick(page, title, point) { // a click, the tile's rect recorded through the zoom - const recording = page.evaluate((title) => window.__record(title, 500), title); + const recording = page.evaluate((title) => window.__record(title, 700), title); // (to the table's fade back in, after the zoom out) await page.waitForTimeout(50); await page.mouse.click(...point); const rec = await recording; @@ -428,184 +444,201 @@ async function pagerDrag(page, [x0, y], dx, { steps = 12, pause = 300 } = {}) { const during = await page.evaluate(() => window.__track()); await page.waitForTimeout(pause); await page.mouse.up(); - await page.waitForTimeout(450); + await calm(page); return { during: Math.round(during), ...await page.evaluate(() => window.__state()) }; } +// a trackpad's swipe over (no wheel event for WHEEL_IDLE_MS, then the strip settling), at rest +const swiped = async (page) => { await page.waitForTimeout(160); await calm(page); }; const cursorAt = (page, [x, y]) => page.evaluate(([x, y]) => getComputedStyle(document.elementFromPoint(x, y)).cursor, [x, y]); -async function zoomMode(browser, url) { +// The zoom in four parts, each its own page (and process: the tests run them side by side): "in" (the cursors, a click zooming a +// tile, the live reading beside it, the keys), "pager" (zoomed: mouse drags, a trackpad's swipes), "last" (zoomed: the last tile, a +// drag across the text, a click back out), "out" (a double-click, Esc, the bounce cut short, the keyboard, Esc mid-way through a +// zoom-in, a single tile) +async function zoomMode(browser, url, part) { const out = {}; const { context, page, errors } = await open(browser, url, 1024, 768, { init: { fn: ZOOM_HELPERS } }); - await page.waitForTimeout(1200); + await calm(page, 5000); // (the gauges' rise) out.initial = await titles(page); out.gridRect = (await tileOf(page, "Humidity").boundingBox()); - const textPoint = async (title, selector) => centreOf(page, tileOf(page, title).locator(selector).first()); - out.cursor = { gauge: await cursorAt(page, await at(page, "Humidity", 0.85, 0.3)), title: await cursorAt(page, await textPoint("Humidity", ".title")), - figure: await cursorAt(page, await textPoint("Humidity", ".figure")), reading: await cursorAt(page, await textPoint("Humidity", "svg text.reading")) }; - // a click on Humidity's gauge: zoomed, in 200 ms, to fill the window - out.zoomIn = await zoomClick(page, "Humidity", await at(page, "Humidity", 0.85, 0.3)); - out.zoomedCursor = { gauge: await cursorAt(page, await at(page, "Humidity", 0.85, 0.3)), margin: await cursorAt(page, [20, 384]), - title: await cursorAt(page, await textPoint("Humidity", ".title")) }; - out.grip = await page.evaluate(() => getComputedStyle(window.__tile("Humidity").querySelector(".close")).display); - out.zoomedLook = await page.evaluate(() => window.__look("Humidity")); // (its title and gauge filling the window, no table) - out.neighbourTable = await page.evaluate(() => window.__look("Temperature").table); // (the gallery's others: no table either) - // live: a new reading for Temperature, the tile beside it off the screen, reaches it in place - await page.evaluate(() => { window.__mark = window.__tile("Temperature"); }); - process.stdout.write(JSON.stringify({ label: await page.evaluate(() => window.__mark.getAttribute("aria-label")) }) + "\n"); - await new Promise((resolve) => readline.createInterface({ input: process.stdin }).once("line", resolve)); - try { await page.waitForFunction(() => /21\.5/.test(window.__mark.getAttribute("aria-label")), null, { timeout: 15000 }); } catch (e) { /* (reported) */ } - await page.waitForTimeout(1000); // (the gauge's move, MOVE_MS) - out.live = { label: await page.evaluate(() => window.__mark.getAttribute("aria-label")), sameTile: await page.evaluate(() => window.__mark === window.__tile("Temperature")), - ...await page.evaluate(() => window.__state()) }; - // the keys: ← to Temperature (now showing the new reading), ← again: the first, a bounce; Space, →, Backspace - out.keys = {}; - out.keys.left = await keyStep(page, "ArrowLeft"); - out.keys.leftReading = await page.evaluate(() => window.__mark.querySelector("svg text.reading").textContent); - out.keys.pastFirst = await keyStep(page, "ArrowLeft"); - out.keys.space = await keyStep(page, " "); - out.keys.right = await keyStep(page, "ArrowRight"); - out.keys.backspace = await keyStep(page, "Backspace"); - out.keys.url = page.url() === url; - out.keys.prevented = await page.evaluate(() => window.__keys); - // a mouse drag on the gauge: followed as it goes; let go past halfway: the next; a short slow one: back; a short quick one: the next - const gauge = () => at(page, "Humidity", 0.85, 0.3); - const g = await page.evaluate(() => window.__state()); - out.drag = { start: g }; - out.drag.far = await pagerDrag(page, [900, 300], -600); - out.drag.short = await pagerDrag(page, [800, 300], -100); - out.drag.flick = await pagerDrag(page, [800, 300], -120, { steps: 3, pause: 0 }); - out.drag.back = await pagerDrag(page, [200, 300], 600); - // the first tile, dragged on rightwards: it gives less and less, then springs back - await page.keyboard.press("ArrowLeft"); await page.keyboard.press("ArrowLeft"); - await page.waitForTimeout(500); - out.drag.pastFirst = await pagerDrag(page, [300, 300], 300); - // a trackpad's two-finger swipe: wheel deltaX, kept from the browser - await page.mouse.move(800, 300); - out.wheel = {}; - for (let i = 0; i < 8; i++) { await page.mouse.wheel(50, 0); await page.waitForTimeout(16); } - await page.waitForTimeout(500); - out.wheel.far = await page.evaluate(() => window.__state()); - for (let i = 0; i < 6; i++) { await page.mouse.wheel(10, 0); await page.waitForTimeout(60); } // (slowly: no flick) - await page.waitForTimeout(500); - out.wheel.short = await page.evaluate(() => window.__state()); - for (let i = 0; i < 8; i++) { await page.mouse.wheel(-50, 0); await page.waitForTimeout(16); } - await page.waitForTimeout(500); - out.wheel.back = await page.evaluate(() => window.__state()); - out.wheel.prevented = await page.evaluate(() => window.__wheels); - // the last tile: → past it bounces, as does a swipe on - const n = (await titles(page)).length; - for (let i = 0; i < n; i++) { await page.keyboard.press("ArrowRight"); await page.waitForTimeout(30); } - await page.waitForTimeout(500); - out.last = { reached: await page.evaluate(() => window.__state()), pastLast: await keyStep(page, "ArrowRight") }; - for (let i = 0; i < 8; i++) { await page.mouse.wheel(50, 0); await page.waitForTimeout(16); } - await page.waitForTimeout(500); - out.last.wheeled = await page.evaluate(() => window.__state()); - out.last.dragged = await pagerDrag(page, [800, 300], -400); - // a drag on the text selects it: no paging, still zoomed - const shown = out.last.reached.shown; - out.text = {}; - for (const [name, selector] of [["title", ".title"], ["reading", "svg text.reading"]]) { - const r = await tileOf(page, shown).locator(selector).first().boundingBox(), y = r.y + r.height / 2; - await mouseDrag(page, [r.x + 2, y], [r.x + r.width - 1, y + 1]); - out.text[name] = { selected: await selection(page), ...await page.evaluate(() => window.__state()) }; - } - // a click without moving on the gauge: back to the dashboard, in 200 ms, the tile in its place - out.zoomOut = await zoomClick(page, shown, await at(page, shown, 0.85, 0.3)); - out.outRect = await tileOf(page, shown).boundingBox(); - out.outTable = await page.evaluate((shown) => window.__look(shown).table, shown); // (its table back) - // a double-click (its clicks 300 ms apart, slower than the zoom): zoomed, not zoomed and straight back out - const wind = await at(page, "Wind", 0.85, 0.3); - await page.mouse.move(...wind); - await page.mouse.down(); await page.mouse.up(); - await page.waitForTimeout(300); - await page.mouse.down({ clickCount: 2 }); await page.mouse.up({ clickCount: 2 }); - await page.waitForTimeout(400); - // Esc: back too - out.esc = { before: await page.evaluate(() => window.__state()) }; - await page.keyboard.press("Escape"); - await page.waitForTimeout(400); - out.esc.after = await page.evaluate(() => window.__state()); - out.esc.titles = await titles(page); - // a click on the gauge doesn't take the focus: no × once the pointer has gone - await page.mouse.move(1020, 4); - await page.waitForTimeout(300); - out.esc.close = await page.evaluate(() => ({ focused: document.activeElement === window.__tile("Wind"), - opacity: getComputedStyle(window.__tile("Wind").querySelector(".close")).opacity })); - // the bounce at the last tile, cut short by Esc: the dashboard back in its place at once; or by a key: that step slides - const n2 = (await titles(page)).length; - await page.mouse.click(...await at(page, "Wind", 0.85, 0.3)); - await page.waitForTimeout(400); - for (let i = 0; i < n2; i++) { await page.keyboard.press("ArrowRight"); await page.waitForTimeout(30); } - await page.waitForTimeout(500); - await page.keyboard.press("ArrowRight"); // (past the last: the bounce) - await page.waitForTimeout(30); - const cut = page.evaluate(() => window.__record(null, 300)); - await page.keyboard.press("ArrowLeft"); - const rec = await cut; - const near100 = rec.frames.filter((f) => f.t >= rec.at + 90 && f.t <= rec.at + 130).map((f) => Math.round(f.x)); - await page.waitForTimeout(300); - out.bounceCut = { step: { mid: near100, ...await page.evaluate(() => window.__state()) } }; - await page.keyboard.press("ArrowRight"); await page.waitForTimeout(400); - await page.keyboard.press("ArrowRight"); // (the bounce again) - await page.waitForTimeout(30); - await page.keyboard.press("Escape"); - await page.waitForTimeout(60); - out.bounceCut.esc = await page.evaluate(() => ({ grid: getComputedStyle(document.getElementById("grid")).transform, - firstLeft: Math.round(document.querySelector("#grid .tile").getBoundingClientRect().left), - zoomed: document.body.classList.contains("zoomed") })); - await page.waitForTimeout(400); - // the keyboard: every tile takes the focus; Enter on one zooms it, the focus going along as it pages, the others out of reach; Esc - // back, the focus on the tile shown last; Space zooms too - const focusState = () => page.evaluate(() => ({ ...window.__state(), focus: document.activeElement.classList.contains("tile") ? document.activeElement.querySelector(".title").textContent : document.activeElement.tagName, - reachable: [...document.querySelectorAll("#grid .tile")].filter((t) => !t.inert).map((t) => t.querySelector(".title").textContent) })); - out.keyboard = { tabbable: await page.evaluate(() => [...document.querySelectorAll("#grid .tile")].every((t) => t.tabIndex === 0)) }; - await page.evaluate(() => window.__tile("Temperature").focus()); - await page.waitForTimeout(200); - out.keyboard.focusedClose = await page.evaluate(() => getComputedStyle(window.__tile("Temperature").querySelector(".close")).opacity); - await page.keyboard.press("Enter"); - await page.waitForTimeout(400); - out.keyboard.enter = await focusState(); - await page.keyboard.press("ArrowRight"); - await page.waitForTimeout(400); - out.keyboard.right = await focusState(); - await page.keyboard.press("Tab"); - out.keyboard.tab = await focusState(); - await page.evaluate(() => window.__tile("Humidity").focus()); - await page.keyboard.press("Escape"); - await page.waitForTimeout(400); - out.keyboard.esc = await focusState(); - await page.keyboard.press(" "); - await page.waitForTimeout(400); - out.keyboard.space = await focusState(); - await page.keyboard.press("Escape"); - await page.waitForTimeout(400); - // Esc 100 ms into a zoom-in: back from where the tile is drawn (no jump to the full size), its table hidden until it's in its grid place - // (never drawn large); the others keep their tables as they fade out, gone only once they're in the gallery - await page.waitForTimeout(300); - { - const recording = page.evaluate(() => window.__record("Humidity", 700)); - await page.waitForTimeout(50); + if (part === "in") { + const textPoint = async (title, selector) => centreOf(page, tileOf(page, title).locator(selector).first()); + out.cursor = { gauge: await cursorAt(page, await at(page, "Humidity", 0.85, 0.3)), title: await cursorAt(page, await textPoint("Humidity", ".title")), + figure: await cursorAt(page, await textPoint("Humidity", ".figure")), reading: await cursorAt(page, await textPoint("Humidity", "svg text.reading")) }; + // a click on Humidity's gauge: zoomed, in 200 ms, to fill the window + out.zoomIn = await zoomClick(page, "Humidity", await at(page, "Humidity", 0.85, 0.3)); + out.zoomedCursor = { gauge: await cursorAt(page, await at(page, "Humidity", 0.85, 0.3)), margin: await cursorAt(page, [20, 384]), + title: await cursorAt(page, await textPoint("Humidity", ".title")) }; + out.grip = await page.evaluate(() => getComputedStyle(window.__tile("Humidity").querySelector(".close")).display); + out.zoomedLook = await page.evaluate(() => window.__look("Humidity")); // (its title and gauge filling the window, no table) + out.neighbourTable = await page.evaluate(() => window.__look("Temperature").table); // (the gallery's others: no table either) + // live: a new reading for Temperature, the tile beside it off the screen, reaches it in place + await page.evaluate(() => { window.__mark = window.__tile("Temperature"); }); + process.stdout.write(JSON.stringify({ label: await page.evaluate(() => window.__mark.getAttribute("aria-label")) }) + "\n"); + await new Promise((resolve) => readline.createInterface({ input: process.stdin }).once("line", resolve)); + try { await page.waitForFunction(() => /21\.5/.test(window.__mark.getAttribute("aria-label")), null, { timeout: 15000 }); } catch (e) { /* (reported) */ } + await calm(page, 1000); // (the gauge's move, MOVE_MS) + out.live = { label: await page.evaluate(() => window.__mark.getAttribute("aria-label")), sameTile: await page.evaluate(() => window.__mark === window.__tile("Temperature")), + ...await page.evaluate(() => window.__state()) }; + // the keys: ← to Temperature (now showing the new reading), ← again: the first, a bounce; Space, →, Backspace + out.keys = {}; + out.keys.left = await keyStep(page, "ArrowLeft"); + out.keys.leftReading = await page.evaluate(() => window.__mark.querySelector("svg text.reading").textContent); + out.keys.pastFirst = await keyStep(page, "ArrowLeft"); + out.keys.space = await keyStep(page, " "); + out.keys.right = await keyStep(page, "ArrowRight"); + out.keys.backspace = await keyStep(page, "Backspace"); + out.keys.url = page.url() === url; + out.keys.prevented = await page.evaluate(() => window.__keys); + } else if (part === "pager") { + // zoomed on Humidity, by a click on its gauge + await page.mouse.click(...await at(page, "Humidity", 0.85, 0.3)); + await calm(page); + // a mouse drag on the gauge: followed as it goes; let go past halfway: the next; a short slow one: back; a short quick one: the next + const gauge = () => at(page, "Humidity", 0.85, 0.3); + const g = await page.evaluate(() => window.__state()); + out.drag = { start: g }; + out.drag.far = await pagerDrag(page, [900, 300], -600); + out.drag.short = await pagerDrag(page, [800, 300], -100); + out.drag.flick = await pagerDrag(page, [800, 300], -120, { steps: 3, pause: 0 }); + out.drag.back = await pagerDrag(page, [200, 300], 600); + // the first tile, dragged on rightwards: it gives less and less, then springs back + await page.keyboard.press("ArrowLeft"); await page.keyboard.press("ArrowLeft"); + await calm(page, 500); + out.drag.pastFirst = await pagerDrag(page, [300, 300], 300); + // a trackpad's two-finger swipe: wheel deltaX, kept from the browser + await page.mouse.move(800, 300); + out.wheel = {}; + for (let i = 0; i < 8; i++) { await page.mouse.wheel(50, 0); await page.waitForTimeout(16); } + await swiped(page); + out.wheel.far = await page.evaluate(() => window.__state()); + for (let i = 0; i < 6; i++) { await page.mouse.wheel(10, 0); await page.waitForTimeout(60); } // (slowly: no flick) + await swiped(page); + out.wheel.short = await page.evaluate(() => window.__state()); + for (let i = 0; i < 8; i++) { await page.mouse.wheel(-50, 0); await page.waitForTimeout(16); } + await swiped(page); + out.wheel.back = await page.evaluate(() => window.__state()); + out.wheel.prevented = await page.evaluate(() => window.__wheels); + } else if (part === "last") { + // zoomed on Humidity, by a click on its gauge await page.mouse.click(...await at(page, "Humidity", 0.85, 0.3)); + await calm(page); + // the last tile: → past it bounces, as does a swipe on + const n = (await titles(page)).length; + for (let i = 1; i < n; i++) { await page.keyboard.press("ArrowRight"); await page.waitForTimeout(30); } // (from the second: once past the last) + await calm(page, 500); + out.last = { reached: await page.evaluate(() => window.__state()), pastLast: await keyStep(page, "ArrowRight") }; + for (let i = 0; i < 8; i++) { await page.mouse.wheel(50, 0); await page.waitForTimeout(16); } + await swiped(page); + out.last.wheeled = await page.evaluate(() => window.__state()); + out.last.dragged = await pagerDrag(page, [800, 300], -400); + // a drag on the text selects it: no paging, still zoomed + const shown = out.last.reached.shown; + out.text = {}; + for (const [name, selector] of [["title", ".title"], ["reading", "svg text.reading"]]) { + const r = await tileOf(page, shown).locator(selector).first().boundingBox(), y = r.y + r.height / 2; + await mouseDrag(page, [r.x + 2, y], [r.x + r.width - 1, y + 1]); + out.text[name] = { selected: await selection(page), ...await page.evaluate(() => window.__state()) }; + } + // a click without moving on the gauge: back to the dashboard, in 200 ms, the tile in its place + out.zoomOut = await zoomClick(page, shown, await at(page, shown, 0.85, 0.3)); + out.outRect = await tileOf(page, shown).boundingBox(); + out.outTable = await page.evaluate((shown) => window.__look(shown).table, shown); // (its table back) + } else { + // a double-click (its clicks 300 ms apart, slower than the zoom): zoomed, not zoomed and straight back out + const wind = await at(page, "Wind", 0.85, 0.3); + await page.mouse.move(...wind); + await page.mouse.down(); await page.mouse.up(); + await page.waitForTimeout(300); + await page.mouse.down({ clickCount: 2 }); await page.mouse.up({ clickCount: 2 }); + await calm(page); + // Esc: back too + out.esc = { before: await page.evaluate(() => window.__state()) }; + await page.keyboard.press("Escape"); + await calm(page); + out.esc.after = await page.evaluate(() => window.__state()); + out.esc.titles = await titles(page); + // a click on the gauge doesn't take the focus: no × once the pointer has gone + await page.mouse.move(1020, 4); + await calm(page); + out.esc.close = await page.evaluate(() => ({ focused: document.activeElement === window.__tile("Wind"), + opacity: getComputedStyle(window.__tile("Wind").querySelector(".close")).opacity })); + // the bounce at the last tile, cut short by Esc: the dashboard back in its place at once; or by a key: that step slides + const n2 = (await titles(page)).length; + await page.mouse.click(...await at(page, "Wind", 0.85, 0.3)); + await calm(page); + for (let i = 0; i < n2; i++) { await page.keyboard.press("ArrowRight"); await page.waitForTimeout(30); } + await calm(page); + await page.keyboard.press("ArrowRight"); // (past the last: the bounce) + await page.waitForTimeout(30); + const cut = page.evaluate(() => window.__record(null, 300)); + await page.keyboard.press("ArrowLeft"); + const rec = await cut; + const near100 = rec.frames.filter((f) => f.t >= rec.at + 90 && f.t <= rec.at + 130).map((f) => Math.round(f.x)); + await calm(page); + out.bounceCut = { step: { mid: near100, ...await page.evaluate(() => window.__state()) } }; + await page.keyboard.press("ArrowRight"); await calm(page); + await page.keyboard.press("ArrowRight"); // (the bounce again) await page.waitForTimeout(30); - const others = await page.evaluate(() => window.__look("Temperature").table); - await page.waitForTimeout(70); await page.keyboard.press("Escape"); - const { frames: f, at: esc } = await recording, last = f[f.length - 1], after = f.filter((x) => x.t >= esc); - out.escMid = { others, last, zoomed: await page.evaluate(() => document.body.classList.contains("zoomed")), - atEsc: f.filter((x) => x.t < esc).pop().width, peakAfter: Math.max(...after.map((x) => x.width)), - tableWhileLarge: Math.max(...after.filter((x) => x.width > last.width + 1).map((x) => x.table)), tableEnd: last.table }; - await page.waitForTimeout(300); + await page.waitForTimeout(60); + out.bounceCut.esc = await page.evaluate(() => ({ grid: getComputedStyle(document.getElementById("grid")).transform, + firstLeft: Math.round(document.querySelector("#grid .tile").getBoundingClientRect().left), + zoomed: document.body.classList.contains("zoomed") })); + await calm(page); + // the keyboard: every tile takes the focus; Enter on one zooms it, the focus going along as it pages, the others out of reach; Esc + // back, the focus on the tile shown last; Space zooms too + const focusState = () => page.evaluate(() => ({ ...window.__state(), focus: document.activeElement.classList.contains("tile") ? document.activeElement.querySelector(".title").textContent : document.activeElement.tagName, + reachable: [...document.querySelectorAll("#grid .tile")].filter((t) => !t.inert).map((t) => t.querySelector(".title").textContent) })); + out.keyboard = { tabbable: await page.evaluate(() => [...document.querySelectorAll("#grid .tile")].every((t) => t.tabIndex === 0)) }; + await page.evaluate(() => window.__tile("Temperature").focus()); + await calm(page); + out.keyboard.focusedClose = await page.evaluate(() => getComputedStyle(window.__tile("Temperature").querySelector(".close")).opacity); + await page.keyboard.press("Enter"); + await calm(page); + out.keyboard.enter = await focusState(); + await page.keyboard.press("ArrowRight"); + await calm(page); + out.keyboard.right = await focusState(); + await page.keyboard.press("Tab"); + out.keyboard.tab = await focusState(); + await page.evaluate(() => window.__tile("Humidity").focus()); + await page.keyboard.press("Escape"); + await calm(page); + out.keyboard.esc = await focusState(); + await page.keyboard.press(" "); + await calm(page); + out.keyboard.space = await focusState(); + await page.keyboard.press("Escape"); + await calm(page); + // Esc 100 ms into a zoom-in: back from where the tile is drawn (no jump to the full size), its table hidden until it's in its grid place + // (never drawn large); the others keep their tables as they fade out, gone only once they're in the gallery + await calm(page); + { + const recording = page.evaluate(() => window.__record("Humidity", 700)); + await page.waitForTimeout(50); + await page.mouse.click(...await at(page, "Humidity", 0.85, 0.3)); + await page.waitForTimeout(30); + const others = await page.evaluate(() => window.__look("Temperature").table); + await page.waitForTimeout(70); + await page.keyboard.press("Escape"); + const { frames: f, at: esc } = await recording, last = f[f.length - 1], after = f.filter((x) => x.t >= esc); + out.escMid = { others, last, zoomed: await page.evaluate(() => document.body.classList.contains("zoomed")), + atEsc: f.filter((x) => x.t < esc).pop().width, peakAfter: Math.max(...after.map((x) => x.width)), + tableWhileLarge: Math.max(...after.filter((x) => x.width > last.width + 1).map((x) => x.table)), tableEnd: last.table }; + await calm(page); + } + // one tile only: no zoom cursor, a click zooms nothing + await page.evaluate((key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: [...document.querySelectorAll(".tile .title")].map((t) => t.textContent).filter((t) => t !== "Rain") })), KEY); + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0); + await calm(page, 300); + const one = await at(page, "Rain", 0.85, 0.3); + out.single = { cursor: await cursorAt(page, one) }; + await page.mouse.click(...one); + await calm(page); + out.single.zoomed = await page.evaluate(() => document.body.classList.contains("zoomed")); } - // one tile only: no zoom cursor, a click zooms nothing - await page.evaluate((key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: [...document.querySelectorAll(".tile .title")].map((t) => t.textContent).filter((t) => t !== "Rain") })), KEY); - await page.reload({ waitUntil: "load" }); - await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0); - await page.waitForTimeout(300); - const one = await at(page, "Rain", 0.85, 0.3); - out.single = { cursor: await cursorAt(page, one) }; - await page.mouse.click(...one); - await page.waitForTimeout(400); - out.single.zoomed = await page.evaluate(() => document.body.classList.contains("zoomed")); out.errors = errors; await context.close(); process.stdout.write(JSON.stringify(out) + "\n"); @@ -621,16 +654,21 @@ async function zoomTouchMode(browser, url) { await page.evaluate(ZOOM_HELPERS); const cdp = await context.newCDPSession(page); const touch = (type, points) => cdp.send("Input.dispatchTouchEvent", { type, touchPoints: points.map(([x, y]) => ({ x, y })) }); - const tap = async ([x, y]) => { await touch("touchStart", [[x, y]]); await page.waitForTimeout(60); await touch("touchEnd", []); await page.waitForTimeout(450); }; + const tap = async ([x, y]) => { // (then its click, and the zoom it starts or ends at rest) + const before = await page.evaluate(() => window.__at); + await touch("touchStart", [[x, y]]); await page.waitForTimeout(60); await touch("touchEnd", []); + await page.waitForFunction((before) => window.__at !== before, before, { timeout: 450 }).catch(() => {}); + await calm(page, 450); + }; const swipe = async ([x, y], dx, { steps = 10, pause = 250, dy = 0 } = {}) => { await touch("touchStart", [[x, y]]); for (let i = 1; i <= steps; i++) { await touch("touchMove", [[x + dx * i / steps, y + dy * i / steps]]); if (pause) await page.waitForTimeout(16); } await page.waitForTimeout(pause); await touch("touchEnd", []); - await page.waitForTimeout(500); + await calm(page, 500); return page.evaluate(() => window.__state()); }; - await page.waitForTimeout(1200); + await calm(page, 5000); // (the gauges' rise) out.initial = await titles(page); // scrolled down a row or two: the tile at the top left tapped const scrolled = await page.evaluate(() => { const t = document.querySelectorAll("#grid .tile")[4]; scrollTo(0, t.getBoundingClientRect().top + scrollY - 8); return scrollY; }); @@ -656,7 +694,7 @@ async function zoomTouchMode(browser, url) { await touch("touchStart", [[200, 300]]); await page.waitForTimeout(700); await touch("touchEnd", []); - await page.waitForTimeout(300); + await calm(page, 300); out.held = { ...await page.evaluate(() => window.__state()), buzz: await page.evaluate(() => window.__buzz), zone: await page.evaluate(() => document.getElementById("remove").classList.contains("on")) }; await swipe([90, 300], 250); @@ -695,10 +733,17 @@ async function fillMode(browser, url, cases) { async function weatherPage(browser, url, options = {}) { const state = { readings: {} }; const context = await browser.newContext({ viewport: { width: 1024, height: 768 }, deviceScaleFactor: 1, ...(options.context || {}) }); - await context.addInitScript(() => { // (every frame the page asks for, counted) + await context.addInitScript(() => { // (every frame the page asks for, counted; and every fetch's data read) window.__frames = 0; const ask = window.requestAnimationFrame.bind(window); window.requestAnimationFrame = (f) => { window.__frames++; return ask(f); }; + window.__fetched = 0; + const get = window.fetch.bind(window); + window.fetch = async (...args) => { + const response = await get(...args), json = response.json.bind(response); + response.json = async () => { const data = await json(); window.__fetched++; return data; }; // (counted before the page renders it) + return response; + }; }); if (options.init) await context.addInitScript(options.init.fn, options.init.arg); await context.route(/\/dashboard\/data$/, async (route) => { @@ -717,10 +762,8 @@ async function weatherPage(browser, url, options = {}) { // The readings now these (fetched again: the page fetches when it's shown again) const reads = async (readings) => { state.readings = readings; - const was = await page.evaluate(() => JSON.stringify(Sky.state().levels) + document.querySelectorAll(".tile.alert").length); - await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))); - await page.waitForTimeout(250); - return was; + const fetched = await page.evaluate(() => { const n = window.__fetched; document.dispatchEvent(new Event("visibilitychange")); return n; }); + await page.waitForFunction((n) => window.__fetched > n, fetched); // (fetched and drawn) }; return { context, page, errors, reads }; } @@ -748,189 +791,235 @@ const framesIn = async (page, ms) => { // the frames the page asked for in thi return (await page.evaluate(() => window.__frames)) - before; }; -async function weatherMode(browser, url) { +// The weather in parts, each its own page (and process: the tests run them side by side): "marks" (nothing called for, each effect at +// its mark and just short of it, smog's bands, rain's strength, the ice's depth), "several" (several at once, the canvas, the tiles see- +// through, their look, zoomed), "stop" ("stop animations", a reload, "start animations", the reset), "links" (the temporary test links), +// "all" (?fx=all: its frame time, its brightness against Hazardous smog alone, its particles), "opened" (?fx= when the page opens, uv +// and the wind alone, a phone's strip, reduced motion) +const WEATHER = { + async marks(browser, url, out) { + const { context, page, errors, reads } = await weatherPage(browser, url); + await calm(page, 5000); // (the gauges' rise) + out.nothing = { ...await weatherSeen(page), frames: await framesIn(page, 800), ink: await canvasInk(page) }; + // each mark: just short of it, then at it + const marks = { rain: [{ rain_rate: 0 }, { rain_rate: 0.1 }], smog: [{ "US AQI": 50 }, { "US AQI": 51 }], + uv: [{ "UV index": 10.9 }, { "UV index": 11 }], humidity: [{ Humidity: 94.9 }, { Humidity: 95 }], + wind: [{ Wind: 50 }, { Wind: 50.1 }], heat: [{ Temperature: 39.9 }, { Temperature: 40 }], + ice: [{ Temperature: 0.1 }, { Temperature: -0.1 }], iceAtZero: [{ Temperature: 0 }, { Temperature: -0.1 }] }; + out.marks = {}; + for (const [name, [below, at]] of Object.entries(marks)) { + await reads(below); + const short = await weatherSeen(page); + await reads(at); + out.marks[name] = { below: short, at: await weatherSeen(page) }; + } + out.smogBands = []; + for (const aqi of [101, 151, 201, 301, 500]) { await reads({ "US AQI": aqi }); out.smogBands.push((await weatherSeen(page)).levels.smog); } + out.rainStrength = []; + for (const rate of [0.5, 8, 20]) { await reads({ rain_rate: rate }); out.rainStrength.push((await weatherSeen(page)).levels.rain); } + out.iceDepth = []; + for (const t of [-0.5, -5]) { await reads({ Temperature: t }); out.iceDepth.push((await weatherSeen(page)).levels.ice); } + out.errors = errors; + await context.close(); + }, + async several(browser, url, out) { + const { context, page, errors, reads } = await weatherPage(browser, url); + await calm(page, 5000); // (the gauges' rise) + // several at once: one canvas, one loop (at most 30 frames a second) + await reads({ "UV index": 11, Wind: 60, Temperature: -3, rain_rate: 2, Humidity: 97, "US AQI": 160 }); + await calm(page, 5000); // (the gauges' move to their new readings, MOVE_MS: frames of their own) + const drawnBefore = await page.evaluate(() => Sky.state().frames); + out.several = { ...await weatherSeen(page), canvases: await page.evaluate(() => document.querySelectorAll("canvas").length), + frames: await framesIn(page, 1000), ink: await canvasInk(page) }; + out.several.drawn = (await page.evaluate(() => Sky.state().frames)) - drawnBefore; + // the canvas: the window's size, fixed, first in the page, behind the tiles (which come after it), clicks through it. (Behind: its + // pointer-events on for a moment, so hit-testing sees it, a tile's middle is still the tile's) + out.canvas = await page.evaluate(() => { + const sky = document.getElementById("sky"), c = sky.querySelector("canvas"), r = sky.getBoundingClientRect(), cr = c.getBoundingClientRect(); + const st = getComputedStyle(sky); + return { rect: [r.left, r.top, r.width, r.height], canvas: [cr.width >= innerWidth, cr.height >= innerHeight], + position: st.position, z: st.zIndex, events: st.pointerEvents, first: document.body.firstElementChild === sky, + pixelated: getComputedStyle(c).imageRendering, + under: (() => { + const r = [...document.querySelectorAll("#grid .tile")][3].getBoundingClientRect(); + sky.style.pointerEvents = "auto"; + const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); + sky.style.pointerEvents = ""; + return hit !== null && hit.closest(".tile") !== null; + })() }; + }); + // the tiles see-through: a tile's blank margin shows what's drawn behind it (smog, Hazardous, over the bottom row) + await reads({ "US AQI": 500 }); + await page.waitForTimeout(1800); + const margin = async () => { + const r = await tileOf(page, "PM10").boundingBox(); + return page.screenshot({ clip: { x: r.x + r.width * 0.04, y: r.y + r.height * 0.45, width: r.width * 0.12, height: r.height * 0.15 } }); + }; + const smoggy = await margin(); + await reads({}); + await page.waitForFunction(() => !Sky.state().running); // (faded out: the loop ended) + await calm(page); + const clear1 = await margin(), clear2 = await margin(); + out.through = { differs: !smoggy.equals(clear1), still: clear1.equals(clear2) }; + out.look = await page.evaluate(() => { + const tile = document.querySelector(".tile"), before = getComputedStyle(tile, "::before"); + return { background: getComputedStyle(tile).backgroundColor, opacity: getComputedStyle(tile).opacity, + title: getComputedStyle(tile.querySelector(".title")).color, frame: before.borderTopColor }; + }); + await reads({ "UV index": 11 }); + out.look.alertFrame = await page.evaluate(() => getComputedStyle(document.querySelector(".tile.alert"), "::before").borderTopColor); + out.look.dragFrames = await page.evaluate(() => { // a framed tile dragged: lifted, then over the remove zone, its frame as any other's + const tile = document.querySelector(".tile.alert"), frame = () => getComputedStyle(tile, "::before").borderTopColor; + tile.classList.add("lifted"); + const lifted = frame(); + tile.classList.add("doomed"); + const doomed = frame(); + tile.classList.remove("lifted", "doomed"); + return { lifted, doomed, after: frame() }; + }); + // zoomed: the tile still see-through, its frame still red, the effect still behind it + const [zx, zy] = await at(page, "UV index", 0.85, 0.3); + await page.mouse.click(zx, zy); + await calm(page); + out.zoomed = await page.evaluate(() => { + const shown = [...document.querySelectorAll("#grid .tile")].find((t) => !t.inert); + return { zoomed: document.body.classList.contains("zoomed"), title: shown.querySelector(".title").textContent, + background: getComputedStyle(shown).backgroundColor, grid: getComputedStyle(document.getElementById("grid")).backgroundColor, + alert: shown.classList.contains("alert"), running: Sky.state().running }; + }); + out.errors = errors; + await context.close(); + }, + async stop(browser, url, out) { + const { context, page, errors, reads } = await weatherPage(browser, url); + await calm(page, 5000); // (the gauges' rise) + await reads({ "UV index": 11 }); + await calm(page, 5000); // (the gauge's move: frames of its own) + // "stop animations": nothing drawn, no loop, the frames stay; kept; "reset preferences" starts them again + await page.locator("#status .animations").click(); + await page.waitForTimeout(200); + out.stopped = { ...await weatherSeen(page), frames: await framesIn(page, 600), ink: await canvasInk(page), + stored: JSON.parse(await page.evaluate((key) => localStorage.getItem(key), KEY)).animations }; + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile.alert").length > 0); + await calm(page, 5000); // (the gauges' rise) + out.reloaded = { ...await weatherSeen(page), frames: await framesIn(page, 500) }; + await page.locator("#status .animations").click(); + await page.waitForTimeout(100); + out.restarted = { ...await weatherSeen(page), frames: await framesIn(page, 500) }; + await page.locator("#status .animations").click(); // (stopped again: reset puts them back) + await page.mouse.move(...await at(page, "Rain", 0.5, 0.4)); + await calm(page); + await tileOf(page, "Rain").locator(".close").click(); + await calm(page); + await page.getByText("reset preferences").click(); + await page.waitForTimeout(100); + out.reset = { ...await weatherSeen(page), frames: await framesIn(page, 500) }; + out.errors = errors; + await context.close(); + }, + async links(browser, url, out) { + // the temporary test links: each turns its effect and frame on (the gauges keep their readings), "clear" ends them; the URL follows + const { context, page, errors } = await weatherPage(browser, url); + await calm(page, 5000); // (the gauges' rise) + const fx = (name) => page.locator("#fxtest button", { hasText: new RegExp(`^${name}`) }).first().click(); + const label = () => page.evaluate(() => document.querySelector(".tile[data-id='UV index']").getAttribute("aria-label")); + out.links = { buttons: await page.evaluate(() => [...document.querySelectorAll("#fxtest button")].map((b) => b.textContent)) }; + for (const name of ["uv", "humidity", "wind", "heat", "ice"]) { + await fx(name); + out.links[name] = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; + } + out.links.label = await label(); + out.links.smog = []; + for (let i = 0; i < 6; i++) { await fx("smog"); out.links.smog.push((await weatherSeen(page)).levels.smog); } + out.links.rain = []; + for (let i = 0; i < 3; i++) { await fx("rain"); out.links.rain.push((await weatherSeen(page)).levels.rain); } + await page.waitForFunction(() => Sky.state().iceReach > 2.5); // (the ice grown in a little) + const grown = await page.evaluate(() => Sky.state().iceReach); + await fx("ice"); // (off: it melts back, the loop running on until it's gone) + await page.waitForTimeout(300); + out.links.melting = { grown, reach: await page.evaluate(() => Sky.state().iceReach), ...await weatherSeen(page) }; + out.links.pressed = await page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#fxtest button[data-fx]")] + .map((b) => [b.dataset.fx, b.getAttribute("aria-pressed")]))); + out.links.role = await page.evaluate(() => document.getElementById("fxtest").getAttribute("role")); + await fx("clear"); + await page.waitForTimeout(100); + out.links.cleared = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; + // every effect at once: ?fx=all (no link of its own) + await page.goto(url + "?fx=all", { waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /updated/.test(document.getElementById("status").textContent)); + out.links.all = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; + out.errors = errors; + await context.close(); + }, + async all(browser, url, out) { + const particles = (p) => p.evaluate(() => ({ ...Sky.state().particles, budget: Sky.state().budget })); + const { context, page, errors } = await weatherPage(browser, url, { query: "?fx=all" }); + await page.waitForTimeout(3000); + out.cost = await page.evaluate(() => Sky.state().cost); // (ms of script a frame, with every effect on) + // the strongest single effect (Hazardous smog), as bright as "all" may be: faded in while the ice grows on + const strongest = (async () => { + const smog = await weatherPage(browser, url, { query: "?fx=smog5" }); + await smog.page.waitForTimeout(2500); // (faded in) + const light = await canvasLight(smog.page); + await smog.context.close(); + return light; + })(); + await page.waitForFunction(() => { // (the ice grown all the way in: its reach the same for half a second) + const r = Sky.state().iceReach, now = performance.now(); + if (window.__reach !== r) { window.__reach = r; window.__reachSince = now; } + return r > 0 && now - window.__reachSince >= 500; + }, null, { timeout: 15000 }); + out.light = { all: await canvasLight(page) }; + out.particles = { all: await particles(page) }; + out.light.smog5 = await strongest; + out.errors = errors; + await context.close(); + }, + async opened(browser, url, out) { + const particles = (p) => p.evaluate(() => ({ ...Sky.state().particles, budget: Sky.state().budget })); + // ?fx= when the page opens + for (const [name, query] of [["param", "?fx=smog3,wind,ice"], ["paramAll", "?fx=all"], ["paramRain", "?fx=rain2"], + ["paramOld", "?fx=leaves,radiation,drips"]]) { + const opened = await weatherPage(browser, url, { query }); + await opened.page.waitForTimeout(200); + out[name] = { ...await weatherSeen(opened.page), errors: opened.errors }; + await opened.context.close(); + } + // uv alone: its beams, no particles; the wind alone: its leaves within the budget + out.particles = {}; + for (const name of ["uv", "wind"]) { + const alone = await weatherPage(browser, url, { query: `?fx=${name}` }); + await alone.page.waitForTimeout(1500); + const p = await particles(alone.page); + out.particles[name] = { [name]: p[name], budget: p.budget }; + await alone.context.close(); + } + // a phone, a tile hidden, an effect on: the strip (reset preferences · stop animations · updated) at the bottom right, the time last; + // the test row not over it + const phone = await weatherPage(browser, url, { query: "?fx=rain", context: { viewport: { width: 360, height: 740 }, hasTouch: true, isMobile: true }, + init: { fn: (key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: ["Rain"] })), arg: KEY } }); + await phone.page.waitForTimeout(300); + out.phone = await phone.page.evaluate(() => { + const a = document.getElementById("fxtest").getBoundingClientRect(), b = document.getElementById("status").getBoundingClientRect(); + return { strip: document.getElementById("status").textContent, right: Math.abs(b.right - innerWidth) < 1 && Math.abs(b.bottom - innerHeight) < 1, + apart: a.right <= b.left || b.right <= a.left || a.bottom <= b.top || b.bottom <= a.top, onScreen: a.left >= 0 && a.bottom <= innerHeight }; + }); + await phone.context.close(); + // reduced motion: no loop, one still, faint frame; the frames as ever + const still = await weatherPage(browser, url, { context: { reducedMotion: "reduce" } }); + await still.reads({ "UV index": 11, Temperature: -4 }); + await still.page.waitForTimeout(500); + out.still = { ...await weatherSeen(still.page), frames: await framesIn(still.page, 800), ink: await canvasInk(still.page), + stateFrames: await still.page.evaluate(() => Sky.state().frames), errors: still.errors }; + await still.context.close(); + out.errors = []; + }, +}; + +async function weatherMode(browser, url, part) { const out = {}; - const { context, page, errors, reads } = await weatherPage(browser, url); - await page.waitForTimeout(1300); // (the gauges' rise) - out.nothing = { ...await weatherSeen(page), frames: await framesIn(page, 800), ink: await canvasInk(page) }; - // each mark: just short of it, then at it - const marks = { rain: [{ rain_rate: 0 }, { rain_rate: 0.1 }], smog: [{ "US AQI": 50 }, { "US AQI": 51 }], - uv: [{ "UV index": 10.9 }, { "UV index": 11 }], humidity: [{ Humidity: 94.9 }, { Humidity: 95 }], - wind: [{ Wind: 50 }, { Wind: 50.1 }], heat: [{ Temperature: 39.9 }, { Temperature: 40 }], - ice: [{ Temperature: 0.1 }, { Temperature: -0.1 }], iceAtZero: [{ Temperature: 0 }, { Temperature: -0.1 }] }; - out.marks = {}; - for (const [name, [below, at]] of Object.entries(marks)) { - await reads(below); - const short = await weatherSeen(page); - await reads(at); - out.marks[name] = { below: short, at: await weatherSeen(page) }; - } - out.smogBands = []; - for (const aqi of [101, 151, 201, 301, 500]) { await reads({ "US AQI": aqi }); out.smogBands.push((await weatherSeen(page)).levels.smog); } - out.rainStrength = []; - for (const rate of [0.5, 8, 20]) { await reads({ rain_rate: rate }); out.rainStrength.push((await weatherSeen(page)).levels.rain); } - out.iceDepth = []; - for (const t of [-0.5, -5]) { await reads({ Temperature: t }); out.iceDepth.push((await weatherSeen(page)).levels.ice); } - // several at once: one canvas, one loop (at most 30 frames a second) - await reads({ "UV index": 11, Wind: 60, Temperature: -3, rain_rate: 2, Humidity: 97, "US AQI": 160 }); - await page.waitForTimeout(1200); // (the gauges' move to their new readings, MOVE_MS: frames of their own) - const drawnBefore = await page.evaluate(() => Sky.state().frames); - out.several = { ...await weatherSeen(page), canvases: await page.evaluate(() => document.querySelectorAll("canvas").length), - frames: await framesIn(page, 1000), ink: await canvasInk(page) }; - out.several.drawn = (await page.evaluate(() => Sky.state().frames)) - drawnBefore; - // the canvas: the window's size, fixed, first in the page, behind the tiles (which come after it), clicks through it. (Behind: its - // pointer-events on for a moment, so hit-testing sees it, a tile's middle is still the tile's) - out.canvas = await page.evaluate(() => { - const sky = document.getElementById("sky"), c = sky.querySelector("canvas"), r = sky.getBoundingClientRect(), cr = c.getBoundingClientRect(); - const st = getComputedStyle(sky); - return { rect: [r.left, r.top, r.width, r.height], canvas: [cr.width >= innerWidth, cr.height >= innerHeight], - position: st.position, z: st.zIndex, events: st.pointerEvents, first: document.body.firstElementChild === sky, - pixelated: getComputedStyle(c).imageRendering, - under: (() => { - const r = [...document.querySelectorAll("#grid .tile")][3].getBoundingClientRect(); - sky.style.pointerEvents = "auto"; - const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); - sky.style.pointerEvents = ""; - return hit !== null && hit.closest(".tile") !== null; - })() }; - }); - // the tiles see-through: a tile's blank margin shows what's drawn behind it (smog, Hazardous, over the bottom row) - await reads({ "US AQI": 500 }); - await page.waitForTimeout(1800); - const margin = async () => { - const r = await tileOf(page, "PM10").boundingBox(); - return page.screenshot({ clip: { x: r.x + r.width * 0.04, y: r.y + r.height * 0.45, width: r.width * 0.12, height: r.height * 0.15 } }); - }; - const smoggy = await margin(); - await reads({}); - await page.waitForTimeout(1800); // (faded out) - const clear1 = await margin(), clear2 = await margin(); - out.through = { differs: !smoggy.equals(clear1), still: clear1.equals(clear2) }; - out.look = await page.evaluate(() => { - const tile = document.querySelector(".tile"), before = getComputedStyle(tile, "::before"); - return { background: getComputedStyle(tile).backgroundColor, opacity: getComputedStyle(tile).opacity, - title: getComputedStyle(tile.querySelector(".title")).color, frame: before.borderTopColor }; - }); - await reads({ "UV index": 11 }); - out.look.alertFrame = await page.evaluate(() => getComputedStyle(document.querySelector(".tile.alert"), "::before").borderTopColor); - out.look.dragFrames = await page.evaluate(() => { // a framed tile dragged: lifted, then over the remove zone, its frame as any other's - const tile = document.querySelector(".tile.alert"), frame = () => getComputedStyle(tile, "::before").borderTopColor; - tile.classList.add("lifted"); - const lifted = frame(); - tile.classList.add("doomed"); - const doomed = frame(); - tile.classList.remove("lifted", "doomed"); - return { lifted, doomed, after: frame() }; - }); - // zoomed: the tile still see-through, its frame still red, the effect still behind it - const [zx, zy] = await at(page, "UV index", 0.85, 0.3); - await page.mouse.click(zx, zy); - await page.waitForTimeout(400); - out.zoomed = await page.evaluate(() => { - const shown = [...document.querySelectorAll("#grid .tile")].find((t) => !t.inert); - return { zoomed: document.body.classList.contains("zoomed"), title: shown.querySelector(".title").textContent, - background: getComputedStyle(shown).backgroundColor, grid: getComputedStyle(document.getElementById("grid")).backgroundColor, - alert: shown.classList.contains("alert"), running: Sky.state().running }; - }); - await page.keyboard.press("Escape"); - await page.waitForTimeout(300); - // "stop animations": nothing drawn, no loop, the frames stay; kept; "reset preferences" starts them again - await page.locator("#status .animations").click(); - await page.waitForTimeout(200); - out.stopped = { ...await weatherSeen(page), frames: await framesIn(page, 600), ink: await canvasInk(page), - stored: JSON.parse(await page.evaluate((key) => localStorage.getItem(key), KEY)).animations }; - await page.reload({ waitUntil: "load" }); - await page.waitForFunction(() => document.querySelectorAll(".tile.alert").length > 0); - await page.waitForTimeout(1300); // (the gauges' rise) - out.reloaded = { ...await weatherSeen(page), frames: await framesIn(page, 500) }; - await page.locator("#status .animations").click(); - await page.waitForTimeout(300); - out.restarted = { ...await weatherSeen(page), frames: await framesIn(page, 500) }; - await page.locator("#status .animations").click(); // (stopped again: reset puts them back) - await page.mouse.move(...await at(page, "Rain", 0.5, 0.4)); - await page.waitForTimeout(250); - await tileOf(page, "Rain").locator(".close").click(); - await page.waitForTimeout(300); - await page.getByText("reset preferences").click(); - await page.waitForTimeout(400); - out.reset = { ...await weatherSeen(page), frames: await framesIn(page, 500) }; - // the temporary test links: each turns its effect and frame on (the gauges keep their readings), "clear" ends them; the URL follows - await reads({}); - await page.waitForTimeout(1700); - const fx = (name) => page.locator("#fxtest button", { hasText: new RegExp(`^${name}`) }).first().click(); - const label = () => page.evaluate(() => document.querySelector(".tile[data-id='UV index']").getAttribute("aria-label")); - out.links = { buttons: await page.evaluate(() => [...document.querySelectorAll("#fxtest button")].map((b) => b.textContent)) }; - for (const name of ["uv", "humidity", "wind", "heat", "ice"]) { - await fx(name); - out.links[name] = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; - } - out.links.label = await label(); - out.links.smog = []; - for (let i = 0; i < 6; i++) { await fx("smog"); out.links.smog.push((await weatherSeen(page)).levels.smog); } - out.links.rain = []; - for (let i = 0; i < 3; i++) { await fx("rain"); out.links.rain.push((await weatherSeen(page)).levels.rain); } - await page.waitForTimeout(2500); // (the ice grown in a little) - const grown = await page.evaluate(() => Sky.state().iceReach); - await fx("ice"); // (off: it melts back, the loop running on until it's gone) - await page.waitForTimeout(300); - out.links.melting = { grown, reach: await page.evaluate(() => Sky.state().iceReach), ...await weatherSeen(page) }; - out.links.pressed = await page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#fxtest button[data-fx]")] - .map((b) => [b.dataset.fx, b.getAttribute("aria-pressed")]))); - out.links.role = await page.evaluate(() => document.getElementById("fxtest").getAttribute("role")); - await fx("clear"); - await page.waitForTimeout(100); - out.links.cleared = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; - // every effect at once: ?fx=all (no link of its own) - await page.goto(url + "?fx=all", { waitUntil: "load" }); - await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /updated/.test(document.getElementById("status").textContent)); - out.links.all = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; - await page.waitForTimeout(3000); - out.cost = await page.evaluate(() => Sky.state().cost); // (ms of script a frame, with every effect on) - await page.waitForTimeout(5000); // (the ice grown all the way in) - out.light = { all: await canvasLight(page) }; - const particles = (p) => p.evaluate(() => ({ ...Sky.state().particles, budget: Sky.state().budget })); - out.particles = { all: await particles(page) }; - out.errors = errors; - await context.close(); - // ?fx= when the page opens - for (const [name, query] of [["param", "?fx=smog3,wind,ice"], ["paramAll", "?fx=all"], ["paramRain", "?fx=rain2"], - ["paramOld", "?fx=leaves,radiation,drips"]]) { - const opened = await weatherPage(browser, url, { query }); - await opened.page.waitForTimeout(200); - out[name] = { ...await weatherSeen(opened.page), errors: opened.errors }; - await opened.context.close(); - } - // the strongest single effect (Hazardous smog), as bright as "all" may be - const strongest = await weatherPage(browser, url, { query: "?fx=smog5" }); - await strongest.page.waitForTimeout(2500); // (faded in) - out.light.smog5 = await canvasLight(strongest.page); - await strongest.context.close(); - // uv alone: its beams, no particles; the wind alone: its leaves within the budget - for (const name of ["uv", "wind"]) { - const alone = await weatherPage(browser, url, { query: `?fx=${name}` }); - await alone.page.waitForTimeout(1500); - const p = await particles(alone.page); - out.particles[name] = { [name]: p[name], budget: p.budget }; - await alone.context.close(); - } - // a phone, a tile hidden, an effect on: the strip (reset preferences · stop animations · updated) at the bottom right, the time last; - // the test row not over it - const phone = await weatherPage(browser, url, { query: "?fx=rain", context: { viewport: { width: 360, height: 740 }, hasTouch: true, isMobile: true }, - init: { fn: (key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: ["Rain"] })), arg: KEY } }); - await phone.page.waitForTimeout(300); - out.phone = await phone.page.evaluate(() => { - const a = document.getElementById("fxtest").getBoundingClientRect(), b = document.getElementById("status").getBoundingClientRect(); - return { strip: document.getElementById("status").textContent, right: Math.abs(b.right - innerWidth) < 1 && Math.abs(b.bottom - innerHeight) < 1, - apart: a.right <= b.left || b.right <= a.left || a.bottom <= b.top || b.bottom <= a.top, onScreen: a.left >= 0 && a.bottom <= innerHeight }; - }); - await phone.context.close(); - // reduced motion: no loop, one still, faint frame; the frames as ever - const still = await weatherPage(browser, url, { context: { reducedMotion: "reduce" } }); - await still.reads({ "UV index": 11, Temperature: -4 }); - await still.page.waitForTimeout(500); - out.still = { ...await weatherSeen(still.page), frames: await framesIn(still.page, 800), ink: await canvasInk(still.page), - stateFrames: await still.page.evaluate(() => Sky.state().frames), errors: still.errors }; - await still.context.close(); + await WEATHER[part](browser, url, out); process.stdout.write(JSON.stringify(out)); } @@ -943,9 +1032,9 @@ async function weatherMode(browser, url) { else if (second === "--arrange") await arrangeMode(browser, url); else if (second === "--touch") await touchMode(browser, url); else if (second === "--fill") await fillMode(browser, url, JSON.parse(third)); - else if (second === "--zoom") await zoomMode(browser, url); + else if (second === "--zoom") await zoomMode(browser, url, third); else if (second === "--zoom-touch") await zoomTouchMode(browser, url); - else if (second === "--weather") await weatherMode(browser, url); + else if (second === "--weather") await weatherMode(browser, url, third); else await sizes(browser, url, second, JSON.parse(third)); } finally { await browser.close(); From 3682e73d6231cbe792186b60b030cfad560eff00 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:44:31 +0000 Subject: [PATCH 015/146] Web dashboard: the strip says "last reading HH:MM" (was "updated HH:MM") Tests: the strip's text, and the pages' wait for the data drawn, by the new words. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 2 +- tests/test_web_dashboard.py | 12 ++++++------ tests/web_dashboard_browser.js | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index b02b4f9b..d3961949 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -1278,7 +1278,7 @@ const parts = []; if (resettable()) parts.push(link("reset preferences", reset, "reset")); if (calling()) parts.push(link(animated() ? "stop animations" : "start animations", toggleAnimations, "animations")); - const time = lost ? "reconnecting…" : asOf ? `updated ${asOf.slice(11, 16)}` : ""; + const time = lost ? "reconnecting…" : asOf ? `last reading ${asOf.slice(11, 16)}` : ""; if (time) parts.push(time); statusLine.replaceChildren(...parts.flatMap((p, i) => i ? [" · ", p] : [p])); } diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index e7805023..24c7df97 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -380,7 +380,7 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl got = report[name] assert got["errors"] == [], (name, got["errors"]) assert got["tiles"] == n and got["scrollWidth"] <= width, (name, got) - assert got["status"] == "stop animations · updated 18:42", (name, got) # (the US AQI's 56, Moderate: smog behind the tiles) + assert got["status"] == "stop animations · last reading 18:42", (name, got) # (the US AQI's 56, Moderate: smog behind the tiles) assert all(r["right"] <= width + 0.5 and r["left"] >= -0.5 for r in got["rects"]), (name, got) assert (shots / f"dashboard-{name}.png").exists() and (shots / f"dashboard-{name}-zoomed.png").exists() assert got["zoomed"]["zoomed"], (name, got["zoomed"]) @@ -505,13 +505,13 @@ async def test_tiles_are_dragged_to_reorder_hidden_by_the_x_or_the_remove_zone_k "table": {"same": True, "dragging": False, "selected": "85"}, "reading": {"same": True, "dragging": False, "selected": "70"}} # the ×, then the remove zone, hide; the reset link shows beside the time - assert got["closed"] == {"titles": [t for t in reordered if t != "Rain"], "status": "reset preferences · stop animations · updated 18:42"} + assert got["closed"] == {"titles": [t for t in reordered if t != "Rain"], "status": "reset preferences · stop animations · last reading 18:42"} assert got["removing"]["over"] and got["removing"]["zone"] == "none" shown = [t for t in reordered if t not in ("Rain", "Wind")] assert got["removed"] == {"titles": shown, "stored": {"order": reordered, "hidden": ["Rain", "Wind"]}} - assert got["reloaded"] == {"titles": shown, "status": "reset preferences · stop animations · updated 18:42"} + assert got["reloaded"] == {"titles": shown, "status": "reset preferences · stop animations · last reading 18:42"} # reset: every tile, in the default order, nothing kept, no link - assert got["reset"] == {"titles": default, "status": "stop animations · updated 18:42", "stored": None} + assert got["reset"] == {"titles": default, "status": "stop animations · last reading 18:42", "stored": None} # unreadable preferences: the defaults; a tile new to the saved order (Rain) in its usual place, after Atmospheric pressure; an # absent tile's place and a later stage's keys kept assert got["corrupt"] == default @@ -551,7 +551,7 @@ async def test_on_a_touch_screen_a_long_press_picks_a_tile_up_and_a_tap_or_a_swi assert got["dropped"]["titles"] == reordered and not got["dropped"]["zone"] and got["dropped"]["clicks"] == 1 # held and let go in place: the grip and × stay, and a tap on the × hides it assert got["armed"]["armed"] == ["Humidity"] and got["armed"]["close"] == "1" - assert got["closed"] == {"titles": [t for t in reordered if t != "Humidity"], "status": "reset preferences · stop animations · updated 18:42"} + assert got["closed"] == {"titles": [t for t in reordered if t != "Humidity"], "status": "reset preferences · stop animations · last reading 18:42"} # held at the bottom edge: the page scrolls to its end, never past it, and stays there once let go edge = got["edge"] assert edge["seen"][-1] == pytest.approx(edge["end"], abs=1) and max(edge["seen"]) <= edge["end"] + 1, edge @@ -884,7 +884,7 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red # the strip at the bottom right: its links, then the time at the far right; on a phone with both its links, the test row # beside it or above it, never over it phone = got["phone"] - assert phone["strip"] == "reset preferences · stop animations · updated 18:42" and phone["right"], phone + assert phone["strip"] == "reset preferences · stop animations · last reading 18:42" and phone["right"], phone assert phone["apart"] and phone["onScreen"], phone # reduced motion: no loop, one still, faint frame (the ice as it would be), the frames and the link as ever still = got["still"] diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 8ddb4b22..6735ad3d 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -39,7 +39,7 @@ async function open(browser, url, width, height, options = {}) { page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); }); page.on("pageerror", (e) => errors.push(String(e))); await page.goto(url, { waitUntil: "load" }); - await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /updated/.test(document.getElementById("status").textContent), + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /last reading/.test(document.getElementById("status").textContent), null, { timeout: 15000 }); return { context, page, errors }; } @@ -758,7 +758,7 @@ async function weatherPage(browser, url, options = {}) { page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); }); page.on("pageerror", (e) => errors.push(String(e))); await page.goto(url + (options.query || ""), { waitUntil: "load" }); - await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /updated/.test(document.getElementById("status").textContent)); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /last reading/.test(document.getElementById("status").textContent)); // The readings now these (fetched again: the page fetches when it's shown again) const reads = async (readings) => { state.readings = readings; @@ -947,7 +947,7 @@ const WEATHER = { out.links.cleared = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; // every effect at once: ?fx=all (no link of its own) await page.goto(url + "?fx=all", { waitUntil: "load" }); - await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /updated/.test(document.getElementById("status").textContent)); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /last reading/.test(document.getElementById("status").textContent)); out.links.all = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; out.errors = errors; await context.close(); @@ -995,7 +995,7 @@ const WEATHER = { out.particles[name] = { [name]: p[name], budget: p.budget }; await alone.context.close(); } - // a phone, a tile hidden, an effect on: the strip (reset preferences · stop animations · updated) at the bottom right, the time last; + // a phone, a tile hidden, an effect on: the strip (reset preferences · stop animations · last reading) at the bottom right, the time last; // the test row not over it const phone = await weatherPage(browser, url, { query: "?fx=rain", context: { viewport: { width: 360, height: 740 }, hasTouch: true, isMobile: true }, init: { fn: (key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: ["Rain"] })), arg: KEY } }); From 148a461d4019d1ae44cdd25b9814386ea2826949 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:44:52 +0000 Subject: [PATCH 016/146] Web dashboard: the humidity effect (drips) from 90 % outdoor humidity (was 95 %) Test: the mark at 90 % and just short of it (89.9 %). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 4 ++-- tests/test_web_dashboard.py | 2 +- tests/web_dashboard_browser.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index d3961949..d1657781 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -1747,7 +1747,7 @@ // ---------- the weather behind the tiles: what the readings call for, the tiles framed in red, "stop animations" ---------- // Each effect while its reading is past its mark, on its tile (Sky draws them): rain while it rains (the station's rain rate above 0, - // stronger to 8 mm/h), smog from the US AQI's Moderate band up (1-5, a band each), uv at a UV index of 11, humidity at 95 % + // stronger to 8 mm/h), smog from the US AQI's Moderate band up (1-5, a band each), uv at a UV index of 11, humidity at 90 % // humidity, wind above 50 km/h (the reading now, not the gust), heat at 40 °C, ice below 0 °C (how far below). A tile // with no reading now calls for nothing. const CALLED_BY = {rain: "Rain", smog: "US AQI", uv: "UV index", humidity: "Humidity", wind: "Wind", heat: "Temperature", @@ -1765,7 +1765,7 @@ ? aqiTile.bounds.slice(1, -1) : BANDS; return {rain: rate > 0 ? 0.3 + 0.7 * Math.min(1, rate / 8) : 0, smog: aqi === null ? 0 : Math.min(5, bands.filter((b) => aqi > b).length), - uv: uvi !== null && uvi >= 11 ? 1 : 0, humidity: humidity !== null && humidity >= 95 ? 1 : 0, + uv: uvi !== null && uvi >= 11 ? 1 : 0, humidity: humidity !== null && humidity >= 90 ? 1 : 0, wind: wind !== null && wind > 50 ? 1 : 0, heat: temperature !== null && temperature >= 40 ? 1 : 0, ice: temperature !== null && temperature < 0 ? -temperature : 0}; } diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 24c7df97..d2ce7cc2 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -786,7 +786,7 @@ async def test_the_weather_behind_the_tiles_comes_with_its_reading_at_its_mark_a # nothing called for (the US AQI Good): no effect, no frame, no link, no loop, nothing drawn assert got["nothing"] == {"effects": [], "levels": {k: 0 for k in got["nothing"]["levels"]}, "running": False, "framed": [], "link": None, "frames": 0, "ink": 0} - # each effect at its mark and not just short of it (rain above 0 mm/h, the AQI's Moderate band from 51, UV 11, 95 %, wind above + # each effect at its mark and not just short of it (rain above 0 mm/h, the AQI's Moderate band from 51, UV 11, 90 %, wind above # 50 km/h, 40 °C, below 0 °C, not at it), its tile framed in red, the strip's link with it for name, mark in got["marks"].items(): effect = "ice" if name == "iceAtZero" else name diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 6735ad3d..7dff2e3f 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -803,7 +803,7 @@ const WEATHER = { out.nothing = { ...await weatherSeen(page), frames: await framesIn(page, 800), ink: await canvasInk(page) }; // each mark: just short of it, then at it const marks = { rain: [{ rain_rate: 0 }, { rain_rate: 0.1 }], smog: [{ "US AQI": 50 }, { "US AQI": 51 }], - uv: [{ "UV index": 10.9 }, { "UV index": 11 }], humidity: [{ Humidity: 94.9 }, { Humidity: 95 }], + uv: [{ "UV index": 10.9 }, { "UV index": 11 }], humidity: [{ Humidity: 89.9 }, { Humidity: 90 }], wind: [{ Wind: 50 }, { Wind: 50.1 }], heat: [{ Temperature: 39.9 }, { Temperature: 40 }], ice: [{ Temperature: 0.1 }, { Temperature: -0.1 }], iceAtZero: [{ Temperature: 0 }, { Temperature: -0.1 }] }; out.marks = {}; From 7dc9483573a216c79e60420637ce178250681e8c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:45:08 +0000 Subject: [PATCH 017/146] Web dashboard: the wind effect (leaves) above 15 km/h of wind speed (was 50; still the speed, not the gust) Test: the mark just above 15 km/h and at it (15: none). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 4 ++-- tests/test_web_dashboard.py | 2 +- tests/web_dashboard_browser.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index d1657781..0fd3718f 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -1748,7 +1748,7 @@ // ---------- the weather behind the tiles: what the readings call for, the tiles framed in red, "stop animations" ---------- // Each effect while its reading is past its mark, on its tile (Sky draws them): rain while it rains (the station's rain rate above 0, // stronger to 8 mm/h), smog from the US AQI's Moderate band up (1-5, a band each), uv at a UV index of 11, humidity at 90 % - // humidity, wind above 50 km/h (the reading now, not the gust), heat at 40 °C, ice below 0 °C (how far below). A tile + // humidity, wind above 15 km/h (the reading now, not the gust), heat at 40 °C, ice below 0 °C (how far below). A tile // with no reading now calls for nothing. const CALLED_BY = {rain: "Rain", smog: "US AQI", uv: "UV index", humidity: "Humidity", wind: "Wind", heat: "Temperature", ice: "Temperature"}; @@ -1766,7 +1766,7 @@ return {rain: rate > 0 ? 0.3 + 0.7 * Math.min(1, rate / 8) : 0, smog: aqi === null ? 0 : Math.min(5, bands.filter((b) => aqi > b).length), uv: uvi !== null && uvi >= 11 ? 1 : 0, humidity: humidity !== null && humidity >= 90 ? 1 : 0, - wind: wind !== null && wind > 50 ? 1 : 0, heat: temperature !== null && temperature >= 40 ? 1 : 0, + wind: wind !== null && wind > 15 ? 1 : 0, heat: temperature !== null && temperature >= 40 ? 1 : 0, ice: temperature !== null && temperature < 0 ? -temperature : 0}; } const calling = () => Object.values(conditions).some((v) => v > 0); // (any effect called for: the strip's link shows) diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index d2ce7cc2..85362299 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -787,7 +787,7 @@ async def test_the_weather_behind_the_tiles_comes_with_its_reading_at_its_mark_a assert got["nothing"] == {"effects": [], "levels": {k: 0 for k in got["nothing"]["levels"]}, "running": False, "framed": [], "link": None, "frames": 0, "ink": 0} # each effect at its mark and not just short of it (rain above 0 mm/h, the AQI's Moderate band from 51, UV 11, 90 %, wind above - # 50 km/h, 40 °C, below 0 °C, not at it), its tile framed in red, the strip's link with it + # 15 km/h, 40 °C, below 0 °C, not at it), its tile framed in red, the strip's link with it for name, mark in got["marks"].items(): effect = "ice" if name == "iceAtZero" else name assert mark["below"] | {"levels": None} == {"effects": [], "levels": None, "running": mark["below"]["running"], "framed": [], diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 7dff2e3f..c8a3a1e5 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -804,7 +804,7 @@ const WEATHER = { // each mark: just short of it, then at it const marks = { rain: [{ rain_rate: 0 }, { rain_rate: 0.1 }], smog: [{ "US AQI": 50 }, { "US AQI": 51 }], uv: [{ "UV index": 10.9 }, { "UV index": 11 }], humidity: [{ Humidity: 89.9 }, { Humidity: 90 }], - wind: [{ Wind: 50 }, { Wind: 50.1 }], heat: [{ Temperature: 39.9 }, { Temperature: 40 }], + wind: [{ Wind: 15 }, { Wind: 15.1 }], heat: [{ Temperature: 39.9 }, { Temperature: 40 }], ice: [{ Temperature: 0.1 }, { Temperature: -0.1 }], iceAtZero: [{ Temperature: 0 }, { Temperature: -0.1 }] }; out.marks = {}; for (const [name, [below, at]] of Object.entries(marks)) { From 4ccce38b7baf30794e54a481e9bb56f93d2e9f9f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:45:20 +0000 Subject: [PATCH 018/146] =?UTF-8?q?Web=20dashboard:=20the=20heat=20effect?= =?UTF-8?q?=20from=2035=20=C2=B0C=20outdoors=20(was=2040)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Test: the mark at 35 °C and just short of it (34.9). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 4 ++-- tests/test_web_dashboard.py | 2 +- tests/web_dashboard_browser.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 0fd3718f..e1c12803 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -1748,7 +1748,7 @@ // ---------- the weather behind the tiles: what the readings call for, the tiles framed in red, "stop animations" ---------- // Each effect while its reading is past its mark, on its tile (Sky draws them): rain while it rains (the station's rain rate above 0, // stronger to 8 mm/h), smog from the US AQI's Moderate band up (1-5, a band each), uv at a UV index of 11, humidity at 90 % - // humidity, wind above 15 km/h (the reading now, not the gust), heat at 40 °C, ice below 0 °C (how far below). A tile + // humidity, wind above 15 km/h (the reading now, not the gust), heat at 35 °C, ice below 0 °C (how far below). A tile // with no reading now calls for nothing. const CALLED_BY = {rain: "Rain", smog: "US AQI", uv: "UV index", humidity: "Humidity", wind: "Wind", heat: "Temperature", ice: "Temperature"}; @@ -1766,7 +1766,7 @@ return {rain: rate > 0 ? 0.3 + 0.7 * Math.min(1, rate / 8) : 0, smog: aqi === null ? 0 : Math.min(5, bands.filter((b) => aqi > b).length), uv: uvi !== null && uvi >= 11 ? 1 : 0, humidity: humidity !== null && humidity >= 90 ? 1 : 0, - wind: wind !== null && wind > 15 ? 1 : 0, heat: temperature !== null && temperature >= 40 ? 1 : 0, + wind: wind !== null && wind > 15 ? 1 : 0, heat: temperature !== null && temperature >= 35 ? 1 : 0, ice: temperature !== null && temperature < 0 ? -temperature : 0}; } const calling = () => Object.values(conditions).some((v) => v > 0); // (any effect called for: the strip's link shows) diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 85362299..7685fadb 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -787,7 +787,7 @@ async def test_the_weather_behind_the_tiles_comes_with_its_reading_at_its_mark_a assert got["nothing"] == {"effects": [], "levels": {k: 0 for k in got["nothing"]["levels"]}, "running": False, "framed": [], "link": None, "frames": 0, "ink": 0} # each effect at its mark and not just short of it (rain above 0 mm/h, the AQI's Moderate band from 51, UV 11, 90 %, wind above - # 15 km/h, 40 °C, below 0 °C, not at it), its tile framed in red, the strip's link with it + # 15 km/h, 35 °C, below 0 °C, not at it), its tile framed in red, the strip's link with it for name, mark in got["marks"].items(): effect = "ice" if name == "iceAtZero" else name assert mark["below"] | {"levels": None} == {"effects": [], "levels": None, "running": mark["below"]["running"], "framed": [], diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index c8a3a1e5..beb59a7f 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -804,7 +804,7 @@ const WEATHER = { // each mark: just short of it, then at it const marks = { rain: [{ rain_rate: 0 }, { rain_rate: 0.1 }], smog: [{ "US AQI": 50 }, { "US AQI": 51 }], uv: [{ "UV index": 10.9 }, { "UV index": 11 }], humidity: [{ Humidity: 89.9 }, { Humidity: 90 }], - wind: [{ Wind: 15 }, { Wind: 15.1 }], heat: [{ Temperature: 39.9 }, { Temperature: 40 }], + wind: [{ Wind: 15 }, { Wind: 15.1 }], heat: [{ Temperature: 34.9 }, { Temperature: 35 }], ice: [{ Temperature: 0.1 }, { Temperature: -0.1 }], iceAtZero: [{ Temperature: 0 }, { Temperature: -0.1 }] }; out.marks = {}; for (const [name, [below, at]] of Object.entries(marks)) { From 25d41056d8810fead3888d830354ffc8016b4688 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:50:25 +0000 Subject: [PATCH 019/146] Web dashboard: the wind blows from the right: leaves, wisps, gusts, turbulence and eddies all go right to left The wind's air is still worked out downwind along +x and drawn mirrored (screen x = W - x, the leaf sprites mirrored too), so the whole field is reversed exactly: the leaves and wisps come in at the right edge, the eddies' loops as before. Sky.state() gives the leaves' on-screen speed (wind: {vx, against}). Tests: with the wind alone, at 1024x768 and on a phone (which now shows the wind rather than rain beside its strip), the leaves move leftward overall, as drawn on the canvas frame to frame too, and some loop rightward a moment. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 22 +++++++++++++------- tests/test_web_dashboard.py | 6 +++++- tests/web_dashboard_browser.js | 38 ++++++++++++++++++++++++++++------ 3 files changed, 52 insertions(+), 14 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index e1c12803..39ce1e79 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -128,7 +128,8 @@ // Sky.set(want, animate): want {rain: 0-1 (its strength), smog: 0-5 (the AQI's band above Good), uv, humidity, wind, heat: 0 or // 1, ice: how far below 0 °C it is (0: none)}; animate false (the page's "stop animations"): nothing drawn. // Sky.state(): {effects, running, frames, cost (ms a frame, averaged), size: [art width, art height, P], particles (each effect's -// now), budget (theirs together, at most), levels, iceReach (art px)}, for the tests. +// now), budget (theirs together, at most), levels, iceReach (art px), wind (its leaves on screen: {vx: their mean speed across, +// negative leftward, against: how many go rightward})}, for the tests. const Sky = (() => { const holder = document.getElementById("sky"), canvas = holder.querySelector("canvas"), ctx = canvas.getContext("2d"); const STILL = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches; @@ -418,7 +419,7 @@ }; }); - // ---------- wind: autumn leaves blowing past left to right, three deep, caught in eddies and gusts; wisps of the wind itself ---------- + // ---------- wind: autumn leaves blowing past right to left, three deep, caught in eddies and gusts; wisps of the wind itself ---------- const LEAF_COLOURS = [ // [shadow, base, light] for: red, amber, ochre, green, brown; and the stem ["#5A1915", "#922B20", "#C24C34"], ["#66290F", "#A94B1B", "#D87A33"], ["#62420F", "#9E7024", "#D2A142"], ["#2C3F17", "#52702D", "#82A047"], ["#3B2816", "#664629", "#8C6840"]].map((r) => r.map(rgb)); @@ -432,21 +433,24 @@ ["..l.l...", ".lmlmld.", "lmmvmmd.", ".lvmmvmd", "lmmvmmd.", ".dmvmd..", "..dsd...", "...s...."]]]; const TURN = [1, 0.7, 0.35, -0.35, -0.7, -1, -0.7, -0.35, 0.35, 0.7]; // a leaf turning over and back (negative: its underside) const wind = effect((e) => { - // The air: a steady wind to the right, pulsing with gusts; slow turbulence over it (the curl of a few drifting waves: it swirls, + // The air: a steady wind to the left, pulsing with gusts; slow turbulence over it (the curl of a few drifting waves: it swirls, // never piles up); and a few eddies drifting along behind it, each a vortex that draws leaves near it onto a ring and sweeps them // round and round, then flings them off as it dies away. A leaf eases toward the air's speed where it is (it has a little // weight), turning over faster the faster the air turns about it. A few wisps of the wind itself trace the same air. + // (All of it is worked out downwind along +x, from the left edge, and drawn mirrored: on screen x is W - x, the sprites mirrored + // too, so everything, the gusts, turbulence and eddies, goes right to left, the leaves and wisps coming in at the right edge.) const LAYERS = [{speed: 40, alpha: 0.5, share: 0.4}, {speed: 60, alpha: 0.75, share: 0.35}, {speed: 85, alpha: 1, share: 0.25}]; const CALM = 0.6; // on narrow art (a phone's) the wind slower, down to this (else leaves cross before they loop) const DRIFT = 60; // the turbulence's own speed along (px/s, at no gust); the eddies lag it const EDDY_DRAW = 150; // how hard an eddy draws leaves onto its ring, and flings them off (px/s, about) // Each layer's leaves: each shape in each colour turning each way, as its frames const transposed = (rows) => rows[0].split("").map((_, x) => rows.map((row) => row[x]).join("")); + const mirrored = (rows) => rows.map((row) => [...row].reverse().join("")); // (drawn mirrored: see above) const sprites = LEAF_SHAPES.map((shapes) => shapes.flatMap((rows) => LEAF_COLOURS.flatMap(([d, m, l]) => { const under = [d, d, m]; // (its underside: darker) // turning about its length, or end over end (squeezed on its side, then stood up again) return [rows, transposed(rows)].map((map, axis) => TURN.map((k) => { - const squashed = axis ? transposed(squeezed(map, k)) : squeezed(map, k); + const squashed = mirrored(axis ? transposed(squeezed(map, k)) : squeezed(map, k)); return mapped(squashed, k > 0 ? {d, m, l, v: l, s: STEM} : {d: under[0], m: under[1], l: under[2], v: under[1], s: STEM}); })); }))); @@ -516,6 +520,9 @@ strength: () => 0.8, need: () => W * H / 2600, count: () => flying.length, + // (on screen: the leaves' mean speed across, px/s, negative leftward; how many go rightward, against the wind, in a loop) + probe: () => ({vx: -flying.reduce((sum, f) => sum + f.vx, 0) / Math.max(flying.length, 1), + against: flying.filter((f) => f.vx < 0).length}), resize() { flying = []; eddies = []; wisps = []; }, step(dt, t, share) { calm = clamp(W / 360, CALM, 1); @@ -574,7 +581,7 @@ if (lit < 0.15 || (i & 1)) continue; g.globalAlpha = alpha * 0.45 * lit; g.fillStyle = WISP[lit > 0.8 ? 2 : lit > 0.45 ? 1 : 0]; - g.fillRect(w.trail[2 * i], w.trail[2 * i + 1], 1, 1); + g.fillRect(W - 1 - w.trail[2 * i], w.trail[2 * i + 1], 1, 1); } } let layer = -1; @@ -582,7 +589,7 @@ if (f.layer !== layer) { layer = f.layer; g.globalAlpha = alpha * LAYERS[layer].alpha; } const frame = f.frames[Math.floor(f.turn) % f.frames.length]; const y = f.y + Math.sin(t * 2.3 + f.phase) * 1.2; // (a flutter) - g.drawImage(frame, Math.round(f.x - frame.width / 2), Math.round(y - frame.height / 2)); + g.drawImage(frame, Math.round(W - f.x - frame.width / 2), Math.round(y - frame.height / 2)); } }, }; @@ -871,7 +878,8 @@ return {set, state: () => ({effects: ORDER.filter((k) => effects[k].level > 0), running: !!frame, frames, cost, size: [W, H, P], particles: Object.fromEntries(ORDER.map((k) => [k, effects[k].count()])), budget: W * H * BUDGET, - levels: Object.fromEntries(ORDER.map((k) => [k, effects[k].level])), iceReach: effects.ice.reach()})}; + levels: Object.fromEntries(ORDER.map((k) => [k, effects[k].level])), iceReach: effects.ice.reach(), + wind: effects.wind.probe()})}; })(); - -
test:
+
test:
diff --git a/lib/web_dashboard.py b/lib/web_dashboard.py index c9a0fd7e..70adcc26 100644 --- a/lib/web_dashboard.py +++ b/lib/web_dashboard.py @@ -17,7 +17,8 @@ tile's specs.Tile fields and whether it is dimmed, with the time of the reading (`as_of`), the look, and the station's rain rate now (`rain_rate`, mm/h: its rain gauge's, or its piezo gauge's where that's the one reporting, which no tile shows; null with neither), for the page's rain behind the tiles; the past hour's highest of the dials with a thin red hand (`hour_highs`, by - title: Wind's gust, Rain rate's, Solar radiation's, UV index's: hour_highs()), and the gust now (`gust`, km/h); + title: Wind's gust, Rain rate's, Solar radiation's, UV index's: hour_highs()), and the gust now (`gust`, km/h: over 99, a new + reading sends a cow, a barn or a chicken across behind the tiles); - GET /dashboard/events: Server-Sent Events, a `readings` event whenever the gauges' readings in the station's kept live reading or the air sensor's latest change, told by the server's own change detection for ecobot://now/weather and ecobot://now/air (EcobotServer.publish_changes: nothing is fetched for it), so the page fetches the data again and moves its gauges in place. A diff --git a/tests/slow_tests.txt b/tests/slow_tests.txt index fe87993d..1a4128cc 100644 --- a/tests/slow_tests.txt +++ b/tests/slow_tests.txt @@ -59,6 +59,7 @@ tests/test_startup.py::test_the_weather_alerts_that_could_not_start_are_named_as tests/test_web_dashboard.py::test_a_click_on_a_gauge_zooms_its_tile_to_fill_the_window_the_tile_beside_it_live_and_the_keys_page tests/test_web_dashboard.py::test_a_double_click_esc_the_bounce_cut_short_the_keyboard_and_esc_mid_zoom tests/test_web_dashboard.py::test_a_flash_flood_fills_the_window_a_quarter_up_its_surface_choppy_what_falls_ending_at_it_and_a_frog_now_and_then +tests/test_web_dashboard.py::test_a_gust_over_99_kmh_blows_a_cow_a_barn_or_a_chicken_across_far_behind_the_tiles tests/test_web_dashboard.py::test_a_tile_with_no_reading_is_dimmed_at_its_floor_and_a_reading_coming_brightens_it_and_moves_it_up_in_place tests/test_web_dashboard.py::test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_reduced_motion tests/test_web_dashboard.py::test_every_effect_at_once_is_cheap_no_brighter_than_the_strongest_alone_and_within_the_particle_budget diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 8a013a2b..7110acb9 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -10,7 +10,8 @@ one canvas behind the tiles, "stop animation", reduced motion, the temporary test links and ?fx=, uv's beams swaying slowly in place with no particles, the wind's leaves within the budget and blowing right to left, rain in the wind bunched into curtains, its drops knocking the leaves they hit, humidity's fog and its beads, heavy rain's drops sticking to the glass, a flash flood filling the window -a quarter up, its waves, its leaves and its frog), the data's rain rate, and the +a quarter up, its waves, its leaves and its frog, a cow, a barn or a chicken blown across in a gust over 99 km/h), the data's rain +rate, and the dials' thin red hands at the past hour's highest (the wind's gust, rain rate, sun, UV: read from the file and the reading now, moving smoothly, at once with reduced motion) with the wind's Gust column. With ECOBOT_SCREENSHOTS set, its screenshots are kept in that folder.""" @@ -1041,7 +1042,7 @@ async def test_the_temporary_test_links_turn_each_effect_on_and_stop_animation_e # the temporary test links: each its effect and frame (the gauges keep their readings), the URL following; smog steps through its # bands, rain light then heavy; ice melts back; "stop animation" ends them all (no "clear"); no "all" link, but ?fx=all links = got["links"] - assert links["buttons"] == ["rain", "smog", "uv", "humidity", "wind", "heat", "ice"], links["buttons"] + assert links["buttons"] == ["rain", "smog", "uv", "humidity", "wind", "heat", "ice", "gust"], links["buttons"] on = [] for name in ("uv", "humidity", "wind", "heat", "ice"): on.append(name) @@ -1068,23 +1069,23 @@ async def test_the_temporary_test_links_turn_each_effect_on_and_stop_animation_e {"level": 0, "url": "?fx=uv,wind,heat", "label": "humidity"}], links["humiditySteps"] assert links["role"] == "group" and links["pressed"] == {"rain": "false", "smog": "false", "uv": "true", "humidity": "true", "wind": "true", "heat": "true", "ice": "false"}, links["pressed"] - # on a phone (360x740, 390x844), every effect on (its links' longest): no "test:", each link and "stop animation" in sight, + # on a phone (360x740, 390x844), every effect on (its links' longest): no "test:", each link ("gust" too) and "stop animation" in sight, # unscrolled, with room for one more short link (some 30 px); a link's step a raised figure, its full words its label for phone in (got["phone360"], got["phone390"]): assert not phone["tag"] and phone["fits"] and phone["spare"] >= 30 and phone["apart"] and phone["onScreen"], phone just_right_of_the_row(phone) for phone in (got["phone360"], got["phone390"]): assert phone["errors"] == [] and phone["link"] == "stop animation", phone - assert phone["buttons"] == ["rain²", "smog³", "uv", "humidity²", "wind", "heat", "ice"], phone["buttons"] - assert phone["labels"] == ["rain: heavy", "smog 3", "uv", "humidity: heavy", "wind", "heat", "ice"], phone["labels"] + assert phone["buttons"] == ["rain²", "smog³", "uv", "humidity²", "wind", "heat", "ice", "gust"], phone["buttons"] + assert phone["labels"] == ["rain: heavy", "smog 3", "uv", "humidity: heavy", "wind", "heat", "ice", "gust"], phone["labels"] assert phone["motion"]["bottom"] == pytest.approx(phone["strip"]["top"], abs=0.5), phone # (above the strip) assert phone["flood"] == ["rain³", "rain: flood"], phone["flood"] # (rain's third step) # MCP_DASHBOARD_ANIMATIONS off (the page as served then, data-animations="off"), every effect asked for (?fx=all) and called for by - # the readings, the animations not stopped in the browser: no loop, nothing drawn, no link, no test links; the tiles and the - # strip as ever + # the readings (a gust over 99 km/h and ?fx=gust too), the animations not stopped in the browser: no loop, nothing drawn, nothing + # blown across, no link, no test links; the tiles and the strip as ever off = got["off"] assert off["off"] == {"effects": off["off"]["effects"], "levels": off["off"]["levels"], "running": False, "framed": off["off"]["framed"], - "link": None, "frames": 0, "ink": 0, "sky": "none", "corner": "none", "row": False}, off["off"] + "link": None, "frames": 0, "ink": 0, "gust": 0, "sky": "none", "corner": "none", "row": False}, off["off"] assert off["off"]["effects"] == EVERY, off["off"] # (asked for all the same: just never drawn) assert off["tiles"] == titles_of(station) and off["strip"] == "last reading 18:42", off # a tile hidden: "reset preferences" in the strip as ever; still nothing drawn @@ -1108,7 +1109,7 @@ def just_right_of_the_row(corner): @needs_browser async def test_every_effect_at_once_is_cheap_no_brighter_than_the_strongest_alone_and_within_the_particle_budget(server, station): got = await weather(server, "all") - assert got["cost"] < 8, got["cost"] + assert got["cost"] < 8 and got["flying"] == 1, (got["cost"], got["flying"]) # (something blown across too: ?fx=all,gust) # ... the ice grown all the way in too, its frost across much of the glass: as cheap assert got["costFrosted"]["cost"] < 8 and got["costFrosted"]["crystals"] > 0.15, got["costFrosted"] # several at once no brighter than one strong one: every effect on (the ice grown all the way in), against Hazardous smog alone @@ -1122,7 +1123,7 @@ async def test_every_effect_at_once_is_cheap_no_brighter_than_the_strongest_alon async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_reduced_motion(server, station): got = await weather(server, "opened") # ?fx= when the page opens - assert got["param"]["levels"] == {"smog": 3, "heat": 0, "uv": 0, "rain": 0, "wind": 1, "humidity": 0, "flood": 0, "ice": 5} + assert got["param"]["levels"] == {"gust": 0, "smog": 3, "heat": 0, "uv": 0, "rain": 0, "wind": 1, "humidity": 0, "flood": 0, "ice": 5} assert sorted(got["param"]["framed"]) == ["Temperature", "US AQI", "Wind"] and got["param"]["errors"] == [] # (the effects' earlier names, in links saved before, still work: as wind, uv, humidity) assert got["paramOld"]["effects"] == ["uv", "wind", "humidity"] and got["paramOld"]["errors"] == [], got["paramOld"] @@ -1357,6 +1358,8 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red # ... and a flash flood's: full at once, still, no frog flood = still["flood"] assert flood["depth"] == flood["full"] > 0 and flood["frog"] is None and not flood["running"] and flood["frames"] == 0, flood + # ... and a gust (the page's, the test link's, asked for by name): nothing blown across, no loop + assert still["gust"] == {"fling": None, "sent": 0, "running": False, "frames": 0}, still["gust"] @needs_browser @@ -1418,3 +1421,52 @@ async def test_a_flash_flood_fills_the_window_a_quarter_up_its_surface_choppy_wh costly = linked["costly"] assert costly["effects"] == ["smog", "heat", "uv", "rain", "wind", "humidity", "flood", "ice"] and costly["cost"] < 8, costly assert sum(costly["particles"].values()) <= costly["budget"] + 3, costly + + +@needs_browser +async def test_a_gust_over_99_kmh_blows_a_cow_a_barn_or_a_chicken_across_far_behind_the_tiles(server, station): + got = await weather(server, "gust") + # the live gust: at 99 nothing; just over, one sent; the same reading fetched again, no more; a new one over, another; under, none + assert got["live"] == [0, 1, 1, 2, 2] and got["liveEffects"] == ["gust"], got["live"] + assert set(got["liveKinds"]) <= {"cow", "barn", "chicken"}, got["liveKinds"] + # a cow, a barn and a chicken at once: each right to left all the way across (in at the right, out at the left), every frame + # further left, in the window's upper part; large (a sixth of the window across or so) and faint (most pixels under half + # opaque), on the back layer, alone here; crossing in some 6-14 s of the weather's time + crossing = got["crossing"] + width, height, _ = crossing["size"] + assert crossing["kinds"] == ["cow", "barn", "chicken"] and crossing["effects"] == ["gust"], crossing + for kind, track in crossing["tracks"].items(): + xs, ys = [p[0] for p in track], [p[1] for p in track] + assert len(track) >= 30 and xs[0] > width and xs[-1] < 0 and all(b < a for a, b in zip(xs, xs[1:])), (kind, xs) + assert all(0 < y < 0.6 * height for y in ys), (kind, ys) + assert track[0][5] >= 50 and track[0][5] >= width / 7, (kind, track[0]) + assert 6 <= track[-1][6] - track[0][6] <= 14, (kind, track[0], track[-1]) + # the cow and the barn tumbling end over end, slowly (anticlockwise, rolling over leftward: 0.3-1 rad/s, more than a turn + # across); the chicken not: facing out, swaying a little (under 0.2 rad either way), its head turning a touch each way, its legs + # swinging through all their frames + for kind in ("cow", "barn"): + track = crossing["tracks"][kind] + angles, took = [p[2] for p in track], track[-1][6] - track[0][6] + assert all(b < a for a, b in zip(angles, angles[1:])), (kind, angles) + assert 0.3 <= (angles[0] - angles[-1]) / took <= 1 and angles[0] - angles[-1] > 3.2, (kind, angles[0], angles[-1], took) + chicken = crossing["tracks"]["chicken"] + assert all(abs(p[2]) <= 0.2 for p in chicken) and max(p[2] for p in chicken) - min(p[2] for p in chicken) > 0.1, chicken + assert {p[3] for p in chicken} == {-1, 0, 1} and {p[4] for p in chicken} == {0, 1, 2, 3}, chicken + assert crossing["inked"] > 1500 and 60 <= crossing["median"] <= 130, crossing + assert crossing["cost"] < 8, crossing["cost"] + # once they're gone: nothing left, nothing drawn, the loop ended + assert crossing["after"]["flyers"] == [] and crossing["after"]["bits"] == 0 and crossing["ink"] == 0 and not crossing["running"], crossing + # the test link: each click one more, at random (all three kinds in five clicks), ?fx=gust; not a switch: never pressed + link = got["link"] + assert link["sent"] == 5 and set(link["kinds"]) == {"cow", "barn", "chicken"} and link["flying"] >= 1, link + assert link["url"] == "?fx=gust" and link["pressed"] is None and "on" not in link["classes"].split(), link + # "stop animation": gone at once, nothing drawn, ?fx= gone; stopped, a gust sends none + assert got["stopped"] == {"flyers": 0, "running": False, "url": "", "ink": 0, "sent": 5}, got["stopped"] + # ?fx=gust as the page opens: one sent + opened = got["opened"] + assert opened["sent"] == 1 and opened["effects"] == ["gust"] and opened["url"] == "?fx=gust" and opened["errors"] == [], opened + # on a phone, every effect on and "gust" clicked: one sent; no "test:", every link ("gust" too) and "stop animation" in sight + phone = got["phone"] + assert phone["sent"] == 1 and phone["buttons"][-1] == "gust" and not phone["tag"] and phone["fits"] and phone["onScreen"], phone + just_right_of_the_row(phone) + assert got["errors"] == [] and phone["errors"] == [], (got["errors"], phone["errors"]) diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index f4d4e83e..765692d5 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -903,6 +903,8 @@ async function weatherPage(browser, url, options = {}) { const readings = { "US AQI": 40, ...state.readings }; for (const t of data.tiles) if (t.title in readings) t.value = readings[t.title]; if ("rain_rate" in readings) data.rain_rate = readings.rain_rate; + if ("gust" in readings) data.gust = readings.gust; // (the gust now, km/h) + if (readings.asOf) data.as_of = { ...data.as_of, time: readings.asOf }; // (a new reading: its time) if (readings.hour) Object.assign(data.hour_highs, readings.hour); // (the red hands' past hour) await route.fulfill({ response, json: data }); }); @@ -1221,9 +1223,10 @@ const framesIn = async (page, ms) => { // the frames the page asked for in thi // MCP_DASHBOARD_ANIMATIONS off (the page as ecobot-mcp serves it then: data-animations="off" on its ): every effect asked for // and called for, nothing drawn; the rest as ever async function animationsOff(browser, url, out) { - const { context, page, errors, reads } = await weatherPage(browser, url, { query: "?fx=all", animations: "off" }); - await reads({ "UV index": 11, Wind: 60, Temperature: -3, rain_rate: 2, Humidity: 97, "US AQI": 160 }); + const { context, page, errors, reads } = await weatherPage(browser, url, { query: "?fx=all,gust", animations: "off" }); + await reads({ "UV index": 11, Wind: 60, Temperature: -3, rain_rate: 2, Humidity: 97, "US AQI": 160, gust: 130 }); const seen = async () => ({ ...await weatherSeen(page), frames: await page.evaluate(() => Sky.state().frames), ink: await canvasInk(page), + gust: await page.evaluate(() => Sky.state().gust.sent), // (a gust over 99 km/h, and ?fx=gust: none sent) ...await page.evaluate(() => ({ sky: getComputedStyle(document.getElementById("sky")).display, corner: getComputedStyle(document.getElementById("corner")).display, row: !!document.getElementById("fxtest") && document.getElementById("fxtest").checkVisibility() })) }); @@ -1248,7 +1251,7 @@ async function animationsOff(browser, url, out) { // "all" (?fx=all: its frame time, its brightness against Hazardous smog alone, its particles), "opened" (?fx= when the page opens, uv // and the wind alone, heavy rain alone and in the wind (on a phone too), uv's beams over 40 s, humidity's beads running down the // glass alone and in the wind, a phone's strip, reduced motion), "flood" (a flash flood: its mark, its rise, its surface and waves, -// what ends at it, the test link's rain3, its leaves and its frog, its cost) +// what ends at it, the test link's rain3, its leaves and its frog, its cost), "gust" (something big blown across in a gust over 99 km/h) const WEATHER = { async marks(browser, url, out) { const { context, page, errors, reads } = await weatherPage(browser, url); @@ -1448,9 +1451,10 @@ const WEATHER = { }, async all(browser, url, out) { const particles = (p) => p.evaluate(() => ({ ...Sky.state().particles, budget: Sky.state().budget })); - const { context, page, errors } = await weatherPage(browser, url, { query: "?fx=all" }); + const { context, page, errors } = await weatherPage(browser, url, { query: "?fx=all,gust" }); await page.waitForTimeout(3000); - out.cost = await page.evaluate(() => Sky.state().cost); // (ms of script a frame, with every effect on) + out.cost = await page.evaluate(() => Sky.state().cost); // (ms of script a frame, with every effect on, and something blown across) + out.flying = await page.evaluate(() => Sky.state().gust.flyers.length); // the strongest single effect (Hazardous smog), as bright as "all" may be: faded in while the ice grows on const strongest = (async () => { const smog = await weatherPage(browser, url, { query: "?fx=smog5" }); @@ -1805,6 +1809,11 @@ const WEATHER = { const f = Sky.state().flood; return { depth: f.depth, full: f.full, frog: f.frog, running: Sky.state().running, frames: Sky.state().frames }; }); + out.still.gust = await still.page.evaluate(() => { // (a gust: nothing sent, by the page or the test link) + document.dispatchEvent(new Event("ecobot-gust")); + document.querySelector("#fxtest button[data-gust]").click(); + return { fling: Sky.fling("cow"), sent: Sky.state().gust.sent, running: Sky.state().running, frames: Sky.state().frames }; + }); out.still.errors = still.errors; await still.context.close(); await Promise.all([params, alone, phoned]); @@ -1815,6 +1824,90 @@ const WEATHER = { [out.bare, out.barePhone] = await bare; out.errors = []; }, + // A gust over 99 km/h: the live gust at 99 (nothing), just over (one sent), the same reading fetched again (no more), a new one over + // (another), one under (none); then a cow, a barn and a chicken sent at once, watched every frame as they cross (the weather's time + // 5 times as fast): where each is, its angle, the chicken's frames, the canvas's pixels while they cross (alone: theirs and their + // bits'), the loop ending once they're gone; the test link (five clicks, its URL, never pressed), "stop animation" (the wind's +// link on too, so it shows: they're gone at once), + // ?fx=gust as the page opens, and on a phone the row (every link, "gust" too, and "stop animation" in sight unscrolled). A frame + // sequence of the three crossing kept as screenshots (SHOTS, when given) + async gust(browser, url, out) { + const opened = (async () => { // (beside the rest) + const p = await weatherPage(browser, url, { query: "?fx=gust" }); + const seen = { ...await p.page.evaluate(() => ({ sent: Sky.state().gust.sent, kinds: Sky.state().gust.kinds, effects: Sky.state().effects })), + url: await p.page.evaluate(() => location.search), errors: p.errors }; + await p.context.close(); + return seen; + })(); + const phone = (async () => { + const p = await weatherPage(browser, url, { query: "?fx=all", context: { viewport: { width: 360, height: 740 }, hasTouch: true, isMobile: true } }); + await p.page.locator("#fxtest button[data-gust]").click(); + const seen = { ...await cornerSeen(p.page), sent: await p.page.evaluate(() => Sky.state().gust.sent), errors: p.errors }; + await p.context.close(); + return seen; + })(); + const { context, page, errors, reads } = await weatherPage(browser, url); + const sent = () => page.evaluate(() => Sky.state().gust.sent); + out.live = []; + for (const [gust, asOf] of [[99, "2026-11-16T10:00:00+11:00"], [99.1, "2026-11-16T10:01:00+11:00"], [99.1, "2026-11-16T10:01:00+11:00"], + [140, "2026-11-16T10:02:00+11:00"], [60, "2026-11-16T10:03:00+11:00"]]) { + await reads({ gust, asOf }); + out.live.push(await sent()); + } + out.liveKinds = await page.evaluate(() => Sky.state().gust.kinds); + out.liveEffects = await page.evaluate(() => Sky.state().effects); + // (the two on their way off first: the time on fast till they're gone) + await page.evaluate(() => Sky.timeScale(8)); + await page.waitForFunction(() => !Sky.state().running); + // a cow, a barn and a chicken at once, every frame till they're gone + out.crossing = await page.evaluate(() => new Promise((resolve) => { + Sky.timeScale(5); + const kinds = ["cow", "barn", "chicken"].map((k) => Sky.fling(k)), c = document.querySelector("#sky canvas"), g = c.getContext("2d"); + const tracks = { cow: [], barn: [], chicken: [] }, size = Sky.state().size; + const alphas = new Array(256).fill(0); // (the canvas's pixels by their alpha, while all three cross: how faint) + let frames = 0, inked = 0, effects = null, first = Sky.state().frames, last = first; + const look = () => { + const s = Sky.state(); + if (s.frames > last) { // (a frame drawn since the last look) + last = s.frames; + frames++; + for (const f of s.gust.flyers) tracks[f.kind].push([f.x, f.y, f.angle, f.turn, f.legs, f.size, s.clock]); + if (s.gust.flyers.length === 3 && frames % 8 === 1) { // (the canvas read now and then: reading it is slow) + effects = effects || s.effects; + const d = g.getImageData(0, 0, c.width, c.height).data; + let n = 0; + for (let i = 3; i < d.length; i += 4) if (d[i]) { n++; alphas[d[i]]++; } + inked = Math.max(inked, n); + } + } + if (s.running || frames === 0) return requestAnimationFrame(look); + Sky.timeScale(1); + const all = alphas.reduce((a, b) => a + b, 0); + let median = 0; + for (let k = 0, n = 0; k < 256; k++) if ((n += alphas[k]) >= all / 2) { median = k; break; } + resolve({ kinds, tracks, size, frames, median, strong: alphas.slice(160).reduce((a, b) => a + b, 0) / all, inked, effects, cost: s.cost, after: s.gust, running: s.running, + ink: (() => { const d = g.getImageData(0, 0, c.width, c.height).data; let n = 0; for (let i = 3; i < d.length; i += 4) if (d[i]) n++; return n; })() }); + }; + requestAnimationFrame(look); + })); + // the test link: each click one, the three kinds in three clicks; ?fx=gust; never pressed; "stop animation": gone at once + const before = await sent(); + for (let i = 0; i < 5; i++) await page.locator("#fxtest button[data-gust]").click(); + out.link = { sent: await sent() - before, kinds: (await page.evaluate(() => Sky.state().gust.kinds)).slice(-5), + flying: await page.evaluate(() => Sky.state().gust.flyers.length), url: await page.evaluate(() => location.search), + pressed: await page.evaluate(() => document.querySelector("#fxtest button[data-gust]").getAttribute("aria-pressed")), + classes: await page.evaluate(() => document.querySelector("#fxtest button[data-gust]").className) }; + await page.locator("#fxtest button[data-fx='wind']").click(); // (an effect on: "stop animation" shows) + await page.locator("#motion .animations").click(); + out.stopped = { ...await page.evaluate(() => ({ flyers: Sky.state().gust.flyers.length, running: Sky.state().running })), + url: await page.evaluate(() => location.search), ink: await canvasInk(page) }; + await page.evaluate(() => document.dispatchEvent(new Event("ecobot-gust"))); // (stopped: none sent) + out.stopped.sent = await sent() - before; + out.errors = errors; + await context.close(); + out.opened = await opened; + out.phone = await phone; + }, }; async function weatherMode(browser, url, part) { From 20cbfb3491c5fb428f0377f400c080ec213ffb52 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:46:11 +0000 Subject: [PATCH 044/146] Web dashboard: natural bead trails. On clear glass (a rain bead's, or any bead off the fog) a trail is no longer a bead-wide haze band with dashes of glint: it is a thin, dirty wet streak, a px or two (a third of the bead's width or less), wandering a little within the bead's width; its thickness rising and falling along it (smooth noise, a little jitter), now and then broken for 1-3 px (then 12 px at least unbroken: no regular pattern); mostly a faint greyish film, grime (a darker grey) along its right edge here and there, a glint now and then, a few tiny droplets left on it (some with a spark); where the bead paused, a slightly wider blob (and often a droplet), never a gap. It dries from its thin parts and its old end first (each pixel shows while the trail is fresher than the streak is thin there), the droplets and thick core last. Through the fog a trail is still about the bead's width (following it as it grew or shrank) but natural: its edges ragged (each a px in or out, wandering down it; a px wider or narrower than the bead at most), the fog coming back at those edges first so it refogs unevenly from the edges inward, specks of fog left unwiped in streaks down it (columns of the bead's, faded in and out), and a few tiny droplets left in it till the fog is back. The physics stays as it was: the beads feel the trail they always did (its own width evenly wiped; the ragged edge's px past it are look only, never over a trail the beads feel), so speeds, growth, shrinking and the 3-10 minute lives are unchanged. Sky.state().humidity gains trailOf(id) (a bead's latest rows as they look). Tests: in the existing sessions, each running bead's fresh trail as it looks (its own rows): clear-glass streaks thin (mean at most a third of the bead's width, a blob at most a little wider), uneven along their length, broken a little at most and never in a regular pattern; fog trails about bead-wide all along, never a gap, their edges moving; the clear streak's colours, its thin parts gone from view well before the trail is dry and the thick ones near the end (several pixels down each streak, time 120 times as fast); the fog trail's inside mostly wiped clear, otherwise only a speck of the faintest fog or a droplet; the wiped width about the bead's (ragged) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 138 ++++++++++++++++++++++++++------- tests/test_web_dashboard.py | 49 ++++++++++-- tests/web_dashboard_browser.js | 70 +++++++++++++---- 3 files changed, 205 insertions(+), 52 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 6a84286a..830ada06 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -162,7 +162,8 @@ // over), bands, physics: {speed(r, glass): px/s, after(r, glass, px, s, fog): its radius after (0: gone), gone}, hasten(k): the // trails' time k times as fast (test-only), clock(): the trails', wetAt(x, y): how fresh a trail is there (1 just left, 0 none), // lifeAt(x, y): its life, glassAt(x, y): "dry", "trail" or "fog", fogAt(x, y): [its fog as shown, its fog not wiped] (0-1), -// shownAt(x, y): what the fog's canvas shows there [r, g, b, alpha], fog(): {cover: how far formed, 0-1, dense, thickness, +// shownAt(x, y): what the fog's canvas shows there [r, g, b, alpha], trailOf(id): a bead's trail as it looks now, its latest rows +// ({y, w, left, wet, alpha, life, fog}: see the probe), fog(): {cover: how far formed, 0-1, dense, thickness, // middle, edge: its mean shown, over the window, its middle and its edges, opacity: its mean alpha as drawn (0-1), most: its // thickest shade's alpha, haze: its mean not wiped inside (the window less its outer sixth), spread: its standard deviation there // over that, gaps: the pixels there under half that}, colours(): the beads' sprites' colours [r, g, b, alpha], stray(): pixels on @@ -846,8 +847,12 @@ // Its size (its water: continuous, no largest): on fog it gathers the fog it passes (GATHER a px, CONDENSE a s as it sits; the // fog wiped) and grows; on a trail it keeps its size; on dry glass, only there, it shrinks, leaving its water behind (LEAVE a px, // EVAPORATE a s). Shrunk to nothing (GONE): gone. Two that touch merge, their water adding up (the fastest way to grow). - // Its trail: as wide as it is, wherever it runs: through fog a clear streak wiped, on clear glass a faint wet one with a glint - // down its lit side; each fogging over again (or drying) over its own LIFE (3 to 10 minutes; crisp for its first 1 - CRISP). + // Its trail: through fog a streak wiped about as wide as it is (its width as it grew or shrank), its edges soft and ragged, a + // little fog left in it in streaks down it, a few tiny droplets; on clear glass a thin, dirty wet streak (a px or two: a third + // of its width or less), uneven along it (thicker, thinner, broken here and there), a greyish film with grime along an edge here + // and there, a glint now and then, a few tiny droplets; where it paused, a slightly wider blob, never a gap. Each fogging over + // again (from its ragged edges inward) or drying (its thin parts first) over its own LIFE (3 to 10 minutes; crisp for its first + // 1 - CRISP). (The beads feel it as before: the glass under them evenly wiped, see feltOf.) // Reaching the window's bottom edge, it runs off it: gone. // The humidity falling below 90 % (the effect off): the fog clearing as from a demister, the middle first and the edges last over // CLEAR s, each condensed bead still slow (under QUICK px/s on fog) drying away (shrinking and fading) as the clearing reaches it, @@ -935,8 +940,11 @@ // 0-1); its canvas and image, as painted last (at drawn: [cover, dense]; key: what each pixel shows there, see look()) let base = null, ring = null, cover = 0, dense = 0, drawn = [0, 0], layer = null, img = null, key = null; // The trails: each pixel's, on the trails' own clock (`clock`, its pace `hasten` for the tests): when it's gone (till) and how long - // it lasts all told (life), so how fresh it is now (wetOf, 1 just left, 0 gone); its lit side (shine); on the list or not - let till = null, life = null, listed = null, shine = null, trails = [], sweep = 0, clock = 0, hasten = 1; + // it lasts all told (life), so how fresh it is now (wetOf, 1 just left, 0 gone); on the list or not. How it looks (as left: see + // wipe()): on clear glass, its part in the thin streak (part: none, film, grime, glint, a droplet or a droplet's spark) and how + // thick the streak is there (thick, 0-255: the thin parts dry first); through fog, how near its ragged edge (rim, 0-255: the fog + // coming back there first) and the fog left unwiped there (smear, 0-255) + let till = null, life = null, listed = null, ghost = null, part = null, thick = null, rim = null, smear = null, trails = [], sweep = 0, clock = 0, hasten = 1; let dirty = null, painting = 0, level = 0, fresh = 0, quiet = false; // (for the tests, as Sky.state() gives them) const seen = {merges: 0, merged: [], absorbed: [], left: [], ranOff: 0, shrunk: 0, faded: 0, largest: 0, born: [], first: null, @@ -948,12 +956,19 @@ const thickness = (v) => 0.5 + 0.5 * v; // the fog at a level (90 %: 0, 100 %: 1), at most const front = (i, c) => clamp((c - (1 - ring[i]) * 0.65) / 0.35, 0, 1); // how far the fog has formed at a pixel (c: cover) const wetOf = (i) => (listed[i] ? Math.max(0, (till[i] - clock) / life[i]) : 0); // how fresh a trail is there + // How far the fog has come back over a trail's pixel (0 wiped clear, 1 as if never wiped): clear while it's fresh (CRISP), then + // back gradually; at its ragged edges sooner (from the start right at them), so it closes in from the edges unevenly + // (rim 255: a px of the bead's own width its ragged edge left in, the fog barely wiped there) + const refog = (i) => Math.max(rim[i] === 255 ? 0.6 : 0, 1 - Math.min(1, wetOf(i) / Math.min(1.1, CRISP * 0.95 + 0.32 * rim[i] / 255))); // A pixel's fog (0-1), as it is (cover c, dense d; wiped: as a trail has left it) or, not wiped, as it would be - const fogOf = (i, c, d, wiped) => d * base[i] * front(i, c) * (wiped && listed[i] ? 1 - Math.min(1, wetOf(i) / CRISP) : 1); + const fogOf = (i, c, d, wiped) => d * base[i] * front(i, c) * (wiped && listed[i] ? refog(i) : 1); + // ... and as the beads feel it (the glass under them): the trail evenly wiped, the fog back evenly after its crisp start + // (its ragged edge's px out past the bead's width, ghost, not felt) + const feltOf = (i) => dense * base[i] * front(i, cover) * (listed[i] && !ghost[i] ? 1 - Math.min(1, wetOf(i) / CRISP) : 1); const at = (x, y) => Math.round(clamp(y, 0, H - 1)) * W + Math.round(clamp(x, 0, W - 1)); const glassAt = (x, y) => { // (a trail while it's less than half fogged over again) - const i = at(x, y), f = fogOf(i, cover, dense, true); - if (listed[i] && wetOf(i) > 0) { const full = fogOf(i, cover, dense, false); if (full < FOG_AT || f < 0.5 * full) return TRAIL; } + const i = at(x, y), f = feltOf(i); + if (listed[i] && !ghost[i] && wetOf(i) > 0) { const full = fogOf(i, cover, dense, false); if (full < FOG_AT || f < 0.5 * full) return TRAIL; } return f >= FOG_AT ? FOGGY : DRY; }; function grain() { // the fog's pattern for the window's size: a fairly even haze, gently varied, a little denser at the edges @@ -971,18 +986,28 @@ } } const LIFT = Float32Array.from({length: 257}, (_, j) => (j / 256) ** 0.8); // (a thin haze still seen: t ** 0.8, looked up) - const WET = 8; // (a wet streak's shades, faint to fresh) + // A trail's looks, each in WET shades (faint to fresh), [colour, alpha at the faintest, at the freshest]: on clear glass a thin wet + // film, greyish; grime, darker, along its edge here and there; a glint now and then; a tiny droplet left on it (or in a trail + // through the fog), now and then its spark + const WET = 8, FILM = 1, GRIME = 2, GLINT = 3, DROP = 4, SPARK = 5; + const LOOKS = [[rgb("#8E9DA8"), 8, 34], [rgb("#4C5861"), 22, 66], [WATER[4], 16, 78], [WATER[3], 34, 104], [WATER[4], 60, 150]]; const SHOWS = [[0, 0, 0, 0], ...FOG.map((c, s) => [...c, FOG_ALPHA[s]]), - ...Array.from({length: WET}, (_, k) => [...WATER[3], Math.round(3 + 11 * (k + 1) / WET)]), // (its body) - ...Array.from({length: WET}, (_, k) => [...WATER[4], Math.round(14 + 66 * (k + 1) / WET)])]; // (its glint) - // What a pixel shows (an index of SHOWS): nothing, a fog shade, or a trail's wet streak on clear glass (its glint down its lit side) + ...LOOKS.flatMap(([c, a, b]) => Array.from({length: WET}, (_, k) => [...c, Math.round(a + (b - a) * k / (WET - 1))]))]; + const showing = (p, k) => 1 + FOG.length + (p - 1) * WET + k - 1; // (part p's shade k, 1 to WET) + // What a pixel shows (an index of SHOWS): nothing, a fog shade, or a trail's look. Through the fog: the fog shown as it is (wiped, + // coming back), a speck of it left here and there where the bead didn't wipe it clean (smear), a droplet left in it. On clear glass + // (no fog to wipe): its thin streak, each pixel there while the trail is fresher than the streak there is thin (the thin parts and + // its ends going first), fainter as it dries function look(i, x, y) { const t = base[i] > 0 ? fogOf(i, drawn[0], drawn[1], true) : 0; + const p = listed[i] ? part[i] : 0, wet = p ? wetOf(i) : 0, full = listed[i] && base[i] > 0 ? fogOf(i, drawn[0], drawn[1], false) : 0; + if (p >= DROP && wet > 0 && t <= 0.6 * full) return showing(p, clamp(Math.ceil(wet * WET), 1, WET)); // (till the fog's back) if (t > 0) { const s = shadeOf(LIFT[(t * 256) | 0], x, y, FOG.length); if (s >= 0) return 1 + s; } if (!listed[i]) return 0; - const bare = 1 - Math.min(1, (base[i] > 0 ? fogOf(i, drawn[0], drawn[1], false) : 0) / 0.1); // (clear glass: no fog wiped) - const k = Math.min(WET, Math.ceil(wetOf(i) * bare * WET)); - return k <= 0 ? 0 : 1 + FOG.length + (shine[i] ? WET : 0) + k - 1; + if (full >= FOG_AT) return smear[i] && hash(x, y, 77) * 255 < smear[i] ? 1 + (hash(x, y, 78) < 0.2 && full > 0.4 ? 1 : 0) : 0; + const q = wet * (1 - Math.min(1, full / 0.1)), s = thick[i] / 255; // (clear glass: no fog wiped) + if (!p || q <= 0.85 * (1 - s)) return 0; + return showing(p, Math.min(WET, Math.max(1, Math.ceil(q * (0.45 + 0.55 * s) * 1.2 * WET)))); } function put(i, x = i % W, y = (i / W) | 0) { // a pixel of the fog's image, as it is now (as painted last: drawn) const k = look(i, x, y); @@ -1002,21 +1027,55 @@ for (let y = 0, i = 0; y < H; y++) for (let x = 0; x < W; x++, i++) put(i, x, y); flush(); } - // A trail left at (x, y): fresh (v: 1, or a little less at its sides, gone sooner), lasting `span` s all told; lit (its glint). - // (The latest bead to pass, its trail there, whatever was before) - const lay = (x, y, v, span, lit) => { + // A trail left at (x, y): fresh (v: 1, or a little less at its sides, gone sooner), lasting `span` s all told; its looks (p: its + // part, k: thick, e: rim, m: smear, see above). (The latest bead to pass, its trail there, whatever was before) + const lay = (x, y, v, span, p, k, e, m, g = 0) => { // (g: a ghost, its look only: never over a trail the beads feel) if (x < 0 || x >= W || y < 1 || y >= H) return; const i = y * W + x; + if (g && listed[i] && !ghost[i] && wetOf(i) > 0) return; if (!listed[i]) { listed[i] = 1; trails.push(i); } - till[i] = clock + v * span; life[i] = span; shine[i] = lit ? 1 : 0; + till[i] = clock + v * span; life[i] = span; ghost[i] = g; part[i] = p; thick[i] = k; rim[i] = e; smear[i] = m; put(i, x, y); }; - // A bead's trail across one row: as wide as its sprite where it's drawn; its lit side (the left), glinting in dashes + // A bead's trail across one row, as it looks wherever it runs (the glass's own, clear or fogged, deciding which shows; see look()): + // Through the fog: wiped as wide as its sprite where it's drawn, its edges ragged (each a px in or out, wandering down the + // trail; a px wider or narrower at most), the fog coming back first right at them; specks of fog left unwiped in streaks down + // it (columns of the bead's, faded in and out along it); now and then a tiny droplet left in it. + // On clear glass: a thin streak (a third of its width or less: a px or two) down its middle, wandering a little within it; its + // thickness rising and falling along it (thicker, thinner, now and then broken for a px or three: no regular pattern), so the + // thin parts dry first; mostly a greyish film, grime here and there along its right edge, a glint now and then, a few tiny + // droplets left on it. Where it paused: a little wider there (a blob, a droplet), never a gap. const wipe = (b, y) => { - const w = b.laidW = sprite(b.r).width, left = Math.round(b.x) - (w >> 1), mid = left + (w - 1) / 2; - for (let x = left; x < left + w; x++) { - lay(x, y, 1 - 0.1 * Math.abs(x - mid) / Math.max(1, w / 2), b.life, w >= 3 && x === left + 1 && ((y + 5 * b.id) % 11) < 3); + const w = b.laidW = sprite(b.r).width, left = Math.round(b.x) - (w >> 1), mid = left + (w - 1) / 2, id = b.id; + const jag = (s) => Math.round((noise(y / 2, id * 5 + s, 1 << 20, 61) - 0.5) * 3.2); // (an edge: -1, 0 or 1 px, wandering) + let a = left + clamp(jag(0), -1, 1), c = left + w - 1 + clamp(jag(1), -1, 1); + if (c - a + 1 < Math.max(1, w - 1)) [a, c] = [left, left + w - 1]; + else if (c - a + 1 > w + 1) c--; // (a px wider than the bead at most) + const n = noise(y / 5.5, id * 3, 1 << 20, 62); + // (a break: 3 px at most, then 12 px at least unbroken) + const broken = noise(y / 3.1, id * 3, 1 << 20, 63) < 0.14 && (b.gap || 0) < 3 && !(b.solid > 0); + if (broken) b.gap = (b.gap || 0) + 1; + else { if (b.gap) b.solid = 12; b.gap = 0; b.solid = (b.solid || 0) - 1; } + const rest = b.rested || 0; + b.rested = 0; + const blob = rest > 0.35 ? 0.9 : 0; + const wide = broken && !blob ? 0 : clamp(Math.min(1.35, Math.max(0.8, w * 0.2)) * (0.25 + 1.4 * n) * (0.75 + 0.5 * hash(y, id, 68)), 0.5, 2.2) + blob; + const sway = (noise(y / 11, id * 3 + 1, 1 << 20, 64) - 0.5) * Math.max(0, w - 3) * 0.55, at = mid + sway; + const drop = hash(y, id, 65) < (blob ? 0.7 : 0.05) ? Math.round(at + (hash(y, id, 66) - 0.5) * Math.max(1, w * 0.45)) : null; + for (let x = Math.min(a, left); x <= Math.max(c, left + w - 1); x++) { // (its own width, as the beads feel it; its ragged edge) + const cov = Math.max(clamp(wide / 2 + 0.5 - Math.abs(x - at), 0, 1), wide > 0 && x === Math.round(at) ? 0.45 : 0), h = hash(x, y, id); + let p = 0, k = 0; + if (cov >= 0.4) { + k = Math.round(255 * clamp(cov * (0.5 + 0.5 * n) + 0.25 * blob, 0.05, 1)); + p = h < 0.045 ? GLINT : x > at && (cov < 1 || x >= at + wide / 2 - 0.5) && h < 0.4 ? GRIME : FILM; + } + if (x === drop) { p = hash(x, y, id + 9) < 0.35 ? SPARK : DROP; k = 255; } + const edge = Math.min(x - a, c - x), e = edge < 0 ? 1 : edge === 0 ? 0.75 + 0.24 * h : edge === 1 ? 0.1 + 0.15 * h : 0.1 * h; + const m = Math.max(0, noise((x - left) * 1.7 + id * 13, y / 9, 1 << 20, 67) - 0.58) * 2.4 + (edge <= 1 ? 0.08 : 0); + lay(x, y, 1 - 0.1 * Math.abs(x - mid) / Math.max(1, w / 2), b.life, p, k, Math.round(255 * e), Math.round(255 * Math.min(0.45, m)), + x < left || x >= left + w ? 1 : 0); } + if (b.rows) { b.rows.push([y, a, c, left, w]); if (b.rows.length > 80) b.rows.shift(); } }; function age(dt) { // the trails' clock on; a slice of them looked at again (all every REDRAW s): gone ones off the list clock += dt * hasten; @@ -1024,7 +1083,7 @@ while (todo-- > 0 && trails.length) { if (sweep >= trails.length) sweep = 0; const i = trails[sweep]; - if (till[i] <= clock) { listed[i] = 0; shine[i] = 0; trails[sweep] = trails[trails.length - 1]; trails.pop(); seen.dried++; } + if (till[i] <= clock) { listed[i] = 0; trails[sweep] = trails[trails.length - 1]; trails.pop(); seen.dried++; } else sweep++; put(i); } @@ -1068,7 +1127,7 @@ const PAUSES = [[0.75, 0.6, 2.6], [0.25, 0.15, 0.8], [0.4, 0.3, 1.2]]; // (after a stretch, on each glass: how often, how long) function shows(b) { // on the glass now: running from here b.vol = b.r ** 3; - Object.assign(b, {state: "on", x0: b.x, y0: b.y, slant: 0, bend: between(3, 10), pause: between(0, 1), on: false, v: 0, g: FOGGY, + Object.assign(b, {state: "on", x0: b.x, y0: b.y, slant: 0, bend: between(3, 10), pause: between(0, 1), on: false, v: 0, g: FOGGY, rows: [], laid: Math.floor(b.y) + (heightOf(b.r) >> 1), shown: 0}); pace(b); } @@ -1108,9 +1167,9 @@ let time = dt; while (time > 1e-6 && !b.gone) { const cx = Math.round(b.x), below = Math.floor(b.y) + heightOf(b.r), g = glassAt(cx, below); - const f = g === FOGGY ? fogOf(at(cx, below), cover, dense, true) : 0; + const f = g === FOGGY ? feltOf(at(cx, below)) : 0; b.g = g; - if (b.pause > 0) { const p = Math.min(b.pause, time); b.pause -= p; time -= p; b.v = 0; account(b, g, f, 0, p); } + if (b.pause > 0) { const p = Math.min(b.pause, time); b.pause -= p; time -= p; b.v = 0; b.rested = (b.rested || 0) + p; account(b, g, f, 0, p); } else { const v = speedFor(b.r, g) * b.base, dy = Math.min(v * time, 1, b.run + 1e-3), s = Math.min(time, dy / v); time -= s; @@ -1181,7 +1240,7 @@ const dries = (b) => { b.state = "fade"; b.fadeFor = b.left = fadeFor(b.r); b.r1 = b.r; }; function clear() { // the glass fresh: no fog, nothing beading, running or wet all = []; splashes = []; trails = []; sweep = 0; painting = 0; seeded = false; cover = 0; dense = 0; fresh = 0; seen.first = null; - if (listed) { listed.fill(0); shine.fill(0); key.fill(0); img.data.fill(0); drawn = [0, 0]; dirty = null; layer.getContext("2d").clearRect(0, 0, W, H); } + if (listed) { listed.fill(0); key.fill(0); img.data.fill(0); drawn = [0, 0]; dirty = null; layer.getContext("2d").clearRect(0, 0, W, H); } } const heavy = () => rain.level >= HEAVY_RAIN; const present = () => e.level > 0 || cover > 0 || all.length > 0 || heavy(); @@ -1220,7 +1279,11 @@ till = new Float64Array(W * H); life = new Float32Array(W * H); listed = new Uint8Array(W * H); - shine = new Uint8Array(W * H); + part = new Uint8Array(W * H); + thick = new Uint8Array(W * H); + rim = new Uint8Array(W * H); + smear = new Uint8Array(W * H); + ghost = new Uint8Array(W * H); key = new Uint8Array(W * H); grain(); layer = canvasOf(W, H); @@ -1308,6 +1371,20 @@ glassAt: (x, y) => (base ? GLASSES[glassAt(x, y)] : null), fogAt: (x, y) => (base && x >= 0 && x < W && y >= 0 && y < H ? [fogOf(y * W + x, cover, dense, true), fogOf(y * W + x, cover, dense, false)] : [0, 0]), shownAt: (x, y) => (key && x >= 0 && x < W && y >= 0 && y < H ? SHOWS[key[y * W + x]].slice() : null), + // (a bead's trail as it looks now, its latest rows (up to 80): each {y, w: the bead's width then, left: its + // sprite's left then, wet: how fresh at its middle, mine: its own trail still there (not another bead's since, over + // it), then from left - 3 to left + w + 2: alpha: as shown on the fog's + // canvas, life: its trail's life (0 none: which trail it is), fog: [as shown, not wiped] (0-1)}) + trailOf: (id) => { + const b = all.find((b) => b.id === id); + return !b || !b.rows ? [] : b.rows.map(([y, , , left, w]) => { + const xs = Array.from({length: w + 6}, (_, k) => left - 3 + k).map((x) => clamp(x, 0, W - 1)); + const m = at(left + (w - 1) / 2, y); + return {y, w, left, wet: wetOf(m), mine: !!listed[m] && life[m] === Math.fround(b.life), alpha: xs.map((x) => SHOWS[key[y * W + x]][3]), + life: xs.map((x) => (listed[y * W + x] ? life[y * W + x] : 0)), + fog: xs.map((x) => [fogOf(y * W + x, cover, dense, true), fogOf(y * W + x, cover, dense, false)])}; + }); + }, fog: fogNow, colours: () => { // (every colour in the beads' sprites: [r, g, b, alpha]) const found = new Set(); @@ -1329,7 +1406,8 @@ }, beads: all.filter((b) => b.state !== "rest").map((b) => { const h = heightOf(b.r), cx = Math.round(b.x), top = Math.floor(b.y); - const trail = [0, -1, 1].map((dx) => [cx + dx, top - 1]).find(([x, y]) => x >= 0 && y >= 0 && wetOf(at(x, y)) > 0 && y < H); + const near = [0, -1, 1].map((dx) => [cx + dx, top - 1]).filter(([x, y]) => x >= 0 && y >= 0 && wetOf(at(x, y)) > 0 && y < H); + const trail = near.find(([x, y]) => rim[at(x, y)] !== 255 && !ghost[at(x, y)]) || near[0]; // (wiped: not its ragged edge) return {id: b.id, kind: b.kind, x: b.x, x0: b.x0, y: b.y, y0: b.y0, cy: b.y + h / 2, r: b.r, vol: b.vol, w: sprite(b.r).width, laidW: b.laidW || null, bottom: top + h, glass: GLASSES[b.g], v: b.state === "on" ? b.v : 0, fading: b.state === "fade", alpha: (b.state === "fade" ? b.left / b.fadeFor : 1) * Math.min(1, b.shown / APPEAR), drawn: b.drawn || null, diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 7110acb9..65fce470 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -968,6 +968,8 @@ async def test_on_a_touch_screen_a_tap_zooms_a_swipe_pages_from_anywhere_and_a_t # ---------- the weather behind the tiles ---------- +STREAK = [[142, 157, 168], [76, 88, 97], [239, 250, 255]] # a trail's thin streak on clear glass: its film, grime, glint +DROPLET = [[166, 215, 242], [239, 250, 255]] # a tiny droplet left on a trail, its spark EFFECTS = {"rain": "Rain", "smog": "US AQI", "uv": "UV index", "humidity": "Humidity", "wind": "Wind", "heat": "Temperature", "ice": "Temperature"} @@ -1209,17 +1211,29 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red # ... nothing at all drawn in the canvas's top two rows (humidity alone: no water along the top edge) assert got["humidity"]["alone"]["top"] == 0, got["humidity"]["alone"] # ... the fog: forming first (the first bead only once it has, there and on the glass at large), its trails wiped clear through it - # as wide as the bead was there (a px more where another's beside it), clearer than the fog beside them (where there is fog); the - # beads' colours as ever (the glass: the deep blue rim, a faint pale body, a crescent, a white glint) + # about as wide as the bead was there (its edges ragged: a px in or out; a px more where another's beside it), clearer than the + # fog beside them (where there is fog); the beads' colours as ever (the glass: the deep blue rim, a faint pale body, a crescent, a + # white glint) for name, beads in got["humidity"].items(): first = beads["first"] assert first["after"] >= 2 and first["cover"] >= 0.3 and first["fog"] > 0.2 and first["formed"]["edge"] > 0.2, (name, first) wiped = beads["wiped"] - assert len(wiped) >= 8 and all(t["shown"] == 0 and t["wet"] > 0.85 for t in wiped), (name, wiped) - assert all(0 <= t["across"] - t["w"] <= 1 for t in wiped), (name, [t for t in wiped if not 0 <= t["across"] - t["w"] <= 1]) + # (wiped clear, or near its ragged edge all but: the fog already creeping back there a little) + assert len(wiped) >= 8 and all(t["shown"] <= 0.25 * t["fog"] and t["wet"] > 0.85 for t in wiped), (name, wiped) + assert sum(t["shown"] == 0 for t in wiped) >= 0.3 * len(wiped), (name, wiped) + assert all(-1 <= t["across"] - t["w"] <= 3 for t in wiped), (name, [t for t in wiped if not -1 <= t["across"] - t["w"] <= 3]) fogged = [t for t in wiped if t["fog"] > 0.05 and t["beside"] > 0.05] assert len(fogged) >= 5 and all(t["beside"] > t["shown"] for t in fogged), (name, wiped) assert sum(t["end"]["wet"] < t["wet"] for t in wiped) >= 0.75 * len(wiped), (name, wiped) # (fogging over again, slowly) + # (natural trails through the fog, as they look while fresh: about the bead's width all along (its width as it grew), never + # a gap; their edges ragged, each wandering a px in or out down the trail, not straight) + fog_trails = [t for t in beads["looks"] if t["kind"] == "fog"] + assert len(fog_trails) >= 6, (name, beads["looks"]) + for t in fog_trails: + assert min(t["widths"]) >= 1 and abs(sum(t["widths"]) / len(t["widths"]) - t["w"]) <= 1.5, (name, t) + moves = [sum(a != b for a, b in zip(edge, edge[1:])) for edge in (t["lefts"], t["rights"])] + assert len(set(t["lefts"] + t["rights"])) >= 2 and sum(moves) >= 0.1 * len(t["lefts"]), (name, t) + assert len(set(t["widths"])) >= 2, (name, t) colours = sorted(beads["colours"], key=lambda c: c[3]) assert len(colours) == len(BEAD_COLOURS) and all(c == pytest.approx(want, abs=3) for c, want in zip(colours, BEAD_COLOURS)), (name, colours) # ... the trails through the fog, their time run on fast: each fogging over again all the way in 3 to 10 minutes (each trail its @@ -1229,7 +1243,11 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red lasted = [t["lasted"] for t in refog] assert len(refog) >= 10 and all(170 <= t <= 610 for t in lasted) and max(lasted) - min(lasted) > 150, refog assert all(t["crispTill"] is not None and t["crispTill"] < 0.25 * t["lasted"] for t in refog), refog - assert all(t["fog"][0] == t["fog"][1] > 0 and t["look"] == [0, 0, 0, 0] for t in refog), refog + assert all(t["fog"][0] == t["fog"][1] > 0 for t in refog), refog + # (as it was picked, inside the trail, fresh: wiped clear mostly; here and there a speck of the fog left unwiped (its two + # faintest shades) or a tiny droplet left in it, no more) + assert sum(t["look"] == [0, 0, 0, 0] for t in refog) >= 0.5 * len(refog), refog + assert all(t["look"] in ([0, 0, 0, 0], [50, 60, 67, 56], [74, 85, 92, 69]) or t["look"][:3] in DROPLET for t in refog), refog # ... light (91 %): a thinner fog than heavy (100 %), fewer beads, the fog first all the same light, heavy = got["humidityLight"], got["humidity"]["alone"] assert light["errors"] == [] and light["popped"] == 0 and light["stray"] == 0, light @@ -1279,8 +1297,10 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red # heavy rain's beads: light rain none; heavy, a drop sticking now and then, a handful on the glass at most, each landing at once # (no fading in) as a large bead (r 3 or more) with a splash (a ring of 10 or more droplets); on dry glass slow (about 0.3 of its # speed on fog, the same size), shrinking only (its water left behind), never growing; none vanishing; their wet streaks on the - # clear glass (faint, pale: the glass's body colour, or its glint) drying over 3 to 10 minutes, each its own. The rain light again: - # none sticking; those there running off or shrinking away + # clear glass drying over 3 to 10 minutes, each its own: thin streaks (a third of the bead's width or less: a px or two), faint + # (a greyish film, grime along an edge, a glint, a tiny droplet), uneven along their length (thicker and thinner, now and then + # broken for a px or three, never more, no regular pattern of gaps: no dashes), their thin parts drying first (gone from view + # well before the trail is dry), the thick ones last. The rain light again: none sticking; those there running off or shrinking away sticking = got["rainBeads"] assert sticking["errors"] == [] and sticking["light"] == {"landed": 0, "levels": 0.35}, sticking heavy_rain = sticking["heavy"] @@ -1292,7 +1312,20 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert heavy_rain["glass"]["fog"]["moves"] == 0, heavy_rain["glass"] # (no fog: rain alone) drying = [t["lasted"] for t in sticking["drying"]] assert len(drying) >= 2 and all(170 <= t <= 610 for t in drying), sticking["drying"] - assert all(t["look"][:3] in ([166, 215, 242], [239, 250, 255]) and 0 < t["look"][3] <= 80 for t in sticking["drying"]), sticking["drying"] + assert all(t["look"][:3] in STREAK + DROPLET and 0 < t["look"][3] <= (150 if t["look"][:3] in DROPLET else 80) for t in sticking["drying"]), sticking["drying"] + hidden = sorted(t["hidden"] for t in sticking["drying"]) + assert hidden[0] < 0.75 and hidden[-1] > 0.7, sticking["drying"] + streaks = list({t["id"]: t for t in sticking["looks"] if t["kind"] == "clear"}.values()) # (each bead's once) + assert len(streaks) >= 2 and all(t["kind"] == "clear" for t in sticking["looks"]), sticking["looks"] + for t in streaks: + widths = t["widths"] + assert sum(widths) / len(widths) <= max(1.6, t["w"] / 3) and max(widths) <= t["w"] / 2 + 1.5, t # (thin: a px or two; a blob) + assert len(set(widths)) >= 2 and max(widths) - min(widths) >= 1, t # (uneven along it) + empty = [w == 0 for w in widths] + runs = [len(r) for r in "".join("x" if e else "." for e in empty).split(".") if r] + assert sum(empty) <= 0.25 * len(widths) and max(runs, default=0) <= 3, t # (broken a little, at most) + starts = [i for i, e in enumerate(empty) if e and (i == 0 or not empty[i - 1])] + assert len(starts) < 3 or len({b - a for a, b in zip(starts, starts[1:])}) > 1, t # (no regular dashes) eased, gone = sticking["eased"], sticking["after"] assert gone["landed"] == eased["landed"] and gone["beads"] == 0 and gone["popped"] == 0, (eased, gone) # (each run off or shrunk to nothing, or merged into one that was: none dried away otherwise) diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 765692d5..93044e08 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1046,12 +1046,35 @@ const uvSeen = (page) => page.evaluate(() => new Promise((resolve) => { // trail) as it passed 20 px down, a pixel of it: how many px across around it were wiped clear (crisp) as it was (its own, not // another beside it), the bead's width as it wiped it, its fog as shown (and not wiped) then, the fog shown beside the trail (a few px either // side of it), and at the end its fog as shown and how fresh +// A bead's trail as it looks (Sky.state().humidity h, a bead b of h.beads), its fresh rows (fresher than 0.88): on clear glass (no +// fog there), each row's streak (its own pixels shown, from a px left of the bead's sprite to a px right of it); through the fog (fog +// there, not wiped, 0.1 or more at its middle), each row's wiped pixels (its own: the fog shown under half what it'd be): how many, the first +// and the last against the sprite's left and right; each kind with 12 rows or more: {id, kind ("clear", "fog"), w: the bead's mean +// width, widths, lefts, rights, ys}. (Put in the page as window.__trailLook, see lookable()) +const trailLook = (h, b) => { + const kinds = { clear: [], fog: [] }; + for (const r of h.trailOf(b.id)) { + if (!(r.wet > 0.88) || !r.mine) continue; // (fresh, its own: not another bead's since, over it) + const mid = 3 + ((r.w - 1) >> 1), fogs = r.fog.slice(2, r.w + 4); + if (fogs.every(([, f]) => f < 0.06)) { + kinds.clear.push({ y: r.y, w: r.w, width: r.alpha.filter((a, k) => k >= 2 && k < r.w + 4 && a > 0 && r.life[k] === r.life[mid]).length }); + } else if (r.fog[mid][1] >= 0.1) { + const wiped = r.fog.map(([s, f], k) => (f > 0 && s < 0.5 * f && r.life[k] === r.life[mid] ? k : -1)).filter((k) => k >= 0); + kinds.fog.push({ y: r.y, w: r.w, width: wiped.length, left: wiped.length ? wiped[0] - 3 : null, + right: wiped.length ? wiped[wiped.length - 1] - 3 - (r.w - 1) : null }); + } + } + return Object.entries(kinds).filter(([, rows]) => rows.length >= 12).map(([kind, rows]) => ({ + id: b.id, kind, w: rows.reduce((s, r) => s + r.w, 0) / rows.length, widths: rows.map((r) => r.width), ys: rows.map((r) => r.y), + lefts: rows.map((r) => r.left), rights: rows.map((r) => r.right) })); +}; +const lookable = (page) => page.evaluate(`window.__trailLook = ${trailLook.toString()}`); const humiditySeen = (page, frames) => page.evaluate((frames) => new Promise((resolve) => { const last = new Map(), first = Sky.state().frames, count = Sky.state().particles.humidity, h0 = Sky.state().humidity; const from = { ranOff: h0.ranOff, merges: h0.merges, glass: h0.glass, sizes: h0.sizes }; let up = 0, down = 0, wander = 0, offset = 0, samples = 0, lowest = 0, moved = 0, behind = 0, trails = 0, popped = 0, under = 0; let top = 0, inked = 0, alphas = 0, most = 0, looked = 0, still = 0, running = 0, counts = 0; - const ran = new Set(), wandered = new Set(), wiped = new Map(); + const ran = new Set(), wandered = new Set(), wiped = new Map(), looks = [], traced = new Set(); const canvas = document.querySelector("#sky canvas"), g = canvas.getContext("2d"); const step = () => { const state = Sky.state(), h = state.humidity, now = new Map(h.beads.map((b) => [b.id, b])), absorbed = new Set(h.absorbed), left = new Set(h.left); @@ -1068,6 +1091,10 @@ const humiditySeen = (page, frames) => page.evaluate((frames) => new Promise((re lowest = Math.max(lowest, b.bottom / h.height); if (Math.floor(b.y) >= h.height) under++; if (b.y - b.y0 > 10) { moved++; if (b.behind) behind++; } + if (b.y - b.y0 > 30 && !traced.has(b.id) && traced.size < 16 && window.__trailLook) { // (its trail's looks, once) + traced.add(b.id); + looks.push(...window.__trailLook(h, b)); + } if (b.y - b.y0 > 20 && b.trail && !wiped.has(b.id) && b.glass === "fog") { // (its own trail: wiped clear as it passed, as this pixel was, not another's close beside it, wiped at another time) // (or a bead's since, close by, wiping it again: fresher) @@ -1112,7 +1139,7 @@ const humiditySeen = (page, frames) => page.evaluate((frames) => new Promise((re showing: { still: still / Math.max(counts, 1), running: running / Math.max(counts, 1) }, wiped: [...wiped.values()].map((t) => ({ ...t, end: { shown: h.fogAt(...t.at)[0], wet: h.wetAt(...t.at) } })), fog: h.fog(), first: h.first, colours: h.colours(), aged: h.beads.filter((b) => !b.fading).map((b) => b.age), - landed: h.landed }); + landed: h.landed, looks }); }; requestAnimationFrame(step); }), frames); @@ -1143,16 +1170,21 @@ const humidityClears = (page, frames) => page.evaluate((frames) => new Promise(( requestAnimationFrame(step); }), frames); // The trails as their time runs on fast (Sky.state().humidity.hasten(k): k times as fast; each frame 0.1 s of the page's): up to -// `most` trail pixels, each of a trail of its own (on clear glass, fresh still; or through the fog, `through`, still crisp), each -// followed till it's gone (fogged over again all the way, or dry) or a bead wipes it afresh (dropped): how fresh it was at the start, -// how long it lasted all told, on the trails' clock (from how fresh it was), how long it stayed crisp (no fog shown) from the start, -// and at the end its fog shown against the fog not wiped there; and its look at the start ([r, g, b, alpha] on the fog's canvas) +// `most` trail pixels, each of a trail of its own (on clear glass, fresh still, on its streak as shown, a few px apart down it; or through the fog, `through`, +// still crisp, inside it: its own on either side), each followed till it's gone (fogged over again all the way, or dry) or a bead +// wipes it afresh (dropped): how fresh it was at the start, how long it lasted all told, on the trails' clock (from how fresh it was), +// how long it stayed crisp (no fog shown) from the start, how long it showed at all (hidden: shown nothing from then on, as a fraction +// of how long it lasted from the start), and at the end its fog shown against the fog not wiped there; and its look at the start +// ([r, g, b, alpha] on the fog's canvas) const trailsAge = (page, k, through, most) => page.evaluate(([k, through, most]) => new Promise((resolve) => { const h0 = Sky.state().humidity, [W, H] = Sky.state().size, picked = []; for (let y = 4; y < H && picked.length < most; y += 1) for (let x = 2; x < W && picked.length < most; x += 1) { const wet = h0.wetAt(x, y), fog = h0.fogAt(x, y)[1], life = h0.lifeAt(x, y); - if (wet > (through ? h0.crisp + 0.03 : 0.3) && (through ? fog > 0.1 : fog === 0) && !picked.some((p) => Math.abs(p.life - life) < 1)) { - picked.push({ at: [x, y], wet, life, start: h0.clock(), last: wet, look: h0.shownAt(x, y), crispTill: null }); + // (through the fog: inside the trail, its own on either side; on clear glass: on its streak, shown) + const inside = through ? [x - 1, x + 1].every((x) => h0.lifeAt(x, y) === life) : h0.shownAt(x, y)[3] > 0; + if (wet > (through ? h0.crisp + 0.03 : 0.3) && (through ? fog > 0.1 : fog === 0) && inside && + !picked.some((p) => Math.abs(p.life - life) < 1 && (through || Math.abs(p.at[1] - y) < 4))) { // (on clear glass: a few down a streak) + picked.push({ at: [x, y], wet, life, start: h0.clock(), last: wet, look: h0.shownAt(x, y), crispTill: null, shownTill: 0 }); } } h0.hasten(k); @@ -1164,12 +1196,14 @@ const trailsAge = (page, k, through, most) => page.evaluate(([k, through, most]) if (wet > p.last + 1e-6) { p.dropped = true; continue; } p.last = wet; if (p.crispTill === null && h.fogAt(...p.at)[0] > 0) p.crispTill = t - p.start; - if (wet <= 0) { p.done = true; p.lasted = (t - p.start) / p.wet; p.fog = h.fogAt(...p.at); } + if (h.shownAt(...p.at)[3] > 0) p.shownTill = t - p.start; + if (wet <= 0) { p.done = true; p.lasted = (t - p.start) / p.wet; p.fog = h.fogAt(...p.at); p.hidden = p.shownTill / (t - p.start); } } n++; if (n < 400 && picked.some((p) => !p.done && !p.dropped)) return requestAnimationFrame(step); h.hasten(1); - resolve(picked.filter((p) => p.done).map((p) => ({ lasted: p.lasted, crispTill: p.crispTill, wet: p.wet, fog: p.fog, look: p.look }))); + resolve(picked.filter((p) => p.done).map((p) => ({ lasted: p.lasted, crispTill: p.crispTill, wet: p.wet, fog: p.fog, look: p.look, + hidden: p.hidden }))); }; requestAnimationFrame(step); }), [k, through, most]); @@ -1179,7 +1213,7 @@ const trailsAge = (page, k, through, most) => page.evaluate(([k, through, most]) // frames, the weather's time `scale` times as fast; unless `phase` "heavy": from there) the rain light again: no new one sticking, // and those there run off or shrunk away const rainBeads = (page, light, heavy, after, scale, from = "light") => page.evaluate(([light, heavy, after, scale, from]) => new Promise((resolve) => { - const out = { stuck: [] }, seenIds = new Set(), last = new Map(); + const out = { stuck: [], looks: [] }, seenIds = new Set(), last = new Map(), looked = new Set(); let n = 0, phase = from, popped = 0, start = Sky.state().frames; const step = () => { const state = Sky.state(), h = state.humidity, absorbed = new Set(h.absorbed), left = new Set(h.left), now = new Map(h.beads.map((b) => [b.id, b])); @@ -1187,6 +1221,10 @@ const rainBeads = (page, light, heavy, after, scale, from = "light") => page.eva last.clear(); for (const b of h.beads) { last.set(b.id, b); + if (b.kind === "rain" && b.y - b.y0 > 20 && !looked.has(b.id) && window.__trailLook) { // (its trail's looks, once) + looked.add(b.id); + out.looks.push(...window.__trailLook(h, b)); + } if (b.kind === "rain" && !seenIds.has(b.id)) { seenIds.add(b.id); const s = h.splashes.find((s) => s.id === b.id); @@ -1679,6 +1717,7 @@ const WEATHER = { const beading = Promise.all(["humidity2", "humidity2,wind", "humidity"].map(async (name) => { const p = await weatherPage(browser, url, { query: `?fx=${name}`, pace: 10, context: { viewport: { width: 640, height: 480 } } }); await p.page.evaluate(() => Sky.timeScale(6)); + await lookable(p.page); const seen = await humiditySeen(p.page, name === "humidity" ? 200 : 360); await p.page.evaluate(() => Sky.timeScale(name === "humidity2,wind" ? 1 : 2)); if (name === "humidity2,wind") { // (then its trails' time 60 times as fast, through the fog; then humidity off: the fog clearing) @@ -1710,14 +1749,17 @@ const WEATHER = { return seen; })); // heavy rain's beads (rain alone, light first; 30 s, then heavy, 75 s: its time 30 times as fast, small: cheap), and on clear - // glass their trails drying (their time 60 times as fast), beside the rest + // glass their trails drying (their time 120 times as fast), beside the rest const sticking = (async () => { const p = await weatherPage(browser, url, { query: "?fx=rain", pace: 10, context: { viewport: { width: 480, height: 360 } } }); await p.page.evaluate(() => Sky.timeScale(3)); + await lookable(p.page); const seen = await rainBeads(p.page, 100, 250, 0, 1); await p.page.evaluate(() => Sky.timeScale(1)); - seen.drying = await trailsAge(p.page, 60, false, 30); // (the rain heavy still) - ({ eased: seen.eased, after: seen.after } = await rainBeads(p.page, 0, 0, 300, 6, "heavy")); + seen.drying = await trailsAge(p.page, 120, false, 30); // (the rain heavy still; 120 times as fast: the beads there still after) + let looks; + ({ eased: seen.eased, after: seen.after, looks } = await rainBeads(p.page, 0, 0, 300, 6, "heavy")); + seen.looks.push(...looks); // (the trails' looks, those running on too) seen.errors = p.errors; await p.context.close(); return seen; From 49e115cb30791a9cf52040f39d4658ecfa4fce64 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:07:45 +0000 Subject: [PATCH 045/146] Web dashboard: a clearer compass, one thermometer line, beads meet the flood, a cuter chicken. The wind direction's needle is an arrow: a bold barbed head on a shaft in the needles' colour pointing where the wind comes from, and behind the hub only a short, thin, dim tail (the Status picture's compass the same). Each thermometer's glass is one thin, straight, see-through line down the tube's left side: no curve on the bulb, no second line. A flash flood: a running bead (condensation or rain) joins it only once it has run down to the waves' own height where it is (ripples and all), and its trail runs on over the rows it covered down to the water; nothing on the glass is cut off in a straight line at the flood's level: heavy rain's spray is drawn column by column down to the wavy surface, and the smog's banks and the heat's shimmer are drawn down to as low as its troughs go and kept above the surface (flood.sunk(), flood.columns()); the fog, trails, drips and frost already followed it. The gust's chicken redrawn as the cow and the barn are (sculpted shapes lit from the upper left, the same muted dithered ramps and outline): plump and round, a big round head, a small beak hanging a touch open, a little comb and wattle, stubby wings splayed out stiffly, thin legs dangling; a blank wide-eyed stare (big round eyes, the left wider, the right's pupil drifting off, each with a tiny glint), blinking now and then; swaying, bobbing, its head turning a touch as before. Tests: each thermometer has exactly one glass line, straight and upright (in the grid and zoomed); the compass's head and tail told apart (colour, opacity, size), in the grid and zoomed; in the flood's every-effect page, each bead joining reached the surface's own height, its trail down to its bottom and wet there, and where a trough dips 3 px or more under the level, the rows just under the level drawn on as those just above (a straight cut there fails it) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/gauges.py | 15 +++- lib/web_dashboard.html | 145 +++++++++++++++++++-------------- tests/test_web_dashboard.py | 35 ++++++-- tests/web_dashboard_browser.js | 40 +++++++-- 4 files changed, 159 insertions(+), 76 deletions(-) diff --git a/lib/gauges.py b/lib/gauges.py index d4b95de6..fde49657 100644 --- a/lib/gauges.py +++ b/lib/gauges.py @@ -119,8 +119,16 @@ def _dial(c: Canvas, tile: Tile, ox: float, oy: float, ink): c.circle(cx, cy, 25, BG, outline=ink(SOFT), width=_lw(3)) +def _arrow(cx: float, cy: float, reach: float, bearing: float) -> list[tuple[float, float]]: + """The compass's arrow from (cx, cy) toward `bearing` (degrees clockwise from north), its tip `reach` out: a broad barbed head on a + shaft down to the hub (as the web page's arrow()).""" + a = math.radians(bearing) + shape = [(0, reach), (17, reach - 30), (5.5, reach - 23), (5.5, 0), (-5.5, 0), (-5.5, reach - 23), (-17, reach - 30)] + return [(cx + x * math.cos(a) + y * math.sin(a), cy + x * math.sin(a) - y * math.cos(a)) for x, y in shape] + + def _compass(c: Canvas, tile: Tile, ox: float, oy: float, ink): - """The wind's direction: a compass rose's ring with its ticks and N, E, S and W, the needle's head where the wind comes from + """The wind's direction: a compass rose's ring with its ticks and N, E, S and W, the needle an arrow pointing where the wind comes from (degrees clockwise from north), the reading under it ("99° E"). As the web page draws it (web_dashboard.html compass()).""" cx, cy, r = ox + COMPASS[0], oy + COMPASS[1], COMPASS[2] outer, inner = r - 8, r - 8 - BAND_WIDTH @@ -135,9 +143,8 @@ def _compass(c: Canvas, tile: Tile, ox: float, oy: float, ink): _text(c, x, y, name, 13 if i % 2 else 20, ink(SOFT if i % 2 else INK), weight="normal" if i % 2 else "bold") value = shown(tile) % 360 a, reach = 90 - value, inner - 8 - tip, tail, left, right = (_polar(cx, cy, reach, a), _polar(cx, cy, -reach, a), _polar(cx, cy, 9, a + 90), _polar(cx, cy, 9, a - 90)) - c.polygon([tail, left, right], _blend(ink(SOFT), 0.55, BG)) - c.polygon([tip, left, right], ink(NEEDLE)) + c.line([(cx, cy), _polar(cx, cy, -reach * 0.3, a)], _blend(ink(SOFT), 0.5, BG), _lw(2)) # (a short, thin, dim tail) + c.polygon(_arrow(cx, cy, reach, value), ink(NEEDLE)) # (the arrow: where the wind comes from) c.circle(cx, cy, 11, BG, outline=ink(SOFT), width=_lw(2.5)) words = f"{value:.0f}° {tile.band}" if tile.value is not None and tile.band else "–" if tile.value is None else f"{value:.0f}°" _text(c, cx, oy + COMPASS_LABEL_Y, words, 40, ink(INK)) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 830ada06..1b6b80c5 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -170,7 +170,9 @@ // the fog's canvas showing otherwise than they should where no trail is any more, beads: [{id, kind ("fog": condensed, "rain"), // x, x0 and y0: where it showed, y: its top, cy: its middle, r, vol: its water, w, laidW: its width as it last left its trail, // bottom: its sprite's lowest row + 1, glass: under it, v: px/s now, fading, alpha, drawn: [x, y, w, h, alpha] as drawn last, -// age: s shown, behind: its trail there behind it, trail: [x, y] a pixel of it}]}), joined: how many have run into a flood}, +// age: s shown, behind: its trail there behind it, trail: [x, y] a pixel of it}]}), joined: how many have run into a flood, joins: the latest of them +// (each {x, bottom: its sprite's lowest row + 1, surface: the flood's surface there then, level: the flood's level, trail: its trail's +// last row + 1, or null: not running, wet: its trail there, in its middle)}, // flood (a flash flood: its depth, its surface, its frog and its waves, as flood.probe() gives them; the wind's water: its leaves // in it; the rain's under: drops drawn below its surface), gust (what's blown across: gust.probe()), for the tests. Sky.timeScale(k): the // weather's time k times as fast, each frame (test-only). Sky.frost() (test-only): @@ -380,7 +382,11 @@ } g.globalAlpha = alpha * 0.8; for (const s of splashes) g.drawImage(SPLASH[Math.min(4, Math.floor(s.age / 0.05))], Math.round(s.x) - 4, Math.round(s.y) - 4); - if (e.level > 0.6) { g.globalAlpha = alpha * (e.level - 0.6) * 0.9; g.drawImage(mist, 0, Math.round(flood.waterline()) - mist.height); } + if (e.level > 0.6) { // (its spray down to the window's bottom, or a flood's surface: its waves, column by column) + g.globalAlpha = alpha * (e.level - 0.6) * 0.9; + const mh = mist.height; + flood.columns((x, n, y) => g.drawImage(mist, x, 0, n, mh, x, y - mh, n, mh)); + } }, }; }); @@ -421,7 +427,7 @@ draw(g, alpha, t) { if (!built) return; flood.above(g, () => LAYERS.forEach((l, i) => { - const x = Math.floor((t * l.drift + i * W / 3) % W), y = Math.round(Math.sin(t * 0.07 + i * 2) * 1.5 - flood.lift()); + const x = Math.floor((t * l.drift + i * W / 3) % W), y = Math.round(Math.sin(t * 0.07 + i * 2) * 1.5 - flood.sunk()); g.globalAlpha = alpha * (0.6 + 0.4 * l.depth); g.drawImage(textures[i], x - W, y); g.drawImage(textures[i], x, y); @@ -431,7 +437,8 @@ }); // ---------- heat: a shimmering amber glow rising from the bottom, its ripples riding up and wavering sideways ---------- - // (In a flood, from its surface: flood.lift(); the smog's banks sit on it too, and neither is drawn below it) + // (In a flood, from its surface: from as low as its troughs go, flood.sunk(), and kept above() it, so its edge is the wavy surface; + // the smog's banks sit on it too, and neither is drawn below it) const HEAT = ["#3A1C0A", "#62300E", "#955015", "#C97B24", "#EFB05A"].map(rgb); const heat = effect((e) => { const SPAN = 0.34, PERIOD = 13, LINES = 7, RISE = 9, SPARE = 4; // its height (of the window's); its ripples' spacing (px), how many @@ -458,7 +465,7 @@ }); }, draw(g, alpha, t) { - const top = Math.round(H - band - flood.lift()), rows = PERIOD * LINES, scroll = Math.floor(t * RISE) % rows; // (a flood: from its surface) + const top = Math.round(H - band - flood.sunk()), rows = PERIOD * LINES, scroll = Math.floor(t * RISE) % rows; // (a flood: from its surface) flood.above(g, () => { for (let y = 0; y < band; y++) { const k = y / band, dx = Math.round(Math.sin(y * 0.5 - t * 3.1) * (0.5 + 1.8 * k)); // (wavering more lower down) @@ -948,7 +955,7 @@ let dirty = null, painting = 0, level = 0, fresh = 0, quiet = false; // (for the tests, as Sky.state() gives them) const seen = {merges: 0, merged: [], absorbed: [], left: [], ranOff: 0, shrunk: 0, faded: 0, largest: 0, born: [], first: null, - dried: 0, landed: 0, rainMost: 0, splashes: [], joined: 0, + dried: 0, landed: 0, rainMost: 0, splashes: [], joined: 0, joins: [], glass: [0, 1, 2].map(() => ({px: 0, s: 0, gained: 0, lost: 0, moves: 0, all: 0, norm: 0})), // (px, s: r 1.8-3.2) sizes: [0, 1, 2, 3, 4].map(() => [0, 0])}; // (on fog: px and s, by size) const BANDS = [1, 1.6, 2.4, 3.2]; @@ -1228,12 +1235,19 @@ if (drowned(b)) return; } } - // A flood: a bead reaching its surface joins it, a small ripple and splash (its trail ending at the waterline); one not yet showing - // there, never shows + // A flood: a bead running down to its surface (the waves' own height where it is, ripples and all) joins it there, a small ripple + // and splash, its trail run on over the rows it covered, down to the water; one not yet showing there, never shows function drowned(b) { - if (Math.floor(b.y) + heightOf(b.r) < flood.surface(b.x)) return false; + const bottom = Math.floor(b.y) + heightOf(b.r), surface = flood.surface(b.x); + if (bottom < surface) return false; b.gone = true; - if (b.state !== "rest") { seen.joined++; flood.hit(b.x, 0.4 + 0.2 * b.r, true); } + if (b.state === "rest") return true; + if (b.state === "on") for (let y = Math.max(b.laid, 0); y < Math.min(bottom, H); y++) wipe(b, y); + seen.joined++; + const last = b.state === "on" && b.rows.length ? b.rows[b.rows.length - 1][0] : null, end = last === null ? -1 : at(Math.round(b.x), last); + seen.joins.push({x: b.x, bottom, surface, level: flood.waterline(), trail: last === null ? null : last + 1, wet: end < 0 ? 0 : wetOf(end)}); + if (seen.joins.length > 100) seen.joins.shift(); + flood.hit(b.x, 0.4 + 0.2 * b.r, true); return true; } const fadeFor = (r) => 0.5 + 0.12 * r ** 3; // s for a bead to dry away (its water) @@ -1352,6 +1366,7 @@ merges: seen.merges, merged: seen.merged.slice(), absorbed: seen.absorbed.slice(), left: seen.left.slice(), ranOff: seen.ranOff, shrunk: seen.shrunk, faded: seen.faded, largest: seen.largest, born: seen.born.slice(), first: seen.first, landed: seen.landed, rainMost: seen.rainMost, splashes: seen.splashes.slice(), joined: seen.joined, + joins: seen.joins.slice(), glass: Object.fromEntries(GLASSES.map((name, g) => [name, {...seen.glass[g]}])), sizes: seen.sizes.map((s) => s.slice()), bands: BANDS, // (the physics as the beads run by it: a bead's mean speed, px/s, of radius r on glass g ("dry", "trail", "fog"), @@ -1464,6 +1479,7 @@ const SLOSH = [4, 10]; // s between the bigger sloshes const FROG_FIRST = 30, FROG_EVERY = 180, FROG_SPEED = [7, 10]; // s, s, px/s const TOP = 2 * MOST + 2; // rows drawn above its full level (its crests, higher up the sides) + const DIP = Math.ceil(MOST * 1.8) + 1; // px: its troughs at most this far below its level (lower at the sides) const pack = ([r, g, b], a) => ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; // (a pixel of ImageData, as a 32-bit word) // The frog on its lily pad, facing out: one eye wide, the other half-lidded, both looking off to the side, a long flat mouth // drooping at one end: unimpressed. Now and then it blinks. (Its pad's middle row sits on the surface.) @@ -1514,6 +1530,18 @@ surface: surfaceAt, waterline: () => (depth > 0 ? H - depth : H), // (its level, its waves aside: the window's bottom with no water) lift: () => depth, + // (how far up from the window's bottom its surface's lowest trough can be: what sits on it is drawn down to there and kept + // above() it, so its edge is the wavy surface, never a straight line at its level) + sunk: () => (depth > 0 ? Math.max(0, depth - DIP) : 0), + // paint(x, n, y) for each run of columns x to x + n - 1 whose surface is on row y (as drawn; H with no water), left to right + columns(paint) { + if (depth <= 0) return paint(0, W, H); + let x0 = 0, y0 = Math.round(surfaceAt(0)); + for (let x = 1; x <= W; x++) { + const y = x < W ? Math.round(surfaceAt(x)) : NaN; + if (y !== y0) { paint(x0, x - x0, y0); x0 = x; y0 = y; } + } + }, // Whatever `paint` draws on g kept above the surface (clipped to it, a column at a time: crisp) above(g, paint) { if (depth <= 0) return paint(); @@ -1863,8 +1891,9 @@ // at random a cow, a barn or a chicken (each in turn from a shuffled bag of the three, so no long run of one). Large, far off on the // back layer (drawn first: every other effect over it) and faint; carried right to left with the wind (faster while the wind effect // blows too), rising and sinking a little on the air. The cow and the barn tumble slowly end over end; the chicken doesn't: it hangs - // facing the viewer, legs dangling under it and swinging, bobbing and swaying a little, its head turning a touch this way and that, - // its eyes on the viewer all the while, bemused (one wide under a raised brow, the other half-lidded), blinking now and then. Each + // facing the viewer, plump and round, its stubby wings splayed out stiffly, its thin legs dangling under it and swinging, bobbing + // and swaying a little, its head turning a touch this way and that, staring blankly out (big round eyes, one wider, the other's + // pupil drifting off), blinking now and then. Each // sheds a few bits as it goes (hay and splinters, tufts of grass, a feather or two). The art: sculpted from a few shapes, lit from // the upper left and dithered into its own muted ramps, outlined in its darkest; turned (tumbling) by sampling each pixel's 3x3 // points in the upright sprite and taking the most common colour, so its pixel lines stay crisp at every angle; each angle made @@ -1970,52 +1999,44 @@ slab(5, 24, 53, 25, "trim", () => 0.6), ]); }; - // The chicken, facing the viewer: wings splayed, a red comb and wattle, one eye wide under a raised brow, the other half-lidded, - // the beak a touch askew; its legs dangling straight down from its hips (`legs`: their swing's frame, 0-3), its head turned - // `turn` px (-1 to 1), or blinking. Swaying `tilt` rad about its middle: its shapes tilted, its face (single pixels) only moved - // with its head, so it stays crisp and on the viewer + // The chicken, facing the viewer, plump and round: a big round head on a round body, a small beak hanging a touch open, a little + // comb and wattle; its stubby wings splayed out stiffly, its thin legs dangling straight down from under it (`legs`: their swing's + // frame, 0-3); a blank, wide-eyed stare (big round eyes, the left one wider, each with a small pupil and a tiny highlight), or + // blinking; its head turned `turn` px (-1 to 1). Swaying `tilt` rad about its middle: its shapes tilted, its pupils (single + // pixels) moved with its eyes, so they stay crisp and on the viewer const LEG_SWING = [[-1, 0], [0, 1], [1, 0], [0, -1]]; const chicken = (turn, legs, blink, tilt) => { - const t = turn, [l, r] = LEG_SWING[legs], ring = C("dark", 1), white = C("eye", 3), pupil = C("dark", 0), lid = C("feather", 1); - const W2 = 40, H2 = 52, cx = 20, cy = 24, c = Math.cos(tilt), s = Math.sin(tilt); + const t = turn, [l, r] = LEG_SWING[legs], pupil = C("dark", 0), shine = C("eye", 3), shut = C("feather", 0); + const W2 = 44, H2 = 50, cx = 22, cy = 26, c = Math.cos(tilt), s = Math.sin(tilt); const at = (x, y) => [cx + c * (x - cx) - s * (y - cy), cy + s * (x - cx) + c * (y - cy)]; // (a point of the upright chicken, tilted) const tilted = (part) => ({m: part.m, at: (x, y) => { const dx = x + 0.5 - cx, dy = y + 0.5 - cy; return part.at(cx + c * dx + s * dy - 0.5, cy - s * dx + c * dy - 0.5); }}); - const [hx, hy] = at(19.5, 12), mx = Math.round(hx - 19.5), my = Math.round(hy - 12); // (its face moved with its head) - const a = 13 + t + mx, b = 22 + t + mx, y = 10 + my; // (the wide eye's left, the half-lidded one's, their top) + // its eyes: [middle x, middle y, radius]; the left wider + const eyes = [[17.4 + t, 13.4, 3.9], [26.2 + t, 13.9, 3.4]]; const over = []; - const put = (x, yy, colour) => over.push([x, yy, colour]); - for (const x0 of [a, b]) { // each eye: a dark ring round 4x4 - for (let i = 0; i < 4; i++) { put(x0 + i, y - 1, ring); put(x0 + i, y + 4, ring); put(x0 - 1, y + i, ring); put(x0 + 4, y + i, ring); } - for (let j = 0; j < 4; j++) for (let i = 0; i < 4; i++) { - const corner = (i === 0 || i === 3) && (j === 0 || j === 3); - put(x0 + i, y + j, blink ? (j === 2 ? ring : lid) : corner ? ring : white); - } - } - if (!blink) { - for (const [i, j] of [[1, 1], [2, 1], [1, 2], [2, 2]]) put(a + i, y + j, pupil); // (wide: looking straight out) - for (let i = 0; i < 4; i++) { put(b + i, y, lid); put(b + i, y + 1, ring); } // (half-lidded, its pupil under the lid) - put(b + 1, y + 2, pupil); put(b + 2, y + 2, pupil); - for (const [x, yy] of [[a - 1, y - 2], [a, y - 3], [a + 1, y - 3], [a + 2, y - 3], [a + 3, y - 2]]) put(x, yy, ring); // (a raised brow) + for (const [ex, ey, er] of eyes) { + const [x, y] = at(ex, ey), px = Math.floor(x), py = Math.floor(y); + if (blink) { for (let i = -Math.round(er) + 1; i < Math.round(er); i++) over.push([px + i, py, shut]); continue; } + const ox = er > 3.5 ? 0 : 1; // (the smaller one's pupil drifting off outward: not quite looking at the same thing) + for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) over.push([px + ox + i, py + j, (i < 0 && j < 0) ? shine : pupil]); // (a glint) } - const bx = 18 + t + mx, by = 15 + my; - for (const [x, yy] of [[0, 0], [1, 0], [2, 0], [3, 0], [1, 1], [2, 1], [3, 1], [2, 2]]) put(bx + x, by + yy, C("beak", yy ? 2 : 3)); - put(bx, by + 1, C("beak", 0)); put(bx + 4, by, C("beak", 0)); // (its beak a touch askew) - const legsOf = (hip, swing, side) => { // (from the hip, tilted with it, straight down; toes drooping) - const [x0, y0] = at(hip, 35), fx = x0 + swing, fy = y0 + 10; - return [limb(x0, y0, fx, fy, 0.75, "beak"), limb(fx, fy, fx - 1.5 * side, fy + 3.5, 0.6, "beak"), - limb(fx, fy, fx + side, fy + 4, 0.6, "beak"), limb(fx, fy, fx, fy + 4.5, 0.6, "beak")]; + const legsOf = (hip, swing, side) => { // (from under it, tilted with it, straight down; toes drooping) + const [x0, y0] = at(hip, 37), fx = x0 + swing, fy = y0 + 8; + return [limb(x0, y0, fx, fy, 0.7, "beak"), limb(fx, fy, fx - 1.5 * side, fy + 3, 0.55, "beak"), + limb(fx, fy, fx + side, fy + 3.5, 0.55, "beak"), limb(fx, fy, fx, fy + 4, 0.55, "beak")]; }; + const eyeParts = blink ? [] : eyes.map(([ex, ey, er]) => ball(ex, ey, er, er, "eye")); return sculpt(W2, H2, [ - ...legsOf(16, l, 1), ...legsOf(23, r, -1), - ...[limb(6, 21, 2.5, 32, 1.7, "feather", 0.7), limb(33, 21, 36.5, 32, 1.7, "feather", 0.6), - ball(9, 25, 5.5, 8, "feather", 0.85), ball(30, 25, 5.5, 8, "feather", 0.7), - ball(19.5, 28, 10.5, 9.5, "feather"), - ball(17 + t, 5.5, 2, 2.2, "comb"), ball(19.5 + t, 4, 2.2, 2.8, "comb"), ball(22 + t, 5.5, 2, 2.2, "comb"), - ball(19.5 + t * 0.6, 12.5, 8, 7.5, "feather"), - ball(20 + t, 20, 1.8, 2.6, "comb")].map(tilted), + ...legsOf(18, l, 1), ...legsOf(26, r, -1), + ...[ball(22, 30, 12.5, 11, "feather"), + limb(11, 27.5, 5, 24.5, 3.1, "feather", 0.95), limb(33, 27.5, 39, 24.5, 3.1, "feather", 0.8), // (its wings, splayed stiffly) + ball(19.5 + t * 0.4, 4.6, 1.9, 2.1, "comb"), ball(22 + t * 0.5, 3.6, 2.1, 2.6, "comb"), ball(24.5 + t * 0.4, 4.8, 1.8, 2, "comb"), + ball(22 + t * 0.6, 13.5, 10, 9.2, "feather"), + ...eyeParts, + ball(22.6 + t, 21.6, 1.3, 2, "comb"), + ball(22 + t, 18.6, 2.2, 1.3, "beak"), ball(22 + t, 20, 1.6, 0.9, "beak", 0.6)].map(tilted), ], over); }; // A sprite turned `angle` rad about its middle (a canvas S x S, S its diagonal): each pixel the most common colour of its 3x3 points @@ -2328,17 +2349,12 @@ `L${cx + half},${join} A${radius},${radius} 0 1 1 ${cx - half},${join} Z`; } - // The thermometer's glass catching the light, so it reads as rounded: a thin soft line down the tube's left side and a short curved - // one on the bulb's upper left, see-through white over the red (in the gauge's own pixels: scaled with the tile, grid or zoomed) + // The thermometer's glass catching the light: one thin, straight, see-through white line down the tube's left side, from just under + // its cap to just above the bulb (in the gauge's own pixels: scaled with the tile, grid or zoomed). No curve on the bulb, no second line function glass(svg, cx, top, half, bulbY, radius) { const x = cx - half * 0.55, from = top + half * 0.9, to = bulbY - Math.sqrt(radius ** 2 - half ** 2) - 6; - const soft = {fill: "none", stroke: "#FFFFFF", "stroke-linecap": "round", class: "glass"}; - el("path", {d: `M${x},${from} L${x},${to}`, ...soft, "stroke-width": 4.5, "stroke-opacity": 0.28}, svg); - el("path", {d: `M${x + 6.5},${from + 4} L${x + 6.5},${from + (to - from) * 0.45}`, ...soft, "stroke-width": 2, - "stroke-opacity": 0.18}, svg); - const r = radius * 0.66, [x0, y0] = polar(cx, bulbY, r, 168), [x1, y1] = polar(cx, bulbY, r, 118); - el("path", {d: `M${x0.toFixed(2)},${y0.toFixed(2)} A${r},${r} 0 0 1 ${x1.toFixed(2)},${y1.toFixed(2)}`, ...soft, "stroke-width": 4, - "stroke-opacity": 0.3}, svg); + el("path", {d: `M${x},${from} L${x},${to}`, fill: "none", stroke: "#FFFFFF", "stroke-linecap": "round", "stroke-width": 3, + "stroke-opacity": 0.28, class: "glass"}, svg); } function thermometer(svg, tile, ink, id) { @@ -2425,9 +2441,14 @@ } // The wind's direction, a compass (as the Status picture's: lib/gauges.py _compass): a ring with fine ticks and the points named, the - // needle's head (the needle's colour) where the wind comes from, in degrees clockwise from north, its tail grey; the reading under it + // needle an arrow (the needles' colour) pointing where the wind comes from, in degrees clockwise from north, its tail a short dim + // stub; the reading under it // ("99° E": the compass point the service gives, or, while the needle swings to it, the point it is passing). No table. const pointOf = (deg) => L.points[Math.floor(((deg % 360) + 360 + 11.25) / 22.5) % 16]; // (direction.py sector()) + // The compass's arrow pointing north from (cx, cy), its tip `reach` out: a broad barbed head on a shaft down to the hub ([x, y], ...; + // as lib/gauges.py _arrow) + const arrow = (cx, cy, reach) => [[0, reach], [17, reach - 30], [5.5, reach - 23], [5.5, 0], [-5.5, 0], [-5.5, reach - 23], [-17, reach - 30]] + .map(([x, y]) => [cx + x, cy - y]); function compass(svg, tile, ink) { const [cx, cy, r] = L.compass, outer = r - 8, inner = outer - L.band_width, mid = (outer + inner) / 2, reach = inner - 8; el("circle", {cx, cy, r, fill: "none", stroke: ink(L.soft), "stroke-width": lw(3)}, svg); @@ -2450,9 +2471,13 @@ const [x, y] = polar(cx, cy, mid, 90 - 45 * i); text(svg, x, y, name, i % 2 ? 13 : 20, ink(i % 2 ? L.soft : L.ink), "middle", i % 2 ? "normal" : "bold").classList.add("point"); }); - const needle = el("g", {class: "needle"}, svg); // (drawn pointing north, turned to the reading) - el("polygon", {points: `${cx},${cy + reach} ${cx - 9},${cy} ${cx + 9},${cy}`, fill: ink(L.soft), "fill-opacity": 0.45}, needle); - el("polygon", {points: `${cx},${cy - reach} ${cx - 9},${cy} ${cx + 9},${cy}`, fill: ink(L.needle), class: "head"}, needle); + // The needle (drawn pointing north, turned to the reading): an arrow, its bold head and shaft in the needles' colour pointing where + // the wind comes from, and behind the hub only a short, thin, dim tail: one end to read, never two alike + const needle = el("g", {class: "needle"}, svg); + el("path", {d: `M${cx},${cy} L${cx},${cy + reach * 0.3}`, stroke: ink(L.soft), "stroke-width": lw(2), "stroke-opacity": 0.5, + "stroke-linecap": "round", class: "tail"}, needle); + el("polygon", {points: arrow(cx, cy, reach).map((p) => p.join(",")).join(" "), fill: ink(L.needle), "stroke-linejoin": "round", + stroke: ink(L.needle), "stroke-width": 1.5, class: "head"}, needle); el("circle", {cx, cy, r: 11, fill: L.bg, stroke: ink(L.soft), "stroke-width": lw(2.5)}, svg); const label = text(svg, cx, L.compass_label_y, "", 40, ink(L.ink)); label.classList.add("reading"); diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 65fce470..10eeffdb 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -448,6 +448,15 @@ def chromium(): needs_browser = pytest.mark.usefixtures("chromium") +def one_end_to_read(compass: dict): + """The compass's needle (compassLook's): its head a bold arrow in the needles' colour, its tail a short, thin, dim stub of another + colour; never two ends alike.""" + head, tail = compass["ends"] + needle = "rgb({}, {}, {})".format(*(int(look()["needle"][i:i + 2], 16) for i in (1, 3, 5))) + assert head["colour"] == needle and tail["colour"] != needle and head["opacity"] == 1 and tail["opacity"] <= 0.6, compass + assert head["area"] > 6 * tail["area"] and head["length"] > 2.5 * tail["length"], compass + + @needs_browser async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error(server, station, tmp_path): shots = Path(os.getenv("ECOBOT_SCREENSHOTS") or tmp_path) @@ -487,12 +496,16 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl assert (shots / f"dashboard-{name}.png").exists() and (shots / f"dashboard-{name}-zoomed.png").exists() assert got["zoomed"]["zoomed"], (name, got["zoomed"]) fills(got["zoomed"], width, height) # zoomed: its title and gauge fill the window, no table - # the thermometers' glass catches the light (a line down the tube, a curve on the bulb); no dial or beaker has it + # the thermometers' glass catches the light: one straight line down the tube (no curve on the bulb, no second line); no dial + # or beaker has it assert sorted(k for k, _ in got["glass"]) == sorted(kinds) and {"thermometer", "dial", "beaker"} <= set(kinds), got["glass"] - assert all(g == 3 if k == "thermometer" else g == 0 for k, g in got["glass"]), got["glass"] + assert all(len(g) == (1 if k == "thermometer" else 0) for k, g in got["glass"]), got["glass"] + for _, (d,) in (g for g in got["glass"] if g[0] == "thermometer"): + m = re.fullmatch(r"M([\d.]+),([\d.]+) L([\d.]+),([\d.]+)", d) # (a straight line, upright: one segment) + assert m and m[1] == m[3] and float(m[4]) - float(m[2]) > 100, d tile, glass = got["zoomed"]["box"], got["zoomed"]["glass"] # (the first tile, Temperature) zoomed: the glass with it - assert len(glass) == 3 and all(g["height"] > 0 and tile["left"] <= g["left"] and g["right"] <= tile["right"] for g in glass) - assert max(g["height"] for g in glass) > tile["width"] * 0.2, (glass, tile) + assert len(glass) == 1 and all(g["height"] > 0 and tile["left"] <= g["left"] and g["right"] <= tile["right"] for g in glass) + assert glass[0]["height"] > tile["width"] * 0.2 and glass[0]["width"] < glass[0]["height"] * 0.06, (glass, tile) # the wind's direction, a compass: N, E, S, W and the points between named, its needle's head turned to where the wind comes # from (99°, east), its reading "99° E" (the service's compass point); no table, the same size as its neighbours c, rects = got["compass"], got["rects"] @@ -501,6 +514,8 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl assert any(near(c["box"], r, 0.5) for r in rects) and len({(round(r["width"]), round(r["height"])) for r in rects}) == 1, c ring, head = c["ring"], c["head"] assert (head["left"] + head["right"]) / 2 > (ring["left"] + ring["right"]) / 2 + ring["width"] * 0.1 and abs((head["top"] + head["bottom"]) / 2 - (ring["top"] + ring["bottom"]) / 2) < ring["height"] * 0.1, c + # ... the end to read unmistakable: the head a bold arrow in the needles' colour, the tail a short, thin, dim stub of another + one_end_to_read(c) assert all(c["box"]["left"] <= r["left"] and r["right"] <= c["box"]["right"] and r["bottom"] <= c["box"]["top"] + c["box"]["width"] * TABLE_TOP / look()["cell"][0] for r in c["texts"]), c # (all of it above where a table would start) # zoomed: the compass and its reading fill the zoomed place, as any tile's title and gauge @@ -509,6 +524,7 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl for r in [z["title"], z["ring"], *z["texts"]]: assert z["box"]["left"] - 1 <= r["left"] and r["right"] <= z["box"]["right"] + 1 and z["box"]["top"] - 1 <= r["top"] and r["bottom"] <= z["box"]["bottom"] + 1, (r, z) assert z["ring"]["width"] > z["box"]["width"] * 0.45, z + one_end_to_read(z) # (zoomed too) assert (shots / f"dashboard-{name}-compass.png").exists() # the dials with a thin red hand at the past hour's highest (Wind's gust, Rain rate's, Solar radiation's, UV's), over the dial # and the needle, under the hub; none on any other tile; the Wind's table: its highest speed, and its highest gust beside it @@ -1445,8 +1461,17 @@ async def test_a_flash_flood_fills_the_window_a_quarter_up_its_surface_choppy_wh assert linked["gaps"] and set(linked["gaps"]) <= {0, 1}, sorted(set(linked["gaps"])) assert linked["resting"] and all(-4 <= r <= 0 for r in linked["resting"]), sorted(set(linked["resting"])) assert 0 < linked["most"] <= 0.42 and linked["over"] <= 3, linked - # ... the drips: joining it as they reach it, none below it + # ... the drips: joining it as they reach it, none below it; each running on down to the waves' own height where it is (its + # sprite's bottom at the surface there, ripples and all, or under a crest risen over it), never joining it short of that, its + # trail all the way down with it, wet to the water assert linked["joined"] >= 1 and linked["under"] == 0, linked + joins = linked["joins"] + assert joins and all(j["bottom"] >= j["surface"] for j in joins), joins + assert all(j["trail"] == j["bottom"] and j["wet"] > 0 for j in joins if j["trail"] is not None) and any(j["trail"] for j in joins), joins + # ... and nothing on the glass cut off in a straight line at its level: where a trough dips 3 px or more under it, the rows just + # under the level as drawn on as those just above (the smog, the heat, the rain's spray, the fog, all down to the wavy surface) + cut = linked["cut"] + assert cut["n"] >= 100 and cut["at"] >= 0.8 * cut["above"], cut drained = linked["drained"] assert 5 <= drained["took"] <= 7 and drained["wet"] == 0 and drained["frog"] is None, drained assert drained["effects"] == ["smog", "heat", "uv", "wind", "humidity", "ice"], drained diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 93044e08..8cbfe267 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1,6 +1,7 @@ // The dashboard page in Playwright's Chromium, for tests/test_web_dashboard.py. // node web_dashboard_browser.js URL SHOTS SIZES: the page at each size ({name: [width, height]}): a screenshot of each (SHOTS/dashboard- -// NAME.png, device scale factor 2) and, on stdout, {name: {tiles, rects, columns, scroll, scrollWidth, scrollHeight, status, glass, errors, +// NAME.png, device scale factor 2) and, on stdout, {name: {tiles, rects, columns, scroll, scrollWidth, scrollHeight, status, glass (each +// tile's [kind, its glass highlights' paths]), errors, // zoomed, compass, compassZoomed}}; then the first tile zoomed (Enter): its look, and a screenshot (SHOTS/dashboard-NAME-zoomed.png); // then the compass (the wind's direction) zoomed: its look (compassLook), and a screenshot (SHOTS/dashboard-NAME-compass.png). // node web_dashboard_browser.js URL --live: the page open at 800x600; prints {label} (the first tile's), waits for a line on stdin @@ -65,7 +66,7 @@ async function sizes(browser, url, shots, wanted) { scrollWidth: document.documentElement.scrollWidth, scrollHeight: document.documentElement.scrollHeight, status: document.getElementById("status").textContent, - glass: [...document.querySelectorAll(".tile")].map((t) => [t.dataset.kind, t.querySelectorAll("svg .glass").length]), + glass: [...document.querySelectorAll(".tile")].map((t) => [t.dataset.kind, [...t.querySelectorAll("svg .glass")].map((e) => e.getAttribute("d"))]), })), errors }; await handsSettled(page); report[name].hands = await handsLook(page); // the dials' thin red hands: the past hour's highest @@ -118,14 +119,21 @@ const handsSettled = (page) => page.waitForFunction(() => { return still; }, null, { timeout: 5000, polling: 150 }).catch(() => { /* reported as it is */ }); -// The compass tile's look: its label, reading, needle's turn, the points named, any table, and where its parts are (the window's px) +// The compass tile's look: its label, reading, needle's turn, the points named, any table, where its parts are (the window's px) and +// its needle's head and tail const compassLook = (page) => page.evaluate(() => { const t = document.querySelector('.tile[data-kind="compass"]'), rect = (e) => e.getBoundingClientRect().toJSON(); return { label: t.getAttribute("aria-label"), reading: t.querySelector("svg text.reading").textContent, faded: t.classList.contains("faded"), turn: t.querySelector(".needle").getAttribute("transform"), points: [...t.querySelectorAll("svg text.point")].map((e) => e.textContent), table: t.querySelectorAll(".unit, .chip, .figure, .tablearea").length, zoomed: document.body.classList.contains("zoomed"), shown: !t.inert, box: rect(t), title: rect(t.querySelector(".title")), texts: [...t.querySelectorAll("svg text")].map(rect), - ring: rect(t.querySelector("svg circle")), head: rect(t.querySelector(".needle .head")) }; + ring: rect(t.querySelector("svg circle")), head: rect(t.querySelector(".needle .head")), + // (its needle's two ends: the head's and the tail's colour, how opaque, their size (the drawn box's area, the window's px²)) + ends: [".head", ".tail"].map((k) => { + const e = t.querySelector(`.needle ${k}`), c = getComputedStyle(e), r = rect(e); + return { colour: k === ".head" ? c.fill : c.stroke, opacity: Number(k === ".head" ? c.fillOpacity : c.strokeOpacity) * Number(c.opacity), + area: r.width * r.height, length: Math.hypot(r.width, r.height) }; + }) }; }); // The compass at rest: its needle turned all the way to the reading its label gives (north with none), rather than a fixed wait @@ -1519,8 +1527,9 @@ const WEATHER = { // its surface choppy all across and higher at the sides, the rain ending at it in ripples and splashes; its waves alone (one // push: travelling both ways, reflecting off a side); draining at 30, its chop calming slowly. Beside it, every other effect on // and the test link's rain3 (rain light, heavy, flood, off): the frame time and the particles with the flood full; then on a fast - // clock, leaves landing on it, floating, sinking and resting on the bottom; the drips joining it; its first frog 30 s after the - // water starts rising, drifting right to left on the waves; off, draining. + // clock, leaves landing on it, floating, sinking and resting on the bottom; the drips joining it (each as it did), and where the + // surface is down in a trough, what's drawn just under its level against what's just above; its first frog 30 s after the water + // starts rising, drifting right to left on the waves; off, draining. async flood(browser, url, out) { const linked = (async () => { const { context, page, errors } = await weatherPage(browser, url, { query: "?fx=smog3,uv,humidity2,wind,heat,ice" }); @@ -1543,7 +1552,7 @@ const WEATHER = { // every frame, until the first frog has crossed (or 100 s of the page's time): the frog, the leaves in the water, the drips Object.assign(seen, await page.evaluate(() => new Promise((resolve) => { const r = { before: null, first: null, track: [], leaves: { float: 0, sink: 0, rest: 0 }, gaps: [], resting: [], wet: 0, most: 0, - over: 0, under: 0, joined: 0, frogs: 0, fullAt: null }; + over: 0, under: 0, joined: 0, joins: [], frogs: 0, fullAt: null }; const step = () => { const s = Sky.state(), f = s.flood, w = s.wind; if (f.depth >= f.full && r.fullAt === null) r.fullAt = f.since; @@ -1565,12 +1574,29 @@ const WEATHER = { r.under = Math.max(r.under, s.humidity.beads.filter((b) => b.bottom > f.surface[Math.round(Math.min(Math.max(b.x, 0), f.width - 1))] + 3).length); } r.joined = s.humidity.joined; + r.joins = s.humidity.joins; r.frogs = f.frogs; if ((r.first && !f.frog) || f.since > 100) { r.gaps = r.gaps.slice(-400); r.resting = r.resting.slice(-400); return resolve(r); } requestAnimationFrame(step); }; requestAnimationFrame(step); }))); + // (still full: where the surface is down in a trough, 3 px or more below its level, the canvas's alpha in the two rows just + // under the level beside two rows a little above it, those columns all summed, frame by frame till 400 of them; last, as reading + // the canvas back can slow its drawing) + seen.cut = await page.evaluate(() => new Promise((resolve) => { + const g = document.querySelector("#sky canvas").getContext("2d"), cut = { n: 0, above: 0, at: 0 }; + let frames = 0; + const step = () => { + const f = Sky.state().flood, level = f.height - f.depth, d = g.getImageData(0, level - 4, f.width, 6).data; + const alpha = (row, x) => d[(row * f.width + x) * 4 + 3]; + for (let x = 0; x < f.width; x++) if (Math.round(f.surface[x]) >= level + 3) { + cut.n++; cut.above += alpha(0, x) + alpha(1, x); cut.at += alpha(4, x) + alpha(5, x); + } + if (cut.n >= 400 || ++frames >= 150) resolve(cut); else requestAnimationFrame(step); + }; + requestAnimationFrame(step); + })); // off: draining, the leaves in it fading out with it (the weather's time four times as fast) await page.evaluate(() => Sky.timeScale(4)); await click(); From 85c557b6008be5aa1ff5de6307873fe19914b68d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:40:25 +0000 Subject: [PATCH 046/146] Web dashboard: nothing an effect leaves behind comes back once it has ended. Each effect, gone all the way (faded out, melted, drained) or with the animations stopped, now forgets everything it had (forget()): heavy rain's beads, their wet streaks and stains, the fog and its trails (the glass's offscreen layer cleared and its state reset), the rain's drops, the wind's leaves (those sunk in a flood too), the flood's waves and frog, the frost and its sparkles (its canvas cleared). So rain coming back (the link back on, the real rate rising again, or the animations started again) starts on clean glass, and the frost grows afresh from the edges. "stop animation" forgets every effect at once (levels still called for stay; they fade in afresh once started). While the rain is merely easing (still on), its streaks stay and dry on their own 3-10 minutes as before (the glass's effect kept on while any streak is left and the rain is on). Sky.state().humidity gains marks() (trail pixels, its canvas's inked pixels, beads, fog) and Sky.frost() gains ink. Tests, in the existing sessions: heavy rain eased to light, its streaks still there 6 s after the last bead; heavy -> streaks -> off, faded out: no trail, no stain on the canvas, no bead; heavy again: the same, no drop; and with stop/start animation between; humidity off -> faded: the glass clean, and with stop/start between; ice melted -> on again: no frost pixel, no sparkle, and with stop/start between Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 53 +++++++++++++++++---- tests/test_web_dashboard.py | 45 +++++++++++++++++- tests/web_dashboard_browser.js | 85 ++++++++++++++++++++++++++++++++-- 3 files changed, 166 insertions(+), 17 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 1b6b80c5..3463a2c1 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -163,7 +163,8 @@ // trails' time k times as fast (test-only), clock(): the trails', wetAt(x, y): how fresh a trail is there (1 just left, 0 none), // lifeAt(x, y): its life, glassAt(x, y): "dry", "trail" or "fog", fogAt(x, y): [its fog as shown, its fog not wiped] (0-1), // shownAt(x, y): what the fog's canvas shows there [r, g, b, alpha], trailOf(id): a bead's trail as it looks now, its latest rows -// ({y, w, left, wet, alpha, life, fog}: see the probe), fog(): {cover: how far formed, 0-1, dense, thickness, +// ({y, w, left, wet, alpha, life, fog}: see the probe), marks(): {trails, listed: trail pixels, ink: its canvas's pixels showing +// anything, beads, cover, amount}, fog(): {cover: how far formed, 0-1, dense, thickness, // middle, edge: its mean shown, over the window, its middle and its edges, opacity: its mean alpha as drawn (0-1), most: its // thickest shade's alpha, haze: its mean not wiped inside (the window less its outer sixth), spread: its standard deviation there // over that, gaps: the pixels there under half that}, colours(): the beads' sprites' colours [r, g, b, alpha], stray(): pixels on @@ -180,7 +181,7 @@ // any frost, under its crystals, fresh: the growth front's fresh tip pixels, deepest: the crystal furthest from its nearest edge, // of the window's shorter side, rim: the share of the window's outer 3 px frosted, fingers: in 32 stretches of the edges (between // the corners) how far in the furthest crystal reaches, of the shorter side, sparkles: how many now, pixels: the crystals there -// could be} (null till first made); Sky.frost(true): only {extent, target, sparkles}, cheap. +// could be, ink: its canvas's pixels showing anything} (null till first made); Sky.frost(true): only {extent, target, sparkles}, cheap. const Sky = (() => { const holder = document.getElementById("sky"), canvas = holder.querySelector("canvas"), ctx = canvas.getContext("2d"); const STILL = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches; @@ -252,9 +253,11 @@ // An effect: its level (0 off), how present it is (0-1: fading in and out), its strength (how bright at full) and the particles it // would like (at full), resized to the window, stepped and drawn each frame. Each one below fills in its own. One that takes a - // share of the particles (need() above 0) says how many it has with count(), so the budget can be checked. + // share of the particles (need() above 0) says how many it has with count(), so the budget can be checked. Gone all the way (faded + // out, or the animations stopped), it forgets whatever it had (forget(): its particles, and any marks it left, its layer cleared), + // so nothing hidden as it ended shows again when it next comes on. function effect(own) { - const e = {level: 0, amount: 0, strength: () => 0.8, need: () => 0, count: () => 0, resize() {}, step() {}, draw() {}, + const e = {level: 0, amount: 0, strength: () => 0.8, need: () => 0, count: () => 0, resize() {}, step() {}, draw() {}, forget() {}, want(v) { e.level = v; }, fade(dt) { e.amount = STILL ? (e.level > 0 ? 1 : 0) : clamp(e.amount + (e.level > 0 ? dt : -dt) / FADE_S, 0, 1); }, alive: () => e.level > 0 || e.amount > 0}; @@ -318,6 +321,7 @@ probe: () => ({xs: drops.filter((d) => d.y > H / 2 && d.y < H && d.x >= 0 && d.x < W).map((d) => Math.round(d.x)), width: W, under, // (drawn last with its head below a flood's surface) vx: drops.reduce((sum, d) => sum + d.vx, 0) / Math.max(drops.length, 1)}), + forget() { drops = []; splashes = []; under = 0; }, resize() { drops = []; mist = painted(W, Math.ceil(H * 0.12), (x, y) => { // heavy rain's spray, low down @@ -727,6 +731,7 @@ return false; }, resize() { flying = []; eddies = []; wisps = []; splashes = []; }, + forget() { flying = []; eddies = []; wisps = []; splashes = []; gust = 0; }, // (its leaves sunk in a flood too) step(dt, t, share) { calm = clamp(W / 360, CALM, 1); const n = Math.round(this.need() * share); @@ -867,8 +872,9 @@ // shades, dithered; a trail's streak), repainted whole only as it forms, clears or thickens (a few times a second), otherwise only // the pixels a bead wipes, and the trails a slice a frame (all of them every REDRAW s). The wind moves none of it (water on the // glass). The budget: a particle a bead; the shared budget shrinking (another effect on): beads yet to show dropped, then the - // smallest dried away. Gone all the way (no fog, no bead, heavy rain over: the trails fading with it), then on again: the glass - // fresh. Reduced motion: the still frame as it would be some seconds in. + // smallest dried away. The rain easing but still on, its streaks dry on their own time; gone all the way (no fog, no bead, the + // rain over: the trails fading with it), or the animations stopped, every trail, stain and bead forgotten (its canvas cleared), + // so on again it starts on clean glass. Reduced motion: the still frame as it would be some seconds in. const WATER = ["#1A2E41", "#2C5573", "#5793BC", "#A6D7F2", "#EFFAFF"].map(rgb); const FOG = ["#323C43", "#4A555C", "#66717A", "#8995A0", "#AFBAC2"].map(rgb); // the fog, thin to thick: pale grey, the page's const FOG_ALPHA = [56, 69, 81, 91, 101]; // ... cool dark palette (alpha 0-255) @@ -1257,7 +1263,9 @@ if (listed) { listed.fill(0); key.fill(0); img.data.fill(0); drawn = [0, 0]; dirty = null; layer.getContext("2d").clearRect(0, 0, W, H); } } const heavy = () => rain.level >= HEAVY_RAIN; - const present = () => e.level > 0 || cover > 0 || all.length > 0 || heavy(); + // (on while it's called for, its fog there, a bead on the glass, or heavy rain; and while the rain is still on, its streaks drying + // on their own time. The rain over, the streaks fade out with it, and are gone for good: see forget) + const present = () => e.level > 0 || cover > 0 || all.length > 0 || heavy() || (rain.level > 0 && trails.length > 0); // The fog's mean thickness (0-1, as shown): over the window, its middle (the central fifth each way) and its edges (the outer // tenth at the sides and the bottom); every other pixel each way. And how even it is, unwiped, inside (the window less its outer // sixth): its spread (the standard deviation over the mean) and its gaps (the pixels under half the mean) @@ -1289,6 +1297,7 @@ }, fade(dt) { e.amount = present() ? 1 : STILL ? 0 : Math.max(0, e.amount - dt / FADE_S); }, // (the trails fading out last) alive: () => present() || e.amount > 0, + forget: clear, // (faded out all the way: fog, beads, trails and stains gone, its layer cleared) resize() { till = new Float64Array(W * H); life = new Float32Array(W * H); @@ -1409,6 +1418,13 @@ } return [...found].sort().map((c) => c.split(",").map(Number)); }, + // (what's on the glass: trail pixels listed, its canvas's pixels with anything on them, the beads, the fog) + marks: () => { + let ink = 0, wet = 0; + if (layer) { const d = layer.getContext("2d").getImageData(0, 0, W, H).data; for (let i = 3; i < d.length; i += 4) if (d[i]) ink++; } + if (listed) for (let i = 0; i < W * H; i++) wet += listed[i]; + return {trails: trails.length, listed: wet, ink, beads: all.length, cover, amount: e.amount}; + }, stray: () => { // (pixels left wiped, or wet, on the fog's canvas where no trail is any more) if (!layer) return 0; const d = layer.getContext("2d").getImageData(0, 0, W, H).data; @@ -1565,6 +1581,7 @@ }, fade(dt) { e.amount = depth > 0 || e.level > 0 ? 1 : 0; }, alive: () => e.level > 0 || depth > 0, + forget() { depth = 0; if (h) { h.fill(0); v.fill(0); far.fill(0); } frog = null; splashes = []; chop = 0; }, resize() { full = Math.max(8, Math.round(H * SPAN)); rows = full + TOP; @@ -1834,6 +1851,10 @@ want(v) { e.level = v; if (STILL) extent = reachFor(v); }, fade() { e.amount = extent > 0 ? 1 : 0; }, alive: () => e.level > 0 || extent > 0, + forget() { // (melted away, or the animations stopped: no frost, no sparkle, its canvas clear) + extent = 0; glints = []; shownAt = -1; + if (img) { img.data.fill(0); layer.getContext("2d").clearRect(0, 0, W, H); } + }, reach: () => extent, resize() { grow(); }, step(dt) { @@ -1879,7 +1900,10 @@ const b = edge * 8 + Math.min(7, Math.floor((along - 0.15) / 0.7 * 8)); most[b] = Math.max(most[b], inward); } - return {extent, target: reachFor(e.level), growing: grows, frosted: frosted / (W * H), crystals: crystal / (W * H), fresh, + const shown = layer.getContext("2d").getImageData(0, 0, W, H).data; // (its canvas: the pixels with anything on them) + let ink = 0; + for (let i = 3; i < shown.length; i += 4) if (shown[i]) ink++; + return {extent, target: reachFor(e.level), growing: grows, frosted: frosted / (W * H), crystals: crystal / (W * H), fresh, ink, deepest: deepest / m, rim: rimFrosted / rim, fingers: Array.from(most, (v) => v / m), sparkles: glints.length, pixels: crystals.length}; }, @@ -2099,6 +2123,7 @@ want() {}, // (no condition of its own: fling() sends one, and it's on while one is crossing) fade() { e.level = e.amount = flyers.length || bits.length ? 1 : 0; }, clear() { flyers = []; bits = []; e.level = e.amount = 0; }, + forget() { this.clear(); }, fling(kind) { if (!KINDS.includes(kind)) { if (!bag.length) bag = KINDS.slice().sort(() => random() - 0.5); @@ -2177,7 +2202,13 @@ function tick(dt) { let need = 0; for (const k of ORDER) if (effects[k].alive() && !effects[k].sized) { effects[k].resize(); effects[k].sized = true; } - for (const k of ORDER) { effects[k].fade(dt); if (effects[k].amount > 0 || effects[k].level > 0) need += effects[k].need(); } + for (const k of ORDER) { + const fx = effects[k]; + fx.fade(dt); + if (fx.alive()) fx.held = true; + else if (fx.held) { fx.held = false; fx.forget(); } // (gone all the way: whatever it had, forgotten) + if (fx.amount > 0 || fx.level > 0) need += fx.need(); + } const share = Math.min(1, W * H * BUDGET / Math.max(need, 1)); for (const k of ORDER) if (effects[k].alive()) effects[k].step(dt, clock, share); } @@ -2233,8 +2264,10 @@ function set(want, on) { animate = on; if (!W) resize(); - if (!on) effects.gust.clear(); // (anything blown across, gone) for (const k of ORDER) effects[k].want(want[k] || 0); + // (stopped: every effect gone at once, and all it had forgotten (anything blown across, the glass's streaks, the frost ...), + // so each starts afresh once the animations are on again) + if (!on) for (const k of ORDER) { const fx = effects[k]; fx.forget(); fx.amount = 0; fx.held = false; } start(); } diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 10eeffdb..426c9179 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -1291,9 +1291,16 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red # ... every other effect then on too, humidity's share of the budget shrinking: fewer beads, none vanishing squeezed = got["humidity"]["alone"]["squeezed"] assert squeezed["count"][1] < squeezed["count"][0] and squeezed["popped"] == 0 and squeezed["stray"] == 0, squeezed - # ... then all off, faded out all the way (some trail still there as it went), and humidity on again: the glass fresh + # ... then all off (trails there as it went), faded out all the way: every trail and bead forgotten, its canvas clear; and + # humidity on again: the glass fresh again = got["humidity"]["alone"]["again"] - assert again["before"] > 0 and again == {"before": again["before"], "trails": 0, "beads": 0, "stray": 0}, again + assert again["before"] > 0 and again == {"before": again["before"], "trails": 0, "beads": 0, "stray": 0, "gone": again["gone"], "marks": again["marks"]}, again + clean_glass(again["gone"]) + clean_glass(again["marks"]) + # ... then its beads leaving trails, and "stop animation", "start animation", humidity on again: the glass fresh too + marked = got["humidity"]["alone"]["marked"] + assert marked["trails"] > 30 and marked["ink"] > 0 and marked["cover"] > 0, marked + started_afresh(got["humidity"]["alone"]["restarted"], "humidity") # BEAD_RULES, the physics every bead runs by: its speed on each glass, dry slowest, a trail medium (twice dry's), fog fastest # (5/3 of a trail's), for the same size; rising gradually with its size (tiny r 0.6 creeping extremely slowly, under 0.01 px/s on # fog; r 1 a little quicker; then faster and faster, no fastest); after 20 px in 5 s: on fog bigger (however big already: no @@ -1347,6 +1354,20 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red # (each run off or shrunk to nothing, or merged into one that was: none dried away otherwise) assert gone["ranOff"] + gone["shrunk"] > eased["ranOff"] + eased["shrunk"] and eased["beads"] > 0, (eased, gone) assert gone["faded"] == eased["faded"], (eased, gone) + # ... their streaks, the rain still on, drying on their own time: there still 6 s after the last bead had gone + easing = sticking["easing"] + assert easing["at"]["beads"] == 0 and easing["at"]["trails"] > 0, easing + assert easing["after"]["trails"] > 0 and easing["after"]["ink"] > 0 and easing["after"]["amount"] == 1, easing + # heavy again, streaks on the glass; off, faded out all the way: every streak and stain forgotten, its canvas clear; heavy + # again: clean glass, nothing from before (no trail, no stain, no bead, no drop); and the same with the animations stopped + # and started between + for streaked in (sticking["streaked"], sticking["streakedAgain"]): + assert streaked["trails"] >= 30 and streaked["ink"] > 0, streaked + cleared = sticking["cleared"] + clean_glass(cleared["gone"]) + clean_glass(cleared["again"]) + assert cleared["stray"] == 0 and cleared["drops"] == 0, cleared + started_afresh(sticking["restarted"], "rain") # the wind blows right to left: its leaves leftward overall, as drawn on the canvas too (frame to frame); some caught in a loop # going rightward a moment (on a phone too) for seen in (got["wind"], got["phoneWind"]): @@ -1395,6 +1416,12 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert melting["extent"] < cold["extent"] and melting["crystals"] < 0.9 * cold["crystals"], (melting, cold) assert melting["rim"] >= 0.97 * cold["rim"] and melting["fresh"] == 0, (melting, cold) assert frost["gone"]["extent"] == 0 and frost["gone"]["frosted"] == 0 and not frost["gone"]["running"], frost["gone"] + # ... and on again, nothing from before (its canvas clear, no sparkle); grown half a minute, then the animations stopped and + # started again, and on: the same + assert frost["again"] == {"extent": 0, "ink": 0, "sparkles": 0}, frost["again"] + assert frost["grown"]["extent"] > 0 and frost["grown"]["ink"] > 0, frost["grown"] + started_afresh(frost["restarted"], "ice") + assert frost["restarted"]["frost"] == {"extent": 0, "ink": 0, "sparkles": 0}, frost["restarted"] # reduced motion: no loop, one still, faint frame (the ice as it would be), the frames and the link as ever still = got["still"] assert still["effects"] == ["uv", "ice"] and not still["running"] and still["frames"] == 0 and still["stateFrames"] == 0, still @@ -1411,6 +1438,20 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert still["gust"] == {"fling": None, "sent": 0, "running": False, "frames": 0}, still["gust"] +def clean_glass(marks): + """Nothing on the glass (Sky.state().humidity.marks()): no trail, no stain on its canvas, no bead, no fog""" + assert {k: marks[k] for k in ("trails", "listed", "ink", "beads", "cover")} == {"trails": 0, "listed": 0, "ink": 0, "beads": 0, "cover": 0}, marks + + +def started_afresh(seen, effect): + """"stop animation", `effect` on, "start animation" (restarted() in the browser script): the loop stopped between, + and nothing from before: the glass clean, no drop, no stray pixel""" + assert seen["link"] == "stop animation" and seen["stopped"]["link"] == "start animation" and not seen["stopped"]["running"], seen + clean_glass(seen["stopped"]["marks"]) + clean_glass(seen["marks"]) + assert seen["stray"] == 0 and seen["drops"] == 0 and effect in seen["effects"], seen + + @needs_browser async def test_a_flash_flood_fills_the_window_a_quarter_up_its_surface_choppy_what_falls_ending_at_it_and_a_frog_now_and_then(server, station): got = await weather(server, "flood") diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 8cbfe267..3b922718 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1260,6 +1260,20 @@ const rainBeads = (page, light, heavy, after, scale, from = "light") => page.eva }; requestAnimationFrame(step); }), [light, heavy, after, scale, from]); +// "stop animation" (an effect on: the link shows; it ends the test links' effects), then `detail` on (stopped still: "start +// animation" shows), then "start animation", all at once (no frame between): the loop and the glass (humidity's marks) as stopped, +// and once started, the glass, the frost and the rain's drops then +const restarted = (page, detail) => page.evaluate((detail) => { + const toggle = () => document.querySelector("#motion .animations").click(), seen = {}; + seen.link = document.querySelector("#motion .animations").textContent; + toggle(); + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail })); + seen.stopped = { running: Sky.state().running, link: document.querySelector("#motion .animations").textContent, marks: Sky.state().humidity.marks() }; + toggle(); + const f = Sky.frost(); + return { ...seen, marks: Sky.state().humidity.marks(), stray: Sky.state().humidity.stray(), drops: Sky.state().particles.rain, + frost: f && { extent: f.extent, ink: f.ink, sparkles: f.sparkles }, effects: Sky.state().effects }; +}, detail); const framesIn = async (page, ms) => { // the frames the page asked for in this long const before = await page.evaluate(() => window.__frames); await page.waitForTimeout(ms); @@ -1729,6 +1743,17 @@ const WEATHER = { seen.melting = await frost(); await until(() => !Sky.state().running); seen.gone = await frost(); + // (on again: nothing from before, its canvas clear, no sparkle; then grown half a minute, and "stop animation", "start + // animation" and on again: the same) + seen.again = await p.page.evaluate(() => { + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { ice: 5 } })); + const f = Sky.frost(); + return { extent: f.extent, ink: f.ink, sparkles: f.sparkles }; + }); + from = await p.page.evaluate(() => Sky.state().clock); + await until((t) => Sky.state().clock >= t, from + 30); + seen.grown = await frost(); + seen.restarted = await restarted(p.page, { ice: 5 }); return seen; }; const swaying = (async () => { @@ -1755,14 +1780,24 @@ const WEATHER = { await p.page.evaluate(() => document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { rain: 1, smog: 3, uv: 1, humidity: 1, wind: 1, heat: 1, ice: 5 } }))); seen.squeezed = await humiditySeen(p.page, 40); // (then all off, faded out all the way, and humidity on again: the glass fresh, nothing left from before) - await p.page.evaluate(() => document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: {} }))); + const before = await p.page.evaluate(() => { // (the trails as it's turned off) + const trails = Sky.state().humidity.trails; + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: {} })); + return trails; + }); await p.page.waitForFunction(() => !Sky.state().running); - seen.again = await p.page.evaluate(() => { - const before = Sky.state().humidity.trails; + seen.again = await p.page.evaluate((before) => { + const gone = Sky.state().humidity.marks(); // (faded out all the way: forgotten) document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { humidity: 1 } })); const h = Sky.state().humidity; - return { before, trails: h.trails, beads: h.beads.length, stray: h.stray() }; - }); + return { before, trails: h.trails, beads: h.beads.length, stray: h.stray(), gone, marks: h.marks() }; + }, before); + // (then its beads running and leaving trails (the weather's time 30 times as fast), and "stop animation", "start animation" + // and humidity on again: the glass fresh too) + await p.page.evaluate(() => Sky.timeScale(30)); + await p.page.waitForFunction(() => Sky.state().humidity.trails > 30, null, { timeout: 20000 }); + seen.marked = await p.page.evaluate(() => { Sky.timeScale(1); return Sky.state().humidity.marks(); }); + seen.restarted = await restarted(p.page, { humidity: 1 }); // (and the physics the beads run by: a bead's mean speed on each glass, by size; its size after running 20 px in 5 s there) seen.physics = await p.page.evaluate(() => { const { speed, after, gone } = Sky.state().humidity.physics, sizes = [0.6, 1, 1.4, 2, 2.8, 4, 6, 10]; @@ -1786,6 +1821,46 @@ const WEATHER = { let looks; ({ eased: seen.eased, after: seen.after, looks } = await rainBeads(p.page, 0, 0, 300, 6, "heavy")); seen.looks.push(...looks); // (the trails' looks, those running on too) + // the rain easing, still on (light): its streaks drying on their own time, there still 6 s (of its weather's time) after + seen.easing = await p.page.evaluate(() => new Promise((resolve) => { + const at = Sky.state().humidity.marks(), from = Sky.state().clock; + Sky.timeScale(6); + const look = () => { + if (Sky.state().clock < from + 6) return requestAnimationFrame(look); + Sky.timeScale(1); + resolve({ at, after: Sky.state().humidity.marks() }); + }; + requestAnimationFrame(look); + })); + // heavy again (its weather's time 10 times as fast) till more streaks; off, faded out all the way (the loop over, its time 30 + // times as fast); heavy + // again: the glass clean, nothing from before (its trails, its canvas, its beads; the rain's drops) + const heavyTill = (more) => p.page.evaluate((more) => new Promise((resolve) => { + const from = Sky.state().humidity.marks().trails; + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { rain: 1 } })); + Sky.timeScale(10); + let n = 0; + const look = () => { + const m = Sky.state().humidity.marks(); + if (m.trails < from + more && n++ < 900) return requestAnimationFrame(look); + Sky.timeScale(1); + resolve(m); + }; + requestAnimationFrame(look); + }), more); + seen.streaked = await heavyTill(30); + await p.page.evaluate(() => { document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: {} })); Sky.timeScale(30); }); + await p.page.waitForFunction(() => !Sky.state().running, null, { timeout: 20000 }); + seen.cleared = await p.page.evaluate(() => { + Sky.timeScale(1); + const gone = Sky.state().humidity.marks(); + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { rain: 1 } })); + const s = Sky.state(); + return { gone, again: s.humidity.marks(), stray: s.humidity.stray(), drops: s.particles.rain }; + }); + // ... and the same with "stop animation" and "start animation" between + seen.streakedAgain = await heavyTill(30); + seen.restarted = await restarted(p.page, { rain: 1 }); seen.errors = p.errors; await p.context.close(); return seen; From e00144d814e22ead65bbecde4599d3df9f8005ea Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:48:04 +0000 Subject: [PATCH 047/146] Web dashboard: more natural frost, never twice alike. The ice grows several crystal forms mixed: long feathery fern fronds, short dense plumes, needles radiating from a point, and small six-armed stars, twigged stars and little plates scattered on the glass ahead of the front. Each frond has its own make: its branches' angle (mostly near 60 degrees to the stem, ice's hexagonal habit, each frond's own spread), spacing, length and fall-off toward the tip, barb density, curve and wander, thickness (bold fronds' stems two pixels), brightness (some bold and bright, others fine and faint) and tint (icy blue, greener, silvery); ridges brighter than side branches, those than barbs, the shade wandering along each frond, a touch brighter where fronds cross. Seeds are clustered in some stretches of the edges and sparse in others (and thick in the corners), a few start a little way in as if from a scratch; the bloom only about the bolder crystals. Growth from the edges, its pace and reach, the fresh tips, sparkles, edge haze, melting and forgetting are as before; the frame cost unchanged (the layer is still redrawn only where it changes). Sky.frost() gains made (forms, fronds, seeds, scratches) and shades. Test, in the existing session: every form present (5+ each) and a scratch; fronds' lengths (90th percentile over 5x the 10th, the longest over 60 px) and branch spacings (over 2.5x) spread widely; the branches' median angle 55-65 degrees, spread between fronds; the seeds' gaps along the edges uneven; stems brighter than side branches, those than barbs, shades spread, 3+ tints. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 223 +++++++++++++++++++++++++++--------- tests/test_web_dashboard.py | 16 +++ 2 files changed, 188 insertions(+), 51 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 3463a2c1..ae96b93f 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -181,7 +181,12 @@ // any frost, under its crystals, fresh: the growth front's fresh tip pixels, deepest: the crystal furthest from its nearest edge, // of the window's shorter side, rim: the share of the window's outer 3 px frosted, fingers: in 32 stretches of the edges (between // the corners) how far in the furthest crystal reaches, of the shorter side, sparkles: how many now, pixels: the crystals there -// could be, ink: its canvas's pixels showing anything} (null till first made); Sky.frost(true): only {extent, target, sparkles}, cheap. +// could be, ink: its canvas's pixels showing anything, made: what was grown {forms: how many of each ({fern, plume, needles, +// star}), fronds: each fern's and plume's stem {kind, length, branches, spacing: its length a branch, angle: its branches' mean +// to it, degrees}, seeds: [edge (0 top, 1 bottom, 2 left, 3 right), where along it] each along the edges, scratches: how many +// from a little way in}, shades: the crystals shown now (not the fresh tips) {mean, spread: their alphas' standard deviation, +// tints: how many tints, stem, side, barb: the mean alpha of each}} (null till first made); Sky.frost(true): only {extent, +// target, sparkles}, cheap. const Sky = (() => { const holder = document.getElementById("sky"), canvas = holder.querySelector("canvas"), ctx = canvas.getContext("2d"); const STILL = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches; @@ -1695,26 +1700,39 @@ }; }); - // ---------- ice: frost ferns creeping in from the window's edges, thickest in the corners, further and faster the colder ---------- - // Grown once for the window's size, like frost on a window pane: from seeds all round the edges (closer in the corners) fronds, - // each a wandering stem with fine side branches every pixel or two (shorter toward its tip, so it ends in a feathery point) and - // tiny barbs on those, now and then forking into a frond of its own; the stems uneven, some short, some reaching far across the - // glass. Each pixel knows when the frost gets there (`extent`, on the ice's own measure: a stem's own pace times it is how far it - // has crept) and its shade; about each frond a faint dithered bloom, and along the edges a soft dithered haze, thickest in the - // corners. Shown out to `extent` on an offscreen canvas (only the pixels whose look changed redrawn: the ones just reached or - // melted, the growth front's fresh white tips), blitted each frame, a few sparkles catching the light now and then. Melting, the - // tips go first, the edges last. + // ---------- ice: frost creeping in from the window's edges, thickest in the corners, further and faster the colder ---------- + // Grown once for the window's size, like frost on a window pane, and never twice alike: seeds along the edges, thick in some + // stretches (and in the corners), sparse in others with bare glass between, a few a little way in (as if from a scratch), each + // one of several forms: long feathery fern fronds (a wandering stem, side branches every pixel or few, mostly near 60° to it as + // ice's hexagonal habit has them, shorter toward the tip, so it ends in a feathery point, with finer barbs on them, now and then + // forking into a frond of its own), short dense plumes, needles radiating from a point; and small six-armed stars and plates + // scattered on the glass ahead of the front. Each frond its own make: its branches' angle, spacing and length, how dense, how + // much it curves, how bold (a bold one's stem two pixels thick), its tint and brightness (some bold and bright, others fine and + // faint), its ridge brighter than its branches, those than its barbs, the shade wandering a little along it; where fronds cross, + // a touch brighter. Each pixel knows when the frost gets there (`extent`, on the ice's own measure: a stem's own pace times it is + // how far it has crept), its shade and its tint; about the bolder crystals a faint dithered bloom, and along the edges a soft + // dithered haze, thickest in the corners. Shown out to `extent` on an offscreen canvas (only the pixels whose look changed + // redrawn: the ones just reached or melted, the growth front's fresh white tips), blitted each frame, a few sparkles catching + // the light now and then. Melting, the tips go first, the edges last. const ICE = ["#7FB6CF", "#A6DCEE", "#C2EAF7", "#DDF6FC", "#F0FCFF", "#FFFFFF"].map(rgb); + // the crystals' tints, each a ramp from faint to bright (frost catching the light a little differently frond to frond): icy + // blue, as the haze, a touch greener, silvery + const FROST_TINTS = [["#6FA8C6", "#8EC6DF", "#AEDCEE", "#CDEDF8", "#E8F8FD", "#FFFFFF"], ICE.map((c) => "#" + c.map((v) => v.toString(16).padStart(2, "0")).join("")), + ["#78B6C2", "#98D3D9", "#B9E7EA", "#D5F4F4", "#EDFCFC", "#FFFFFF"], + ["#97B6CA", "#B5CFDF", "#CDE2EE", "#E1EEF6", "#F1F8FB", "#FFFFFF"]].map((ramp) => ramp.map(rgb)); const ice = effect((e) => { - // each pixel's look: [colour, alpha]; 0, 1 the haze, 2 the bloom, 3 a barb, 4 a side branch, 5 a stem, 6 a fresh tip - const LOOK = [[ICE[0], 95], [ICE[1], 135], [ICE[1], 90], [ICE[2], 125], [ICE[3], 165], [ICE[4], 215], [ICE[5], 255]]; + // each pixel's look: 0, 1 the haze, 2 the bloom (each [colour, alpha]); a crystal's: 3 a barb, 4 a side branch (or a star's + // arm), 5 a stem (or a needle, a star's heart), 6 a fresh tip; a crystal's colour and alpha its own + const LOOK = [[ICE[0], 95], [ICE[1], 135], [ICE[1], 90]]; const BLOOM = 2, BARB = 3, SIDE = 4, STEM = 5, FRESH = 6; const GLINT = [mapped(["5"], {5: ICE[5]}), mapped([".4.", "454", ".4."], {4: ICE[3], 5: ICE[5]}), mapped(["...3...", "...4...", "...5...", "3455543", "...5...", "...4...", "...3..."], {3: ICE[2], 4: ICE[3], 5: ICE[5]})]; let extent = 0, shownAt = -1, shownGrowing = false, layer = null, img = null, glints = []; - // per pixel: when a crystal reaches it (Infinity: never) and its look; when its bloom does; how far in it is for the haze - let crystalAt = null, crystalLook = null, bloomAt = null, hazeIn = null; + // per pixel: when a crystal reaches it (Infinity: never), its look, alpha and tint; when its bloom does; how far in it is for + // the haze + let crystalAt = null, crystalLook = null, crystalAlpha = null, crystalTint = null, bloomAt = null, hazeIn = null; let crystals = null, crystalKeys = null, blooms = null, bloomKeys = null, hazes = null, hazeKeys = null; // (each sorted by its key) + let made = null; // (for the tests: what was grown: its forms, its fronds, its seeds) const big = () => Math.max(W, H); // How far the frost creeps (on its own measure; a stem goes its own pace times it, about 0.6 to 1.9): just below 0 °C a fringe, // 3.5 % of the window's longer side; at -5 °C 65 %, reaching well across the glass; to 80 % at -10 °C and colder @@ -1740,59 +1758,151 @@ return lo; }; function grow() { - const n = W * H, r = seeded(4242), D = big(), m = Math.min(W, H); - crystalAt = new Float32Array(n).fill(Infinity); crystalLook = new Uint8Array(n); - bloomAt = new Float32Array(n).fill(Infinity); hazeIn = new Float32Array(n); - const mark = (x, y, at, look) => { + const n = W * H, r = seeded(4242), D = big(), m = Math.min(W, H), DEG = Math.PI / 180; + crystalAt = new Float32Array(n).fill(Infinity); crystalLook = new Uint8Array(n); crystalAlpha = new Uint8Array(n); + crystalTint = new Uint8Array(n); bloomAt = new Float32Array(n).fill(Infinity); hazeIn = new Float32Array(n); + made = {forms: {fern: 0, plume: 0, needles: 0, star: 0}, fronds: [], seeds: [], scratches: 0}; + const mark = (x, y, at, look, alpha, tint) => { x = Math.round(x); y = Math.round(y); if (x < 0 || y < 0 || x >= W || y >= H) return; const i = y * W + x; - if (at < crystalAt[i]) { crystalAt[i] = at; crystalLook[i] = look; } + alpha = clamp(Math.round(alpha), 40, 240); + if (at < crystalAt[i]) { + if (crystalAt[i] < Infinity) alpha = Math.min(240, Math.max(alpha, crystalAlpha[i]) + 14); // (where two cross) + crystalAt[i] = at; crystalLook[i] = look; crystalAlpha[i] = alpha; crystalTint[i] = tint; + } else crystalAlpha[i] = Math.min(240, Math.max(alpha, crystalAlpha[i]) + 14); }; + let ids = 0; + // A frond's own make (o): its branches' spacing ([least, most] px along the stem), angle to the stem (about 60°) and how much + // that wanders, their length (most, px; shape: how it falls off toward the tip), barbs (the chance of each on a branch, how + // long, how far apart), how it curves and wanders, how bright (its stem's alpha; its branches' and barbs' a share of that), + // tint, bold (a stem two pixels thick), how deep it branches, its forks, whether its branches alternate side to side or + // lean to one side + const fern = (bold) => { + const sparse = r() < 0.25, lo = sparse ? 2.6 + r() * 2.6 : 1.1 + r() * 1.9, tier = bold ? 1 : r(); // (some spiky and open) + return {id: ++ids, spacing: [lo, lo * (1.25 + r() * 1.1)], angle: (54 + r() * 13) * DEG, jit: (6 + r() * 16) * DEG, + reach: sparse ? 2 + r() * 3 : 3 + r() * r() * 11, shape: 0.5 + r() * 1.3, barbs: 0.25 + r() * 0.75, barbReach: 1.2 + r() * 2.2, + barbGap: [1.1 + r() * 0.6, 2.2 + r() * 1.4], curve: (r() - 0.5) * 0.02, wander: 0.002 + r() * 0.007, + alpha: bold ? 205 + r() * 30 : tier < 0.35 ? 115 + r() * 35 : 160 + r() * 45, sideK: 0.7 + r() * 0.2, + barbK: 0.5 + r() * 0.2, tint: (r() * FROST_TINTS.length) | 0, bold, depth: 2, forks: 2, forkP: 0.008 + r() * 0.03, + slow: 0.38 + r() * 0.14, lean: r() < 0.3 ? (r() < 0.5 ? 0.2 : 0.8) : 0}; + }; + const plume = () => { + const lo = 0.75 + r() * 0.5; + return {...fern(false), spacing: [lo, lo * (1.2 + r() * 0.4)], angle: (50 + r() * 16) * DEG, reach: 4 + r() * 7, shape: 0.3 + r() * 0.5, + barbs: 0.7 + r() * 0.3, barbGap: [0.9, 1.5 + r()], curve: (r() - 0.5) * 0.05, wander: 0.006 + r() * 0.012, + alpha: 125 + r() * 55, sideK: 0.8 + r() * 0.12, barbK: 0.6 + r() * 0.15, forks: 0}; + }; + const needle = (tint) => ({...fern(false), spacing: [5 + r() * 6, 12 + r() * 12], reach: 1 + r() * 2.5, barbs: 0, curve: (r() - 0.5) * 0.004, + wander: 0.0005, alpha: 150 + r() * 80, depth: 1, forks: 0, tint}); // A frond from (x, y) heading `angle`, `length` long, reached at `from`, going `pace` px for each of `extent`; side branches // (depth 1) and barbs (2) slower than what they grow from, so a frond's growing tip is a feathery point - const frond = (x, y, angle, length, from, pace, depth, forks) => { + const frond = (x, y, angle, length, from, pace, depth, o, kind) => { const step = 0.6, look = depth === 0 ? STEM : depth === 1 ? SIDE : BARB; - let a = angle, bend = (r() - 0.5) * 0.03, side = r() < 0.5 ? 1 : -1, dx = Math.cos(a) * step, dy = Math.sin(a) * step; - let next = depth === 0 ? 1.5 + r() * 2 : 1 + r() * 1.5; - for (let s = 0; s <= length; s += step) { + const base = depth === 0 ? o.alpha : o.alpha * (depth === 1 ? o.sideK : o.barbK) * (0.85 + r() * 0.3); + let a = angle, bend = depth === 0 ? o.curve : o.curve * 0.4, drift = 0, side = r() < 0.5 ? 1 : -1; + let dx = Math.cos(a) * step, dy = Math.sin(a) * step, branches = 0, turned = 0; + const gap = () => depth === 0 ? o.spacing[0] + r() * (o.spacing[1] - o.spacing[0]) : o.barbGap[0] + r() * (o.barbGap[1] - o.barbGap[0]); + let next = gap() * (0.4 + r() * 0.8), s = 0; + for (; s <= length; s += step) { x += dx; y += dy; - if (x < -1 || y < -1 || x > W || y > H) return; - mark(x, y, from + s / pace, look); - if (depth === 0) { // (a stem wanders a little; its branches straight) - bend = (bend + (r() - 0.5) * 0.005) * 0.95; a += bend; dx = Math.cos(a) * step; dy = Math.sin(a) * step; + if (x < -1 || y < -1 || x > W || y > H) break; + const at = from + s / pace, tip = clamp((length - s) / 5, 0.6, 1); // (finer at the very tip) + mark(x, y, at, look, base * tip * (0.8 + 0.4 * noise(s / 7, o.id, 4096, 31)), o.tint); + if (o.bold && depth === 0 && length - s > 5) mark(x - dy / step, y + dx / step, at + 0.5, look, base * 0.62, o.tint); + if (depth === 0) { // (a stem wanders a little and curves its own way; its branches nearly straight) + drift = (drift + (r() - 0.5) * o.wander) * 0.95; a += bend * step + drift; dx = Math.cos(a) * step; dy = Math.sin(a) * step; } - if (depth < 2 && s >= next && length - s > 1.5) { - const left = length - s, at = from + s / pace; - if (depth === 0 && forks > 0 && left > 25 && r() < 0.02) { // a fork: a frond of its own - frond(x, y, a + side * (0.45 + r() * 0.35), left * (0.4 + r() * 0.5), at, pace * (0.8 + r() * 0.3), 0, forks - 1); - } else { - const most = depth === 0 ? 3 + r() * 7 : 1 + r() * 2, size = Math.min(most, left * (depth === 0 ? 0.4 : 0.5)); - if (size >= 1) frond(x, y, a + side * (0.9 + r() * 0.35), size, at, pace * (depth === 0 ? 0.45 : 0.4), depth + 1, 0); + if (depth < o.depth && s >= next && length - s > 1.5) { + const left = length - s, t = s / length; + if (depth === 0 && o.forks > 0 && left > 25 && r() < o.forkP) { // a fork: a frond of its own + frond(x, y, a + side * (0.7 + r() * 0.35), left * (0.4 + r() * 0.5), at, pace * (0.8 + r() * 0.3), 0, {...o, id: ++ids, forks: o.forks - 1}); + } else if (depth === 1 ? r() < o.barbs : true) { + const most = depth === 0 ? o.reach * (0.5 + r() * 0.7) * Math.pow(Math.sin(Math.PI * (0.12 + 0.88 * t)), o.shape) : o.barbReach * (0.5 + r() * 0.8); + const size = Math.min(most, left * (depth === 0 ? 0.5 : 0.6)), turn = o.angle + (r() - 0.5) * o.jit; + if (size >= 1) { + frond(x, y, a + side * turn, size, at, pace * o.slow, depth + 1, o); + branches++; turned += turn; + } } - side = -side; - next = s + (depth === 0 ? 1.6 + r() * 1.8 : 1.4 + r() * 1.4); + side = o.lean ? (r() < o.lean ? 1 : -1) : -side; + next = s + gap(); } } + if (kind) made.fronds.push({kind, length: Math.round(Math.min(s, length) * 10) / 10, branches, + spacing: branches > 1 ? Math.min(s, length) / branches : null, angle: branches ? turned / branches / DEG : null}); }; - const edges = [[W, (p) => [p, 0], Math.PI / 2], [W, (p) => [p, H - 1], -Math.PI / 2], - [H, (p) => [0, p], 0], [H, (p) => [W - 1, p], Math.PI]]; - for (const [span, at, inward] of edges) { - for (let p = r() * 4; p < span; ) { + // ... the forms, from a seed at (x, y) heading inward (`inward`, the way into the glass), reached at `from`; `corner`: how + // near a corner (0-1), its fronds longer there + const planted = (x, y, inward, from, corner, kind) => { + const pace = (0.6 + r() * 0.6) * (1 + 0.6 * corner); + if (kind === "fern") { + const u = r(), length = D * (0.04 + 0.95 * u * u * u) * (1 + 0.4 * corner); // (most short, a few reaching far) + const o = fern(r() < 0.22); + o.reach = Math.min(15, o.reach * (0.6 + length / 80)); // (a long frond's branches longer) + frond(x, y, inward, length, from, pace, 0, o, "fern"); + } else if (kind === "plume") { + frond(x, y, inward, 7 + r() * r() * 30, from, pace * 0.8, 0, plume(), "plume"); + } else { // needles: a few to many from one point, fanned about the way in, each its own length + const count = 3 + Math.floor(r() * 6), spread = 0.8 + r() * 1.4, tint = (r() * FROST_TINTS.length) | 0; + for (let k = 0; k < count; k++) { + const u = r(); + frond(x, y, inward + (r() - 0.5) * spread, 3 + u * u * 26, from + r() * 2, pace * (0.9 + r() * 0.5), 0, needle(tint)); + } + } + made.forms[kind]++; + }; + const edges = [[W, (p, d) => [p, d], Math.PI / 2], [W, (p, d) => [p, H - 1 - d], -Math.PI / 2], + [H, (p, d) => [d, p], 0], [H, (p, d) => [W - 1 - d, p], Math.PI]]; + edges.forEach(([span, at, inward], edge) => { + for (let p = r() * 6; p < span; ) { const corner = Math.pow(clamp(1 - Math.min(p, span - p) / (0.35 * m), 0, 1), 1.5); + const thick = Math.max(corner, noise(p / 30, edge * 17 + 3, 4096, 57)); // (stretches thick with seeds, others sparse) const toward = (p < span / 2 ? -1 : 1) * (inward === Math.PI || inward === Math.PI / 2 ? -1 : 1); // (a corner's lean) - const tilt = (r() - 0.5) * 1.0 + corner * 0.5 * toward; - const u = r(), length = D * (0.04 + 0.95 * u * u * u) * (1 + 0.4 * corner); // (most short, a few reaching far) - const pace = (0.6 + r() * 0.6) * (1 + 0.6 * corner); - const [x, y] = at(p); - frond(x, y, inward + tilt, length, r() * 4, pace, 0, 2); - p += (16 + r() * 20) * (1 - 0.6 * corner); + const tilt = (r() - 0.5) * (0.6 + r() * 0.9) + corner * 0.5 * toward, u = r(); + const kind = u < 0.45 + 0.35 * corner ? "fern" : u < 0.78 + 0.15 * corner ? "plume" : "needles"; + const [x, y] = at(p, 0); + planted(x, y, inward + tilt, r() * 6, corner, kind); + made.seeds.push([edge, Math.round(p * 10) / 10]); + p += (5 + r() * 21) * (0.3 + 2.8 * Math.pow(1 - thick, 2.4)) * (1 - 0.4 * corner); } + }); + // ... a few from a little way in, as if from a scratch: any way + for (let k = 2 + Math.floor(r() * 4); k > 0; k--) { + const [span, at, inward] = edges[Math.floor(r() * 4)], d = 4 + r() * 0.08 * m, [x, y] = at(0.15 * span + r() * 0.7 * span, d); + planted(x, y, inward + (r() - 0.5) * 2.6, d / 1.2, 0, r() < 0.6 ? "fern" : "needles"); + made.scratches++; + } + // ... and the stars: small six-armed crystals scattered on the glass ahead of the front, more near the edges: plain stars, + // stars with twigs on their arms (at 60°) and little plates; each its own size, tilt, brightness and tint + for (let k = Math.round(W * H / 1200); k > 0; k--) { + const x = 2 + r() * (W - 4), y = 2 + r() * (H - 4), inward = Math.min(x, y, W - 1 - x, H - 1 - y); + if (inward > 0.45 * m || r() < inward / (0.45 * m) * 0.7) continue; + const from = inward / (1.5 + r() * 0.7) + r() * 3, turn = r() * Math.PI / 3, tint = (r() * FROST_TINTS.length) | 0; + const bright = 120 + r() * 100, kind = r(), arm = kind < 0.45 ? 2 + r() * 2 : kind < 0.85 ? 3.5 + r() * 2.5 : 1.2 + r() * 0.8; + mark(x, y, from, STEM, bright, tint); + for (let j = 0; j < 6; j++) { + const a = turn + j * Math.PI / 3, c = Math.cos(a), s = Math.sin(a); + for (let d = 0.5; d <= arm; d += 0.5) mark(x + c * d, y + s * d, from + d * 0.8, SIDE, bright * (1 - 0.25 * d / arm), tint); + if (kind >= 0.45 && kind < 0.85) for (const w of [-1, 1]) { // (twigs, at 60° to the arm, two-thirds out) + const bx = x + c * arm * 0.6, by = y + s * arm * 0.6, b = a + w * Math.PI / 3; + for (let d = 0.5; d <= arm * 0.4; d += 0.5) mark(bx + Math.cos(b) * d, by + Math.sin(b) * d, from + arm * 0.5 + d, BARB, bright * 0.7, tint); + } + if (kind >= 0.85) { // (a plate: its hexagon's rim, its middle fainter) + const b = a + Math.PI / 3, nx = x + Math.cos(b) * (arm + 1), ny = y + Math.sin(b) * (arm + 1); + const ex = x + c * (arm + 1), ey = y + s * (arm + 1); + for (let t = 0; t <= 1; t += 0.25) mark(ex + (nx - ex) * t, ey + (ny - ey) * t, from + 1.5, SIDE, bright, tint); + mark(x + c * 0.8, y + s * 0.8, from + 0.5, BARB, bright * 0.55, tint); + } + } + made.forms.star++; } const list = []; for (let i = 0; i < n; i++) if (crystalAt[i] < Infinity) list.push(i); - // the bloom: a dithered pixel or two about each crystal, a little after it (half of those next to it, a quarter one further) + // the bloom: a dithered pixel or two about each bolder crystal, a little after it (half of those next to it, a quarter one + // further); none about the faintest for (const i of list) { + if (crystalAlpha[i] < 120) continue; const x = i % W, y = (i / W) | 0, at = crystalAt[i] + 1.5; for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) { const X = x + dx, Y = y + dy, far = Math.abs(dx) + Math.abs(dy); @@ -1819,7 +1929,7 @@ const growing = () => extent < reachFor(e.level) - 0.25; function lookOf(i, grows) { // pixel i's look at `extent` (-1: clear) const since = extent - crystalAt[i]; - if (since >= 0) return grows && since < 1.5 ? FRESH : grows && since < 5 ? Math.min(FRESH, crystalLook[i] + 1) : crystalLook[i]; + if (since >= 0) return grows && since < 1.5 ? FRESH : crystalLook[i]; if (bloomAt[i] <= extent) return BLOOM; const depth = hazeDepth(extent), x = i % W, y = (i / W) | 0; if (hazeIn[i] >= depth) return -1; @@ -1830,6 +1940,12 @@ const paint = (i) => { const look = lookOf(i, grows), k = i * 4; if (look < 0) { d[k + 3] = 0; return; } + if (look >= BARB) { // (a crystal: its own shade and tint, whiter the brighter; just behind the fresh tips, brighter still) + const since = extent - crystalAt[i], alpha = look === FRESH ? 255 : grows && since < 5 ? Math.min(250, crystalAlpha[i] + 45) : crystalAlpha[i]; + const c = FROST_TINTS[crystalTint[i]][clamp(((alpha - 40) / 40) | 0, 0, 5)]; + d[k] = c[0]; d[k + 1] = c[1]; d[k + 2] = c[2]; d[k + 3] = alpha; + return; + } const [c, alpha] = LOOK[look]; d[k] = c[0]; d[k + 1] = c[1]; d[k + 2] = c[2]; d[k + 3] = alpha; }; @@ -1867,7 +1983,7 @@ const frozen = firstAt(crystalKeys, extent); // (the crystals there now: the first `frozen` of them) if (frozen > 20 && glints.length < 2 + Math.min(6, frozen / 3000) && random() < dt * 1.2) { // a sparkle on one of them const i = crystals[Math.floor(random() * frozen)]; - if (crystalLook[i] >= SIDE && crystalAt[i] <= extent) glints.push({x: i % W, y: (i / W) | 0, age: 0, life: between(0.6, 1.4)}); + if ((crystalLook[i] >= SIDE || crystalAlpha[i] >= 170) && crystalAt[i] <= extent) glints.push({x: i % W, y: (i / W) | 0, age: 0, life: between(0.6, 1.4)}); } }, draw(g, alpha) { @@ -1884,7 +2000,8 @@ if (!crystalAt) return null; if (quick) return {extent, target: reachFor(e.level), sparkles: glints.length}; const grows = growing(), m = Math.min(W, H), BUCKETS = 32, most = new Float32Array(BUCKETS); - let frosted = 0, crystal = 0, fresh = 0, deepest = 0, rim = 0, rimFrosted = 0; + let frosted = 0, crystal = 0, fresh = 0, deepest = 0, rim = 0, rimFrosted = 0, sum = 0, sum2 = 0; + const tints = new Set(), byLook = {[BARB]: [0, 0], [SIDE]: [0, 0], [STEM]: [0, 0]}; for (let i = 0; i < W * H; i++) { const x = i % W, y = (i / W) | 0, look = lookOf(i, grows), inward = Math.min(x, y, W - 1 - x, H - 1 - y); if (inward < 3) { rim++; if (look >= 0) rimFrosted++; } @@ -1893,6 +2010,7 @@ if (look < BARB) continue; crystal++; if (look === FRESH) fresh++; + else { const al = crystalAlpha[i]; sum += al; sum2 += al * al; tints.add(crystalTint[i]); byLook[look][0] += al; byLook[look][1]++; } deepest = Math.max(deepest, inward); // (along which edge, where: the deepest crystal in each of 32 stretches of the window's edges, between the corners' 15 %) const edge = [y, H - 1 - y, x, W - 1 - x].indexOf(inward), along = edge < 2 ? x / W : y / H; @@ -1905,7 +2023,10 @@ for (let i = 3; i < shown.length; i += 4) if (shown[i]) ink++; return {extent, target: reachFor(e.level), growing: grows, frosted: frosted / (W * H), crystals: crystal / (W * H), fresh, ink, deepest: deepest / m, rim: rimFrosted / rim, fingers: Array.from(most, (v) => v / m), sparkles: glints.length, - pixels: crystals.length}; + pixels: crystals.length, made, + shades: {mean: sum / Math.max(1, crystal - fresh), spread: Math.sqrt(Math.max(0, sum2 / Math.max(1, crystal - fresh) - (sum / Math.max(1, crystal - fresh)) ** 2)), + tints: tints.size, stem: byLook[STEM][0] / Math.max(1, byLook[STEM][1]), side: byLook[SIDE][0] / Math.max(1, byLook[SIDE][1]), + barb: byLook[BARB][0] / Math.max(1, byLook[BARB][1])}}; }, }; }); diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 426c9179..f01e4db9 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -1407,6 +1407,22 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red fingers = sorted(cold["fingers"]) assert fingers[-1] > 0.35 and fingers[0] < 0.6 * fingers[-1] and fingers[-1] - fingers[len(fingers) // 2] > 0.05, fingers assert frost["sparkles"] >= 1, frost["sparkles"] + # ... and varied, as real frost on a window: fern fronds, short plumes, needles radiating from a point and small six-armed stars, + # a few from a little way in (as if from a scratch); the fronds' lengths and their branches' spacing spread widely, the + # branches mostly near 60° to their stems (ice's hexagonal habit), each frond its own; the seeds along the edges uneven, crowded + # in some stretches with bare gaps in others; the shading uneven: ridges brighter than side branches, those than the fine + # barbs, the shades spread widely and in several tints + made, shades = cold["made"], cold["shades"] + assert all(made["forms"][k] >= 5 for k in ("fern", "plume", "needles", "star")) and made["scratches"] >= 1, made + q = lambda v, p: sorted(v)[int(p * (len(v) - 1))] + lengths = [f["length"] for f in made["fronds"]] + spacings, angles = [f["spacing"] for f in made["fronds"] if f["spacing"]], [f["angle"] for f in made["fronds"] if f["angle"]] + assert len(lengths) >= 40 and q(lengths, 0.9) > 5 * q(lengths, 0.1) and max(lengths) > 60, sorted(lengths) + assert len(spacings) >= 30 and q(spacings, 0.9) > 2.5 * q(spacings, 0.1), sorted(spacings) + assert 55 <= q(angles, 0.5) <= 65 and q(angles, 0.1) > 45 and q(angles, 0.9) < 75 and q(angles, 0.9) - q(angles, 0.1) > 6, sorted(angles) + gaps = [b[1] - a[1] for a, b in zip(made["seeds"], made["seeds"][1:]) if a[0] == b[0]] + assert len(gaps) >= 40 and q(gaps, 0.9) > 4 * q(gaps, 0.1) and max(gaps) > 4 * q(gaps, 0.5), sorted(gaps) + assert shades["stem"] > shades["side"] + 20 > shades["barb"] + 40 and shades["spread"] > 35 and shades["tints"] >= 3, shades # ... faint (the tiles read over it), pale cyan to white shown = cold["pixels"] assert shown["drawn"] > 0.3 and shown["alpha"] < 0.15 and shown["strong"] < 0.002, shown From 8f5afe311ca9f3eb0109637f28826746c8d0d957 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:17:28 +0000 Subject: [PATCH 048/146] Web dashboard: leaves that touch a flash flood stick to it and stay while it lasts. Every leaf the water's actual (wavy) surface reaches is the flood's from then on (wind.wade(), called by the flood's step once its waves have moved): its lowest row on the surface row or under it in any column it covers, as drawn (flutter and frame), the waves as they are now; one that crossed it between frames laid on it where it crossed along its path. None passes through, skims across, bounces off or is blown out again; none is blown in at or under the water (spawned above its highest crest), none leaves the window downward through it, the water rising to a leaf takes it too. A stuck leaf floats (5-15 s), sinks and rests on the bottom, piling up (a px up on one already resting there); the flood owns, steps and draws them (under its water), so they stay with the wind gone or calm, floating ones going on to sink; gone only as the flood drains away (fading with its last few px), the animations stop or it ends, so a new flood starts with a clean bottom. Past the most (40 % of the wind's share of the budget) one fades at a time: once the pile is 60 % of the most, its oldest, else the leaf floating longest, so the pile builds however fast leaves come and is slowly renewed; the wind blows in replacements at its upwind edge, its leaves and the flood's together its share as before. The leaves' frame cost unchanged. Sky.state().wind gains flyers ([id, its lowest row over the water or null, x, y]) and wet ([id, state, its bottom against the surface]); Sky.state().flood gains leaves. Tests, in the flood's existing every-effect session (wind, heavy rain, flood, the weather's time 10x): every frame, no flying leaf drawn touching or under the surface, none stuck flying again, above the surface or going back a state, each stuck one above the water the frame before (some well above: crossing between frames), none vanishing near the water; then the wind off: the leaves resting stay resting, the floating ones sink, none fading; draining: all of them there till its last 8 px, then gone; a new flood: none from before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 237 +++++++++++++++++++++------------ tests/test_web_dashboard.py | 33 ++++- tests/web_dashboard_browser.js | 69 ++++++++-- 3 files changed, 242 insertions(+), 97 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index ae96b93f..1b61c0ee 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -174,8 +174,9 @@ // age: s shown, behind: its trail there behind it, trail: [x, y] a pixel of it}]}), joined: how many have run into a flood, joins: the latest of them // (each {x, bottom: its sprite's lowest row + 1, surface: the flood's surface there then, level: the flood's level, trail: its trail's // last row + 1, or null: not running, wet: its trail there, in its middle)}, -// flood (a flash flood: its depth, its surface, its frog and its waves, as flood.probe() gives them; the wind's water: its leaves -// in it; the rain's under: drops drawn below its surface), gust (what's blown across: gust.probe()), for the tests. Sky.timeScale(k): the +// flood (a flash flood: its depth, its surface, its frog and its waves, as flood.probe() gives them; the wind's water, fading, +// floating, resting, wet: its leaves in it, as flood.leaves() gives them (the flood's too, as leaves), and flyers: the leaves +// flying, each [id, its lowest row over the water under it or null, x, y]; the rain's under: drops drawn below its surface), gust (what's blown across: gust.probe()), for the tests. Sky.timeScale(k): the // weather's time k times as fast, each frame (test-only). Sky.frost() (test-only): // the ice now, {extent, target: where it's going (on its own measure), growing, frosted, crystals: the share of the window under // any frost, under its crystals, fresh: the growth front's fresh tip pixels, deepest: the crystal furthest from its nearest edge, @@ -555,7 +556,7 @@ // roll along with it, one set for everything: the air faster in a band, slower between, harder after a gust; the rain rides them // (across(), below), the leaves a little (with or without the rain). In the rain, a drop that hits a leaf knocks it (knock()): // a push along the drop's slant, down and on, and a burst of spin; hit after hit, it tumbles and is battered down. A tiny splash on - // the leaf where it hit. + // the leaf where it hit. A flood: none blown in under its water; one its surface reaches is the flood's (wade()). // (All of it is worked out downwind along +x, from the left edge, and drawn mirrored: on screen x is W - x, the sprites mirrored // too, so everything, the gusts, turbulence and eddies, goes right to left, the leaves and wisps coming in at the right edge.) const LAYERS = [{speed: 40, alpha: 0.5, share: 0.4}, {speed: 60, alpha: 0.75, share: 0.35}, {speed: 85, alpha: 1, share: 0.25}]; @@ -579,7 +580,7 @@ })))); const WISP = ["#2E363D", "#45515B", "#5F6E7A"].map((c) => `rgb(${rgb(c)})`); let flying = [], eddies = [], wisps = [], gust = 0, nextGust = 0, travelled = 0, calm = 1, swept = 0, riding = 0; - let splashes = [], hits = 0, pushed = 0, kicked = 0; + let splashes = [], hits = 0, pushed = 0, kicked = 0, born = 0, lastT = 0, owed = 0; const KNOCK = 60; // a heavy drop's push on a near leaf (px/s, along its fall); farther leaves less (parallax) // A splash on a leaf, frame by frame: a bead where the drop struck, then two droplets thrown up off it, falling away ([dx, dy, shade]) const SPLASH = [[[0, 0, 4], [0, -1, 3]], [[-1, -1, 3], [1, -2, 4], [0, 0, 2]], [[-2, -2, 2], [2, -2, 3]], [[-2, -1, 1], [3, -1, 2]]] @@ -640,9 +641,10 @@ const set = leafSprites()[f.layer], i = Math.floor(random() * set.length); f.frames = set[i]; f.flat = set[i | 1]; // (the same leaf turning end over end: its frames squeezed flat, lying on water) - f.wet = null; + f.id = ++born; f.x = anywhere ? between(-10, W) : between(-30, -8); - f.y = between(H * 0.05, H * 0.95); + f.y = between(H * 0.05, clamp(flood.clear() - 7, H * 0.05, H * 0.95)); // (never in a flood: above its highest crest) + f.gap = Infinity; // (its lowest row's height over the water as last drawn, px: none yet) f.vx = LAYERS[f.layer].speed * calm; f.vy = 0; f.weight = between(0.12, 0.3); // (s: how long it takes to catch the air's speed) f.turn = between(0, 10); @@ -652,37 +654,20 @@ f.whirl = 0; f.batter = 0; // (rain's knocks: spin on top of its own, frames/s; sink on top of its own, px/s; both dying away) f.hw = -1; // (where it is on screen, for the rain: not yet) }; - // A flood: a leaf touching its surface lies on it ("float"), bobbing with the waves, drifting a little; after FLOATS s it sinks - // slowly ("sink"), rocking side to side, to the bottom, and rests there ("rest"); the oldest fading out (then blown in again) - // once more than WET_MOST of the wind's leaves are in the water, all of them as it drains. The rain passes them by. - const FLOATS = [5, 15], WET_MOST = 0.4, FADE = 1.2; - function soak(f) { // (into the water: a little ripple and splash where it lands) - const frame = f.flat[2]; - f.wet = {state: "float", left: between(...FLOATS), drift: between(-1, 2.5), age: 0, fade: 0, sink: between(2.5, 4.5), - rock: between(1.2, 2), phase: between(0, 7), bed: H - 1 - Math.ceil(frame.height / 2) - Math.floor(between(0, 3))}; - f.hw = -1; f.vx = 0; f.vy = 0; - flood.hit(W - f.x, 0.8, true); - } - const floats = (f) => flood.surface(W - f.x) - Math.floor(f.flat[2].height / 2) + 1; // (its middle, lying on the surface) - function soaking(f, dt, t) { - const w = f.wet, frame = f.flat[2]; - w.age += dt; - if (w.fade > 0) { - if ((w.fade -= dt) <= 0) spawn(f, false); - return; - } - if (w.state === "float") { // (on the surface, bobbing; from under it, bobbing up to it) - const y = floats(f); - f.y = y > f.y ? y : Math.max(y, f.y - 18 * dt); - w.up = f.y === y; // (up at the surface: drawn on it as it is when drawn) - f.x = clamp(f.x + w.drift * dt, 4, W - 4); - if ((w.left -= dt) <= 0) w.state = "sink"; - } else if (w.state === "sink") { // (down slowly, swinging side to side) - f.y += w.sink * dt; - f.x = clamp(f.x + Math.cos(t * w.rock + w.phase) * 4 * dt, 4, W - 4); - if (f.y >= w.bed) { f.y = w.bed; w.state = "rest"; } - } - } + // Where a leaf is drawn at time t: its frame, its left column and top row on screen (art px) + const drawn = (f, t) => { + const frame = f.frames[Math.floor(f.turn) % f.frames.length]; + return [frame, Math.round(W - f.x - frame.width / 2), Math.round(f.y + Math.sin(t * 2.3 + f.phase) * 1.2 - frame.height / 2)]; // (a flutter) + }; + // How far its lowest row is above the flood's surface under it (the highest the water reaches across its columns on screen), px: + // 0 or less, touching it (Infinity: no water under it) + const gapOf = (f, t) => { + const [frame, x0, y0] = drawn(f, t), bottom = y0 + frame.height - 1; + if (bottom < flood.clear()) return Infinity; // (well above its highest crest: no need to look) + let top = Infinity; + for (let x = Math.max(0, x0), end = Math.min(W - 1, x0 + frame.width - 1); x <= end; x++) top = Math.min(top, Math.round(flood.surface(x))); + return top - bottom; + }; const wisp = (w, anywhere) => { w.x = anywhere ? between(0, W) : between(-40, -5); w.y = between(H * 0.1, H * 0.9); @@ -705,14 +690,12 @@ against: flying.filter((f) => f.vx < 0).length, hits, push: pushed / Math.max(hits, 1), kick: kicked / Math.max(hits, 1), whirl: flying.reduce((most, f) => Math.max(most, f.whirl), 0), - // (in a flood: its leaves floating, sinking, resting on the bottom, fading out; each floating one's bottom row - // against the surface there (px, + below it); the resting ones' bottom rows against the window's bottom) - water: Object.fromEntries(["float", "sink", "rest"].map((k) => [k, flying.filter((f) => f.wet && !f.wet.fade && f.wet.state === k).length])), - fading: flying.filter((f) => f.wet && f.wet.fade > 0).length, - floating: flying.filter((f) => f.wet && !f.wet.fade && f.wet.state === "float" && f.wet.up) - .map((f) => Math.round(floats(f) - f.flat[2].height / 2) + f.flat[2].height - 1 - Math.round(flood.surface(W - f.x))), - resting: flying.filter((f) => f.wet && f.wet.state === "rest").map((f) => Math.round(f.y - f.flat[2].height / 2) + f.flat[2].height - H), - leaves: flying.length}), + // (in a flood: the leaves in it, the flood's own (flood.leaves()): see there; leaves: those flying and those) + ...flood.leaves(), + leaves: flying.length + flood.count(), + // (each flying leaf as drawn last: [id, its lowest row's height over the flood's surface under it (null: no + // water under it), x, y on screen]) + flyers: flying.map((f) => { const gap = gapOf(f, lastT); return [f.id, gap < Infinity ? gap : null, W - f.x, f.y]; })}), // A drop of rain layer `layer` going from (x0, y0) to (x1, y1) this frame (its head, on screen, art px), at vx across and vy down // (px/s): if it hits a leaf as far off as itself, the leaf knocked (`hard` 0-1: how heavy the rain) and true (the drop ends) knock(layer, x0, y0, x1, y1, vx, vy, hard) { @@ -736,10 +719,36 @@ return false; }, resize() { flying = []; eddies = []; wisps = []; splashes = []; }, - forget() { flying = []; eddies = []; wisps = []; splashes = []; gust = 0; }, // (its leaves sunk in a flood too) + forget() { flying = []; eddies = []; wisps = []; splashes = []; gust = 0; owed = 0; }, // (not those in a flood: the flood's now) + // Every flying leaf the flood's surface has reached (its lowest row on it or under it, in any column it covers, the waves as + // they are now: the flood's step calls this once its waves have moved) handed to it, stuck there: none passes through it, + // skims it or is blown out again. One that crossed it between frames, where it crossed (along its path), lying on it. + // (Those it took, and those it has done with since, blown in again at the window's upwind edge: as many leaves as ever.) + wade(t) { + lastT = t; + if (!flying.length) return; + if (flood.lift() <= 0) { for (const f of flying) f.gap = Infinity; return; } + let kept = 0; + for (const f of flying) { + const gap = gapOf(f, t); + if (gap > 0) { f.gap = gap; flying[kept++] = f; continue; } + const k = f.gap < Infinity && f.px !== undefined ? clamp(f.gap / (f.gap - gap), 0, 1) : 1; + flood.take(f, W - (f.px + (f.x - f.px) * k), LAYERS[f.layer].alpha); + f.hw = -1; + } + flying.length = kept; + while (flying.length + flood.count() < owed) { + const k = random(), f = {layer: k < LAYERS[0].share ? 0 : k < LAYERS[0].share + LAYERS[1].share ? 1 : 2}; + spawn(f, false); + f.gap = gapOf(f, t); + flying.push(f); + } + }, step(dt, t, share) { calm = clamp(W / 360, CALM, 1); - const n = Math.round(this.need() * share); + lastT = t; + owed = Math.round(this.need() * share); + const n = Math.max(0, owed - flood.count()); // (those in a flood its share too) while (flying.length < n) { const k = flying.length / Math.max(n, 1); const f = {layer: k < LAYERS[0].share ? 0 : k < LAYERS[0].share + LAYERS[1].share ? 1 : 2}; @@ -767,19 +776,9 @@ d.y += d.vy * dt; if (d.age >= d.life || d.x > W + 2 * d.r) eddy(d, false); } - // (a flood: leaves in it, the oldest faded out past the most (those resting on the bottom first), one at a time to make room - // for more once it's full; all of them as it drains. Full, a leaf touching it skims off it, the wind lifting it again.) - const flooded = flood.lift() > 3, wet = flying.filter((f) => f.wet && !f.wet.fade), most = Math.max(3, Math.round(n * WET_MOST)); - let room = most - wet.length; - if (!flooded) for (const f of wet) f.wet.fade = FADE; - else { - wet.sort((a, b) => (b.wet.state === "rest") - (a.wet.state === "rest") || b.wet.age - a.wet.age); - let k = 0; - while (wet.length - k > most) wet[k++].wet.fade = FADE; - if (room <= 0 && wet[k] && wet[k].wet.state === "rest" && wet[k].wet.age > 20 && !flying.some((f) => f.wet && f.wet.fade)) wet[k].wet.fade = FADE; - } + const flooded = flood.lift() > 0; for (const f of flying) { - if (f.wet) { soaking(f, dt, t); continue; } + f.px = f.x; // (where it was: if it crosses a flood's surface this frame, where it did) const [vx, vy, curl] = airAt(f.x, f.y, LAYERS[f.layer].speed, t), ease = 1 - Math.exp(-dt / f.weight); f.vx += (vx - f.vx) * ease; f.vy += (vy + f.sink + f.batter - f.vy) * ease; @@ -787,14 +786,10 @@ f.y += f.vy * dt; f.turn += (f.spin + Math.min(Math.abs(curl) * 2.5, 14) + f.whirl) * dt; if (f.whirl) { f.whirl *= Math.exp(-1.6 * dt); f.batter *= Math.exp(-0.6 * dt); if (f.whirl < 0.05) f.whirl = f.batter = 0; } - if (f.x > W + 14 || f.x < -60 || f.y > H + 14 || f.y < -14) { spawn(f, false); continue; } + // (out of the window: blown in again; but below it in a flood only through the water, so the flood takes it: wade()) + if (f.x > W + 14 || f.x < -60 || f.y < -14 || (f.y > H + 14 && !flooded)) { spawn(f, false); continue; } const frame = f.frames[Math.floor(f.turn) % f.frames.length]; // (its size as drawn: what a drop can hit, a little inside it) f.hw = frame.width * 0.4; f.hh = frame.height * 0.4; - const surface = flooded ? flood.surface(W - f.x) : Infinity; - if (f.y + f.hh >= surface) { - if (room-- > 0) soak(f); - else { f.y = surface - f.hh - 1; f.vy = -between(10, 25); } - } } for (const s of splashes) s.age += dt; if (splashes.length) splashes = splashes.filter((s) => s.age < 0.16 && s.f.hw >= 0); @@ -822,21 +817,13 @@ } } let layer = -1; - for (const f of flying) { - if (f.wet) { // (in a flood: lying flat on it, rocking as it sinks, at rest; the water drawn over those under it) - const w = f.wet, frame = w.state === "sink" && Math.sin(t * w.rock + w.phase) > 0.55 ? f.flat[1] : f.flat[2]; - const y = w.state === "float" && w.up ? floats(f) : f.y; - g.globalAlpha = alpha * LAYERS[f.layer].alpha * (w.fade > 0 ? w.fade / FADE : 1); - g.drawImage(frame, Math.round(W - f.x - frame.width / 2), Math.round(y - frame.height / 2)); - layer = -1; - continue; - } + for (const f of flying) { // (those in a flood the flood draws: its own) if (f.layer !== layer) { layer = f.layer; g.globalAlpha = alpha * LAYERS[layer].alpha; } - const frame = f.frames[Math.floor(f.turn) % f.frames.length]; - const y = f.y + Math.sin(t * 2.3 + f.phase) * 1.2; // (a flutter) - g.drawImage(frame, Math.round(W - f.x - frame.width / 2), Math.round(y - frame.height / 2)); + const [frame, x, y] = drawn(f, t); + g.drawImage(frame, x, y); } for (const s of splashes) { // (riding on the leaf it hit, as it flutters) + if (s.f.hw < 0) continue; // (the leaf gone: into a flood) const f = s.f, y = f.y + Math.sin(t * 2.3 + f.phase) * 1.2; g.globalAlpha = alpha * LAYERS[f.layer].alpha * 0.9; g.drawImage(SPLASH[Math.min(3, Math.floor(s.age / 0.04))], Math.round(W - f.x + s.dx) - 3, Math.round(y + s.dy) - 3); @@ -1480,8 +1467,10 @@ // tank's far side. The surface: a height a pixel column under a damped wave equation (WAVE px/s), its waves travelling, reflecting // off the window's sides, piling up and slapping higher there; stirred all across by every raindrop landing in it (hit(): a ripple // spreading both ways, and a tiny splash), a drip running into it, a restless chop while it pours, now and then a bigger slosh from - // one side; calming slowly as the rain eases. Rain, the drips and the wind's wisps end at it, none ever drawn below; leaves land on - // it, float, then sink (the wind's); the smog and the heat's shimmer rise above it (lift()). Rarely (about every FROG_EVERY s on + // one side; calming slowly as the rain eases. Rain, the drips and the wind's wisps end at it, none ever drawn below; every one of + // the wind's leaves its surface reaches (its waves as they are, wherever a leaf meets them) sticks there, floats, then sinks and + // rests on the bottom, the flood's own from then on: there while it lasts, the wind gone or not, gone as it drains away; the smog + // and the heat's shimmer rise above it (lift()). Rarely (about every FROG_EVERY s on // average, never in its first FROG_FIRST s) a bemused frog on a lily pad floats across, right to left with the wind, bobbing; the // test link's flood (level 2) sends its first one FROG_FIRST s after the water starts rising. Drawn after the drips and the // leaves (the sunken ones show through it, tinted and dimmed), before the ice. @@ -1517,6 +1506,15 @@ let h = null, v = null, a = null, far = null, slap = null, depth = 0, full = 0, rows = 0, layer = null, img = null, px = null, body = null; let chop = 0, nextSlosh = 0, since = 0, test = false, nextFrog = Infinity, frog = null, frogs = 0, splashes = []; let hits = 0, sloshes = 0, drops = 0; + // The leaves in it (the wind's, once they touch it: wind.wade()): its own from then on, the wind on or not. Each floats on the + // surface ("float"), bobbing with the waves, drifting a little (more in the wind); after FLOATS s it sinks slowly ("sink"), + // rocking side to side, to the bottom, and rests there ("rest"), on those already resting there too. They pile up there; only + // past the most (WET_MOST of the wind's share of the budget) one fades out (FADE s): once the pile on the bottom is PILE of the + // most, the oldest resting there, else the one floating longest (one sinking only when none floats), so it builds up + // however fast they come and is slowly renewed. All of them gone as it drains away (fading with its last few px). The rain + // passes them by. Drawn under its water, which tints and dims them. + const FLOATS = [5, 15], WET_MOST = 0.4, PILE = 0.6, FADE = 1.2, LEAF_ALPHA = 0.8 / 0.6; // (LEAF_ALPHA: as bright as the wind's own) + let leaves = []; const calm = () => Math.min(1, depth / 10); // (shallow: its waves smaller) const surfaceAt = (x) => { // the surface's height at x on screen (art px, a float: its row there, rounded, as drawn) if (depth <= 0) return Infinity; @@ -1524,6 +1522,51 @@ return H - depth - h[i] * slap[i] * calm(); }; const expo = (mean) => -mean * Math.log(1 - random()); + const floats = (l) => surfaceAt(l.sx) - Math.floor(l.flat[2].height / 2) + 1; // (a leaf's middle, lying on the surface) + const bedFor = (l) => { // (where it comes to rest: on the bottom, a px up on one already resting there) + const on = leaves.some((o) => o.state === "rest" && Math.abs(o.sx - l.sx) < 6) ? 1 : 0; + return H - 1 - Math.ceil(l.flat[2].height / 2) - Math.min(2, Math.floor(between(0, 2)) + on); + }; + const leafProbe = () => ({water: Object.fromEntries(["float", "sink", "rest"].map((k) => [k, leaves.filter((l) => !l.fade && l.state === k).length])), + fading: leaves.filter((l) => l.fade > 0).length, + floating: leaves.filter((l) => !l.fade && l.state === "float") + .map((l) => Math.round(floats(l) - l.flat[2].height / 2) + l.flat[2].height - 1 - Math.round(surfaceAt(l.sx))), + resting: leaves.filter((l) => l.state === "rest").map((l) => Math.round(l.y - l.flat[2].height / 2) + l.flat[2].height - H), + wet: leaves.map((l) => [l.id, l.state, Math.round((l.state === "float" ? floats(l) : l.y) - l.flat[2].height / 2) + + l.flat[2].height - 1 - Math.round(surfaceAt(l.sx))]), + all: leaves.length}); + function crowded(share) { // (too many: one faded at a time, see above) + const most = Math.max(3, Math.round(wind.need() * share * WET_MOST)); + for (let over = leaves.filter((l) => !l.fade).length - most; over > 0; over--) { + const pile = leaves.filter((l) => !l.fade && l.state === "rest").length >= PILE * most; + let oldest = null; + for (const l of leaves) { + if (l.fade || (pile ? l.state !== "rest" : l.state === "rest")) continue; + if (!oldest || (l.state === "float") > (oldest.state === "float") || ((l.state === "float") === (oldest.state === "float") && l.age > oldest.age)) oldest = l; + } + if (!oldest) break; + oldest.fade = FADE; + } + } + function soaking(dt, t) { + const drift = wind.amount > 0 ? 1 : 0.3; + let kept = 0; + for (const l of leaves) { + l.age += dt; + if (l.fade > 0 && (l.fade -= dt) <= 0) continue; + leaves[kept++] = l; + if (l.state === "float") { // (on the surface, bobbing) + l.sx = clamp(l.sx - l.drift * drift * dt, 4, W - 4); + l.y = floats(l); + if ((l.left -= dt) <= 0) { l.state = "sink"; l.bed = bedFor(l); } + } else if (l.state === "sink") { // (down slowly, swinging side to side; never above the surface, as it drains) + l.sx = clamp(l.sx - Math.cos(t * l.rock + l.phase) * 4 * dt, 4, W - 4); + l.y = Math.max(floats(l), l.y + l.sink * dt); + if (l.y >= l.bed) { l.y = l.bed; l.state = "rest"; } + } + } + leaves.length = kept; + } // The waves dt s on: a damped wave equation, the window's sides reflecting (in a few steps a frame, each short enough to be // stable; at most 12, so with the tests' time run on fast they lag), its level kept, and never past MOST either way function waves(h, v, a, dt) { @@ -1550,6 +1593,22 @@ strength: () => 0.6, surface: surfaceAt, waterline: () => (depth > 0 ? H - depth : H), // (its level, its waves aside: the window's bottom with no water) + // (the row above its highest crest, however the waves go: nothing above it touches the water; reduced motion, where it will be) + clear: () => (STILL && e.level > 0 && full ? H - full - DIP : depth > 0 ? H - depth - DIP : H), + // A leaf of the wind's touching it (wind.wade()), at x on screen: its own now, lying on the surface there, a ripple and splash + take(f, x, alpha) { + const l = {id: f.id, sx: clamp(x, 4, W - 4), y: 0, flat: f.flat, alpha, state: "float", left: between(...FLOATS), + drift: between(-1, 2.5), age: 0, fade: 0, sink: between(2.5, 4.5), rock: between(1.2, 2), phase: between(0, 7), bed: H}; + l.y = floats(l); + leaves.push(l); + this.hit(l.sx, 0.8, true); + }, + count: () => leaves.length, + need: () => (wind.alive() ? 0 : leaves.length), // (with the wind on, its share: see wind.step) + // (for the tests: its leaves floating, sinking, resting on the bottom (not fading), fading out; each floating one's bottom row + // against the surface there (px, + below it); the resting ones' bottom rows against the window's bottom; each one [id, state, + // its bottom row against the surface at its middle]; all of them) + leaves: () => leafProbe(), lift: () => depth, // (how far up from the window's bottom its surface's lowest trough can be: what sits on it is drawn down to there and kept // above() it, so its edge is the wavy surface, never a straight line at its level) @@ -1586,7 +1645,7 @@ }, fade(dt) { e.amount = depth > 0 || e.level > 0 ? 1 : 0; }, alive: () => e.level > 0 || depth > 0, - forget() { depth = 0; if (h) { h.fill(0); v.fill(0); far.fill(0); } frog = null; splashes = []; chop = 0; }, + forget() { depth = 0; if (h) { h.fill(0); v.fill(0); far.fill(0); } frog = null; splashes = []; chop = 0; leaves = []; }, resize() { full = Math.max(8, Math.round(H * SPAN)); rows = full + TOP; @@ -1606,8 +1665,9 @@ } frog = null; splashes = []; + leaves = []; }, - step(dt, t) { + step(dt, t, share) { if (e.level > 0 && depth <= 0) { // (rising from empty: its frogs' clock from now) since = 0; test = e.level >= 2; @@ -1619,7 +1679,7 @@ depth = STILL ? target : depth + clamp(target - depth, -dt * full / DRAIN, dt * full / RISE); const pouring = e.level > 0 ? 1 : 0; chop += (pouring - chop) * (1 - Math.exp(-dt / (pouring > chop ? 3 : CALMS))); - if (depth <= 0) { h.fill(0); v.fill(0); far.fill(0); frog = null; splashes = []; chop = 0; return; } + if (depth <= 0) { h.fill(0); v.fill(0); far.fill(0); frog = null; splashes = []; chop = 0; leaves = []; return; } if (STILL && !drops) { // (reduced motion: a still surface some seconds in, gently uneven) drops = 1; for (let x = 0; x < W; x++) h[x] = 1.6 * Math.sin(x * 0.09) + 0.9 * Math.sin(x * 0.23 + 1) + (x < 12 || x > W - 13 ? 1.5 : 0); @@ -1639,6 +1699,9 @@ waves(h, v, a, dt); const lag = 1 - Math.exp(-dt / 0.5); // (the far side: the near one's waves, half a second behind) for (let i = 0; i < W; i++) far[i] += (h[i] - far[i]) * lag; + soaking(dt, t); + wind.wade(t); // (the wind's leaves its surface reaches, as it is now: its own) + crowded(share); for (const s of splashes) s.age += dt; splashes = splashes.filter((s) => s.age < 0.2); // the frog: rarely, never at once; drifting across with the wind, bobbing on the waves @@ -1651,6 +1714,14 @@ }, draw(g, alpha, t) { if (depth <= 0) return; + if (leaves.length) { // (under its water: lying flat on it, rocking as they sink, at rest on the bottom) + const o = Math.min(1, alpha * LEAF_ALPHA) * (e.level > 0 ? 1 : Math.min(1, depth / 4)); + for (const l of leaves) { + const frame = l.state === "sink" && Math.sin(t * l.rock + l.phase) > 0.55 ? l.flat[1] : l.flat[2]; + g.globalAlpha = o * l.alpha * (l.fade > 0 ? l.fade / FADE : 1); + g.drawImage(frame, Math.round(l.sx - frame.width / 2), Math.round((l.state === "float" ? floats(l) : l.y) - frame.height / 2)); + } + } const top = H - rows, k = calm(); px.fill(0); for (let x = 0; x < W; x++) { @@ -1695,7 +1766,7 @@ for (let t = 0; t <= s + 1e-9; t += every) { out.push(Array.from(h)); waves(h, v, a, every); } return out; }, - frog: frog && {x: frog.x, y: frog.y || null}, + frog: frog && {x: frog.x, y: frog.y || null}, leaves: leafProbe(), surface: depth > 0 ? Array.from({length: W}, (_, x) => surfaceAt(x)) : []}), }; }); diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index f01e4db9..c589e59e 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -1500,11 +1500,11 @@ async def test_a_flash_flood_fills_the_window_a_quarter_up_its_surface_choppy_wh assert 5 <= draining["took"] <= 7 and draining["surface"] == 0 and got["drained"]["effects"] == ["rain"], (draining, got["drained"]) assert draining["half"]["chop"] > 0.7 * draining["chop0"], draining # the test link (every other effect on): rain light, heavy, then heavy with a flash flood (rain3; the test's own flood level, 2), - # then off: draining + # then off (the wind turned off before it): draining linked = got["linked"] assert [(s["url"].split(",")[-1], s["label"], s["rain"], s["flood"]) for s in linked["steps"]] == [ ("rain", "rain: light", 0.35, 0), ("rain2", "rain: heavy", 1, 0), ("rain3", "rain: flood", 1, 2)], linked["steps"] - assert linked["off"]["url"] == "?fx=smog3,uv,humidity2,wind,heat,ice" and linked["off"]["flood"] == linked["off"]["rain"] == 0, linked["off"] + assert linked["off"]["url"] == "?fx=smog3,uv,humidity2,heat,ice" and linked["off"]["flood"] == linked["off"]["rain"] == 0, linked["off"] # ... its first frog some 30 s after the water started rising, not before; one, crossing right to left, on the waves (bobbing) assert 29 <= linked["before"] < 30 <= linked["first"] <= 31 and linked["frogs"] == 1, linked track = linked["track"] @@ -1512,12 +1512,21 @@ async def test_a_flash_flood_fills_the_window_a_quarter_up_its_surface_choppy_wh assert all(b[0] <= a[0] for a, b in zip(track, track[1:])), track # (two looks a frame drawn, at times) assert all(abs(y - surface) <= 1 for _, y, surface in track) and max(t[1] for t in track) - min(t[1] for t in track) >= 2, track # ... the leaves: landing on it and lying there (on the surface line, or a px into it), then sinking and resting on the bottom; no - # more than 40 % of them in the water, within the budget; fading out as it drains + # more than 40 % of them in the water, within the budget leaves = linked["leaves"] assert leaves["float"] >= 2 and leaves["sink"] >= 1 and leaves["rest"] >= 1, leaves assert linked["gaps"] and set(linked["gaps"]) <= {0, 1}, sorted(set(linked["gaps"])) assert linked["resting"] and all(-4 <= r <= 0 for r in linked["resting"]), sorted(set(linked["resting"])) - assert 0 < linked["most"] <= 0.42 and linked["over"] <= 3, linked + assert 0 < linked["most"] <= 0.42 and linked["over"] <= 3, (linked["most"], linked["over"], linked["wet"]) + # ... every leaf its wavy surface reaches stuck on it (many, in the wind, the heavy rain knocking them about): none flying drawn + # touching it or under it, none flying again, above it or going back a state (floating, sinking, resting, in that order); those + # seen flying the frame before it took them, all of them above it then (some well above: crossing it between frames); none + # vanishing near it but into it + stuck = linked["stuck"] + assert stuck["wet"] >= 8 and stuck["seen"] >= 0.6 * stuck["wet"] and stuck["near"] >= 5 and stuck["hits"] > 0, stuck + assert stuck["touching"] == 0 and stuck["back"] == 0 and stuck["above"] == 0 and stuck["backwards"] == 0, stuck + assert stuck["lost"] == [] and all(g is None or g >= 1 for g in stuck["lastGaps"]), stuck + assert sum(g is None or g > 3 for g in stuck["lastGaps"]) >= 3, stuck # (crossing it between frames: from well above it) # ... the drips: joining it as they reach it, none below it; each running on down to the waves' own height where it is (its # sprite's bottom at the surface there, ripples and all, or under a crest risen over it), never joining it short of that, its # trail all the way down with it, wet to the water @@ -1529,9 +1538,21 @@ async def test_a_flash_flood_fills_the_window_a_quarter_up_its_surface_choppy_wh # under the level as drawn on as those just above (the smog, the heat, the rain's spray, the fog, all down to the wavy surface) cut = linked["cut"] assert cut["n"] >= 100 and cut["at"] >= 0.8 * cut["above"], cut + # ... the wind off (and gone): the leaves in the water its own, staying (those resting still resting, none fading), the floating + # ones sinking or resting by 16 s on, none flying + off = linked["windOff"] + before, after = {i: st for i, st, _ in off["before"]}, {i: st for i, st, _ in off["after"]} + assert "wind" not in off["effects"] and off["flyers"] == 0 and off["fading"] == 0, off + assert "rest" in before.values() and "float" in before.values() and set(before) <= set(after), off + assert all(after[i] == "rest" for i, st in before.items() if st == "rest"), off + assert all(after[i] in ("sink", "rest") for i, st in before.items() if st == "float"), off + # ... off: draining in about 6 s, its leaves all there till its last few px, then gone with it; a new flood: none from before drained = linked["drained"] - assert 5 <= drained["took"] <= 7 and drained["wet"] == 0 and drained["frog"] is None, drained - assert drained["effects"] == ["smog", "heat", "uv", "wind", "humidity", "ice"], drained + assert 5 <= drained["took"] <= 7 and drained["wet"] == drained["all"] == 0 and drained["frog"] is None, drained + assert drained["low"] == drained["n0"] == len(after), drained + assert drained["effects"] == ["smog", "heat", "uv", "humidity", "ice"], drained + again = linked["again"] + assert again["url"].endswith(",rain3") and again["leaves"]["all"] == 0 and again["leaves"]["wet"] == [], again # every effect on with the flood (full): as cheap as ever (about 3 ms), within the budget costly = linked["costly"] assert costly["effects"] == ["smog", "heat", "uv", "rain", "wind", "humidity", "flood", "ice"] and costly["cost"] < 8, costly diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 3b922718..00be6ef9 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1566,9 +1566,39 @@ const WEATHER = { // every frame, until the first frog has crossed (or 100 s of the page's time): the frog, the leaves in the water, the drips Object.assign(seen, await page.evaluate(() => new Promise((resolve) => { const r = { before: null, first: null, track: [], leaves: { float: 0, sink: 0, rest: 0 }, gaps: [], resting: [], wet: 0, most: 0, - over: 0, under: 0, joined: 0, joins: [], frogs: 0, fullAt: null }; + over: 0, under: 0, joined: 0, joins: [], frogs: 0, fullAt: null, + // (the leaves and the water, every frame: flying ones drawn touching it or under it; those stuck in it, and of them + // the ones seen flying just before (and how near the water they were then); any flying again, any above the surface + // or going back a state; flying ones vanishing other than into it, last seen near the water and away from the + // window's edges; flying ones seen within 3 px of it; the rain's hits on leaves meanwhile) + stuck: { touching: 0, wet: 0, seen: 0, lastGaps: [], back: 0, above: 0, backwards: 0, lost: [], near: 0, hits0: null, hits: 0 } }; + const flyers = new Map(), states = new Map(), ORDER = ["float", "sink", "rest"]; const step = () => { - const s = Sky.state(), f = s.flood, w = s.wind; + const s = Sky.state(), f = s.flood, w = s.wind, k = r.stuck; + if (f.depth >= f.full) { + if (k.hits0 === null) k.hits0 = w.hits; + k.hits = w.hits - k.hits0; + const now = new Map(w.flyers.map(([id, gap, x, y]) => [id, [gap, x, y]])); + for (const [id, [gap]] of now) { + if (gap !== null && gap <= 0) k.touching++; + if (gap !== null && gap <= 3) k.near++; + if (states.has(id)) k.back++; + } + for (const [id, state, gap] of w.wet) { + if (gap < 0) k.above++; + if (!states.has(id)) { + k.wet++; + if (flyers.has(id)) { k.seen++; k.lastGaps.push(flyers.get(id)[0]); } + } else if (ORDER.indexOf(state) < ORDER.indexOf(states.get(id))) k.backwards++; + states.set(id, state); + } + for (const [id, [gap, x, y]] of flyers) { + if (now.has(id) || states.has(id)) continue; + if (gap !== null && gap <= 8 && x > 16 && x < f.width - 16) k.lost.push([id, gap, x, y]); + } + flyers.clear(); + for (const [id, v] of now) flyers.set(id, v); + } if (f.depth >= f.full && r.fullAt === null) r.fullAt = f.since; if (!f.frog && !r.first) r.before = f.since; if (f.frog) { @@ -1590,7 +1620,10 @@ const WEATHER = { r.joined = s.humidity.joined; r.joins = s.humidity.joins; r.frogs = f.frogs; - if ((r.first && !f.frog) || f.since > 100) { r.gaps = r.gaps.slice(-400); r.resting = r.resting.slice(-400); return resolve(r); } + if ((r.first && !f.frog) || f.since > 100) { + r.gaps = r.gaps.slice(-400); r.resting = r.resting.slice(-400); r.stuck.lastGaps = r.stuck.lastGaps.slice(-200); + return resolve(r); + } requestAnimationFrame(step); }; requestAnimationFrame(step); @@ -1611,23 +1644,43 @@ const WEATHER = { }; requestAnimationFrame(step); })); - // off: draining, the leaves in it fading out with it (the weather's time four times as fast) + // the wind off, some leaves resting on the bottom and some floating: those in the water staying, the floating ones sinking + // (once the wind is gone and none is fading: then the weather's time 20 times as fast for 16 s of it) + await page.waitForFunction(() => { const w = Sky.state().wind.water; return w.rest >= 1 && w.float >= 2; }); + await page.locator("#fxtest button[data-fx='wind']").click(); + await page.waitForFunction(() => !Sky.state().effects.includes("wind") && Sky.state().particles.wind === 0 && !Sky.state().flood.leaves.fading); + seen.windOff = { before: await page.evaluate(() => Sky.state().flood.leaves.wet) }; + await page.evaluate(() => Sky.timeScale(20)); + const gone = await page.evaluate(() => Sky.state().clock); + await page.waitForFunction((c) => Sky.state().clock >= c + 16, gone); + Object.assign(seen.windOff, await page.evaluate(() => ({ after: Sky.state().flood.leaves.wet, flyers: Sky.state().wind.flyers.length, + effects: Sky.state().effects, fading: Sky.state().flood.leaves.fading }))); + // off: draining, the leaves in it staying till it's nearly gone, then gone with it (the weather's time four times as fast) await page.evaluate(() => Sky.timeScale(4)); + const n0 = await page.evaluate(() => Sky.state().flood.leaves.all); await click(); seen.off = await rain(); - seen.drained = await page.evaluate(() => new Promise((resolve) => { + seen.drained = await page.evaluate((n0) => new Promise((resolve) => { const c0 = Sky.state().clock, depth0 = Sky.state().flood.depth; + let low = null; // (how many leaves in it as it got down to its last 8 px) const step = () => { const s = Sky.state(); - if (s.flood.depth > 0) return requestAnimationFrame(step); + if (s.flood.depth > 0) { + if (s.flood.depth <= 8 && low === null) low = s.flood.leaves.all; + return requestAnimationFrame(step); + } requestAnimationFrame(() => requestAnimationFrame(() => { const w = Sky.state().wind; resolve({ took: s.clock - c0, depth0, effects: Sky.state().effects, wet: w.water.float + w.water.sink + w.water.rest, - fading: w.fading, frog: Sky.state().flood.frog }); + fading: w.fading, all: Sky.state().flood.leaves.all, frog: Sky.state().flood.frog, n0, low }); })); }; requestAnimationFrame(step); - })); + }), n0); + // a new flood (rain3 again): none of the leaves from before in it + for (let i = 0; i < 3; i++) await click(); + await page.waitForFunction(() => Sky.state().flood.depth > 0); + seen.again = await page.evaluate(() => ({ url: location.search, leaves: Sky.state().flood.leaves })); seen.errors = errors; await context.close(); return seen; From d206aa2e79b153fcd6846fd527fe4d7c619e5a66 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:37:29 +0000 Subject: [PATCH 049/146] Web dashboard: the AQI's effect is a particulate haze, even over the whole window, drifting with the wind. The layered banks low across the window (smog) are gone: fine dust hangs evenly, so the haze is an even dithered veil over the whole window (its cover the band's: faint at Moderate, heavy at Hazardous; its colours by band as before), with only a very gentle large-scale swell in it (its pixels' alpha, about 6 % either way; each row's mean taken out, so no height is denser than another: no band near the ground, no cloud shapes), and a sparse grain of tiny dust motes (three deep, far ones dimmer and slower; 1 px, the band's lightest paled; in the particle budget). Both drift right to left, the wind's way: about 3 px/s in calm air, faster with the wind on and quickening in its gusts (wind.breeze()). The veil is one texture wrapping sideways, slid in steps of its 4 px dither so its dots stay put and only its swell moves; nothing drawn below a flood's surface; the brightness cap as before; its frame cost under 1 ms alone. Named haze throughout (the effect, Sky.set's and Sky.state's keys, the test link "haze", ?fx=haze1-haze5); ?fx=smog1-smog5 still work. Sky.state() gains haze {level, slide, speed, motes}. Tests, on the existing Hazardous page beside "all": each band in turn, its blocks' spread under 0.15 of their mean, its bottom and top fifths within 5 % of the mean, each band denser than the last by over 20 %; every mote moving left, about 3 px/s, its veil sliding too, and over twice as fast with the wind on; ?fx=smog4 opens as haze 4. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- README.md | 2 +- docs/configuration.md | 2 +- lib/web_dashboard.html | 151 ++++++++++++++++++++++----------- tests/test_web_dashboard.py | 56 +++++++----- tests/web_dashboard_browser.js | 81 +++++++++++++----- 5 files changed, 198 insertions(+), 94 deletions(-) diff --git a/README.md b/README.md index 9647fa15..6b3c073a 100644 --- a/README.md +++ b/README.md @@ -295,7 +295,7 @@ A click or tap on a gauge (or Enter or Space on a tile reached with Tab) zooms i back) to fill the window, a single tile shown too. Zoomed, page through the tiles like a photo gallery, each still live: ← and →, Space (next) and Backspace (previous), a swipe, a drag on the gauge, or a two-finger sideways swipe on a trackpad; it stops at the first and the last (with one tile, paging just nudges it and back). A click or tap (not on the text) or Esc goes back. -Behind the gauges, the weather is drawn as faint pixel art while the readings call for it: rain while it rains, smog from the US +Behind the gauges, the weather is drawn as faint pixel art while the readings call for it: rain while it rains, a particulate haze from the US AQI's Moderate band up, UV beams at a UV index of 11, the glass fogging over at 90 % humidity (heavier to 100 %), beads condensing in the fog and running down it, wiping clear tracks, leaves blowing past above 15 km/h of wind, a heat haze from 35 °C and ice below 0 °C. "stop animation" at the bottom left stops them in that browser (kept with its arrangement), and ends any effect a temporary test link turned on; with reduced motion asked for, one still frame. To draw none of it for anyone, set `MCP_DASHBOARD_ANIMATIONS=off`. diff --git a/docs/configuration.md b/docs/configuration.md index b94788be..4b0ac426 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -71,7 +71,7 @@ At least one of Ecowitt (cloud or Home Assistant) or AirGradient (cloud, local o | `MCP_CHART_BASE_URL` | none | Where people's browsers reach the chart links' pictures (`?charts=link`, below): the URL a reverse proxy serves `/charts` at, e.g. `https://api.example.org/ecobot-charts` with nginx's `location /ecobot-charts/ { proxy_pass http://127.0.0.1:8765/charts/; }`. Unset: the address the MCP request came to (`X-Forwarded-Proto` and `X-Forwarded-Host` when a proxy sends them) with `/charts` | | `MCP_CHART_LINK_HOURS` | `24` | How long a chart link's picture answers (1 to 720 hours). They are kept in memory (at most 500, 64 MB in all, the oldest dropped first): a restart forgets them, and an old link answers 404 | | `MCP_DASHBOARD` | `on` | The gauges' live web page at `/dashboard` beside `/mcp` (`http://deb1:8765/dashboard`): read-only, so it needs no token and answers any `Host` (open it by the machine's name or address from the LAN); `/mcp` keeps both checks. `off`: `/dashboard`, `/dashboard/`, `/dashboard/icon.png`, `/dashboard/data` and `/dashboard/events` answer 404 | -| `MCP_DASHBOARD_ANIMATIONS` | `on` | The page's weather drawn behind its gauges (pixel-art rain, smog, UV, humidity, wind, heat and ice while the readings call for them, with a "stop animation" link for each viewer). `off`: none of it for every viewer (nothing drawn, no link); the rest of the page is the same | +| `MCP_DASHBOARD_ANIMATIONS` | `on` | The page's weather drawn behind its gauges (pixel-art rain, haze, UV, humidity, wind, heat and ice while the readings call for them, with a "stop animation" link for each viewer). `off`: none of it for every viewer (nothing drawn, no link); the rest of the page is the same | Every request to `/mcp` needs a token (`AUTH_TOKENS`, below). Chart images are not a setting of ecobot-mcp but of each client: a client whose MCP URL ends `?charts=png` (`http://127.0.0.1:8765/mcp?charts=png`) gets each chart as a PNG beside the figures, drawn in `DARKMODE`'s theme; a client whose URL ends `?charts=link` gets each chart as a link to its PNG (`/charts/.png`, served with no token and any `Host`, so anyone with the link can open it until it expires; `MCP_CHART_BASE_URL`, `MCP_CHART_LINK_HOURS`) and the model is asked to put it in its reply as a markdown image, for a chat app that shows those but not a tool's image (LibreChat); a call's request `_meta` `chart_image` (`"png"`, `"link"` or `"none"`) overrides its connection's ([ecobot-mcp.md](ecobot-mcp.md) 3.7). They need Pillow (`requirements-charts.txt`, in both Docker images): installed from `requirements-mcp.txt` alone ecobot-mcp answers with the charts' JSON and a note, and warns once. diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 1b61c0ee..e6df4193 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -12,7 +12,7 @@ The tiles can be rearranged in the browser: dragged to reorder (a long press on a touch screen), hidden with their × or the remove zone, all put back with "reset preferences"; kept in localStorage ("ecobot.dashboard.v1"), nothing sent to the server. A click or tap on a gauge zooms its tile (title and gauge, no table) to fill the window, a gallery paged through by keys, swipes and drags; Esc goes back. - Behind everything, the weather as pixel art on one canvas (Sky): rain, smog, uv, humidity, wind, heat and ice, each while the + Behind everything, the weather as pixel art on one canvas (Sky): rain, haze, uv, humidity, wind, heat and ice, each while the readings call for it, its tile framed in red; "stop animation" at the bottom left stops them. With MCP_DASHBOARD_ANIMATIONS off the server sends data-animations="off" on (lib/web_dashboard.py): none of it, for every viewer (no canvas drawn, no loop, no link, no test links), the rest of the page as ever. --> @@ -136,7 +136,7 @@ // for every effect, each frame cleared once and drawn back to front (ORDER). The effects share a particle budget and a cap on their // strength together, so several at once are no busier or brighter than one strong one. Nothing runs while no effect is on or fading // out; the tab hidden, it waits; with reduced motion, one still, faint frame and no loop. -// Sky.set(want, animate): want {rain: 0-1 (its strength), smog: 0-5 (the AQI's band above Good), humidity: 0-1 (90 % to +// Sky.set(want, animate): want {rain: 0-1 (its strength), haze: 0-5 (the AQI's band above Good), humidity: 0-1 (90 % to // 100 %), uv, wind, heat: 0 or 1, ice: how far below 0 °C it is (0: none), flood: 0 or 1 (2: the test link's, its first frog // sooner)}; animate false (the page's "stop animation", or // MCP_DASHBOARD_ANIMATIONS off): nothing drawn (and anything blown across gone). @@ -197,7 +197,7 @@ const BUDGET = 1 / 400; // the particles of every effect together: this many per art pixel² (480 x 300: 360) const CAP = 1.5; // ... and their strengths together at most this (one strong effect: about 0.8) const STILL_HINT = 0.5; // reduced motion: the still frame this faint - const ORDER = ["gust", "smog", "heat", "uv", "rain", "wind", "humidity", "flood", "ice"]; // back to front + const ORDER = ["gust", "haze", "heat", "uv", "rain", "wind", "humidity", "flood", "ice"]; // back to front let W = 0, H = 0, P = 3; // the art's size (art px) and one art pixel's (CSS px) // ---------- tools: seeded randomness, colours, dithering, noise, little canvases ---------- @@ -401,54 +401,101 @@ }; }); - // ---------- smog: banks of haze drifting low across the window, three deep; thicker, higher and redder with each AQI band ---------- - const SMOG = [ // each band's four shades, dark to light: Moderate (ochre), USG (amber), Unhealthy (rust), Very Unhealthy, Hazardous (maroon) + // ---------- haze: the particulates the air sensor measures, an even veil over the whole window; denser and redder with each AQI band ---------- + // Fine dust hangs evenly in the air, not in banks: an even dithered tint (its density the band's, faint at Moderate, heavy at + // Hazardous) with only a very gentle, large-scale swell in it, and a sparse grain of tiny motes (dust, three deep: the far ones + // dimmer and slower). Both drift right to left, the wind's way: slowly in calm air, faster with the wind on, quickening in its + // gusts (wind.breeze()). In a flood, none below its surface. (The veil is one texture, wrapping sideways: dithered evenly, its + // swell in its pixels' alpha, slid in steps of its dither's 4 px, so its dots stay put and only its swell moves; the motes, a few + // dozen 1 px rectangles.) + const HAZE = [ // each band's four shades, dark to light: Moderate (ochre), USG (amber), Unhealthy (rust), Very Unhealthy, Hazardous (maroon) ["#2A2616", "#433C21", "#5F552D", "#7C6E38"], ["#2D2216", "#4A3420", "#6A4A29", "#8A6132"], ["#2B1B17", "#462820", "#62352B", "#7C4335"], ["#28181F", "#3E2330", "#563040", "#6C3C4E"], ["#22101A", "#371722", "#4E1F2C", "#652938"]].map((r) => r.map(rgb)); - const smog = effect((e) => { - const LAYERS = [{cell: 120, flat: 0.32, drift: 1.2, depth: 0.55, seed: 11}, {cell: 80, flat: 0.36, drift: 2.6, depth: 0.8, seed: 23}, - {cell: 52, flat: 0.42, drift: 5, depth: 1, seed: 37}]; - let built = 0, textures = []; + const haze = effect((e) => { + const DENSITY = [0.36, 0.52, 0.68, 0.84, 0.97]; // the veil's cover, each band (of its pixels) + const SWELL = 0.6; // its gentle large-scale variation: its alpha's, for each 1 of the noise's own (about 6 % either way) + const CALM = 3, BREEZE = 7; // its drift leftward, px/s (the middle motes'): in calm air; more for the wind (its breeze 1-3) + const DEPTHS = [{pace: 0.55, alpha: 0.4, share: 0.45}, {pace: 1, alpha: 0.6, share: 0.35}, {pace: 1.6, alpha: 0.85, share: 0.2}]; + let built = 0, veil = null, span = 0, slide = 0, speed = 0, motes = [], born = 0, dust = []; function build(level) { built = level; - const shades = SMOG[level - 1], reach = [0.45, 0.58, 0.72, 0.86, 1][level - 1], thick = [0.62, 0.72, 0.82, 0.92, 1][level - 1]; - textures = LAYERS.map((l) => { - const cells = Math.max(2, Math.round(W / l.cell)), across = cells / W, down = 1 / (l.cell * l.flat); - const top = H * (1 - reach * (1.1 - 0.25 * l.depth)); // (the far banks reach higher) - const density = (x, y) => { // 0-1: the banks, denser lower down - const low = clamp((y - top) / (H - top), 0, 1); // (0 at the smog's top, 1 at the window's bottom) - const n = 0.65 * noise(x * across, y * down, cells, l.seed) + 0.35 * noise(x * across * 2, y * down * 2, cells * 2, l.seed + 1); - return clamp((n - 0.58 + low * 0.55) * 2.2, 0, 1) * Math.pow(low, 0.3) * thick * l.depth; - }; - return painted(W, H, (x, y) => { - if (y < top) return null; - const v = density(x, y); - let s = shadeOf(v * 0.8, x, y, 4); - if (s >= 0 && v > 0.12 && density(x, y - 3) < v - 0.1) s = Math.min(3, s + 1); // (a bank's top, catching the light) - return s < 0 ? null : shades[s]; - }); + const shades = HAZE[level - 1], cover = DENSITY[level - 1]; + span = Math.ceil(W / 4) * 4; // (a whole number of dither tiles across: it wraps seamlessly) + const cells = Math.max(2, Math.round(span / 150)), across = cells / span; + // (its swell: soft noise, each row's mean taken out, so every height is as dense as any other, on the whole: no band anywhere) + const swell = new Float32Array(span * H); + for (let y = 0; y < H; y++) { + let mean = 0; + for (let x = 0; x < span; x++) { + const n = 0.65 * noise(x * across, y / 150, cells, 41) + 0.35 * noise(x * across * 2, y / 75, cells * 2, 43); + swell[y * span + x] = n; + mean += n / span; + } + for (let x = 0; x < span; x++) swell[y * span + x] -= mean; + } + veil = painted(span, H, (x, y) => { + const b = BAYER[(y & 3) * 4 + (x & 3)]; + if (b >= cover) return null; + // (its tone: mostly the band's third shade, a sprinkle of the lightest, more of it the denser; the second where it thins) + const tone = BAYER[((y + 2) & 3) * 4 + ((x + 1) & 3)]; + return [...shades[tone < 0.1 + 0.2 * cover ? 3 : b > cover - 0.13 ? 1 : 2], Math.round(255 * clamp(0.84 + SWELL * swell[y * span + x], 0.5, 1))]; }); + // (the motes: the band's lightest, paler still, as dust catching the light) + dust = [0.1, 0.22, 0.36].map((k) => `rgb(${shades[3].map((c) => Math.round(c + (225 - c) * k)).join(",")})`); } + const place = (m, anywhere) => { + m.id = ++born; + m.x = anywhere ? between(0, W) : W + between(0, 6); + m.y = between(0, H); + m.phase = between(0, 7); + m.bob = between(0.6, 2); // (px/s: a slow wander up and down) + }; return { strength: () => [0.4, 0.48, 0.56, 0.64, 0.72][Math.max(1, built || e.level) - 1], - resize() { built = 0; }, - step() { if (e.level > 0 && (e.level !== built || !textures.length)) build(e.level); }, - draw(g, alpha, t) { + need: () => (W * H / 1800) * (0.6 + 0.2 * Math.max(1, e.level || built)), // (sparse: about 65 at Moderate on a laptop, 130 at Hazardous) + count: () => motes.length, + forget() { motes = []; slide = 0; }, + resize() { built = 0; motes = []; }, + // (for the tests: its band as drawn, how far its veil has slid leftward (px), its drift now (px/s, leftward), its motes [id, x, y]) + probe: () => ({level: built, slide, speed, motes: motes.map((m) => [m.id, m.x, m.y])}), + step(dt, t, share) { + if (e.level > 0 && (e.level !== built || !veil)) build(e.level); + speed = CALM + BREEZE * wind.breeze(); + slide += speed * dt; + const n = Math.round(this.need() * share); + while (motes.length < n) { // (the depths in their shares, far first: drawn back to front) + const k = motes.length / Math.max(n, 1), m = {depth: k < DEPTHS[0].share ? 0 : k < DEPTHS[0].share + DEPTHS[1].share ? 1 : 2}; + place(m, true); + motes.push(m); + } + if (motes.length > n) motes.length = n; + for (const m of motes) { + m.x -= speed * DEPTHS[m.depth].pace * dt; + m.y += Math.sin(t * 0.45 + m.phase) * m.bob * dt; + if (m.x < -1 || m.y < -2 || m.y > H + 2) place(m, false); + } + }, + draw(g, alpha) { if (!built) return; - flood.above(g, () => LAYERS.forEach((l, i) => { - const x = Math.floor((t * l.drift + i * W / 3) % W), y = Math.round(Math.sin(t * 0.07 + i * 2) * 1.5 - flood.sunk()); - g.globalAlpha = alpha * (0.6 + 0.4 * l.depth); - g.drawImage(textures[i], x - W, y); - g.drawImage(textures[i], x, y); - })); + flood.above(g, () => { + const x = -(Math.floor(slide / 4) * 4 % span); + g.globalAlpha = alpha; + g.drawImage(veil, x, 0); + if (x + span < W) g.drawImage(veil, x + span, 0); + let depth = -1; + for (const m of motes) { + if (m.depth !== depth) { depth = m.depth; g.fillStyle = dust[depth]; g.globalAlpha = alpha * DEPTHS[depth].alpha; } + g.fillRect(Math.round(m.x), Math.round(m.y), 1, 1); + } + }); }, }; }); // ---------- heat: a shimmering amber glow rising from the bottom, its ripples riding up and wavering sideways ---------- // (In a flood, from its surface: from as low as its troughs go, flood.sunk(), and kept above() it, so its edge is the wavy surface; - // the smog's banks sit on it too, and neither is drawn below it) + // the haze is drawn above it too, and neither below it) const HEAT = ["#3A1C0A", "#62300E", "#955015", "#C97B24", "#EFB05A"].map(rgb); const heat = effect((e) => { const SPAN = 0.34, PERIOD = 13, LINES = 7, RISE = 9, SPARE = 4; // its height (of the window's); its ripples' spacing (px), how many @@ -682,6 +729,8 @@ // wind); and its steady part. (Its bands not slowed on narrow art: there they are what's left of the wind in the rain.) across: (x, k) => e.amount * k * (calm * STEADY * (1 + gust) + BANDS * gusting() * bandAt(W - x - swept)), steady: (k) => e.amount * k * calm * STEADY * (1 + gust), + // How hard it blows now, for the haze's drift: 0 without the wind, 1 at its steady pace, more in a gust + breeze: () => e.amount * calm * (1 + gust), ride: (v) => { riding = v; }, // (this frame, the gust bands carried along at v px/s: the rain's) // (on screen: the leaves' mean speed across, px/s, negative leftward; how many go rightward, against the wind, in a loop) // (and the rain's hits on them so far, and their mean push, px/s, and the mean change it made in a hit leaf's own velocity, px/s; @@ -1469,8 +1518,8 @@ // spreading both ways, and a tiny splash), a drip running into it, a restless chop while it pours, now and then a bigger slosh from // one side; calming slowly as the rain eases. Rain, the drips and the wind's wisps end at it, none ever drawn below; every one of // the wind's leaves its surface reaches (its waves as they are, wherever a leaf meets them) sticks there, floats, then sinks and - // rests on the bottom, the flood's own from then on: there while it lasts, the wind gone or not, gone as it drains away; the smog - // and the heat's shimmer rise above it (lift()). Rarely (about every FROG_EVERY s on + // rests on the bottom, the flood's own from then on: there while it lasts, the wind gone or not, gone as it drains away; the haze + // and the heat's shimmer are drawn above it (above(): the haze down to its surface, the heat from as low as its troughs go). Rarely (about every FROG_EVERY s on // average, never in its first FROG_FIRST s) a bemused frog on a lily pad floats across, right to left with the wind, bobbing; the // test link's flood (level 2) sends its first one FROG_FIRST s after the water starts rising. Drawn after the drips and the // leaves (the sunken ones show through it, tinted and dimmed), before the ice. @@ -2375,7 +2424,7 @@ }; }); - const effects = {gust, smog, heat, uv, rain, wind, humidity, flood, ice}; + const effects = {gust, haze, heat, uv, rain, wind, humidity, flood, ice}; // ---------- the loop ---------- let animate = true, frame = 0, last = 0, clock = 0, frames = 0, cost = 0, scale = 1; @@ -2485,7 +2534,7 @@ state: () => ({effects: ORDER.filter((k) => effects[k].level > 0), running: !!frame, frames, cost, clock, size: [W, H, P], particles: Object.fromEntries(ORDER.map((k) => [k, effects[k].count()])), budget: W * H * BUDGET, levels: Object.fromEntries(ORDER.map((k) => [k, effects[k].level])), iceReach: effects.ice.reach(), - wind: effects.wind.probe(), rain: effects.rain.probe(), + wind: effects.wind.probe(), rain: effects.rain.probe(), haze: effects.haze.probe(), humidity: effects.humidity.probe(), flood: effects.flood.probe(), gust: effects.gust.probe()})}; })(); @@ -3484,11 +3533,11 @@ // ---------- the weather behind the tiles: what the readings call for, the tiles framed in red, "stop animation" (bottom left) ---------- // (And with each new live gust reading over 99 km/h, something big blown across once: gusting(), below.) // Each effect while its reading is past its mark, on its tile (Sky draws them): rain while it rains (the station's rain rate above 0, - // stronger to 8 mm/h), smog from the US AQI's Moderate band up (1-5, a band each), uv at a UV index of 11, humidity at 90 % + // stronger to 8 mm/h), haze from the US AQI's Moderate band up (1-5, a band each), uv at a UV index of 11, humidity at 90 % // humidity (heavier to 100 %: 0.1 at 91 %, 1 at 100 %; 0.05 at 90 % itself), wind above 15 km/h (the reading now, not the gust), heat at 35 °C, ice below 0 °C (how far below), a flash flood // over 30 mm/h (the rain's too). A tile // with no reading now calls for nothing. - const CALLED_BY = {rain: "Rain", smog: "US AQI", uv: "UV index", humidity: "Humidity", wind: "Wind", heat: "Temperature", + const CALLED_BY = {rain: "Rain", haze: "US AQI", uv: "UV index", humidity: "Humidity", wind: "Wind", heat: "Temperature", ice: "Temperature", flood: "Rain"}; const BANDS = [50, 100, 150, 200, 300]; // the US AQI's bands' upper edges, Good to Very Unhealthy (the tile's own bounds if it has them) let real = {}, simulated = {}, conditions = {}; @@ -3502,7 +3551,7 @@ const aqiTile = (data.tiles || []).find((t) => idOf(t) === "US AQI"), bands = aqiTile && aqiTile.bounds && aqiTile.bounds.length > 2 ? aqiTile.bounds.slice(1, -1) : BANDS; return {rain: rate > 0 ? 0.3 + 0.7 * Math.min(1, rate / 8) : 0, - smog: aqi === null ? 0 : Math.min(5, bands.filter((b) => aqi > b).length), + haze: aqi === null ? 0 : Math.min(5, bands.filter((b) => aqi > b).length), uv: uvi !== null && uvi >= 11 ? 1 : 0, humidity: humidity !== null && humidity >= 90 ? Math.max(0.05, Math.min(1, (humidity - 90) / 10)) : 0, wind: wind !== null && wind > 15 ? 1 : 0, heat: temperature !== null && temperature >= 35 ? 1 : 0, @@ -3584,8 +3633,8 @@ @@ -138,7 +144,8 @@ // pixelated). Every sprite and texture is drawn once to a small offscreen canvas and blitted; one loop (at most 30 frames a second) // for every effect, each frame cleared once and drawn back to front (ORDER). The effects share a particle budget and a cap on their // strength together, so several at once are no busier or brighter than one strong one. Nothing runs while no effect is on or fading -// out; the tab hidden, it waits; with reduced motion, one still, faint frame and no loop. +// out; the tab hidden, it waits; with reduced motion, or low motion (MCP_DASHBOARD_ANIMATIONS=low), one still, faint frame and no loop +// (low motion: drawn again only as the conditions change). // Sky.set(want, animate): want {rain: 0-1 (its strength), haze: 0-5 (the AQI's band above Good), humidity: 0-1 (90 % to // 100 %), uv, wind, heat: 0 or 1, ice: how far below 0 °C it is (0: none), flood: 0 or 1 (2: the test link's, its first frog // sooner)}; animate false (the page's "stop animation", or @@ -180,7 +187,7 @@ // last row + 1, or null: not running, wet: its trail there, in its middle)}, // flood (a flash flood: its depth, its surface, its frog and its waves, as flood.probe() gives them; the wind's water, took, rested, // floating, resting, wet, all, shows(): its leaves in it, as flood.leaves() gives them (the flood's too, as leaves), and flyers: the leaves -// flying, each [id, its lowest row over the water under it or null, x, y]; the rain's under: drops drawn below its surface), gust (what's blown across: gust.probe()), for the tests. Sky.timeScale(k): the +// flying, each [id, its lowest row over the water under it or null, x, y]; the rain's under: drops drawn below its surface), gust (what's blown across: gust.probe()), stills (how many still frames have been drawn: reduced or low motion), for the tests. Sky.timeScale(k): the // weather's time k times as fast, each frame (test-only). Sky.advance(n) (test-only): n frames now (window.__skyTest: see the // loop); Sky.clock() (test-only): {frames, clock, running}, as Sky.state() has them, cheaply. Sky.frost() (test-only): // the ice now, {extent, target: where it's going (on its own measure), growing, frosted, crystals: the share of the window under @@ -195,7 +202,10 @@ // target, sparkles}, cheap. const Sky = (() => { const holder = document.getElementById("sky"), canvas = holder.querySelector("canvas"), ctx = canvas.getContext("2d"); - const STILL = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches; + // Low motion (MCP_DASHBOARD_ANIMATIONS=low: e-ink), as reduced motion: one still, faint frame and no loop; drawn again only as the + // conditions change (or the window's size) + const LOW = document.documentElement.dataset.animations === "low"; + const STILL = LOW || (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches); const FRAME_MS = 1000 / 30; // the frame rate's cap: art moving a pixel at a time needs no more const FADE_S = 1.5; // an effect fades in, and out, over this long const ART_PX = 480; // the art's width (or height, if taller) about this many pixels: P = 3 on a laptop, 4 on 1920 @@ -2968,14 +2978,21 @@ return made; } + let stillKey = null, stills = 0; // (the still frame's conditions and size; how many still frames were drawn) function start() { if (!animate || !alive()) { cancelAnimationFrame(frame); frame = 0; + if (LOW && stillKey === "") return; // (low motion: cleared already, not again) + stillKey = ""; ctx.clearRect(0, 0, W, H); return; } - if (STILL) { // one still, faint frame: the particles where they'd be a few seconds in + if (STILL) { // one still, faint frame: the particles where they'd be a few seconds in (low motion: only for new conditions) + const key = JSON.stringify([W, H, P, ORDER.map((k) => effects[k].level > 0 ? Math.max(1, Math.round(effects[k].level * 4)) : 0)]); // (in quarters) + if (LOW && key === stillKey) return; + stillKey = key; + stills++; clock = 4; tick(0); draw(STILL_HINT); @@ -3024,7 +3041,7 @@ levels: Object.fromEntries(ORDER.map((k) => [k, effects[k].level])), iceReach: effects.ice.reach(), wind: effects.wind.probe(), rain: effects.rain.probe(), haze: effects.haze.probe(), humidity: effects.humidity.probe(), flood: effects.flood.probe(), - gust: effects.gust.probe()})}; + gust: effects.gust.probe(), stills})}; })(); @@ -4204,7 +4259,7 @@ // (And with each new live gust reading over 99 km/h, something big blown across once: gusting(), below.) // Each effect while its reading is past its mark, on its tile (Sky draws them): rain while it rains (the station's rain rate above 0, // stronger to 8 mm/h), haze from the US AQI's Moderate band up (1-5, a band each), uv at a UV index of 11, humidity at 90 % - // humidity (heavier to 100 %: 0.1 at 91 %, 1 at 100 %; 0.05 at 90 % itself), wind above 15 km/h (the reading now, not the gust), heat at 35 °C, ice below 0 °C (how far below), a flash flood + // humidity (heavier to 100 %: 0.1 at 91 %, 1 at 100 %; 0.05 at 90 % itself), wind above 15 km/h (the reading now, not the gust), heat at 35 °C (stronger to 43 °C: 0.3 to 1), ice below 0 °C (how far below), a flash flood // over 30 mm/h (the rain's too). A tile // with no reading now calls for nothing. const CALLED_BY = {rain: "Rain", haze: "US AQI", uv: "UV index", humidity: "Humidity", wind: "Wind", heat: "Temperature", @@ -4224,7 +4279,7 @@ haze: aqi === null ? 0 : Math.min(5, bands.filter((b) => aqi > b).length), uv: uvi !== null && uvi >= 11 ? 1 : 0, humidity: humidity !== null && humidity >= 90 ? Math.max(0.05, Math.min(1, (humidity - 90) / 10)) : 0, - wind: wind !== null && wind > 15 ? 1 : 0, heat: temperature !== null && temperature >= 35 ? 1 : 0, + wind: wind !== null && wind > 15 ? 1 : 0, heat: temperature !== null && temperature >= 35 ? 0.3 + 0.7 * Math.min(1, (temperature - 35) / 8) : 0, ice: temperature !== null && temperature < 0 ? -temperature : 0, flood: rate > 30 ? 1 : 0}; } const calling = () => Object.values(conditions).some((v) => v > 0); // (any effect called for: "stop animation" shows) diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 2be1c338..4259d189 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -1187,6 +1187,7 @@ async def test_the_weather_behind_the_tiles_comes_with_its_reading_at_its_mark_a assert got["rainStrength"][0] < 0.4 and got["rainStrength"][1:] == [1, 1] # light at 0.5 mm/h, heavy from 8 assert got["humidityStrength"] == pytest.approx([0.1, 0.5, 1]) # heavier from 90 % to 100 % assert got["iceDepth"] == [0.5, 5] # further in the colder + assert got["heatStrength"] == pytest.approx([0.3, 0.65, 1, 1]) # stronger from 35 °C to 43 °C @needs_browser @@ -1817,6 +1818,33 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert flood["depth"] == flood["full"] > 0 and flood["frog"] is None and not flood["running"] and flood["frames"] == 0, flood # ... and a gust (the page's, the test link's, asked for by name): nothing blown across, no loop assert still["gust"] == {"fling": None, "sent": 0, "running": False, "frames": 0}, still["gust"] + # ... and the heat's: its faint warm haze only, nothing bent (no shimmer: it would need motion) + heat = still["heat"] + assert heat["refracted"] == heat["shifts"] == 0 and heat["drawn"] > 0 and heat["band"] > 0 and not heat["running"], heat + # the heat (?fx=heat): a heat haze, not drawn lines (squiggles read as smell lines): a faint amber veil low down, and the canvas's + # own bottom band bent sideways through it in thin rows, by ripples rising and dying away upward + for name, hot in (("alone", got["heat"]), ("over", got["heatOver"])): + assert hot["errors"] == [] and hot["refracted"] > 0 and hot["band"] >= 0.25 * hot["height"], (name, hot) + assert hot["top"] + hot["band"] == hot["height"], (name, hot) # (from the bottom: no flood) + rows = [(r, *row) for f in hot["frames"] for r, row in enumerate(f["rows"]) if r < hot["band"] - 3] # (not the glints' rows) + # each row drawn exactly as the band was before it was bent, shifted by its own shift (none differing but those shifted) + assert all(match == shift for _, shift, _, match in rows if match is not None), (name, rows) + assert all(differs for _, shift, differs, match in rows if shift and match is not None), (name, rows) + assert all(not differs for _, shift, differs, _ in rows if not shift), (name, rows) + bent = [r for r, shift, _, match in rows if shift and match is not None] + assert len(bent) >= 0.2 * len(rows), (name, len(bent), len(rows)) + # ... strongest at the bottom, dying away upward (its top eighth all but still), and never still: changing frame to frame + band, frames = hot["band"], hot["frames"] + mean = lambda lo, hi: sum(abs(v) for f in frames for v in f["shifts"][int(lo * band):int(hi * band)]) / (len(frames) * (int(hi * band) - int(lo * band))) + assert mean(0.75, 1) > 0.8 and mean(0.75, 1) > 3 * mean(0, 0.25) and mean(0, 0.125) < 0.1, (name, mean(0, 0.25), mean(0.75, 1)) + assert all(max(map(abs, f["shifts"])) <= round(hot["most"]) + 1 for f in frames), name + assert sum(a != b for f, g in zip(frames, frames[1:]) for a, b in zip(f["shifts"], g["shifts"])) > 0.3 * band * (len(frames) - 1), name + # ... no long thin strokes in it (a pixel tall, 5 px or more long, brighter than above and below: a drawn squiggle) + assert hot["strokes"] <= 3, (name, hot["strokes"]) + # ... alone: its veil over all of its bottom rows, faint, amber (red over green over blue: no green or brown smoke) + alone = got["heat"] + r, g, b = alone["colour"] + assert alone["cover"] > 0.9 and 0.08 < alone["alpha"] < 0.35 and r > g * 1.15 and g > b * 1.4 and r > 180, alone def clean_glass(marks): diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 50258597..ddf891cc 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1348,6 +1348,42 @@ const rainSeen = (page, ms) => page.evaluate((ms) => new Promise((resolve) => { const begun = () => Sky.clock().frames >= 50 ? look() : __next(begun); begun(); }), ms); +// The heat's haze on a driven page (its effect on, and nothing else but what the query asks for), 60 frames in, then 8 frames 5 +// apart: each its band's rows as Sky's heat probe sees them (seen(): [shift, differs from the band as drawn before it was bent, the +// shift that matches it]) and its shifts; then the canvas: in the band (all but its bottom 4 rows: the mirage's glints), the long thin +// strokes (runs of 5 px or more a pixel tall, each brighter than the pixels above and below it by half again: a drawn line), the share +// of its bottom 10 rows drawn, the drawn pixels' mean colour and alpha (0-1) there +const heatSeen = (page) => page.evaluate(() => { + Sky.advance(60); + const frames = []; + for (let i = 0; i < 8; i++) { + Sky.advance(5); + const h = Sky.state().heat; + frames.push({ rows: h.seen(), shifts: h.shifts }); + } + const h = Sky.state().heat, c = document.querySelector("#sky canvas"), W = c.width; + const d = c.getContext("2d").getImageData(0, h.top, W, h.band).data; + const light = (x, y) => { const i = (y * W + x) * 4; return (0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2]) * d[i + 3] / 255; }; + let strokes = 0; + for (let y = 1; y < h.band - 4; y++) { + let run = 0; + for (let x = 0; x <= W; x++) { + const on = x < W && light(x, y) > 4 && light(x, y) > 1.5 * Math.max(light(x, y - 1), light(x, y + 1)); + if (on) run++; + else { if (run >= 5) strokes++; run = 0; } + } + } + let drawn = 0, n = 0, rgb = [0, 0, 0], alpha = 0; + for (let y = h.band - 10; y < h.band; y++) for (let x = 0; x < W; x++) { + const i = (y * W + x) * 4; + n++; + if (!d[i + 3]) continue; + drawn++; alpha += d[i + 3] / 255; + for (let k = 0; k < 3; k++) rgb[k] += d[i + k]; + } + return { band: h.band, top: h.top, most: h.most, refracted: h.refracted, frames, strokes, cover: drawn / n, + colour: rgb.map((v) => Math.round(v / Math.max(drawn, 1))), alpha: alpha / Math.max(drawn, 1), height: c.height }; +}); // uv's beams over 40 s of the page's time (on a page whose clock runs on fast: `pace`, below; each frame drawn 0.1 s on, Sky's // longest step): where each beam's halo was drawn (with uv alone, the glow, then each beam's halo and core), its least and greatest x // (art px), how many times it turned back (from going one way to the other), and how faint and bright it was @@ -1890,6 +1926,8 @@ const WEATHER = { for (const rate of [0.5, 8, 20]) { await reads({ rain_rate: rate }); out.rainStrength.push((await weatherSeen(page)).levels.rain); } out.humidityStrength = []; for (const rh of [91, 95, 100]) { await reads({ Humidity: rh }); out.humidityStrength.push((await weatherSeen(page)).levels.humidity); } + out.heatStrength = []; + for (const t of [35, 39, 43, 48]) { await reads({ Temperature: t }); out.heatStrength.push((await weatherSeen(page)).levels.heat); } out.iceDepth = []; for (const t of [-0.5, -5]) { await reads({ Temperature: t }); out.iceDepth.push((await weatherSeen(page)).levels.ice); } out.errors = errors; @@ -2415,6 +2453,14 @@ const WEATHER = { await uv.context.close(); return [seen, frost]; })(); + // the heat's haze, alone and over the haze's clouds and heavy rain in the wind (small: cheap) + const hot = Promise.all(["heat", "heat,haze3,rain2,wind"].map(async (name) => { + const p = await weatherPage(browser, url, { query: `?fx=${name}`, driven: true, context: { viewport: { width: 640, height: 480 } } }); + const seen = await heatSeen(p.page); + seen.errors = p.errors; + await p.context.close(); + return seen; + })); // humidity's beads condensing on the glass and running down it over 3.6 minutes of the page's time (its weather's time 6 times as // fast), alone and with the wind, beside the rest (small: cheap) (heavy: 100 %); and light (91 %), watched for 2 minutes const beading = Promise.all(["humidity2", "humidity2,wind", "humidity"].map(async (name) => { @@ -2624,6 +2670,12 @@ const WEATHER = { const f = Sky.state().flood; return { depth: f.depth, full: f.full, frog: f.frog, running: Sky.state().running, frames: Sky.state().frames }; }); + out.still.heat = await still.page.evaluate(() => { // (the heat: its still haze only, nothing bent) + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { heat: 1 } })); + const h = Sky.state().heat; + return { refracted: h.refracted, shifts: h.shifts.filter((v) => v).length, top: h.top, band: h.band, drawn: Sky.state().drawn.heat, + running: Sky.state().running }; + }); out.still.gust = await still.page.evaluate(() => { // (a gust: nothing sent, by the page or the test link) document.dispatchEvent(new Event("ecobot-gust")); document.querySelector("#fxtest button[data-gust]").click(); @@ -2635,6 +2687,7 @@ const WEATHER = { [out.uv, out.frost] = await swaying; [out.humidity.alone, out.humidity.windy, out.humidityLight] = await beading; out.rainBeads = await sticking; + [out.heat, out.heatOver] = await hot; [out.rain.alone, out.rain.windy, out.rain.phone] = await raining; [out.bare, out.barePhone] = await bare; out.errors = []; From 399522cf57e97c3bcf73fa8d56d6b06785dc7e6b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:50:22 +0000 Subject: [PATCH 088/146] Web dashboard: beads on dry glass at 0.3 of fog speed (was 0.25); a heavy-rain bead settles a moment after its splash before it runs Tests to follow (some bead statistics shift with every change: being made independent of each other's randomness). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 3 ++- tests/test_web_dashboard.py | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 482cf4c6..3134f7cb 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -1262,7 +1262,7 @@ const SIZES = [0.6, 1, 1.4, 1.9, 2.4, 2.9, 3.4, 3.9, 4.5]; // a bead's radius (its half-width), growing (and past the last: // ... drawn as wide as it is, however big, see sprite()) const DRY = 0, TRAIL = 1, FOGGY = 2, GLASSES = ["dry", "trail", "fog"]; // the glass under a bead - const PACE = [0.25, 1.6, 1]; // how fast a bead runs on each [dry, trail, fog]: dry slowest, fog quicker, a trail fastest (water on water) ... + const PACE = [0.3, 1.6, 1]; // how fast a bead runs on each [dry, trail, fog]: dry slowest, fog quicker, a trail fastest (water on water) ... const SPEED = 13; // ... times this, px/s, for a bead of r 2.8; from RUN_R up, rising gradually with its size, ever // ... faster (r 0.87: about 0.04 px/s on fog, r 1: 0.08, r 1.4: 0.4, r 2: 2.4, r 2.8: 13, r 4: 38) const GATHER = 0.1; // water a bead gathers for each px it runs through fog, for each px of its width (fog at 1) ... @@ -1620,6 +1620,7 @@ const b = {id: ++made, kind: "rain", x, y, r, merged: 0, life: between(...LIFE)}; shows(b); b.shown = APPEAR; // (there at once) + b.pause = between(0.45, 0.8); // (settling a moment after its splash before it runs: its droplets thrown clear first) all.push(b); const cy = y + heightOf(r) / 2, n = 10 + Math.floor(random() * 4); const dots = Array.from({length: n}, (_, j) => ({a: (j + between(-0.3, 0.3)) * 2 * Math.PI / n, v: between(14, 24), s: random() < 0.4 ? 1 : 0})); diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 4259d189..711ef763 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -1606,7 +1606,7 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red marked = got["humidity"]["alone"]["marked"] assert marked["trails"] > 30 and marked["ink"] > 0 and marked["cover"] > 0, marked started_afresh(got["humidity"]["alone"]["restarted"], "humidity") - # BEAD_RULES, the physics every bead runs by: its speed on each glass, dry slowest (0.25 of fog's: crawling), fog quicker, a trail + # BEAD_RULES, the physics every bead runs by: its speed on each glass, dry slowest (0.3 of fog's: crawling), fog quicker, a trail # fastest (1.6 times fog's: water on water; the user: fog beads move fast down tracks like with rain), for the same size, and down # a trail never under TRACK (a freshly landed rain bead's speed there, r 3: a condensed one as quick as a rain one down a track); # still under the run size (about sixteen tiny ones' water: r 1.4), from there creeping extremely slowly, rising gradually with @@ -1622,7 +1622,7 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red else: assert speed["dry"][i] < speed["fog"][i] < speed["trail"][i], (r, speed) assert speed["trail"][i] == pytest.approx(max(1.6 * speed["fog"][i], track)), (r, speed) - assert speed["dry"][i] == pytest.approx(0.25 * speed["fog"][i]), (r, speed) + assert speed["dry"][i] == pytest.approx(0.3 * speed["fog"][i]), (r, speed) assert after["fog"][i] > r and after["trail"][i] == r and after["dry"][i] < r, (r, after) assert [v for r, v in zip(sizes, speed["trail"]) if physics["run"] <= r <= 3] == [track] * 4, speed["trail"] # (r 1.4-3: TRACK) for g in ("dry", "trail", "fog"): @@ -1636,7 +1636,7 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert after["dry"][0] == 0 and after["fog"][-1] > sizes[-1], after # heavy rain's beads: light rain none; heavy, a drop sticking every few s (one in 3 s), a dozen or so (14) on the glass at most, each landing at once # (no fading in) as a large bead (r 3 or more) with a splash (a ring of 10 or more droplets, 3 to 6 of them left on the glass as - # tiny beads); on dry glass crawling (about 0.25 of its speed on fog, the same size), down a trail at TRACK or more (its own size's + # tiny beads); on dry glass crawling (about 0.3 of its speed on fog, the same size), down a trail at TRACK or more (its own size's # speed there), shrinking only (its water left behind), never growing; none vanishing; their wet streaks on the # clear glass drying over 3 to 10 minutes, each its own: thin streaks (a third of the bead's width or less: a px or two), faint # (a greyish film, grime along an edge, a glint, a tiny droplet), uneven along their length (thicker and thinner, now and then @@ -1651,7 +1651,7 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert all(s["r"] >= 3 and s["alpha"] == 1 and s["dots"] >= 10 and s["phase"] == "heavy" for s in sticking["stuck"]), sticking["stuck"] assert all(3 <= s["stay"] <= 6 for s in sticking["stuck"]) and len({s["stay"] for s in sticking["stuck"]}) >= 3, sticking["stuck"] dry, trail = heavy_rain["glass"]["dry"], heavy_rain["glass"]["trail"] - assert dry["lost"] > 0 and dry["gained"] == 0 and 0.17 < dry["all"] / dry["norm"] < 0.33, dry + assert dry["lost"] > 0 and dry["gained"] == 0 and 0.2 < dry["all"] / dry["norm"] < 0.4, dry assert trail["moves"] > 100 and all(0.75 < o["all"] / o["pace"] < 1.3 for o in (dry, trail)), heavy_rain["glass"] assert 0.75 * TRACK < trail["px"] / trail["s"] < 1.3 * 31, trail # (r 1.8-3.2 down a trail: about TRACK, not their size's) # (the splash's droplets left on the glass: tiny beads (r 0.55) like any other, from the splash's end on, as many as were left; From 95872d2b5fdbe44aab33acd6d0255b13bedb0f13 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 01:58:05 +0000 Subject: [PATCH 089/146] Dashboard weather: each part of it its own random stream; checks over enough samples, and the rules stated exactly Every effect (rain, haze's motes, wind, flood, ice, gust) draws from its own stream, seeded apart; inside humidity each concern its own (condensing, thinning, landing), each landing its own (its drop, its splash and droplets) and each bead its own (pace, pauses, path, stretch, life), keyed by its kind and number; a trail's streak and edges noise keyed by its bead's key and the row. A change in one part's draws no longer reshuffles the others'. Tests: the splash droplets kept are checked against the room the beads' own most had as each drop landed (none cut while there was room, every one past it cut); the stretches per restart, the trail speed and the streak widths pooled over every page and trail; the still frame's restarts and runs over 40 fresh still frames; droplets taken back at once over every landing watched; the ice's reach read as it is turned off. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 107 +++++++++++++++++++++------------ tests/test_web_dashboard.py | 97 ++++++++++++++++++++++++------ tests/web_dashboard_browser.js | 54 ++++++++++++++--- 3 files changed, 191 insertions(+), 67 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 3134f7cb..2e30b686 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -230,8 +230,16 @@ return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; const TEST = window.__skyTest || {}; // (test-only, set before the page loads: {step, driven} (see the loop), seed) - const random = seeded(TEST.seed || 1115); - const between = (a, b) => a + (b - a) * random(); + // Each part of the weather its own randomness (a stream named for it, seeded apart: each effect's, and inside one, each of its + // concerns'), so a change in how often one draws leaves every other's sequence as it was: streamOf(name), a function giving 0-1, + // with .between(a, b) + const streamOf = (name) => { + let h = 2166136261; + for (let i = 0; i < name.length; i++) h = Math.imul(h ^ name.charCodeAt(i), 16777619); + const r = seeded((h ^ Math.imul(TEST.seed || 1115, 2654435761)) | 0); + r.between = (a, b) => a + (b - a) * r(); + return r; + }; const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi); const rgb = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)); // Dithering without a grid: a threshold 0-1 at each pixel from a 32 px tile of blue noise (made once, void and cluster: its @@ -345,6 +353,7 @@ // drop that hits a leaf (one as far off as itself) knocks it (wind.knock(), below) and ends there in a tiny splash. const RAIN = ["#2A4560", "#3A6688", "#5A90B8", "#8FC2E2", "#D6F0FF"].map(rgb); const rain = effect((e) => { + const random = streamOf("rain"), between = random.between; // (its own randomness) const SLANT = 0.45; // px left for each px down (no wind) const SLANTS = [0.15, 0.3, 0.45, 0.6, 0.75, 0.9, 1.1, 1.3, 1.55], ALONE = SLANTS.indexOf(SLANT); // the streaks drawn at these const FASTEST = 330; // the near layer's speed: the wind's air full strength on it; slower layers, further off, less @@ -490,6 +499,7 @@ ["#1E1117", "#2C1922", "#3C222F", "#53303F", "#6A3D4F", "#845266"], // Very Unhealthy (plum) ["#1A0C12", "#271119", "#361722", "#4C1F2C", "#642939", "#7E3A4A"]].map((r) => r.map(rgb)); // Hazardous (maroon) const haze = effect((e) => { + const random = streamOf("haze:motes"), between = random.between; // (the dust motes' own randomness; the clouds', own below) const COVER = [0.12, 0.27, 0.45, 0.65, 0.85]; // about how much of the window is under cloud, each band const THICK = [0.75, 0.8, 0.86, 0.93, 1]; // ... and how opaque it is const CALM = 3, BREEZE = 7; // the drift leftward, px/s (the middle depth's): in calm air; more for the wind (1-3) @@ -922,6 +932,7 @@ ["..l.l...", ".lmlmld.", "lmmvmmd.", ".lvmmvmd", "lmmvmmd.", ".dmvmd..", "..dsd...", "...s...."]]]; const TURN = [1, 0.7, 0.35, -0.35, -0.7, -1, -0.7, -0.35, 0.35, 0.7]; // a leaf turning over and back (negative: its underside) const wind = effect((e) => { + const random = streamOf("wind"), between = random.between; // (its own randomness) // The air: a steady wind to the left, pulsing with gusts; slow turbulence over it (the curl of a few drifting waves: it swirls, // never piles up); and a few eddies drifting along behind it, each a vortex that draws leaves near it onto a ring and sweeps them // round and round, then flings them off as it dies away. A leaf eases toward the air's speed where it is (it has a little @@ -1381,6 +1392,17 @@ } const stretchOf = (b) => (b.surge === undefined || !b.st ? 0 : b.st * b.st * (3 - 2 * b.st)); const DOTS = [mapped(["3"], {3: [...WATER[3], 200]}), mapped(["4"], {4: [...WATER[4], 230]})]; // (a splash's droplets) + // (its randomness, each concern its own stream (see streamOf): where beads condense, which tiny ones dry away for others, when a + // drop lands; and each landing's own (its drop, its splash and the droplets it leaves), each bead's own (its pace, its pauses, + // its path, its stretching), known by its kind and its number among that kind: one part's draws never reshuffling another's. + // A trail's streak and edges (wipe) are noise keyed by its bead's own key and the row) + const condensing = streamOf("humidity:condensing"), thinning = streamOf("humidity:thinning"), landing = streamOf("humidity:landing"); + const counts = {fog: 0, rain: 0, splash: 0, placed: 0}, KINDS = Object.keys(counts); + const numbered = (b, n, as = b.kind) => { // (its number among its kind (as: counted as, a test's placed ones apart), its key) + if (n === undefined) n = ++counts[as]; + return Object.assign(b, {tag: `${as}:${n}`, key: n * 4 + KINDS.indexOf(as)}); + }; + const own = (b, concern) => (b.streams || (b.streams = {}))[concern] || (b.streams[concern] = streamOf(`humidity:${concern}:${b.tag}`)); let all = [], splashes = [], made = 0, seeded = false, mist = 0, cap = 0, grid = new Map(), movers = [], fastest = 0, widest = 0, across = null; // (the tiny beads still on the glass, shown in full: drawn once on their own canvas, dots, kept till they go: dotted, each's px) let dots = null; @@ -1498,7 +1520,7 @@ // thin parts dry first; mostly a greyish film, grime here and there along its right edge, a glint now and then, a few tiny // droplets left on it. Where it paused: a little wider there (a blob, a droplet), never a gap. const wipe = (b, y) => { - const w = b.laidW = sprite(b.r).width, left = Math.round(b.x) - (w >> 1), mid = left + (w - 1) / 2, id = b.id; + const w = b.laidW = sprite(b.r).width, left = Math.round(b.x) - (w >> 1), mid = left + (w - 1) / 2, id = b.key; const jag = (s) => Math.round((noise(y / 2, id * 5 + s, 1 << 20, 61) - 0.5) * 3.2); // (an edge: -1, 0 or 1 px, wandering) let a = left + clamp(jag(0), -1, 1), c = left + w - 1 + clamp(jag(1), -1, 1); if (c - a + 1 < Math.max(1, w - 1)) [a, c] = [left, left + w - 1]; @@ -1592,54 +1614,59 @@ let x, y; const near = all.filter((b) => b.state === "on" && b.kind === "fog" && !b.still); for (let tries = 0; tries < 8; tries++) { - if (near.length && random() < 0.12) { - const o = near[Math.floor(random() * near.length)], a = between(0, 2 * Math.PI), far = o.r + between(2, 4.5); + if (near.length && condensing() < 0.12) { + const o = near[Math.floor(condensing() * near.length)], a = condensing.between(0, 2 * Math.PI), far = o.r + condensing.between(2, 4.5); [x, y] = [o.x + Math.cos(a) * far, o.y + heightOf(o.r) / 2 + Math.sin(a) * far]; - } else [x, y] = [between(3, W - 4), 6 + (H * 0.82 - 6) * random() ** 1.3]; + } else [x, y] = [condensing.between(3, W - 4), 6 + (H * 0.82 - 6) * condensing() ** 1.3]; const i = at(x, y); if (listed[i] && wetOf(i) > 0) continue; - if (random() < 0.15 + base[i]) break; + if (condensing() < 0.15 + base[i]) break; } - return {id: ++made, kind: "fog", state: "rest", x: Math.round(clamp(x, 3, W - 4)), y: clamp(y, 6, H * 0.82), r: between(...BORN), - vol: 0, k: random() < 0.15 ? between(3, 5) : between(0.3, 1.5), wait: between(0, 0.5), merged: 0, life: between(...LIFE), - still: true}; + return numbered({id: ++made, kind: "fog", state: "rest", x: Math.round(clamp(x, 3, W - 4)), y: clamp(y, 6, H * 0.82), r: condensing.between(...BORN), + vol: 0, k: condensing() < 0.15 ? condensing.between(3, 5) : condensing.between(0.3, 1.5), wait: condensing.between(0, 0.5), merged: 0, life: condensing.between(...LIFE), + still: true}); }; const pace = (b) => { // a run's next stretch: how fast (of its speed), how far - b.base = random() < 0.25 ? between(1.4, 2.2) : between(0.6, 1); - b.run = between(3, 14); + const r = own(b, "pace"); + b.base = r() < 0.25 ? r.between(1.4, 2.2) : r.between(0.6, 1); + b.run = r.between(3, 14); }; const PAUSES = [[0.75, 0.6, 2.6], [0.25, 0.15, 0.8], [0.4, 0.3, 1.2]]; // (after a stretch, on each glass: how often, how long) function shows(b) { // on the glass now: running from here b.vol = b.r ** 3; - Object.assign(b, {state: "on", x0: b.x, y0: b.y, slant: 0, bend: between(3, 10), pause: between(0, 1), on: false, v: 0, g: FOGGY, rows: [], + Object.assign(b, {state: "on", x0: b.x, y0: b.y, slant: 0, bend: own(b, "path").between(3, 10), pause: own(b, "pauses").between(0, 1), on: false, v: 0, g: FOGGY, rows: [], laid: Math.floor(b.y) + (heightOf(b.r) >> 1), shown: 0}); pace(b); } function land(most) { // heavy rain: a drop sticking to the glass, a large bead at once, with a splash - const r = between(...RAIN_R), x = Math.round(between(Math.ceil(r) + 2, W - 3 - Math.ceil(r))), y = between(6, H * 0.7); - const b = {id: ++made, kind: "rain", x, y, r, merged: 0, life: between(...LIFE)}; + const landed = ++counts.rain, drop = streamOf(`humidity:drop:${landed}`), splash = streamOf(`humidity:splash:${landed}`); // (this landing's own) + const r = drop.between(...RAIN_R), x = Math.round(drop.between(Math.ceil(r) + 2, W - 3 - Math.ceil(r))), y = drop.between(6, H * 0.7); + const b = numbered({id: ++made, kind: "rain", x, y, r, merged: 0, life: drop.between(...LIFE)}, landed); shows(b); b.shown = APPEAR; // (there at once) - b.pause = between(0.45, 0.8); // (settling a moment after its splash before it runs: its droplets thrown clear first) + b.pause = own(b, "pauses").between(0.45, 0.8); // (settling a moment after its splash before it runs: its droplets thrown clear first) all.push(b); - const cy = y + heightOf(r) / 2, n = 10 + Math.floor(random() * 4); - const dots = Array.from({length: n}, (_, j) => ({a: (j + between(-0.3, 0.3)) * 2 * Math.PI / n, v: between(14, 24), s: random() < 0.4 ? 1 : 0})); + const cy = y + heightOf(r) / 2, n = 10 + Math.floor(splash() * 4); + const dots = Array.from({length: n}, (_, j) => ({a: (j + splash.between(-0.3, 0.3)) * 2 * Math.PI / n, v: splash.between(14, 24), s: splash() < 0.4 ? 1 : 0})); // (a few of them, spread round it, thrown out to varied distances and left there: tiny beads once the splash is gone, as many // as the beads' own most has room for, none in a flood; that far past its edge every way, the ring's flattening (0.8 down and // up) made up for, so none thrown up or down lands on it, or close enough to snap back into it at once) - const stay = STAY[0] + Math.floor(random() * (STAY[1] - STAY[0] + 1)), from = Math.floor(random() * n); - let kept = 0; + const stay = STAY[0] + Math.floor(splash() * (STAY[1] - STAY[0] + 1)), from = Math.floor(splash() * n); + let kept = 0, cut = 0, off = 0; // (for the tests: those not left for the beads' most (cut), off the window or in a flood (off), + let room = 0; // and how many the beads' most had room for as it landed (up to all meant)) + for (const now = used(); room < stay && now + (room + 1) * TINY_COST <= most;) room++; for (let j = 0; j < stay; j++) { - const d = dots[(from + Math.round(j * n / stay)) % n], far = (r + 1 + between(...STAY_AT)) / Math.hypot(Math.cos(d.a), 0.8 * Math.sin(d.a)); + const d = dots[(from + Math.round(j * n / stay)) % n], far = (r + 1 + splash.between(...STAY_AT)) / Math.hypot(Math.cos(d.a), 0.8 * Math.sin(d.a)); const px = Math.round(x + Math.cos(d.a) * far), py = Math.round(cy + Math.sin(d.a) * far * 0.8); - if (px < 1 || px > W - 2 || py < 1 || py > H - 2 || used() + (kept + 1) * TINY_COST > most) continue; - if (py + heightOf(BORN[0] + 0.05) >= flood.surface(px) - 1) continue; // (none left in a flood: thrown into its water) + if (px < 1 || px > W - 2 || py < 1 || py > H - 2) { off++; continue; } + if (used() + (kept + 1) * TINY_COST > most) { cut++; continue; } + if (py + heightOf(BORN[0] + 0.05) >= flood.surface(px) - 1) { off++; continue; } // (none left in a flood: thrown into its water) Object.assign(d, {stay: far, px, py}); kept++; } - splashes.push({x, y: cy, r, age: 0, dots}); + splashes.push({x, y: cy, r, age: 0, dots, landed, own: splash}); seen.landed++; - seen.splashes.push({id: b.id, r, dots: n, stay: kept}); + seen.splashes.push({id: b.id, r, dots: n, stay: kept, meant: stay, cut, off, room}); if (seen.splashes.length > 50) seen.splashes.shift(); } const centre = (b) => b.y + heightOf(b.r) / 2; @@ -1722,7 +1749,7 @@ const tiny = all.filter((b) => b.state === "on" && b.still); let best = null, fewest = Infinity; for (let n = 0; n < Math.min(6, tiny.length); n++) { - const b = tiny[Math.floor(random() * tiny.length)]; + const b = tiny[Math.floor(thinning() * tiny.length)]; let k = 0; for (let gy = -1; gy <= 1; gy++) for (let gx = -1; gx <= 1; gx++) { for (const o of grid.get(cell(b.x + gx * GRID, centre(b) + gy * GRID)) || []) if (o !== b && Math.hypot(o.x - b.x, o.y - b.y) <= 4) k++; @@ -1756,7 +1783,7 @@ if (b.waited) { // (setting off again after a pause: the biggest now and then elongating a little as they go) b.waited = false; if (b.r >= STRETCH_R) seen.restarts++; - if (!STILL && b.r >= STRETCH_R && random() < STRETCHES) { b.surge = 0; b.st = b.st || 0; seen.stretches++; } + if (!STILL && b.r >= STRETCH_R && own(b, "stretch")() < STRETCHES) { b.surge = 0; b.st = b.st || 0; seen.stretches++; } } const v = speedFor(b.r, g) * b.base, dy = Math.min(v * time, 1, b.run + 1e-3), s = Math.min(time, dy / v); time -= s; @@ -1767,15 +1794,16 @@ if (!b.on) { // its own wandering: a slant kept a while, now and then a kink; turned back near its bounds b.x = clamp(b.x + b.slant * dy, b.x0 - MEANDER, b.x0 + MEANDER); if ((b.bend -= dy) <= 0) { - const off = b.x - b.x0, k = random(); - b.slant = k < 0.35 ? 0 : k < 0.55 ? between(-1.2, 1.2) : between(-0.45, 0.45); // (straight, a kink, a slant) + const off = b.x - b.x0, path = own(b, "path"), k = path(); + b.slant = k < 0.35 ? 0 : k < 0.55 ? path.between(-1.2, 1.2) : path.between(-0.45, 0.45); // (straight, a kink, a slant) if (Math.abs(off) > MEANDER * 0.5 && Math.sign(b.slant) === Math.sign(off)) b.slant = -b.slant; - b.bend = Math.abs(b.slant) > 0.6 ? between(1, 2.5) : between(4, 16); + b.bend = Math.abs(b.slant) > 0.6 ? path.between(1, 2.5) : path.between(4, 16); } } if (b.run <= 0) { // (the stretch's end: the next, and perhaps a pause, as the glass is here) pace(b); - if (random() < PAUSES[g][0]) b.pause = between(PAUSES[g][1], PAUSES[g][2]); + const pauses = own(b, "pauses"); + if (pauses() < PAUSES[g][0]) b.pause = pauses.between(PAUSES[g][1], PAUSES[g][2]); } } if (b.vol <= GONE) { b.gone = true; seen.shrunk++; return; } // (shrunk to nothing) @@ -1938,12 +1966,12 @@ mist += MISTING * W * (0.95 + 0.4 * e.level) * dt; // (the more humid, the more tiny ones: light 0.95 times MISTING, heavy 1.35) for (let n = tiny; mist >= 1; mist--) { if (n < cap) { all.push(condense()); n++; continue; } - if (random() < 0.75) continue; + if (thinning() < 0.75) continue; const old = isolated(); if (old) { dries(old); all.push(condense()); } } } else mist = 0; - if (heavy() && rainy < RAIN_MOST && used() + 1 <= most && random() < LANDING * dt) land(most); + if (heavy() && rainy < RAIN_MOST && used() + 1 <= most && landing() < LANDING * dt) land(most); seen.rainMost = Math.max(seen.rainMost, all.filter((b) => b.kind === "rain").length); snaps(); for (const b of all) { @@ -1973,9 +2001,10 @@ } all = all.filter((b) => !b.gone); for (const s of splashes) s.age += dt; - for (const s of splashes) if (s.age >= SPLASH_S) for (const d of s.dots) if (d.stay) { // (its droplets left behind: tiny beads now) - const r = BORN[0] + 0.05, b = {id: ++made, kind: "splash", x: d.px, y: d.py, r, k: 1, merged: 0, life: between(...LIFE), - still: true, drying: between(...DRYING)}; + for (const s of splashes) if (s.age >= SPLASH_S) for (const [j, d] of s.dots.entries()) if (d.stay) { // (its droplets left + // behind: tiny beads now) + const r = BORN[0] + 0.05, b = numbered({id: ++made, kind: "splash", x: d.px, y: d.py, r, k: 1, merged: 0, life: s.own.between(...LIFE), + still: true, drying: s.own.between(...DRYING)}, s.landed * 16 + j); shows(b); b.shown = APPEAR; all.push(b); @@ -2011,7 +2040,8 @@ // r}: their ids) tiny: TINY, snap: SNAP, snaps: seen.snaps, cap, place: (list) => list.map(({x, y, r = 0.55}) => { - const b = {id: ++made, kind: "fog", x, y: y - heightOf(r) / 2, r, k: 1, merged: 0, life: between(...LIFE), still: true}; + const b = numbered({id: ++made, kind: "fog", x, y: y - heightOf(r) / 2, r, k: 1, merged: 0, still: true}, undefined, "placed"); + b.life = own(b, "life").between(...LIFE); shows(b); b.shown = APPEAR; all.push(b); @@ -2143,6 +2173,7 @@ const FROG = {k: rgb("#16240F"), g: rgb("#3E7232"), l: rgb("#68A04A"), y: rgb("#B9C97A"), w: rgb("#DCE4C8"), p: rgb("#0B0F08"), d: rgb("#2C5426"), P: rgb("#244A22"), Q: rgb("#356B2E"), R: rgb("#57903F"), S: rgb("#7FB65A")}; const flood = effect((e) => { + const random = streamOf("flood"), between = random.between; // (its own randomness) const SPAN = 0.25; // its full height, of the window's const RISE = 4, DRAIN = 6; // s to fill from empty, and to drain const WAVE = 34; // px/s: the waves' speed along the surface @@ -2494,6 +2525,7 @@ ["#78B6C2", "#98D3D9", "#B9E7EA", "#D5F4F4", "#EDFCFC", "#FFFFFF"], ["#97B6CA", "#B5CFDF", "#CDE2EE", "#E1EEF6", "#F1F8FB", "#FFFFFF"]].map((ramp) => ramp.map(rgb)); const ice = effect((e) => { + const random = streamOf("ice"), between = random.between; // (its own randomness) // each pixel's look: 0, 1 the haze, 2 the bloom (each [colour, alpha]); a crystal's: 3 a barb (or a speck), 4 a side // branch, 5 a stem (or a needle), 6 a fresh tip; a crystal's colour and alpha its own const LOOK = [[ICE[0], 95], [ICE[1], 135], [ICE[1], 90]]; @@ -2834,6 +2866,7 @@ beak: ["#3A250A", "#6C4915", "#9C6F22", "#BE9440"], eye: ["#E4E0D4", "#E4E0D4", "#E4E0D4", "#E4E0D4"], }).map(([k, ramp]) => [k, ramp.map(rgb)])); const gust = effect((e) => { + const random = streamOf("gust"), between = random.between; // (its own randomness) const SPEED = [42, 56]; // px/s across (the wind blowing too: a third faster) const SPIN = [0.45, 0.8]; // rad/s: the cow's and the barn's tumble, slow const TURNS = 48; // ... drawn at this many angles a turn diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 711ef763..32b91fcc 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -1304,8 +1304,13 @@ async def test_the_temporary_test_links_turn_each_effect_on_and_stop_animation_e "effects": [e for e in EVERY if e != "heat"], "levels": None, "running": False, "framed": low["called"]["framed"], "link": None, "frames": 0, "drawn": 0, "stills": 1, "gust": 0, "ink": None, "hand": "rotate(-27.50 240 203)"}, low["called"] assert low["called"]["ink"] > 0, low["called"] - # (humidity's still frame, some minutes in: its biggest beads set off again after pauses meanwhile, none ever elongating) - assert low["beads"]["beads"] >= 20 and low["beads"]["restarts"] >= 1 and low["beads"]["stretches"] == low["beads"]["stretched"] == 0, low["beads"] + # (humidity's still frame, some minutes in: its biggest beads set off again after pauses meanwhile, none ever elongating; seen + # over many still frames, the glass fresh for each (at the end): in one, its few biggest may never pause) + frames = [low["beads"], *low["again"]] + assert len(frames) == 40 and all(f["beads"] >= 20 for f in frames), frames + # (restarts in a good share of them: on the whole one in every other frame or more (a frame's own 0 to a dozen or more, about + # 1 to 2 a frame), so a frame without one is no matter) + assert sum(f["restarts"] for f in frames) >= len(frames) / 2 and all(f["stretches"] == f["stretched"] == 0 for f in frames), frames # the data asked for again and again, the same conditions: fetched once more, no new frame; new conditions: one new still frame assert low["same"] == {k: v for k, v in low["called"].items() if k != "hand"}, low["same"] assert low["changed"]["stills"] == 2 and low["changed"]["effects"] == [e for e in EVERY if e not in ("heat", "uv")] and low["changed"]["frames"] == 0, low["changed"] @@ -1374,6 +1379,24 @@ async def test_every_effect_at_once_is_cheap_no_brighter_than_the_strongest_alon assert sum(v for k, v in together.items() if k not in ("budget", "humidity")) <= together["budget"] + 3, together # (each rounded) +def _whole_streaks(looks): + """Each bead's clear-glass streak, from all the looks at it (each its latest rows as it ran on): each row as first looked at + (fresh), in order down the glass; its width (w) the rows' mean.""" + rows = {} + for t in looks: + if t["kind"] != "clear": + continue + mine = rows.setdefault(t["id"], {}) + for k, y in enumerate(t["ys"]): + mine.setdefault(y, (t["widths"][k], t["paused"][k], t["w"])) + streaks = [] + for bead, mine in rows.items(): + ys = sorted(mine) + streaks.append({"id": bead, "kind": "clear", "ys": ys, "widths": [mine[y][0] for y in ys], "paused": [mine[y][1] for y in ys], + "w": sum(mine[y][2] for y in ys) / len(ys)}) + return streaks + + @needs_browser async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_reduced_motion(server, station): got = await weather(server, "opened") @@ -1450,8 +1473,7 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert speed["trail"] > 1.6 * speed["fog"], (name, speed) assert 0.75 < glass["fog"]["all"] / glass["fog"]["norm"] < 1.3 and 1.6 < glass["trail"]["all"] / glass["trail"]["norm"], (name, glass) assert all(0.75 < glass[g]["all"] / glass[g]["pace"] < 1.3 for g in ("fog", "trail")), (name, glass) - # (down a trail, r 1.8-3.2, all at about TRACK (a rain bead's least there, about 25.6 px/s; r 3.2: 31), not their size's 2-20) - assert 0.75 * TRACK < glass["trail"]["px"] / glass["trail"]["s"] < 1.3 * 31, (name, glass["trail"]) + # (down a trail, r 1.8-3.2, all at about TRACK: seen over all three, below) on_fog = [px / s for px, s in beads["sizes"] if s > 0] # (by size: under 1, 1-1.6, 1.6-2.4, 2.4-3.2, 3.2 and over) assert beads["sizes"][0] == [0, 0], (name, beads["sizes"]) # (under r 1: none running, they run from r 1.4) assert len(on_fog) == 4 and on_fog == sorted(on_fog) and on_fog[0] < 1 and on_fog[-1] > 5, (name, beads["sizes"]) # (1.4-1.6: creeping) @@ -1477,13 +1499,21 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red # (heavy humidity condensing them fast, its glass beaded up a while first (150 frames): full from the watch's start; light's # watched from the first, below: more and more of them) assert beads["tinies"][1]["n"] >= beads["tinies"][1]["cap"] - 3, (name, beads["tinies"]) - # (the biggest (r 2.5 and up) now and then elongating as they set off again after a pause: about one restart in three; never - # a smaller one (as followed here, the weather's time 6 times as fast: a stretch is over within a frame, seen in rain's, below)) - assert beads["restarts"] >= 20 and 0.15 * beads["restarts"] <= beads["stretches"] <= 0.55 * beads["restarts"], (name, beads["restarts"], beads["stretches"]) + # (the biggest (r 2.5 and up) now and then elongating as they set off again after a pause: about one restart in three, as + # seen over all three, below; never a smaller one (as followed here, the weather's time 6 times as fast: a stretch is over + # within a frame, seen in rain's, below)) assert beads["watched"]["small"] == 0 and all(e["r"] >= 2.5 for e in beads["watched"]["stretches"]), (name, beads["watched"]) assert any(t["n"] >= t["cap"] - 3 for t in beads["tinies"]), (name, beads["tinies"]) assert all(t["n"] <= 1.05 * t["cap"] + 4 for t in beads["tinies"]), (name, beads["tinies"]) assert beads["sizes"][1][0] > 0, (name, beads["sizes"]) + # (down a trail, r 1.8-3.2, all at about TRACK (a rain bead's least there, about 25.6 px/s; r 3.2: 31), not their size's 2-20: + # seen over all three pages' together, a page's own a second or two of them, too few for a mean, its pauses one way or another) + px, s = (sum(beads["glass"]["trail"][k] for beads in got["humidity"].values()) for k in ("px", "s")) + assert s >= 3 and 0.75 * TRACK < px / s < 1.3 * 31, {n: b["glass"]["trail"] for n, b in got["humidity"].items()} + # (about one restart in three elongating: seen over all of each page's beads since it opened (the glass beading up first too) + # together, a hundred restarts or more, so a watch's handful more or fewer is no matter) + restarts, stretches = (sum(beads["since"][k] for beads in got["humidity"].values()) for k in ("restarts", "stretches")) + assert restarts >= 20 * len(got["humidity"]) and 0.15 * restarts <= stretches <= 0.55 * restarts, {n: b["since"] for n, b in got["humidity"].items()} # ... nothing at all drawn in the canvas's top two rows (humidity alone: no water along the top edge) assert got["humidity"]["alone"]["top"] == 0, got["humidity"]["alone"] # ... two tiny beads put close together (not touching, within the snap): snapped into one small bead (not tiny) in a few frames, @@ -1647,9 +1677,17 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red heavy_rain = sticking["heavy"] # (75 s of heavy rain at one in 3 s: about 26; more than the handful (5) there were at most before, up to 14) assert 12 <= heavy_rain["landed"] <= 42 and 6 <= heavy_rain["rainMost"] <= 14 and heavy_rain["popped"] == 0, heavy_rain + # (each landing seen: shown at once, or, landing on a bead already there, merged into it at once (in its absorbed)) assert len(sticking["stuck"]) == heavy_rain["landed"], sticking["stuck"] - assert all(s["r"] >= 3 and s["alpha"] == 1 and s["dots"] >= 10 and s["phase"] == "heavy" for s in sticking["stuck"]), sticking["stuck"] - assert all(3 <= s["stay"] <= 6 for s in sticking["stuck"]) and len({s["stay"] for s in sticking["stuck"]}) >= 3, sticking["stuck"] + assert all(s["r"] >= 3 and (s["alpha"] == 1 or s.get("merged")) and s["dots"] >= 10 and s["phase"] == "heavy" for s in sticking["stuck"]), sticking["stuck"] + # (3 to 6 of its droplets meant to stay, all of them left but those thrown off the window or into a flood (off), as many as the + # beads' own most had room for as it landed (room): none cut while there was room, every one past it cut) + assert all(3 <= s["meant"] <= 6 and s["stay"] + s["cut"] + s["off"] == s["meant"] and s["stay"] == min(s["meant"] - s["off"], s["room"]) + for s in sticking["stuck"]), sticking["stuck"] + # (... where there was room, 3 or more left, as ever, but one now and then thrown off the window by a drop landing near its edge) + roomy = [s for s in sticking["stuck"] if s["room"] >= s["meant"]] + assert roomy and all(s["stay"] >= 3 for s in roomy if not s["off"]) and sum(s["off"] > 0 for s in roomy) <= 0.2 * len(roomy), sticking["stuck"] + assert len({s["meant"] for s in sticking["stuck"]}) >= 3, sticking["stuck"] dry, trail = heavy_rain["glass"]["dry"], heavy_rain["glass"]["trail"] assert dry["lost"] > 0 and dry["gained"] == 0 and 0.2 < dry["all"] / dry["norm"] < 0.4, dry assert trail["moves"] > 100 and all(0.75 < o["all"] / o["pace"] < 1.3 for o in (dry, trail)), heavy_rain["glass"] @@ -1666,7 +1704,9 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert len({round(d["fadedAt"]) for d in ends["faded"]}) >= 8, ends["faded"] # (each its own time) # (thrown past the drop's edge every way, up and down too: hardly any taken back the moment it's left (by a runner passing); # none landing on its drop, or close enough to snap back into it at once (they did, about one in ten)) - assert sum(d["end"] == "taken" and d["aged"] <= 0.45 for d in left_on) <= 0.05 * len(left_on), left_on + # (each left in the heavy rain, as followed here and on, below, as its biggest beads set off again: every one once) + every = list({d["id"]: d for d in left_on + sticking["stretching"]["splashes"]}.values()) + assert len(every) >= 120 and sum(d["end"] == "taken" and d["aged"] <= 0.45 for d in every) <= 0.05 * len(every), every # (none outstaying its drying (shown 0.4 s in, 40 s at most, half a second drying away): gone, a merged one shrunk away) assert all(d["aged"] <= 42 for d in ends["on"] + ends["other"]), left_on # (the biggest (r 2.5 and up: here most) setting off again after a pause (heavy rain's own time, 30 s): about one restart in three @@ -1686,16 +1726,26 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert all(t["look"][:3] in STREAK + DROPLET and 0 < t["look"][3] <= (150 if t["look"][:3] in DROPLET else 80) for t in sticking["drying"]), sticking["drying"] hidden = sorted(t["hidden"] for t in sticking["drying"]) assert hidden[0] < 0.75 and hidden[-1] > 0.7, sticking["drying"] - streaks = list({t["id"]: t for t in sticking["looks"] if t["kind"] == "clear"}.values()) # (each bead's once) - assert len(streaks) >= 2 and all(t["kind"] == "clear" for t in sticking["looks"]), sticking["looks"] + assert all(t["kind"] == "clear" for t in sticking["looks"]), sticking["looks"] + streaks = list({t["id"]: t for t in reversed(sticking["looks"])}.values()) # (each bead's first look, as it had run 20 px) + whole = {t["id"]: t for t in _whole_streaks(sticking["looks"])} # (... and all its looks together: its trail as far as it ran) + assert len(streaks) >= 2, sticking["looks"] # (thin: all told a third of the beads' width or less; each a px or two (2 at most on the whole, but where it paused: a little # wider there, a blob; a bead shrunk on dry glass to under 6 px wide keeps its streak's width, so a third of its own width may # be under 2); a blob) rows = [w for t in streaks for w in t["widths"]] assert sum(rows) / len(rows) <= sum(t["w"] for t in streaks) / len(streaks) / 3, streaks + # (their width where they ran, on the whole: over all their trails, as far as each ran, each row held to its own bead's most + # (a mean over one bead's rows alone, a dozen or two of them, is a px or two's wobble)); a px or two everywhere + ran, most = [], 0 + for t in whole.values(): + rows = [w for w, paused in zip(t["widths"], t["paused"]) if not paused] + ran += rows + most += len(rows) * (2 if t["w"] >= 5.5 else max(1.6, t["w"] / 3)) + assert len(ran) >= 100 and sum(ran) <= most, list(whole.values()) for t in streaks: - widths, ran = t["widths"], [w for w, paused in zip(t["widths"], t["paused"]) if not paused] - assert sum(ran) / len(ran) <= (2 if t["w"] >= 5.5 else max(1.6, t["w"] / 3)) and max(widths) <= t["w"] / 2 + 1.5, t + widths = t["widths"] + assert max(widths) <= t["w"] / 2 + 1.5, t assert len(set(widths)) >= 2 and max(widths) - min(widths) >= 1, t # (uneven along it) empty = [w == 0 for w in widths] runs = [len(r) for r in "".join("x" if e else "." for e in empty).split(".") if r] @@ -1705,11 +1755,12 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red eased, gone = sticking["eased"], sticking["after"] assert gone["landed"] == eased["landed"] and gone["beads"] == 0 and gone["popped"] == 0, (eased, gone) # (each run off or shrunk to nothing, or merged into one that was: none dried away otherwise but the splashes' droplets, each - # after 15 to 40 s (some within a frame there: gone between two looks)) + # after 15 to 40 s (some within a frame there: gone between two looks), unless swept up first by a runner passing (taken), as + # ever) assert gone["ranOff"] + gone["shrunk"] > eased["ranOff"] + eased["shrunk"] and eased["beads"] > 0, (eased, gone) dried = sticking["afterWatched"]["splashes"] - assert dried and all(d["end"] in ("faded", "other") and d["aged"] <= 42 and d["glass"] != "fog" for d in dried), dried - assert gone["faded"] - eased["faded"] == len(dried), (eased, gone, len(dried)) + assert dried and all(d["end"] in ("faded", "other", "taken") and d["aged"] <= 42 and d["glass"] != "fog" for d in dried), dried + assert gone["faded"] - eased["faded"] == sum(d["end"] != "taken" for d in dried) > 0, (eased, gone, dried) assert all(15 <= d["fadedAt"] <= 41 for d in dried if d["fadedAt"] is not None), dried # ... their streaks, the rain still on, drying on their own time: there still 6 s after the last bead had gone easing = sticking["easing"] @@ -1809,10 +1860,16 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert still["hand"] == "rotate(-27.50 240 203)", still["hand"] # (the UV's red hand at once at 9: no frames for it) # ... and humidity's still frame as it would be some minutes in: the fog formed, many beads on it, some that have run, their trails beading = still["humidity"] - assert beading["fog"] == 1 and beading["beads"] >= 20 and beading["ran"] >= 2 and beading["trails"] > 30 and beading["stray"] == 0, beading + assert beading["fog"] == 1 and beading["beads"] >= 20 and beading["trails"] > 30 and beading["stray"] == 0, beading assert not beading["running"] and beading["frames"] == 0, beading - # (its biggest beads setting off again after pauses meanwhile, none ever elongating: no stretch in reduced motion) - assert beading["restarts"] >= 1 and beading["stretches"] == beading["stretched"] == 0, beading + # (its beads running meanwhile, and its biggest setting off again after pauses, none ever elongating: no stretch in reduced + # motion; seen over many still frames, the glass fresh for each: in one, its few biggest may never pause) + frames = [beading, *still["again"]] + assert len(frames) == 40 and all(f["beads"] >= 20 for f in frames), frames + # (on the whole one run, and one restart, in every other frame or more: a frame's own few (0 to 4 run, about 1 a frame; restarts + # 0 to a dozen or more, about 1 to 2) too few to bound one alone) + assert sum(f["ran"] for f in frames) >= len(frames) / 2 and sum(f["restarts"] for f in frames) >= len(frames) / 2, frames + assert all(f["stretches"] == f["stretched"] == 0 for f in frames), frames # ... and a flash flood's: full at once, still, no frog flood = still["flood"] assert flood["depth"] == flood["full"] > 0 and flood["frog"] is None and not flood["running"] and flood["frames"] == 0, flood diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index ddf891cc..3ace95aa 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1085,7 +1085,8 @@ async function weatherPage(browser, url, options = {}) { response.json = async () => { const data = await json(); window.__fetched++; return data; }; // (counted before the page renders it) return response; }; - }, [options.pace || 1, !!options.driven, Number(process.env.SKY_SEED) || 0]); // (SKY_SEED: the weather's randomness seeded otherwise) + }, [options.pace || 1, !!options.driven, (Number(process.env.SKY_SEED) || (options.seed ? 1115 : 0)) + (options.seed || 0)]); // (SKY_SEED: the + // weather's randomness seeded otherwise; `seed`: this page's seeded that much further on, another sample of the same weather) if (options.init) await context.addInitScript(options.init.fn, options.init.arg); if (options.animations) await context.route((u) => u.pathname.endsWith("/dashboard"), async (route) => { // (as served with const response = await route.fetch(), page = await response.text(); // MCP_DASHBOARD_ANIMATIONS) @@ -1518,7 +1519,7 @@ const beadWatch = () => { if (b.kind === "splash") { let d = splashes.get(b.id); const before = last.get(b.id); - if (!d) { d = { r: b.r, tiny: true, moved: 0, glass: null, fogged: 0, aged: 0, fadedAt: null, end: "other" }; splashes.set(b.id, d); } + if (!d) { d = { id: b.id, r: b.r, tiny: true, moved: 0, glass: null, fogged: 0, aged: 0, fadedAt: null, end: "other" }; splashes.set(b.id, d); } d.r = Math.max(d.r, b.r); if (!b.tiny) d.tiny = false; if (before && b.tiny && !b.snapping && !before.snapping && (b.x !== before.x || b.y !== before.y)) d.moved++; @@ -1633,7 +1634,8 @@ const humiditySeen = (page, frames) => page.evaluate((frames) => new Promise((re wiped: [...wiped.values()].map((t) => ({ ...t, end: { shown: h.fogAt(...t.at)[0], wet: h.wetAt(...t.at) } })), fog: h.fog(), first: h.first, colours: h.colours(), aged: h.beads.filter((b) => !b.fading).map((b) => b.age), landed: h.landed, looks, crept, tinies, snaps: h.snaps - snaps, tiny: h.tiny, - restarts: h.restarts - from.restarts, stretches: h.stretches - from.stretches, watched: watch && watch.result() }); + restarts: h.restarts - from.restarts, stretches: h.stretches - from.stretches, watched: watch && watch.result(), + since: { restarts: h.restarts, stretches: h.stretches } }); // (since the page opened: its beading up first too) }; __next(step); }), frames); @@ -1742,7 +1744,7 @@ const trailsAge = (page, k, through, most) => page.evaluate(([k, through, most]) // clock held the while, so they're no older for it)) the rain light again: no new one sticking, and those there run off or // shrunk away const rainBeads = (page, light, heavy, after, scale, from = "light") => page.evaluate(([light, heavy, after, scale, from]) => new Promise((resolve) => { - const out = { stuck: [], looks: [] }, seenIds = new Set(), last = new Map(), looked = new Set(), h0 = Sky.state().humidity; + const out = { stuck: [], looks: [] }, seenIds = new Set(), last = new Map(), looked = new Map(), h0 = Sky.state().humidity; const watch = window.__beadWatch ? window.__beadWatch() : null, counts = { restarts: h0.restarts, stretches: h0.stretches }; let n = 0, phase = from, popped = 0, start = Sky.state().frames; const end = () => { // (the beads followed, and the biggest's restarts after a pause and their stretches the while) @@ -1756,16 +1758,23 @@ const rainBeads = (page, light, heavy, after, scale, from = "light") => page.eva last.clear(); for (const b of h.beads) { last.set(b.id, b); - if (b.kind === "rain" && b.y - b.y0 > 20 && !looked.has(b.id) && window.__trailLook) { // (its trail's looks, once) - looked.add(b.id); + // (its trail's looks: once it has run 20 px, and again each 40 px further on (its latest rows, up to 80): all its trail, as far + // as it runs, looked at) + if (b.kind === "rain" && b.y - b.y0 > 20 && b.y - (looked.has(b.id) ? looked.get(b.id) : -Infinity) >= 40 && window.__trailLook) { + looked.set(b.id, b.y); out.looks.push(...window.__trailLook(h, b)); } if (b.kind === "rain" && !seenIds.has(b.id)) { seenIds.add(b.id); const s = h.splashes.find((s) => s.id === b.id); - out.stuck.push({ r: s ? s.r : 0, alpha: b.alpha, dots: s ? s.dots : 0, stay: s ? s.stay : 0, phase }); // (r: as it landed) + out.stuck.push({ r: s ? s.r : 0, alpha: b.alpha, dots: s ? s.dots : 0, stay: s ? s.stay : 0, meant: s ? s.meant : 0, cut: s ? s.cut : 0, + off: s ? s.off : 0, room: s ? s.room : 0, phase }); // (r: as it landed) } } + for (const s of h.splashes) if (!seenIds.has(s.id) && absorbed.has(s.id)) { // (one landing on a bead there, merged at once: never + seenIds.add(s.id); // shown on its own) + out.stuck.push({ r: s.r, alpha: null, dots: s.dots, stay: s.stay, meant: s.meant, cut: s.cut, off: s.off, room: s.room, phase, merged: true }); + } n = state.frames - start; if (phase === "light" && n >= light) { out.light = { landed: h.landed, levels: state.levels.rain }; @@ -1839,6 +1848,23 @@ async function animationsOff(browser, url, out) { // transition, no zoom animation or slide; the data applied at most once a minute (here LOW_EVERY ms: window.__lowTest), however often // it is asked for; no "stop animation" const LOW_EVERY = 1200; +// Humidity's still frame (reduced or low motion) made again `times` times, the glass fresh each time (humidity off, then on again +// at full, the other effects as they are: each another 2.5 minutes of its weather as it would be): each frame's beads, those that +// ran (10 px or more, or off the bottom), its biggest beads' restarts after a pause, its stretches set going and its beads elongated +// (none, ever): so what a still frame's few biggest beads do is seen over many +const STILL_AGAIN = 39; +const stillAgain = (page, times) => page.evaluate((times) => { + const frames = [], levels = Sky.state().levels; + for (let n = 0; n < times; n++) { + const h0 = Sky.state().humidity; + Sky.set({ ...levels, humidity: 0 }, true); + Sky.set({ ...levels, humidity: 1 }, true); + const h = Sky.state().humidity; + frames.push({ beads: h.beads.length, ran: h.beads.filter((b) => b.y - b.y0 >= 10).length + h.ranOff - h0.ranOff, + restarts: h.restarts - h0.restarts, stretches: h.stretches - h0.stretches, stretched: h.beads.filter((b) => b.stretch > 0).length }); + } + return frames; +}, times); async function lowMotion(browser, url, out) { const { context, page, errors, reads } = await weatherPage(browser, url, { animations: "low", init: { fn: (every) => { window.__lowTest = { every }; @@ -1891,6 +1917,7 @@ async function lowMotion(browser, url, out) { tiles: document.querySelectorAll(".tile").length })); out.frames = await page.evaluate((opening) => window.__own - opening, opening); out.opening = opening; + out.again = await stillAgain(page, STILL_AGAIN); // (humidity's still frame again and again: its biggest beads' restarts) out.errors = errors; await context.close(); } @@ -2082,8 +2109,11 @@ const WEATHER = { out.links.rain = []; // (rain: light, heavy, heavy with a flash flood (the test's own flood level), off: [rain, flood]) for (let i = 0; i < 4; i++) { await fx("rain"); const { levels } = await weatherSeen(page); out.links.rain.push([levels.rain, levels.flood]); } await page.waitForFunction(() => Sky.state().iceReach > 2.5); // (the ice grown in a little) - const grown = await page.evaluate(() => Sky.state().iceReach); - await fx("ice"); // (off: it melts back, the loop running on until it's gone) + const grown = await page.evaluate(() => { // (as far as it had grown as it's turned off (one step: none growing between, the + const reach = Sky.state().iceReach; // machine however slow)); off: it melts back, the loop running on until it's gone + [...document.querySelectorAll("#fxtest button")].find((b) => /^ice/.test(b.textContent)).click(); + return reach; + }); await page.waitForTimeout(300); out.links.melting = { grown, reach: await page.evaluate(() => Sky.state().iceReach), ...await weatherSeen(page) }; out.links.pressed = await page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#fxtest button[data-fx]")] @@ -2464,7 +2494,10 @@ const WEATHER = { // humidity's beads condensing on the glass and running down it over 3.6 minutes of the page's time (its weather's time 6 times as // fast), alone and with the wind, beside the rest (small: cheap) (heavy: 100 %); and light (91 %), watched for 2 minutes const beading = Promise.all(["humidity2", "humidity2,wind", "humidity"].map(async (name) => { - const p = await weatherPage(browser, url, { query: `?fx=${name}`, pace: 10, driven: true, context: { viewport: { width: 640, height: 480 } } }); + // (the wind's page another glass than humidity's alone, its own seed: the wind blows no water on the glass, so seeded alike it + // would be the very same beads, nothing more seen) + const p = await weatherPage(browser, url, { query: `?fx=${name}`, pace: 10, driven: true, seed: name.includes("wind") ? 1 : 0, + context: { viewport: { width: 640, height: 480 } } }); await p.page.evaluate(() => Sky.timeScale(6)); await lookable(p.page); if (name !== "humidity") await drive(p.page, 150); // (beaded up a while first: beads run only from about large) @@ -2665,6 +2698,7 @@ const WEATHER = { fog: h.fog().cover, running: Sky.state().running, frames: Sky.state().frames, restarts: h.restarts, stretches: h.stretches, stretched: h.beads.filter((b) => b.stretch > 0).length }; // (none elongating) }); + out.still.again = await stillAgain(still.page, STILL_AGAIN); // (more of its still frames, the glass fresh each time) out.still.flood = await still.page.evaluate(() => { // (a flood: full at once, still; no frog) document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { rain: 1, flood: 1 } })); const f = Sky.state().flood; From 1adb606467a5dbe6d51975051ed77a526083aca7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:11:37 +0000 Subject: [PATCH 090/146] Dashboard weather: the heat as a blazing sun's glare, not a shimmer A white-gold sun bloom in the top right corner (white-hot core, wide warm glow, thin spikes), a few faint sunbeams fanning from it, soft pixel-art lens flares (rings, hexagons, discs, each faintly its own colour) strung along the diagonal through the window's middle, and a faint warm veil over the window. Bigger, whiter and stronger toward 43 C (level 0.3 to 1). Very slow motion: the bloom breathing, the sun wandering a pixel or so, the flares drifting with it; one still frame in low/reduced motion. Sprites pre-rendered once per size (the bloom once per level), dithered on the blue noise; its own random stream ("sun"). The sun drawn after the UV's violet shafts; the flood in front. The refraction shimmer, its veil and mirage glints, and flood.sunk() are gone. Tests updated to the new look. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- README.md | 2 +- lib/web_dashboard.html | 236 ++++++++++++++++++--------------- tests/test_web_dashboard.py | 73 ++++++---- tests/web_dashboard_browser.js | 99 ++++++++------ 4 files changed, 234 insertions(+), 176 deletions(-) diff --git a/README.md b/README.md index 71a5efd9..f05d11a0 100644 --- a/README.md +++ b/README.md @@ -297,7 +297,7 @@ swipe, a drag on the gauge, or a two-finger sideways swipe on a trackpad; it sto Behind the gauges, the weather is drawn as faint pixel art while the readings call for it: rain while it rains, hazy clouds drifting across from the US AQI's Moderate band up, UV beams at a UV index of 11, the glass fogging over at 90 % humidity (heavier to 100 %), beads condensing in the fog and running down it, wiping clear tracks, leaves blowing past -above 15 km/h of wind, a heat haze from 35 °C and ice below 0 °C. "stop animation" at the bottom left stops and clears them for that page view only, and ends any effect a temporary test link turned on; +above 15 km/h of wind, a blazing sun's glare from 35 °C and ice below 0 °C. "stop animation" at the bottom left stops and clears them for that page view only, and ends any effect a temporary test link turned on; nothing is saved, so a reload brings them back. With reduced motion asked for, one still frame. To turn them off for good (for everyone), set `MCP_DASHBOARD_ANIMATIONS=off`. For an e-ink display, set `MCP_DASHBOARD_ANIMATIONS=low` (low motion, for everyone): nothing moves, the weather one faint still frame drawn again only when the conditions change, no transitions, the gauges jumping to each new reading, diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 2e30b686..67cb09cd 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -757,119 +757,142 @@ }; }); - // ---------- heat: heat haze, the air over hot ground shimmering (a mirage's), bending whatever is seen through it ---------- - // No lines of its own: a very faint warm haze low down (draw(), in its place among the effects: something there to bend even with - // nothing else on), then, once everything in front of the flood is drawn (refract(), from the loop's draw()), the canvas's own - // bottom band re-blitted in thin rows, each shifted sideways its own way: fine, fast, irregular ripples (a few waves and a little - // noise summed), rising and dying away upward, strongest at the bottom, as air over hot tarmac; and now and then a pale glint of - // mirage along the very bottom. Stronger the hotter it is (its level: 35 °C to 43 °C). Reduced or low motion: the still haze only. - // (In a flood, from its surface: from as low as its troughs go, flood.sunk(), and kept above() it, so nothing under it is touched) - const HEAT = ["#E2A85A", "#F4C982", "#FCE2AE", "#FFF4D8"].map(rgb); // amber haze, faint to bright; the glint + // ---------- heat: a blazing sun's glare from the top right corner (where the light comes from in the rest's art) ---------- + // A white-gold bloom in the corner: a white-hot core and a wide warm glow round it, a few thin spikes in it; a few faint sunbeams + // fanning down from it across the window; soft lens flares strung along the diagonal from it through the window's middle (rings, + // hexagons and discs of different sizes, each faintly its own colour); and the whole window faintly sun-bleached, a warm veil + // lifting the dark, warmest near the sun. Stronger and whiter the hotter (its level: 0.3 at 35 °C to 1 at 43 °C): a gentle warm + // glow at 35 °C; to 43 °C and up a bigger, whiter, blinding sun, its flares stronger. Very slow: the bloom breathing (its glow and + // its core out of step, the beams each half their own way), the sun wandering a pixel or so and the flares drifting with it (each + // its own way along the diagonal, as a lens's do). Each part painted once a size (the bloom once a level) and blitted; dithered on + // the blue noise (no grid). Reduced or low motion: one still frame. Drawn behind the flood (the sun in the sky, well clear of it), + // the sun itself (sun()) in front of the UV's shafts. + const SUN = ["#B8641E", "#D98A32", "#EFAE4C", "#F8CC70", "#FCE09A", "#FFEFC4", "#FFF8E6", "#FFFFFA"].map(rgb); // ember to white-hot + const SUN_ALPHA = [18, 30, 48, 72, 104, 146, 196, 245]; // (the glow's shades' alphas) + const FLARE = ["#FFD27A", "#FFB08A", "#A6E8C6", "#F6A3A8", "#EEF0A0", "#FFE6B8"].map(rgb); // gold, peach, mint, rose, lemon, cream const heat = effect((e) => { - const SPAN = 0.3, RISE = 14, ROW_MOST = 2; // the band's height (of the window's); its ripples' speed upward (px/s); rows re-blitted - // at most this tall at once where they shift alike - const chance = seeded(4111), within = (lo, hi) => lo + (hi - lo) * chance(); // (its own randomness: the rest's as without it) - let haze = null, band = 0, copy = null, copied = null, shifts = new Int8Array(0), glints = [], glint = [], refracted = 0, top = 0; - // how far (px, + right) the row y px up from the band's bottom is shifted at t: summed waves riding upward, their phases wandering, - // a little noise, all dying away upward; `most`: at the bottom - const shiftOf = (y, t, most) => { - const u = y - t * RISE, k = Math.pow(1 - y / band, 1.4); - const w = 0.5 * Math.sin(u * 0.9 + 1.6 * Math.sin(u * 0.13 + t * 0.8)) + 0.3 * Math.sin(u * 2.3 - t * 5.1) + - 0.9 * (noise(u * 0.55, t * 2.2, 4096, 17) - 0.5) + 0.25 * Math.sin(u * 0.37 + t * 1.3); - return Math.round(most * k * w * (0.8 + 0.2 * Math.sin(t * 0.7 + y * 0.05))); + const random = streamOf("sun"), between = random.between; // (its own randomness) + const DRIFT = [1.6, 1.1]; // how far the sun wanders each way (art px), very slowly + let S = 0, home = [0, 0], at = [0, 0], veil = null, beams = [], spikes = [], flares = [], glow = null, core = null; + let built = 0, R = 0, rc = 0, placed = []; + // The bloom at level L: its glow (radius R, spikes and all) and its core (radius rc, white-hot), each a sprite centred on the sun + const build = (L) => { + built = L; + R = Math.round(S * (0.2 + 0.16 * L)); + rc = Math.max(2, Math.round(S * (0.018 + 0.03 * L))); + glow = painted(2 * R + 1, 2 * R + 1, (x, y) => { + const dx = x - R, dy = y - R, r = Math.hypot(dx, dy), d = r / R; + if (d >= 1) return null; + const angle = Math.atan2(dy, dx); + let spike = 0; + for (const s of spikes) { + const off = Math.abs(((angle - s.angle + 3 * Math.PI) % (2 * Math.PI)) - Math.PI) * r; // (px off its line) + if (d < s.reach) spike = Math.max(spike, Math.exp(-(off * off) / (s.wide * s.wide)) * Math.pow(1 - d / s.reach, 1.4)); + } + const v = Math.pow(1 - d, 2.4) * (0.5 + 0.5 * L) + 0.4 * spike * (0.45 + 0.55 * L), s = shadeOf(v, x, y, SUN.length); + return s < 0 ? null : [...SUN[Math.round(s * (0.55 + 0.45 * L))], SUN_ALPHA[s]]; // (golder the cooler) + }); + const n = Math.ceil(rc * 1.8); + core = painted(2 * n + 1, 2 * n + 1, (x, y) => { + const d = Math.hypot(x - n, y - n) / rc, s = d < 1 ? 2 : shadeOf((1.8 - d) / 0.8, x, y, 3); + return s < 0 ? null : [...SUN[Math.min(7, 4 + s + (L > 0.6 ? 1 : 0))], [150, 210, 255][s]]; + }); + }; + // A lens flare's sprite: radius r, its colour; a disc (soft, fading out), a ring (a thin bright rim, a whisper inside) or a hexagon + // (faintly filled, its rim brighter) + const flare = (kind, r, c) => { + const n = Math.ceil(r) + 1, tints = [c.map((v) => v * 0.85), c, c.map((v) => v + (255 - v) * 0.45)]; + return painted(2 * n + 1, 2 * n + 1, (x, y) => { + const dx = x - n, dy = y - n, d = Math.hypot(dx, dy) / r; + let v; + if (kind === "disc") v = d < 1 ? 0.25 + 0.6 * Math.pow(1 - d * d, 0.7) : 0; + else if (kind === "ring") v = Math.exp(-Math.pow((d - 0.86) / 0.11, 2)) * 0.95 + (d < 0.86 ? 0.12 : 0); + else { // (a hexagon: its edges' distance across, flat top and bottom) + const h = Math.max(Math.abs(dy), Math.abs(dy) / 2 + Math.abs(dx) * 0.866) / (r * 0.866); + v = h < 1 ? (h > 0.84 ? 0.85 : 0.22 + 0.1 * (1 - h)) : 0; + } + const s = shadeOf(v, x, y, 3); + return s < 0 ? null : [...tints[s].map(Math.round), [44, 70, 104][s]]; + }); }; return { - strength: () => 0.35 + 0.3 * e.level, - // (for the tests: the band (art px), its top as last drawn, each of its rows' shift (top first), the most a row may shift now, - // how many frames it has refracted, the glints showing; seen(): the band as drawn against the band as it was before it was bent - // (the canvas's own, saved): each row's [shift, whether it differs, the shift that matches it (null: none does)]) - probe: () => ({band, top, shifts: [...shifts], most: mostNow(), refracted, glints: glints.length, seen}), - forget() { glints = []; refracted = 0; shifts.fill(0); }, + strength: () => 0.4 + 0.4 * e.level, + // (for the tests: the sun's middle as last drawn and its home (art px), the bloom's radius and its core's, the level it was + // built for, the beams; each flare as last drawn {kind, x, y (its middle), r, k: how far along the diagonal, colour}) + probe: () => ({sun: at.map(Math.round), home, radius: R, core: rc, built, beams: beams.length, size: [W, H], + flares: placed.map((f) => ({...f}))}), resize() { - band = Math.max(8, Math.ceil(H * SPAN)); - // the haze: a faint warm veil, thickest at the bottom, its alpha in a few dithered steps, mottled in soft streaks wider than - // tall (so its bending shows) - haze = painted(W, band, (x, y) => { - const k = y / band, m = noise(x / 11, y / 1.6, Math.max(1, Math.ceil(W / 11)), 23), n = noise(x / 37, y / 5, Math.max(1, Math.ceil(W / 37)), 29); - const v = Math.pow(k, 2.2) * (0.3 + 0.5 * m * m + 0.2 * n), s = shadeOf(v, x, y, 6); - return s < 0 ? null : [...HEAT[s > 3 ? 1 : 0], 22 + 26 * s]; + S = Math.min(W, H); + home = [W - Math.round(S * 0.03), Math.round(S * 0.03)]; // (in the corner: its glare over the tiles' edges, not their gauges) + at = home.slice(); + built = 0; + // its spikes: six thin ones, about evenly round, each its own length + spikes = Array.from({length: 6}, (_, i) => ({angle: (i + between(-0.2, 0.2)) * Math.PI / 3 + 0.35, reach: between(0.55, 1), + wide: between(0.7, 1.3)})); + // the veil: faint warm light over the whole window, warmest near the sun + const far = Math.hypot(W, H); + veil = painted(W, H, (x, y) => { + const v = 0.3 + 0.7 * Math.pow(1 - Math.min(1, Math.hypot(x - home[0], y - home[1]) / (far * 0.85)), 1.8); + const s = shadeOf(v, x, y, 4); + return s < 0 ? null : [...SUN[s > 1 ? 2 : 1], [16, 24, 34, 46][s]]; }); - copy = canvasOf(W, band); - copied = copy.getContext("2d"); - shifts = new Int8Array(band); - glint = [8, 13, 19].map((n) => painted(n, 1, (x) => { // (a glint: a broken streak a pixel tall, brightest in its middle) - const v = Math.sin(Math.PI * (x + 0.5) / n); - return dither(x * 7, n) < v * 0.9 ? [...HEAT[v > 0.6 ? 3 : 2], Math.round(255 * v)] : null; + // the sunbeams: five, fanning down and left from the sun, faint, fading as they go, each its own width and length; two + // canvases (alternate beams), breathing out of step + const rays = Array.from({length: 5}, (_, i) => ({angle: (0.56 + (i + between(-0.3, 0.3)) * 0.2) * Math.PI, // (down to left) + wide: between(0.018, 0.04), long: far * between(0.55, 0.95)})); + beams = [0, 1].map((half) => painted(W, H, (x, y) => { + const dx = x - home[0], dy = y - home[1], r = Math.hypot(dx, dy), angle = Math.atan2(dy, dx); + let v = 0; + for (let i = half; i < rays.length; i += 2) { + const b = rays[i], off = Math.abs(((angle - b.angle + 3 * Math.PI) % (2 * Math.PI)) - Math.PI) / b.wide; + if (r < b.long && off < 3) v += Math.exp(-off * off) * Math.pow(1 - r / b.long, 1.2) * Math.min(1, r / (S * 0.12)); + } + const s = shadeOf(v * 0.75, x, y, 3); + return s < 0 ? null : [...SUN[4 + s], [20, 30, 42][s]]; })); - glints = []; - }, - step(dt) { - if (STILL) return; - for (const g of glints) g.age += dt; - glints = glints.filter((g) => g.age < g.life); - if (glints.length < 4 && chance() < dt * (0.8 + 1.6 * e.level) * e.amount) - glints.push({x: within(0, W - 20), row: Math.floor(within(0, 3)), sprite: glint[Math.floor(within(0, 3))], age: 0, - life: within(0.25, 0.9)}); - }, - draw(g, alpha) { - top = Math.round(H - band - flood.sunk()); - flood.above(g, () => { - g.globalAlpha = Math.min(1, alpha * 1.2); - g.drawImage(haze, 0, top); + // the flares: along the diagonal from the sun through the window's middle (k: 0 at the sun, 1 at the middle), a little off it + // either way, of different sizes and kinds and faint colours + const KINDS = ["hex", "disc", "ring", "hex", "disc", "ring", "disc"]; + const ks = [0.34, 0.52, 0.7, 0.93, 1.16, 1.42, 1.72]; + flares = ks.map((k, i) => { + const kind = KINDS[i], r = S * (kind === "ring" ? between(0.04, 0.085) : kind === "hex" ? between(0.02, 0.045) : between(0.012, 0.035)); + const colour = FLARE[Math.floor(random() * FLARE.length)]; + return {kind, k: k + between(-0.04, 0.04), r, colour, aside: between(-0.015, 0.015) * S, weight: between(0.55, 1), + sprite: flare(kind, r, colour)}; }); }, - // The bending: the band as drawn so far saved, then each row whose shift isn't 0 drawn again shifted (rows alike drawn together, - // ROW_MOST at most), the gap it leaves at its edge filled from the row unshifted; then the glints, on their rows' shifts - refract(g, alpha, t) { - if (STILL || !band) return; - const most = mostNow(); - for (let y = 0; y < band; y++) shifts[band - 1 - y] = shiftOf(y, t, most); - copied.clearRect(0, 0, W, band); - copied.drawImage(canvas, 0, top, W, band, 0, 0, W, band); - refracted++; - flood.above(g, () => { - g.globalAlpha = 1; - for (let r = 0; r < band;) { - const dx = shifts[r]; - let n = 1; - while (n < ROW_MOST && r + n < band && shifts[r + n] === dx) n++; - if (dx) { - g.clearRect(0, top + r, W, n); - g.drawImage(copy, 0, r, W, n, dx, top + r, W, n); - if (dx > 0) g.drawImage(copy, 0, r, dx, n, 0, top + r, dx, n); - else g.drawImage(copy, W + dx, r, -dx, n, W + dx, top + r, -dx, n); - } - r += n; - } - for (const gl of glints) { - const r = band - 1 - gl.row; - g.globalAlpha = alpha * 0.9 * Math.sin(Math.PI * gl.age / gl.life); - g.drawImage(gl.sprite, Math.round(gl.x) + shifts[r], top + r); - } + draw(g, alpha, t) { + if (e.level > 0 && e.level !== built) build(e.level); + const L = built; + at = [home[0] + DRIFT[0] * Math.sin(t * 0.07 + 1.3), home[1] + DRIFT[1] * Math.sin(t * 0.053 + 0.4)]; + const sx = Math.round(at[0] - home[0]), sy = Math.round(at[1] - home[1]); + g.globalAlpha = alpha * (0.75 + 0.25 * L); + g.drawImage(veil, 0, 0); + beams.forEach((b, i) => { + g.globalAlpha = alpha * (0.55 + 0.45 * L) * (0.7 + 0.3 * Math.sin(t * (i ? 0.23 : 0.29) + i * 2.1)); + g.drawImage(b, sx, sy); }); + // the flares: each where the line from the sun through the window's middle puts it (so drifting as the sun does, those past + // the middle the other way) + const mx = W / 2 - at[0], my = H / 2 - at[1], len = Math.hypot(mx, my) || 1; + placed = flares.map((f) => { + const x = Math.round(at[0] + f.k * mx - f.aside * my / len), y = Math.round(at[1] + f.k * my + f.aside * mx / len); + const n = (f.sprite.width - 1) / 2; + g.globalAlpha = alpha * f.weight * (0.35 + 0.65 * L) * (0.9 + 0.1 * Math.sin(t * 0.31 + f.k * 4)); + g.drawImage(f.sprite, x - n, y - n); + return {kind: f.kind, x, y, r: f.r, k: f.k, colour: f.colour}; + }); + }, + // The sun itself, drawn after the UV's shafts and glow (from the loop's draw()): its glow, breathing, and its white-hot core, so + // nothing cool lies over it + sun(g, alpha, t) { + g.globalAlpha = alpha * (0.86 + 0.14 * Math.sin(t * 0.45)); // (the glow breathing, about every 14 s) + g.drawImage(glow, Math.round(at[0]) - R, Math.round(at[1]) - R); + g.globalAlpha = Math.min(1, alpha * (1.15 + 0.15 * Math.sin(t * 0.71 + 2))); // (the core: out of step with the glow) + const n = (core.width - 1) / 2; + g.drawImage(core, Math.round(at[0]) - n, Math.round(at[1]) - n); }, }; - function mostNow() { return (1 + 2.6 * e.level) * e.amount; } - function seen() { // (test-only: see probe) - const now = ctx.getImageData(0, top, W, band).data, was = copied.getImageData(0, 0, W, band).data, edge = 10; - const rows = []; - for (let r = 0; r < band; r++) { - const at = (d, x) => r * W * 4 + x * 4, same = (x, dx) => { - for (let c = 0; c < 4; c++) if (now[at(now, x) + c] !== was[at(was, x - dx) + c]) return false; - return true; - }; - let differs = false, ink = false; - for (let x = edge; x < W - edge; x++) { if (!same(x, 0)) differs = true; if (was[at(was, x) + 3]) ink = true; } - let match = null; - if (ink) for (const dx of [0, 1, -1, 2, -2, 3, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8, -8]) { - let ok = true; - for (let x = edge; x < W - edge && ok; x++) ok = same(x, dx); - if (ok) { match = dx; break; } - } - rows.push([shifts[r], differs, match]); - } - return rows; - } }); // ---------- uv: soft shafts of violet light coming in from the top, slowly swaying and breathing ---------- @@ -2164,7 +2187,7 @@ // one side; calming slowly as the rain eases. Rain, the drips and the wind's wisps end at it, none ever drawn below; every one of // the wind's leaves its surface reaches (its waves as they are, wherever a leaf meets them) sticks there, floats, then sinks and // rests on the bottom, every one, the flood's own from then on: there while it lasts, the wind gone or not, gone as it drains away; the haze - // and the heat's shimmer are drawn above it (above(): the haze down to its surface, the heat from as low as its troughs go). Rarely (about every FROG_EVERY s on + // is drawn above it (above(): down to its surface, as low as its troughs go). Rarely (about every FROG_EVERY s on // average, never in its first FROG_FIRST s) a bemused frog on a lily pad floats across, right to left with the wind, bobbing; the // test link's flood (level 2) sends its first one FROG_FIRST s after the water starts rising. Drawn after the drips and the // leaves (the sunken ones show through it, tinted and dimmed), before the ice. @@ -2323,9 +2346,6 @@ // window's bottom; each one [id, state, its bottom row against the surface at its middle]; all of them; shows()) leaves: () => leafProbe(), lift: () => depth, - // (how far up from the window's bottom its surface's lowest trough can be: what sits on it is drawn down to there and kept - // above() it, so its edge is the wavy surface, never a straight line at its level) - sunk: () => (depth > 0 ? Math.max(0, depth - DIP) : 0), // paint(x, n, y) for each run of columns x to x + n - 1 whose surface is on row y (as drawn; H with no water), left to right columns(paint) { if (depth <= 0) return paint(0, W, H); @@ -3163,9 +3183,9 @@ for (const k of ORDER) { const fx = effects[k], a = fx.strength() * fx.amount * (OWN_STRENGTH.has(k) ? faint : cap); drawn[k] = fx.amount > 0 ? a : 0; - // (the heat's haze bending what's drawn so far, before the flood: everything in front of the water but the frost on the glass) - if (k === "flood" && effects.heat.amount > 0) effects.heat.refract(ctx, drawn.heat, clock); if (fx.amount > 0) fx.draw(ctx, a, clock); + // (the heat's sun in front of the UV's shafts: white-hot over their violet) + if (k === "uv" && effects.heat.amount > 0) effects.heat.sun(ctx, drawn.heat, clock); } ctx.globalAlpha = 1; } diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 32b91fcc..50c0d47c 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -1875,33 +1875,54 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert flood["depth"] == flood["full"] > 0 and flood["frog"] is None and not flood["running"] and flood["frames"] == 0, flood # ... and a gust (the page's, the test link's, asked for by name): nothing blown across, no loop assert still["gust"] == {"fling": None, "sent": 0, "running": False, "frames": 0}, still["gust"] - # ... and the heat's: its faint warm haze only, nothing bent (no shimmer: it would need motion) + # ... and the heat's: its sun in the corner, white-hot, its flares, still (no loop) heat = still["heat"] - assert heat["refracted"] == heat["shifts"] == 0 and heat["drawn"] > 0 and heat["band"] > 0 and not heat["running"], heat - # the heat (?fx=heat): a heat haze, not drawn lines (squiggles read as smell lines): a faint amber veil low down, and the canvas's - # own bottom band bent sideways through it in thin rows, by ripples rising and dying away upward - for name, hot in (("alone", got["heat"]), ("over", got["heatOver"])): - assert hot["errors"] == [] and hot["refracted"] > 0 and hot["band"] >= 0.25 * hot["height"], (name, hot) - assert hot["top"] + hot["band"] == hot["height"], (name, hot) # (from the bottom: no flood) - rows = [(r, *row) for f in hot["frames"] for r, row in enumerate(f["rows"]) if r < hot["band"] - 3] # (not the glints' rows) - # each row drawn exactly as the band was before it was bent, shifted by its own shift (none differing but those shifted) - assert all(match == shift for _, shift, _, match in rows if match is not None), (name, rows) - assert all(differs for _, shift, differs, match in rows if shift and match is not None), (name, rows) - assert all(not differs for _, shift, differs, _ in rows if not shift), (name, rows) - bent = [r for r, shift, _, match in rows if shift and match is not None] - assert len(bent) >= 0.2 * len(rows), (name, len(bent), len(rows)) - # ... strongest at the bottom, dying away upward (its top eighth all but still), and never still: changing frame to frame - band, frames = hot["band"], hot["frames"] - mean = lambda lo, hi: sum(abs(v) for f in frames for v in f["shifts"][int(lo * band):int(hi * band)]) / (len(frames) * (int(hi * band) - int(lo * band))) - assert mean(0.75, 1) > 0.8 and mean(0.75, 1) > 3 * mean(0, 0.25) and mean(0, 0.125) < 0.1, (name, mean(0, 0.25), mean(0.75, 1)) - assert all(max(map(abs, f["shifts"])) <= round(hot["most"]) + 1 for f in frames), name - assert sum(a != b for f, g in zip(frames, frames[1:]) for a, b in zip(f["shifts"], g["shifts"])) > 0.3 * band * (len(frames) - 1), name - # ... no long thin strokes in it (a pixel tall, 5 px or more long, brighter than above and below: a drawn squiggle) - assert hot["strokes"] <= 3, (name, hot["strokes"]) - # ... alone: its veil over all of its bottom rows, faint, amber (red over green over blue: no green or brown smoke) - alone = got["heat"] - r, g, b = alone["colour"] - assert alone["cover"] > 0.9 and 0.08 < alone["alpha"] < 0.35 and r > g * 1.15 and g > b * 1.4 and r > 180, alone + assert heat["built"] == 1 and heat["flares"] >= 5 and heat["drawn"] > 0 and not heat["running"] and heat["frames"] == 0, heat + assert max(abs(a - b) for a, b in zip(heat["sun"], heat["home"])) <= 2 and heat["at"][3] > 60 and min(heat["at"][:3]) > 140, heat # (faint: a still frame, every effect on) + # the heat (?fx=heat): a blazing sun's glare, not a shimmer: a white-gold bloom in the top right corner, lens flares strung along + # the diagonal from it through the window's middle, the window faintly warmed; more so the hotter + hot = got["heat"] + assert hot["errors"] == [] and hot["cost"] < 4, hot + looks = hot["looks"] + for look in looks: + w, h = look["size"] + # (its sun in the top right corner, its core white-hot: bright, warm (no blue over red), at every level) + assert look["home"][0] >= 0.9 * w and look["home"][1] <= 0.1 * h and look["built"] == look["level"], look + r, g, b = look["coreLook"]["colour"] + assert look["coreLook"]["light"] > 150 and r >= g >= b and b > 150, look["coreLook"] + # (its flares: five or more on screen, each standing out of the veil around it, near the line from the sun through the middle, the + # first nearer the sun than the middle, the last past it, of different sizes and kinds) + on = [f for f in look["flares"] if f["on"]] + assert len(on) >= 5 and all(f["alpha"] > 1.5 * look["veil"]["alpha"] for f in on), (on, look["veil"]) + assert all(f["aside"] <= 0.03 * min(w, h) + 1.5 for f in on), on + assert min(f["k"] for f in on) < 0.5 and max(f["k"] for f in on) > 1.2, on + assert {f["kind"] for f in on} == {"ring", "hex", "disc"} and max(f["r"] for f in on) > 2.5 * min(f["r"] for f in on), on + # (the window outside the bloom faintly veiled, warm: red over blue, inked nearly all over, its light a lift, not a glare) + r, g, b = look["veil"]["colour"] + assert look["veil"]["alpha"] > 0.03 and r > 1.3 * b and look["veil"]["light"] < 25, look["veil"] + # ... stronger the hotter: from 35 °C to 43 °C the bloom bigger, its core larger, the veil warmer, the flares stronger + cool, warm, hottest = looks + assert cool["radius"] < warm["radius"] < hottest["radius"] and cool["core"] < hottest["core"], looks + assert cool["veil"]["light"] < warm["veil"]["light"] < hottest["veil"]["light"], [l["veil"] for l in looks] + assert cool["drawn"] < warm["drawn"] < hottest["drawn"] and cool["veil"]["alpha"] < hottest["veil"]["alpha"], looks + # ... dithered irregularly (no grid: under 100, as gridPeak sees it; ordered, about 200) + assert hot["grid"] < 100, hot["grid"] + # ... very slow: over 24 s the sun wandering a pixel or two about its home, never more than a pixel a second; each flare drifting + # with it, the other way past the middle ((1 - k) times as far, as a lens's flares do) + moving = hot["moving"] + home = looks[-1]["home"] + assert all(abs(m["sun"][0] - home[0]) <= 2 and abs(m["sun"][1] - home[1]) <= 2 for m in moving), moving + assert len({tuple(m["sun"]) for m in moving}) > 1, moving + assert all(abs(a - b) <= 1 for m, n in zip(moving, moving[1:]) for a, b in zip(m["sun"], n["sun"])), moving + for m, n in zip(moving, moving[1:]): + dx, dy = n["sun"][0] - m["sun"][0], n["sun"][1] - m["sun"][1] + for (x0, y0, k), (x1, y1, _) in zip(m["flares"], n["flares"]): + assert abs((x1 - x0) - (1 - k) * dx) <= abs(1 - k) + 1 and abs((y1 - y0) - (1 - k) * dy) <= abs(1 - k) + 1, (m, n) + # with the UV on too: the sun still white-hot in its corner (the UV's shafts cool violet beside it), the two within the cap + over = got["heatOver"] + assert over["errors"] == [] and over["looks"][0]["drawn"] < hottest["drawn"], over + r, g, b = over["looks"][0]["coreLook"]["colour"] + assert over["looks"][0]["coreLook"]["light"] > 150 and r >= b, over["looks"][0]["coreLook"] def clean_glass(marks): diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 3ace95aa..72ae38d6 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1349,42 +1349,57 @@ const rainSeen = (page, ms) => page.evaluate((ms) => new Promise((resolve) => { const begun = () => Sky.clock().frames >= 50 ? look() : __next(begun); begun(); }), ms); -// The heat's haze on a driven page (its effect on, and nothing else but what the query asks for), 60 frames in, then 8 frames 5 -// apart: each its band's rows as Sky's heat probe sees them (seen(): [shift, differs from the band as drawn before it was bent, the -// shift that matches it]) and its shifts; then the canvas: in the band (all but its bottom 4 rows: the mirage's glints), the long thin -// strokes (runs of 5 px or more a pixel tall, each brighter than the pixels above and below it by half again: a drawn line), the share -// of its bottom 10 rows drawn, the drawn pixels' mean colour and alpha (0-1) there -const heatSeen = (page) => page.evaluate(() => { - Sky.advance(60); - const frames = []; - for (let i = 0; i < 8; i++) { - Sky.advance(5); - const h = Sky.state().heat; - frames.push({ rows: h.seen(), shifts: h.shifts }); - } - const h = Sky.state().heat, c = document.querySelector("#sky canvas"), W = c.width; - const d = c.getContext("2d").getImageData(0, h.top, W, h.band).data; - const light = (x, y) => { const i = (y * W + x) * 4; return (0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2]) * d[i + 3] / 255; }; - let strokes = 0; - for (let y = 1; y < h.band - 4; y++) { - let run = 0; - for (let x = 0; x <= W; x++) { - const on = x < W && light(x, y) > 4 && light(x, y) > 1.5 * Math.max(light(x, y - 1), light(x, y + 1)); - if (on) run++; - else { if (run >= 5) strokes++; run = 0; } - } +// The heat's blazing sun on a driven page, with each of `levels` in turn (the effects on: {heat: its strength, 0.3 at 35 °C to 1 +// at 43 °C, and any others}), each 60 frames after it's set: the sun as Sky's heat probe has it (its middle, home, bloom +// and core radii, the level built, its flares), the canvas's mean colour and luminance (alpha-weighted, 0-255) in the sun's core and +// the canvas's mean alpha (0-1) and colour over the window outside the bloom (the veil, the beams and flares in it), each flare's +// mean alpha over its own disc, how far it is off the line from the sun through the window's middle (art px), the grid seen in the +// window's top left (gridPeak's ratio: the veil's dithering); then, at the last level, 24 looks a second apart: the sun's middle and +// each flare's, as drawn +const sunSeen = (page, levels) => page.evaluate(async (levels) => { + const c = document.querySelector("#sky canvas"), g = c.getContext("2d"); + const looks = []; + for (const detail of levels) { + const level = detail.heat; + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail })); + Sky.advance(60); + const h = Sky.state().heat, W = c.width, H = c.height, d = g.getImageData(0, 0, W, H).data; + const at = (x, y) => { const i = (y * W + x) * 4; return [d[i], d[i + 1], d[i + 2], d[i + 3]]; }; + const mean = (inside) => { + let n = 0, alpha = 0, rgb = [0, 0, 0], light = 0; + for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { + if (!inside(x, y)) continue; + const [r, gg, b, a] = at(x, y); + n++; alpha += a / 255; + light += (0.2126 * r + 0.7152 * gg + 0.0722 * b) * a / 255; + if (a) { rgb[0] += r * a; rgb[1] += gg * a; rgb[2] += b * a; } + } + const wa = alpha * 255; + return { n, alpha: alpha / Math.max(n, 1), light: light / Math.max(n, 1), colour: rgb.map((v) => Math.round(v / Math.max(wa, 1))) }; + }; + const [sx, sy] = h.sun, off = (x, y) => Math.hypot(x - sx, y - sy); + const core = mean((x, y) => off(x, y) <= h.core * 0.8); + const veil = mean((x, y) => off(x, y) > h.radius); + const [mx, my] = [W / 2 - sx, H / 2 - sy], len = Math.hypot(mx, my); + const flares = h.flares.map((f) => { + let n = 0, alpha = 0; + for (let y = Math.max(0, Math.floor(f.y - f.r)); y <= Math.min(H - 1, Math.ceil(f.y + f.r)); y++) + for (let x = Math.max(0, Math.floor(f.x - f.r)); x <= Math.min(W - 1, Math.ceil(f.x + f.r)); x++) + if (Math.hypot(x - f.x, y - f.y) <= f.r * 0.95) { n++; alpha += at(x, y)[3] / 255; } + return { ...f, alpha: alpha / Math.max(n, 1), aside: Math.abs((f.x - sx) * my - (f.y - sy) * mx) / len, + on: f.x >= 0 && f.x < W && f.y >= 0 && f.y < H }; + }); + looks.push({ level, sun: h.sun, home: h.home, radius: h.radius, core: h.core, built: h.built, size: h.size, flares, + coreLook: core, veil, drawn: Sky.state().drawn.heat }); } - let drawn = 0, n = 0, rgb = [0, 0, 0], alpha = 0; - for (let y = h.band - 10; y < h.band; y++) for (let x = 0; x < W; x++) { - const i = (y * W + x) * 4; - n++; - if (!d[i + 3]) continue; - drawn++; alpha += d[i + 3] / 255; - for (let k = 0; k < 3; k++) rgb[k] += d[i + k]; + const moving = []; + for (let i = 0; i < 24; i++) { + Sky.advance(30); + const h = Sky.state().heat; + moving.push({ sun: h.sun, flares: h.flares.map((f) => [f.x, f.y, f.k]) }); } - return { band: h.band, top: h.top, most: h.most, refracted: h.refracted, frames, strokes, cover: drawn / n, - colour: rgb.map((v) => Math.round(v / Math.max(drawn, 1))), alpha: alpha / Math.max(drawn, 1), height: c.height }; -}); + return { looks, moving, cost: Sky.state().cost, width: c.width, height: c.height }; +}, levels); // uv's beams over 40 s of the page's time (on a page whose clock runs on fast: `pace`, below; each frame drawn 0.1 s on, Sky's // longest step): where each beam's halo was drawn (with uv alone, the glow, then each beam's halo and core), its least and greatest x // (art px), how many times it turned back (from going one way to the other), and how faint and bright it was @@ -2483,10 +2498,11 @@ const WEATHER = { await uv.context.close(); return [seen, frost]; })(); - // the heat's haze, alone and over the haze's clouds and heavy rain in the wind (small: cheap) - const hot = Promise.all(["heat", "heat,haze3,rain2,wind"].map(async (name) => { + // the heat's blazing sun at 35 °C, between and at 43 °C; and at 43 °C with the UV's shafts on too (small: cheap) + const hot = Promise.all([["heat", [{ heat: 0.3 }, { heat: 0.65 }, { heat: 1 }]], ["heat,uv", [{ heat: 1, uv: 1 }]]].map(async ([name, levels]) => { const p = await weatherPage(browser, url, { query: `?fx=${name}`, driven: true, context: { viewport: { width: 640, height: 480 } } }); - const seen = await heatSeen(p.page); + const seen = await sunSeen(p.page, levels); + seen.grid = (await gridPeak(p.page)).ratio; // (its veil's dithering) seen.errors = p.errors; await p.context.close(); return seen; @@ -2704,11 +2720,12 @@ const WEATHER = { const f = Sky.state().flood; return { depth: f.depth, full: f.full, frog: f.frog, running: Sky.state().running, frames: Sky.state().frames }; }); - out.still.heat = await still.page.evaluate(() => { // (the heat: its still haze only, nothing bent) + out.still.heat = await still.page.evaluate(() => { // (the heat: its sun, still) document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { heat: 1 } })); - const h = Sky.state().heat; - return { refracted: h.refracted, shifts: h.shifts.filter((v) => v).length, top: h.top, band: h.band, drawn: Sky.state().drawn.heat, - running: Sky.state().running }; + const h = Sky.state().heat, c = document.querySelector("#sky canvas"); + const [r, g, b, a] = c.getContext("2d").getImageData(h.sun[0], h.sun[1], 1, 1).data; + return { sun: h.sun, home: h.home, built: h.built, flares: h.flares.length, drawn: Sky.state().drawn.heat, at: [r, g, b, a], + running: Sky.state().running, frames: Sky.state().frames }; }); out.still.gust = await still.page.evaluate(() => { // (a gust: nothing sent, by the page or the test link) document.dispatchEvent(new Event("ecobot-gust")); From c2ae11decf5e35de9005f8b4ec26966ddda24576 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:42:45 +0000 Subject: [PATCH 091/146] Dashboard weather: heavy rain's drops splash in harder, no landing pause A drop sticking to the glass now lands squashed flat and wide for a frame or two, then wobbles back to round over 0.2 s (its water unchanged), and runs at once (the pause after its splash is gone). Its splash throws 14 to 20 droplets faster and further, falling a little as they fly, about a third of them short spray streaks, the burst lopsided in a direction of its own each landing; 4 to 8 stay on the glass, scattered further out, within the beads' own limit; all of it harder in heavier rain. Nothing drawn below a flood's surface; reduced motion: no squash. Also: two splash droplets snapped together (too small to run) dry on their own time as a droplet does instead of staying for a trail's whole life; with the humidity off, the beads' budget is what's there rounded up (a tiny one a quarter), so none dries away for the rounding. Tests: droplet counts, kept within room, lopsidedness, spray streaks, the squash and recoil frame by frame and back to round; droplets thrown up or to the sides hardly ever taken at once (those below may be: its drop runs down through them). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 127 +++++++++++++++++++++++++-------- tests/test_web_dashboard.py | 68 +++++++++++++----- tests/web_dashboard_browser.js | 32 +++++++-- 3 files changed, 176 insertions(+), 51 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 67cb09cd..eb89c32b 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -169,7 +169,8 @@ // (ids), left: the latest run off the bottom edge (ids), ranOff, shrunk (to nothing), faded (dried away): how many, largest: the // largest radius a merge has made, born: the latest condensed [{id, kind, r, fog: shown there, y: its middle, of the height}], // first: the first bead to show since the glass was fresh {after: s, cover, fog: the fog where it showed (not wiped), formed: -// fog() then} or null, landed: heavy rain's drops stuck, rainMost: the most of them at once, splashes: the latest {id, r, dots, stay: its droplets left on the glass}, +// fog() then} or null, landed: heavy rain's drops stuck, rainMost: the most of them at once, splashes: the latest {id, r, dots, stay: its droplets left on the glass, +// meant, cut, off, room, squash: how far it landed squashed, aim, lean: its burst's lopsidedness, thrown: its droplets [angle, px/s, streak (1), left (1)]}, // glass: {dry, trail, fog: each {px, s: run and taken there by beads of r 1.8-3.2, band: what they'd have run on fog (each at its // size then), gained, lost: water, moves: steps, all, norm, pace: // px run by any, what they'd have run on fog in that time, and at that glass's own mean speed}}, restarts: the biggest beads (STRETCH_R @@ -187,7 +188,9 @@ // the fog's canvas showing otherwise than they should where no trail is any more, beads: [{id, kind ("fog": condensed, "rain", "splash": a heavy-rain splash's droplet left on the glass), // x, x0 and y0: where it showed, y: its top, cy: its middle, r, vol: its water, w, laidW: its width as it last left its trail, // bottom: its sprite's lowest row + 1, glass: under it, v: px/s now, fading, alpha, drawn: [x, y, w, h, alpha] as drawn last, -// age: s shown, behind: its trail there behind it, trail: [x, y] a pixel of it, stretch: how far elongated now, 0-1}]}), joined: how many have run into a flood, joins: the latest of them +// age: s shown, behind: its trail there behind it, trail: [x, y] a pixel of it, stretch: how far elongated now, 0-1 (as drawn: none while squashed), impact: a rain +// bead's s since it landed (9 at most; null: none), squash: how far squashed now (above 0 wider, below taller), thrown: a splash's +// droplet's [dx, dy] from where its drop struck}]}), joined: how many have run into a flood, joins: the latest of them // (each {x, bottom: its sprite's lowest row + 1, surface: the flood's surface there then, level: the flood's level, trail: its trail's // last row + 1, or null: not running, wet: its trail there, in its middle)}, // flood (a flash flood: its depth, its surface, its frog and its waves, as flood.probe() gives them; the wind's water, took, rested, @@ -1254,9 +1257,10 @@ // for POP s). A bead not running (under 1 px/s) and a tiny one close below it the same; a running one takes in any tiny one // beside or above it as it passes. Only large ones (RUN_R and up: about sixteen tiny ones' water) run (as below); smaller ones stay // put (snapping as tiny ones do), a small one growing on the fog till it's large enough. Heavy rain (HEAVY_RAIN or more, the humidity high or not): now and - // then (LANDING a second, RAIN_MOST on the glass at most) a drop sticks, landing at once as a large bead (RAIN_R) with a splash (a - // ring of tiny droplets bursting out and fading in a few frames, a few of them (STAY) thrown out to varied distances and left there - // as tiny beads: from then on tiny beads like any other, the humidity on or not, drying away (DRYING) on glass with no fog shown + // then (LANDING a second, RAIN_MOST on the glass at most) a drop sticks, landing at once as a large bead (RAIN_R), hard: squashed + // flat and wide for a frame or two, wobbling back to round (SQUASH), with a splash (a ring of tiny droplets (THROWN), some of them + // short spray streaks, bursting out fast, lopsided (LEAN), falling a little and fading in a few frames, a few of them (STAY) thrown + // out to varied distances and left there as tiny beads; all of it harder in heavier rain: from then on tiny beads like any other, the humidity on or not, drying away (DRYING) on glass with no fog shown // if nothing takes them first); none in lighter rain, and none forming once the rain eases. // Every bead, condensed or rain, one set of rules (a merged one too): // The glass under it (the row just below it): FOG (fog shown there: FOG_AT or more), a TRAIL (a streak a bead has left: wiped @@ -1333,9 +1337,19 @@ const LANDING = 0.35; // ... about this many a second (one in 3 s) ... const RAIN_MOST = 14; // ... a dozen or so on the glass at most ... const RAIN_R = [3, 3.8]; // ... each landing this big (its radius) ... + const SQUASH = [0.5, 0.75]; // ... landing squashed flat and wide (this much wider at first, as much shorter: its water + // ... kept), held a frame or two (HOLD s), then wobbling back to round (a little taller and + const HOLD = 0.05; // ... narrower, then wider again, less and less) over SQUASH_S in all ... + const SQUASH_S = 0.2; const SPLASH_S = 0.25; // ... with a splash, bursting out and gone in this long ... - const STAY = [3, 6]; // ... a few of its droplets (this many) left on the glass as tiny beads, thrown out ... - const STAY_AT = [1.5, 9]; // ... this far past the drop's edge (px) ... + const THROWN = [14, 20]; // ... its droplets thrown out (this many) ... + const THROW = [24, 40]; // ... this fast (px/s, along the ring: squashed a little up and down), falling as they fly ... + const FALL = 80; // ... (px/s², falling) ... + const SPRAY = 0.25; // ... about a third of them short spray streaks, not dots (every sixth, and this many of the rest) ... + const LEAN = [0.25, 0.5]; // ... the burst lopsided, this much (faster that way, slower the other, more of them thrown + // ... that way) in a direction of its own each landing ... + const STAY = [4, 8]; // ... a few of its droplets (this many) left on the glass as tiny beads, thrown out ... + const STAY_AT = [2.5, 14]; // ... this far past the drop's edge (px) ... const STAY_S = 0.15; // ... there in this long (s), slowing to a stop, not fading with the rest ... const DRYING = [15, 40]; // ... and on glass with no fog shown (none taking them), drying away after this long (s) const PER_PX = 0.45; // beads at most, for each px of the window's width (light or heavy) @@ -1360,8 +1374,8 @@ // A bead bigger than the largest above (merged on and on: no size too big), drawn as wide as it is: the same glass, its rows // worked out (one for each width, kept) const grown = new Map(); - function rowsFor(w) { - const h = w + 1, cx = (w - 1) / 2, cy = h * 0.53, rx = w / 2, ry = h / 2 + 0.4; + function rowsFor(w, h = w + 1) { // (h: its own height, a squashed one's (see squashed())) + const cx = (w - 1) / 2, cy = h * 0.53, rx = w / 2, ry = h / 2 + 0.4; const inside = (x, y) => { if (x < 0 || x >= w || y < 0 || y >= h) return false; const squeeze = y < cy ? 0.82 + 0.18 * y / cy : 1; // (the top a little narrower) @@ -1667,19 +1681,31 @@ const b = numbered({id: ++made, kind: "rain", x, y, r, merged: 0, life: drop.between(...LIFE)}, landed); shows(b); b.shown = APPEAR; // (there at once) - b.pause = own(b, "pauses").between(0.45, 0.8); // (settling a moment after its splash before it runs: its droplets thrown clear first) + // (the harder the rain, the harder it hits (hard: 0 at HEAVY_RAIN, 1 at the heaviest): squashed flatter, more droplets thrown + // faster and further, more of them left) + const hard = clamp((rain.level - HEAVY_RAIN) / (1 - HEAVY_RAIN), 0, 1), more = (k, [lo, hi]) => lo + Math.floor(k * (hi - lo + 1) * (0.6 + 0.4 * hard)); + const squash = splash.between(...SQUASH) * (0.8 + 0.2 * hard); + if (!STILL) Object.assign(b, {impact: 0, squash, fresh: true}); // (squashed, from its first frame; reduced or low motion: never) all.push(b); - const cy = y + heightOf(r) / 2, n = 10 + Math.floor(splash() * 4); - const dots = Array.from({length: n}, (_, j) => ({a: (j + splash.between(-0.3, 0.3)) * 2 * Math.PI / n, v: splash.between(14, 24), s: splash() < 0.4 ? 1 : 0})); + // (its droplets: round it (evenly, a little jitter), each its speed; lopsided: bunched toward a direction of its own (lean, at + // aim), faster that way, slower the other; some spray streaks) + const cy = y + heightOf(r) / 2, n = more(splash(), THROWN), aim = splash.between(0, 2 * Math.PI), lean = splash.between(...LEAN); + const dots = Array.from({length: n}, (_, j) => { + let a = (j + splash.between(-0.3, 0.3)) * 2 * Math.PI / n; + a -= lean * 0.6 * Math.sin(a - aim); + return {a, v: splash.between(...THROW) * (0.8 + 0.2 * hard) * (1 + lean * Math.cos(a - aim)), s: splash() < 0.4 ? 1 : 0, streak: splash() < SPRAY || j % 6 === 0}; + }); // (a few of them, spread round it, thrown out to varied distances and left there: tiny beads once the splash is gone, as many - // as the beads' own most has room for, none in a flood; that far past its edge every way, the ring's flattening (0.8 down and - // up) made up for, so none thrown up or down lands on it, or close enough to snap back into it at once) - const stay = STAY[0] + Math.floor(splash() * (STAY[1] - STAY[0] + 1)), from = Math.floor(splash() * n); + // as the beads' own most has room for, none in a flood; that far past its edge every way (further the way it leans), the + // ring's flattening (0.8 down and up) made up for, so none thrown up or down lands on it, or close enough to snap back into it + // at once) + const stay = more(splash(), STAY), from = Math.floor(splash() * n); let kept = 0, cut = 0, off = 0; // (for the tests: those not left for the beads' most (cut), off the window or in a flood (off), let room = 0; // and how many the beads' most had room for as it landed (up to all meant)) for (const now = used(); room < stay && now + (room + 1) * TINY_COST <= most;) room++; for (let j = 0; j < stay; j++) { - const d = dots[(from + Math.round(j * n / stay)) % n], far = (r + 1 + splash.between(...STAY_AT)) / Math.hypot(Math.cos(d.a), 0.8 * Math.sin(d.a)); + const d = dots[(from + Math.round(j * n / stay)) % n], past = splash.between(0, STAY_AT[1] - STAY_AT[0]) * (1 + lean * Math.cos(d.a - aim)); + const far = (r + 1 + STAY_AT[0] + past) / Math.hypot(Math.cos(d.a), 0.8 * Math.sin(d.a)); const px = Math.round(x + Math.cos(d.a) * far), py = Math.round(cy + Math.sin(d.a) * far * 0.8); if (px < 1 || px > W - 2 || py < 1 || py > H - 2) { off++; continue; } if (used() + (kept + 1) * TINY_COST > most) { cut++; continue; } @@ -1689,9 +1715,29 @@ } splashes.push({x, y: cy, r, age: 0, dots, landed, own: splash}); seen.landed++; - seen.splashes.push({id: b.id, r, dots: n, stay: kept, meant: stay, cut, off, room}); + seen.splashes.push({id: b.id, r, dots: n, stay: kept, meant: stay, cut, off, room, squash, aim, lean, + thrown: dots.map((d) => [d.a, d.v, d.streak ? 1 : 0, d.stay ? 1 : 0])}); if (seen.splashes.length > 50) seen.splashes.shift(); } + // A rain bead just landed: how far squashed (0 round; above, wider and shorter; below, taller and narrower), held at its most a + // frame or two, then wobbling back to round, less and less + const squashOf = (b) => { + if (b.impact === undefined || b.impact >= SQUASH_S) return 0; + if (b.impact < HOLD) return b.squash; + const u = (b.impact - HOLD) / (SQUASH_S - HOLD); + const w = b.squash * (1 - u) ** 2 * Math.cos(3 * Math.PI * u); + return w < 0 ? 0.6 * w : w; // (its recoil, taller, less than its squash) + }; + // ... drawn so: as wide as that, as much shorter (its water kept), the same glass (quantized to whole px, each kept) + const flattened = new Map(); + function squashed(r, q) { + const base = sprite(r), w0 = base.width, h0 = base.height; + const w = Math.max(1, Math.round(w0 * (1 + q))), h = Math.max(2, Math.round(h0 / (1 + q))); + if (w === w0 && h === h0) return base; + const key = `${w}x${h}`; + if (!flattened.has(key)) flattened.set(key, mapped(rowsFor(w, h), GLASS)); + return flattened.get(key); + } const centre = (b) => b.y + heightOf(b.r) / 2; const touching = (a, b) => Math.abs(a.x - b.x) <= a.r + b.r + 0.5 && Math.abs(a.y - b.y) <= 2 * (a.r + b.r) + 2 && Math.hypot(a.x - b.x, centre(a) - centre(b)) <= a.r + b.r + 0.5; function merge(into, from) { // `from`'s water into `into` (never higher on the glass than it was) @@ -1703,6 +1749,8 @@ into.merged += 1 + from.merged; from.gone = true; into.still = into.still && into.r <= TINY; // (tiny no more: running, as its size has it) + if (from.impact < SQUASH_S && !(into.impact < SQUASH_S)) Object.assign(into, {impact: from.impact, squash: from.squash, fresh: from.fresh}); // (a drop + // landing on a bead: that one struck, squashed) seen.merges++; seen.largest = Math.max(seen.largest, into.r); seen.merged.push({vol: was, into: into.vol, r: radii, intoR: into.r}); @@ -1925,7 +1973,8 @@ const strength = () => (e.level > 0 || cover > 0 ? 0.85 : 0.3); // (heavy rain's beads alone: fainter in the cap's sum ... return { strength, // ... drawn as bright all the same, see draw()) - need: () => (e.level > 0 ? PER_PX * W : used()) + (heavy() ? RAIN_MOST : 0), // (as many at light humidity as heavy: its tiny ones pile up) + need: () => (e.level > 0 ? PER_PX * W : Math.ceil(used())) + (heavy() ? RAIN_MOST : 0), // (as many at light humidity as heavy: its tiny ones pile up; off, + // those there, whole: a tiny one a quarter, never rounded down to dry one) count: () => Math.round(used()), want(v) { // (on again after gone all the way: the glass fresh; reduced motion, off: gone at once) if ((v > 0 && !present() && e.amount <= 0) || (STILL && v <= 0)) clear(); @@ -2000,6 +2049,8 @@ for (const b of all) { if (b.gone || drowned(b)) continue; if (b.shown !== undefined) b.shown += dt; + if (b.impact !== undefined) { if (b.fresh) b.fresh = false; else b.impact = Math.min(9, b.impact + dt); } // (its landing's + // first frame drawn as it struck) if (b.pop > 0) b.pop -= dt; if (b.state === "rest") { // (showing once the fog has formed there, and shows: else not at all) const i = at(b.x, b.y + heightOf(b.r) / 2); @@ -2013,9 +2064,10 @@ } } else if (b.state === "on") { if (!b.still) move(b, dt); - else if (b.drying !== undefined && (b.g = glassAt(Math.round(b.x), Math.floor(b.y) + heightOf(b.r))) !== FOGGY && (b.drying -= dt) <= 0) { - dries(b); // (a splash's droplet left on clear glass, nothing taking it: drying away, slowly) - b.fadeFor = b.left = 1.5; + if (b.drying !== undefined && b.state === "on" && b.r < RUN_R && (b.still ? (b.g = glassAt(Math.round(b.x), Math.floor(b.y) + heightOf(b.r))) : b.g) !== FOGGY + && (b.drying -= dt) <= 0) { + dries(b); // (a splash's droplet left on clear glass, nothing taking it, or two of them snapped together, too small to + b.fadeFor = b.left = 1.5; // run: drying away, slowly) } } else if (b.state === "snap") pull(b, dt); @@ -2027,7 +2079,7 @@ for (const s of splashes) if (s.age >= SPLASH_S) for (const [j, d] of s.dots.entries()) if (d.stay) { // (its droplets left // behind: tiny beads now) const r = BORN[0] + 0.05, b = numbered({id: ++made, kind: "splash", x: d.px, y: d.py, r, k: 1, merged: 0, life: s.own.between(...LIFE), - still: true, drying: s.own.between(...DRYING)}, s.landed * 16 + j); + still: true, drying: s.own.between(...DRYING), thrown: [d.px - s.x, d.py - s.y]}, s.landed * 32 + j); shows(b); b.shown = APPEAR; all.push(b); @@ -2127,7 +2179,8 @@ laidW: b.laidW || null, bottom: top + h, glass: GLASSES[b.g], v: b.state === "on" ? b.v : 0, fading: b.state === "fade", alpha: (b.state === "fade" ? b.left / b.fadeFor : 1) * Math.min(1, b.shown / APPEAR), drawn: b.drawn || null, age: b.shown, behind: top < b.y0 + 4 || !!trail, trail: trail || null, tiny: !!b.still, snapping: b.state === "snap", - stretch: b.state === "on" ? stretchOf(b) : 0}; + stretch: b.state === "on" && !squashOf(b) ? stretchOf(b) : 0, impact: b.impact === undefined ? null : b.impact, + squash: b.state === "on" ? squashOf(b) : 0, thrown: b.thrown || null}; })}), draw(g, alpha) { const a0 = Math.min(1, alpha * 0.85 / strength()); // (heavy rain's beads alone: as bright as with the fog) @@ -2151,26 +2204,38 @@ g.drawImage(dots, 0, 0); for (const b of all) { if (b.state === "rest" || dotted.has(b)) continue; - const st = b.pop > 0 || b.state !== "on" ? 0 : stretchOf(b); - const pic = b.pop > 0 ? sprite(SIZES[Math.min(SIZES.length - 1, SIZES.findIndex((size) => size >= b.r - 0.01) + 1)]) : st > 0 ? elongated(b.r, st) : sprite(b.r), a = (b.state === "fade" ? b.left / b.fadeFor : 1) * Math.min(1, b.shown / APPEAR); - const left = Math.round(b.x) - (pic.width >> 1), top = (b.state === "fade" ? Math.round(b.y) : Math.floor(b.y)) - (pic.height - sprite(b.r).height); // (elongated: its lower edge where it is) + const q = b.state !== "on" ? 0 : squashOf(b), st = b.pop > 0 || b.state !== "on" || q ? 0 : stretchOf(b); // (squashed: not + // its pop as well) + const pic = q ? squashed(b.r, q) : b.pop > 0 ? sprite(SIZES[Math.min(SIZES.length - 1, SIZES.findIndex((size) => size >= b.r - 0.01) + 1)]) : st > 0 ? elongated(b.r, st) : sprite(b.r), a = (b.state === "fade" ? b.left / b.fadeFor : 1) * Math.min(1, b.shown / APPEAR); + const left = Math.round(b.x) - (pic.width >> 1), top = (b.state === "fade" ? Math.round(b.y) : Math.floor(b.y)) - (q ? Math.round((pic.height - sprite(b.r).height) / 2) : pic.height - sprite(b.r).height); // (elongated: its lower + // edge where it is; squashed: its middle) g.globalAlpha = a0 * a; g.drawImage(pic, left, top); b.drawn = [left, top, pic.width, pic.height, a0 * a]; } - for (const s of splashes) { // (a ring of droplets bursting out from where the drop struck, fading) - const k = s.age / SPLASH_S; + for (const s of splashes) { // (a ring of droplets bursting out from where the drop struck, falling a little as they fly, + // fading; a spray streak a px or two trailing behind its head; none in a flood's water) + const k = s.age / SPLASH_S, fall = 0.5 * FALL * s.age * s.age; + const put = (pic, x, y) => { if (y < flood.surface(x) - 1) g.drawImage(pic, x, y); }; g.globalAlpha = a0 * (1 - k); for (const d of s.dots) { if (d.stay) continue; - const far = s.r + 1 + d.v * s.age; - g.drawImage(DOTS[d.s], Math.round(s.x + Math.cos(d.a) * far), Math.round(s.y + Math.sin(d.a) * far * 0.8)); + const far = s.r + 1 + d.v * s.age, c = Math.cos(d.a), sn = Math.sin(d.a) * 0.8; + const px = Math.round(s.x + c * far), py = Math.round(s.y + sn * far + fall); + put(DOTS[d.s], px, py); + if (d.streak) { // (its tail: back along its flight, as long as a frame's flight or so, 1 to 3 px, fainter) + const back = Math.min(3, Math.max(1, d.v * 0.06 * (1 - k))); + for (let t = 1; t <= back; t++) { + const tx = Math.round(s.x + c * (far - t)), ty = Math.round(s.y + sn * (far - t) + fall); + if (tx !== px || ty !== py) put(DOTS[0], tx, ty); + } + } } g.globalAlpha = a0; // (those staying: thrown out, slowing to a stop where they'll stay, not fading) for (const d of s.dots) if (d.stay) { const k2 = Math.min(1, s.age / STAY_S), far = s.r + 1 + (d.stay - s.r - 1) * (1 - (1 - k2) ** 2); const px = k2 >= 1 ? d.px : Math.round(s.x + Math.cos(d.a) * far), py = k2 >= 1 ? d.py : Math.round(s.y + Math.sin(d.a) * far * 0.8); - g.drawImage(k2 >= 1 ? beads[0] : DOTS[0], px, py); + put(k2 >= 1 ? beads[0] : DOTS[0], px, py); } } }, diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 50c0d47c..1d7a0928 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -23,6 +23,7 @@ import html import io import json +import math import re import os import shutil @@ -1665,8 +1666,9 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert speed["fog"][3] == 0 and 0.2 < speed["fog"][4] < 0.6 and speed["fog"][-1] > 100, speed["fog"] assert after["dry"][0] == 0 and after["fog"][-1] > sizes[-1], after # heavy rain's beads: light rain none; heavy, a drop sticking every few s (one in 3 s), a dozen or so (14) on the glass at most, each landing at once - # (no fading in) as a large bead (r 3 or more) with a splash (a ring of 10 or more droplets, 3 to 6 of them left on the glass as - # tiny beads); on dry glass crawling (about 0.3 of its speed on fog, the same size), down a trail at TRACK or more (its own size's + # (no fading in) as a large bead (r 3 or more), hard: squashed flat and wide a frame or two, wobbling back to round, with a splash + # (a ring of 14 to 20 droplets thrown out fast, lopsided, some of them spray streaks, 4 to 8 of them left on the glass as tiny + # beads); on dry glass crawling (about 0.3 of its speed on fog, the same size), down a trail at TRACK or more (its own size's # speed there), shrinking only (its water left behind), never growing; none vanishing; their wet streaks on the # clear glass drying over 3 to 10 minutes, each its own: thin streaks (a third of the bead's width or less: a px or two), faint # (a greyish film, grime along an edge, a glint, a tiny droplet), uneven along their length (thicker and thinner, now and then @@ -1679,34 +1681,66 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert 12 <= heavy_rain["landed"] <= 42 and 6 <= heavy_rain["rainMost"] <= 14 and heavy_rain["popped"] == 0, heavy_rain # (each landing seen: shown at once, or, landing on a bead already there, merged into it at once (in its absorbed)) assert len(sticking["stuck"]) == heavy_rain["landed"], sticking["stuck"] - assert all(s["r"] >= 3 and (s["alpha"] == 1 or s.get("merged")) and s["dots"] >= 10 and s["phase"] == "heavy" for s in sticking["stuck"]), sticking["stuck"] - # (3 to 6 of its droplets meant to stay, all of them left but those thrown off the window or into a flood (off), as many as the + assert all(s["r"] >= 3 and (s["alpha"] == 1 or s.get("merged")) and 14 <= s["dots"] <= 20 and len(s["thrown"]) == s["dots"] and s["phase"] == "heavy" + for s in sticking["stuck"]), sticking["stuck"] + assert len({s["dots"] for s in sticking["stuck"]}) >= 4, sticking["stuck"] + # (the burst lopsided: its droplets' mean throw a fifth or so of their speed or more one way, a direction of its own each landing; + # some of them (a third or so all told, at least two a splash) spray streaks; squashed 0.5 to 0.75 wider at first) + for s in sticking["stuck"]: + vx, vy = (sum(v * f(a) for a, v, *_ in s["thrown"]) for f in (math.cos, math.sin)) + s["lean"], s["aim"] = math.hypot(vx, vy) / sum(v for _, v, *_ in s["thrown"]), math.atan2(vy, vx) + assert all(s["lean"] >= 0.12 for s in sticking["stuck"]), [s["lean"] for s in sticking["stuck"]] + assert len({int((s["aim"] + math.pi) // (math.pi / 2)) for s in sticking["stuck"]}) == 4, [s["aim"] for s in sticking["stuck"]] + sprays = [sum(t[2] for t in s["thrown"]) for s in sticking["stuck"]] + assert min(sprays) >= 2 and 0.2 <= sum(sprays) / sum(s["dots"] for s in sticking["stuck"]) <= 0.5, sprays + assert all(0.5 <= s["squash"] <= 0.75 for s in sticking["stuck"]), sticking["stuck"] + # (followed frame by frame (a 30th of a second each) as they land: as wide as that, as much shorter, held a frame or two; then + # within 0.2 s wobbling back (taller and narrower a moment), round again from there on (but elongated as it sets off, as below); its water no different for it (but what + # it leaves on dry glass as it runs, or a tiny bead it sweeps up)) + landings = sticking["landings"] + assert len(landings) == 4 and all(len(l["frames"]) >= 10 for l in landings), landings + for l in landings: + f = l["frames"] + held = [x for x in f if x["impact"] < 0.05] + assert f[0]["impact"] == 0 and 1 <= len(held) <= 2 and all((x["w"], x["h"]) == (f[0]["w"], f[0]["h"]) for x in held), l + assert f[0]["w"] >= 1.4 * f[0]["rw"] and f[0]["h"] <= 0.7 * f[0]["rh"], l + assert any(x["w"] < x["rw"] and x["h"] > x["rh"] for x in f if 0.05 <= x["impact"] < 0.2), l + assert all((x["w"], x["h"]) == (x["rw"], x["rh"]) for x in f if x["impact"] >= 0.2 - 1e-9 and not x["stretch"]), l # (round, but as + # it sets off, elongating) + assert all(0.75 <= x["w"] * x["h"] / (x["rw"] * x["rh"]) <= 1.3 for x in f), l + assert all(abs(x["vol"] - f[0]["vol"]) <= 0.03 * f[0]["vol"] for x in f if x["impact"] < 0.2), l + # (4 to 8 of its droplets meant to stay, all of them left but those thrown off the window or into a flood (off), as many as the # beads' own most had room for as it landed (room): none cut while there was room, every one past it cut) - assert all(3 <= s["meant"] <= 6 and s["stay"] + s["cut"] + s["off"] == s["meant"] and s["stay"] == min(s["meant"] - s["off"], s["room"]) + assert all(4 <= s["meant"] <= 8 and s["stay"] + s["cut"] + s["off"] == s["meant"] and s["stay"] == min(s["meant"] - s["off"], s["room"]) for s in sticking["stuck"]), sticking["stuck"] - # (... where there was room, 3 or more left, as ever, but one now and then thrown off the window by a drop landing near its edge) + # (... where there was room, 4 or more left, as ever, but one now and then thrown off the window by a drop landing near its edge + # (scattered further out, more of the landings lose one so, but hardly any of their droplets)) roomy = [s for s in sticking["stuck"] if s["room"] >= s["meant"]] - assert roomy and all(s["stay"] >= 3 for s in roomy if not s["off"]) and sum(s["off"] > 0 for s in roomy) <= 0.2 * len(roomy), sticking["stuck"] + assert roomy and all(s["stay"] >= 4 for s in roomy if not s["off"]) and sum(s["off"] for s in roomy) <= 0.1 * sum(s["meant"] for s in roomy), sticking["stuck"] assert len({s["meant"] for s in sticking["stuck"]}) >= 3, sticking["stuck"] dry, trail = heavy_rain["glass"]["dry"], heavy_rain["glass"]["trail"] assert dry["lost"] > 0 and dry["gained"] == 0 and 0.2 < dry["all"] / dry["norm"] < 0.4, dry assert trail["moves"] > 100 and all(0.75 < o["all"] / o["pace"] < 1.3 for o in (dry, trail)), heavy_rain["glass"] assert 0.75 * TRACK < trail["px"] / trail["s"] < 1.3 * 31, trail # (r 1.8-3.2 down a trail: about TRACK, not their size's) # (the splash's droplets left on the glass: tiny beads (r 0.55) like any other, from the splash's end on, as many as were left; - # never moving but to snap (merged into a neighbour, or swept up by a runner passing); on the clear glass, nothing taking them, - # drying away after 15 to 40 s each) + # never moving but to snap (merged into a neighbour, or swept up by a runner passing: as many as eight thrown out, now and then + # three of them together at most); on the clear glass, nothing taking them, drying away after 15 to 40 s each) left_on = sticking["watched"]["splashes"] - assert sum(s["stay"] for s in sticking["stuck"]) - 6 <= len(left_on) <= sum(s["stay"] for s in sticking["stuck"]), (len(left_on), sticking["stuck"]) - assert all(d["moved"] == 0 and d["r"] < 0.75 for d in left_on) and sum(d["tiny"] for d in left_on) >= 0.9 * len(left_on), left_on + assert sum(s["stay"] for s in sticking["stuck"]) - 8 <= len(left_on) <= sum(s["stay"] for s in sticking["stuck"]), (len(left_on), sticking["stuck"]) + assert all(d["moved"] == 0 and d["r"] < 0.85 for d in left_on) and sum(d["tiny"] for d in left_on) >= 0.9 * len(left_on), left_on ends = {end: [d for d in left_on if d["end"] == end] for end in ("faded", "taken", "on", "other")} assert len(ends["faded"]) >= 10 and len(ends["taken"]) >= 10, {end: len(d) for end, d in ends.items()} assert all(15 <= d["fadedAt"] <= 41 and d["glass"] != "fog" for d in ends["faded"]), ends["faded"] assert len({round(d["fadedAt"]) for d in ends["faded"]}) >= 8, ends["faded"] # (each its own time) - # (thrown past the drop's edge every way, up and down too: hardly any taken back the moment it's left (by a runner passing); - # none landing on its drop, or close enough to snap back into it at once (they did, about one in ten)) + # (thrown past the drop's edge every way, up and down too: none landing on its drop, or close enough to snap back into it at + # once (they did, about one in ten); those thrown up or to the sides (no further down than half as far across) hardly ever + # taken back the moment they're left (by a runner passing); those below it may be: its drop, running at once, runs down through + # them) # (each left in the heavy rain, as followed here and on, below, as its biggest beads set off again: every one once) every = list({d["id"]: d for d in left_on + sticking["stretching"]["splashes"]}.values()) - assert len(every) >= 120 and sum(d["end"] == "taken" and d["aged"] <= 0.45 for d in every) <= 0.05 * len(every), every + across = [d for d in every if d["thrown"][1] <= abs(d["thrown"][0]) / 2] + assert len(every) >= 120 and len(across) >= 60, every + assert sum(d["end"] == "taken" and d["aged"] <= 0.45 for d in across) <= 0.05 * len(across), across # (none outstaying its drying (shown 0.4 s in, 40 s at most, half a second drying away): gone, a merged one shrunk away) assert all(d["aged"] <= 42 for d in ends["on"] + ends["other"]), left_on # (the biggest (r 2.5 and up: here most) setting off again after a pause (heavy rain's own time, 30 s): about one restart in three @@ -1756,11 +1790,13 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert gone["landed"] == eased["landed"] and gone["beads"] == 0 and gone["popped"] == 0, (eased, gone) # (each run off or shrunk to nothing, or merged into one that was: none dried away otherwise but the splashes' droplets, each # after 15 to 40 s (some within a frame there: gone between two looks), unless swept up first by a runner passing (taken), as - # ever) + # ever; two snapped together (too small to run) the same, or shrunk away first on dry glass, never faded) assert gone["ranOff"] + gone["shrunk"] > eased["ranOff"] + eased["shrunk"] and eased["beads"] > 0, (eased, gone) dried = sticking["afterWatched"]["splashes"] assert dried and all(d["end"] in ("faded", "other", "taken") and d["aged"] <= 42 and d["glass"] != "fog" for d in dried), dried - assert gone["faded"] - eased["faded"] == sum(d["end"] != "taken" for d in dried) > 0, (eased, gone, dried) + shrunk = [d for d in dried if d["end"] == "other" and d["fadedAt"] is None and not d["tiny"]] + assert len(shrunk) <= gone["shrunk"] - eased["shrunk"], shrunk + assert gone["faded"] - eased["faded"] == sum(d["end"] != "taken" for d in dried) - len(shrunk) > 0, (eased, gone, dried) assert all(15 <= d["fadedAt"] <= 41 for d in dried if d["fadedAt"] is not None), dried # ... their streaks, the rain still on, drying on their own time: there still 6 s after the last bead had gone easing = sticking["easing"] diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 72ae38d6..a325dfb0 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1508,7 +1508,7 @@ const trailLook = (h, b) => { // with none set going while it was 2.5 or more; // splashes: each heavy-rain splash's droplet left on the glass {r: its radius at most, tiny: tiny always while it was one, moved: // frames it moved (not snapping), glass: the glass under it as it last sat (before fading), fogged: s on fog, aged: s shown in -// all, fadedAt: its age as it began drying away (null: never), end: "faded" (dried away), "taken" (merged into another: snapped +// all, fadedAt: its age as it began drying away (null: never), thrown: [dx, dy] from where its drop struck, end: "faded" (dried away), "taken" (merged into another: snapped // or swept up by a runner), "on" (still there at the end) or "other"} const beadWatch = () => { const stretching = new Map(), stretches = [], splashes = new Map(), last = new Map(); @@ -1534,7 +1534,7 @@ const beadWatch = () => { if (b.kind === "splash") { let d = splashes.get(b.id); const before = last.get(b.id); - if (!d) { d = { id: b.id, r: b.r, tiny: true, moved: 0, glass: null, fogged: 0, aged: 0, fadedAt: null, end: "other" }; splashes.set(b.id, d); } + if (!d) { d = { id: b.id, r: b.r, tiny: true, moved: 0, glass: null, fogged: 0, aged: 0, fadedAt: null, end: "other", thrown: b.thrown }; splashes.set(b.id, d); } d.r = Math.max(d.r, b.r); if (!b.tiny) d.tiny = false; if (before && b.tiny && !b.snapping && !before.snapping && (b.x !== before.x || b.y !== before.y)) d.moved++; @@ -1783,12 +1783,13 @@ const rainBeads = (page, light, heavy, after, scale, from = "light") => page.eva seenIds.add(b.id); const s = h.splashes.find((s) => s.id === b.id); out.stuck.push({ r: s ? s.r : 0, alpha: b.alpha, dots: s ? s.dots : 0, stay: s ? s.stay : 0, meant: s ? s.meant : 0, cut: s ? s.cut : 0, - off: s ? s.off : 0, room: s ? s.room : 0, phase }); // (r: as it landed) + off: s ? s.off : 0, room: s ? s.room : 0, squash: s ? s.squash : 0, thrown: s ? s.thrown : [], phase }); // (r: as it landed) } } for (const s of h.splashes) if (!seenIds.has(s.id) && absorbed.has(s.id)) { // (one landing on a bead there, merged at once: never seenIds.add(s.id); // shown on its own) - out.stuck.push({ r: s.r, alpha: null, dots: s.dots, stay: s.stay, meant: s.meant, cut: s.cut, off: s.off, room: s.room, phase, merged: true }); + out.stuck.push({ r: s.r, alpha: null, dots: s.dots, stay: s.stay, meant: s.meant, cut: s.cut, off: s.off, room: s.room, squash: s.squash, + thrown: s.thrown, phase, merged: true }); } n = state.frames - start; if (phase === "light" && n >= light) { @@ -1814,6 +1815,27 @@ const rainBeads = (page, light, heavy, after, scale, from = "light") => page.eva }; __next(step); }), [light, heavy, after, scale, from]); +// Heavy rain's drops landing, each followed frame by frame (the weather's time a 30th of a second a frame) from the frame it landed +// in till 0.35 s on: `landings` of them (up to `most` frames): each {id, frames: [{impact: s since it landed, squash, w, h: as drawn, +// rw, rh: its round sprite's, r, vol, stretch: elongated as it sets off (see beadWatch)}]} (till it merges or goes) +const landingsWatched = (page, landings, most) => page.evaluate(([landings, most]) => new Promise((resolve) => { + const followed = new Map(), done = []; + let n = 0; + Sky.timeScale(1 / 3); + const step = () => { + const h = Sky.state().humidity; + for (const b of h.beads) if (b.kind === "rain" && b.impact !== null && b.impact <= 0.35 && b.drawn) { + if (!followed.has(b.id)) { if (b.impact > 0 || followed.size + done.length >= landings) continue; followed.set(b.id, { id: b.id, frames: [] }); } + followed.get(b.id).frames.push({ impact: b.impact, squash: b.squash, w: b.drawn[2], h: b.drawn[3], rw: b.w, rh: b.bottom - Math.floor(b.y), r: b.r, vol: b.vol, + stretch: b.stretch }); + } + for (const [id, f] of followed) if (f.frames.at(-1).impact >= 0.33 || !h.beads.some((b) => b.id === id)) { done.push(f); followed.delete(id); } + if ((done.length < landings || followed.size) && ++n < most) return __next(step); + Sky.timeScale(1); + resolve(done); + }; + __next(step); +}), [landings, most]); // "stop animation" (an effect on: the link shows; it ends the test links' effects; the link gone), then `detail` on (as a test link // clicked after it: the animations on again), all at once (no frame between): the loop, the link and the glass (humidity's marks) as // stopped, and once started again, the glass, the frost and the rain's drops then @@ -2579,6 +2601,8 @@ const WEATHER = { await p.page.evaluate(() => Sky.timeScale(1)); // (heavy still, its weather's own time (a frame 0.1 s: a stretch over a few), 30 s: the biggest setting off again after pauses) seen.stretching = await beadsWatched(p.page, 300); + // (a few drops landing, frame by frame: squashed and back to round) + seen.landings = await landingsWatched(p.page, 4, 900); let looks; // (the rain eased: watched till the last bead has gone, up to 1100 frames (11 minutes of its weather's time): one shrunk on // dry glass under the run size and sitting on a wet trail keeps its size till that trail dries, 3 to 10 minutes) From 197e053dc4ff546452bf96a7240cadfc75de5b07 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:51:23 +0000 Subject: [PATCH 092/146] Web dashboard: a modern compass the size of the dials, today's wind rose under its needle The Wind direction tile's compass now uses a dial's centre and ring (DIAL), so it lines up with its neighbours in the grid and when zoomed. It is flat like the dials: one thin ring, fine ticks every 10 degrees and longer ones every 45, and only N, E, S and W, with N in an accent colour. The needle is a slim blade with a sharp head, a short dim tapered tail and a small hub. Layers from the bottom: today's wind rose, the reading inside the ring below the hub, then the face, the needle and the hub. /dashboard/data gives the compass tile a `rose`: today's share of the wind's direction from each of the 16 points (the station's day). It is counted by directions_on from the file's 5-minute readings and the minutes they don't cover, leaving out calm readings, read at most once a minute, and [] with no data, in which case nothing is drawn. The Status PNG is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/ecowitt/reads.py | 26 +++++- lib/gauge_look.py | 3 +- lib/web_dashboard.html | 101 +++++++++++++--------- lib/web_dashboard.py | 37 +++++++- tests/test_web_dashboard.py | 153 ++++++++++++++++++++++++++++----- tests/web_dashboard_browser.js | 29 +++++-- 6 files changed, 273 insertions(+), 76 deletions(-) diff --git a/lib/ecowitt/reads.py b/lib/ecowitt/reads.py index 2656b046..b4dab814 100644 --- a/lib/ecowitt/reads.py +++ b/lib/ecowitt/reads.py @@ -8,6 +8,7 @@ catalogue's decimals: a 5-minute mean of the bot's live readings is drawn as the station would have sent it). """ +import bisect from dataclasses import dataclass, field from ..lines import Plotted, Sample @@ -15,6 +16,7 @@ from ..storage.read import Reader from ..storage.schema import q, some_value from .api import cycle_seconds +from .direction import sector from .period import Period, period_on type Store = dict[str, dict] # "group.field" -> {"unit": str, "pts": {epoch: Sample}} @@ -84,6 +86,28 @@ def highest_on(r: Reader, mac: str, wheres: list[tuple[str, str]], start: int, e return out +def directions_on(r: Reader, mac: str, start: int, end: int) -> list[int]: + """How long the wind blew from each of the 16 compass points (direction.sector: N first, clockwise) from start to end, in minutes, of + the wind's 5-minute readings (5 each) and its minutes (1 each) where no 5-minute reading covers them (300 s either side), in one query; + a calm reading (its speed 0) left out, one with no speed counted. All 0 with none (the web page's wind rose: today's).""" + counts = [0] * 16 + sensor = r.sensor(mac, "wind") + if sensor is None or sensor.kind != "wind": + return counts + got = r.db.execute(f"SELECT res, ts, {q('wind_direction')}, {q('wind_speed')} FROM wind WHERE sensor = ? AND res IN ('1min', '5min') " + f"AND ts BETWEEN ? AND ? AND {q('wind_direction')} IS NOT NULL ORDER BY ts", (sensor.id, start, end)).fetchall() + fives = [ts for res, ts, _, _ in got if res == "5min"] + for res, ts, degrees, speed in got: + if speed is not None and speed <= 0: + continue + if res == "1min": + i = bisect.bisect_left(fives, ts - 299) + if i < len(fives) and fives[i] < ts + 300: + continue + counts[sector(degrees)] += 5 if res == "5min" else 1 + return counts + + def newest_minute_on(r: Reader, mac: str) -> int | None: """The time of the newest minute held of the station (where the next pull of Home Assistant's starts), None for none.""" found = [r.db.execute(f"SELECT MAX(ts) FROM {s.kind} WHERE sensor = ? AND res = '1min'", (s.id,)).fetchone()[0] @@ -180,5 +204,5 @@ def history_on(r: Reader, mac: str, groups: list[str], plan: list[tuple[str, int return held -__all__ = ["Held", "Store", "buckets_on", "counts_on", "first_minute_on", "history_on", "newest_minute_on", "readings_on", "rows_on", +__all__ = ["Held", "Store", "buckets_on", "counts_on", "directions_on", "first_minute_on", "history_on", "newest_minute_on", "readings_on", "rows_on", "slot_values_on"] diff --git a/lib/gauge_look.py b/lib/gauge_look.py index a4d49b70..0b14c620 100644 --- a/lib/gauge_look.py +++ b/lib/gauge_look.py @@ -25,6 +25,7 @@ COMPASS = (240, 188, 130) # the wind's direction, a compass: its centre and outline's radius (above the table's place: it has none) COMPASS_LABEL_Y = 346 # ... its reading ("99° E") under it COMPASS_BAND = "#262E34" # ... its ring, under the ticks and the letters N, E, S and W +COMPASS_NORTH = "#E5534B" # the web page's compass: its N, a small accent WATER = "#4FB3F6" # the rain beaker's water NEEDLE = "#3E86C0" CELL_W, CELL_H, MARGIN = 480, 575, 20 @@ -69,7 +70,7 @@ def look() -> dict: "needle": NEEDLE, "hour_hand": HOUR_HAND, "hour_hand_width": HOUR_HAND_WIDTH, "tube_half": TUBE_HALF, "bulb_radius": BULB_RADIUS, "mercury_gap": MERCURY_GAP, "bar_width": BAR_WIDTH, "bar_gap": BAR_GAP, "ring_outer": RING_OUTER, "band_width": BAND_WIDTH, "label_radius": LABEL_RADIUS, "cell": [CELL_W, CELL_H], "compass": list(COMPASS), - "compass_label_y": COMPASS_LABEL_Y, "compass_band": COMPASS_BAND, "points": list(POINTS), + "compass_label_y": COMPASS_LABEL_Y, "compass_band": COMPASS_BAND, "compass_north": COMPASS_NORTH, "points": list(POINTS), "fade": FADE, "sweep": SWEEP, "start": START, "rows": list(ROWS)} diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index eb89c32b..3e07e37b 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -3485,9 +3485,10 @@ }; } + const DIAL = [240, 203, 138]; // a dial's centre and its ring's radius (the compass's too: the same size, lined up) function dial(svg, tile, ink) { - const cx = 240, cy = 203, angle = (v) => L.start - L.sweep * share(tile, v); - el("circle", {cx, cy, r: 138, fill: "none", stroke: ink(L.soft), "stroke-width": lw(3)}, svg); + const [cx, cy] = DIAL, angle = (v) => L.start - L.sweep * share(tile, v); + el("circle", {cx, cy, r: DIAL[2], fill: "none", stroke: ink(L.soft), "stroke-width": lw(3)}, svg); const n = tile.colours.length, step = L.sweep / n, outer = L.ring_outer, inner = L.ring_outer - L.band_width; tile.colours.forEach((colour, i) => { const a0 = L.start - i * step - 0.8, a1 = a0 - step + 1.6; @@ -3528,48 +3529,60 @@ return at; } - // The wind's direction, a compass (as the Status picture's: lib/gauges.py _compass): a ring with fine ticks and the points named, the - // needle an arrow (the needles' colour) pointing where the wind comes from, in degrees clockwise from north, its tail a short dim - // stub; the reading under it - // ("99° E": the compass point the service gives, or, while the needle swings to it, the point it is passing). No table. + // The wind's direction, a compass, flat like the dials and the same size (DIAL: its ring where theirs is, so it lines up with its + // neighbours, grid or zoomed). Layers, bottom to top: today's wind rose (rose: 16 soft petals in the needles' colour, each as long as + // its compass point's share of today's readings, the longest ROSE_REACH of the radius; none with no data), the reading inside the + // ring, below the hub ("99° E": the compass point the service gives, or, while the needle swings to it, the point it is passing), then + // the face (one thin ring, fine ticks every 10 degrees and longer ones every 45, N, E, S and W, N in an accent colour) and the needle + // (pointing where the wind comes from, in degrees clockwise from north: a slim blade with a sharp head in the needles' colour and a + // short, dim, tapered tail) on a small hub. No table. + const ROSE_REACH = 0.8, ROSE_HALF = 9; // the longest petal's reach (of the radius) and each petal's half-width (degrees) const pointOf = (deg) => L.points[Math.floor(((deg % 360) + 360 + 11.25) / 22.5) % 16]; // (direction.py sector()) - // The compass's arrow pointing north from (cx, cy), its tip `reach` out: a broad barbed head on a shaft down to the hub ([x, y], ...; - // as lib/gauges.py _arrow) - const arrow = (cx, cy, reach) => [[0, reach], [17, reach - 30], [5.5, reach - 23], [5.5, 0], [-5.5, 0], [-5.5, reach - 23], [-17, reach - 30]] - .map(([x, y]) => [cx + x, cy - y]); + // The needle pointing north from (cx, cy), its tip `reach` out ([x, y], ...): the head a slim blade to a sharp tip, widest at the hub; + // the tail a short taper behind it + const blade = (cx, cy, reach) => [[0, reach], [5, 0], [-5, 0]].map(([x, y]) => [cx + x, cy - y]); + const stub = (cx, cy, reach) => [[3.5, 0], [0, -reach * 0.2], [-3.5, 0]].map(([x, y]) => [cx + x, cy - y]); + const points = (pts) => pts.map((p) => p.map((n) => n.toFixed(2)).join(",")).join(" "); function compass(svg, tile, ink) { - // (its ring a little smaller than the Status picture's and its reading a little smaller, not dropped: room above the table's place) - const [cx, cy] = L.compass, r = L.compass[2] - 10, outer = r - 8, inner = outer - L.band_width, mid = (outer + inner) / 2, reach = inner - 8; - el("circle", {cx, cy, r, fill: "none", stroke: ink(L.soft), "stroke-width": lw(3)}, svg); - el("circle", {cx, cy, r: mid, fill: "none", stroke: ink(L.compass_band), "stroke-width": L.band_width}, svg); - let ticks = ""; // (fine ticks every 10 degrees, longer every 30; none where a point is named: one path) - for (let b = 0; b < 360; b += 10) { - if (Math.min(b % 45, 45 - b % 45) <= 5 || b % 30 === 0) continue; - const [x0, y0] = polar(cx, cy, outer - 4, 90 - b), [x1, y1] = polar(cx, cy, outer - 7, 90 - b); - ticks += `M${x0.toFixed(1)},${y0.toFixed(1)}L${x1.toFixed(1)},${y1.toFixed(1)}`; - } - el("path", {d: ticks, stroke: ink(L.soft), "stroke-width": lw(1.5), "stroke-linecap": "round"}, svg); - ticks = ""; - for (let b = 30; b < 360; b += 30) { - if (Math.min(b % 45, 45 - b % 45) <= 5) continue; - const [x0, y0] = polar(cx, cy, outer - 4, 90 - b), [x1, y1] = polar(cx, cy, outer - 12, 90 - b); - ticks += `M${x0.toFixed(1)},${y0.toFixed(1)}L${x1.toFixed(1)},${y1.toFixed(1)}`; - } - el("path", {d: ticks, stroke: ink(L.soft), "stroke-width": lw(2.2), "stroke-linecap": "round"}, svg); - L.points.filter((_, i) => i % 2 === 0).forEach((name, i) => { // N, NE, E...: the cardinal points large, the others small - const [x, y] = polar(cx, cy, mid, 90 - 45 * i); - text(svg, x, y, name, i % 2 ? 13 : 20, ink(i % 2 ? L.soft : L.ink), "middle", i % 2 ? "normal" : "bold").classList.add("point"); + const [cx, cy, r] = DIAL, reach = r - 22; + const rose = el("g", {class: "rose", "pointer-events": "none"}, svg); + const label = text(svg, cx, cy + 66, "", 34, ink(L.ink)); + label.classList.add("reading"); + const face = el("g", {class: "face"}, svg); + el("circle", {cx, cy, r, fill: "none", stroke: ink(L.soft), "stroke-width": lw(3), class: "ring"}, face); + const tick = (b, length) => { + const [x0, y0] = polar(cx, cy, r - 5, 90 - b), [x1, y1] = polar(cx, cy, r - 5 - length, 90 - b); + return `M${x0.toFixed(1)},${y0.toFixed(1)}L${x1.toFixed(1)},${y1.toFixed(1)}`; + }; + let fine = "", long = ""; // (fine ticks every 10 degrees, longer ones every 45: one path each) + for (let b = 0; b < 360; b += 10) if (b % 45) fine += tick(b, 6); + for (let b = 0; b < 360; b += 45) long += tick(b, 12); + el("path", {d: fine, stroke: ink(L.soft), "stroke-width": lw(1), "stroke-opacity": 0.7, "stroke-linecap": "round", class: "ticks"}, face); + el("path", {d: long, stroke: ink(L.soft), "stroke-width": lw(1.8), "stroke-linecap": "round", class: "ticks long"}, face); + ["N", "E", "S", "W"].forEach((name, i) => { + const [x, y] = polar(cx, cy, r - 34, 90 - 90 * i); + text(face, x, y, name, 22, ink(i ? L.soft : L.compass_north), "middle", "600").classList.add("point"); }); - // The needle (drawn pointing north, turned to the reading): an arrow, its bold head and shaft in the needles' colour pointing where - // the wind comes from, and behind the hub only a short, thin, dim tail: one end to read, never two alike const needle = el("g", {class: "needle"}, svg); - el("path", {d: `M${cx},${cy} L${cx},${cy + reach * 0.3}`, stroke: ink(L.soft), "stroke-width": lw(2), "stroke-opacity": 0.5, - "stroke-linecap": "round", class: "tail"}, needle); - el("polygon", {points: arrow(cx, cy, reach).map((p) => p.join(",")).join(" "), fill: ink(L.needle), "stroke-linejoin": "round", - stroke: ink(L.needle), "stroke-width": 1.5, class: "head"}, needle); - el("circle", {cx, cy, r: 11, fill: L.bg, stroke: ink(L.soft), "stroke-width": lw(2.5)}, svg); - const label = text(svg, cx, L.compass_label_y + 2 - DROP, "", 36, ink(L.ink)); - label.classList.add("reading"); + el("polygon", {points: points(stub(cx, cy, reach)), fill: ink(L.soft), "fill-opacity": 0.45, class: "tail"}, needle); + el("polygon", {points: points(blade(cx, cy, reach)), fill: ink(L.needle), stroke: L.bg, "stroke-width": 1.2, "paint-order": "stroke", + "stroke-linejoin": "miter", class: "head"}, needle); + el("circle", {cx, cy, r: 6.5, fill: L.bg, stroke: ink(L.needle), "stroke-width": 2.5, class: "hub"}, svg); + // the rose: a petal per compass point with any share, a slim wedge from the centre to its share of the longest's reach + const petals = (shares) => { + rose.replaceChildren(); + const most = Math.max(0, ...(shares || [])); + if (!(most > 0)) return; + shares.forEach((v, i) => { + if (!(v > 0)) return; + const out = r * ROSE_REACH * v / most, b = 22.5 * i; + const [x0, y0] = polar(cx, cy, out, 90 - b + ROSE_HALF), [x1, y1] = polar(cx, cy, out, 90 - b - ROSE_HALF); + el("path", {d: `M${cx},${cy} L${x0.toFixed(2)},${y0.toFixed(2)} A${out.toFixed(2)},${out.toFixed(2)} 0 0 1 ${x1.toFixed(2)},${y1.toFixed(2)} Z`, + fill: ink(L.needle), "fill-opacity": 0.32, stroke: ink(L.needle), "stroke-opacity": 0.55, "stroke-width": 1, + "stroke-linejoin": "round", class: "petal", "data-point": L.points[i], "data-share": v}, rose); + }); + }; + petals(tile.rose); let now = tile; // (the tile as last given: its reading and the service's compass point) const at = (v) => { const deg = ((v % 360) + 360) % 360; @@ -3577,7 +3590,13 @@ const whole = Math.round(deg) % 360, still = now.value !== null && Math.abs(deg - now.value) < 1e-6; label.textContent = now.value === null ? "–" : `${whole}° ${still && now.band ? now.band : pointOf(deg)}`; }; - at.band = (t) => { now = t; }; + let drawnRose = JSON.stringify(tile.rose || []); + at.band = (t) => { // (the tile as given again: its reading's compass point, and today's rose, redrawn if it changed) + now = t; + const next = JSON.stringify(t.rose || []); + if (next !== drawnRose) petals(t.rose); + drawnRose = next; + }; at.toward = (from, to) => from + ((((to - from) % 360) + 540) % 360) - 180; // (the short way round: 350° to 10° through north) return at; } diff --git a/lib/web_dashboard.py b/lib/web_dashboard.py index fe473bb4..82bf9a35 100644 --- a/lib/web_dashboard.py +++ b/lib/web_dashboard.py @@ -19,7 +19,9 @@ configured is not there), for the strip's stalled device greyed out, the look, and the station's rain rate now (`rain_rate`, mm/h: its rain gauge's, or its piezo gauge's where that's the one reporting, which no tile shows; null with neither), for the page's rain behind the tiles; the past hour's highest of the dials with a thin red hand (`hour_highs`, by - title: Wind's gust, Rain rate's, Solar radiation's, UV index's: hour_highs()), and the gust now (`gust`, km/h: over 99, a new + title: Wind's gust, Rain rate's, Solar radiation's, UV index's: hour_highs()), the Wind direction tile's `rose` (today's + share of the wind's direction from each of the 16 compass points, N first, clockwise, from the file's readings, calm ones left out; + [] with none: rose()), and the gust now (`gust`, km/h: over 99, a new reading sends a cow, a barn or a chicken across behind the tiles); - GET /dashboard/events: Server-Sent Events, a `readings` event whenever the gauges' readings in the station's kept live reading or the air sensor's latest change, told by the server's own change detection for ecobot://now/weather and ecobot://now/air @@ -58,8 +60,9 @@ from .airgradient.metrics import value_of from .service.common import iso from .ecowitt.dashboard import GAUGES, GUST, live_value -from .ecowitt.reads import highest_on +from .ecowitt.reads import directions_on, highest_on from .gauge_look import look, tile_json +from .timeutil import day_bounds, local_date log = logging.getLogger(__name__) @@ -78,6 +81,8 @@ NOT_ANSWERING = "The weather station isn't answering right now." RAIN_RATES = ("rainfall", "rainfall_piezo") # where the station's rain rate is (current's groups): its rain gauge's first, then the piezo's HOUR_SECONDS = 3600 # a red hand's reach back: the highest of the past hour, rolling (a peak held until it is an hour old) +ROSE_SECONDS = 60 # the wind rose (today's directions) read from the file at most this often (the data asked for again sooner: the same) +ROSE_DECIMALS = 4 # its shares rounded so HOURLY = {g.title: g.hourly for g in GAUGES if g.hourly} # the dials with a red hand, and the reading whose past hour it shows @@ -136,6 +141,7 @@ def __init__(self, server, uris: tuple[str, ...] = ("ecobot://now/weather", "eco if self.animations not in MOTIONS: raise ValueError(f"animations: {animations!r} is not one of {', '.join(MOTIONS)}") self._streams: set[asyncio.Queue] = set() + self._rose: tuple[float, int, list[float]] | None = None # (when read, the day's start, its shares): rose()'s, kept ROSE_SECONDS self._shown = self._readings() self.closed = False server.bus.subscribe(self._on_event) @@ -148,7 +154,11 @@ async def data(self) -> dict: result = json.loads(await tool.call(gauge_sheet.call(), {"fetch": False})) if tool else {"error": "no current"} sheet = gauge_sheet.sheet(result, indoor=self.indoor) # (indoor off: no indoor tile, nothing indoor sent) live = self._kept_live() - out = {"as_of": result.get("as_of"), "devices": self.device_times(), "tiles": [tile_json(t) for t in sheet.tiles] if sheet else [], "look": look(), + tiles = [tile_json(t) for t in sheet.tiles] if sheet else [] + for tile in tiles: + if tile["kind"] == "compass": # (the wind's direction: today's rose under its needle) + tile["rose"] = await self.rose() + out = {"as_of": result.get("as_of"), "devices": self.device_times(), "tiles": tiles, "look": look(), "rain_rate": rain_rate_of(result, live), "gust": now_of(result, live, GUST), "hour_highs": await self.hour_highs(result, live, [t.title for t in sheet.tiles] if sheet else [])} if sheet is None: @@ -177,6 +187,25 @@ async def hour_highs(self, result: dict, live: dict | None, titles: list[str]) - out[title] = max(found) if found else None return out + async def rose(self) -> list[float]: + """Today's wind rose (the station's day, in its zone): the share of today's readings of the wind's direction (its 5-minute + readings and minutes in the file, calm ones left out: directions_on) from each of the 16 compass points, N first, clockwise; + [] with none (or no file, or an error reading it). Read at most every ROSE_SECONDS (and again as the day turns), else kept.""" + eco, now = self.server.ctx.eco, time.time() + start = day_bounds(local_date(int(now), self.server.ctx.zone), self.server.ctx.zone)[0] + if self._rose and self._rose[1] == start and now - self._rose[0] < ROSE_SECONDS: + return self._rose[2] + shares: list[float] = [] + if getattr(eco, "storage", None) is not None and getattr(eco, "mac", None): + try: + counts = await eco.storage.read(directions_on, eco.mac, start, int(now) + 60) + total = sum(counts) + shares = [round(n / total, ROSE_DECIMALS) for n in counts] if total else [] + except Exception as e: # (no rose drawn) + log.warning("Dashboard: couldn't read today's wind directions: %s: %s", type(e).__name__, e) + self._rose = (now, start, shares) + return shares + @staticmethod def _recent(live: dict | None, where: tuple[str, str]) -> bool: """Is the kept live reading's (else current's) of this reading from the past hour: not one read longer ago (a station silent @@ -308,4 +337,4 @@ def routes(self, path: str = "/dashboard") -> list[Route]: Route(f"{path}/events", self.events, methods=["GET"])] -__all__ = ["HOURLY", "WebDashboard", "air_readings_of", "now_of", "rain_rate_of", "readings_of"] +__all__ = ["HOURLY", "ROSE_SECONDS", "WebDashboard", "air_readings_of", "now_of", "rain_rate_of", "readings_of"] diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 1d7a0928..9f18ed56 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -36,13 +36,14 @@ import httpx import pytest -from lib import gauge_sheet +from lib import gauge_sheet, web_dashboard +from lib.ecowitt.direction import POINTS from lib.gauge_look import look, tile_json from lib.mcp_server import AIR_URI, EcobotServer, WEATHER_URI, http_app from lib.service.context import Context from lib.service.names import Catalogue from lib.ecowitt.dashboard import GUST -from lib.ecowitt.reads import highest_on +from lib.ecowitt.reads import directions_on, highest_on from lib.gauge_look import START, SWEEP from lib.web_dashboard import (DESCRIPTION, HOUR_SECONDS, HOURLY, ICON, ICON_URL, PAGE, WebDashboard, air_readings_of, rain_rate_of, readings_of) @@ -89,10 +90,18 @@ def air_from(self, at: float): self.air_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(at)) self._keep_air() - def held(self, highs: dict): - """The station's file holds these highest of the past hour ({(group, field): value}, highest_on's), as the dashboard reads it.""" - async def read(fn, mac, wheres, start, end): - assert fn is highest_on and mac == "fake" and end - start == HOUR_SECONDS + 60 and abs(end - 60 - time.time()) < 5 + def held(self, highs: dict, rose: list[int] | None = None): + """The station's file holds these highest of the past hour ({(group, field): value}, highest_on's), as the dashboard reads it, + and today's wind directions (directions_on's: minutes from each of the 16 compass points; none: all 0).""" + async def read(fn, mac, *args): + assert mac == "fake" + if fn is directions_on: # (today's: from the station's midnight to now) + start, end = args + assert datetime.fromtimestamp(start, TZ).time() == datetime.min.time() and abs(end - 60 - time.time()) < 5 + assert datetime.fromtimestamp(start, TZ).date() == datetime.now(TZ).date() + return list(rose or [0] * 16) + wheres, start, end = args + assert fn is highest_on and end - start == HOUR_SECONDS + 60 and abs(end - 60 - time.time()) < 5 return {w: v for w, v in highs.items() if w in wheres} self.eco.storage, self.eco.mac = NS(read=read), "fake" @@ -143,7 +152,8 @@ async def test_the_page_and_its_data_are_served_without_a_token_to_any_host_and_ assert data.status_code == 200 got = data.json() sheet = gauge_sheet.sheet(station.current(gauge_sheet.call(), {"fetch": False})) - assert got["tiles"] == [tile_json(t) for t in sheet.tiles] and got["as_of"] == AS_OF and got["look"] == look() + assert got["tiles"] == [{**tile_json(t), **({"rose": []} if t.kind == "compass" else {})} for t in sheet.tiles] # (no file: no rose) + assert got["as_of"] == AS_OF and got["look"] == look() titles = [t["title"] for t in got["tiles"]] assert titles[:6] == ["Temperature", "Humidity", "Atmospheric pressure", "Rain", "UV index", "US AQI"] # gauge_sheet.FIRST assert titles[-6:] == ["PM2.5", "PM10", "PM1", "CO₂", "VOC index", "NOx index"] # the rest in their order: the air sensor's after @@ -228,6 +238,60 @@ async def test_the_past_hours_highest_is_read_from_the_minutes_and_the_5_minute_ storage.close() +async def test_the_data_carries_todays_wind_rose_on_the_wind_direction_tile_read_from_the_file_and_kept_a_minute(server, station, + monkeypatch, caplog): + """The Wind direction tile's `rose`: the share of today's readings of the wind's direction (the station's day, in its zone; the + file's: directions_on) from each of the 16 compass points, N first; [] with no file, no reading today, or the file not read. Read at + most every ROSE_SECONDS, else kept; no other tile has one, and the sheet's tiles are as ever.""" + page = WebDashboard(server) + compass = lambda got: next(t for t in got["tiles"] if t["kind"] == "compass") + got = await page.data() + assert compass(got)["rose"] == [] and all("rose" not in t for t in got["tiles"] if t["kind"] != "compass") # (no file) + assert [{k: v for k, v in t.items() if k != "rose"} for t in got["tiles"]] == [tile_json(t) for t in gauge_sheet.sheet( + station.current(gauge_sheet.call(), {"fetch": False})).tiles] + minutes = [10, 4, 2, 0, 30, 12, 6, 0, 0, 0, 3, 0, 0, 0, 5, 8] + station.held({}, minutes) + assert compass(await page.data())["rose"] == [] and web_dashboard.ROSE_SECONDS == 60 # (kept: read under a minute ago) + page._rose = None + got = compass(await page.data())["rose"] + assert len(got) == 16 and got == [round(n / 80, 4) for n in minutes] and got[4] == 0.375, got + station.held({}, [0] * 16) # read again a minute on: none today + page._rose = (page._rose[0] - 61, *page._rose[1:]) + assert compass(await page.data())["rose"] == [] + + async def broken(*a): + raise OSError("disk") + station.eco.storage = NS(read=broken) + monkeypatch.setattr(web_dashboard, "ROSE_SECONDS", 0) + assert compass(await page.data())["rose"] == [] and "couldn't read today's wind directions: OSError: disk" in caplog.text + + +async def test_todays_wind_directions_are_counted_from_the_5_minute_readings_and_the_minutes_they_dont_cover_calm_left_out(tmp_path): + """directions_on: minutes from each of the 16 compass points from start to end: a 5-minute reading counts 5, a minute 1 where no + 5-minute reading is within 300 s of it (never counted twice); a calm one (its speed 0) left out, one with no speed counted; nothing + older or newer, nor a 30-minute reading; all 0 with none, or no wind sensor.""" + from lib.storage import Storage + storage = Storage(tmp_path / "s.sqlite", TZ) + mac, now = "AA:BB", 1_794_279_900 + start = now - 6 * 3600 + assert await storage.read(directions_on, mac, start, now) == [0] * 16 + fives = {now - 3600: ("90", "5"), now - 3300: ("95", "0"), now - 3000: ("180", "3"), now - 7 * 3600: ("0", "4")} # (calm; too old) + wind = lambda rows: {"wind": {"wind_direction": {"unit": "º", "list": {str(t): d for t, (d, _) in rows.items()}}, + "wind_speed": {"unit": "km/h", "list": {str(t): v for t, (_, v) in rows.items()}}}} + with storage.writer.transaction() as w: + w.put_ecowitt(mac, "5min", ["wind"], wind(fives), now - 8 * 3600, now - 2000, now=now) + w.put_ecowitt(mac, "30min", ["wind"], wind({now - 1800: ("270", "4")}), now - 1800, now - 1800, now=now) + w.put_minutes(mac, wind({now - 3060: ("200", "2"), # (within the 5-minute readings: theirs) + now - 600: ("350", "6"), now - 540: ("5", "6"), now - 480: ("22", "1"), now - 420: ("300", "0"), + now + 120: ("90", "9")}), now) # (newer than `end`) + w.put_minutes(mac, {"wind": {"wind_direction": {"unit": "º", "list": {str(now - 360): "135"}}}}, now) # (no speed: counted) + got = await storage.read(directions_on, mac, start, now) + want = [0] * 16 + want[4] += 5; want[8] += 5; want[0] += 2; want[1] += 1; want[6] += 1 # (E, S; N twice, NNE, SE) + assert got == want, got + storage.close() + + async def test_the_page_answers_at_dashboard_slash_too_so_a_proxy_mapping_a_sites_root_there_gets_no_redirect_to_the_lan(server): # nginx's `location / { proxy_pass http://deb1:8765/dashboard/; }` sends the site's root as /dashboard/ with ecobot-mcp's own Host: # a redirect to /dashboard would be built from that Host, the LAN address, and break the page from the internet @@ -569,23 +633,59 @@ def chromium(): needs_browser = pytest.mark.usefixtures("chromium") +def rgb(colour: str) -> str: + return "rgb({}, {}, {})".format(*(int(colour[i:i + 2], 16) for i in (1, 3, 5))) + + def one_end_to_read(compass: dict): - """The compass's needle (compassLook's): its head a bold arrow in the needles' colour, its tail a short, thin, dim stub of another - colour; never two ends alike.""" + """The compass's needle (compassLook's, in its own px): its head a slim blade to a sharp tip in the needles' colour, solid; its tail + a short, dim taper of another colour; never two ends alike.""" head, tail = compass["ends"] - needle = "rgb({}, {}, {})".format(*(int(look()["needle"][i:i + 2], 16) for i in (1, 3, 5))) - assert head["colour"] == needle and tail["colour"] != needle and head["opacity"] == 1 and tail["opacity"] <= 0.6, compass - assert head["area"] > 6 * tail["area"] and head["length"] > 2.5 * tail["length"], compass + assert head["colour"] == rgb(look()["needle"]) and tail["colour"] != head["colour"], compass + assert head["opacity"] == 1 and tail["opacity"] <= 0.6, compass + assert head["length"] > 4 * tail["length"] and head["area"] > 3 * tail["area"] and head["width"] <= 12, compass # (slim) + + +ROSE = [10, 4, 2, 0, 30, 12, 6, 0, 0, 0, 3, 0, 0, 0, 5, 8] # today's minutes from each compass point (N first): mostly from the east +ROSE_LATER = [0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 10, 0, 40, 20, 0, 0] # ... later: from the west + + +def compass_as_a_dial(c: dict): + """The compass (compassLook's) the size of a dial, lined up with them: its ring a dial's (centre and radius in the tile's own px, its + line as thin), as wide drawn; the layers from the bottom: the rose, the reading, the face (its ring, ticks and N, E, S and W), the + needle, its hub; the reading inside the ring, in its lower half, centred.""" + assert c["circle"] == c["dialCircle"] == [240, 203, 138] and c["ringStroke"] == pytest.approx(3 * 100 / 72), c + if not c["zoomed"]: # (in the grid: as large as its neighbours' drawn) + assert c["ring"]["width"] == pytest.approx(c["dialRing"]["width"], abs=0.5), c + assert c["layers"] == ["rose", "reading", "face", "needle", "hub"], c + reading = next(r for r in c["texts"] if r["width"] and abs((r["left"] + r["right"]) / 2 - (c["ring"]["left"] + c["ring"]["right"]) / 2) < 1 + and r["top"] > (c["ring"]["top"] + c["ring"]["bottom"]) / 2) + assert c["readingBelow"] > 30 and c["readingAt"] + 20 < 138 and c["ring"]["left"] < reading["left"] and reading["right"] < c["ring"]["right"], c + assert reading["bottom"] < c["ring"]["bottom"] - c["ring"]["height"] * 0.1, (reading, c) + + +def rose_drawn(c: dict, minutes: list[int]): + """Today's rose as drawn (compassLook's petals): a petal for each compass point with any share, in the needles' colour, see-through, + its reach from the centre in proportion to its share, the longest 80% of the radius.""" + total, most = sum(minutes), max(minutes) + want = {POINTS[i]: n / total for i, n in enumerate(minutes) if n} + petals = c["petals"] + assert {p["point"]: p["share"] for p in petals} == pytest.approx(want, abs=1e-4), petals + for p in petals: + assert p["reach"] == pytest.approx(138 * 0.8 * minutes[POINTS.index(p["point"])] / most, abs=0.05), p + assert p["colour"] == rgb(look()["needle"]) and 0.15 <= p["opacity"] <= 0.5, p @needs_browser -async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error(server, station, tmp_path): +async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error(server, station, tmp_path, + monkeypatch): shots = Path(os.getenv("ECOBOT_SCREENSHOTS") or tmp_path) shots.mkdir(parents=True, exist_ok=True) port = free_port() url = f"http://127.0.0.1:{port}/dashboard" + monkeypatch.setattr(web_dashboard, "ROSE_SECONDS", 0) # (today's rose read again with each data: it changes below) station.reads("wind", "wind_gust", "12") - station.held({GUST: 37.0, RATE: 4.2, SOLAR: 820.0, UVI: 6.5}) # (the past hour: higher than the readings now, all but 0) + station.held({GUST: 37.0, RATE: 4.2, SOLAR: 820.0, UVI: 6.5}, ROSE) # (the past hour: higher than the readings now, all but 0; today's rose) station.reads("indoor", "temperature", "23.7") # an indoor sensor, served with MCP_DASHBOARD_INDOOR off: station.reads("indoor", "humidity", "47") # its tiles never drawn (the same tiles as with none) async with Serving(http_app(server, tokens=(TOKEN,), dashboard_indoor=False), port): @@ -600,7 +700,8 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl before = json.loads(await asyncio.wait_for(live.stdout.readline(), 60)) station.reads("outdoor", "temperature", "21.5") station.reads("wind", "wind_direction", "300") # (and the wind backs from the east to WNW) - station.held({GUST: 60.0, RATE: 4.2, SOLAR: 820.0, UVI: 6.5}) # (and the past hour's highest gust rises) + station.held({GUST: 60.0, RATE: 4.2, SOLAR: 820.0, UVI: 6.5}, ROSE_LATER) # (and the past hour's highest gust rises, and + # today's rose turns to the west) await server.publish_changes() live.stdin.write(b"go\n") await live.stdin.drain() @@ -640,16 +741,20 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl tile, glass = got["zoomed"]["box"], got["zoomed"]["glass"] # (the first tile, Temperature) zoomed: the glass with it assert len(glass) == 1 and all(g["height"] > 0 and tile["left"] <= g["left"] and g["right"] <= tile["right"] for g in glass) assert glass[0]["height"] > tile["width"] * 0.2 and glass[0]["width"] < glass[0]["height"] * 0.06, (glass, tile) - # the wind's direction, a compass: N, E, S, W and the points between named, its needle's head turned to where the wind comes + # the wind's direction, a compass: N, E, S and W named (N in its accent), its needle's head turned to where the wind comes # from (99°, east), its reading "99° E" (the service's compass point); no table, the same size as its neighbours c, rects = got["compass"], got["rects"] - assert (c["label"], c["reading"], c["turn"], c["faded"]) == ("Wind direction 99° E", "99° E", "rotate(99.00 240 188)", False), c - assert c["points"] == ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] and c["table"] == 0, c + assert (c["label"], c["reading"], c["turn"], c["faded"]) == ("Wind direction 99° E", "99° E", "rotate(99.00 240 203)", False), c + assert c["points"] == ["N", "E", "S", "W"] and c["table"] == 0, c + assert c["pointColours"] == [look()["compass_north"], *[look()["soft"]] * 3], c assert any(near(c["box"], r, 0.5) for r in rects) and len({(round(r["width"]), round(r["height"])) for r in rects}) == 1, c + compass_as_a_dial(c) ring, head = c["ring"], c["head"] assert (head["left"] + head["right"]) / 2 > (ring["left"] + ring["right"]) / 2 + ring["width"] * 0.1 and abs((head["top"] + head["bottom"]) / 2 - (ring["top"] + ring["bottom"]) / 2) < ring["height"] * 0.1, c - # ... the end to read unmistakable: the head a bold arrow in the needles' colour, the tail a short, thin, dim stub of another + # ... the end to read unmistakable: the head a slim sharp blade in the needles' colour, the tail a short, dim taper of another one_end_to_read(c) + # ... today's rose under it all, a petal per compass point blown from, as long as its share (the longest 80% of the radius) + rose_drawn(c, ROSE) assert all(c["box"]["left"] <= r["left"] and r["right"] <= c["box"]["right"] and r["bottom"] <= c["box"]["top"] + c["box"]["width"] * TABLE_TOP / look()["cell"][0] for r in c["texts"]), c # (all of it above where a table would start) # zoomed: the compass and its reading fill the zoomed place, as any tile's title and gauge @@ -659,6 +764,8 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl assert z["box"]["left"] - 1 <= r["left"] and r["right"] <= z["box"]["right"] + 1 and z["box"]["top"] - 1 <= r["top"] and r["bottom"] <= z["box"]["bottom"] + 1, (r, z) assert z["ring"]["width"] > z["box"]["width"] * 0.45, z one_end_to_read(z) # (zoomed too) + compass_as_a_dial(z) + rose_drawn(z, ROSE) assert (shots / f"dashboard-{name}-compass.png").exists() # the dials with a thin red hand at the past hour's highest (Wind's gust, Rain rate's, Solar radiation's, UV's), over the dial # and the needle, under the hub; none on any other tile; the Wind's table: its highest speed, and its highest gust beside it @@ -683,7 +790,8 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl assert after["same_tile"] and "21.5 °C" in after["shown"], after # the gauge moved in place to the new reading # the compass's needle swung from 99° to 300° the short way round, through north (never through the south), the reading WNW c = after["compass"] - assert (c["label"], c["reading"], c["turn"]) == ("Wind direction 300° WNW", "300° WNW", "rotate(300.00 240 188)"), c + assert (c["label"], c["reading"], c["turn"]) == ("Wind direction 300° WNW", "300° WNW", "rotate(300.00 240 203)"), c + rose_drawn(c, ROSE_LATER) # (today's rose redrawn in place with it) turns = c["turns"] assert all(t <= 99.01 or t >= 299.99 for t in turns) and any(t < 30 for t in turns) and any(t > 330 for t in turns), turns # the Wind's red hand moved smoothly, frame by frame, from the past hour's highest gust before (37) to the new one (60) @@ -746,7 +854,8 @@ async def test_a_tile_with_no_reading_is_dimmed_at_its_floor_and_a_reading_comin # the compass with no reading: dimmed, its needle back at north, no figure or point claimed was, now = got["compass"] assert not was["faded"] and was["reading"] == "99° E", was - assert now["faded"] and (now["label"], now["reading"], now["turn"]) == ("Wind direction: no reading", "–", "rotate(0.00 240 188)"), now + assert now["faded"] and (now["label"], now["reading"], now["turn"]) == ("Wind direction: no reading", "–", "rotate(0.00 240 203)"), now + assert was["petals"] == [] == now["petals"] and was["layers"][0] == "rose", was # (no file: no rose drawn, nothing else in its place) async def test_an_event_is_sent_when_the_air_sensors_gauges_readings_change(server, station): @@ -937,7 +1046,7 @@ async def test_fewer_tiles_grow_evenly_to_fill_the_window_and_never_shrink_below # ---------- the zoomed view and its gallery ---------- ZOOM_MS = 200 -GAPS_BEFORE = {"dial": 2, "thermometer": 21.7, "beaker": 16.7, "compass": -5} # (the gap under the title, each kind, before the gauges +GAPS_BEFORE = {"dial": 2, "thermometer": 21.7, "beaker": 16.7, "compass": 2} # (the gap under the title, each kind, before the gauges # were moved down: the tile's own px) TABLE_TOP = 372 # (the web page's: where a tile's table starts, in its own pixels; above it the title and gauge, all a zoomed tile shows) diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index a325dfb0..28f2d42e 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -153,19 +153,34 @@ const handsSettled = (page) => page.waitForFunction(() => { }, null, { timeout: 5000, polling: 150 }).catch(() => { /* reported as it is */ }); // The compass tile's look: its label, reading, needle's turn, the points named, any table, where its parts are (the window's px) and -// its needle's head and tail +// its needle's head and tail; its ring's centre and radius in its own px beside a dial's (the first dial tile's ring); its layers, bottom +// to top (the gauge's children's classes); its rose's petals (compass point, share, reach in its own px, colour, opacity); its reading's +// centre's distance from the ring's centre, in its own px const compassLook = (page) => page.evaluate(() => { const t = document.querySelector('.tile[data-kind="compass"]'), rect = (e) => e.getBoundingClientRect().toJSON(); - return { label: t.getAttribute("aria-label"), reading: t.querySelector("svg text.reading").textContent, faded: t.classList.contains("faded"), + const ring = t.querySelector("svg .ring"), dialRing = document.querySelector('.tile[data-kind="dial"] svg g.gauge > circle'); + const circle = (c) => c && ["cx", "cy", "r"].map((k) => Number(c.getAttribute(k))); + const [cx, cy] = circle(ring), reading = t.querySelector("svg text.reading"); + return { label: t.getAttribute("aria-label"), reading: reading.textContent, faded: t.classList.contains("faded"), turn: t.querySelector(".needle").getAttribute("transform"), points: [...t.querySelectorAll("svg text.point")].map((e) => e.textContent), + pointColours: [...t.querySelectorAll("svg text.point")].map((e) => e.getAttribute("fill")), table: t.querySelectorAll(".unit, .chip, .figure, .tablearea").length, zoomed: document.body.classList.contains("zoomed"), shown: !t.inert, box: rect(t), title: rect(t.querySelector(".title")), texts: [...t.querySelectorAll("svg text")].map(rect), - ring: rect(t.querySelector("svg circle")), head: rect(t.querySelector(".needle .head")), - // (its needle's two ends: the head's and the tail's colour, how opaque, their size (the drawn box's area, the window's px²)) + ring: rect(ring), head: rect(t.querySelector(".needle .head")), circle: circle(ring), dialCircle: circle(dialRing), + dialRing: dialRing && rect(dialRing), ringStroke: Number(ring.getAttribute("stroke-width")), + layers: [...t.querySelector("svg g.gauge").children].map((e) => e.getAttribute("class") || e.tagName), + readingAt: Math.hypot(Number(reading.getAttribute("x")) - cx, Number(reading.getAttribute("y")) - cy), + readingBelow: Number(reading.getAttribute("y")) - cy, + petals: [...t.querySelectorAll("svg .rose .petal")].map((e) => { + const [x, y] = e.getAttribute("d").match(/L([-\d.]+),([-\d.]+)/).slice(1).map(Number), c = getComputedStyle(e); + return { point: e.dataset.point, share: Number(e.dataset.share), reach: Math.hypot(x - cx, y - cy), colour: c.fill, + opacity: Number(c.fillOpacity) }; + }), + // (its needle's two ends: their fill and how opaque, their size in its own px (the shape's box, not turned) and on the window) ends: [".head", ".tail"].map((k) => { - const e = t.querySelector(`.needle ${k}`), c = getComputedStyle(e), r = rect(e); - return { colour: k === ".head" ? c.fill : c.stroke, opacity: Number(k === ".head" ? c.fillOpacity : c.strokeOpacity) * Number(c.opacity), - area: r.width * r.height, length: Math.hypot(r.width, r.height) }; + const e = t.querySelector(`.needle ${k}`), c = getComputedStyle(e), b = e.getBBox(); + return { colour: c.fill, opacity: Number(c.fillOpacity) * Number(c.opacity), area: b.width * b.height, length: b.height, + width: b.width }; }) }; }); From 2d65ca4fd27c99f33d2d023d010c5b96342633f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:59:25 +0000 Subject: [PATCH 093/146] Web dashboard: the UV's and the particles' tables show their Max alone; the red hands at today's highest - The US AQI, PM2.5, PM10 and PM1 tiles' Daily/Monthly/Yearly tables drop their Min column (AirGauge.lowest), as the UV index's already had none. Only the web page shows those tiles: the Status picture's three are untouched. - The thin red hands (Wind's gust, Rain rate, Solar radiation, UV index) show today's highest (the station's day) instead of the past hour's: /dashboard/data's hour_highs becomes today_highs, taken from the tiles' Daily Max (the Wind's Daily Gust) already in the sheet, which counts the reading now in, so the hand rises with it. No file read for it any more: highest_on and HOUR_SECONDS go. Gauge.hourly -> high_hand, HOURLY -> RED_HANDS, the look's hour_hand -> high_hand; the page's tile.todayHigh (not tile.high: the scale's top). - Tests (Python and browser) and docs updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/ecobot-mcp.md | 4 +- docs/features.md | 2 +- lib/airgradient/dashboard.py | 13 ++-- lib/ecowitt/dashboard.py | 14 ++-- lib/ecowitt/reads.py | 20 ------ lib/gauge_look.py | 6 +- lib/gauge_sheet.py | 10 +-- lib/service/current.py | 2 +- lib/web_dashboard.html | 30 ++++---- lib/web_dashboard.py | 63 ++++++----------- tests/test_dashboard.py | 14 ++-- tests/test_web_dashboard.py | 121 ++++++++++++++------------------- tests/web_dashboard_browser.js | 20 +++--- 13 files changed, 137 insertions(+), 182 deletions(-) diff --git a/docs/ecobot-mcp.md b/docs/ecobot-mcp.md index 27f2230e..527fac0c 100644 --- a/docs/ecobot-mcp.md +++ b/docs/ecobot-mcp.md @@ -722,7 +722,9 @@ Each step ships on its own, with the tests and evals green and the bot working t Read-only, so no token and no Host check; `/mcp` keeps both. After the station's gauges come the air sensor's (`lib/airgradient/dashboard.py`, on US standards: the US AQI and PM2.5 on the EPA's 2024 categories, PM10 on the EPA's, CO2 on the usual ASHRAE-based indoor guidance, the VOC and NOx indices on bands of Sensirion's index); a tile with no reading now is - dimmed at its floor. + dimmed at its floor. The UV index's, the US AQI's and the particles' tables have a Max column alone (no Min); the Wind's, + Rain rate's, Solar radiation's and UV index's dials carry a thin red hand at today's highest (`/dashboard/data`'s + `today_highs`: their Daily Max, the Wind's Daily Gust, rising with the reading now). - **6b. Client only.** `BOT_MCP_URL` is required: the in-process mode (`LocalWeather`, the bot starting the sources, the syncers, the alert rules and the alert log itself) is deleted. Under systemd, `ecobot.service` wants and starts after `ecobot-mcp.service`; in Docker this is already the layout. The bot's image installs only its own packages (python-telegram-bot, openai, mcp, httpx). diff --git a/docs/features.md b/docs/features.md index 34327771..c9df72a5 100644 --- a/docs/features.md +++ b/docs/features.md @@ -6,7 +6,7 @@ Type a question in any chat the bot is in ("how hot is it?", "will it rain?", "r - **Charts:** any reading or several on one time axis, rain behind the lines, one colour per reading. Under a single chart are period buttons (1D, 7D, 1M, 3M, 1Y); pressing one redraws it in place (its other periods are fetched in the background as soon as the chart is sent, so a press is answered at once). Ask for "plot uv and solar on two axes" (or "dual axis", "overlay") to put two readings on one chart, each with its own scale: the left axis for the first, the right for the second. The AirGradient sensor's own temperature and humidity can be charted too, against the weather station's: "plot airgradient humidity over ecowitt humidity" draws both on one axis. They're offered to the AI model only when you name the AirGradient with temperature or humidity. "weather all week" draws every reading, a panel each. - **Status and the report:** the Status button (or `/status`) sends one message: a picture of three gauges, the temperature, humidity and rain now, with the report under it (the readings now, today's forecast and the pollen, written by ecobot-mcp in code, no AI model: `ecobot://status`), and a 🔄 that reads both again into the same message. `/report` asks the AI model for a report instead (ecobot-mcp's `report` prompt). -- **Dashboard:** every gauge, with its highest and lowest today, this month and this year, is ecobot-mcp's live web page (`/dashboard` beside `/mcp`, README); the chat has no dashboard picture any more (typing "dashboard" asks the AI model). +- **Dashboard:** every gauge, with its highest and lowest today, this month and this year (the UV index, the US AQI, PM2.5, PM10 and PM1: their highest alone), is ecobot-mcp's live web page (`/dashboard` beside `/mcp`, README), the wind's, rain rate's, sun's and UV's dials with a thin red hand at today's highest (the wind's: its gust); the chat has no dashboard picture any more (typing "dashboard" asks the AI model). - **Dark charts:** `DARKMODE=on` draws every chart on a dark background, or only between set times, e.g. `DARKMODE=8pm-8am` (docs/configuration.md). - **Readings at an interval:** "humidity each hour for the last 5 hours", "PM2.5 every 30 minutes this morning", "rain each hour today". Any reading, every minute to every day, each with its time, from the history the bot has stored. Rain is the millimetres that fell in each interval. A gap, such as a sensor that was off, is said, never filled in. Up to 300 rows a question: a longer period gets a coarser interval. - **Days and totals:** count or rank days by any reading ("how many days was UV 9 or more", "hottest day each year"), or total rain per month or year as bars. diff --git a/lib/airgradient/dashboard.py b/lib/airgradient/dashboard.py index 1a251d96..66a69a4f 100644 --- a/lib/airgradient/dashboard.py +++ b/lib/airgradient/dashboard.py @@ -21,6 +21,9 @@ high, 300-500 very high (the EPA's first four colours). The edges at 150 and 250 (VOC) and 20 and 150 (NOx) are the service's own ratings (lib/series.py AIR). +Each table has a Max and a Min column, but the US AQI's and the particles' (PM2.5, PM10, PM1): their Max alone (`lowest`), as the +UV index's: how clean the air got says little beside how bad it got. + Left out: PM1 (no US standard for it), and the sensor's own temperature and humidity (it is outdoors: the station's outdoor gauges show the same air). """ @@ -46,6 +49,8 @@ class AirGauge: step: float # the breakpoints' resolution: a reading below an edge + step is still in the band below decimals: int = 0 aqi: bool = False # shows the US AQI (the higher of PM2.5's and PM10's now: metrics.us_aqi), not the reading itself + lowest: bool = True # its table has a Min column beside its Max (not the particles' and the AQI's: their lowest says + # nothing worth a column, as the UV index's doesn't) @property def reading(self) -> str: @@ -67,10 +72,10 @@ def band(self, value: float | None) -> str | None: AIR_GAUGES = ( - AirGauge("US AQI", "", "pm2_5", (0, *(a_hi for *_, a_hi, _ in PM25_AQI)), EPA, EPA_NAMES, 1, aqi=True), - AirGauge("PM2.5", "µg/m³", "pm2_5", (0, *(hi for _, hi, *_ in PM25_AQI)), EPA, EPA_NAMES, 0.1, 1), - AirGauge("PM10", "µg/m³", "pm10", (0, 54, 154, 254, 354, 424, 604), EPA, EPA_NAMES, 1), - AirGauge("PM1", "µg/m³", "pm1", (0, *(hi for _, hi, *_ in PM25_AQI)), EPA, EPA_NAMES, 0.1, 1), # (on PM2.5's bands: no standard of its own) + AirGauge("US AQI", "", "pm2_5", (0, *(a_hi for *_, a_hi, _ in PM25_AQI)), EPA, EPA_NAMES, 1, aqi=True, lowest=False), + AirGauge("PM2.5", "µg/m³", "pm2_5", (0, *(hi for _, hi, *_ in PM25_AQI)), EPA, EPA_NAMES, 0.1, 1, lowest=False), + AirGauge("PM10", "µg/m³", "pm10", (0, 54, 154, 254, 354, 424, 604), EPA, EPA_NAMES, 1, lowest=False), + AirGauge("PM1", "µg/m³", "pm1", (0, *(hi for _, hi, *_ in PM25_AQI)), EPA, EPA_NAMES, 0.1, 1, lowest=False), # (on PM2.5's bands: no standard of its own) AirGauge("CO₂", "ppm", "co2", (400, 800, 1000, 1500, 2000, 2500), EPA[:5], ("Good", "Fair", "Poor", "Bad", "Very bad"), 0), AirGauge("VOC index", "", "voc_index", (1, 100, 150, 250, 400, 500), VOC_COLOURS, ("Low", "Average", "Elevated", "High", "Very high"), 0), diff --git a/lib/ecowitt/dashboard.py b/lib/ecowitt/dashboard.py index 0c35328e..658fbcd2 100644 --- a/lib/ecowitt/dashboard.py +++ b/lib/ecowitt/dashboard.py @@ -20,7 +20,7 @@ SUN = ("#FBE79A", "#F5D45A", "#F2A53C", "#D27A2A", "#A9501F") UV = ("#A9E34B", "#F7E04A", "#F4A93B", "#E8562A", "#9A1F5A", "#7A2CF0") DEGREES = (40, 30, 20, 10, 0) # a thermometer's scale as it starts (THERMOMETER), before it widens to take in the reading -GUST = ("wind", "wind_gust") # the live gust: the Wind gauge's Gust column's, and its red hand's +GUST = ("wind", "wind_gust") # the live gust: the Wind gauge's Gust column's, and its red hand's (today's highest gust) THERMOMETER = (0, 40, 10) # a thermometer's scale: its ends and its step, in °C; widened a step at a time to the reading @@ -50,8 +50,8 @@ class Gauge: total: bool = False # rain: the Total column, the sum of the days' figures (its Max is the wettest day's) gust: str | None = None # wind: the day figure whose highest is its Gust column (where Min usually is), the live gust # (GUST) counted in, as the speed now is into its Max - hourly: tuple[str, str] | None = None # the live reading whose highest of the past hour the web page's thin red hand shows (wind: - # the gust; rain rate, solar radiation and UV: their own) + high_hand: tuple[str, str] | None = None # the live reading whose highest today the web page's thin red hand shows (its table's + # Daily Max; wind: the gust, its Daily Gust; rain rate, solar radiation and UV: their own) @property def reading(self) -> str: @@ -69,15 +69,15 @@ def reading(self) -> str: Gauge("Dew point", "°C", "thermometer", 0, 40, COLD_TO_HOT, DEGREES, ("outdoor", "dew_point"), "dew_point_max", "dew_point_min"), Gauge("Feels like", "°C", "thermometer", 0, 40, COLD_TO_HOT, DEGREES, ("outdoor", "feels_like"), "feels_like_max", "feels_like_min"), Gauge("Wind", "km/h", "dial", 0, 100, WIND, (0, 20, 40, 60, 80, 100), ("wind", "wind_speed"), "wind_speed_max", None, 0, - gust="wind_gust", hourly=GUST), + gust="wind_gust", high_hand=GUST), Gauge("Wind direction", "°", "compass", 0, 360, WIND, (0, 90, 180, 270), ("wind", "wind_direction"), None, None, 0), Gauge("Rain", "mm", "beaker", 0, 100, WATER, (100, 80, 60, 40, 20, 0), ("rainfall", "daily"), "rain", None, 1, True), Gauge("Rain rate", "mm/h", "dial", 0, 50, WATER, (0, 10, 20, 30, 40, 50), ("rainfall", "rain_rate"), "rain_rate_max", - hourly=("rainfall", "rain_rate")), + high_hand=("rainfall", "rain_rate")), Gauge("Solar radiation", "W/m²", "dial", 0, 1500, SUN, (0, 300, 600, 900, 1200, 1500), ("solar_and_uvi", "solar"), "solar_max", None, 0, - hourly=("solar_and_uvi", "solar")), + high_hand=("solar_and_uvi", "solar")), Gauge("UV index", "", "dial", 0, 12, UV, (0, 3, 6, 8, 11), ("solar_and_uvi", "uvi"), "uv_max", - hourly=("solar_and_uvi", "uvi")), + high_hand=("solar_and_uvi", "uvi")), Gauge("Indoor temperature", "°C", "thermometer", 0, 40, COLD_TO_HOT, DEGREES, ("indoor", "temperature"), "indoor_temp_max", "indoor_temp_min"), Gauge("Indoor humidity", "%", "dial", 0, 100, WATER, (0, 20, 40, 60, 80, 100), ("indoor", "humidity"), "indoor_humidity_max", "indoor_humidity_min", 0), diff --git a/lib/ecowitt/reads.py b/lib/ecowitt/reads.py index b4dab814..a76381a3 100644 --- a/lib/ecowitt/reads.py +++ b/lib/ecowitt/reads.py @@ -66,26 +66,6 @@ def first_minute_on(r: Reader, mac: str, groups: list[str], start: int, end: int return min((t for t in found if t is not None), default=None) -def highest_on(r: Reader, mac: str, wheres: list[tuple[str, str]], start: int, end: int) -> dict[tuple[str, str], float]: - """{(group, field): the highest of the reading from start to end}, of its minutes (Home Assistant's) and its 5-minute readings, each - with the highest of its band where it has one (the bot's live readings counted into it: a 5-minute row holding only a band counts - too). A reading with none is left out. One query per kind of sensor (the web page's red hands: the past hour's highest).""" - by_sensor: dict = {} - for where in wheres: - sensor, place = r.sensor(mac, where[0]), column_of(*where) - if sensor is not None and place is not None and place[1] == "value": - by_sensor.setdefault((sensor.kind, sensor.id), []).append((where, place[0])) - out: dict[tuple[str, str], float] = {} - for (kind, sensor), columns in by_sensor.items(): - picks = ", ".join(f"MAX({q(c)}), MAX({q(c + '_hi')})" for _, c in columns) - got = r.db.execute(f"SELECT {picks} FROM {kind} WHERE sensor = ? AND res IN ('1min', '5min') AND ts BETWEEN ? AND ?", - (sensor, start, end)).fetchone() - for i, (where, _) in enumerate(columns): - if found := [v for v in got[2 * i:2 * i + 2] if v is not None]: - out[where] = float(max(found)) - return out - - def directions_on(r: Reader, mac: str, start: int, end: int) -> list[int]: """How long the wind blew from each of the 16 compass points (direction.sector: N first, clockwise) from start to end, in minutes, of the wind's 5-minute readings (5 each) and its minutes (1 each) where no 5-minute reading covers them (300 s either side), in one query; diff --git a/lib/gauge_look.py b/lib/gauge_look.py index 0b14c620..0c356105 100644 --- a/lib/gauge_look.py +++ b/lib/gauge_look.py @@ -14,8 +14,8 @@ MAX_CHIP, MIN_CHIP, TOTAL_CHIP, GUST_CHIP = "#C62828", "#4FB3F6", "#5BC8F0", "#7C8790" CHIPS = {"Max": MAX_CHIP, "Min": MIN_CHIP, "Total": TOTAL_CHIP, "Gust": GUST_CHIP} MARKS = {"Max": "▲", "Min": "▼", "Total": "+", "Gust": "»"} # in front of a column's name -HOUR_HAND = "#FF3B30" # a dial's thin red hand: its reading's highest of the past hour (the web page's: wind's gust, rain rate, sun, UV) -HOUR_HAND_WIDTH = 1.4 # ... how wide (pixels) +HIGH_HAND = "#FF3B30" # a dial's thin red hand: its reading's highest today (the web page's: wind's gust, rain rate, sun, UV) +HIGH_HAND_WIDTH = 1.4 # ... how wide (pixels) FILL = "#D32F27" # the thermometer's mercury TUBE_HALF, BULB_RADIUS = 28, 38 # the thermometer: half the tube's width, the bulb's radius (pixels, to the outline) MERCURY_GAP = 7 # the gap between the outline and the red, the same round the bulb as up the tube @@ -67,7 +67,7 @@ def share(tile: Tile, value: float) -> float: def look() -> dict: """The figures above as JSON, for the web page to draw with.""" return {"bg": BG, "ink": INK, "soft": SOFT, "chip": CHIP, "chips": CHIPS, "marks": MARKS, "fill": FILL, "water": WATER, - "needle": NEEDLE, "hour_hand": HOUR_HAND, "hour_hand_width": HOUR_HAND_WIDTH, "tube_half": TUBE_HALF, "bulb_radius": BULB_RADIUS, "mercury_gap": MERCURY_GAP, "bar_width": BAR_WIDTH, + "needle": NEEDLE, "high_hand": HIGH_HAND, "high_hand_width": HIGH_HAND_WIDTH, "tube_half": TUBE_HALF, "bulb_radius": BULB_RADIUS, "mercury_gap": MERCURY_GAP, "bar_width": BAR_WIDTH, "bar_gap": BAR_GAP, "ring_outer": RING_OUTER, "band_width": BAND_WIDTH, "label_radius": LABEL_RADIUS, "cell": [CELL_W, CELL_H], "compass": list(COMPASS), "compass_label_y": COMPASS_LABEL_Y, "compass_band": COMPASS_BAND, "compass_north": COMPASS_NORTH, "points": list(POINTS), diff --git a/lib/gauge_sheet.py b/lib/gauge_sheet.py index 0dcc5e49..25f548ad 100644 --- a/lib/gauge_sheet.py +++ b/lib/gauge_sheet.py @@ -2,9 +2,9 @@ gauges (lib/web_dashboard.py) and the Status picture's three (lib/status.py, drawn by lib/gauges.py): each gauge's scale and colours (the weather station's, lib/ecowitt/dashboard.py GAUGES, then the air sensor's, lib/airgradient/dashboard.py AIR_GAUGES) filled from the service's `current` with `context`, its reading now and the highs and lows of today, the month and the year beside it (rain: its totals and wettest day; wind: its highest speed, and its highest gust in a Gust -column where Min usually is; the US AQI: the higher of PM2.5's -and PM10's, as AQI). An air gauge's band is named from its own reading now, and the US AQI is worked out from PM2.5 and PM10 now, the -higher of the two, its band saying "(PM10)" when PM10 sets it: the dials agree with their needles (the service's `aqi_us` and `band` +column where Min usually is; the UV index, the US AQI and the particles (PM2.5, PM10, PM1): their highest alone, no Min; the US AQI: +the higher of PM2.5's and PM10's, as AQI). An air gauge's band is named from its own reading now, and the US AQI is worked out from +PM2.5 and PM10 now, the higher of the two, its band saying "(PM10)" when PM10 sets it: the dials agree with their needles (the service's `aqi_us` and `band` are of the lower of the last two readings, for its ratings). The wind's direction is a compass (its needle where the wind comes from, its band the compass point current gives with it), with no @@ -48,7 +48,7 @@ def _row(gauge: Gauge | AirGauge, figures: dict) -> tuple[float | None, ...]: """A row of a tile's table from current's figures of that period: Max and Min, Max alone, (wind) Max and Gust, or (rain) its wettest day and Total (the US AQI's already worked out as AQI: _aqi_entry).""" if isinstance(gauge, AirGauge): - return figures.get("high"), figures.get("low") + return (figures.get("high"), figures.get("low")) if gauge.lowest else (figures.get("high"),) if gauge.total: return (figures.get("wettest_day") or {}).get("rain"), figures.get("total") if gauge.gust: @@ -94,7 +94,7 @@ def _tile(gauge: Gauge | AirGauge, entry: dict) -> Tile | None: if band and entry.get("from") == "PM10": band = f"{band} (PM10)" ticks = gauge.bounds - return Tile(gauge.title, gauge.unit, now, "dial", gauge.low, gauge.high, gauge.colours, ("Max", "Min"), rows, ticks, + return Tile(gauge.title, gauge.unit, now, "dial", gauge.low, gauge.high, gauge.colours, ("Max", "Min") if gauge.lowest else ("Max",), rows, ticks, gauge.decimals, gauge.bounds, band) columns = ("Max", "Total") if gauge.total else ("Max", "Min") if gauge.lowest else ("Max", "Gust") if gauge.gust else ("Max",) low, high, colours, ticks = scale(gauge, now) # (a thermometer's widens to take in the reading) diff --git a/lib/service/current.py b/lib/service/current.py index 938768b8..96a99671 100644 --- a/lib/service/current.py +++ b/lib/service/current.py @@ -290,7 +290,7 @@ def gauge_of(name: str) -> Gauge | None: no figures (the wind's direction: its compass).""" if name == "wind.wind_gust": wind = next(g for g in GAUGES if g.live == ("wind", "wind_speed")) - return replace(wind, live=GUST, highest=wind.gust, gust=None, hourly=None) + return replace(wind, live=GUST, highest=wind.gust, gust=None, high_hand=None) return next((g for g in GAUGES if g.reading == name and g.highest), None) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 3e07e37b..0914c54c 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -3504,14 +3504,14 @@ } text(svg, cx, cy + 64, tile.unit, 18, ink(L.soft)); const needle = el("polygon", {fill: ink(L.needle)}, svg); - // The past hour's highest (the wind's gust, rain rate, sun, UV: tile.hour, null with none): a very thin red hand, like a clock's + // Today's highest (the wind's gust, rain rate, sun, UV: tile.todayHigh, null with none): a very thin red hand, like a clock's // second hand, over the dial and the needle and under the hub, its short tail behind the hub with a small counterweight. Drawn // pointing right (0 degrees), turned to its reading - const hand = tile.hour === undefined ? null : el("g", {class: "hour", "pointer-events": "none"}, svg); + const hand = tile.todayHigh === undefined ? null : el("g", {class: "high", "pointer-events": "none"}, svg); if (hand) { - el("path", {d: `M${cx - 40},${cy} L${cx + outer - 3},${cy}`, stroke: L.hour_hand, "stroke-width": L.hour_hand_width, + el("path", {d: `M${cx - 40},${cy} L${cx + outer - 3},${cy}`, stroke: L.high_hand, "stroke-width": L.high_hand_width, "stroke-linecap": "round", fill: "none"}, hand); - el("circle", {cx: cx - 34, cy, r: 3.6, fill: L.hour_hand}, hand); + el("circle", {cx: cx - 34, cy, r: 3.6, fill: L.high_hand}, hand); } const label = text(svg, cx, cy + 102, "", 50, ink(L.ink)); // (the reading alone: no band word ("Moderate") under the dial, its label.classList.add("reading"); // colours say it) @@ -3639,7 +3639,7 @@ // What can't change in place (a tile so different is drawn again): its kind and scale. A reading coming or going doesn't: the tile // brightens or dims (its opacity, eased) and the gauge moves from or to its floor. const shape = (t) => JSON.stringify([t.kind, t.title, t.unit, t.low, t.high, t.colours, t.ticks, t.bounds, t.columns, t.decimals, - t.hour !== undefined]); + t.todayHigh !== undefined]); const label = (t) => t.value === null ? `${t.title}: no reading` : t.kind === "compass" ? `${t.title} ${figure(t.value, t.decimals)}° ${t.band || ""}`.trim() : `${t.title} ${figure(t.value, t.decimals)} ${t.unit}`.trim(); let clips = 0; @@ -3668,14 +3668,14 @@ close.setAttribute("aria-label", `Hide ${tile.title}`); close.addEventListener("click", () => hide(idOf(tile), close.matches(":focus-visible"))); box.append(grip, close); - const drawnTile = {box, shape: shape(tile), value: shown(tile), frame: 0, hour: tile.hour ?? null, hourFrame: 0}; + const drawnTile = {box, shape: shape(tile), value: shown(tile), frame: 0, high: tile.todayHigh ?? null, highFrame: 0}; drawnTile.update = (t) => { // the same gauge at a new reading: the needle, mercury or water moves there, the figures change; box.setAttribute("aria-label", label(t)); // a reading come or gone: the tile brightens or dims, the gauge from or to its floor box.classList.toggle("faded", !!t.faded); fill(t); if (at.band) at.band(t); move(drawnTile.value, aim(drawnTile.value, shown(t)), MOVE_MS); - if (at.hand) moveHand(drawnTile.hour, t.hour ?? null, MOVE_MS); + if (at.hand) moveHand(drawnTile.high, t.todayHigh ?? null, MOVE_MS); }; const aim = (from, to) => at.toward ? at.toward(from, to) : to; // (a compass's needle: the short way round) const move = (from, to, ms) => { @@ -3693,22 +3693,22 @@ // The red hand on its own clock (its value changes apart from the needle's): eased there, or put there at once with reduced motion, // a hidden page, or coming or going (null) const moveHand = (from, to, ms) => { - drawnTile.hour = to; - cancelAnimationFrame(drawnTile.hourFrame); + drawnTile.high = to; + cancelAnimationFrame(drawnTile.highFrame); if (from === to || from === null || to === null || STILL || document.hidden) return at.hand(to); const start = performance.now(); const step = (now) => { const p = Math.min(Math.max((now - start) / ms, 0), 1), eased = 1 - (1 - p) ** 3; at.hand(p < 1 ? from + (to - from) * eased : to); - if (p < 1) drawnTile.hourFrame = requestAnimationFrame(step); + if (p < 1) drawnTile.highFrame = requestAnimationFrame(step); }; - drawnTile.hourFrame = requestAnimationFrame(step); + drawnTile.highFrame = requestAnimationFrame(step); }; if (opening) move(tile.floor, aim(tile.floor, shown(tile)), RISE_MS); // the page just opened: every gauge rises from its floor to its reading else at(shown(tile)); if (at.hand) { // (its hand with it) - at.hand(tile.hour === null ? null : opening ? tile.floor : tile.hour); - if (opening) moveHand(tile.floor, tile.hour, RISE_MS); + at.hand(tile.todayHigh === null ? null : opening ? tile.floor : tile.todayHigh); + if (opening) moveHand(tile.floor, tile.todayHigh, RISE_MS); } return drawnTile; } @@ -3923,8 +3923,8 @@ L = data.look; document.documentElement.style.setProperty("--fade", L.fade); tiles = data.tiles || []; - const hours = data.hour_highs || {}; // (the dials with a red hand: their past hour's highest, null with none) - for (const t of tiles) if (t.title in hours) t.hour = hours[t.title]; + const highs = data.today_highs || {}; // (the dials with a red hand: today's highest, null with none) + for (const t of tiles) if (t.title in highs) t.todayHigh = highs[t.title]; asOf = data.as_of && data.as_of.time ? data.as_of.time : null; devices = data.devices || {}; unavailable = data.unavailable || ""; diff --git a/lib/web_dashboard.py b/lib/web_dashboard.py index 82bf9a35..1f01f1d7 100644 --- a/lib/web_dashboard.py +++ b/lib/web_dashboard.py @@ -18,8 +18,9 @@ device's own (`devices`: {"station", "air"}: its reading's time, ISO in the station's zone, null with none held; a device not configured is not there), for the strip's stalled device greyed out, the look, and the station's rain rate now (`rain_rate`, mm/h: its rain gauge's, or its piezo gauge's where that's the one reporting, which no tile shows; null with - neither), for the page's rain behind the tiles; the past hour's highest of the dials with a thin red hand (`hour_highs`, by - title: Wind's gust, Rain rate's, Solar radiation's, UV index's: hour_highs()), the Wind direction tile's `rose` (today's + neither), for the page's rain behind the tiles; today's highest of the dials with a thin red hand (`today_highs`, by title, + the station's day in its zone: Wind's gust, Rain rate's, Solar radiation's, UV index's: their tiles' Daily Max, the Wind's its + Daily Gust, the reading now counted in: today_highs()), the Wind direction tile's `rose` (today's share of the wind's direction from each of the 16 compass points, N first, clockwise, from the file's readings, calm ones left out; [] with none: rose()), and the gust now (`gust`, km/h: over 99, a new reading sends a cow, a barn or a chicken across behind the tiles); @@ -60,7 +61,7 @@ from .airgradient.metrics import value_of from .service.common import iso from .ecowitt.dashboard import GAUGES, GUST, live_value -from .ecowitt.reads import directions_on, highest_on +from .ecowitt.reads import directions_on from .gauge_look import look, tile_json from .timeutil import day_bounds, local_date @@ -80,10 +81,10 @@ QUEUED = 4 # events waiting on a stream that isn't read: more are dropped (one says it all: fetch again) NOT_ANSWERING = "The weather station isn't answering right now." RAIN_RATES = ("rainfall", "rainfall_piezo") # where the station's rain rate is (current's groups): its rain gauge's first, then the piezo's -HOUR_SECONDS = 3600 # a red hand's reach back: the highest of the past hour, rolling (a peak held until it is an hour old) ROSE_SECONDS = 60 # the wind rose (today's directions) read from the file at most this often (the data asked for again sooner: the same) ROSE_DECIMALS = 4 # its shares rounded so -HOURLY = {g.title: g.hourly for g in GAUGES if g.hourly} # the dials with a red hand, and the reading whose past hour it shows +RED_HANDS = {g.title: "Gust" if g.gust else "Max" for g in GAUGES if g.high_hand} # the dials with a red hand at today's highest, +# and the column of their table whose Daily figure it is (the Wind's: its highest gust) def readings_of(live: dict | None, indoor: bool = True) -> tuple | None: @@ -93,7 +94,7 @@ def readings_of(live: dict | None, indoor: bool = True) -> tuple | None: if not live: return None gauges = [g for g in GAUGES if indoor or not gauge_sheet.is_indoor(g)] - return (*(live_value(live, where) for g in gauges for where in dict.fromkeys((g.live, *([g.hourly] if g.hourly else [])))), + return (*(live_value(live, where) for g in gauges for where in dict.fromkeys((g.live, *([g.high_hand] if g.high_hand else [])))), live_value(live, ("rainfall_piezo", "rain_rate"))) # (the piezo gauge's rain rate: the page's rain, with no gauge of its own) @@ -120,6 +121,18 @@ def now_of(result: dict, live: dict | None, where: tuple[str, str]) -> float | N return got +def today_highs(tiles) -> dict[str, float | None]: + """{title: today's highest} of these tiles' dials with a thin red hand (RED_HANDS: Wind's gust, Rain rate's, Solar radiation's, UV + index's): their table's Daily figure (the Max; the Wind's Gust), which current gives for the station's day in its zone with the + reading now counted in, so the hand rises with it; None with none. Nothing read for it: the sheet already holds it.""" + out = {} + for tile in tiles: + if tile.title in RED_HANDS: + daily = dict(zip(tile.columns, tile.rows.get("Daily") or ())) + out[tile.title] = daily.get(RED_HANDS[tile.title]) + return out + + def air_readings_of(row: dict | None) -> tuple | None: """What the air gauges show now of the air sensor's latest reading (its raw row, as AirGradient keeps it): each of their readings (the AQI is PM2.5's). None without one.""" @@ -148,7 +161,7 @@ def __init__(self, server, uris: tuple[str, ...] = ("ecobot://now/weather", "eco # ---------- the data ---------- async def data(self) -> dict: - """{as_of, devices, tiles, look, rain_rate, gust, hour_highs}, or with `unavailable` (and no tiles) when the station gives nothing. From what is held, whatever its age + """{as_of, devices, tiles, look, rain_rate, gust, today_highs}, or with `unavailable` (and no tiles) when the station gives nothing. From what is held, whatever its age (fetch off): an open request on the LAN never asks the station (the keep-warm keeps the live reading, and the events come from it).""" tool = self.server.service.get("current") result = json.loads(await tool.call(gauge_sheet.call(), {"fetch": False})) if tool else {"error": "no current"} @@ -160,33 +173,11 @@ async def data(self) -> dict: tile["rose"] = await self.rose() out = {"as_of": result.get("as_of"), "devices": self.device_times(), "tiles": tiles, "look": look(), "rain_rate": rain_rate_of(result, live), "gust": now_of(result, live, GUST), - "hour_highs": await self.hour_highs(result, live, [t.title for t in sheet.tiles] if sheet else [])} + "today_highs": today_highs(sheet.tiles if sheet else [])} if sheet is None: out["unavailable"] = (result.get("unavailable") or {}).get("station") or NOT_ANSWERING return out - async def hour_highs(self, result: dict, live: dict | None, titles: list[str]) -> dict[str, float | None]: - """{title: its reading's highest of the past HOUR_SECONDS} for these tiles' dials with a red hand (HOURLY): of the readings kept - in the station's file (its minutes and 5-minute readings, with their bands of the live readings the bot saw: highest_on) and its - reading now (the kept live reading's, else current's); None for one with neither. Read in one go from what is held, never - asked of the station; the file not read (none, or an error): the readings now alone.""" - wanted = {title: HOURLY[title] for title in titles if title in HOURLY} - if not wanted: - return {} - held: dict = {} - eco = self.server.ctx.eco - if getattr(eco, "storage", None) is not None and getattr(eco, "mac", None): - now = int(time.time()) - try: - held = await eco.storage.read(highest_on, eco.mac, list(dict.fromkeys(wanted.values())), now - HOUR_SECONDS, now + 60) - except Exception as e: # (the hands then show the readings now) - log.warning("Dashboard: couldn't read the past hour's highest: %s: %s", type(e).__name__, e) - out = {} - for title, where in wanted.items(): - found = [v for v in (held.get(where), now_of(result, live, where) if self._recent(live, where) else None) if v is not None] - out[title] = max(found) if found else None - return out - async def rose(self) -> list[float]: """Today's wind rose (the station's day, in its zone): the share of today's readings of the wind's direction (its 5-minute readings and minutes in the file, calm ones left out: directions_on) from each of the 16 compass points, N first, clockwise; @@ -206,16 +197,6 @@ async def rose(self) -> list[float]: self._rose = (now, start, shares) return shares - @staticmethod - def _recent(live: dict | None, where: tuple[str, str]) -> bool: - """Is the kept live reading's (else current's) of this reading from the past hour: not one read longer ago (a station silent - for hours), which no longer counts. A reading with no time of its own counts.""" - try: - at = int(((live or {}).get(where[0]) or {}).get(where[1], {}).get("time") or 0) - except (AttributeError, TypeError, ValueError): - return True - return not at or at >= time.time() - HOUR_SECONDS - def device_times(self) -> dict[str, str | None]: """{"station", "air"}: the time of each configured device's reading as it is held (the station's: its newest reading's own time in the kept live reading, else when that was kept; the air sensor's: its latest row's timestamp, else when that was fetched), ISO @@ -337,4 +318,4 @@ def routes(self, path: str = "/dashboard") -> list[Route]: Route(f"{path}/events", self.events, methods=["GET"])] -__all__ = ["HOURLY", "ROSE_SECONDS", "WebDashboard", "air_readings_of", "now_of", "rain_rate_of", "readings_of"] +__all__ = ["RED_HANDS", "ROSE_SECONDS", "WebDashboard", "air_readings_of", "now_of", "rain_rate_of", "readings_of", "today_highs"] diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index dad8c6d6..3aa8fde2 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -369,7 +369,7 @@ def air_result(latest: dict | None, air_values: dict | None = None) -> dict: def test_the_air_sensors_tiles_come_after_the_stations_with_their_aqi_bands_and_figures(): - from lib.airgradient.metrics import pm10_aqi, pm25_aqi + from lib.airgradient.metrics import pm25_aqi latest = {"pm2_5": {"value": 40.0, "unit": "µg/m³"}, "pm10": {"value": 60.0, "unit": "µg/m³"}, "pm1": {"value": 20.0, "unit": "µg/m³"}, "co2": {"value": 1200, "unit": "ppm"}} values = {"pm2_5_max": {date(2026, 10, 2): 70.0, TODAY: 30.0}, "pm2_5_min": {TODAY: 5.0}, "co2_max": {TODAY: 900}, "co2_min": {TODAY: 410}} @@ -378,12 +378,18 @@ def test_the_air_sensors_tiles_come_after_the_stations_with_their_aqi_bands_and_ assert list(tiles) == ["Temperature", "US AQI", "PM2.5", "PM10", "PM1", "CO₂"] # no VOC nor NOx sent: left out aqi = tiles["US AQI"] assert (aqi.value, aqi.band, aqi.kind, aqi.low, aqi.high, aqi.columns) == (pm25_aqi(40.0)[0], "Unhealthy for Sensitive Groups", "dial", - 0, 500, ("Max", "Min")) - assert aqi.rows["Daily"] == (pm25_aqi(40.0)[0], pm10_aqi(60.0)[0]) and aqi.rows["Monthly"][0] == pm25_aqi(70.0)[0] # (the higher of each) + 0, 500, ("Max",)) + assert aqi.rows["Daily"] == (pm25_aqi(40.0)[0],) and aqi.rows["Monthly"] == (pm25_aqi(70.0)[0],) # (the higher of each; no Min) assert aqi.ticks == aqi.bounds == (0, 50, 100, 150, 200, 300, 500) pm = tiles["PM2.5"] - assert (pm.value, pm.band, pm.decimals, pm.rows["Monthly"]) == (40.0, "Unhealthy for Sensitive Groups", 1, (70.0, 5.0)) + assert (pm.value, pm.band, pm.decimals, pm.rows["Monthly"]) == (40.0, "Unhealthy for Sensitive Groups", 1, (70.0,)) assert (tiles["PM10"].band, tiles["CO₂"].band, tiles["CO₂"].rows["Daily"]) == ("Moderate", "Poor", (1200.0, 410.0)) + # the US AQI's and the particles' tables: their Max alone, as the UV index's; the rest a Min beside their Max + from tests.chart_samples import _air, _station + live, days, today = _station() + columns = {t.title: t.columns for t in gauge_sheet.sheet(gauges_result(live, days, today, *_air(today))).tiles} + assert {t for t, c in columns.items() if c == ("Max",)} == {"US AQI", "PM2.5", "PM10", "PM1", "UV index", "Rain rate", "Solar radiation"} + assert columns["CO₂"] == columns["Temperature"] == ("Max", "Min") and all(len(r) == len(t.columns) for t in sheet.tiles for r in t.rows.values()) assert [t.title for t in gauge_sheet.sheet(air_result(None)).tiles] == ["Temperature"] # no air sensor: no air gauges diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 9f18ed56..8249aa3b 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -13,8 +13,8 @@ knocking the leaves they hit, humidity's fog and its beads, heavy rain's drops sticking to the glass, a flash flood filling the window a quarter up, its waves, its leaves and its frog, a cow, a barn or a chicken blown across in a gust over 99 km/h), the data's rain rate, and the -dials' thin red hands at the past hour's highest (the wind's gust, rain rate, sun, UV: read from the file and the reading now, moving -smoothly, at once with reduced motion) with the wind's Gust column. +dials' thin red hands at today's highest (the wind's gust, rain rate, sun, UV: their tiles' Daily figures, the reading now counted in, +moving smoothly, at once with reduced motion) with the wind's Gust column. With ECOBOT_SCREENSHOTS set, its screenshots are kept in that folder.""" import asyncio @@ -42,11 +42,10 @@ from lib.mcp_server import AIR_URI, EcobotServer, WEATHER_URI, http_app from lib.service.context import Context from lib.service.names import Catalogue -from lib.ecowitt.dashboard import GUST -from lib.ecowitt.reads import directions_on, highest_on +from lib.ecowitt.reads import directions_on from lib.gauge_look import START, SWEEP -from lib.web_dashboard import (DESCRIPTION, HOUR_SECONDS, HOURLY, ICON, ICON_URL, PAGE, WebDashboard, air_readings_of, rain_rate_of, - readings_of) +from lib.web_dashboard import (DESCRIPTION, ICON, ICON_URL, PAGE, RED_HANDS, WebDashboard, air_readings_of, rain_rate_of, readings_of, + today_highs) from tests.chart_samples import _air, _station from tests.fakes import TZ, StandInService, gauges_result from tests.test_mcp_listen import Serving, free_port, until @@ -90,21 +89,23 @@ def air_from(self, at: float): self.air_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(at)) self._keep_air() - def held(self, highs: dict, rose: list[int] | None = None): - """The station's file holds these highest of the past hour ({(group, field): value}, highest_on's), as the dashboard reads it, - and today's wind directions (directions_on's: minutes from each of the 16 compass points; none: all 0).""" + def held(self, rose: list[int] | None = None): + """The station's file holds today's wind directions (directions_on's: minutes from each of the 16 compass points; none: all + 0), as the dashboard reads it (nothing else: the red hands' highs are the sheet's).""" async def read(fn, mac, *args): - assert mac == "fake" - if fn is directions_on: # (today's: from the station's midnight to now) - start, end = args - assert datetime.fromtimestamp(start, TZ).time() == datetime.min.time() and abs(end - 60 - time.time()) < 5 - assert datetime.fromtimestamp(start, TZ).date() == datetime.now(TZ).date() - return list(rose or [0] * 16) - wheres, start, end = args - assert fn is highest_on and end - start == HOUR_SECONDS + 60 and abs(end - 60 - time.time()) < 5 - return {w: v for w, v in highs.items() if w in wheres} + assert mac == "fake" and fn is directions_on # (today's: from the station's midnight to now) + start, end = args + assert datetime.fromtimestamp(start, TZ).time() == datetime.min.time() and abs(end - 60 - time.time()) < 5 + assert datetime.fromtimestamp(start, TZ).date() == datetime.now(TZ).date() + return list(rose or [0] * 16) self.eco.storage, self.eco.mac = NS(read=read), "fake" + def highs_today(self, highs: dict): + """Today's day rows hold these highest ({day figure: value}, e.g. {"wind_gust": 37.0}), as current's context gives them.""" + self.values = {k: dict(v) for k, v in self.values.items()} + for figure, value in highs.items(): + self.values.setdefault(figure, {})[self.today] = value + def air_reads(self, column: str, value: float | None): """The air sensor's latest has this reading (None: it hasn't).""" self.latest = {k: e for k, e in self.latest.items() if k != column} @@ -188,56 +189,35 @@ async def test_the_data_carries_the_stations_rain_rate_now_its_rain_gauges_or_el assert readings_of({**station.live, **live}) != readings_of(station.live) # the piezo's rate changing: an event, the page fetches it -RATE, SOLAR, UVI = ("rainfall", "rain_rate"), ("solar_and_uvi", "solar"), ("solar_and_uvi", "uvi") - - -async def test_the_data_carries_the_past_hours_highest_of_the_wind_gust_rain_rate_sun_and_uv_and_the_gust_now(server, station): - """The dials' thin red hands: each one's reading's highest of the past hour (Wind: its gust), the higher of the file's (its minutes - and 5-minute readings: highest_on) and the reading now; with no file, the reading now; null with neither. And the gust now.""" +async def test_the_data_carries_todays_highest_of_the_wind_gust_rain_rate_sun_and_uv_and_the_gust_now(server, station): + """The dials' thin red hands: each one's reading's highest today (the station's day; Wind: its gust), its tile's Daily figure (Max; + the Wind's Gust), which counts the reading now in, so it rises with it; null with none. Nothing read from the file for it. And the + gust now.""" page = WebDashboard(server) - assert HOURLY == {"Wind": GUST, "Rain rate": RATE, "Solar radiation": SOLAR, "UV index": UVI} + assert RED_HANDS == {"Wind": "Gust", "Rain rate": "Max", "Solar radiation": "Max", "UV index": "Max"} + got = await page.data() # (the October evening: today's day rows, the sun down) + assert got["today_highs"] == {"Wind": 28.0, "Rain rate": 8.0, "Solar radiation": 700.0, "UV index": 6.0} and got["gust"] is None + tiles = {t["title"]: t for t in got["tiles"]} + assert all(got["today_highs"][t] == dict(zip(tiles[t]["columns"], tiles[t]["rows"]["Daily"]))[c] for t, c in RED_HANDS.items()) + station.highs_today({"wind_gust": 37.0, "rain_rate_max": 4.2, "solar_max": 820.0, "uv_max": 2.0}) + station.reads("wind", "wind_gust", "12") # (a gust now below today's highest) got = await page.data() - assert got["hour_highs"] == {"Rain rate": 0.0, "Solar radiation": 0.0, "UV index": 0.0, "Wind": None} and got["gust"] is None - station.reads("wind", "wind_gust", "12") # (no file: the readings now alone) + assert got["today_highs"] == {"Wind": 37.0, "Rain rate": 4.2, "Solar radiation": 820.0, "UV index": 2.0} and got["gust"] == 12.0 + station.reads("wind", "wind_gust", "41") # a gust above today's highest: it is the highest, + station.reads("solar_and_uvi", "uvi", "3") # as is the UV now got = await page.data() - assert got["hour_highs"]["Wind"] == 12.0 and got["gust"] == 12.0 - station.held({GUST: 37.0, RATE: 4.2, SOLAR: 820.0}) # the file's past hour: higher than now, but the UV's - station.reads("solar_and_uvi", "uvi", "2") + assert (got["today_highs"]["Wind"], got["today_highs"]["UV index"], got["gust"]) == (41.0, 3.0, 41.0) + station.values = {k: {d: v for d, v in days.items() if d != station.today or k not in ("rain_rate_max", "solar_max")} + for k, days in station.values.items()} # no day row today for the rain rate and the sun, + station.live = {k: v for k, v in station.live.items() if k != "rainfall"} # nor a rain rate now: null, its tile dimmed with the + station.eco._live = (time.time(), station.live) # month's (the sun's: its reading now, 0) got = await page.data() - assert got["hour_highs"] == {"Wind": 37.0, "Rain rate": 4.2, "Solar radiation": 820.0, "UV index": 2.0} and got["gust"] == 12.0 - station.reads("wind", "wind_gust", "41") # a gust above the past hour's: it is the highest - assert (await page.data())["hour_highs"]["Wind"] == 41.0 - station.held({}) # the peaks an hour old: the next highest, the readings now - assert (await page.data())["hour_highs"] == {"Wind": 41.0, "Rain rate": 0.0, "Solar radiation": 0.0, "UV index": 2.0} - station.live = json.loads(json.dumps(station.live)) # a reading now from over an hour ago: not counted - station.live["wind"]["wind_gust"]["time"] = str(int(time.time()) - HOUR_SECONDS - 120) - station.eco._live = (time.time(), station.live) - assert (await page.data())["hour_highs"]["Wind"] is None - - async def broken(*a): - raise OSError("disk") - station.eco.storage = NS(read=broken) # the file not read: the readings now - assert (await page.data())["hour_highs"]["UV index"] == 2.0 + assert got["today_highs"] == {"Wind": 41.0, "Rain rate": None, "Solar radiation": 0.0, "UV index": 3.0}, got["today_highs"] + assert today_highs([]) == {} station.reads("wind", "wind_gust", "9") assert readings_of(station.live) != readings_of({**station.live, "wind": {**station.live["wind"], "wind_gust": {"value": "10"}}}) -async def test_the_past_hours_highest_is_read_from_the_minutes_and_the_5_minute_readings_with_their_bands(tmp_path): - """highest_on: of a reading's minutes and 5-minute readings from start to end, each with the highest of its band, a band alone (a - 5-minute mark not fetched yet) too; nothing older or newer, nor a 30-minute reading; one with none left out.""" - from lib.storage import Storage - storage = Storage(tmp_path / "s.sqlite", TZ) - mac, now = "AA:BB", 1_794_279_900 - with storage.writer.transaction() as w: - w.put_minutes(mac, {"wind": {"wind_gust": {"unit": "km/h", "list": {str(now - 4000): "70", str(now - 3000): "33", str(now - 60): "21"}}}, - "solar_and_uvi": {"uvi": {"unit": "", "list": {str(now - 120): "3"}}}}, now) - w.put_ranges(mac, {"wind.wind_gust": {now - 900: (3, 20.0, 45.0)}, "solar_and_uvi.solar": {now - 600: (2, 400.0, 610.0)}}) - got = await storage.read(highest_on, mac, [GUST, SOLAR, UVI, RATE], now - 3600, now) - assert got == {GUST: 45.0, SOLAR: 610.0, UVI: 3.0} - assert await storage.read(highest_on, mac, [GUST], now - 600, now) == {GUST: 21.0} - storage.close() - - async def test_the_data_carries_todays_wind_rose_on_the_wind_direction_tile_read_from_the_file_and_kept_a_minute(server, station, monkeypatch, caplog): """The Wind direction tile's `rose`: the share of today's readings of the wind's direction (the station's day, in its zone; the @@ -250,12 +230,12 @@ async def test_the_data_carries_todays_wind_rose_on_the_wind_direction_tile_read assert [{k: v for k, v in t.items() if k != "rose"} for t in got["tiles"]] == [tile_json(t) for t in gauge_sheet.sheet( station.current(gauge_sheet.call(), {"fetch": False})).tiles] minutes = [10, 4, 2, 0, 30, 12, 6, 0, 0, 0, 3, 0, 0, 0, 5, 8] - station.held({}, minutes) + station.held(minutes) assert compass(await page.data())["rose"] == [] and web_dashboard.ROSE_SECONDS == 60 # (kept: read under a minute ago) page._rose = None got = compass(await page.data())["rose"] assert len(got) == 16 and got == [round(n / 80, 4) for n in minutes] and got[4] == 0.375, got - station.held({}, [0] * 16) # read again a minute on: none today + station.held([0] * 16) # read again a minute on: none today page._rose = (page._rose[0] - 61, *page._rose[1:]) assert compass(await page.data())["rose"] == [] @@ -685,7 +665,9 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl url = f"http://127.0.0.1:{port}/dashboard" monkeypatch.setattr(web_dashboard, "ROSE_SECONDS", 0) # (today's rose read again with each data: it changes below) station.reads("wind", "wind_gust", "12") - station.held({GUST: 37.0, RATE: 4.2, SOLAR: 820.0, UVI: 6.5}, ROSE) # (the past hour: higher than the readings now, all but 0; today's rose) + station.highs_today({"wind_gust": 37.0, "rain_rate_max": 4.2, "solar_max": 820.0, "uv_max": 6.5}) # (today's highest: above the + station.held(ROSE) # readings now, all but 0; today's rose) + wind = next(t for t in gauge_sheet.sheet(station.current(gauge_sheet.call(), {"fetch": False})).tiles if t.title == "Wind") station.reads("indoor", "temperature", "23.7") # an indoor sensor, served with MCP_DASHBOARD_INDOOR off: station.reads("indoor", "humidity", "47") # its tiles never drawn (the same tiles as with none) async with Serving(http_app(server, tokens=(TOKEN,), dashboard_indoor=False), port): @@ -700,8 +682,8 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl before = json.loads(await asyncio.wait_for(live.stdout.readline(), 60)) station.reads("outdoor", "temperature", "21.5") station.reads("wind", "wind_direction", "300") # (and the wind backs from the east to WNW) - station.held({GUST: 60.0, RATE: 4.2, SOLAR: 820.0, UVI: 6.5}, ROSE_LATER) # (and the past hour's highest gust rises, and - # today's rose turns to the west) + station.highs_today({"wind_gust": 60.0}) # (and today's highest gust rises, and today's + station.held(ROSE_LATER) # rose turns to the west) await server.publish_changes() live.stdin.write(b"go\n") await live.stdin.drain() @@ -710,7 +692,6 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl after = json.loads(out) sheet = gauge_sheet.sheet(Station().current(gauge_sheet.call(), {"fetch": False})).tiles n, kinds = len(sheet), [t.kind for t in sheet] - wind = next(t for t in gauge_sheet.sheet(station.current(gauge_sheet.call(), {"fetch": False})).tiles if t.title == "Wind") for name, (width, height) in SIZES.items(): got = report[name] assert got["errors"] == [], (name, got["errors"]) @@ -767,14 +748,14 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl compass_as_a_dial(z) rose_drawn(z, ROSE) assert (shots / f"dashboard-{name}-compass.png").exists() - # the dials with a thin red hand at the past hour's highest (Wind's gust, Rain rate's, Solar radiation's, UV's), over the dial + # the dials with a thin red hand at today's highest (Wind's gust, Rain rate's, Solar radiation's, UV's), over the dial # and the needle, under the hub; none on any other tile; the Wind's table: its highest speed, and its highest gust beside it hands = got["hands"] - assert {t for t, h in hands.items() if h} == set(HOURLY), hands + assert {t for t, h in hands.items() if h} == set(RED_HANDS), hands for title, value in {"Wind": 37.0, "Rain rate": 4.2, "Solar radiation": 820.0, "UV index": 6.5}.items(): h, tile = hands[title], next(t for t in sheet if t.title == title) assert h["turn"] == hand_turn(tile, value) and h["shown"], (name, title, h) - assert h["colour"] == look()["hour_hand"] and h["width"] <= 1.5 and h["needleWidth"] > 10 * h["width"], (name, title, h) + assert h["colour"] == look()["high_hand"] and h["width"] <= 1.5 and h["needleWidth"] > 10 * h["width"], (name, title, h) assert h["order"][0] < h["order"][1] < h["order"][2], (name, title, h) assert hands["Wind"]["heads"] == ["▲ Max", "» Gust"] and wind.columns == ("Max", "Gust"), hands["Wind"] assert hands["Wind"]["daily"] == [f"{v:.0f}" for v in wind.rows["Daily"]] and wind.rows["Daily"][1] >= 12, (hands["Wind"], wind) @@ -794,7 +775,7 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl rose_drawn(c, ROSE_LATER) # (today's rose redrawn in place with it) turns = c["turns"] assert all(t <= 99.01 or t >= 299.99 for t in turns) and any(t < 30 for t in turns) and any(t > 330 for t in turns), turns - # the Wind's red hand moved smoothly, frame by frame, from the past hour's highest gust before (37) to the new one (60) + # the Wind's red hand moved smoothly, frame by frame, from today's highest gust before (37) to the new one (60) windy = next(t for t in sheet if t.title == "Wind") h, frames = after["hands"]["Wind"], after["hands"]["frames"] assert h["turn"] == hand_turn(windy, 60.0) and frames[0] == turn_of(windy, 37.0) and frames[-1] == turn_of(windy, 60.0), h diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 28f2d42e..3e6d05c6 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -102,7 +102,7 @@ async function sizes(browser, url, shots, wanted) { }), })), errors }; await handsSettled(page); - report[name].hands = await handsLook(page); // the dials' thin red hands: the past hour's highest + report[name].hands = await handsLook(page); // the dials' thin red hands: today's highest await compassSettled(page); report[name].compass = await compassLook(page); // the wind's direction in the grid: its compass, no table // zoomed (Enter on the first tile): its look (box, title, text, table) and a screenshot (SHOTS/dashboard-NAME-zoomed.png) @@ -134,7 +134,7 @@ async function sizes(browser, url, shots, wanted) { // Each tile's red hand (null without one): its turn, shown or not, its colour and width, where it is among the dial's parts (after the // needle, before the hub: [needle, hand, hub] indexes), its drawn box's narrower side against the needle's; with the Wind tile's table const handsLook = (page) => page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#grid .tile")].map((t) => { - const hand = t.querySelector("svg .hour"), title = t.querySelector(".title").textContent; + const hand = t.querySelector("svg .high"), title = t.querySelector(".title").textContent; if (!hand) return [title, null]; const parts = [...t.querySelector("svg > g.gauge").children], line = hand.querySelector("path"); const hub = parts.filter((e) => e.tagName === "circle").pop(), needle = t.querySelector("svg > g.gauge > polygon"); @@ -146,7 +146,7 @@ const handsLook = (page) => page.evaluate(() => Object.fromEntries([...document. }))); // The red hands at rest (the opening's rise or a move over): none turned since the last look, 150 ms before, rather than a fixed wait const handsSettled = (page) => page.waitForFunction(() => { - const now = [...document.querySelectorAll("#grid .tile svg .hour")].map((h) => h.getAttribute("transform")).join("|"); + const now = [...document.querySelectorAll("#grid .tile svg .high")].map((h) => h.getAttribute("transform")).join("|"); const still = now && now === window.__hands; window.__hands = now; return still; @@ -200,9 +200,9 @@ async function live(browser, url) { await handsSettled(page); await page.evaluate(() => { window.__turns = []; - window.__hand = []; // (and the Wind's red hand, every frame: its past hour's highest gust rises) + window.__hand = []; // (and the Wind's red hand, every frame: today's highest gust rises) const needle = document.querySelector('.tile[data-kind="compass"] .needle'); - const wind = [...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === "Wind").querySelector("svg .hour"); + const wind = [...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === "Wind").querySelector("svg .high"); const sample = () => { window.__turns.push(Number(/rotate\(([-\d.]+)/.exec(needle.getAttribute("transform"))[1])); window.__hand.push(Number(/rotate\(([-\d.]+)/.exec(wind.getAttribute("transform"))[1])); @@ -1118,7 +1118,7 @@ async function weatherPage(browser, url, options = {}) { if ("rain_rate" in readings) data.rain_rate = readings.rain_rate; if ("gust" in readings) data.gust = readings.gust; // (the gust now, km/h) if (readings.asOf) data.as_of = { ...data.as_of, time: readings.asOf }; // (a new reading: its time) - if (readings.hour) Object.assign(data.hour_highs, readings.hour); // (the red hands' past hour) + if (readings.high) Object.assign(data.today_highs, readings.high); // (the red hands': today's highest) await route.fulfill({ response, json: data }); }); const page = await context.newPage(); @@ -1936,9 +1936,9 @@ async function lowMotion(browser, url, out) { .map((e) => getComputedStyle(e).transitionDuration).filter((d) => d.split(",").some((t) => parseFloat(t) > 0)).length); const hand = () => page.evaluate(() => { const t = [...document.querySelectorAll(".tile")].find((e) => e.querySelector(".title").textContent === "UV index"); - return t.querySelector("svg .hour").getAttribute("transform"); + return t.querySelector("svg .high").getAttribute("transform"); }); - const called = { "UV index": 11, Wind: 60, Temperature: -3, rain_rate: 2, Humidity: 97, "US AQI": 160, gust: 130, hour: { "UV index": 9 } }; + const called = { "UV index": 11, Wind: 60, Temperature: -3, rain_rate: 2, Humidity: 97, "US AQI": 160, gust: 130, high: { "UV index": 9 } }; await reads(called); // (the page asks at once: fetched LOW_EVERY after the last) out.called = { ...await seen(), hand: await hand() }; out.beads = await page.evaluate(() => { // (humidity's still frame: its biggest beads set off again, none elongating) @@ -2738,10 +2738,10 @@ const WEATHER = { })(); // reduced motion: no loop, one still, faint frame; the frames as ever const still = await weatherPage(browser, url, { context: { reducedMotion: "reduce" } }); - await still.reads({ "UV index": 11, Temperature: -4, hour: { "UV index": 9 } }); + await still.reads({ "UV index": 11, Temperature: -4, high: { "UV index": 9 } }); const stillHand = await still.page.evaluate(() => { // (the UV's red hand at once at its new highest: no frames for it) const t = [...document.querySelectorAll(".tile")].find((e) => e.querySelector(".title").textContent === "UV index"); - return t.querySelector("svg .hour").getAttribute("transform"); + return t.querySelector("svg .high").getAttribute("transform"); }); await still.page.waitForTimeout(500); out.still = { ...await weatherSeen(still.page), frames: await framesIn(still.page, 800), ink: await canvasInk(still.page), hand: stillHand, From 6ca73b7fe8e43de64af5d1a8406232ef3184ac6c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:07:05 +0000 Subject: [PATCH 094/146] Web dashboard: the compass's needle red (the red hands' red), over today's blue rose The needle's head and its hub's ring in HIGH_HAND (#FF3B30), keeping the dark edge and the short dim tail; the rose stays as it was, see-through in the needles' blue. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 8 ++++---- tests/test_web_dashboard.py | 11 ++++++----- tests/web_dashboard_browser.js | 2 +- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 0914c54c..74716d7b 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -3534,8 +3534,8 @@ // its compass point's share of today's readings, the longest ROSE_REACH of the radius; none with no data), the reading inside the // ring, below the hub ("99° E": the compass point the service gives, or, while the needle swings to it, the point it is passing), then // the face (one thin ring, fine ticks every 10 degrees and longer ones every 45, N, E, S and W, N in an accent colour) and the needle - // (pointing where the wind comes from, in degrees clockwise from north: a slim blade with a sharp head in the needles' colour and a - // short, dim, tapered tail) on a small hub. No table. + // (pointing where the wind comes from, in degrees clockwise from north: a slim blade with a sharp head in the red hands' red, over + // the blue rose, and a short, dim, tapered tail) on a small hub ringed in the same red. No table. const ROSE_REACH = 0.8, ROSE_HALF = 9; // the longest petal's reach (of the radius) and each petal's half-width (degrees) const pointOf = (deg) => L.points[Math.floor(((deg % 360) + 360 + 11.25) / 22.5) % 16]; // (direction.py sector()) // The needle pointing north from (cx, cy), its tip `reach` out ([x, y], ...): the head a slim blade to a sharp tip, widest at the hub; @@ -3565,9 +3565,9 @@ }); const needle = el("g", {class: "needle"}, svg); el("polygon", {points: points(stub(cx, cy, reach)), fill: ink(L.soft), "fill-opacity": 0.45, class: "tail"}, needle); - el("polygon", {points: points(blade(cx, cy, reach)), fill: ink(L.needle), stroke: L.bg, "stroke-width": 1.2, "paint-order": "stroke", + el("polygon", {points: points(blade(cx, cy, reach)), fill: ink(L.high_hand), stroke: L.bg, "stroke-width": 1.2, "paint-order": "stroke", "stroke-linejoin": "miter", class: "head"}, needle); - el("circle", {cx, cy, r: 6.5, fill: L.bg, stroke: ink(L.needle), "stroke-width": 2.5, class: "hub"}, svg); + el("circle", {cx, cy, r: 6.5, fill: L.bg, stroke: ink(L.high_hand), "stroke-width": 2.5, class: "hub"}, svg); // the rose: a petal per compass point with any share, a slim wedge from the centre to its share of the longest's reach const petals = (shares) => { rose.replaceChildren(); diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 8249aa3b..4e7f4b76 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -618,11 +618,12 @@ def rgb(colour: str) -> str: def one_end_to_read(compass: dict): - """The compass's needle (compassLook's, in its own px): its head a slim blade to a sharp tip in the needles' colour, solid; its tail - a short, dim taper of another colour; never two ends alike.""" + """The compass's needle (compassLook's, in its own px): its head a slim blade to a sharp tip in the red hands' red (not the rose's + blue), solid; its tail a short, dim taper of another colour; never two ends alike.""" head, tail = compass["ends"] - assert head["colour"] == rgb(look()["needle"]) and tail["colour"] != head["colour"], compass + assert head["colour"] == rgb(look()["high_hand"]) != rgb(look()["needle"]) and tail["colour"] != head["colour"], compass assert head["opacity"] == 1 and tail["opacity"] <= 0.6, compass + assert compass["hubColour"] == head["colour"], compass # (its hub ringed in the same red) assert head["length"] > 4 * tail["length"] and head["area"] > 3 * tail["area"] and head["width"] <= 12, compass # (slim) @@ -645,7 +646,7 @@ def compass_as_a_dial(c: dict): def rose_drawn(c: dict, minutes: list[int]): - """Today's rose as drawn (compassLook's petals): a petal for each compass point with any share, in the needles' colour, see-through, + """Today's rose as drawn (compassLook's petals): a petal for each compass point with any share, in the dials' needles' blue, see-through, its reach from the centre in proportion to its share, the longest 80% of the radius.""" total, most = sum(minutes), max(minutes) want = {POINTS[i]: n / total for i, n in enumerate(minutes) if n} @@ -732,7 +733,7 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl compass_as_a_dial(c) ring, head = c["ring"], c["head"] assert (head["left"] + head["right"]) / 2 > (ring["left"] + ring["right"]) / 2 + ring["width"] * 0.1 and abs((head["top"] + head["bottom"]) / 2 - (ring["top"] + ring["bottom"]) / 2) < ring["height"] * 0.1, c - # ... the end to read unmistakable: the head a slim sharp blade in the needles' colour, the tail a short, dim taper of another + # ... the end to read unmistakable: the head a slim sharp blade in the red hands' red, the tail a short, dim taper of another one_end_to_read(c) # ... today's rose under it all, a petal per compass point blown from, as long as its share (the longest 80% of the radius) rose_drawn(c, ROSE) diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 3e6d05c6..4d6f2994 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -166,7 +166,7 @@ const compassLook = (page) => page.evaluate(() => { pointColours: [...t.querySelectorAll("svg text.point")].map((e) => e.getAttribute("fill")), table: t.querySelectorAll(".unit, .chip, .figure, .tablearea").length, zoomed: document.body.classList.contains("zoomed"), shown: !t.inert, box: rect(t), title: rect(t.querySelector(".title")), texts: [...t.querySelectorAll("svg text")].map(rect), - ring: rect(ring), head: rect(t.querySelector(".needle .head")), circle: circle(ring), dialCircle: circle(dialRing), + ring: rect(ring), head: rect(t.querySelector(".needle .head")), hubColour: getComputedStyle(t.querySelector("svg .hub")).stroke, circle: circle(ring), dialCircle: circle(dialRing), dialRing: dialRing && rect(dialRing), ringStroke: Number(ring.getAttribute("stroke-width")), layers: [...t.querySelector("svg g.gauge").children].map((e) => e.getAttribute("class") || e.tagName), readingAt: Math.hypot(Number(reading.getAttribute("x")) - cx, Number(reading.getAttribute("y")) - cy), From da91021ec32eeed025e67686c7f5b0220fed45e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:10:12 +0000 Subject: [PATCH 095/146] Web dashboard: the compass's N like E, S and W; no frame on mouseover; the Wind's Max grey and Gust red; a bigger grip - The compass's N in the letters' colour (COMPASS_NORTH gone); the rose stays blue, the needle red. - A tile's frame no longer shows on mouseover: only picked up, with the keyboard's focus, or red; the grip and x still show on hover. - The Wind table's heads: Max grey (GUST_CHIP), Gust the red hand's red (HIGH_HAND) (WIND_CHIPS); every other tile's Max stays red. - The grip 15x30 px (was 10x15), dots still 5 px apart: three across, six down, in the same corner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/gauge_look.py | 6 +++--- lib/web_dashboard.html | 12 ++++++------ tests/test_web_dashboard.py | 20 +++++++++++++++----- tests/web_dashboard_browser.js | 25 ++++++++++++++++++++++++- 4 files changed, 48 insertions(+), 15 deletions(-) diff --git a/lib/gauge_look.py b/lib/gauge_look.py index 0c356105..cf7822c2 100644 --- a/lib/gauge_look.py +++ b/lib/gauge_look.py @@ -16,6 +16,7 @@ MARKS = {"Max": "▲", "Min": "▼", "Total": "+", "Gust": "»"} # in front of a column's name HIGH_HAND = "#FF3B30" # a dial's thin red hand: its reading's highest today (the web page's: wind's gust, rain rate, sun, UV) HIGH_HAND_WIDTH = 1.4 # ... how wide (pixels) +WIND_CHIPS = {**CHIPS, "Max": GUST_CHIP, "Gust": HIGH_HAND} # the web page's Wind table: its Max grey, its Gust its red hand's red FILL = "#D32F27" # the thermometer's mercury TUBE_HALF, BULB_RADIUS = 28, 38 # the thermometer: half the tube's width, the bulb's radius (pixels, to the outline) MERCURY_GAP = 7 # the gap between the outline and the red, the same round the bulb as up the tube @@ -25,7 +26,6 @@ COMPASS = (240, 188, 130) # the wind's direction, a compass: its centre and outline's radius (above the table's place: it has none) COMPASS_LABEL_Y = 346 # ... its reading ("99° E") under it COMPASS_BAND = "#262E34" # ... its ring, under the ticks and the letters N, E, S and W -COMPASS_NORTH = "#E5534B" # the web page's compass: its N, a small accent WATER = "#4FB3F6" # the rain beaker's water NEEDLE = "#3E86C0" CELL_W, CELL_H, MARGIN = 480, 575, 20 @@ -66,11 +66,11 @@ def share(tile: Tile, value: float) -> float: def look() -> dict: """The figures above as JSON, for the web page to draw with.""" - return {"bg": BG, "ink": INK, "soft": SOFT, "chip": CHIP, "chips": CHIPS, "marks": MARKS, "fill": FILL, "water": WATER, + return {"bg": BG, "ink": INK, "soft": SOFT, "chip": CHIP, "chips": CHIPS, "wind_chips": WIND_CHIPS, "marks": MARKS, "fill": FILL, "water": WATER, "needle": NEEDLE, "high_hand": HIGH_HAND, "high_hand_width": HIGH_HAND_WIDTH, "tube_half": TUBE_HALF, "bulb_radius": BULB_RADIUS, "mercury_gap": MERCURY_GAP, "bar_width": BAR_WIDTH, "bar_gap": BAR_GAP, "ring_outer": RING_OUTER, "band_width": BAND_WIDTH, "label_radius": LABEL_RADIUS, "cell": [CELL_W, CELL_H], "compass": list(COMPASS), - "compass_label_y": COMPASS_LABEL_Y, "compass_band": COMPASS_BAND, "compass_north": COMPASS_NORTH, "points": list(POINTS), + "compass_label_y": COMPASS_LABEL_Y, "compass_band": COMPASS_BAND, "points": list(POINTS), "fade": FADE, "sweep": SWEEP, "start": START, "rows": list(ROWS)} diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 74716d7b..86add73b 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -31,13 +31,12 @@ #grid { display: grid; justify-content: center; align-content: center; padding: var(--pad, 8px); padding-bottom: calc(var(--pad, 8px) + var(--status, 18px)); min-height: 100%; } /* (room under the tiles for the status line) */ /* A tile: its own background clear (whatever is behind the page shows through it), its foreground opaque; a thin opaque frame - (::before, inset, so neighbours don't share a line), seen only on mouseover, picked up, focused or red. Its gauge can be dragged (user-select none), its + (::before, inset, so neighbours don't share a line), seen only picked up, focused or red (not on mouseover). Its gauge can be dragged (user-select none), its title, reading and table keep their text selectable. transform-origin 0 0: the reflow animations' scale is from the corner. Its contents are placed by its width alone (cqw), so the zoomed view, its box only their top (the title and gauge), shows them alike. */ .tile { position: relative; container-type: inline-size; overflow: hidden; background: transparent; transform-origin: 0 0; transition: opacity 0.9s ease, transform 0.22s ease; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; } .tile::before { content: ""; position: absolute; inset: 0.9cqw; border: 1px solid transparent; border-radius: 2.5cqw; pointer-events: none; } - @media (hover: hover) { .tile:hover::before { border-color: #262E34; } } /* (its frame unseen until the mouse is over it) */ .tile.faded { opacity: var(--fade, 0.4); } /* no reading now: dimmed towards the card (as the PNG blends its colours) */ .tile svg { position: absolute; left: 0; top: 0; width: 100%; display: block; } /* (its height: by the width, drawTile()) */ .tile svg text { font-family: inherit; } @@ -47,7 +46,7 @@ .chip { border-radius: 1.875cqw; } /* The grip and the × (hide), shown only on mouseover, on a tile picked up, or (touch) on one long-pressed and let go in place */ .grip, .close { position: absolute; top: 6px; z-index: 1; opacity: 0; pointer-events: none; transition: opacity 0.15s ease; } - .grip { left: 8px; width: 10px; height: 15px; cursor: grab; + .grip { left: 8px; width: 15px; height: 30px; cursor: grab; /* (dots 5px apart: three across, six down) */ background: radial-gradient(circle, var(--soft) 1.1px, transparent 1.5px) 0 0 / 5px 5px; } .close { right: 5px; width: 22px; height: 22px; padding: 0; border: 0; border-radius: 50%; background: none; color: var(--soft); font: 18px/22px system-ui, sans-serif; cursor: pointer; } @@ -3533,7 +3532,7 @@ // neighbours, grid or zoomed). Layers, bottom to top: today's wind rose (rose: 16 soft petals in the needles' colour, each as long as // its compass point's share of today's readings, the longest ROSE_REACH of the radius; none with no data), the reading inside the // ring, below the hub ("99° E": the compass point the service gives, or, while the needle swings to it, the point it is passing), then - // the face (one thin ring, fine ticks every 10 degrees and longer ones every 45, N, E, S and W, N in an accent colour) and the needle + // the face (one thin ring, fine ticks every 10 degrees and longer ones every 45, N, E, S and W, all four alike) and the needle // (pointing where the wind comes from, in degrees clockwise from north: a slim blade with a sharp head in the red hands' red, over // the blue rose, and a short, dim, tapered tail) on a small hub ringed in the same red. No table. const ROSE_REACH = 0.8, ROSE_HALF = 9; // the longest petal's reach (of the radius) and each petal's half-width (degrees) @@ -3561,7 +3560,7 @@ el("path", {d: long, stroke: ink(L.soft), "stroke-width": lw(1.8), "stroke-linecap": "round", class: "ticks long"}, face); ["N", "E", "S", "W"].forEach((name, i) => { const [x, y] = polar(cx, cy, r - 34, 90 - 90 * i); - text(face, x, y, name, 22, ink(i ? L.soft : L.compass_north), "middle", "600").classList.add("point"); + text(face, x, y, name, 22, ink(L.soft), "middle", "600").classList.add("point"); }); const needle = el("g", {class: "needle"}, svg); el("polygon", {points: points(stub(cx, cy, reach)), fill: ink(L.soft), "fill-opacity": 0.45, class: "tail"}, needle); @@ -3621,8 +3620,9 @@ const left = 60, top = 378, w = 128, h = 38, gap = 4; const xs = tile.columns.map((_, i) => left + (w + gap) * (i + 1)); place(box, left, top, w, h, 17, tile.unit, "unit", {color: ink(L.ink), fontWeight: 700}); + const chips = tile.columns.includes("Gust") ? L.wind_chips : L.chips; // (the Wind's: its Max grey, its Gust its red hand's red) tile.columns.forEach((name, i) => - place(box, xs[i], top, w, h, 19, `${L.marks[name]} ${name}`, "chip head", {background: ink(L.chips[name]), color: ink("#FFFFFF"), fontWeight: 700})); + place(box, xs[i], top, w, h, 19, `${L.marks[name]} ${name}`, "chip head", {background: ink(chips[name]), color: ink("#FFFFFF"), fontWeight: 700})); L.rows.forEach((name, r) => { const y = top + (r + 1) * (h + 10); place(box, left, y, w, h, 19, name, "chip row", {background: ink(L.chip), color: ink(L.soft)}); diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 4e7f4b76..334e5707 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -43,7 +43,7 @@ from lib.service.context import Context from lib.service.names import Catalogue from lib.ecowitt.reads import directions_on -from lib.gauge_look import START, SWEEP +from lib.gauge_look import CHIPS, GUST_CHIP, MAX_CHIP, START, SWEEP from lib.web_dashboard import (DESCRIPTION, ICON, ICON_URL, PAGE, RED_HANDS, WebDashboard, air_readings_of, rain_rate_of, readings_of, today_highs) from tests.chart_samples import _air, _station @@ -723,12 +723,12 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl tile, glass = got["zoomed"]["box"], got["zoomed"]["glass"] # (the first tile, Temperature) zoomed: the glass with it assert len(glass) == 1 and all(g["height"] > 0 and tile["left"] <= g["left"] and g["right"] <= tile["right"] for g in glass) assert glass[0]["height"] > tile["width"] * 0.2 and glass[0]["width"] < glass[0]["height"] * 0.06, (glass, tile) - # the wind's direction, a compass: N, E, S and W named (N in its accent), its needle's head turned to where the wind comes + # the wind's direction, a compass: N, E, S and W named (all four alike: no red N), its needle's head turned to where the wind comes # from (99°, east), its reading "99° E" (the service's compass point); no table, the same size as its neighbours c, rects = got["compass"], got["rects"] assert (c["label"], c["reading"], c["turn"], c["faded"]) == ("Wind direction 99° E", "99° E", "rotate(99.00 240 203)", False), c assert c["points"] == ["N", "E", "S", "W"] and c["table"] == 0, c - assert c["pointColours"] == [look()["compass_north"], *[look()["soft"]] * 3], c + assert c["pointColours"] == [look()["soft"]] * 4 and "compass_north" not in look(), c assert any(near(c["box"], r, 0.5) for r in rects) and len({(round(r["width"]), round(r["height"])) for r in rects}) == 1, c compass_as_a_dial(c) ring, head = c["ring"], c["head"] @@ -759,6 +759,13 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl assert h["colour"] == look()["high_hand"] and h["width"] <= 1.5 and h["needleWidth"] > 10 * h["width"], (name, title, h) assert h["order"][0] < h["order"][1] < h["order"][2], (name, title, h) assert hands["Wind"]["heads"] == ["▲ Max", "» Gust"] and wind.columns == ("Max", "Gust"), hands["Wind"] + # ... its heads: Max grey, Gust in the red hand's very red (the hand and its column go together); every other tile's Max red + assert hands["Wind"]["headColours"] == [rgb(GUST_CHIP), rgb(look()["high_hand"])], hands["Wind"] + others = got["headColours"] + assert others["Wind"] == [["▲ Max", rgb(GUST_CHIP)], ["» Gust", rgb(look()["high_hand"])]], others + assert any(t != "Wind" and heads for t, heads in others.items()), others + assert all(c == rgb(CHIPS[n.split()[-1]]) for t, heads in others.items() if t != "Wind" for n, c in heads), others + assert all(c == rgb(MAX_CHIP) for t, heads in others.items() if t != "Wind" for n, c in heads if n.endswith("Max")), others assert hands["Wind"]["daily"] == [f"{v:.0f}" for v in wind.rows["Daily"]] and wind.rows["Daily"][1] >= 12, (hands["Wind"], wind) for name in ("tablet-landscape", "tablet-portrait", "desktop"): # these fit every tile without scrolling got = report[name] @@ -913,6 +920,8 @@ async def test_tiles_are_dragged_to_reorder_hidden_by_the_x_or_the_remove_zone_k assert got["errors"] == [] and got["initial"] == default, got["errors"] # mouseover: the grip and the × on the tile under the mouse only assert got["hover"] == [{"grip": "0", "close": "0"}, {"grip": "1", "close": "1"}, {"grip": "0", "close": "0"}] + # the grip: 15 by 30 px (dots 5 px apart: three across, six down), in the tile's top left corner + assert got["grip"] == {"width": 15, "height": 30, "left": 8, "top": 6, "dots": "5px 5px"}, got["grip"] # dragged from its gauge: the others make room as it goes (transforms), the remove zone shows; the order kept assert got["during"] == {"zone": "none", "over": False, "dragging": True, "moved": ["Humidity", "Atmospheric pressure"]} reordered = moved(default, "Temperature", "Atmospheric pressure") @@ -950,9 +959,10 @@ async def test_tiles_are_dragged_to_reorder_hidden_by_the_x_or_the_remove_zone_k assert look_["background"] == "rgba(0, 0, 0, 0)" and look_["image"] == "none" and look_["grid"] == "rgba(0, 0, 0, 0)" assert look_["opacity"] == "1" and look_["body"] == "rgb(20, 25, 29)" assert all(look_[k].startswith("rgb(") for k in ("title", "reading")) and look_["frameWidth"] == "1px", look_ - # the frame unseen until the mouse is over its tile, then on that tile only + # the frame unseen, the mouse over its tile too; shown while it is picked up, and with the keyboard's focus assert look_["frame"] == "rgba(0, 0, 0, 0)", look_ - assert got["hoverFrames"] == ["rgba(0, 0, 0, 0)", "rgb(38, 46, 52)", "rgba(0, 0, 0, 0)"], got["hoverFrames"] + assert got["hoverFrames"] == ["rgba(0, 0, 0, 0)"] * 3, got["hoverFrames"] + assert got["shownFrames"] == {"lifted": "rgb(90, 102, 112)", "focused": rgb(look()["soft"]), "after": "rgba(0, 0, 0, 0)"}, got["shownFrames"] # the strip's reading time with a device's reading over an hour old ("stale", its data's devices altered on the way): both fresh, # as ever; one stale, its name and own time first, greyed out, then the fresh one's; both stale (or the only device), all greyed out stale = got["stale"] diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 4d6f2994..9d4a112f 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -103,6 +103,8 @@ async function sizes(browser, url, shots, wanted) { })), errors }; await handsSettled(page); report[name].hands = await handsLook(page); // the dials' thin red hands: today's highest + report[name].headColours = await page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#grid .tile")].map((t) => // every + [t.querySelector(".title").textContent, [...t.querySelectorAll(".chip.head")].map((e) => [e.textContent, getComputedStyle(e).backgroundColor])]))); // table's heads await compassSettled(page); report[name].compass = await compassLook(page); // the wind's direction in the grid: its compass, no table // zoomed (Enter on the first tile): its look (box, title, text, table) and a screenshot (SHOTS/dashboard-NAME-zoomed.png) @@ -142,6 +144,7 @@ const handsLook = (page) => page.evaluate(() => Object.fromEntries([...document. width: Number(line.getAttribute("stroke-width")), needleWidth: needle.getBBox().width, order: [parts.indexOf(needle), parts.indexOf(hand), parts.indexOf(hub)], heads: title === "Wind" ? [...t.querySelectorAll(".chip.head")].map((e) => e.textContent) : undefined, + headColours: title === "Wind" ? [...t.querySelectorAll(".chip.head")].map((e) => getComputedStyle(e).backgroundColor) : undefined, daily: title === "Wind" ? [...t.querySelectorAll(".figure")].slice(0, 2).map((e) => e.textContent) : undefined }]; }))); // The red hands at rest (the opening's rise or a move over): none turned since the last look, 150 ms before, rather than a fixed wait @@ -341,10 +344,30 @@ async function arranged(browser, url, out, allErrors) { // mouseover: the grip and the × show on the tile under the mouse only await page.mouse.move(...await at(page, "Humidity", 0.5, 0.4)); await calm(page); - // mouseover: the frame too, on the tile under the mouse only (unseen otherwise) + // mouseover: no frame, the tile under the mouse too (shown only picked up, or with the keyboard's focus) out.hoverFrames = await page.evaluate(() => [...document.querySelectorAll(".tile")].slice(0, 3).map((t) => getComputedStyle(t, "::before").borderTopColor)); out.hover = await page.evaluate(() => [...document.querySelectorAll(".tile")].slice(0, 3).map((t) => ({ grip: getComputedStyle(t.querySelector(".grip")).opacity, close: getComputedStyle(t.querySelector(".close")).opacity }))); + // the grip under the mouse: its size and place in its tile (px), its dots' spacing + out.grip = await page.evaluate(() => { + const t = [...document.querySelectorAll(".tile")][1], g = t.querySelector(".grip"), r = g.getBoundingClientRect(), b = t.getBoundingClientRect(); + return { width: r.width, height: r.height, left: r.left - b.left, top: r.top - b.top, dots: getComputedStyle(g).backgroundSize }; + }); + // the frame shown on the tile under the mouse picked up, then (the mouse gone) with the keyboard's focus, then neither + const frameOf = (title) => page.evaluate((title) => getComputedStyle([...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === title), "::before").borderTopColor, title); + const humidity = (how) => page.evaluate((how) => [...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === "Humidity").classList[how]("lifted"), how); + out.shownFrames = {}; + await humidity("add"); + out.shownFrames.lifted = await frameOf("Humidity"); + await humidity("remove"); + await page.mouse.move(1, 1); + await page.keyboard.press("Shift"); // (the keyboard in use: the focus seen) + await page.evaluate(() => [...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === "Humidity").focus()); + out.shownFrames.focused = await frameOf("Humidity"); + await page.evaluate(() => document.activeElement.blur()); + out.shownFrames.after = await frameOf("Humidity"); + await page.mouse.move(...await at(page, "Humidity", 0.5, 0.4)); + await calm(page); // a drag from the gauge: Temperature to Atmospheric pressure's place, the others making room meanwhile out.during = await mouseDrag(page, await at(page, "Temperature", 0.85, 0.3), await at(page, "Atmospheric pressure", 0.5, 0.4), () => midDrag(page)); out.dragged = await titles(page); From dfc0075f71909b65cbdf1abf411c14582659ecc3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:39:10 +0000 Subject: [PATCH 096/146] Web dashboard: the humidity's fog cheaper to repaint; a big bead's pop a size bigger, not a dot The fog's dither and each pixel's start (where the fog forms first and clears last) worked out once a window size, not on every repaint; a pixel's fog worked out once in look(); clearing, only the pixels the clearing front has passed are repainted (the pixels kept in bins by their start), not the whole fog. Fog repaint frames about 4.2 ms -> 4.0 ms forming; while clearing the frame mean 1.3 ms -> 0.9 ms and repaint frames 3.9 ms -> 3.2 ms. Fix: a bead bigger than the sprite table (r over 4.5) was drawn a single pixel while it popped after a snap; its pop is now a size bigger (sprite(r + 0.5)), its size looked up in one place (sizeOf). Tidier: the fog's unread level and each bead's unread merged count gone; step() counts rain and tiny beads in one pass; one capped log helper for the latest-n lists; settled() for a bead shown at once (the random draws in the same streams, the same order); one streak-coverage formula in wipe(); account()'s test statistics with fewer calls. Every bead, trail and canvas fingerprint the same as before (humidity, humidity2; humidity2 with heavy rain too but for trail pixels refreshed by their sweep rather than the clearing's repaint, the same within a second). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 146 ++++++++++++++++++++++------------------- 1 file changed, 78 insertions(+), 68 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 86add73b..7dc1f637 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -1309,6 +1309,7 @@ const GONE = 0.03; // a bead's water this little: gone (r about 0.3) const BORN = [0.5, 0.6]; // a bead condensing: its radius, tiny (a px: two of them together small, r 0.63 or more) const TINY = 0.61; // a condensed bead this small or less: tiny, never running (see snaps()) + const DROPLET = BORN[0] + 0.05; // a splash's droplet left on the glass: its radius (tiny) const RUN_R = 1.4; // a bead runs only this big or bigger (about sixteen tiny ones' water); smaller, it stays put // ... (growing, keeping or shrinking as its glass has it, snapping as tiny ones do) const SNAP = 1; // px between two beads' edges or less (a pixel's gap), one of them tiny: they snap together @@ -1390,12 +1391,15 @@ return "2"; }).join("")); } + const LARGEST = SIZES[SIZES.length - 1] + 0.01; + const sizeOf = (r) => { let k = 0; while (k < SIZES.length - 1 && SIZES[k] < r - 0.01) k++; return k; }; // (its size in SIZES, up to LARGEST) const sprite = (r) => { - if (r <= SIZES[SIZES.length - 1] + 0.01) return beads[Math.max(0, SIZES.findIndex((size) => size >= r - 0.01))]; + if (r <= LARGEST) return beads[sizeOf(r)]; const w = Math.ceil(2 * r - 0.01); if (!grown.has(w)) grown.set(w, mapped(rowsFor(w), GLASS)); return grown.get(w); }; + const popped = (r) => (r <= LARGEST ? beads[Math.min(SIZES.length - 1, sizeOf(r) + 1)] : sprite(r + 0.5)); // (its pop: a size bigger) // A bead elongated along its path, s (0-1) of the most (STRETCH): a body row (below its glint, above its lower crescent) repeated, // a column just right of its middle taken out (never its glint or rim), keeping its water; the same plump rounded lower edge, no // point. Quantized to whole rows and columns, each kept (a few levels a size) @@ -1406,7 +1410,7 @@ if (rows <= 0) return base; const cols = Math.min(w - 3, Math.round(w - w * h / (h + rows))), key = `${w}x${h}+${rows}-${cols}`; if (!stretched.has(key)) { - let art = r <= SIZES[SIZES.length - 1] + 0.01 ? BEADS[beads.indexOf(base)] : rowsFor(w); + let art = r <= LARGEST ? BEADS[beads.indexOf(base)] : rowsFor(w); for (let c = 0; c < cols; c++) { const n = art[0].length, at = (n >> 1) + (n & 1); art = art.map((row) => row.slice(0, at) + row.slice(at + 1)); @@ -1443,26 +1447,30 @@ // (the tiny beads still on the glass, shown in full: drawn once on their own canvas, dots, kept till they go: dotted, each's px) let dots = null; const dotted = new Map(); - // The fog: each pixel's thickness at most (base: even, a little thicker at the edges), when it forms and clears (ring: 0 the - // middle, 1 the edges; it forms there first and clears there last); how far it has formed (cover, 0-1) and how thick (dense, - // 0-1); its canvas and image, as painted last (at drawn: [cover, dense]; key: what each pixel shows there, see look()) - let base = null, ring = null, cover = 0, dense = 0, drawn = [0, 0], layer = null, img = null, key = null; + // The fog: each pixel's thickness at most (base: even, a little thicker at the edges), when it forms and clears (starts: the + // cover it starts forming at there, 0 at the edges to 0.65 in the middle: formed there first, cleared there last), its + // dither (dith); how far it has formed (cover, 0-1) and how thick (dense, 0-1); its canvas and image, as painted last (at + // drawn: [cover, dense]; key: what each pixel shows there, see look()). (order: the pixels by their start, from[k] the first + // in bin k of BINS (binOf): those a clearing front passes looked up) + let base = null, starts = null, dith = null, order = null, from = null, cover = 0, dense = 0, drawn = [0, 0], layer = null, img = null, key = null; // The trails: each pixel's, on the trails' own clock (`clock`, its pace `hasten` for the tests): when it's gone (till) and how long // it lasts all told (life), so how fresh it is now (wetOf, 1 just left, 0 gone); on the list or not. How it looks (as left: see // wipe()): on clear glass, its part in the thin streak (part: none, film, grime, glint, a droplet or a droplet's spark) and how // thick the streak is there (thick, 0-255: the thin parts dry first); through fog, how near its ragged edge (rim, 0-255: the fog // coming back there first) and the fog left unwiped there (smear: 0 none, 128 faint, 255 a little more: a residue streak's) let till = null, life = null, listed = null, ghost = null, part = null, thick = null, rim = null, smear = null, trails = [], sweep = 0, clock = 0, hasten = 1, swept = 0; - let dirty = null, painting = 0, level = 0, fresh = 0, quiet = false; + let dirty = null, painting = 0, fresh = 0, quiet = false; // (for the tests, as Sky.state() gives them) const seen = {merges: 0, merged: [], absorbed: [], left: [], ranOff: 0, shrunk: 0, faded: 0, largest: 0, born: [], first: null, dried: 0, landed: 0, rainMost: 0, snaps: 0, splashes: [], joined: 0, joins: [], restarts: 0, stretches: 0, glass: [0, 1, 2].map(() => ({px: 0, s: 0, band: 0, gained: 0, lost: 0, moves: 0, all: 0, norm: 0, pace: 0})), // (px, s, band: r 1.8-3.2) sizes: [0, 1, 2, 3, 4].map(() => [0, 0])}; // (on fog: px and s, by size) const BANDS = [1, 1.6, 2.4, 3.2]; + const log = (list, v, most) => { list.push(v); if (list.length > most) list.shift(); }; // (the latest `most` kept) const heightOf = (r) => sprite(r).height; const thickness = (v) => 0.5 + 0.5 * v; // the fog at a level (90 %: 0, 100 %: 1), at most - const front = (i, c) => clamp((c - (1 - ring[i]) * 0.65) / 0.35, 0, 1); // how far the fog has formed at a pixel (c: cover) + const front = (i, c) => clamp((c - starts[i]) / 0.35, 0, 1); // how far the fog has formed at a pixel (c: cover) + const BINS = 512, binOf = (v) => clamp(Math.floor(v / 0.65 * BINS), 0, BINS - 1); const wetOf = (i) => (listed[i] ? Math.max(0, (till[i] - clock) / life[i]) : 0); // how fresh a trail is there // How far the fog has come back over a trail's pixel (0 wiped clear, 1 as if never wiped): clear while it's fresh (CRISP), then // back gradually; at its ragged edges sooner (from the start right at them), so it closes in from the edges unevenly @@ -1480,7 +1488,7 @@ return f >= FOG_AT ? FOGGY : DRY; }; function grain() { // the fog's pattern for the window's size: a fairly even haze, gently varied, a little denser at the edges - base = new Float32Array(W * H); ring = new Float32Array(W * H); + base = new Float32Array(W * H); starts = new Float64Array(W * H); dith = new Float32Array(W * H); for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { const u = x / Math.max(1, W - 1), v = y / Math.max(1, H - 1), su = Math.min(u, 1 - u), i = y * W + x; const side = Math.max(0, 1 - su / 0.2), low = Math.max(0, 1 - (1 - v) / 0.22), high = 0.55 * Math.max(0, 1 - v / 0.1); @@ -1490,10 +1498,18 @@ let b = 0.36 + 0.26 * edge + (soft - 0.5) * 0.15 + (fine - 0.5) * 0.06; if (y < 2) b = 0; else if (y < 6) b *= (y - 1) / 5; // (none along the top edge) base[i] = clamp(b, 0, 1); - ring[i] = clamp(0.5 * Math.max(Math.abs(2 * u - 1), Math.abs(2 * v - 1)) + 0.5 * edge + (noise(x / 9, y / 9, 1 << 20, 23) - 0.5) * 0.3, 0, 1); + const ring = Math.fround(clamp(0.5 * Math.max(Math.abs(2 * u - 1), Math.abs(2 * v - 1)) + 0.5 * edge + (noise(x / 9, y / 9, 1 << 20, 23) - 0.5) * 0.3, 0, 1)); + starts[i] = (1 - ring) * 0.65; // (ring: 0 the middle, 1 the edges) + dith[i] = dither(x, y); } + from = new Uint32Array(BINS + 1); order = new Uint32Array(W * H); + for (let i = 0; i < W * H; i++) from[binOf(starts[i]) + 1]++; + for (let k = 0; k < BINS; k++) from[k + 1] += from[k]; + const next = from.slice(0, BINS); + for (let i = 0; i < W * H; i++) order[next[binOf(starts[i])]++] = i; } const LIFT = Float32Array.from({length: 257}, (_, j) => (j / 256) ** 0.8); // (a thin haze still seen: t ** 0.8, looked up) + const fogShade = (t, i) => Math.min(FOG.length - 1, Math.floor(LIFT[(t * 256) | 0] * FOG.length + dith[i] - 1)); // (shadeOf, its dither kept) // A trail's looks, each in WET shades (faint to fresh), [colour, alpha at the faintest, at the freshest]: on clear glass a thin wet // film, greyish; grime, darker, along its edge here and there; a glint now and then; a tiny droplet left on it, now and then // its spark (none in a trail through the fog) @@ -1507,11 +1523,11 @@ // shade, the next in the streak's middle where the fog's thick), never a droplet or a speck. On clear glass // (no fog to wipe): its thin streak, each pixel there while the trail is fresher than the streak there is thin (the thin parts and // its ends going first), fainter as it dries - function look(i, x, y) { - const t = base[i] > 0 ? fogOf(i, drawn[0], drawn[1], true) : 0; - const p = listed[i] ? part[i] : 0, wet = p ? wetOf(i) : 0, full = listed[i] && base[i] > 0 ? fogOf(i, drawn[0], drawn[1], false) : 0; + function look(i) { + const full = base[i] > 0 ? fogOf(i, drawn[0], drawn[1], false) : 0, t = listed[i] ? full * refog(i) : full; // (wiped; not) + const p = listed[i] ? part[i] : 0, wet = p ? wetOf(i) : 0; if (p >= DROP && wet > 0 && full < FOG_AT && t <= 0.6 * full) return showing(p, clamp(Math.ceil(wet * WET), 1, WET)); // (clear glass only) - if (t > 0) { const s = shadeOf(LIFT[(t * 256) | 0], x, y, FOG.length); if (s >= 0) return 1 + s; } + if (t > 0) { const s = fogShade(t, i); if (s >= 0) return 1 + s; } if (!listed[i]) return 0; if (full >= FOG_AT) return smear[i] ? 1 + (smear[i] === 255 && full > 0.4 ? 1 : 0) : 0; // (a streak of residue, or wiped clean) const q = wet * (1 - Math.min(1, full / 0.1)), s = thick[i] / 255; // (clear glass: no fog wiped) @@ -1519,7 +1535,7 @@ return showing(p, Math.min(WET, Math.max(1, Math.ceil(q * (0.45 + 0.55 * s) * 1.2 * WET)))); } function put(i, x = i % W, y = (i / W) | 0) { // a pixel of the fog's image, as it is now (as painted last: drawn) - const k = look(i, x, y); + const k = look(i); if (k === key[i]) return; key[i] = k; const c = SHOWS[k], d = img.data, j = i * 4; @@ -1531,9 +1547,11 @@ if (dirty && !quiet) layer.getContext("2d").putImageData(img, 0, 0, dirty[0], dirty[1], dirty[2] - dirty[0] + 1, dirty[3] - dirty[1] + 1); if (!quiet) dirty = null; } - function paint() { // the fog painted whole, as it is now + function paint() { // the fog painted as it is now: whole; or clearing (as thick, less formed), the pixels its front has passed since + const was = drawn[0], clearing = dense === drawn[1] && cover < was; drawn = [cover, dense]; - for (let y = 0, i = 0; y < H; y++) for (let x = 0; x < W; x++, i++) put(i, x, y); + if (clearing) for (let j = from[binOf(cover - 0.36)]; j < from[binOf(was + 0.01) + 1]; j++) put(order[j]); // (front 0 to 1 over 0.35) + else for (let y = 0, i = 0; y < H; y++) for (let x = 0; x < W; x++, i++) put(i, x, y); flush(); } // A trail left at (x, y): fresh (v: 1, or a little less at its sides, gone sooner), lasting `span` s all told; its looks (p: its @@ -1569,30 +1587,32 @@ const rest = b.rested || 0; b.rested = 0; const blob = rest > 0.35 ? 0.9 : 0; - const sway = (noise(y / 11, id * 3 + 1, 1 << 20, 64) - 0.5) * Math.max(0, w - 3) * 0.55, at = mid + sway; + const sway = (noise(y / 11, id * 3 + 1, 1 << 20, 64) - 0.5) * Math.max(0, w - 3) * 0.55, sx = mid + sway; // (the streak's middle) let wide = broken && !blob ? 0 : clamp(Math.min(1.35, Math.max(0.8, w * 0.2)) * (0.25 + 1.4 * n) * (0.75 + 0.5 * hash(y, id, 68)), 0.5, 2.2) + blob; + const x0 = Math.min(a, left), x1 = Math.max(c, left + w - 1); // (its own width, as the beads feel it; its ragged edge) + const covered = (wd, x) => Math.max(clamp(wd / 2 + 0.5 - Math.abs(x - sx), 0, 1), wd > 0 && x === Math.round(sx) ? 0.45 : 0); // (by the streak) // (never one width for long, where the noise lingers: after a run of 5-9 rows alike, a row a px thinner, or if it's a px, thicker) - const across = (wd) => { // (its px across at this width: those covered enough to show, as below) + const pxAt = (wd) => { // (its px across at this width: those covered enough to show, as below) let k = 0; - for (let x = Math.min(a, left); x <= Math.max(c, left + w - 1); x++) k += Math.max(clamp(wd / 2 + 0.5 - Math.abs(x - at), 0, 1), wd > 0 && x === Math.round(at) ? 0.45 : 0) >= 0.4; + for (let x = x0; x <= x1; x++) k += covered(wd, x) >= 0.4; return k; }; if (wide > 0 && !blob) { - const k = across(wide); + const k = pxAt(wide); if (k === b.streakW && ++b.streakRun >= 5 + Math.floor(hash(y, id, 69) * 5)) { - for (const wd of k > 1 ? [wide - 1, wide - 0.6, 0.5] : [wide + 0.6, wide + 1, 1.6, 2]) if (wd > 0 && across(wd) !== k) { wide = wd; break; } + for (const wd of k > 1 ? [wide - 1, wide - 0.6, 0.5] : [wide + 0.6, wide + 1, 1.6, 2]) if (wd > 0 && pxAt(wd) !== k) { wide = wd; break; } } - const now = across(wide); + const now = pxAt(wide); if (now !== b.streakW) { b.streakW = now; b.streakRun = 0; } } else { b.streakW = 0; b.streakRun = 0; } - const drop = hash(y, id, 65) < (blob ? 0.7 : 0.05) ? Math.round(at + (hash(y, id, 66) - 0.5) * Math.max(1, w * 0.45)) : null; + const drop = hash(y, id, 65) < (blob ? 0.7 : 0.05) ? Math.round(sx + (hash(y, id, 66) - 0.5) * Math.max(1, w * 0.45)) : null; const res = b.res || (b.res = []); // (through the fog: each of its columns' residue streak, see below) - for (let x = Math.min(a, left); x <= Math.max(c, left + w - 1); x++) { // (its own width, as the beads feel it; its ragged edge) - const cov = Math.max(clamp(wide / 2 + 0.5 - Math.abs(x - at), 0, 1), wide > 0 && x === Math.round(at) ? 0.45 : 0), h = hash(x, y, id); + for (let x = x0; x <= x1; x++) { + const cov = covered(wide, x), h = hash(x, y, id); let p = 0, k = 0; if (cov >= 0.4) { k = Math.round(255 * clamp(cov * (0.5 + 0.5 * n) + 0.25 * blob, 0.05, 1)); - p = h < 0.045 ? GLINT : x > at && (cov < 1 || x >= at + wide / 2 - 0.5) && h < 0.4 ? GRIME : FILM; + p = h < 0.045 ? GLINT : x > sx && (cov < 1 || x >= sx + wide / 2 - 0.5) && h < 0.4 ? GRIME : FILM; } if (x === drop) { p = hash(x, y, id + 9) < 0.35 ? SPARK : DROP; k = 255; } if (b.kind === "fog") p = 0; // (a condensed bead's: nothing on clear glass, gone with the fog under it as it clears) @@ -1609,7 +1629,7 @@ if (r[0] > 0) { m = r[0] === r[1] || r[0] === 1 ? 128 : 255; r[0]--; } lay(x, y, 1 - 0.1 * Math.abs(x - mid) / Math.max(1, w / 2), b.life, p, k, Math.round(255 * e), m, x < left || x >= left + w ? 1 : 0); } - if (b.rows) { b.rows.push([y, a, c, left, w, blob > 0]); if (b.rows.length > 80) b.rows.shift(); } + if (b.rows) log(b.rows, [y, a, c, left, w, blob > 0], 80); }; function age(dt) { // the trails' clock on; a slice of them looked at again (all every REDRAW s of it, SWEEP_MOST a frame at // most): gone ones off the list @@ -1639,9 +1659,11 @@ change(b, g, f, px, s); if (b.vol > was) o.gained += b.vol - was; else o.lost += was - b.vol; o.moves++; - if (px > 0 && r >= 1.8 && r <= 3.2) { o.px += px; o.s += s; o.band += s * speedFor(r, FOGGY); } // (band: px it'd have run on fog) - if (px > 0) { o.all += px; o.norm += s * speedFor(r, FOGGY); o.pace += s * speedFor(r, g); } // (any size: px run, against what it'd have run on fog, and there) - if (px > 0 && g === FOGGY) { const band = seen.sizes[BANDS.filter((x) => r >= x).length]; band[0] += px; band[1] += s; } + if (!(px > 0)) return; + const fog = speedFor(r, FOGGY); + if (r >= 1.8 && r <= 3.2) { o.px += px; o.s += s; o.band += s * fog; } // (band: px it'd have run on fog) + o.all += px; o.norm += s * fog; o.pace += s * speedFor(r, g); // (any size: px run, against what it'd have run on fog, and there) + if (g === FOGGY) { let k = 0; while (k < BANDS.length && r >= BANDS[k]) k++; seen.sizes[k][0] += px; seen.sizes[k][1] += s; } } // A bead to condense somewhere: unseen till the fog has formed and shows there (and a moment more), then tiny. Where: anywhere in // the fog (a little more toward the top, more often where it's thick; not in a trail wiped through it), or now and then close @@ -1659,7 +1681,7 @@ if (condensing() < 0.15 + base[i]) break; } return numbered({id: ++made, kind: "fog", state: "rest", x: Math.round(clamp(x, 3, W - 4)), y: clamp(y, 6, H * 0.82), r: condensing.between(...BORN), - vol: 0, k: condensing() < 0.15 ? condensing.between(3, 5) : condensing.between(0.3, 1.5), wait: condensing.between(0, 0.5), merged: 0, life: condensing.between(...LIFE), + vol: 0, k: condensing() < 0.15 ? condensing.between(3, 5) : condensing.between(0.3, 1.5), wait: condensing.between(0, 0.5), life: condensing.between(...LIFE), still: true}); }; const pace = (b) => { // a run's next stretch: how fast (of its speed), how far @@ -1674,18 +1696,16 @@ laid: Math.floor(b.y) + (heightOf(b.r) >> 1), shown: 0}); pace(b); } + const settled = (b) => { shows(b); b.shown = APPEAR; all.push(b); return b; }; // (shown at once) function land(most) { // heavy rain: a drop sticking to the glass, a large bead at once, with a splash const landed = ++counts.rain, drop = streamOf(`humidity:drop:${landed}`), splash = streamOf(`humidity:splash:${landed}`); // (this landing's own) const r = drop.between(...RAIN_R), x = Math.round(drop.between(Math.ceil(r) + 2, W - 3 - Math.ceil(r))), y = drop.between(6, H * 0.7); - const b = numbered({id: ++made, kind: "rain", x, y, r, merged: 0, life: drop.between(...LIFE)}, landed); - shows(b); - b.shown = APPEAR; // (there at once) + const b = settled(numbered({id: ++made, kind: "rain", x, y, r, life: drop.between(...LIFE)}, landed)); // (the harder the rain, the harder it hits (hard: 0 at HEAVY_RAIN, 1 at the heaviest): squashed flatter, more droplets thrown // faster and further, more of them left) const hard = clamp((rain.level - HEAVY_RAIN) / (1 - HEAVY_RAIN), 0, 1), more = (k, [lo, hi]) => lo + Math.floor(k * (hi - lo + 1) * (0.6 + 0.4 * hard)); const squash = splash.between(...SQUASH) * (0.8 + 0.2 * hard); if (!STILL) Object.assign(b, {impact: 0, squash, fresh: true}); // (squashed, from its first frame; reduced or low motion: never) - all.push(b); // (its droplets: round it (evenly, a little jitter), each its speed; lopsided: bunched toward a direction of its own (lean, at // aim), faster that way, slower the other; some spray streaks) const cy = y + heightOf(r) / 2, n = more(splash(), THROWN), aim = splash.between(0, 2 * Math.PI), lean = splash.between(...LEAN); @@ -1708,15 +1728,14 @@ const px = Math.round(x + Math.cos(d.a) * far), py = Math.round(cy + Math.sin(d.a) * far * 0.8); if (px < 1 || px > W - 2 || py < 1 || py > H - 2) { off++; continue; } if (used() + (kept + 1) * TINY_COST > most) { cut++; continue; } - if (py + heightOf(BORN[0] + 0.05) >= flood.surface(px) - 1) { off++; continue; } // (none left in a flood: thrown into its water) + if (py + heightOf(DROPLET) >= flood.surface(px) - 1) { off++; continue; } // (none left in a flood: thrown into its water) Object.assign(d, {stay: far, px, py}); kept++; } splashes.push({x, y: cy, r, age: 0, dots, landed, own: splash}); seen.landed++; - seen.splashes.push({id: b.id, r, dots: n, stay: kept, meant: stay, cut, off, room, squash, aim, lean, - thrown: dots.map((d) => [d.a, d.v, d.streak ? 1 : 0, d.stay ? 1 : 0])}); - if (seen.splashes.length > 50) seen.splashes.shift(); + log(seen.splashes, {id: b.id, r, dots: n, stay: kept, meant: stay, cut, off, room, squash, aim, lean, + thrown: dots.map((d) => [d.a, d.v, d.streak ? 1 : 0, d.stay ? 1 : 0])}, 50); } // A rain bead just landed: how far squashed (0 round; above, wider and shorter; below, taller and narrower), held at its most a // frame or two, then wobbling back to round, less and less @@ -1745,17 +1764,14 @@ into.r = Math.cbrt(into.vol); into.x = clamp(Math.round(into.x + (from.x - into.x) * k), into.x0 - MEANDER, into.x0 + MEANDER); into.y = Math.max(into.y, into.y + (from.y - into.y) * k); - into.merged += 1 + from.merged; from.gone = true; into.still = into.still && into.r <= TINY; // (tiny no more: running, as its size has it) if (from.impact < SQUASH_S && !(into.impact < SQUASH_S)) Object.assign(into, {impact: from.impact, squash: from.squash, fresh: from.fresh}); // (a drop // landing on a bead: that one struck, squashed) seen.merges++; seen.largest = Math.max(seen.largest, into.r); - seen.merged.push({vol: was, into: into.vol, r: radii, intoR: into.r}); - if (seen.merged.length > 100) seen.merged.shift(); - seen.absorbed.push(from.id); - if (seen.absorbed.length > 300) seen.absorbed.shift(); + log(seen.merged, {vol: was, into: into.vol, r: radii, intoR: into.r}, 100); + log(seen.absorbed, from.id, 300); } // Tiny beads snapping together: two beads close (their edges SNAP px apart or less), one of them tiny (or both), neither running // on its own (a bead under 1 px/s, as tiny ones are): the higher one (the same height: the smaller) pulled into the lower one, @@ -1917,7 +1933,7 @@ } } b.x = clamp(b.x, Math.ceil(b.r), W - 1 - Math.ceil(b.r)); // (never part off the window's side) - if (top >= H) { b.gone = true; seen.ranOff++; seen.left.push(b.id); if (seen.left.length > 300) seen.left.shift(); return; } // (run off its bottom edge) + if (top >= H) { b.gone = true; seen.ranOff++; log(seen.left, b.id, 300); return; } // (run off its bottom edge) if (drowned(b)) return; } stretching(b, dt, b.v > 0); @@ -1932,8 +1948,7 @@ if (b.state === "on") for (let y = Math.max(b.laid, 0); y < Math.min(bottom, H); y++) wipe(b, y); seen.joined++; const last = b.state === "on" && b.rows.length ? b.rows[b.rows.length - 1][0] : null, end = last === null ? -1 : at(Math.round(b.x), last); - seen.joins.push({x: b.x, bottom, surface, level: flood.waterline(), trail: last === null ? null : last + 1, wet: end < 0 ? 0 : wetOf(end)}); - if (seen.joins.length > 100) seen.joins.shift(); + log(seen.joins, {x: b.x, bottom, surface, level: flood.waterline(), trail: last === null ? null : last + 1, wet: end < 0 ? 0 : wetOf(end)}, 100); flood.hit(b.x, 0.4 + 0.2 * b.r, true); return true; } @@ -1957,7 +1972,7 @@ const i = y * W + x, t = fogOf(i, cover, dense, true), u = x / W, v = y / H; const add = (k, by = t) => { sums[k][0] += by; sums[k][1]++; }; add("thickness"); - const k = t > 0 ? shadeOf(LIFT[(t * 256) | 0], x, y, FOG.length) : -1; + const k = t > 0 ? fogShade(t, i) : -1; add("opacity", k < 0 ? 0 : FOG_ALPHA[k] / 255); if (Math.abs(u - 0.5) < 0.2 && Math.abs(v - 0.5) < 0.2) add("middle"); if (Math.min(u, 1 - u) < 0.1 || v > 0.9) add("edge"); @@ -2008,7 +2023,6 @@ quiet = false; paint(); } - if (e.level > 0) level = e.level; // The fog forming (or clearing), thickening or thinning to its level cover = STILL ? (e.level > 0 ? 1 : 0) : clamp(cover + (e.level > 0 ? dt / FORM : -dt / CLEAR), 0, 1); const target = e.level > 0 ? thickness(e.level) : dense; @@ -2031,7 +2045,8 @@ // More condensing (in the fog, each as it shows: tiny), a few a second, accumulating up to the most (leaving heavy rain its // room); there, now and then the most isolated tiny one (or, alike, the oldest) drying away quietly for another; heavy rain, // now and then, a drop - const rainy = all.filter((b) => b.kind === "rain").length, tiny = all.filter((b) => b.still).length; + let rainy = 0, tiny = 0; + for (const b of all) { rainy += b.kind === "rain"; tiny += !!b.still; } cap = Math.max(0, Math.floor((Math.min(most - room, most - rainy) - (all.length - tiny - rainy)) / TINY_COST)); if (e.level > 0) { mist += MISTING * W * (0.95 + 0.4 * e.level) * dt; // (the more humid, the more tiny ones: light 0.95 times MISTING, heavy 1.35) @@ -2042,8 +2057,9 @@ if (old) { dries(old); all.push(condense()); } } } else mist = 0; - if (heavy() && rainy < RAIN_MOST && used() + 1 <= most && landing() < LANDING * dt) land(most); - seen.rainMost = Math.max(seen.rainMost, all.filter((b) => b.kind === "rain").length); + const lands = heavy() && rainy < RAIN_MOST && used() + 1 <= most && landing() < LANDING * dt; + if (lands) land(most); + seen.rainMost = Math.max(seen.rainMost, rainy + lands); snaps(); for (const b of all) { if (b.gone || drowned(b)) continue; @@ -2057,8 +2073,7 @@ const fog = fogOf(i, cover, dense, true); if (fog < FOG_AT || glassAt(b.x, b.y + heightOf(b.r) / 2) !== FOGGY) { b.gone = true; continue; } // (fog only) shows(b); - seen.born.push({id: b.id, kind: "fog", r: b.r, fog, y: (b.y + heightOf(b.r) / 2) / H}); - if (seen.born.length > 300) seen.born.shift(); + log(seen.born, {id: b.id, kind: "fog", r: b.r, fog, y: (b.y + heightOf(b.r) / 2) / H}, 300); if (!seen.first) seen.first = {after: fresh, cover, fog: fogOf(i, cover, dense, false), formed: fogNow()}; } } else if (b.state === "on") { @@ -2077,11 +2092,8 @@ for (const s of splashes) s.age += dt; for (const s of splashes) if (s.age >= SPLASH_S) for (const [j, d] of s.dots.entries()) if (d.stay) { // (its droplets left // behind: tiny beads now) - const r = BORN[0] + 0.05, b = numbered({id: ++made, kind: "splash", x: d.px, y: d.py, r, k: 1, merged: 0, life: s.own.between(...LIFE), - still: true, drying: s.own.between(...DRYING), thrown: [d.px - s.x, d.py - s.y]}, s.landed * 32 + j); - shows(b); - b.shown = APPEAR; - all.push(b); + settled(numbered({id: ++made, kind: "splash", x: d.px, y: d.py, r: DROPLET, k: 1, life: s.own.between(...LIFE), still: true, + drying: s.own.between(...DRYING), thrown: [d.px - s.x, d.py - s.y]}, s.landed * 32 + j)); } splashes = splashes.filter((s) => s.age < SPLASH_S); age(dt); @@ -2114,12 +2126,9 @@ // r}: their ids) tiny: TINY, snap: SNAP, snaps: seen.snaps, cap, place: (list) => list.map(({x, y, r = 0.55}) => { - const b = numbered({id: ++made, kind: "fog", x, y: y - heightOf(r) / 2, r, k: 1, merged: 0, still: true}, undefined, "placed"); + const b = numbered({id: ++made, kind: "fog", x, y: y - heightOf(r) / 2, r, k: 1, still: true}, undefined, "placed"); b.life = own(b, "life").between(...LIFE); - shows(b); - b.shown = APPEAR; - all.push(b); - return b.id; + return settled(b).id; }), clock: () => clock, wetAt: (x, y) => (listed && x >= 0 && x < W && y >= 0 && y < H ? wetOf(y * W + x) : 0), @@ -2165,7 +2174,7 @@ const d = layer.getContext("2d").getImageData(0, 0, W, H).data; let n = 0; for (let i = 0; i < W * H; i++) if (!listed[i]) { - const want = SHOWS[look(i, i % W, (i / W) | 0)]; + const want = SHOWS[look(i)]; if (Math.abs(d[i * 4 + 3] - want[3]) > 2) n++; } return n; @@ -2205,8 +2214,9 @@ if (b.state === "rest" || dotted.has(b)) continue; const q = b.state !== "on" ? 0 : squashOf(b), st = b.pop > 0 || b.state !== "on" || q ? 0 : stretchOf(b); // (squashed: not // its pop as well) - const pic = q ? squashed(b.r, q) : b.pop > 0 ? sprite(SIZES[Math.min(SIZES.length - 1, SIZES.findIndex((size) => size >= b.r - 0.01) + 1)]) : st > 0 ? elongated(b.r, st) : sprite(b.r), a = (b.state === "fade" ? b.left / b.fadeFor : 1) * Math.min(1, b.shown / APPEAR); - const left = Math.round(b.x) - (pic.width >> 1), top = (b.state === "fade" ? Math.round(b.y) : Math.floor(b.y)) - (q ? Math.round((pic.height - sprite(b.r).height) / 2) : pic.height - sprite(b.r).height); // (elongated: its lower + const round = sprite(b.r), pic = q ? squashed(b.r, q) : b.pop > 0 ? popped(b.r) : st > 0 ? elongated(b.r, st) : round; + const a = (b.state === "fade" ? b.left / b.fadeFor : 1) * Math.min(1, b.shown / APPEAR); + const left = Math.round(b.x) - (pic.width >> 1), top = (b.state === "fade" ? Math.round(b.y) : Math.floor(b.y)) - (q ? Math.round((pic.height - round.height) / 2) : pic.height - round.height); // (elongated: its lower // edge where it is; squashed: its middle) g.globalAlpha = a0 * a; g.drawImage(pic, left, top); From 9243b193e2aa666b86e97e58a577060be9c2554a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:45:44 +0000 Subject: [PATCH 097/146] Web dashboard: the heat as faint red beams between the UV's, 40 % longer; the sun's glare gone The heat (35 C and up) is now soft shafts from the top in the UV's own style (breathing, a small slow sway, never drifting), in a faint ember red: one in each gap between the UV's shafts' places (halfway between two, one past the last), so with both on they interleave, each 1.4 times as long as the UV shaft to its left. More of them and brighter the hotter (0.3 at 35 C to 1 at 43 C), its own random stream, nothing below a flood's water. The sun's bloom, flares, beams and veil are removed. The UV's shaft sprite and layout are shared (its look unchanged). Tests and README to match. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- README.md | 2 +- lib/web_dashboard.html | 231 +++++++++++---------------------- tests/test_web_dashboard.py | 70 +++++----- tests/web_dashboard_browser.js | 62 ++++----- 4 files changed, 130 insertions(+), 235 deletions(-) diff --git a/README.md b/README.md index f05d11a0..73685485 100644 --- a/README.md +++ b/README.md @@ -297,7 +297,7 @@ swipe, a drag on the gauge, or a two-finger sideways swipe on a trackpad; it sto Behind the gauges, the weather is drawn as faint pixel art while the readings call for it: rain while it rains, hazy clouds drifting across from the US AQI's Moderate band up, UV beams at a UV index of 11, the glass fogging over at 90 % humidity (heavier to 100 %), beads condensing in the fog and running down it, wiping clear tracks, leaves blowing past -above 15 km/h of wind, a blazing sun's glare from 35 °C and ice below 0 °C. "stop animation" at the bottom left stops and clears them for that page view only, and ends any effect a temporary test link turned on; +above 15 km/h of wind, faint red beams between the UV's from 35 °C (more and brighter to 43 °C) and ice below 0 °C. "stop animation" at the bottom left stops and clears them for that page view only, and ends any effect a temporary test link turned on; nothing is saved, so a reload brings them back. With reduced motion asked for, one still frame. To turn them off for good (for everyone), set `MCP_DASHBOARD_ANIMATIONS=off`. For an e-ink display, set `MCP_DASHBOARD_ANIMATIONS=low` (low motion, for everyone): nothing moves, the weather one faint still frame drawn again only when the conditions change, no transitions, the gauges jumping to each new reading, diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 7dc1f637..6e3fd135 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -759,170 +759,99 @@ }; }); - // ---------- heat: a blazing sun's glare from the top right corner (where the light comes from in the rest's art) ---------- - // A white-gold bloom in the corner: a white-hot core and a wide warm glow round it, a few thin spikes in it; a few faint sunbeams - // fanning down from it across the window; soft lens flares strung along the diagonal from it through the window's middle (rings, - // hexagons and discs of different sizes, each faintly its own colour); and the whole window faintly sun-bleached, a warm veil - // lifting the dark, warmest near the sun. Stronger and whiter the hotter (its level: 0.3 at 35 °C to 1 at 43 °C): a gentle warm - // glow at 35 °C; to 43 °C and up a bigger, whiter, blinding sun, its flares stronger. Very slow: the bloom breathing (its glow and - // its core out of step, the beams each half their own way), the sun wandering a pixel or so and the flares drifting with it (each - // its own way along the diagonal, as a lens's do). Each part painted once a size (the bloom once a level) and blitted; dithered on - // the blue noise (no grid). Reduced or low motion: one still frame. Drawn behind the flood (the sun in the sky, well clear of it), - // the sun itself (sun()) in front of the UV's shafts. - const SUN = ["#B8641E", "#D98A32", "#EFAE4C", "#F8CC70", "#FCE09A", "#FFEFC4", "#FFF8E6", "#FFFFFA"].map(rgb); // ember to white-hot - const SUN_ALPHA = [18, 30, 48, 72, 104, 146, 196, 245]; // (the glow's shades' alphas) - const FLARE = ["#FFD27A", "#FFB08A", "#A6E8C6", "#F6A3A8", "#EEF0A0", "#FFE6B8"].map(rgb); // gold, peach, mint, rose, lemon, cream + // ---------- uv and heat: soft shafts of light coming in from the top, slowly swaying and breathing ---------- + // Each shaft a dithered wedge, widening and fading as it comes down; drawn twice, a wide faint halo and a narrow bright core, the two + // breathing out of step, so it seems to waver. Each sways a pixel or so side to side about its own place, very slowly (a minute + // and a half to two a sway), never travelling on. shaftOf(colours, wide, long, slope, bright): one (its top `rows` rows only: the + // window's height, the rest never seen) + const shaftOf = (colours, wide, long, slope, bright, rows = long) => + painted(wide * 2 + Math.min(long, rows) * Math.abs(slope) + 2, Math.min(long, rows), (x, y) => { + const k = y / long, half = wide * (0.6 + 0.6 * k), mid = wide + (slope < 0 ? long * -slope : 0) + y * slope; + const across = 1 - Math.abs(x - mid) / half; + if (across <= 0) return null; + const s = shadeOf(Math.pow(across, 0.7) * Math.pow(1 - k, 1.1) * bright, x, y, colours.length); + return s < 0 ? null : colours[s]; + }); + // The UV's shafts' places for the window's size (seeded: the same every time): each {wide, long, slope, x: its place (art px), phase, + // rate, sway, swayRate}; the heat's go between them + const uvShafts = () => { + const r = seeded(77), n = Math.max(4, Math.round(W / 70)); + return Array.from({length: n}, (_, i) => { + const wide = Math.round(10 + r() * 22), long = Math.round(H * (0.4 + r() * 0.5)), slope = 0.12 + r() * 0.1; + return {wide, long, slope, x: (i + r() * 0.6) * W / n - 10, phase: r() * 7, rate: 0.3 + r() * 0.25, + sway: 0.85 + r() * 0.8, swayRate: 0.05 + r() * 0.03}; // (how far each way, art px; rad/s) + }); + }; + // A shaft's halo and core drawn (from the loop's draw()), breathing and swaying as the UV's do; its left x as drawn + const shaftDrawn = (g, s, alpha, t) => { + const x = Math.round(s.x - s.halo.width / 2 + s.sway * Math.sin(t * s.swayRate + s.phase * 3)); + g.globalAlpha = alpha * (0.3 + 0.4 * Math.pow(Math.sin(t * s.rate + s.phase), 2)); + g.drawImage(s.halo, x, 0); + g.globalAlpha = alpha * (0.15 + 0.55 * Math.pow(Math.sin(t * s.rate * 1.7 + s.phase * 2), 4)); + g.drawImage(s.core, x + s.inset, 0); + return x; + }; + + // ---------- heat: soft shafts of faint red light from the top, as the UV's, between the UV's (with both on, the two interleave) ---------- + // One in each gap between the UV's shafts' places (halfway between two, and one half a spacing past the last), each 40 % longer + // than the UV's shaft to its left, leaning as its two neighbours do (so never crossing them); its own width, breathing and sway. + // Stronger the hotter (its level: 0.3 at 35 °C to 1 at 43 °C): brighter, and more of them (about that share of them on, the + // others fading out), the first few on at 35 °C spread about at random. Drawn behind the flood (nothing below its water). + // Reduced or low motion: one still frame. + const EMBER = ["#2A0F0C", "#4A1A13", "#7C2C1E", "#B24A34", "#F0A08A"].map(rgb); // ember red, faint (the UV's violet's way) + const HEAT_LONGER = 1.4; // each this much longer than a UV shaft const heat = effect((e) => { - const random = streamOf("sun"), between = random.between; // (its own randomness) - const DRIFT = [1.6, 1.1]; // how far the sun wanders each way (art px), very slowly - let S = 0, home = [0, 0], at = [0, 0], veil = null, beams = [], spikes = [], flares = [], glow = null, core = null; - let built = 0, R = 0, rc = 0, placed = []; - // The bloom at level L: its glow (radius R, spikes and all) and its core (radius rc, white-hot), each a sprite centred on the sun - const build = (L) => { - built = L; - R = Math.round(S * (0.2 + 0.16 * L)); - rc = Math.max(2, Math.round(S * (0.018 + 0.03 * L))); - glow = painted(2 * R + 1, 2 * R + 1, (x, y) => { - const dx = x - R, dy = y - R, r = Math.hypot(dx, dy), d = r / R; - if (d >= 1) return null; - const angle = Math.atan2(dy, dx); - let spike = 0; - for (const s of spikes) { - const off = Math.abs(((angle - s.angle + 3 * Math.PI) % (2 * Math.PI)) - Math.PI) * r; // (px off its line) - if (d < s.reach) spike = Math.max(spike, Math.exp(-(off * off) / (s.wide * s.wide)) * Math.pow(1 - d / s.reach, 1.4)); - } - const v = Math.pow(1 - d, 2.4) * (0.5 + 0.5 * L) + 0.4 * spike * (0.45 + 0.55 * L), s = shadeOf(v, x, y, SUN.length); - return s < 0 ? null : [...SUN[Math.round(s * (0.55 + 0.45 * L))], SUN_ALPHA[s]]; // (golder the cooler) - }); - const n = Math.ceil(rc * 1.8); - core = painted(2 * n + 1, 2 * n + 1, (x, y) => { - const d = Math.hypot(x - n, y - n) / rc, s = d < 1 ? 2 : shadeOf((1.8 - d) / 0.8, x, y, 3); - return s < 0 ? null : [...SUN[Math.min(7, 4 + s + (L > 0.6 ? 1 : 0))], [150, 210, 255][s]]; - }); - }; - // A lens flare's sprite: radius r, its colour; a disc (soft, fading out), a ring (a thin bright rim, a whisper inside) or a hexagon - // (faintly filled, its rim brighter) - const flare = (kind, r, c) => { - const n = Math.ceil(r) + 1, tints = [c.map((v) => v * 0.85), c, c.map((v) => v + (255 - v) * 0.45)]; - return painted(2 * n + 1, 2 * n + 1, (x, y) => { - const dx = x - n, dy = y - n, d = Math.hypot(dx, dy) / r; - let v; - if (kind === "disc") v = d < 1 ? 0.25 + 0.6 * Math.pow(1 - d * d, 0.7) : 0; - else if (kind === "ring") v = Math.exp(-Math.pow((d - 0.86) / 0.11, 2)) * 0.95 + (d < 0.86 ? 0.12 : 0); - else { // (a hexagon: its edges' distance across, flat top and bottom) - const h = Math.max(Math.abs(dy), Math.abs(dy) / 2 + Math.abs(dx) * 0.866) / (r * 0.866); - v = h < 1 ? (h > 0.84 ? 0.85 : 0.22 + 0.1 * (1 - h)) : 0; - } - const s = shadeOf(v, x, y, 3); - return s < 0 ? null : [...tints[s].map(Math.round), [44, 70, 104][s]]; - }); - }; + const random = streamOf("heat"), between = random.between; // (its own randomness) + let shafts = [], last = null; return { strength: () => 0.4 + 0.4 * e.level, - // (for the tests: the sun's middle as last drawn and its home (art px), the bloom's radius and its core's, the level it was - // built for, the beams; each flare as last drawn {kind, x, y (its middle), r, k: how far along the diagonal, colour}) - probe: () => ({sun: at.map(Math.round), home, radius: R, core: rc, built, beams: beams.length, size: [W, H], - flares: placed.map((f) => ({...f}))}), + // (for the tests: the UV's places (art px) and its shafts' tops' middles there (unswayed), each shaft {x: its place, long (art px), uvLong: the UV shaft's to its left, on: how + // far shown (0-1), at: its left as last drawn (null: not drawn), top: its top's middle then}, the window's size) + probe: () => ({level: e.level, size: [W, H], uv: uvShafts().map((s) => s.x), + uvTops: uvShafts().map((u) => u.x - (u.long * u.slope + 2) / 2), + shafts: shafts.map((s) => ({x: s.x, long: s.long, uvLong: s.uvLong, on: s.on, at: s.at, + top: s.at === null ? null : s.at + s.wide}))}), resize() { - S = Math.min(W, H); - home = [W - Math.round(S * 0.03), Math.round(S * 0.03)]; // (in the corner: its glare over the tiles' edges, not their gauges) - at = home.slice(); - built = 0; - // its spikes: six thin ones, about evenly round, each its own length - spikes = Array.from({length: 6}, (_, i) => ({angle: (i + between(-0.2, 0.2)) * Math.PI / 3 + 0.35, reach: between(0.55, 1), - wide: between(0.7, 1.3)})); - // the veil: faint warm light over the whole window, warmest near the sun - const far = Math.hypot(W, H); - veil = painted(W, H, (x, y) => { - const v = 0.3 + 0.7 * Math.pow(1 - Math.min(1, Math.hypot(x - home[0], y - home[1]) / (far * 0.85)), 1.8); - const s = shadeOf(v, x, y, 4); - return s < 0 ? null : [...SUN[s > 1 ? 2 : 1], [16, 24, 34, 46][s]]; - }); - // the sunbeams: five, fanning down and left from the sun, faint, fading as they go, each its own width and length; two - // canvases (alternate beams), breathing out of step - const rays = Array.from({length: 5}, (_, i) => ({angle: (0.56 + (i + between(-0.3, 0.3)) * 0.2) * Math.PI, // (down to left) - wide: between(0.018, 0.04), long: far * between(0.55, 0.95)})); - beams = [0, 1].map((half) => painted(W, H, (x, y) => { - const dx = x - home[0], dy = y - home[1], r = Math.hypot(dx, dy), angle = Math.atan2(dy, dx); - let v = 0; - for (let i = half; i < rays.length; i += 2) { - const b = rays[i], off = Math.abs(((angle - b.angle + 3 * Math.PI) % (2 * Math.PI)) - Math.PI) / b.wide; - if (r < b.long && off < 3) v += Math.exp(-off * off) * Math.pow(1 - r / b.long, 1.2) * Math.min(1, r / (S * 0.12)); - } - const s = shadeOf(v * 0.75, x, y, 3); - return s < 0 ? null : [...SUN[4 + s], [20, 30, 42][s]]; - })); - // the flares: along the diagonal from the sun through the window's middle (k: 0 at the sun, 1 at the middle), a little off it - // either way, of different sizes and kinds and faint colours - const KINDS = ["hex", "disc", "ring", "hex", "disc", "ring", "disc"]; - const ks = [0.34, 0.52, 0.7, 0.93, 1.16, 1.42, 1.72]; - flares = ks.map((k, i) => { - const kind = KINDS[i], r = S * (kind === "ring" ? between(0.04, 0.085) : kind === "hex" ? between(0.02, 0.045) : between(0.012, 0.035)); - const colour = FLARE[Math.floor(random() * FLARE.length)]; - return {kind, k: k + between(-0.04, 0.04), r, colour, aside: between(-0.015, 0.015) * S, weight: between(0.55, 1), - sprite: flare(kind, r, colour)}; + const uv = uvShafts(), spacing = W / uv.length; + const order = uv.map((_, i) => [random(), i]).sort((a, b) => a[0] - b[0]).map(([, i]) => i); // (which are on first) + shafts = uv.map((u, i) => { + const next = uv[i + 1], x = next ? (u.x + next.x) / 2 : u.x + spacing / 2; + const slope = next ? (u.slope + next.slope) / 2 : u.slope, long = Math.round(u.long * HEAT_LONGER); + const wide = Math.round(between(8, 18)), narrow = Math.max(3, Math.round(wide * 0.5)); + return {x, long, uvLong: u.long, rank: order.indexOf(i), on: 0, at: null, wide, + halo: shaftOf(EMBER, wide, long, slope, 0.45, H), core: shaftOf(EMBER, narrow, Math.round(long * 0.8), slope, 0.6, H), + inset: wide - narrow, // (the core down the halo's middle) + phase: between(0, 7), rate: between(0.3, 0.55), sway: between(0.85, 1.65), swayRate: between(0.05, 0.08)}; }); + last = null; }, + forget() { for (const s of shafts) s.on = 0; last = null; }, draw(g, alpha, t) { - if (e.level > 0 && e.level !== built) build(e.level); - const L = built; - at = [home[0] + DRIFT[0] * Math.sin(t * 0.07 + 1.3), home[1] + DRIFT[1] * Math.sin(t * 0.053 + 0.4)]; - const sx = Math.round(at[0] - home[0]), sy = Math.round(at[1] - home[1]); - g.globalAlpha = alpha * (0.75 + 0.25 * L); - g.drawImage(veil, 0, 0); - beams.forEach((b, i) => { - g.globalAlpha = alpha * (0.55 + 0.45 * L) * (0.7 + 0.3 * Math.sin(t * (i ? 0.23 : 0.29) + i * 2.1)); - g.drawImage(b, sx, sy); - }); - // the flares: each where the line from the sun through the window's middle puts it (so drifting as the sun does, those past - // the middle the other way) - const mx = W / 2 - at[0], my = H / 2 - at[1], len = Math.hypot(mx, my) || 1; - placed = flares.map((f) => { - const x = Math.round(at[0] + f.k * mx - f.aside * my / len), y = Math.round(at[1] + f.k * my + f.aside * mx / len); - const n = (f.sprite.width - 1) / 2; - g.globalAlpha = alpha * f.weight * (0.35 + 0.65 * L) * (0.9 + 0.1 * Math.sin(t * 0.31 + f.k * 4)); - g.drawImage(f.sprite, x - n, y - n); - return {kind: f.kind, x, y, r: f.r, k: f.k, colour: f.colour}; + // (first drawn since on: those wanted on at once, the effect itself fading in; after, each fading in or out on its own) + const want = Math.max(1, Math.round(shafts.length * e.level)), first = last === null, dt = first ? 0 : Math.max(0, t - last); + last = t; + flood.above(g, () => { + for (const s of shafts) { + const to = s.rank < want ? 1 : 0; + s.on = STILL || first ? to : clamp(s.on + (to ? dt : -dt) / FADE_S, 0, 1); + s.at = s.on > 0 ? shaftDrawn(g, s, alpha * (0.55 + 0.45 * e.level) * s.on, t) : null; + } }); }, - // The sun itself, drawn after the UV's shafts and glow (from the loop's draw()): its glow, breathing, and its white-hot core, so - // nothing cool lies over it - sun(g, alpha, t) { - g.globalAlpha = alpha * (0.86 + 0.14 * Math.sin(t * 0.45)); // (the glow breathing, about every 14 s) - g.drawImage(glow, Math.round(at[0]) - R, Math.round(at[1]) - R); - g.globalAlpha = Math.min(1, alpha * (1.15 + 0.15 * Math.sin(t * 0.71 + 2))); // (the core: out of step with the glow) - const n = (core.width - 1) / 2; - g.drawImage(core, Math.round(at[0]) - n, Math.round(at[1]) - n); - }, }; }); - // ---------- uv: soft shafts of violet light coming in from the top, slowly swaying and breathing ---------- - // Each shaft a dithered wedge, widening and fading as it comes down; drawn twice, a wide faint halo and a narrow bright core, the two - // breathing out of step, so it seems to waver. Each sways a pixel or so side to side about its own place, very slowly (a minute - // and a half to two a sway), never travelling on. A faint glow along the top. + // ---------- uv: soft shafts of violet light coming in from the top (see the heat's, above), and a faint glow along the top ---------- const RAD = ["#22153C", "#3C256A", "#6444A8", "#A287E6", "#EFE7FF"].map(rgb); const uv = effect((e) => { let shafts = [], glow = null; - const shaft = (wide, long, slope, bright) => painted(wide * 2 + long * Math.abs(slope) + 2, long, (x, y) => { - const k = y / long, half = wide * (0.6 + 0.6 * k), mid = wide + (slope < 0 ? long * -slope : 0) + y * slope; - const across = 1 - Math.abs(x - mid) / half; - if (across <= 0) return null; - const s = shadeOf(Math.pow(across, 0.7) * Math.pow(1 - k, 1.1) * bright, x, y, 5); - return s < 0 ? null : RAD[s]; - }); return { strength: () => 0.8, resize() { - const r = seeded(77); - const n = Math.max(4, Math.round(W / 70)); - shafts = Array.from({length: n}, (_, i) => { - const wide = Math.round(10 + r() * 22), long = Math.round(H * (0.4 + r() * 0.5)), slope = 0.12 + r() * 0.1; - const narrow = Math.max(3, Math.round(wide * 0.5)); - const halo = shaft(wide, long, slope, 0.6), core = shaft(narrow, Math.round(long * 0.8), slope, 0.75); - return {halo, core, inset: wide - narrow, // (the core down the halo's middle) - x: (i + r() * 0.6) * W / n - 10, phase: r() * 7, rate: 0.3 + r() * 0.25, - sway: 0.85 + r() * 0.8, swayRate: 0.05 + r() * 0.03}; // (how far each way, art px; rad/s) + shafts = uvShafts().map((u) => { + const narrow = Math.max(3, Math.round(u.wide * 0.5)); + return {...u, halo: shaftOf(RAD, u.wide, u.long, u.slope, 0.6), core: shaftOf(RAD, narrow, Math.round(u.long * 0.8), u.slope, 0.75), + inset: u.wide - narrow}; // (the core down the halo's middle) }); glow = painted(W, Math.ceil(H * 0.16), (x, y) => { const s = shadeOf(Math.pow(1 - y / (H * 0.16), 2.4) * 0.6, x, y, 3); @@ -932,13 +861,7 @@ draw(g, alpha, t) { g.globalAlpha = alpha * 0.8; g.drawImage(glow, 0, 0); - for (const s of shafts) { - const x = Math.round(s.x - s.halo.width / 2 + s.sway * Math.sin(t * s.swayRate + s.phase * 3)); - g.globalAlpha = alpha * (0.3 + 0.4 * Math.pow(Math.sin(t * s.rate + s.phase), 2)); - g.drawImage(s.halo, x, 0); - g.globalAlpha = alpha * (0.15 + 0.55 * Math.pow(Math.sin(t * s.rate * 1.7 + s.phase * 2), 4)); - g.drawImage(s.core, x + s.inset, 0); - } + for (const s of shafts) shaftDrawn(g, s, alpha, t); }, }; }); @@ -3258,8 +3181,6 @@ const fx = effects[k], a = fx.strength() * fx.amount * (OWN_STRENGTH.has(k) ? faint : cap); drawn[k] = fx.amount > 0 ? a : 0; if (fx.amount > 0) fx.draw(ctx, a, clock); - // (the heat's sun in front of the UV's shafts: white-hot over their violet) - if (k === "uv" && effects.heat.amount > 0) effects.heat.sun(ctx, drawn.heat, clock); } ctx.globalAlpha = 1; } diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 334e5707..b367d637 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -2012,55 +2012,47 @@ async def test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_red assert flood["depth"] == flood["full"] > 0 and flood["frog"] is None and not flood["running"] and flood["frames"] == 0, flood # ... and a gust (the page's, the test link's, asked for by name): nothing blown across, no loop assert still["gust"] == {"fling": None, "sent": 0, "running": False, "frames": 0}, still["gust"] - # ... and the heat's: its sun in the corner, white-hot, its flares, still (no loop) + # ... and the heat's: its shafts, every one on (43 °C), still (no loop) heat = still["heat"] - assert heat["built"] == 1 and heat["flares"] >= 5 and heat["drawn"] > 0 and not heat["running"] and heat["frames"] == 0, heat - assert max(abs(a - b) for a, b in zip(heat["sun"], heat["home"])) <= 2 and heat["at"][3] > 60 and min(heat["at"][:3]) > 140, heat # (faint: a still frame, every effect on) - # the heat (?fx=heat): a blazing sun's glare, not a shimmer: a white-gold bloom in the top right corner, lens flares strung along - # the diagonal from it through the window's middle, the window faintly warmed; more so the hotter + assert heat["shafts"] >= 4 and heat["on"] == heat["shafts"] and heat["drawn"] > 0 and not heat["running"] and heat["frames"] == 0, heat + # the heat (?fx=heat): soft shafts of faint red light from the top, as the UV's: one in each gap between the UV's places (halfway + # between two, one past the last), each 40 % longer than the UV's to its left; more of them and brighter the hotter hot = got["heat"] assert hot["errors"] == [] and hot["cost"] < 4, hot looks = hot["looks"] for look in looks: - w, h = look["size"] - # (its sun in the top right corner, its core white-hot: bright, warm (no blue over red), at every level) - assert look["home"][0] >= 0.9 * w and look["home"][1] <= 0.1 * h and look["built"] == look["level"], look - r, g, b = look["coreLook"]["colour"] - assert look["coreLook"]["light"] > 150 and r >= g >= b and b > 150, look["coreLook"] - # (its flares: five or more on screen, each standing out of the veil around it, near the line from the sun through the middle, the - # first nearer the sun than the middle, the last past it, of different sizes and kinds) - on = [f for f in look["flares"] if f["on"]] - assert len(on) >= 5 and all(f["alpha"] > 1.5 * look["veil"]["alpha"] for f in on), (on, look["veil"]) - assert all(f["aside"] <= 0.03 * min(w, h) + 1.5 for f in on), on - assert min(f["k"] for f in on) < 0.5 and max(f["k"] for f in on) > 1.2, on - assert {f["kind"] for f in on} == {"ring", "hex", "disc"} and max(f["r"] for f in on) > 2.5 * min(f["r"] for f in on), on - # (the window outside the bloom faintly veiled, warm: red over blue, inked nearly all over, its light a lift, not a glare) - r, g, b = look["veil"]["colour"] - assert look["veil"]["alpha"] > 0.03 and r > 1.3 * b and look["veil"]["light"] < 25, look["veil"] - # ... stronger the hotter: from 35 °C to 43 °C the bloom bigger, its core larger, the veil warmer, the flares stronger + uv, shafts = look["uv"], look["shafts"] + assert len(shafts) == len(uv) >= 4, look + assert all(a < s["x"] < b for a, s, b in zip(uv, shafts, uv[1:])) and shafts[-1]["x"] > uv[-1], (uv, shafts) + assert all(s["long"] == round(1.4 * s["uvLong"]) for s in shafts), shafts + # (about the level's share of them on, at least one; each on drawn) + on = [s for s in shafts if s["on"] == 1] + assert len(on) == max(1, round(len(shafts) * look["level"])) and all(s["at"] is not None for s in on), shafts + # (red, from the top: the top third warm (red over green and blue), the shafts' tops inked, the UV's places' tops (between + # them) far fainter) + r, g, b = look["top"]["colour"] + assert r > 1.5 * b and r > 1.5 * g and 0.01 < look["top"]["alpha"] < 0.25, look["top"] + r, g, b = look["atHeat"]["colour"] + assert r > 1.5 * b and look["atHeat"]["alpha"] > 3 * look["atUv"]["alpha"], (look["atHeat"], look["atUv"]) + # ... stronger the hotter: from 35 °C to 43 °C more of them, brighter cool, warm, hottest = looks - assert cool["radius"] < warm["radius"] < hottest["radius"] and cool["core"] < hottest["core"], looks - assert cool["veil"]["light"] < warm["veil"]["light"] < hottest["veil"]["light"], [l["veil"] for l in looks] - assert cool["drawn"] < warm["drawn"] < hottest["drawn"] and cool["veil"]["alpha"] < hottest["veil"]["alpha"], looks + count = [sum(s["on"] == 1 for s in l["shafts"]) for l in looks] + assert count[0] < count[1] < count[2] == len(hottest["shafts"]), count + assert cool["drawn"] < warm["drawn"] < hottest["drawn"] and cool["top"]["alpha"] < warm["top"]["alpha"] < hottest["top"]["alpha"], looks # ... dithered irregularly (no grid: under 100, as gridPeak sees it; ordered, about 200) assert hot["grid"] < 100, hot["grid"] - # ... very slow: over 24 s the sun wandering a pixel or two about its home, never more than a pixel a second; each flare drifting - # with it, the other way past the middle ((1 - k) times as far, as a lens's flares do) - moving = hot["moving"] - home = looks[-1]["home"] - assert all(abs(m["sun"][0] - home[0]) <= 2 and abs(m["sun"][1] - home[1]) <= 2 for m in moving), moving - assert len({tuple(m["sun"]) for m in moving}) > 1, moving - assert all(abs(a - b) <= 1 for m, n in zip(moving, moving[1:]) for a, b in zip(m["sun"], n["sun"])), moving - for m, n in zip(moving, moving[1:]): - dx, dy = n["sun"][0] - m["sun"][0], n["sun"][1] - m["sun"][1] - for (x0, y0, k), (x1, y1, _) in zip(m["flares"], n["flares"]): - assert abs((x1 - x0) - (1 - k) * dx) <= abs(1 - k) + 1 and abs((y1 - y0) - (1 - k) * dy) <= abs(1 - k) + 1, (m, n) - # with the UV on too: the sun still white-hot in its corner (the UV's shafts cool violet beside it), the two within the cap + # ... swaying as the UV's: over 24 s each a pixel or so either side of its place, never more than a pixel a second, never drifting + columns = list(zip(*hot["moving"])) + assert all(max(c) - min(c) <= 4 and all(abs(a - b) <= 1 for a, b in zip(c, c[1:])) for c in columns), columns + assert any(max(c) > min(c) for c in columns), columns + # with the UV on too: the two interleaving, the heat's tops warmer than the UV's (red over the UV's violet glow along the top), + # the UV's violet (blue over red), within the cap over = got["heatOver"] assert over["errors"] == [] and over["looks"][0]["drawn"] < hottest["drawn"], over - r, g, b = over["looks"][0]["coreLook"]["colour"] - assert over["looks"][0]["coreLook"]["light"] > 150 and r >= b, over["looks"][0]["coreLook"] - + there = over["looks"][0] + assert [s["x"] for s in there["shafts"]] == [s["x"] for s in hottest["shafts"]], there + (hr, _, hb), (ur, _, ub) = there["atHeat"]["colour"], there["atUv"]["colour"] + assert ub > ur and hr / hb > 1.3 * ur / ub and there["atUv"]["alpha"] > 0.1, (there["atHeat"], there["atUv"]) def clean_glass(marks): """Nothing on the glass (Sky.state().humidity.marks()): no trail, no stain on its canvas, no bead, no fog""" diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 9d4a112f..30c4ec98 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1387,56 +1387,39 @@ const rainSeen = (page, ms) => page.evaluate((ms) => new Promise((resolve) => { const begun = () => Sky.clock().frames >= 50 ? look() : __next(begun); begun(); }), ms); -// The heat's blazing sun on a driven page, with each of `levels` in turn (the effects on: {heat: its strength, 0.3 at 35 °C to 1 -// at 43 °C, and any others}), each 60 frames after it's set: the sun as Sky's heat probe has it (its middle, home, bloom -// and core radii, the level built, its flares), the canvas's mean colour and luminance (alpha-weighted, 0-255) in the sun's core and -// the canvas's mean alpha (0-1) and colour over the window outside the bloom (the veil, the beams and flares in it), each flare's -// mean alpha over its own disc, how far it is off the line from the sun through the window's middle (art px), the grid seen in the -// window's top left (gridPeak's ratio: the veil's dithering); then, at the last level, 24 looks a second apart: the sun's middle and -// each flare's, as drawn -const sunSeen = (page, levels) => page.evaluate(async (levels) => { +// The heat's red shafts on a driven page, with each of `levels` in turn (the effects on: {heat: its strength, 0.3 at 35 °C to 1 +// at 43 °C, and any others}), each 60 frames after it's set: Sky's heat probe (the UV's places, its shafts), the canvas's mean alpha +// (0-1) and colour (alpha-weighted) over the window's top third, and its mean alpha and colour in the top 4 rows within 2 px of each +// shown shaft's top and of each UV shaft's top (where it would be, unswayed); then, at the last level, 24 looks a second apart: each shaft's left as drawn +const heatSeen = (page, levels) => page.evaluate(async (levels) => { const c = document.querySelector("#sky canvas"), g = c.getContext("2d"); const looks = []; for (const detail of levels) { - const level = detail.heat; document.dispatchEvent(new CustomEvent("ecobot-fx", { detail })); Sky.advance(60); const h = Sky.state().heat, W = c.width, H = c.height, d = g.getImageData(0, 0, W, H).data; - const at = (x, y) => { const i = (y * W + x) * 4; return [d[i], d[i + 1], d[i + 2], d[i + 3]]; }; const mean = (inside) => { - let n = 0, alpha = 0, rgb = [0, 0, 0], light = 0; + let n = 0, alpha = 0, rgb = [0, 0, 0]; for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { if (!inside(x, y)) continue; - const [r, gg, b, a] = at(x, y); + const i = (y * W + x) * 4, a = d[i + 3]; n++; alpha += a / 255; - light += (0.2126 * r + 0.7152 * gg + 0.0722 * b) * a / 255; - if (a) { rgb[0] += r * a; rgb[1] += gg * a; rgb[2] += b * a; } + rgb[0] += d[i] * a; rgb[1] += d[i + 1] * a; rgb[2] += d[i + 2] * a; } - const wa = alpha * 255; - return { n, alpha: alpha / Math.max(n, 1), light: light / Math.max(n, 1), colour: rgb.map((v) => Math.round(v / Math.max(wa, 1))) }; + return { alpha: alpha / Math.max(n, 1), colour: rgb.map((v) => Math.round(v / Math.max(alpha * 255, 1))) }; }; - const [sx, sy] = h.sun, off = (x, y) => Math.hypot(x - sx, y - sy); - const core = mean((x, y) => off(x, y) <= h.core * 0.8); - const veil = mean((x, y) => off(x, y) > h.radius); - const [mx, my] = [W / 2 - sx, H / 2 - sy], len = Math.hypot(mx, my); - const flares = h.flares.map((f) => { - let n = 0, alpha = 0; - for (let y = Math.max(0, Math.floor(f.y - f.r)); y <= Math.min(H - 1, Math.ceil(f.y + f.r)); y++) - for (let x = Math.max(0, Math.floor(f.x - f.r)); x <= Math.min(W - 1, Math.ceil(f.x + f.r)); x++) - if (Math.hypot(x - f.x, y - f.y) <= f.r * 0.95) { n++; alpha += at(x, y)[3] / 255; } - return { ...f, alpha: alpha / Math.max(n, 1), aside: Math.abs((f.x - sx) * my - (f.y - sy) * mx) / len, - on: f.x >= 0 && f.x < W && f.y >= 0 && f.y < H }; - }); - looks.push({ level, sun: h.sun, home: h.home, radius: h.radius, core: h.core, built: h.built, size: h.size, flares, - coreLook: core, veil, drawn: Sky.state().drawn.heat }); + const tops = (xs) => mean((x, y) => y < 4 && xs.some((t) => Math.abs(x - t) <= 2)); + const shown = h.shafts.filter((s) => s.top !== null); + looks.push({ level: detail.heat, size: h.size, uv: h.uv, shafts: h.shafts, drawn: Sky.state().drawn.heat, + top: mean((x, y) => y < H / 3), atHeat: tops(shown.map((s) => s.top)), + atUv: tops(h.uvTops) }); } const moving = []; for (let i = 0; i < 24; i++) { Sky.advance(30); - const h = Sky.state().heat; - moving.push({ sun: h.sun, flares: h.flares.map((f) => [f.x, f.y, f.k]) }); + moving.push(Sky.state().heat.shafts.map((s) => s.at)); } - return { looks, moving, cost: Sky.state().cost, width: c.width, height: c.height }; + return { looks, moving, cost: Sky.state().cost }; }, levels); // uv's beams over 40 s of the page's time (on a page whose clock runs on fast: `pace`, below; each frame drawn 0.1 s on, Sky's // longest step): where each beam's halo was drawn (with uv alone, the glow, then each beam's halo and core), its least and greatest x @@ -2558,11 +2541,11 @@ const WEATHER = { await uv.context.close(); return [seen, frost]; })(); - // the heat's blazing sun at 35 °C, between and at 43 °C; and at 43 °C with the UV's shafts on too (small: cheap) + // the heat's red shafts at 35 °C, between and at 43 °C; and at 43 °C with the UV's shafts on too (small: cheap) const hot = Promise.all([["heat", [{ heat: 0.3 }, { heat: 0.65 }, { heat: 1 }]], ["heat,uv", [{ heat: 1, uv: 1 }]]].map(async ([name, levels]) => { const p = await weatherPage(browser, url, { query: `?fx=${name}`, driven: true, context: { viewport: { width: 640, height: 480 } } }); - const seen = await sunSeen(p.page, levels); - seen.grid = (await gridPeak(p.page)).ratio; // (its veil's dithering) + const seen = await heatSeen(p.page, levels); + seen.grid = (await gridPeak(p.page)).ratio; // (its shafts' dithering) seen.errors = p.errors; await p.context.close(); return seen; @@ -2782,11 +2765,10 @@ const WEATHER = { const f = Sky.state().flood; return { depth: f.depth, full: f.full, frog: f.frog, running: Sky.state().running, frames: Sky.state().frames }; }); - out.still.heat = await still.page.evaluate(() => { // (the heat: its sun, still) + out.still.heat = await still.page.evaluate(() => { // (the heat: its shafts, still) document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { heat: 1 } })); - const h = Sky.state().heat, c = document.querySelector("#sky canvas"); - const [r, g, b, a] = c.getContext("2d").getImageData(h.sun[0], h.sun[1], 1, 1).data; - return { sun: h.sun, home: h.home, built: h.built, flares: h.flares.length, drawn: Sky.state().drawn.heat, at: [r, g, b, a], + const h = Sky.state().heat; + return { shafts: h.shafts.length, on: h.shafts.filter((s) => s.on === 1 && s.at !== null).length, drawn: Sky.state().drawn.heat, running: Sky.state().running, frames: Sky.state().frames }; }); out.still.gust = await still.page.evaluate(() => { // (a gust: nothing sent, by the page or the test link) From 629de23374923bf110835349d988f88c851d9ade Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 03:48:55 +0000 Subject: [PATCH 098/146] Web dashboard: the gust link a one-off, never in the URL (?fx=gust ignored: no flyer on a reload); the grip 4x4 dots Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/web_dashboard.html | 20 +++++++++----------- tests/test_web_dashboard.py | 18 +++++++++++------- tests/web_dashboard_browser.js | 18 +++++++++++++++--- 3 files changed, 35 insertions(+), 21 deletions(-) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index 6e3fd135..3511df2d 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -46,7 +46,7 @@ .chip { border-radius: 1.875cqw; } /* The grip and the × (hide), shown only on mouseover, on a tile picked up, or (touch) on one long-pressed and let go in place */ .grip, .close { position: absolute; top: 6px; z-index: 1; opacity: 0; pointer-events: none; transition: opacity 0.15s ease; } - .grip { left: 8px; width: 15px; height: 30px; cursor: grab; /* (dots 5px apart: three across, six down) */ + .grip { left: 8px; width: 20px; height: 20px; cursor: grab; /* (dots 5px apart: four across, four down) */ background: radial-gradient(circle, var(--soft) 1.1px, transparent 1.5px) 0 0 / 5px 5px; } .close { right: 5px; width: 22px; height: 22px; padding: 0; border: 0; border-radius: 50%; background: none; color: var(--soft); font: 18px/22px system-ui, sans-serif; cursor: pointer; } @@ -4442,8 +4442,8 @@ "ecobot-fx-stop"; a link clicked after it starts the animations again, with its effect), one link per effect, simulating its condition (the effect and its tile's red frame, as a real one; the gauges keep their readings; nothing saved), and the same as a URL parameter: ?fx=rain, ?fx=haze3,wind,ice, ?fx=all (rain light, rain2 heavy (now and then a drop sticking to the glass), rain3 heavy with a flash - flood (its first frog 30 s after the water starts rising; off: it drains), haze1-haze5 (or smog1-smog5, its earlier name), uv, humidity light (91 %), humidity2 heavy (100 %), wind, heat, ice; ?fx=all every one, no link of its own); and "gust" (?fx=gust), not - on or off: each click (and ?fx=gust as the page opens) sends one cow, barn or chicken across, as a gust over 99 km/h does. To remove: delete + flood (its first frog 30 s after the water starts rising; off: it drains), haze1-haze5 (or smog1-smog5, its earlier name), uv, humidity light (91 %), humidity2 heavy (100 %), wind, heat, ice; ?fx=all every one, no link of its own); and "gust", not + on or off and never in the URL (?fx=gust is ignored): each click sends one cow, barn or chicken across, as a gust over 99 km/h does. To remove: delete from here to "END TEMPORARY" (this style, the row and its script). The page's own listener for "ecobot-fx" then simply hears nothing. --> -
test:
+