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>
This commit is contained in:
Martin Robinson 2025-04-04 10:06:07 +02:00 committed by GitHub
parent df9efde1c3
commit 0d693114ad
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
52 changed files with 640 additions and 568 deletions

20
Cargo.lock generated
View file

@ -1172,6 +1172,7 @@ dependencies = [
"stylo_traits",
"tracing",
"webgpu",
"webgpu_traits",
"webrender",
"webrender_api",
"webrender_traits",
@ -6378,6 +6379,7 @@ dependencies = [
"uuid",
"webdriver",
"webgpu",
"webgpu_traits",
"webrender_api",
"webrender_traits",
"webxr-api",
@ -6501,10 +6503,11 @@ dependencies = [
"stylo_traits",
"uuid",
"webdriver",
"webgpu",
"webgpu_traits",
"webrender_api",
"webrender_traits",
"webxr-api",
"wgpu-core",
]
[[package]]
@ -8567,6 +8570,7 @@ dependencies = [
"serde",
"servo_config",
"servo_malloc_size_of",
"webgpu_traits",
"webrender",
"webrender_api",
"webrender_traits",
@ -8574,6 +8578,20 @@ dependencies = [
"wgpu-types",
]
[[package]]
name = "webgpu_traits"
version = "0.0.1"
dependencies = [
"arrayvec",
"base",
"ipc-channel",
"serde",
"servo_malloc_size_of",
"webrender_api",
"wgpu-core",
"wgpu-types",
]
[[package]]
name = "webpki-roots"
version = "0.26.8"

View file

@ -162,6 +162,7 @@ unicode-segmentation = "1.12.0"
url = "2.5"
uuid = { version = "1.12.1", features = ["v4"] }
webdriver = "0.51.0"
webgpu_traits = { path = "components/shared/webgpu" }
webpki-roots = "0.26"
webrender = { git = "https://github.com/servo/webrender", branch = "0.66", features = ["capture"] }
webrender_api = { git = "https://github.com/servo/webrender", branch = "0.66" }

View file

@ -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 }

View file

@ -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(),

View file

@ -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 }

View file

@ -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;

View file

@ -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

View file

@ -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::{

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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);

View file

@ -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;

View file

@ -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;

View file

@ -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};

View file

@ -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};

View file

@ -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,

View file

@ -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;

View file

@ -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,
};

View file

@ -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(),
));

View file

@ -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,
),
)
},
}
}
}

View file

@ -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};

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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,
};

View file

@ -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;

View file

@ -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;

View file

@ -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

View file

@ -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;

View file

@ -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 {

View file

@ -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;

View file

@ -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;

View file

@ -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 }

View file

@ -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;

View file

@ -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

View file

@ -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 }

View file

@ -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();

View file

@ -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);

View file

@ -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 {
@ -59,15 +124,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,
@ -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>;

View file

@ -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::*;

View file

@ -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,
},
}

View file

@ -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>,
);

View file

@ -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 {

View file

@ -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(

View file

@ -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 }

View file

@ -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,
},
}

View file

@ -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) {
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 (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);
return None;
}
Some((WebGPU(sender), script_recv))
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_clone = sender.clone();
pub fn exit(&self, sender: IpcSender<()>) -> Result<(), &'static str> {
self.0
.send(WebGPURequest::Exit(sender))
.map_err(|_| "Failed to send Exit message")
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);
return None;
}
Some((WebGPU(sender), script_recv))
}

View file

@ -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

View file

@ -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