use dom_struct::dom_struct;
use js::context::{JSContext, NoGC};
use log::warn;
use malloc_size_of_derive::MallocSizeOf;
use script_bindings::DomTypes;
use script_bindings::cell::DomRefCell;
use script_bindings::codegen::GenericBindings::WebGPUBinding::{
GPUCommandBufferDescriptor, GPUCommandEncoderDescriptor, GPUCommandEncoderMethods,
GPUCommandEncoderWrap, GPUComputePassDescriptor, GPURenderPassDescriptor, GPUSize64,
GPUTexelCopyBufferInfo, GPUTexelCopyTextureInfo,
};
use script_bindings::codegen::GenericUnionTypes::RangeEnforcedUnsignedLongSequenceOrGPUExtent3DDict as GPUExtent3D;
use script_bindings::interfaces::PromiseHelpers;
use script_bindings::reflector::{DomGlobalGeneric, Reflector, reflect_dom_object_with_wrap};
use webgpu_traits::{
CommandBufferDescriptor, CommandEncoderCommand, CommandEncoderDescriptor, DebugCommand,
PassChannel, RenderPassColorAttachment, RenderPassDepthStencilAttachment, WebGPU,
WebGPUCommandBuffer, WebGPUCommandEncoder, WebGPUComputePass, WebGPUDevice, WebGPURenderPass,
WebGPURequest,
};
use crate::JSTraceable;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::USVString;
use crate::gpubuffer::GPUBuffer;
use crate::gpucommandbuffer::GPUCommandBuffer;
use crate::gpucomputepassencoder::GPUComputePassEncoder;
use crate::gpuconvert::{
WebGPUConvert, WebGPUTryConvert, convert_load_op, convert_texture_for_wgpu_with_cx,
};
use crate::gpuqueryset::GPUQuerySet;
use crate::gpurenderpassencoder::GPURenderPassEncoder;
use crate::traits::{Equivalence, WebGPUGlobalTrait, WebGPUPromise};
#[derive(JSTraceable, MallocSizeOf)]
struct DroppableGPUCommandEncoder {
#[no_trace]
channel: WebGPU,
#[no_trace]
encoder: WebGPUCommandEncoder,
}
#[dom_struct]
pub struct GPUCommandEncoder<D: DomTypes> {
reflector_: Reflector,
droppable: DroppableGPUCommandEncoder,
label: DomRefCell<USVString>,
device: Dom<D::GPUDevice>,
}
impl Drop for DroppableGPUCommandEncoder {
fn drop(&mut self) {
if let Err(e) = self
.channel
.0
.send(WebGPURequest::DropCommandEncoder(self.encoder.0))
{
warn!("Failed to send WebGPURequest::DropCommandEncoder with {e:?}");
}
}
}
impl<D: Equivalence> GPUCommandEncoder<D> {
pub(crate) fn new_inherited(
channel: WebGPU,
device: &D::GPUDevice,
encoder: WebGPUCommandEncoder,
label: USVString,
) -> Self {
Self {
droppable: DroppableGPUCommandEncoder { channel, encoder },
reflector_: Reflector::new(),
label: DomRefCell::new(label),
device: Dom::from_ref(device),
}
}
pub(crate) fn new(
cx: &mut JSContext,
global: &D::GlobalScope,
channel: WebGPU,
device: &D::GPUDevice,
encoder: WebGPUCommandEncoder,
label: USVString,
) -> DomRoot<Self> {
reflect_dom_object_with_wrap::<D, _, _>(
cx,
Box::new(GPUCommandEncoder::new_inherited(
channel, device, encoder, label,
)),
global,
GPUCommandEncoderWrap::<D>,
)
}
}
impl<D> GPUCommandEncoder<D>
where
D: Equivalence,
<D::Promise as PromiseHelpers<D>>::StackRoot: WebGPUPromise<D>,
{
pub(crate) fn id(&self) -> WebGPUCommandEncoder {
self.droppable.encoder
}
pub(crate) fn device_id(&self) -> WebGPUDevice {
self.device.id()
}
pub(crate) fn create(
cx: &mut JSContext,
device: &D::GPUDevice,
descriptor: &GPUCommandEncoderDescriptor,
) -> DomRoot<GPUCommandEncoder<D>> {
let command_encoder_id = device
.global_from_reflector()
.global_wgpu_id_hub()
.create_command_encoder_id();
device
.channel()
.0
.send(WebGPURequest::CreateCommandEncoder {
device_id: device.id().0,
command_encoder_id,
desc: CommandEncoderDescriptor {
label: (&descriptor.parent).convert(),
},
})
.expect("Failed to create WebGPU command encoder");
let encoder = WebGPUCommandEncoder(command_encoder_id);
GPUCommandEncoder::new(
cx,
&*device.global_from_reflector(),
device.channel(),
device,
encoder,
descriptor.parent.label.clone(),
)
}
fn send_command(&self, command: CommandEncoderCommand) {
if let Err(error) = self
.droppable
.channel
.0
.send(WebGPURequest::CommandEncoderCommand {
command_encoder_id: self.droppable.encoder.0,
command,
device_id: self.device.id().0,
})
{
warn!("Failed to send WebGPURequest::CommandEncoderCommand {error:?}");
}
}
}
impl<D> GPUCommandEncoderMethods<D> for GPUCommandEncoder<D>
where
D: Equivalence,
<D::Promise as PromiseHelpers<D>>::StackRoot: WebGPUPromise<D>,
{
fn Label(&self) -> USVString {
self.label.borrow().clone()
}
fn SetLabel(&self, no_gc: &NoGC, value: USVString) {
*self.label.safe_borrow_mut(no_gc) = value;
}
fn BeginComputePass(
&self,
cx: &mut JSContext,
descriptor: &GPUComputePassDescriptor<D>,
) -> DomRoot<GPUComputePassEncoder<D>> {
let compute_pass_id = self
.global_from_reflector()
.global_wgpu_id_hub()
.create_compute_pass_id();
if let Err(error) = self
.droppable
.channel
.0
.send(WebGPURequest::BeginComputePass {
command_encoder_id: self.id().0,
compute_pass_id,
label: (&descriptor.parent).convert(),
timestamp_writes: descriptor
.timestampWrites
.as_ref()
.map(WebGPUConvert::convert),
device_id: self.device.id().0,
})
{
warn!("Failed to send WebGPURequest::BeginComputePass {error:?}");
}
GPUComputePassEncoder::new(
cx,
&*self.global_from_reflector(),
self.droppable.channel.clone(),
self,
WebGPUComputePass(compute_pass_id),
descriptor.parent.label.clone(),
)
}
fn BeginRenderPass(
&self,
cx: &mut JSContext,
descriptor: &GPURenderPassDescriptor<D>,
) -> Fallible<DomRoot<GPURenderPassEncoder<D>>> {
let depth_stencil_attachment =
descriptor
.depthStencilAttachment
.as_ref()
.map(|ds| RenderPassDepthStencilAttachment {
depth: PassChannel {
load_op: ds
.depthLoadOp
.as_ref()
.map(|l| convert_load_op(l, ds.depthClearValue.map(|v| *v))),
store_op: ds.depthStoreOp.as_ref().map(WebGPUConvert::convert),
read_only: ds.depthReadOnly,
},
stencil: PassChannel {
load_op: ds
.stencilLoadOp
.as_ref()
.map(|l| convert_load_op(l, Some(ds.stencilClearValue))),
store_op: ds.stencilStoreOp.as_ref().map(WebGPUConvert::convert),
read_only: ds.stencilReadOnly,
},
view: convert_texture_for_wgpu_with_cx(cx, &ds.view).0,
});
let color_attachments = descriptor
.colorAttachments
.iter()
.map(|color| -> Fallible<_> {
Ok(Some(RenderPassColorAttachment {
resolve_target: color
.resolveTarget
.as_ref()
.map(|t| convert_texture_for_wgpu_with_cx(cx, t).0),
load_op: convert_load_op(
&color.loadOp,
color
.clearValue
.as_ref()
.map(|color| (color).try_convert())
.transpose()?
.unwrap_or_default(),
),
store_op: color.storeOp.convert(),
view: convert_texture_for_wgpu_with_cx(cx, &color.view).0,
depth_slice: None,
}))
})
.collect::<Fallible<Vec<_>>>()?;
let render_pass_id = self
.global_from_reflector()
.global_wgpu_id_hub()
.create_render_pass_id();
if let Err(error) = self
.droppable
.channel
.0
.send(WebGPURequest::BeginRenderPass {
command_encoder_id: self.id().0,
render_pass_id,
label: (&descriptor.parent).convert(),
depth_stencil_attachment,
color_attachments,
timestamp_writes: descriptor
.timestampWrites
.as_ref()
.map(WebGPUConvert::convert),
device_id: self.device.id().0,
})
{
warn!("Failed to send WebGPURequest::BeginRenderPass {error:?}");
}
Ok(GPURenderPassEncoder::new(
cx,
&*self.global_from_reflector(),
self.droppable.channel.clone(),
WebGPURenderPass(render_pass_id),
self,
descriptor.parent.label.clone(),
))
}
fn CopyBufferToBuffer(
&self,
source: &GPUBuffer<D>,
source_offset: GPUSize64,
destination: &GPUBuffer<D>,
destination_offset: GPUSize64,
size: GPUSize64,
) {
self.send_command(CommandEncoderCommand::CopyBufferToBuffer {
source: source.id().0,
source_offset,
destination: destination.id().0,
destination_offset,
size: Some(size),
});
}
fn CopyBufferToTexture(
&self,
source: &GPUTexelCopyBufferInfo<D>,
destination: &GPUTexelCopyTextureInfo<D>,
copy_size: GPUExtent3D,
) -> Fallible<()> {
self.send_command(CommandEncoderCommand::CopyBufferToTexture {
source: source.convert(),
destination: destination.try_convert()?,
copy_size: (©_size).try_convert()?,
});
Ok(())
}
fn CopyTextureToBuffer(
&self,
source: &GPUTexelCopyTextureInfo<D>,
destination: &GPUTexelCopyBufferInfo<D>,
copy_size: GPUExtent3D,
) -> Fallible<()> {
self.send_command(CommandEncoderCommand::CopyTextureToBuffer {
source: source.try_convert()?,
destination: destination.convert(),
copy_size: (©_size).try_convert()?,
});
Ok(())
}
fn CopyTextureToTexture(
&self,
source: &GPUTexelCopyTextureInfo<D>,
destination: &GPUTexelCopyTextureInfo<D>,
copy_size: GPUExtent3D,
) -> Fallible<()> {
self.send_command(CommandEncoderCommand::CopyTextureToTexture {
source: source.try_convert()?,
destination: destination.try_convert()?,
copy_size: (©_size).try_convert()?,
});
Ok(())
}
fn Finish(
&self,
cx: &mut JSContext,
descriptor: &GPUCommandBufferDescriptor,
) -> DomRoot<GPUCommandBuffer<D>> {
let command_buffer_id = self
.global_from_reflector()
.global_wgpu_id_hub()
.create_command_buffer_id();
self.droppable
.channel
.0
.send(WebGPURequest::CommandEncoderFinish {
command_encoder_id: self.droppable.encoder.0,
device_id: self.device.id().0,
desc: CommandBufferDescriptor {
label: (&descriptor.parent).convert(),
},
command_buffer_id,
})
.expect("Failed to send Finish");
let buffer = WebGPUCommandBuffer(command_buffer_id);
GPUCommandBuffer::new(
cx,
&*self.global_from_reflector(),
self.droppable.channel.clone(),
buffer,
descriptor.parent.label.clone(),
)
}
fn PushDebugGroup(&self, group_label: USVString) {
self.send_command(CommandEncoderCommand::DebugCommand(
DebugCommand::PushDebugGroup(group_label.to_string()),
));
}
fn PopDebugGroup(&self) {
self.send_command(CommandEncoderCommand::DebugCommand(
DebugCommand::PopDebugGroup,
));
}
fn InsertDebugMarker(&self, marker_label: USVString) {
self.send_command(CommandEncoderCommand::DebugCommand(
DebugCommand::InsertDebugMarker(marker_label.to_string()),
));
}
fn ResolveQuerySet(
&self,
query_set: &GPUQuerySet<D>,
first_query: u32,
query_count: u32,
destination: &GPUBuffer<D>,
destination_offset: u64,
) {
self.send_command(CommandEncoderCommand::ResolveQuerySet {
query_set: query_set.id().0,
first_query,
query_count,
destination: destination.id().0,
destination_offset,
});
}
}