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