-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Add framelimiter winit #23486
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
joelawm
wants to merge
4
commits into
bevyengine:main
Choose a base branch
from
joelawm:add-framelimiter-winit
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Add framelimiter winit #23486
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| //! Demonstrates capping Bevy's frame rate in the `winit` event loop. | ||
| //! | ||
| //! Press space to toggle the limiter and up and down to change the target FPS. | ||
| //! The on-screen text shows the requested limit alongside the measured smoothed FPS. | ||
|
|
||
| use bevy::{ | ||
| color::palettes::basic::{LIME, YELLOW}, | ||
| diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin}, | ||
| prelude::*, | ||
| window::{PresentMode, WindowPlugin}, | ||
| winit::WinitSettings, | ||
| }; | ||
|
|
||
| const DEFAULT_FPS: u16 = 60; | ||
| const MIN_FPS: u16 = 30; | ||
| const MAX_FPS: u16 = 240; | ||
| const FPS_STEP: u16 = 30; | ||
|
|
||
| fn main() { | ||
| App::new() | ||
| .insert_resource(FrameLimiterSettings::default()) | ||
| .insert_resource(WinitSettings::game_with_max_fps(DEFAULT_FPS as f64)) | ||
| .add_plugins(( | ||
| DefaultPlugins.set(WindowPlugin { | ||
| primary_window: Some(Window { | ||
| title: "Frame limiter".into(), | ||
| present_mode: PresentMode::AutoNoVsync, | ||
| ..default() | ||
| }), | ||
| ..default() | ||
| }), | ||
| FrameTimeDiagnosticsPlugin::default(), | ||
| )) | ||
| .add_systems(Startup, setup) | ||
| .add_systems( | ||
| Update, | ||
| ( | ||
| adjust_frame_limiter, | ||
| apply_frame_limiter, | ||
| rotate_cube, | ||
| update_overlay, | ||
| ), | ||
| ) | ||
| .run(); | ||
| } | ||
|
|
||
| #[derive(Resource, Debug, Clone)] | ||
| struct FrameLimiterSettings { | ||
| enabled: bool, | ||
| max_fps: u16, | ||
| } | ||
|
|
||
| impl Default for FrameLimiterSettings { | ||
| fn default() -> Self { | ||
| Self { | ||
| enabled: true, | ||
| max_fps: DEFAULT_FPS, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl FrameLimiterSettings { | ||
| fn winit_settings(&self) -> WinitSettings { | ||
| if self.enabled { | ||
| WinitSettings::game_with_max_fps(self.max_fps as f64) | ||
| } else { | ||
| WinitSettings::game() | ||
| } | ||
| } | ||
|
|
||
| fn limiter_label(&self) -> String { | ||
| if self.enabled { | ||
| format!("capped at {} FPS", self.max_fps) | ||
| } else { | ||
| "uncapped".to_string() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[derive(Component)] | ||
| struct Rotator; | ||
|
|
||
| #[derive(Component)] | ||
| struct OverlayText; | ||
|
|
||
| fn setup( | ||
| mut commands: Commands, | ||
| mut meshes: ResMut<Assets<Mesh>>, | ||
| mut materials: ResMut<Assets<StandardMaterial>>, | ||
| ) { | ||
| commands.spawn(( | ||
| Mesh3d(meshes.add(Cuboid::new(0.7, 0.7, 0.7))), | ||
| 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), | ||
| )); | ||
|
|
||
| commands.spawn(( | ||
| Text::default(), | ||
| Node { | ||
| align_self: AlignSelf::FlexStart, | ||
| position_type: PositionType::Absolute, | ||
| top: px(12), | ||
| left: px(12), | ||
| ..default() | ||
| }, | ||
| OverlayText, | ||
| children![ | ||
| TextSpan::new("Space: toggle limiter | Up/Down: target FPS\n"), | ||
| (TextSpan::default(), TextColor(LIME.into())), | ||
| (TextSpan::new("\nSmoothed FPS: "), TextColor(YELLOW.into())), | ||
| (TextSpan::new(""), TextColor(YELLOW.into())), | ||
| ], | ||
| )); | ||
| } | ||
|
|
||
| fn adjust_frame_limiter( | ||
| input: Res<ButtonInput<KeyCode>>, | ||
| mut settings: ResMut<FrameLimiterSettings>, | ||
| ) { | ||
| let mut changed = false; | ||
|
|
||
| if input.just_pressed(KeyCode::Space) { | ||
| settings.enabled = !settings.enabled; | ||
| changed = true; | ||
| } | ||
|
|
||
| if input.just_pressed(KeyCode::ArrowUp) { | ||
| settings.max_fps = (settings.max_fps + FPS_STEP).min(MAX_FPS); | ||
| settings.enabled = true; | ||
| changed = true; | ||
| } | ||
|
|
||
| if input.just_pressed(KeyCode::ArrowDown) { | ||
| settings.max_fps = settings.max_fps.saturating_sub(FPS_STEP).max(MIN_FPS); | ||
| settings.enabled = true; | ||
| changed = true; | ||
| } | ||
|
|
||
| if changed { | ||
| info!("Frame limiter updated: {}", settings.limiter_label()); | ||
| } | ||
| } | ||
|
|
||
| fn apply_frame_limiter( | ||
| settings: Res<FrameLimiterSettings>, | ||
| mut winit_settings: ResMut<WinitSettings>, | ||
| mut window: Single<&mut Window>, | ||
| ) { | ||
| if !settings.is_changed() { | ||
| return; | ||
| } | ||
|
|
||
| *winit_settings = settings.winit_settings(); | ||
| window.title = format!("Frame limiter | {}", settings.limiter_label()); | ||
| } | ||
|
|
||
| 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_secs()); | ||
| transform.rotate_local_y(time.delta_secs()); | ||
| } | ||
| } | ||
|
|
||
| fn update_overlay( | ||
| settings: Res<FrameLimiterSettings>, | ||
| diagnostics: Res<DiagnosticsStore>, | ||
| text: Single<Entity, With<OverlayText>>, | ||
| mut writer: TextUiWriter, | ||
| ) { | ||
| *writer.text(*text, 1) = format!("Mode: {}", settings.limiter_label(),); | ||
|
|
||
| let fps = diagnostics | ||
| .get(&FrameTimeDiagnosticsPlugin::FPS) | ||
| .and_then(bevy::diagnostic::Diagnostic::smoothed) | ||
| .map(|value| format!("{value:.1}")) | ||
| .unwrap_or_else(|| "--".to_string()); | ||
| *writer.text(*text, 3) = fps; | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I really don't like defaulting to 60 fps locked. Winit exposes the monitor refresh rate which should always be used when it's available.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Additionally,
winitonly provides monitor Hz to the nearest integer. If you don't round your fps up, you'll end up accumulating frames and latency, which defeats the point of pacing.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://github.com/aevyrie/bevy_framepace/blob/873ee0b4631b414dca03dc41b1a7c1f8e1c9b672/src/lib.rs#L210