diff options
author | Martin Robinson <mrobinson@igalia.com> | 2025-04-04 10:06:07 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2025-04-04 08:06:07 +0000 |
commit | 0d693114ad4f27a07a3cd18c4c34da53be55d1bc (patch) | |
tree | 35d4382e088703434cb6b109b3a4bd9476c8ccf6 /components | |
parent | df9efde1c377f0ff701fdd72814b628e73397464 (diff) | |
download | servo-0d693114ad4f27a07a3cd18c4c34da53be55d1bc.tar.gz servo-0d693114ad4f27a07a3cd18c4c34da53be55d1bc.zip |
webgpu: Add a `webgpu_traits` crate (#36320)
This breaks the `script_traits` dependency on `webgpu`. In general, the
`traits` crates shouldn't depend on Servo non-`traits` crates. This is
necessary to move "script to constellation" messages to the
`constellation_traits` crate, making it the entire API for talking to
the
constellation. This will break a circular dependency when that happens.
Testing: Successfully building is enough of a test for this one as
it is mainly moving types around.
Signed-off-by: Martin Robinson <mrobinson@igalia.com>
Signed-off-by: Martin Robinson <mrobinson@igalia.com>
Diffstat (limited to 'components')
50 files changed, 618 insertions, 565 deletions
diff --git a/components/constellation/Cargo.toml b/components/constellation/Cargo.toml index 3c7ff9990c3..1b3402eaf56 100644 --- a/components/constellation/Cargo.toml +++ b/components/constellation/Cargo.toml @@ -49,6 +49,7 @@ servo_url = { path = "../url" } stylo_traits = { workspace = true } tracing = { workspace = true, optional = true } webgpu = { path = "../webgpu" } +webgpu_traits = { workspace = true } webrender = { workspace = true } webrender_api = { workspace = true } webrender_traits = { workspace = true } diff --git a/components/constellation/constellation.rs b/components/constellation/constellation.rs index 20ff87f8a82..8ef33132966 100644 --- a/components/constellation/constellation.rs +++ b/components/constellation/constellation.rs @@ -158,7 +158,7 @@ use style_traits::CSSPixel; #[cfg(feature = "webgpu")] use webgpu::swapchain::WGPUImageMap; #[cfg(feature = "webgpu")] -use webgpu::{self, WebGPU, WebGPURequest}; +use webgpu_traits::{WebGPU, WebGPURequest}; #[cfg(feature = "webgpu")] use webrender::RenderApi; use webrender::RenderApiSender; @@ -1894,6 +1894,8 @@ where browsing_context_id: BrowsingContextId, request: FromScriptMsg, ) { + use webgpu::start_webgpu_thread; + let browsing_context_group_id = match self.browsing_contexts.get(&browsing_context_id) { Some(bc) => &bc.bc_group_id, None => return warn!("Browsing context not found"), @@ -1915,7 +1917,7 @@ where return warn!("Browsing context group not found"); }; let webgpu_chan = match browsing_context_group.webgpus.entry(host) { - Entry::Vacant(v) => WebGPU::new( + Entry::Vacant(v) => start_webgpu_thread( self.webrender_wgpu.webrender_api.create_sender(), self.webrender_document, self.webrender_wgpu.webrender_external_images.clone(), diff --git a/components/script/Cargo.toml b/components/script/Cargo.toml index 7158c15d117..ede6b9fb941 100644 --- a/components/script/Cargo.toml +++ b/components/script/Cargo.toml @@ -133,6 +133,7 @@ utf-8 = "0.7" uuid = { workspace = true, features = ["serde"] } webdriver = { workspace = true } webgpu = { path = "../webgpu" } +webgpu_traits = { workspace = true } webrender_api = { workspace = true } webrender_traits = { workspace = true } webxr-api = { workspace = true, features = ["ipc"], optional = true } diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 6528a8e641d..167b397a4c6 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -72,7 +72,7 @@ use stylo_atoms::Atom; use url::Host; use uuid::Uuid; #[cfg(feature = "webgpu")] -use webgpu::swapchain::WebGPUContextId; +use webgpu_traits::WebGPUContextId; use webrender_api::units::DeviceIntRect; use crate::animation_timeline::AnimationTimeline; diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 6cce4b0f0e7..6d5712291ac 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -64,7 +64,7 @@ use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl}; use timers::{TimerEventId, TimerEventRequest, TimerSource}; use uuid::Uuid; #[cfg(feature = "webgpu")] -use webgpu::{DeviceLostReason, WebGPUDevice}; +use webgpu_traits::{DeviceLostReason, WebGPUDevice}; use super::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions; #[cfg(feature = "webgpu")] @@ -3006,7 +3006,7 @@ impl GlobalScope { pub(crate) fn handle_uncaptured_gpu_error( &self, device: WebGPUDevice, - error: webgpu::Error, + error: webgpu_traits::Error, can_gc: CanGc, ) { if let Some(gpu_device) = self diff --git a/components/script/dom/webgpu/gpu.rs b/components/script/dom/webgpu/gpu.rs index ce5f3d1f5fd..fd0c30c13bb 100644 --- a/components/script/dom/webgpu/gpu.rs +++ b/components/script/dom/webgpu/gpu.rs @@ -7,8 +7,9 @@ use std::rc::Rc; use dom_struct::dom_struct; use js::jsapi::Heap; use script_traits::ScriptMsg; +use webgpu::wgc; use webgpu::wgt::PowerPreference; -use webgpu::{WebGPUAdapterResponse, wgc}; +use webgpu_traits::WebGPUAdapterResponse; use super::wgsllanguagefeatures::WGSLLanguageFeatures; use crate::dom::bindings::codegen::Bindings::WebGPUBinding::{ diff --git a/components/script/dom/webgpu/gpuadapter.rs b/components/script/dom/webgpu/gpuadapter.rs index 04a7b9e42ad..b30fad1e1b5 100644 --- a/components/script/dom/webgpu/gpuadapter.rs +++ b/components/script/dom/webgpu/gpuadapter.rs @@ -7,8 +7,8 @@ use std::rc::Rc; use dom_struct::dom_struct; use js::jsapi::{Heap, JSObject}; use webgpu::wgc::instance::RequestDeviceError; -use webgpu::wgt::MemoryHints; -use webgpu::{WebGPU, WebGPUAdapter, WebGPUDeviceResponse, WebGPURequest, wgt}; +use webgpu::wgt::{self, MemoryHints}; +use webgpu_traits::{WebGPU, WebGPUAdapter, WebGPUDeviceResponse, WebGPURequest}; use super::gpusupportedfeatures::GPUSupportedFeatures; use super::gpusupportedlimits::set_limit; diff --git a/components/script/dom/webgpu/gpubindgroup.rs b/components/script/dom/webgpu/gpubindgroup.rs index 0cc36c4cfcb..98d7f3eca91 100644 --- a/components/script/dom/webgpu/gpubindgroup.rs +++ b/components/script/dom/webgpu/gpubindgroup.rs @@ -6,7 +6,7 @@ use std::borrow::Cow; use dom_struct::dom_struct; use webgpu::wgc::binding_model::BindGroupDescriptor; -use webgpu::{WebGPU, WebGPUBindGroup, WebGPUDevice, WebGPURequest}; +use webgpu_traits::{WebGPU, WebGPUBindGroup, WebGPUDevice, WebGPURequest}; use crate::conversions::Convert; use crate::dom::bindings::cell::DomRefCell; diff --git a/components/script/dom/webgpu/gpubindgrouplayout.rs b/components/script/dom/webgpu/gpubindgrouplayout.rs index 2f8ff161b50..ae48f3497fc 100644 --- a/components/script/dom/webgpu/gpubindgrouplayout.rs +++ b/components/script/dom/webgpu/gpubindgrouplayout.rs @@ -6,7 +6,7 @@ use std::borrow::Cow; use dom_struct::dom_struct; use webgpu::wgc::binding_model::BindGroupLayoutDescriptor; -use webgpu::{WebGPU, WebGPUBindGroupLayout, WebGPURequest}; +use webgpu_traits::{WebGPU, WebGPUBindGroupLayout, WebGPURequest}; use crate::conversions::Convert; use crate::dom::bindings::cell::DomRefCell; diff --git a/components/script/dom/webgpu/gpubuffer.rs b/components/script/dom/webgpu/gpubuffer.rs index b6c5d6c4977..6aafdf5e863 100644 --- a/components/script/dom/webgpu/gpubuffer.rs +++ b/components/script/dom/webgpu/gpubuffer.rs @@ -10,7 +10,8 @@ use dom_struct::dom_struct; use ipc_channel::ipc::IpcSharedMemory; use js::typedarray::ArrayBuffer; use webgpu::wgc::device::HostMap; -use webgpu::{Mapping, WebGPU, WebGPUBuffer, WebGPURequest, wgc, wgt}; +use webgpu::{wgc, wgt}; +use webgpu_traits::{Mapping, WebGPU, WebGPUBuffer, WebGPURequest}; use wgc::resource::BufferAccessError; use crate::conversions::Convert; @@ -263,7 +264,7 @@ impl GPUBufferMethods<crate::DomTypeHolder> for GPUBuffer { GPUMapModeConstants::WRITE => HostMap::Write, _ => { self.device - .dispatch_error(webgpu::Error::Validation(String::from( + .dispatch_error(webgpu_traits::Error::Validation(String::from( "Invalid MapModeFlags", ))); self.map_failure(&promise, can_gc); diff --git a/components/script/dom/webgpu/gpucanvascontext.rs b/components/script/dom/webgpu/gpucanvascontext.rs index 00bdcbec64c..60bce21022d 100644 --- a/components/script/dom/webgpu/gpucanvascontext.rs +++ b/components/script/dom/webgpu/gpucanvascontext.rs @@ -9,10 +9,10 @@ use arrayvec::ArrayVec; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcSharedMemory}; use script_layout_interface::HTMLCanvasDataSource; -use webgpu::swapchain::WebGPUContextId; use webgpu::wgc::id; -use webgpu::{ - ContextConfiguration, PRESENTATION_BUFFER_COUNT, WebGPU, WebGPURequest, WebGPUTexture, +use webgpu_traits::{ + ContextConfiguration, PRESENTATION_BUFFER_COUNT, WebGPU, WebGPUContextId, WebGPURequest, + WebGPUTexture, }; use webrender_api::ImageKey; use webrender_api::units::DeviceIntSize; diff --git a/components/script/dom/webgpu/gpucommandbuffer.rs b/components/script/dom/webgpu/gpucommandbuffer.rs index e014599e34e..4c122e4b237 100644 --- a/components/script/dom/webgpu/gpucommandbuffer.rs +++ b/components/script/dom/webgpu/gpucommandbuffer.rs @@ -3,7 +3,7 @@ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use dom_struct::dom_struct; -use webgpu::{WebGPU, WebGPUCommandBuffer, WebGPURequest}; +use webgpu_traits::{WebGPU, WebGPUCommandBuffer, WebGPURequest}; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPUCommandBufferMethods; diff --git a/components/script/dom/webgpu/gpucommandencoder.rs b/components/script/dom/webgpu/gpucommandencoder.rs index 7d99c4f2bfb..0ade134124d 100644 --- a/components/script/dom/webgpu/gpucommandencoder.rs +++ b/components/script/dom/webgpu/gpucommandencoder.rs @@ -4,9 +4,10 @@ use dom_struct::dom_struct; use webgpu::wgc::command as wgpu_com; -use webgpu::{ +use webgpu::wgt; +use webgpu_traits::{ WebGPU, WebGPUCommandBuffer, WebGPUCommandEncoder, WebGPUComputePass, WebGPUDevice, - WebGPURenderPass, WebGPURequest, wgt, + WebGPURenderPass, WebGPURequest, }; use crate::conversions::{Convert, TryConvert}; diff --git a/components/script/dom/webgpu/gpucompilationinfo.rs b/components/script/dom/webgpu/gpucompilationinfo.rs index ae092479f2b..0969e06970f 100644 --- a/components/script/dom/webgpu/gpucompilationinfo.rs +++ b/components/script/dom/webgpu/gpucompilationinfo.rs @@ -4,7 +4,7 @@ use dom_struct::dom_struct; use js::rust::MutableHandleValue; -use webgpu::ShaderCompilationInfo; +use webgpu_traits::ShaderCompilationInfo; use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPUCompilationInfoMethods; use crate::dom::bindings::reflector::{Reflector, reflect_dom_object_with_proto}; diff --git a/components/script/dom/webgpu/gpucompilationmessage.rs b/components/script/dom/webgpu/gpucompilationmessage.rs index 74094030f2b..7ffbebd5cb0 100644 --- a/components/script/dom/webgpu/gpucompilationmessage.rs +++ b/components/script/dom/webgpu/gpucompilationmessage.rs @@ -5,7 +5,7 @@ #![allow(dead_code)] // this file is stub as wgpu does not provide info use dom_struct::dom_struct; -use webgpu::ShaderCompilationInfo; +use webgpu_traits::ShaderCompilationInfo; use crate::dom::bindings::codegen::Bindings::WebGPUBinding::{ GPUCompilationMessageMethods, GPUCompilationMessageType, diff --git a/components/script/dom/webgpu/gpucomputepassencoder.rs b/components/script/dom/webgpu/gpucomputepassencoder.rs index fba1af44a96..3534de74d74 100644 --- a/components/script/dom/webgpu/gpucomputepassencoder.rs +++ b/components/script/dom/webgpu/gpucomputepassencoder.rs @@ -3,7 +3,7 @@ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use dom_struct::dom_struct; -use webgpu::{WebGPU, WebGPUComputePass, WebGPURequest}; +use webgpu_traits::{WebGPU, WebGPUComputePass, WebGPURequest}; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPUComputePassEncoderMethods; diff --git a/components/script/dom/webgpu/gpucomputepipeline.rs b/components/script/dom/webgpu/gpucomputepipeline.rs index fb6ac7b01e7..8015ea2756d 100644 --- a/components/script/dom/webgpu/gpucomputepipeline.rs +++ b/components/script/dom/webgpu/gpucomputepipeline.rs @@ -5,7 +5,7 @@ use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; use webgpu::wgc::pipeline::ComputePipelineDescriptor; -use webgpu::{ +use webgpu_traits::{ WebGPU, WebGPUBindGroupLayout, WebGPUComputePipeline, WebGPUComputePipelineResponse, WebGPURequest, }; diff --git a/components/script/dom/webgpu/gpuconvert.rs b/components/script/dom/webgpu/gpuconvert.rs index fbc507a45ee..f672847d29b 100644 --- a/components/script/dom/webgpu/gpuconvert.rs +++ b/components/script/dom/webgpu/gpuconvert.rs @@ -509,7 +509,7 @@ impl<'a> Convert<Option<Cow<'a, str>>> for &GPUObjectDescriptorBase { pub(crate) fn convert_bind_group_layout_entry( bgle: &GPUBindGroupLayoutEntry, device: &GPUDevice, -) -> Fallible<Result<wgt::BindGroupLayoutEntry, webgpu::Error>> { +) -> Fallible<Result<wgt::BindGroupLayoutEntry, webgpu_traits::Error>> { let number_of_provided_bindings = bgle.buffer.is_some() as u8 + bgle.sampler.is_some() as u8 + bgle.storageTexture.is_some() as u8 + @@ -569,7 +569,7 @@ pub(crate) fn convert_bind_group_layout_entry( } else { ty } - .ok_or(webgpu::Error::Validation( + .ok_or(webgpu_traits::Error::Validation( "Exactly on entry type must be provided".to_string(), )); diff --git a/components/script/dom/webgpu/gpudevice.rs b/components/script/dom/webgpu/gpudevice.rs index f0e82ff9020..2a3970ab56a 100644 --- a/components/script/dom/webgpu/gpudevice.rs +++ b/components/script/dom/webgpu/gpudevice.rs @@ -13,11 +13,11 @@ use js::jsapi::{Heap, JSObject}; use webgpu::wgc::id::{BindGroupLayoutId, PipelineLayoutId}; use webgpu::wgc::pipeline as wgpu_pipe; use webgpu::wgc::pipeline::RenderPipelineDescriptor; -use webgpu::wgt::TextureFormat; -use webgpu::{ - PopError, WebGPU, WebGPUComputePipeline, WebGPUComputePipelineResponse, - WebGPUPoppedErrorScopeResponse, WebGPURenderPipeline, WebGPURenderPipelineResponse, - WebGPURequest, wgt, +use webgpu::wgt::{self, TextureFormat}; +use webgpu_traits::{ + PopError, WebGPU, WebGPUComputePipeline, WebGPUComputePipelineResponse, WebGPUDevice, + WebGPUPoppedErrorScopeResponse, WebGPUQueue, WebGPURenderPipeline, + WebGPURenderPipelineResponse, WebGPURequest, }; use super::gpudevicelostinfo::GPUDeviceLostInfo; @@ -78,7 +78,7 @@ pub(crate) struct GPUDevice { limits: Dom<GPUSupportedLimits>, label: DomRefCell<USVString>, #[no_trace] - device: webgpu::WebGPUDevice, + device: WebGPUDevice, default_queue: Dom<GPUQueue>, /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-lost> #[ignore_malloc_size_of = "promises are hard"] @@ -117,7 +117,7 @@ impl GPUDevice { extensions: Heap<*mut JSObject>, features: &GPUSupportedFeatures, limits: &GPUSupportedLimits, - device: webgpu::WebGPUDevice, + device: WebGPUDevice, queue: &GPUQueue, label: String, lost_promise: Rc<Promise>, @@ -145,8 +145,8 @@ impl GPUDevice { extensions: Heap<*mut JSObject>, features: wgt::Features, limits: wgt::Limits, - device: webgpu::WebGPUDevice, - queue: webgpu::WebGPUQueue, + device: WebGPUDevice, + queue: WebGPUQueue, label: String, can_gc: CanGc, ) -> DomRoot<Self> { @@ -175,11 +175,11 @@ impl GPUDevice { } impl GPUDevice { - pub(crate) fn id(&self) -> webgpu::WebGPUDevice { + pub(crate) fn id(&self) -> WebGPUDevice { self.device } - pub(crate) fn queue_id(&self) -> webgpu::WebGPUQueue { + pub(crate) fn queue_id(&self) -> WebGPUQueue { self.default_queue.id() } @@ -187,7 +187,7 @@ impl GPUDevice { self.channel.clone() } - pub(crate) fn dispatch_error(&self, error: webgpu::Error) { + pub(crate) fn dispatch_error(&self, error: webgpu_traits::Error) { if let Err(e) = self.channel.0.send(WebGPURequest::DispatchError { device_id: self.device.0, error, @@ -196,7 +196,7 @@ impl GPUDevice { } } - pub(crate) fn fire_uncaptured_error(&self, error: webgpu::Error, can_gc: CanGc) { + pub(crate) fn fire_uncaptured_error(&self, error: webgpu_traits::Error, can_gc: CanGc) { let error = GPUError::from_error(&self.global(), error, can_gc); let ev = GPUUncapturedErrorEvent::new( &self.global(), @@ -620,7 +620,7 @@ impl RoutedPromiseListener<WebGPUComputePipelineResponse> for GPUDevice { ), can_gc, ), - Err(webgpu::Error::Validation(msg)) => promise.reject_native( + Err(webgpu_traits::Error::Validation(msg)) => promise.reject_native( &GPUPipelineError::new( &self.global(), msg.into(), @@ -629,8 +629,8 @@ impl RoutedPromiseListener<WebGPUComputePipelineResponse> for GPUDevice { ), can_gc, ), - Err(webgpu::Error::OutOfMemory(msg) | webgpu::Error::Internal(msg)) => promise - .reject_native( + Err(webgpu_traits::Error::OutOfMemory(msg) | webgpu_traits::Error::Internal(msg)) => { + promise.reject_native( &GPUPipelineError::new( &self.global(), msg.into(), @@ -638,7 +638,8 @@ impl RoutedPromiseListener<WebGPUComputePipelineResponse> for GPUDevice { can_gc, ), can_gc, - ), + ) + }, } } } @@ -661,7 +662,7 @@ impl RoutedPromiseListener<WebGPURenderPipelineResponse> for GPUDevice { ), can_gc, ), - Err(webgpu::Error::Validation(msg)) => promise.reject_native( + Err(webgpu_traits::Error::Validation(msg)) => promise.reject_native( &GPUPipelineError::new( &self.global(), msg.into(), @@ -670,8 +671,8 @@ impl RoutedPromiseListener<WebGPURenderPipelineResponse> for GPUDevice { ), can_gc, ), - Err(webgpu::Error::OutOfMemory(msg) | webgpu::Error::Internal(msg)) => promise - .reject_native( + Err(webgpu_traits::Error::OutOfMemory(msg) | webgpu_traits::Error::Internal(msg)) => { + promise.reject_native( &GPUPipelineError::new( &self.global(), msg.into(), @@ -679,7 +680,8 @@ impl RoutedPromiseListener<WebGPURenderPipelineResponse> for GPUDevice { can_gc, ), can_gc, - ), + ) + }, } } } diff --git a/components/script/dom/webgpu/gpuerror.rs b/components/script/dom/webgpu/gpuerror.rs index 8b9d643d8b9..4c88f73e5de 100644 --- a/components/script/dom/webgpu/gpuerror.rs +++ b/components/script/dom/webgpu/gpuerror.rs @@ -4,7 +4,7 @@ use dom_struct::dom_struct; use js::rust::HandleObject; -use webgpu::{Error, ErrorFilter}; +use webgpu_traits::{Error, ErrorFilter}; use crate::conversions::Convert; use crate::dom::bindings::codegen::Bindings::WebGPUBinding::{GPUErrorFilter, GPUErrorMethods}; diff --git a/components/script/dom/webgpu/gpupipelinelayout.rs b/components/script/dom/webgpu/gpupipelinelayout.rs index 9f8923bbb0f..aa7e767131a 100644 --- a/components/script/dom/webgpu/gpupipelinelayout.rs +++ b/components/script/dom/webgpu/gpupipelinelayout.rs @@ -6,7 +6,7 @@ use std::borrow::Cow; use dom_struct::dom_struct; use webgpu::wgc::binding_model::PipelineLayoutDescriptor; -use webgpu::{WebGPU, WebGPUBindGroupLayout, WebGPUPipelineLayout, WebGPURequest}; +use webgpu_traits::{WebGPU, WebGPUBindGroupLayout, WebGPUPipelineLayout, WebGPURequest}; use crate::conversions::Convert; use crate::dom::bindings::cell::DomRefCell; diff --git a/components/script/dom/webgpu/gpuqueue.rs b/components/script/dom/webgpu/gpuqueue.rs index 14a446604b2..941f6777d82 100644 --- a/components/script/dom/webgpu/gpuqueue.rs +++ b/components/script/dom/webgpu/gpuqueue.rs @@ -6,7 +6,8 @@ use std::rc::Rc; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSharedMemory; -use webgpu::{WebGPU, WebGPUQueue, WebGPURequest, wgt}; +use webgpu::wgt; +use webgpu_traits::{WebGPU, WebGPUQueue, WebGPURequest}; use crate::conversions::{Convert, TryConvert}; use crate::dom::bindings::cell::DomRefCell; diff --git a/components/script/dom/webgpu/gpurenderbundle.rs b/components/script/dom/webgpu/gpurenderbundle.rs index 83b7cc43d75..83febb60b8c 100644 --- a/components/script/dom/webgpu/gpurenderbundle.rs +++ b/components/script/dom/webgpu/gpurenderbundle.rs @@ -3,7 +3,7 @@ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use dom_struct::dom_struct; -use webgpu::{WebGPU, WebGPUDevice, WebGPURenderBundle, WebGPURequest}; +use webgpu_traits::{WebGPU, WebGPUDevice, WebGPURenderBundle, WebGPURequest}; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPURenderBundleMethods; diff --git a/components/script/dom/webgpu/gpurenderbundleencoder.rs b/components/script/dom/webgpu/gpurenderbundleencoder.rs index 1353f46dd5b..8d5af341cfb 100644 --- a/components/script/dom/webgpu/gpurenderbundleencoder.rs +++ b/components/script/dom/webgpu/gpurenderbundleencoder.rs @@ -8,7 +8,8 @@ use dom_struct::dom_struct; use webgpu::wgc::command::{ RenderBundleEncoder, RenderBundleEncoderDescriptor, bundle_ffi as wgpu_bundle, }; -use webgpu::{WebGPU, WebGPURenderBundle, WebGPURequest, wgt}; +use webgpu::wgt; +use webgpu_traits::{WebGPU, WebGPURenderBundle, WebGPURequest}; use crate::conversions::Convert; use crate::dom::bindings::cell::DomRefCell; diff --git a/components/script/dom/webgpu/gpurenderpassencoder.rs b/components/script/dom/webgpu/gpurenderpassencoder.rs index 5263c52138d..29b1bc618be 100644 --- a/components/script/dom/webgpu/gpurenderpassencoder.rs +++ b/components/script/dom/webgpu/gpurenderpassencoder.rs @@ -3,7 +3,8 @@ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use dom_struct::dom_struct; -use webgpu::{RenderCommand, WebGPU, WebGPURenderPass, WebGPURequest, wgt}; +use webgpu::wgt; +use webgpu_traits::{RenderCommand, WebGPU, WebGPURenderPass, WebGPURequest}; use crate::conversions::TryConvert; use crate::dom::bindings::cell::DomRefCell; diff --git a/components/script/dom/webgpu/gpurenderpipeline.rs b/components/script/dom/webgpu/gpurenderpipeline.rs index 4ac7acd2bce..4c093ed6756 100644 --- a/components/script/dom/webgpu/gpurenderpipeline.rs +++ b/components/script/dom/webgpu/gpurenderpipeline.rs @@ -5,7 +5,7 @@ use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; use webgpu::wgc::pipeline::RenderPipelineDescriptor; -use webgpu::{ +use webgpu_traits::{ WebGPU, WebGPUBindGroupLayout, WebGPURenderPipeline, WebGPURenderPipelineResponse, WebGPURequest, }; diff --git a/components/script/dom/webgpu/gpusampler.rs b/components/script/dom/webgpu/gpusampler.rs index 56e63ca6a5a..9793203d8e2 100644 --- a/components/script/dom/webgpu/gpusampler.rs +++ b/components/script/dom/webgpu/gpusampler.rs @@ -4,7 +4,7 @@ use dom_struct::dom_struct; use webgpu::wgc::resource::SamplerDescriptor; -use webgpu::{WebGPU, WebGPUDevice, WebGPURequest, WebGPUSampler}; +use webgpu_traits::{WebGPU, WebGPUDevice, WebGPURequest, WebGPUSampler}; use crate::conversions::Convert; use crate::dom::bindings::cell::DomRefCell; diff --git a/components/script/dom/webgpu/gpushadermodule.rs b/components/script/dom/webgpu/gpushadermodule.rs index a970e6dbf10..fd9e65788c8 100644 --- a/components/script/dom/webgpu/gpushadermodule.rs +++ b/components/script/dom/webgpu/gpushadermodule.rs @@ -5,7 +5,7 @@ use std::rc::Rc; use dom_struct::dom_struct; -use webgpu::{ShaderCompilationInfo, WebGPU, WebGPURequest, WebGPUShaderModule}; +use webgpu_traits::{ShaderCompilationInfo, WebGPU, WebGPURequest, WebGPUShaderModule}; use super::gpucompilationinfo::GPUCompilationInfo; use crate::dom::bindings::cell::DomRefCell; diff --git a/components/script/dom/webgpu/gputexture.rs b/components/script/dom/webgpu/gputexture.rs index e02bbedbdd5..32459a10975 100644 --- a/components/script/dom/webgpu/gputexture.rs +++ b/components/script/dom/webgpu/gputexture.rs @@ -6,7 +6,8 @@ use std::string::String; use dom_struct::dom_struct; use webgpu::wgc::resource; -use webgpu::{WebGPU, WebGPURequest, WebGPUTexture, WebGPUTextureView, wgt}; +use webgpu::wgt; +use webgpu_traits::{WebGPU, WebGPURequest, WebGPUTexture, WebGPUTextureView}; use super::gpuconvert::convert_texture_descriptor; use crate::conversions::Convert; @@ -207,7 +208,7 @@ impl GPUTextureMethods<crate::DomTypeHolder> for GPUTexture { }) } else { self.device - .dispatch_error(webgpu::Error::Validation(String::from( + .dispatch_error(webgpu_traits::Error::Validation(String::from( "arrayLayerCount and mipLevelCount cannot be 0", ))); None diff --git a/components/script/dom/webgpu/gputextureview.rs b/components/script/dom/webgpu/gputextureview.rs index f51b644cc83..20a0e18c0db 100644 --- a/components/script/dom/webgpu/gputextureview.rs +++ b/components/script/dom/webgpu/gputextureview.rs @@ -3,7 +3,7 @@ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use dom_struct::dom_struct; -use webgpu::{WebGPU, WebGPURequest, WebGPUTextureView}; +use webgpu_traits::{WebGPU, WebGPURequest, WebGPUTextureView}; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPUTextureViewMethods; diff --git a/components/script/dom/webgpu/identityhub.rs b/components/script/dom/webgpu/identityhub.rs index 102699c033e..b9ded561594 100644 --- a/components/script/dom/webgpu/identityhub.rs +++ b/components/script/dom/webgpu/identityhub.rs @@ -2,7 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ -use webgpu::identity::{ComputePass, ComputePassId, RenderPass, RenderPassId}; use webgpu::wgc::id::markers::{ Adapter, BindGroup, BindGroupLayout, Buffer, CommandEncoder, ComputePipeline, Device, PipelineLayout, Queue, RenderBundle, RenderPipeline, Sampler, ShaderModule, Texture, @@ -14,6 +13,7 @@ use webgpu::wgc::id::{ ShaderModuleId, TextureId, TextureViewId, }; use webgpu::wgc::identity::IdentityManager; +use webgpu_traits::{ComputePass, ComputePassId, RenderPass, RenderPassId}; #[derive(Debug)] pub(crate) struct IdentityHub { diff --git a/components/script/messaging.rs b/components/script/messaging.rs index ad643278ded..9012b27d424 100644 --- a/components/script/messaging.rs +++ b/components/script/messaging.rs @@ -22,7 +22,7 @@ use script_traits::{Painter, ScriptMsg, ScriptThreadMessage}; use stylo_atoms::Atom; use timers::TimerScheduler; #[cfg(feature = "webgpu")] -use webgpu::WebGPUMsg; +use webgpu_traits::WebGPUMsg; use crate::dom::abstractworker::WorkerScriptMsg; use crate::dom::bindings::trace::CustomTraceable; diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index c3356c5e72b..42241ae83ab 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -91,7 +91,7 @@ use stylo_atoms::Atom; use timers::{TimerEventRequest, TimerScheduler}; use url::Position; #[cfg(feature = "webgpu")] -use webgpu::{WebGPUDevice, WebGPUMsg}; +use webgpu_traits::{WebGPUDevice, WebGPUMsg}; use webrender_api::DocumentId; use webrender_traits::CrossProcessCompositorApi; diff --git a/components/shared/script/Cargo.toml b/components/shared/script/Cargo.toml index ef80573473c..dda1371817f 100644 --- a/components/shared/script/Cargo.toml +++ b/components/shared/script/Cargo.toml @@ -13,7 +13,7 @@ path = "lib.rs" [features] bluetooth = ["bluetooth_traits"] -webgpu = [] +webgpu = ["wgpu-core"] [dependencies] background_hang_monitor_api = { workspace = true } @@ -47,7 +47,8 @@ stylo_atoms = { workspace = true } stylo_traits = { workspace = true } uuid = { workspace = true } webdriver = { workspace = true } -webgpu = { path = "../../webgpu" } +webgpu_traits = { workspace = true } webrender_api = { workspace = true } webrender_traits = { workspace = true } webxr-api = { workspace = true, features = ["ipc"] } +wgpu-core = { workspace = true, optional = true } diff --git a/components/shared/script/lib.rs b/components/shared/script/lib.rs index 4a1cf193a34..5f9c0eec777 100644 --- a/components/shared/script/lib.rs +++ b/components/shared/script/lib.rs @@ -55,7 +55,7 @@ use strum_macros::IntoStaticStr; use style_traits::{CSSPixel, SpeculativePainter}; use stylo_atoms::Atom; #[cfg(feature = "webgpu")] -use webgpu::WebGPUMsg; +use webgpu_traits::WebGPUMsg; use webrender_api::units::DevicePixel; use webrender_api::{DocumentId, ImageKey}; use webrender_traits::CrossProcessCompositorApi; diff --git a/components/shared/script/script_msg.rs b/components/shared/script/script_msg.rs index 33ebb496dc7..8baf158312c 100644 --- a/components/shared/script/script_msg.rs +++ b/components/shared/script/script_msg.rs @@ -24,7 +24,7 @@ use servo_url::{ImmutableOrigin, ServoUrl}; use strum_macros::IntoStaticStr; use style_traits::CSSPixel; #[cfg(feature = "webgpu")] -use webgpu::{WebGPU, WebGPUAdapterResponse, wgc}; +use webgpu_traits::{WebGPU, WebGPUAdapterResponse}; use webrender_api::ImageKey; use crate::mem::MemoryReportResult; @@ -205,8 +205,8 @@ pub enum ScriptMsg { /// Create a WebGPU Adapter instance RequestAdapter( IpcSender<WebGPUAdapterResponse>, - wgc::instance::RequestAdapterOptions, - wgc::id::AdapterId, + wgpu_core::instance::RequestAdapterOptions, + wgpu_core::id::AdapterId, ), #[cfg(feature = "webgpu")] /// Get WebGPU channel diff --git a/components/shared/webgpu/Cargo.toml b/components/shared/webgpu/Cargo.toml new file mode 100644 index 00000000000..8b38af1fa6d --- /dev/null +++ b/components/shared/webgpu/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "webgpu_traits" +version.workspace = true +authors.workspace = true +license.workspace = true +edition.workspace = true +publish.workspace = true +rust-version.workspace = true + +[lib] +name = "webgpu_traits" +path = "lib.rs" + +[dependencies] +arrayvec = { workspace = true } +base = { workspace = true } +ipc-channel = { workspace = true } +malloc_size_of = { workspace = true } +serde = { workspace = true } +webrender_api = { workspace = true } +wgpu-core = { workspace = true } +wgpu-types = { workspace = true } diff --git a/components/webgpu/gpu_error.rs b/components/shared/webgpu/error.rs index 173598e1c8e..4669a605840 100644 --- a/components/webgpu/gpu_error.rs +++ b/components/shared/webgpu/error.rs @@ -7,12 +7,11 @@ use std::fmt; use serde::{Deserialize, Serialize}; - -use crate::wgc; +use wgpu_core::device::DeviceError; /// <https://www.w3.org/TR/webgpu/#gpu-error-scope> #[derive(Clone, Debug, Eq, Hash, PartialEq)] -pub(crate) struct ErrorScope { +pub struct ErrorScope { pub errors: Vec<Error>, pub filter: ErrorFilter, } @@ -76,9 +75,7 @@ impl Error { pub fn from_error<E: std::error::Error + 'static>(error: E) -> Self { let mut source_opt: Option<&(dyn std::error::Error + 'static)> = Some(&error); while let Some(source) = source_opt { - if let Some(wgc::device::DeviceError::OutOfMemory) = - source.downcast_ref::<wgc::device::DeviceError>() - { + if let Some(DeviceError::OutOfMemory) = source.downcast_ref::<DeviceError>() { return Self::OutOfMemory(error.to_string()); } source_opt = source.source(); diff --git a/components/webgpu/identity.rs b/components/shared/webgpu/ids.rs index 2203f6db35a..28f2d1c24af 100644 --- a/components/webgpu/identity.rs +++ b/components/shared/webgpu/ids.rs @@ -4,22 +4,21 @@ use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use serde::{Deserialize, Serialize}; - -pub use crate::wgc::id::markers::{ +pub use wgpu_core::id::markers::{ ComputePassEncoder as ComputePass, RenderPassEncoder as RenderPass, }; -use crate::wgc::id::{ +use wgpu_core::id::{ AdapterId, BindGroupId, BindGroupLayoutId, BufferId, CommandBufferId, CommandEncoderId, ComputePipelineId, DeviceId, PipelineLayoutId, QueueId, RenderBundleId, RenderPipelineId, SamplerId, ShaderModuleId, SurfaceId, TextureId, TextureViewId, }; -pub use crate::wgc::id::{ +pub use wgpu_core::id::{ ComputePassEncoderId as ComputePassId, RenderPassEncoderId as RenderPassId, }; macro_rules! webgpu_resource { ($name:ident, $id:ty) => { - #[derive(Clone, Copy, Debug, Deserialize, Hash, PartialEq, Serialize)] + #[derive(Clone, Copy, Debug, Deserialize, Hash, PartialEq, PartialOrd, Serialize)] pub struct $name(pub $id); impl MallocSizeOf for $name { @@ -51,3 +50,4 @@ webgpu_resource!(WebGPUTexture, TextureId); webgpu_resource!(WebGPUTextureView, TextureViewId); webgpu_resource!(WebGPUComputePass, ComputePassId); webgpu_resource!(WebGPURenderPass, RenderPassId); +webgpu_resource!(WebGPUContextId, u64); diff --git a/components/webgpu/ipc_messages/to_dom.rs b/components/shared/webgpu/lib.rs index 5dfa2e1abca..c33afc0b734 100644 --- a/components/webgpu/ipc_messages/to_dom.rs +++ b/components/shared/webgpu/lib.rs @@ -2,20 +2,85 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ -//! IPC messages that are send to WebGPU DOM objects. +pub mod error; +pub mod ids; +pub mod messages; +pub mod render_commands; use std::ops::Range; -use ipc_channel::ipc::IpcSharedMemory; +use ipc_channel::ipc::{IpcSender, IpcSharedMemory}; use serde::{Deserialize, Serialize}; -use wgc::id; -use wgc::pipeline::CreateShaderModuleError; +use webrender_api::ImageFormat; use wgpu_core::device::HostMap; +pub use wgpu_core::id::markers::{ + ComputePassEncoder as ComputePass, RenderPassEncoder as RenderPass, +}; +pub use wgpu_core::id::{ + ComputePassEncoderId as ComputePassId, RenderPassEncoderId as RenderPassId, +}; +use wgpu_core::id::{ComputePipelineId, DeviceId, QueueId, RenderPipelineId}; use wgpu_core::instance::{RequestAdapterError, RequestDeviceError}; -pub use {wgpu_core as wgc, wgpu_types as wgt}; +use wgpu_core::pipeline::CreateShaderModuleError; +use wgpu_types::{AdapterInfo, DeviceDescriptor, Features, Limits, TextureFormat}; -use crate::identity::*; -use crate::{Error, PopError, WebGPU}; +pub use crate::error::*; +pub use crate::ids::*; +pub use crate::messages::*; +pub use crate::render_commands::*; + +pub const PRESENTATION_BUFFER_COUNT: usize = 10; + +pub type WebGPUAdapterResponse = Option<Result<Adapter, RequestAdapterError>>; +pub type WebGPUComputePipelineResponse = Result<Pipeline<ComputePipelineId>, Error>; +pub type WebGPUPoppedErrorScopeResponse = Result<Option<Error>, PopError>; +pub type WebGPURenderPipelineResponse = Result<Pipeline<RenderPipelineId>, Error>; + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WebGPU(pub IpcSender<WebGPURequest>); + +impl WebGPU { + pub fn exit(&self, sender: IpcSender<()>) -> Result<(), &'static str> { + self.0 + .send(WebGPURequest::Exit(sender)) + .map_err(|_| "Failed to send Exit message") + } +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct Adapter { + pub adapter_info: AdapterInfo, + pub adapter_id: WebGPUAdapter, + pub features: Features, + pub limits: Limits, + pub channel: WebGPU, +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +pub struct ContextConfiguration { + pub device_id: DeviceId, + pub queue_id: QueueId, + pub format: TextureFormat, + pub is_opaque: bool, +} + +impl ContextConfiguration { + pub fn format(&self) -> ImageFormat { + match self.format { + TextureFormat::Rgba8Unorm => ImageFormat::RGBA8, + TextureFormat::Bgra8Unorm => ImageFormat::BGRA8, + // TODO: wgt::TextureFormat::Rgba16Float + _ => unreachable!("Unsupported canvas context format in configuration"), + } + } +} + +/// <https://gpuweb.github.io/gpuweb/#enumdef-gpudevicelostreason> +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +pub enum DeviceLostReason { + Unknown, + Destroyed, +} #[derive(Clone, Debug, Default, Deserialize, Serialize)] pub struct ShaderCompilationInfo { @@ -60,15 +125,6 @@ impl ShaderCompilationInfo { } #[derive(Debug, Deserialize, Serialize)] -pub struct Adapter { - pub adapter_info: wgt::AdapterInfo, - pub adapter_id: WebGPUAdapter, - pub features: wgt::Features, - pub limits: wgt::Limits, - pub channel: WebGPU, -} - -#[derive(Debug, Deserialize, Serialize)] pub struct Pipeline<T: std::fmt::Debug + Serialize> { pub id: T, pub label: String, @@ -84,11 +140,5 @@ pub struct Mapping { pub type WebGPUDeviceResponse = ( WebGPUDevice, WebGPUQueue, - Result<wgt::DeviceDescriptor<Option<String>>, RequestDeviceError>, + Result<DeviceDescriptor<Option<String>>, RequestDeviceError>, ); - -pub type WebGPUAdapterResponse = Option<Result<Adapter, RequestAdapterError>>; - -pub type WebGPUPoppedErrorScopeResponse = Result<Option<Error>, PopError>; -pub type WebGPURenderPipelineResponse = Result<Pipeline<id::RenderPipelineId>, Error>; -pub type WebGPUComputePipelineResponse = Result<Pipeline<id::ComputePipelineId>, Error>; diff --git a/components/webgpu/ipc_messages/mod.rs b/components/shared/webgpu/messages/mod.rs index 017749d4807..47fa26161f7 100644 --- a/components/webgpu/ipc_messages/mod.rs +++ b/components/shared/webgpu/messages/mod.rs @@ -5,3 +5,7 @@ pub mod recv; pub mod to_dom; pub mod to_script; + +pub use recv::*; +pub use to_dom::*; +pub use to_script::*; diff --git a/components/shared/webgpu/messages/recv.rs b/components/shared/webgpu/messages/recv.rs new file mode 100644 index 00000000000..47c32437e45 --- /dev/null +++ b/components/shared/webgpu/messages/recv.rs @@ -0,0 +1,338 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! IPC messages that are received in the WebGPU thread +//! (usually from the ScriptThread, and more specifically from DOM objects) + +use arrayvec::ArrayVec; +use base::id::PipelineId; +use ipc_channel::ipc::{IpcSender, IpcSharedMemory}; +use serde::{Deserialize, Serialize}; +use webrender_api::ImageKey; +use webrender_api::units::DeviceIntSize; +use wgpu_core::Label; +use wgpu_core::binding_model::{ + BindGroupDescriptor, BindGroupLayoutDescriptor, PipelineLayoutDescriptor, +}; +use wgpu_core::command::{ + RenderBundleDescriptor, RenderBundleEncoder, RenderPassColorAttachment, + RenderPassDepthStencilAttachment, TexelCopyBufferInfo, TexelCopyTextureInfo, +}; +use wgpu_core::device::HostMap; +pub use wgpu_core::id::markers::{ + ComputePassEncoder as ComputePass, RenderPassEncoder as RenderPass, +}; +use wgpu_core::id::{ + AdapterId, BindGroupId, BindGroupLayoutId, BufferId, CommandBufferId, CommandEncoderId, + ComputePassEncoderId, ComputePipelineId, DeviceId, PipelineLayoutId, QuerySetId, QueueId, + RenderBundleId, RenderPassEncoderId, RenderPipelineId, SamplerId, ShaderModuleId, TextureId, + TextureViewId, +}; +pub use wgpu_core::id::{ + ComputePassEncoderId as ComputePassId, RenderPassEncoderId as RenderPassId, +}; +use wgpu_core::instance::RequestAdapterOptions; +use wgpu_core::pipeline::{ComputePipelineDescriptor, RenderPipelineDescriptor}; +use wgpu_core::resource::{ + BufferAccessError, BufferDescriptor, SamplerDescriptor, TextureDescriptor, + TextureViewDescriptor, +}; +use wgpu_types::{ + BufferAddress, CommandBufferDescriptor, CommandEncoderDescriptor, DeviceDescriptor, Extent3d, + TexelCopyBufferLayout, +}; + +use crate::{ + ContextConfiguration, Error, ErrorFilter, Mapping, PRESENTATION_BUFFER_COUNT, RenderCommand, + ShaderCompilationInfo, WebGPUAdapter, WebGPUAdapterResponse, WebGPUComputePipelineResponse, + WebGPUContextId, WebGPUDeviceResponse, WebGPUPoppedErrorScopeResponse, + WebGPURenderPipelineResponse, +}; + +#[derive(Debug, Deserialize, Serialize)] +pub enum WebGPURequest { + BufferMapAsync { + sender: IpcSender<Result<Mapping, BufferAccessError>>, + buffer_id: BufferId, + device_id: DeviceId, + host_map: HostMap, + offset: u64, + size: Option<u64>, + }, + CommandEncoderFinish { + command_encoder_id: CommandEncoderId, + device_id: DeviceId, + desc: CommandBufferDescriptor<Label<'static>>, + }, + CopyBufferToBuffer { + command_encoder_id: CommandEncoderId, + source_id: BufferId, + source_offset: BufferAddress, + destination_id: BufferId, + destination_offset: BufferAddress, + size: BufferAddress, + }, + CopyBufferToTexture { + command_encoder_id: CommandEncoderId, + source: TexelCopyBufferInfo, + destination: TexelCopyTextureInfo, + copy_size: Extent3d, + }, + CopyTextureToBuffer { + command_encoder_id: CommandEncoderId, + source: TexelCopyTextureInfo, + destination: TexelCopyBufferInfo, + copy_size: Extent3d, + }, + CopyTextureToTexture { + command_encoder_id: CommandEncoderId, + source: TexelCopyTextureInfo, + destination: TexelCopyTextureInfo, + copy_size: Extent3d, + }, + CreateBindGroup { + device_id: DeviceId, + bind_group_id: BindGroupId, + descriptor: BindGroupDescriptor<'static>, + }, + CreateBindGroupLayout { + device_id: DeviceId, + bind_group_layout_id: BindGroupLayoutId, + descriptor: Option<BindGroupLayoutDescriptor<'static>>, + }, + CreateBuffer { + device_id: DeviceId, + buffer_id: BufferId, + descriptor: BufferDescriptor<'static>, + }, + CreateCommandEncoder { + device_id: DeviceId, + command_encoder_id: CommandEncoderId, + desc: CommandEncoderDescriptor<Label<'static>>, + }, + CreateComputePipeline { + device_id: DeviceId, + compute_pipeline_id: ComputePipelineId, + descriptor: ComputePipelineDescriptor<'static>, + implicit_ids: Option<(PipelineLayoutId, Vec<BindGroupLayoutId>)>, + /// present only on ASYNC versions + async_sender: Option<IpcSender<WebGPUComputePipelineResponse>>, + }, + CreatePipelineLayout { + device_id: DeviceId, + pipeline_layout_id: PipelineLayoutId, + descriptor: PipelineLayoutDescriptor<'static>, + }, + CreateRenderPipeline { + device_id: DeviceId, + render_pipeline_id: RenderPipelineId, + descriptor: RenderPipelineDescriptor<'static>, + implicit_ids: Option<(PipelineLayoutId, Vec<BindGroupLayoutId>)>, + /// present only on ASYNC versions + async_sender: Option<IpcSender<WebGPURenderPipelineResponse>>, + }, + CreateSampler { + device_id: DeviceId, + sampler_id: SamplerId, + descriptor: SamplerDescriptor<'static>, + }, + CreateShaderModule { + device_id: DeviceId, + program_id: ShaderModuleId, + program: String, + label: Option<String>, + sender: IpcSender<Option<ShaderCompilationInfo>>, + }, + /// Creates context + CreateContext { + buffer_ids: ArrayVec<BufferId, PRESENTATION_BUFFER_COUNT>, + size: DeviceIntSize, + sender: IpcSender<(WebGPUContextId, ImageKey)>, + }, + /// Recreates swapchain (if needed) + UpdateContext { + context_id: WebGPUContextId, + size: DeviceIntSize, + configuration: Option<ContextConfiguration>, + }, + /// Reads texture to swapchains buffer and maps it + SwapChainPresent { + context_id: WebGPUContextId, + texture_id: TextureId, + encoder_id: CommandEncoderId, + }, + /// Obtains image from latest presentation buffer (same as wr update) + GetImage { + context_id: WebGPUContextId, + sender: IpcSender<IpcSharedMemory>, + }, + ValidateTextureDescriptor { + device_id: DeviceId, + texture_id: TextureId, + descriptor: TextureDescriptor<'static>, + }, + DestroyContext { + context_id: WebGPUContextId, + }, + CreateTexture { + device_id: DeviceId, + texture_id: TextureId, + descriptor: TextureDescriptor<'static>, + }, + CreateTextureView { + texture_id: TextureId, + texture_view_id: TextureViewId, + device_id: DeviceId, + descriptor: Option<TextureViewDescriptor<'static>>, + }, + DestroyBuffer(BufferId), + DestroyDevice(DeviceId), + DestroyTexture(TextureId), + DropTexture(TextureId), + DropAdapter(AdapterId), + DropDevice(DeviceId), + DropBuffer(BufferId), + DropPipelineLayout(PipelineLayoutId), + DropComputePipeline(ComputePipelineId), + DropRenderPipeline(RenderPipelineId), + DropBindGroup(BindGroupId), + DropBindGroupLayout(BindGroupLayoutId), + DropCommandBuffer(CommandBufferId), + DropTextureView(TextureViewId), + DropSampler(SamplerId), + DropShaderModule(ShaderModuleId), + DropRenderBundle(RenderBundleId), + DropQuerySet(QuerySetId), + DropComputePass(ComputePassEncoderId), + DropRenderPass(RenderPassEncoderId), + Exit(IpcSender<()>), + RenderBundleEncoderFinish { + render_bundle_encoder: RenderBundleEncoder, + descriptor: RenderBundleDescriptor<'static>, + render_bundle_id: RenderBundleId, + device_id: DeviceId, + }, + RequestAdapter { + sender: IpcSender<WebGPUAdapterResponse>, + options: RequestAdapterOptions, + adapter_id: AdapterId, + }, + RequestDevice { + sender: IpcSender<WebGPUDeviceResponse>, + adapter_id: WebGPUAdapter, + descriptor: DeviceDescriptor<Option<String>>, + device_id: DeviceId, + queue_id: QueueId, + pipeline_id: PipelineId, + }, + // Compute Pass + BeginComputePass { + command_encoder_id: CommandEncoderId, + compute_pass_id: ComputePassId, + label: Label<'static>, + device_id: DeviceId, + }, + ComputePassSetPipeline { + compute_pass_id: ComputePassId, + pipeline_id: ComputePipelineId, + device_id: DeviceId, + }, + ComputePassSetBindGroup { + compute_pass_id: ComputePassId, + index: u32, + bind_group_id: BindGroupId, + offsets: Vec<u32>, + device_id: DeviceId, + }, + ComputePassDispatchWorkgroups { + compute_pass_id: ComputePassId, + x: u32, + y: u32, + z: u32, + device_id: DeviceId, + }, + ComputePassDispatchWorkgroupsIndirect { + compute_pass_id: ComputePassId, + buffer_id: BufferId, + offset: u64, + device_id: DeviceId, + }, + EndComputePass { + compute_pass_id: ComputePassId, + device_id: DeviceId, + command_encoder_id: CommandEncoderId, + }, + // Render Pass + BeginRenderPass { + command_encoder_id: CommandEncoderId, + render_pass_id: RenderPassId, + label: Label<'static>, + color_attachments: Vec<Option<RenderPassColorAttachment>>, + depth_stencil_attachment: Option<RenderPassDepthStencilAttachment>, + device_id: DeviceId, + }, + RenderPassCommand { + render_pass_id: RenderPassId, + render_command: RenderCommand, + device_id: DeviceId, + }, + EndRenderPass { + render_pass_id: RenderPassId, + device_id: DeviceId, + command_encoder_id: CommandEncoderId, + }, + Submit { + device_id: DeviceId, + queue_id: QueueId, + command_buffers: Vec<CommandBufferId>, + }, + UnmapBuffer { + buffer_id: BufferId, + /// Return back mapping for writeback + mapping: Option<Mapping>, + }, + WriteBuffer { + device_id: DeviceId, + queue_id: QueueId, + buffer_id: BufferId, + buffer_offset: u64, + data: IpcSharedMemory, + }, + WriteTexture { + device_id: DeviceId, + queue_id: QueueId, + texture_cv: TexelCopyTextureInfo, + data_layout: TexelCopyBufferLayout, + size: Extent3d, + data: IpcSharedMemory, + }, + QueueOnSubmittedWorkDone { + sender: IpcSender<()>, + queue_id: QueueId, + }, + PushErrorScope { + device_id: DeviceId, + filter: ErrorFilter, + }, + DispatchError { + device_id: DeviceId, + error: Error, + }, + PopErrorScope { + device_id: DeviceId, + sender: IpcSender<WebGPUPoppedErrorScopeResponse>, + }, + ComputeGetBindGroupLayout { + device_id: DeviceId, + pipeline_id: ComputePipelineId, + index: u32, + id: BindGroupLayoutId, + }, + RenderGetBindGroupLayout { + device_id: DeviceId, + pipeline_id: RenderPipelineId, + index: u32, + id: BindGroupLayoutId, + }, +} diff --git a/components/shared/webgpu/messages/to_dom.rs b/components/shared/webgpu/messages/to_dom.rs new file mode 100644 index 00000000000..b5d5db72e38 --- /dev/null +++ b/components/shared/webgpu/messages/to_dom.rs @@ -0,0 +1,16 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! IPC messages that are sent to WebGPU DOM objects. + +use wgpu_core::instance::RequestDeviceError; +use wgpu_types::DeviceDescriptor; + +use crate::{WebGPUDevice, WebGPUQueue}; + +pub type WebGPUDeviceResponse = ( + WebGPUDevice, + WebGPUQueue, + Result<DeviceDescriptor<Option<String>>, RequestDeviceError>, +); diff --git a/components/webgpu/ipc_messages/to_script.rs b/components/shared/webgpu/messages/to_script.rs index 1f0cd56cf83..303e17eeaad 100644 --- a/components/webgpu/ipc_messages/to_script.rs +++ b/components/shared/webgpu/messages/to_script.rs @@ -2,26 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ -//! IPC messages that are send to script thread. +//! IPC messages that are sent to the ScriptThread. use base::id::PipelineId; use serde::{Deserialize, Serialize}; - -use crate::gpu_error::Error; -use crate::identity::WebGPUDevice; -use crate::wgc::id::{ +use wgpu_core::id::{ AdapterId, BindGroupId, BindGroupLayoutId, BufferId, CommandBufferId, ComputePassEncoderId, ComputePipelineId, DeviceId, PipelineLayoutId, QuerySetId, RenderBundleId, RenderPassEncoderId, RenderPipelineId, SamplerId, ShaderModuleId, StagingBufferId, SurfaceId, TextureId, TextureViewId, }; -/// <https://gpuweb.github.io/gpuweb/#enumdef-gpudevicelostreason> -#[derive(Clone, Copy, Debug, Deserialize, Serialize)] -pub enum DeviceLostReason { - Unknown, - Destroyed, -} +use crate::{DeviceLostReason, Error, WebGPUDevice}; #[derive(Clone, Debug, Deserialize, Serialize)] pub enum WebGPUMsg { diff --git a/components/webgpu/render_commands.rs b/components/shared/webgpu/render_commands.rs index 3cd374e4118..37ba70daaca 100644 --- a/components/webgpu/render_commands.rs +++ b/components/shared/webgpu/render_commands.rs @@ -7,17 +7,15 @@ use serde::{Deserialize, Serialize}; use wgpu_core::command::{RenderPass, RenderPassError}; use wgpu_core::global::Global; - -use crate::wgc::id; -use crate::wgt; +use wgpu_core::id::{BindGroupId, BufferId, RenderBundleId, RenderPipelineId}; /// <https://github.com/gfx-rs/wgpu/blob/f25e07b984ab391628d9568296d5970981d79d8b/wgpu-core/src/command/render_command.rs#L17> #[derive(Debug, Deserialize, Serialize)] pub enum RenderCommand { - SetPipeline(id::RenderPipelineId), + SetPipeline(RenderPipelineId), SetBindGroup { index: u32, - bind_group_id: id::BindGroupId, + bind_group_id: BindGroupId, offsets: Vec<u32>, }, SetViewport { @@ -34,19 +32,19 @@ pub enum RenderCommand { width: u32, height: u32, }, - SetBlendConstant(wgt::Color), + SetBlendConstant(wgpu_types::Color), SetStencilReference(u32), SetIndexBuffer { - buffer_id: id::BufferId, - index_format: wgt::IndexFormat, + buffer_id: BufferId, + index_format: wgpu_types::IndexFormat, offset: u64, - size: Option<wgt::BufferSize>, + size: Option<wgpu_types::BufferSize>, }, SetVertexBuffer { slot: u32, - buffer_id: id::BufferId, + buffer_id: BufferId, offset: u64, - size: Option<wgt::BufferSize>, + size: Option<wgpu_types::BufferSize>, }, Draw { vertex_count: u32, @@ -62,14 +60,14 @@ pub enum RenderCommand { first_instance: u32, }, DrawIndirect { - buffer_id: id::BufferId, + buffer_id: BufferId, offset: u64, }, DrawIndexedIndirect { - buffer_id: id::BufferId, + buffer_id: BufferId, offset: u64, }, - ExecuteBundles(Vec<id::RenderBundleId>), + ExecuteBundles(Vec<RenderBundleId>), } pub fn apply_render_command( diff --git a/components/webgpu/Cargo.toml b/components/webgpu/Cargo.toml index fe456cecef7..029be8a5e76 100644 --- a/components/webgpu/Cargo.toml +++ b/components/webgpu/Cargo.toml @@ -20,6 +20,7 @@ log = { workspace = true } malloc_size_of = { workspace = true } serde = { workspace = true, features = ["serde_derive"] } servo_config = { path = "../config" } +webgpu_traits = { workspace = true } webrender = { workspace = true } webrender_api = { workspace = true } webrender_traits = { workspace = true } diff --git a/components/webgpu/ipc_messages/recv.rs b/components/webgpu/ipc_messages/recv.rs deleted file mode 100644 index ce69080760e..00000000000 --- a/components/webgpu/ipc_messages/recv.rs +++ /dev/null @@ -1,335 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -//! IPC messages that are received in wgpu thread -//! (usually from script thread more specifically from dom objects) - -use arrayvec::ArrayVec; -use base::id::PipelineId; -use ipc_channel::ipc::{IpcSender, IpcSharedMemory}; -use serde::{Deserialize, Serialize}; -use webrender_api::ImageKey; -use webrender_api::units::DeviceIntSize; -use wgc::binding_model::{ - BindGroupDescriptor, BindGroupLayoutDescriptor, PipelineLayoutDescriptor, -}; -use wgc::command::{ - RenderBundleDescriptor, RenderBundleEncoder, TexelCopyBufferInfo, TexelCopyTextureInfo, -}; -use wgc::device::HostMap; -use wgc::id; -use wgc::instance::RequestAdapterOptions; -use wgc::pipeline::{ComputePipelineDescriptor, RenderPipelineDescriptor}; -use wgc::resource::{ - BufferDescriptor, SamplerDescriptor, TextureDescriptor, TextureViewDescriptor, -}; -use wgpu_core::Label; -use wgpu_core::command::{RenderPassColorAttachment, RenderPassDepthStencilAttachment}; -use wgpu_core::id::AdapterId; -pub use {wgpu_core as wgc, wgpu_types as wgt}; - -use crate::identity::*; -use crate::render_commands::RenderCommand; -use crate::swapchain::WebGPUContextId; -use crate::wgc::resource::BufferAccessError; -use crate::{ - Error, ErrorFilter, Mapping, PRESENTATION_BUFFER_COUNT, ShaderCompilationInfo, - WebGPUAdapterResponse, WebGPUComputePipelineResponse, WebGPUDeviceResponse, - WebGPUPoppedErrorScopeResponse, WebGPURenderPipelineResponse, -}; - -#[derive(Clone, Copy, Debug, Deserialize, Serialize)] -pub struct ContextConfiguration { - pub device_id: id::DeviceId, - pub queue_id: id::QueueId, - pub format: wgt::TextureFormat, - pub is_opaque: bool, -} - -#[derive(Debug, Deserialize, Serialize)] -pub enum WebGPURequest { - BufferMapAsync { - sender: IpcSender<Result<Mapping, BufferAccessError>>, - buffer_id: id::BufferId, - device_id: id::DeviceId, - host_map: HostMap, - offset: u64, - size: Option<u64>, - }, - CommandEncoderFinish { - command_encoder_id: id::CommandEncoderId, - device_id: id::DeviceId, - desc: wgt::CommandBufferDescriptor<Label<'static>>, - }, - CopyBufferToBuffer { - command_encoder_id: id::CommandEncoderId, - source_id: id::BufferId, - source_offset: wgt::BufferAddress, - destination_id: id::BufferId, - destination_offset: wgt::BufferAddress, - size: wgt::BufferAddress, - }, - CopyBufferToTexture { - command_encoder_id: id::CommandEncoderId, - source: TexelCopyBufferInfo, - destination: TexelCopyTextureInfo, - copy_size: wgt::Extent3d, - }, - CopyTextureToBuffer { - command_encoder_id: id::CommandEncoderId, - source: TexelCopyTextureInfo, - destination: TexelCopyBufferInfo, - copy_size: wgt::Extent3d, - }, - CopyTextureToTexture { - command_encoder_id: id::CommandEncoderId, - source: TexelCopyTextureInfo, - destination: TexelCopyTextureInfo, - copy_size: wgt::Extent3d, - }, - CreateBindGroup { - device_id: id::DeviceId, - bind_group_id: id::BindGroupId, - descriptor: BindGroupDescriptor<'static>, - }, - CreateBindGroupLayout { - device_id: id::DeviceId, - bind_group_layout_id: id::BindGroupLayoutId, - descriptor: Option<BindGroupLayoutDescriptor<'static>>, - }, - CreateBuffer { - device_id: id::DeviceId, - buffer_id: id::BufferId, - descriptor: BufferDescriptor<'static>, - }, - CreateCommandEncoder { - device_id: id::DeviceId, - command_encoder_id: id::CommandEncoderId, - desc: wgt::CommandEncoderDescriptor<Label<'static>>, - }, - CreateComputePipeline { - device_id: id::DeviceId, - compute_pipeline_id: id::ComputePipelineId, - descriptor: ComputePipelineDescriptor<'static>, - implicit_ids: Option<(id::PipelineLayoutId, Vec<id::BindGroupLayoutId>)>, - /// present only on ASYNC versions - async_sender: Option<IpcSender<WebGPUComputePipelineResponse>>, - }, - CreatePipelineLayout { - device_id: id::DeviceId, - pipeline_layout_id: id::PipelineLayoutId, - descriptor: PipelineLayoutDescriptor<'static>, - }, - CreateRenderPipeline { - device_id: id::DeviceId, - render_pipeline_id: id::RenderPipelineId, - descriptor: RenderPipelineDescriptor<'static>, - implicit_ids: Option<(id::PipelineLayoutId, Vec<id::BindGroupLayoutId>)>, - /// present only on ASYNC versions - async_sender: Option<IpcSender<WebGPURenderPipelineResponse>>, - }, - CreateSampler { - device_id: id::DeviceId, - sampler_id: id::SamplerId, - descriptor: SamplerDescriptor<'static>, - }, - CreateShaderModule { - device_id: id::DeviceId, - program_id: id::ShaderModuleId, - program: String, - label: Option<String>, - sender: IpcSender<Option<ShaderCompilationInfo>>, - }, - /// Creates context - CreateContext { - buffer_ids: ArrayVec<id::BufferId, PRESENTATION_BUFFER_COUNT>, - size: DeviceIntSize, - sender: IpcSender<(WebGPUContextId, ImageKey)>, - }, - /// Recreates swapchain (if needed) - UpdateContext { - context_id: WebGPUContextId, - size: DeviceIntSize, - configuration: Option<ContextConfiguration>, - }, - /// Reads texture to swapchains buffer and maps it - SwapChainPresent { - context_id: WebGPUContextId, - texture_id: id::TextureId, - encoder_id: id::CommandEncoderId, - }, - /// Obtains image from latest presentation buffer (same as wr update) - GetImage { - context_id: WebGPUContextId, - sender: IpcSender<IpcSharedMemory>, - }, - ValidateTextureDescriptor { - device_id: id::DeviceId, - texture_id: id::TextureId, - descriptor: TextureDescriptor<'static>, - }, - DestroyContext { - context_id: WebGPUContextId, - }, - CreateTexture { - device_id: id::DeviceId, - texture_id: id::TextureId, - descriptor: TextureDescriptor<'static>, - }, - CreateTextureView { - texture_id: id::TextureId, - texture_view_id: id::TextureViewId, - device_id: id::DeviceId, - descriptor: Option<TextureViewDescriptor<'static>>, - }, - DestroyBuffer(id::BufferId), - DestroyDevice(id::DeviceId), - DestroyTexture(id::TextureId), - DropTexture(id::TextureId), - DropAdapter(id::AdapterId), - DropDevice(id::DeviceId), - DropBuffer(id::BufferId), - DropPipelineLayout(id::PipelineLayoutId), - DropComputePipeline(id::ComputePipelineId), - DropRenderPipeline(id::RenderPipelineId), - DropBindGroup(id::BindGroupId), - DropBindGroupLayout(id::BindGroupLayoutId), - DropCommandBuffer(id::CommandBufferId), - DropTextureView(id::TextureViewId), - DropSampler(id::SamplerId), - DropShaderModule(id::ShaderModuleId), - DropRenderBundle(id::RenderBundleId), - DropQuerySet(id::QuerySetId), - DropComputePass(id::ComputePassEncoderId), - DropRenderPass(id::RenderPassEncoderId), - Exit(IpcSender<()>), - RenderBundleEncoderFinish { - render_bundle_encoder: RenderBundleEncoder, - descriptor: RenderBundleDescriptor<'static>, - render_bundle_id: id::RenderBundleId, - device_id: id::DeviceId, - }, - RequestAdapter { - sender: IpcSender<WebGPUAdapterResponse>, - options: RequestAdapterOptions, - adapter_id: AdapterId, - }, - RequestDevice { - sender: IpcSender<WebGPUDeviceResponse>, - adapter_id: WebGPUAdapter, - descriptor: wgt::DeviceDescriptor<Option<String>>, - device_id: id::DeviceId, - queue_id: id::QueueId, - pipeline_id: PipelineId, - }, - // Compute Pass - BeginComputePass { - command_encoder_id: id::CommandEncoderId, - compute_pass_id: ComputePassId, - label: Label<'static>, - device_id: id::DeviceId, - }, - ComputePassSetPipeline { - compute_pass_id: ComputePassId, - pipeline_id: id::ComputePipelineId, - device_id: id::DeviceId, - }, - ComputePassSetBindGroup { - compute_pass_id: ComputePassId, - index: u32, - bind_group_id: id::BindGroupId, - offsets: Vec<u32>, - device_id: id::DeviceId, - }, - ComputePassDispatchWorkgroups { - compute_pass_id: ComputePassId, - x: u32, - y: u32, - z: u32, - device_id: id::DeviceId, - }, - ComputePassDispatchWorkgroupsIndirect { - compute_pass_id: ComputePassId, - buffer_id: id::BufferId, - offset: u64, - device_id: id::DeviceId, - }, - EndComputePass { - compute_pass_id: ComputePassId, - device_id: id::DeviceId, - command_encoder_id: id::CommandEncoderId, - }, - // Render Pass - BeginRenderPass { - command_encoder_id: id::CommandEncoderId, - render_pass_id: RenderPassId, - label: Label<'static>, - color_attachments: Vec<Option<RenderPassColorAttachment>>, - depth_stencil_attachment: Option<RenderPassDepthStencilAttachment>, - device_id: id::DeviceId, - }, - RenderPassCommand { - render_pass_id: RenderPassId, - render_command: RenderCommand, - device_id: id::DeviceId, - }, - EndRenderPass { - render_pass_id: RenderPassId, - device_id: id::DeviceId, - command_encoder_id: id::CommandEncoderId, - }, - Submit { - device_id: id::DeviceId, - queue_id: id::QueueId, - command_buffers: Vec<id::CommandBufferId>, - }, - UnmapBuffer { - buffer_id: id::BufferId, - /// Return back mapping for writeback - mapping: Option<Mapping>, - }, - WriteBuffer { - device_id: id::DeviceId, - queue_id: id::QueueId, - buffer_id: id::BufferId, - buffer_offset: u64, - data: IpcSharedMemory, - }, - WriteTexture { - device_id: id::DeviceId, - queue_id: id::QueueId, - texture_cv: TexelCopyTextureInfo, - data_layout: wgt::TexelCopyBufferLayout, - size: wgt::Extent3d, - data: IpcSharedMemory, - }, - QueueOnSubmittedWorkDone { - sender: IpcSender<()>, - queue_id: id::QueueId, - }, - PushErrorScope { - device_id: id::DeviceId, - filter: ErrorFilter, - }, - DispatchError { - device_id: id::DeviceId, - error: Error, - }, - PopErrorScope { - device_id: id::DeviceId, - sender: IpcSender<WebGPUPoppedErrorScopeResponse>, - }, - ComputeGetBindGroupLayout { - device_id: id::DeviceId, - pipeline_id: id::ComputePipelineId, - index: u32, - id: id::BindGroupLayoutId, - }, - RenderGetBindGroupLayout { - device_id: id::DeviceId, - pipeline_id: id::RenderPipelineId, - index: u32, - id: id::BindGroupLayoutId, - }, -} diff --git a/components/webgpu/lib.rs b/components/webgpu/lib.rs index f67c55ab02e..1842258a9fb 100644 --- a/components/webgpu/lib.rs +++ b/components/webgpu/lib.rs @@ -5,95 +5,73 @@ use log::warn; use swapchain::WGPUImageMap; pub use swapchain::{ContextData, WGPUExternalImages}; +use webgpu_traits::{WebGPU, WebGPUMsg}; use webrender::RenderApiSender; use wgpu_thread::WGPU; pub use {wgpu_core as wgc, wgpu_types as wgt}; -pub mod identity; mod poll_thread; mod wgpu_thread; use std::borrow::Cow; use std::sync::{Arc, Mutex}; -pub use gpu_error::{Error, ErrorFilter, PopError}; -use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; -pub use render_commands::RenderCommand; -use serde::{Deserialize, Serialize}; +use ipc_channel::ipc::{self, IpcReceiver}; use servo_config::pref; use webrender_api::DocumentId; use webrender_traits::WebrenderExternalImageRegistry; -mod gpu_error; -mod ipc_messages; -mod render_commands; pub mod swapchain; -pub use identity::*; -pub use ipc_messages::recv::*; -pub use ipc_messages::to_dom::*; -pub use ipc_messages::to_script::*; -pub use swapchain::PRESENTATION_BUFFER_COUNT; -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct WebGPU(pub IpcSender<WebGPURequest>); - -impl WebGPU { - pub fn new( - webrender_api_sender: RenderApiSender, - webrender_document: DocumentId, - external_images: Arc<Mutex<WebrenderExternalImageRegistry>>, - wgpu_image_map: WGPUImageMap, - ) -> Option<(Self, IpcReceiver<WebGPUMsg>)> { - if !pref!(dom_webgpu_enabled) { +pub fn start_webgpu_thread( + webrender_api_sender: RenderApiSender, + webrender_document: DocumentId, + external_images: Arc<Mutex<WebrenderExternalImageRegistry>>, + wgpu_image_map: WGPUImageMap, +) -> Option<(WebGPU, IpcReceiver<WebGPUMsg>)> { + if !pref!(dom_webgpu_enabled) { + return None; + } + let (sender, receiver) = match ipc::channel() { + Ok(sender_and_receiver) => sender_and_receiver, + Err(e) => { + warn!( + "Failed to create sender and receiver for WGPU thread ({})", + e + ); return None; - } - let (sender, receiver) = match ipc::channel() { - Ok(sender_and_receiver) => sender_and_receiver, - Err(e) => { - warn!( - "Failed to create sender and receiver for WGPU thread ({})", - e - ); - return None; - }, - }; - let sender_clone = sender.clone(); + }, + }; + let sender_clone = sender.clone(); - let (script_sender, script_recv) = match ipc::channel() { - Ok(sender_and_receiver) => sender_and_receiver, - Err(e) => { - warn!( - "Failed to create receiver and sender for WGPU thread ({})", - e - ); - return None; - }, - }; - - if let Err(e) = std::thread::Builder::new() - .name("WGPU".to_owned()) - .spawn(move || { - WGPU::new( - receiver, - sender_clone, - script_sender, - webrender_api_sender, - webrender_document, - external_images, - wgpu_image_map, - ) - .run(); - }) - { - warn!("Failed to spawn WGPU thread ({})", e); + let (script_sender, script_recv) = match ipc::channel() { + Ok(sender_and_receiver) => sender_and_receiver, + Err(e) => { + warn!( + "Failed to create receiver and sender for WGPU thread ({})", + e + ); return None; - } - Some((WebGPU(sender), script_recv)) - } + }, + }; - pub fn exit(&self, sender: IpcSender<()>) -> Result<(), &'static str> { - self.0 - .send(WebGPURequest::Exit(sender)) - .map_err(|_| "Failed to send Exit message") + if let Err(e) = std::thread::Builder::new() + .name("WGPU".to_owned()) + .spawn(move || { + WGPU::new( + receiver, + sender_clone, + script_sender, + webrender_api_sender, + webrender_document, + external_images, + wgpu_image_map, + ) + .run(); + }) + { + warn!("Failed to spawn WGPU thread ({})", e); + return None; } + Some((WebGPU(sender), script_recv)) } diff --git a/components/webgpu/swapchain.rs b/components/webgpu/swapchain.rs index 78b0c2bbf7e..0245084e480 100644 --- a/components/webgpu/swapchain.rs +++ b/components/webgpu/swapchain.rs @@ -11,8 +11,10 @@ use arrayvec::ArrayVec; use euclid::default::Size2D; use ipc_channel::ipc::{IpcSender, IpcSharedMemory}; use log::{error, warn}; -use malloc_size_of::MallocSizeOf; use serde::{Deserialize, Serialize}; +use webgpu_traits::{ + ContextConfiguration, Error, PRESENTATION_BUFFER_COUNT, WebGPUContextId, WebGPUMsg, +}; use webrender::{RenderApi, Transaction}; use webrender_api::units::DeviceIntSize; use webrender_api::{ @@ -25,31 +27,10 @@ use wgpu_core::global::Global; use wgpu_core::id; use wgpu_core::resource::{BufferAccessError, BufferMapOperation}; -use crate::{ContextConfiguration, Error, WebGPUMsg, wgt}; +use crate::wgt; -pub const PRESENTATION_BUFFER_COUNT: usize = 10; const DEFAULT_IMAGE_FORMAT: ImageFormat = ImageFormat::RGBA8; -#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] -pub struct WebGPUContextId(pub u64); - -impl MallocSizeOf for WebGPUContextId { - fn size_of(&self, _ops: &mut malloc_size_of::MallocSizeOfOps) -> usize { - 0 - } -} - -impl ContextConfiguration { - fn format(&self) -> ImageFormat { - match self.format { - wgt::TextureFormat::Rgba8Unorm => ImageFormat::RGBA8, - wgt::TextureFormat::Bgra8Unorm => ImageFormat::BGRA8, - // TODO: wgt::TextureFormat::Rgba16Float - _ => unreachable!("Unsupported canvas context format in configuration"), - } - } -} - pub type WGPUImageMap = Arc<Mutex<HashMap<WebGPUContextId, ContextData>>>; /// Presentation id encodes current configuration and current image diff --git a/components/webgpu/wgpu_thread.rs b/components/webgpu/wgpu_thread.rs index d0cec8250ba..93cf5a56bae 100644 --- a/components/webgpu/wgpu_thread.rs +++ b/components/webgpu/wgpu_thread.rs @@ -13,6 +13,11 @@ use base::id::PipelineId; use ipc_channel::ipc::{IpcReceiver, IpcSender, IpcSharedMemory}; use log::{info, warn}; use servo_config::pref; +use webgpu_traits::{ + Adapter, ComputePassId, DeviceLostReason, Error, ErrorScope, Mapping, Pipeline, PopError, + RenderPassId, ShaderCompilationInfo, WebGPU, WebGPUAdapter, WebGPUContextId, WebGPUDevice, + WebGPUMsg, WebGPUQueue, WebGPURequest, apply_render_command, +}; use webrender::{RenderApi, RenderApiSender}; use webrender_api::{DocumentId, ExternalImageId}; use webrender_traits::{WebrenderExternalImageRegistry, WebrenderImageHandlerType}; @@ -30,14 +35,8 @@ use wgpu_types::MemoryHints; use wgt::InstanceDescriptor; pub use {wgpu_core as wgc, wgpu_types as wgt}; -use crate::gpu_error::ErrorScope; use crate::poll_thread::Poller; -use crate::render_commands::apply_render_command; -use crate::swapchain::{WGPUImageMap, WebGPUContextId}; -use crate::{ - Adapter, ComputePassId, Error, Mapping, Pipeline, PopError, RenderPassId, WebGPU, - WebGPUAdapter, WebGPUDevice, WebGPUMsg, WebGPUQueue, WebGPURequest, -}; +use crate::swapchain::WGPUImageMap; #[derive(Eq, Hash, PartialEq)] pub(crate) struct DeviceScope { @@ -489,7 +488,7 @@ impl WGPU { if let Err(e) = sender.send( error .as_ref() - .map(|e| crate::ShaderCompilationInfo::from(e, &program)), + .map(|e| ShaderCompilationInfo::from(e, &program)), ) { warn!("Failed to send CompilationInfo {e:?}"); } @@ -710,11 +709,9 @@ impl WGPU { let devices = Arc::clone(&self.devices); let callback = Box::from(move |reason, msg| { let reason = match reason { - wgt::DeviceLostReason::Unknown => { - crate::DeviceLostReason::Unknown - }, + wgt::DeviceLostReason::Unknown => DeviceLostReason::Unknown, wgt::DeviceLostReason::Destroyed => { - crate::DeviceLostReason::Destroyed + DeviceLostReason::Destroyed }, }; // make device lost by removing error scopes stack |