Skip to main content

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 dom_struct::dom_struct;
8use euclid::{Rect, Size2D};
9use js::context::JSContext;
10use js::rust::HandleObject;
11use script_bindings::reflector::reflect_dom_object_with_proto_and_cx;
12use servo_canvas_traits::webgl::{WebGLCommand, WebGLContextId, WebGLTextureId};
13use webxr_api::{ContextId as WebXRContextId, LayerId, LayerInit, Viewport};
14
15use crate::canvas_context::CanvasContext;
16use crate::conversions::Convert;
17use crate::dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as constants;
18use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextMethods;
19use crate::dom::bindings::codegen::Bindings::XRWebGLLayerBinding::{
20    XRWebGLLayerInit, XRWebGLLayerMethods, XRWebGLRenderingContext,
21};
22use crate::dom::bindings::error::{Error, Fallible};
23use crate::dom::bindings::inheritance::Castable;
24use crate::dom::bindings::num::Finite;
25use crate::dom::bindings::reflector::DomGlobal;
26use crate::dom::bindings::root::{Dom, DomRoot};
27use crate::dom::globalscope::GlobalScope;
28use crate::dom::webgl::webglframebuffer::WebGLFramebuffer;
29use crate::dom::webgl::webglrenderingcontext::WebGLRenderingContext;
30use crate::dom::webgl::webgltexture::WebGLTexture;
31use crate::dom::window::Window;
32use crate::dom::xrframe::XRFrame;
33use crate::dom::xrlayer::XRLayer;
34use crate::dom::xrsession::XRSession;
35use crate::dom::xrview::XRView;
36use crate::dom::xrviewport::XRViewport;
37
38impl Convert<LayerInit> for XRWebGLLayerInit {
39    fn convert(self) -> LayerInit {
40        LayerInit::WebGLLayer {
41            alpha: self.alpha,
42            antialias: self.antialias,
43            depth: self.depth,
44            stencil: self.stencil,
45            framebuffer_scale_factor: *self.framebufferScaleFactor as f32,
46            ignore_depth_values: self.ignoreDepthValues,
47        }
48    }
49}
50
51#[dom_struct]
52pub(crate) struct XRWebGLLayer {
53    xr_layer: XRLayer,
54    antialias: bool,
55    depth: bool,
56    stencil: bool,
57    alpha: bool,
58    ignore_depth_values: bool,
59    /// If none, this is an inline session (the composition disabled flag is true)
60    framebuffer: Option<Dom<WebGLFramebuffer>>,
61}
62
63impl XRWebGLLayer {
64    pub(crate) fn new_inherited(
65        session: &XRSession,
66        context: &WebGLRenderingContext,
67        init: &XRWebGLLayerInit,
68        framebuffer: Option<&WebGLFramebuffer>,
69        layer_id: Option<LayerId>,
70    ) -> XRWebGLLayer {
71        XRWebGLLayer {
72            xr_layer: XRLayer::new_inherited(session, context, layer_id),
73            antialias: init.antialias,
74            depth: init.depth,
75            stencil: init.stencil,
76            alpha: init.alpha,
77            ignore_depth_values: init.ignoreDepthValues,
78            framebuffer: framebuffer.map(Dom::from_ref),
79        }
80    }
81
82    #[expect(clippy::too_many_arguments)]
83    fn new(
84        cx: &mut JSContext,
85        global: &GlobalScope,
86        proto: Option<HandleObject>,
87        session: &XRSession,
88        context: &WebGLRenderingContext,
89        init: &XRWebGLLayerInit,
90        framebuffer: Option<&WebGLFramebuffer>,
91        layer_id: Option<LayerId>,
92    ) -> DomRoot<XRWebGLLayer> {
93        reflect_dom_object_with_proto_and_cx(
94            Box::new(XRWebGLLayer::new_inherited(
95                session,
96                context,
97                init,
98                framebuffer,
99                layer_id,
100            )),
101            global,
102            proto,
103            cx,
104        )
105    }
106
107    pub(crate) fn layer_id(&self) -> Option<LayerId> {
108        self.xr_layer.layer_id()
109    }
110
111    pub(crate) fn context_id(&self) -> WebGLContextId {
112        self.xr_layer.context_id()
113    }
114
115    pub(crate) fn session(&self) -> &XRSession {
116        self.xr_layer.session()
117    }
118
119    pub(crate) fn size(&self) -> Size2D<u32, Viewport> {
120        if let Some(framebuffer) = self.framebuffer.as_ref() {
121            let size = framebuffer.size().unwrap_or((0, 0));
122            Size2D::new(
123                size.0.try_into().unwrap_or(0),
124                size.1.try_into().unwrap_or(0),
125            )
126        } else {
127            Size2D::from_untyped(self.context().size())
128        }
129    }
130
131    fn texture_target(&self) -> u32 {
132        if cfg!(target_os = "macos") {
133            glow::TEXTURE_RECTANGLE
134        } else {
135            glow::TEXTURE_2D
136        }
137    }
138
139    pub(crate) fn begin_frame(&self, cx: &mut JSContext, frame: &XRFrame) -> Option<()> {
140        debug!("XRWebGLLayer begin frame");
141        let framebuffer = self.framebuffer.as_ref()?;
142        let sub_images = frame.get_sub_images(self.layer_id()?)?;
143        let session = self.session();
144        let context = framebuffer.upcast().context()?;
145
146        // TODO: Cache this texture
147        let color_texture_id = WebGLTextureId::new(sub_images.sub_image.as_ref()?.color_texture?);
148        let color_texture = WebGLTexture::new_webxr(cx, &context, color_texture_id, session);
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(cx, &context, depth_stencil_texture_id, session);
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        cx: &mut JSContext,
239        global: &Window,
240        proto: Option<HandleObject>,
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(cx, session, &context, size)
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            cx,
286            &global.global(),
287            proto,
288            session,
289            &context,
290            init,
291            framebuffer.as_deref(),
292            layer_id,
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, cx: &mut JSContext, 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(cx, &self.global(), viewport))
361    }
362}