use crate::opengl::shader::{ Error as ShaderError, Kind as ShaderKind, Program as ShaderProgram, Shader, }; use crate::renderer::Renderable; use crate::transform::Transform; use crate::vector::Vec3; use crate::vertex::Vertex; #[derive(Debug)] pub struct Object { id: Id, renderable: Renderable, transform: Transform, } impl Object { /// Returns the object ID. #[must_use] pub fn id(&self) -> Id { self.id } #[must_use] pub fn position(&self) -> &Vec3 { self.transform.translation() } pub fn translate(&mut self, translation: Vec3) { self.transform.set_translation(translation); } pub fn scale(&mut self, scaling: Vec3) { self.transform.set_scaling(scaling); } pub(crate) fn renderable(&self) -> &Renderable { &self.renderable } pub(crate) fn transform(&self) -> &Transform { &self.transform } } /// Object builder. #[derive(Debug, Clone, Default)] pub struct Builder { vertices: Vec, indices: Option>, } impl Builder { /// Returns a new [`Object`] builder. #[must_use] pub fn new() -> Self { Self::default() } #[must_use] pub fn vertices(mut self, vertices: impl IntoIterator) -> Self { self.vertices = vertices.into_iter().collect(); self } #[must_use] pub fn indices(mut self, indices: impl IntoIterator) -> Self { self.indices = Some(indices.into_iter().collect()); self } /// Builds a new [`Object`]. /// /// # Errors /// Will return `Err` if: /// - Creating shaders fails /// - Linking the shader program fails pub fn build(&self, id: Id) -> Result { let vertex_shader = Self::create_shader(ShaderKind::Vertex, include_str!("../vertex.glsl")) .map_err(Error::CreateVertexShaderFailed)?; let fragment_shader = Self::create_shader(ShaderKind::Fragment, include_str!("../fragment.glsl")) .map_err(Error::CreateFragmentShaderFailed)?; let shader_program = ShaderProgram::new(); shader_program.attach(&vertex_shader); shader_program.attach(&fragment_shader); shader_program .link() .map_err(Error::LinkShaderProgramFailed)?; let renderable = Renderable::new(shader_program, &self.vertices, self.indices.as_deref()); let transform = Transform::new(); Ok(Object { id, renderable, transform }) } fn create_shader(kind: ShaderKind, source: &str) -> Result { let shader = Shader::new(kind); shader.set_source(source)?; shader.compile()?; Ok(shader) } } /// Object error #[derive(Debug, thiserror::Error)] pub enum Error { #[error("Failed to create vertex shader")] CreateVertexShaderFailed(#[source] ShaderError), #[error("Failed to create fragment shader")] CreateFragmentShaderFailed(#[source] ShaderError), #[error("Failed to link shader program")] LinkShaderProgramFailed(#[source] ShaderError), } /// Object ID. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Id { id: u16, } impl Id { /// Returns a new object ID. #[must_use] pub fn new(id: u16) -> Self { Self { id } } }