mirror of
https://github.com/bevyengine/bevy
synced 2024-11-26 14:40:19 +00:00
2d674e7c3e
# Objective - Reduce power usage for games when not focused. - Reduce power usage to ~0 when a desktop application is minimized (opt-in). - Reduce power usage when focused, only updating on a `winit` event, or the user sends a redraw request. (opt-in) https://user-images.githubusercontent.com/2632925/156904387-ec47d7de-7f06-4c6f-8aaf-1e952c1153a2.mp4 Note resource usage in the Task Manager in the above video. ## Solution - Added a type `UpdateMode` that allows users to specify how the winit event loop is updated, without exposing winit types. - Added two fields to `WinitConfig`, both with the `UpdateMode` type. One configures how the application updates when focused, and the other configures how the application behaves when it is not focused. Users can modify this resource manually to set the type of event loop control flow they want. - For convenience, two functions were added to `WinitConfig`, that provide reasonable presets: `game()` (default) and `desktop_app()`. - The `game()` preset, which is used by default, is unchanged from current behavior with one exception: when the app is out of focus the app updates at a minimum of 10fps, or every time a winit event is received. This has a huge positive impact on power use and responsiveness on my machine, which will otherwise continue running the app at many hundreds of fps when out of focus or minimized. - The `desktop_app()` preset is fully reactive, only updating when user input (winit event) is supplied or a `RedrawRequest` event is sent. When the app is out of focus, it only updates on `Window` events - i.e. any winit event that directly interacts with the window. What this means in practice is that the app uses *zero* resources when minimized or not interacted with, but still updates fluidly when the app is out of focus and the user mouses over the application. - Added a `RedrawRequest` event so users can force an update even if there are no events. This is useful in an application when you want to, say, run an animation even when the user isn't providing input. - Added an example `low_power` to demonstrate these changes ## Usage Configuring the event loop: ```rs use bevy::winit::{WinitConfig}; // ... .insert_resource(WinitConfig::desktop_app()) // preset // or .insert_resource(WinitConfig::game()) // preset // or .insert_resource(WinitConfig{ .. }) // manual ``` Requesting a redraw: ```rs use bevy:🪟:RequestRedraw; // ... fn request_redraw(mut event: EventWriter<RequestRedraw>) { event.send(RequestRedraw); } ``` ## Other details - Because we have a single event loop for multiple windows, every time I've mentioned "focused" above, I more precisely mean, "if at least one bevy window is focused". - Due to a platform bug in winit (https://github.com/rust-windowing/winit/issues/1619), we can't simply use `Window::request_redraw()`. As a workaround, this PR will temporarily set the window mode to `Poll` when a redraw is requested. This is then reset to the user's `WinitConfig` setting on the next frame.
220 lines
8.5 KiB
Rust
220 lines
8.5 KiB
Rust
use std::time::Duration;
|
|
|
|
use bevy::{
|
|
prelude::*,
|
|
window::{PresentMode, RequestRedraw},
|
|
winit::WinitSettings,
|
|
};
|
|
|
|
/// 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.
|
|
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 [`WinitConfig`]
|
|
.insert_resource(WinitSettings {
|
|
focused_mode: bevy::winit::UpdateMode::Continuous,
|
|
unfocused_mode: bevy::winit::UpdateMode::ReactiveLowPower {
|
|
max_wait: Duration::from_millis(10),
|
|
},
|
|
..default()
|
|
})
|
|
// Turn off vsync to maximize CPU/GPU usage
|
|
.insert_resource(WindowDescriptor {
|
|
present_mode: PresentMode::Immediate,
|
|
..default()
|
|
})
|
|
.insert_resource(ExampleMode::Game)
|
|
.add_plugins(DefaultPlugins)
|
|
.add_startup_system(test_setup::setup)
|
|
.add_system(test_setup::cycle_modes)
|
|
.add_system(test_setup::rotate_cube)
|
|
.add_system(test_setup::update_text)
|
|
.add_system(update_winit)
|
|
.run();
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
enum ExampleMode {
|
|
Game,
|
|
Application,
|
|
ApplicationWithRedraw,
|
|
}
|
|
|
|
/// Update winit based on the current `ExampleMode`
|
|
fn update_winit(
|
|
mode: Res<ExampleMode>,
|
|
mut event: EventWriter<RequestRedraw>,
|
|
mut winit_config: ResMut<WinitSettings>,
|
|
) {
|
|
use ExampleMode::*;
|
|
*winit_config = match *mode {
|
|
Game => {
|
|
// In the default `WinitConfig::game()` mode:
|
|
// * When focused: the event loop runs as fast as possible
|
|
// * When not focused: the event loop runs as fast as possible
|
|
WinitSettings::game()
|
|
}
|
|
Application => {
|
|
// While in `WinitConfig::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()
|
|
}
|
|
ApplicationWithRedraw => {
|
|
// 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
|
|
// `WinitConfig::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.
|
|
event.send(RequestRedraw);
|
|
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::{prelude::*, window::RequestRedraw};
|
|
|
|
/// Switch between update modes when the mouse is clicked.
|
|
pub(crate) fn cycle_modes(
|
|
mut mode: ResMut<ExampleMode>,
|
|
mouse_button_input: Res<Input<KeyCode>>,
|
|
) {
|
|
if mouse_button_input.just_pressed(KeyCode::Space) {
|
|
*mode = match *mode {
|
|
ExampleMode::Game => ExampleMode::Application,
|
|
ExampleMode::Application => ExampleMode::ApplicationWithRedraw,
|
|
ExampleMode::ApplicationWithRedraw => 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 cube_transform.iter_mut() {
|
|
let t = time.seconds_since_startup() as f32;
|
|
*transform =
|
|
transform.with_rotation(Quat::from_rotation_x(t) * Quat::from_rotation_y(t));
|
|
}
|
|
}
|
|
|
|
#[derive(Component)]
|
|
pub struct ModeText;
|
|
|
|
pub(crate) fn update_text(
|
|
mut frame: Local<usize>,
|
|
mode: Res<ExampleMode>,
|
|
mut query: Query<&mut Text, With<ModeText>>,
|
|
) {
|
|
*frame += 1;
|
|
let mode = match *mode {
|
|
ExampleMode::Game => "game(), continuous, default",
|
|
ExampleMode::Application => "desktop_app(), reactive",
|
|
ExampleMode::ApplicationWithRedraw => "desktop_app(), reactive, RequestRedraw sent",
|
|
};
|
|
query.get_single_mut().unwrap().sections[1].value = mode.to_string();
|
|
query.get_single_mut().unwrap().sections[3].value = format!("{}", *frame);
|
|
}
|
|
|
|
/// 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>,
|
|
asset_server: Res<AssetServer>,
|
|
) {
|
|
commands
|
|
.spawn_bundle(PbrBundle {
|
|
mesh: meshes.add(Mesh::from(shape::Cube { size: 0.5 })),
|
|
material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()),
|
|
..default()
|
|
})
|
|
.insert(Rotator);
|
|
commands.spawn_bundle(PointLightBundle {
|
|
point_light: PointLight {
|
|
intensity: 1500.0,
|
|
shadows_enabled: true,
|
|
..default()
|
|
},
|
|
transform: Transform::from_xyz(4.0, 8.0, 4.0),
|
|
..default()
|
|
});
|
|
commands.spawn_bundle(PerspectiveCameraBundle {
|
|
transform: Transform::from_xyz(-2.0, 2.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y),
|
|
..Default::default()
|
|
});
|
|
event.send(RequestRedraw);
|
|
commands.spawn_bundle(UiCameraBundle::default());
|
|
commands
|
|
.spawn_bundle(TextBundle {
|
|
style: Style {
|
|
align_self: AlignSelf::FlexStart,
|
|
position_type: PositionType::Absolute,
|
|
position: Rect {
|
|
top: Val::Px(5.0),
|
|
left: Val::Px(5.0),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
},
|
|
text: Text {
|
|
sections: vec![
|
|
TextSection {
|
|
value: "Press spacebar to cycle modes\n".into(),
|
|
style: TextStyle {
|
|
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
|
|
font_size: 50.0,
|
|
color: Color::WHITE,
|
|
},
|
|
},
|
|
TextSection {
|
|
value: "".into(),
|
|
style: TextStyle {
|
|
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
|
|
font_size: 50.0,
|
|
color: Color::GREEN,
|
|
},
|
|
},
|
|
TextSection {
|
|
value: "\nFrame: ".into(),
|
|
style: TextStyle {
|
|
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
|
|
font_size: 50.0,
|
|
color: Color::YELLOW,
|
|
},
|
|
},
|
|
TextSection {
|
|
value: "".into(),
|
|
style: TextStyle {
|
|
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
|
|
font_size: 50.0,
|
|
color: Color::YELLOW,
|
|
},
|
|
},
|
|
],
|
|
alignment: TextAlignment::default(),
|
|
},
|
|
..Default::default()
|
|
})
|
|
.insert(ModeText);
|
|
}
|
|
}
|