diff --git a/Cargo.toml b/Cargo.toml index 96e6e3163..9d1c24922 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,21 +50,25 @@ tracing = { version = "0.1", default-features = false, features = ["std"] } serde = { version = "1", features = ["derive"], optional = true } [dev-dependencies] -cgmath = "0.18" -log = "0.4" -png = "0.16" -winit = { version = "0.24.0", features = ["web-sys"] } -rand = { version = "0.7.2", features = ["wasm-bindgen"] } bytemuck = { version = "1.4", features = ["derive"] } -noise = "0.7" +cgmath = "0.18" ddsfile = "0.4" +log = "0.4" +naga = { git = "https://github.com/gfx-rs/naga", tag = "gfx-8", features = ["wgsl-in"] } +noise = "0.7" +png = "0.16" +rand = { version = "0.7.2", features = ["wasm-bindgen"] } +winit = { version = "0.24.0", features = ["web-sys"] } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] async-executor = "1.0" pollster = "0.2" +wgpu-subscriber = "0.1" -[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies.wgpu-subscriber] -version = "0.1" +[target.'cfg(target_arch = "wasm32")'.dependencies.naga] +git = "https://github.com/gfx-rs/naga" +tag = "gfx-8" +features = ["wgsl-in", "spv-out"] [[example]] name="hello-compute" diff --git a/examples/README.md b/examples/README.md index 71bf215d1..270dcc92c 100644 --- a/examples/README.md +++ b/examples/README.md @@ -39,7 +39,7 @@ All framework-based examples render to the window. | - compressed textures | | | | | | :star: | | | | - polygon mode | | :star: | | | | | | | | - queries | | | :star: | | | | | | -| WGSL shaders | | | | | | | | | +| WGSL shaders | :star: | :star: | :star: | :star: | :star: | :star: | | | ## Hacking diff --git a/examples/boids/boids.comp b/examples/boids/boids.comp deleted file mode 100644 index 69a4ca6dd..000000000 --- a/examples/boids/boids.comp +++ /dev/null @@ -1,78 +0,0 @@ -#version 450 - -// These should match the Rust constants defined in main.rs -#define NUM_PARTICLES 1500 -#define PARTICLES_PER_GROUP 64 - -layout(local_size_x = PARTICLES_PER_GROUP) in; - -struct Particle { - vec2 pos; - vec2 vel; -}; -layout(std140, set = 0, binding = 0) uniform SimParams { - float deltaT; - float rule1Distance; - float rule2Distance; - float rule3Distance; - float rule1Scale; - float rule2Scale; - float rule3Scale; -} params; -layout(std140, set = 0, binding = 1) buffer SrcParticles { - Particle particles[NUM_PARTICLES]; -} srcParticles; -layout(std140, set = 0, binding = 2) buffer DstParticles { - Particle particles[NUM_PARTICLES]; -} dstParticles; - -void main() { - // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp - uint index = gl_GlobalInvocationID.x; - - if (index >= NUM_PARTICLES) { return; } - vec2 vPos = srcParticles.particles[index].pos; - vec2 vVel = srcParticles.particles[index].vel; - vec2 cMass = vec2(0.0, 0.0); - vec2 cVel = vec2(0.0, 0.0); - vec2 colVel = vec2(0.0, 0.0); - int cMassCount = 0; - int cVelCount = 0; - vec2 pos; - vec2 vel; - for (int i = 0; i < NUM_PARTICLES; ++i) { - if (i == index) { continue; } - pos = srcParticles.particles[i].pos.xy; - vel = srcParticles.particles[i].vel.xy; - if (distance(pos, vPos) < params.rule1Distance) { - cMass += pos; - cMassCount++; - } - if (distance(pos, vPos) < params.rule2Distance) { - colVel -= (pos - vPos); - } - if (distance(pos, vPos) < params.rule3Distance) { - cVel += vel; - cVelCount++; - } - } - if (cMassCount > 0) { - cMass = cMass / cMassCount - vPos; - } - if (cVelCount > 0) { - cVel = cVel / cVelCount; - } - vVel += cMass * params.rule1Scale + colVel * params.rule2Scale + cVel * params.rule3Scale; - // clamp velocity for a more pleasing simulation. - vVel = normalize(vVel) * clamp(length(vVel), 0.0, 0.1); - // kinematic update - vPos += vVel * params.deltaT; - // Wrap around boundary - if (vPos.x < -1.0) vPos.x = 1.0; - if (vPos.x > 1.0) vPos.x = -1.0; - if (vPos.y < -1.0) vPos.y = 1.0; - if (vPos.y > 1.0) vPos.y = -1.0; - dstParticles.particles[index].pos = vPos; - // Write back - dstParticles.particles[index].vel = vVel; -} diff --git a/examples/boids/boids.comp.spv b/examples/boids/boids.comp.spv deleted file mode 100644 index cadd91ef2..000000000 Binary files a/examples/boids/boids.comp.spv and /dev/null differ diff --git a/examples/boids/compute.wgsl b/examples/boids/compute.wgsl new file mode 100644 index 000000000..8c1c505a2 --- /dev/null +++ b/examples/boids/compute.wgsl @@ -0,0 +1,113 @@ +// This should match `NUM_PARTICLES` on the Rust side. +const NUM_PARTICLES: u32 = 1500; + +[[block]] +struct Particle { + pos : vec2; + vel : vec2; +}; + +[[block]] +struct SimParams { + deltaT : f32; + rule1Distance : f32; + rule2Distance : f32; + rule3Distance : f32; + rule1Scale : f32; + rule2Scale : f32; + rule3Scale : f32; +}; + +[[block]] +struct Particles { + particles : [[stride(16)]] array; +}; + +[[group(0), binding(0)]] var params : SimParams; +[[group(0), binding(1)]] var particlesSrc : [[access(read)]] Particles; +[[group(0), binding(2)]] var particlesDst : [[access(read_write)]] Particles; + +[[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3; + +// https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp +[[stage(compute), workgroup_size(64)]] +fn main() { + const index : u32 = gl_GlobalInvocationID.x; + if (index >= NUM_PARTICLES) { + return; + } + + var vPos : vec2 = particlesSrc.particles[index].pos; + var vVel : vec2 = particlesSrc.particles[index].vel; + + var cMass : vec2 = vec2(0.0, 0.0); + var cVel : vec2 = vec2(0.0, 0.0); + var colVel : vec2 = vec2(0.0, 0.0); + var cMassCount : i32 = 0; + var cVelCount : i32 = 0; + + var pos : vec2; + var vel : vec2; + var i : u32 = 0u; + loop { + if (i >= NUM_PARTICLES) { + break; + } + if (i == index) { + continue; + } + + pos = particlesSrc.particles[i].pos; + vel = particlesSrc.particles[i].vel; + + if (distance(pos, vPos) < params.rule1Distance) { + cMass = cMass + pos; + cMassCount = cMassCount + 1; + } + if (distance(pos, vPos) < params.rule2Distance) { + colVel = colVel - (pos - vPos); + } + if (distance(pos, vPos) < params.rule3Distance) { + cVel = cVel + vel; + cVelCount = cVelCount + 1; + } + + continuing { + i = i + 1u; + } + } + if (cMassCount > 0) { + cMass = cMass * (1.0 / f32(cMassCount)) - vPos; + } + if (cVelCount > 0) { + cVel = cVel * (1.0 / f32(cVelCount)); + } + + vVel = vVel + (cMass * params.rule1Scale) + + (colVel * params.rule2Scale) + + (cVel * params.rule3Scale); + + // clamp velocity for a more pleasing simulation + vVel = normalize(vVel) * clamp(length(vVel), 0.0, 0.1); + + // kinematic update + vPos = vPos + (vVel * params.deltaT); + + // Wrap around boundary + if (vPos.x < -1.0) { + vPos.x = 1.0; + } + if (vPos.x > 1.0) { + vPos.x = -1.0; + } + if (vPos.y < -1.0) { + vPos.y = 1.0; + } + if (vPos.y > 1.0) { + vPos.y = -1.0; + } + + // Write back + particlesDst.particles[index].pos = vPos; + particlesDst.particles[index].vel = vVel; +} diff --git a/examples/boids/draw.wgsl b/examples/boids/draw.wgsl new file mode 100644 index 000000000..cab88bdb3 --- /dev/null +++ b/examples/boids/draw.wgsl @@ -0,0 +1,26 @@ +[[location(0)]] +var in_particle_pos: vec2; +[[location(1)]] +var in_particle_vel: vec2; +[[location(2)]] +var in_position: vec2; +[[builtin(position)]] +var out_position: vec4; + +[[stage(vertex)]] +fn main() { + const angle: f32 = -atan2(in_particle_vel.x, in_particle_vel.y); + const pos: vec2 = vec2( + in_position.x * cos(angle) - in_position.y * sin(angle), + in_position.x * sin(angle) + in_position.y * cos(angle) + ); + out_position = vec4(pos + in_particle_pos, 0.0, 1.0); +} + +[[location(0)]] +var out_color: vec4; + +[[stage(fragment)]] +fn main() { + out_color = vec4(1.0, 1.0, 1.0, 1.0); +} diff --git a/examples/boids/main.rs b/examples/boids/main.rs index 08be4f475..f7587e39f 100644 --- a/examples/boids/main.rs +++ b/examples/boids/main.rs @@ -1,6 +1,7 @@ // Flocking boids example with gpu compute update pass // adapted from https://github.com/austinEng/webgpu-samples/blob/master/src/examples/computeBoids.ts +use std::{borrow::Cow, mem}; use wgpu::util::DeviceExt; #[path = "../framework.rs"] @@ -29,15 +30,28 @@ impl framework::Example for Example { /// constructs initial instance of Example struct fn init( sc_desc: &wgpu::SwapChainDescriptor, - _adapter: &wgpu::Adapter, + adapter: &wgpu::Adapter, device: &wgpu::Device, _queue: &wgpu::Queue, ) -> Self { - // load (and compile) shaders and create shader modules - - let boids_module = device.create_shader_module(&wgpu::include_spirv!("boids.comp.spv")); - let vs_module = device.create_shader_module(&wgpu::include_spirv!("shader.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("shader.frag.spv")); + // load and compile the shader + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgt::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION; + } + _ => {} //TODO + } + let compute_shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("compute.wgsl"))), + flags, + }); + let draw_shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("draw.wgsl"))), + flags, + }); // buffer for simulation parameters uniform @@ -69,7 +83,7 @@ impl framework::Example for Example { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new( - (sim_param_data.len() * std::mem::size_of::()) as _, + (sim_param_data.len() * mem::size_of::()) as _, ), }, count: None, @@ -78,7 +92,7 @@ impl framework::Example for Example { binding: 1, visibility: wgpu::ShaderStage::COMPUTE, ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, + ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new((NUM_PARTICLES * 16) as _), }, @@ -117,7 +131,7 @@ impl framework::Example for Example { label: None, layout: Some(&render_pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, + module: &draw_shader, entry_point: "main", buffers: &[ wgpu::VertexBufferLayout { @@ -133,7 +147,7 @@ impl framework::Example for Example { ], }, fragment: Some(wgpu::FragmentState { - module: &fs_module, + module: &draw_shader, entry_point: "main", targets: &[sc_desc.format.into()], }), @@ -147,7 +161,7 @@ impl framework::Example for Example { let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("Compute pipeline"), layout: Some(&compute_pipeline_layout), - module: &boids_module, + module: &compute_shader, entry_point: "main", }); diff --git a/examples/boids/shader.frag b/examples/boids/shader.frag deleted file mode 100644 index a778506c3..000000000 --- a/examples/boids/shader.frag +++ /dev/null @@ -1,5 +0,0 @@ -#version 450 -layout(location = 0) out vec4 fragColor; -void main() { - fragColor = vec4(1.0); -} diff --git a/examples/boids/shader.frag.spv b/examples/boids/shader.frag.spv deleted file mode 100644 index 3b3d8fbd7..000000000 Binary files a/examples/boids/shader.frag.spv and /dev/null differ diff --git a/examples/boids/shader.vert b/examples/boids/shader.vert deleted file mode 100644 index b302b6cf3..000000000 --- a/examples/boids/shader.vert +++ /dev/null @@ -1,11 +0,0 @@ -#version 450 -layout(location = 0) in vec2 a_particlePos; -layout(location = 1) in vec2 a_particleVel; -layout(location = 2) in vec2 a_pos; - -void main() { - float angle = -atan(a_particleVel.x, a_particleVel.y); - vec2 pos = vec2(a_pos.x * cos(angle) - a_pos.y * sin(angle), - a_pos.x * sin(angle) + a_pos.y * cos(angle)); - gl_Position = vec4(pos + a_particlePos, 0, 1); -} diff --git a/examples/boids/shader.vert.spv b/examples/boids/shader.vert.spv deleted file mode 100644 index 3e95e49fb..000000000 Binary files a/examples/boids/shader.vert.spv and /dev/null differ diff --git a/examples/cube/main.rs b/examples/cube/main.rs index 6b31988b1..e0e42c857 100644 --- a/examples/cube/main.rs +++ b/examples/cube/main.rs @@ -2,6 +2,7 @@ mod framework; use bytemuck::{Pod, Zeroable}; +use std::{borrow::Cow, iter, mem}; use wgpu::util::DeviceExt; #[repr(C)] @@ -65,8 +66,6 @@ fn create_vertices() -> (Vec, Vec) { } fn create_texels(size: usize) -> Vec { - use std::iter; - (0..size * size) .flat_map(|id| { // get high five for recognizing this ;) @@ -117,12 +116,10 @@ impl framework::Example for Example { fn init( sc_desc: &wgpu::SwapChainDescriptor, - _adapter: &wgpu::Adapter, + adapter: &wgpu::Adapter, device: &wgpu::Device, queue: &wgpu::Queue, ) -> Self { - use std::mem; - // Create the vertex and index buffers let vertex_size = mem::size_of::(); let (vertex_data, index_data) = create_vertices(); @@ -251,9 +248,18 @@ impl framework::Example for Example { label: None, }); - // Create the render pipeline - let vs_module = device.create_shader_module(&wgpu::include_spirv!("shader.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("shader.frag.spv")); + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Metal | wgpu::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION + } + _ => (), //TODO + } + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), + flags, + }); let vertex_buffers = [wgpu::VertexBufferLayout { array_stride: vertex_size as wgpu::BufferAddress, @@ -276,13 +282,13 @@ impl framework::Example for Example { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &vertex_buffers, }, fragment: Some(wgpu::FragmentState { - module: &fs_module, - entry_point: "main", + module: &shader, + entry_point: "fs_main", targets: &[sc_desc.format.into()], }), primitive: wgpu::PrimitiveState { @@ -297,19 +303,17 @@ impl framework::Example for Example { .features() .contains(wgt::Features::NON_FILL_POLYGON_MODE) { - let fs_wire_module = - device.create_shader_module(&wgpu::include_spirv!("wire.frag.spv")); let pipeline_wire = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &vertex_buffers, }, fragment: Some(wgpu::FragmentState { - module: &fs_wire_module, - entry_point: "main", + module: &shader, + entry_point: "fs_wire", targets: &[wgpu::ColorTargetState { format: sc_desc.format, color_blend: wgpu::BlendState { diff --git a/examples/cube/shader.frag b/examples/cube/shader.frag deleted file mode 100644 index 966bfdb02..000000000 --- a/examples/cube/shader.frag +++ /dev/null @@ -1,12 +0,0 @@ -#version 450 - -layout(location = 0) in vec2 v_TexCoord; -layout(location = 0) out vec4 o_Target; -layout(set = 0, binding = 1) uniform texture2D t_Color; -layout(set = 0, binding = 2) uniform sampler s_Color; - -void main() { - vec4 tex = texture(sampler2D(t_Color, s_Color), v_TexCoord); - float mag = length(v_TexCoord-vec2(0.5)); - o_Target = vec4(mix(tex.xyz, vec3(0.0), mag*mag), 1.0); -} diff --git a/examples/cube/shader.frag.spv b/examples/cube/shader.frag.spv deleted file mode 100644 index f41e3c9ec..000000000 Binary files a/examples/cube/shader.frag.spv and /dev/null differ diff --git a/examples/cube/shader.vert b/examples/cube/shader.vert deleted file mode 100644 index 6a4028e7a..000000000 --- a/examples/cube/shader.vert +++ /dev/null @@ -1,14 +0,0 @@ -#version 450 - -layout(location = 0) in vec4 a_Pos; -layout(location = 1) in vec2 a_TexCoord; -layout(location = 0) out vec2 v_TexCoord; - -layout(set = 0, binding = 0) uniform Locals { - mat4 u_Transform; -}; - -void main() { - v_TexCoord = a_TexCoord; - gl_Position = u_Transform * a_Pos; -} diff --git a/examples/cube/shader.vert.spv b/examples/cube/shader.vert.spv deleted file mode 100644 index a5539aff6..000000000 Binary files a/examples/cube/shader.vert.spv and /dev/null differ diff --git a/examples/cube/shader.wgsl b/examples/cube/shader.wgsl new file mode 100644 index 000000000..cc9404240 --- /dev/null +++ b/examples/cube/shader.wgsl @@ -0,0 +1,44 @@ +[[location(0)]] +var in_position: vec4; +[[location(1)]] +var in_tex_coord_vs: vec2; +[[location(0)]] +var out_tex_coord: vec2; +[[builtin(position)]] +var out_position: vec4; + +[[block]] +struct Locals { + transform: mat4x4; +}; +[[group(0), binding(0)]] +var r_locals: Locals; + +[[stage(vertex)]] +fn vs_main() { + out_tex_coord = in_tex_coord_vs; + out_position = r_locals.transform * in_position; +} + +[[location(0)]] +var in_tex_coord_fs: vec2; +[[location(0)]] +var out_color: vec4; +[[group(0), binding(1)]] +var r_color: texture_2d; +[[group(0), binding(2)]] +var r_sampler: sampler; + +[[stage(fragment)]] +fn fs_main() { + var tex: vec4 = textureSample(r_color, r_sampler, in_tex_coord_fs); + out_color = tex; + //TODO: support `length` and `mix` functions + //var mag: f32 = length(in_tex_coord_fs-vec2(0.5, 0.5)); + //out_color = vec4(mix(tex.xyz, vec3(0.0, 0.0, 0.0), mag*mag), 1.0); +} + +[[stage(fragment)]] +fn fs_wire() { + out_color = vec4(0.0, 0.5, 0.0, 0.5); +} diff --git a/examples/cube/wire.frag b/examples/cube/wire.frag deleted file mode 100644 index dde4b20f6..000000000 --- a/examples/cube/wire.frag +++ /dev/null @@ -1,7 +0,0 @@ -#version 450 - -layout(location = 0) out vec4 o_Target; - -void main() { - o_Target = vec4(0.0, 0.5, 0.0, 0.5); -} diff --git a/examples/cube/wire.frag.spv b/examples/cube/wire.frag.spv deleted file mode 100644 index f2afd9aae..000000000 Binary files a/examples/cube/wire.frag.spv and /dev/null differ diff --git a/examples/hello-compute/main.rs b/examples/hello-compute/main.rs index 022de1088..ad6c31c8d 100644 --- a/examples/hello-compute/main.rs +++ b/examples/hello-compute/main.rs @@ -1,4 +1,4 @@ -use std::{convert::TryInto, str::FromStr}; +use std::{borrow::Cow, convert::TryInto, str::FromStr}; use wgpu::util::DeviceExt; async fn run() { @@ -44,7 +44,18 @@ async fn execute_gpu(numbers: Vec) -> Vec { .unwrap(); // Loads the shader from the SPIR-V file.arrayvec - let cs_module = device.create_shader_module(&wgpu::include_spirv!("shader.comp.spv")); + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Vulkan | wgpu::Backend::Metal => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION; + } + _ => {} + } + let cs_module = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), + flags, + }); // Gets the size in bytes of the buffer. let slice_size = numbers.len() * std::mem::size_of::(); diff --git a/examples/hello-compute/shader.comp b/examples/hello-compute/shader.comp deleted file mode 100644 index b7b1edef8..000000000 --- a/examples/hello-compute/shader.comp +++ /dev/null @@ -1,31 +0,0 @@ -#version 450 -layout(local_size_x = 1) in; - -layout(set = 0, binding = 0) buffer PrimeIndices { - uint[] indices; -}; // this is used as both input and output for convenience - -// The Collatz Conjecture states that for any integer n: -// If n is even, n = n/2 -// If n is odd, n = 3n+1 -// And repeat this process for each new n, you will always eventually reach 1. -// Though the conjecture has not been proven, no counterexample has ever been found. -// This function returns how many times this recurrence needs to be applied to reach 1. -uint collatz_iterations(uint n) { - uint i = 0; - while(n > 1) { - if (mod(n, 2) == 0) { - n = n / 2; - } - else { - n = (3 * n) + 1; - } - i++; - } - return i; -} - -void main() { - uint index = gl_GlobalInvocationID.x; - indices[index] = collatz_iterations(indices[index]); -} \ No newline at end of file diff --git a/examples/hello-compute/shader.comp.spv b/examples/hello-compute/shader.comp.spv deleted file mode 100644 index 7bf37d71d..000000000 Binary files a/examples/hello-compute/shader.comp.spv and /dev/null differ diff --git a/examples/hello-compute/shader.wgsl b/examples/hello-compute/shader.wgsl new file mode 100644 index 000000000..2433f3243 --- /dev/null +++ b/examples/hello-compute/shader.wgsl @@ -0,0 +1,39 @@ +[[builtin(global_invocation_id)]] +var global_id: vec3; + +[[block]] +struct PrimeIndices { + data: [[stride(4)]] array; +}; // this is used as both input and output for convenience + +[[group(0), binding(0)]] +var v_indices: [[access(read_write)]] PrimeIndices; + +// The Collatz Conjecture states that for any integer n: +// If n is even, n = n/2 +// If n is odd, n = 3n+1 +// And repeat this process for each new n, you will always eventually reach 1. +// Though the conjecture has not been proven, no counterexample has ever been found. +// This function returns how many times this recurrence needs to be applied to reach 1. +fn collatz_iterations(n_base: u32) -> u32{ + var n: u32 = n_base; + var i: u32 = 0u; + loop { + if (n <= 1u) { + break; + } + if (n % 2u == 0u) { + n = n / 2u; + } + else { + n = 3u * n + 1u; + } + i = i + 1u; + } + return i; +} + +[[stage(compute), workgroup_size(1)]] +fn main() { + v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); +} diff --git a/examples/hello-triangle/main.rs b/examples/hello-triangle/main.rs index c87cafaf1..7d5ed6472 100644 --- a/examples/hello-triangle/main.rs +++ b/examples/hello-triangle/main.rs @@ -7,7 +7,7 @@ use winit::{ async fn run(event_loop: EventLoop<()>, window: Window) { let size = window.inner_size(); - let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); + let instance = wgpu::Instance::new(wgpu::BackendBit::all()); let surface = unsafe { instance.create_surface(&window) }; let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { diff --git a/examples/mipmap/blit.frag b/examples/mipmap/blit.frag deleted file mode 100644 index cfe6499aa..000000000 --- a/examples/mipmap/blit.frag +++ /dev/null @@ -1,10 +0,0 @@ -#version 450 - -layout(location = 0) in vec2 v_TexCoord; -layout(location = 0) out vec4 o_Target; -layout(set = 0, binding = 0) uniform texture2D t_Color; -layout(set = 0, binding = 1) uniform sampler s_Color; - -void main() { - o_Target = textureLod(sampler2D(t_Color, s_Color), v_TexCoord, 0.0); -} diff --git a/examples/mipmap/blit.frag.spv b/examples/mipmap/blit.frag.spv deleted file mode 100644 index ff08dac76..000000000 Binary files a/examples/mipmap/blit.frag.spv and /dev/null differ diff --git a/examples/mipmap/blit.vert b/examples/mipmap/blit.vert deleted file mode 100644 index d8ab87c76..000000000 --- a/examples/mipmap/blit.vert +++ /dev/null @@ -1,16 +0,0 @@ -#version 450 - -layout(location = 0) out vec2 v_TexCoord; - -void main() { - vec2 tc = vec2(0.0); - switch(gl_VertexIndex) { - case 0: tc = vec2(1.0, 0.0); break; - case 1: tc = vec2(1.0, 1.0); break; - case 2: tc = vec2(0.0, 0.0); break; - case 3: tc = vec2(0.0, 1.0); break; - } - v_TexCoord = tc; - vec2 pos = tc * 2.0 - 1.0; - gl_Position = vec4(pos.x, -pos.y, 0.5, 1.0); -} diff --git a/examples/mipmap/blit.vert.spv b/examples/mipmap/blit.vert.spv deleted file mode 100644 index b2ad4687e..000000000 Binary files a/examples/mipmap/blit.vert.spv and /dev/null differ diff --git a/examples/mipmap/blit.wgsl b/examples/mipmap/blit.wgsl new file mode 100644 index 000000000..e5cb571f5 --- /dev/null +++ b/examples/mipmap/blit.wgsl @@ -0,0 +1,36 @@ +[[builtin(vertex_index)]] +var in_vertex_index: u32; +[[builtin(position)]] +var out_position: vec4; +[[location(0)]] +var out_tex_coords_vs: vec2; + +[[stage(vertex)]] +fn vs_main() { + var x: i32 = i32(in_vertex_index) / 2; + var y: i32 = i32(in_vertex_index) & 1; + out_tex_coords_vs = vec2( + f32(x) * 2.0, + f32(y) * 2.0 + ); + out_position = vec4( + out_tex_coords_vs.x * 2.0 - 1.0, + 1.0 - out_tex_coords_vs.y * 2.0, + 0.0, 1.0 + ); +} + +[[location(0)]] +var in_tex_coord_fs: vec2; +[[location(0)]] +var out_color_fs: vec4; + +[[group(0), binding(0)]] +var r_color: texture_2d; +[[group(0), binding(1)]] +var r_sampler: sampler; + +[[stage(fragment)]] +fn fs_main() { + out_color_fs = textureSample(r_color, r_sampler, in_tex_coord_fs); +} diff --git a/examples/mipmap/draw.frag b/examples/mipmap/draw.frag deleted file mode 100644 index c705c207c..000000000 --- a/examples/mipmap/draw.frag +++ /dev/null @@ -1,10 +0,0 @@ -#version 450 - -layout(location = 0) in vec2 v_TexCoord; -layout(location = 0) out vec4 o_Target; -layout(set = 0, binding = 1) uniform texture2D t_Color; -layout(set = 0, binding = 2) uniform sampler s_Color; - -void main() { - o_Target = texture(sampler2D(t_Color, s_Color), v_TexCoord); -} diff --git a/examples/mipmap/draw.frag.spv b/examples/mipmap/draw.frag.spv deleted file mode 100644 index 57d411376..000000000 Binary files a/examples/mipmap/draw.frag.spv and /dev/null differ diff --git a/examples/mipmap/draw.vert b/examples/mipmap/draw.vert deleted file mode 100644 index f646a282b..000000000 --- a/examples/mipmap/draw.vert +++ /dev/null @@ -1,13 +0,0 @@ -#version 450 - -layout(location = 0) in vec4 a_Pos; -layout(location = 0) out vec2 v_TexCoord; - -layout(set = 0, binding = 0) uniform Locals { - mat4 u_Transform; -}; - -void main() { - v_TexCoord = a_Pos.xy / 20.0 + 0.5; - gl_Position = u_Transform * a_Pos; -} diff --git a/examples/mipmap/draw.vert.spv b/examples/mipmap/draw.vert.spv deleted file mode 100644 index d8128ba45..000000000 Binary files a/examples/mipmap/draw.vert.spv and /dev/null differ diff --git a/examples/mipmap/draw.wgsl b/examples/mipmap/draw.wgsl new file mode 100644 index 000000000..6e2c82d29 --- /dev/null +++ b/examples/mipmap/draw.wgsl @@ -0,0 +1,34 @@ +[[location(0)]] +var in_position_vs: vec4; +[[builtin(position)]] +var out_position: vec4; +[[location(0)]] +var out_tex_coords_vs: vec2; + +[[block]] +struct Locals { + transform: mat4x4; +}; +[[group(0), binding(0)]] +var r_data: Locals; + +[[stage(vertex)]] +fn vs_main() { + out_tex_coords_vs = 0.05 * in_position_vs.xy + vec2(0.5, 0.5); + out_position = r_data.transform * in_position_vs; +} + +[[location(0)]] +var in_tex_coord_fs: vec2; +[[location(0)]] +var out_color_fs: vec4; + +[[group(0), binding(1)]] +var r_color: texture_2d; +[[group(0), binding(2)]] +var r_sampler: sampler; + +[[stage(fragment)]] +fn fs_main() { + out_color_fs = textureSample(r_color, r_sampler, in_tex_coord_fs); +} diff --git a/examples/mipmap/main.rs b/examples/mipmap/main.rs index 8577a5f28..9994cf439 100644 --- a/examples/mipmap/main.rs +++ b/examples/mipmap/main.rs @@ -2,7 +2,7 @@ mod framework; use bytemuck::{Pod, Zeroable}; -use std::{mem, num::NonZeroU32}; +use std::{borrow::Cow, mem, num::NonZeroU32}; use wgpu::util::DeviceExt; const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb; @@ -102,21 +102,25 @@ impl Example { texture: &wgpu::Texture, query_sets: &Option, mip_count: u32, + shader_flags: wgpu::ShaderFlags, ) { - let vs_module = device.create_shader_module(&wgpu::include_spirv!("blit.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("blit.frag.spv")); + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("blit.wgsl"))), + flags: shader_flags, + }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("blit"), layout: None, vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &[], }, fragment: Some(wgpu::FragmentState { - module: &fs_module, - entry_point: "main", + module: &shader, + entry_point: "fs_main", targets: &[TEXTURE_FORMAT.into()], }), primitive: wgpu::PrimitiveState { @@ -307,15 +311,25 @@ impl framework::Example for Example { }); // Create the render pipeline - let vs_module = device.create_shader_module(&wgpu::include_spirv!("draw.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("draw.frag.spv")); + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Metal | wgpu::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION + } + _ => (), //TODO + } + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("draw.wgsl"))), + flags, + }); let draw_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("draw"), layout: None, vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &[wgpu::VertexBufferLayout { array_stride: vertex_size as wgpu::BufferAddress, step_mode: wgpu::InputStepMode::Vertex, @@ -323,8 +337,8 @@ impl framework::Example for Example { }], }, fragment: Some(wgpu::FragmentState { - module: &fs_module, - entry_point: "main", + module: &shader, + entry_point: "fs_main", targets: &[sc_desc.format.into()], }), primitive: wgpu::PrimitiveState { @@ -411,6 +425,7 @@ impl framework::Example for Example { &texture, &query_sets, MIP_LEVEL_COUNT, + flags, ); queue.submit(Some(init_encoder.finish())); diff --git a/examples/msaa-line/main.rs b/examples/msaa-line/main.rs index 64a55c1bb..2a7787135 100644 --- a/examples/msaa-line/main.rs +++ b/examples/msaa-line/main.rs @@ -10,7 +10,7 @@ #[path = "../framework.rs"] mod framework; -use std::iter; +use std::{borrow::Cow, iter}; use bytemuck::{Pod, Zeroable}; use wgpu::util::DeviceExt; @@ -24,8 +24,7 @@ struct Vertex { struct Example { bundle: wgpu::RenderBundle, - vs_module: wgpu::ShaderModule, - fs_module: wgpu::ShaderModule, + shader: wgpu::ShaderModule, pipeline_layout: wgpu::PipelineLayout, multisampled_framebuffer: wgpu::TextureView, vertex_buffer: wgpu::Buffer, @@ -39,8 +38,7 @@ impl Example { fn create_bundle( device: &wgpu::Device, sc_desc: &wgpu::SwapChainDescriptor, - vs_module: &wgpu::ShaderModule, - fs_module: &wgpu::ShaderModule, + shader: &wgpu::ShaderModule, pipeline_layout: &wgpu::PipelineLayout, sample_count: u32, vertex_buffer: &wgpu::Buffer, @@ -51,8 +49,8 @@ impl Example { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: vs_module, - entry_point: "main", + module: shader, + entry_point: "vs_main", buffers: &[wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as wgpu::BufferAddress, step_mode: wgpu::InputStepMode::Vertex, @@ -60,8 +58,8 @@ impl Example { }], }, fragment: Some(wgpu::FragmentState { - module: fs_module, - entry_point: "main", + module: shader, + entry_point: "fs_main", targets: &[sc_desc.format.into()], }), primitive: wgpu::PrimitiveState { @@ -119,15 +117,25 @@ impl Example { impl framework::Example for Example { fn init( sc_desc: &wgpu::SwapChainDescriptor, - _adapter: &wgpu::Adapter, + adapter: &wgpu::Adapter, device: &wgpu::Device, _queue: &wgpu::Queue, ) -> Self { log::info!("Press left/right arrow keys to change sample_count."); let sample_count = 4; - let vs_module = device.create_shader_module(&wgpu::include_spirv!("shader.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("shader.frag.spv")); + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Metal | wgpu::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION + } + _ => (), //TODO + } + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), + flags, + }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, @@ -164,8 +172,7 @@ impl framework::Example for Example { let bundle = Example::create_bundle( device, &sc_desc, - &vs_module, - &fs_module, + &shader, &pipeline_layout, sample_count, &vertex_buffer, @@ -174,8 +181,7 @@ impl framework::Example for Example { Example { bundle, - vs_module, - fs_module, + shader, pipeline_layout, multisampled_framebuffer, vertex_buffer, @@ -235,8 +241,7 @@ impl framework::Example for Example { self.bundle = Example::create_bundle( device, &self.sc_desc, - &self.vs_module, - &self.fs_module, + &self.shader, &self.pipeline_layout, self.sample_count, &self.vertex_buffer, diff --git a/examples/msaa-line/shader.frag b/examples/msaa-line/shader.frag deleted file mode 100644 index 1bb727606..000000000 --- a/examples/msaa-line/shader.frag +++ /dev/null @@ -1,8 +0,0 @@ -#version 450 - -layout(location = 0) in vec4 v_Color; -layout(location = 0) out vec4 f_Color; - -void main() { - f_Color = v_Color; -} diff --git a/examples/msaa-line/shader.frag.spv b/examples/msaa-line/shader.frag.spv deleted file mode 100644 index 46d3355b7..000000000 Binary files a/examples/msaa-line/shader.frag.spv and /dev/null differ diff --git a/examples/msaa-line/shader.vert b/examples/msaa-line/shader.vert deleted file mode 100644 index b42b54058..000000000 --- a/examples/msaa-line/shader.vert +++ /dev/null @@ -1,10 +0,0 @@ -#version 450 - -layout(location = 0) in vec2 a_Pos; -layout(location = 1) in vec4 a_Color; -layout(location = 0) out vec4 v_Color; - -void main() { - gl_Position = vec4(a_Pos, 0.0, 1.0); - v_Color = a_Color; -} diff --git a/examples/msaa-line/shader.vert.spv b/examples/msaa-line/shader.vert.spv deleted file mode 100644 index f50702009..000000000 Binary files a/examples/msaa-line/shader.vert.spv and /dev/null differ diff --git a/examples/msaa-line/shader.wgsl b/examples/msaa-line/shader.wgsl new file mode 100644 index 000000000..606eab5a1 --- /dev/null +++ b/examples/msaa-line/shader.wgsl @@ -0,0 +1,24 @@ +[[location(0)]] +var in_position: vec2; +[[location(1)]] +var in_color_vs: vec4; +[[location(0)]] +var out_color_vs: vec4; +[[builtin(position)]] +var out_position: vec4; + +[[stage(vertex)]] +fn vs_main() { + out_position = vec4(in_position, 0.0, 1.0); + out_color_vs = in_color_vs; +} + +[[location(0)]] +var in_color_fs: vec4; +[[location(0)]] +var out_color_fs: vec4; + +[[stage(fragment)]] +fn fs_main() { + out_color_fs = in_color_fs; +} diff --git a/examples/shadow/bake.vert b/examples/shadow/bake.vert deleted file mode 100644 index e4426b745..000000000 --- a/examples/shadow/bake.vert +++ /dev/null @@ -1,16 +0,0 @@ -#version 450 - -layout(location = 0) in ivec4 a_Pos; - -layout(set = 0, binding = 0) uniform Globals { - mat4 u_ViewProj; -}; - -layout(set = 1, binding = 0) uniform Entity { - mat4 u_World; - vec4 u_Color; -}; - -void main() { - gl_Position = u_ViewProj * u_World * vec4(a_Pos); -} diff --git a/examples/shadow/bake.vert.spv b/examples/shadow/bake.vert.spv deleted file mode 100644 index 26f1000fd..000000000 Binary files a/examples/shadow/bake.vert.spv and /dev/null differ diff --git a/examples/shadow/forward.frag b/examples/shadow/forward.frag deleted file mode 100644 index 8a3e2579d..000000000 --- a/examples/shadow/forward.frag +++ /dev/null @@ -1,64 +0,0 @@ -#version 450 - -const int MAX_LIGHTS = 10; - -layout(location = 0) in vec3 v_Normal; -layout(location = 1) in vec4 v_Position; - -layout(location = 0) out vec4 o_Target; - -struct Light { - mat4 proj; - vec4 pos; - vec4 color; -}; - -layout(set = 0, binding = 0) uniform Globals { - mat4 u_ViewProj; - uvec4 u_NumLights; -}; -layout(set = 0, binding = 1) uniform Lights { - Light u_Lights[MAX_LIGHTS]; -}; -layout(set = 0, binding = 2) uniform texture2DArray t_Shadow; -layout(set = 0, binding = 3) uniform samplerShadow s_Shadow; - -layout(set = 1, binding = 0) uniform Entity { - mat4 u_World; - vec4 u_Color; -}; - -float fetch_shadow(int light_id, vec4 homogeneous_coords) { - if (homogeneous_coords.w <= 0.0) { - return 1.0; - } - // compensate for the Y-flip difference between the NDC and texture coordinates - const vec2 flip_correction = vec2(0.5, -0.5); - // compute texture coordinates for shadow lookup - vec4 light_local = vec4( - homogeneous_coords.xy * flip_correction/homogeneous_coords.w + 0.5, - light_id, - homogeneous_coords.z / homogeneous_coords.w - ); - // do the lookup, using HW PCF and comparison - return texture(sampler2DArrayShadow(t_Shadow, s_Shadow), light_local); -} - -void main() { - vec3 normal = normalize(v_Normal); - vec3 ambient = vec3(0.05, 0.05, 0.05); - // accumulate color - vec3 color = ambient; - for (int i=0; i Self { @@ -408,10 +403,10 @@ impl framework::Example for Example { ]; let light_uniform_size = (Self::MAX_LIGHTS * mem::size_of::()) as wgpu::BufferAddress; - let light_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { + let light_storage_buf = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: light_uniform_size, - usage: wgpu::BufferUsage::UNIFORM + usage: wgpu::BufferUsage::STORAGE | wgpu::BufferUsage::COPY_SRC | wgpu::BufferUsage::COPY_DST, mapped_at_creation: false, @@ -424,8 +419,21 @@ impl framework::Example for Example { attributes: &vertex_attr, }; + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION; + } + _ => (), //TODO + } + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), + flags, + }); + let shadow_pass = { - let uniform_size = mem::size_of::() as wgpu::BufferAddress; + let uniform_size = mem::size_of::() as wgpu::BufferAddress; // Create pipeline layout let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { @@ -465,14 +473,12 @@ impl framework::Example for Example { }); // Create the render pipeline - let vs_module = device.create_shader_module(&wgpu::include_spirv!("bake.vert.spv")); - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("shadow"), layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_bake", buffers: &[vb_desc.clone()], }, fragment: None, @@ -515,11 +521,9 @@ impl framework::Example for Example { ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, - min_binding_size: wgpu::BufferSize::new(mem::size_of::< - ForwardUniforms, - >( - ) - as _), + min_binding_size: wgpu::BufferSize::new( + mem::size_of::() as _, + ), }, count: None, }, @@ -527,7 +531,7 @@ impl framework::Example for Example { binding: 1, // lights visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, + ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new(light_uniform_size), }, @@ -562,7 +566,7 @@ impl framework::Example for Example { }); let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32); - let forward_uniforms = ForwardUniforms { + let forward_uniforms = GlobalUniforms { proj: *mx_total.as_ref(), num_lights: [lights.len() as u32, 0, 0, 0], }; @@ -582,7 +586,7 @@ impl framework::Example for Example { }, wgpu::BindGroupEntry { binding: 1, - resource: light_uniform_buf.as_entire_binding(), + resource: light_storage_buf.as_entire_binding(), }, wgpu::BindGroupEntry { binding: 2, @@ -597,20 +601,17 @@ impl framework::Example for Example { }); // Create the render pipeline - let vs_module = device.create_shader_module(&wgpu::include_spirv!("forward.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("forward.frag.spv")); - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("main"), layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &[vb_desc], }, fragment: Some(wgpu::FragmentState { - module: &fs_module, - entry_point: "main", + module: &shader, + entry_point: "fs_main", targets: &[sc_desc.format.into()], }), primitive: wgpu::PrimitiveState { @@ -657,7 +658,7 @@ impl framework::Example for Example { shadow_pass, forward_pass, forward_depth: depth_texture.create_view(&wgpu::TextureViewDescriptor::default()), - light_uniform_buf, + light_storage_buf, entity_uniform_buf, entity_bind_group, } @@ -731,7 +732,7 @@ impl framework::Example for Example { self.lights_are_dirty = false; for (i, light) in self.lights.iter().enumerate() { queue.write_buffer( - &self.light_uniform_buf, + &self.light_storage_buf, (i * mem::size_of::()) as wgpu::BufferAddress, bytemuck::bytes_of(&light.to_raw()), ); @@ -751,7 +752,7 @@ impl framework::Example for Example { // The light uniform buffer already has the projection, // let's just copy it over to the shadow uniform buffer. encoder.copy_buffer_to_buffer( - &self.light_uniform_buf, + &self.light_storage_buf, (i * mem::size_of::()) as wgpu::BufferAddress, &self.shadow_pass.uniform_buf, 0, diff --git a/examples/shadow/shader.wgsl b/examples/shadow/shader.wgsl new file mode 100644 index 000000000..a9244df63 --- /dev/null +++ b/examples/shadow/shader.wgsl @@ -0,0 +1,114 @@ +[[location(0)]] +var in_position: vec4; +[[builtin(position)]] +var out_position: vec4; + +[[block]] +struct Globals { + view_proj: mat4x4; + num_lights: vec4; +}; + +[[group(0), binding(0)]] +var u_globals: Globals; + +[[block]] +struct Entity { + world: mat4x4; + color: vec4; +}; + +[[group(1), binding(0)]] +var u_entity: Entity; + +[[stage(vertex)]] +fn vs_bake() { + out_position = u_globals.view_proj * u_entity.world * vec4(in_position); +} + + +[[location(1)]] +var in_normal: vec4; + +[[location(0)]] +var out_normal_vs: vec3; +[[location(1)]] +var out_position_vs: vec4; + +[[stage(vertex)]] +fn vs_main() { + const w: mat4x4 = u_entity.world; + out_normal_vs = mat3x3(w.x.xyz, w.y.xyz, w.z.xyz) * vec3(in_normal.xyz); + out_position_vs = u_entity.world * vec4(in_position); + out_position = u_globals.view_proj * out_position_vs; +} + +// fragment shader + +[[block]] +struct Light { + proj: mat4x4; + pos: vec4; + color: vec4; +}; + +[[block]] +struct Lights { + data: [[stride(96)]] array; +}; + +[[group(0), binding(1)]] +var s_lights: [[access(read)]] Lights; +[[group(0), binding(2)]] +var t_shadow: texture_depth_2d_array; +[[group(0), binding(3)]] +var sampler_shadow: sampler; + +fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { + if (homogeneous_coords.w <= 0.0) { + return 1.0; + } + // compensate for the Y-flip difference between the NDC and texture coordinates + const flip_correction: vec2 = vec2(0.5, -0.5); + // compute texture coordinates for shadow lookup + const proj_correction: f32 = 1.0 / homogeneous_coords.w; + const light_local: vec2 = homogeneous_coords.xy * flip_correction * proj_correction + vec2(0.5, 0.5); + // do the lookup, using HW PCF and comparison + return textureSampleCompare(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z * proj_correction); +} + +[[location(0)]] +var in_normal_fs: vec3; +[[location(1)]] +var in_position_fs: vec4; +[[location(0)]] +var out_color_fs: vec4; + +const c_ambient: vec3 = vec3(0.05, 0.05, 0.05); +const c_max_lights: u32 = 10u; + +[[stage(fragment)]] +fn fs_main() { + const normal: vec3 = normalize(in_normal_fs); + // accumulate color + var color: vec3 = c_ambient; + var i: u32 = 0u; + loop { + if (i >= min(u_globals.num_lights.x, c_max_lights)) { + break; + } + const light: Light = s_lights.data[i]; + // project into the light space + const shadow: f32 = fetch_shadow(i, light.proj * in_position_fs); + // compute Lambertian diffuse term + const light_dir: vec3 = normalize(light.pos.xyz - in_position_fs.xyz); + const diffuse: f32 = max(0.0, dot(normal, light_dir)); + // add light contribution + color = color + shadow * diffuse * light.color.xyz; + continuing { + i = i + 1u; + } + } + // multiply the light by material color + out_color_fs = vec4(color, 1.0) * u_entity.color; +} diff --git a/examples/skybox/main.rs b/examples/skybox/main.rs index c6b6145f9..e5a8a4367 100644 --- a/examples/skybox/main.rs +++ b/examples/skybox/main.rs @@ -1,6 +1,7 @@ #[path = "../framework.rs"] mod framework; +use std::borrow::Cow; use wgpu::util::DeviceExt; const IMAGE_SIZE: u32 = 128; @@ -26,6 +27,8 @@ pub struct Skybox { impl Skybox { fn generate_uniforms(aspect_ratio: f32) -> Uniforms { + use cgmath::SquareMatrix; + let mx_projection = cgmath::perspective(cgmath::Deg(45f32), aspect_ratio, 1.0, 10.0); let mx_view = cgmath::Matrix4::look_at_rh( cgmath::Point3::new(1.5f32, -5.0, 3.0), @@ -33,7 +36,8 @@ impl Skybox { cgmath::Vector3::unit_z(), ); let mx_correction = framework::OPENGL_TO_WGPU_MATRIX; - [mx_correction * mx_projection, mx_correction * mx_view] + let proj_inv = (mx_correction * mx_projection).invert().unwrap(); + [proj_inv, mx_correction * mx_view] } } @@ -46,7 +50,7 @@ impl framework::Example for Skybox { fn init( sc_desc: &wgpu::SwapChainDescriptor, - _adapter: &wgpu::Adapter, + adapter: &wgpu::Adapter, device: &wgpu::Device, queue: &wgpu::Queue, ) -> Self { @@ -86,13 +90,23 @@ impl framework::Example for Skybox { }); // Create the render pipeline - let vs_module = device.create_shader_module(&wgpu::include_spirv!("shader.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("shader.frag.spv")); + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Metal | wgpu::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION + } + _ => (), //TODO + } + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), + flags, + }); let aspect = sc_desc.width as f32 / sc_desc.height as f32; let uniforms = Self::generate_uniforms(aspect); let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some(" Buffer"), + label: Some("Buffer"), contents: bytemuck::cast_slice(&raw_uniforms(&uniforms)), usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, }); @@ -108,13 +122,13 @@ impl framework::Example for Skybox { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &[], }, fragment: Some(wgpu::FragmentState { - module: &fs_module, - entry_point: "main", + module: &shader, + entry_point: "fs_main", targets: &[sc_desc.format.into()], }), primitive: wgpu::PrimitiveState { diff --git a/examples/skybox/shader.frag b/examples/skybox/shader.frag deleted file mode 100644 index 8c0cee397..000000000 --- a/examples/skybox/shader.frag +++ /dev/null @@ -1,11 +0,0 @@ -#version 450 - -layout(set = 0, binding = 1) uniform textureCube t_Cubemap; -layout(set = 0, binding = 2) uniform sampler s_Cubemap; - -layout(location = 0) in vec3 v_Uv; -layout(location = 0) out vec4 f_Color; - -void main() { - f_Color = texture(samplerCube(t_Cubemap, s_Cubemap), v_Uv); -} diff --git a/examples/skybox/shader.frag.spv b/examples/skybox/shader.frag.spv deleted file mode 100644 index 65ab23b9a..000000000 Binary files a/examples/skybox/shader.frag.spv and /dev/null differ diff --git a/examples/skybox/shader.vert b/examples/skybox/shader.vert deleted file mode 100644 index f6aabda61..000000000 --- a/examples/skybox/shader.vert +++ /dev/null @@ -1,22 +0,0 @@ -#version 450 - -layout(location = 0) out vec3 v_Uv; - -layout(set = 0, binding = 0) uniform Data { - mat4 proj; - mat4 view; -}; - -void main() { - vec4 pos = vec4(0.0); - switch(gl_VertexIndex) { - case 0: pos = vec4(-1.0, -1.0, 0.0, 1.0); break; - case 1: pos = vec4( 3.0, -1.0, 0.0, 1.0); break; - case 2: pos = vec4(-1.0, 3.0, 0.0, 1.0); break; - } - mat3 invModelView = transpose(mat3(view)); - vec3 unProjected = (inverse(proj) * pos).xyz; - v_Uv = invModelView * unProjected; - - gl_Position = pos; -} diff --git a/examples/skybox/shader.vert.spv b/examples/skybox/shader.vert.spv deleted file mode 100644 index 5b10601f1..000000000 Binary files a/examples/skybox/shader.vert.spv and /dev/null differ diff --git a/examples/skybox/shader.wgsl b/examples/skybox/shader.wgsl new file mode 100644 index 000000000..9254ab6a2 --- /dev/null +++ b/examples/skybox/shader.wgsl @@ -0,0 +1,43 @@ +[[builtin(position)]] +var out_position: vec4; +[[location(0)]] var out_uv: vec3; +[[builtin(vertex_index)]] var in_vertex_index: u32; + +[[block]] +struct Data { + proj_inv: mat4x4; + view: mat4x4; +}; +[[group(0), binding(0)]] +var r_data: Data; + +[[stage(vertex)]] +fn vs_main() { + // hacky way to draw a large triangle + var tmp1: i32 = i32(in_vertex_index) / 2; + var tmp2: i32 = i32(in_vertex_index) & 1; + const pos: vec4 = vec4( + f32(tmp1) * 4.0 - 1.0, + f32(tmp2) * 4.0 - 1.0, + 0.0, + 1.0 + ); + + const inv_model_view: mat3x3 = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); + var unprojected: vec4 = r_data.proj_inv * pos; //TODO: const + out_uv = inv_model_view * unprojected.xyz; + out_position = pos; +} + +[[group(0), binding(1)]] +var r_texture: texture_cube; +[[group(0), binding(2)]] +var r_sampler: sampler; + +[[location(0)]] var in_uv: vec3; +[[location(0)]] var out_color: vec4; + +[[stage(fragment)]] +fn fs_main() { + out_color = textureSample(r_texture, r_sampler, in_uv); +} diff --git a/src/backend/web.rs b/src/backend/web.rs index 60eead872..22502bdfa 100644 --- a/src/backend/web.rs +++ b/src/backend/web.rs @@ -1,4 +1,5 @@ use std::{ + collections::HashSet, fmt, future::Future, marker::PhantomData, @@ -1045,7 +1046,14 @@ impl crate::Context for Context { crate::ShaderSource::SpirV(ref spv) => { web_sys::GpuShaderModuleDescriptor::new(&js_sys::Uint32Array::from(&**spv)) } - crate::ShaderSource::Wgsl(_) => panic!("WGSL is not yet supported by the Web backend"), + crate::ShaderSource::Wgsl(ref code) => { + use naga::{back::spv, front::wgsl}; + let module = wgsl::parse_str(code).unwrap(); + let mut capabilities = HashSet::default(); + capabilities.insert(spv::Capability::Shader); + let words = spv::write_vec(&module, spv::WriterFlags::NONE, capabilities).unwrap(); + web_sys::GpuShaderModuleDescriptor::new(&js_sys::Uint32Array::from(&words[..])) + } }; if let Some(ref label) = desc.label { descriptor.label(label); diff --git a/tests/example-wgsl.rs b/tests/example-wgsl.rs new file mode 100644 index 000000000..545987cb8 --- /dev/null +++ b/tests/example-wgsl.rs @@ -0,0 +1,47 @@ +use naga::{front::wgsl, proc::Validator}; +use std::{fs, path::PathBuf}; + +#[test] +fn parse_example_wgsl() { + let read_dir = match PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples") + .read_dir() + { + Ok(iter) => iter, + Err(e) => { + log::error!("Unable to open the examples folder: {:?}", e); + return; + } + }; + for example_entry in read_dir { + let read_files = match example_entry { + Ok(dir_entry) => match dir_entry.path().read_dir() { + Ok(iter) => iter, + Err(_) => continue, + }, + Err(e) => { + log::warn!("Skipping example: {:?}", e); + continue; + } + }; + for file_entry in read_files { + let shader = match file_entry { + Ok(entry) => match entry.path().extension() { + Some(ostr) if &*ostr == "wgsl" => { + println!("Validating {:?}", entry.path()); + fs::read_to_string(entry.path()).unwrap_or_default() + } + _ => continue, + }, + Err(e) => { + log::warn!("Skipping file: {:?}", e); + continue; + } + }; + + let module = wgsl::parse_str(&shader).unwrap(); + //TODO: re-use the validator + Validator::new().validate(&module).unwrap(); + } + } +}