summaryrefslogtreecommitdiff
path: root/engine/src/renderer/vertex_array.rs
blob: b0aac81ec418491653b2655b66c773a2ad1a996d (plain)
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
use std::mem::size_of;

use crate::vertex::{Attribute, AttributeComponentType, Vertex};

const VERTEX_STRIDE: usize = size_of::<Vertex>();

#[derive(Debug)]
pub struct VertexArray
{
    array: gl::types::GLuint,
}

impl VertexArray
{
    pub fn new() -> Self
    {
        let mut array = 0;

        unsafe {
            gl::GenVertexArrays(1, &mut array);
        }

        Self { array }
    }

    pub fn draw(&self, primitive_kind: PrimitiveKind, start_index: u32, index_cnt: u32)
    {
        self.bind();

        unsafe {
            #[allow(clippy::cast_possible_wrap)]
            gl::DrawArrays(
                primitive_kind.into_gl(),
                start_index as gl::types::GLint,
                index_cnt as gl::types::GLsizei,
            );
        }
    }

    pub fn configure_attrs()
    {
        let mut offset = 0;

        for attr in Vertex::attrs() {
            Self::vertex_attrib_ptr(attr, offset);

            Self::enable_vertex_attrib_array(attr.index);

            offset += attr.component_size * attr.component_cnt as usize;
        }
    }

    pub fn bind(&self)
    {
        unsafe { gl::BindVertexArray(self.array) }
    }

    fn vertex_attrib_ptr(vertex_attr: &Attribute, offset: usize)
    {
        unsafe {
            #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
            gl::VertexAttribPointer(
                vertex_attr.index as gl::types::GLuint,
                vertex_attr.component_cnt as i32,
                Self::vertex_attr_type_to_gl(&vertex_attr.component_type),
                gl::FALSE,
                VERTEX_STRIDE as gl::types::GLsizei,
                offset as *const _,
            );
        }
    }

    fn enable_vertex_attrib_array(index: usize)
    {
        unsafe {
            #[allow(clippy::cast_possible_truncation)]
            gl::EnableVertexAttribArray(index as gl::types::GLuint);
        }
    }

    fn vertex_attr_type_to_gl(
        vertex_attr_type: &AttributeComponentType,
    ) -> gl::types::GLenum
    {
        match vertex_attr_type {
            AttributeComponentType::Float => gl::FLOAT,
        }
    }
}

impl Drop for VertexArray
{
    fn drop(&mut self)
    {
        unsafe {
            gl::DeleteVertexArrays(1, &self.array);
        }
    }
}

#[derive(Debug)]
pub enum PrimitiveKind
{
    Triangles,
}

impl PrimitiveKind
{
    fn into_gl(self) -> gl::types::GLenum
    {
        match self {
            Self::Triangles => gl::TRIANGLES,
        }
    }
}