Compare commits

...

7 Commits

16 changed files with 319 additions and 254 deletions

2
Cargo.lock generated
View File

@@ -174,7 +174,7 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
[[package]]
name = "pacman"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"anyhow",
"glam",

View File

@@ -1,6 +1,6 @@
[package]
name = "pacman"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -19,6 +19,12 @@ thiserror = "1.0"
anyhow = "1.0"
glam = "0.30.4"
[profile.release]
lto = true
panic = "abort"
panic-strategy = "abort"
opt-level = "z"
[target.'cfg(target_os = "windows")'.dependencies.winapi]
version = "0.3"
features = ["consoleapi", "fileapi", "handleapi", "processenv", "winbase", "wincon", "winnt", "winuser", "windef", "minwindef"]

View File

@@ -1,136 +0,0 @@
//! This module provides a simple animation and atlas system for textures.
use sdl2::{
rect::Rect,
render::{Canvas, Texture},
video::Window,
};
use crate::direction::Direction;
/// Trait for drawable atlas-based textures
pub trait FrameDrawn {
fn render(&self, canvas: &mut Canvas<Window>, position: (i32, i32), direction: Direction, frame: Option<u32>);
}
/// A texture atlas abstraction for static (non-animated) rendering.
pub struct AtlasTexture<'a> {
pub raw_texture: Texture<'a>,
pub offset: (i32, i32),
pub frame_count: u32,
pub frame_width: u32,
pub frame_height: u32,
}
impl<'a> AtlasTexture<'a> {
pub fn new(texture: Texture<'a>, frame_count: u32, frame_width: u32, frame_height: u32, offset: Option<(i32, i32)>) -> Self {
AtlasTexture {
raw_texture: texture,
frame_count,
frame_width,
frame_height,
offset: offset.unwrap_or((0, 0)),
}
}
pub fn get_frame_rect(&self, frame: u32) -> Option<Rect> {
if frame >= self.frame_count {
return None;
}
Some(Rect::new(
frame as i32 * self.frame_width as i32,
0,
self.frame_width,
self.frame_height,
))
}
pub fn set_color_modulation(&mut self, r: u8, g: u8, b: u8) {
self.raw_texture.set_color_mod(r, g, b);
}
}
impl<'a> FrameDrawn for AtlasTexture<'a> {
fn render(&self, canvas: &mut Canvas<Window>, position: (i32, i32), direction: Direction, frame: Option<u32>) {
let texture_source_frame_rect = self.get_frame_rect(frame.unwrap_or(0));
let canvas_destination_rect = Rect::new(
position.0 + self.offset.0,
position.1 + self.offset.1,
self.frame_width,
self.frame_height,
);
canvas
.copy_ex(
&self.raw_texture,
texture_source_frame_rect,
Some(canvas_destination_rect),
direction.angle(),
None,
false,
false,
)
.expect("Could not render texture on canvas");
}
}
/// An animated texture using a texture atlas.
pub struct AnimatedAtlasTexture<'a> {
pub atlas: AtlasTexture<'a>,
pub ticks_per_frame: u32,
pub ticker: u32,
pub reversed: bool,
pub paused: bool,
}
impl<'a> AnimatedAtlasTexture<'a> {
pub fn new(
texture: Texture<'a>,
ticks_per_frame: u32,
frame_count: u32,
width: u32,
height: u32,
offset: Option<(i32, i32)>,
) -> Self {
AnimatedAtlasTexture {
atlas: AtlasTexture::new(texture, frame_count, width, height, offset),
ticks_per_frame,
ticker: 0,
reversed: false,
paused: false,
}
}
fn current_frame(&self) -> u32 {
self.ticker / self.ticks_per_frame
}
/// Advances the animation by one tick, unless paused.
pub fn tick(&mut self) {
if self.paused {
return;
}
if self.reversed {
if self.ticker > 0 {
self.ticker -= 1;
}
if self.ticker == 0 {
self.reversed = !self.reversed;
}
} else {
self.ticker += 1;
if self.ticker + 1 == self.ticks_per_frame * self.atlas.frame_count {
self.reversed = !self.reversed;
}
}
}
pub fn set_color_modulation(&mut self, r: u8, g: u8, b: u8) {
self.atlas.set_color_modulation(r, g, b);
}
}
impl<'a> FrameDrawn for AnimatedAtlasTexture<'a> {
fn render(&self, canvas: &mut Canvas<Window>, position: (i32, i32), direction: Direction, frame: Option<u32>) {
let frame = frame.unwrap_or_else(|| self.current_frame());
self.atlas.render(canvas, position, direction, Some(frame));
}
}

View File

@@ -1,7 +1,7 @@
//! Debug rendering utilities for Pac-Man.
use crate::{
constants::{MapTile, BOARD_HEIGHT, BOARD_WIDTH},
ghosts::blinky::Blinky,
entity::blinky::Blinky,
map::Map,
};
use glam::{IVec2, UVec2};

View File

@@ -4,32 +4,32 @@ use std::rc::Rc;
use sdl2::render::{Canvas, Texture};
use sdl2::video::Window;
use crate::direction::Direction;
use crate::entity::direction::Direction;
use crate::entity::ghost::{Ghost, GhostMode, GhostType};
use crate::entity::pacman::Pacman;
use crate::entity::{Entity, Moving, Renderable, StaticEntity};
use crate::ghost::{Ghost, GhostMode, GhostType};
use crate::map::Map;
use crate::pacman::Pacman;
use glam::{IVec2, UVec2};
pub struct Blinky<'a> {
ghost: Ghost<'a>,
pub struct Blinky {
ghost: Ghost,
}
impl<'a> Blinky<'a> {
impl Blinky {
pub fn new(
starting_position: UVec2,
body_texture: Texture<'a>,
eyes_texture: Texture<'a>,
body_texture: Texture<'_>,
eyes_texture: Texture<'_>,
map: Rc<RefCell<Map>>,
pacman: Rc<RefCell<Pacman<'a>>>,
) -> Blinky<'a> {
pacman: Rc<RefCell<Pacman>>,
) -> Blinky {
Blinky {
ghost: Ghost::new(GhostType::Blinky, starting_position, body_texture, eyes_texture, map, pacman),
}
}
/// Gets Blinky's chase target - directly targets Pac-Man's current position
fn get_chase_target(&self) -> IVec2 {
pub fn get_chase_target(&self) -> IVec2 {
let pacman = self.ghost.pacman.borrow();
let cell = pacman.base().cell_position;
IVec2::new(cell.x as i32, cell.y as i32)
@@ -44,19 +44,19 @@ impl<'a> Blinky<'a> {
}
}
impl<'a> Entity for Blinky<'a> {
impl Entity for Blinky {
fn base(&self) -> &StaticEntity {
self.ghost.base.base()
}
}
impl<'a> Renderable for Blinky<'a> {
impl Renderable for Blinky {
fn render(&self, canvas: &mut Canvas<Window>) {
self.ghost.render(canvas);
}
}
impl<'a> Moving for Blinky<'a> {
impl Moving for Blinky {
fn move_forward(&mut self) {
self.ghost.move_forward();
}
@@ -81,15 +81,15 @@ impl<'a> Moving for Blinky<'a> {
}
// Allow direct access to ghost fields
impl<'a> std::ops::Deref for Blinky<'a> {
type Target = Ghost<'a>;
impl std::ops::Deref for Blinky {
type Target = Ghost;
fn deref(&self) -> &Self::Target {
&self.ghost
}
}
impl<'a> std::ops::DerefMut for Blinky<'a> {
impl std::ops::DerefMut for Blinky {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.ghost
}

View File

@@ -1,5 +1,6 @@
//! This module defines the `Direction` enum, which is used to represent the
//! direction of an entity.
use glam::IVec2;
use sdl2::keyboard::Keycode;
/// An enum representing the direction of an entity.
@@ -23,12 +24,12 @@ impl Direction {
}
/// Returns the offset of the direction as a tuple of (x, y).
pub fn offset(&self) -> (i32, i32) {
pub fn offset(&self) -> IVec2 {
match self {
Direction::Right => (1, 0),
Direction::Down => (0, 1),
Direction::Left => (-1, 0),
Direction::Up => (0, -1),
Direction::Right => IVec2::new(1, 0),
Direction::Down => IVec2::new(0, 1),
Direction::Left => IVec2::new(-1, 0),
Direction::Up => IVec2::new(0, -1),
}
}

View File

@@ -1,9 +1,10 @@
//! Edible entity for Pac-Man: pellets, power pellets, and fruits.
use crate::animation::{AtlasTexture, FrameDrawn};
use crate::constants::{FruitType, MapTile, BOARD_HEIGHT, BOARD_WIDTH};
use crate::direction::Direction;
use crate::entity::direction::Direction;
use crate::entity::{Entity, Renderable, StaticEntity};
use crate::map::Map;
use crate::texture::atlas::AtlasTexture;
use crate::texture::FrameDrawn;
use glam::{IVec2, UVec2};
use sdl2::{render::Canvas, video::Window};
use std::cell::RefCell;
@@ -16,14 +17,14 @@ pub enum EdibleKind {
Fruit(FruitType),
}
pub struct Edible<'a> {
pub struct Edible {
pub base: StaticEntity,
pub kind: EdibleKind,
pub sprite: Rc<AtlasTexture<'a>>,
pub sprite: Rc<AtlasTexture>,
}
impl<'a> Edible<'a> {
pub fn new(kind: EdibleKind, cell_position: UVec2, sprite: Rc<AtlasTexture<'a>>) -> Self {
impl Edible {
pub fn new(kind: EdibleKind, cell_position: UVec2, sprite: Rc<AtlasTexture>) -> Self {
let pixel_position = Map::cell_to_pixel(cell_position);
Edible {
base: StaticEntity::new(pixel_position, cell_position),
@@ -38,26 +39,26 @@ impl<'a> Edible<'a> {
}
}
impl<'a> Entity for Edible<'a> {
impl Entity for Edible {
fn base(&self) -> &StaticEntity {
&self.base
}
}
impl<'a> Renderable for Edible<'a> {
impl Renderable for Edible {
fn render(&self, canvas: &mut Canvas<Window>) {
let pos = self.base.pixel_position;
self.sprite.render(canvas, (pos.x, pos.y), Direction::Right, Some(0));
self.sprite.render(canvas, pos, Direction::Right, Some(0));
}
}
/// Reconstruct all edibles from the original map layout
pub fn reconstruct_edibles<'a>(
pub fn reconstruct_edibles(
map: Rc<RefCell<Map>>,
pellet_sprite: Rc<AtlasTexture<'a>>,
power_pellet_sprite: Rc<AtlasTexture<'a>>,
_fruit_sprite: Rc<AtlasTexture<'a>>,
) -> Vec<Edible<'a>> {
pellet_sprite: Rc<AtlasTexture>,
power_pellet_sprite: Rc<AtlasTexture>,
_fruit_sprite: Rc<AtlasTexture>,
) -> Vec<Edible> {
let mut edibles = Vec::new();
for x in 0..BOARD_WIDTH {
for y in 0..BOARD_HEIGHT {

View File

@@ -2,13 +2,15 @@ use rand::rngs::SmallRng;
use rand::Rng;
use rand::SeedableRng;
use crate::animation::{AnimatedAtlasTexture, FrameDrawn};
use crate::constants::{MapTile, BOARD_WIDTH};
use crate::direction::Direction;
use crate::entity::direction::Direction;
use crate::entity::pacman::Pacman;
use crate::entity::{Entity, MovableEntity, Moving, Renderable};
use crate::map::Map;
use crate::modulation::{SimpleTickModulator, TickModulator};
use crate::pacman::Pacman;
use crate::texture::animated::AnimatedAtlasTexture;
use crate::texture::atlas::{texture_to_static, AtlasTexture};
use crate::texture::FrameDrawn;
use glam::{IVec2, UVec2};
use sdl2::pixels::Color;
use sdl2::render::Texture;
@@ -52,7 +54,7 @@ impl GhostType {
}
/// Base ghost struct that contains common functionality
pub struct Ghost<'a> {
pub struct Ghost {
/// Shared movement and position fields.
pub base: MovableEntity,
/// The current mode of the ghost
@@ -60,23 +62,30 @@ pub struct Ghost<'a> {
/// The type/personality of this ghost
pub ghost_type: GhostType,
/// Reference to Pac-Man for targeting
pub pacman: Rc<RefCell<Pacman<'a>>>,
pub body_sprite: AnimatedAtlasTexture<'a>,
pub eyes_sprite: AnimatedAtlasTexture<'a>,
pub pacman: Rc<RefCell<Pacman>>,
pub body_sprite: AnimatedAtlasTexture,
pub eyes_sprite: AnimatedAtlasTexture,
}
impl Ghost<'_> {
impl Ghost {
/// Creates a new ghost instance
pub fn new<'a>(
pub fn new(
ghost_type: GhostType,
starting_position: UVec2,
body_texture: Texture<'a>,
eyes_texture: Texture<'a>,
body_texture: Texture<'_>,
eyes_texture: Texture<'_>,
map: Rc<RefCell<Map>>,
pacman: Rc<RefCell<Pacman<'a>>>,
) -> Ghost<'a> {
pacman: Rc<RefCell<Pacman>>,
) -> Ghost {
let color = ghost_type.color();
let mut body_sprite = AnimatedAtlasTexture::new(body_texture, 8, 2, 32, 32, Some((-4, -4)));
let mut body_sprite = AnimatedAtlasTexture::new(
unsafe { texture_to_static(body_texture) },
8,
2,
32,
32,
Some(IVec2::new(-4, -4)),
);
body_sprite.set_color_modulation(color.r, color.g, color.b);
let pixel_position = Map::cell_to_pixel(starting_position);
Ghost {
@@ -92,7 +101,14 @@ impl Ghost<'_> {
ghost_type,
pacman,
body_sprite,
eyes_sprite: AnimatedAtlasTexture::new(eyes_texture, 1, 4, 32, 32, Some((-4, -4))),
eyes_sprite: AnimatedAtlasTexture::new(
unsafe { texture_to_static(eyes_texture) },
1,
4,
32,
32,
Some((-4, -4).into()),
),
}
}
@@ -180,8 +196,8 @@ impl Ghost<'_> {
}
}
for dir in &[Direction::Up, Direction::Down, Direction::Left, Direction::Right] {
let (dx, dy) = dir.offset();
let next_p = IVec2::new(p.x as i32 + dx, p.y as i32 + dy);
let offset = dir.offset();
let next_p = IVec2::new(p.x as i32 + offset.x, p.y as i32 + offset.y);
if let Some(tile) = map.get_tile(next_p) {
if tile == MapTile::Wall {
continue;
@@ -266,7 +282,7 @@ impl Ghost<'_> {
}
}
impl<'a> Moving for Ghost<'a> {
impl Moving for Ghost {
fn move_forward(&mut self) {
self.base.move_forward();
}
@@ -290,10 +306,10 @@ impl<'a> Moving for Ghost<'a> {
}
}
impl<'a> Renderable for Ghost<'a> {
impl Renderable for Ghost {
fn render(&self, canvas: &mut sdl2::render::Canvas<sdl2::video::Window>) {
let pos = self.base.base.pixel_position;
self.body_sprite.render(canvas, (pos.x, pos.y), Direction::Right, None);
self.body_sprite.render(canvas, pos, Direction::Right, None);
// Inline the eye_frame logic here
let eye_frame = if self.mode == GhostMode::Frightened {
4 // Frightened frame
@@ -305,7 +321,6 @@ impl<'a> Renderable for Ghost<'a> {
Direction::Down => 3,
}
};
self.eyes_sprite
.render(canvas, (pos.x, pos.y), Direction::Right, Some(eye_frame));
self.eyes_sprite.render(canvas, pos, Direction::Right, Some(eye_frame));
}
}

View File

@@ -1,6 +1,12 @@
pub mod blinky;
pub mod direction;
pub mod edible;
pub mod ghost;
pub mod pacman;
use crate::{
constants::{MapTile, BOARD_OFFSET, BOARD_WIDTH, CELL_SIZE},
direction::Direction,
entity::direction::Direction,
map::Map,
modulation::SimpleTickModulator,
};
@@ -108,7 +114,7 @@ impl Moving for MovableEntity {
);
}
fn next_cell(&self, direction: Option<Direction>) -> IVec2 {
let (x, y) = direction.unwrap_or(self.direction).offset();
let IVec2 { x, y } = direction.unwrap_or(self.direction).offset();
IVec2::new(self.base.cell_position.x as i32 + x, self.base.cell_position.y as i32 + y)
}
fn is_wall_ahead(&self, direction: Option<Direction>) -> bool {

View File

@@ -8,33 +8,33 @@ use sdl2::{
};
use crate::{
animation::{AnimatedAtlasTexture, FrameDrawn},
direction::Direction,
entity::{Entity, MovableEntity, Moving, Renderable, StaticEntity},
entity::{direction::Direction, Entity, MovableEntity, Moving, Renderable, StaticEntity},
map::Map,
modulation::{SimpleTickModulator, TickModulator},
texture::animated::AnimatedAtlasTexture,
texture::FrameDrawn,
};
use glam::{IVec2, UVec2};
/// The Pac-Man entity.
pub struct Pacman<'a> {
pub struct Pacman {
/// Shared movement and position fields.
pub base: MovableEntity,
/// The next direction of Pac-Man, which will be applied when Pac-Man is next aligned with the grid.
pub next_direction: Option<Direction>,
/// Whether Pac-Man is currently stopped.
pub stopped: bool,
pub sprite: AnimatedAtlasTexture<'a>,
pub sprite: AnimatedAtlasTexture,
}
impl<'a> Entity for Pacman<'a> {
impl Entity for Pacman {
fn base(&self) -> &StaticEntity {
&self.base.base
}
}
impl<'a> Moving for Pacman<'a> {
impl Moving for Pacman {
fn move_forward(&mut self) {
self.base.move_forward();
}
@@ -58,9 +58,9 @@ impl<'a> Moving for Pacman<'a> {
}
}
impl Pacman<'_> {
impl Pacman {
/// Creates a new `Pacman` instance.
pub fn new<'a>(starting_position: UVec2, atlas: Texture<'a>, map: Rc<RefCell<Map>>) -> Pacman<'a> {
pub fn new(starting_position: UVec2, atlas: Texture<'_>, map: Rc<RefCell<Map>>) -> Pacman {
let pixel_position = Map::cell_to_pixel(starting_position);
Pacman {
base: MovableEntity::new(
@@ -73,7 +73,14 @@ impl Pacman<'_> {
),
next_direction: None,
stopped: false,
sprite: AnimatedAtlasTexture::new(atlas, 2, 3, 32, 32, Some((-4, -4))),
sprite: AnimatedAtlasTexture::new(
unsafe { crate::texture::atlas::texture_to_static(atlas) },
2,
3,
32,
32,
Some(IVec2::new(-4, -4)),
),
}
}
@@ -119,14 +126,14 @@ impl Pacman<'_> {
}
}
impl Renderable for Pacman<'_> {
impl Renderable for Pacman {
fn render(&self, canvas: &mut Canvas<Window>) {
let pos = self.base.base.pixel_position;
let dir = self.base.direction;
if self.stopped {
self.sprite.render(canvas, (pos.x, pos.y), dir, Some(2));
self.sprite.render(canvas, pos, dir, Some(2));
} else {
self.sprite.render(canvas, (pos.x, pos.y), dir, None);
self.sprite.render(canvas, pos, dir, None);
}
}
}

View File

@@ -3,7 +3,7 @@ use std::cell::RefCell;
use std::ops::Not;
use std::rc::Rc;
use glam::UVec2;
use glam::{IVec2, UVec2};
use rand::rngs::SmallRng;
use rand::seq::IteratorRandom;
use rand::SeedableRng;
@@ -15,38 +15,38 @@ use sdl2::ttf::Font;
use sdl2::video::WindowContext;
use sdl2::{pixels::Color, render::Canvas, video::Window};
use crate::animation::AtlasTexture;
use crate::asset::{get_asset_bytes, Asset};
use crate::audio::Audio;
use crate::constants::RAW_BOARD;
use crate::debug::{DebugMode, DebugRenderer};
use crate::direction::Direction;
use crate::edible::{reconstruct_edibles, Edible, EdibleKind};
use crate::entity::blinky::Blinky;
use crate::entity::direction::Direction;
use crate::entity::edible::{reconstruct_edibles, Edible, EdibleKind};
use crate::entity::pacman::Pacman;
use crate::entity::Renderable;
use crate::ghosts::blinky::Blinky;
use crate::map::Map;
use crate::pacman::Pacman;
use crate::texture::atlas::{texture_to_static, AtlasTexture};
/// The main game state.
///
/// This struct contains all the information necessary to run the game, including
/// the canvas, textures, fonts, game objects, and the current score.
pub struct Game<'a> {
canvas: &'a mut Canvas<Window>,
map_texture: Texture<'a>,
pellet_texture: Rc<AtlasTexture<'a>>,
power_pellet_texture: Rc<AtlasTexture<'a>>,
font: Font<'a, 'static>,
pacman: Rc<RefCell<Pacman<'a>>>,
pub struct Game {
canvas: &'static mut Canvas<Window>,
map_texture: Texture<'static>,
pellet_texture: Rc<AtlasTexture>,
power_pellet_texture: Rc<AtlasTexture>,
font: Font<'static, 'static>,
pacman: Rc<RefCell<Pacman>>,
map: Rc<RefCell<Map>>,
debug_mode: DebugMode,
score: u32,
pub audio: Audio,
blinky: Blinky<'a>,
edibles: Vec<Edible<'a>>,
blinky: Blinky,
edibles: Vec<Edible>,
}
impl<'a> Game<'a> {
impl Game {
/// Creates a new `Game` instance.
///
/// # Arguments
@@ -56,11 +56,11 @@ impl<'a> Game<'a> {
/// * `ttf_context` - The SDL TTF context.
/// * `_audio_subsystem` - The SDL audio subsystem (currently unused).
pub fn new(
canvas: &'a mut Canvas<Window>,
texture_creator: &'a TextureCreator<WindowContext>,
ttf_context: &'a sdl2::ttf::Sdl2TtfContext,
_audio_subsystem: &'a sdl2::AudioSubsystem,
) -> Game<'a> {
canvas: &'static mut Canvas<Window>,
texture_creator: &TextureCreator<WindowContext>,
ttf_context: &sdl2::ttf::Sdl2TtfContext,
_audio_subsystem: &sdl2::AudioSubsystem,
) -> Game {
let map = Rc::new(RefCell::new(Map::new(RAW_BOARD)));
// Load Pacman texture from asset API
@@ -91,20 +91,28 @@ impl<'a> Game<'a> {
// Load pellet texture from asset API
let pellet_bytes = get_asset_bytes(Asset::Pellet).expect("Failed to load asset");
let power_pellet_bytes = get_asset_bytes(Asset::Energizer).expect("Failed to load asset");
let pellet_texture = Rc::new(AtlasTexture::new(
texture_creator
.load_texture_bytes(&pellet_bytes)
.expect("Could not load pellet texture from asset API"),
unsafe {
texture_to_static(
texture_creator
.load_texture_bytes(&pellet_bytes)
.expect("Could not load pellet texture from asset API"),
)
},
1,
24,
24,
None,
));
let power_pellet_bytes = get_asset_bytes(Asset::Energizer).expect("Failed to load asset");
let power_pellet_texture = Rc::new(AtlasTexture::new(
texture_creator
.load_texture_bytes(&power_pellet_bytes)
.expect("Could not load power pellet texture from asset API"),
unsafe {
texture_to_static(
texture_creator
.load_texture_bytes(&power_pellet_bytes)
.expect("Could not load power pellet texture from asset API"),
)
},
1,
24,
24,
@@ -117,6 +125,7 @@ impl<'a> Game<'a> {
.load_texture_bytes(&map_bytes)
.expect("Could not load map texture from asset API");
map_texture.set_color_mod(0, 0, 255);
let map_texture = unsafe { texture_to_static(map_texture) };
let edibles = reconstruct_edibles(
Rc::clone(&map),
@@ -130,7 +139,9 @@ impl<'a> Game<'a> {
let font_bytes = get_asset_bytes(Asset::FontKonami).expect("Failed to load asset").into_owned();
let font_bytes_static: &'static [u8] = Box::leak(font_bytes.into_boxed_slice());
let font_rwops = RWops::from_bytes(font_bytes_static).expect("Failed to create RWops for font");
ttf_context
// Leak the ttf_context to get a 'static lifetime
let ttf_context_static: &'static sdl2::ttf::Sdl2TtfContext = unsafe { std::mem::transmute(ttf_context) };
ttf_context_static
.load_font_from_rwops(font_rwops, 24)
.expect("Could not load font from asset API")
};
@@ -232,7 +243,7 @@ impl<'a> Game<'a> {
self.blinky.base.base.cell_position = *pos;
self.blinky.base.in_tunnel = false;
self.blinky.base.direction = Direction::Left;
self.blinky.mode = crate::ghost::GhostMode::Chase;
self.blinky.mode = crate::entity::ghost::GhostMode::Chase;
}
}
@@ -340,18 +351,18 @@ impl<'a> Game<'a> {
// Render the score and high score
self.render_text(
&format!("{lives}UP HIGH SCORE "),
(24 * lives_offset + x_offset, y_offset),
IVec2::new(24 * lives_offset + x_offset, y_offset),
Color::WHITE,
);
self.render_text(
&score_text,
(24 * score_offset + x_offset, 24 + y_offset + gap_offset),
IVec2::new(24 * score_offset + x_offset, 24 + y_offset + gap_offset),
Color::WHITE,
);
}
/// Renders text to the screen at the given position.
fn render_text(&mut self, text: &str, position: (i32, i32), color: Color) {
fn render_text(&mut self, text: &str, position: IVec2, color: Color) {
let surface = self.font.render(text).blended(color).expect("Could not render text surface");
let texture_creator = self.canvas.texture_creator();
@@ -360,7 +371,7 @@ impl<'a> Game<'a> {
.expect("Could not create texture from surface");
let query = texture.query();
let dst_rect = sdl2::rect::Rect::new(position.0, position.1, query.width, query.height);
let dst_rect = sdl2::rect::Rect::new(position.x, position.y, query.width, query.height);
self.canvas
.copy(&texture, None, Some(dst_rect))

View File

@@ -1 +0,0 @@
pub mod blinky;

View File

@@ -52,23 +52,18 @@ unsafe fn attach_console() {
// Do NOT call AllocConsole here - we don't want a console when launched from Explorer
}
mod animation;
mod asset;
mod audio;
mod constants;
mod debug;
mod direction;
mod edible;
#[cfg(target_os = "emscripten")]
mod emscripten;
mod entity;
mod game;
mod ghost;
mod ghosts;
mod helper;
mod map;
mod modulation;
mod pacman;
mod texture;
#[cfg(not(target_os = "emscripten"))]
fn sleep(value: Duration) {
@@ -128,7 +123,8 @@ pub fn main() {
.expect("Could not set logical size");
let texture_creator = canvas.texture_creator();
let mut game = Game::new(&mut canvas, &texture_creator, &ttf_context, &audio_subsystem);
let canvas_static: &'static mut sdl2::render::Canvas<sdl2::video::Window> = Box::leak(Box::new(canvas));
let mut game = Game::new(canvas_static, &texture_creator, &ttf_context, &audio_subsystem);
game.audio.set_mute(cfg!(debug_assertions));
let mut event_pump = sdl_context.event_pump().expect("Could not get SDL EventPump");

73
src/texture/animated.rs Normal file
View File

@@ -0,0 +1,73 @@
//! This module provides a simple animation and atlas system for textures.
use glam::IVec2;
use sdl2::{
render::{Canvas, Texture},
video::Window,
};
use crate::entity::direction::Direction;
use crate::texture::atlas::AtlasTexture;
use crate::texture::FrameDrawn;
/// An animated texture using a texture atlas.
pub struct AnimatedAtlasTexture {
pub atlas: AtlasTexture,
pub ticks_per_frame: u32,
pub ticker: u32,
pub reversed: bool,
pub paused: bool,
}
impl AnimatedAtlasTexture {
pub fn new(
texture: Texture<'static>,
ticks_per_frame: u32,
frame_count: u32,
width: u32,
height: u32,
offset: Option<IVec2>,
) -> Self {
AnimatedAtlasTexture {
atlas: AtlasTexture::new(texture, frame_count, width, height, offset),
ticks_per_frame,
ticker: 0,
reversed: false,
paused: false,
}
}
fn current_frame(&self) -> u32 {
self.ticker / self.ticks_per_frame
}
/// Advances the animation by one tick, unless paused.
pub fn tick(&mut self) {
if self.paused {
return;
}
if self.reversed {
if self.ticker > 0 {
self.ticker -= 1;
}
if self.ticker == 0 {
self.reversed = !self.reversed;
}
} else {
self.ticker += 1;
if self.ticker + 1 == self.ticks_per_frame * self.atlas.frame_count {
self.reversed = !self.reversed;
}
}
}
pub fn set_color_modulation(&mut self, r: u8, g: u8, b: u8) {
self.atlas.set_color_modulation(r, g, b);
}
}
impl FrameDrawn for AnimatedAtlasTexture {
fn render(&self, canvas: &mut Canvas<Window>, position: IVec2, direction: Direction, frame: Option<u32>) {
let frame = frame.unwrap_or_else(|| self.current_frame());
self.atlas.render(canvas, position, direction, Some(frame));
}
}

74
src/texture/atlas.rs Normal file
View File

@@ -0,0 +1,74 @@
use glam::IVec2;
use sdl2::{
rect::Rect,
render::{Canvas, Texture},
video::Window,
};
use crate::{entity::direction::Direction, texture::FrameDrawn};
/// Unsafely converts a Texture with any lifetime to a 'static lifetime.
/// Only use this if you guarantee the renderer/context will never be dropped!
pub unsafe fn texture_to_static<'a>(texture: Texture<'a>) -> Texture<'static> {
std::mem::transmute::<Texture<'a>, Texture<'static>>(texture)
}
/// A texture atlas abstraction for static (non-animated) rendering.
pub struct AtlasTexture {
pub raw_texture: Texture<'static>,
pub offset: IVec2,
pub frame_count: u32,
pub frame_width: u32,
pub frame_height: u32,
}
impl AtlasTexture {
pub fn new(texture: Texture<'static>, frame_count: u32, frame_width: u32, frame_height: u32, offset: Option<IVec2>) -> Self {
AtlasTexture {
raw_texture: texture,
frame_count,
frame_width,
frame_height,
offset: offset.unwrap_or(IVec2::new(0, 0)).into(),
}
}
pub fn get_frame_rect(&self, frame: u32) -> Option<Rect> {
if frame >= self.frame_count {
return None;
}
Some(Rect::new(
frame as i32 * self.frame_width as i32,
0,
self.frame_width,
self.frame_height,
))
}
pub fn set_color_modulation(&mut self, r: u8, g: u8, b: u8) {
self.raw_texture.set_color_mod(r, g, b);
}
}
impl FrameDrawn for AtlasTexture {
fn render(&self, canvas: &mut Canvas<Window>, position: IVec2, direction: Direction, frame: Option<u32>) {
let texture_source_frame_rect = self.get_frame_rect(frame.unwrap_or(0));
let canvas_destination_rect = Rect::new(
position.x + self.offset.x,
position.y + self.offset.y,
self.frame_width,
self.frame_height,
);
canvas
.copy_ex(
&self.raw_texture,
texture_source_frame_rect,
Some(canvas_destination_rect),
direction.angle(),
None,
false,
false,
)
.expect("Could not render texture on canvas");
}
}

12
src/texture/mod.rs Normal file
View File

@@ -0,0 +1,12 @@
use glam::IVec2;
use sdl2::{render::Canvas, video::Window};
use crate::entity::direction::Direction;
/// Trait for drawable atlas-based textures
pub trait FrameDrawn {
fn render(&self, canvas: &mut Canvas<Window>, position: IVec2, direction: Direction, frame: Option<u32>);
}
pub mod animated;
pub mod atlas;