Compare commits

...

3 Commits

Author SHA1 Message Date
Ryan Walters
5cc9b1a6ee fix: avoid acquiring filtered player query until movement command received 2025-08-28 14:17:46 -05:00
Ryan Walters
5d4adb7743 refactor: merge 'formatting' submodule into 'profiling' 2025-08-28 14:12:23 -05:00
Ryan Walters
633d467f2c chore: remove LevelTiming resource 2025-08-28 13:21:21 -05:00
8 changed files with 128 additions and 178 deletions

View File

@@ -18,8 +18,8 @@ use crate::systems::{
ghost_movement_system, hud_render_system, item_system, profile, ready_visibility_system, render_system, AudioEvent,
AudioResource, AudioState, BackbufferResource, Collider, DebugFontResource, DebugState, DebugTextureResource, DeltaTime,
DirectionalAnimated, EntityType, Frozen, Ghost, GhostBundle, GhostCollider, GlobalState, ItemBundle, ItemCollider,
LevelTiming, MapTextureResource, PacmanCollider, PlayerBundle, PlayerControlled, PlayerStateBundle, Renderable,
ScoreResource, StartupSequence, SystemTimings,
MapTextureResource, PacmanCollider, PlayerBundle, PlayerControlled, PlayerStateBundle, Renderable, ScoreResource,
StartupSequence, SystemTimings,
};
use crate::texture::animated::AnimatedTexture;
use bevy_ecs::event::EventRegistry;
@@ -227,7 +227,6 @@ impl Game {
world.insert_resource(DebugState::default());
world.insert_resource(AudioState::default());
world.insert_resource(CursorPosition::default());
world.insert_resource(LevelTiming::for_level(1));
world.add_observer(
|event: Trigger<GameEvent>, mut state: ResMut<GlobalState>, _score: ResMut<ScoreResource>| {
@@ -295,15 +294,7 @@ impl Game {
.chain(),
));
// Initialize StartupSequence as a global resource
let ready_duration_ticks = {
let duration = world
.get_resource::<LevelTiming>()
.map(|t| t.spawn_freeze_duration)
.unwrap_or(1.5);
(duration * 60.0) as u32 // Convert to ticks at 60 FPS
};
world.insert_resource(StartupSequence::new(ready_duration_ticks, 60));
world.insert_resource(StartupSequence::new(60 * 3, 60));
// Spawn ghosts
Self::spawn_ghosts(&mut world)?;

View File

@@ -141,35 +141,6 @@ impl Default for MovementModifiers {
}
}
/// Level-dependent timing configuration
#[derive(Resource, Debug, Clone, Copy)]
pub struct LevelTiming {
/// Duration of energizer effect in seconds
pub energizer_duration: f32,
/// Freeze duration at spawn/ready in seconds
pub spawn_freeze_duration: f32,
/// When to start flashing relative to energizer end (seconds)
pub energizer_flash_threshold: f32,
}
impl Default for LevelTiming {
fn default() -> Self {
Self {
energizer_duration: 6.0,
spawn_freeze_duration: 1.5,
energizer_flash_threshold: 2.0,
}
}
}
impl LevelTiming {
/// Returns timing configuration for a given level.
pub fn for_level(_level: u32) -> Self {
// Placeholder: tune per the Pac-Man Dossier tables
Self::default()
}
}
/// Tag component for entities that should be frozen during startup
#[derive(Component, Debug, Clone, Copy)]
pub struct Frozen;

View File

@@ -1,107 +0,0 @@
use num_width::NumberWidth;
use smallvec::SmallVec;
use std::time::Duration;
use strum::EnumCount;
use crate::systems::profiling::SystemId;
// Helper to split a duration into a integer, decimal, and unit
fn get_value(duration: &Duration) -> (u64, u32, &'static str) {
let (int, decimal, unit) = match duration {
// if greater than 1 second, return as seconds
n if n >= &Duration::from_secs(1) => {
let secs = n.as_secs();
let decimal = n.as_millis() as u64 % 1000;
(secs, decimal as u32, "s")
}
// if greater than 1 millisecond, return as milliseconds
n if n >= &Duration::from_millis(1) => {
let ms = n.as_millis() as u64;
let decimal = n.as_micros() as u64 % 1000;
(ms, decimal as u32, "ms")
}
// if greater than 1 microsecond, return as microseconds
n if n >= &Duration::from_micros(1) => {
let us = n.as_micros() as u64;
let decimal = n.as_nanos() as u64 % 1000;
(us, decimal as u32, "µs")
}
// otherwise, return as nanoseconds
n => {
let ns = n.as_nanos() as u64;
(ns, 0, "ns")
}
};
(int, decimal, unit)
}
/// Formats timing data into a vector of strings with proper alignment
pub fn format_timing_display(
timing_data: impl IntoIterator<Item = (String, Duration, Duration)>,
) -> SmallVec<[String; SystemId::COUNT]> {
let mut iter = timing_data.into_iter().peekable();
if iter.peek().is_none() {
return SmallVec::new();
}
struct Entry {
name: String,
avg_int: u64,
avg_decimal: u32,
avg_unit: &'static str,
std_int: u64,
std_decimal: u32,
std_unit: &'static str,
}
let entries = iter
.map(|(name, avg, std_dev)| {
let (avg_int, avg_decimal, avg_unit) = get_value(&avg);
let (std_int, std_decimal, std_unit) = get_value(&std_dev);
Entry {
name: name.clone(),
avg_int,
avg_decimal,
avg_unit,
std_int,
std_decimal,
std_unit,
}
})
.collect::<SmallVec<[Entry; 12]>>();
let (max_name_width, max_avg_int_width, max_avg_decimal_width, max_std_int_width, max_std_decimal_width) = entries
.iter()
.fold((0, 0, 3, 0, 3), |(name_w, avg_int_w, avg_dec_w, std_int_w, std_dec_w), e| {
(
name_w.max(e.name.len()),
avg_int_w.max(e.avg_int.width() as usize),
avg_dec_w.max(e.avg_decimal.width() as usize),
std_int_w.max(e.std_int.width() as usize),
std_dec_w.max(e.std_decimal.width() as usize),
)
});
entries.iter().map(|e| {
format!(
"{name:max_name_width$} : {avg_int:max_avg_int_width$}.{avg_decimal:<max_avg_decimal_width$}{avg_unit} ± {std_int:max_std_int_width$}.{std_decimal:<max_std_decimal_width$}{std_unit}",
// Content
name = e.name,
avg_int = e.avg_int,
avg_decimal = e.avg_decimal,
std_int = e.std_int,
std_decimal = e.std_decimal,
// Units
avg_unit = e.avg_unit,
std_unit = e.std_unit,
// Padding
max_name_width = max_name_width,
max_avg_int_width = max_avg_int_width,
max_avg_decimal_width = max_avg_decimal_width,
max_std_int_width = max_std_int_width,
max_std_decimal_width = max_std_decimal_width
)
}).collect::<SmallVec<[String; SystemId::COUNT]>>()
}

View File

@@ -2,12 +2,12 @@ use bevy_ecs::{
entity::Entity,
event::{EventReader, EventWriter},
query::With,
system::{Commands, Query, Res, ResMut},
system::{Commands, Query, ResMut},
};
use crate::{
events::GameEvent,
systems::{AudioEvent, EntityType, GhostCollider, ItemCollider, LevelTiming, PacmanCollider, ScoreResource, Vulnerable},
systems::{AudioEvent, EntityType, GhostCollider, ItemCollider, PacmanCollider, ScoreResource, Vulnerable},
};
/// Determines if a collision between two entity types should be handled by the item system.
@@ -29,7 +29,6 @@ pub fn item_system(
item_query: Query<(Entity, &EntityType), With<ItemCollider>>,
ghost_query: Query<Entity, With<GhostCollider>>,
mut events: EventWriter<AudioEvent>,
level_timing: Res<LevelTiming>,
) {
for event in collision_events.read() {
if let GameEvent::Collision(entity1, entity2) = event {
@@ -58,7 +57,7 @@ pub fn item_system(
// Make ghosts vulnerable when power pellet is collected
if *entity_type == EntityType::PowerPellet {
// Convert seconds to frames (assumes 60 FPS)
let total_ticks = (level_timing.energizer_duration * 60.0).round().clamp(0.0, u32::MAX as f32) as u32;
let total_ticks = 60 * 5;
// Add Vulnerable component to all ghosts
for ghost_entity in ghost_query.iter() {

View File

@@ -8,7 +8,6 @@ pub mod blinking;
pub mod collision;
pub mod components;
pub mod debug;
pub mod formatting;
pub mod ghost;
pub mod input;
pub mod item;

View File

@@ -39,6 +39,11 @@ impl Default for PlayerLifecycle {
}
}
pub fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
let entity_flags = entity_type.traversal_flags();
edge.traversal_flags.contains(entity_flags)
}
/// Processes player input commands and updates game state accordingly.
///
/// Handles keyboard-driven commands like movement direction changes, debug mode
@@ -50,29 +55,26 @@ pub fn player_control_system(
mut state: ResMut<GlobalState>,
mut debug_state: ResMut<DebugState>,
mut audio_state: ResMut<AudioState>,
mut players: Query<(&PlayerLifecycle, &mut BufferedDirection), (With<PlayerControlled>, Without<Frozen>)>,
mut players: Query<&mut BufferedDirection, (With<PlayerControlled>, Without<Frozen>)>,
mut errors: EventWriter<GameError>,
) {
// Get the player's movable component (ensuring there is only one player)
let (lifecycle, mut buffered_direction) = match players.single_mut() {
Ok(tuple) => tuple,
Err(e) => {
errors.write(GameError::InvalidState(format!(
"No/multiple entities queried for player system: {}",
e
)));
return;
}
};
// If the player is not interactive or input is locked, ignore movement commands
// let allow_input = lifecycle.is_interactive();
// Handle events
for event in events.read() {
if let GameEvent::Command(command) = event {
match command {
GameCommand::MovePlayer(direction) => {
// Get the player's movable component (ensuring there is only one player)
let (mut buffered_direction) = match players.single_mut() {
Ok(tuple) => tuple,
Err(e) => {
errors.write(GameError::InvalidState(format!(
"No/multiple entities queried for player system: {}",
e
)));
return;
}
};
*buffered_direction = BufferedDirection::Some {
direction: *direction,
remaining_time: 0.25,
@@ -94,11 +96,6 @@ pub fn player_control_system(
}
}
pub fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
let entity_flags = entity_type.traversal_flags();
edge.traversal_flags.contains(entity_flags)
}
/// Executes frame-by-frame movement for Pac-Man.
///
/// Handles movement logic including buffered direction changes, edge traversal validation, and continuous movement between nodes.

View File

@@ -2,6 +2,7 @@ use bevy_ecs::system::IntoSystem;
use bevy_ecs::{resource::Resource, system::System};
use circular_buffer::CircularBuffer;
use micromap::Map;
use num_width::NumberWidth;
use parking_lot::{Mutex, RwLock};
use smallvec::SmallVec;
use std::fmt::Display;
@@ -10,8 +11,6 @@ use strum::EnumCount;
use strum_macros::{EnumCount, IntoStaticStr};
use thousands::Separable;
use crate::systems::formatting;
/// The maximum number of systems that can be profiled. Must not be exceeded, or it will panic.
const MAX_SYSTEMS: usize = SystemId::COUNT;
/// The number of durations to keep in the circular buffer.
@@ -159,7 +158,7 @@ impl SystemTimings {
}
// Use the formatting module to format the data
formatting::format_timing_display(timing_data)
format_timing_display(timing_data)
}
}
@@ -184,3 +183,104 @@ where
}
}
}
// Helper to split a duration into a integer, decimal, and unit
fn get_value(duration: &Duration) -> (u64, u32, &'static str) {
let (int, decimal, unit) = match duration {
// if greater than 1 second, return as seconds
n if n >= &Duration::from_secs(1) => {
let secs = n.as_secs();
let decimal = n.as_millis() as u64 % 1000;
(secs, decimal as u32, "s")
}
// if greater than 1 millisecond, return as milliseconds
n if n >= &Duration::from_millis(1) => {
let ms = n.as_millis() as u64;
let decimal = n.as_micros() as u64 % 1000;
(ms, decimal as u32, "ms")
}
// if greater than 1 microsecond, return as microseconds
n if n >= &Duration::from_micros(1) => {
let us = n.as_micros() as u64;
let decimal = n.as_nanos() as u64 % 1000;
(us, decimal as u32, "µs")
}
// otherwise, return as nanoseconds
n => {
let ns = n.as_nanos() as u64;
(ns, 0, "ns")
}
};
(int, decimal, unit)
}
/// Formats timing data into a vector of strings with proper alignment
pub fn format_timing_display(
timing_data: impl IntoIterator<Item = (String, Duration, Duration)>,
) -> SmallVec<[String; SystemId::COUNT]> {
let mut iter = timing_data.into_iter().peekable();
if iter.peek().is_none() {
return SmallVec::new();
}
struct Entry {
name: String,
avg_int: u64,
avg_decimal: u32,
avg_unit: &'static str,
std_int: u64,
std_decimal: u32,
std_unit: &'static str,
}
let entries = iter
.map(|(name, avg, std_dev)| {
let (avg_int, avg_decimal, avg_unit) = get_value(&avg);
let (std_int, std_decimal, std_unit) = get_value(&std_dev);
Entry {
name: name.clone(),
avg_int,
avg_decimal,
avg_unit,
std_int,
std_decimal,
std_unit,
}
})
.collect::<SmallVec<[Entry; 12]>>();
let (max_name_width, max_avg_int_width, max_avg_decimal_width, max_std_int_width, max_std_decimal_width) = entries
.iter()
.fold((0, 0, 3, 0, 3), |(name_w, avg_int_w, avg_dec_w, std_int_w, std_dec_w), e| {
(
name_w.max(e.name.len()),
avg_int_w.max(e.avg_int.width() as usize),
avg_dec_w.max(e.avg_decimal.width() as usize),
std_int_w.max(e.std_int.width() as usize),
std_dec_w.max(e.std_decimal.width() as usize),
)
});
entries.iter().map(|e| {
format!(
"{name:max_name_width$} : {avg_int:max_avg_int_width$}.{avg_decimal:<max_avg_decimal_width$}{avg_unit} ± {std_int:max_std_int_width$}.{std_decimal:<max_std_decimal_width$}{std_unit}",
// Content
name = e.name,
avg_int = e.avg_int,
avg_decimal = e.avg_decimal,
std_int = e.std_int,
std_decimal = e.std_decimal,
// Units
avg_unit = e.avg_unit,
std_unit = e.std_unit,
// Padding
max_name_width = max_name_width,
max_avg_int_width = max_avg_int_width,
max_avg_decimal_width = max_avg_decimal_width,
max_std_int_width = max_std_int_width,
max_std_decimal_width = max_std_decimal_width
)
}).collect::<SmallVec<[String; SystemId::COUNT]>>()
}

View File

@@ -1,4 +1,4 @@
use pacman::systems::formatting::format_timing_display;
use pacman::systems::profiling::format_timing_display;
use std::time::Duration;
use pretty_assertions::assert_eq;