Camera, impl macro for "Childbearing" (really?)

This commit is contained in:
Dane Johnson 2022-04-15 13:15:39 -05:00
parent 2084d1eddb
commit 0e6cc64c89
2 changed files with 53 additions and 20 deletions

View File

@ -13,6 +13,30 @@ pub trait Childbearing<T> {
fn find_node(&mut self, name: &str) -> Option<&mut Box<T>>;
}
macro_rules! impl_childbearing {
($t:ty, $e:path) => {
impl Childbearing<$t> for Node {
fn add_child(&mut self, name: &str, child: $t) {
self.children.push(Node::new(name.to_string(), $e(Box::new(child))));
}
fn find_node(&mut self, name: &str) -> Option<&mut Box<$t>> {
match self.children.iter_mut().find(|node| node.name == name) {
Some(node) => {
if let $e(child) = &mut node.gameobject {
Some(child)
} else {
None
}
},
None => None,
}
}
}
}
}
impl Node {
pub fn new(name: String, gameobject: GameObject) -> Self {
Node {
@ -25,6 +49,7 @@ impl Node {
pub enum GameObject {
Null,
Camera(Box<Camera>),
Mesh(Box<Mesh>),
}
@ -50,6 +75,29 @@ pub trait Spatial {
fn set_transform(&mut self, transform: Transform);
}
pub struct Camera {
transform: Transform,
}
impl Camera {
pub fn new() -> Self {
Camera {
transform: Default::default(),
}
}
}
impl Spatial for Camera {
fn get_transform(&self) -> Transform {
self.transform
}
fn set_transform(&mut self, transform: Transform) {
self.transform = transform
}
}
impl_childbearing!(Camera, GameObject::Camera);
pub struct Mesh {
pub model: Model,
transform: Transform,
@ -73,21 +121,4 @@ impl Spatial for Mesh {
}
}
impl Childbearing<Mesh> for Node {
fn add_child(&mut self, name: &str, child: Mesh) {
self.children.push(Node::new(name.to_string(), GameObject::Mesh(Box::new(child))));
}
fn find_node(&mut self, name: &str) -> Option<&mut Box<Mesh>> {
match self.children.iter_mut().find(|node| node.name == name) {
Some(node) => {
if let GameObject::Mesh(mesh) = &mut node.gameobject {
Some(mesh)
} else {
None
}
},
None => None,
}
}
}
impl_childbearing!(Mesh, GameObject::Mesh);

View File

@ -31,6 +31,7 @@ fn main() {
let mut device_manager = crate::device::DeviceManager::new();
let mut root = Node::new("_root_".to_string(), GameObject::Null);
root.add_child("camera", Camera::new());
let mut cube = Mesh::new(Model::new(&display, "Box.glb"));
cube.set_transform(gameobject::Transform {
@ -89,17 +90,18 @@ fn main() {
} else if device_manager.is_pressed(&device::Key::D) {
transform.rotation.x -= 1.0 * delta;
}
cube.set_transform(transform);
let mvp = glm::perspective::<f32>(4.0/3.0, 45.0_f32.to_radians(), 0.2, 100.0);
let mvp = glm::translate::<f32>(&mvp, &cube.get_transform().position);
let mvp = glm::rotate_x(&mvp, cube.get_transform().rotation.x);
let uniforms = uniform! {
MVP: *mvp.as_ref(),
};
cube.model.draw(&mut target, &program, &uniforms, &params);
let _camera: &mut Box<Camera> = root.find_node("camera").unwrap();
target.finish().unwrap();
}