From a2ca2b682741a667a5165dc749f49845b6149dee Mon Sep 17 00:00:00 2001 From: Evan Pratten Date: Thu, 30 Sep 2021 10:18:50 -0400 Subject: [PATCH] working on err handling --- game/Cargo.toml | 2 ++ game/src/utilities/datastore.rs | 44 +++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/game/Cargo.toml b/game/Cargo.toml index a220020..dfb38f6 100644 --- a/game/Cargo.toml +++ b/game/Cargo.toml @@ -21,6 +21,8 @@ puffin_http = "0.6" dirty-fsm = "^0.2.2" num-traits = "0.2" sentry = "0.23" +image = "0.23" +tempfile = "3.2" [dev-dependencies] puffin_viewer = "0.6" diff --git a/game/src/utilities/datastore.rs b/game/src/utilities/datastore.rs index 2c0ce0f..c037967 100644 --- a/game/src/utilities/datastore.rs +++ b/game/src/utilities/datastore.rs @@ -1,3 +1,47 @@ +use std::io::Write; + +use raylib::{texture::Texture2D, RaylibHandle, RaylibThread}; +use tempfile::{tempfile, NamedTempFile}; + +/// Contains all game assets. +/// +/// This uses macro magic to automatically embed the contents of `game/assets/` into the executable +/// file so we only have to distribute a single file, instead of a game and its assets separately #[derive(rust_embed::RustEmbed)] #[folder = "assets"] pub struct StaticGameData; + +#[derive(Debug, Error)] +pub enum ResourceLoadError { + #[error(transparent)] + Io(#[from] std::io::Error), + #[error("Could not load embedded asset: {0}")] + AssetNotFound(String), + #[error("Generic error: {0}")] + Generic(String), +} + +pub fn load_texture_from_internal_data( + raylib_handle: &RaylibHandle, + thread: &RaylibThread, + path: &str, +) -> Result { + // Create a temp file path to work with + let tmp_path = NamedTempFile::new()?.into_temp_path(); + + // Unpack the raw image data to a real file on the local filesystem so raylib will read it correctly + std::fs::write( + tmp_path, + &StaticGameData::get(path) + .ok_or(ResourceLoadError::AssetNotFound(path.to_string()))? + .data, + )?; + + // Call through via FFI to re-load the file + let texture = raylib_handle.load_texture(thread, tmp_path.to_str().unwrap()).map_err(|e| ResourceLoadError::Generic(e)); + + // Close the file + tmp_path.close()?; + + Ok(texture) +}