Skip to content

Commit

Permalink
Reduce power usage with configurable event loop (bevyengine#3974)
Browse files Browse the repository at this point in the history
# 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::window::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 (rust-windowing/winit#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.
  • Loading branch information
aevyrie authored and ItsDoot committed Feb 1, 2023
1 parent 4b86b29 commit f75df17
Show file tree
Hide file tree
Showing 8 changed files with 435 additions and 43 deletions.
8 changes: 7 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ bevy_dylib = { path = "crates/bevy_dylib", version = "0.6.0", default-features =
bevy_internal = { path = "crates/bevy_internal", version = "0.6.0", default-features = false }

[target.'cfg(target_arch = "wasm32")'.dependencies]
bevy_internal = { path = "crates/bevy_internal", version = "0.6.0", default-features = false, features = ["webgl"] }
bevy_internal = { path = "crates/bevy_internal", version = "0.6.0", default-features = false, features = [
"webgl",
] }

[dev-dependencies]
anyhow = "1.0.4"
Expand Down Expand Up @@ -522,6 +524,10 @@ path = "examples/ui/ui.rs"
name = "clear_color"
path = "examples/window/clear_color.rs"

[[example]]
name = "low_power"
path = "examples/window/low_power.rs"

[[example]]
name = "multiple_windows"
path = "examples/window/multiple_windows.rs"
Expand Down
5 changes: 5 additions & 0 deletions crates/bevy_window/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ pub struct CreateWindow {
pub descriptor: WindowDescriptor,
}

/// An event that indicates the window should redraw, even if its control flow is set to `Wait` and
/// there have been no window events.
#[derive(Debug, Clone)]
pub struct RequestRedraw;

/// An event that indicates a window should be closed.
#[derive(Debug, Clone)]
pub struct CloseWindow {
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_window/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ impl Plugin for WindowPlugin {
.add_event::<CreateWindow>()
.add_event::<WindowCreated>()
.add_event::<WindowCloseRequested>()
.add_event::<RequestRedraw>()
.add_event::<CloseWindow>()
.add_event::<CursorMoved>()
.add_event::<CursorEntered>()
Expand Down
137 changes: 110 additions & 27 deletions crates/bevy_winit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,18 @@ use bevy_ecs::{
world::World,
};
use bevy_math::{ivec2, DVec2, Vec2};
use bevy_utils::tracing::{error, trace, warn};
use bevy_utils::{
tracing::{error, trace, warn},
Instant,
};
use bevy_window::{
CreateWindow, CursorEntered, CursorLeft, CursorMoved, FileDragAndDrop, ReceivedCharacter,
WindowBackendScaleFactorChanged, WindowCloseRequested, WindowCreated, WindowFocused,
WindowMoved, WindowResized, WindowScaleFactorChanged, Windows,
RequestRedraw, WindowBackendScaleFactorChanged, WindowCloseRequested, WindowCreated,
WindowFocused, WindowMoved, WindowResized, WindowScaleFactorChanged, Windows,
};
use winit::{
dpi::PhysicalPosition,
event::{self, DeviceEvent, Event, WindowEvent},
event::{self, DeviceEvent, Event, StartCause, WindowEvent},
event_loop::{ControlFlow, EventLoop, EventLoopWindowTarget},
};

Expand All @@ -37,6 +40,7 @@ pub struct WinitPlugin;
impl Plugin for WinitPlugin {
fn build(&self, app: &mut App) {
app.init_non_send_resource::<WinitWindows>()
.init_resource::<WinitSettings>()
.set_runner(winit_runner)
.add_system_to_stage(CoreStage::PostUpdate, change_window.exclusive_system());
let event_loop = EventLoop::new();
Expand Down Expand Up @@ -227,41 +231,71 @@ pub fn winit_runner(app: App) {
// winit_runner_with(app, EventLoop::new_any_thread());
// }

/// Stores state that must persist between frames.
struct WinitPersistentState {
/// Tracks whether or not the application is active or suspended.
active: bool,
/// Tracks whether or not an event has occurred this frame that would trigger an update in low
/// power mode. Should be reset at the end of every frame.
low_power_event: bool,
/// Tracks whether the event loop was started this frame because of a redraw request.
redraw_request_sent: bool,
/// Tracks if the event loop was started this frame because of a `WaitUntil` timeout.
timeout_reached: bool,
last_update: Instant,
}
impl Default for WinitPersistentState {
fn default() -> Self {
Self {
active: true,
low_power_event: false,
redraw_request_sent: false,
timeout_reached: false,
last_update: Instant::now(),
}
}
}

pub fn winit_runner_with(mut app: App) {
let mut event_loop = app
.world
.remove_non_send_resource::<EventLoop<()>>()
.unwrap();
let mut create_window_event_reader = ManualEventReader::<CreateWindow>::default();
let mut app_exit_event_reader = ManualEventReader::<AppExit>::default();
let mut redraw_event_reader = ManualEventReader::<RequestRedraw>::default();
let mut winit_state = WinitPersistentState::default();
app.world
.insert_non_send_resource(event_loop.create_proxy());

let return_from_run = app.world.resource::<WinitSettings>().return_from_run;
trace!("Entering winit event loop");

let should_return_from_run = app
.world
.get_resource::<WinitConfig>()
.map_or(false, |config| config.return_from_run);

let mut active = true;

let event_handler = move |event: Event<()>,
event_loop: &EventLoopWindowTarget<()>,
control_flow: &mut ControlFlow| {
*control_flow = ControlFlow::Poll;

if let Some(app_exit_events) = app.world.get_resource_mut::<Events<AppExit>>() {
if app_exit_event_reader
.iter(&app_exit_events)
.next_back()
.is_some()
{
*control_flow = ControlFlow::Exit;
}
}

match event {
event::Event::NewEvents(start) => {
let winit_config = app.world.resource::<WinitSettings>();
let windows = app.world.resource::<Windows>();
let focused = windows.iter().any(|w| w.is_focused());
// Check if either the `WaitUntil` timeout was triggered by winit, or that same
// amount of time has elapsed since the last app update. This manual check is needed
// because we don't know if the criteria for an app update were met until the end of
// the frame.
let auto_timeout_reached = matches!(start, StartCause::ResumeTimeReached { .. });
let now = Instant::now();
let manual_timeout_reached = match winit_config.update_mode(focused) {
UpdateMode::Continuous => false,
UpdateMode::Reactive { max_wait }
| UpdateMode::ReactiveLowPower { max_wait } => {
now.duration_since(winit_state.last_update) >= *max_wait
}
};
// The low_power_event state and timeout must be reset at the start of every frame.
winit_state.low_power_event = false;
winit_state.timeout_reached = auto_timeout_reached || manual_timeout_reached;
}
event::Event::WindowEvent {
event,
window_id: winit_window_id,
Expand All @@ -287,6 +321,7 @@ pub fn winit_runner_with(mut app: App) {
warn!("Skipped event for unknown Window Id {:?}", winit_window_id);
return;
};
winit_state.low_power_event = true;

match event {
WindowEvent::Resized(size) => {
Expand Down Expand Up @@ -497,25 +532,73 @@ pub fn winit_runner_with(mut app: App) {
});
}
event::Event::Suspended => {
active = false;
winit_state.active = false;
}
event::Event::Resumed => {
active = true;
winit_state.active = true;
}
event::Event::MainEventsCleared => {
handle_create_window_events(
&mut app.world,
event_loop,
&mut create_window_event_reader,
);
if active {
let winit_config = app.world.resource::<WinitSettings>();
let update = if winit_state.active {
let windows = app.world.resource::<Windows>();
let focused = windows.iter().any(|w| w.is_focused());
match winit_config.update_mode(focused) {
UpdateMode::Continuous | UpdateMode::Reactive { .. } => true,
UpdateMode::ReactiveLowPower { .. } => {
winit_state.low_power_event
|| winit_state.redraw_request_sent
|| winit_state.timeout_reached
}
}
} else {
false
};
if update {
winit_state.last_update = Instant::now();
app.update();
}
}
Event::RedrawEventsCleared => {
{
let winit_config = app.world.resource::<WinitSettings>();
let windows = app.world.resource::<Windows>();
let focused = windows.iter().any(|w| w.is_focused());
let now = Instant::now();
use UpdateMode::*;
*control_flow = match winit_config.update_mode(focused) {
Continuous => ControlFlow::Poll,
Reactive { max_wait } | ReactiveLowPower { max_wait } => {
ControlFlow::WaitUntil(now + *max_wait)
}
};
}
// This block needs to run after `app.update()` in `MainEventsCleared`. Otherwise,
// we won't be able to see redraw requests until the next event, defeating the
// purpose of a redraw request!
let mut redraw = false;
if let Some(app_redraw_events) = app.world.get_resource::<Events<RequestRedraw>>() {
if redraw_event_reader.iter(app_redraw_events).last().is_some() {
*control_flow = ControlFlow::Poll;
redraw = true;
}
}
if let Some(app_exit_events) = app.world.get_resource::<Events<AppExit>>() {
if app_exit_event_reader.iter(app_exit_events).last().is_some() {
*control_flow = ControlFlow::Exit;
}
}
winit_state.redraw_request_sent = redraw;
}
_ => (),
}
};
if should_return_from_run {

if return_from_run {
run_return(&mut event_loop, event_handler);
} else {
run(event_loop, event_handler);
Expand Down
98 changes: 86 additions & 12 deletions crates/bevy_winit/src/winit_config.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,89 @@
use bevy_utils::Duration;

/// A resource for configuring usage of the `rust_winit` library.
#[derive(Debug, Default)]
pub struct WinitConfig {
/// Configures the winit library to return control to the main thread after
/// the [run](bevy_app::App::run) loop is exited. Winit strongly recommends
/// avoiding this when possible. Before using this please read and understand
/// the [caveats](winit::platform::run_return::EventLoopExtRunReturn::run_return)
/// in the winit documentation.
///
/// This feature is only available on desktop `target_os` configurations.
/// Namely `windows`, `macos`, `linux`, `dragonfly`, `freebsd`, `netbsd`, and
/// `openbsd`. If set to true on an unsupported platform
/// [run](bevy_app::App::run) will panic.
#[derive(Debug)]
pub struct WinitSettings {
/// Configures the winit library to return control to the main thread after the
/// [run](bevy_app::App::run) loop is exited. Winit strongly recommends avoiding this when
/// possible. Before using this please read and understand the
/// [caveats](winit::platform::run_return::EventLoopExtRunReturn::run_return) in the winit
/// documentation.
///
/// This feature is only available on desktop `target_os` configurations. Namely `windows`,
/// `macos`, `linux`, `dragonfly`, `freebsd`, `netbsd`, and `openbsd`. If set to true on an
/// unsupported platform [run](bevy_app::App::run) will panic.
pub return_from_run: bool,
/// Configures how the winit event loop updates while the window is focused.
pub focused_mode: UpdateMode,
/// Configures how the winit event loop updates while the window is *not* focused.
pub unfocused_mode: UpdateMode,
}
impl WinitSettings {
/// Configure winit with common settings for a game.
pub fn game() -> Self {
WinitSettings::default()
}

/// Configure winit with common settings for a desktop application.
pub fn desktop_app() -> Self {
WinitSettings {
focused_mode: UpdateMode::Reactive {
max_wait: Duration::from_secs(5),
},
unfocused_mode: UpdateMode::ReactiveLowPower {
max_wait: Duration::from_secs(60),
},
..Default::default()
}
}

/// Gets the configured `UpdateMode` depending on whether the window is focused or not
pub fn update_mode(&self, focused: bool) -> &UpdateMode {
match focused {
true => &self.focused_mode,
false => &self.unfocused_mode,
}
}
}
impl Default for WinitSettings {
fn default() -> Self {
WinitSettings {
return_from_run: false,
focused_mode: UpdateMode::Continuous,
unfocused_mode: UpdateMode::Continuous,
}
}
}

/// Configure how the winit event loop should update.
#[derive(Debug)]
pub enum UpdateMode {
/// The event loop will update continuously, running as fast as possible.
Continuous,
/// The event loop will only update if there is a winit event, a redraw is requested, or the
/// maximum wait time has elapsed.
///
/// ## Note
///
/// Once the app has executed all bevy systems and reaches the end of the event loop, there is
/// no way to force the app to wake and update again, unless a `winit` event (such as user
/// input, or the window being resized) is received or the time limit is reached.
Reactive { max_wait: Duration },
/// The event loop will only update if there is a winit event from direct interaction with the
/// window (e.g. mouseover), a redraw is requested, or the maximum wait time has elapsed.
///
/// ## Note
///
/// Once the app has executed all bevy systems and reaches the end of the event loop, there is
/// no way to force the app to wake and update again, unless a `winit` event (such as user
/// input, or the window being resized) is received or the time limit is reached.
///
/// ## Differences from [`UpdateMode::Reactive`]
///
/// Unlike [`UpdateMode::Reactive`], this mode will ignore winit events that aren't directly
/// caused by interaction with the window. For example, you might want to use this mode when the
/// window is not focused, to only re-draw your bevy app when the cursor is over the window, but
/// not when the mouse moves somewhere else on the screen. This helps to significantly reduce
/// power consumption by only updated the app when absolutely necessary.
ReactiveLowPower { max_wait: Duration },
}
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,7 @@ Example | File | Description
Example | File | Description
--- | --- | ---
`clear_color` | [`window/clear_color.rs`](./window/clear_color.rs) | Creates a solid color window
`low_power` | [`window/low_power.rs`](./window/low_power.rs) | Demonstrates settings to reduce power use for bevy applications
`multiple_windows` | [`window/multiple_windows.rs`](./window/multiple_windows.rs) | Demonstrates creating multiple windows, and rendering to them
`scale_factor_override` | [`window/scale_factor_override.rs`](./window/scale_factor_override.rs) | Illustrates how to customize the default window settings
`transparent_window` | [`window/transparent_window.rs`](./window/transparent_window.rs) | Illustrates making the window transparent and hiding the window decoration
Expand Down
8 changes: 5 additions & 3 deletions examples/app/return_after_run.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
use bevy::{prelude::*, winit::WinitConfig};
use bevy::{prelude::*, winit::WinitSettings};

fn main() {
println!("Running first App.");
App::new()
.insert_resource(WinitConfig {
.insert_resource(WinitSettings {
return_from_run: true,
..default()
})
.insert_resource(ClearColor(Color::rgb(0.2, 0.2, 0.8)))
.add_plugins(DefaultPlugins)
.add_system(system1)
.run();
println!("Running another App.");
App::new()
.insert_resource(WinitConfig {
.insert_resource(WinitSettings {
return_from_run: true,
..default()
})
.insert_resource(ClearColor(Color::rgb(0.2, 0.8, 0.2)))
.add_plugins_with(DefaultPlugins, |group| {
Expand Down
Loading

0 comments on commit f75df17

Please sign in to comment.