tile manager

This commit is contained in:
2024-04-09 21:06:45 -04:00
parent 5dc4cdb5d4
commit 27193adf15
11 changed files with 137 additions and 58 deletions

2
.vscode/launch.json vendored
View File

@@ -13,7 +13,7 @@
"program": "${workspaceRoot}/target/debug/phos.exe", "program": "${workspaceRoot}/target/debug/phos.exe",
"args": [], "args": [],
"cwd": "${workspaceRoot}", "cwd": "${workspaceRoot}",
"preLaunchTask": "Build", "preLaunchTask": "Build"
} }
] ]
} }

View File

@@ -1,3 +1,6 @@
{ {
"cmake.configureOnOpen": false "cmake.configureOnOpen": false,
"rust-analyzer.linkedProjects": [
"Cargo.toml",
]
} }

6
.vscode/tasks.json vendored
View File

@@ -3,10 +3,8 @@
"tasks": [ "tasks": [
{ {
"type": "cargo", "type": "cargo",
"command": "", "command": "build",
"args": [ "args": [],
"build"
],
"problemMatcher": [ "problemMatcher": [
"$rustc" "$rustc"
], ],

6
Cargo.lock generated
View File

@@ -3292,9 +3292,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.114" version = "1.0.115"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd"
dependencies = [ dependencies = [
"itoa", "itoa",
"ryu", "ryu",
@@ -4295,6 +4295,8 @@ version = "0.1.0"
dependencies = [ dependencies = [
"bevy", "bevy",
"noise 0.9.0", "noise 0.9.0",
"serde",
"serde_json",
] ]
[[package]] [[package]]

View File

@@ -8,3 +8,5 @@ edition = "2021"
[dependencies] [dependencies]
bevy = "0.13.1" bevy = "0.13.1"
noise = "0.9.0" noise = "0.9.0"
serde = {version="1.0.197", features=["derive"]}
serde_json = "1.0.115"

View File

@@ -69,3 +69,4 @@ pub mod prelude {
pub mod heightmap; pub mod heightmap;
pub mod hex_utils; pub mod hex_utils;
pub mod mesh_generator; pub mod mesh_generator;
pub mod tile_manager;

View File

@@ -11,8 +11,6 @@ use bevy::{
}, },
}; };
use std::vec::Vec; use std::vec::Vec;
use bevy::render::mesh::MeshVertexAttribute;
use bevy::render::render_resource::VertexFormat;
const HEX_CORNERS: [Vec3; 6] = [ const HEX_CORNERS: [Vec3; 6] = [
Vec3::new(0., 0., OUTER_RADIUS), Vec3::new(0., 0., OUTER_RADIUS),
@@ -23,7 +21,6 @@ const HEX_CORNERS: [Vec3; 6] = [
Vec3::new(-INNER_RADIUS, 0., 0.5 * OUTER_RADIUS), Vec3::new(-INNER_RADIUS, 0., 0.5 * OUTER_RADIUS),
]; ];
pub fn generate_chunk_mesh(chunk: &Chunk, map: &Map) -> Mesh { pub fn generate_chunk_mesh(chunk: &Chunk, map: &Map) -> Mesh {
let vertex_count: usize = Chunk::SIZE * Chunk::SIZE * 6; let vertex_count: usize = Chunk::SIZE * Chunk::SIZE * 6;
let mut verts = Vec::with_capacity(vertex_count); let mut verts = Vec::with_capacity(vertex_count);

View File

@@ -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<u32, TileDefination>,
}
#[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<Self> {
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<TileDefination, serde_json::Error> =
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);
}
}

View File

@@ -2,6 +2,7 @@
name = "phos" name = "phos"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
build = "build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

48
game/main/build.rs Normal file
View File

@@ -0,0 +1,48 @@
use std::{
env, fs,
path::{Path, PathBuf},
};
/// A helper function for recursively copying a directory.
fn copy_dir<P, Q>(from: P, to: Q)
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
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);
}

View File

@@ -1,19 +1,20 @@
use crate::prelude::*;
use bevy::asset::LoadState; use bevy::asset::LoadState;
use bevy::pbr::{ExtendedMaterial}; use bevy::pbr::ExtendedMaterial;
use bevy::{pbr::CascadeShadowConfig, prelude::*}; use bevy::{pbr::CascadeShadowConfig, prelude::*};
use camera_system::PhosCameraPlugin; use camera_system::PhosCameraPlugin;
use iyes_perf_ui::prelude::*; 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::{ use world_generation::{
heightmap::generate_heightmap, mesh_generator::generate_chunk_mesh, prelude::*, heightmap::generate_heightmap, mesh_generator::generate_chunk_mesh, prelude::*,
}; };
use crate::prelude::*;
pub struct PhosGamePlugin; pub struct PhosGamePlugin;
impl Plugin for PhosGamePlugin { impl Plugin for PhosGamePlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_plugins(PhosCameraPlugin).add_plugins(MaterialPlugin::< app.add_plugins(PhosCameraPlugin)
.add_plugins(MaterialPlugin::<
ExtendedMaterial<StandardMaterial, ChunkMaterial>, ExtendedMaterial<StandardMaterial, ChunkMaterial>,
>::default()); >::default());
app.add_systems(Startup, init_game) app.add_systems(Startup, init_game)
@@ -51,10 +52,7 @@ fn init_game(mut commands: Commands) {
commands.insert_resource(PhosMap::default()); commands.insert_resource(PhosMap::default());
} }
fn load_textures( fn load_textures(mut commands: Commands, asset_server: Res<AssetServer>) {
mut commands: Commands,
asset_server: Res<AssetServer>,
) {
let main_tex = asset_server.load("textures/world/stack.png"); let main_tex = asset_server.load("textures/world/stack.png");
commands.insert_resource(ChunkAtlas { commands.insert_resource(ChunkAtlas {
handle: main_tex.clone(), handle: main_tex.clone(),
@@ -80,42 +78,11 @@ fn check_texture(
let array_layers = 7; let array_layers = 7;
image.reinterpret_stacked_2d_as_array(array_layers); image.reinterpret_stacked_2d_as_array(array_layers);
atlas.is_loaded = true; atlas.is_loaded = true;
map.ready = true; map.ready = true;
map.regenerate = true; map.regenerate = true;
} }
fn draw_gizmos(mut gizmos: Gizmos, hm: Res<Map>) {
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) { fn create_map(mut commands: Commands) {
let heightmap = generate_heightmap( let heightmap = generate_heightmap(
&GenerationConfig { &GenerationConfig {
@@ -216,4 +183,3 @@ fn spawn_map(
)); ));
} }
} }