Skip to content

Commit

Permalink
more complete error on texture load and move descriptions to common
Browse files Browse the repository at this point in the history
  • Loading branch information
Uriopass committed Aug 20, 2023
1 parent ec03e8c commit 005a1fe
Show file tree
Hide file tree
Showing 18 changed files with 204 additions and 138 deletions.
38 changes: 37 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ egui-winit = { version = "0.22.0", default-features = false }
ordered-float = { version = "3.4.0", default-features = false }
winit = "0.28.6"
oddio = "0.6.2"
derive_more = "0.99.17"

# Set the settings for build scripts and proc-macros.
[profile.dev.build-override]
Expand Down
43 changes: 43 additions & 0 deletions common/src/descriptions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use geom::Vec2;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct RecipeDescription {
pub consumption: Vec<(String, i32)>,
pub production: Vec<(String, i32)>,
pub complexity: i32,
pub storage_multiplier: i32,
}

#[derive(Serialize, Deserialize)]
pub struct BuildingGenDescription {
pub kind: String,
pub vertical_factor: Option<f32>,
pub door_pos: Option<Vec2>,
}

#[derive(Serialize, Deserialize)]
pub struct GoodsCompanyDescriptionJSON {
pub name: String,
pub bgen: BuildingGenDescription,
pub kind: String,
pub recipe: RecipeDescription,
pub n_workers: i32,
pub n_trucks: Option<u32>,
pub size: f32,
pub asset_location: String,
pub price: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub zone: Option<Box<ZoneDescription>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ZoneDescription {
pub floor: String,
pub filler: String,
/// The price for each "production unit"
pub price_per_area: i64,
/// Wether the zone filler positions should be randomized
#[serde(default)]
pub randomize_filler: bool,
}
1 change: 1 addition & 0 deletions common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ where
{
}

pub mod descriptions;
pub mod history;
pub mod logger;
pub mod rand;
Expand Down
25 changes: 14 additions & 11 deletions common/src/saveload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::fs::File;
use std::io;
use std::io::{BufReader, BufWriter, ErrorKind, Read, Write};

fn create_file(path: &str) -> Option<File> {
Expand All @@ -24,8 +25,8 @@ pub fn walkdir(dir: &Path) -> impl Iterator<Item = PathBuf> {
paths.into_iter()
}

fn open_file(path: &str) -> Option<File> {
File::open(path).ok()
fn open_file(path: &str) -> Result<File> {
File::open(path)
}
pub trait Encoder {
const EXTENSION: &'static str;
Expand All @@ -49,9 +50,9 @@ pub trait Encoder {
format!("world/{}.{}", name, Self::EXTENSION)
}

fn load_reader(name: &str) -> Option<BufReader<File>> {
fn load_reader(name: &str) -> Result<BufReader<File>> {
let file = open_file(&Self::filename(name))?;
Some(BufReader::new(file))
Ok(BufReader::new(file))
}

fn save(x: &impl Serialize, name: &str) -> Option<()> {
Expand All @@ -73,14 +74,18 @@ pub trait Encoder {
Some(())
}

fn load<T: DeserializeOwned>(name: &str) -> Option<T> {
fn load<T: DeserializeOwned>(name: &str) -> Result<T> {
Self::decode_reader(Self::load_reader(name)?)
.map_err(|err| log::error!("failed deserializing {}: {}", name, err))
.map_err(|err| {
io::Error::new(
ErrorKind::Other,
format!("failed deserializing {}: {}", name, err),
)
})
.map(|x| {
log::info!("successfully loaded {}", name);
x
})
.ok()
}
}

Expand Down Expand Up @@ -181,10 +186,8 @@ impl Encoder for JSONPretty {
}
}

pub fn load_raw(
p: impl AsRef<Path>,
) -> std::result::Result<Vec<u8>, Box<dyn std::error::Error + 'static>> {
std::fs::read(p).map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
pub fn load_raw(p: impl AsRef<Path>) -> Result<Vec<u8>> {
std::fs::read(p)
}

pub fn load_string(
Expand Down
2 changes: 1 addition & 1 deletion egregoria/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pathfinding = "4.2.1"
serde-big-array = "0.5.0"
lazy_static = "1.4.0"
arc-swap = "1.3.0"
derive_more = "0.99.17"
derive_more = { workspace = true }

[dev-dependencies]
easybench = "1.1.0"
Expand Down
4 changes: 2 additions & 2 deletions egregoria/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,12 +285,12 @@ impl Egregoria {

pub fn load_replay_from_disk(save_name: &str) -> Option<Replay> {
let path = format!("{save_name}_replay");
let replay: Replay = common::saveload::JSON::load(&path)?;
let replay: Replay = common::saveload::JSON::load(&path).ok()?;
Some(replay)
}

pub fn load_from_disk(save_name: &str) -> Option<Self> {
let goria: Egregoria = common::saveload::CompressedBincode::load(save_name)?;
let goria: Egregoria = common::saveload::CompressedBincode::load(save_name).ok()?;
Some(goria)
}

Expand Down
42 changes: 1 addition & 41 deletions egregoria/src/souls/goods_company.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::utils::time::GameTime;
use crate::world::{CompanyEnt, HumanEnt, HumanID, VehicleID};
use crate::World;
use crate::{Egregoria, ParCommandBuffer, SoulID};
use common::descriptions::{GoodsCompanyDescriptionJSON, ZoneDescription};
use common::saveload::Encoder;
use egui_inspect::Inspect;
use geom::{Transform, Vec2};
Expand Down Expand Up @@ -48,52 +49,11 @@ pub struct GoodsCompanyDescription {
pub zone: Option<Box<ZoneDescription>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ZoneDescription {
pub floor: String,
pub filler: String,
/// The price for each "production unit"
pub price_per_area: i64,
/// Wether the zone filler positions should be randomized
#[serde(default)]
pub randomize_filler: bool,
}

#[derive(Default)]
pub struct GoodsCompanyRegistry {
pub descriptions: SlotMap<GoodsCompanyID, GoodsCompanyDescription>,
}

#[derive(Serialize, Deserialize)]
struct RecipeDescription {
pub consumption: Vec<(String, i32)>,
pub production: Vec<(String, i32)>,
pub complexity: i32,
pub storage_multiplier: i32,
}

#[derive(Serialize, Deserialize)]
struct BuildingGenDescription {
pub kind: String,
pub vertical_factor: Option<f32>,
pub door_pos: Option<Vec2>,
}

#[derive(Serialize, Deserialize)]
struct GoodsCompanyDescriptionJSON {
pub name: String,
pub bgen: BuildingGenDescription,
pub kind: String,
pub recipe: RecipeDescription,
pub n_workers: i32,
pub n_trucks: Option<u32>,
pub size: f32,
pub asset_location: String,
pub price: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub zone: Option<Box<ZoneDescription>>,
}

impl GoodsCompanyRegistry {
pub fn load(&mut self, source: &str, registry: &ItemRegistry) {
let descriptions: Vec<GoodsCompanyDescriptionJSON> =
Expand Down
15 changes: 6 additions & 9 deletions engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ edition = "2021"
geom = { path = "../geom" }
common = { path = "../common" }
ordered-float = { workspace = true }
egui-winit = { workspace = true, default-features = false }
egui = { workspace = true }
winit = { workspace = true }
oddio = { workspace = true }
derive_more = { workspace = true }
wgpu = { version = "0.16.0", default-features = false, features=["wgsl"] }
bytemuck = "1.7.2"
image = { version = "0.24.3", default-features = false, features = ["png"] }
Expand All @@ -24,14 +29,6 @@ slotmapd = "1.0"
smallvec = "1.10.0"
inline_tweak = "1.0.8"
egui-wgpu = { version = "0.22.0" }
egui-winit = { workspace = true, default-features = false }
egui = { workspace = true }
winit = { workspace = true }
oddio = { workspace = true }
cpal = "0.15.0"
lewton = "0.10.2"
serde = { version = "1.0.183", features = ["derive"] }

[target.'cfg(target_arch = "wasm32")'.dependencies.wgpu]
version = "0.16.0"
features = ["webgl"]
serde = { version = "1.0.183", features = ["derive"] }
15 changes: 10 additions & 5 deletions engine/src/gfx.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::pbr::PBR;
use crate::{
bg_layout_litmesh, CompiledModule, Drawable, IndexType, LampLights, Material, MaterialID,
MaterialMap, PipelineBuilder, Pipelines, Texture, TextureBuilder, Uniform, UvVertex, TL,
MaterialMap, PipelineBuilder, Pipelines, Texture, TextureBuildError, TextureBuilder, Uniform,
UvVertex, TL,
};
use common::FastMap;
use geom::{vec2, LinearColor, Matrix4, Vec2, Vec3};
Expand Down Expand Up @@ -348,13 +349,17 @@ impl GfxContext {
&mut self,
path: impl Into<PathBuf>,
label: &'static str,
) -> Option<Arc<Texture>> {
) -> Result<Arc<Texture>, TextureBuildError> {
self.texture_inner(path.into(), label)
}

fn texture_inner(&mut self, p: PathBuf, label: &'static str) -> Option<Arc<Texture>> {
fn texture_inner(
&mut self,
p: PathBuf,
label: &'static str,
) -> Result<Arc<Texture>, TextureBuildError> {
if let Some(tex) = self.texture_cache_paths.get(&p) {
return Some(tex.clone());
return Ok(tex.clone());
}

let tex = Arc::new(
Expand All @@ -364,7 +369,7 @@ impl GfxContext {
.build(&self.device, &self.queue),
);
self.texture_cache_paths.insert(p, tex.clone());
Some(tex)
Ok(tex)
}

pub fn read_texture(&self, path: impl Into<PathBuf>) -> Option<&Arc<Texture>> {
Expand Down
Loading

0 comments on commit 005a1fe

Please sign in to comment.