diff --git a/.config/env.sh b/.config/env.sh index e779d95..94aa17c 100644 --- a/.config/env.sh +++ b/.config/env.sh @@ -11,7 +11,6 @@ fi if [[ -n "$CI" ]]; then export MISE_ENV="ci" - # export RUSTFLAGS="-Clink-arg=-fuse-ld=$(which mold)" elif [[ -n "$SSH_CLIENT" ]]; then export MISE_ENV="ssh" fi diff --git a/.config/mise.toml b/.config/mise.toml index a9f58ff..8a77313 100644 --- a/.config/mise.toml +++ b/.config/mise.toml @@ -10,15 +10,16 @@ sccache="latest" [tools.rust] # keep in sync with bevy_cli -version = "nightly-2025-12-11" +version = "nightly-2026-01-22" components = "rustc-codegen-cranelift-preview,rustc-dev,llvm-tools-preview,clippy" targets = "x86_64-pc-windows-msvc,x86_64-unknown-linux-gnu" [tasks.install_bevy_lint] hide = true run = """ -rustup run nightly-2025-12-11 cargo install \ +rustup run nightly-2026-01-22 cargo install \ --git https://github.com/TheBevyFlock/bevy_cli.git \ + --tag lint-v0.6.0 \ --locked \ bevy_lint || true """ @@ -103,6 +104,7 @@ act -P ubuntu-24.04=ghcr.io/catthehacker/ubuntu:act-24.04 \ --env ACTIONS_RUNTIME_TOKEN=foo \ --env ACTIONS_CACHE_URL=http://artifacts.docker.internal:8080/ \ --artifact-server-path ../artifacts \ + --env RUSTC_WRAPPER=""\ """ [tasks.test] diff --git a/.config/nextest.toml b/.config/nextest.toml index ae874ea..f3d6ec2 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -2,4 +2,4 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # ------------------------------------------ [profile.default] -slow-timeout = { period = "5s", terminate-after = 3 } +slow-timeout = { period = "1s", terminate-after = 3 } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bcf4f82..089f283 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,7 +6,6 @@ on: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - RUST_LOG: app=debug,tfw=debug MISE_ENV: ci jobs: @@ -47,7 +46,7 @@ jobs: - name: Install rust uses: actions-rust-lang/setup-rust-toolchain@v1 with: - toolchain: nightly-2025-12-11 + toolchain: nightly-2026-01-22 components: rustc-codegen-cranelift-preview,rustc-dev,llvm-tools-preview,clippy - uses: cargo-bins/cargo-binstall@main @@ -60,12 +59,3 @@ jobs: - run: "mise clippy" - run: "mise bevy_lint" - run: "mise test" - - - uses: taiki-e/install-action@cargo-llvm-cov - - name: Collect coverage data - run: cargo llvm-cov nextest - - name: Upload coverage reports to Codecov - uses: codecov/codecov-action@v5 - with: - token: ${{ secrets.CODECOV_TOKEN }} - slug: ada-x64/qproj diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml new file mode 100644 index 0000000..1b79be4 --- /dev/null +++ b/.github/workflows/codecov.yml @@ -0,0 +1,74 @@ +name: Generate codecov + +on: + push: + +env: + CARGO_TERM_COLOR: always + RUST_BACKTRACE: 1 + MISE_ENV: ci + RUSTFLAGS: -Zcodegen-backend=llvm + RUSTC_WRAPPER: sccache # disabled locally + +jobs: + generate-coverage: + runs-on: ubuntu-latest + strategy: + matrix: + package: [q_screens, q_cmd_prompt, q_test_harness] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Cache + uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{matrix.package}}-ci-${{ hashFiles('**/Cargo.toml') }} + + - name: Run sccache-cache + uses: mozilla-actions/sccache-action@v0.0.9 + if: ${{contains(env.RUSTC_WRAPPER, 'sccache')}} + + - name: Install dependencies + shell: bash + run: > + sudo apt-get update; + sudo apt-get install -y --no-install-recommends + libasound2-dev + libudev-dev + libwayland-dev + ; + + - name: Install rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + toolchain: nightly-2026-01-22 + components: rustc-dev,llvm-tools-preview + + - uses: taiki-e/install-action@cargo-llvm-cov + - uses: taiki-e/install-action@nextest + - name: Collect coverage data + run: cargo llvm-cov nextest -p ${{ matrix.package }} --lcov --output-path report.lcov + + - name: Upload to coveralls + uses: coverallsapp/github-action@v2.3.6 + with: + parallel: true + flag-name: ${{matrix.package}} + finish: + runs-on: ubuntu-latest + needs: generate-coverage + if: ${{always()}} + steps: + - name: Finish coveralls upload + uses: coverallsapp/github-action@v2 + with: + parallel-finished: true + carryforward: "q_screens,q_cmd_prompt,q_test_harness" # MUST MATCH ALL MATRIX VALUES diff --git a/Cargo.lock b/Cargo.lock index 13da645..23e53d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -246,9 +246,9 @@ dependencies = [ "built", "clap", "itertools 0.14.0", + "q_screens", "serde", "strum", - "tfw", "thiserror 2.0.18", "tiny_bail", "variadics_please", @@ -820,26 +820,6 @@ dependencies = [ "wgpu-types", ] -[[package]] -name = "bevy_command_prompt" -version = "0.1.0" -dependencies = [ - "bevy", - "bevy-inspector-egui", - "bevy_dylib", - "bevy_test_harness", - "clap", - "cosmic-text 0.16.0", - "regex", - "shlex", - "smallvec", - "smol_str", - "strum", - "thiserror 2.0.18", - "tiny_bail", - "variadics_please", -] - [[package]] name = "bevy_core_pipeline" version = "0.18.0" @@ -1789,14 +1769,6 @@ dependencies = [ "pin-project", ] -[[package]] -name = "bevy_test_harness" -version = "0.1.0" -dependencies = [ - "bevy", - "log", -] - [[package]] name = "bevy_text" version = "0.18.0" @@ -2122,9 +2094,9 @@ checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510" [[package]] name = "bytemuck" -version = "1.24.0" +version = "1.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4" +checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" dependencies = [ "bytemuck_derive", ] @@ -2186,9 +2158,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.54" +version = "1.2.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6354c81bbfd62d9cfa9cb3c773c2b7b2a3a482d569de977fd0e961f6e7c00583" +checksum = "47b26a0954ae34af09b50f0de26458fa95369a0d478d8236d3f93082b219bd29" dependencies = [ "find-msvc-tools", "jobserver", @@ -2247,9 +2219,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.55" +version = "4.5.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e34525d5bbbd55da2bb745d34b36121baac88d07619a9a09cfcf4a6c0832785" +checksum = "a75ca66430e33a14957acc24c5077b503e7d374151b2b4b3a10c83b4ceb4be0e" dependencies = [ "clap_builder", "clap_derive", @@ -2257,9 +2229,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.55" +version = "4.5.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a20016a20a3da95bef50ec7238dbd09baeef4311dcdd38ec15aba69812fb61" +checksum = "793207c7fa6300a0608d1080b858e5fdbe713cdc1c8db9fb17777d8a13e63df0" dependencies = [ "anstream", "anstyle", @@ -2937,9 +2909,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" [[package]] name = "fixedbitset" @@ -3544,9 +3516,9 @@ checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" [[package]] name = "iana-time-zone" -version = "0.1.64" +version = "0.1.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -4784,15 +4756,15 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.13.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f89776e4d69bb58bc6993e99ffa1d11f228b839984854c7daeb5d37f87cbe950" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" [[package]] name = "portable-atomic-util" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507" +checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5" dependencies = [ "portable-atomic", ] @@ -4876,6 +4848,63 @@ dependencies = [ "num-traits", ] +[[package]] +name = "q_cmd_prompt" +version = "0.1.0" +dependencies = [ + "bevy", + "bevy-inspector-egui", + "bevy_dylib", + "clap", + "cosmic-text 0.16.0", + "q_test_harness", + "regex", + "shlex", + "smallvec", + "smol_str", + "strum", + "thiserror 2.0.18", + "tiny_bail", + "variadics_please", +] + +[[package]] +name = "q_screens" +version = "0.1.0" +dependencies = [ + "anyhow", + "bevy", + "bevy-inspector-egui", + "bevy_asset_loader", + "bitflags 2.10.0", + "itertools 0.14.0", + "q_screens_derive", + "q_test_harness", + "serde", + "strum", + "thiserror 2.0.18", + "tiny_bail", + "variadics_please", +] + +[[package]] +name = "q_screens_derive" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "q_test_harness" +version = "0.1.0" +dependencies = [ + "bevy", + "bevy_asset", + "log", +] + [[package]] name = "quick-error" version = "2.0.1" @@ -5370,9 +5399,9 @@ dependencies = [ [[package]] name = "slab" -version = "0.4.11" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "slotmap" @@ -5579,24 +5608,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "tfw" -version = "0.1.0" -dependencies = [ - "anyhow", - "bevy", - "bevy-inspector-egui", - "bevy_asset_loader", - "bevy_test_harness", - "bitflags 2.10.0", - "itertools 0.14.0", - "serde", - "strum", - "thiserror 2.0.18", - "tiny_bail", - "variadics_please", -] - [[package]] name = "thiserror" version = "1.0.69" @@ -7046,18 +7057,18 @@ checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" [[package]] name = "zerocopy" -version = "0.8.35" +version = "0.8.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdea86ddd5568519879b8187e1cf04e24fce28f7fe046ceecbce472ff19a2572" +checksum = "7456cf00f0685ad319c5b1693f291a650eaf345e941d082fc4e03df8a03996ac" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.35" +version = "0.8.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c15e1b46eff7c6c91195752e0eeed8ef040e391cdece7c25376957d5f15df22" +checksum = "1328722bbf2115db7e19d69ebcc15e795719e2d66b60827c6a69a117365e37a0" dependencies = [ "proc-macro2", "quote", @@ -7066,9 +7077,9 @@ dependencies = [ [[package]] name = "zmij" -version = "1.0.17" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02aae0f83f69aafc94776e879363e9771d7ecbffe2c7fbb6c14c5e00dfe88439" +checksum = "3ff05f8caa9038894637571ae6b9e29466c1f4f829d26c9b28f869a29cbe3445" [[package]] name = "zune-core" diff --git a/Cargo.toml b/Cargo.toml index d6a0a78..d877fb0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/*"] +members = ["crates/*", "crates/*/macros"] resolver="3" [workspace.lints] diff --git a/README.md b/README.md index bebc62f..47c47dd 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,7 @@ illustration of a quail next to text, 'qproj' -![ci](https://github.com/ada-x64/qproj/actions/workflows/ci.yml/badge.svg) -[![codecov](https://codecov.io/gh/ada-x64/qproj/graph/badge.svg?token=AKP1aBwU4S)](https://codecov.io/gh/ada-x64/qproj) +![ci](https://github.com/ada-x64/qproj/actions/workflows/ci.yml/badge.svg) [![Coverage Status](https://coveralls.io/repos/github/ada-x64/qproj/badge.svg?branch=main)](https://coveralls.io/github/ada-x64/qproj?branch=main) Monorepo for _qproj_. This includes utilities, templates, and more for my [bevy](https://bevy.org) game projects. @@ -25,6 +24,6 @@ _This continues the work started [here.](https://github.com/ada-x64/qproj_OLD)_ ## Compatility -| branch | bevy | -| ------ | ---- | -| main | 0.18 | +| branch/tag | bevy | +| ---------- | ---- | +| main | 0.18 | diff --git a/crates/cmd_prompt/Cargo.toml b/crates/cmd_prompt/Cargo.toml index 0f170f4..3623f30 100644 --- a/crates/cmd_prompt/Cargo.toml +++ b/crates/cmd_prompt/Cargo.toml @@ -1,12 +1,12 @@ [package] -name = "bevy_command_prompt" +name = "q_cmd_prompt" version = "0.1.0" edition = "2024" [dependencies] bevy = '0.18.0' bevy-inspector-egui = "0.36.0" -bevy_test_harness = {path = "../test_harness"} +q_test_harness = {path = "../test_harness"} bevy_dylib={optional=true, version="0.18.0"} clap = { version = "4.5.53", features = ["derive"] } cosmic-text = "0.16.0" diff --git a/crates/cmd_prompt/README.md b/crates/cmd_prompt/README.md index 7d49935..2ef80d6 100644 --- a/crates/cmd_prompt/README.md +++ b/crates/cmd_prompt/README.md @@ -1,5 +1,5 @@
-Logo - 'bevy command prompt' over a sketch of a green magpie +Logo - 'bevy command prompt' over a sketch of a green magpie
This is an attempt at a `bevy_ui`-native dev console. diff --git a/crates/cmd_prompt/examples/minimal.rs b/crates/cmd_prompt/examples/minimal.rs index dc8b416..b744287 100644 --- a/crates/cmd_prompt/examples/minimal.rs +++ b/crates/cmd_prompt/examples/minimal.rs @@ -1,5 +1,5 @@ use bevy::prelude::*; -use bevy_command_prompt::prelude::*; +use q_cmd_prompt::prelude::*; // use bevy_inspector_egui::{bevy_egui::EguiPlugin, quick::WorldInspectorPlugin}; pub fn main() { diff --git a/crates/cmd_prompt/examples/styled.rs b/crates/cmd_prompt/examples/styled.rs index 7f1ebc7..c01e142 100644 --- a/crates/cmd_prompt/examples/styled.rs +++ b/crates/cmd_prompt/examples/styled.rs @@ -1,6 +1,6 @@ use bevy::color::palettes::tailwind; use bevy::prelude::*; -use bevy_command_prompt::prelude::*; +use q_cmd_prompt::prelude::*; pub fn main() { let mut app = App::new(); diff --git a/crates/cmd_prompt/src/actions/actions/history.rs b/crates/cmd_prompt/src/actions/actions/history.rs index d3b08b0..43fce56 100644 --- a/crates/cmd_prompt/src/actions/actions/history.rs +++ b/crates/cmd_prompt/src/actions/actions/history.rs @@ -68,7 +68,7 @@ mod test { use bevy::input::ButtonState; use bevy::input::keyboard::Key; use bevy::input::keyboard::KeyboardInput; - use bevy_test_harness::prelude::*; + use q_test_harness::prelude::*; fn key_input(key_code: KeyCode, logical_key: Key, state: ButtonState) -> KeyboardInput { KeyboardInput { diff --git a/crates/cmd_prompt/src/lib.rs b/crates/cmd_prompt/src/lib.rs index 22e3842..0964251 100644 --- a/crates/cmd_prompt/src/lib.rs +++ b/crates/cmd_prompt/src/lib.rs @@ -18,7 +18,7 @@ pub mod prelude { use bevy::{input_focus::InputFocus, ui::ui_layout_system}; use prelude::*; -/// The main entrypoint for bevy_command_prompt. +/// The main entrypoint for q_cmd_prompt. pub struct ConsolePlugin; impl Plugin for ConsolePlugin { fn build(&self, app: &mut App) { diff --git a/crates/cmd_prompt/src/test_harness.rs b/crates/cmd_prompt/src/test_harness.rs index d4a2da0..20e0b64 100644 --- a/crates/cmd_prompt/src/test_harness.rs +++ b/crates/cmd_prompt/src/test_harness.rs @@ -1,8 +1,8 @@ use bevy::{ - image::TextureAtlasPlugin, input::InputPlugin, input_focus::InputFocus, text::TextPlugin, - ui::UiPlugin, + image::TextureAtlasPlugin, input::InputPlugin, input_focus::InputFocus, + render::texture::TexturePlugin, text::TextPlugin, ui::UiPlugin, }; -use bevy_test_harness::{TestRunnerPlugin, TestRunnerTimeout}; +use q_test_harness::{TestRunnerPlugin, TestRunnerTimeout}; use crate::prelude::*; @@ -20,6 +20,8 @@ pub fn plugin(app: &mut App) { UiPlugin, TextPlugin, TextureAtlasPlugin, + ImagePlugin::default(), + TexturePlugin, )); app.add_systems(Startup, setup); app.insert_resource(TestRunnerTimeout(1.)); diff --git a/crates/tfw/Cargo.toml b/crates/screens/Cargo.toml similarity index 68% rename from crates/tfw/Cargo.toml rename to crates/screens/Cargo.toml index 33d8e3e..792e642 100644 --- a/crates/tfw/Cargo.toml +++ b/crates/screens/Cargo.toml @@ -1,12 +1,11 @@ [package] -name = "tfw" +name = "q_screens" version = "0.1.0" edition = "2024" [dependencies] # bevy -bevy = {version="0.18", features=["default_app", "default_platform", "common_api"]} -bevy_asset_loader = "0.25" +bevy = {version="0.18"} # features=["default_app", "default_platform", "common_api"]} # not bevy tiny_bail = "0.7" @@ -19,11 +18,13 @@ strum = { version = "0.27.2", features = ["derive"] } variadics_please = "1.1.0" # local -bevy_test_harness = {path="../test_harness"} +q_test_harness = {path="../test_harness", version="0.1.0"} +q_screens_derive = {path="./macros", version="0.1.0"} [dev-dependencies] # just for a few inspector things... should really fork them bevy-inspector-egui = "0.36" +bevy_asset_loader = "0.25" [lints] workspace = true diff --git a/crates/screens/README.md b/crates/screens/README.md new file mode 100644 index 0000000..5947bb1 --- /dev/null +++ b/crates/screens/README.md @@ -0,0 +1,11 @@ +# q_screens + +Screen implementation for Bevy. + +## Features + +- [x] Basic screen lifecycle (load, ready, unload, unloaded) +- [x] Screen-scoped and persistent entities +- [x] App-level screen registration +- [x] Friendly and bevyish API +- [x] Well-tested diff --git a/assets/test/cat2.png b/crates/screens/assets/test/cat2.png similarity index 100% rename from assets/test/cat2.png rename to crates/screens/assets/test/cat2.png diff --git a/crates/screens/assets/test/test.txt b/crates/screens/assets/test/test.txt new file mode 100644 index 0000000..59c1c59 --- /dev/null +++ b/crates/screens/assets/test/test.txt @@ -0,0 +1,1363 @@ +According to all known laws of aviation, there is no way a bee should be able to fly. +Its wings are too small to get its fat little body off the ground. +The bee, of course, flies anyway because bees don't care what humans think is impossible. +Yellow, black. Yellow, black. Yellow, black. Yellow, black. +Ooh, black and yellow! +Let's shake it up a little. +Barry! Breakfast is ready! +Coming! +Hang on a second. +Hello? +Barry? +Adam? +Can you believe this is happening? +I can't. +I'll pick you up. +Looking sharp. +Use the stairs, Your father paid good money for those. +Sorry. I'm excited. +Here's the graduate. +We're very proud of you, son. +A perfect report card, all B's. +Very proud. +Ma! I got a thing going here. +You got lint on your fuzz. +Ow! That's me! +Wave to us! We'll be in row 118,000. +Bye! +Barry, I told you, stop flying in the house! +Hey, Adam. +Hey, Barry. +Is that fuzz gel? +A little. Special day, graduation. +Never thought I'd make it. +Three days grade school, three days high school. +Those were awkward. +Three days college. I'm glad I took a day and hitchhiked around The Hive. +You did come back different. +Hi, Barry. Artie, growing a mustache? Looks good. +Hear about Frankie? +Yeah. +You going to the funeral? +No, I'm not going. +Everybody knows, sting someone, you die. +Don't waste it on a squirrel. +Such a hothead. +I guess he could have just gotten out of the way. +I love this incorporating an amusement park into our day. +That's why we don't need vacations. +Boy, quite a bit of pomp under the circumstances. +Well, Adam, today we are men. +We are! +Bee-men. +Amen! +Hallelujah! +Students, faculty, distinguished bees, +please welcome Dean Buzzwell. +Welcome, New Hive City graduating class of 9:15. +That concludes our ceremonies And begins your career at Honex Industries! +Will we pick our job today? +I heard it's just orientation. +Heads up! Here we go. +Keep your hands and antennas inside the tram at all times. +Wonder what it'll be like? +A little scary. +Welcome to Honex, a division of Honesco and a part of the Hexagon Group. +This is it! +Wow. +Wow. +We know that you, as a bee, have worked your whole life to get to the point where you can work for your whole life. +Honey begins when our valiant Pollen Jocks bring the nectar to The Hive. +Our top-secret formula is automatically color-corrected, scent-adjusted and bubble-contoured into this soothing sweet syrup with its distinctive golden glow you know as... Honey! +That girl was hot. +She's my cousin! +She is? +Yes, we're all cousins. +Right. You're right. +At Honex, we constantly strive to improve every aspect of bee existence. +These bees are stress-testing a new helmet technology. +What do you think he makes? +Not enough. +Here we have our latest advancement, the Krelman. +What does that do? +Catches that little strand of honey that hangs after you pour it. +Saves us millions. +Can anyone work on the Krelman? +Of course. Most bee jobs are small ones. +But bees know that every small job, if it's done well, means a lot. +But choose carefully because you'll stay in the job you pick for the rest of your life. +The same job the rest of your life? I didn't know that. +What's the difference? +You'll be happy to know that bees, as a species, haven't had one day off in 27 million years. +So you'll just work us to death? +We'll sure try. +Wow! That blew my mind! +"What's the difference?" +How can you say that? +One job forever? +That's an insane choice to have to make. +I'm relieved. Now we only have to make one decision in life. +But, Adam, how could they never have told us that? +Why would you question anything? We're bees. +We're the most perfectly functioning society on Earth. +You ever think maybe things work a little too well here? +Like what? Give me one example. +I don't know. But you know what I'm talking about. +Please clear the gate. Royal Nectar Force on approach. +Wait a second. Check it out. +Hey, those are Pollen Jocks! +Wow. +I've never seen them this close. +They know what it's like outside The Hive. +Yeah, but some don't come back. +Hey, Jocks! +Hi, Jocks! +You guys did great! +You're monsters! +You're sky freaks! I love it! I love it! +I wonder where they were. +I don't know. +Their day's not planned. +Outside The Hive, flying who knows where, doing who knows what. +You can't just decide to be a Pollen Jock. You have to be bred for that. +Right. +Look. That's more pollen than you and I will see in a lifetime. +It's just a status symbol. +Bees make too much of it. +Perhaps. Unless you're wearing it and the ladies see you wearing it. +Those ladies? +Aren't they our cousins too? +Distant. Distant. +Look at these two. +Couple of Hive Harrys. +Let's have fun with them. +It must be dangerous being a Pollen Jock. +Yeah. Once a bear pinned me against a mushroom! +He had a paw on my throat, and with the other, he was slapping me! +Oh, my! +I never thought I'd knock him out. +What were you doing during this? +Trying to alert the authorities. +I can autograph that. +A little gusty out there today, wasn't it, comrades? +Yeah. Gusty. +We're hitting a sunflower patch six miles from here tomorrow. +Six miles, huh? +Barry! +A puddle jump for us, but maybe you're not up for it. +Maybe I am. +You are not! +We're going 0900 at J-Gate. +What do you think, buzzy-boy? +Are you bee enough? +I might be. It all depends on what 0900 means. +Hey, Honex! +Dad, you surprised me. +You decide what you're interested in? +Well, there's a lot of choices. +But you only get one. +Do you ever get bored doing the same job every day? +Son, let me tell you about stirring. +You grab that stick, and you just move it around, and you stir it around. +You get yourself into a rhythm. +It's a beautiful thing. +You know, Dad, the more I think about it, +maybe the honey field just isn't right for me. +You were thinking of what, making balloon animals? +That's a bad job for a guy with a stinger. +Janet, your son's not sure he wants to go into honey! +Barry, you are so funny sometimes. +I'm not trying to be funny. +You're not funny! You're going into honey. Our son, the stirrer! +You're gonna be a stirrer? +No one's listening to me! +Wait till you see the sticks I have. +I could say anything right now. +I'm gonna get an ant tattoo! +Let's open some honey and celebrate! +Maybe I'll pierce my thorax. Shave my antennae. Shack up with a grasshopper. Get a gold tooth and call everybody "dawg"! +I'm so proud. +We're starting work today! +Today's the day. +Come on! All the good jobs will be gone. +Yeah, right. +Pollen counting, stunt bee, pouring, stirrer, front desk, hair removal... +Is it still available? +Hang on. Two left! +One of them's yours! Congratulations! +Step to the side. +What'd you get? +Picking crud out. Stellar! +Wow! +Couple of newbies? +Yes, sir! Our first day! We are ready! +Make your choice. +You want to go first? +No, you go. +Oh, my. What's available? +Restroom attendant's open, not for the reason you think. +Any chance of getting the Krelman? +Sure, you're on. +I'm sorry, the Krelman just closed out. +Wax monkey's always open. +The Krelman opened up again. +What happened? +A bee died. Makes an opening. See? He's dead. Another dead one. +Deady. Deadified. Two more dead. +Dead from the neck up. Dead from the neck down. That's life! +Oh, this is so hard! +Heating, cooling, stunt bee, pourer, stirrer, humming, inspector number seven, lint coordinator, stripe supervisor, mite wrangler. +Barry, what do you think I should... Barry? +Barry! +All right, we've got the sunflower patch in quadrant nine... +What happened to you? +Where are you? +I'm going out. +Out? Out where? +Out there. +Oh, no! +I have to, before I go to work for the rest of my life. +You're gonna die! You're crazy! Hello? +Another call coming in. +If anyone's feeling brave, there's a Korean deli on 83rd that gets their roses today. +Hey, guys. +Look at that. +Isn't that the kid we saw yesterday? +Hold it, son, flight deck's restricted. +It's OK, Lou. We're gonna take him up. +Really? Feeling lucky, are you? +Sign here, here. Just initial that. +Thank you. +OK. +You got a rain advisory today, and as you all know, bees cannot fly in rain. +So be careful. As always, watch your brooms, hockey sticks, dogs, birds, bears and bats. +Also, I got a couple of reports of root beer being poured on us. +Murphy's in a home because of it, babbling like a cicada! +That's awful. +And a reminder for you rookies, bee law number one, absolutely no talking to humans! + All right, launch positions! +Buzz, buzz, buzz, buzz! Buzz, buzz, buzz, buzz! Buzz, buzz, buzz, buzz! +Black and yellow! +Hello! +You ready for this, hot shot? +Yeah. Yeah, bring it on. +Wind, check. +Antennae, check. +Nectar pack, check. +Wings, check. +Stinger, check. +Scared out of my shorts, check. +OK, ladies, +let's move it out! +Pound those petunias, you striped stem-suckers! +All of you, drain those flowers! +Wow! I'm out! +I can't believe I'm out! +So blue. +I feel so fast and free! +Box kite! +Wow! +Flowers! +This is Blue Leader, We have roses visual. +Bring it around 30 degrees and hold. +Roses! +30 degrees, roger. Bringing it around. +Stand to the side, kid. +It's got a bit of a kick. +That is one nectar collector! +Ever see pollination up close? +No, sir. +I pick up some pollen here, sprinkle it over here. Maybe a dash over there, a pinch on that one. +See that? It's a little bit of magic. +That's amazing. Why do we do that? +That's pollen power. More pollen, more flowers, more nectar, more honey for us. +Cool. +I'm picking up a lot of bright yellow, Could be daisies, Don't we need those? +Copy that visual. +Wait. One of these flowers seems to be on the move. +Say again? You're reporting a moving flower? +Affirmative. +That was on the line! +This is the coolest. What is it? +I don't know, but I'm loving this color. +It smells good. +Not like a flower, but I like it. +Yeah, fuzzy. +Chemical-y. +Careful, guys. It's a little grabby. +My sweet lord of bees! +Candy-brain, get off there! +Problem! +Guys! +This could be bad. +Affirmative. +Very close. +Gonna hurt. +Mama's little boy. +You are way out of position, rookie! +Coming in at you like a missile! +Help me! +I don't think these are flowers. +Should we tell him? +I think he knows. +What is this?! +Match point! +You can start packing up, honey, because you're about to eat it! +Yowser! +Gross. +There's a bee in the car! +Do something! +I'm driving! +Hi, bee. +He's back here! +He's going to sting me! +Nobody move. If you don't move, he won't sting you. Freeze! +He blinked! +Spray him, Granny! +What are you doing?! +Wow... the tension level out here is unbelievable. +I gotta get home. +Can't fly in rain. Can't fly in rain. Can't fly in rain. +Mayday! Mayday! Bee going down! +Ken, could you close the window please? +Ken, could you close the window please? +Check out my new resume. I made it into a fold-out brochure. You see? Folds out. +Oh, no. More humans. I don't need this. +What was that? +Maybe this time. This time. This time. This time! This time! This... Drapes! +That is diabolical. +It's fantastic. It's got all my special skills, even my top-ten favorite movies. +What's number one? Star Wars? +Nah, I don't go for that... kind of stuff. +No wonder we shouldn't talk to them. They're out of their minds. +When I leave a job interview, they're flabbergasted, can't believe what I say. +There's the sun. Maybe that's a way out. +I don't remember the sun having a big 75 on it. +I predicted global warming. I could feel it getting hotter. At first I thought it was just me. +Wait! Stop! Bee! +Stand back. These are winter boots. +Wait! +Don't kill him! +You know I'm allergic to them! This thing could kill me! +Why does his life have less value than yours? +Why does his life have any less value than mine? Is that your statement? +I'm just saying all life has value. You don't know what he's capable of feeling. +My brochure! +There you go, little guy. +I'm not scared of him.It's an allergic thing. + Put that on your resume brochure. +My whole face could puff up. +Make it one of your special skills. +Knocking someone out is also a special skill. +Right. Bye, Vanessa. Thanks. +Vanessa, next week? Yogurt night? +Sure, Ken. You know, whatever. +You could put carob chips on there. +Bye. +Supposed to be less calories. +Bye. +I gotta say something. She saved my life. I gotta say something. +All right, here it goes. +Nah. +What would I say? +I could really get in trouble. It's a bee law. You're not supposed to talk to a human. +I can't believe I'm doing this. I've got to. +Oh, I can't do it. Come on! +No. Yes. No. Do it. I can't. +How should I start it? "You like jazz?" No, that's no good. +Here she comes! Speak, you fool! +Hi! +I'm sorry. You're talking. +Yes, I know. +You're talking! +I'm so sorry. +No, it's OK. It's fine. +I know I'm dreaming. But I don't recall going to bed. +Well, I'm sure this is very disconcerting. +This is a bit of a surprise to me. I mean, you're a bee! +I am. And I'm not supposed to be doing this, but they were all trying to kill me. +And if it wasn't for you... I had to thank you. It's just how I was raised. +That was a little weird. I'm talking with a bee. +Yeah. +I'm talking to a bee. And the bee is talking to me! +I just want to say I'm grateful. +I'll leave now. +Wait! How did you learn to do that? +What? +The talking thing. +Same way you did, I guess. "Mama, Dada, honey." You pick it up. +That's very funny. +Yeah. +Bees are funny. If we didn't laugh, we'd cry with what we have to deal with. +Anyway... Can I... get you something? +Like what? +I don't know. I mean... I don't know. Coffee? +I don't want to put you out. +It's no trouble. It takes two minutes. +It's just coffee. +I hate to impose. +Don't be ridiculous! +Actually, I would love a cup. +Hey, you want rum cake? +I shouldn't. +Have some. +No, I can't. +Come on! +I'm trying to lose a couple micrograms. +Where? +These stripes don't help. +You look great! +I don't know if you know anything about fashion. +Are you all right? +No. +He's making the tie in the cab as they're flying up Madison. +He finally gets there. +He runs up the steps into the church. +The wedding is on. +And he says, "Watermelon? +I thought you said Guatemalan. +Why would I marry a watermelon?" +Is that a bee joke? +That's the kind of stuff we do. +Yeah, different. +So, what are you gonna do, Barry? +About work? I don't know. +I want to do my part for The Hive, but I can't do it the way they want. +I know how you feel. +You do? +Sure. +My parents wanted me to be a lawyer or a doctor, but I wanted to be a florist. +Really? +My only interest is flowers. +Our new queen was just elected with that same campaign slogan. +Anyway, if you look... There's my hive right there. See it? +You're in Sheep Meadow! +Yes! I'm right off the Turtle Pond! +No way! I know that area. I lost a toe ring there once. +Why do girls put rings on their toes? +Why not? +It's like putting a hat on your knee. +Maybe I'll try that. +You all right, ma'am? +Oh, yeah. Fine. +Just having two cups of coffee! +Anyway, this has been great. +Thanks for the coffee. +Yeah, it's no trouble. +Sorry I couldn't finish it. If I did, I'd be up the rest of my life. +Are you...? +Can I take a piece of this with me? +Sure! Here, have a crumb. +Thanks! +Yeah. +All right. Well, then... I guess I'll see you around. Or not. +OK, Barry. +And thank you so much again... for before. +Oh, that? That was nothing. +Well, not nothing, but... Anyway... +This can't possibly work. +He's all set to go. +We may as well try it. +OK, Dave, pull the chute. +Sounds amazing. +It was amazing! +It was the scariest, happiest moment of my life. +Humans! I can't believe you were with humans! +Giant, scary humans! +What were they like? +Huge and crazy. They talk crazy. +They eat crazy giant things. +They drive crazy. +Do they try and kill you, like on TV? +Some of them. But some of them don't. +How'd you get back? +Poodle. +You did it, and I'm glad. You saw whatever you wanted to see. +You had your "experience." Now you can pick out yourjob and be normal. +Well... +Well? +Well, I met someone. +You did? Was she Bee-ish? +A wasp?! Your parents will kill you! +No, no, no, not a wasp. +Spider? +I'm not attracted to spiders. +I know it's the hottest thing, with the eight legs and all. I can't get by that face. +So who is she? +She's... human. +No, no. That's a bee law. You wouldn't break a bee law. +Her name's Vanessa. +Oh, boy. +She's so nice. And she's a florist! +Oh, no! You're dating a human florist! +We're not dating. +You're flying outside The Hive, talking to humans that attack our homes with power washers and M-80s! One-eighth a stick of dynamite! +She saved my life! And she understands me. +This is over! +Eat this. +This is not over! What was that? +They call it a crumb. +It was so stingin' stripey! +And that's not what they eat. +That's what falls off what they eat! +You know what a Cinnabon is? +No. +It's bread and cinnamon and frosting. They heat it up... +Sit down! +...really hot! +Listen to me! +We are not them! We're us. +There's us and there's them! +Yes, but who can deny the heart that is yearning? +There's no yearning. Stop yearning. Listen to me! +You have got to start thinking bee, my friend. Thinking bee! +Thinking bee. +Thinking bee. +Thinking bee! Thinking bee! Thinking bee! Thinking bee! +There he is. He's in the pool. +You know what your problem is, Barry? +I gotta start thinking bee? +How much longer will this go on? +It's been three days! Why aren't you working? +I've got a lot of big life decisions to think about. +What life? You have no life! +You have no job. You're barely a bee! +Would it kill you to make a little honey? +Barry, come out. Your father's talking to you. +Martin, would you talk to him? +Barry, I'm talking to you! +You coming? +Got everything? +All set! +Go ahead. I'll catch up. +Don't be too long. +Watch this! +Vanessa! +We're still here. +I told you not to yell at him. +He doesn't respond to yelling! +Then why yell at me? +Because you don't listen! +I'm not listening to this. +Sorry, I've gotta go. +Where are you going? +I'm meeting a friend. +A girl? Is this why you can't decide? +Bye. +I just hope she's Bee-ish. +They have a huge parade of flowers every year in Pasadena? +To be in the Tournament of Roses, that's every florist's dream! +Up on a float, surrounded by flowers, crowds cheering. +A tournament. Do the roses compete in athletic events? +No. All right, I've got one. +How come you don't fly everywhere? +It's exhausting. Why don't you run everywhere? It's faster. +Yeah, OK, I see, I see. +All right, your turn. +TiVo. You can just freeze live TV? That's insane! +You don't have that? +We have Hivo, but it's a disease. It's a horrible, horrible disease. +Oh, my. +Dumb bees! +You must want to sting all those jerks. +We try not to sting. It's usually fatal for us. +So you have to watch your temper. +Very carefully. +You kick a wall, take a walk, write an angry letter and throw it out. Work through it like any emotion: Anger, jealousy, lust. +Oh, my goodness! Are you OK? +Yeah. +What is wrong with you?! +It's a bug. +He's not bothering anybody. +Get out of here, you creep! +What was that? A Pic 'N' Save circular? +Yeah, it was. How did you know? +It felt like about 10 pages. Seventy-five is pretty much our limit. +You've really got that down to a science. +I lost a cousin to Italian Vogue. +I'll bet. +What in the name of Mighty Hercules is this? +How did this get here? cute Bee, Golden Blossom, Ray Liotta Private Select? +Is he that actor? +I never heard of him. +Why is this here? +For people. We eat it. +You don't have enough food of your own? +Well, yes. +How do you get it? +Bees make it. +I know who makes it! And it's hard to make it! +There's heating, cooling, stirring. You need a whole Krelman thing! +It's organic. +It's our-ganic! +It's just honey, Barry. +Just what?! +Bees don't know about this! This is stealing! A lot of stealing! +You've taken our homes, schools,hospitals! This is all we have! +And it's on sale?! I'm getting to the bottom of this. +I'm getting to the bottom of all of this! +Hey, Hector. You almost done? +Almost. +He is here. I sense it. +Well, I guess I'll go home now and just leave this nice honey out, with no one around. +You're busted, box boy! +I knew I heard something. +So you can talk! +I can talk. And now you'll start talking! +Where you getting the sweet stuff? Who's your supplier? +I don't understand. +I thought we were friends. +The last thing we want to do is upset bees! +You're too late! It's ours now! +You, sir, have crossed the wrong sword! +You, sir, will be lunch for my iguana, Ignacio! +Where is the honey coming from? Tell me where! +Honey Farms! It comes from Honey Farms! +Crazy person! +What horrible thing has happened here? +These faces, they never knew what hit them. And now +they're on the road to nowhere! +Just keep still. +What? You're not dead? +Do I look dead? They will wipe anything that moves. Where you headed? +To Honey Farms. I am onto something huge here. +I'm going to Alaska. Moose blood, crazy stuff. Blows your head off! +I'm going to Tacoma. +And you? +He really is dead. +All right. +Uh-oh! +What is that?! +Oh, no! +A wiper! Triple blade! +Triple blade? +Jump on! It's your only chance, bee! +Why does everything have +to be so doggone clean?! +How much do you people need to see?! +Open your eyes! +Stick your head out the window! +From NPR News in Washington, +I'm Carl Kasell. +But don't kill no more bugs! +Bee! +Moose blood guy!! +You hear something? +Like what? +Like tiny screaming. +Turn off the radio. +Whassup, bee boy? +Hey, Blood. +Just a row of honey jars, as far as the eye could see. +Wow! +I assume wherever this truck goes is where they're getting it. I mean, that honey's ours. +Bees hang tight. We're all jammed in. +It's a close community. +Not us, man. We on our own. Every mosquito on his own. +What if you get in trouble? +You a mosquito, you in trouble. Nobody likes us. They just smack. See a mosquito, smack, smack! +At least you're out in the world. You must meet girls. +Mosquito girls try to trade up, get with a moth, dragonfly. Mosquito girl don't want no mosquito. +You got to be kidding me! +Mooseblood's about to leave the building! So long, bee! +Hey, guys! +Mooseblood! +I knew I'd catch y'all down here. +Did you bring your crazy straw? +We throw it in jars, slap a label on it, and it's pretty much pure profit. +What is this place? +A bee's got a brain the size of a pinhead. +They are pinheads! +Pinhead. +Check out the new smoker. +Oh, sweet. That's the one you want. The Thomas 3000! +Smoker? +Ninety puffs a minute, semi-automatic. Twice the nicotine, all the tar. A couple breaths of this knocks them right out. +They make the honey, and we make the money. +"They make the honey, and we make the money"? +Oh, my! +What's going on? Are you OK? +Yeah. It doesn't last too long. +Do you know you're in a fake hive with fake walls? +Our queen was moved here. We had no choice. +This is your queen? That's a man in women's clothes! That's a drag queen! +What is this? +Oh, no! +There's hundreds of them! +Bee honey. +Our honey is being brazenly stolen on a massive scale! +This is worse than anything bears have done! I intend to do something. +Oh, Barry, stop. +Who told you humans are taking our honey? That's a rumor. +Do these look like rumors? +That's a conspiracy theory. These are obviously doctored photos. How did you get mixed up in this? +He's been talking to humans. +What? Talking to humans?! +He has a human girlfriend. And they make out! +Make out? Barry! +We do not. +You wish you could. +Whose side are you on? +The bees! +I dated a cricket once in San Antonio. Those crazy legs kept me up all night. +Barry, this is what you want to do with your life? +I want to do it for all our lives. Nobody works harder than bees! +Dad, I remember you coming home so overworked +your hands were still stirring. You couldn't stop. +I remember that. +What right do they have to our honey? +We live on two cups a year. They put it in lip balm for no reason whatsoever! +Even if it's true, what can one bee do? +Sting them where it really hurts. +In the face! The eye! +That would hurt. +No. +Up the nose? That's a killer. +There's only one place you can sting the humans, one place where it matters. +Hive at Five, The Hive's only full-hour action news source. +No more bee beards! +With Bob Bumble at the anchor desk. Weather with Storm Stinger. Sports with Buzz Larvi. And Jeanette Chung. +Good evening. I'm Bob Bumble. +And I'm Jeanette Ohung. +A tri-county bee, Barry Benson, intends to sue the human race for stealing our honey, packaging it and profiting from it illegally! +Tomorrow night on Bee Larry King, we'll have three former queens here in our studio, discussing their new book, classy Ladies, out this week on Hexagon. +Tonight we're talking to Barry Benson. +Did you ever think, "I'm a kid from The Hive. I can't do this"? +Bees have never been afraid to change the world. +What about Bee Oolumbus? Bee Gandhi? Bejesus? +Where I'm from, we'd never sue humans. +We were thinking of stickball or candy stores. +How old are you? +The bee community is supporting you in this case, which will be the trial of the bee century. +You know, they have a Larry King in the human world too. +It's a common name. Next week... +He looks like you and has a show and suspenders and colored dots... +Next week... +Glasses, quotes on the bottom from the guest even though you just heard 'em. +Bear Week next week! They're scary, hairy and here live. +Always leans forward, pointy shoulders, squinty eyes, very Jewish. +In tennis, you attack at the point of weakness! +It was my grandmother, Ken. She's 81. +Honey, her backhand's a joke! +I'm not gonna take advantage of that? +Quiet, please. +Actual work going on here. +Is that that same bee? +Yes, it is! +I'm helping him sue the human race. +Hello. +Hello, bee. +This is Ken. +Yeah, I remember you. Timberland, size ten and a half. Vibram sole, I believe. +Why does he talk again? +Listen, you better go 'cause we're really busy working. +But it's our yogurt night! +Bye-bye. +Why is yogurt night so difficult?! +You poor thing. You two have been at this for hours! +Yes, and Adam here has been a huge help. +Frosting... +How many sugars? +Just one. I try not to use the competition. +So why are you helping me? +Bees have good qualities. And it takes my mind off the shop. Instead of flowers, people are giving balloon bouquets now. +Those are great, if you're three. +And artificial flowers. +Oh, those just get me psychotic! +Yeah, me too. +Bent stingers, pointless pollination. +Bees must hate those fake things! +Nothing worse than a daffodil that's had work done. +Maybe this could make up for it a little bit. +This lawsuit's a pretty big deal. +I guess. +You sure you want to go through with it? +Am I sure? When I'm done with the humans, they won't be able to say, "Honey, I'm home," without paying a royalty! +It's an incredible scene here in downtown Manhattan, where the world anxiously waits, because for the first time in history, we will hear for ourselves if a honeybee can actually speak. +What have we gotten into here, Barry? +It's pretty big, isn't it? +I can't believe how many humans don't work during the day. +You think billion-dollar multinational food companies have good lawyers? +Everybody needs to stay behind the barricade. +What's the matter? +I don't know, I just got a chill. +Well, if it isn't the bee team. +You boys work on this? +All rise! The Honorable Judge Bumbleton presiding. +All right. Case number 4475, +Superior Court of New York, +Barry Bee Benson v. the Honey Industry is now in session. +Mr. Montgomery, you're representing the five food companies collectively? +A privilege. +Mr. Benson... you're representing all the bees of the world? +I'm kidding. Yes, Your Honor, we're ready to proceed. +Mr. Montgomery, your opening statement, please. +Ladies and gentlemen of the jury, my grandmother was a simple woman. Born on a farm, she believed it was man's divine right to benefit from the bounty of nature God put before us. +If we lived in the topsy-turvy world Mr. Benson imagines, just think of what would it mean. +I would have to negotiate with the silkworm for the elastic in my britches! +Talking bee! +How do we know this isn't some sort of holographic motion-picture-capture Hollywood wizardry? +They could be using laser beams! Robotics! Ventriloquism! Cloning! For all we know, he could be on steroids! +Mr. Benson? +Ladies and gentlemen, there's no trickery here. I'm just an ordinary bee. Honey's pretty important to me. It's important to all bees. We invented it! We make it. And we protect it with our lives. +Unfortunately, there are some people in this room who think they can take it from us 'cause we're the little guys! +I'm hoping that, after this is all over, you'll see how, by taking our honey, you not only take everything we have but everything we are! +I wish he'd dress like that all the time. So nice! +Call your first witness. +So, Mr. Klauss Vanderhayden of Honey Farms, big company you have. +I suppose so. +I see you also own Honeyburton and Honron! +Yes, they provide beekeepers for our farms. +Beekeeper. I find that to be a very disturbing term. +I don't imagine you employ any bee-free-ers, do you? +No. +I couldn't hear you. +No. +No. Because you don't free bees. You keep bees. Not only that, it seems you thought a bear would be an appropriate image for a jar of honey. +They're very lovable creatures. Yogi Bear, Fozzie Bear, Build-A-Bear. +You mean like this? +Bears kill bees! +How'd you like his head crashing through your living room?! Biting into your couch! Spitting out your throw pillows! OK, that's enough. Take him away. +So, Mr. Sting, thank you for being here. Your name intrigues me. Where have I heard it before? +I was with a band called The Police. +But you've never been a police officer, have you? +No, I haven't. +No, you haven't. And so here we have yet another example of bee culture casually stolen by a human for nothing more than a prance-about stage name. +Oh, please. +Have you ever been stung, Mr. Sting? Because I'm feeling a little stung, Sting. Or should I say... Mr. Gordon M. Sumner! +That's not his real name?! You idiots! +Mr. Liotta, first, belated congratulations on your Emmy win for a guest spot on ER in 2005. +Thank you. Thank you. +I see from your resume that you're devilishly handsome with a churning inner turmoil that's ready to blow. +I enjoy what I do. Is that a crime? +Not yet it isn't. But is this what it's come to for you? Exploiting tiny, helpless bees so you don't have to rehearse your part and learn your lines, sir? +Watch it, Benson! I could blow right now! +This isn't a goodfella. +This is a badfella! +Why doesn't someone just step on this creep, and we can all go home?! +Order in this court! +You're all thinking it! +Order! Order, I say! +Say it! +Mr. Liotta, please sit down! +I think it was awfully nice of that bear to pitch in like that. I think the jury's on our side. +Are we doing everything right, legally? +I'm a florist. +Right. Well, here's to a great team. +To a great team! +Well, hello. +Ken! +Hello. +I didn't think you were coming. +No, I was just late I tried to call, but... the battery. +I didn't want all this to go to waste, +so I called Barry. Luckily, he was free. +Oh, that was lucky. +There's a little left. I could heat it up. +Yeah, heat it up, sure, whatever. +So I hear you're quite a tennis player. I'm not much for the game myself. The ball's a little grabby. +That's where I usually sit. Right... there. +Ken, Barry was looking at your resume, and he agreed with me that eating with chopsticks isn't really a special skill. +You think I don't see what you're doing? +I know how hard it is to find the right job. We have that in common. +Do we? +Bees have 100 percent employment, but we do jobs like taking the crud out. +That's just what I was thinking about doing. +Ken, I let Barry borrow your razor for his fuzz. I hope that was all right. +I'm going to drain the old stinger. +Yeah, you do that. +Look at that. +You know, I've just about had it with your little Mind Games. +What's that? +Italian Vogue. +Mamma mia, that's a lot of pages. +A lot of ads. +Remember what Van said, why is your life more valuable than mine? +Funny, I just can't seem to recall that! I think something stinks in here! +I love the smell of flowers. +How do you like the smell of flames?! +Not as much. +Water bug! Not taking sides! +Ken, I'm wearing a Chapstick hat! +This is pathetic! +I've got issues! +Well, well, well, a royal flush! +You're bluffing. +Am I? +Surf's up, dude! +Poo water! +That bowl is gnarly. Except for those dirty yellow rings! +Kenneth! What are you doing?! +You know, I don't even like honey! I don't eat it! +We need to talk! He's just a little bee! +And he happens to be the nicest bee I've met in a long time! +Long time? What are you talking about?! Are there other bugs in your life? + No, but there are other things bugging me in life. And you're one of them! +Fine! Talking bees, no yogurt night... +My nerves are fried from riding on this emotional roller coaster! +Goodbye, Ken. +And for your information, I prefer sugar-free, artificial sweeteners made by man! +I'm sorry about all that. +I know it's got an aftertaste! I like it! +I always felt there was some kind of barrier between Ken and me. I couldn't overcome it. +Oh, well. +Are you OK for the trial? +I believe Mr. Montgomery is about out of ideas. +We would like to call Mr. Barry Benson Bee to the stand. +Good idea! You can really see why he's considered one of the best lawyers... +Yeah. +Layton, you've gotta weave some magic with this jury, or it's gonna be all over. +Don't worry. The only thing I have to do to turn this jury around is to remind them of what they don't like about bees. +You got the tweezers? +Are you allergic? +Only to losing, son. Only to losing. +Mr. Benson Bee, I'll ask you what I think we'd all like to know. +What exactly is your relationship to that woman? +We're friends. +Good friends? +Yes. +How good? Do you live together? +Wait a minute... Are you her little... bedbug? +I've seen a bee documentary or two. From what I understand, doesn't your queen give birth to all the bee children? +Yeah, but... +So those aren't your real parents! +Oh, Barry... +Yes, they are! +Hold me back! +You're an illegitimate bee, aren't you, Benson? +He's denouncing bees! +Don't y'all date your cousins? +Objection! +I'm going to pincushion this guy! +Adam, don't! It's what he wants! +Oh, I'm hit!! Oh, lordy, I am hit! +Order! Order! +The venom! The venom is coursing through my veins! I have been felled by a winged beast of destruction! You see? You can't treat them like equals! They're striped savages! Stinging's the only thing they know! It's their way! +Adam, stay with me. +I can't feel my legs. +What Angel of Mercy will come forward to suck the poison from my heaving buttocks? +I will have order in this court. Order! Order, please! +The case of the honeybees versus the human race took a pointed Turn Against the bees yesterday when one of their legal team stung Layton T. Montgomery. +Hey, buddy. +Hey. +Is there much pain? +Yeah. +I... I blew the whole case, didn't I? +It doesn't matter. What matters is +you're alive. You could have died. +I'd be better off dead. Look at me. +They got it from the cafeteria downstairs, in a tuna sandwich. Look, there's a little celery still on it. +What was it like to sting someone? +I can't explain it. It was all... All adrenaline and then...and then ecstasy! +All right. +You think it was all a trap? +Of course. I'm sorry. I flew us right into this. +What were we thinking? Look at us. We're just a couple of bugs in this world. +What will the humans do to us if they win? +I don't know. +I hear they put the roaches in motels. That doesn't sound so bad. +Adam, they check in, but they don't check out! +Oh, my. +Could you get a nurse to close that window? +Why? +The smoke. +Bees don't smoke. +Right. Bees don't smoke. +Bees don't smoke! +But some bees are smoking. +That's it! That's our case! +It is? It's not over? +Get dressed. I've gotta go somewhere. +Get back to the court and stall. Stall any way you can. +And assuming you've done step correctly, you're ready for the tub. +Mr. Flayman. +Yes? Yes, Your Honor! +Where is the rest of your team? +Well, Your Honor, it's interesting. Bees are trained to fly haphazardly, and as a result, we don't make very good time. +I actually heard a funny story about... +Your Honor, haven't these ridiculous bugs taken up enough of this court's valuable time? How much longer will we allow these absurd shenanigans to go on? +They have presented no compelling evidence to support their charges against my clients, who run legitimate businesses. +I move for a complete dismissal of this entire case! +Mr. Flayman, I'm afraid I'm going to have to consider Mr. Montgomery's motion. +But you can't! We have a terrific case. +Where is your proof? +Where is the evidence? +Show me the smoking gun! +Hold it, Your Honor! +You want a smoking gun? Here is your smoking gun. +What is that? +It's a bee smoker! +What, this? This harmless little contraption? This couldn't hurt a fly, let alone a bee. +Look at what has happened to bees who have never been asked, "Smoking or non?" Is this what nature intended for us? To be forcibly addicted to smoke machines and man-made wooden slat work camps? +Living out our lives as honey slaves to the white man? +What are we gonna do? +He's playing the species card. +Ladies and gentlemen, please, free these bees! +Free the bees! Free the bees! Free the bees! Free the bees! Free the bees! +The court finds in favor of the bees! +Vanessa, we won! +I knew you could do it! High-five! +Sorry. +I'm OK! You know what this means? +All the honey will finally belong to the bees. +Now we won't have to work so hard all the time. +This is an unholy perversion of the balance of nature, Benson. +You'll regret this. +Barry, how much honey is out there? +All right. One at a time. +Barry, who are you wearing? +My sweater is Ralph Lauren, and I have no pants. +What if Montgomery's right? +What do you mean? +We've been living the bee way a long time, 27 million years. +Congratulations on your victory. What will you demand as a settlement? +First, we'll demand a complete shutdown of all bee work camps. +Then we want back the honey that was ours to begin with, every last drop. +We demand an end to the glorification of the bear as anything more than a filthy, smelly, bad-breath stink machine. +We're all aware of what they do in the woods. +Wait for my signal. Take him out. +He'll have nauseous for a few hours, then he'll be fine. +And we will no longer tolerate bee-negative nicknames... +But it's just a prance-about stage name! +...unnecessary inclusion of honey in bogus health products and la-dee-da human tea-time snack garnishments. +Can't breathe. +Bring it in, boys! +Hold it right there! Good. +Tap it. +Mr. Buzzwell, we just passed three cups and there's gallons more coming! +I think we need to shut down! +Shut down? We've never shut down. +Shut down honey production! +Stop making honey! +Turn your key, sir! +What do we do now? +Cannonball! +We're shutting honey production! +Mission abort. +Aborting pollination and nectar detail. +Returning to base. +Adam, you wouldn't believe how much honey was out there. +Oh, yeah? +What's going on? Where is everybody? +Are they out celebrating? +They're home. +They don't know what to do. Laying out, sleeping in. +I heard your Uncle Carl was on his way to San Antonio with a cricket. +At least we got our honey back. +Sometimes I think, so what if humans liked our honey? Who wouldn't? +It's the greatest thing in the world! I was excited to be part of making it. +This was my new desk. This was my new job. I wanted to do it really well. And now... +Now I can't. +I don't understand why they're not happy. +I thought their lives would be better! +They're doing nothing. It's amazing. +Honey really changes people. +You don't have any idea what's going on, do you? +What did you want to show me? +This. +What happened here? +That is not the half of it. +Oh, no. Oh, my. +They're all wilting. +Doesn't look very good, does it? +No. +And whose fault do you think that is? +You know, I'm gonna guess bees. +Bees? +Specifically, me. +I didn't think bees not needing to make honey would affect all these things. +It's not just flowers. Fruits, vegetables, they all need bees. +That's our whole SAT test right there. +Take away produce, that affects the entire animal kingdom. +And then, of course... +The human species? +So if there's no more pollination, it could all just go south here, couldn't it? +I know this is also partly my fault. +How about a suicide pact? +How do we do it? +I'll sting you, you step on me. +That just kills you twice. +Right, right. +Listen, Barry... sorry, but I gotta get going. +I had to open my mouth and talk. +Vanessa? +Vanessa? Why are you leaving? +Where are you going? +To the final Tournament of Roses parade in Pasadena. +They've moved it to this weekend because all the flowers are dying. +It's the Last Chance I'll ever have to see it. +Vanessa, I just wanna say I'm sorry. +I never meant it to turn out like this. +I know. Me neither. +Tournament of Roses. +Roses can't do sports. +Wait a minute. Roses. Roses? +Roses! +Vanessa! +Roses?! +Barry? +Roses are flowers! +Yes, they are. +Flowers, bees, pollen! +I know. +That's why this is the last parade. +Maybe not. +Could you ask him to slow down? +Could you slow down? +Barry! +OK, I made a huge mistake. +This is a total disaster, all my fault. +Yes, it kind of is. +I've ruined the planet. I wanted to help you with the flower shop. I've made it worse. +Actually, it's completely closed down. +I thought maybe you were remodeling. +But I have another idea, and it's greater than my previous ideas combined. +I don't want to hear it! +All right, they have the roses, the roses have the pollen. +I know every bee, plant and flower bud in this park. +All we gotta do is get what they've got back here with what we've got. +Bees. +Park. +Pollen! +Flowers. +Repollination! +Across the nation! +Tournament of Roses, Pasadena, California. +They've got nothing but flowers, floats and cotton candy. +Security will be tight. +I have an idea. +Vanessa Bloome, FTD. +Official floral business. It's real. +Sorry, ma'am. Nice brooch. +Thank you. It was a gift. +Once inside, we just pick the right float. +How about The Princess and the Pea? +I could be the princess, and you could be the pea! +Yes, I got it. +Where should I sit? +What are you? +I believe I'm the pea. +The pea? +It goes under the mattresses. +Not in this fairy tale, sweetheart. +I'm getting the marshal. +You do that! This whole parade is a fiasco! +Let's see what this baby'll do. +Hey, what are you doing?! +Then all we do is blend in with traffic... without arousing suspicion. +Once at the airport, there's no stopping us. +Stop! Security. +You and your insect pack your float? +Yes. +Has it been in your possession the entire time? +Would you remove your shoes? +Remove your stinger. +It's part of me. +I know. Just having some fun. +Enjoy your flight. +Then if we're lucky, we'll have just enough pollen to do the job. +Can you believe how lucky we are? We have just enough pollen to do the job! +I think this is gonna work. +It's got to work. +Attention, passengers, this is Captain Scott. We have a bit of bad weather in New York. It looks like we'll experience a couple hours delay. +Barry, these are cut flowers with no water. They'll never make it. +I gotta get up there and talk to them. +Be careful. +Can I get help with the Sky Mall magazine? I'd like to order the talking inflatable nose and ear hair trimmer. +Captain, I'm in a real situation. +What'd you say, Hal? +Nothing. +Bee! +Don't freak out! My entire species... +What are you doing? +Wait a minute! I'm an attorney! +Who's an attorney? +Don't move. +Oh, Barry. +Good afternoon, passengers. This is your captain. Would a Miss Vanessa Bloome in 24B please report to the cockpit? And please hurry! +What happened here? +There was a DustBuster, a toupee, a life raft exploded. +One's bald, one's in a boat, they're both unconscious! +Is that another bee joke? +No! +No one's flying the plane! +This is JFK control tower, Flight 356. What's your status? +This is Vanessa Bloome. I'm a florist from New York. +Where's the pilot? +He's unconscious, and so is the copilot. +Not good. Does anyone onboard have flight experience? +As a matter of fact, there is. +Who's that? +Barry Benson. +From the honey trial?! Oh, great. +Vanessa, this is nothing more than a big metal bee. +It's got giant wings, huge engines. +I can't fly a plane. +Why not? Isn't John Travolta a pilot? +Yes. +How hard could it be? +Wait, Barry! +We're headed into some lightning. +This is Bob Bumble. We have some late-breaking news from JFK Airport, where a suspenseful scene is developing. +Barry Benson, fresh from his legal victory... +That's Barry! +...is attempting to land a plane, loaded with people, flowers and an incapacitated flight crew. +Flowers?! +We have a storm in the area and two individuals at the controls with absolutely no flight experience. +Just a minute. There's a bee on that plane. +I'm quite familiar with Mr. Benson and his no-account compadres. +They've done enough damage. +But isn't he your only hope? +Technically, a bee shouldn't be able to fly at all. +Their wings are too small... Haven't we heard this a million times? +"The surface area of the wings and body mass make no sense." +Get this on the air! +Got it. +Stand by. +We're going live. +The way we work may be a mystery to you. Making honey takes a lot of bees doing a lot of small jobs. +But let me tell you about a small job. If you do it well, it makes a big difference. +More than we realized. To us, to everyone. +That's why I want to get bees back to working together. That's the bee way! We're not made of Jell-O. +We get behind a fellow. +Black and yellow! +Hello! +Left, right, down, hover. +Hover? +Forget hover. +This isn't so hard. +Beep-beep! Beep-beep! +Barry, what happened?! +Wait, I think we were on autopilot the whole time. +That may have been helping me. +And now we're not! +So it turns out I cannot fly a plane. +All of you, let's get behind this fellow! Move it out! +Move out! +Our only chance is if I do what I'd do, you copy me with the wings of the plane! +Don't have to yell. +I'm not yelling! We're in a lot of trouble. +It's very hard to concentrate with that panicky tone in your voice! +It's not a tone. I'm panicking! +I can't do this! +Vanessa, pull yourself together. You have to snap out of it! +You snap out of it. +You snap out of it. +You snap out of it! +You snap out of it! +You snap out of it! +You snap out of it! +You snap out of it! +You snap out of it! +Hold it! +Why? Come on, it's my turn. +How is the plane flying? +I don't know. +Hello? +Benson, got any flowers for a happy occasion in there? +The Pollen Jocks! +They do get behind a fellow. +Black and yellow. +Hello. +All right, let's drop this tin can on the blacktop. +Where? I can't see anything. Can you? +No, nothing. It's all cloudy. +Come on. You got to think bee, Barry. +Thinking bee. +Thinking bee. +Thinking bee! +Thinking bee! Thinking bee! +Wait a minute. I think I'm feeling something. +What? +I don't know. It's strong, pulling me. +Like a 27-million-year-old instinct. +Bring the nose down. +Thinking bee! +Thinking bee! Thinking bee! +What in the world is on the tarmac? +Get some lights on that! +Thinking bee! +Thinking bee! Thinking bee! +Vanessa, aim for the flower. +OK. +Cut the engines. We're going in on bee power. Ready, boys? +Affirmative! +Good. Good. Easy, now. That's it. +Land on that flower! +Ready? Full reverse! +Spin it around! +Not that flower! The other one! +Which one? +That flower. +I'm aiming at the flower! +That's a fat guy in a flowered shirt. +I mean the giant pulsating flower made of millions of bees! +Pull forward. Nose down. Tail up. +Rotate around it. +This is insane, Barry! +This's the only way I know how to fly. +Am I koo-koo-kachoo, or is this plane flying in an insect-like pattern? +Get your nose in there. Don't be afraid. Smell it. Full reverse! +Just drop it. Be a part of it. +Aim for the center! +Now drop it in! Drop it in, woman! +Come on, already. +Barry, we did it! You taught me how to fly! +Yes. No high-five! +Right. +Barry, it worked! +Did you see the giant flower? +What giant flower? Where? Of course +I saw the flower! That was genius! +Thank you. +But we're not done yet. +Listen, everyone! +This runway is covered with the last pollen from the last flowers available anywhere on Earth. +That means this is our Last Chance. We're the only ones who make honey, pollinate flowers and dress like this. +If we're gonna survive as a species, this is our moment! What do you say? +Are we going to be bees, or just Museum of Natural History keychains? +We're bees! +Keychain! +Then follow me! Except Keychain. +Hold on, Barry. Here. You've earned this. +Yeah! +I'm a Pollen Jock! And it's a perfect fit. All I gotta do are the sleeves. +Oh, yeah. +That's our Barry. +Mom! The bees are back! +If anybody needs to make a call, now's the time. I got a feeling we'll be working late tonight! +Here's your change. Have a great afternoon! Can I help who's next? +Would you like some honey with that? +It is bee-approved. Don't forget these. +Milk, cream, cheese, it's all me. And I don't see a nickel! +Sometimes I just feel like a piece of meat! +I had no idea. +Barry, I'm sorry. +Have you got a moment? +Would you excuse me? +My mosquito associate will help you. +Sorry I'm late. +He's a lawyer too? +I was already a blood-sucking parasite. All I needed was a briefcase. +Have a great afternoon! +Barry, I just got this huge tulip order, and I can't get them anywhere. +No problem, Vannie. Just leave it to me. +You're a lifesaver, Barry. Can I help who's next? +All right, scramble, jocks! It's time to fly. +Thank you, Barry! +That bee is living my life! +Let it go, Kenny. +When will this nightmare end?! +Let it all go. +Beautiful day to fly. +Sure is. +Between you and me, +I was dying to get out of that office. +You have got to start thinking bee, my friend. +Thinking bee! +Me? +Hold it. Let's just stop for a second. Hold it. +I'm sorry. I'm sorry, everyone. Can we stop here? +I'm not making a major life decision during a production number! +All right. Take ten, everybody. Wrap it up, guys. +I had virtually no rehearsal for that. diff --git a/crates/screens/macros/Cargo.toml b/crates/screens/macros/Cargo.toml new file mode 100644 index 0000000..10e82bf --- /dev/null +++ b/crates/screens/macros/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "q_screens_derive" +version = "0.1.0" +edition = "2024" + +[lib] +proc-macro=true + +[dependencies] +proc-macro2 = "1.0.106" +quote = "1.0.44" +syn = "2.0.114" + +[lints] +workspace = true diff --git a/crates/screens/macros/src/lib.rs b/crates/screens/macros/src/lib.rs new file mode 100644 index 0000000..5d62e7b --- /dev/null +++ b/crates/screens/macros/src/lib.rs @@ -0,0 +1,15 @@ +extern crate proc_macro; +use proc_macro::TokenStream; +use quote::quote; +use syn::{DeriveInput, parse_macro_input}; + +/// Proc macro deriving the Screen trait. +#[proc_macro_derive(Screen)] +pub fn derive_screen(ts: TokenStream) -> TokenStream { + let input = parse_macro_input!(ts as DeriveInput); + let ident = input.ident; + quote! { + impl Screen for #ident {} + } + .into() +} diff --git a/crates/screens/src/data.rs b/crates/screens/src/data.rs new file mode 100644 index 0000000..6332be2 --- /dev/null +++ b/crates/screens/src/data.rs @@ -0,0 +1,456 @@ +use crate::prelude::*; +use bevy::{ + ecs::{ + component::ComponentId, + schedule::ScheduleLabel, + system::{ReadOnlySystemParam, SystemParam}, + }, + platform::collections::HashMap, +}; +use std::{any::TypeId, marker::PhantomData}; + +mod general_api { + use super::*; + + /// Call this when you want to switch screens. This will trigger a + /// [SwitchToScreenMsg] with the screen's [ComponentId]. + #[derive(Event, Debug, PartialEq, Eq, Clone, Deref, Default)] + pub struct SwitchToScreen(PhantomData); + pub fn switch_to_screen() -> SwitchToScreen { + SwitchToScreen::::default() + } + + /// Switches to the given screen by its [ComponentId]. When possible, prefer + /// to use [SwitchToScreen] to ensure type safety. This is a [Message] so we + /// can buffer any [SwitchToScreenMsg]s to avoid conflicts. Only the last + /// valid [SwitchToScreenMsg] will be read. + #[derive(Message, Debug, PartialEq, Eq, Clone, Deref)] + pub struct SwitchToScreenMsg(pub ComponentId); + + /// Scopes an entity to the current screen. The entity will be cleaned up when + /// the [Screens] state changes. By default, all entities _except_ those listed + /// in the [module documentation](crate::framework::screen) are screen-scoped. + /// + /// Note: This is effectively used to skip the propagation of the + /// [Persistent] component. Since screen scoping is the default behavior, it + /// should not be necessary to add this component in other cases. + #[derive(Component, Debug, Reflect, Clone, Copy, Default, PartialEq)] + pub struct ScreenScoped; + + /// Marks an entity as screen-persistent, i.e., this entity will _not_ be + /// automatically cleaned up when the screen changes. By default, all entites + /// _except_ those listed in the [module + /// documentation](crate::framework::screen) are screen-scoped. + /// + /// In order to mark the children of this component as Persistent, you should + /// use the [Propagate](bevy::app::Propagate) component. + #[derive(Component, Debug, Reflect, Clone, Copy, Default, PartialEq)] + pub struct Persistent; + + /// The first screen. Typically this will be a splash screen, a loading + /// screen, or a main menu. + #[derive(Resource, Default, Debug, Deref)] + pub struct InitialScreen(Option); + impl InitialScreen { + pub fn new() -> Self { + Self(Some(S::name())) + } + pub fn from_name(name: String) -> Self { + Self(Some(name)) + } + } +} +pub use general_api::*; + +mod screens { + use bevy::ecs::change_detection::Tick; + + use super::*; + + /// Marker struct for a screen. + #[derive(Component, Reflect, PartialEq)] + pub struct ScreenMarker(pub ComponentId); + + /// Stores a map from the system's name to its spawn function. + /// Used to dynamically load a screen. + #[derive(Resource, Debug, Deref, DerefMut, Default)] + pub struct ScreenRegistry(HashMap); + + /// Data about a given screen. This is where all the screen's identifying information lives, including it's [ScreenState]. + #[derive(Debug)] + pub struct ScreenData { + /// Serialized name of the [Screen] + name: String, + id: ComponentId, + state: ScreenState, + /// TypeId of the underlying [Screen] component + type_id: TypeId, + /// Indicates that the state has changed and needs to run the corresponding state schedule. + pub(crate) needs_update: bool, + pub(crate) changed_at: Tick, + pub(crate) initialized: bool, + /// Should the Update schedule run even while loading? + load_strategy: LoadStrategy, + /// Initialize directly into Ready. + skip_load: bool, + /// Deinitialize immediately + skip_unload: bool, + } + impl ScreenData { + pub fn new(id: ComponentId, tick: Tick) -> Self { + Self { + name: S::name(), + id, + state: ScreenState::Unloaded, + type_id: TypeId::of::(), + needs_update: true, + skip_load: true, + skip_unload: true, + load_strategy: LoadStrategy::Blocking, + changed_at: tick, + initialized: false, + } + } + + /// Loads the screen. + /// Has no effect if already in Loading or Ready states. + pub fn load(&mut self, tick: Tick) { + if matches!(self.state, ScreenState::Unloaded | ScreenState::Unloading) { + if self.skip_load { + self.state = ScreenState::Ready + } else { + self.state = ScreenState::Loading; + } + self.needs_update = true; + self.changed_at = tick; + } + } + + /// Unloads the screen. + /// Has no effect if already in Unloading or Unloaded states. + pub fn unload(&mut self, tick: Tick) { + if matches!(self.state, ScreenState::Loading | ScreenState::Ready) { + if self.skip_unload { + self.state = ScreenState::Unloaded + } else { + self.state = ScreenState::Unloading; + } + self.needs_update = true; + self.changed_at = tick; + } + } + /// Finishes loading the screen. + /// Has no effect if already in Loading or Ready states. + pub fn finish_loading(&mut self, tick: Tick) { + if matches!(self.state, ScreenState::Loading) { + self.state = ScreenState::Ready; + self.needs_update = true; + self.changed_at = tick; + } + } + /// Finishes loading the screen. + /// Has no effect if already in Loading or Ready states. + pub fn finish_unloading(&mut self, tick: Tick) { + if matches!(self.state, ScreenState::Unloading) { + self.state = ScreenState::Unloaded; + self.needs_update = true; + self.changed_at = tick; + } + } + + pub fn load_strategy(&self) -> LoadStrategy { + self.load_strategy + } + + pub fn skip_load(&self) -> bool { + self.skip_load + } + + pub fn skip_unload(&self) -> bool { + self.skip_unload + } + + pub fn set_skip_unload(&mut self, skip_unload: bool) { + self.skip_unload = skip_unload; + } + + pub fn set_skip_load(&mut self, skip_load: bool) { + self.skip_load = skip_load; + } + + pub fn set_load_strategy(&mut self, load_strategy: LoadStrategy) { + self.load_strategy = load_strategy; + } + + pub fn initialized(&self) -> bool { + self.initialized + } + + pub fn changed_at(&self) -> Tick { + self.changed_at + } + + pub fn needs_update(&self) -> bool { + self.needs_update + } + + pub fn type_id(&self) -> TypeId { + self.type_id + } + + pub fn state(&self) -> ScreenState { + self.state + } + + pub fn id(&self) -> ComponentId { + self.id + } + + pub fn name(&self) -> &str { + &self.name + } + } +} +pub use screens::*; + +mod schedules { + use super::*; + /// Describes a screen's [Schedule]. All systems added to this schedule, using the + /// [ScreenScope] below, will be scoped to this screen's lifetime. That is, + /// they will only run when the screen is in [ScreenStatus::Ready]. + /// To use as a schedule, wrap it with [ScreenScheduleLabel]. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::EnumIter)] + pub enum ScreenSchedule { + Update, + FixedUpdate, + Loading, + Unloading, + /// Can also be specified as [on_screen_load] + OnLoad, + /// Can also be specified as [on_screen_ready] + OnReady, + /// Can also be specified as [on_screen_unload] + OnUnload, + /// Can also be specified as [on_screen_unloaded] + OnUnloaded, + } + + /// Wrapper around [ScreenSchedule]. Needed to make schedules unique per type. + #[derive(ScheduleLabel, Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub struct ScreenScheduleLabel { + id: TypeId, + kind: ScreenSchedule, + } + impl ScreenScheduleLabel { + pub fn new(kind: ScreenSchedule) -> Self { + Self { + id: TypeId::of::(), + kind, + } + } + pub fn from_id(kind: ScreenSchedule, id: TypeId) -> Self { + Self { id, kind } + } + } +} +pub use schedules::*; + +/// Describes the current state of a screen. Not an actual [State]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub enum ScreenState { + #[default] + Unloaded, + Loading, + Ready, + Unloading, +} +impl ScreenState { + pub fn is_ready(&self) -> bool { + matches!(self, Self::Ready) + } + pub fn is_loading(&self) -> bool { + matches!(self, Self::Loading) + } + pub fn is_unloading(&self) -> bool { + matches!(self, Self::Unloading) + } + pub fn is_unloaded(&self) -> bool { + matches!(self, Self::Unloaded) + } +} + +mod system_params { + use bevy::ecs::change_detection::Tick; + + use super::*; + + /// Read-only [SystemParam] for easy access to a screen's [ScreenData] + pub struct ScreenDataRef<'w, S: Screen> { + data: &'w ScreenData, + _ghost: PhantomData, + } + impl<'w, S: Screen> ScreenDataRef<'w, S> { + pub fn data(&self) -> &'w ScreenData { + self.data + } + } + + unsafe impl<'w, S: Screen> SystemParam for ScreenDataRef<'w, S> { + type State = (); + type Item<'world, 'state> = ScreenDataRef<'world, S>; + + fn init_state(_world: &mut World) -> Self::State {} + + fn init_access( + _state: &Self::State, + _system_meta: &mut bevy::ecs::system::SystemMeta, + component_access_set: &mut bevy::ecs::query::FilteredAccessSet, + world: &mut World, + ) { + component_access_set + .add_unfiltered_resource_read(world.resource_id::().unwrap()); + } + + unsafe fn get_param<'world, 'state>( + _state: &'state mut Self::State, + _system_meta: &bevy::ecs::system::SystemMeta, + world: bevy::ecs::world::unsafe_world_cell::UnsafeWorldCell<'world>, + _change_tick: bevy::ecs::change_detection::Tick, + ) -> Self::Item<'world, 'state> { + let cid = world.components().get_id(TypeId::of::()).unwrap(); + let registry = unsafe { world.get_resource::().unwrap() }; + let data = registry.get(&cid).unwrap(); + ScreenDataRef { + _ghost: PhantomData, + data, + } + } + } + unsafe impl<'w, S: Screen> ReadOnlySystemParam for ScreenDataRef<'w, S> {} + + /// [SystemParam] for easy mutable access to the given screen's data. + /// All functionality happens through helper functions for API sanity. + pub struct ScreenDataMut<'w, S: Screen> { + _ghost: PhantomData, + registry: Mut<'w, ScreenRegistry>, + cid: ComponentId, + change_tick: Tick, + } + impl<'w, S: Screen> ScreenDataMut<'w, S> { + /// Loads the screen. Has no effect if the screen is already Loaded or Ready. + pub fn load(&mut self) { + let tick = self.change_tick; + self.data_mut().load(tick); + } + /// Unloads the screen. Has no effect if the screen is already Loaded or Ready. + pub fn unload(&mut self) { + let tick = self.change_tick; + self.data_mut().unload(tick); + } + /// Loads the screen. Has no effect if the screen is not Loading. + pub fn finish_loading(&mut self) { + let tick = self.change_tick; + self.data_mut().finish_loading(tick); + } + /// Loads the screen. Has no effect if the screen is not Loading. + pub fn finish_unloading(&mut self) { + let tick = self.change_tick; + self.data_mut().finish_unloading(tick); + } + pub fn data(&self) -> &ScreenData { + self.registry.get(&self.cid).unwrap() + } + fn data_mut(&mut self) -> &mut ScreenData { + self.registry.get_mut(&self.cid).unwrap() + } + } + unsafe impl<'w, S: Screen> SystemParam for ScreenDataMut<'w, S> { + type State = (); + type Item<'world, 'state> = ScreenDataMut<'world, S>; + + fn init_state(_world: &mut World) -> Self::State {} + + fn init_access( + _state: &Self::State, + _system_meta: &mut bevy::ecs::system::SystemMeta, + component_access_set: &mut bevy::ecs::query::FilteredAccessSet, + world: &mut World, + ) { + component_access_set + .add_unfiltered_resource_write(world.resource_id::().unwrap()); + } + + unsafe fn get_param<'world, 'state>( + _state: &'state mut Self::State, + _system_meta: &bevy::ecs::system::SystemMeta, + world: bevy::ecs::world::unsafe_world_cell::UnsafeWorldCell<'world>, + change_tick: bevy::ecs::change_detection::Tick, + ) -> Self::Item<'world, 'state> { + let registry = unsafe { world.get_resource_mut::().unwrap() }; + let cid = world.components().get_id(TypeId::of::()).unwrap(); + Self::Item { + registry, + cid, + _ghost: PhantomData, + change_tick, + } + } + } +} +pub use system_params::*; + +mod helpers { + pub use super::*; + + /// Condition, like [in_state], but for screens. + pub fn screen_has_state( + state: ScreenState, + ) -> impl FnMut(ScreenDataRef) -> bool + Clone { + move |data: ScreenDataRef| data.data().state() == state + } + /// Is the screen still loading? + pub fn screen_loading() -> impl FnMut(ScreenDataRef) -> bool + Clone { + |data: ScreenDataRef| matches!(data.data().state(), ScreenState::Loading) + } + /// Has the screen finished loading? + pub fn screen_ready() -> impl FnMut(ScreenDataRef) -> bool + Clone { + |data: ScreenDataRef| matches!(data.data().state(), ScreenState::Ready) + } + /// Is the screen currently unloading? + pub fn screen_unloading() -> impl FnMut(ScreenDataRef) -> bool + Clone { + |data: ScreenDataRef| matches!(data.data().state(), ScreenState::Unloading) + } + /// Has the screen finished unloading? + pub fn screen_unloaded() -> impl FnMut(ScreenDataRef) -> bool + Clone { + |data: ScreenDataRef| matches!(data.data().state(), ScreenState::Unloaded) + } + + /// Label of a schedule which fires when the screen has begun to load. + #[derive(ScheduleLabel, Debug, PartialEq, Eq, Hash, Clone, Copy)] + pub struct OnScreenLoad(pub TypeId); + pub fn on_screen_load() -> impl ScheduleLabel { + OnScreenLoad(TypeId::of::()) + } + + /// Label of a schedule which fires when the screen has finished loading. + #[derive(ScheduleLabel, Debug, PartialEq, Eq, Hash, Clone, Copy)] + pub struct OnScreenReady(pub TypeId); + pub fn on_screen_ready() -> impl ScheduleLabel { + OnScreenReady(TypeId::of::()) + } + + /// Label of a schedule which fires when the screen is beginning to unload. Not to be confused with [OnScreenUnloaded]. + #[derive(ScheduleLabel, Debug, PartialEq, Eq, Hash, Clone, Copy)] + pub struct OnScreenUnload(pub TypeId); + pub fn on_screen_unload() -> impl ScheduleLabel { + OnScreenUnload(TypeId::of::()) + } + + /// Label of a schedule which fires when the screen has finished unloading and is no longer active. + #[derive(ScheduleLabel, Debug, PartialEq, Eq, Hash, Clone, Copy)] + pub struct OnScreenUnloaded(pub TypeId); + pub fn on_screen_unloaded() -> impl ScheduleLabel { + OnScreenUnloaded(TypeId::of::()) + } +} +pub use helpers::*; diff --git a/crates/tfw/src/screen/doc.md b/crates/screens/src/doc.md similarity index 100% rename from crates/tfw/src/screen/doc.md rename to crates/screens/src/doc.md diff --git a/crates/screens/src/lib.rs b/crates/screens/src/lib.rs new file mode 100644 index 0000000..ef961d3 --- /dev/null +++ b/crates/screens/src/lib.rs @@ -0,0 +1,23 @@ +#![feature(register_tool)] +#![register_tool(bevy)] +#![allow(bevy::panicking_methods)] +#![doc = include_str!("./doc.md")] + +mod data; +mod plugin; +mod scope; +mod systems; +mod trait_impl; + +pub mod prelude { + pub use super::data::*; + pub use super::plugin::*; + pub use super::scope::*; + pub(crate) use super::systems::*; + pub use super::trait_impl::*; + pub(crate) use bevy::prelude::*; + pub(crate) use itertools::Itertools; + pub use q_screens_derive::*; + pub(crate) use std::marker::PhantomData; + pub(crate) use tiny_bail::prelude::*; +} diff --git a/crates/screens/src/plugin.rs b/crates/screens/src/plugin.rs new file mode 100644 index 0000000..b58e3a1 --- /dev/null +++ b/crates/screens/src/plugin.rs @@ -0,0 +1,20 @@ +use bevy::app::HierarchyPropagatePlugin; + +use crate::prelude::*; +/// The main export plugin for TFW. `Screens` should be an enum with screen +/// names. Refer to the template documentation for more details. +/// The template parameter refers to the initial screen. +#[derive(Default, Debug)] +pub struct ScreenPlugin; +impl Plugin for ScreenPlugin { + fn build(&self, app: &mut App) { + app.init_resource::(); + app.init_resource::(); + app.add_message::(); + app.add_plugins(( + HierarchyPropagatePlugin::::new(PostUpdate), + HierarchyPropagatePlugin::::new(PostUpdate), + )); + app.add_plugins(super::systems::plugin); + } +} diff --git a/crates/screens/src/scope.rs b/crates/screens/src/scope.rs new file mode 100644 index 0000000..3128d3c --- /dev/null +++ b/crates/screens/src/scope.rs @@ -0,0 +1,206 @@ +pub use crate::prelude::*; +use bevy::{ecs::system::ScheduleSystem, platform::collections::HashMap}; +use strum::IntoEnumIterator; + +pub trait RegisterScreen { + /// Registers a [Screen] to the application. + fn register_screen(&mut self) -> &mut Self; +} +impl RegisterScreen for App { + fn register_screen(&mut self) -> &mut Self { + S::builder(ScreenScopeBuilder::::new()).build(self); + self + } +} + +// TODO: DOCUMENT ME +pub struct ScreenScopeBuilder +where + S: Screen, +{ + schedules: HashMap, + skip_load: Option, + skip_unload: Option, + load_strategy: LoadStrategy, + _ghost: PhantomData, +} + +impl ScreenScopeBuilder +where + S: Screen, +{ + pub fn new() -> Self { + let schedules = ScreenSchedule::iter() + .map(|kind| (kind, Schedule::new(ScreenScheduleLabel::new::(kind)))) + .collect::>(); + Self { + schedules, + skip_load: None, + skip_unload: None, + load_strategy: LoadStrategy::default(), + _ghost: PhantomData, + } + } + + /// Initialize directly into ready state. By default this is true, unless + /// there are systems present in the Load schedule. + pub fn with_skip_load(&mut self, val: bool) -> &mut Self { + self.skip_load = Some(val); + self + } + /// Deinitialize directly into unloaded state. By default this is true, + /// unless there are systems present in the Unload schedule. + pub fn with_skip_unload(&mut self, val: bool) -> &mut Self { + self.skip_unload = Some(val); + self + } + /// Sets the [LoadingStrategy]. By default, this is Blocking. + pub fn with_load_strategy(&mut self, val: LoadStrategy) -> &mut Self { + self.load_strategy = val; + self + } + + /// Add systems to the schedule scope. Will run in the specified schedule. + /// + /// The following schedules run on every (fixed) update: + /// + /// - Update + /// - FixedUpdate + /// - Loading + /// - Unloading + /// + /// ... While the following run only on screen state transitions: + /// + /// - OnLoad + /// - OnReady + /// - OnUnload + /// - OnUnloaded + /// + /// Note that adding an `On` system _will not_ automatically enable loading + /// or unloading for this screen. Make sure you either have systems in the + /// [ScreenSchedule::Load](ScreenSchedule) schedule, or you manually set + /// [with_skip_load(false)](ScreenScopeBuilder::with_skip_load), or the + /// analgous for unloading. + pub fn add_systems( + &mut self, + kind: ScreenSchedule, + systems: impl IntoScheduleConfigs, + ) -> &mut Self { + self.schedules + .entry(kind) + .or_insert(Schedule::new(ScreenScheduleLabel::new::(kind))) + .add_systems(systems); + self + } + + fn build(self, app: &mut App) { + // init + let id = app.world_mut().register_component::(); + let tick = app.world_mut().change_tick(); + let mut registry = app.world_mut().get_resource_or_init::(); + + // insert data + let mut data = ScreenData::new::(id, tick); + let skip_load = self + .schedules + .get(&ScreenSchedule::Loading) + .map(|v| v.systems_len() == 0) + .unwrap_or_default(); + let skip_unload = self + .schedules + .get(&ScreenSchedule::Unloading) + .map(|v| v.systems_len() == 0) + .unwrap_or_default(); + data.set_skip_load(self.skip_load.unwrap_or(skip_load)); + data.set_skip_unload(self.skip_unload.unwrap_or(skip_unload)); + data.set_load_strategy(self.load_strategy); + debug!("Built screen {data:#?}"); + registry.insert(id, data); + + // watch screen switcher + app.add_observer(on_switch_screen::); + info!("watching on_switch_screen for {}", S::name()); + + // scope systems + for (kind, schedule) in self.schedules.into_iter() { + let label = schedule.label(); + match kind { + ScreenSchedule::OnLoad => { + app.add_systems(on_screen_load::(), move |mut commands: Commands| { + commands.run_schedule(label) + }); + } + ScreenSchedule::OnReady => { + let label = schedule.label(); + app.add_systems(on_screen_ready::(), move |mut commands: Commands| { + commands.run_schedule(label) + }); + } + ScreenSchedule::OnUnload => { + let label = schedule.label(); + app.add_systems(on_screen_unload::(), move |mut commands: Commands| { + commands.run_schedule(label) + }); + } + ScreenSchedule::OnUnloaded => { + let label = schedule.label(); + app.add_systems(on_screen_unloaded::(), move |mut commands: Commands| { + commands.run_schedule(label) + }); + } + _ => { + // run on update, see [run_schedules](systems.rs) + } + } + app.add_schedule(schedule); + } + + // Lifecycle + #[cfg(debug_assertions)] + { + app.add_systems(on_screen_load::(), || debug!("Loading {:?}", S::name())); + app.add_systems(on_screen_ready::(), || debug!("Ready {:?}", S::name())); + app.add_systems(on_screen_unload::(), || { + debug!("Unloading {:?}", S::name()) + }); + app.add_systems(on_screen_unloaded::(), || { + debug!("Unloaded {:?}", S::name()) + }); + } + app.add_systems(on_screen_unloaded::(), clean_up_scoped_entities::); + } +} + +impl Default for ScreenScopeBuilder +where + S: Screen, +{ + fn default() -> Self { + Self::new() + } +} + +fn clean_up_scoped_entities( + mut commands: Commands, + mut screen_data: ScreenDataMut, + // Any entity which is (explicitly marked as ScreenScoped, or is _not_ marked + // as persistent) _and_ is not a top-level observer + screen_scoped: Query< + Entity, + ( + Or<( + With, // is explicitly screen-scoped + Without, // is explicitly persistent + )>, + ), + >, + top_levels: Query, With)>, Without)>, +) { + screen_scoped + .iter() + .filter(|c| !top_levels.iter().contains(c)) + .for_each(|e| { + commands.entity(e).detach_all_children().despawn(); + }); + screen_data.unload(); +} diff --git a/crates/screens/src/systems.rs b/crates/screens/src/systems.rs new file mode 100644 index 0000000..a38f02c --- /dev/null +++ b/crates/screens/src/systems.rs @@ -0,0 +1,148 @@ +//! This module contains all systems, including observers. + +use crate::prelude::*; +use bevy::ecs::{component::ComponentIdFor, system::SystemChangeTick}; + +fn handle_switch_msg( + mut reader: MessageReader, + mut registry: ResMut, + tick: SystemChangeTick, +) { + // get the most recent valid message, then load it and unload all others + if reader.is_empty() { + return; + } + let vec = reader.read().collect::>(); + let msg_key = vec.iter().rev().find(|msg| registry.get(&msg.0).is_some()); + let msg_key = rq!(msg_key); + for (key, data) in registry.iter_mut() { + if *key == ***msg_key { + data.load(tick.this_run()); + } else { + data.unload(tick.this_run()); + } + } +} +/// NOTE: This is registered in scope.rs +pub fn on_switch_screen( + _trigger: On>, + id: ComponentIdFor, + mut commands: Commands, +) { + commands.write_message(SwitchToScreenMsg(id.get())); +} + +fn run_schedules( + mut registry: ResMut, + mut commands: Commands, + tick: SystemChangeTick, + screens: Query<&ScreenMarker>, +) { + for data in registry.values_mut() { + if matches!(data.state(), ScreenState::Loading | ScreenState::Ready) + && !screens.iter().contains(&ScreenMarker(data.id())) + { + commands.spawn((ScreenMarker(data.id()), Name::new(data.name().to_owned()))); + } + match data.state() { + ScreenState::Unloaded => { + if !data.initialized { + data.initialized = true; + data.needs_update = false; + data.changed_at = tick.this_run(); + } + if data.needs_update { + commands.run_schedule(OnScreenUnloaded(data.type_id())); + data.needs_update = false; + data.changed_at = tick.this_run(); + } + } + ScreenState::Loading => { + commands.run_schedule(ScreenScheduleLabel::from_id( + ScreenSchedule::Loading, + data.type_id(), + )); + if data.needs_update { + commands.run_schedule(OnScreenLoad(data.type_id())); + data.needs_update = false; + data.changed_at = tick.this_run(); + } + if matches!(data.load_strategy(), LoadStrategy::Nonblocking) { + commands.run_schedule(ScreenScheduleLabel::from_id( + ScreenSchedule::Update, + data.type_id(), + )); + } + } + ScreenState::Ready => { + commands.run_schedule(ScreenScheduleLabel::from_id( + ScreenSchedule::Update, + data.type_id(), + )); + if data.needs_update { + commands.run_schedule(OnScreenReady(data.type_id())); + data.needs_update = false; + data.changed_at = tick.this_run(); + } + } + ScreenState::Unloading => { + commands.run_schedule(ScreenScheduleLabel::from_id( + ScreenSchedule::Unloading, + data.type_id(), + )); + if data.needs_update { + commands.run_schedule(OnScreenUnload(data.type_id())); + data.needs_update = false; + data.changed_at = tick.this_run(); + } + } + } + } +} + +fn run_fixed_schedules(registry: ResMut, mut commands: Commands) { + for data in registry.values() { + match data.state() { + ScreenState::Loading => { + if matches!(data.load_strategy(), LoadStrategy::Nonblocking) { + commands.run_schedule(ScreenScheduleLabel::from_id( + ScreenSchedule::FixedUpdate, + data.type_id(), + )); + } + } + ScreenState::Ready => { + commands.run_schedule(ScreenScheduleLabel::from_id( + ScreenSchedule::FixedUpdate, + data.type_id(), + )); + } + _ => {} + } + } +} + +pub fn initial_screen( + mut commands: Commands, + initial_screen: Res, + registry: Res, +) { + if let Some(initial_screen) = (*initial_screen).as_ref() { + if let Some(cid) = registry + .values() + .find_map(|v| (v.name() == initial_screen).then_some(v.id())) + { + info!("Switching to initial screen {}", *initial_screen); + commands.write_message(SwitchToScreenMsg(cid)); + } else { + warn!("Could not find screen with name {initial_screen}"); + } + } +} + +pub fn plugin(app: &mut App) { + app.add_systems(Startup, initial_screen); + app.add_systems(PostUpdate, handle_switch_msg); + app.add_systems(Update, run_schedules); + app.add_systems(FixedUpdate, run_fixed_schedules); +} diff --git a/crates/screens/src/trait_impl.rs b/crates/screens/src/trait_impl.rs new file mode 100644 index 0000000..a02b152 --- /dev/null +++ b/crates/screens/src/trait_impl.rs @@ -0,0 +1,44 @@ +pub use crate::prelude::*; + +/// An empty settings parameter. +#[derive(Resource, Default)] +pub struct NoSettings; + +/// How should the screen load its assets? +/// If `LoadingStrategy` is Blocking, the screen's systems will not run until +/// loading is complete. If it is Nonblocking, the screen's systems will run +/// regardless of asset completion status. +#[derive(Default, Copy, Clone, Debug, PartialEq, Eq, Reflect)] +pub enum LoadStrategy { + #[default] + Blocking, + Nonblocking, +} + +/// Implementation trait for Screen components. +pub trait Screen: + Component + + Sized + + Default + + Reflect + + std::fmt::Debug + + Clone + + Copy + + Eq + + std::hash::Hash + + Send + + Sync + + 'static +{ + /// The screen's public name. Used for serialization. Defaults to the short type path. + fn name() -> String { + let default = Self::default(); + Reflect::as_reflect(&default) + .reflect_short_type_path() + .to_owned() + } + + /// Get the builder for this screen. Used to scope systems. + /// Don't forget to register your screen! [App::register_screen] + fn builder(builder: ScreenScopeBuilder) -> ScreenScopeBuilder; +} diff --git a/crates/screens/tests/screen_tests/entity_scoping.rs b/crates/screens/tests/screen_tests/entity_scoping.rs new file mode 100644 index 0000000..cc8dcb1 --- /dev/null +++ b/crates/screens/tests/screen_tests/entity_scoping.rs @@ -0,0 +1,174 @@ +use q_test_harness::prelude::*; + +use crate::prelude::*; + +// #[test] +// fn screen_transitions() { +// let mut app = get_test_app::(); +// app.add_step( +// 0, +// |mut step: ResMut>, +// mut settings: ResMut, +// mut commands: Commands| { +// settings.entity_name = "1".into(); +// commands.trigger(SwitchToScreen::::default()); +// step.set(Step(1)); +// }, +// ) +// .add_step( +// 1, +// |mut step: ResMut>, +// mut commands: Commands, +// q: Query<(Entity, &Name)>, +// data: ScreenDataRef| { +// if !data.data().state.is_ready() { +// return; +// } +// commands.log_hierarchy(); +// let found = q.iter().any(|(_, ename)| (**ename).eq("1")); +// if !found { +// error!("Could not find entity with name '1'"); +// commands.write_message(AppExit::error()); +// return; +// } +// commands.trigger(SwitchToScreen::::default()); +// step.set(Step(2)); +// }, +// ) +// .add_step( +// 2, +// |mut step: ResMut>, +// mut settings: ResMut, +// mut commands: Commands, +// q: Query<(Entity, &Name)>, +// data: ScreenDataRef| { +// if !data.data().state.is_ready() { +// return; +// } +// commands.log_hierarchy(); +// let found = q.iter().any(|(_, ename)| (**ename).eq("1")); +// if found { +// error!("Could not find entity with name '1'"); +// commands.write_message(AppExit::error()); +// return; +// } +// settings.entity_name = "2".into(); +// commands.trigger(SwitchToScreen::::default()); +// step.set(Step(3)); +// }, +// ) +// .add_step( +// 3, +// |mut commands: Commands, +// q: Query<(Entity, &Name)>, +// data: ScreenDataRef| { +// if !data.data().state.is_ready() { +// return; +// } +// commands.log_hierarchy(); +// let found = q.iter().any(|(_, ename)| (**ename).eq("2")); +// if !found { +// error!("Could not find entity with name '2'"); +// commands.write_message(AppExit::error()); +// return; +// } +// commands.write_message(AppExit::Success); +// }, +// ); + +// assert!(app.run().is_success()); +// } + +// #[test] +// fn persistent_entities() { +// let mut app = get_test_app::(); +// app.insert_resource(NamedEntityScreenSettings { +// entity_name: "1".into(), +// }); +// app.add_step( +// 0, +// |mut commands: Commands, data: ScreenDataRef| { +// if !data.data().state.is_ready() { +// return; +// } +// commands.spawn(( +// Name::new("Persistent"), +// bevy::app::Propagate(Persistent), +// children![( +// Name::new("Child"), +// children![( +// Name::new("Grandchild"), +// bevy::app::PropagateStop::::default(), +// children![Name::new("Great Grandchild")] +// )] +// )], +// )); +// commands.log_hierarchy(); +// commands.find_entity("Persistent"); +// commands.find_entity_filtered::>("Child"); +// commands.find_entity_filtered::>("Grandchild"); +// commands.find_entity_filtered::>("Great Grandchild"); +// commands.find_entity_filtered::>("1"); +// commands.trigger(SwitchToScreen::::default()); +// }, +// ) +// .add_step( +// 1, +// |mut commands: Commands, data: ScreenDataRef| { +// if !data.data().state.is_ready() { +// return; +// } +// commands.log_hierarchy(); +// commands.find_entity("Persistent"); +// commands.find_entity("Child"); +// commands.find_no_entity("Grandchild"); +// commands.find_no_entity("Great Grandchild"); +// commands.find_no_entity("1"); +// }, +// ); +// } + +// #[derive(Component)] +// struct Empty; + +// /// Child observers should be removed, but top-level observers should remain. +// /// NOTE: Child observers _probably_ shouldn't exist. This functionality has been +// /// replaced with [EntityEvent]. But, this checks the scoping query functions as intended. +// #[test] +// fn observer_cleanup() { +// let mut app = get_test_app::(); +// app.add_step( +// 0, +// |mut commands: Commands, +// data: ScreenDataRef, +// mut step: ResMut>| { +// if !data.data().state.is_ready() { +// return; +// } +// commands.spawn(( +// Name::new("Parent"), +// children![( +// Name::new("Child"), +// Observer::new(|trigger: On>| { +// info!("Observer ({:?})", *trigger) +// }), +// Empty +// )], +// )); +// commands.find_entity("Parent"); +// commands.find_entity("Child"); +// commands.trigger(SwitchToScreen::::default()); +// step.set(Step(1)); +// }, +// ) +// .add_step( +// 1, +// |mut commands: Commands, data: ScreenDataRef| { +// if !data.data().state.is_ready() { +// return; +// } +// commands.find_no_entity("Parent"); +// commands.find_no_entity("Child"); +// }, +// ); +// } diff --git a/crates/screens/tests/screens/empty.rs b/crates/screens/tests/screens/empty.rs new file mode 100644 index 0000000..fc9ed06 --- /dev/null +++ b/crates/screens/tests/screens/empty.rs @@ -0,0 +1,9 @@ +use crate::prelude::*; + +#[derive(Component, Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Reflect)] +pub struct EmptyScreen; +impl Screen for EmptyScreen { + fn builder(builder: ScreenScopeBuilder) -> ScreenScopeBuilder { + builder + } +} diff --git a/crates/screens/tests/screens/entity_scope.rs b/crates/screens/tests/screens/entity_scope.rs new file mode 100644 index 0000000..efd04b6 --- /dev/null +++ b/crates/screens/tests/screens/entity_scope.rs @@ -0,0 +1,94 @@ +use bevy::{ + app::Propagate, + ecs::{lifecycle::HookContext, world::DeferredWorld}, +}; +use itertools::Itertools; + +use crate::prelude::*; + +#[derive(Component, PartialEq, Debug, Copy, Clone)] +#[component(on_insert = Self::on_insert)] +enum Target { + PersistentParent, + PersistentChild, + PersistentGrandchild, + PersistentGreatGrandchild, + ScopedGrandchild, + ScopedParent, + ScopedChild, +} +impl Target { + fn on_insert(mut world: DeferredWorld, ctx: HookContext) { + let this = *world.get::(ctx.entity).unwrap(); + world + .commands() + .entity(ctx.entity) + .insert(Name::new(format!("{:?}", this))); + } +} + +#[derive(Component, Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Reflect)] +pub struct ScopedEntitiesScreen; +impl Screen for ScopedEntitiesScreen { + fn builder(mut builder: ScreenScopeBuilder) -> ScreenScopeBuilder { + builder.add_systems( + ScreenSchedule::Loading, + |mut commands: Commands, mut data: ScreenDataMut| { + commands.spawn(( + Target::PersistentParent, + Propagate(Persistent), + children![ + Target::PersistentChild, + children![( + Target::ScopedGrandchild, + ScreenScoped, + children![Target::PersistentGreatGrandchild] + )] + ], + )); + commands.spawn(( + Target::ScopedParent, + children![ + Target::ScopedChild, + children![(Target::PersistentGrandchild, Persistent)] + ], + )); + commands.log_hierarchy(); + data.finish_loading(); + }, + ); + builder.add_systems(ScreenSchedule::OnReady, |mut commands: Commands| { + commands.trigger(switch_to_screen::()); + }); + builder.add_systems( + ScreenSchedule::OnUnloaded, + |mut commands: Commands, query: Query<&Target>| { + let mut ok = true; + ok = ok && query.iter().contains(&Target::PersistentParent); + ok = ok && query.iter().contains(&Target::PersistentChild); + ok = ok && query.iter().contains(&Target::PersistentGrandchild); + ok = ok && query.iter().contains(&Target::PersistentGreatGrandchild); + ok = ok && !query.iter().contains(&Target::ScopedParent); + ok = ok && !query.iter().contains(&Target::ScopedChild); + ok = ok && !query.iter().contains(&Target::ScopedGrandchild); + if ok { + commands.log_hierarchy(); + commands.write_message(AppExit::Success); + } else { + error!("Bad hierarchy."); + commands.log_hierarchy(); + commands.write_message(AppExit::error()); + } + }, + ); + builder + } +} + +type Scr = ScopedEntitiesScreen; +#[test] +fn test_scoped_entities() { + let mut app = get_test_app::(); + app.register_screen::(); + assert!(app.run().is_success()); +} diff --git a/crates/screens/tests/screens/lifecycle.rs b/crates/screens/tests/screens/lifecycle.rs new file mode 100644 index 0000000..6fa809e --- /dev/null +++ b/crates/screens/tests/screens/lifecycle.rs @@ -0,0 +1,146 @@ +use bevy::ecs::component::ComponentIdFor; +use itertools::Itertools; + +use crate::prelude::*; + +macro_rules! gen_fns { + ($($name:ident),*) => { + $( + fn $name(mut r: ResMut) { + r.$name = true; + } + )* + #[derive(Resource, Debug, Default)] + pub struct LifecycleStatus { + $(pub $name:bool,)* + } + impl LifecycleStatus { + pub fn ok(&self) -> bool { + $(self.$name) &&* + } + } + } +} +gen_fns!( + loading, + update, + fixed_update, + unloading, + load, + ready, + unload, + unloaded +); + +macro_rules! gen_test_fns { + ($($name:ident),*) => { + #[derive(Resource, Default, Debug)] + struct TestRes { + $($name: bool,)* + } + impl TestRes { + pub fn ok(&self) -> bool { + $(self.$name) &&* + } + } + } +} +macro_rules! impl_test_fns { + ($app:expr, $($name:ident),*) => { + $( + $app.add_systems( + $name::(), + |mut r: ResMut| {r.$name = true;} + ); + )* + } +} +gen_test_fns!(on_screen_load, on_screen_ready, on_screen_unloaded); + +macro_rules! progress_by { + ($name:ident) => { + |mut data: ScreenDataMut| { + data.$name(); + } + }; +} + +/// The main [Screen] implementation. +#[derive(Component, Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Reflect)] +pub struct LifecycleScreen; +impl Screen for LifecycleScreen { + fn builder(mut builder: ScreenScopeBuilder) -> ScreenScopeBuilder { + builder + .add_systems( + ScreenSchedule::Loading, + ( + loading, + progress_by!(finish_loading), + |query: Query<&ScreenMarker>, + id: ComponentIdFor, + mut commands: Commands| { + if !query.iter().contains(&ScreenMarker(id.get())) { + error!("Failed to find LifecycleScreen in component hierarchy!"); + commands.write_message(AppExit::error()); + } + }, + ), + ) + // progress to unload by loading in EmptyScreen + .add_systems( + ScreenSchedule::Update, + (update, |r: Res, mut commands: Commands| { + if r.fixed_update && r.update { + commands.trigger(switch_to_screen::()); + } + }), + ) + .add_systems(ScreenSchedule::FixedUpdate, fixed_update) + .add_systems( + ScreenSchedule::Unloading, + (unloading, progress_by!(finish_unloading)), + ) + .add_systems(ScreenSchedule::OnLoad, load) + .add_systems(ScreenSchedule::OnReady, ready) + .add_systems(ScreenSchedule::OnUnload, unload) + .add_systems( + ScreenSchedule::OnUnloaded, + ( + unloaded, + |query: Query<&ScreenMarker>, + id: ComponentIdFor, + mut commands: Commands| { + if query.iter().contains(&ScreenMarker(id.get())) { + error!("Found LifecycleScreen in component hierarchy after unload!"); + commands.write_message(AppExit::error()); + } + }, + |r: Res, r2: Res, mut commands: Commands| { + let ok = r.ok() && r2.ok(); + if ok { + info!("OK!"); + commands.write_message(AppExit::Success); + } else { + error!("Did not reach all expected points."); + error!(?r); + error!(?r2); + commands.write_message(AppExit::error()); + } + }, + ) + .chain(), + ); + builder + } +} + +type Scr = LifecycleScreen; +#[test] +fn lifecycle() { + let mut app = get_test_app::(); + app.register_screen::(); + app.init_resource::(); + app.init_resource::(); + impl_test_fns!(app, on_screen_load, on_screen_ready, on_screen_unloaded); + assert!(app.run().is_success()); +} diff --git a/crates/screens/tests/screens/load_strategy.rs b/crates/screens/tests/screens/load_strategy.rs new file mode 100644 index 0000000..b468aa6 --- /dev/null +++ b/crates/screens/tests/screens/load_strategy.rs @@ -0,0 +1,74 @@ +use crate::prelude::*; + +#[derive(Resource, Debug, Default)] +struct FinalValue(u32); + +#[derive(Component, Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Reflect)] +struct LoadStrategyScreen; + +impl Screen for LoadStrategyScreen { + fn builder(mut builder: ScreenScopeBuilder) -> ScreenScopeBuilder { + builder + .with_load_strategy(if BLOCKING { + LoadStrategy::Blocking + } else { + LoadStrategy::Nonblocking + }) + .add_systems(ScreenSchedule::Update, Self::update) + .add_systems(ScreenSchedule::Loading, Self::load) + .add_systems(ScreenSchedule::OnUnloaded, Self::unloaded); + builder + } +} + +impl LoadStrategyScreen { + fn load(mut count: Local, mut data: ScreenDataMut) { + *count += 1; + if *count == 100 { + data.finish_loading(); + info!("Finished loading!"); + } + } + + fn update( + mut count: Local, + data: ScreenDataRef, + mut commands: Commands, + mut value: ResMut, + ) { + *count += 1; + if data.data().state() == ScreenState::Ready { + value.0 = *count; + commands.trigger(switch_to_screen::()); + } + } + + fn unloaded(data: ScreenDataRef, value: Res, mut commands: Commands) { + let expected_value = match data.data().load_strategy() { + LoadStrategy::Nonblocking => 100, + LoadStrategy::Blocking => 1, + }; + info!("Got {}, expected {}", value.0, expected_value); + if value.0 != expected_value { + commands.write_message(AppExit::error()); + } else { + commands.write_message(AppExit::Success); + } + } +} + +#[test] +fn blocking() { + let mut app = get_test_app::>(); + app.init_resource::(); + app.register_screen::(); + assert!(app.run().is_success()); +} + +#[test] +fn nonblocking() { + let mut app = get_test_app::>(); + app.init_resource::(); + app.register_screen::(); + assert!(app.run().is_success()); +} diff --git a/crates/screens/tests/screens/mod.rs b/crates/screens/tests/screens/mod.rs new file mode 100644 index 0000000..0d5f73b --- /dev/null +++ b/crates/screens/tests/screens/mod.rs @@ -0,0 +1,9 @@ +mod empty; +mod entity_scope; +mod lifecycle; +mod load_strategy; + +pub mod prelude { + pub use super::empty::*; + pub use super::lifecycle::*; +} diff --git a/crates/screens/tests/tests.rs b/crates/screens/tests/tests.rs new file mode 100644 index 0000000..b4f1c94 --- /dev/null +++ b/crates/screens/tests/tests.rs @@ -0,0 +1,90 @@ +mod screens; +pub mod prelude { + pub use super::globals::*; + pub use super::screens::prelude::*; + pub use bevy::prelude::*; + pub use bevy_asset_loader::prelude::*; + pub use q_screens::prelude::*; + pub use q_test_harness::prelude::*; +} + +mod globals { + use crate::prelude::*; + use bevy::asset::{AssetLoader, AsyncReadExt}; + + pub fn get_test_app() -> App { + let mut app = App::new(); + app.add_plugins((TestRunnerPlugin::default(), ScreenPlugin)); + app.register_screen::(); + app.insert_resource(InitialScreen::new::()); + app.init_asset::(); + app.init_asset_loader::(); + app + } + + #[derive(Asset, Deref, DerefMut, Debug, Reflect)] + pub struct TextAsset(String); + + #[derive(Reflect, Default)] + pub struct TextAssetLoader; + impl AssetLoader for TextAssetLoader { + type Asset = TextAsset; + type Settings = (); + type Error = String; + + async fn load<'a>( + &self, + reader: &mut dyn bevy::asset::io::Reader, + _settings: &Self::Settings, + _load_context: &mut bevy::asset::LoadContext<'a>, + ) -> Result { + let mut string = String::new(); + + match reader.read_to_string(&mut string).await { + Ok(_) => Ok(TextAsset(string)), + Err(e) => Err(e.to_string()), + } + } + + fn extensions(&self) -> &[&str] { + &["txt"] + } + } + + #[derive(Resource, Default)] + struct TheHandle(Handle); + #[test] + fn test_load() { + let mut app = get_test_app::(); + app.insert_resource(TestRunnerTimeout(0.25)); + app.init_resource::(); + app.add_systems( + Startup, + |server: Res, mut thehandle: ResMut| { + let handle = server.load("test/test.txt"); + thehandle.0 = handle; + }, + ); + app.add_systems( + Update, + |server: Res, thehandle: Res, mut commands: Commands| { + match server.load_state(thehandle.0.id()) { + bevy::asset::LoadState::NotLoaded => { + warn!("Asset not started to load."); + } + bevy::asset::LoadState::Loading => { + info!("loading..."); + } + bevy::asset::LoadState::Loaded => { + commands.write_message(AppExit::Success); + } + bevy::asset::LoadState::Failed(asset_load_error) => { + error!(?asset_load_error); + commands.write_message(AppExit::error()); + } + } + }, + ); + assert!(app.run().is_success()) + } +} diff --git a/crates/template/.github/workflows/ci.yaml b/crates/template/.github/workflows/ci.yaml index 2dfc2e7..3ccb05f 100644 --- a/crates/template/.github/workflows/ci.yaml +++ b/crates/template/.github/workflows/ci.yaml @@ -1,54 +1,54 @@ name: Cargo Build & Test on: - push: + push: env: - CARGO_TERM_COLOR: always + CARGO_TERM_COLOR: always jobs: - build_and_test: - runs-on: ubuntu-24.04 - env: - CARGO_TERM_COLOR: always - strategy: - matrix: - target: [x86_64-pc-windows-msvc, x86_64-unknown-linux-gnu] - steps: - - uses: actions/checkout@v4 - with: - submodules: recursive - - - name: Cache - uses: actions/cache@v4 - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - target/ - key: ${{ matrix.target }}-ci-${{ hashFiles('**/Cargo.toml') }} - - - name: Install dependencies - shell: bash - run: > - sudo apt-get update; - sudo apt-get install -y --no-install-recommends - libasound2-dev - libudev-dev - libwayland-dev - ; - - - name: Install rust - uses: actions-rust-lang/setup-rust-toolchain@v1 - with: - toolchain: nightly-2025-12-11 - components: rustc-codegen-cranelift-preview,rustc-dev,llvm-tools-preview,clippy - - - uses: jdx/mise-action@v3 - with: - log_level: info - - - run: "rustup component list --installed" - - run: "RUST_BACKTRACE=1 RUST_LOG=app=debug,tfw=debug MISE_ENV=ci mise check ::: test" + build_and_test: + runs-on: ubuntu-24.04 + env: + CARGO_TERM_COLOR: always + strategy: + matrix: + target: [x86_64-pc-windows-msvc, x86_64-unknown-linux-gnu] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Cache + uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ matrix.target }}-ci-${{ hashFiles('**/Cargo.toml') }} + + - name: Install dependencies + shell: bash + run: > + sudo apt-get update; + sudo apt-get install -y --no-install-recommends + libasound2-dev + libudev-dev + libwayland-dev + ; + + - name: Install rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + toolchain: nightly-2026-01-22 + components: rustc-codegen-cranelift-preview,rustc-dev,llvm-tools-preview,clippy + + - uses: jdx/mise-action@v3 + with: + log_level: info + + - run: "rustup component list --installed" + - run: "RUST_BACKTRACE=1 RUST_LOG=app=debug,tfw=debug MISE_ENV=ci mise check ::: test" diff --git a/crates/template/Cargo.toml b/crates/template/Cargo.toml index 6a56f42..267a4df 100644 --- a/crates/template/Cargo.toml +++ b/crates/template/Cargo.toml @@ -32,7 +32,7 @@ variadics_please = "1.1.0" clap = {version = "4.5.54", features = ["derive"] } # workspace -tfw = {path = "../tfw"} +q_screens = {path = "../screens", version="0.1.0"} [build-dependencies] built = {version = "0.8.0", features=["chrono"]} diff --git a/crates/template/README.md b/crates/template/README.md index e694d73..e8e0038 100644 --- a/crates/template/README.md +++ b/crates/template/README.md @@ -22,7 +22,7 @@ Features: - [x] Service-oriented framework - [x] Screen-scoped systems - [ ] Devex - - [ ] Lightweight console (with [bevy_ui_console](https://github.com/ada-x64/bevy_command_prompt)) + - [ ] Lightweight console (with [bevy_ui_console](https://github.com/ada-x64/q_cmd_prompt)) - [x] CLI - [x] Template scaffolding - [x] Screens diff --git a/crates/template/src/lib.rs b/crates/template/src/lib.rs index 9f0cc52..9c1ed8a 100644 --- a/crates/template/src/lib.rs +++ b/crates/template/src/lib.rs @@ -27,5 +27,6 @@ pub use plugin::{AppPlugin, AppSettings}; pub mod prelude { pub use super::screen::prelude::*; pub use super::service::prelude::*; - pub use tfw::prelude::*; + pub(crate) use bevy::ecs::{lifecycle::HookContext, world::DeferredWorld}; + pub use q_screens::prelude::*; } diff --git a/crates/template/src/plugin.rs b/crates/template/src/plugin.rs index 7ae134b..f2dcf7c 100644 --- a/crates/template/src/plugin.rs +++ b/crates/template/src/plugin.rs @@ -1,5 +1,3 @@ -use tfw::TfwSettings; - use crate::prelude::*; /// Allows for configuration of the application. When the "dev" feature is set, @@ -38,16 +36,10 @@ pub struct AppPlugin { impl Plugin for AppPlugin { fn build(&self, app: &mut App) { app.world_mut().insert_resource(self.settings.clone()); - app.add_plugins(( - tfw::TfwPlugin { - settings: TfwSettings { - // TODO: FIXME - initial_screen: self.settings.initial_screen.clone(), - }, - }, - crate::service::plugin, - crate::screen::plugin, - )) - .insert_resource(self.settings.clone()); + app.add_plugins((ScreenPlugin, crate::service::plugin, crate::screen::plugin)) + .insert_resource(self.settings.clone()); + app.insert_resource(InitialScreen::from_name( + self.settings.initial_screen.clone(), + )); } } diff --git a/crates/template/src/screen/dev/camera_test/mod.rs b/crates/template/src/screen/dev/camera_test/mod.rs index fa3d566..9d5144e 100644 --- a/crates/template/src/screen/dev/camera_test/mod.rs +++ b/crates/template/src/screen/dev/camera_test/mod.rs @@ -2,15 +2,12 @@ use crate::prelude::*; mod data; mod screen; -mod systems; pub mod prelude { pub use super::data::*; pub use super::screen::CameraTestScreen; } -pub use systems::systems; - pub fn plugin(app: &mut App) { - app.add_plugins(screen::plugin); + app.register_screen::(); } diff --git a/crates/template/src/screen/dev/camera_test/screen.rs b/crates/template/src/screen/dev/camera_test/screen.rs index f511e10..cec0e13 100644 --- a/crates/template/src/screen/dev/camera_test/screen.rs +++ b/crates/template/src/screen/dev/camera_test/screen.rs @@ -1,11 +1,13 @@ -use crate::{prelude::*, screen::dev::camera_test}; +use crate::prelude::*; #[derive(Component, Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Reflect)] pub struct CameraTestScreen; impl Screen for CameraTestScreen { - type SETTINGS = NoSettings; - type ASSETS = NoAssets; - const STRATEGY: LoadingStrategy = LoadingStrategy::Nonblocking; + fn builder(mut builder: ScreenScopeBuilder) -> ScreenScopeBuilder { + builder.add_systems(ScreenSchedule::Loading, init); + builder.add_systems(ScreenSchedule::Update, (update, camera_systems().take())); + builder + } } /// spawn the scene. @@ -15,6 +17,7 @@ fn init( mut commands: Commands, mut meshes: ResMut>, mut materials: ResMut>, + mut screen: ScreenDataMut, ) { // spawn everything let cube = meshes.add(Cuboid::default()); @@ -48,12 +51,15 @@ fn init( commands.trigger(SpawnCursorCapture); commands.spawn((tracking_cam_bundle(cube_entt), Name::new("Tracking Cam"))); commands.spawn((flycam_bundle(), Name::new("Fly Cam"))); + + screen.finish_loading(); } -pub fn plugin(app: &mut App) { - ScreenScopeBuilder::::new(app) - .on_ready(init) - .add_systems(camera_test::systems().take()) - .add_systems(camera_systems().take()) - .build(); +fn update(mut query: Query<&mut Transform, With>, time: Res