Skip to main content

script_webgpu/
gpu.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::marker::PhantomData;
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use js::realm::CurrentRealm;
10use jstraceable_derive::JSTraceable;
11use malloc_size_of_derive::MallocSizeOf;
12use script_bindings::DomTypes;
13use script_bindings::codegen::GenericBindings::WebGPUBinding::{
14    GPUMethods, GPUPowerPreference, GPURequestAdapterOptions, GPUTextureFormat, GPUWrap,
15};
16use script_bindings::dom::MutNullableDom;
17use script_bindings::interfaces::{GlobalScopeHelpers, PromiseHelpers};
18use script_bindings::reflector::{DomGlobalGeneric, Reflector, reflect_dom_object_with_wrap};
19use script_bindings::root::DomRoot;
20use servo_constellation_traits::ScriptToConstellationMessage;
21use webgpu_traits::{PowerPreference, RequestAdapterOptions};
22
23use super::wgsllanguagefeatures::WGSLLanguageFeatures;
24use crate::dom::bindings::error::Error;
25use crate::gpuadapter::GPUAdapter;
26use crate::traits::{Equivalence, WebGPUGlobalTrait, WebGPUPromise, WebGPUPromiseCallbackTrait};
27
28#[dom_struct]
29pub struct GPU<D: DomTypes> {
30    reflector_: Reflector,
31    /// Same object for <https://www.w3.org/TR/webgpu/#dom-gpu-wgsllanguagefeatures>
32    wgsl_language_features: MutNullableDom<WGSLLanguageFeatures<D>>,
33    #[no_trace = "PhantomData does not exist"]
34    phantom: PhantomData<D>,
35}
36
37impl<D: Equivalence> GPU<D> {
38    pub(crate) fn new_inherited() -> GPU<D> {
39        GPU {
40            reflector_: Reflector::new(),
41            wgsl_language_features: MutNullableDom::default(),
42            phantom: PhantomData,
43        }
44    }
45
46    pub fn new(cx: &mut JSContext, global: &D::GlobalScope) -> DomRoot<GPU<D>> {
47        reflect_dom_object_with_wrap::<D, _, _>(
48            Box::new(GPU::new_inherited()),
49            global,
50            cx,
51            GPUWrap::<D>,
52        )
53    }
54}
55
56impl<D> GPUMethods<D> for GPU<D>
57where
58    D: Equivalence,
59    <D::Promise as PromiseHelpers<D>>::StackRoot: WebGPUPromise<D>,
60    Self: DomGlobalGeneric<D>,
61{
62    /// <https://gpuweb.github.io/gpuweb/#dom-gpu-requestadapter>
63    fn RequestAdapter(
64        &self,
65        cx: &mut CurrentRealm,
66        options: &GPURequestAdapterOptions,
67    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
68        let global = self.global_from_reflector();
69        // 1. Let promise be a new promise.
70        let promise = D::Promise::new_in_realm_rooted(cx);
71        let callback = promise.callback_promise_dom_manipulation_task_source(self);
72
73        let power_preference = match options.powerPreference {
74            Some(GPUPowerPreference::Low_power) => PowerPreference::LowPower,
75            Some(GPUPowerPreference::High_performance) => PowerPreference::HighPerformance,
76            None => PowerPreference::default(),
77        };
78        let ids = global.global_wgpu_id_hub().create_adapter_id();
79
80        // 3. Issue the initialization steps on the Device timeline of this
81
82        /*
83        We do some steps here to avoid IPC round-trips
84        1. options.featureLevel must be a feature level string.
85        If any are unmet
86            Let adapter be null, issue the resolution steps on contentTimeline, and return.
87        If adapter is null:
88            Resolve promise with null.
89        */
90        match &*options.featureLevel.str() {
91            "core" => {},
92            "compatibility" => {
93                // Set options.featureLevel to "compatibility" if the user agent chooses to support it, or "core" if not.
94                // and wgpu does not support "compatibility" yet so we return core for now
95            },
96            _ => {
97                promise.resolve_native(cx, &None::<GPUAdapter<D>>);
98                return promise;
99            },
100        }
101        let script_to_constellation_chan = global.script_to_constellation_chan();
102        if script_to_constellation_chan
103            .send(ScriptToConstellationMessage::RequestAdapter(
104                callback,
105                RequestAdapterOptions {
106                    power_preference,
107                    compatible_surface: None,
108                    force_fallback_adapter: options.forceFallbackAdapter,
109                    apply_limit_buckets: false,
110                },
111                ids,
112            ))
113            .is_err()
114        {
115            promise.reject_error(
116                cx,
117                Error::Operation(Some(
118                    "Could not send `requestAdapter` request from script thread to constellation thread".into(),
119                )),
120            );
121        }
122        // 4. Return promise
123        promise
124    }
125
126    /// <https://gpuweb.github.io/gpuweb/#dom-gpu-getpreferredcanvasformat>
127    fn GetPreferredCanvasFormat(&self) -> GPUTextureFormat {
128        // From https://github.com/mozilla-firefox/firefox/blob/24d49101ce17b78c3ba1217d00297fe2891be6b3/dom/webgpu/Instance.h#L68
129        if cfg!(target_os = "android") {
130            GPUTextureFormat::Rgba8unorm
131        } else {
132            GPUTextureFormat::Bgra8unorm
133        }
134    }
135
136    /// <https://www.w3.org/TR/webgpu/#dom-gpu-wgsllanguagefeatures>
137    fn WgslLanguageFeatures(
138        &self,
139        cx: &mut js::context::JSContext,
140    ) -> DomRoot<WGSLLanguageFeatures<D>> {
141        self.wgsl_language_features
142            .or_init(|| WGSLLanguageFeatures::new(cx, &*self.global_from_reflector(), None))
143    }
144}