summaryrefslogtreecommitdiff
path: root/engine/src/renderer/vertex_buffers.rs
blob: a6d1a2c12f174100e04ad76cba46303dbf51f63b (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
use std::mem::size_of_val;

pub struct VertexBuffers<const CNT: usize>
{
    buffers: [gl::types::GLuint; CNT],
}

impl<const CNT: usize> VertexBuffers<CNT>
{
    pub fn new() -> Self
    {
        let mut buffers = [gl::types::GLuint::default(); CNT];

        unsafe {
            #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
            gl::GenBuffers(CNT as gl::types::GLsizei, buffers.as_mut_ptr());
        };

        Self { buffers }
    }

    pub fn store(
        &self,
        buffer_index: usize,
        vertices: &[f32],
        usage: BufferUsage,
    ) -> Option<()>
    {
        let buffer = *self.buffers.get(buffer_index)?;

        unsafe {
            gl::BindBuffer(gl::ARRAY_BUFFER, buffer);
        }

        unsafe {
            #[allow(clippy::cast_possible_wrap)]
            gl::BufferData(
                gl::ARRAY_BUFFER,
                size_of_val(vertices) as gl::types::GLsizeiptr,
                vertices.as_ptr().cast(),
                usage.into_gl(),
            );
        }

        Some(())
    }
}

impl<const CNT: usize> Drop for VertexBuffers<CNT>
{
    fn drop(&mut self)
    {
        #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
        unsafe {
            gl::DeleteBuffers(CNT as gl::types::GLsizei, self.buffers.as_ptr());
        }
    }
}

#[allow(dead_code)]
pub enum BufferUsage
{
    /// The buffer data is set only once and used by the GPU at most a few times.
    Stream,

    /// The buffer data is set only once and used many times.
    Static,

    /// The buffer data is changed a lot and used many times.
    Dynamic,
}

impl BufferUsage
{
    fn into_gl(self) -> gl::types::GLenum
    {
        match self {
            Self::Stream => gl::STREAM_DRAW,
            Self::Static => gl::STATIC_DRAW,
            Self::Dynamic => gl::DYNAMIC_DRAW,
        }
    }
}