summaryrefslogtreecommitdiff
path: root/opengl-bindings/src/vertex_array.rs
blob: 9942fe75ee29ed776ee82e46c3341b9ac17abdf2 (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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use std::ffi::{c_int, c_void};
use std::mem::size_of;

use safer_ffi::layout::ReprC;

use crate::buffer::Buffer;
use crate::CurrentContextWithFns;

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

impl VertexArray
{
    #[must_use]
    pub fn new(current_context: &CurrentContextWithFns<'_>) -> Self
    {
        let mut array = 0;

        unsafe {
            current_context.fns().CreateVertexArrays(1, &raw mut array);
        }

        Self { array }
    }

    /// Draws the currently bound vertex array.
    ///
    /// # Errors
    /// Returns `Err` if:
    /// - `start_index` is too large
    /// - `cnt` is too large
    pub fn draw_arrays(
        current_context: &CurrentContextWithFns<'_>,
        primitive_kind: PrimitiveKind,
        start_index: u32,
        cnt: u32,
    ) -> Result<(), DrawError>
    {
        let start_index: crate::sys::types::GLint =
            start_index
                .try_into()
                .map_err(|_| DrawError::StartIndexValueTooLarge {
                    value: start_index,
                    max_value: crate::sys::types::GLint::MAX as u32,
                })?;

        let cnt: crate::sys::types::GLsizei =
            cnt.try_into().map_err(|_| DrawError::CountValueTooLarge {
                value: cnt,
                max_value: crate::sys::types::GLsizei::MAX as u32,
            })?;

        unsafe {
            current_context
                .fns()
                .DrawArrays(primitive_kind.into_gl(), start_index, cnt);
        }

        Ok(())
    }

    /// Draws the currently bound vertex array.
    ///
    /// # Errors
    /// Returns `Err` if `cnt` is too large.
    pub fn draw_elements(
        current_context: &CurrentContextWithFns<'_>,
        primitive_kind: PrimitiveKind,
        start_index: u32,
        cnt: u32,
    ) -> Result<(), DrawError>
    {
        let cnt: crate::sys::types::GLsizei =
            cnt.try_into().map_err(|_| DrawError::CountValueTooLarge {
                value: cnt,
                max_value: crate::sys::types::GLsizei::MAX as u32,
            })?;

        unsafe {
            current_context.fns().DrawElements(
                primitive_kind.into_gl(),
                cnt,
                crate::sys::UNSIGNED_INT,
                // TODO: Make this not sometimes UB. DrawElements expects a actual
                // pointer to a memory location when no VBO is bound.
                // See: https://stackoverflow.com/q/21706113
                std::ptr::without_provenance::<c_void>(start_index as usize),
            );
        }

        Ok(())
    }

    pub fn bind_element_buffer(
        &self,
        current_context: &CurrentContextWithFns<'_>,
        element_buffer: &Buffer<u32>,
    )
    {
        unsafe {
            current_context
                .fns()
                .VertexArrayElementBuffer(self.array, element_buffer.object());
        }
    }

    pub fn bind_vertex_buffer<VertexT: ReprC>(
        &self,
        current_context: &CurrentContextWithFns<'_>,
        binding_index: u32,
        vertex_buffer: &Buffer<VertexT>,
        offset: isize,
    )
    {
        let vertex_size = const { cast_usize_to_c_int(size_of::<VertexT>()) };

        unsafe {
            current_context.fns().VertexArrayVertexBuffer(
                self.array,
                binding_index,
                vertex_buffer.object(),
                offset,
                vertex_size,
            );
        }
    }

    pub fn enable_attrib(
        &self,
        current_context: &CurrentContextWithFns<'_>,
        attrib_index: u32,
    )
    {
        unsafe {
            current_context.fns().EnableVertexArrayAttrib(
                self.array,
                attrib_index as crate::sys::types::GLuint,
            );
        }
    }

    pub fn set_attrib_format(
        &self,
        current_context: &CurrentContextWithFns<'_>,
        attrib_index: u32,
        data_type: DataType,
        normalized: bool,
        offset: u32,
    )
    {
        unsafe {
            current_context.fns().VertexArrayAttribFormat(
                self.array,
                attrib_index,
                data_type.size(),
                data_type as u32,
                if normalized {
                    crate::sys::TRUE
                } else {
                    crate::sys::FALSE
                },
                offset,
            );
        }
    }

    /// Associate a vertex attribute and a vertex buffer binding.
    pub fn set_attrib_vertex_buf_binding(
        &self,
        current_context: &CurrentContextWithFns<'_>,
        attrib_index: u32,
        vertex_buf_binding_index: u32,
    )
    {
        unsafe {
            current_context.fns().VertexArrayAttribBinding(
                self.array,
                attrib_index,
                vertex_buf_binding_index,
            );
        }
    }

    pub fn bind(&self, current_context: &CurrentContextWithFns<'_>)
    {
        unsafe { current_context.fns().BindVertexArray(self.array) }
    }
}

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

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

#[derive(Debug, Clone, Copy)]
#[repr(u32)]
pub enum DataType
{
    Float = crate::sys::FLOAT,
}

impl DataType
{
    fn size(self) -> crate::sys::types::GLint
    {
        match self {
            Self::Float => const { cast_usize_to_c_int(size_of::<f32>()) },
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum DrawError
{
    #[error("Start index value {value} is too large. Must be < {max_value}")]
    StartIndexValueTooLarge
    {
        value: u32, max_value: u32
    },

    #[error("Count value {value} is too large. Must be < {max_value}")]
    CountValueTooLarge
    {
        value: u32, max_value: u32
    },
}

const fn cast_usize_to_c_int(num: usize) -> c_int
{
    assert!(num <= c_int::MAX.cast_unsigned() as usize);

    c_int::from_ne_bytes(shorten_byte_array(num.to_ne_bytes()))
}

const fn shorten_byte_array<const SRC_LEN: usize, const DST_LEN: usize>(
    src: [u8; SRC_LEN],
) -> [u8; DST_LEN]
{
    assert!(DST_LEN < SRC_LEN);

    let mut ret = [0; DST_LEN];

    ret.copy_from_slice(src.split_at(DST_LEN).0);

    ret
}