From 82245e5f7722a0f05d9f31c3699f1cf417fa13fb Mon Sep 17 00:00:00 2001 From: Jonathan Woollett-Light Date: Wed, 19 Aug 2020 18:16:10 +0100 Subject: [PATCH] Added some explanatory comments to hello-compute example --- examples/hello-compute/main.rs | 57 +++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/examples/hello-compute/main.rs b/examples/hello-compute/main.rs index b63ae16f4..60e03c1e9 100644 --- a/examples/hello-compute/main.rs +++ b/examples/hello-compute/main.rs @@ -20,10 +20,11 @@ async fn run() { } async fn execute_gpu(numbers: Vec) -> Vec { - let slice_size = numbers.len() * std::mem::size_of::(); - let size = slice_size as wgpu::BufferAddress; - + // Instantiates instance of WebGPU + // 'wgpu::BackendBit::PRIMARY' selects one of 'Vulkan + Metal + DX12 + Browser WebGPU' as the backend let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); + + // `request_adapter` instantiates the general connection to the GPU let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::Default, @@ -32,6 +33,8 @@ async fn execute_gpu(numbers: Vec) -> Vec { .await .unwrap(); + // `request_device` instantiates the feature specific connection to the GPU, defining some parameters, + // `features` being the available features. let (device, queue) = adapter .request_device( &wgpu::DeviceDescriptor { @@ -44,8 +47,17 @@ async fn execute_gpu(numbers: Vec) -> Vec { .await .unwrap(); + // Loads the shader from the SPIR-V file.arrayvec let cs_module = device.create_shader_module(wgpu::include_spirv!("shader.comp.spv")); + // Gets the size in bytes of the buffer. + let slice_size = numbers.len() * std::mem::size_of::(); + let size = slice_size as wgpu::BufferAddress; + + // Instantiates buffer without data. + // `usage` of buffer specifies how it can be used: + // `BufferUsage::MAP_READ` allows it to be read (outside the shader). + // `BufferUsage::COPY_DST` allows it to be the destination of the copy. let staging_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: None, size, @@ -53,6 +65,11 @@ async fn execute_gpu(numbers: Vec) -> Vec { mapped_at_creation: false, }); + // Instantiates buffer with data (`numbers`). + // Usage allowing the buffer to be: + // A storage buffer (can be bound within a bind group and thus available to a shader). + // The destination of a copy. + // The source of a copy. let storage_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Storage Buffer"), contents: bytemuck::cast_slice(&numbers), @@ -61,20 +78,26 @@ async fn execute_gpu(numbers: Vec) -> Vec { | wgpu::BufferUsage::COPY_SRC, }); + // A bind group defines how buffers are accessed by shaders. + // It is to WebGPU what a descriptor set is to Vulkan. + // `binding` here refers to the `binding` of a buffer in the shader (`layout(set = 0, binding = 0) buffer`). + + // Here we specifiy the layout of the bind group. let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &[wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStage::COMPUTE, + binding: 0, // The location + visibility: wgpu::ShaderStage::COMPUTE, // Which shader type in the pipeline this buffer is available to. ty: wgpu::BindingType::StorageBuffer { dynamic: false, - readonly: false, + readonly: false, // Specifies if the buffer can only be read within the shader min_binding_size: wgpu::BufferSize::new(4), }, count: None, }], }); + // Instantiates the bind group, once again specifying the binding of buffers. let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &bind_group_layout, @@ -84,12 +107,16 @@ async fn execute_gpu(numbers: Vec) -> Vec { }], }); + // A pipeline specifices the operation of a shader + + // Here we specifiy the layout of the pipeline. let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[&bind_group_layout], push_constant_ranges: &[], }); + // Instantiates the pipeline. let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: None, layout: Some(&pipeline_layout), @@ -99,20 +126,26 @@ async fn execute_gpu(numbers: Vec) -> Vec { }, }); + // A command encoder executes one or many pipelines. + // It is to WebGPU what a command buffer is to Vulkan. let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); { let mut cpass = encoder.begin_compute_pass(); cpass.set_pipeline(&compute_pipeline); cpass.set_bind_group(0, &bind_group, &[]); - cpass.dispatch(numbers.len() as u32, 1, 1); + cpass.dispatch(numbers.len() as u32, 1, 1); // Number of cells to run, the (x,y,z) size of item being processed } + // Sets adds copy operation to command encoder. + // Will copy data from storage buffer on GPU to staging buffer on CPU. encoder.copy_buffer_to_buffer(&storage_buffer, 0, &staging_buffer, 0, size); + // Submits command encoder for processing queue.submit(Some(encoder.finish())); // Note that we're not calling `.await` here. let buffer_slice = staging_buffer.slice(..); + // Gets the future representing when `staging_buffer` can be read from let buffer_future = buffer_slice.map_async(wgpu::MapMode::Read); // Poll the device in a blocking manner so that our future resolves. @@ -120,8 +153,11 @@ async fn execute_gpu(numbers: Vec) -> Vec { // be called in an event loop or on another thread. device.poll(wgpu::Maintain::Wait); + // Awaits until `buffer_future` can be read from if let Ok(()) = buffer_future.await { + // Gets contents of buffer let data = buffer_slice.get_mapped_range(); + // Since contents are got in bytes, this converts these bytes back to u32 let result = data .chunks_exact(4) .map(|b| u32::from_ne_bytes(b.try_into().unwrap())) @@ -130,8 +166,13 @@ async fn execute_gpu(numbers: Vec) -> Vec { // With the current interface, we have to make sure all mapped views are // dropped before we unmap the buffer. drop(data); - staging_buffer.unmap(); + staging_buffer.unmap(); // Unmaps buffer from memory + // If you are familiar with C++ these 2 lines can be thought of similarly to: + // delete myPointer; + // myPointer = NULL; + // It effectively frees the memory + // Returns data from buffer result } else { panic!("failed to run compute on gpu!")