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