Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bevy integration #23

Draft
wants to merge 10 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -552,4 +552,4 @@ target
*.swp
*.iml

gaiku-3d/examples/output
**/**/output
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ serialization = ["gaiku_common/serialization"]

[dependencies]
gaiku_common = { path = "crates/gaiku_common", version = "0.1.0" }

# Bakers
gaiku_baker_heightmap = { path = "crates/gaiku_baker_heightmap", version = "0.1.0", optional = true }
gaiku_baker_marching_cubes = { path = "crates/gaiku_baker_marching_cubes", version = "0.1.0", optional = true }
Expand Down
2 changes: 1 addition & 1 deletion crates/gaiku_common/src/chunk/chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
};

/// Provides a `Chunkify` implementation with index and value support `(u8, u8)`.
#[derive(Debug, Clone)]
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Chunk {
position: [f32; 3],
Expand Down
2 changes: 1 addition & 1 deletion crates/gaiku_common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! work with different file formats and mesh generators, based on voxels.
use std::fs::read;

pub use anyhow::Result;
pub use anyhow::{self, Result};
pub use mint;

use crate::{
Expand Down
1 change: 1 addition & 0 deletions crates/gaiku_format_png/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use gaiku_common::{prelude::*, Result};
use image::load_from_memory;

/// Converts a `png` file to 2d chunk data.
#[derive(Default)]
pub struct PNGReader;

impl FileFormat for PNGReader {
Expand Down
30 changes: 30 additions & 0 deletions integrations/gaiku_bevy/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
[package]
name = "gaiku_bevy"
version = "0.1.0"
authors = ["norman784 <[email protected]>"]
edition = "2018"

[dependencies]
bevy_app = "0.5.0"
bevy_asset = "0.5.0"
bevy_ecs = "0.5.0"
bevy_math = "0.5.0"
bevy_pbr = "0.5.0"
bevy_render = "0.5.0"
bevy_scene = "0.5.0"
bevy_transform = "0.5.0"
bevy_utils = "0.5.0"
gaiku_common = { path = "../../crates/gaiku_common", version = "0.1.0" }
png = "0.16.8"
anyhow = "1.0.42"

[[example]]
name = "terrain"
path = "examples/terrain.rs"

[dev-dependencies]
bevy = "0.5.0"
gaiku_baker_voxel = { path = "../../crates/gaiku_baker_voxel", version = "0.1.0" }
gaiku_baker_marching_cubes = { path = "../../crates/gaiku_baker_marching_cubes", version = "0.1.0" }
gaiku_baker_modified_marching_cubes = { path = "../../crates/gaiku_baker_modified_marching_cubes", version = "0.1.0" }
gaiku_format_gox = { path = "../../crates/gaiku_format_gox", version = "0.1.0" }
Binary file added integrations/gaiku_bevy/assets/terrain.gox
Binary file not shown.
46 changes: 46 additions & 0 deletions integrations/gaiku_bevy/examples/terrain.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use bevy::prelude::*;
use gaiku_common::chunk::Chunk;
use gaiku_baker_voxel::VoxelBaker;
use gaiku_bevy::*;

struct CameraRotation {
angle: f32,
}

fn setup(commands: &mut Commands, asset_server: Res<AssetServer>) {
commands
.spawn((
Transform::default(),
GlobalTransform::default(),
CameraRotation { angle: 0.0 },
))
.with_children(|parent| {
parent.spawn(Camera3dBundle {
transform: Transform::from_translation(Vec3::new(0.0, 120.0, -200.0))
.looking_at(Vec3::default(), Vec3::unit_y()),
..Default::default()
});
})
.spawn_scene(asset_server.load("terrain.gox"))
.spawn(LightBundle {
transform: Transform::from_translation(Vec3::new(0.0, 50.0, 50.0)),
..Default::default()
});
}

fn rotate_terrain(time: Res<Time>, mut query: Query<(&mut CameraRotation, &mut Transform)>) {
for (mut rotation, mut transform) in &mut query.iter_mut() {
rotation.angle += 10.0 * time.delta_seconds();
transform.rotation = Quat::from_rotation_y(rotation.angle.to_radians());
}
}

fn main() {
App::build()
.add_resource(Msaa { samples: 4 })
.add_plugins(DefaultPlugins)
.add_plugin(GaikuPlugin::<GoxReader, VoxelBaker, Chunk>::default())
.add_startup_system(setup.system())
.add_system(rotate_terrain.system())
.run();
}
10 changes: 10 additions & 0 deletions integrations/gaiku_bevy/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
mod mesh;
mod plugin;
mod texture;

pub use mesh::*;
pub use plugin::*;
pub use texture::*;

#[derive(Default)]
pub struct GaikuTerrain;
96 changes: 96 additions & 0 deletions integrations/gaiku_bevy/src/mesh.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
use bevy_render::{
mesh::{Indices, VertexAttributeValues},
pipeline::PrimitiveTopology,
prelude::Mesh,
};
use gaiku_common::prelude::*;

pub struct GaikuMesh {
indices: Vec<u32>,
positions: Vec<[f32; 3]>,
normals: Vec<[f32; 3]>,
uvs: Vec<[f32; 2]>,
}

impl Meshify for GaikuMesh {
fn new() -> Self {
Self::with(vec![], vec![], vec![], vec![])
}

fn with(
indices: Vec<u32>,
positions: Vec<[f32; 3]>,
normals: Vec<[f32; 3]>,
uvs: Vec<[f32; 2]>,
) -> Self {
Self {
indices,
positions,
normals,
uvs,
}
}

fn get_indices(&self) -> &Vec<u32> {
&self.indices
}

fn get_normals(&self) -> &Vec<[f32; 3]> {
&self.normals
}

fn get_positions(&self) -> &Vec<[f32; 3]> {
&self.positions
}

fn get_uvs(&self) -> &Vec<[f32; 2]> {
&self.uvs
}

fn set_indices(&mut self, indices: Vec<u32>) {
self.indices = indices;
}

fn set_normals(&mut self, normals: Vec<[f32; 3]>) {
self.normals = normals;
}

fn set_positions(&mut self, positions: Vec<[f32; 3]>) {
self.positions = positions;
}

fn set_uvs(&mut self, uvs: Vec<[f32; 2]>) {
self.uvs = uvs;
}
}

impl Into<Mesh> for GaikuMesh {
fn into(self) -> Mesh {
let mut mesh = Mesh::new(PrimitiveTopology::TriangleList);

if !self.indices.is_empty() {
mesh.set_indices(Some(Indices::U32(self.indices.clone())));
}

mesh.set_attribute(
Mesh::ATTRIBUTE_POSITION,
VertexAttributeValues::Float3(self.positions.clone()),
);

if !self.normals.is_empty() {
mesh.set_attribute(
Mesh::ATTRIBUTE_NORMAL,
VertexAttributeValues::Float3(self.normals.clone()),
);
}

if !self.uvs.is_empty() {
mesh.set_attribute(
Mesh::ATTRIBUTE_UV_0,
VertexAttributeValues::Float2(self.uvs),
);
}

mesh
}
}
130 changes: 130 additions & 0 deletions integrations/gaiku_bevy/src/plugin.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
use std::marker::PhantomData;

use anyhow;
use bevy_app::{AppBuilder, Plugin};
use bevy_asset::{AddAsset, AssetLoader, AssetPath, LoadContext, LoadedAsset};
use bevy_ecs::prelude::World;
use bevy_pbr::prelude::{PbrBundle, StandardMaterial};
use bevy_render::prelude::{Color, Mesh, Texture};
use bevy_scene::Scene;
use bevy_transform::prelude::Transform;
use bevy_utils::BoxedFuture;
use gaiku_common::prelude::*;

use crate::{GaikuMesh, GaikuTexture};

#[derive(Default)]
pub struct GaikuPlugin<F, B, C>
where
F: FileFormat + Send + Sync + 'static + Default,
B: Baker + Send + Sync + 'static + Default,
C: Chunkify<F::Value> + ChunkifyMut<F::Value> + Atlasify<B::AtlasValue> + AtlasifyMut<B::AtlasValue> + Boxify + Sizable + Send + Sync + 'static + Default,
{
file_format: PhantomData<F>,
baker: PhantomData<B>,
chunk: PhantomData<C>,
}

impl<F, B, C> Plugin for GaikuPlugin<F, B, C>
where
F: FileFormat + Send + Sync + 'static + Default,
B: Baker + Send + Sync + 'static + Default,
C: Chunkify<F::Value> + ChunkifyMut<F::Value> + Atlasify<B::AtlasValue> + AtlasifyMut<B::AtlasValue> + Boxify + Sizable + Send + Sync + 'static + Default,
{
fn build(&self, app: &mut AppBuilder) {
app.init_asset_loader::<GaikuAssetLoader<F, B, C>>();
}
}

#[derive(Default)]
pub struct GaikuAssetLoader<F, B, C>
where
F: FileFormat + Send + Sync + 'static + Default,
B: Baker + Send + Sync + 'static + Default,
C: Chunkify<F::Value> + ChunkifyMut<F::Value> + Atlasify<B::AtlasValue> + AtlasifyMut<B::AtlasValue> + Boxify + Sizable + Send + Sync + 'static + Default,
{
file_format: PhantomData<F>,
baker: PhantomData<B>,
chunk: PhantomData<C>,
}

impl<F, B, C> AssetLoader for GaikuAssetLoader<F, B, C>
where
F: FileFormat + Send + Sync + 'static + Default,
B: Baker + Send + Sync + 'static + Default,
C: Chunkify<F::Value> + ChunkifyMut<F::Value> + Atlasify<B::AtlasValue> + AtlasifyMut<B::AtlasValue> + Boxify + Sizable + Send + Sync + 'static + Default,
{
fn load<'a>(
&'a self,
bytes: &'a [u8],
load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, Result<(), anyhow::Error>> {
Box::pin(async move {
let mut world = World::default();

let (chunks, atlas) = F::load::<C, GaikuTexture>(bytes.to_vec())?;

let texture_label = "test_texture.png";

let loaded_asset = if let Some(atlas) = &atlas {
atlas
.get_texture()
.write_to_file("output/terrain_texture.png")?;
let texture: Texture = atlas.get_texture().into();
LoadedAsset::new(texture)
} else {
LoadedAsset::new(Texture::default())
};

load_context.set_labeled_asset(texture_label, loaded_asset);

let material_label = "ChunkAtlas";
load_context.set_labeled_asset(
material_label,
LoadedAsset::new(StandardMaterial {
base_color: Color::WHITE,
base_color_texture: Some(
load_context.get_handle(AssetPath::new_ref(load_context.path(), Some(texture_label))),
),
..Default::default()
}),
);

let baker_options = BakerOptions {
texture: atlas,
..Default::default()
};

world.spawn_batch(chunks.iter().map(|chunk| {
let mesh = B::bake::<C, GaikuTexture, GaikuMesh>(chunk, &baker_options)
.expect("Expected mesh to be baked");

if let Some(mesh) = mesh {
let mesh: Mesh = mesh.into();

let name = format!("Chunk{:?}", chunk.position());
load_context.set_labeled_asset(&name, LoadedAsset::new(mesh));
}

let name = format!("Chunk{:?}", &chunk.position());
let mesh_asset_path = AssetPath::new_ref(load_context.path(), Some(&name));
let material_asset_path = AssetPath::new_ref(load_context.path(), Some(material_label));

PbrBundle {
mesh: load_context.get_handle(mesh_asset_path),
material: load_context.get_handle(material_asset_path),
transform: Transform::from_translation(chunk.position().into()),
..Default::default()
}
}));

load_context.set_default_asset(LoadedAsset::new(Scene::new(world)));

Ok(())
})
}

fn extensions(&self) -> &[&str] {
&["gox"]
}
}
Loading