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
use crate::context::{consts, Context};
use crate::core::Error;

///
/// A buffer containing indices for rendering, see for example [draw_elements](crate::Program::draw_elements).
/// Also known as an index buffer.
///
pub struct ElementBuffer {
    context: Context,
    id: crate::context::Buffer,
    count: usize,
}

impl ElementBuffer {
    ///
    /// Creates a new element buffer and fills it with the given indices.
    ///
    pub fn new_with_u32(context: &Context, data: &[u32]) -> Result<ElementBuffer, Error> {
        let id = context.create_buffer().unwrap();
        let mut buffer = ElementBuffer {
            context: context.clone(),
            id,
            count: 0,
        };
        if data.len() > 0 {
            buffer.fill_with_u32(data);
        }
        Ok(buffer)
    }

    ///
    /// Fills the buffer with the given indices.
    ///
    pub fn fill_with_u32(&mut self, data: &[u32]) {
        self.bind();
        self.context
            .buffer_data_u32(consts::ELEMENT_ARRAY_BUFFER, data, consts::STATIC_DRAW);
        self.context.unbind_buffer(consts::ELEMENT_ARRAY_BUFFER);
        self.count = data.len();
    }

    ///
    /// The number of elements in the buffer.
    ///
    pub fn count(&self) -> usize {
        self.count
    }

    pub(crate) fn bind(&self) {
        self.context
            .bind_buffer(consts::ELEMENT_ARRAY_BUFFER, &self.id);
    }
}

impl Drop for ElementBuffer {
    fn drop(&mut self) {
        self.context.delete_buffer(&self.id);
    }
}