git clone https://garage44.eu/jeroen/cartopolis.gitcartopolis-agent · 2026-11-26T14:38:34Z
refactor(gui): remove egui The last step of the component-library port: every screen has drawn through the library since stage 1, and nothing reached egui any more but the manager, the theme's painters and the input it reported. - egui and egui-wgpu are out of both manifests; tools/dep-rules.ts now refuses them (and epaint, ecolor) in the client, the APK, mithril_bevy and the viewer. wgpu is a direct dependency for the types Bevy does not re-export (DeviceType, Backend, the vendored wgpu::meter). - egui_manager.rs, theme/style.rs and theme/palette32.rs are deleted; golden colours pin straight bytes, nine translucent ones moving one byte that egui's premultiplying had rounded. - UiInput is fed by the library alone: a click belongs to the interface over a library screen or, for a finger, outside the map's free area; the keyboard yields to a focused library field, a modal or the edit dialog; map_dragged comes from a new track_map_drag (a press on the bare map that travels more than 6 pt). - The faces egui carried come along on their own: Hack as theme::MONO_TTF for code fields, line badges and departure boards, and Noto Emoji as the library's fallback face (FontMap::emoji), so a chat's emoji and the call reactions draw instead of empty boxes. - render_scale no longer shrinks the interface's camera (order 100 and up, INTERFACE_CAMERA_ORDER): on the phone tier every screen was drawn at the reduced resolution and stretched, text and all. - source_rules drops the rules that guarded egui calls; CLAUDE.md's "egui and input" rules become "The interface and input", and the notes are renamed (ui-input.md, texture-lifetime.md) or retired (egui-quiet-frame-staleness.md).
.claude/skills/shots/SKILL.md | 2 +-
CLAUDE.md | 28 +-
Cargo.lock | 169 +--
Cargo.toml | 10 +-
assets/fonts/Hack-Regular.ttf | 3 +
assets/fonts/README.md | 10 +
crates/cartopolis/Cargo.toml | 15 +-
crates/cartopolis/src/lib.rs | 11 +-
crates/cartopolis/src/platform/storage.rs | 8 +-
crates/cartopolis/src/source_rules.rs | 155 +--
crates/cartopolis/src/systems/dev/frame_pacing.rs | 4 -
crates/cartopolis/src/systems/dev/perf.rs | 2 +-
crates/cartopolis/src/systems/dev/shot_harness.rs | 4 +-
crates/cartopolis/src/systems/dev/ui_probe.rs | 1 +
crates/cartopolis/src/systems/dev/upload_meter.rs | 2 +-
crates/cartopolis/src/systems/gui/chat_overlay.rs | 2 +-
crates/cartopolis/src/systems/gui/discs.rs | 23 +-
crates/cartopolis/src/systems/gui/dismiss.rs | 32 +-
crates/cartopolis/src/systems/gui/egui_manager.rs | 1331 --------------------
.../src/systems/gui/egui_manager/tests.rs | 753 -----------
crates/cartopolis/src/systems/gui/icons.rs | 56 +-
crates/cartopolis/src/systems/gui/lib_call.rs | 95 +-
crates/cartopolis/src/systems/gui/lib_host.rs | 35 +-
crates/cartopolis/src/systems/gui/mod.rs | 1 -
crates/cartopolis/src/systems/gui/motion.rs | 4 +-
crates/cartopolis/src/systems/gui/plugin.rs | 35 +-
crates/cartopolis/src/systems/gui/theme/color.rs | 124 +-
crates/cartopolis/src/systems/gui/theme/frames.rs | 2 +-
crates/cartopolis/src/systems/gui/theme/golden.rs | 26 +-
.../src/systems/gui/theme/golden_colours.txt | 338 ++---
crates/cartopolis/src/systems/gui/theme/metrics.rs | 139 +-
crates/cartopolis/src/systems/gui/theme/mod.rs | 23 +-
crates/cartopolis/src/systems/gui/theme/palette.rs | 7 +-
.../cartopolis/src/systems/gui/theme/palette32.rs | 118 --
crates/cartopolis/src/systems/gui/theme/style.rs | 230 ----
crates/cartopolis/src/systems/gui/theme/tests.rs | 336 ++---
crates/cartopolis/src/systems/gui/ui_input.rs | 322 +++--
crates/cartopolis/src/systems/map/render_scale.rs | 30 +-
crates/cartopolis/src/systems/map/street_labels.rs | 23 +-
crates/cartopolis/src/systems/mod.rs | 9 +-
crates/cartopolis/src/systems/nav/transit_live.rs | 13 +-
.../cartopolis/src/systems/nav/transit_vehicles.rs | 17 +-
crates/cartopolis/src/systems/net/chat_pictures.rs | 6 +-
crates/cartopolis/src/systems/net/voice.rs | 6 +-
.../cartopolis/src/systems/player/free_camera.rs | 10 +-
crates/cartopolis/src/systems/player/picking.rs | 2 +-
crates/cartopolis/src/systems/player/touch.rs | 12 +-
crates/cartopolis/src/utils/clipboard.rs | 9 +
crates/cartopolis_android/Cargo.toml | 2 +-
crates/mithril_bevy/src/images.rs | 2 +-
crates/mithril_bevy/src/tree.rs | 21 +-
crates/viewer/Cargo.toml | 2 +-
docs/guides/development.md | 6 +-
docs/notes/android-build.md | 22 +-
docs/notes/avatar-faces.md | 11 +-
docs/notes/chat-without-a-panel.md | 12 +-
docs/notes/client-build-cost.md | 7 +-
docs/notes/component-library-in-the-client.md | 156 +--
docs/notes/design-room.md | 6 +-
docs/notes/driving-the-client-from-an-ide.md | 29 +-
docs/notes/egui-shared-root-ui.md | 142 ---
docs/notes/egui-texture-lifetime.md | 72 --
docs/notes/icon-font.md | 14 +-
docs/notes/makehuman-avatars.md | 4 +-
docs/notes/map-chrome.md | 140 +-
docs/notes/module-graph.md | 7 +-
docs/notes/navigation-display.md | 26 +-
docs/notes/pictures-in-private-chats.md | 6 +-
docs/notes/place-photos.md | 36 +-
docs/notes/render-performance-survey.md | 43 +-
docs/notes/render-scale-shrinks-the-target.md | 11 +-
.../{ => retired}/egui-quiet-frame-staleness.md | 15 +-
docs/notes/route-planner-sheet.md | 66 +-
docs/notes/scenarios.md | 22 +-
docs/notes/screen-overlay-projection.md | 50 +-
docs/notes/selecting-a-building.md | 9 +-
docs/notes/session-modes.md | 25 +-
docs/notes/terrain-relief.md | 13 +-
docs/notes/texture-lifetime.md | 51 +
docs/notes/tile-raster-cost.md | 6 +-
docs/notes/touch-input.md | 431 ++-----
docs/notes/ui-input.md | 78 ++
docs/notes/ui-vocabulary.md | 464 ++-----
docs/notes/web-client-is-the-world.md | 15 +-
docs/notes/web-persistence.md | 5 +-
docs/notes/zoom-ladder.md | 17 +-
tools/dep-rules.ts | 11 +
87 files changed, 1535 insertions(+), 5113 deletions(-)
diff --git a/.claude/skills/shots/SKILL.md b/.claude/skills/shots/SKILL.md
index 615f034b..6836ebc6 100644
--- a/.claude/skills/shots/SKILL.md
+++ b/.claude/skills/shots/SKILL.md
@@ -69,7 +69,7 @@ cargo run -p cartopolis -- --shot /tmp/fly.png \
- Each capture waits for the streams to go quiet (`--settle`, capped by `--wait`)
rather than sleeping. Both count *virtual* seconds clamped at 0.25 s a frame, so
on a slow renderer they run ~6× longer than they read.
-- The egui overlay is in the picture (the HUD documents the shot); `--hide-ui`
+- The interface is in the picture (the HUD documents the shot); `--hide-ui`
drops it. `--ui a,b` opens panels and states — the vocabulary is
`shot_harness::UI_ELEMENTS` (`dev`, `layers`, `route` seeds a demo route,
`driver`, `sit`, `fire`, `building`, `inside`, `chat`, `settings`, `all`, …);
diff --git a/CLAUDE.md b/CLAUDE.md
index 249a0589..d93bec35 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -48,7 +48,7 @@ crates/cartopolis_android/build-apk.sh # → $CARGO_TARGET_DIR/android/cartopol
**`cargo check` does not compile `cfg(test)` code.** The suite silently rotted
through the egui 0.35 migration until someone ran it, so run the tests, not just a
-check, when touching egui or the building geometry. Unit tests live in
+check, when touching the interface or the building geometry. Unit tests live in
`#[cfg(test)]` modules; `cartopolis` is a lib plus a shim bin, both shim bins carry
`test = false` and the owned libs `doctest = false`, so `cargo test` links a harness
only for targets with tests in them.
@@ -121,7 +121,7 @@ in the gate's `tests` step: a new rule goes in its table, not only in this one.
| `cartopolis_atlas` (`crates/atlas`) | Map-data pipelines, terrain tiles, and the web UI in `crates/atlas/web` (`atlas.md`) |
| `cartopolis_server` (`crates/server`, `cartopolis-server`) | The simulator and atlas as one program: one binary, one `cartopolis.toml` (`[atlas]` inside), one HTTP address; atlas runs as a supervised second process of it, never in the tick's runtime (`the-server-stack.md`) |
| `cartopolis_viewer` (`crates/viewer`, `carto-view`) | Draws what `cartopolis_geo` builds, in seconds, with stock materials; must not depend on `cartopolis`, and is a second Bevy binary in every workspace build |
-| `cartopolis` | The Bevy 0.20 client: rendering, ECS systems, egui 0.36 UI |
+| `cartopolis` | The Bevy 0.20 client: rendering, ECS systems, the component library's screens (`mithril_bevy` natively, DOM on the web) |
| `cartopolis_android` | The APK's `cdylib`; both dependencies target-gated, so empty off Android (`android-build.md`) |
| `cartopolis_mcp` (`crates/mcp_server`) | The client's MCP server: a socket on Unix desktops, the Midas device link on Android. **No `bevy` or `cartopolis`** (`driving-the-client-from-an-ide.md`) |
| `cartopolis_materials` (`crates/materials`) | The custom material types and `MaterialsPlugin` only, split for build cost; never depends on `cartopolis` |
@@ -184,8 +184,7 @@ hand-mirrors `auth::AccountRow`**: change an account field and change it there t
Each of these bit someone, usually silently. The note behind each has the story.
The ones a source scan can hold are tests (`crates/cartopolis/src/source_rules.rs`,
-the panel chain in `egui_manager.rs`, the fixture in `testdata.rs`); the rest are
-prose, so read them.
+the fixture in `testdata.rs`); the rest are prose, so read them.
**Bevy and the ECS**
- A command aimed at an entity another system may despawn uses `try_insert` / `try_remove` / `try_despawn`; a release build only warns, a debug build panics — `entity-commands-outlive-entities.md`
@@ -201,7 +200,7 @@ prose, so read them.
- A ring streamer centres on `AnchoredCamera::stream_xz_at` (`grid::StreamCentre`), never the camera: in Earth mode a rotate-drag swings the camera round a 2 km circle — `render-performance-survey.md`
- Bound every streaming path per frame **in bytes** (`stream_ledger::admit`), not only in items, and gate it on drift or altitude: mass mesh churn loses the GPU device — `upload-bursts.md`
- `NoFrustumCulling` also enters an entity into every shadow cascade; add `NotShadowCaster` unless it really casts — `render-performance-survey.md`
-- Never destroy a texture or buffer in the frame that recorded work on it; defer the free past `Queue::submit` — `egui-texture-lifetime.md`
+- Never destroy a texture or buffer in the frame that recorded work on it; defer the free past `Queue::submit` (the library's `ImageCache` frees a sweep late) — `texture-lifetime.md`
- Altitude-driven visuals crossfade on `GlobeState::space_factor`, never switch on `in_space`, or a climb steps mid-zoom — `the-atmosphere-from-the-street-to-orbit.md`
- Key any world-fixed shader pattern to anchor metres (UV0, `MeshTag`), never `world_position`: `big_space` jumps the render origin a whole cell — `water-surface.md`
- Shaders are WESL (`import a::b;`, `@if`, bevy modules by file path); a shader error shows only in a run's log, never in `cargo check` or `cargo test` — `shaders-are-wesl.md`
@@ -211,16 +210,15 @@ prose, so read them.
- Find a ring's outward side by probing 5 cm off the edge, never from its signed area: +z runs south, so winding rules come out inside-out — `doors-and-rooms.md`
- Anything reading `Query<&Window>` falls back to `resources::HeadlessSurface`; a scissor that does not match the target quits a headless run silently — `headless-shots-software-renderer.md`
-**egui and input**
-- Systems reach egui through `EguiRef` / `EguiMut`, never `Res<EguiManager>` — it is non-send on wasm, so the mistake breaks only the web check — `egui-shared-root-ui.md`
-- Every system drawing into the shared root `Ui` goes in the panel-chain `.chain()` tuple in `systems/gui/plugin.rs`, or panels steal each other's clicks — `egui-shared-root-ui.md`
-- Floating `Area`s paint over panels: a world-anchored overlay culls (not clips) itself to `place_pins::map_area` and runs at the chain's tail — `egui-shared-root-ui.md`
-- UI chrome — colour, spacing, type, overlay frames, panel headers and close buttons — comes from `systems::theme`; never a fresh `Color32` for chrome in a panel (a palette for content, people or categories, is a named const in its module) — `ui-vocabulary.md`
-- Gate a world click on `UiInput::owns_click` (`systems::ui_input`, egui's and the library's verdict in one); `wants_pointer()` is only right while a button is down — `touch-input.md`
-- Game keys yield only to `UiInput::ui_owns_keyboard` (a focused text field), never `egui_wants_keyboard_input()`; read the UI's scale and size from `UiMetrics`, never egui — `egui-shared-root-ui.md`
-- Touch emits no mouse events: world clicks get an emulated mouse, gestures read `TouchGestures`, egui reads the event stream — `touch-input.md`
-- A clickable widget with a context menu guards its click with `!response.long_touched()`, because a long press also fires `clicked()` — `touch-input.md`
-- An anchored, size-to-content `Area` pins its content width, or it grows every frame until it spans the screen — `map-chrome.md`
+**The interface and input**
+- The interface is the component library: a screen is a `systems::lib_*` module on `mithril_bevy` natively and DOM on the web; its logic lives on the state, the view only draws it — `component-library-in-the-client.md`
+- UI chrome — colour, spacing, type — comes from `systems::theme` (`theme::p()`, `app_tokens()`) as `theme::Rgba8`; never a fresh colour literal for chrome in a screen (a palette for content, people or categories, is a named const in its module) — `ui-vocabulary.md`
+- A screen dark in both themes draws in `theme::DARK`'s colours rather than mounting dark: the host's dark switch is one for every screen — `ui-vocabulary.md`
+- A node is not laid out in the frame that makes it: ticking content (a timer, a readout) rewrites its text in place through a signal, never rebuilds its rows — `component-library-in-the-client.md`
+- A panel that takes room from the map marks its root `data-reserves-map`, or the dock, pins and names stand under it (`UiInput::map_rect`) — `ui-input.md`
+- Gate a world click on `UiInput::owns_click`; a finger's brisk tap has lifted before its click arrives, so it is judged by where it landed — `touch-input.md`
+- Game keys yield only to `UiInput::ui_owns_keyboard` (a focused text field, a modal); read the UI's scale and size from `UiMetrics` and convert window points with `window_to_ui` — `ui-input.md`
+- Touch emits no mouse events: world clicks get an emulated mouse, gestures read `TouchGestures`, the library reads Bevy's picking pointers — `touch-input.md`
**Platforms**
- Everything the client keeps for the user (settings, chats, photos) goes through `platform::storage`, never `std::fs`, which fails on wasm; `std::fs` is for code that never runs on the web (caches, crash reports, dev tools). On the web a read can be `Loading`, and treating that as `Missing` never recovers — `web-persistence.md`
diff --git a/Cargo.lock b/Cargo.lock
index 805db23e..7c094daa 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2599,8 +2599,6 @@ dependencies = [
"cpal",
"dotenvy",
"earcutr",
- "egui",
- "egui-wgpu",
"ehttp",
"flate2",
"fontdue",
@@ -2646,6 +2644,7 @@ dependencies = [
"wasm_thread",
"web-sys",
"web-time",
+ "wgpu",
"windows-sys 0.61.2",
"winit",
"winresource",
@@ -2793,7 +2792,7 @@ dependencies = [
"tiff",
"tiny-skia 0.12.0",
"tracing",
- "vello_cpu 0.2.0",
+ "vello_cpu",
]
[[package]]
@@ -4088,16 +4087,6 @@ dependencies = [
"spki 0.7.3",
]
-[[package]]
-name = "ecolor"
-version = "0.36.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0656a7530b9e2841ee7a5f983965bdd9840c32f4012f759cfd44b912cced6b34"
-dependencies = [
- "bytemuck",
- "emath",
-]
-
[[package]]
name = "ed25519"
version = "2.2.3"
@@ -4123,44 +4112,6 @@ dependencies = [
"zeroize",
]
-[[package]]
-name = "egui"
-version = "0.36.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc938cc27cd911415e1e4d151bc56ff9df063d8db081374e87aeb805ea74b2ba"
-dependencies = [
- "accesskit",
- "ahash",
- "bitflags 2.13.1",
- "emath",
- "epaint",
- "itertools 0.15.0",
- "log",
- "nohash-hasher",
- "profiling",
- "smallvec",
- "unicode-segmentation",
- "web-sys",
-]
-
-[[package]]
-name = "egui-wgpu"
-version = "0.36.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5cef1f6d1bba40b09a4d0d62cb822b81030922cfbf65c5373398c3a3caafc5bd"
-dependencies = [
- "ahash",
- "bytemuck",
- "document-features",
- "epaint",
- "log",
- "profiling",
- "thiserror 2.0.20",
- "type-map",
- "web-time",
- "wgpu",
-]
-
[[package]]
name = "ehttp"
version = "0.5.0"
@@ -4218,15 +4169,6 @@ version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
-[[package]]
-name = "emath"
-version = "0.36.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "52c8d4141cf0f60fb2f7aefaf352d3ffa5171ef0ab09731c64391801e95e48f1"
-dependencies = [
- "bytemuck",
-]
-
[[package]]
name = "embedded-io"
version = "0.4.0"
@@ -4306,37 +4248,6 @@ dependencies = [
"syn 2.0.119",
]
-[[package]]
-name = "epaint"
-version = "0.36.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a0ec0308dc23130fc1a7d4623a8534c2ed069c6dc84e258ee4f3de99615aa1a3"
-dependencies = [
- "ahash",
- "bytemuck",
- "ecolor",
- "emath",
- "epaint_default_fonts",
- "font-types",
- "harfrust",
- "log",
- "nohash-hasher",
- "parking_lot",
- "profiling",
- "self_cell",
- "skrifa",
- "smallvec",
- "unicode-general-category",
- "unicode-segmentation",
- "vello_cpu 0.1.0",
-]
-
-[[package]]
-name = "epaint_default_fonts"
-version = "0.36.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13"
-
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -4932,22 +4843,6 @@ dependencies = [
"simba",
]
-[[package]]
-name = "glifo"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed4a1bb24121291d27230c1b1b44e07d6a9b28cefdb32fe1581dfb84e14f940a"
-dependencies = [
- "bytemuck",
- "foldhash 0.2.0",
- "hashbrown 0.17.1",
- "log",
- "peniko",
- "skrifa",
- "smallvec",
- "vello_common 0.1.0",
-]
-
[[package]]
name = "glifo"
version = "0.3.0"
@@ -4962,7 +4857,7 @@ dependencies = [
"png",
"skrifa",
"smallvec",
- "vello_common 0.2.0",
+ "vello_common",
]
[[package]]
@@ -7053,12 +6948,6 @@ dependencies = [
"once_cell",
]
-[[package]]
-name = "nohash-hasher"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
-
[[package]]
name = "nokhwa"
version = "0.10.11"
@@ -9414,12 +9303,6 @@ dependencies = [
"zeroize",
]
-[[package]]
-name = "self_cell"
-version = "1.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813"
-
[[package]]
name = "semver"
version = "1.0.28"
@@ -10898,15 +10781,6 @@ version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8464ec13c3691491391d9fce00f6416c9a48e46972f72d7865688be2080192c9"
-[[package]]
-name = "type-map"
-version = "0.5.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90"
-dependencies = [
- "rustc-hash 2.1.3",
-]
-
[[package]]
name = "typeid"
version = "1.0.3"
@@ -10981,12 +10855,6 @@ version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
-[[package]]
-name = "unicode-general-category"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f"
-
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -11143,21 +11011,6 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
-[[package]]
-name = "vello_common"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2e9aed918117e8152c9eddfd8362d73c465c23f26c44786aa331707b8a64fa2"
-dependencies = [
- "bytemuck",
- "fearless_simd",
- "guillotiere",
- "log",
- "peniko",
- "smallvec",
- "thiserror 2.0.20",
-]
-
[[package]]
name = "vello_common"
version = "0.2.0"
@@ -11174,18 +11027,6 @@ dependencies = [
"thiserror 2.0.20",
]
-[[package]]
-name = "vello_cpu"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ac7349e1f55f6b801c7c277958df4ea53e7f20f21e8014910ad888b2ecda93ea"
-dependencies = [
- "bytemuck",
- "glifo 0.2.0",
- "hashbrown 0.17.1",
- "vello_common 0.1.0",
-]
-
[[package]]
name = "vello_cpu"
version = "0.2.0"
@@ -11193,10 +11034,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9"
dependencies = [
"bytemuck",
- "glifo 0.3.0",
+ "glifo",
"hashbrown 0.17.1",
"png",
- "vello_common 0.2.0",
+ "vello_common",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index b19153e4..feb78d6c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -172,13 +172,13 @@ bevy = { version = "0.20", default-features = false, features = [
# now (above) but the client uses `Fxaa`, which needs no LUT at all. Adding
# it back is only worth it if somebody switches the edge filter to `Smaa`.
# * `default_font` is `bevy_text?/default_font`, and `bevy_text` is not enabled
- # either — the UI is egui, which carries its own font (`systems::theme`). A
- # pure no-op.
+ # either — the client embeds its own faces and hands them to the
+ # component library (`systems::theme`, `lib_host`'s `FontMap`). A pure
+ # no-op.
#
# Two more went on 2026-08-19, by the same audit:
#
- # * `custom_cursor` — zero hits for `CustomCursor`/`CursorIcon` in the client
- # (the `cursor` matches are all `egui::text::CCursor`).
+ # * `custom_cursor` — zero hits for `CustomCursor`/`CursorIcon` in the client.
# * `jpeg` — bevy_image's JPEG decoder for `asset_server.load`, and no image
# in this tree goes through the asset server at all: tiles, photos and the
# window icon decode via the `image` crate directly, and the glTFs embed
@@ -191,8 +191,6 @@ bevy = { version = "0.20", default-features = false, features = [
bevy_image = { version = "0.20", features = ["zstd_rust"] }
big_space = { path = "crates/big_space" }
bytes = "1.9"
-egui = "0.36"
-egui-wgpu = { version = "0.36", default-features = false }
clap = { version = "4.5", features = ["derive"] }
earcutr = "0.4"
figment = { version = "0.10", features = ["toml", "env"] }
diff --git a/assets/fonts/Hack-Regular.ttf b/assets/fonts/Hack-Regular.ttf
new file mode 100644
index 00000000..45d33832
--- /dev/null
+++ b/assets/fonts/Hack-Regular.ttf
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:15f55cc0c85a2988d2b4b3a8cdb5d77fdfbaf319e1bb5309d725db9818fb7125
+size 309408
diff --git a/assets/fonts/README.md b/assets/fonts/README.md
index 9c16737d..c72eeaf0 100644
--- a/assets/fonts/README.md
+++ b/assets/fonts/README.md
@@ -38,3 +38,13 @@ so chat emoji draw instead of `◻`: egui's bundled Noto Emoji stops at U+1F6C5.
Google Fonts ships it as a variable font (`NotoEmoji[wght].ttf`, google/fonts
`ofl/notoemoji`); this file is that instanced at `wght` 400 with fontTools
(`fonttools varLib.instancer NotoEmoji[wght].ttf wght=400`), 0.9 MB.
+
+**Hack** (`Hack-Regular.ttf`) — MIT License (Source Foundry Authors), derived
+from Bitstream Vera Sans Mono (Bitstream Vera License) and DejaVu (public
+domain). <https://sourcefoundry.org/hack/>
+
+The monospace face (`theme::MONO_TTF`): the library's code fields, the transit
+line numbers, the live departures board and the street-name fallback. Copied
+unchanged from `epaint_default_fonts` 0.36.2, which is where the client took it
+from while it still linked egui. Both licences require their notices to travel
+with the font; keep this one.
diff --git a/crates/cartopolis/Cargo.toml b/crates/cartopolis/Cargo.toml
index 6f2bd97a..c3cc93d9 100644
--- a/crates/cartopolis/Cargo.toml
+++ b/crates/cartopolis/Cargo.toml
@@ -42,8 +42,7 @@ test = false
# every server uses. The simulator crate survives here as a dev-dependency, so
# the loopback tests still boot the real thing.
# `ui-probe`: the component library's screens on bevy_ui, the app's interface
-# since 2026-11-25 (egui is on its way out; `CARTO_UI_LIB=0` brings it back
-# until then).
+# since 2026-11-25 and its only one since egui went (2026-11-26).
default = ["audio", "comms", "ui-probe"]
# `audio`: the avatar soundscape (`systems::soundscape` — footsteps, landings,
# wind). On by default, because a city you can walk through in silence reads as a
@@ -137,9 +136,7 @@ perf = [
scalar-fallback = []
# Bevy's own UI stack, for the component-library study's phase 0
# (`docs/mockups/component-library/`): `systems::dev::ui_probe` draws one card
-# with `bevy_ui` beside egui's Settings panel, and a long list for the layout
-# cost. Off by default — nothing in the client reads these crates otherwise,
-# and a shipped build must not carry a second UI toolkit for a measurement.
+# with `bevy_ui`, and a long list for the layout cost.
# The component library's screens (`systems::lib_settings`), on whichever
# backend the lane has: `ui-probe` draws them through `bevy_ui` (native),
# `ui-dom` as DOM over the canvas (the web build, `systems::lib_host`).
@@ -209,7 +206,6 @@ cartopolis_calls = { path = "../calls", features = ["client"], optional = true }
# The private-chat state blob (`systems::private_chat`); already built for core.
postcard = { workspace = true }
bytes.workspace = true
-egui.workspace = true
# The component library and its Bevy backend, for the `ui-probe` feature
# (docs/mockups/component-library, phase 3); not in a shipped build yet.
mithril = { git = "https://code.garage44.eu/jeroen/mithril.git", rev = "3dedb903", optional = true }
@@ -222,7 +218,12 @@ tiny-skia = { version = "0.11", default-features = false, features = ["std", "si
# are what the web's `theme.css` is written from and what the Bevy backend
# draws with. Bevy-free and dependency-free, so every lane carries it.
mithril_style = { git = "https://code.garage44.eu/jeroen/mithril.git", rev = "3dedb903" }
-egui-wgpu.workspace = true
+# wgpu itself, for the adapter's `DeviceType`/`Backend` and the vendored
+# `wgpu::meter` (`upload_meter`, `shot_harness`), which bevy does not
+# re-export. The one bevy links (the `crates/wgpu` patch); `std` and `wgsl`
+# are what egui-wgpu asked of it while it was here, kept so its features do
+# not move.
+wgpu = { version = "30", default-features = false, features = ["std", "wgsl"] }
# The contact link drawn as a QR code (`systems::contacts`). Pure Rust with no
# dependencies of its own, so it builds on every lane, Android and wasm included.
qrcodegen = { version = "1.8", optional = true }
diff --git a/crates/cartopolis/src/lib.rs b/crates/cartopolis/src/lib.rs
index fd9bfa3e..3229467f 100644
--- a/crates/cartopolis/src/lib.rs
+++ b/crates/cartopolis/src/lib.rs
@@ -113,7 +113,6 @@ use resources::{
EditDialogState, GameState, LocalAvatarSimId, MarqueeState, OsmTileUrlTemplate,
PrimTextureCache, TextureLibrary,
};
-use systems::egui_manager::EguiPlugin;
use systems::*;
/// Start the client.
@@ -973,15 +972,11 @@ fn run_client() {
// there to be replaced.
.add_plugins(render_setup::MeshSlabCapPlugin)
// `UiMetrics` and `UiInput`: the UI's scale and who owns the input, as
- // plain resources (`systems::ui_input`). Before `EguiPlugin`, which
- // writes egui's half of `UiInput`.
+ // plain resources (`systems::ui_input`), written by the library's side.
.add_plugins(systems::ui_input::UiInputPlugin)
- .add_plugins(EguiPlugin)
// Renders the 3D world below the screen's resolution on a tier that asks
- // for it, and no-ops entirely on the tiers that do not. Must come after
- // `EguiPlugin`, which is what puts `egui_pass` after `upscaling` — the
- // ordering that keeps the interface at full resolution while the world
- // scales.
+ // for it, and no-ops entirely on the tiers that do not. The interface
+ // stays at full resolution: the library draws on its own camera.
.add_plugins(systems::render_scale::RenderScalePlugin)
// Watches the render app's `PipelineCache` for pipelines that failed to
// build, for the diagnostics report — a failed pipeline is otherwise a
diff --git a/crates/cartopolis/src/platform/storage.rs b/crates/cartopolis/src/platform/storage.rs
index 924966c1..ba523a45 100644
--- a/crates/cartopolis/src/platform/storage.rs
+++ b/crates/cartopolis/src/platform/storage.rs
@@ -23,7 +23,7 @@
//!
//! IndexedDB has **no synchronous read**, and two callers need one:
//! `UserStore::load` runs while the `App` is still being built, and
-//! `photo_store::read_thumb` runs inside an egui draw. Neither can `await`.
+//! `photo_store::read_thumb` runs inside a screen's draw. Neither can `await`.
//!
//! So on the web, [`preload`] pulls a prefix of the Data namespace into memory
//! *before the app is constructed* ([`crate::run`]), and [`get_now`] answers out
@@ -158,7 +158,7 @@ pub fn view_bytes() -> usize {
imp::view_bytes()
}
-/// Read from a synchronous context — an egui pass, or `App` construction.
+/// Read from a synchronous context — a screen being drawn, or `App` construction.
///
/// Natively this is the file read, and answers `Ready` or `Missing` in the same
/// call. On the web it answers out of the in-memory view, and a key that is in
@@ -195,8 +195,8 @@ pub fn remove_now(ns: Namespace, key: &str) {
///
/// It exists because neither platform can answer "cleared" in the call: natively
/// the work is a directory walk on another thread, and on the web it is a chain of
-/// IndexedDB requests. A caller that wanted a return value would have to block an
-/// egui frame on a filesystem.
+/// IndexedDB requests. A caller that wanted a return value would have to block a
+/// frame on a filesystem.
#[derive(Default)]
pub struct ClearProgress {
done: std::sync::atomic::AtomicBool,
diff --git a/crates/cartopolis/src/source_rules.rs b/crates/cartopolis/src/source_rules.rs
index 82349ae2..36363b01 100644
--- a/crates/cartopolis/src/source_rules.rs
+++ b/crates/cartopolis/src/source_rules.rs
@@ -3,8 +3,8 @@
//! Each rule here bit someone silently, and a line of prose only reaches the
//! agent that happens to read it; a red test reaches every one. These read the
//! sources rather than the types because none of them is a type error: a
-//! `Res<EguiManager>` compiles everywhere but the web, and a `NoFrustumCulling`
-//! without `NotShadowCaster` compiles and draws, just into every shadow cascade.
+//! `NoFrustumCulling` without `NotShadowCaster` compiles and draws, just into
+//! every shadow cascade, and `std`'s clock compiles and panics on the web.
//! The one tile fixture (`cartopolis_geo::testdata`) is held the same way,
//! where it lives.
//!
@@ -53,35 +53,6 @@ fn code_lines_with(needle: &str) -> Vec<String> {
hits
}
-/// `EguiManager` is non-send on wasm, so `Res<EguiManager>` compiles and
-/// runs on every native target and breaks only the web build
-/// (`docs/notes/egui-shared-root-ui.md`).
-#[test]
-fn egui_is_reached_through_egui_ref_and_egui_mut() {
- let hits: Vec<_> = ["Res<EguiManager>", "ResMut<EguiManager>"]
- .iter()
- .flat_map(|n| code_lines_with(n))
- .collect();
- assert!(
- hits.is_empty(),
- "reach egui through `EguiRef` / `EguiMut`, never `Res<EguiManager>`:\n{}",
- hits.join("\n")
- );
-}
-
-/// `egui_wants_keyboard_input()` is true for any focused widget, a button
-/// included, so game keys died after every click on the UI. Only a focused
-/// text field owns the keyboard (`docs/notes/egui-shared-root-ui.md`).
-#[test]
-fn game_keys_yield_only_to_a_focused_text_field() {
- let hits = code_lines_with("egui_wants_keyboard_input");
- assert!(
- hits.is_empty(),
- "use `UiInput::ui_owns_keyboard`, never `egui_wants_keyboard_input()`:\n{}",
- hits.join("\n")
- );
-}
-
/// Bevy's shader compiles and screenshot readbacks share
/// `AsyncComputeTaskPool`, so blocking work there stalls them; it goes through
/// `platform::workers` (`docs/notes/headless-shots-software-renderer.md`).
@@ -215,24 +186,6 @@ fn the_clock_is_web_time_where_the_web_runs() {
);
}
-/// Time and curve live in `systems::motion` (`docs/mockups/fluid-ui/`): a
-/// panel says what kind of change it draws and takes the duration from there,
-/// so the five durations stay five and the reduced-motion setting reaches
-/// everything. egui's `animate_*` is called in that one module only.
-#[test]
-fn every_animation_goes_through_motion() {
- let hits: Vec<_> = ["animate_bool", "animate_value"]
- .iter()
- .flat_map(|n| code_lines_with(n))
- .filter(|hit| !hit.contains("systems/gui/motion.rs"))
- .collect();
- assert!(
- hits.is_empty(),
- "take durations and curves from `systems::motion`, never egui's `animate_*` directly:\n{}",
- hits.join("\n")
- );
-}
-
/// The ground floor of the module graph names nothing above it.
///
/// `resources` was meant as the state layer everyone reads, and by 2026-11-19
@@ -273,107 +226,3 @@ fn the_ground_floor_names_no_system() {
bad.join("\n")
);
}
-
-/// Where a control's look is allowed to be egui's own rather than the
-/// theme's: the theme itself, and the controls that are custom by design
-/// (`docs/notes/ui-vocabulary.md`, "The controls are the web's"). A line
-/// elsewhere earns an exception with an `// egui's own:` comment on it or the
-/// line above, saying why.
-const EGUI_OWN_FILES: &[&str] = &[
- "systems/gui/theme/",
- "systems/gui/text_touch.rs",
- // The chat pill over the map and the code editor draw their own fields.
- "systems/gui/chat_overlay.rs",
- "systems/gui/script_editor.rs",
- // The developer tools (the dev panel, the Midas link, release approval):
- // tooling, not the product's face. Bring them over when they are touched.
- "systems/dev/",
- "/tests.rs",
-];
-
-fn egui_own(path: &str, lines: &[&str], i: usize) -> bool {
- EGUI_OWN_FILES.iter().any(|f| path.contains(f))
- || lines[i].contains("egui's own:")
- || (i > 0 && lines[i - 1].contains("egui's own:"))
-}
-
-/// Sites of `needles` outside [`EGUI_OWN_FILES`] and `cfg(test)` modules,
-/// with `ok` false for the ones that break the rule given their window.
-fn raw_widget_sites(needles: &[&str], ok: impl Fn(&[&str], usize) -> bool) -> Vec<String> {
- let mut bad = Vec::new();
- for (path, text) in sources() {
- let rel = path
- .strip_prefix(env!("CARGO_MANIFEST_DIR"))
- .unwrap_or(&path)
- .display()
- .to_string();
- let lines: Vec<&str> = text.lines().collect();
- for (i, line) in lines.iter().enumerate() {
- if line.starts_with("#[cfg(test)]") {
- break;
- }
- if is_comment(line)
- || !needles.iter().any(|n| line.contains(n))
- || egui_own(&rel, &lines, i)
- || ok(&lines, i)
- {
- continue;
- }
- bad.push(format!("{rel}:{}: {}", i + 1, line.trim()));
- }
- }
- bad
-}
-
-/// A text field is `theme::text_field`, never egui's `TextEdit` shown bare:
-/// egui frames a focused field with the pressed button's plate and
-/// `expansion`, the thick dark rim the owner called "really badly styled"
-/// (2026-11-22, `docs/notes/ui-vocabulary.md`).
-#[test]
-fn text_fields_are_the_themes() {
- const REACH: usize = 3;
- let bad = raw_widget_sites(
- &[
- "TextEdit::singleline(",
- "TextEdit::multiline(",
- "text_edit_singleline(",
- "text_edit_multiline(",
- ],
- |lines, i| {
- lines[i.saturating_sub(REACH)..=i]
- .iter()
- .any(|l| l.contains("text_field(") || l.contains("password_field("))
- },
- );
- assert!(
- bad.is_empty(),
- "a text field goes through `theme::text_field` (the web's `.m-input`):\n{}",
- bad.join("\n")
- );
-}
-
-/// A button is one of the theme's — primary, secondary, ghost, danger, icon,
-/// or a menu entry — never a bare `egui::Button`, which beside the painted
-/// ones reads as egui's grey pill (`docs/notes/ui-vocabulary.md`).
-#[test]
-fn buttons_are_the_themes() {
- let bad = raw_widget_sites(&[".button(", "egui::Button::new("], |_, _| false);
- assert!(
- bad.is_empty(),
- "a button is `theme::primary_button_sized` / `secondary_button` / `ghost_button` / \
- `danger_button` / `icon_button`, or `theme::menu_entry` in a menu:\n{}",
- bad.join("\n")
- );
-}
-
-/// A checkbox is `theme::checkbox`: egui's takes the buttons' radius and reads
-/// as a radio button.
-#[test]
-fn checkboxes_are_the_themes() {
- let bad = raw_widget_sites(&["ui.checkbox("], |_, _| false);
- assert!(
- bad.is_empty(),
- "a checkbox is `theme::checkbox`:\n{}",
- bad.join("\n")
- );
-}
diff --git a/crates/cartopolis/src/systems/dev/frame_pacing.rs b/crates/cartopolis/src/systems/dev/frame_pacing.rs
index 0a21ee45..7f529f63 100644
--- a/crates/cartopolis/src/systems/dev/frame_pacing.rs
+++ b/crates/cartopolis/src/systems/dev/frame_pacing.rs
@@ -168,7 +168,6 @@ pub(crate) fn present_rate(
driver: Res<systems::driver::DriverState>,
camera: Query<&Transform, With<crate::components::FreeCamera>>,
prefs: Res<crate::resources::AppPrefs>,
- ui_input: Res<crate::systems::ui_input::UiInput>,
scenario: Option<Res<crate::systems::scenario::ScenarioView>>,
mut rate: ResMut<PresentationRate>,
mut watch: Local<IdleWatch>,
@@ -198,9 +197,6 @@ pub(crate) fn present_rate(
|| mouse.get_just_released().next().is_some()
|| touches.iter().next().is_some()
|| touches.iter_just_released().next().is_some()
- // A card arriving over a still map is the moment somebody is looking
- // hardest; at the idle rate it arrived in steps.
- || ui_input.ui_animating()
// A scenario's clock playing, or its lens's colours easing, over a
// still map: the tracks and areas move while nothing else does
// (egui's repaint request did this before the library drew them).
diff --git a/crates/cartopolis/src/systems/dev/perf.rs b/crates/cartopolis/src/systems/dev/perf.rs
index e74bcde5..a963a05d 100644
--- a/crates/cartopolis/src/systems/dev/perf.rs
+++ b/crates/cartopolis/src/systems/dev/perf.rs
@@ -2217,7 +2217,7 @@ fn finish(
let report = Report {
meta: ReportMeta {
adapter: format!("{:?} {}", adapter.device_type, adapter.name),
- software_renderer: adapter.device_type == egui_wgpu::wgpu::DeviceType::Cpu
+ software_renderer: adapter.device_type == wgpu::DeviceType::Cpu
|| is_software(&adapter.name),
quality: format!("{:?}", crate::quality::budget().tier),
size: run.size.clone(),
diff --git a/crates/cartopolis/src/systems/dev/shot_harness.rs b/crates/cartopolis/src/systems/dev/shot_harness.rs
index b9cc83d1..02468762 100644
--- a/crates/cartopolis/src/systems/dev/shot_harness.rs
+++ b/crates/cartopolis/src/systems/dev/shot_harness.rs
@@ -5366,7 +5366,7 @@ fn record_metrics(
r.total_reserved_bytes / 1024,
)
});
- let gpu_meter = egui_wgpu::wgpu::meter::snapshot();
+ let gpu_meter = wgpu::meter::snapshot();
let deck_steps = readouts.decks.approach_steps(&readouts.terrain);
let m = ShotMetrics {
shot: progress.index + 1,
@@ -5631,7 +5631,7 @@ fn record_metrics(
)
})
.collect(),
- software_renderer: readouts.adapter.device_type == egui_wgpu::wgpu::DeviceType::Cpu,
+ software_renderer: readouts.adapter.device_type == wgpu::DeviceType::Cpu,
vram_allocated_kb: vram.0,
vram_reserved_kb: vram.1,
gpu_buffers_kb: gpu_meter.buffer_bytes / 1024,
diff --git a/crates/cartopolis/src/systems/dev/ui_probe.rs b/crates/cartopolis/src/systems/dev/ui_probe.rs
index c3d7e915..ccc06aef 100644
--- a/crates/cartopolis/src/systems/dev/ui_probe.rs
+++ b/crates/cartopolis/src/systems/dev/ui_probe.rs
@@ -324,6 +324,7 @@ fn spawn_probe(
mono: faces.body.clone(),
icons: None,
icon_scale: 1.0,
+ emoji: None,
});
let p = theme::p();
mithril_bevy::with_host(|host| {
diff --git a/crates/cartopolis/src/systems/dev/upload_meter.rs b/crates/cartopolis/src/systems/dev/upload_meter.rs
index e7465a00..99d3c4cc 100644
--- a/crates/cartopolis/src/systems/dev/upload_meter.rs
+++ b/crates/cartopolis/src/systems/dev/upload_meter.rs
@@ -232,7 +232,7 @@ impl GpuReport {
streamed_assets: usize,
held: impl FnOnce() -> (usize, usize, usize),
) {
- let now = egui_wgpu::wgpu::meter::snapshot();
+ let now = wgpu::meter::snapshot();
let frame = now.written_bytes.saturating_sub(self.written_at_frame);
self.written_at_frame = now.written_bytes;
self.max_frame = self.max_frame.max(frame);
diff --git a/crates/cartopolis/src/systems/gui/chat_overlay.rs b/crates/cartopolis/src/systems/gui/chat_overlay.rs
index 047ab8d0..0abb935a 100644
--- a/crates/cartopolis/src/systems/gui/chat_overlay.rs
+++ b/crates/cartopolis/src/systems/gui/chat_overlay.rs
@@ -465,7 +465,7 @@ pub fn seed_demo_chat(chat: &mut ChatState, overlay: &mut ChatOverlay, open: boo
"The stroopwafel stall is open".into(),
Some(6.0),
);
- chat.receive("local", ME, "You".into(), "On my way".into(), Some(0.0));
+ chat.receive("local", ME, "You".into(), "On my way 👍".into(), Some(0.0));
chat.receive(
"local",
THEM,
diff --git a/crates/cartopolis/src/systems/gui/discs.rs b/crates/cartopolis/src/systems/gui/discs.rs
index ec24126f..89a5fe36 100644
--- a/crates/cartopolis/src/systems/gui/discs.rs
+++ b/crates/cartopolis/src/systems/gui/discs.rs
@@ -6,6 +6,7 @@
use crate::systems::chat::ChatState;
use crate::systems::icons;
+use crate::systems::theme::Rgba8;
/// The round initials, picked by name so a person keeps theirs (`.c1`–`.c6`).
///
@@ -13,17 +14,17 @@ use crate::systems::icons;
/// read as six shades of the same mud, and a person's colour is the one
/// thing in a list of names that is theirs. Each still carries white initials
/// at better than 3:1.
-const AVATAR_TONES: [egui::Color32; 6] = [
- egui::Color32::from_rgb(0x86, 0x5C, 0xC4),
- egui::Color32::from_rgb(0x2C, 0x91, 0x7C),
- egui::Color32::from_rgb(0xC0, 0x66, 0x30),
- egui::Color32::from_rgb(0x43, 0x74, 0xC4),
- egui::Color32::from_rgb(0xB8, 0x48, 0x68),
- egui::Color32::from_rgb(0x5F, 0x8A, 0x2E),
+const AVATAR_TONES: [Rgba8; 6] = [
+ Rgba8::from_rgb(0x86, 0x5C, 0xC4),
+ Rgba8::from_rgb(0x2C, 0x91, 0x7C),
+ Rgba8::from_rgb(0xC0, 0x66, 0x30),
+ Rgba8::from_rgb(0x43, 0x74, 0xC4),
+ Rgba8::from_rgb(0xB8, 0x48, 0x68),
+ Rgba8::from_rgb(0x5F, 0x8A, 0x2E),
];
/// The "Here" disc: the v1 inbox's dark slate, with a location pin on it.
-const HERE_TONE: egui::Color32 = egui::Color32::from_rgb(0x3F, 0x3B, 0x38);
+const HERE_TONE: Rgba8 = Rgba8::from_rgb(0x3F, 0x3B, 0x38);
/// What kind of chat a channel is, which decides what it says about itself.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -49,7 +50,7 @@ pub fn kind_of(key: &str) -> ChatKind {
}
}
-pub(crate) fn tone_for(name: &str) -> egui::Color32 {
+pub(crate) fn tone_for(name: &str) -> Rgba8 {
let h = name
.bytes()
.fold(0u32, |h, b| h.wrapping_mul(31).wrapping_add(u32::from(b)));
@@ -61,10 +62,10 @@ pub(crate) fn tone_for(name: &str) -> egui::Color32 {
/// component library's discs (`lib_chats`).
#[derive(Clone, Debug, PartialEq)]
pub struct DiscLook {
- pub tone: egui::Color32,
+ pub tone: Rgba8,
/// The initial, `#`, or an icon glyph.
pub text: String,
- /// `text` is a glyph of the icon font (egui's fonts fall back to it).
+ /// `text` is a glyph of the icon font.
#[cfg_attr(not(all(feature = "ui-lib", feature = "comms")), allow(dead_code))]
pub icon: bool,
/// The text's size as a share of the disc's.
diff --git a/crates/cartopolis/src/systems/gui/dismiss.rs b/crates/cartopolis/src/systems/gui/dismiss.rs
index d3a4b6ac..d5429a2b 100644
--- a/crates/cartopolis/src/systems/gui/dismiss.rs
+++ b/crates/cartopolis/src/systems/gui/dismiss.rs
@@ -30,17 +30,15 @@
//!
//! ## The one rung the text field owns
//!
-//! A focused text field consumes Escape itself to clear its focus, whatever
-//! this system decides. So "a text field had focus when the frame began"
-//! ([`UiInput`]'s answer) is rung 2 *and this ladder must stop there* —
-//! otherwise a single Escape both blurs the search box and closes the panel
-//! behind it, which is two dismissals for one press and precisely the bug the
-//! single-rung rule exists to prevent.
+//! A text field that consumed Escape itself to clear its focus is rung 2 *and
+//! this ladder must stop there* — otherwise a single Escape both blurs the
+//! search box and closes the panel behind it, which is two dismissals for one
+//! press. Only the old toolkit's fields did; the library's do not take
+//! Escape, so the callers pass `false` and the rung stays for a field that
+//! does.
use bevy::prelude::*;
-use crate::systems::ui_input::UiInput;
-
use crate::resources::{ContextMenuState, EditDialogState, RightPanel};
use crate::systems::driver::DriverState;
use crate::systems::navigation::RouteState;
@@ -373,19 +371,14 @@ impl Dismissable<'_> {
/// Escape walks the ladder and stops. It never quits — that rung belongs to Back
/// alone, and an Escape that could close the application from a bare map is a
/// keystroke nobody wants to discover by accident.
-pub fn handle_escape(keys: Res<ButtonInput<KeyCode>>, ui: Res<UiInput>, mut d: Dismissable) {
+///
+/// No field takes the `TextFocus` rung from here: a library field does not
+/// blur itself on Escape, so the press goes on to close what the field is in.
+pub fn handle_escape(keys: Res<ButtonInput<KeyCode>>, mut d: Dismissable) {
if !keys.just_pressed(KeyCode::Escape) {
return;
}
- let _ = d.dismiss_innermost(text_focused(&ui));
-}
-
-/// Did a text field that blurs itself on Escape hold the keyboard as the
-/// frame began? Only the old toolkit's fields do, as published in
-/// [`UiInput`]; a library field does not take Escape, so it is not this
-/// rung, and the press goes on to close what the field is in.
-fn text_focused(ui: &UiInput) -> bool {
- ui.egui_verdict().text_focused
+ let _ = d.dismiss_innermost(false);
}
#[cfg(test)]
@@ -594,7 +587,6 @@ mod tests {
/// that quits on the first back press while a panel is open would be unusable.
pub fn handle_back_gesture(
keys: Res<ButtonInput<KeyCode>>,
- ui: Res<UiInput>,
mut dismissable: Dismissable,
mut exit: MessageWriter<AppExit>,
) {
@@ -611,7 +603,7 @@ pub fn handle_back_gesture(
// one ladder now (`systems::dismiss`), and the *only* difference between the
// two gestures is this last rung, which is why it is the only thing written
// here.
- if dismissable.dismiss_innermost(text_focused(&ui)).is_none() {
+ if dismissable.dismiss_innermost(false).is_none() {
// On the phone the last rung is "to the background", not "quit": quitting
// ends the process there, so coming back was a cold start that had
// forgotten the tab, the open chat and any call (`move_task_to_back`).
diff --git a/crates/cartopolis/src/systems/gui/egui_manager.rs b/crates/cartopolis/src/systems/gui/egui_manager.rs
deleted file mode 100644
index 3aa1e65f..00000000
--- a/crates/cartopolis/src/systems/gui/egui_manager.rs
+++ /dev/null
@@ -1,1331 +0,0 @@
-//! Egui integration for Bevy 0.19.
-//!
-//! Manual integration using egui-wgpu as the rendering backend,
-//! inspired by https://github.com/vladbat00/bevy_egui.
-//!
-//! Architecture:
-//! - `EguiManager` lives in the main world and holds the egui context plus a
-//! per-frame root `Ui` (egui 0.35 shows panels inside a `Ui`, not the `Context`).
-//! - `begin_egui_frame` (PreUpdate) collects Bevy input, starts the egui frame,
-//! and builds the shared root `Ui`.
-//! - What egui still draws runs in Update through `EguiRef::ctx()`.
-//! - `end_egui_frame` (PostUpdate) finalizes the root `Ui` and tessellates the
-//! output into `EguiRenderOutput`.
-//! - `ExtractResourcePlugin` copies `EguiRenderOutput` to the render world.
-//! - `egui_pass` is a system in the `Core3d` render schedule (Bevy 0.19's
-//! schedule-based render graph), ordered after `Core3dSystems::PostProcess`
-//! (tonemapping) and before `upscaling`.
-
-use crate::platform::sync::Mutex;
-use bevy::{
- core_pipeline::{upscaling::upscaling, Core3d},
- input::{keyboard::KeyboardInput, mouse::MouseScrollUnit, ButtonState},
- prelude::*,
- render::{
- camera::ExtractedCamera,
- extract_resource::{ExtractResource, ExtractResourcePlugin},
- render_resource::{RenderPassDescriptor, TextureFormat},
- renderer::{RenderContext, RenderDevice, RenderQueue, ViewQuery},
- view::ViewTarget,
- RenderApp,
- },
-};
-
-use crate::resources::HeadlessSurface;
-use crate::systems::ui_input::{EguiVerdict, UiInput, UiInputPlugin, UiMetrics};
-
-// ─── Main-world resource ─────────────────────────────────────────────────────
-
-/// How a system reads [`EguiManager`]. A plain resource everywhere but the web.
-///
-/// egui 0.36 holds dropped files as `Arc<dyn DroppedFile>` without `Send + Sync`
-/// on `wasm32` with atomics — a `web_sys::File` is not thread-safe there — so its
-/// `Context`, and with it this whole struct, cannot be a Bevy `Resource` on the
-/// web build. It is a non-send resource there instead, behind these two names, so
-/// no system signature has to carry a `cfg`. Not an `unsafe impl Send`: that
-/// would assert something about Bevy's executor a future Bevy is free to change
-/// (the rule `platform::location` states for its callbacks).
-#[cfg(not(target_arch = "wasm32"))]
-pub type EguiRef<'w> = Res<'w, EguiManager>;
-/// The mutable half of [`EguiRef`].
-#[cfg(not(target_arch = "wasm32"))]
-pub type EguiMut<'w> = ResMut<'w, EguiManager>;
-#[cfg(target_arch = "wasm32")]
-pub type EguiRef<'w> = bevy::ecs::system::NonSend<'w, EguiManager>;
-#[cfg(target_arch = "wasm32")]
-pub type EguiMut<'w> = bevy::ecs::system::NonSendMut<'w, EguiManager>;
-
-/// Holds the egui context for the main Bevy world.
-/// Call [`EguiManager::ctx_mut`] inside Update systems to build UI.
-#[cfg_attr(not(target_arch = "wasm32"), derive(Resource))]
-pub struct EguiManager {
- pub ctx: egui::Context,
- /// Full-viewport background `Ui` rebuilt each frame in `begin_egui_frame`.
- /// egui 0.35 shows panels inside a `Ui`; sharing one across all UI systems
- /// keeps the cooperative panel layout the old ctx-based panels had.
- root_ui: Option<egui::Ui>,
- elapsed_time: f64,
- /// The surface egui lays out against and the UI scale, refreshed each frame
- /// in [`begin_egui_frame`] — the same [`UiMetrics`] the `UiMetrics`
- /// resource holds, by the same arithmetic (`systems::ui_input`), so a
- /// system that reads the resource sees the points egui lays out in. UI
- /// systems read [`Self::compact`] off [`Self::viewport_pts`] to lay out
- /// responsively — egui has no media queries.
- ///
- /// Kept here (rather than read from the resource) because it is also the
- /// fallback for a frame that has **no** surface at all — see
- /// [`begin_egui_frame`] — and a test app may run egui alone.
- metrics: UiMetrics,
- /// What the panels left of the root `Ui` at the end of the last pass — the
- /// map, in egui points. Read by [`Self::owns_click`]; `None` before the first
- /// pass has ended.
- map_rect: Option<egui::Rect>,
- /// Whether the last pass had an animation in progress — egui asked to be
- /// drawn again *now* (`repaint_delay` zero), which is what every
- /// `animate_*` does on each pass it moves. Read by
- /// `frame_pacing::present_rate`, so a surface arriving over a still map
- /// is drawn at the full rate and not the idle one.
- ui_animating: bool,
- /// The pointer is over a screen drawn beside egui (the component
- /// library's): a world click yields to it as it does to a panel. Set
- /// each frame by `lib_host::bridge_input`, for the next frame.
- overlay_owns_pointer: bool,
-}
-
-#[cfg(test)]
-use crate::systems::ui_input::UI_SCALE_RANGE;
-
-impl Default for EguiManager {
- fn default() -> Self {
- let ctx = egui::Context::default();
- // The Cartopolis look — palette, spacing, type scale, brand font family.
- // Installed here, at construction, rather than from a startup system:
- // `set_fonts` only takes effect from the next `begin_pass`, so doing it
- // before the first one is what makes the brand family safe to paint with
- // on frame one (the boot splash's wordmark).
- crate::systems::theme::install(&ctx);
- // egui defaults *two* `DebugOptions` to `cfg!(debug_assertions)`, so every
- // debug build paints stray overlays over the real UI:
- // - `show_unaligned` draws orange edges on widgets off the physical-pixel
- // grid (common under fractional display scaling), and
- // - `warn_if_rect_changes_id` strokes a red box around any widget that
- // keeps its rect but changes `Id` between passes — which our animated
- // panels (chat / bookmarks slide-in, conditionally-shown widgets that
- // shift their neighbours' auto-ids) trip constantly, so it reads as red
- // boxes all over the chat panel and bottom bar.
- // Force the whole debug overlay off so none of it leaks in, in any build.
- //
- // `Style::debug` is itself `#[cfg(debug_assertions)]` in egui, so this must
- // be gated the same way: with assertions off the field does not exist and
- // naming it is a compile error, not a no-op. That is why this only surfaced
- // on the first optimised build — and it would have broken a native
- // `--release` just as surely. There is nothing to turn off in that case;
- // egui compiles the overlay out entirely.
- #[cfg(debug_assertions)]
- ctx.all_styles_mut(|style| {
- style.debug.show_unaligned = false;
- style.debug.warn_if_rect_changes_id = false;
- style.debug.debug_on_hover = false;
- style.debug.show_interactive_widgets = false;
- style.debug.show_expand_width = false;
- style.debug.show_expand_height = false;
- });
- Self {
- ctx,
- root_ui: None,
- elapsed_time: 0.0,
- // The primary window's default resolution in `main.rs`; only ever
- // used for the frames before the first `begin_egui_frame`.
- metrics: UiMetrics::default(),
- map_rect: None,
- ui_animating: false,
- overlay_owns_pointer: false,
- }
- }
-}
-
-/// Whether the last tessellated geometry can stand in for this frame.
-///
-/// `repaint_delay` is egui's own answer to "how long may I go without being
-/// drawn": `Duration::MAX` for a UI waiting on input, and something finite when a
-/// widget has called `request_repaint_after`. Measuring it against the time since
-/// the last write is the whole of the test — a finite delay does not mean "draw
-/// now", it means "draw within", and an animating widget re-requests on every pass
-/// it draws.
-fn geometry_still_current(repaint_delay: std::time::Duration, since_write: f32) -> bool {
- repaint_delay.as_secs_f32() > since_write
-}
-
-impl EguiManager {
- /// Borrow the egui context *shared*. Only valid between `begin_egui_frame`
- /// and `end_egui_frame` (i.e. during the Update schedule).
- ///
- /// `egui::Context` is `Sync` (an `Arc<RwLock<…>>` inside) and every
- /// floating-`Area` call takes `&Context`, so a system that draws only its
- /// own `Area`s — no shared root `Ui`, no event injection — can take the
- /// manager as a plain `Res`. That matters for scheduling, not hygiene: the
- /// mutable claim on this manager is one of the two cliques that serialise
- /// the whole Update schedule (`docs/notes/render-performance-survey.md`),
- /// and every demotion to `Res` lets that system overlap the others. Area
- /// z-order is unaffected — each `Area` owns its own layer, ordered by
- /// egui's memory, not by which system happened to register it first this
- /// frame.
- pub fn ctx(&self) -> &egui::Context {
- &self.ctx
- }
-
- /// Whether the UI moved on its own last pass (a `motion` in progress), as
- /// opposed to merely wanting a look within a quarter second. The idle
- /// throttle counts it as busy.
- #[must_use]
- pub fn ui_animating(&self) -> bool {
- self.ui_animating
- }
-
- /// Record the surface this frame is laid out against, given the *display's*
- /// scale factor — [`UiMetrics::set_surface`], which folds in the UI scale
- /// and sanitises a zero or NaN display scale.
- #[cfg(test)]
- fn set_surface(&mut self, physical: UVec2, display_scale: f32) {
- self.metrics.set_surface(physical, display_scale);
- }
-
- /// The UI magnification in force (`ui_input::resolve_ui_scale`). Also the
- /// factor between the window's logical points and egui's.
- pub fn ui_scale(&self) -> f32 {
- self.metrics.ui_scale()
- }
-
- /// The surface and scale egui lays out against this frame — the same
- /// value the `UiMetrics` resource holds.
- #[cfg(test)]
- #[must_use]
- pub fn metrics(&self) -> UiMetrics {
- self.metrics
- }
-
- /// Convert a position in the window's logical points — which is what
- /// `Window::cursor_position`, `TouchInput::position` and
- /// `Camera::world_to_viewport` all speak — into egui points.
- ///
- /// The two spaces coincide only while [`Self::ui_scale`] is 1.0, so a
- /// world-anchored overlay that skips this is *correct on every desktop* and
- /// slides away from its subject on a phone, proportionally to how far it is
- /// from the top-left corner.
- pub fn window_to_ui(&self, p: Vec2) -> egui::Pos2 {
- let p = self.metrics.window_to_ui(p);
- egui::pos2(p.x, p.y)
- }
-
- /// Does this frame's `just_pressed(Left)` belong to egui rather than to the
- /// world under it? The gate for a *world click* — `picking::prim_picking` and
- /// `building_select::pick_building`, which must agree (`picking::PrimClick`).
- ///
- /// A mouse click asks `egui_wants_pointer_input()`, which is right for a
- /// mouse: the press reaches `ButtonInput` on the same frame egui sees it, so
- /// the button is still down and the answer is "did a widget take it".
- ///
- /// **A finger's click cannot ask that**, because it arrives a frame late
- /// (`touch::emulate_mouse`'s ordering note) and egui reads the `TouchInput`
- /// stream directly. When the finger lifted in that one frame — a brisk tap on
- /// a handset, and the second tap of a double tap is the brisk one — egui has
- /// already seen the release by the time the click lands, and with no button
- /// down `egui_wants_pointer_input()` falls through to `is_pointer_over_egui()`,
- /// which is unconditionally true here (the root `Ui` is ours, so egui never
- /// learns its `root_ui_available_rect`). The tap was swallowed over the bare
- /// map, and the building card never opened. So a finger's click is decided by
- /// *where it landed* instead: on a floating area or modal, or on the root
- /// layer outside the map (a panel), it is egui's — [`press_over_ui`].
- ///
- /// The world's clicks ask `UiInput::owns_click`, which carries this
- /// verdict over; this one stays for its tests, which pin the rule.
- #[cfg_attr(not(test), allow(dead_code))]
- pub fn owns_click(&self, touch_click: bool, cursor: Option<Vec2>) -> bool {
- if self.overlay_owns_pointer {
- return true;
- }
- match (touch_click, cursor) {
- (true, Some(at)) => press_over_ui(&self.ctx, self.map_rect, self.window_to_ui(at)),
- _ => self.ctx.egui_wants_pointer_input(),
- }
- }
-
- /// Declare (each frame) that the pointer is over a screen drawn beside
- /// egui — see the `overlay_owns_pointer` field. Only the library's
- /// screens (`ui-probe`) have one to declare.
- #[cfg_attr(not(feature = "ui-probe"), allow(dead_code))]
- pub fn set_overlay_owns_pointer(&mut self, owns: bool) {
- self.overlay_owns_pointer = owns;
- }
-
- /// egui's answers to `UiInput`'s questions this frame, for a press at the
- /// window `cursor` — see [`publish_ui_input`].
- pub fn verdict(&self, cursor: Option<Vec2>) -> EguiVerdict {
- verdict_of(&self.ctx, self.map_rect, &self.metrics, cursor)
- }
-}
-
-/// [`EguiManager::verdict`] over its parts, so a test can drive a bare
-/// `Context`: `press_over_ui` for [`EguiManager::owns_click`]'s finger, a
-/// drag that started on the bare map (a sheet over the map steps aside for
-/// it), and whether a text field has the keyboard.
-pub(crate) fn verdict_of(
- ctx: &egui::Context,
- map_rect: Option<egui::Rect>,
- metrics: &UiMetrics,
- cursor: Option<Vec2>,
-) -> EguiVerdict {
- let map_dragged = ctx
- .input(|i| {
- i.pointer
- .is_decidedly_dragging()
- .then(|| i.pointer.press_origin())
- .flatten()
- })
- .is_some_and(|at| !press_over_ui(ctx, map_rect, at));
- let press_over_ui = cursor.is_some_and(|at| {
- let p = metrics.window_to_ui(at);
- press_over_ui(ctx, map_rect, egui::pos2(p.x, p.y))
- });
- // Back into window points, by the inverse of `window_to_ui`.
- let k = metrics.ui_scale();
- let map_rect = map_rect.map(|r| Rect::new(r.min.x * k, r.min.y * k, r.max.x * k, r.max.y * k));
- EguiVerdict {
- wants_pointer: ctx.egui_wants_pointer_input(),
- text_focused: ctx.text_edit_focused(),
- map_dragged,
- cursor,
- press_over_ui,
- map_rect,
- }
-}
-
-/// Write egui's verdict into [`UiInput`] (`PreUpdate`, right after
-/// [`begin_egui_frame`] and after `touch::recognize_touch_gestures` has put
-/// the window cursor on the finger), and hand the library's verdict — set by
-/// `lib_host::bridge_input` last frame — to the egui systems that still ask
-/// the manager.
-///
-/// Taken at the start of the pass, so a system in `Update` reads what the
-/// frame began with; egui decides its pointer interaction in `begin_pass`
-/// too, so only a focus or an `Area` that changes mid-pass is seen a frame
-/// later than when it was asked of egui directly.
-pub fn publish_ui_input(mut egui: EguiMut, mut input: ResMut<UiInput>, windows: Query<&Window>) {
- egui.set_overlay_owns_pointer(input.overlay_owns_pointer());
- let cursor = windows.iter().next().and_then(|w| w.cursor_position());
- let verdict = egui.verdict(cursor);
- if input.egui_verdict() != verdict {
- input.set_egui(verdict);
- }
-}
-
-/// Copy `ui_animating` into [`UiInput`] once [`end_egui_frame`] has decided
-/// it, for `frame_pacing::present_rate` in `Last`.
-pub fn publish_ui_animating(egui: EguiRef, mut input: ResMut<UiInput>) {
- if input.ui_animating() != egui.ui_animating() {
- input.set_ui_animating(egui.ui_animating());
- }
-}
-
-/// Re-apply the palette in force to egui's style when the theme flips
-/// (`ui_theme::follow_the_light` sets it, `theme::set_light`), and on the
-/// first frame. Only what egui still draws needs it; it goes with egui.
-pub fn follow_theme_visuals(egui: EguiRef, mut was: Local<Option<bool>>) {
- let light = crate::systems::theme::is_light();
- if *was == Some(light) {
- return;
- }
- *was = Some(light);
- crate::systems::theme::apply_visuals(egui.ctx());
-}
-
-// ─── Extracted render data ────────────────────────────────────────────────────
-
-/// egui's [`egui::TexturesDelta`], owned the way this bridge owns it.
-///
-/// egui 0.36 debug-asserts that a delta is never dropped unapplied, which assumes
-/// one painter consuming each delta exactly once. Here the delta is *cloned* into
-/// the render world on every extract and the main-world copy is replaced once
-/// [`APPLIED_GENERATION`] says it landed, so dropping a copy is the normal end of
-/// its life — the generation, not the drop, is what tracks whether it was applied.
-#[derive(Clone, Default)]
-pub struct TextureUpdates(pub egui::TexturesDelta);
-
-impl Drop for TextureUpdates {
- fn drop(&mut self) {
- self.0.clear();
- }
-}
-
-impl std::ops::Deref for TextureUpdates {
- type Target = egui::TexturesDelta;
- fn deref(&self) -> &Self::Target {
- &self.0
- }
-}
-
-impl std::ops::DerefMut for TextureUpdates {
- fn deref_mut(&mut self) -> &mut Self::Target {
- &mut self.0
- }
-}
-
-/// Tessellated egui output, extracted to the render world when it changes.
-///
-/// Deliberately *not* rewritten every frame — see [`end_egui_frame`]. `ExtractResource`'s
-/// derive is a plain `clone()`, and `extract_resource` only skips it when the main-world
-/// resource is unchanged, so an unconditional write meant deep-copying the whole UI
-/// vertex/index geometry into the render world 60×/s for a pixel-identical picture.
-#[derive(Resource, Clone, Default, ExtractResource)]
-#[extract_app(RenderApp)]
-pub struct EguiRenderOutput {
- pub clipped_primitives: Vec<egui::ClippedPrimitive>,
- pub textures_delta: TextureUpdates,
- /// Physical window size in pixels (for `ScreenDescriptor`).
- pub size_in_pixels: [u32; 2],
- pub pixels_per_point: f32,
- /// Bumped on every real write. [`egui_pass`] compares it against the generation
- /// it last uploaded so it can skip `update_buffers` / texture uploads for
- /// geometry already resident on the GPU — and, critically, so a `textures_delta`
- /// that lingers in a re-used output isn't re-applied every frame.
- pub generation: u64,
- /// Set by a system that mutated this resource in place (currently
- /// [`suppress_egui_for_screenshot`], which clears the geometry for one frame).
- /// Forces the next [`end_egui_frame`] to write even if egui reports no repaint,
- /// otherwise the suppressed state would stick and the UI would never come back.
- pub force_next_write: bool,
-}
-
-/// When a screenshot is being captured, drop this frame's tessellated egui geometry so
-/// the shot is free of UI chrome. Runs in PostUpdate **after** `end_egui_frame` (which
-/// writes the output) and before render-world extraction. Only `clipped_primitives` is
-/// cleared — `textures_delta` is left intact so egui's font/texture uploads aren't lost.
-/// The screenshot state is optional: a test app without the client has none.
-pub fn suppress_egui_for_screenshot(
- shot: Option<Res<crate::resources::ScreenshotState>>,
- mut output: ResMut<EguiRenderOutput>,
-) {
- if shot.is_some_and(|s| s.hide_ui) {
- output.clipped_primitives.clear();
- // This mutates the output in place, so `end_egui_frame` must rewrite it next
- // frame even if egui reports nothing changed — otherwise the cleared geometry
- // is what stays resident and the UI never comes back after a screenshot.
- output.force_next_write = true;
- output.generation = output.generation.wrapping_add(1);
- }
-}
-
-// ─── Render-world resource ─────────────────────────────────────────────────
-
-/// Lazily-initialized egui-wgpu renderer in the render world.
-/// Stores the renderer alongside the sample count it was compiled for so we
-/// can detect and handle MSAA changes (e.g. camera settings changed), the
-/// [`EguiRenderOutput::generation`] whose geometry/textures are currently resident
-/// on the GPU (`None` until the first upload), and the textures egui has finished
-/// with but which cannot be destroyed until the frame that drew them has been
-/// **submitted** — see [`egui_pass`].
-// On wasm `egui_wgpu::Renderer` holds WebGL handles that are `!Send + !Sync` (the
-// browser GPU is main-thread-only), so it cannot be a normal Bevy `Resource` there
-// — it is stored as a **non-send** resource instead (ADR-033). On native it stays a
-// regular `Resource`. The `egui_pass` accessor and its registration mirror this.
-#[cfg_attr(not(target_arch = "wasm32"), derive(Resource))]
-#[derive(Default)]
-pub struct EguiWgpuRenderer(
- pub Mutex<
- Option<(
- egui_wgpu::Renderer,
- TextureFormat,
- u32,
- Option<u64>,
- Vec<egui::TextureId>,
- )>,
- >,
-);
-
-// ─── Plugin ──────────────────────────────────────────────────────────────────
-
-pub struct EguiPlugin;
-
-impl Plugin for EguiPlugin {
- fn build(&self, app: &mut App) {
- #[cfg(not(target_arch = "wasm32"))]
- app.init_resource::<EguiManager>();
- #[cfg(target_arch = "wasm32")]
- app.init_non_send::<EguiManager>();
- app.init_resource::<EguiRenderOutput>()
- .add_plugins(ExtractResourcePlugin::<EguiRenderOutput>::default())
- // MUST run after Bevy has written this frame's input: begin_egui_frame
- // reads `ButtonInput`, cursor position and the keyboard/mouse events to
- // build egui's `RawInput`. Unordered, it can run *before* `InputSystem`
- // and collect stale/partial input, which corrupts click and keyboard-
- // focus handling (fields lose focus on keypress).
- .add_systems(PreUpdate, begin_egui_frame.after(bevy::input::InputSystems))
- .add_systems(PostUpdate, end_egui_frame);
- // egui's half of `UiInput`, which a system that only asks "who owns the
- // input" reads instead of the manager. After the touch recogniser,
- // which moves the window cursor onto the finger a world click reads.
- if !app.is_plugin_added::<UiInputPlugin>() {
- app.add_plugins(UiInputPlugin);
- }
- app.add_systems(
- PreUpdate,
- publish_ui_input
- .after(begin_egui_frame)
- .after(crate::systems::touch::recognize_touch_gestures),
- )
- .add_systems(PostUpdate, publish_ui_animating.after(end_egui_frame))
- // Drop egui geometry for the screenshot frame, after end_egui_frame has
- // written it.
- .add_systems(
- PostUpdate,
- suppress_egui_for_screenshot.after(end_egui_frame),
- );
-
- let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
- return;
- };
-
- #[cfg(not(target_arch = "wasm32"))]
- {
- use bevy::render::GpuResourceAppExt as _;
- render_app.init_resource::<EguiWgpuRenderer>();
- // …and again on **every** device, which is what makes the renderer
- // survive `handle_render_error`'s `DeviceLost` recovery. `RenderStartup`
- // re-runs each time a `RenderDevice` is acquired, and this drops the
- // cached `egui_wgpu::Renderer` with it.
- //
- // Without this the recovery is worse than the loss. The cached renderer
- // holds pipelines, bind groups and textures belonging to the dead
- // device, and nothing in `egui_pass` would notice: `needs_recreate`
- // compares the *format* and the sample count, both unchanged by a
- // device loss, and `uploaded_gen` still matches the current output, so
- // not even a re-upload is attempted. egui would then draw dead handles
- // at the new device and raise `Validation` — which `handle_render_error`
- // halts on, by design, because validation errors recur. So a transient,
- // recoverable `DeviceLost` would be converted into the terminal halt the
- // recovery exists to avoid. The `init_resource` above stays because the
- // resource must exist before the first `RenderStartup` runs.
- render_app.init_gpu_resource::<EguiWgpuRenderer>();
- }
- // The wasm arm is a non-send resource (WebGL handles are main-thread-only)
- // and cannot go through `init_gpu_resource`, which requires `Resource`. It
- // is also the one target where bevy's device-loss recovery does not apply:
- // a lost WebGL context is delivered to the page, not to wgpu's callback.
- #[cfg(target_arch = "wasm32")]
- render_app.world_mut().init_non_send::<EguiWgpuRenderer>();
- render_app.add_systems(
- Core3d,
- // Draw egui AFTER upscaling, onto the final presented output — a stable,
- // single-sampled, sRGB swapchain texture. Drawing before upscaling (on the
- // ping-ponged HDR main texture) made the UI flicker and read too bright.
- egui_pass.after(upscaling),
- );
- }
-}
-
-// ─── Systems ──────────────────────────────────────────────────────────────────
-
-/// State the pointer bridge threads through the window-event stream.
-#[derive(Default)]
-pub(crate) struct PointerBridge {
- /// The running pointer position, so a button event carries the position it
- /// had *at its point in the stream*.
- last: Option<egui::Pos2>,
- /// Which finger is currently standing in for egui's pointer. egui has
- /// exactly one pointer, so the first finger down owns it until it lifts:
- /// otherwise the second finger of a pinch would drag the UI out from under
- /// the first, and lifting either would report the pointer gone.
- touch: Option<u64>,
-}
-
-impl PointerBridge {
- /// Seed the position for a button that arrives before any motion has been
- /// seen (cursor already inside the window at startup).
- pub(crate) fn seed(&mut self, pos: Option<egui::Pos2>) {
- if self.last.is_none() {
- self.last = pos;
- }
- }
-}
-
-/// Map one Bevy window event to its egui pointer events, threading the running
-/// cursor position so button events carry the position *at their point in the
-/// stream*. Pure, so the ordering contract is unit-testable.
-///
-/// Order and per-event positions are load-bearing: a fast click-then-flick
-/// batches `[press, release, move…]` into a single frame, and the old bridge —
-/// moves first, then `ButtonInput` press/release stamped with the end-of-frame
-/// `cursor_position()` — teleported the click to wherever the flick ended. egui
-/// then either hit-tested the wrong widget or, with press and release split
-/// across frames, cancelled the click as a drag (press→release further than its
-/// ~6 pt click threshold). Panel checkboxes needed several tries because only a
-/// motionless click survived; anything floating on an `Area` (menu bar, HUD)
-/// felt fine since those get clicked deliberately.
-///
-/// **Touch is not a variant of the mouse here, it is the only input there is.**
-/// winit's web backend sends a touch pointer as `WindowEvent::Touch` *only* —
-/// never `CursorMoved`, never `MouseInput` — so without this arm every panel,
-/// button and text field in the client is dead on a phone. One `Event::Touch`
-/// goes out per finger (that is what egui's own multi-touch readers want), and
-/// the finger holding the pointer role additionally synthesises the pointer
-/// sequence egui needs for ordinary widgets: move-then-press on the way down,
-/// press-release *then `PointerGone`* on the way up. `PointerGone` is not
-/// optional — a finger leaves no cursor behind it, and without it egui goes on
-/// hovering whatever was last touched, which lights up buttons under a finger
-/// that left and keeps `egui_wants_pointer_input()` true over the map.
-///
-/// Appends rather than returning one event, because a single touch phase is
-/// worth up to three egui events. `systems::touch` is the matching bridge for
-/// the *world* (camera gestures and the emulated mouse) and does not go through
-/// here — it reads the settled `Touches` set instead.
-///
-/// `ui_scale` converts the incoming positions — which are in the *window's*
-/// logical points — into egui's (see [`EguiManager::window_to_ui`]). It is
-/// applied here, at the one place events enter, so that `state.last` and every
-/// event built from it are already in egui's space and nothing downstream has to
-/// remember which of the two it is holding.
-pub(crate) fn pointer_events(
- ev: &bevy::window::WindowEvent,
- ui_scale: f32,
- state: &mut PointerBridge,
- out: &mut Vec<egui::Event>,
-) {
- use bevy::window::WindowEvent as We;
- let to_ui = |p: Vec2| egui::pos2(p.x / ui_scale, p.y / ui_scale);
- match ev {
- We::CursorMoved(e) => {
- let pos = to_ui(e.position);
- state.last = Some(pos);
- out.push(egui::Event::PointerMoved(pos));
- }
- We::MouseWheel(e) => {
- let (unit, delta) = match e.unit {
- MouseScrollUnit::Line => (egui::MouseWheelUnit::Line, egui::Vec2::new(e.x, e.y)),
- MouseScrollUnit::Pixel => (egui::MouseWheelUnit::Point, egui::Vec2::new(e.x, e.y)),
- };
- out.push(egui::Event::MouseWheel {
- unit,
- delta,
- // We don't distinguish trackpad scroll phases; "unknown" maps to Move.
- phase: egui::TouchPhase::Move,
- modifiers: egui::Modifiers::default(),
- });
- }
- We::MouseButtonInput(e) => {
- let button = match e.button {
- MouseButton::Left => egui::PointerButton::Primary,
- MouseButton::Right => egui::PointerButton::Secondary,
- MouseButton::Middle => egui::PointerButton::Middle,
- _ => return,
- };
- let Some(pos) = state.last else { return };
- out.push(egui::Event::PointerButton {
- pos,
- button,
- pressed: e.state == ButtonState::Pressed,
- modifiers: egui::Modifiers::default(),
- });
- }
- We::TouchInput(e) => {
- use bevy::input::touch::TouchPhase as BevyPhase;
- let pos = to_ui(e.position);
- out.push(egui::Event::Touch {
- // One touchscreen; egui only uses this to keep devices apart.
- device_id: egui::TouchDeviceId(0),
- id: egui::TouchId(e.id),
- phase: match e.phase {
- BevyPhase::Started => egui::TouchPhase::Start,
- BevyPhase::Moved => egui::TouchPhase::Move,
- BevyPhase::Ended => egui::TouchPhase::End,
- BevyPhase::Canceled => egui::TouchPhase::Cancel,
- },
- pos,
- force: None,
- });
-
- // Only the pointer-holding finger drives the widget-level events.
- if state.touch.is_some_and(|held| held != e.id) {
- return;
- }
- match e.phase {
- BevyPhase::Started => {
- state.touch = Some(e.id);
- state.last = Some(pos);
- // Move first: egui hit-tests the press at the pointer's
- // position, and a finger's press is the first time that
- // position exists.
- out.push(egui::Event::PointerMoved(pos));
- out.push(egui::Event::PointerButton {
- pos,
- button: egui::PointerButton::Primary,
- pressed: true,
- modifiers: egui::Modifiers::default(),
- });
- }
- BevyPhase::Moved => {
- state.last = Some(pos);
- out.push(egui::Event::PointerMoved(pos));
- }
- BevyPhase::Ended | BevyPhase::Canceled => {
- state.touch = None;
- out.push(egui::Event::PointerButton {
- pos,
- button: egui::PointerButton::Primary,
- pressed: false,
- modifiers: egui::Modifiers::default(),
- });
- out.push(egui::Event::PointerGone);
- }
- }
- }
- _ => {}
- }
-}
-
-/// Release a finger the bridge still thinks is down but Bevy has already
-/// forgotten, and say so to egui.
-///
-/// **One dropped touch-up is otherwise permanent input death.** `state.touch` is
-/// set on `Started` and cleared in exactly one place — the `Ended | Canceled` arm
-/// of [`pointer_events`] — so if that event never arrives, the id sticks. Android
-/// touch ids only ever increase, so no later finger can match it, and
-/// `pointer_events` returns early for every one of them: egui then receives
-/// `Event::Touch` and nothing else, forever. No `PointerMoved`, no
-/// `PointerButton`, no panel, no button, no way to close anything. Worse, the last
-/// pointer event egui saw said `pressed: true`, so `is_using_pointer()` stays true
-/// and the *world* consumers (`picking`, `camera_controls`) refuse every input as
-/// well, on the grounds that egui has the pointer. The app renders at full rate
-/// and responds to nothing, which is indistinguishable from a hang.
-///
-/// It is not hypothetical on this platform. The Android camera intent
-/// (`platform::photo`) is the one thing that backgrounds the app mid-session, and
-/// android-activity detaches the NativeActivity input queue on pause and discards
-/// what is unconsumed — a finger still on the glass when the camera opens is
-/// exactly the event that goes missing. `quiesce_while_backgrounded` calls
-/// `Touches::release_all` on resume for that reason, and this is what turns that
-/// into the release egui needs to hear.
-///
-/// The events are the same three the ordinary lift emits, in the same order, so
-/// nothing downstream can tell a healed release from a real one — which is the
-/// point: egui must not learn a new state, it must be told the one it missed.
-/// `still_down` answers whether Bevy still has that finger pressed. Taken as a
-/// predicate rather than as `&Touches` so this stays a pure function the tests
-/// can drive — `Touches` has no public way to seed a pressed finger, and the one
-/// behaviour worth pinning here is precisely what happens when it says "no".
-fn heal_lost_touch(
- state: &mut PointerBridge,
- still_down: impl Fn(u64) -> bool,
- out: &mut Vec<egui::Event>,
-) {
- let Some(held) = state.touch else { return };
- if still_down(held) {
- return;
- }
- state.touch = None;
- let Some(pos) = state.last else { return };
- tracing::debug!(held, "released a touch the bridge never saw lifted");
- out.push(egui::Event::PointerButton {
- pos,
- button: egui::PointerButton::Primary,
- pressed: false,
- modifiers: egui::Modifiers::default(),
- });
- out.push(egui::Event::PointerGone);
-}
-
-/// Split off the pointer events for one egui pass: everything up to and
-/// including the FIRST button event; the remainder stays in `pending` for the
-/// next pass. egui hit-tests once per pass, at the batch's **final** pointer
-/// position — so a pass whose batch continues past a press/release
-/// re-attributes that button to wherever the pointer ended up afterwards (the
-/// flick away from a fast click), and the click is lost. Deferring the tail
-/// delays pointer motion by one frame only on frames containing a button, and
-/// leaves drags intact: a `[press]` / `[moves…, release]` split keeps every
-/// drag delta with its release.
-pub(crate) fn take_pass_events(pending: &mut Vec<egui::Event>) -> Vec<egui::Event> {
- let split = pending
- .iter()
- .position(|e| matches!(e, egui::Event::PointerButton { .. }))
- .map(|i| i + 1)
- .unwrap_or(pending.len());
- let tail = pending.split_off(split);
- std::mem::replace(pending, tail)
-}
-
-/// Collect Bevy input and begin an egui frame (runs in PreUpdate).
-pub fn begin_egui_frame(
- mut egui_manager: EguiMut,
- windows: Query<&Window>,
- headless: Option<Res<HeadlessSurface>>,
- keys: Res<ButtonInput<KeyCode>>,
- mut window_events: MessageReader<bevy::window::WindowEvent>,
- mut keyboard_input: MessageReader<KeyboardInput>,
- time: Res<Time>,
- touches: Res<bevy::input::touch::Touches>,
- mut pointer_bridge: Local<PointerBridge>,
- mut pointer_carry: Local<Vec<egui::Event>>,
-) {
- // A frame with no surface at all still begins (and ends) an egui pass, laid
- // out against the last one we saw.
- //
- // The window entity is despawned by Bevy's `close_when_requested` (in `Last`)
- // while `Update` keeps running, so the shutdown sequence can put a whole frame
- // through the schedule with zero `Window`s in the world. Returning early here
- // left `root_ui` at `None` for that frame — and every panel system still ran,
- // each one hitting `ui_mut()`'s `expect` on a task-pool thread. That is the
- // macOS "ui_mut() called outside an egui frame" crash (#2): a stack with no
- // system name, on a compute-pool thread, at shutdown.
- //
- // The cost is one laid-out, tessellated frame that is never presented; the
- // gain is that `ui_mut()`'s invariant holds by construction instead of by the
- // convention that a window exists.
- egui_manager.metrics.observe(&windows, headless.as_deref());
- let (physical, scale) = (
- egui_manager.metrics.physical(),
- egui_manager.metrics.pixels_per_point(),
- );
-
- egui_manager.elapsed_time += time.delta_secs_f64();
-
- let logical_w = physical.x as f32 / scale;
- let logical_h = physical.y as f32 / scale;
-
- let mut events: Vec<egui::Event> = Vec::new();
-
- // Pointer input, from the ORDERED window-event stream (see [`pointer_event`]
- // for why the per-frame `ButtonInput`/`cursor_position()` snapshot lost
- // clicks). `last_pointer` persists across frames so a button event with no
- // motion this frame keeps the position of the last motion ever; the fallback
- // covers a click before any `CursorMoved` has been seen (cursor already
- // inside the window at startup). Headless runs see no window events at all.
- let ui_scale = egui_manager.ui_scale();
- pointer_bridge.seed(
- windows
- .iter()
- .next()
- .and_then(|w| w.cursor_position())
- .map(|p| egui::pos2(p.x / ui_scale, p.y / ui_scale)),
- );
- let mut pending = std::mem::take(&mut *pointer_carry);
- // A finger we still believe is down, that Bevy no longer has: heal before
- // reading this frame's events, so the recovery is ordered ahead of whatever
- // the new finger is doing.
- heal_lost_touch(
- &mut pointer_bridge,
- |id| touches.get_pressed(id).is_some(),
- &mut pending,
- );
- for ev in window_events.read() {
- pointer_events(ev, ui_scale, &mut pointer_bridge, &mut pending);
- }
- events.extend(take_pass_events(&mut pending));
- *pointer_carry = pending;
-
- // Keyboard: text input for text fields + special keys. Ctrl+C/V/X become
- // explicit clipboard events bridged to the system clipboard (this custom
- // integration has no winit clipboard plumbing of its own).
- //
- // Forwarded ONLY while text is actually being edited — the exact mirror of
- // `EguiManager::ui_owns_keyboard`, which yields the game's keys to the UI
- // under the same condition, so exactly one side ever acts on a key. egui
- // keeps *focus* on the last-clicked widget (a checkbox, a panel's collapse
- // button), and Space/Enter activate the focused widget: a game key as ordinary
- // as Space re-triggered whatever was clicked last, collapsing panels from
- // across the map. The reader is
- // drained regardless, or the keys held before clicking into a field would
- // arrive as a stale burst the moment it gains focus.
- let forward_keys = egui_manager.ctx.text_edit_focused();
- let ctrl = keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight);
- let shift = keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight);
- let alt = keys.pressed(KeyCode::AltLeft) || keys.pressed(KeyCode::AltRight);
- // macOS puts the accelerator on Super, not Control. Without this, `Cmd+C` in
- // a text field did nothing while `Ctrl+C` did — the wrong key on that
- // platform — and a held Cmd did not suppress avatar movement the way a held
- // Ctrl does.
- let cmd = keys.pressed(KeyCode::SuperLeft) || keys.pressed(KeyCode::SuperRight);
- let mac = cfg!(target_os = "macos");
- let accel = if mac { cmd } else { ctrl };
- let modifiers = egui::Modifiers {
- ctrl,
- shift,
- alt,
- mac_cmd: mac && cmd,
- command: accel,
- };
- for ev in keyboard_input.read() {
- // **Escape and Tab are dismissal and navigation, not activation.** The
- // gate above is right for keys that *fire* the focused widget — that is
- // what stopped Space collapsing a panel from across the map — and it was
- // applied to every key, which made every `Key::Escape` handler in the
- // client unreachable code and stranded Tab focus on the first widget it
- // reached. These two go through whether or not a field has focus;
- // everything else still waits its turn. See `systems::dismiss` for what
- // Escape then does with it.
- let always = matches!(ev.key_code, KeyCode::Escape | KeyCode::Tab);
- if !forward_keys && !always {
- continue;
- }
- if ev.state == ButtonState::Pressed && accel {
- match ev.key_code {
- KeyCode::KeyC => {
- events.push(egui::Event::Copy);
- continue;
- }
- KeyCode::KeyX => {
- events.push(egui::Event::Cut);
- continue;
- }
- KeyCode::KeyV => {
- if let Some(text) = crate::utils::clipboard::get_text() {
- events.push(egui::Event::Paste(text));
- }
- continue;
- }
- _ => {}
- }
- }
- if ev.state == ButtonState::Pressed && !accel {
- if let Some(ref text) = ev.text {
- let s = text.as_str();
- if !s.is_empty() && !s.chars().any(|c| c.is_control()) {
- events.push(egui::Event::Text(s.to_string()));
- }
- }
- }
- if let Some(egui_key) = bevy_key_to_egui(ev.key_code) {
- events.push(egui::Event::Key {
- key: egui_key,
- physical_key: None,
- pressed: ev.state == ButtonState::Pressed,
- repeat: ev.repeat,
- modifiers,
- });
- }
- }
-
- let screen_rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(logical_w, logical_h));
-
- let mut viewport_info = egui::ViewportInfo::default();
- viewport_info.native_pixels_per_point = Some(scale);
- viewport_info.inner_rect = Some(screen_rect);
-
- let mut raw_input = egui::RawInput {
- screen_rect: Some(screen_rect),
- time: Some(egui_manager.elapsed_time),
- // The frame egui should plan for. Left at its default (1/60 s) egui
- // advanced its animations and the kinetic scroll by a sixtieth on a
- // phone frame of 25–40 ms, so a fling ran slow exactly where it is
- // most used. The last frame's length is the best guess for this one.
- predicted_dt: time.delta_secs().clamp(1.0 / 240.0, 0.1),
- events,
- focused: true,
- ..Default::default()
- };
- raw_input
- .viewports
- .insert(egui::ViewportId::ROOT, viewport_info);
-
- egui_manager.ctx.begin_pass(raw_input);
-
- // egui 0.35 shows panels inside a root `Ui` (not the `Context`). Build a
- // full-viewport background `Ui` that every UI system shares this frame, so
- // panels cooperate on layout exactly as the old ctx-based panels did.
- let root_ui = egui::Ui::new(
- egui_manager.ctx.clone(),
- egui::Id::new((egui_manager.ctx.viewport_id(), "__cartopolis_root_ui")),
- egui::UiBuilder::new()
- .layer_id(egui::LayerId::background())
- .max_rect(egui_manager.ctx.viewport_rect()),
- );
- egui_manager.root_ui = Some(root_ui);
-}
-
-fn bevy_key_to_egui(key: KeyCode) -> Option<egui::Key> {
- Some(match key {
- KeyCode::Escape => egui::Key::Escape,
- KeyCode::Tab => egui::Key::Tab,
- KeyCode::Backspace => egui::Key::Backspace,
- KeyCode::Delete => egui::Key::Delete,
- KeyCode::Enter => egui::Key::Enter,
- KeyCode::Space => egui::Key::Space,
- KeyCode::ArrowUp => egui::Key::ArrowUp,
- KeyCode::ArrowDown => egui::Key::ArrowDown,
- KeyCode::ArrowLeft => egui::Key::ArrowLeft,
- KeyCode::ArrowRight => egui::Key::ArrowRight,
- KeyCode::Home => egui::Key::Home,
- KeyCode::End => egui::Key::End,
- KeyCode::PageUp => egui::Key::PageUp,
- KeyCode::PageDown => egui::Key::PageDown,
- // The three letters egui's text editor binds to an accelerator. They
- // reach it only as a `Key` event — the `Event::Text` path above is
- // skipped while the accelerator is held — so without them `Ctrl+A`,
- // `Ctrl+Z` and `Ctrl+Y` were dead in every text field on the desktop,
- // while the on-screen keyboard, which injects `Key::A + COMMAND`
- // directly, could select-all on a phone. Nothing else in the client
- // wants a bare letter from egui, which is why the map stops here.
- KeyCode::KeyA => egui::Key::A,
- KeyCode::KeyZ => egui::Key::Z,
- KeyCode::KeyY => egui::Key::Y,
- _ => return None,
- })
-}
-
-/// Tessellate the egui frame and store the output for the render world (runs in PostUpdate).
-/// Did a press at `at` (egui points) land on the UI?
-///
-/// A floating area, window or modal is found by `layer_id_at` and is the UI's
-/// outright. The root layer covers the whole screen — egui registers it so panels
-/// can catch clicks — so there the answer is whether the press is outside
-/// `map_rect`, i.e. on a panel. Pure over the context's last pass, so it answers
-/// the same whether or not the finger is still down.
-fn press_over_ui(ctx: &egui::Context, map_rect: Option<egui::Rect>, at: egui::Pos2) -> bool {
- match ctx.layer_id_at(at) {
- None => false,
- Some(layer) if layer == egui::LayerId::background() => {
- map_rect.is_some_and(|map| !map.contains(at))
- }
- Some(_) => true,
- }
-}
-
-pub fn end_egui_frame(
- mut egui_manager: EguiMut,
- mut render_output: ResMut<EguiRenderOutput>,
- time: Res<Time<Real>>,
- // Wall-clock seconds since the last real write, for the repaint-delay test
- // below. A `Local` rather than a field on the output resource because writing
- // it there would go through `DerefMut` and mark the resource changed every
- // frame — defeating exactly the extract skip this function exists to set up.
- mut since_write: Local<f32>,
-) {
- *since_write += time.delta_secs();
- // Unconditional, and deliberately not gated on a surface existing: every
- // `begin_pass` needs its `end_pass`, or a windowless frame would leave the
- // pass open and the next `begin_pass` would nest inside it. `begin_egui_frame`
- // laid this frame out against `surface` — quote the same numbers back.
- let physical = egui_manager.metrics.physical();
-
- // Drop the shared root `Ui`, finalizing its panel layers, before ending the pass.
- // What the panels left of it is the map, for `owns_click`'s next frame.
- egui_manager.map_rect = egui_manager
- .root_ui
- .take()
- .map(|root| root.available_rect_before_wrap());
-
- let full_output = egui_manager.ctx.end_pass();
- // Bridge egui-side copies (Ctrl+C in a text field) to the system clipboard.
- for command in &full_output.platform_output.commands {
- if let egui::OutputCommand::CopyText(text) = command {
- crate::utils::clipboard::set_text(text);
- }
- }
- let pixels_per_point = full_output.pixels_per_point;
- let size_in_pixels = [physical.x, physical.y];
-
- // Skip the whole tessellate → clone → upload chain when egui itself says the UI
- // is unchanged. `repaint_delay == Duration::MAX` is egui's "nothing to redraw"
- // signal; `Context::tessellate` never reuses the previous frame's work, so
- // without this a completely static menu bar + panel rebuilt (and reallocated)
- // its full vertex/index geometry, deep-copied it into the render world, and
- // re-uploaded it to the GPU, every single frame.
- //
- // Leaving `render_output` untouched is what makes it free: the last-written
- // primitives are still there, `egui_pass` redraws them against the fresh colour
- // target, and Bevy's change detection skips the extract clone.
- //
- // NB: these reads must not go through `DerefMut` — touching `render_output`
- // mutably would mark it changed and defeat the very skip we're setting up.
- let force = render_output.force_next_write;
- // How long egui is willing to go before it needs drawing again. `MAX` is "not
- // until something happens" — a static panel — and any finite value comes from a
- // `request_repaint_after`, i.e. from a widget that told us it animates
- // (`EguiManager::animating`).
- //
- // Comparing it against the time since the last write, rather than testing it
- // for `MAX`, is what makes those two cases different in the right way. A bare
- // `== MAX` test would treat "repaint within 250 ms" as "repaint now", and since
- // an animating widget re-requests on every pass it draws, the skip would be off
- // permanently while anything on screen animated — trading a frozen clock for
- // full-rate tessellation, which is not the trade worth making.
- let repaint_delay = full_output
- .viewport_output
- .get(&egui::ViewportId::ROOT)
- .map_or(std::time::Duration::MAX, |v| v.repaint_delay);
- // Zero, and only zero: `animating()`'s quarter-second ask (a clock
- // readout) is not motion the frame rate has to keep up with.
- egui_manager.ui_animating = repaint_delay.is_zero();
- let quiet = geometry_still_current(repaint_delay, *since_write);
- if !force
- && quiet
- && full_output.textures_delta.is_empty()
- && render_output.size_in_pixels == size_in_pixels
- && render_output.pixels_per_point == pixels_per_point
- {
- // Drop the shapes without tessellating them.
- return;
- }
- *since_write = 0.0;
-
- let clipped_primitives = egui_manager
- .ctx
- .tessellate(full_output.shapes, pixels_per_point);
-
- // Carry unconsumed texture deltas forward instead of dropping them.
- //
- // A delta is *incremental*: egui allocates a texture once with a full image
- // (`pos: None`) and every later change is a patch (`pos: Some`) against it.
- // egui clears its own accumulator on `end_pass`, so whatever is written here is
- // the only copy. Overwriting the previous `textures_delta` therefore loses the
- // allocation, and egui-wgpu answers the first patch against a texture it never
- // allocated with `panic!("Tried to update a texture that has not been allocated
- // yet.")` — an abort, not a dropped frame.
- //
- // Desktop never reached it because `egui_pass` runs from frame zero, so nothing
- // is ever unconsumed. **Android has no view for its first few seconds**: winit
- // logs `Creating new window` about five seconds after `android_main`, and every
- // egui frame before that produces deltas with no view to apply them. The font
- // atlas is allocated in that window, so the app aborted a few seconds after
- // startup on every launch (reproduced on the emulator 2026-08-15).
- //
- // `append` is egui's own merge and keeps order, so the allocation stays ahead of
- // its patches. It is a no-op once a view exists, which is the steady state on
- // every platform.
- // Bounded by `APPLIED_GENERATION`: carry forward only while the last write is
- // still unapplied, or every frame would re-upload the whole atlas forever.
- let mut textures_delta = if render_output.generation == applied_generation() {
- Default::default()
- } else {
- std::mem::take(&mut render_output.textures_delta)
- };
- textures_delta.append(full_output.textures_delta);
-
- *render_output = EguiRenderOutput {
- clipped_primitives,
- textures_delta,
- size_in_pixels,
- pixels_per_point,
- generation: render_output.generation.wrapping_add(1),
- force_next_write: false,
- };
-}
-
-/// Generation of the last [`EguiRenderOutput`] whose texture deltas actually
-/// reached the GPU, written by `egui_pass` and read by `end_egui_frame`.
-///
-/// A `static` rather than a resource because the two live in different worlds:
-/// `egui_pass` runs in the render world on an extracted copy, so it has no way to
-/// tell the main world "I applied that" through ordinary change detection. One
-/// `u64` of shared state is cheaper than a channel, and the only thing the main
-/// world needs to know is whether its last write was consumed.
-static APPLIED_GENERATION: std::sync::atomic::AtomicU64 =
- std::sync::atomic::AtomicU64::new(u64::MAX);
-
-fn applied_generation() -> u64 {
- APPLIED_GENERATION.load(std::sync::atomic::Ordering::Relaxed)
-}
-
-// ─── Render pass system ────────────────────────────────────────────────────────
-
-/// Draws the tessellated egui output onto the view target. Runs per view in the
-/// `Core3d` render schedule (Bevy 0.19's schedule-based render graph).
-pub fn egui_pass(
- view: ViewQuery<(&'static ViewTarget, &'static ExtractedCamera)>,
- render_data: Res<EguiRenderOutput>,
- #[cfg(not(target_arch = "wasm32"))] egui_renderer_res: Res<EguiWgpuRenderer>,
- #[cfg(target_arch = "wasm32")] egui_renderer_res: bevy::ecs::system::NonSend<EguiWgpuRenderer>,
- render_device: Res<RenderDevice>,
- render_queue: Res<RenderQueue>,
- mut render_context: RenderContext,
-) {
- if render_data.clipped_primitives.is_empty() && render_data.textures_delta.is_empty() {
- return;
- }
-
- let (view_target, camera) = view.into_inner();
- // The UI is the window's: a camera ordered before the main one renders
- // into a picture of its own (`avatar_video`'s, 512 × 384), and the
- // window's scissors on it fail the whole submission — silently, headless.
- if camera.order < 0 {
- return;
- }
- let render_queue = render_queue.into_inner();
- let mut guard = egui_renderer_res.0.lock().unwrap();
-
- // Draw onto the final presented output when there's a separate output texture
- // (HDR / upscaling), otherwise the main texture already is the swapchain. Either
- // way this is a single-sampled sRGB target, so egui reads correctly and stably.
- let has_out = view_target.out_texture().is_some();
- let texture_format = view_target
- .out_texture_view_format()
- .unwrap_or_else(|| view_target.main_texture_format());
- let sample_count = 1u32;
-
- // (Re-)create the wgpu renderer when the output format or sample count changes.
- let needs_recreate = guard
- .as_ref()
- .map(|(_, fmt, s, _, _)| *fmt != texture_format || *s != sample_count)
- .unwrap_or(true);
-
- if needs_recreate {
- *guard = Some((
- egui_wgpu::Renderer::new(
- render_device.wgpu_device(),
- texture_format,
- egui_wgpu::RendererOptions {
- depth_stencil_format: None, // no depth buffer
- msaa_samples: sample_count,
- dithering: false,
- ..Default::default()
- },
- ),
- texture_format,
- sample_count,
- // A fresh renderer holds no buffers, so force an upload below.
- None,
- // Whatever was queued for destruction belonged to the renderer this
- // replaces; dropping it releases those textures the safe way (wgpu
- // keeps a dropped resource alive until the buffers using it retire).
- Vec::new(),
- ));
- }
-
- let (renderer, _, _, uploaded_gen, pending_free) = guard.as_mut().unwrap();
-
- // Destroy last frame's retired textures *now*, at the top of the pass, rather
- // than at the bottom of the one that retired them — see the note where they
- // are queued. Bevy has submitted that frame's command buffers by the time this
- // runs again, so the destroy can no longer invalidate a recorded draw.
- for id in pending_free.drain(..) {
- renderer.free_texture(&id);
- }
-
- let screen_descriptor = egui_wgpu::ScreenDescriptor {
- size_in_pixels: render_data.size_in_pixels,
- pixels_per_point: render_data.pixels_per_point,
- };
-
- // Only re-upload when the output actually changed. `end_egui_frame` leaves
- // `render_data` untouched on quiet frames, so its `clipped_primitives` — and its
- // `textures_delta` — are the same ones already on the GPU; re-running these
- // would rewrite the whole vertex/index buffer set and re-apply a spent texture
- // delta every frame for an identical picture.
- let needs_upload = *uploaded_gen != Some(render_data.generation);
-
- let extra_cmd_bufs = if needs_upload {
- // Upload new / changed textures (font atlas, custom images).
- for (id, deltas) in &render_data.textures_delta.set {
- for delta in deltas {
- renderer.update_texture(render_device.wgpu_device(), render_queue, *id, delta);
- }
- }
- // Tell the main world these landed, so `end_egui_frame` stops carrying them
- // forward. Set here rather than at the end of the pass because this loop is
- // the whole of "applied" — everything below is geometry.
- APPLIED_GENERATION.store(render_data.generation, std::sync::atomic::Ordering::Relaxed);
- // Upload vertex/index buffers; collect any extra staging command buffers.
- let encoder = render_context.command_encoder();
- renderer.update_buffers(
- render_device.wgpu_device(),
- render_queue,
- encoder,
- &render_data.clipped_primitives,
- &screen_descriptor,
- )
- } else {
- Vec::new()
- };
- *uploaded_gen = Some(render_data.generation);
-
- // Draw egui on top of the presented frame.
- {
- let encoder = render_context.command_encoder();
- let color_attachment = if has_out {
- view_target.out_texture_color_attachment(None).unwrap()
- } else {
- view_target.get_color_attachment()
- };
- let mut render_pass = encoder
- .begin_render_pass(&RenderPassDescriptor {
- label: Some("egui_render_pass"),
- color_attachments: &[Some(color_attachment)],
- depth_stencil_attachment: None,
- timestamp_writes: None,
- occlusion_query_set: None,
- multiview_mask: None,
- })
- .forget_lifetime();
-
- renderer.render(
- &mut render_pass,
- &render_data.clipped_primitives,
- &screen_descriptor,
- );
- }
-
- // Submit extra command buffers produced by paint callbacks.
- for cb in extra_cmd_bufs {
- render_context.add_command_buffer(cb);
- }
-
- // Queue the textures egui has finished with — once, on the frame the delta
- // arrived (see `needs_upload`), not every frame it stays resident. **Queued,
- // not freed**, because `Renderer::free_texture` calls `wgpu::Texture::destroy`,
- // which takes effect immediately rather than when the last user retires: doing
- // it here would destroy a texture whose draw call this very pass has just
- // recorded, and wgpu answers that at `Queue::submit` — after the render graph
- // has moved on — with
- //
- // Validation Error … In a draw command … Texture with
- // 'egui_texid_Managed(3)' label has been destroyed
- //
- // `handle_render_error` halts the renderer on `Validation` (it recurs), so the
- // whole app freezes with the picture it last drew. Reported from a phone on
- // 2026-08-16: opening a saved place's photo and closing it again froze the app,
- // because egui retires a texture in the pass that its `TextureHandle` is
- // dropped in, and the viewer's window — image and all — was drawn in that same
- // pass. egui-wgpu's own winit painter has the same ordering constraint and
- // solves it by freeing after `Queue::submit`; the render graph submits for us,
- // so the equivalent here is "at the top of the next pass".
- if needs_upload {
- pending_free.extend(render_data.textures_delta.free.iter().copied());
- }
-}
-
-// ─── Tests ────────────────────────────────────────────────────────────────────
-
-/// A test's own egui passes, whose output nobody paints.
-///
-/// egui 0.36 debug-asserts that a `TexturesDelta` is never dropped unapplied, and
-/// a test that runs a `Context` by hand has no painter to apply one, so these
-/// clear the texture half of the output and hand back the rest.
-#[cfg(test)]
-pub(crate) trait UnpaintedPasses {
- fn run_ui_unpainted(
- &self,
- input: egui::RawInput,
- run_ui: impl FnMut(&mut egui::Ui),
- ) -> egui::FullOutput;
- fn end_pass_unpainted(&self) -> egui::FullOutput;
-}
-
-#[cfg(test)]
-impl UnpaintedPasses for egui::Context {
- fn run_ui_unpainted(
- &self,
- input: egui::RawInput,
- run_ui: impl FnMut(&mut egui::Ui),
- ) -> egui::FullOutput {
- let mut out = self.run_ui(input, run_ui);
- out.textures_delta.clear();
- out
- }
-
- fn end_pass_unpainted(&self) -> egui::FullOutput {
- let mut out = self.end_pass();
- out.textures_delta.clear();
- out
- }
-}
-
-#[cfg(test)]
-mod tests;
diff --git a/crates/cartopolis/src/systems/gui/egui_manager/tests.rs b/crates/cartopolis/src/systems/gui/egui_manager/tests.rs
deleted file mode 100644
index babc9e5f..00000000
--- a/crates/cartopolis/src/systems/gui/egui_manager/tests.rs
+++ /dev/null
@@ -1,753 +0,0 @@
-use super::*;
-use bevy::input::mouse::MouseButtonInput;
-
-/// A UI waiting on input is reused forever; a UI that said it animates is
-/// reused *until its deadline* and then redrawn.
-///
-/// The second half is the one worth pinning. Testing `repaint_delay` for
-/// `Duration::MAX` instead — which is what this did — reads a finite delay as
-/// "redraw now", and since an animating widget re-requests every pass it draws,
-/// the skip goes off permanently the moment anything on screen animates. Both
-/// failure modes are silent: one freezes a clock, the other quietly tessellates
-/// the whole UI sixty times a second.
-#[test]
-fn animating_ui_is_redrawn_on_its_deadline_and_not_before() {
- let forever = std::time::Duration::MAX;
- assert!(geometry_still_current(forever, 0.0));
- assert!(geometry_still_current(forever, 3_600.0));
-
- // A widget asking for a look within a quarter second.
- let soon = std::time::Duration::from_millis(250);
- assert!(geometry_still_current(soon, 0.0));
- assert!(geometry_still_current(soon, 0.2));
- assert!(!geometry_still_current(soon, 0.3));
-}
-
-use bevy::input::InputPlugin;
-use bevy::window::{
- CursorMoved, ExitCondition, PrimaryWindow, WindowCloseRequested, WindowEvent, WindowPlugin,
-};
-
-fn moved(x: f32, y: f32) -> WindowEvent {
- WindowEvent::CursorMoved(CursorMoved {
- window: Entity::PLACEHOLDER,
- position: Vec2::new(x, y),
- delta: None,
- })
-}
-
-fn button(pressed: bool) -> WindowEvent {
- WindowEvent::MouseButtonInput(MouseButtonInput {
- button: MouseButton::Left,
- state: if pressed {
- ButtonState::Pressed
- } else {
- ButtonState::Released
- },
- window: Entity::PLACEHOLDER,
- })
-}
-
-fn touch(id: u64, phase: bevy::input::touch::TouchPhase, x: f32, y: f32) -> WindowEvent {
- WindowEvent::TouchInput(bevy::input::touch::TouchInput {
- phase,
- position: Vec2::new(x, y),
- window: Entity::PLACEHOLDER,
- force: None,
- id,
- })
-}
-
-/// Run a window-event stream through the bridge, as `begin_egui_frame` does.
-fn bridge(stream: &[WindowEvent]) -> Vec<egui::Event> {
- bridge_scaled(stream, 1.0)
-}
-
-/// As [`bridge`], with an explicit UI scale.
-fn bridge_scaled(stream: &[WindowEvent], ui_scale: f32) -> Vec<egui::Event> {
- let mut state = PointerBridge::default();
- let mut out = Vec::new();
- for ev in stream {
- pointer_events(ev, ui_scale, &mut state, &mut out);
- }
- out
-}
-
-/// The double tap that never opened the building card.
-///
-/// A finger's click reaches `ButtonInput` a frame after egui saw the finger
-/// land, and a brisk tap has lifted by then. On that frame egui has no button
-/// down and `egui_wants_pointer_input()` answers `true` over the bare map, so
-/// the world gate threw the tap away. [`press_over_ui`] answers from where the
-/// finger landed: the map is the world's, a panel is egui's.
-#[test]
-fn a_brisk_tap_on_the_map_is_the_worlds_after_egui_saw_it_lift() {
- use bevy::input::touch::TouchPhase;
-
- let ctx = egui::Context::default();
- let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 720.0));
- let mut map_rect = None;
- let mut pass = |stream: &[WindowEvent]| {
- let mut raw = egui::RawInput::default();
- raw.screen_rect = Some(screen);
- raw.events = bridge(stream);
- ctx.begin_pass(raw);
- // As `begin_egui_frame` builds it, with one docked panel on the right.
- let mut root = egui::Ui::new(
- ctx.clone(),
- egui::Id::new((ctx.viewport_id(), "__cartopolis_root_ui")),
- egui::UiBuilder::new()
- .layer_id(egui::LayerId::background())
- .max_rect(ctx.viewport_rect()),
- );
- egui::Panel::right("panel")
- .default_size(260.0)
- .show(&mut root, |ui| {
- ui.label("panel");
- });
- map_rect = Some(root.available_rect_before_wrap());
- drop(root);
- let _ = ctx.end_pass_unpainted();
- };
-
- let on_map = egui::pos2(300.0, 300.0);
- let on_panel = egui::pos2(1200.0, 300.0);
- pass(&[]);
- pass(&[touch(1, TouchPhase::Started, on_map.x, on_map.y)]);
- // The frame the emulated click lands on, with the lift in its batch.
- pass(&[touch(1, TouchPhase::Ended, on_map.x, on_map.y)]);
-
- assert!(
- ctx.egui_wants_pointer_input(),
- "the old gate: egui claims a lifted tap over the bare map"
- );
- assert!(
- !press_over_ui(&ctx, map_rect, on_map),
- "the map is the world's"
- );
- assert!(press_over_ui(&ctx, map_rect, on_panel), "a panel is egui's");
-
- // The same frame through `UiInput`, which the world's click gates read:
- // the verdict is taken at the window cursor, in window points — the
- // egui points above at 1.0×, and half as many again at 1.5×.
- let metrics = UiMetrics::with_ui_scale(1.0);
- let at = |p: egui::Pos2| Vec2::new(p.x, p.y);
- let mut input = UiInput::default();
- input.set_egui(verdict_of(&ctx, map_rect, &metrics, Some(at(on_map))));
- assert!(
- !input.owns_click(true, Some(at(on_map))),
- "UiInput: the map is the world's"
- );
- assert!(
- input.owns_click(false, Some(at(on_map))),
- "UiInput: a mouse asks egui, as before"
- );
- input.set_egui(verdict_of(&ctx, map_rect, &metrics, Some(at(on_panel))));
- assert!(
- input.owns_click(true, Some(at(on_panel))),
- "UiInput: a panel is egui's"
- );
-
- let scaled = UiMetrics::with_ui_scale(1.5);
- let window = |p: egui::Pos2| Vec2::new(p.x * 1.5, p.y * 1.5);
- input.set_egui(verdict_of(&ctx, map_rect, &scaled, Some(window(on_map))));
- assert!(!input.owns_click(true, Some(window(on_map))));
- input.set_egui(verdict_of(&ctx, map_rect, &scaled, Some(window(on_panel))));
- assert!(input.owns_click(true, Some(window(on_panel))));
- // A cursor the verdict was not taken at falls back to the map rect,
- // carried back into window points.
- assert!(!input.owns_click(true, Some(window(on_map))));
-}
-
-/// The resources are what the manager says, frame by frame: `UiMetrics`
-/// lays out against the same surface, and `UiInput` carries egui's verdict
-/// and hands the library's back to the manager for the egui systems that
-/// still ask it.
-#[test]
-fn ui_metrics_and_ui_input_follow_the_manager() {
- let mut window = Window::default();
- window.resolution.set_physical_resolution(1080, 2280);
- window.resolution.set_scale_factor(2.75);
- let mut app = ui_app(Some(window));
- app.update();
- app.update();
- let mgr = app.world().resource::<EguiManager>();
- let metrics = *app.world().resource::<UiMetrics>();
- assert_eq!(metrics, mgr.metrics());
-
- let input = *app.world().resource::<UiInput>();
- assert_eq!(input.egui_verdict(), mgr.verdict(None));
- assert!(!input.overlay_owns_pointer());
-
- app.world_mut()
- .resource_mut::<UiInput>()
- .set_overlay(true, true);
- app.update();
- let mgr = app.world().resource::<EguiManager>();
- assert!(
- mgr.owns_click(false, None),
- "the library's pointer reaches egui"
- );
- let keys = ButtonInput::<KeyCode>::default();
- assert!(app
- .world()
- .resource::<UiInput>()
- .ui_owns_keyboard(false, &keys));
-}
-
-/// A finger that goes down and is never lifted — the Android camera intent
-/// taking the activity away with a thumb still on the glass — must not deafen
-/// the bridge to every later touch.
-///
-/// Without the heal this is permanent: `state.touch` holds the dead id,
-/// `pointer_events` returns early for every finger that is not it, and touch
-/// ids only increase, so egui never receives another pointer event for the
-/// rest of the run. See [`heal_lost_touch`].
-#[test]
-fn a_touch_that_is_never_lifted_does_not_deafen_the_bridge() {
- use bevy::input::touch::TouchPhase;
-
- let mut state = PointerBridge::default();
- let mut out = Vec::new();
- pointer_events(
- &touch(7, TouchPhase::Started, 10.0, 20.0),
- 1.0,
- &mut state,
- &mut out,
- );
- assert_eq!(state.touch, Some(7), "the first finger takes the pointer");
-
- // The lift never arrives — the app was suspended. On resume Bevy's own
- // set is released (`quiesce_while_backgrounded`), which is the only
- // signal that finger 7 is gone.
- out.clear();
- heal_lost_touch(&mut state, |_| false, &mut out);
- assert_eq!(state.touch, None, "the dead finger was not released");
- assert!(
- matches!(
- out.as_slice(),
- [
- egui::Event::PointerButton { pressed: false, .. },
- egui::Event::PointerGone
- ]
- ),
- "a healed lift must look exactly like a real one, got {out:?}"
- );
-
- // …and the next finger is heard.
- out.clear();
- pointer_events(
- &touch(8, TouchPhase::Started, 30.0, 40.0),
- 1.0,
- &mut state,
- &mut out,
- );
- assert!(
- out.iter().any(|e| matches!(
- e,
- egui::Event::PointerButton {
- pressed: true,
- button: egui::PointerButton::Primary,
- ..
- }
- )),
- "the finger after a lost lift never reached egui, got {out:?}"
- );
-}
-
-/// The heal must not fire on a finger that is genuinely still down, or every
-/// drag would be cut short one frame after it started.
-#[test]
-fn a_finger_still_on_the_glass_is_left_alone() {
- use bevy::input::touch::TouchPhase;
-
- let mut state = PointerBridge::default();
- let mut out = Vec::new();
- pointer_events(
- &touch(3, TouchPhase::Started, 10.0, 20.0),
- 1.0,
- &mut state,
- &mut out,
- );
-
- out.clear();
- heal_lost_touch(&mut state, |id| id == 3, &mut out);
- assert_eq!(state.touch, Some(3), "a live finger was released");
- assert!(out.is_empty(), "a live finger produced events, got {out:?}");
-}
-
-/// The click-then-flick frame: `[move→target, press, release, move→far]`
-/// arrives as one batch, and the buttons must be stamped with the position
-/// *at their point in the stream* (the target), not the end-of-frame cursor
-/// position (the far side of the flick). The old `ButtonInput` +
-/// `cursor_position()` bridge got exactly this wrong, which is why panel
-/// checkboxes only responded to a motionless click.
-#[test]
-fn buttons_carry_the_position_at_their_point_in_the_stream() {
- let target = egui::Pos2::new(100.0, 100.0);
- let stream = [
- moved(100.0, 100.0),
- button(true),
- button(false),
- moved(400.0, 300.0),
- ];
- let events = bridge(&stream);
-
- assert_eq!(events.len(), 4);
- match (&events[1], &events[2]) {
- (
- egui::Event::PointerButton {
- pos: p1,
- pressed: true,
- ..
- },
- egui::Event::PointerButton {
- pos: p2,
- pressed: false,
- ..
- },
- ) => {
- assert_eq!(*p1, target, "press teleported away from the pointer");
- assert_eq!(*p2, target, "release teleported away from the pointer");
- }
- other => panic!("expected press then release, got {other:?}"),
- }
- assert!(
- matches!(events[3], egui::Event::PointerMoved(p) if p.x == 400.0),
- "the flick motion must still be delivered, after the click"
- );
-}
-
-/// A finger down-move-up must produce the full pointer sequence, ending in
-/// `PointerGone` — a finger leaves no cursor behind it, and egui otherwise
-/// keeps hovering (and claiming) whatever it last touched.
-#[test]
-fn a_finger_synthesises_a_whole_pointer_sequence() {
- use bevy::input::touch::TouchPhase as P;
- let events = bridge(&[
- touch(7, P::Started, 100.0, 100.0),
- touch(7, P::Moved, 120.0, 140.0),
- touch(7, P::Ended, 120.0, 140.0),
- ]);
- // Every phase also goes out verbatim, for egui's own multi-touch readers.
- assert_eq!(
- events
- .iter()
- .filter(|e| matches!(e, egui::Event::Touch { .. }))
- .count(),
- 3
- );
- let pointer: Vec<_> = events
- .iter()
- .filter(|e| !matches!(e, egui::Event::Touch { .. }))
- .collect();
- let down = egui::Pos2::new(100.0, 100.0);
- assert!(
- matches!(pointer[0], egui::Event::PointerMoved(p) if *p == down),
- "the press must be preceded by a move, or egui hit-tests it at the \
- stale position: {pointer:?}"
- );
- assert!(matches!(
- pointer[1],
- egui::Event::PointerButton { pressed: true, .. }
- ));
- assert!(matches!(pointer[2], egui::Event::PointerMoved(_)));
- assert!(matches!(
- pointer[3],
- egui::Event::PointerButton { pressed: false, .. }
- ));
- assert!(matches!(pointer[4], egui::Event::PointerGone));
- assert_eq!(pointer.len(), 5);
-}
-
-/// egui has one pointer. The second finger of a pinch must not drag the UI
-/// out from under the first, nor report the pointer gone when it lifts.
-#[test]
-fn only_the_first_finger_drives_the_egui_pointer() {
- use bevy::input::touch::TouchPhase as P;
- let events = bridge(&[
- touch(1, P::Started, 100.0, 100.0),
- touch(2, P::Started, 300.0, 100.0),
- touch(2, P::Moved, 400.0, 100.0),
- touch(2, P::Ended, 400.0, 100.0),
- ]);
- let pointer: Vec<_> = events
- .iter()
- .filter(|e| !matches!(e, egui::Event::Touch { .. }))
- .collect();
- // Only finger 1's move+press.
- assert_eq!(pointer.len(), 2, "{pointer:?}");
- assert!(
- !pointer
- .iter()
- .any(|e| matches!(e, egui::Event::PointerGone)),
- "the second finger lifting must not take the pointer with it"
- );
-}
-
-/// A cancelled touch (the browser taking the gesture, a call arriving) must
-/// release the pointer exactly as a lift does — otherwise egui is left with
-/// a button held down forever and every later tap reads as a drag.
-#[test]
-fn a_cancelled_touch_releases_the_pointer() {
- use bevy::input::touch::TouchPhase as P;
- let events = bridge(&[
- touch(1, P::Started, 100.0, 100.0),
- touch(1, P::Canceled, 100.0, 100.0),
- // The pointer is free again, so a fresh finger takes it.
- touch(2, P::Started, 200.0, 200.0),
- ]);
- let pressed: Vec<bool> = events
- .iter()
- .filter_map(|e| match e {
- egui::Event::PointerButton { pressed, .. } => Some(*pressed),
- _ => None,
- })
- .collect();
- assert_eq!(pressed, vec![true, false, true]);
-}
-
-/// End-to-end: a click-then-flick arriving as ONE frame's batch must still
-/// toggle a checkbox, via the pass-splitting the live bridge applies
-/// ([`take_pass_events`]). Without the split this exact scenario fails:
-/// egui hit-tests once per pass at the batch's final pointer position, so
-/// the click lands wherever the flick ended.
-#[test]
-fn click_then_flick_in_one_frame_still_clicks() {
- let ctx = egui::Context::default();
- crate::systems::theme::install(&ctx);
- let mut checked = true;
- let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 720.0));
-
- let mut target: Option<egui::Pos2> = None;
- let mut pending: Vec<egui::Event> = Vec::new();
- for frame in 0..6 {
- let mut raw = egui::RawInput::default();
- raw.screen_rect = Some(screen);
- if let (1, Some(pos)) = (frame, target) {
- // One frame's batch: arrive at the checkbox, click, flick away.
- pending = bridge(&[
- moved(pos.x, pos.y),
- button(true),
- button(false),
- moved(pos.x + 300.0, pos.y + 200.0),
- ]);
- }
- raw.events = take_pass_events(&mut pending);
- let rect = std::cell::Cell::new(None);
- let checked_ref = &mut checked;
- // The pass output is the paint job; this test only reads widget state.
- let _ = ctx.run_ui_unpainted(raw, |ui| {
- egui::Panel::right("panel")
- .default_size(260.0)
- .show(ui, |ui| {
- let resp = ui.checkbox(checked_ref, "a checkbox");
- rect.set(Some(resp.rect));
- });
- });
- if target.is_none() {
- target = rect.get().map(|r| r.center());
- }
- }
- assert!(pending.is_empty(), "the carry never drained");
- assert!(!checked, "the click-then-flick frame lost the click");
-}
-
-/// Drive a checkbox through the **app's own** frame shape: the shared root
-/// `Ui` that [`begin_egui_frame`] builds by hand, not the one `run_ui` hands
-/// out. Returns whether the click landed.
-///
-/// `overlay` gets the map area (the root `Ui`'s leftover space, exactly what
-/// `place_pins` culls against) after the panel has taken its width, so a test
-/// can put a floating `Area` there and ask whether it eats the panel's clicks.
-fn click_checkbox_through_root_ui(overlay: impl Fn(&egui::Context, egui::Rect)) -> bool {
- click_checkbox_with_drift(overlay, 0.0)
-}
-
-/// As above, but the pointer drifts `drift` points between press and release —
-/// what a real hand does. The events interleave as
-/// `[moved, press]` … `[moved, release]`, which is the shape the live bridge
-/// hands egui.
-fn click_checkbox_with_drift(overlay: impl Fn(&egui::Context, egui::Rect), drift: f32) -> bool {
- let ctx = egui::Context::default();
- crate::systems::theme::install(&ctx);
- let mut checked = false;
- let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 720.0));
-
- // The panel slides open (`show_collapsible` animates), so a click aimed at
- // frame 0's rect would land on a moving target and prove nothing. Wait for
- // the checkbox to hold the same rect two passes running, then click that.
- let mut seen: Option<egui::Rect> = None;
- let mut settled: Option<egui::Pos2> = None;
- let mut clicked_at: Option<usize> = None;
- let mut pending: Vec<egui::Event> = Vec::new();
- for frame in 0..24 {
- let mut raw = egui::RawInput::default();
- raw.screen_rect = Some(screen);
- if let (None, Some(pos)) = (clicked_at, settled) {
- pending = bridge(&[
- moved(pos.x, pos.y),
- button(true),
- moved(pos.x + drift, pos.y),
- button(false),
- ]);
- clicked_at = Some(frame);
- }
- raw.events = take_pass_events(&mut pending);
-
- ctx.begin_pass(raw);
- // Verbatim from `begin_egui_frame` — the thing under test.
- let mut root = egui::Ui::new(
- ctx.clone(),
- egui::Id::new((ctx.viewport_id(), "__cartopolis_root_ui")),
- egui::UiBuilder::new()
- .layer_id(egui::LayerId::background())
- .max_rect(ctx.viewport_rect()),
- );
- let mut open = true;
- let rect = std::cell::Cell::new(None);
- let checked_ref = &mut checked;
- egui::Panel::right("layers_panel")
- .default_size(260.0)
- .show_collapsible(&mut root, &mut open, |ui| {
- let resp = ui.checkbox(checked_ref, "Buildings");
- rect.set(Some(resp.rect));
- });
- overlay(&ctx, root.available_rect_before_wrap());
- drop(root);
- // The pass output is the paint job; this test only reads widget state.
- let _ = ctx.end_pass_unpainted();
-
- if settled.is_none() {
- if let Some(r) = rect.get() {
- if seen == Some(r) {
- settled = Some(r.center());
- }
- seen = Some(r);
- }
- }
- }
- assert!(settled.is_some(), "the checkbox never settled into a rect");
- assert!(
- clicked_at.is_some_and(|f| f + 3 < 24),
- "the click was issued too late to be resolved"
- );
- checked
-}
-
-/// A checkbox in a right panel must respond to a click when nothing is over
-/// it. This is the app's real frame shape, which `run_ui` does not reproduce.
-#[test]
-fn panel_checkbox_clicks_through_the_shared_root_ui() {
- assert!(
- click_checkbox_through_root_ui(|_, _| {}),
- "a panel checkbox in the shared root `Ui` ignored a clean click"
- );
-}
-
-/// A hand does not hold a mouse still. Sub-pixel drift between press and
-/// release — measured at 0.67 and 0.89 pt in a live session, far inside egui's
-/// 6 pt `max_click_dist` — must not lose the click. In that session the only
-/// press that toggled anything was the one that drifted exactly 0.0 pt.
-#[test]
-fn a_drifting_hand_still_clicks() {
- for drift in [0.0, 0.5, 0.89, 2.0, 5.0] {
- assert!(
- click_checkbox_with_drift(|_, _| {}, drift),
- "{drift} pt of drift between press and release lost the click"
- );
- }
-}
-
-/// A floating `Area` covering the **map** must not eat clicks aimed at the
-/// panel beside it. Panels live on the background layer and every `Area`
-/// paints above them, so an overlay that fails to cull itself to the map area
-/// steals the panel's input — the whole reason `place_pins` culls rather than
-/// clips (see `docs/notes/egui-shared-root-ui.md`). This pins the contract
-/// from the panel's side.
-#[test]
-fn a_map_overlay_does_not_eat_panel_clicks() {
- assert!(
- click_checkbox_through_root_ui(|ctx, map_rect| {
- egui::Area::new(egui::Id::new("test_map_overlay"))
- .fixed_pos(map_rect.left_top())
- .show(ctx, |ui| {
- ui.allocate_response(map_rect.size(), egui::Sense::click());
- });
- }),
- "an overlay confined to the map area ate a click meant for the panel"
- );
-}
-
-/// A UI-bearing app with no render world (`EguiPlugin` skips its render-app
-/// half when there is none, which is exactly what a test wants).
-fn ui_app(primary_window: Option<Window>) -> App {
- let mut app = App::new();
- app.add_plugins((
- MinimalPlugins,
- InputPlugin,
- WindowPlugin {
- primary_window,
- exit_condition: ExitCondition::OnAllClosed,
- close_when_requested: true,
- ..default()
- },
- EguiPlugin,
- ))
- .add_systems(Update, touch_root_ui);
- app
-}
-
-/// The first thing every panel system does.
-fn touch_root_ui(egui: EguiRef) {
- let _ = egui.ctx();
-}
-
-/// The macOS shutdown crash (#2): Bevy despawns the window in `Last`, so the
-/// frames between the close and the process actually exiting run the whole
-/// `Update` schedule with no `Window` in the world. `begin_egui_frame` used to
-/// bail out there, leaving every panel system to panic on `ui_mut()`.
-#[test]
-fn update_survives_the_window_being_closed() {
- let mut app = ui_app(Some(Window::default()));
- app.update();
-
- let window = app
- .world_mut()
- .query_filtered::<Entity, With<PrimaryWindow>>()
- .single(app.world())
- .expect("primary window");
- app.world_mut()
- .write_message(WindowCloseRequested { window });
-
- // `close_when_requested` marks on one frame and despawns on the next, so
- // give it both — then run the frames that used to panic.
- for _ in 0..4 {
- app.update();
- }
- assert!(
- app.world_mut()
- .query_filtered::<Entity, With<Window>>()
- .iter(app.world())
- .next()
- .is_none(),
- "the window should be gone — otherwise this test never reaches the case it is about"
- );
-}
-
-/// The same invariant from the other end: a windowless run whose
-/// `HeadlessSurface` is missing — what a `--shot` capture looks like if the
-/// harness fails to insert one. The UI has nothing to lay out against, which
-/// is not a reason to take the process down.
-#[test]
-fn update_survives_a_run_with_no_surface_at_all() {
- let mut app = ui_app(None);
- app.update();
- app.update();
-}
-
-/// A zero/NaN scale factor divides every viewport size, so it is sanitised on
-/// the way in rather than propagated as infinities through panel layout.
-#[test]
-fn a_degenerate_scale_factor_never_reaches_layout() {
- let mut mgr = EguiManager::default();
- for bad in [0.0, -1.0, f32::NAN] {
- mgr.set_surface(UVec2::new(1280, 720), bad);
- assert_eq!(mgr.metrics().viewport_pts(), Vec2::new(1280.0, 720.0));
- }
- mgr.set_surface(UVec2::new(2560, 1440), 2.0);
- assert_eq!(mgr.metrics().viewport_pts(), Vec2::new(1280.0, 720.0));
-}
-
-/// The UI scale multiplies the widgets by dividing the viewport: the same
-/// screen holds fewer, larger points. Everything responsive keys off
-/// `viewport_pts`, so a phone that was merely narrow becomes narrow *and*
-/// compact from this one number.
-#[test]
-fn ui_scale_shrinks_the_viewport_it_magnifies() {
- let mut mgr = EguiManager::default();
- mgr.metrics = UiMetrics::with_ui_scale(1.5);
- // Android, where a phone's whole 1080 px width reaches Bevy: 393 pt of
- // viewport at a 2.75 scale factor, 262 pt of it after the magnification.
- mgr.set_surface(UVec2::new(1080, 2280), 2.75);
- assert!((mgr.metrics().viewport_pts().x - 261.8).abs() < 0.1);
- assert!(mgr.metrics().compact());
-}
-
-/// Why [`phone_ui_scale`] is 1.0 on the web: the render budget's stage
-/// transform has already shrunk the surface Bevy sees, so magnifying again
-/// would halve an already-tight viewport (it was also, until the fix above,
-/// how a docked panel came out wider than the screen).
-///
-/// Same handset as above, but through the phone tier's k ≈ 1.83: winit
-/// measures the *untransformed* box, so Bevy's surface is 1080/1.83 px.
-#[test]
-fn the_web_phone_tier_has_no_room_to_magnify() {
- let surface = UVec2::new(590, 1245); // 1080×2280 ÷ 1.83
- let mut unscaled = EguiManager::default();
- unscaled.metrics = UiMetrics::with_ui_scale(1.0);
- unscaled.set_surface(surface, 2.75);
- assert!(unscaled.metrics().viewport_pts().x > 200.0, "usable at 1.0");
-
- let mut scaled = EguiManager::default();
- scaled.metrics = UiMetrics::with_ui_scale(1.5);
- scaled.set_surface(surface, 2.75);
- assert!(
- scaled.metrics().viewport_pts().x < 240.0,
- "1.5× would dock a 240 pt panel in a {} pt viewport",
- scaled.metrics().viewport_pts().x
- );
-}
-
-/// Positions enter in the window's logical points and must leave in egui's,
-/// or every widget is hit-tested at a position that drifts further from the
-/// finger the further it is from the top-left corner. Converted at the
-/// bridge so `state.last` — and the button events built from it — are
-/// already in egui's space.
-#[test]
-fn the_pointer_bridge_converts_into_egui_points() {
- let events = bridge_scaled(&[moved(300.0, 600.0), button(true)], 1.5);
- let positions: Vec<egui::Pos2> = events
- .iter()
- .filter_map(|e| match e {
- egui::Event::PointerMoved(p) => Some(*p),
- egui::Event::PointerButton { pos, .. } => Some(*pos),
- _ => None,
- })
- .collect();
- assert_eq!(positions, vec![egui::pos2(200.0, 400.0); 2]);
-}
-
-/// The same conversion, for the world-anchored overlays that get their
-/// positions from `Camera::world_to_viewport` rather than from an event.
-#[test]
-fn window_to_ui_matches_the_bridge() {
- let mut mgr = EguiManager::default();
- mgr.metrics = UiMetrics::with_ui_scale(1.5);
- assert_eq!(
- mgr.window_to_ui(Vec2::new(300.0, 600.0)),
- egui::pos2(200.0, 400.0)
- );
-}
-
-/// The display scale and the UI magnification have to come apart again:
-/// `set_surface` multiplies them into one number, and anything reasoning
-/// about *physical* size (`onscreen_keyboard`'s 48 dp touch target) needs the
-/// density on its own.
-#[test]
-fn display_scale_survives_being_folded_into_the_surface() {
- let mut mgr = EguiManager::default();
- mgr.metrics = UiMetrics::with_ui_scale(1.5);
- mgr.set_surface(UVec2::new(1080, 2280), 2.75);
- assert!((mgr.metrics().display_scale() - 2.75).abs() < 1e-4);
-}
-
-/// An out-of-range scale is clamped rather than obeyed: at 20× there is no
-/// longer a button on screen to press to undo it.
-#[test]
-fn an_absurd_ui_scale_is_clamped() {
- for (raw, want) in [(20.0_f32, 3.0_f32), (0.01, 0.5), (1.4, 1.4)] {
- let clamped = raw.clamp(*UI_SCALE_RANGE.start(), *UI_SCALE_RANGE.end());
- assert_eq!(clamped, want, "clamping {raw}");
- }
-}
diff --git a/crates/cartopolis/src/systems/gui/icons.rs b/crates/cartopolis/src/systems/gui/icons.rs
index 6fc8fea7..919818e8 100644
--- a/crates/cartopolis/src/systems/gui/icons.rs
+++ b/crates/cartopolis/src/systems/gui/icons.rs
@@ -3,8 +3,8 @@
//! # Why a font of our own
//!
//! Every icon in this client used to be a Unicode symbol picked out of whatever
-//! egui's bundled font stack (`Ubuntu-Light` + `NotoEmoji` + `emoji-icon-font`)
-//! happened to cover, chosen through a *preference ladder* — `["🔍", "⌕", "S"]` —
+//! the old toolkit's bundled font stack (`Ubuntu-Light` + `NotoEmoji` +
+//! `emoji-icon-font`) happened to cover, chosen through a *preference ladder* — `["🔍", "⌕", "S"]` —
//! that fell back to a letter when the font could not draw the glyph. That
//! machinery worked, in the sense that nothing drew an empty box; what it could
//! not do is look like an icon set. The ladder's survivors were a dharma wheel
@@ -39,21 +39,14 @@ use crate::systems::routing::{Maneuver, TravelMode};
/// The subset font, embedded at compile time.
///
/// Like the brand font and the app icon, this is a **Git LFS object**: a clone
-/// without `git lfs install` embeds a 130-byte pointer file here and epaint
-/// panics on it (see the repo `CLAUDE.md`).
+/// without `git lfs install` embeds a 130-byte pointer file here, which no
+/// font parser accepts (see the repo `CLAUDE.md`). The library draws it as
+/// `FontMap::icons` (`lib_host`).
pub const FONT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../assets/fonts/MaterialSymbolsRounded-subset.ttf"
));
-/// The name `theme::fonts` registers [`FONT`] under, and the name it appends to
-/// every family's fallback list.
-///
-/// It names font *data*, not a family: `FontFamily::Name(FONT_NAME)` is unbound
-/// and panics in epaint the first frame it is drawn. Draw an icon with
-/// `FontId::proportional`, where the fallback list finds it.
-pub const FONT_NAME: &str = "MaterialSymbols";
-
/// One row of the table, for the test that checks the shipped font against it.
///
/// `#[cfg(test)]`, along with [`ALL`]: nothing in the running app reads the
@@ -453,7 +446,6 @@ pub fn travel_mode(mode: TravelMode) -> &'static str {
#[cfg(test)]
mod tests {
use super::*;
- use crate::systems::egui_manager::UnpaintedPasses as _;
/// **Every icon in the table must be in the shipped subset.**
///
@@ -463,32 +455,18 @@ mod tests {
/// at on a screen, since a missing glyph is an empty box and nothing logs.
#[test]
fn every_icon_has_a_glyph() {
- let ctx = egui::Context::default();
- crate::systems::theme::install(&ctx);
- // Inside a pass, like the other font tests: the fonts are built on the
- // first frame, and asking before one has run answers about a stack that
- // does not exist yet.
- let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0));
- let _ = ctx.run_ui_unpainted(
- egui::RawInput {
- screen_rect: Some(screen),
- ..Default::default()
- },
- |ui| {
- let font = egui::TextStyle::Body.resolve(ui.style());
- let missing: Vec<&str> = ui.ctx().fonts_mut(|f| {
- ALL.iter()
- .filter(|i| !f.has_glyphs(&font, i.glyph))
- .map(|i| i.konst)
- .collect()
- });
- assert!(
- missing.is_empty(),
- "the subset font has no glyph for {missing:?} — re-run \
- `tools/subset-icon-font.py` and commit \
- assets/fonts/MaterialSymbolsRounded-subset.ttf with the table",
- );
- },
+ let font = fontdue::Font::from_bytes(FONT, fontdue::FontSettings::default())
+ .expect("the icon font parses (is Git LFS fetched?)");
+ let missing: Vec<&str> = ALL
+ .iter()
+ .filter(|i| i.glyph.chars().any(|c| font.lookup_glyph_index(c) == 0))
+ .map(|i| i.konst)
+ .collect();
+ assert!(
+ missing.is_empty(),
+ "the subset font has no glyph for {missing:?} — re-run \
+ `tools/subset-icon-font.py` and commit \
+ assets/fonts/MaterialSymbolsRounded-subset.ttf with the table",
);
}
diff --git a/crates/cartopolis/src/systems/gui/lib_call.rs b/crates/cartopolis/src/systems/gui/lib_call.rs
index 32e77207..7fc150bc 100644
--- a/crates/cartopolis/src/systems/gui/lib_call.rs
+++ b/crates/cartopolis/src/systems/gui/lib_call.rs
@@ -494,19 +494,52 @@ fn write_html(view: View) {
// ─── Pieces ──────────────────────────────────────────────────────────────────
-type Rect = egui::Rect;
+fn pos2(x: f32, y: f32) -> Vec2 {
+ Vec2::new(x, y)
+}
+
+/// The rect builders the placement was written with (it was egui's), over
+/// Bevy's `Rect`. `from_min_max` does not reorder its corners.
+trait RectExt {
+ fn from_min_max(min: Vec2, max: Vec2) -> Rect;
+ fn from_min_size(min: Vec2, size: Vec2) -> Rect;
+ /// `by` in from every side.
+ fn shrink(self, by: f32) -> Rect;
+ /// `by` out on every side.
+ fn expand(self, by: f32) -> Rect;
+}
+
+impl RectExt for Rect {
+ fn from_min_max(min: Vec2, max: Vec2) -> Rect {
+ Rect { min, max }
+ }
+
+ fn from_min_size(min: Vec2, size: Vec2) -> Rect {
+ Rect {
+ min,
+ max: min + size,
+ }
+ }
+
+ fn shrink(self, by: f32) -> Rect {
+ self.expand(-by)
+ }
-fn pos2(x: f32, y: f32) -> egui::Pos2 {
- egui::pos2(x, y)
+ fn expand(self, by: f32) -> Rect {
+ Rect {
+ min: self.min - Vec2::splat(by),
+ max: self.max + Vec2::splat(by),
+ }
+ }
}
/// The largest rect of shape `aspect` inside `rect`, centred.
fn contain(aspect: f32, rect: Rect) -> Rect {
let target = rect.width() / rect.height().max(1.0);
let size = if aspect > target {
- egui::vec2(rect.width(), rect.width() / aspect)
+ Vec2::new(rect.width(), rect.width() / aspect)
} else {
- egui::vec2(rect.height() * aspect, rect.height())
+ Vec2::new(rect.height() * aspect, rect.height())
};
Rect::from_center_size(rect.center(), size)
}
@@ -547,9 +580,9 @@ fn plate(k: f32, r: Rect, radius: f32, fill: &str) -> View {
/// A circle's outline: `radius` to the middle of a `width` stroke, as egui's
/// `circle_stroke`.
-fn ring(k: f32, c: egui::Pos2, radius: f32, width: f32, colour: &str) -> View {
+fn ring(k: f32, c: Vec2, radius: f32, width: f32, colour: &str) -> View {
let outer = radius + width * 0.5;
- let r = Rect::from_center_size(c, egui::Vec2::splat(2.0 * outer));
+ let r = Rect::from_center_size(c, Vec2::splat(2.0 * outer));
let style = bx(
k,
r,
@@ -603,7 +636,7 @@ fn line(segs: Vec<Seg>, size: f32) -> View {
/// nowhere.
#[allow(clippy::too_many_arguments)]
fn text_at(k: f32, x: f32, y: f32, band: f32, segs: Vec<Seg>, size: f32, colour: &str) -> View {
- let r = Rect::from_center_size(pos2(x, y), egui::vec2(band, size * 2.0 + 8.0));
+ let r = Rect::from_center_size(pos2(x, y), Vec2::new(band, size * 2.0 + 8.0));
let style = bx(
k,
r,
@@ -616,8 +649,8 @@ fn text_at(k: f32, x: f32, y: f32, band: f32, segs: Vec<Seg>, size: f32, colour:
}
/// A person's disc, `d` across, centred on `c`: their coloured initial.
-fn avatar(k: f32, c: egui::Pos2, name: &str, d: f32) -> View {
- let r = Rect::from_center_size(c, egui::Vec2::splat(d));
+fn avatar(k: f32, c: Vec2, name: &str, d: f32) -> View {
+ let r = Rect::from_center_size(c, Vec2::splat(d));
let style = bx(
k,
r,
@@ -691,7 +724,7 @@ fn call_button(
acts: &Acts,
k: f32,
pal: &Palette,
- c: egui::Pos2,
+ c: Vec2,
d: f32,
glyph: &'static str,
tip: &str,
@@ -720,7 +753,7 @@ fn call_button(
}
}
};
- let r = Rect::from_center_size(c, egui::Vec2::splat(d - 2.0));
+ let r = Rect::from_center_size(c, Vec2::splat(d - 2.0));
let style = bx(
k,
r,
@@ -786,7 +819,7 @@ fn encrypted_line(k: f32, x: f32, y: f32, band: f32, agent: bool) -> View {
/// The fold-down arrow in the top-left corner.
fn fold_button(acts: &Acts, k: f32) -> View {
let d = 40.0;
- let r = Rect::from_min_size(pos2(EDGE, EDGE), egui::Vec2::splat(d));
+ let r = Rect::from_min_size(pos2(EDGE, EDGE), Vec2::splat(d));
let style = bx(
k,
r,
@@ -865,7 +898,7 @@ fn screen_view(l: &ScreenLive) -> View {
}
/// Where the incoming screen's disc stands, and how wide it is.
-fn incoming_disc(w: f32, h: f32) -> (egui::Pos2, f32) {
+fn incoming_disc(w: f32, h: f32) -> (Vec2, f32) {
let disc = (w.min(h) * 0.34).clamp(96.0, 150.0);
(pos2(w * 0.5, h * 0.30), disc)
}
@@ -982,7 +1015,7 @@ fn incoming(
fn waiting(l: &ScreenLive, title: &str, own: Option<f32>, agent: bool, w: f32, h: f32) -> View {
let k = l.k;
let pal = &theme::DARK;
- let full = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(w, h));
+ let full = Rect::from_min_size(Vec2::ZERO, Vec2::new(w, h));
let x = w * 0.5;
let band = w - 2.0 * EDGE;
let mut out = Vec::new();
@@ -993,7 +1026,7 @@ fn waiting(l: &ScreenLive, title: &str, own: Option<f32>, agent: bool, w: f32, h
let y = h * 0.38;
// The spinner: a faint ring with the gold arc turning on it.
let r = 18.0;
- let spin = Rect::from_center_size(pos2(x, y), egui::Vec2::splat(2.0 * r + 3.0));
+ let spin = Rect::from_center_size(pos2(x, y), Vec2::splat(2.0 * r + 3.0));
let spin_style = bx(
k,
spin,
@@ -1137,14 +1170,14 @@ fn grid(
let cols = cols.clamp(1, n);
let rows = n.div_ceil(cols);
let gap = 8.0;
- let cell = egui::vec2(
+ let cell = Vec2::new(
(area.width() - gap * (cols - 1) as f32) / cols as f32,
(area.height() - gap * (rows - 1) as f32) / rows as f32,
);
for (i, person) in tiles.iter().enumerate() {
let (r, c) = (i / cols, i % cols);
let rect = Rect::from_min_size(
- area.min + egui::vec2(c as f32 * (cell.x + gap), r as f32 * (cell.y + gap)),
+ area.min + Vec2::new(c as f32 * (cell.x + gap), r as f32 * (cell.y + gap)),
cell,
);
grid_tile(out, k, pal, rect, person);
@@ -1156,7 +1189,7 @@ fn grid(
fn in_call(l: &ScreenLive, v: &InCallView, w: f32, h: f32) -> View {
let k = l.k;
let pal = &theme::DARK;
- let full = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(w, h));
+ let full = Rect::from_min_size(Vec2::ZERO, Vec2::new(w, h));
let x = w * 0.5;
let mut out: Vec<View> = Vec::new();
@@ -1176,12 +1209,12 @@ fn in_call(l: &ScreenLive, v: &InCallView, w: f32, h: f32) -> View {
tiles.push(&v.me);
let (screen_rect, strip) = if portrait {
let sh = (stage.width() / aspect.max(0.1)).min(stage.height() * 0.55);
- let screen_rect = Rect::from_min_size(stage.min, egui::vec2(stage.width(), sh));
+ let screen_rect = Rect::from_min_size(stage.min, Vec2::new(stage.width(), sh));
let strip = Rect::from_min_max(pos2(stage.min.x, screen_rect.max.y + 8.0), stage.max);
(screen_rect, strip)
} else {
let sw = (stage.width() * 0.78).min(stage.width() - 160.0);
- let screen_rect = Rect::from_min_size(stage.min, egui::vec2(sw, stage.height()));
+ let screen_rect = Rect::from_min_size(stage.min, Vec2::new(sw, stage.height()));
let strip = Rect::from_min_max(pos2(screen_rect.max.x + 8.0, stage.min.y), stage.max);
(screen_rect, strip)
};
@@ -1309,7 +1342,7 @@ fn in_call(l: &ScreenLive, v: &InCallView, w: f32, h: f32) -> View {
let ph = (pw / a.max(0.1)).min(h * 0.32);
let pw = ph * a;
let top = if v.controls { 76.0 } else { EDGE };
- let rect = Rect::from_min_size(pos2(w - EDGE - pw, top), egui::vec2(pw, ph));
+ let rect = Rect::from_min_size(pos2(w - EDGE - pw, top), Vec2::new(pw, ph));
out.push(plate(k, rect.expand(1.0), 13.0, &black(47.0)));
out.push(picture(k, &tile_name(SELF_TILE), a, rect, 12.0, true));
let rim = bx(
@@ -1324,7 +1357,7 @@ fn in_call(l: &ScreenLive, v: &InCallView, w: f32, h: f32) -> View {
out.push(view! { <div style={rim}></div> });
if v.me.muted {
let b = pos2(rect.min.x + 16.0, rect.max.y - 16.0);
- let r = Rect::from_center_size(b, egui::Vec2::splat(24.0));
+ let r = Rect::from_center_size(b, Vec2::splat(24.0));
let style = bx(
k,
r,
@@ -1357,7 +1390,7 @@ fn in_call(l: &ScreenLive, v: &InCallView, w: f32, h: f32) -> View {
if v.any_picture {
out.push(shade(
k,
- Rect::from_min_size(full.min, egui::vec2(w, 120.0)),
+ Rect::from_min_size(full.min, Vec2::new(w, 120.0)),
true,
));
out.push(shade(
@@ -1441,7 +1474,7 @@ fn people_button(l: &ScreenLive, v: &InCallView, w: f32) -> View {
let pal = &theme::DARK;
let d = 40.0;
let c = pos2(w - EDGE - d * 0.5, EDGE + d * 0.5);
- let r = Rect::from_center_size(c, egui::Vec2::splat(d));
+ let r = Rect::from_center_size(c, Vec2::splat(d));
let style = bx(
k,
r,
@@ -1462,7 +1495,7 @@ fn people_button(l: &ScreenLive, v: &InCallView, w: f32) -> View {
};
// `c + (0.38 d, −0.36 d)` in the button's own frame.
let b = pos2(d * 0.5 + d * 0.38, d * 0.5 - d * 0.36);
- let br = Rect::from_center_size(b, egui::Vec2::splat(18.0));
+ let br = Rect::from_center_size(b, Vec2::splat(18.0));
let style = bx(
k,
br,
@@ -1507,7 +1540,7 @@ fn dock(out: &mut Vec<View>, l: &ScreenLive, v: &InCallView, w: f32, h: f32) {
let mut cx = x - (n - 1.0) * step * 0.5;
let tray = Rect::from_center_size(
pos2(x, y + LABEL_GAP * 0.5),
- egui::vec2((n - 1.0) * step + d + 24.0, d + 20.0 + LABEL_GAP),
+ Vec2::new((n - 1.0) * step + d + 24.0, d + 20.0 + LABEL_GAP),
);
out.push(plate(k, tray, tray.height() * 0.5, &black(51.0)));
let label = |cx: f32, word: &str| {
@@ -1603,7 +1636,7 @@ fn meeting_chips(out: &mut Vec<View>, l: &ScreenLive, v: &InCallView, w: f32) {
let mut y = EDGE + 60.0;
// A band the window's width, centred on `y`, its content centred in it.
let band = |y: f32, child: View| -> View {
- let r = Rect::from_center_size(pos2(w * 0.5, y), egui::vec2(w, 32.0));
+ let r = Rect::from_center_size(pos2(w * 0.5, y), Vec2::new(w, 32.0));
let style = bx(
k,
r,
@@ -2588,7 +2621,7 @@ fn folded_tiles(
);
let mut tiles: Vec<View> = Vec::new();
for (i, person) in people.iter().enumerate() {
- let tile = Rect::from_min_size(pos2(i as f32 * (tw + gap), 0.0), egui::vec2(tw, th));
+ let tile = Rect::from_min_size(pos2(i as f32 * (tw + gap), 0.0), Vec2::new(tw, th));
// The card's shadow under each tile, as egui's `card_shadow`.
let lift = bx(
k,
@@ -2604,7 +2637,7 @@ fn folded_tiles(
// The tiles take the tap that unfolds: a box over them, listening.
let over = bx(
k,
- Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, th)),
+ Rect::from_min_size(Vec2::ZERO, Vec2::new(width, th)),
"cursor: pointer",
);
let unfold = on(&l.acts, vec![CallAct::Unfold]);
@@ -2747,7 +2780,7 @@ mod tests {
#[test]
fn a_letterboxed_picture_keeps_its_shape() {
- let rect = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 900.0));
+ let rect = Rect::from_min_size(Vec2::ZERO, Vec2::new(1600.0, 900.0));
let r = contain(0.75, rect);
assert!((r.height() - 900.0).abs() < 1e-3);
assert!((r.width() / r.height() - 0.75).abs() < 1e-4);
diff --git a/crates/cartopolis/src/systems/gui/lib_host.rs b/crates/cartopolis/src/systems/gui/lib_host.rs
index db798926..56d62115 100644
--- a/crates/cartopolis/src/systems/gui/lib_host.rs
+++ b/crates/cartopolis/src/systems/gui/lib_host.rs
@@ -129,10 +129,10 @@ pub fn prepare_bevy(
ui_scale.0 = metrics.ui_scale();
let body = fonts.add(bevy::prelude::Font::from_bytes(theme::BODY_TTF.to_vec()));
// A camera of the library's own, drawing nothing but the library and
- // after the world's camera has finished — egui included, which draws
- // after the upscale, past where `bevy_ui`'s pass sits. On the world's
- // camera every egui button lay over the library's cards. It draws to
- // the world camera's target (`follow_world_target`).
+ // after the world's camera has finished, past the upscale — so the
+ // interface stays at full resolution while the world scales
+ // (`render_scale`). It draws to the world camera's target
+ // (`follow_world_target`).
//
// Unlike the world's (HDR, its own MSAA) it has a texture of its own,
// laid over the target after: so it clears that texture to transparent
@@ -144,7 +144,8 @@ pub fn prepare_bevy(
.spawn((
bevy::prelude::Camera2d,
bevy::prelude::Camera {
- order: 100,
+ // Above it, `render_scale` leaves a camera at full resolution.
+ order: crate::systems::render_scale::INTERFACE_CAMERA_ORDER,
clear_color: bevy::camera::ClearColorConfig::Custom(bevy::prelude::Color::NONE),
output_mode: bevy::camera::CameraOutputMode::Write {
blend_state: Some(
@@ -161,17 +162,12 @@ pub fn prepare_bevy(
.id();
commands.insert_resource(mithril_bevy::UiCamera(overlay));
commands.insert_resource(mithril_bevy::FontMap {
- regular: body.clone(),
+ regular: body,
semibold: fonts.add(bevy::prelude::Font::from_bytes(theme::BRAND_TTF.to_vec())),
- // egui's own monospace (Hack, in its default fonts), which egui's
- // code fields set; the body face before, so code was not monospace.
- mono: egui::FontDefinitions::default()
- .font_data
- .get("Hack")
- .map(|d| fonts.add(bevy::prelude::Font::from_bytes(d.font.to_vec())))
- .unwrap_or(body),
+ mono: fonts.add(bevy::prelude::Font::from_bytes(theme::MONO_TTF.to_vec())),
icons: Some(fonts.add(bevy::prelude::Font::from_bytes(icons::FONT.to_vec()))),
icon_scale: theme::ICON_SCALE,
+ emoji: Some(fonts.add(bevy::prelude::Font::from_bytes(theme::EMOJI_TTF.to_vec()))),
});
*ready = true;
}
@@ -220,13 +216,12 @@ pub fn follow_world_target(
*lib = world.clone();
}
-/// The library's screens hold the input they are under, as egui's panels
-/// do: a world click under any of them yields (`UiInput::owns_click`), and
-/// a text field with the keyboard holds the game keys off
-/// (`UiInput::ui_owns_keyboard`). Written into `UiInput` for the next frame;
-/// `egui_manager::publish_ui_input` hands it on to the egui systems that
-/// still ask `EguiManager`. As DOM the screens sit over the canvas, whose
-/// pointer and keyboard Bevy reads, so only the Bevy backend needs telling.
+/// The library's screens hold the input they are under: a world click under
+/// any of them yields (`UiInput::owns_click`), and a text field with the
+/// keyboard holds the game keys off (`UiInput::ui_owns_keyboard`). Written
+/// into `UiInput` for the next frame. As DOM the screens sit over the
+/// canvas, whose pointer and keyboard Bevy reads, so only the Bevy backend
+/// needs telling.
#[cfg(feature = "ui-probe")]
pub fn bridge_input(
focus: Option<bevy::prelude::Res<bevy::input_focus::InputFocus>>,
diff --git a/crates/cartopolis/src/systems/gui/mod.rs b/crates/cartopolis/src/systems/gui/mod.rs
index 8f0f881d..32fa124d 100644
--- a/crates/cartopolis/src/systems/gui/mod.rs
+++ b/crates/cartopolis/src/systems/gui/mod.rs
@@ -41,7 +41,6 @@ pub mod design_room;
pub mod discs;
pub mod dismiss;
pub mod dock;
-pub mod egui_manager;
#[cfg(feature = "comms")]
pub mod external_signin;
pub mod facade_check;
diff --git a/crates/cartopolis/src/systems/gui/motion.rs b/crates/cartopolis/src/systems/gui/motion.rs
index 5d252f84..b5d61a91 100644
--- a/crates/cartopolis/src/systems/gui/motion.rs
+++ b/crates/cartopolis/src/systems/gui/motion.rs
@@ -20,7 +20,9 @@
use std::sync::atomic::{AtomicBool, Ordering};
/// A state change: colour and rim of on/off, hover, a tab, a label appearing,
-/// the crossfade between the two spaces. Also egui's `Style::animation_time`.
+/// the crossfade between the two spaces. Was egui's `Style::animation_time`;
+/// kept as the vocabulary's, like [`ENTER`]'s readers.
+#[allow(dead_code)]
pub const STATE: f32 = 0.2;
/// A surface arriving: a card, a page, a cover, the keyboard.
pub const ENTER: f32 = 0.36;
diff --git a/crates/cartopolis/src/systems/gui/plugin.rs b/crates/cartopolis/src/systems/gui/plugin.rs
index 301d195a..bfcc8828 100644
--- a/crates/cartopolis/src/systems/gui/plugin.rs
+++ b/crates/cartopolis/src/systems/gui/plugin.rs
@@ -166,9 +166,6 @@ impl Plugin for GuiPlugin {
systems::ui_theme::follow_the_light,
// And how much it moves (`systems::motion`), for the same reason.
systems::motion::apply_pref,
- // egui's own style follows it, for what egui still draws.
- systems::egui_manager::follow_theme_visuals
- .after(systems::ui_theme::follow_the_light),
)
.in_set(ClientPhase::Input),
);
@@ -508,31 +505,15 @@ impl Plugin for GuiPlugin {
.in_set(ClientPhase::Input),
);
- // The right-hand panel chain — ONE ordered declaration.
+ // The panel drivers' chain — ONE ordered declaration.
//
- // Every system here draws into the *same* shared root `Ui`, so their call
- // order fixes their right-to-left placement, and every one of them takes
- // `crate::systems::egui_manager::EguiMut`, so Bevy already runs them one at a time
- // regardless. The only thing ordering decides is *which* order — and where
- // two are unconstrained, Bevy is free to pick differently from frame to
- // frame.
- //
- // That is not a visual swap. The panels share the single `Background`
- // layer, so a panel that lands over another on some frames wins egui's hit
- // test on those frames, while `layer_id_at` still answers `Background`
- // because the contest is *within* a layer. The symptom is a checkbox that
- // ignores about half the clicks aimed at it, invisible to every
- // layer-level diagnostic and impossible to reproduce in a single-panel
- // test. `chat` and `appearance` were the two left unlinked once (fixed
- // 2026-07-31).
- //
- // This used to be ~12 `.after()` links scattered over seven places in two
- // `add_systems` calls, with the intended chain recorded only in a comment.
- // `.chain()` makes the order structural: a panel added to this tuple is
- // ordered by construction, and one added anywhere else is visibly not in
- // the chain.
- // Since these systems cannot run concurrently anyway, the total order
- // costs no parallelism.
+ // These once drew into egui's shared root `Ui`, where the call order
+ // decided both placement and who won a click. The library draws them
+ // now, but the drivers still hand state to each other within a frame
+ // (the face sheet opens sign-in, the dock writes `MapChrome::holes`
+ // the overlays read), so the order stays structural: a driver added
+ // to this tuple is ordered by construction, and one added anywhere
+ // else is visibly not in the chain.
//
// **Two halves, one order.** The head runs in `ClientPhase::Input`: the
// main menu opens the sign-in screen whose session driver has to land
diff --git a/crates/cartopolis/src/systems/gui/theme/color.rs b/crates/cartopolis/src/systems/gui/theme/color.rs
index e522a3ac..cffa1352 100644
--- a/crates/cartopolis/src/systems/gui/theme/color.rs
+++ b/crates/cartopolis/src/systems/gui/theme/color.rs
@@ -1,18 +1,12 @@
//! The theme's own colour: sRGB bytes with **straight** alpha.
//!
//! Every colour the theme names was an `egui::Color32` until egui-removal
-//! stage S3 (2026-11-26); this is what they are now, so the palette, the
-//! tokens and the component library's screens no longer depend on egui.
+//! stage S3 (2026-11-26); this is what they are now.
//!
-//! **Straight, not premultiplied.** `Color32` stores its channels multiplied
-//! by alpha, so reading a translucent one back (`r()`) does not return the
-//! colour it was made from — the trap `tokens::alpha` used to warn about.
-//! [`Rgba8`] keeps the bytes it was given; the conversion into `Color32`
-//! premultiplies exactly as `Color32::from_rgba_unmultiplied` does, so an
-//! egui painter handed `rgba.into()` paints the bytes it painted before.
-//!
-//! The `Color32` conversions are temporary: they exist for the egui
-//! painters that remain until their family is deleted.
+//! **Straight, not premultiplied.** `Color32` stored its channels multiplied
+//! by alpha, so reading a translucent one back did not return the colour it
+//! was made from — the trap `tokens::alpha` used to warn about. [`Rgba8`]
+//! keeps the bytes it was given.
/// An sRGB colour, a byte per channel, alpha not premultiplied.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
@@ -26,9 +20,6 @@ pub struct Rgba8 {
impl Rgba8 {
pub const WHITE: Self = Self::from_rgb(0xFF, 0xFF, 0xFF);
pub const BLACK: Self = Self::from_rgb(0, 0, 0);
- /// Fully transparent black — what `Color32::TRANSPARENT` is.
- pub const TRANSPARENT: Self = Self::from_rgba_unmultiplied(0, 0, 0, 0);
-
/// An opaque colour.
#[must_use]
pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
@@ -107,101 +98,38 @@ impl Rgba8 {
}
}
-// ─── The egui edge (temporary) ────────────────────────────────────────────────
-
-impl Rgba8 {
- /// As egui's colour, in a `const` (`From` is not): premultiplied as
- /// `Color32::from_rgba_unmultiplied` does, so the bytes are the ones a
- /// `Color32` constant made from the same literal held. For an egui
- /// painter's own `const`; elsewhere `.into()`.
- #[must_use]
- pub const fn to_egui(self) -> egui::Color32 {
- egui::Color32::from_rgba_unmultiplied_const(self.r, self.g, self.b, self.a)
- }
-}
-
-impl From<Rgba8> for egui::Color32 {
- /// [`Rgba8::to_egui`].
- fn from(c: Rgba8) -> Self {
- c.to_egui()
- }
-}
-
-impl From<Rgba8> for egui::Rgba {
- fn from(c: Rgba8) -> Self {
- egui::Color32::from(c).into()
- }
-}
-
-impl From<egui::Color32> for Rgba8 {
- /// Unmultiplies: a translucent `Color32` loses precision in its colour
- /// bytes, which this cannot give back.
- fn from(c: egui::Color32) -> Self {
- let [r, g, b, a] = c.to_srgba_unmultiplied();
- Self { r, g, b, a }
- }
-}
-
#[cfg(test)]
mod tests {
use super::Rgba8;
- use egui::Color32;
-
- #[test]
- fn into_color32_is_from_rgba_unmultiplied() {
- for a in [0u8, 1, 22, 90, 140, 150, 235, 254, 255] {
- for (r, g, b) in [(0x14, 0x1A, 0x1C), (0xFF, 0xFF, 0xFF), (0x0F, 0x14, 0x16)] {
- assert_eq!(
- Color32::from(Rgba8::from_rgba_unmultiplied(r, g, b, a)),
- Color32::from_rgba_unmultiplied(r, g, b, a)
- );
- }
- }
- assert_eq!(Color32::from(Rgba8::WHITE), Color32::WHITE);
- assert_eq!(Color32::from(Rgba8::BLACK), Color32::BLACK);
- assert_eq!(Color32::from(Rgba8::TRANSPARENT), Color32::TRANSPARENT);
- }
+ /// Only the alpha moves, rounded to the nearest step, and a factor out of
+ /// `0..=1` is clamped.
#[test]
- fn from_color32_unmultiplies() {
- let c = Rgba8::from_rgba_unmultiplied(0xFF, 0xFF, 0xFF, 22);
- assert_eq!(Rgba8::from(Color32::from(c)), c);
- assert_eq!(
- Rgba8::from(Color32::from_rgb(1, 2, 3)),
- Rgba8::from_rgb(1, 2, 3)
- );
- }
-
- /// `gamma_multiply` on an opaque colour and `with_alpha_scaled` paint the
- /// same, to one step of rounding per byte.
- #[test]
- fn alpha_scaling_matches_gamma_multiply() {
- for f in [0.0, 0.12, 0.35, 0.5, 0.6, 0.85, 1.0] {
- for c in [
- Rgba8::from_rgb(0x2B, 0x83, 0x7E),
- Rgba8::WHITE,
- Rgba8::from_rgb(0xD6, 0x45, 0x45),
- ] {
- let theirs = Color32::from(c).gamma_multiply(f).to_array();
- let ours = Color32::from(c.with_alpha_scaled(f)).to_array();
- for (t, o) in theirs.iter().zip(ours) {
- assert!(t.abs_diff(o) <= 1, "{c:?} × {f}: {theirs:?} vs {ours:?}");
- }
- assert_eq!(theirs[3], ours[3]);
- }
+ fn alpha_scaling_moves_only_the_alpha() {
+ let c = Rgba8::from_rgb(0x2B, 0x83, 0x7E);
+ for (f, a) in [
+ (0.0, 0u8),
+ (0.12, 31),
+ (0.5, 128),
+ (0.85, 217),
+ (1.0, 255),
+ (2.0, 255),
+ ] {
+ let s = c.with_alpha_scaled(f);
+ assert_eq!(s.to_array(), [0x2B, 0x83, 0x7E, a], "× {f}");
}
+ assert_eq!(Rgba8::WHITE.with_alpha(22).a(), 22);
}
+ /// Per byte in sRGB, ends included.
#[test]
- fn lerp_of_opaque_colours_is_lerp_to_gamma() {
+ fn lerp_runs_per_byte_from_one_end_to_the_other() {
let a = Rgba8::from_rgb(0x0F, 0x14, 0x16);
let b = Rgba8::from_rgb(0xF4, 0xF8, 0xF8);
- for t in [0.0, 0.25, 0.5, 0.9, 1.0] {
- assert_eq!(
- Color32::from(a.lerp(b, t)),
- Color32::from(a).lerp_to_gamma(Color32::from(b), t)
- );
- }
+ assert_eq!(a.lerp(b, 0.0), a);
+ assert_eq!(a.lerp(b, 1.0), b);
+ assert_eq!(a.lerp(b, 0.5).to_array(), [0x82, 0x86, 0x87, 0xFF]);
+ assert_eq!(a.lerp(b, -1.0), a, "clamped");
}
#[test]
diff --git a/crates/cartopolis/src/systems/gui/theme/frames.rs b/crates/cartopolis/src/systems/gui/theme/frames.rs
index 60511153..6b842844 100644
--- a/crates/cartopolis/src/systems/gui/theme/frames.rs
+++ b/crates/cartopolis/src/systems/gui/theme/frames.rs
@@ -5,7 +5,7 @@ use super::*;
/// Padding inside a label chip over the map ([`LABEL_CHIP`] behind a few
/// words, [`RADIUS_SM`] round): the driver's chip and the lens's marks
/// (`lib_driver`, `lib_scenario_map`) use the same two numbers.
-pub const CHIP_PADDING: egui::Vec2 = egui::vec2(6.0, 3.0);
+pub const CHIP_PADDING: bevy::math::Vec2 = bevy::math::Vec2::new(6.0, 3.0);
/// Height of a primary button on a pointer. Under a finger it grows to
/// [`row_height`], which is larger.
diff --git a/crates/cartopolis/src/systems/gui/theme/golden.rs b/crates/cartopolis/src/systems/gui/theme/golden.rs
index a2d681db..8e0e349e 100644
--- a/crates/cartopolis/src/systems/gui/theme/golden.rs
+++ b/crates/cartopolis/src/systems/gui/theme/golden.rs
@@ -1,13 +1,11 @@
-//! Every colour the theme names, as egui draws it, pinned in
-//! `golden_colours.txt`.
+//! Every colour the theme names, pinned in `golden_colours.txt`.
//!
//! Written before the theme moved off `egui::Color32` onto its own
//! [`Rgba8`](super::Rgba8) (egui-removal stage S3, 2026-11-26), so the move
-//! could be shown to change no visible colour: each line is a value's bytes
-//! *as egui gets them* — premultiplied, which is what is painted — and the
-//! straight (unmultiplied) bytes read back from that. A table that still
-//! matches after an edit to `palette.rs` or `tokens.rs` changed nothing on
-//! screen; one that does not names the value that moved.
+//! could be shown to change no visible colour. With egui gone each line is a
+//! value's straight (unmultiplied) bytes. A table that still matches after an
+//! edit to `palette.rs` or `tokens.rs` changed nothing on screen; one that
+//! does not names the value that moved.
//!
//! ```text
//! CARTO_WRITE_THEME_GOLDEN=1 cargo test -p cartopolis theme::golden
@@ -17,22 +15,14 @@
use std::fmt::Write as _;
-use egui::Color32;
-
use super::tokens::{self, WEB};
-use super::{brand, scenario, Palette, DARK, LIGHT};
+use super::{brand, scenario, Palette, Rgba8, DARK, LIGHT};
const FILE: &str = "src/systems/gui/theme/golden_colours.txt";
-fn line(out: &mut String, name: &str, c: impl Into<Color32>) {
- let c: Color32 = c.into();
+fn line(out: &mut String, name: &str, c: Rgba8) {
let [r, g, b, a] = c.to_array();
- let [ur, ug, ub, ua] = c.to_srgba_unmultiplied();
- writeln!(
- out,
- "{name:<32} premul {r:02x}{g:02x}{b:02x}{a:02x} straight {ur:02x}{ug:02x}{ub:02x}{ua:02x}"
- )
- .unwrap();
+ writeln!(out, "{name:<32} straight {r:02x}{g:02x}{b:02x}{a:02x}").unwrap();
}
fn palette(out: &mut String, name: &str, p: &Palette) {
diff --git a/crates/cartopolis/src/systems/gui/theme/golden_colours.txt b/crates/cartopolis/src/systems/gui/theme/golden_colours.txt
index 42c82cfd..764da7e0 100644
--- a/crates/cartopolis/src/systems/gui/theme/golden_colours.txt
+++ b/crates/cartopolis/src/systems/gui/theme/golden_colours.txt
@@ -1,175 +1,175 @@
-DARK.ink premul 0f1416ff straight 0f1416ff
-DARK.on_accent premul ffffffff straight ffffffff
-DARK.on_status premul 0f1416ff straight 0f1416ff
-DARK.surface premul 141a1cff straight 141a1cff
-DARK.surface_raised premul 1f2829ff straight 1f2829ff
-DARK.surface_hover premul 2a3536ff straight 2a3536ff
-DARK.line premul 63797cff straight 63797cff
-DARK.accent premul 2b837eff straight 2b837eff
-DARK.accent_bright premul ffffffff straight ffffffff
-DARK.accent_lift premul 277a75ff straight 277a75ff
-DARK.accent_ring premul 24706cff straight 24706cff
-DARK.accent_pressed premul 24706cff straight 24706cff
-DARK.accent_text premul ffffffff straight ffffffff
-DARK.accent_word premul a8dcd8ff straight a8dcd8ff
-DARK.accent_muted premul 263f42ff straight 263f42ff
-DARK.cream premul f4f8f8ff straight f4f8f8ff
-DARK.text premul e2e9eaff straight e2e9eaff
-DARK.text_dim premul aac2c6ff straight aac2c6ff
-DARK.warn premul d8c07aff straight d8c07aff
-DARK.error premul f2a296ff straight f2a296ff
-DARK.overlay premul 172324ff straight 172324ff
-DARK.glass premul 172324ff straight 172324ff
-DARK.panel premul 172324ff straight 172324ff
-DARK.card premul 161f21ff straight 161f21ff
-DARK.panel_rim premul 2a3536ff straight 2a3536ff
-DARK.overlay_line premul 2a3536ff straight 2a3536ff
-DARK.overlay_soft premul 0b0e0f8c straight 141a1b8c
-DARK.list_line premul 16161616 straight ffffff16
-DARK.tile_on premul 263f42ff straight 263f42ff
-DARK.knob_on premul e2e9eaff straight e2e9eaff
-DARK.gold premul d8c07aff straight d8c07aff
-DARK.on_gold premul 1f2829ff straight 1f2829ff
-DARK.control_edge premul 3a4849ff straight 3a4849ff
-DARK.map_fill premul 172324ff straight 172324ff
-DARK.map_ink premul e2e9eaff straight e2e9eaff
-DARK.map_rim premul 2a3536ff straight 2a3536ff
-DARK.map_mark premul f4f8f8ff straight f4f8f8ff
+DARK.ink straight 0f1416ff
+DARK.on_accent straight ffffffff
+DARK.on_status straight 0f1416ff
+DARK.surface straight 141a1cff
+DARK.surface_raised straight 1f2829ff
+DARK.surface_hover straight 2a3536ff
+DARK.line straight 63797cff
+DARK.accent straight 2b837eff
+DARK.accent_bright straight ffffffff
+DARK.accent_lift straight 277a75ff
+DARK.accent_ring straight 24706cff
+DARK.accent_pressed straight 24706cff
+DARK.accent_text straight ffffffff
+DARK.accent_word straight a8dcd8ff
+DARK.accent_muted straight 263f42ff
+DARK.cream straight f4f8f8ff
+DARK.text straight e2e9eaff
+DARK.text_dim straight aac2c6ff
+DARK.warn straight d8c07aff
+DARK.error straight f2a296ff
+DARK.overlay straight 172324ff
+DARK.glass straight 172324ff
+DARK.panel straight 172324ff
+DARK.card straight 161f21ff
+DARK.panel_rim straight 2a3536ff
+DARK.overlay_line straight 2a3536ff
+DARK.overlay_soft straight 141a1c8c
+DARK.list_line straight ffffff16
+DARK.tile_on straight 263f42ff
+DARK.knob_on straight e2e9eaff
+DARK.gold straight d8c07aff
+DARK.on_gold straight 1f2829ff
+DARK.control_edge straight 3a4849ff
+DARK.map_fill straight 172324ff
+DARK.map_ink straight e2e9eaff
+DARK.map_rim straight 2a3536ff
+DARK.map_mark straight f4f8f8ff
DARK.shadow 1 dark true
-LIGHT.ink premul e7ededff straight e7ededff
-LIGHT.on_accent premul ffffffff straight ffffffff
-LIGHT.on_status premul ffffffff straight ffffffff
-LIGHT.surface premul ffffffff straight ffffffff
-LIGHT.surface_raised premul f8fafaff straight f8fafaff
-LIGHT.surface_hover premul e7ededff straight e7ededff
-LIGHT.line premul 788b8eff straight 788b8eff
-LIGHT.accent premul 2b837eff straight 2b837eff
-LIGHT.accent_bright premul 17696aff straight 17696aff
-LIGHT.accent_lift premul 277a75ff straight 277a75ff
-LIGHT.accent_ring premul 24706cff straight 24706cff
-LIGHT.accent_pressed premul 24706cff straight 24706cff
-LIGHT.accent_text premul 17696aff straight 17696aff
-LIGHT.accent_word premul 17696aff straight 17696aff
-LIGHT.accent_muted premul d9f0eeff straight d9f0eeff
-LIGHT.cream premul 0f1416ff straight 0f1416ff
-LIGHT.text premul 1f2829ff straight 1f2829ff
-LIGHT.text_dim premul 546568ff straight 546568ff
-LIGHT.warn premul 855700ff straight 855700ff
-LIGHT.error premul b3361eff straight b3361eff
-LIGHT.overlay premul f1f5f5ff straight f1f5f5ff
-LIGHT.glass premul f1f5f5ff straight f1f5f5ff
-LIGHT.panel premul f1f5f5ff straight f1f5f5ff
-LIGHT.card premul ffffffff straight ffffffff
-LIGHT.panel_rim premul dae3e3ff straight dae3e3ff
-LIGHT.overlay_line premul dae3e3ff straight dae3e3ff
-LIGHT.overlay_soft premul 96969696 straight ffffff96
-LIGHT.list_line premul 01020216 straight 0c171716
-LIGHT.tile_on premul ffffffff straight ffffffff
-LIGHT.knob_on premul ffffffff straight ffffffff
-LIGHT.gold premul e0bc5cff straight e0bc5cff
-LIGHT.on_gold premul 1f2829ff straight 1f2829ff
-LIGHT.control_edge premul c9d4d5ff straight c9d4d5ff
-LIGHT.map_fill premul ffffffff straight ffffffff
-LIGHT.map_ink premul 17696aff straight 17696aff
-LIGHT.map_rim premul 9fd1cdff straight 9fd1cdff
-LIGHT.map_mark premul 2b837eff straight 2b837eff
+LIGHT.ink straight e7ededff
+LIGHT.on_accent straight ffffffff
+LIGHT.on_status straight ffffffff
+LIGHT.surface straight ffffffff
+LIGHT.surface_raised straight f8fafaff
+LIGHT.surface_hover straight e7ededff
+LIGHT.line straight 788b8eff
+LIGHT.accent straight 2b837eff
+LIGHT.accent_bright straight 17696aff
+LIGHT.accent_lift straight 277a75ff
+LIGHT.accent_ring straight 24706cff
+LIGHT.accent_pressed straight 24706cff
+LIGHT.accent_text straight 17696aff
+LIGHT.accent_word straight 17696aff
+LIGHT.accent_muted straight d9f0eeff
+LIGHT.cream straight 0f1416ff
+LIGHT.text straight 1f2829ff
+LIGHT.text_dim straight 546568ff
+LIGHT.warn straight 855700ff
+LIGHT.error straight b3361eff
+LIGHT.overlay straight f1f5f5ff
+LIGHT.glass straight f1f5f5ff
+LIGHT.panel straight f1f5f5ff
+LIGHT.card straight ffffffff
+LIGHT.panel_rim straight dae3e3ff
+LIGHT.overlay_line straight dae3e3ff
+LIGHT.overlay_soft straight ffffff96
+LIGHT.list_line straight 0f141616
+LIGHT.tile_on straight ffffffff
+LIGHT.knob_on straight ffffffff
+LIGHT.gold straight e0bc5cff
+LIGHT.on_gold straight 1f2829ff
+LIGHT.control_edge straight c9d4d5ff
+LIGHT.map_fill straight ffffffff
+LIGHT.map_ink straight 17696aff
+LIGHT.map_rim straight 9fd1cdff
+LIGHT.map_mark straight 2b837eff
LIGHT.shadow 0.6 dark false
-WEB.ink premul 0f1416ff straight 0f1416ff
-WEB.on_accent premul 0f1416ff straight 0f1416ff
-WEB.on_status premul 0f1416ff straight 0f1416ff
-WEB.surface premul 141a1cff straight 141a1cff
-WEB.surface_raised premul 1f2829ff straight 1f2829ff
-WEB.surface_hover premul 2a3536ff straight 2a3536ff
-WEB.line premul 63797cff straight 63797cff
-WEB.accent premul 5cc6c0ff straight 5cc6c0ff
-WEB.accent_bright premul ffffffff straight ffffffff
-WEB.accent_lift premul ffffffff straight ffffffff
-WEB.accent_ring premul a8dcd8ff straight a8dcd8ff
-WEB.accent_pressed premul 3fa9a2ff straight 3fa9a2ff
-WEB.accent_text premul ffffffff straight ffffffff
-WEB.accent_word premul a8dcd8ff straight a8dcd8ff
-WEB.accent_muted premul 263f42ff straight 263f42ff
-WEB.cream premul f4f8f8ff straight f4f8f8ff
-WEB.text premul e2e9eaff straight e2e9eaff
-WEB.text_dim premul aac2c6ff straight aac2c6ff
-WEB.warn premul d8c07aff straight d8c07aff
-WEB.error premul f2a296ff straight f2a296ff
-WEB.overlay premul 172324ff straight 172324ff
-WEB.glass premul 172324ff straight 172324ff
-WEB.panel premul 172324ff straight 172324ff
-WEB.card premul 161f21ff straight 161f21ff
-WEB.panel_rim premul 2a3536ff straight 2a3536ff
-WEB.overlay_line premul 2a3536ff straight 2a3536ff
-WEB.overlay_soft premul 0b0e0f8c straight 141a1b8c
-WEB.list_line premul 16161616 straight ffffff16
-WEB.tile_on premul 263f42ff straight 263f42ff
-WEB.knob_on premul e2e9eaff straight e2e9eaff
-WEB.gold premul d8c07aff straight d8c07aff
-WEB.on_gold premul 1f2829ff straight 1f2829ff
-WEB.control_edge premul 3a4849ff straight 3a4849ff
-WEB.map_fill premul 172324ff straight 172324ff
-WEB.map_ink premul e2e9eaff straight e2e9eaff
-WEB.map_rim premul 2a3536ff straight 2a3536ff
-WEB.map_mark premul f4f8f8ff straight f4f8f8ff
+WEB.ink straight 0f1416ff
+WEB.on_accent straight 0f1416ff
+WEB.on_status straight 0f1416ff
+WEB.surface straight 141a1cff
+WEB.surface_raised straight 1f2829ff
+WEB.surface_hover straight 2a3536ff
+WEB.line straight 63797cff
+WEB.accent straight 5cc6c0ff
+WEB.accent_bright straight ffffffff
+WEB.accent_lift straight ffffffff
+WEB.accent_ring straight a8dcd8ff
+WEB.accent_pressed straight 3fa9a2ff
+WEB.accent_text straight ffffffff
+WEB.accent_word straight a8dcd8ff
+WEB.accent_muted straight 263f42ff
+WEB.cream straight f4f8f8ff
+WEB.text straight e2e9eaff
+WEB.text_dim straight aac2c6ff
+WEB.warn straight d8c07aff
+WEB.error straight f2a296ff
+WEB.overlay straight 172324ff
+WEB.glass straight 172324ff
+WEB.panel straight 172324ff
+WEB.card straight 161f21ff
+WEB.panel_rim straight 2a3536ff
+WEB.overlay_line straight 2a3536ff
+WEB.overlay_soft straight 141a1c8c
+WEB.list_line straight ffffff16
+WEB.tile_on straight 263f42ff
+WEB.knob_on straight e2e9eaff
+WEB.gold straight d8c07aff
+WEB.on_gold straight 1f2829ff
+WEB.control_edge straight 3a4849ff
+WEB.map_fill straight 172324ff
+WEB.map_ink straight e2e9eaff
+WEB.map_rim straight 2a3536ff
+WEB.map_mark straight f4f8f8ff
WEB.shadow 1 dark true
-super::BRAND premul fd6012ff straight fd6012ff
-super::REAL_LOCATION premul 4fb2ffff straight 4fb2ffff
-super::PUBLIC premul b39dffff straight b39dffff
-super::COUNCIL premul 2f4a7aff straight 2f4a7aff
-super::COUNCIL_LIGHT premul 9db7e6ff straight 9db7e6ff
-super::LABEL_CHIP premul 0e1214eb straight 0f1416eb
-super::LABEL_HALO premul 101113be straight 15171abe
-super::LABEL_INK premul f6f3ecff straight f6f3ecff
-super::CALL_END_RED premul d64545ff straight d64545ff
-super::CALL_ACCEPT_GREEN premul 2ea05aff straight 2ea05aff
-super::WORDMARK_TAIL_COLOR premul fd6012ff straight fd6012ff
-brand::mark::PLATE premul 25353fff straight 25353fff
-brand::mark::STREET premul 8c9295ff straight 8c9295ff
-brand::mark::WATER premul 626d72ff straight 626d72ff
-scenario::LIVE premul d63a2fff straight d63a2fff
-scenario::REPLAY premul 4caf6eff straight 4caf6eff
-scenario::EXERCISE premul e8c547ff straight e8c547ff
-scenario::SANDBOX premul 9b7bffff straight 9b7bffff
-scenario::TRACK premul ffcf9aff straight ffcf9aff
-scenario::TRACK_GLOW premul 281c1328 straight ffb37928
-scenario::CONE premul 22100a22 straight ff784b22
-scenario::CONE_EDGE premul 5a36255a straight ff99695a
-scenario::AREA_EDGE premul 0b0e0f96 straight 13181a96
-scenario::AREA_HALO premul 0a0d0faa straight 0f1417aa
-scenario::HEAD premul 5a25145a straight ff69395a
-scenario::HEAD_DOT premul fff1c9ff straight fff1c9ff
-scenario::HEAD_RIM premul ff8a5aff straight ff8a5aff
-scenario::INTERCEPT premul 9fd3ffff straight 9fd3ffff
-tokens::L_BG premul f1f5f5ff straight f1f5f5ff
-tokens::L_SURFACE premul ffffffff straight ffffffff
-tokens::L_SURFACE_RAISED premul f8fafaff straight f8fafaff
-tokens::L_SURFACE_SUNKEN premul e7ededff straight e7ededff
-tokens::L_TEXT premul 1f2829ff straight 1f2829ff
-tokens::L_TEXT_DIM premul 546568ff straight 546568ff
-tokens::L_TEXT_FAINT premul 84979aff straight 84979aff
-tokens::L_BORDER premul dae3e3ff straight dae3e3ff
-tokens::L_BORDER_STRONG premul 84979aff straight 84979aff
-tokens::L_ACCENT_HOVER premul 3fa9a2ff straight 3fa9a2ff
-tokens::L_ACCENT_TEXT premul 17696aff straight 17696aff
-tokens::L_ACCENT_SOFT premul d9f0eeff straight d9f0eeff
-tokens::L_INFO premul 1f6ab0ff straight 1f6ab0ff
-tokens::D_INFO premul 4fb2ffff straight 4fb2ffff
-tokens::L_INFO_SOFT premul e4f0fbff straight e4f0fbff
-tokens::D_INFO_SOFT premul 152736ff straight 152736ff
-tokens::L_SUCCESS premul 1c7442ff straight 1c7442ff
-tokens::D_SUCCESS premul 7ccf9bff straight 7ccf9bff
-tokens::L_SUCCESS_SOFT premul e3f4e9ff straight e3f4e9ff
-tokens::D_SUCCESS_SOFT premul 152c1eff straight 152c1eff
-tokens::L_WARNING premul 855700ff straight 855700ff
-tokens::D_WARNING premul d8c07aff straight d8c07aff
-tokens::L_WARNING_SOFT premul fbf1daff straight fbf1daff
-tokens::D_WARNING_SOFT premul 302916ff straight 302916ff
-tokens::L_DANGER premul b3361eff straight b3361eff
-tokens::D_DANGER premul f2a296ff straight f2a296ff
-tokens::L_DANGER_SOFT premul fce8e4ff straight fce8e4ff
-tokens::D_DANGER_SOFT premul 361d19ff straight 361d19ff
-midas_gold (dark) premul d8c07aff straight d8c07aff
-midas_gold (light) premul 855700ff straight 855700ff
+super::BRAND straight fd6012ff
+super::REAL_LOCATION straight 4fb2ffff
+super::PUBLIC straight b39dffff
+super::COUNCIL straight 2f4a7aff
+super::COUNCIL_LIGHT straight 9db7e6ff
+super::LABEL_CHIP straight 0f1416eb
+super::LABEL_HALO straight 161719be
+super::LABEL_INK straight f6f3ecff
+super::CALL_END_RED straight d64545ff
+super::CALL_ACCEPT_GREEN straight 2ea05aff
+super::WORDMARK_TAIL_COLOR straight fd6012ff
+brand::mark::PLATE straight 25353fff
+brand::mark::STREET straight 8c9295ff
+brand::mark::WATER straight 626d72ff
+scenario::LIVE straight d63a2fff
+scenario::REPLAY straight 4caf6eff
+scenario::EXERCISE straight e8c547ff
+scenario::SANDBOX straight 9b7bffff
+scenario::TRACK straight ffcf9aff
+scenario::TRACK_GLOW straight ffb27a28
+scenario::CONE straight ff7a4a22
+scenario::CONE_EDGE straight ff9a6a5a
+scenario::AREA_EDGE straight 12181a96
+scenario::AREA_HALO straight 0f1416aa
+scenario::HEAD straight ff6a3a5a
+scenario::HEAD_DOT straight fff1c9ff
+scenario::HEAD_RIM straight ff8a5aff
+scenario::INTERCEPT straight 9fd3ffff
+tokens::L_BG straight f1f5f5ff
+tokens::L_SURFACE straight ffffffff
+tokens::L_SURFACE_RAISED straight f8fafaff
+tokens::L_SURFACE_SUNKEN straight e7ededff
+tokens::L_TEXT straight 1f2829ff
+tokens::L_TEXT_DIM straight 546568ff
+tokens::L_TEXT_FAINT straight 84979aff
+tokens::L_BORDER straight dae3e3ff
+tokens::L_BORDER_STRONG straight 84979aff
+tokens::L_ACCENT_HOVER straight 3fa9a2ff
+tokens::L_ACCENT_TEXT straight 17696aff
+tokens::L_ACCENT_SOFT straight d9f0eeff
+tokens::L_INFO straight 1f6ab0ff
+tokens::D_INFO straight 4fb2ffff
+tokens::L_INFO_SOFT straight e4f0fbff
+tokens::D_INFO_SOFT straight 152736ff
+tokens::L_SUCCESS straight 1c7442ff
+tokens::D_SUCCESS straight 7ccf9bff
+tokens::L_SUCCESS_SOFT straight e3f4e9ff
+tokens::D_SUCCESS_SOFT straight 152c1eff
+tokens::L_WARNING straight 855700ff
+tokens::D_WARNING straight d8c07aff
+tokens::L_WARNING_SOFT straight fbf1daff
+tokens::D_WARNING_SOFT straight 302916ff
+tokens::L_DANGER straight b3361eff
+tokens::D_DANGER straight f2a296ff
+tokens::L_DANGER_SOFT straight fce8e4ff
+tokens::D_DANGER_SOFT straight 361d19ff
+midas_gold (dark) straight d8c07aff
+midas_gold (light) straight 855700ff
tokens.accent #5cc6c0 | #5cc6c0
tokens.accent_hover #3fa9a2 | #a8dcd8
tokens.accent_text #17696a | #a8dcd8
diff --git a/crates/cartopolis/src/systems/gui/theme/metrics.rs b/crates/cartopolis/src/systems/gui/theme/metrics.rs
index 2bae26c7..0833f29f 100644
--- a/crates/cartopolis/src/systems/gui/theme/metrics.rs
+++ b/crates/cartopolis/src/systems/gui/theme/metrics.rs
@@ -1,118 +1,46 @@
-use super::*;
-
// ─── Fonts ────────────────────────────────────────────────────────────────────
/// The wordmark face (SIL OFL — see `assets/fonts/README.md`). Embedded rather
/// than loaded as an asset because the splash draws on frame one, before any
/// asset pipeline has run — and on the web that would be an HTTP round trip.
-/// egui reads TTF/OTF, not woff2.
-/// Also the face the street names on the map are rasterised in
-/// (`systems::street_labels`): a semibold reads at the size a road marking gets,
-/// where egui's light body face breaks up.
+/// The library's semibold (headings), and the face the street names on the
+/// map are rasterised in (`systems::street_labels`): a semibold reads at the
+/// size a road marking gets, where a light face breaks up.
pub const BRAND_TTF: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../assets/fonts/PlusJakartaSans-SemiBold.ttf"
));
-pub(super) const BRAND_FAMILY: &str = "cartopolis-brand";
/// The body face: Plus Jakarta Sans **Regular**, the brand face's own family
-/// one weight down, at the front of egui's `Proportional` stack.
-///
-/// **Until 2026-10-04 body text was egui's default, Ubuntu Light**, which is
-/// a fine debugging face and a poor one for this UI: a light weight in light
-/// ink on a dark panel thins out at the 11–12.5 pt the panels are full of,
-/// and next to a Jakarta heading it was a second, unrelated typeface. One
-/// family at two weights is what makes a heading and its rows read as one
-/// voice. Ubuntu stays behind it in the stack for the glyphs Jakarta lacks.
+/// one weight down — one family at two weights is what makes a heading and
+/// its rows read as one voice (the library's `FontMap::regular`).
… (cut)