Skip to main content

example_5_texture/
example_5_texture.rs

1//! This example will draw an image inside a square on the screen.
2
3// This example assumes you have also read example 3: triangle.
4// Many things are not explained here as they were explained in that example.
5
6use realms::data::Color;
7use realms::shader::{Shader, ShaderProgram, ShaderType};
8use realms::texture::Texture;
9use realms::vertex::VertexBuffer;
10use realms::window::Window;
11
12fn main() {
13    let mut window =
14        Window::new(600, 600, "Rendering Pictures?!").expect("Failed to create window");
15
16    let shader_program = ShaderProgram::new(vec![
17        Shader::load_str(ShaderType::Vertex, include_str!("shaders/vertex5.glsl")).unwrap(),
18        Shader::load_str(ShaderType::Fragment, include_str!("shaders/fragment5.glsl")).unwrap(),
19    ])
20    .unwrap();
21
22    let vertices: [f32; 16] = [
23        // specify type `f32` with 16 elements: 4 vertices * 4 floats each.
24        //        X     Y    texX texY
25        -0.5, 0.5, 0.0, 1.0, // top left of triangle, top left of texture
26        -0.5, -0.5, 0.0, 0.0, // bottom left of triangle, bottom left of texture
27        0.5, -0.5, 1.0, 0.0, // bottom right of triangle, bottom right of texture
28        0.5, 0.5, 1.0, 1.0, // top right of triangle, top right of texture
29    ];
30
31    let elements: [u32; 6] = [0, 1, 2, 2, 3, 0];
32
33    let vb = VertexBuffer::new(&vertices, &elements);
34
35    vb.set_layout(&[
36        2, // each vertex has a position, made up of TWO float components (x, y)
37        2, // each vertex has a texture position, made up of TWO float components (x, y)
38    ]);
39
40    let texture = Texture::load_file("examples/images/parrot.png").unwrap();
41    texture.bind();
42
43    while window.is_running() {
44        window.new_frame();
45        window.events();
46
47        window.fill(Color::rgb(39, 85, 163));
48        vb.draw(&shader_program);
49    }
50}