gfx-rs / wgpu

A cross-platform, safe, pure-Rust graphics API.
https://wgpu.rs
Apache License 2.0
12.63k stars 926 forks source link

Use argument buffers on Metal #4491

Open kanerogers opened 1 year ago

kanerogers commented 1 year ago

Background

This is a companion to the wgpu issue https://github.com/gfx-rs/wgpu/issues/3334

Using argument buffers would simplify the Metal shaders emitted by naga. Instead of having to pass each binding to the shader function as an argument, each binding group can be bundled into a struct which can then be used throughout the shader. For example:

Input wgsl

@group(0) @binding(0) var u_texture : texture_2d<f32>;
@group(0) @binding(1) var u_sampler : sampler;

@fragment
fn frag_main(@location(0) uv : vec2<f32>) -> @location(0) vec4<f32> {
  return textureSample(u_texture, u_sampler, uv);
}

Without argument buffers

fragment frag_mainOutput frag_main(
  frag_mainInput varyings_1 [[stage_in]]
, metal::texture2d<float, metal::access::sample> u_texture [[user(fake0)]]
, metal::sampler u_sampler [[user(fake0)]]
  metal::float4 color = u_texture.sample(u_sampler, uv_1);
  return frag_mainOutput { color };
)

With argument buffers

struct Group_0 {
   metal::texture2d<float, metal::access::sample> u_texture [[id(0)]];
   metal::sampler u_sampler [[id(1)]];
};

fragment frag_mainOutput frag_main(
  frag_mainInput varyings_1 [[stage_in]]
  device Group_0 & group_0 [[buffer(0)]]
) {
  metal::float4 color = group_0.u_texture.sample(group_0.u_sampler, uv_1);
  return frag_mainOutput { color };
}
kanerogers commented 1 year ago

Some updates on this one:

Some notes (for my reference, or for anyone who wants to pick this up should I get hit by a bus):

teoxoy commented 1 year ago

Some considerations:

jimblandy commented 1 year ago

@kanerogers The "Without argument buffers" example in the top comment seems mangled - is that valid MSL?

kanerogers commented 1 year ago

@kanerogers The "Without argument buffers" example in the top comment seems mangled - is that valid MSL?

Ah, good pick up! 😅

No, it's not valid MSL. This was just a rough sketch I wrote, mostly for myself, when I was first looking into the project.