cleanup
Some checks failed
Rust / build (push) Failing after 4s

This commit is contained in:
2026-03-13 18:02:11 -04:00
parent e3ddd3b5d4
commit b567dd00fd
24 changed files with 456 additions and 299 deletions

View File

@@ -1,5 +1,3 @@
use bevy::{asset::AssetLoader, reflect::TypePath};
#[macro_export] #[macro_export]
macro_rules! create_asset_loader { macro_rules! create_asset_loader {
( (

View File

@@ -1,6 +1,6 @@
use std::ops::Add; use std::ops::Add;
use bevy::{asset::AssetLoader, math::VectorSpace, prelude::*}; use bevy::{math::VectorSpace, prelude::*};
use image::ImageBuffer; use image::ImageBuffer;
use rayon::prelude::*; use rayon::prelude::*;
@@ -13,7 +13,8 @@ pub fn render_image(
data: &Vec<f32>, data: &Vec<f32>,
color1: LinearRgba, color1: LinearRgba,
color2: LinearRgba, color2: LinearRgba,
) -> ImageBuffer<image::Rgba<u8>, Vec<u8>> { ) -> ImageBuffer<image::Rgba<u8>, Vec<u8>>
{
let mut image = ImageBuffer::new(size.x * Chunk::SIZE as u32, size.y * Chunk::SIZE as u32); let mut image = ImageBuffer::new(size.x * Chunk::SIZE as u32, size.y * Chunk::SIZE as u32);
update_image(size, data, color1, color2, &mut image); update_image(size, data, color1, color2, &mut image);
@@ -26,7 +27,8 @@ pub fn update_image(
color1: LinearRgba, color1: LinearRgba,
color2: LinearRgba, color2: LinearRgba,
image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>,
) { )
{
let min = *data.iter().min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or(&0.0); let min = *data.iter().min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or(&0.0);
let max = *data.iter().min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or(&1.0); let max = *data.iter().min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or(&1.0);
@@ -41,7 +43,8 @@ pub fn update_image(
}); });
} }
fn to_pixel(col: &LinearRgba) -> image::Rgba<u8> { fn to_pixel(col: &LinearRgba) -> image::Rgba<u8>
{
return image::Rgba([ return image::Rgba([
(col.red * 255.0) as u8, (col.red * 255.0) as u8,
(col.green * 255.0) as u8, (col.green * 255.0) as u8,
@@ -49,7 +52,8 @@ fn to_pixel(col: &LinearRgba) -> image::Rgba<u8> {
255, 255,
]); ]);
} }
pub fn render_map(map: &Map, smooth: f32) -> ImageBuffer<image::Rgba<u8>, Vec<u8>> { pub fn render_map(map: &Map, smooth: f32) -> ImageBuffer<image::Rgba<u8>, Vec<u8>>
{
let mut image = ImageBuffer::new( let mut image = ImageBuffer::new(
map.width as u32 * Chunk::SIZE as u32, map.width as u32 * Chunk::SIZE as u32,
map.height as u32 * Chunk::SIZE as u32, map.height as u32 * Chunk::SIZE as u32,
@@ -57,18 +61,21 @@ pub fn render_map(map: &Map, smooth: f32) -> ImageBuffer<image::Rgba<u8>, Vec<u8
update_map(map, smooth, &mut image); update_map(map, smooth, &mut image);
return image; return image;
} }
pub fn update_map(map: &Map, smooth: f32, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>) { pub fn update_map(map: &Map, smooth: f32, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>)
{
image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| { image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| {
let coord = HexCoord::from_grid_pos(x as usize, y as usize); let coord = HexCoord::from_grid_pos(x as usize, y as usize);
let right = coord.get_neighbor(1); let right = coord.get_neighbor(1);
let height = map.sample_height(&coord); let height = map.sample_height(&coord);
let mut color = Hsla::hsl(138.0, 1.0, 0.4); let mut color = Hsla::hsl(138.0, 1.0, 0.4);
if height < map.sealevel { if height < map.sealevel
{
color.hue = 217.0; color.hue = 217.0;
} }
if map.is_in_bounds(&right) { if map.is_in_bounds(&right)
{
let h2 = map.sample_height(&right); let h2 = map.sample_height(&right);
color = get_height_color_blend(color, height, h2, smooth); color = get_height_color_blend(color, height, h2, smooth);
} }
@@ -77,22 +84,33 @@ pub fn update_map(map: &Map, smooth: f32, image: &mut ImageBuffer<image::Rgba<u8
}); });
} }
fn get_height_color_blend(base_color: Hsla, height: f32, height2: f32, smooth: f32) -> Hsla { fn get_height_color_blend(base_color: Hsla, height: f32, height2: f32, smooth: f32) -> Hsla
{
let mut color = base_color; let mut color = base_color;
let mut d = height2 - height; let mut d = height2 - height;
if smooth == 0.0 || d.abs() > smooth { if smooth == 0.0 || d.abs() > smooth
if d > 0.0 { {
if d > 0.0
{
color.lightness += 0.1; color.lightness += 0.1;
} else if d < 0.0 { }
else if d < 0.0
{
color.lightness -= 0.1; color.lightness -= 0.1;
} }
} else { }
if d.abs() <= smooth { else
{
if d.abs() <= smooth
{
d /= smooth; d /= smooth;
if d > 0.0 { if d > 0.0
{
let c2: LinearRgba = color.with_lightness(color.lightness + 0.1).into(); let c2: LinearRgba = color.with_lightness(color.lightness + 0.1).into();
color = LinearRgba::lerp(color.into(), c2, d).into(); color = LinearRgba::lerp(color.into(), c2, d).into();
} else { }
else
{
let c2: LinearRgba = color.with_lightness(color.lightness - 0.1).into(); let c2: LinearRgba = color.with_lightness(color.lightness - 0.1).into();
color = LinearRgba::lerp(color.into(), c2, d.abs()).into(); color = LinearRgba::lerp(color.into(), c2, d.abs()).into();
} }
@@ -102,13 +120,15 @@ fn get_height_color_blend(base_color: Hsla, height: f32, height2: f32, smooth: f
return color; return color;
} }
pub fn render_biome_noise_map(map: &BiomeMap, multi: Vec3) -> ImageBuffer<image::Rgba<u8>, Vec<u8>> { pub fn render_biome_noise_map(map: &BiomeMap, multi: Vec3) -> ImageBuffer<image::Rgba<u8>, Vec<u8>>
{
let mut image = ImageBuffer::new(map.width as u32, map.height as u32); let mut image = ImageBuffer::new(map.width as u32, map.height as u32);
update_biome_noise_map(map, multi, &mut image); update_biome_noise_map(map, multi, &mut image);
return image; return image;
} }
pub fn update_biome_noise_map(map: &BiomeMap, multi: Vec3, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>) { pub fn update_biome_noise_map(map: &BiomeMap, multi: Vec3, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>)
{
image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| { image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| {
let tile = map.get_biome_data(x as usize, y as usize); let tile = map.get_biome_data(x as usize, y as usize);
@@ -121,7 +141,8 @@ pub fn update_biome_noise_map(map: &BiomeMap, multi: Vec3, image: &mut ImageBuff
}); });
} }
pub fn render_biome_map(map: &Map, biome_map: &BiomeMap) -> ImageBuffer<image::Rgba<u8>, Vec<u8>> { pub fn render_biome_map(map: &Map, biome_map: &BiomeMap) -> ImageBuffer<image::Rgba<u8>, Vec<u8>>
{
let mut image = ImageBuffer::new( let mut image = ImageBuffer::new(
map.width as u32 * Chunk::SIZE as u32, map.width as u32 * Chunk::SIZE as u32,
map.height as u32 * Chunk::SIZE as u32, map.height as u32 * Chunk::SIZE as u32,
@@ -130,19 +151,22 @@ pub fn render_biome_map(map: &Map, biome_map: &BiomeMap) -> ImageBuffer<image::R
return image; return image;
} }
pub fn update_biome_map(map: &Map, biome_map: &BiomeMap, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>) { pub fn update_biome_map(map: &Map, biome_map: &BiomeMap, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>)
{
let map_biome_count = map.biome_count as f32; let map_biome_count = map.biome_count as f32;
image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| { image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| {
let coord = HexCoord::from_grid_pos(x as usize, y as usize); let coord = HexCoord::from_grid_pos(x as usize, y as usize);
let biome_blend = biome_map.get_biome(x as i32, y as i32).unwrap(); let biome_blend = biome_map.get_biome(x as i32, y as i32).unwrap();
let right = coord.get_neighbor(1); let right = coord.get_neighbor(1);
let mut color = Oklaba::BLACK; let mut color = Oklaba::BLACK;
for i in 0..biome_blend.len() { for i in 0..biome_blend.len()
{
let mut c: Oklaba = Hsla::hsl((i as f32 / map_biome_count) * 360.0, 0.8, 0.7).into(); let mut c: Oklaba = Hsla::hsl((i as f32 / map_biome_count) * 360.0, 0.8, 0.7).into();
c *= biome_blend[i]; c *= biome_blend[i];
color = Oklaba::add(c, color.into()).into(); color = Oklaba::add(c, color.into()).into();
} }
if map.is_in_bounds(&right) { if map.is_in_bounds(&right)
{
let h1 = map.sample_height(&coord); let h1 = map.sample_height(&coord);
let h2 = map.sample_height(&right); let h2 = map.sample_height(&right);
color = get_height_color_blend(color.into(), h1, h2, 0.5).into(); color = get_height_color_blend(color.into(), h1, h2, 0.5).into();

View File

@@ -6,7 +6,8 @@ use crate::hex_utils::HexCoord;
use super::chunk::Chunk; use super::chunk::Chunk;
pub struct MeshChunkData { pub struct MeshChunkData
{
pub heights: [f32; Chunk::AREA], pub heights: [f32; Chunk::AREA],
pub textures: [[u32; 2]; Chunk::AREA], pub textures: [[u32; 2]; Chunk::AREA],
pub min_height: f32, pub min_height: f32,
@@ -14,13 +15,17 @@ pub struct MeshChunkData {
pub distance_to_land: [f32; Chunk::AREA], pub distance_to_land: [f32; Chunk::AREA],
} }
impl MeshChunkData { impl MeshChunkData
pub fn get_neighbors(&self, coord: &HexCoord) -> [f32; 6] { {
pub fn get_neighbors(&self, coord: &HexCoord) -> [f32; 6]
{
let mut data = [self.min_height; 6]; let mut data = [self.min_height; 6];
let n_tiles = coord.get_neighbors(); let n_tiles = coord.get_neighbors();
for i in 0..6 { for i in 0..6
{
let n = n_tiles[i]; let n = n_tiles[i];
if !n.is_in_bounds(Chunk::SIZE, Chunk::SIZE) { if !n.is_in_bounds(Chunk::SIZE, Chunk::SIZE)
{
continue; continue;
} }
data[i] = self.heights[n.to_index(Chunk::SIZE)]; data[i] = self.heights[n.to_index(Chunk::SIZE)];
@@ -29,56 +34,70 @@ impl MeshChunkData {
return data; return data;
} }
pub fn get_neighbors_with_water_info(&self, coord: &HexCoord) -> ([(f32, Option<f32>); 6], bool) { pub fn get_neighbors_with_water_info(&self, coord: &HexCoord) -> ([(f32, Option<f32>); 6], bool)
{
let mut has_land = false; let mut has_land = false;
let mut data = [(self.min_height, None); 6]; let mut data = [(self.min_height, None); 6];
let n_tiles = coord.get_neighbors(); let n_tiles = coord.get_neighbors();
for i in 0..6 { for i in 0..6
{
let n = n_tiles[i]; let n = n_tiles[i];
if !n.is_in_bounds(Chunk::SIZE, Chunk::SIZE) { if !n.is_in_bounds(Chunk::SIZE, Chunk::SIZE)
{
continue; continue;
} }
let idx = n.to_index(Chunk::SIZE); let idx = n.to_index(Chunk::SIZE);
data[i] = (self.heights[idx], Some(self.distance_to_land[idx])); data[i] = (self.heights[idx], Some(self.distance_to_land[idx]));
if data[i].0 > self.sealevel { if data[i].0 > self.sealevel
{
has_land = true; has_land = true;
} }
} }
return (data, has_land); return (data, has_land);
} }
pub fn caluclate_water_distances(data: &mut Vec<MeshChunkData>, height: usize, width: usize, range: usize) { pub fn caluclate_water_distances(data: &mut Vec<MeshChunkData>, height: usize, width: usize, _range: usize)
{
let mut open: VecDeque<(HexCoord, f32, usize)> = VecDeque::new(); let mut open: VecDeque<(HexCoord, f32, usize)> = VecDeque::new();
let mut closed: Vec<(HexCoord, f32)> = Vec::new(); // let mut closed: Vec<(HexCoord, f32)> = Vec::new();
for z in 0..height { for z in 0..height
for x in 0..width { {
for x in 0..width
{
let chunk = &mut data[z * height + x]; let chunk = &mut data[z * height + x];
chunk.prepare_chunk_open(x * Chunk::SIZE, z * Chunk::SIZE, &mut open); chunk.prepare_chunk_open(x * Chunk::SIZE, z * Chunk::SIZE, &mut open);
} }
} }
} }
fn prepare_chunk_open(&mut self, offset_x: usize, offset_z: usize, open: &mut VecDeque<(HexCoord, f32, usize)>) { fn prepare_chunk_open(&mut self, offset_x: usize, offset_z: usize, open: &mut VecDeque<(HexCoord, f32, usize)>)
for z in 0..Chunk::SIZE { {
for x in 0..Chunk::SIZE { for z in 0..Chunk::SIZE
{
for x in 0..Chunk::SIZE
{
let coord = HexCoord::from_grid_pos(x + offset_x, z + offset_z); let coord = HexCoord::from_grid_pos(x + offset_x, z + offset_z);
let idx = coord.to_chunk_local_index(); let idx = coord.to_chunk_local_index();
let h = self.heights[idx]; let h = self.heights[idx];
self.distance_to_land[idx] = if h > self.sealevel { 0.0 } else { 4.0 }; self.distance_to_land[idx] = if h > self.sealevel { 0.0 } else { 4.0 };
if h > self.sealevel { if h > self.sealevel
{
open.push_back((coord, h, 0)); open.push_back((coord, h, 0));
} }
} }
} }
} }
#[allow(dead_code)]
#[allow(unused)]
fn fill_chunk_borders( fn fill_chunk_borders(
&mut self, &mut self,
chunks: &Vec<MeshChunkData>, chunks: &Vec<MeshChunkData>,
offset: IVec2, offset: IVec2,
open: &mut VecDeque<(HexCoord, f32, usize)>, open: &mut VecDeque<(HexCoord, f32, usize)>,
closed: &mut Vec<(HexCoord, f32)>, closed: &mut Vec<(HexCoord, f32)>,
) { )
{
self.prepare_chunk_open(offset.x as usize * Chunk::SIZE, offset.y as usize * Chunk::SIZE, open); self.prepare_chunk_open(offset.x as usize * Chunk::SIZE, offset.y as usize * Chunk::SIZE, open);
todo!("Fill closed list with bordering tiles") todo!("Fill closed list with bordering tiles")
} }

View File

@@ -12,11 +12,11 @@ use crate::{
resource_gathering::ResourceGatheringBuildingInfo, resource_gathering::ResourceGatheringBuildingInfo,
}, },
footprint::BuildingFootprint, footprint::BuildingFootprint,
prelude::Building,
}; };
#[derive(Asset, TypePath, Debug, Serialize, Deserialize)] #[derive(Asset, TypePath, Debug, Serialize, Deserialize)]
pub struct BuildingAsset { pub struct BuildingAsset
{
pub name: String, pub name: String,
pub description: String, pub description: String,
pub footprint: BuildingFootprint, pub footprint: BuildingFootprint,
@@ -35,7 +35,9 @@ pub struct BuildingAsset {
// pub components: Option<Vec<ComponentDefination>>, // pub components: Option<Vec<ComponentDefination>>,
} }
impl BuildingAsset { impl BuildingAsset
{
#[allow(unused)]
pub fn spawn( pub fn spawn(
&self, &self,
pos: Vec3, pos: Vec3,
@@ -44,7 +46,8 @@ impl BuildingAsset {
commands: &mut Commands, commands: &mut Commands,
meshes: &Assets<GltfMesh>, meshes: &Assets<GltfMesh>,
nodes: &Assets<GltfNode>, nodes: &Assets<GltfNode>,
) -> Option<Entity> { ) -> Option<Entity>
{
todo!("Update building spawning"); todo!("Update building spawning");
// let base_node = &gltf.named_nodes[&self.base_mesh_path.clone().into_boxed_str()]; // let base_node = &gltf.named_nodes[&self.base_mesh_path.clone().into_boxed_str()];
// if let Some(node) = nodes.get(base_node.id()) { // if let Some(node) = nodes.get(base_node.id()) {
@@ -120,7 +123,8 @@ impl BuildingAsset {
} }
#[derive(Serialize, Deserialize, Debug, TypePath)] #[derive(Serialize, Deserialize, Debug, TypePath)]
pub enum BuildingType { pub enum BuildingType
{
Basic, Basic,
Gathering(ResourceGatheringBuildingInfo), Gathering(ResourceGatheringBuildingInfo),
FactoryBuildingInfo(FactoryBuildingInfo), FactoryBuildingInfo(FactoryBuildingInfo),

View File

@@ -1,26 +1,19 @@
use std::f32::consts::E;
use bevy::{ use bevy::{
ecs::world::CommandQueue, ecs::world::CommandQueue,
gltf::{GltfMesh, GltfNode}, gltf::{GltfMesh, GltfNode},
prelude::*, prelude::*,
window::PrimaryWindow,
}; };
use bevy_asset_loader::loading_state::{ use bevy_asset_loader::loading_state::{
config::{ConfigureLoadingState, LoadingStateConfig}, config::{ConfigureLoadingState, LoadingStateConfig},
LoadingStateAppExt, LoadingStateAppExt,
}; };
use bevy_rapier3d::{parry::transformation::utils::transform, pipeline::QueryFilter, plugin::RapierContext};
use shared::{ use shared::{
despawn::Despawn, despawn::Despawn,
events::TileModifiedEvent, events::TileModifiedEvent,
resources::TileUnderCursor, resources::TileUnderCursor,
states::{AssetLoadState, GameplayState}, states::{AssetLoadState, GameplayState},
tags::MainCamera,
};
use world_generation::{
heightmap, hex_utils::HexCoord, map::map::Map, prelude::GenerationConfig, states::GeneratorState,
}; };
use world_generation::{map::map::Map, prelude::GenerationConfig, states::GeneratorState};
use crate::{ use crate::{
assets::{ assets::{
@@ -34,8 +27,10 @@ use crate::{
pub struct BuildingPugin; pub struct BuildingPugin;
impl Plugin for BuildingPugin { impl Plugin for BuildingPugin
fn build(&self, app: &mut App) { {
fn build(&self, app: &mut App)
{
app.insert_resource(BuildQueue::default()); app.insert_resource(BuildQueue::default());
app.add_plugins(BuildingAssetPlugin); app.add_plugins(BuildingAssetPlugin);
@@ -62,12 +57,15 @@ impl Plugin for BuildingPugin {
} }
} }
fn prepare_building_map(mut commands: Commands, cfg: Res<GenerationConfig>) { fn prepare_building_map(mut commands: Commands, cfg: Res<GenerationConfig>)
{
commands.insert_resource(BuildingMap::new(cfg.size)); commands.insert_resource(BuildingMap::new(cfg.size));
} }
fn regernerate(mut commands: Commands, buildings: Query<Entity, With<Building>>, cfg: Res<GenerationConfig>) { fn regernerate(mut commands: Commands, buildings: Query<Entity, With<Building>>, cfg: Res<GenerationConfig>)
for e in buildings.iter() { {
for e in buildings.iter()
{
commands.entity(e).despawn(); commands.entity(e).despawn();
} }
commands.insert_resource(BuildingMap::new(cfg.size)); commands.insert_resource(BuildingMap::new(cfg.size));
@@ -76,7 +74,8 @@ fn regernerate(mut commands: Commands, buildings: Query<Entity, With<Building>>,
#[derive(Resource)] #[derive(Resource)]
struct IndicatorCube(Handle<Mesh>, Handle<StandardMaterial>); struct IndicatorCube(Handle<Mesh>, Handle<StandardMaterial>);
fn init(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>) { fn init(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>)
{
let cube = Cuboid::from_size(Vec3::splat(1.)); let cube = Cuboid::from_size(Vec3::splat(1.));
let mesh_handle = meshes.add(cube); let mesh_handle = meshes.add(cube);
let mat_handle = materials.add(Color::WHITE); let mat_handle = materials.add(Color::WHITE);
@@ -91,12 +90,15 @@ fn hq_placement(
indicator: Res<IndicatorCube>, indicator: Res<IndicatorCube>,
mut build_queue: ResMut<BuildQueue>, mut build_queue: ResMut<BuildQueue>,
mut next_state: ResMut<NextState<GameplayState>>, mut next_state: ResMut<NextState<GameplayState>>,
) { )
if let Some(contact) = tile_under_cursor.0 { {
if let Some(contact) = tile_under_cursor.0
{
let positions = map.hex_select(&contact.tile, 3, true, |pos, h, _| pos.to_world(h)); let positions = map.hex_select(&contact.tile, 3, true, |pos, h, _| pos.to_world(h));
show_indicators(positions, &mut commands, &indicator); show_indicators(positions, &mut commands, &indicator);
if mouse.just_pressed(MouseButton::Left) { if mouse.just_pressed(MouseButton::Left)
{
build_queue.queue.push(QueueEntry { build_queue.queue.push(QueueEntry {
building: 0.into(), building: 0.into(),
pos: contact.tile, pos: contact.tile,
@@ -107,8 +109,10 @@ fn hq_placement(
} }
} }
fn show_indicators(positions: Vec<Vec3>, commands: &mut Commands, indicator: &IndicatorCube) { fn show_indicators(positions: Vec<Vec3>, commands: &mut Commands, indicator: &IndicatorCube)
for p in positions { {
for p in positions
{
commands.spawn(( commands.spawn((
Mesh3d(indicator.0.clone()), Mesh3d(indicator.0.clone()),
MeshMaterial3d(indicator.1.clone()), MeshMaterial3d(indicator.1.clone()),
@@ -128,13 +132,17 @@ fn process_build_queue(
gltf_nodes: Res<Assets<GltfNode>>, gltf_nodes: Res<Assets<GltfNode>>,
mut building_map: ResMut<BuildingMap>, mut building_map: ResMut<BuildingMap>,
heightmap: Res<Map>, heightmap: Res<Map>,
) { )
for item in &queue.queue { {
for item in &queue.queue
{
let handle = &db.buildings[item.building.0]; let handle = &db.buildings[item.building.0];
if let Some(building) = building_assets.get(handle.id()) { if let Some(building) = building_assets.get(handle.id())
{
let h = heightmap.sample_height(&item.pos); let h = heightmap.sample_height(&item.pos);
println!("Spawning {} at {}", building.name, item.pos); println!("Spawning {} at {}", building.name, item.pos);
if let Some(gltf) = gltf_assets.get(building.prefab.id()) { if let Some(gltf) = gltf_assets.get(building.prefab.id())
{
let e = building.spawn( let e = building.spawn(
item.pos.to_world(h), item.pos.to_world(h),
Quat::IDENTITY, Quat::IDENTITY,
@@ -143,10 +151,13 @@ fn process_build_queue(
&gltf_meshes, &gltf_meshes,
&gltf_nodes, &gltf_nodes,
); );
if let Some(b) = e { if let Some(b) = e
{
building_map.add_building(BuildingEntry::new(item.pos, b)); building_map.add_building(BuildingEntry::new(item.pos, b));
} }
} else { }
else
{
warn!("Failed to spawn building"); warn!("Failed to spawn building");
} }
} }
@@ -158,17 +169,23 @@ fn update_building_heights(
mut tile_updates: MessageReader<TileModifiedEvent>, mut tile_updates: MessageReader<TileModifiedEvent>,
building_map: Res<BuildingMap>, building_map: Res<BuildingMap>,
mut commands: Commands, mut commands: Commands,
) { )
for event in tile_updates.read() { {
match event { for event in tile_updates.read()
TileModifiedEvent::HeightChanged(coord, new_height) => { {
if let Some(building) = building_map.get_building(coord) { match event
{
TileModifiedEvent::HeightChanged(coord, new_height) =>
{
if let Some(building) = building_map.get_building(coord)
{
let mut queue = CommandQueue::default(); let mut queue = CommandQueue::default();
let e = building.entity.clone(); let e = building.entity.clone();
let h = *new_height; let h = *new_height;
queue.push(move |world: &mut World| { queue.push(move |world: &mut World| {
let mut emut = world.entity_mut(e); let mut emut = world.entity_mut(e);
if let Some(mut transform) = emut.get_mut::<Transform>() { if let Some(mut transform) = emut.get_mut::<Transform>()
{
transform.translation.y = h; transform.translation.y = h;
} }
}); });

View File

@@ -1,4 +1,4 @@
use bevy::anti_alias::taa::{TemporalAntiAliasPlugin, TemporalAntiAliasing}; use bevy::anti_alias::taa::TemporalAntiAliasing;
use bevy::core_pipeline::prepass::DepthPrepass; use bevy::core_pipeline::prepass::DepthPrepass;
use bevy::input::mouse::{MouseMotion, MouseScrollUnit, MouseWheel}; use bevy::input::mouse::{MouseMotion, MouseScrollUnit, MouseWheel};
use bevy::prelude::*; use bevy::prelude::*;
@@ -25,12 +25,10 @@ impl Plugin for PhosCameraPlugin
app.add_systems(Update, orbit_camera_upate.in_set(GameplaySet)); app.add_systems(Update, orbit_camera_upate.in_set(GameplaySet));
app.add_systems(Update, init_bounds.run_if(in_state(GeneratorState::SpawnMap))); app.add_systems(Update, init_bounds.run_if(in_state(GeneratorState::SpawnMap)));
// app.add_plugins(TemporalAntiAliasPlugin);
} }
} }
fn init_bounds(mut commands: Commands, mut cam: Single<(&mut Transform, Entity), With<PhosCamera>>, heightmap: Res<Map>) fn init_bounds(mut commands: Commands, cam: Single<(&mut Transform, Entity), With<PhosCamera>>, heightmap: Res<Map>)
{ {
let (mut cam_t, cam_entity) = cam.into_inner(); let (mut cam_t, cam_entity) = cam.into_inner();
cam_t.translation = heightmap.get_center(); cam_t.translation = heightmap.get_center();

View File

@@ -1,10 +1,11 @@
use bevy::prelude::*; use bevy::prelude::*;
use rayon::str; use rayon::str;
use world_generation::{hex_utils::SHORT_DIAGONAL, prelude::Chunk}; use world_generation::prelude::Chunk;
#[derive(Component, Reflect)] #[derive(Component, Reflect)]
#[reflect(Component)] #[reflect(Component)]
pub struct PhosCamera { pub struct PhosCamera
{
pub min_height: f32, pub min_height: f32,
pub max_height: f32, pub max_height: f32,
pub speed: f32, pub speed: f32,
@@ -14,8 +15,10 @@ pub struct PhosCamera {
pub max_angle: f32, pub max_angle: f32,
} }
impl Default for PhosCamera { impl Default for PhosCamera
fn default() -> Self { {
fn default() -> Self
{
Self { Self {
min_height: 10., min_height: 10.,
max_height: 420., max_height: 420.,
@@ -28,14 +31,17 @@ impl Default for PhosCamera {
} }
} }
#[derive(Component, Reflect)] #[derive(Component, Reflect)]
pub struct PhosOrbitCamera { pub struct PhosOrbitCamera
{
pub target: Vec3, pub target: Vec3,
pub distance: f32, pub distance: f32,
pub forward: Vec3, pub forward: Vec3,
} }
impl Default for PhosOrbitCamera { impl Default for PhosOrbitCamera
fn default() -> Self { {
fn default() -> Self
{
Self { Self {
target: Default::default(), target: Default::default(),
distance: 40.0, distance: 40.0,
@@ -45,13 +51,16 @@ impl Default for PhosOrbitCamera {
} }
#[derive(Component, Default)] #[derive(Component, Default)]
pub struct CameraBounds { pub struct CameraBounds
{
pub min: Vec2, pub min: Vec2,
pub max: Vec2, pub max: Vec2,
} }
impl CameraBounds { impl CameraBounds
pub fn from_size(world_size: Vec2) -> Self { {
pub fn from_size(world_size: Vec2) -> Self
{
let padding = Chunk::WORLD_SIZE; let padding = Chunk::WORLD_SIZE;
return Self { return Self {
min: Vec2::ZERO - padding, min: Vec2::ZERO - padding,

View File

@@ -1,5 +1,3 @@
use std::env;
use bevy::image::{ImageAddressMode, ImageFilterMode, ImageSamplerDescriptor}; use bevy::image::{ImageAddressMode, ImageFilterMode, ImageSamplerDescriptor};
use bevy::pbr::wireframe::WireframePlugin; use bevy::pbr::wireframe::WireframePlugin;
use bevy::prelude::*; use bevy::prelude::*;

View File

@@ -9,6 +9,7 @@ use world_generation::prelude::Map;
use world_generation::states::GeneratorState; use world_generation::states::GeneratorState;
use crate::prelude::RebuildChunk; use crate::prelude::RebuildChunk;
use crate::prelude::WaterMesh;
use crate::{ use crate::{
prelude::{PhosChunk, PhosChunkRegistry}, prelude::{PhosChunk, PhosChunkRegistry},
utlis::chunk_utils::prepare_chunk_mesh, utlis::chunk_utils::prepare_chunk_mesh,
@@ -16,8 +17,10 @@ use crate::{
pub struct ChunkRebuildPlugin; pub struct ChunkRebuildPlugin;
impl Plugin for ChunkRebuildPlugin { impl Plugin for ChunkRebuildPlugin
fn build(&self, app: &mut App) { {
fn build(&self, app: &mut App)
{
app.init_resource::<PhosChunkRegistry>(); app.init_resource::<PhosChunkRegistry>();
app.add_message::<ChunkModifiedEvent>(); app.add_message::<ChunkModifiedEvent>();
app.add_message::<TileModifiedEvent>(); app.add_message::<TileModifiedEvent>();
@@ -30,11 +33,13 @@ fn chunk_rebuilder(
mut commands: Commands, mut commands: Commands,
chunk_query: Query<(Entity, &PhosChunk), (With<RebuildChunk>, Without<ChunkRebuildTask>)>, chunk_query: Query<(Entity, &PhosChunk), (With<RebuildChunk>, Without<ChunkRebuildTask>)>,
heightmap: Res<Map>, heightmap: Res<Map>,
) { )
{
let pool = AsyncComputeTaskPool::get(); let pool = AsyncComputeTaskPool::get();
let map_size = UVec2::new(heightmap.width as u32, heightmap.height as u32); let map_size = UVec2::new(heightmap.width as u32, heightmap.height as u32);
for (chunk_entity, idx) in &chunk_query { for (chunk_entity, idx) in &chunk_query
{
#[cfg(feature = "tracing")] #[cfg(feature = "tracing")]
let _spawn_span = info_span!("Rebuild Chunk").entered(); let _spawn_span = info_span!("Rebuild Chunk").entered();
info!("Rebuilding Chunk"); info!("Rebuilding Chunk");
@@ -62,7 +67,7 @@ fn chunk_rebuilder(
world.entity_mut(chunk_entity).insert(c).remove::<ChunkRebuildTask>(); world.entity_mut(chunk_entity).insert(c).remove::<ChunkRebuildTask>();
}); });
return (queue, mesh); return (queue, mesh, water_mesh);
}); });
commands commands
@@ -73,19 +78,28 @@ fn chunk_rebuilder(
} }
fn collider_task_resolver( fn collider_task_resolver(
mut chunks: Query<(&mut ChunkRebuildTask, &Mesh3d), With<PhosChunk>>, mut chunks: Query<(&mut ChunkRebuildTask, &Mesh3d, &WaterMesh), With<PhosChunk>>,
mut commands: Commands, mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>, mut meshes: ResMut<Assets<Mesh>>,
) { )
for (mut task, mesh_handle) in &mut chunks { {
if let Some((mut c, mesh)) = futures::check_ready(&mut task.task) { for (mut task, mesh_handle, water_mesh_handle) in &mut chunks
{
if let Some((mut c, chunk_mesh, water_mesh)) = futures::check_ready(&mut task.task)
{
commands.append(&mut c); commands.append(&mut c);
meshes.insert(mesh_handle.id(), mesh); meshes
.insert(mesh_handle.id(), chunk_mesh)
.expect("Failed to update chunk mesh");
meshes
.insert(water_mesh_handle.0, water_mesh)
.expect("Failed to update chink water mesh");
} }
} }
} }
#[derive(Component)] #[derive(Component)]
struct ChunkRebuildTask { struct ChunkRebuildTask
pub task: Task<(CommandQueue, Mesh)>, {
pub task: Task<(CommandQueue, Mesh, Mesh)>,
} }

View File

@@ -1,11 +1,6 @@
#[cfg(feature = "tracing")] #[cfg(feature = "tracing")]
use bevy::log::*; use bevy::log::*;
use bevy::{ use bevy::{light::NotShadowCaster, pbr::ExtendedMaterial, prelude::*};
light::NotShadowCaster,
pbr::ExtendedMaterial,
prelude::*,
render::render_resource::{ColorTargetState, FragmentState, RenderPipelineDescriptor},
};
use bevy_asset_loader::prelude::*; use bevy_asset_loader::prelude::*;
use bevy_inspector_egui::quick::ResourceInspectorPlugin; use bevy_inspector_egui::quick::ResourceInspectorPlugin;
@@ -23,7 +18,7 @@ use world_generation::{
}; };
use crate::{ use crate::{
prelude::{PhosAssets, PhosChunk, PhosChunkRegistry}, prelude::{PhosAssets, PhosChunk, PhosChunkRegistry, WaterMesh},
shader_extensions::{ shader_extensions::{
chunk_material::ChunkMaterial, chunk_material::ChunkMaterial,
water_material::{WaterMaterial, WaterSettings}, water_material::{WaterMaterial, WaterSettings},
@@ -258,19 +253,21 @@ fn spawn_map(
for (chunk_mesh, water_mesh, collider, pos, index) in chunk_meshes for (chunk_mesh, water_mesh, collider, pos, index) in chunk_meshes
{ {
// let mesh_handle = meshes.a // let mesh_handle = meshes.a
let water_mesh_handle = meshes.add(water_mesh);
let chunk = commands let chunk = commands
.spawn(( .spawn((
Mesh3d(meshes.add(chunk_mesh)), Mesh3d(meshes.add(chunk_mesh)),
MeshMaterial3d(atlas.chunk_material_handle.clone()), MeshMaterial3d(atlas.chunk_material_handle.clone()),
Transform::from_translation(pos), Transform::from_translation(pos),
PhosChunk::new(index), PhosChunk::new(index),
WaterMesh(water_mesh_handle.id()),
RenderDistanceVisibility::default().with_offset(visibility_offset), RenderDistanceVisibility::default().with_offset(visibility_offset),
collider, collider,
)) ))
.id(); .id();
let water = commands let water = commands
.spawn(( .spawn((
Mesh3d(meshes.add(water_mesh)), Mesh3d(water_mesh_handle),
MeshMaterial3d(atlas.water_material.clone()), MeshMaterial3d(atlas.water_material.clone()),
Transform::from_translation(pos), Transform::from_translation(pos),
PhosChunk::new(index), PhosChunk::new(index),

View File

@@ -1,2 +1 @@
use bevy::prelude::*;
use world_generation::biome_painter::BiomePainterAsset;

View File

@@ -1,12 +1,12 @@
use bevy::prelude::*; use bevy::prelude::*;
use shared::tags::MainCamera; use shared::tags::MainCamera;
use crate::camera_system::components::PhosCamera;
pub struct RenderDistancePlugin; pub struct RenderDistancePlugin;
impl Plugin for RenderDistancePlugin { impl Plugin for RenderDistancePlugin
fn build(&self, app: &mut bevy::prelude::App) { {
fn build(&self, app: &mut bevy::prelude::App)
{
app.register_type::<RenderDistanceSettings>(); app.register_type::<RenderDistanceSettings>();
app.add_systems(PostUpdate, render_distance_system) app.add_systems(PostUpdate, render_distance_system)
.insert_resource(RenderDistanceSettings::default()); .insert_resource(RenderDistanceSettings::default());
@@ -15,38 +15,48 @@ impl Plugin for RenderDistancePlugin {
#[derive(Resource, Reflect)] #[derive(Resource, Reflect)]
#[reflect(Resource)] #[reflect(Resource)]
pub struct RenderDistanceSettings { pub struct RenderDistanceSettings
{
pub render_distance: f32, pub render_distance: f32,
} }
impl RenderDistanceSettings { impl RenderDistanceSettings
pub fn new(distance: f32) -> Self { {
pub fn new(distance: f32) -> Self
{
return Self { return Self {
render_distance: distance, render_distance: distance,
}; };
} }
} }
impl Default for RenderDistanceSettings { impl Default for RenderDistanceSettings
fn default() -> Self { {
fn default() -> Self
{
Self::new(500.) Self::new(500.)
} }
} }
#[derive(Component)] #[derive(Component)]
pub struct RenderDistanceVisibility { pub struct RenderDistanceVisibility
{
pub offset: Vec3, pub offset: Vec3,
} }
impl RenderDistanceVisibility { impl RenderDistanceVisibility
pub fn with_offset(mut self, offset: Vec3) -> Self { {
pub fn with_offset(mut self, offset: Vec3) -> Self
{
self.offset = offset; self.offset = offset;
return self; return self;
} }
} }
impl Default for RenderDistanceVisibility { impl Default for RenderDistanceVisibility
fn default() -> Self { {
fn default() -> Self
{
Self { offset: Vec3::ZERO } Self { offset: Vec3::ZERO }
} }
} }
@@ -55,13 +65,18 @@ fn render_distance_system(
mut objects: Query<(&Transform, &mut Visibility, &RenderDistanceVisibility)>, mut objects: Query<(&Transform, &mut Visibility, &RenderDistanceVisibility)>,
camera: Single<&Transform, With<MainCamera>>, camera: Single<&Transform, With<MainCamera>>,
settings: Res<RenderDistanceSettings>, settings: Res<RenderDistanceSettings>,
) { )
{
let cam_pos = Vec3::new(camera.translation.x, 0.0, camera.translation.z); let cam_pos = Vec3::new(camera.translation.x, 0.0, camera.translation.z);
for (t, mut vis, r) in objects.iter_mut() { for (t, mut vis, r) in objects.iter_mut()
{
let dist = (cam_pos - (t.translation + r.offset)).length(); let dist = (cam_pos - (t.translation + r.offset)).length();
if settings.render_distance < dist { if settings.render_distance < dist
{
*vis = Visibility::Hidden; *vis = Visibility::Hidden;
} else { }
else
{
*vis = Visibility::Visible; *vis = Visibility::Visible;
} }
} }

View File

@@ -1,21 +1,20 @@
use bevy::{platform::collections::HashSet, prelude::*, window::PrimaryWindow}; use bevy::{platform::collections::HashSet, prelude::*};
use bevy_rapier3d::{pipeline::QueryFilter, plugin::RapierContext};
use shared::{ use shared::{
events::{ChunkModifiedEvent, TileModifiedEvent}, events::{ChunkModifiedEvent, TileModifiedEvent},
resources::TileUnderCursor, resources::TileUnderCursor,
states::GameplayState, states::GameplayState,
}; };
use world_generation::{hex_utils::HexCoord, prelude::Map, states::GeneratorState}; use world_generation::{prelude::Map, states::GeneratorState};
use crate::{ use crate::prelude::{PhosChunkRegistry, RebuildChunk};
camera_system::components::PhosCamera,
prelude::{PhosChunkRegistry, RebuildChunk},
};
#[allow(dead_code)]
pub struct TerraFormingTestPlugin; pub struct TerraFormingTestPlugin;
impl Plugin for TerraFormingTestPlugin { impl Plugin for TerraFormingTestPlugin
fn build(&self, app: &mut App) { {
fn build(&self, app: &mut App)
{
app.add_systems( app.add_systems(
Update, Update,
deform deform
@@ -25,6 +24,7 @@ impl Plugin for TerraFormingTestPlugin {
} }
} }
#[allow(dead_code)]
fn deform( fn deform(
mut commands: Commands, mut commands: Commands,
mouse: Res<ButtonInput<MouseButton>>, mouse: Res<ButtonInput<MouseButton>>,
@@ -33,26 +33,34 @@ fn deform(
tile_under_cursor: Res<TileUnderCursor>, tile_under_cursor: Res<TileUnderCursor>,
mut chunk_modified: MessageWriter<ChunkModifiedEvent>, mut chunk_modified: MessageWriter<ChunkModifiedEvent>,
mut tile_modified: MessageWriter<TileModifiedEvent>, mut tile_modified: MessageWriter<TileModifiedEvent>,
) { )
{
let mut multi = 0.; let mut multi = 0.;
if mouse.just_pressed(MouseButton::Left) { if mouse.just_pressed(MouseButton::Left)
{
multi = 1.; multi = 1.;
} else if mouse.just_pressed(MouseButton::Right) { }
else if mouse.just_pressed(MouseButton::Right)
{
multi = -1.; multi = -1.;
} }
if multi == 0. { if multi == 0.
{
return; return;
} }
if let Some(contact) = tile_under_cursor.0 { if let Some(contact) = tile_under_cursor.0
{
#[cfg(feature = "tracing")] #[cfg(feature = "tracing")]
let span = info_span!("Deform Mesh").entered(); let span = info_span!("Deform Mesh").entered();
let modified_tiles = heightmap.create_crater(&contact.tile, 5, 5. * multi); let modified_tiles = heightmap.create_crater(&contact.tile, 5, 5. * multi);
let mut chunk_set: HashSet<usize> = HashSet::new(); let mut chunk_set: HashSet<usize> = HashSet::new();
for (tile, height) in modified_tiles { for (tile, height) in modified_tiles
{
let chunk = tile.to_chunk_index(heightmap.width); let chunk = tile.to_chunk_index(heightmap.width);
if !chunk_set.contains(&chunk) { if !chunk_set.contains(&chunk)
{
chunk_modified.write(ChunkModifiedEvent { index: chunk }); chunk_modified.write(ChunkModifiedEvent { index: chunk });
chunk_set.insert(chunk); chunk_set.insert(chunk);
commands.entity(chunks.chunks[chunk]).insert(RebuildChunk); commands.entity(chunks.chunks[chunk]).insert(RebuildChunk);

View File

@@ -1,7 +1,7 @@
use crate::camera_system::components::PhosCamera; use crate::camera_system::components::PhosCamera;
use crate::map_rendering::map_init::MapInitPlugin; use crate::map_rendering::map_init::MapInitPlugin;
use crate::map_rendering::render_distance_system::RenderDistancePlugin; use crate::map_rendering::render_distance_system::RenderDistancePlugin;
// use crate::ui::build_ui::BuildUIPlugin; use crate::ui::build_ui::BuildUIPlugin;
use crate::utlis::editor_plugin::EditorPlugin; use crate::utlis::editor_plugin::EditorPlugin;
use crate::utlis::tile_selection_plugin::TileSelectionPlugin; use crate::utlis::tile_selection_plugin::TileSelectionPlugin;
use crate::{camera_system::camera_plugin::PhosCameraPlugin, utlis::debug_plugin::DebugPlugin}; use crate::{camera_system::camera_plugin::PhosCameraPlugin, utlis::debug_plugin::DebugPlugin};
@@ -40,7 +40,7 @@ impl Plugin for PhosGamePlugin
MapInitPlugin, MapInitPlugin,
RenderDistancePlugin, RenderDistancePlugin,
// BuildingPugin, // BuildingPugin,
// BuildUIPlugin, BuildUIPlugin,
// SimpleAnimationPlugin, // SimpleAnimationPlugin,
// UnitsPlugin, // UnitsPlugin,
DespawnPuglin, DespawnPuglin,

View File

@@ -3,13 +3,13 @@ use bevy::pbr::ExtendedMaterial;
use bevy::prelude::*; use bevy::prelude::*;
use bevy::prelude::{Component, Image, Resource}; use bevy::prelude::{Component, Image, Resource};
use bevy_asset_loader::asset_collection::AssetCollection; use bevy_asset_loader::asset_collection::AssetCollection;
use world_generation::biome_painter::BiomePainterAsset;
use crate::shader_extensions::chunk_material::ChunkMaterial; use crate::shader_extensions::chunk_material::ChunkMaterial;
use crate::shader_extensions::water_material::WaterMaterial; use crate::shader_extensions::water_material::WaterMaterial;
#[derive(AssetCollection, Resource, Default)] #[derive(AssetCollection, Resource, Default)]
pub struct PhosAssets { pub struct PhosAssets
{
#[asset(key = "chunk_atlas")] #[asset(key = "chunk_atlas")]
pub handle: Handle<Image>, pub handle: Handle<Image>,
pub chunk_material_handle: Handle<ExtendedMaterial<StandardMaterial, ChunkMaterial>>, pub chunk_material_handle: Handle<ExtendedMaterial<StandardMaterial, ChunkMaterial>>,
@@ -17,24 +17,33 @@ pub struct PhosAssets {
} }
#[derive(Component)] #[derive(Component)]
pub struct PhosChunk { pub struct PhosChunk
{
pub index: usize, pub index: usize,
} }
impl PhosChunk { impl PhosChunk
pub fn new(index: usize) -> Self { {
pub fn new(index: usize) -> Self
{
return Self { index }; return Self { index };
} }
} }
#[derive(Component)]
pub struct WaterMesh(pub AssetId<Mesh>);
#[derive(Resource, Default)] #[derive(Resource, Default)]
pub struct PhosChunkRegistry { pub struct PhosChunkRegistry
{
pub chunks: Vec<Entity>, pub chunks: Vec<Entity>,
pub waters: Vec<Entity>, pub waters: Vec<Entity>,
} }
impl PhosChunkRegistry { impl PhosChunkRegistry
pub fn new(size: usize) -> Self { {
pub fn new(size: usize) -> Self
{
return Self { return Self {
chunks: Vec::with_capacity(size), chunks: Vec::with_capacity(size),
waters: Vec::with_capacity(size), waters: Vec::with_capacity(size),

View File

@@ -22,6 +22,7 @@ impl MaterialExtension for ChunkMaterial
} }
} }
#[allow(dead_code)]
#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)] #[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
pub struct PackedChunkMaterial pub struct PackedChunkMaterial
{ {
@@ -56,10 +57,10 @@ impl Material for PackedChunkMaterial
// } // }
fn specialize( fn specialize(
pipeline: &bevy::pbr::MaterialPipeline, _pipeline: &bevy::pbr::MaterialPipeline,
descriptor: &mut bevy::render::render_resource::RenderPipelineDescriptor, descriptor: &mut bevy::render::render_resource::RenderPipelineDescriptor,
layout: &bevy::mesh::MeshVertexBufferLayoutRef, layout: &bevy::mesh::MeshVertexBufferLayoutRef,
key: bevy::pbr::MaterialPipelineKey<Self>, _key: bevy::pbr::MaterialPipelineKey<Self>,
) -> bevy::ecs::error::Result<(), bevy::render::render_resource::SpecializedMeshPipelineError> ) -> bevy::ecs::error::Result<(), bevy::render::render_resource::SpecializedMeshPipelineError>
{ {
let vertex_layout = layout.0.get_layout(&[ let vertex_layout = layout.0.get_layout(&[

View File

@@ -1,11 +1,9 @@
use bevy::asset::Asset; use bevy::asset::Asset;
use bevy::math::VectorSpace;
use bevy::pbr::MaterialExtension; use bevy::pbr::MaterialExtension;
use bevy::prelude::*; use bevy::prelude::*;
use bevy::reflect::Reflect; use bevy::reflect::Reflect;
use bevy::render::render_resource::{AsBindGroup, ShaderType}; use bevy::render::render_resource::{AsBindGroup, ShaderType};
use bevy::shader::ShaderRef; use bevy::shader::ShaderRef;
use world_generation::consts::{ATTRIBUTE_PACKED_VERTEX_DATA, ATTRIBUTE_VERTEX_HEIGHT};
#[derive(Asset, Reflect, AsBindGroup, Debug, Clone, Default)] #[derive(Asset, Reflect, AsBindGroup, Debug, Clone, Default)]
pub struct WaterMaterial pub struct WaterMaterial

View File

@@ -1,19 +1,23 @@
use bevy::prelude::*; use bevy::{camera::visibility::RenderLayers, prelude::*};
use shared::{states::AssetLoadState, tags::MainCamera}; use shared::states::AssetLoadState;
pub struct BuildUIPlugin; pub struct BuildUIPlugin;
impl Plugin for BuildUIPlugin { impl Plugin for BuildUIPlugin
fn build(&self, app: &mut App) { {
fn build(&self, app: &mut App)
{
app.add_systems(Startup, setup_cameras); app.add_systems(Startup, setup_cameras);
app.add_systems(Update, spawn_ui.run_if(in_state(AssetLoadState::LoadComplete))); app.add_systems(Update, spawn_ui.run_if(in_state(AssetLoadState::LoadComplete)));
} }
} }
fn setup_cameras(mut commands: Commands) { fn setup_cameras(mut commands: Commands)
commands.spawn((Camera2d, IsDefaultUiCamera)); {
commands.spawn((Camera2d, IsDefaultUiCamera, RenderLayers::layer(2)));
} }
fn spawn_ui(mut commands: Commands) { fn spawn_ui(mut commands: Commands)
{
commands commands
.spawn((Node { .spawn((Node {
width: Val::Percent(100.), width: Val::Percent(100.),

View File

@@ -13,7 +13,6 @@ use world_generation::{
generators::{ generators::{
chunk_colliders::generate_chunk_collider, chunk_colliders::generate_chunk_collider,
mesh_generator::{generate_chunk_mesh, generate_chunk_water_mesh}, mesh_generator::{generate_chunk_mesh, generate_chunk_water_mesh},
packed_mesh_generator::generate_packed_chunk_mesh,
}, },
hex_utils::offset_to_world, hex_utils::offset_to_world,
prelude::{Chunk, Map, MeshChunkData}, prelude::{Chunk, Map, MeshChunkData},
@@ -26,7 +25,8 @@ pub fn paint_map(
painter: &BiomePainter, painter: &BiomePainter,
tiles: &Res<Assets<TileAsset>>, tiles: &Res<Assets<TileAsset>>,
mappers: &Res<Assets<TileMapperAsset>>, mappers: &Res<Assets<TileMapperAsset>>,
) { )
{
map.chunks.par_iter_mut().for_each(|chunk: &mut Chunk| { map.chunks.par_iter_mut().for_each(|chunk: &mut Chunk| {
paint_chunk(chunk, painter, tiles, mappers); paint_chunk(chunk, painter, tiles, mappers);
}); });
@@ -37,9 +37,12 @@ pub fn paint_chunk(
painter: &BiomePainter, painter: &BiomePainter,
tiles: &Res<Assets<TileAsset>>, tiles: &Res<Assets<TileAsset>>,
mappers: &Res<Assets<TileMapperAsset>>, mappers: &Res<Assets<TileMapperAsset>>,
) { )
for z in 0..Chunk::SIZE { {
for x in 0..Chunk::SIZE { for z in 0..Chunk::SIZE
{
for x in 0..Chunk::SIZE
{
let idx = x + z * Chunk::SIZE; let idx = x + z * Chunk::SIZE;
let height = chunk.heights[idx]; let height = chunk.heights[idx];
let biome_id = chunk.biome_id[idx]; let biome_id = chunk.biome_id[idx];
@@ -58,7 +61,8 @@ pub fn prepare_chunk_mesh(
chunk_offset: IVec2, chunk_offset: IVec2,
chunk_index: usize, chunk_index: usize,
map_size: UVec2, map_size: UVec2,
) -> (Mesh, Mesh, (Vec<Vec3>, Vec<[u32; 3]>), Vec3, usize) { ) -> (Mesh, Mesh, (Vec<Vec3>, Vec<[u32; 3]>), Vec3, usize)
{
#[cfg(feature = "tracing")] #[cfg(feature = "tracing")]
let _gen_mesh = info_span!("Generate Chunk").entered(); let _gen_mesh = info_span!("Generate Chunk").entered();
let chunk_mesh = generate_chunk_mesh(chunk); let chunk_mesh = generate_chunk_mesh(chunk);
@@ -80,7 +84,8 @@ pub fn prepare_chunk_mesh_with_collider(
chunk_offset: IVec2, chunk_offset: IVec2,
chunk_index: usize, chunk_index: usize,
map_size: UVec2, map_size: UVec2,
) -> (Mesh, Mesh, Collider, Vec3, usize) { ) -> (Mesh, Mesh, Collider, Vec3, usize)
{
let (chunk_mesh, water_mesh, (col_verts, col_indicies), pos, index) = let (chunk_mesh, water_mesh, (col_verts, col_indicies), pos, index) =
prepare_chunk_mesh(chunk, sealevel, chunk_offset, chunk_index, map_size); prepare_chunk_mesh(chunk, sealevel, chunk_offset, chunk_index, map_size);
let collider: Collider; let collider: Collider;

View File

@@ -1,4 +1,4 @@
use bevy::{gizmos::gizmos, prelude::*}; use bevy::prelude::*;
use shared::states::GameplayState; use shared::states::GameplayState;
use shared::{resources::TileUnderCursor, sets::GameplaySet}; use shared::{resources::TileUnderCursor, sets::GameplaySet};
use world_generation::{ use world_generation::{
@@ -11,8 +11,10 @@ use crate::camera_system::components::{PhosCamera, PhosOrbitCamera};
pub struct DebugPlugin; pub struct DebugPlugin;
impl Plugin for DebugPlugin { impl Plugin for DebugPlugin
fn build(&self, app: &mut App) { {
fn build(&self, app: &mut App)
{
app.insert_state(DebugState::Base); app.insert_state(DebugState::Base);
app.add_systems( app.add_systems(
@@ -29,7 +31,7 @@ impl Plugin for DebugPlugin {
.run_if(in_state(DebugState::Verbose)), .run_if(in_state(DebugState::Verbose)),
); );
// app.add_systems(Update, camera_debug.in_set(GameplaySet)); app.add_systems(Update, camera_debug.in_set(GameplaySet));
app.add_systems(Update, regenerate_map.run_if(in_state(GeneratorState::Idle))); app.add_systems(Update, regenerate_map.run_if(in_state(GeneratorState::Idle)));
app.insert_resource(Shape(Polyline3d::new([ app.insert_resource(Shape(Polyline3d::new([
@@ -48,7 +50,8 @@ impl Plugin for DebugPlugin {
struct Shape(pub Polyline3d); struct Shape(pub Polyline3d);
#[derive(States, Debug, Clone, PartialEq, Eq, Hash)] #[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
pub enum DebugState { pub enum DebugState
{
Base, Base,
None, None,
Verbose, Verbose,
@@ -58,15 +61,19 @@ fn regenerate_map(
mut generator_state: ResMut<NextState<GeneratorState>>, mut generator_state: ResMut<NextState<GeneratorState>>,
mut gameplay_state: ResMut<NextState<GameplayState>>, mut gameplay_state: ResMut<NextState<GameplayState>>,
input: Res<ButtonInput<KeyCode>>, input: Res<ButtonInput<KeyCode>>,
) { )
if input.just_pressed(KeyCode::KeyR) { {
if input.just_pressed(KeyCode::KeyR)
{
generator_state.set(GeneratorState::Regenerate); generator_state.set(GeneratorState::Regenerate);
gameplay_state.set(GameplayState::PlaceHQ); gameplay_state.set(GameplayState::PlaceHQ);
} }
} }
fn show_tile_heights(map: Res<Map>, mut gizmos: Gizmos, shape: Res<Shape>, tile_under_cursor: Res<TileUnderCursor>) { fn show_tile_heights(map: Res<Map>, mut gizmos: Gizmos, shape: Res<Shape>, tile_under_cursor: Res<TileUnderCursor>)
if let Some(contact) = tile_under_cursor.0 { {
if let Some(contact) = tile_under_cursor.0
{
let height = map.sample_height(&contact.tile); let height = map.sample_height(&contact.tile);
gizmos.primitive_3d(&shape.0, contact.tile.to_world(height + 0.01), Color::WHITE); gizmos.primitive_3d(&shape.0, contact.tile.to_world(height + 0.01), Color::WHITE);
@@ -78,8 +85,11 @@ fn show_tile_heights(map: Res<Map>, mut gizmos: Gizmos, shape: Res<Shape>, tile_
} }
} }
fn show_water_corners(pos: Vec3, gizmos: &mut Gizmos) { #[allow(dead_code)]
for i in 0..WATER_HEX_CORNERS.len() { fn show_water_corners(pos: Vec3, gizmos: &mut Gizmos)
{
for i in 0..WATER_HEX_CORNERS.len()
{
let p = pos + WATER_HEX_CORNERS[i]; let p = pos + WATER_HEX_CORNERS[i];
let p2 = pos + WATER_HEX_CORNERS[(i + 1) % WATER_HEX_CORNERS.len()]; let p2 = pos + WATER_HEX_CORNERS[(i + 1) % WATER_HEX_CORNERS.len()];
@@ -87,8 +97,9 @@ fn show_water_corners(pos: Vec3, gizmos: &mut Gizmos) {
} }
} }
fn camera_debug(mut cam_query: Single<(&PhosCamera, &PhosOrbitCamera)>, mut gizmos: Gizmos) { fn camera_debug(cam_query: Single<(&PhosCamera, &PhosOrbitCamera)>, mut gizmos: Gizmos)
let (config, orbit) = cam_query.into_inner(); {
let (_config, orbit) = cam_query.into_inner();
gizmos.sphere(orbit.target, 0.3, LinearRgba::RED); gizmos.sphere(orbit.target, 0.3, LinearRgba::RED);
let cam_proxy = orbit.target - (orbit.forward * 10.0); let cam_proxy = orbit.target - (orbit.forward * 10.0);

View File

@@ -11,22 +11,25 @@ use world_generation::{map::map_utils::render_map, prelude::Map, states::Generat
pub struct EditorPlugin; pub struct EditorPlugin;
impl Plugin for EditorPlugin { impl Plugin for EditorPlugin
fn build(&self, app: &mut App) { {
fn build(&self, app: &mut App)
{
app.init_resource::<UIState>(); app.init_resource::<UIState>();
// app.add_systems(PostUpdate, prepare_image.run_if(in_state(GeneratorState::SpawnMap))); app.add_systems(PostUpdate, prepare_image.run_if(in_state(GeneratorState::SpawnMap)));
// app.add_systems( app.add_systems(
// Update, Update,
// (render_map_ui, update_map_render, asset_reloaded).run_if(in_state(GeneratorState::Idle)), (render_map_ui, update_map_render, asset_reloaded).run_if(in_state(GeneratorState::Idle)),
// ); );
} }
} }
#[derive(Resource)] #[derive(Resource)]
struct MapImage(pub Handle<Image>); struct MapImage(pub Handle<Image>);
pub fn prepare_image(mut images: ResMut<Assets<Image>>, heightmap: Res<Map>, mut commands: Commands) { pub fn prepare_image(mut images: ResMut<Assets<Image>>, heightmap: Res<Map>, mut commands: Commands)
{
let image = render_map(&heightmap, 0.1); let image = render_map(&heightmap, 0.1);
let handle = images.add(Image::from_dynamic(image.into(), true, RenderAssetUsages::RENDER_WORLD)); let handle = images.add(Image::from_dynamic(image.into(), true, RenderAssetUsages::RENDER_WORLD));
@@ -34,14 +37,17 @@ pub fn prepare_image(mut images: ResMut<Assets<Image>>, heightmap: Res<Map>, mut
} }
#[derive(Resource)] #[derive(Resource)]
struct UIState { struct UIState
{
pub is_open: bool, pub is_open: bool,
pub target_map_type: MapDisplayType, pub target_map_type: MapDisplayType,
pub cur_map_type: MapDisplayType, pub cur_map_type: MapDisplayType,
} }
impl Default for UIState { impl Default for UIState
fn default() -> Self { {
fn default() -> Self
{
Self { Self {
is_open: true, is_open: true,
target_map_type: default(), target_map_type: default(),
@@ -51,7 +57,8 @@ impl Default for UIState {
} }
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)] #[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
enum MapDisplayType { enum MapDisplayType
{
#[default] #[default]
HeightMap, HeightMap,
Biomes, Biomes,
@@ -63,72 +70,77 @@ enum MapDisplayType {
fn asset_reloaded( fn asset_reloaded(
mut asset_events: MessageReader<AssetEvent<BiomeAsset>>, mut asset_events: MessageReader<AssetEvent<BiomeAsset>>,
mut biomes: ResMut<Assets<BiomeAsset>>, biomes: Res<Assets<BiomeAsset>>,
biome_painter: Res<BiomePainterAsset>, biome_painter: Res<BiomePainterAsset>,
mut commands: Commands, mut commands: Commands,
) { )
{
let mut rebuild = false; let mut rebuild = false;
for event in asset_events.read() { for event in asset_events.read()
match event { {
match event
{
AssetEvent::Modified { .. } => rebuild = true, AssetEvent::Modified { .. } => rebuild = true,
_ => (), _ => (),
} }
} }
if rebuild { if rebuild
{
let painter = biome_painter.build(&biomes); let painter = biome_painter.build(&biomes);
commands.insert_resource(painter); commands.insert_resource(painter);
} }
} }
// fn render_map_ui( fn render_map_ui(
// image: Res<MapImage>, // image: Res<MapImage>,
// heightmap: Res<Map>, heightmap: Res<Map>,
// biome_map: Res<BiomeMap>, biome_map: Res<BiomeMap>,
// mut contexts: EguiContexts, mut contexts: EguiContexts,
// mut state: ResMut<UIState>, mut state: ResMut<UIState>,
// ) { )
// let id = contexts.add_image(image.0.clone()); {
// let id = contexts.add_image(image.0.);
let mut map_type = state.target_map_type;
let ctx = contexts.ctx_mut().expect("Failed to get egui context");
egui::Window::new("Map").open(&mut state.is_open).show(ctx, |ui| {
ui.label("Map Test");
egui::ComboBox::from_label("Display Type")
.selected_text(format!("{:?}", map_type))
.show_ui(ui, |ui| {
ui.selectable_value(&mut map_type, MapDisplayType::HeightMap, "Heightmap");
ui.selectable_value(&mut map_type, MapDisplayType::Biomes, "Biomes");
ui.selectable_value(&mut map_type, MapDisplayType::BiomeNoise, "Biome Noise");
ui.selectable_value(
&mut map_type,
MapDisplayType::BiomeNoiseTemp,
"Biome Noise: Tempurature",
);
ui.selectable_value(
&mut map_type,
MapDisplayType::BiomeNoiseContinent,
"Biome Noise: Continent",
);
ui.selectable_value(
&mut map_type,
MapDisplayType::BiomeNoiseMoisture,
"Biome Noise: Moisture",
);
});
// let mut map_type = state.target_map_type; // ui.add(egui::widgets::Image::new(egui::load::SizedTexture::new(
// let ctx = contexts.ctx_mut(); // id,
// egui::Window::new("Map").open(&mut state.is_open).show(ctx, |ui| { // [512.0, 512.0],
// ui.label("Map Test"); // )));
// egui::ComboBox::from_label("Display Type")
// .selected_text(format!("{:?}", map_type))
// .show_ui(ui, |ui| {
// ui.selectable_value(&mut map_type, MapDisplayType::HeightMap, "Heightmap");
// ui.selectable_value(&mut map_type, MapDisplayType::Biomes, "Biomes");
// ui.selectable_value(&mut map_type, MapDisplayType::BiomeNoise, "Biome Noise");
// ui.selectable_value(
// &mut map_type,
// MapDisplayType::BiomeNoiseTemp,
// "Biome Noise: Tempurature",
// );
// ui.selectable_value(
// &mut map_type,
// MapDisplayType::BiomeNoiseContinent,
// "Biome Noise: Continent",
// );
// ui.selectable_value(
// &mut map_type,
// MapDisplayType::BiomeNoiseMoisture,
// "Biome Noise: Moisture",
// );
// });
// ui.add(egui::widgets::Image::new(egui::load::SizedTexture::new( if ui.button("Save Image").clicked()
// id, {
// [512.0, 512.0], let img = get_map_image(&heightmap, &biome_map, map_type);
// ))); _ = img.save(format!("{:?}.png", map_type));
}
});
// if ui.button("Save Image").clicked() { state.target_map_type = map_type;
// let img = get_map_image(&heightmap, &biome_map, map_type); }
// _ = img.save(format!("{:?}.png", map_type));
// }
// });
// state.target_map_type = map_type;
// }
fn update_map_render( fn update_map_render(
mut state: ResMut<UIState>, mut state: ResMut<UIState>,
@@ -136,22 +148,28 @@ fn update_map_render(
heightmap: Res<Map>, heightmap: Res<Map>,
biome_map: Res<BiomeMap>, biome_map: Res<BiomeMap>,
image: Res<MapImage>, image: Res<MapImage>,
) { )
if state.cur_map_type == state.target_map_type { {
if state.cur_map_type == state.target_map_type
{
return; return;
} }
let result = get_map_image(&heightmap, &biome_map, state.target_map_type); let result = get_map_image(&heightmap, &biome_map, state.target_map_type);
images.insert( images
.insert(
image.0.id(), image.0.id(),
Image::from_dynamic(result.into(), true, RenderAssetUsages::RENDER_WORLD), Image::from_dynamic(result.into(), true, RenderAssetUsages::RENDER_WORLD),
); )
.expect("Failed to update map image");
state.cur_map_type = state.target_map_type; state.cur_map_type = state.target_map_type;
} }
fn get_map_image(heightmap: &Map, biome_map: &BiomeMap, map_type: MapDisplayType) -> ImageBuffer<Rgba<u8>, Vec<u8>> { fn get_map_image(heightmap: &Map, biome_map: &BiomeMap, map_type: MapDisplayType) -> ImageBuffer<Rgba<u8>, Vec<u8>>
return match map_type { {
return match map_type
{
MapDisplayType::HeightMap => render_map(&heightmap, 0.1), MapDisplayType::HeightMap => render_map(&heightmap, 0.1),
MapDisplayType::Biomes => render_biome_map(&heightmap, &biome_map), MapDisplayType::Biomes => render_biome_map(&heightmap, &biome_map),
MapDisplayType::BiomeNoise => render_biome_noise_map(&biome_map, Vec3::ONE), MapDisplayType::BiomeNoise => render_biome_noise_map(&biome_map, Vec3::ONE),

View File

@@ -1,5 +1,5 @@
use bevy::{prelude::*, window::PrimaryWindow}; use bevy::{prelude::*, window::PrimaryWindow};
use bevy_rapier3d::{plugin::RapierContext, prelude::QueryFilter}; use bevy_rapier3d::{plugin::ReadRapierContext, prelude::QueryFilter};
use shared::{ use shared::{
resources::{TileContact, TileUnderCursor}, resources::{TileContact, TileUnderCursor},
tags::MainCamera, tags::MainCamera,
@@ -7,8 +7,10 @@ use shared::{
use world_generation::{hex_utils::HexCoord, prelude::Map, states::GeneratorState}; use world_generation::{hex_utils::HexCoord, prelude::Map, states::GeneratorState};
pub struct TileSelectionPlugin; pub struct TileSelectionPlugin;
impl Plugin for TileSelectionPlugin { impl Plugin for TileSelectionPlugin
fn build(&self, app: &mut App) { {
fn build(&self, app: &mut App)
{
app.init_resource::<TileUnderCursor>(); app.init_resource::<TileUnderCursor>();
app.add_systems( app.add_systems(
PreUpdate, PreUpdate,
@@ -20,42 +22,53 @@ impl Plugin for TileSelectionPlugin {
fn update_tile_under_cursor( fn update_tile_under_cursor(
cam_query: Single<(&GlobalTransform, &Camera), With<MainCamera>>, cam_query: Single<(&GlobalTransform, &Camera), With<MainCamera>>,
window: Single<&Window, With<PrimaryWindow>>, window: Single<&Window, With<PrimaryWindow>>,
// rapier_context: RapierContext, rapier: ReadRapierContext,
map: Res<Map>, map: Res<Map>,
mut tile_under_cursor: ResMut<TileUnderCursor>, mut tile_under_cursor: ResMut<TileUnderCursor>,
) { )
{
let (cam_transform, camera) = cam_query.into_inner(); let (cam_transform, camera) = cam_query.into_inner();
let Some(cursor_pos) = window.cursor_position() else { let Some(cursor_pos) = window.cursor_position()
else
{
return; return;
}; };
let Ok(cam_ray) = camera.viewport_to_world(cam_transform, cursor_pos) else { let Ok(cam_ray) = camera.viewport_to_world(cam_transform, cursor_pos)
else
{
return; return;
}; };
// let collision = rapier_context.cast_ray( let ctx = rapier.single().expect("Failed to get rapier read context");
// cam_ray.origin,
// cam_ray.direction.into(),
// 500.,
// true,
// QueryFilter::only_fixed(),
// );
// if let Some((_e, dist)) = collision { let collision = ctx.cast_ray(
// let contact_point = cam_ray.get_point(dist); cam_ray.origin,
// let contact_coord = HexCoord::from_world_pos(contact_point); cam_ray.direction.into(),
// //todo: handle correct tile detection when contacting a tile from the side 500.,
// if !map.is_in_bounds(&contact_coord) { true,
// tile_under_cursor.0 = None; QueryFilter::only_fixed(),
// return; );
// }
// let surface = map.sample_height(&contact_coord); if let Some((_e, dist)) = collision
// tile_under_cursor.0 = Some(TileContact::new( {
// contact_coord, let contact_point = cam_ray.get_point(dist);
// contact_point, let contact_coord = HexCoord::from_world_pos(contact_point);
// contact_coord.to_world(surface), //todo: handle correct tile detection when contacting a tile from the side
// )); if !map.is_in_bounds(&contact_coord)
// } else { {
// tile_under_cursor.0 = None; tile_under_cursor.0 = None;
// } return;
}
let surface = map.sample_height(&contact_coord);
tile_under_cursor.0 = Some(TileContact::new(
contact_coord,
contact_point,
contact_coord.to_world(surface),
));
}
else
{
tile_under_cursor.0 = None;
}
} }

View File

@@ -1,9 +1,9 @@
use bevy::reflect::Reflect; use bevy::reflect::Reflect;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use world_generation::hex_utils::HexCoord;
#[derive(Serialize, Deserialize, Debug, Reflect)] #[derive(Serialize, Deserialize, Debug, Reflect)]
pub struct ResourceIdentifier { pub struct ResourceIdentifier
{
pub id: u32, pub id: u32,
pub qty: u32, pub qty: u32,
} }

View File

@@ -1,6 +1,3 @@
use bevy::reflect::Reflect;
use serde::{Deserialize, Serialize};
pub mod assets; pub mod assets;
pub mod components; pub mod components;
pub mod nav_data; pub mod nav_data;
@@ -11,6 +8,7 @@ pub mod units_plugin;
pub mod units_spacial_set; pub mod units_spacial_set;
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub enum UnitType { pub enum UnitType
{
Basic, Basic,
} }