Skip to main content

script/dom/webgl/
webglrenderingcontext.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::rc::Rc;
7use std::{cmp, ptr};
8
9#[cfg(feature = "webgl_backtrace")]
10use backtrace::Backtrace;
11use bitflags::bitflags;
12use dom_struct::dom_struct;
13use euclid::default::{Point2D, Rect, Size2D};
14use js::context::{JSContext, NoGC};
15use js::jsapi::{JSObject, Type};
16use js::jsval::{BooleanValue, DoubleValue, Int32Value, NullValue, ObjectValue, UInt32Value};
17use js::rust::{CustomAutoRooterGuard, MutableHandleObject, MutableHandleValue};
18use js::typedarray::{
19    ArrayBufferView, CreateWith, Float32, Float32Array, Int32, Int32Array, TypedArray,
20    TypedArrayElementCreator, Uint32Array,
21};
22use pixels::{self, Alpha, PixelFormat, Snapshot, SnapshotPixelFormat};
23use script_bindings::cell::{DomRefCell, Ref, RefMut};
24use script_bindings::conversions::SafeToJSValConvertible;
25use script_bindings::reflector::{
26    AssociatedMemory, Reflector, reflect_weak_referenceable_dom_object,
27};
28use serde::{Deserialize, Serialize};
29use servo_base::generic_channel::GenericSharedMemory;
30use servo_base::{Epoch, generic_channel};
31use servo_canvas_traits::webgl::WebGLError::*;
32use servo_canvas_traits::webgl::{
33    AlphaTreatment, GLContextAttributes, GLLimits, GlType, Parameter, SizedDataType, TexDataType,
34    TexFormat, TexParameter, WebGLCommand, WebGLCommandBacktrace, WebGLContextId, WebGLError,
35    WebGLFramebufferBindingRequest, WebGLMsg, WebGLMsgSender, WebGLProgramId, WebGLResult,
36    WebGLSLVersion, WebGLVersion, YAxisTreatment, webgl_channel,
37};
38use servo_config::pref;
39use webrender_api::ImageKey;
40
41use crate::canvas_context::{CanvasContext, HTMLCanvasElementOrOffscreenCanvas};
42use crate::dom::bindings::buffer_source::get_buffer_source_slice;
43use crate::dom::bindings::codegen::Bindings::ANGLEInstancedArraysBinding::ANGLEInstancedArraysConstants;
44use crate::dom::bindings::codegen::Bindings::EXTBlendMinmaxBinding::EXTBlendMinmaxConstants;
45use crate::dom::bindings::codegen::Bindings::OESVertexArrayObjectBinding::OESVertexArrayObjectConstants;
46use crate::dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants;
47use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::{
48    TexImageSource, WebGLContextAttributes, WebGLRenderingContextConstants as constants,
49    WebGLRenderingContextMethods,
50};
51use crate::dom::bindings::codegen::UnionTypes::{
52    ArrayBufferViewOrArrayBuffer, Float32ArrayOrUnrestrictedFloatSequence,
53    HTMLCanvasElementOrOffscreenCanvas as RootedHTMLCanvasElementOrOffscreenCanvas,
54    Int32ArrayOrLongSequence,
55};
56use crate::dom::bindings::conversions::DerivedFrom;
57use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
58use crate::dom::bindings::inheritance::Castable;
59use crate::dom::bindings::reflector::DomGlobal;
60use crate::dom::bindings::root::{DomOnceCell, DomRoot, MutNullableDom};
61use crate::dom::bindings::str::DOMString;
62use crate::dom::event::{Event, EventBubbles, EventCancelable};
63#[cfg(feature = "webgl_backtrace")]
64use crate::dom::globalscope::GlobalScope;
65use crate::dom::node::NodeTraits;
66#[cfg(feature = "webxr")]
67use crate::dom::promise::Promise;
68use crate::dom::webgl::extensions::WebGLExtensions;
69use crate::dom::webgl::validations::WebGLValidator;
70use crate::dom::webgl::validations::tex_image_2d::{
71    CommonCompressedTexImage2DValidatorResult, CommonTexImage2DValidator,
72    CommonTexImage2DValidatorResult, CompressedTexImage2DValidator,
73    CompressedTexSubImage2DValidator, TexImage2DValidator, TexImage2DValidatorResult,
74};
75use crate::dom::webgl::validations::types::TexImageTarget;
76use crate::dom::webgl::vertexarrayobject::VertexAttribData;
77use crate::dom::webgl::webglactiveinfo::WebGLActiveInfo;
78use crate::dom::webgl::webglbuffer::WebGLBuffer;
79use crate::dom::webgl::webglcontextevent::WebGLContextEvent;
80use crate::dom::webgl::webglframebuffer::{
81    CompleteForRendering, WebGLFramebuffer, WebGLFramebufferAttachmentRoot,
82};
83use crate::dom::webgl::webglobject::WebGLObject;
84use crate::dom::webgl::webglprogram::WebGLProgram;
85use crate::dom::webgl::webglrenderbuffer::WebGLRenderbuffer;
86use crate::dom::webgl::webglshader::WebGLShader;
87use crate::dom::webgl::webglshaderprecisionformat::WebGLShaderPrecisionFormat;
88use crate::dom::webgl::webgltexture::{TexParameterValue, WebGLTexture};
89use crate::dom::webgl::webgluniformlocation::WebGLUniformLocation;
90use crate::dom::webgl::webglvertexarrayobject::WebGLVertexArrayObject;
91use crate::dom::webgl::webglvertexarrayobjectoes::WebGLVertexArrayObjectOES;
92use crate::dom::window::Window;
93
94fn has_invalid_blend_constants(arg1: u32, arg2: u32) -> bool {
95    match (arg1, arg2) {
96        (constants::CONSTANT_COLOR, constants::CONSTANT_ALPHA) => true,
97        (constants::ONE_MINUS_CONSTANT_COLOR, constants::ONE_MINUS_CONSTANT_ALPHA) => true,
98        (constants::ONE_MINUS_CONSTANT_COLOR, constants::CONSTANT_ALPHA) => true,
99        (constants::CONSTANT_COLOR, constants::ONE_MINUS_CONSTANT_ALPHA) => true,
100        (_, _) => false,
101    }
102}
103
104pub(crate) fn uniform_get<T, F>(triple: (&WebGLRenderingContext, WebGLProgramId, i32), f: F) -> T
105where
106    F: FnOnce(WebGLProgramId, i32, generic_channel::GenericSender<T>) -> WebGLCommand,
107    T: for<'de> Deserialize<'de> + Serialize,
108{
109    let (sender, receiver) = webgl_channel().unwrap();
110    triple.0.send_command(f(triple.1, triple.2, sender));
111    receiver.recv().unwrap()
112}
113
114#[expect(unsafe_code)]
115pub(crate) unsafe fn uniform_typed<T>(
116    cx: &mut JSContext,
117    value: &[T::Element],
118    mut retval: MutableHandleValue,
119) where
120    T: TypedArrayElementCreator,
121{
122    rooted!(&in(cx) let mut rval = ptr::null_mut::<JSObject>());
123    unsafe {
124        <TypedArray<T, *mut JSObject>>::create(
125            cx.raw_cx(),
126            CreateWith::Slice(value),
127            rval.handle_mut(),
128        )
129    }
130    .unwrap();
131    retval.set(ObjectValue(rval.get()));
132}
133
134/// Set of bitflags for texture unpacking (texImage2d, etc...)
135#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
136pub(crate) struct TextureUnpacking(u8);
137
138bitflags! {
139    impl TextureUnpacking: u8 {
140        const FLIP_Y_AXIS = 0x01;
141        const PREMULTIPLY_ALPHA = 0x02;
142        const CONVERT_COLORSPACE = 0x04;
143    }
144}
145
146#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
147pub(crate) enum VertexAttrib {
148    Float(f32, f32, f32, f32),
149    Int(i32, i32, i32, i32),
150    Uint(u32, u32, u32, u32),
151}
152
153#[derive(Clone, Copy, Debug)]
154pub(crate) enum Operation {
155    Fallible,
156    Infallible,
157}
158
159#[derive(JSTraceable, MallocSizeOf)]
160struct DroppableWebGLRenderingContext {
161    #[no_trace]
162    webgl_sender: WebGLMsgSender,
163}
164
165impl Drop for DroppableWebGLRenderingContext {
166    fn drop(&mut self) {
167        let _ = self.webgl_sender.send_remove();
168    }
169}
170
171#[dom_struct(associated_memory)]
172pub(crate) struct WebGLRenderingContext {
173    reflector_: Reflector<AssociatedMemory>,
174    #[no_trace]
175    webgl_version: WebGLVersion,
176    #[no_trace]
177    glsl_version: WebGLSLVersion,
178    #[ignore_malloc_size_of = "Defined in surfman"]
179    #[no_trace]
180    limits: GLLimits,
181    canvas: HTMLCanvasElementOrOffscreenCanvas,
182    #[ignore_malloc_size_of = "Defined in servo_canvas_traits"]
183    #[no_trace]
184    last_error: Cell<Option<WebGLError>>,
185    texture_packing_alignment: Cell<u8>,
186    texture_unpacking_settings: Cell<TextureUnpacking>,
187    // TODO(nox): Should be Cell<u8>.
188    texture_unpacking_alignment: Cell<u32>,
189    bound_draw_framebuffer: MutNullableDom<WebGLFramebuffer>,
190    // TODO(mmatyas): This was introduced in WebGL2, but listed here because it's used by
191    // Textures and Renderbuffers, but such WebGLObjects have access only to the GL1 context.
192    bound_read_framebuffer: MutNullableDom<WebGLFramebuffer>,
193    bound_renderbuffer: MutNullableDom<WebGLRenderbuffer>,
194    bound_buffer_array: MutNullableDom<WebGLBuffer>,
195    current_program: MutNullableDom<WebGLProgram>,
196    current_vertex_attribs: DomRefCell<Box<[VertexAttrib]>>,
197    #[ignore_malloc_size_of = "Because it's small"]
198    current_scissor: Cell<(i32, i32, u32, u32)>,
199    #[ignore_malloc_size_of = "Because it's small"]
200    current_clear_color: Cell<(f32, f32, f32, f32)>,
201    #[no_trace]
202    size: Cell<Size2D<u32>>,
203    extension_manager: WebGLExtensions,
204    capabilities: Capabilities,
205    default_vao: DomOnceCell<WebGLVertexArrayObjectOES>,
206    current_vao: MutNullableDom<WebGLVertexArrayObjectOES>,
207    default_vao_webgl2: DomOnceCell<WebGLVertexArrayObject>,
208    current_vao_webgl2: MutNullableDom<WebGLVertexArrayObject>,
209    textures: Textures,
210    #[no_trace]
211    api_type: GlType,
212    droppable: DroppableWebGLRenderingContext,
213}
214
215impl WebGLRenderingContext {
216    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
217    pub(crate) fn new_inherited(
218        window: &Window,
219        canvas: HTMLCanvasElementOrOffscreenCanvas,
220        webgl_version: WebGLVersion,
221        size: Size2D<u32>,
222        attrs: GLContextAttributes,
223    ) -> Result<WebGLRenderingContext, String> {
224        if pref!(webgl_testing_context_creation_error) {
225            return Err("WebGL context creation error forced by pref `webgl.testing.context_creation_error`".into());
226        }
227
228        let webgl_chan = match window.webgl_chan() {
229            Some(chan) => chan,
230            None => return Err("WebGL initialization failed early on".into()),
231        };
232
233        let (sender, receiver) = webgl_channel().unwrap();
234        webgl_chan
235            .send(WebGLMsg::CreateContext(
236                window.webview_id().into(),
237                webgl_version,
238                size,
239                attrs,
240                sender,
241            ))
242            .unwrap();
243        let result = receiver.recv().unwrap();
244
245        result.map(|ctx_data| {
246            let max_combined_texture_image_units = ctx_data.limits.max_combined_texture_image_units;
247            let max_vertex_attribs = ctx_data.limits.max_vertex_attribs as usize;
248            Self {
249                reflector_: Reflector::new(),
250                webgl_version,
251                glsl_version: ctx_data.glsl_version,
252                limits: ctx_data.limits,
253                canvas,
254                last_error: Cell::new(None),
255                texture_packing_alignment: Cell::new(4),
256                texture_unpacking_settings: Cell::new(TextureUnpacking::CONVERT_COLORSPACE),
257                texture_unpacking_alignment: Cell::new(4),
258                bound_draw_framebuffer: MutNullableDom::new(None),
259                bound_read_framebuffer: MutNullableDom::new(None),
260                bound_buffer_array: MutNullableDom::new(None),
261                bound_renderbuffer: MutNullableDom::new(None),
262                current_program: MutNullableDom::new(None),
263                current_vertex_attribs: DomRefCell::new(
264                    vec![VertexAttrib::Float(0f32, 0f32, 0f32, 1f32); max_vertex_attribs].into(),
265                ),
266                current_scissor: Cell::new((0, 0, size.width, size.height)),
267                // FIXME(#21718) The backend is allowed to choose a size smaller than
268                // what was requested
269                size: Cell::new(size),
270                current_clear_color: Cell::new((0.0, 0.0, 0.0, 0.0)),
271                extension_manager: WebGLExtensions::new(
272                    webgl_version,
273                    ctx_data.api_type,
274                    ctx_data.glsl_version,
275                ),
276                capabilities: Default::default(),
277                default_vao: Default::default(),
278                current_vao: Default::default(),
279                default_vao_webgl2: Default::default(),
280                current_vao_webgl2: Default::default(),
281                textures: Textures::new(max_combined_texture_image_units),
282                api_type: ctx_data.api_type,
283                droppable: DroppableWebGLRenderingContext {
284                    webgl_sender: ctx_data.sender,
285                },
286            }
287        })
288    }
289
290    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
291    pub(crate) fn new(
292        cx: &mut JSContext,
293        window: &Window,
294        canvas: &RootedHTMLCanvasElementOrOffscreenCanvas,
295        webgl_version: WebGLVersion,
296        size: Size2D<u32>,
297        attrs: GLContextAttributes,
298    ) -> Option<DomRoot<WebGLRenderingContext>> {
299        match WebGLRenderingContext::new_inherited(
300            window,
301            HTMLCanvasElementOrOffscreenCanvas::from(canvas),
302            webgl_version,
303            size,
304            attrs,
305        ) {
306            Ok(ctx) => Some(reflect_weak_referenceable_dom_object(
307                cx,
308                Rc::new(ctx),
309                window,
310            )),
311            Err(msg) => {
312                error!("Couldn't create WebGLRenderingContext: {}", msg);
313                let event = WebGLContextEvent::new(
314                    cx,
315                    window,
316                    atom!("webglcontextcreationerror"),
317                    EventBubbles::DoesNotBubble,
318                    EventCancelable::Cancelable,
319                    DOMString::from(msg),
320                );
321                match canvas {
322                    RootedHTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(canvas) => {
323                        event.upcast::<Event>().fire(cx, canvas.upcast());
324                    },
325                    RootedHTMLCanvasElementOrOffscreenCanvas::OffscreenCanvas(canvas) => {
326                        event.upcast::<Event>().fire(cx, canvas.upcast());
327                    },
328                }
329                None
330            },
331        }
332    }
333
334    pub(crate) fn set_image_key(&self, image_key: ImageKey) {
335        self.droppable.webgl_sender.set_image_key(image_key);
336    }
337
338    pub(crate) fn update_rendering(&self, canvas_epoch: Epoch) -> bool {
339        if !self.onscreen() {
340            return false;
341        }
342
343        let global = self.global();
344        let Some(window) = global.downcast::<Window>() else {
345            return false;
346        };
347
348        window
349            .webgl_chan()
350            .expect("Where's the WebGL channel?")
351            .send(WebGLMsg::SwapBuffers(
352                vec![self.context_id()],
353                Some(canvas_epoch),
354                0, /* time */
355            ))
356            .is_ok()
357    }
358
359    pub(crate) fn webgl_version(&self) -> WebGLVersion {
360        self.webgl_version
361    }
362
363    pub(crate) fn limits(&self) -> &GLLimits {
364        &self.limits
365    }
366
367    pub(crate) fn texture_unpacking_alignment(&self) -> u32 {
368        self.texture_unpacking_alignment.get()
369    }
370
371    pub(crate) fn bound_draw_framebuffer(&self) -> Option<DomRoot<WebGLFramebuffer>> {
372        self.bound_draw_framebuffer.get()
373    }
374
375    pub(crate) fn current_vao(&self, cx: &mut JSContext) -> DomRoot<WebGLVertexArrayObjectOES> {
376        self.current_vao.or_init(|| {
377            DomRoot::from_ref(
378                self.default_vao
379                    .init_once(|| WebGLVertexArrayObjectOES::new(cx, self, None)),
380            )
381        })
382    }
383
384    pub(crate) fn current_vao_webgl2(&self, cx: &mut JSContext) -> DomRoot<WebGLVertexArrayObject> {
385        self.current_vao_webgl2.or_init(|| {
386            DomRoot::from_ref(
387                self.default_vao_webgl2
388                    .init_once(|| WebGLVertexArrayObject::new(cx, self, None)),
389            )
390        })
391    }
392
393    pub(crate) fn current_vertex_attribs(&self) -> RefMut<'_, Box<[VertexAttrib]>> {
394        self.current_vertex_attribs.borrow_mut()
395    }
396
397    #[inline]
398    pub(crate) fn sender(&self) -> &WebGLMsgSender {
399        &self.droppable.webgl_sender
400    }
401
402    #[inline]
403    pub(crate) fn send_with_fallibility(&self, command: WebGLCommand, fallibility: Operation) {
404        let result = self
405            .droppable
406            .webgl_sender
407            .send(command, capture_webgl_backtrace());
408        if matches!(fallibility, Operation::Infallible) {
409            result.expect("Operation failed");
410        }
411    }
412
413    #[inline]
414    pub(crate) fn send_command(&self, command: WebGLCommand) {
415        self.send_with_fallibility(command, Operation::Infallible);
416    }
417
418    pub(crate) fn send_command_ignored(&self, command: WebGLCommand) {
419        self.send_with_fallibility(command, Operation::Fallible);
420    }
421
422    pub(crate) fn webgl_error(&self, err: WebGLError) {
423        // TODO(emilio): Add useful debug messages to this
424        warn!(
425            "WebGL error: {:?}, previous error was {:?}",
426            err,
427            self.last_error.get()
428        );
429
430        // If an error has been detected no further errors must be
431        // recorded until `getError` has been called
432        if self.last_error.get().is_none() {
433            self.last_error.set(Some(err));
434        }
435    }
436
437    // Helper function for validating framebuffer completeness in
438    // calls touching the framebuffer.  From the GLES 2.0.25 spec,
439    // page 119:
440    //
441    //    "Effects of Framebuffer Completeness on Framebuffer
442    //     Operations
443    //
444    //     If the currently bound framebuffer is not framebuffer
445    //     complete, then it is an error to attempt to use the
446    //     framebuffer for writing or reading. This means that
447    //     rendering commands such as DrawArrays and DrawElements, as
448    //     well as commands that read the framebuffer such as
449    //     ReadPixels and CopyTexSubImage, will generate the error
450    //     INVALID_FRAMEBUFFER_OPERATION if called while the
451    //     framebuffer is not framebuffer complete."
452    //
453    // The WebGL spec mentions a couple more operations that trigger
454    // this: clear() and getParameter(IMPLEMENTATION_COLOR_READ_*).
455    pub(crate) fn validate_framebuffer(&self) -> WebGLResult<()> {
456        match self.bound_draw_framebuffer.get() {
457            Some(fb) => match fb.check_status_for_rendering() {
458                CompleteForRendering::Complete => Ok(()),
459                CompleteForRendering::Incomplete => Err(InvalidFramebufferOperation),
460                CompleteForRendering::MissingColorAttachment => Err(InvalidOperation),
461            },
462            None => Ok(()),
463        }
464    }
465
466    pub(crate) fn validate_ownership<T>(&self, object: &T) -> WebGLResult<()>
467    where
468        T: DerivedFrom<WebGLObject>,
469    {
470        let Some(context) = object.upcast().context() else {
471            return Err(WebGLError::InvalidOperation);
472        };
473        if self != &*context {
474            return Err(WebGLError::InvalidOperation);
475        }
476        Ok(())
477    }
478
479    pub(crate) fn with_location<F>(&self, location: Option<&WebGLUniformLocation>, f: F)
480    where
481        F: FnOnce(&WebGLUniformLocation) -> WebGLResult<()>,
482    {
483        let location = match location {
484            Some(loc) => loc,
485            None => return,
486        };
487        match self.current_program.get() {
488            Some(ref program)
489                if program.id() == location.program_id() &&
490                    program.link_generation() == location.link_generation() => {},
491            _ => return self.webgl_error(InvalidOperation),
492        }
493        handle_potential_webgl_error!(self, f(location));
494    }
495
496    pub(crate) fn textures(&self) -> &Textures {
497        &self.textures
498    }
499
500    fn tex_parameter(&self, target: u32, param: u32, value: TexParameterValue) {
501        let texture_slot = handle_potential_webgl_error!(
502            self,
503            self.textures
504                .active_texture_slot(target, self.webgl_version()),
505            return
506        );
507        let texture =
508            handle_potential_webgl_error!(self, texture_slot.get().ok_or(InvalidOperation), return);
509
510        if !self
511            .extension_manager
512            .is_get_tex_parameter_name_enabled(param)
513        {
514            return self.webgl_error(InvalidEnum);
515        }
516
517        handle_potential_webgl_error!(self, texture.tex_parameter(param, value), return);
518
519        // Validate non filterable TEXTURE_2D data_types
520        if target != constants::TEXTURE_2D {
521            return;
522        }
523
524        let target = TexImageTarget::Texture2D;
525        if let Some(info) = texture.image_info_for_target(&target, 0) {
526            self.validate_filterable_texture(
527                &texture,
528                target,
529                0,
530                info.internal_format(),
531                Size2D::new(info.width(), info.height()),
532                info.data_type().unwrap_or(TexDataType::UnsignedByte),
533            );
534        }
535    }
536
537    fn vertex_attrib(&self, cx: &mut JSContext, indx: u32, x: f32, y: f32, z: f32, w: f32) {
538        if indx >= self.limits.max_vertex_attribs {
539            return self.webgl_error(InvalidValue);
540        }
541
542        match self.webgl_version() {
543            WebGLVersion::WebGL1 => self
544                .current_vao(cx)
545                .set_vertex_attrib_type(indx, constants::FLOAT),
546            WebGLVersion::WebGL2 => self
547                .current_vao_webgl2(cx)
548                .set_vertex_attrib_type(indx, constants::FLOAT),
549        };
550        self.current_vertex_attribs.borrow_mut()[indx as usize] = VertexAttrib::Float(x, y, z, w);
551
552        self.send_command(WebGLCommand::VertexAttrib(indx, x, y, z, w));
553    }
554
555    pub(crate) fn get_current_framebuffer_size(&self) -> Option<(i32, i32)> {
556        match self.bound_draw_framebuffer.get() {
557            Some(fb) => fb.size(),
558
559            // The window system framebuffer is bound
560            None => Some((self.DrawingBufferWidth(), self.DrawingBufferHeight())),
561        }
562    }
563
564    pub(crate) fn get_texture_packing_alignment(&self) -> u8 {
565        self.texture_packing_alignment.get()
566    }
567
568    pub(crate) fn get_current_unpack_state(
569        &self,
570        premultiplied: Alpha,
571    ) -> (Option<AlphaTreatment>, YAxisTreatment) {
572        let settings = self.texture_unpacking_settings.get();
573        let dest_premultiplied = settings.contains(TextureUnpacking::PREMULTIPLY_ALPHA);
574
575        let alpha_treatment = match (premultiplied, dest_premultiplied) {
576            (Alpha::Premultiplied, false) => Some(AlphaTreatment::Unmultiply),
577            (Alpha::NotPremultiplied, true) => Some(AlphaTreatment::Premultiply),
578            _ => None,
579        };
580
581        let y_axis_treatment = if settings.contains(TextureUnpacking::FLIP_Y_AXIS) {
582            YAxisTreatment::Flipped
583        } else {
584            YAxisTreatment::AsIs
585        };
586
587        (alpha_treatment, y_axis_treatment)
588    }
589
590    // LINEAR filtering may be forbidden when using WebGL extensions.
591    /// <https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/>
592    fn validate_filterable_texture(
593        &self,
594        texture: &WebGLTexture,
595        target: TexImageTarget,
596        level: u32,
597        internal_format: TexFormat,
598        size: Size2D<u32>,
599        data_type: TexDataType,
600    ) -> bool {
601        if self
602            .extension_manager
603            .is_filterable(data_type.as_gl_constant()) ||
604            !texture.is_using_linear_filtering()
605        {
606            return true;
607        }
608
609        // Handle validation failed: LINEAR filtering not valid for this texture
610        // WebGL Conformance tests expect to fallback to [0, 0, 0, 255] RGBA UNSIGNED_BYTE
611        let data_type = TexDataType::UnsignedByte;
612        let expected_byte_length = size.area() * 4;
613        let mut pixels = vec![0u8; expected_byte_length as usize];
614        for rgba8 in pixels.chunks_mut(4) {
615            rgba8[3] = 255u8;
616        }
617
618        // TODO(nox): AFAICT here we construct a RGBA8 array and then we
619        // convert it to whatever actual format we need, we should probably
620        // construct the desired format from the start.
621        self.tex_image_2d(
622            texture,
623            target,
624            data_type,
625            internal_format,
626            internal_format.to_unsized(),
627            level,
628            0,
629            1,
630            size,
631            TexSource::Pixels(TexPixels::new(
632                GenericSharedMemory::from_vec(pixels),
633                size,
634                PixelFormat::RGBA8,
635                None,
636                YAxisTreatment::AsIs,
637            )),
638        );
639
640        false
641    }
642
643    fn validate_stencil_actions(&self, action: u32) -> bool {
644        matches!(
645            action,
646            0 | constants::KEEP |
647                constants::REPLACE |
648                constants::INCR |
649                constants::DECR |
650                constants::INVERT |
651                constants::INCR_WRAP |
652                constants::DECR_WRAP
653        )
654    }
655
656    pub(crate) fn get_image_pixels(
657        &self,
658        no_gc: &NoGC,
659        source: TexImageSource,
660    ) -> Fallible<Option<TexPixels>> {
661        Ok(Some(match source {
662            TexImageSource::ImageBitmap(bitmap) => {
663                if !bitmap.origin_is_clean() {
664                    return Err(Error::Security(None));
665                }
666
667                let Some(snapshot) = bitmap.bitmap_data().clone() else {
668                    return Ok(None);
669                };
670
671                let snapshot = snapshot.to_shared();
672                let size = snapshot.size().cast();
673                let format = match snapshot.format() {
674                    SnapshotPixelFormat::RGBA => PixelFormat::RGBA8,
675                    SnapshotPixelFormat::BGRA => PixelFormat::BGRA8,
676                };
677
678                // If the TexImageSource is an ImageBitmap, the values of
679                // UNPACK_FLIP_Y, UNPACK_PREMULTIPLY_ALPHA, and
680                // UNPACK_COLORSPACE_CONVERSION are to be ignored.
681                // Set alpha and y_axis treatment parameters such that no
682                // conversions will be made.
683                // <https://registry.khronos.org/webgl/specs/latest/1.0/#6.10>
684                TexPixels::new(
685                    snapshot.shared_memory(),
686                    size,
687                    format,
688                    None,
689                    YAxisTreatment::AsIs,
690                )
691            },
692            TexImageSource::ImageData(image_data) => {
693                let (alpha_treatment, y_axis_treatment) =
694                    self.get_current_unpack_state(Alpha::NotPremultiplied);
695
696                TexPixels::new(
697                    image_data.to_shared_memory(no_gc),
698                    image_data.get_size(),
699                    PixelFormat::RGBA8,
700                    alpha_treatment,
701                    y_axis_treatment,
702                )
703            },
704            TexImageSource::HTMLImageElement(image) => {
705                let document = match self.canvas {
706                    HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(ref canvas) => {
707                        canvas.owner_document()
708                    },
709                    HTMLCanvasElementOrOffscreenCanvas::OffscreenCanvas(ref _canvas) => {
710                        // TODO: Support retrieving image pixels here for OffscreenCanvas
711                        return Ok(None);
712                    },
713                };
714                if !image.same_origin(&document.origin()) {
715                    return Err(Error::Security(None));
716                }
717
718                // Vector images are not currently supported here and there are
719                // some open questions in the specification about how to handle them:
720                // See https://github.com/KhronosGroup/WebGL/issues/1503
721                let Some(snapshot) = image.get_raster_image_data() else {
722                    return Ok(None);
723                };
724
725                let snapshot = snapshot.to_shared();
726                let size = snapshot.size().cast();
727                let format: PixelFormat = match snapshot.format() {
728                    SnapshotPixelFormat::RGBA => PixelFormat::RGBA8,
729                    SnapshotPixelFormat::BGRA => PixelFormat::BGRA8,
730                };
731
732                let (alpha_treatment, y_axis_treatment) =
733                    self.get_current_unpack_state(snapshot.alpha_mode().alpha());
734
735                TexPixels::new(
736                    snapshot.shared_memory(),
737                    size,
738                    format,
739                    alpha_treatment,
740                    y_axis_treatment,
741                )
742            },
743            // TODO(emilio): Getting canvas data is implemented in CanvasRenderingContext2D,
744            // but we need to refactor it moving it to `HTMLCanvasElement` and support
745            // WebGLContext (probably via GetPixels()).
746            TexImageSource::HTMLCanvasElement(canvas) => {
747                if !canvas.origin_is_clean() {
748                    return Err(Error::Security(None));
749                }
750
751                let Some(snapshot) = canvas.get_image_data() else {
752                    return Ok(None);
753                };
754
755                let snapshot = snapshot.to_shared();
756                let size = snapshot.size().cast();
757                let format = match snapshot.format() {
758                    SnapshotPixelFormat::RGBA => PixelFormat::RGBA8,
759                    SnapshotPixelFormat::BGRA => PixelFormat::BGRA8,
760                };
761
762                let (alpha_treatment, y_axis_treatment) =
763                    self.get_current_unpack_state(snapshot.alpha_mode().alpha());
764
765                TexPixels::new(
766                    snapshot.shared_memory(),
767                    size,
768                    format,
769                    alpha_treatment,
770                    y_axis_treatment,
771                )
772            },
773            TexImageSource::HTMLVideoElement(video) => {
774                if !video.origin_is_clean() {
775                    return Err(Error::Security(None));
776                }
777
778                let Some(snapshot) = video.get_current_frame_data() else {
779                    return Ok(None);
780                };
781
782                let snapshot = snapshot.to_shared();
783                let size = snapshot.size().cast();
784                let format: PixelFormat = match snapshot.format() {
785                    SnapshotPixelFormat::RGBA => PixelFormat::RGBA8,
786                    SnapshotPixelFormat::BGRA => PixelFormat::BGRA8,
787                };
788
789                let (alpha_treatment, y_axis_treatment) =
790                    self.get_current_unpack_state(snapshot.alpha_mode().alpha());
791
792                TexPixels::new(
793                    snapshot.shared_memory(),
794                    size,
795                    format,
796                    alpha_treatment,
797                    y_axis_treatment,
798                )
799            },
800        }))
801    }
802
803    // TODO(emilio): Move this logic to a validator.
804    pub(crate) fn validate_tex_image_2d_data(
805        &self,
806        width: u32,
807        height: u32,
808        format: TexFormat,
809        data_type: TexDataType,
810        unpacking_alignment: u32,
811        data: Option<&ArrayBufferView>,
812    ) -> Result<u32, ()> {
813        let element_size = data_type.element_size();
814        let components_per_element = data_type.components_per_element();
815        let components = format.components();
816
817        // If data is non-null, the type of pixels must match the type of the
818        // data to be read.
819        // If it is UNSIGNED_BYTE, a Uint8Array must be supplied;
820        // if it is UNSIGNED_SHORT_5_6_5, UNSIGNED_SHORT_4_4_4_4,
821        // or UNSIGNED_SHORT_5_5_5_1, a Uint16Array must be supplied.
822        // or FLOAT, a Float32Array must be supplied.
823        // If the types do not match, an INVALID_OPERATION error is generated.
824        let data_type_matches = data.as_ref().is_none_or(|buffer| {
825            Some(data_type.sized_data_type()) ==
826                array_buffer_type_to_sized_type(buffer.get_array_type()) &&
827                data_type.required_webgl_version() <= self.webgl_version()
828        });
829
830        if !data_type_matches {
831            self.webgl_error(InvalidOperation);
832            return Err(());
833        }
834
835        // NOTE: width and height are positive or zero due to validate()
836        if height == 0 {
837            Ok(0)
838        } else {
839            // We need to be careful here to not count unpack
840            // alignment at the end of the image, otherwise (for
841            // example) passing a single byte for uploading a 1x1
842            // GL_ALPHA/GL_UNSIGNED_BYTE texture would throw an error.
843            let cpp = element_size * components / components_per_element;
844            let stride = (width * cpp + unpacking_alignment - 1) & !(unpacking_alignment - 1);
845            Ok(stride * (height - 1) + width * cpp)
846        }
847    }
848
849    #[allow(clippy::too_many_arguments)]
850    pub(crate) fn tex_image_2d(
851        &self,
852        texture: &WebGLTexture,
853        target: TexImageTarget,
854        data_type: TexDataType,
855        internal_format: TexFormat,
856        format: TexFormat,
857        level: u32,
858        _border: u32,
859        unpacking_alignment: u32,
860        size: Size2D<u32>,
861        source: TexSource,
862    ) {
863        // TexImage2D depth is always equal to 1.
864        handle_potential_webgl_error!(
865            self,
866            texture.initialize(
867                target,
868                size.width,
869                size.height,
870                1,
871                format,
872                level,
873                Some(data_type)
874            )
875        );
876
877        let internal_format = self
878            .extension_manager
879            .get_effective_tex_internal_format(internal_format, data_type.as_gl_constant());
880
881        let effective_data_type = self
882            .extension_manager
883            .effective_type(data_type.as_gl_constant());
884
885        match source {
886            TexSource::Pixels(pixels) => {
887                // TODO(emilio): convert colorspace if requested.
888                self.send_command(WebGLCommand::TexImage2D {
889                    target: target.as_gl_constant(),
890                    level,
891                    internal_format,
892                    size,
893                    format,
894                    data_type,
895                    effective_data_type,
896                    unpacking_alignment,
897                    alpha_treatment: pixels.alpha_treatment,
898                    y_axis_treatment: pixels.y_axis_treatment,
899                    pixel_format: pixels.pixel_format,
900                    data: pixels.data.into(),
901                });
902            },
903            TexSource::BufferOffset(offset) => {
904                self.send_command(WebGLCommand::TexImage2DPBO {
905                    target: target.as_gl_constant(),
906                    level,
907                    internal_format,
908                    size,
909                    format,
910                    effective_data_type,
911                    unpacking_alignment,
912                    offset,
913                });
914            },
915        }
916
917        if let Some(fb) = self.bound_draw_framebuffer.get() {
918            fb.invalidate_texture(texture);
919        }
920    }
921
922    #[allow(clippy::too_many_arguments)]
923    fn tex_sub_image_2d(
924        &self,
925        texture: DomRoot<WebGLTexture>,
926        target: TexImageTarget,
927        level: u32,
928        xoffset: i32,
929        yoffset: i32,
930        format: TexFormat,
931        data_type: TexDataType,
932        unpacking_alignment: u32,
933        pixels: TexPixels,
934    ) {
935        // We have already validated level
936        let image_info = match texture.image_info_for_target(&target, level) {
937            Some(info) => info,
938            None => return self.webgl_error(InvalidOperation),
939        };
940
941        // GL_INVALID_VALUE is generated if:
942        //   - xoffset or yoffset is less than 0
943        //   - x offset plus the width is greater than the texture width
944        //   - y offset plus the height is greater than the texture height
945        if xoffset < 0 ||
946            (xoffset as u32 + pixels.size().width) > image_info.width() ||
947            yoffset < 0 ||
948            (yoffset as u32 + pixels.size().height) > image_info.height()
949        {
950            return self.webgl_error(InvalidValue);
951        }
952
953        // The unsized format must be compatible with the sized internal format
954        debug_assert!(!format.is_sized());
955        if format != image_info.internal_format().to_unsized() {
956            return self.webgl_error(InvalidOperation);
957        }
958
959        // See https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.1.6
960        if self.webgl_version() == WebGLVersion::WebGL1 &&
961            data_type != image_info.data_type().unwrap()
962        {
963            return self.webgl_error(InvalidOperation);
964        }
965
966        let effective_data_type = self
967            .extension_manager
968            .effective_type(data_type.as_gl_constant());
969
970        // TODO(emilio): convert colorspace if requested.
971        self.send_command(WebGLCommand::TexSubImage2D {
972            target: target.as_gl_constant(),
973            level,
974            xoffset,
975            yoffset,
976            size: pixels.size(),
977            format,
978            data_type,
979            effective_data_type,
980            unpacking_alignment,
981            alpha_treatment: pixels.alpha_treatment,
982            y_axis_treatment: pixels.y_axis_treatment,
983            pixel_format: pixels.pixel_format,
984            data: pixels.data.into(),
985        });
986    }
987
988    fn get_gl_extensions(&self) -> String {
989        let (sender, receiver) = webgl_channel().unwrap();
990        self.send_command(WebGLCommand::GetExtensions(sender));
991        receiver.recv().unwrap()
992    }
993
994    // https://www.khronos.org/registry/webgl/extensions/ANGLE_instanced_arrays/
995    pub(crate) fn draw_arrays_instanced(
996        &self,
997        cx: &mut JSContext,
998        mode: u32,
999        first: i32,
1000        count: i32,
1001        primcount: i32,
1002    ) -> WebGLResult<()> {
1003        match mode {
1004            constants::POINTS |
1005            constants::LINE_STRIP |
1006            constants::LINE_LOOP |
1007            constants::LINES |
1008            constants::TRIANGLE_STRIP |
1009            constants::TRIANGLE_FAN |
1010            constants::TRIANGLES => {},
1011            _ => {
1012                return Err(InvalidEnum);
1013            },
1014        }
1015        if first < 0 || count < 0 || primcount < 0 {
1016            return Err(InvalidValue);
1017        }
1018
1019        let current_program = self.current_program.get().ok_or(InvalidOperation)?;
1020
1021        let required_len = if count > 0 {
1022            first
1023                .checked_add(count)
1024                .map(|len| len as u32)
1025                .ok_or(InvalidOperation)?
1026        } else {
1027            0
1028        };
1029
1030        match self.webgl_version() {
1031            WebGLVersion::WebGL1 => self.current_vao(cx).validate_for_draw(
1032                required_len,
1033                primcount as u32,
1034                &current_program.active_attribs(),
1035            )?,
1036            WebGLVersion::WebGL2 => self.current_vao_webgl2(cx).validate_for_draw(
1037                required_len,
1038                primcount as u32,
1039                &current_program.active_attribs(),
1040            )?,
1041        };
1042
1043        self.validate_framebuffer()?;
1044
1045        if count == 0 || primcount == 0 {
1046            return Ok(());
1047        }
1048
1049        self.send_command(if primcount == 1 {
1050            WebGLCommand::DrawArrays { mode, first, count }
1051        } else {
1052            WebGLCommand::DrawArraysInstanced {
1053                mode,
1054                first,
1055                count,
1056                primcount,
1057            }
1058        });
1059        self.mark_as_dirty();
1060        Ok(())
1061    }
1062
1063    // https://www.khronos.org/registry/webgl/extensions/ANGLE_instanced_arrays/
1064    pub(crate) fn draw_elements_instanced(
1065        &self,
1066        cx: &mut JSContext,
1067        mode: u32,
1068        count: i32,
1069        type_: u32,
1070        offset: i64,
1071        primcount: i32,
1072    ) -> WebGLResult<()> {
1073        match mode {
1074            constants::POINTS |
1075            constants::LINE_STRIP |
1076            constants::LINE_LOOP |
1077            constants::LINES |
1078            constants::TRIANGLE_STRIP |
1079            constants::TRIANGLE_FAN |
1080            constants::TRIANGLES => {},
1081            _ => {
1082                return Err(InvalidEnum);
1083            },
1084        }
1085        if count < 0 || offset < 0 || primcount < 0 {
1086            return Err(InvalidValue);
1087        }
1088        let type_size = match type_ {
1089            constants::UNSIGNED_BYTE => 1,
1090            constants::UNSIGNED_SHORT => 2,
1091            constants::UNSIGNED_INT => match self.webgl_version() {
1092                WebGLVersion::WebGL1 if self.extension_manager.is_element_index_uint_enabled() => 4,
1093                WebGLVersion::WebGL2 => 4,
1094                _ => return Err(InvalidEnum),
1095            },
1096            _ => return Err(InvalidEnum),
1097        };
1098        if offset % type_size != 0 {
1099            return Err(InvalidOperation);
1100        }
1101
1102        let current_program = self.current_program.get().ok_or(InvalidOperation)?;
1103        let array_buffer = match self.webgl_version() {
1104            WebGLVersion::WebGL1 => self.current_vao(cx).element_array_buffer().get(),
1105            WebGLVersion::WebGL2 => self.current_vao_webgl2(cx).element_array_buffer().get(),
1106        }
1107        .ok_or(InvalidOperation)?;
1108
1109        if count > 0 && primcount > 0 {
1110            // This operation cannot overflow in u64 and we know all those values are nonnegative.
1111            let val = offset as u64 + (count as u64 * type_size as u64);
1112            if val > array_buffer.capacity() as u64 {
1113                return Err(InvalidOperation);
1114            }
1115        }
1116
1117        // TODO(nox): Pass the correct number of vertices required.
1118        match self.webgl_version() {
1119            WebGLVersion::WebGL1 => self.current_vao(cx).validate_for_draw(
1120                0,
1121                primcount as u32,
1122                &current_program.active_attribs(),
1123            )?,
1124            WebGLVersion::WebGL2 => self.current_vao_webgl2(cx).validate_for_draw(
1125                0,
1126                primcount as u32,
1127                &current_program.active_attribs(),
1128            )?,
1129        };
1130
1131        self.validate_framebuffer()?;
1132
1133        if count == 0 || primcount == 0 {
1134            return Ok(());
1135        }
1136
1137        let offset = offset as u32;
1138        self.send_command(if primcount == 1 {
1139            WebGLCommand::DrawElements {
1140                mode,
1141                count,
1142                type_,
1143                offset,
1144            }
1145        } else {
1146            WebGLCommand::DrawElementsInstanced {
1147                mode,
1148                count,
1149                type_,
1150                offset,
1151                primcount,
1152            }
1153        });
1154        self.mark_as_dirty();
1155        Ok(())
1156    }
1157
1158    pub(crate) fn vertex_attrib_divisor(&self, cx: &mut JSContext, index: u32, divisor: u32) {
1159        if index >= self.limits.max_vertex_attribs {
1160            return self.webgl_error(InvalidValue);
1161        }
1162
1163        match self.webgl_version() {
1164            WebGLVersion::WebGL1 => self.current_vao(cx).vertex_attrib_divisor(index, divisor),
1165            WebGLVersion::WebGL2 => self
1166                .current_vao_webgl2(cx)
1167                .vertex_attrib_divisor(index, divisor),
1168        };
1169        self.send_command(WebGLCommand::VertexAttribDivisor { index, divisor });
1170    }
1171
1172    pub(crate) fn array_buffer(&self) -> Option<DomRoot<WebGLBuffer>> {
1173        self.bound_buffer_array.get()
1174    }
1175
1176    pub(crate) fn array_buffer_slot(&self) -> &MutNullableDom<WebGLBuffer> {
1177        &self.bound_buffer_array
1178    }
1179
1180    pub(crate) fn bound_buffer(
1181        &self,
1182        cx: &mut JSContext,
1183        target: u32,
1184    ) -> WebGLResult<Option<DomRoot<WebGLBuffer>>> {
1185        match target {
1186            constants::ARRAY_BUFFER => Ok(self.bound_buffer_array.get()),
1187            constants::ELEMENT_ARRAY_BUFFER => {
1188                Ok(self.current_vao(cx).element_array_buffer().get())
1189            },
1190            _ => Err(WebGLError::InvalidEnum),
1191        }
1192    }
1193
1194    pub(crate) fn buffer_usage(&self, usage: u32) -> WebGLResult<u32> {
1195        match usage {
1196            constants::STREAM_DRAW | constants::STATIC_DRAW | constants::DYNAMIC_DRAW => Ok(usage),
1197            _ => Err(WebGLError::InvalidEnum),
1198        }
1199    }
1200
1201    pub(crate) fn create_vertex_array(
1202        &self,
1203        cx: &mut JSContext,
1204    ) -> Option<DomRoot<WebGLVertexArrayObjectOES>> {
1205        let (sender, receiver) = webgl_channel().unwrap();
1206        self.send_command(WebGLCommand::CreateVertexArray(sender));
1207        receiver
1208            .recv()
1209            .unwrap()
1210            .map(|id| WebGLVertexArrayObjectOES::new(cx, self, Some(id)))
1211    }
1212
1213    pub(crate) fn create_vertex_array_webgl2(
1214        &self,
1215        cx: &mut JSContext,
1216    ) -> Option<DomRoot<WebGLVertexArrayObject>> {
1217        let (sender, receiver) = webgl_channel().unwrap();
1218        self.send_command(WebGLCommand::CreateVertexArray(sender));
1219        receiver
1220            .recv()
1221            .unwrap()
1222            .map(|id| WebGLVertexArrayObject::new(cx, self, Some(id)))
1223    }
1224
1225    pub(crate) fn delete_vertex_array(
1226        &self,
1227        cx: &mut JSContext,
1228        vao: Option<&WebGLVertexArrayObjectOES>,
1229    ) {
1230        if let Some(vao) = vao {
1231            handle_potential_webgl_error!(self, self.validate_ownership(vao), return);
1232            // The default vertex array has no id and should never be passed around.
1233            assert!(vao.id().is_some());
1234            if vao.is_deleted() {
1235                return;
1236            }
1237            if vao == &*self.current_vao(cx) {
1238                // Setting it to None will make self.current_vao() reset it to the default one
1239                // next time it is called.
1240                self.current_vao.set(None);
1241                self.send_command(WebGLCommand::BindVertexArray(None));
1242            }
1243            vao.delete(Operation::Infallible);
1244        }
1245    }
1246
1247    pub(crate) fn delete_vertex_array_webgl2(
1248        &self,
1249        cx: &mut JSContext,
1250        vao: Option<&WebGLVertexArrayObject>,
1251    ) {
1252        if let Some(vao) = vao {
1253            handle_potential_webgl_error!(self, self.validate_ownership(vao), return);
1254            // The default vertex array has no id and should never be passed around.
1255            assert!(vao.id().is_some());
1256            if vao.is_deleted() {
1257                return;
1258            }
1259            if vao == &*self.current_vao_webgl2(cx) {
1260                // Setting it to None will make self.current_vao() reset it to the default one
1261                // next time it is called.
1262                self.current_vao_webgl2.set(None);
1263                self.send_command(WebGLCommand::BindVertexArray(None));
1264            }
1265            vao.delete(Operation::Infallible);
1266        }
1267    }
1268
1269    pub(crate) fn is_vertex_array(&self, vao: Option<&WebGLVertexArrayObjectOES>) -> bool {
1270        vao.is_some_and(|vao| {
1271            // The default vertex array has no id and should never be passed around.
1272            assert!(vao.id().is_some());
1273            self.validate_ownership(vao).is_ok() && vao.ever_bound() && !vao.is_deleted()
1274        })
1275    }
1276
1277    pub(crate) fn is_vertex_array_webgl2(&self, vao: Option<&WebGLVertexArrayObject>) -> bool {
1278        vao.is_some_and(|vao| {
1279            // The default vertex array has no id and should never be passed around.
1280            assert!(vao.id().is_some());
1281            self.validate_ownership(vao).is_ok() && vao.ever_bound() && !vao.is_deleted()
1282        })
1283    }
1284
1285    pub(crate) fn bind_vertex_array(&self, vao: Option<&WebGLVertexArrayObjectOES>) {
1286        if let Some(vao) = vao {
1287            // The default vertex array has no id and should never be passed around.
1288            assert!(vao.id().is_some());
1289            handle_potential_webgl_error!(self, self.validate_ownership(vao), return);
1290            if vao.is_deleted() {
1291                return self.webgl_error(InvalidOperation);
1292            }
1293            vao.set_ever_bound();
1294        }
1295        self.send_command(WebGLCommand::BindVertexArray(vao.and_then(|vao| vao.id())));
1296        // Setting it to None will make self.current_vao() reset it to the default one
1297        // next time it is called.
1298        self.current_vao.set(vao);
1299    }
1300
1301    pub(crate) fn bind_vertex_array_webgl2(&self, vao: Option<&WebGLVertexArrayObject>) {
1302        if let Some(vao) = vao {
1303            // The default vertex array has no id and should never be passed around.
1304            assert!(vao.id().is_some());
1305            handle_potential_webgl_error!(self, self.validate_ownership(vao), return);
1306            if vao.is_deleted() {
1307                return self.webgl_error(InvalidOperation);
1308            }
1309            vao.set_ever_bound();
1310        }
1311        self.send_command(WebGLCommand::BindVertexArray(vao.and_then(|vao| vao.id())));
1312        // Setting it to None will make self.current_vao() reset it to the default one
1313        // next time it is called.
1314        self.current_vao_webgl2.set(vao);
1315    }
1316
1317    fn validate_blend_mode(&self, mode: u32) -> WebGLResult<()> {
1318        match mode {
1319            constants::FUNC_ADD | constants::FUNC_SUBTRACT | constants::FUNC_REVERSE_SUBTRACT => {
1320                Ok(())
1321            },
1322            EXTBlendMinmaxConstants::MIN_EXT | EXTBlendMinmaxConstants::MAX_EXT
1323                if self.extension_manager.is_blend_minmax_enabled() =>
1324            {
1325                Ok(())
1326            },
1327            _ => Err(InvalidEnum),
1328        }
1329    }
1330
1331    pub(crate) fn initialize_framebuffer(&self, clear_bits: u32) {
1332        if clear_bits == 0 {
1333            return;
1334        }
1335        self.send_command(WebGLCommand::InitializeFramebuffer {
1336            color: clear_bits & constants::COLOR_BUFFER_BIT != 0,
1337            depth: clear_bits & constants::DEPTH_BUFFER_BIT != 0,
1338            stencil: clear_bits & constants::STENCIL_BUFFER_BIT != 0,
1339        });
1340    }
1341
1342    pub(crate) fn extension_manager(&self) -> &WebGLExtensions {
1343        &self.extension_manager
1344    }
1345
1346    pub(crate) fn buffer_data(
1347        &self,
1348        no_gc: &NoGC,
1349        target: u32,
1350        data: Option<ArrayBufferViewOrArrayBuffer>,
1351        usage: u32,
1352        bound_buffer: Option<DomRoot<WebGLBuffer>>,
1353    ) {
1354        let data = handle_potential_webgl_error!(self, data.ok_or(InvalidValue), return);
1355        let bound_buffer =
1356            handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return);
1357
1358        let data = get_buffer_source_slice(&data, no_gc);
1359        handle_potential_webgl_error!(self, bound_buffer.buffer_data(target, data, usage));
1360    }
1361
1362    pub(crate) fn buffer_data_(
1363        &self,
1364        target: u32,
1365        size: i64,
1366        usage: u32,
1367        bound_buffer: Option<DomRoot<WebGLBuffer>>,
1368    ) {
1369        let bound_buffer =
1370            handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return);
1371
1372        if size < 0 {
1373            return self.webgl_error(InvalidValue);
1374        }
1375
1376        // FIXME: Allocating a buffer based on user-requested size is
1377        // not great, but we don't have a fallible allocation to try.
1378        let data = vec![0u8; size as usize];
1379        handle_potential_webgl_error!(self, bound_buffer.buffer_data(target, &data, usage));
1380    }
1381
1382    pub(crate) fn buffer_sub_data(
1383        &self,
1384        no_gc: &NoGC,
1385        target: u32,
1386        offset: i64,
1387        data: ArrayBufferViewOrArrayBuffer,
1388        bound_buffer: Option<DomRoot<WebGLBuffer>>,
1389    ) {
1390        let bound_buffer =
1391            handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return);
1392
1393        if offset < 0 {
1394            return self.webgl_error(InvalidValue);
1395        }
1396
1397        let data = get_buffer_source_slice(&data, no_gc);
1398        if (offset as u64) + data.len() as u64 > bound_buffer.capacity() as u64 {
1399            return self.webgl_error(InvalidValue);
1400        }
1401        let (sender, receiver) = generic_channel::channel().unwrap();
1402        self.send_command(WebGLCommand::BufferSubData(
1403            target,
1404            offset as isize,
1405            receiver,
1406        ));
1407        let buffer = GenericSharedMemory::from_bytes(data);
1408        sender.send(buffer).unwrap();
1409    }
1410
1411    pub(crate) fn bind_buffer_maybe(
1412        &self,
1413        slot: &MutNullableDom<WebGLBuffer>,
1414        target: u32,
1415        buffer: Option<&WebGLBuffer>,
1416    ) {
1417        if let Some(buffer) = buffer {
1418            handle_potential_webgl_error!(self, self.validate_ownership(buffer), return);
1419
1420            if buffer.is_marked_for_deletion() {
1421                return self.webgl_error(InvalidOperation);
1422            }
1423            handle_potential_webgl_error!(self, buffer.set_target_maybe(target), return);
1424            buffer.increment_attached_counter();
1425        }
1426
1427        self.send_command(WebGLCommand::BindBuffer(target, buffer.map(|b| b.id())));
1428        if let Some(old) = slot.get() {
1429            old.decrement_attached_counter(Operation::Infallible);
1430        }
1431
1432        slot.set(buffer);
1433    }
1434
1435    pub(crate) fn current_program(&self) -> Option<DomRoot<WebGLProgram>> {
1436        self.current_program.get()
1437    }
1438
1439    pub(crate) fn uniform_check_program(
1440        &self,
1441        program: &WebGLProgram,
1442        location: &WebGLUniformLocation,
1443    ) -> WebGLResult<()> {
1444        self.validate_ownership(program)?;
1445
1446        if program.is_deleted() ||
1447            !program.is_linked() ||
1448            self.context_id() != location.context_id() ||
1449            program.id() != location.program_id() ||
1450            program.link_generation() != location.link_generation()
1451        {
1452            return Err(InvalidOperation);
1453        }
1454
1455        Ok(())
1456    }
1457
1458    fn uniform_vec_section_int(
1459        &self,
1460        vec: Int32ArrayOrLongSequence,
1461        offset: u32,
1462        length: u32,
1463        uniform_size: usize,
1464        uniform_location: &WebGLUniformLocation,
1465    ) -> WebGLResult<Vec<i32>> {
1466        let vec = match vec {
1467            Int32ArrayOrLongSequence::Int32Array(v) => v.to_vec().unwrap_or_default(),
1468            Int32ArrayOrLongSequence::LongSequence(v) => v,
1469        };
1470        self.uniform_vec_section::<i32>(vec, offset, length, uniform_size, uniform_location)
1471    }
1472
1473    fn uniform_vec_section_float(
1474        &self,
1475        vec: Float32ArrayOrUnrestrictedFloatSequence,
1476        offset: u32,
1477        length: u32,
1478        uniform_size: usize,
1479        uniform_location: &WebGLUniformLocation,
1480    ) -> WebGLResult<Vec<f32>> {
1481        let vec = match vec {
1482            Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => {
1483                v.to_vec().unwrap_or_default()
1484            },
1485            Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
1486        };
1487        self.uniform_vec_section::<f32>(vec, offset, length, uniform_size, uniform_location)
1488    }
1489
1490    pub(crate) fn uniform_vec_section<T: Clone>(
1491        &self,
1492        vec: Vec<T>,
1493        offset: u32,
1494        length: u32,
1495        uniform_size: usize,
1496        uniform_location: &WebGLUniformLocation,
1497    ) -> WebGLResult<Vec<T>> {
1498        let offset = offset as usize;
1499        if offset > vec.len() {
1500            return Err(InvalidValue);
1501        }
1502
1503        let length = if length > 0 {
1504            length as usize
1505        } else {
1506            vec.len() - offset
1507        };
1508        if offset + length > vec.len() {
1509            return Err(InvalidValue);
1510        }
1511
1512        let vec = if offset == 0 && length == vec.len() {
1513            vec
1514        } else {
1515            vec[offset..offset + length].to_vec()
1516        };
1517
1518        if vec.len() < uniform_size || vec.len() % uniform_size != 0 {
1519            return Err(InvalidValue);
1520        }
1521        if uniform_location.size().is_none() && vec.len() != uniform_size {
1522            return Err(InvalidOperation);
1523        }
1524
1525        Ok(vec)
1526    }
1527
1528    pub(crate) fn uniform_matrix_section(
1529        &self,
1530        vec: Float32ArrayOrUnrestrictedFloatSequence,
1531        offset: u32,
1532        length: u32,
1533        transpose: bool,
1534        uniform_size: usize,
1535        uniform_location: &WebGLUniformLocation,
1536    ) -> WebGLResult<Vec<f32>> {
1537        let vec = match vec {
1538            Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => {
1539                v.to_vec().unwrap_or_default()
1540            },
1541            Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
1542        };
1543        if transpose {
1544            return Err(InvalidValue);
1545        }
1546        self.uniform_vec_section::<f32>(vec, offset, length, uniform_size, uniform_location)
1547    }
1548
1549    pub(crate) fn get_draw_framebuffer_slot(&self) -> &MutNullableDom<WebGLFramebuffer> {
1550        &self.bound_draw_framebuffer
1551    }
1552
1553    pub(crate) fn get_read_framebuffer_slot(&self) -> &MutNullableDom<WebGLFramebuffer> {
1554        &self.bound_read_framebuffer
1555    }
1556
1557    pub(crate) fn validate_new_framebuffer_binding(
1558        &self,
1559        framebuffer: Option<&WebGLFramebuffer>,
1560    ) -> WebGLResult<()> {
1561        if let Some(fb) = framebuffer {
1562            self.validate_ownership(fb)?;
1563            if fb.is_deleted() {
1564                // From the WebGL spec:
1565                //
1566                //     "An attempt to bind a deleted framebuffer will
1567                //      generate an INVALID_OPERATION error, and the
1568                //      current binding will remain untouched."
1569                return Err(InvalidOperation);
1570            }
1571        }
1572        Ok(())
1573    }
1574
1575    pub(crate) fn bind_framebuffer_to(
1576        &self,
1577        target: u32,
1578        framebuffer: Option<&WebGLFramebuffer>,
1579        slot: &MutNullableDom<WebGLFramebuffer>,
1580    ) {
1581        match framebuffer {
1582            Some(framebuffer) => framebuffer.bind(target),
1583            None => {
1584                // Bind the default framebuffer
1585                let cmd =
1586                    WebGLCommand::BindFramebuffer(target, WebGLFramebufferBindingRequest::Default);
1587                self.send_command(cmd);
1588            },
1589        }
1590        slot.set(framebuffer);
1591    }
1592
1593    pub(crate) fn renderbuffer_storage(
1594        &self,
1595        target: u32,
1596        samples: i32,
1597        internal_format: u32,
1598        width: i32,
1599        height: i32,
1600    ) {
1601        if target != constants::RENDERBUFFER {
1602            return self.webgl_error(InvalidEnum);
1603        }
1604
1605        let max = self.limits.max_renderbuffer_size;
1606
1607        if samples < 0 || width < 0 || width as u32 > max || height < 0 || height as u32 > max {
1608            return self.webgl_error(InvalidValue);
1609        }
1610
1611        let rb = handle_potential_webgl_error!(
1612            self,
1613            self.bound_renderbuffer.get().ok_or(InvalidOperation),
1614            return
1615        );
1616        handle_potential_webgl_error!(
1617            self,
1618            rb.storage(self.api_type, samples, internal_format, width, height)
1619        );
1620        if let Some(fb) = self.bound_draw_framebuffer.get() {
1621            fb.invalidate_renderbuffer(&rb);
1622        }
1623
1624        // FIXME: https://github.com/servo/servo/issues/13710
1625    }
1626
1627    pub(crate) fn valid_color_attachment_enum(&self, attachment: u32) -> bool {
1628        let last_slot = constants::COLOR_ATTACHMENT0 + self.limits().max_color_attachments - 1;
1629        constants::COLOR_ATTACHMENT0 <= attachment && attachment <= last_slot
1630    }
1631
1632    #[allow(clippy::too_many_arguments)]
1633    pub(crate) fn compressed_tex_image_2d(
1634        &self,
1635        target: u32,
1636        level: i32,
1637        internal_format: u32,
1638        width: i32,
1639        height: i32,
1640        border: i32,
1641        data: &[u8],
1642    ) {
1643        let validator = CompressedTexImage2DValidator::new(
1644            self,
1645            target,
1646            level,
1647            width,
1648            height,
1649            border,
1650            internal_format,
1651            data.len(),
1652        );
1653        let CommonCompressedTexImage2DValidatorResult {
1654            texture,
1655            target,
1656            level,
1657            width,
1658            height,
1659            compression,
1660        } = match validator.validate() {
1661            Ok(result) => result,
1662            Err(_) => return,
1663        };
1664
1665        if texture.is_immutable() {
1666            return self.webgl_error(InvalidOperation);
1667        }
1668
1669        let size = Size2D::new(width, height);
1670        let data = GenericSharedMemory::from_bytes(data);
1671
1672        handle_potential_webgl_error!(
1673            self,
1674            texture.initialize(
1675                target,
1676                size.width,
1677                size.height,
1678                1,
1679                compression.format,
1680                level,
1681                Some(TexDataType::UnsignedByte)
1682            )
1683        );
1684
1685        self.send_command(WebGLCommand::CompressedTexImage2D {
1686            target: target.as_gl_constant(),
1687            level,
1688            internal_format,
1689            size: Size2D::new(width, height),
1690            data: data.into(),
1691        });
1692
1693        if let Some(fb) = self.bound_draw_framebuffer.get() {
1694            fb.invalidate_texture(&texture);
1695        }
1696    }
1697
1698    #[allow(clippy::too_many_arguments)]
1699    pub(crate) fn compressed_tex_sub_image_2d(
1700        &self,
1701        target: u32,
1702        level: i32,
1703        xoffset: i32,
1704        yoffset: i32,
1705        width: i32,
1706        height: i32,
1707        format: u32,
1708        data: &[u8],
1709    ) {
1710        let validator = CompressedTexSubImage2DValidator::new(
1711            self,
1712            target,
1713            level,
1714            xoffset,
1715            yoffset,
1716            width,
1717            height,
1718            format,
1719            data.len(),
1720        );
1721        let CommonCompressedTexImage2DValidatorResult {
1722            texture: _,
1723            target,
1724            level,
1725            width,
1726            height,
1727            ..
1728        } = match validator.validate() {
1729            Ok(result) => result,
1730            Err(_) => return,
1731        };
1732
1733        let data = GenericSharedMemory::from_bytes(data);
1734
1735        self.send_command(WebGLCommand::CompressedTexSubImage2D {
1736            target: target.as_gl_constant(),
1737            level: level as i32,
1738            xoffset,
1739            yoffset,
1740            size: Size2D::new(width, height),
1741            format,
1742            data: data.into(),
1743        });
1744    }
1745
1746    pub(crate) fn uniform1iv(
1747        &self,
1748        location: Option<&WebGLUniformLocation>,
1749        val: Int32ArrayOrLongSequence,
1750        src_offset: u32,
1751        src_length: u32,
1752    ) {
1753        self.with_location(location, |location| {
1754            match location.type_() {
1755                constants::BOOL |
1756                constants::INT |
1757                constants::SAMPLER_2D |
1758                WebGL2RenderingContextConstants::SAMPLER_2D_ARRAY |
1759                WebGL2RenderingContextConstants::SAMPLER_3D |
1760                constants::SAMPLER_CUBE => {},
1761                _ => return Err(InvalidOperation),
1762            }
1763
1764            let val = self.uniform_vec_section_int(val, src_offset, src_length, 1, location)?;
1765
1766            match location.type_() {
1767                constants::SAMPLER_2D |
1768                constants::SAMPLER_CUBE |
1769                WebGL2RenderingContextConstants::SAMPLER_2D_ARRAY |
1770                WebGL2RenderingContextConstants::SAMPLER_3D => {
1771                    for &v in val
1772                        .iter()
1773                        .take(cmp::min(location.size().unwrap_or(1) as usize, val.len()))
1774                    {
1775                        if v < 0 || v as u32 >= self.limits.max_combined_texture_image_units {
1776                            return Err(InvalidValue);
1777                        }
1778                    }
1779                },
1780                _ => {},
1781            }
1782            self.send_command(WebGLCommand::Uniform1iv(location.id(), val));
1783            Ok(())
1784        });
1785    }
1786
1787    pub(crate) fn uniform1fv(
1788        &self,
1789        location: Option<&WebGLUniformLocation>,
1790        val: Float32ArrayOrUnrestrictedFloatSequence,
1791        src_offset: u32,
1792        src_length: u32,
1793    ) {
1794        self.with_location(location, |location| {
1795            match location.type_() {
1796                constants::BOOL | constants::FLOAT => {},
1797                _ => return Err(InvalidOperation),
1798            }
1799            let val = self.uniform_vec_section_float(val, src_offset, src_length, 1, location)?;
1800            self.send_command(WebGLCommand::Uniform1fv(location.id(), val));
1801            Ok(())
1802        });
1803    }
1804
1805    pub(crate) fn uniform2fv(
1806        &self,
1807        location: Option<&WebGLUniformLocation>,
1808        val: Float32ArrayOrUnrestrictedFloatSequence,
1809        src_offset: u32,
1810        src_length: u32,
1811    ) {
1812        self.with_location(location, |location| {
1813            match location.type_() {
1814                constants::BOOL_VEC2 | constants::FLOAT_VEC2 => {},
1815                _ => return Err(InvalidOperation),
1816            }
1817            let val = self.uniform_vec_section_float(val, src_offset, src_length, 2, location)?;
1818            self.send_command(WebGLCommand::Uniform2fv(location.id(), val));
1819            Ok(())
1820        });
1821    }
1822
1823    pub(crate) fn uniform2iv(
1824        &self,
1825        location: Option<&WebGLUniformLocation>,
1826        val: Int32ArrayOrLongSequence,
1827        src_offset: u32,
1828        src_length: u32,
1829    ) {
1830        self.with_location(location, |location| {
1831            match location.type_() {
1832                constants::BOOL_VEC2 | constants::INT_VEC2 => {},
1833                _ => return Err(InvalidOperation),
1834            }
1835            let val = self.uniform_vec_section_int(val, src_offset, src_length, 2, location)?;
1836            self.send_command(WebGLCommand::Uniform2iv(location.id(), val));
1837            Ok(())
1838        });
1839    }
1840
1841    pub(crate) fn uniform3fv(
1842        &self,
1843        location: Option<&WebGLUniformLocation>,
1844        val: Float32ArrayOrUnrestrictedFloatSequence,
1845        src_offset: u32,
1846        src_length: u32,
1847    ) {
1848        self.with_location(location, |location| {
1849            match location.type_() {
1850                constants::BOOL_VEC3 | constants::FLOAT_VEC3 => {},
1851                _ => return Err(InvalidOperation),
1852            }
1853            let val = self.uniform_vec_section_float(val, src_offset, src_length, 3, location)?;
1854            self.send_command(WebGLCommand::Uniform3fv(location.id(), val));
1855            Ok(())
1856        });
1857    }
1858
1859    pub(crate) fn uniform3iv(
1860        &self,
1861        location: Option<&WebGLUniformLocation>,
1862        val: Int32ArrayOrLongSequence,
1863        src_offset: u32,
1864        src_length: u32,
1865    ) {
1866        self.with_location(location, |location| {
1867            match location.type_() {
1868                constants::BOOL_VEC3 | constants::INT_VEC3 => {},
1869                _ => return Err(InvalidOperation),
1870            }
1871            let val = self.uniform_vec_section_int(val, src_offset, src_length, 3, location)?;
1872            self.send_command(WebGLCommand::Uniform3iv(location.id(), val));
1873            Ok(())
1874        });
1875    }
1876
1877    pub(crate) fn uniform4iv(
1878        &self,
1879        location: Option<&WebGLUniformLocation>,
1880        val: Int32ArrayOrLongSequence,
1881        src_offset: u32,
1882        src_length: u32,
1883    ) {
1884        self.with_location(location, |location| {
1885            match location.type_() {
1886                constants::BOOL_VEC4 | constants::INT_VEC4 => {},
1887                _ => return Err(InvalidOperation),
1888            }
1889            let val = self.uniform_vec_section_int(val, src_offset, src_length, 4, location)?;
1890            self.send_command(WebGLCommand::Uniform4iv(location.id(), val));
1891            Ok(())
1892        });
1893    }
1894
1895    pub(crate) fn uniform4fv(
1896        &self,
1897        location: Option<&WebGLUniformLocation>,
1898        val: Float32ArrayOrUnrestrictedFloatSequence,
1899        src_offset: u32,
1900        src_length: u32,
1901    ) {
1902        self.with_location(location, |location| {
1903            match location.type_() {
1904                constants::BOOL_VEC4 | constants::FLOAT_VEC4 => {},
1905                _ => return Err(InvalidOperation),
1906            }
1907            let val = self.uniform_vec_section_float(val, src_offset, src_length, 4, location)?;
1908            self.send_command(WebGLCommand::Uniform4fv(location.id(), val));
1909            Ok(())
1910        });
1911    }
1912
1913    pub(crate) fn uniform_matrix_2fv(
1914        &self,
1915        location: Option<&WebGLUniformLocation>,
1916        transpose: bool,
1917        val: Float32ArrayOrUnrestrictedFloatSequence,
1918        src_offset: u32,
1919        src_length: u32,
1920    ) {
1921        self.with_location(location, |location| {
1922            match location.type_() {
1923                constants::FLOAT_MAT2 => {},
1924                _ => return Err(InvalidOperation),
1925            }
1926            let val =
1927                self.uniform_matrix_section(val, src_offset, src_length, transpose, 4, location)?;
1928            self.send_command(WebGLCommand::UniformMatrix2fv(location.id(), val));
1929            Ok(())
1930        });
1931    }
1932
1933    pub(crate) fn uniform_matrix_3fv(
1934        &self,
1935        location: Option<&WebGLUniformLocation>,
1936        transpose: bool,
1937        val: Float32ArrayOrUnrestrictedFloatSequence,
1938        src_offset: u32,
1939        src_length: u32,
1940    ) {
1941        self.with_location(location, |location| {
1942            match location.type_() {
1943                constants::FLOAT_MAT3 => {},
1944                _ => return Err(InvalidOperation),
1945            }
1946            let val =
1947                self.uniform_matrix_section(val, src_offset, src_length, transpose, 9, location)?;
1948            self.send_command(WebGLCommand::UniformMatrix3fv(location.id(), val));
1949            Ok(())
1950        });
1951    }
1952
1953    pub(crate) fn uniform_matrix_4fv(
1954        &self,
1955        location: Option<&WebGLUniformLocation>,
1956        transpose: bool,
1957        val: Float32ArrayOrUnrestrictedFloatSequence,
1958        src_offset: u32,
1959        src_length: u32,
1960    ) {
1961        self.with_location(location, |location| {
1962            match location.type_() {
1963                constants::FLOAT_MAT4 => {},
1964                _ => return Err(InvalidOperation),
1965            }
1966            let val =
1967                self.uniform_matrix_section(val, src_offset, src_length, transpose, 16, location)?;
1968            self.send_command(WebGLCommand::UniformMatrix4fv(location.id(), val));
1969            Ok(())
1970        });
1971    }
1972
1973    pub(crate) fn get_buffer_param(
1974        &self,
1975        buffer: Option<DomRoot<WebGLBuffer>>,
1976        parameter: u32,
1977        mut retval: MutableHandleValue,
1978    ) {
1979        let buffer = handle_potential_webgl_error!(
1980            self,
1981            buffer.ok_or(InvalidOperation),
1982            return retval.set(NullValue())
1983        );
1984
1985        retval.set(match parameter {
1986            constants::BUFFER_SIZE => Int32Value(buffer.capacity() as i32),
1987            constants::BUFFER_USAGE => Int32Value(buffer.usage() as i32),
1988            _ => {
1989                self.webgl_error(InvalidEnum);
1990                NullValue()
1991            },
1992        })
1993    }
1994}
1995
1996impl CanvasContext for WebGLRenderingContext {
1997    type ID = WebGLContextId;
1998
1999    fn context_id(&self) -> Self::ID {
2000        self.droppable.webgl_sender.context_id()
2001    }
2002
2003    fn canvas(&self) -> Option<RootedHTMLCanvasElementOrOffscreenCanvas> {
2004        Some(RootedHTMLCanvasElementOrOffscreenCanvas::from(&self.canvas))
2005    }
2006
2007    fn resize(&self) {
2008        let size = self.size().cast();
2009        let (sender, receiver) = webgl_channel().unwrap();
2010        self.droppable
2011            .webgl_sender
2012            .send_resize(size, sender)
2013            .unwrap();
2014        // FIXME(#21718) The backend is allowed to choose a size smaller than
2015        // what was requested
2016        self.size.set(size);
2017        self.reflector_
2018            .update_memory_size(self, size.cast::<usize>().area() * 4);
2019
2020        if let Err(msg) = receiver.recv().unwrap() {
2021            error!("Error resizing WebGLContext: {}", msg);
2022            return;
2023        };
2024
2025        // ClearColor needs to be restored because after a resize the GLContext is recreated
2026        // and the framebuffer is cleared using the default black transparent color.
2027        let color = self.current_clear_color.get();
2028        self.send_command(WebGLCommand::ClearColor(color.0, color.1, color.2, color.3));
2029
2030        // WebGL Spec: Scissor rect must not change if the canvas is resized.
2031        // See: webgl/conformance-1.0.3/conformance/rendering/gl-scissor-canvas-dimensions.html
2032        // NativeContext handling library changes the scissor after a resize, so we need to reset the
2033        // default scissor when the canvas was created or the last scissor that the user set.
2034        let rect = self.current_scissor.get();
2035        self.send_command(WebGLCommand::Scissor(rect.0, rect.1, rect.2, rect.3));
2036
2037        // Bound texture must not change when the canvas is resized.
2038        // Right now surfman generates a new FBO and the bound texture is changed
2039        // in order to create a new render to texture attachment.
2040        // Send a command to re-bind the TEXTURE_2D, if any.
2041        if let Some(texture) = self
2042            .textures
2043            .active_texture_slot(constants::TEXTURE_2D, self.webgl_version())
2044            .unwrap()
2045            .get()
2046        {
2047            self.send_command(WebGLCommand::BindTexture(
2048                constants::TEXTURE_2D,
2049                Some(texture.id()),
2050            ));
2051        }
2052
2053        // Bound framebuffer must not change when the canvas is resized.
2054        // Right now surfman generates a new FBO on resize.
2055        // Send a command to re-bind the framebuffer, if any.
2056        if let Some(fbo) = self.bound_draw_framebuffer.get() {
2057            let id = WebGLFramebufferBindingRequest::Explicit(fbo.id());
2058            self.send_command(WebGLCommand::BindFramebuffer(constants::FRAMEBUFFER, id));
2059        }
2060    }
2061
2062    fn reset_bitmap(&self) {
2063        warn!("The WebGLRenderingContext 'reset_bitmap' is not implemented yet");
2064    }
2065
2066    // Used by HTMLCanvasElement.toDataURL
2067    //
2068    // This emits errors quite liberally, but the spec says that this operation
2069    // can fail and that it is UB what happens in that case.
2070    //
2071    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#2.2>
2072    fn get_image_data(&self) -> Option<Snapshot> {
2073        handle_potential_webgl_error!(self, self.validate_framebuffer(), return None);
2074        let mut size = self.size().cast();
2075
2076        let (fb_width, fb_height) = handle_potential_webgl_error!(
2077            self,
2078            self.get_current_framebuffer_size().ok_or(InvalidOperation),
2079            return None
2080        );
2081        size.width = cmp::min(size.width, fb_width as u32);
2082        size.height = cmp::min(size.height, fb_height as u32);
2083
2084        let (sender, receiver) = generic_channel::channel().unwrap();
2085        self.send_command(WebGLCommand::ReadPixels(
2086            Rect::from_size(size),
2087            constants::RGBA,
2088            constants::UNSIGNED_BYTE,
2089            sender,
2090        ));
2091        let (data, alpha_mode) = receiver.recv().unwrap();
2092        Some(Snapshot::from_vec(
2093            size.cast(),
2094            SnapshotPixelFormat::RGBA,
2095            alpha_mode,
2096            data.to_vec(),
2097        ))
2098    }
2099
2100    fn mark_as_dirty(&self) {
2101        // If we have a bound framebuffer, then don't mark the canvas as dirty.
2102        if self.bound_draw_framebuffer.get().is_some() {
2103            return;
2104        }
2105
2106        // Dirtying the canvas is unnecessary if we're actively displaying immersive
2107        // XR content right now.
2108        if self.global().as_window().in_immersive_xr_session() {
2109            return;
2110        }
2111
2112        self.canvas.mark_as_dirty();
2113    }
2114}
2115
2116#[cfg(not(feature = "webgl_backtrace"))]
2117#[inline]
2118pub(crate) fn capture_webgl_backtrace() -> WebGLCommandBacktrace {
2119    WebGLCommandBacktrace {}
2120}
2121
2122#[cfg(feature = "webgl_backtrace")]
2123#[cfg_attr(feature = "webgl_backtrace", expect(unsafe_code))]
2124pub(crate) fn capture_webgl_backtrace() -> WebGLCommandBacktrace {
2125    let bt = Backtrace::new();
2126    unsafe {
2127        // TODO: https://github.com/servo/servo/issues/40600
2128        #[expect(unsafe_code)]
2129        let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
2130        capture_stack!(&in(cx) let stack);
2131        WebGLCommandBacktrace {
2132            backtrace: format!("{:?}", bt),
2133            js_backtrace: stack.and_then(|s| s.as_string(None, js::jsapi::StackFormat::Default)),
2134        }
2135    }
2136}
2137
2138impl WebGLRenderingContextMethods<crate::DomTypeHolder> for WebGLRenderingContext {
2139    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1>
2140    fn Canvas(&self) -> RootedHTMLCanvasElementOrOffscreenCanvas {
2141        RootedHTMLCanvasElementOrOffscreenCanvas::from(&self.canvas)
2142    }
2143
2144    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11>
2145    fn Flush(&self) {
2146        self.send_command(WebGLCommand::Flush);
2147    }
2148
2149    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11>
2150    fn Finish(&self) {
2151        let (sender, receiver) = webgl_channel().unwrap();
2152        self.send_command(WebGLCommand::Finish(sender));
2153        receiver.recv().unwrap()
2154    }
2155
2156    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1>
2157    fn DrawingBufferWidth(&self) -> i32 {
2158        let (sender, receiver) = webgl_channel().unwrap();
2159        self.send_command(WebGLCommand::DrawingBufferWidth(sender));
2160        receiver.recv().unwrap()
2161    }
2162
2163    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1>
2164    fn DrawingBufferHeight(&self) -> i32 {
2165        let (sender, receiver) = webgl_channel().unwrap();
2166        self.send_command(WebGLCommand::DrawingBufferHeight(sender));
2167        receiver.recv().unwrap()
2168    }
2169
2170    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
2171    fn GetBufferParameter(
2172        &self,
2173        cx: &mut JSContext,
2174        target: u32,
2175        parameter: u32,
2176        mut retval: MutableHandleValue,
2177    ) {
2178        let buffer = handle_potential_webgl_error!(
2179            self,
2180            self.bound_buffer(cx, target),
2181            return retval.set(NullValue())
2182        );
2183        self.get_buffer_param(buffer, parameter, retval)
2184    }
2185
2186    #[expect(unsafe_code)]
2187    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2188    fn GetParameter(&self, cx: &mut JSContext, parameter: u32, mut retval: MutableHandleValue) {
2189        if !self
2190            .extension_manager
2191            .is_get_parameter_name_enabled(parameter)
2192        {
2193            self.webgl_error(WebGLError::InvalidEnum);
2194            return retval.set(NullValue());
2195        }
2196
2197        match parameter {
2198            constants::ARRAY_BUFFER_BINDING => {
2199                self.bound_buffer_array.get().safe_to_jsval(cx, retval);
2200                return;
2201            },
2202            constants::CURRENT_PROGRAM => {
2203                self.current_program.get().safe_to_jsval(cx, retval);
2204                return;
2205            },
2206            constants::ELEMENT_ARRAY_BUFFER_BINDING => {
2207                let buffer = self.current_vao(cx).element_array_buffer().get();
2208                buffer.safe_to_jsval(cx, retval);
2209                return;
2210            },
2211            constants::FRAMEBUFFER_BINDING => {
2212                self.bound_draw_framebuffer.get().safe_to_jsval(cx, retval);
2213                return;
2214            },
2215            constants::RENDERBUFFER_BINDING => {
2216                self.bound_renderbuffer.get().safe_to_jsval(cx, retval);
2217                return;
2218            },
2219            constants::TEXTURE_BINDING_2D => {
2220                let texture = self
2221                    .textures
2222                    .active_texture_slot(constants::TEXTURE_2D, self.webgl_version())
2223                    .unwrap()
2224                    .get();
2225                texture.safe_to_jsval(cx, retval);
2226                return;
2227            },
2228            WebGL2RenderingContextConstants::TEXTURE_BINDING_2D_ARRAY => {
2229                let texture = self
2230                    .textures
2231                    .active_texture_slot(
2232                        WebGL2RenderingContextConstants::TEXTURE_2D_ARRAY,
2233                        self.webgl_version(),
2234                    )
2235                    .unwrap()
2236                    .get();
2237                texture.safe_to_jsval(cx, retval);
2238                return;
2239            },
2240            WebGL2RenderingContextConstants::TEXTURE_BINDING_3D => {
2241                let texture = self
2242                    .textures
2243                    .active_texture_slot(
2244                        WebGL2RenderingContextConstants::TEXTURE_3D,
2245                        self.webgl_version(),
2246                    )
2247                    .unwrap()
2248                    .get();
2249                texture.safe_to_jsval(cx, retval);
2250                return;
2251            },
2252            constants::TEXTURE_BINDING_CUBE_MAP => {
2253                let texture = self
2254                    .textures
2255                    .active_texture_slot(constants::TEXTURE_CUBE_MAP, self.webgl_version())
2256                    .unwrap()
2257                    .get();
2258                texture.safe_to_jsval(cx, retval);
2259                return;
2260            },
2261            OESVertexArrayObjectConstants::VERTEX_ARRAY_BINDING_OES => {
2262                let vao = self.current_vao.get().filter(|vao| vao.id().is_some());
2263                vao.safe_to_jsval(cx, retval);
2264                return;
2265            },
2266            // In readPixels we currently support RGBA/UBYTE only.  If
2267            // we wanted to support other formats, we could ask the
2268            // driver, but we would need to check for
2269            // GL_OES_read_format support (assuming an underlying GLES
2270            // driver. Desktop is happy to format convert for us).
2271            constants::IMPLEMENTATION_COLOR_READ_FORMAT => {
2272                if self.validate_framebuffer().is_err() {
2273                    self.webgl_error(InvalidOperation);
2274                    return retval.set(NullValue());
2275                }
2276                return retval.set(Int32Value(constants::RGBA as i32));
2277            },
2278            constants::IMPLEMENTATION_COLOR_READ_TYPE => {
2279                if self.validate_framebuffer().is_err() {
2280                    self.webgl_error(InvalidOperation);
2281                    return retval.set(NullValue());
2282                }
2283                return retval.set(Int32Value(constants::UNSIGNED_BYTE as i32));
2284            },
2285            constants::COMPRESSED_TEXTURE_FORMATS => unsafe {
2286                let format_ids = self.extension_manager.get_tex_compression_ids();
2287
2288                rooted!(&in(cx) let mut rval = ptr::null_mut::<JSObject>());
2289                Uint32Array::create(
2290                    cx.raw_cx(),
2291                    CreateWith::Slice(&format_ids),
2292                    rval.handle_mut(),
2293                )
2294                .unwrap();
2295                return retval.set(ObjectValue(rval.get()));
2296            },
2297            constants::VERSION => {
2298                "WebGL 1.0".safe_to_jsval(cx, retval);
2299                return;
2300            },
2301            constants::RENDERER | constants::VENDOR => {
2302                "Mozilla/Servo".safe_to_jsval(cx, retval);
2303                return;
2304            },
2305            constants::SHADING_LANGUAGE_VERSION => {
2306                "WebGL GLSL ES 1.0".safe_to_jsval(cx, retval);
2307                return;
2308            },
2309            constants::UNPACK_FLIP_Y_WEBGL => {
2310                let unpack = self.texture_unpacking_settings.get();
2311                retval.set(BooleanValue(unpack.contains(TextureUnpacking::FLIP_Y_AXIS)));
2312                return;
2313            },
2314            constants::UNPACK_PREMULTIPLY_ALPHA_WEBGL => {
2315                let unpack = self.texture_unpacking_settings.get();
2316                retval.set(BooleanValue(
2317                    unpack.contains(TextureUnpacking::PREMULTIPLY_ALPHA),
2318                ));
2319                return;
2320            },
2321            constants::PACK_ALIGNMENT => {
2322                retval.set(UInt32Value(self.texture_packing_alignment.get() as u32));
2323                return;
2324            },
2325            constants::UNPACK_ALIGNMENT => {
2326                retval.set(UInt32Value(self.texture_unpacking_alignment.get()));
2327                return;
2328            },
2329            constants::UNPACK_COLORSPACE_CONVERSION_WEBGL => {
2330                let unpack = self.texture_unpacking_settings.get();
2331                retval.set(UInt32Value(
2332                    if unpack.contains(TextureUnpacking::CONVERT_COLORSPACE) {
2333                        constants::BROWSER_DEFAULT_WEBGL
2334                    } else {
2335                        constants::NONE
2336                    },
2337                ));
2338                return;
2339            },
2340            _ => {},
2341        }
2342
2343        // Handle any MAX_ parameters by retrieving the limits that were stored
2344        // when this context was created.
2345        let limit = match parameter {
2346            constants::MAX_VERTEX_ATTRIBS => Some(self.limits.max_vertex_attribs),
2347            constants::MAX_TEXTURE_SIZE => Some(self.limits.max_tex_size),
2348            constants::MAX_CUBE_MAP_TEXTURE_SIZE => Some(self.limits.max_cube_map_tex_size),
2349            constants::MAX_COMBINED_TEXTURE_IMAGE_UNITS => {
2350                Some(self.limits.max_combined_texture_image_units)
2351            },
2352            constants::MAX_FRAGMENT_UNIFORM_VECTORS => {
2353                Some(self.limits.max_fragment_uniform_vectors)
2354            },
2355            constants::MAX_RENDERBUFFER_SIZE => Some(self.limits.max_renderbuffer_size),
2356            constants::MAX_TEXTURE_IMAGE_UNITS => Some(self.limits.max_texture_image_units),
2357            constants::MAX_VARYING_VECTORS => Some(self.limits.max_varying_vectors),
2358            constants::MAX_VERTEX_TEXTURE_IMAGE_UNITS => {
2359                Some(self.limits.max_vertex_texture_image_units)
2360            },
2361            constants::MAX_VERTEX_UNIFORM_VECTORS => Some(self.limits.max_vertex_uniform_vectors),
2362            _ => None,
2363        };
2364        if let Some(limit) = limit {
2365            retval.set(UInt32Value(limit));
2366            return;
2367        }
2368
2369        if let Ok(value) = self.capabilities.is_enabled(parameter) {
2370            retval.set(BooleanValue(value));
2371            return;
2372        }
2373
2374        match handle_potential_webgl_error!(
2375            self,
2376            Parameter::from_u32(parameter),
2377            return retval.set(NullValue())
2378        ) {
2379            Parameter::Bool(param) => {
2380                let (sender, receiver) = webgl_channel().unwrap();
2381                self.send_command(WebGLCommand::GetParameterBool(param, sender));
2382                retval.set(BooleanValue(receiver.recv().unwrap()))
2383            },
2384            Parameter::Bool4(param) => {
2385                let (sender, receiver) = webgl_channel().unwrap();
2386                self.send_command(WebGLCommand::GetParameterBool4(param, sender));
2387                receiver.recv().unwrap().safe_to_jsval(cx, retval);
2388            },
2389            Parameter::Int(param) => {
2390                let (sender, receiver) = webgl_channel().unwrap();
2391                self.send_command(WebGLCommand::GetParameterInt(param, sender));
2392                retval.set(Int32Value(receiver.recv().unwrap()))
2393            },
2394            Parameter::Int2(param) => unsafe {
2395                let (sender, receiver) = webgl_channel().unwrap();
2396                self.send_command(WebGLCommand::GetParameterInt2(param, sender));
2397                rooted!(&in(cx) let mut rval = ptr::null_mut::<JSObject>());
2398                Int32Array::create(
2399                    cx.raw_cx(),
2400                    CreateWith::Slice(&receiver.recv().unwrap()),
2401                    rval.handle_mut(),
2402                )
2403                .unwrap();
2404                retval.set(ObjectValue(rval.get()))
2405            },
2406            Parameter::Int4(param) => unsafe {
2407                let (sender, receiver) = webgl_channel().unwrap();
2408                self.send_command(WebGLCommand::GetParameterInt4(param, sender));
2409                rooted!(&in(cx) let mut rval = ptr::null_mut::<JSObject>());
2410                Int32Array::create(
2411                    cx.raw_cx(),
2412                    CreateWith::Slice(&receiver.recv().unwrap()),
2413                    rval.handle_mut(),
2414                )
2415                .unwrap();
2416                retval.set(ObjectValue(rval.get()))
2417            },
2418            Parameter::Float(param) => {
2419                let (sender, receiver) = webgl_channel().unwrap();
2420                self.send_command(WebGLCommand::GetParameterFloat(param, sender));
2421                retval.set(DoubleValue(receiver.recv().unwrap() as f64))
2422            },
2423            Parameter::Float2(param) => unsafe {
2424                let (sender, receiver) = webgl_channel().unwrap();
2425                self.send_command(WebGLCommand::GetParameterFloat2(param, sender));
2426                rooted!(&in(cx) let mut rval = ptr::null_mut::<JSObject>());
2427                Float32Array::create(
2428                    cx.raw_cx(),
2429                    CreateWith::Slice(&receiver.recv().unwrap()),
2430                    rval.handle_mut(),
2431                )
2432                .unwrap();
2433                retval.set(ObjectValue(rval.get()))
2434            },
2435            Parameter::Float4(param) => unsafe {
2436                let (sender, receiver) = webgl_channel().unwrap();
2437                self.send_command(WebGLCommand::GetParameterFloat4(param, sender));
2438                rooted!(&in(cx) let mut rval = ptr::null_mut::<JSObject>());
2439                Float32Array::create(
2440                    cx.raw_cx(),
2441                    CreateWith::Slice(&receiver.recv().unwrap()),
2442                    rval.handle_mut(),
2443                )
2444                .unwrap();
2445                retval.set(ObjectValue(rval.get()))
2446            },
2447        }
2448    }
2449
2450    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
2451    fn GetTexParameter(
2452        &self,
2453        _cx: &mut JSContext,
2454        target: u32,
2455        pname: u32,
2456        mut retval: MutableHandleValue,
2457    ) {
2458        let texture_slot = handle_potential_webgl_error!(
2459            self,
2460            self.textures
2461                .active_texture_slot(target, self.webgl_version()),
2462            return retval.set(NullValue())
2463        );
2464        let texture = handle_potential_webgl_error!(
2465            self,
2466            texture_slot.get().ok_or(InvalidOperation),
2467            return retval.set(NullValue())
2468        );
2469
2470        if !self
2471            .extension_manager
2472            .is_get_tex_parameter_name_enabled(pname)
2473        {
2474            self.webgl_error(InvalidEnum);
2475            return retval.set(NullValue());
2476        }
2477
2478        match pname {
2479            constants::TEXTURE_MAG_FILTER => return retval.set(UInt32Value(texture.mag_filter())),
2480            constants::TEXTURE_MIN_FILTER => return retval.set(UInt32Value(texture.min_filter())),
2481            _ => {},
2482        }
2483
2484        let texparam = handle_potential_webgl_error!(
2485            self,
2486            TexParameter::from_u32(pname),
2487            return retval.set(NullValue())
2488        );
2489        if self.webgl_version() < texparam.required_webgl_version() {
2490            self.webgl_error(InvalidEnum);
2491            return retval.set(NullValue());
2492        }
2493
2494        if let Some(value) = texture.maybe_get_tex_parameter(texparam) {
2495            match value {
2496                TexParameterValue::Float(v) => retval.set(DoubleValue(v as f64)),
2497                TexParameterValue::Int(v) => retval.set(Int32Value(v)),
2498                TexParameterValue::Bool(v) => retval.set(BooleanValue(v)),
2499            }
2500            return;
2501        }
2502
2503        match texparam {
2504            TexParameter::Float(param) => {
2505                let (sender, receiver) = webgl_channel().unwrap();
2506                self.send_command(WebGLCommand::GetTexParameterFloat(target, param, sender));
2507                retval.set(DoubleValue(receiver.recv().unwrap() as f64))
2508            },
2509            TexParameter::Int(param) => {
2510                let (sender, receiver) = webgl_channel().unwrap();
2511                self.send_command(WebGLCommand::GetTexParameterInt(target, param, sender));
2512                retval.set(Int32Value(receiver.recv().unwrap()))
2513            },
2514            TexParameter::Bool(param) => {
2515                let (sender, receiver) = webgl_channel().unwrap();
2516                self.send_command(WebGLCommand::GetTexParameterBool(target, param, sender));
2517                retval.set(BooleanValue(receiver.recv().unwrap()))
2518            },
2519        }
2520    }
2521
2522    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2523    fn GetError(&self) -> u32 {
2524        let error_code = if let Some(error) = self.last_error.get() {
2525            match error {
2526                WebGLError::InvalidEnum => constants::INVALID_ENUM,
2527                WebGLError::InvalidFramebufferOperation => constants::INVALID_FRAMEBUFFER_OPERATION,
2528                WebGLError::InvalidValue => constants::INVALID_VALUE,
2529                WebGLError::InvalidOperation => constants::INVALID_OPERATION,
2530                WebGLError::OutOfMemory => constants::OUT_OF_MEMORY,
2531                WebGLError::ContextLost => constants::CONTEXT_LOST_WEBGL,
2532            }
2533        } else {
2534            constants::NO_ERROR
2535        };
2536        self.last_error.set(None);
2537        error_code
2538    }
2539
2540    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.2>
2541    fn GetContextAttributes(&self) -> Option<WebGLContextAttributes> {
2542        let (sender, receiver) = webgl_channel().unwrap();
2543
2544        // If the send does not succeed, assume context lost
2545        let backtrace = capture_webgl_backtrace();
2546        if self
2547            .droppable
2548            .webgl_sender
2549            .send(WebGLCommand::GetContextAttributes(sender), backtrace)
2550            .is_err()
2551        {
2552            return None;
2553        }
2554
2555        let attrs = receiver.recv().unwrap();
2556
2557        Some(WebGLContextAttributes {
2558            alpha: attrs.alpha,
2559            antialias: attrs.antialias,
2560            depth: attrs.depth,
2561            failIfMajorPerformanceCaveat: false,
2562            preferLowPowerToHighPerformance: false,
2563            premultipliedAlpha: attrs.premultiplied_alpha,
2564            preserveDrawingBuffer: attrs.preserve_drawing_buffer,
2565            stencil: attrs.stencil,
2566        })
2567    }
2568
2569    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.13>
2570    fn IsContextLost(&self) -> bool {
2571        false
2572    }
2573
2574    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14>
2575    fn GetSupportedExtensions(&self) -> Option<Vec<DOMString>> {
2576        self.extension_manager
2577            .init_once(|| self.get_gl_extensions());
2578        let extensions = self.extension_manager.get_supported_extensions();
2579        Some(
2580            extensions
2581                .iter()
2582                .map(|name| DOMString::from(*name))
2583                .collect(),
2584        )
2585    }
2586
2587    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14>
2588    fn GetExtension(
2589        &self,
2590        cx: &mut js::context::JSContext,
2591        name: DOMString,
2592        mut return_value: MutableHandleObject,
2593    ) {
2594        self.extension_manager
2595            .init_once(|| self.get_gl_extensions());
2596        return_value.set(
2597            self.extension_manager
2598                .get_or_init_extension(cx, &name, self)
2599                .map(|nonnull| nonnull.as_ptr())
2600                .unwrap_or(ptr::null_mut()),
2601        );
2602    }
2603
2604    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2605    fn ActiveTexture(&self, texture: u32) {
2606        handle_potential_webgl_error!(self, self.textures.set_active_unit_enum(texture), return);
2607        self.send_command(WebGLCommand::ActiveTexture(texture));
2608    }
2609
2610    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2611    fn BlendColor(&self, r: f32, g: f32, b: f32, a: f32) {
2612        self.send_command(WebGLCommand::BlendColor(r, g, b, a));
2613    }
2614
2615    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2616    fn BlendEquation(&self, mode: u32) {
2617        handle_potential_webgl_error!(self, self.validate_blend_mode(mode), return);
2618        self.send_command(WebGLCommand::BlendEquation(mode))
2619    }
2620
2621    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2622    fn BlendEquationSeparate(&self, mode_rgb: u32, mode_alpha: u32) {
2623        handle_potential_webgl_error!(self, self.validate_blend_mode(mode_rgb), return);
2624        handle_potential_webgl_error!(self, self.validate_blend_mode(mode_alpha), return);
2625        self.send_command(WebGLCommand::BlendEquationSeparate(mode_rgb, mode_alpha));
2626    }
2627
2628    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2629    fn BlendFunc(&self, src_factor: u32, dest_factor: u32) {
2630        // From the WebGL 1.0 spec, 6.13: Viewport Depth Range:
2631        //
2632        //     A call to blendFunc will generate an INVALID_OPERATION error if one of the two
2633        //     factors is set to CONSTANT_COLOR or ONE_MINUS_CONSTANT_COLOR and the other to
2634        //     CONSTANT_ALPHA or ONE_MINUS_CONSTANT_ALPHA.
2635        if has_invalid_blend_constants(src_factor, dest_factor) {
2636            return self.webgl_error(InvalidOperation);
2637        }
2638        if has_invalid_blend_constants(dest_factor, src_factor) {
2639            return self.webgl_error(InvalidOperation);
2640        }
2641
2642        self.send_command(WebGLCommand::BlendFunc(src_factor, dest_factor));
2643    }
2644
2645    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
2646    fn BlendFuncSeparate(&self, src_rgb: u32, dest_rgb: u32, src_alpha: u32, dest_alpha: u32) {
2647        // From the WebGL 1.0 spec, 6.13: Viewport Depth Range:
2648        //
2649        //     A call to blendFuncSeparate will generate an INVALID_OPERATION error if srcRGB is
2650        //     set to CONSTANT_COLOR or ONE_MINUS_CONSTANT_COLOR and dstRGB is set to
2651        //     CONSTANT_ALPHA or ONE_MINUS_CONSTANT_ALPHA or vice versa.
2652        if has_invalid_blend_constants(src_rgb, dest_rgb) {
2653            return self.webgl_error(InvalidOperation);
2654        }
2655        if has_invalid_blend_constants(dest_rgb, src_rgb) {
2656            return self.webgl_error(InvalidOperation);
2657        }
2658
2659        self.send_command(WebGLCommand::BlendFuncSeparate(
2660            src_rgb, dest_rgb, src_alpha, dest_alpha,
2661        ));
2662    }
2663
2664    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2665    fn AttachShader(&self, program: &WebGLProgram, shader: &WebGLShader) {
2666        handle_potential_webgl_error!(self, self.validate_ownership(program), return);
2667        handle_potential_webgl_error!(self, self.validate_ownership(shader), return);
2668        handle_potential_webgl_error!(self, program.attach_shader(shader));
2669    }
2670
2671    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2672    fn DetachShader(&self, program: &WebGLProgram, shader: &WebGLShader) {
2673        handle_potential_webgl_error!(self, self.validate_ownership(program), return);
2674        handle_potential_webgl_error!(self, self.validate_ownership(shader), return);
2675        handle_potential_webgl_error!(self, program.detach_shader(shader));
2676    }
2677
2678    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
2679    fn BindAttribLocation(&self, program: &WebGLProgram, index: u32, name: DOMString) {
2680        handle_potential_webgl_error!(self, self.validate_ownership(program), return);
2681        handle_potential_webgl_error!(self, program.bind_attrib_location(index, name));
2682    }
2683
2684    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
2685    fn BindBuffer(&self, cx: &mut JSContext, target: u32, buffer: Option<&WebGLBuffer>) {
2686        let current_vao;
2687        let slot = match target {
2688            constants::ARRAY_BUFFER => &self.bound_buffer_array,
2689            constants::ELEMENT_ARRAY_BUFFER => {
2690                current_vao = self.current_vao(cx);
2691                current_vao.element_array_buffer()
2692            },
2693            _ => return self.webgl_error(InvalidEnum),
2694        };
2695        self.bind_buffer_maybe(slot, target, buffer);
2696    }
2697
2698    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
2699    fn BindFramebuffer(&self, target: u32, framebuffer: Option<&WebGLFramebuffer>) {
2700        handle_potential_webgl_error!(
2701            self,
2702            self.validate_new_framebuffer_binding(framebuffer),
2703            return
2704        );
2705
2706        if target != constants::FRAMEBUFFER {
2707            return self.webgl_error(InvalidEnum);
2708        }
2709
2710        self.bind_framebuffer_to(target, framebuffer, &self.bound_draw_framebuffer)
2711    }
2712
2713    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
2714    fn BindRenderbuffer(&self, target: u32, renderbuffer: Option<&WebGLRenderbuffer>) {
2715        if let Some(rb) = renderbuffer {
2716            handle_potential_webgl_error!(self, self.validate_ownership(rb), return);
2717        }
2718
2719        if target != constants::RENDERBUFFER {
2720            return self.webgl_error(InvalidEnum);
2721        }
2722
2723        match renderbuffer {
2724            // Implementations differ on what to do in the deleted
2725            // case: Chromium currently unbinds, and Gecko silently
2726            // returns.  The conformance tests don't cover this case.
2727            Some(renderbuffer) if !renderbuffer.is_deleted() => {
2728                self.bound_renderbuffer.set(Some(renderbuffer));
2729                renderbuffer.bind(target);
2730            },
2731            _ => {
2732                if renderbuffer.is_some() {
2733                    self.webgl_error(InvalidOperation);
2734                }
2735
2736                self.bound_renderbuffer.set(None);
2737                // Unbind the currently bound renderbuffer
2738                self.send_command(WebGLCommand::BindRenderbuffer(target, None));
2739            },
2740        }
2741    }
2742
2743    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
2744    fn BindTexture(&self, target: u32, texture: Option<&WebGLTexture>) {
2745        if let Some(texture) = texture {
2746            handle_potential_webgl_error!(self, self.validate_ownership(texture), return);
2747        }
2748
2749        let texture_slot = handle_potential_webgl_error!(
2750            self,
2751            self.textures
2752                .active_texture_slot(target, self.webgl_version()),
2753            return
2754        );
2755
2756        if let Some(texture) = texture {
2757            handle_potential_webgl_error!(self, texture.bind(target), return);
2758        } else {
2759            self.send_command(WebGLCommand::BindTexture(target, None));
2760        }
2761        texture_slot.set(texture);
2762    }
2763
2764    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
2765    fn GenerateMipmap(&self, target: u32) {
2766        let texture_slot = handle_potential_webgl_error!(
2767            self,
2768            self.textures
2769                .active_texture_slot(target, self.webgl_version()),
2770            return
2771        );
2772        let texture =
2773            handle_potential_webgl_error!(self, texture_slot.get().ok_or(InvalidOperation), return);
2774        handle_potential_webgl_error!(self, texture.generate_mipmap());
2775    }
2776
2777    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
2778    fn BufferData_(
2779        &self,
2780        cx: &mut JSContext,
2781        target: u32,
2782        data: Option<ArrayBufferViewOrArrayBuffer>,
2783        usage: u32,
2784    ) {
2785        let usage = handle_potential_webgl_error!(self, self.buffer_usage(usage), return);
2786        let bound_buffer =
2787            handle_potential_webgl_error!(self, self.bound_buffer(cx, target), return);
2788        self.buffer_data(cx.no_gc(), target, data, usage, bound_buffer)
2789    }
2790
2791    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
2792    fn BufferData(&self, cx: &mut JSContext, target: u32, size: i64, usage: u32) {
2793        let usage = handle_potential_webgl_error!(self, self.buffer_usage(usage), return);
2794        let bound_buffer =
2795            handle_potential_webgl_error!(self, self.bound_buffer(cx, target), return);
2796        self.buffer_data_(target, size, usage, bound_buffer)
2797    }
2798
2799    // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5
2800    fn BufferSubData(
2801        &self,
2802        cx: &mut JSContext,
2803        target: u32,
2804        offset: i64,
2805        data: ArrayBufferViewOrArrayBuffer,
2806    ) {
2807        let bound_buffer =
2808            handle_potential_webgl_error!(self, self.bound_buffer(cx, target), return);
2809        self.buffer_sub_data(cx.no_gc(), target, offset, data, bound_buffer)
2810    }
2811
2812    // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8
2813    fn CompressedTexImage2D(
2814        &self,
2815        no_gc: &NoGC,
2816        target: u32,
2817        level: i32,
2818        internal_format: u32,
2819        width: i32,
2820        height: i32,
2821        border: i32,
2822        data: CustomAutoRooterGuard<ArrayBufferView>,
2823    ) {
2824        let data = data.as_slice_safe(no_gc).unwrap_or(&[]);
2825        self.compressed_tex_image_2d(target, level, internal_format, width, height, border, data)
2826    }
2827
2828    // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8
2829    fn CompressedTexSubImage2D(
2830        &self,
2831        no_gc: &NoGC,
2832        target: u32,
2833        level: i32,
2834        xoffset: i32,
2835        yoffset: i32,
2836        width: i32,
2837        height: i32,
2838        format: u32,
2839        data: CustomAutoRooterGuard<ArrayBufferView>,
2840    ) {
2841        let data = data.as_slice_safe(no_gc).unwrap_or(&[]);
2842        self.compressed_tex_sub_image_2d(
2843            target, level, xoffset, yoffset, width, height, format, data,
2844        )
2845    }
2846
2847    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
2848    fn CopyTexImage2D(
2849        &self,
2850        target: u32,
2851        level: i32,
2852        internal_format: u32,
2853        x: i32,
2854        y: i32,
2855        width: i32,
2856        height: i32,
2857        border: i32,
2858    ) {
2859        handle_potential_webgl_error!(self, self.validate_framebuffer(), return);
2860
2861        let validator = CommonTexImage2DValidator::new(
2862            self,
2863            target,
2864            level,
2865            internal_format,
2866            width,
2867            height,
2868            border,
2869        );
2870        let CommonTexImage2DValidatorResult {
2871            texture,
2872            target,
2873            level,
2874            internal_format,
2875            width,
2876            height,
2877            border,
2878        } = match validator.validate() {
2879            Ok(result) => result,
2880            Err(_) => return,
2881        };
2882
2883        if texture.is_immutable() {
2884            return self.webgl_error(InvalidOperation);
2885        }
2886
2887        let framebuffer_format = match self.bound_draw_framebuffer.get() {
2888            Some(fb) => match fb.attachment(constants::COLOR_ATTACHMENT0) {
2889                Some(WebGLFramebufferAttachmentRoot::Renderbuffer(rb)) => {
2890                    TexFormat::from_gl_constant(rb.internal_format())
2891                },
2892                Some(WebGLFramebufferAttachmentRoot::Texture(texture)) => texture
2893                    .image_info_for_target(&target, 0)
2894                    .map(|info| info.internal_format()),
2895                None => None,
2896            },
2897            None => {
2898                let attrs = self.GetContextAttributes().unwrap();
2899                Some(if attrs.alpha {
2900                    TexFormat::RGBA
2901                } else {
2902                    TexFormat::RGB
2903                })
2904            },
2905        };
2906
2907        let framebuffer_format = match framebuffer_format {
2908            Some(f) => f,
2909            None => {
2910                self.webgl_error(InvalidOperation);
2911                return;
2912            },
2913        };
2914
2915        match (framebuffer_format, internal_format) {
2916            (a, b) if a == b => (),
2917            (TexFormat::RGBA, TexFormat::RGB) => (),
2918            (TexFormat::RGBA, TexFormat::Alpha) => (),
2919            (TexFormat::RGBA, TexFormat::Luminance) => (),
2920            (TexFormat::RGBA, TexFormat::LuminanceAlpha) => (),
2921            (TexFormat::RGB, TexFormat::Luminance) => (),
2922            _ => {
2923                self.webgl_error(InvalidOperation);
2924                return;
2925            },
2926        }
2927
2928        // NB: TexImage2D depth is always equal to 1
2929        handle_potential_webgl_error!(
2930            self,
2931            texture.initialize(target, width, height, 1, internal_format, level, None)
2932        );
2933
2934        let msg = WebGLCommand::CopyTexImage2D(
2935            target.as_gl_constant(),
2936            level as i32,
2937            internal_format.as_gl_constant(),
2938            x,
2939            y,
2940            width as i32,
2941            height as i32,
2942            border as i32,
2943        );
2944
2945        self.send_command(msg);
2946
2947        if let Some(framebuffer) = self.bound_draw_framebuffer.get() {
2948            framebuffer.invalidate_texture(&texture);
2949        }
2950    }
2951
2952    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
2953    fn CopyTexSubImage2D(
2954        &self,
2955        target: u32,
2956        level: i32,
2957        xoffset: i32,
2958        yoffset: i32,
2959        x: i32,
2960        y: i32,
2961        width: i32,
2962        height: i32,
2963    ) {
2964        handle_potential_webgl_error!(self, self.validate_framebuffer(), return);
2965
2966        // NB: We use a dummy (valid) format and border in order to reuse the
2967        // common validations, but this should have its own validator.
2968        let validator = CommonTexImage2DValidator::new(
2969            self,
2970            target,
2971            level,
2972            TexFormat::RGBA.as_gl_constant(),
2973            width,
2974            height,
2975            0,
2976        );
2977        let CommonTexImage2DValidatorResult {
2978            texture,
2979            target,
2980            level,
2981            width,
2982            height,
2983            ..
2984        } = match validator.validate() {
2985            Ok(result) => result,
2986            Err(_) => return,
2987        };
2988
2989        let image_info = match texture.image_info_for_target(&target, level) {
2990            Some(info) => info,
2991            None => return self.webgl_error(InvalidOperation),
2992        };
2993
2994        // GL_INVALID_VALUE is generated if:
2995        //   - xoffset or yoffset is less than 0
2996        //   - x offset plus the width is greater than the texture width
2997        //   - y offset plus the height is greater than the texture height
2998        if xoffset < 0 ||
2999            (xoffset as u32 + width) > image_info.width() ||
3000            yoffset < 0 ||
3001            (yoffset as u32 + height) > image_info.height()
3002        {
3003            self.webgl_error(InvalidValue);
3004            return;
3005        }
3006
3007        let msg = WebGLCommand::CopyTexSubImage2D(
3008            target.as_gl_constant(),
3009            level as i32,
3010            xoffset,
3011            yoffset,
3012            x,
3013            y,
3014            width as i32,
3015            height as i32,
3016        );
3017
3018        self.send_command(msg);
3019    }
3020
3021    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11>
3022    fn Clear(&self, mask: u32) {
3023        handle_potential_webgl_error!(self, self.validate_framebuffer(), return);
3024        if mask &
3025            !(constants::DEPTH_BUFFER_BIT |
3026                constants::STENCIL_BUFFER_BIT |
3027                constants::COLOR_BUFFER_BIT) !=
3028            0
3029        {
3030            return self.webgl_error(InvalidValue);
3031        }
3032
3033        self.send_command(WebGLCommand::Clear(mask));
3034        self.mark_as_dirty();
3035    }
3036
3037    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3038    fn ClearColor(&self, red: f32, green: f32, blue: f32, alpha: f32) {
3039        self.current_clear_color.set((red, green, blue, alpha));
3040        self.send_command(WebGLCommand::ClearColor(red, green, blue, alpha));
3041    }
3042
3043    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3044    fn ClearDepth(&self, depth: f32) {
3045        self.send_command(WebGLCommand::ClearDepth(depth))
3046    }
3047
3048    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3049    fn ClearStencil(&self, stencil: i32) {
3050        self.send_command(WebGLCommand::ClearStencil(stencil))
3051    }
3052
3053    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3054    fn ColorMask(&self, r: bool, g: bool, b: bool, a: bool) {
3055        self.send_command(WebGLCommand::ColorMask(r, g, b, a))
3056    }
3057
3058    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3059    fn CullFace(&self, mode: u32) {
3060        match mode {
3061            constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => {
3062                self.send_command(WebGLCommand::CullFace(mode))
3063            },
3064            _ => self.webgl_error(InvalidEnum),
3065        }
3066    }
3067
3068    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3069    fn FrontFace(&self, mode: u32) {
3070        match mode {
3071            constants::CW | constants::CCW => self.send_command(WebGLCommand::FrontFace(mode)),
3072            _ => self.webgl_error(InvalidEnum),
3073        }
3074    }
3075    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3076    fn DepthFunc(&self, func: u32) {
3077        match func {
3078            constants::NEVER |
3079            constants::LESS |
3080            constants::EQUAL |
3081            constants::LEQUAL |
3082            constants::GREATER |
3083            constants::NOTEQUAL |
3084            constants::GEQUAL |
3085            constants::ALWAYS => self.send_command(WebGLCommand::DepthFunc(func)),
3086            _ => self.webgl_error(InvalidEnum),
3087        }
3088    }
3089
3090    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3091    fn DepthMask(&self, flag: bool) {
3092        self.send_command(WebGLCommand::DepthMask(flag))
3093    }
3094
3095    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3096    fn DepthRange(&self, near: f32, far: f32) {
3097        // https://www.khronos.org/registry/webgl/specs/latest/1.0/#VIEWPORT_DEPTH_RANGE
3098        if near > far {
3099            return self.webgl_error(InvalidOperation);
3100        }
3101        self.send_command(WebGLCommand::DepthRange(near, far))
3102    }
3103
3104    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3105    fn Enable(&self, cap: u32) {
3106        if handle_potential_webgl_error!(self, self.capabilities.set(cap, true), return) {
3107            self.send_command(WebGLCommand::Enable(cap));
3108        }
3109    }
3110
3111    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3112    fn Disable(&self, cap: u32) {
3113        if handle_potential_webgl_error!(self, self.capabilities.set(cap, false), return) {
3114            self.send_command(WebGLCommand::Disable(cap));
3115        }
3116    }
3117
3118    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3119    fn CompileShader(&self, shader: &WebGLShader) {
3120        handle_potential_webgl_error!(self, self.validate_ownership(shader), return);
3121        handle_potential_webgl_error!(
3122            self,
3123            shader.compile(
3124                self.api_type,
3125                self.webgl_version,
3126                self.glsl_version,
3127                &self.limits,
3128                &self.extension_manager,
3129            )
3130        )
3131    }
3132
3133    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
3134    fn CreateBuffer(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLBuffer>> {
3135        WebGLBuffer::maybe_new(cx, self)
3136    }
3137
3138    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
3139    fn CreateFramebuffer(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLFramebuffer>> {
3140        WebGLFramebuffer::maybe_new(cx, self)
3141    }
3142
3143    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
3144    fn CreateRenderbuffer(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLRenderbuffer>> {
3145        WebGLRenderbuffer::maybe_new(cx, self)
3146    }
3147
3148    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
3149    fn CreateTexture(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLTexture>> {
3150        WebGLTexture::maybe_new(cx, self)
3151    }
3152
3153    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3154    fn CreateProgram(&self, cx: &mut JSContext) -> Option<DomRoot<WebGLProgram>> {
3155        WebGLProgram::maybe_new(cx, self)
3156    }
3157
3158    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3159    fn CreateShader(&self, cx: &mut JSContext, shader_type: u32) -> Option<DomRoot<WebGLShader>> {
3160        match shader_type {
3161            constants::VERTEX_SHADER | constants::FRAGMENT_SHADER => {},
3162            _ => {
3163                self.webgl_error(InvalidEnum);
3164                return None;
3165            },
3166        }
3167        WebGLShader::maybe_new(cx, self, shader_type)
3168    }
3169
3170    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
3171    fn DeleteBuffer(&self, cx: &mut JSContext, buffer: Option<&WebGLBuffer>) {
3172        let buffer = match buffer {
3173            Some(buffer) => buffer,
3174            None => return,
3175        };
3176        handle_potential_webgl_error!(self, self.validate_ownership(buffer), return);
3177        if buffer.is_marked_for_deletion() {
3178            return;
3179        }
3180        self.current_vao(cx).unbind_buffer(buffer);
3181        if self.bound_buffer_array.get().is_some_and(|b| buffer == &*b) {
3182            self.bound_buffer_array.set(None);
3183            buffer.decrement_attached_counter(Operation::Infallible);
3184        }
3185        buffer.mark_for_deletion(Operation::Infallible);
3186    }
3187
3188    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
3189    fn DeleteFramebuffer(&self, framebuffer: Option<&WebGLFramebuffer>) {
3190        if let Some(framebuffer) = framebuffer {
3191            // https://immersive-web.github.io/webxr/#opaque-framebuffer
3192            // Can opaque framebuffers be deleted?
3193            // https://github.com/immersive-web/webxr/issues/855
3194            handle_potential_webgl_error!(self, framebuffer.validate_transparent(), return);
3195            handle_potential_webgl_error!(self, self.validate_ownership(framebuffer), return);
3196            if let Some(bound_object) = self.bound_draw_framebuffer.get() &&
3197                bound_object.id() == framebuffer.id()
3198            {
3199                self.bound_draw_framebuffer.set(None);
3200                self.send_command(WebGLCommand::BindFramebuffer(
3201                    framebuffer.target().unwrap(),
3202                    WebGLFramebufferBindingRequest::Default,
3203                ));
3204            }
3205            framebuffer.delete(Operation::Infallible)
3206        }
3207    }
3208
3209    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
3210    fn DeleteRenderbuffer(&self, renderbuffer: Option<&WebGLRenderbuffer>) {
3211        if let Some(renderbuffer) = renderbuffer {
3212            handle_potential_webgl_error!(self, self.validate_ownership(renderbuffer), return);
3213            if let Some(bound_object) = self.bound_renderbuffer.get() &&
3214                bound_object.id() == renderbuffer.id()
3215            {
3216                self.bound_renderbuffer.set(None);
3217                self.send_command(WebGLCommand::BindRenderbuffer(
3218                    constants::RENDERBUFFER,
3219                    None,
3220                ));
3221            }
3222            renderbuffer.delete(Operation::Infallible)
3223        }
3224    }
3225
3226    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
3227    fn DeleteTexture(&self, texture: Option<&WebGLTexture>) {
3228        if let Some(texture) = texture {
3229            handle_potential_webgl_error!(self, self.validate_ownership(texture), return);
3230
3231            // From the GLES 2.0.25 spec, page 85:
3232            //
3233            //     "If a texture that is currently bound to one of the targets
3234            //      TEXTURE_2D, or TEXTURE_CUBE_MAP is deleted, it is as though
3235            //      BindTexture had been executed with the same target and texture
3236            //      zero."
3237            //
3238            // The same texture may be bound to multiple texture units.
3239            let mut active_unit_enum = self.textures.active_unit_enum();
3240            for (unit_enum, slot) in self.textures.iter() {
3241                if let Some(target) = slot.unbind(texture) {
3242                    if unit_enum != active_unit_enum {
3243                        self.send_command(WebGLCommand::ActiveTexture(unit_enum));
3244                        active_unit_enum = unit_enum;
3245                    }
3246                    self.send_command(WebGLCommand::BindTexture(target, None));
3247                }
3248            }
3249
3250            // Restore bound texture unit if it has been changed.
3251            if active_unit_enum != self.textures.active_unit_enum() {
3252                self.send_command(WebGLCommand::ActiveTexture(
3253                    self.textures.active_unit_enum(),
3254                ));
3255            }
3256
3257            texture.delete(Operation::Infallible)
3258        }
3259    }
3260
3261    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3262    fn DeleteProgram(&self, program: Option<&WebGLProgram>) {
3263        if let Some(program) = program {
3264            handle_potential_webgl_error!(self, self.validate_ownership(program), return);
3265            program.mark_for_deletion(Operation::Infallible)
3266        }
3267    }
3268
3269    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3270    fn DeleteShader(&self, shader: Option<&WebGLShader>) {
3271        if let Some(shader) = shader {
3272            handle_potential_webgl_error!(self, self.validate_ownership(shader), return);
3273            shader.mark_for_deletion(Operation::Infallible)
3274        }
3275    }
3276
3277    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11>
3278    fn DrawArrays(&self, cx: &mut JSContext, mode: u32, first: i32, count: i32) {
3279        handle_potential_webgl_error!(self, self.draw_arrays_instanced(cx, mode, first, count, 1));
3280    }
3281
3282    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11>
3283    fn DrawElements(&self, cx: &mut JSContext, mode: u32, count: i32, type_: u32, offset: i64) {
3284        handle_potential_webgl_error!(
3285            self,
3286            self.draw_elements_instanced(cx, mode, count, type_, offset, 1)
3287        );
3288    }
3289
3290    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3291    fn EnableVertexAttribArray(&self, cx: &mut JSContext, attrib_id: u32) {
3292        if attrib_id >= self.limits.max_vertex_attribs {
3293            return self.webgl_error(InvalidValue);
3294        }
3295        match self.webgl_version() {
3296            WebGLVersion::WebGL1 => self
3297                .current_vao(cx)
3298                .enabled_vertex_attrib_array(attrib_id, true),
3299            WebGLVersion::WebGL2 => self
3300                .current_vao_webgl2(cx)
3301                .enabled_vertex_attrib_array(attrib_id, true),
3302        };
3303        self.send_command(WebGLCommand::EnableVertexAttribArray(attrib_id));
3304    }
3305
3306    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3307    fn DisableVertexAttribArray(&self, cx: &mut JSContext, attrib_id: u32) {
3308        if attrib_id >= self.limits.max_vertex_attribs {
3309            return self.webgl_error(InvalidValue);
3310        }
3311        match self.webgl_version() {
3312            WebGLVersion::WebGL1 => self
3313                .current_vao(cx)
3314                .enabled_vertex_attrib_array(attrib_id, false),
3315            WebGLVersion::WebGL2 => self
3316                .current_vao_webgl2(cx)
3317                .enabled_vertex_attrib_array(attrib_id, false),
3318        };
3319        self.send_command(WebGLCommand::DisableVertexAttribArray(attrib_id));
3320    }
3321
3322    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3323    fn GetActiveUniform(
3324        &self,
3325        cx: &mut JSContext,
3326        program: &WebGLProgram,
3327        index: u32,
3328    ) -> Option<DomRoot<WebGLActiveInfo>> {
3329        handle_potential_webgl_error!(self, self.validate_ownership(program), return None);
3330        match program.get_active_uniform(cx, index) {
3331            Ok(ret) => Some(ret),
3332            Err(e) => {
3333                self.webgl_error(e);
3334                None
3335            },
3336        }
3337    }
3338
3339    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3340    fn GetActiveAttrib(
3341        &self,
3342        cx: &mut JSContext,
3343        program: &WebGLProgram,
3344        index: u32,
3345    ) -> Option<DomRoot<WebGLActiveInfo>> {
3346        handle_potential_webgl_error!(self, self.validate_ownership(program), return None);
3347        handle_potential_webgl_error!(self, program.get_active_attrib(cx, index).map(Some), None)
3348    }
3349
3350    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3351    fn GetAttribLocation(&self, program: &WebGLProgram, name: DOMString) -> i32 {
3352        handle_potential_webgl_error!(self, self.validate_ownership(program), return -1);
3353        handle_potential_webgl_error!(self, program.get_attrib_location(name), -1)
3354    }
3355
3356    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
3357    fn GetFramebufferAttachmentParameter(
3358        &self,
3359        cx: &mut JSContext,
3360        target: u32,
3361        attachment: u32,
3362        pname: u32,
3363        mut retval: MutableHandleValue,
3364    ) {
3365        // Check if currently bound framebuffer is non-zero as per spec.
3366        if let Some(fb) = self.bound_draw_framebuffer.get() {
3367            // Opaque framebuffers cannot have their attachments inspected
3368            // https://immersive-web.github.io/webxr/#opaque-framebuffer
3369            handle_potential_webgl_error!(
3370                self,
3371                fb.validate_transparent(),
3372                return retval.set(NullValue())
3373            );
3374        } else {
3375            self.webgl_error(InvalidOperation);
3376            return retval.set(NullValue());
3377        }
3378
3379        // Note: commented out stuff is for the WebGL2 standard.
3380        let target_matches = match target {
3381            // constants::READ_FRAMEBUFFER |
3382            // constants::DRAW_FRAMEBUFFER => true,
3383            constants::FRAMEBUFFER => true,
3384            _ => false,
3385        };
3386        let attachment_matches = match attachment {
3387            // constants::MAX_COLOR_ATTACHMENTS ... gl::COLOR_ATTACHMENT0 |
3388            // constants::BACK |
3389            constants::COLOR_ATTACHMENT0 |
3390            constants::DEPTH_STENCIL_ATTACHMENT |
3391            constants::DEPTH_ATTACHMENT |
3392            constants::STENCIL_ATTACHMENT => true,
3393            _ => false,
3394        };
3395        let pname_matches = match pname {
3396            // constants::FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE |
3397            // constants::FRAMEBUFFER_ATTACHMENT_BLUE_SIZE |
3398            // constants::FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING |
3399            // constants::FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE |
3400            // constants::FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE |
3401            // constants::FRAMEBUFFER_ATTACHMENT_GREEN_SIZE |
3402            // constants::FRAMEBUFFER_ATTACHMENT_RED_SIZE |
3403            // constants::FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE |
3404            // constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER |
3405            constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME |
3406            constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE |
3407            constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE |
3408            constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL => true,
3409            _ => false,
3410        };
3411
3412        let bound_attachment_matches = match self
3413            .bound_draw_framebuffer
3414            .get()
3415            .unwrap()
3416            .attachment(attachment)
3417        {
3418            Some(attachment_root) => match attachment_root {
3419                WebGLFramebufferAttachmentRoot::Renderbuffer(_) => matches!(
3420                    pname,
3421                    constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE |
3422                        constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME
3423                ),
3424                WebGLFramebufferAttachmentRoot::Texture(_) => matches!(
3425                    pname,
3426                    constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE |
3427                        constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME |
3428                        constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL |
3429                        constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE
3430                ),
3431            },
3432            _ => matches!(pname, constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE),
3433        };
3434
3435        if !target_matches || !attachment_matches || !pname_matches || !bound_attachment_matches {
3436            self.webgl_error(InvalidEnum);
3437            return retval.set(NullValue());
3438        }
3439
3440        // From the GLES2 spec:
3441        //
3442        //     If the value of FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is NONE,
3443        //     then querying any other pname will generate INVALID_ENUM.
3444        //
3445        // otherwise, return `WebGLRenderbuffer` or `WebGLTexture` dom object
3446        if pname == constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME {
3447            // if fb is None, an INVALID_OPERATION is returned
3448            // at the beggining of the function, so `.unwrap()` will never panic
3449            let fb = self.bound_draw_framebuffer.get().unwrap();
3450            if let Some(webgl_attachment) = fb.attachment(attachment) {
3451                match webgl_attachment {
3452                    WebGLFramebufferAttachmentRoot::Renderbuffer(rb) => {
3453                        rb.safe_to_jsval(cx, retval);
3454                        return;
3455                    },
3456                    WebGLFramebufferAttachmentRoot::Texture(texture) => {
3457                        texture.safe_to_jsval(cx, retval);
3458                        return;
3459                    },
3460                }
3461            }
3462            self.webgl_error(InvalidEnum);
3463            return retval.set(NullValue());
3464        }
3465
3466        let (sender, receiver) = webgl_channel().unwrap();
3467        self.send_command(WebGLCommand::GetFramebufferAttachmentParameter(
3468            target, attachment, pname, sender,
3469        ));
3470
3471        retval.set(Int32Value(receiver.recv().unwrap()))
3472    }
3473
3474    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
3475    fn GetRenderbufferParameter(
3476        &self,
3477        _cx: &mut JSContext,
3478        target: u32,
3479        pname: u32,
3480        mut retval: MutableHandleValue,
3481    ) {
3482        // We do not check to see if the renderbuffer came from an opaque framebuffer
3483        // https://github.com/immersive-web/webxr/issues/862
3484        let target_matches = target == constants::RENDERBUFFER;
3485
3486        let pname_matches = matches!(
3487            pname,
3488            constants::RENDERBUFFER_WIDTH |
3489                constants::RENDERBUFFER_HEIGHT |
3490                constants::RENDERBUFFER_INTERNAL_FORMAT |
3491                constants::RENDERBUFFER_RED_SIZE |
3492                constants::RENDERBUFFER_GREEN_SIZE |
3493                constants::RENDERBUFFER_BLUE_SIZE |
3494                constants::RENDERBUFFER_ALPHA_SIZE |
3495                constants::RENDERBUFFER_DEPTH_SIZE |
3496                constants::RENDERBUFFER_STENCIL_SIZE
3497        );
3498
3499        if !target_matches || !pname_matches {
3500            self.webgl_error(InvalidEnum);
3501            return retval.set(NullValue());
3502        }
3503
3504        if self.bound_renderbuffer.get().is_none() {
3505            self.webgl_error(InvalidOperation);
3506            return retval.set(NullValue());
3507        }
3508
3509        let result = if pname == constants::RENDERBUFFER_INTERNAL_FORMAT {
3510            let rb = self.bound_renderbuffer.get().unwrap();
3511            rb.internal_format() as i32
3512        } else {
3513            let (sender, receiver) = webgl_channel().unwrap();
3514            self.send_command(WebGLCommand::GetRenderbufferParameter(
3515                target, pname, sender,
3516            ));
3517            receiver.recv().unwrap()
3518        };
3519
3520        retval.set(Int32Value(result))
3521    }
3522
3523    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3524    fn GetProgramInfoLog(&self, program: &WebGLProgram) -> Option<DOMString> {
3525        handle_potential_webgl_error!(self, self.validate_ownership(program), return None);
3526        match program.get_info_log() {
3527            Ok(value) => Some(DOMString::from(value)),
3528            Err(e) => {
3529                self.webgl_error(e);
3530                None
3531            },
3532        }
3533    }
3534
3535    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3536    fn GetProgramParameter(
3537        &self,
3538        _cx: &mut JSContext,
3539        program: &WebGLProgram,
3540        param: u32,
3541        mut retval: MutableHandleValue,
3542    ) {
3543        handle_potential_webgl_error!(
3544            self,
3545            self.validate_ownership(program),
3546            return retval.set(NullValue())
3547        );
3548        if program.is_deleted() {
3549            self.webgl_error(InvalidOperation);
3550            return retval.set(NullValue());
3551        }
3552        retval.set(match param {
3553            constants::DELETE_STATUS => BooleanValue(program.is_marked_for_deletion()),
3554            constants::LINK_STATUS => BooleanValue(program.is_linked()),
3555            constants::VALIDATE_STATUS => {
3556                // FIXME(nox): This could be cached on the DOM side when we call validateProgram
3557                // but I'm not sure when the value should be reset.
3558                let (sender, receiver) = webgl_channel().unwrap();
3559                self.send_command(WebGLCommand::GetProgramValidateStatus(program.id(), sender));
3560                BooleanValue(receiver.recv().unwrap())
3561            },
3562            constants::ATTACHED_SHADERS => {
3563                // FIXME(nox): This allocates a vector and roots a couple of shaders for nothing.
3564                Int32Value(
3565                    program
3566                        .attached_shaders()
3567                        .map(|shaders| shaders.len() as i32)
3568                        .unwrap_or(0),
3569                )
3570            },
3571            constants::ACTIVE_ATTRIBUTES => Int32Value(program.active_attribs().len() as i32),
3572            constants::ACTIVE_UNIFORMS => Int32Value(program.active_uniforms().len() as i32),
3573            _ => {
3574                self.webgl_error(InvalidEnum);
3575                NullValue()
3576            },
3577        })
3578    }
3579
3580    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3581    fn GetShaderInfoLog(&self, shader: &WebGLShader) -> Option<DOMString> {
3582        handle_potential_webgl_error!(self, self.validate_ownership(shader), return None);
3583        Some(shader.info_log())
3584    }
3585
3586    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3587    fn GetShaderParameter(
3588        &self,
3589        _cx: &mut JSContext,
3590        shader: &WebGLShader,
3591        param: u32,
3592        mut retval: MutableHandleValue,
3593    ) {
3594        handle_potential_webgl_error!(
3595            self,
3596            self.validate_ownership(shader),
3597            return retval.set(NullValue())
3598        );
3599        if shader.is_deleted() {
3600            self.webgl_error(InvalidValue);
3601            return retval.set(NullValue());
3602        }
3603        retval.set(match param {
3604            constants::DELETE_STATUS => BooleanValue(shader.is_marked_for_deletion()),
3605            constants::COMPILE_STATUS => BooleanValue(shader.successfully_compiled()),
3606            constants::SHADER_TYPE => UInt32Value(shader.gl_type()),
3607            _ => {
3608                self.webgl_error(InvalidEnum);
3609                NullValue()
3610            },
3611        })
3612    }
3613
3614    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3615    fn GetShaderPrecisionFormat(
3616        &self,
3617        cx: &mut JSContext,
3618        shader_type: u32,
3619        precision_type: u32,
3620    ) -> Option<DomRoot<WebGLShaderPrecisionFormat>> {
3621        match shader_type {
3622            constants::FRAGMENT_SHADER | constants::VERTEX_SHADER => (),
3623            _ => {
3624                self.webgl_error(InvalidEnum);
3625                return None;
3626            },
3627        }
3628
3629        match precision_type {
3630            constants::LOW_FLOAT |
3631            constants::MEDIUM_FLOAT |
3632            constants::HIGH_FLOAT |
3633            constants::LOW_INT |
3634            constants::MEDIUM_INT |
3635            constants::HIGH_INT => (),
3636            _ => {
3637                self.webgl_error(InvalidEnum);
3638                return None;
3639            },
3640        }
3641
3642        let (sender, receiver) = webgl_channel().unwrap();
3643        self.send_command(WebGLCommand::GetShaderPrecisionFormat(
3644            shader_type,
3645            precision_type,
3646            sender,
3647        ));
3648
3649        let (range_min, range_max, precision) = receiver.recv().unwrap();
3650        Some(WebGLShaderPrecisionFormat::new(
3651            cx,
3652            self.global().as_window(),
3653            range_min,
3654            range_max,
3655            precision,
3656        ))
3657    }
3658
3659    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3660    fn GetUniformLocation(
3661        &self,
3662        cx: &mut JSContext,
3663        program: &WebGLProgram,
3664        name: DOMString,
3665    ) -> Option<DomRoot<WebGLUniformLocation>> {
3666        handle_potential_webgl_error!(self, self.validate_ownership(program), return None);
3667        handle_potential_webgl_error!(self, program.get_uniform_location(cx, name), None)
3668    }
3669
3670    #[expect(unsafe_code)]
3671    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3672    fn GetVertexAttrib(
3673        &self,
3674        cx: &mut JSContext,
3675        index: u32,
3676        param: u32,
3677        mut retval: MutableHandleValue,
3678    ) {
3679        let mut get_attrib = |cx: &mut JSContext, data: Ref<'_, VertexAttribData>| {
3680            if param == constants::CURRENT_VERTEX_ATTRIB {
3681                let attrib = self.current_vertex_attribs.borrow()[index as usize];
3682                match attrib {
3683                    VertexAttrib::Float(x, y, z, w) => {
3684                        let value = [x, y, z, w];
3685                        unsafe {
3686                            rooted!(&in(cx) let mut result = ptr::null_mut::<JSObject>());
3687                            Float32Array::create(
3688                                cx.raw_cx(),
3689                                CreateWith::Slice(&value),
3690                                result.handle_mut(),
3691                            )
3692                            .unwrap();
3693                            return retval.set(ObjectValue(result.get()));
3694                        }
3695                    },
3696                    VertexAttrib::Int(x, y, z, w) => {
3697                        let value = [x, y, z, w];
3698                        unsafe {
3699                            rooted!(&in(cx) let mut result = ptr::null_mut::<JSObject>());
3700                            Int32Array::create(
3701                                cx.raw_cx(),
3702                                CreateWith::Slice(&value),
3703                                result.handle_mut(),
3704                            )
3705                            .unwrap();
3706                            return retval.set(ObjectValue(result.get()));
3707                        }
3708                    },
3709                    VertexAttrib::Uint(x, y, z, w) => {
3710                        let value = [x, y, z, w];
3711                        unsafe {
3712                            rooted!(&in(cx) let mut result = ptr::null_mut::<JSObject>());
3713                            Uint32Array::create(
3714                                cx.raw_cx(),
3715                                CreateWith::Slice(&value),
3716                                result.handle_mut(),
3717                            )
3718                            .unwrap();
3719                            return retval.set(ObjectValue(result.get()));
3720                        }
3721                    },
3722                };
3723            }
3724            if !self
3725                .extension_manager
3726                .is_get_vertex_attrib_name_enabled(param)
3727            {
3728                self.webgl_error(WebGLError::InvalidEnum);
3729                return retval.set(NullValue());
3730            }
3731
3732            match param {
3733                constants::VERTEX_ATTRIB_ARRAY_ENABLED => {
3734                    retval.set(BooleanValue(data.enabled_as_array))
3735                },
3736                constants::VERTEX_ATTRIB_ARRAY_SIZE => retval.set(Int32Value(data.size as i32)),
3737                constants::VERTEX_ATTRIB_ARRAY_TYPE => retval.set(Int32Value(data.type_ as i32)),
3738                constants::VERTEX_ATTRIB_ARRAY_NORMALIZED => {
3739                    retval.set(BooleanValue(data.normalized))
3740                },
3741                constants::VERTEX_ATTRIB_ARRAY_STRIDE => retval.set(Int32Value(data.stride as i32)),
3742                constants::VERTEX_ATTRIB_ARRAY_BUFFER_BINDING => {
3743                    if let Some(buffer) = data.buffer() {
3744                        buffer.safe_to_jsval(cx, retval.reborrow());
3745                    } else {
3746                        retval.set(NullValue());
3747                    }
3748                },
3749                ANGLEInstancedArraysConstants::VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE => {
3750                    retval.set(UInt32Value(data.divisor))
3751                },
3752                _ => {
3753                    self.webgl_error(InvalidEnum);
3754                    retval.set(NullValue())
3755                },
3756            }
3757        };
3758
3759        match self.webgl_version() {
3760            WebGLVersion::WebGL1 => {
3761                let current_vao = self.current_vao(cx);
3762                let data = handle_potential_webgl_error!(
3763                    self,
3764                    current_vao.get_vertex_attrib(index).ok_or(InvalidValue),
3765                    return retval.set(NullValue())
3766                );
3767                get_attrib(cx, data)
3768            },
3769            WebGLVersion::WebGL2 => {
3770                let current_vao = self.current_vao_webgl2(cx);
3771                let data = handle_potential_webgl_error!(
3772                    self,
3773                    current_vao.get_vertex_attrib(index).ok_or(InvalidValue),
3774                    return retval.set(NullValue())
3775                );
3776                get_attrib(cx, data)
3777            },
3778        }
3779    }
3780
3781    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
3782    fn GetVertexAttribOffset(&self, cx: &mut JSContext, index: u32, pname: u32) -> i64 {
3783        if pname != constants::VERTEX_ATTRIB_ARRAY_POINTER {
3784            self.webgl_error(InvalidEnum);
3785            return 0;
3786        }
3787        match self.webgl_version() {
3788            WebGLVersion::WebGL1 => {
3789                let current_vao = self.current_vao(cx);
3790                let data = handle_potential_webgl_error!(
3791                    self,
3792                    current_vao.get_vertex_attrib(index).ok_or(InvalidValue),
3793                    return 0
3794                );
3795                data.offset as i64
3796            },
3797            WebGLVersion::WebGL2 => {
3798                let current_vao = self.current_vao_webgl2(cx);
3799                let data = handle_potential_webgl_error!(
3800                    self,
3801                    current_vao.get_vertex_attrib(index).ok_or(InvalidValue),
3802                    return 0
3803                );
3804                data.offset as i64
3805            },
3806        }
3807    }
3808
3809    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3810    fn Hint(&self, target: u32, mode: u32) {
3811        if target != constants::GENERATE_MIPMAP_HINT &&
3812            !self.extension_manager.is_hint_target_enabled(target)
3813        {
3814            return self.webgl_error(InvalidEnum);
3815        }
3816
3817        match mode {
3818            constants::FASTEST | constants::NICEST | constants::DONT_CARE => (),
3819
3820            _ => return self.webgl_error(InvalidEnum),
3821        }
3822
3823        self.send_command(WebGLCommand::Hint(target, mode));
3824    }
3825
3826    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5>
3827    fn IsBuffer(&self, buffer: Option<&WebGLBuffer>) -> bool {
3828        buffer.is_some_and(|buf| {
3829            self.validate_ownership(buf).is_ok() && buf.target().is_some() && !buf.is_deleted()
3830        })
3831    }
3832
3833    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3834    fn IsEnabled(&self, cap: u32) -> bool {
3835        handle_potential_webgl_error!(self, self.capabilities.is_enabled(cap), false)
3836    }
3837
3838    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
3839    fn IsFramebuffer(&self, frame_buffer: Option<&WebGLFramebuffer>) -> bool {
3840        frame_buffer.is_some_and(|buf| {
3841            self.validate_ownership(buf).is_ok() && buf.target().is_some() && !buf.is_deleted()
3842        })
3843    }
3844
3845    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3846    fn IsProgram(&self, program: Option<&WebGLProgram>) -> bool {
3847        program.is_some_and(|p| self.validate_ownership(p).is_ok() && !p.is_deleted())
3848    }
3849
3850    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
3851    fn IsRenderbuffer(&self, render_buffer: Option<&WebGLRenderbuffer>) -> bool {
3852        render_buffer.is_some_and(|buf| {
3853            self.validate_ownership(buf).is_ok() && buf.ever_bound() && !buf.is_deleted()
3854        })
3855    }
3856
3857    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
3858    fn IsShader(&self, shader: Option<&WebGLShader>) -> bool {
3859        shader.is_some_and(|s| self.validate_ownership(s).is_ok() && !s.is_deleted())
3860    }
3861
3862    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
3863    fn IsTexture(&self, texture: Option<&WebGLTexture>) -> bool {
3864        texture.is_some_and(|tex| {
3865            self.validate_ownership(tex).is_ok() && tex.target().is_some() && !tex.is_invalid()
3866        })
3867    }
3868
3869    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3870    fn LineWidth(&self, width: f32) {
3871        if width.is_nan() || width <= 0f32 {
3872            return self.webgl_error(InvalidValue);
3873        }
3874
3875        self.send_command(WebGLCommand::LineWidth(width))
3876    }
3877
3878    /// NOTE: Usage of this function could affect rendering while we keep using
3879    ///   readback to render to the page.
3880    ///
3881    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3882    fn PixelStorei(&self, param_name: u32, param_value: i32) {
3883        let mut texture_settings = self.texture_unpacking_settings.get();
3884        match param_name {
3885            constants::UNPACK_FLIP_Y_WEBGL => {
3886                texture_settings.set(TextureUnpacking::FLIP_Y_AXIS, param_value != 0);
3887            },
3888            constants::UNPACK_PREMULTIPLY_ALPHA_WEBGL => {
3889                texture_settings.set(TextureUnpacking::PREMULTIPLY_ALPHA, param_value != 0);
3890            },
3891            constants::UNPACK_COLORSPACE_CONVERSION_WEBGL => {
3892                let convert = match param_value as u32 {
3893                    constants::BROWSER_DEFAULT_WEBGL => true,
3894                    constants::NONE => false,
3895                    _ => return self.webgl_error(InvalidEnum),
3896                };
3897                texture_settings.set(TextureUnpacking::CONVERT_COLORSPACE, convert);
3898            },
3899            constants::UNPACK_ALIGNMENT => {
3900                match param_value {
3901                    1 | 2 | 4 | 8 => (),
3902                    _ => return self.webgl_error(InvalidValue),
3903                }
3904                self.texture_unpacking_alignment.set(param_value as u32);
3905                return;
3906            },
3907            constants::PACK_ALIGNMENT => {
3908                match param_value {
3909                    1 | 2 | 4 | 8 => (),
3910                    _ => return self.webgl_error(InvalidValue),
3911                }
3912                // We never actually change the actual value on the GL side
3913                // because it's better to receive the pixels without the padding
3914                // and then write the result at the right place in ReadPixels.
3915                self.texture_packing_alignment.set(param_value as u8);
3916                return;
3917            },
3918            _ => return self.webgl_error(InvalidEnum),
3919        }
3920        self.texture_unpacking_settings.set(texture_settings);
3921    }
3922
3923    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
3924    fn PolygonOffset(&self, factor: f32, units: f32) {
3925        self.send_command(WebGLCommand::PolygonOffset(factor, units))
3926    }
3927
3928    // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.12
3929    fn ReadPixels(
3930        &self,
3931        no_gc: &NoGC,
3932        x: i32,
3933        y: i32,
3934        width: i32,
3935        height: i32,
3936        format: u32,
3937        pixel_type: u32,
3938        mut pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>,
3939    ) {
3940        handle_potential_webgl_error!(self, self.validate_framebuffer(), return);
3941
3942        let pixels =
3943            handle_potential_webgl_error!(self, pixels.as_mut().ok_or(InvalidValue), return);
3944
3945        if width < 0 || height < 0 {
3946            return self.webgl_error(InvalidValue);
3947        }
3948
3949        if format != constants::RGBA || pixel_type != constants::UNSIGNED_BYTE {
3950            return self.webgl_error(InvalidOperation);
3951        }
3952
3953        if pixels.get_array_type() != Type::Uint8 {
3954            return self.webgl_error(InvalidOperation);
3955        }
3956
3957        let (fb_width, fb_height) = handle_potential_webgl_error!(
3958            self,
3959            self.get_current_framebuffer_size().ok_or(InvalidOperation),
3960            return
3961        );
3962
3963        if width == 0 || height == 0 {
3964            return;
3965        }
3966
3967        let bytes_per_pixel = 4;
3968
3969        let row_len = handle_potential_webgl_error!(
3970            self,
3971            width.checked_mul(bytes_per_pixel).ok_or(InvalidOperation),
3972            return
3973        );
3974
3975        let pack_alignment = self.texture_packing_alignment.get() as i32;
3976        let dest_padding = match row_len % pack_alignment {
3977            0 => 0,
3978            remainder => pack_alignment - remainder,
3979        };
3980        let dest_stride = row_len + dest_padding;
3981
3982        let full_rows_len = handle_potential_webgl_error!(
3983            self,
3984            dest_stride.checked_mul(height - 1).ok_or(InvalidOperation),
3985            return
3986        );
3987        let required_dest_len = handle_potential_webgl_error!(
3988            self,
3989            full_rows_len.checked_add(row_len).ok_or(InvalidOperation),
3990            return
3991        );
3992
3993        let dest = pixels.as_mut_slice_safe(no_gc).unwrap_or(&mut []);
3994        if dest.len() < required_dest_len as usize {
3995            return self.webgl_error(InvalidOperation);
3996        }
3997
3998        let src_origin = Point2D::new(x, y);
3999        let src_size = Size2D::new(width as u32, height as u32);
4000        let fb_size = Size2D::new(fb_width as u32, fb_height as u32);
4001        let src_rect = match pixels::clip(src_origin, src_size.to_u32(), fb_size.to_u32()) {
4002            Some(rect) => rect,
4003            None => return,
4004        };
4005
4006        // Note: we're casting a Rect<u64> back into a Rect<u32> here, but it's okay because
4007        //  it used u32 data types to begin with. It just got converted to Rect<u64> in
4008        //  pixels::clip
4009        let src_rect = src_rect.to_u32();
4010
4011        let mut dest_offset = 0;
4012        if x < 0 {
4013            dest_offset += -x * bytes_per_pixel;
4014        }
4015        if y < 0 {
4016            dest_offset += -y * row_len;
4017        }
4018
4019        let (sender, receiver) = generic_channel::channel().unwrap();
4020        self.send_command(WebGLCommand::ReadPixels(
4021            src_rect, format, pixel_type, sender,
4022        ));
4023        let (src, _) = receiver.recv().unwrap();
4024
4025        let src_row_len = src_rect.size.width as usize * bytes_per_pixel as usize;
4026        for i in 0..src_rect.size.height {
4027            let dest_start = dest_offset as usize + i as usize * dest_stride as usize;
4028            let dest_end = dest_start + src_row_len;
4029            let src_start = i as usize * src_row_len;
4030            let src_end = src_start + src_row_len;
4031            dest[dest_start..dest_end].copy_from_slice(&src[src_start..src_end]);
4032        }
4033    }
4034
4035    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
4036    fn SampleCoverage(&self, value: f32, invert: bool) {
4037        self.send_command(WebGLCommand::SampleCoverage(value, invert));
4038    }
4039
4040    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4>
4041    fn Scissor(&self, x: i32, y: i32, width: i32, height: i32) {
4042        if width < 0 || height < 0 {
4043            return self.webgl_error(InvalidValue);
4044        }
4045
4046        let width = width as u32;
4047        let height = height as u32;
4048
4049        self.current_scissor.set((x, y, width, height));
4050        self.send_command(WebGLCommand::Scissor(x, y, width, height));
4051    }
4052
4053    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
4054    fn StencilFunc(&self, func: u32, ref_: i32, mask: u32) {
4055        match func {
4056            constants::NEVER |
4057            constants::LESS |
4058            constants::EQUAL |
4059            constants::LEQUAL |
4060            constants::GREATER |
4061            constants::NOTEQUAL |
4062            constants::GEQUAL |
4063            constants::ALWAYS => self.send_command(WebGLCommand::StencilFunc(func, ref_, mask)),
4064            _ => self.webgl_error(InvalidEnum),
4065        }
4066    }
4067
4068    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
4069    fn StencilFuncSeparate(&self, face: u32, func: u32, ref_: i32, mask: u32) {
4070        match face {
4071            constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => (),
4072            _ => return self.webgl_error(InvalidEnum),
4073        }
4074
4075        match func {
4076            constants::NEVER |
4077            constants::LESS |
4078            constants::EQUAL |
4079            constants::LEQUAL |
4080            constants::GREATER |
4081            constants::NOTEQUAL |
4082            constants::GEQUAL |
4083            constants::ALWAYS => {
4084                self.send_command(WebGLCommand::StencilFuncSeparate(face, func, ref_, mask))
4085            },
4086            _ => self.webgl_error(InvalidEnum),
4087        }
4088    }
4089
4090    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
4091    fn StencilMask(&self, mask: u32) {
4092        self.send_command(WebGLCommand::StencilMask(mask))
4093    }
4094
4095    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
4096    fn StencilMaskSeparate(&self, face: u32, mask: u32) {
4097        match face {
4098            constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => {
4099                self.send_command(WebGLCommand::StencilMaskSeparate(face, mask))
4100            },
4101            _ => self.webgl_error(InvalidEnum),
4102        };
4103    }
4104
4105    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
4106    fn StencilOp(&self, fail: u32, zfail: u32, zpass: u32) {
4107        if self.validate_stencil_actions(fail) &&
4108            self.validate_stencil_actions(zfail) &&
4109            self.validate_stencil_actions(zpass)
4110        {
4111            self.send_command(WebGLCommand::StencilOp(fail, zfail, zpass));
4112        } else {
4113            self.webgl_error(InvalidEnum)
4114        }
4115    }
4116
4117    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3>
4118    fn StencilOpSeparate(&self, face: u32, fail: u32, zfail: u32, zpass: u32) {
4119        match face {
4120            constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => (),
4121            _ => return self.webgl_error(InvalidEnum),
4122        }
4123
4124        if self.validate_stencil_actions(fail) &&
4125            self.validate_stencil_actions(zfail) &&
4126            self.validate_stencil_actions(zpass)
4127        {
4128            self.send_command(WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass))
4129        } else {
4130            self.webgl_error(InvalidEnum)
4131        }
4132    }
4133
4134    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
4135    fn LinkProgram(&self, program: &WebGLProgram) {
4136        handle_potential_webgl_error!(self, self.validate_ownership(program), return);
4137        if program.is_deleted() {
4138            return self.webgl_error(InvalidValue);
4139        }
4140        handle_potential_webgl_error!(self, program.link());
4141    }
4142
4143    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
4144    fn ShaderSource(&self, shader: &WebGLShader, source: DOMString) {
4145        handle_potential_webgl_error!(self, self.validate_ownership(shader), return);
4146        shader.set_source(source)
4147    }
4148
4149    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
4150    fn GetShaderSource(&self, shader: &WebGLShader) -> Option<DOMString> {
4151        handle_potential_webgl_error!(self, self.validate_ownership(shader), return None);
4152        Some(shader.source())
4153    }
4154
4155    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4156    fn Uniform1f(&self, location: Option<&WebGLUniformLocation>, val: f32) {
4157        self.with_location(location, |location| {
4158            match location.type_() {
4159                constants::BOOL | constants::FLOAT => {},
4160                _ => return Err(InvalidOperation),
4161            }
4162            self.send_command(WebGLCommand::Uniform1f(location.id(), val));
4163            Ok(())
4164        });
4165    }
4166
4167    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4168    fn Uniform1i(&self, location: Option<&WebGLUniformLocation>, val: i32) {
4169        self.with_location(location, |location| {
4170            match location.type_() {
4171                constants::BOOL | constants::INT => {},
4172                constants::SAMPLER_2D |
4173                WebGL2RenderingContextConstants::SAMPLER_3D |
4174                WebGL2RenderingContextConstants::SAMPLER_2D_ARRAY |
4175                constants::SAMPLER_CUBE => {
4176                    if val < 0 || val as u32 >= self.limits.max_combined_texture_image_units {
4177                        return Err(InvalidValue);
4178                    }
4179                },
4180                _ => return Err(InvalidOperation),
4181            }
4182            self.send_command(WebGLCommand::Uniform1i(location.id(), val));
4183            Ok(())
4184        });
4185    }
4186
4187    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4188    fn Uniform1iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) {
4189        self.uniform1iv(location, val, 0, 0)
4190    }
4191
4192    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4193    fn Uniform1fv(
4194        &self,
4195        location: Option<&WebGLUniformLocation>,
4196        val: Float32ArrayOrUnrestrictedFloatSequence,
4197    ) {
4198        self.uniform1fv(location, val, 0, 0)
4199    }
4200
4201    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4202    fn Uniform2f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32) {
4203        self.with_location(location, |location| {
4204            match location.type_() {
4205                constants::BOOL_VEC2 | constants::FLOAT_VEC2 => {},
4206                _ => return Err(InvalidOperation),
4207            }
4208            self.send_command(WebGLCommand::Uniform2f(location.id(), x, y));
4209            Ok(())
4210        });
4211    }
4212
4213    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4214    fn Uniform2fv(
4215        &self,
4216        location: Option<&WebGLUniformLocation>,
4217        val: Float32ArrayOrUnrestrictedFloatSequence,
4218    ) {
4219        self.uniform2fv(location, val, 0, 0)
4220    }
4221
4222    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4223    fn Uniform2i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32) {
4224        self.with_location(location, |location| {
4225            match location.type_() {
4226                constants::BOOL_VEC2 | constants::INT_VEC2 => {},
4227                _ => return Err(InvalidOperation),
4228            }
4229            self.send_command(WebGLCommand::Uniform2i(location.id(), x, y));
4230            Ok(())
4231        });
4232    }
4233
4234    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4235    fn Uniform2iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) {
4236        self.uniform2iv(location, val, 0, 0)
4237    }
4238
4239    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4240    fn Uniform3f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32) {
4241        self.with_location(location, |location| {
4242            match location.type_() {
4243                constants::BOOL_VEC3 | constants::FLOAT_VEC3 => {},
4244                _ => return Err(InvalidOperation),
4245            }
4246            self.send_command(WebGLCommand::Uniform3f(location.id(), x, y, z));
4247            Ok(())
4248        });
4249    }
4250
4251    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4252    fn Uniform3fv(
4253        &self,
4254        location: Option<&WebGLUniformLocation>,
4255        val: Float32ArrayOrUnrestrictedFloatSequence,
4256    ) {
4257        self.uniform3fv(location, val, 0, 0)
4258    }
4259
4260    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4261    fn Uniform3i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32) {
4262        self.with_location(location, |location| {
4263            match location.type_() {
4264                constants::BOOL_VEC3 | constants::INT_VEC3 => {},
4265                _ => return Err(InvalidOperation),
4266            }
4267            self.send_command(WebGLCommand::Uniform3i(location.id(), x, y, z));
4268            Ok(())
4269        });
4270    }
4271
4272    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4273    fn Uniform3iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) {
4274        self.uniform3iv(location, val, 0, 0)
4275    }
4276
4277    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4278    fn Uniform4i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32, w: i32) {
4279        self.with_location(location, |location| {
4280            match location.type_() {
4281                constants::BOOL_VEC4 | constants::INT_VEC4 => {},
4282                _ => return Err(InvalidOperation),
4283            }
4284            self.send_command(WebGLCommand::Uniform4i(location.id(), x, y, z, w));
4285            Ok(())
4286        });
4287    }
4288
4289    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4290    fn Uniform4iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) {
4291        self.uniform4iv(location, val, 0, 0)
4292    }
4293
4294    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4295    fn Uniform4f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32, w: f32) {
4296        self.with_location(location, |location| {
4297            match location.type_() {
4298                constants::BOOL_VEC4 | constants::FLOAT_VEC4 => {},
4299                _ => return Err(InvalidOperation),
4300            }
4301            self.send_command(WebGLCommand::Uniform4f(location.id(), x, y, z, w));
4302            Ok(())
4303        });
4304    }
4305
4306    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4307    fn Uniform4fv(
4308        &self,
4309        location: Option<&WebGLUniformLocation>,
4310        val: Float32ArrayOrUnrestrictedFloatSequence,
4311    ) {
4312        self.uniform4fv(location, val, 0, 0)
4313    }
4314
4315    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4316    fn UniformMatrix2fv(
4317        &self,
4318        location: Option<&WebGLUniformLocation>,
4319        transpose: bool,
4320        val: Float32ArrayOrUnrestrictedFloatSequence,
4321    ) {
4322        self.uniform_matrix_2fv(location, transpose, val, 0, 0)
4323    }
4324
4325    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4326    fn UniformMatrix3fv(
4327        &self,
4328        location: Option<&WebGLUniformLocation>,
4329        transpose: bool,
4330        val: Float32ArrayOrUnrestrictedFloatSequence,
4331    ) {
4332        self.uniform_matrix_3fv(location, transpose, val, 0, 0)
4333    }
4334
4335    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4336    fn UniformMatrix4fv(
4337        &self,
4338        location: Option<&WebGLUniformLocation>,
4339        transpose: bool,
4340        val: Float32ArrayOrUnrestrictedFloatSequence,
4341    ) {
4342        self.uniform_matrix_4fv(location, transpose, val, 0, 0)
4343    }
4344
4345    // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10
4346    #[expect(unsafe_code)]
4347    fn GetUniform(
4348        &self,
4349        cx: &mut JSContext,
4350        program: &WebGLProgram,
4351        location: &WebGLUniformLocation,
4352        mut rval: MutableHandleValue,
4353    ) {
4354        handle_potential_webgl_error!(
4355            self,
4356            self.uniform_check_program(program, location),
4357            return rval.set(NullValue())
4358        );
4359
4360        let triple = (self, program.id(), location.id());
4361
4362        match location.type_() {
4363            constants::BOOL => rval.set(BooleanValue(uniform_get(
4364                triple,
4365                WebGLCommand::GetUniformBool,
4366            ))),
4367            constants::BOOL_VEC2 => {
4368                uniform_get(triple, WebGLCommand::GetUniformBool2).safe_to_jsval(cx, rval)
4369            },
4370            constants::BOOL_VEC3 => {
4371                uniform_get(triple, WebGLCommand::GetUniformBool3).safe_to_jsval(cx, rval)
4372            },
4373            constants::BOOL_VEC4 => {
4374                uniform_get(triple, WebGLCommand::GetUniformBool4).safe_to_jsval(cx, rval)
4375            },
4376            constants::INT |
4377            constants::SAMPLER_2D |
4378            constants::SAMPLER_CUBE |
4379            WebGL2RenderingContextConstants::SAMPLER_2D_ARRAY |
4380            WebGL2RenderingContextConstants::SAMPLER_3D => {
4381                rval.set(Int32Value(uniform_get(triple, WebGLCommand::GetUniformInt)))
4382            },
4383            constants::INT_VEC2 => unsafe {
4384                uniform_typed::<Int32>(cx, &uniform_get(triple, WebGLCommand::GetUniformInt2), rval)
4385            },
4386            constants::INT_VEC3 => unsafe {
4387                uniform_typed::<Int32>(cx, &uniform_get(triple, WebGLCommand::GetUniformInt3), rval)
4388            },
4389            constants::INT_VEC4 => unsafe {
4390                uniform_typed::<Int32>(cx, &uniform_get(triple, WebGLCommand::GetUniformInt4), rval)
4391            },
4392            constants::FLOAT => rval
4393                .set(DoubleValue(
4394                    uniform_get(triple, WebGLCommand::GetUniformFloat) as f64,
4395                )),
4396            constants::FLOAT_VEC2 => unsafe {
4397                uniform_typed::<Float32>(
4398                    cx,
4399                    &uniform_get(triple, WebGLCommand::GetUniformFloat2),
4400                    rval,
4401                )
4402            },
4403            constants::FLOAT_VEC3 => unsafe {
4404                uniform_typed::<Float32>(
4405                    cx,
4406                    &uniform_get(triple, WebGLCommand::GetUniformFloat3),
4407                    rval,
4408                )
4409            },
4410            constants::FLOAT_VEC4 | constants::FLOAT_MAT2 => unsafe {
4411                uniform_typed::<Float32>(
4412                    cx,
4413                    &uniform_get(triple, WebGLCommand::GetUniformFloat4),
4414                    rval,
4415                )
4416            },
4417            constants::FLOAT_MAT3 => unsafe {
4418                uniform_typed::<Float32>(
4419                    cx,
4420                    &uniform_get(triple, WebGLCommand::GetUniformFloat9),
4421                    rval,
4422                )
4423            },
4424            constants::FLOAT_MAT4 => unsafe {
4425                uniform_typed::<Float32>(
4426                    cx,
4427                    &uniform_get(triple, WebGLCommand::GetUniformFloat16),
4428                    rval,
4429                )
4430            },
4431            _ => panic!("wrong uniform type"),
4432        }
4433    }
4434
4435    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
4436    fn UseProgram(&self, program: Option<&WebGLProgram>) {
4437        if let Some(program) = program {
4438            handle_potential_webgl_error!(self, self.validate_ownership(program), return);
4439            if program.is_deleted() || !program.is_linked() {
4440                return self.webgl_error(InvalidOperation);
4441            }
4442            if program.is_in_use() {
4443                return;
4444            }
4445            program.in_use(true);
4446        }
4447        match self.current_program.get() {
4448            Some(ref current) if program != Some(&**current) => current.in_use(false),
4449            _ => {},
4450        }
4451        self.send_command(WebGLCommand::UseProgram(program.map(|p| p.id())));
4452        self.current_program.set(program);
4453    }
4454
4455    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
4456    fn ValidateProgram(&self, program: &WebGLProgram) {
4457        handle_potential_webgl_error!(self, self.validate_ownership(program), return);
4458        if let Err(e) = program.validate() {
4459            self.webgl_error(e);
4460        }
4461    }
4462
4463    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4464    fn VertexAttrib1f(&self, cx: &mut JSContext, indx: u32, x: f32) {
4465        self.vertex_attrib(cx, indx, x, 0f32, 0f32, 1f32)
4466    }
4467
4468    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4469    fn VertexAttrib1fv(
4470        &self,
4471        cx: &mut JSContext,
4472        indx: u32,
4473        v: Float32ArrayOrUnrestrictedFloatSequence,
4474    ) {
4475        let values = match v {
4476            Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => {
4477                v.to_vec().unwrap_or_default()
4478            },
4479            Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
4480        };
4481        if values.is_empty() {
4482            // https://github.com/KhronosGroup/WebGL/issues/2700
4483            return self.webgl_error(InvalidValue);
4484        }
4485        self.vertex_attrib(cx, indx, values[0], 0f32, 0f32, 1f32);
4486    }
4487
4488    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4489    fn VertexAttrib2f(&self, cx: &mut JSContext, indx: u32, x: f32, y: f32) {
4490        self.vertex_attrib(cx, indx, x, y, 0f32, 1f32)
4491    }
4492
4493    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4494    fn VertexAttrib2fv(
4495        &self,
4496        cx: &mut JSContext,
4497        indx: u32,
4498        v: Float32ArrayOrUnrestrictedFloatSequence,
4499    ) {
4500        let values = match v {
4501            Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => {
4502                v.to_vec().unwrap_or_default()
4503            },
4504            Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
4505        };
4506        if values.len() < 2 {
4507            // https://github.com/KhronosGroup/WebGL/issues/2700
4508            return self.webgl_error(InvalidValue);
4509        }
4510        self.vertex_attrib(cx, indx, values[0], values[1], 0f32, 1f32);
4511    }
4512
4513    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4514    fn VertexAttrib3f(&self, cx: &mut JSContext, indx: u32, x: f32, y: f32, z: f32) {
4515        self.vertex_attrib(cx, indx, x, y, z, 1f32)
4516    }
4517
4518    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4519    fn VertexAttrib3fv(
4520        &self,
4521        cx: &mut JSContext,
4522        indx: u32,
4523        v: Float32ArrayOrUnrestrictedFloatSequence,
4524    ) {
4525        let values = match v {
4526            Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => {
4527                v.to_vec().unwrap_or_default()
4528            },
4529            Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
4530        };
4531        if values.len() < 3 {
4532            // https://github.com/KhronosGroup/WebGL/issues/2700
4533            return self.webgl_error(InvalidValue);
4534        }
4535        self.vertex_attrib(cx, indx, values[0], values[1], values[2], 1f32);
4536    }
4537
4538    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4539    fn VertexAttrib4f(&self, cx: &mut JSContext, indx: u32, x: f32, y: f32, z: f32, w: f32) {
4540        self.vertex_attrib(cx, indx, x, y, z, w)
4541    }
4542
4543    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4544    fn VertexAttrib4fv(
4545        &self,
4546        cx: &mut JSContext,
4547        indx: u32,
4548        v: Float32ArrayOrUnrestrictedFloatSequence,
4549    ) {
4550        let values = match v {
4551            Float32ArrayOrUnrestrictedFloatSequence::Float32Array(v) => {
4552                v.to_vec().unwrap_or_default()
4553            },
4554            Float32ArrayOrUnrestrictedFloatSequence::UnrestrictedFloatSequence(v) => v,
4555        };
4556        if values.len() < 4 {
4557            // https://github.com/KhronosGroup/WebGL/issues/2700
4558            return self.webgl_error(InvalidValue);
4559        }
4560        self.vertex_attrib(cx, indx, values[0], values[1], values[2], values[3]);
4561    }
4562
4563    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10>
4564    fn VertexAttribPointer(
4565        &self,
4566        cx: &mut JSContext,
4567        index: u32,
4568        size: i32,
4569        type_: u32,
4570        normalized: bool,
4571        stride: i32,
4572        offset: i64,
4573    ) {
4574        let res = match self.webgl_version() {
4575            WebGLVersion::WebGL1 => self
4576                .current_vao(cx)
4577                .vertex_attrib_pointer(index, size, type_, normalized, stride, offset),
4578            WebGLVersion::WebGL2 => self
4579                .current_vao_webgl2(cx)
4580                .vertex_attrib_pointer(index, size, type_, normalized, stride, offset),
4581        };
4582        handle_potential_webgl_error!(self, res);
4583    }
4584
4585    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4>
4586    fn Viewport(&self, x: i32, y: i32, width: i32, height: i32) {
4587        if width < 0 || height < 0 {
4588            return self.webgl_error(InvalidValue);
4589        }
4590
4591        self.send_command(WebGLCommand::SetViewport(x, y, width, height))
4592    }
4593
4594    // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8
4595    fn TexImage2D(
4596        &self,
4597        no_gc: &NoGC,
4598        target: u32,
4599        level: i32,
4600        internal_format: i32,
4601        width: i32,
4602        height: i32,
4603        border: i32,
4604        format: u32,
4605        data_type: u32,
4606        pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>,
4607    ) -> ErrorResult {
4608        if !self.extension_manager.is_tex_type_enabled(data_type) {
4609            self.webgl_error(InvalidEnum);
4610            return Ok(());
4611        }
4612
4613        let validator = TexImage2DValidator::new(
4614            self,
4615            target,
4616            level,
4617            internal_format as u32,
4618            width,
4619            height,
4620            border,
4621            format,
4622            data_type,
4623        );
4624
4625        let TexImage2DValidatorResult {
4626            texture,
4627            target,
4628            width,
4629            height,
4630            level,
4631            border,
4632            internal_format,
4633            format,
4634            data_type,
4635        } = match validator.validate() {
4636            Ok(result) => result,
4637            Err(_) => return Ok(()), // NB: The validator sets the correct error for us.
4638        };
4639
4640        if !internal_format.compatible_data_types().contains(&data_type) {
4641            return {
4642                self.webgl_error(InvalidOperation);
4643                Ok(())
4644            };
4645        }
4646        if texture.is_immutable() {
4647            return {
4648                self.webgl_error(InvalidOperation);
4649                Ok(())
4650            };
4651        }
4652
4653        let unpacking_alignment = self.texture_unpacking_alignment.get();
4654
4655        let expected_byte_length = match self.validate_tex_image_2d_data(
4656            width,
4657            height,
4658            format,
4659            data_type,
4660            unpacking_alignment,
4661            pixels.as_ref(),
4662        ) {
4663            Ok(byte_length) => byte_length,
4664            Err(()) => return Ok(()),
4665        };
4666
4667        // If data is null, a buffer of sufficient size
4668        // initialized to 0 is passed.
4669        let buff = match *pixels {
4670            None => GenericSharedMemory::from_byte(0, expected_byte_length as usize),
4671            Some(ref data) => {
4672                GenericSharedMemory::from_bytes(data.as_slice_safe(no_gc).unwrap_or_default())
4673            },
4674        };
4675
4676        // From the WebGL spec:
4677        //
4678        //     "If pixels is non-null but its size is less than what
4679        //      is required by the specified width, height, format,
4680        //      type, and pixel storage parameters, generates an
4681        //      INVALID_OPERATION error."
4682        if buff.len() < expected_byte_length as usize {
4683            return {
4684                self.webgl_error(InvalidOperation);
4685                Ok(())
4686            };
4687        }
4688
4689        let size = Size2D::new(width, height);
4690
4691        if !self.validate_filterable_texture(
4692            &texture,
4693            target,
4694            level,
4695            internal_format,
4696            size,
4697            data_type,
4698        ) {
4699            // FIXME(nox): What is the spec for this? No error is emitted ever
4700            // by validate_filterable_texture.
4701            return Ok(());
4702        }
4703
4704        let size = Size2D::new(width, height);
4705
4706        let (alpha_treatment, y_axis_treatment) =
4707            self.get_current_unpack_state(Alpha::NotPremultiplied);
4708
4709        self.tex_image_2d(
4710            &texture,
4711            target,
4712            data_type,
4713            internal_format,
4714            format,
4715            level,
4716            border,
4717            unpacking_alignment,
4718            size,
4719            TexSource::Pixels(TexPixels::from_array(
4720                buff,
4721                size,
4722                alpha_treatment,
4723                y_axis_treatment,
4724            )),
4725        );
4726
4727        Ok(())
4728    }
4729
4730    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
4731    fn TexImage2D_(
4732        &self,
4733        no_gc: &NoGC,
4734        target: u32,
4735        level: i32,
4736        internal_format: i32,
4737        format: u32,
4738        data_type: u32,
4739        source: TexImageSource,
4740    ) -> ErrorResult {
4741        if !self.extension_manager.is_tex_type_enabled(data_type) {
4742            self.webgl_error(InvalidEnum);
4743            return Ok(());
4744        }
4745
4746        let pixels = match self.get_image_pixels(no_gc, source)? {
4747            Some(pixels) => pixels,
4748            None => return Ok(()),
4749        };
4750
4751        let validator = TexImage2DValidator::new(
4752            self,
4753            target,
4754            level,
4755            internal_format as u32,
4756            pixels.size().width as i32,
4757            pixels.size().height as i32,
4758            0,
4759            format,
4760            data_type,
4761        );
4762
4763        let TexImage2DValidatorResult {
4764            texture,
4765            target,
4766            level,
4767            border,
4768            internal_format,
4769            format,
4770            data_type,
4771            ..
4772        } = match validator.validate() {
4773            Ok(result) => result,
4774            Err(_) => return Ok(()), // NB: The validator sets the correct error for us.
4775        };
4776
4777        if !internal_format.compatible_data_types().contains(&data_type) {
4778            return {
4779                self.webgl_error(InvalidOperation);
4780                Ok(())
4781            };
4782        }
4783        if texture.is_immutable() {
4784            return {
4785                self.webgl_error(InvalidOperation);
4786                Ok(())
4787            };
4788        }
4789
4790        if !self.validate_filterable_texture(
4791            &texture,
4792            target,
4793            level,
4794            internal_format,
4795            pixels.size(),
4796            data_type,
4797        ) {
4798            // FIXME(nox): What is the spec for this? No error is emitted ever
4799            // by validate_filterable_texture.
4800            return Ok(());
4801        }
4802
4803        self.tex_image_2d(
4804            &texture,
4805            target,
4806            data_type,
4807            internal_format,
4808            format,
4809            level,
4810            border,
4811            1,
4812            pixels.size(),
4813            TexSource::Pixels(pixels),
4814        );
4815        Ok(())
4816    }
4817
4818    // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8
4819    fn TexSubImage2D(
4820        &self,
4821        no_gc: &NoGC,
4822        target: u32,
4823        level: i32,
4824        xoffset: i32,
4825        yoffset: i32,
4826        width: i32,
4827        height: i32,
4828        format: u32,
4829        data_type: u32,
4830        pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>,
4831    ) -> ErrorResult {
4832        let validator = TexImage2DValidator::new(
4833            self, target, level, format, width, height, 0, format, data_type,
4834        );
4835        let TexImage2DValidatorResult {
4836            texture,
4837            target,
4838            width,
4839            height,
4840            level,
4841            format,
4842            data_type,
4843            ..
4844        } = match validator.validate() {
4845            Ok(result) => result,
4846            Err(_) => return Ok(()), // NB: The validator sets the correct error for us.
4847        };
4848
4849        let unpacking_alignment = self.texture_unpacking_alignment.get();
4850
4851        let expected_byte_length = match self.validate_tex_image_2d_data(
4852            width,
4853            height,
4854            format,
4855            data_type,
4856            unpacking_alignment,
4857            pixels.as_ref(),
4858        ) {
4859            Ok(byte_length) => byte_length,
4860            Err(()) => return Ok(()),
4861        };
4862
4863        let buff = handle_potential_webgl_error!(
4864            self,
4865            pixels
4866                .as_ref()
4867                .map(|p| GenericSharedMemory::from_bytes(p.as_slice_safe(no_gc).unwrap_or(&[])))
4868                .ok_or(InvalidValue),
4869            return Ok(())
4870        );
4871
4872        // From the WebGL spec:
4873        //
4874        //     "If pixels is non-null but its size is less than what
4875        //      is required by the specified width, height, format,
4876        //      type, and pixel storage parameters, generates an
4877        //      INVALID_OPERATION error."
4878        if buff.len() < expected_byte_length as usize {
4879            return {
4880                self.webgl_error(InvalidOperation);
4881                Ok(())
4882            };
4883        }
4884
4885        let (alpha_treatment, y_axis_treatment) =
4886            self.get_current_unpack_state(Alpha::NotPremultiplied);
4887
4888        self.tex_sub_image_2d(
4889            texture,
4890            target,
4891            level,
4892            xoffset,
4893            yoffset,
4894            format,
4895            data_type,
4896            unpacking_alignment,
4897            TexPixels::from_array(
4898                buff,
4899                Size2D::new(width, height),
4900                alpha_treatment,
4901                y_axis_treatment,
4902            ),
4903        );
4904        Ok(())
4905    }
4906
4907    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
4908    fn TexSubImage2D_(
4909        &self,
4910        no_gc: &NoGC,
4911        target: u32,
4912        level: i32,
4913        xoffset: i32,
4914        yoffset: i32,
4915        format: u32,
4916        data_type: u32,
4917        source: TexImageSource,
4918    ) -> ErrorResult {
4919        let pixels = match self.get_image_pixels(no_gc, source)? {
4920            Some(pixels) => pixels,
4921            None => return Ok(()),
4922        };
4923
4924        let validator = TexImage2DValidator::new(
4925            self,
4926            target,
4927            level,
4928            format,
4929            pixels.size().width as i32,
4930            pixels.size().height as i32,
4931            0,
4932            format,
4933            data_type,
4934        );
4935        let TexImage2DValidatorResult {
4936            texture,
4937            target,
4938            level,
4939            format,
4940            data_type,
4941            ..
4942        } = match validator.validate() {
4943            Ok(result) => result,
4944            Err(_) => return Ok(()), // NB: The validator sets the correct error for us.
4945        };
4946
4947        self.tex_sub_image_2d(
4948            texture, target, level, xoffset, yoffset, format, data_type, 1, pixels,
4949        );
4950        Ok(())
4951    }
4952
4953    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
4954    fn TexParameterf(&self, target: u32, name: u32, value: f32) {
4955        self.tex_parameter(target, name, TexParameterValue::Float(value))
4956    }
4957
4958    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8>
4959    fn TexParameteri(&self, target: u32, name: u32, value: i32) {
4960        self.tex_parameter(target, name, TexParameterValue::Int(value))
4961    }
4962
4963    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
4964    fn CheckFramebufferStatus(&self, target: u32) -> u32 {
4965        // From the GLES 2.0.25 spec, 4.4 ("Framebuffer Objects"):
4966        //
4967        //    "If target is not FRAMEBUFFER, INVALID_ENUM is
4968        //     generated. If CheckFramebufferStatus generates an
4969        //     error, 0 is returned."
4970        if target != constants::FRAMEBUFFER {
4971            self.webgl_error(InvalidEnum);
4972            return 0;
4973        }
4974
4975        match self.bound_draw_framebuffer.get() {
4976            Some(fb) => fb.check_status(),
4977            None => constants::FRAMEBUFFER_COMPLETE,
4978        }
4979    }
4980
4981    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7>
4982    fn RenderbufferStorage(&self, target: u32, internal_format: u32, width: i32, height: i32) {
4983        self.renderbuffer_storage(target, 0, internal_format, width, height)
4984    }
4985
4986    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
4987    fn FramebufferRenderbuffer(
4988        &self,
4989        target: u32,
4990        attachment: u32,
4991        renderbuffertarget: u32,
4992        rb: Option<&WebGLRenderbuffer>,
4993    ) {
4994        if let Some(rb) = rb {
4995            handle_potential_webgl_error!(self, self.validate_ownership(rb), return);
4996        }
4997
4998        if target != constants::FRAMEBUFFER || renderbuffertarget != constants::RENDERBUFFER {
4999            return self.webgl_error(InvalidEnum);
5000        }
5001
5002        match self.bound_draw_framebuffer.get() {
5003            Some(fb) => handle_potential_webgl_error!(self, fb.renderbuffer(attachment, rb)),
5004            None => self.webgl_error(InvalidOperation),
5005        };
5006    }
5007
5008    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6>
5009    fn FramebufferTexture2D(
5010        &self,
5011        target: u32,
5012        attachment: u32,
5013        textarget: u32,
5014        texture: Option<&WebGLTexture>,
5015        level: i32,
5016    ) {
5017        if let Some(texture) = texture {
5018            handle_potential_webgl_error!(self, self.validate_ownership(texture), return);
5019        }
5020
5021        if target != constants::FRAMEBUFFER {
5022            return self.webgl_error(InvalidEnum);
5023        }
5024
5025        // From the GLES 2.0.25 spec, page 113:
5026        //
5027        //     "level specifies the mipmap level of the texture image
5028        //      to be attached to the framebuffer and must be
5029        //      0. Otherwise, INVALID_VALUE is generated."
5030        if level != 0 {
5031            return self.webgl_error(InvalidValue);
5032        }
5033
5034        match self.bound_draw_framebuffer.get() {
5035            Some(fb) => handle_potential_webgl_error!(
5036                self,
5037                fb.texture2d(attachment, textarget, texture, level)
5038            ),
5039            None => self.webgl_error(InvalidOperation),
5040        };
5041    }
5042
5043    /// <https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9>
5044    fn GetAttachedShaders(&self, program: &WebGLProgram) -> Option<Vec<DomRoot<WebGLShader>>> {
5045        handle_potential_webgl_error!(self, self.validate_ownership(program), return None);
5046        handle_potential_webgl_error!(self, program.attached_shaders().map(Some), None)
5047    }
5048
5049    /// <https://immersive-web.github.io/webxr/#dom-webglrenderingcontextbase-makexrcompatible>
5050    #[cfg(feature = "webxr")]
5051    fn MakeXRCompatible(&self, cx: &mut js::context::JSContext) -> Rc<Promise> {
5052        // XXXManishearth Fill in with compatibility checks when rust-webxr supports this
5053        Promise::new_resolved(cx, &self.global(), ())
5054    }
5055}
5056
5057#[derive(Default, JSTraceable, MallocSizeOf)]
5058struct Capabilities {
5059    value: Cell<CapFlags>,
5060}
5061
5062impl Capabilities {
5063    fn set(&self, cap: u32, set: bool) -> WebGLResult<bool> {
5064        let cap = CapFlags::from_enum(cap)?;
5065        let mut value = self.value.get();
5066        if value.contains(cap) == set {
5067            return Ok(false);
5068        }
5069        value.set(cap, set);
5070        self.value.set(value);
5071        Ok(true)
5072    }
5073
5074    fn is_enabled(&self, cap: u32) -> WebGLResult<bool> {
5075        Ok(self.value.get().contains(CapFlags::from_enum(cap)?))
5076    }
5077}
5078
5079impl Default for CapFlags {
5080    fn default() -> Self {
5081        CapFlags::DITHER
5082    }
5083}
5084
5085macro_rules! capabilities {
5086    ($name:ident, $next:ident, $($rest:ident,)*) => {
5087        capabilities!($name, $next, $($rest,)* [$name = 1;]);
5088    };
5089    ($prev:ident, $name:ident, $($rest:ident,)* [$($tt:tt)*]) => {
5090        capabilities!($name, $($rest,)* [$($tt)* $name = Self::$prev.bits() << 1;]);
5091    };
5092    ($prev:ident, [$($name:ident = $value:expr;)*]) => {
5093        #[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
5094        pub(crate) struct CapFlags(u16);
5095
5096        bitflags! {
5097            impl CapFlags: u16 {
5098                $(const $name = $value;)*
5099            }
5100        }
5101
5102        impl CapFlags {
5103            fn from_enum(cap: u32) -> WebGLResult<Self> {
5104                match cap {
5105                    $(constants::$name => Ok(Self::$name),)*
5106                    _ => Err(InvalidEnum),
5107                }
5108            }
5109        }
5110    };
5111}
5112
5113capabilities! {
5114    BLEND,
5115    CULL_FACE,
5116    DEPTH_TEST,
5117    DITHER,
5118    POLYGON_OFFSET_FILL,
5119    SAMPLE_ALPHA_TO_COVERAGE,
5120    SAMPLE_COVERAGE,
5121    SCISSOR_TEST,
5122    STENCIL_TEST,
5123}
5124
5125#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
5126#[derive(JSTraceable, MallocSizeOf)]
5127pub(crate) struct Textures {
5128    active_unit: Cell<u32>,
5129    units: Box<[TextureUnit]>,
5130}
5131
5132impl Textures {
5133    fn new(max_combined_textures: u32) -> Self {
5134        Self {
5135            active_unit: Default::default(),
5136            units: (0..max_combined_textures)
5137                .map(|_| Default::default())
5138                .collect::<Vec<_>>()
5139                .into(),
5140        }
5141    }
5142
5143    pub(crate) fn active_unit_enum(&self) -> u32 {
5144        self.active_unit.get() + constants::TEXTURE0
5145    }
5146
5147    fn set_active_unit_enum(&self, index: u32) -> WebGLResult<()> {
5148        if (constants::TEXTURE0..constants::TEXTURE0 + self.units.len() as u32).contains(&index) {
5149            self.active_unit.set(index - constants::TEXTURE0);
5150            Ok(())
5151        } else {
5152            Err(InvalidEnum)
5153        }
5154    }
5155
5156    pub(crate) fn active_texture_slot(
5157        &self,
5158        target: u32,
5159        webgl_version: WebGLVersion,
5160    ) -> WebGLResult<&MutNullableDom<WebGLTexture>> {
5161        let active_unit = self.active_unit();
5162        let is_webgl2 = webgl_version == WebGLVersion::WebGL2;
5163        match target {
5164            constants::TEXTURE_2D => Ok(&active_unit.tex_2d),
5165            constants::TEXTURE_CUBE_MAP => Ok(&active_unit.tex_cube_map),
5166            WebGL2RenderingContextConstants::TEXTURE_2D_ARRAY if is_webgl2 => {
5167                Ok(&active_unit.tex_2d_array)
5168            },
5169            WebGL2RenderingContextConstants::TEXTURE_3D if is_webgl2 => Ok(&active_unit.tex_3d),
5170            _ => Err(InvalidEnum),
5171        }
5172    }
5173
5174    pub(crate) fn active_texture_for_image_target(
5175        &self,
5176        target: TexImageTarget,
5177    ) -> Option<DomRoot<WebGLTexture>> {
5178        let active_unit = self.active_unit();
5179        match target {
5180            TexImageTarget::Texture2D => active_unit.tex_2d.get(),
5181            TexImageTarget::Texture2DArray => active_unit.tex_2d_array.get(),
5182            TexImageTarget::Texture3D => active_unit.tex_3d.get(),
5183            TexImageTarget::CubeMap |
5184            TexImageTarget::CubeMapPositiveX |
5185            TexImageTarget::CubeMapNegativeX |
5186            TexImageTarget::CubeMapPositiveY |
5187            TexImageTarget::CubeMapNegativeY |
5188            TexImageTarget::CubeMapPositiveZ |
5189            TexImageTarget::CubeMapNegativeZ => active_unit.tex_cube_map.get(),
5190        }
5191    }
5192
5193    fn active_unit(&self) -> &TextureUnit {
5194        &self.units[self.active_unit.get() as usize]
5195    }
5196
5197    fn iter(&self) -> impl Iterator<Item = (u32, &TextureUnit)> {
5198        self.units
5199            .iter()
5200            .enumerate()
5201            .map(|(index, unit)| (index as u32 + constants::TEXTURE0, unit))
5202    }
5203}
5204
5205#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
5206#[derive(Default, JSTraceable, MallocSizeOf)]
5207struct TextureUnit {
5208    tex_2d: MutNullableDom<WebGLTexture>,
5209    tex_cube_map: MutNullableDom<WebGLTexture>,
5210    tex_2d_array: MutNullableDom<WebGLTexture>,
5211    tex_3d: MutNullableDom<WebGLTexture>,
5212}
5213
5214impl TextureUnit {
5215    fn unbind(&self, texture: &WebGLTexture) -> Option<u32> {
5216        let fields = [
5217            (&self.tex_2d, constants::TEXTURE_2D),
5218            (&self.tex_cube_map, constants::TEXTURE_CUBE_MAP),
5219            (
5220                &self.tex_2d_array,
5221                WebGL2RenderingContextConstants::TEXTURE_2D_ARRAY,
5222            ),
5223            (&self.tex_3d, WebGL2RenderingContextConstants::TEXTURE_3D),
5224        ];
5225        for &(slot, target) in &fields {
5226            if slot.get().is_some_and(|t| texture == &*t) {
5227                slot.set(None);
5228                return Some(target);
5229            }
5230        }
5231        None
5232    }
5233}
5234
5235pub(crate) struct TexPixels {
5236    data: GenericSharedMemory,
5237    size: Size2D<u32>,
5238    pixel_format: Option<PixelFormat>,
5239    alpha_treatment: Option<AlphaTreatment>,
5240    y_axis_treatment: YAxisTreatment,
5241}
5242
5243impl TexPixels {
5244    fn new(
5245        data: GenericSharedMemory,
5246        size: Size2D<u32>,
5247        pixel_format: PixelFormat,
5248        alpha_treatment: Option<AlphaTreatment>,
5249        y_axis_treatment: YAxisTreatment,
5250    ) -> Self {
5251        Self {
5252            data,
5253            size,
5254            pixel_format: Some(pixel_format),
5255            alpha_treatment,
5256            y_axis_treatment,
5257        }
5258    }
5259
5260    pub(crate) fn from_array(
5261        data: GenericSharedMemory,
5262        size: Size2D<u32>,
5263        alpha_treatment: Option<AlphaTreatment>,
5264        y_axis_treatment: YAxisTreatment,
5265    ) -> Self {
5266        Self {
5267            data,
5268            size,
5269            pixel_format: None,
5270            alpha_treatment,
5271            y_axis_treatment,
5272        }
5273    }
5274
5275    pub(crate) fn size(&self) -> Size2D<u32> {
5276        self.size
5277    }
5278
5279    pub(crate) fn pixel_format(&self) -> Option<PixelFormat> {
5280        self.pixel_format
5281    }
5282
5283    pub(crate) fn alpha_treatment(&self) -> Option<AlphaTreatment> {
5284        self.alpha_treatment
5285    }
5286
5287    pub(crate) fn y_axis_treatment(&self) -> YAxisTreatment {
5288        self.y_axis_treatment
5289    }
5290
5291    pub(crate) fn into_shared_memory(self) -> GenericSharedMemory {
5292        self.data
5293    }
5294}
5295
5296pub(crate) enum TexSource {
5297    Pixels(TexPixels),
5298    BufferOffset(i64),
5299}
5300
5301fn array_buffer_type_to_sized_type(type_: Type) -> Option<SizedDataType> {
5302    match type_ {
5303        Type::Uint8 | Type::Uint8Clamped => Some(SizedDataType::Uint8),
5304        Type::Uint16 => Some(SizedDataType::Uint16),
5305        Type::Uint32 => Some(SizedDataType::Uint32),
5306        Type::Int8 => Some(SizedDataType::Int8),
5307        Type::Int16 => Some(SizedDataType::Int16),
5308        Type::Int32 => Some(SizedDataType::Int32),
5309        Type::Float32 => Some(SizedDataType::Float32),
5310        Type::Float16 |
5311        Type::Float64 |
5312        Type::BigInt64 |
5313        Type::BigUint64 |
5314        Type::MaxTypedArrayViewType |
5315        Type::Int64 |
5316        Type::Simd128 => None,
5317    }
5318}