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

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,100 +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/. */
//! Error scopes and GPUError types
use std::fmt;
use serde::{Deserialize, Serialize};
use crate::wgc;
/// <https://www.w3.org/TR/webgpu/#gpu-error-scope>
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub(crate) struct ErrorScope {
pub errors: Vec<Error>,
pub filter: ErrorFilter,
}
impl ErrorScope {
pub fn new(filter: ErrorFilter) -> Self {
Self {
filter,
errors: Vec::new(),
}
}
}
/// <https://www.w3.org/TR/webgpu/#enumdef-gpuerrorfilter>
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum ErrorFilter {
Validation,
OutOfMemory,
Internal,
}
/// <https://www.w3.org/TR/webgpu/#gpuerror>
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum Error {
Validation(String),
OutOfMemory(String),
Internal(String),
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message())
}
}
impl Error {
pub fn filter(&self) -> ErrorFilter {
match self {
Error::Validation(_) => ErrorFilter::Validation,
Error::OutOfMemory(_) => ErrorFilter::OutOfMemory,
Error::Internal(_) => ErrorFilter::Internal,
}
}
pub fn message(&self) -> &str {
match self {
Error::Validation(m) => m,
Error::OutOfMemory(m) => m,
Error::Internal(m) => m,
}
}
// TODO: labels
// based on https://github.com/gfx-rs/wgpu/blob/trunk/wgpu/src/backend/wgpu_core.rs#L289
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>()
{
return Self::OutOfMemory(error.to_string());
}
source_opt = source.source();
}
// TODO: This hack is needed because there are
// multiple OutOfMemory error variant in wgpu-core
// and even upstream does not handle them correctly
if format!("{error:?}").contains("OutOfMemory") {
return Self::OutOfMemory(error.to_string());
}
Self::Validation(error.to_string())
}
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum PopError {
Lost,
Empty,
}

View file

@ -1,53 +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/. */
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use serde::{Deserialize, Serialize};
pub use crate::wgc::id::markers::{
ComputePassEncoder as ComputePass, RenderPassEncoder as RenderPass,
};
use crate::wgc::id::{
AdapterId, BindGroupId, BindGroupLayoutId, BufferId, CommandBufferId, CommandEncoderId,
ComputePipelineId, DeviceId, PipelineLayoutId, QueueId, RenderBundleId, RenderPipelineId,
SamplerId, ShaderModuleId, SurfaceId, TextureId, TextureViewId,
};
pub use crate::wgc::id::{
ComputePassEncoderId as ComputePassId, RenderPassEncoderId as RenderPassId,
};
macro_rules! webgpu_resource {
($name:ident, $id:ty) => {
#[derive(Clone, Copy, Debug, Deserialize, Hash, PartialEq, Serialize)]
pub struct $name(pub $id);
impl MallocSizeOf for $name {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
impl Eq for $name {}
};
}
webgpu_resource!(WebGPUAdapter, AdapterId);
webgpu_resource!(WebGPUBindGroup, BindGroupId);
webgpu_resource!(WebGPUBindGroupLayout, BindGroupLayoutId);
webgpu_resource!(WebGPUBuffer, BufferId);
webgpu_resource!(WebGPUCommandBuffer, CommandBufferId);
webgpu_resource!(WebGPUCommandEncoder, CommandEncoderId);
webgpu_resource!(WebGPUComputePipeline, ComputePipelineId);
webgpu_resource!(WebGPUDevice, DeviceId);
webgpu_resource!(WebGPUPipelineLayout, PipelineLayoutId);
webgpu_resource!(WebGPUQueue, QueueId);
webgpu_resource!(WebGPURenderBundle, RenderBundleId);
webgpu_resource!(WebGPURenderPipeline, RenderPipelineId);
webgpu_resource!(WebGPUSampler, SamplerId);
webgpu_resource!(WebGPUShaderModule, ShaderModuleId);
webgpu_resource!(WebGPUSurface, SurfaceId);
webgpu_resource!(WebGPUTexture, TextureId);
webgpu_resource!(WebGPUTextureView, TextureViewId);
webgpu_resource!(WebGPUComputePass, ComputePassId);
webgpu_resource!(WebGPURenderPass, RenderPassId);

View file

@ -1,7 +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/. */
pub mod recv;
pub mod to_dom;
pub mod to_script;

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

@ -1,94 +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 send to WebGPU DOM objects.
use std::ops::Range;
use ipc_channel::ipc::IpcSharedMemory;
use serde::{Deserialize, Serialize};
use wgc::id;
use wgc::pipeline::CreateShaderModuleError;
use wgpu_core::device::HostMap;
use wgpu_core::instance::{RequestAdapterError, RequestDeviceError};
pub use {wgpu_core as wgc, wgpu_types as wgt};
use crate::identity::*;
use crate::{Error, PopError, WebGPU};
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct ShaderCompilationInfo {
pub line_number: u64,
pub line_pos: u64,
pub offset: u64,
pub length: u64,
pub message: String,
}
impl ShaderCompilationInfo {
pub fn from(error: &CreateShaderModuleError, source: &str) -> Self {
let location = match error {
CreateShaderModuleError::Parsing(e) => e.inner.location(source),
CreateShaderModuleError::Validation(e) => e.inner.location(source),
_ => None,
};
if let Some(location) = location {
// Naga reports locations in UTF-8 code units, but spec requires location in UTF-16 code units
// Based on https://searchfox.org/mozilla-central/rev/5b037d9c6ecdb0729f39ad519f0b867d80a92aad/gfx/wgpu_bindings/src/server.rs#353
fn len_utf16(s: &str) -> u64 {
s.chars().map(|c| c.len_utf16() as u64).sum()
}
let start = location.offset as usize;
let end = start + location.length as usize;
let line_start = source[0..start].rfind('\n').map(|pos| pos + 1).unwrap_or(0);
Self {
line_number: location.line_number as u64,
line_pos: len_utf16(&source[line_start..start]) + 1,
offset: len_utf16(&source[0..start]),
length: len_utf16(&source[start..end]),
message: error.to_string(),
}
} else {
Self {
message: error.to_string(),
..Default::default()
}
}
}
}
#[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,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Mapping {
pub data: IpcSharedMemory,
pub mode: HostMap,
pub range: Range<u64>,
}
pub type WebGPUDeviceResponse = (
WebGPUDevice,
WebGPUQueue,
Result<wgt::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

@ -1,62 +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 send to script thread.
use base::id::PipelineId;
use serde::{Deserialize, Serialize};
use crate::gpu_error::Error;
use crate::identity::WebGPUDevice;
use crate::wgc::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,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum WebGPUMsg {
FreeAdapter(AdapterId),
FreeDevice {
device_id: DeviceId,
pipeline_id: PipelineId,
},
FreeBuffer(BufferId),
FreePipelineLayout(PipelineLayoutId),
FreeComputePipeline(ComputePipelineId),
FreeRenderPipeline(RenderPipelineId),
FreeBindGroup(BindGroupId),
FreeBindGroupLayout(BindGroupLayoutId),
FreeCommandBuffer(CommandBufferId),
FreeTexture(TextureId),
FreeTextureView(TextureViewId),
FreeSampler(SamplerId),
FreeSurface(SurfaceId),
FreeShaderModule(ShaderModuleId),
FreeRenderBundle(RenderBundleId),
FreeStagingBuffer(StagingBufferId),
FreeQuerySet(QuerySetId),
FreeComputePass(ComputePassEncoderId),
FreeRenderPass(RenderPassEncoderId),
UncapturedError {
device: WebGPUDevice,
pipeline_id: PipelineId,
error: Error,
},
DeviceLost {
device: WebGPUDevice,
pipeline_id: PipelineId,
reason: DeviceLostReason,
msg: String,
},
Exit,
}

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

@ -1,157 +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/. */
//! Render pass commands
use serde::{Deserialize, Serialize};
use wgpu_core::command::{RenderPass, RenderPassError};
use wgpu_core::global::Global;
use crate::wgc::id;
use crate::wgt;
/// <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),
SetBindGroup {
index: u32,
bind_group_id: id::BindGroupId,
offsets: Vec<u32>,
},
SetViewport {
x: f32,
y: f32,
width: f32,
height: f32,
min_depth: f32,
max_depth: f32,
},
SetScissorRect {
x: u32,
y: u32,
width: u32,
height: u32,
},
SetBlendConstant(wgt::Color),
SetStencilReference(u32),
SetIndexBuffer {
buffer_id: id::BufferId,
index_format: wgt::IndexFormat,
offset: u64,
size: Option<wgt::BufferSize>,
},
SetVertexBuffer {
slot: u32,
buffer_id: id::BufferId,
offset: u64,
size: Option<wgt::BufferSize>,
},
Draw {
vertex_count: u32,
instance_count: u32,
first_vertex: u32,
first_instance: u32,
},
DrawIndexed {
index_count: u32,
instance_count: u32,
first_index: u32,
base_vertex: i32,
first_instance: u32,
},
DrawIndirect {
buffer_id: id::BufferId,
offset: u64,
},
DrawIndexedIndirect {
buffer_id: id::BufferId,
offset: u64,
},
ExecuteBundles(Vec<id::RenderBundleId>),
}
pub fn apply_render_command(
global: &Global,
pass: &mut RenderPass,
command: RenderCommand,
) -> Result<(), RenderPassError> {
match command {
RenderCommand::SetPipeline(pipeline_id) => {
global.render_pass_set_pipeline(pass, pipeline_id)
},
RenderCommand::SetBindGroup {
index,
bind_group_id,
offsets,
} => global.render_pass_set_bind_group(pass, index, Some(bind_group_id), &offsets),
RenderCommand::SetViewport {
x,
y,
width,
height,
min_depth,
max_depth,
} => global.render_pass_set_viewport(pass, x, y, width, height, min_depth, max_depth),
RenderCommand::SetScissorRect {
x,
y,
width,
height,
} => global.render_pass_set_scissor_rect(pass, x, y, width, height),
RenderCommand::SetBlendConstant(color) => {
global.render_pass_set_blend_constant(pass, color)
},
RenderCommand::SetStencilReference(reference) => {
global.render_pass_set_stencil_reference(pass, reference)
},
RenderCommand::SetIndexBuffer {
buffer_id,
index_format,
offset,
size,
} => global.render_pass_set_index_buffer(pass, buffer_id, index_format, offset, size),
RenderCommand::SetVertexBuffer {
slot,
buffer_id,
offset,
size,
} => global.render_pass_set_vertex_buffer(pass, slot, buffer_id, offset, size),
RenderCommand::Draw {
vertex_count,
instance_count,
first_vertex,
first_instance,
} => global.render_pass_draw(
pass,
vertex_count,
instance_count,
first_vertex,
first_instance,
),
RenderCommand::DrawIndexed {
index_count,
instance_count,
first_index,
base_vertex,
first_instance,
} => global.render_pass_draw_indexed(
pass,
index_count,
instance_count,
first_index,
base_vertex,
first_instance,
),
RenderCommand::DrawIndirect { buffer_id, offset } => {
global.render_pass_draw_indirect(pass, buffer_id, offset)
},
RenderCommand::DrawIndexedIndirect { buffer_id, offset } => {
global.render_pass_draw_indexed_indirect(pass, buffer_id, offset)
},
RenderCommand::ExecuteBundles(bundles) => {
global.render_pass_execute_bundles(pass, &bundles)
},
}
}

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