mod mesh; mod scene; mod shaders; use std::ops::Not; use ombre::derive::Packed; use ombre::prelude::*; pub use mesh::*; pub use scene::*; use crate::camera::Camera; #[derive(Debug)] pub enum Error { InvalidVertexId(u32), Backend(T), } impl From for Error { fn from(e: T) -> Self { Self::Backend(e) } } impl std::fmt::Display for Error where T: std::fmt::Display, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::InvalidVertexId(id) => write!(f, "invalid vertex id {id}"), Self::Backend(e) => e.fmt(f), } } } struct Pipeline { id: gfx::PipelineId, uniforms: U, } impl Pipeline { fn new(id: gfx::PipelineId, uniforms: U) -> Self { Self { id, uniforms } } } struct Pipelines { offscreen: Pipeline, display: Pipeline, gizmo: Pipeline, } struct Passes { offscreen: OffscreenPass, default: DefaultPass, } struct OffscreenPass { id: PassId, } struct DefaultPass { bindings: gfx::Bindings<0, 1>, } #[derive(Debug, Copy, Clone)] pub enum Component { Point(i32), Polygon(i32), Edge(i32), } impl From for i32 { fn from(value: Component) -> Self { match value { Component::Point(id) => id, Component::Polygon(id) => id, Component::Edge(id) => id, } } } struct ActiveState { pub node: NodeId, pub component: Option, } pub struct Renderer { pub scene: scene::Graph, pipelines: Pipelines, passes: Passes, viewport: Size, active: Option, backend: T, } impl Renderer { pub fn init(viewport: platform::LogicalSize, mut backend: T) -> Result { let viewport = Size::new(viewport.width, viewport.height); let passes = { let default = backend.texture(gfx::Texture { data: gfx::Empty, target: TextureKind::default(), size: viewport.map(|n| n.floor() as u32), access: gfx::TextureAccess::RenderTarget, wrap: gfx::TextureWrap::Clamp, format: gfx::TextureFormat::Rgba8, min_filter: FilterMode::Nearest, mag_filter: FilterMode::Nearest, })?; let ids = backend.texture(gfx::Texture { data: gfx::Empty, target: TextureKind::default(), size: viewport.map(|n| n.floor() as u32), access: gfx::TextureAccess::RenderTarget, wrap: gfx::TextureWrap::Clamp, format: gfx::TextureFormat::Signed, min_filter: FilterMode::Nearest, mag_filter: FilterMode::Nearest, })?; let depth = backend.texture(gfx::Texture { data: gfx::Empty, access: gfx::TextureAccess::RenderTarget, size: viewport.map(|n| n.floor() as u32), format: gfx::TextureFormat::Depth, ..Default::default() })?; let offscreen = backend.pass(gfx::PassDescriptor { color_attachments: &[default, ids], depth_attachment: Some(depth), })?; let bindings = gfx::Bindings { vertex: [], index: None, textures: [default], }; Passes { offscreen: OffscreenPass { id: offscreen }, default: DefaultPass { bindings }, } }; // Default pipeline for shading models. let default_shader = backend.shader(shaders::default::source(), shaders::default::description())?; let default_pipeline = backend.pipeline( default_shader, gfx::PipelineDescriptor { layout: &[ gfx::BufferLayout { attrs: &shaders::default::attributes()[0..=5], stride: Some(mesh::Vertex::stride()), ..gfx::BufferLayout::default() }, gfx::BufferLayout { attrs: &shaders::default::attributes()[6..=6], stride: None, ..gfx::BufferLayout::default() }, ], depth: Some(gfx::DepthState { compare: gfx::Comparison::LessOrEqual, offset: None, }), culling: gfx::CullMode::Nothing, ..gfx::PipelineDescriptor::default() }, )?; // Pipeline for rendering gizmos, like for manipulating objects. let gizmo_shader = backend.shader( shaders::constant::source(), shaders::constant::description(), )?; let gizmo_pipeline = backend.pipeline( gizmo_shader, gfx::PipelineDescriptor { layout: &[gfx::BufferLayout { attrs: &shaders::constant::attributes(), stride: Some(mesh::Vertex::stride()), ..gfx::BufferLayout::default() }], depth: Some(gfx::DepthState { compare: gfx::Comparison::LessOrEqual, offset: None, }), culling: gfx::CullMode::Nothing, ..gfx::PipelineDescriptor::default() }, )?; // Pipeline for rendering backbuffer to the screen. let display_shader = backend.shader(shaders::display::source(), shaders::display::description())?; let display_pipeline = backend.pipeline( display_shader, gfx::PipelineDescriptor { layout: &[], depth: None, culling: gfx::CullMode::Nothing, ..gfx::PipelineDescriptor::default() }, )?; Ok(Self { pipelines: Pipelines { offscreen: Pipeline::new( default_pipeline, shaders::default::Uniforms { model: Transform3D::default(), view: Transform3D::default(), proj: Transform3D::default(), light: Vector3D::new(5., 3., 2.), window_size: viewport.map(|n| n.floor() as f32), enable_tomemap: 0, render_mode: 1, object_id: 0, interaction_mode: InteractionMode::default().into(), vertex_hovered: -1, }, ), display: Pipeline::new(display_pipeline, ()), gizmo: Pipeline::new( gizmo_pipeline, shaders::constant::Uniforms { model: Transform3D::default(), view: Transform3D::default(), proj: Transform3D::default(), }, ), }, passes, active: None, scene: scene::Graph::default(), viewport, backend, }) } pub fn frame(&mut self, camera: &Camera) -> Result<(), Error> { let mut frame = self.backend.frame(); let proj = camera.projection(self.viewport.map(|n| n.floor() as f32)); let view = camera.view(); let model = Transform3D::rotation(30., Vector3D::new(0., 1., 0.)) * Transform3D::::rotation(30., Vector3D::new(1., 0., 0.)); // // Offscreen pass. // self.pipelines.offscreen.uniforms.model = model; self.pipelines.offscreen.uniforms.view = view; self.pipelines.offscreen.uniforms.proj = proj; self.pipelines.offscreen.uniforms.window_size = self.viewport.map(|n| n.floor() as f32); frame.begin_pass(self.passes.offscreen.id, gfx::PassAction::default()); frame.apply_pipeline(&self.pipelines.offscreen.id)?; for node in self.scene.iter() { if let scene::Object::Mesh { bindings, elements, style, mode, .. } = &node.object { self.pipelines.offscreen.uniforms.object_id = node.id.into(); self.pipelines.offscreen.uniforms.render_mode = style.into(); self.pipelines.offscreen.uniforms.interaction_mode = (*mode).into(); if let Some(hover) = &self.active { if hover.node == node.id { if let Some(c) = hover.component { self.pipelines.offscreen.uniforms.vertex_hovered = c.into(); } else { self.pipelines.offscreen.uniforms.vertex_hovered = -1; } } } frame.apply_uniforms(&self.pipelines.offscreen.uniforms)?; frame.apply_bindings(bindings)?; frame.draw(0, *elements, 1)?; } } frame.end_pass(); // // Default pass. // frame.begin_default_pass(gfx::PassAction::default(), self.viewport.map(|n| n as u32)); frame.apply_pipeline(&self.pipelines.display.id)?; frame.apply_uniforms(&self.pipelines.display.uniforms)?; frame.apply_bindings(&self.passes.default.bindings)?; frame.draw(0, 6, 1)?; // // Gizmo pipeline // self.pipelines.gizmo.uniforms.model = model; self.pipelines.gizmo.uniforms.view = view; self.pipelines.gizmo.uniforms.proj = proj; frame.apply_pipeline(&self.pipelines.gizmo.id)?; frame.apply_uniforms(&self.pipelines.gizmo.uniforms)?; for node in self.scene.iter() { if let scene::Object::Null = &node.object { // TODO } } frame.end_pass(); frame.commit(); Ok(()) } pub fn active(&mut self, node: NodeId, component: Option) { self.active = Some(ActiveState { node, component }); } #[allow(dead_code)] pub fn inactive(&mut self) { self.active = None; } pub fn model(&mut self, builder: ModelBuilder) -> Result> { let bindings = { let vbo = self.backend.buffer( gfx::BufferKind::Vertex, gfx::BufferUsage::Immutable, gfx::BufferSource::slice(&builder.mesh.vertices), )?; let svbo = self.backend.buffer( gfx::BufferKind::Vertex, gfx::BufferUsage::Dynamic, gfx::BufferSource::::zero(builder.mesh.vertices.len()), )?; let ibo = builder .mesh .indices .as_ref() .map(|i| { self.backend.buffer( gfx::BufferKind::Index, gfx::BufferUsage::Immutable, gfx::BufferSource::slice(i), ) }) .transpose()?; let blank = self.backend.texture(gfx::Texture { data: [Rgba8::WHITE].as_slice(), size: Size::new(1, 1), wrap: gfx::TextureWrap::Repeat, ..gfx::Texture::default() })?; gfx::Bindings { vertex: [vbo, svbo], index: ibo, textures: [blank, blank], } }; let node = Node::new(scene::Object::Mesh { bindings, selection: vec![Flag::NO; builder.mesh.vertices.len()], elements: builder.mesh.elements(), vertices: builder.mesh.vertices, style: RenderStyle::default(), mode: InteractionMode::default(), }); let id = node.id; let parent = self.scene.root().id; self.scene.insert(node, parent); Ok(id) } #[allow(dead_code)] pub fn color_at( &mut self, point: Point2D, ) -> Result>, Error> { if let Some(color) = self.at::>(point, 0)? { return Ok(Some(color)); } Ok(None) } pub fn vertex_at( &mut self, point: Point2D, ) -> Result, Error> { if let Some(id) = self.at::(point, 1)? { return Ok(id.checked_sub(1)); } Ok(None) } pub fn polygon_at( &mut self, point: Point2D, ) -> Result, Error> { if let Some(id) = self.at::(point, 1)? { if id.is_zero() { return Ok(None); } return Ok(Some(id)); } Ok(None) } pub fn node_at( &mut self, point: Point2D, ) -> Result, Error> { if let Some(pixel) = self.at::(point, 1)? { return Ok(NodeId::new(pixel)); } Ok(None) } pub fn window_resized(&mut self, size: platform::LogicalSize) -> Result<(), Error> { self.backend.window_resized(size); self.backend.pass_resize_attachments( self.passes.offscreen.id, Size::new(size.width as u32, size.height as u32), )?; self.viewport = Size::new(size.width, size.height); Ok(()) } pub fn at( &mut self, point: Point2D, index: usize, ) -> Result, Error> { // TODO: Use `MaybeUninit` (measure)? let mut output = vec![S::default(); self.viewport.area() as usize]; self.backend .pass_read_color_attachment(self.passes.offscreen.id, index, &mut output)?; // TODO: Use conversion functions instead. let y = self.viewport.h as usize - point.y as usize; let pixels = pixels::Pixels::new(&output, self.viewport.w as usize, self.viewport.h as usize); let pixel = pixels.get(point.x.floor() as usize, self.viewport.h as usize - y); if let Some(pixel) = pixel { return Ok(Some(*pixel)); } Ok(None) } pub fn select_vertices(&mut self, ixs: &[u32], node: NodeId) -> Result<(), Error> { if let Some(node) = self.scene.get_mut(&node) { match &mut node.object { Object::Mesh { bindings, selection, vertices, .. } => { for ix in ixs.iter() { // Find all vertices at this position, and select them. let pos = vertices .get(*ix as usize) .ok_or(Error::InvalidVertexId(*ix))? .position; for (i, v) in vertices.iter().enumerate() { if v.position == pos { selection[i] = Flag::YES; } } } // Update the selection buffer for this mesh. self.backend .buffer_update(bindings.vertex[1], BufferKind::Vertex, 0, selection) .map_err(Error::Backend)?; } _ => {} } } Ok(()) } pub fn select_polygons(&mut self, ids: &[u32], node: NodeId) -> Result<(), Error> { if let Some(node) = self.scene.get_mut(&node) { match &mut node.object { Object::Mesh { bindings, selection, vertices, .. } => { for id in ids.iter() { for (i, v) in vertices.iter().enumerate() { if v.polygon == *id { selection[i] = Flag::YES; } } } // Update the selection buffer for this mesh. self.backend .buffer_update(bindings.vertex[1], BufferKind::Vertex, 0, selection) .map_err(Error::Backend)?; } _ => {} } } Ok(()) } } pub struct ModelBuilder { mesh: Mesh, } impl ModelBuilder { pub fn cube(size: f32) -> Self { Self { mesh: Mesh::::cube(size), } } pub fn sphere() -> Self { Self { mesh: Mesh::::sphere(Rgba8::new(130, 47, 61, 255), 1.0, 12, 12), } } } /// On/off flag. Essentially a boolean in disguise, since GLSL shaders /// do not support booleans as input. #[derive(Debug, Copy, Clone, PartialEq, Default, Packed)] #[repr(C)] pub struct Flag(f32); impl Flag { pub const YES: Flag = Flag(1.0); pub const NO: Flag = Flag(0.0); } #[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] #[repr(u8)] pub enum InteractionMode { #[default] Objects = 0, Edges = 1, Points = 2, Polygons = 3, } impl InteractionMode { pub fn toggle(&mut self, mode: Self) { if *self == mode { *self = Self::Objects; } else { *self = mode; } } } impl From for u32 { fn from(rm: InteractionMode) -> Self { rm as u32 } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RenderStyle(u32); impl RenderStyle { pub const DIFFUSE: Self = Self(0b00000001); pub const FLAT_SHADED: Self = Self(0b00000010); pub const SPECULAR: Self = Self(0b00000100); pub const TEXTURED: Self = Self(0b00001000); pub const WIREFRAME: Self = Self(0b00010000); pub fn remove(&mut self, other: Self) { self.0 &= other.0.not(); } } impl std::ops::BitOr for RenderStyle { type Output = Self; fn bitor(self, rhs: Self) -> Self::Output { Self(self.0 | rhs.0) } } impl std::ops::BitOrAssign for RenderStyle { fn bitor_assign(&mut self, rhs: Self) { self.0 |= rhs.0 } } impl From<&RenderStyle> for u32 { fn from(rs: &RenderStyle) -> Self { rs.0 } } impl Default for RenderStyle { fn default() -> Self { Self::DIFFUSE | Self::SPECULAR } }