70 lines
1.9 KiB
Rust
70 lines
1.9 KiB
Rust
use std::collections::HashMap;
|
|
use std::{
|
|
fs,
|
|
path::{Path, PathBuf},
|
|
};
|
|
|
|
use bevy::prelude::*;
|
|
use json::JsonValue;
|
|
|
|
use crate::{json::*, pokemon::*};
|
|
|
|
pub struct DatabasePlugin;
|
|
|
|
impl Plugin for DatabasePlugin {
|
|
fn build(&self, app: &mut App) {
|
|
app.insert_resource(Database::<Pokemon>::default())
|
|
.insert_resource(Database::<Nature>::default())
|
|
.insert_resource(Database::<Characteristic>::default())
|
|
.insert_resource(Database::<Ability>::default())
|
|
.add_startup_system(database_setup);
|
|
}
|
|
}
|
|
|
|
#[derive(Resource, Default)]
|
|
pub struct Database<T> {
|
|
pub map: HashMap<String, T>,
|
|
}
|
|
|
|
impl<T> Database<T>
|
|
where
|
|
T: FromJson + GetKey,
|
|
{
|
|
fn populate_from_json(&mut self, json: &JsonValue) {
|
|
for item in json.members() {
|
|
if let Some(item) = T::from_json(item) {
|
|
let key = item.key();
|
|
if !self.map.contains_key(&key) {
|
|
self.map.insert(key, item);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn database_setup(
|
|
mut pokemon_database: ResMut<Database<Pokemon>>,
|
|
mut ability_database: ResMut<Database<Ability>>,
|
|
mut nature_database: ResMut<Database<Nature>>,
|
|
mut characteristic_database: ResMut<Database<Characteristic>>,
|
|
) {
|
|
ability_database.populate_from_json(&read_abilities());
|
|
nature_database.populate_from_json(&read_natures());
|
|
pokemon_database.populate_from_json(&read_pokedex());
|
|
characteristic_database.populate_from_json(&read_characteristics());
|
|
}
|
|
|
|
pub fn load_url_asset(
|
|
url: String,
|
|
path: PathBuf,
|
|
assets: &Res<AssetServer>,
|
|
) -> Result<Handle<Image>, Box<dyn std::error::Error>> {
|
|
let system_path = Path::new("assets").join(&path);
|
|
if Path::exists(&system_path) {
|
|
return Ok(assets.load(path));
|
|
}
|
|
let data = reqwest::blocking::get(&url)?.bytes()?;
|
|
fs::write(&system_path, data).unwrap();
|
|
Ok(assets.load(path))
|
|
}
|