Skip to main content

example_2_triangle/
example_2_triangle.rs

1//! This example draws a triangle to the screen, by sending the vertex *positions* to the GPU and
2//! using a shader with a hardcoded
3
4use realms::data::Color;
5use realms::shader::{Shader, ShaderProgram, ShaderType};
6use realms::vertex::VertexBuffer;
7use realms::window::Window; // don't accidentally import realms::glfw::Window!
8
9fn main() {
10    // create the window and unwrap the result:
11    let mut window = Window::new(800, 600, "Hello Triangle!").expect("Failed to create window");
12
13    // create the shader program from the shaders `vertex2.glsl` and `fragment2.glsl`:
14    let shader_program = ShaderProgram::new(vec![
15        Shader::load_str(ShaderType::Vertex, include_str!("shaders/vertex2.glsl")).unwrap(),
16        Shader::load_str(ShaderType::Fragment, include_str!("shaders/fragment2.glsl")).unwrap(),
17    ])
18    .unwrap();
19    // NOTE: you need to code the `vertex2.glsl` and `fragment2.glsl` files. Some
20    // default shaders are provided for you, in the same directory as this file
21    // in the files `vertex2.glsl` and `fragment2.glsl`. You can copy and paste
22    // these into the SAME DIRECTORY as your example3_colorful_triangle file.
23
24    // create an [f32] slice of vertex data:
25    let vertices: [f32; 6] = [
26        // specify type `f32` with 6 elements.
27        //   X     Y
28        0.0, 0.5, // top of triangle
29        -0.5, -0.5, // bottom left of triangle
30        0.5, -0.5, // bottom right of triangle
31    ];
32
33    // Create a [u32] slice listing the indices of the `vertices` array to draw.
34    // Although in this case we only have one triangle, in scenes with many
35    // triangles this drastically reduces the size of data sent to the GPU.
36    // Read more at https://learnopengl.com/Getting-started/Hello-Triangle,
37    // scroll to the section on Element Buffer Objects.
38    let elements: [u32; 3] = [0, 1, 2];
39
40    // create a VertexBuffer using references to the `vertices` and `elements`:
41    let vb = VertexBuffer::new(&vertices, &elements);
42
43    // Tell Realms how each vertex is structured. Each vertex has a single
44    // component (a position) made up of TWO float components (x and y):
45    vb.set_layout(&[2]);
46
47    // loop until the user closes the window
48    while window.is_running() {
49        // swap the buffers (draw to the screen) and bind our shader program:
50        window.new_frame();
51
52        window.fill(Color::rgb(20, 34, 40)); // fill the screen dark blue
53        window.events(); // we don't handle any events, but we need to poll for them anyway.
54
55        vb.draw(&shader_program); // draw the data in our vertex buffer
56    }
57}