Files
rust-engine/src/vulkan/gameobject.rs
2021-10-22 08:46:29 +02:00

94 lines
3.0 KiB
Rust

use std::sync::Arc;
use cgmath::{Deg, Euler, Matrix4, Quaternion, Vector3};
use crate::game::GameState;
use crate::input::InputState;
use crate::vulkan::{RendererDescriptorSets, TextureHandle};
use crate::vulkan::{MeshHandle, VulkanRenderer};
use super::pipelines::vs;
#[derive(Clone)]
pub struct GameObject {
pub mesh_index: usize,
pub textures: TextureData,
pub position: Vector3<f32>,
pub rotation: Quaternion<f32>,
pub scale: Vector3<f32>,
pub children: Vec<GameObject>,
pub descriptor_sets: Vec<Arc<RendererDescriptorSets>>,
pub is_selected: bool,
pub pipeline_index: usize,
pub visible: bool,
}
#[derive(Clone)]
pub struct TextureData {
pub texture_index: TextureHandle,
pub normal_map_index: TextureHandle,
}
impl GameObject {
pub fn new(mesh: MeshHandle) -> GameObject {
let textures = TextureData {
texture_index: mesh.diffuse_handle,
normal_map_index: mesh.normal_handle.unwrap_or(0),
};
GameObject { mesh_index: mesh.index, textures, position: Vector3::new(0.0, 0.0, 0.0),
rotation: Quaternion::new(1.0, 0.0, 0.0, 0.0), scale: Vector3::new(1.0, 1.0, 1.0), children: vec![],
descriptor_sets: vec![], is_selected: false, pipeline_index: mesh.pipeline_index, visible: true }
}
pub fn init_descriptor_sets(&mut self, renderer: &mut VulkanRenderer) {
self.descriptor_sets = renderer.pipelines[self.pipeline_index].create_descriptor_set(&self.textures, renderer);
}
pub fn _set_position(&mut self, x: f32, y: f32, z: f32) {
self.position.x = x;
self.position.y = y;
self.position.z = z;
}
pub fn _set_scale(&mut self, x: f32, y: f32, z: f32) {
self.scale.x = x;
self.scale.y = y;
self.scale.z = z;
}
pub fn _set_rotation(&mut self, euler_x: f32, euler_y: f32, euler_z: f32) {
self.rotation = Quaternion::from(Euler::new(Deg(euler_x), Deg(euler_y), Deg(euler_z)));
}
pub fn _translate(&mut self, x: f32, y: f32, z: f32) {
self.position.x += x;
self.position.y += y;
self.position.z += z;
}
pub fn _rotate(&mut self, x: f32, y: f32, z: f32) {
self.rotation = self.rotation * Quaternion::from(Euler::new(Deg(x), Deg(y), Deg(z)));
}
pub fn get_push_constants(&self) -> vs::ty::PushConstants {
vs::ty::PushConstants {
model: self.get_model_matrix().into(),
is_selected: if self.is_selected { 1 } else { 0 },
}
}
pub fn get_model_matrix(&self) -> Matrix4<f32> {
let translation = Matrix4::from_translation(self.position);
let rotation: Matrix4<f32> = self.rotation.into();
let scale = Matrix4::from_nonuniform_scale(self.scale.x, self.scale.y, self.scale.z);
translation * rotation * scale
}
}
pub type GameObjectHandle = usize;
pub trait Updatable {
fn update(&mut self, delta_time: f32, input: &InputState, game_state: &mut GameState, game_objects: &mut Vec<GameObject>, renderer: &mut VulkanRenderer);
}