Skip to main content

script/dom/webgl/
webglframebuffer.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
6use std::cell::Cell;
7
8use dom_struct::dom_struct;
9#[cfg(feature = "webxr")]
10use euclid::Size2D;
11use js::context::JSContext;
12use script_bindings::cell::DomRefCell;
13use script_bindings::reflector::reflect_dom_object;
14use script_bindings::weakref::WeakRef;
15use servo_canvas_traits::webgl::{
16    TexFormat, WebGLCommand, WebGLError, WebGLFramebufferBindingRequest, WebGLFramebufferId,
17    WebGLRenderbufferId, WebGLResult, WebGLTextureId, WebGLVersion, webgl_channel,
18};
19#[cfg(feature = "webxr")]
20use webxr_api::Viewport;
21
22use crate::dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as constants;
23use crate::dom::bindings::inheritance::Castable;
24use crate::dom::bindings::reflector::DomGlobal;
25#[cfg(feature = "webxr")]
26use crate::dom::bindings::root::MutNullableDom;
27use crate::dom::bindings::root::{Dom, DomRoot};
28use crate::dom::webgl::webglobject::WebGLObject;
29use crate::dom::webgl::webglrenderbuffer::WebGLRenderbuffer;
30use crate::dom::webgl::webglrenderingcontext::{Operation, WebGLRenderingContext};
31use crate::dom::webgl::webgltexture::WebGLTexture;
32#[cfg(feature = "webxr")]
33use crate::dom::xrsession::XRSession;
34
35pub(crate) enum CompleteForRendering {
36    Complete,
37    Incomplete,
38}
39
40#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
41#[derive(Clone, JSTraceable, MallocSizeOf)]
42enum WebGLFramebufferAttachment {
43    Renderbuffer(Dom<WebGLRenderbuffer>),
44    Texture {
45        texture: Dom<WebGLTexture>,
46        level: i32,
47        /// Cube face or texture target, so faces count as distinct images.
48        target: u32,
49        /// Array or 3D slice; `None` for a 2D or cube face image.
50        layer: Option<i32>,
51    },
52}
53
54impl WebGLFramebufferAttachment {
55    fn needs_initialization(&self) -> bool {
56        match *self {
57            WebGLFramebufferAttachment::Renderbuffer(ref r) => !r.is_initialized(),
58            WebGLFramebufferAttachment::Texture { .. } => false,
59        }
60    }
61
62    fn mark_initialized(&self) {
63        match *self {
64            WebGLFramebufferAttachment::Renderbuffer(ref r) => r.mark_initialized(),
65            WebGLFramebufferAttachment::Texture { .. } => (),
66        }
67    }
68
69    /// Whether both hold one image: a renderbuffer, or one level, face and layer of a texture.
70    fn is_same_image(&self, other: &Self) -> bool {
71        use WebGLFramebufferAttachment::{Renderbuffer, Texture};
72        match (self, other) {
73            (Renderbuffer(a), Renderbuffer(b)) => a.id() == b.id(),
74            (
75                Texture {
76                    texture: a,
77                    level: level_a,
78                    target: target_a,
79                    layer: layer_a,
80                },
81                Texture {
82                    texture: b,
83                    level: level_b,
84                    target: target_b,
85                    layer: layer_b,
86                },
87            ) => {
88                a.id() == b.id() && level_a == level_b && target_a == target_b && layer_a == layer_b
89            },
90            _ => false,
91        }
92    }
93
94    fn root(&self) -> WebGLFramebufferAttachmentRoot {
95        match self {
96            WebGLFramebufferAttachment::Renderbuffer(rb) => {
97                WebGLFramebufferAttachmentRoot::Renderbuffer(DomRoot::from_ref(rb))
98            },
99            WebGLFramebufferAttachment::Texture { texture, .. } => {
100                WebGLFramebufferAttachmentRoot::Texture(DomRoot::from_ref(texture))
101            },
102        }
103    }
104
105    fn detach(&self) {
106        match self {
107            WebGLFramebufferAttachment::Renderbuffer(rb) => rb.detach_from_framebuffer(),
108            WebGLFramebufferAttachment::Texture { texture, .. } => {
109                texture.detach_from_framebuffer()
110            },
111        }
112    }
113}
114
115#[derive(Clone, JSTraceable, MallocSizeOf)]
116pub(crate) enum WebGLFramebufferAttachmentRoot {
117    Renderbuffer(DomRoot<WebGLRenderbuffer>),
118    Texture(DomRoot<WebGLTexture>),
119}
120
121#[derive(JSTraceable, MallocSizeOf)]
122struct DroppableWebGLFramebuffer {
123    #[no_trace]
124    id: WebGLFramebufferId,
125    is_deleted: Cell<bool>,
126    context: WeakRef<WebGLRenderingContext>,
127}
128
129impl DroppableWebGLFramebuffer {
130    fn new(
131        id: WebGLFramebufferId,
132        is_deleted: Cell<bool>,
133        context: WeakRef<WebGLRenderingContext>,
134    ) -> Self {
135        Self {
136            id,
137            is_deleted,
138            context,
139        }
140    }
141}
142
143impl DroppableWebGLFramebuffer {
144    pub(crate) fn id(&self) -> WebGLFramebufferId {
145        self.id
146    }
147    pub(crate) fn is_deleted(&self) -> bool {
148        self.is_deleted.get()
149    }
150
151    pub(crate) fn set_deleted(&self, deleted: bool) {
152        self.is_deleted.set(deleted);
153    }
154
155    pub(crate) fn delete(&self, operation_fallibility: Operation) {
156        if !self.is_deleted() {
157            self.set_deleted(true);
158            if let Some(context) = self.context.root() {
159                let cmd = WebGLCommand::DeleteFramebuffer(self.id());
160                match operation_fallibility {
161                    Operation::Fallible => context.send_command_ignored(cmd),
162                    Operation::Infallible => context.send_command(cmd),
163                }
164            }
165        }
166    }
167}
168
169impl Drop for DroppableWebGLFramebuffer {
170    fn drop(&mut self) {
171        self.delete(Operation::Fallible);
172    }
173}
174
175#[dom_struct]
176pub(crate) struct WebGLFramebuffer {
177    webgl_object: WebGLObject,
178    #[no_trace]
179    webgl_version: WebGLVersion,
180    target: Cell<Option<u32>>,
181    size: Cell<Option<(i32, i32)>>,
182    status: Cell<u32>,
183    // The attachment points for textures and renderbuffers on this
184    // FBO.
185    colors: Vec<DomRefCell<Option<WebGLFramebufferAttachment>>>,
186    depth: DomRefCell<Option<WebGLFramebufferAttachment>>,
187    stencil: DomRefCell<Option<WebGLFramebufferAttachment>>,
188    depthstencil: DomRefCell<Option<WebGLFramebufferAttachment>>,
189    color_read_buffer: Cell<u32>,
190    color_draw_buffers: DomRefCell<Vec<u32>>,
191    is_initialized: Cell<bool>,
192    // Framebuffers for XR keep a reference to the XR session.
193    // https://github.com/immersive-web/webxr/issues/856
194    #[cfg(feature = "webxr")]
195    xr_session: MutNullableDom<XRSession>,
196    droppable: DroppableWebGLFramebuffer,
197}
198
199impl WebGLFramebuffer {
200    fn new_inherited(context: &WebGLRenderingContext, id: WebGLFramebufferId) -> Self {
201        Self {
202            webgl_object: WebGLObject::new_inherited(context),
203            webgl_version: context.webgl_version(),
204            target: Cell::new(None),
205            size: Cell::new(None),
206            status: Cell::new(constants::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT),
207            colors: vec![DomRefCell::new(None); context.limits().max_color_attachments as usize],
208            depth: DomRefCell::new(None),
209            stencil: DomRefCell::new(None),
210            depthstencil: DomRefCell::new(None),
211            color_read_buffer: Cell::new(constants::COLOR_ATTACHMENT0),
212            color_draw_buffers: DomRefCell::new(vec![constants::COLOR_ATTACHMENT0]),
213            is_initialized: Cell::new(false),
214            #[cfg(feature = "webxr")]
215            xr_session: Default::default(),
216            droppable: DroppableWebGLFramebuffer::new(id, Cell::new(false), WeakRef::new(context)),
217        }
218    }
219
220    pub(crate) fn maybe_new(
221        cx: &mut JSContext,
222        context: &WebGLRenderingContext,
223    ) -> Option<DomRoot<Self>> {
224        let (sender, receiver) = webgl_channel().unwrap();
225        context.send_command(WebGLCommand::CreateFramebuffer(sender));
226        let id = receiver.recv().unwrap()?;
227        let framebuffer = WebGLFramebuffer::new(cx, context, id);
228        Some(framebuffer)
229    }
230
231    // TODO: depth, stencil and alpha
232    // https://github.com/servo/servo/issues/24498
233    #[cfg(feature = "webxr")]
234    pub(crate) fn maybe_new_webxr(
235        cx: &mut JSContext,
236        session: &XRSession,
237        context: &WebGLRenderingContext,
238        size: Size2D<i32, Viewport>,
239    ) -> Option<DomRoot<Self>> {
240        let framebuffer = Self::maybe_new(cx, context)?;
241        framebuffer.size.set(Some((size.width, size.height)));
242        framebuffer.status.set(constants::FRAMEBUFFER_COMPLETE);
243        framebuffer.xr_session.set(Some(session));
244        Some(framebuffer)
245    }
246
247    pub(crate) fn new(
248        cx: &mut JSContext,
249        context: &WebGLRenderingContext,
250        id: WebGLFramebufferId,
251    ) -> DomRoot<Self> {
252        reflect_dom_object(
253            cx,
254            Box::new(WebGLFramebuffer::new_inherited(context, id)),
255            &*context.global(),
256        )
257    }
258}
259
260impl WebGLFramebuffer {
261    pub(crate) fn id(&self) -> WebGLFramebufferId {
262        self.droppable.id()
263    }
264
265    #[cfg(feature = "webxr")]
266    fn is_in_xr_session(&self) -> bool {
267        self.xr_session.get().is_some()
268    }
269
270    #[cfg(not(feature = "webxr"))]
271    fn is_in_xr_session(&self) -> bool {
272        false
273    }
274
275    pub(crate) fn validate_transparent(&self) -> WebGLResult<()> {
276        if self.is_in_xr_session() {
277            Err(WebGLError::InvalidOperation)
278        } else {
279            Ok(())
280        }
281    }
282
283    pub(crate) fn bind(&self, target: u32) {
284        if !self.is_in_xr_session() {
285            // Update the framebuffer status on binding.  It may have
286            // changed if its attachments were resized or deleted while
287            // we've been unbound.
288            self.update_status();
289        }
290
291        self.target.set(Some(target));
292        self.upcast().send_command(WebGLCommand::BindFramebuffer(
293            target,
294            WebGLFramebufferBindingRequest::Explicit(self.id()),
295        ));
296    }
297
298    pub(crate) fn delete(&self, operation_fallibility: Operation) {
299        self.droppable.delete(operation_fallibility);
300    }
301
302    pub(crate) fn is_deleted(&self) -> bool {
303        // TODO: if a framebuffer has an attachment which is invalid due to
304        // being outside a webxr rAF, should this make the framebuffer invalid?
305        // https://github.com/immersive-web/layers/issues/196
306        self.droppable.is_deleted()
307    }
308
309    pub(crate) fn size(&self) -> Option<(i32, i32)> {
310        self.size.get()
311    }
312
313    pub(crate) fn get_attachment_formats(
314        &self,
315    ) -> WebGLResult<(Option<u32>, Option<u32>, Option<u32>)> {
316        if self.check_status() != constants::FRAMEBUFFER_COMPLETE {
317            return Err(WebGLError::InvalidFramebufferOperation);
318        }
319        Ok((
320            self.attachment_gl_format(self.read_buffer()),
321            self.attachment_gl_format(constants::DEPTH_ATTACHMENT),
322            self.attachment_gl_format(constants::STENCIL_ATTACHMENT),
323        ))
324    }
325
326    pub(crate) fn color_draw_buffer_formats(&self) -> Vec<u32> {
327        self.color_draw_buffers
328            .borrow()
329            .iter()
330            .filter_map(|&buffer| self.attachment_gl_format(buffer))
331            .collect()
332    }
333
334    pub(crate) fn color_read_buffer_is_texture(&self) -> bool {
335        matches!(
336            self.attachment(self.read_buffer()),
337            Some(WebGLFramebufferAttachmentRoot::Texture(_))
338        )
339    }
340
341    fn attachment_gl_format(&self, attachment: u32) -> Option<u32> {
342        self.attachment_effective_format(attachment)
343            .map(|format| format.as_gl_constant())
344    }
345
346    fn check_attachment_constraints<'a>(
347        &self,
348        attachment: &Option<WebGLFramebufferAttachment>,
349        mut constraints: impl Iterator<Item = &'a u32>,
350        fb_size: &mut Option<(i32, i32)>,
351    ) -> Result<(), u32> {
352        // Get the size of this attachment.
353        let (format, size) = match attachment {
354            Some(WebGLFramebufferAttachment::Renderbuffer(att_rb)) => {
355                (Some(att_rb.internal_format()), att_rb.size())
356            },
357            Some(WebGLFramebufferAttachment::Texture {
358                texture: att_tex,
359                level,
360                ..
361            }) => match att_tex.image_info_at_face(0, *level as u32) {
362                Some(info) => (
363                    Some(info.internal_format().as_gl_constant()),
364                    Some((info.width() as i32, info.height() as i32)),
365                ),
366                None => return Err(constants::FRAMEBUFFER_INCOMPLETE_ATTACHMENT),
367            },
368            None => (None, None),
369        };
370
371        // Make sure that, if we've found any other attachment,
372        // that the size matches.
373        if size.is_some() {
374            if fb_size.is_some() && size != *fb_size {
375                return Err(constants::FRAMEBUFFER_INCOMPLETE_DIMENSIONS);
376            } else {
377                *fb_size = size;
378            }
379        }
380
381        if let Some(format) = format &&
382            constraints.all(|c| *c != format)
383        {
384            return Err(constants::FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
385        }
386
387        Ok(())
388    }
389
390    /// Whether one image sits behind two color attachment points, which WebGL 2 reports as
391    /// `FRAMEBUFFER_UNSUPPORTED`.
392    fn has_shared_color_image(&self) -> bool {
393        self.colors.iter().enumerate().any(|(i, slot)| {
394            let slot = slot.borrow();
395            let Some(att) = slot.as_ref() else {
396                return false;
397            };
398            self.colors[..i].iter().any(|earlier| {
399                earlier
400                    .borrow()
401                    .as_ref()
402                    .is_some_and(|earlier| earlier.is_same_image(att))
403            })
404        })
405    }
406
407    pub(crate) fn update_status(&self) {
408        let z = self.depth.borrow();
409        let s = self.stencil.borrow();
410        let zs = self.depthstencil.borrow();
411        let has_z = z.is_some();
412        let has_s = s.is_some();
413        let has_zs = zs.is_some();
414
415        let is_supported = match self.webgl_version {
416            // From the WebGL 1.0 spec, 6.6 ("Framebuffer Object Attachments"):
417            //
418            //    "In the WebGL API, it is an error to concurrently attach
419            //     renderbuffers to the following combinations of
420            //     attachment points:
421            //
422            //     DEPTH_ATTACHMENT + DEPTH_STENCIL_ATTACHMENT
423            //     STENCIL_ATTACHMENT + DEPTH_STENCIL_ATTACHMENT
424            //     DEPTH_ATTACHMENT + STENCIL_ATTACHMENT
425            //
426            //     If any of the constraints above are violated, then:
427            //
428            //     checkFramebufferStatus must return FRAMEBUFFER_UNSUPPORTED."
429            WebGLVersion::WebGL1 => !(has_zs && (has_z || has_s)) && !(has_z && has_s),
430
431            // In WebGL 2.0, DEPTH_STENCIL_ATTACHMENT is considered an alias for
432            // DEPTH_ATTACHMENT + STENCIL_ATTACHMENT, i.e., the same image is attached to both DEPTH_ATTACHMENT
433            // and STENCIL_ATTACHMENT, overwriting the original images attached to the two attachment points.
434            // If different images are bound to the depth and stencil attachment points, checkFramebufferStatus
435            // returns FRAMEBUFFER_UNSUPPORTED, and getFramebufferAttachmentParameter with attachment of
436            // DEPTH_STENCIL_ATTACHMENT generates an INVALID_OPERATION error.
437            // -- WebGL 2.0 spec, 4.1.5 Framebuffer Object Attachments
438            WebGLVersion::WebGL2 => {
439                let depth_stencil_match = match (&*z, &*s) {
440                    (Some(z), Some(s)) => z.is_same_image(s),
441                    _ => true,
442                };
443                depth_stencil_match && !self.has_shared_color_image()
444            },
445        };
446        if !is_supported {
447            return self.status.set(constants::FRAMEBUFFER_UNSUPPORTED);
448        }
449
450        let mut fb_size = None;
451
452        let attachments = [&*z, &*s, &*zs];
453        let webgl1_attachment_constraints = &[
454            &[
455                constants::DEPTH_COMPONENT16,
456                constants::DEPTH_COMPONENT24,
457                constants::DEPTH_COMPONENT32F,
458                constants::DEPTH24_STENCIL8,
459                constants::DEPTH32F_STENCIL8,
460            ][..],
461            &[
462                constants::STENCIL_INDEX8,
463                constants::DEPTH24_STENCIL8,
464                constants::DEPTH32F_STENCIL8,
465            ][..],
466            &[constants::DEPTH_STENCIL][..],
467        ];
468        let webgl2_attachment_constraints = &[
469            &[constants::DEPTH_STENCIL][..],
470            &[constants::DEPTH_STENCIL][..],
471            &[][..],
472        ];
473        let empty_attachment_constrains = &[&[][..], &[][..], &[][..]];
474        let extra_attachment_constraints = match self.webgl_version {
475            WebGLVersion::WebGL1 => empty_attachment_constrains,
476            WebGLVersion::WebGL2 => webgl2_attachment_constraints,
477        };
478        let attachment_constraints = webgl1_attachment_constraints
479            .iter()
480            .zip(extra_attachment_constraints.iter())
481            .map(|(a, b)| a.iter().chain(b.iter()));
482
483        for (attachment, constraints) in attachments.iter().zip(attachment_constraints) {
484            if let Err(errnum) =
485                self.check_attachment_constraints(attachment, constraints, &mut fb_size)
486            {
487                return self.status.set(errnum);
488            }
489        }
490
491        let webgl1_color_constraints = &[
492            constants::RGB,
493            constants::RGB565,
494            constants::RGB5_A1,
495            constants::RGBA,
496            constants::RGBA4,
497        ][..];
498        // The color-renderable formats of OpenGL ES 3.0.6 table 3.13, plus those of
499        // EXT_color_buffer_float.
500        let webgl2_color_constraints = &[
501            constants::R8,
502            constants::R8I,
503            constants::R8UI,
504            constants::R16I,
505            constants::R16UI,
506            constants::R32I,
507            constants::R32UI,
508            constants::RG8,
509            constants::RG8I,
510            constants::RG8UI,
511            constants::RG16I,
512            constants::RG16UI,
513            constants::RG32I,
514            constants::RG32UI,
515            constants::RGB8,
516            constants::RGBA8,
517            constants::SRGB8_ALPHA8,
518            constants::RGB10_A2,
519            constants::RGB10_A2UI,
520            constants::RGBA8I,
521            constants::RGBA8UI,
522            constants::RGBA16I,
523            constants::RGBA16UI,
524            constants::RGBA32I,
525            constants::RGBA32UI,
526            // TODO: gate these behind EXT_color_buffer_float once Servo exposes it.
527            constants::R16F,
528            constants::RG16F,
529            constants::RGBA16F,
530            constants::R32F,
531            constants::RG32F,
532            constants::RGBA32F,
533            constants::R11F_G11F_B10F,
534        ][..];
535        let empty_color_constrains = &[][..];
536        let extra_color_constraints = match self.webgl_version {
537            WebGLVersion::WebGL1 => empty_color_constrains,
538            WebGLVersion::WebGL2 => webgl2_color_constraints,
539        };
540        let color_constraints = webgl1_color_constraints
541            .iter()
542            .chain(extra_color_constraints.iter());
543
544        let has_c = self.colors.iter().any(|att| att.borrow().is_some());
545        for attachment in self.colors.iter() {
546            let attachment = attachment.borrow();
547            let constraints = color_constraints.clone();
548            if let Err(errnum) =
549                self.check_attachment_constraints(&attachment, constraints, &mut fb_size)
550            {
551                return self.status.set(errnum);
552            }
553        }
554
555        self.size.set(fb_size);
556
557        if has_c || has_z || has_zs || has_s {
558            if self.size.get().is_some_and(|(w, h)| w != 0 && h != 0) {
559                self.status.set(constants::FRAMEBUFFER_COMPLETE);
560            } else {
561                self.status
562                    .set(constants::FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
563            }
564        } else {
565            self.status
566                .set(constants::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
567        }
568    }
569
570    pub(crate) fn check_status(&self) -> u32 {
571        // For opaque framebuffers, check to see if the XR session is currently processing an rAF
572        // https://immersive-web.github.io/webxr/#opaque-framebuffer
573        #[cfg(feature = "webxr")]
574        if let Some(xr_session) = self.xr_session.get() {
575            return if xr_session.is_outside_raf() {
576                constants::FRAMEBUFFER_UNSUPPORTED
577            } else {
578                constants::FRAMEBUFFER_COMPLETE
579            };
580        }
581
582        self.status.get()
583        // TODO: if a framebuffer has an attachment which is invalid due to
584        // being outside a webxr rAF, should this make the framebuffer incomplete?
585        // https://github.com/immersive-web/layers/issues/196
586    }
587
588    pub(crate) fn has_color_attachment(&self) -> bool {
589        self.colors
590            .iter()
591            .any(|attachment| attachment.borrow().is_some())
592    }
593
594    pub(crate) fn check_status_for_rendering(&self) -> CompleteForRendering {
595        let result = self.check_status();
596        if result != constants::FRAMEBUFFER_COMPLETE {
597            return CompleteForRendering::Incomplete;
598        }
599
600        // XR framebuffers are complete inside an rAF
601        // https://github.com/immersive-web/webxr/issues/854
602        #[cfg(feature = "webxr")]
603        if self.xr_session.get().is_some() {
604            return CompleteForRendering::Complete;
605        }
606
607        if !self.is_initialized.get() {
608            let attachments = [
609                (&self.depth, constants::DEPTH_BUFFER_BIT),
610                (&self.stencil, constants::STENCIL_BUFFER_BIT),
611                (
612                    &self.depthstencil,
613                    constants::DEPTH_BUFFER_BIT | constants::STENCIL_BUFFER_BIT,
614                ),
615            ];
616            let colors = self
617                .colors
618                .iter()
619                .map(|attachment| (attachment, constants::COLOR_BUFFER_BIT));
620            // Collect every bit before marking: in WebGL 2 one image can fill two slots.
621            let mut clear_bits = 0;
622            for (attachment, bits) in attachments.into_iter().chain(colors.clone()) {
623                if let Some(ref att) = *attachment.borrow() &&
624                    att.needs_initialization()
625                {
626                    clear_bits |= bits;
627                }
628            }
629            for (attachment, _) in attachments.into_iter().chain(colors) {
630                if let Some(ref att) = *attachment.borrow() {
631                    att.mark_initialized();
632                }
633            }
634
635            if let Some(context) = self.upcast().context() {
636                context.initialize_framebuffer(clear_bits);
637            }
638
639            self.is_initialized.set(true);
640        }
641
642        // TODO: if a framebuffer has an attachment which is invalid due to
643        // being outside a webxr rAF, should this make the framebuffer incomplete?
644        // https://github.com/immersive-web/layers/issues/196
645
646        CompleteForRendering::Complete
647    }
648
649    /// Clears the uninitialized attachments of this framebuffer, which is bound for reading only.
650    /// Clearing requires a draw binding, so the `draw_framebuffer` binding is restored afterwards.
651    pub(crate) fn initialize_for_reading(&self, draw_framebuffer: Option<&WebGLFramebuffer>) {
652        if self.is_initialized.get() {
653            return;
654        }
655        let bind_draw = |request| {
656            self.upcast().send_command(WebGLCommand::BindFramebuffer(
657                constants::DRAW_FRAMEBUFFER,
658                request,
659            ))
660        };
661        bind_draw(WebGLFramebufferBindingRequest::Explicit(self.id()));
662        self.check_status_for_rendering();
663        bind_draw(
664            draw_framebuffer.map_or(WebGLFramebufferBindingRequest::Default, |fb| {
665                WebGLFramebufferBindingRequest::Explicit(fb.id())
666            }),
667        );
668    }
669
670    pub(crate) fn renderbuffer(
671        &self,
672        attachment: u32,
673        rb: Option<&WebGLRenderbuffer>,
674    ) -> WebGLResult<()> {
675        // Opaque framebuffers cannot have their attachments changed
676        // https://immersive-web.github.io/webxr/#opaque-framebuffer
677        self.validate_transparent()?;
678
679        let binding = self
680            .attachment_binding(attachment)
681            .ok_or(WebGLError::InvalidEnum)?;
682
683        let rb_id = match rb {
684            Some(rb) => {
685                if !rb.ever_bound() {
686                    return Err(WebGLError::InvalidOperation);
687                }
688                *binding.borrow_mut() =
689                    Some(WebGLFramebufferAttachment::Renderbuffer(Dom::from_ref(rb)));
690                self.mirror_alias(binding, attachment);
691                rb.attach_to_framebuffer(self);
692                Some(rb.id())
693            },
694
695            _ => None,
696        };
697
698        self.upcast()
699            .send_command(WebGLCommand::FramebufferRenderbuffer(
700                self.target.get().unwrap(),
701                attachment,
702                constants::RENDERBUFFER,
703                rb_id,
704            ));
705
706        if rb.is_none() {
707            self.detach_binding(binding, attachment)?;
708        }
709
710        self.update_status();
711        self.is_initialized.set(false);
712        Ok(())
713    }
714
715    fn detach_binding(
716        &self,
717        binding: &DomRefCell<Option<WebGLFramebufferAttachment>>,
718        attachment: u32,
719    ) -> WebGLResult<()> {
720        // Opaque framebuffers cannot have their attachments changed
721        // https://immersive-web.github.io/webxr/#opaque-framebuffer
722        self.validate_transparent()?;
723
724        for slot in std::iter::once(binding).chain(self.aliased_binding(attachment)) {
725            if let Some(att) = &*slot.borrow() {
726                att.detach();
727            }
728            *slot.borrow_mut() = None;
729        }
730        if INTERESTING_ATTACHMENT_POINTS.contains(&attachment) {
731            self.reattach_depth_stencil()?;
732        }
733        Ok(())
734    }
735
736    fn attachment_binding(
737        &self,
738        attachment: u32,
739    ) -> Option<&DomRefCell<Option<WebGLFramebufferAttachment>>> {
740        match attachment {
741            constants::COLOR_ATTACHMENT0..=constants::COLOR_ATTACHMENT15 => {
742                let idx = attachment - constants::COLOR_ATTACHMENT0;
743                self.colors.get(idx as usize)
744            },
745            constants::DEPTH_ATTACHMENT => Some(&self.depth),
746            constants::STENCIL_ATTACHMENT => Some(&self.stencil),
747            constants::DEPTH_STENCIL_ATTACHMENT => match self.webgl_version {
748                WebGLVersion::WebGL1 => Some(&self.depthstencil),
749                WebGLVersion::WebGL2 => Some(&self.depth),
750            },
751            _ => None,
752        }
753    }
754
755    /// Returns the stencil slot for WebGL 2's `DEPTH_STENCIL_ATTACHMENT`, which aliases
756    /// `DEPTH_ATTACHMENT` + `STENCIL_ATTACHMENT`, and `None` for any other attachment.
757    fn aliased_binding(
758        &self,
759        attachment: u32,
760    ) -> Option<&DomRefCell<Option<WebGLFramebufferAttachment>>> {
761        (self.webgl_version == WebGLVersion::WebGL2 &&
762            attachment == constants::DEPTH_STENCIL_ATTACHMENT)
763            .then_some(&self.stencil)
764    }
765
766    fn mirror_alias(
767        &self,
768        binding: &DomRefCell<Option<WebGLFramebufferAttachment>>,
769        attachment: u32,
770    ) {
771        if let Some(alias) = self.aliased_binding(attachment) {
772            *alias.borrow_mut() = binding.borrow().clone();
773        }
774    }
775
776    fn reattach_depth_stencil(&self) -> WebGLResult<()> {
777        // Opaque framebuffers cannot have their attachments changed
778        // https://immersive-web.github.io/webxr/#opaque-framebuffer
779        self.validate_transparent()?;
780
781        // WebGL 2 attachment points match GL's, so there is nothing to restore.
782        if self.webgl_version == WebGLVersion::WebGL2 {
783            return Ok(());
784        }
785
786        let reattach = |attachment: &WebGLFramebufferAttachment, attachment_point| {
787            let webgl_object = self.upcast();
788            match *attachment {
789                WebGLFramebufferAttachment::Renderbuffer(ref rb) => {
790                    rb.attach_to_framebuffer(self);
791                    webgl_object.send_command(WebGLCommand::FramebufferRenderbuffer(
792                        self.target.get().unwrap(),
793                        attachment_point,
794                        constants::RENDERBUFFER,
795                        Some(rb.id()),
796                    ));
797                },
798                WebGLFramebufferAttachment::Texture {
799                    ref texture, level, ..
800                } => {
801                    texture.attach_to_framebuffer(self);
802                    webgl_object.send_command(WebGLCommand::FramebufferTexture2D(
803                        self.target.get().unwrap(),
804                        attachment_point,
805                        texture.target().expect("missing texture target"),
806                        Some(texture.id()),
807                        level,
808                    ));
809                },
810            }
811        };
812
813        // Since the DEPTH_STENCIL attachment causes both the DEPTH and STENCIL
814        // attachments to be overwritten, we need to ensure that we reattach
815        // the DEPTH and STENCIL attachments when any of those attachments
816        // is cleared.
817        if let Some(ref depth) = *self.depth.borrow() {
818            reattach(depth, constants::DEPTH_ATTACHMENT);
819        }
820        if let Some(ref stencil) = *self.stencil.borrow() {
821            reattach(stencil, constants::STENCIL_ATTACHMENT);
822        }
823        if let Some(ref depth_stencil) = *self.depthstencil.borrow() {
824            reattach(depth_stencil, constants::DEPTH_STENCIL_ATTACHMENT);
825        }
826        Ok(())
827    }
828
829    pub(crate) fn attachment(&self, attachment: u32) -> Option<WebGLFramebufferAttachmentRoot> {
830        let binding = self.attachment_binding(attachment)?;
831        binding
832            .borrow()
833            .as_ref()
834            .map(WebGLFramebufferAttachment::root)
835    }
836
837    /// Returns the effective internal format of the image bound to `attachment`: the sized
838    /// format it was created with, or the sized format corresponding to its unsized format
839    /// and type; `None` if no image is bound or script does not track its format.
840    pub(crate) fn attachment_effective_format(&self, attachment: u32) -> Option<TexFormat> {
841        match self.attachment_binding(attachment)?.borrow().as_ref()? {
842            WebGLFramebufferAttachment::Renderbuffer(rb) => {
843                TexFormat::from_gl_constant(rb.internal_format())
844            },
845            WebGLFramebufferAttachment::Texture { texture, level, .. } => {
846                let info = texture.image_info_at_face(0, *level as u32)?;
847                Some(match info.data_type() {
848                    Some(data_type) => info.internal_format().effective_internal_format(data_type),
849                    None => info.internal_format(),
850                })
851            },
852        }
853    }
854
855    pub(crate) fn texture2d(
856        &self,
857        attachment: u32,
858        textarget: u32,
859        texture: Option<&WebGLTexture>,
860        level: i32,
861    ) -> WebGLResult<()> {
862        // Opaque framebuffers cannot have their attachments changed
863        // https://immersive-web.github.io/webxr/#opaque-framebuffer
864        self.validate_transparent()?;
865        if let Some(texture) = texture {
866            //     "If texture is not zero, then texture must either
867            //      name an existing texture object with an target of
868            //      textarget, or texture must name an existing cube
869            //      map texture and textarget must be one of:
870            //      TEXTURE_CUBE_MAP_POSITIVE_X,
871            //      TEXTURE_CUBE_MAP_POSITIVE_Y,
872            //      TEXTURE_CUBE_MAP_POSITIVE_Z,
873            //      TEXTURE_CUBE_MAP_NEGATIVE_X,
874            //      TEXTURE_CUBE_MAP_NEGATIVE_Y, or
875            //      TEXTURE_CUBE_MAP_NEGATIVE_Z. Otherwise,
876            //      INVALID_OPERATION is generated."
877            let is_cube = match textarget {
878                constants::TEXTURE_2D => false,
879
880                constants::TEXTURE_CUBE_MAP_POSITIVE_X => true,
881                constants::TEXTURE_CUBE_MAP_POSITIVE_Y => true,
882                constants::TEXTURE_CUBE_MAP_POSITIVE_Z => true,
883                constants::TEXTURE_CUBE_MAP_NEGATIVE_X => true,
884                constants::TEXTURE_CUBE_MAP_NEGATIVE_Y => true,
885                constants::TEXTURE_CUBE_MAP_NEGATIVE_Z => true,
886
887                _ => return Err(WebGLError::InvalidEnum),
888            };
889
890            match texture.target() {
891                Some(constants::TEXTURE_CUBE_MAP) if is_cube => {},
892                Some(_) if !is_cube => {},
893                _ => return Err(WebGLError::InvalidOperation),
894            }
895
896            let Some(context) = self.upcast().context() else {
897                return Err(WebGLError::ContextLost);
898            };
899            let max_tex_size = if is_cube {
900                context.limits().max_cube_map_tex_size
901            } else {
902                context.limits().max_tex_size
903            };
904            if level < 0 || level as u32 > max_tex_size.ilog2() {
905                return Err(WebGLError::InvalidValue);
906            }
907        }
908        self.texture2d_even_if_opaque(attachment, textarget, texture, level)
909    }
910
911    pub(crate) fn texture2d_even_if_opaque(
912        &self,
913        attachment: u32,
914        textarget: u32,
915        texture: Option<&WebGLTexture>,
916        level: i32,
917    ) -> WebGLResult<()> {
918        let binding = self
919            .attachment_binding(attachment)
920            .ok_or(WebGLError::InvalidEnum)?;
921
922        let tex_id = match texture {
923            // Note, from the GLES 2.0.25 spec, page 113:
924            //      "If texture is zero, then textarget and level are ignored."
925            Some(texture) => {
926                *binding.borrow_mut() = Some(WebGLFramebufferAttachment::Texture {
927                    texture: Dom::from_ref(texture),
928                    level,
929                    target: textarget,
930                    layer: None,
931                });
932                self.mirror_alias(binding, attachment);
933                texture.attach_to_framebuffer(self);
934
935                Some(texture.id())
936            },
937
938            _ => None,
939        };
940
941        self.upcast()
942            .send_command(WebGLCommand::FramebufferTexture2D(
943                self.target.get().unwrap(),
944                attachment,
945                textarget,
946                tex_id,
947                level,
948            ));
949
950        if texture.is_none() {
951            self.detach_binding(binding, attachment)?;
952        }
953
954        self.update_status();
955        self.is_initialized.set(false);
956        Ok(())
957    }
958
959    pub(crate) fn texture_layer(
960        &self,
961        attachment: u32,
962        texture: Option<&WebGLTexture>,
963        level: i32,
964        layer: i32,
965    ) -> WebGLResult<()> {
966        // Opaque framebuffers cannot have their attachments changed
967        // https://immersive-web.github.io/webxr/#opaque-framebuffer
968        self.validate_transparent()?;
969
970        let binding = self
971            .attachment_binding(attachment)
972            .ok_or(WebGLError::InvalidEnum)?;
973
974        let Some(context) = self.upcast().context() else {
975            return Err(WebGLError::ContextLost);
976        };
977
978        let tex_id = match texture {
979            Some(texture) => {
980                let (target, max_level, max_layer) = match texture.target() {
981                    Some(target @ constants::TEXTURE_3D) => (
982                        target,
983                        context.limits().max_3d_texture_size.ilog2(),
984                        context.limits().max_3d_texture_size - 1,
985                    ),
986                    Some(target @ constants::TEXTURE_2D_ARRAY) => (
987                        target,
988                        context.limits().max_tex_size.ilog2(),
989                        context.limits().max_array_texture_layers - 1,
990                    ),
991                    _ => return Err(WebGLError::InvalidOperation),
992                };
993
994                if level < 0 || level as u32 > max_level {
995                    return Err(WebGLError::InvalidValue);
996                }
997                if layer < 0 || layer as u32 > max_layer {
998                    return Err(WebGLError::InvalidValue);
999                }
1000
1001                *binding.borrow_mut() = Some(WebGLFramebufferAttachment::Texture {
1002                    texture: Dom::from_ref(texture),
1003                    level,
1004                    target,
1005                    layer: Some(layer),
1006                });
1007                self.mirror_alias(binding, attachment);
1008                texture.attach_to_framebuffer(self);
1009
1010                Some(texture.id())
1011            },
1012            _ => None,
1013        };
1014
1015        context.send_command(WebGLCommand::FramebufferTextureLayer(
1016            self.target.get().unwrap(),
1017            attachment,
1018            tex_id,
1019            level,
1020            layer,
1021        ));
1022
1023        if texture.is_none() {
1024            self.detach_binding(binding, attachment)?;
1025        }
1026
1027        self.update_status();
1028        self.is_initialized.set(false);
1029        Ok(())
1030    }
1031
1032    fn with_matching_renderbuffers_id<F>(&self, rb_id: &WebGLRenderbufferId, mut closure: F)
1033    where
1034        F: FnMut(&DomRefCell<Option<WebGLFramebufferAttachment>>, u32),
1035    {
1036        let attachments = [
1037            (&self.depth, constants::DEPTH_ATTACHMENT),
1038            (&self.stencil, constants::STENCIL_ATTACHMENT),
1039            (&self.depthstencil, constants::DEPTH_STENCIL_ATTACHMENT),
1040        ];
1041
1042        fn has_matching_id(
1043            attachment: &DomRefCell<Option<WebGLFramebufferAttachment>>,
1044            target: &WebGLRenderbufferId,
1045        ) -> bool {
1046            match *attachment.borrow() {
1047                Some(WebGLFramebufferAttachment::Renderbuffer(ref att_rb)) => {
1048                    att_rb.id() == *target
1049                },
1050                _ => false,
1051            }
1052        }
1053
1054        for (attachment, name) in &attachments {
1055            if has_matching_id(attachment, rb_id) {
1056                closure(attachment, *name);
1057            }
1058        }
1059
1060        for (idx, attachment) in self.colors.iter().enumerate() {
1061            if has_matching_id(attachment, rb_id) {
1062                let name = constants::COLOR_ATTACHMENT0 + idx as u32;
1063                closure(attachment, name);
1064            }
1065        }
1066    }
1067
1068    fn with_matching_textures_id<F>(&self, tex_id: WebGLTextureId, mut closure: F)
1069    where
1070        F: FnMut(&DomRefCell<Option<WebGLFramebufferAttachment>>, u32),
1071    {
1072        let attachments = [
1073            (&self.depth, constants::DEPTH_ATTACHMENT),
1074            (&self.stencil, constants::STENCIL_ATTACHMENT),
1075            (&self.depthstencil, constants::DEPTH_STENCIL_ATTACHMENT),
1076        ];
1077
1078        fn has_matching_id(
1079            attachment: &DomRefCell<Option<WebGLFramebufferAttachment>>,
1080            target: &WebGLTextureId,
1081        ) -> bool {
1082            matches!(*attachment.borrow(), Some(WebGLFramebufferAttachment::Texture {
1083                                     texture: ref att_texture,
1084                                     ..
1085                                }) if att_texture.id() == *target)
1086        }
1087
1088        for (attachment, name) in &attachments {
1089            if has_matching_id(attachment, &tex_id) {
1090                closure(attachment, *name);
1091            }
1092        }
1093
1094        for (idx, attachment) in self.colors.iter().enumerate() {
1095            if has_matching_id(attachment, &tex_id) {
1096                let name = constants::COLOR_ATTACHMENT0 + idx as u32;
1097                closure(attachment, name);
1098            }
1099        }
1100    }
1101
1102    pub(crate) fn detach_renderbuffer_by_id(&self, rb_id: &WebGLRenderbufferId) -> WebGLResult<()> {
1103        // Opaque framebuffers cannot have their attachments changed
1104        // https://immersive-web.github.io/webxr/#opaque-framebuffer
1105        self.validate_transparent()?;
1106
1107        let mut depth_or_stencil_updated = false;
1108        self.with_matching_renderbuffers_id(rb_id, |att, name| {
1109            depth_or_stencil_updated |= INTERESTING_ATTACHMENT_POINTS.contains(&name);
1110            if let Some(att) = &*att.borrow() {
1111                att.detach();
1112            }
1113            *att.borrow_mut() = None;
1114            self.update_status();
1115        });
1116
1117        if depth_or_stencil_updated {
1118            self.reattach_depth_stencil()?;
1119        }
1120        Ok(())
1121    }
1122
1123    pub(crate) fn detach_texture(&self, tex_id: WebGLTextureId) -> WebGLResult<()> {
1124        // Opaque framebuffers cannot have their attachments changed
1125        // https://immersive-web.github.io/webxr/#opaque-framebuffer
1126        self.validate_transparent()?;
1127
1128        let mut depth_or_stencil_updated = false;
1129        self.with_matching_textures_id(tex_id, |att, name| {
1130            depth_or_stencil_updated |= INTERESTING_ATTACHMENT_POINTS.contains(&name);
1131            if let Some(att) = &*att.borrow() {
1132                att.detach();
1133            }
1134            *att.borrow_mut() = None;
1135            self.update_status();
1136        });
1137
1138        if depth_or_stencil_updated {
1139            self.reattach_depth_stencil()?;
1140        }
1141        Ok(())
1142    }
1143
1144    pub(crate) fn invalidate_renderbuffer(&self, rb: &WebGLRenderbuffer) {
1145        self.with_matching_renderbuffers_id(&rb.id(), |_att, _| {
1146            self.is_initialized.set(false);
1147            self.update_status();
1148        });
1149    }
1150
1151    pub(crate) fn invalidate_texture(&self, texture: &WebGLTexture) {
1152        self.with_matching_textures_id(texture.id(), |_att, _name| {
1153            self.update_status();
1154        });
1155    }
1156
1157    pub(crate) fn set_read_buffer(&self, buffer: u32) -> WebGLResult<()> {
1158        let Some(context) = self.upcast().context() else {
1159            return Err(WebGLError::ContextLost);
1160        };
1161
1162        match buffer {
1163            constants::NONE => {},
1164            _ if context.valid_color_attachment_enum(buffer) => {},
1165            _ => return Err(WebGLError::InvalidOperation),
1166        };
1167
1168        self.color_read_buffer.set(buffer);
1169        context.send_command(WebGLCommand::ReadBuffer(buffer));
1170        Ok(())
1171    }
1172
1173    pub(crate) fn set_draw_buffers(&self, buffers: Vec<u32>) -> WebGLResult<()> {
1174        let Some(context) = self.upcast().context() else {
1175            return Err(WebGLError::ContextLost);
1176        };
1177
1178        if buffers.len() > context.limits().max_draw_buffers as usize {
1179            return Err(WebGLError::InvalidValue);
1180        }
1181
1182        let enums_valid = buffers
1183            .iter()
1184            .all(|&val| val == constants::NONE || context.valid_color_attachment_enum(val));
1185        if !enums_valid {
1186            return Err(WebGLError::InvalidEnum);
1187        }
1188
1189        let values_valid = buffers.iter().enumerate().all(|(i, &val)| {
1190            val == constants::NONE || val == (constants::COLOR_ATTACHMENT0 + i as u32)
1191        });
1192        if !values_valid {
1193            return Err(WebGLError::InvalidOperation);
1194        }
1195
1196        self.color_draw_buffers.borrow_mut().clone_from(&buffers);
1197        context.send_command(WebGLCommand::DrawBuffers(buffers));
1198        Ok(())
1199    }
1200
1201    pub(crate) fn read_buffer(&self) -> u32 {
1202        self.color_read_buffer.get()
1203    }
1204
1205    pub(crate) fn draw_buffer_i(&self, index: usize) -> u32 {
1206        let buffers = &*self.color_draw_buffers.borrow();
1207        *buffers.get(index).unwrap_or(&constants::NONE)
1208    }
1209
1210    pub(crate) fn target(&self) -> Option<u32> {
1211        self.target.get()
1212    }
1213}
1214
1215static INTERESTING_ATTACHMENT_POINTS: &[u32] = &[
1216    constants::DEPTH_ATTACHMENT,
1217    constants::STENCIL_ATTACHMENT,
1218    constants::DEPTH_STENCIL_ATTACHMENT,
1219];