canary-rs/apps/magpie/src/gl.rs

103 lines
2.6 KiB
Rust
Raw Normal View History

2022-10-29 23:23:56 +00:00
use canary::DrawCommand;
2022-10-28 02:15:47 +00:00
use glium::{glutin, Display, Surface};
#[derive(Copy, Clone)]
pub struct Vertex {
pub position: [f32; 2],
pub color: [u8; 4],
}
glium::implement_vertex!(Vertex, position normalize(false), color normalize(true));
impl From<&canary::MeshVertex> for Vertex {
fn from(v: &canary::MeshVertex) -> Self {
let (r, g, b, a) = v.color.to_rgba_unmultiplied();
Self {
position: [v.position.x, v.position.y],
color: [r, g, b, a],
}
}
}
const VERTEX_SHADER_SRC: &str = r#"
#version 330
in vec2 position;
in vec4 color;
out vec4 frag_color;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
frag_color = color;
}
"#;
const FRAGMENT_SHADER_SRC: &str = r#"
#version 330
in vec4 frag_color;
out vec4 fb_color;
void main() {
fb_color = frag_color;
}
"#;
pub struct Graphics {
2022-10-29 23:23:56 +00:00
pub display: glium::Display,
2022-10-28 02:15:47 +00:00
pub program: glium::Program,
}
impl Graphics {
2022-10-29 23:23:56 +00:00
pub fn new(display: glium::Display) -> Self {
2022-10-28 02:15:47 +00:00
let program =
2022-10-29 23:23:56 +00:00
glium::Program::from_source(&display, VERTEX_SHADER_SRC, FRAGMENT_SHADER_SRC, None)
2022-10-28 02:15:47 +00:00
.unwrap();
2022-10-29 23:23:56 +00:00
Self { display, program }
}
pub fn draw(&mut self, commands: &[DrawCommand]) {
let mut joined_vs: Vec<Vertex> = Vec::new();
let mut joined_is = Vec::new();
for command in commands.iter() {
match command {
canary::DrawCommand::Mesh { vertices, indices } => {
let voff = joined_vs.len() as canary::MeshIndex;
joined_vs.extend(vertices.iter().map(Vertex::from));
joined_is.extend(indices.iter().map(|i| i + voff));
}
_ => unimplemented!(),
}
}
let vertex_buffer = glium::VertexBuffer::new(&self.display, &joined_vs).unwrap();
let index_buffer = glium::IndexBuffer::new(
&self.display,
glium::index::PrimitiveType::TrianglesList,
&joined_is,
)
.unwrap();
let params = glium::DrawParameters {
blend: glium::Blend::alpha_blending(),
..Default::default()
};
let mut target = self.display.draw();
target.clear_color(0.0, 0.0, 0.0, 1.0);
target
.draw(
&vertex_buffer,
&index_buffer,
&self.program,
&glium::uniforms::EmptyUniforms,
&params,
)
.unwrap();
target.finish().unwrap();
2022-10-28 02:15:47 +00:00
}
}