Skip to content

Commit

Permalink
Added a fps counter
Browse files Browse the repository at this point in the history
  • Loading branch information
rxn7 committed Mar 13, 2024
1 parent dbbec40 commit fd935af
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
28 changes: 28 additions & 0 deletions src/fps_counter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
pub struct FpsCounter {
last_frame_time: std::time::Instant,
frame_count: u32,
fps: u32
}

impl FpsCounter {
pub fn new() -> Self {
Self {
last_frame_time: std::time::Instant::now(),
frame_count: 0,
fps: 0,
}
}

pub fn fps(&self) -> u32 {
self.fps
}

pub fn tick(&mut self) {
self.frame_count += 1;
if self.last_frame_time.elapsed() > std::time::Duration::from_secs(1) {
self.fps = self.frame_count;
self.frame_count = 0;
self.last_frame_time = std::time::Instant::now();
}
}
}
8 changes: 7 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ mod color;
mod emitter;
mod particle;
mod renderer;
mod fps_counter;

use emitter::{EmitShape, Emitter, EmitterOptions};
use particle::Particle;
use fps_counter::FpsCounter;

use fontdue::{Font, FontSettings};
use glam::Vec2;
Expand Down Expand Up @@ -75,6 +78,7 @@ fn main() {
let mut particles: Vec<Particle> = Vec::with_capacity(1000);
let mut emitters: Vec<Emitter> = Vec::with_capacity(10);
let mut renderer: Renderer = Renderer::new(WIDTH, HEIGHT);
let mut fps_counter: FpsCounter = FpsCounter::new();

let mut last_win_size: (usize, usize) = window.get_size();
let mut last_start_time: std::time::Instant = std::time::Instant::now();
Expand All @@ -89,6 +93,8 @@ fn main() {
let frame_delta: std::time::Duration = last_start_time.elapsed();
last_start_time = std::time::Instant::now();

fps_counter.tick();

let win_size: (usize, usize) = window.get_size();
if win_size != last_win_size {
last_win_size = win_size;
Expand Down Expand Up @@ -121,7 +127,7 @@ fn main() {

renderer.draw_text(
&font,
format!("fps: {}\nparticles: {}", (1.0 / frame_delta.as_secs_f32()) as u32, particles.len()).as_str(),
format!("fps: {}\nparticles: {}", fps_counter.fps(), particles.len()).as_str(),
Vec2::ZERO,
8.0,
0xffffff,
Expand Down
1 change: 1 addition & 0 deletions src/particle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ impl Particle {

// Returns true if alive
pub fn update(&mut self, frame_delta: std::time::Duration, renderer: &mut Renderer) -> bool {
// Delete itself if it's out of bounds, TODO: Size should be used
if self.position.y < 0.0 || self.position.y > renderer.height() as f32 || self.position.x < 0.0 || self.position.x > renderer.width() as f32 {
return false;
}
Expand Down

0 comments on commit fd935af

Please sign in to comment.