diff --git a/crates/reims-vgpu-vulkan/src/rt_platform.rs b/crates/reims-vgpu-vulkan/src/rt_platform.rs index 5f46a279d..ad5dfa73c 100644 --- a/crates/reims-vgpu-vulkan/src/rt_platform.rs +++ b/crates/reims-vgpu-vulkan/src/rt_platform.rs @@ -10,8 +10,9 @@ //! [`mod@format`]), its command queues ([`queue`]), events, fences and shared events ([`event`]), //! the reservation of resource indices, buffers and the textures over them ([`buffer`]), heaps but //! sparse ones ([`heap`]), textures made of a descriptor, with their views ([`texture`]), -//! command buffers ([`command`]) with their blit encoders ([`blit`]), and sampler and -//! depth-stencil states ([`state`]). Until a piece is built, every +//! command buffers ([`command`]) with their blit encoders ([`blit`]), sampler and depth-stencil +//! states ([`state`]), libraries and their functions ([`library`]), and compute pipeline states +//! ([`pipeline`]). Until a piece is built, every //! call that reaches it is refused ([`unbuilt`]). The call answers as Metal's call answers where it //! fails: a nil object, an `NSError`, zeros. The refusal is counted under the piece's code, //! `rt-unbuilt-`, in the process's degradation counts, and the first of each kind writes a @@ -37,6 +38,8 @@ pub mod device; pub mod event; pub mod format; pub mod heap; +pub mod library; +pub mod pipeline; pub mod queue; pub mod state; pub mod texture; @@ -60,6 +63,8 @@ pub use command::RtCommandBuffer; pub use descriptor::{PassFields, RateMapFields, TextureFields}; pub use device::RtDevice; pub use heap::RtHeap; +pub use library::{RtFunction, RtLibrary}; +pub use pipeline::RtComputePipeline; pub use queue::RtQueue; pub use state::RtSampler; pub use texture::RtTexture; @@ -178,9 +183,9 @@ impl Platform for RtPlatform { type SharedEvent = RtObj; type SharedEventListener = RtObj; type SharedTextureHandle = Unmade; - type Library = Unmade; - type Function = Unmade; - type ComputePipeline = Unmade; + type Library = RtObj; + type Function = RtObj; + type ComputePipeline = RtObj; type FunctionHandle = Unmade; type VisibleFunctionTable = Unmade; type DynamicLibrary = Unmade; diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/device.rs b/crates/reims-vgpu-vulkan/src/rt_platform/device.rs index c375eaa0a..c98ad4697 100644 --- a/crates/reims-vgpu-vulkan/src/rt_platform/device.rs +++ b/crates/reims-vgpu-vulkan/src/rt_platform/device.rs @@ -18,7 +18,7 @@ //! **Its registry ID** folds its `deviceUUID` (`super::answers::registry_id`), so it differs from //! the Vulkan platform's for the same GPU, which metal2vulkan-runtime gives. -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use ash::vk; use metal2vulkan_rt as rt; @@ -43,6 +43,8 @@ use crate::gpu::identity; use super::answers::{self, Facts}; use super::buffer::{self, KnownBlocks}; use super::heap; +use super::library::{self, RtLibrary}; +use super::pipeline::{self, Numbering}; use super::queue::RtQueue; use super::texture::OwnIndices; use super::unbuilt::{ @@ -77,8 +79,13 @@ pub struct RtDevice { caps: Arc, /// The texture indices its textures the guest does not place take (`super::texture`). indices: OwnIndices, - /// The sampler indices its sampler states the guest does not place take (`super::state`). + /// The sampler indices its sampler states the guest does not place take (`super::state`), and + /// its pipeline states' samplers (`super::pipeline`). sampler_indices: OwnIndices, + /// The sampler indices its pipeline states' samplers hold. + numbering: Numbering, + /// The platform's shaders as its library, read at the first ask (`super::library`). + shaders: OnceLock>, /// The blocks it knows by address, which pinned buffers and heaps inside them are ranges of. known: KnownBlocks, } @@ -104,6 +111,11 @@ impl RtDevice { &self.sampler_indices } + /// The sampler indices its pipeline states' samplers hold. + pub fn numbering(&self) -> &Numbering { + &self.numbering + } + /// The blocks it knows by address (`super::buffer`'s docs, "A pinned address"): the graphics /// lane keeps a clone, the same set, to know and forget its blocks in. pub fn known_blocks(&self) -> &KnownBlocks { @@ -210,6 +222,8 @@ pub fn open(page_size: u64) -> Result, Unopened> { caps, indices: OwnIndices::new(rt::IndexClass::Texture), sampler_indices: OwnIndices::new(rt::IndexClass::Sampler), + numbering: Numbering::default(), + shaders: OnceLock::new(), known: KnownBlocks::default(), })) } @@ -364,13 +378,18 @@ impl GpuDevice for RtObj { Ok(None) } + /// Unbuilt: no encoder ([`Unbuilt::ArgumentLayout`]). fn function_argument_layout( &self, function: &::Function, buffer_index: u64, ) -> RaiseResult> { - let _ = buffer_index; - function.unreachable() + let _ = (function, buffer_index); + refuse_create( + Unbuilt::ArgumentLayout, + "newArgumentEncoderWithBufferIndex:", + ); + Ok(None) } /// rt's answer: the device's image's own memory requirements, rounded to its buffer-image @@ -463,26 +482,20 @@ impl GpuDevice for RtObj { .unwrap_or(0) } - /// Unbuilt ([`Unbuilt::Pipeline`]): the `NSError`. + /// rt's state of the function alone (`super::pipeline`); nil for no function. fn new_compute_pipeline_state_for_function( &self, compute_function: Option<&::Function>, ) -> Result::ComputePipeline>, NsErrorText> { - if let Some(function) = compute_function { - function.unreachable() - } - Err(refused_error( - Unbuilt::Pipeline, - "newComputePipelineStateWithFunction:error:", - )) + let Some(function) = compute_function else { + return Ok(None); + }; + pipeline::of_function(self, function).map(Some) } - /// Unbuilt ([`Unbuilt::Library`]): the `NSError`. + /// The platform's shaders, read once (`super::library`). fn new_shader_library(&self) -> Result::Library>, NsErrorText> { - Err(refused_error( - Unbuilt::Library, - "newLibraryWithSource:options:error:", - )) + library::shader_library(&self.shaders).map(Some) } /// rt's event; nil where rt refuses it. @@ -502,23 +515,24 @@ impl GpuDevice for RtObj { Ok(Some(RtObj::new(self.rt.new_fence()))) } - /// Unbuilt ([`Unbuilt::Library`]): the `NSError`. + /// The translator's library of a metallib (`super::library`). fn new_library( &self, data: &[u8], ) -> RaiseResult::Library>, NsErrorText>> { - let _ = data; - Ok(Err(refused_error( - Unbuilt::Library, - "newLibraryWithData:error:", - ))) + Ok(library::new_library(data).map(Some)) } + /// Unbuilt ([`Unbuilt::DynamicLibrary`]): the `NSError`. fn new_dynamic_library( &self, library: &::Library, ) -> RaiseResult::DynamicLibrary>, NsErrorText>> { - library.unreachable() + let _ = library; + Ok(Err(refused_error( + Unbuilt::DynamicLibrary, + "newDynamicLibrary:error:", + ))) } /// Unbuilt: nil ([`Unbuilt::RateMap`]). @@ -759,16 +773,12 @@ impl GpuDevice for RtObj { )) } - /// Unbuilt ([`Unbuilt::Pipeline`]): the `NSError`. + /// rt's state of the whole descriptor (`super::pipeline`). fn new_compute_pipeline_state_full( &self, desc: &FullComputePipelineDesc<'_, RtPlatform>, ) -> Result::ComputePipeline>, NsErrorText> { - let _ = desc; - Err(refused_error( - Unbuilt::Pipeline, - "newComputePipelineStateWithDescriptor:options:reflection:error:", - )) + pipeline::of_descriptor(self, desc).map(Some) } } diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/library.rs b/crates/reims-vgpu-vulkan/src/rt_platform/library.rs new file mode 100644 index 000000000..ac10229ae --- /dev/null +++ b/crates/reims-vgpu-vulkan/src/rt_platform/library.rs @@ -0,0 +1,216 @@ +//! The rt platform's libraries ([`RtLibrary`]) and functions ([`RtFunction`]): the translator's, +//! which rt's pipeline creators take. +//! +//! - **A library** is the translator's of a metallib (`newLibraryWithData:error:`), parsed from +//! its container's tags alone: no function is decoded until a pipeline compiles it. Other bytes, +//! raw AIR and a bitcode wrapper among them, are refused as Metal refuses them, with an +//! `NSError`, counted (`rt-refused-translation`), as is a metallib the translator cannot read. +//! The platform's own shaders (`newLibraryWithSource:options:error:`) are the metallib the build +//! makes of `shaders.metal` ([`crate::gpu::shaders::METALLIB`]), read once per device, and each +//! ask answers the same library. +//! - **A function** is a function of its library's table as it was made: with the constant values +//! it was specialized with, by index (`newFunctionWithName:constantValues:error:`), and the name +//! and options it was made under (`newFunctionWithDescriptor:error:`), as the translator's +//! `LinkedFunction` holds them. A pipeline compiles it, and checks its constant values then: +//! Metal checks them as it makes the function, so a value of the wrong type, or a required +//! constant given none, answers nil at Metal's function and at rt's pipeline. A name the table +//! lacks is nil, as Metal answers. A constant of a type no function constant takes, and options +//! Metal names none of, are Metal's refusal: nil, counted (`rt-refused-metal`). +//! `MTLFunctionOptionCompileToBinary` is the function's `precompiled`, which rt checks of a +//! binary function; the other options change nothing rt compiles. + +use std::sync::OnceLock; + +use metal2vulkan::error::{DescriptorError, Error as TranslatorError}; +use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues}; +use metal2vulkan::metal::{DataType, FunctionOptions}; +use metal2vulkan::pipeline::LinkedFunction; +use metal2vulkan_rt as rt; + +use crate::core::platform::Handle; +use crate::core::platform::resource::{FunctionConstant, Library}; +use crate::core::platform::types::NsErrorText; +use crate::core::raise::{OnFault, RaiseResult}; + +use super::texture::refused_metal; +use super::unbuilt::{rt_refused_create, rt_refused_error}; +use super::{RtObj, RtPlatform}; + +/// `newLibraryWithData:error:`. +const LIBRARY: &str = "newLibraryWithData:error:"; + +/// `newLibraryWithSource:options:error:`, which core asks the platform's shaders by. +const SHADERS: &str = "newLibraryWithSource:options:error:"; + +/// `id` on metal2vulkan-rt: the translator's library. +pub struct RtLibrary { + rt: rt::Library, +} + +impl RtLibrary { + /// The translator's library. + pub fn rt(&self) -> &rt::Library { + &self.rt + } +} + +/// `id` on metal2vulkan-rt: a function of a library, as it was made (the module's +/// docs). +pub struct RtFunction { + made: LinkedFunction, +} + +impl RtFunction { + /// The function as it was made, as a pipeline links it. + pub fn linked(&self) -> &LinkedFunction { + &self.made + } + + /// The function as a pipeline's stage: its library function, its constant values, and + /// whether it was made specialized. + pub fn stage(&self) -> rt::FunctionDescriptor { + let mut stage = rt::FunctionDescriptor::new(self.made.function.clone()); + stage.constants = self.made.constants.clone(); + stage.specialized = self.made.specialized; + stage + } + + /// The name the function answers: its specialized name where it was made with one, else its + /// library function's own. + pub fn name(&self) -> &str { + self.made.name() + } +} + +/// The library of `bytes` (`newLibraryWithData:error:`, the module's docs): `Err` is the +/// `NSError` of bytes the translator reads no metallib of, counted. +pub fn new_library(bytes: &[u8]) -> Result, NsErrorText> { + match rt::Library::from_metallib(bytes) { + Ok(rt) => Ok(RtObj::new(RtLibrary { rt })), + Err(error) => Err(rt_refused_error(LIBRARY, &rt::Error::Translation(error))), + } +} + +/// The platform's shaders as a library, read the first time `shaders` is asked and kept there: +/// each ask answers a new reference to it. `Err` is the `NSError` of the translator's refusal of +/// the metallib, counted at each ask. +pub fn shader_library( + shaders: &OnceLock>, +) -> Result, NsErrorText> { + if let Some(library) = shaders.get() { + return Ok(library.clone_ref()); + } + match rt::Library::from_metallib(crate::gpu::shaders::METALLIB) { + Ok(rt) => Ok(shaders + .get_or_init(|| RtObj::new(RtLibrary { rt })) + .clone_ref()), + Err(error) => Err(rt_refused_error(SHADERS, &rt::Error::Translation(error))), + } +} + +impl RtObj { + /// The function named `name` made as `made` makes it of the library function, by the creator + /// `sel`: nil for a name the table lacks, as Metal answers, and for one the translator refuses, + /// counted. + fn made( + &self, + sel: &'static str, + name: &str, + made: impl FnOnce(LinkedFunction) -> LinkedFunction, + ) -> Option> { + match self.rt.function(name) { + Ok(function) => Some(RtObj::new(RtFunction { + made: made(LinkedFunction::new(function)), + })), + Err(TranslatorError::InvalidDescriptor(DescriptorError::EntryNotFound { .. })) => None, + Err(error) => { + rt_refused_create(sel, &rt::Error::Translation(error)); + None + } + } + } +} + +impl Library for RtObj { + /// Every function of the table, in its order. + fn function_names(&self) -> Vec { + (self.rt.functions()) + .map(|info| info.name.to_owned()) + .collect() + } + + /// The function unspecialized, as `newFunctionWithName:` makes it. + fn new_function( + &self, + on: OnFault, + function_name: &str, + ) -> RaiseResult>> { + let _ = on; + Ok(self.made("newFunctionWithName:", function_name, |f| f)) + } + + /// The function specialized with `constants` (the module's docs). + fn new_function_with_constants( + &self, + on: OnFault, + function_name: &str, + constants: &[FunctionConstant], + ) -> RaiseResult>> { + let _ = on; + let sel = "newFunctionWithName:constantValues:error:"; + let Some(values) = constant_values(sel, constants) else { + return Ok(None); + }; + Ok(self.made(sel, function_name, |f| f.with_constants(values))) + } + + /// The function specialized, with `constants` where there are any, under `specialized_name` + /// where there is one, and compiled to a binary where `options` says so (the module's docs). + fn new_function_with_options( + &self, + on: OnFault, + function_name: &str, + constants: &[FunctionConstant], + options: u64, + specialized_name: Option<&str>, + ) -> RaiseResult>> { + let _ = on; + let sel = "newFunctionWithDescriptor:error:"; + let options = u32::try_from(options).ok().map(FunctionOptions::try_from); + let Some(Ok(options)) = options else { + return Ok(refused_metal(sel, &"function options Metal names none of")); + }; + let Some(values) = constant_values(sel, constants) else { + return Ok(None); + }; + Ok(self.made(sel, function_name, |f| { + let f = f + .with_constants(values) + .with_precompiled(options.contains(FunctionOptions::COMPILE_TO_BINARY)); + match specialized_name { + Some(name) => f.with_specialized_name(name), + None => f.with_specialized(true), + } + })) + } +} + +/// The translator's values of `constants`, each by its index: `None` where one is of a type no +/// function constant takes, Metal's refusal, counted. +fn constant_values( + sel: &'static str, + constants: &[FunctionConstant], +) -> Option { + let mut values = FunctionConstantValues::defaults(); + for c in constants { + let (Ok(ty), Some(bytes)) = (DataType::try_from(c.data_type), c.bytes()) else { + let why = format!( + "constant {} of MTLDataType {}, which no function constant takes", + c.index, c.data_type + ); + return refused_metal(sel, &why); + }; + values = values.with_index(c.index, FunctionConstantValue::new(ty, bytes.to_vec())); + } + Some(values) +} diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/pipeline.rs b/crates/reims-vgpu-vulkan/src/rt_platform/pipeline.rs new file mode 100644 index 000000000..d3637a221 --- /dev/null +++ b/crates/reims-vgpu-vulkan/src/rt_platform/pipeline.rs @@ -0,0 +1,586 @@ +//! The rt platform's compute pipeline states ([`RtComputePipeline`]): rt's, made of a function +//! (`newComputePipelineStateWithFunction:error:`) or of core's whole descriptor +//! (`newComputePipelineStateWithDescriptor:options:reflection:error:`), with the sampler indices +//! their samplers take ([`Numbering`]). +//! +//! - **The descriptor** is rt's of core's values: the kernel as its function was made +//! (`super::library`), the linked functions as theirs were, the stage-input descriptor, and the +//! descriptor's numbers, a value past rt's word held at the word's maximum, which rt refuses as +//! Metal refuses a value past its limit. rt refuses a state for indirect command buffers +//! (`rt-refused-gap`). Every refusal is the creator's `NSError`, counted under its kind. A +//! kernel made unspecialized (`newFunctionWithName:`) that declares function constants is +//! refused before rt compiles it (`rt-refused-metal`): Metal's creation ends the process at it. +//! - **Its samplers' indices.** rt numbers the samplers a state samples through as Metal's +//! creation does: its constexpr samplers, then one for a texture read and one for a texture +//! write, and takes an index of a live sampler grant for each. A sampler equal to one a live +//! state holds takes its index, as Metal's numbering does, and any other an index of the +//! platform's own (`super::texture`'s `OwnIndices`, the sampler states' own, which never takes +//! an index the guest reserved). rt places a constexpr sampler's device samplers at its index; +//! the read and write samplers take nothing there. A state gives its indices back as it goes, +//! after rt's state: an index whose last holder goes is the platform's again. Where none is +//! free, the creation is refused (`rt-refused-limit`). +//! - **Its answers.** `maxTotalThreadsPerThreadgroup` is rt's; `threadExecutionWidth` is 32, the +//! SIMD-group width rt runs every kernel's SIMD groups at; `gpuResourceID` and `resourceIndex` +//! are 0, as Metal's are for a state without indirect command buffer support; and +//! `uniqueIdentifier` is one of a process-wide count from 1, where Metal's is an address that +//! differs from run to run. rt's state answers no static threadgroup memory length and no +//! imageblock length: each is 0, counted (`rt-unbuilt-pipeline-query`). Function handles and +//! visible function tables are nil, counted (`rt-unbuilt-function-table`): rt's kernels take +//! no function table. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use metal2vulkan::Budget; +use metal2vulkan::metal::{AttributeFormat, IndexType, StepFunction}; +use metal2vulkan::pipeline::{ + LinkedFunction, LinkedFunctions, StageEntries, StageInputAttributeDescriptor, StageInputDescriptor, + StageInputLayoutDescriptor, +}; +use metal2vulkan_rt as rt; + +use crate::core::platform::resource::ComputePipeline; +use crate::core::platform::{Handle, Platform}; +use crate::core::platform::types::{MtlSize, NsErrorText}; +use crate::core::platform::values::{FullComputePipelineDesc, LinkedFunctionsDesc, StageInputDesc}; +use crate::core::raise::RaiseResult; +use crate::core::sync::Mutex; + +use super::device::RtDevice; +use super::library::RtFunction; +use super::state::value; +use super::texture::OwnIndices; +use super::unbuilt::{RtRefusal, Unbuilt, refuse, refuse_create, refused_error_as, rt_refused_error}; +use super::{RtObj, RtPlatform}; + +/// `newComputePipelineStateWithFunction:error:`. +pub const WITH_FUNCTION: &str = "newComputePipelineStateWithFunction:error:"; + +/// `newComputePipelineStateWithDescriptor:options:reflection:error:`. +pub const WITH_DESCRIPTOR: &str = "newComputePipelineStateWithDescriptor:options:reflection:error:"; + +/// `threadExecutionWidth`: the SIMD-group width rt runs every kernel's SIMD groups at. +pub const THREAD_EXECUTION_WIDTH: u64 = 32; + +/// `MTLBufferLayoutStrideDynamic`: a layout whose stride the encoder binds the buffer with. +const STRIDE_DYNAMIC: u64 = u64::MAX; + +/// The next `uniqueIdentifier` a state takes. +static NEXT_IDENTIFIER: AtomicU64 = AtomicU64::new(1); + +/// The sampler indices the live pipeline states' samplers hold (the module's docs): each sampler +/// a live state numbers, with its index and how many of the live states' samplers hold it. +#[derive(Default)] +pub struct Numbering { + held: Mutex>, +} + +/// A numbered sampler's index and its holders. +struct Held { + index: u32, + holders: usize, +} + +impl Numbering { + /// How many indices live states' samplers hold. + pub fn held(&self) -> usize { + self.held.lock().len() + } + + /// An index for each of `samplers`, in their order, held until [`give_back`](Self::give_back) + /// of the same samplers: a sampler equal to one held takes its index, and any other one of + /// `own`, granted on `device` where it is new. `Ok(None)` where none of `own` is free for one; + /// on `None` or `Err` it holds nothing. + fn take( + &self, + own: &OwnIndices, + device: &rt::Device, + samplers: &[rt::NumberedSampler], + ) -> Result>, rt::Error> { + let mut held = self.held.lock(); + let mut indices = Vec::with_capacity(samplers.len()); + for (at, sampler) in samplers.iter().enumerate() { + if let Some(h) = held.get_mut(sampler) { + h.holders = h.holders.saturating_add(1); + indices.push(h.index); + continue; + } + let taken = own.take(device); + let Ok(Some(index)) = taken else { + give_back(&mut held, own, samplers.get(..at).unwrap_or_default()); + return taken.map(|_| None); + }; + held.insert(*sampler, Held { index, holders: 1 }); + indices.push(index); + } + Ok(Some(indices)) + } + + /// Gives back one hold of each of `samplers`: an index whose last holder goes is `own`'s. + fn give_back(&self, own: &OwnIndices, samplers: &[rt::NumberedSampler]) { + give_back(&mut self.held.lock(), own, samplers); + } +} + +/// [`Numbering::give_back`] under its lock. +fn give_back( + held: &mut HashMap, + own: &OwnIndices, + samplers: &[rt::NumberedSampler], +) { + for sampler in samplers { + let Some(h) = held.get_mut(sampler) else { + continue; + }; + h.holders = h.holders.saturating_sub(1); + if h.holders == 0 { + own.give_back(h.index); + held.remove(sampler); + } + } +} + +/// The samplers a state holds indices for, given back at its drop. +struct Lease { + device: RtObj, + samplers: Vec, + /// Each one's index. + indices: Vec, +} + +impl Drop for Lease { + fn drop(&mut self) { + let device = &self.device; + (device.numbering()).give_back(device.sampler_indices(), &self.samplers); + } +} + +/// `id` on metal2vulkan-rt. +pub struct RtComputePipeline { + /// rt's state. Declared before `lease`, so it goes first: rt gives up a constexpr sampler's + /// device samplers before its index is the platform's again. + rt: rt::ComputePipelineState, + /// Its samplers' indices. + lease: Lease, + /// Its `uniqueIdentifier`. + unique_identifier: u64, +} + +impl RtComputePipeline { + /// rt's state. + pub fn rt(&self) -> &rt::ComputePipelineState { + &self.rt + } + + /// The samplers it numbers, in rt's order. + pub fn samplers(&self) -> &[rt::NumberedSampler] { + &self.lease.samplers + } + + /// The index each of [`samplers`](Self::samplers) holds. + pub fn sampler_indices(&self) -> &[u32] { + &self.lease.indices + } +} + +/// The state of `function` alone, as `newComputePipelineStateWithFunction:error:` makes it, with +/// Metal's defaults elsewhere. +pub fn of_function( + device: &RtObj, + function: &RtObj, +) -> Result, NsErrorText> { + let stage = function.stage(); + specialized(WITH_FUNCTION, &stage)?; + let descriptor = rt::ComputePipelineDescriptor::new(rt::StageSource::Function(stage)); + make(device, WITH_FUNCTION, &descriptor) +} + +/// The state of core's whole descriptor `desc` (the module's docs). +pub fn of_descriptor( + device: &RtObj, + desc: &FullComputePipelineDesc<'_, RtPlatform>, +) -> Result, NsErrorText> { + if let Some(library) = desc.libraries.preloaded.first() { + library.unreachable() + } + if let Some((_, library)) = desc.libraries.loaded.first() { + library.unreachable() + } + let mut stage = desc.function.stage(); + specialized(WITH_DESCRIPTOR, &stage)?; + stage.linked = linked_functions(&desc.linked); + let mut d = rt::ComputePipelineDescriptor::new(rt::StageSource::Function(stage)); + if let Some(input) = &desc.stage_input { + match stage_input(input) { + Ok(input) => d.stage_input = Some(input), + Err(why) => return Err(refused_error_as(WITH_DESCRIPTOR, RtRefusal::Refused, &why)), + } + } + d.max_total_threads_per_threadgroup = (desc.max_total_threads_per_threadgroup != 0) + .then(|| word(desc.max_total_threads_per_threadgroup)); + d.threadgroup_size_is_multiple_of_execution_width = + desc.threadgroup_size_is_multiple_of_execution_width; + d.support_indirect_command_buffers = desc.support_indirect_command_buffers; + d.max_call_stack_depth = word(desc.max_call_stack_depth); + d.open_cl_mode_enabled = desc.open_cl_mode; + make(device, WITH_DESCRIPTOR, &d) +} + +/// Whether Metal makes a state of `stage` by the creator `sel`: none of a function made +/// unspecialized that declares function constants (`FunctionDescriptor::needs_specialization`), +/// whose creation ends the process on Metal. `Err` is the creator's `NSError`, counted: Metal's +/// refusal, or the translator's of the function's constants. +fn specialized(sel: &'static str, stage: &rt::FunctionDescriptor) -> Result<(), NsErrorText> { + match stage.needs_specialization(&Budget::standard(), &StageEntries::default()) { + Ok(false) => Ok(()), + Ok(true) => { + let why = format!( + "function {} declares function constants and was made unspecialized", + stage.function.info().name + ); + Err(refused_error_as(sel, RtRefusal::Refused, &why)) + } + Err(error) => Err(rt_refused_error(sel, &rt::Error::Translation(error))), + } +} + +/// `v` as rt's word, held at the word's maximum. +fn word(v: u64) -> u32 { + u32::try_from(v).unwrap_or(u32::MAX) +} + +/// The translator's linked functions of `linked`, each as it was made. +fn linked_functions(linked: &LinkedFunctionsDesc) -> LinkedFunctions { + fn each(functions: &[RtObj]) -> Vec { + (functions.iter()) + .map(|function| function.linked().clone()) + .collect() + } + let mut out = LinkedFunctions::new(); + out.functions = each(&linked.functions); + out.binary_functions = each(&linked.binary_functions); + out.private_functions = each(&linked.private_functions); + out.groups = (linked.groups.iter()) + .map(|(name, functions)| (name.clone(), each(functions))) + .collect(); + out +} + +/// The translator's stage-input descriptor of `input`. +/// +/// Err: the first value it has no value of, named. +fn stage_input(input: &StageInputDesc) -> Result { + let mut out = StageInputDescriptor::new(); + out.index_type = value::("index type", input.index_type)?; + out.index_buffer_index = u32::try_from(input.index_buffer_index) + .map_err(|_| format!("index buffer index {}", input.index_buffer_index))?; + let mut layouts = BTreeMap::new(); + for l in &input.layouts { + let index = + u32::try_from(l.buffer_index).map_err(|_| format!("layout {}", l.buffer_index))?; + let stride = match l.stride { + STRIDE_DYNAMIC => None, + stride => Some(u32::try_from(stride).map_err(|_| format!("stride {stride}"))?), + }; + let mut layout = StageInputLayoutDescriptor::new(stride); + layout.step_function = value::("step function", l.step_function)?; + layout.step_rate = + u32::try_from(l.step_rate).map_err(|_| format!("step rate {}", l.step_rate))?; + layouts.insert(index, layout); + } + out.layouts = layouts; + for a in &input.attributes { + let index = (u32::try_from(a.attribute_index)) + .map_err(|_| format!("attribute {}", a.attribute_index))?; + let format = value::("attribute format", a.format)?; + let offset = u32::try_from(a.offset).map_err(|_| format!("offset {}", a.offset))?; + let buffer = (u32::try_from(a.buffer_index)) + .map_err(|_| format!("attribute buffer {}", a.buffer_index))?; + let attribute = StageInputAttributeDescriptor::new(format, offset, buffer); + out.attributes.insert(index, attribute); + } + Ok(out) +} + +/// rt's state of `descriptor`, by the creator `sel`, its samplers' indices taken (the module's +/// docs). `Err` is the creator's `NSError`, counted under the refusal's kind. +fn make( + device: &RtObj, + sel: &'static str, + descriptor: &rt::ComputePipelineDescriptor, +) -> Result, NsErrorText> { + let mut taken = (Vec::new(), Vec::new()); + let mut exhausted = false; + let made = device.rt().new_compute_pipeline_state(descriptor, |samplers| { + let indices = (device.numbering()).take(device.sampler_indices(), device.rt(), samplers)?; + let Some(indices) = indices else { + exhausted = true; + return Err(rt::Error::Refused(rt::Refusal::IndicesNotGranted { + class: rt::IndexClass::Sampler, + index: 0, + })); + }; + taken = (samplers.to_vec(), indices.clone()); + Ok(indices) + }); + let lease = Lease { + device: device.clone_ref(), + samplers: taken.0, + indices: taken.1, + }; + match made { + Ok(rt) => Ok(RtObj::new(RtComputePipeline { + rt, + lease, + unique_identifier: NEXT_IDENTIFIER.fetch_add(1, Ordering::Relaxed), + })), + Err(_) if exhausted => Err(refused_error_as( + sel, + RtRefusal::Limit, + &"live states and sampler states hold every sampler index", + )), + Err(error) => Err(rt_refused_error(sel, &error)), + } +} + +impl ComputePipeline for RtObj { + /// 0: rt makes no state for indirect command buffers. + fn gpu_resource_id(&self) -> u64 { + 0 + } + + /// Unbuilt: nil ([`Unbuilt::FunctionTable`]). + fn function_handle( + &self, + function: &RtObj, + ) -> RaiseResult::FunctionHandle>> { + let _ = function; + refuse_create(Unbuilt::FunctionTable, "functionHandleWithFunction:"); + Ok(None) + } + + /// Unbuilt: nil ([`Unbuilt::FunctionTable`]). + fn new_visible_function_table( + &self, + function_count: u64, + ) -> RaiseResult::VisibleFunctionTable>> { + let _ = function_count; + refuse_create( + Unbuilt::FunctionTable, + "newVisibleFunctionTableWithDescriptor:", + ); + Ok(None) + } + + /// Unbuilt: 0 ([`Unbuilt::PipelineQuery`]). + fn imageblock_memory_length(&self, imageblock_dimensions: MtlSize) -> RaiseResult { + let _ = imageblock_dimensions; + refuse( + Unbuilt::PipelineQuery, + "imageblockMemoryLengthForDimensions:", + ); + Ok(0) + } + + fn max_total_threads_per_threadgroup(&self) -> u64 { + u64::from(self.rt.max_total_threads_per_threadgroup()) + } + + /// 0, as [`gpu_resource_id`](Self::gpu_resource_id). + fn resource_index(&self) -> u64 { + 0 + } + + /// Unbuilt: 0 ([`Unbuilt::PipelineQuery`]). + fn static_threadgroup_memory_length(&self) -> u64 { + refuse(Unbuilt::PipelineQuery, "staticThreadgroupMemoryLength"); + 0 + } + + fn support_indirect_command_buffers(&self) -> bool { + false + } + + fn thread_execution_width(&self) -> u64 { + THREAD_EXECUTION_WIDTH + } + + fn unique_identifier(&self) -> u64 { + self.unique_identifier + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::platform::device::GpuDevice as _; + use crate::core::platform::resource::{FunctionConstant, Library as _}; + use crate::core::platform::values::{AttributeDesc, BufferLayoutDesc}; + use crate::core::raise::OnFault; + + /// `numbered_samplers.metal`'s functions, compiled by build.rs. + const NUMBERED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/numbered_samplers.metallib")); + + /// `optional_constant.metal`'s kernel, compiled by build.rs. + const OPTIONAL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/optional_constant.metallib")); + + fn counted(code: &str) -> u64 { + (crate::answer::degradation_counts().into_iter()) + .find(|(c, _)| c == code) + .map_or(0, |(_, n)| n) + } + + /// Each value of a stage-input descriptor is the translator's, a dynamic stride none; a value + /// it has none of is named. + #[test] + fn stage_input_values_are_the_translator_s() { + let input = StageInputDesc { + layouts: vec![ + BufferLayoutDesc { + buffer_index: 1, + stride: 16, + step_function: 5, + step_rate: 1, + }, + BufferLayoutDesc { + buffer_index: 2, + stride: u64::MAX, + step_function: 0, + step_rate: 0, + }, + ], + attributes: vec![AttributeDesc { + attribute_index: 3, + format: 31, + offset: 4, + buffer_index: 1, + }], + index_type: 1, + index_buffer_index: 7, + }; + let out = stage_input(&input).expect("the translator's values"); + assert_eq!( + (out.index_type, out.index_buffer_index), + (IndexType::UInt32, 7) + ); + let one = out.layouts.get(&1).expect("layout 1"); + assert_eq!(one.stride, Some(16)); + assert_eq!(one.step_function, StepFunction::ThreadPositionInGridX); + let two = out.layouts.get(&2).expect("layout 2"); + assert_eq!((two.stride, two.step_function), (None, StepFunction::Constant)); + let attribute = StageInputAttributeDescriptor::new(AttributeFormat::Float4, 4, 1); + assert_eq!(out.attributes.get(&3), Some(&attribute)); + + let mut bad = input.clone(); + bad.layouts[0].step_function = 99; + assert_eq!(stage_input(&bad).err(), Some("step function 99".to_owned())); + } + + /// Libraries of metallibs and the platform's shaders, functions as they were made, and compute + /// states of them: samplers equal to a live state's take its index and give it back with the + /// last; every refusal is counted. + #[test] + fn libraries_and_compute_pipelines_on_vulkan() { + let platform = RtPlatform::new(); + let device = (platform.system_default_device()).expect("an rt device on the GPU it holds"); + let on = OnFault::Return; + let translation = RtRefusal::Translation.code(); + let metal = RtRefusal::Refused.code(); + + let before = counted(translation); + let junk = device.new_library(b"no metallib").expect("never a raise"); + assert!(junk.is_err()); + assert_eq!(counted(translation), before + 1); + + let shaders = device.new_shader_library().expect("our shaders").expect("a library"); + let again = device.new_shader_library().expect("our shaders").expect("a library"); + assert_eq!(shaders.id(), again.id()); + assert!(shaders.function_names().iter().any(|n| n == "displayMirrorTile")); + + let library = device.new_library(NUMBERED).expect("never a raise"); + let library = library.expect("a metallib").expect("a library"); + let names = library.function_names(); + for name in ["numbered_read", "numbered_sample", "numbered_write"] { + assert!(names.iter().any(|n| n == name), "{names:?}"); + } + assert!(library.new_function(on, "absent").expect("never a raise").is_none()); + let function = |name: &str| { + let made = library.new_function(on, name).expect("never a raise"); + made.expect("a function of the table") + }; + let state = |f: &RtObj| { + let made = device.new_compute_pipeline_state_for_function(Some(f)); + made.expect("a compute state").expect("a compute state") + }; + + let last = rt::IndexClass::Sampler.range().end - 1; + let held = device.numbering().held(); + let sample = function("numbered_sample"); + let first = state(&sample); + let second = state(&sample); + assert!(matches!(first.samplers(), [rt::NumberedSampler::Constexpr(_)])); + assert_eq!(first.sampler_indices(), [last]); + assert_eq!(second.sampler_indices(), [last]); + assert_eq!(device.numbering().held(), held + 1); + let read = state(&function("numbered_read")); + assert_eq!(read.samplers(), [rt::NumberedSampler::Read]); + assert_eq!(read.sampler_indices(), [last - 1]); + assert_eq!(device.numbering().held(), held + 2); + + assert!(first.max_total_threads_per_threadgroup() > 0); + assert_eq!(first.thread_execution_width(), 32); + assert_eq!((first.gpu_resource_id(), first.resource_index()), (0, 0)); + assert!(!first.support_indirect_command_buffers()); + assert_ne!(first.unique_identifier(), 0); + assert_ne!(first.unique_identifier(), second.unique_identifier()); + + let tables = counted(Unbuilt::FunctionTable.code()); + assert!(first.function_handle(&sample).expect("never a raise").is_none()); + assert!(first.new_visible_function_table(2).expect("never a raise").is_none()); + assert_eq!(counted(Unbuilt::FunctionTable.code()), tables + 2); + let queries = counted(Unbuilt::PipelineQuery.code()); + assert_eq!(first.static_threadgroup_memory_length(), 0); + assert_eq!(counted(Unbuilt::PipelineQuery.code()), queries + 1); + + drop((first, second, read)); + assert_eq!(device.numbering().held(), held); + + let mut desc = FullComputePipelineDesc::new(&sample); + desc.max_total_threads_per_threadgroup = 64; + let limited = device.new_compute_pipeline_state_full(&desc); + let limited = limited.expect("a compute state").expect("a compute state"); + assert_eq!(limited.max_total_threads_per_threadgroup(), 64); + + let optional = device.new_library(OPTIONAL).expect("never a raise"); + let optional = optional.expect("a metallib").expect("a library"); + let plain = optional.new_function(on, "optional_constant").expect("never a raise"); + let plain = plain.expect("a function of the table"); + let before = counted(metal); + let refused = device.new_compute_pipeline_state_for_function(Some(&plain)); + assert!(refused.is_err()); + assert_eq!(counted(metal), before + 1); + let five = FunctionConstant { + index: 0, + data_type: 29, + value: [5; FunctionConstant::MAX_BYTES], + }; + let made = optional.new_function_with_constants(on, "optional_constant", &[five]); + let specialized = made.expect("never a raise").expect("a specialized function"); + assert!(state(&specialized).max_total_threads_per_threadgroup() > 0); + let made = optional.new_function_with_options(on, "optional_constant", &[], 0, Some("o")); + let named = made.expect("never a raise").expect("a function made by a descriptor"); + assert_eq!(named.name(), "o"); + assert!(state(&named).max_total_threads_per_threadgroup() > 0); + + let before = counted(metal); + let unknown = FunctionConstant { + data_type: 7, + ..five + }; + let made = optional.new_function_with_constants(on, "optional_constant", &[unknown]); + assert!(made.expect("never a raise").is_none()); + let made = optional.new_function_with_options(on, "optional_constant", &[], 0x100, None); + assert!(made.expect("never a raise").is_none()); + assert_eq!(counted(metal), before + 2); + } +} diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/state.rs b/crates/reims-vgpu-vulkan/src/rt_platform/state.rs index cc4853952..d159bce4b 100644 --- a/crates/reims-vgpu-vulkan/src/rt_platform/state.rs +++ b/crates/reims-vgpu-vulkan/src/rt_platform/state.rs @@ -61,7 +61,7 @@ impl RtSampler { } /// The raw value `raw` as rt's `T`, or the error naming it as `what`. -fn value>(what: &str, raw: u64) -> Result { +pub(super) fn value>(what: &str, raw: u64) -> Result { let named = || format!("{what} {raw}"); let raw = u32::try_from(raw).map_err(|_| named())?; T::try_from(raw).map_err(|_| named()) diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/unbuilt.rs b/crates/reims-vgpu-vulkan/src/rt_platform/unbuilt.rs index 1ea35273e..4ed6948b5 100644 --- a/crates/reims-vgpu-vulkan/src/rt_platform/unbuilt.rs +++ b/crates/reims-vgpu-vulkan/src/rt_platform/unbuilt.rs @@ -47,12 +47,16 @@ pub enum Unbuilt { /// What of heaps is not built yet (`super::heap`): a sparse heap, whose ranges rt maps no /// tiles of. Each answers nil. Heap, - /// Libraries and their functions (`newLibraryWithData:error:`): over the translator's - /// library. Each answers nil. - Library, - /// Compute and render pipeline states. Each answers nil, with an `NSError` where Metal's + /// Render and mesh render pipeline states. Each answers nil, with an `NSError` where Metal's /// creation fills one. Pipeline, + /// Function handles and visible function tables (`functionHandleWithFunction:`, + /// `newVisibleFunctionTableWithDescriptor:`): rt's kernels take no function table. Each + /// answers nil. + FunctionTable, + /// What a pipeline state answers that rt's state does not: its static threadgroup memory + /// length and its imageblock lengths. Each answers 0. + PipelineQuery, /// Argument buffers' layouts (`newArgumentEncoderWithArguments:` and a function's). Each /// answers nil. ArgumentLayout, @@ -89,13 +93,14 @@ pub enum Unbuilt { impl Unbuilt { /// Every piece, once, in the order of their codes' places. - pub const ALL: [Unbuilt; 16] = [ + pub const ALL: [Unbuilt; 17] = [ Unbuilt::Buffer, Unbuilt::IosurfaceTexture, Unbuilt::SharedTexture, Unbuilt::Heap, - Unbuilt::Library, Unbuilt::Pipeline, + Unbuilt::FunctionTable, + Unbuilt::PipelineQuery, Unbuilt::ArgumentLayout, Unbuilt::Encoder, Unbuilt::Protection, @@ -115,8 +120,9 @@ impl Unbuilt { Unbuilt::IosurfaceTexture => "rt-unbuilt-iosurface-texture", Unbuilt::SharedTexture => "rt-unbuilt-shared-texture", Unbuilt::Heap => "rt-unbuilt-heap", - Unbuilt::Library => "rt-unbuilt-library", Unbuilt::Pipeline => "rt-unbuilt-pipeline", + Unbuilt::FunctionTable => "rt-unbuilt-function-table", + Unbuilt::PipelineQuery => "rt-unbuilt-pipeline-query", Unbuilt::ArgumentLayout => "rt-unbuilt-argument-layout", Unbuilt::Encoder => "rt-unbuilt-encoder", Unbuilt::Protection => "rt-unbuilt-protection", @@ -137,8 +143,9 @@ impl Unbuilt { Unbuilt::IosurfaceTexture => "a texture over an IOSurface's plane", Unbuilt::SharedTexture => "a shared texture", Unbuilt::Heap => "a sparse heap", - Unbuilt::Library => "a library", - Unbuilt::Pipeline => "a pipeline state", + Unbuilt::Pipeline => "a render pipeline state", + Unbuilt::FunctionTable => "a function handle or a visible function table", + Unbuilt::PipelineQuery => "a pipeline state's threadgroup memory or imageblock length", Unbuilt::ArgumentLayout => "an argument buffer's layout", Unbuilt::Encoder => "a compute or render command encoder", Unbuilt::Protection => "a command buffer's protection options", @@ -360,6 +367,34 @@ pub fn rt_refused_texture(sel: &'static str, error: &rt::Error) -> RtRefusal { RtRefusal::Gap } +/// [`rt_refused_create`] of a creator with an `error:` out-parameter: the `NSError` it answers, in +/// [`RT_DOMAIN`], code 0, naming rt's error and its kind's code. +pub fn rt_refused_error(sel: &'static str, error: &rt::Error) -> NsErrorText { + let kind = rt_refused_create(sel, error); + rt_error(kind, error) +} + +/// [`refused_as`] of a creator with an `error:` out-parameter, noted for core as a gap of the +/// platform's own as [`refuse_create`] does: the `NSError` it answers, as [`rt_refused_error`]'s. +pub fn refused_error_as( + sel: &'static str, + kind: RtRefusal, + why: &dyn std::fmt::Display, +) -> NsErrorText { + crate::core::platform::device::note_relayed_gap(); + refused_as(sel, kind, why); + rt_error(kind, why) +} + +/// The `NSError` of a refusal of the kind `kind` for `why`. +fn rt_error(kind: RtRefusal, why: &dyn std::fmt::Display) -> NsErrorText { + NsErrorText { + domain: RT_DOMAIN.to_owned(), + code: 0, + description: format!("metal2vulkan-rt refused it: {why} ({})", kind.code()), + } +} + /// [`rt_refused_texture`] of a creator, which answers nil where Metal makes the texture: noted /// for core as a gap of the platform's own, as [`refuse_create`] does. pub fn rt_refused_texture_create(sel: &'static str, error: &rt::Error) -> RtRefusal { @@ -488,12 +523,22 @@ mod tests { #[test] fn a_refused_creator_answers_an_nserror() { let (error, relayed) = - relaying_gaps(|| refused_error(Unbuilt::Library, "newLibraryWithData:error:")); + relaying_gaps(|| refused_error(Unbuilt::DynamicLibrary, "newDynamicLibrary:error:")); assert!(relayed); assert_eq!((error.domain.as_str(), error.code), (RT_DOMAIN, 0)); assert_eq!( error.description, - "a library is not built on metal2vulkan-rt (rt-unbuilt-library)" + "a dynamic library is not built on metal2vulkan-rt (rt-unbuilt-dynamic-library)" + ); + let (error, relayed) = relaying_gaps(|| rt_refused_error("test", &rt::Error::Quiesced)); + assert!(relayed); + assert_eq!(error.domain, RT_DOMAIN); + assert!(error.description.ends_with("(rt-refused-quiesced)"), "{error}"); + let (error, relayed) = relaying_gaps(|| refused_error_as("test", RtRefusal::Limit, &"full")); + assert!(relayed); + assert_eq!( + error.description, + "metal2vulkan-rt refused it: full (rt-refused-limit)" ); let code = RtRefusal::NoDevice.code(); let before = counted(code); diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/unmade.rs b/crates/reims-vgpu-vulkan/src/rt_platform/unmade.rs index 2eb678dc6..c6d2c9db2 100644 --- a/crates/reims-vgpu-vulkan/src/rt_platform/unmade.rs +++ b/crates/reims-vgpu-vulkan/src/rt_platform/unmade.rs @@ -19,7 +19,6 @@ use crate::core::platform::icb::IcbRenderCmd; use crate::core::platform::icb::ImageBlockArgs; use crate::core::platform::icb::TessellationFactorArgs; use crate::core::platform::render::RenderCmd; -use crate::core::platform::resource::FunctionConstant; use crate::core::platform::types::MtlCoordinate2D; use crate::core::platform::types::MtlRegion; use crate::core::platform::types::MtlSize; @@ -62,12 +61,6 @@ pub mod kinds { pub enum RenderEncoder {} /// `MTLSharedTextureHandle *`. pub enum SharedTextureHandle {} - /// `id`. - pub enum Library {} - /// `id`. - pub enum Function {} - /// `id`. - pub enum ComputePipeline {} /// `id`. pub enum FunctionHandle {} /// `id`. @@ -121,42 +114,6 @@ impl render::RenderEncoder

for Unmade { } } -impl resource::ComputePipeline

for Unmade { - fn gpu_resource_id(&self) -> u64 { - self.unreachable() - } - fn function_handle(&self, _function: &P::Function) -> RaiseResult> { - self.unreachable() - } - fn new_visible_function_table( - &self, - _function_count: u64, - ) -> RaiseResult> { - self.unreachable() - } - fn imageblock_memory_length(&self, _imageblock_dimensions: MtlSize) -> RaiseResult { - self.unreachable() - } - fn max_total_threads_per_threadgroup(&self) -> u64 { - self.unreachable() - } - fn resource_index(&self) -> u64 { - self.unreachable() - } - fn static_threadgroup_memory_length(&self) -> u64 { - self.unreachable() - } - fn support_indirect_command_buffers(&self) -> bool { - self.unreachable() - } - fn thread_execution_width(&self) -> u64 { - self.unreachable() - } - fn unique_identifier(&self) -> u64 { - self.unreachable() - } -} - impl resource::RenderPipeline for Unmade { fn gpu_resource_id(&self) -> u64 { self.unreachable() @@ -199,33 +156,6 @@ impl resource::RenderPipeline for Unmade { } } -impl resource::Library

for Unmade { - fn function_names(&self) -> Vec { - self.unreachable() - } - fn new_function(&self, _on: OnFault, _function_name: &str) -> RaiseResult> { - self.unreachable() - } - fn new_function_with_constants( - &self, - _on: OnFault, - _function_name: &str, - _constants: &[FunctionConstant], - ) -> RaiseResult> { - self.unreachable() - } - fn new_function_with_options( - &self, - _on: OnFault, - _function_name: &str, - _constants: &[FunctionConstant], - _options: u64, - _specialized_name: Option<&str>, - ) -> RaiseResult> { - self.unreachable() - } -} - impl function_table::VisibleFunctionTable

for Unmade { fn gpu_resource_id(&self) -> u64 { self.unreachable()