diff --git a/crates/metal2vulkan-air/src/canon/tests/command_buffers.rs b/crates/metal2vulkan-air/src/canon/tests/command_buffers.rs index 7014b8c5e..6ca6791d9 100644 --- a/crates/metal2vulkan-air/src/canon/tests/command_buffers.rs +++ b/crates/metal2vulkan-air/src/canon/tests/command_buffers.rs @@ -275,12 +275,6 @@ fn a_draw_writes_its_constant_primitive_type() { let writes = e.command_writes(); assert_eq!(writes.operations, CommandWrites::DRAW, "{raw}"); assert_eq!(writes.primitive_types, types, "{raw}"); - assert_eq!( - writes.may_draw_primitive_type(3), - types & 0b1000 != 0, - "{raw}" - ); - assert!(!writes.may_draw_primitive_type(5)); } let loaded = specialized(|f| { let i32t = f.module().int(32); diff --git a/crates/metal2vulkan/src/bind/argument_buffer.rs b/crates/metal2vulkan/src/bind/argument_buffer.rs index 9b4fb1238..b1088f25a 100644 --- a/crates/metal2vulkan/src/bind/argument_buffer.rs +++ b/crates/metal2vulkan/src/bind/argument_buffer.rs @@ -313,7 +313,6 @@ fn type_size_align(ty: DataType) -> Option<(u64, u64, ArgumentType)> { } impl ArgumentBufferLayout { - /// Where argument `index` lands: in the last member whose indices hold it, inside a struct /// member's element as that element's layout says. `None` when no member holds it. pub fn argument(&self, index: u32) -> Option { @@ -359,8 +358,7 @@ impl ArgumentBufferLayout { } } -impl ArgumentBufferLayout { -} +impl ArgumentBufferLayout {} /// Which of Metal's two rules lays out a reflected struct (the module docs). #[derive(Clone, Copy, PartialEq, Eq)] diff --git a/crates/metal2vulkan/src/bind/astc_decode/tests/hdr.rs b/crates/metal2vulkan/src/bind/astc_decode/tests/hdr.rs index 3d59342de..75f2536b3 100644 --- a/crates/metal2vulkan/src/bind/astc_decode/tests/hdr.rs +++ b/crates/metal2vulkan/src/bind/astc_decode/tests/hdr.rs @@ -309,7 +309,6 @@ fn an_hdr_format_s_twin_holds_halves() { for texels in [AstcTexels::Unorm8, AstcTexels::Half] { assert_eq!(d.form(texels), AstcTexels::Half); assert_eq!(d.texel_format(texels), Format::R16G16B16A16_SFLOAT); - assert_eq!(d.texel_pixel_format(texels), PixelFormat::RGBA16Float); assert_eq!(d.texel_bytes(texels), 8); } assert_eq!( diff --git a/crates/metal2vulkan/src/bind/color_resolve.rs b/crates/metal2vulkan/src/bind/color_resolve.rs index a6b2219d6..2e79ee8b6 100644 --- a/crates/metal2vulkan/src/bind/color_resolve.rs +++ b/crates/metal2vulkan/src/bind/color_resolve.rs @@ -62,8 +62,8 @@ //! The twin's formats are never read from planes: a twin resolve reads the attachment. //! //! Draw it into a render pass whose one color attachment is the resolve texture's single-sampled -//! level and layer in [`ColorResolveFormat::written_format`] (its own format, or its raw twin -//! where the result is written raw), over the render area, one sample, without blending; for +//! level and layer in its own format, or its raw twin's where the result is written raw +//! ([`ColorResolveFormat::written_raw`]), over the render area, one sample, without blending; for //! [`ResolveSource::InputAttachment`] the pass's subpass also reads the multisampled attachment as //! its input attachment 0, and for [`ResolveSource::RawInputAttachment`] a view of it in its raw //! twin. diff --git a/crates/metal2vulkan/src/bind/color_resolve/extended_tests.rs b/crates/metal2vulkan/src/bind/color_resolve/extended_tests.rs index cab97d05d..64c1cb01a 100644 --- a/crates/metal2vulkan/src/bind/color_resolve/extended_tests.rs +++ b/crates/metal2vulkan/src/bind/color_resolve/extended_tests.rs @@ -45,7 +45,7 @@ const UNMADE: [ExtendedRange; 9] = [ /// The sources a test reads `form` from: the input attachment, and the sample planes of its raw /// format's bits copy. fn sources(form: ExtendedRange) -> [ResolveSource; 2] { - let copy = PlanesCopy::for_planes(form.raw_format()).expect("a bits copy"); + let copy = super::tests::bits_copy(form.raw_format()); [ResolveSource::InputAttachment, ResolveSource::Planes(copy)] } diff --git a/crates/metal2vulkan/src/bind/color_resolve/tests.rs b/crates/metal2vulkan/src/bind/color_resolve/tests.rs index abf1b8957..70025bc65 100644 --- a/crates/metal2vulkan/src/bind/color_resolve/tests.rs +++ b/crates/metal2vulkan/src/bind/color_resolve/tests.rs @@ -9,6 +9,23 @@ use crate::spirv::interp::{run, Buffer, Config, Order, Outcome, Resources}; use crate::spirv::testing::{assert_valid, committed_profiles}; use std::path::PathBuf; +/// The sample planes' copy that moves the bits of `format`'s texels: the one of its texel's size. +pub(super) fn bits_copy(format: Format) -> PlanesCopy { + let size = |f: Format| f.block().map(|b| b.size); + (PlanesCopy::ALL.into_iter()) + .find(|c| c.moves_bits() && size(c.format()) == size(format)) + .expect("a bits copy") +} + +/// The format of the view `format`'s result is written through: the raw twin's where it is +/// written raw, else its own. +pub(super) fn written(format: ColorResolveFormat) -> Format { + match format.written_raw { + true => format.raw_format(), + false => format.format, + } +} + /// Every format the module docs list: the twin resolve's. const CLOSED: [Format; 8] = [ Format::R8_UNORM, @@ -189,7 +206,7 @@ fn the_modules_come_numbered_and_refuse_another_count_or_planes() { assert!(matches!(refused, Err(Error::Internal(_))), "{samples}"); } for format in representatives() { - let copy = PlanesCopy::for_planes(format.format()).expect("copy"); + let copy = bits_copy(format.format()); let planes = ResolveSource::Planes(copy); assert!( fragment_typed_module(format, 4, planes).is_err(), @@ -239,7 +256,7 @@ fn arithmetic_module( ) -> TypedModule { let mut b = ModuleBuilder::new(); let t = Types::new(&mut b).expect("types"); - let srgb = (format.srgb() && !format.decodes_on_device()) + let srgb = (format.srgb() && !format.device_srgb) .then(|| SrgbTables::declare(&mut b, t, format, source)) .transpose() .expect("tables"); @@ -460,7 +477,7 @@ fn check( "{:?} written as {:?} x{samples} {source:?} component {component}: {codes:x?} \ wrote {word:#x}", format.format(), - format.written_format() + written(format) ); } } @@ -723,8 +740,8 @@ fn the_device_srgb_form_writes_the_mean_of_the_decoded_samples() { let resolve = ColorResolveFormat::of(format) .expect("closed") .device_srgb(); - assert!(resolve.decodes_on_device(), "{format:?}"); - assert_eq!(resolve.written_format(), format, "{format:?}"); + assert!(resolve.device_srgb, "{format:?}"); + assert_eq!(written(resolve), format, "{format:?}"); let source = ResolveSource::InputAttachment; let tables = fragment_typed_module(resolve, 4, source).expect("module"); let table = diff --git a/crates/metal2vulkan/src/bind/color_resolve/word_tests.rs b/crates/metal2vulkan/src/bind/color_resolve/word_tests.rs index 0a4d9fcee..5ca584cf6 100644 --- a/crates/metal2vulkan/src/bind/color_resolve/word_tests.rs +++ b/crates/metal2vulkan/src/bind/color_resolve/word_tests.rs @@ -40,10 +40,10 @@ fn a_word_resolve_holds_the_word_and_an_srgb_word_has_none() { for word in words() { let rules = ColorResolveFormat::word(word).expect("a word resolve"); assert_eq!(rules.format(), word.word_format(), "{word:?}"); - assert_eq!(rules.held_word(), Some(word)); + assert_eq!(rules.word, Some(word)); assert_eq!(rules.channels(), [None; 4]); assert_eq!(rules.raw_format(), rules.format()); - assert_eq!(rules.written_format(), rules.format()); + assert_eq!(super::tests::written(rules), rules.format()); assert_eq!(rules.exact(), word == WordAttachment::Rgb9e5, "{word:?}"); } let srgb = WordAttachment::layout(crate::metal::PixelFormat::R8UnormSRGB).expect("a word"); @@ -58,7 +58,7 @@ fn the_word_modules_are_valid_and_need_nothing_of_a_device() { let profiles = committed_profiles().expect("profiles"); for word in words() { let rules = ColorResolveFormat::word(word).expect("a word resolve"); - let copy = PlanesCopy::for_planes(word.word_format()).expect("a bits copy"); + let copy = super::tests::bits_copy(word.word_format()); for source in [ResolveSource::InputAttachment, ResolveSource::Planes(copy)] { for samples in [2, 4, 8] { let m = fragment_typed_module(rules, samples, source).expect("module"); diff --git a/crates/metal2vulkan/src/bind/dispatch/tests.rs b/crates/metal2vulkan/src/bind/dispatch/tests.rs index 746d0fbde..59c6065fd 100644 --- a/crates/metal2vulkan/src/bind/dispatch/tests.rs +++ b/crates/metal2vulkan/src/bind/dispatch/tests.rs @@ -1242,127 +1242,3 @@ fn a_dispatch_reaches_where_an_element_may_end_past_four_gigabytes() { // A kernel without a thread-position fetch reaches nothing. assert!(!reach(Vec::new(), along_x(0, 64), [64, 1, 1], &unbound)); } - -/// `BindingPlan::dispatch_reads` names the slot values a plan's commands read. A plan that binds -/// a buffer alone gives the same commands for two states of its shape whose texture and sampler -/// slots bind other values (resource IDs, an array length); a texel buffer's range and the -/// resource ID of a handle table's member bound at a slot are read, and a change of either changes -/// the commands; a push field of a texture's in-place planes reads its texture slot. -#[test] -fn dispatch_reads_names_the_slot_values_the_commands_read() { - use crate::bind::heap::{HeapMember, PlannedHandleTable}; - use crate::bind::plan::PlannedTexel; - use crate::bind::state::{BoundSampler, BoundTexture, SamplerDescriptor, TextureFacts}; - use crate::metal::{PixelFormat, TextureSwizzleChannels, TextureType}; - let d = Dispatch::Threadgroups { - groups: [2, 1, 1], - threads_per_group: [64, 1, 1], - }; - let slot = |class, index| SlotRef { - stage: Stage::Kernel, - class, - index, - }; - let facts = |array_length| { - let mut facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA8Unorm); - facts.array_length = array_length; - facts - }; - // The buffer slot's state, with `textures` bound at their indices and a sampler state of - // resource ID `sampler` at 0. - let with = |textures: &[(u32, BoundTexture)], sampler: u64| { - let mut s = state(0); - let k = s - .stages - .get_mut(&Stage::Kernel) - .expect("the kernel's table"); - k.textures.extend(textures.iter().copied()); - let mut bound = BoundSampler::new(SamplerDescriptor::new()); - bound.resource_id = Some(sampler); - k.samplers.insert(0, bound); - s - }; - let image = |id, array_length| BoundTexture::Texture { - facts: facts(array_length), - resource_id: Some(id), - }; - - // A buffer slot alone: no texture or sampler value is read. - let plan = compute_plan(&template(), VariantKey::new()); - assert!(plan.dispatch_reads(SlotClass::Buffer)); - assert!(!plan.dispatch_reads(SlotClass::Texture)); - assert!(!plan.dispatch_reads(SlotClass::Sampler)); - let (a, b) = (with(&[(1, image(1, 1))], 3), with(&[(1, image(2, 4))], 4)); - assert_eq!(a.shape(), b.shape(), "one shape"); - assert_eq!( - plan.instantiate_dispatch(&a, &d), - plan.instantiate_dispatch(&b, &d), - "the same commands" - ); - - // A texel buffer at texture slot 1: its range is read. - let mut t = template(); - t.resources.texel_buffers.push(PlannedTexel { - set: 0, - binding: 1, - slot: slot(SlotClass::Texture, 1), - alignment: 16, - max_elements: 1 << 20, - block_size: 4, - texels_per_block: 1, - parts: 1, - part_texels: 1 << 20, - }); - let plan = compute_plan(&t, VariantKey::new()); - assert!(plan.dispatch_reads(SlotClass::Texture)); - assert!(!plan.dispatch_reads(SlotClass::Sampler)); - let texels = |offset| BoundTexture::Buffer { - pixel_format: PixelFormat::R32Float, - offset, - length: 256, - bytes_per_row: 256, - resource_id: None, - swizzle: TextureSwizzleChannels::default(), - parts: 1, - }; - let (a, b) = (with(&[(1, texels(0))], 3), with(&[(1, texels(64))], 3)); - assert_eq!(a.shape(), b.shape(), "one shape"); - assert_ne!( - plan.instantiate_dispatch(&a, &d).expect("commands"), - plan.instantiate_dispatch(&b, &d).expect("commands"), - "another texel-buffer range" - ); - - // A handle table naming the texture bound at texture slot 2: its resource ID is read. - let mut t = template(); - t.resources.heap_members.push(HeapMember { - source: HeapSource::Bound(slot(SlotClass::Texture, 2)), - shape: facts(1).shape(), - stages: vec![Stage::Kernel], - unreadable: false, - }); - t.resources.handle_tables.push(PlannedHandleTable { - set: 0, - binding: 4, - stage: Stage::Kernel, - entries: 2, - }); - let plan = compute_plan(&t, VariantKey::new()); - assert!(plan.dispatch_reads(SlotClass::Texture)); - let (a, b) = (with(&[(2, image(7, 1))], 3), with(&[(2, image(8, 1))], 3)); - assert_eq!(a.shape(), b.shape(), "one shape"); - assert_ne!( - plan.instantiate_dispatch(&a, &d).expect("commands"), - plan.instantiate_dispatch(&b, &d).expect("commands"), - "another resource ID in the handle table" - ); - - // A push field of a texture's in-place planes. - let mut t = template(); - t.fields.push(PlacedField { - field: PushField::YCbCrInPlace(slot(SlotClass::Texture, 0)), - loc: PushLoc::Push { offset: 36 }, - size: 4 * crate::bind::YCbCrInPlace::WORDS as u32, - }); - assert!(compute_plan(&t, VariantKey::new()).dispatch_reads(SlotClass::Texture)); -} diff --git a/crates/metal2vulkan/src/bind/etc_decode/tests.rs b/crates/metal2vulkan/src/bind/etc_decode/tests.rs index 19e9ff753..cb6958aa3 100644 --- a/crates/metal2vulkan/src/bind/etc_decode/tests.rs +++ b/crates/metal2vulkan/src/bind/etc_decode/tests.rs @@ -44,12 +44,6 @@ fn the_etc2_and_eac_formats_alone_decode() { assert_eq!(decode.eleven_bit(), compact != float, "{decode:?}"); for texels in [EtcTexels::Compact, EtcTexels::Float] { let format = decode.texel_format(texels); - let pf = decode.texel_pixel_format(texels); - assert_eq!( - crate::metal::format::direct_format(pf), - Some(format), - "{decode:?} {texels:?}" - ); let bytes = format.block().map(|b| b.size).expect("a block"); assert_eq!(decode.texel_bytes(texels), bytes, "{decode:?} {texels:?}"); } diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 81479f653..bdb47855a 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -2943,21 +2943,6 @@ impl BindingPlan { Ok(t) } - /// What [`rebind_draw_slots_into`](Self::rebind_draw_slots_into) of the slots `slots` works - /// out of the plan alone, whatever the state and the commands: each changed buffer slot's - /// place among the descriptor ranges, the push fields that read the slots and where they lie, - /// and the fixed-function vertex buffers they bind. `None` where the plan reads one of them - /// some other way (a device-address slot, a stage's argument or root table, a fixed-function - /// binding of a per-bind stride, a texture buffer's texel range, a YCbCr texture's planes, a - /// mesh, patch or de-indexed draw, a uniform view a written slot may alias), where that method - /// answers `Ok(false)`. Made once, it serves every rebind of the same slots on this plan - /// ([`rebind_draw_slots_with`](Self::rebind_draw_slots_with)). - pub fn slot_rebinds(&self, slots: &[SlotRef]) -> Option { - let mut rebinds = SlotRebinds::default(); - self.slot_rebinds_into(slots, &mut rebinds) - .then_some(rebinds) - } - /// [`slot_rebinds`](Self::slot_rebinds) of `slots`, made in `into` in place of what it held, /// keeping its lists' room: whether the plan rebinds them so (`into` then holds the same /// rebinds `slot_rebinds` answers), else `into` serves no rebind. A caller that makes rebinds @@ -2972,34 +2957,6 @@ impl BindingPlan { } } } - - /// [`rebind_draw_slots_into`](Self::rebind_draw_slots_into) of the slots `rebinds` was made - /// for, by [`slot_rebinds`](Self::slot_rebinds) of this plan: the same commands, the same - /// answers, where only the state and the commands are looked at. `Ok(false)` also where the - /// commands read a slot some other way (an argument table's bytes or a root table), or a moved - /// fixed-function vertex buffer's offset cannot be fetched there. `rebinds` is this plan's, or - /// an equal plan's (checked in builds with debug assertions). - pub fn rebind_draw_slots_with( - &self, - rebinds: &SlotRebinds, - state: &BindState, - commands: &mut DrawCommands, - ) -> Result { - // Made again in a scratch of the thread's, whose lists keep their room from check to - // check, so the check allocates nothing past its first; none past the thread's - // thread-locals' end (a program's exit handler, which runs after them). - #[cfg(debug_assertions)] - let _ = REBINDS_MADE_AGAIN.try_with(|again| { - let again = &mut *again.borrow_mut(); - let made = self.slot_rebinds_into(&rebinds.slots, again); - assert!(made && again == rebinds, "slot rebinds another plan made"); - }); - match self.graphics.as_ref() { - Some(t) if !t.other_layer_variant => rebind_with(t, rebinds, state, commands), - _ => Ok(false), - } - } - } /// The Vulkan draw of a Metal draw, and the base vertex and first instance the diff --git a/crates/metal2vulkan/src/bind/heap.rs b/crates/metal2vulkan/src/bind/heap.rs index c97fd1aba..a0e6027b7 100644 --- a/crates/metal2vulkan/src/bind/heap.rs +++ b/crates/metal2vulkan/src/bind/heap.rs @@ -2495,7 +2495,6 @@ fn relisted_sampler_tables( } impl BindingPlan { - /// Where this plan's heap writes go for `state` ([`HeapElements`]), each heap array having /// `capacity` elements (the layout's set-1 count). Under [`HeapPlacement::ResourceId`] a /// member's element is its resource ID and a listed sampler's its diff --git a/crates/metal2vulkan/src/bind/heap/tests.rs b/crates/metal2vulkan/src/bind/heap/tests.rs index d732bf6c0..72fef8eb1 100644 --- a/crates/metal2vulkan/src/bind/heap/tests.rs +++ b/crates/metal2vulkan/src/bind/heap/tests.rs @@ -544,9 +544,10 @@ fn resource_id_placement_puts_a_sampler_at_its_element() { ..BindState::default() }; for (id, element) in [(16380, 1), (2, 2)] { - state.argument_samplers.push( - crate::bind::ArgumentSampler::new(SamplerDescriptor::new(), id).at_element(element), - ); + state.argument_samplers.push(crate::bind::ArgumentSampler { + element: Some(element), + ..crate::bind::ArgumentSampler::new(SamplerDescriptor::new(), id) + }); } let planned = PlannedHandleTable { set: 0, @@ -993,8 +994,9 @@ fn sampler_tables_relist_states_of_the_plans_shapes() { descs .iter() .enumerate() - .map(|(i, &d)| { - crate::bind::ArgumentSampler::new(d, i as u64 + 1).at_element(i as u32 + 1) + .map(|(i, &d)| crate::bind::ArgumentSampler { + element: Some(i as u32 + 1), + ..crate::bind::ArgumentSampler::new(d, i as u64 + 1) }) .collect() }; @@ -1096,8 +1098,9 @@ fn a_late_cubic_sampler_is_listed_with_its_cubic_bit_beside_tested_stages() { descs .iter() .enumerate() - .map(|(i, &d)| { - crate::bind::ArgumentSampler::new(d, i as u64 + 1).at_element(i as u32 + 1) + .map(|(i, &d)| crate::bind::ArgumentSampler { + element: Some(i as u32 + 1), + ..crate::bind::ArgumentSampler::new(d, i as u64 + 1) }) .collect() }; @@ -1182,7 +1185,10 @@ fn sampler_tables_admit_the_shapes_the_plan_s_checks_pass() { stage: Stage::Kernel, entries: 4, }; - let encoded = [crate::bind::ArgumentSampler::new(SamplerDescriptor::new(), 1).at_element(1)]; + let encoded = [crate::bind::ArgumentSampler { + element: Some(1), + ..crate::bind::ArgumentSampler::new(SamplerDescriptor::new(), 1) + }]; let template = |classes: Vec, opaque_black: bool| ResourceTemplate { sampler_tables: vec![planned], argument_samplers: Some(ArgumentSamplersShape::of(&encoded)), @@ -1200,7 +1206,10 @@ fn sampler_tables_admit_the_shapes_the_plan_s_checks_pass() { let held_on = |profile: &DeviceProfile, template: &ResourceTemplate, late: SamplerDescriptor| -> bool { let mut samplers = encoded.to_vec(); - samplers.push(crate::bind::ArgumentSampler::new(late, 2).at_element(2)); + samplers.push(crate::bind::ArgumentSampler { + element: Some(2), + ..crate::bind::ArgumentSampler::new(late, 2) + }); assert!(!template .argument_samplers .as_ref() diff --git a/crates/metal2vulkan/src/bind/index_bounds.rs b/crates/metal2vulkan/src/bind/index_bounds.rs index d079d9d5a..2e2212780 100644 --- a/crates/metal2vulkan/src/bind/index_bounds.rs +++ b/crates/metal2vulkan/src/bind/index_bounds.rs @@ -32,9 +32,9 @@ //! | Words | Written by | Contents | //! |---|---|---| //! | 0 to 7 | the consumer | [`IndexBoundsPass::parameters`]: the arguments' first word in the bound arguments range, the index offset's byte in the bound indices range, the whole indices from the offset (saturated to `u32`), 1 for 32-bit indices, the pool's index bytes; then zeros | -//! | 8 to 12 | the plan | the first draw's `VkDrawIndexedIndirectCommand` ([`IndexBoundsPass::FIRST_DRAW_OFFSET`]) | -//! | 13 to 17 | the plan | the second draw's ([`IndexBoundsPass::SECOND_DRAW_OFFSET`]) | -//! | 18 to 20 | the plan | the fill's `VkDispatchIndirectCommand` ([`IndexBoundsPass::FILL_DISPATCH_OFFSET`]) | +//! | 8 to 12 | the plan | the first draw's `VkDrawIndexedIndirectCommand` | +//! | 13 to 17 | the plan | the second draw's | +//! | 18 to 20 | the plan | the fill's `VkDispatchIndirectCommand` | //! | 21 to 23 | the plan | the fill's first pool word, first Metal position, and count | //! //! **The pool**: [`IndexBoundsPass::POOL_HEADER_BYTES`] of header (the counter in its first word, @@ -103,10 +103,6 @@ impl IndexBoundsPass { pub const BYTES: u64 = 96; /// The consumer's parameter words at the bounds words' start. pub const PARAMETER_WORDS: usize = 8; - /// The first draw's `VkDrawIndexedIndirectCommand` in the bounds words. - pub const FIRST_DRAW_OFFSET: u64 = 32; - /// The second draw's `VkDrawIndexedIndirectCommand` in the bounds words. - pub const SECOND_DRAW_OFFSET: u64 = 52; /// The pool's header: its counter, then reserved bytes; its index bytes follow, where the /// second draw binds the pool as its index buffer. pub const POOL_HEADER_BYTES: u64 = 16; @@ -162,7 +158,6 @@ impl IndexBoundsPass { parameters, }) } - } /// The consumer's parameter words, by index into the bounds words. diff --git a/crates/metal2vulkan/src/bind/index_bounds/run.rs b/crates/metal2vulkan/src/bind/index_bounds/run.rs index 38d862afd..f875e3945 100644 --- a/crates/metal2vulkan/src/bind/index_bounds/run.rs +++ b/crates/metal2vulkan/src/bind/index_bounds/run.rs @@ -17,7 +17,7 @@ //! | 5 to 7 | nobody | zero | //! //! A slot's words 0 to 23 are a pass's bounds words (the parent module's table), its two draws -//! at [`IndexBoundsRun::first_draw_offset`] and [`IndexBoundsRun::second_draw_offset`]; its word +//! at its words 8 and 13; its word //! 24, which the plan writes, is the draw's first fill workgroup (the fill workgroups of the //! draws before it). //! - **The plan** ([`index_bounds_plan_run_module`]) plans each draw in turn, then writes the @@ -201,11 +201,6 @@ impl IndexBoundsRun { .flat_map(|w| w.to_le_bytes()) .collect() } - - /// The byte of the words at which slot `slot` starts. - fn slot_offset(slot: u32) -> u64 { - 4 * u64::from(Self::HEADER_WORDS) + u64::from(slot) * Self::SLOT_BYTES - } } /// The first word of the slot of draw `d`. diff --git a/crates/metal2vulkan/src/bind/index_bounds/run/tests.rs b/crates/metal2vulkan/src/bind/index_bounds/run/tests.rs index 740a93541..1730c4366 100644 --- a/crates/metal2vulkan/src/bind/index_bounds/run/tests.rs +++ b/crates/metal2vulkan/src/bind/index_bounds/run/tests.rs @@ -106,7 +106,7 @@ fn passes(draws: &[BoundsRunDraw], arguments: &[u8], indices: &[u8]) -> Left { ); let planned = words(&after[0]); (pool, status) = (after[2].clone(), after[3].clone()); - let groups = planned[(IndexBoundsPass::FILL_DISPATCH_OFFSET / 4) as usize]; + let groups = planned[Output::FillDispatch as usize]; if groups > 0 { let filled = dispatch( &fill, @@ -115,7 +115,7 @@ fn passes(draws: &[BoundsRunDraw], arguments: &[u8], indices: &[u8]) -> Left { ); pool = filled[2].clone(); } - let at = (IndexBoundsPass::FIRST_DRAW_OFFSET / 4) as usize; + let at = (super::super::tests::FIRST_DRAW / 4) as usize; commands.push(planned[at..at + 10].try_into().expect("commands")); } (commands, words(&pool), status) @@ -170,11 +170,8 @@ fn run_of( planned[last + FIRST_GROUP as usize] + planned[last + Output::FillDispatch as usize]; let commands = (0..draws.len() as u32) .map(|slot| { - let at = (IndexBoundsRun::first_draw_offset(slot) / 4) as usize; - assert_eq!( - IndexBoundsRun::second_draw_offset(slot), - IndexBoundsRun::first_draw_offset(slot) + 20 - ); + let at = (IndexBoundsRun::HEADER_WORDS + slot * IndexBoundsRun::SLOT_WORDS) as usize + + (super::super::tests::FIRST_DRAW / 4) as usize; planned[at..at + 10].try_into().expect("commands") }) .collect(); diff --git a/crates/metal2vulkan/src/bind/index_bounds/tests.rs b/crates/metal2vulkan/src/bind/index_bounds/tests.rs index fe887c7b4..0b259087e 100644 --- a/crates/metal2vulkan/src/bind/index_bounds/tests.rs +++ b/crates/metal2vulkan/src/bind/index_bounds/tests.rs @@ -10,6 +10,12 @@ use crate::bind::status::{ExecutionStatus, StatusReport}; use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; use crate::spirv::testing::{assert_valid, committed_profiles}; +/// The byte of the bounds words at which the first draw's `VkDrawIndexedIndirectCommand` lies +/// (words 8 to 12 of the module's table). +pub(super) const FIRST_DRAW: u64 = 32; +/// The byte of the second draw's (words 13 to 17). +const SECOND_DRAW: u64 = 52; + /// The pool's index bytes in these tests. const POOL_BYTES: u32 = 64; @@ -97,7 +103,7 @@ fn ran(pass: &IndexBoundsPass, arguments: &[u32], indices: &[u8], counter: u32) let mut pool = words(&after[2]); let status: [u8; 32] = after[3].as_slice().try_into().expect("status"); let report = ExecutionStatus::decode(&status); - let groups = bounds[(IndexBoundsPass::FILL_DISPATCH_OFFSET / 4) as usize]; + let groups = bounds[Output::FillDispatch as usize]; if groups > 0 { // The indices as bound: the range `pass` names, or 4 bytes nothing reads. let bound = match pass.indices_range { @@ -167,8 +173,8 @@ fn drawn(r: &Ran, indices: &[u8], index_offset: u64, vk_end: u64, wide: bool) -> )) } }; - let first = command(&r.words, IndexBoundsPass::FIRST_DRAW_OFFSET); - let second = command(&r.words, IndexBoundsPass::SECOND_DRAW_OFFSET); + let first = command(&r.words, FIRST_DRAW); + let second = command(&r.words, SECOND_DRAW); assert!( first[0] == 0 || second[0] == 0, "one draw carries the primitives: {first:?} {second:?}" @@ -288,10 +294,7 @@ fn a_draw_inside_the_buffer_draws_from_it() { metal(&indices, 4, start, count, 100), "{count} from {start}" ); - assert_eq!( - command(&r.words, IndexBoundsPass::FIRST_DRAW_OFFSET)[0], - count - ); + assert_eq!(command(&r.words, FIRST_DRAW)[0], count); assert_eq!(r.pool[0], 0, "no reservation"); assert!(!r.report.index_pool_overflow); } @@ -331,8 +334,8 @@ fn a_draw_past_the_buffer_draws_metals_vertices_from_the_pool() { want, "{size}-byte indices: {count} from {start}" ); - let first = command(&r.words, IndexBoundsPass::FIRST_DRAW_OFFSET); - let second = command(&r.words, IndexBoundsPass::SECOND_DRAW_OFFSET); + let first = command(&r.words, FIRST_DRAW); + let second = command(&r.words, SECOND_DRAW); let past = u64::from(start) + u64::from(count) > inside; assert_eq!((first[0] != 0, second[0] != 0), (!past, past)); if past { diff --git a/crates/metal2vulkan/src/bind/index_rewrite.rs b/crates/metal2vulkan/src/bind/index_rewrite.rs index 98841f557..bff8142c9 100644 --- a/crates/metal2vulkan/src/bind/index_rewrite.rs +++ b/crates/metal2vulkan/src/bind/index_rewrite.rs @@ -619,7 +619,6 @@ impl IndexRewritePass { self.parameters[Parameter::Listed as usize] = 1; self } - } /// The consumer's words, by index into the rewrite words. diff --git a/crates/metal2vulkan/src/bind/index_rewrite/gather/plan.rs b/crates/metal2vulkan/src/bind/index_rewrite/gather/plan.rs index 9e1cc8e7d..1b6999091 100644 --- a/crates/metal2vulkan/src/bind/index_rewrite/gather/plan.rs +++ b/crates/metal2vulkan/src/bind/index_rewrite/gather/plan.rs @@ -14,8 +14,8 @@ //! - writes each draw's record (its first workgroup, its list's indices and first word in the //! pool, its first index), the run's workgroups and the gather's `VkDispatchIndirectCommand` //! (at most [`IndexGatherModule::MAX_GROUPS`] workgroups, which take the run's in turn), and -//! each draw's `VkDrawIndexedIndirectCommand` at its place's [`IndexGatherPlanModule::DRAW_BYTES`] -//! of the draws' binding: its list's indices, Metal's instances, its first index in the pool's +//! each draw's `VkDrawIndexedIndirectCommand` in its place's 20 bytes of the draws' +//! binding: its list's indices, Metal's instances, its first index in the pool's //! index region, its base vertex (Metal's base vertex, or its vertex start), Metal's base //! instance. //! diff --git a/crates/metal2vulkan/src/bind/index_rewrite/gather/tests.rs b/crates/metal2vulkan/src/bind/index_rewrite/gather/tests.rs index 3fe404b31..efba63574 100644 --- a/crates/metal2vulkan/src/bind/index_rewrite/gather/tests.rs +++ b/crates/metal2vulkan/src/bind/index_rewrite/gather/tests.rs @@ -2,17 +2,13 @@ //! interpreter, each draw of a run gets the list the index rewrite pass writes for it //! ([`RewriteProgram::list`] of its fetched positions in the run's order), every program that //! gathers, either index size, offsets and counts reaching past the buffer's whole indices, and -//! a dispatch of fewer workgroups than the run's; an indirect run's plan places each draw's list -//! in the pool and writes its command from Metal's arguments (first indices past the buffer, no -//! instance, a pool too small for a list); the positions' list of fewer positions is the start of +//! a dispatch of fewer workgroups than the run's; the positions' list of fewer positions is the start of //! the list of more for exactly the programs that gather, and its closed form is the list; and a //! run refuses what it cannot take. -use super::plan::{plan_typed_module, IndexGatherPlanModule}; +use super::plan::plan_typed_module; use super::*; -use crate::bind::index_bounds::IndexBoundsPass; -use crate::bind::index_rewrite::{RewriteOrder, STATUS}; -use crate::bind::status::ExecutionStatus; +use crate::bind::index_rewrite::RewriteOrder; use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; use crate::spirv::testing::{assert_valid, committed_profiles}; @@ -370,99 +366,6 @@ fn a_run_refuses_what_it_cannot_take() { None, "workgroups past the most" ); - // A direct run takes no indirect draw. - let indirect = IndirectGatherDraw { - arguments_offset: 0, - index_offset: 64, - index_end: 4096, - wide: false, - }; - assert_eq!(wide.push_indirect(indirect), None); -} - -/// An indirect run refuses a program that does not gather draws of its kind, arguments outside -/// its bytes or at an offset not a multiple of 4, an index offset not a multiple of the index -/// size, indices outside its bytes, a direct draw, and draws past the plan's most. -#[test] -fn an_indirect_run_refuses_what_it_cannot_take() { - let limits = (ALIGNMENT, 1 << 16); - let indexed = Some((64, 4096)); - for program in RewriteProgram::ALL { - let order = RewriteOrder::LastFirst; - let with = IndexGather::indirect((program, order), (0, 400), indexed, limits, 1024); - assert_eq!(with.is_some(), program.gathers(), "{program:?}"); - let without = IndexGather::indirect((program, order), (0, 400), None, limits, 1024); - assert_eq!( - without.is_some(), - program.gathers_without_indices(), - "{program:?}" - ); - } - let program = (RewriteProgram::TriangleList, RewriteOrder::LastFirst); - let mut run = IndexGather::indirect(program, (16, 400), indexed, limits, 1024).expect("run"); - assert!(run.is_indirect()); - let draw = |arguments_offset, index_offset, wide| IndirectGatherDraw { - arguments_offset, - index_offset, - index_end: 4096, - wide, - }; - assert_eq!( - run.push_indirect(draw(18, 64, false)), - None, - "arguments' offset" - ); - assert_eq!( - run.push_indirect(draw(8, 64, false)), - None, - "before the arguments" - ); - assert_eq!( - run.push_indirect(draw(384, 64, false)), - None, - "past the arguments" - ); - assert_eq!( - run.push_indirect(draw(16, 65, false)), - None, - "odd index offset" - ); - assert_eq!( - run.push_indirect(draw(16, 32, true)), - None, - "before the indices" - ); - assert_eq!(run.push_indirect(draw(16, 64, true)), Some(0)); - assert_eq!(run.push_indirect(draw(36, 66, false)), Some(1)); - // Wholly past the index bytes: reads no index. - assert_eq!(run.push_indirect(draw(56, 8192, true)), Some(2)); - let direct = GatherDraw { - count: 3, - index_offset: 64, - index_end: 4096, - wide: false, - }; - assert_eq!(run.push(direct), None, "a direct draw"); - let range = run.arguments_range().expect("arguments"); - assert_eq!((range.offset, range.range), (16, 384)); - let table = run.table(); - assert_eq!(table[..10], [3, 0, 0, 1024, 0, 0, 0, 0, 3, 3]); - let record = |i: usize| { - let at = - (IndexGatherModule::HEADER_WORDS + IndexGatherModule::RECORD_WORDS * i as u32) as usize; - table[at..at + 8].to_vec() - }; - assert_eq!(record(0), [0, 0, 0, 0, 1008, 1, 0, 0]); - assert_eq!(record(1), [0, 0, 0, 2, 2015, 0, 0, 5]); - assert_eq!(record(2), [0, 0, 0, 0, 0, 1, 0, 10]); - let mut full = IndexGather::indirect(program, (0, 1 << 15), None, limits, 1024).expect("run"); - for i in 0..IndexGatherPlanModule::MAX_DRAWS { - assert_eq!( - full.push_indirect(draw(u64::from(i) * 16, 0, false)), - Some(i) - ); - } - assert_eq!(full.push_indirect(draw(0, 0, false)), None, "past the most"); } /// A 16-bit buffer of an odd number of indices: Metal's fetch reads its partial last index from @@ -491,275 +394,3 @@ fn a_partial_last_index_reads_its_word() { ); assert_eq!(lists[0][5], 0xCCCC); } - -/// One indirect draw of a test: its Metal arguments (four words without indices), and an indexed -/// draw's index offset in the buffer and index size. -#[derive(Clone, Debug)] -struct Indirect { - arguments: Vec, - offset: u64, - wide: bool, -} - -/// What an indirect run's plan and gather left: each draw's command and list, the pool's counter, -/// and whether the plan reported an overflow. -struct Planned { - draws: Vec<([u32; 5], Vec)>, - counter: u32, - overflow: bool, -} - -/// Where the arguments start in their `VkBuffer`, and each draw's arguments' stride. -const ARGUMENTS_BASE: u64 = 32; -const ARGUMENTS_STRIDE: u64 = 24; - -/// The indirect run of `draws` of `program` in `order` (over `buffer`, an index buffer at [`BASE`] -/// of its `VkBuffer`, or without indices) into a pool of `pool_bytes` index bytes whose counter -/// starts at `counter`, as the interpreter runs the plan and then the gather over the plan's -/// dispatch, in both workgroup orders. -fn planned( - (program, order): (RewriteProgram, RewriteOrder), - buffer: Option<&[u8]>, - draws: &[Indirect], - (pool_bytes, counter): (u32, u32), -) -> Planned { - let end = ARGUMENTS_BASE + ARGUMENTS_STRIDE * draws.len() as u64; - let indices = buffer.map(|b| (BASE, BASE + b.len() as u64)); - let mut run_of = IndexGather::indirect( - (program, order), - (ARGUMENTS_BASE, end), - indices, - (ALIGNMENT, u32::MAX), - pool_bytes, - ) - .expect("the program gathers"); - let mut arguments = vec![0xEEEE_EEEEu32; (end / 4) as usize]; - for (i, draw) in draws.iter().enumerate() { - let at = (ARGUMENTS_BASE + ARGUMENTS_STRIDE * i as u64) as usize / 4; - arguments[at..at + draw.arguments.len()].copy_from_slice(&draw.arguments); - let place = run_of - .push_indirect(IndirectGatherDraw { - arguments_offset: (at * 4) as u64, - index_offset: BASE + draw.offset, - index_end: indices.map_or(0, |(_, end)| end), - wide: draw.wide, - }) - .expect("the run takes the draw"); - assert_eq!(place, i as u32); - } - let range = run_of.arguments_range().expect("arguments"); - let arguments = - bytes(&arguments)[range.offset as usize..(range.offset + range.range) as usize].to_vec(); - let indices = match (buffer, run_of.indices_range()) { - (Some(buffer), Some(range)) => { - let mut padded = vec![0xAB; BASE as usize]; - padded.extend_from_slice(buffer); - padded.resize(padded.len().next_multiple_of(16).max(16), 0xCC); - padded[range.offset as usize..(range.offset + range.range) as usize].to_vec() - } - _ => vec![0xCC; 4], - }; - let header = (IndexBoundsPass::POOL_HEADER_BYTES / 4) as usize; - let mut pool = vec![0xDDDD_DDDD; header + (pool_bytes / 4) as usize]; - pool[0] = counter; - let draw_words = (IndexGatherPlanModule::DRAW_BYTES / 4) as usize; - let commands = vec![0xFFFF_FFFFu32; draw_words * draws.len()]; - let plan = plan_typed_module().expect("plan"); - let gather = gather_typed_module().expect("gather"); - let buffer_of = |slot, bytes| Buffer { - slot: Some(slot), - address: None, - bytes, - }; - let mut ran = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let res = Resources { - buffers: vec![ - buffer_of(WORDS, run_of.table_bytes()), - buffer_of(plan::ARGUMENTS, arguments.clone()), - buffer_of(plan::POOL, bytes(&pool)), - buffer_of(STATUS, ExecutionStatus::initial().to_vec()), - buffer_of(plan::DRAWS, bytes(&commands)), - ], - push: Vec::new(), - spec: Default::default(), - }; - let cfg = Config { - order, - workgroups: [1, 1, 1], - ..Config::default() - }; - let after = run(&plan, &cfg, res).expect("plan run").buffers; - let table = words(&after[0]); - let at = (IndexGather::DISPATCH_OFFSET / 4) as usize; - let dispatch: [u32; 3] = table[at..at + 3].try_into().expect("dispatch"); - assert_eq!(dispatch[1..], [1, 1]); - assert_eq!(dispatch[0], table[2].min(IndexGatherModule::MAX_GROUPS)); - let res = Resources { - buffers: vec![ - buffer_of(TABLE, after[0].clone()), - buffer_of(PATTERN, bytes(&run_of.pattern())), - buffer_of(INDICES, indices.clone()), - buffer_of(OUTPUT, after[2].clone()), - ], - push: Vec::new(), - spec: Default::default(), - }; - let cfg = Config { - order, - workgroups: dispatch, - ..Config::default() - }; - let gathered = run(&gather, &cfg, res).expect("gather run").buffers; - ran.push((after, gathered)); - } - assert_eq!(ran[0], ran[1], "order independent"); - let (after, gathered) = &ran[0]; - let status: [u8; 32] = after[3].as_slice().try_into().expect("status"); - let pool = words(&gathered[3]); - let commands = words(&after[4]); - let lists = (0..draws.len()) - .map(|i| { - let command: [u32; 5] = commands[i * draw_words..(i + 1) * draw_words] - .try_into() - .expect("command"); - let first = header + command[2] as usize; - let list = pool[first..first + command[0] as usize].to_vec(); - (command, list) - }) - .collect(); - Planned { - draws: lists, - counter: pool[0], - overflow: ExecutionStatus::decode(&status).index_pool_overflow, - } -} - -/// Each indexed indirect draw of a gathering program gets the rewrite pass's list from its -/// arguments (first indices inside, reaching past and wholly past the buffer's whole indices, no -/// instance), placed one after another from the pool's counter, and its command its list and -/// Metal's other arguments; nothing overflows. -#[test] -fn indexed_indirect_draws_get_the_rewrite_pass_s_lists() { - let buffer: Vec = (0..1200u32).map(|b| (b * 37 + 11) as u8).collect(); - for program in RewriteProgram::ALL.into_iter().filter(|p| p.gathers()) { - for order in [RewriteOrder::First, RewriteOrder::LastFirst] { - for wide in [false, true] { - let size: u64 = if wide { 4 } else { 2 }; - // count, instances, first index, base vertex, base instance; the offset. - let cases = [ - ([7, 1, 0, 0, 0], 0), - ([140, 2, 3, 5, 1], 52), - ([13, 1, 280 / size as u32, u32::MAX, 0], 8), - ([24, 1, 0, 0, 0], 1188), - ([8, 1, 2, 0, 0], 4000), - ([9, 0, 0, 0, 0], 0), - ([2, 1, 0, 0, 0], 0), - ]; - let draws: Vec = cases - .iter() - .map(|&(arguments, offset)| Indirect { - arguments: arguments.to_vec(), - offset: offset / size * size, - wide, - }) - .collect(); - let counter = 40; - let p = planned((program, order), Some(&buffer), &draws, (1 << 14, counter)); - assert!(!p.overflow); - let mut next = counter / 4; - for (draw, (command, list)) in draws.iter().zip(&p.draws) { - let a = &draw.arguments; - let values: Vec = (0..a[0]) - .map(|q| { - let at = draw.offset + u64::from(a[2] + q) * size; - let inside = at + size <= buffer.len() as u64; - match (inside, wide) { - (false, _) => 0, - (true, true) => u32::from_le_bytes( - buffer[at as usize..at as usize + 4].try_into().expect("4"), - ), - (true, false) => u32::from(u16::from_le_bytes( - buffer[at as usize..at as usize + 2].try_into().expect("2"), - )), - } - }) - .collect(); - let expected = match a[1] { - 0 => Vec::new(), - _ => program.list(&values, u32::MAX, order), - }; - let what = format!("{program:?} {order:?} wide {wide} {a:?}"); - assert_eq!(list, &expected, "{what}"); - let n = expected.len() as u32; - assert_eq!(command, &[n, a[1], next, a[3], a[4]], "{what}"); - next += n; - } - assert_eq!(p.counter, next * 4); - } - } - } -} - -/// Each indirect draw without indices of every program but a line loop gets its positions' list -/// from its count, drawn from its vertex start as base vertex. -#[test] -fn indirect_draws_without_indices_get_their_positions_lists() { - for program in RewriteProgram::ALL - .into_iter() - .filter(|p| p.gathers_without_indices()) - { - for order in [ - RewriteOrder::First, - RewriteOrder::Last, - RewriteOrder::LastFirst, - ] { - // count, instances, vertex start, base instance. - let cases = [[9, 1, 0, 0], [300, 3, 17, 2], [1, 1, 5, 0], [6, 0, 0, 0]]; - let draws: Vec = cases - .iter() - .map(|a| Indirect { - arguments: a.to_vec(), - offset: 0, - wide: false, - }) - .collect(); - let p = planned((program, order), None, &draws, (1 << 14, 0)); - assert!(!p.overflow); - let mut next = 0; - for (a, (command, list)) in cases.iter().zip(&p.draws) { - let expected = match a[1] { - 0 => Vec::new(), - _ => program.sequential_list(a[0], order), - }; - let what = format!("{program:?} {order:?} {a:?}"); - assert_eq!(list, &expected, "{what}"); - let n = expected.len() as u32; - assert_eq!(command, &[n, a[1], next, a[2], a[3]], "{what}"); - next += n; - } - } - } -} - -/// A list the pool's room cannot hold is none, and the plan reports the overflow; the lists -/// before and after it that fit are placed. -#[test] -fn a_list_past_the_pool_s_room_is_none_and_reported() { - let program = (RewriteProgram::TriangleList, RewriteOrder::LastFirst); - let draws: Vec = [[30, 1, 0, 0], [3000, 1, 0, 0], [6, 1, 0, 0]] - .iter() - .map(|a| Indirect { - arguments: a.to_vec(), - offset: 0, - wide: false, - }) - .collect(); - // 256 bytes of room past the counter's 64: 48 indices. - let p = planned(program, None, &draws, (320, 64)); - assert!(p.overflow); - let counts: Vec = p.draws.iter().map(|(command, _)| command[0]).collect(); - assert_eq!(counts, [30, 0, 6]); - assert_eq!(p.draws[2].0[2], 16 + 30); - assert_eq!(p.counter, 64 + 36 * 4); -} diff --git a/crates/metal2vulkan/src/bind/mipmap_filter/tests.rs b/crates/metal2vulkan/src/bind/mipmap_filter/tests.rs index 6fede2723..cc67284fb 100644 --- a/crates/metal2vulkan/src/bind/mipmap_filter/tests.rs +++ b/crates/metal2vulkan/src/bind/mipmap_filter/tests.rs @@ -15,15 +15,27 @@ use crate::spirv::ir::TypedModule; use crate::spirv::testing::{check_valid, committed_profiles}; use crate::vk::Format; +/// The view a fetch reads an image of `image` through: the UNORM twin of an 8-bit sRGB format (the +/// same bytes, its codes undecoded), else the image's own. +fn unorm_twin(image: Format) -> Format { + match image { + Format::R8_SRGB => Format::R8_UNORM, + Format::R8G8_SRGB => Format::R8G8_UNORM, + Format::R8G8B8A8_SRGB => Format::R8G8B8A8_UNORM, + Format::B8G8R8A8_SRGB => Format::B8G8R8A8_UNORM, + other => other, + } +} + /// The sampled views through which a fetch reads the first level of `pf`: one per candidate -/// Vulkan format of its image whose fetch recovers the texel (`MipmapFilterChain::fetch_format`). +/// Vulkan format of its image whose fetch recovers the texel, through its view (`unorm_twin`). fn fetch_views(pf: PixelFormat) -> Vec { let Some(l) = layout(pf) else { return Vec::new(); }; let mut views: Vec = candidate_formats(pf) .into_iter() - .filter_map(MipmapFilterChain::fetch_format) + .map(unorm_twin) .filter(|&view| components(view).is_some_and(|c| fits(&l, &c))) .collect(); views.dedup(); @@ -784,19 +796,4 @@ fn the_plan_fetches_only_what_a_fetch_recovers() { fetched(PixelFormat::BGRA10XRSRGB, Some(Format::R16G16B16A16_UINT)), Some(Format::R16G16B16A16_UINT) ); - assert_eq!( - MipmapFilterChain::fetch_format(Format::B8G8R8A8_SRGB), - Some(Format::B8G8R8A8_UNORM) - ); - assert_eq!(MipmapFilterChain::fetch_format(Format::R32_SFLOAT), None); - assert!(MipmapFilterChain::fetch_converts( - Format::R16G16B16A16_SFLOAT - )); - assert!(MipmapFilterChain::fetch_converts( - Format::A2B10G10R10_UNORM_PACK32 - )); - assert!(!MipmapFilterChain::fetch_converts(Format::R32_UINT)); - assert!(!MipmapFilterChain::fetch_converts( - Format::R16G16B16A16_UINT - )); } diff --git a/crates/metal2vulkan/src/bind/neutral.rs b/crates/metal2vulkan/src/bind/neutral.rs index 4f1342427..d40f5f558 100644 --- a/crates/metal2vulkan/src/bind/neutral.rs +++ b/crates/metal2vulkan/src/bind/neutral.rs @@ -297,8 +297,7 @@ pub fn ulong_classes(profile: &DeviceProfile) -> Vec { out } -impl Device { -} +impl Device {} /// Bytes of the `ZeroBuffer` neutral on `profile`: large enough for any uniform-buffer view /// (`maxUniformBufferRange`, capped at 64 KiB), a multiple of 16. diff --git a/crates/metal2vulkan/src/bind/neutral/tests.rs b/crates/metal2vulkan/src/bind/neutral/tests.rs index ebe7eed6f..b8589b0ad 100644 --- a/crates/metal2vulkan/src/bind/neutral/tests.rs +++ b/crates/metal2vulkan/src/bind/neutral/tests.rs @@ -1,5 +1,6 @@ -//! The required test: on every committed profile, every image type the core can declare has a -//! neutral in `Device::neutral_kinds()` that satisfies Vulkan's view/format compatibility rules. +//! The neutral resources: a `ulong` atomic's neutral is listed exactly where its slot compiles, +//! the zero buffer covers any uniform view, an undeclarable type has none, and their formats follow +//! the declared type and the registry's numeric formats. use std::collections::BTreeSet; use std::path::PathBuf; @@ -151,76 +152,6 @@ fn assert_compatible(stem: &str, class: &ImageHandleClass, n: &NeutralResource, } } -#[test] -fn every_declarable_image_has_a_compatible_neutral_on_every_profile() { - for (stem, device) in committed_devices() { - let profile = device.profile(); - let kinds: BTreeSet = device.neutral_kinds().into_iter().collect(); - let mut classes = image_classes(profile); - assert!(!classes.is_empty(), "{stem}"); - classes.extend(ulong_classes(profile)); - let depth_dims: BTreeSet<(ImageDim, bool, bool)> = classes - .iter() - .filter(|c| c.depth_compare) - .map(|c| (c.dim, c.arrayed, c.multisampled)) - .collect(); - for shape in [ - (ImageDim::D2, false, false), - (ImageDim::D2, true, false), - (ImageDim::D2, false, true), - (ImageDim::D2, true, true), - (ImageDim::Cube, false, false), - ] { - assert!(depth_dims.contains(&shape), "{stem}: depth {shape:?}"); - } - assert!( - depth_dims - .iter() - .all(|&(dim, _, _)| matches!(dim, ImageDim::D2 | ImageDim::Cube)), - "{stem}: depth only for 2D and cube: {depth_dims:?}" - ); - for class in &classes { - let n = NeutralResource::for_image(class) - .unwrap_or_else(|| panic!("{stem}: no neutral for {class:?}")); - assert!( - kinds.contains(&n), - "{stem}: {n:?} missing from neutral_kinds" - ); - assert_compatible(&stem, class, &n, profile); - } - for n in [ - NeutralResource::ZeroBuffer { - min_bytes: zero_buffer_bytes(profile), - }, - NeutralResource::Sink { min_bytes: 64 }, - NeutralResource::Sampler { compare: false }, - NeutralResource::Sampler { compare: true }, - ] { - assert!(kinds.contains(&n), "{stem}: {n:?} missing"); - } - } -} - -#[test] -fn neutral_kinds_are_exactly_the_derived_set() { - for (stem, device) in committed_devices() { - let kinds = device.neutral_kinds(); - let sorted: Vec = kinds - .iter() - .copied() - .collect::>() - .into_iter() - .collect(); - assert_eq!(kinds, sorted, "{stem}: fixed order, no duplicates"); - let images: BTreeSet = image_classes(device.profile()) - .iter() - .chain(&ulong_classes(device.profile())) - .filter_map(NeutralResource::for_image) - .collect(); - assert_eq!(kinds.len(), images.len() + 4, "{stem}"); - } -} - /// A `ulong` slot that a `ulong` atomic updates is declared `R64ui`: its `R64_UINT` neutral is /// listed exactly where the profile has what that slot needs, image and texel buffer apart, and /// never on MoltenVK, which has no 64-bit image atomics. diff --git a/crates/metal2vulkan/src/bind/rate_map.rs b/crates/metal2vulkan/src/bind/rate_map.rs index 9746ee119..f86ac6cf8 100644 --- a/crates/metal2vulkan/src/bind/rate_map.rs +++ b/crates/metal2vulkan/src/bind/rate_map.rs @@ -497,7 +497,6 @@ pub struct RasterizationRateMap { } impl RasterizationRateMap { - /// Compile `desc` (`newRasterizationRateMapWithDescriptor:`) by this module's rule, Apple /// M3's, or refuse it ([`RateMapError::Unpinned`]) outside the bounds the rule is measured in. /// A descriptor of no layers compiles to a map of none. diff --git a/crates/metal2vulkan/src/bind/rate_map/apple_tests.rs b/crates/metal2vulkan/src/bind/rate_map/apple_tests.rs index 32ec91c88..67eb5c954 100644 --- a/crates/metal2vulkan/src/bind/rate_map/apple_tests.rs +++ b/crates/metal2vulkan/src/bind/rate_map/apple_tests.rs @@ -179,35 +179,3 @@ fn metals_integer_answers() { mismatches[..mismatches.len().min(20)].join("\n") ); } - -/// A reset to and from a map of a zero screen extent writes Metal's words (an Apple M3 Max under -/// macOS 27.0.1, our probe `vec`, one map per process): a 64 by 64 map of quality 0.5 reset to 0 -/// by 64 keeps the entries the narrower map does not write, and the same map reset the other way -/// holds exactly what a fresh 64 by 64 map holds. -#[test] -fn metals_words_across_a_zero_extent_reset() { - let half = |screen| { - let mut d = RateMapDescriptor::new(screen); - d.layers - .push(RateMapLayerDescriptor::new(vec![0.5], vec![0.5])); - d - }; - let wide = RasterizationRateMap::new(&half([64, 64])).expect("64 by 64"); - let narrowed = - RasterizationRateMap::new_over(&half([0, 64]), wide.words()).expect("reset to 0 by 64"); - assert_eq!(narrowed.physical_size(0), Some([0, 33])); - assert_eq!( - sha(&narrowed.to_bytes()), - "e8367ffa698309495b1907fddd1a752dee56f95d953f513aa11a2a900f7c221d", - "the reset to a zero screen width is not Metal's" - ); - let narrow = RasterizationRateMap::new(&half([0, 64])).expect("0 by 64"); - let widened = - RasterizationRateMap::new_over(&half([64, 64]), narrow.words()).expect("reset to 64 by 64"); - assert_eq!(widened.to_bytes(), wide.to_bytes()); - assert_eq!( - sha(&widened.to_bytes()), - "4c21eca9c26d2f2d4f50ce61db86bda15021461bf41b9eccc94798443a93dd5e", - "the reset from a zero screen width is not Metal's" - ); -} diff --git a/crates/metal2vulkan/src/bind/rate_map/tests.rs b/crates/metal2vulkan/src/bind/rate_map/tests.rs index fced6be43..a54b479f5 100644 --- a/crates/metal2vulkan/src/bind/rate_map/tests.rs +++ b/crates/metal2vulkan/src/bind/rate_map/tests.rs @@ -832,53 +832,6 @@ fn fnv(bytes: &[u8]) -> u64 { }) } -/// A reset writes the new map's tables over the old (`new_over`), as Metal's private -/// `resetUsingDescriptor:` does (our probe `none`, the M3 Max under macOS 27.0.1: a mutable map of -/// 64 by 32 screen pixels reset to 100 by 60 at one and two layers, then to no layers; every byte of -/// each map's parameter data, here by its hash). Each map reset to no layers keeps the horizontal -/// tables and the vertical entries past its own; a map over zero words is `new`'s. -#[test] -fn a_reset_writes_its_tables_over_the_maps() { - let none = RateMapDescriptor::new([64, 32]); - let fresh = RasterizationRateMap::new(&none).unwrap(); - assert_eq!( - fnv(&fresh.to_bytes()), - 0x7ead_0d0b_02b1_afdb, - "a fresh map of none" - ); - let zeros = vec![0u32; format::WORDS as usize]; - assert_eq!( - RasterizationRateMap::new_over(&none, &zeros), - Ok(fresh.clone()) - ); - let cases: [(&[RateMapLayerDescriptor], u64, u64); 3] = [ - ( - &[layer(&[0.5], &[0.5])], - 0xb906_457e_1eb4_0870, - 0x03b3_2978_774d_4131, - ), - ( - &[layer(&[0.5], &[0.5]), layer(&[0.25], &[0.25])], - 0x2b20_361b_8ed2_a324, - 0x5fb1_b833_f7c6_3085, - ), - ( - &[layer(&[1.0], &[1.0])], - 0x3185_559d_f1c5_12a1, - 0xcd66_ddc9_de96_0d01, - ), - ]; - for (layers, before, after) in cases { - let earlier = map([100, 60], layers); - assert_eq!(fnv(&earlier.to_bytes()), before, "{layers:?}"); - let reset = RasterizationRateMap::new_over(&none, earlier.words()).unwrap(); - assert_eq!(fnv(&reset.to_bytes()), after, "{layers:?} reset to none"); - assert_eq!(reset.words()[..4104], earlier.words()[..4104]); - assert_eq!(reset.layer_count(), 0); - assert_eq!(reset.vertical(), fresh.vertical()); - } -} - /// An axis of no screen pixels has one tile of no screen and no physical pixels, whatever its /// quality samples, so the layer's physical extent on it is 0 and the map compiles (Metal's API /// validation stops the descriptor; plain Metal compiles it, and `apple_tests` holds its bytes). diff --git a/crates/metal2vulkan/src/bind/replay/draws.rs b/crates/metal2vulkan/src/bind/replay/draws.rs index e1b19aad4..a40168493 100644 --- a/crates/metal2vulkan/src/bind/replay/draws.rs +++ b/crates/metal2vulkan/src/bind/replay/draws.rs @@ -283,7 +283,6 @@ impl DrawReplayLayout { pub fn params_offset(&self) -> u64 { self.resident_offset - PARAMS_BYTES } - } /// The preprocess of one draw replay: what the consumer uploads into the scratch (of diff --git a/crates/metal2vulkan/src/bind/replay/draws/tests.rs b/crates/metal2vulkan/src/bind/replay/draws/tests.rs index 8f4b6ec2b..a91c5b27b 100644 --- a/crates/metal2vulkan/src/bind/replay/draws/tests.rs +++ b/crates/metal2vulkan/src/bind/replay/draws/tests.rs @@ -244,8 +244,8 @@ fn preprocess_raw( put(bytes.offset, &BYTES.to_le_bytes()); } if let Some([location, length]) = range { - put(l.range_offset(), &location.to_le_bytes()); - put(l.range_offset() + 4, &length.to_le_bytes()); + put(l.params_offset() + P_RANGE, &location.to_le_bytes()); + put(l.params_offset() + P_RANGE + 4, &length.to_le_bytes()); } let mut push = pre.push_constants.clone(); for hole in &pre.push_holes { diff --git a/crates/metal2vulkan/src/bind/replay/predication.rs b/crates/metal2vulkan/src/bind/replay/predication.rs index 30305f16c..95dda9552 100644 --- a/crates/metal2vulkan/src/bind/replay/predication.rs +++ b/crates/metal2vulkan/src/bind/replay/predication.rs @@ -237,7 +237,6 @@ pub enum PredicationCompare { } impl PredicationCompare { - fn code(self) -> u32 { match self { PredicationCompare::Equal => 0, diff --git a/crates/metal2vulkan/src/bind/replay/tests.rs b/crates/metal2vulkan/src/bind/replay/tests.rs index e798fa4ef..a67cb9841 100644 --- a/crates/metal2vulkan/src/bind/replay/tests.rs +++ b/crates/metal2vulkan/src/bind/replay/tests.rs @@ -2143,7 +2143,12 @@ fn bound_out( }; let record = bound.record(0).to_vec(); let gate_bytes = PredicationStep::GATE_BYTES as usize; - let mut region = vec![0xEE; PredicationStep::bound_bytes(gates.len() as u64) as usize]; + let mut region = vec![ + 0xEE; + (PredicationStep::BOUND_GATES_OFFSET + + (gates.len() as u64 + 1) * PredicationStep::GATE_BYTES) + as usize + ]; region[..record.len()].copy_from_slice(&record); let count = PredicationStep::BOUND_COUNT_OFFSET as usize; region[count..count + 4].copy_from_slice(&(gates.len() as u32).to_le_bytes()); @@ -2420,31 +2425,6 @@ fn a_predication_step_drops_holds_resumes_and_checks_a_units_end() { ); } -/// Metal's six comparison codes compare the word with the reference unsigned, the word on the left, -/// and every other code compares `==` (measured: 6, 7, 8, 255, `2^32 + 2`, `2^64 - 1`). -#[test] -fn a_predication_condition_compares_as_metal_does() { - let words = [0u32, 1, 7, 8, 9, 0x8000_0000, u32::MAX]; - for raw in [0u64, 1, 2, 3, 4, 5, 6, 7, 8, 255, 0x1_0000_0002, u64::MAX] { - let compare = PredicationCompare::from_metal(raw); - for &word in &words { - let reference = 8; - let expected = match raw { - 1 => word != reference, - 2 => word > reference, - 3 => word >= reference, - 4 => word < reference, - 5 => word <= reference, - _ => word == reference, - }; - assert_eq!(compare.holds(word, reference), expected, "{raw} {word}"); - let step = PredicationStep::condition(STEP_COUNTER, STEP_WORD, compare, reference); - let (c, _) = step_run(step, 0, Some(word), &[]); - assert_eq!(c, u32::from(!expected), "code {raw}, word {word:#x}"); - } - } -} - /// A step's gates run their commands where the counter it leaves is 0, and nothing (a zero command) /// where not. #[test] @@ -2484,7 +2464,7 @@ fn a_predication_table_ends_at_the_records_sink_gate() { for gates in 0..3 { let past = PredicationStep::BOUND_GATES_OFFSET + gates * PredicationStep::GATE_BYTES; assert_eq!( - PredicationStep::bound_bytes(gates), + PredicationStep::BOUND_GATES_OFFSET + (gates + 1) * PredicationStep::GATE_BYTES, past + PredicationStep::GATE_BYTES ); } @@ -2511,9 +2491,15 @@ const OTHER_ID: u32 = 3; /// word it leaves. fn loop_run(op: PredicationOp, holds: bool, (counter, flag, halt): (u32, u32, u32)) -> [u32; 3] { let reference = if holds { 8 } else { 7 }; - let step = PredicationStep::new(STEP_COUNTER, op) - .testing(STEP_WORD, PredicationCompare::Less, reference) - .in_loop(STEP_FLAG, LOOP_ID); + let step = PredicationStep { + flag: STEP_FLAG, + id: LOOP_ID, + ..PredicationStep::new(STEP_COUNTER, op).testing( + STEP_WORD, + PredicationCompare::Less, + reference, + ) + }; let record = step.record(STEP_RECORD).to_vec(); let buffer = |address, bytes: Vec| Buffer { slot: None, @@ -2554,7 +2540,8 @@ fn bound_loop_run(step: PredicationStep, (counter, flag, halt): (u32, u32, u32)) ..step }; let record = bound.record(0).to_vec(); - let mut region = vec![0; PredicationStep::bound_bytes(0) as usize]; + let mut region = + vec![0; (PredicationStep::BOUND_GATES_OFFSET + PredicationStep::GATE_BYTES) as usize]; region[..record.len()].copy_from_slice(&record); let mut words = vec![0xEE; BOUND_WORD_AT + 8]; words[BOUND_WORD_AT..BOUND_WORD_AT + 4].copy_from_slice(&7u32.to_le_bytes()); @@ -2678,9 +2665,15 @@ fn a_halted_unit_holds_every_step_and_runs_nothing() { assert_eq!(left, Some(word), "{:?} at {c}", step.op); } } - let first = PredicationStep::new(STEP_COUNTER, PredicationOp::WhileFirst) - .testing(STEP_WORD, PredicationCompare::Equal, 7) - .in_loop(STEP_FLAG, LOOP_ID); + let first = PredicationStep { + flag: STEP_FLAG, + id: LOOP_ID, + ..PredicationStep::new(STEP_COUNTER, PredicationOp::WhileFirst).testing( + STEP_WORD, + PredicationCompare::Equal, + 7, + ) + }; let resumed = halted_out(first, (0, LOOP_ID), Some(7), &gates); assert_eq!((resumed.0, resumed.1), ((0, 0), gates.to_vec())); let other = halted_out(first, (0, OTHER_ID), Some(7), &gates); diff --git a/crates/metal2vulkan/src/bind/resident/tests.rs b/crates/metal2vulkan/src/bind/resident/tests.rs index d35af48b0..65de7369f 100644 --- a/crates/metal2vulkan/src/bind/resident/tests.rs +++ b/crates/metal2vulkan/src/bind/resident/tests.rs @@ -339,40 +339,6 @@ fn ranges_listed_apart_join_the_resident_set_and_not_the_shape() { assert_eq!(listed.shape(), state.shape()); } -/// A root table's `R0` points at a resident set uploaded apart, below or above the table, as a -/// count of 32-byte entries modulo `2^64`; a set not a whole number of entries away is refused. -#[test] -fn a_root_table_points_at_a_resident_set_uploaded_apart() { - use crate::bind::instantiate::ResidentRange; - for (table, set) in [(0x1000u64, 0x2000u64), (0x2000, 0x1000), (0x40, 0x40)] { - let fields = RootTable::resident_fields(table, set, 7).unwrap(); - let first = u64::from_le_bytes(fields[..8].try_into().unwrap()); - let count = u64::from_le_bytes(fields[8..].try_into().unwrap()); - assert_eq!(table.wrapping_add(first.wrapping_mul(32)), set); - assert_eq!(count, 7); - } - assert_eq!(RootTable::resident_fields(0x1000, 0x1010, 1), None); - // The fields lie where the search reads `R0` and `N`. - let table = stage_root_table( - &[], - 2, - &[RootEntry { - host: 0x9000, - guest: 0x4000, - size: 64, - bind_offset: 0, - }], - ); - let at = RootTable::RESIDENT_FIELDS_OFFSET as usize; - let first = u64::from_le_bytes(table.bytes[at..at + 8].try_into().unwrap()); - let count = u64::from_le_bytes(table.bytes[at + 8..at + 16].try_into().unwrap()); - assert_eq!((first, count), (2, 1)); - assert_eq!( - table.resident_ranges(), - vec![ResidentRange::new(0x9000, 0x4000, 64)] - ); -} - /// A resident set made apart coalesces as a root table's does, and holds a range exactly where /// one of its entries resolves every address of it to the same device address. #[test] @@ -399,50 +365,6 @@ fn a_resident_set_holds_what_its_entries_resolve_alike() { assert!(with.holds(&other) && with.holds(&own) && with.holds(&placed)); } -/// What a consumer points a replay preprocess's resident root table at holds the set of its -/// ranges in their entries' layout, then each entry's unpadded extent, then a zero: the same -/// set, and the same extents, as the binder lays out after the table it builds of those -/// allocations, so a table pointed there resolves as the binder's own does. -#[test] -fn replay_bytes_are_the_binders_set_then_its_extents() { - use crate::bind::{ResidentRange, ResidentSet}; - // Three allocations, one inside another and one of a length the padding rounds up. - let ranges = [ - ResidentRange::new(0x9000, 0x1_0000_0000, 64), - ResidentRange::new(0x9010, 0x1_0000_0010, 16), - ResidentRange::new(0x5000, 0x2_0000_0000, 60), - ]; - let (bytes, count) = ResidentSet::replay_bytes(ranges); - let set = ResidentSet::new(ranges); - assert_eq!(count, set.len()); - assert_eq!(count, 2); - let entries = set.bytes(); - assert_eq!(&bytes[..entries.len()], &entries[..]); - let extents: Vec = bytes[entries.len()..] - .as_chunks::<8>() - .0 - .iter() - .map(|c| u64::from_le_bytes(*c)) - .collect(); - assert_eq!(extents, [64, 60, 0]); - let allocations = ranges.iter().map(|r| (r.guest, r.length)); - let entries: Vec = (set.bytes().as_chunks::<32>().0.iter()) - .map(|e| { - let field = |at: usize| u64::from_le_bytes(e[at..at + 8].try_into().unwrap()); - RootEntry { - host: field(0), - guest: field(8), - size: field(16), - bind_offset: field(24), - } - }) - .collect(); - assert_eq!( - extents_bytes(extents_of(allocations, &entries)), - bytes[set.bytes().len()..] - ); -} - /// Under `BindState::resident_apart` a root table's own resident set is the bound buffers' alone, /// and without it the whole set; and a resident set made of a table's ranges and of the used /// resources' and listed ranges (as a consumer that points its tables at one makes it) is the same @@ -571,38 +493,3 @@ fn list_ranges(rng: &mut Rng, sorted: bool) -> Vec { } ranges } - -/// The property a consumer's cached parts rest on: the set joined of parts -/// (`ResidentSet::of_parts`), each made of a run of consecutive ranges of a list, is the set made -/// of the whole list (`ResidentSet::new`), entry for entry: parts in order, parts whose ranges -/// interleave, empty parts, shared starts at different hosts (where the order of the list -/// decides), and records. -#[test] -fn a_set_joined_of_parts_is_the_set_of_their_ranges() { - use crate::bind::{ResidentPart, ResidentSet}; - let mut rng = Rng(0xD1B5_4A32_D192_ED03); - let mut interleaved = 0; - for case in 0..4000 { - let ranges = list_ranges(&mut rng, case % 2 == 0); - let mut parts = Vec::new(); - // The greatest start of a range before the part, and whether a part's starts below it. - let (mut greatest, mut below) = (0, false); - let mut at = 0; - while at < ranges.len() { - let take = (rng.below(10) as usize).min(ranges.len() - at); - let part = &ranges[at..at + take]; - let starts = part.iter().filter(|range| range.length > 0); - below |= starts.clone().any(|range| range.guest < greatest); - greatest = starts.map(|range| range.guest).fold(greatest, u64::max); - parts.push(ResidentPart::new(part.iter().copied())); - at += take; - } - if rng.below(4) == 0 { - parts.push(ResidentPart::new([])); - } - let want = ResidentSet::new(ranges.iter().copied()); - assert_eq!(ResidentSet::of_parts(&parts), want, "case {case}"); - interleaved += usize::from(below); - } - assert!(interleaved > 1000, "{interleaved} cases interleave"); -} diff --git a/crates/metal2vulkan/src/bind/sample_planes.rs b/crates/metal2vulkan/src/bind/sample_planes.rs index 7470f2f51..4ac6731f2 100644 --- a/crates/metal2vulkan/src/bind/sample_planes.rs +++ b/crates/metal2vulkan/src/bind/sample_planes.rs @@ -72,8 +72,8 @@ pub enum PlanesCopy { Rgba32, /// One byte of `A8_UNORM`'s own compatibility class ("8-bit alpha"), which no view of another /// format reads: moved through `A8_UNORM` views as the `float` each reads, `code / 255` in - /// alpha, which its store keeps as the code. Not a bits copy ([`PlanesCopy::for_format`]): - /// the sample planes' copies alone take it ([`PlanesCopy::for_planes`]). + /// alpha, which its store keeps as the code. Not a bits copy ([`PlanesCopy::moves_bits`]): + /// the sample planes' copies alone take it. Alpha8, } @@ -88,34 +88,6 @@ impl PlanesCopy { PlanesCopy::Alpha8, ]; - /// The copy format of `format` through which a copy moves its texels' bits: a color format - /// of one texel per block, of 1, 2, 4, 8 or 16 bytes, which shares the compatibility class of - /// that unsigned format, so a view of it moves the texel's bits. `None` for a depth, stencil, - /// compressed, multi-planar or 3-component 96-bit format, and for one of a class of its own - /// (`A8_UNORM`'s "8-bit alpha", the 4-pack 10- and 12-bit formats', the 4:2:2 formats'), - /// which no view of another format reads (VUID-VkImageCreateInfo-pNext-06722). - pub fn for_format(format: Format) -> Option { - let block = format.block()?; - if block.color.is_none() || block.depth.is_some() || block.stencil.is_some() { - return None; - } - if block.texels != 1 { - return None; - } - let copy = match block.size { - 1 => PlanesCopy::R8, - 2 => PlanesCopy::R16, - 4 => PlanesCopy::R32, - 8 => PlanesCopy::Rg32, - 16 => PlanesCopy::Rgba32, - _ => return None, - }; - copy.format() - .block() - .is_some_and(|own| own.class == block.class) - .then_some(copy) - } - /// The Vulkan format of the copy's views: an unsigned-integer one, or `A8_UNORM` for /// [`PlanesCopy::Alpha8`]. pub fn format(self) -> Format { diff --git a/crates/metal2vulkan/src/bind/sample_planes/tests.rs b/crates/metal2vulkan/src/bind/sample_planes/tests.rs index fb2e9809c..b42ce4e11 100644 --- a/crates/metal2vulkan/src/bind/sample_planes/tests.rs +++ b/crates/metal2vulkan/src/bind/sample_planes/tests.rs @@ -1,5 +1,5 @@ //! The sample planes' copy modules: what each needs, valid on every committed profile that has -//! it (L3, `G-val`), refused on a device that does not; and the copy format of each texel size. +//! it (L3, `G-val`), refused on a device that does not. use super::*; use crate::device::requirements::VkFeature; @@ -7,48 +7,6 @@ use crate::device::{DeviceDescription, DevicePolicy}; use crate::spirv::testing::assert_valid; use std::path::PathBuf; -/// The copy format follows the texel size of a single-texel color format that shares its -/// compatibility class, and no other format has one; the sample planes' copies take `A8_UNORM`'s -/// own format besides. -#[test] -fn the_copy_format_is_the_texel_size() { - for (format, copy) in [ - (Format::R8_UNORM, Some(PlanesCopy::R8)), - (Format::R8G8_UNORM, Some(PlanesCopy::R16)), - (Format::R16_SFLOAT, Some(PlanesCopy::R16)), - (Format::R8G8B8A8_SRGB, Some(PlanesCopy::R32)), - (Format::B10G11R11_UFLOAT_PACK32, Some(PlanesCopy::R32)), - (Format::R32_SFLOAT, Some(PlanesCopy::R32)), - (Format::R16G16B16A16_SNORM, Some(PlanesCopy::Rg32)), - (Format::R32G32B32A32_UINT, Some(PlanesCopy::Rgba32)), - (Format::R32G32B32_SFLOAT, None), - (Format::D32_SFLOAT, None), - (Format::S8_UINT, None), - (Format::BC1_RGBA_UNORM_BLOCK, None), - // A size shared with a copy format, a class of its own: no view of it in the copy's. - (Format::A8_UNORM, None), - (Format::A1B5G5R5_UNORM_PACK16, Some(PlanesCopy::R16)), - (Format::R10X6G10X6B10X6A10X6_UNORM_4PACK16, None), - (Format::G8B8G8R8_422_UNORM, None), - ] { - assert_eq!(PlanesCopy::for_format(format), copy, "{format:?}"); - let planes = match format { - Format::A8_UNORM => Some(PlanesCopy::Alpha8), - _ => copy, - }; - assert_eq!(PlanesCopy::for_planes(format), planes, "{format:?}"); - } - for copy in PlanesCopy::ALL { - assert_eq!( - PlanesCopy::for_planes(copy.format()), - Some(copy), - "{copy:?}" - ); - let bits = copy.moves_bits().then_some(copy); - assert_eq!(PlanesCopy::for_format(copy.format()), bits, "{copy:?}"); - } -} - /// The requirements of `m` as serialized. fn needs(m: TypedModule) -> Requirements { crate::spirv::serialize::serialize(m) diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index fcb61a704..337800b3c 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -721,7 +721,6 @@ impl TessellationFactorBuffer { } impl BindState { - /// The projection of this state that can change a plan: per stage, which slots are bound and /// with what kind of resource, whether a buffer has a device address, its per-bind stride, its /// length class as the table's [`StageTable::buffer_ranges`] tell it apart and bind-offset @@ -1943,9 +1942,7 @@ pub struct BindShape { pub region_fan_out: Option, } -impl BindShape { - -} +impl BindShape {} /// One stage's slots into a shape key ([`BindShape::key_beside_used`]): the stage, then each /// class's count and its slots' shapes in index order, as a state's table and a shape's give them. diff --git a/crates/metal2vulkan/src/bind/tiled_texels/tests.rs b/crates/metal2vulkan/src/bind/tiled_texels/tests.rs index 480cd377e..545418ffe 100644 --- a/crates/metal2vulkan/src/bind/tiled_texels/tests.rs +++ b/crates/metal2vulkan/src/bind/tiled_texels/tests.rs @@ -218,76 +218,3 @@ fn a_shape_takes_at_most_sixteen_levels() { assert!(TiledTexelsModule::shape(&vec![level; limit], true, 64).is_some()); assert!(TiledTexelsModule::shape(&vec![level; limit + 1], true, 64).is_none()); } - -/// A level of 32-bit float depths that the move into the image clamps -/// ([`TiledLevelMove::clamping_depth`]): each value inside `[0, 1]` bit for bit (`-0.0` and a -/// denormal among them), a negative one 0.0, one above 1.0 (an infinity too) 1.0, and a NaN of -/// either sign 1.0; the same level unclamped moves every value as it is, and back each takes the -/// tight bytes as they are. -#[test] -fn clamped_depths_move_into_the_image_inside_0_1() { - let values: [u32; 12] = [ - 0x0000_0000, - 0x8000_0000, - 0x0000_0001, - 0x3f00_0000, - 0x3f80_0000, - 0x3f80_0001, - 0x7f80_0000, - 0x7fc0_0000, - 0xbf80_0000, - 0xff80_0000, - 0xffc0_0000, - 0xeeee_eeee, - ]; - let clamped: [u32; 12] = [ - 0x0000_0000, - 0x8000_0000, - 0x0000_0001, - 0x3f00_0000, - 0x3f80_0000, - 0x3f80_0000, - 0x3f80_0000, - 0x3f80_0000, - 0x0000_0000, - 0x0000_0000, - 0x3f80_0000, - 0x0000_0000, - ]; - let level = TiledLevelMove::new(4, [4, 3], 1, [4, 4], 1, 0, 64, 0, 64); - let word = |bytes: &[u8], at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()); - let mut tiled = vec![0u8; 64]; - let mut tight = vec![0u8; 48]; - for (i, value) in values.iter().enumerate() { - let (x, y) = (i as u32 % 4, i as u32 / 4); - let at = tiled_at(&level, 0, x, y); - tiled[at..at + 4].copy_from_slice(&value.to_le_bytes()); - let at = tight_at(&level, 0, x, y); - tight[at..at + 4].copy_from_slice(&value.to_le_bytes()); - } - for (levels, want) in [([level.clamping_depth()], clamped), ([level], values)] { - let (t, p) = moved(&levels, true, &[0; 48], &tiled); - assert_eq!(p, tiled, "the tiled bytes are only read"); - for (i, want) in want.iter().enumerate() { - let at = tight_at(&level, 0, i as u32 % 4, i as u32 / 4); - assert_eq!( - word(&t, at), - *want, - "{:#x}, clamped {}", - values[i], - levels[0].clamps_depth - ); - } - let (t, p) = moved(&levels, false, &tight, &[0; 64]); - assert_eq!(t, tight, "the tight bytes are only read"); - for (i, value) in values.iter().enumerate() { - let at = tiled_at(&level, 0, i as u32 % 4, i as u32 / 4); - assert_eq!( - word(&p, at), - *value, - "back, clamped {}", - levels[0].clamps_depth - ); - } - } -} diff --git a/crates/metal2vulkan/src/bind/visibility_combine/tests.rs b/crates/metal2vulkan/src/bind/visibility_combine/tests.rs index b4bbc3ac2..039ac4a37 100644 --- a/crates/metal2vulkan/src/bind/visibility_combine/tests.rs +++ b/crates/metal2vulkan/src/bind/visibility_combine/tests.rs @@ -209,8 +209,14 @@ fn the_plan_binds_aligned_windows() { // A sum into the low half states 2; an OR stays an OR. let low = VisibilityCombine::plan( &[ - at(8, 0, 1, true).in_low_half(), - at(16, 1, 1, false).in_low_half(), + ContinuedResult { + low_half: true, + ..at(8, 0, 1, true) + }, + ContinuedResult { + low_half: true, + ..at(16, 1, 1, false) + }, ], 8, 1 << 16, diff --git a/crates/metal2vulkan/src/device/tests/from_queries.rs b/crates/metal2vulkan/src/device/tests/from_queries.rs index e74962302..60256bf60 100644 --- a/crates/metal2vulkan/src/device/tests/from_queries.rs +++ b/crates/metal2vulkan/src/device/tests/from_queries.rs @@ -70,7 +70,7 @@ fn from_queries_derives_one_profile_whatever_the_identity() { ], "{stem}" ); - assert!(queried.reads_ycbcr_planes_in_place(), "{stem}"); + assert!(queried.fields().ycbcr_in_place, "{stem}"); } } diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index d7ddfc569..587c70d78 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -111,18 +111,6 @@ pub enum Retry { Later, } -/// What the outcome is permanent for, i.e. which cache key may memoize it. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Permanence { - /// Permanent for the input (bytes, entry, constants, descriptor) on every device. - Input, - /// Permanent for the input on this device profile. - InputAndDevice, - /// Not permanent; never memoize. - Never, -} - impl Error { /// A refusal ([`Error::Unsupported`]) tied to render pipeline attachment `attachment` /// ([`Unsupported::at_attachment`]); any other error as it is. @@ -150,7 +138,6 @@ impl Error { | Error::Internal(_) => Retry::Never, } } - } impl fmt::Display for Error { @@ -452,7 +439,6 @@ impl Unsupported { self.symbol = Some(symbol); self } - } impl fmt::Display for Unsupported { diff --git a/crates/metal2vulkan/src/error/tests.rs b/crates/metal2vulkan/src/error/tests.rs index 29843e88d..5f167179e 100644 --- a/crates/metal2vulkan/src/error/tests.rs +++ b/crates/metal2vulkan/src/error/tests.rs @@ -53,17 +53,15 @@ fn one_of_each() -> Vec { ] } -/// Retry() and is_permanent_for() for every outcome class. +/// Retry() for every outcome class. #[test] -fn retry_and_permanence_table() { +fn retry_table() { for err in one_of_each() { // Exhaustive over `Error`, so a new variant must be classified here. - let (retry, permanence) = match &err { + let retry = match &err { Error::Unsupported(u) => match u.needs { - Needs::AnyOf(_) => (Retry::Never, Permanence::InputAndDevice), - Needs::NotImplemented | Needs::NotRepresentable => { - (Retry::Never, Permanence::Input) - } + Needs::AnyOf(_) => Retry::Never, + Needs::NotImplemented | Needs::NotRepresentable => Retry::Never, // A defect of the device's driver: another device translates the input. A stage // past the bound: another device's plan may write it lighter. A Metal GPU // family the device does not claim: another device, one that claims it, may. A @@ -75,32 +73,31 @@ fn retry_and_permanence_table() { | Needs::StageBound | Needs::DeviceCapability(_) | Needs::MetalGpuFamily(_) - | Needs::MetalRefuses(_) => (Retry::Never, Permanence::InputAndDevice), + | Needs::MetalRefuses(_) => Retry::Never, }, - Error::NeedsInput(_) => (Retry::Never, Permanence::Input), - Error::InvalidInput(_) => (Retry::Never, Permanence::Input), - Error::InvalidDescriptor(_) => (Retry::Never, Permanence::Input), - Error::LimitExceeded(_) => (Retry::Never, Permanence::Input), - Error::Budget(BudgetExceeded::Time) => (Retry::Later, Permanence::Never), + Error::NeedsInput(_) => Retry::Never, + Error::InvalidInput(_) => Retry::Never, + Error::InvalidDescriptor(_) => Retry::Never, + Error::LimitExceeded(_) => Retry::Never, + Error::Budget(BudgetExceeded::Time) => Retry::Later, // `BudgetExceeded` and `InternalKind` are the front end's crate's, `#[non_exhaustive]` // there: each variant this pinned version has is listed, and a new one fails here until // it is. Error::Budget(other) => panic!("classify {other:?}"), - Error::Cancelled => (Retry::Later, Permanence::Never), + Error::Cancelled => Retry::Later, // Every `InternalKind`: the host allocator failing a reservation the ledger admitted is // transient; every other kind is an invariant of the emitted, profile-dependent module. Error::Internal(internal) => match internal.kind { - InternalKind::AllocationFailed => (Retry::Later, Permanence::Never), + InternalKind::AllocationFailed => Retry::Later, InternalKind::Build | InternalKind::Verify | InternalKind::RequirementsExceedProfile | InternalKind::Panic - | InternalKind::Invariant => (Retry::Never, Permanence::InputAndDevice), + | InternalKind::Invariant => Retry::Never, other => panic!("classify {other:?}"), }, }; assert_eq!(err.retry(), retry, "{err:?}"); - assert_eq!(err.is_permanent_for(), permanence, "{err:?}"); assert!(!err.to_string().is_empty()); } } @@ -111,11 +108,6 @@ fn only_transient_outcomes_are_retryable() { let transient = matches!(err, Error::Cancelled | Error::Budget(_)) || matches!(&err, Error::Internal(i) if i.kind == InternalKind::AllocationFailed); assert_eq!(err.retry() == Retry::Later, transient, "{err:?}"); - assert_eq!( - err.is_permanent_for() == Permanence::Never, - transient, - "{err:?}" - ); } } @@ -148,7 +140,6 @@ fn input_error_mapping() { err, Error::InvalidInput(InputError::new(kind, Location::module())) ); - assert_eq!(err.is_permanent_for(), Permanence::Input); } let not_implemented = [ @@ -221,10 +212,6 @@ fn single_capability_needs_is_one_alternative() { VkExtension::ExtRasterizationOrderAttachmentAccess )]]) ); - assert_eq!( - Error::from(u).is_permanent_for(), - Permanence::InputAndDevice - ); } #[test] diff --git a/crates/metal2vulkan/src/indirect_commands.rs b/crates/metal2vulkan/src/indirect_commands.rs index 9cfe05277..d85d9b7d8 100644 --- a/crates/metal2vulkan/src/indirect_commands.rs +++ b/crates/metal2vulkan/src/indirect_commands.rs @@ -910,8 +910,7 @@ pub enum RecordField { ImageblockSize([u16; 2]), } -impl CommandRecord { -} +impl CommandRecord {} fn require_length(bytes: &[u8]) -> Result<(), RecordError> { if bytes.len() == COMMAND_BYTES { diff --git a/crates/metal2vulkan/src/indirect_commands/tests/records.rs b/crates/metal2vulkan/src/indirect_commands/tests/records.rs index 076d4b234..2614572bb 100644 --- a/crates/metal2vulkan/src/indirect_commands/tests/records.rs +++ b/crates/metal2vulkan/src/indirect_commands/tests/records.rs @@ -81,8 +81,7 @@ fn a_retained_pipeline_runs_and_reads_back_cleared() { } /// A pipeline a kernel wrote (`CommandRecord::kernel_pipeline`) is flagged in the state word -/// (`layout::KERNEL_PIPELINE`), set or retained, and decodes as written: a CPU pipeline setter's -/// write of the field clears the flag, a field of another setter keeps it. Flagged without a +/// (`layout::KERNEL_PIPELINE`), set or retained, and decodes as written. Flagged without a /// pipeline, it neither encodes nor decodes. #[test] fn a_kernel_s_pipeline_is_told_from_the_cpu_s() { @@ -111,14 +110,6 @@ fn a_kernel_s_pipeline_is_told_from_the_cpu_s() { assert_eq!(&CommandRecord::decode(&bytes).unwrap(), record); assert!(RecordView::new(&bytes).unwrap().kernel_pipeline()); } - // Another field's setter keeps the flag; the CPU's pipeline setter clears it. - written.encode_into(&mut bytes).unwrap(); - CommandRecord::write_field(&mut bytes, RecordField::Barrier(true)).unwrap(); - assert!(CommandRecord::decode(&bytes).unwrap().kernel_pipeline); - let at = CommandRecord::write_field(&mut bytes, RecordField::Pipeline(token.unwrap())).unwrap(); - assert!(at.contains(&state), "{at:?}"); - assert_eq!(&bytes[state..state + 4], &[0; 4]); - assert!(!CommandRecord::decode(&bytes).unwrap().kernel_pipeline); // Flagged beside no pipeline. let unnamed = CommandRecord { kernel_pipeline: true, @@ -831,177 +822,4 @@ impl Draws { record.imageblock_size = [self.word() as u16, self.word() as u16]; record } - - fn field(&mut self) -> RecordField { - match self.below(7) { - 0 => RecordField::Action(self.action()), - 1 => RecordField::Barrier(self.below(2) == 0), - 2 => RecordField::Pipeline(NonZeroU64::new(self.next() | 1).unwrap()), - 3 => RecordField::Buffer { - stage: self.stage(), - slot: self.below(BINDING_COUNT as u64 + 2) as usize, - binding: self.binding(), - }, - 4 => RecordField::ThreadgroupMemoryLength { - index: self.below(THREADGROUP_COUNT as u64 + 2) as usize, - length: self.word(), - }, - 5 => RecordField::StageInRegion(match self.below(2) { - 0 => [0; 6], - _ => self.words(), - }), - _ => RecordField::ImageblockSize([self.word() as u16, self.word() as u16]), - } - } -} - -/// `record` with `field` set, as a setter of the field sets it; `None` past the record's slots. -fn with_field(mut record: CommandRecord, field: RecordField) -> Option { - match field { - RecordField::Action(action) => record.action = action, - RecordField::Barrier(barrier) => record.barrier = barrier, - RecordField::Pipeline(pipeline) => { - record.bindings.pipeline = Some(pipeline); - record.retained_pipeline = None; - record.kernel_pipeline = false; - } - RecordField::Buffer { - stage, - slot, - binding, - } => *record.bindings.buffers_mut(stage).get_mut(slot)? = binding, - RecordField::ThreadgroupMemoryLength { index, length } => { - *record.threadgroup_memory_lengths.get_mut(index)? = length - } - RecordField::StageInRegion(region) => record.stage_in_region = region, - RecordField::ImageblockSize(size) => record.imageblock_size = size, - } - Some(record) -} - -/// A field written alone (`CommandRecord::write_field`) is the record decoded, the field set and -/// encoded again: over records `encode_into` wrote, byte for byte, and over bytes of any words -/// that decode, as what they decode to; where `encode_into` refuses the record with the field -/// set, or the field's index is past the record's, it refuses too and leaves the bytes as they -/// were. It writes nothing outside the bytes it answers. `RecordView` reads each field as -/// `decode` does, and its `record_into` writes the record over the last round's, every field. -#[test] -fn a_field_written_alone_is_the_record_encoded_again() { - let mut draws = Draws(0x9e37_79b9_7f4a_7c15); - let (mut written, mut refused) = (0, 0); - let mut into = CommandRecord::default(); - for round in 0..20_000 { - let mut bytes = vec![0u8; COMMAND_BYTES]; - if round % 2 == 0 { - draws.record().encode_into(&mut bytes).unwrap(); - } else { - // Words of any value, of a known action and barrier, with no state word. - for chunk in bytes.chunks_mut(8) { - chunk.copy_from_slice(&draws.next().to_le_bytes()[..chunk.len()]); - } - bytes[0..4].copy_from_slice(&(draws.below(9) as u32).to_le_bytes()); - bytes[4..8].copy_from_slice(&(draws.below(2) as u32).to_le_bytes()); - let state = layout::STATE as usize; - bytes[state..state + 4].fill(0); - } - let record = CommandRecord::decode(&bytes).unwrap(); - let view = RecordView::new(&bytes).unwrap(); - assert_eq!(view.record(), record, "round {round}: the view's record"); - view.record_into(&mut into); - assert_eq!( - into, record, - "round {round}: the view's record over the last" - ); - assert_eq!(view.writes(), record.writes(), "round {round}"); - for stage in BufferStage::of(false) - .into_iter() - .chain([BufferStage::Mesh]) - { - for slot in 0..BINDING_COUNT { - assert_eq!( - view.buffer(stage, slot), - record.bindings.buffers(stage)[slot], - "round {round}: {stage:?} slot {slot}" - ); - } - assert_eq!(view.buffer(stage, BINDING_COUNT), None); - } - for (index, &length) in record - .threadgroup_memory_lengths - .iter() - .enumerate() - .take(THREADGROUP_COUNT) - { - assert_eq!(view.threadgroup_memory_length(index), Some(length)); - } - assert_eq!(view.threadgroup_memory_length(THREADGROUP_COUNT), None); - let field = draws.field(); - let mut expected = vec![0u8; COMMAND_BYTES]; - let encoded = - with_field(record.clone(), field).map(|changed| changed.encode_into(&mut expected)); - let before = bytes.clone(); - let result = CommandRecord::write_field(&mut bytes, field); - match encoded { - Some(Ok(())) => { - let span = result - .unwrap_or_else(|error| panic!("round {round}: {field:?} refused: {error}")); - assert_eq!( - CommandRecord::decode(&bytes).unwrap(), - CommandRecord::decode(&expected).unwrap(), - "round {round}: {field:?} of {record:?}" - ); - if round % 2 == 0 { - assert_eq!(bytes, expected, "round {round}: {field:?}, byte for byte"); - } - for (at, (now, was)) in bytes.iter().zip(&before).enumerate() { - assert!( - now == was || span.contains(&at), - "round {round}: {field:?} wrote byte {at} outside {span:?}" - ); - } - written += 1; - } - Some(Err(error)) => { - assert_eq!(result, Err(error), "round {round}: {field:?}"); - assert_eq!(bytes, before, "round {round}: a refusal changes nothing"); - refused += 1; - } - None => { - assert!( - matches!(result, Err(RecordError::Index { .. })), - "round {round}: {field:?}: {result:?}" - ); - assert_eq!(bytes, before); - refused += 1; - } - } - } - assert!( - written > 15_000 && refused > 500, - "{written} written, {refused} refused" - ); -} - -/// A record that does not decode is refused as `decode` refuses it, by the view and by a field's -/// write, which changes nothing. -#[test] -fn a_field_of_a_record_that_does_not_decode_is_refused() { - let mut bytes = vec![0u8; COMMAND_BYTES]; - bytes[0..4].copy_from_slice(&9u32.to_le_bytes()); - assert_eq!( - RecordView::new(&bytes).map(|_| ()), - Err(RecordError::Action { value: 9 }) - ); - let before = bytes.clone(); - assert_eq!( - CommandRecord::write_field(&mut bytes, RecordField::Barrier(true)), - Err(RecordError::Action { value: 9 }) - ); - assert_eq!(bytes, before); - assert_eq!( - RecordView::new(&bytes[1..]).map(|_| ()), - Err(RecordError::Length { - actual: COMMAND_BYTES - 1 - }) - ); } diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index ea8cb5ce8..f864428dc 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -728,39 +728,6 @@ impl ExtendedRange { } } -/// How Metal converts a render pass's clear color to a bfloat attachment's codes -/// ([`ExtendedRange::clear_texel`]). Its two routes depend on the pass and the attachment, not on -/// the release: an Apple M4 under macOS 27.0.1 (16 colors and 39 NaN colors, 34 shapes, each bfloat -/// format) and the consumer's Apple M3 Max under macOS 26.7 take each as the shape says. The -/// runtime chooses by its clear's pass and attachment. A `BGR10_XR` or `BGRA10_XR` attachment and -/// their `_sRGB` twins take the same two routes by the same shapes (the M4 under 27.0.1; the -/// consumer's M3 Max under 26.7 byte for byte alike); a two-plane form's are one (each of its 2,574 -/// colors' planes alike). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum ClearRoute { - /// Each channel through `float` and then `half`, each rounded to nearest even (past the - /// largest `half`, the infinity), then the bfloat code nearest that `half`, ties to even; a - /// NaN `0x7fc0`, its sign and payload dropped. Metal's clear of a texture it does not keep - /// losslessly compressed (a level under 16 texels a side, `ShaderWrite` or `PixelFormatView` - /// usage, `allowGPUOptimizedContents` off), and of any texture in a pass that records a draw - /// call, even one that draws nothing. - ThroughHalf, - /// Each channel through `float`, rounded to nearest even, then the bfloat code nearest that, - /// ties to even, `float` subnormals kept: `-3e38` is `0xff62`, `1e-40` is `0x0001`, `70000` is - /// `0x4789`, `1 + 2^-8 + 2^-23` is `0x3f81`. A NaN is the `float` NaN of its sign and its top - /// 23 payload bits, quieted, cut to its top 16 bits (`0xfff0_0400_0000_0000` is `0xffc0`, - /// `0x7ff8_4000_0000_0000` is `0x7fc2`, `0x7fff_ffff_ffff_ffff` is `0x7fff`). Metal's clear of - /// a texture it keeps losslessly compressed, the attachment's level 16 texels or more a side, - /// by a pass that records no draw call (the consumer's M3 Max rows of a 16x16 `Private` - /// texture). A `BGR10_XR` or `BGRA10_XR` channel's code there is straight from the `float` too: - /// a linear channel's `(v + 384/510) · 510` in `float` steps, ties up, a color NaN 0 and an - /// alpha NaN 384, an `_sRGB` color channel's by Metal's own encode, and `BGR10_XR`'s bits 30 - /// and 31 zero. - Straight, -} - /// The bfloat code of `v` by [`ClearRoute::Straight`]: its `float` rounded to nearest even /// (Rust's conversion), then [`bfloat_nearest_even`]; a NaN the `float` NaN of its sign and top /// 23 payload bits, quieted, cut to its top 16 bits. @@ -2001,8 +1968,8 @@ pub const BICUBIC_TEXELS_UNBOUND: u32 = crate::metal::bicubic::BicubicTexels::NE /// The class of pixel format `pf` (`metal::texel_format::TexelFormat`'s word, as its `half` /// conversion takes it): the value a specialized note's test of /// `SpecKey::BoundTexelFormat` reads for a texture of `pf` bound at its slot -/// (`StageModule::bound_format_clauses`), which a runtime takes from each draw's or dispatch's -/// bound textures. +/// (`StageModule::precision_notes_bound`'s `bound`), which a runtime takes from each draw's or +/// dispatch's bound textures. pub fn bound_texel_format(pf: PixelFormat) -> u32 { crate::metal::texel_format::texel_format(pf).0 } diff --git a/crates/metal2vulkan/src/metal/format/tests.rs b/crates/metal2vulkan/src/metal/format/tests.rs index 0a08038d8..6487ba1c3 100644 --- a/crates/metal2vulkan/src/metal/format/tests.rs +++ b/crates/metal2vulkan/src/metal/format/tests.rs @@ -791,94 +791,6 @@ fn a_storage_access_without_a_format_goes_by_the_format_s_own_bits_with_the_exte } } -/// An `A8Unorm` view reads an `R8Unorm` image through `(Zero, Zero, Zero, Red)` composed under the -/// view's own swizzle, where the device has `A8_UNORM` and where it does not (the probe a8view on -/// an Apple M3 Max under macOS 27.0.1: Metal's `A8Unorm` view of an `R8Unorm` texture made without -/// `PixelFormatView` samples, reads, gathers and borders as a plain `A8Unorm` texture and as an -/// `R8Unorm` view of that swizzle do, shared and private, through four swizzles). A pair whose -/// opaque-black border texel moves with the mapping (`BGRA8Unorm` over `RGBA8Unorm`: the format -/// has alpha of its own) has none, nor a format over itself, nor a format of no such candidate, -/// nor a device whose portability subset withholds `imageViewFormatSwizzle`. -#[test] -fn a_view_in_other_channels_of_the_same_bits_reads_through_a_swizzle() { - use crate::metal::TextureSwizzle as T; - let s = SAMPLED; - let table = [ - (vk::Format::R8_UNORM, s), - (vk::Format::A8_UNORM, s), - (vk::Format::R8G8B8A8_UNORM, s), - (vk::Format::B8G8R8A8_UNORM, s), - ]; - let mut desc = floor_with(&table); - desc.extensions.extend([ - VkExtension::KhrMaintenance5, - VkExtension::KhrDynamicRendering, - ]); - let m5 = device(desc); - let floor = device(floor_with(&table)); - let alpha = TextureSwizzleChannels::new(T::Zero, T::Zero, T::Zero, T::Red); - for d in [&m5, &floor] { - let over = |pf, swizzle, own| swizzle_over(pf, swizzle, own, d.profile()); - let default = TextureSwizzleChannels::DEFAULT; - assert_eq!( - over(PixelFormat::A8Unorm, default, PixelFormat::R8Unorm), - Some(alpha) - ); - let swizzled = TextureSwizzleChannels::new(T::Alpha, T::Red, T::One, T::Zero); - assert_eq!( - over(PixelFormat::A8Unorm, swizzled, PixelFormat::R8Unorm), - Some(TextureSwizzleChannels::new( - T::Red, - T::Zero, - T::One, - T::Zero - )) - ); - // The first lane whose source is alpha stores the image's red (probe a8write). - let second = TextureSwizzleChannels::new(T::Zero, T::Alpha, T::Alpha, T::Red); - assert_eq!( - over(PixelFormat::A8Unorm, second, PixelFormat::R8Unorm), - Some(TextureSwizzleChannels::new( - T::Zero, - T::Red, - T::Red, - T::Zero - )) - ); - // No lane's source is alpha: Metal stores the alpha lane, a swizzled R8 image its red. - let opaque = TextureSwizzleChannels::new(T::Red, T::Green, T::Blue, T::One); - assert_eq!( - over(PixelFormat::A8Unorm, opaque, PixelFormat::R8Unorm), - None - ); - assert_eq!( - over(PixelFormat::BGRA8Unorm, default, PixelFormat::RGBA8Unorm), - None - ); - assert_eq!( - over(PixelFormat::R8Unorm, default, PixelFormat::R8Unorm), - None - ); - assert_eq!( - over(PixelFormat::R8Uint, default, PixelFormat::R8Unorm), - None - ); - } - let mut desc = floor_with(&table); - desc.extensions.insert(VkExtension::KhrPortabilitySubset); - let withheld = device(desc); - let default = TextureSwizzleChannels::DEFAULT; - assert_eq!( - swizzle_over( - PixelFormat::A8Unorm, - default, - PixelFormat::R8Unorm, - withheld.profile() - ), - None - ); -} - /// A portability subset that withholds `imageViewFormatSwizzle` makes no view with a component /// mapping (`VUID-VkImageViewCreateInfo-imageViewFormatSwizzle-04465`): `A8Unorm`'s swizzled /// `R8_UNORM` candidate names the feature beside the direct format's needs, and is chosen once the @@ -1136,7 +1048,7 @@ fn formats_metal_names_are_named_and_refused_typed() { (650, "MTLPixelFormatRGB10A8Uint_2P"), ]; // All but `R10Unorm_X6`, `RG10Unorm_X12` and their `_sRGB` twins, held raw - // in their words' integer formats (`padded_words`). + // in their words' integer formats. // And the eleven RGBX formats, held in their RGBA twins (`x_channel`). // And the three bfloat formats and `RGB10A2Unorm_sRGB`, held raw (`ExtendedRange`). // And `BGRA4Unorm`, held in the 4-bit word of its bits (`A4R4G4B4_UNORM_PACK16`, or @@ -1155,7 +1067,14 @@ fn formats_metal_names_are_named_and_refused_typed() { let pf = PixelFormat::try_from(raw).unwrap_or_else(|e| panic!("{raw}: {e}")); assert_eq!(pf.name(), name); assert_eq!(PixelFormat::from_name(name), Some(pf)); - if padded_words(pf) || x_channel(pf) || bfloat(pf) || rgb10a2_srgb(pf) { + let padded = matches!( + pf, + PixelFormat::R10UnormX6 + | PixelFormat::RG10UnormX12 + | PixelFormat::R10UnormX6SRGB + | PixelFormat::RG10UnormX12SRGB + ); + if padded || x_channel(pf) || bfloat(pf) || rgb10a2_srgb(pf) { continue; } if pf == PixelFormat::BGRA4Unorm || copies_only(pf) { @@ -1183,28 +1102,12 @@ fn formats_metal_names_are_named_and_refused_typed() { /// `R10Unorm_X6` and `RG10Unorm_X12` are held raw in their words' integer formats for sampling, /// storage and rendering (the shader decodes, filters and encodes them, `ExtendedRange::R10X6` and `Rg10X12`), -/// they and their `_sRGB` twins are exactly the formats whose codes sit in the top bits of their -/// own 16-bit words (`padded_words`), and a clear stores Metal's words: the color -/// through `float` and `half`, each to nearest even, the code of the exact product with 1023 -/// rounded to nearest in the top 10 bits. +/// and they and their `_sRGB` twins are the formats whose codes sit in the top bits of their own +/// 16-bit words. #[test] fn padded_formats_are_held_raw() { use FormatUsage as U; use PixelFormat as P; - let held: Vec = PixelFormat::ALL - .iter() - .copied() - .filter(|&pf| padded_words(pf)) - .collect(); - assert_eq!( - held, - [ - P::R10UnormX6, - P::R10UnormX6SRGB, - P::RG10UnormX12, - P::RG10UnormX12SRGB - ] - ); for (pf, raw, form) in [ (P::R10UnormX6, vk::Format::R16_UINT, ExtendedRange::R10X6), ( @@ -1260,48 +1163,6 @@ fn padded_formats_are_held_raw() { assert!(held > 0, "{pf:?}"); assert_eq!(out_of_bounds_alpha_one(pf), Some(true)); } - let r = ExtendedRange::R10X6; - let rg = ExtendedRange::Rg10X12; - assert_eq!( - rg.clear_texel([0.5, 0.25, 0.0, 1.0], ClearRoute::ThroughHalf), - [32768, 16384, 0, 0] - ); - assert_eq!( - rg.clear_texel([0.3, 0.7, 0.0, 1.0], ClearRoute::ThroughHalf), - [19648, 45824, 0, 0] - ); - assert_eq!( - r.clear_texel([0.3, 0.7, 0.0, 1.0], ClearRoute::ThroughHalf), - [19648, 0, 0, 0] - ); - assert_eq!( - r.clear_texel([-1.0, 0.0, 0.0, 0.0], ClearRoute::ThroughHalf), - [0, 0, 0, 0] - ); - assert_eq!( - r.clear_texel([2.0, 0.0, 0.0, 0.0], ClearRoute::ThroughHalf), - [1023 << 6, 0, 0, 0] - ); - // The `_sRGB` twins' clear of (0.3, 0.7) is Metal's (a clear-only - // pass over a buffer stores 38208 and [4928, 7424] in every texel), through their tables. - let rs = ExtendedRange::R10X6Srgb; - let rgs = ExtendedRange::Rg10X12Srgb; - assert_eq!( - rs.clear_texel([0.3, 0.7, 0.0, 1.0], ClearRoute::ThroughHalf), - [597 << 6, 0, 0, 0] - ); - assert_eq!( - rgs.clear_texel([0.3, 0.7, 0.0, 1.0], ClearRoute::ThroughHalf), - [77 << 6, 116 << 6, 0, 0] - ); - assert_eq!( - rs.clear_texel([2.0, 0.0, 0.0, 0.0], ClearRoute::ThroughHalf), - [1023 << 6, 0, 0, 0] - ); - assert_eq!( - rgs.clear_texel([1.0, -1.0, 0.0, 0.0], ClearRoute::ThroughHalf), - [137 << 6, 0, 0, 0] - ); } /// Every swizzled sampling view reads Metal's opaque-black border texel where the device applies @@ -1634,8 +1495,7 @@ fn storage_choices_follow_d25() { /// Apple's bfloat formats are held raw in the unsigned integer format of their 16-bit words /// ([`FormatEmulation::Bfloat`]): read as floats, sampled and stored through it, never filtered /// by a device nor blended; a color attachment of the raw format; a multisample texture is none -/// (the runtime's descriptor rules). A fill's texel is each channel through `float` and `half`, -/// each to nearest even, then the bfloat nearest that, ties to even, a NaN `0x7fc0`. +/// (the runtime's descriptor rules). #[test] fn bfloat_formats_are_held_raw() { use vk::Format as F; @@ -1711,89 +1571,6 @@ fn bfloat_formats_are_held_raw() { assert!(blended.is_err(), "{pf:?} on {stem}: {blended:?}"); } } - // Clears under `ThroughHalf`: the color through `float` and `half` to nearest even, then the - // bfloat code nearest, ties to even (a tie of the `half` rounded down and one rounded up), - // the overflow of the `half` its infinity, a NaN `0x7fc0`. - let texel = |form: ExtendedRange, c: [f64; 4]| form.clear_texel(c, ClearRoute::ThroughHalf); - let one_tie_down = 1.0 + 1.0 / 256.0; - let one_tie_up = 1.0 + 3.0 / 256.0; - assert_eq!( - texel( - ExtendedRange::Rgba16Bfloat, - [one_tie_down, one_tie_up, -0.0, f64::NAN] - ), - [0x3f80, 0x3f82, 0x8000, 0x7fc0] - ); - assert_eq!( - texel( - ExtendedRange::Rgba16Bfloat, - [65520.0, -65520.0, 65504.0, 0.1] - ), - [0x7f80, 0xff80, 0x4780, 0x3dcd] - ); - assert_eq!( - texel(ExtendedRange::Rg16Bfloat, [0.25, 0.5, 0.75, 1.0]), - [0x3e80, 0x3f00, 0, 0] - ); - assert_eq!( - texel(ExtendedRange::R16Bfloat, [1.5, -0.5, 7.0, 0.0]), - [0x3fc0, 0, 0, 0] - ); - // Clears under `Nearest`: the color through `float` to nearest even, then the bfloat code - // nearest, ties to even, subnormals kept (the consumer's M3 Max: `-3e38`, `1e-40`, `70000` - // and `1 + 2^-8 + 2^-23`, where `ThroughHalf` gives `0xff80`, 0, `0x7f80` and `0x3f80`), a - // `half`'s value as under `ThroughHalf`, the infinity past the largest `float`, a NaN its - // `float`'s sign and top payload bits, quieted. - let nearest = |form: ExtendedRange, c: [f64; 4]| form.clear_texel(c, ClearRoute::Straight); - let consumers = [-3e38, 1e-40, 70000.0, 1.0 + 1.0 / 256.0 + 2f64.powi(-23)]; - assert_eq!( - nearest(ExtendedRange::Rgba16Bfloat, consumers), - [0xff62, 0x0001, 0x4789, 0x3f81] - ); - assert_eq!( - texel(ExtendedRange::Rgba16Bfloat, consumers), - [0xff80, 0x0000, 0x7f80, 0x3f80] - ); - assert_eq!( - nearest( - ExtendedRange::Rgba16Bfloat, - [-2.5, one_tie_down, one_tie_up, -0.0] - ), - [0xc020, 0x3f80, 0x3f82, 0x8000] - ); - assert_eq!( - nearest( - ExtendedRange::Rgba16Bfloat, - [3.402_823_466_385_288_6e38, 1e39, -1e39, f64::NAN] - ), - [0x7f80, 0x7f80, 0xff80, 0x7fc0] - ); - assert_eq!( - nearest( - ExtendedRange::Rg16Bfloat, - [1.401_298_464_324_817e-45, -f64::NAN, 1.0, 1.0] - ), - [0x0000, 0xffc0, 0, 0] - ); - assert_eq!( - nearest( - ExtendedRange::Rgba16Bfloat, - [ - f64::from_bits(0x7ff8_4000_0000_0000), - f64::from_bits(0xfff0_0400_0000_0000), - f64::from_bits(0x7fff_ffff_ffff_ffff), - f64::from_bits(0x7ff4_0000_0000_0000), - ] - ), - [0x7fc2, 0xffc0, 0x7fff, 0x7fe0] - ); - // The bfloat rounding alone: ties to even, either sign, and the infinity past the largest. - assert_eq!(bfloat_nearest_even(f32::from_bits(0x3f80_8000)), 0x3f80); - assert_eq!(bfloat_nearest_even(f32::from_bits(0x3f81_8000)), 0x3f82); - assert_eq!(bfloat_nearest_even(f32::from_bits(0xbf81_8001)), 0xbf82); - assert_eq!(bfloat_nearest_even(f32::from_bits(0x7f7f_8000)), 0x7f80); - assert_eq!(bfloat_nearest_even(f32::NEG_INFINITY), 0xff80); - assert_eq!(bfloat_nearest_even(-f32::NAN), 0x7fc0); } #[test] @@ -2141,20 +1918,6 @@ fn queries_cover_candidates_and_neutrals() { } // The view of a `ulong` slot a `ulong` atomic updates, which no Metal format maps to. assert!(set.contains(&vk::Format::R64_UINT)); - for (stem, dev) in committed_devices() { - // Neutral images of a declared storage format take it from the profile's own table; - // the others use fixed formats the consumer must be able to ask about. - for neutral in dev.neutral_kinds() { - if let crate::bind::NeutralResource::Image { - storage_format: None, - .. - } = neutral - { - let f = neutral.format().unwrap(); - assert!(set.contains(&f), "{stem}: neutral {f:?} is not queried"); - } - } - } } #[test] @@ -2373,61 +2136,6 @@ fn color_records_are_metals() { } } -/// `explicit_imageblock_sample_length` answers what Metal answered for a render pipeline whose -/// fragment function declares an explicit imageblock, on an M3 Max and an M4: the data size, then -/// the color attachments' bytes rounded up to 8 and then to the layout's alignment. Each row is a -/// layout (its data size and alignment) and color formats. -#[test] -fn explicit_imageblock_sample_lengths_are_metals() { - use PixelFormat as P; - let r8 = Some(P::R8Unorm); - let rgba32f = Some(P::RGBA32Float); - let rgba8x4 = vec![Some(P::RGBA8Unorm); 4]; - for (data_size, alignment, formats, metal) in [ - // `char` - (1, 1, vec![], 1), - (1, 1, vec![r8], 9), - (1, 1, vec![rgba32f], 17), - (1, 1, vec![r8, rgba32f], 25), - (1, 1, rgba8x4.clone(), 17), - // `half` - (2, 2, vec![r8], 10), - (2, 2, vec![r8, rgba32f], 26), - // three `char`s - (3, 1, vec![r8], 11), - // three `half`s - (6, 2, vec![rgba32f], 22), - (6, 2, vec![r8, rgba32f], 30), - // `float2` - (8, 8, vec![r8], 16), - (8, 8, vec![r8, rgba32f], 32), - // `float`, `half` and `uint` - (12, 4, vec![r8, rgba32f], 36), - (12, 4, rgba8x4.clone(), 28), - // `float4` - (16, 16, vec![], 16), - (16, 16, vec![r8], 32), - (16, 16, vec![rgba32f], 32), - (16, 16, vec![r8, rgba32f], 48), - // `packed_float4`, and four `float`s - (16, 4, vec![r8], 24), - (16, 4, vec![rgba32f], 32), - (16, 4, vec![r8, rgba32f], 40), - // `float4` and `float` - (32, 16, vec![], 32), - (32, 16, vec![r8], 48), - (32, 16, vec![r8, rgba32f], 64), - (32, 16, rgba8x4, 48), - ] { - let colors = imageblock_sample_length(&formats).expect("measured formats pack"); - assert_eq!( - explicit_imageblock_sample_length(data_size, alignment, colors), - Some(metal), - "{data_size} bytes aligned to {alignment}, {formats:?}" - ); - } -} - /// [`ycbcr_format`] describes exactly the 69 two-plane YCbCr formats, each as its Metal name /// states (`MTLPixelFormat{YCBCR|RGB}{bits}_{420|422|444}_2P[_PACKED][_{sRGB|PQ|HLG|XR}]`), and /// this crate holds a texture of the ones of unpacked 8- and 10-bit codes read converted, through @@ -2642,93 +2350,6 @@ fn a_pass_renders_only_the_ycbcr_formats_whose_store_is_matched() { } } -/// A clear's halves are what its stored codes read back, rounded to `half`, only where each -/// channel's `half` is the `half` of its code's value: `0.1`'s (code 435 reads 51/510, whose -/// `half` is `half` 0.1's), not `0.25`'s (code 512 reads 0.25098) or `0.0012345`'s (code 385); -/// the two-plane formats' alpha byte reads `0.5` as `128 / 255`, a `BGRA10_XR` alpha code exactly; -/// `BGR10_XR` has no alpha. A padded form's channels read `c / 1023`: `0.33371`'s `half` is not -/// code 341's (the M3 Max's tile held the `half`: a premultiplied blend of `(0, 0, 0, 0.5)` over -/// that clear stored code 171 where code 341's value gives 170), nor `0.5`'s code 512's, while 0 -/// and 1 are (but `RG10Unorm_X12_sRGB`'s 1, whose code reads back linear); only the channels a -/// padded form has count. The bfloat forms' tile memory is unmeasured. -#[test] -fn clears_read_back_where_their_halves_are_their_codes_values() { - let planes = ExtendedRange::Planes { srgb: false }; - let bgra = ExtendedRange::Bgra10 { srgb: false }; - let bgr = ExtendedRange::Bgr10 { srgb: false }; - for form in [planes, bgra, bgr, ExtendedRange::Bgra10 { srgb: true }] { - assert_eq!(form.clear_read_back([0.0; 4]), Some(true), "{form:?}"); - assert_eq!(form.clear_read_back([1.0; 4]), Some(true), "{form:?}"); - } - assert_eq!(bgra.clear_read_back([0.1, 0.3, 1.0 / 3.0, 0.7]), Some(true)); - assert_eq!( - planes.clear_read_back([0.1, 0.3, 1.0 / 3.0, 0.7]), - Some(false) - ); - assert_eq!(bgra.clear_read_back([0.25, 0.5, 0.0, 1.0]), Some(false)); - assert_eq!( - bgra.clear_read_back([0.0012345, 0.0, 0.0, 1.0]), - Some(false) - ); - assert_eq!(bgra.clear_read_back([0.0, 0.0, 0.0, 0.5]), Some(true)); - assert_eq!(planes.clear_read_back([0.0, 0.0, 0.0, 0.5]), Some(false)); - assert_eq!(bgr.clear_read_back([0.0, 0.0, 0.0, 0.5]), Some(true)); - for form in [ - ExtendedRange::R10X6, - ExtendedRange::Rg10X12, - ExtendedRange::R10X6Srgb, - ExtendedRange::Rg10X12Srgb, - ExtendedRange::Rgb10A2Srgb, - ] { - assert_eq!(form.clear_read_back([0.0; 4]), Some(true), "{form:?}"); - // `RG10Unorm_X12_sRGB` writes 1 as code 137 (Metal's table), which reads `137 / 1023`. - let one = form != ExtendedRange::Rg10X12Srgb; - assert_eq!(form.clear_read_back([1.0; 4]), Some(one), "{form:?}"); - } - let r10 = ExtendedRange::R10X6; - assert_eq!( - r10.clear_read_back([0.33371, 0.70011, 0.10049, 0.5]), - Some(false) - ); - // Red alone counts: green's 0.5 is no channel of `R10Unorm_X6`. - assert_eq!(r10.clear_read_back([1.0, 0.5, 0.5, 0.5]), Some(true)); - let rg = ExtendedRange::Rg10X12; - assert_eq!(rg.clear_read_back([1.0, 0.5, 0.0, 1.0]), Some(false)); - assert_eq!(ExtendedRange::Rgba16Bfloat.clear_read_back([0.0; 4]), None); -} - -/// A clear's tile holds each channel through `float` and then `half`, nearest even, unclamped: -/// `0.1` as `half` 0.1 (`0x2e66`), `1/3` as `0x3555`, `5.0` past the codes' range as 5, a value -/// halfway between two `float`s rounding twice; `BGR10_XR`'s alpha reads 1 whatever the clear's; -/// the padded and bfloat forms' tile memory is unmeasured. -#[test] -fn a_clears_tile_holds_its_colors_halves() { - let h = crate::float16::f16_bits_to_f32; - let bgra = ExtendedRange::Bgra10 { srgb: true }; - assert_eq!( - bgra.clear_tile_value([0.1, 1.0 / 3.0, 5.0, -0.75]), - Some([h(0x2e66), h(0x3555), 5.0, -0.75]) - ); - let planes = ExtendedRange::Planes { srgb: false }; - assert_eq!( - planes.clear_tile_value([0.0, -0.0, 1.0, 0.5]), - Some([0.0, -0.0, 1.0, 0.5]) - ); - let bgr = ExtendedRange::Bgr10 { srgb: false }; - assert_eq!( - bgr.clear_tile_value([0.25, 0.5, 2.0, 0.0]), - Some([0.25, 0.5, 2.0, 1.0]) - ); - // 1 + 2^-11 + 2^-40 is 1 + 2^-11 as a `float`, a tie, which `half` rounds to 1. - let twice = 1.0 + 2f64.powi(-11) + 2f64.powi(-40); - assert_eq!( - bgr.clear_tile_value([twice, 0.0, 0.0, 1.0]).map(|v| v[0]), - Some(1.0) - ); - assert_eq!(ExtendedRange::R10X6.clear_tile_value([0.0; 4]), None); - assert_eq!(ExtendedRange::Rgba16Bfloat.clear_tile_value([0.0; 4]), None); -} - /// The probe's clear colors: each 10-bit code's value and each tie between two /// codes, 512 values of its generator, and the specials; color `i` is values `i` to `i + 3`. fn straight_clear_colors() -> Vec<[f64; 4]> { @@ -2767,96 +2388,6 @@ fn straight_clear_colors() -> Vec<[f64; 4]> { .collect() } -/// Metal's two clear routes store the texels the model gives (an Apple M4 under -/// macOS 27.0.1, plain and under Metal's validation layer alike: 2,574 colors into a 16 x 16 -/// private target of plain usage in a pass with no draw call, `ClearRoute::Straight`, and into a -/// 4 x 4 one, `ClearRoute::ThroughHalf`), as an FNV-1a digest of each format's texels as Metal -/// stores them, a two-plane format's plane-0 word then its alpha byte. The two-plane formats -/// store the same on either route; `0.25` is code 511 on the straight route, 512 through `half`. -#[test] -fn clears_store_metal_s_texels_on_each_route() { - let fnv = |bytes: &[u8]| { - bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &b| { - (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) - }) - }; - let colors = straight_clear_colors(); - assert_eq!(colors.len(), 2574); - let bytes = |form: ExtendedRange, route: ClearRoute| -> Vec { - colors - .iter() - .flat_map(|&c| { - let t = form.clear_texel(c, route); - match form { - ExtendedRange::Bgr10 { .. } => t[0].to_le_bytes().to_vec(), - ExtendedRange::Planes { .. } => { - let mut word = t[0].to_le_bytes().to_vec(); - word.push(t[1] as u8); - word - } - _ => t.iter().flat_map(|&f| (f as u16).to_le_bytes()).collect(), - } - }) - .collect() - }; - // (form, Metal's straight digest, its digest through `half`) - let metal = [ - ( - ExtendedRange::Bgr10 { srgb: false }, - 0xbb6a_4158_d28b_a838u64, - 0x9619_2923_5cc4_c348u64, - ), - ( - ExtendedRange::Bgr10 { srgb: true }, - 0xa62c_eca5_4ebf_3d07, - 0x1b43_711d_789f_660d, - ), - ( - ExtendedRange::Bgra10 { srgb: false }, - 0x304d_3161_5f46_4eea, - 0xd417_f619_6f15_36c5, - ), - ( - ExtendedRange::Bgra10 { srgb: true }, - 0x5456_e21b_8297_972b, - 0xfa8f_e6a4_b69b_bb94, - ), - ( - ExtendedRange::Planes { srgb: false }, - 0x3051_a4b4_879c_69e9, - 0x3051_a4b4_879c_69e9, - ), - ( - ExtendedRange::Planes { srgb: true }, - 0xf844_3bb4_8958_6eba, - 0xf844_3bb4_8958_6eba, - ), - ]; - for (form, straight, through_half) in metal { - let got = fnv(&bytes(form, ClearRoute::Straight)); - assert_eq!(got, straight, "{form:?} straight: {got:#018x}"); - let got = fnv(&bytes(form, ClearRoute::ThroughHalf)); - assert_eq!(got, through_half, "{form:?} through half: {got:#018x}"); - } - let bgr = ExtendedRange::Bgr10 { srgb: false }; - let codes = |t: [u32; 4]| { - [ - t[0] >> 20 & 1023, - t[0] >> 10 & 1023, - t[0] & 1023, - t[0] >> 30, - ] - }; - assert_eq!( - codes(bgr.clear_texel([0.25, -0.25, f64::NAN, 0.0], ClearRoute::Straight)), - [511, 257, 0, 0] - ); - assert_eq!( - codes(bgr.clear_texel([0.25, -0.25, f64::NAN, 0.0], ClearRoute::ThroughHalf)), - [512, 256, 384, 3] - ); -} - /// The table [`repr`] reads holds [`make_repr`]'s entry of every format, at its raw value. #[test] fn the_format_table_holds_each_format_s_entry() { diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 0fc2fd070..2fa27abb4 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -147,7 +147,11 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() { ] { let mut sorted = m.precision_notes.clone(); sorted.retain(|n| want.contains(n)); - assert_eq!(m.precision_notes_under(&key(&values)), sorted, "{values:?}"); + assert_eq!( + m.precision_notes_bound(&key(&values), &|_| None), + sorted, + "{values:?}" + ); } } diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 73669c66b..5edf18a89 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -274,24 +274,6 @@ impl StageModule { .collect() } - /// The clauses of `note`'s [`specialized_notes`](Self::specialized_notes) entry that hold - /// where a pipeline creates the stage under `specialization` and a draw or dispatch binds - /// the values `bound` gives, as [`precision_notes_bound`](Self::precision_notes_bound) reads - /// them. - pub fn note_clauses_bound( - &self, - note: PrecisionNote, - specialization: &SpecializationKey, - bound: &dyn Fn(SpecKey) -> Option, - ) -> Vec<&SpecClause> { - self.specialized_notes - .iter() - .filter(|s| s.note == note) - .flat_map(|s| &s.when) - .filter(|clause| self.clause_holds(clause, specialization, bound)) - .collect() - } - /// Whether every test of `clause` holds under `specialization`, a constant the key does not /// give reading its default, and a key no pipeline's key carries (one the stage reads as data, /// a bound sampler's word) reading the value `bound` gives. @@ -419,30 +401,6 @@ pub struct SpecClause { pub all: Vec, } -impl SpecClause { - /// Whether every test reads the class of the format bound at a texture slot - /// (`SpecKey::BoundTexelFormat`), which no pipeline's key carries: a clause a runtime reads - /// at a draw or dispatch, from the textures it binds - /// ([`StageModule::bound_format_clauses`]). - pub fn tests_bound_formats(&self) -> bool { - self.all - .iter() - .all(|t| matches!(t.key, SpecKey::BoundTexelFormat(_))) - } - - /// Whether every test of the bound formats holds where `bound` gives the class of the format - /// bound at each slot (`None` where it is not known, of which the test holds); a test of any - /// other key holds here. - pub(crate) fn holds_of_bound(&self, bound: &dyn Fn(SlotRef) -> Option) -> bool { - self.all.iter().all(|t| match t.key { - SpecKey::BoundTexelFormat(slot) => { - bound(slot).is_none_or(|v| (v & t.mask == t.bits) == t.equal) - } - _ => true, - }) - } -} - /// A test of one specialization constant's value `v`: it holds when `(v & mask == bits) == equal`. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] diff --git a/crates/metal2vulkan/src/pipeline/descriptor.rs b/crates/metal2vulkan/src/pipeline/descriptor.rs index f95fdfdb1..3d783bd52 100644 --- a/crates/metal2vulkan/src/pipeline/descriptor.rs +++ b/crates/metal2vulkan/src/pipeline/descriptor.rs @@ -91,7 +91,6 @@ impl FunctionDescriptor { self.libraries = libraries; self } - } /// The dynamic libraries a pipeline stage links (`MTLDynamicLibrary`): its preloaded libraries, and diff --git a/crates/metal2vulkan/src/pipeline/interface.rs b/crates/metal2vulkan/src/pipeline/interface.rs index 70901b219..bc34e1ac0 100644 --- a/crates/metal2vulkan/src/pipeline/interface.rs +++ b/crates/metal2vulkan/src/pipeline/interface.rs @@ -753,9 +753,7 @@ impl SampledLevels { } } -impl LevelReads { - -} +impl LevelReads {} /// An emulated mesh function's records: what each of its threadgroups writes to the draw's records /// buffer (`SyntheticBinding::MeshRecords`), all of it words. @@ -913,7 +911,6 @@ pub enum PatchDomain { } impl PipelineInterface { - /// The buffer slots of `stage` (bit `i` for index `i`, below 64) whose form `takes`. fn buffers_where(&self, stage: Stage, takes: impl Fn(BufferForm) -> bool) -> u64 { let mut slots = 0; diff --git a/crates/metal2vulkan/src/reflection/linked_tests.rs b/crates/metal2vulkan/src/reflection/linked_tests.rs index d3fc32097..db7d5ecbd 100644 --- a/crates/metal2vulkan/src/reflection/linked_tests.rs +++ b/crates/metal2vulkan/src/reflection/linked_tests.rs @@ -866,21 +866,9 @@ fn direct_argument_use_is_decided_where_the_reflection_refuses_a_type() { } other => panic!("{at}: {other:?}"), }; - for (kernel, uses) in [("buffer_kernel", false), ("texture_kernel", true)] { - let descriptor = - |library: &Library| ComputePipelineDescriptor::new(source(library, kernel)); - refused_type( - descriptor(&unmeasured).reflection(&budget).map(drop), - BUFFER, - kernel, - ); - for library in [&measured, &unmeasured] { - assert_eq!( - descriptor(library).uses_direct_arguments(&budget), - Ok(uses), - "{kernel}" - ); - } + for kernel in ["buffer_kernel", "texture_kernel"] { + let descriptor = ComputePipelineDescriptor::new(source(&unmeasured, kernel)); + refused_type(descriptor.reflection(&budget).map(drop), BUFFER, kernel); } for (fragment, uses) in [ ("plain_fragment", vec![]), diff --git a/crates/metal2vulkan/src/reflection/tests/encoder.rs b/crates/metal2vulkan/src/reflection/tests/encoder.rs index 57fd723b0..f76eaa6ff 100644 --- a/crates/metal2vulkan/src/reflection/tests/encoder.rs +++ b/crates/metal2vulkan/src/reflection/tests/encoder.rs @@ -1,9 +1,6 @@ -//! Encoders made from reflected buffer bindings (`newArgumentEncoderWithBufferBinding:`, -//! [`ArgumentBufferLayout::from_buffer_binding`]) against Metal's, beside the function's own -//! (`newArgumentEncoderWithBufferIndex:`): `metal-answers.txt`'s `encoder_` sections over the -//! `argument_buffers` and `buffers` fixtures and its `enc:` sections over the `encoders` and -//! `encoder_types` fixtures, recorded by `probe.swift` on an M3 Max and an M4 (where the two -//! differ, the M3 Max's). +//! A function's own encoders (`newArgumentEncoderWithBufferIndex:`) against Metal's: +//! `metal-answers.txt`'s `encoder_` sections over the `argument_buffers` fixture, recorded by +//! `probe.swift` on an M3 Max and an M4 (where the two differ, the M3 Max's). use std::collections::{BTreeMap, BTreeSet}; @@ -41,29 +38,8 @@ fn encoder_answers() -> BTreeMap> { out } -/// The fixture's library binding and pipeline binding named `name`; `None` without `llvm-as`. -fn bindings(name: &str) -> Option<(Binding, Binding)> { - let lib = Library::from_air(&fixture("argument_buffers")?).expect("library"); - let f = lib.function(FUNCTION).expect("function"); - let pick = |bindings: &[Binding]| { - bindings - .iter() - .find(|b| b.name() == name) - .unwrap_or_else(|| panic!("no binding {name}")) - .clone() - }; - let budget = Budget::standard(); - let library = f.reflection(&budget).expect("reflection").expect("present"); - let pipeline = - ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f.clone()))) - .reflection(&budget) - .expect("pipeline reflection"); - Some((pick(library.bindings()), pick(pipeline.bindings()))) -} - -/// The function's encoder of its buffer `index` and the encoders of its library's and its -/// pipeline's binding `name`, labelled as the probe labels them. -fn encoders(index: u32, name: &str) -> Option> { +/// The function's encoder of its buffer `index`; `None` without `llvm-as`. +fn function_encoder(index: u32) -> Option { let lib = Library::from_air(&fixture("argument_buffers")?).expect("library"); let function = lib .function(FUNCTION) @@ -74,15 +50,23 @@ fn encoders(index: u32, name: &str) -> Option Vec { + let mut out = Vec::new(); + let mut open = false; + for line in lines { + if !line.starts_with(' ') { + open = line.starts_with("function "); + } + if open { + out.push(line.clone()); + } + } + out } /// The probe's lines for an encoder: its length and alignment, the offset `constantDataAtIndex:` @@ -114,25 +98,21 @@ fn encoder_lines( out } -/// An encoder from a library's binding equals the function's own; one from a pipeline's binding -/// is shorter (its arrays of resources and of resource-only structs reflect stride 0), with the same constants and -/// nested encoders: lengths, alignments, constant offsets and nested encoders as Metal's. +/// The function's encoders: lengths, alignments, constant offsets and nested encoders as Metal's. #[test] -fn binding_encoders_match_metal() { +fn the_function_s_encoders_match_metal() { let answers = encoder_answers(); let mut mismatches = Vec::new(); for (case, index, name, constants, nested) in [ ("args", 0, "args", &[7, 8, 20, 21][..], &[2, 12, 15][..]), ("imp", 1, "imp", &[3][..], &[0][..]), ] { - let Some(encoders) = encoders(index, name) else { + let Some(l) = function_encoder(index) else { return; }; - let got: Vec = encoders - .iter() - .flat_map(|(label, l)| encoder_lines(label, l, constants, nested)) - .collect(); - mismatches.extend(diff(&format!("encoder_{case}"), &got, &answers[case])); + let got = encoder_lines("function", &l, constants, nested); + let want = function_lines(&answers[case]); + mismatches.extend(diff(&format!("encoder_{case} {name}"), &got, &want)); } assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); } @@ -173,17 +153,17 @@ fn placements(l: &ArgumentBufferLayout) -> BTreeMap> { .collect() } -/// Every element and struct member lands where Metal's encoders put it: the function's and the -/// library binding's at their layout's places, the pipeline binding's every array element at -/// element 0's (the last written wins). Metal's lists can also hold another argument's place -/// (a texture's and a sampler's resource IDs can be equal), so each list must be this crate's -/// place for the argument plus only places of other arguments. +/// Every element and struct member lands where Metal's encoder of the function's argument buffer +/// puts it, at its layout's place. Metal's lists can also hold another argument's place (a +/// texture's and a sampler's resource IDs can be equal), so each list must be this crate's place +/// for the argument plus only places of other arguments. #[test] -fn binding_encoders_place_arguments_as_metal() { +fn the_function_s_encoder_places_arguments_as_metal() { let answers = encoder_answers(); - let Some(encoders) = encoders(0, "args") else { + let Some(function) = function_encoder(0) else { return; }; + let encoders = [("function", function)]; let mut recorded: BTreeMap<&str, (String, BTreeMap>)> = BTreeMap::new(); let mut label = ""; for line in &answers["args_places"] { @@ -227,219 +207,6 @@ fn binding_encoders_place_arguments_as_metal() { ); } } - // The pipeline binding's arrays overlap: texs, smps, ptrs and pairs keep their last element. - let pipeline = placements(&encoders[2].1); - for (lost, kept) in [(3, 5), (4, 5), (16, 17), (18, 19), (24, 26), (25, 27)] { - assert!(pipeline[&lost].is_empty(), "{lost}"); - assert!(!pipeline[&kept].is_empty(), "{kept}"); - } -} - -/// A plain buffer's binding, the library's or the pipeline's, of a pointee that is no struct makes -/// Metal's encoder of no bytes, alignment 1, which API validation lets through, while the -/// function's encoder at that buffer's index is refused, as validation stops it (Metal without -/// validation answers the same empty encoder there). -#[test] -fn a_plain_buffer_binding_makes_an_empty_encoder() { - let answers = encoder_answers(); - for case in [ - "plain_buffer", - "plain_buffer_pipeline", - "plain_buffer_function", - ] { - assert_eq!( - answers[case], - ["plain encodedLength=0 alignment=1"], - "{case}" - ); - } - let Some((library, pipeline)) = bindings("out") else { - return; - }; - for b in [&library, &pipeline] { - let l = ArgumentBufferLayout::from_buffer_binding(b.buffer().expect("a buffer")) - .expect("an empty layout"); - assert_eq!( - encoder_lines("plain", &l, &[], &[]), - ["plain encodedLength=0 alignment=1"] - ); - assert!(l.members.is_empty()); - } - let Some(lib) = fixture("argument_buffers").map(|bc| Library::from_air(&bc).expect("library")) - else { - return; - }; - assert_eq!( - lib.function(FUNCTION) - .expect("function") - .argument_buffer_layout(2, &FunctionConstantValues::defaults(), &Budget::standard()), - Err(ArgumentLayoutError::NoArgumentBuffer { index: 2 }) - ); -} - -/// A plain buffer whose pointee is a struct makes the encoder Metal lays out by the plain -/// buffer's rule: each constant 8 bytes aligned to 8 at its member's offset, and index 0 the last -/// member's (`encoder_plain_struct`: the buffers fixture's `plain`, `nested` and `counter`). -#[test] -fn a_plain_struct_buffer_binding_makes_metals_encoder() { - let answers = encoder_answers(); - let Some(lib) = fixture("buffers").map(|bc| Library::from_air(&bc).expect("library")) else { - return; - }; - let reflection = lib - .function("reflection_buffers") - .expect("function") - .reflection(&Budget::standard()) - .expect("reflection") - .expect("present"); - let got: Vec = ["plain", "nested", "counter"] - .into_iter() - .flat_map(|name| { - let b = reflection - .bindings() - .iter() - .find(|b| b.name() == name) - .and_then(Binding::buffer) - .unwrap_or_else(|| panic!("no buffer binding {name}")); - let l = ArgumentBufferLayout::from_buffer_binding(b) - .unwrap_or_else(|e| panic!("{name}: {e:?}")); - encoder_lines(name, &l, &[0, 1, 2], &[]) - }) - .collect(); - let mismatches = diff("encoder_plain_struct", &got, &answers["plain_struct"]); - assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); -} - -/// Metal's `enc::` sections, in order: the fixture, the kernel and the lines. -fn binding_encoder_answers() -> Vec<(String, String, Vec)> { - let path = fixtures_dir().join("reflection/metal-answers.txt"); - let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}")); - let mut out: Vec<(String, String, Vec)> = Vec::new(); - let mut open = false; - for line in text.lines().filter(|l| !l.starts_with('#')) { - if let Some(name) = line.strip_prefix("== ") { - open = match name.strip_prefix("enc:").and_then(|n| n.split_once(':')) { - Some((fixture, kernel)) => { - out.push((fixture.to_owned(), kernel.to_owned(), Vec::new())); - true - } - None => false, - }; - } else if open { - out.last_mut().expect("a section").2.push(line.to_owned()); - } - } - out -} - -/// The probe's lines for the encoder of buffer binding `name` under `label`: its length and -/// alignment and, for one of any bytes, the offset `constantDataAtIndex:` answers for indices 0 -/// to 7 (the argument's offset, 0 for an index no argument has). -fn binding_encoder_lines(label: &str, name: &str, l: &ArgumentBufferLayout) -> Vec { - let mut out = vec![format!( - "{label} {name} encodedLength={} alignment={}", - l.encoded_length, l.alignment - )]; - if l.encoded_length > 0 { - let offsets: Vec = (0..8) - .map(|i| format!("{i}:{}", l.argument(i).map_or(0, |p| p.offset))) - .collect(); - out.push(format!(" constants {}", offsets.join(" "))); - } - out -} - -/// Every buffer binding of the encoders, encoder_types and encoder_arrays fixtures' kernels, the -/// library's and the pipeline's, makes Metal's encoder: plain buffers of a struct of each scalar, -/// vector, packed vector, matrix and atomic type, of arrays, of members in both orders and of -/// nested structs and arrays of them (each constant 8 bytes aligned to 8); argument buffers whose -/// last member is a constant of each type (its MSL size and alignment deciding the length), a -/// plain-data struct held by value and an array of them, explicit ids with a gap, and arrays of -/// structs mixing resources and constants (which a pipeline's reflection keeps at their element -/// size); and a plain buffer of a vector (no bytes). Lengths, alignments and the constants' -/// offsets, line for line. -#[test] -fn every_binding_encoder_matches_metal() { - let answers = binding_encoder_answers(); - assert_eq!( - answers.len(), - 9, - "the encoders, encoder_types and encoder_arrays kernels" - ); - let budget = Budget::standard(); - let mut libraries: BTreeMap = BTreeMap::new(); - let mut mismatches = Vec::new(); - let mut compared = 0; - for (stem, kernel, want) in &answers { - if !libraries.contains_key(stem) { - let Some(bc) = fixture(stem) else { - return; - }; - let lib = Library::from_air(&bc).unwrap_or_else(|e| panic!("{stem}: {e:?}")); - libraries.insert(stem.clone(), lib); - } - let f = libraries[stem] - .function(kernel) - .unwrap_or_else(|e| panic!("{stem} {kernel}: {e:?}")); - let library = f - .reflection(&budget) - .unwrap_or_else(|e| panic!("{kernel}: {e:?}")) - .expect("present"); - let pipeline = - ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))) - .reflection(&budget) - .unwrap_or_else(|e| panic!("{kernel} pipeline: {e:?}")); - let mut got = Vec::new(); - for (label, bindings) in [ - ("library", library.bindings()), - ("pipeline", pipeline.bindings()), - ] { - for b in bindings { - let Some(buffer) = b.buffer() else { - continue; - }; - let l = ArgumentBufferLayout::from_buffer_binding(buffer) - .unwrap_or_else(|e| panic!("{kernel} {label} {}: {e:?}", b.name())); - got.extend(binding_encoder_lines(label, b.name(), &l)); - compared += 1; - } - } - mismatches.extend(diff(&format!("enc:{stem}:{kernel}"), &got, want)); - } - // encoders_plain's 25 bindings, encoders_args' 11, each encoder_types_plain kernel's 22, - // each encoder_types_tail kernel's 23 and encoder_arrays' 11, the library's and the - // pipeline's. - assert_eq!(compared, 2 * (25 + 11 + 3 * 22 + 3 * 23 + 11)); - assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); -} - -/// A plain buffer's struct member that is no constant (here a pointer) has an encoder Metal's -/// answer was not measured for: refused, typed, naming the member. -#[test] -fn a_plain_buffer_pointer_member_is_refused() { - let pointer = PointerType::new( - DataType::Float, - BindingAccess::ReadOnly, - 4, - 4, - false, - TypeDetail::Plain, - ); - let st = StructType::new(vec![StructMember::new( - "p".to_owned(), - 0, - DataType::Pointer, - 0, - TypeDetail::Pointer(Box::new(pointer)), - )]); - let binding = BufferBinding::new(8, 8, DataType::Struct, Some(st), None); - match ArgumentBufferLayout::from_buffer_binding(&binding) { - Err(ArgumentLayoutError::Compile(Error::Unsupported(u))) => { - assert_eq!(u.feature, Feature::Reflection); - assert_eq!(u.symbol, Some(DiagName::new("p"))); - } - other => panic!("{other:?}"), - } } /// An argument buffer's member the AIR gives no argument index (a plain member of its struct diff --git a/crates/metal2vulkan/src/spirv/requirements/level_reads/tests.rs b/crates/metal2vulkan/src/spirv/requirements/level_reads/tests.rs index 875e45c8e..cb0cd57f3 100644 --- a/crates/metal2vulkan/src/spirv/requirements/level_reads/tests.rs +++ b/crates/metal2vulkan/src/spirv/requirements/level_reads/tests.rs @@ -360,164 +360,6 @@ fn levels(min_lod: f32, max_lod: f32, linear: bool, finite_texels: bool) -> Samp } } -/// The highest level a slot's reads reach under a sampler: the nearest mipmap mode's rounding of -/// the clamped level of detail, the linear one's next level unless a whole level of finite texels -/// gives it no weight, a constant clamped into the sampler's bounds, a NaN at `maxLod`, and none -/// where a read reaches any level, the sampler is unknown, or its bounds are crossed. -#[test] -fn the_highest_level_follows_the_bound_sampler() { - let s = SamplerRef::Slot(0); - let computed = LevelReads { - slot: 0, - any: false, - named: None, - lowest_read: None, - sampled: vec![sampled(s, None, true)], - }; - let constant = |c: f32| LevelReads { - sampled: vec![sampled(s, Some((c, c)), false)], - ..computed.clone() - }; - let at = |reads: &LevelReads, l: SamplerLevels| { - reads.highest_level(|r| (r.sampler == s).then(|| r.level(l)).flatten()) - }; - // Metal's `NotMipmapped`, as `vk_sampler` maps it: the first level alone. - assert_eq!(at(&computed, levels(0.0, 0.25, false, true)), Some(0)); - assert_eq!(at(&computed, levels(0.0, 1.0, false, true)), Some(1)); - assert_eq!(at(&computed, levels(0.0, 1.4, false, true)), Some(1)); - assert_eq!(at(&computed, levels(0.0, 1.5, false, true)), Some(2)); - assert_eq!(at(&computed, levels(0.0, 1.0, true, true)), Some(1)); - assert_eq!(at(&computed, levels(0.0, 1.0, true, false)), Some(2)); - assert_eq!(at(&computed, levels(0.0, 1.25, true, true)), Some(2)); - assert_eq!(at(&constant(1.0), levels(0.0, 1000.0, true, true)), Some(1)); - assert_eq!( - at(&constant(1.0), levels(0.0, 1000.0, false, false)), - Some(1) - ); - assert_eq!( - at(&constant(1.0), levels(0.0, 1000.0, true, false)), - Some(2) - ); - assert_eq!(at(&constant(3.0), levels(0.0, 1.0, false, true)), Some(1)); - assert_eq!(at(&constant(-2.0), levels(0.0, 1.0, false, true)), Some(0)); - assert_eq!( - at(&constant(f32::NAN), levels(0.0, 2.0, false, true)), - Some(2) - ); - // A constexpr sampler's bias raises a constant level of detail, and a negative one is not - // counted on to lower it. - let biased = |bias: f32| SamplerLevels { - bias, - ..levels(0.0, 1000.0, false, true) - }; - assert_eq!(at(&constant(1.0), biased(1.0)), Some(2)); - assert_eq!(at(&constant(2.0), biased(-1.0)), Some(2)); - assert_eq!(at(&computed, biased(1.0)), None); - assert!(SamplerLevels::finite_texels( - crate::vk::Format::B8G8R8A8_UNORM - )); - assert!(!SamplerLevels::finite_texels( - crate::vk::Format::R16G16_SFLOAT - )); - // Metal's `lodMaxClamp` of `FLT_MAX`: every level. - assert_eq!(at(&computed, levels(0.0, f32::MAX, false, true)), None); - assert_eq!(at(&computed, levels(2.0, 1.0, false, true)), None); - assert_eq!(computed.highest_level(|_| None), None); - let fetched = LevelReads { - named: Some(2), - lowest_read: Some(2), - ..computed.clone() - }; - assert_eq!(at(&fetched, levels(0.0, 1.0, false, true)), Some(2)); - let any = LevelReads { - any: true, - ..fetched - }; - assert_eq!(at(&any, levels(0.0, 0.25, false, true)), None); -} - -/// The lowest level a slot's reads may reach under a sampler: `floor` of the sampler's `minLod` -/// where a level of detail is computed, of the lowest constant clamped into the sampler's bounds -/// and lowered by a negative bias, the lowest a fetch names, the first level where a read reaches -/// any level, a NaN constant, or the sampler's bounds are crossed or not finite, and none where -/// no read reaches a level. -#[test] -fn the_lowest_level_follows_the_bound_sampler() { - let s = SamplerRef::Slot(0); - let computed = LevelReads { - slot: 0, - any: false, - named: None, - lowest_read: None, - sampled: vec![sampled(s, None, true)], - }; - let constants = |lowest: f32, highest: f32| LevelReads { - sampled: vec![sampled(s, Some((lowest, highest)), false)], - ..computed.clone() - }; - let at = |reads: &LevelReads, l: SamplerLevels| reads.lowest_level(|r| r.lowest(l)); - assert_eq!(at(&computed, levels(0.0, 1000.0, false, true)), Some(0)); - assert_eq!(at(&computed, levels(3.0, 1000.0, false, true)), Some(3)); - // Both nearest roundings of 2.5 read level 2; the linear mode reads 2 and 3. - assert_eq!(at(&computed, levels(2.5, 1000.0, false, true)), Some(2)); - assert_eq!(at(&computed, levels(2.5, 1000.0, true, true)), Some(2)); - assert_eq!(at(&computed, levels(3.0, f32::MAX, true, false)), Some(3)); - assert_eq!( - at(&constants(3.7, 5.0), levels(0.0, 1000.0, false, true)), - Some(3) - ); - assert_eq!( - at(&constants(3.0, 5.0), levels(4.0, 1000.0, false, true)), - Some(4) - ); - assert_eq!( - at(&constants(3.0, 5.0), levels(0.0, 1.0, false, true)), - Some(1) - ); - assert_eq!( - at(&constants(-2.0, 5.0), levels(0.0, 1.0, false, true)), - Some(0) - ); - assert_eq!( - at(&constants(f32::NAN, 5.0), levels(2.0, 9.0, false, true)), - Some(0) - ); - // A negative bias lowers a constant level of detail; a positive one is not counted on to - // raise it. A computed one stays at `minLod` or above whatever the bias. - let biased = |min_lod: f32, bias: f32| SamplerLevels { - bias, - ..levels(min_lod, 1000.0, false, true) - }; - assert_eq!(at(&constants(3.0, 5.0), biased(0.0, -1.0)), Some(2)); - assert_eq!(at(&constants(3.0, 5.0), biased(0.0, 1.0)), Some(3)); - assert_eq!(at(&computed, biased(2.0, -1.0)), Some(2)); - // A NaN bias is none, as a device's sampler takes it. - assert_eq!(at(&constants(3.0, 5.0), biased(0.0, f32::NAN)), Some(3)); - // Crossed or unbounded sampler levels: the first level. - assert_eq!(at(&computed, levels(2.0, 1.0, false, true)), Some(0)); - assert_eq!( - at(&computed, levels(2.0, f32::INFINITY, false, true)), - Some(0) - ); - // A fetch's level among the samples' (a comparison of the level count is no read). - let fetched = LevelReads { - named: Some(5), - lowest_read: Some(2), - ..computed.clone() - }; - assert_eq!(at(&fetched, levels(3.0, 1000.0, false, true)), Some(2)); - let any = LevelReads { - any: true, - ..fetched - }; - assert_eq!(at(&any, levels(3.0, 1000.0, false, true)), Some(0)); - let none = LevelReads { - sampled: Vec::new(), - ..computed - }; - assert_eq!(at(&none, levels(3.0, 1000.0, false, true)), None); -} - /// A NaN among a sampler's constant levels of detail stays the highest whatever comes after it, /// as `SampledLevels::level` reads a NaN at the sampler's `maxLod`: `f32::max` would drop it. #[test] diff --git a/crates/metal2vulkan/src/tests/argument_buffers.rs b/crates/metal2vulkan/src/tests/argument_buffers.rs index ea1e9b47c..d4d2a8cca 100644 --- a/crates/metal2vulkan/src/tests/argument_buffers.rs +++ b/crates/metal2vulkan/src/tests/argument_buffers.rs @@ -1,36 +1,13 @@ -//! Argument-buffer layouts: where `MTLArgumentEncoder` writes each argument, from argument -//! descriptors and from a function's `air.struct_type_info`. Every expected offset, length and +//! Argument-buffer layouts: where `MTLArgumentEncoder` writes each argument, from a function's +//! `air.struct_type_info`. Every expected offset, length and //! alignment here is what Metal's encoder answered on an M3 Max and an M4 (probes, CPU only: the //! bytes each setter changed in a buffer). -use crate::bind::{ - ArgumentBufferLayout, ArgumentDescriptor, ArgumentLayoutError, ArgumentType as T, -}; +use crate::bind::{ArgumentBufferLayout, ArgumentLayoutError, ArgumentType as T}; use crate::budget::Budget; use crate::library::{FunctionConstantValues, Library}; -use crate::metal::DataType as D; use crate::pipeline::testing::AssembleError; -fn one(data_type: D, index: u32) -> ArgumentDescriptor { - ArgumentDescriptor::new(data_type, index) -} - -fn array(data_type: D, index: u32, length: u32) -> ArgumentDescriptor { - let mut d = ArgumentDescriptor::new(data_type, index); - d.array_length = length; - d -} - -fn aligned(data_type: D, index: u32, alignment: u32) -> ArgumentDescriptor { - let mut d = ArgumentDescriptor::new(data_type, index); - d.constant_block_alignment = alignment; - d -} - -fn layout(descriptors: &[ArgumentDescriptor]) -> ArgumentBufferLayout { - ArgumentBufferLayout::from_descriptors(descriptors).expect("a layout") -} - /// Argument `index`'s offset and type. fn at(layout: &ArgumentBufferLayout, index: u32) -> (u64, T) { let place = layout @@ -44,260 +21,6 @@ fn sized(layout: &ArgumentBufferLayout) -> (u64, u64) { (layout.encoded_length, layout.alignment) } -#[test] -fn descriptors_lay_out_as_a_c_struct_in_the_order_given() { - // probe d1: a pointer, a texture, a sampler, a float and a float4. - let l = layout(&[ - one(D::Pointer, 0), - one(D::Texture, 1), - one(D::Sampler, 2), - one(D::Float, 3), - one(D::Float4, 4), - ]); - assert_eq!(sized(&l), (48, 16)); - assert_eq!(at(&l, 0), (0, T::Buffer)); - assert_eq!(at(&l, 1), (8, T::Texture)); - assert_eq!(at(&l, 2), (16, T::Sampler)); - assert_eq!(at(&l, 3), (24, T::Constant)); - assert_eq!(at(&l, 4), (32, T::Constant)); - // probe d2: constants first. - let l = layout(&[ - one(D::Float, 0), - one(D::Pointer, 1), - one(D::Char, 2), - one(D::Texture, 3), - ]); - assert_eq!(sized(&l), (32, 8)); - assert_eq!( - [at(&l, 0).0, at(&l, 1).0, at(&l, 2).0, at(&l, 3).0], - [0, 8, 16, 24] - ); - // probe d3: the order given, not the indices', with gaps between indices. - let l = layout(&[one(D::Texture, 9), one(D::Float, 2), one(D::Pointer, 5)]); - assert_eq!(sized(&l), (24, 8)); - assert_eq!([at(&l, 9).0, at(&l, 2).0, at(&l, 5).0], [0, 8, 16]); - assert!(l.argument(3).is_none()); - // probes d10 and d18: every object is 8 bytes. - let l = layout(&[ - one(D::IndirectCommandBuffer, 0), - one(D::ComputePipeline, 1), - one(D::RenderPipeline, 2), - one(D::VisibleFunctionTable, 3), - one(D::Char, 4), - ]); - assert_eq!(sized(&l), (40, 8)); - assert_eq!(at(&l, 3), (24, T::VisibleFunctionTable)); - assert_eq!(at(&l, 4), (32, T::Constant)); - let l = layout(&[ - one(D::InstanceAccelerationStructure, 0), - one(D::PrimitiveAccelerationStructure, 1), - one(D::IntersectionFunctionTable, 2), - ]); - assert_eq!(sized(&l), (24, 8)); -} - -#[test] -fn descriptor_arrays_take_an_index_per_element() { - // probe d4. - let l = layout(&[ - array(D::Texture, 0, 3), - array(D::Pointer, 3, 2), - array(D::Float, 5, 4), - array(D::Sampler, 9, 2), - ]); - assert_eq!(sized(&l), (72, 8)); - let offsets: Vec = (0..11).map(|i| at(&l, i).0).collect(); - assert_eq!(offsets, [0, 8, 16, 24, 32, 40, 44, 48, 52, 56, 64]); - assert!(l.argument(11).is_none()); - // probes d13 and d15: an array of 1 is one argument; a constant array is packed. - let l = layout(&[array(D::Pointer, 0, 1), array(D::Texture, 1, 1)]); - assert_eq!(sized(&l), (16, 8)); - let l = layout(&[array(D::UChar, 0, 3), one(D::Float, 3)]); - assert_eq!(sized(&l), (8, 4)); - assert_eq!([at(&l, 1).0, at(&l, 2).0, at(&l, 3).0], [1, 2, 4]); -} - -#[test] -fn constants_take_msl_sizes_and_alignments() { - // probe 4's type cases, `[texture, type, char]`: (type, the type's offset, the char's offset, - // length, alignment). - let cases = [ - (D::BFloat3, 8, 16, 24, 8), - (D::Long3, 32, 64, 96, 32), - (D::ULong4, 32, 64, 96, 32), - (D::Half2x3, 8, 24, 32, 8), - (D::Half3x3, 8, 32, 40, 8), - (D::Short3, 8, 16, 24, 8), - (D::Char3, 8, 12, 16, 8), - (D::Bool3, 8, 12, 16, 8), - (D::Float3x2, 8, 32, 40, 8), - (D::Float4x3, 16, 80, 96, 16), - (D::Int3, 16, 32, 48, 16), - (D::DepthStencilState, 8, 16, 24, 8), - ]; - for (ty, offset, next, length, alignment) in cases { - let l = layout(&[one(D::Texture, 0), one(ty, 1), one(D::Char, 2)]); - assert_eq!(l.argument(1).map(|p| p.offset), Some(offset), "{ty:?}"); - assert_eq!(at(&l, 2).0, next, "{ty:?}"); - assert_eq!(sized(&l), (length, alignment), "{ty:?}"); - } - let l = layout(&[ - one(D::Char, 0), - one(D::Float4, 1), - one(D::Char, 2), - one(D::Float3, 3), - one(D::Half, 4), - ]); - assert_eq!(sized(&l), (80, 16)); - let offsets: Vec = (0..5).map(|i| at(&l, i).0).collect(); - assert_eq!(offsets, [0, 16, 32, 48, 64]); - let l = layout(&[ - one(D::Float2x3, 0), - one(D::Half3, 1), - one(D::Long, 2), - one(D::UChar4, 3), - one(D::Bool2, 4), - one(D::Float3x3, 5), - ]); - assert_eq!(sized(&l), (112, 16)); - let offsets: Vec = (0..6).map(|i| at(&l, i).0).collect(); - assert_eq!(offsets, [0, 32, 40, 48, 52, 64]); - // probes d8 and d8c. - let l = layout(&[ - one(D::Float4x4, 0), - one(D::Int2, 1), - one(D::Bool, 2), - one(D::UShort3, 3), - ]); - assert_eq!(sized(&l), (96, 16)); - let offsets: Vec = (0..4).map(|i| at(&l, i).0).collect(); - assert_eq!(offsets, [0, 64, 72, 80]); - let l = layout(&[one(D::Char, 0), one(D::ULong2, 1)]); - assert_eq!((at(&l, 1).0, sized(&l)), (16, (32, 16))); - // probe d7. - let l = layout(&[one(D::Char, 0)]); - assert_eq!(sized(&l), (1, 1)); -} - -#[test] -fn a_constant_block_alignment_moves_only_its_block() { - // probes d6a, d6b, d6e to d6h, a12 to a48, f4a20 to f4a40 and fa6: (layout, index, offset, - // length, alignment). An alignment that is no power of two steps as `(o + a - 1) & !(a - 1)`. - let tex = || one(D::Texture, 0); - let cases: Vec<(Vec, u32, u64, u64, u64)> = vec![ - (vec![aligned(D::Char, 0, 64), one(D::Float, 1)], 1, 4, 8, 4), - ( - vec![ - one(D::Pointer, 0), - aligned(D::Char, 1, 64), - one(D::Float, 2), - ], - 2, - 68, - 72, - 8, - ), - ( - vec![tex(), aligned(D::Int, 1, 32), one(D::Int, 2)], - 1, - 32, - 40, - 8, - ), - (vec![tex(), aligned(D::Char, 1, 3)], 1, 8, 16, 8), - (vec![aligned(D::Char, 0, 1024)], 0, 0, 1, 1), - ( - vec![aligned(D::Float4, 0, 4), one(D::Char, 1)], - 1, - 16, - 32, - 16, - ), - (vec![tex(), aligned(D::Char, 1, 12)], 1, 16, 24, 8), - (vec![tex(), aligned(D::Char, 1, 20)], 1, 8, 16, 8), - (vec![tex(), aligned(D::Char, 1, 24)], 1, 8, 16, 8), - (vec![tex(), aligned(D::Char, 1, 48)], 1, 16, 24, 8), - (vec![tex(), aligned(D::Float4, 1, 24)], 1, 8, 32, 16), - (vec![tex(), aligned(D::Float4, 1, 20)], 1, 8, 32, 16), - (vec![tex(), aligned(D::Float4, 1, 40)], 1, 8, 32, 16), - (vec![tex(), aligned(D::Float, 1, 6)], 1, 8, 16, 8), - ]; - for (descriptors, index, offset, length, alignment) in cases { - let l = layout(&descriptors); - assert_eq!(at(&l, index).0, offset, "{descriptors:?}"); - assert_eq!(sized(&l), (length, alignment), "{descriptors:?}"); - } - // Two blocks (d6c): a pointer ends the first. - let l = layout(&[ - one(D::Pointer, 0), - one(D::Char, 1), - one(D::Pointer, 2), - aligned(D::Char, 3, 32), - one(D::Char, 4), - ]); - assert_eq!(sized(&l), (40, 8)); - let offsets: Vec = (0..5).map(|i| at(&l, i).0).collect(); - assert_eq!(offsets, [0, 8, 16, 32, 33]); - // A block's alignment below its type's (a2-float4), and an aligned array (a16-array). - let l = layout(&[ - tex(), - one(D::Char, 1), - one(D::Texture, 2), - aligned(D::Float4, 3, 2), - ]); - assert_eq!((at(&l, 3).0, sized(&l)), (32, (48, 16))); - let mut chars = array(D::Char, 1, 3); - chars.constant_block_alignment = 16; - let l = layout(&[tex(), chars, one(D::Float, 4)]); - let offsets: Vec = (1..5).map(|i| at(&l, i).0).collect(); - assert_eq!(offsets, [16, 17, 18, 20]); - assert_eq!(sized(&l), (24, 8)); -} - -#[test] -fn descriptors_metal_refuses_are_refused() { - assert_eq!( - ArgumentBufferLayout::from_descriptors(&[]), - Err(ArgumentLayoutError::NoDescriptors) - ); - for ty in [ - D::None, - D::Struct, - D::Array, - D::R8Unorm, - D::RGBA16Unorm, - D::Tensor, - ] { - assert_eq!( - ArgumentBufferLayout::from_descriptors(&[one(D::Texture, 0), one(ty, 1)]), - Err(ArgumentLayoutError::DataType { - position: 1, - data_type: ty - }) - ); - } - // Only a block's first constant may set the alignment (probe d6d); a 0 later is no setting. - assert_eq!( - ArgumentBufferLayout::from_descriptors(&[one(D::Char, 0), aligned(D::Float4, 1, 4)]), - Err(ArgumentLayoutError::ConstantBlockAlignment { position: 1 }) - ); - let l = layout(&[one(D::Char, 0), one(D::Float, 1)]); - assert_eq!((at(&l, 1).0, sized(&l)), (4, (8, 4))); -} - -#[test] -fn an_index_two_descriptors_claim_is_the_later_ones() { - // probe d11: the same index twice; probe d16: an index inside an earlier array. - let l = layout(&[one(D::Float, 0), one(D::Pointer, 0)]); - assert_eq!(sized(&l), (16, 8)); - assert_eq!(at(&l, 0), (8, T::Buffer)); - let l = layout(&[array(D::Texture, 0, 3), one(D::Pointer, 1)]); - assert_eq!(sized(&l), (32, 8)); - assert_eq!(at(&l, 0), (0, T::Texture)); - assert_eq!(at(&l, 1), (24, T::Buffer)); - assert_eq!(at(&l, 2), (16, T::Texture)); -} - /// Synthetic AIR (opaque pointers, empty bodies). Kernels `kA` and `kH` state the /// `air.struct_type_info` that Metal's compiler gives the probe's `A` and probe 3's `H` (MSL of our /// own; nodes !9 to !92). `kAA` takes an array of arrays, and `kP` a plain buffer. diff --git a/crates/metal2vulkan/src/tests/bind_shape_of.rs b/crates/metal2vulkan/src/tests/bind_shape_of.rs index 4e05ded9f..63cbc8697 100644 --- a/crates/metal2vulkan/src/tests/bind_shape_of.rs +++ b/crates/metal2vulkan/src/tests/bind_shape_of.rs @@ -294,30 +294,6 @@ fn a_state_has_exactly_the_shape_it_makes() { assert_eq!(same, 10 * 9 + 2 + 2, "pairs of one shape"); } -/// A state's shape key is its shape's, and the key of every shape it has beside its used -/// resources: a consumer that compares whole only the shapes of its key finds every one it would -/// find comparing all. The fixture's states of other shapes beside their used resources have other -/// keys too, so the key spares their comparisons. -#[test] -fn a_state_s_shape_key_is_the_key_of_every_shape_it_has() { - let states = states(); - let shapes: Vec<_> = states.iter().map(BindState::shape).collect(); - let mut apart = 0; - for (at, state) in states.iter().enumerate() { - let key = state.shape_key_beside_used(); - assert_eq!(key, shapes[at].key_beside_used(), "state {at}: {state:?}"); - for (of, shape) in shapes.iter().enumerate() { - if state.has_shape_beside_used(shape) { - assert_eq!(key, shape.key_beside_used(), "state {at}, shape {of}"); - } else { - assert_ne!(key, shape.key_beside_used(), "state {at}, shape {of}"); - apart += 1; - } - } - } - assert!(apart > 0, "no state of another shape in the fixture"); -} - /// A buffer's bind offset cycling through the multiples of 16 up to 256 at a view base alignment /// of 64 keeps one shape where its slot tells no alignment past 4 apart (vertex data, or a view /// a runtime left out), and takes two where the slot tells it apart (a uniform view: 64 divides @@ -347,135 +323,6 @@ fn a_slot_s_offsets_moving_among_multiples_of_16_keep_their_shapes() { } } -/// A state that lists used resources is found among shapes that each match it in every other -/// field, and differ in what it lists but the last, with its used resources' shape made once -/// (`position_of_shape`), as allocating as one comparison (`has_shape`) is: compared one by one, -/// each comparison makes it again. -#[test] -fn a_state_s_shape_is_found_among_many_with_its_used_resources_made_once() { - use super::constant_blob_footprint::allocations_during; - const SHAPES: u32 = 4; - let listing = |tokens: std::ops::Range| { - let mut state = base(); - for token in tokens { - let mut used = UsedResource::new(ResourceClass::Buffer, token); - used.usage = ResourceUsage::READ; - used.stages = RenderStages::FRAGMENT; - state.used_resources.push(used); - } - state - }; - // Each lists 16 resources; the state lists the last's. - let shapes: Vec<_> = (0..SHAPES) - .map(|at| listing(at * 16..at * 16 + 16).shape()) - .collect(); - let state = listing((SHAPES - 1) * 16..SHAPES * 16); - let last = SHAPES as usize - 1; - - let (found, one_by_one) = - allocations_during(|| shapes.iter().position(|shape| state.has_shape(shape))); - assert_eq!(found, Some(last)); - let (found, at_once) = allocations_during(|| state.position_of_shape(&shapes)); - assert_eq!(found, Some(last)); - let (has, one) = allocations_during(|| state.has_shape(&shapes[last])); - assert!(has); - assert!(one > 0, "a used resources' shape is made"); - assert_eq!( - at_once, one, - "found among {SHAPES}: as allocating as one comparison" - ); - assert_eq!(one_by_one, one * u64::from(SHAPES), "one by one: one each"); - // A state that lists none makes nothing; nor does one whose shape differs in another field. - let none = base(); - let (found, made) = allocations_during(|| none.position_of_shape(&shapes)); - assert_eq!((found, made), (None, 0), "a state that lists none"); - let mut other = listing(0..16); - other.render_target_array_length = 2; - let (found, made) = allocations_during(|| other.position_of_shape(&shapes)); - assert_eq!((found, made), (None, 0), "a state of another field"); -} - -/// A state that lists its used resources in token order (`BindState::used_in_token_order`) -/// compares them with a shape's in place, making nothing: over listings that differ in a token, a -/// usage, a stage, a class, a token listed twice (whose entries union, the first's class kept) or -/// one listed more or less, each answers as the same listing in no order does, against the shape -/// of every other, and is found among them all without allocating. -#[test] -fn a_state_listed_in_token_order_compares_its_used_resources_in_place() { - use super::constant_blob_footprint::allocations_during; - let entry = |class, token, usage, stages| { - let mut used = UsedResource::new(class, token); - used.usage = usage; - used.stages = stages; - used - }; - let buffer = ResourceClass::Buffer; - let read = |token| entry(buffer, token, ResourceUsage::READ, RenderStages::FRAGMENT); - let listing = |change: &dyn Fn(&mut Vec)| { - let mut state = base(); - state.used_resources = (0..16).map(read).collect(); - change(&mut state.used_resources); - state - }; - let facts = |format| ResourceClass::Texture(TextureFacts::new(TextureType::Type2D, format)); - let unorm = facts(PixelFormat::RGBA8Unorm); - let states = [ - listing(&|_| {}), - listing(&|used| used[15].token = 40), - listing(&|used| used[5].usage = ResourceUsage::WRITE), - listing(&|used| used[5].stages = RenderStages::VERTEX), - listing(&|used| used[7].class = unorm), - listing(&|used| used[7].class = facts(PixelFormat::R32Float)), - listing(&|used| used.insert(8, read(8))), - listing(&|used| { - used.insert( - 9, - entry(buffer, 8, ResourceUsage::WRITE, RenderStages::VERTEX), - ) - }), - listing(&|used| { - used.insert( - 9, - entry(unorm, 8, ResourceUsage::WRITE, RenderStages::VERTEX), - ) - }), - listing(&|used| { - used[8].usage = ResourceUsage::READ | ResourceUsage::WRITE; - used[8].stages = RenderStages::VERTEX | RenderStages::FRAGMENT; - }), - listing(&|used| { - used.remove(10); - }), - listing(&|used| used.push(read(16))), - listing(&|used| used.truncate(1)), - ]; - let shapes: Vec<_> = states.iter().map(BindState::shape).collect(); - let mut same = 0; - for (at, state) in states.iter().enumerate() { - let mut ordered = state.clone(); - ordered.used_in_token_order = true; - for (of, shape) in shapes.iter().enumerate() { - let equal = shapes[at] == *shape; - same += usize::from(equal && at != of); - let (has, made) = allocations_during(|| ordered.has_shape(shape)); - assert_eq!(has, equal, "state {at} in token order, shape {of}"); - assert_eq!( - has, - state.has_shape(shape), - "state {at} in no order, shape {of}" - ); - assert_eq!(made, 0, "state {at} in token order, shape {of}: made"); - } - let (found, made) = allocations_during(|| ordered.position_of_shape(&shapes)); - assert_eq!(found, state.position_of_shape(&shapes), "state {at}: found"); - assert_eq!(made, 0, "state {at}: found among them all, made"); - } - // A token listed twice with the same usage and stages is the listing's shape (one pair); one - // listed again with a vertex write, as a buffer or as a texture, is the one listed once that - // reads and writes it in both stages (three of one shape). - assert_eq!(same, 2 + 3 * 2, "pairs of one shape"); -} - /// `BoundBuffer::same_shape` answers `a.shape(x, r) == b.shape(x, r)` for every pair of bindings /// over lengths of one length class and of others, bind offsets of one alignment class and of /// others, with and without a device address and a stride, and inline bytes, at view base diff --git a/crates/metal2vulkan/src/tests/engine_dynamic_libraries.rs b/crates/metal2vulkan/src/tests/engine_dynamic_libraries.rs index 3c924d7d6..98d68efb3 100644 --- a/crates/metal2vulkan/src/tests/engine_dynamic_libraries.rs +++ b/crates/metal2vulkan/src/tests/engine_dynamic_libraries.rs @@ -506,59 +506,3 @@ fn the_searched_libraries_are_part_of_the_key() { ) ); } - -/// Loading a stage's dependencies asks for each install name in the search's order, a loaded -/// library's own after those already reached, skips one already loaded, and stops at the first -/// that does not load, whose imports the compile then refuses. -#[test] -fn dependencies_load_in_the_search_order() { - let (Some(a), Some(b)) = (dylib("libA.metallib", 3, 7), dylib("libB.metallib", 5, 11)) else { - return; - }; - let Some(module) = library_module("libC", 9, 13, false) else { - return; - }; - let c = Library::parse(&dylib_bytes_linked( - "libC.metallib", - &module, - &["libA.metallib"], - )) - .expect("library"); - let c = DynamicLibrary::new(c, &Budget::standard()).expect("dynamic"); - let Some(client) = client("load", true, &["libC.metallib", "libB.metallib"]) else { - return; - }; - let file = |name: &str| match name { - "libA.metallib" => Some(a.clone()), - "libB.metallib" => Some(b.clone()), - "libC.metallib" => Some(c.clone()), - _ => None, - }; - let mut asked = Vec::new(); - let fd = stage(&client, DynamicLibraries::new()).with_loaded_dependencies(|name| { - asked.push(name.to_owned()); - file(name) - }); - assert_eq!(asked, ["libC.metallib", "libB.metallib", "libA.metallib"]); - // The client's first dependency exports both symbols. - let want: Vec = (0..16).map(|i| 9 * i + 13).collect(); - assert_eq!(computed(&fd), want); - - // A library already loaded is not asked for. - let mut asked = Vec::new(); - let given = DynamicLibraries::new().with_loaded("libC.metallib", c.clone()); - stage(&client, given).with_loaded_dependencies(|name| { - asked.push(name.to_owned()); - file(name) - }); - assert_eq!(asked, ["libB.metallib", "libA.metallib"]); - - // An install name that does not load ends the loading, and the import is refused. - let mut asked = Vec::new(); - let fd = stage(&client, DynamicLibraries::new()).with_loaded_dependencies(|name| { - asked.push(name.to_owned()); - (name == "libC.metallib").then(|| c.clone()) - }); - assert_eq!(asked, ["libC.metallib", "libB.metallib"]); - assert_eq!(compile(fd), Err(needs_library("libB.metallib"))); -} diff --git a/crates/metal2vulkan/src/tests/engine_dynamic_roots.rs b/crates/metal2vulkan/src/tests/engine_dynamic_roots.rs index 793e12f52..72c843210 100644 --- a/crates/metal2vulkan/src/tests/engine_dynamic_roots.rs +++ b/crates/metal2vulkan/src/tests/engine_dynamic_roots.rs @@ -638,72 +638,6 @@ fn resident_entries(resident: &[(u64, u64, u64)]) -> Vec { bytes } -/// A resident set uploaded apart from its root table, below it (`R0` wraps modulo 2^64) or far -/// above it, resolves every resident address as one inside the table does, and misses the gaps; the -/// search indexes the set from its own first entry, so the interpreter, which traps a negative -/// access-chain index, reads only the set. -#[test] -fn a_resident_set_apart_from_the_table_resolves_below_and_above_it() { - let body = " %g = load i64, ptr addrspace(1) %2, align 8\n\ - %p = inttoptr i64 %g to ptr addrspace(1)\n\ - %v = load i32, ptr addrspace(1) %p, align 4\n\ - store i32 %v, ptr addrspace(1) %1, align 4\n"; - let Some(bc) = assemble_text("from_int", &kernel("from_int", body)) else { - return; - }; - let p = profile("moltenvk-m3", true, DevicePolicy::default()); - let a = compile(&bc, "from_int", &p).expect("compile"); - link_and_validate(&a, &p).expect("L3"); - let (plan, m) = typed_module(&bc, "from_int", &p).expect("module"); - for set in [TABLE - 0x1_0000_0000, TABLE - 0x800, TABLE + 0x3_0000_0000] { - for n in [1u64, 2, 5, 17] { - let resident: Vec<(u64, u64, u64)> = - (0..n).map(|k| (host(k), guest(k), ALLOC)).collect(); - let mut table = root_table(&[(0, 0, 0, 0); 3], &[]); - let fields = crate::bind::RootTable::resident_fields(TABLE, set, n).expect("aligned"); - let at = crate::bind::RootTable::RESIDENT_FIELDS_OFFSET as usize; - table[at..at + 16].copy_from_slice(&fields); - let mut probes: Vec<(u64, Option<(u64, u64)>)> = - vec![(0, None), (guest(0) - 4, None), (guest(n) + 8, None)]; - for k in 0..n { - probes.push((guest(k), Some((k, 0)))); - probes.push((guest(k) + 12, Some((k, 12)))); - probes.push((guest(k) + ALLOC + 4, None)); - } - for (addr, want) in probes { - let mut buffers = vec![ - slot_buffer(0, vec![0; 16]), - slot_buffer(1, vec![0; 16]), - slot_buffer(2, addr.to_le_bytes().to_vec()), - addressed(TABLE, table.clone()), - addressed(SINK, vec![0; 64]), - addressed(STATUS, vec![0; ExecutionStatus::BYTES]), - addressed(set, resident_entries(&resident)), - ]; - for k in 0..n { - buffers.push(addressed(host(k), pattern(k))); - } - let res = Resources { - buffers, - push: push_bytes(&plan), - spec: Default::default(), - }; - let case = format!("set={set:#x} n={n} addr={addr:#x}"); - let out = - run(&m, &Config::default(), res).unwrap_or_else(|e| panic!("{case}: {e}")); - let expect = match want { - Some((k, rel)) => pattern(k)[rel as usize..rel as usize + 4].to_vec(), - None => vec![0; 4], - }; - assert_eq!(&out.buffers[1][..4], &expect[..], "{case}"); - let misses = - status_words(&out.buffers[5])[StatusWord::ResidentMisses.index() as usize]; - assert_eq!(misses, u32::from(want.is_none()), "{case}: misses"); - } - } - } -} - /// A linked-list walk: the head is the `[[buffer(0)]]` parameter and each next pointer is loaded /// from the current node, so the loop's pointer phi merges the parameter with loaded pointers. /// The parameter's slot is reached through its root entry (`Psb`, `DeviceAddresses`) and the phi diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs b/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs index 14beb86b9..88f397330 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs @@ -633,7 +633,7 @@ fn a_heap_decode_s_note_holds_where_its_command_can_name_a_raw_texture() { }; assert!( (p.stage) - .precision_notes_under(&SpecializationKey::new()) + .precision_notes_bound(&SpecializationKey::new(), &|_| None) .contains(¬e), "{stem}: {:?}", p.stage.precision_notes diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/targets.rs b/crates/metal2vulkan/src/tests/engine_extended_range/targets.rs index 3fa54d54d..424339e0e 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/targets.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/targets.rs @@ -2,10 +2,6 @@ //! of one of Apple's extended-range formats is written as the raw texel Metal stores, and the //! attachment holds the format's raw texels. //! -//! - On the CPU interpreter, the raw texel `ExtendedRange::clear_texel` gives a clear color (the -//! runtime's clear value) is the texel the shader's encode stores for the same `half` values, -//! over a grid of `half`s from below the format's range to past it, and NaN, the infinities and -//! the largest finite `half`s. //! - On every committed profile, a fragment function compiled for a pipeline with such an //! attachment (`rt6_fill_rgba32float`, `rt6_fill_rgba16float`) records the attachment //! (`StageIo::extended_range_colors`), keeps its interface variable's Metal type, declares the @@ -35,7 +31,6 @@ use super::*; use crate::error::{DescriptorError, Error, MetalAnswer, Needs, RuntimeInput}; -use crate::metal::format::ClearRoute; use crate::metal::ColorWriteMask; use crate::pipeline::descriptor::ColorAttachmentDescriptor; use crate::pipeline::link::{link, LinkInputs, RenderLinkInputs}; @@ -119,58 +114,6 @@ fn half_lane(b: u32, l: u32) -> u16 { } } -/// The `ExtendedRange::clear_texel` of `half` values is the texel the shader's encode stores -/// for them (the module docs): the runtime's clear value of a color is the kernel write's texel -/// of the color rounded to `half`, as Metal clears. -#[test] -fn clear_texels_are_the_kernel_writes_of_their_halves() { - let Some(bc) = assemble("clear texels", WRITE) else { - return; - }; - let (stem, p) = profiles().into_iter().next().expect("profile"); - // An `_sRGB` form's write takes the device's `Pow`, which the interpreter does not model (and - // its clear texel keeps Metal's table: the two may be a code apart). - for form in FORMS.into_iter().filter(|f| !f.srgb()) { - let mut inputs = LowerInputs::new(); - inputs.extended_range.insert(TARGET, form); - inputs.storage_images.insert( - TARGET, - StorageImageChoice::new(form.raw_format(), StorageImageClass::Identity), - ); - let what = format!("{form:?} on {stem}"); - let (plan, m) = - typed_module_with(&bc, "k", &p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); - validate(&bc, &inputs, &p, &what); - // Batches 0 to 3 reach every fourth pattern below 0x4400 (4.0) of either sign. - for batch in 0..4 { - let lanes = |n: u32| -> [u16; 4] { [0, 1, 2, 3].map(|c| half_lane(batch, 4 * n + c)) }; - let mut res = resources(&plan, 16, &[]); - res.buffers[0].bytes = (0..SIDE * SIDE) - .flat_map(&lanes) - .flat_map(|h| crate::float16::f16_bits_to_f32(h).to_le_bytes()) - .collect(); - let images = [image(1, |_| [0; 4])]; - let (_, images) = run(&m, &res, &images); - let target = texels_of(&images, 1); - let layout = image(1, |_| [0; 4]); - for n in 0..SIDE * SIDE { - let color = lanes(n).map(|h| f64::from(crate::float16::f16_bits_to_f32(h))); - let want = form.clear_texel(color, ClearRoute::ThroughHalf); - let at = layout - .index(0, 0, 0, [n % SIDE, n / SIDE, 0]) - .expect("texel"); - let raw = form.raw_components() as usize; - assert_eq!( - target[at][..raw], - want[..raw], - "{what}: batch {batch} texel {n} of halves {:x?}", - lanes(n) - ); - } - } - } -} - fn fixture() -> Option> { match llvm_assemble(&engine_dir().join("rt6_samples.ll")) { Ok(b) => Some(b), diff --git a/crates/metal2vulkan/src/tests/engine_graphics_binder.rs b/crates/metal2vulkan/src/tests/engine_graphics_binder.rs index c83779c42..cdba2f5cb 100644 --- a/crates/metal2vulkan/src/tests/engine_graphics_binder.rs +++ b/crates/metal2vulkan/src/tests/engine_graphics_binder.rs @@ -1014,151 +1014,6 @@ fn a_per_bind_stride_comes_from_the_bind() { assert!(pulled(max.next_multiple_of(4) + 4)); } -/// `state` with vertex-stage buffer 0 replaced by `b`. -/// A rebind of buffer slots writes over a draw's commands the commands a whole instantiation of -/// the new state writes: for each committed profile, each state of the vertex buffer and the -/// constant buffer at other offsets and over other allocations that keeps the plan's shape, the -/// commands of the first state rebound at the slots that changed are the new state's. Where the -/// rebind writes nothing (`Ok(false)`), the plan reads a slot some other way. The slot rebinds made -/// once for a plan and its slots (`slot_rebinds`) answer each of those rebinds as the whole rebind -/// does. -#[test] -fn a_rebind_of_buffer_slots_writes_what_an_instantiation_writes() { - let Some(bc) = fixture("stage_io") else { - return; - }; - let (vertex, scale) = ( - slot(Stage::Vertex, SlotClass::Buffer, 0), - slot(Stage::Vertex, SlotClass::Buffer, 1), - ); - let draw = DrawCall::Primitives { - vertex_start: 3, - vertex_count: 6, - instance_count: 2, - base_instance: 5, - }; - // The same allocation's length and offset at another address. - let elsewhere = |b: BoundBuffer| match b { - BoundBuffer::Buffer { - length, - offset, - device_address, - attribute_stride, - .. - } => BoundBuffer::Buffer { - length, - offset, - gpu_address: 0x7_0000, - device_address, - attribute_stride, - }, - other => other, - }; - let (mut rebound, mut pushed, mut whole, mut alone) = (0, 0, 0, 0); - // A rebind of the slots by the plan's rebinds of them, made once: the answer and the commands - // the whole rebind gives. - let by_rebinds = |plan: &BindingPlan, - rebinds: Option<&SlotRebinds>, - state: &BindState, - before: &DrawCommands, - whole: (&Result, &DrawCommands)| { - let mut cmds = before.clone(); - let answer = rebinds.map_or(Ok(false), |r| { - plan.rebind_draw_slots_with(r, state, &mut cmds) - }); - assert_eq!(&answer, whole.0, "the rebinds' answer"); - if answer == Ok(true) { - assert_eq!(&cmds, whole.1, "the rebinds' commands"); - } - }; - for (stem, dev) in devices() { - let Ok(p) = render_pipeline(&dev, &bc) else { - continue; - }; - // From a constant at an aligned offset, and at one a residual reaches. - for first in [render_state(16), render_state(4)] { - let Ok(plan) = p.plan(&dev, &first.shape()) else { - continue; - }; - let scales = [0, 4, 16, 20, 36, 48, 100, 240, 256]; - let vertices = [0, 24, 48, 72, 96, 2400]; - let (scale_alone, both) = ( - plan.slot_rebinds(&[scale]), - plan.slot_rebinds(&[vertex, scale]), - ); - // Made again in place, over rebinds of other slots, they are the same, and name their - // slots. - let mut again = SlotRebinds::default(); - for (slots, made) in [(&[vertex, scale][..], &both), (&[scale][..], &scale_alone)] { - let rebinds = plan.slot_rebinds_into(slots, &mut again); - assert_eq!(rebinds.then_some(&again), made.as_ref()); - assert_eq!(again.slots(), slots); - } - // The scale slot alone named, the vertex slot before it bound as before: its place - // among the bound ones taken from the plan. - for &s in &scales { - let state = render_state(s); - if state.shape() != first.shape() { - continue; - } - let before = plan.instantiate_draw(&first, &draw).expect("first draw"); - let mut cmds = before.clone(); - let answer = plan.rebind_draw_slots_into(&state, &[scale], &mut cmds); - by_rebinds( - &plan, - scale_alone.as_ref(), - &state, - &before, - (&answer, &cmds), - ); - if answer == Ok(true) { - alone += 1; - let expected = plan.instantiate_draw(&state, &draw); - assert_eq!(Ok(&cmds), expected.as_ref(), "{stem} {s}: the scale alone"); - } - } - let cases = scales - .iter() - .flat_map(|&s| vertices.iter().map(move |&v| (s, v))); - for ((s, v), moved) in cases.flat_map(|c| [(c, false), (c, true)]) { - let mut state = render_state(s); - let table = state.stages.get_mut(&Stage::Vertex).expect("vertex"); - table.buffers.insert(0, buffer(24 * 64 + v, v, None)); - if moved { - let b = table.buffers.get(&1).copied().expect("scale"); - table.buffers.insert(1, elsewhere(b)); - } - if state.shape() != first.shape() { - continue; - } - let before = plan.instantiate_draw(&first, &draw).expect("first draw"); - let expected = plan.instantiate_draw(&state, &draw); - let mut cmds = before.clone(); - let answer = plan.rebind_draw_slots_into(&state, &[vertex, scale], &mut cmds); - by_rebinds(&plan, both.as_ref(), &state, &before, (&answer, &cmds)); - match answer { - Ok(true) => { - rebound += 1; - pushed += usize::from(cmds.push_constants != before.push_constants); - assert_eq!(Ok(&cmds), expected.as_ref(), "{stem} {s} {v} {moved}"); - } - Ok(false) => whole += 1, - Err(e) => assert_eq!(Err(e), expected, "{stem} {s} {v} {moved}"), - } - } - } - } - assert!( - rebound > 0, - "no rebind wrote commands ({whole} instantiated whole)" - ); - assert!( - pushed > 0, - "no rebind wrote a push field ({rebound} rebound)" - ); - assert!(alone > 0, "no rebind of the scale slot alone"); -} - fn with_vertex_buffer(state: &BindState, b: BoundBuffer) -> BindState { let mut s = state.clone(); s.stages @@ -1620,7 +1475,6 @@ fn sampled_textures_and_runtime_samplers() { SamplerSource::Neutral(NeutralResource::Sampler { compare: false }), ) => { assert_eq!(view_type, vk::ImageViewType::TYPE_2D, "{stem}"); - assert!(dev.neutral_kinds().contains(&n), "{stem}: {n:?}"); } other => panic!("{stem}: {other:?}"), } diff --git a/crates/metal2vulkan/src/tests/engine_half_storage_notes.rs b/crates/metal2vulkan/src/tests/engine_half_storage_notes.rs index cd24c23c9..174f7767f 100644 --- a/crates/metal2vulkan/src/tests/engine_half_storage_notes.rs +++ b/crates/metal2vulkan/src/tests/engine_half_storage_notes.rs @@ -112,109 +112,3 @@ fn state(pf: PixelFormat, buffer: bool) -> BindState { s.stages.insert(Stage::Kernel, t); s } - -/// Whether the runtime announces `note` of `stage` at a dispatch that binds a texture of `pf` at -/// [`SLOT`]: a note no specialization removes, or a specialized one with a clause of the bound -/// formats that holds of `pf`'s class. -fn announced(stage: &StageModule, note: PrecisionNote, pf: PixelFormat) -> bool { - if !stage.precision_notes.contains(¬e) { - return false; - } - let Some(s) = stage.specialized_notes.iter().find(|s| s.note == note) else { - return true; - }; - assert!( - s.when.iter().all(|c| c.tests_bound_formats()), - "{note:?}: {:?}", - s.when - ); - let class = |slot: SlotRef| { - assert_eq!(slot, SLOT); - Some(bound_texel_format(pf)) - }; - !stage.bound_format_clauses(note, &class).is_empty() -} - -/// On every committed profile that compiles the kernels without a storage format, each form's -/// dispatch with a half-float, `RG11B10Float`, `RGBA32Float` or `RGBA8Unorm` texture bound runs the -/// variant the binder plans for it, whose module records the write's notes, or requires the -/// properties, as the module docs say, under the format bound there; the module of no storage -/// choice notes the NaN of exactly the half-float and small-float formats. Without a note under the -/// bound format, the dispatch of a half-float texture on lavapipe announced no -/// `device-nan-encoding` though the device stores `0xffc00000` as `0xfe00`, where Metal stores -/// `0x7e00`. -#[test] -fn a_float_write_notes_the_device_s_half_conversion_under_the_bound_format() { - let Some(bc) = fixture() else { - return; - }; - let mut noted = 0; - for (stem, desc) in committed_descriptions().expect("profiles") { - let dev = Device::from_queries(desc.clone(), DevicePolicy::default()).expect("device"); - for (entry, buffer) in [ - ("hsw_write", false), - ("hsw_read_write", false), - ("hsw_buffer", true), - ] { - let Some(plain) = pipeline(&dev, &bc, entry, &LoweringInputs::new()) else { - continue; - }; - let formats = HALVES.into_iter().chain([ - PixelFormat::RG11B10Float, - PixelFormat::RGBA32Float, - PixelFormat::RGBA8Unorm, - ]); - for pf in formats { - let what = format!("{entry} of {pf:?} on {stem}"); - // A format the device does not write so is refused by the plan. - let Ok(plan) = plain.plan(&dev, &state(pf, buffer).shape()) else { - continue; - }; - let key = plan.variant.lowering_inputs(Stage::Kernel); - let variant = pipeline(&dev, &bc, entry, &key).expect("the variant's inputs"); - let stage = &variant.stage; - let relied = &variant.requirements.properties; - let nan = announced(stage, PrecisionNote::DeviceNanEncoding, pf); - for property in [ - VkProperty::MetalHalfStorageNans, - VkProperty::MetalHalfStorageWrites, - VkProperty::MetalSmallFloatNans, - ] { - assert!(!relied.contains(&property), "{what}: {property:?}"); - } - if HALVES.contains(&pf) { - assert!(nan, "{what}: {:?}", stage.specialized_notes); - assert!( - announced(stage, PrecisionNote::DeviceColorConversion, pf), - "{what}: {:?}", - stage.precision_notes - ); - noted += 1; - continue; - } - // Metal stores a small float's every NaN as its canonical one, and RADV and - // NVIDIA keep another's payload bits; a 32-bit float or normalized channel takes - // no half's NaN. - let small = pf == PixelFormat::RG11B10Float; - assert_eq!(nan, small, "{what}: {:?}", stage.specialized_notes); - } - // The module of no storage choice serves every format the device writes without one: - // its NaN note holds of the half-float classes (where the device's NaN is not Metal's) - // and the small floats' alone. - for &pf in PixelFormat::ALL { - use PixelFormat as P; - let half = matches!( - pf, - P::R16Float | P::RG16Float | P::RGBA16Float | P::RGBX16Float - ); - let small = matches!(pf, P::RG11B10Float | P::RGB9E5Float); - assert_eq!( - announced(&plain.stage, PrecisionNote::DeviceNanEncoding, pf), - half || small, - "{entry} without a storage choice, bound as {pf:?}, on {stem}" - ); - } - } - } - assert!(noted > 0, "no half-float write noted"); -} diff --git a/crates/metal2vulkan/src/tests/engine_mesh.rs b/crates/metal2vulkan/src/tests/engine_mesh.rs index 2be2de73b..4b109a12a 100644 --- a/crates/metal2vulkan/src/tests/engine_mesh.rs +++ b/crates/metal2vulkan/src/tests/engine_mesh.rs @@ -1932,8 +1932,7 @@ fn a_mesh_pipeline_answers_metals_mesh_queries_within_the_device() { for (stem, p) in mesh_profiles().into_iter().chain(emulating_profiles()) { let dev = device(&stem); let l = &p.fields().limits; - let emulated = p.emulates_mesh_shading(); - assert_eq!(emulated, crate::lower::mesh::emulates(&p), "{stem}"); + let emulated = crate::lower::mesh::emulates(&p); let (object, mesh, total) = match emulated { true => ( l.max_compute_work_group_invocations, @@ -2364,7 +2363,7 @@ fn the_descriptors_payload_length_sizes_both_stages_payloads() { let budget = Budget::standard(); for (stem, p) in mesh_profiles().into_iter().chain(emulating_profiles()) { let dev = device(&stem); - let emulated = p.emulates_mesh_shading(); + let emulated = crate::lower::mesh::emulates(&p); let mut d = MeshPipelineDescriptor::new(StageSource::Function(function("mesh_outputs_triangles"))); d.object = Some(StageSource::Function(function("mesh_outputs_object"))); diff --git a/crates/metal2vulkan/src/tests/engine_recursion.rs b/crates/metal2vulkan/src/tests/engine_recursion.rs index 80ffd0d84..dc1f25d05 100644 --- a/crates/metal2vulkan/src/tests/engine_recursion.rs +++ b/crates/metal2vulkan/src/tests/engine_recursion.rs @@ -1044,10 +1044,15 @@ fn a_tile_function_recurses_under_its_pipeline_s_depth() { d.max_call_stack_depth = k; d }; - let key = |k| dev.tile_pipeline_key(&descriptor(StageSource::Function(t.clone()), k)); + let b = Budget::standard(); + let key = |k| { + let d = descriptor(StageSource::Function(t.clone()), k); + dev.compile_tile_pipeline(&d, &b) + .unwrap_or_else(|e| panic!("the tile pipeline at {k}: {e}")) + .key + }; assert_eq!(key(0), key(1)); assert_ne!(key(1), key(8)); - let b = Budget::standard(); dev.compile_tile_pipeline(&descriptor(StageSource::Function(t.clone()), 8), &b) .unwrap_or_else(|e| panic!("the tile pipeline at 8: {e}")); let inputs = LowerInputs { diff --git a/crates/metal2vulkan/src/tests/engine_srgb_decode.rs b/crates/metal2vulkan/src/tests/engine_srgb_decode.rs index 5d205182a..675fa3211 100644 --- a/crates/metal2vulkan/src/tests/engine_srgb_decode.rs +++ b/crates/metal2vulkan/src/tests/engine_srgb_decode.rs @@ -29,7 +29,7 @@ use crate::metal::texel_format::srgb_twin_on; use crate::metal::{self, PixelFormat, TextureType}; use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef}; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{SlotClass, SlotRef, Stage}; +use crate::pipeline::sym::{SlotClass, SlotRef, SpecKey, Stage}; use crate::pipeline::testing::{ link_and_validate, llvm_assemble, meter, profile, typed_module_with, AssembleError, }; @@ -428,11 +428,13 @@ fn bound_note(specialized: &[SpecializedNote], pf: PixelFormat) -> bool { .filter(|s| s.note == PrecisionNote::SrgbTexelDecode) .flat_map(|s| &s.when) .any(|c| { - c.tests_bound_formats() - && c.holds_of_bound(&|slot| { + c.all.iter().all(|t| match t.key { + SpecKey::BoundTexelFormat(slot) => { assert_eq!(slot, TEXTURE); - Some(bound_texel_format(pf)) - }) + (bound_texel_format(pf) & t.mask == t.bits) == t.equal + } + _ => false, + }) }) } @@ -698,16 +700,6 @@ fn slot_views(plan: &crate::bind::BindingPlan, slot: SlotRef) -> Vec bool { - !p.stage - .bound_format_clauses(PrecisionNote::SrgbTexelDecode, &|_| { - Some(bound_texel_format(pf)) - }) - .is_empty() -} - /// A slot bound in an 8-bit sRGB format joins the plan's variant exactly where the device holds /// the format as its UNORM twin (`metal::texel_format::srgb_twin_on`), from the device's format /// features alone. Where the device samples the format the slot joins nothing, every binding of @@ -733,7 +725,6 @@ fn a_slot_bound_in_srgb_joins_the_variant_only_where_the_device_holds_its_twin() }; for (stem, dev) in devices() { let plain = pipeline(&dev, &bc, &inputs(false)); - assert!(!notes_bound(&plain, PixelFormat::RGBA8Unorm), "{stem}"); for pf in [ PixelFormat::RGBA8UnormSRGB, PixelFormat::BGRA8UnormSRGB, @@ -769,7 +760,6 @@ fn a_slot_bound_in_srgb_joins_the_variant_only_where_the_device_holds_its_twin() "{what}" ); } - assert!(notes_bound(&plain, pf), "{what}"); decoded += 1; continue; } @@ -795,7 +785,6 @@ fn a_slot_bound_in_srgb_joins_the_variant_only_where_the_device_holds_its_twin() .contains(&PrecisionNote::SrgbTexelDecode), "{what}" ); - assert!(!notes_bound(&variant, pf), "{what}"); let a = compile_bitcode( &bc, EntryRef::Name("k"), @@ -865,7 +854,6 @@ fn an_astc_srgb_slot_samples_the_devices_decode() { } else { native += 1; } - assert!(notes_bound(&plain, pf), "{what}"); } } assert!(decoded > 0, "no committed profile holds an ASTC sRGB twin"); @@ -904,7 +892,9 @@ fn the_device_s_srgb_decode_converts_to_half_noted() { for pf in [PixelFormat::RGBA8UnormSRGB, PixelFormat::BGRA8UnormSRGB] { let plan = p.plan(&dev, &state(Some(pf)).shape()).expect("plan"); assert!(plan.variant.srgb_textures.is_empty(), "{stem} {pf:?}"); - let notes = p.stage.precision_notes_under(&plan.specialization); + let notes = p + .stage + .precision_notes_bound(&plan.specialization, &|_| None); assert!( notes.contains(&PrecisionNote::HalfTexelConversion), "{stem} {pf:?}: {notes:?}" diff --git a/crates/metal2vulkan/src/tests/engine_texture.rs b/crates/metal2vulkan/src/tests/engine_texture.rs index fb51e83a0..424a25922 100644 --- a/crates/metal2vulkan/src/tests/engine_texture.rs +++ b/crates/metal2vulkan/src/tests/engine_texture.rs @@ -375,16 +375,18 @@ fn a_half_texel_read_notes_the_device_nan_encoding_where_the_bound_format_may_ho let when = &entries[0].when; assert_eq!(when.len(), 1, "{stem}: {when:?}"); for clause in when { - assert!(clause.tests_bound_formats(), "{stem}: {clause:?}"); for test in &clause.all { assert_eq!(test.key, SpecKey::BoundTexelFormat(texture_slot(2))); } } let holds = |pf: Option| { when.iter().any(|clause| { - clause.holds_of_bound(&|slot| { - assert_eq!(slot, texture_slot(2)); - pf.map(bound_texel_format) + clause.all.iter().all(|t| match (t.key, pf) { + (SpecKey::BoundTexelFormat(slot), Some(pf)) => { + assert_eq!(slot, texture_slot(2)); + (bound_texel_format(pf) & t.mask == t.bits) == t.equal + } + _ => true, }) }) }; diff --git a/crates/metal2vulkan/src/tests/engine_texture_levels.rs b/crates/metal2vulkan/src/tests/engine_texture_levels.rs index ec189755e..09e2030ca 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_levels.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_levels.rs @@ -1763,82 +1763,11 @@ fn pushed_levels(plan: &BindingPlan, s: &BindState) -> u32 { u32::from_le_bytes(w.bytes[i..i + 4].try_into().expect("u32")) } -/// A plan's key keeps a bound texture's level count only at a slot whose levels the pipeline -/// reads (`StorageTextureLevels` or `StorageTextureLevelViews`): a texture another slot samples, -/// and a used texture (a heap array views level 0 alone), key one level, and a shape with nothing -/// to project is borrowed. -#[test] -fn a_plan_s_key_keeps_levels_only_where_the_pipeline_reads_them() { - use crate::bind::{TextureShape, UsedClass, UsedShape}; - use crate::pipeline::artifact::RuntimeDependency; - use crate::pipeline::facts::Mechanism; - use std::borrow::Cow; - - let levels = |shape: &TextureShape| match shape { - TextureShape::Texture { - mipmap_level_count, .. - } => *mipmap_level_count, - other => panic!("{other:?}"), - }; - let texture = |n: u32| { - let mut facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA16Float); - facts.usage = TextureUsage::SHADER_READ; - facts.mipmap_level_count = n; - facts - }; - let mut s = state(Some(3)); - let table = s.stages.get_mut(&Stage::Kernel).expect("kernel table"); - table.textures.insert( - 1, - BoundTexture::Texture { - facts: texture(5), - resource_id: None, - }, - ); - let mut shape = s.shape(); - shape.used.insert( - 7, - UsedShape { - class: UsedClass::Texture(texture(4).shape()), - usage: crate::metal::ResourceUsage::empty(), - stages: crate::metal::RenderStages::empty(), - }, - ); - let at = |shape: &crate::bind::BindShape, index: u32| { - levels(&shape.stages[&Stage::Kernel].textures[&index]) - }; - let used = |shape: &crate::bind::BindShape| match &shape.used[&7].class { - UsedClass::Texture(t) => levels(t), - other => panic!("{other:?}"), - }; - assert_eq!((at(&shape, 0), at(&shape, 1), used(&shape)), (3, 5, 4)); - - for fact in [ - RuntimeFact::StorageTextureLevels { slot: tslot(0) }, - RuntimeFact::StorageTextureLevelViews { slot: tslot(0) }, - ] { - let deps = [RuntimeDependency::new(fact, Mechanism::PushConstant)]; - let key = shape.for_plan(&deps); - assert!(matches!(key, Cow::Owned(_)), "{fact:?}"); - assert_eq!( - (at(&key, 0), at(&key, 1), used(&key)), - (3, 1, 1), - "{fact:?}" - ); - assert_eq!(key.for_plan(&deps), Cow::Borrowed(key.as_ref()), "{fact:?}"); - } - let key = shape.for_plan(&[]); - assert_eq!((at(&key, 0), at(&key, 1), used(&key)), (1, 1, 1)); - let one = state(Some(1)).shape(); - assert!(matches!(one.for_plan(&[]), Cow::Borrowed(_))); -} - /// A level slot binds a texture of any usage at its levels: plain Metal writes a texture made /// without `ShaderWrite` at every level, through every write form, as one made with it /// (CoreAnimation's blur textures are `ShaderRead | RenderTarget | BlockWritesOnly`), /// where the binder bound the neutral there and dropped the writes. Its shape states its levels -/// whatever the usage, and the plan's key (`BindShape::for_plan`) keeps them only where the -/// pipeline reads them. A texture with more levels than the views hold is larger than the device's +/// whatever the usage. A texture with more levels than the views hold is larger than the device's /// largest 2D image: refused, naming `maxImageDimension2D`. #[test] fn level_slots_bind_textures_of_every_usage_the_device_can_hold() { @@ -1873,16 +1802,6 @@ fn level_slots_bind_textures_of_every_usage_the_device_can_hold() { let what = format!("{usage:?}"); let (three, one) = (with_usage(Some(3), usage), with_usage(Some(1), usage)); assert_ne!(three.shape(), one.shape(), "{what}"); - assert_ne!( - three.shape().for_plan(&pipe.dependencies), - one.shape().for_plan(&pipe.dependencies), - "{what}: the pipeline reads the slot's levels" - ); - assert_eq!( - three.shape().for_plan(&[]), - one.shape().for_plan(&[]), - "{what}: a pipeline that reads no levels" - ); let plan = pipe.plan(&dev, &three.shape()).expect("plan"); let writes: Vec<_> = plan diff --git a/crates/metal2vulkan/src/tests/engine_tile.rs b/crates/metal2vulkan/src/tests/engine_tile.rs index 26a44694e..2e1921775 100644 --- a/crates/metal2vulkan/src/tests/engine_tile.rs +++ b/crates/metal2vulkan/src/tests/engine_tile.rs @@ -976,7 +976,6 @@ fn a_tile_pipeline_binds_its_attachments() { let pipe = dev .compile_tile_pipeline(&d, &Budget::standard()) .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(pipe.key, dev.tile_pipeline_key(&d), "{stem}"); assert!(pipe .dependencies .iter() @@ -1133,6 +1132,7 @@ fn a_tile_pipeline_binds_its_attachments() { // The descriptor's limit lowers it, never raises it, and is part of the key; Metal's 0 is // no limit. A limit answers the most threads of a threadgroup of even sides within it, as // Metal's does (on an M3 Max and an M4: 1000 answers 960, 255 252, 3 none). + let unlimited = pipe.key; for (limit, metal) in [ (Some(64), 64), (Some(1024), 1024), @@ -1155,7 +1155,7 @@ fn a_tile_pipeline_binds_its_attachments() { pipe.metal_info.metal_max_total_threads_per_threadgroup, metal, "{stem} {limit:?}: Metal's own" ); - assert_ne!(dev.tile_pipeline_key(&limited), dev.tile_pipeline_key(&d)); + assert_ne!(pipe.key, unlimited, "{stem} {limit:?}"); } } } diff --git a/crates/metal2vulkan/src/tests/engine_viewport_compensation.rs b/crates/metal2vulkan/src/tests/engine_viewport_compensation.rs index 78d69ccdc..936f0d9b7 100644 --- a/crates/metal2vulkan/src/tests/engine_viewport_compensation.rs +++ b/crates/metal2vulkan/src/tests/engine_viewport_compensation.rs @@ -450,10 +450,12 @@ fn a_compensated_draw_runs_its_variant_with_the_states_values() { let clamp = [-0.5f32, 1.25]; let state = BindState { viewport_compensation: Some( - CompensatedViewport::new(compensation, values) - .with_guard(guard) - .with_mirrors(bits) - .with_vertex_clamp(clamp), + CompensatedViewport { + guard, + ..CompensatedViewport::new(compensation, values) + } + .with_mirrors(bits) + .with_vertex_clamp(clamp), ), ..Default::default() }; diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 47a99e25a..37f5a63c2 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -187,7 +187,6 @@ surface! { enum VerifyError N; enum Error N; enum Retry N; - enum Permanence N; struct Unsupported N; enum Needs N; enum RuntimeDriverDefect N; @@ -949,9 +948,7 @@ surface! { enum ExtendedRange N; enum WordAttachment N; struct WordField E; - enum ClearRoute N; fn vk_format; - fn swizzle_over; fn direct_format; fn byte_format; fn srgb_raw_twin; @@ -964,7 +961,6 @@ surface! { fn copies_only; fn imageblock_sample_length; fn color_record; - fn explicit_imageblock_sample_length; fn aspects; fn is_depth_stencil; fn sampled_type;