use std::mem::size_of_val; pub struct VertexBuffers { buffers: [gl::types::GLuint; CNT], } impl VertexBuffers { 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 Drop for VertexBuffers { 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, } } }