From 27193adf1565485c575eef2c1ecfab712c87a3d6 Mon Sep 17 00:00:00 2001 From: Amatsugu Date: Tue, 9 Apr 2024 21:06:45 -0400 Subject: [PATCH] tile manager --- .vscode/launch.json | 2 +- .vscode/settings.json | 5 +- .vscode/tasks.json | 6 +- Cargo.lock | 6 +- engine/world_generation/Cargo.toml | 2 + engine/world_generation/src/lib.rs | 1 + engine/world_generation/src/mesh_generator.rs | 13 ++-- engine/world_generation/src/tile_manager.rs | 61 +++++++++++++++++++ game/main/Cargo.toml | 1 + game/main/build.rs | 48 +++++++++++++++ game/main/src/phos.rs | 50 +++------------ 11 files changed, 137 insertions(+), 58 deletions(-) create mode 100644 engine/world_generation/src/tile_manager.rs create mode 100644 game/main/build.rs diff --git a/.vscode/launch.json b/.vscode/launch.json index 9a56cd6..c72d3ea 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -13,7 +13,7 @@ "program": "${workspaceRoot}/target/debug/phos.exe", "args": [], "cwd": "${workspaceRoot}", - "preLaunchTask": "Build", + "preLaunchTask": "Build" } ] } \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index cd7798d..c0ef69c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,6 @@ { - "cmake.configureOnOpen": false + "cmake.configureOnOpen": false, + "rust-analyzer.linkedProjects": [ + "Cargo.toml", + ] } \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index e4f59a0..7c0718d 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -3,10 +3,8 @@ "tasks": [ { "type": "cargo", - "command": "", - "args": [ - "build" - ], + "command": "build", + "args": [], "problemMatcher": [ "$rustc" ], diff --git a/Cargo.lock b/Cargo.lock index 6342dc6..78cb9a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3292,9 +3292,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.114" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" +checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd" dependencies = [ "itoa", "ryu", @@ -4295,6 +4295,8 @@ version = "0.1.0" dependencies = [ "bevy", "noise 0.9.0", + "serde", + "serde_json", ] [[package]] diff --git a/engine/world_generation/Cargo.toml b/engine/world_generation/Cargo.toml index 1356c84..5a6b6c2 100644 --- a/engine/world_generation/Cargo.toml +++ b/engine/world_generation/Cargo.toml @@ -8,3 +8,5 @@ edition = "2021" [dependencies] bevy = "0.13.1" noise = "0.9.0" +serde = {version="1.0.197", features=["derive"]} +serde_json = "1.0.115" diff --git a/engine/world_generation/src/lib.rs b/engine/world_generation/src/lib.rs index b1b0bc7..e7854be 100644 --- a/engine/world_generation/src/lib.rs +++ b/engine/world_generation/src/lib.rs @@ -69,3 +69,4 @@ pub mod prelude { pub mod heightmap; pub mod hex_utils; pub mod mesh_generator; +pub mod tile_manager; diff --git a/engine/world_generation/src/mesh_generator.rs b/engine/world_generation/src/mesh_generator.rs index ca63f9e..3d912d2 100644 --- a/engine/world_generation/src/mesh_generator.rs +++ b/engine/world_generation/src/mesh_generator.rs @@ -11,8 +11,6 @@ use bevy::{ }, }; use std::vec::Vec; -use bevy::render::mesh::MeshVertexAttribute; -use bevy::render::render_resource::VertexFormat; const HEX_CORNERS: [Vec3; 6] = [ Vec3::new(0., 0., OUTER_RADIUS), @@ -23,7 +21,6 @@ const HEX_CORNERS: [Vec3; 6] = [ Vec3::new(-INNER_RADIUS, 0., 0.5 * OUTER_RADIUS), ]; - pub fn generate_chunk_mesh(chunk: &Chunk, map: &Map) -> Mesh { let vertex_count: usize = Chunk::SIZE * Chunk::SIZE * 6; let mut verts = Vec::with_capacity(vertex_count); @@ -55,11 +52,11 @@ pub fn generate_chunk_mesh(chunk: &Chunk, map: &Map) -> Mesh { PrimitiveTopology::TriangleList, RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD, ) - .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, verts) - .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs) - .with_inserted_indices(Indices::U32(indices)) - .with_duplicated_vertices() - .with_computed_flat_normals(); + .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, verts) + .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs) + .with_inserted_indices(Indices::U32(indices)) + .with_duplicated_vertices() + .with_computed_flat_normals(); return mesh; } diff --git a/engine/world_generation/src/tile_manager.rs b/engine/world_generation/src/tile_manager.rs new file mode 100644 index 0000000..7c44db2 --- /dev/null +++ b/engine/world_generation/src/tile_manager.rs @@ -0,0 +1,61 @@ +use std::{collections::HashMap, fs}; + +use bevy::ecs::system::Resource; +use serde::{Deserialize, Serialize}; + +#[derive(Resource)] +pub struct TileManager { + pub tiles: HashMap, +} + +#[derive(Serialize, Deserialize, Debug)] +pub struct TileDefination { + pub id: u32, + pub texture_id: u32, + pub side_texture_id: u32, +} + +impl TileManager { + pub fn new(path: String) -> Option { + let mut cur_id: u32 = 0; + + let paths = fs::read_dir(path); + + if paths.is_err() { + print!("{}", paths.err().unwrap()); + return None; + } + + let mut manager = TileManager { + tiles: HashMap::new(), + }; + + for dir_entry in paths.unwrap() { + let cur_path = dir_entry.unwrap().path(); + if !cur_path.is_file() { + continue; + } + let data = fs::read_to_string(cur_path); + if data.is_err() { + print!("{}", data.err().unwrap()); + return None; + } + + let result: Result = + serde_json::from_str(data.unwrap().as_str()); + + if result.is_err() { + print!("{}", result.err().unwrap()); + return None; + } + + let mut tile = result.unwrap(); + tile.id = cur_id; + + manager.tiles.insert(tile.id, tile); + cur_id += 1; + } + + return Some(manager); + } +} diff --git a/game/main/Cargo.toml b/game/main/Cargo.toml index 39bce16..2dfd25e 100644 --- a/game/main/Cargo.toml +++ b/game/main/Cargo.toml @@ -2,6 +2,7 @@ name = "phos" version = "0.1.0" edition = "2021" +build = "build.rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/game/main/build.rs b/game/main/build.rs new file mode 100644 index 0000000..359d7f2 --- /dev/null +++ b/game/main/build.rs @@ -0,0 +1,48 @@ +use std::{ + env, fs, + path::{Path, PathBuf}, +}; + +/// A helper function for recursively copying a directory. +fn copy_dir(from: P, to: Q) +where + P: AsRef, + Q: AsRef, +{ + let to = to.as_ref().to_path_buf(); + + for path in fs::read_dir(from).unwrap() { + let path = path.unwrap().path(); + let to = to.clone().join(path.file_name().unwrap()); + + if path.is_file() { + fs::copy(&path, to).unwrap(); + } else if path.is_dir() { + if !to.exists() { + fs::create_dir(&to).unwrap(); + } + + copy_dir(&path, to); + } else { /* Skip other content */ + } + } +} + +const COPY_DIR: &'static str = "assets"; + +fn main() { + // Request the output directory + let out = env::var("PROFILE").unwrap(); + let out = PathBuf::from(format!("../../target/{}/{}", out, COPY_DIR)); + + // If it is already in the output directory, delete it and start over + if out.exists() { + fs::remove_dir_all(&out).unwrap(); + } + + // Create the out directory + fs::create_dir(&out).unwrap(); + + // Copy the directory + copy_dir(COPY_DIR, &out); +} diff --git a/game/main/src/phos.rs b/game/main/src/phos.rs index 89fa2d6..4bbe45e 100644 --- a/game/main/src/phos.rs +++ b/game/main/src/phos.rs @@ -1,21 +1,22 @@ +use crate::prelude::*; use bevy::asset::LoadState; -use bevy::pbr::{ExtendedMaterial}; +use bevy::pbr::ExtendedMaterial; use bevy::{pbr::CascadeShadowConfig, prelude::*}; use camera_system::PhosCameraPlugin; use iyes_perf_ui::prelude::*; -use world_generation::hex_utils::{offset_to_world, HexCoord}; +use world_generation::hex_utils::offset_to_world; use world_generation::{ heightmap::generate_heightmap, mesh_generator::generate_chunk_mesh, prelude::*, }; -use crate::prelude::*; pub struct PhosGamePlugin; impl Plugin for PhosGamePlugin { fn build(&self, app: &mut App) { - app.add_plugins(PhosCameraPlugin).add_plugins(MaterialPlugin::< - ExtendedMaterial, - >::default()); + app.add_plugins(PhosCameraPlugin) + .add_plugins(MaterialPlugin::< + ExtendedMaterial, + >::default()); app.add_systems(Startup, init_game) .add_systems(Startup, (load_textures, create_map).chain()); app.add_systems(Update, (check_texture, spawn_map)); @@ -51,10 +52,7 @@ fn init_game(mut commands: Commands) { commands.insert_resource(PhosMap::default()); } -fn load_textures( - mut commands: Commands, - asset_server: Res, -) { +fn load_textures(mut commands: Commands, asset_server: Res) { let main_tex = asset_server.load("textures/world/stack.png"); commands.insert_resource(ChunkAtlas { handle: main_tex.clone(), @@ -80,42 +78,11 @@ fn check_texture( let array_layers = 7; image.reinterpret_stacked_2d_as_array(array_layers); - atlas.is_loaded = true; map.ready = true; map.regenerate = true; } -fn draw_gizmos(mut gizmos: Gizmos, hm: Res) { - gizmos.arrow(Vec3::ZERO, Vec3::Y * 1.5, Color::GREEN); - gizmos.arrow(Vec3::ZERO, Vec3::Z * 1.5, Color::BLUE); - gizmos.arrow(Vec3::ZERO, Vec3::X * 1.5, Color::RED); - - let coord = HexCoord::from_grid_pos(64, 14); - let ch = &hm.chunks[coord.to_chunk_index(hm.width) as usize]; - let h = ch.points[coord.to_chunk_local_index() as usize]; - gizmos.ray(coord.to_world(h), Vec3::Y, Color::RED); - gizmos.ray(coord.to_world(h), Vec3::Z * 1.5, Color::BLUE); - - // let t = coord.get_neighbor(5); - // let h = ch.points[t.to_chunk_local_index() as usize]; - // gizmos.ray(t.to_world(h), Vec3::Y * 1., Color::PINK); - let n = coord.get_neighbors(); - let nh = hm.get_neighbors(&coord); - for i in 0..6 { - let t = n[i]; - let h = nh[i]; - if h.is_none() { - continue; - } - gizmos.ray( - t.to_world(h.unwrap()), - Vec3::Y * (i + 1) as f32, - Color::CYAN, - ); - } -} - fn create_map(mut commands: Commands) { let heightmap = generate_heightmap( &GenerationConfig { @@ -216,4 +183,3 @@ fn spawn_map( )); } } -