diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 0e8343a02..448f5f59b 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -897,6 +897,8 @@ codec_enum! { IndirectBase, TextureLevelBase(f0), StencilBit, + PatchIndexAddress, + ControlPointIndexAddress, } Symbol { Binding(f0), DescriptorSet(f0), Location(f0), Component(f0), SpecId(f0) } } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index cf77b708c..099ec8087 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2322; +pub const SEMANTICS_VERSION: u32 = 2323; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 2322; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 600; +pub const ARTIFACT_FORMAT_VERSION: u32 = 601; /// The version of what this crate gives a runtime for the runs of a compiled pipeline, beside the /// compile: the device a run opens and what it enables, the Vulkan and Metal vocabularies a runtime diff --git a/crates/metal2vulkan/src/lower/push.rs b/crates/metal2vulkan/src/lower/push.rs index cc2cb7449..fd13f3936 100644 --- a/crates/metal2vulkan/src/lower/push.rs +++ b/crates/metal2vulkan/src/lower/push.rs @@ -176,6 +176,8 @@ pub const fn shape(f: PushField) -> FieldShape { | PushField::CommandRecordsAddress | PushField::ReplayRegionAddress | PushField::TessellationFactorAddress + | PushField::PatchIndexAddress + | PushField::ControlPointIndexAddress | PushField::PrivateArenaAddress => FieldShape::U64, // A Metal address, low word first: the same eight bytes as a `u64`, readable without // `shaderInt64`. @@ -775,25 +777,34 @@ mod tests { } /// The control stage's push range fits below a post-tessellation vertex function's window in - /// either form, with every factor step and scale, so link places it at 0 beside any pair of - /// functions; a fragment function behind such a vertex function that pushes nothing starts - /// past it too, and behind any other at 0. + /// either form, with every factor step, scale and control-point index type the form takes, so + /// link places it at 0 beside any pair of functions; a fragment function behind such a vertex + /// function that pushes nothing starts past it too, and behind any other at 0. #[test] fn the_control_stage_fits_below_a_post_tessellation_window() { + use crate::metal::TessellationControlPointIndexType as IndexType; use crate::metal::TessellationFactorStepFunction as Step; - use crate::pipeline::link::tessellation::control::Control; + use crate::pipeline::link::tessellation::control::{address_fits, Control}; let steps = [ Step::Constant, Step::PerPatch, Step::PerInstance, Step::PerPatchAndPerInstance, ]; + let types = [IndexType::None, IndexType::UInt16, IndexType::UInt32]; for addressed in [false, true] { for step in steps { for scale in [false, true] { - let (bytes, align) = Control::push_bytes(addressed, step, scale); - assert!(bytes <= TESSELLATION_BASE, "{addressed} {step:?} {scale}"); - assert_eq!(TESSELLATION_BASE % align, 0); + for index_type in types { + if addressed && !address_fits(step, scale, index_type) { + continue; + } + let (bytes, align) = + Control::push_bytes(addressed, step, scale, index_type); + let case = format!("{addressed} {step:?} {scale} {index_type:?}"); + assert!(bytes <= TESSELLATION_BASE, "{case}"); + assert_eq!(TESSELLATION_BASE % align, 0); + } } } } diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index a4e1b4a24..1efa71fb1 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -505,9 +505,9 @@ pub enum PrimitiveIdStore { first: FirstVertex, object: usize, }, - /// A post-tessellation vertex function, on every device: Metal's patch index, the patch input - /// the control stage writes (`lower::tessellation`), the same at every vertex the tessellator - /// makes of the patch, so each fragment of each of its triangles reads it. + /// A post-tessellation vertex function, on every device: the patch's position in its draw, + /// the patch input the control stage writes (`lower::tessellation`), the same at every vertex + /// the tessellator makes of the patch, so each fragment of each of its triangles reads it. Patch { object: usize }, } @@ -1997,7 +1997,7 @@ pub(crate) fn metal_point_size(fb: &mut FunctionBuilder<'_>, size: SValue) -> BR /// Store the primitive ID of the primitive the vertex provokes to its varying /// ([`PrimitiveIdStore`]): `(VertexIndex - first) / n`, `n` from -/// `PushField::VerticesPerPrimitive`, or a post-tessellation function's patch index. +/// `PushField::VerticesPerPrimitive`, or a post-tessellation function's patch position. fn store_primitive_id( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, @@ -2021,7 +2021,7 @@ fn store_primitive_id( object, } => (vertex, first, object), PrimitiveIdStore::Patch { object } => { - let id = crate::lower::tessellation::patch_index(cx, fb)?; + let id = crate::lower::tessellation::patch_position(cx, fb)?; return store(cx, fb, &link(object), id); } }; diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index d90048165..87b087a26 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -1503,18 +1503,18 @@ fn first_vertex(cx: &mut SelectCx<'_>) -> super::FirstVertex { /// [`super::PrimitiveIdStore`]): its varying, the vertex index it divides, the draw's first /// vertex (the `BaseVertex` builtin with `shaderDrawParameters`, lane 0 of /// `PushField::BaseVertexInstance` without, as for `[[base_vertex]]`), and -/// `PushField::VerticesPerPrimitive`. A post-tessellation vertex function writes Metal's patch -/// index, its patch input (`lower::tessellation`), which Metal's `[[primitive_id]]` behind it is -/// without a patch index buffer: the patch's position in its draw, patch start included, the -/// same in every instance and at every triangle the tessellator makes of the patch (measured on -/// an Apple M3 Max, two draws of two patches from patch 0 over two instances and from patch 2). +/// `PushField::VerticesPerPrimitive`. A post-tessellation vertex function writes the patch's +/// position, its patch input (`lower::tessellation`), which Metal's `[[primitive_id]]` behind it +/// is: the patch's position in its draw, patch start included, the same in every instance and at +/// every triangle the tessellator makes of the patch, with or without a patch index buffer +/// (measured on an Apple M3 Max). /// A form that reads its draw's indices at their address ([`captured_index_type`]) draws them as /// `index count` vertices from vertex 0: its first vertex is 0 /// ([`super::FirstVertex::Zero`]). The private list form draws its list from its first vertex, /// as a draw without indices does. fn primitive_id_output(cx: &mut SelectCx<'_>) -> Result<(), Error> { if matches!(cx.entry.ep.stage, AirStage::Vertex { patch: Some(_) }) { - crate::lower::tessellation::read_patch_index(cx)?; + crate::lower::tessellation::read_patch_position(cx)?; let object = primitive_id(&mut cx.families.stage_io, IoDir::Output)?; cx.families.stage_io.primitive_id = Some(super::PrimitiveIdStore::Patch { object }); return Ok(()); diff --git a/crates/metal2vulkan/src/lower/tessellation/mod.rs b/crates/metal2vulkan/src/lower/tessellation/mod.rs index f8dd6ea1b..3c4482186 100644 --- a/crates/metal2vulkan/src/lower/tessellation/mod.rs +++ b/crates/metal2vulkan/src/lower/tessellation/mod.rs @@ -51,14 +51,13 @@ //! tessellation stages also needs `multiviewTessellationShader`, the pipeline's to require. //! //! A fragment function's `[[primitive_id]]` behind the function is the flat varying it writes at -//! each return under `LoweringInputs::primitive_id_varying`: Metal's patch index, its patch input -//! (`stage_io::PrimitiveIdStore::Patch`). Without a patch index buffer, Metal's value there is the -//! patch's position in its draw, patch start included, the same in every instance and at every -//! triangle the tessellator makes of the patch (measured on an Apple M3 Max); Vulkan's -//! `PrimitiveId` counts the draw's patches from 0 and restarts in each instance. With a patch -//! index buffer the varying would carry the buffer's index for the patch, Metal's patch index -//! there, where Metal's `[[primitive_id]]` stays the patch's position (measured on an Apple M3 -//! Max); the runtime draws no patches through a patch index buffer. +//! each return under `LoweringInputs::primitive_id_varying`: the patch's position in its draw, a +//! `uint` patch input at the fixed location `TessellationStage::PATCH_POSITION_LOCATION`, which +//! the control stage writes (`stage_io::PrimitiveIdStore::Patch`). Metal's value there is that +//! position, patch start included, the same in every instance and at every triangle the +//! tessellator makes of the patch, with or without a patch index buffer, whose word at the +//! position is the patch index (measured on an Apple M3 Max); Vulkan's `PrimitiveId` counts the +//! draw's patches from 0 and restarts in each instance. //! //! # Without `tessellationShader` //! @@ -224,10 +223,12 @@ pub struct EvalPlan { pub domain: PatchDomain, /// `[[patch(_, N)]]` (0 when unstated). pub control_points: u32, - /// Whether the module declares `TessCoord`, the patch-index input, the instance input, the - /// base-instance input, `ViewIndex`, and the control points' elements. + /// Whether the module declares `TessCoord`, the patch-index input, the patch-position + /// input, the instance input, the base-instance input, `ViewIndex`, and the control points' + /// elements. pub coord: bool, pub patch: bool, + pub position: bool, pub instance: bool, pub base_instance: bool, pub view: bool, @@ -466,6 +467,7 @@ pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { control_points, coord: false, patch: false, + position: false, instance: false, base_instance: false, view: false, @@ -476,10 +478,10 @@ pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { Ok(()) } -/// Declare the patch-index input, which the function's primitive ID varying is +/// Declare the patch-position input, which the function's primitive ID varying is /// (`stage_io::PrimitiveIdStore::Patch`). -pub fn read_patch_index(cx: &mut SelectCx<'_>) -> Result<(), Error> { - eval(cx)?.patch = true; +pub fn read_patch_position(cx: &mut SelectCx<'_>) -> Result<(), Error> { + eval(cx)?.position = true; Ok(()) } @@ -804,6 +806,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { pub struct Declared { pub coord: Option, pub patch: Option, + pub position: Option, pub instance: Option, pub base_instance: Option, pub view: Option, @@ -837,6 +840,10 @@ pub fn declare( let at = TessellationStage::PATCH_INDEX_LOCATION; d.patch = Some(mb.fixed_io(at, IoDir::Input, u32_, true)?); } + if e.position { + let at = TessellationStage::PATCH_POSITION_LOCATION; + d.position = Some(mb.fixed_io(at, IoDir::Input, u32_, true)?); + } if e.instance { let at = TessellationStage::INSTANCE_LOCATION; d.instance = Some(mb.fixed_io(at, IoDir::Input, u32_, true)?); @@ -939,10 +946,11 @@ pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult< Ok(()) } -/// Metal's patch index, the patch-index input ([`read_patch_index`]), loaded here. -pub fn patch_index(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult { - let patch = cx.decl.families.tessellation.patch; - load(cx, fb, patch) +/// The patch's position in its draw, the patch-position input ([`read_patch_position`]), +/// loaded here. +pub fn patch_position(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult { + let position = cx.decl.families.tessellation.position; + load(cx, fb, position) } /// The value of builtin `b` of the evaluation entry in its lowered representation, loaded at diff --git a/crates/metal2vulkan/src/pipeline/graphics.rs b/crates/metal2vulkan/src/pipeline/graphics.rs index 352d1fcf5..37786e8ba 100644 --- a/crates/metal2vulkan/src/pipeline/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/graphics.rs @@ -224,10 +224,11 @@ pub struct TessellationState { /// instance stride, the factor scale, the patch index buffer's residual bind offset, and /// whether the draw binds one; and a sixth, the control-point index buffer's residual bind /// offset, for a pipeline with a control-point index type. Under the identity domains the - /// control stage binds no buffer and reads the factors through their address: its fields - /// (`PushField::TessellationFactorAddress`, and where read the instance stride and the scale) - /// are a vertex-stage placement of `PipelineInterface::push` from this offset, and it reads - /// no patch index buffer. + /// control stage binds no buffer and reads the factors and the indices through their + /// addresses: its fields (`PushField::TessellationFactorAddress`, + /// `PushField::PatchIndexAddress`, and where read `PushField::ControlPointIndexAddress` or the + /// instance stride and the scale) are a vertex-stage placement of `PipelineInterface::push` + /// from this offset. pub push_offset: u32, /// The descriptor's `tessellationControlPointIndexType`: other than `None`, the pipeline /// draws indexed patches only (`DrawCall::IndexedPatches`), whose control-point index buffer diff --git a/crates/metal2vulkan/src/pipeline/interface.rs b/crates/metal2vulkan/src/pipeline/interface.rs index f9dc94607..7cf537a31 100644 --- a/crates/metal2vulkan/src/pipeline/interface.rs +++ b/crates/metal2vulkan/src/pipeline/interface.rs @@ -634,8 +634,10 @@ impl LevelReads {} /// pipeline's control stage: its patch domain and Metal's control points per patch. It reads the /// patch index and the instance as `uint` patch inputs at /// [`TessellationStage::PATCH_INDEX_LOCATION`] and [`TessellationStage::INSTANCE_LOCATION`], -/// and, on a profile with `shaderDrawParameters`, the base instance at -/// [`TessellationStage::BASE_INSTANCE_LOCATION`], which the control stage writes. +/// on a profile with `shaderDrawParameters` the base instance at +/// [`TessellationStage::BASE_INSTANCE_LOCATION`], and, where it writes the primitive ID's +/// varying, the patch's position at [`TessellationStage::PATCH_POSITION_LOCATION`], which the +/// control stage writes. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -654,10 +656,15 @@ impl TessellationStage { /// The patch input holding the draw's base instance (`[[base_instance]]`), on a profile with /// `shaderDrawParameters`. pub const BASE_INSTANCE_LOCATION: u32 = 2; + /// The patch input holding the patch's position in its draw (`patchStart` plus its index in + /// the draw), which a fragment function's `[[primitive_id]]` behind the function is: Metal's + /// patch index there is the patch index buffer's word at the position, where the draw has + /// one. + pub const PATCH_POSITION_LOCATION: u32 = 3; /// The patch input holding the element of each of the patch's control points: a `uvec4` array /// of `ceil(N / 4)` elements, control point `k`'s element in component `k % 4` of element `k / /// 4`, from this location on. - pub const CONTROL_POINT_LOCATION: u32 = 3; + pub const CONTROL_POINT_LOCATION: u32 = 4; /// The evaluation stage of a `domain` patch of `control_points` control points. pub fn new(domain: PatchDomain, control_points: u32) -> TessellationStage { diff --git a/crates/metal2vulkan/src/pipeline/link/tessellation/control.rs b/crates/metal2vulkan/src/pipeline/link/tessellation/control.rs index 3bf0c3955..6cffd5c9a 100644 --- a/crates/metal2vulkan/src/pipeline/link/tessellation/control.rs +++ b/crates/metal2vulkan/src/pipeline/link/tessellation/control.rs @@ -16,7 +16,9 @@ //! `TessellationStage::BASE_INSTANCE_LOCATION`; //! - the **control stage** ([`control_module`]), one invocation per patch (`OutputVertices` 1), //! hands the evaluation stage Metal's patch index ([`patch_index`]), the instance index and the -//! base instance as patch outputs at the same locations, and each of the patch's `N` control +//! base instance as patch outputs at the same locations, the patch's position at +//! `TessellationStage::PATCH_POSITION_LOCATION` (a fragment function's `[[primitive_id]]` +//! behind the evaluation stage, whatever the patch index), and each of the patch's `N` control //! points' elements ([`elements`]) from `TessellationStage::CONTROL_POINT_LOCATION`, and writes //! the patch's tessellation levels from its factors ([`levels`]); //! - the post-tessellation vertex function's evaluation stage, then the fragment stage. @@ -114,11 +116,18 @@ //! `PushField::TessellationFactorAddress` (the factor buffer's address plus the encoder's offset, a //! `u64`), at the same bytes and with the same rules as above, from the word that holds the even //! byte the address names, and no word past the one that holds the last factor's byte. Nothing -//! contains the read: as Metal's own, a read past the buffer reads whatever memory is there. The patch index is the patch's position: the form reads no patch -//! index buffer, and its consumer refuses a draw that names one. A control-point index type is not -//! implemented in it ([`super::control_plan`]). Its push fields ([`address_fields`]) are the -//! address and, where read, the instance stride and the scale, which the pipeline's interface -//! places as its vertex stage's (`PipelineInterface::push`). +//! contains the read: as Metal's own, a read past the buffer reads whatever memory is there. The +//! patch indices and the control-point indices are read the same way, through their addresses +//! and unchecked: the patch index is the word at the pushed `PatchIndexAddress` (the patch index +//! buffer's address plus the draw's offset) plus `4 · position`, read only where that address is +//! not 0 (a draw without a patch index buffer, whose patch index is the position); control point +//! `k`'s element is the `ushort` or `uint` at the pushed `ControlPointIndexAddress` plus +//! `(p · N + k) · size`, a `ushort` from the word that holds it. Its push fields +//! ([`address_fields`]) are the factors' address, the patch indices' address and either the +//! control-point indices' address (a control-point index type) or, where read, the instance +//! stride and the scale, within [`PUSH_BYTES`]; a control-point index type with a per-instance +//! step or a scale is not implemented in it ([`address_fits`], [`super::control_plan`]). The +//! pipeline's interface places them as its vertex stage's (`PipelineInterface::push`). //! //! Noted on the pipeline's evaluation stage ([`Control::notes`]): the output winding's vertex //! order, measured on four drivers (above) and not on the rest; and, read from Metal's @@ -138,6 +147,7 @@ use crate::metal::{ use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::interface::{PatchDomain, TessellationStage}; use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, SyntheticBinding}; +use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; use crate::spirv::ids::{GlobalId, TypeId, Value}; @@ -186,21 +196,39 @@ pub const PUSH_FIELDS: [PushField; 6] = [ /// Bytes of the control stage's push range. pub const PUSH_BYTES: u32 = 24; -/// The address form's push fields (the module docs), for step function `step` and a scale -/// enabled or not: each with its byte offset from the stage's push offset, a multiple of 8. The -/// factors' address (`u64`), then, where the stage reads them, the instance stride (`u32`, a -/// per-instance step) and the scale (`float`). -pub fn address_fields(step: Step, scale_enabled: bool) -> Vec<(PushField, u32)> { +/// The address form's push fields (the module docs), for step function `step`, a scale enabled +/// or not and control-point index type `index_type`: each with its byte offset from the stage's +/// push offset. The factors' address (`u64`) at 0; then, without an index type, where the stage +/// reads them, the instance stride (`u32`, a per-instance step) at 8 and the scale (`float`) at +/// 12, and with one the control-point indices' address (`u64`) at 8; and the patch indices' +/// address (`u64`) at 16. Within [`PUSH_BYTES`] wherever [`address_fits`]. +pub fn address_fields( + step: Step, + scale_enabled: bool, + index_type: IndexType, +) -> Vec<(PushField, u32)> { let mut fields = vec![(PushField::TessellationFactorAddress, 0)]; - if per_instance(step) { - fields.push((PushField::TessellationFactorInstanceStride, 8)); - } - if scale_enabled { - fields.push((PushField::TessellationFactorScale, 12)); + if index_type != IndexType::None { + fields.push((PushField::ControlPointIndexAddress, 8)); + } else { + if per_instance(step) { + fields.push((PushField::TessellationFactorInstanceStride, 8)); + } + if scale_enabled { + fields.push((PushField::TessellationFactorScale, 12)); + } } + fields.push((PushField::PatchIndexAddress, 16)); fields } +/// Whether the address form's fields fit their [`PUSH_BYTES`]: the control-point indices' +/// address takes the place of the instance stride and the scale, so a control-point index type +/// goes with neither a per-instance step nor a scale there. +pub fn address_fits(step: Step, scale_enabled: bool, index_type: IndexType) -> bool { + index_type == IndexType::None || !(per_instance(step) || scale_enabled) +} + /// Whether step function `step` addresses a patch's factors by its instance. fn per_instance(step: Step) -> bool { matches!(step, Step::PerInstance | Step::PerPatchAndPerInstance) @@ -246,12 +274,17 @@ impl Control { } /// Bytes and alignment of the stage's push range: [`PUSH_BYTES`] of words, or the address - /// form's fields ([`address_fields`]), 8-aligned for the address. - pub fn push_bytes(addressed: bool, step: Step, scale_enabled: bool) -> (u32, u32) { + /// form's fields ([`address_fields`]), 8-aligned for the addresses. + pub fn push_bytes( + addressed: bool, + step: Step, + scale_enabled: bool, + index_type: IndexType, + ) -> (u32, u32) { match addressed { false => (PUSH_BYTES, 4), true => { - let end = (address_fields(step, scale_enabled).iter()) + let end = (address_fields(step, scale_enabled, index_type).iter()) .map(|&(field, at)| at + crate::lower::push::shape(field).size()) .max() .unwrap_or(0); @@ -313,10 +346,12 @@ impl Control { /// Where the control stage reads what a draw binds: the factor buffer, the patch index buffer, /// and, for a pipeline with a control-point index type, the control-point index buffer (each a /// `Block { uint[] }` storage buffer), and the push block with [`PUSH_FIELDS`] at member indices -/// `members`. In the address form no buffer is bound, and `members` holds the member of each of -/// [`address_fields`] at its field's place in [`PUSH_FIELDS`] (the address at the offset's). +/// `members`. In the address form (`addressed`) no buffer is bound, and `members` holds the member +/// of each of [`address_fields`] at its field's place in [`PUSH_FIELDS`] (each address at its +/// buffer's offset's). #[derive(Clone, Copy, Debug)] pub struct Sources { + pub addressed: bool, pub factors: Option, pub patch_indices: Option, pub control_point_indices: Option, @@ -339,16 +374,19 @@ pub fn declare_sources(mb: &mut ModuleBuilder, c: &Control) -> BResult signed: false, })?; let mut members = [0; 6]; - for (field, at) in address_fields(c.step, c.scale_enabled) { + for (field, at) in address_fields(c.step, c.scale_enabled, c.index_type) { let (k, ty) = match field { PushField::TessellationFactorInstanceStride => (1, u32_), PushField::TessellationFactorScale => (2, f32_), + PushField::PatchIndexAddress => (3, u64_), + PushField::ControlPointIndexAddress => (5, u64_), _ => (0, u64_), }; members[k] = mb.push_member(field, ty, c.push_offset + at)?.index; } let push = mb.push_global()?; return Ok(Sources { + addressed: true, factors: None, patch_indices: None, control_point_indices: None, @@ -379,6 +417,7 @@ pub fn declare_sources(mb: &mut ModuleBuilder, c: &Control) -> BResult } let push = mb.push_global()?; Ok(Sources { + addressed: false, factors: Some(factors), patch_indices: Some(patch_indices), control_point_indices, @@ -420,6 +459,50 @@ fn push_word(fb: &mut FunctionBuilder<'_>, push: GlobalId, member: u32) -> BResu fb.load(ptr, MemAccess::default()) } +/// A `u64` constant. +fn k64(fb: &mut FunctionBuilder<'_>, v: u64) -> BResult { + let u64_ = fb.module().ty(Type::Int { + width: 64, + signed: false, + })?; + let c = fb.module().constant(Constant::Scalar { + ty: u64_, + bits: ConstBits(v), + })?; + fb.module().const_value(c) +} + +/// The device address `base + size · index` (`base` a `u64`, `index` a `uint`), in `u64`. +fn scaled_address( + fb: &mut FunctionBuilder<'_>, + base: Value, + index: Value, + size: u64, +) -> BResult { + let u64_ = fb.module().ty(Type::Int { + width: 64, + signed: false, + })?; + let wide = fb.convert(ConvOp::UConvert, index, u64_)?; + let size = k64(fb, size)?; + let offset = fb.binary(BinOp::IMul, wide, size)?; + fb.binary(BinOp::IAdd, base, offset) +} + +/// The word at device address `at` (a `u64`, a multiple of 4), loaded through a read-only +/// `PhysicalStorageBuffer` pointer, unchecked, as the address form's factors are. +fn address_word(fb: &mut FunctionBuilder<'_>, at: Value) -> BResult { + let u32_ = uint(fb)?; + let ptr = fb.device_place_read_only(at, u32_)?; + fb.load( + ptr, + MemAccess { + aligned: Some(4), + ..MemAccess::default() + }, + ) +} + /// The `float` value of a finite positive `half` `h` (bits in `[0x0001, 0x7bff]`, a `uint`), /// exactly: its significand (the implicit bit set for a normal one) converted and scaled by /// `2^(max(e, 1) - 25)` as `Ldexp` by `max(e, 1)` and a multiply by `2^-25`, both exact since the @@ -482,8 +565,22 @@ fn pow2(fb: &mut FunctionBuilder<'_>, x: Value) -> BResult { /// patch's index in the draw): the patch index buffer's word at byte `residual + 4 · position` /// of its bound range (wrapping `u32`; the pushed residual bind offset is a multiple of 4 modulo /// `2^32`), 0 where the range does not hold it, when the pushed `PatchIndexBound` is nonzero; -/// `position` otherwise, and in the address form (the module docs). +/// `position` otherwise. In the address form, the word at the pushed `PatchIndexAddress` plus +/// `4 · position`, read only where that address is not 0, and `position` where it is (the +/// module docs). pub fn patch_index(fb: &mut FunctionBuilder<'_>, src: &Sources, position: Value) -> BResult { + if src.addressed { + let base = push_word(fb, src.push, src.members[3])?; + let zero = k64(fb, 0)?; + let bound = fb.binary(BinOp::INotEqual, base, zero)?; + let read: ArmFn<'_, ()> = Box::new(move |fb, _| { + let at = scaled_address(fb, base, position, 4)?; + Ok(ArmEnd::FallThrough(vec![address_word(fb, at)?])) + }); + let keep: ArmFn<'_, ()> = Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![position]))); + let merged = fb.if_(&mut (), bound, read, Some(keep))?; + return Ok(merged.0[0]); + } let Some(patch_indices) = src.patch_indices else { return Ok(position); }; @@ -504,7 +601,9 @@ pub fn patch_index(fb: &mut FunctionBuilder<'_>, src: &Sources, position: Value) /// (the module docs): control point `k`'s is `patch · N + k` (wrapping `u32`), or, with a /// control-point index type, the index there in the control-point index buffer: the `uint` or /// `ushort` at byte `residual + e · size` of its bound range (wrapping `u32`, the pushed residual -/// a multiple of the size modulo `2^32`), 0 where the range does not hold it. +/// a multiple of the size modulo `2^32`), 0 where the range does not hold it. In the address +/// form, the index at the pushed `ControlPointIndexAddress` plus `e · size`, unchecked: a +/// `ushort` from the word that holds it. pub fn elements( fb: &mut FunctionBuilder<'_>, c: &Control, @@ -513,6 +612,37 @@ pub fn elements( ) -> BResult> { let n = ku(fb, c.control_points)?; let first = fb.binary(BinOp::IMul, patch, n)?; + if src.addressed && c.index_type != IndexType::None { + let base = push_word(fb, src.push, src.members[5])?; + let size = match c.index_type { + IndexType::UInt16 => 2, + _ => 4, + }; + let mut out = Vec::with_capacity(c.control_points as usize); + for k in 0..c.control_points { + let k = ku(fb, k)?; + let e = fb.binary(BinOp::IAdd, first, k)?; + let at = scaled_address(fb, base, e, size)?; + if size == 4 { + out.push(address_word(fb, at)?); + continue; + } + // The `ushort` in the word's low half at a multiple of 4, its high half otherwise. + let aligned = k64(fb, !3)?; + let word_at = fb.binary(BinOp::BitwiseAnd, at, aligned)?; + let w = address_word(fb, word_at)?; + let u32_ = uint(fb)?; + let low = fb.convert(ConvOp::UConvert, at, u32_)?; + let two = ku(fb, 2)?; + let half = fb.binary(BinOp::BitwiseAnd, low, two)?; + let three = ku(fb, 3)?; + let shift = fb.binary(BinOp::ShiftLeftLogical, half, three)?; + let w = fb.binary(BinOp::ShiftRightLogical, w, shift)?; + let mask = ku(fb, 0xffff)?; + out.push(fb.binary(BinOp::BitwiseAnd, w, mask)?); + } + return Ok(out); + } let residual = match src.control_point_indices { Some(_) => Some(push_word(fb, src.push, src.members[5])?), None => None, @@ -856,6 +986,12 @@ pub fn control_module(c: &Control) -> BResult { true => Some(io(TessellationStage::BASE_INSTANCE_LOCATION)?), false => None, }; + let position_out = mb.fixed_io( + TessellationStage::PATCH_POSITION_LOCATION, + IoDir::Output, + u32_, + true, + )?; let elements_out = match c.control_points { 0 => None, n => { @@ -884,10 +1020,12 @@ pub fn control_module(c: &Control) -> BResult { None => None, }; let patch = patch_index(&mut fb, &src, position)?; - for (to, v) in [(patch_io.1, patch), (instance_io.1, instance)] - .into_iter() - .chain(base) - { + let carried = [ + (patch_io.1, patch), + (instance_io.1, instance), + (position_out, position), + ]; + for (to, v) in carried.into_iter().chain(base) { let dst = fb.module().global_value(to)?; fb.store(dst, v, MemAccess::default())?; } diff --git a/crates/metal2vulkan/src/pipeline/link/tessellation/control/tests.rs b/crates/metal2vulkan/src/pipeline/link/tessellation/control/tests.rs index c280a576b..c06a8f771 100644 --- a/crates/metal2vulkan/src/pipeline/link/tessellation/control/tests.rs +++ b/crates/metal2vulkan/src/pipeline/link/tessellation/control/tests.rs @@ -278,6 +278,8 @@ fn run_levels( push_bytes.extend((FACTORS + u64::from(push.0)).to_le_bytes()); push_bytes.extend(push.1.to_le_bytes()); push_bytes.extend(push.2.to_bits().to_le_bytes()); + // No patch index buffer. + push_bytes.extend(0u64.to_le_bytes()); (None, Some(FACTORS)) } }; @@ -693,47 +695,78 @@ fn the_address_form_reads_what_the_bound_form_reads() { } } -/// The address form's push fields: the address at the stage's offset, a `u64`, and the stride and -/// the scale where the stage reads them; its push range ends at the last. +/// The address form's push fields: the factors' address at the stage's offset, a `u64`; the +/// stride and the scale where the stage reads them, or the control-point indices' address under +/// a control-point index type; and the patch indices' address. Its push range is +/// [`PUSH_BYTES`], and a control-point index type goes with neither a per-instance step nor a +/// scale there. #[test] -fn the_address_form_pushes_the_address_and_what_it_reads() { +fn the_address_form_pushes_the_addresses_and_what_it_reads() { use crate::pipeline::sym::PushField as F; - for (step, scale, fields, bytes) in [ + let (factors, patches) = ( + (F::TessellationFactorAddress, 0), + (F::PatchIndexAddress, 16), + ); + for (step, scale, index_type, fields) in [ ( Step::PerPatch, false, - vec![(F::TessellationFactorAddress, 0)], - 8, + IndexType::None, + vec![factors, patches], ), ( Step::Constant, true, - vec![ - (F::TessellationFactorAddress, 0), - (F::TessellationFactorScale, 12), - ], - 16, + IndexType::None, + vec![factors, (F::TessellationFactorScale, 12), patches], ), ( Step::PerInstance, false, - vec![ - (F::TessellationFactorAddress, 0), - (F::TessellationFactorInstanceStride, 8), - ], - 12, + IndexType::None, + vec![factors, (F::TessellationFactorInstanceStride, 8), patches], + ), + ( + Step::PerPatch, + false, + IndexType::UInt16, + vec![factors, (F::ControlPointIndexAddress, 8), patches], + ), + ( + Step::Constant, + false, + IndexType::UInt32, + vec![factors, (F::ControlPointIndexAddress, 8), patches], ), ] { - assert_eq!(address_fields(step, scale), fields, "{step:?} {scale}"); - assert_eq!(Control::push_bytes(true, step, scale), (bytes, 8)); - assert_eq!(Control::push_bytes(false, step, scale), (PUSH_BYTES, 4)); + let what = format!("{step:?} {scale} {index_type:?}"); + assert!(address_fits(step, scale, index_type), "{what}"); + assert_eq!(address_fields(step, scale, index_type), fields, "{what}"); + assert_eq!( + Control::push_bytes(true, step, scale, index_type), + (PUSH_BYTES, 8) + ); + assert_eq!( + Control::push_bytes(false, step, scale, index_type), + (PUSH_BYTES, 4) + ); + } + for (step, scale) in [ + (Step::PerInstance, false), + (Step::PerPatchAndPerInstance, false), + (Step::PerPatch, true), + ] { + assert!(!address_fits(step, scale, IndexType::UInt16)); + assert!(address_fits(step, scale, IndexType::None)); } } -/// In the address form the patch index is the patch's position: the form binds no patch index -/// buffer. -#[test] -fn the_address_form_s_patch_index_is_the_position() { +/// Where the address form's patch index buffer lies: past 2^32. +const PATCH_INDICES: u64 = 0x0000_0023_4560_0000; + +/// The address form's patch index of each position `0..positions`, `indices` at +/// [`PATCH_INDICES`] and `address` pushed as the patch indices' address (0: no buffer). +fn run_addressed_patch_index(indices: &[u32], address: u64, positions: u32) -> Vec { let mut c = control(PatchDomain::Triangle, Partition::Integer, 64); c.addressed = true; let m = kernel(move |mb| { @@ -748,22 +781,48 @@ fn the_address_form_s_patch_index_is_the_position() { store(fb, out, position, as_float) })) }); + let mut push = vec![0u8; 16]; + push.extend(address.to_le_bytes()); let res = Resources { - buffers: vec![Buffer { - slot: Some(out_slot()), - address: None, - bytes: vec![0; 16], - }], - push: vec![0; 8], + buffers: vec![ + Buffer { + slot: Some(out_slot()), + address: None, + bytes: vec![0; (positions * 4) as usize], + }, + Buffer { + slot: None, + address: Some(PATCH_INDICES), + bytes: le_words(indices), + }, + ], + push, ..Resources::default() }; let cfg = Config { - workgroups: [4, 1, 1], + workgroups: [positions, 1, 1], step_limit: u64::MAX, ..Config::default() }; let o = run(&m, &cfg, res).expect("run"); - assert_eq!(words_of(&o.buffers[0]), [0, 1, 2, 3]); + words_of(&o.buffers[0]) +} + +/// In the address form the patch index is the patch's position where the pushed address is 0 +/// (no patch index buffer), and the word at the address plus `4 · position` where it is not, as +/// Metal reads it (an Apple M3 Max, job m3-max-80366): the same words the bound form reads. +#[test] +fn the_address_form_s_patch_index_is_the_word_at_the_position() { + let indices = [7, 7, 1, 3, 0, 2]; + assert_eq!(run_addressed_patch_index(&indices, 0, 4), [0, 1, 2, 3]); + assert_eq!( + run_addressed_patch_index(&indices, PATCH_INDICES + 8, 4), + [1, 3, 0, 2] + ); + assert_eq!( + run_addressed_patch_index(&indices, PATCH_INDICES, 6), + indices + ); } /// The patch index of each position `0..positions` with `indices` bound as the patch index @@ -952,6 +1011,100 @@ fn control_points_are_the_indices_at_the_patch_positions() { ); } +/// Where the address form's control-point index buffer lies: past 2^32. +const CONTROL_POINT_INDICES: u64 = 0x0000_0034_5670_0000; + +/// The elements the address form's [`elements`] computes for patch indices `0..patches` of `n` +/// control points under `index_type`, `indices` (bytes) at [`CONTROL_POINT_INDICES`] and that +/// address plus `offset` pushed as the control-point indices' address: per patch, its `n` +/// elements. +fn run_addressed_elements( + index_type: IndexType, + n: u32, + indices: &[u8], + offset: u64, + patches: u32, +) -> Vec> { + let mut c = control(PatchDomain::Triangle, Partition::Integer, 64); + c.control_points = n; + c.index_type = index_type; + c.addressed = true; + let m = kernel(move |mb| { + let src = declare_sources(mb, &c)?; + assert!(src.control_point_indices.is_none()); + let out = out_buffer(mb)?; + Ok(Box::new(move |fb: &mut FunctionBuilder<'_>| { + let patch = global_id(fb, 0)?; + let count = ku(fb, n)?; + let first = fb.binary(BinOp::IMul, patch, count)?; + let base = fb.module().global_value(out)?; + let zero = ku(fb, 0)?; + for (k, v) in elements(fb, &c, &src, patch)?.into_iter().enumerate() { + let k = ku(fb, k as u32)?; + let at = fb.binary(BinOp::IAdd, first, k)?; + let ptr = fb.access_chain(base, &[zero, at])?; + fb.store(ptr, v, MemAccess::default())?; + } + Ok(()) + })) + }); + let mut push = vec![0u8; 8]; + push.extend((CONTROL_POINT_INDICES + offset).to_le_bytes()); + push.extend([0; 8]); + let res = Resources { + buffers: vec![ + Buffer { + slot: Some(out_slot()), + address: None, + bytes: vec![0; (patches * n * 4) as usize], + }, + Buffer { + slot: None, + address: Some(CONTROL_POINT_INDICES), + bytes: indices.to_vec(), + }, + ], + push, + ..Resources::default() + }; + let cfg = Config { + workgroups: [patches, 1, 1], + step_limit: u64::MAX, + ..Config::default() + }; + let o = run(&m, &cfg, res).expect("run"); + words_of(&o.buffers[0]) + .chunks(n as usize) + .map(<[u32]>::to_vec) + .collect() +} + +/// The address form's control points are the indices the bound form reads, through the pushed +/// address plus the element times the index size: a `uint`, or a `ushort` in either half of the +/// word that holds it (Metal's, an Apple M3 Max, job m3-max-80366). +#[test] +fn the_address_form_s_control_points_are_the_indices_at_the_address() { + let words: Vec = (0..8).rev().collect(); + let bytes = le_words(&words); + assert_eq!( + run_addressed_elements(IndexType::UInt32, 3, &bytes, 4, 2), + [[6, 5, 4], [3, 2, 1]] + ); + let halves: Vec = (0..8u16) + .rev() + .map(|i| 0x100 * i + 0x10) + .flat_map(u16::to_le_bytes) + .collect(); + assert_eq!( + run_addressed_elements(IndexType::UInt16, 3, &halves, 0, 2), + [[0x710, 0x610, 0x510], [0x410, 0x310, 0x210]] + ); + assert_eq!( + run_addressed_elements(IndexType::UInt16, 3, &halves, 2, 2), + [[0x610, 0x510, 0x410], [0x310, 0x210, 0x110]] + ); +} + /// Every class of `half` as an edge factor and as an inside factor follows Metal's stated rules: /// the cull, the scale, the clamp, and `pow2`'s rounding for NaNs, infinities, zeros, negatives, /// subnormals, and normals. A quad patch per value `x`: edge 0 and inside 0 are `x`, inside 1 is @@ -1143,9 +1296,9 @@ fn the_synthesized_stages_pass_l3() { crate::spirv::testing::check_valid(control_module(&c).expect("control"), p) .unwrap_or_else(|e| panic!("{stem} {c:?}: {e}")); // The address form, on a profile with device addresses and 64-bit integers, - // without a control-point index type, which it does not implement. + // where its fields fit. let enabled = &p.fields().enabled.features; - if index_type == IndexType::None + if address_fits(c.step, c.scale_enabled, index_type) && enabled.contains(&VkFeature::BufferDeviceAddress) && enabled.contains(&VkFeature::ShaderInt64) { diff --git a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs index 573ce6d05..98c27b57b 100644 --- a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs +++ b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs @@ -25,9 +25,11 @@ //! `maxTessellationGenerationLevel` (`Unsupported{Tessellation; Limit}`); //! - a pipeline of vertex amplification above 1 (multiview) with tessellation stages needs //! `multiviewTessellationShader` (`Unsupported{VertexAmplification; Feature}` without it); -//! - under the identity domains, whose control stage reads the factors through their address -//! ([`control`]'s address form), a control-point index type is not implemented -//! (`Unsupported{Tessellation; NotImplemented}`). +//! - under the identity domains, whose control stage reads the factors and the indices through +//! their addresses ([`control`]'s address form), a control-point index type with a per-instance +//! factor step or an enabled factor scale is not implemented +//! (`Unsupported{Tessellation; NotImplemented}`): the indices' address takes the place of the +//! step's stride and the scale in the stage's push range ([`control::address_fits`]). //! //! Link numbers the factor buffer (`SyntheticBinding::TessellationFactors`), the patch index //! buffer (`SyntheticBinding::PatchIndices`), and, for a pipeline with a control-point index @@ -38,10 +40,10 @@ //! otherwise): 0, as the post-tessellation vertex function's window starts past those bytes //! (`push::TESSELLATION_BASE`) and its fragment function's behind it, so the range fits beside //! theirs on every device the floor admits. A fragment function that reads `[[primitive_id]]` -//! behind the evaluation stage reads the varying the evaluation stage writes, Metal's patch index -//! (`lower::tessellation`): Vulkan's `PrimitiveId` there counts the draw's patches from 0 and -//! restarts in each instance, where Metal's, without a patch index buffer, is the patch's -//! position, patch start included, in every instance. One compiled to read Vulkan's is +//! behind the evaluation stage reads the varying the evaluation stage writes, the patch's +//! position (`lower::tessellation`): Vulkan's `PrimitiveId` there counts the draw's patches from +//! 0 and restarts in each instance, where Metal's is the patch's position, patch start included, +//! in every instance, with or without a patch index buffer. One compiled to read Vulkan's is //! `NeedsInput(PrimitiveId)` ([`check_fragment`]). //! //! In the address form the control stage binds no buffer: link numbers none for it, places its @@ -202,6 +204,7 @@ impl ControlPlan { self.addressed, self.desc.factor_step_function, self.desc.factor_scale_enabled, + self.desc.control_point_index_type, ) } @@ -215,6 +218,7 @@ impl ControlPlan { let fields = control::address_fields( self.desc.factor_step_function, self.desc.factor_scale_enabled, + self.desc.control_point_index_type, ); Some(PushPlacement { stage: Stage::Vertex, @@ -270,7 +274,12 @@ pub fn control_plan( ) -> Result { let desc = checked(desc)?; let addressed = crate::lower::access::identity(p); - if addressed && desc.control_point_index_type != TessellationControlPointIndexType::None { + let fits = control::address_fits( + desc.factor_step_function, + desc.factor_scale_enabled, + desc.control_point_index_type, + ); + if addressed && !fits { return Err(Unsupported::not_implemented(Feature::Tessellation).into()); } let max = desc.max_tessellation_factor; diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index b7970ba9a..286fe081f 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -247,9 +247,9 @@ pub struct LoweringInputs { /// `n · i` of a list's primitive `i` and `i` of a strip's, so every fragment reads its /// primitive's index in its instance, Metal's /// `[[primitive_id]]` (Metal probes on the M3 Max, macOS 27.0.1). A post-tessellation vertex - /// function writes Metal's patch index there (`lower::tessellation`): without a patch index - /// buffer the patch's position in its draw, patch start included, in every instance, where - /// Vulkan's `PrimitiveId` counts the draw's patches from 0 in each instance. + /// function writes the patch's position in its draw there (`lower::tessellation`), patch + /// start included, in every instance, with or without a patch index buffer, where Vulkan's + /// `PrimitiveId` counts the draw's patches from 0 in each instance. /// /// A fragment function reads `[[primitive_id]]` from the varying under this field, as it does /// without it on a device that cannot declare a fragment `PrimitiveId`. diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index deaeb3fa7..5437e3bfc 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -991,6 +991,18 @@ pub enum PushField { /// pipeline's interface states it in a vertex-stage placement of its own, at the /// `TessellationState::push_offset`. TessellationFactorAddress, + /// Under the identity domains, the device address of the patch index buffer's words a + /// tessellation pipeline's synthesized control stage reads (`u64`): the buffer's address plus + /// the draw's `patchIndexBufferOffset` (`drawPatches:` and `drawIndexedPatches:`'s), a + /// multiple of 4; 0 for a draw without a patch index buffer, whose patch indices are the + /// patches' positions. Placed as [`PushField::TessellationFactorAddress`] is. + PatchIndexAddress, + /// Under the identity domains, the device address of the control-point indices a + /// tessellation pipeline with a control-point index type reads (`u64`): the + /// `drawIndexedPatches:` call's control-point index buffer's address plus its + /// `controlPointIndexBufferOffset`, a multiple of the index size. Placed as + /// [`PushField::TessellationFactorAddress`] is. + ControlPointIndexAddress, /// The device address (`u64`, a multiple of 16) of the runtime's memory that holds a kernel's /// private arena past the floor (`RuntimeFact::PrivateArena`): one slot of the fact's /// `slot_bytes` for each invocation of the dispatch, the invocation's slot its index in its diff --git a/crates/metal2vulkan/src/tests/engine_tessellation.rs b/crates/metal2vulkan/src/tests/engine_tessellation.rs index 84f7a3482..1109f60eb 100644 --- a/crates/metal2vulkan/src/tests/engine_tessellation.rs +++ b/crates/metal2vulkan/src/tests/engine_tessellation.rs @@ -1104,12 +1104,13 @@ fn what_the_control_stage_cannot_do_is_refused_typed() { } /// A fragment function's `[[primitive_id]]` behind a post-tessellation function is the flat -/// varying the evaluation stage writes from its patch-index input, Metal's patch index, on -/// MoltenVK's profile and RADV's, which both declare a fragment `PrimitiveId`: the evaluation -/// stage reads the patch input at `TessellationStage::PATCH_INDEX_LOCATION`, the fragment stage -/// reads one flat input and no `PrimitiveId`, and every module passes L3. +/// varying the evaluation stage writes from its patch-position input, the patch's position, which +/// Metal's is with or without a patch index buffer, on MoltenVK's profile and RADV's, which both +/// declare a fragment `PrimitiveId`: the evaluation stage reads the patch input at +/// `TessellationStage::PATCH_POSITION_LOCATION`, the fragment stage reads one flat input and no +/// `PrimitiveId`, and every module passes L3. #[test] -fn a_fragment_primitive_id_behind_tessellation_is_the_patch_index_varying() { +fn a_fragment_primitive_id_behind_tessellation_is_the_patch_position_varying() { let Some(bc) = fixture() else { return }; let Some(fragments) = assemble_text("fragments", FRAGMENTS) else { return; @@ -1151,7 +1152,7 @@ fn a_fragment_primitive_id_behind_tessellation_is_the_patch_index_varying() { assert_evaluation( evaluation, crate::spv::ExecutionMode::Quads, - &[TessellationStage::PATCH_INDEX_LOCATION], + &[TessellationStage::PATCH_POSITION_LOCATION], ); let fragment = &module(vk::ShaderStage::FRAGMENT).spirv; assert_eq!( @@ -1197,14 +1198,18 @@ fn the_tessellation_state_keys_no_vertex_function() { } /// Under the identity domains (`Device::from_queries`' profile), a tessellation pipeline's control -/// stage reads the factors through their address: the layout binds nothing, the interface states -/// `PushField::TessellationFactorAddress` as a vertex-stage placement at the tessellation state's -/// push offset (0, below the post-tessellation function's window, which starts at -/// `push::TESSELLATION_BASE`), the evaluation stage reaches its -/// pulled buffers through their pushed addresses with their strides, and every module passes L3, -/// on each committed profile with `tessellationShader`, `bufferDeviceAddress` and `shaderInt64`. -/// The stream's state (`fractionalOdd`, maximum 64, per patch, counter-clockwise) and Metal's -/// defaults compile; a control-point index type is not implemented in this form. +/// stage reads the factors and the indices through their addresses: the layout binds nothing, the +/// interface states `PushField::TessellationFactorAddress`, `PushField::PatchIndexAddress` 16 +/// bytes past it and, under a control-point index type, `PushField::ControlPointIndexAddress` 8 +/// bytes past it, as a vertex-stage placement at the tessellation state's push offset (0, below +/// the post-tessellation function's window, which starts at `push::TESSELLATION_BASE`), the +/// evaluation stage reaches its pulled buffers through their pushed addresses with their strides, +/// and every module passes L3, on each committed profile with `tessellationShader`, +/// `bufferDeviceAddress` and `shaderInt64`. The stream's state (`fractionalOdd`, maximum 64, per +/// patch, counter-clockwise), Metal's defaults and the stream's state under a `UInt16` or a +/// `UInt32` control-point index type compile; a control-point index type beside a per-instance +/// factor step or an enabled factor scale, whose fields the indices' address displaces, is +/// `NotImplemented(Tessellation)`. #[test] fn under_the_identity_domains_the_control_stage_reads_the_factors_by_address() { use crate::device::{HandleDomain, PointerDomain}; @@ -1226,6 +1231,14 @@ fn under_the_identity_domains_the_control_stage_reads_the_factors_by_address() { output_winding_order: Winding::CounterClockwise, ..Default::default() }; + let indexed = TessellationDescriptor { + control_point_index_type: TessellationControlPointIndexType::UInt16, + ..streamed + }; + let wide = TessellationDescriptor { + control_point_index_type: TessellationControlPointIndexType::UInt32, + ..streamed + }; let mut tried = 0; for (stem, p) in committed_profiles().expect("committed profiles") { let enabled = &p.fields().enabled.features; @@ -1238,7 +1251,7 @@ fn under_the_identity_domains_the_control_stage_reads_the_factors_by_address() { let desc = crate::pipeline::testing::description(&stem).unwrap_or_else(|e| panic!("{e}")); let dev = Device::from_queries(desc, policy).unwrap_or_else(|e| panic!("{stem}: {e}")); tried += 1; - for t in [streamed, TessellationDescriptor::default()] { + for t in [streamed, TessellationDescriptor::default(), indexed, wide] { let d = tessellation_pipeline( &bc, &fragments, @@ -1263,18 +1276,17 @@ fn under_the_identity_domains_the_control_stage_reads_the_factors_by_address() { panic!("{stem}: one placement of the factors' address: {control:?}"); }; assert_eq!(control.stage, Stage::Vertex, "{stem}"); - assert_eq!(control.push_range, Some((ts.push_offset, 8)), "{stem}"); + assert_eq!(control.push_range, Some((ts.push_offset, 24)), "{stem}"); let fields: Vec<_> = control.fields.iter().map(|f| (f.field, f.loc)).collect(); - assert_eq!( - fields, - [( - PushField::TessellationFactorAddress, - PushLoc::Push { - offset: ts.push_offset - } - )], - "{stem}" - ); + let at = |offset| PushLoc::Push { + offset: ts.push_offset + offset, + }; + let mut want = vec![(PushField::TessellationFactorAddress, at(0))]; + if t.control_point_index_type != TessellationControlPointIndexType::None { + want.push((PushField::ControlPointIndexAddress, at(8))); + } + want.push((PushField::PatchIndexAddress, at(16))); + assert_eq!(fields, want, "{stem} {t:?}"); let vertex = &p.interface.push[0]; assert_eq!(ts.push_offset, 0, "{stem}: below the functions' fields"); let base = crate::lower::push::TESSELLATION_BASE; @@ -1306,23 +1318,29 @@ fn under_the_identity_domains_the_control_stage_reads_the_factors_by_address() { .unwrap_or_else(|e| panic!("{stem} {:?}: L3: {e}", m.stage)); } } - let indexed = TessellationDescriptor { - control_point_index_type: TessellationControlPointIndexType::UInt32, - ..streamed + let stepped = TessellationDescriptor { + factor_step_function: TessellationFactorStepFunction::PerInstance, + ..wide }; - let d = tessellation_pipeline( - &bc, - &fragments, - "tess_triangle_points", - Some("tess_fragment"), - Some(indexed), - ); - match dev.compile_render_pipeline(&d, &Budget::standard()) { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::Tessellation, "{stem}"); - assert_eq!(u.needs, Needs::NotImplemented, "{stem}"); + let scaled = TessellationDescriptor { + factor_scale_enabled: true, + ..wide + }; + for t in [stepped, scaled] { + let d = tessellation_pipeline( + &bc, + &fragments, + "tess_triangle_points", + Some("tess_fragment"), + Some(t), + ); + match dev.compile_render_pipeline(&d, &Budget::standard()) { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::Tessellation, "{stem} {t:?}"); + assert_eq!(u.needs, Needs::NotImplemented, "{stem} {t:?}"); + } + other => panic!("{stem} {t:?}: {:?}", other.map(|_| ())), } - other => panic!("{stem}: {:?}", other.map(|_| ())), } } assert!( diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index c886ea528..7962ea8e4 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -10004,6 +10004,7 @@ variant metal2vulkan::pipeline::PushField::CaptureIndexAddress CaptureIndexAddre variant metal2vulkan::pipeline::PushField::CaptureLayout CaptureLayout variant metal2vulkan::pipeline::PushField::CommandRecordsAddress CommandRecordsAddress variant metal2vulkan::pipeline::PushField::ConstexprSampler ConstexprSampler(CombinedSampler) +variant metal2vulkan::pipeline::PushField::ControlPointIndexAddress ControlPointIndexAddress variant metal2vulkan::pipeline::PushField::ControlPointIndexOffset ControlPointIndexOffset variant metal2vulkan::pipeline::PushField::DepthClampRange DepthClampRange variant metal2vulkan::pipeline::PushField::DispatchRegion DispatchRegion @@ -10017,6 +10018,7 @@ variant metal2vulkan::pipeline::PushField::IndirectSequence IndirectSequence variant metal2vulkan::pipeline::PushField::InstanceCount InstanceCount(SlotRef) variant metal2vulkan::pipeline::PushField::LineBand LineBand variant metal2vulkan::pipeline::PushField::MergedDrawAddress MergedDrawAddress +variant metal2vulkan::pipeline::PushField::PatchIndexAddress PatchIndexAddress variant metal2vulkan::pipeline::PushField::PatchIndexBound PatchIndexBound variant metal2vulkan::pipeline::PushField::PatchIndexOffset PatchIndexOffset variant metal2vulkan::pipeline::PushField::PrivateArenaAddress PrivateArenaAddress diff --git a/docs/API.md b/docs/API.md index ecb6ed054..464823c3b 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1094,15 +1094,13 @@ indirect and indexed forms), with the factors from a tessellation factor buffer. orders the triangles (`PrecisionNote::TessellationTriangleOrder` where it is not Apple's). A device without `tessellationShader` refuses the function (`Unsupported{Tessellation}`, naming -the feature). A fragment function's `[[primitive_id]]` behind it is Metal's patch index, which -the evaluation stage writes to a flat varying the fragment stage reads (`IoRole::PrimitiveId`), on -every device. Without a patch index buffer that is Metal's value: the patch's position in its -draw, `patchStart` included, the same in every instance and for every triangle of the patch -(measured on an Apple M3 Max), where Vulkan's `PrimitiveId` counts the draw's patches from 0 and -restarts in each instance. With a patch index buffer it would be the buffer's index for the -patch, where Metal's `[[primitive_id]]` stays the patch's position (measured on an Apple M3 Max); -the runtime refuses a patch draw through a patch index buffer. A fragment function compiled to -read Vulkan's `PrimitiveId` behind it is `NeedsInput(PrimitiveId)`. +the feature). A fragment function's `[[primitive_id]]` behind it is the patch's position in its +draw, which the evaluation stage writes to a flat varying the fragment stage reads +(`IoRole::PrimitiveId`), on every device: Metal's value, `patchStart` included, the same in every +instance and for every triangle of the patch, with or without a patch index buffer (measured on +an Apple M3 Max), where Vulkan's `PrimitiveId` counts the draw's patches from 0 and restarts in +each instance. A fragment function compiled to read Vulkan's `PrimitiveId` behind it is +`NeedsInput(PrimitiveId)`. ### Mesh pipelines