From d7b745e5af2251709e831b403ce720af9782064e Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Tue, 10 Nov 2020 23:35:34 -0330 Subject: [PATCH 1/4] Update web bindings --- Cargo.toml | 5 ++ src/backend/direct.rs | 49 ++++++----- src/backend/mod.rs | 4 +- src/backend/web.rs | 194 +++++++++++++++++++++++------------------- src/lib.rs | 63 +++++++------- src/util/mod.rs | 40 ++------- 6 files changed, 180 insertions(+), 175 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 54bd94c0f..811515dbc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,6 +97,10 @@ test = true #gfx-backend-dx12 = { version = "0.6", path = "../gfx/src/backend/dx12" } #gfx-backend-dx11 = { version = "0.6", path = "../gfx/src/backend/dx11" } #gfx-backend-metal = { version = "0.6", path = "../gfx/src/backend/metal" } +wasm-bindgen = { git = "https://github.com/rustwasm/wasm-bindgen", rev = "316c5a70fdc4a052fb65ef82bf02d52107b5671b" } +wasm-bindgen-futures = { git = "https://github.com/rustwasm/wasm-bindgen", rev = "316c5a70fdc4a052fb65ef82bf02d52107b5671b" } +web-sys = { git = "https://github.com/rustwasm/wasm-bindgen", rev = "316c5a70fdc4a052fb65ef82bf02d52107b5671b" } +js-sys = { git = "https://github.com/rustwasm/wasm-bindgen", rev = "316c5a70fdc4a052fb65ef82bf02d52107b5671b" } [target.'cfg(target_os = "macos")'.dependencies] objc = "0.2.7" @@ -149,6 +153,7 @@ web-sys = { version = "=0.3.45", features = [ "GpuInputStepMode", "GpuLimits", "GpuLoadOp", + "GpuMapMode", "GpuOrigin3dDict", "GpuPipelineLayout", "GpuPipelineLayoutDescriptor", diff --git a/src/backend/direct.rs b/src/backend/direct.rs index 721ac6de5..7aac3823e 100644 --- a/src/backend/direct.rs +++ b/src/backend/direct.rs @@ -1216,7 +1216,7 @@ impl crate::Context for Context { &self, buffer: &Self::BufferId, sub_range: Range, - ) -> &[u8] { + ) -> BufferMappedRange { let size = sub_range.end - sub_range.start; let global = &self.0; match wgc::gfx_select!(buffer.id => global.buffer_get_mapped_range( @@ -1224,28 +1224,15 @@ impl crate::Context for Context { sub_range.start, wgt::BufferSize::new(size) )) { - Ok(ptr) => unsafe { slice::from_raw_parts(ptr, size as usize) }, + Ok(ptr) => BufferMappedRange { + ptr, + size: size as usize, + phantom: PhantomData, + }, Err(err) => self.handle_error_fatal(err, "Buffer::get_mapped_range"), } } - fn buffer_get_mapped_range_mut( - &self, - buffer: &Self::BufferId, - sub_range: Range, - ) -> &mut [u8] { - let size = sub_range.end - sub_range.start; - let global = &self.0; - match wgc::gfx_select!(buffer.id => global.buffer_get_mapped_range( - buffer.id, - sub_range.start, - wgt::BufferSize::new(size) - )) { - Ok(ptr) => unsafe { slice::from_raw_parts_mut(ptr, size as usize) }, - Err(err) => self.handle_error_fatal(err, "Buffer::get_mapped_range_mut"), - } - } - fn buffer_unmap(&self, buffer: &Self::BufferId) { let global = &self.0; match wgc::gfx_select!(buffer.id => global.buffer_unmap(buffer.id)) { @@ -1740,3 +1727,27 @@ fn default_error_handler(err: crate::Error) { panic!("Handling wgpu errors as fatal by default"); } + +#[derive(Debug)] +pub struct BufferMappedRange<'a> { + ptr: *mut u8, + size: usize, + phantom: PhantomData<&'a ()>, +} + +impl<'a> crate::BufferMappedRangeSlice for BufferMappedRange<'a> { + fn slice(&self) -> &[u8] { + unsafe { slice::from_raw_parts(self.ptr, self.size) } + } + + fn slice_mut(&mut self) -> &mut [u8] { + unsafe { slice::from_raw_parts_mut(self.ptr, self.size) } + } +} + +impl<'a> Drop for BufferMappedRange<'a> { + fn drop(&mut self) { + // Intentionally left blank so that `BufferMappedRange` still + // implements `Drop`, to match the web backend + } +} diff --git a/src/backend/mod.rs b/src/backend/mod.rs index f8a3ec562..c9584c2f7 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -1,7 +1,7 @@ #[cfg(target_arch = "wasm32")] mod web; #[cfg(target_arch = "wasm32")] -pub(crate) use web::Context; +pub(crate) use web::{Context, BufferMappedRange}; #[cfg(not(target_arch = "wasm32"))] mod direct; @@ -9,7 +9,7 @@ mod direct; mod error; #[cfg(not(target_arch = "wasm32"))] -pub(crate) use direct::Context; +pub(crate) use direct::{Context, BufferMappedRange}; #[cfg(not(target_arch = "wasm32"))] mod native_gpu_future; diff --git a/src/backend/web.rs b/src/backend/web.rs index b9be65c9c..be6d24d5a 100644 --- a/src/backend/web.rs +++ b/src/backend/web.rs @@ -42,29 +42,6 @@ impl fmt::Debug for Context { } } -impl Context { - pub fn create_buffer_init_polyfill( - device: &Sendable, - desc: &BufferDescriptor<'_>, - contents: &[u8], - ) -> Sendable { - // Emulate buffer mapping with the old API. This is a temporary - // polyfill until the new buffer mapping API is available on gecko. - let mut buffer_desc = - web_sys::GpuBufferDescriptor::new(desc.size as f64, desc.usage.bits()); - if let Some(label) = desc.label { - buffer_desc.label(label); - } - let buffer = device.0.create_buffer(&buffer_desc); - let data = js_sys::Uint8Array::from(contents).buffer(); - device - .0 - .default_queue() - .write_buffer_with_u32(&buffer, 0, &data); - Sendable(buffer) - } -} - #[derive(Debug)] pub(crate) struct ComputePass(web_sys::GpuComputePassEncoder); #[derive(Debug)] @@ -331,7 +308,7 @@ fn map_texture_format(texture_format: wgt::TextureFormat) -> web_sys::GpuTexture TextureFormat::Bgra8Unorm => tf::Bgra8unorm, TextureFormat::Bgra8UnormSrgb => tf::Bgra8unormSrgb, TextureFormat::Rgb10a2Unorm => tf::Rgb10a2unorm, - TextureFormat::Rg11b10Float => tf::Rg11b10float, + TextureFormat::Rg11b10Float => tf::Rg11b10ufloat, TextureFormat::Rg32Uint => tf::Rg32uint, TextureFormat::Rg32Sint => tf::Rg32sint, TextureFormat::Rg32Float => tf::Rg32float, @@ -355,9 +332,7 @@ fn map_texture_component_type( wgt::TextureComponentType::Float => web_sys::GpuTextureComponentType::Float, wgt::TextureComponentType::Sint => web_sys::GpuTextureComponentType::Sint, wgt::TextureComponentType::Uint => web_sys::GpuTextureComponentType::Uint, - wgt::TextureComponentType::DepthComparison => { - panic!("depth-comparison is not supported here yet") - } + wgt::TextureComponentType::DepthComparison => web_sys::GpuTextureComponentType::DepthComparison, } } @@ -583,7 +558,11 @@ fn map_vertex_state_descriptor( } fn map_extent_3d(extent: wgt::Extent3d) -> web_sys::GpuExtent3dDict { - web_sys::GpuExtent3dDict::new(extent.depth, extent.height, extent.width) + let mut mapped = web_sys::GpuExtent3dDict::new(); + mapped.depth(extent.depth); + mapped.height(extent.height); + mapped.width(extent.height); + mapped } fn map_origin_3d(origin: wgt::Origin3d) -> web_sys::GpuOrigin3dDict { @@ -617,7 +596,8 @@ fn map_texture_view_dimension( } fn map_buffer_copy_view(view: crate::BufferCopyView) -> web_sys::GpuBufferCopyView { - let mut mapped = web_sys::GpuBufferCopyView::new(view.layout.bytes_per_row, &view.buffer.id.0); + let mut mapped = web_sys::GpuBufferCopyView::new(&view.buffer.id.0); + mapped.bytes_per_row(view.layout.bytes_per_row); mapped.rows_per_image(view.layout.rows_per_image); mapped.offset(view.layout.offset as f64); mapped @@ -666,6 +646,13 @@ fn map_store_op(store: bool) -> web_sys::GpuStoreOp { } } +fn map_map_mode(mode: crate::MapMode) -> u32 { + match mode { + crate::MapMode::Read => web_sys::GpuMapMode::READ, + crate::MapMode::Write => web_sys::GpuMapMode::WRITE, + } +} + type JsFutureResult = Result; type FutureMap = futures::future::Map T>; @@ -688,35 +675,13 @@ fn future_request_device( .map_err(|_| crate::RequestDeviceError) } -pub(crate) struct MapFuture { - child: wasm_bindgen_futures::JsFuture, - buffer: Option, - marker: PhantomData, -} -impl Unpin for MapFuture {} -//type MapData = (web_sys::GpuBuffer, Vec); - -impl std::future::Future for MapFuture<()> { - type Output = Result<(), crate::BufferAsyncError>; - fn poll( - mut self: std::pin::Pin<&mut Self>, - context: &mut std::task::Context, - ) -> std::task::Poll { - std::future::Future::poll( - std::pin::Pin::new(&mut self.as_mut().get_mut().child), - context, - ) - .map(|result| { - let _buffer = self.buffer.take().unwrap(); - result - .map(|js_value| { - let array_buffer = js_sys::ArrayBuffer::from(js_value); - let _view = js_sys::Uint8Array::new(&array_buffer); - () //TODO - }) - .map_err(|_| crate::BufferAsyncError) - }) - } +fn future_map_async( + result: JsFutureResult, +) -> Result<(), crate::BufferAsyncError> +{ + result + .map(|_| ()) + .map_err(|_| crate::BufferAsyncError) } impl crate::Context for Context { @@ -748,7 +713,7 @@ impl crate::Context for Context { type RequestDeviceFuture = MakeSendFuture< FutureMap>, >; - type MapAsyncFuture = MakeSendFuture>; + type MapAsyncFuture = MakeSendFuture>>; fn init(_backends: wgt::BackendBit) -> Self { Context(web_sys::window().unwrap().navigator().gpu()) @@ -893,6 +858,7 @@ impl crate::Context for Context { BindingType::StorageBuffer { readonly: true, .. } => bt::ReadonlyStorageBuffer, BindingType::Sampler { comparison: false } => bt::Sampler, BindingType::Sampler { .. } => bt::ComparisonSampler, + BindingType::SampledTexture { multisampled: true, .. } => bt::MultisampledTexture, BindingType::SampledTexture { .. } => bt::SampledTexture, BindingType::StorageTexture { readonly: true, .. } => { bt::ReadonlyStorageTexture @@ -921,12 +887,10 @@ impl crate::Context for Context { if let BindingType::SampledTexture { component_type, - multisampled, .. } = bind.ty { mapped_entry.texture_component_type(map_texture_component_type(component_type)); - mapped_entry.multisampled(multisampled); } match bind.ty { @@ -1096,6 +1060,7 @@ impl crate::Context for Context { ) -> Self::BufferId { let mut mapped_desc = web_sys::GpuBufferDescriptor::new(desc.size as f64, desc.usage.bits()); + mapped_desc.mapped_at_creation(desc.mapped_at_creation); if let Some(ref label) = desc.label { mapped_desc.label(label); } @@ -1182,32 +1147,37 @@ impl crate::Context for Context { fn buffer_map_async( &self, - _buffer: &Self::BufferId, - _mode: crate::MapMode, - _range: Range, + buffer: &Self::BufferId, + mode: crate::MapMode, + range: Range, ) -> Self::MapAsyncFuture { - unimplemented!() - //MakeSendFuture(MapFuture { - // child: wasm_bindgen_futures::JsFuture::from(buffer.0.map_async()), - // buffer: Some(buffer.0.clone()), - // marker: PhantomData, - //}) + let map_promise = buffer.0.map_async_with_f64_and_f64( + map_map_mode(mode), + range.start as f64, + (range.end - range.start) as f64, + ); + + MakeSendFuture( + wasm_bindgen_futures::JsFuture::from(map_promise).map(future_map_async), + ) } fn buffer_get_mapped_range( &self, - _buffer: &Self::BufferId, - _sub_range: Range, - ) -> &[u8] { - unimplemented!() - } - - fn buffer_get_mapped_range_mut( - &self, - _buffer: &Self::BufferId, - _sub_range: Range, - ) -> &mut [u8] { - unimplemented!() + buffer: &Self::BufferId, + sub_range: Range, + ) -> BufferMappedRange { + let array_buffer = buffer.0.get_mapped_range_with_f64_and_f64( + sub_range.start as f64, + (sub_range.end - sub_range.start) as f64, + ); + let actual_mapping = js_sys::Uint8Array::new(&array_buffer); + let temporary_mapping = actual_mapping.to_vec(); + BufferMappedRange { + actual_mapping, + temporary_mapping, + phantom: PhantomData, + } } fn buffer_unmap(&self, buffer: &Self::BufferId) { @@ -1499,13 +1469,13 @@ impl crate::Context for Context { Sendable(encoder.finish_with_descriptor(&mapped_desc)) } - fn command_encoder_insert_debug_marker(&self, encoder: &Self::CommandEncoderId, label: &str) { + fn command_encoder_insert_debug_marker(&self, _encoder: &Self::CommandEncoderId, _label: &str) { // TODO } - fn command_encoder_push_debug_group(&self, encoder: &Self::CommandEncoderId, label: &str) { + fn command_encoder_push_debug_group(&self, _encoder: &Self::CommandEncoderId, _label: &str) { // TODO } - fn command_encoder_pop_debug_group(&self, encoder: &Self::CommandEncoderId) { + fn command_encoder_pop_debug_group(&self, _encoder: &Self::CommandEncoderId) { // TODO } @@ -1524,7 +1494,16 @@ impl crate::Context for Context { offset: wgt::BufferAddress, data: &[u8], ) { - queue.0.write_buffer_with_f64_and_f64_and_f64( + /* Skip the copy once gecko allows BufferSource instead of ArrayBuffer + queue.0.write_buffer_with_f64_and_u8_array_and_f64_and_f64( + &buffer.0, + offset as f64, + data, + 0f64, + data.len() as f64, + ); + */ + queue.0.write_buffer_with_f64_and_buffer_source_and_f64_and_f64( &buffer.0, offset as f64, &js_sys::Uint8Array::from(data).buffer(), @@ -1541,11 +1520,20 @@ impl crate::Context for Context { data_layout: wgt::TextureDataLayout, size: wgt::Extent3d, ) { - let mut mapped_data_layout = web_sys::GpuTextureDataLayout::new(data_layout.bytes_per_row); + let mut mapped_data_layout = web_sys::GpuTextureDataLayout::new(); + mapped_data_layout.bytes_per_row(data_layout.bytes_per_row); mapped_data_layout.rows_per_image(data_layout.rows_per_image); mapped_data_layout.offset(data_layout.offset as f64); - queue.0.write_texture_with_gpu_extent_3d_dict( + /* Skip the copy once gecko allows BufferSource instead of ArrayBuffer + queue.0.write_texture_with_u8_array_and_gpu_extent_3d_dict( + &map_texture_copy_view(texture), + data, + &mapped_data_layout, + &map_extent_3d(size), + ); + */ + queue.0.write_texture_with_buffer_source_and_gpu_extent_3d_dict( &map_texture_copy_view(texture), &js_sys::Uint8Array::from(data).buffer(), &mapped_data_layout, @@ -1565,3 +1553,33 @@ impl crate::Context for Context { } pub(crate) type SwapChainOutputDetail = (); + +#[derive(Debug)] +pub struct BufferMappedRange<'a> { + actual_mapping: js_sys::Uint8Array, + temporary_mapping: Vec, + phantom: PhantomData<&'a ()>, +} + +impl<'a> crate::BufferMappedRangeSlice for BufferMappedRange<'a> { + fn slice(&self) -> &[u8] { + &self.temporary_mapping + } + + fn slice_mut(&mut self) -> &mut [u8] { + &mut self.temporary_mapping + } +} + +impl<'a> Drop for BufferMappedRange<'a> { + fn drop(&mut self) { + // Copy from the temporary mapping back into the array buffer that was + // originally provided by the browser + let temporary_mapping_slice = self.temporary_mapping.as_slice(); + unsafe { + // Note: no allocations can happen between `view` and `set`, or this + // will break + self.actual_mapping.set(&js_sys::Uint8Array::view(temporary_mapping_slice), 0); + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 154d6269d..f8fe7088e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -45,7 +45,7 @@ pub use wgt::{ COPY_BUFFER_ALIGNMENT, COPY_BYTES_PER_ROW_ALIGNMENT, PUSH_CONSTANT_ALIGNMENT, }; -use backend::Context as C; +use backend::{Context as C, BufferMappedRange}; trait ComputePassInner { fn set_pipeline(&mut self, pipeline: &Ctx::ComputePipelineId); @@ -274,18 +274,11 @@ trait Context: Debug + Send + Sized + Sync { mode: MapMode, range: Range, ) -> Self::MapAsyncFuture; - //TODO: we might be able to merge these, depending on how Web backend - // turns out to be implemented. fn buffer_get_mapped_range( &self, buffer: &Self::BufferId, sub_range: Range, - ) -> &[u8]; - fn buffer_get_mapped_range_mut( - &self, - buffer: &Self::BufferId, - sub_range: Range, - ) -> &mut [u8]; + ) -> BufferMappedRange; fn buffer_unmap(&self, buffer: &Self::BufferId); fn swap_chain_get_current_texture_view( &self, @@ -466,9 +459,8 @@ pub enum Maintain { Poll, } -/// The main purpose of this struct is to resolve mapped ranges -/// (convert sizes to end points), and to ensure that the sub-ranges -/// don't intersect. +/// The main purpose of this struct is to resolve mapped ranges (convert sizes +/// to end points), and to ensure that the sub-ranges don't intersect. #[derive(Debug)] struct MapContext { total_size: BufferAddress, @@ -1602,18 +1594,23 @@ fn range_to_offset_size>( (offset, size) } +trait BufferMappedRangeSlice { + fn slice(&self) -> &[u8]; + fn slice_mut(&mut self) -> &mut [u8]; +} + /// Read only view into a mapped buffer. #[derive(Debug)] pub struct BufferView<'a> { slice: BufferSlice<'a>, - data: &'a [u8], + data: BufferMappedRange<'a>, } /// Write only view into mapped buffer. #[derive(Debug)] pub struct BufferViewMut<'a> { slice: BufferSlice<'a>, - data: &'a mut [u8], + data: BufferMappedRange<'a>, readable: bool, } @@ -1621,7 +1618,7 @@ impl std::ops::Deref for BufferView<'_> { type Target = [u8]; fn deref(&self) -> &[u8] { - self.data + self.data.slice() } } @@ -1634,25 +1631,25 @@ impl std::ops::Deref for BufferViewMut<'_> { "Attempting to read a write-only mapping for buffer {:?}", self.slice.buffer.id ); - self.data + self.data.slice() } } impl std::ops::DerefMut for BufferViewMut<'_> { fn deref_mut(&mut self) -> &mut Self::Target { - self.data + self.data.slice_mut() } } impl AsRef<[u8]> for BufferView<'_> { fn as_ref(&self) -> &[u8] { - self.data + self.data.slice() } } impl AsMut<[u8]> for BufferViewMut<'_> { fn as_mut(&mut self) -> &mut [u8] { - self.data + self.data.slice_mut() } } @@ -1724,21 +1721,19 @@ impl<'a> BufferSlice<'a> { &self, mode: MapMode, ) -> impl Future> + Send { - let end = { - let mut mc = self.buffer.map_context.lock(); - assert_eq!( - mc.initial_range, - 0..0, - "Buffer {:?} is already mapped", - self.buffer.id - ); - let end = match self.size { - Some(s) => self.offset + s.get(), - None => mc.total_size, - }; - mc.initial_range = self.offset..end; - end + let mut mc = self.buffer.map_context.lock(); + assert_eq!( + mc.initial_range, + 0..0, + "Buffer {:?} is already mapped", + self.buffer.id + ); + let end = match self.size { + Some(s) => self.offset + s.get(), + None => mc.total_size, }; + mc.initial_range = self.offset..end; + Context::buffer_map_async( &*self.buffer.context, &self.buffer.id, @@ -1763,7 +1758,7 @@ impl<'a> BufferSlice<'a> { /// through [`BufferDescriptor::mapped_at_creation`] or [`BufferSlice::map_async`], will panic. pub fn get_mapped_range_mut(&self) -> BufferViewMut<'a> { let end = self.buffer.map_context.lock().add(self.offset, self.size); - let data = Context::buffer_get_mapped_range_mut( + let data = Context::buffer_get_mapped_range( &*self.buffer.context, &self.buffer.id, self.offset..end, diff --git a/src/util/mod.rs b/src/util/mod.rs index 9613afb60..84dfa3f80 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -9,7 +9,6 @@ use std::{ }; pub use belt::StagingBelt; -use std::sync::Arc; /// Treat the given byte slice as a SPIR-V module. /// @@ -75,39 +74,16 @@ impl DeviceExt for crate::Device { map_context.initial_range = 0..padded_size; - #[cfg(target_arch = "wasm32")] - let buffer = crate::Buffer { - context: Arc::clone(&self.context), - id: crate::backend::Context::create_buffer_init_polyfill( - &self.id, - &wgt_descriptor, - descriptor.contents, - ), - map_context: parking_lot::Mutex::new(map_context), - usage: descriptor.usage, - }; - #[cfg(not(target_arch = "wasm32"))] - let buffer = { - let buffer = crate::Buffer { - context: Arc::clone(&self.context), - id: crate::Context::device_create_buffer(&*self.context, &self.id, &wgt_descriptor), - map_context: parking_lot::Mutex::new(map_context), - usage: descriptor.usage, - }; - - let range = crate::Context::buffer_get_mapped_range_mut( - &*self.context, - &buffer.id, - 0..padded_size, - ); - range[0..unpadded_size as usize].copy_from_slice(descriptor.contents); + let buffer = self.create_buffer(&wgt_descriptor); + { + let mut slice = buffer.slice(..).get_mapped_range_mut(); + slice[0..unpadded_size as usize].copy_from_slice(descriptor.contents); + for i in unpadded_size..padded_size { - range[i as usize] = 0; + slice[i as usize] = 0; } - - buffer.unmap(); - buffer - }; + } + buffer.unmap(); buffer } } From 38d0d37dbf22a0b7a91261260a28e7bb0182b50a Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Wed, 11 Nov 2020 00:42:39 -0330 Subject: [PATCH 2/4] Add render bundles to web backend --- Cargo.toml | 4 + src/backend/web.rs | 181 +++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 170 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 811515dbc..b62fcf8d9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -162,6 +162,10 @@ web-sys = { version = "=0.3.45", features = [ "GpuProgrammableStageDescriptor", "GpuQueue", "GpuRasterizationStateDescriptor", + "GpuRenderBundle", + "GpuRenderBundleDescriptor", + "GpuRenderBundleEncoder", + "GpuRenderBundleEncoderDescriptor", "GpuRenderPassColorAttachmentDescriptor", "GpuRenderPassDepthStencilAttachmentDescriptor", "GpuRenderPassDescriptor", diff --git a/src/backend/web.rs b/src/backend/web.rs index be6d24d5a..795710eec 100644 --- a/src/backend/web.rs +++ b/src/backend/web.rs @@ -46,6 +46,8 @@ impl fmt::Debug for Context { pub(crate) struct ComputePass(web_sys::GpuComputePassEncoder); #[derive(Debug)] pub(crate) struct RenderPass(web_sys::GpuRenderPassEncoder); +#[derive(Debug)] +pub(crate) struct RenderBundleEncoder(web_sys::GpuRenderBundleEncoder); // We need to assert that any future we return is Send to match the native API. // @@ -238,6 +240,130 @@ impl crate::RenderInner for RenderPass { } } +impl crate::RenderInner for RenderBundleEncoder { + fn set_pipeline(&mut self, pipeline: &Sendable) { + self.0.set_pipeline(&pipeline.0); + } + fn set_bind_group( + &mut self, + index: u32, + bind_group: &Sendable, + offsets: &[wgt::DynamicOffset], + ) { + self.0 + .set_bind_group_with_u32_array_and_f64_and_dynamic_offsets_data_length( + index, + &bind_group.0, + offsets, + 0f64, + offsets.len() as u32, + ); + } + fn set_index_buffer( + &mut self, + buffer: &Sendable, + offset: wgt::BufferAddress, + size: Option, + ) { + let mapped_size = match size { + Some(s) => s.get() as f64, + None => 0f64, + }; + self.0 + .set_index_buffer_with_f64_and_f64(&buffer.0, offset as f64, mapped_size); + } + fn set_vertex_buffer( + &mut self, + slot: u32, + buffer: &Sendable, + offset: wgt::BufferAddress, + size: Option, + ) { + let mapped_size = match size { + Some(s) => s.get() as f64, + None => 0f64, + }; + self.0 + .set_vertex_buffer_with_f64_and_f64(slot, &buffer.0, offset as f64, mapped_size); + } + fn set_push_constants(&mut self, _stages: wgt::ShaderStage, _offset: u32, _data: &[u8]) { + panic!("PUSH_CONSTANTS feature must be enabled to call multi_draw_indexed_indirect") + } + fn draw(&mut self, vertices: Range, instances: Range) { + self.0 + .draw_with_instance_count_and_first_vertex_and_first_instance( + vertices.end - vertices.start, + instances.end - instances.start, + vertices.start, + instances.start, + ); + } + fn draw_indexed(&mut self, indices: Range, base_vertex: i32, instances: Range) { + self.0 + .draw_indexed_with_instance_count_and_first_index_and_base_vertex_and_first_instance( + indices.end - indices.start, + instances.end - instances.start, + indices.start, + base_vertex, + instances.start, + ); + } + fn draw_indirect( + &mut self, + indirect_buffer: &Sendable, + indirect_offset: wgt::BufferAddress, + ) { + self.0 + .draw_indirect_with_f64(&indirect_buffer.0, indirect_offset as f64); + } + fn draw_indexed_indirect( + &mut self, + indirect_buffer: &Sendable, + indirect_offset: wgt::BufferAddress, + ) { + self.0 + .draw_indexed_indirect_with_f64(&indirect_buffer.0, indirect_offset as f64); + } + fn multi_draw_indirect( + &mut self, + _indirect_buffer: &Sendable, + _indirect_offset: wgt::BufferAddress, + _count: u32, + ) { + panic!("MULTI_DRAW_INDIRECT feature must be enabled to call multi_draw_indirect") + } + fn multi_draw_indexed_indirect( + &mut self, + _indirect_buffer: &Sendable, + _indirect_offset: wgt::BufferAddress, + _count: u32, + ) { + panic!("MULTI_DRAW_INDIRECT feature must be enabled to call multi_draw_indexed_indirect") + } + fn multi_draw_indirect_count( + &mut self, + _indirect_buffer: &Sendable, + _indirect_offset: wgt::BufferAddress, + _count_buffer: &Sendable, + _count_buffer_offset: wgt::BufferAddress, + _max_count: u32, + ) { + panic!( + "MULTI_DRAW_INDIRECT_COUNT feature must be enabled to call multi_draw_indirect_count" + ) + } + fn multi_draw_indexed_indirect_count( + &mut self, + _indirect_buffer: &Sendable, + _indirect_offset: wgt::BufferAddress, + _count_buffer: &Sendable, + _count_buffer_offset: wgt::BufferAddress, + _max_count: u32, + ) { + panic!("MULTI_DRAW_INDIRECT_COUNT feature must be enabled to call multi_draw_indexed_indirect_count") + } +} + impl crate::RenderPassInner for RenderPass { fn set_blend_color(&mut self, color: wgt::Color) { self.0 @@ -274,8 +400,11 @@ impl crate::RenderPassInner for RenderPass { // TODO } - fn execute_bundles<'a, I: Iterator>(&mut self, _render_bundles: I) { - unimplemented!() + fn execute_bundles<'a, I: Iterator>>(&mut self, render_bundles: I) { + let mapped = render_bundles + .map(|bundle| &bundle.0) + .collect::(); + self.0.execute_bundles(&mapped); } } @@ -702,8 +831,8 @@ impl crate::Context for Context { type ComputePassId = ComputePass; type RenderPassId = RenderPass; type CommandBufferId = Sendable; - type RenderBundleEncoderId = RenderPass; //web_sys::GpuRenderBundleEncoder; - type RenderBundleId = (); //web_sys::GpuRenderBundle; + type RenderBundleEncoderId = RenderBundleEncoder; + type RenderBundleId = Sendable; type SurfaceId = Sendable; type SwapChainId = Sendable; @@ -1123,10 +1252,22 @@ impl crate::Context for Context { fn device_create_render_bundle_encoder( &self, - _device: &Self::DeviceId, - _desc: &RenderBundleEncoderDescriptor, + device: &Self::DeviceId, + desc: &RenderBundleEncoderDescriptor, ) -> Self::RenderBundleEncoderId { - unimplemented!() + let mapped_color_formats = desc.color_formats + .iter() + .map(|cf| wasm_bindgen::JsValue::from(map_texture_format(*cf))) + .collect::(); + let mut mapped_desc = web_sys::GpuRenderBundleEncoderDescriptor::new(&mapped_color_formats); + if let Some(ref label) = desc.label { + mapped_desc.label(label); + } + if let Some(dsf) = desc.depth_stencil_format { + mapped_desc.depth_stencil_format(map_texture_format(dsf)); + } + mapped_desc.sample_count(desc.sample_count); + RenderBundleEncoder(device.0.create_render_bundle_encoder(&mapped_desc)) } fn device_drop(&self, _device: &Self::DeviceId) { @@ -1462,11 +1603,14 @@ impl crate::Context for Context { } fn command_encoder_finish(&self, encoder: &Self::CommandEncoderId) -> Self::CommandBufferId { - let mut mapped_desc = web_sys::GpuCommandBufferDescriptor::new(); - if let Some(ref label) = encoder.label() { - mapped_desc.label(label); - } - Sendable(encoder.finish_with_descriptor(&mapped_desc)) + Sendable(match encoder.label() { + Some(ref label) => { + let mut mapped_desc = web_sys::GpuCommandBufferDescriptor::new(); + mapped_desc.label(label); + encoder.finish_with_descriptor(&mapped_desc) + } + None => encoder.finish(), + }) } fn command_encoder_insert_debug_marker(&self, _encoder: &Self::CommandEncoderId, _label: &str) { @@ -1481,10 +1625,17 @@ impl crate::Context for Context { fn render_bundle_encoder_finish( &self, - _encoder: Self::RenderBundleEncoderId, - _desc: &crate::RenderBundleDescriptor, + encoder: Self::RenderBundleEncoderId, + desc: &crate::RenderBundleDescriptor, ) -> Self::RenderBundleId { - unimplemented!() + Sendable(match desc.label { + Some(label) => { + let mut mapped_desc = web_sys::GpuRenderBundleDescriptor::new(); + mapped_desc.label(label); + encoder.0.finish_with_descriptor(&mapped_desc) + } + None => encoder.0.finish(), + }) } fn queue_write_buffer( From 069828d831ac175c032fcdd6dd8b1c1e74f05ab7 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Wed, 11 Nov 2020 00:54:41 -0330 Subject: [PATCH 3/4] Add more labels and debug markers to web backend --- src/backend/web.rs | 77 ++++++++++++++++++++++++++++++---------------- 1 file changed, 50 insertions(+), 27 deletions(-) diff --git a/src/backend/web.rs b/src/backend/web.rs index 795710eec..37872c593 100644 --- a/src/backend/web.rs +++ b/src/backend/web.rs @@ -91,16 +91,16 @@ impl crate::ComputePassInner for ComputePass { panic!("PUSH_CONSTANTS feature must be enabled to call multi_draw_indexed_indirect") } - fn insert_debug_marker(&mut self, _label: &str) { - // TODO + fn insert_debug_marker(&mut self, label: &str) { + self.0.insert_debug_marker(label); } - fn push_debug_group(&mut self, _group_label: &str) { - // TODO + fn push_debug_group(&mut self, group_label: &str) { + self.0.push_debug_group(group_label); } fn pop_debug_group(&mut self) { - // TODO + self.0.pop_debug_group(); } fn dispatch(&mut self, x: u32, y: u32, z: u32) { @@ -388,16 +388,16 @@ impl crate::RenderPassInner for RenderPass { self.0.set_stencil_reference(reference); } - fn insert_debug_marker(&mut self, _label: &str) { - // TODO + fn insert_debug_marker(&mut self, label: &str) { + self.0.insert_debug_marker(label); } - fn push_debug_group(&mut self, _group_label: &str) { - // TODO + fn push_debug_group(&mut self, group_label: &str) { + self.0.push_debug_group(group_label); } fn pop_debug_group(&mut self) { - // TODO + self.0.pop_debug_group(); } fn execute_bundles<'a, I: Iterator>>(&mut self, render_bundles: I) { @@ -1083,7 +1083,7 @@ impl crate::Context for Context { let mut mapped_desc = web_sys::GpuBindGroupDescriptor::new(&mapped_entries, &desc.layout.id.0); - if let Some(ref label) = desc.label { + if let Some(label) = desc.label { mapped_desc.label(label); } Sendable(device.0.create_bind_group(&mapped_desc)) @@ -1099,8 +1099,10 @@ impl crate::Context for Context { .iter() .map(|bgl| bgl.id.0.clone()) .collect::(); - let mapped_desc = web_sys::GpuPipelineLayoutDescriptor::new(&temp_layouts); - // TODO: label + let mut mapped_desc = web_sys::GpuPipelineLayoutDescriptor::new(&temp_layouts); + if let Some(label) = desc.label { + mapped_desc.label(label); + } Sendable(device.0.create_pipeline_layout(&mapped_desc)) } @@ -1175,10 +1177,12 @@ impl crate::Context for Context { ) -> Self::ComputePipelineId { let mapped_compute_stage = map_stage_descriptor(&desc.compute_stage); let mut mapped_desc = web_sys::GpuComputePipelineDescriptor::new(&mapped_compute_stage); - // TODO: label if let Some(layout) = desc.layout { mapped_desc.layout(&layout.id.0); } + if let Some(label) = desc.label { + mapped_desc.label(label); + } Sendable(device.0.create_compute_pipeline(&mapped_desc)) } @@ -1221,7 +1225,6 @@ impl crate::Context for Context { desc: &SamplerDescriptor, ) -> Self::SamplerId { let mut mapped_desc = web_sys::GpuSamplerDescriptor::new(); - // TODO: label mapped_desc.address_mode_u(map_address_mode(desc.address_mode_u)); mapped_desc.address_mode_v(map_address_mode(desc.address_mode_v)); mapped_desc.address_mode_w(map_address_mode(desc.address_mode_w)); @@ -1233,6 +1236,9 @@ impl crate::Context for Context { mapped_desc.mag_filter(map_filter_mode(desc.mag_filter)); mapped_desc.min_filter(map_filter_mode(desc.min_filter)); mapped_desc.mipmap_filter(map_filter_mode(desc.mipmap_filter)); + if let Some(label) = desc.label { + mapped_desc.label(label); + } Sendable(device.0.create_sampler_with_descriptor(&mapped_desc)) } @@ -1371,7 +1377,9 @@ impl crate::Context for Context { if let Some(count) = desc.level_count { mapped.mip_level_count(count.get()); } - // TODO: label + if let Some(label) = desc.label { + mapped.label(label); + } Sendable(texture.0.create_view_with_descriptor(&mapped)) } @@ -1383,45 +1391,58 @@ impl crate::Context for Context { // Dropped automatically } - fn buffer_destroy(&self, _buffer: &Self::BufferId) { - // TODO + fn buffer_destroy(&self, buffer: &Self::BufferId) { + buffer.0.destroy(); } + fn buffer_drop(&self, _buffer: &Self::BufferId) { // Dropped automatically } - fn texture_destroy(&self, _texture: &Self::TextureId) { - // TODO - } + fn texture_drop(&self, _texture: &Self::TextureId) { // Dropped automatically } + + fn texture_destroy(&self, texture: &Self::TextureId) { + texture.0.destroy(); + } + fn texture_view_drop(&self, _texture_view: &Self::TextureViewId) { // Dropped automatically } + fn sampler_drop(&self, _sampler: &Self::SamplerId) { // Dropped automatically } + fn bind_group_drop(&self, _bind_group: &Self::BindGroupId) { // Dropped automatically } + fn bind_group_layout_drop(&self, _bind_group_layout: &Self::BindGroupLayoutId) { // Dropped automatically } + fn pipeline_layout_drop(&self, _pipeline_layout: &Self::PipelineLayoutId) { // Dropped automatically } + fn shader_module_drop(&self, _shader_module: &Self::ShaderModuleId) { // Dropped automatically } + fn command_buffer_drop(&self, _command_buffer: &Self::CommandBufferId) { // Dropped automatically } + fn render_bundle_drop(&self, _render_bundle: &Self::RenderBundleId) { // Dropped automatically } + fn compute_pipeline_drop(&self, _pipeline: &Self::ComputePipelineId) { // Dropped automatically } + fn render_pipeline_drop(&self, _pipeline: &Self::RenderPipelineId) { // Dropped automatically } @@ -1613,14 +1634,16 @@ impl crate::Context for Context { }) } - fn command_encoder_insert_debug_marker(&self, _encoder: &Self::CommandEncoderId, _label: &str) { - // TODO + fn command_encoder_insert_debug_marker(&self, encoder: &Self::CommandEncoderId, label: &str) { + encoder.insert_debug_marker(label); } - fn command_encoder_push_debug_group(&self, _encoder: &Self::CommandEncoderId, _label: &str) { - // TODO + + fn command_encoder_push_debug_group(&self, encoder: &Self::CommandEncoderId, label: &str) { + encoder.push_debug_group(label); } - fn command_encoder_pop_debug_group(&self, _encoder: &Self::CommandEncoderId) { - // TODO + + fn command_encoder_pop_debug_group(&self, encoder: &Self::CommandEncoderId) { + encoder.pop_debug_group(); } fn render_bundle_encoder_finish( From bd23f803d7b8f547a3a4c537659fe6b6a6c6b0c1 Mon Sep 17 00:00:00 2001 From: Joshua Groves Date: Wed, 11 Nov 2020 01:02:07 -0330 Subject: [PATCH 4/4] Add `get_bind_group_layout` to web backend --- src/backend/mod.rs | 4 +-- src/backend/web.rs | 82 ++++++++++++++++++++++++---------------------- src/lib.rs | 2 +- src/util/mod.rs | 2 +- 4 files changed, 47 insertions(+), 43 deletions(-) diff --git a/src/backend/mod.rs b/src/backend/mod.rs index c9584c2f7..e0fbccf78 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -1,7 +1,7 @@ #[cfg(target_arch = "wasm32")] mod web; #[cfg(target_arch = "wasm32")] -pub(crate) use web::{Context, BufferMappedRange}; +pub(crate) use web::{BufferMappedRange, Context}; #[cfg(not(target_arch = "wasm32"))] mod direct; @@ -9,7 +9,7 @@ mod direct; mod error; #[cfg(not(target_arch = "wasm32"))] -pub(crate) use direct::{Context, BufferMappedRange}; +pub(crate) use direct::{BufferMappedRange, Context}; #[cfg(not(target_arch = "wasm32"))] mod native_gpu_future; diff --git a/src/backend/web.rs b/src/backend/web.rs index 37872c593..fdc654066 100644 --- a/src/backend/web.rs +++ b/src/backend/web.rs @@ -87,6 +87,7 @@ impl crate::ComputePassInner for ComputePass { offsets.len() as u32, ); } + fn set_push_constants(&mut self, _offset: u32, _data: &[u8]) { panic!("PUSH_CONSTANTS feature must be enabled to call multi_draw_indexed_indirect") } @@ -400,7 +401,10 @@ impl crate::RenderPassInner for RenderPass { self.0.pop_debug_group(); } - fn execute_bundles<'a, I: Iterator>>(&mut self, render_bundles: I) { + fn execute_bundles<'a, I: Iterator>>( + &mut self, + render_bundles: I, + ) { let mapped = render_bundles .map(|bundle| &bundle.0) .collect::(); @@ -461,7 +465,9 @@ fn map_texture_component_type( wgt::TextureComponentType::Float => web_sys::GpuTextureComponentType::Float, wgt::TextureComponentType::Sint => web_sys::GpuTextureComponentType::Sint, wgt::TextureComponentType::Uint => web_sys::GpuTextureComponentType::Uint, - wgt::TextureComponentType::DepthComparison => web_sys::GpuTextureComponentType::DepthComparison, + wgt::TextureComponentType::DepthComparison => { + web_sys::GpuTextureComponentType::DepthComparison + } } } @@ -804,13 +810,8 @@ fn future_request_device( .map_err(|_| crate::RequestDeviceError) } -fn future_map_async( - result: JsFutureResult, -) -> Result<(), crate::BufferAsyncError> -{ - result - .map(|_| ()) - .map_err(|_| crate::BufferAsyncError) +fn future_map_async(result: JsFutureResult) -> Result<(), crate::BufferAsyncError> { + result.map(|_| ()).map_err(|_| crate::BufferAsyncError) } impl crate::Context for Context { @@ -987,7 +988,9 @@ impl crate::Context for Context { BindingType::StorageBuffer { readonly: true, .. } => bt::ReadonlyStorageBuffer, BindingType::Sampler { comparison: false } => bt::Sampler, BindingType::Sampler { .. } => bt::ComparisonSampler, - BindingType::SampledTexture { multisampled: true, .. } => bt::MultisampledTexture, + BindingType::SampledTexture { + multisampled: true, .. + } => bt::MultisampledTexture, BindingType::SampledTexture { .. } => bt::SampledTexture, BindingType::StorageTexture { readonly: true, .. } => { bt::ReadonlyStorageTexture @@ -1014,11 +1017,7 @@ impl crate::Context for Context { _ => {} } - if let BindingType::SampledTexture { - component_type, - .. - } = bind.ty - { + if let BindingType::SampledTexture { component_type, .. } = bind.ty { mapped_entry.texture_component_type(map_texture_component_type(component_type)); } @@ -1261,7 +1260,8 @@ impl crate::Context for Context { device: &Self::DeviceId, desc: &RenderBundleEncoderDescriptor, ) -> Self::RenderBundleEncoderId { - let mapped_color_formats = desc.color_formats + let mapped_color_formats = desc + .color_formats .iter() .map(|cf| wasm_bindgen::JsValue::from(map_texture_format(*cf))) .collect::(); @@ -1304,9 +1304,7 @@ impl crate::Context for Context { (range.end - range.start) as f64, ); - MakeSendFuture( - wasm_bindgen_futures::JsFuture::from(map_promise).map(future_map_async), - ) + MakeSendFuture(wasm_bindgen_futures::JsFuture::from(map_promise).map(future_map_async)) } fn buffer_get_mapped_range( @@ -1449,17 +1447,18 @@ impl crate::Context for Context { fn compute_pipeline_get_bind_group_layout( &self, - _pipeline: &Self::ComputePipelineId, - _index: u32, + pipeline: &Self::ComputePipelineId, + index: u32, ) -> Self::BindGroupLayoutId { - unimplemented!() + Sendable(pipeline.0.get_bind_group_layout(index)) } + fn render_pipeline_get_bind_group_layout( &self, - _pipeline: &Self::RenderPipelineId, - _index: u32, + pipeline: &Self::RenderPipelineId, + index: u32, ) -> Self::BindGroupLayoutId { - unimplemented!() + Sendable(pipeline.0.get_bind_group_layout(index)) } fn command_encoder_copy_buffer_to_buffer( @@ -1677,13 +1676,15 @@ impl crate::Context for Context { data.len() as f64, ); */ - queue.0.write_buffer_with_f64_and_buffer_source_and_f64_and_f64( - &buffer.0, - offset as f64, - &js_sys::Uint8Array::from(data).buffer(), - 0f64, - data.len() as f64, - ); + queue + .0 + .write_buffer_with_f64_and_buffer_source_and_f64_and_f64( + &buffer.0, + offset as f64, + &js_sys::Uint8Array::from(data).buffer(), + 0f64, + data.len() as f64, + ); } fn queue_write_texture( @@ -1707,12 +1708,14 @@ impl crate::Context for Context { &map_extent_3d(size), ); */ - queue.0.write_texture_with_buffer_source_and_gpu_extent_3d_dict( - &map_texture_copy_view(texture), - &js_sys::Uint8Array::from(data).buffer(), - &mapped_data_layout, - &map_extent_3d(size), - ); + queue + .0 + .write_texture_with_buffer_source_and_gpu_extent_3d_dict( + &map_texture_copy_view(texture), + &js_sys::Uint8Array::from(data).buffer(), + &mapped_data_layout, + &map_extent_3d(size), + ); } fn queue_submit>( @@ -1753,7 +1756,8 @@ impl<'a> Drop for BufferMappedRange<'a> { unsafe { // Note: no allocations can happen between `view` and `set`, or this // will break - self.actual_mapping.set(&js_sys::Uint8Array::view(temporary_mapping_slice), 0); + self.actual_mapping + .set(&js_sys::Uint8Array::view(temporary_mapping_slice), 0); } } } diff --git a/src/lib.rs b/src/lib.rs index f8fe7088e..7cfb3b53e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -45,7 +45,7 @@ pub use wgt::{ COPY_BUFFER_ALIGNMENT, COPY_BYTES_PER_ROW_ALIGNMENT, PUSH_CONSTANT_ALIGNMENT, }; -use backend::{Context as C, BufferMappedRange}; +use backend::{BufferMappedRange, Context as C}; trait ComputePassInner { fn set_pipeline(&mut self, pipeline: &Ctx::ComputePipelineId); diff --git a/src/util/mod.rs b/src/util/mod.rs index 84dfa3f80..6c25d8ed8 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -78,7 +78,7 @@ impl DeviceExt for crate::Device { { let mut slice = buffer.slice(..).get_mapped_range_mut(); slice[0..unpadded_size as usize].copy_from_slice(descriptor.contents); - + for i in unpadded_size..padded_size { slice[i as usize] = 0; }