script/dom/webgl/
vertexarrayobject.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6
7use canvas_traits::webgl::{
8    ActiveAttribInfo, WebGLCommand, WebGLError, WebGLResult, WebGLVersion, WebGLVertexArrayId,
9};
10use script_bindings::weakref::WeakRef;
11
12use crate::dom::bindings::cell::{DomRefCell, Ref};
13use crate::dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as constants2;
14use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
15use crate::dom::bindings::root::{Dom, MutNullableDom};
16use crate::dom::webgl::webglbuffer::WebGLBuffer;
17use crate::dom::webgl::webglrenderingcontext::{Operation, WebGLRenderingContext};
18
19#[derive(JSTraceable, MallocSizeOf)]
20#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
21pub(crate) struct VertexArrayObject {
22    context: WeakRef<WebGLRenderingContext>,
23    #[no_trace]
24    id: Option<WebGLVertexArrayId>,
25    ever_bound: Cell<bool>,
26    is_deleted: Cell<bool>,
27    vertex_attribs: DomRefCell<Box<[VertexAttribData]>>,
28    element_array_buffer: MutNullableDom<WebGLBuffer>,
29}
30
31impl VertexArrayObject {
32    pub(crate) fn new(context: &WebGLRenderingContext, id: Option<WebGLVertexArrayId>) -> Self {
33        let max_vertex_attribs = context.limits().max_vertex_attribs as usize;
34        Self {
35            context: WeakRef::new(context),
36            id,
37            ever_bound: Default::default(),
38            is_deleted: Default::default(),
39            vertex_attribs: DomRefCell::new(vec![Default::default(); max_vertex_attribs].into()),
40            element_array_buffer: Default::default(),
41        }
42    }
43
44    pub(crate) fn id(&self) -> Option<WebGLVertexArrayId> {
45        self.id
46    }
47
48    pub(crate) fn is_deleted(&self) -> bool {
49        self.is_deleted.get()
50    }
51
52    pub(crate) fn delete(&self, operation_fallibility: Operation) {
53        assert!(self.id.is_some());
54        if self.is_deleted.get() {
55            return;
56        }
57        self.is_deleted.set(true);
58
59        if let Some(context) = self.context.root() {
60            context.send_with_fallibility(
61                WebGLCommand::DeleteVertexArray(self.id.unwrap()),
62                operation_fallibility,
63            );
64        }
65
66        for attrib_data in &**self.vertex_attribs.borrow() {
67            if let Some(buffer) = attrib_data.buffer() {
68                buffer.decrement_attached_counter(operation_fallibility);
69            }
70        }
71        if let Some(buffer) = self.element_array_buffer.get() {
72            buffer.decrement_attached_counter(operation_fallibility);
73        }
74    }
75
76    pub(crate) fn ever_bound(&self) -> bool {
77        self.ever_bound.get()
78    }
79
80    pub(crate) fn set_ever_bound(&self) {
81        self.ever_bound.set(true);
82    }
83
84    pub(crate) fn element_array_buffer(&self) -> &MutNullableDom<WebGLBuffer> {
85        &self.element_array_buffer
86    }
87
88    pub(crate) fn get_vertex_attrib(&self, index: u32) -> Option<Ref<'_, VertexAttribData>> {
89        Ref::filter_map(self.vertex_attribs.borrow(), |attribs| {
90            attribs.get(index as usize)
91        })
92        .ok()
93    }
94
95    pub(crate) fn set_vertex_attrib_type(&self, index: u32, type_: u32) {
96        self.vertex_attribs.borrow_mut()[index as usize].type_ = type_;
97    }
98
99    pub(crate) fn vertex_attrib_pointer(
100        &self,
101        index: u32,
102        size: i32,
103        type_: u32,
104        normalized: bool,
105        stride: i32,
106        offset: i64,
107    ) -> WebGLResult<()> {
108        let mut attribs = self.vertex_attribs.borrow_mut();
109        let data = attribs
110            .get_mut(index as usize)
111            .ok_or(WebGLError::InvalidValue)?;
112
113        if !(1..=4).contains(&size) {
114            return Err(WebGLError::InvalidValue);
115        }
116
117        // https://www.khronos.org/registry/webgl/specs/latest/1.0/#BUFFER_OFFSET_AND_STRIDE
118        // https://www.khronos.org/registry/webgl/specs/latest/1.0/#VERTEX_STRIDE
119        if !(0..=255).contains(&stride) || offset < 0 {
120            return Err(WebGLError::InvalidValue);
121        }
122
123        let Some(context) = self.context.root() else {
124            return Err(WebGLError::ContextLost);
125        };
126
127        let is_webgl2 = matches!(context.webgl_version(), WebGLVersion::WebGL2);
128        let bytes_per_component: i32 = match type_ {
129            constants::BYTE | constants::UNSIGNED_BYTE => 1,
130            constants::SHORT | constants::UNSIGNED_SHORT => 2,
131            constants::FLOAT => 4,
132            constants::INT | constants::UNSIGNED_INT if is_webgl2 => 4,
133            constants2::HALF_FLOAT if is_webgl2 => 2,
134            glow::FIXED if is_webgl2 => 4,
135            constants2::INT_2_10_10_10_REV | constants2::UNSIGNED_INT_2_10_10_10_REV
136                if is_webgl2 && size == 4 =>
137            {
138                4
139            },
140            _ => return Err(WebGLError::InvalidEnum),
141        };
142
143        if offset % bytes_per_component as i64 > 0 || stride % bytes_per_component > 0 {
144            return Err(WebGLError::InvalidOperation);
145        }
146
147        let buffer = context.array_buffer();
148        match buffer {
149            Some(ref buffer) => buffer.increment_attached_counter(),
150            None if offset != 0 => {
151                // https://github.com/KhronosGroup/WebGL/pull/2228
152                return Err(WebGLError::InvalidOperation);
153            },
154            _ => {},
155        }
156        context.send_command(WebGLCommand::VertexAttribPointer(
157            index,
158            size,
159            type_,
160            normalized,
161            stride,
162            offset as u32,
163        ));
164        if let Some(old) = data.buffer() {
165            old.decrement_attached_counter(Operation::Infallible);
166        }
167
168        *data = VertexAttribData {
169            enabled_as_array: data.enabled_as_array,
170            size: size as u8,
171            type_,
172            bytes_per_vertex: size as u8 * bytes_per_component as u8,
173            normalized,
174            stride: stride as u8,
175            offset: offset as u32,
176            buffer: buffer.map(|b| Dom::from_ref(&*b)),
177            divisor: data.divisor,
178        };
179
180        Ok(())
181    }
182
183    pub(crate) fn vertex_attrib_divisor(&self, index: u32, value: u32) {
184        self.vertex_attribs.borrow_mut()[index as usize].divisor = value;
185    }
186
187    pub(crate) fn enabled_vertex_attrib_array(&self, index: u32, value: bool) {
188        self.vertex_attribs.borrow_mut()[index as usize].enabled_as_array = value;
189    }
190
191    pub(crate) fn unbind_buffer(&self, buffer: &WebGLBuffer) {
192        for attrib in &mut **self.vertex_attribs.borrow_mut() {
193            if let Some(b) = attrib.buffer() {
194                if b.id() != buffer.id() {
195                    continue;
196                }
197                b.decrement_attached_counter(Operation::Infallible);
198            }
199            attrib.buffer = None;
200        }
201        if self
202            .element_array_buffer
203            .get()
204            .is_some_and(|b| buffer == &*b)
205        {
206            buffer.decrement_attached_counter(Operation::Infallible);
207            self.element_array_buffer.set(None);
208        }
209    }
210
211    pub(crate) fn validate_for_draw(
212        &self,
213        required_len: u32,
214        instance_count: u32,
215        active_attribs: &[ActiveAttribInfo],
216    ) -> WebGLResult<()> {
217        // TODO(nox): Cache limits per VAO.
218        let attribs = self.vertex_attribs.borrow();
219        // https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.2
220        if attribs
221            .iter()
222            .any(|data| data.enabled_as_array && data.buffer.is_none())
223        {
224            return Err(WebGLError::InvalidOperation);
225        }
226        let mut has_active_attrib = false;
227        let mut has_divisor_0 = false;
228        for active_info in active_attribs {
229            let Some(location) = active_info.location else {
230                continue;
231            };
232            has_active_attrib = true;
233            let attrib = &attribs[location as usize];
234            if attrib.divisor == 0 {
235                has_divisor_0 = true;
236            }
237            if !attrib.enabled_as_array {
238                continue;
239            }
240            // https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.6
241            if required_len > 0 && instance_count > 0 {
242                let max_vertices = attrib.max_vertices();
243                if attrib.divisor == 0 {
244                    if max_vertices < required_len {
245                        return Err(WebGLError::InvalidOperation);
246                    }
247                } else if max_vertices
248                    .checked_mul(attrib.divisor)
249                    .is_some_and(|v| v < instance_count)
250                {
251                    return Err(WebGLError::InvalidOperation);
252                }
253            }
254        }
255        if has_active_attrib && !has_divisor_0 {
256            return Err(WebGLError::InvalidOperation);
257        }
258        Ok(())
259    }
260}
261
262impl Drop for VertexArrayObject {
263    fn drop(&mut self) {
264        if self.id.is_some() {
265            self.delete(Operation::Fallible);
266        }
267    }
268}
269
270#[derive(Clone, JSTraceable, MallocSizeOf)]
271#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
272pub(crate) struct VertexAttribData {
273    pub(crate) enabled_as_array: bool,
274    pub(crate) size: u8,
275    pub(crate) type_: u32,
276    bytes_per_vertex: u8,
277    pub(crate) normalized: bool,
278    pub(crate) stride: u8,
279    pub(crate) offset: u32,
280    pub(crate) buffer: Option<Dom<WebGLBuffer>>,
281    pub(crate) divisor: u32,
282}
283
284impl Default for VertexAttribData {
285    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
286    fn default() -> Self {
287        Self {
288            enabled_as_array: false,
289            size: 4,
290            type_: constants::FLOAT,
291            bytes_per_vertex: 16,
292            normalized: false,
293            stride: 0,
294            offset: 0,
295            buffer: None,
296            divisor: 0,
297        }
298    }
299}
300
301impl VertexAttribData {
302    pub(crate) fn buffer(&self) -> Option<&WebGLBuffer> {
303        self.buffer.as_deref()
304    }
305
306    pub(crate) fn max_vertices(&self) -> u32 {
307        let capacity = (self.buffer().unwrap().capacity() as u32).saturating_sub(self.offset);
308        if capacity < self.bytes_per_vertex as u32 {
309            0
310        } else if self.stride == 0 {
311            capacity / self.bytes_per_vertex as u32
312        } else if self.stride < self.bytes_per_vertex {
313            (capacity - (self.bytes_per_vertex - self.stride) as u32) / self.stride as u32
314        } else {
315            let mut max = capacity / self.stride as u32;
316            if capacity % self.stride as u32 >= self.bytes_per_vertex as u32 {
317                max += 1;
318            }
319            max
320        }
321    }
322}