mirror of
https://github.com/Xevion/Pac-Man.git
synced 2025-12-06 07:15:41 -06:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c5213320ac | |||
| e0f8443e75 | |||
| 6702b3723a | |||
| f6e7228f75 | |||
| 14cebe4462 | |||
| c39fcaa7d7 | |||
| 1d9499c4f8 | |||
| 61050a5585 | |||
| 85420711df | |||
| 2efa7a4df5 |
2
.github/workflows/build.yaml
vendored
2
.github/workflows/build.yaml
vendored
@@ -120,7 +120,7 @@ jobs:
|
||||
echo "Build attempt $attempt of $MAX_RETRIES"
|
||||
|
||||
# Capture output and check for specific error while preserving real-time output
|
||||
if bun run web.build.ts 2>&1 | tee /tmp/build_output.log; then
|
||||
if bun run -i web.build.ts 2>&1 | tee /tmp/build_output.log; then
|
||||
echo "Build successful on attempt $attempt"
|
||||
break
|
||||
else
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -4,3 +4,4 @@ emsdk/
|
||||
.idea
|
||||
rust-sdl2-emscripten/
|
||||
assets/site/build.css
|
||||
tailwindcss-*
|
||||
|
||||
47
README.md
47
README.md
@@ -14,8 +14,6 @@
|
||||
[demo]: https://xevion.github.io/Pac-Man/
|
||||
[commits]: https://github.com/Xevion/Pac-Man/commits/master
|
||||
|
||||
## Description
|
||||
|
||||
A faithful recreation of the classic Pac-Man arcade game written in Rust. This project aims to replicate the original game's mechanics, graphics, sound, and behavior as accurately as possible while providing modern development features like cross-platform compatibility and WebAssembly support.
|
||||
|
||||
The game includes all the original features you'd expect from Pac-Man:
|
||||
@@ -27,38 +25,63 @@ The game includes all the original features you'd expect from Pac-Man:
|
||||
- [ ] Progressive difficulty with faster ghosts and shorter power pellet duration
|
||||
- [x] Authentic sound effects and sprites
|
||||
|
||||
Built with SDL2 for cross-platform graphics and audio, this implementation can run on Windows, Linux, macOS, and in web browsers via WebAssembly.
|
||||
This cross-platform implementation is built with SDL2 for graphics, audio, and input handling. It can run on Windows, Linux, macOS, and in web browsers via WebAssembly.
|
||||
|
||||
## Feature Targets
|
||||
## Why?
|
||||
|
||||
- Near-perfect replication of logic, scoring, graphics, sound, and behaviors.
|
||||
- Written in Rust, buildable on Windows, Linux, Mac and WebAssembly.
|
||||
Just because. And because I wanted to learn more about Rust, inter-operability with C, and compiling to WebAssembly.
|
||||
|
||||
I was inspired by a certain code review video on YouTube; [SOME UNIQUE C++ CODE // Pacman Clone Code Review](https://www.youtube.com/watch?v=OKs_JewEeOo) by The Cherno.
|
||||
|
||||
For some reason, I was inspired to try and replicate it in Rust, and it was uniquely challenging.
|
||||
|
||||
I wanted to hit a log of goals and features, making it a 'perfect' project that I could be proud of.
|
||||
|
||||
- Near-perfect replication of logic, scoring, graphics, sound, and behaviors. No hacks, workarounds, or poor designs.
|
||||
- Written in Rust, buildable on Windows, Linux, Mac and WebAssembly. Statically linked, no runtime dependencies.
|
||||
- Performant, low memory, CPU and GPU usage.
|
||||
- Online demo, playable in a browser.
|
||||
- Automatic build system, with releases for Windows, Linux, and Mac & Web-Assembly.
|
||||
- Completely automatic build system with releases for all platforms.
|
||||
- Well documented, well-tested, and maintainable.
|
||||
|
||||
## Experimental Ideas
|
||||
|
||||
- Debug tooling
|
||||
- Game state visualization
|
||||
- Game speed controls + pausing
|
||||
- Log tracing
|
||||
- Performance details
|
||||
|
||||
## Experimental Ideas
|
||||
|
||||
- Customized Themes & Colors
|
||||
- Color-blind friendly
|
||||
- Perfected Ghost Algorithms
|
||||
- More than 4 ghosts
|
||||
- Custom Level Generation
|
||||
- Multi-map tunnelling
|
||||
- Online Scoreboard
|
||||
- WebAssembly build contains a special API key for communicating with server.
|
||||
- To prevent abuse, the server will only accept scores from the WebAssembly build.
|
||||
- An online axum server with a simple database and OAuth2 authentication.
|
||||
- Integrates with GitHub, Discord, and Google OAuth2 to acquire an email identifier & avatar.
|
||||
- Avatars are optional for score submission and can be disabled, instead using a blank avatar.
|
||||
- Avatars are downscaled to a low resolution pixellated image to maintain the 8-bit aesthetic.
|
||||
- A custom name is used for the score submission, which is checked for potential abusive language.
|
||||
- A max length of 14 characters, and a min length of 3 characters.
|
||||
- Names are checked for potential abusive language via an external API.
|
||||
- The client implementation should require zero configuration, environment variables, or special secrets.
|
||||
- It simply defaults to the pacman server API, or can be overriden manually.
|
||||
|
||||
## Build Notes
|
||||
|
||||
Since this project is still in progress, I'm only going to cover non-obvious build details. By reading the code, build scripts, and copying the online build workflows, you should be able to replicate the build process.
|
||||
|
||||
- Install `cargo-vcpkg` with `cargo install cargo-vcpkg`, then run `cargo vcpkg build` to build the requisite dependencies via vcpkg.
|
||||
- For the WASM build, you need to have the Emscripten SDK cloned; you can do so with `git clone https://github.com/emscripten-core/emsdk.git`
|
||||
- The first time you clone, you'll need to install the appropriate SDK version with `./emsdk install 3.1.43` and then activate it with `./emsdk activate 3.1.43`. On Windows, use `./emsdk/emsdk.ps1` instead.
|
||||
- I'm still not sure _why_ 3.1.43 is required, but it is. Perhaps in the future I will attempt to use a more modern version.
|
||||
- Occasionally, the build will fail due to dependencies failing to download. I even have a retry mechanism in the build workflow due to this.
|
||||
- You can then activate the Emscripten SDK with `source ./emsdk/emsdk_env.sh` or `./emsdk/emsdk_env.ps1` or `./emsdk/emsdk_env.bat` depending on your OS/terminal.
|
||||
- While using the `web.build.ts` is not technically required, it simplifies the build process and is very helpful.
|
||||
- It is intended to be run with `bun`, which you can acquire at [bun.sh](https://bun.sh/)
|
||||
- Tip: You can launch a fileserver with `python` or `caddy` to serve the files in the `dist` folder.
|
||||
- `python3 -m http.server 8080 -d dist`
|
||||
- `caddy file-server --root dist` (install with `[sudo apt|brew|choco] install caddy` or [a dozen other ways](https://caddyserver.com/docs/install))
|
||||
- `web.build.ts` auto installs dependencies, but you may need to pass `-i` or `--install=fallback|force` to install missing packages. My guess is that if you have some packages installed, it won't install any missing ones. If you have no packages installed, it will install all of them.
|
||||
- If you want to have TypeScript resolution for development, you can manually install the dependencies with `bun install` in the `assets/site` folder.
|
||||
|
||||
@@ -54,7 +54,8 @@
|
||||
<div class="w-full max-w-5xl">
|
||||
<canvas
|
||||
id="canvas"
|
||||
class="block mx-auto bg-black w-full max-w-[90vw] h-auto mt-5 rounded-xl shadow-[inset_0_0_0_2px_rgba(255,255,255,0.12),0_10px_30px_rgba(0,0,0,0.8)]"
|
||||
oncontextmenu="event.preventDefault()"
|
||||
class="block bg-black w-full max-w-[90vw] h-auto rounded-xl shadow-[inset_0_0_0_2px_rgba(255,255,255,0.12),0_10px_30px_rgba(0,0,0,0.8)]"
|
||||
></canvas>
|
||||
|
||||
<div
|
||||
|
||||
19
src/app.rs
19
src/app.rs
@@ -10,19 +10,7 @@ use tracing::{error, event};
|
||||
|
||||
use crate::constants::{CANVAS_SIZE, LOOP_TIME, SCALE};
|
||||
use crate::game::Game;
|
||||
|
||||
#[cfg(target_os = "emscripten")]
|
||||
use crate::emscripten;
|
||||
|
||||
#[cfg(not(target_os = "emscripten"))]
|
||||
fn sleep(value: Duration) {
|
||||
spin_sleep::sleep(value);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "emscripten")]
|
||||
fn sleep(value: Duration) {
|
||||
emscripten::emscripten::sleep(value.as_millis() as u32);
|
||||
}
|
||||
use crate::platform::get_platform;
|
||||
|
||||
pub struct App<'a> {
|
||||
game: Game,
|
||||
@@ -35,6 +23,9 @@ pub struct App<'a> {
|
||||
|
||||
impl App<'_> {
|
||||
pub fn new() -> Result<Self> {
|
||||
// Initialize platform-specific console
|
||||
get_platform().init_console().map_err(|e| anyhow!(e))?;
|
||||
|
||||
let sdl_context = sdl2::init().map_err(|e| anyhow!(e))?;
|
||||
let video_subsystem = sdl_context.video().map_err(|e| anyhow!(e))?;
|
||||
let audio_subsystem = sdl_context.audio().map_err(|e| anyhow!(e))?;
|
||||
@@ -138,7 +129,7 @@ impl App<'_> {
|
||||
if start.elapsed() < LOOP_TIME {
|
||||
let time = LOOP_TIME.saturating_sub(start.elapsed());
|
||||
if time != Duration::ZERO {
|
||||
sleep(time);
|
||||
get_platform().sleep(time);
|
||||
}
|
||||
} else {
|
||||
event!(
|
||||
|
||||
32
src/asset.rs
32
src/asset.rs
@@ -42,40 +42,12 @@ impl Asset {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "emscripten"))]
|
||||
mod imp {
|
||||
use super::*;
|
||||
macro_rules! asset_bytes_enum {
|
||||
( $asset:expr ) => {
|
||||
match $asset {
|
||||
Asset::Wav1 => Cow::Borrowed(include_bytes!("../assets/game/sound/waka/1.ogg")),
|
||||
Asset::Wav2 => Cow::Borrowed(include_bytes!("../assets/game/sound/waka/2.ogg")),
|
||||
Asset::Wav3 => Cow::Borrowed(include_bytes!("../assets/game/sound/waka/3.ogg")),
|
||||
Asset::Wav4 => Cow::Borrowed(include_bytes!("../assets/game/sound/waka/4.ogg")),
|
||||
Asset::Atlas => Cow::Borrowed(include_bytes!("../assets/game/atlas.png")),
|
||||
Asset::AtlasJson => Cow::Borrowed(include_bytes!("../assets/game/atlas.json")),
|
||||
}
|
||||
};
|
||||
}
|
||||
pub fn get_asset_bytes(asset: Asset) -> Result<Cow<'static, [u8]>, AssetError> {
|
||||
Ok(asset_bytes_enum!(asset))
|
||||
}
|
||||
}
|
||||
use crate::platform::get_platform;
|
||||
|
||||
#[cfg(target_os = "emscripten")]
|
||||
mod imp {
|
||||
use super::*;
|
||||
use sdl2::rwops::RWops;
|
||||
use std::io::Read;
|
||||
pub fn get_asset_bytes(asset: Asset) -> Result<Cow<'static, [u8]>, AssetError> {
|
||||
let path = format!("assets/game/{}", asset.path());
|
||||
let mut rwops = RWops::from_file(&path, "rb").map_err(|_| AssetError::NotFound(asset.path().to_string()))?;
|
||||
let len = rwops.len().ok_or_else(|| AssetError::NotFound(asset.path().to_string()))?;
|
||||
let mut buf = vec![0u8; len];
|
||||
rwops
|
||||
.read_exact(&mut buf)
|
||||
.map_err(|e| AssetError::Io(std::io::Error::new(std::io::ErrorKind::Other, e)))?;
|
||||
Ok(Cow::Owned(buf))
|
||||
get_platform().get_asset_bytes(asset)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
#[allow(dead_code)]
|
||||
#[cfg(target_os = "emscripten")]
|
||||
pub mod emscripten {
|
||||
use std::os::raw::c_uint;
|
||||
|
||||
extern "C" {
|
||||
pub fn emscripten_get_now() -> f64;
|
||||
pub fn emscripten_sleep(ms: c_uint);
|
||||
pub fn emscripten_get_element_css_size(target: *const u8, width: *mut f64, height: *mut f64) -> i32;
|
||||
}
|
||||
|
||||
// milliseconds since start of program
|
||||
pub fn now() -> f64 {
|
||||
unsafe { emscripten_get_now() }
|
||||
}
|
||||
|
||||
pub fn sleep(ms: u32) {
|
||||
unsafe {
|
||||
emscripten_sleep(ms);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_canvas_size() -> (u32, u32) {
|
||||
let mut width = 0.0;
|
||||
let mut height = 0.0;
|
||||
unsafe {
|
||||
emscripten_get_element_css_size("canvas\0".as_ptr(), &mut width, &mut height);
|
||||
}
|
||||
(width as u32, height as u32)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
use glam::IVec2;
|
||||
|
||||
/// The four cardinal directions.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum Direction {
|
||||
Up,
|
||||
@@ -9,7 +10,12 @@ pub enum Direction {
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
pub fn opposite(&self) -> Direction {
|
||||
/// The four cardinal directions.
|
||||
/// This is just a convenience constant for iterating over the directions.
|
||||
pub const DIRECTIONS: [Direction; 4] = [Direction::Up, Direction::Down, Direction::Left, Direction::Right];
|
||||
|
||||
/// Returns the opposite direction. Constant time.
|
||||
pub const fn opposite(self) -> Direction {
|
||||
match self {
|
||||
Direction::Up => Direction::Down,
|
||||
Direction::Down => Direction::Up,
|
||||
@@ -18,8 +24,20 @@ impl Direction {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_ivec2(&self) -> IVec2 {
|
||||
(*self).into()
|
||||
/// Returns the direction as an IVec2.
|
||||
pub fn as_ivec2(self) -> IVec2 {
|
||||
self.into()
|
||||
}
|
||||
|
||||
/// Returns the direction as a usize (0-3). Constant time.
|
||||
/// This is useful for indexing into arrays.
|
||||
pub const fn as_usize(self) -> usize {
|
||||
match self {
|
||||
Direction::Up => 0,
|
||||
Direction::Down => 1,
|
||||
Direction::Left => 2,
|
||||
Direction::Right => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,5 +51,3 @@ impl From<Direction> for IVec2 {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const DIRECTIONS: [Direction; 4] = [Direction::Up, Direction::Down, Direction::Left, Direction::Right];
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
//! Pac-Man entity implementation.
|
||||
//!
|
||||
//! This module contains the main player character logic, including movement,
|
||||
//! animation, and rendering. Pac-Man moves through the game graph using
|
||||
//! a traverser and displays directional animated textures.
|
||||
|
||||
use glam::{UVec2, Vec2};
|
||||
|
||||
use crate::constants::BOARD_PIXEL_OFFSET;
|
||||
@@ -9,23 +15,35 @@ use crate::texture::directional::DirectionalAnimatedTexture;
|
||||
use crate::texture::sprite::SpriteAtlas;
|
||||
use sdl2::keyboard::Keycode;
|
||||
use sdl2::render::{Canvas, RenderTarget};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Determines if Pac-Man can traverse a given edge.
|
||||
///
|
||||
/// Pac-Man can only move through edges that allow all entities.
|
||||
fn can_pacman_traverse(edge: Edge) -> bool {
|
||||
matches!(edge.permissions, EdgePermissions::All)
|
||||
}
|
||||
|
||||
/// The main player character entity.
|
||||
///
|
||||
/// Pac-Man moves through the game world using a graph-based navigation system
|
||||
/// and displays directional animated sprites based on movement state.
|
||||
pub struct Pacman {
|
||||
/// Handles movement through the game graph
|
||||
pub traverser: Traverser,
|
||||
/// Manages directional animated textures for different movement states
|
||||
texture: DirectionalAnimatedTexture,
|
||||
}
|
||||
|
||||
impl Pacman {
|
||||
/// Creates a new Pac-Man instance at the specified starting node.
|
||||
///
|
||||
/// Sets up animated textures for all four directions with moving and stopped states.
|
||||
/// The moving animation cycles through open mouth, closed mouth, and full sprites.
|
||||
pub fn new(graph: &Graph, start_node: NodeId, atlas: &SpriteAtlas) -> Self {
|
||||
let mut textures = HashMap::new();
|
||||
let mut stopped_textures = HashMap::new();
|
||||
let mut textures = [None, None, None, None];
|
||||
let mut stopped_textures = [None, None, None, None];
|
||||
|
||||
for &direction in &[Direction::Up, Direction::Down, Direction::Left, Direction::Right] {
|
||||
for direction in Direction::DIRECTIONS {
|
||||
let moving_prefix = match direction {
|
||||
Direction::Up => "pacman/up",
|
||||
Direction::Down => "pacman/down",
|
||||
@@ -40,14 +58,9 @@ impl Pacman {
|
||||
|
||||
let stopped_tiles = vec![SpriteAtlas::get_tile(atlas, &format!("{moving_prefix}_b.png")).unwrap()];
|
||||
|
||||
textures.insert(
|
||||
direction,
|
||||
AnimatedTexture::new(moving_tiles, 0.08).expect("Invalid frame duration"),
|
||||
);
|
||||
stopped_textures.insert(
|
||||
direction,
|
||||
AnimatedTexture::new(stopped_tiles, 0.1).expect("Invalid frame duration"),
|
||||
);
|
||||
textures[direction.as_usize()] = Some(AnimatedTexture::new(moving_tiles, 0.08).expect("Invalid frame duration"));
|
||||
stopped_textures[direction.as_usize()] =
|
||||
Some(AnimatedTexture::new(stopped_tiles, 0.1).expect("Invalid frame duration"));
|
||||
}
|
||||
|
||||
Self {
|
||||
@@ -56,11 +69,19 @@ impl Pacman {
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates Pac-Man's position and animation state.
|
||||
///
|
||||
/// Advances movement through the graph and updates texture animation.
|
||||
/// Movement speed is scaled by 60 FPS and a 1.125 multiplier.
|
||||
pub fn tick(&mut self, dt: f32, graph: &Graph) {
|
||||
self.traverser.advance(graph, dt * 60.0 * 1.125, &can_pacman_traverse);
|
||||
self.texture.tick(dt);
|
||||
}
|
||||
|
||||
/// Handles keyboard input to change Pac-Man's direction.
|
||||
///
|
||||
/// Maps arrow keys to directions and queues the direction change
|
||||
/// for the next valid intersection.
|
||||
pub fn handle_key(&mut self, keycode: Keycode) {
|
||||
let direction = match keycode {
|
||||
Keycode::Up => Some(Direction::Up),
|
||||
@@ -75,6 +96,9 @@ impl Pacman {
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculates the current pixel position in the game world.
|
||||
///
|
||||
/// Interpolates between nodes when moving between them.
|
||||
fn get_pixel_pos(&self, graph: &Graph) -> Vec2 {
|
||||
match self.traverser.position {
|
||||
Position::AtNode(node_id) => graph.get_node(node_id).unwrap().position,
|
||||
@@ -86,6 +110,10 @@ impl Pacman {
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders Pac-Man to the canvas.
|
||||
///
|
||||
/// Calculates screen position, determines if Pac-Man is stopped,
|
||||
/// and renders the appropriate directional texture.
|
||||
pub fn render<T: RenderTarget>(&self, canvas: &mut Canvas<T>, atlas: &mut SpriteAtlas, graph: &Graph) {
|
||||
let pixel_pos = self.get_pixel_pos(graph).round().as_ivec2() + BOARD_PIXEL_OFFSET.as_ivec2();
|
||||
let dest = centered_with_size(pixel_pos, UVec2::new(16, 16));
|
||||
|
||||
@@ -4,9 +4,9 @@ pub mod app;
|
||||
pub mod asset;
|
||||
pub mod audio;
|
||||
pub mod constants;
|
||||
pub mod emscripten;
|
||||
pub mod entity;
|
||||
pub mod game;
|
||||
pub mod helpers;
|
||||
pub mod map;
|
||||
pub mod platform;
|
||||
pub mod texture;
|
||||
|
||||
53
src/main.rs
53
src/main.rs
@@ -5,59 +5,16 @@ use tracing::info;
|
||||
use tracing_error::ErrorLayer;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
|
||||
#[cfg(windows)]
|
||||
use winapi::{
|
||||
shared::ntdef::NULL,
|
||||
um::{
|
||||
fileapi::{CreateFileA, OPEN_EXISTING},
|
||||
handleapi::INVALID_HANDLE_VALUE,
|
||||
processenv::SetStdHandle,
|
||||
winbase::{STD_ERROR_HANDLE, STD_OUTPUT_HANDLE},
|
||||
wincon::{AttachConsole, GetConsoleWindow},
|
||||
winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE},
|
||||
},
|
||||
};
|
||||
|
||||
/// Attaches the process to the parent console on Windows.
|
||||
///
|
||||
/// This allows the application to print to the console when run from a terminal,
|
||||
/// which is useful for debugging purposes. If the application is not run from a
|
||||
/// terminal, this function does nothing.
|
||||
#[cfg(windows)]
|
||||
unsafe fn attach_console() {
|
||||
if !std::ptr::eq(GetConsoleWindow(), std::ptr::null_mut()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if AttachConsole(winapi::um::wincon::ATTACH_PARENT_PROCESS) != 0 {
|
||||
let handle = CreateFileA(
|
||||
c"CONOUT$".as_ptr(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
std::ptr::null_mut(),
|
||||
OPEN_EXISTING,
|
||||
0,
|
||||
NULL,
|
||||
);
|
||||
|
||||
if handle != INVALID_HANDLE_VALUE {
|
||||
SetStdHandle(STD_OUTPUT_HANDLE, handle);
|
||||
SetStdHandle(STD_ERROR_HANDLE, handle);
|
||||
}
|
||||
}
|
||||
// Do NOT call AllocConsole here - we don't want a console when launched from Explorer
|
||||
}
|
||||
|
||||
mod app;
|
||||
mod asset;
|
||||
mod audio;
|
||||
mod constants;
|
||||
#[cfg(target_os = "emscripten")]
|
||||
mod emscripten;
|
||||
|
||||
mod entity;
|
||||
mod game;
|
||||
mod helpers;
|
||||
mod map;
|
||||
mod platform;
|
||||
mod texture;
|
||||
|
||||
/// The main entry point of the application.
|
||||
@@ -65,12 +22,6 @@ mod texture;
|
||||
/// This function initializes SDL, the window, the game state, and then enters
|
||||
/// the main game loop.
|
||||
pub fn main() {
|
||||
// Attaches the console on Windows for debugging purposes.
|
||||
#[cfg(windows)]
|
||||
unsafe {
|
||||
attach_console();
|
||||
}
|
||||
|
||||
// Setup tracing
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_ansi(cfg!(not(target_os = "emscripten")))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Map construction and building functionality.
|
||||
|
||||
use crate::constants::{MapTile, BOARD_CELL_SIZE, CELL_SIZE};
|
||||
use crate::entity::direction::{Direction, DIRECTIONS};
|
||||
use crate::entity::direction::Direction;
|
||||
use crate::entity::graph::{EdgePermissions, Graph, Node, NodeId};
|
||||
use crate::map::parser::MapTileParser;
|
||||
use crate::map::render::MapRenderer;
|
||||
@@ -75,7 +75,7 @@ impl Map {
|
||||
|
||||
// Iterate over the queue, adding nodes to the graph and connecting them to their neighbors
|
||||
while let Some(source_position) = queue.pop_front() {
|
||||
for &dir in DIRECTIONS.iter() {
|
||||
for dir in Direction::DIRECTIONS {
|
||||
let new_position = source_position + dir.as_ivec2();
|
||||
|
||||
// Skip if the new position is out of bounds
|
||||
@@ -121,7 +121,7 @@ impl Map {
|
||||
|
||||
// While most nodes are already connected to their neighbors, some may not be, so we need to connect them
|
||||
for (grid_pos, &node_id) in &grid_to_node {
|
||||
for dir in DIRECTIONS {
|
||||
for dir in Direction::DIRECTIONS {
|
||||
// If the node doesn't have an edge in this direction, look for a neighbor in that direction
|
||||
if graph.adjacency_list[node_id].get(dir).is_none() {
|
||||
let neighbor = grid_pos + dir.as_ivec2();
|
||||
|
||||
77
src/platform/desktop.rs
Normal file
77
src/platform/desktop.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
//! Desktop platform implementation.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::asset::{Asset, AssetError};
|
||||
use crate::platform::{Platform, PlatformError};
|
||||
|
||||
/// Desktop platform implementation.
|
||||
pub struct DesktopPlatform;
|
||||
|
||||
impl Platform for DesktopPlatform {
|
||||
fn sleep(&self, duration: Duration) {
|
||||
spin_sleep::sleep(duration);
|
||||
}
|
||||
|
||||
fn get_time(&self) -> f64 {
|
||||
std::time::Instant::now().elapsed().as_secs_f64()
|
||||
}
|
||||
|
||||
fn init_console(&self) -> Result<(), PlatformError> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
unsafe {
|
||||
use winapi::{
|
||||
shared::ntdef::NULL,
|
||||
um::{
|
||||
fileapi::{CreateFileA, OPEN_EXISTING},
|
||||
handleapi::INVALID_HANDLE_VALUE,
|
||||
processenv::SetStdHandle,
|
||||
winbase::{STD_ERROR_HANDLE, STD_OUTPUT_HANDLE},
|
||||
wincon::{AttachConsole, GetConsoleWindow},
|
||||
winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE},
|
||||
},
|
||||
};
|
||||
|
||||
if !std::ptr::eq(GetConsoleWindow(), std::ptr::null_mut()) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if AttachConsole(winapi::um::wincon::ATTACH_PARENT_PROCESS) != 0 {
|
||||
let handle = CreateFileA(
|
||||
c"CONOUT$".as_ptr(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
std::ptr::null_mut(),
|
||||
OPEN_EXISTING,
|
||||
0,
|
||||
NULL,
|
||||
);
|
||||
|
||||
if handle != INVALID_HANDLE_VALUE {
|
||||
SetStdHandle(STD_OUTPUT_HANDLE, handle);
|
||||
SetStdHandle(STD_ERROR_HANDLE, handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_canvas_size(&self) -> Option<(u32, u32)> {
|
||||
None // Desktop doesn't need this
|
||||
}
|
||||
|
||||
fn get_asset_bytes(&self, asset: Asset) -> Result<Cow<'static, [u8]>, AssetError> {
|
||||
match asset {
|
||||
Asset::Wav1 => Ok(Cow::Borrowed(include_bytes!("../../assets/game/sound/waka/1.ogg"))),
|
||||
Asset::Wav2 => Ok(Cow::Borrowed(include_bytes!("../../assets/game/sound/waka/2.ogg"))),
|
||||
Asset::Wav3 => Ok(Cow::Borrowed(include_bytes!("../../assets/game/sound/waka/3.ogg"))),
|
||||
Asset::Wav4 => Ok(Cow::Borrowed(include_bytes!("../../assets/game/sound/waka/4.ogg"))),
|
||||
Asset::Atlas => Ok(Cow::Borrowed(include_bytes!("../../assets/game/atlas.png"))),
|
||||
Asset::AtlasJson => Ok(Cow::Borrowed(include_bytes!("../../assets/game/atlas.json"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
61
src/platform/emscripten.rs
Normal file
61
src/platform/emscripten.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
//! Emscripten platform implementation.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::asset::{Asset, AssetError};
|
||||
use crate::platform::{Platform, PlatformError};
|
||||
|
||||
/// Emscripten platform implementation.
|
||||
pub struct EmscriptenPlatform;
|
||||
|
||||
impl Platform for EmscriptenPlatform {
|
||||
fn sleep(&self, duration: Duration) {
|
||||
unsafe {
|
||||
emscripten_sleep(duration.as_millis() as u32);
|
||||
}
|
||||
}
|
||||
|
||||
fn get_time(&self) -> f64 {
|
||||
unsafe { emscripten_get_now() }
|
||||
}
|
||||
|
||||
fn init_console(&self) -> Result<(), PlatformError> {
|
||||
Ok(()) // No-op for Emscripten
|
||||
}
|
||||
|
||||
fn get_canvas_size(&self) -> Option<(u32, u32)> {
|
||||
Some(unsafe { get_canvas_size() })
|
||||
}
|
||||
|
||||
fn get_asset_bytes(&self, asset: Asset) -> Result<Cow<'static, [u8]>, AssetError> {
|
||||
use sdl2::rwops::RWops;
|
||||
use std::io::Read;
|
||||
|
||||
let path = format!("assets/game/{}", asset.path());
|
||||
let mut rwops = RWops::from_file(&path, "rb").map_err(|_| AssetError::NotFound(asset.path().to_string()))?;
|
||||
|
||||
let len = rwops.len().ok_or_else(|| AssetError::NotFound(asset.path().to_string()))?;
|
||||
|
||||
let mut buf = vec![0u8; len];
|
||||
rwops
|
||||
.read_exact(&mut buf)
|
||||
.map_err(|e| AssetError::Io(std::io::Error::other(e)))?;
|
||||
|
||||
Ok(Cow::Owned(buf))
|
||||
}
|
||||
}
|
||||
|
||||
// Emscripten FFI functions
|
||||
extern "C" {
|
||||
fn emscripten_get_now() -> f64;
|
||||
fn emscripten_sleep(ms: u32);
|
||||
fn emscripten_get_element_css_size(target: *const u8, width: *mut f64, height: *mut f64) -> i32;
|
||||
}
|
||||
|
||||
unsafe fn get_canvas_size() -> (u32, u32) {
|
||||
let mut width = 0.0;
|
||||
let mut height = 0.0;
|
||||
emscripten_get_element_css_size(c"canvas".as_ptr().cast(), &mut width, &mut height);
|
||||
(width as u32, height as u32)
|
||||
}
|
||||
58
src/platform/mod.rs
Normal file
58
src/platform/mod.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
//! Platform abstraction layer for cross-platform functionality.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::asset::{Asset, AssetError};
|
||||
|
||||
pub mod desktop;
|
||||
pub mod emscripten;
|
||||
|
||||
/// Platform abstraction trait that defines cross-platform functionality.
|
||||
pub trait Platform {
|
||||
/// Sleep for the specified duration using platform-appropriate method.
|
||||
fn sleep(&self, duration: Duration);
|
||||
|
||||
/// Get the current time in seconds since some reference point.
|
||||
/// This is available for future use in timing and performance monitoring.
|
||||
#[allow(dead_code)]
|
||||
fn get_time(&self) -> f64;
|
||||
|
||||
/// Initialize platform-specific console functionality.
|
||||
fn init_console(&self) -> Result<(), PlatformError>;
|
||||
|
||||
/// Get canvas size for platforms that need it (e.g., Emscripten).
|
||||
/// This is available for future use in responsive design.
|
||||
#[allow(dead_code)]
|
||||
fn get_canvas_size(&self) -> Option<(u32, u32)>;
|
||||
|
||||
/// Load asset bytes using platform-appropriate method.
|
||||
fn get_asset_bytes(&self, asset: Asset) -> Result<Cow<'static, [u8]>, AssetError>;
|
||||
}
|
||||
|
||||
/// Platform-specific errors.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[allow(dead_code)]
|
||||
pub enum PlatformError {
|
||||
#[error("Console initialization failed: {0}")]
|
||||
ConsoleInit(String),
|
||||
#[error("Platform-specific error: {0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// Get the current platform implementation.
|
||||
#[allow(dead_code)]
|
||||
pub fn get_platform() -> &'static dyn Platform {
|
||||
static DESKTOP: desktop::DesktopPlatform = desktop::DesktopPlatform;
|
||||
static EMSCRIPTEN: emscripten::EmscriptenPlatform = emscripten::EmscriptenPlatform;
|
||||
|
||||
#[cfg(not(target_os = "emscripten"))]
|
||||
{
|
||||
&DESKTOP
|
||||
}
|
||||
|
||||
#[cfg(target_os = "emscripten")]
|
||||
{
|
||||
&EMSCRIPTEN
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use anyhow::Result;
|
||||
use sdl2::rect::Rect;
|
||||
use sdl2::render::{Canvas, RenderTarget};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::entity::direction::Direction;
|
||||
use crate::texture::animated::AnimatedTexture;
|
||||
@@ -9,12 +8,12 @@ use crate::texture::sprite::SpriteAtlas;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DirectionalAnimatedTexture {
|
||||
textures: HashMap<Direction, AnimatedTexture>,
|
||||
stopped_textures: HashMap<Direction, AnimatedTexture>,
|
||||
textures: [Option<AnimatedTexture>; 4],
|
||||
stopped_textures: [Option<AnimatedTexture>; 4],
|
||||
}
|
||||
|
||||
impl DirectionalAnimatedTexture {
|
||||
pub fn new(textures: HashMap<Direction, AnimatedTexture>, stopped_textures: HashMap<Direction, AnimatedTexture>) -> Self {
|
||||
pub fn new(textures: [Option<AnimatedTexture>; 4], stopped_textures: [Option<AnimatedTexture>; 4]) -> Self {
|
||||
Self {
|
||||
textures,
|
||||
stopped_textures,
|
||||
@@ -22,7 +21,7 @@ impl DirectionalAnimatedTexture {
|
||||
}
|
||||
|
||||
pub fn tick(&mut self, dt: f32) {
|
||||
for texture in self.textures.values_mut() {
|
||||
for texture in self.textures.iter_mut().flatten() {
|
||||
texture.tick(dt);
|
||||
}
|
||||
}
|
||||
@@ -34,7 +33,7 @@ impl DirectionalAnimatedTexture {
|
||||
dest: Rect,
|
||||
direction: Direction,
|
||||
) -> Result<()> {
|
||||
if let Some(texture) = self.textures.get(&direction) {
|
||||
if let Some(texture) = &self.textures[direction.as_usize()] {
|
||||
texture.render(canvas, atlas, dest)
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -48,7 +47,7 @@ impl DirectionalAnimatedTexture {
|
||||
dest: Rect,
|
||||
direction: Direction,
|
||||
) -> Result<()> {
|
||||
if let Some(texture) = self.stopped_textures.get(&direction) {
|
||||
if let Some(texture) = &self.stopped_textures[direction.as_usize()] {
|
||||
texture.render(canvas, atlas, dest)
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -58,24 +57,24 @@ impl DirectionalAnimatedTexture {
|
||||
/// Returns true if the texture has a direction.
|
||||
#[allow(dead_code)]
|
||||
pub fn has_direction(&self, direction: Direction) -> bool {
|
||||
self.textures.contains_key(&direction)
|
||||
self.textures[direction.as_usize()].is_some()
|
||||
}
|
||||
|
||||
/// Returns true if the texture has a stopped direction.
|
||||
#[allow(dead_code)]
|
||||
pub fn has_stopped_direction(&self, direction: Direction) -> bool {
|
||||
self.stopped_textures.contains_key(&direction)
|
||||
self.stopped_textures[direction.as_usize()].is_some()
|
||||
}
|
||||
|
||||
/// Returns the number of textures.
|
||||
#[allow(dead_code)]
|
||||
pub fn texture_count(&self) -> usize {
|
||||
self.textures.len()
|
||||
self.textures.iter().filter(|t| t.is_some()).count()
|
||||
}
|
||||
|
||||
/// Returns the number of stopped textures.
|
||||
#[allow(dead_code)]
|
||||
pub fn stopped_texture_count(&self) -> usize {
|
||||
self.stopped_textures.len()
|
||||
self.stopped_textures.iter().filter(|t| t.is_some()).count()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ use pacman::texture::animated::AnimatedTexture;
|
||||
use pacman::texture::directional::DirectionalAnimatedTexture;
|
||||
use pacman::texture::sprite::AtlasTile;
|
||||
use sdl2::pixels::Color;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn mock_atlas_tile(id: u32) -> AtlasTile {
|
||||
AtlasTile {
|
||||
@@ -20,10 +19,10 @@ fn mock_animated_texture(id: u32) -> AnimatedTexture {
|
||||
|
||||
#[test]
|
||||
fn test_directional_texture_partial_directions() {
|
||||
let mut textures = HashMap::new();
|
||||
textures.insert(Direction::Up, mock_animated_texture(1));
|
||||
let mut textures = [None, None, None, None];
|
||||
textures[Direction::Up.as_usize()] = Some(mock_animated_texture(1));
|
||||
|
||||
let texture = DirectionalAnimatedTexture::new(textures, HashMap::new());
|
||||
let texture = DirectionalAnimatedTexture::new(textures, [None, None, None, None]);
|
||||
|
||||
assert_eq!(texture.texture_count(), 1);
|
||||
assert!(texture.has_direction(Direction::Up));
|
||||
@@ -34,7 +33,7 @@ fn test_directional_texture_partial_directions() {
|
||||
|
||||
#[test]
|
||||
fn test_directional_texture_all_directions() {
|
||||
let mut textures = HashMap::new();
|
||||
let mut textures = [None, None, None, None];
|
||||
let directions = [
|
||||
(Direction::Up, 1),
|
||||
(Direction::Down, 2),
|
||||
@@ -43,10 +42,10 @@ fn test_directional_texture_all_directions() {
|
||||
];
|
||||
|
||||
for (direction, id) in directions {
|
||||
textures.insert(direction, mock_animated_texture(id));
|
||||
textures[direction.as_usize()] = Some(mock_animated_texture(id));
|
||||
}
|
||||
|
||||
let texture = DirectionalAnimatedTexture::new(textures, HashMap::new());
|
||||
let texture = DirectionalAnimatedTexture::new(textures, [None, None, None, None]);
|
||||
|
||||
assert_eq!(texture.texture_count(), 4);
|
||||
for direction in &[Direction::Up, Direction::Down, Direction::Left, Direction::Right] {
|
||||
|
||||
442
web.build.ts
442
web.build.ts
@@ -3,6 +3,24 @@ import { existsSync, promises as fs } from "fs";
|
||||
import { platform } from "os";
|
||||
import { dirname, join, relative, resolve } from "path";
|
||||
import { match, P } from "ts-pattern";
|
||||
import { configure, getConsoleSink, getLogger } from "@logtape/logtape";
|
||||
|
||||
// Constants
|
||||
const TAILWIND_UPDATE_WINDOW_DAYS = 60; // 2 months
|
||||
|
||||
await configure({
|
||||
sinks: { console: getConsoleSink() },
|
||||
loggers: [
|
||||
{ category: "web", lowestLevel: "debug", sinks: ["console"] },
|
||||
{
|
||||
category: ["logtape", "meta"],
|
||||
lowestLevel: "warning",
|
||||
sinks: ["console"],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const logger = getLogger("web");
|
||||
|
||||
type Os =
|
||||
| { type: "linux"; wsl: boolean }
|
||||
@@ -22,29 +40,37 @@ const os: Os = match(platform())
|
||||
throw new Error(`Unsupported platform: ${platform()}`);
|
||||
});
|
||||
|
||||
function log(msg: string) {
|
||||
console.log(`[web.build] ${msg}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the application with Emscripten, generate the CSS, and copy the files into 'dist'.
|
||||
*
|
||||
* @param release - Whether to build in release mode.
|
||||
* @param env - The environment variables to inject into build commands.
|
||||
*/
|
||||
async function build(release: boolean, env: Record<string, string>) {
|
||||
log(
|
||||
async function build(release: boolean, env: Record<string, string> | null) {
|
||||
logger.info(
|
||||
`Building for 'wasm32-unknown-emscripten' for ${
|
||||
release ? "release" : "debug"
|
||||
}`
|
||||
);
|
||||
await $`cargo build --target=wasm32-unknown-emscripten ${
|
||||
release ? "--release" : ""
|
||||
}`.env(env);
|
||||
}`.env(env ?? undefined);
|
||||
|
||||
log("Invoking @tailwindcss/cli");
|
||||
// unfortunately, bunx doesn't seem to work with @tailwindcss/cli, so we have to use npx directly
|
||||
await $`npx --yes @tailwindcss/cli --minify --input styles.css --output build.css --cwd assets/site`;
|
||||
// Download the Tailwind CSS CLI for rendering the CSS
|
||||
const tailwindExecutable = match(
|
||||
await downloadTailwind(process.cwd(), {
|
||||
version: "latest",
|
||||
force: false,
|
||||
})
|
||||
)
|
||||
.with({ path: P.select() }, (path) => path)
|
||||
.with({ err: P.select() }, (err) => {
|
||||
throw new Error(err);
|
||||
})
|
||||
.exhaustive();
|
||||
|
||||
logger.debug(`Invoking ${tailwindExecutable}...`);
|
||||
await $`${tailwindExecutable} --minify --input styles.css --output build.css --cwd assets/site`;
|
||||
|
||||
const buildType = release ? "release" : "debug";
|
||||
const siteFolder = resolve("assets/site");
|
||||
@@ -80,20 +106,20 @@ async function build(release: boolean, env: Record<string, string>) {
|
||||
.map(async (dir) => {
|
||||
// If the folder doesn't exist, create it
|
||||
if (!(await fs.exists(dir))) {
|
||||
log(`Creating folder ${dir}`);
|
||||
logger.debug(`Creating folder ${dir}`);
|
||||
await fs.mkdir(dir, { recursive: true });
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Copy the files to the dist folder
|
||||
log("Copying files into dist");
|
||||
logger.debug("Copying files into dist");
|
||||
await Promise.all(
|
||||
files.map(async ({ optional, src, dest }) => {
|
||||
match({ optional, exists: await fs.exists(src) })
|
||||
// If optional and doesn't exist, skip
|
||||
.with({ optional: true, exists: false }, () => {
|
||||
log(
|
||||
logger.debug(
|
||||
`Optional file ${os.type === "windows" ? "\\" : "/"}${relative(
|
||||
process.cwd(),
|
||||
src
|
||||
@@ -110,6 +136,248 @@ async function build(release: boolean, env: Record<string, string>) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download the Tailwind CSS CLI to the specified directory.
|
||||
* @param dir - The directory to download the Tailwind CSS CLI to.
|
||||
* @returns The path to the downloaded Tailwind CSS CLI, or an error message if the download fails.
|
||||
*/
|
||||
async function downloadTailwind(
|
||||
dir: string,
|
||||
options?: Partial<{
|
||||
version: string; // The version of Tailwind CSS to download. If not specified, the latest version will be downloaded.
|
||||
force: boolean; // Whether to force the download even if the file already exists.
|
||||
}>
|
||||
): Promise<{ path: string } | { err: string }> {
|
||||
const asset = match(os)
|
||||
.with({ type: "linux" }, () => "tailwindcss-linux-x64")
|
||||
.with({ type: "macos" }, () => "tailwindcss-macos-arm64")
|
||||
.with({ type: "windows" }, () => "tailwindcss-windows-x64.exe")
|
||||
.exhaustive();
|
||||
|
||||
const version = options?.version ?? "latest";
|
||||
const force = options?.force ?? false;
|
||||
|
||||
const url =
|
||||
version === "latest" || version == null
|
||||
? `https://github.com/tailwindlabs/tailwindcss/releases/latest/download/${asset}`
|
||||
: `https://github.com/tailwindlabs/tailwindcss/releases/download/${version}/${asset}`;
|
||||
|
||||
// If the GITHUB_TOKEN environment variable is set, use it for Bearer authentication
|
||||
const headers: Record<string, string> = {};
|
||||
if (process.env.GITHUB_TOKEN) {
|
||||
headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`;
|
||||
}
|
||||
|
||||
// Check if the file already exists
|
||||
const path = join(dir, asset);
|
||||
const exists = await fs.exists(path);
|
||||
|
||||
// Check if we should download based on timestamps
|
||||
let shouldDownload = force || !exists;
|
||||
|
||||
if (exists && !force) {
|
||||
try {
|
||||
const fileStats = await fs.stat(path);
|
||||
const fileModifiedTime = fileStats.mtime;
|
||||
const now = new Date();
|
||||
|
||||
// Check if file is older than the update window
|
||||
const updateWindowAgo = new Date(
|
||||
now.getTime() - TAILWIND_UPDATE_WINDOW_DAYS * 24 * 60 * 60 * 1000
|
||||
);
|
||||
|
||||
if (fileModifiedTime < updateWindowAgo) {
|
||||
logger.debug(
|
||||
`File is older than ${TAILWIND_UPDATE_WINDOW_DAYS} days, checking for updates...`
|
||||
);
|
||||
shouldDownload = true;
|
||||
} else {
|
||||
logger.debug(
|
||||
`File is recent (${fileModifiedTime.toISOString()}), checking if newer version available...`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.debug(
|
||||
`Error checking file timestamp: ${error}, will download anyway`
|
||||
);
|
||||
shouldDownload = true;
|
||||
}
|
||||
}
|
||||
|
||||
// If we need to download, check the server's last-modified header
|
||||
if (shouldDownload) {
|
||||
const response = await fetch(url, {
|
||||
headers,
|
||||
method: "HEAD",
|
||||
redirect: "follow",
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const lastModified = response.headers.get("last-modified");
|
||||
if (lastModified) {
|
||||
const serverTime = new Date(lastModified);
|
||||
const now = new Date();
|
||||
|
||||
// If server timestamp is in the future, something is wrong - download anyway
|
||||
if (serverTime > now) {
|
||||
logger.debug(
|
||||
`Server timestamp is in the future (${serverTime.toISOString()}), downloading anyway`
|
||||
);
|
||||
shouldDownload = true;
|
||||
} else if (exists) {
|
||||
// Compare with local file timestamp (both in UTC)
|
||||
const fileStats = await fs.stat(path);
|
||||
const fileModifiedTime = new Date(fileStats.mtime.getTime());
|
||||
|
||||
if (serverTime > fileModifiedTime) {
|
||||
logger.debug(
|
||||
`Server has newer version (${serverTime.toISOString()} vs local ${fileModifiedTime.toISOString()})`
|
||||
);
|
||||
shouldDownload = true;
|
||||
} else {
|
||||
logger.debug(
|
||||
`Local file is up to date (${fileModifiedTime.toISOString()})`
|
||||
);
|
||||
shouldDownload = false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.debug(
|
||||
`No last-modified header available, downloading to be safe`
|
||||
);
|
||||
shouldDownload = true;
|
||||
}
|
||||
} else {
|
||||
logger.debug(
|
||||
`Failed to check server headers: ${response.status} ${response.statusText}`
|
||||
);
|
||||
shouldDownload = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (exists && !shouldDownload) {
|
||||
const displayPath = match(relative(process.cwd(), path))
|
||||
// If the path is not a subpath of cwd, display the absolute path
|
||||
.with(P.string.startsWith(".."), (_relative) => path)
|
||||
// Otherwise, display the relative path
|
||||
.otherwise((relative) => relative);
|
||||
|
||||
logger.debug(
|
||||
`Tailwind CSS CLI already exists and is up to date at ${displayPath}`
|
||||
);
|
||||
return { path };
|
||||
}
|
||||
|
||||
if (exists) {
|
||||
const displayPath = match(relative(process.cwd(), path))
|
||||
// If the path is not a subpath of cwd, display the absolute path
|
||||
.with(P.string.startsWith(".."), (_relative) => path)
|
||||
// Otherwise, display the relative path
|
||||
.otherwise((relative) => relative);
|
||||
|
||||
if (force) {
|
||||
logger.debug(`Overwriting Tailwind CSS CLI at ${displayPath}`);
|
||||
} else {
|
||||
logger.debug(`Downloading updated Tailwind CSS CLI to ${displayPath}`);
|
||||
}
|
||||
} else {
|
||||
logger.debug(`Downloading Tailwind CSS CLI to ${path}`);
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(`Fetching ${url}...`);
|
||||
const response = await fetch(url, { headers });
|
||||
|
||||
if (!response.ok) {
|
||||
return {
|
||||
err: `Failed to download Tailwind CSS: ${response.status} ${response.statusText} for '${url}'`,
|
||||
};
|
||||
} else if (!response.body) {
|
||||
return { err: `No response body received for '${url}'` };
|
||||
}
|
||||
|
||||
// Validate Content-Length if available
|
||||
const contentLength = response.headers.get("content-length");
|
||||
if (contentLength) {
|
||||
const expectedSize = parseInt(contentLength, 10);
|
||||
if (isNaN(expectedSize)) {
|
||||
return { err: `Invalid Content-Length header: ${contentLength}` };
|
||||
}
|
||||
logger.debug(`Expected file size: ${expectedSize} bytes`);
|
||||
}
|
||||
|
||||
logger.debug(`Writing to ${path}...`);
|
||||
await fs.mkdir(dir, { recursive: true });
|
||||
|
||||
const file = Bun.file(path);
|
||||
const writer = file.writer();
|
||||
|
||||
const reader = response.body.getReader();
|
||||
let downloadedBytes = 0;
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
writer.write(value);
|
||||
downloadedBytes += value.length;
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
await writer.end();
|
||||
}
|
||||
|
||||
// Validate downloaded file size
|
||||
if (contentLength) {
|
||||
const expectedSize = parseInt(contentLength, 10);
|
||||
const actualSize = downloadedBytes;
|
||||
|
||||
if (actualSize !== expectedSize) {
|
||||
// Clean up the corrupted file
|
||||
try {
|
||||
await fs.unlink(path);
|
||||
} catch (unlinkError) {
|
||||
logger.debug(
|
||||
`Warning: Failed to clean up corrupted file: ${unlinkError}`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
err: `File size mismatch: expected ${expectedSize} bytes, got ${actualSize} bytes. File may be corrupted.`,
|
||||
};
|
||||
}
|
||||
|
||||
logger.debug(`File size validation passed: ${actualSize} bytes`);
|
||||
}
|
||||
|
||||
// Make the file executable on Unix-like systems
|
||||
if (os.type !== "windows") {
|
||||
await $`chmod +x ${path}`;
|
||||
}
|
||||
|
||||
// Ensure file is not locked; sometimes the runtime is too fast and the file is executed before the lock is released
|
||||
const timeout = Date.now() + 2500; // 2.5s timeout
|
||||
do {
|
||||
try {
|
||||
if ((await fs.stat(path)).size > 0) break;
|
||||
} catch {
|
||||
// File might not be ready yet
|
||||
logger.debug(`File ${path} is not ready yet, waiting...`);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
} while (Date.now() < timeout);
|
||||
|
||||
// All done!
|
||||
return { path };
|
||||
} catch (error) {
|
||||
return {
|
||||
err: `Download failed: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if the Emscripten SDK is activated for a Windows or *nix machine by looking for a .exe file and the equivalent file on Linux/macOS. Returns both results for handling.
|
||||
* @param emsdkDir - The directory containing the Emscripten SDK.
|
||||
@@ -128,14 +396,73 @@ async function checkEmsdkType(
|
||||
|
||||
/**
|
||||
* Activate the Emscripten SDK environment variables.
|
||||
* Technically, this doesn't actaully activate the environment variables for the current shell,
|
||||
* Technically, this doesn't actually activate the environment variables for the current shell,
|
||||
* it just runs the environment sourcing script and returns the environment variables for future command invocations.
|
||||
* @param emsdkDir - The directory containing the Emscripten SDK.
|
||||
* @returns A record of environment variables.
|
||||
*/
|
||||
async function activateEmsdk(
|
||||
emsdkDir: string
|
||||
): Promise<{ vars: Record<string, string> } | { err: string }> {
|
||||
): Promise<{ vars: Record<string, string> | null } | { err: string }> {
|
||||
// If the EMSDK environment variable is set already & the path specified exists, return nothing
|
||||
if (process.env.EMSDK && (await fs.exists(resolve(process.env.EMSDK)))) {
|
||||
logger.debug(
|
||||
"Emscripten SDK already activated in environment, using existing configuration"
|
||||
);
|
||||
return { vars: null };
|
||||
}
|
||||
|
||||
// Check if the emsdk directory exists
|
||||
if (!(await fs.exists(emsdkDir))) {
|
||||
return {
|
||||
err: `Emscripten SDK directory not found at ${emsdkDir}. Please install or clone 'emsdk' and try again.`,
|
||||
};
|
||||
}
|
||||
|
||||
// Check if the emsdk directory is activated/installed properly for the current OS
|
||||
match({
|
||||
os: os,
|
||||
...(await checkEmsdkType(emsdkDir)),
|
||||
})
|
||||
// If the Emscripten SDK is not activated/installed properly, exit with an error
|
||||
.with(
|
||||
{
|
||||
nix: false,
|
||||
windows: false,
|
||||
},
|
||||
() => {
|
||||
return {
|
||||
err: "Emscripten SDK does not appear to be activated/installed properly.",
|
||||
};
|
||||
}
|
||||
)
|
||||
// If the Emscripten SDK is activated for Windows, but is currently running on a *nix OS, exit with an error
|
||||
.with(
|
||||
{
|
||||
nix: false,
|
||||
windows: true,
|
||||
os: { type: P.not("windows") },
|
||||
},
|
||||
() => {
|
||||
return {
|
||||
err: "Emscripten SDK appears to be activated for Windows, but is currently running on a *nix OS.",
|
||||
};
|
||||
}
|
||||
)
|
||||
// If the Emscripten SDK is activated for *nix, but is currently running on a Windows OS, exit with an error
|
||||
.with(
|
||||
{
|
||||
nix: true,
|
||||
windows: false,
|
||||
os: { type: "windows" },
|
||||
},
|
||||
() => {
|
||||
return {
|
||||
err: "Emscripten SDK appears to be activated for *nix, but is currently running on a Windows OS.",
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
// Determine the environment script to use based on the OS
|
||||
const envScript = match(os)
|
||||
.with({ type: "windows" }, () => join(emsdkDir, "emsdk_env.bat"))
|
||||
@@ -174,7 +501,7 @@ async function activateEmsdk(
|
||||
|
||||
async function main() {
|
||||
// Print the OS detected
|
||||
log(
|
||||
logger.debug(
|
||||
"OS Detected: " +
|
||||
match(os)
|
||||
.with({ type: "windows" }, () => "Windows")
|
||||
@@ -188,81 +515,14 @@ async function main() {
|
||||
const release = process.env.RELEASE !== "0";
|
||||
const emsdkDir = resolve("./emsdk");
|
||||
|
||||
// Check if Emscripten is already activated in the environment
|
||||
const emscriptenAlreadyActivated =
|
||||
process.env.EMSCRIPTEN || process.env.EMSDK;
|
||||
|
||||
let vars: Record<string, string>;
|
||||
|
||||
if (emscriptenAlreadyActivated) {
|
||||
log(
|
||||
"Emscripten SDK already activated in environment, using existing configuration"
|
||||
);
|
||||
vars = process.env as Record<string, string>;
|
||||
} else {
|
||||
// Ensure the emsdk directory exists before attempting to activate or use it
|
||||
if (!(await fs.exists(emsdkDir))) {
|
||||
log(
|
||||
`Emscripten SDK directory not found at ${emsdkDir}. Please install or clone 'emsdk' and try again.`
|
||||
);
|
||||
// Activate the Emscripten SDK (returns null if already activated)
|
||||
const vars = match(await activateEmsdk(emsdkDir))
|
||||
.with({ vars: P.select() }, (vars) => vars)
|
||||
.with({ err: P.any }, ({ err }) => {
|
||||
logger.debug("Error activating Emscripten SDK: " + err);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
vars = match(await activateEmsdk(emsdkDir)) // result handling
|
||||
.with({ vars: P.select() }, (vars) => vars)
|
||||
.with({ err: P.any }, ({ err }) => {
|
||||
log("Error activating Emscripten SDK: " + err);
|
||||
process.exit(1);
|
||||
})
|
||||
.exhaustive();
|
||||
}
|
||||
|
||||
// Check if the Emscripten SDK is activated/installed properly for the current OS
|
||||
match({
|
||||
os: os,
|
||||
...(await checkEmsdkType(emsdkDir)),
|
||||
})
|
||||
// If the Emscripten SDK is not activated/installed properly, exit with an error
|
||||
.with(
|
||||
{
|
||||
nix: false,
|
||||
windows: false,
|
||||
},
|
||||
() => {
|
||||
log(
|
||||
"Emscripten SDK does not appear to be activated/installed properly."
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
)
|
||||
// If the Emscripten SDK is activated for Windows, but is currently running on a *nix OS, exit with an error
|
||||
.with(
|
||||
{
|
||||
nix: false,
|
||||
windows: true,
|
||||
os: { type: P.not("windows") },
|
||||
},
|
||||
() => {
|
||||
log(
|
||||
"Emscripten SDK appears to be activated for Windows, but is currently running on a *nix OS."
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
)
|
||||
// If the Emscripten SDK is activated for *nix, but is currently running on a Windows OS, exit with an error
|
||||
.with(
|
||||
{
|
||||
nix: true,
|
||||
windows: false,
|
||||
os: { type: "windows" },
|
||||
},
|
||||
() => {
|
||||
log(
|
||||
"Emscripten SDK appears to be activated for *nix, but is currently running on a Windows OS."
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
);
|
||||
})
|
||||
.exhaustive();
|
||||
|
||||
// Build the application
|
||||
await build(release, vars);
|
||||
@@ -272,6 +532,6 @@ async function main() {
|
||||
* Main entry point.
|
||||
*/
|
||||
main().catch((err) => {
|
||||
console.error("[web.build] Error:", err);
|
||||
console.error({ msg: "fatal error", error: err });
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user