script/dom/webxr/
xrwebgllayer.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::convert::TryInto;
6
7use canvas_traits::webgl::{WebGLCommand, WebGLContextId, WebGLTextureId};
8use dom_struct::dom_struct;
9use euclid::{Rect, Size2D};
10use js::rust::HandleObject;
11use webxr_api::{ContextId as WebXRContextId, LayerId, LayerInit, Viewport};
12
13use crate::canvas_context::CanvasContext;
14use crate::conversions::Convert;
15use crate::dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as constants;
16use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextMethods;
17use crate::dom::bindings::codegen::Bindings::XRWebGLLayerBinding::{
18    XRWebGLLayerInit, XRWebGLLayerMethods, XRWebGLRenderingContext,
19};
20use crate::dom::bindings::error::{Error, Fallible};
21use crate::dom::bindings::inheritance::Castable;
22use crate::dom::bindings::num::Finite;
23use crate::dom::bindings::reflector::{DomGlobal, reflect_dom_object_with_proto};
24use crate::dom::bindings::root::{Dom, DomRoot};
25use crate::dom::globalscope::GlobalScope;
26use crate::dom::webgl::webglframebuffer::WebGLFramebuffer;
27use crate::dom::webgl::webglrenderingcontext::WebGLRenderingContext;
28use crate::dom::webgl::webgltexture::WebGLTexture;
29use crate::dom::window::Window;
30use crate::dom::xrframe::XRFrame;
31use crate::dom::xrlayer::XRLayer;
32use crate::dom::xrsession::XRSession;
33use crate::dom::xrview::XRView;
34use crate::dom::xrviewport::XRViewport;
35use crate::script_runtime::CanGc;
36
37impl Convert<LayerInit> for XRWebGLLayerInit {
38    fn convert(self) -> LayerInit {
39        LayerInit::WebGLLayer {
40            alpha: self.alpha,
41            antialias: self.antialias,
42            depth: self.depth,
43            stencil: self.stencil,
44            framebuffer_scale_factor: *self.framebufferScaleFactor as f32,
45            ignore_depth_values: self.ignoreDepthValues,
46        }
47    }
48}
49
50#[dom_struct]
51pub(crate) struct XRWebGLLayer {
52    xr_layer: XRLayer,
53    antialias: bool,
54    depth: bool,
55    stencil: bool,
56    alpha: bool,
57    ignore_depth_values: bool,
58    /// If none, this is an inline session (the composition disabled flag is true)
59    framebuffer: Option<Dom<WebGLFramebuffer>>,
60}
61
62impl XRWebGLLayer {
63    pub(crate) fn new_inherited(
64        session: &XRSession,
65        context: &WebGLRenderingContext,
66        init: &XRWebGLLayerInit,
67        framebuffer: Option<&WebGLFramebuffer>,
68        layer_id: Option<LayerId>,
69    ) -> XRWebGLLayer {
70        XRWebGLLayer {
71            xr_layer: XRLayer::new_inherited(session, context, layer_id),
72            antialias: init.antialias,
73            depth: init.depth,
74            stencil: init.stencil,
75            alpha: init.alpha,
76            ignore_depth_values: init.ignoreDepthValues,
77            framebuffer: framebuffer.map(Dom::from_ref),
78        }
79    }
80
81    #[allow(clippy::too_many_arguments)]
82    fn new(
83        global: &GlobalScope,
84        proto: Option<HandleObject>,
85        session: &XRSession,
86        context: &WebGLRenderingContext,
87        init: &XRWebGLLayerInit,
88        framebuffer: Option<&WebGLFramebuffer>,
89        layer_id: Option<LayerId>,
90        can_gc: CanGc,
91    ) -> DomRoot<XRWebGLLayer> {
92        reflect_dom_object_with_proto(
93            Box::new(XRWebGLLayer::new_inherited(
94                session,
95                context,
96                init,
97                framebuffer,
98                layer_id,
99            )),
100            global,
101            proto,
102            can_gc,
103        )
104    }
105
106    pub(crate) fn layer_id(&self) -> Option<LayerId> {
107        self.xr_layer.layer_id()
108    }
109
110    pub(crate) fn context_id(&self) -> WebGLContextId {
111        self.xr_layer.context_id()
112    }
113
114    pub(crate) fn session(&self) -> &XRSession {
115        self.xr_layer.session()
116    }
117
118    pub(crate) fn size(&self) -> Size2D<u32, Viewport> {
119        if let Some(framebuffer) = self.framebuffer.as_ref() {
120            let size = framebuffer.size().unwrap_or((0, 0));
121            Size2D::new(
122                size.0.try_into().unwrap_or(0),
123                size.1.try_into().unwrap_or(0),
124            )
125        } else {
126            Size2D::from_untyped(self.context().size())
127        }
128    }
129
130    fn texture_target(&self) -> u32 {
131        if cfg!(target_os = "macos") {
132            glow::TEXTURE_RECTANGLE
133        } else {
134            glow::TEXTURE_2D
135        }
136    }
137
138    pub(crate) fn begin_frame(&self, frame: &XRFrame) -> Option<()> {
139        debug!("XRWebGLLayer begin frame");
140        let framebuffer = self.framebuffer.as_ref()?;
141        let sub_images = frame.get_sub_images(self.layer_id()?)?;
142        let session = self.session();
143        let context = framebuffer.upcast().context()?;
144
145        // TODO: Cache this texture
146        let color_texture_id = WebGLTextureId::new(sub_images.sub_image.as_ref()?.color_texture?);
147        let color_texture =
148            WebGLTexture::new_webxr(&context, color_texture_id, session, CanGc::note());
149        let target = self.texture_target();
150
151        // Save the current bindings
152        let saved_framebuffer = context.get_draw_framebuffer_slot().get();
153        let saved_framebuffer_target = framebuffer.target();
154        let saved_texture_id = context
155            .textures()
156            .active_texture_slot(target, context.webgl_version())
157            .ok()
158            .and_then(|slot| slot.get().map(|texture| texture.id()));
159
160        // We have to pick a framebuffer target.
161        // If there is a draw framebuffer, we use its target,
162        // otherwise we just use DRAW_FRAMEBUFFER.
163        let framebuffer_target = saved_framebuffer
164            .as_ref()
165            .and_then(|fb| fb.target())
166            .unwrap_or(constants::DRAW_FRAMEBUFFER);
167
168        // Update the attachments
169        context.send_command(WebGLCommand::BindTexture(target, Some(color_texture_id)));
170        framebuffer.bind(framebuffer_target);
171        framebuffer
172            .texture2d_even_if_opaque(
173                constants::COLOR_ATTACHMENT0,
174                self.texture_target(),
175                Some(&color_texture),
176                0,
177            )
178            .ok()?;
179        if let Some(id) = sub_images.sub_image.as_ref()?.depth_stencil_texture {
180            // TODO: Cache this texture
181            let depth_stencil_texture_id = WebGLTextureId::new(id);
182            let depth_stencil_texture =
183                WebGLTexture::new_webxr(&context, depth_stencil_texture_id, session, CanGc::note());
184            framebuffer
185                .texture2d_even_if_opaque(
186                    constants::DEPTH_STENCIL_ATTACHMENT,
187                    constants::TEXTURE_2D,
188                    Some(&depth_stencil_texture),
189                    0,
190                )
191                .ok()?;
192        }
193
194        // Restore the old bindings
195        context.send_command(WebGLCommand::BindTexture(target, saved_texture_id));
196        if let Some(framebuffer_target) = saved_framebuffer_target {
197            framebuffer.bind(framebuffer_target);
198        }
199        if let Some(framebuffer) = saved_framebuffer {
200            framebuffer.bind(framebuffer_target);
201        }
202        Some(())
203    }
204
205    pub(crate) fn end_frame(&self, _frame: &XRFrame) -> Option<()> {
206        debug!("XRWebGLLayer end frame");
207        // TODO: invalidate the old texture
208        let framebuffer = self.framebuffer.as_ref()?;
209        // TODO: rebind the current bindings
210        framebuffer.bind(constants::FRAMEBUFFER);
211        framebuffer
212            .texture2d_even_if_opaque(constants::COLOR_ATTACHMENT0, self.texture_target(), None, 0)
213            .ok()?;
214        framebuffer
215            .texture2d_even_if_opaque(
216                constants::DEPTH_STENCIL_ATTACHMENT,
217                constants::DEPTH_STENCIL_ATTACHMENT,
218                None,
219                0,
220            )
221            .ok()?;
222
223        if let Some(context) = framebuffer.upcast().context() {
224            context.Flush();
225        }
226
227        Some(())
228    }
229
230    pub(crate) fn context(&self) -> &WebGLRenderingContext {
231        self.xr_layer.context()
232    }
233}
234
235impl XRWebGLLayerMethods<crate::DomTypeHolder> for XRWebGLLayer {
236    /// <https://immersive-web.github.io/webxr/#dom-xrwebgllayer-xrwebgllayer>
237    fn Constructor(
238        global: &Window,
239        proto: Option<HandleObject>,
240        can_gc: CanGc,
241        session: &XRSession,
242        context: XRWebGLRenderingContext,
243        init: &XRWebGLLayerInit,
244    ) -> Fallible<DomRoot<Self>> {
245        let context = match context {
246            XRWebGLRenderingContext::WebGLRenderingContext(ctx) => ctx,
247            XRWebGLRenderingContext::WebGL2RenderingContext(ctx) => ctx.base_context(),
248        };
249
250        // Step 2
251        if session.is_ended() {
252            return Err(Error::InvalidState(None));
253        }
254        // XXXManishearth step 3: throw error if context is lost
255        // XXXManishearth step 4: check XR compat flag for immersive sessions
256
257        let (framebuffer, layer_id) = if session.is_immersive() {
258            // Step 9.2. "Initialize layer’s framebuffer to a new opaque framebuffer created with context."
259            let size = session
260                .with_session(|session| session.recommended_framebuffer_resolution())
261                .ok_or(Error::Operation(None))?;
262            let framebuffer = WebGLFramebuffer::maybe_new_webxr(session, &context, size, can_gc)
263                .ok_or(Error::Operation(None))?;
264
265            // Step 9.3. "Allocate and initialize resources compatible with session’s XR device,
266            // including GPU accessible memory buffers, as required to support the compositing of layer."
267            let context_id = WebXRContextId::from(context.context_id());
268            let layer_init: LayerInit = init.convert();
269            let layer_id = session
270                .with_session(|session| session.create_layer(context_id, layer_init))
271                .map_err(|_| Error::Operation(None))?;
272
273            // Step 9.4: "If layer’s resources were unable to be created for any reason,
274            // throw an OperationError and abort these steps."
275            (Some(framebuffer), Some(layer_id))
276        } else {
277            (None, None)
278        };
279
280        // Ensure that we finish setting up this layer before continuing.
281        context.Finish();
282
283        // Step 10. "Return layer."
284        Ok(XRWebGLLayer::new(
285            &global.global(),
286            proto,
287            session,
288            &context,
289            init,
290            framebuffer.as_deref(),
291            layer_id,
292            can_gc,
293        ))
294    }
295
296    /// <https://www.w3.org/TR/webxr/#dom-xrwebgllayer-getnativeframebufferscalefactor>
297    fn GetNativeFramebufferScaleFactor(_window: &Window, session: &XRSession) -> Finite<f64> {
298        let value: f64 = if session.is_ended() { 0.0 } else { 1.0 };
299        Finite::wrap(value)
300    }
301
302    /// <https://immersive-web.github.io/webxr/#dom-xrwebgllayer-antialias>
303    fn Antialias(&self) -> bool {
304        self.antialias
305    }
306
307    /// <https://immersive-web.github.io/webxr/#dom-xrwebgllayer-ignoredepthvalues>
308    fn IgnoreDepthValues(&self) -> bool {
309        self.ignore_depth_values
310    }
311
312    /// <https://www.w3.org/TR/webxr/#dom-xrwebgllayer-fixedfoveation>
313    fn GetFixedFoveation(&self) -> Option<Finite<f32>> {
314        // Fixed foveation is only available on Quest/Pico headset runtimes
315        None
316    }
317
318    /// <https://www.w3.org/TR/webxr/#dom-xrwebgllayer-fixedfoveation>
319    fn SetFixedFoveation(&self, _value: Option<Finite<f32>>) {
320        // no-op until fixed foveation is supported
321    }
322
323    /// <https://immersive-web.github.io/webxr/#dom-xrwebgllayer-framebuffer>
324    fn GetFramebuffer(&self) -> Option<DomRoot<WebGLFramebuffer>> {
325        self.framebuffer.as_ref().map(|x| DomRoot::from_ref(&**x))
326    }
327
328    /// <https://immersive-web.github.io/webxr/#dom-xrwebgllayer-framebufferwidth>
329    fn FramebufferWidth(&self) -> u32 {
330        self.size().width
331    }
332
333    /// <https://immersive-web.github.io/webxr/#dom-xrwebgllayer-framebufferheight>
334    fn FramebufferHeight(&self) -> u32 {
335        self.size().height
336    }
337
338    /// <https://immersive-web.github.io/webxr/#dom-xrwebgllayer-getviewport>
339    fn GetViewport(&self, view: &XRView) -> Option<DomRoot<XRViewport>> {
340        if self.session() != view.session() {
341            return None;
342        }
343
344        let index = view.viewport_index();
345
346        let viewport = self.session().with_session(|s| {
347            // Inline sessions
348            if s.viewports().is_empty() {
349                Rect::from_size(self.size().to_i32())
350            } else {
351                s.viewports()[index]
352            }
353        });
354
355        // NOTE: According to spec, viewport sizes should be recalculated here if the
356        // requested viewport scale has changed. However, existing browser implementations
357        // don't seem to do this for stereoscopic immersive sessions.
358        // Revisit if Servo gets support for handheld AR/VR via ARCore/ARKit
359
360        Some(XRViewport::new(&self.global(), viewport, CanGc::note()))
361    }
362}