diff --git a/crates/metal2vulkan-harness/src/rt.rs b/crates/metal2vulkan-harness/src/rt.rs index ed14a8161..3a56b06d8 100644 --- a/crates/metal2vulkan-harness/src/rt.rs +++ b/crates/metal2vulkan-harness/src/rt.rs @@ -207,6 +207,28 @@ impl Device { "every {class:?} index is in use" )))) } + + /// The indices of a pipeline state's numbered samplers: a constexpr sampler takes the index + /// its state words took first; a read's or a write's sampler takes nothing at its index. + fn sampler_ids( + &self, + samplers: &[rt::NumberedSampler], + ) -> std::result::Result, rt::Error> { + let mut indices = self.indices.borrow_mut(); + let ids = samplers.iter().map(|sampler| match sampler { + rt::NumberedSampler::Constexpr(words) => match indices.constexprs.get(words) { + Some(&index) => index, + None => { + let index = indices.next(rt::IndexClass::Sampler, indices.sampler); + indices.sampler = index; + indices.constexprs.insert(*words, index); + index + } + }, + _ => 0, + }); + Ok(ids.collect()) + } } /// `MTLBuffer`: the runtime's buffer, and its place, freed when it is dropped. @@ -459,26 +481,8 @@ impl crate::ComputeDevice for Device { ) -> Result { let function = plan::with_private(function.clone(), private); let descriptor = rt::ComputePipelineDescriptor::new(rt::StageSource::Function(function)); - // A constexpr sampler takes the index its state words took first; a read's or a write's - // sampler takes nothing at its index. - let sampler_ids = |samplers: &[rt::NumberedSampler]| { - let mut indices = self.indices.borrow_mut(); - let ids = samplers.iter().map(|sampler| match sampler { - rt::NumberedSampler::Constexpr(words) => match indices.constexprs.get(words) { - Some(&index) => index, - None => { - let index = indices.next(rt::IndexClass::Sampler, indices.sampler); - indices.sampler = index; - indices.constexprs.insert(*words, index); - index - } - }, - _ => 0, - }); - Ok(ids.collect()) - }; (self.device) - .new_compute_pipeline_state(&descriptor, sampler_ids) + .new_compute_pipeline_state(&descriptor, |samplers| self.sampler_ids(samplers)) .map_err(error) } @@ -493,7 +497,7 @@ impl crate::ComputeDevice for Device { descriptor.fragment = Some(rt::StageSource::Function(fragment.clone())); descriptor.color_attachments[0] = Some(rt::ColorAttachmentDescriptor::new(color)); (self.device) - .new_render_pipeline_state(&descriptor) + .new_render_pipeline_state(&descriptor, |samplers| self.sampler_ids(samplers)) .map_err(error) } diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 97f3a8552..23ac59a84 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -1064,11 +1064,16 @@ With no directory, nothing is kept on disk, and each `VkPipeline` is made withou ## Render pipeline states -- `Device::new_render_pipeline_state(&RenderPipelineDescriptor)` is +- `Device::new_render_pipeline_state(&RenderPipelineDescriptor, sampler_ids)` is `newRenderPipelineStateWithDescriptor:error:` without reflection. The translator lowers the vertex and fragment functions on the calling thread, which waits for them, within its 20-second budget per lowering, for what device creation enabled and under its identity domains, as for a compute state. A refusal of the translator is `Error::Translation`. +- A state numbers its functions' samplers as a compute state numbers its kernel's: + `sampler_ids` takes the vertex function's, then the fragment function's, each in Metal's order, + and answers the index the consumer gives each. Each constexpr sampler a function samples + through takes its device samplers at its index before the call returns, and each draw pushes + the index. - What a state compiles is its content, never the state: its descriptor, with its functions' constant values and linked functions, and every field (the translator's `Device::queried_render_descriptor_key`). Every state of one content shares one compiled content: its @@ -1086,27 +1091,30 @@ With no directory, nothing is kept on disk, and each `VkPipeline` is made withou `Error::Translation` with `maxPushConstantsSize`'s limit; no pair in the replay streams comes near it (the most is 248 bytes). - A `VkPipeline` bakes what Vulkan 1.3 cannot leave dynamic: the content and the topology class - (point, line or triangle) of the draws it serves. It takes as dynamic state the viewport, - scissor, cull mode, front face, primitive topology within its class, primitive restart, depth - test, write and compare, stencil test, operations, masks and reference, depth bias, blend - constants and vertex buffer strides. It renders dynamically into its attachments' formats, with - no render pass. + (line or triangle) of the draws it serves. It takes as dynamic state the viewport, scissor, cull + mode, front face, primitive topology within its class, primitive restart, depth test, write and + compare, stencil test, operations, masks and reference, depth bias and blend constants. Vertex + buffer strides are the descriptor's, so the content's, and baked. It renders dynamically into + its attachments' formats, with no render pass. - The triangle class's `VkPipeline` is made with the state, through its file in the cache - directory where there is one; a point or line class's comes with the draws. Of the two replay - streams' 537 render contents drawn, 527 draw only triangles and 2 lines and triangles; a content - drawn only as points or lines (8 of them) makes a triangle `VkPipeline` it never uses. + directory where there is one; the line class's is made by the content's first draw of lines, + which waits for it (`Metrics::first_use_waits`). Of the two replay streams' 537 render contents + drawn, 527 draw only triangles and 2 lines and triangles; a content drawn only as lines (8 of + them) makes a triangle `VkPipeline` it never uses. ### Known gaps of render pipeline states -- There is no draw yet: a render encoder renders its pass's load and store actions alone, and a - state holds its triangle class's `VkPipeline`, which nothing draws with. - Refused at creation by `Gap::RenderPipeline`, naming its `RenderPipelineKind`: a depth attachment, more than one sample, vertex amplification, a post-tessellation vertex function, stages the translator synthesizes beside the functions', framebuffer fetch, an imageblock, a - fragment function's stencil output, alpha to one, an instance step rate above 1, samplers the - state numbers (a constexpr sampler, or a texture read or write's), constant data the binder - supplies, a specialization other than the sample and amplification counts, dynamic state beyond - Vulkan 1.3's, and a feature or extension device creation does not enable. A state for indirect + fragment function's stencil output, alpha to one, an instance step rate above 1, constant data + the binder supplies, a specialization other than the sample and amplification counts, dynamic + state beyond Vulkan 1.3's (a vertex buffer layout whose stride is set per bind among it), a + feature or extension device creation does not enable, and a function that reads what a draw + does not supply (`DrawInput`: a function table, a table the binder builds, a parameter block + past the push range, a push field or bind-time fact the encoder does not fill, an unnormalized + constexpr sampler). Of the replay streams' contents that translate, every one reads only its + slots' addresses, resource IDs and constexpr sampler indices. A state for indirect command buffers is `Gap::IndirectCommandBuffers`. The `completionHandler:` forms are not built. - Metal's triangle fill mode and depth clip mode, which Vulkan 1.3 bakes into a `VkPipeline`, are their defaults. @@ -1124,9 +1132,10 @@ With no directory, nothing is kept on disk, and each `VkPipeline` is made withou array, a cube or a cube array, of one sample and `RenderTarget` usage. The texture keeps an image view of that level and layer with the identity swizzle, made at the first pass that renders into it and freed with the texture (`Gauges::attachment_views`). -- Load and store actions are one to one: `Load`, `Clear` and `DontCare` are Vulkan's load - operations of those names, `Store` and `DontCare` its store operations. A `DontCare` store - leaves the attachment's texels undefined, as Metal's does. A clear color is a `float` in a +- Load actions are one to one: `Load`, `Clear` and `DontCare` are Vulkan's load operations of + those names. Both store actions store: a pass may end its rendering before the encoder ends and + begin it again, loading what it stored (below), so a `DontCare` store keeps the texels, one of + the outcomes Metal allows. A clear color is a `float` in a float, normalized or sRGB channel, which the device converts to the format by its own rules (Vulkan clamps a normalized value and asks for rounding to nearest; Metal rounds to nearest even); an integer channel's is truncated toward zero and saturated to the channel's width, NaN @@ -1147,11 +1156,53 @@ With no directory, nothing is kept on disk, and each `VkPipeline` is made withou attachment of a format without stencil (`Refusal::AttachmentFormat`). A pass whose color attachments reach past the device's `maxColorAttachments` is `Limit::ColorAttachments`. A refused descriptor leaves the command buffer open for another encoder. +- An encoder holds Metal's render state: a pipeline state, the vertex and fragment functions' + buffers (`set_vertex_buffer`, `set_vertex_bytes` and their offsets, the fragment's alike), + textures and sampler states, one viewport and scissor rectangle, the cull mode, the + front-facing winding, a depth-stencil state (`Device::new_depth_stencil_state`), the stencil + references and the blend color, Metal's defaults where it set none. A vertex buffer slot serves + the vertex function's buffer argument of its index and the vertex descriptor's layout of its + index alike, a `set_vertex_bytes` copy too, read through the parameter ring's buffer. +- `draw_primitives` and `draw_indexed_primitives` are one `vkCmdDraw` or `vkCmdDrawIndexed` each. + A draw pushes its functions' fields in the one push range (the addresses of their buffer slots + plus offsets, the resource IDs of their textures and sampler states, the state's constexpr + sampler indices), binds the vertex buffers its vertex descriptor reads and the index buffer, + and sets the dynamic state that changed since the encoder's last draw: all of it at the first. + A draw takes no barrier, as Metal orders none between the draws of one encoder, so a pass of + any number of draws is still its two barriers. A draw of no vertices, indices or instances + records nothing. +- A viewport is Vulkan's with its height negated (from `y + height`): framebuffer rows, the + fragment position and derivatives follow Metal's clip space, whose y points up, and Metal's + front-facing winding is Vulkan's front face of the same name. A viewport of no width or height, + or with a NaN origin x, draws nothing, as Metal's. Metal clips a draw to the pixels its viewport + covers, so the scissor is Metal's rectangle cut to them; a rectangle past the render area, + which Metal's validation stops, is cut to it, as plain Metal cuts it. A stencil reference + saturates at 255, as Metal stores it. +- `memory_barrier` after a draw of the encoder that wrote memory ends the rendering, records one + barrier and begins the rendering again, loading what it stored; after none it records nothing, + as the pass's first barrier ordered everything before it. A draw that needs a copy first, of a + texture over a buffer in an image of its own or over a Managed buffer's device copy, records it + the same way, between the rendering's end and its new beginning. Fences record nothing, as in a + compute encoder. +- Refused, as Metal's validation stops them: a draw with no pipeline state + (`Refusal::NoPipeline`), a vertex buffer the vertex descriptor reads that is not bound + (`Refusal::NoBufferAtIndex`) or bound at an offset past its length + (`Refusal::VertexBufferOffset`), an index offset that is not a multiple of the index size or + indices past the buffer (`Refusal::IndexBufferOffset`), a viewport field NaN or infinite but its + origin's x (`Refusal::ViewportNotFinite`), and a stencil test in a pass without a stencil + attachment (`Refusal::StencilAttachment`). ### Known gaps of render encoders -- Every encoder call but `end_encoding` is not built yet: a pass renders its load and store - actions alone. +- Refused by `Gap::Draw`, naming its `DrawKind`: a draw of points, a depth-stencil state that + tests or writes depth (no pass has a depth attachment yet), a viewport Vulkan's is not (a + negative width, a depth range past `[0, 1]`, bounds past the device's viewport limits), a + pipeline state whose formats are not the pass's attachments', and a draw that binds a texture + whose image the pass renders into. The replay streams draw lines and triangles under + depth-stencil states that test no depth. +- Not built, and so not methods: indirect draws, several viewports or scissor rectangles, the + triangle fill mode, the depth clip mode, depth bias, visibility results, `useResource:`, the + store action setters, tile functions and `setVertexBuffer:offset:attributeStride:atIndex:`. - Refused by `Gap::RenderPass`, naming its `RenderPassKind`: a depth attachment, an attachment of more than one sample, a resolve, a 1D or 3D texture's attachment, the `Unknown` and `CustomSampleDepthStore` store actions, a clear of a format only a shader clears (extended diff --git a/crates/metal2vulkan-rt/src/command.rs b/crates/metal2vulkan-rt/src/command.rs index 5e53a7a43..7884ab25b 100644 --- a/crates/metal2vulkan-rt/src/command.rs +++ b/crates/metal2vulkan-rt/src/command.rs @@ -14,7 +14,8 @@ use crate::pipeline::ComputePipelineState; use crate::queue::QueueInner; use crate::readback; use crate::record::{self, Reach, Recorder}; -use crate::ring::Writes; +use crate::render::RenderPipelineState; +use crate::ring::{Placed, Writes}; use crate::sampler::SamplerState; use crate::texture::{Image, OverCopy, Texture}; use crate::times::{self, Stamps, Times}; @@ -137,8 +138,10 @@ pub(crate) struct Building { /// between dispatches leaves them out unless the dispatch after it is indirect, so an /// indirect dispatch after such a write needs one that reaches them. args_unordered: bool, - /// The pipeline bound in the current segment's command buffer. + /// The compute pipeline bound in the current segment's command buffer. bound: Option, + /// The graphics pipeline bound in the current segment's command buffer. + drawn: Option, /// The current segment wrote memory the host may read: its end barrier reaches the host. host_written: bool, } @@ -155,6 +158,7 @@ pub(crate) struct Gpu { pub(crate) copies: Vec>, /// The pipeline states the commands use, once each, kept until the command buffer retires. pub(crate) pipelines: Vec, + pub(crate) render_pipelines: Vec, /// The textures and sampler states the encoders bound or declared, once each, kept until the /// command buffer retires: their elements of set 1 stay theirs while work may read them. pub(crate) textures: Vec, @@ -258,6 +262,7 @@ impl CommandBuffer { blocks: Vec::new(), copies: Vec::new(), pipelines: Vec::new(), + render_pipelines: Vec::new(), textures: Vec::new(), samplers: Vec::new(), ring: Writes::default(), @@ -273,6 +278,7 @@ impl CommandBuffer { owed: false, args_unordered: false, bound: None, + drawn: None, host_written: false, }), ended: None, @@ -648,6 +654,7 @@ impl Building { } self.last().command = Some(command); self.bound = None; + self.drawn = None; Ok(command) } @@ -803,20 +810,36 @@ impl Building { } } - /// Whether the current command buffer has no pipeline bound yet. + /// Whether the current command buffer has no compute pipeline bound yet. pub(crate) fn unbound(&self) -> bool { self.bound.is_none() } - /// Whether `pipeline` needs binding in the current command buffer; it is bound from now. + /// Whether the compute pipeline `pipeline` needs binding in the current command buffer; it is + /// bound from now. pub(crate) fn bind(&mut self, pipeline: vk::Pipeline) -> bool { let needed = self.bound != Some(pipeline); self.bound = Some(pipeline); needed } + /// Whether the graphics pipeline `pipeline` needs binding in the current command buffer, and + /// whether it is the command buffer's first, before which set 1 is bound at the graphics bind + /// point; it is bound from now. + pub(crate) fn bind_graphics(&mut self, pipeline: vk::Pipeline) -> (bool, bool) { + let first = self.drawn.is_none(); + let needed = self.drawn != Some(pipeline); + self.drawn = Some(pipeline); + (needed, first) + } + /// Copies `bytes` into the parameter ring, returning their address. pub(crate) fn write_ring(&mut self, bytes: &[u8]) -> Result { + Ok(self.write_ring_placed(bytes)?.address) + } + + /// Copies `bytes` into the parameter ring, returning where they lie. + pub(crate) fn write_ring_placed(&mut self, bytes: &[u8]) -> Result { let core = Arc::clone(self.device.core()); core.counters.count(Metric::RingWrites); self.gpu.ring.write(&core, bytes) @@ -851,6 +874,14 @@ impl Building { } } + /// Keeps `state` until the command buffer retires. + pub(crate) fn keep_render_pipeline(&mut self, state: &RenderPipelineState) { + let pipelines = &mut self.gpu.render_pipelines; + if !pipelines.iter().rev().any(|kept| kept.is(state)) { + pipelines.push(state.clone()); + } + } + /// Keeps `texture` until the command buffer retires. pub(crate) fn keep_texture(&mut self, texture: &Texture) { let textures = &mut self.gpu.textures; @@ -883,11 +914,30 @@ impl Building { if !self.last().signals.is_empty() { self.split()?; } + let copies = self.overs_owed(accesses, unbound); + self.record_overs(copies) + } + + /// The copies a command that makes `accesses` (by hazard id), `unbound` where it reaches + /// memory through an address outside its resources, needs first (`crate::over`), in the + /// current segment, which the caller records ([`record_overs`](Self::record_overs)): a draw's, + /// which ends its pass's rendering to record them. None while no texture over a buffer in an + /// image of its own lives. + pub(crate) fn overs_owed(&mut self, accesses: &[(u32, Access)], unbound: bool) -> over::Copies { + if !self.copies_over() { + return over::Copies::default(); + } let segments = &mut self.gpu.segments; let last = segments.len() - 1; - let copies = segments[last] + segments[last] .overs - .before(accesses, &self.gpu.textures, unbound); + .before(accesses, &self.gpu.textures, unbound) + } + + /// Records `copies`, ordered as a blit's copy is; nothing where there are none. + /// + /// Err: [`Error::Vulkan`] where the command buffer cannot record. + pub(crate) fn record_overs(&mut self, copies: over::Copies) -> Result<(), Error> { if copies.is_empty() { return Ok(()); } @@ -1052,6 +1102,7 @@ pub(crate) fn retire( blocks, copies, pipelines, + render_pipelines, textures, samplers, ring, @@ -1065,7 +1116,15 @@ pub(crate) fn retire( copy_in.retire(core); } ring.give_back(core); - drop((blocks, copies, pipelines, textures, samplers, images)); + drop(( + blocks, + copies, + pipelines, + render_pipelines, + textures, + samplers, + images, + )); times::reset( &core.device, inner.queue.stamps.pool, diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 472cd6eb4..dfa9f026c 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -465,7 +465,8 @@ pub struct Metrics { /// segment with commands and of each upload, one before a dispatch at a hazard, one owed by /// an encoder that wrote or a memory barrier call, recorded before the next command, two /// around each blit copy, fill and synchronize copy, and two around each render pass, the - /// first of each pair paying what is owed. + /// first of each pair paying what is owed, with one inside a render pass at a memory barrier + /// after a draw that wrote memory. A draw takes none. pub barriers: u64, /// Bytes the runtime copied for a call: `replace_region` and `get_bytes` staging, and the /// copies between a texture over a buffer and its image of its own @@ -482,7 +483,7 @@ pub struct Metrics { /// First-use waits: encoding calls that waited while the `VkPipeline` they needed was made, /// for a workgroup size (a threadgroup size, or the tile of an image-only kernel's grid more /// than one deep) or threadgroup memory lengths no state of the kernel's content had run with - /// before. + /// before, or for a render content's first draw of lines. pub first_use_waits: u64, /// The nanoseconds of [`host_time`](crate::host_time) the first-use waits took, in total. pub first_use_wait_nanos: u64, @@ -529,7 +530,8 @@ pub struct Metrics { /// [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir pub cache_bytes_written: u64, /// Writes into the parameter ring: a dispatch's parameter block, its fields past the push - /// window (a kernel with more than 28 buffers), and each `set_bytes` copy. + /// window (a kernel with more than 28 buffers), and each `set_bytes` copy, a render + /// encoder's too. pub ring_writes: u64, /// Calls that waited for an upload to complete before they recorded: the upload at its /// bound of calls or bytes, or the staging region with no room for a copy. diff --git a/crates/metal2vulkan-rt/src/depth_stencil.rs b/crates/metal2vulkan-rt/src/depth_stencil.rs new file mode 100644 index 000000000..a9b544922 --- /dev/null +++ b/crates/metal2vulkan-rt/src/depth_stencil.rs @@ -0,0 +1,97 @@ +//! Depth/stencil states: a descriptor's depth and stencil tests in Vulkan's terms, which a render +//! encoder sets as dynamic state before its draws. + +use crate::device::{Core, Device}; +use ash::vk; +use metal2vulkan::metal::state::{depth_stencil_state, DepthStencilDescriptor, StencilOpState}; +use std::sync::Arc; + +/// `MTLDepthStencilState`. +/// +/// A cheap handle: clones share one state. It holds no Vulkan object: a draw under it sets its +/// tests as dynamic state. +#[derive(Clone)] +pub struct DepthStencilState { + inner: Arc, +} + +struct Inner { + device: Device, + descriptor: DepthStencilDescriptor, + tests: Tests, +} + +/// A depth/stencil descriptor's tests as Vulkan's dynamic state takes them. +#[derive(Clone, Copy)] +pub(crate) struct Tests { + /// Whether the depth test compares or writes (`depth_stencil_state`). + pub(crate) depth: bool, + /// Whether the stencil test can fail or change the stencil. + pub(crate) stencil: bool, + /// The front face's and the back face's stencil operations, compare operation and masks. + pub(crate) faces: [Face; 2], +} + +/// One face's stencil state. +#[derive(Clone, Copy)] +pub(crate) struct Face { + pub(crate) fail: vk::StencilOp, + pub(crate) pass: vk::StencilOp, + pub(crate) depth_fail: vk::StencilOp, + pub(crate) compare: vk::CompareOp, + pub(crate) compare_mask: u32, + pub(crate) write_mask: u32, +} + +impl Tests { + /// The tests of `descriptor`, by the translator's mapping. + pub(crate) fn of(descriptor: &DepthStencilDescriptor) -> Tests { + let state = depth_stencil_state(descriptor); + let face = |s: &StencilOpState| Face { + fail: vk::StencilOp::from_raw(s.fail_op.as_raw()), + pass: vk::StencilOp::from_raw(s.pass_op.as_raw()), + depth_fail: vk::StencilOp::from_raw(s.depth_fail_op.as_raw()), + compare: vk::CompareOp::from_raw(s.compare_op.as_raw()), + compare_mask: s.compare_mask, + write_mask: s.write_mask, + }; + Tests { + depth: state.depth_test_enable || state.depth_write_enable, + stencil: state.stencil_test_enable, + faces: [face(&state.front), face(&state.back)], + } + } +} + +impl Device { + /// `newDepthStencilStateWithDescriptor:`. + pub fn new_depth_stencil_state( + &self, + descriptor: &DepthStencilDescriptor, + ) -> DepthStencilState { + DepthStencilState { + inner: Arc::new(Inner { + device: self.clone(), + descriptor: *descriptor, + tests: Tests::of(descriptor), + }), + } + } +} + +impl DepthStencilState { + /// The descriptor it was made with. + pub fn descriptor(&self) -> &DepthStencilDescriptor { + &self.inner.descriptor + } + + /// Its tests. + pub(crate) fn tests(&self) -> Tests { + self.inner.tests + } + + /// Whether `core` is the device this state was made on. + pub(crate) fn is_of(&self, core: &Arc) -> bool { + Arc::ptr_eq(self.inner.device.core(), core) + } +} diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index b27085074..1f2c87e34 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -14,7 +14,7 @@ use crate::hazard::Ids; use crate::instance::{Instance, PhysicalDevice}; use crate::kernel_map::KernelMap; use crate::memory::{self, BlockId, BlockMappings, Memory, MemoryClass, Pool}; -use crate::pipeline::PUSH_BYTES; +use crate::pipeline::{PUSH_BYTES, PUSH_STAGES}; use crate::places::Places; use crate::reaper::{self, Job, Reaper}; use crate::record::Recorders; @@ -191,7 +191,7 @@ pub(crate) struct Core { /// any, the commands track what they write. pub(crate) copied_overs: AtomicUsize, /// The device's compute limits. - pub(crate) limits: ComputeLimits, + pub(crate) limits: EncoderLimits, /// The parameter ring. pub(crate) ring: Ring, /// Resource ids, for the hazard sets. @@ -420,10 +420,12 @@ impl Device { let limits = &properties.properties.limits; // The sampler arrays' two defaults count against the device's samplers too. let sampler_cap = limits.max_sampler_allocation_count.saturating_sub(2); - let limits = ComputeLimits { + let limits = EncoderLimits { max_group_count: limits.max_compute_work_group_count, max_group_size: limits.max_compute_work_group_size, max_shared_memory: limits.max_compute_shared_memory_size, + max_viewport: limits.max_viewport_dimensions, + viewport_bounds: limits.viewport_bounds_range, }; let max_block_len = vulkan11 .max_memory_allocation_size @@ -925,7 +927,7 @@ unsafe fn objects( } }; let push = [vk::PushConstantRange { - stage_flags: vk::ShaderStageFlags::ALL, + stage_flags: PUSH_STAGES, offset: 0, size: PUSH_BYTES, }]; @@ -962,14 +964,18 @@ unsafe fn objects( } } -/// The device's compute limits a dispatch is checked against. -pub(crate) struct ComputeLimits { +/// The device's limits a dispatch or a render encoder's state is checked against. +pub(crate) struct EncoderLimits { /// `maxComputeWorkGroupCount`. pub(crate) max_group_count: [u32; 3], /// `maxComputeWorkGroupSize`. pub(crate) max_group_size: [u32; 3], /// `maxComputeSharedMemorySize`. pub(crate) max_shared_memory: u32, + /// `maxViewportDimensions`. + pub(crate) max_viewport: [u32; 2], + /// `viewportBoundsRange`. + pub(crate) viewport_bounds: [f32; 2], } impl Core { diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index aaa1700f2..c8b0b2def 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -9,7 +9,8 @@ use crate::hazard::Access; use crate::memory::BlockId; use crate::over; use crate::pipeline::{ - ComputePipelineState, FieldValue, Form, Interface, Kernel, Place, Variant, PUSH_BYTES, SQUARE, + ComputePipelineState, FieldValue, Form, Interface, Kernel, Place, Variant, PUSH_BYTES, + PUSH_STAGES, SQUARE, }; use crate::record::Reach; use crate::ring::CHUNK; @@ -22,11 +23,11 @@ use std::ops::BitOr; use std::sync::Arc; /// Metal's count of buffer argument table entries per stage. -const BUFFER_SLOTS: u32 = 31; +pub(crate) const BUFFER_SLOTS: u32 = 31; /// Metal's count of texture argument table entries per stage. -const TEXTURE_SLOTS: u32 = 128; +pub(crate) const TEXTURE_SLOTS: u32 = 128; /// Metal's count of sampler argument table entries per stage. -const SAMPLER_SLOTS: u32 = 16; +pub(crate) const SAMPLER_SLOTS: u32 = 16; /// `MTLDispatchType`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -1157,7 +1158,7 @@ impl Building { let first = self.unbound(); // SAFETY: the command buffer is recording outside any render pass; the pipeline, the // layout and set 1 are the device's, set 1 of that layout and update-after-bind, and the - // push range of the layout spans every stage's first 128 bytes. + // window lies in the layout's one push range, of `PUSH_STAGES`. unsafe { if first { device.cmd_bind_descriptor_sets( @@ -1173,7 +1174,7 @@ impl Building { device.cmd_bind_pipeline(command, vk::PipelineBindPoint::COMPUTE, pipeline); } if !push.is_empty() { - device.cmd_push_constants(command, core.layout, vk::ShaderStageFlags::ALL, 0, push); + device.cmd_push_constants(command, core.layout, PUSH_STAGES, 0, push); } match *launch { Launch::Direct(groups) => { diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index 9ec159678..375411003 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -138,9 +138,10 @@ pub enum Refusal { /// Basis: metal-documented (a command buffer has one active encoder at a time, ended by /// `endEncoding` before another is made or the command buffer is committed). EncoderOpen, - /// A dispatch with no pipeline state set. + /// A dispatch or a draw with no pipeline state set. /// - /// Basis: metal-documented (a compute dispatch needs a compute pipeline state set first). + /// Basis: metal-documented (a compute dispatch needs a compute pipeline state set first, and a + /// draw a render pipeline state). NoPipeline, /// A buffer argument index past Metal's 31 entries (`setBuffer`, `setBytes`, /// `setBufferOffset`, `setThreadgroupMemoryLength`). @@ -177,9 +178,11 @@ pub enum Refusal { /// The indices given. given: usize, }, - /// `setBufferOffset` at an index where no buffer is bound. + /// `setBufferOffset` at an index where no buffer is bound, or a draw whose vertex descriptor + /// reads a vertex buffer index where none is bound. /// - /// Basis: ours (there is no buffer whose offset to change). + /// Basis: ours (there is no buffer whose offset to change, and none whose vertices the draw + /// reads; Metal's validation stops such a draw). NoBufferAtIndex { /// The index asked for. index: u32, @@ -567,6 +570,41 @@ pub enum Refusal { /// The texture's pixel format. pixel_format: PixelFormat, }, + /// A draw whose vertex descriptor reads a vertex buffer at an offset at or past the buffer's + /// length. + /// + /// Basis: metal-documented (a buffer's offset lies inside it; Metal's validation stops the + /// bind). + VertexBufferOffset { + /// The vertex buffer index. + index: u32, + /// The offset bound. + offset: u64, + /// The buffer's length. + length: u64, + }, + /// An indexed draw whose index buffer offset is not a multiple of the index size, or whose + /// indices leave the buffer. + /// + /// Basis: metal-documented (the offset is a multiple of the index size and the indices lie in + /// the buffer; Metal's validation stops the draw). + IndexBufferOffset { + /// The offset asked for. + offset: u64, + /// The buffer's length. + length: u64, + }, + /// A viewport with a field that is NaN or infinite (but its origin's x, which draws nothing). + /// + /// Basis: metal-measured (an Apple M4, macOS 27.0.1: Metal's validation stops a NaN or + /// infinite origin; the other fields are taken by the same rule). + ViewportNotFinite, + /// A draw under a depth-stencil state that tests the stencil, in a pass without a stencil + /// attachment. + /// + /// Basis: metal-measured (an Apple M4, macOS 27.0.1: Metal's validation stops the draw; plain + /// Metal tests it against a hidden stencil of 0 that the runtime does not keep). + StencilAttachment, } /// A Metal feature the runtime does not build yet, with what it was asked. Each is refused until a @@ -777,6 +815,16 @@ pub enum Gap { /// What the pass asks for. kind: RenderPassKind, }, + /// A draw or render encoder state the runtime does not build yet + /// ([`RenderCommandEncoder`](crate::RenderCommandEncoder)): what `kind` names. + /// + /// Basis: ours (the replay streams draw lines and triangles under depth-stencil states that + /// test no depth, through viewports Vulkan's are, with pipeline states of their pass's formats; + /// each other kind is built when a replay stream draws one). + Draw { + /// What the draw asks for. + kind: DrawKind, + }, } /// What a render pipeline state asks that the runtime does not build ([`Gap::RenderPipeline`]). @@ -804,8 +852,6 @@ pub enum RenderPipelineKind { AlphaToOne, /// A vertex buffer layout of an instance step rate above 1. StepRate, - /// Samplers the state numbers: constexpr samplers, or a texture read or write's own. - Samplers, /// A function that reads constant data the binder supplies. ConstantData, /// A specialization the draw would set, beside the sample and amplification counts. @@ -815,6 +861,28 @@ pub enum RenderPipelineKind { /// A Vulkan feature or extension the translator's pipeline needs (its `Requirements`) that /// device creation does not enable. DeviceFeature, + /// A function that reads what a draw does not supply yet: a function table, a table the + /// binder builds, a parameter block past the push range, a push field or bind-time fact the + /// render encoder does not fill, or an unnormalized constexpr sampler. + DrawInput, +} + +/// What a draw asks that the runtime does not build ([`Gap::Draw`]). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum DrawKind { + /// A draw of points (`MTLPrimitiveTypePoint`). + Points, + /// A depth-stencil state that tests or writes depth: no pass has a depth attachment yet. + DepthTest, + /// A viewport Vulkan's is not: a negative width (Metal mirrors the draw), a depth range past + /// `[0, 1]`, or bounds past the device's viewport limits. + Viewport, + /// A pipeline state whose colour or stencil formats are not its pass's attachments': Metal's + /// validation stops most such draws, and plain Metal zeroes or drops the colours. + AttachmentFormats, + /// A draw that binds a texture whose image the pass renders into. + AttachmentRead, } /// What a render pass asks that the runtime does not build ([`Gap::RenderPass`]). @@ -1065,7 +1133,7 @@ impl fmt::Display for Refusal { f.write_str("a command queue must hold at least one command buffer") } Refusal::EncoderOpen => f.write_str("an encoder of the command buffer is open"), - Refusal::NoPipeline => f.write_str("no compute pipeline state is set"), + Refusal::NoPipeline => f.write_str("no pipeline state is set"), Refusal::BufferIndex { index } => { write!(f, "buffer index {index} is past the 31 entries") } @@ -1236,6 +1304,22 @@ impl fmt::Display for Refusal { f, "an attachment of {pixel_format:?} is not of its kind's formats" ), + Refusal::VertexBufferOffset { + index, + offset, + length, + } => write!( + f, + "vertex buffer {index} at offset {offset} lies past its {length} bytes" + ), + Refusal::IndexBufferOffset { offset, length } => write!( + f, + "indices at offset {offset} of a {length}-byte buffer are misaligned or past its end" + ), + Refusal::ViewportNotFinite => f.write_str("a viewport field is NaN or infinite"), + Refusal::StencilAttachment => { + f.write_str("a draw tests the stencil in a pass without a stencil attachment") + } } } } @@ -1312,6 +1396,7 @@ impl fmt::Display for Gap { } Gap::TextureView { kind } => write!(f, "a texture view that changes {kind:?} is not built"), Gap::RenderPass { kind } => write!(f, "a render pass with {kind:?} is not built"), + Gap::Draw { kind } => write!(f, "a draw with {kind:?} is not built"), } } } diff --git a/crates/metal2vulkan-rt/src/lib.rs b/crates/metal2vulkan-rt/src/lib.rs index 4bbcd4f81..0acdf45f7 100644 --- a/crates/metal2vulkan-rt/src/lib.rs +++ b/crates/metal2vulkan-rt/src/lib.rs @@ -17,6 +17,7 @@ mod capture; mod command; mod complete; mod counters; +mod depth_stencil; mod device; mod encoder; mod error; @@ -54,9 +55,12 @@ pub use block::Block; pub use buffer::{Buffer, MAX_BUFFER_LENGTH}; pub use command::{CommandBuffer, CommandBufferError, CommandBufferStatus}; pub use counters::{Counters, Gauges, Metrics}; +pub use depth_stencil::DepthStencilState; pub use device::{Device, DeviceOptions, RawDevice}; pub use encoder::{ComputeCommandEncoder, DispatchType, Resource, ResourceUsage}; -pub use error::{Error, Gap, Limit, Refusal, RenderPassKind, RenderPipelineKind, TextureViewKind}; +pub use error::{ + DrawKind, Error, Gap, Limit, Refusal, RenderPassKind, RenderPipelineKind, TextureViewKind, +}; pub use event::{Event, SharedEvent}; pub use extension::{ConsumerFeature, DeviceExtension}; pub use fence::Fence; @@ -66,12 +70,17 @@ pub use memory::{BlockId, BlockInfo, BlockMappings, MemoryClass}; /// `MTLSamplerDescriptor`: the translator's. pub use metal2vulkan::bind::SamplerDescriptor; pub use metal2vulkan::library::Library; +/// `MTLDepthStencilDescriptor` and its `MTLStencilDescriptor`: the translator's. +pub use metal2vulkan::metal::state::{DepthStencilDescriptor, StencilDescriptor}; /// `MTLSamplerMinMagFilter`, `MTLSamplerMipFilter`, `MTLSamplerAddressMode`, /// `MTLSamplerBorderColor`, `MTLCompareFunction` and `MTLSamplerReductionMode`: the translator's. pub use metal2vulkan::metal::{ CompareFunction, SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter, SamplerMipFilter, SamplerReductionMode, }; +/// `MTLPrimitiveType`, `MTLIndexType`, `MTLCullMode`, `MTLWinding` and `MTLStencilOperation`: +/// the translator's. +pub use metal2vulkan::metal::{CullMode, IndexType, PrimitiveType, StencilOperation, Winding}; /// `MTLPixelFormat`, `MTLTextureType`, `MTLTextureUsage` and `MTLTextureSwizzleChannels` with its /// `MTLTextureSwizzle`: the translator's. pub use metal2vulkan::metal::{ @@ -95,7 +104,7 @@ pub use pass::{ pub use pipeline::ComputePipelineState; pub use queue::CommandQueue; pub use render::RenderPipelineState; -pub use render_encoder::RenderCommandEncoder; +pub use render_encoder::{IndexBuffer, RenderCommandEncoder, ScissorRect, Viewport}; pub use sampler::SamplerState; pub use texture::{ BytesPlace, HeapRange, Region, SizeAndAlign, StorageMode, Texture, TextureDescriptor, diff --git a/crates/metal2vulkan-rt/src/pass.rs b/crates/metal2vulkan-rt/src/pass.rs index 026361c7f..213c4fc9d 100644 --- a/crates/metal2vulkan-rt/src/pass.rs +++ b/crates/metal2vulkan-rt/src/pass.rs @@ -3,11 +3,12 @@ //! encoder begins ([`Pass`]). //! //! Each attachment is one level and slice of its texture, viewed through an image view of that -//! level and layer with the identity swizzle, which the texture keeps. Its load and store actions -//! are Vulkan's of the same -//! name: `Load`, `Clear` and `DontCare` load, `Store` and `DontCare` store. The render area is the -//! smallest attachment's level, cut to `renderTargetWidth` and `renderTargetHeight` where they are -//! set. +//! level and layer with the identity swizzle, which the texture keeps. Its load actions are +//! Vulkan's of the same name: `Load`, `Clear` and `DontCare`. Both store actions store: a pass may +//! end its rendering before the encoder ends and begin it again, loading what it stored (a memory +//! barrier after a draw that wrote memory, or a copy a draw needs first), so a `DontCare` store +//! keeps the texels too, one of the outcomes Metal allows. The render area is the smallest +//! attachment's level, cut to `renderTargetWidth` and `renderTargetHeight` where they are set. use crate::device::Core; use crate::error::{Error, Gap, Limit, Refusal, RenderPassKind}; @@ -38,8 +39,9 @@ pub enum LoadAction { #[non_exhaustive] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum StoreAction { - /// `MTLStoreActionDontCare`: the pass's texels are not kept, and the attachment's are - /// undefined after it, `VK_ATTACHMENT_STORE_OP_DONT_CARE`. + /// `MTLStoreActionDontCare`: the attachment's texels are undefined after the pass. The + /// runtime keeps them, `VK_ATTACHMENT_STORE_OP_STORE`: a pass that ends its rendering early + /// and begins it again loads what it stored. DontCare, /// `MTLStoreActionStore`: the pass's texels are kept, `VK_ATTACHMENT_STORE_OP_STORE`. #[default] @@ -228,12 +230,16 @@ impl Target { self.layout != self.attachment.home } - /// Its `VkRenderingAttachmentInfo`. - pub(crate) fn info(&self) -> vk::RenderingAttachmentInfo<'static> { + /// Its `VkRenderingAttachmentInfo`; `resumed`, for a rendering the pass begins again, which + /// loads what the pass stored. + pub(crate) fn info(&self, resumed: bool) -> vk::RenderingAttachmentInfo<'static> { vk::RenderingAttachmentInfo::default() .image_view(self.attachment.view) .image_layout(self.layout) - .load_op(self.load) + .load_op(match resumed { + true => vk::AttachmentLoadOp::LOAD, + false => self.load, + }) .store_op(self.store) .clear_value(self.clear) } @@ -281,6 +287,42 @@ impl Pass { (self.colors.iter().flatten()).chain(&self.stencil) } + /// Records `vkCmdBeginRendering` of the pass into `command`; `resumed`, again after the + /// encoder ended it early, loading what it stored. + /// + /// # Safety + /// + /// `command` records outside any rendering and keeps each attachment's texture until it + /// retires; each attachment is in the layout the pass renders it in. + pub(crate) unsafe fn begin( + &self, + device: &ash::Device, + command: vk::CommandBuffer, + resumed: bool, + ) { + let colors: Vec = (self.colors.iter()) + .map(|c| { + c.as_ref() + .map_or_else(Default::default, |t| t.info(resumed)) + }) + .collect(); + let stencil = self.stencil.as_ref().map(|t| t.info(resumed)); + let [width, height] = self.area; + let mut info = vk::RenderingInfo::default() + .render_area(vk::Rect2D { + offset: vk::Offset2D { x: 0, y: 0 }, + extent: vk::Extent2D { width, height }, + }) + .layer_count(1) + .color_attachments(&colors); + if let Some(stencil) = &stencil { + info = info.stencil_attachment(stencil); + } + // SAFETY: as the caller states; the render area lies inside every attachment, and each + // is a view of one level and layer of its image. + unsafe { device.cmd_begin_rendering(command, &info) }; + } + /// Checks `d` on the device of `core`. /// /// Err: [`Refusal::OtherDevice`] for another device's texture; [`Refusal::AttachmentUsage`]; @@ -384,7 +426,8 @@ impl Pass { } } -/// The Vulkan load and store operations of Metal's `load` and `store` actions, one to one. +/// The Vulkan load and store operations of Metal's `load` and `store` actions: the load one to +/// one, and `STORE` for both store actions ([`StoreAction::DontCare`]). /// /// Err: [`Gap::RenderPass`] of [`RenderPassKind::Resolve`] or [`RenderPassKind::StoreAction`]. pub(crate) fn ops( @@ -398,8 +441,7 @@ pub(crate) fn ops( }; let gap = |kind| Err(Error::Unsupported(Gap::RenderPass { kind })); let store = match store { - StoreAction::DontCare => vk::AttachmentStoreOp::DONT_CARE, - StoreAction::Store => vk::AttachmentStoreOp::STORE, + StoreAction::DontCare | StoreAction::Store => vk::AttachmentStoreOp::STORE, StoreAction::MultisampleResolve | StoreAction::StoreAndMultisampleResolve => { return gap(RenderPassKind::Resolve) } diff --git a/crates/metal2vulkan-rt/src/pipeline.rs b/crates/metal2vulkan-rt/src/pipeline.rs index 5807861f2..d1412cf46 100644 --- a/crates/metal2vulkan-rt/src/pipeline.rs +++ b/crates/metal2vulkan-rt/src/pipeline.rs @@ -69,6 +69,10 @@ use std::sync::{Arc, Mutex, OnceLock}; /// parameter ring, whose address is a field in the window. pub(crate) const PUSH_BYTES: u32 = crate::floor::PUSH_CONSTANT_BYTES; +/// The stages of the layout's one push range, which every `vkCmdPushConstants` names: a +/// dispatch's and a draw's pushes are of one range over the compute, vertex and fragment stages. +pub(crate) const PUSH_STAGES: vk::ShaderStageFlags = vk::ShaderStageFlags::ALL; + /// `MTLComputePipelineState`. /// /// A cheap handle: clones share one state. A command buffer that dispatches with it keeps it until @@ -150,6 +154,23 @@ fn number( { return Err(gap()); } + let uses: Vec<(usize, CombinedSampler)> = (kernels.iter()) + .flat_map(|kernel| kernel.interface.constexprs.iter().copied()) + .collect(); + number_samplers(core, samplers, &uses, sampler_ids, gap) +} + +/// A state's numbered samplers `samplers`: `sampler_ids` gives an index to each, and each +/// constexpr sampler of `uses` (by its place in `samplers`, with its use) takes the device sampler +/// of each use at its index. `gap` is the error of a use whose sampler the translator cannot +/// state. +pub(crate) fn number_samplers( + core: &Core, + samplers: Vec, + uses: &[(usize, CombinedSampler)], + sampler_ids: impl FnOnce(&[NumberedSampler]) -> Result, Error>, + gap: fn() -> Error, +) -> Result { let ids = sampler_ids(&samplers)?; if ids.len() != samplers.len() { return Err(Error::Refused(Refusal::SamplerIds { @@ -167,22 +188,18 @@ fn number( let NumberedSampler::Constexpr(words) = *sampler else { continue; }; - let mut uses = [None; 3]; - let used = kernels - .iter() - .flat_map(|kernel| &kernel.interface.constexprs) - .filter(|(place, _)| *place == at); - for (_, sampler) in used { + let mut held = [None; 3]; + for (_, sampler) in uses.iter().filter(|(place, _)| *place == at) { let desc = sampler .constexpr_sampler(profile) .map_err(Error::Translation)? .ok_or_else(gap)?; - uses[sampler_array(sampler)] = Some(canonical(desc)); + held[sampler_array(sampler)] = Some(canonical(desc)); } - if uses.iter().all(Option::is_none) { + if held.iter().all(Option::is_none) { continue; } - if let Err(error) = hold_constexpr(core, numbered.ids[at], words, uses) { + if let Err(error) = hold_constexpr(core, numbered.ids[at], words, held) { numbered.release(core); return Err(error); } @@ -193,7 +210,7 @@ fn number( impl Numbered { /// Gives up the constexpr samplers' elements the state holds. - fn release(&mut self, core: &Core) { + pub(crate) fn release(&mut self, core: &Core) { for at in self.held.drain(..) { release_constexpr(core, self.ids[at]); } @@ -387,7 +404,8 @@ pub(crate) enum FieldValue { /// saturates to them (`metal::format::integer_channels_word`), 0 where none is. IntegerChannels(u32), /// A `u32`: the sampler index the consumer gave the constexpr sampler at this place of the - /// state's numbered samplers. + /// state's numbered samplers (a render state's: the vertex function's, then the fragment + /// function's). ConstexprSampler(usize), /// The dispatch's region, 32 bytes read as two `uvec4`: the first threadgroup of the dispatch /// in Metal's grid (0 for a whole dispatch) with the threadgroup size packed as @@ -996,9 +1014,9 @@ fn gap() -> Error { Error::Unsupported(Gap::KernelInput) } -/// Whether `set` of a kernel's layout is the device's: set 1 the device's texture and sampler -/// arrays (those of them the kernel reads), any other set empty. -fn of_the_device(set: &DescriptorSetLayout) -> bool { +/// Whether `set` of a pipeline's layout is the device's: set 1 the device's texture and sampler +/// arrays (those of them its functions read), any other set empty. +pub(crate) fn of_the_device(set: &DescriptorSetLayout) -> bool { match set.set { 1 => set.bindings.iter().all(|binding| { let ty: vk::DescriptorType = binding.ty.into(); @@ -1009,8 +1027,8 @@ fn of_the_device(set: &DescriptorSetLayout) -> bool { } } -/// The hazard table's access of a texture slot the kernel samples, reads, writes, or several. -fn texture_access(used: TextureAccess) -> Access { +/// The hazard table's access of a texture slot a function samples, reads, writes, or several. +pub(crate) fn texture_access(used: TextureAccess) -> Access { match (used.sample || used.read, used.write) { (_, false) => Access::Read, (false, true) => Access::Write, @@ -1018,8 +1036,8 @@ fn texture_access(used: TextureAccess) -> Access { } } -/// The hazard table's access of a slot the kernel reads, writes, or both. -fn access(used: AccessSet) -> Access { +/// The hazard table's access of a slot a function reads, writes, or both. +pub(crate) fn access(used: AccessSet) -> Access { match (used.read, used.write) { (_, false) => Access::Read, (false, true) => Access::Write, diff --git a/crates/metal2vulkan-rt/src/render.rs b/crates/metal2vulkan-rt/src/render.rs index 5d1088fb1..07883119a 100644 --- a/crates/metal2vulkan-rt/src/render.rs +++ b/crates/metal2vulkan-rt/src/render.rs @@ -17,48 +17,96 @@ //! topology class (point, line or triangle) of the draws it serves. Everything Metal sets on the //! encoder that Vulkan 1.3 makes dynamic without a feature is dynamic state: viewport, scissor, //! cull mode, front face, the primitive topology within its class and primitive restart, the -//! depth test, write and compare, the stencil test, operations, masks and reference, depth bias, -//! blend constants and vertex buffer strides. Metal's triangle fill mode and depth clip mode, -//! which Vulkan 1.3 bakes, are their defaults: the render encoder does not set them yet. +//! depth test, write and compare, the stencil test, operations, masks and reference, depth bias +//! and blend constants. Vertex buffer strides are the descriptor's, so the content's: they are +//! baked, and a layout whose stride is set per bind (`MTLBufferLayoutStrideDynamic`), which the +//! replay streams' never are, is refused. Metal's triangle fill mode and depth clip mode, which +//! Vulkan 1.3 bakes, are their defaults: the render encoder does not set them yet. +//! +//! What a draw supplies is the content's [`Draws`]: each function's slots with their accesses, +//! its push fields (addresses, resource IDs and indices of the slots, in the floor's one push +//! range, the fragment function's after the vertex function's), and the vertex buffers its +//! fixed-function vertex input reads. A state numbers its functions' samplers as a compute state +//! numbers its kernel's, the vertex function's first. //! //! A descriptor names no topology class unless it sets `inputPrimitiveTopology`, and the replay //! streams' never do, while nearly every content draws only triangles (527 of the 537 contents //! gb and b2 draw). So the triangle class's `VkPipeline` is made with the state, where Metal //! compiles; a point or line class's comes with the draws, made by the first draw of that class. //! The cost: a content drawn only as lines or points makes a triangle `VkPipeline` it never uses -//! (8 contents of the 537). +//! (8 contents of the 537). The replay streams draw no points: a draw of points is refused. use crate::cache::{module_digest, pipeline_key}; use crate::counters::Gauge; -use crate::device::Core; +use crate::device::{lock, Core}; use crate::error::{Error, Gap, RenderPipelineKind}; +use crate::hazard::Access; use crate::kernel_map::KernelKey; -use crate::pipeline::{layout_words, lower, made_through_cache}; +use crate::pass::Pass; +use crate::pipeline::{ + access, layout_words, lower, made_through_cache, number_samplers, of_the_device, + texture_access, FieldValue, Numbered, PUSH_BYTES, +}; use crate::reaper::{Free, Job}; +use crate::times::host_time; use ash::vk; use metal2vulkan::cache::VariantKey; use metal2vulkan::device::EnabledCaps; use metal2vulkan::pipeline::{ - PrecisionNote, RenderPipeline, RenderPipelineDescriptor, RenderPipelineKeys, SpecKey, - StageEntries, StageSource, VertexStride, + BufferKind, CombinedSampler, NumberedSampler, PrecisionNote, PushField, PushLoc, + RenderPipeline, RenderPipelineDescriptor, RenderPipelineKeys, RuntimeFact, SamplerRef, + SlotClass, SlotInterface, SlotRef, SpecKey, Stage, StageEntries, StageSource, VertexStride, }; use metal2vulkan::Budget; use sha2::{Digest, Sha256}; use std::ffi::CString; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; /// `MTLRenderPipelineState`. /// -/// A cheap handle: clones share one state. States of one content (the functions, their constant -/// values and linked functions, and the descriptor's fields that change the compile) share its -/// translation and `VkPipeline`s, so a guest that makes one state many times compiles it once. +/// A cheap handle: clones share one state. A command buffer that draws with it keeps it until it +/// retires. States of one content (the functions, their constant values and linked functions, and +/// the descriptor's fields that change the compile) share its translation and `VkPipeline`s, so a +/// guest that makes one state many times compiles it once; each numbers its own samplers. #[derive(Clone)] pub struct RenderPipelineState { + pub(crate) inner: Arc, +} + +pub(crate) struct RenderInner { + /// What the state's content compiles to, shared with every state of that content. pub(crate) compiled: Arc, + /// The samplers the state numbers and the indices the consumer gave them. + pub(crate) numbered: Numbered, +} + +/// The vertex function's index in a draw's tables, and the fragment function's. +pub(crate) const VERTEX: usize = 0; +pub(crate) const FRAGMENT: usize = 1; + +/// What a draw of a content supplies, from the translator. +pub(crate) struct Draws { + /// Each buffer slot a function uses: its function ([`VERTEX`] or [`FRAGMENT`]), its index and + /// its access. + pub(crate) buffers: Vec<(usize, u32, Access)>, + /// Each texture slot a function uses, likewise. + pub(crate) textures: Vec<(usize, u32, Access)>, + /// Each fixed-function vertex binding: its binding and the vertex buffer index it reads. + pub(crate) bindings: Vec<(u32, u32)>, + /// Whether a function reads through an address that is not one of its slots. + pub(crate) reads_unbound: bool, + /// Whether a function writes through an address that is not one of its slots. + pub(crate) writes_unbound: bool, + /// Whether a function writes memory (`PipelineInterface::writes_memory`). + pub(crate) writes_memory: bool, + /// The bytes of the push range the functions read, from 0. + pub(crate) push_len: u32, + /// Each push field: its offset, its function's tables, and its value. + pub(crate) fields: Vec<(u32, usize, FieldValue)>, } /// The state Vulkan 1.3 lets a draw set, which every render `VkPipeline` takes as dynamic. -const DYNAMIC: [vk::DynamicState; 18] = [ +const DYNAMIC: [vk::DynamicState; 17] = [ vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR, vk::DynamicState::CULL_MODE, @@ -76,7 +124,6 @@ const DYNAMIC: [vk::DynamicState; 18] = [ vk::DynamicState::DEPTH_BIAS, vk::DynamicState::DEPTH_BIAS_ENABLE, vk::DynamicState::BLEND_CONSTANTS, - vk::DynamicState::VERTEX_INPUT_BINDING_STRIDE, ]; /// What one render pipeline content compiles to, shared by every state of it and held by the @@ -93,8 +140,17 @@ pub(crate) struct RenderCompiled { digest: [u8; 32], /// The triangle class's `VkPipeline`, made with the content. triangles: vk::Pipeline, + /// The line class's, made by the first draw of lines; null until then. + lines: Mutex, /// The translator's notes of where the pipeline's answers may differ from Metal's. notes: Vec, + /// What a draw supplies. + pub(crate) draws: Draws, + /// The samplers a state numbers, the vertex function's then the fragment function's, each in + /// Metal's order, and each constexpr sampler a function samples through, by its place there, + /// with its use. + numbered: Vec, + constexprs: Vec<(usize, CombinedSampler)>, } /// One stage's shader module and what a `VkPipeline` of it takes. @@ -142,15 +198,28 @@ impl crate::Device { /// /// Built: one vertex and at most one fragment function, colour attachments of any format the /// translator maps for the device, a stencil attachment, one sample, and every blend state, - /// write mask and vertex descriptor Vulkan's fixed-function state takes with what device - /// creation enables; what else the translator states is refused at the creation, by kind. + /// write mask and vertex descriptor of static strides Vulkan's fixed-function state takes with + /// what device creation enables; what else the translator states is refused at the creation, + /// by kind. + /// + /// The state numbers samplers as Metal's pipeline creation does + /// (`PipelineInterface::numbered_samplers`), as + /// [`new_compute_pipeline_state`](Self::new_compute_pipeline_state) numbers a kernel's: once + /// the functions are lowered, `sampler_ids` takes the vertex function's, then the fragment + /// function's, each in Metal's order, and answers the sampler index the consumer gives each. + /// Each constexpr sampler a function samples through takes the device sampler of each use it + /// has at its index before the call returns, and every draw pushes the index. /// /// Err: [`Error::Translation`], the translator's typed refusal or a descriptor Metal refuses; /// [`Gap::IndirectCommandBuffers`]; [`Gap::RenderPipeline`] for what the runtime does not - /// build, naming it; [`Error::Vulkan`]. + /// build, naming it; [`Refusal::SamplerIds`](crate::Refusal::SamplerIds) where `sampler_ids` + /// answers another count; [`Refusal::IndicesNotGranted`](crate::Refusal::IndicesNotGranted) + /// and [`Refusal::IndexInUse`](crate::Refusal::IndexInUse) for a constexpr sampler's index; + /// [`Limit::DeviceSamplers`](crate::Limit::DeviceSamplers); [`Error::Vulkan`]. pub fn new_render_pipeline_state( &self, descriptor: &RenderPipelineDescriptor, + sampler_ids: impl FnOnce(&[NumberedSampler]) -> Result, Error>, ) -> Result { refuse(descriptor)?; let core = self.core(); @@ -172,10 +241,180 @@ impl crate::Device { (core.kernels).keep_render(key, Arc::new(compiled), &core.counters) } }; - Ok(RenderPipelineState { compiled }) + let numbered = number_samplers( + core, + compiled.numbered.clone(), + &compiled.constexprs, + sampler_ids, + draw_input, + )?; + Ok(RenderPipelineState { + inner: Arc::new(RenderInner { compiled, numbered }), + }) } } +/// The samplers a state of a content numbers and the constexpr samplers its functions sample +/// through ([`RenderCompiled::numbered`]). +type Numbering = (Vec, Vec<(usize, CombinedSampler)>); + +/// [`Gap::RenderPipeline`] of [`RenderPipelineKind::DrawInput`]. +fn draw_input() -> Error { + Error::Unsupported(Gap::RenderPipeline { + kind: RenderPipelineKind::DrawInput, + }) +} + +/// The samplers a state of `pipeline` numbers and the constexpr samplers its functions sample +/// through ([`RenderCompiled::numbered`]), and what a draw of it supplies. +/// +/// Err: [`Gap::RenderPipeline`] of [`RenderPipelineKind::DrawInput`] for a pipeline that reads +/// what a draw does not supply: a function table, a table the binder builds, a parameter block, +/// a push field or bind-time fact the encoder does not fill, or an unnormalized constexpr +/// sampler. +fn draws(pipeline: &RenderPipeline) -> Result<(Draws, Numbering), Error> { + let translated = &pipeline.interface; + if translated.needs_pointer_translation + || translated.needs_handle_translation + || translated.reaches_command_buffers + || !pipeline.layout.sets.iter().all(of_the_device) + { + return Err(draw_input()); + } + let table = |stage| match stage { + Stage::Vertex => Ok(VERTEX), + Stage::Fragment => Ok(FRAGMENT), + _ => Err(draw_input()), + }; + // The slot's address, rounded down to a multiple of its argument's alignment. + let mut aligned = Vec::new(); + for dependency in &pipeline.dependencies { + match dependency.fact { + RuntimeFact::AddressAlignment { + slot: + SlotRef { + stage, + class: SlotClass::Buffer, + index, + }, + align, + } if align.is_power_of_two() => { + aligned.push((table(stage)?, index, u64::from(align) - 1)) + } + RuntimeFact::DeviceAddresses { .. } => {} + // A colour moved into a storage form, which the runtime never moves. + RuntimeFact::MovableStorageWrites { .. } => {} + // `RuntimeFact` is non-exhaustive: a fact this match does not name is one a draw does + // not supply. + _ => return Err(draw_input()), + } + } + let mut buffers = Vec::new(); + let mut textures = Vec::new(); + for (slot, used) in &translated.slots { + let at = table(slot.stage)?; + match (slot.class, used) { + (SlotClass::Buffer, SlotInterface::Buffer(buffer)) + if buffer.kind == BufferKind::Buffer => + { + buffers.push((at, slot.index, access(buffer.access))); + } + (SlotClass::Texture, SlotInterface::Texture(texture)) => { + textures.push((at, slot.index, texture_access(texture.access))); + } + (SlotClass::Sampler, SlotInterface::Sampler(_)) => {} + _ => return Err(draw_input()), + } + } + // The samplers a state numbers: the vertex function's, then the fragment function's. + let mut numbered = Vec::new(); + let mut firsts = [0; 2]; + for (stage, samplers) in &translated.numbered_samplers { + firsts[table(*stage)?] = numbered.len(); + numbered.extend(samplers.iter().copied()); + } + let mut constexprs = Vec::new(); + let mut fields = Vec::new(); + let mut push_len = 0; + for placement in &translated.push { + let at = table(placement.stage)?; + if placement.argument_table_size != 0 { + return Err(draw_input()); + } + if let Some((offset, size)) = placement.push_range { + push_len = push_len.max(offset + size); + } + for placed in &placement.fields { + let PushLoc::Push { offset } = placed.loc else { + return Err(draw_input()); + }; + let value = match placed.field { + PushField::SlotGuestBase(SlotRef { + stage, + class, + index, + }) => { + let of = table(stage)?; + let value = match class { + SlotClass::Buffer => FieldValue::BufferAddress { + slot: index, + mask: (aligned.iter()) + .find(|&&(table, slot, _)| table == of && slot == index) + .map_or(0, |&(_, _, mask)| mask), + }, + SlotClass::Texture => FieldValue::TextureId(index), + SlotClass::Sampler => FieldValue::SamplerId(index), + }; + fields.push((offset, of, value)); + continue; + } + PushField::TextureIntegerChannels(SlotRef { + stage, + class: SlotClass::Texture, + index, + }) => { + fields.push((offset, table(stage)?, FieldValue::IntegerChannels(index))); + continue; + } + PushField::ConstexprSampler(sampler) => { + let SamplerRef::Constexpr(words) = sampler.sampler else { + return Err(draw_input()); + }; + let first = firsts[at]; + let place = (numbered[first..].iter()) + .position(|&n| n == NumberedSampler::Constexpr(words)) + .ok_or_else(draw_input)? + + first; + if sampler.unnormalized { + return Err(draw_input()); + } + constexprs.push((place, sampler)); + FieldValue::ConstexprSampler(place) + } + _ => return Err(draw_input()), + }; + fields.push((offset, at, value)); + } + } + if push_len > PUSH_BYTES { + return Err(draw_input()); + } + let bindings = (pipeline.vertex_input.bindings.iter()) + .map(|binding| (binding.binding, binding.buffer_index)) + .collect(); + let draws = Draws { + buffers, + textures, + bindings, + reads_unbound: translated.reads_unbound_resources, + writes_unbound: translated.writes_unbound_resources, + writes_memory: translated.writes_memory, + push_len, + fields, + }; + Ok((draws, (numbered, constexprs))) +} + /// What the descriptor asks that the runtime does not build. fn refuse(d: &RenderPipelineDescriptor) -> Result<(), Error> { let kind = if d.support_indirect_command_buffers { @@ -198,7 +437,6 @@ fn refuse(d: &RenderPipelineDescriptor) -> Result<(), Error> { /// `enabled` is what device creation enabled. fn unbuilt(pipeline: &RenderPipeline, enabled: &EnabledCaps) -> Option { let g = &pipeline.graphics; - let interface = &pipeline.interface; let requirements = &pipeline.requirements; let synthesized = g.tessellation.is_some() || g.emulated_tessellation.is_some() @@ -212,7 +450,6 @@ fn unbuilt(pipeline: &RenderPipeline, enabled: &EnabledCaps) -> Option Option 1) { RenderPipelineKind::StepRate - } else if numbered { - RenderPipelineKind::Samplers } else if (pipeline.stages.iter()).any(|stage| stage.constant_blob.is_some()) { RenderPipelineKind::ConstantData } else if !(g.dynamic_states.iter()).all(|state| DYNAMIC.contains(&dynamic(*state))) { @@ -388,6 +623,7 @@ impl RenderCompiled { if let Some(kind) = unbuilt(&pipeline, translator.profile().enabled()) { return Err(Error::Unsupported(Gap::RenderPipeline { kind })); } + let (draws, (numbered, constexprs)) = draws(&pipeline)?; let samples = descriptor.raster_sample_count; let mut stages = Vec::new(); let mut notes = Vec::new(); @@ -477,13 +713,50 @@ impl RenderCompiled { fixed, digest, triangles: vk::Pipeline::null(), + lines: Mutex::new(vk::Pipeline::null()), notes, + draws, + numbered, + constexprs, }; // Made whole before the `VkPipeline`, so dropping it releases what was made. compiled.triangles = compiled.make(vk::PrimitiveTopology::TRIANGLE_LIST)?; Ok(compiled) } + /// The `VkPipeline` of the content for draws of `topology`'s class, a line or triangle one: + /// the line class's made by its first draw, which waits for it, a first-use wait + /// ([`Metrics::first_use_waits`](crate::Metrics::first_use_waits)). + /// + /// Err: [`Error::Vulkan`] where the pipeline cannot be made. + pub(crate) fn pipeline(&self, topology: vk::PrimitiveTopology) -> Result { + if topology != vk::PrimitiveTopology::LINE_LIST + && topology != vk::PrimitiveTopology::LINE_STRIP + { + return Ok(self.triangles); + } + let mut lines = lock(&self.lines); + if *lines == vk::Pipeline::null() { + let began = host_time(); + *lines = self.make(vk::PrimitiveTopology::LINE_LIST)?; + (self.core.counters).first_use_wait(host_time().saturating_sub(began)); + } + Ok(*lines) + } + + /// Whether the content's `VkPipeline`s render into `pass`'s attachments: its colour formats are + /// the pass's colour attachments', by index, an absent one where the pass has none, and its + /// stencil format the pass's stencil attachment's, or none without one. + pub(crate) fn renders_into(&self, pass: &Pass) -> bool { + let fixed = &self.fixed; + let format = |t: Option<&crate::pass::Target>| { + t.map_or(vk::Format::UNDEFINED, |t| t.attachment.format) + }; + fixed.colors.len() == pass.colors.len() + && (fixed.colors.iter().zip(&pass.colors)).all(|(&f, t)| f == format(t.as_ref())) + && fixed.stencil == format(pass.stencil.as_ref()) + } + /// A `VkPipeline` of the content for draws of the class of `topology`, a list topology, made /// through the device's pipeline data, rendering dynamically into the descriptor's attachment /// formats. A draw sets its own topology within the class as dynamic state. @@ -573,7 +846,23 @@ impl RenderPipelineState { /// No Metal counterpart: the translator's notes of where this pipeline's answers may differ /// from Metal's, of its modules ([`PrecisionNote`]); empty where they match. pub fn precision_notes(&self) -> Vec { - self.compiled.notes.clone() + self.inner.compiled.notes.clone() + } + + /// Whether two handles are one state. + pub(crate) fn is(&self, other: &RenderPipelineState) -> bool { + Arc::ptr_eq(&self.inner, &other.inner) + } + + /// Whether `core` is the device this state was made on. + pub(crate) fn is_of(&self, core: &Arc) -> bool { + Arc::ptr_eq(&self.inner.compiled.core, core) + } +} + +impl Drop for RenderInner { + fn drop(&mut self) { + self.numbered.release(&self.compiled.core); } } @@ -582,8 +871,11 @@ impl Drop for RenderCompiled { // No state holds it, so no command buffer that used it is left: each kept its state until // it retired. self.core.counters.fall(Gauge::RenderContents); - if self.triangles != vk::Pipeline::null() { - (self.core.reaper).give(Job::Free(Free::Pipeline(self.triangles))); + let lines = *self.lines.get_mut().unwrap_or_else(|e| e.into_inner()); + for pipeline in [self.triangles, lines] { + if pipeline != vk::Pipeline::null() { + (self.core.reaper).give(Job::Free(Free::Pipeline(pipeline))); + } } release(&self.core, &self.stages); } diff --git a/crates/metal2vulkan-rt/src/render_encoder.rs b/crates/metal2vulkan-rt/src/render_encoder.rs index a3f7cb977..4cf2422eb 100644 --- a/crates/metal2vulkan-rt/src/render_encoder.rs +++ b/crates/metal2vulkan-rt/src/render_encoder.rs @@ -1,5 +1,5 @@ //! Render command encoders: one dynamic rendering a Metal render encoder, begun as the encoder is -//! made and ended as it ends. +//! made and ended as it ends, and the draws recorded into it. //! //! The pass orders itself as a blit's copy does. Its first barrier runs it after every earlier //! command, makes their writes visible to it, and moves each attachment whose home is @@ -7,26 +7,184 @@ //! attachment layout renders in it. It pays the barrier an earlier encoder owed, and the hazard //! sets start again. Its second, after `vkCmdEndRendering`, moves those attachments home and makes //! the pass's writes visible to every later command. A pass is two barriers, whatever it renders. +//! +//! Draws record into the rendering with no barrier between them, as Metal orders the memory +//! accesses of no two draws of one encoder: what a draw writes, a later draw of the encoder sees +//! after a memory barrier. A memory barrier after a draw that wrote memory ends the rendering, +//! records one barrier and begins the rendering again, loading what it stored; so does a draw that +//! needs a copy first (a texture over a buffer in an image of its own, or one over a Managed +//! buffer's device copy, `crate::over`), recording the copy between. A memory barrier after no +//! such draw records nothing: the pass's first barrier ordered everything before it. +//! +//! A draw sets Metal's state as dynamic state: every state at the encoder's first draw, Metal's +//! defaults where the encoder set none, and after that what changed. A viewport is Vulkan's with +//! its height negated (from `y + height`), so framebuffer rows, the fragment position and +//! derivatives follow Metal's clip space, whose y points up; Metal's front-facing winding is then +//! Vulkan's front face of the same name. Metal clips a draw to the pixels its viewport covers, so +//! the scissor is Metal's rectangle cut to those pixels. +use crate::buffer::Buffer; use crate::command::{Building, CommandBuffer}; use crate::counters::Metric; -use crate::error::Error; +use crate::depth_stencil::{DepthStencilState, Tests}; +use crate::encoder::{BUFFER_SLOTS, SAMPLER_SLOTS, TEXTURE_SLOTS}; +use crate::error::{DrawKind, Error, Gap, Limit, Refusal}; +use crate::fence::Fence; use crate::hazard::Access; +use crate::over; use crate::pass::{Pass, RenderPassDescriptor}; +use crate::pipeline::{FieldValue, PUSH_STAGES}; use crate::record::{memory_barrier, Reach}; +use crate::render::{RenderPipelineState, FRAGMENT, VERTEX}; +use crate::ring::{Placed, CHUNK}; +use crate::sampler::SamplerState; +use crate::texture::Texture; use ash::vk; +use metal2vulkan::metal::format::integer_channels_word; +use metal2vulkan::metal::state::{input_assembly, DepthStencilDescriptor}; +use metal2vulkan::metal::{CullMode, IndexType, PrimitiveType, Winding}; use std::sync::Arc; +/// `MTLViewport`: an origin and size in pixels, and a depth range. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Viewport { + /// `originX`. + pub origin_x: f64, + /// `originY`. + pub origin_y: f64, + /// `width`. + pub width: f64, + /// `height`: negative flips the draw. + pub height: f64, + /// `znear`. + pub znear: f64, + /// `zfar`. + pub zfar: f64, +} + +/// `MTLScissorRect`: a rectangle of pixels. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ScissorRect { + /// `x`. + pub x: u64, + /// `y`. + pub y: u64, + /// `width`. + pub width: u64, + /// `height`. + pub height: u64, +} + +/// The index buffer of an indexed draw +/// ([`RenderCommandEncoder::draw_indexed_primitives`]): `indexBuffer`, `indexBufferOffset` and +/// `indexType`. +#[derive(Clone, Copy)] +pub struct IndexBuffer<'a> { + /// `indexBuffer`. + pub buffer: &'a Buffer, + /// `indexBufferOffset`. + pub offset: u64, + /// `indexType`. + pub index_type: IndexType, +} + +/// The dynamic state a draw records before it: the viewport and scissor, the cull mode, the +/// front face, the depth and stencil tests, the stencil references, the blend constants, and the +/// depth bias the encoder does not set. +const VIEWPORT: u32 = 1; +const CULL: u32 = 2; +const FRONT: u32 = 4; +const TESTS: u32 = 8; +const REFERENCE: u32 = 16; +const BLEND: u32 = 32; +const BIAS: u32 = 64; +const ALL: u32 = 127; + +/// What a buffer slot holds. +#[derive(Clone, Default)] +enum Bound { + #[default] + Empty, + Buffer { + buffer: Buffer, + offset: u64, + }, + /// A `set_*_bytes` copy in the parameter ring. + Bytes(Placed), +} + +/// One function's argument tables. +struct Tables { + buffers: Vec, + textures: Vec>, + samplers: Vec>, +} + +impl Tables { + fn new() -> Tables { + Tables { + buffers: vec![Bound::Empty; BUFFER_SLOTS as usize], + textures: vec![None; TEXTURE_SLOTS as usize], + samplers: vec![None; SAMPLER_SLOTS as usize], + } + } + + /// The buffer bound at `slot`, where a buffer is. + fn buffer(&self, slot: u32) -> Option<&Buffer> { + match self.buffers.get(slot as usize) { + Some(Bound::Buffer { buffer, .. }) => Some(buffer), + _ => None, + } + } + + /// The texture bound at `slot`, where one is. + fn texture(&self, slot: u32) -> Option<&Texture> { + self.textures.get(slot as usize)?.as_ref() + } + + /// The address of buffer slot `slot`: the buffer's plus its offset, or the bytes' copy; 0 + /// where none is bound. + fn address(&self, slot: u32) -> u64 { + match self.buffers.get(slot as usize) { + Some(Bound::Buffer { buffer, offset }) => buffer.gpu_address().wrapping_add(*offset), + Some(Bound::Bytes(placed)) => placed.address, + Some(Bound::Empty) | None => 0, + } + } +} + +/// What a draw draws. +#[derive(Clone, Copy)] +enum Call<'a> { + Direct { + vertex_start: u32, + vertex_count: u32, + }, + Indexed { + index_count: u32, + indices: IndexBuffer<'a>, + base_vertex: i32, + }, +} + /// `MTLRenderCommandEncoder`: one dynamic rendering into its pass's attachments, begun as the /// encoder is made, with each attachment's load action, and ended by -/// [`end_encoding`](Self::end_encoding), with each one's store action. +/// [`end_encoding`](Self::end_encoding), with each one's store action; its draws record into it. /// /// It orders itself against every command before and after it with a barrier of its own on each /// side, as a blit's copy does: it needs no hazard tracking of its own and leaves none for the -/// encoders after it. +/// encoders after it. Its draws take no barrier between them, as Metal orders none: a draw sees +/// what an earlier draw of the encoder wrote after a +/// [`memory_barrier`](Self::memory_barrier). /// -/// Not built yet: every call but [`end_encoding`](Self::end_encoding). A pass renders its load -/// and store actions alone. +/// Built: a render pipeline state, the vertex and fragment functions' buffers, bytes, textures +/// and sampler states, one viewport and scissor rectangle, the cull mode, the front-facing +/// winding, a depth-stencil state that tests the stencil, the stencil references, the blend color, +/// memory barriers, fences, and direct draws of lines and triangles, indexed or not. Not built, +/// and so not methods: indirect draws, several viewports or scissor rectangles, the triangle fill +/// mode, the depth clip mode, depth bias, visibility results, `useResource:`, the store action +/// setters, tile functions and the `setVertexBuffer:offset:attributeStride:atIndex:` family. A +/// draw of what the runtime does not build is [`Gap::Draw`], naming its [`DrawKind`]. /// /// Owned: one thread encodes at a time. Dropping it ends it, as /// [`end_encoding`](Self::end_encoding) does. @@ -34,10 +192,35 @@ pub struct RenderCommandEncoder { command_buffer: CommandBuffer, /// What the command buffer records, held while the encoder is open. building: Option, - /// The checked pass, for its second barrier. + /// The checked pass, for its second barrier and to begin its rendering again. pass: Pass, /// The command buffer the pass records into. command: vk::CommandBuffer, + /// The vertex function's argument tables, then the fragment function's. + tables: [Tables; 2], + pipeline: Option, + /// Whether the pipeline state renders into the pass's attachments' formats. + renders_into: bool, + /// The depth-stencil state's tests, Metal's default state's where none is set. + tests: Tests, + viewport: Viewport, + /// Metal's scissor rectangle cut to the render area, per axis `[first, end)`. + scissor: [[u32; 2]; 2], + cull_mode: CullMode, + winding: Winding, + /// The front and back stencil references, saturated to 8 bits. + stencil_reference: [u32; 2], + blend_color: [f32; 4], + /// The dynamic state to record before the next draw. + dirty: u32, + /// The topology and primitive restart the last draw set. + topology: Option<(vk::PrimitiveTopology, bool)>, + /// A draw since the rendering began wrote memory: a memory barrier ends the rendering. + wrote: bool, + /// The fixed-function vertex buffers of the draw being recorded: binding, buffer and offset. + vertex_buffers: Vec<(u32, vk::Buffer, u64)>, + /// The push bytes of the draw being recorded. + push: Vec, } impl CommandBuffer { @@ -61,12 +244,37 @@ impl CommandBuffer { ) -> Result { let mut building = self.open_encoder()?; match begin(&mut building, descriptor) { - Ok((pass, command)) => Ok(RenderCommandEncoder { - command_buffer: self.clone(), - building: Some(building), - pass, - command, - }), + Ok((pass, command)) => { + let [width, height] = pass.area; + Ok(RenderCommandEncoder { + command_buffer: self.clone(), + building: Some(building), + command, + tables: [Tables::new(), Tables::new()], + pipeline: None, + renders_into: false, + tests: Tests::of(&DepthStencilDescriptor::default()), + viewport: Viewport { + origin_x: 0.0, + origin_y: 0.0, + width: f64::from(width), + height: f64::from(height), + znear: 0.0, + zfar: 1.0, + }, + scissor: [[0, width], [0, height]], + cull_mode: CullMode::None, + winding: Winding::Clockwise, + stencil_reference: [0; 2], + blend_color: [0.0; 4], + dirty: ALL, + topology: None, + wrote: false, + vertex_buffers: Vec::new(), + push: Vec::new(), + pass, + }) + } Err(error) => { self.close_encoder(building); Err(error) @@ -103,26 +311,10 @@ fn begin( .filter(|t| t.moves()) .map(|t| t.barrier(t.attachment.home, t.layout)) .collect(); - let colors: Vec = (pass.colors.iter()) - .map(|c| c.as_ref().map_or_else(Default::default, |t| t.info())) - .collect(); - let stencil = pass.stencil.as_ref().map(|t| t.info()); - let [width, height] = pass.area; - let mut info = vk::RenderingInfo::default() - .render_area(vk::Rect2D { - offset: vk::Offset2D { x: 0, y: 0 }, - extent: vk::Extent2D { width, height }, - }) - .layer_count(1) - .color_attachments(&colors); - if let Some(stencil) = &stencil { - info = info.stencil_attachment(stencil); - } let device = &core.device; // SAFETY: the command buffer records outside any render pass and keeps each attachment's - // texture until it retires; each attachment is a view of one level and layer of its image, - // in its home layout between commands, which the barrier moves to the layout the pass names; - // the render area lies inside every attachment. + // texture until it retires; each attachment is in its home layout between commands, which + // the barrier moves to the layout the pass names. unsafe { device.cmd_pipeline_barrier2( command, @@ -130,13 +322,850 @@ fn begin( .memory_barriers(&earlier) .image_memory_barriers(&away), ); - device.cmd_begin_rendering(command, &info); + pass.begin(device, command, false); } core.counters.count(Metric::Barriers); Ok((pass, command)) } impl RenderCommandEncoder { + fn building(&mut self) -> &mut Building { + self.building + .as_mut() + .expect("an encoder holds its command buffer's recording until it ends") + } + + /// `setRenderPipelineState:`. The command buffer keeps the state until it retires. + /// + /// Err: [`Refusal::OtherDevice`] for another device's state. + pub fn set_render_pipeline_state(&mut self, state: &RenderPipelineState) -> Result<(), Error> { + if !state.is_of(self.building().device.core()) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + if self.pipeline.as_ref().is_some_and(|set| set.is(state)) { + return Ok(()); + } + self.building().keep_render_pipeline(state); + self.renders_into = state.inner.compiled.renders_into(&self.pass); + self.pipeline = Some(state.clone()); + Ok(()) + } + + /// `setVertexBuffer:offset:atIndex:` (`setVertexBuffers:offsets:withRange:` is a loop of it). + /// `None` unbinds the slot. The slot serves the vertex function's buffer argument of its index + /// and the vertex descriptor's layout of its index alike. The command buffer keeps the buffer's + /// block until it retires. + /// + /// Err: [`Refusal::BufferIndex`] for an index of 31 or more; [`Refusal::OtherDevice`] for + /// another device's buffer. + pub fn set_vertex_buffer( + &mut self, + buffer: Option<&Buffer>, + offset: u64, + index: u32, + ) -> Result<(), Error> { + self.set_buffer(VERTEX, buffer, offset, index) + } + + /// `setFragmentBuffer:offset:atIndex:` (`setFragmentBuffers:offsets:withRange:` is a loop of + /// it), as [`set_vertex_buffer`](Self::set_vertex_buffer) for the fragment function. + /// + /// Err: as [`set_vertex_buffer`](Self::set_vertex_buffer). + pub fn set_fragment_buffer( + &mut self, + buffer: Option<&Buffer>, + offset: u64, + index: u32, + ) -> Result<(), Error> { + self.set_buffer(FRAGMENT, buffer, offset, index) + } + + fn set_buffer( + &mut self, + table: usize, + buffer: Option<&Buffer>, + offset: u64, + index: u32, + ) -> Result<(), Error> { + let slot = slot(index)?; + let bound = match buffer { + Some(buffer) => { + let building = self.building(); + if !buffer.is_of(building.device.core()) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + building.keep(buffer); + Bound::Buffer { + buffer: buffer.clone(), + offset, + } + } + None => Bound::Empty, + }; + self.tables[table].buffers[slot] = bound; + Ok(()) + } + + /// `setVertexBufferOffset:atIndex:`. + /// + /// Err: [`Refusal::BufferIndex`] for an index of 31 or more; [`Refusal::NoBufferAtIndex`] + /// where no buffer is bound there. + pub fn set_vertex_buffer_offset(&mut self, offset: u64, index: u32) -> Result<(), Error> { + self.set_buffer_offset(VERTEX, offset, index) + } + + /// `setFragmentBufferOffset:atIndex:`. + /// + /// Err: as [`set_vertex_buffer_offset`](Self::set_vertex_buffer_offset). + pub fn set_fragment_buffer_offset(&mut self, offset: u64, index: u32) -> Result<(), Error> { + self.set_buffer_offset(FRAGMENT, offset, index) + } + + fn set_buffer_offset(&mut self, table: usize, offset: u64, index: u32) -> Result<(), Error> { + match &mut self.tables[table].buffers[slot(index)?] { + Bound::Buffer { offset: bound, .. } => { + *bound = offset; + Ok(()) + } + _ => Err(Error::Refused(Refusal::NoBufferAtIndex { index })), + } + } + + /// `setVertexBytes:length:atIndex:`: the bytes are copied into the parameter ring now, as + /// Metal copies them, and the slot is the copy, for the vertex function's argument and the + /// vertex descriptor's layout alike. + /// + /// Err: [`Refusal::BufferIndex`] for an index of 31 or more; [`Limit::BytesLength`] past one + /// ring chunk (64 KiB; Metal documents the call for data under 4 KB); + /// [`Limit::MemoryAllocations`] where the ring's next block would take the device past its + /// allocation count; [`Error::Vulkan`] where the ring cannot grow. + pub fn set_vertex_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> { + self.set_bytes(VERTEX, bytes, index) + } + + /// `setFragmentBytes:length:atIndex:`, as [`set_vertex_bytes`](Self::set_vertex_bytes) for + /// the fragment function. + /// + /// Err: as [`set_vertex_bytes`](Self::set_vertex_bytes). + pub fn set_fragment_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> { + self.set_bytes(FRAGMENT, bytes, index) + } + + fn set_bytes(&mut self, table: usize, bytes: &[u8], index: u32) -> Result<(), Error> { + let slot = slot(index)?; + if bytes.len() as u64 > CHUNK { + return Err(Error::Limit(Limit::BytesLength { + len: bytes.len() as u64, + max: CHUNK, + })); + } + let placed = self.building().write_ring_placed(bytes)?; + self.tables[table].buffers[slot] = Bound::Bytes(placed); + Ok(()) + } + + /// `setVertexTexture:atIndex:` (`setVertexTextures:withRange:` is a loop of it). `None` + /// unbinds the slot. A draw pushes the texture's `gpuResourceID` for each texture slot its + /// vertex function reads, and the channel widths an integer write saturates to where the + /// function takes them. The command buffer keeps the texture until it retires. + /// + /// Err: [`Refusal::TextureArgumentIndex`] for an index of 128 or more; + /// [`Refusal::OtherDevice`] for another device's texture. + pub fn set_vertex_texture( + &mut self, + texture: Option<&Texture>, + index: u32, + ) -> Result<(), Error> { + self.set_texture(VERTEX, texture, index) + } + + /// `setFragmentTexture:atIndex:` (`setFragmentTextures:withRange:` is a loop of it), as + /// [`set_vertex_texture`](Self::set_vertex_texture) for the fragment function. + /// + /// Err: as [`set_vertex_texture`](Self::set_vertex_texture). + pub fn set_fragment_texture( + &mut self, + texture: Option<&Texture>, + index: u32, + ) -> Result<(), Error> { + self.set_texture(FRAGMENT, texture, index) + } + + fn set_texture( + &mut self, + table: usize, + texture: Option<&Texture>, + index: u32, + ) -> Result<(), Error> { + if index >= TEXTURE_SLOTS { + return Err(Error::Refused(Refusal::TextureArgumentIndex { index })); + } + if let Some(texture) = texture { + let building = self.building(); + if !texture.is_of(building.device.core()) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + building.keep_texture(texture); + } + self.tables[table].textures[index as usize] = texture.cloned(); + Ok(()) + } + + /// `setVertexSamplerState:atIndex:` (`setVertexSamplerStates:withRange:` is a loop of it). + /// `None` unbinds the slot. A draw pushes the state's `gpuResourceID` for each sampler slot its + /// vertex function samples through. The command buffer keeps the state until it retires. + /// + /// Err: [`Refusal::SamplerArgumentIndex`] for an index of 16 or more; + /// [`Refusal::OtherDevice`] for another device's state. + pub fn set_vertex_sampler_state( + &mut self, + sampler: Option<&SamplerState>, + index: u32, + ) -> Result<(), Error> { + self.set_sampler_state(VERTEX, sampler, index) + } + + /// `setFragmentSamplerState:atIndex:` (`setFragmentSamplerStates:withRange:` is a loop of + /// it), as [`set_vertex_sampler_state`](Self::set_vertex_sampler_state) for the fragment + /// function. + /// + /// Err: as [`set_vertex_sampler_state`](Self::set_vertex_sampler_state). + pub fn set_fragment_sampler_state( + &mut self, + sampler: Option<&SamplerState>, + index: u32, + ) -> Result<(), Error> { + self.set_sampler_state(FRAGMENT, sampler, index) + } + + fn set_sampler_state( + &mut self, + table: usize, + sampler: Option<&SamplerState>, + index: u32, + ) -> Result<(), Error> { + if index >= SAMPLER_SLOTS { + return Err(Error::Refused(Refusal::SamplerArgumentIndex { index })); + } + if let Some(sampler) = sampler { + let building = self.building(); + if !sampler.is_of(building.device.core()) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + building.keep_sampler(sampler); + } + self.tables[table].samplers[index as usize] = sampler.cloned(); + Ok(()) + } + + /// `setViewport:`. Metal's default covers the render area with the depth range `[0, 1]`. A + /// viewport of no width or height draws nothing, as Metal's; so does one whose origin's x is + /// NaN, as plain Metal draws nothing through it. A negative height flips the draw, as Metal's. + /// + /// Err: [`Refusal::ViewportNotFinite`] for any other field NaN or infinite; [`Gap::Draw`] of + /// [`DrawKind::Viewport`] for a negative width, a depth range past `[0, 1]`, or bounds past + /// the device's `maxViewportDimensions` and `viewportBoundsRange`. + pub fn set_viewport(&mut self, viewport: Viewport) -> Result<(), Error> { + let v = match viewport.origin_x.is_nan() { + true => Viewport { + origin_x: 0.0, + width: 0.0, + ..viewport + }, + false => viewport, + }; + let fields = [v.origin_x, v.origin_y, v.width, v.height, v.znear, v.zfar]; + if fields.iter().any(|f| !f.is_finite()) { + return Err(Error::Refused(Refusal::ViewportNotFinite)); + } + let core = Arc::clone(self.building().device.core()); + let limits = &core.limits; + let [low, high] = limits.viewport_bounds.map(f64::from); + let vk = vk_viewport(&v); + let [x, y, width, height] = [vk.x, vk.y, vk.width, vk.height].map(f64::from); + let unit = 0.0..=1.0; + let fits = v.width >= 0.0 + && unit.contains(&v.znear) + && unit.contains(&v.zfar) + && width <= f64::from(limits.max_viewport[0]) + && height.abs() <= f64::from(limits.max_viewport[1]) + && x >= low + && x + width <= high + && [y, y + height].iter().all(|y| (low..=high).contains(y)); + if !fits { + return Err(Error::Unsupported(Gap::Draw { + kind: DrawKind::Viewport, + })); + } + self.viewport = v; + self.dirty |= VIEWPORT; + Ok(()) + } + + /// `setScissorRect:`. Metal's default is the render area. A rectangle past the render area, + /// which Metal's validation stops, is cut to it, as plain Metal cuts it. + pub fn set_scissor_rect(&mut self, rect: ScissorRect) { + let [width, height] = self.pass.area; + let cut = |origin: u64, size: u64, limit: u32| { + let limit = u64::from(limit); + [origin.min(limit), origin.saturating_add(size).min(limit)].map(|at| at as u32) + }; + self.scissor = [ + cut(rect.x, rect.width, width), + cut(rect.y, rect.height, height), + ]; + self.dirty |= VIEWPORT; + } + + /// `setCullMode:`. Metal's default culls nothing. + pub fn set_cull_mode(&mut self, mode: CullMode) { + self.cull_mode = mode; + self.dirty |= CULL; + } + + /// `setFrontFacingWinding:`. Metal's default is clockwise. + pub fn set_front_facing_winding(&mut self, winding: Winding) { + self.winding = winding; + self.dirty |= FRONT; + } + + /// `setDepthStencilState:`; `None` sets Metal's default state again, which tests nothing. + /// + /// Err: [`Refusal::OtherDevice`] for another device's state. + pub fn set_depth_stencil_state( + &mut self, + state: Option<&DepthStencilState>, + ) -> Result<(), Error> { + self.tests = match state { + Some(state) => { + if !state.is_of(self.building().device.core()) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + state.tests() + } + None => Tests::of(&DepthStencilDescriptor::default()), + }; + self.dirty |= TESTS; + Ok(()) + } + + /// `setStencilReferenceValue:`: both faces' reference, saturated to 255 as Metal stores it. + pub fn set_stencil_reference_value(&mut self, value: u32) { + self.set_stencil_front_back_reference_value(value, value); + } + + /// `setStencilFrontReferenceValue:backReferenceValue:`, each saturated to 255. + pub fn set_stencil_front_back_reference_value(&mut self, front: u32, back: u32) { + self.stencil_reference = [front.min(255), back.min(255)]; + self.dirty |= REFERENCE; + } + + /// `setBlendColorRed:green:blue:alpha:`. Metal's default is zero. + pub fn set_blend_color(&mut self, red: f32, green: f32, blue: f32, alpha: f32) { + self.blend_color = [red, green, blue, alpha]; + self.dirty |= BLEND; + } + + /// `memoryBarrierWithScope:afterStages:beforeStages:` and + /// `memoryBarrierWithResources:count:afterStages:beforeStages:`: after a draw of the encoder + /// that wrote memory, the rendering ends, one global memory barrier is recorded, and the + /// rendering begins again, loading what it stored; after none, nothing is recorded, as the + /// pass's first barrier ordered everything before it. + /// + /// Err: [`Error::Vulkan`] where the command buffer cannot record. + pub fn memory_barrier(&mut self) -> Result<(), Error> { + if !self.wrote { + return Ok(()); + } + self.interrupt(|building| { + let command = building.ordered_command()?; + building.barrier(command, Reach::Commands); + Ok(()) + }) + } + + /// `updateFence:afterStages:`: encoders that wait on `fence` after this one see what this + /// encoder and the ones before it wrote. It records nothing ([`Fence`]): the pass's second + /// barrier already reaches them. + /// + /// Err: [`Refusal::OtherDevice`] for another device's fence; [`Gap::FenceOtherQueue`] for a + /// fence another queue used first. + pub fn update_fence(&mut self, fence: &Fence) -> Result<(), Error> { + let core = Arc::clone(self.building().device.core()); + fence.used_on(&core, self.command_buffer.queue()) + } + + /// `waitForFence:beforeStages:`: this encoder sees what the encoders up to `fence`'s last + /// update wrote. It records nothing ([`Fence`]): the pass's first barrier already orders them. + /// + /// Err: as [`update_fence`](Self::update_fence). + pub fn wait_for_fence(&mut self, fence: &Fence) -> Result<(), Error> { + let core = Arc::clone(self.building().device.core()); + fence.used_on(&core, self.command_buffer.queue()) + } + + /// `drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:` (the shorter forms are + /// this call with one instance and a base instance of 0): one `vkCmdDraw`. A draw of no + /// vertices or no instances records nothing. + /// + /// The draw pushes its functions' fields (the addresses of their buffer slots plus their + /// offsets, the resource IDs of their textures and sampler states, and the indices of the + /// state's constexpr samplers), binds the vertex buffers the pipeline state's vertex + /// descriptor reads, and sets the dynamic state that changed. A draw of lines first makes + /// its content's line `VkPipeline`, where no draw made it before. + /// + /// Err: [`Refusal::NoPipeline`]; [`Refusal::NoBufferAtIndex`] for a vertex buffer the vertex + /// descriptor reads that is not bound; [`Refusal::VertexBufferOffset`]; + /// [`Refusal::StencilAttachment`]; [`Gap::Draw`] for what the runtime does not build, naming + /// it; [`Error::Vulkan`] where a pipeline cannot be made or the command buffer cannot record. + pub fn draw_primitives( + &mut self, + primitive_type: PrimitiveType, + vertex_start: u32, + vertex_count: u32, + instance_count: u32, + base_instance: u32, + ) -> Result<(), Error> { + let call = Call::Direct { + vertex_start, + vertex_count, + }; + self.draw(primitive_type, call, instance_count, base_instance) + } + + /// `drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:instanceCount:baseVertex:baseInstance:` + /// (the shorter forms are this call with one instance and bases of 0), its index buffer + /// arguments in `indices`: one `vkCmdDrawIndexed`. The index buffer counts as a read, and the + /// command buffer keeps it until it retires. A strip restarts at the all-ones index, as + /// Metal's. A draw of no indices or no instances records nothing. + /// + /// Err: as [`draw_primitives`](Self::draw_primitives); [`Refusal::OtherDevice`] for another + /// device's index buffer; [`Refusal::IndexBufferOffset`]. + pub fn draw_indexed_primitives( + &mut self, + primitive_type: PrimitiveType, + index_count: u32, + indices: IndexBuffer<'_>, + instance_count: u32, + base_vertex: i32, + base_instance: u32, + ) -> Result<(), Error> { + let call = Call::Indexed { + index_count, + indices, + base_vertex, + }; + self.draw(primitive_type, call, instance_count, base_instance) + } + + fn draw( + &mut self, + primitive_type: PrimitiveType, + call: Call<'_>, + instance_count: u32, + base_instance: u32, + ) -> Result<(), Error> { + let state = (self.pipeline.clone()).ok_or(Error::Refused(Refusal::NoPipeline))?; + let compiled = &state.inner.compiled; + let draws = &compiled.draws; + let gap = |kind| Err(Error::Unsupported(Gap::Draw { kind })); + if !self.renders_into { + return gap(DrawKind::AttachmentFormats); + } + let (topology, restart) = input_assembly(primitive_type); + let topology = vk::PrimitiveTopology::from_raw(topology.as_raw()); + if topology == vk::PrimitiveTopology::POINT_LIST { + return gap(DrawKind::Points); + } + if self.tests.depth { + return gap(DrawKind::DepthTest); + } + if self.tests.stencil && self.pass.stencil.is_none() { + return Err(Error::Refused(Refusal::StencilAttachment)); + } + let core = Arc::clone(self.building().device.core()); + // The index buffer: its `VkBuffer`, the offset there, and the index type. + let index = match call { + Call::Direct { .. } => None, + Call::Indexed { + index_count, + indices: + IndexBuffer { + buffer, + offset, + index_type, + }, + .. + } => { + if !buffer.is_of(&core) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + let size = match index_type { + IndexType::UInt16 => 2, + IndexType::UInt32 => 4, + }; + let end = u64::from(index_count) + .checked_mul(size) + .and_then(|bytes| offset.checked_add(bytes)); + if offset % size != 0 || end.is_none_or(|end| end > buffer.length()) { + return Err(Error::Refused(Refusal::IndexBufferOffset { + offset, + length: buffer.length(), + })); + } + let (reached, at) = buffer.device_range(); + let ty = metal2vulkan::metal::state::index_type(index_type); + Some(( + buffer, + reached, + at + offset, + vk::IndexType::from_raw(ty.as_raw()), + )) + } + }; + // The vertex buffers the vertex descriptor reads. + self.vertex_buffers.clear(); + for &(binding, index) in &draws.bindings { + let (buffer, offset) = match self.tables[VERTEX].buffers.get(index as usize) { + Some(Bound::Buffer { buffer, offset }) => { + if *offset >= buffer.length() { + return Err(Error::Refused(Refusal::VertexBufferOffset { + index, + offset: *offset, + length: buffer.length(), + })); + } + let (reached, at) = buffer.device_range(); + (reached, at + offset) + } + Some(Bound::Bytes(placed)) => (placed.buffer, placed.offset), + Some(Bound::Empty) | None => { + return Err(Error::Refused(Refusal::NoBufferAtIndex { index })) + } + }; + self.vertex_buffers.push((binding, buffer, offset)); + } + // A texture the pass renders into, read or written as the pass renders it, is a feedback + // loop the runtime does not build. + let tables = &self.tables; + let rendered = (draws.textures.iter()).any(|&(table, slot, _)| { + tables[table].texture(slot).is_some_and(|texture| { + (self.pass.targets()).any(|t| t.texture.hazard_id() == texture.hazard_id()) + }) + }); + if rendered { + return gap(DrawKind::AttachmentRead); + } + let count = match call { + Call::Direct { vertex_count, .. } => vertex_count, + Call::Indexed { index_count, .. } => index_count, + }; + if count == 0 || instance_count == 0 { + return Ok(()); + } + let pipeline = compiled.pipeline(topology)?; + // The copies the draw needs first: its textures over a buffer in an image of their own + // (`crate::over`), and the textures over a Managed buffer's device copy it reaches + // (`crate::over::ManagedOvers`), each recorded between the rendering's end and its new + // beginning. + let building = (self.building.as_mut()) + .expect("an encoder holds its command buffer's recording until it ends"); + let vertex_reads = (draws.bindings.iter()) + .filter_map(|&(_, index)| tables[VERTEX].buffer(index)) + .chain(index.map(|(buffer, ..)| buffer)); + let accesses: Vec<(u32, Access)> = match building.copies_over() { + false => Vec::new(), + true => (draws.buffers.iter()) + .filter_map(|&(table, slot, access)| { + Some((tables[table].buffer(slot)?.id(), access)) + }) + .chain( + (draws.textures.iter()).filter_map(|&(table, slot, access)| { + Some((tables[table].texture(slot)?.hazard_id(), access)) + }), + ) + .chain( + vertex_reads + .clone() + .map(|buffer| (buffer.id(), Access::Read)), + ) + .collect(), + }; + let unbound = draws.reads_unbound || draws.writes_unbound; + let copies = building.overs_owed(&accesses, unbound); + let mut backs = Vec::new(); + for &(table, slot, access) in &draws.buffers { + if let Some(buffer) = tables[table].buffer(slot) { + if buffer.managed_overs().is_some() { + backs.extend(over::backs(buffer, None, true)); + if access.writes() { + building.wrote_managed(buffer); + } + } + } + } + for buffer in vertex_reads { + if buffer.managed_overs().is_some() { + backs.extend(over::backs(buffer, None, true)); + } + } + for &(table, slot, access) in &draws.textures { + if let (true, Some(texture)) = (access.writes(), tables[table].texture(slot)) { + building.wrote_texture_managed(texture); + } + } + // A write the host may read once the command buffer completes: to a Shared buffer or a + // texture over one, or through an address outside the draw's resources. + let host = draws.writes_unbound + || (draws.buffers.iter()).any(|&(table, slot, access)| { + access.writes() && tables[table].buffer(slot).is_some_and(Buffer::is_shared) + }) + || (draws.textures.iter()).any(|&(table, slot, access)| { + access.writes() && tables[table].texture(slot).is_some_and(Texture::host_reads) + }); + if !copies.is_empty() || !backs.is_empty() { + self.interrupt(|building| { + building.record_overs(copies)?; + building.managed_backs(backs) + })?; + } + let building = (self.building.as_mut()) + .expect("an encoder holds its command buffer's recording until it ends"); + building.overs_after(&accesses, draws.writes_unbound); + if host { + building.wrote_host(); + } + self.wrote |= draws.writes_memory; + let (bind, first) = building.bind_graphics(pipeline); + self.fill_push(&state); + let device = &core.device; + let command = self.command; + // SAFETY: the command buffer is inside the pass's rendering, which the pipeline renders + // into (its formats are the attachments'), and keeps the pipeline state, every bound + // resource and set 1 until it retires; the layout and set 1 are the device's, set 1 of + // that layout and update-after-bind; the push bytes lie in the layout's one push range, + // of `PUSH_STAGES`; every vertex binding the pipeline reads is bound inside its buffer. + unsafe { + if first { + device.cmd_bind_descriptor_sets( + command, + vk::PipelineBindPoint::GRAPHICS, + core.layout, + 1, + &[core.arrays.set()], + &[], + ); + } + if bind { + device.cmd_bind_pipeline(command, vk::PipelineBindPoint::GRAPHICS, pipeline); + } + self.record_state(device, topology, restart); + for &(binding, buffer, offset) in &self.vertex_buffers { + device.cmd_bind_vertex_buffers(command, binding, &[buffer], &[offset]); + } + if !self.push.is_empty() { + device.cmd_push_constants(command, core.layout, PUSH_STAGES, 0, &self.push); + } + match (call, index) { + ( + Call::Indexed { + index_count, + base_vertex, + .. + }, + Some((_, buffer, offset, ty)), + ) => { + device.cmd_bind_index_buffer(command, buffer, offset, ty); + device.cmd_draw_indexed( + command, + index_count, + instance_count, + 0, + base_vertex, + base_instance, + ); + } + ( + Call::Direct { + vertex_start, + vertex_count, + }, + _, + ) => device.cmd_draw( + command, + vertex_count, + instance_count, + vertex_start, + base_instance, + ), + (Call::Indexed { .. }, None) => {} + } + } + Ok(()) + } + + /// Fills the push bytes of a draw of `state` from the tables. + fn fill_push(&mut self, state: &RenderPipelineState) { + let draws = &state.inner.compiled.draws; + let ids = &state.inner.numbered.ids; + let push = &mut self.push; + push.clear(); + push.resize(draws.push_len.next_multiple_of(4) as usize, 0); + for &(offset, table, value) in &draws.fields { + let tables = &self.tables[table]; + let at = offset as usize; + match value { + FieldValue::BufferAddress { slot, mask } => { + let address = tables.address(slot) & !mask; + push[at..at + 8].copy_from_slice(&address.to_le_bytes()); + } + FieldValue::TextureId(slot) => { + let id = (tables.texture(slot)).map_or(0, |t| t.gpu_resource_id().to_bits()); + push[at..at + 8].copy_from_slice(&id.to_le_bytes()); + } + FieldValue::SamplerId(slot) => { + let id = match tables.samplers.get(slot as usize) { + Some(Some(sampler)) => sampler.gpu_resource_id().to_bits(), + _ => 0, + }; + push[at..at + 8].copy_from_slice(&id.to_le_bytes()); + } + FieldValue::IntegerChannels(slot) => { + let word = (tables.texture(slot)) + .map_or(0, |t| integer_channels_word(t.descriptor().pixel_format)); + push[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + FieldValue::ConstexprSampler(place) => { + let index = ids.get(place).copied().unwrap_or(0); + push[at..at + 4].copy_from_slice(&index.to_le_bytes()); + } + // A render content has no dispatch region (`render::draws`). + FieldValue::DispatchRegion => {} + } + } + } + + /// Records the dynamic state that changed since the last draw, and the draw's topology and + /// primitive restart where they changed. + /// + /// # Safety + /// + /// The encoder's command buffer is inside its pass's rendering. + unsafe fn record_state( + &mut self, + device: &ash::Device, + topology: vk::PrimitiveTopology, + restart: bool, + ) { + let command = self.command; + let dirty = self.dirty; + self.dirty = 0; + let both = [vk::StencilFaceFlags::FRONT, vk::StencilFaceFlags::BACK]; + // SAFETY: the command buffer records; each state is dynamic in every render pipeline. + unsafe { + if dirty & VIEWPORT != 0 { + device.cmd_set_viewport(command, 0, &[vk_viewport(&self.viewport)]); + device.cmd_set_scissor(command, 0, &[self.vk_scissor()]); + } + if dirty & CULL != 0 { + let mode = match self.cull_mode { + CullMode::None => vk::CullModeFlags::NONE, + CullMode::Front => vk::CullModeFlags::FRONT, + CullMode::Back => vk::CullModeFlags::BACK, + }; + device.cmd_set_cull_mode(command, mode); + } + if dirty & FRONT != 0 { + let face = match self.winding { + Winding::Clockwise => vk::FrontFace::CLOCKWISE, + Winding::CounterClockwise => vk::FrontFace::COUNTER_CLOCKWISE, + }; + device.cmd_set_front_face(command, face); + } + if dirty & TESTS != 0 { + // No pass has a depth attachment: a state that tests depth draws nothing + // (`DrawKind::DepthTest`). + device.cmd_set_depth_test_enable(command, false); + device.cmd_set_depth_write_enable(command, false); + device.cmd_set_depth_compare_op(command, vk::CompareOp::ALWAYS); + device.cmd_set_stencil_test_enable(command, self.tests.stencil); + for (face, f) in both.iter().zip(&self.tests.faces) { + device.cmd_set_stencil_op( + command, + *face, + f.fail, + f.pass, + f.depth_fail, + f.compare, + ); + device.cmd_set_stencil_compare_mask(command, *face, f.compare_mask); + device.cmd_set_stencil_write_mask(command, *face, f.write_mask); + } + } + if dirty & REFERENCE != 0 { + for (face, reference) in both.iter().zip(self.stencil_reference) { + device.cmd_set_stencil_reference(command, *face, reference); + } + } + if dirty & BLEND != 0 { + device.cmd_set_blend_constants(command, &self.blend_color); + } + if dirty & BIAS != 0 { + device.cmd_set_depth_bias(command, 0.0, 0.0, 0.0); + device.cmd_set_depth_bias_enable(command, false); + } + if self.topology != Some((topology, restart)) { + device.cmd_set_primitive_topology(command, topology); + device.cmd_set_primitive_restart_enable(command, restart); + self.topology = Some((topology, restart)); + } + } + } + + /// The draw's scissor: Metal's rectangle cut to the pixels its viewport covers. + fn vk_scissor(&self) -> vk::Rect2D { + let pixels = viewport_pixels(&self.viewport, self.pass.area); + let [x, y] = [0, 1].map(|axis| { + let first = self.scissor[axis][0].max(pixels[axis][0]); + let end = self.scissor[axis][1].min(pixels[axis][1]); + [first, end.max(first)] + }); + // Each bound lies in the render area, which fits an `i32`. + vk::Rect2D { + offset: vk::Offset2D { + x: x[0] as i32, + y: y[0] as i32, + }, + extent: vk::Extent2D { + width: x[1] - x[0], + height: y[1] - y[0], + }, + } + } + + /// Ends the pass's rendering, has `record` record into the command buffer, and begins the + /// rendering again, loading what it stored; the rendering's draws since it began are + /// unwritten again. + fn interrupt( + &mut self, + record: impl FnOnce(&mut Building) -> Result<(), Error>, + ) -> Result<(), Error> { + let building = (self.building.as_mut()) + .expect("an encoder holds its command buffer's recording until it ends"); + let core = Arc::clone(building.device.core()); + // SAFETY: the command buffer is inside the pass's rendering, which nothing else records + // into while the encoder holds it. + unsafe { core.device.cmd_end_rendering(self.command) }; + let recorded = record(building); + // SAFETY: the command buffer records outside any rendering and keeps each attachment's + // texture until it retires; each attachment stays in the layout the pass renders it in, + // and what `record` recorded orders itself after the rendering and before the next by + // barriers of its own. + unsafe { self.pass.begin(&core.device, self.command, true) }; + self.wrote = false; + recorded + } + /// `endEncoding`: ends the pass, one `vkCmdEndRendering` and the pass's second barrier. pub fn end_encoding(mut self) { self.end(); @@ -153,9 +1182,9 @@ impl RenderCommandEncoder { .map(|t| t.barrier(t.layout, t.attachment.home)) .collect(); let device = &core.device; - // SAFETY: the command buffer is inside the pass `begin` recorded, which nothing else - // records into while the encoder holds it; each attachment the barrier moves is in the - // layout the pass rendered it in. + // SAFETY: the command buffer is inside the pass's rendering, which nothing else records + // into while the encoder holds it; each attachment the barrier moves is in the layout the + // pass rendered it in. unsafe { device.cmd_end_rendering(self.command); device.cmd_pipeline_barrier2( @@ -175,3 +1204,51 @@ impl Drop for RenderCommandEncoder { self.end(); } } + +/// The slot of buffer index `index`. +/// +/// Err: [`Refusal::BufferIndex`] for an index of 31 or more. +fn slot(index: u32) -> Result { + match index < BUFFER_SLOTS { + true => Ok(index as usize), + false => Err(Error::Refused(Refusal::BufferIndex { index })), + } +} + +/// The Vulkan viewport of `v`: its height negated, from `y + height`, so the draw follows Metal's +/// clip space; a viewport of no width or height takes one pixel, behind an empty scissor. +pub(crate) fn vk_viewport(v: &Viewport) -> vk::Viewport { + let width = if v.width == 0.0 { 1.0 } else { v.width }; + let height = if v.height == 0.0 { 1.0 } else { v.height }; + vk::Viewport { + x: v.origin_x as f32, + y: (v.origin_y + height) as f32, + width: width as f32, + height: (-height) as f32, + min_depth: v.znear as f32, + max_depth: v.zfar as f32, + } +} + +/// The pixels `v` covers in a render area of `extent`, per axis `[first, end)`: none for a +/// viewport of no width or height. +pub(crate) fn viewport_pixels(v: &Viewport, extent: [u32; 2]) -> [[u32; 2]; 2] { + let empty = v.width == 0.0 || v.height == 0.0; + let axis = |origin: f64, size: f64, limit: u32| { + let (low, high) = match size < 0.0 { + true => (origin + size, origin), + false => (origin, origin + size), + }; + let limit = f64::from(limit); + let first = low.floor().clamp(0.0, limit) as u32; + let end = high.ceil().clamp(0.0, limit) as u32; + match empty { + true => [first, first], + false => [first, end.max(first)], + } + }; + [ + axis(v.origin_x, v.width, extent[0]), + axis(v.origin_y, v.height, extent[1]), + ] +} diff --git a/crates/metal2vulkan-rt/src/ring.rs b/crates/metal2vulkan-rt/src/ring.rs index 485b9dc9e..bfde2165c 100644 --- a/crates/metal2vulkan-rt/src/ring.rs +++ b/crates/metal2vulkan-rt/src/ring.rs @@ -1,6 +1,7 @@ //! The parameter ring: memory of the floor's ring type (device-local, host-visible, coherent) that //! the host writes and the GPU reads by address. It holds parameter blocks longer than the push -//! range and the bytes of `set_bytes`. +//! range and the bytes of `set_bytes`, which a draw's vertex input also reads through the block's +//! buffer. //! //! The ring is made of 2 MiB blocks, each split into 64 KiB chunks. A command buffer takes chunks //! as it records, writes each byte once, and gives them back when it retires, so the GPU never @@ -39,11 +40,22 @@ struct RingBlock { memory: vk::DeviceMemory, } -/// A chunk: its device address and its host address. +/// A chunk: its device address, its host address, and its block's buffer with its offset there. #[derive(Clone, Copy)] pub(crate) struct Chunk { address: u64, host: Mapping, + buffer: vk::Buffer, + offset: u64, +} + +/// Where a write into the ring lies: its device address, and its block's buffer with its offset +/// there. +#[derive(Clone, Copy)] +pub(crate) struct Placed { + pub(crate) address: u64, + pub(crate) buffer: vk::Buffer, + pub(crate) offset: u64, } impl Ring { @@ -63,15 +75,23 @@ impl Ring { return Ok(chunk); } let (block, address, host) = make(core)?; + let buffer = block.buffer; state.blocks.push(block); for index in (1..BLOCK / CHUNK).rev() { state.free.push(Chunk { address: address + index * CHUNK, // SAFETY: the chunk lies in the block's mapping. host: Mapping::new(unsafe { host.at(index * CHUNK) }), + buffer, + offset: index * CHUNK, }); } - Ok(Chunk { address, host }) + Ok(Chunk { + address, + host, + buffer, + offset: 0, + }) } /// Takes back a retired command buffer's chunks. @@ -178,8 +198,8 @@ pub(crate) struct Writes { impl Writes { /// Copies `bytes`, at most a chunk, into the ring at an address aligned to 16 bytes, and - /// returns that address. - pub(crate) fn write(&mut self, core: &Core, bytes: &[u8]) -> Result { + /// returns where it lies. + pub(crate) fn write(&mut self, core: &Core, bytes: &[u8]) -> Result { let len = bytes.len() as u64; debug_assert!(len <= CHUNK); let start = self.used.next_multiple_of(ALIGN); @@ -195,13 +215,21 @@ impl Writes { (chunk, 0) } }; - let (Chunk { address, host }, offset) = chunk; + let (chunk, offset) = chunk; // SAFETY: `offset..offset + len` lies in the chunk, which this command buffer alone writes // until it retires, and which no pending work reads: its last command buffer retired. unsafe { - std::ptr::copy_nonoverlapping(bytes.as_ptr(), host.at(offset).as_ptr(), bytes.len()) + std::ptr::copy_nonoverlapping( + bytes.as_ptr(), + chunk.host.at(offset).as_ptr(), + bytes.len(), + ) }; - Ok(address + offset) + Ok(Placed { + address: chunk.address + offset, + buffer: chunk.buffer, + offset: chunk.offset + offset, + }) } /// Gives the chunks back once the command buffer retired or never ran. diff --git a/crates/metal2vulkan-rt/src/tests/draw.rs b/crates/metal2vulkan-rt/src/tests/draw.rs new file mode 100644 index 000000000..8e9dd4609 --- /dev/null +++ b/crates/metal2vulkan-rt/src/tests/draw.rs @@ -0,0 +1,724 @@ +//! Draws: the render encoder's state and its draws. +//! +//! - A viewport is Vulkan's with its height negated, from `y + height`; one of no width or height +//! is one pixel wide or high and covers no pixel; the pixels a viewport covers are its own, +//! fractional edges widened, cut to the render area. +//! - Under a device cfg, on every device of the cfg's kind, of the owned fixtures +//! `examples/runtime_examples.ll` and `engine/fca_vertex_unread_attribute.ll`: +//! - triangles whose vertex function reads its positions and colors from buffers by vertex ID +//! land where Metal's clip space puts them (y up): a direct draw, an indexed draw of 16-bit +//! indices through a scissor rectangle, and a direct draw through a viewport, which cuts it +//! to its pixels. The pass is one submission, its two barriers and the segment's end, makes no +//! pipeline and copies no byte of the runtime's own; a memory barrier after draws that wrote +//! no memory records nothing. +//! - a draw of lines makes its content's line `VkPipeline` once, a first-use wait, and draws +//! its row. +//! - a stencil state that replaces the stencil marks what a draw covers, and one that tests it +//! keeps a later draw to those pixels. +//! - a fragment function samples a texture through its constexpr sampler at the index the +//! consumer gave it: each pixel reads its own texel. +//! - a vertex function's `[[stage_in]]` attributes come from a vertex buffer, and from +//! `set_vertex_bytes`' copy. +//! - what Metal refuses is refused, and what a draw does not build is a gap: no pipeline state, +//! a pipeline state of other formats than the pass's, points, a depth test, a stencil test +//! without a stencil attachment, a misaligned index offset, a non-finite viewport and a +//! mirrored one. +//! +//! `llvm-as` assembles the fixtures; without it a device test skips visibly. + +use crate::render_encoder::{viewport_pixels, vk_viewport}; +use crate::Viewport; + +/// A viewport of `x`, `y`, `width` and `height`, depths 0 to 1. +fn viewport(x: f64, y: f64, width: f64, height: f64) -> Viewport { + Viewport { + origin_x: x, + origin_y: y, + width, + height, + znear: 0.0, + zfar: 1.0, + } +} + +/// Vulkan's viewport is Metal's flipped; one of no extent is a pixel that covers nothing. +#[test] +fn a_viewport_is_vulkans_flipped_and_covers_its_own_pixels() { + let v = vk_viewport(&viewport(2.0, 4.0, 8.0, 6.0)); + assert_eq!([v.x, v.y, v.width, v.height], [2.0, 10.0, 8.0, -6.0]); + // Metal's own flip is a positive Vulkan height. + let v = vk_viewport(&viewport(0.0, 8.0, 4.0, -8.0)); + assert_eq!([v.x, v.y, v.width, v.height], [0.0, 0.0, 4.0, 8.0]); + let v = vk_viewport(&viewport(1.0, 1.0, 0.0, 0.0)); + assert_eq!([v.width, v.height], [1.0, -1.0]); + // Fractional edges widen to whole pixels, cut to the area; no extent covers nothing. + assert_eq!( + viewport_pixels(&viewport(0.5, 1.25, 3.0, 2.5), [8, 8]), + [[0, 4], [1, 4]] + ); + assert_eq!( + viewport_pixels(&viewport(-4.0, 6.0, 16.0, 8.0), [8, 8]), + [[0, 8], [6, 8]] + ); + assert_eq!( + viewport_pixels(&viewport(0.0, 8.0, 4.0, -8.0), [8, 8]), + [[0, 4], [0, 8]] + ); + assert_eq!( + viewport_pixels(&viewport(2.0, 2.0, 0.0, 4.0), [8, 8]), + [[2, 2], [2, 2]] + ); +} + +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod on_device { + use crate::tests::blit::on_device::settled; + use crate::tests::command::on_device::{each_device, finished}; + use crate::{ + Block, Buffer, ColorAttachmentDescriptor, CommandBuffer, CompareFunction, CullMode, + DepthStencilDescriptor, Device, DrawKind, Error, FunctionDescriptor, Gap, IndexBuffer, + IndexClass, IndexType, Library, MemoryClass, NumberedSampler, PixelFormat, PrimitiveType, + Refusal, Region, RenderPassDescriptor, RenderPipelineDescriptor, RenderPipelineState, + ScissorRect, StageSource, StencilOperation, StorageMode, Texture, TextureDescriptor, + TextureType, TextureUsage, Viewport, + }; + use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues}; + use metal2vulkan::metal::{DataType, VertexFormat}; + use metal2vulkan::pipeline::{ + VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, + }; + use metal2vulkan_devtools::{engine_dir, fixtures_dir, llvm_assemble, AssembleError}; + use std::path::Path; + + /// The side of the targets. + const SIDE: u32 = 8; + /// The constexpr sampler's index the test gives `sampled_fragment`. + const CONSTEXPR: u32 = 3; + + /// The library of `ll`, or None where `llvm-as` is missing. + fn library(ll: &Path) -> Option { + match llvm_assemble(ll) { + Ok(bitcode) => Some(Library::from_air(&bitcode).expect("the library")), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(error) => panic!("{}: {error:?}", ll.display()), + } + } + + fn examples() -> Option { + library(&fixtures_dir().join("examples/runtime_examples.ll")) + } + + /// `colored_vertex` with `fragment`, drawing into one colour attachment of `color`. + fn descriptor( + library: &Library, + fragment: &str, + color: PixelFormat, + ) -> RenderPipelineDescriptor { + let function = |name| { + StageSource::Function(FunctionDescriptor::new( + library.function(name).expect("the function"), + )) + }; + let mut d = RenderPipelineDescriptor::new(function("colored_vertex")); + d.fragment = Some(function(fragment)); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(color)); + d + } + + fn state(name: &str, device: &Device, d: &RenderPipelineDescriptor) -> RenderPipelineState { + (device.new_render_pipeline_state(d, crate::tests::no_constexpr_samplers)) + .unwrap_or_else(|error| panic!("{name}: {error}")) + } + + /// Shared buffers in one block, 256 bytes apart. + struct Buffers { + block: Block, + next: u64, + } + + impl Buffers { + fn new(device: &Device) -> Buffers { + Buffers { + block: (device.take_block(MemoryClass::Shared, 65536)).expect("a block"), + next: 0, + } + } + + /// A buffer of `bytes`. + fn of(&mut self, device: &Device, bytes: &[u8]) -> Buffer { + let len = bytes.len() as u64; + let buffer = + (device.new_buffer(self.block.id, self.next, len, true)).expect("a buffer"); + self.next += len.next_multiple_of(256); + let contents = buffer.contents().expect("a Shared buffer"); + // SAFETY: the range lies in the buffer, which is alive, and no GPU work uses it. + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) + }; + buffer + } + } + + fn floats(values: &[f32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() + } + + /// A 2D render target of `format`, `SIDE` a side. + fn target(device: &Device, format: PixelFormat, usage: TextureUsage) -> Texture { + let mut d = TextureDescriptor::new(TextureType::Type2D, format, SIDE, SIDE); + d.usage = usage; + d.storage_mode = StorageMode::Shared; + (device.new_texture(&d, None)).unwrap_or_else(|error| panic!("{format:?}: {error}")) + } + + /// The texels of `texture`, `unit` bytes each. + fn read(texture: &Texture, unit: usize) -> Vec { + let row = SIDE as usize * unit; + let mut bytes = vec![0; row * SIDE as usize]; + let region = Region { + origin: [0; 3], + size: [SIDE, SIDE, 1], + }; + (texture.get_bytes( + &mut bytes, + row as u64, + (row * SIDE as usize) as u64, + region, + 0, + 0, + )) + .expect("get_bytes"); + bytes + } + + /// A pass that clears `color` to opaque black, with `stencil` cleared to 0 where given. + fn pass(color: &Texture, stencil: Option<&Texture>) -> RenderPassDescriptor { + let mut d = RenderPassDescriptor::default(); + let c = &mut d.color_attachments[0]; + c.texture = Some(color.clone()); + c.load_action = crate::LoadAction::Clear; + if let Some(stencil) = stencil { + d.stencil_attachment.texture = Some(stencil.clone()); + } + d + } + + /// `command_buffer` committed and complete with no error. + fn run(name: &str, command_buffer: &CommandBuffer) { + command_buffer.commit().expect("a commit"); + finished(name, command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + } + + /// The RGBA8 texel `color` of a float colour of 0 or 1 channels. + fn rgba8(color: [f32; 4]) -> [u8; 4] { + color.map(|c| (c * 255.0) as u8) + } + + const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; + const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; + const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; + const WHITE: [f32; 4] = [1.0; 4]; + + /// The fixture's vertices, positions and colors: the top half of clip space (y up) in green, + /// then the whole of it in blue and in white, three each. + fn vertices(device: &Device, buffers: &mut Buffers) -> (Buffer, Buffer) { + let top = [-1.0, 0.0, 3.0, 0.0, -1.0, 4.0]; + let whole = [-1.0, -1.0, 3.0, -1.0, -1.0, 3.0]; + let positions: Vec = [top, whole, whole].concat(); + let colors: Vec = [GREEN, BLUE, WHITE] + .iter() + .flat_map(|c| [*c; 3].concat()) + .collect(); + ( + buffers.of(device, &floats(&positions)), + buffers.of(device, &floats(&colors)), + ) + } + + /// The texels of `SIDE` rows of `SIDE` texels, `texel(x, y)` each. + fn texels(texel: impl Fn(u32, u32) -> [f32; 4]) -> Vec { + (0..SIDE) + .flat_map(|y| (0..SIDE).map(move |x| (x, y))) + .flat_map(|(x, y)| rgba8(texel(x, y))) + .collect() + } + + /// Triangles land where Metal's clip space puts them, through a scissor rectangle and a + /// viewport; the pass is three barriers, no pipeline made and no byte copied. + #[test] + fn every_device_draws_triangles_where_metal_puts_them() { + let Some(library) = examples() else { + return; + }; + let d = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm); + each_device("draw_triangles", |name, _, device| { + let state = state(name, &device, &d); + let mut buffers = Buffers::new(&device); + let (positions, colors) = vertices(&device, &mut buffers); + let indices = buffers.of(&device, &[3, 0, 4, 0, 5, 0, 0, 0]); + let color = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + let queue = device.new_command_queue(4).expect("a queue"); + let counters = device.counters(); + settled(&device); + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + draw(encoder.set_render_pipeline_state(&state)); + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + // The top half, green. + draw(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)); + draw(encoder.memory_barrier()); + // The whole target in blue, through the bottom-right quarter's rectangle. + encoder.set_scissor_rect(ScissorRect { + x: 4, + y: 4, + width: 4, + height: 40, + }); + let indexed = IndexBuffer { + buffer: &indices, + offset: 0, + index_type: IndexType::UInt16, + }; + draw(encoder.draw_indexed_primitives(PrimitiveType::Triangle, 3, indexed, 1, 0, 0)); + // The whole target in white, through the bottom-left quarter's viewport, which cuts + // it to its pixels. + encoder.set_scissor_rect(ScissorRect { + x: 0, + y: 0, + width: 8, + height: 8, + }); + draw(encoder.set_viewport(Viewport { + origin_x: 0.0, + origin_y: 4.0, + width: 4.0, + height: 4.0, + znear: 0.0, + zfar: 1.0, + })); + encoder.set_cull_mode(CullMode::None); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 6, 3, 1, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + let after = counters.metrics(); + assert_eq!( + ( + after.submissions - before.submissions, + after.barriers - before.barriers, + after.passes - before.passes, + after.pipelines_created - before.pipelines_created, + after.bytes_copied - before.bytes_copied, + ), + (1, 3, 1, 0, 0), + "{name}: submissions, barriers, passes, pipelines made, bytes copied" + ); + let want = texels(|x, y| match (x, y) { + (_, 0..4) => GREEN, + (0..4, _) => WHITE, + _ => BLUE, + }); + assert_eq!(read(&color, 4), want, "{name}: the texels"); + println!("{name}: three draws in one pass, 3 barriers, no pipeline made"); + }); + } + + /// A draw of lines makes the line pipeline once and draws its row. + #[test] + fn every_device_makes_its_line_pipeline_at_the_first_draw_of_lines() { + let Some(library) = examples() else { + return; + }; + let d = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm); + each_device("draw_lines", |name, _, device| { + let state = state(name, &device, &d); + // A line across row 2's centres, Metal's y up. + let y = 1.0 - 2.5 / 4.0; + let mut buffers = Buffers::new(&device); + let positions = buffers.of(&device, &floats(&[-1.0, y, 1.0, y])); + let colors = buffers.of(&device, &floats(&[GREEN, GREEN].concat())); + let color = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + let queue = device.new_command_queue(4).expect("a queue"); + let counters = device.counters(); + for round in 0..2 { + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let draw = + |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + draw(encoder.set_render_pipeline_state(&state)); + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + draw(encoder.draw_primitives(PrimitiveType::Line, 0, 2, 1, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + let after = counters.metrics(); + let made = u64::from(round == 0); + assert_eq!( + ( + after.pipelines_created - before.pipelines_created, + after.first_use_waits - before.first_use_waits, + ), + (made, made), + "{name}: round {round}: pipelines made, first-use waits" + ); + let texels = read(&color, 4); + let at = |x: u32, y: u32| { + let i = ((y * SIDE + x) * 4) as usize; + [texels[i], texels[i + 1], texels[i + 2], texels[i + 3]] + }; + for x in 1..SIDE - 1 { + assert_eq!(at(x, 2), rgba8(GREEN), "{name}: ({x}, 2)"); + assert_eq!(at(x, 5), rgba8(BLACK), "{name}: ({x}, 5)"); + } + } + println!("{name}: one line pipeline, made at the first draw of lines"); + }); + } + + /// A stencil state that replaces marks the top half; one that tests keeps a later draw there. + #[test] + fn every_device_marks_and_tests_the_stencil() { + let Some(library) = examples() else { + return; + }; + let plain = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm); + let mut d = plain.clone(); + d.stencil_format = Some(PixelFormat::Stencil8); + each_device("draw_stencil", |name, _, device| { + let state = state(name, &device, &d); + let mut buffers = Buffers::new(&device); + let (positions, colors) = vertices(&device, &mut buffers); + let color = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + let stencil = target(&device, PixelFormat::Stencil8, TextureUsage::RENDER_TARGET); + let mut replace = DepthStencilDescriptor::default(); + for face in [ + &mut replace.front_face_stencil, + &mut replace.back_face_stencil, + ] { + face.depth_stencil_pass_operation = StencilOperation::Replace; + } + let mut equal = DepthStencilDescriptor::default(); + for face in [&mut equal.front_face_stencil, &mut equal.back_face_stencil] { + face.stencil_compare_function = CompareFunction::Equal; + } + let (replace, equal) = ( + device.new_depth_stencil_state(&replace), + device.new_depth_stencil_state(&equal), + ); + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer + .render_command_encoder(&pass(&color, Some(&stencil)))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + draw(encoder.set_render_pipeline_state(&state)); + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + // 0x1a5 saturates to 255 as Metal stores it; the test compares what the first draw + // stored. + encoder.set_stencil_reference_value(0x1a5); + draw(encoder.set_depth_stencil_state(Some(&replace))); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)); + draw(encoder.set_depth_stencil_state(Some(&equal))); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + let want = texels(|_, y| match y { + 0..4 => BLUE, + _ => BLACK, + }); + assert_eq!(read(&color, 4), want, "{name}: the tested draw"); + if stencil.unit().is_some() { + let want: Vec = (0..SIDE * SIDE) + .map(|i| if i < SIDE * SIDE / 2 { 255 } else { 0 }) + .collect(); + assert_eq!(read(&stencil, 1), want, "{name}: the stencil"); + } + + // A stencil test in a pass without a stencil attachment is refused. + let plain = state(name, &device, &plain); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + draw(encoder.set_render_pipeline_state(&plain)); + draw(encoder.set_depth_stencil_state(Some(&equal))); + assert!( + matches!( + encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0), + Err(Error::Refused(Refusal::StencilAttachment)) + ), + "{name}: a stencil test without a stencil attachment" + ); + encoder.end_encoding(); + run(name, &command_buffer); + println!("{name}: the stencil marks and tests"); + }); + } + + /// Each pixel samples its own texel through the constexpr sampler at the consumer's index. + #[test] + fn every_device_samples_a_texture_through_a_constexpr_sampler_in_a_draw() { + let Some(library) = examples() else { + return; + }; + let d = descriptor(&library, "sampled_fragment", PixelFormat::RGBA16Float); + each_device("draw_sampled", |name, _, device| { + for (class, first) in [(IndexClass::Texture, 4096), (IndexClass::Sampler, 1)] { + (device.grant_indices(class, first, 4)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + } + let state = (device.new_render_pipeline_state(&d, |samplers| { + assert!( + matches!(samplers, [NumberedSampler::Constexpr(_)]), + "{name}: {samplers:?}" + ); + Ok(vec![CONSTEXPR]) + })) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let mut sd = + TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA16Float, SIDE, SIDE); + sd.usage = TextureUsage::SHADER_READ; + let source = (device.new_texture(&sd, Some(4096))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + // Each texel's channels in sixteenths, which a half holds exactly: x, y, x + y, 1. + let half = |k: u32| -> [u8; 2] { + match k { + 0 => [0, 0], + _ => { + let bits = (k as f32 / 16.0).to_bits(); + let exponent = ((bits >> 23) & 0xff) as i32 - 127 + 15; + (((exponent as u16) << 10) | ((bits >> 13) & 0x3ff) as u16).to_le_bytes() + } + } + }; + let bytes: Vec = (0..SIDE) + .flat_map(|y| (0..SIDE).map(move |x| (x, y))) + .flat_map(|(x, y)| [x, y, x + y, 16].into_iter().flat_map(half)) + .collect(); + let whole = Region { + origin: [0; 3], + size: [SIDE, SIDE, 1], + }; + let row = u64::from(SIDE * 8); + (source.replace_region(whole, 0, 0, &bytes, row, row * u64::from(SIDE))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let mut buffers = Buffers::new(&device); + let (positions, colors) = vertices(&device, &mut buffers); + let color = target( + &device, + PixelFormat::RGBA16Float, + TextureUsage::RENDER_TARGET, + ); + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + draw(encoder.set_render_pipeline_state(&state)); + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + draw(encoder.set_fragment_texture(Some(&source), 0)); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + assert_eq!(read(&color, 8), bytes, "{name}: each pixel its own texel"); + println!("{name}: a constexpr sampler at index {CONSTEXPR} sampled each texel"); + }); + } + + /// `[[stage_in]]` attributes come from a vertex buffer, and from `set_vertex_bytes`' copy. + #[test] + fn every_device_fetches_vertex_attributes_from_vertex_buffers_and_bytes() { + let Some(library) = library(&engine_dir().join("fca_vertex_unread_attribute.ll")) else { + return; + }; + let constants = FunctionConstantValues::defaults() + .with_index(0, FunctionConstantValue::new(DataType::Bool, [1])); + let function = |name| { + let mut f = FunctionDescriptor::new(library.function(name).expect("the function")); + f.constants = constants.clone(); + f.specialized = true; + StageSource::Function(f) + }; + let mut d = RenderPipelineDescriptor::new(function("fca_vertex_unread_attribute")); + d.fragment = Some(function("fca_fragment_unread_attribute")); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + let mut vertex = VertexDescriptor::new(); + for a in 0..2 { + let attribute = VertexAttributeDescriptor::new(VertexFormat::Float4, 16 * a, 0); + vertex.attributes.insert(a, attribute); + } + let layout = VertexBufferLayoutDescriptor::new(Some(32)); + vertex.layouts.insert(0, layout); + d.vertex_descriptor = Some(vertex); + // Three `{ position, color }` vertices that cover the target, `color` (1, 0, 0, 1), + // which the vertex function scales by 0.5 and biases by 0.25. + let red = [1.0, 0.0, 0.0, 1.0]; + let records: Vec = [[-1.0, -1.0], [3.0, -1.0], [-1.0, 3.0]] + .iter() + .flat_map(|[x, y]| [[*x, *y, 0.0, 1.0], red].concat()) + .collect(); + let records = floats(&records); + each_device("draw_stage_in", |name, _, device| { + let state = state(name, &device, &d); + let mut buffers = Buffers::new(&device); + let vertices = buffers.of(&device, &records); + let color = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + let queue = device.new_command_queue(4).expect("a queue"); + for bytes in [false, true] { + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let draw = + |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + draw(encoder.set_render_pipeline_state(&state)); + draw(match bytes { + false => encoder.set_vertex_buffer(Some(&vertices), 0, 0), + true => encoder.set_vertex_bytes(&records, 0), + }); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + // Metal's (191, 64, 64, 191), each channel within one code: near a tie the + // device may store the other code nearest it. + for texel in read(&color, 4).chunks(4) { + let near = (texel.iter().zip([191u8, 64, 64, 191])) + .all(|(&got, want)| got.abs_diff(want) <= 1); + assert!(near, "{name}: bytes {bytes}: {texel:?}"); + } + } + println!("{name}: attributes from a vertex buffer and from bytes"); + }); + } + + /// What Metal refuses is refused, and what a draw does not build is a gap. + #[test] + fn every_device_refuses_the_draws_it_does_not_build() { + let Some(library) = examples() else { + return; + }; + let plain = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm); + let other = descriptor(&library, "colored_fragment", PixelFormat::BGRA8Unorm); + each_device("draw_refused", |name, _, device| { + let state = state(name, &device, &plain); + let other = self::state(name, &device, &other); + let mut buffers = Buffers::new(&device); + let (positions, colors) = vertices(&device, &mut buffers); + let indices = buffers.of(&device, &[3, 0, 4, 0, 5, 0, 0, 0]); + let color = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + let mut depth = DepthStencilDescriptor::default(); + depth.depth_compare_function = CompareFunction::Less; + let depth = device.new_depth_stencil_state(&depth); + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let triangle = PrimitiveType::Triangle; + let gap = |kind| Err::<(), _>(Error::Unsupported(Gap::Draw { kind })); + let same = |got: Result<(), Error>, want: Result<(), Error>, case: &str| { + assert_eq!(format!("{got:?}"), format!("{want:?}"), "{name}: {case}"); + }; + same( + encoder.draw_primitives(triangle, 0, 3, 1, 0), + Err(Error::Refused(Refusal::NoPipeline)), + "no pipeline state", + ); + encoder.set_render_pipeline_state(&other).expect("a state"); + same( + encoder.draw_primitives(triangle, 0, 3, 1, 0), + gap(DrawKind::AttachmentFormats), + "another format", + ); + encoder.set_render_pipeline_state(&state).expect("a state"); + same( + encoder.draw_primitives(PrimitiveType::Point, 0, 3, 1, 0), + gap(DrawKind::Points), + "points", + ); + encoder + .set_depth_stencil_state(Some(&depth)) + .expect("a state"); + same( + encoder.draw_primitives(triangle, 0, 3, 1, 0), + gap(DrawKind::DepthTest), + "a depth test", + ); + encoder.set_depth_stencil_state(None).expect("no state"); + let viewport = Viewport { + origin_x: 0.0, + origin_y: 0.0, + width: 4.0, + height: 4.0, + znear: 0.0, + zfar: 1.0, + }; + same( + encoder.set_viewport(Viewport { + height: f64::INFINITY, + ..viewport + }), + Err(Error::Refused(Refusal::ViewportNotFinite)), + "an infinite height", + ); + same( + encoder.set_viewport(Viewport { + width: -4.0, + ..viewport + }), + gap(DrawKind::Viewport), + "a mirrored viewport", + ); + encoder + .set_vertex_buffer(Some(&positions), 0, 0) + .expect("a buffer"); + encoder + .set_vertex_buffer(Some(&colors), 0, 1) + .expect("a buffer"); + let misaligned = IndexBuffer { + buffer: &indices, + offset: 1, + index_type: IndexType::UInt16, + }; + same( + encoder.draw_indexed_primitives(triangle, 3, misaligned, 1, 0, 0), + Err(Error::Refused(Refusal::IndexBufferOffset { + offset: 1, + length: 8, + })), + "a misaligned index offset", + ); + encoder.end_encoding(); + run(name, &command_buffer); + println!("{name}: each draw refused by kind"); + }); + } +} diff --git a/crates/metal2vulkan-rt/src/tests/mod.rs b/crates/metal2vulkan-rt/src/tests/mod.rs index dae843850..628e3a96c 100644 --- a/crates/metal2vulkan-rt/src/tests/mod.rs +++ b/crates/metal2vulkan-rt/src/tests/mod.rs @@ -6,6 +6,7 @@ mod command; mod compute; mod copy_over; mod device; +mod draw; mod fence; mod floor; mod hazard; diff --git a/crates/metal2vulkan-rt/src/tests/pass.rs b/crates/metal2vulkan-rt/src/tests/pass.rs index 4c1a7bddb..1776cd238 100644 --- a/crates/metal2vulkan-rt/src/tests/pass.rs +++ b/crates/metal2vulkan-rt/src/tests/pass.rs @@ -1,8 +1,8 @@ //! Render passes: load and store actions, clear values, and what a pass does not build. //! -//! - Metal's load and store actions are Vulkan's of the same name, one to one; a resolving store -//! action is `Gap::RenderPass` of `Resolve`, `Unknown` and `CustomSampleDepthStore` of -//! `StoreAction`. +//! - Metal's load actions are Vulkan's of the same name, and both plain store actions store +//! (a pass that ends its rendering early loads what it stored); a resolving store action is +//! `Gap::RenderPass` of `Resolve`, `Unknown` and `CustomSampleDepthStore` of `StoreAction`. //! - A clear color is a `float` for a float, normalized or sRGB channel, rotated for a rotated //! format and for `A8Unorm` held in `R8_UNORM`; an integer channel's is truncated toward zero //! and saturated to its width, NaN 0; a format only a shader clears (extended range, bfloat) @@ -23,10 +23,10 @@ use crate::{ClearColor, LoadAction, PixelFormat, StoreAction}; use ash::vk; use metal2vulkan::metal::format::FormatEmulation; -/// Each load action and the two plain store actions are Vulkan's of the same name; the others -/// are gaps. +/// Each load action is Vulkan's of the same name, and the two plain store actions store; the +/// others are gaps. #[test] -fn load_and_store_actions_are_one_to_one() { +fn load_actions_are_one_to_one_and_plain_store_actions_store() { let pairs = [ (LoadAction::DontCare, vk::AttachmentLoadOp::DONT_CARE), (LoadAction::Load, vk::AttachmentLoadOp::LOAD), @@ -34,7 +34,7 @@ fn load_and_store_actions_are_one_to_one() { ]; for (load, op) in pairs { for (store, store_op) in [ - (StoreAction::DontCare, vk::AttachmentStoreOp::DONT_CARE), + (StoreAction::DontCare, vk::AttachmentStoreOp::STORE), (StoreAction::Store, vk::AttachmentStoreOp::STORE), ] { assert!( diff --git a/crates/metal2vulkan-rt/src/tests/render.rs b/crates/metal2vulkan-rt/src/tests/render.rs index aa8d41ab6..00a6c7309 100644 --- a/crates/metal2vulkan-rt/src/tests/render.rs +++ b/crates/metal2vulkan-rt/src/tests/render.rs @@ -9,8 +9,7 @@ //! - Filled past a cap of 2, the map holds 2 render contents and forgets the least recently used, //! which lives while a state holds it and goes once that state does; a forgotten content //! compiles again, and one the map holds does not. -//! - A depth attachment, more than one sample, or a fragment function with a constexpr sampler is -//! refused by kind, making no `VkPipeline`. +//! - A depth attachment or more than one sample is refused by kind, making no `VkPipeline`. //! - A device on a cache directory a device before it used lowers nothing at creation: both //! lowerings are read from the directory, and the triangle class's `VkPipeline` is made from //! its file; the first device writes one pipeline file for each `VkPipeline` it made, and the @@ -65,12 +64,13 @@ mod on_device { } fn state(name: &str, device: &Device, d: &RenderPipelineDescriptor) -> RenderPipelineState { - (device.new_render_pipeline_state(d)).unwrap_or_else(|error| panic!("{name}: {error}")) + (device.new_render_pipeline_state(d, crate::tests::no_constexpr_samplers)) + .unwrap_or_else(|error| panic!("{name}: {error}")) } /// Whether two states share their compiled content. fn shared(a: &RenderPipelineState, b: &RenderPipelineState) -> bool { - Arc::ptr_eq(&a.compiled, &b.compiled) + Arc::ptr_eq(&a.inner.compiled, &b.inner.compiled) } /// The lowerings (made and read from the cache directory) and the `VkPipeline`s from `before` @@ -144,7 +144,7 @@ mod on_device { gauges.render_contents + 1 + others.len() as u64, "{name}: a content each" ); - let compiled = Arc::clone(&a.compiled); + let compiled = Arc::clone(&a.inner.compiled); drop((a, b)); // The map holds it still, beside this test's handle. assert_eq!(Arc::strong_count(&compiled), 2, "{name}: held by the map"); @@ -223,7 +223,6 @@ mod on_device { depth.depth_format = Some(PixelFormat::Depth32Float); let mut samples = plain.clone(); samples.raster_sample_count = 4; - let sampled = descriptor(&library, "sampled_fragment", PixelFormat::RGBA16Float); let cases = [ ( "a depth attachment", @@ -231,13 +230,12 @@ mod on_device { RenderPipelineKind::DepthAttachment, ), ("four samples", samples, RenderPipelineKind::Multisample), - ("a constexpr sampler", sampled, RenderPipelineKind::Samplers), ]; each_device("render_refused", |name, _, device| { let counters = device.counters(); for (case, d, kind) in &cases { let before = counters.metrics().pipelines_created; - match device.new_render_pipeline_state(d) { + match device.new_render_pipeline_state(d, crate::tests::no_constexpr_samplers) { Err(Error::Unsupported(Gap::RenderPipeline { kind: refused })) => { assert_eq!(refused, *kind, "{name}: {case}") } diff --git a/crates/metal2vulkan-rt/src/texture.rs b/crates/metal2vulkan-rt/src/texture.rs index 125bda63a..ed11c38ec 100644 --- a/crates/metal2vulkan-rt/src/texture.rs +++ b/crates/metal2vulkan-rt/src/texture.rs @@ -221,6 +221,8 @@ pub(crate) struct Attachment { pub(crate) home: vk::ImageLayout, /// The level's width and height. pub(crate) extent: [u32; 2], + /// The image's format, the view's. + pub(crate) format: vk::Format, } /// A texture's bytes in a buffer, which [`Texture::replace_region`] and [`Texture::get_bytes`] @@ -2349,6 +2351,7 @@ impl Texture { aspects: image.aspects, home: image.home, extent: [(d.width >> level).max(1), (d.height >> level).max(1)], + format: self.inner.format, }) } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 0c651b7f1..32b9b57bf 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1413,6 +1413,7 @@ enum metal2vulkan-rt::CommandBufferStatus #[derive(Clone, Copy, Debug, PartialEq enum metal2vulkan-rt::CompareFunction #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum CompareFunction enum metal2vulkan-rt::ConsumerFeature #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ConsumerFeature enum metal2vulkan-rt::DispatchType #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DispatchType +enum metal2vulkan-rt::DrawKind #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum DrawKind enum metal2vulkan-rt::Error #[derive(Debug)] #[non_exhaustive] pub enum Error enum metal2vulkan-rt::Gap #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum Gap enum metal2vulkan-rt::IndexClass #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum IndexClass @@ -2269,6 +2270,10 @@ field metal2vulkan-rt::ComputePipelineDescriptor.stage_input pub stage_input: Op field metal2vulkan-rt::ComputePipelineDescriptor.support_adding_binary_functions pub support_adding_binary_functions: bool field metal2vulkan-rt::ComputePipelineDescriptor.support_indirect_command_buffers pub support_indirect_command_buffers: bool field metal2vulkan-rt::ComputePipelineDescriptor.threadgroup_size_is_multiple_of_execution_width pub threadgroup_size_is_multiple_of_execution_width: bool +field metal2vulkan-rt::DepthStencilDescriptor.back_face_stencil pub back_face_stencil: StencilDescriptor +field metal2vulkan-rt::DepthStencilDescriptor.depth_compare_function pub depth_compare_function: CompareFunction +field metal2vulkan-rt::DepthStencilDescriptor.depth_write_enabled pub depth_write_enabled: bool +field metal2vulkan-rt::DepthStencilDescriptor.front_face_stencil pub front_face_stencil: StencilDescriptor field metal2vulkan-rt::DeviceOptions.block_mappings pub block_mappings: Option> field metal2vulkan-rt::DeviceOptions.extensions pub extensions: Vec field metal2vulkan-rt::DeviceOptions.features pub features: Vec @@ -2302,6 +2307,9 @@ field metal2vulkan-rt::Gauges.textures pub textures: u64 field metal2vulkan-rt::HeapRange.block pub block: BlockId field metal2vulkan-rt::HeapRange.len pub len: u64 field metal2vulkan-rt::HeapRange.offset pub offset: u64 +field metal2vulkan-rt::IndexBuffer.buffer pub buffer: &'a Buffer +field metal2vulkan-rt::IndexBuffer.index_type pub index_type: IndexType +field metal2vulkan-rt::IndexBuffer.offset pub offset: u64 field metal2vulkan-rt::IndexGrant.class pub class: IndexClass field metal2vulkan-rt::IndexGrant.count pub count: u32 field metal2vulkan-rt::IndexGrant.first pub first: u32 @@ -2412,8 +2420,18 @@ field metal2vulkan-rt::SamplerDescriptor.r_address_mode pub r_address_mode: meta field metal2vulkan-rt::SamplerDescriptor.reduction_mode pub reduction_mode: metal::SamplerReductionMode field metal2vulkan-rt::SamplerDescriptor.s_address_mode pub s_address_mode: metal::SamplerAddressMode field metal2vulkan-rt::SamplerDescriptor.t_address_mode pub t_address_mode: metal::SamplerAddressMode +field metal2vulkan-rt::ScissorRect.height pub height: u64 +field metal2vulkan-rt::ScissorRect.width pub width: u64 +field metal2vulkan-rt::ScissorRect.x pub x: u64 +field metal2vulkan-rt::ScissorRect.y pub y: u64 field metal2vulkan-rt::SizeAndAlign.align pub align: u64 field metal2vulkan-rt::SizeAndAlign.size pub size: u64 +field metal2vulkan-rt::StencilDescriptor.depth_failure_operation pub depth_failure_operation: StencilOperation +field metal2vulkan-rt::StencilDescriptor.depth_stencil_pass_operation pub depth_stencil_pass_operation: StencilOperation +field metal2vulkan-rt::StencilDescriptor.read_mask pub read_mask: u32 +field metal2vulkan-rt::StencilDescriptor.stencil_compare_function pub stencil_compare_function: CompareFunction +field metal2vulkan-rt::StencilDescriptor.stencil_failure_operation pub stencil_failure_operation: StencilOperation +field metal2vulkan-rt::StencilDescriptor.write_mask pub write_mask: u32 field metal2vulkan-rt::TextureDescriptor.array_length pub array_length: u32 field metal2vulkan-rt::TextureDescriptor.depth pub depth: u32 field metal2vulkan-rt::TextureDescriptor.height pub height: u32 @@ -2434,6 +2452,12 @@ field metal2vulkan-rt::TextureSwizzleChannels.green pub green: TextureSwizzle field metal2vulkan-rt::TextureSwizzleChannels.red pub red: TextureSwizzle field metal2vulkan-rt::VertexDescriptor.attributes pub attributes: BTreeMap field metal2vulkan-rt::VertexDescriptor.layouts pub layouts: BTreeMap +field metal2vulkan-rt::Viewport.height pub height: f64 +field metal2vulkan-rt::Viewport.origin_x pub origin_x: f64 +field metal2vulkan-rt::Viewport.origin_y pub origin_y: f64 +field metal2vulkan-rt::Viewport.width pub width: f64 +field metal2vulkan-rt::Viewport.zfar pub zfar: f64 +field metal2vulkan-rt::Viewport.znear pub znear: f64 field metal2vulkan-rt::floor::BelowFloor.missing pub missing: Vec field metal2vulkan-rt::floor::Capabilities.buffer_int64_atomics pub buffer_int64_atomics: bool field metal2vulkan-rt::floor::Capabilities.extensions pub extensions: Vec<&'static CStr> @@ -6159,7 +6183,11 @@ macro-decl metal2vulkan-air::ir::TypeId id_type! TypeId macro-decl metal2vulkan-air::ir::TypeId ir_id! TypeId macro-decl metal2vulkan-air::metal::DataType metal_enum! DataType macro-decl metal2vulkan-rt::CompareFunction metal_enum! CompareFunction +macro-decl metal2vulkan-rt::CullMode metal_enum! CullMode +macro-decl metal2vulkan-rt::IndexType metal_enum! IndexType +macro-decl metal2vulkan-rt::IndexType vk_enum! IndexType macro-decl metal2vulkan-rt::PixelFormat metal_enum! PixelFormat +macro-decl metal2vulkan-rt::PrimitiveType metal_enum! PrimitiveType macro-decl metal2vulkan-rt::SamplerAddressMode metal_enum! SamplerAddressMode macro-decl metal2vulkan-rt::SamplerAddressMode vk_enum! SamplerAddressMode macro-decl metal2vulkan-rt::SamplerBorderColor metal_enum! SamplerBorderColor @@ -6167,9 +6195,11 @@ macro-decl metal2vulkan-rt::SamplerMinMagFilter metal_enum! SamplerMinMagFilter macro-decl metal2vulkan-rt::SamplerMipFilter metal_enum! SamplerMipFilter macro-decl metal2vulkan-rt::SamplerReductionMode metal_enum! SamplerReductionMode macro-decl metal2vulkan-rt::SamplerReductionMode vk_enum! SamplerReductionMode +macro-decl metal2vulkan-rt::StencilOperation metal_enum! StencilOperation macro-decl metal2vulkan-rt::TextureSwizzle metal_enum! TextureSwizzle macro-decl metal2vulkan-rt::TextureType metal_enum! TextureType macro-decl metal2vulkan-rt::TextureUsage metal_flags! TextureUsage +macro-decl metal2vulkan-rt::Winding metal_enum! Winding macro-decl metal2vulkan-runtime::Degradation degradations! Degradation macro-decl metal2vulkan::metal::ArgumentBuffersTier metal_enum! ArgumentBuffersTier macro-decl metal2vulkan::metal::AttributeFormat metal_enum! AttributeFormat @@ -6398,6 +6428,20 @@ macro-member metal2vulkan-rt::CompareFunction::LessEqual LessEqual = 3, "MTLComp macro-member metal2vulkan-rt::CompareFunction::Never Never = 0, "MTLCompareFunctionNever"; macro-member metal2vulkan-rt::CompareFunction::NotEqual NotEqual = 5, "MTLCompareFunctionNotEqual"; macro-member metal2vulkan-rt::CompareFunction::aliases aliases +macro-member metal2vulkan-rt::CullMode::Back Back = 2, "MTLCullModeBack"; +macro-member metal2vulkan-rt::CullMode::CullMode CullMode = "MTLCullMode" +macro-member metal2vulkan-rt::CullMode::Front Front = 1, "MTLCullModeFront"; +macro-member metal2vulkan-rt::CullMode::None None = 0, "MTLCullModeNone"; +macro-member metal2vulkan-rt::CullMode::aliases aliases +macro-member metal2vulkan-rt::IndexType::IndexType IndexType = "MTLIndexType" +macro-member metal2vulkan-rt::IndexType::IndexType IndexType(i32) = "VkIndexType" +macro-member metal2vulkan-rt::IndexType::NONE_KHR NONE_KHR = 1000165000, "VK_INDEX_TYPE_NONE_KHR"; +macro-member metal2vulkan-rt::IndexType::UINT16 UINT16 = 0, "VK_INDEX_TYPE_UINT16"; +macro-member metal2vulkan-rt::IndexType::UINT32 UINT32 = 1, "VK_INDEX_TYPE_UINT32"; +macro-member metal2vulkan-rt::IndexType::UINT8 UINT8 = 1000265000, "VK_INDEX_TYPE_UINT8"; +macro-member metal2vulkan-rt::IndexType::UInt16 UInt16 = 0, "MTLIndexTypeUInt16"; +macro-member metal2vulkan-rt::IndexType::UInt32 UInt32 = 1, "MTLIndexTypeUInt32"; +macro-member metal2vulkan-rt::IndexType::aliases aliases macro-member metal2vulkan-rt::PixelFormat::A1BGR5Unorm A1BGR5Unorm = 41, "MTLPixelFormatA1BGR5Unorm"; macro-member metal2vulkan-rt::PixelFormat::A8Unorm A8Unorm = 1, "MTLPixelFormatA8Unorm"; macro-member metal2vulkan-rt::PixelFormat::ABGR4Unorm ABGR4Unorm = 42, "MTLPixelFormatABGR4Unorm"; @@ -6701,6 +6745,13 @@ macro-member metal2vulkan-rt::PixelFormat::YCBCR84442P YCBCR84442P = 503, "MTLPi macro-member metal2vulkan-rt::PixelFormat::YCBCR84442PSRGB YCBCR84442PSRGB = 523, "MTLPixelFormatYCBCR8_444_2P_sRGB"; macro-member metal2vulkan-rt::PixelFormat::YCBCRA84441P YCBCRA84441P = 560, "MTLPixelFormatYCBCRA8_444_1P"; macro-member metal2vulkan-rt::PixelFormat::aliases aliases +macro-member metal2vulkan-rt::PrimitiveType::Line Line = 1, "MTLPrimitiveTypeLine"; +macro-member metal2vulkan-rt::PrimitiveType::LineStrip LineStrip = 2, "MTLPrimitiveTypeLineStrip"; +macro-member metal2vulkan-rt::PrimitiveType::Point Point = 0, "MTLPrimitiveTypePoint"; +macro-member metal2vulkan-rt::PrimitiveType::PrimitiveType PrimitiveType = "MTLPrimitiveType" +macro-member metal2vulkan-rt::PrimitiveType::Triangle Triangle = 3, "MTLPrimitiveTypeTriangle"; +macro-member metal2vulkan-rt::PrimitiveType::TriangleStrip TriangleStrip = 4, "MTLPrimitiveTypeTriangleStrip"; +macro-member metal2vulkan-rt::PrimitiveType::aliases aliases macro-member metal2vulkan-rt::SamplerAddressMode::CLAMP_TO_BORDER CLAMP_TO_BORDER = 3, "VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER"; macro-member metal2vulkan-rt::SamplerAddressMode::CLAMP_TO_EDGE CLAMP_TO_EDGE = 2, "VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE"; macro-member metal2vulkan-rt::SamplerAddressMode::ClampToBorderColor ClampToBorderColor = 5, "MTLSamplerAddressModeClampToBorderColor"; @@ -6740,6 +6791,16 @@ macro-member metal2vulkan-rt::SamplerReductionMode::WEIGHTED_AVERAGE WEIGHTED_AV macro-member metal2vulkan-rt::SamplerReductionMode::WEIGHTED_AVERAGE_RANGECLAMP_QCOM WEIGHTED_AVERAGE_RANGECLAMP_QCOM = 1000521000, "VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_RANGECLAMP_QCOM"; macro-member metal2vulkan-rt::SamplerReductionMode::WeightedAverage WeightedAverage = 0, "MTLSamplerReductionModeWeightedAverage"; macro-member metal2vulkan-rt::SamplerReductionMode::aliases aliases +macro-member metal2vulkan-rt::StencilOperation::DecrementClamp DecrementClamp = 4, "MTLStencilOperationDecrementClamp"; +macro-member metal2vulkan-rt::StencilOperation::DecrementWrap DecrementWrap = 7, "MTLStencilOperationDecrementWrap"; +macro-member metal2vulkan-rt::StencilOperation::IncrementClamp IncrementClamp = 3, "MTLStencilOperationIncrementClamp"; +macro-member metal2vulkan-rt::StencilOperation::IncrementWrap IncrementWrap = 6, "MTLStencilOperationIncrementWrap"; +macro-member metal2vulkan-rt::StencilOperation::Invert Invert = 5, "MTLStencilOperationInvert"; +macro-member metal2vulkan-rt::StencilOperation::Keep Keep = 0, "MTLStencilOperationKeep"; +macro-member metal2vulkan-rt::StencilOperation::Replace Replace = 2, "MTLStencilOperationReplace"; +macro-member metal2vulkan-rt::StencilOperation::StencilOperation StencilOperation = "MTLStencilOperation" +macro-member metal2vulkan-rt::StencilOperation::Zero Zero = 1, "MTLStencilOperationZero"; +macro-member metal2vulkan-rt::StencilOperation::aliases aliases macro-member metal2vulkan-rt::TextureSwizzle::Alpha Alpha = 5, "MTLTextureSwizzleAlpha"; macro-member metal2vulkan-rt::TextureSwizzle::Blue Blue = 4, "MTLTextureSwizzleBlue"; macro-member metal2vulkan-rt::TextureSwizzle::Green Green = 3, "MTLTextureSwizzleGreen"; @@ -6772,6 +6833,10 @@ macro-member metal2vulkan-rt::TextureUsage::UNKNOWN UNKNOWN = 0x0, "MTLTextureUs macro-member metal2vulkan-rt::TextureUsage::VIDEO VIDEO = 0x8000, "MTLTextureUsageVideo"; macro-member metal2vulkan-rt::TextureUsage::aliases aliases macro-member metal2vulkan-rt::TextureUsage::dropped dropped +macro-member metal2vulkan-rt::Winding::Clockwise Clockwise = 0, "MTLWindingClockwise"; +macro-member metal2vulkan-rt::Winding::CounterClockwise CounterClockwise = 1, "MTLWindingCounterClockwise"; +macro-member metal2vulkan-rt::Winding::Winding Winding = "MTLWinding" +macro-member metal2vulkan-rt::Winding::aliases aliases macro-member metal2vulkan-runtime::Degradation::AbsentArgumentRead AbsentArgumentRead = "absent-argument-read", Precision, macro-member metal2vulkan-runtime::Degradation::AmplificationDraws AmplificationDraws = "amplification-draws", Performance, macro-member metal2vulkan-runtime::Degradation::AnisotropicFilter AnisotropicFilter = "anisotropic-filter"; @@ -9405,6 +9470,7 @@ method metal2vulkan-rt::ComputePipelineState::max_total_threads_per_threadgroup method metal2vulkan-rt::ComputePipelineState::precision_notes pub fn precision_notes(&self) -> Vec method metal2vulkan-rt::Counters::gauges pub fn gauges(&self) -> Gauges method metal2vulkan-rt::Counters::metrics pub fn metrics(&self) -> Metrics +method metal2vulkan-rt::DepthStencilState::descriptor pub fn descriptor(&self) -> &DepthStencilDescriptor method metal2vulkan-rt::Device::counters pub fn counters(&self) -> Counters method metal2vulkan-rt::Device::extensions pub fn extensions(&self) -> &[CString] method metal2vulkan-rt::Device::features pub fn features(&self) -> &[ConsumerFeature] @@ -9416,6 +9482,7 @@ method metal2vulkan-rt::Device::minimum_linear_texture_alignment pub fn minimum_ method metal2vulkan-rt::Device::new pub fn new(physical: &PhysicalDevice, options: DeviceOptions) -> Result method metal2vulkan-rt::Device::new_buffer pub fn new_buffer(&self, block: BlockId, offset: u64, length: u64, zero_from: Option) -> Result method metal2vulkan-rt::Device::new_command_queue pub fn new_command_queue(&self, max_command_buffer_count: u32) -> Result +method metal2vulkan-rt::Device::new_depth_stencil_state pub fn new_depth_stencil_state(&self, descriptor: &DepthStencilDescriptor) -> DepthStencilState method metal2vulkan-rt::Device::new_event pub fn new_event(&self) -> Result method metal2vulkan-rt::Device::new_fence pub fn new_fence(&self) -> Fence method metal2vulkan-rt::Device::new_heap_texture pub fn new_heap_texture(&self, descriptor: &TextureDescriptor, index: Option, heap: HeapRange, offset: u64) -> Result @@ -9463,7 +9530,31 @@ method metal2vulkan-rt::PhysicalDevice::check pub fn check(&self) -> Result vk::PhysicalDevice method metal2vulkan-rt::PrecisionNote::of_float_operator pub fn of_float_operator(op: AirBin, width: FloatWidth, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option> method metal2vulkan-rt::PrecisionNote::of_math_call pub fn of_math_call(call: Math, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option> +method metal2vulkan-rt::RenderCommandEncoder::draw_indexed_primitives pub fn draw_indexed_primitives(&mut self, primitive_type: PrimitiveType, index_count: u32, indices: IndexBuffer<'_>, instance_count: u32, base_vertex: i32, base_instance: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::draw_primitives pub fn draw_primitives(&mut self, primitive_type: PrimitiveType, vertex_start: u32, vertex_count: u32, instance_count: u32, base_instance: u32) -> Result<(), Error> method metal2vulkan-rt::RenderCommandEncoder::end_encoding pub fn end_encoding(mut self) +method metal2vulkan-rt::RenderCommandEncoder::memory_barrier pub fn memory_barrier(&mut self) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_blend_color pub fn set_blend_color(&mut self, red: f32, green: f32, blue: f32, alpha: f32) +method metal2vulkan-rt::RenderCommandEncoder::set_cull_mode pub fn set_cull_mode(&mut self, mode: CullMode) +method metal2vulkan-rt::RenderCommandEncoder::set_depth_stencil_state pub fn set_depth_stencil_state(&mut self, state: Option<&DepthStencilState>) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_fragment_buffer pub fn set_fragment_buffer(&mut self, buffer: Option<&Buffer>, offset: u64, index: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_fragment_buffer_offset pub fn set_fragment_buffer_offset(&mut self, offset: u64, index: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_fragment_bytes pub fn set_fragment_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_fragment_sampler_state pub fn set_fragment_sampler_state(&mut self, sampler: Option<&SamplerState>, index: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_fragment_texture pub fn set_fragment_texture(&mut self, texture: Option<&Texture>, index: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_front_facing_winding pub fn set_front_facing_winding(&mut self, winding: Winding) +method metal2vulkan-rt::RenderCommandEncoder::set_render_pipeline_state pub fn set_render_pipeline_state(&mut self, state: &RenderPipelineState) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_scissor_rect pub fn set_scissor_rect(&mut self, rect: ScissorRect) +method metal2vulkan-rt::RenderCommandEncoder::set_stencil_front_back_reference_value pub fn set_stencil_front_back_reference_value(&mut self, front: u32, back: u32) +method metal2vulkan-rt::RenderCommandEncoder::set_stencil_reference_value pub fn set_stencil_reference_value(&mut self, value: u32) +method metal2vulkan-rt::RenderCommandEncoder::set_vertex_buffer pub fn set_vertex_buffer(&mut self, buffer: Option<&Buffer>, offset: u64, index: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_vertex_buffer_offset pub fn set_vertex_buffer_offset(&mut self, offset: u64, index: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_vertex_bytes pub fn set_vertex_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_vertex_sampler_state pub fn set_vertex_sampler_state(&mut self, sampler: Option<&SamplerState>, index: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_vertex_texture pub fn set_vertex_texture(&mut self, texture: Option<&Texture>, index: u32) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::set_viewport pub fn set_viewport(&mut self, viewport: Viewport) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::update_fence pub fn update_fence(&mut self, fence: &Fence) -> Result<(), Error> +method metal2vulkan-rt::RenderCommandEncoder::wait_for_fence pub fn wait_for_fence(&mut self, fence: &Fence) -> Result<(), Error> method metal2vulkan-rt::RenderPipelineDescriptor::fragment_writes_depth_unattached pub fn fragment_writes_depth_unattached(&self, budget: &crate::Budget, entries: &StageEntries) -> Result method metal2vulkan-rt::RenderPipelineDescriptor::new pub fn new(vertex: StageSource) -> RenderPipelineDescriptor method metal2vulkan-rt::RenderPipelineDescriptor::reflection pub fn reflection(&self, budget: &crate::Budget) -> Result @@ -11528,6 +11619,8 @@ struct metal2vulkan-rt::ComputeCommandEncoder pub struct ComputeCommandEncoder struct metal2vulkan-rt::ComputePipelineDescriptor #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ComputePipelineDescriptor struct metal2vulkan-rt::ComputePipelineState #[derive(Clone)] pub struct ComputePipelineState struct metal2vulkan-rt::Counters #[derive(Clone)] pub struct Counters +struct metal2vulkan-rt::DepthStencilDescriptor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct DepthStencilDescriptor +struct metal2vulkan-rt::DepthStencilState #[derive(Clone)] pub struct DepthStencilState struct metal2vulkan-rt::Device #[derive(Clone)] pub struct Device struct metal2vulkan-rt::DeviceExtension #[derive(Clone)] pub struct DeviceExtension struct metal2vulkan-rt::DeviceOptions #[derive(Clone, Default)] #[non_exhaustive] pub struct DeviceOptions @@ -11536,6 +11629,7 @@ struct metal2vulkan-rt::Fence #[derive(Clone)] pub struct Fence struct metal2vulkan-rt::FunctionDescriptor #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct FunctionDescriptor struct metal2vulkan-rt::Gauges #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct Gauges struct metal2vulkan-rt::HeapRange #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct HeapRange +struct metal2vulkan-rt::IndexBuffer #[derive(Clone, Copy)] pub struct IndexBuffer<'a> struct metal2vulkan-rt::IndexGrant #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct IndexGrant struct metal2vulkan-rt::Instance #[derive(Clone)] pub struct Instance struct metal2vulkan-rt::Library #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Library(Arc) @@ -11554,13 +11648,16 @@ struct metal2vulkan-rt::ResourceId #[derive(Clone, Copy, Debug, Default, Partial struct metal2vulkan-rt::ResourceUsage #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ResourceUsage(u32) struct metal2vulkan-rt::SamplerDescriptor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct SamplerDescriptor struct metal2vulkan-rt::SamplerState #[derive(Clone)] pub struct SamplerState +struct metal2vulkan-rt::ScissorRect #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ScissorRect struct metal2vulkan-rt::SharedEvent #[derive(Clone)] pub struct SharedEvent struct metal2vulkan-rt::SizeAndAlign #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct SizeAndAlign +struct metal2vulkan-rt::StencilDescriptor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct StencilDescriptor struct metal2vulkan-rt::Texture #[derive(Clone)] pub struct Texture struct metal2vulkan-rt::TextureDescriptor #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct TextureDescriptor struct metal2vulkan-rt::TexturePlace #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct TexturePlace struct metal2vulkan-rt::TextureSwizzleChannels #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TextureSwizzleChannels struct metal2vulkan-rt::VertexDescriptor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct VertexDescriptor +struct metal2vulkan-rt::Viewport #[derive(Clone, Copy, Debug, PartialEq)] pub struct Viewport struct metal2vulkan-rt::floor::BelowFloor #[derive(Clone, Debug, PartialEq, Eq)] pub struct BelowFloor struct metal2vulkan-rt::floor::Capabilities pub struct Capabilities struct metal2vulkan-rt::floor::Features #[derive(Clone, Copy, Default)] pub struct Features @@ -12110,6 +12207,7 @@ trait-impl metal2vulkan-rt::BlockInfo impl fe impl Send unsafe impl Send for Blo trait-impl metal2vulkan-rt::BlockInfo impl fe impl Sync unsafe impl Sync for BlockInfo trait-impl metal2vulkan-rt::ClearColor impl Default impl Default for ClearColor trait-impl metal2vulkan-rt::ComputeCommandEncoder impl Drop impl Drop for ComputeCommandEncoder +trait-impl metal2vulkan-rt::DepthStencilDescriptor impl Default impl Default for DepthStencilDescriptor trait-impl metal2vulkan-rt::Error impl fmt::Display impl fmt::Display for Error trait-impl metal2vulkan-rt::Error impl std::error::Error impl std::error::Error for Error trait-impl metal2vulkan-rt::Gap impl fmt::Display impl fmt::Display for Gap @@ -12120,6 +12218,7 @@ trait-impl metal2vulkan-rt::RenderPassDepthAttachmentDescriptor impl Default imp trait-impl metal2vulkan-rt::RenderPassStencilAttachmentDescriptor impl Default impl Default for RenderPassStencilAttachmentDescriptor trait-impl metal2vulkan-rt::ResourceUsage impl BitOr impl BitOr for ResourceUsage trait-impl metal2vulkan-rt::SamplerDescriptor impl Default impl Default for SamplerDescriptor +trait-impl metal2vulkan-rt::StencilDescriptor impl Default impl Default for StencilDescriptor trait-impl metal2vulkan-rt::TextureSwizzleChannels impl Default impl Default for TextureSwizzleChannels trait-impl metal2vulkan-rt::floor::BelowFloor impl fmt::Display impl fmt::Display for BelowFloor trait-impl metal2vulkan-rt::floor::BelowFloor impl std::error::Error impl std::error::Error for BelowFloor @@ -13446,6 +13545,11 @@ variant metal2vulkan-rt::CompareFunction::NotEqual NotEqual variant metal2vulkan-rt::ConsumerFeature::SamplerYcbcrConversion SamplerYcbcrConversion variant metal2vulkan-rt::DispatchType::Concurrent Concurrent variant metal2vulkan-rt::DispatchType::Serial Serial +variant metal2vulkan-rt::DrawKind::AttachmentFormats AttachmentFormats +variant metal2vulkan-rt::DrawKind::AttachmentRead AttachmentRead +variant metal2vulkan-rt::DrawKind::DepthTest DepthTest +variant metal2vulkan-rt::DrawKind::Points Points +variant metal2vulkan-rt::DrawKind::Viewport Viewport variant metal2vulkan-rt::Error::BelowFloor BelowFloor(BelowFloor) variant metal2vulkan-rt::Error::Limit Limit(Limit) variant metal2vulkan-rt::Error::Loader Loader(ash::LoadingError) @@ -13458,6 +13562,7 @@ variant metal2vulkan-rt::Error::Unsupported Unsupported(Gap) variant metal2vulkan-rt::Error::Vulkan Vulkan { call: &'static str, result: vk::Result } variant metal2vulkan-rt::Gap::BufferCopyAlignment BufferCopyAlignment { pixel_format: PixelFormat, offset: u64, bytes_per_row: u64, bytes_per_image: u64 } variant metal2vulkan-rt::Gap::CubicSampler CubicSampler +variant metal2vulkan-rt::Gap::Draw Draw { kind: DrawKind } variant metal2vulkan-rt::Gap::FenceOtherQueue FenceOtherQueue variant metal2vulkan-rt::Gap::FillAlignment FillAlignment { start: u64, end: u64 } variant metal2vulkan-rt::Gap::FloatDepthUpload FloatDepthUpload { pixel_format: PixelFormat } @@ -13593,6 +13698,7 @@ variant metal2vulkan-rt::Refusal::EmptyBuffer EmptyBuffer variant metal2vulkan-rt::Refusal::EncoderOpen EncoderOpen variant metal2vulkan-rt::Refusal::FillRange FillRange { start: u64, end: u64, len: u64 } variant metal2vulkan-rt::Refusal::HeapTexturePlace HeapTexturePlace { offset: u64, size: u64, align: u64, heap_len: u64 } +variant metal2vulkan-rt::Refusal::IndexBufferOffset IndexBufferOffset { offset: u64, length: u64 } variant metal2vulkan-rt::Refusal::IndexInUse IndexInUse { class: IndexClass, index: u32 } variant metal2vulkan-rt::Refusal::IndicesGranted IndicesGranted { class: IndexClass, index: u32 } variant metal2vulkan-rt::Refusal::IndicesInUse IndicesInUse { class: IndexClass, index: u32 } @@ -13607,6 +13713,7 @@ variant metal2vulkan-rt::Refusal::NoPipeline NoPipeline variant metal2vulkan-rt::Refusal::OtherDevice OtherDevice variant metal2vulkan-rt::Refusal::SamplerArgumentIndex SamplerArgumentIndex { index: u32 } variant metal2vulkan-rt::Refusal::SamplerIds SamplerIds { numbered: usize, given: usize } +variant metal2vulkan-rt::Refusal::StencilAttachment StencilAttachment variant metal2vulkan-rt::Refusal::TextureArgumentIndex TextureArgumentIndex { index: u32 } variant metal2vulkan-rt::Refusal::TextureArrayLength TextureArrayLength { array_length: u32 } variant metal2vulkan-rt::Refusal::TextureBytesLayout TextureBytesLayout { bytes_per_row: u64, bytes_per_image: u64, len: u64 } @@ -13623,6 +13730,8 @@ variant metal2vulkan-rt::Refusal::TextureViewFormat TextureViewFormat { texture: variant metal2vulkan-rt::Refusal::TextureViewRange TextureViewRange { level: u32, level_count: u32, slice: u32, slice_count: u32 } variant metal2vulkan-rt::Refusal::TextureZeroExtent TextureZeroExtent variant metal2vulkan-rt::Refusal::ThreadgroupSize ThreadgroupSize { size: [u32; 3], max: u32 } +variant metal2vulkan-rt::Refusal::VertexBufferOffset VertexBufferOffset { index: u32, offset: u64, length: u64 } +variant metal2vulkan-rt::Refusal::ViewportNotFinite ViewportNotFinite variant metal2vulkan-rt::RenderPassKind::ClearFormat ClearFormat variant metal2vulkan-rt::RenderPassKind::DepthAttachment DepthAttachment variant metal2vulkan-rt::RenderPassKind::Multisample Multisample @@ -13634,11 +13743,11 @@ variant metal2vulkan-rt::RenderPipelineKind::AlphaToOne AlphaToOne variant metal2vulkan-rt::RenderPipelineKind::ConstantData ConstantData variant metal2vulkan-rt::RenderPipelineKind::DepthAttachment DepthAttachment variant metal2vulkan-rt::RenderPipelineKind::DeviceFeature DeviceFeature +variant metal2vulkan-rt::RenderPipelineKind::DrawInput DrawInput variant metal2vulkan-rt::RenderPipelineKind::DynamicState DynamicState variant metal2vulkan-rt::RenderPipelineKind::FramebufferFetch FramebufferFetch variant metal2vulkan-rt::RenderPipelineKind::Imageblock Imageblock variant metal2vulkan-rt::RenderPipelineKind::Multisample Multisample -variant metal2vulkan-rt::RenderPipelineKind::Samplers Samplers variant metal2vulkan-rt::RenderPipelineKind::ShaderStencil ShaderStencil variant metal2vulkan-rt::RenderPipelineKind::Specialization Specialization variant metal2vulkan-rt::RenderPipelineKind::StepRate StepRate diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 6a0ac5631..8d0313cdd 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -37,9 +37,9 @@ Columns: | What a call did wrong | 73 | 73 | 0 | 0 | 0 | 0 | 0 | | What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 | | Devices below the new runtime's floor | 8 | 8 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 47 | 47 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 51 | 51 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Limit` | 11 | 11 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Gap` | 19 | 19 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Gap` | 20 | 20 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis @@ -55,9 +55,9 @@ Columns: | What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 | | What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 | | Devices below the new runtime's floor | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 14 | 13 | 0 | 0 | 20 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 16 | 15 | 0 | 0 | 20 | 0 | 0 | 0 | | The new runtime's `Limit` | 0 | 0 | 0 | 8 | 3 | 0 | 0 | 0 | -| The new runtime's `Gap` | 0 | 0 | 0 | 0 | 19 | 0 | 0 | 0 | +| The new runtime's `Gap` | 0 | 0 | 0 | 0 | 20 | 0 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -620,15 +620,15 @@ Columns: | `ManagedBlockNotShared` | A Managed buffer whose bytes are in a Private block (`Device::new_managed_buffer`) | every device (a public call's own check of its arguments) | `ours`: a Managed buffer's bytes are the consumer's, which it maps; a Private block has no mapping | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` | | `ModifiedRange` | A changed range that leaves its buffer (`Buffer::did_modify_range`) | every device (a public call's own check of its arguments) | `ours`: the copy of such a range would write past the buffer's device copy | 1: `crates/metal2vulkan-rt/src/buffer.rs (did_modify_range)` | `-` | | `Committed` | A call on a command buffer already committed | every device (a public call's own check of its arguments) | `metal-documented`: Metal's validation asserts "commit an already committed command buffer", "Completed handler provided after commit call" and "Scheduled handler provided after commit call" | 1: `crates/metal2vulkan-rt/src/command.rs (open)` | `-` | -| `OtherDevice` | An event, a buffer, a texture or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block, a texture's image, a pipeline and a block belong to the `VkDevice` that made them | 17: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-rt/src/blit.rs (copy_from_buffer_to_buffer)` (+14) | `-` | +| `OtherDevice` | An event, a buffer, a texture or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block, a texture's image, a pipeline and a block belong to the `VkDevice` that made them | 23: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-rt/src/blit.rs (copy_from_buffer_to_buffer)` (+20) | `-` | | `NoCommandBuffers` | A queue that may hold no command buffer (`Device::new_command_queue` with a count of 0) | every device (a public call's own check of its arguments) | `ours`: its first `commandBuffer` call would wait forever | 1: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` | `-` | | `EncoderOpen` | A second encoder, an encode call, or a commit or enqueue, while an encoder of the command buffer is open | every device (a public call's own check of its arguments) | `metal-documented`: a command buffer has one active encoder at a time, ended by `endEncoding` before another is made or the command buffer is committed | 1: `crates/metal2vulkan-rt/src/command.rs (open)` | `-` | -| `NoPipeline` | A dispatch with no pipeline state set | every device (a public call's own check of its arguments) | `metal-documented`: a compute dispatch needs a compute pipeline state set first | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | -| `BufferIndex` | A buffer argument index past Metal's 31 entries (`setBuffer`, `setBytes`, `setBufferOffset`, `setThreadgroupMemoryLength`) | every device (a public call's own check of its arguments) | `metal-documented`: the buffer argument table has 31 entries per stage | 1: `crates/metal2vulkan-rt/src/encoder.rs (slot)` | `-` | -| `TextureArgumentIndex` | A texture argument index past Metal's 128 entries (`setTexture`) | every device (a public call's own check of its arguments) | `metal-documented`: the texture argument table has 128 entries per stage on Apple GPUs | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_texture)` | `-` | -| `SamplerArgumentIndex` | A sampler argument index past Metal's 16 entries (`setSamplerState`) | every device (a public call's own check of its arguments) | `metal-documented`: the sampler argument table has 16 entries per stage | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)` | `-` | -| `SamplerIds` | A consumer's answer to `Device::new_compute_pipeline_state`'s numbered samplers with another count of indices | every device (a public call's own check of its arguments) | `ours`: each numbered sampler takes one index | 1: `crates/metal2vulkan-rt/src/pipeline.rs (number)` | `-` | -| `NoBufferAtIndex` | `setBufferOffset` at an index where no buffer is bound | every device (a public call's own check of its arguments) | `ours`: there is no buffer whose offset to change | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)` | `-` | +| `NoPipeline` | A dispatch or a draw with no pipeline state set | every device (a public call's own check of its arguments) | `metal-documented`: a compute dispatch needs a compute pipeline state set first, and a draw a render pipeline state | 2: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)`, `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` | `-` | +| `BufferIndex` | A buffer argument index past Metal's 31 entries (`setBuffer`, `setBytes`, `setBufferOffset`, `setThreadgroupMemoryLength`) | every device (a public call's own check of its arguments) | `metal-documented`: the buffer argument table has 31 entries per stage | 2: `crates/metal2vulkan-rt/src/encoder.rs (slot)`, `crates/metal2vulkan-rt/src/render_encoder.rs (slot)` | `-` | +| `TextureArgumentIndex` | A texture argument index past Metal's 128 entries (`setTexture`) | every device (a public call's own check of its arguments) | `metal-documented`: the texture argument table has 128 entries per stage on Apple GPUs | 2: `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`, `crates/metal2vulkan-rt/src/render_encoder.rs (set_texture)` | `-` | +| `SamplerArgumentIndex` | A sampler argument index past Metal's 16 entries (`setSamplerState`) | every device (a public call's own check of its arguments) | `metal-documented`: the sampler argument table has 16 entries per stage | 2: `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`, `crates/metal2vulkan-rt/src/render_encoder.rs (set_sampler_state)` | `-` | +| `SamplerIds` | A consumer's answer to `Device::new_compute_pipeline_state`'s numbered samplers with another count of indices | every device (a public call's own check of its arguments) | `ours`: each numbered sampler takes one index | 1: `crates/metal2vulkan-rt/src/pipeline.rs (number_samplers)` | `-` | +| `NoBufferAtIndex` | `setBufferOffset` at an index where no buffer is bound, or a draw whose vertex descriptor reads a vertex buffer index where none is bound | every device (a public call's own check of its arguments) | `ours`: there is no buffer whose offset to change, and none whose vertices the draw reads; Metal's validation stops such a draw | 3: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)`, `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` (+1) | `-` | | `ThreadgroupSize` | A threadgroup of no threads, or of more than the pipeline state's `maxTotalThreadsPerThreadgroup` | every device (a public call's own check of its arguments) | `metal-documented`: a threadgroup's threads total at most the state's `maxTotalThreadsPerThreadgroup` | 2: `crates/metal2vulkan-rt/src/encoder.rs (dispatch, 2 sites)` | `-` | | `IndirectOffset` | An indirect dispatch's argument offset that is not a multiple of 4, or that leaves fewer than 12 bytes (three 32-bit counts) in the buffer | every device (a public call's own check of its arguments) | `ours`: `vkCmdDispatchIndirect` reads three 32-bit counts at a 4-byte aligned offset inside the buffer | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` | `-` | | `BufferOffsetAlignment` | A dispatch whose kernel reaches a buffer bound where its address, the buffer's `gpuAddress` plus the bind offset, is not a multiple of the kernel... | every device (a public call's own check of its arguments) | `metal-documented`: Metal's API validation refuses the bind offset: "must be a multiple of 4 but was set to 2" for a `uint *` argument bound at offset 2, an Apple M3 Max, macOS 27.0.1, `probes/vector_access_placement.m` in the conformance crate | 1: `crates/metal2vulkan-rt/src/encoder.rs (check_alignment)` | `-` | @@ -661,6 +661,10 @@ Columns: | `AttachmentUsage` | A render pass attachment (`CommandBuffer::render_command_encoder`) whose texture was made without `RenderTarget` usage | every device (a public call's own check of its arguments) | `metal-documented`: a texture a render pass renders into needs `MTLTextureUsageRenderTarget`; Metal's validation stops the descriptor | 1: `crates/metal2vulkan-rt/src/texture.rs (attachment)` | `-` | | `AttachmentPlace` | A render pass attachment of a level or slice past its texture's | every device (a public call's own check of its arguments) | `ours`: no texel of the texture is there to render into | 1: `crates/metal2vulkan-rt/src/texture.rs (attachment)` | `-` | | `AttachmentFormat` | A render pass color attachment of a depth or stencil pixel format, or a stencil attachment of a format without stencil | every device (a public call's own check of its arguments) | `metal-documented`: a color attachment takes a color-renderable format and a stencil attachment a format with stencil; Metal's validation stops the descriptor | 2: `crates/metal2vulkan-rt/src/pass.rs (check, 2 sites)` | `-` | +| `VertexBufferOffset` | A draw whose vertex descriptor reads a vertex buffer at an offset at or past the buffer's length | every device (a public call's own check of its arguments) | `metal-documented`: a buffer's offset lies inside it; Metal's validation stops the bind | 1: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` | `-` | +| `IndexBufferOffset` | An indexed draw whose index buffer offset is not a multiple of the index size, or whose indices leave the buffer | every device (a public call's own check of its arguments) | `metal-documented`: the offset is a multiple of the index size and the indices lie in the buffer; Metal's validation stops the draw | 1: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` | `-` | +| `ViewportNotFinite` | A viewport with a field that is NaN or infinite (but its origin's x, which draws nothing) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M4, macOS 27.0.1: Metal's validation stops a NaN or infinite origin; the other fields are taken by the same rule | 1: `crates/metal2vulkan-rt/src/render_encoder.rs (set_viewport)` | `-` | +| `StencilAttachment` | A draw under a depth-stencil state that tests the stencil, in a pass without a stencil attachment | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M4, macOS 27.0.1: Metal's validation stops the draw; plain Metal tests it against a hidden stencil of 0 that the runtime does not keep | 1: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` | `-` | ## 12. The new runtime's `Limit` (`Error::Limit(Limit)`) @@ -670,7 +674,7 @@ Columns: | `BlockIds` | A block after every block number has been used (`Device::take_block`) | every device (a public call's own check of its arguments) | `ours`: block numbers are 32 bits | 1: `crates/metal2vulkan-rt/src/memory.rs (number)` | `-` | | `ThreadgroupShape` | A threadgroup longer on an axis than the device's `maxComputeWorkGroupSize` (the floor holds 1,024 by 1,024 by 64), where the threadgroup is the... | at the device's limit | `device`: the device's `maxComputeWorkGroupSize` | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | | `ThreadgroupMemory` | A dispatch whose threadgroup memory, the kernel's own and the lengths set (each rounded up to 16 bytes), is past the device's... | at the device's limit | `device`: the device's `maxComputeSharedMemorySize` | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | -| `BytesLength` | `setBytes` data longer than one parameter ring chunk | every device (a public call's own check of its arguments) | `ours`: a ring chunk is 64 KiB | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_bytes)` | `-` | +| `BytesLength` | `setBytes` data longer than one parameter ring chunk | every device (a public call's own check of its arguments) | `ours`: a ring chunk is 64 KiB | 2: `crates/metal2vulkan-rt/src/encoder.rs (set_bytes)`, `crates/metal2vulkan-rt/src/render_encoder.rs (set_bytes)` | `-` | | `IndexRange` | A grant of no indices, or one past its class's range (`Device::grant_indices`, [`IndexClass::range`]) | every device (a public call's own check of its arguments) | `ours`: the descriptor arrays are 65,536 sampled textures, 4,096 storage textures and 4,000 samplers of each use, and index 0 is nil | 1: `crates/metal2vulkan-rt/src/arrays.rs (grant)` | `-` | | `TextureSize` | A texture whose extent or array layers are past what the device makes of its format, type, usage and sample count | at the device's limit | `device`: the image format query's `maxExtent` and `maxArrayLayers` | 1: `crates/metal2vulkan-rt/src/texture.rs (plan)` | `-` | | `DeviceSamplers` | A sampler state whose device samplers would take the device past its `maxSamplerAllocationCount`, less the sampler arrays' two defaults... | at the device's limit | `device`: the device's `maxSamplerAllocationCount` | 1: `crates/metal2vulkan-rt/src/sampler.rs (take)` | `-` | @@ -697,10 +701,11 @@ Columns: | `HeapTexture` | A heap texture the runtime does not place (`Device::new_heap_texture` and `Device::heap_texture_size_and_align`) | every device (a public call's own check of its arguments) | `ours`: heap textures are built for Private heaps of placeable images | 2: `crates/metal2vulkan-rt/src/texture.rs (heap_fit)`, `crates/metal2vulkan-rt/src/texture.rs (new_heap_texture)` | `-` | | `BufferCopyAlignment` | `BlitCommandEncoder::copy_from_buffer` or `BlitCommandEncoder::copy_from_texture_to_buffer` whose bytes no copy command in the floor addresses,... | every device (a public call's own check of its arguments) | `ours`: Vulkan 1.3 places a copy's rows in a buffer by a count of texels from an aligned offset; each is built when a replay stream makes one | 1: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)` | `-` | | `FillAlignment` | `BlitCommandEncoder::fill_buffer` of a range that does not start and end on whole 4-byte words of the bytes shaders reach, which Metal fills byte... | every device (a public call's own check of its arguments) | `ours`: `vkCmdFillBuffer` writes whole words; a byte fill is built when a replay stream makes one | 1: `crates/metal2vulkan-rt/src/blit.rs (fill_range)` | `-` | -| `RenderPipeline` | A render pipeline state of something the runtime does not build yet | every device (a public call's own check of its arguments) | `ours`: the replay streams' render pipelines draw into colour and stencil attachments of one sample, with no depth attachment, no tessellation and no framebuffer fetch; each other kind is built when a replay stream makes one | 4: `crates/metal2vulkan-rt/src/render.rs (of, 3 sites)`, `crates/metal2vulkan-rt/src/render.rs (refuse)` | `-` | +| `RenderPipeline` | A render pipeline state of something the runtime does not build yet | every device (a public call's own check of its arguments) | `ours`: the replay streams' render pipelines draw into colour and stencil attachments of one sample, with no depth attachment, no tessellation and no framebuffer fetch; each other kind is built when a replay stream makes one | 5: `crates/metal2vulkan-rt/src/render.rs (draw_input)`, `crates/metal2vulkan-rt/src/render.rs (of, 3 sites)` (+1) | `-` | | `FenceOtherQueue` | A `Fence` updated or waited on by an encoder of a queue other than the first that used it | every device (a public call's own check of its arguments) | `ours`: a fence is built for one queue; the replay streams use each on one queue | 1: `crates/metal2vulkan-rt/src/fence.rs (used_on)` | `-` | | `TextureView` | `Texture::new_texture_view` of a kind Metal makes and the runtime does not build | every device (a public call's own check of its arguments) | `ours`: the replay streams' views that compute binds are same-format views of every slice, 2D views of one slice of a 2D array, and level subranges; each other kind is built when a replay stream binds one | 1: `crates/metal2vulkan-rt/src/texture.rs (new_texture_view)` | `-` | | `RenderPass` | A render pass of something the runtime does not build yet (`CommandBuffer::render_command_encoder`) | every device (a public call's own check of its arguments) | `ours`: the replay streams' passes render into one to two color attachments and a stencil attachment, each a level of a 2D texture of one sample, with no depth attachment, no resolve and no store action left unknown; each other kind is built when a replay stream makes one | 3: `crates/metal2vulkan-rt/src/pass.rs (check)`, `crates/metal2vulkan-rt/src/pass.rs (ops)` (+1) | `-` | +| `Draw` | A draw or render encoder state the runtime does not build yet (`RenderCommandEncoder`) | every device (a public call's own check of its arguments) | `ours`: the replay streams draw lines and triangles under depth-stencil states that test no depth, through viewports Vulkan's are, with pipeline states of their pass's formats; each other kind is built when a replay stream draws one | 2: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)`, `crates/metal2vulkan-rt/src/render_encoder.rs (set_viewport)` | `-` | ## Appendix: every site @@ -1196,15 +1201,15 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::ManagedBlockNotShared`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` - `rt:Refusal::ModifiedRange`: `crates/metal2vulkan-rt/src/buffer.rs (did_modify_range)` - `rt:Refusal::Committed`: `crates/metal2vulkan-rt/src/command.rs (open)` -- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`; `crates/metal2vulkan-rt/src/blit.rs (copy_from_buffer_to_buffer)`; `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)`; `crates/metal2vulkan-rt/src/blit.rs (fill_buffer)`; `crates/metal2vulkan-rt/src/blit.rs (synchronize_resource)`; `crates/metal2vulkan-rt/src/command.rs (check)`; `crates/metal2vulkan-rt/src/device.rs (release_block)`; `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/encoder.rs (use_resource, 2 sites)`; `crates/metal2vulkan-rt/src/fence.rs (used_on)`; `crates/metal2vulkan-rt/src/pass.rs (check)`; `crates/metal2vulkan-rt/src/texture.rs (new_managed_texture)` +- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`; `crates/metal2vulkan-rt/src/blit.rs (copy_from_buffer_to_buffer)`; `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)`; `crates/metal2vulkan-rt/src/blit.rs (fill_buffer)`; `crates/metal2vulkan-rt/src/blit.rs (synchronize_resource)`; `crates/metal2vulkan-rt/src/command.rs (check)`; `crates/metal2vulkan-rt/src/device.rs (release_block)`; `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/encoder.rs (use_resource, 2 sites)`; `crates/metal2vulkan-rt/src/fence.rs (used_on)`; `crates/metal2vulkan-rt/src/pass.rs (check)`; `crates/metal2vulkan-rt/src/render_encoder.rs (draw)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_depth_stencil_state)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_render_pipeline_state)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/texture.rs (new_managed_texture)` - `rt:Refusal::NoCommandBuffers`: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` - `rt:Refusal::EncoderOpen`: `crates/metal2vulkan-rt/src/command.rs (open)` -- `rt:Refusal::NoPipeline`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` -- `rt:Refusal::BufferIndex`: `crates/metal2vulkan-rt/src/encoder.rs (slot)` -- `rt:Refusal::TextureArgumentIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_texture)` -- `rt:Refusal::SamplerArgumentIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)` -- `rt:Refusal::SamplerIds`: `crates/metal2vulkan-rt/src/pipeline.rs (number)` -- `rt:Refusal::NoBufferAtIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)` +- `rt:Refusal::NoPipeline`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)`; `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` +- `rt:Refusal::BufferIndex`: `crates/metal2vulkan-rt/src/encoder.rs (slot)`; `crates/metal2vulkan-rt/src/render_encoder.rs (slot)` +- `rt:Refusal::TextureArgumentIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_texture)` +- `rt:Refusal::SamplerArgumentIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_sampler_state)` +- `rt:Refusal::SamplerIds`: `crates/metal2vulkan-rt/src/pipeline.rs (number_samplers)` +- `rt:Refusal::NoBufferAtIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)`; `crates/metal2vulkan-rt/src/render_encoder.rs (draw)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_buffer_offset)` - `rt:Refusal::ThreadgroupSize`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch, 2 sites)` - `rt:Refusal::IndirectOffset`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` - `rt:Refusal::BufferOffsetAlignment`: `crates/metal2vulkan-rt/src/encoder.rs (check_alignment)` @@ -1237,11 +1242,15 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::AttachmentUsage`: `crates/metal2vulkan-rt/src/texture.rs (attachment)` - `rt:Refusal::AttachmentPlace`: `crates/metal2vulkan-rt/src/texture.rs (attachment)` - `rt:Refusal::AttachmentFormat`: `crates/metal2vulkan-rt/src/pass.rs (check, 2 sites)` +- `rt:Refusal::VertexBufferOffset`: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` +- `rt:Refusal::IndexBufferOffset`: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` +- `rt:Refusal::ViewportNotFinite`: `crates/metal2vulkan-rt/src/render_encoder.rs (set_viewport)` +- `rt:Refusal::StencilAttachment`: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` - `rt:Limit::BlockLen`: `crates/metal2vulkan-rt/src/memory.rs (round)` - `rt:Limit::BlockIds`: `crates/metal2vulkan-rt/src/memory.rs (number)` - `rt:Limit::ThreadgroupShape`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` - `rt:Limit::ThreadgroupMemory`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` -- `rt:Limit::BytesLength`: `crates/metal2vulkan-rt/src/encoder.rs (set_bytes)` +- `rt:Limit::BytesLength`: `crates/metal2vulkan-rt/src/encoder.rs (set_bytes)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_bytes)` - `rt:Limit::IndexRange`: `crates/metal2vulkan-rt/src/arrays.rs (grant)` - `rt:Limit::TextureSize`: `crates/metal2vulkan-rt/src/texture.rs (plan)` - `rt:Limit::DeviceSamplers`: `crates/metal2vulkan-rt/src/sampler.rs (take)` @@ -1263,8 +1272,9 @@ Each refusal's sites, with the function that builds it. - `rt:Gap::HeapTexture`: `crates/metal2vulkan-rt/src/texture.rs (heap_fit)`; `crates/metal2vulkan-rt/src/texture.rs (new_heap_texture)` - `rt:Gap::BufferCopyAlignment`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)` - `rt:Gap::FillAlignment`: `crates/metal2vulkan-rt/src/blit.rs (fill_range)` -- `rt:Gap::RenderPipeline`: `crates/metal2vulkan-rt/src/render.rs (of, 3 sites)`; `crates/metal2vulkan-rt/src/render.rs (refuse)` +- `rt:Gap::RenderPipeline`: `crates/metal2vulkan-rt/src/render.rs (draw_input)`; `crates/metal2vulkan-rt/src/render.rs (of, 3 sites)`; `crates/metal2vulkan-rt/src/render.rs (refuse)` - `rt:Gap::FenceOtherQueue`: `crates/metal2vulkan-rt/src/fence.rs (used_on)` - `rt:Gap::TextureView`: `crates/metal2vulkan-rt/src/texture.rs (new_texture_view)` - `rt:Gap::RenderPass`: `crates/metal2vulkan-rt/src/pass.rs (check)`; `crates/metal2vulkan-rt/src/pass.rs (ops)`; `crates/metal2vulkan-rt/src/texture.rs (attachment)` +- `rt:Gap::Draw`: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_viewport)`