Skip to content

Commit c1d392a

Browse files
authored
Reduce iOS cpu usage (bevyengine#16548)
# Objective - Avoid recreating the monitor every loop (temp fix until it's done properly on winit side) - Add a new `WinitSettings` preset for mobile that makes the winit loop wait more and recommend its usage
1 parent 75c92fb commit c1d392a

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

crates/bevy_winit/src/system.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,16 @@ pub fn create_monitors(
158158
seen_monitors[idx] = true;
159159
continue 'outer;
160160
}
161+
// on iOS, equality doesn't work, so we need to compare the names
162+
// otherwise the monitor entity is recreated every time
163+
// TODO: remove after https://github.com/rust-windowing/winit/pull/4013 has been released
164+
#[cfg(target_os = "ios")]
165+
{
166+
if monitor.name() == m.name() {
167+
seen_monitors[idx] = true;
168+
continue 'outer;
169+
}
170+
}
161171
}
162172

163173
let size = monitor.size();

crates/bevy_winit/src/winit_config.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,19 @@ impl WinitSettings {
3535
}
3636
}
3737

38+
/// Default settings for mobile.
39+
///
40+
/// [`Reactive`](UpdateMode::Reactive) if windows have focus,
41+
/// [`reactive_low_power`](UpdateMode::reactive_low_power) otherwise.
42+
///
43+
/// Use the [`EventLoopProxy`](crate::EventLoopProxy) to request a redraw from outside bevy.
44+
pub fn mobile() -> Self {
45+
WinitSettings {
46+
focused_mode: UpdateMode::reactive(Duration::from_secs_f32(1.0 / 60.0)),
47+
unfocused_mode: UpdateMode::reactive_low_power(Duration::from_secs(1)),
48+
}
49+
}
50+
3851
/// Returns the current [`UpdateMode`].
3952
///
4053
/// **Note:** The output depends on whether the window has focus or not.

examples/mobile/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use bevy::{
66
log::{Level, LogPlugin},
77
prelude::*,
88
window::{AppLifecycle, WindowMode},
9+
winit::WinitSettings,
910
};
1011

1112
// the `bevy_main` proc_macro generates the required boilerplate for iOS and Android
@@ -34,6 +35,9 @@ fn main() {
3435
..default()
3536
}),
3637
)
38+
// Make the winit loop wait more aggressively when no user input is received
39+
// This can help reduce cpu usage on mobile devices
40+
.insert_resource(WinitSettings::mobile())
3741
.add_systems(Startup, (setup_scene, setup_music))
3842
.add_systems(Update, (touch_camera, button_handler, handle_lifetime))
3943
.run();

0 commit comments

Comments
 (0)