/
tutorial-04.rs
95 lines (81 loc) · 3.12 KB
/
tutorial-04.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#[macro_use]
extern crate glium;
use glium::Surface;
fn main() {
let event_loop = winit::event_loop::EventLoopBuilder::new()
.build()
.expect("event loop building");
let (window, display) = glium::backend::glutin::SimpleWindowBuilder::new()
.with_title("Glium tutorial #4")
.build(&event_loop);
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position);
let shape = vec![
Vertex { position: [-0.5, -0.5] },
Vertex { position: [ 0.0, 0.5] },
Vertex { position: [ 0.5, -0.25] }
];
let vertex_buffer = glium::VertexBuffer::new(&display, &shape).unwrap();
let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);
let vertex_shader_src = r#"
#version 140
in vec2 position;
uniform mat4 matrix;
void main() {
gl_Position = matrix * 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();
let mut t: f32 = 0.0;
event_loop.run(move |ev, window_target| {
match ev {
winit::event::Event::WindowEvent { event, .. } => match event {
winit::event::WindowEvent::CloseRequested => {
window_target.exit();
},
// We now need to render everyting in response to a RedrawRequested event due to the animation
winit::event::WindowEvent::RedrawRequested => {
// we update `t`
t += 0.02;
let x = t.sin() * 0.5;
let mut target = display.draw();
target.clear_color(0.0, 0.0, 1.0, 1.0);
let uniforms = uniform! {
matrix: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[ x, 0.0, 0.0, 1.0f32],
]
};
target.draw(&vertex_buffer, &indices, &program, &uniforms,
&Default::default()).unwrap();
target.finish().unwrap();
},
// Because glium doesn't know about windows we need to resize the display
// when the window's size has changed.
winit::event::WindowEvent::Resized(window_size) => {
display.resize(window_size.into());
},
_ => (),
},
// By requesting a redraw in response to a AboutToWait event we get continuous rendering.
// For applications that only change due to user input you could remove this handler.
winit::event::Event::AboutToWait => {
window.request_redraw();
},
_ => (),
}
})
.unwrap();
}