bevy/examples/window/low_power.rs
UkoeHB c2c19e5ae4
Text rework (#15591)
**Ready for review. Examples migration progress: 100%.**

# Objective

- Implement https://github.com/bevyengine/bevy/discussions/15014

## Solution

This implements [cart's
proposal](https://github.com/bevyengine/bevy/discussions/15014#discussioncomment-10574459)
faithfully except for one change. I separated `TextSpan` from
`TextSpan2d` because `TextSpan` needs to require the `GhostNode`
component, which is a `bevy_ui` component only usable by UI.

Extra changes:
- Added `EntityCommands::commands_mut` that returns a mutable reference.
This is a blocker for extension methods that return something other than
`self`. Note that `sickle_ui`'s `UiBuilder::commands` returns a mutable
reference for this reason.

## Testing

- [x] Text examples all work.

---

## Showcase

TODO: showcase-worthy

## Migration Guide

TODO: very breaking

### Accessing text spans by index

Text sections are now text sections on different entities in a
hierarchy, Use the new `TextReader` and `TextWriter` system parameters
to access spans by index.

Before:
```rust
fn refresh_text(mut query: Query<&mut Text, With<TimeText>>, time: Res<Time>) {
    let text = query.single_mut();
    text.sections[1].value = format_time(time.elapsed());
}
```

After:
```rust
fn refresh_text(
    query: Query<Entity, With<TimeText>>,
    mut writer: UiTextWriter,
    time: Res<Time>
) {
    let entity = query.single();
    *writer.text(entity, 1) = format_time(time.elapsed());
}
```

### Iterating text spans

Text spans are now entities in a hierarchy, so the new `UiTextReader`
and `UiTextWriter` system parameters provide ways to iterate that
hierarchy. The `UiTextReader::iter` method will give you a normal
iterator over spans, and `UiTextWriter::for_each` lets you visit each of
the spans.

---------

Co-authored-by: ickshonpe <david.curthoys@googlemail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2024-10-09 18:35:36 +00:00

226 lines
8.5 KiB
Rust

//! This example illustrates how to run a winit window in a reactive, low power mode.
//!
//! This is useful for making desktop applications, or any other program that doesn't need to be
//! running the event loop non-stop.
use bevy::{
prelude::*,
utils::Duration,
window::{PresentMode, RequestRedraw, WindowPlugin},
winit::{EventLoopProxyWrapper, WakeUp, WinitSettings},
};
fn main() {
App::new()
// Continuous rendering for games - bevy's default.
.insert_resource(WinitSettings::game())
// Power-saving reactive rendering for applications.
.insert_resource(WinitSettings::desktop_app())
// You can also customize update behavior with the fields of [`WinitSettings`]
.insert_resource(WinitSettings {
focused_mode: bevy::winit::UpdateMode::Continuous,
unfocused_mode: bevy::winit::UpdateMode::reactive_low_power(Duration::from_millis(10)),
})
.insert_resource(ExampleMode::Game)
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
// Turn off vsync to maximize CPU/GPU usage
present_mode: PresentMode::AutoNoVsync,
..default()
}),
..default()
}))
.add_systems(Startup, test_setup::setup)
.add_systems(
Update,
(
test_setup::cycle_modes,
test_setup::rotate_cube,
test_setup::update_text,
update_winit,
),
)
.run();
}
#[derive(Resource, Debug)]
enum ExampleMode {
Game,
Application,
ApplicationWithRequestRedraw,
ApplicationWithWakeUp,
}
/// Update winit based on the current `ExampleMode`
fn update_winit(
mode: Res<ExampleMode>,
mut winit_config: ResMut<WinitSettings>,
event_loop_proxy: Res<EventLoopProxyWrapper<WakeUp>>,
mut redraw_request_events: EventWriter<RequestRedraw>,
) {
use ExampleMode::*;
*winit_config = match *mode {
Game => {
// In the default `WinitSettings::game()` mode:
// * When focused: the event loop runs as fast as possible
// * When not focused: the app will update when the window is directly interacted with
// (e.g. the mouse hovers over a visible part of the out of focus window), a
// [`RequestRedraw`] event is received, or one sixtieth of a second has passed
// without the app updating (60 Hz refresh rate max).
WinitSettings::game()
}
Application => {
// While in `WinitSettings::desktop_app()` mode:
// * When focused: the app will update any time a winit event (e.g. the window is
// moved/resized, the mouse moves, a button is pressed, etc.), a [`RequestRedraw`]
// event is received, or after 5 seconds if the app has not updated.
// * When not focused: the app will update when the window is directly interacted with
// (e.g. the mouse hovers over a visible part of the out of focus window), a
// [`RequestRedraw`] event is received, or one minute has passed without the app
// updating.
WinitSettings::desktop_app()
}
ApplicationWithRequestRedraw => {
// Sending a `RequestRedraw` event is useful when you want the app to update the next
// frame regardless of any user input. For example, your application might use
// `WinitSettings::desktop_app()` to reduce power use, but UI animations need to play even
// when there are no inputs, so you send redraw requests while the animation is playing.
// Note that in this example the RequestRedraw winit event will make the app run in the same
// way as continuous
redraw_request_events.send(RequestRedraw);
WinitSettings::desktop_app()
}
ApplicationWithWakeUp => {
// Sending a `WakeUp` event is useful when you want the app to update the next
// frame regardless of any user input. This can be used from outside Bevy, see example
// `window/custom_user_event.rs` for an example usage from outside.
// Note that in this example the Wakeup winit event will make the app run in the same
// way as continuous
let _ = event_loop_proxy.send_event(WakeUp);
WinitSettings::desktop_app()
}
};
}
/// Everything in this module is for setting up and animating the scene, and is not important to the
/// demonstrated features.
pub(crate) mod test_setup {
use crate::ExampleMode;
use bevy::{
color::palettes::basic::{LIME, YELLOW},
prelude::*,
window::RequestRedraw,
};
/// Switch between update modes when the mouse is clicked.
pub(crate) fn cycle_modes(
mut mode: ResMut<ExampleMode>,
button_input: Res<ButtonInput<KeyCode>>,
) {
if button_input.just_pressed(KeyCode::Space) {
*mode = match *mode {
ExampleMode::Game => ExampleMode::Application,
ExampleMode::Application => ExampleMode::ApplicationWithRequestRedraw,
ExampleMode::ApplicationWithRequestRedraw => ExampleMode::ApplicationWithWakeUp,
ExampleMode::ApplicationWithWakeUp => ExampleMode::Game,
};
}
}
#[derive(Component)]
pub(crate) struct Rotator;
/// Rotate the cube to make it clear when the app is updating
pub(crate) fn rotate_cube(
time: Res<Time>,
mut cube_transform: Query<&mut Transform, With<Rotator>>,
) {
for mut transform in &mut cube_transform {
transform.rotate_x(time.delta_seconds());
transform.rotate_local_y(time.delta_seconds());
}
}
#[derive(Component)]
pub struct ModeText;
pub(crate) fn update_text(
mut frame: Local<usize>,
mode: Res<ExampleMode>,
query: Query<Entity, With<ModeText>>,
mut writer: UiTextWriter,
) {
*frame += 1;
let mode = match *mode {
ExampleMode::Game => "game(), continuous, default",
ExampleMode::Application => "desktop_app(), reactive",
ExampleMode::ApplicationWithRequestRedraw => {
"desktop_app(), reactive, RequestRedraw sent"
}
ExampleMode::ApplicationWithWakeUp => "desktop_app(), reactive, WakeUp sent",
};
let text = query.single();
*writer.text(text, 2) = mode.to_string();
*writer.text(text, 4) = frame.to_string();
}
/// Set up a scene with a cube and some text
pub fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut event: EventWriter<RequestRedraw>,
) {
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))),
Rotator,
));
commands.spawn((
DirectionalLight::default(),
Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::ZERO, Vec3::Y),
));
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.0, 2.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y),
));
event.send(RequestRedraw);
commands
.spawn((
Text::default(),
Style {
align_self: AlignSelf::FlexStart,
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
ModeText,
))
.with_children(|p| {
p.spawn(TextSpan::new("Press space bar to cycle modes\n"));
p.spawn((
TextSpan::default(),
TextStyle {
color: LIME.into(),
..default()
},
));
p.spawn((
TextSpan::new("\nFrame: "),
TextStyle {
color: YELLOW.into(),
..default()
},
));
p.spawn((
TextSpan::new(""),
TextStyle {
color: YELLOW.into(),
..default()
},
));
});
}
}