Skip to content

Expose magica voxel scene info #10

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

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
Binary file added .DS_Store
Binary file not shown.
9 changes: 8 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,22 @@ bevy = { version = "0.11.0", default-features = false, features = [
"bevy_render",
"bevy_asset",
] }
dot_vox = "4.1.0"
dot_vox = "5.1.1"
ndshape = "0.3.0"
block-mesh = "0.2.0"
ndcopy = "0.3.0"
anyhow = "1.0.38"

[dev-dependencies]
bevy = { version = "0.11.0" }
bevy-inspector-egui = "0.19.0"
bevy_egui = "0.21.0"

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


[[example]]
name = "boy"
path = "examples/boy.rs"
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,9 @@ Take a look in the `examples/` directory for a complete working example.
## Acknowledgements

This asset loader is powered by the awesome [`block-mesh-rs`](https://github.com/bonsairobo/block-mesh-rs) crate.


# ChangeLog
- Add more information read from vox. such as relationship between vox models in scene. see `examples/boy.rs`
- in example boy use Tab can toggle the faces.
- boy.vox copy from [teravit](https://teravit.app/en/contents/index.html?category=content-en&id=5854&platform=null%23#)
Binary file added assets/boy.vox
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just in case to not get into any legal trouble, what's the usage license for this ?

Binary file not shown.
174 changes: 174 additions & 0 deletions examples/boy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
use bevy::prelude::*;
use bevy_egui::EguiPlugin;
use bevy_inspector_egui::quick::WorldInspectorPlugin;
use bevy_vox_mesh::{vox_scene_info::VoxSceneInfo, VoxMeshPlugin};
use std::f32::consts::PI;

fn main() {
App::default()
.add_plugins(DefaultPlugins)
.add_plugins(EguiPlugin)
.add_plugins(WorldInspectorPlugin::new())
.add_plugins(VoxMeshPlugin::default())
.register_type::<Entity>()
.insert_resource(BoyMate {
handle: None,
mate: None,
})
.insert_resource(BoyEntity { boy_entity: None })
.insert_resource(FaceNow::default())
.add_systems(Startup, setup)
.add_systems(Update, (load_mate, load_boy, toggle_faces))
.run();
}

#[derive(Debug, Resource)]
pub struct BoyEntity {
pub boy_entity: Option<Entity>,
}

#[derive(Debug, Resource, Clone)]
pub struct BoyMate {
pub handle: Option<Handle<VoxSceneInfo>>,
pub mate: Option<VoxSceneInfo>,
}

#[derive(Debug, Resource, Clone)]
pub struct FaceNow {
pub now_face: &'static str,
}

impl Default for FaceNow {
fn default() -> Self {
Self { now_face: "face0" }
}
}

fn toggle_faces(
keyboard_input: Res<Input<KeyCode>>,
mut query: Query<(Entity, &Name, &mut Visibility)>,
mut face_now: ResMut<FaceNow>,
) {
let faces = vec!["face0", "face1", "face2", "face3"];
if keyboard_input.just_pressed(KeyCode::Tab) {
if let Some(index) = faces.iter().position(|&x| x == face_now.now_face) {
let next_index = if index == faces.len() - 1 {
0
} else {
index + 1
};
let next_face = faces[next_index];
for (_, name, mut visibility) in query.iter_mut() {
if faces.contains(&name.as_str()) {
if name.as_str() == next_face {
*visibility.as_mut() = Visibility::Inherited;
} else {
*visibility.as_mut() = Visibility::Hidden;
}
}
}
face_now.now_face = next_face;
}
}
}

fn load_boy(
mut commands: Commands,
boy_mate: Res<BoyMate>,
mut boy_entity: ResMut<BoyEntity>,
assets: Res<AssetServer>,
mut stdmats: ResMut<Assets<StandardMaterial>>,
mut mesh_assets: ResMut<Assets<Mesh>>,
) {
if let Some(_entity) = boy_entity.boy_entity {
// 这里可以进行其他的处理?
} else {
if let Some(mate_data) = boy_mate.mate.clone() {
if mate_data.all_loaded("boy.vox", mesh_assets.as_ref(), assets.as_ref()) {
// println!("这里生成模型的详情");
let boy = mate_data.to_entity(
"boy.vox",
&mut commands,
assets.as_ref(),
stdmats.add(Color::rgb(1., 1., 1.).into()),
&mut mesh_assets,
);
commands.entity(boy).insert((
Visibility::Inherited,
ComputedVisibility::HIDDEN,
GlobalTransform::IDENTITY,
Transform {
translation: Vec3 {
x: 0.0,
y: 1.0 / 40. * 40., // height is 80 so the button is scale*80/2
z: 0.0,
},
scale: Vec3 {
x: 1.0 / 40.,
y: 1.0 / 40.,
z: 1.0 / 40.,
},
..Default::default()
} * Transform::from_rotation(Quat::from_axis_angle(Vec3::Y, PI)),
));
boy_entity.boy_entity = Some(boy);
}
}
}
}

fn load_mate(mate_assets: Res<Assets<VoxSceneInfo>>, mut boy_mate: ResMut<BoyMate>) {
if let Some(handle) = boy_mate.handle.clone() {
match boy_mate.mate {
Some(_) => {}
None => {
if let Some(mate) = mate_assets.get(&handle) {
boy_mate.mate = Some(mate.clone());
}
}
}
}
}

fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut stdmats: ResMut<Assets<StandardMaterial>>,
mut boy_mate: ResMut<BoyMate>,
assets: Res<AssetServer>,
) {
let mate_data_handle: Handle<VoxSceneInfo> = assets.load("boy.vox#scene");
boy_mate.handle = Some(mate_data_handle);

commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
..Default::default()
});

commands.spawn(PointLightBundle {
point_light: PointLight {
intensity: 1500.0,
shadows_enabled: true,
..default()
},
transform: Transform::from_xyz(4.0, 8.0, 4.0),
..default()
});

commands.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Plane {
subdivisions: 2,
size: 5.0,
})),
material: stdmats.add(Color::rgb(0.3, 0.5, 0.3).into()),
..Default::default()
});

// commands.spawn(PbrBundle {
// transform: Transform::from_scale((0.01, 0.01, 0.01).into())
// * Transform::from_rotation(Quat::from_axis_angle(Vec3::Y, PI)),
// mesh: assets.load("boy.vox#model5"),
// material: stdmats.add(Color::rgb(1., 1., 1.).into()),
// ..Default::default()
// });
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ use block_mesh::{QuadCoordinateConfig, RIGHT_HANDED_Y_UP_CONFIG};
mod loader;
#[doc(inline)]
use loader::VoxLoader;
use vox_scene_info::VoxSceneInfo;

pub mod vox_scene_info;
mod mesh;
mod voxel;

Expand Down Expand Up @@ -61,6 +63,7 @@ impl Default for VoxMeshPlugin {

impl Plugin for VoxMeshPlugin {
fn build(&self, app: &mut App) {
app.add_asset::<VoxSceneInfo>();
app.add_asset_loader(VoxLoader {
config: self.config.clone(),
v_flip_face: self.v_flip_faces,
Expand Down
19 changes: 14 additions & 5 deletions src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ use anyhow::{anyhow, Error};
use bevy::asset::{AssetLoader, LoadContext, LoadedAsset};
use block_mesh::QuadCoordinateConfig;

use crate::vox_scene_info::VoxSceneInfo;


/// An asset loader capable of loading models in `.vox` files as usable [`bevy::render::mesh::Mesh`]es.
///
/// The meshes generated by this asset loader only use standard [`bevy::render::mesh::Mesh`] attributes for easier compatibility with shaders.
Expand All @@ -20,7 +23,7 @@ impl AssetLoader for VoxLoader {
load_context: &'a mut LoadContext,
) -> bevy::utils::BoxedFuture<'a, Result<(), Error>> {
Box::pin(async move {
self.process_vox_file(bytes, load_context)?;
self.process_vox_file(bytes, load_context).await?;
Ok(())
})
}
Expand All @@ -31,10 +34,10 @@ impl AssetLoader for VoxLoader {
}

impl VoxLoader {
fn process_vox_file<'a>(
async fn process_vox_file<'a, 'b>(
&self,
bytes: &'a [u8],
load_context: &'a mut LoadContext,
load_context: &'a mut LoadContext<'b>,
) -> Result<(), Error> {
let file = match dot_vox::load_bytes(bytes) {
Ok(data) => data,
Expand All @@ -44,14 +47,16 @@ impl VoxLoader {
let palette: Vec<[f32; 4]> = file
.palette
.iter()
.map(|color| color.to_le_bytes().map(|byte| byte as f32 / u8::MAX as f32))
.map(|color| {
let color_rgba: [u8; 4] = color.into();
color_rgba.map(|byte| byte as f32 / u8::MAX as f32)
})
.collect();

for (index, model) in file.models.iter().enumerate() {
let (shape, buffer) = crate::voxel::load_from_model(model);
let mesh =
crate::mesh::mesh_model(shape, &buffer, &palette, &self.config, self.v_flip_face);

match index {
0 => {
load_context.set_default_asset(LoadedAsset::new(mesh.clone()));
Expand All @@ -64,6 +69,10 @@ impl VoxLoader {
}
}
}
load_context.set_labeled_asset(
&format!("scene"),
LoadedAsset::new(VoxSceneInfo::new(file.scenes, file.layers)),
);

Ok(())
}
Expand Down
Loading