mirror of
https://github.com/storytold/wgpu.git
synced 2026-11-29 17:44:09 +01:00
Implement bindless buffers on metal (#9081)
This commit is contained in:
1 parent
2374e16ab9
commit
bf5c6cff4e
18 files changed
+1059
-277
No files matched your search
@@ -1246,6 +1246,14 @@ impl super::CapabilitiesQuery {
|
||||
.unwrap_or(MTLArgumentBuffersTier::Tier1)
|
||||
>= MTLArgumentBuffersTier::Tier2,
|
||||
);
|
||||
features.set(
|
||||
F::BUFFER_BINDING_ARRAY,
|
||||
self.msl_version >= MTLLanguageVersion::Version2_0
|
||||
&& self
|
||||
.argument_buffers
|
||||
.unwrap_or(MTLArgumentBuffersTier::Tier1)
|
||||
>= MTLArgumentBuffersTier::Tier2,
|
||||
);
|
||||
features.set(
|
||||
F::STORAGE_RESOURCE_BINDING_ARRAY,
|
||||
self.msl_version >= MTLLanguageVersion::Version3_0
|
||||
|
||||
@@ -350,12 +350,31 @@ impl super::CommandEncoder {
|
||||
}
|
||||
let index = (resource_indices.buffers + index) as usize;
|
||||
encoder.set_buffer(buffer, offset as usize, index);
|
||||
let br = naga::ResourceBinding {
|
||||
group: group_index,
|
||||
binding: *binding_location,
|
||||
};
|
||||
if let Some(size) = binding_size {
|
||||
let br = naga::ResourceBinding {
|
||||
group: group_index,
|
||||
binding: *binding_location,
|
||||
};
|
||||
self.state.storage_buffer_length_map.insert(br, *size);
|
||||
self.state.storage_buffer_length_map.insert((br, 0), *size);
|
||||
changes_sizes_buffer = true;
|
||||
}
|
||||
}
|
||||
super::BufferLikeResource::StorageBindingArray {
|
||||
ptr,
|
||||
array_element_sizes,
|
||||
binding_location,
|
||||
} => {
|
||||
let buffer = Some(unsafe { ptr.as_ref() });
|
||||
let index = (resource_indices.buffers + index) as usize;
|
||||
encoder.set_buffer(buffer, 0, index);
|
||||
let br = naga::ResourceBinding {
|
||||
group: group_index,
|
||||
binding: *binding_location,
|
||||
};
|
||||
for &(array_idx, size) in array_element_sizes {
|
||||
self.state
|
||||
.storage_buffer_length_map
|
||||
.insert((br, array_idx), size);
|
||||
changes_sizes_buffer = true;
|
||||
}
|
||||
}
|
||||
@@ -430,9 +449,9 @@ impl super::CommandState {
|
||||
let slot = stage_info.sizes_slot?;
|
||||
|
||||
result_sizes.clear();
|
||||
result_sizes.extend(stage_info.sized_bindings.iter().map(|br| {
|
||||
result_sizes.extend(stage_info.sized_bindings.iter().map(|(br, array_idx)| {
|
||||
self.storage_buffer_length_map
|
||||
.get(br)
|
||||
.get(&(*br, *array_idx))
|
||||
.map(|size| u32::try_from(size.get()).unwrap_or(u32::MAX))
|
||||
.unwrap_or_default()
|
||||
}));
|
||||
|
||||
@@ -365,6 +365,13 @@ pub fn map_resource_usage(ty: &wgt::BindingType) -> MTLResourceUsage {
|
||||
}
|
||||
},
|
||||
wgt::BindingType::Sampler(..) => MTLResourceUsage::empty(),
|
||||
wgt::BindingType::Buffer { ty, .. } => match ty {
|
||||
wgt::BufferBindingType::Uniform
|
||||
| wgt::BufferBindingType::Storage { read_only: true } => MTLResourceUsage::Read,
|
||||
wgt::BufferBindingType::Storage { read_only: false } => {
|
||||
MTLResourceUsage::Read | MTLResourceUsage::Write
|
||||
}
|
||||
},
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
+126
-41
@@ -1,5 +1,5 @@
|
||||
use alloc::{borrow::ToOwned as _, sync::Arc, vec::Vec};
|
||||
use core::ptr::NonNull;
|
||||
use core::{mem::align_of, ptr::NonNull};
|
||||
|
||||
use bytemuck::TransparentWrapper;
|
||||
use objc2::{
|
||||
@@ -43,15 +43,16 @@ struct CompiledShader {
|
||||
wg_size: MTLSize,
|
||||
wg_memory_sizes: Vec<u32>,
|
||||
|
||||
/// Bindings of WGSL `storage` globals that contain variable-sized arrays.
|
||||
/// Bindings of WGSL `storage` globals that contain variable-sized arrays,
|
||||
/// paired with a binding-array element index when applicable.
|
||||
///
|
||||
/// In order to implement bounds checks and the `arrayLength` function for
|
||||
/// WGSL runtime-sized arrays, we pass the entry point a struct with a
|
||||
/// member for each global variable that contains such an array. That member
|
||||
/// is a `u32` holding the variable's total size in bytes---which is simply
|
||||
/// the size of the `Buffer` supplying that variable's contents for the
|
||||
/// draw call.
|
||||
sized_bindings: Vec<naga::ResourceBinding>,
|
||||
/// `u32` member for each such binding. For ordinary storage buffers the
|
||||
/// element index is zero; for storage binding arrays there is one entry per
|
||||
/// layout element. Each member holds that element's total size in bytes---
|
||||
/// the size of the `Buffer` supplying its contents for the draw or dispatch.
|
||||
sized_bindings: Vec<(naga::ResourceBinding, u32)>,
|
||||
|
||||
immutable_buffer_mask: usize,
|
||||
}
|
||||
@@ -89,6 +90,21 @@ fn create_depth_stencil_desc(
|
||||
desc
|
||||
}
|
||||
|
||||
#[allow(
|
||||
clippy::mut_from_ref,
|
||||
reason = "MTLBuffer shared contents are writable through `&MTLBuffer`"
|
||||
)]
|
||||
fn bindless_id_table_mut(
|
||||
buffer: &ProtocolObject<dyn MTLBuffer>,
|
||||
count: u32,
|
||||
) -> &mut [MTLResourceID] {
|
||||
let ptr = buffer.contents().cast::<u8>().as_ptr();
|
||||
// SAFETY: The buffer is aligned to the size of `MTLResourceID`.
|
||||
assert_eq!(ptr as usize % align_of::<MTLResourceID>(), 0);
|
||||
let ptr = ptr.cast::<MTLResourceID>();
|
||||
unsafe { core::slice::from_raw_parts_mut(ptr, count as usize) }
|
||||
}
|
||||
|
||||
const fn convert_vertex_format_to_naga(format: wgt::VertexFormat) -> nt::VertexFormat {
|
||||
match format {
|
||||
wgt::VertexFormat::Uint8 => nt::VertexFormat::Uint8,
|
||||
@@ -231,6 +247,7 @@ impl super::Device {
|
||||
},
|
||||
vertex_pulling_transform: true,
|
||||
vertex_buffer_mappings: vertex_buffer_mappings.to_vec(),
|
||||
binding_array_length_map: layout.binding_array_length_map.clone(),
|
||||
};
|
||||
|
||||
let (source, info) = naga::back::msl::write_string(
|
||||
@@ -322,18 +339,27 @@ impl super::Device {
|
||||
immutable_buffer_mask |= 1 << slot;
|
||||
}
|
||||
|
||||
let mut dynamic_array_container_ty = var.ty;
|
||||
if let naga::TypeInner::Struct { ref members, .. } =
|
||||
module.types[var.ty].inner
|
||||
if module.types[var.ty]
|
||||
.inner
|
||||
.needs_host_buffer_byte_size(&module.types)
|
||||
{
|
||||
dynamic_array_container_ty = members.last().unwrap().ty;
|
||||
}
|
||||
if let naga::TypeInner::Array {
|
||||
size: naga::ArraySize::Dynamic,
|
||||
..
|
||||
} = module.types[dynamic_array_container_ty].inner
|
||||
{
|
||||
sized_bindings.push(br);
|
||||
let n = match module.types[var.ty].inner {
|
||||
naga::TypeInner::BindingArray { size, .. } => {
|
||||
let from_shader = match size {
|
||||
naga::ArraySize::Constant(n) => n.get(),
|
||||
naga::ArraySize::Pending(_)
|
||||
| naga::ArraySize::Dynamic => 0,
|
||||
};
|
||||
let from_layout = layout
|
||||
.binding_array_length_map
|
||||
.get(&br)
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
from_shader.max(from_layout).max(1)
|
||||
}
|
||||
_ => 1,
|
||||
};
|
||||
sized_bindings.extend((0..n).map(|i| (br, i)));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -789,6 +815,7 @@ impl crate::Device for super::Device {
|
||||
resources: Default::default(),
|
||||
});
|
||||
let mut bind_group_infos = [const { None }; crate::MAX_BIND_GROUPS];
|
||||
let mut binding_array_length_map = naga::FastHashMap::default();
|
||||
|
||||
// First, place the immediates
|
||||
for info in stage_data.iter_mut() {
|
||||
@@ -811,6 +838,22 @@ impl crate::Device for super::Device {
|
||||
let base_resource_indices = stage_data.map_ref(|info| info.counters.clone());
|
||||
|
||||
for entry in bgl.entries.iter() {
|
||||
let br = naga::ResourceBinding {
|
||||
group: group_index as u32,
|
||||
binding: entry.binding,
|
||||
};
|
||||
if let Some(count) = entry.count {
|
||||
if matches!(
|
||||
entry.ty,
|
||||
wgt::BindingType::Buffer {
|
||||
ty: wgt::BufferBindingType::Storage { .. },
|
||||
..
|
||||
}
|
||||
) {
|
||||
binding_array_length_map.insert(br, count.get());
|
||||
}
|
||||
}
|
||||
|
||||
if let wgt::BindingType::Buffer {
|
||||
ty: wgt::BufferBindingType::Storage { .. },
|
||||
..
|
||||
@@ -883,10 +926,6 @@ impl crate::Device for super::Device {
|
||||
}
|
||||
}
|
||||
|
||||
let br = naga::ResourceBinding {
|
||||
group: group_index as u32,
|
||||
binding: entry.binding,
|
||||
};
|
||||
info.resources.insert(br, target);
|
||||
}
|
||||
}
|
||||
@@ -930,6 +969,7 @@ impl crate::Device for super::Device {
|
||||
immediates_infos,
|
||||
total_immediates: desc.immediate_size,
|
||||
per_stage_map,
|
||||
binding_array_length_map,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -974,7 +1014,7 @@ impl crate::Device for super::Device {
|
||||
let uses = conv::map_resource_usage(&layout.ty);
|
||||
|
||||
// Create argument buffer for this array
|
||||
let buffer = self
|
||||
let argument_buffer = self
|
||||
.shared
|
||||
.device
|
||||
.newBufferWithLength_options(
|
||||
@@ -984,22 +1024,18 @@ impl crate::Device for super::Device {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let contents: &mut [MTLResourceID] = unsafe {
|
||||
core::slice::from_raw_parts_mut(
|
||||
buffer.contents().cast().as_ptr(),
|
||||
count as usize,
|
||||
)
|
||||
};
|
||||
|
||||
let mut array_element_sizes = Vec::new();
|
||||
match layout.ty {
|
||||
wgt::BindingType::Texture { .. }
|
||||
| wgt::BindingType::StorageTexture { .. } => {
|
||||
let resource_ids =
|
||||
bindless_id_table_mut(argument_buffer.as_ref(), count);
|
||||
let start = entry.resource_index as usize;
|
||||
let end = start + count as usize;
|
||||
let textures = &desc.textures[start..end];
|
||||
|
||||
for (idx, tex) in textures.iter().enumerate() {
|
||||
contents[idx] = tex.view.raw.gpuResourceID();
|
||||
resource_ids[idx] = tex.view.raw.gpuResourceID();
|
||||
|
||||
let use_info = bg
|
||||
.resources_to_use
|
||||
@@ -1012,17 +1048,51 @@ impl crate::Device for super::Device {
|
||||
}
|
||||
}
|
||||
wgt::BindingType::Sampler { .. } => {
|
||||
let resource_ids =
|
||||
bindless_id_table_mut(argument_buffer.as_ref(), count);
|
||||
let start = entry.resource_index as usize;
|
||||
let end = start + count as usize;
|
||||
let samplers = &desc.samplers[start..end];
|
||||
|
||||
for (idx, &sampler) in samplers.iter().enumerate() {
|
||||
contents[idx] = sampler.raw.gpuResourceID();
|
||||
resource_ids[idx] = sampler.raw.gpuResourceID();
|
||||
// Samplers aren't resources like buffers and textures, so don't
|
||||
// need to be passed to useResource
|
||||
}
|
||||
}
|
||||
wgt::BindingType::Buffer { ty, .. } => {
|
||||
let start = entry.resource_index as usize;
|
||||
let end = start + count as usize;
|
||||
let buffers = &desc.buffers[start..end];
|
||||
let pointers = argument_buffer.contents().cast::<u64>();
|
||||
for (idx, source) in buffers.iter().enumerate() {
|
||||
let addr = source.buffer.raw.gpuAddress() + source.offset;
|
||||
unsafe {
|
||||
pointers.add(idx).write(addr);
|
||||
}
|
||||
|
||||
if let wgt::BufferBindingType::Storage { .. } = ty {
|
||||
let remaining_size = wgt::BufferSize::new(
|
||||
source.buffer.size - source.offset,
|
||||
);
|
||||
if let Some(binding_size) = source.size.or(remaining_size) {
|
||||
array_element_sizes.push((idx as u32, binding_size));
|
||||
}
|
||||
}
|
||||
|
||||
let use_info = bg
|
||||
.resources_to_use
|
||||
.entry(source.buffer.as_raw().cast())
|
||||
.or_default();
|
||||
use_info.stages |= stages;
|
||||
use_info.uses |= uses;
|
||||
use_info.visible_in_compute |=
|
||||
layout.visibility.contains(wgt::ShaderStages::COMPUTE);
|
||||
}
|
||||
}
|
||||
wgt::BindingType::AccelerationStructure { .. } => {
|
||||
let resource_ids =
|
||||
bindless_id_table_mut(argument_buffer.as_ref(), count);
|
||||
let start = entry.resource_index as usize;
|
||||
let end = start + count as usize;
|
||||
let acceleration_structures =
|
||||
@@ -1031,7 +1101,7 @@ impl crate::Device for super::Device {
|
||||
for (idx, &acceleration_structure) in
|
||||
acceleration_structures.iter().enumerate()
|
||||
{
|
||||
contents[idx] = acceleration_structure.raw.gpuResourceID();
|
||||
resource_ids[idx] = acceleration_structure.raw.gpuResourceID();
|
||||
|
||||
let use_info = bg
|
||||
.resources_to_use
|
||||
@@ -1048,16 +1118,31 @@ impl crate::Device for super::Device {
|
||||
}
|
||||
}
|
||||
|
||||
bg.buffers.push(super::BufferLikeResource::Buffer {
|
||||
ptr: NonNull::from(&*buffer),
|
||||
offset: 0,
|
||||
dynamic_index: None,
|
||||
binding_size: None,
|
||||
binding_location: layout.binding,
|
||||
});
|
||||
if matches!(
|
||||
layout.ty,
|
||||
wgt::BindingType::Buffer {
|
||||
ty: wgt::BufferBindingType::Storage { .. },
|
||||
..
|
||||
}
|
||||
) {
|
||||
bg.buffers
|
||||
.push(super::BufferLikeResource::StorageBindingArray {
|
||||
ptr: NonNull::from(&*argument_buffer),
|
||||
array_element_sizes,
|
||||
binding_location: layout.binding,
|
||||
});
|
||||
} else {
|
||||
bg.buffers.push(super::BufferLikeResource::Buffer {
|
||||
ptr: NonNull::from(&*argument_buffer),
|
||||
offset: 0,
|
||||
dynamic_index: None,
|
||||
binding_size: None,
|
||||
binding_location: layout.binding,
|
||||
});
|
||||
}
|
||||
counter.buffers += 1;
|
||||
|
||||
bg.argument_buffers.push(buffer)
|
||||
bg.argument_buffers.push(argument_buffer)
|
||||
}
|
||||
// Bindfull path
|
||||
else {
|
||||
|
||||
@@ -1020,6 +1020,7 @@ pub struct PipelineLayout {
|
||||
immediates_infos: MultiStageData<Option<ImmediateDataInfo>>,
|
||||
total_immediates: u32,
|
||||
per_stage_map: MultiStageResources,
|
||||
binding_array_length_map: FastHashMap<naga::ResourceBinding, u32>,
|
||||
}
|
||||
|
||||
impl crate::DynPipelineLayout for PipelineLayout {}
|
||||
@@ -1043,6 +1044,16 @@ enum BufferLikeResource {
|
||||
|
||||
binding_location: u32,
|
||||
},
|
||||
|
||||
/// Bindless storage `binding_array`: one argument [`MTLBuffer`] (pointer table) plus element
|
||||
/// byte sizes `(array index, size)` for `_buffer_sizes` / runtime-sized arrays.
|
||||
///
|
||||
/// [`MTLBuffer`]: objc2_metal::MTLBuffer
|
||||
StorageBindingArray {
|
||||
ptr: NonNull<ProtocolObject<dyn MTLBuffer>>,
|
||||
array_element_sizes: Vec<(u32, wgt::BufferSize)>,
|
||||
binding_location: u32,
|
||||
},
|
||||
AccelerationStructure(NonNull<ProtocolObject<dyn MTLAccelerationStructure>>),
|
||||
}
|
||||
|
||||
@@ -1116,7 +1127,7 @@ struct PipelineStageInfo {
|
||||
/// Bindings of all WGSL `storage` globals that contain runtime-sized arrays.
|
||||
///
|
||||
/// See `device::CompiledShader::sized_bindings` for more details.
|
||||
sized_bindings: Vec<naga::ResourceBinding>,
|
||||
sized_bindings: Vec<(naga::ResourceBinding, u32)>,
|
||||
|
||||
/// Info on all bound vertex buffers.
|
||||
vertex_buffer_mappings: Vec<naga::back::msl::VertexBufferMapping>,
|
||||
@@ -1317,7 +1328,7 @@ struct CommandState {
|
||||
/// See `device::CompiledShader::sized_bindings` for more details.
|
||||
///
|
||||
/// [`ResourceBinding`]: naga::ResourceBinding
|
||||
storage_buffer_length_map: FastHashMap<naga::ResourceBinding, wgt::BufferSize>,
|
||||
storage_buffer_length_map: FastHashMap<(naga::ResourceBinding, u32), wgt::BufferSize>,
|
||||
|
||||
vertex_buffer_size_map: FastHashMap<u32, wgt::BufferSize>,
|
||||
|
||||
|
||||
Reference in new issue
Block a user