From 702c4ef4da95ab1317aac1dd3ca0d07462c1501e Mon Sep 17 00:00:00 2001 From: Inner Daemons <85136135+inner-daemons@users.noreply.github.com> Date: Tue, 10 Feb 2026 05:40:41 -0600 Subject: [PATCH] [wgsl] gate `primitive_index` built-in behind its extension & [glsl-out] require extensions for `gl_PrimitiveID` if needed (#8879) --- CHANGELOG.md | 1 + naga/src/back/glsl/features.rs | 17 ++ naga/src/back/spv/writer.rs | 1 + naga/src/back/wgsl/writer.rs | 122 ++++++++----- naga/src/front/wgsl/parse/conv.rs | 28 +-- .../wgsl/parse/directive/enable_extension.rs | 40 ++-- naga/tests/in/wgsl/extra.wgsl | 2 + naga/tests/in/wgsl/primitive-index-mesh.toml | 8 + naga/tests/in/wgsl/primitive-index-mesh.wgsl | 6 + naga/tests/in/wgsl/primitive-index.toml | 12 ++ naga/tests/in/wgsl/primitive-index.wgsl | 6 + naga/tests/naga/spirv_capabilities.rs | 1 + naga/tests/naga/wgsl_errors.rs | 32 +--- ...sl-primitive-index-mesh.func.Fragment.glsl | 13 ++ .../wgsl-primitive-index.func.Fragment.glsl | 9 + naga/tests/out/hlsl/wgsl-primitive-index.hlsl | 9 + naga/tests/out/hlsl/wgsl-primitive-index.ron | 12 ++ naga/tests/out/msl/wgsl-primitive-index.metal | 17 ++ .../tests/out/spv/wgsl-primitive-index.spvasm | 33 ++++ naga/tests/out/wgsl/wgsl-extra.wgsl | 2 + naga/tests/out/wgsl/wgsl-primitive-index.wgsl | 6 + tests/tests/wgpu-gpu/main.rs | 2 + tests/tests/wgpu-gpu/primitive_index.rs | 171 ++++++++++++++++++ .../primitive_index.wgsl | 2 + wgpu-core/src/validation.rs | 7 + 25 files changed, 456 insertions(+), 103 deletions(-) create mode 100644 naga/tests/in/wgsl/primitive-index-mesh.toml create mode 100644 naga/tests/in/wgsl/primitive-index-mesh.wgsl create mode 100644 naga/tests/in/wgsl/primitive-index.toml create mode 100644 naga/tests/in/wgsl/primitive-index.wgsl create mode 100644 naga/tests/out/glsl/wgsl-primitive-index-mesh.func.Fragment.glsl create mode 100644 naga/tests/out/glsl/wgsl-primitive-index.func.Fragment.glsl create mode 100644 naga/tests/out/hlsl/wgsl-primitive-index.hlsl create mode 100644 naga/tests/out/hlsl/wgsl-primitive-index.ron create mode 100644 naga/tests/out/msl/wgsl-primitive-index.metal create mode 100644 naga/tests/out/spv/wgsl-primitive-index.spvasm create mode 100644 naga/tests/out/wgsl/wgsl-primitive-index.wgsl create mode 100644 tests/tests/wgpu-gpu/primitive_index.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index a85c1b152..08f0c1d24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,6 +68,7 @@ By @cwfitzgerald in [#8999](https://github.com/gfx-rs/wgpu/pull/8999). - `ir::Block::len` - Changed passthrough shaders to not require an entry point parameter, so that the same shader module may be used in multiple entry points. Also added support for metallib passthrough. By @inner-daemons in #8886. - Added support for `insert_debug_marker`, `push_debug_group` and `pop_debug_group` on WebGPU. By @evilpie in [#9017](https://github.com/gfx-rs/wgpu/pull/9017). +- Added support for `enable primitive_index` and `@builtin(primitive_index)` with support on all platforms. By @inner-daemons in #8879. #### naga diff --git a/naga/src/back/glsl/features.rs b/naga/src/back/glsl/features.rs index d8ec4755c..38cec90b2 100644 --- a/naga/src/back/glsl/features.rs +++ b/naga/src/back/glsl/features.rs @@ -57,6 +57,8 @@ bitflags::bitflags! { const TEXTURE_ATOMICS = 1 << 25; /// Image atomics const SHADER_BARYCENTRICS = 1 << 26; + /// Primitive index builtin + const PRIMITIVE_INDEX = 1 << 27; } } @@ -298,6 +300,18 @@ impl FeaturesManager { )?; } + if self.0.contains(Features::PRIMITIVE_INDEX) { + match options.version { + Version::Embedded { version, .. } if version < 320 => { + writeln!(out, "#extension GL_OES_geometry_shader : require")?; + } + Version::Desktop(version) if version < 150 => { + writeln!(out, "#extension GL_ARB_geometry_shader4 : require")?; + } + _ => (), + } + } + Ok(()) } } @@ -616,6 +630,9 @@ impl Writer<'_, W> { crate::BuiltIn::Barycentric { .. } => { self.features.request(Features::SHADER_BARYCENTRICS) } + crate::BuiltIn::PrimitiveIndex => { + self.features.request(Features::PRIMITIVE_INDEX) + } _ => {} }, Binding::Location { diff --git a/naga/src/back/spv/writer.rs b/naga/src/back/spv/writer.rs index ba4ac1406..ec73ced5d 100644 --- a/naga/src/back/spv/writer.rs +++ b/naga/src/back/spv/writer.rs @@ -3083,6 +3083,7 @@ impl Writer { Bi::PointCoord => BuiltIn::PointCoord, Bi::FrontFacing => BuiltIn::FrontFacing, Bi::PrimitiveIndex => { + // Geometry shader capability is required for primitive index self.require_any( "`primitive_index` built-in", &[spirv::Capability::Geometry], diff --git a/naga/src/back/wgsl/writer.rs b/naga/src/back/wgsl/writer.rs index ffeece59b..6e7b6a229 100644 --- a/naga/src/back/wgsl/writer.rs +++ b/naga/src/back/wgsl/writer.rs @@ -278,11 +278,51 @@ impl Writer { /// Helper method which writes all the `enable` declarations /// needed for a module. fn write_enable_declarations(&mut self, module: &Module) -> BackendResult { - let mut needs_f16 = false; - let mut needs_dual_source_blending = false; - let mut needs_clip_distances = false; - let mut needs_mesh_shaders = false; - let mut needs_cooperative_matrix = false; + #[derive(Default)] + struct RequiredEnabled { + f16: bool, + dual_source_blending: bool, + clip_distances: bool, + mesh_shaders: bool, + primitive_index: bool, + cooperative_matrix: bool, + } + let mut needed = RequiredEnabled::default(); + + let check_binding = |binding: &crate::Binding, needed: &mut RequiredEnabled| match *binding + { + crate::Binding::Location { + blend_src: Some(_), .. + } => { + needed.dual_source_blending = true; + } + crate::Binding::BuiltIn(crate::BuiltIn::ClipDistance) => { + needed.clip_distances = true; + } + crate::Binding::BuiltIn(crate::BuiltIn::PrimitiveIndex) => { + needed.primitive_index = true; + } + crate::Binding::Location { + per_primitive: true, + .. + } => { + needed.mesh_shaders = true; + } + crate::Binding::BuiltIn( + crate::BuiltIn::MeshTaskSize + | crate::BuiltIn::CullPrimitive + | crate::BuiltIn::PointIndex + | crate::BuiltIn::LineIndices + | crate::BuiltIn::TriangleIndices + | crate::BuiltIn::VertexCount + | crate::BuiltIn::Vertices + | crate::BuiltIn::PrimitiveCount + | crate::BuiltIn::Primitives, + ) => { + needed.mesh_shaders = true; + } + _ => {} + }; // Determine which `enable` declarations are needed for (_, ty) in module.types.iter() { @@ -290,55 +330,35 @@ impl Writer { TypeInner::Scalar(scalar) | TypeInner::Vector { scalar, .. } | TypeInner::Matrix { scalar, .. } => { - needs_f16 |= scalar == crate::Scalar::F16; + needed.f16 |= scalar == crate::Scalar::F16; } TypeInner::Struct { ref members, .. } => { for binding in members.iter().filter_map(|m| m.binding.as_ref()) { - match *binding { - crate::Binding::Location { - blend_src: Some(_), .. - } => { - needs_dual_source_blending = true; - } - crate::Binding::BuiltIn(crate::BuiltIn::ClipDistance) => { - needs_clip_distances = true; - } - crate::Binding::Location { - per_primitive: true, - .. - } => { - needs_mesh_shaders = true; - } - crate::Binding::BuiltIn( - crate::BuiltIn::MeshTaskSize - | crate::BuiltIn::CullPrimitive - | crate::BuiltIn::PointIndex - | crate::BuiltIn::LineIndices - | crate::BuiltIn::TriangleIndices - | crate::BuiltIn::VertexCount - | crate::BuiltIn::Vertices - | crate::BuiltIn::PrimitiveCount - | crate::BuiltIn::Primitives, - ) => { - needs_mesh_shaders = true; - } - _ => {} - } + check_binding(binding, &mut needed); } } TypeInner::CooperativeMatrix { .. } => { - needs_cooperative_matrix = true; + needed.cooperative_matrix = true; } _ => {} } } - if module - .entry_points - .iter() - .any(|ep| matches!(ep.stage, ShaderStage::Mesh | ShaderStage::Task)) - { - needs_mesh_shaders = true; + for ep in &module.entry_points { + if matches!(ep.stage, ShaderStage::Mesh | ShaderStage::Task) { + needed.mesh_shaders = true; + } + if let Some(res) = ep.function.result.as_ref().and_then(|a| a.binding.as_ref()) { + check_binding(res, &mut needed); + } + for arg in ep + .function + .arguments + .iter() + .filter_map(|a| a.binding.as_ref()) + { + check_binding(arg, &mut needed); + } } if module @@ -346,28 +366,32 @@ impl Writer { .iter() .any(|gv| gv.1.space == crate::AddressSpace::TaskPayload) { - needs_mesh_shaders = true; + needed.mesh_shaders = true; } // Write required declarations let mut any_written = false; - if needs_f16 { + if needed.f16 { writeln!(self.out, "enable f16;")?; any_written = true; } - if needs_dual_source_blending { + if needed.dual_source_blending { writeln!(self.out, "enable dual_source_blending;")?; any_written = true; } - if needs_clip_distances { + if needed.clip_distances { writeln!(self.out, "enable clip_distances;")?; any_written = true; } - if needs_mesh_shaders { + if needed.mesh_shaders { writeln!(self.out, "enable wgpu_mesh_shader;")?; any_written = true; } - if needs_cooperative_matrix { + if needed.primitive_index { + writeln!(self.out, "enable primitive_index;")?; + any_written = true; + } + if needed.cooperative_matrix { writeln!(self.out, "enable wgpu_cooperative_matrix;")?; any_written = true; } diff --git a/naga/src/front/wgsl/parse/conv.rs b/naga/src/front/wgsl/parse/conv.rs index d951ab0b0..7160ed6d5 100644 --- a/naga/src/front/wgsl/parse/conv.rs +++ b/naga/src/front/wgsl/parse/conv.rs @@ -21,14 +21,8 @@ pub fn map_address_space<'a>( "immediate" => Ok(crate::AddressSpace::Immediate), "function" => Ok(crate::AddressSpace::Function), "task_payload" => { - if enable_extensions.contains(ImplementedEnableExtension::WgpuMeshShader) { - Ok(crate::AddressSpace::TaskPayload) - } else { - Err(Box::new(Error::EnableExtensionNotEnabled { - span, - kind: ImplementedEnableExtension::WgpuMeshShader.into(), - })) - } + enable_extensions.require(ImplementedEnableExtension::WgpuMeshShader, span)?; + Ok(crate::AddressSpace::TaskPayload) } "ray_payload" => { if enable_extensions.contains(ImplementedEnableExtension::WgpuRayTracingPipeline) { @@ -154,12 +148,11 @@ pub fn map_built_in( }; match built_in { crate::BuiltIn::ClipDistance => { - if !enable_extensions.contains(ImplementedEnableExtension::ClipDistances) { - return Err(Box::new(Error::EnableExtensionNotEnabled { - span, - kind: ImplementedEnableExtension::ClipDistances.into(), - })); - } + enable_extensions.require(ImplementedEnableExtension::ClipDistances, span)? + } + + crate::BuiltIn::PrimitiveIndex => { + enable_extensions.require(ImplementedEnableExtension::PrimitiveIndex, span)? } crate::BuiltIn::CullPrimitive | crate::BuiltIn::PointIndex @@ -169,12 +162,7 @@ pub fn map_built_in( | crate::BuiltIn::Vertices | crate::BuiltIn::PrimitiveCount | crate::BuiltIn::Primitives => { - if !enable_extensions.contains(ImplementedEnableExtension::WgpuMeshShader) { - return Err(Box::new(Error::EnableExtensionNotEnabled { - span, - kind: ImplementedEnableExtension::WgpuMeshShader.into(), - })); - } + enable_extensions.require(ImplementedEnableExtension::WgpuMeshShader, span)? } _ => {} } diff --git a/naga/src/front/wgsl/parse/directive/enable_extension.rs b/naga/src/front/wgsl/parse/directive/enable_extension.rs index ca438b2f4..85ea4dbfb 100644 --- a/naga/src/front/wgsl/parse/directive/enable_extension.rs +++ b/naga/src/front/wgsl/parse/directive/enable_extension.rs @@ -19,6 +19,7 @@ pub(crate) struct EnableExtensions { f16: bool, clip_distances: bool, wgpu_cooperative_matrix: bool, + primitive_index: bool, } impl EnableExtensions { @@ -32,6 +33,7 @@ impl EnableExtensions { dual_source_blending: false, clip_distances: false, wgpu_cooperative_matrix: false, + primitive_index: false, } } @@ -50,6 +52,7 @@ impl EnableExtensions { ImplementedEnableExtension::F16 => &mut self.f16, ImplementedEnableExtension::ClipDistances => &mut self.clip_distances, ImplementedEnableExtension::WgpuCooperativeMatrix => &mut self.wgpu_cooperative_matrix, + ImplementedEnableExtension::PrimitiveIndex => &mut self.primitive_index, }; *field = true; } @@ -67,6 +70,22 @@ impl EnableExtensions { ImplementedEnableExtension::F16 => self.f16, ImplementedEnableExtension::ClipDistances => self.clip_distances, ImplementedEnableExtension::WgpuCooperativeMatrix => self.wgpu_cooperative_matrix, + ImplementedEnableExtension::PrimitiveIndex => self.primitive_index, + } + } + + pub(crate) fn require( + &self, + ext: ImplementedEnableExtension, + span: Span, + ) -> Result<'static, ()> { + if !self.contains(ext) { + Err(Box::new(Error::EnableExtensionNotEnabled { + span, + kind: ext.into(), + })) + } else { + Ok(()) } } } @@ -124,9 +143,7 @@ impl EnableExtension { Self::Implemented(ImplementedEnableExtension::WgpuCooperativeMatrix) } Self::SUBGROUPS => Self::Unimplemented(UnimplementedEnableExtension::Subgroups), - Self::PRIMITIVE_INDEX => { - Self::Unimplemented(UnimplementedEnableExtension::PrimitiveIndex) - } + Self::PRIMITIVE_INDEX => Self::Implemented(ImplementedEnableExtension::PrimitiveIndex), _ => return Err(Box::new(Error::UnknownEnableExtension(span, word))), }) } @@ -144,11 +161,11 @@ impl EnableExtension { ImplementedEnableExtension::DualSourceBlending => Self::DUAL_SOURCE_BLENDING, ImplementedEnableExtension::F16 => Self::F16, ImplementedEnableExtension::ClipDistances => Self::CLIP_DISTANCES, + ImplementedEnableExtension::PrimitiveIndex => Self::PRIMITIVE_INDEX, ImplementedEnableExtension::WgpuRayTracingPipeline => Self::RAY_TRACING_PIPELINE, }, Self::Unimplemented(kind) => match kind { UnimplementedEnableExtension::Subgroups => Self::SUBGROUPS, - UnimplementedEnableExtension::PrimitiveIndex => Self::PRIMITIVE_INDEX, }, } } @@ -186,6 +203,12 @@ pub enum ImplementedEnableExtension { WgpuRayTracingPipeline, /// Enables the `wgpu_cooperative_matrix` extension, native only. WgpuCooperativeMatrix, + /// Enables the `@builtin(primitive_index)` attribute in WGSL. + /// + /// In the WGSL standard, this corresponds to [`enable primitive-index;`]. + /// + /// [`enable primitive-index;`]: https://www.w3.org/TR/WGSL/#extension-primitive_index + PrimitiveIndex, } impl ImplementedEnableExtension { @@ -199,6 +222,7 @@ impl ImplementedEnableExtension { Self::WgpuRayQueryVertexReturn, Self::WgpuRayTracingPipeline, Self::WgpuCooperativeMatrix, + Self::PrimitiveIndex, ]; /// Returns slice of all variants of [`ImplementedEnableExtension`]. @@ -218,6 +242,7 @@ impl ImplementedEnableExtension { Self::WgpuRayQueryVertexReturn => C::RAY_HIT_VERTEX_POSITION, Self::WgpuCooperativeMatrix => C::COOPERATIVE_MATRIX, Self::WgpuRayTracingPipeline => C::RAY_TRACING_PIPELINE, + Self::PrimitiveIndex => C::PRIMITIVE_INDEX, } } } @@ -241,19 +266,12 @@ pub enum UnimplementedEnableExtension { /// /// [`enable subgroups;`]: https://www.w3.org/TR/WGSL/#extension-subgroups Subgroups, - /// Enables the `@builtin(primitive_index)` attribute in WGSL. - /// - /// In the WGSL standard, this corresponds to [`enable primitive-index;`]. - /// - /// [`enable primitive-index;`]: https://www.w3.org/TR/WGSL/#extension-primitive_index - PrimitiveIndex, } impl UnimplementedEnableExtension { pub(crate) const fn tracking_issue_num(self) -> u16 { match self { Self::Subgroups => 5555, - Self::PrimitiveIndex => 8236, } } } diff --git a/naga/tests/in/wgsl/extra.wgsl b/naga/tests/in/wgsl/extra.wgsl index 2ae3ddf01..5a299a7b1 100644 --- a/naga/tests/in/wgsl/extra.wgsl +++ b/naga/tests/in/wgsl/extra.wgsl @@ -1,3 +1,5 @@ +enable primitive_index; + struct ImmediateData { index: u32, double: vec2, diff --git a/naga/tests/in/wgsl/primitive-index-mesh.toml b/naga/tests/in/wgsl/primitive-index-mesh.toml new file mode 100644 index 000000000..4a25845ef --- /dev/null +++ b/naga/tests/in/wgsl/primitive-index-mesh.toml @@ -0,0 +1,8 @@ +# Tests on GLES + +capabilities = "PRIMITIVE_INDEX" +targets = "GLSL" + +[glsl] +version.Embedded.version = 320 +version.Embedded.is_webgl = false diff --git a/naga/tests/in/wgsl/primitive-index-mesh.wgsl b/naga/tests/in/wgsl/primitive-index-mesh.wgsl new file mode 100644 index 000000000..74760634c --- /dev/null +++ b/naga/tests/in/wgsl/primitive-index-mesh.wgsl @@ -0,0 +1,6 @@ +enable primitive_index; + +@fragment +fn func(@builtin(primitive_index) index: u32) -> @location(0) vec4 { + return vec4(f32(index), 1.0, 1.0, 1.0); +} diff --git a/naga/tests/in/wgsl/primitive-index.toml b/naga/tests/in/wgsl/primitive-index.toml new file mode 100644 index 000000000..3130e3afc --- /dev/null +++ b/naga/tests/in/wgsl/primitive-index.toml @@ -0,0 +1,12 @@ +capabilities = "PRIMITIVE_INDEX" +targets = "WGSL | SPIRV | HLSL | METAL | GLSL" + +[spv] +version = [1, 4] +capabilities = ["Geometry"] + +[glsl] +version.Desktop = 450 + +[msl] +lang_version = [2, 3] diff --git a/naga/tests/in/wgsl/primitive-index.wgsl b/naga/tests/in/wgsl/primitive-index.wgsl new file mode 100644 index 000000000..74760634c --- /dev/null +++ b/naga/tests/in/wgsl/primitive-index.wgsl @@ -0,0 +1,6 @@ +enable primitive_index; + +@fragment +fn func(@builtin(primitive_index) index: u32) -> @location(0) vec4 { + return vec4(f32(index), 1.0, 1.0, 1.0); +} diff --git a/naga/tests/naga/spirv_capabilities.rs b/naga/tests/naga/spirv_capabilities.rs index 723d22d1e..809df877d 100644 --- a/naga/tests/naga/spirv_capabilities.rs +++ b/naga/tests/naga/spirv_capabilities.rs @@ -164,6 +164,7 @@ fn geometry() { require( &[Ca::Geometry], r#" + enable primitive_index; @fragment fn f(@builtin(primitive_index) x: u32) { } "#, diff --git a/naga/tests/naga/wgsl_errors.rs b/naga/tests/naga/wgsl_errors.rs index cd5a6eaad..9dc4f938b 100644 --- a/naga/tests/naga/wgsl_errors.rs +++ b/naga/tests/naga/wgsl_errors.rs @@ -4210,13 +4210,10 @@ fn invalid_clip_distances() { #[test] fn recognized_but_unimplemented_enable_extension() { - for extension in [ - naga::front::wgsl::UnimplementedEnableExtension::Subgroups, - naga::front::wgsl::UnimplementedEnableExtension::PrimitiveIndex, - ] { - // NOTE: We match exhaustively here to help maintainers add or remove variants to the above - // array. - let snapshot = match extension { + let extension = naga::front::wgsl::UnimplementedEnableExtension::Subgroups; + // NOTE: We match exhaustively here to help maintainers add or remove variants to the above + // array. + let snapshot = match extension { naga::front::wgsl::UnimplementedEnableExtension::Subgroups => "\ error: the `subgroups` enable-extension is not yet supported ┌─ wgsl:1:8 @@ -4226,26 +4223,15 @@ error: the `subgroups` enable-extension is not yet supported │ = note: Let Naga maintainers know that you ran into this at , so they can prioritize it! -", - naga::front::wgsl::UnimplementedEnableExtension::PrimitiveIndex => "\ -error: the `primitive_index` enable-extension is not yet supported - ┌─ wgsl:1:8 - │ -1 │ enable primitive_index; - │ ^^^^^^^^^^^^^^^ this enable-extension specifies standard functionality which is not yet implemented in Naga - │ - = note: Let Naga maintainers know that you ran into this at , so they can prioritize it! - ", }; - let shader = { - let extension = naga::front::wgsl::EnableExtension::Unimplemented(extension); - format!("enable {};", extension.to_ident()) - }; + let shader = { + let extension = naga::front::wgsl::EnableExtension::Unimplemented(extension); + format!("enable {};", extension.to_ident()) + }; - check(&shader, snapshot); - } + check(&shader, snapshot); } #[test] diff --git a/naga/tests/out/glsl/wgsl-primitive-index-mesh.func.Fragment.glsl b/naga/tests/out/glsl/wgsl-primitive-index-mesh.func.Fragment.glsl new file mode 100644 index 000000000..975343e96 --- /dev/null +++ b/naga/tests/out/glsl/wgsl-primitive-index-mesh.func.Fragment.glsl @@ -0,0 +1,13 @@ +#version 320 es + +precision highp float; +precision highp int; + +layout(location = 0) out vec4 _fs2p_location0; + +void main() { + uint index = uint(gl_PrimitiveID); + _fs2p_location0 = vec4(float(index), 1.0, 1.0, 1.0); + return; +} + diff --git a/naga/tests/out/glsl/wgsl-primitive-index.func.Fragment.glsl b/naga/tests/out/glsl/wgsl-primitive-index.func.Fragment.glsl new file mode 100644 index 000000000..971d15c7e --- /dev/null +++ b/naga/tests/out/glsl/wgsl-primitive-index.func.Fragment.glsl @@ -0,0 +1,9 @@ +#version 450 core +layout(location = 0) out vec4 _fs2p_location0; + +void main() { + uint index = uint(gl_PrimitiveID); + _fs2p_location0 = vec4(float(index), 1.0, 1.0, 1.0); + return; +} + diff --git a/naga/tests/out/hlsl/wgsl-primitive-index.hlsl b/naga/tests/out/hlsl/wgsl-primitive-index.hlsl new file mode 100644 index 000000000..113457870 --- /dev/null +++ b/naga/tests/out/hlsl/wgsl-primitive-index.hlsl @@ -0,0 +1,9 @@ +struct FragmentInput_func { + uint index_1 : SV_PrimitiveID; +}; + +float4 func(FragmentInput_func fragmentinput_func) : SV_Target0 +{ + uint index = fragmentinput_func.index_1; + return float4(float(index), 1.0, 1.0, 1.0); +} diff --git a/naga/tests/out/hlsl/wgsl-primitive-index.ron b/naga/tests/out/hlsl/wgsl-primitive-index.ron new file mode 100644 index 000000000..9000dde58 --- /dev/null +++ b/naga/tests/out/hlsl/wgsl-primitive-index.ron @@ -0,0 +1,12 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"func", + target_profile:"ps_5_1", + ), + ], + compute:[ + ], +) diff --git a/naga/tests/out/msl/wgsl-primitive-index.metal b/naga/tests/out/msl/wgsl-primitive-index.metal new file mode 100644 index 000000000..3f210e4c5 --- /dev/null +++ b/naga/tests/out/msl/wgsl-primitive-index.metal @@ -0,0 +1,17 @@ +// language: metal2.3 +#include +#include + +using metal::uint; + + +struct funcInput { +}; +struct funcOutput { + metal::float4 member [[color(0)]]; +}; +fragment funcOutput func( + uint index [[primitive_id]] +) { + return funcOutput { metal::float4(static_cast(index), 1.0, 1.0, 1.0) }; +} diff --git a/naga/tests/out/spv/wgsl-primitive-index.spvasm b/naga/tests/out/spv/wgsl-primitive-index.spvasm new file mode 100644 index 000000000..439accfce --- /dev/null +++ b/naga/tests/out/spv/wgsl-primitive-index.spvasm @@ -0,0 +1,33 @@ +; SPIR-V +; Version: 1.4 +; Generator: rspirv +; Bound: 18 +OpCapability Shader +OpCapability Geometry +%1 = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %12 "func" %7 %10 +OpExecutionMode %12 OriginUpperLeft +OpDecorate %7 BuiltIn PrimitiveId +OpDecorate %7 Flat +OpDecorate %10 Location 0 +%2 = OpTypeVoid +%3 = OpTypeInt 32 0 +%5 = OpTypeFloat 32 +%4 = OpTypeVector %5 4 +%8 = OpTypePointer Input %3 +%7 = OpVariable %8 Input +%11 = OpTypePointer Output %4 +%10 = OpVariable %11 Output +%13 = OpTypeFunction %2 +%14 = OpConstant %5 1 +%12 = OpFunction %2 None %13 +%6 = OpLabel +%9 = OpLoad %3 %7 +OpBranch %15 +%15 = OpLabel +%16 = OpConvertUToF %5 %9 +%17 = OpCompositeConstruct %4 %16 %14 %14 %14 +OpStore %10 %17 +OpReturn +OpFunctionEnd \ No newline at end of file diff --git a/naga/tests/out/wgsl/wgsl-extra.wgsl b/naga/tests/out/wgsl/wgsl-extra.wgsl index 02d185be0..3cfd0145d 100644 --- a/naga/tests/out/wgsl/wgsl-extra.wgsl +++ b/naga/tests/out/wgsl/wgsl-extra.wgsl @@ -1,3 +1,5 @@ +enable primitive_index; + struct ImmediateData { index: u32, double: vec2, diff --git a/naga/tests/out/wgsl/wgsl-primitive-index.wgsl b/naga/tests/out/wgsl/wgsl-primitive-index.wgsl new file mode 100644 index 000000000..08b723b48 --- /dev/null +++ b/naga/tests/out/wgsl/wgsl-primitive-index.wgsl @@ -0,0 +1,6 @@ +enable primitive_index; + +@fragment +fn func(@builtin(primitive_index) index: u32) -> @location(0) vec4 { + return vec4(f32(index), 1f, 1f, 1f); +} diff --git a/tests/tests/wgpu-gpu/main.rs b/tests/tests/wgpu-gpu/main.rs index 2689e8410..185732ba8 100644 --- a/tests/tests/wgpu-gpu/main.rs +++ b/tests/tests/wgpu-gpu/main.rs @@ -48,6 +48,7 @@ mod pipeline; mod pipeline_cache; mod planar_texture; mod poll; +mod primitive_index; mod query_set; mod queue_transfer; mod ray_tracing; @@ -114,6 +115,7 @@ fn all_tests() -> Vec { pipeline::all_tests(&mut tests); planar_texture::all_tests(&mut tests); poll::all_tests(&mut tests); + primitive_index::all_tests(&mut tests); immediates::all_tests(&mut tests); query_set::all_tests(&mut tests); queue_transfer::all_tests(&mut tests); diff --git a/tests/tests/wgpu-gpu/primitive_index.rs b/tests/tests/wgpu-gpu/primitive_index.rs new file mode 100644 index 000000000..1a0c7ed63 --- /dev/null +++ b/tests/tests/wgpu-gpu/primitive_index.rs @@ -0,0 +1,171 @@ +use wgpu::{ + ColorTargetState, ColorWrites, Features, FragmentState, Limits, MeshPipelineDescriptor, + MeshState, RenderPipelineDescriptor, ShaderModuleDescriptor, TextureFormat, VertexState, +}; +use wgpu_test::{ + gpu_test, FailureCase, GpuTestConfiguration, GpuTestInitializer, TestParameters, TestingContext, +}; + +pub fn all_tests(tests: &mut Vec) { + tests.push(PRIMITIVE_INDEX); + tests.push(PRIMITIVE_INDEX_MESH_FRAGMENT); + tests.push(PRIMITIVE_INDEX_MESH_NOT_FRAGMENT); + tests.push(PRIMITIVE_INDEX_FRAGMENT_NOT_MESH); +} + +async fn primitive_index(ctx: TestingContext) { + const CODE: &str = "\ +enable primitive_index; +@vertex +fn vertex() -> @builtin(position) vec4 { + return vec4(1.0, 1.0, 1.0, 1.0); +} +@fragment +fn fragment(@builtin(primitive_index) index: u32) -> @location(0) vec4 { + return vec4(f32(index), 1.0, 1.0, 1.0); +} +"; + let module = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(CODE)), + }); + let _ = ctx + .device + .create_render_pipeline(&RenderPipelineDescriptor { + label: None, + layout: None, + vertex: VertexState { + module: &module, + entry_point: None, + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(FragmentState { + module: &module, + entry_point: None, + compilation_options: Default::default(), + targets: &[Some(ColorTargetState { + format: TextureFormat::Rgba8Unorm, + blend: None, + write_mask: ColorWrites::all(), + })], + }), + multiview_mask: None, + cache: None, + }); +} + +#[gpu_test] +static PRIMITIVE_INDEX: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters(TestParameters::default().features(Features::SHADER_PRIMITIVE_INDEX)) + .run_async(primitive_index); + +async fn mesh_primitive_index( + ctx: TestingContext, + mesh_primitive_index: bool, + fragment_primitive_index: bool, +) { + const CODE: &str = "\ +enable primitive_index; +enable wgpu_mesh_shader; + +struct VertexOutput { + @builtin(position) position: vec4, +} +struct PrimitiveOutput { + @builtin(triangle_indices) indices: vec3,MESH_PRIMITIVE_INDEX +} +struct MeshOutput { + @builtin(vertices) vertices: array, + @builtin(vertex_count) vertex_count: u32, + @builtin(primitives) primitives: array, + @builtin(primitive_count) primitive_count: u32, +} +var mesh_output: MeshOutput; + +@mesh(mesh_output) +@workgroup_size(1) +fn mesh() { + mesh_output.vertex_count = 0; + mesh_output.primitive_count = 0; +} +@fragment +fn fragment(FRAGMENT_PRIMITIVE_INDEX) -> @location(0) vec4 { + return vec4(f32(index), 1.0, 1.0, 1.0); +} +"; + let used_code = CODE + .replace( + "MESH_PRIMITIVE_INDEX", + if mesh_primitive_index { + "\n@builtin(primitive_index) index: u32," + } else { + "" + }, + ) + .replace( + "FRAGMENT_PRIMITIVE_INDEX", + if fragment_primitive_index { + "@builtin(primitive_index) index: u32" + } else { + "" + }, + ); + let module = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(&used_code)), + }); + let _ = ctx.device.create_mesh_pipeline(&MeshPipelineDescriptor { + label: None, + layout: None, + task: None, + mesh: MeshState { + module: &module, + entry_point: None, + compilation_options: Default::default(), + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(FragmentState { + module: &module, + entry_point: None, + compilation_options: Default::default(), + targets: &[Some(ColorTargetState { + format: TextureFormat::Rgba8Unorm, + blend: None, + write_mask: ColorWrites::all(), + })], + }), + multiview: None, + cache: None, + }); +} + +fn mesh_params() -> TestParameters { + // TODO: when naga support for MSL/HLSL mesh shaders lands enable Metal and DX12 + TestParameters::default() + .features(Features::SHADER_PRIMITIVE_INDEX | Features::EXPERIMENTAL_MESH_SHADER) + .limits(Limits::defaults().using_recommended_minimum_mesh_shader_values()) + .skip(FailureCase::backend( + wgpu::Backends::METAL | wgpu::Backends::DX12, + )) +} + +#[gpu_test] +static PRIMITIVE_INDEX_MESH_FRAGMENT: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters(mesh_params()) + .run_async(async |ctx| mesh_primitive_index(ctx, true, true).await); + +#[gpu_test] +static PRIMITIVE_INDEX_MESH_NOT_FRAGMENT: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters(mesh_params().expect_fail(FailureCase::always())) + .run_async(async |ctx| mesh_primitive_index(ctx, true, false).await); + +#[gpu_test] +static PRIMITIVE_INDEX_FRAGMENT_NOT_MESH: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters(mesh_params().expect_fail(FailureCase::always())) + .run_async(async |ctx| mesh_primitive_index(ctx, false, true).await); diff --git a/tests/tests/wgpu-gpu/shader_primitive_index/primitive_index.wgsl b/tests/tests/wgpu-gpu/shader_primitive_index/primitive_index.wgsl index 8240edfd7..b3779977b 100644 --- a/tests/tests/wgpu-gpu/shader_primitive_index/primitive_index.wgsl +++ b/tests/tests/wgpu-gpu/shader_primitive_index/primitive_index.wgsl @@ -1,3 +1,5 @@ +enable primitive_index; + @vertex fn vs_main(@location(0) xy: vec2) -> @builtin(position) vec4 { return vec4(xy, 0.0, 1.0); diff --git a/wgpu-core/src/validation.rs b/wgpu-core/src/validation.rs index 7aaf45c01..6b45c00ee 100644 --- a/wgpu-core/src/validation.rs +++ b/wgpu-core/src/validation.rs @@ -1687,6 +1687,13 @@ impl Interface { return Err(StageError::MissingFragDepthAttachment); } } + ShaderStageForValidation::Mesh => { + for output in &entry_point.outputs { + if matches!(output, Varying::BuiltIn(naga::BuiltIn::PrimitiveIndex)) { + this_stage_primitive_index = true; + } + } + } _ => (), }