Compare commits

..

6 Commits

21 changed files with 309 additions and 249 deletions

View File

@@ -1,5 +1,13 @@
name: Builds name: Builds
on: ["push", "pull_request"]
on:
push:
branches:
- master
pull_request:
branches:
- master
workflow_dispatch:
permissions: permissions:
contents: write contents: write

View File

@@ -1,6 +1,13 @@
name: Checks name: Checks
on: ["push", "pull_request"] on:
push:
branches:
- master
pull_request:
branches:
- master
workflow_dispatch:
env: env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always

View File

@@ -1,6 +1,12 @@
name: Code Coverage name: Code Coverage
on: ["push", "pull_request"] on:
push:
branches:
- master
pull_request:
branches:
- master
env: env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always

View File

@@ -1,6 +1,13 @@
name: Tests name: Tests
on: ["push", "pull_request"] on:
push:
branches:
- master
pull_request:
branches:
- master
workflow_dispatch:
env: env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always

3
.gitignore vendored
View File

@@ -20,3 +20,6 @@ coverage.html
# Profiling output # Profiling output
flamegraph.svg flamegraph.svg
/profile.* /profile.*
# Logs
*.log

2
Cargo.lock generated
View File

@@ -711,7 +711,7 @@ checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]] [[package]]
name = "pacman" name = "pacman"
version = "0.80.1" version = "0.80.3"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bevy_ecs", "bevy_ecs",

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "pacman" name = "pacman"
version = "0.80.1" version = "0.80.3"
authors = ["Xevion"] authors = ["Xevion"]
edition = "2021" edition = "2021"
rust-version = "1.86.0" rust-version = "1.86.0"
@@ -89,6 +89,12 @@ opt-level = "z"
lto = true lto = true
panic = "abort" panic = "abort"
# This profile is intended to appear as a 'release' profile to the build system due to`debug_assertions = false`,
# but it will compile faster without optimizations. Useful for rapid testing of release-mode logic.
[profile.dev-release]
inherits = "dev"
debug-assertions = false
[package.metadata.vcpkg] [package.metadata.vcpkg]
dependencies = ["sdl2", "sdl2-image", "sdl2-ttf", "sdl2-gfx", "sdl2-mixer"] dependencies = ["sdl2", "sdl2-image", "sdl2-ttf", "sdl2-gfx", "sdl2-mixer"]
git = "https://github.com/microsoft/vcpkg" git = "https://github.com/microsoft/vcpkg"
@@ -100,5 +106,10 @@ x86_64-unknown-linux-gnu = { triplet = "x64-linux" }
x86_64-apple-darwin = { triplet = "x64-osx" } x86_64-apple-darwin = { triplet = "x64-osx" }
aarch64-apple-darwin = { triplet = "arm64-osx" } aarch64-apple-darwin = { triplet = "arm64-osx" }
[features]
# Windows-specific features
force-console = []
default = []
[lints.rust] [lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage,coverage_nightly)'] } unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage,coverage_nightly)', 'cfg(use_console)'] }

View File

@@ -42,3 +42,6 @@ web *args:
fix: fix:
cargo fix --workspace --lib --allow-dirty cargo fix --workspace --lib --allow-dirty
cargo fmt --all cargo fmt --all
push:
git push origin --tags && git push

View File

@@ -132,7 +132,7 @@ A comprehensive list of features needed to complete the Pac-Man emulation, organ
- [x] Animation system - [x] Animation system
- [x] HUD rendering - [x] HUD rendering
- [ ] Display Options - [ ] Display Options
- [ ] Fullscreen support - [x] Fullscreen support
- [x] Window resizing - [x] Window resizing
- [ ] Pause while resizing (SDL2 limitation mitigation) - [ ] Pause while resizing (SDL2 limitation mitigation)
- [ ] Multiple resolution support - [ ] Multiple resolution support

View File

@@ -51,4 +51,11 @@ fn main() {
writeln!(&mut file, "}};").unwrap(); writeln!(&mut file, "}};").unwrap();
println!("cargo:rerun-if-changed=assets/game/atlas.json"); println!("cargo:rerun-if-changed=assets/game/atlas.json");
#[cfg(target_os = "windows")]
{
if cfg!(any(feature = "force-console", debug_assertions)) {
println!("cargo:rustc-cfg=use_console");
}
}
} }

View File

@@ -2,12 +2,18 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::asset::Asset; use crate::asset::Asset;
use anyhow::{anyhow, Result};
use sdl2::{ use sdl2::{
mixer::{self, Chunk, InitFlag, LoaderRWops, AUDIO_S16LSB, DEFAULT_CHANNELS}, mixer::{self, Chunk, InitFlag, LoaderRWops, AUDIO_S16LSB},
rwops::RWops, rwops::RWops,
}; };
use strum::IntoEnumIterator; use strum::IntoEnumIterator;
const AUDIO_FREQUENCY: i32 = 16_000;
const AUDIO_CHANNELS: i32 = 4;
const DEFAULT_VOLUME: u8 = 32;
const WAKA_SOUND_COUNT: u8 = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Sound { pub enum Sound {
Waka(u8), Waka(u8),
@@ -23,19 +29,16 @@ impl IntoEnumIterator for Sound {
type Iterator = std::vec::IntoIter<Sound>; type Iterator = std::vec::IntoIter<Sound>;
fn iter() -> Self::Iterator { fn iter() -> Self::Iterator {
vec![ let mut sounds = vec![
Sound::Waka(0),
Sound::Waka(1),
Sound::Waka(2),
Sound::Waka(3),
Sound::PacmanDeath, Sound::PacmanDeath,
Sound::ExtraLife, Sound::ExtraLife,
Sound::Fruit, Sound::Fruit,
Sound::Ghost, Sound::Ghost,
Sound::Beginning, Sound::Beginning,
Sound::Intermission, Sound::Intermission,
] ];
.into_iter() sounds.extend((0..WAKA_SOUND_COUNT).map(Sound::Waka));
sounds.into_iter()
} }
} }
@@ -48,8 +51,14 @@ pub struct Audio {
_mixer_context: Option<mixer::Sdl2MixerContext>, _mixer_context: Option<mixer::Sdl2MixerContext>,
sounds: HashMap<Sound, Chunk>, sounds: HashMap<Sound, Chunk>,
next_waka_index: u8, next_waka_index: u8,
muted: bool, state: AudioState,
disabled: bool, }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AudioState {
Enabled { volume: u8 },
Muted { previous_volume: u8 },
Disabled,
} }
impl Default for Audio { impl Default for Audio {
@@ -64,7 +73,21 @@ impl Audio {
/// If audio fails to initialize, the audio system will be disabled and /// If audio fails to initialize, the audio system will be disabled and
/// all functions will silently do nothing. /// all functions will silently do nothing.
pub fn new() -> Self { pub fn new() -> Self {
let frequency = 16_000; match Self::try_new() {
Ok(audio) => audio,
Err(e) => {
tracing::warn!("Failed to initialize audio: {}. Audio will be disabled.", e);
Self {
_mixer_context: None,
sounds: HashMap::new(),
next_waka_index: 0,
state: AudioState::Disabled,
}
}
}
}
fn try_new() -> Result<Self> {
let format = AUDIO_S16LSB; let format = AUDIO_S16LSB;
let chunk_size = { let chunk_size = {
// 256 is the minimum for Emscripten, but in practice 1024 is much more reliable // 256 is the minimum for Emscripten, but in practice 1024 is much more reliable
@@ -81,103 +104,52 @@ impl Audio {
}; };
// Try to open audio, but don't panic if it fails // Try to open audio, but don't panic if it fails
if let Err(e) = mixer::open_audio(frequency, format, DEFAULT_CHANNELS, chunk_size) { mixer::open_audio(AUDIO_FREQUENCY, format, AUDIO_CHANNELS, chunk_size)
tracing::warn!("Failed to open audio: {}. Audio will be disabled.", e); .map_err(|e| anyhow!("Failed to open audio: {}", e))?;
return Self {
_mixer_context: None,
sounds: HashMap::new(),
next_waka_index: 0u8,
muted: false,
disabled: true,
};
}
let channels = 4; mixer::allocate_channels(AUDIO_CHANNELS);
mixer::allocate_channels(4);
// set channel volume // set channel volume
for i in 0..channels { for i in 0..AUDIO_CHANNELS {
mixer::Channel(i).set_volume(32); mixer::Channel(i).set_volume(DEFAULT_VOLUME as i32);
} }
// Try to initialize mixer, but don't panic if it fails // Try to initialize mixer, but don't panic if it fails
let mixer_context = match mixer::init(InitFlag::OGG) { let mixer_context = mixer::init(InitFlag::OGG).map_err(|e| anyhow!("Failed to initialize SDL2_mixer: {}", e))?;
Ok(ctx) => ctx,
Err(e) => {
tracing::warn!("Failed to initialize SDL2_mixer: {}. Audio will be disabled.", e);
return Self {
_mixer_context: None,
sounds: HashMap::new(),
next_waka_index: 0u8,
muted: false,
disabled: true,
};
}
};
// Try to load sounds, but don't panic if any fail // Try to load sounds, but don't panic if any fail
let mut sounds = HashMap::new(); let sounds: HashMap<Sound, Chunk> = Sound::iter()
for (i, sound_type) in Sound::iter().enumerate() { .filter_map(|sound_type| match Self::load_sound(sound_type) {
let asset = Asset::SoundFile(sound_type); Ok(chunk) => Some((sound_type, chunk)),
match asset.get_bytes() {
Ok(data) => match RWops::from_bytes(&data) {
Ok(rwops) => match rwops.load_wav() {
Ok(chunk) => {
sounds.insert(sound_type, chunk);
}
Err(e) => {
tracing::warn!("Failed to load sound {} from asset API: {}", i + 1, e);
}
},
Err(e) => {
tracing::warn!("Failed to create RWops for sound {}: {}", i + 1, e);
}
},
Err(e) => { Err(e) => {
tracing::warn!("Failed to load sound asset {}: {}", i + 1, e); tracing::warn!("Failed to load sound {:?}: {}", sound_type, e);
}
}
}
let death_sound = match Asset::SoundFile(Sound::PacmanDeath).get_bytes() {
Ok(data) => match RWops::from_bytes(&data) {
Ok(rwops) => match rwops.load_wav() {
Ok(chunk) => Some(chunk),
Err(e) => {
tracing::warn!("Failed to load death sound from asset API: {}", e);
None
}
},
Err(e) => {
tracing::warn!("Failed to create RWops for death sound: {}", e);
None None
} }
}, })
Err(e) => { .collect();
tracing::warn!("Failed to load death sound asset: {}", e);
None
}
};
// If no sounds loaded successfully, disable audio // If no sounds loaded successfully, disable audio
if sounds.is_empty() && death_sound.is_none() { if sounds.is_empty() {
tracing::warn!("No sounds loaded successfully. Audio will be disabled."); return Err(anyhow!("No sounds loaded successfully"));
return Self {
_mixer_context: Some(mixer_context),
sounds: HashMap::new(),
next_waka_index: 0u8,
muted: false,
disabled: true,
};
} }
Audio { Ok(Audio {
_mixer_context: Some(mixer_context), _mixer_context: Some(mixer_context),
sounds, sounds,
next_waka_index: 0u8, next_waka_index: 0u8,
muted: false, state: AudioState::Enabled { volume: DEFAULT_VOLUME },
disabled: false, })
} }
fn load_sound(sound_type: Sound) -> Result<Chunk> {
let asset = Asset::SoundFile(sound_type);
let data = asset
.get_bytes()
.map_err(|e| anyhow!("Failed to get bytes for {:?}: {}", sound_type, e))?;
let rwops = RWops::from_bytes(&data).map_err(|e| anyhow!("Failed to create RWops for {:?}: {}", sound_type, e))?;
rwops
.load_wav()
.map_err(|e| anyhow!("Failed to load wav for {:?}: {}", sound_type, e))
} }
/// Plays the next waka eating sound in the cycle of four variants. /// Plays the next waka eating sound in the cycle of four variants.
@@ -186,7 +158,7 @@ impl Audio {
/// advances to the next variant. Silently returns if audio is disabled, muted, /// advances to the next variant. Silently returns if audio is disabled, muted,
/// or no sounds were loaded successfully. /// or no sounds were loaded successfully.
pub fn waka(&mut self) { pub fn waka(&mut self) {
if self.disabled || self.muted || self.sounds.is_empty() { if !matches!(self.state, AudioState::Enabled { .. }) {
return; return;
} }
@@ -200,12 +172,12 @@ impl Audio {
} }
} }
} }
self.next_waka_index = (self.next_waka_index + 1) & 3; self.next_waka_index = (self.next_waka_index + 1) % WAKA_SOUND_COUNT;
} }
/// Plays the provided sound effect once. /// Plays the provided sound effect once.
pub fn play(&mut self, sound: Sound) { pub fn play(&mut self, sound: Sound) {
if self.disabled || self.muted { if !matches!(self.state, AudioState::Enabled { .. }) {
return; return;
} }
@@ -216,21 +188,21 @@ impl Audio {
/// Halts all currently playing audio channels. /// Halts all currently playing audio channels.
pub fn stop_all(&mut self) { pub fn stop_all(&mut self) {
if !self.disabled { if self.state != AudioState::Disabled {
mixer::Channel::all().halt(); mixer::Channel::all().halt();
} }
} }
/// Pauses all currently playing audio channels. /// Pauses all currently playing audio channels.
pub fn pause_all(&mut self) { pub fn pause_all(&mut self) {
if !self.disabled { if self.state != AudioState::Disabled {
mixer::Channel::all().pause(); mixer::Channel::all().pause();
} }
} }
/// Resumes all currently playing audio channels. /// Resumes all currently playing audio channels.
pub fn resume_all(&mut self) { pub fn resume_all(&mut self) {
if !self.disabled { if self.state != AudioState::Disabled {
mixer::Channel::all().resume(); mixer::Channel::all().resume();
} }
} }
@@ -241,15 +213,23 @@ impl Audio {
/// their default volume (32) when unmuting. The mute state is tracked internally /// their default volume (32) when unmuting. The mute state is tracked internally
/// regardless of whether audio is disabled, allowing the state to be preserved. /// regardless of whether audio is disabled, allowing the state to be preserved.
pub fn set_mute(&mut self, mute: bool) { pub fn set_mute(&mut self, mute: bool) {
if !self.disabled { match (mute, self.state) {
let channels = 4; // Mute
let volume = if mute { 0 } else { 32 }; (true, AudioState::Enabled { volume }) => {
for i in 0..channels { self.state = AudioState::Muted { previous_volume: volume };
mixer::Channel(i).set_volume(volume); for i in 0..AUDIO_CHANNELS {
mixer::Channel(i).set_volume(0);
}
} }
// Unmute
(false, AudioState::Muted { previous_volume }) => {
self.state = AudioState::Enabled { volume: previous_volume };
for i in 0..AUDIO_CHANNELS {
mixer::Channel(i).set_volume(previous_volume as i32);
}
}
_ => {}
} }
self.muted = mute;
} }
/// Returns the current mute state regardless of whether audio is functional. /// Returns the current mute state regardless of whether audio is functional.
@@ -257,7 +237,7 @@ impl Audio {
/// This tracks the user's mute preference and will return `true` if muted /// This tracks the user's mute preference and will return `true` if muted
/// even when the audio system is disabled due to initialization failures. /// even when the audio system is disabled due to initialization failures.
pub fn is_muted(&self) -> bool { pub fn is_muted(&self) -> bool {
self.muted matches!(self.state, AudioState::Muted { .. })
} }
/// Returns whether the audio system failed to initialize and is non-functional. /// Returns whether the audio system failed to initialize and is non-functional.
@@ -266,6 +246,6 @@ impl Audio {
/// audio device, or failure to load any sound assets. When disabled, all /// audio device, or failure to load any sound assets. When disabled, all
/// audio operations become no-ops. /// audio operations become no-ops.
pub fn is_disabled(&self) -> bool { pub fn is_disabled(&self) -> bool {
self.disabled matches!(self.state, AudioState::Disabled)
} }
} }

View File

@@ -53,9 +53,9 @@ pub mod animation {
/// Frightened ghost animation speed (ticks per frame at 60 ticks/sec) /// Frightened ghost animation speed (ticks per frame at 60 ticks/sec)
pub const GHOST_FRIGHTENED_SPEED: u16 = 12; pub const GHOST_FRIGHTENED_SPEED: u16 = 12;
/// Time in ticks for frightened ghosts to return to normal /// Time in ticks for frightened ghosts to return to normal
pub const GHOST_FRIGHTENED_TICKS: u32 = 300; pub const GHOST_FRIGHTENED_TICKS: u32 = 5 * 60;
/// Time in ticks when frightened ghosts start flashing /// Time in ticks when frightened ghosts start flashing
pub const GHOST_FRIGHTENED_FLASH_START_TICKS: u32 = GHOST_FRIGHTENED_TICKS - 120; pub const GHOST_FRIGHTENED_FLASH_START_TICKS: u32 = GHOST_FRIGHTENED_TICKS - 2 * 60;
} }
/// The size of the canvas, in pixels. /// The size of the canvas, in pixels.
@@ -75,13 +75,15 @@ pub const LARGE_CANVAS_SIZE: UVec2 = UVec2::new(
pub mod collider { pub mod collider {
use super::CELL_SIZE; use super::CELL_SIZE;
/// Collider size for player and ghosts (1.375x cell size) /// Collider size for player and ghosts
pub const PLAYER_GHOST_SIZE: f32 = CELL_SIZE as f32 * 1.375; pub const PLAYER_SIZE: f32 = CELL_SIZE as f32 * 1.385;
/// Collider size for pellets (0.4x cell size) /// Collider size for ghosts
pub const GHOST_SIZE: f32 = CELL_SIZE as f32 * 1.55;
/// Collider size for pellets
pub const PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.4; pub const PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.4;
/// Collider size for power pellets/energizers (0.95x cell size) /// Collider size for power pellets/energizers
pub const POWER_PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.95; pub const POWER_PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.95;
/// Collider size for fruits (0.8x cell size) /// Collider size for fruits
pub const FRUIT_SIZE: f32 = CELL_SIZE as f32 * 1.375; pub const FRUIT_SIZE: f32 = CELL_SIZE as f32 * 1.375;
} }
@@ -148,7 +150,7 @@ pub const RAW_BOARD: [&str; BOARD_CELL_SIZE.y as usize] = [
/// Game initialization constants /// Game initialization constants
pub mod startup { pub mod startup {
/// Number of frames for the startup sequence (3 seconds at 60 FPS) /// Number of frames for the startup sequence (3 seconds at 60 FPS)
pub const STARTUP_FRAMES: u32 = 60 * 3; pub const STARTUP_FRAMES: u32 = 60 * 4;
} }
/// Game mechanics constants /// Game mechanics constants

View File

@@ -54,7 +54,6 @@ pub enum AssetError {
#[derive(thiserror::Error, Debug)] #[derive(thiserror::Error, Debug)]
pub enum PlatformError { pub enum PlatformError {
#[error("Console initialization failed: {0}")] #[error("Console initialization failed: {0}")]
#[cfg(any(windows, target_os = "emscripten"))]
ConsoleInit(String), ConsoleInit(String),
} }

View File

@@ -22,6 +22,7 @@ pub enum GameCommand {
/// TODO: Display pause state, fix debug rendering pause distress /// TODO: Display pause state, fix debug rendering pause distress
TogglePause, TogglePause,
/// Toggle fullscreen mode (desktop only) /// Toggle fullscreen mode (desktop only)
#[cfg(not(target_os = "emscripten"))]
ToggleFullscreen, ToggleFullscreen,
} }

View File

@@ -381,7 +381,7 @@ impl Game {
directional_animation: player_animation, directional_animation: player_animation,
entity_type: EntityType::Player, entity_type: EntityType::Player,
collider: Collider { collider: Collider {
size: constants::collider::PLAYER_GHOST_SIZE, size: constants::collider::PLAYER_SIZE,
}, },
pacman_collider: PacmanCollider, pacman_collider: PacmanCollider,
} }
@@ -629,7 +629,7 @@ impl Game {
directional_animation: animations, directional_animation: animations,
entity_type: EntityType::Ghost, entity_type: EntityType::Ghost,
collider: Collider { collider: Collider {
size: constants::collider::PLAYER_GHOST_SIZE, size: constants::collider::GHOST_SIZE,
}, },
ghost_collider: GhostCollider, ghost_collider: GhostCollider,
ghost_state: GhostState::Normal, ghost_state: GhostState::Normal,

View File

@@ -1,8 +1,10 @@
// Note: This disables the console window on Windows. We manually re-attach to the parent terminal or process later on. #![cfg_attr(all(not(use_console), target_os = "windows"), windows_subsystem = "windows")]
#![windows_subsystem = "windows"] #![cfg_attr(all(use_console, target_os = "windows"), windows_subsystem = "console")]
#![cfg_attr(coverage_nightly, feature(coverage_attribute))] #![cfg_attr(coverage_nightly, feature(coverage_attribute))]
#![cfg_attr(coverage_nightly, coverage(off))] #![cfg_attr(coverage_nightly, coverage(off))]
use std::env;
use crate::{app::App, constants::LOOP_TIME}; use crate::{app::App, constants::LOOP_TIME};
use tracing::info; use tracing::info;
@@ -32,9 +34,12 @@ mod texture;
/// This function initializes SDL, the window, the game state, and then enters /// This function initializes SDL, the window, the game state, and then enters
/// the main game loop. /// the main game loop.
pub fn main() { pub fn main() {
// On Windows, this connects output streams to the console dynamically // Parse command line arguments
let args: Vec<String> = env::args().collect();
let force_console = args.iter().any(|arg| arg == "--console" || arg == "-c");
// On Emscripten, this connects the subscriber to the browser console // On Emscripten, this connects the subscriber to the browser console
platform::init_console().expect("Could not initialize console"); platform::init_console(force_console).expect("Could not initialize console");
let mut app = App::new().expect("Could not create app"); let mut app = App::new().expect("Could not create app");

View File

@@ -20,41 +20,84 @@ pub fn sleep(duration: Duration, focused: bool) {
} }
} }
pub fn init_console() -> Result<(), PlatformError> { #[allow(unused_variables)]
pub fn init_console(force_console: bool) -> Result<(), PlatformError> {
use crate::formatter::CustomFormatter;
use tracing::Level;
use tracing_error::ErrorLayer;
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, Layer};
// Create a file layer
let log_file = std::fs::File::create("pacman.log")
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to create log file: {}", e)))?;
let file_layer = fmt::layer()
.with_ansi(false)
.with_writer(log_file)
.event_format(CustomFormatter)
.with_filter(tracing_subscriber::filter::LevelFilter::from_level(Level::DEBUG))
.boxed();
#[cfg(windows)] #[cfg(windows)]
{ {
use crate::platform::tracing_buffer::setup_switchable_subscriber; // If using windows subsystem, and force_console is true, allocate a new console window
use tracing::{debug, info, trace}; if force_console && cfg!(not(use_console)) {
use windows::Win32::System::Console::GetConsoleWindow; use crate::platform::tracing_buffer::{SwitchableMakeWriter, SwitchableWriter};
// Setup buffered tracing subscriber that will buffer logs until console is ready // Setup deferred tracing subscriber that will buffer logs until console is ready
let switchable_writer = setup_switchable_subscriber(); let switchable_writer = SwitchableWriter::default();
let make_writer = SwitchableMakeWriter::new(switchable_writer.clone());
let console_layer = fmt::layer()
.with_ansi(true)
.with_writer(make_writer)
.event_format(CustomFormatter)
.with_filter(tracing_subscriber::filter::LevelFilter::from_level(Level::DEBUG))
.boxed();
// Check if we already have a console window tracing_subscriber::registry()
if unsafe { !GetConsoleWindow().0.is_null() } { .with(console_layer)
debug!("Already have a console window"); .with(file_layer)
return Ok(()); .with(ErrorLayer::default())
.init();
// Enable virtual terminal processing for ANSI colors
allocate_console()?;
enable_ansi_support()?;
switchable_writer
.switch_to_direct_mode()
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to switch to direct mode: {}", e)))?;
} else { } else {
trace!("No existing console window found"); // Set up tracing subscriber with ANSI colors enabled
let console_layer = fmt::layer()
.with_ansi(true)
.with_writer(std::io::stdout)
.event_format(CustomFormatter)
.with_filter(tracing_subscriber::filter::LevelFilter::from_level(Level::DEBUG))
.boxed();
tracing_subscriber::registry()
.with(console_layer)
.with(file_layer)
.with(ErrorLayer::default())
.init();
} }
}
if let Some(file_type) = is_output_setup()? { #[cfg(not(windows))]
trace!(r#type = file_type, "Existing output detected"); {
} else { // Set up tracing subscriber with ANSI colors enabled
trace!("No existing output detected"); let console_layer = fmt::layer()
.with_ansi(true)
.with_writer(std::io::stdout)
.event_format(CustomFormatter)
.with_filter(tracing_subscriber::filter::LevelFilter::from_level(Level::DEBUG))
.boxed();
// Try to attach to parent console for direct cargo run tracing_subscriber::registry()
attach_to_parent_console()?; .with(console_layer)
info!("Successfully attached to parent console"); .with(file_layer)
} .with(ErrorLayer::default())
.init();
// Now that console is initialized, flush buffered logs and switch to direct output
trace!("Switching to direct logging mode and flushing buffer...");
if let Err(error) = switchable_writer.switch_to_direct_mode() {
use tracing::warn;
warn!("Failed to flush buffered logs to console: {error:?}");
}
} }
Ok(()) Ok(())
@@ -64,73 +107,66 @@ pub fn rng() -> ThreadRng {
rand::rng() rand::rng()
} }
/* Internal functions */ /// Enable ANSI escape sequence support in the Windows console
/// Check if the output stream has been setup by a parent process
/// Windows-only /// Windows-only
#[cfg(windows)] #[cfg(windows)]
fn is_output_setup() -> Result<Option<&'static str>, PlatformError> { fn enable_ansi_support() -> Result<(), PlatformError> {
use tracing::{trace, warn}; use windows::Win32::System::Console::{
GetConsoleMode, GetStdHandle, SetConsoleMode, CONSOLE_MODE, ENABLE_VIRTUAL_TERMINAL_PROCESSING, STD_ERROR_HANDLE,
use windows::Win32::Storage::FileSystem::{ STD_OUTPUT_HANDLE,
GetFileType, FILE_TYPE_CHAR, FILE_TYPE_DISK, FILE_TYPE_PIPE, FILE_TYPE_REMOTE, FILE_TYPE_UNKNOWN,
}; };
use windows_sys::Win32::{ // Enable ANSI processing for stdout
Foundation::INVALID_HANDLE_VALUE, unsafe {
System::Console::{GetStdHandle, STD_OUTPUT_HANDLE}, let stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE)
}; .map_err(|e| PlatformError::ConsoleInit(format!("Failed to get stdout handle: {:?}", e)))?;
// Get the process's standard output handle, check if it's invalid let mut console_mode = CONSOLE_MODE(0);
let handle = match unsafe { GetStdHandle(STD_OUTPUT_HANDLE) } { GetConsoleMode(stdout_handle, &mut console_mode)
INVALID_HANDLE_VALUE => { .map_err(|e| PlatformError::ConsoleInit(format!("Failed to get console mode: {:?}", e)))?;
return Err(PlatformError::ConsoleInit("Invalid handle".to_string()));
}
handle => handle,
};
// Identify the file type of the handle and whether it's 'well known' (i.e. we trust it to be a reasonable output destination) console_mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
let (well_known, file_type) = match unsafe { SetConsoleMode(stdout_handle, console_mode)
use windows::Win32::Foundation::HANDLE; .map_err(|e| PlatformError::ConsoleInit(format!("Failed to enable ANSI for stdout: {:?}", e)))?;
GetFileType(HANDLE(handle)) }
} {
FILE_TYPE_PIPE => (true, "pipe"),
FILE_TYPE_CHAR => (true, "char"),
FILE_TYPE_DISK => (true, "disk"),
FILE_TYPE_UNKNOWN => (false, "unknown"),
FILE_TYPE_REMOTE => (false, "remote"),
unexpected => {
warn!("Unexpected file type: {unexpected:?}");
(false, "unknown")
}
};
trace!("File type: {file_type:?}, well known: {well_known}"); // Enable ANSI processing for stderr
unsafe {
let stderr_handle = GetStdHandle(STD_ERROR_HANDLE)
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to get stderr handle: {:?}", e)))?;
// If it's anything recognizable and valid, assume that a parent process has setup an output stream let mut console_mode = CONSOLE_MODE(0);
Ok(well_known.then_some(file_type)) GetConsoleMode(stderr_handle, &mut console_mode)
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to get console mode: {:?}", e)))?;
console_mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(stderr_handle, console_mode)
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to enable ANSI for stderr: {:?}", e)))?;
}
Ok(())
} }
/// Try to attach to parent console /// Allocate a new console window for the process
/// Windows-only /// Windows-only
#[cfg(windows)] #[cfg(windows)]
fn attach_to_parent_console() -> Result<(), PlatformError> { fn allocate_console() -> Result<(), PlatformError> {
use windows::{ use windows::{
core::PCSTR, core::PCSTR,
Win32::{ Win32::{
Foundation::{GENERIC_READ, GENERIC_WRITE}, Foundation::{GENERIC_READ, GENERIC_WRITE},
Storage::FileSystem::{CreateFileA, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING}, Storage::FileSystem::{CreateFileA, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING},
System::Console::{ System::Console::{AllocConsole, SetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE},
AttachConsole, FreeConsole, SetStdHandle, ATTACH_PARENT_PROCESS, STD_ERROR_HANDLE, STD_OUTPUT_HANDLE,
},
}, },
}; };
// Attach the process to the parent's console // Allocate a new console for this process
unsafe { AttachConsole(ATTACH_PARENT_PROCESS) } unsafe { AllocConsole() }.map_err(|e| PlatformError::ConsoleInit(format!("Failed to allocate console: {:?}", e)))?;
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to attach to parent console: {:?}", e)))?;
let handle = unsafe { // Note: SetConsoleTitle is not available in the imported modules, skipping title setting
// Redirect stdout
let stdout_handle = unsafe {
let pcstr = PCSTR::from_raw(c"CONOUT$".as_ptr() as *const u8); let pcstr = PCSTR::from_raw(c"CONOUT$".as_ptr() as *const u8);
CreateFileA::<PCSTR>( CreateFileA::<PCSTR>(
pcstr, pcstr,
@@ -142,28 +178,32 @@ fn attach_to_parent_console() -> Result<(), PlatformError> {
None, None,
) )
} }
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to create console handle: {:?}", e)))?; .map_err(|e| PlatformError::ConsoleInit(format!("Failed to create stdout handle: {:?}", e)))?;
// Set the console's output and then error handles // Redirect stdin
if let Some(handle_error) = unsafe { SetStdHandle(STD_OUTPUT_HANDLE, handle) } let stdin_handle = unsafe {
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to set console output handle: {:?}", e))) let pcstr = PCSTR::from_raw(c"CONIN$".as_ptr() as *const u8);
.and_then(|_| { CreateFileA::<PCSTR>(
unsafe { SetStdHandle(STD_ERROR_HANDLE, handle) } pcstr,
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to set console error handle: {:?}", e))) (GENERIC_READ | GENERIC_WRITE).0,
}) FILE_SHARE_READ | FILE_SHARE_WRITE,
.err() None,
{ OPEN_EXISTING,
// If either set handle call fails, free the console FILE_FLAGS_AND_ATTRIBUTES(0),
unsafe { FreeConsole() } None,
// Free the console if the SetStdHandle calls fail )
.map_err(|free_error| {
PlatformError::ConsoleInit(format!(
"Failed to free console after SetStdHandle failed: {free_error:?} ({handle_error:?})"
))
})
// And then return the original error if the FreeConsole call succeeds
.and(Err(handle_error))?;
} }
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to create stdin handle: {:?}", e)))?;
// Set the standard handles
unsafe { SetStdHandle(STD_OUTPUT_HANDLE, stdout_handle) }
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to set stdout handle: {:?}", e)))?;
unsafe { SetStdHandle(STD_ERROR_HANDLE, stdout_handle) }
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to set stderr handle: {:?}", e)))?;
unsafe { SetStdHandle(STD_INPUT_HANDLE, stdin_handle) }
.map_err(|e| PlatformError::ConsoleInit(format!("Failed to set stdin handle: {:?}", e)))?;
Ok(()) Ok(())
} }

View File

@@ -19,7 +19,7 @@ pub fn sleep(duration: Duration, _focused: bool) {
} }
} }
pub fn init_console() -> Result<(), PlatformError> { pub fn init_console(_force_console: bool) -> Result<(), PlatformError> {
use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter}; use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter};
// Set up a custom tracing subscriber that writes directly to emscripten console // Set up a custom tracing subscriber that writes directly to emscripten console

View File

@@ -1,14 +1,11 @@
//! Buffered tracing setup for handling logs before console attachment. //! Buffered tracing setup for handling logs before console attachment.
use crate::formatter::CustomFormatter;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::io; use std::io;
use std::io::Write; use std::io::Write;
use std::sync::Arc; use std::sync::Arc;
use tracing::{debug, Level}; use tracing::debug;
use tracing_error::ErrorLayer;
use tracing_subscriber::fmt::MakeWriter; use tracing_subscriber::fmt::MakeWriter;
use tracing_subscriber::layer::SubscriberExt;
/// A thread-safe buffered writer that stores logs in memory until flushed. /// A thread-safe buffered writer that stores logs in memory until flushed.
#[derive(Clone)] #[derive(Clone)]
@@ -76,7 +73,7 @@ impl SwitchableWriter {
// Get buffer size before flushing for debug logging // Get buffer size before flushing for debug logging
let buffer_size = self.buffered_writer.buffer_size(); let buffer_size = self.buffered_writer.buffer_size();
// Flush any buffered content // Flush any buffered content to stdout only
self.buffered_writer.flush_to(io::stdout())?; self.buffered_writer.flush_to(io::stdout())?;
// Switch to direct mode (and drop the lock) // Switch to direct mode (and drop the lock)
@@ -130,23 +127,3 @@ impl<'a> MakeWriter<'a> for SwitchableMakeWriter {
self.writer.clone() self.writer.clone()
} }
} }
/// Sets up a switchable tracing subscriber that can transition from buffered to direct output.
///
/// Returns the switchable writer that can be used to control the behavior.
pub fn setup_switchable_subscriber() -> SwitchableWriter {
let switchable_writer = SwitchableWriter::default();
let make_writer = SwitchableMakeWriter::new(switchable_writer.clone());
let _subscriber = tracing_subscriber::fmt()
.with_ansi(cfg!(not(target_os = "emscripten")))
.with_max_level(Level::DEBUG)
.event_format(CustomFormatter)
.with_writer(make_writer)
.finish()
.with(ErrorLayer::default());
tracing::subscriber::set_global_default(_subscriber).expect("Could not set global default switchable subscriber");
switchable_writer
}

View File

@@ -27,7 +27,7 @@ fn calculate_fruit_sprite_position(index: u32) -> Vec2 {
let sprite_spacing = CELL_SIZE + CELL_SIZE / 2; // 1.5 cells between sprites let sprite_spacing = CELL_SIZE + CELL_SIZE / 2; // 1.5 cells between sprites
let x = start_x - ((index as f32) * (sprite_spacing as f32 * 1.5)).round() as u32; let x = start_x - ((index as f32) * (sprite_spacing as f32 * 1.5)).round() as u32;
let y = start_y - CELL_SIZE / 2; let y = start_y - (1 + CELL_SIZE / 2);
Vec2::new((x - CELL_SIZE) as f32, (y + CELL_SIZE) as f32) Vec2::new((x - CELL_SIZE) as f32, (y + CELL_SIZE) as f32)
} }

View File

@@ -3,12 +3,14 @@ use bevy_ecs::{
observer::Trigger, observer::Trigger,
system::{Commands, NonSendMut, Res}, system::{Commands, NonSendMut, Res},
}; };
use rand::Rng;
use strum_macros::IntoStaticStr; use strum_macros::IntoStaticStr;
use tracing::debug; use tracing::debug;
use crate::{ use crate::{
constants, constants,
map::builder::Map, map::builder::Map,
platform::rng,
systems::{common::bundles::ItemBundle, Collider, Position, Renderable, TimeToLive}, systems::{common::bundles::ItemBundle, Collider, Position, Renderable, TimeToLive},
texture::{ texture::{
sprite::SpriteAtlas, sprite::SpriteAtlas,
@@ -112,7 +114,9 @@ pub fn spawn_fruit_observer(
item_collider: ItemCollider, item_collider: ItemCollider,
}; };
commands.spawn(bundle) let lifetime_ticks = (rng().random_range(9f32..10f32) * 60f32).round() as u32;
commands.spawn((bundle, TimeToLive::new(lifetime_ticks)))
} }
SpawnTrigger::Bonus { position, value, ttl } => { SpawnTrigger::Bonus { position, value, ttl } => {
let sprite = &atlas let sprite = &atlas