Skip to main content

script/dom/webgl/
webgl2renderingcontext.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;
6use std::{cmp, ptr};
7
8use bitflags::bitflags;
9use dom_struct::dom_struct;
10use euclid::default::{Point2D, Rect, Size2D};
11use js::context::{JSContext, NoGC};
12use js::conversions::ToJSValConvertible;
13use js::jsapi::{JSObject, Type};
14use js::jsval::{BooleanValue, DoubleValue, Int32Value, NullValue, ObjectValue, UInt32Value};
15use js::rust::{CustomAutoRooterGuard, HandleObject, MutableHandleObject, MutableHandleValue};
16use js::typedarray::{ArrayBufferView, Float32, Int32, Uint32};
17use pixels::{Alpha, Snapshot};
18use script_bindings::interfaces::WebGL2RenderingContextHelpers;
19use script_bindings::reflector::{Reflector, reflect_dom_object};
20use servo_base::generic_channel::{self, GenericSharedMemory};
21use servo_canvas_traits::webgl::WebGLError::*;
22use servo_canvas_traits::webgl::{
23    AlphaTreatment, GLContextAttributes, InternalFormatParameter, TexComponentType, TexDataType,
24    TexFormat, WebGLCommand, WebGLContextId, WebGLResult, WebGLVersion, YAxisTreatment,
25    webgl_channel,
26};
27use servo_config::pref;
28use url::Host;
29use webrender_api::ImageKey;
30
31use super::validations::types::TexImageTarget;
32use crate::canvas_context::CanvasContext;
33#[cfg(feature = "webxr")]
34use crate::dom::RootedPromise;
35use crate::dom::bindings::buffer_source::create_buffer_source;
36use crate::dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::{
37    WebGL2RenderingContextConstants as constants, WebGL2RenderingContextMethods,
38};
39use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::{
40    TexImageSource, WebGLContextAttributes, WebGLRenderingContextMethods,
41};
42use crate::dom::bindings::codegen::UnionTypes::{
43    ArrayBufferViewOrArrayBuffer, Float32ArrayOrUnrestrictedFloatSequence,
44    HTMLCanvasElementOrOffscreenCanvas as RootedHTMLCanvasElementOrOffscreenCanvas,
45    Int32ArrayOrLongSequence, Uint32ArrayOrUnsignedLongSequence,
46};
47use crate::dom::bindings::error::{ErrorResult, Fallible};
48use crate::dom::bindings::reflector::DomGlobal;
49use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
50use crate::dom::bindings::str::DOMString;
51use crate::dom::globalscope::GlobalScope;
52#[cfg(feature = "webxr")]
53use crate::dom::promise::Promise;
54use crate::dom::webgl::validations::WebGLValidator;
55use crate::dom::webgl::validations::tex_image_2d::{
56    TexImage2DValidator, TexImage2DValidatorResult, TexStorageValidator, TexStorageValidatorResult,
57};
58use crate::dom::webgl::validations::tex_image_3d::{
59    TexImage3DValidator, TexImage3DValidatorResult,
60};
61use crate::dom::webgl::vertexarrayobject::VertexAttribPointerKind;
62use crate::dom::webgl::webglactiveinfo::WebGLActiveInfo;
63use crate::dom::webgl::webglbuffer::WebGLBuffer;
64use crate::dom::webgl::webglframebuffer::{
65    CompleteForRendering, WebGLFramebuffer, WebGLFramebufferAttachmentRoot,
66};
67use crate::dom::webgl::webglprogram::WebGLProgram;
68use crate::dom::webgl::webglquery::WebGLQuery;
69use crate::dom::webgl::webglrenderbuffer::{WebGLRenderbuffer, renderbuffer_format};
70use crate::dom::webgl::webglrenderingcontext::{
71    Operation, TexPixels, TexSource, VertexAttrib, WebGLRenderingContext, bytes_per_pixel,
72    uniform_get, uniform_typed,
73};
74use crate::dom::webgl::webglsampler::{WebGLSampler, WebGLSamplerValue};
75use crate::dom::webgl::webglshader::WebGLShader;
76use crate::dom::webgl::webglshaderprecisionformat::WebGLShaderPrecisionFormat;
77use crate::dom::webgl::webglsync::WebGLSync;
78use crate::dom::webgl::webgltexture::WebGLTexture;
79use crate::dom::webgl::webgltransformfeedback::WebGLTransformFeedback;
80use crate::dom::webgl::webgluniformlocation::WebGLUniformLocation;
81use crate::dom::webgl::webglvertexarrayobject::WebGLVertexArrayObject;
82use crate::dom::window::Window;
83
84#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
85#[derive(JSTraceable, MallocSizeOf)]
86struct IndexedBinding {
87    buffer: MutNullableDom<WebGLBuffer>,
88    start: Cell<i64>,
89    size: Cell<i64>,
90}
91
92impl IndexedBinding {
93    fn new() -> IndexedBinding {
94        IndexedBinding {
95            buffer: MutNullableDom::new(None),
96            start: Cell::new(0),
97            size: Cell::new(0),
98        }
99    }
100}
101
102#[dom_struct] // no need to report size here as it is reported as part of WebGLRenderingContext
103pub(crate) struct WebGL2RenderingContext {
104    reflector_: Reflector,
105    base: Dom<WebGLRenderingContext>,
106    occlusion_query: MutNullableDom<WebGLQuery>,
107    primitives_query: MutNullableDom<WebGLQuery>,
108    samplers: Box<[MutNullableDom<WebGLSampler>]>,
109    bound_copy_read_buffer: MutNullableDom<WebGLBuffer>,
110    bound_copy_write_buffer: MutNullableDom<WebGLBuffer>,
111    bound_pixel_pack_buffer: MutNullableDom<WebGLBuffer>,
112    bound_pixel_unpack_buffer: MutNullableDom<WebGLBuffer>,
113    bound_transform_feedback_buffer: MutNullableDom<WebGLBuffer>,
114    bound_uniform_buffer: MutNullableDom<WebGLBuffer>,
115    indexed_uniform_buffer_bindings: Box<[IndexedBinding]>,
116    indexed_transform_feedback_buffer_bindings: Box<[IndexedBinding]>,
117    current_transform_feedback: MutNullableDom<WebGLTransformFeedback>,
118    texture_pack_row_length: Cell<usize>,
119    texture_pack_skip_pixels: Cell<usize>,
120    texture_pack_skip_rows: Cell<usize>,
121    enable_rasterizer_discard: Cell<bool>,
122    default_fb_readbuffer: Cell<u32>,
123    default_fb_drawbuffer: Cell<u32>,
124}
125
126struct ReadPixelsAllowedFormats<'a> {
127    array_types: &'a [Type],
128    elements_per_pixel: usize,
129}
130
131struct ReadPixelsSizes {
132    row_stride: usize,
133    skipped_bytes: usize,
134    size: usize,
135}
136
137impl WebGL2RenderingContext {
138    fn new_inherited(base: &WebGLRenderingContext) -> WebGL2RenderingContext {
139        let samplers = (0..base.limits().max_combined_texture_image_units)
140            .map(|_| Default::default())
141            .collect::<Vec<_>>()
142            .into();
143        let indexed_uniform_buffer_bindings = (0..base.limits().max_uniform_buffer_bindings)
144            .map(|_| IndexedBinding::new())
145            .collect::<Vec<_>>()
146            .into();
147        let indexed_transform_feedback_buffer_bindings =
148            (0..base.limits().max_transform_feedback_separate_attribs)
149                .map(|_| IndexedBinding::new())
150                .collect::<Vec<_>>()
151                .into();
152
153        WebGL2RenderingContext {
154            reflector_: Reflector::new(),
155            base: Dom::from_ref(base),
156            occlusion_query: MutNullableDom::new(None),
157            primitives_query: MutNullableDom::new(None),
158            samplers,
159            bound_copy_read_buffer: MutNullableDom::new(None),
160            bound_copy_write_buffer: MutNullableDom::new(None),
161            bound_pixel_pack_buffer: MutNullableDom::new(None),
162            bound_pixel_unpack_buffer: MutNullableDom::new(None),
163            bound_transform_feedback_buffer: MutNullableDom::new(None),
164            bound_uniform_buffer: MutNullableDom::new(None),
165            indexed_uniform_buffer_bindings,
166            indexed_transform_feedback_buffer_bindings,
167            current_transform_feedback: MutNullableDom::new(None),
168            texture_pack_row_length: Cell::new(0),
169            texture_pack_skip_pixels: Cell::new(0),
170            texture_pack_skip_rows: Cell::new(0),
171            enable_rasterizer_discard: Cell::new(false),
172            default_fb_readbuffer: Cell::new(constants::BACK),
173            default_fb_drawbuffer: Cell::new(constants::BACK),
174        }
175    }
176
177    pub(crate) fn new(
178        cx: &mut js::context::JSContext,
179        window: &Window,
180        canvas: &RootedHTMLCanvasElementOrOffscreenCanvas,
181        size: Size2D<u32>,
182        attrs: GLContextAttributes,
183    ) -> Option<DomRoot<WebGL2RenderingContext>> {
184        let base =
185            WebGLRenderingContext::new(cx, window, canvas, WebGLVersion::WebGL2, size, attrs)?;
186        Some(reflect_dom_object(
187            cx,
188            Box::new(WebGL2RenderingContext::new_inherited(&base)),
189            window,
190        ))
191    }
192
193    pub(crate) fn set_image_key(&self, image_key: ImageKey) {
194        self.base.set_image_key(image_key);
195    }
196
197    #[expect(unsafe_code)]
198    pub(crate) fn is_webgl2_enabled(
199        _cx: &mut js::context::JSContext,
200        global: HandleObject,
201    ) -> bool {
202        if pref!(dom_webgl2_enabled) {
203            return true;
204        }
205
206        let global = unsafe { GlobalScope::from_object(global.get()) };
207        let origin = global.origin();
208        let host = origin.host();
209        WEBGL2_ORIGINS
210            .iter()
211            .any(|origin| host == Host::parse(origin).ok().as_ref())
212    }
213}
214
215/// List of domains for which WebGL 2 is enabled automatically, regardless
216/// of the status of the dom.webgl2.enabled preference.
217static WEBGL2_ORIGINS: &[&str] = &["www.servoexperiments.com"];
218
219impl WebGL2RenderingContext {
220    pub(crate) fn current_vao(&self, cx: &mut JSContext) -> DomRoot<WebGLVertexArrayObject> {
221        self.base.current_vao_webgl2(cx)
222    }
223
224    pub(crate) fn validate_uniform_block_for_draw(&self) {
225        let program = match self.base.current_program() {
226            Some(program) => program,
227            None => return,
228        };
229        for uniform_block in program.active_uniform_blocks().iter() {
230            let data_size = uniform_block.size as usize;
231            for block in program.active_uniforms().iter() {
232                let index = match block.bind_index {
233                    Some(index) => index,
234                    None => continue,
235                };
236                let indexed = &self.indexed_uniform_buffer_bindings[index as usize];
237                let buffer = match indexed.buffer.get() {
238                    Some(buffer) => buffer,
239                    None => {
240                        self.base.webgl_error(InvalidOperation);
241                        return;
242                    },
243                };
244                if indexed.size.get() == 0 {
245                    if data_size > buffer.capacity() {
246                        self.base.webgl_error(InvalidOperation);
247                        return;
248                    }
249                } else {
250                    let start = indexed.start.get() as usize;
251                    let mut size = indexed.size.get() as usize;
252                    if start >= size {
253                        self.base.webgl_error(InvalidOperation);
254                        return;
255                    }
256                    size -= start;
257                    if data_size > size {
258                        self.base.webgl_error(InvalidOperation);
259                        return;
260                    }
261                }
262            }
263        }
264    }
265
266    fn validate_vertex_attribs_for_draw(&self, cx: &mut JSContext) {
267        let program = match self.base.current_program() {
268            Some(program) => program,
269            None => return,
270        };
271        let groups = [
272            [
273                constants::INT,
274                constants::INT_VEC2,
275                constants::INT_VEC3,
276                constants::INT_VEC4,
277            ],
278            [
279                constants::UNSIGNED_INT,
280                constants::UNSIGNED_INT_VEC2,
281                constants::UNSIGNED_INT_VEC3,
282                constants::UNSIGNED_INT_VEC4,
283            ],
284            [
285                constants::FLOAT,
286                constants::FLOAT_VEC2,
287                constants::FLOAT_VEC3,
288                constants::FLOAT_VEC4,
289            ],
290        ];
291        let vao = self.current_vao(cx);
292        for prog_attrib in program.active_attribs().iter() {
293            // Built-in inputs have no location and read no vertex attribute.
294            let Some(location) = prog_attrib.location else {
295                continue;
296            };
297            let Some(attrib) = vao.get_vertex_attrib(location) else {
298                return self.base.webgl_error(InvalidOperation);
299            };
300
301            let current_vertex_attrib = self.base.current_vertex_attribs()[location as usize];
302            // The base type comes from the call that set the attribute:
303            //
304            // https://registry.khronos.org/webgl/specs/latest/2.0/#ATTRIBUTE_TYPE_MATCH
305            let attrib_data_base_type = if !attrib.enabled_as_array {
306                match current_vertex_attrib {
307                    VertexAttrib::Int(_, _, _, _) => constants::INT,
308                    VertexAttrib::Uint(_, _, _, _) => constants::UNSIGNED_INT,
309                    VertexAttrib::Float(_, _, _, _) => constants::FLOAT,
310                }
311            } else if attrib.kind.is_integer() {
312                match attrib.type_ {
313                    constants::BYTE | constants::SHORT | constants::INT => constants::INT,
314                    _ => constants::UNSIGNED_INT,
315                }
316            } else {
317                constants::FLOAT
318            };
319
320            let contains = groups
321                .iter()
322                .find(|g| g.contains(&attrib_data_base_type) && g.contains(&prog_attrib.type_));
323            if contains.is_none() {
324                self.base.webgl_error(InvalidOperation);
325                return;
326            }
327        }
328    }
329
330    pub(crate) fn base_context(&self) -> DomRoot<WebGLRenderingContext> {
331        DomRoot::from_ref(&*self.base)
332    }
333
334    fn bound_buffer(
335        &self,
336        cx: &mut JSContext,
337        target: u32,
338    ) -> WebGLResult<Option<DomRoot<WebGLBuffer>>> {
339        match target {
340            constants::COPY_READ_BUFFER => Ok(self.bound_copy_read_buffer.get()),
341            constants::COPY_WRITE_BUFFER => Ok(self.bound_copy_write_buffer.get()),
342            constants::PIXEL_PACK_BUFFER => Ok(self.bound_pixel_pack_buffer.get()),
343            constants::PIXEL_UNPACK_BUFFER => Ok(self.bound_pixel_unpack_buffer.get()),
344            constants::TRANSFORM_FEEDBACK_BUFFER => Ok(self.bound_transform_feedback_buffer.get()),
345            constants::UNIFORM_BUFFER => Ok(self.bound_uniform_buffer.get()),
346            constants::ELEMENT_ARRAY_BUFFER => {
347                Ok(self.current_vao(cx).element_array_buffer().get())
348            },
349            _ => self.base.bound_buffer(cx, target),
350        }
351    }
352
353    pub(crate) fn buffer_usage(&self, usage: u32) -> WebGLResult<u32> {
354        match usage {
355            constants::STATIC_READ |
356            constants::DYNAMIC_READ |
357            constants::STREAM_READ |
358            constants::STATIC_COPY |
359            constants::DYNAMIC_COPY |
360            constants::STREAM_COPY => Ok(usage),
361            _ => self.base.buffer_usage(usage),
362        }
363    }
364
365    fn unbind_from(&self, slot: &MutNullableDom<WebGLBuffer>, buffer: &WebGLBuffer) {
366        if slot.get().is_some_and(|b| buffer == &*b) {
367            buffer.decrement_attached_counter(Operation::Infallible);
368            slot.set(None);
369        }
370    }
371
372    /// Returns the `format`/`type` pairs accepted by `readPixels` for the current read buffer:
373    /// first, the one required by OpenGL ES 3.0.6 section 4.3.2 for its component type, then
374    /// the implementation-chosen pair (table 3.15); `InvalidOperation` if it has no image.
375    fn accepted_read_pixels_format_types(&self) -> WebGLResult<&'static [(u32, u32)]> {
376        let Some(fb) = self.base.get_draw_framebuffer_slot().get() else {
377            if self.default_fb_readbuffer.get() == constants::NONE {
378                return Err(InvalidOperation);
379            }
380            return Ok(&[(constants::RGBA, constants::UNSIGNED_BYTE)]);
381        };
382        if fb.attachment(fb.read_buffer()).is_none() {
383            return Err(InvalidOperation);
384        }
385        // An opaque framebuffer's color image is an RGBA8 texture allocated outside of script.
386        let Some(format) = fb.attachment_effective_format(fb.read_buffer()) else {
387            return Ok(&[(constants::RGBA, constants::UNSIGNED_BYTE)]);
388        };
389        Ok(match format.component_type().ok_or(InvalidOperation)? {
390            TexComponentType::UnsignedNormalized if format == TexFormat::RGB10A2 => &[
391                (constants::RGBA, constants::UNSIGNED_BYTE),
392                (constants::RGBA, constants::UNSIGNED_INT_2_10_10_10_REV),
393            ],
394            TexComponentType::UnsignedNormalized | TexComponentType::SignedNormalized => {
395                &[(constants::RGBA, constants::UNSIGNED_BYTE)]
396            },
397            TexComponentType::Float => &[(constants::RGBA, constants::FLOAT)],
398            TexComponentType::SignedInt => &[(constants::RGBA_INTEGER, constants::INT)],
399            TexComponentType::UnsignedInt => &[(constants::RGBA_INTEGER, constants::UNSIGNED_INT)],
400        })
401    }
402
403    fn calc_read_pixel_formats(
404        &self,
405        pixel_type: u32,
406        format: u32,
407    ) -> WebGLResult<ReadPixelsAllowedFormats<'_>> {
408        let array_types = match pixel_type {
409            constants::BYTE => &[Type::Int8][..],
410            constants::SHORT => &[Type::Int16][..],
411            constants::INT => &[Type::Int32][..],
412            constants::UNSIGNED_BYTE => &[Type::Uint8, Type::Uint8Clamped][..],
413            constants::UNSIGNED_SHORT |
414            constants::UNSIGNED_SHORT_4_4_4_4 |
415            constants::UNSIGNED_SHORT_5_5_5_1 |
416            constants::UNSIGNED_SHORT_5_6_5 => &[Type::Uint16][..],
417            constants::UNSIGNED_INT |
418            constants::UNSIGNED_INT_2_10_10_10_REV |
419            constants::UNSIGNED_INT_10F_11F_11F_REV |
420            constants::UNSIGNED_INT_5_9_9_9_REV => &[Type::Uint32][..],
421            constants::FLOAT => &[Type::Float32][..],
422            constants::HALF_FLOAT => &[Type::Uint16][..],
423            _ => return Err(InvalidEnum),
424        };
425        let channels = match format {
426            constants::ALPHA | constants::RED | constants::RED_INTEGER => 1,
427            constants::RG | constants::RG_INTEGER => 2,
428            constants::RGB | constants::RGB_INTEGER => 3,
429            constants::RGBA | constants::RGBA_INTEGER => 4,
430            _ => return Err(InvalidEnum),
431        };
432        // A packed type stores the whole pixel in one array element.
433        let elements_per_pixel = match pixel_type {
434            constants::UNSIGNED_SHORT_4_4_4_4 |
435            constants::UNSIGNED_SHORT_5_5_5_1 |
436            constants::UNSIGNED_SHORT_5_6_5 |
437            constants::UNSIGNED_INT_2_10_10_10_REV |
438            constants::UNSIGNED_INT_10F_11F_11F_REV |
439            constants::UNSIGNED_INT_5_9_9_9_REV => 1,
440            _ => channels,
441        };
442        Ok(ReadPixelsAllowedFormats {
443            array_types,
444            elements_per_pixel,
445        })
446    }
447
448    fn calc_read_pixel_sizes(
449        &self,
450        width: i32,
451        height: i32,
452        bytes_per_pixel: usize,
453    ) -> WebGLResult<ReadPixelsSizes> {
454        if width < 0 || height < 0 {
455            return Err(InvalidValue);
456        }
457
458        // See also https://www.khronos.org/registry/webgl/specs/latest/2.0/#6.36
459        let pixels_per_row = if self.texture_pack_row_length.get() > 0 {
460            self.texture_pack_row_length.get()
461        } else {
462            width as usize
463        };
464        if self.texture_pack_skip_pixels.get() + width as usize > pixels_per_row {
465            return Err(InvalidOperation);
466        }
467
468        let bytes_per_row = pixels_per_row
469            .checked_mul(bytes_per_pixel)
470            .ok_or(InvalidOperation)?;
471        let row_padding_bytes = {
472            let pack_alignment = self.base.get_texture_packing_alignment() as usize;
473            match bytes_per_row % pack_alignment {
474                0 => 0,
475                remainder => pack_alignment - remainder,
476            }
477        };
478        let row_stride = bytes_per_row + row_padding_bytes;
479        let size = if width == 0 || height == 0 {
480            0
481        } else {
482            let full_row_bytes = row_stride
483                .checked_mul(height as usize - 1)
484                .ok_or(InvalidOperation)?;
485            let last_row_bytes = bytes_per_pixel
486                .checked_mul(width as usize)
487                .ok_or(InvalidOperation)?;
488            full_row_bytes
489                .checked_add(last_row_bytes)
490                .ok_or(InvalidOperation)?
491        };
492        let skipped_bytes = {
493            let skipped_row_bytes = self
494                .texture_pack_skip_rows
495                .get()
496                .checked_mul(row_stride)
497                .ok_or(InvalidOperation)?;
498            let skipped_pixel_bytes = self
499                .texture_pack_skip_pixels
500                .get()
501                .checked_mul(bytes_per_pixel)
502                .ok_or(InvalidOperation)?;
503            skipped_row_bytes
504                .checked_add(skipped_pixel_bytes)
505                .ok_or(InvalidOperation)?
506        };
507        Ok(ReadPixelsSizes {
508            row_stride,
509            skipped_bytes,
510            size,
511        })
512    }
513
514    #[expect(clippy::too_many_arguments)]
515    fn read_pixels_into(
516        &self,
517        no_gc: &NoGC,
518        x: i32,
519        y: i32,
520        width: i32,
521        height: i32,
522        format: u32,
523        pixel_type: u32,
524        dst: &mut ArrayBufferView,
525        dst_elem_offset: u32,
526    ) {
527        if let Err(error) = self.base.validate_read_framebuffer() {
528            return self.base.webgl_error(error);
529        }
530
531        if self.bound_pixel_pack_buffer.get().is_some() {
532            return self.base.webgl_error(InvalidOperation);
533        }
534
535        let accepted = match self.accepted_read_pixels_format_types() {
536            Ok(accepted) => accepted,
537            Err(error) => return self.base.webgl_error(error),
538        };
539
540        let dst_byte_offset = {
541            let dst_elem_size = dst.get_array_type().byte_size().unwrap();
542            dst_elem_offset as usize * dst_elem_size
543        };
544        if dst_byte_offset > dst.len() {
545            return self.base.webgl_error(InvalidValue);
546        }
547
548        let dst_array_type = dst.get_array_type();
549        let ReadPixelsAllowedFormats {
550            array_types: allowed_array_types,
551            elements_per_pixel,
552        } = match self.calc_read_pixel_formats(pixel_type, format) {
553            Ok(result) => result,
554            Err(error) => return self.base.webgl_error(error),
555        };
556        if !allowed_array_types.contains(&dst_array_type) {
557            return self.base.webgl_error(InvalidOperation);
558        }
559        if !accepted.contains(&(format, pixel_type)) {
560            return self.base.webgl_error(InvalidOperation);
561        }
562
563        let bytes_per_pixel = dst_array_type.byte_size().unwrap() * elements_per_pixel;
564        let ReadPixelsSizes {
565            row_stride,
566            skipped_bytes,
567            size,
568        } = match self.calc_read_pixel_sizes(width, height, bytes_per_pixel) {
569            Ok(result) => result,
570            Err(error) => return self.base.webgl_error(error),
571        };
572        let dst_end = dst_byte_offset + skipped_bytes + size;
573        let dst_pixels = dst.as_mut_slice_safe(no_gc).unwrap_or(&mut []);
574        if dst_pixels.len() < dst_end {
575            return self.base.webgl_error(InvalidOperation);
576        }
577
578        let dst_byte_offset = {
579            let margin_left = cmp::max(0, -x) as usize;
580            let margin_top = cmp::max(0, -y) as usize;
581            dst_byte_offset +
582                skipped_bytes +
583                margin_left * bytes_per_pixel +
584                margin_top * row_stride
585        };
586        let src_rect = {
587            let Some((fb_width, fb_height)) = self.base.get_current_framebuffer_size() else {
588                return self.base.webgl_error(InvalidOperation);
589            };
590            let src_origin = Point2D::new(x, y);
591            let src_size = Size2D::new(width as u32, height as u32);
592            let fb_size = Size2D::new(fb_width as u32, fb_height as u32);
593            match pixels::clip(src_origin, src_size.to_u32(), fb_size.to_u32()) {
594                Some(rect) => rect.to_u32(),
595                None => return,
596            }
597        };
598        let Some(src_row_bytes) = src_rect.size.width.checked_mul(bytes_per_pixel as u32) else {
599            return self.base.webgl_error(InvalidOperation);
600        };
601
602        let (sender, receiver) = generic_channel::channel().unwrap();
603        self.base.send_command(WebGLCommand::ReadPixels(
604            src_rect, format, pixel_type, sender,
605        ));
606        let (src, _) = receiver.recv().unwrap();
607
608        for i in 0..src_rect.size.height as usize {
609            let src_start = i * src_row_bytes as usize;
610            let dst_start = dst_byte_offset + i * row_stride;
611            dst_pixels[dst_start..dst_start + src_row_bytes as usize]
612                .copy_from_slice(&src[src_start..src_start + src_row_bytes as usize]);
613        }
614    }
615
616    fn uniform_vec_section_uint(
617        &self,
618        vec: Uint32ArrayOrUnsignedLongSequence,
619        offset: u32,
620        length: u32,
621        uniform_size: usize,
622        uniform_location: &WebGLUniformLocation,
623    ) -> WebGLResult<Vec<u32>> {
624        let vec = match vec {
625            Uint32ArrayOrUnsignedLongSequence::Uint32Array(v) => v.to_vec().unwrap_or_default(),
626            Uint32ArrayOrUnsignedLongSequence::UnsignedLongSequence(v) => v,
627        };
628        self.base
629            .uniform_vec_section::<u32>(vec, offset, length, uniform_size, uniform_location)
630    }
631
632    fn get_default_fb_attachment_param(
633        &self,
634        attachment: u32,
635        pname: u32,
636        mut retval: MutableHandleValue,
637    ) -> WebGLResult<()> {
638        match attachment {
639            constants::BACK | constants::DEPTH | constants::STENCIL => {},
640            _ => return Err(InvalidEnum),
641        }
642
643        if pname == constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME {
644            retval.set(NullValue());
645            return Ok(());
646        }
647
648        let attrs = self
649            .GetContextAttributes()
650            .unwrap_or_else(WebGLContextAttributes::empty);
651
652        let intval = match pname {
653            constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE => match attachment {
654                constants::DEPTH if !attrs.depth => constants::NONE as _,
655                constants::STENCIL if !attrs.stencil => constants::NONE as _,
656                _ => constants::FRAMEBUFFER_DEFAULT as _,
657            },
658            constants::FRAMEBUFFER_ATTACHMENT_RED_SIZE |
659            constants::FRAMEBUFFER_ATTACHMENT_GREEN_SIZE |
660            constants::FRAMEBUFFER_ATTACHMENT_BLUE_SIZE => match attachment {
661                constants::BACK => 8,
662                _ => 0,
663            },
664            constants::FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE => match attachment {
665                constants::BACK if attrs.alpha => 8,
666                constants::BACK => return Err(InvalidOperation),
667                _ => 0,
668            },
669            constants::FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE => match attachment {
670                constants::DEPTH if attrs.depth => 24,
671                constants::DEPTH => return Err(InvalidOperation),
672                _ => 0,
673            },
674            constants::FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE => match attachment {
675                constants::STENCIL if attrs.stencil => 8,
676                constants::STENCIL => return Err(InvalidOperation),
677                _ => 0,
678            },
679            constants::FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE => match attachment {
680                constants::DEPTH if attrs.depth => constants::UNSIGNED_NORMALIZED as _,
681                constants::STENCIL if attrs.stencil => constants::UNSIGNED_INT as _,
682                constants::DEPTH => return Err(InvalidOperation),
683                constants::STENCIL => return Err(InvalidOperation),
684                _ => constants::UNSIGNED_NORMALIZED as _,
685            },
686            constants::FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING => match attachment {
687                constants::DEPTH if !attrs.depth => return Err(InvalidOperation),
688                constants::STENCIL if !attrs.stencil => return Err(InvalidOperation),
689                _ => constants::LINEAR as _,
690            },
691            _ => return Err(InvalidEnum),
692        };
693        retval.set(Int32Value(intval));
694        Ok(())
695    }
696
697    fn get_specific_fb_attachment_param(
698        &self,
699        cx: &mut JSContext,
700        fb: &WebGLFramebuffer,
701        target: u32,
702        attachment: u32,
703        pname: u32,
704        mut rval: MutableHandleValue,
705    ) -> WebGLResult<()> {
706        use crate::dom::webgl::webglframebuffer::WebGLFramebufferAttachmentRoot::{
707            Renderbuffer, Texture,
708        };
709
710        match attachment {
711            constants::DEPTH_ATTACHMENT | constants::STENCIL_ATTACHMENT => {},
712            constants::DEPTH_STENCIL_ATTACHMENT => {
713                if pname == constants::FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE {
714                    return Err(InvalidOperation);
715                }
716
717                let a = fb.attachment(constants::DEPTH_ATTACHMENT);
718                let b = fb.attachment(constants::STENCIL_ATTACHMENT);
719                match (a, b) {
720                    (Some(Renderbuffer(ref a)), Some(Renderbuffer(ref b))) if a.id() == b.id() => {
721                    },
722                    (Some(Texture(ref a)), Some(Texture(ref b))) if a.id() == b.id() => {},
723                    (None, None) => {},
724                    _ => return Err(InvalidOperation),
725                }
726            },
727            constants::COLOR_ATTACHMENT0..=constants::COLOR_ATTACHMENT15 => {
728                let last_slot =
729                    constants::COLOR_ATTACHMENT0 + self.base.limits().max_color_attachments - 1;
730                if last_slot < attachment {
731                    return Err(InvalidEnum);
732                }
733            },
734            _ => return Err(InvalidEnum),
735        }
736
737        let attachment = match attachment {
738            constants::DEPTH_STENCIL_ATTACHMENT => constants::DEPTH_ATTACHMENT,
739            _ => attachment,
740        };
741
742        if pname == constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME {
743            match fb.attachment(attachment) {
744                Some(Renderbuffer(rb)) => {
745                    rb.to_jsval(cx, rval);
746                },
747                Some(Texture(texture)) => {
748                    texture.to_jsval(cx, rval);
749                },
750                _ => rval.set(NullValue()),
751            }
752            return Ok(());
753        }
754
755        match pname {
756            constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE => {},
757            _ => match fb.attachment(attachment) {
758                Some(webgl_attachment) => match pname {
759                    constants::FRAMEBUFFER_ATTACHMENT_RED_SIZE |
760                    constants::FRAMEBUFFER_ATTACHMENT_GREEN_SIZE |
761                    constants::FRAMEBUFFER_ATTACHMENT_BLUE_SIZE |
762                    constants::FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE |
763                    constants::FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE |
764                    constants::FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE |
765                    constants::FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE |
766                    constants::FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING => {},
767                    _ => match webgl_attachment {
768                        WebGLFramebufferAttachmentRoot::Renderbuffer(_) => return Err(InvalidEnum),
769                        WebGLFramebufferAttachmentRoot::Texture(_) => match pname {
770                            constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL |
771                            constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE |
772                            constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER => {},
773                            _ => return Err(InvalidEnum),
774                        },
775                    },
776                },
777                None => return Err(InvalidOperation),
778            },
779        }
780
781        let (sender, receiver) = webgl_channel().unwrap();
782        self.base
783            .send_command(WebGLCommand::GetFramebufferAttachmentParameter(
784                target, attachment, pname, sender,
785            ));
786
787        let retval = receiver.recv().unwrap();
788        rval.set(Int32Value(retval));
789        Ok(())
790    }
791
792    fn clearbuffer_array_size(&self, buffer: u32, draw_buffer: i32) -> WebGLResult<usize> {
793        match buffer {
794            constants::COLOR => {
795                if draw_buffer < 0 || draw_buffer as u32 >= self.base.limits().max_draw_buffers {
796                    return Err(InvalidValue);
797                }
798                Ok(4)
799            },
800            constants::DEPTH | constants::STENCIL | constants::DEPTH_STENCIL => {
801                if draw_buffer != 0 {
802                    return Err(InvalidValue);
803                }
804                Ok(1)
805            },
806            _ => unreachable!(),
807        }
808    }
809
810    fn clear_buffer<T: Clone>(
811        &self,
812        buffer: u32,
813        draw_buffer: i32,
814        valid_buffers: &[u32],
815        src_offset: u32,
816        array: Vec<T>,
817        msg: fn(u32, i32, Vec<T>) -> WebGLCommand,
818    ) {
819        if !valid_buffers.contains(&buffer) {
820            return self.base.webgl_error(InvalidEnum);
821        }
822
823        let array_size = match self.clearbuffer_array_size(buffer, draw_buffer) {
824            Ok(array_size) => array_size,
825            Err(error) => return self.base.webgl_error(error),
826        };
827        let src_offset = src_offset as usize;
828
829        if array.len() < src_offset + array_size {
830            return self.base.webgl_error(InvalidValue);
831        }
832        let array = array[src_offset..src_offset + array_size].to_vec();
833
834        self.base.send_command(msg(buffer, draw_buffer, array));
835        self.mark_as_dirty();
836    }
837
838    fn valid_fb_attachment_values(&self, target: u32, attachments: &[u32]) -> bool {
839        let fb_slot = match target {
840            constants::FRAMEBUFFER | constants::DRAW_FRAMEBUFFER => {
841                self.base.get_draw_framebuffer_slot()
842            },
843            constants::READ_FRAMEBUFFER => self.base.get_read_framebuffer_slot(),
844            _ => {
845                self.base.webgl_error(InvalidEnum);
846                return false;
847            },
848        };
849
850        if let Some(fb) = fb_slot.get() {
851            if fb.check_status() != constants::FRAMEBUFFER_COMPLETE {
852                return false;
853            }
854
855            for &attachment in attachments {
856                match attachment {
857                    constants::DEPTH_ATTACHMENT |
858                    constants::STENCIL_ATTACHMENT |
859                    constants::DEPTH_STENCIL_ATTACHMENT => {},
860                    constants::COLOR_ATTACHMENT0..=constants::COLOR_ATTACHMENT15 => {
861                        let last_slot = constants::COLOR_ATTACHMENT0 +
862                            self.base.limits().max_color_attachments -
863                            1;
864                        if last_slot < attachment {
865                            return false;
866                        }
867                    },
868                    _ => return false,
869                }
870            }
871        } else {
872            for &attachment in attachments {
873                match attachment {
874                    constants::COLOR | constants::DEPTH | constants::STENCIL => {},
875                    _ => return false,
876                }
877            }
878        }
879
880        true
881    }
882
883    fn vertex_attrib_i(&self, index: u32, x: i32, y: i32, z: i32, w: i32) {
884        if index >= self.base.limits().max_vertex_attribs {
885            return self.base.webgl_error(InvalidValue);
886        }
887        self.base.current_vertex_attribs()[index as usize] = VertexAttrib::Int(x, y, z, w);
888        self.base
889            .send_command(WebGLCommand::VertexAttribI(index, x, y, z, w));
890    }
891
892    fn vertex_attrib_u(&self, index: u32, x: u32, y: u32, z: u32, w: u32) {
893        if index >= self.base.limits().max_vertex_attribs {
894            return self.base.webgl_error(InvalidValue);
895        }
896        self.base.current_vertex_attribs()[index as usize] = VertexAttrib::Uint(x, y, z, w);
897        self.base
898            .send_command(WebGLCommand::VertexAttribU(index, x, y, z, w));
899    }
900
901    #[expect(clippy::too_many_arguments)]
902    fn tex_storage(
903        &self,
904        dimensions: u8,
905        target: u32,
906        levels: i32,
907        internal_format: u32,
908        width: i32,
909        height: i32,
910        depth: i32,
911    ) {
912        let validator = TexStorageValidator::new(
913            &self.base,
914            dimensions,
915            target,
916            levels,
917            internal_format,
918            width,
919            height,
920            depth,
921        );
922        let TexStorageValidatorResult {
923            texture,
924            target,
925            levels,
926            internal_format,
927            width,
928            height,
929            depth,
930        } = match validator.validate() {
931            Ok(result) => result,
932            Err(_) => return, // NB: The validator sets the correct error for us.
933        };
934
935        if let Err(error) = texture.storage(target, levels, internal_format, width, height, depth) {
936            self.base.webgl_error(error);
937        }
938    }
939
940    #[expect(clippy::too_many_arguments)]
941    fn tex_image_3d(
942        &self,
943        texture: &WebGLTexture,
944        target: TexImageTarget,
945        data_type: TexDataType,
946        internal_format: TexFormat,
947        format: TexFormat,
948        level: u32,
949        width: u32,
950        height: u32,
951        depth: u32,
952        _border: u32,
953        unpacking_alignment: u32,
954        data: TexPixels,
955    ) {
956        if let Err(error) = texture.initialize(
957            target,
958            width,
959            height,
960            depth,
961            internal_format,
962            level,
963            Some(data_type),
964        ) {
965            self.base.webgl_error(error);
966        }
967
968        let internal_format = self
969            .base
970            .extension_manager()
971            .get_effective_tex_internal_format(internal_format, data_type.as_gl_constant());
972        let effective_data_type = self
973            .base
974            .extension_manager()
975            .effective_type(data_type.as_gl_constant());
976
977        self.base.send_command(WebGLCommand::TexImage3D {
978            target: target.as_gl_constant(),
979            level,
980            internal_format,
981            size: data.size(),
982            depth,
983            format,
984            data_type,
985            effective_data_type,
986            unpacking_alignment,
987            alpha_treatment: data.alpha_treatment(),
988            y_axis_treatment: data.y_axis_treatment(),
989            pixel_format: data.pixel_format(),
990            data: data.into_shared_memory().into(),
991        });
992        // TODO: Hint/tex_parameter
993
994        if let Some(fb) = self.base.bound_draw_framebuffer() {
995            fb.invalidate_texture(texture);
996        }
997    }
998}
999
1000impl CanvasContext for WebGL2RenderingContext {
1001    type ID = WebGLContextId;
1002
1003    fn context_id(&self) -> Self::ID {
1004        self.base.context_id()
1005    }
1006
1007    fn canvas(&self) -> Option<RootedHTMLCanvasElementOrOffscreenCanvas> {
1008        self.base.canvas()
1009    }
1010
1011    fn resize(&self) {
1012        self.base.resize();
1013    }
1014
1015    fn reset_bitmap(&self) {
1016        self.base.reset_bitmap();
1017    }
1018
1019    fn get_image_data(&self) -> Option<Snapshot> {
1020        self.base.get_image_data()
1021    }
1022
1023    fn mark_as_dirty(&self) {
1024        self.base.mark_as_dirty()
1025    }
1026}
1027
1028impl WebGL2RenderingContextMethods<crate::DomTypeHolder> for WebGL2RenderingContext {
1029    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1>
1030    fn Canvas(&self) -> RootedHTMLCanvasElementOrOffscreenCanvas {
1031        self.base.Canvas()
1032    }
1033
1034    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11>
1035    fn Flush(&self) {
1036        self.base.Flush()
1037    }
1038
1039    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11>
1040    fn Finish(&self) {
1041        self.base.Finish()
1042    }
1043
1044    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1>
1045    fn DrawingBufferWidth(&self) -> i32 {
1046        self.base.DrawingBufferWidth()
1047    }
1048
1049    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1>
1050    fn DrawingBufferHeight(&self) -> i32 {
1051        self.base.DrawingBufferHeight()
1052    }
1053
1054    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
1055    fn GetBufferParameter(
1056        &self,
1057        cx: &mut JSContext,
1058        target: u32,
1059        parameter: u32,
1060        mut retval: MutableHandleValue,
1061    ) {
1062        let buffer = match self.bound_buffer(cx, target) {
1063            Ok(buffer) => buffer,
1064            Err(error) => {
1065                self.base.webgl_error(error);
1066                return retval.set(NullValue());
1067            },
1068        };
1069        self.base.get_buffer_param(buffer, parameter, retval)
1070    }
1071
1072    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1073    fn GetParameter(&self, cx: &mut JSContext, parameter: u32, mut rval: MutableHandleValue) {
1074        match parameter {
1075            constants::VERSION => {
1076                "WebGL 2.0".to_jsval(cx, rval);
1077                return;
1078            },
1079            constants::SHADING_LANGUAGE_VERSION => {
1080                "WebGL GLSL ES 3.00".to_jsval(cx, rval);
1081                return;
1082            },
1083            constants::IMPLEMENTATION_COLOR_READ_FORMAT |
1084            constants::IMPLEMENTATION_COLOR_READ_TYPE => {
1085                // The WebGL spec makes an incomplete framebuffer INVALID_OPERATION here.
1086                let (format, pixel_type) = match self
1087                    .base
1088                    .validate_framebuffer()
1089                    .and_then(|()| self.accepted_read_pixels_format_types())
1090                {
1091                    Ok(accepted) => accepted[accepted.len() - 1],
1092                    Err(_) => {
1093                        self.base.webgl_error(InvalidOperation);
1094                        return rval.set(NullValue());
1095                    },
1096                };
1097                let value = if parameter == constants::IMPLEMENTATION_COLOR_READ_FORMAT {
1098                    format
1099                } else {
1100                    pixel_type
1101                };
1102                rval.set(Int32Value(value as i32));
1103                return;
1104            },
1105            constants::MAX_CLIENT_WAIT_TIMEOUT_WEBGL => {
1106                rval.set(DoubleValue(
1107                    self.base.limits().max_client_wait_timeout_webgl.as_nanos() as f64,
1108                ));
1109                return;
1110            },
1111            constants::UNPACK_ROW_LENGTH |
1112            constants::UNPACK_IMAGE_HEIGHT |
1113            constants::UNPACK_SKIP_PIXELS |
1114            constants::UNPACK_SKIP_ROWS |
1115            constants::UNPACK_SKIP_IMAGES => {
1116                let layout = self.base.texture_unpack_layout();
1117                let value = match parameter {
1118                    constants::UNPACK_ROW_LENGTH => layout.row_length,
1119                    constants::UNPACK_IMAGE_HEIGHT => layout.image_height,
1120                    constants::UNPACK_SKIP_PIXELS => layout.skip_pixels,
1121                    constants::UNPACK_SKIP_ROWS => layout.skip_rows,
1122                    _ => layout.skip_images,
1123                };
1124                rval.set(Int32Value(value as i32));
1125                return;
1126            },
1127            constants::MAX_SERVER_WAIT_TIMEOUT => {
1128                rval.set(DoubleValue(
1129                    self.base.limits().max_server_wait_timeout.as_nanos() as f64,
1130                ));
1131                return;
1132            },
1133            constants::SAMPLER_BINDING => {
1134                let idx = (self.base.textures().active_unit_enum() - constants::TEXTURE0) as usize;
1135                assert!(idx < self.samplers.len());
1136                let sampler = self.samplers[idx].get();
1137                sampler.to_jsval(cx, rval);
1138                return;
1139            },
1140            constants::COPY_READ_BUFFER_BINDING => {
1141                self.bound_copy_read_buffer.get().to_jsval(cx, rval);
1142                return;
1143            },
1144            constants::COPY_WRITE_BUFFER_BINDING => {
1145                self.bound_copy_write_buffer.get().to_jsval(cx, rval);
1146                return;
1147            },
1148            constants::PIXEL_PACK_BUFFER_BINDING => {
1149                self.bound_pixel_pack_buffer.get().to_jsval(cx, rval);
1150                return;
1151            },
1152            constants::PIXEL_UNPACK_BUFFER_BINDING => {
1153                self.bound_pixel_unpack_buffer.get().to_jsval(cx, rval);
1154                return;
1155            },
1156            constants::TRANSFORM_FEEDBACK_BUFFER_BINDING => {
1157                self.bound_transform_feedback_buffer
1158                    .get()
1159                    .to_jsval(cx, rval);
1160                return;
1161            },
1162            constants::UNIFORM_BUFFER_BINDING => {
1163                self.bound_uniform_buffer.get().to_jsval(cx, rval);
1164                return;
1165            },
1166            constants::TRANSFORM_FEEDBACK_BINDING => {
1167                self.current_transform_feedback.get().to_jsval(cx, rval);
1168                return;
1169            },
1170            constants::ELEMENT_ARRAY_BUFFER_BINDING => {
1171                let buffer = self.current_vao(cx).element_array_buffer().get();
1172                buffer.to_jsval(cx, rval);
1173                return;
1174            },
1175            constants::VERTEX_ARRAY_BINDING => {
1176                let vao = self.current_vao(cx);
1177                let vao = vao.id().map(|_| &*vao);
1178                vao.to_jsval(cx, rval);
1179                return;
1180            },
1181            // NOTE: DRAW_FRAMEBUFFER_BINDING is the same as FRAMEBUFFER_BINDING, handled on the WebGL1 side
1182            constants::READ_FRAMEBUFFER_BINDING => {
1183                self.base
1184                    .get_read_framebuffer_slot()
1185                    .get()
1186                    .to_jsval(cx, rval);
1187                return;
1188            },
1189            constants::READ_BUFFER => {
1190                let buffer = match self.base.get_read_framebuffer_slot().get() {
1191                    Some(fb) => fb.read_buffer(),
1192                    None => self.default_fb_readbuffer.get(),
1193                };
1194                rval.set(UInt32Value(buffer));
1195                return;
1196            },
1197            constants::DRAW_BUFFER0..=constants::DRAW_BUFFER15 => {
1198                let buffer = match self.base.get_read_framebuffer_slot().get() {
1199                    Some(fb) => {
1200                        let idx = parameter - constants::DRAW_BUFFER0;
1201                        fb.draw_buffer_i(idx as usize)
1202                    },
1203                    None if parameter == constants::DRAW_BUFFER0 => {
1204                        self.default_fb_readbuffer.get()
1205                    },
1206                    None => constants::NONE,
1207                };
1208                rval.set(UInt32Value(buffer));
1209                return;
1210            },
1211            constants::MAX_TEXTURE_LOD_BIAS => {
1212                rval.set(DoubleValue(self.base.limits().max_texture_lod_bias as f64));
1213                return;
1214            },
1215            constants::MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS => {
1216                rval.set(DoubleValue(
1217                    self.base.limits().max_combined_fragment_uniform_components as f64,
1218                ));
1219                return;
1220            },
1221            constants::MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS => {
1222                rval.set(DoubleValue(
1223                    self.base.limits().max_combined_vertex_uniform_components as f64,
1224                ));
1225                return;
1226            },
1227            constants::MAX_ELEMENT_INDEX => {
1228                rval.set(DoubleValue(self.base.limits().max_element_index as f64));
1229                return;
1230            },
1231            constants::MAX_UNIFORM_BLOCK_SIZE => {
1232                rval.set(DoubleValue(
1233                    self.base.limits().max_uniform_block_size as f64,
1234                ));
1235                return;
1236            },
1237            constants::MIN_PROGRAM_TEXEL_OFFSET => {
1238                rval.set(Int32Value(self.base.limits().min_program_texel_offset));
1239                return;
1240            },
1241            _ => {},
1242        }
1243
1244        let limit = match parameter {
1245            constants::MAX_3D_TEXTURE_SIZE => Some(self.base.limits().max_3d_texture_size),
1246            constants::MAX_ARRAY_TEXTURE_LAYERS => {
1247                Some(self.base.limits().max_array_texture_layers)
1248            },
1249            constants::MAX_COLOR_ATTACHMENTS => Some(self.base.limits().max_color_attachments),
1250            constants::MAX_COMBINED_UNIFORM_BLOCKS => {
1251                Some(self.base.limits().max_combined_uniform_blocks)
1252            },
1253            constants::MAX_DRAW_BUFFERS => Some(self.base.limits().max_draw_buffers),
1254            constants::MAX_ELEMENTS_INDICES => Some(self.base.limits().max_elements_indices),
1255            constants::MAX_ELEMENTS_VERTICES => Some(self.base.limits().max_elements_vertices),
1256            constants::MAX_FRAGMENT_INPUT_COMPONENTS => {
1257                Some(self.base.limits().max_fragment_input_components)
1258            },
1259            constants::MAX_FRAGMENT_UNIFORM_BLOCKS => {
1260                Some(self.base.limits().max_fragment_uniform_blocks)
1261            },
1262            constants::MAX_FRAGMENT_UNIFORM_COMPONENTS => {
1263                Some(self.base.limits().max_fragment_uniform_components)
1264            },
1265            constants::MAX_PROGRAM_TEXEL_OFFSET => {
1266                Some(self.base.limits().max_program_texel_offset)
1267            },
1268            constants::MAX_SAMPLES => Some(self.base.limits().max_samples),
1269            constants::MAX_UNIFORM_BUFFER_BINDINGS => {
1270                Some(self.base.limits().max_uniform_buffer_bindings)
1271            },
1272            constants::MAX_VARYING_COMPONENTS => Some(self.base.limits().max_varying_components),
1273            constants::MAX_VERTEX_OUTPUT_COMPONENTS => {
1274                Some(self.base.limits().max_vertex_output_components)
1275            },
1276            constants::MAX_VERTEX_UNIFORM_BLOCKS => {
1277                Some(self.base.limits().max_vertex_uniform_blocks)
1278            },
1279            constants::MAX_VERTEX_UNIFORM_COMPONENTS => {
1280                Some(self.base.limits().max_vertex_uniform_components)
1281            },
1282            constants::UNIFORM_BUFFER_OFFSET_ALIGNMENT => {
1283                Some(self.base.limits().uniform_buffer_offset_alignment)
1284            },
1285            _ => None,
1286        };
1287        if let Some(limit) = limit {
1288            rval.set(UInt32Value(limit));
1289            return;
1290        }
1291
1292        self.base.GetParameter(cx, parameter, rval)
1293    }
1294
1295    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
1296    fn GetTexParameter(
1297        &self,
1298        cx: &mut JSContext,
1299        target: u32,
1300        pname: u32,
1301        retval: MutableHandleValue,
1302    ) {
1303        self.base.GetTexParameter(cx, target, pname, retval)
1304    }
1305
1306    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1307    fn GetError(&self) -> u32 {
1308        self.base.GetError()
1309    }
1310
1311    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.2>
1312    fn GetContextAttributes(&self) -> Option<WebGLContextAttributes> {
1313        self.base.GetContextAttributes()
1314    }
1315
1316    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.13>
1317    fn IsContextLost(&self) -> bool {
1318        self.base.IsContextLost()
1319    }
1320
1321    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14>
1322    fn GetSupportedExtensions(&self) -> Option<Vec<DOMString>> {
1323        self.base.GetSupportedExtensions()
1324    }
1325
1326    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14>
1327    fn GetExtension(
1328        &self,
1329        cx: &mut js::context::JSContext,
1330        name: DOMString,
1331        return_value: MutableHandleObject,
1332    ) {
1333        self.base.GetExtension(cx, name, return_value)
1334    }
1335
1336    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.4>
1337    fn GetFramebufferAttachmentParameter(
1338        &self,
1339        cx: &mut JSContext,
1340        target: u32,
1341        attachment: u32,
1342        pname: u32,
1343        mut rval: MutableHandleValue,
1344    ) {
1345        let fb_slot = match target {
1346            constants::FRAMEBUFFER | constants::DRAW_FRAMEBUFFER => {
1347                self.base.get_draw_framebuffer_slot()
1348            },
1349            constants::READ_FRAMEBUFFER => self.base.get_read_framebuffer_slot(),
1350            _ => {
1351                self.base.webgl_error(InvalidEnum);
1352                rval.set(NullValue());
1353                return;
1354            },
1355        };
1356
1357        if let Some(fb) = fb_slot.get() {
1358            // A selected framebuffer is bound to the target
1359            if let Err(error) = fb.validate_transparent() {
1360                self.base.webgl_error(error);
1361                return rval.set(NullValue());
1362            }
1363            if let Err(error) = self.get_specific_fb_attachment_param(
1364                cx,
1365                &fb,
1366                target,
1367                attachment,
1368                pname,
1369                rval.reborrow(),
1370            ) {
1371                self.base.webgl_error(error);
1372                rval.set(NullValue());
1373            }
1374        } else {
1375            // The default framebuffer is bound to the target
1376            if let Err(error) =
1377                self.get_default_fb_attachment_param(attachment, pname, rval.reborrow())
1378            {
1379                self.base.webgl_error(error);
1380                rval.set(NullValue());
1381            }
1382        }
1383    }
1384
1385    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
1386    fn GetRenderbufferParameter(
1387        &self,
1388        cx: &mut JSContext,
1389        target: u32,
1390        pname: u32,
1391        retval: MutableHandleValue,
1392    ) {
1393        self.base
1394            .GetRenderbufferParameter(cx, target, pname, retval)
1395    }
1396
1397    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1398    fn ActiveTexture(&self, texture: u32) {
1399        self.base.ActiveTexture(texture)
1400    }
1401
1402    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1403    fn BlendColor(&self, r: f32, g: f32, b: f32, a: f32) {
1404        self.base.BlendColor(r, g, b, a)
1405    }
1406
1407    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1408    fn BlendEquation(&self, mode: u32) {
1409        self.base.BlendEquation(mode)
1410    }
1411
1412    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1413    fn BlendEquationSeparate(&self, mode_rgb: u32, mode_alpha: u32) {
1414        self.base.BlendEquationSeparate(mode_rgb, mode_alpha)
1415    }
1416
1417    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1418    fn BlendFunc(&self, src_factor: u32, dest_factor: u32) {
1419        self.base.BlendFunc(src_factor, dest_factor)
1420    }
1421
1422    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1423    fn BlendFuncSeparate(&self, src_rgb: u32, dest_rgb: u32, src_alpha: u32, dest_alpha: u32) {
1424        self.base
1425            .BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha)
1426    }
1427
1428    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
1429    fn AttachShader(&self, program: &WebGLProgram, shader: &WebGLShader) {
1430        self.base.AttachShader(program, shader)
1431    }
1432
1433    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
1434    fn DetachShader(&self, program: &WebGLProgram, shader: &WebGLShader) {
1435        self.base.DetachShader(program, shader)
1436    }
1437
1438    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
1439    fn BindAttribLocation(&self, program: &WebGLProgram, index: u32, name: DOMString) {
1440        self.base.BindAttribLocation(program, index, name)
1441    }
1442
1443    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.2>
1444    fn BindBuffer(&self, cx: &mut JSContext, target: u32, buffer: Option<&WebGLBuffer>) {
1445        let current_vao;
1446        let slot = match target {
1447            constants::COPY_READ_BUFFER => &self.bound_copy_read_buffer,
1448            constants::COPY_WRITE_BUFFER => &self.bound_copy_write_buffer,
1449            constants::PIXEL_PACK_BUFFER => &self.bound_pixel_pack_buffer,
1450            constants::PIXEL_UNPACK_BUFFER => &self.bound_pixel_unpack_buffer,
1451            constants::TRANSFORM_FEEDBACK_BUFFER => &self.bound_transform_feedback_buffer,
1452            constants::UNIFORM_BUFFER => &self.bound_uniform_buffer,
1453            constants::ELEMENT_ARRAY_BUFFER => {
1454                current_vao = self.current_vao(cx);
1455                current_vao.element_array_buffer()
1456            },
1457            _ => return self.base.BindBuffer(cx, target, buffer),
1458        };
1459        self.base.bind_buffer_maybe(slot, target, buffer);
1460    }
1461
1462    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
1463    fn BindFramebuffer(&self, target: u32, framebuffer: Option<&WebGLFramebuffer>) {
1464        if let Err(error) = self.base.validate_new_framebuffer_binding(framebuffer) {
1465            return self.base.webgl_error(error);
1466        }
1467
1468        let (bind_read, bind_draw) = match target {
1469            constants::FRAMEBUFFER => (true, true),
1470            constants::READ_FRAMEBUFFER => (true, false),
1471            constants::DRAW_FRAMEBUFFER => (false, true),
1472            _ => return self.base.webgl_error(InvalidEnum),
1473        };
1474        if bind_read {
1475            self.base.bind_framebuffer_to(
1476                target,
1477                framebuffer,
1478                self.base.get_read_framebuffer_slot(),
1479            );
1480        }
1481        if bind_draw {
1482            self.base.bind_framebuffer_to(
1483                target,
1484                framebuffer,
1485                self.base.get_draw_framebuffer_slot(),
1486            );
1487        }
1488    }
1489
1490    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
1491    fn BindRenderbuffer(&self, target: u32, renderbuffer: Option<&WebGLRenderbuffer>) {
1492        self.base.BindRenderbuffer(target, renderbuffer)
1493    }
1494
1495    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
1496    fn BindTexture(&self, target: u32, texture: Option<&WebGLTexture>) {
1497        self.base.BindTexture(target, texture)
1498    }
1499
1500    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
1501    fn GenerateMipmap(&self, target: u32) {
1502        self.base.GenerateMipmap(target)
1503    }
1504
1505    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
1506    fn BufferData_(
1507        &self,
1508        cx: &mut JSContext,
1509        target: u32,
1510        data: Option<ArrayBufferViewOrArrayBuffer>,
1511        usage: u32,
1512    ) {
1513        let usage = match self.buffer_usage(usage) {
1514            Ok(usage) => usage,
1515            Err(error) => return self.base.webgl_error(error),
1516        };
1517        let bound_buffer = match self.bound_buffer(cx, target) {
1518            Ok(bound_buffer) => bound_buffer,
1519            Err(error) => return self.base.webgl_error(error),
1520        };
1521        self.base
1522            .buffer_data(cx.no_gc(), target, data, usage, bound_buffer)
1523    }
1524
1525    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
1526    fn BufferData(&self, cx: &mut JSContext, target: u32, size: i64, usage: u32) {
1527        let usage = match self.buffer_usage(usage) {
1528            Ok(usage) => usage,
1529            Err(error) => return self.base.webgl_error(error),
1530        };
1531        let bound_buffer = match self.bound_buffer(cx, target) {
1532            Ok(bound_buffer) => bound_buffer,
1533            Err(error) => return self.base.webgl_error(error),
1534        };
1535        self.base.buffer_data_(target, size, usage, bound_buffer)
1536    }
1537
1538    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.3>
1539    fn BufferData__(
1540        &self,
1541        cx: &mut JSContext,
1542        target: u32,
1543        data: CustomAutoRooterGuard<ArrayBufferView>,
1544        usage: u32,
1545        elem_offset: u32,
1546        length: u32,
1547    ) {
1548        let usage = match self.buffer_usage(usage) {
1549            Ok(usage) => usage,
1550            Err(error) => return self.base.webgl_error(error),
1551        };
1552        let bound_buffer = match self.bound_buffer(cx, target) {
1553            Ok(bound_buffer) => bound_buffer,
1554            Err(error) => return self.base.webgl_error(error),
1555        };
1556        let Some(bound_buffer) = bound_buffer else {
1557            return self.base.webgl_error(InvalidOperation);
1558        };
1559
1560        let elem_size = data.get_array_type().byte_size().unwrap();
1561        let elem_count = data.len() / elem_size;
1562        let elem_offset = elem_offset as usize;
1563        let byte_offset = elem_offset * elem_size;
1564
1565        if byte_offset > data.len() {
1566            return self.base.webgl_error(InvalidValue);
1567        }
1568
1569        let copy_count = if length == 0 {
1570            elem_count - elem_offset
1571        } else {
1572            length as usize
1573        };
1574        if copy_count == 0 {
1575            return;
1576        }
1577        let copy_bytes = copy_count * elem_size;
1578
1579        if byte_offset + copy_bytes > data.len() {
1580            return self.base.webgl_error(InvalidValue);
1581        }
1582
1583        let data_end = byte_offset + copy_bytes;
1584        let data = data.as_slice_safe(cx.no_gc()).unwrap_or(&[]);
1585        let data = &data[byte_offset..data_end];
1586        if let Err(error) = bound_buffer.buffer_data(target, data, usage) {
1587            self.base.webgl_error(error);
1588        }
1589    }
1590
1591    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
1592    fn BufferSubData(
1593        &self,
1594        cx: &mut JSContext,
1595        target: u32,
1596        offset: i64,
1597        data: ArrayBufferViewOrArrayBuffer,
1598    ) {
1599        let bound_buffer = match self.bound_buffer(cx, target) {
1600            Ok(bound_buffer) => bound_buffer,
1601            Err(error) => return self.base.webgl_error(error),
1602        };
1603        self.base
1604            .buffer_sub_data(cx.no_gc(), target, offset, data, bound_buffer)
1605    }
1606
1607    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.3>
1608    fn BufferSubData_(
1609        &self,
1610        cx: &mut JSContext,
1611        target: u32,
1612        dst_byte_offset: i64,
1613        src_data: CustomAutoRooterGuard<ArrayBufferView>,
1614        src_elem_offset: u32,
1615        length: u32,
1616    ) {
1617        let bound_buffer = match self.bound_buffer(cx, target) {
1618            Ok(bound_buffer) => bound_buffer,
1619            Err(error) => return self.base.webgl_error(error),
1620        };
1621        let Some(bound_buffer) = bound_buffer else {
1622            return self.base.webgl_error(InvalidOperation);
1623        };
1624
1625        let src_elem_size = src_data.get_array_type().byte_size().unwrap();
1626        let src_elem_count = src_data.len() / src_elem_size;
1627        let src_elem_offset = src_elem_offset as usize;
1628        let src_byte_offset = src_elem_offset * src_elem_size;
1629
1630        if dst_byte_offset < 0 || src_byte_offset > src_data.len() {
1631            return self.base.webgl_error(InvalidValue);
1632        }
1633
1634        let copy_count = if length == 0 {
1635            src_elem_count - src_elem_offset
1636        } else {
1637            length as usize
1638        };
1639        if copy_count == 0 {
1640            return;
1641        }
1642        let copy_bytes = copy_count * src_elem_size;
1643
1644        let dst_byte_offset = dst_byte_offset as usize;
1645        if dst_byte_offset + copy_bytes > bound_buffer.capacity() ||
1646            src_byte_offset + copy_bytes > src_data.len()
1647        {
1648            return self.base.webgl_error(InvalidValue);
1649        }
1650
1651        let (sender, receiver) = generic_channel::channel().unwrap();
1652        self.base.send_command(WebGLCommand::BufferSubData(
1653            target,
1654            dst_byte_offset as isize,
1655            receiver,
1656        ));
1657        let src_end = src_byte_offset + copy_bytes;
1658        let data = src_data.as_slice_safe(cx.no_gc()).unwrap_or(&[]);
1659        let data = &data[src_byte_offset..src_end];
1660        let buffer = GenericSharedMemory::from_bytes(data);
1661        sender.send(buffer).unwrap();
1662    }
1663
1664    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.3>
1665    fn CopyBufferSubData(
1666        &self,
1667        cx: &mut JSContext,
1668        read_target: u32,
1669        write_target: u32,
1670        read_offset: i64,
1671        write_offset: i64,
1672        size: i64,
1673    ) {
1674        if read_offset < 0 || write_offset < 0 || size < 0 {
1675            return self.base.webgl_error(InvalidValue);
1676        }
1677
1678        let read_buffer = match self.bound_buffer(cx, read_target) {
1679            Ok(read_buffer) => read_buffer,
1680            Err(error) => return self.base.webgl_error(error),
1681        };
1682        let Some(read_buffer) = read_buffer else {
1683            return self.base.webgl_error(InvalidOperation);
1684        };
1685
1686        let write_buffer = match self.bound_buffer(cx, write_target) {
1687            Ok(write_buffer) => write_buffer,
1688            Err(error) => return self.base.webgl_error(error),
1689        };
1690        let Some(write_buffer) = write_buffer else {
1691            return self.base.webgl_error(InvalidOperation);
1692        };
1693
1694        let read_until = read_offset + size;
1695        let write_until = write_offset + size;
1696        if read_until as usize > read_buffer.capacity() ||
1697            write_until as usize > write_buffer.capacity()
1698        {
1699            return self.base.webgl_error(InvalidValue);
1700        }
1701
1702        if read_target == write_target {
1703            let is_separate = read_until <= write_offset || write_until <= read_offset;
1704            if !is_separate {
1705                return self.base.webgl_error(InvalidValue);
1706            }
1707        }
1708        let src_is_elemarray = read_buffer
1709            .target()
1710            .is_some_and(|t| t == constants::ELEMENT_ARRAY_BUFFER);
1711        let dst_is_elemarray = write_buffer
1712            .target()
1713            .is_some_and(|t| t == constants::ELEMENT_ARRAY_BUFFER);
1714        if src_is_elemarray != dst_is_elemarray {
1715            return self.base.webgl_error(InvalidOperation);
1716        }
1717
1718        self.base.send_command(WebGLCommand::CopyBufferSubData(
1719            read_target,
1720            write_target,
1721            read_offset,
1722            write_offset,
1723            size,
1724        ));
1725    }
1726
1727    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.3>
1728    fn GetBufferSubData(
1729        &self,
1730        cx: &mut JSContext,
1731        target: u32,
1732        src_byte_offset: i64,
1733        mut dst_buffer: CustomAutoRooterGuard<ArrayBufferView>,
1734        dst_elem_offset: u32,
1735        length: u32,
1736    ) {
1737        let bound_buffer = match self.bound_buffer(cx, target) {
1738            Ok(bound_buffer) => bound_buffer,
1739            Err(error) => return self.base.webgl_error(error),
1740        };
1741        let Some(bound_buffer) = bound_buffer else {
1742            return self.base.webgl_error(InvalidOperation);
1743        };
1744
1745        let dst_elem_size = dst_buffer.get_array_type().byte_size().unwrap();
1746        let dst_elem_count = dst_buffer.len() / dst_elem_size;
1747        let dst_elem_offset = dst_elem_offset as usize;
1748        let dst_byte_offset = dst_elem_offset * dst_elem_size;
1749
1750        if src_byte_offset < 0 || dst_byte_offset > dst_buffer.len() {
1751            return self.base.webgl_error(InvalidValue);
1752        }
1753
1754        let copy_count = if length == 0 {
1755            dst_elem_count - dst_elem_offset
1756        } else {
1757            length as usize
1758        };
1759        if copy_count == 0 {
1760            return;
1761        }
1762        let copy_bytes = copy_count * dst_elem_size;
1763
1764        // TODO(mmatyas): Transform Feedback
1765
1766        let src_byte_offset = src_byte_offset as usize;
1767        if src_byte_offset + copy_bytes > bound_buffer.capacity() ||
1768            dst_byte_offset + copy_bytes > dst_buffer.len()
1769        {
1770            return self.base.webgl_error(InvalidValue);
1771        }
1772
1773        let (sender, receiver) = generic_channel::channel().unwrap();
1774        self.base.send_command(WebGLCommand::GetBufferSubData(
1775            target,
1776            src_byte_offset,
1777            copy_bytes,
1778            sender,
1779        ));
1780        let data = receiver.recv().unwrap();
1781        let dst_end = dst_byte_offset + copy_bytes;
1782        let dst_buffer = dst_buffer.as_mut_slice_safe(cx.no_gc()).unwrap_or(&mut []);
1783        dst_buffer[dst_byte_offset..dst_end].copy_from_slice(&data);
1784    }
1785
1786    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.6>
1787    fn CompressedTexImage2D(
1788        &self,
1789        no_gc: &NoGC,
1790        target: u32,
1791        level: i32,
1792        internal_format: u32,
1793        width: i32,
1794        height: i32,
1795        border: i32,
1796        pixels: CustomAutoRooterGuard<ArrayBufferView>,
1797        src_offset: u32,
1798        src_length_override: u32,
1799    ) {
1800        let mut data = pixels.as_slice_safe(no_gc).unwrap_or(&[]);
1801        let start = src_offset as usize;
1802        let end = (src_offset + src_length_override) as usize;
1803        if start > data.len() || end > data.len() {
1804            self.base.webgl_error(InvalidValue);
1805            return;
1806        }
1807        if src_length_override != 0 {
1808            data = &data[start..end];
1809        }
1810        self.base.compressed_tex_image_2d(
1811            target,
1812            level,
1813            internal_format,
1814            width,
1815            height,
1816            border,
1817            data,
1818        )
1819    }
1820
1821    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
1822    fn CompressedTexSubImage2D(
1823        &self,
1824        no_gc: &NoGC,
1825        target: u32,
1826        level: i32,
1827        xoffset: i32,
1828        yoffset: i32,
1829        width: i32,
1830        height: i32,
1831        format: u32,
1832        pixels: CustomAutoRooterGuard<ArrayBufferView>,
1833        src_offset: u32,
1834        src_length_override: u32,
1835    ) {
1836        let mut data = pixels.as_slice_safe(no_gc).unwrap_or(&[]);
1837        let start = src_offset as usize;
1838        let end = (src_offset + src_length_override) as usize;
1839        if start > data.len() || end > data.len() {
1840            self.base.webgl_error(InvalidValue);
1841            return;
1842        }
1843        if src_length_override != 0 {
1844            data = &data[start..end];
1845        }
1846        self.base.compressed_tex_sub_image_2d(
1847            target, level, xoffset, yoffset, width, height, format, data,
1848        )
1849    }
1850
1851    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
1852    fn CopyTexImage2D(
1853        &self,
1854        target: u32,
1855        level: i32,
1856        internal_format: u32,
1857        x: i32,
1858        y: i32,
1859        width: i32,
1860        height: i32,
1861        border: i32,
1862    ) {
1863        self.base
1864            .CopyTexImage2D(target, level, internal_format, x, y, width, height, border)
1865    }
1866
1867    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
1868    fn CopyTexSubImage2D(
1869        &self,
1870        target: u32,
1871        level: i32,
1872        xoffset: i32,
1873        yoffset: i32,
1874        x: i32,
1875        y: i32,
1876        width: i32,
1877        height: i32,
1878    ) {
1879        self.base
1880            .CopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height)
1881    }
1882
1883    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11>
1884    fn Clear(&self, mask: u32) {
1885        self.base.Clear(mask)
1886    }
1887
1888    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1889    fn ClearColor(&self, red: f32, green: f32, blue: f32, alpha: f32) {
1890        self.base.ClearColor(red, green, blue, alpha)
1891    }
1892
1893    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1894    fn ClearDepth(&self, depth: f32) {
1895        self.base.ClearDepth(depth)
1896    }
1897
1898    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1899    fn ClearStencil(&self, stencil: i32) {
1900        self.base.ClearStencil(stencil)
1901    }
1902
1903    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1904    fn ColorMask(&self, r: bool, g: bool, b: bool, a: bool) {
1905        self.base.ColorMask(r, g, b, a)
1906    }
1907
1908    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1909    fn CullFace(&self, mode: u32) {
1910        self.base.CullFace(mode)
1911    }
1912
1913    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1914    fn FrontFace(&self, mode: u32) {
1915        self.base.FrontFace(mode)
1916    }
1917    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1918    fn DepthFunc(&self, func: u32) {
1919        self.base.DepthFunc(func)
1920    }
1921
1922    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1923    fn DepthMask(&self, flag: bool) {
1924        self.base.DepthMask(flag)
1925    }
1926
1927    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1928    fn DepthRange(&self, near: f32, far: f32) {
1929        self.base.DepthRange(near, far)
1930    }
1931
1932    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1933    fn Enable(&self, cap: u32) {
1934        match cap {
1935            constants::RASTERIZER_DISCARD => {
1936                self.enable_rasterizer_discard.set(true);
1937                self.base.send_command(WebGLCommand::Enable(cap));
1938            },
1939            _ => self.base.Enable(cap),
1940        }
1941    }
1942
1943    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
1944    fn Disable(&self, cap: u32) {
1945        match cap {
1946            constants::RASTERIZER_DISCARD => {
1947                self.enable_rasterizer_discard.set(false);
1948                self.base.send_command(WebGLCommand::Disable(cap));
1949            },
1950            _ => self.base.Disable(cap),
1951        }
1952    }
1953
1954    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
1955    fn CompileShader(&self, shader: &WebGLShader) {
1956        self.base.CompileShader(shader)
1957    }
1958
1959    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
1960    fn CreateBuffer(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLBuffer>> {
1961        self.base.CreateBuffer(cx)
1962    }
1963
1964    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
1965    fn CreateFramebuffer(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLFramebuffer>> {
1966        self.base.CreateFramebuffer(cx)
1967    }
1968
1969    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
1970    fn CreateRenderbuffer(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLRenderbuffer>> {
1971        self.base.CreateRenderbuffer(cx)
1972    }
1973
1974    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
1975    fn CreateTexture(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLTexture>> {
1976        self.base.CreateTexture(cx)
1977    }
1978
1979    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
1980    fn CreateProgram(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLProgram>> {
1981        self.base.CreateProgram(cx)
1982    }
1983
1984    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
1985    fn CreateShader(&self, cx: &mut JSContext, shader_type: u32) -> Option<DomRoot<WebGLShader>> {
1986        self.base.CreateShader(cx, shader_type)
1987    }
1988
1989    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.17>
1990    fn CreateVertexArray(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLVertexArrayObject>> {
1991        self.base.create_vertex_array_webgl2(cx)
1992    }
1993
1994    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
1995    fn DeleteBuffer(&self, cx: &mut JSContext, buffer: Option<&WebGLBuffer>) {
1996        let buffer = match buffer {
1997            Some(buffer) => buffer,
1998            None => return,
1999        };
2000        if let Err(error) = self.base.validate_ownership(buffer) {
2001            return self.base.webgl_error(error);
2002        }
2003        if buffer.is_marked_for_deletion() {
2004            return;
2005        }
2006        self.current_vao(cx).unbind_buffer(buffer);
2007        self.unbind_from(self.base.array_buffer_slot(), buffer);
2008        self.unbind_from(&self.bound_copy_read_buffer, buffer);
2009        self.unbind_from(&self.bound_copy_write_buffer, buffer);
2010        self.unbind_from(&self.bound_pixel_pack_buffer, buffer);
2011        self.unbind_from(&self.bound_pixel_unpack_buffer, buffer);
2012        self.unbind_from(&self.bound_transform_feedback_buffer, buffer);
2013        self.unbind_from(&self.bound_uniform_buffer, buffer);
2014
2015        for binding in self.indexed_uniform_buffer_bindings.iter() {
2016            self.unbind_from(&binding.buffer, buffer);
2017        }
2018        for binding in self.indexed_transform_feedback_buffer_bindings.iter() {
2019            self.unbind_from(&binding.buffer, buffer);
2020        }
2021
2022        buffer.mark_for_deletion(Operation::Infallible);
2023    }
2024
2025    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
2026    fn DeleteFramebuffer(&self, framebuffer: Option<&WebGLFramebuffer>) {
2027        self.base.DeleteFramebuffer(framebuffer)
2028    }
2029
2030    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
2031    fn DeleteRenderbuffer(&self, renderbuffer: Option<&WebGLRenderbuffer>) {
2032        self.base.DeleteRenderbuffer(renderbuffer)
2033    }
2034
2035    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
2036    fn DeleteTexture(&self, texture: Option<&WebGLTexture>) {
2037        self.base.DeleteTexture(texture)
2038    }
2039
2040    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2041    fn DeleteProgram(&self, program: Option<&WebGLProgram>) {
2042        self.base.DeleteProgram(program)
2043    }
2044
2045    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2046    fn DeleteShader(&self, shader: Option<&WebGLShader>) {
2047        self.base.DeleteShader(shader)
2048    }
2049
2050    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.17>
2051    fn DeleteVertexArray(&self, cx: &mut JSContext, vertex_array: Option<&WebGLVertexArrayObject>) {
2052        self.base.delete_vertex_array_webgl2(cx, vertex_array);
2053    }
2054
2055    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11>
2056    fn DrawArrays(&self, cx: &mut JSContext, mode: u32, first: i32, count: i32) {
2057        self.validate_uniform_block_for_draw();
2058        self.validate_vertex_attribs_for_draw(cx);
2059        self.base.DrawArrays(cx, mode, first, count)
2060    }
2061
2062    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11>
2063    fn DrawElements(&self, cx: &mut JSContext, mode: u32, count: i32, type_: u32, offset: i64) {
2064        self.validate_uniform_block_for_draw();
2065        self.validate_vertex_attribs_for_draw(cx);
2066        self.base.DrawElements(cx, mode, count, type_, offset)
2067    }
2068
2069    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2070    fn EnableVertexAttribArray(&self, cx: &mut JSContext, attrib_id: u32) {
2071        self.base.EnableVertexAttribArray(cx, attrib_id)
2072    }
2073
2074    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2075    fn DisableVertexAttribArray(&self, cx: &mut JSContext, attrib_id: u32) {
2076        self.base.DisableVertexAttribArray(cx, attrib_id)
2077    }
2078
2079    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2080    fn GetActiveUniform(
2081        &self,
2082        cx: &mut JSContext,
2083        program: &WebGLProgram,
2084        index: u32,
2085    ) -> Option<DomRoot<WebGLActiveInfo>> {
2086        self.base.GetActiveUniform(cx, program, index)
2087    }
2088
2089    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2090    fn GetActiveAttrib(
2091        &self,
2092        cx: &mut JSContext,
2093        program: &WebGLProgram,
2094        index: u32,
2095    ) -> Option<DomRoot<WebGLActiveInfo>> {
2096        self.base.GetActiveAttrib(cx, program, index)
2097    }
2098
2099    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2100    fn GetAttribLocation(&self, program: &WebGLProgram, name: DOMString) -> i32 {
2101        self.base.GetAttribLocation(program, name)
2102    }
2103
2104    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.7>
2105    fn GetFragDataLocation(&self, program: &WebGLProgram, name: DOMString) -> i32 {
2106        if let Err(error) = self.base.validate_ownership(program) {
2107            self.base.webgl_error(error);
2108            return -1;
2109        }
2110        match program.get_frag_data_location(name) {
2111            Ok(location) => location,
2112            Err(error) => {
2113                self.base.webgl_error(error);
2114                -1
2115            },
2116        }
2117    }
2118
2119    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2120    fn GetProgramInfoLog(&self, program: &WebGLProgram) -> Option<DOMString> {
2121        self.base.GetProgramInfoLog(program)
2122    }
2123
2124    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2125    fn GetProgramParameter(
2126        &self,
2127        cx: &mut JSContext,
2128        program: &WebGLProgram,
2129        param_id: u32,
2130        mut retval: MutableHandleValue,
2131    ) {
2132        if let Err(error) = self.base.validate_ownership(program) {
2133            self.base.webgl_error(error);
2134            return retval.set(NullValue());
2135        }
2136        if program.is_deleted() {
2137            self.base.webgl_error(InvalidOperation);
2138            return retval.set(NullValue());
2139        }
2140        match param_id {
2141            constants::TRANSFORM_FEEDBACK_VARYINGS => {
2142                retval.set(Int32Value(program.transform_feedback_varyings_length()))
2143            },
2144            constants::TRANSFORM_FEEDBACK_BUFFER_MODE => {
2145                retval.set(Int32Value(program.transform_feedback_buffer_mode()))
2146            },
2147            constants::ACTIVE_UNIFORM_BLOCKS => {
2148                retval.set(Int32Value(program.active_uniform_blocks().len() as i32))
2149            },
2150            _ => self.base.GetProgramParameter(cx, program, param_id, retval),
2151        }
2152    }
2153
2154    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2155    fn GetShaderInfoLog(&self, shader: &WebGLShader) -> Option<DOMString> {
2156        self.base.GetShaderInfoLog(shader)
2157    }
2158
2159    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2160    fn GetShaderParameter(
2161        &self,
2162        cx: &mut JSContext,
2163        shader: &WebGLShader,
2164        param_id: u32,
2165        retval: MutableHandleValue,
2166    ) {
2167        self.base.GetShaderParameter(cx, shader, param_id, retval)
2168    }
2169
2170    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2171    fn GetShaderPrecisionFormat(
2172        &self,
2173        cx: &mut JSContext,
2174        shader_type: u32,
2175        precision_type: u32,
2176    ) -> Option<DomRoot<WebGLShaderPrecisionFormat>> {
2177        self.base
2178            .GetShaderPrecisionFormat(cx, shader_type, precision_type)
2179    }
2180
2181    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.2>
2182    fn GetIndexedParameter(
2183        &self,
2184        cx: &mut JSContext,
2185        target: u32,
2186        index: u32,
2187        mut retval: MutableHandleValue,
2188    ) {
2189        let bindings = match target {
2190            constants::TRANSFORM_FEEDBACK_BUFFER_BINDING |
2191            constants::TRANSFORM_FEEDBACK_BUFFER_SIZE |
2192            constants::TRANSFORM_FEEDBACK_BUFFER_START => {
2193                &self.indexed_transform_feedback_buffer_bindings
2194            },
2195            constants::UNIFORM_BUFFER_BINDING |
2196            constants::UNIFORM_BUFFER_SIZE |
2197            constants::UNIFORM_BUFFER_START => &self.indexed_uniform_buffer_bindings,
2198            _ => {
2199                self.base.webgl_error(InvalidEnum);
2200                return retval.set(NullValue());
2201            },
2202        };
2203
2204        let binding = match bindings.get(index as usize) {
2205            Some(binding) => binding,
2206            None => {
2207                self.base.webgl_error(InvalidValue);
2208                return retval.set(NullValue());
2209            },
2210        };
2211
2212        match target {
2213            constants::TRANSFORM_FEEDBACK_BUFFER_BINDING | constants::UNIFORM_BUFFER_BINDING => {
2214                binding.buffer.get().to_jsval(cx, retval)
2215            },
2216            constants::TRANSFORM_FEEDBACK_BUFFER_START | constants::UNIFORM_BUFFER_START => {
2217                retval.set(Int32Value(binding.start.get() as _))
2218            },
2219            constants::TRANSFORM_FEEDBACK_BUFFER_SIZE | constants::UNIFORM_BUFFER_SIZE => {
2220                retval.set(Int32Value(binding.size.get() as _))
2221            },
2222            _ => unreachable!(),
2223        }
2224    }
2225
2226    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2227    fn GetUniformLocation(
2228        &self,
2229        cx: &mut JSContext,
2230        program: &WebGLProgram,
2231        name: DOMString,
2232    ) -> Option<DomRoot<WebGLUniformLocation>> {
2233        self.base.GetUniformLocation(cx, program, name)
2234    }
2235
2236    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2237    fn GetVertexAttrib(
2238        &self,
2239        cx: &mut JSContext,
2240        index: u32,
2241        pname: u32,
2242        retval: MutableHandleValue,
2243    ) {
2244        self.base.GetVertexAttrib(cx, index, pname, retval)
2245    }
2246
2247    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2248    fn GetVertexAttribOffset(&self, cx: &mut JSContext, index: u32, pname: u32) -> i64 {
2249        self.base.GetVertexAttribOffset(cx, index, pname)
2250    }
2251
2252    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2253    fn Hint(&self, target: u32, mode: u32) {
2254        self.base.Hint(target, mode)
2255    }
2256
2257    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
2258    fn IsBuffer(&self, buffer: Option<&WebGLBuffer>) -> bool {
2259        self.base.IsBuffer(buffer)
2260    }
2261
2262    // TODO: We could write this without IPC, recording the calls to `enable` and `disable`.
2263    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.2>
2264    fn IsEnabled(&self, cap: u32) -> bool {
2265        match cap {
2266            constants::RASTERIZER_DISCARD => self.enable_rasterizer_discard.get(),
2267            _ => self.base.IsEnabled(cap),
2268        }
2269    }
2270
2271    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
2272    fn IsFramebuffer(&self, frame_buffer: Option<&WebGLFramebuffer>) -> bool {
2273        self.base.IsFramebuffer(frame_buffer)
2274    }
2275
2276    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2277    fn IsProgram(&self, program: Option<&WebGLProgram>) -> bool {
2278        self.base.IsProgram(program)
2279    }
2280
2281    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
2282    fn IsRenderbuffer(&self, render_buffer: Option<&WebGLRenderbuffer>) -> bool {
2283        self.base.IsRenderbuffer(render_buffer)
2284    }
2285
2286    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2287    fn IsShader(&self, shader: Option<&WebGLShader>) -> bool {
2288        self.base.IsShader(shader)
2289    }
2290
2291    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
2292    fn IsTexture(&self, texture: Option<&WebGLTexture>) -> bool {
2293        self.base.IsTexture(texture)
2294    }
2295
2296    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.17>
2297    fn IsVertexArray(&self, vertex_array: Option<&WebGLVertexArrayObject>) -> bool {
2298        self.base.is_vertex_array_webgl2(vertex_array)
2299    }
2300
2301    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2302    fn LineWidth(&self, width: f32) {
2303        self.base.LineWidth(width)
2304    }
2305
2306    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.2>
2307    fn PixelStorei(&self, param_name: u32, param_value: i32) {
2308        if param_value < 0 {
2309            return self.base.webgl_error(InvalidValue);
2310        }
2311
2312        match param_name {
2313            constants::PACK_ROW_LENGTH => self.texture_pack_row_length.set(param_value as _),
2314            constants::PACK_SKIP_PIXELS => self.texture_pack_skip_pixels.set(param_value as _),
2315            constants::PACK_SKIP_ROWS => self.texture_pack_skip_rows.set(param_value as _),
2316            constants::UNPACK_ROW_LENGTH |
2317            constants::UNPACK_IMAGE_HEIGHT |
2318            constants::UNPACK_SKIP_PIXELS |
2319            constants::UNPACK_SKIP_ROWS |
2320            constants::UNPACK_SKIP_IMAGES => {
2321                let mut layout = self.base.texture_unpack_layout();
2322                let value = param_value as u32;
2323                match param_name {
2324                    constants::UNPACK_ROW_LENGTH => layout.row_length = value,
2325                    constants::UNPACK_IMAGE_HEIGHT => layout.image_height = value,
2326                    constants::UNPACK_SKIP_PIXELS => layout.skip_pixels = value,
2327                    constants::UNPACK_SKIP_ROWS => layout.skip_rows = value,
2328                    _ => layout.skip_images = value,
2329                }
2330                self.base.set_texture_unpack_layout(layout);
2331            },
2332            _ => self.base.PixelStorei(param_name, param_value),
2333        }
2334    }
2335
2336    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2337    fn PolygonOffset(&self, factor: f32, units: f32) {
2338        self.base.PolygonOffset(factor, units)
2339    }
2340
2341    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.12>
2342    fn ReadPixels(
2343        &self,
2344        no_gc: &NoGC,
2345        x: i32,
2346        y: i32,
2347        width: i32,
2348        height: i32,
2349        format: u32,
2350        pixel_type: u32,
2351        mut pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>,
2352    ) {
2353        let Some(pixels) = pixels.as_mut() else {
2354            return self.base.webgl_error(InvalidValue);
2355        };
2356
2357        self.read_pixels_into(no_gc, x, y, width, height, format, pixel_type, pixels, 0)
2358    }
2359
2360    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.10>
2361    fn ReadPixels_(
2362        &self,
2363        _no_gc: &NoGC,
2364        x: i32,
2365        y: i32,
2366        width: i32,
2367        height: i32,
2368        format: u32,
2369        pixel_type: u32,
2370        dst_byte_offset: i64,
2371    ) {
2372        if let Err(error) = self.base.validate_read_framebuffer() {
2373            return self.base.webgl_error(error);
2374        }
2375
2376        let dst = match self.bound_pixel_pack_buffer.get() {
2377            Some(buffer) => buffer,
2378            None => return self.base.webgl_error(InvalidOperation),
2379        };
2380        let accepted = match self.accepted_read_pixels_format_types() {
2381            Ok(accepted) => accepted,
2382            Err(error) => return self.base.webgl_error(error),
2383        };
2384
2385        if dst_byte_offset < 0 {
2386            return self.base.webgl_error(InvalidValue);
2387        }
2388        let dst_byte_offset = dst_byte_offset as usize;
2389        if dst_byte_offset > dst.capacity() {
2390            return self.base.webgl_error(InvalidOperation);
2391        }
2392
2393        let ReadPixelsAllowedFormats {
2394            array_types,
2395            elements_per_pixel,
2396        } = match self.calc_read_pixel_formats(pixel_type, format) {
2397            Ok(result) => result,
2398            Err(error) => return self.base.webgl_error(error),
2399        };
2400        let bytes_per_pixel = array_types[0]
2401            .byte_size()
2402            .expect("readPixels pixel types map to scalar array types") *
2403            elements_per_pixel;
2404        if !accepted.contains(&(format, pixel_type)) {
2405            return self.base.webgl_error(InvalidOperation);
2406        }
2407
2408        let ReadPixelsSizes {
2409            row_stride: _,
2410            skipped_bytes,
2411            size,
2412        } = match self.calc_read_pixel_sizes(width, height, bytes_per_pixel) {
2413            Ok(result) => result,
2414            Err(error) => return self.base.webgl_error(error),
2415        };
2416        let dst_end = dst_byte_offset + skipped_bytes + size;
2417        if dst.capacity() < dst_end {
2418            return self.base.webgl_error(InvalidOperation);
2419        }
2420
2421        {
2422            let Some((fb_width, fb_height)) = self.base.get_current_framebuffer_size() else {
2423                return self.base.webgl_error(InvalidOperation);
2424            };
2425            let src_origin = Point2D::new(x, y);
2426            let src_size = Size2D::new(width as u32, height as u32);
2427            let fb_size = Size2D::new(fb_width as u32, fb_height as u32);
2428            if pixels::clip(src_origin, src_size.to_u32(), fb_size.to_u32()).is_none() {
2429                return;
2430            }
2431        }
2432        let src_rect = Rect::new(Point2D::new(x, y), Size2D::new(width, height));
2433
2434        self.base.send_command(WebGLCommand::PixelStorei(
2435            constants::PACK_ALIGNMENT,
2436            self.base.get_texture_packing_alignment() as _,
2437        ));
2438        self.base.send_command(WebGLCommand::PixelStorei(
2439            constants::PACK_ROW_LENGTH,
2440            self.texture_pack_row_length.get() as _,
2441        ));
2442        self.base.send_command(WebGLCommand::PixelStorei(
2443            constants::PACK_SKIP_ROWS,
2444            self.texture_pack_skip_rows.get() as _,
2445        ));
2446        self.base.send_command(WebGLCommand::PixelStorei(
2447            constants::PACK_SKIP_PIXELS,
2448            self.texture_pack_skip_pixels.get() as _,
2449        ));
2450        self.base.send_command(WebGLCommand::ReadPixelsPP(
2451            src_rect,
2452            format,
2453            pixel_type,
2454            dst_byte_offset,
2455        ));
2456    }
2457
2458    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.10>
2459    fn ReadPixels__(
2460        &self,
2461        no_gc: &NoGC,
2462        x: i32,
2463        y: i32,
2464        width: i32,
2465        height: i32,
2466        format: u32,
2467        pixel_type: u32,
2468        mut dst: CustomAutoRooterGuard<ArrayBufferView>,
2469        dst_elem_offset: u32,
2470    ) {
2471        self.read_pixels_into(
2472            no_gc,
2473            x,
2474            y,
2475            width,
2476            height,
2477            format,
2478            pixel_type,
2479            &mut dst,
2480            dst_elem_offset,
2481        )
2482    }
2483
2484    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2485    fn SampleCoverage(&self, value: f32, invert: bool) {
2486        self.base.SampleCoverage(value, invert)
2487    }
2488
2489    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4>
2490    fn Scissor(&self, x: i32, y: i32, width: i32, height: i32) {
2491        self.base.Scissor(x, y, width, height)
2492    }
2493
2494    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2495    fn StencilFunc(&self, func: u32, ref_: i32, mask: u32) {
2496        self.base.StencilFunc(func, ref_, mask)
2497    }
2498
2499    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2500    fn StencilFuncSeparate(&self, face: u32, func: u32, ref_: i32, mask: u32) {
2501        self.base.StencilFuncSeparate(face, func, ref_, mask)
2502    }
2503
2504    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2505    fn StencilMask(&self, mask: u32) {
2506        self.base.StencilMask(mask)
2507    }
2508
2509    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2510    fn StencilMaskSeparate(&self, face: u32, mask: u32) {
2511        self.base.StencilMaskSeparate(face, mask)
2512    }
2513
2514    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2515    fn StencilOp(&self, fail: u32, zfail: u32, zpass: u32) {
2516        self.base.StencilOp(fail, zfail, zpass)
2517    }
2518
2519    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2520    fn StencilOpSeparate(&self, face: u32, fail: u32, zfail: u32, zpass: u32) {
2521        self.base.StencilOpSeparate(face, fail, zfail, zpass)
2522    }
2523
2524    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2525    fn LinkProgram(&self, program: &WebGLProgram) {
2526        self.base.LinkProgram(program)
2527    }
2528
2529    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2530    fn ShaderSource(&self, shader: &WebGLShader, source: DOMString) {
2531        self.base.ShaderSource(shader, source)
2532    }
2533
2534    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2535    fn GetShaderSource(&self, shader: &WebGLShader) -> Option<DOMString> {
2536        self.base.GetShaderSource(shader)
2537    }
2538
2539    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2540    fn Uniform1f(&self, location: Option<&WebGLUniformLocation>, val: f32) {
2541        self.base.Uniform1f(location, val)
2542    }
2543
2544    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2545    fn Uniform1i(&self, location: Option<&WebGLUniformLocation>, val: i32) {
2546        self.base.Uniform1i(location, val)
2547    }
2548
2549    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2550    fn Uniform1iv(
2551        &self,
2552        location: Option<&WebGLUniformLocation>,
2553        v: Int32ArrayOrLongSequence,
2554        src_offset: u32,
2555        src_length: u32,
2556    ) {
2557        self.base.uniform1iv(location, v, src_offset, src_length)
2558    }
2559
2560    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2561    fn Uniform1ui(&self, location: Option<&WebGLUniformLocation>, val: u32) {
2562        self.base.with_location(location, |location| {
2563            match location.type_() {
2564                constants::BOOL | constants::UNSIGNED_INT => (),
2565                _ => return Err(InvalidOperation),
2566            }
2567            self.base
2568                .send_command(WebGLCommand::Uniform1ui(location.id(), val));
2569            Ok(())
2570        });
2571    }
2572
2573    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2574    fn Uniform1uiv(
2575        &self,
2576        location: Option<&WebGLUniformLocation>,
2577        val: Uint32ArrayOrUnsignedLongSequence,
2578        src_offset: u32,
2579        src_length: u32,
2580    ) {
2581        self.base.with_location(location, |location| {
2582            match location.type_() {
2583                constants::BOOL |
2584                constants::UNSIGNED_INT |
2585                constants::SAMPLER_2D |
2586                constants::SAMPLER_2D_ARRAY |
2587                constants::SAMPLER_3D |
2588                constants::SAMPLER_CUBE => {},
2589                _ => return Err(InvalidOperation),
2590            }
2591
2592            let val = self.uniform_vec_section_uint(val, src_offset, src_length, 1, location)?;
2593
2594            match location.type_() {
2595                constants::SAMPLER_2D | constants::SAMPLER_CUBE => {
2596                    for &v in val
2597                        .iter()
2598                        .take(cmp::min(location.size().unwrap_or(1) as usize, val.len()))
2599                    {
2600                        if v >= self.base.limits().max_combined_texture_image_units {
2601                            return Err(InvalidValue);
2602                        }
2603                    }
2604                },
2605                _ => {},
2606            }
2607            self.base
2608                .send_command(WebGLCommand::Uniform1uiv(location.id(), val));
2609            Ok(())
2610        });
2611    }
2612
2613    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2614    fn Uniform1fv(
2615        &self,
2616        location: Option<&WebGLUniformLocation>,
2617        v: Float32ArrayOrUnrestrictedFloatSequence,
2618        src_offset: u32,
2619        src_length: u32,
2620    ) {
2621        self.base.uniform1fv(location, v, src_offset, src_length);
2622    }
2623
2624    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2625    fn Uniform2f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32) {
2626        self.base.Uniform2f(location, x, y)
2627    }
2628
2629    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2630    fn Uniform2fv(
2631        &self,
2632        location: Option<&WebGLUniformLocation>,
2633        v: Float32ArrayOrUnrestrictedFloatSequence,
2634        src_offset: u32,
2635        src_length: u32,
2636    ) {
2637        self.base.uniform2fv(location, v, src_offset, src_length);
2638    }
2639
2640    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2641    fn Uniform2i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32) {
2642        self.base.Uniform2i(location, x, y)
2643    }
2644
2645    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2646    fn Uniform2iv(
2647        &self,
2648        location: Option<&WebGLUniformLocation>,
2649        v: Int32ArrayOrLongSequence,
2650        src_offset: u32,
2651        src_length: u32,
2652    ) {
2653        self.base.uniform2iv(location, v, src_offset, src_length)
2654    }
2655
2656    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2657    fn Uniform2ui(&self, location: Option<&WebGLUniformLocation>, x: u32, y: u32) {
2658        self.base.with_location(location, |location| {
2659            match location.type_() {
2660                constants::BOOL_VEC2 | constants::UNSIGNED_INT_VEC2 => {},
2661                _ => return Err(InvalidOperation),
2662            }
2663            self.base
2664                .send_command(WebGLCommand::Uniform2ui(location.id(), x, y));
2665            Ok(())
2666        });
2667    }
2668
2669    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2670    fn Uniform2uiv(
2671        &self,
2672        location: Option<&WebGLUniformLocation>,
2673        val: Uint32ArrayOrUnsignedLongSequence,
2674        src_offset: u32,
2675        src_length: u32,
2676    ) {
2677        self.base.with_location(location, |location| {
2678            match location.type_() {
2679                constants::BOOL_VEC2 | constants::UNSIGNED_INT_VEC2 => {},
2680                _ => return Err(InvalidOperation),
2681            }
2682            let val = self.uniform_vec_section_uint(val, src_offset, src_length, 2, location)?;
2683            self.base
2684                .send_command(WebGLCommand::Uniform2uiv(location.id(), val));
2685            Ok(())
2686        });
2687    }
2688
2689    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2690    fn Uniform3f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32) {
2691        self.base.Uniform3f(location, x, y, z)
2692    }
2693
2694    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2695    fn Uniform3fv(
2696        &self,
2697        location: Option<&WebGLUniformLocation>,
2698        v: Float32ArrayOrUnrestrictedFloatSequence,
2699        src_offset: u32,
2700        src_length: u32,
2701    ) {
2702        self.base.uniform3fv(location, v, src_offset, src_length);
2703    }
2704
2705    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2706    fn Uniform3i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32) {
2707        self.base.Uniform3i(location, x, y, z)
2708    }
2709
2710    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2711    fn Uniform3iv(
2712        &self,
2713        location: Option<&WebGLUniformLocation>,
2714        v: Int32ArrayOrLongSequence,
2715        src_offset: u32,
2716        src_length: u32,
2717    ) {
2718        self.base.uniform3iv(location, v, src_offset, src_length)
2719    }
2720
2721    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2722    fn Uniform3ui(&self, location: Option<&WebGLUniformLocation>, x: u32, y: u32, z: u32) {
2723        self.base.with_location(location, |location| {
2724            match location.type_() {
2725                constants::BOOL_VEC3 | constants::UNSIGNED_INT_VEC3 => {},
2726                _ => return Err(InvalidOperation),
2727            }
2728            self.base
2729                .send_command(WebGLCommand::Uniform3ui(location.id(), x, y, z));
2730            Ok(())
2731        });
2732    }
2733
2734    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2735    fn Uniform3uiv(
2736        &self,
2737        location: Option<&WebGLUniformLocation>,
2738        val: Uint32ArrayOrUnsignedLongSequence,
2739        src_offset: u32,
2740        src_length: u32,
2741    ) {
2742        self.base.with_location(location, |location| {
2743            match location.type_() {
2744                constants::BOOL_VEC3 | constants::UNSIGNED_INT_VEC3 => {},
2745                _ => return Err(InvalidOperation),
2746            }
2747            let val = self.uniform_vec_section_uint(val, src_offset, src_length, 3, location)?;
2748            self.base
2749                .send_command(WebGLCommand::Uniform3uiv(location.id(), val));
2750            Ok(())
2751        });
2752    }
2753
2754    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2755    fn Uniform4i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32, w: i32) {
2756        self.base.Uniform4i(location, x, y, z, w)
2757    }
2758
2759    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2760    fn Uniform4iv(
2761        &self,
2762        location: Option<&WebGLUniformLocation>,
2763        v: Int32ArrayOrLongSequence,
2764        src_offset: u32,
2765        src_length: u32,
2766    ) {
2767        self.base.uniform4iv(location, v, src_offset, src_length)
2768    }
2769
2770    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2771    fn Uniform4ui(&self, location: Option<&WebGLUniformLocation>, x: u32, y: u32, z: u32, w: u32) {
2772        self.base.with_location(location, |location| {
2773            match location.type_() {
2774                constants::BOOL_VEC4 | constants::UNSIGNED_INT_VEC4 => {},
2775                _ => return Err(InvalidOperation),
2776            }
2777            self.base
2778                .send_command(WebGLCommand::Uniform4ui(location.id(), x, y, z, w));
2779            Ok(())
2780        });
2781    }
2782
2783    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2784    fn Uniform4uiv(
2785        &self,
2786        location: Option<&WebGLUniformLocation>,
2787        val: Uint32ArrayOrUnsignedLongSequence,
2788        src_offset: u32,
2789        src_length: u32,
2790    ) {
2791        self.base.with_location(location, |location| {
2792            match location.type_() {
2793                constants::BOOL_VEC4 | constants::UNSIGNED_INT_VEC4 => {},
2794                _ => return Err(InvalidOperation),
2795            }
2796            let val = self.uniform_vec_section_uint(val, src_offset, src_length, 4, location)?;
2797            self.base
2798                .send_command(WebGLCommand::Uniform4uiv(location.id(), val));
2799            Ok(())
2800        });
2801    }
2802
2803    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2804    fn Uniform4f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32, w: f32) {
2805        self.base.Uniform4f(location, x, y, z, w)
2806    }
2807
2808    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2809    fn Uniform4fv(
2810        &self,
2811        location: Option<&WebGLUniformLocation>,
2812        v: Float32ArrayOrUnrestrictedFloatSequence,
2813        src_offset: u32,
2814        src_length: u32,
2815    ) {
2816        self.base.uniform4fv(location, v, src_offset, src_length);
2817    }
2818
2819    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2820    fn UniformMatrix2fv(
2821        &self,
2822        location: Option<&WebGLUniformLocation>,
2823        transpose: bool,
2824        v: Float32ArrayOrUnrestrictedFloatSequence,
2825        src_offset: u32,
2826        src_length: u32,
2827    ) {
2828        self.base
2829            .uniform_matrix_2fv(location, transpose, v, src_offset, src_length)
2830    }
2831
2832    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2833    fn UniformMatrix3fv(
2834        &self,
2835        location: Option<&WebGLUniformLocation>,
2836        transpose: bool,
2837        v: Float32ArrayOrUnrestrictedFloatSequence,
2838        src_offset: u32,
2839        src_length: u32,
2840    ) {
2841        self.base
2842            .uniform_matrix_3fv(location, transpose, v, src_offset, src_length)
2843    }
2844
2845    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
2846    fn UniformMatrix4fv(
2847        &self,
2848        location: Option<&WebGLUniformLocation>,
2849        transpose: bool,
2850        v: Float32ArrayOrUnrestrictedFloatSequence,
2851        src_offset: u32,
2852        src_length: u32,
2853    ) {
2854        self.base
2855            .uniform_matrix_4fv(location, transpose, v, src_offset, src_length)
2856    }
2857
2858    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2859    fn UniformMatrix3x2fv(
2860        &self,
2861        location: Option<&WebGLUniformLocation>,
2862        transpose: bool,
2863        val: Float32ArrayOrUnrestrictedFloatSequence,
2864        src_offset: u32,
2865        src_length: u32,
2866    ) {
2867        self.base.with_location(location, |location| {
2868            match location.type_() {
2869                constants::FLOAT_MAT3x2 => {},
2870                _ => return Err(InvalidOperation),
2871            }
2872            let val = self.base.uniform_matrix_section(
2873                val,
2874                src_offset,
2875                src_length,
2876                transpose,
2877                3 * 2,
2878                location,
2879            )?;
2880            self.base
2881                .send_command(WebGLCommand::UniformMatrix3x2fv(location.id(), val));
2882            Ok(())
2883        });
2884    }
2885
2886    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2887    fn UniformMatrix4x2fv(
2888        &self,
2889        location: Option<&WebGLUniformLocation>,
2890        transpose: bool,
2891        val: Float32ArrayOrUnrestrictedFloatSequence,
2892        src_offset: u32,
2893        src_length: u32,
2894    ) {
2895        self.base.with_location(location, |location| {
2896            match location.type_() {
2897                constants::FLOAT_MAT4x2 => {},
2898                _ => return Err(InvalidOperation),
2899            }
2900            let val = self.base.uniform_matrix_section(
2901                val,
2902                src_offset,
2903                src_length,
2904                transpose,
2905                4 * 2,
2906                location,
2907            )?;
2908            self.base
2909                .send_command(WebGLCommand::UniformMatrix4x2fv(location.id(), val));
2910            Ok(())
2911        });
2912    }
2913
2914    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2915    fn UniformMatrix2x3fv(
2916        &self,
2917        location: Option<&WebGLUniformLocation>,
2918        transpose: bool,
2919        val: Float32ArrayOrUnrestrictedFloatSequence,
2920        src_offset: u32,
2921        src_length: u32,
2922    ) {
2923        self.base.with_location(location, |location| {
2924            match location.type_() {
2925                constants::FLOAT_MAT2x3 => {},
2926                _ => return Err(InvalidOperation),
2927            }
2928            let val = self.base.uniform_matrix_section(
2929                val,
2930                src_offset,
2931                src_length,
2932                transpose,
2933                2 * 3,
2934                location,
2935            )?;
2936            self.base
2937                .send_command(WebGLCommand::UniformMatrix2x3fv(location.id(), val));
2938            Ok(())
2939        });
2940    }
2941
2942    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2943    fn UniformMatrix4x3fv(
2944        &self,
2945        location: Option<&WebGLUniformLocation>,
2946        transpose: bool,
2947        val: Float32ArrayOrUnrestrictedFloatSequence,
2948        src_offset: u32,
2949        src_length: u32,
2950    ) {
2951        self.base.with_location(location, |location| {
2952            match location.type_() {
2953                constants::FLOAT_MAT4x3 => {},
2954                _ => return Err(InvalidOperation),
2955            }
2956            let val = self.base.uniform_matrix_section(
2957                val,
2958                src_offset,
2959                src_length,
2960                transpose,
2961                4 * 3,
2962                location,
2963            )?;
2964            self.base
2965                .send_command(WebGLCommand::UniformMatrix4x3fv(location.id(), val));
2966            Ok(())
2967        });
2968    }
2969
2970    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2971    fn UniformMatrix2x4fv(
2972        &self,
2973        location: Option<&WebGLUniformLocation>,
2974        transpose: bool,
2975        val: Float32ArrayOrUnrestrictedFloatSequence,
2976        src_offset: u32,
2977        src_length: u32,
2978    ) {
2979        self.base.with_location(location, |location| {
2980            match location.type_() {
2981                constants::FLOAT_MAT2x4 => {},
2982                _ => return Err(InvalidOperation),
2983            }
2984            let val = self.base.uniform_matrix_section(
2985                val,
2986                src_offset,
2987                src_length,
2988                transpose,
2989                2 * 4,
2990                location,
2991            )?;
2992            self.base
2993                .send_command(WebGLCommand::UniformMatrix2x4fv(location.id(), val));
2994            Ok(())
2995        });
2996    }
2997
2998    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
2999    fn UniformMatrix3x4fv(
3000        &self,
3001        location: Option<&WebGLUniformLocation>,
3002        transpose: bool,
3003        val: Float32ArrayOrUnrestrictedFloatSequence,
3004        src_offset: u32,
3005        src_length: u32,
3006    ) {
3007        self.base.with_location(location, |location| {
3008            match location.type_() {
3009                constants::FLOAT_MAT3x4 => {},
3010                _ => return Err(InvalidOperation),
3011            }
3012            let val = self.base.uniform_matrix_section(
3013                val,
3014                src_offset,
3015                src_length,
3016                transpose,
3017                3 * 4,
3018                location,
3019            )?;
3020            self.base
3021                .send_command(WebGLCommand::UniformMatrix3x4fv(location.id(), val));
3022            Ok(())
3023        });
3024    }
3025
3026    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
3027    fn GetUniform(
3028        &self,
3029        cx: &mut JSContext,
3030        program: &WebGLProgram,
3031        location: &WebGLUniformLocation,
3032        mut retval: MutableHandleValue,
3033    ) {
3034        if let Err(error) = self.base.uniform_check_program(program, location) {
3035            self.base.webgl_error(error);
3036            return retval.set(NullValue());
3037        }
3038
3039        let triple = (&*self.base, program.id(), location.id());
3040
3041        match location.type_() {
3042            constants::UNSIGNED_INT => retval.set(UInt32Value(uniform_get(
3043                triple,
3044                WebGLCommand::GetUniformUint,
3045            ))),
3046            constants::UNSIGNED_INT_VEC2 => uniform_typed::<Uint32>(
3047                cx,
3048                &uniform_get(triple, WebGLCommand::GetUniformUint2),
3049                retval,
3050            ),
3051            constants::UNSIGNED_INT_VEC3 => uniform_typed::<Uint32>(
3052                cx,
3053                &uniform_get(triple, WebGLCommand::GetUniformUint3),
3054                retval,
3055            ),
3056            constants::UNSIGNED_INT_VEC4 => uniform_typed::<Uint32>(
3057                cx,
3058                &uniform_get(triple, WebGLCommand::GetUniformUint4),
3059                retval,
3060            ),
3061            constants::FLOAT_MAT2x3 => uniform_typed::<Float32>(
3062                cx,
3063                &uniform_get(triple, WebGLCommand::GetUniformFloat2x3),
3064                retval,
3065            ),
3066            constants::FLOAT_MAT2x4 => uniform_typed::<Float32>(
3067                cx,
3068                &uniform_get(triple, WebGLCommand::GetUniformFloat2x4),
3069                retval,
3070            ),
3071            constants::FLOAT_MAT3x2 => uniform_typed::<Float32>(
3072                cx,
3073                &uniform_get(triple, WebGLCommand::GetUniformFloat3x2),
3074                retval,
3075            ),
3076            constants::FLOAT_MAT3x4 => uniform_typed::<Float32>(
3077                cx,
3078                &uniform_get(triple, WebGLCommand::GetUniformFloat3x4),
3079                retval,
3080            ),
3081            constants::FLOAT_MAT4x2 => uniform_typed::<Float32>(
3082                cx,
3083                &uniform_get(triple, WebGLCommand::GetUniformFloat4x2),
3084                retval,
3085            ),
3086            constants::FLOAT_MAT4x3 => uniform_typed::<Float32>(
3087                cx,
3088                &uniform_get(triple, WebGLCommand::GetUniformFloat4x3),
3089                retval,
3090            ),
3091            constants::SAMPLER_3D | constants::SAMPLER_2D_ARRAY => {
3092                retval.set(Int32Value(uniform_get(triple, WebGLCommand::GetUniformInt)))
3093            },
3094            _ => self.base.GetUniform(cx, program, location, retval),
3095        }
3096    }
3097
3098    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3099    fn UseProgram(&self, program: Option<&WebGLProgram>) {
3100        self.base.UseProgram(program)
3101    }
3102
3103    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3104    fn ValidateProgram(&self, program: &WebGLProgram) {
3105        self.base.ValidateProgram(program)
3106    }
3107
3108    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3109    fn VertexAttrib1f(&self, cx: &mut JSContext, indx: u32, x: f32) {
3110        self.base.VertexAttrib1f(cx, indx, x)
3111    }
3112
3113    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3114    fn VertexAttrib1fv(
3115        &self,
3116        cx: &mut JSContext,
3117        indx: u32,
3118        v: Float32ArrayOrUnrestrictedFloatSequence,
3119    ) {
3120        self.base.VertexAttrib1fv(cx, indx, v)
3121    }
3122
3123    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3124    fn VertexAttrib2f(&self, cx: &mut JSContext, indx: u32, x: f32, y: f32) {
3125        self.base.VertexAttrib2f(cx, indx, x, y)
3126    }
3127
3128    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3129    fn VertexAttrib2fv(
3130        &self,
3131        cx: &mut JSContext,
3132        indx: u32,
3133        v: Float32ArrayOrUnrestrictedFloatSequence,
3134    ) {
3135        self.base.VertexAttrib2fv(cx, indx, v)
3136    }
3137
3138    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3139    fn VertexAttrib3f(&self, cx: &mut JSContext, indx: u32, x: f32, y: f32, z: f32) {
3140        self.base.VertexAttrib3f(cx, indx, x, y, z)
3141    }
3142
3143    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3144    fn VertexAttrib3fv(
3145        &self,
3146        cx: &mut JSContext,
3147        indx: u32,
3148        v: Float32ArrayOrUnrestrictedFloatSequence,
3149    ) {
3150        self.base.VertexAttrib3fv(cx, indx, v)
3151    }
3152
3153    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3154    fn VertexAttrib4f(&self, cx: &mut JSContext, indx: u32, x: f32, y: f32, z: f32, w: f32) {
3155        self.base.VertexAttrib4f(cx, indx, x, y, z, w)
3156    }
3157
3158    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3159    fn VertexAttrib4fv(
3160        &self,
3161        cx: &mut JSContext,
3162        indx: u32,
3163        v: Float32ArrayOrUnrestrictedFloatSequence,
3164    ) {
3165        self.base.VertexAttrib4fv(cx, indx, v)
3166    }
3167
3168    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
3169    fn VertexAttribI4i(&self, _cx: &mut JSContext, index: u32, x: i32, y: i32, z: i32, w: i32) {
3170        self.vertex_attrib_i(index, x, y, z, w)
3171    }
3172
3173    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
3174    fn VertexAttribI4iv(&self, _cx: &mut JSContext, index: u32, v: Int32ArrayOrLongSequence) {
3175        let values = match v {
3176            Int32ArrayOrLongSequence::Int32Array(v) => v.to_vec().unwrap_or_default(),
3177            Int32ArrayOrLongSequence::LongSequence(v) => v,
3178        };
3179        if values.len() < 4 {
3180            return self.base.webgl_error(InvalidValue);
3181        }
3182        self.vertex_attrib_i(index, values[0], values[1], values[2], values[3]);
3183    }
3184
3185    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
3186    fn VertexAttribI4ui(&self, _cx: &mut JSContext, index: u32, x: u32, y: u32, z: u32, w: u32) {
3187        self.vertex_attrib_u(index, x, y, z, w)
3188    }
3189
3190    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
3191    fn VertexAttribI4uiv(
3192        &self,
3193        _cx: &mut JSContext,
3194        index: u32,
3195        v: Uint32ArrayOrUnsignedLongSequence,
3196    ) {
3197        let values = match v {
3198            Uint32ArrayOrUnsignedLongSequence::Uint32Array(v) => v.to_vec().unwrap_or_default(),
3199            Uint32ArrayOrUnsignedLongSequence::UnsignedLongSequence(v) => v,
3200        };
3201        if values.len() < 4 {
3202            return self.base.webgl_error(InvalidValue);
3203        }
3204        self.vertex_attrib_u(index, values[0], values[1], values[2], values[3]);
3205    }
3206
3207    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3208    fn VertexAttribPointer(
3209        &self,
3210        cx: &mut JSContext,
3211        attrib_id: u32,
3212        size: i32,
3213        data_type: u32,
3214        normalized: bool,
3215        stride: i32,
3216        offset: i64,
3217    ) {
3218        self.base
3219            .VertexAttribPointer(cx, attrib_id, size, data_type, normalized, stride, offset)
3220    }
3221
3222    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.8>
3223    fn VertexAttribIPointer(
3224        &self,
3225        cx: &mut JSContext,
3226        index: u32,
3227        size: i32,
3228        type_: u32,
3229        stride: i32,
3230        offset: i64,
3231    ) {
3232        match type_ {
3233            constants::BYTE |
3234            constants::UNSIGNED_BYTE |
3235            constants::SHORT |
3236            constants::UNSIGNED_SHORT |
3237            constants::INT |
3238            constants::UNSIGNED_INT => {},
3239            _ => return self.base.webgl_error(InvalidEnum),
3240        };
3241        let res = self.current_vao(cx).vertex_attrib_pointer(
3242            index,
3243            size,
3244            type_,
3245            stride,
3246            offset,
3247            VertexAttribPointerKind::Integer,
3248        );
3249        if let Err(error) = res {
3250            self.base.webgl_error(error);
3251        }
3252    }
3253
3254    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4>
3255    fn Viewport(&self, x: i32, y: i32, width: i32, height: i32) {
3256        self.base.Viewport(x, y, width, height)
3257    }
3258
3259    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.6>
3260    ///
3261    /// Allocates and initializes the specified mipmap level of a three-dimensional or
3262    /// two-dimensional array texture.
3263    fn TexImage3D(
3264        &self,
3265        no_gc: &NoGC,
3266        target: u32,
3267        level: i32,
3268        internal_format: i32,
3269        width: i32,
3270        height: i32,
3271        depth: i32,
3272        border: i32,
3273        format: u32,
3274        type_: u32,
3275        src_data: CustomAutoRooterGuard<Option<ArrayBufferView>>,
3276    ) -> Fallible<()> {
3277        // If a WebGLBuffer is bound to the PIXEL_UNPACK_BUFFER target,
3278        // generates an INVALID_OPERATION error.
3279        if self.bound_pixel_unpack_buffer.get().is_some() {
3280            self.base.webgl_error(InvalidOperation);
3281            return Ok(());
3282        }
3283
3284        // If type is specified as FLOAT_32_UNSIGNED_INT_24_8_REV, srcData must be null;
3285        // otherwise, generates an INVALID_OPERATION error.
3286        if type_ == constants::FLOAT_32_UNSIGNED_INT_24_8_REV && src_data.is_some() {
3287            self.base.webgl_error(InvalidOperation);
3288            return Ok(());
3289        }
3290
3291        if border != 0 {
3292            self.base.webgl_error(InvalidValue);
3293            return Ok(());
3294        }
3295
3296        let Ok(TexImage3DValidatorResult {
3297            width,
3298            height,
3299            depth,
3300            level,
3301            border,
3302            texture,
3303            target,
3304            internal_format,
3305            format,
3306            data_type,
3307        }) = TexImage3DValidator::new(
3308            &self.base,
3309            target,
3310            level,
3311            internal_format as u32,
3312            width,
3313            height,
3314            depth,
3315            border,
3316            format,
3317            type_,
3318            &src_data,
3319        )
3320        .validate()
3321        else {
3322            return Ok(());
3323        };
3324
3325        let unpacking_alignment = self.base.texture_unpacking_alignment();
3326        let element_size = data_type.element_size();
3327        let components_per_element = data_type.components_per_element();
3328        let components = format.components();
3329        // NOTE: width, height and depth are positive or zero due to validate()
3330        let expected_byte_len = if height == 0 {
3331            0
3332        } else {
3333            // We need to be careful here to not count unpack
3334            // alignment at the end of the image, otherwise (for
3335            // example) passing a single byte for uploading a 1x1x1
3336            // GL_ALPHA/GL_UNSIGNED_BYTE texture would throw an error.
3337            let cpp = element_size * components / components_per_element;
3338            let mut padding_bytes = (cpp * width) % unpacking_alignment;
3339            if padding_bytes > 0 {
3340                padding_bytes = unpacking_alignment - padding_bytes;
3341            }
3342            let bytes_per_row = cpp * width + padding_bytes;
3343            let bytes_last_row = cpp * width;
3344            let bytes_per_image = bytes_per_row * height;
3345            let bytes_last_image = bytes_per_row * (height - 1) + bytes_last_row;
3346            bytes_per_image * (depth - 1) + bytes_last_image
3347        };
3348
3349        // If srcData is null, a buffer of sufficient size initialized to 0 is passed.
3350        let buff = match *src_data {
3351            Some(ref data) => {
3352                let block = match self.base.unpack_block(
3353                    data.as_slice_safe(no_gc).unwrap_or(&[]),
3354                    width,
3355                    height,
3356                    Some(depth),
3357                    bytes_per_pixel(format, data_type),
3358                ) {
3359                    Ok(block) => block,
3360                    Err(()) => return Ok(()),
3361                };
3362                GenericSharedMemory::from_bytes(&block)
3363            },
3364            None => GenericSharedMemory::from_byte(0, expected_byte_len as usize),
3365        };
3366        if buff.len() < expected_byte_len as usize {
3367            return {
3368                self.base.webgl_error(InvalidOperation);
3369                Ok(())
3370            };
3371        }
3372        let (alpha_treatment, y_axis_treatment) =
3373            self.base.get_current_unpack_state(Alpha::NotPremultiplied);
3374        // If UNPACK_FLIP_Y_WEBGL or UNPACK_PREMULTIPLY_ALPHA_WEBGL is set to true, texImage3D and texSubImage3D
3375        // generate an INVALID_OPERATION error if they upload data from a PIXEL_UNPACK_BUFFER or a non-null client
3376        // side ArrayBufferView.
3377        if let (Some(AlphaTreatment::Premultiply), YAxisTreatment::Flipped) =
3378            (alpha_treatment, y_axis_treatment) &&
3379            src_data.is_some()
3380        {
3381            self.base.webgl_error(InvalidOperation);
3382            return Ok(());
3383        }
3384        let tex_source = TexPixels::from_array(
3385            buff,
3386            Size2D::new(width, height),
3387            alpha_treatment,
3388            y_axis_treatment,
3389        );
3390
3391        self.tex_image_3d(
3392            &texture,
3393            target,
3394            data_type,
3395            internal_format,
3396            format,
3397            level,
3398            width,
3399            height,
3400            depth,
3401            border,
3402            unpacking_alignment,
3403            tex_source,
3404        );
3405        Ok(())
3406    }
3407
3408    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
3409    fn TexImage2D(
3410        &self,
3411        no_gc: &NoGC,
3412        target: u32,
3413        level: i32,
3414        internal_format: i32,
3415        width: i32,
3416        height: i32,
3417        border: i32,
3418        format: u32,
3419        data_type: u32,
3420        pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>,
3421    ) -> Fallible<()> {
3422        self.base.TexImage2D(
3423            no_gc,
3424            target,
3425            level,
3426            internal_format,
3427            width,
3428            height,
3429            border,
3430            format,
3431            data_type,
3432            pixels,
3433        )
3434    }
3435
3436    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
3437    fn TexImage2D_(
3438        &self,
3439        no_gc: &NoGC,
3440        target: u32,
3441        level: i32,
3442        internal_format: i32,
3443        format: u32,
3444        data_type: u32,
3445        source: TexImageSource,
3446    ) -> ErrorResult {
3447        self.base.TexImage2D_(
3448            no_gc,
3449            target,
3450            level,
3451            internal_format,
3452            format,
3453            data_type,
3454            source,
3455        )
3456    }
3457
3458    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.6>
3459    fn TexImage2D__(
3460        &self,
3461        _no_gc: &NoGC,
3462        target: u32,
3463        level: i32,
3464        internalformat: i32,
3465        width: i32,
3466        height: i32,
3467        border: i32,
3468        format: u32,
3469        type_: u32,
3470        pbo_offset: i64,
3471    ) -> Fallible<()> {
3472        let pixel_unpack_buffer = match self.bound_pixel_unpack_buffer.get() {
3473            Some(pixel_unpack_buffer) => pixel_unpack_buffer,
3474            None => {
3475                self.base.webgl_error(InvalidOperation);
3476                return Ok(());
3477            },
3478        };
3479
3480        if let Some(tf_buffer) = self.bound_transform_feedback_buffer.get() &&
3481            pixel_unpack_buffer == tf_buffer
3482        {
3483            self.base.webgl_error(InvalidOperation);
3484            return Ok(());
3485        }
3486
3487        if pbo_offset < 0 || pbo_offset as usize > pixel_unpack_buffer.capacity() {
3488            self.base.webgl_error(InvalidValue);
3489            return Ok(());
3490        }
3491
3492        // TODO: Apply the unpack layout to pixel unpack buffer uploads.
3493        let mut layout = self.base.texture_unpack_layout();
3494        layout.image_height = 0;
3495        layout.skip_images = 0;
3496        if layout != Default::default() {
3497            self.base.webgl_error(InvalidOperation);
3498            return Ok(());
3499        }
3500
3501        let unpacking_alignment = self.base.texture_unpacking_alignment();
3502
3503        let validator = TexImage2DValidator::new(
3504            &self.base,
3505            target,
3506            level,
3507            internalformat as u32,
3508            width,
3509            height,
3510            border,
3511            format,
3512            type_,
3513        );
3514
3515        let TexImage2DValidatorResult {
3516            texture,
3517            target,
3518            width,
3519            height,
3520            level,
3521            border,
3522            internal_format,
3523            format,
3524            data_type,
3525        } = match validator.validate() {
3526            Ok(result) => result,
3527            Err(_) => return Ok(()),
3528        };
3529
3530        self.base.tex_image_2d(
3531            &texture,
3532            target,
3533            data_type,
3534            internal_format,
3535            format,
3536            level,
3537            border,
3538            unpacking_alignment,
3539            Size2D::new(width, height),
3540            TexSource::BufferOffset(pbo_offset),
3541        );
3542
3543        Ok(())
3544    }
3545
3546    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.6>
3547    fn TexImage2D___(
3548        &self,
3549        no_gc: &NoGC,
3550        target: u32,
3551        level: i32,
3552        internalformat: i32,
3553        width: i32,
3554        height: i32,
3555        border: i32,
3556        format: u32,
3557        type_: u32,
3558        source: TexImageSource,
3559    ) -> Fallible<()> {
3560        if self.bound_pixel_unpack_buffer.get().is_some() {
3561            self.base.webgl_error(InvalidOperation);
3562            return Ok(());
3563        }
3564
3565        let validator = TexImage2DValidator::new(
3566            &self.base,
3567            target,
3568            level,
3569            internalformat as u32,
3570            width,
3571            height,
3572            border,
3573            format,
3574            type_,
3575        );
3576
3577        let TexImage2DValidatorResult {
3578            texture,
3579            target,
3580            width,
3581            height,
3582            level,
3583            border,
3584            internal_format,
3585            format,
3586            data_type,
3587        } = match validator.validate() {
3588            Ok(result) => result,
3589            Err(_) => return Ok(()),
3590        };
3591
3592        let pixels = match self.base.get_image_pixels(no_gc, source)? {
3593            Some(pixels) => pixels,
3594            None => return Ok(()),
3595        };
3596        // <https://registry.khronos.org/webgl/specs/latest/2.0/#DOM_UPLOAD_UNPACK_PARAMS>
3597        let layout = self.base.texture_unpack_layout();
3598        let origin = Point2D::new(layout.skip_pixels, layout.skip_rows);
3599        let Some(pixels) = pixels.sub_rect(origin, Size2D::new(width, height)) else {
3600            self.base.webgl_error(InvalidOperation);
3601            return Ok(());
3602        };
3603
3604        self.base.tex_image_2d(
3605            &texture,
3606            target,
3607            data_type,
3608            internal_format,
3609            format,
3610            level,
3611            border,
3612            // UNPACK_ALIGNMENT does not apply to TexImageSource uploads, whose rows are packed.
3613            1,
3614            pixels.size(),
3615            TexSource::Pixels(pixels),
3616        );
3617
3618        Ok(())
3619    }
3620
3621    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.6>
3622    fn TexImage2D____(
3623        &self,
3624        no_gc: &NoGC,
3625        target: u32,
3626        level: i32,
3627        internalformat: i32,
3628        width: i32,
3629        height: i32,
3630        border: i32,
3631        format: u32,
3632        type_: u32,
3633        src_data: CustomAutoRooterGuard<ArrayBufferView>,
3634        src_offset: u32,
3635    ) -> Fallible<()> {
3636        if self.bound_pixel_unpack_buffer.get().is_some() {
3637            self.base.webgl_error(InvalidOperation);
3638            return Ok(());
3639        }
3640
3641        if type_ == constants::FLOAT_32_UNSIGNED_INT_24_8_REV {
3642            self.base.webgl_error(InvalidOperation);
3643            return Ok(());
3644        }
3645
3646        let validator = TexImage2DValidator::new(
3647            &self.base,
3648            target,
3649            level,
3650            internalformat as u32,
3651            width,
3652            height,
3653            border,
3654            format,
3655            type_,
3656        );
3657
3658        let TexImage2DValidatorResult {
3659            texture,
3660            target,
3661            width,
3662            height,
3663            level,
3664            border,
3665            internal_format,
3666            format,
3667            data_type,
3668        } = match validator.validate() {
3669            Ok(result) => result,
3670            Err(_) => return Ok(()),
3671        };
3672
3673        let unpacking_alignment = self.base.texture_unpacking_alignment();
3674
3675        let src_elem_size = src_data.get_array_type().byte_size().unwrap();
3676        let src_byte_offset = src_offset as usize * src_elem_size;
3677
3678        if src_data.len() <= src_byte_offset {
3679            self.base.webgl_error(InvalidOperation);
3680            return Ok(());
3681        }
3682
3683        let src_data_slice = src_data.as_slice_safe(no_gc).unwrap_or(&[]);
3684        let block = match self.base.unpack_block(
3685            &src_data_slice[src_byte_offset..],
3686            width,
3687            height,
3688            None,
3689            bytes_per_pixel(format, data_type),
3690        ) {
3691            Ok(block) => block,
3692            Err(()) => return Ok(()),
3693        };
3694        let buff = GenericSharedMemory::from_bytes(&block);
3695
3696        let expected_byte_length = match self.base.validate_tex_image_2d_data(
3697            width,
3698            height,
3699            format,
3700            data_type,
3701            unpacking_alignment,
3702            Some(&*src_data),
3703        ) {
3704            Ok(byte_length) => byte_length,
3705            Err(()) => return Ok(()),
3706        };
3707
3708        if expected_byte_length as usize > buff.len() {
3709            self.base.webgl_error(InvalidOperation);
3710            return Ok(());
3711        }
3712
3713        let size = Size2D::new(width, height);
3714
3715        let (alpha_treatment, y_axis_treatment) =
3716            self.base.get_current_unpack_state(Alpha::NotPremultiplied);
3717
3718        self.base.tex_image_2d(
3719            &texture,
3720            target,
3721            data_type,
3722            internal_format,
3723            format,
3724            level,
3725            border,
3726            unpacking_alignment,
3727            size,
3728            TexSource::Pixels(TexPixels::from_array(
3729                buff,
3730                size,
3731                alpha_treatment,
3732                y_axis_treatment,
3733            )),
3734        );
3735
3736        Ok(())
3737    }
3738
3739    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
3740    fn TexSubImage2D(
3741        &self,
3742        no_gc: &NoGC,
3743        target: u32,
3744        level: i32,
3745        xoffset: i32,
3746        yoffset: i32,
3747        width: i32,
3748        height: i32,
3749        format: u32,
3750        data_type: u32,
3751        pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>,
3752    ) -> Fallible<()> {
3753        self.base.TexSubImage2D(
3754            no_gc, target, level, xoffset, yoffset, width, height, format, data_type, pixels,
3755        )
3756    }
3757
3758    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
3759    fn TexSubImage2D_(
3760        &self,
3761        no_gc: &NoGC,
3762        target: u32,
3763        level: i32,
3764        xoffset: i32,
3765        yoffset: i32,
3766        format: u32,
3767        data_type: u32,
3768        source: TexImageSource,
3769    ) -> ErrorResult {
3770        self.base.TexSubImage2D_(
3771            no_gc, target, level, xoffset, yoffset, format, data_type, source,
3772        )
3773    }
3774
3775    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
3776    fn TexParameterf(&self, target: u32, name: u32, value: f32) {
3777        self.base.TexParameterf(target, name, value)
3778    }
3779
3780    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
3781    fn TexParameteri(&self, target: u32, name: u32, value: i32) {
3782        self.base.TexParameteri(target, name, value)
3783    }
3784
3785    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
3786    fn CheckFramebufferStatus(&self, target: u32) -> u32 {
3787        let fb_slot = match target {
3788            constants::FRAMEBUFFER | constants::DRAW_FRAMEBUFFER => {
3789                self.base.get_draw_framebuffer_slot()
3790            },
3791            constants::READ_FRAMEBUFFER => self.base.get_read_framebuffer_slot(),
3792            _ => {
3793                self.base.webgl_error(InvalidEnum);
3794                return 0;
3795            },
3796        };
3797        match fb_slot.get() {
3798            Some(fb) => fb.check_status(),
3799            None => constants::FRAMEBUFFER_COMPLETE,
3800        }
3801    }
3802
3803    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
3804    fn RenderbufferStorage(&self, target: u32, internal_format: u32, width: i32, height: i32) {
3805        self.base
3806            .RenderbufferStorage(target, internal_format, width, height)
3807    }
3808
3809    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.4S>
3810    fn BlitFramebuffer(
3811        &self,
3812        src_x0: i32,
3813        src_y0: i32,
3814        src_x1: i32,
3815        src_y1: i32,
3816        dst_x0: i32,
3817        dst_y0: i32,
3818        dst_x1: i32,
3819        dst_y1: i32,
3820        mask: u32,
3821        filter: u32,
3822    ) {
3823        bitflags! {
3824            struct BlitFrameBufferFlags: u32 {
3825                const DEPTH = constants::DEPTH_BUFFER_BIT;
3826                const COLOR = constants::COLOR_BUFFER_BIT;
3827                const STENCIL = constants::STENCIL_BUFFER_BIT;
3828                const DEPTH_STENCIL = constants::DEPTH_BUFFER_BIT | constants::STENCIL_BUFFER_BIT;
3829            }
3830        };
3831        let Some(bits) = BlitFrameBufferFlags::from_bits(mask) else {
3832            return self.base.webgl_error(InvalidValue);
3833        };
3834        let attributes = self.base.GetContextAttributes().unwrap();
3835
3836        if bits.intersects(BlitFrameBufferFlags::DEPTH_STENCIL) {
3837            match filter {
3838                constants::LINEAR => return self.base.webgl_error(InvalidOperation),
3839                constants::NEAREST => {},
3840                _ => return self.base.webgl_error(InvalidOperation),
3841            }
3842        }
3843
3844        let src_fb = self.base.get_read_framebuffer_slot().get();
3845        let dst_fb = self.base.get_draw_framebuffer_slot().get();
3846
3847        if src_fb
3848            .as_ref()
3849            .is_some_and(|fb| fb.check_status() != constants::FRAMEBUFFER_COMPLETE)
3850        {
3851            return self.base.webgl_error(InvalidFramebufferOperation);
3852        }
3853        // Both framebuffers' uninitialized attachments must be cleared before the blit.
3854        if let Some(fb) = &dst_fb &&
3855            let CompleteForRendering::Incomplete = fb.check_status_for_rendering()
3856        {
3857            return self.base.webgl_error(InvalidFramebufferOperation);
3858        }
3859        if let Some(fb) = &src_fb {
3860            fb.initialize_for_reading(dst_fb.as_deref());
3861        }
3862
3863        let get_default_formats = || -> WebGLResult<(Option<u32>, Option<u32>, Option<u32>)> {
3864            // All attempts to blit to an antialiased back buffer should fail.
3865            if attributes.antialias {
3866                return Err(InvalidOperation);
3867            };
3868            let color = if attributes.alpha {
3869                Some(constants::RGBA8)
3870            } else {
3871                Some(constants::RGB8)
3872            };
3873            let (depth, stencil) = match (attributes.depth, attributes.stencil) {
3874                (true, true) => (
3875                    Some(constants::DEPTH24_STENCIL8),
3876                    Some(constants::DEPTH24_STENCIL8),
3877                ),
3878                (true, false) => (Some(constants::DEPTH_COMPONENT16), None),
3879                (false, true) => (None, Some(constants::STENCIL_INDEX8)),
3880                _ => (None, None),
3881            };
3882            Ok((color, depth, stencil))
3883        };
3884
3885        let (src_color, src_depth, src_stencil) = match &src_fb {
3886            Some(fb) => match fb.get_attachment_formats() {
3887                Ok(formats) => formats,
3888                Err(error) => return self.base.webgl_error(error),
3889            },
3890            None => match get_default_formats() {
3891                Ok(formats) => formats,
3892                Err(error) => return self.base.webgl_error(error),
3893            },
3894        };
3895        let (dst_color, dst_depth, dst_stencil) = match dst_fb {
3896            Some(fb) => match fb.get_attachment_formats() {
3897                Ok((_, depth, stencil)) => (fb.color_draw_buffer_formats(), depth, stencil),
3898                Err(error) => return self.base.webgl_error(error),
3899            },
3900            None => match get_default_formats() {
3901                Ok((color, depth, stencil)) => (Vec::from_iter(color), depth, stencil),
3902                Err(error) => return self.base.webgl_error(error),
3903            },
3904        };
3905
3906        // Renderbuffer sample counts are untracked, so any renderbuffer may be multisampled.
3907        let src_single_sampled = src_fb
3908            .as_ref()
3909            .is_none_or(|fb| fb.color_read_buffer_is_texture());
3910        // Format rules from GLES 3.0 section 4.3.3.
3911        let colors_compatible = dst_color.iter().all(|&dst| {
3912            src_color.is_some_and(|src| {
3913                if src_single_sampled {
3914                    blit_integer_type(src) == blit_integer_type(dst)
3915                } else {
3916                    src == dst
3917                }
3918            })
3919        });
3920        if bits.intersects(BlitFrameBufferFlags::COLOR) && !colors_compatible {
3921            return self.base.webgl_error(InvalidOperation);
3922        }
3923        if bits.intersects(BlitFrameBufferFlags::DEPTH) && src_depth != dst_depth {
3924            return self.base.webgl_error(InvalidOperation);
3925        }
3926        if bits.intersects(BlitFrameBufferFlags::STENCIL) && src_stencil != dst_stencil {
3927            return self.base.webgl_error(InvalidOperation);
3928        }
3929
3930        let src_width = src_x1.checked_sub(src_x0);
3931        let dst_width = dst_x1.checked_sub(dst_x0);
3932        let src_height = src_y1.checked_sub(src_y0);
3933        let dst_height = dst_y1.checked_sub(dst_y0);
3934
3935        if src_width.is_none() ||
3936            dst_width.is_none() ||
3937            src_height.is_none() ||
3938            dst_height.is_none()
3939        {
3940            return self.base.webgl_error(InvalidOperation);
3941        }
3942
3943        self.base.send_command(WebGLCommand::BlitFrameBuffer(
3944            src_x0, src_y0, src_x1, src_y1, dst_x0, dst_y0, dst_x1, dst_y1, mask, filter,
3945        ));
3946        self.mark_as_dirty();
3947    }
3948
3949    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
3950    fn FramebufferRenderbuffer(
3951        &self,
3952        target: u32,
3953        attachment: u32,
3954        renderbuffertarget: u32,
3955        rb: Option<&WebGLRenderbuffer>,
3956    ) {
3957        if let Some(rb) = rb &&
3958            let Err(error) = self.base.validate_ownership(rb)
3959        {
3960            return self.base.webgl_error(error);
3961        }
3962
3963        let fb_slot = match target {
3964            constants::FRAMEBUFFER | constants::DRAW_FRAMEBUFFER => {
3965                self.base.get_draw_framebuffer_slot()
3966            },
3967            constants::READ_FRAMEBUFFER => self.base.get_read_framebuffer_slot(),
3968            _ => return self.base.webgl_error(InvalidEnum),
3969        };
3970
3971        if renderbuffertarget != constants::RENDERBUFFER {
3972            return self.base.webgl_error(InvalidEnum);
3973        }
3974
3975        match fb_slot.get() {
3976            Some(fb) => {
3977                if let Err(error) = fb.renderbuffer(attachment, rb) {
3978                    self.base.webgl_error(error);
3979                }
3980            },
3981            None => self.base.webgl_error(InvalidOperation),
3982        };
3983    }
3984
3985    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
3986    fn FramebufferTexture2D(
3987        &self,
3988        target: u32,
3989        attachment: u32,
3990        textarget: u32,
3991        texture: Option<&WebGLTexture>,
3992        level: i32,
3993    ) {
3994        if let Some(texture) = texture &&
3995            let Err(error) = self.base.validate_ownership(texture)
3996        {
3997            return self.base.webgl_error(error);
3998        }
3999
4000        let fb_slot = match target {
4001            constants::FRAMEBUFFER | constants::DRAW_FRAMEBUFFER => {
4002                self.base.get_draw_framebuffer_slot()
4003            },
4004            constants::READ_FRAMEBUFFER => self.base.get_read_framebuffer_slot(),
4005            _ => return self.base.webgl_error(InvalidEnum),
4006        };
4007        match fb_slot.get() {
4008            Some(fb) => {
4009                if let Err(error) = fb.texture2d(attachment, textarget, texture, level) {
4010                    self.base.webgl_error(error);
4011                }
4012            },
4013            None => self.base.webgl_error(InvalidOperation),
4014        }
4015    }
4016
4017    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
4018    fn GetAttachedShaders(&self, program: &WebGLProgram) -> Option<Vec<DomRoot<WebGLShader>>> {
4019        self.base.GetAttachedShaders(program)
4020    }
4021
4022    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.9>
4023    fn DrawArraysInstanced(
4024        &self,
4025        cx: &mut JSContext,
4026        mode: u32,
4027        first: i32,
4028        count: i32,
4029        primcount: i32,
4030    ) {
4031        self.validate_uniform_block_for_draw();
4032        self.validate_vertex_attribs_for_draw(cx);
4033        if let Err(error) = self
4034            .base
4035            .draw_arrays_instanced(cx, mode, first, count, primcount)
4036        {
4037            self.base.webgl_error(error);
4038        }
4039    }
4040
4041    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.9>
4042    fn DrawElementsInstanced(
4043        &self,
4044        cx: &mut JSContext,
4045        mode: u32,
4046        count: i32,
4047        type_: u32,
4048        offset: i64,
4049        primcount: i32,
4050    ) {
4051        self.validate_uniform_block_for_draw();
4052        self.validate_vertex_attribs_for_draw(cx);
4053        if let Err(error) = self
4054            .base
4055            .draw_elements_instanced(cx, mode, count, type_, offset, primcount)
4056        {
4057            self.base.webgl_error(error);
4058        }
4059    }
4060
4061    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.9>
4062    fn DrawRangeElements(
4063        &self,
4064        cx: &mut JSContext,
4065        mode: u32,
4066        start: u32,
4067        end: u32,
4068        count: i32,
4069        type_: u32,
4070        offset: i64,
4071    ) {
4072        if end < start {
4073            self.base.webgl_error(InvalidValue);
4074            return;
4075        }
4076        self.validate_uniform_block_for_draw();
4077        self.validate_vertex_attribs_for_draw(cx);
4078        if let Err(error) = self
4079            .base
4080            .draw_elements_instanced(cx, mode, count, type_, offset, 1)
4081        {
4082            self.base.webgl_error(error);
4083        }
4084    }
4085
4086    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.9>
4087    fn VertexAttribDivisor(&self, cx: &mut JSContext, index: u32, divisor: u32) {
4088        self.base.vertex_attrib_divisor(cx, index, divisor);
4089    }
4090
4091    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.12>
4092    fn CreateQuery(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLQuery>> {
4093        Some(WebGLQuery::new(cx, &self.base))
4094    }
4095
4096    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.12>
4097    fn DeleteQuery(&self, query: Option<&WebGLQuery>) {
4098        if let Some(query) = query {
4099            if let Err(error) = self.base.validate_ownership(query) {
4100                return self.base.webgl_error(error);
4101            }
4102
4103            if let Some(query_target) = query.target() {
4104                let slot = match query_target {
4105                    constants::ANY_SAMPLES_PASSED | constants::ANY_SAMPLES_PASSED_CONSERVATIVE => {
4106                        &self.occlusion_query
4107                    },
4108                    constants::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN => &self.primitives_query,
4109                    _ => unreachable!(),
4110                };
4111                if let Some(stored_query) = slot.get() &&
4112                    stored_query.target() == query.target()
4113                {
4114                    slot.set(None);
4115                }
4116            }
4117
4118            query.delete(Operation::Infallible);
4119        }
4120    }
4121
4122    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.12>
4123    fn IsQuery(&self, query: Option<&WebGLQuery>) -> bool {
4124        match query {
4125            Some(query) => self.base.validate_ownership(query).is_ok() && query.is_valid(),
4126            None => false,
4127        }
4128    }
4129
4130    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.13>
4131    fn CreateSampler(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLSampler>> {
4132        Some(WebGLSampler::new(cx, &self.base))
4133    }
4134
4135    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.13>
4136    fn DeleteSampler(&self, sampler: Option<&WebGLSampler>) {
4137        if let Some(sampler) = sampler {
4138            if let Err(error) = self.base.validate_ownership(sampler) {
4139                return self.base.webgl_error(error);
4140            }
4141            for slot in self.samplers.iter() {
4142                if slot.get().is_some_and(|s| sampler == &*s) {
4143                    slot.set(None);
4144                }
4145            }
4146            sampler.delete(Operation::Infallible);
4147        }
4148    }
4149
4150    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.13>
4151    fn IsSampler(&self, sampler: Option<&WebGLSampler>) -> bool {
4152        match sampler {
4153            Some(sampler) => self.base.validate_ownership(sampler).is_ok() && sampler.is_valid(),
4154            None => false,
4155        }
4156    }
4157
4158    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.12>
4159    fn BeginQuery(&self, target: u32, query: &WebGLQuery) {
4160        if let Err(error) = self.base.validate_ownership(query) {
4161            return self.base.webgl_error(error);
4162        }
4163
4164        let active_query = match target {
4165            constants::ANY_SAMPLES_PASSED | constants::ANY_SAMPLES_PASSED_CONSERVATIVE => {
4166                &self.occlusion_query
4167            },
4168            constants::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN => &self.primitives_query,
4169            _ => {
4170                self.base.webgl_error(InvalidEnum);
4171                return;
4172            },
4173        };
4174        if active_query.get().is_some() {
4175            self.base.webgl_error(InvalidOperation);
4176            return;
4177        }
4178        let result = query.begin(&self.base, target);
4179        match result {
4180            Ok(_) => active_query.set(Some(query)),
4181            Err(error) => self.base.webgl_error(error),
4182        }
4183    }
4184
4185    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.12>
4186    fn EndQuery(&self, target: u32) {
4187        let active_query = match target {
4188            constants::ANY_SAMPLES_PASSED | constants::ANY_SAMPLES_PASSED_CONSERVATIVE => {
4189                self.occlusion_query.take()
4190            },
4191            constants::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN => self.primitives_query.take(),
4192            _ => {
4193                self.base.webgl_error(InvalidEnum);
4194                return;
4195            },
4196        };
4197        match active_query {
4198            None => self.base.webgl_error(InvalidOperation),
4199            Some(query) => {
4200                let result = query.end(&self.base, target);
4201                if let Err(error) = result {
4202                    self.base.webgl_error(error);
4203                }
4204            },
4205        }
4206    }
4207
4208    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.12>
4209    fn GetQuery(&self, target: u32, pname: u32) -> Option<DomRoot<WebGLQuery>> {
4210        if pname != constants::CURRENT_QUERY {
4211            self.base.webgl_error(InvalidEnum);
4212            return None;
4213        }
4214        let active_query = match target {
4215            constants::ANY_SAMPLES_PASSED | constants::ANY_SAMPLES_PASSED_CONSERVATIVE => {
4216                self.occlusion_query.get()
4217            },
4218            constants::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN => self.primitives_query.get(),
4219            _ => {
4220                self.base.webgl_error(InvalidEnum);
4221                None
4222            },
4223        };
4224        if let Some(query) = active_query.as_ref() &&
4225            query.target() != Some(target)
4226        {
4227            return None;
4228        }
4229        active_query
4230    }
4231
4232    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.12>
4233    fn GetQueryParameter(
4234        &self,
4235        _cx: &mut JSContext,
4236        query: &WebGLQuery,
4237        pname: u32,
4238        mut retval: MutableHandleValue,
4239    ) {
4240        if let Err(error) = self.base.validate_ownership(query) {
4241            self.base.webgl_error(error);
4242            return retval.set(NullValue());
4243        }
4244        match query.get_parameter(&self.base, pname) {
4245            Ok(value) => match pname {
4246                constants::QUERY_RESULT => retval.set(UInt32Value(value)),
4247                constants::QUERY_RESULT_AVAILABLE => retval.set(BooleanValue(value != 0)),
4248                _ => unreachable!(),
4249            },
4250            Err(error) => {
4251                self.base.webgl_error(error);
4252                retval.set(NullValue())
4253            },
4254        }
4255    }
4256
4257    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.14>
4258    fn FenceSync(
4259        &self,
4260        cx: &mut JSContext,
4261        condition: u32,
4262        flags: u32,
4263    ) -> Option<DomRoot<WebGLSync>> {
4264        if flags != 0 {
4265            self.base.webgl_error(InvalidValue);
4266            return None;
4267        }
4268        if condition != constants::SYNC_GPU_COMMANDS_COMPLETE {
4269            self.base.webgl_error(InvalidEnum);
4270            return None;
4271        }
4272
4273        Some(WebGLSync::new(cx, &self.base))
4274    }
4275
4276    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.14>
4277    fn IsSync(&self, sync: Option<&WebGLSync>) -> bool {
4278        match sync {
4279            Some(sync) => {
4280                // Returns false if the sync was generated by a different
4281                // WebGL2RenderingContext than this one.
4282                if self.base.validate_ownership(sync).is_err() {
4283                    return false;
4284                }
4285
4286                // Returns false if the sync's invalidated flag is set.
4287                if !sync.is_valid() {
4288                    return false;
4289                }
4290
4291                // Return true if the passed WebGLSync is valid and false otherwise.
4292                if let Err(error) = self.base.validate_ownership(sync) {
4293                    self.base.webgl_error(error);
4294                    return false;
4295                }
4296                let (sender, receiver) = webgl_channel().unwrap();
4297                self.base
4298                    .send_command(WebGLCommand::IsSync(sync.id(), sender));
4299                receiver.recv().unwrap()
4300            },
4301            None => false,
4302        }
4303    }
4304
4305    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.14>
4306    fn ClientWaitSync(&self, sync: &WebGLSync, flags: u32, timeout: u64) -> u32 {
4307        if !sync.is_valid() {
4308            self.base.webgl_error(InvalidOperation);
4309            return constants::WAIT_FAILED;
4310        }
4311        if let Err(error) = self.base.validate_ownership(sync) {
4312            self.base.webgl_error(error);
4313            return constants::WAIT_FAILED;
4314        }
4315        if flags != 0 && flags != constants::SYNC_FLUSH_COMMANDS_BIT {
4316            self.base.webgl_error(InvalidValue);
4317            return constants::WAIT_FAILED;
4318        }
4319        if timeout > self.base.limits().max_client_wait_timeout_webgl.as_nanos() as u64 {
4320            self.base.webgl_error(InvalidOperation);
4321            return constants::WAIT_FAILED;
4322        }
4323
4324        match sync.client_wait_sync(&self.base, flags, timeout) {
4325            Some(status) => status,
4326            None => constants::WAIT_FAILED,
4327        }
4328    }
4329
4330    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.14>
4331    fn WaitSync(&self, sync: &WebGLSync, flags: u32, timeout: i64) {
4332        if !sync.is_valid() {
4333            self.base.webgl_error(InvalidOperation);
4334            return;
4335        }
4336        if let Err(error) = self.base.validate_ownership(sync) {
4337            return self.base.webgl_error(error);
4338        }
4339        if flags != 0 {
4340            self.base.webgl_error(InvalidValue);
4341            return;
4342        }
4343        if timeout != constants::TIMEOUT_IGNORED {
4344            self.base.webgl_error(InvalidValue);
4345            return;
4346        }
4347
4348        self.base
4349            .send_command(WebGLCommand::WaitSync(sync.id(), flags, timeout));
4350    }
4351
4352    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.14>
4353    fn GetSyncParameter(
4354        &self,
4355        _cx: &mut JSContext,
4356        sync: &WebGLSync,
4357        pname: u32,
4358        mut retval: MutableHandleValue,
4359    ) {
4360        if !sync.is_valid() {
4361            self.base.webgl_error(InvalidOperation);
4362            return retval.set(NullValue());
4363        }
4364        if let Err(error) = self.base.validate_ownership(sync) {
4365            self.base.webgl_error(error);
4366            return retval.set(NullValue());
4367        }
4368        match pname {
4369            constants::OBJECT_TYPE | constants::SYNC_CONDITION | constants::SYNC_FLAGS => {
4370                let (sender, receiver) = webgl_channel().unwrap();
4371                self.base
4372                    .send_command(WebGLCommand::GetSyncParameter(sync.id(), pname, sender));
4373                retval.set(UInt32Value(receiver.recv().unwrap()))
4374            },
4375            constants::SYNC_STATUS => match sync.get_sync_status(pname, &self.base) {
4376                Some(status) => retval.set(UInt32Value(status)),
4377                None => retval.set(UInt32Value(constants::UNSIGNALED)),
4378            },
4379            _ => {
4380                self.base.webgl_error(InvalidEnum);
4381                retval.set(NullValue())
4382            },
4383        }
4384    }
4385
4386    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.14>
4387    fn DeleteSync(&self, sync: Option<&WebGLSync>) {
4388        if let Some(sync) = sync {
4389            if let Err(error) = self.base.validate_ownership(sync) {
4390                return self.base.webgl_error(error);
4391            }
4392            sync.delete(Operation::Infallible);
4393        }
4394    }
4395
4396    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.13>
4397    fn BindSampler(&self, unit: u32, sampler: Option<&WebGLSampler>) {
4398        if let Some(sampler) = sampler {
4399            if let Err(error) = self.base.validate_ownership(sampler) {
4400                return self.base.webgl_error(error);
4401            }
4402
4403            if unit as usize >= self.samplers.len() {
4404                self.base.webgl_error(InvalidValue);
4405                return;
4406            }
4407
4408            let result = sampler.bind(&self.base, unit);
4409            match result {
4410                Ok(_) => self.samplers[unit as usize].set(Some(sampler)),
4411                Err(error) => self.base.webgl_error(error),
4412            }
4413        }
4414    }
4415
4416    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.17>
4417    fn BindVertexArray(&self, array: Option<&WebGLVertexArrayObject>) {
4418        self.base.bind_vertex_array_webgl2(array);
4419    }
4420
4421    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.13>
4422    fn SamplerParameteri(&self, sampler: &WebGLSampler, pname: u32, param: i32) {
4423        if let Err(error) = self.base.validate_ownership(sampler) {
4424            return self.base.webgl_error(error);
4425        }
4426        let param = WebGLSamplerValue::GLenum(param as u32);
4427        let result = sampler.set_parameter(&self.base, pname, param);
4428        if let Err(error) = result {
4429            self.base.webgl_error(error);
4430        }
4431    }
4432
4433    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.13>
4434    fn SamplerParameterf(&self, sampler: &WebGLSampler, pname: u32, param: f32) {
4435        if let Err(error) = self.base.validate_ownership(sampler) {
4436            return self.base.webgl_error(error);
4437        }
4438        let param = WebGLSamplerValue::Float(param);
4439        let result = sampler.set_parameter(&self.base, pname, param);
4440        if let Err(error) = result {
4441            self.base.webgl_error(error);
4442        }
4443    }
4444
4445    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.13>
4446    fn GetSamplerParameter(
4447        &self,
4448        _cx: &mut JSContext,
4449        sampler: &WebGLSampler,
4450        pname: u32,
4451        mut retval: MutableHandleValue,
4452    ) {
4453        if let Err(error) = self.base.validate_ownership(sampler) {
4454            self.base.webgl_error(error);
4455            return retval.set(NullValue());
4456        }
4457        match sampler.get_parameter(&self.base, pname) {
4458            Ok(value) => match value {
4459                WebGLSamplerValue::GLenum(value) => retval.set(UInt32Value(value)),
4460                WebGLSamplerValue::Float(value) => retval.set(DoubleValue(value as f64)),
4461            },
4462            Err(error) => {
4463                self.base.webgl_error(error);
4464                retval.set(NullValue())
4465            },
4466        }
4467    }
4468
4469    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.15>
4470    fn CreateTransformFeedback(
4471        &self,
4472        cx: &mut JSContext,
4473    ) -> Option<DomRoot<WebGLTransformFeedback>> {
4474        Some(WebGLTransformFeedback::new(cx, &self.base))
4475    }
4476
4477    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.15>
4478    fn DeleteTransformFeedback(&self, tf: Option<&WebGLTransformFeedback>) {
4479        if let Some(tf) = tf {
4480            if let Err(error) = self.base.validate_ownership(tf) {
4481                return self.base.webgl_error(error);
4482            }
4483            if tf.is_active() {
4484                self.base.webgl_error(InvalidOperation);
4485                return;
4486            }
4487            tf.delete(Operation::Infallible);
4488            self.current_transform_feedback.set(None);
4489        }
4490    }
4491
4492    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.15>
4493    fn IsTransformFeedback(&self, tf: Option<&WebGLTransformFeedback>) -> bool {
4494        match tf {
4495            Some(tf) => {
4496                // Returns false if the transform feedback was generated by a different
4497                // WebGL2RenderingContext than this one.
4498                if self.base.validate_ownership(tf).is_err() {
4499                    return false;
4500                }
4501
4502                // Returns false if the transform feedback's invalidated flag is set.
4503                if !tf.is_valid() {
4504                    return false;
4505                }
4506
4507                // Return true if the passed WebGLTransformFeedback is valid and false otherwise.
4508                if let Err(error) = self.base.validate_ownership(tf) {
4509                    self.base.webgl_error(error);
4510                    return false;
4511                }
4512                let (sender, receiver) = webgl_channel().unwrap();
4513                self.base
4514                    .send_command(WebGLCommand::IsTransformFeedback(tf.id(), sender));
4515                receiver.recv().unwrap()
4516            },
4517            // Returns false if `transformFeedback` is null.
4518            None => false,
4519        }
4520    }
4521
4522    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.15>
4523    fn BindTransformFeedback(&self, target: u32, tf: Option<&WebGLTransformFeedback>) {
4524        if target != constants::TRANSFORM_FEEDBACK {
4525            self.base.webgl_error(InvalidEnum);
4526            return;
4527        }
4528        match tf {
4529            Some(transform_feedback) => {
4530                if let Err(error) = self.base.validate_ownership(transform_feedback) {
4531                    return self.base.webgl_error(error);
4532                }
4533                if !transform_feedback.is_valid() {
4534                    self.base.webgl_error(InvalidOperation);
4535                    return;
4536                }
4537                if let Some(current_tf) = self.current_transform_feedback.get() &&
4538                    current_tf.is_active() &&
4539                    !current_tf.is_paused()
4540                {
4541                    self.base.webgl_error(InvalidOperation);
4542                    return;
4543                }
4544                transform_feedback.bind(&self.base, target);
4545                self.current_transform_feedback
4546                    .set(Some(transform_feedback));
4547            },
4548            None => self
4549                .base
4550                .send_command(WebGLCommand::BindTransformFeedback(target, 0)),
4551        }
4552    }
4553
4554    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.15>
4555    #[expect(non_snake_case)]
4556    fn BeginTransformFeedback(&self, primitiveMode: u32) {
4557        match primitiveMode {
4558            constants::POINTS | constants::LINES | constants::TRIANGLES => {},
4559            _ => {
4560                self.base.webgl_error(InvalidEnum);
4561                return;
4562            },
4563        };
4564        let current_tf = match self.current_transform_feedback.get() {
4565            Some(current_tf) => current_tf,
4566            None => {
4567                self.base.webgl_error(InvalidOperation);
4568                return;
4569            },
4570        };
4571        if current_tf.is_active() {
4572            self.base.webgl_error(InvalidOperation);
4573            return;
4574        };
4575        let program = match self.base.current_program() {
4576            Some(program) => program,
4577            None => {
4578                self.base.webgl_error(InvalidOperation);
4579                return;
4580            },
4581        };
4582        if !program.is_linked() || program.transform_feedback_varyings_length() == 0 {
4583            self.base.webgl_error(InvalidOperation);
4584            return;
4585        };
4586        current_tf.begin(&self.base, primitiveMode);
4587    }
4588
4589    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.15>
4590    fn EndTransformFeedback(&self) {
4591        if let Some(current_tf) = self.current_transform_feedback.get() {
4592            if !current_tf.is_active() {
4593                self.base.webgl_error(InvalidOperation);
4594                return;
4595            }
4596            current_tf.end(&self.base);
4597        }
4598    }
4599
4600    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.15>
4601    fn ResumeTransformFeedback(&self) {
4602        if let Some(current_tf) = self.current_transform_feedback.get() {
4603            if !current_tf.is_active() || !current_tf.is_paused() {
4604                self.base.webgl_error(InvalidOperation);
4605                return;
4606            }
4607            current_tf.resume(&self.base);
4608        }
4609    }
4610
4611    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.15>
4612    fn PauseTransformFeedback(&self) {
4613        if let Some(current_tf) = self.current_transform_feedback.get() {
4614            if !current_tf.is_active() || current_tf.is_paused() {
4615                self.base.webgl_error(InvalidOperation);
4616                return;
4617            }
4618            current_tf.pause(&self.base);
4619        }
4620    }
4621
4622    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.15>
4623    #[expect(non_snake_case)]
4624    fn TransformFeedbackVaryings(
4625        &self,
4626        program: &WebGLProgram,
4627        varyings: Vec<DOMString>,
4628        bufferMode: u32,
4629    ) {
4630        // Spec: If program was generated by a different WebGL2RenderingContext
4631        // than this one, generates an INVALID_OPERATION error.
4632        if let Err(error) = self.base.validate_ownership(program) {
4633            self.base.webgl_error(error);
4634            return;
4635        }
4636        if let Err(error) = program.validate() {
4637            return self.base.webgl_error(error);
4638        }
4639        let strs = varyings
4640            .iter()
4641            .map(|name| String::from(name.to_owned()))
4642            .collect::<Vec<String>>();
4643        match bufferMode {
4644            constants::INTERLEAVED_ATTRIBS => {
4645                self.base
4646                    .send_command(WebGLCommand::TransformFeedbackVaryings(
4647                        program.id(),
4648                        strs,
4649                        bufferMode,
4650                    ));
4651            },
4652            constants::SEPARATE_ATTRIBS => {
4653                let max_tf_sp_att =
4654                    self.base.limits().max_transform_feedback_separate_attribs as usize;
4655                if strs.len() >= max_tf_sp_att {
4656                    self.base.webgl_error(InvalidValue);
4657                    return;
4658                }
4659                self.base
4660                    .send_command(WebGLCommand::TransformFeedbackVaryings(
4661                        program.id(),
4662                        strs,
4663                        bufferMode,
4664                    ));
4665            },
4666            _ => self.base.webgl_error(InvalidEnum),
4667        }
4668    }
4669
4670    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.15>
4671    fn GetTransformFeedbackVarying(
4672        &self,
4673        cx: &mut JSContext,
4674        program: &WebGLProgram,
4675        index: u32,
4676    ) -> Option<DomRoot<WebGLActiveInfo>> {
4677        // Spec: If program was generated by a different WebGL2RenderingContext,
4678        // generate INVALID_OPERATION and return null.
4679        if let Err(error) = self.base.validate_ownership(program) {
4680            self.base.webgl_error(error);
4681            return None;
4682        }
4683
4684        if let Err(error) = program.validate() {
4685            self.base.webgl_error(error);
4686            return None;
4687        }
4688
4689        if index >= program.transform_feedback_varyings_length() as u32 {
4690            self.base.webgl_error(InvalidValue);
4691            return None;
4692        }
4693
4694        let (sender, receiver) = webgl_channel().unwrap();
4695        self.base
4696            .send_command(WebGLCommand::GetTransformFeedbackVarying(
4697                program.id(),
4698                index,
4699                sender,
4700            ));
4701        let (size, ty, name) = receiver.recv().unwrap();
4702        Some(WebGLActiveInfo::new(
4703            cx,
4704            self.base.global().as_window(),
4705            size,
4706            ty,
4707            DOMString::from(name),
4708        ))
4709    }
4710
4711    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.16>
4712    fn BindBufferBase(&self, target: u32, index: u32, buffer: Option<&WebGLBuffer>) {
4713        let (generic_slot, indexed_bindings) = match target {
4714            constants::TRANSFORM_FEEDBACK_BUFFER => (
4715                &self.bound_transform_feedback_buffer,
4716                &self.indexed_transform_feedback_buffer_bindings,
4717            ),
4718            constants::UNIFORM_BUFFER => (
4719                &self.bound_uniform_buffer,
4720                &self.indexed_uniform_buffer_bindings,
4721            ),
4722            _ => return self.base.webgl_error(InvalidEnum),
4723        };
4724        let indexed_binding = match indexed_bindings.get(index as usize) {
4725            Some(slot) => slot,
4726            None => return self.base.webgl_error(InvalidValue),
4727        };
4728
4729        if let Some(buffer) = buffer {
4730            if let Err(error) = self.base.validate_ownership(buffer) {
4731                return self.base.webgl_error(error);
4732            }
4733
4734            if buffer.is_marked_for_deletion() {
4735                return self.base.webgl_error(InvalidOperation);
4736            }
4737            if let Err(error) = buffer.set_target_maybe(target) {
4738                return self.base.webgl_error(error);
4739            }
4740
4741            // for both the generic and the indexed bindings
4742            buffer.increment_attached_counter();
4743            buffer.increment_attached_counter();
4744        }
4745
4746        self.base.send_command(WebGLCommand::BindBufferBase(
4747            target,
4748            index,
4749            buffer.map(|b| b.id()),
4750        ));
4751
4752        for slot in &[generic_slot, &indexed_binding.buffer] {
4753            if let Some(old) = slot.get() {
4754                old.decrement_attached_counter(Operation::Infallible);
4755            }
4756            slot.set(buffer);
4757        }
4758        indexed_binding.start.set(0);
4759        indexed_binding.size.set(0);
4760    }
4761
4762    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.16>
4763    fn BindBufferRange(
4764        &self,
4765        target: u32,
4766        index: u32,
4767        buffer: Option<&WebGLBuffer>,
4768        offset: i64,
4769        size: i64,
4770    ) {
4771        let (generic_slot, indexed_bindings) = match target {
4772            constants::TRANSFORM_FEEDBACK_BUFFER => (
4773                &self.bound_transform_feedback_buffer,
4774                &self.indexed_transform_feedback_buffer_bindings,
4775            ),
4776            constants::UNIFORM_BUFFER => (
4777                &self.bound_uniform_buffer,
4778                &self.indexed_uniform_buffer_bindings,
4779            ),
4780            _ => return self.base.webgl_error(InvalidEnum),
4781        };
4782        let indexed_binding = match indexed_bindings.get(index as usize) {
4783            Some(slot) => slot,
4784            None => return self.base.webgl_error(InvalidValue),
4785        };
4786
4787        if offset < 0 || size < 0 {
4788            return self.base.webgl_error(InvalidValue);
4789        }
4790        if buffer.is_some() && size == 0 {
4791            return self.base.webgl_error(InvalidValue);
4792        }
4793
4794        match target {
4795            constants::TRANSFORM_FEEDBACK_BUFFER => {
4796                if size % 4 != 0 && offset % 4 != 0 {
4797                    return self.base.webgl_error(InvalidValue);
4798                }
4799            },
4800            constants::UNIFORM_BUFFER => {
4801                let offset_alignment = self.base.limits().uniform_buffer_offset_alignment;
4802                if offset % offset_alignment as i64 != 0 {
4803                    return self.base.webgl_error(InvalidValue);
4804                }
4805            },
4806            _ => unreachable!(),
4807        }
4808
4809        if let Some(buffer) = buffer {
4810            if let Err(error) = self.base.validate_ownership(buffer) {
4811                return self.base.webgl_error(error);
4812            }
4813
4814            if buffer.is_marked_for_deletion() {
4815                return self.base.webgl_error(InvalidOperation);
4816            }
4817            if let Err(error) = buffer.set_target_maybe(target) {
4818                return self.base.webgl_error(error);
4819            }
4820
4821            // for both the generic and the indexed bindings
4822            buffer.increment_attached_counter();
4823            buffer.increment_attached_counter();
4824        }
4825
4826        self.base.send_command(WebGLCommand::BindBufferRange(
4827            target,
4828            index,
4829            buffer.map(|b| b.id()),
4830            offset,
4831            size,
4832        ));
4833
4834        for slot in &[generic_slot, &indexed_binding.buffer] {
4835            if let Some(old) = slot.get() {
4836                old.decrement_attached_counter(Operation::Infallible);
4837            }
4838            slot.set(buffer);
4839        }
4840        indexed_binding.start.set(offset);
4841        indexed_binding.size.set(size);
4842    }
4843
4844    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.16>
4845    fn GetUniformIndices(&self, program: &WebGLProgram, names: Vec<DOMString>) -> Option<Vec<u32>> {
4846        if let Err(error) = self.base.validate_ownership(program) {
4847            self.base.webgl_error(error);
4848            return None;
4849        }
4850        let indices = match program.get_uniform_indices(names) {
4851            Ok(indices) => indices,
4852            Err(error) => {
4853                self.base.webgl_error(error);
4854                return None;
4855            },
4856        };
4857        Some(indices)
4858    }
4859
4860    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.16>
4861    fn GetActiveUniforms(
4862        &self,
4863        cx: &mut JSContext,
4864        program: &WebGLProgram,
4865        indices: Vec<u32>,
4866        pname: u32,
4867        mut rval: MutableHandleValue,
4868    ) {
4869        if let Err(error) = self.base.validate_ownership(program) {
4870            self.base.webgl_error(error);
4871            return rval.set(NullValue());
4872        }
4873        let values = match program.get_active_uniforms(indices, pname) {
4874            Ok(values) => values,
4875            Err(error) => {
4876                self.base.webgl_error(error);
4877                return rval.set(NullValue());
4878            },
4879        };
4880
4881        match pname {
4882            constants::UNIFORM_SIZE |
4883            constants::UNIFORM_TYPE |
4884            constants::UNIFORM_BLOCK_INDEX |
4885            constants::UNIFORM_OFFSET |
4886            constants::UNIFORM_ARRAY_STRIDE |
4887            constants::UNIFORM_MATRIX_STRIDE => {
4888                values.to_jsval(cx, rval);
4889            },
4890            constants::UNIFORM_IS_ROW_MAJOR => {
4891                let values = values.iter().map(|&v| v != 0).collect::<Vec<_>>();
4892                values.to_jsval(cx, rval);
4893            },
4894            _ => unreachable!(),
4895        }
4896    }
4897
4898    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.16>
4899    fn GetUniformBlockIndex(&self, program: &WebGLProgram, block_name: DOMString) -> u32 {
4900        if let Err(error) = self.base.validate_ownership(program) {
4901            self.base.webgl_error(error);
4902            return constants::INVALID_INDEX;
4903        }
4904        match program.get_uniform_block_index(block_name) {
4905            Ok(index) => index,
4906            Err(error) => {
4907                self.base.webgl_error(error);
4908                constants::INVALID_INDEX
4909            },
4910        }
4911    }
4912
4913    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.16>
4914    fn GetActiveUniformBlockParameter(
4915        &self,
4916        cx: &mut JSContext,
4917        program: &WebGLProgram,
4918        block_index: u32,
4919        pname: u32,
4920        mut retval: MutableHandleValue,
4921    ) {
4922        if let Err(error) = self.base.validate_ownership(program) {
4923            self.base.webgl_error(error);
4924            return retval.set(NullValue());
4925        }
4926        let values = match program.get_active_uniform_block_parameter(block_index, pname) {
4927            Ok(values) => values,
4928            Err(error) => {
4929                self.base.webgl_error(error);
4930                return retval.set(NullValue());
4931            },
4932        };
4933        match pname {
4934            constants::UNIFORM_BLOCK_BINDING |
4935            constants::UNIFORM_BLOCK_DATA_SIZE |
4936            constants::UNIFORM_BLOCK_ACTIVE_UNIFORMS => {
4937                assert!(values.len() == 1);
4938                retval.set(UInt32Value(values[0] as u32))
4939            },
4940            constants::UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES => {
4941                let values = values.iter().map(|&v| v as u32).collect::<Vec<_>>();
4942                rooted!(&in(cx) let mut result = ptr::null_mut::<JSObject>());
4943                create_buffer_source::<Uint32>(cx, &values, result.handle_mut()).unwrap();
4944                retval.set(ObjectValue(result.get()))
4945            },
4946            constants::UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER |
4947            constants::UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER => {
4948                assert!(values.len() == 1);
4949                retval.set(BooleanValue(values[0] != 0))
4950            },
4951            _ => unreachable!(),
4952        }
4953    }
4954
4955    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.16>
4956    fn GetActiveUniformBlockName(
4957        &self,
4958        program: &WebGLProgram,
4959        block_index: u32,
4960    ) -> Option<DOMString> {
4961        if let Err(error) = self.base.validate_ownership(program) {
4962            self.base.webgl_error(error);
4963            return None;
4964        }
4965        let name = match program.get_active_uniform_block_name(block_index) {
4966            Ok(name) => name,
4967            Err(error) => {
4968                self.base.webgl_error(error);
4969                return None;
4970            },
4971        };
4972        Some(DOMString::from(name))
4973    }
4974
4975    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.16>
4976    fn UniformBlockBinding(&self, program: &WebGLProgram, block_index: u32, block_binding: u32) {
4977        if let Err(error) = self.base.validate_ownership(program) {
4978            return self.base.webgl_error(error);
4979        }
4980
4981        if block_binding >= self.base.limits().max_uniform_buffer_bindings {
4982            return self.base.webgl_error(InvalidValue);
4983        }
4984
4985        if let Err(error) = program.bind_uniform_block(block_index, block_binding) {
4986            self.base.webgl_error(error);
4987        }
4988    }
4989
4990    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.11>
4991    fn ClearBufferfv(
4992        &self,
4993        buffer: u32,
4994        draw_buffer: i32,
4995        values: Float32ArrayOrUnrestrictedFloatSequence,
4996        src_offset: u32,
4997    ) {
4998        let array = match values {
4999            Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => {
5000                v.to_vec().unwrap_or_default()
5001            },
5002            Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
5003        };
5004        self.clear_buffer::<f32>(
5005            buffer,
5006            draw_buffer,
5007            &[constants::COLOR, constants::DEPTH],
5008            src_offset,
5009            array,
5010            WebGLCommand::ClearBufferfv,
5011        )
5012    }
5013
5014    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.11>
5015    fn ClearBufferiv(
5016        &self,
5017        buffer: u32,
5018        draw_buffer: i32,
5019        values: Int32ArrayOrLongSequence,
5020        src_offset: u32,
5021    ) {
5022        let array = match values {
5023            Int32ArrayOrLongSequence::Int32Array(v) => v.to_vec().unwrap_or_default(),
5024            Int32ArrayOrLongSequence::LongSequence(v) => v,
5025        };
5026        self.clear_buffer::<i32>(
5027            buffer,
5028            draw_buffer,
5029            &[constants::COLOR, constants::STENCIL],
5030            src_offset,
5031            array,
5032            WebGLCommand::ClearBufferiv,
5033        )
5034    }
5035
5036    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.11>
5037    fn ClearBufferuiv(
5038        &self,
5039        buffer: u32,
5040        draw_buffer: i32,
5041        values: Uint32ArrayOrUnsignedLongSequence,
5042        src_offset: u32,
5043    ) {
5044        let array = match values {
5045            Uint32ArrayOrUnsignedLongSequence::Uint32Array(v) => v.to_vec().unwrap_or_default(),
5046            Uint32ArrayOrUnsignedLongSequence::UnsignedLongSequence(v) => v,
5047        };
5048        self.clear_buffer::<u32>(
5049            buffer,
5050            draw_buffer,
5051            &[constants::COLOR],
5052            src_offset,
5053            array,
5054            WebGLCommand::ClearBufferuiv,
5055        )
5056    }
5057
5058    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.11>
5059    fn ClearBufferfi(&self, buffer: u32, draw_buffer: i32, depth: f32, stencil: i32) {
5060        if buffer != constants::DEPTH_STENCIL {
5061            return self.base.webgl_error(InvalidEnum);
5062        }
5063
5064        if let Err(error) = self.clearbuffer_array_size(buffer, draw_buffer) {
5065            return self.base.webgl_error(error);
5066        }
5067
5068        self.base.send_command(WebGLCommand::ClearBufferfi(
5069            buffer,
5070            draw_buffer,
5071            depth,
5072            stencil,
5073        ));
5074        self.mark_as_dirty();
5075    }
5076
5077    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.4>
5078    fn InvalidateFramebuffer(&self, target: u32, attachments: Vec<u32>) {
5079        if !self.valid_fb_attachment_values(target, &attachments) {
5080            return;
5081        }
5082
5083        self.base
5084            .send_command(WebGLCommand::InvalidateFramebuffer(target, attachments))
5085    }
5086
5087    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.4>
5088    fn InvalidateSubFramebuffer(
5089        &self,
5090        target: u32,
5091        attachments: Vec<u32>,
5092        x: i32,
5093        y: i32,
5094        width: i32,
5095        height: i32,
5096    ) {
5097        if !self.valid_fb_attachment_values(target, &attachments) {
5098            return;
5099        }
5100
5101        if width < 0 || height < 0 {
5102            return self.base.webgl_error(InvalidValue);
5103        }
5104
5105        self.base
5106            .send_command(WebGLCommand::InvalidateSubFramebuffer(
5107                target,
5108                attachments,
5109                x,
5110                y,
5111                width,
5112                height,
5113            ))
5114    }
5115
5116    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.4>
5117    fn FramebufferTextureLayer(
5118        &self,
5119        target: u32,
5120        attachment: u32,
5121        texture: Option<&WebGLTexture>,
5122        level: i32,
5123        layer: i32,
5124    ) {
5125        if let Some(tex) = texture &&
5126            let Err(error) = self.base.validate_ownership(tex)
5127        {
5128            return self.base.webgl_error(error);
5129        }
5130
5131        let fb_slot = match target {
5132            constants::FRAMEBUFFER | constants::DRAW_FRAMEBUFFER => {
5133                self.base.get_draw_framebuffer_slot()
5134            },
5135            constants::READ_FRAMEBUFFER => self.base.get_read_framebuffer_slot(),
5136            _ => return self.base.webgl_error(InvalidEnum),
5137        };
5138
5139        match fb_slot.get() {
5140            Some(fb) => {
5141                if let Err(error) = fb.texture_layer(attachment, texture, level, layer) {
5142                    self.base.webgl_error(error);
5143                }
5144            },
5145            None => self.base.webgl_error(InvalidOperation),
5146        }
5147    }
5148
5149    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.5>
5150    fn GetInternalformatParameter(
5151        &self,
5152        cx: &mut JSContext,
5153        target: u32,
5154        internal_format: u32,
5155        pname: u32,
5156        mut retval: MutableHandleValue,
5157    ) {
5158        if target != constants::RENDERBUFFER {
5159            self.base.webgl_error(InvalidEnum);
5160            return retval.set(NullValue());
5161        }
5162
5163        let internal_format = match renderbuffer_format(&self.base, internal_format) {
5164            Ok(internal_format) => internal_format,
5165            Err(error) => {
5166                self.base.webgl_error(error);
5167                return retval.set(NullValue());
5168            },
5169        };
5170
5171        let param = match InternalFormatParameter::from_u32(pname) {
5172            Ok(param) => param,
5173            Err(error) => {
5174                self.base.webgl_error(error);
5175                return retval.set(NullValue());
5176            },
5177        };
5178        match param {
5179            InternalFormatParameter::IntVec(param) => {
5180                let (sender, receiver) = webgl_channel().unwrap();
5181                self.base
5182                    .send_command(WebGLCommand::GetInternalFormatIntVec(
5183                        target,
5184                        internal_format,
5185                        param,
5186                        sender,
5187                    ));
5188
5189                rooted!(&in(cx) let mut rval = ptr::null_mut::<JSObject>());
5190                create_buffer_source::<Int32>(cx, &receiver.recv().unwrap(), rval.handle_mut())
5191                    .unwrap();
5192                retval.set(ObjectValue(rval.get()))
5193            },
5194        }
5195    }
5196
5197    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.5>
5198    fn RenderbufferStorageMultisample(
5199        &self,
5200        target: u32,
5201        samples: i32,
5202        internal_format: u32,
5203        width: i32,
5204        height: i32,
5205    ) {
5206        self.base
5207            .renderbuffer_storage(target, samples, internal_format, width, height)
5208    }
5209
5210    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.4>
5211    fn ReadBuffer(&self, src: u32) {
5212        match src {
5213            constants::BACK | constants::NONE => {},
5214            _ if self.base.valid_color_attachment_enum(src) => {},
5215            _ => return self.base.webgl_error(InvalidEnum),
5216        }
5217
5218        if let Some(fb) = self.base.get_read_framebuffer_slot().get() {
5219            if let Err(error) = fb.set_read_buffer(src) {
5220                self.base.webgl_error(error);
5221            }
5222        } else {
5223            match src {
5224                constants::NONE | constants::BACK => {},
5225                _ => return self.base.webgl_error(InvalidOperation),
5226            }
5227
5228            self.default_fb_readbuffer.set(src);
5229            self.base.send_command(WebGLCommand::ReadBuffer(src));
5230        }
5231    }
5232
5233    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.11>
5234    fn DrawBuffers(&self, buffers: Vec<u32>) {
5235        if let Some(fb) = self.base.get_draw_framebuffer_slot().get() {
5236            if let Err(error) = fb.set_draw_buffers(buffers) {
5237                self.base.webgl_error(error);
5238            }
5239        } else {
5240            if buffers.len() != 1 {
5241                return self.base.webgl_error(InvalidOperation);
5242            }
5243
5244            match buffers[0] {
5245                constants::NONE | constants::BACK => {},
5246                _ => return self.base.webgl_error(InvalidOperation),
5247            }
5248
5249            self.default_fb_drawbuffer.set(buffers[0]);
5250            self.base.send_command(WebGLCommand::DrawBuffers(buffers));
5251        }
5252    }
5253
5254    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.6>
5255    fn TexStorage2D(
5256        &self,
5257        target: u32,
5258        levels: i32,
5259        internal_format: u32,
5260        width: i32,
5261        height: i32,
5262    ) {
5263        self.tex_storage(2, target, levels, internal_format, width, height, 1)
5264    }
5265
5266    /// <https://www.khronos.org/registry/webgl/specs/latest/2.0/#4.7.6>
5267    fn TexStorage3D(
5268        &self,
5269        target: u32,
5270        levels: i32,
5271        internal_format: u32,
5272        width: i32,
5273        height: i32,
5274        depth: i32,
5275    ) {
5276        self.tex_storage(3, target, levels, internal_format, width, height, depth)
5277    }
5278
5279    /// <https://immersive-web.github.io/webxr/#dom-webglrenderingcontextbase-makexrcompatible>
5280    #[cfg(feature = "webxr")]
5281    fn MakeXRCompatible(&self, cx: &mut js::context::JSContext) -> RootedPromise {
5282        // XXXManishearth Fill in with compatibility checks when rust-webxr supports this
5283        Promise::new_resolved(cx, &self.global(), ())
5284    }
5285}
5286
5287impl WebGL2RenderingContextHelpers for WebGL2RenderingContext {
5288    fn is_webgl2_enabled(cx: &mut js::context::JSContext, global: HandleObject) -> bool {
5289        Self::is_webgl2_enabled(cx, global)
5290    }
5291}
5292
5293/// Returns the component type of a signed or unsigned integer format.
5294fn blit_integer_type(format: u32) -> Option<TexComponentType> {
5295    use TexComponentType::{SignedInt, UnsignedInt};
5296    TexFormat::from_gl_constant(format)?
5297        .component_type()
5298        .filter(|ty| matches!(ty, SignedInt | UnsignedInt))
5299}