summaryrefslogtreecommitdiff
path: root/opengl-bindings/src/buffer.rs
blob: 66ab719de1e354bc2d648f462ee7b62b8b322831 (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
use std::marker::PhantomData;
use std::mem::size_of_val;
use std::ptr::null;

use safer_ffi::layout::ReprC;

use crate::CurrentContextWithFns;

#[derive(Debug)]
pub struct Buffer<Item: ReprC>
{
    buf: crate::sys::types::GLuint,
    _pd: PhantomData<Item>,
}

impl<Item: ReprC> Buffer<Item>
{
    #[must_use]
    pub fn new(current_context: &CurrentContextWithFns<'_>) -> Self
    {
        let mut buffer = crate::sys::types::GLuint::default();

        unsafe {
            current_context.fns().CreateBuffers(1, &raw mut buffer);
        };

        Self { buf: buffer, _pd: PhantomData }
    }

    /// Initializes this buffer with a size and a usage.
    ///
    /// # Errors
    /// Returns `Err` if the size (in bytes) is too large.
    pub fn init(
        &self,
        current_context: &CurrentContextWithFns<'_>,
        size: usize,
        usage: Usage,
    ) -> Result<(), Error>
    {
        let size: crate::sys::types::GLsizeiptr =
            size.try_into().map_err(|_| Error::SizeTooLarge {
                size,
                max_size: crate::sys::types::GLsizeiptr::MAX as usize,
            })?;

        unsafe {
            current_context.fns().NamedBufferData(
                self.buf,
                size,
                null(),
                usage.into_gl(),
            );
        }

        Ok(())
    }

    /// Stores items in this buffer.
    ///
    /// # Errors
    /// Returns `Err` if the total size (in bytes) is too large.
    pub fn store(
        &self,
        current_context: &CurrentContextWithFns<'_>,
        items: &[Item],
        usage: Usage,
    ) -> Result<(), Error>
    {
        let total_size = size_of_val(items);

        let total_size: crate::sys::types::GLsizeiptr =
            total_size.try_into().map_err(|_| Error::SizeTooLarge {
                size: total_size,
                max_size: crate::sys::types::GLsizeiptr::MAX as usize,
            })?;

        unsafe {
            current_context.fns().NamedBufferData(
                self.buf,
                total_size,
                items.as_ptr().cast(),
                usage.into_gl(),
            );
        }

        Ok(())
    }

    /// Stores items in this buffer, starting at a byte offset.
    ///
    /// # Errors
    /// Returns `Err` if the total size (in bytes) is too large.
    pub fn store_at_byte_offset(
        &self,
        current_context: &CurrentContextWithFns<'_>,
        byte_offset: usize,
        items: &[Item],
        // usage: Usage,
    ) -> Result<(), Error>
    {
        let total_size = size_of_val(items);

        let byte_offset: crate::sys::types::GLintptr =
            byte_offset
                .try_into()
                .map_err(|_| Error::ByteOffsetTooLarge {
                    byte_offset,
                    max_byte_offset: crate::sys::types::GLintptr::MAX as usize,
                })?;

        let total_size: crate::sys::types::GLsizeiptr =
            total_size.try_into().map_err(|_| Error::SizeTooLarge {
                size: total_size,
                max_size: crate::sys::types::GLsizeiptr::MAX as usize,
            })?;

        unsafe {
            current_context.fns().NamedBufferSubData(
                self.buf,
                byte_offset,
                total_size,
                items.as_ptr().cast(),
                // usage.into_gl(),
            );
        }

        Ok(())
    }

    /// Maps the values in the `values` slice into `Item`s which is stored into this
    /// buffer.
    ///
    /// # Errors
    /// Returns `Err` if the total size (in bytes) is too large.
    pub fn store_mapped<Value>(
        &self,
        current_context: &CurrentContextWithFns<'_>,
        values: &[Value],
        usage: Usage,
        mut map_func: impl FnMut(&Value) -> Item,
    ) -> Result<(), Error>
    {
        let item_size: crate::sys::types::GLsizeiptr = const {
            assert!(size_of::<Item>() <= crate::sys::types::GLsizeiptr::MAX as usize);

            size_of::<Item>().cast_signed()
        };

        let total_size = size_of::<Item>() * values.len();

        let total_size: crate::sys::types::GLsizeiptr =
            total_size.try_into().map_err(|_| Error::SizeTooLarge {
                size: total_size,
                max_size: crate::sys::types::GLsizeiptr::MAX as usize,
            })?;

        unsafe {
            current_context.fns().NamedBufferData(
                self.buf,
                total_size,
                null(),
                usage.into_gl(),
            );
        }

        for (index, value) in values.iter().enumerate() {
            let item = map_func(value);

            let offset = index * size_of::<Item>();

            let Ok(offset_casted) = crate::sys::types::GLintptr::try_from(offset) else {
                unreachable!(); // Reason: The total size can be casted to a GLintptr
                // (done above) so offsets should be castable as well
            };

            unsafe {
                current_context.fns().NamedBufferSubData(
                    self.buf,
                    offset_casted,
                    item_size,
                    (&raw const item).cast(),
                );
            }
        }

        Ok(())
    }

    pub fn delete(&self, current_context: &CurrentContextWithFns<'_>)
    {
        unsafe {
            current_context.fns().DeleteBuffers(1, &raw const self.buf);
        }
    }

    pub(crate) fn object(&self) -> crate::sys::types::GLuint
    {
        self.buf
    }
}

/// Buffer usage.
#[derive(Debug)]
pub enum Usage
{
    /// 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 Usage
{
    fn into_gl(self) -> crate::sys::types::GLenum
    {
        match self {
            Self::Stream => crate::sys::STREAM_DRAW,
            Self::Static => crate::sys::STATIC_DRAW,
            Self::Dynamic => crate::sys::DYNAMIC_DRAW,
        }
    }
}

#[derive(Debug)]
#[repr(u32)]
pub enum BindingTarget
{
    AtomicCounterBuffer = crate::sys::ATOMIC_COUNTER_BUFFER,
    TransformFeedbackBuffer = crate::sys::TRANSFORM_FEEDBACK_BUFFER,
    UniformBuffer = crate::sys::UNIFORM_BUFFER,
    ShaderStorageBuffer = crate::sys::SHADER_STORAGE_BUFFER,
}

#[derive(Debug, thiserror::Error)]
pub enum Error
{
    #[error("Size ({size}) is too large. Must be < {max_size}")]
    SizeTooLarge
    {
        size: usize, max_size: usize
    },

    #[error("Byte offset ({byte_offset}) is too large. Must be < {max_byte_offset}")]
    ByteOffsetTooLarge
    {
        byte_offset: usize,
        max_byte_offset: usize,
    },
}