siftgl 0.1.0

Memory-safe, ergonomic, zero-dependency, security-hardened OpenGL 3.3-4.6 Core frontend for Rust
Documentation
//! Vertex Array Objects (VAOs) and validated vertex attribute layout descriptors.

use std::ffi::c_void;
use std::fmt;
use std::rc::Rc;

use crate::buffer::Buffer;
use crate::context::{GlContext, GlInner};
use crate::error::{checked_sizei, GlError, Result};
use crate::sys;
use crate::types::{BufferTarget, DataType};

/// Descriptor for a single vertex attribute binding in a [`VertexArray`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VertexAttribDesc {
    /// Generic vertex attribute index (`layout(location = index)`).
    pub location: u32,
    /// Number of scalar components per vertex (`1`, `2`, `3`, or `4`).
    pub components: u8,
    /// Scalar element type.
    pub data_type: DataType,
    /// Whether fixed-point integer data should be normalized to `[-1, 1]` or `[0, 1]`.
    pub normalized: bool,
    /// Byte stride between consecutive vertex elements (`0` = tightly packed).
    pub stride: usize,
    /// Byte offset of this attribute within each vertex record.
    pub offset: usize,
}

/// RAII wrapper around an OpenGL Vertex Array Object (`VAO`).
pub struct VertexArray {
    ctx: Rc<GlInner>,
    id: sys::GLuint,
}

impl fmt::Debug for VertexArray {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VertexArray").field("id", &self.id).finish()
    }
}

impl Drop for VertexArray {
    fn drop(&mut self) {
        if self.id != 0 {
            // SAFETY: `self.id` is exclusively owned by this `VertexArray`.
            unsafe { (self.ctx.fns.delete_vertex_arrays)(1, &self.id) };
        }
    }
}

impl VertexArray {
    /// Allocates a new OpenGL Vertex Array Object (`glGenVertexArrays`).
    pub fn new(ctx: &GlContext) -> Result<Self> {
        let mut id: sys::GLuint = 0;
        // SAFETY: Generates one VAO name in valid stack storage.
        unsafe { (ctx.inner.fns.gen_vertex_arrays)(1, &mut id) };
        if id == 0 {
            return Err(GlError::ObjectCreationFailed {
                object: "VertexArray",
            });
        }
        Ok(Self {
            ctx: Rc::clone(&ctx.inner),
            id,
        })
    }

    /// Returns the raw OpenGL VAO ID.
    #[inline]
    pub const fn raw_id(&self) -> u32 {
        self.id
    }

    /// Binds this VAO to the current context (`glBindVertexArray`).
    #[inline]
    pub fn bind(&self) {
        // SAFETY: `self.id` is a valid VAO handle.
        unsafe { (self.ctx.fns.bind_vertex_array)(self.id) };
    }

    /// Unbinds any active VAO (`glBindVertexArray(0)`).
    #[inline]
    pub fn unbind(ctx: &GlContext) {
        // SAFETY: `0` unbinds the current VAO.
        unsafe { (ctx.inner.fns.bind_vertex_array)(0) };
    }

    /// Configures and enables a floating-point / normalized vertex attribute from `buffer`.
    pub fn set_attrib_pointer(&self, buffer: &Buffer, desc: &VertexAttribDesc) -> Result<()> {
        if !(1..=4).contains(&desc.components) {
            return Err(GlError::InvalidParameter {
                parameter: "components",
                reason: "vertex attribute component count must be 1, 2, 3, or 4",
            });
        }
        let stride = checked_sizei(desc.stride, "VertexArray::set_attrib_pointer stride")?;
        let normalized = if desc.normalized {
            sys::GL_TRUE
        } else {
            sys::GL_FALSE
        };

        // SAFETY: VAO and `GL_ARRAY_BUFFER` are bound before `glVertexAttribPointer`,
        // so `desc.offset` is interpreted as a byte offset into `buffer`.
        unsafe {
            (self.ctx.fns.bind_vertex_array)(self.id);
            (self.ctx.fns.bind_buffer)(sys::GL_ARRAY_BUFFER, buffer.raw_id());
            (self.ctx.fns.vertex_attrib_pointer)(
                desc.location,
                sys::GLint::from(desc.components),
                desc.data_type as sys::GLenum,
                normalized,
                stride,
                desc.offset as *const c_void,
            );
            (self.ctx.fns.enable_vertex_attrib_array)(desc.location);
        }
        self.ctx.check_gl_error("glVertexAttribPointer")
    }

    /// Configures and enables an unnormalized integer vertex attribute (`glVertexAttribIPointer`).
    pub fn set_attrib_integer(&self, buffer: &Buffer, desc: &VertexAttribDesc) -> Result<()> {
        if !(1..=4).contains(&desc.components) {
            return Err(GlError::InvalidParameter {
                parameter: "components",
                reason: "vertex attribute component count must be 1, 2, 3, or 4",
            });
        }
        if !desc.data_type.is_integer() {
            return Err(GlError::InvalidParameter {
                parameter: "data_type",
                reason: "set_attrib_integer requires an integer DataType",
            });
        }
        let stride = checked_sizei(desc.stride, "VertexArray::set_attrib_integer stride")?;

        // SAFETY: VAO and `GL_ARRAY_BUFFER` are bound and `data_type` is validated integer.
        unsafe {
            (self.ctx.fns.bind_vertex_array)(self.id);
            (self.ctx.fns.bind_buffer)(sys::GL_ARRAY_BUFFER, buffer.raw_id());
            (self.ctx.fns.vertex_attrib_ipointer)(
                desc.location,
                sys::GLint::from(desc.components),
                desc.data_type as sys::GLenum,
                stride,
                desc.offset as *const c_void,
            );
            (self.ctx.fns.enable_vertex_attrib_array)(desc.location);
        }
        self.ctx.check_gl_error("glVertexAttribIPointer")
    }

    /// Sets the instancing divisor for a vertex attribute (`glVertexAttribDivisor`).
    pub fn set_attrib_divisor(&self, location: u32, divisor: u32) -> Result<()> {
        // SAFETY: VAO is bound before setting the divisor.
        unsafe {
            (self.ctx.fns.bind_vertex_array)(self.id);
            (self.ctx.fns.vertex_attrib_divisor)(location, divisor);
        }
        self.ctx.check_gl_error("glVertexAttribDivisor")
    }

    /// Associates an index buffer (`GL_ELEMENT_ARRAY_BUFFER`) with this VAO.
    pub fn set_index_buffer(&self, index_buffer: &Buffer) -> Result<()> {
        if index_buffer.target() != BufferTarget::ElementArray {
            return Err(GlError::InvalidParameter {
                parameter: "index_buffer",
                reason: "expected a buffer created with BufferTarget::ElementArray",
            });
        }
        // SAFETY: Binding `GL_ELEMENT_ARRAY_BUFFER` while a VAO is bound stores it in the VAO state.
        unsafe {
            (self.ctx.fns.bind_vertex_array)(self.id);
            (self.ctx.fns.bind_buffer)(sys::GL_ELEMENT_ARRAY_BUFFER, index_buffer.raw_id());
        }
        Ok(())
    }

    /// Disables a vertex attribute array on this VAO (`glDisableVertexAttribArray`).
    pub fn disable_attrib(&self, location: u32) {
        // SAFETY: VAO is bound before disabling the attribute.
        unsafe {
            (self.ctx.fns.bind_vertex_array)(self.id);
            (self.ctx.fns.disable_vertex_attrib_array)(location);
        }
    }
}