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