Rust glium ( OpenGL ) triangle and square
rust の glium ライブラリを利用して、三角と四角を同一ウィンドウに
表示します。
実行結果
プログラム
#[macro_use] extern crate glium; fn main() { use glium::{DisplayBuild, Surface}; let display = glium::glutin::WindowBuilder::new() .with_dimensions(800, 600) .with_title(format!("Glium Triangle and Square")) .build_glium().unwrap(); #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], } implement_vertex!(Vertex, position); // triangle let vertex1 = Vertex { position: [-0.75, -0.5] }; let vertex2 = Vertex { position: [-0.5 , 0.5] }; let vertex3 = Vertex { position: [-0.25, -0.5] }; let shape1 = vec![vertex1, vertex2, vertex3]; let vertex_buffer1 = glium::VertexBuffer::new(&display, &shape1).unwrap(); let indices1 = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList); //square let vertex1 = Vertex { position: [ 0.25, -0.5] }; let vertex2 = Vertex { position: [ 0.25, 0.5] }; let vertex3 = Vertex { position: [ 0.75, 0.5] }; let vertex4 = Vertex { position: [ 0.75, -0.5] }; let shape2 = vec![vertex1, vertex2, vertex3, vertex4]; let vertex_buffer2 = glium::VertexBuffer::new(&display, &shape2).unwrap(); let indices2 = glium::IndexBuffer::new(&display, glium::index::PrimitiveType::TrianglesList, &[0u16, 1, 2, 2, 0, 3,]).unwrap(); let vertex_shader_src = r#" #version 140 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } "#; let fragment_shader_src = r#" #version 140 out vec4 color; void main() { color = vec4(1.0, 0.0, 0.0, 1.0); } "#; let program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None).unwrap(); loop { let mut target = display.draw(); target.clear_color(0.0, 0.0, 1.0, 1.0); // triangle target.draw(&vertex_buffer1, &indices1, &program, &glium::uniforms::EmptyUniforms, &Default::default()).unwrap(); // square target.draw(&vertex_buffer2, &indices2, &program, &glium::uniforms::EmptyUniforms, &Default::default()).unwrap(); target.finish().unwrap(); for ev in display.poll_events() { match ev { glium::glutin::Event::Closed => return, _ => () } } } }
Cargo.toml
[package] name = "triangle" version = "0.1.0" authors = ["xxxxx"] [dependencies] glium = "*"
vertex, VertexBuffer, IndexBufferの設定
三角形と四角形のvertex, VertexBuffer, IndexBufferをそれぞれ準備します。
IndexBufferの設定では、三角形では頂点indexを使用しないのでNoIndicesを
使います。
四角形では頂点indexを使用しているので、IndexBufferを使います。
描画
target.draw()文を2回使って、三角形と四角形を描画します。