app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+73
View File
@@ -0,0 +1,73 @@
[package]
name = "rune-gpu"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "GPU adapter selection, backend dispatch, native Apple Metal backend, and analytic GPU springs for Rune."
[features]
default = ["metal-backend"]
# macOS and iOS: Rune's native Metal backend (research/34). Mac apps draw with it by default; an
# app opts out with `App::gpu_backend(GpuBackend::Wgpu)`, or a launch with `RUNE_GPU_BACKEND=wgpu`,
# and an app built with `default-features = false` draws with wgpu unless it adds this feature.
# iOS apps keep wgpu unless they choose `GpuBackend::Metal`. It plugs in through wgpu's `custom`
# backend, which rune-gpu turns on for Apple targets alone. No effect on other platforms: its crates
# are Apple-only dependencies.
metal-backend = [
"dep:blake3",
"dep:libc",
"dep:objc2-core-foundation",
"dep:objc2-foundation",
"dep:objc2-metal",
"dep:objc2-quartz-core",
"dep:parking_lot",
"dep:raw-window-metal",
"dep:wgpu-naga-bridge",
]
# Live GPU resource counters (`Device::get_internal_counters`) for the storage-swap buffer-count test.
test-gpu-counters = ["wgpu/counters"]
[dependencies]
bytemuck = { workspace = true }
rune-core = { workspace = true }
rune-motion = { workspace = true }
# `health::poll` lives there, below every crate that waits on the GPU.
rune-staging = { workspace = true }
wgpu = { workspace = true, features = ["std", "parking_lot", "wgsl"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
pollster = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wgpu = { workspace = true, features = ["webgpu"] }
[target.'cfg(target_vendor = "apple")'.dependencies]
blake3 = { workspace = true, optional = true }
libc = { workspace = true, optional = true }
objc2 = { workspace = true }
objc2-core-foundation = { workspace = true, optional = true, features = ["std", "CFCGTypes", "objc2"] }
objc2-foundation = { workspace = true, optional = true, features = ["std", "NSArray", "NSError", "NSObject", "NSRange", "NSString"] }
objc2-metal = { workspace = true, optional = true, features = ["std", "MTLAllocation", "MTLArgument", "MTLBlitCommandEncoder", "MTLBuffer", "MTLCommandBuffer", "MTLCommandEncoder", "MTLCommandQueue", "MTLComputeCommandEncoder", "MTLComputePass", "MTLComputePipeline", "MTLCounters", "MTLDepthStencil", "MTLDevice", "MTLDrawable", "MTLEvent", "MTLLibrary", "MTLPixelFormat", "MTLRenderCommandEncoder", "MTLRenderPass", "MTLRenderPipeline", "MTLResource", "MTLSampler", "MTLTexture", "MTLTypes", "MTLVertexDescriptor"] }
objc2-quartz-core = { version = "0.3.2", optional = true, default-features = false, features = ["std", "bitflags", "CALayer", "CAMetalLayer", "objc2-core-foundation", "objc2-core-graphics", "objc2-metal"] }
parking_lot = { version = "0.12", optional = true }
raw-window-metal = { version = "1.1", optional = true }
wgpu-naga-bridge = { workspace = true, optional = true }
# wgpu's Metal backend and `custom` backend (`metal-backend` plugs into it), on Apple targets alone:
# off Apple, wgpu compiles neither `wgpu-hal/metal` nor `naga/msl-out`, and dispatches with no branch.
wgpu = { workspace = true, features = ["metal", "custom"] }
[target.'cfg(target_os = "windows")'.dependencies]
wgpu = { workspace = true, features = ["dx12"] }
windows = { workspace = true, features = ["Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi"] }
windows-sys = { workspace = true, features = ["Win32_Graphics_Gdi"] }
[target.'cfg(target_os = "linux")'.dependencies]
wayland-client = "0.31"
wayland-protocols = { version = "0.32", features = ["client", "staging"] }
# wgpu's Vulkan backend everywhere but Windows (D3D12 above) and Apple (Metal above).
[target.'cfg(all(not(target_vendor = "apple"), not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies]
wgpu = { workspace = true, features = ["vulkan"] }
[lints]
workspace = true
+219
View File
@@ -0,0 +1,219 @@
//! Which backend an Apple app draws with: Rune's native Metal backend (`metal-backend`, on by
//! default, and the default on macOS), or wgpu's.
use std::sync::atomic::{AtomicU8, Ordering};
/// The GPU backend an app draws with on macOS (`App::gpu_backend`) and iOS (`prewarm_gpu_on`, before
/// the first `embed::LayerHost`). Elsewhere wgpu picks one.
///
/// A Mac app that chooses neither draws with `Metal` when Rune's `metal-backend` feature is on (it
/// is by default), and with `Wgpu` when it's off; an iOS app draws with `Wgpu`. `Default` stays `Wgpu`; passing it to
/// `App::gpu_backend` opts out of the native backend.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GpuBackend {
/// wgpu's Metal backend.
#[default]
Wgpu,
/// Rune's native Metal backend, with Rune's `metal-backend` feature; without it, wgpu.
Metal,
}
const UNSET: u8 = 0;
const WGPU: u8 = 1;
const METAL: u8 = 2;
/// What the app chose: nothing yet, `Wgpu` or `Metal`.
#[cfg_attr(not(all(target_vendor = "apple", feature = "metal-backend")), allow(dead_code))]
static CHOSEN: AtomicU8 = AtomicU8::new(UNSET);
/// The backend an app that chooses none draws with: the native one on macOS with the feature.
const DEFAULT: GpuBackend = if cfg!(all(target_os = "macos", feature = "metal-backend")) { GpuBackend::Metal } else { GpuBackend::Wgpu };
/// Makes GPUs from now on with `backend`, process-wide. Returns `true` when the active backend
/// changed, so a caller with a prewarm running on the old backend can start it over.
#[cfg_attr(not(target_vendor = "apple"), allow(unused_variables))]
pub fn choose(backend: GpuBackend) -> bool {
#[cfg(all(target_vendor = "apple", not(feature = "metal-backend")))]
if backend == GpuBackend::Metal {
eprintln!("rune: GpuBackend::Metal needs Rune's `metal-backend` feature; drawing with wgpu");
}
#[cfg(all(target_vendor = "apple", feature = "metal-backend"))]
{
let before = current();
CHOSEN.store(match backend { GpuBackend::Wgpu => WGPU, GpuBackend::Metal => METAL }, Ordering::Relaxed);
return current() != before;
}
#[cfg(not(all(target_vendor = "apple", feature = "metal-backend")))]
false
}
fn chosen() -> Option<GpuBackend> {
match CHOSEN.load(Ordering::Relaxed) {
WGPU => Some(GpuBackend::Wgpu),
METAL => Some(GpuBackend::Metal),
_ => None,
}
}
fn env() -> Option<String> {
rune_core::env::var("RUNE_GPU_BACKEND")
}
/// The backend GPUs are made with: `RUNE_GPU_BACKEND` (`wgpu` or `metal`) over the app's
/// choice, over the default.
pub fn current() -> GpuBackend {
resolve(env().as_deref(), chosen())
}
/// What `RUNE_GPU_LOG` calls the backend `adapter` is on.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn label(adapter: &wgpu::Adapter) -> &'static str {
#[cfg(all(target_vendor = "apple", feature = "metal-backend"))]
if crate::metal::owns_adapter(adapter) {
return "rune backend";
}
let _ = adapter;
"wgpu"
}
/// Whether `device` is the native Metal backend's.
pub fn native(device: &wgpu::Device) -> bool {
#[cfg(all(target_vendor = "apple", feature = "metal-backend"))]
return crate::metal::raw_device(device).is_some();
#[cfg(not(all(target_vendor = "apple", feature = "metal-backend")))]
{
let _ = device;
false
}
}
/// Features a device on `adapter` gets whether or not a compositor asks: all the native backend
/// offers, which cost it nothing, so a prewarmed device serves any compositor it can draw for.
pub fn free_features(adapter: &wgpu::Adapter) -> wgpu::Features {
#[cfg(all(target_vendor = "apple", feature = "metal-backend"))]
if crate::metal::owns_adapter(adapter) {
return crate::metal::FEATURES;
}
let _ = adapter;
// Dmabuf frames from other processes (`native_surface::linux`): extensions the device enables
// whenever the driver has them; the feature only lets wgpu import with them.
#[cfg(target_os = "linux")]
return wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF;
#[cfg(not(target_os = "linux"))]
wgpu::Features::empty()
}
/// The features the last compositor that fell back to wgpu wanted and the native backend lacks.
#[cfg_attr(not(all(target_vendor = "apple", feature = "metal-backend")), allow(dead_code))]
static MISSING: std::sync::Mutex<wgpu::Features> = std::sync::Mutex::new(wgpu::Features::empty());
/// Whether a GPU for a compositor that wants `wanted` draws with wgpu instead of the native
/// backend: only when the native backend is the default, neither the app nor the environment
/// asked for it, and it lacks one of `wanted`'s features. Says so once.
#[cfg_attr(not(all(target_vendor = "apple", feature = "metal-backend")), allow(unused_variables))]
pub fn wgpu_for(wanted: wgpu::Features) -> bool {
#[cfg(all(target_vendor = "apple", feature = "metal-backend"))]
{
let missing = wanted - crate::metal::FEATURES;
if !missing.is_empty() && DEFAULT == GpuBackend::Metal && defaulted(env().as_deref(), chosen()) {
*MISSING.lock().unwrap_or_else(|e| e.into_inner()) = missing;
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| eprintln!("rune: the compositor wants {missing}, which Rune's Metal backend lacks; drawing with wgpu"));
return true;
}
}
false
}
/// Which backend draws on `device`, on which GPU, and why, for an app's log: "Rune's Metal
/// backend on Apple M4 (the default)", or "wgpu Metal on Apple M4 (a compositor wants
/// POLYGON_MODE_LINE, which Rune's Metal backend lacks)". A window's compositor gets its device in
/// `compose::Frame::device`. `RUNE_GPU_LOG=1` prints it for each window and overlay GPU Rune makes.
pub fn describe(device: &wgpu::Device) -> String {
let info = device.adapter_info();
let backend = if native(device) { "Rune's Metal backend".to_string() } else { format!("wgpu {:?}", info.backend) };
let why = reason(native(device));
if why.is_empty() { format!("{backend} on {}", info.name) } else { format!("{backend} on {} ({why})", info.name) }
}
/// Why the backend is the native one (`native`) or wgpu's; empty where wgpu is the only one.
fn reason(native: bool) -> String {
#[cfg(all(target_vendor = "apple", feature = "metal-backend"))]
{
let (env, chosen) = (env(), chosen());
let missing = *MISSING.lock().unwrap_or_else(|e| e.into_inner());
return match (native, env.as_deref(), chosen) {
(true, Some("metal"), _) => "RUNE_GPU_BACKEND=metal".into(),
(true, _, Some(GpuBackend::Metal)) => "App::gpu_backend chose it".into(),
(true, ..) => "the default".into(),
(false, Some("wgpu"), _) => "RUNE_GPU_BACKEND=wgpu".into(),
(false, _, Some(GpuBackend::Wgpu)) => "App::gpu_backend chose it".into(),
(false, ..) if DEFAULT == GpuBackend::Wgpu => "the default here".into(),
(false, ..) if !missing.is_empty() => format!("a compositor wants {missing}, which Rune's Metal backend lacks"),
(false, ..) => String::new(),
};
}
#[cfg(all(target_vendor = "apple", not(feature = "metal-backend")))]
return if native { String::new() } else { "Rune's metal-backend feature is off".into() };
#[cfg(not(target_vendor = "apple"))]
{
let _ = native;
String::new()
}
}
/// Whether a GPU on `device` serves a compositor that wants `wanted`: false for a native
/// backend device when `wgpu_for(wanted)`.
pub fn serves(device: &wgpu::Device, wanted: wgpu::Features) -> bool {
#[cfg(all(target_vendor = "apple", feature = "metal-backend"))]
if crate::metal::raw_device(device).is_some() {
return !wgpu_for(wanted);
}
let _ = (device, wanted);
true
}
#[cfg_attr(not(all(target_vendor = "apple", feature = "metal-backend")), allow(dead_code))]
fn resolve(env: Option<&str>, chosen: Option<GpuBackend>) -> GpuBackend {
match env {
Some("metal") => GpuBackend::Metal,
Some("wgpu") => GpuBackend::Wgpu,
_ => chosen.unwrap_or(DEFAULT),
}
}
/// Whether the backend is the default one, which neither the environment nor the app chose.
#[cfg_attr(not(all(target_vendor = "apple", feature = "metal-backend")), allow(dead_code))]
fn defaulted(env: Option<&str>, chosen: Option<GpuBackend>) -> bool {
!matches!(env, Some("metal" | "wgpu")) && chosen.is_none()
}
#[cfg(test)]
mod tests {
use super::{DEFAULT, GpuBackend, defaulted, resolve};
#[test]
fn the_environment_overrides_the_app() {
assert_eq!(resolve(None, Some(GpuBackend::Metal)), GpuBackend::Metal);
assert_eq!(resolve(Some("wgpu"), Some(GpuBackend::Metal)), GpuBackend::Wgpu);
assert_eq!(resolve(Some("metal"), Some(GpuBackend::Wgpu)), GpuBackend::Metal);
assert_eq!(resolve(Some(""), Some(GpuBackend::Metal)), GpuBackend::Metal);
}
#[test]
fn an_app_that_chooses_wgpu_keeps_it_over_the_default() {
assert_eq!(resolve(None, Some(GpuBackend::Wgpu)), GpuBackend::Wgpu);
assert_eq!(resolve(None, None), DEFAULT);
assert_eq!(resolve(Some("bogus"), None), DEFAULT);
assert!(defaulted(None, None));
assert!(!defaulted(None, Some(GpuBackend::Metal)));
assert!(!defaulted(Some("metal"), None));
}
#[cfg(target_os = "macos")]
#[test]
fn macos_draws_with_the_native_backend_by_default_with_the_feature() {
let expected = if cfg!(feature = "metal-backend") { GpuBackend::Metal } else { GpuBackend::Wgpu };
assert_eq!(DEFAULT, expected);
}
}
+95
View File
@@ -0,0 +1,95 @@
//! What a page logs of its GPU device's uncaptured errors. A frame that fails validation fails
//! the same way every frame after it, and a browser stops logging a device's errors after a few
//! hundred, so the cause scrolls away under copies of it. Rune logs the first error with the
//! adapter it happened on, each different error once after it, and stops after a few.
/// How many different errors are logged before the rest are muted.
const DIFFERENT: usize = 4;
/// What to do with an uncaptured error.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Note {
/// The device's first error: log it with the adapter's description.
First,
/// An error not seen before: log it.
New,
/// The error that reached the limit: say that the rest won't be logged.
Mute,
/// Seen before, or past the limit: log nothing.
Quiet,
}
/// The errors a device has reported.
#[derive(Default)]
pub struct ErrorLog {
seen: Vec<String>,
}
impl ErrorLog {
pub fn note(&mut self, message: &str) -> Note {
if self.seen.len() > DIFFERENT || self.seen.iter().any(|m| m == message) { return Note::Quiet; }
self.seen.push(message.to_owned());
match self.seen.len() {
1 => Note::First,
n if n > DIFFERENT => Note::Mute,
_ => Note::New,
}
}
}
pub use rune_staging::health::{PollFailed, poll, removed};
/// `removed` for one device, cheap enough to ask every frame: `removed` costs about 200 ns a
/// call on D3D12 (`GetDeviceRemovedReason` is most of it), while this reads a fence of its own,
/// never signalled, which D3D12 sets to `u64::MAX` when it removes the device.
pub struct Removal {
#[cfg(target_os = "windows")]
fence: Option<RemovalFence>,
}
/// D3D12 fences are free-threaded.
#[cfg(target_os = "windows")]
struct RemovalFence(windows::Win32::Graphics::Direct3D12::ID3D12Fence);
#[cfg(target_os = "windows")]
// SAFETY: ID3D12Fence is free-threaded; it is only read.
#[allow(unsafe_code)]
unsafe impl Send for RemovalFence {}
#[cfg(target_os = "windows")]
// SAFETY: as for Send.
#[allow(unsafe_code)]
unsafe impl Sync for RemovalFence {}
impl Removal {
/// Watches `device`; on other backends, and if the fence can't be made, it never reads removed.
#[allow(unsafe_code)]
pub fn watch(device: &wgpu::Device) -> Removal {
#[cfg(target_os = "windows")]
{
// SAFETY: a fence made on the device's D3D12 interface, only ever read.
let fence = unsafe { device.as_hal::<wgpu::hal::api::Dx12>() }
.and_then(|d| unsafe { d.raw_device().CreateFence(0, windows::Win32::Graphics::Direct3D12::D3D12_FENCE_FLAG_NONE) }.ok())
.map(RemovalFence);
Removal { fence }
}
#[cfg(not(target_os = "windows"))]
{
let _ = device;
Removal {}
}
}
#[allow(unsafe_code)]
pub fn removed(&self) -> bool {
#[cfg(target_os = "windows")]
{
// SAFETY: a plain read of a live fence.
self.fence.as_ref().is_some_and(|f| unsafe { f.0.GetCompletedValue() } == u64::MAX)
}
#[cfg(not(target_os = "windows"))]
false
}
}
#[cfg(test)]
#[path = "health_tests.rs"]
mod tests;
+19
View File
@@ -0,0 +1,19 @@
use super::{ErrorLog, Note};
/// An invalid pipeline set every frame logs once, not once a frame.
#[test]
fn a_repeated_error_is_logged_once() {
let mut log = ErrorLog::default();
let error = "[Invalid RenderPipeline \"uber\"] is invalid due to a previous error.";
assert_eq!(log.note(error), Note::First);
for _ in 0..300 { assert_eq!(log.note(error), Note::Quiet); }
}
/// Different errors are each logged, up to a limit, then one line says the rest are muted.
#[test]
fn different_errors_are_logged_until_the_limit() {
let mut log = ErrorLog::default();
let notes: Vec<Note> = (0..8).map(|n| log.note(&format!("error {n}"))).collect();
assert_eq!(notes, [Note::First, Note::New, Note::New, Note::New, Note::Mute, Note::Quiet, Note::Quiet, Note::Quiet]);
assert_eq!(log.note("error 0"), Note::Quiet);
}
+51
View File
@@ -0,0 +1,51 @@
//! GPU adapter selection, backend dispatch, device error logging, analytic GPU springs and
//! Rune's native Apple Metal backend. On macOS and iOS, `metal-backend` (on by default) provides
//! the native Metal backend (`metal`) alongside wgpu's: a Mac app draws with the native one
//! unless `GpuBackend::Wgpu` or `RUNE_GPU_BACKEND=wgpu` selects wgpu's, and an iOS app draws with
//! wgpu's unless it chooses `GpuBackend::Metal`. Apps normally reach this crate through `rune`.
pub mod backend;
pub mod health;
#[cfg(all(target_vendor = "apple", feature = "metal-backend"))]
pub mod metal;
#[cfg(not(target_arch = "wasm32"))]
pub mod pick;
pub mod springs;
pub use backend::GpuBackend;
pub use backend::describe as describe_gpu;
#[cfg(target_os = "macos")]
use objc2::runtime::AnyObject;
/// Runs `f` on the CAMetalLayer `surface` presents into, under wgpu-hal's lock on wgpu's Metal
/// backend. `None` when the surface is on neither backend.
#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
pub fn with_layer<R>(surface: &wgpu::Surface<'_>, f: impl FnOnce(&AnyObject) -> R) -> Option<R> {
// SAFETY: the layer is only borrowed, under wgpu's lock.
if let Some(hal) = unsafe { surface.as_hal::<wgpu::hal::api::Metal>() } {
let layer = hal.render_layer().lock();
// SAFETY: a live CAMetalLayer, which the lock keeps; wgpu's objc2 may be another version
// than ours, the object is the same.
return Some(f(unsafe { &*objc2::rc::Retained::as_ptr(&*layer).cast::<AnyObject>() }));
}
#[cfg(feature = "metal-backend")]
if let Some(layer) = metal::layer(surface) {
return Some(f(layer));
}
None
}
/// Whether `queue` is Rune's native Metal backend's, where a frame's submit and present commit
/// one command buffer, too cheap to hand to a present thread.
#[cfg(target_os = "macos")]
pub fn native(queue: &wgpu::Queue) -> bool {
#[cfg(feature = "metal-backend")]
return metal::owns(queue);
#[cfg(not(feature = "metal-backend"))]
{
let _ = queue;
false
}
}
+99
View File
@@ -0,0 +1,99 @@
//! What `wgpu::custom` costs on top of the Metal calls it makes. The `metal_dispatch`
//! example runs it, in the perf profile (Rune's unit tests need debug assertions).
#![allow(unsafe_code)]
use objc2_metal::{MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLLoadAction, MTLRenderPassDescriptor, MTLStoreAction};
use super::resource::{MetalBuffer, MetalTexture};
use super::*;
// The libc crate declares it for macOS only; iOS's libSystem has it too.
unsafe extern "C" {
fn proc_pid_rusage(pid: libc::c_int, flavor: libc::c_int, buffer: *mut libc::c_void) -> libc::c_int;
}
fn instructions() -> u64 {
// SAFETY: proc_pid_rusage fills the rusage_info_v4 it is handed for RUSAGE_INFO_V4.
unsafe {
let mut info: libc::rusage_info_v4 = std::mem::zeroed();
assert_eq!(proc_pid_rusage(libc::getpid(), libc::RUSAGE_INFO_V4, (&raw mut info).cast()), 0);
info.ri_instructions
}
}
pub(super) fn gpu() -> (wgpu::Device, wgpu::Queue) {
let adapter = pollster::block_on(instance().request_adapter(&Default::default())).unwrap();
pollster::block_on(adapter.request_device(&Default::default())).unwrap()
}
pub(super) fn clear<'e>(encoder: &'e mut wgpu::CommandEncoder, view: &wgpu::TextureView) -> wgpu::RenderPass<'e> {
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("hud"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view, resolve_target: None, depth_slice: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.0, g: 0.0, b: 0.2, a: 0.4 }), store: wgpu::StoreOp::Store },
})],
..Default::default()
})
}
/// The HUD's frame (a cleared pass, `writes` uniform writes, a submit) through wgpu's API into
/// this backend, against the same Metal calls made directly, offscreen. Prints the medians of 4
/// alternating rounds in instructions per frame.
#[doc(hidden)]
pub fn dispatch_overhead() {
const FRAMES: u64 = 3000;
let (device, queue) = gpu();
let target = device.create_texture(&wgpu::TextureDescriptor {
label: None, size: wgpu::Extent3d { width: 720, height: 160, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Bgra8UnormSrgb, usage: wgpu::TextureUsages::RENDER_ATTACHMENT, view_formats: &[],
});
let uniforms = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 256, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let shared = device.as_custom::<MetalDevice>().unwrap().shared.clone();
let raw_target = target.as_custom::<MetalTexture>().unwrap().raw.raw.clone();
let raw_uniforms = uniforms.as_custom::<MetalBuffer>().unwrap().raw();
let data = [0.5f32; 64];
let bytes: &[u8] = bytemuck::cast_slice(&data);
let via_wgpu = |writes: usize| {
shared.pace();
let view = target.create_view(&Default::default());
let mut encoder = device.create_command_encoder(&Default::default());
drop(clear(&mut encoder, &view));
for _ in 0..writes { queue.write_buffer(&uniforms, 0, bytes); }
queue.submit([encoder.finish()]);
};
let direct = |writes: usize| {
shared.pace();
let cb = shared.queue.commandBufferWithUnretainedReferences().unwrap();
let pass = MTLRenderPassDescriptor::new();
// SAFETY: index 0 always exists.
let color = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) };
color.setTexture(Some(&raw_target));
color.setLoadAction(MTLLoadAction::Clear);
color.setClearColor(MTLClearColor { red: 0.0, green: 0.0, blue: 0.2, alpha: 0.4 });
color.setStoreAction(MTLStoreAction::Store);
cb.renderCommandEncoderWithDescriptor(&pass).unwrap().endEncoding();
for _ in 0..writes { raw_uniforms.write(0, bytes); }
shared.commit(cb);
};
let measure = |f: &dyn Fn(usize), writes| {
for _ in 0..200 { f(writes); }
let start = instructions();
for _ in 0..FRAMES { f(writes); }
(instructions() - start) as f64 / FRAMES as f64 / 1e3
};
let mut runs: [Vec<f64>; 4] = Default::default();
for _ in 0..4 {
for writes in [0, 1] {
runs[writes * 2].push(measure(&via_wgpu, writes));
runs[writes * 2 + 1].push(measure(&direct, writes));
}
}
let median = |mut v: Vec<f64>| { v.sort_by(f64::total_cmp); (v[1] + v[2]) / 2.0 };
for writes in [0, 1] {
let (w, d) = (median(runs[writes * 2].clone()), median(runs[writes * 2 + 1].clone()));
println!("writes={writes} kinstr/frame: wgpu::custom {w:.1}, direct {d:.1}, custom adds {:.1} (rounds {:.1?} vs {:.1?})",
w - d, runs[writes * 2], runs[writes * 2 + 1]);
}
}
+114
View File
@@ -0,0 +1,114 @@
//! Rune's, rune-fx's and rune-light's own pipelines, precompiled into `builtin_native.metallib`,
//! so their first use skips naga and Metal's front end (MSL to AIR), which is most of what a
//! pipeline costs on a cold shader cache. On iOS that includes the uber shader, which macOS
//! loads from `uber_native.metallib` instead.
//!
//! A pipeline's key hashes everything that decides the MSL naga writes for it: the WGSL (each
//! `\r\n` read as `\n`, so a CRLF checkout of the built-in sources finds them too), the
//! stage and entry point, override constants, runtime checks, whether it draws points, and the
//! slots its pipeline layout hands out. A key in the table names a function in the library,
//! so a precompiled function always binds the slots the runtime path would have given it. Any
//! other pipeline, an app's shader or a changed one, compiles at runtime as before.
//!
//! `scripts/precompile-metal-shaders.sh` regenerates the library and `builtin_table.rs`: it runs
//! rune-light's `builtin_shaders` test, which builds every built-in pipeline with
//! `RUNE_METAL_CAPTURE` set, so this module writes each one's MSL, in MSL 3.0, into its own
//! namespace, and compiles it for macOS, iOS and the iOS simulator. `RUNE_DISABLE_METALLIB=1`
//! turns the library off.
use std::sync::OnceLock;
use std::sync::atomic::{AtomicUsize, Ordering};
use wgpu::naga::{self, back::msl};
use super::Shared;
use super::shader::{Compiled, Ir, Point, function, library, translate};
include!("builtin_table.rs");
#[cfg(target_os = "macos")]
const LIBRARY: &[u8] = include_bytes!("../shaders/builtin_native.metallib");
#[cfg(all(target_os = "ios", not(target_abi = "sim")))]
const LIBRARY: &[u8] = include_bytes!("../shaders/builtin_native_ios.metallib");
#[cfg(all(target_os = "ios", target_abi = "sim"))]
const LIBRARY: &[u8] = include_bytes!("../shaders/builtin_native_ios_sim.metallib");
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
const LIBRARY: &[u8] = &[];
/// Pipelines that found no precompiled function, for the test that keeps the table current.
static MISSES: AtomicUsize = AtomicUsize::new(0);
fn capture_dir() -> Option<&'static std::path::Path> {
static DIR: OnceLock<Option<std::path::PathBuf>> = OnceLock::new();
DIR.get_or_init(|| std::env::var_os("RUNE_METAL_CAPTURE").map(Into::into)).as_deref()
}
fn enabled() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| {
let off = rune_core::env::flag("RUNE_DISABLE_METALLIB");
!LIBRARY.is_empty() && !off && capture_dir().is_none()
})
}
fn short(hash: &blake3::Hash) -> String {
hash.to_hex()[..32].to_string()
}
/// Whether `source` is a built-in shader's WGSL.
pub(super) fn known(source: &blake3::Hash) -> bool {
enabled() && SOURCES.binary_search(&short(source).as_str()).is_ok()
}
pub(super) fn key(ir: &Ir, point: &Point<'_>, resources: &msl::EntryPointResources, points: bool) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(ir.hash.as_bytes());
let Point { kind, entry, constants } = point;
hasher.update(format!("{kind:?}|{entry:?}|{constants:?}|{:?}|{points}|{resources:?}", ir.checks).as_bytes());
format!("k{}", short(&hasher.finalize()))
}
/// The precompiled function for the pipeline `key` names, if the table has it.
pub(super) fn find(shared: &Shared, key: &str) -> Option<Compiled> {
if !enabled() { return None }
let Ok(at) = FUNCTIONS.binary_search_by(|f| f.0.cmp(key)) else {
MISSES.fetch_add(1, Ordering::Relaxed);
return None;
};
let (_, name, sized, workgroup, workgroup_memory) = FUNCTIONS[at];
let library = shared.builtin.get_or_init(|| library(shared, LIBRARY).ok()).as_ref()?;
let function = function(library, name).ok()?;
let sized = sized.iter().map(|&(group, binding)| naga::ResourceBinding { group, binding }).collect();
Some(Compiled { function, sized, workgroup, workgroup_memory: workgroup_memory.to_vec() })
}
/// How many pipelines compiled at runtime because the table lacked them.
pub(crate) fn misses() -> usize {
MISSES.load(Ordering::Relaxed)
}
/// Under `RUNE_METAL_CAPTURE`, writes the pipeline's MSL 3.0 into the directory it names, in a
/// namespace named for its hash, with its table row and its source's hash beside it.
pub(super) fn capture(ir: &Ir, point: &Point<'_>, resources: &msl::EntryPointResources, points: bool, key: &str) {
let Some(dir) = capture_dir() else { return };
let msl = translate(ir, point, resources, points, (3, 0)).unwrap_or_else(|e| panic!("{e}"));
let split = msl.source.rfind("#include").and_then(|at| msl.source[at..].find('\n').map(|n| at + n + 1)).unwrap_or(0);
let (head, body) = msl.source.split_at(split);
let sized: Vec<String> = msl.sized.iter().map(|b| format!("({}, {})", b.group, b.binding)).collect();
let workgroup_memory: Vec<String> = msl.workgroup_memory.iter().map(|n| n.to_string()).collect();
let [x, y, z] = msl.workgroup;
// Pipelines whose MSL is the same share one function.
let space = format!("m{}", short(&blake3::hash(body.as_bytes())));
let write = |name: String, text: String| std::fs::write(dir.join(name), text).expect("RUNE_METAL_CAPTURE: write");
write(format!("{space}.metal"), format!("{head}namespace {space} {{\n{body}\n}}\n"));
write(
format!("{key}.row"),
format!(
" (\"{key}\", \"{space}::{}\", &[{}], [{x}, {y}, {z}], &[{}]),\n",
msl.function,
sized.join(", "),
workgroup_memory.join(", "),
),
);
write(format!("{}.source", short(&ir.hash)), String::new());
}
@@ -0,0 +1,95 @@
// Generated by scripts/precompile-metal-shaders.sh: the built-in shaders' WGSL hashes, and each
// precompiled pipeline's key, function, sized bindings, workgroup size and workgroup memory sizes,
// sorted by key.
const SOURCES: &[&str] = &[
"0ded5c98a550685ae59f7d5f05e1a83b",
"0f4e6df6af481ff9ef96b014721003b1",
"293dba34982a51cfda2ccbbe111cbf4f",
"3056bcace89aac552633ef37549cb88b",
"321953684c57f92a08e8d125167db30e",
"3328cab6a829979a5f039cae845150dd",
"37c384347fc8b128be1fe4d74240f109",
"3d1630fc09197c719a90cf96ffcd4cc1",
"4125ab6467934754747ac20aff379256",
"4d14f19dbcda03e8d68a69f522296ac4",
"51ff39a0e18ecf5d548f9268354d6635",
"56ba4a59e83f287a8ad0174debc90fa4",
"56f011a145ea9860c673d4db2eedf907",
"5a5c19095cfb20f0b1281ffe424e89fe",
"6a090671983612e9a5f12f4542bf334c",
"71d5e66fff21415bedc5d5bbc68554e2",
"80eff74c7f72da28870a03e327a1134e",
"98bd3aebd738fb3793444525c3616127",
"aa3c4f0be11b22d24ba3cd91ff70168e",
"b1046c41bff846232066b62e9f0fb613",
"bbcc3a509263bef52f505442644d5649",
"c19b876de35a56e424d241db841f14bd",
"ca47cffb5f1cce62283aa362caaedd3c",
"cba650dfa098efbdff65c869234d87c1",
"e36972ab3b8998c668dcca279a5ef078",
"e3d040c9ff7fae9f6198a4174b95074d",
"ec954166535d10cea30353e0fda9b94b",
"f9207a506778ba3ee7d58ec1c42df906",
];
const FUNCTIONS: &[(&str, &str, &[(u32, u32)], [u32; 3], &[u32])] = &[
("k024088e1b318322993f9cf64d1ec1eb4", "m2f79583aa42edf341732be9460dc524b::vs", &[(0, 1)], [0, 0, 0], &[]),
("k0a6f36525e72a0c87e268155da07092c", "mb652406f862270a61dfb9222b95df3bc::vs_springs", &[(1, 0), (1, 1)], [0, 0, 0], &[]),
("k0cb9caa30f07482a4bf4734b9feb96ec", "m83792c1400075cf55cdd4553e3fee64e::fs", &[(0, 1), (0, 2)], [0, 0, 0], &[]),
("k0d6e8e4ba10bacd94048785e62009d38", "m2f79583aa42edf341732be9460dc524b::vs", &[(0, 1)], [0, 0, 0], &[]),
("k117f5ebc12ff09531421705986dfebec", "m2b8b7b33dbd5cdfedc156751043ab905::fs", &[], [0, 0, 0], &[]),
("k12d7677c548173cde8a2ce84f9f2280e", "md982bc745116f52d24df44ece504814e::curl", &[], [8, 8, 1], &[]),
("k1617b6330c127657ae1b1b74192f582d", "ma734f91c7408c66d765f7e245f1749c6::fs", &[(0, 1)], [0, 0, 0], &[]),
("k19bf1e63beb3f4f1c3deb8ab464f62dc", "m1c49d4de7a80392049d92d8d1c9aab4a::divergence", &[], [8, 8, 1], &[]),
("k19eecf554a2242758fd18e54fe714e89", "m5788ca8c3daa91555200451dce562c8b::fs_down", &[], [0, 0, 0], &[]),
("k1f78c460f7fa477c75e24c2b46a3b912", "mb2dcb0ef7debf1207caa561d97708171::vs", &[(0, 1)], [0, 0, 0], &[]),
("k21f9dac17a14195016ff972a64b10131", "m2f79583aa42edf341732be9460dc524b::vs", &[(0, 1)], [0, 0, 0], &[]),
("k2213421d9399996f3ce122df1c1e23ca", "mf785e584b2e95e5cd950860ac0486665::fs", &[(0, 1)], [0, 0, 0], &[]),
("k2331a4afeea2bd23754af83f48fb6cd7", "m8b542e16754591c146308a98ff2fb81e::vs", &[], [0, 0, 0], &[]),
("k267bc2cdc3878ff73acd3fc9610b582f", "m5a09619b6f8a741466cddb5c3df36d46::fs", &[(0, 1), (0, 2)], [0, 0, 0], &[]),
("k2a32973f01b8a4c2ebe3f50879e297cd", "m1b0f5eafb54262a38dce18b94e8d1ec6::fs", &[(0, 1), (0, 2)], [0, 0, 0], &[]),
("k2b07e7f2202a7fa1d36b2da0c147ffb7", "m1edc70c07691540b7608288baa0a0e38::fs", &[(0, 1)], [0, 0, 0], &[]),
("k2b1353add14a6db741ff279cac88af27", "mb8ef6e081b0b872df0cd8bffb76e42e3::vs", &[], [0, 0, 0], &[]),
("k3319575bfbfbb5d87cfd4ff325bc3cec", "m2ff131790b5e74f55677765b9b907082::vs", &[], [0, 0, 0], &[]),
("k3a8678f108e06f0db49ca7dbab9a9cf5", "mb2dcb0ef7debf1207caa561d97708171::vs", &[(0, 1)], [0, 0, 0], &[]),
("k4020af573bb5fbe40febac71951710e1", "m0d5717ff65d1b508bf422020ddd4aa63::vs", &[(0, 1)], [0, 0, 0], &[]),
("k4374f87672f3459f5a4fbc4870d0114c", "meeb181944f9ff8215a7ad1c64d921fec::jacobi", &[], [8, 8, 1], &[]),
("k4427f7df2f524c5ffe48dcb7e92039da", "mefe83d92c01227a13965f68776539ca7::vs", &[], [0, 0, 0], &[]),
("k542fcc644d87abb728cf1f9b0fa9769b", "m1b9118fbcc053cc5353f59b8fd002af4::fs", &[], [0, 0, 0], &[]),
("k58f088fc1666f65ad695c2fc2fcd8e31", "m0c12b17c0ef7856a6e8bd21fe63f233e::fs", &[], [0, 0, 0], &[]),
("k5f681b13611bbb67f08e1924725efffe", "meed8387f9cc160fdce90a041f5aeb501::fs_up", &[], [0, 0, 0], &[]),
("k60123095194b2cc0b2ea3f5506409274", "m8de9ac951d973fc92f4e5640584210d0::main_", &[(0, 1)], [16, 16, 1], &[1024, 4]),
("k63add30ce8b4da493ecf39359ed35363", "m1c737e7a8c5abcc904a2da9a2825ac38::fs", &[], [0, 0, 0], &[]),
("k6ffbae7dc28139b873d103c637ecfcf3", "m8bdd1084b7d60a525410d546b5a87b77::fs", &[(0, 1), (0, 2)], [0, 0, 0], &[]),
("k734e6d1d9a4042487f62ce0951de708b", "md0bd1ee451e14d50292a0a2b98c1a9d9::vs", &[], [0, 0, 0], &[]),
("k7794c2c9c13c17dcabd8855b0785d01f", "md8294b2df2cc43d750eaef890def63c9::forces", &[], [8, 8, 1], &[]),
("k8b29b5678243a22c786e89a7b7f80791", "m547041d70fa017b3e6774c28c68e46a5::fs", &[], [0, 0, 0], &[]),
("k8ebad456db86552e178e85aaeba032f4", "m87e59e030add6e1a45509928843d18b8::scene", &[(1, 0), (1, 1)], [8, 8, 1], &[]),
("k8fa91dcc5cdb2fbd888dc0352007483d", "m2ff131790b5e74f55677765b9b907082::vs", &[], [0, 0, 0], &[]),
("k91b0314ee0e000bf238da12912544711", "m405386023a91e44eab45a6b1bdb619b6::fs", &[(0, 1)], [0, 0, 0], &[]),
("k94ff83acea3ca2a5589836a503b74c54", "m0cbf8de4ed04683f230f3ef28c65e81c::fs", &[(0, 1), (0, 2)], [0, 0, 0], &[]),
("k95eebc5aec6dc46161642137eefa11d6", "ma0d7eb8079fa312db31aeafd05992302::fs", &[], [0, 0, 0], &[]),
("k98fb587de982d03e56b161d83aa0786f", "mb2dcb0ef7debf1207caa561d97708171::vs", &[(0, 1)], [0, 0, 0], &[]),
("kac57f0f1349a17806ba0011b90de83e9", "m2e3ed3c785534730b432b753411bc487::fs_up", &[], [0, 0, 0], &[]),
("kac861722733835e80380e91b676d815b", "m8857338171beaaa30391be8910f719e5::cascade", &[], [8, 8, 1], &[]),
("kaeb02cf8d50af70182b5f3580b98e328", "mbfe265a0c3f7b280b7dcfdd20ceecec7::vs", &[], [0, 0, 0], &[]),
("kaf1affb9093b811cf8becf80b0063268", "mc56576886af26e2c1ba5d3f92e3e9aa2::fs", &[], [0, 0, 0], &[]),
("kb0b73879a1288bfc459db5e3479975e8", "m6f063b893f1b1402fdfc29708cc8d1dd::fs", &[], [0, 0, 0], &[]),
("kb4e6d1f32a7ca6085f0ddfcce790b120", "m9a59e2c5386334dd4e093c88359e850e::fs_down", &[], [0, 0, 0], &[]),
("kb50ab43585c935cb1f7a0d86901c8d9a", "m934bcb93e3c9c91318ae7fdd10032794::noop", &[], [1, 1, 1], &[]),
("kb529566e7da522f1afd79e37cfc8939e", "m375ba27d8c7afa2832248bfb4d24a1b4::main_", &[(0, 1)], [8, 8, 1], &[]),
("kb6bdc4e8b42c5197ea454df7be34641b", "m5a5852af6a4184d0e955ece495353816::fs", &[], [0, 0, 0], &[]),
("kba8710abdf0f1c92d88d7e05f46364c0", "m80d2352f0d6c8554b82bdab0fe49d31c::fs_down", &[], [0, 0, 0], &[]),
("kbbed3c31edf442b3449559b6d89f6727", "m2ff131790b5e74f55677765b9b907082::vs", &[], [0, 0, 0], &[]),
("kbfb40b68240f2f41cde8c91772aff3d6", "mc0dabdae962478d651357223381b83b6::vs", &[], [0, 0, 0], &[]),
("kc1b0402b5f0a04eb5231d108b39e360b", "m999a4e87b6739be03c91c5064e503934::fs", &[(0, 1), (0, 2)], [0, 0, 0], &[]),
("kc1ba97a6e793bddc3dcb04ec69c63645", "m9168a58ab1664917dc3b35a8daf5d5e3::vs", &[(0, 1)], [0, 0, 0], &[]),
("kc2c45907017abc04721a4fbea3884ab0", "mfa17670fb587a52c4b8c7d9c0fbad4c2::vs", &[], [0, 0, 0], &[]),
("kc2ecdae196c5cafb366364ee88f76947", "m2f79583aa42edf341732be9460dc524b::vs", &[(0, 1)], [0, 0, 0], &[]),
("kd54724550a6137fae0b6b5d80f62f6c8", "ma0d7eb8079fa312db31aeafd05992302::fs", &[], [0, 0, 0], &[]),
("kde9ba5297c37b1028b12e0a605119be2", "m9394dba0277daf66bb6424ea105c6ca4::fs", &[(0, 1), (0, 2)], [0, 0, 0], &[]),
("kdf716358669d7be83cdf88d6473688ec", "md3e19db8e7e71278af7b7aae4b7b55a5::fs", &[], [0, 0, 0], &[]),
("ke7b34db7d22314facf954085312166f2", "m92a5c36413d0c786d8b75259b8c08f9b::advect", &[], [8, 8, 1], &[]),
("kebb66a94832b4e2c51faf6abfa6f85f8", "m0da346df72cbc6d22f756ab718fccb3a::project", &[], [8, 8, 1], &[]),
("kf71d4b2936790af37d8334adcb49e8a3", "mdb958e9c52725e5b765b326dae5f2502::vs", &[], [0, 0, 0], &[]),
("kfc97b30bd4224a866e97861a4c9b1484", "m98cf835fafeb8efbf015ed2a0c458a67::fluence", &[], [8, 8, 1], &[]),
];
+245
View File
@@ -0,0 +1,245 @@
//! Compute pipelines and passes. As in render passes, bind groups apply at the next dispatch
//! against the pipeline bound then, and the sizes buffer and immediates travel as inline bytes.
//! A pass's timestamp writes sample at its start and end.
#![allow(unsafe_code)]
use std::ptr::NonNull;
use std::sync::Arc;
use std::sync::atomic::Ordering;
#[cfg(debug_assertions)]
use objc2_foundation::NSString;
use objc2_metal::{MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, MTLComputePassDescriptor, MTLComputePipelineDescriptor, MTLComputePipelineState, MTLDevice, MTLPipelineOption, MTLSize};
use objc2::rc::autoreleasepool;
use parking_lot::Mutex;
use wgpu::custom::*;
use wgpu::naga;
use super::derive::{self, Use};
use super::encode::Rec;
use super::layout::{COMPUTE, GroupRaw, LayoutRaw, PipelineLayout};
use super::shader::{Stage, compile};
use super::store::SWAPS;
use super::submit::Keep;
use super::{Obj, Shared, query, send_sync};
const GROUPS: usize = 8;
#[derive(Debug)]
pub(crate) struct ComputePipeline {
pub(super) raw: Arc<ComputeRaw>,
}
#[derive(Debug)]
pub(crate) struct ComputeRaw {
state: Obj<dyn MTLComputePipelineState>,
layout: Arc<LayoutRaw>,
/// The storage bindings whose sizes the shader reads, in order.
sized: Vec<naga::ResourceBinding>,
/// Byte lengths of each `var<workgroup>` parameter, rounded up to Metal's 16-byte alignment.
workgroup_memory: Box<[u32]>,
workgroup: MTLSize,
}
send_sync!(ComputeRaw);
pub(super) fn create(shared: &Shared, desc: &wgpu::ComputePipelineDescriptor<'_>) -> ComputePipeline {
let label = desc.label.unwrap_or("compute pipeline");
let layout = match desc.layout {
Some(layout) => layout.as_custom::<PipelineLayout>().expect("a Metal pipeline layout").raw.clone(),
None => derive::layout(label, &[Use { module: desc.module, entry: desc.entry_point, kind: naga::ShaderStage::Compute }]).raw,
};
let stage = Stage { module: desc.module, entry: desc.entry_point, constants: desc.compilation_options.constants,
kind: naga::ShaderStage::Compute };
let cs = compile(shared, &stage, &layout.stages[COMPUTE], false).unwrap_or_else(|e| panic!("{label}: {e}"));
let d = MTLComputePipelineDescriptor::new();
d.setComputeFunction(Some(&cs.function));
#[cfg(debug_assertions)]
if let Some(label) = desc.label { d.setLabel(Some(&NSString::from_str(label))); }
let state = shared.device
.newComputePipelineStateWithDescriptor_options_reflection_error(&d, MTLPipelineOption::empty(), None)
.unwrap_or_else(|e| panic!("{label}: {}", e.localizedDescription()));
let [x, y, z] = cs.workgroup.map(|n| n as usize);
let workgroup_memory = cs.workgroup_memory.into_iter().map(|size| size.next_multiple_of(16)).collect();
ComputePipeline {
raw: Arc::new(ComputeRaw {
state,
layout,
sized: cs.sized,
workgroup_memory,
workgroup: MTLSize { width: x, height: y, depth: z },
}),
}
}
impl ComputePipelineInterface for ComputePipeline {
fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout {
self.raw.layout.group(index)
}
}
#[derive(Debug)]
pub(crate) struct MetalComputePass {
rec: Arc<Mutex<Rec>>,
raw: Obj<dyn MTLComputeCommandEncoder>,
keep: Keep,
pipeline: Option<Arc<ComputeRaw>>,
groups: [Option<(Arc<GroupRaw>, Vec<u32>)>; GROUPS],
/// Groups to apply at the next dispatch, a bit each.
dirty: u32,
sizes_dirty: bool,
immediates: Vec<u8>,
immediates_dirty: bool,
/// `SWAPS` when buffers were last bound: a swap since may have moved a bound buffer.
swaps: u64,
}
send_sync!(MetalComputePass);
impl MetalComputePass {
pub(super) fn begin(rec: Arc<Mutex<Rec>>, desc: &wgpu::ComputePassDescriptor<'_>) -> Self {
let d = MTLComputePassDescriptor::new();
let mut keep = rec.lock().shared().keep_list();
if let Some(ts) = &desc.timestamp_writes {
let set = ts.query_set.as_custom::<query::QuerySet>().expect("a Metal query set").raw.clone();
// SAFETY: attachment 0 exists on every descriptor; the indices are within the query set, as wgpu validated.
unsafe {
let attachment = d.sampleBufferAttachments().objectAtIndexedSubscript(0);
attachment.setSampleBuffer(Some(&set.0));
attachment.setStartOfEncoderSampleIndex(query::index(ts.beginning_of_pass_write_index));
attachment.setEndOfEncoderSampleIndex(query::index(ts.end_of_pass_write_index));
}
keep.push(set);
}
let raw = {
let mut rec = rec.lock();
let cb = rec.pass_buffer();
autoreleasepool(|_| cb.computeCommandEncoderWithDescriptor(&d)).expect("a Metal compute encoder")
};
#[cfg(debug_assertions)]
{
let label = desc.label.unwrap_or("rune metal compute pass");
raw.setLabel(Some(&NSString::from_str(label)));
}
MetalComputePass {
rec, raw, keep, pipeline: None, groups: Default::default(), dirty: 0, sizes_dirty: false,
immediates: Vec::new(), immediates_dirty: false, swaps: SWAPS.load(Ordering::Relaxed),
}
}
fn bound(&self) -> u32 { self.groups.iter().enumerate().filter(|(_, g)| g.is_some()).fold(0, |m, (i, _)| m | 1 << i) }
/// Applies what changed since the last dispatch against the bound pipeline.
fn flush(&mut self) {
let swaps = SWAPS.load(Ordering::Relaxed);
if swaps != self.swaps {
self.swaps = swaps;
self.dirty = self.bound();
}
let Some(pipeline) = &self.pipeline else { return };
let layout = &pipeline.layout;
while self.dirty != 0 {
let index = self.dirty.trailing_zeros() as usize;
self.dirty &= self.dirty - 1;
let (Some((group, offsets)), Some(bases)) = (&self.groups[index], layout.bases.get(index)) else { continue };
let base = bases[COMPUTE];
let binds = &group.stages[COMPUTE];
// SAFETY: slots come from the pipeline layout the shader was compiled against, and the
// resources stay alive in the pass's keep list.
unsafe {
for b in &binds.buffers {
let offset = (b.offset + b.dynamic.map_or(0, |i| u64::from(offsets[i]))) as usize;
let buffer = b.store.current();
self.raw.setBuffer_offset_atIndex(Some(&buffer.raw), offset, usize::from(base.buffers + b.slot));
self.keep.push(buffer);
}
for (slot, texture) in &binds.textures { self.raw.setTexture_atIndex(Some(texture), usize::from(base.textures + slot)); }
for (slot, sampler) in &binds.samplers { self.raw.setSamplerState_atIndex(Some(sampler), usize::from(base.samplers + slot)); }
}
self.sizes_dirty = true;
}
if std::mem::take(&mut self.sizes_dirty) && let Some(slot) = layout.stages[COMPUTE].sizes_buffer && !pipeline.sized.is_empty() {
let sizes: Vec<u32> = pipeline.sized.iter().map(|b| {
let group = self.groups.get(b.group as usize).and_then(Option::as_ref);
group.and_then(|(g, _)| g.sizes.iter().find(|(at, _)| *at == b.binding)).map_or(0, |&(_, size)| size)
}).collect();
bytes(&self.raw, &sizes, slot);
}
if std::mem::take(&mut self.immediates_dirty) && !self.immediates.is_empty()
&& let Some(slot) = layout.stages[COMPUTE].immediates_buffer {
bytes(&self.raw, &self.immediates, slot);
}
}
}
/// Sets `data` inline at buffer `slot`.
fn bytes<T: Copy>(raw: &Obj<dyn MTLComputeCommandEncoder>, data: &[T], slot: u8) {
// SAFETY: Metal copies the bytes before returning.
unsafe { raw.setBytes_length_atIndex(NonNull::from(data).cast(), std::mem::size_of_val(data), slot as usize) }
}
impl Drop for MetalComputePass {
fn drop(&mut self) {
self.raw.endEncoding();
let mut rec = self.rec.lock();
rec.keep.append(&mut self.keep);
rec.shared().recycle(std::mem::take(&mut self.keep));
}
}
impl ComputePassInterface for MetalComputePass {
fn set_pipeline(&mut self, pipeline: &DispatchComputePipeline) {
let next = &pipeline.as_custom::<ComputePipeline>().expect("a Metal compute pipeline").raw;
if self.pipeline.as_ref().is_some_and(|p| Arc::ptr_eq(p, next)) { return }
if self.pipeline.as_ref().is_none_or(|p| !Arc::ptr_eq(&p.layout, &next.layout)) {
self.dirty = self.bound();
// Zeroed for a new layout, as wgpu-core does.
self.immediates.clear();
self.immediates.resize(next.layout.immediates as usize, 0);
self.immediates_dirty = true;
}
self.raw.setComputePipelineState(&next.state);
for (index, &size) in next.workgroup_memory.iter().enumerate() {
// SAFETY: `index` and 16-byte-aligned `size` match the `threadgroup` arguments Naga
// emitted for this compute function.
unsafe { self.raw.setThreadgroupMemoryLength_atIndex(size as usize, index) };
}
self.sizes_dirty = true;
self.keep.push(next.clone());
self.pipeline = Some(next.clone());
}
fn set_bind_group(&mut self, index: u32, group: Option<&DispatchBindGroup>, offsets: &[wgpu::DynamicOffset]) {
let index = index as usize;
if index >= GROUPS { super::unsupported!("bind group {index}") }
let Some(group) = group else { self.groups[index] = None; return };
let group = &group.as_custom::<super::layout::BindGroup>().expect("a Metal bind group").raw;
if let Some((bound, bound_offsets)) = &self.groups[index]
&& Arc::ptr_eq(bound, group) && bound_offsets[..] == *offsets { return }
self.keep.push(group.clone());
self.groups[index] = Some((group.clone(), offsets.to_vec()));
self.dirty |= 1 << index;
}
fn set_immediates(&mut self, offset: u32, data: &[u8]) {
let at = offset as usize;
if self.immediates.len() < at + data.len() { self.immediates.resize(at + data.len(), 0); }
self.immediates[at..at + data.len()].copy_from_slice(data);
self.immediates_dirty = true;
}
fn insert_debug_marker(&mut self, _: &str) {}
fn push_debug_group(&mut self, _: &str) {}
fn pop_debug_group(&mut self) {}
fn write_timestamp(&mut self, _: &DispatchQuerySet, _: u32) { super::unsupported!("timestamps inside passes") }
fn begin_pipeline_statistics_query(&mut self, _: &DispatchQuerySet, _: u32) { super::unsupported!("query sets") }
fn end_pipeline_statistics_query(&mut self) { super::unsupported!("query sets") }
fn dispatch_workgroups(&mut self, x: u32, y: u32, z: u32) {
if x == 0 || y == 0 || z == 0 { return }
self.flush();
let Some(pipeline) = &self.pipeline else { return };
let groups = MTLSize { width: x as usize, height: y as usize, depth: z as usize };
self.raw.dispatchThreadgroups_threadsPerThreadgroup(groups, pipeline.workgroup);
}
fn dispatch_workgroups_indirect(&mut self, _: &DispatchBuffer, _: wgpu::BufferAddress) {
super::unsupported!("indirect dispatches")
}
fn transition_resources<'a>(&mut self, _: &mut dyn Iterator<Item = wgpu::wgt::BufferTransition<&'a DispatchBuffer>>,
_: &mut dyn Iterator<Item = wgpu::wgt::TextureTransition<&'a DispatchTextureView>>) {}
}
@@ -0,0 +1,499 @@
use super::bench::{clear, gpu};
use super::instance;
fn wgpu_metal() -> (wgpu::Device, wgpu::Queue) {
let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
descriptor.backends = wgpu::Backends::METAL;
let instance = wgpu::Instance::new(descriptor);
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).unwrap();
// The iOS simulator passes fewer inter-stage variables than wgpu's defaults ask for.
let desc = wgpu::DeviceDescriptor { required_limits: adapter.limits(), ..Default::default() };
pollster::block_on(adapter.request_device(&desc)).unwrap()
}
fn timed() -> (wgpu::Device, wgpu::Queue) {
let adapter = pollster::block_on(instance().request_adapter(&Default::default())).unwrap();
assert!(adapter.features().contains(wgpu::Features::TIMESTAMP_QUERY), "Apple GPUs sample at stage boundaries");
let desc = wgpu::DeviceDescriptor { required_features: wgpu::Features::TIMESTAMP_QUERY, ..Default::default() };
pollster::block_on(adapter.request_device(&desc)).unwrap()
}
fn texture(device: &wgpu::Device, format: wgpu::TextureFormat, size: wgpu::Extent3d, mips: u32, usage: wgpu::TextureUsages) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: None, size, mip_level_count: mips, sample_count: 1, dimension: wgpu::TextureDimension::D2, format, usage, view_formats: &[],
})
}
fn size(width: u32, height: u32) -> wgpu::Extent3d { wgpu::Extent3d { width, height, depth_or_array_layers: 1 } }
fn buffer(device: &wgpu::Device, size: u64, usage: wgpu::BufferUsages) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor { label: None, size, usage, mapped_at_creation: false })
}
fn read(device: &wgpu::Device, buffer: &wgpu::Buffer) -> Vec<u8> {
let slice = buffer.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let out = slice.get_mapped_range().unwrap().to_vec();
buffer.unmap();
out
}
const STEP: &str = r#"
struct U { scale: vec4<f32> };
@group(0) @binding(0) var<uniform> u: U;
@group(0) @binding(1) var<storage, read> weights: array<f32>;
@group(0) @binding(2) var src: texture_2d<f32>;
@group(0) @binding(3) var dst: texture_storage_2d<rgba16float, write>;
@group(0) @binding(4) var<storage, read_write> counts: array<atomic<u32>>;
@compute @workgroup_size(8, 4)
fn step(@builtin(global_invocation_id) id: vec3<u32>) {
let n = arrayLength(&weights);
let c = textureLoad(src, vec2<i32>(id.xy), 0) * u.scale * weights[(id.x + id.y) % n];
textureStore(dst, vec2<i32>(id.xy), c + vec4<f32>(f32(id.x) / 64.0, f32(id.y) / 32.0, 0.0, 0.0));
atomicAdd(&counts[id.x % 4u], 1u);
}
"#;
const W: u32 = 64;
const H: u32 = 32;
/// Two dispatches in one pass, the second reading what the first stored, through a dynamic
/// uniform offset, a runtime-sized storage array, a storage texture and storage atomics.
fn steps(device: &wgpu::Device, queue: &wgpu::Queue) -> (Vec<u8>, Vec<u8>) {
use wgpu::{BufferUsages as B, ShaderStages as S, TextureUsages as T};
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("step"), source: wgpu::ShaderSource::Wgsl(STEP.into()) });
let entry = |binding, ty| wgpu::BindGroupLayoutEntry { binding, visibility: S::COMPUTE, ty, count: None };
let storage = |read_only| wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None };
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &[
entry(0, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: None }),
entry(1, storage(true)),
entry(2, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }),
entry(3, wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format: wgpu::TextureFormat::Rgba16Float,
view_dimension: wgpu::TextureViewDimension::D2 }),
entry(4, storage(false)),
] });
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&bgl)], immediate_size: 0 });
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("step"), layout: Some(&layout), module: &module, entry_point: Some("step"), compilation_options: Default::default(), cache: None,
});
let uniforms = buffer(device, 512, B::UNIFORM | B::COPY_DST);
queue.write_buffer(&uniforms, 0, bytemuck::cast_slice(&[0.5f32, 1.0, 2.0, 1.0]));
queue.write_buffer(&uniforms, 256, bytemuck::cast_slice(&[1.5f32, 0.25, 1.0, 0.5]));
let weights = buffer(device, 64, B::STORAGE | B::COPY_DST);
queue.write_buffer(&weights, 0, bytemuck::cast_slice(&[1.0f32, 0.5, 0.25]));
let counts = buffer(device, 16, B::STORAGE | B::COPY_SRC);
let image = texture(device, wgpu::TextureFormat::Rgba16Float, size(W, H), 1, T::TEXTURE_BINDING | T::COPY_DST);
let texels: Vec<u16> = (0..W * H * 4).map(|i| half_bits((i % 97) as f32 / 97.0)).collect();
queue.write_texture(image.as_image_copy(), bytemuck::cast_slice(&texels),
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(W * 8), rows_per_image: None }, image.size());
let mid = texture(device, wgpu::TextureFormat::Rgba16Float, size(W, H), 1, T::TEXTURE_BINDING | T::STORAGE_BINDING);
let out = texture(device, wgpu::TextureFormat::Rgba16Float, size(W, H), 1, T::STORAGE_BINDING | T::COPY_SRC);
let view = |t: &wgpu::Texture| t.create_view(&Default::default());
let (image_view, mid_view, out_view) = (view(&image), view(&mid), view(&out));
let group = |src, dst| device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &bgl, entries: &[
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &uniforms, offset: 0, size: wgpu::BufferSize::new(16) }) },
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &weights, offset: 0, size: wgpu::BufferSize::new(12) }) },
wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(src) },
wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(dst) },
wgpu::BindGroupEntry { binding: 4, resource: counts.as_entire_binding() },
] });
let (first, second) = (group(&image_view, &mid_view), group(&mid_view, &out_view));
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
// The group before the pipeline: it lands at the slots the pipeline reads.
pass.set_bind_group(0, &first, &[0]);
pass.set_pipeline(&pipeline);
pass.dispatch_workgroups(W / 8, H / 4, 1);
pass.set_bind_group(0, &second, &[256]);
pass.dispatch_workgroups(W / 8, H / 4, 1);
}
let (pixels, totals) = (buffer(device, u64::from(W * 8 * H), B::COPY_DST | B::MAP_READ), buffer(device, 16, B::COPY_DST | B::MAP_READ));
encoder.copy_texture_to_buffer(out.as_image_copy(), wgpu::TexelCopyBufferInfo {
buffer: &pixels, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(W * 8), rows_per_image: Some(H) },
}, out.size());
encoder.copy_buffer_to_buffer(&counts, 0, &totals, 0, 16);
queue.submit([encoder.finish()]);
(read(device, &pixels), read(device, &totals))
}
/// `f32` to IEEE half bits, for values in [0, 1].
fn half_bits(v: f32) -> u16 {
if v == 0.0 { return 0 }
let bits = v.to_bits();
let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15;
let mantissa = (bits >> 13) & 0x3ff;
if exp <= 0 { 0 } else { ((exp as u32) << 10 | mantissa) as u16 }
}
#[test]
fn compute_matches_wgpus_bit_for_bit() {
let (device, queue) = gpu();
let (pixels, totals) = steps(&device, &queue);
let (wgpu_device, wgpu_queue) = wgpu_metal();
let (want_pixels, want_totals) = steps(&wgpu_device, &wgpu_queue);
let totals: &[u32] = bytemuck::cast_slice(&totals);
assert_eq!(totals, [2 * W * H / 4; 4], "every invocation of both dispatches ran");
assert!(pixels.iter().any(|&b| b != 0), "the second dispatch stored");
assert!(pixels == want_pixels, "differs from wgpu's at {:?}", pixels.iter().zip(&want_pixels).position(|(a, b)| a != b));
assert_eq!(totals, bytemuck::cast_slice::<u8, u32>(&want_totals));
}
/// wgpu promises a texture nothing wrote reads as zero, as a fill's backdrop does.
#[test]
fn new_textures_read_as_zero() {
use wgpu::TextureUsages as T;
let (device, queue) = gpu();
let layered = wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 2 };
for _ in 0..2 {
let t = texture(&device, wgpu::TextureFormat::Rgba16Float, layered, 2, T::RENDER_ATTACHMENT | T::TEXTURE_BINDING | T::COPY_SRC);
let mut encoder = device.create_command_encoder(&Default::default());
for layer in 0..2 {
for mip in 0..2 {
let view = t.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2), base_mip_level: mip,
mip_level_count: Some(1), base_array_layer: layer, array_layer_count: Some(1), ..Default::default() });
drop(clear(&mut encoder, &view));
}
}
queue.submit([encoder.finish()]);
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
}
let t = texture(&device, wgpu::TextureFormat::Rgba16Float, layered, 2, T::RENDER_ATTACHMENT | T::TEXTURE_BINDING | T::COPY_SRC);
let out = buffer(&device, 256 * u64::from(H / 2), wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ);
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo { texture: &t, mip_level: 1, origin: wgpu::Origin3d { x: 0, y: 0, z: 1 }, aspect: wgpu::TextureAspect::All },
wgpu::TexelCopyBufferInfo { buffer: &out, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256), rows_per_image: Some(H / 2) } },
size(W / 2, H / 2));
queue.submit([encoder.finish()]);
assert!(read(&device, &out).iter().all(|&b| b == 0), "a new texture's last layer and mip read as zero");
}
#[test]
#[cfg_attr(target_abi = "sim", ignore = "the iOS simulator samples no GPU counters")]
fn passes_sample_timestamps_at_their_boundaries() {
let (device, queue) = timed();
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(r#"
@compute @workgroup_size(1) fn noop() {}
@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
return vec4<f32>(f32(i & 1u) * 4.0 - 1.0, f32(i >> 1u) * 4.0 - 1.0, 0.0, 1.0);
}
@fragment fn fs() -> @location(0) vec4<f32> { return vec4<f32>(1.0); }
"#.into()) });
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[], immediate_size: 0 });
let noop = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: None, layout: Some(&layout), module: &module, entry_point: None, compilation_options: Default::default(), cache: None,
});
let fill = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None, layout: Some(&layout),
vertex: wgpu::VertexState { module: &module, entry_point: None, compilation_options: Default::default(), buffers: &[] },
fragment: Some(wgpu::FragmentState { module: &module, entry_point: None, compilation_options: Default::default(),
targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())] }),
primitive: Default::default(), depth_stencil: None, multisample: Default::default(), multiview_mask: None, cache: None,
});
let queries = device.create_query_set(&wgpu::QuerySetDescriptor { label: None, ty: wgpu::QueryType::Timestamp, count: 4 });
let target = texture(&device, wgpu::TextureFormat::Rgba8Unorm, size(W, H), 1, wgpu::TextureUsages::RENDER_ATTACHMENT);
let view = target.create_view(&Default::default());
let resolve = buffer(&device, 32, wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC);
let out = buffer(&device, 32, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ);
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: None, timestamp_writes: Some(wgpu::ComputePassTimestampWrites {
query_set: &queries, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) }) });
pass.set_pipeline(&noop);
pass.dispatch_workgroups(1, 1, 1);
}
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, resolve_target: None, depth_slice: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store } })],
timestamp_writes: Some(wgpu::RenderPassTimestampWrites { query_set: &queries, beginning_of_pass_write_index: Some(2), end_of_pass_write_index: Some(3) }),
..Default::default()
});
pass.set_pipeline(&fill);
pass.draw(0..3, 0..1);
}
let index = queue.submit([encoder.finish()]);
device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: None }).unwrap();
let mut encoder = device.create_command_encoder(&Default::default());
encoder.resolve_query_set(&queries, 0..4, &resolve, 0);
encoder.copy_buffer_to_buffer(&resolve, 0, &out, 0, 32);
queue.submit([encoder.finish()]);
let ticks: Vec<u64> = bytemuck::cast_slice(&read(&device, &out)).to_vec();
assert!(ticks[0] != 0 && ticks.windows(2).all(|w| w[0] <= w[1]), "pass boundaries in order: {ticks:?}");
let ms = (ticks[3] - ticks[0]) as f64 * f64::from(queue.get_timestamp_period()) / 1e6;
assert!(ms < 100.0, "a noop dispatch and a clear take well under 100 ms, not {ms} ms");
}
const WORKGROUP: &str = r#"
@group(0) @binding(0) var<storage, read> input: array<u32>;
@group(0) @binding(1) var<storage, read_write> output: array<u32>;
// Unused by `gather`: Naga's MSL writer skips it, leaving `ids` at index 0 and `count` at index 1.
var<workgroup> unused_wg: array<u32, 16>;
var<workgroup> ids: array<u32, 64>;
var<workgroup> count: atomic<u32>;
@compute @workgroup_size(64)
fn gather(@builtin(local_invocation_index) li: u32, @builtin(workgroup_id) wid: vec3<u32>) {
if (li == 0u) {
atomicStore(&count, 0u);
}
workgroupBarrier();
let idx = wid.x * 64u + li;
let v = input[idx];
if ((v & 1u) != 0u) {
let slot = atomicAdd(&count, 1u);
ids[slot] = v;
}
workgroupBarrier();
let n = atomicLoad(&count);
var sum = 0u;
for (var k = 0u; k < n; k = k + 1u) {
sum = sum + ids[k];
}
output[idx] = sum + n * 100000u;
}
"#;
/// Runs `WORKGROUP` once after switching from a pipeline with no workgroup memory in the same pass,
/// and once in a fresh compute pass on the same encoder.
fn run_workgroup(device: &wgpu::Device, queue: &wgpu::Queue) -> (Vec<u32>, Vec<u32>) {
use wgpu::{BufferUsages as B, ShaderStages as S};
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("workgroup"),
source: wgpu::ShaderSource::Wgsl(WORKGROUP.into()),
});
let noop_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("noop"),
source: wgpu::ShaderSource::Wgsl("@compute @workgroup_size(1) fn noop() {}".into()),
});
let storage = |binding, read_only| wgpu::BindGroupLayoutEntry {
binding,
visibility: S::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &[storage(0, true), storage(1, false)],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let gather = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("gather"),
layout: Some(&layout),
module: &module,
entry_point: Some("gather"),
compilation_options: Default::default(),
cache: None,
});
let noop_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[],
immediate_size: 0,
});
let noop = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("noop"),
layout: Some(&noop_layout),
module: &noop_module,
entry_point: Some("noop"),
compilation_options: Default::default(),
cache: None,
});
let input = buffer(device, 128 * 4, B::STORAGE | B::COPY_DST);
let data: Vec<u32> = (1..=128).collect();
queue.write_buffer(&input, 0, bytemuck::cast_slice(&data));
let out1 = buffer(device, 128 * 4, B::STORAGE | B::COPY_SRC);
let out2 = buffer(device, 128 * 4, B::STORAGE | B::COPY_SRC);
let read1 = buffer(device, 128 * 4, B::COPY_DST | B::MAP_READ);
let read2 = buffer(device, 128 * 4, B::COPY_DST | B::MAP_READ);
let group = |out: &wgpu::Buffer| {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &bgl,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: input.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: out.as_entire_binding() },
],
})
};
let (bg1, bg2) = (group(&out1), group(&out2));
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&noop);
pass.dispatch_workgroups(1, 1, 1);
pass.set_pipeline(&gather);
pass.set_bind_group(0, &bg1, &[]);
pass.dispatch_workgroups(2, 1, 1);
}
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&gather);
pass.set_bind_group(0, &bg2, &[]);
pass.dispatch_workgroups(2, 1, 1);
}
encoder.copy_buffer_to_buffer(&out1, 0, &read1, 0, 128 * 4);
encoder.copy_buffer_to_buffer(&out2, 0, &read2, 0, 128 * 4);
queue.submit([encoder.finish()]);
(
bytemuck::cast_slice(&read(device, &read1)).to_vec(),
bytemuck::cast_slice(&read(device, &read2)).to_vec(),
)
}
#[test]
fn workgroup_memory_matches_wgpus_bit_for_bit() {
let (device, queue) = gpu();
let (first, second) = run_workgroup(&device, &queue);
let (wgpu_device, wgpu_queue) = wgpu_metal();
let (want_first, want_second) = run_workgroup(&wgpu_device, &wgpu_queue);
// 32 odd values in 1..=64 sum to 1024; 32 odd values in 65..=128 sum to 3072.
assert!(first[..64].iter().all(|&v| v == 32 * 100_000 + 1024), "workgroup 0: {:?}", &first[..4]);
assert!(first[64..].iter().all(|&v| v == 32 * 100_000 + 3072), "workgroup 1: {:?}", &first[64..68]);
assert_eq!(first, want_first);
assert_eq!(second, first, "fresh compute pass bound workgroup memory too");
assert_eq!(second, want_second);
}
/// Dispatches `rune-light`'s `field.wgsl` (the only built-in shader with `var<workgroup>`) with
/// its exact bind-group layout so this backend loads it from `builtin_native.metallib` and binds
/// its workgroup memory from `builtin_table.rs`.
fn run_field(device: &wgpu::Device, queue: &wgpu::Queue) -> Vec<u8> {
use wgpu::{BufferUsages as B, ShaderStages as S, TextureUsages as T};
const FW: u32 = 48;
const FH: u32 = 40;
const PADDED_ROW: u32 = 512;
let src = format!(
"{}\n{}",
include_str!("../../../rune-light/src/shaders/common.wgsl"),
include_str!("../../../rune-light/src/shaders/field.wgsl"),
);
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("light field"),
source: wgpu::ShaderSource::Wgsl(src.into()),
});
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("field"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: S::COMPUTE,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: S::COMPUTE,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: None },
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: S::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::WriteOnly,
format: wgpu::TextureFormat::Rgba16Float,
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("light field"),
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("light field"),
layout: Some(&layout),
module: &module,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
if let Some(super::shader::ShaderModule::Naga(ir)) = module.as_custom::<super::shader::ShaderModule>()
&& super::builtin::known(&ir.hash)
{
assert!(!ir.was_parsed(), "light field pipeline missed the precompiled builtin table");
}
let frame_buf = buffer(device, 144, B::UNIFORM | B::COPY_DST);
let mut frame = [0u32; 36];
frame[0] = 96.0f32.to_bits();
frame[1] = 80.0f32.to_bits();
frame[2] = (FW as f32).to_bits();
frame[3] = (FH as f32).to_bits();
frame[4] = 16.0f32.to_bits();
frame[5] = 16.0f32.to_bits();
frame[6] = 0.5f32.to_bits();
frame[7] = 0.125f32.to_bits();
frame[12] = 1;
queue.write_buffer(&frame_buf, 0, bytemuck::cast_slice(&frame));
let prim_buf = buffer(device, 96, B::STORAGE | B::COPY_DST);
let prim: [f32; 24] = [
8.0, 8.0, 80.0, 64.0,
12.0, 12.0, 12.0, 12.0,
0.0, 16.0, 0.0, 0.0,
0.0, 0.6, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.5, 0.5, 0.5, 0.0,
];
queue.write_buffer(&prim_buf, 0, bytemuck::cast_slice(&prim));
let out = texture(device, wgpu::TextureFormat::Rgba16Float, size(FW, FH), 1, T::STORAGE_BINDING | T::COPY_SRC);
let out_view = out.create_view(&Default::default());
let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &bgl,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: frame_buf.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: prim_buf.as_entire_binding() },
wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&out_view) },
],
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &bg, &[]);
pass.dispatch_workgroups(FW.div_ceil(16), FH.div_ceil(16), 1);
}
let readback = buffer(device, u64::from(PADDED_ROW * FH), B::COPY_DST | B::MAP_READ);
encoder.copy_texture_to_buffer(
out.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &readback,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(PADDED_ROW), rows_per_image: Some(FH) },
},
out.size(),
);
queue.submit([encoder.finish()]);
read(device, &readback)
}
#[test]
fn precompiled_field_pipeline_binds_workgroup_memory() {
let (device, queue) = gpu();
let got = run_field(&device, &queue);
let (wgpu_device, wgpu_queue) = wgpu_metal();
let want = run_field(&wgpu_device, &wgpu_queue);
// Texel (23, 19) is device px (47, 39), inside [8..88, 8..72] r=12: exact distance -31.0 (f16 0xCFC0).
let at = 19 * 512 + 23 * 8;
let center_x = u16::from_le_bytes([got[at], got[at + 1]]);
assert_eq!(center_x, 0xCFC0, "centre of occluder must hold -31.0 (0xCFC0), not CLAMP 256.0 (0x5C00)");
for y in 0..40usize {
let row = y * 512..y * 512 + 48 * 8;
assert_eq!(&got[row.clone()], &want[row], "field row {y} differs from wgpu");
}
}
+126
View File
@@ -0,0 +1,126 @@
//! Layouts derived from a pipeline's shaders, for a pipeline made with `layout: None`, as
//! wgpu-core derives them: each group holds every resource the pipeline's entry points use,
//! visible to the stages that use it and typed by its declaration, and the immediates are as
//! large as the largest a stage uses. `get_bind_group_layout` hands out its groups.
use std::collections::BTreeMap;
use wgpu::naga;
use super::layout::{BindGroupLayout, PipelineLayout};
use super::shader::ShaderModule;
/// An entry point a layout is derived from.
pub(super) struct Use<'a> {
pub(super) module: &'a wgpu::ShaderModule,
pub(super) entry: Option<&'a str>,
pub(super) kind: naga::ShaderStage,
}
pub(super) fn layout(label: &str, uses: &[Use<'_>]) -> PipelineLayout {
let mut groups: BTreeMap<u32, BTreeMap<u32, wgpu::BindGroupLayoutEntry>> = BTreeMap::new();
let mut immediates = 0;
for point in uses {
let Some(ShaderModule::Naga(ir)) = point.module.as_custom::<ShaderModule>() else {
super::unsupported!("{label}: a layout derived from a precompiled library's entry points")
};
let (module, info) = ir.parts();
let index = entry(module, point).unwrap_or_else(|e| panic!("{label}: {e}"));
let used = info.get_entry_point(index);
let visibility = match point.kind {
naga::ShaderStage::Vertex => wgpu::ShaderStages::VERTEX,
naga::ShaderStage::Fragment => wgpu::ShaderStages::FRAGMENT,
naga::ShaderStage::Compute => wgpu::ShaderStages::COMPUTE,
other => super::unsupported!("{other:?} shaders"),
};
for (handle, var) in module.global_variables.iter() {
if used[handle].is_empty() { continue }
if var.space == naga::AddressSpace::Immediate {
immediates = immediates.max(module.types[var.ty].inner.size(module.to_ctx()));
continue;
}
let Some(binding) = var.binding else { continue };
let ty = binding_type(module, var).unwrap_or_else(|what| super::unsupported!("{label}: {what}"));
groups.entry(binding.group).or_default().entry(binding.binding)
.and_modify(|e| e.visibility |= visibility)
.or_insert(wgpu::BindGroupLayoutEntry { binding: binding.binding, visibility, ty, count: None });
}
}
let count = groups.keys().next_back().map_or(0, |&g| g + 1);
let layouts: Vec<BindGroupLayout> = (0..count).map(|g| {
let entries: Vec<_> = groups.get(&g).map(|g| g.values().copied().collect()).unwrap_or_default();
BindGroupLayout::new(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &entries })
}).collect();
let refs: Vec<_> = layouts.iter().map(Some).collect();
PipelineLayout::from_groups(&refs, immediates)
}
/// The index of `point`'s entry point: the named one, or the module's only one of its kind.
fn entry(module: &naga::Module, point: &Use<'_>) -> Result<usize, String> {
let mut of_kind = module.entry_points.iter().enumerate().filter(|(_, e)| e.stage == point.kind);
match point.entry {
Some(name) => of_kind.find(|(_, e)| e.name == name).map(|(i, _)| i).ok_or_else(|| format!("no entry point {name}")),
None => match (of_kind.next(), of_kind.next()) {
(Some((i, _)), None) => Ok(i),
_ => Err(format!("no single {:?} entry point", point.kind)),
},
}
}
/// The binding type `var`'s declaration implies, or what this backend can't bind.
fn binding_type(module: &naga::Module, var: &naga::GlobalVariable) -> Result<wgpu::BindingType, String> {
let buffer = |ty| Ok(wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None });
match var.space {
naga::AddressSpace::Uniform => return buffer(wgpu::BufferBindingType::Uniform),
naga::AddressSpace::Storage { access } => {
return buffer(wgpu::BufferBindingType::Storage { read_only: !access.contains(naga::StorageAccess::STORE) });
}
_ => {}
}
Ok(match module.types[var.ty].inner {
naga::TypeInner::Sampler { comparison } => wgpu::BindingType::Sampler(if comparison {
wgpu::SamplerBindingType::Comparison
} else {
wgpu::SamplerBindingType::Filtering
}),
naga::TypeInner::Image { dim, arrayed, class } => {
let view_dimension = match dim {
naga::ImageDimension::D1 => wgpu::TextureViewDimension::D1,
naga::ImageDimension::D2 if arrayed => wgpu::TextureViewDimension::D2Array,
naga::ImageDimension::D2 => wgpu::TextureViewDimension::D2,
naga::ImageDimension::D3 => wgpu::TextureViewDimension::D3,
naga::ImageDimension::Cube if arrayed => wgpu::TextureViewDimension::CubeArray,
naga::ImageDimension::Cube => wgpu::TextureViewDimension::Cube,
};
match class {
naga::ImageClass::Sampled { kind, multi } => wgpu::BindingType::Texture {
sample_type: match kind {
naga::ScalarKind::Sint => wgpu::TextureSampleType::Sint,
naga::ScalarKind::Uint => wgpu::TextureSampleType::Uint,
_ => wgpu::TextureSampleType::Float { filterable: true },
},
view_dimension,
multisampled: multi,
},
naga::ImageClass::Depth { multi } => {
wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Depth, view_dimension, multisampled: multi }
}
naga::ImageClass::Storage { format, access } => wgpu::BindingType::StorageTexture {
access: if access.contains(naga::StorageAccess::ATOMIC) {
wgpu::StorageTextureAccess::Atomic
} else if access.contains(naga::StorageAccess::LOAD | naga::StorageAccess::STORE) {
wgpu::StorageTextureAccess::ReadWrite
} else if access.contains(naga::StorageAccess::STORE) {
wgpu::StorageTextureAccess::WriteOnly
} else {
wgpu::StorageTextureAccess::ReadOnly
},
format: wgpu_naga_bridge::map_storage_format_from_naga(format),
view_dimension,
},
naga::ImageClass::External => return Err("external textures".into()),
}
}
ref other => return Err(format!("a binding of type {other:?}")),
})
}
@@ -0,0 +1,149 @@
use wgpu::util::DeviceExt;
use super::bench::{clear, gpu};
fn wgpu_metal() -> (wgpu::Device, wgpu::Queue) {
let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
descriptor.backends = wgpu::Backends::METAL;
let instance = wgpu::Instance::new(descriptor);
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).unwrap();
pollster::block_on(adapter.request_device(&Default::default())).unwrap()
}
/// Group 0 is unused; group 1 holds a uniform both stages read, a texture and a sampler.
const DRAW: &str = r#"
struct U { tint: vec4<f32>, shift: vec4<f32> };
@group(1) @binding(0) var<uniform> u: U;
@group(1) @binding(2) var tex: texture_2d<f32>;
@group(1) @binding(3) var smp: sampler;
struct O { @builtin(position) p: vec4<f32>, @location(0) uv: vec2<f32> };
@vertex fn vs(@builtin(vertex_index) i: u32) -> O {
let uv = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
var o: O;
o.p = vec4<f32>(uv * 2.0 - 1.0 + u.shift.xy, 0.0, 1.0);
o.uv = uv;
return o;
}
@fragment fn fs(i: O) -> @location(0) vec4<f32> { return textureSample(tex, smp, i.uv) * u.tint; }
"#;
const SUM: &str = r#"
@group(0) @binding(0) var<storage, read> input: array<u32>;
@group(0) @binding(1) var<storage, read_write> output: array<u32>;
@compute @workgroup_size(4) fn sum(@builtin(global_invocation_id) id: vec3<u32>) {
output[id.x] = input[id.x] * 3u + 1u;
}
"#;
const SIZE: u32 = 64;
fn draw(device: &wgpu::Device, queue: &wgpu::Queue) -> Vec<u8> {
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("derived"), source: wgpu::ShaderSource::Wgsl(DRAW.into()) });
let format = wgpu::TextureFormat::Rgba8Unorm;
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("derived"),
layout: None,
vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] },
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &module, entry_point: Some("fs"), compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })],
}),
multiview_mask: None,
cache: None,
});
let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None, contents: bytemuck::cast_slice(&[1.0f32, 0.5, 0.25, 1.0, 0.25, -0.25, 0.0, 0.0]), usage: wgpu::BufferUsages::UNIFORM,
});
let texels: Vec<u8> = (0..16u8).flat_map(|i| [i * 16, 255 - i * 16, 128, 255]).collect();
let source = device.create_texture_with_data(queue, &wgpu::TextureDescriptor {
label: None, size: wgpu::Extent3d { width: 4, height: 4, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, format, usage: wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[],
}, Default::default(), &texels);
let sampler = device.create_sampler(&Default::default());
let view = source.create_view(&Default::default());
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(1),
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&view) },
wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&sampler) },
],
});
let empty = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &pipeline.get_bind_group_layout(0), entries: &[] });
let target = device.create_texture(&wgpu::TextureDescriptor {
label: None, size: wgpu::Extent3d { width: SIZE, height: SIZE, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, view_formats: &[],
});
let out = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: (SIZE * SIZE * 4) as u64, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
let mut encoder = device.create_command_encoder(&Default::default());
{
let target_view = target.create_view(&Default::default());
let mut pass = clear(&mut encoder, &target_view);
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &empty, &[]);
pass.set_bind_group(1, &group, &[]);
pass.draw(0..3, 0..1);
}
encoder.copy_texture_to_buffer(target.as_image_copy(), wgpu::TexelCopyBufferInfo {
buffer: &out, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(SIZE * 4), rows_per_image: Some(SIZE) },
}, target.size());
queue.submit([encoder.finish()]);
read(device, &out)
}
fn sum(device: &wgpu::Device, queue: &wgpu::Queue) -> Vec<u8> {
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("sum"), source: wgpu::ShaderSource::Wgsl(SUM.into()) });
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("sum"), layout: None, module: &module, entry_point: None, compilation_options: Default::default(), cache: None,
});
let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None, contents: bytemuck::cast_slice(&[1u32, 2, 3, 4, 5, 6, 7, 8]), usage: wgpu::BufferUsages::STORAGE,
});
let output = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 32, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
let readback = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 32, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: input.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: output.as_entire_binding() },
],
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &group, &[]);
pass.dispatch_workgroups(2, 1, 1);
}
encoder.copy_buffer_to_buffer(&output, 0, &readback, 0, 32);
queue.submit([encoder.finish()]);
read(device, &readback)
}
fn read(device: &wgpu::Device, buffer: &wgpu::Buffer) -> Vec<u8> {
let slice = buffer.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let out = slice.get_mapped_range().unwrap().to_vec();
buffer.unmap();
out
}
/// A pipeline made with `layout: None` derives its layout from its shaders, as wgpu does, and
/// draws the same pixels through the groups `get_bind_group_layout` hands out.
#[test]
fn a_pipeline_without_a_layout_derives_one_as_wgpu_does() {
let (device, queue) = gpu();
let (wgpu_device, wgpu_queue) = wgpu_metal();
let ours = draw(&device, &queue);
assert!(ours.chunks(4).any(|p| p != [0, 0, 51, 102]), "the triangle drew");
assert_eq!(ours, draw(&wgpu_device, &wgpu_queue));
let sums = sum(&device, &queue);
assert_eq!(bytemuck::cast_slice::<u8, u32>(&sums), [4, 7, 10, 13, 16, 19, 22, 25]);
assert_eq!(sums, sum(&wgpu_device, &wgpu_queue));
}
+173
View File
@@ -0,0 +1,173 @@
//! The device: what it shares with its queue, and the resources it makes.
#![allow(unsafe_code)]
use std::future::ready;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::sync::atomic::{AtomicIsize, AtomicUsize, Ordering};
#[cfg(debug_assertions)]
use objc2_foundation::NSString;
#[cfg(debug_assertions)]
use objc2_metal::MTLEvent;
use objc2_metal::{MTLCommandQueue, MTLDevice, MTLLanguageVersion, MTLLibrary, MTLSharedEvent};
use parking_lot::Mutex;
use wgpu::custom::*;
use super::encode::{Inert, MetalEncoder, Zeros, zero_texture};
use super::layout::{BindGroup, BindGroupLayout, PipelineLayout};
use super::resource::{Live, MetalBuffer, MetalSampler, MetalTexture};
use super::shader::ShaderModule;
use super::submit::{MetalQueue, State};
use super::{Obj, info, send_sync};
/// The device, its one queue, the event every command buffer signals on completion, and the
/// submission state behind it.
#[derive(Debug)]
pub(crate) struct Shared {
pub(super) device: Obj<dyn MTLDevice>,
pub(super) queue: Obj<dyn MTLCommandQueue>,
pub(super) event: Obj<dyn MTLSharedEvent>,
pub(super) msl: ((u8, u8), MTLLanguageVersion),
pub(super) state: Mutex<State>,
/// Buffers alive, for `Device::get_internal_counters`.
pub(super) buffers: Arc<AtomicIsize>,
/// Bind groups and textures alive, likewise.
bind_groups: Arc<AtomicIsize>,
textures: Arc<AtomicIsize>,
/// Encoders that made a command buffer not yet submitted or dropped. While none has, every
/// recorded command that reads a buffer's storage was submitted.
pub(super) recording: AtomicUsize,
/// What new textures are zeroed from, made with the first.
pub(super) zeros: OnceLock<Zeros>,
/// Rune's precompiled pipelines, loaded with the first pipeline that looks one up.
pub(super) builtin: OnceLock<Option<Obj<dyn MTLLibrary>>>,
}
send_sync!(Shared);
#[derive(Debug)]
pub(crate) struct MetalDevice {
pub(crate) shared: Arc<Shared>,
features: wgpu::Features,
limits: wgpu::Limits,
}
pub(super) fn new(device: Obj<dyn MTLDevice>, desc: &wgpu::DeviceDescriptor<'_>) -> (MetalDevice, MetalQueue) {
let queue = device.newCommandQueue().expect("a Metal command queue");
let event = device.newSharedEvent().expect("a Metal shared event");
#[cfg(debug_assertions)]
{
queue.setLabel(Some(&NSString::from_str("rune metal queue")));
event.setLabel(Some(&NSString::from_str("rune metal event")));
}
let shared = Arc::new(Shared {
queue,
event,
msl: msl_version(),
state: Mutex::new(State::default()),
buffers: Arc::default(),
bind_groups: Arc::default(),
textures: Arc::default(),
recording: AtomicUsize::new(0),
zeros: OnceLock::new(),
builtin: OnceLock::new(),
device,
});
let device = MetalDevice { shared: shared.clone(), features: desc.required_features, limits: desc.required_limits.clone() };
(device, MetalQueue(shared))
}
/// wgpu-hal's choice of MSL version for this macOS or iOS. Their numbers meet at 26; before, iOS
/// 18 and 17 match macOS 15 and 14.
pub(super) fn msl_version() -> ((u8, u8), MTLLanguageVersion) {
let mut buf = [0u8; 32];
let mut len = buf.len();
// SAFETY: sysctlbyname writes at most `len` bytes into `buf` and the length it wrote into `len`.
let ok = unsafe { libc::sysctlbyname(c"kern.osproductversion".as_ptr(), buf.as_mut_ptr().cast(), &mut len, std::ptr::null_mut(), 0) } == 0;
let version = if ok { String::from_utf8_lossy(&buf[..len.saturating_sub(1)]).into_owned() } else { String::new() };
let major: u32 = version.split('.').next().and_then(|m| m.trim().parse().ok()).unwrap_or(0);
#[cfg(not(target_os = "macos"))]
let major = match major { 18 => 15, 17 => 14, 26.. => major, _ => 0 };
match major {
26.. => ((4, 0), MTLLanguageVersion::Version4_0),
15 => ((3, 2), MTLLanguageVersion::Version3_2),
14 => ((3, 1), MTLLanguageVersion::Version3_1),
_ => ((3, 0), MTLLanguageVersion::Version3_0),
}
}
impl DeviceInterface for MetalDevice {
fn features(&self) -> wgpu::Features { self.features }
fn limits(&self) -> wgpu::Limits { self.limits.clone() }
fn adapter_info(&self) -> wgpu::AdapterInfo { info(&self.shared.device) }
fn create_shader_module(&self, desc: wgpu::ShaderModuleDescriptor<'_>, checks: wgpu::ShaderRuntimeChecks) -> DispatchShaderModule {
DispatchShaderModule::custom(ShaderModule::new(desc, checks))
}
unsafe fn create_shader_module_passthrough(&self, desc: &wgpu::ShaderModuleDescriptorPassthrough<'_>) -> DispatchShaderModule {
DispatchShaderModule::custom(ShaderModule::passthrough(&self.shared, desc))
}
fn create_bind_group_layout(&self, desc: &wgpu::BindGroupLayoutDescriptor<'_>) -> DispatchBindGroupLayout {
DispatchBindGroupLayout::custom(BindGroupLayout::new(desc))
}
fn create_bind_group(&self, desc: &wgpu::BindGroupDescriptor<'_>) -> DispatchBindGroup { DispatchBindGroup::custom(BindGroup::new(desc, Live::new(&self.shared.bind_groups))) }
fn create_pipeline_layout(&self, desc: &wgpu::PipelineLayoutDescriptor<'_>) -> DispatchPipelineLayout {
DispatchPipelineLayout::custom(PipelineLayout::new(desc))
}
fn create_render_pipeline(&self, desc: &wgpu::RenderPipelineDescriptor<'_>) -> DispatchRenderPipeline {
DispatchRenderPipeline::custom(super::pipeline::create(&self.shared, desc))
}
fn create_mesh_pipeline(&self, _: &wgpu::MeshPipelineDescriptor<'_>) -> DispatchRenderPipeline {
super::unsupported!("mesh shaders")
}
fn create_compute_pipeline(&self, desc: &wgpu::ComputePipelineDescriptor<'_>) -> DispatchComputePipeline {
DispatchComputePipeline::custom(super::compute::create(&self.shared, desc))
}
unsafe fn create_pipeline_cache(&self, _: &wgpu::PipelineCacheDescriptor<'_>) -> DispatchPipelineCache { DispatchPipelineCache::custom(Inert) }
fn create_buffer(&self, desc: &wgpu::BufferDescriptor<'_>) -> DispatchBuffer {
DispatchBuffer::custom(MetalBuffer::new(&self.shared, desc.size, desc.label))
}
fn create_texture(&self, desc: &wgpu::TextureDescriptor<'_>) -> DispatchTexture {
let texture = MetalTexture::new(&self.shared.device, desc, Live::new(&self.shared.textures));
let raw = texture.raw.clone();
let zeros = self.shared.zeros.get_or_init(|| Zeros::new(&self.shared));
self.shared.upload(|blit| zero_texture(blit, zeros, &raw), [raw.clone() as _]);
DispatchTexture::custom(texture)
}
fn create_external_texture(&self, _: &wgpu::ExternalTextureDescriptor<'_>, _: &[&wgpu::TextureView]) -> DispatchExternalTexture {
super::unsupported!("external textures")
}
fn create_blas(&self, _: &wgpu::CreateBlasDescriptor<'_>, _: wgpu::BlasGeometrySizeDescriptors) -> (Option<u64>, DispatchBlas) {
super::unsupported!("ray tracing")
}
fn create_tlas(&self, _: &wgpu::CreateTlasDescriptor<'_>) -> DispatchTlas { super::unsupported!("ray tracing") }
fn create_sampler(&self, desc: &wgpu::SamplerDescriptor<'_>) -> DispatchSampler {
DispatchSampler::custom(MetalSampler::new(&self.shared.device, desc))
}
fn create_query_set(&self, desc: &wgpu::QuerySetDescriptor<'_>) -> DispatchQuerySet {
DispatchQuerySet::custom(super::query::QuerySet::new(&self.shared.device, desc))
}
fn create_command_encoder(&self, desc: &wgpu::CommandEncoderDescriptor<'_>) -> DispatchCommandEncoder {
DispatchCommandEncoder::custom(MetalEncoder::new(self.shared.clone(), desc.label))
}
fn create_render_bundle_encoder(&self, _: &wgpu::RenderBundleEncoderDescriptor<'_>) -> DispatchRenderBundleEncoder {
super::unsupported!("render bundles")
}
fn set_device_lost_callback(&self, _: BoxDeviceLostCallback) {}
fn on_uncaptured_error(&self, _: Arc<dyn wgpu::UncapturedErrorHandler>) {}
// The backend validates nothing, so a scope never catches an error.
fn push_error_scope(&self, _: wgpu::ErrorFilter) -> u32 { 0 }
fn pop_error_scope(&self, _: u32) -> Pin<Box<dyn PopErrorScopeFuture>> { Box::pin(ready(None)) }
unsafe fn start_graphics_debugger_capture(&self) {}
unsafe fn stop_graphics_debugger_capture(&self) {}
fn poll(&self, poll: wgpu::wgt::PollType<u64>) -> Result<wgpu::PollStatus, wgpu::PollError> { self.shared.poll(poll) }
fn get_internal_counters(&self) -> wgpu::InternalCounters {
let counters = wgpu::InternalCounters::default();
counters.hal.buffers.set(self.shared.buffers.load(Ordering::Relaxed));
counters.hal.bind_groups.set(self.shared.bind_groups.load(Ordering::Relaxed));
counters.hal.textures.set(self.shared.textures.load(Ordering::Relaxed));
counters
}
fn generate_allocator_report(&self) -> Option<wgpu::AllocatorReport> { None }
fn destroy(&self) {}
}
+379
View File
@@ -0,0 +1,379 @@
//! The command encoder: one `MTLCommandBuffer` with unretained references, blit copies between
//! passes, and the list of what it used, which the queue keeps alive until the buffer completes.
#![allow(unsafe_code)]
use std::any::Any;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use objc2_foundation::NSRange;
#[cfg(debug_assertions)]
use objc2_foundation::NSString;
#[cfg(debug_assertions)]
use objc2_metal::MTLResource;
use objc2_metal::{MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLDevice, MTLOrigin, MTLResourceOptions, MTLSize, MTLTexture};
use objc2::rc::autoreleasepool;
use objc2::runtime::ProtocolObject;
use parking_lot::Mutex;
use wgpu::custom::*;
use super::compute::MetalComputePass;
use super::pass::MetalPass;
use super::query::QuerySet;
use super::resource::{MetalBuffer, MetalTexture, TextureRaw};
use super::submit::Keep;
use super::{Obj, Shared, send_sync};
/// What an encoder has recorded so far. Its passes share it, so a pass's resources join it.
#[derive(Debug)]
pub(super) struct Rec {
shared: Arc<Shared>,
open: Open,
pub(super) keep: Keep,
/// Whether a pass drew into a drawable, so the buffer waits for its present.
pub(super) drawable: bool,
#[cfg(debug_assertions)]
label: Option<Box<str>>,
}
/// The command buffer as recorded so far.
#[derive(Debug, Default)]
enum Open {
/// Nothing recorded yet.
#[default]
Empty,
Buffer(Obj<dyn MTLCommandBuffer>),
/// A blit encoder is open for copies, until a pass or `finish` ends it.
Blit(Obj<dyn MTLCommandBuffer>, Obj<dyn MTLBlitCommandEncoder>),
}
impl Open {
/// The buffer, ending an open blit encoder.
fn close(self) -> Option<Obj<dyn MTLCommandBuffer>> {
match self {
Open::Empty => None,
Open::Buffer(cb) => Some(cb),
Open::Blit(cb, blit) => {
blit.endEncoding();
Some(cb)
}
}
}
}
#[derive(Debug)]
pub(crate) struct MetalEncoder {
rec: Arc<Mutex<Rec>>,
}
/// A finished encoder's buffer, until a submit takes it.
#[derive(Debug)]
pub(crate) struct MetalCommandBuffer(Mutex<Option<Recorded>>);
#[derive(Debug)]
pub(super) struct Recorded {
pub(super) cb: Obj<dyn MTLCommandBuffer>,
pub(super) keep: Keep,
pub(super) drawable: bool,
pub(super) shared: Arc<Shared>,
}
/// Pipeline caches: accepted and ignored.
#[derive(Debug)]
pub(crate) struct Inert;
send_sync!(Rec, Recorded);
impl Rec {
/// The buffer, made on the first command: from then until it is submitted or dropped, the
/// encoder counts in `Shared::recording`, so read buffer storage only after this.
fn cb(&mut self) -> &ProtocolObject<dyn MTLCommandBuffer> {
if let Open::Empty = self.open {
self.shared.recording.fetch_add(1, Ordering::AcqRel);
let cb = self.shared.command_buffer();
#[cfg(debug_assertions)]
{
let label = self.label.as_deref().unwrap_or("rune metal encoder");
cb.setLabel(Some(&NSString::from_str(label)));
}
self.open = Open::Buffer(cb);
}
match &self.open {
Open::Buffer(cb) | Open::Blit(cb, _) => cb,
Open::Empty => unreachable!("opened above"),
}
}
/// The buffer for a render or compute pass: an open blit encoder ends first, as Metal
/// allows one encoder at a time.
pub(super) fn pass_buffer(&mut self) -> &ProtocolObject<dyn MTLCommandBuffer> {
if let Open::Blit(..) = self.open
&& let Some(cb) = std::mem::take(&mut self.open).close()
{
self.open = Open::Buffer(cb);
}
self.cb()
}
fn blit(&mut self) -> &ProtocolObject<dyn MTLBlitCommandEncoder> {
if !matches!(self.open, Open::Blit(..)) {
self.cb();
let Open::Buffer(cb) = std::mem::take(&mut self.open) else { unreachable!("opened above") };
let blit = autoreleasepool(|_| cb.blitCommandEncoder()).expect("a Metal blit encoder");
#[cfg(debug_assertions)]
blit.setLabel(Some(&NSString::from_str("rune metal blit")));
self.open = Open::Blit(cb, blit);
}
match &self.open {
Open::Blit(_, blit) => blit,
_ => unreachable!("opened above"),
}
}
fn keep(&mut self, items: impl IntoIterator<Item = Arc<dyn Any + Send + Sync>>) { self.keep.extend(items); }
pub(super) fn shared(&self) -> &Shared { &self.shared }
}
impl Drop for Rec {
/// An encoder dropped unfinished. Metal ends a buffer's open encoders when it frees the
/// buffer, reading their attachments, so the buffer goes before what it used.
fn drop(&mut self) {
if std::mem::take(&mut self.open).close().is_some() { self.shared.recording.fetch_sub(1, Ordering::AcqRel); }
self.shared.recycle(std::mem::take(&mut self.keep));
}
}
impl MetalEncoder {
pub(crate) fn new(shared: Arc<Shared>, label: Option<&str>) -> Self {
let keep = shared.keep_list();
#[cfg(not(debug_assertions))]
let _ = label;
MetalEncoder {
rec: Arc::new(Mutex::new(Rec {
shared,
open: Open::Empty,
keep,
drawable: false,
#[cfg(debug_assertions)]
label: label.map(Box::from),
})),
}
}
}
impl MetalCommandBuffer {
pub(super) fn take(&self) -> Option<Recorded> { self.0.lock().take() }
}
impl Recorded {
/// No longer recording: submitted, or dropped unsubmitted.
pub(super) fn close(self) -> (Obj<dyn MTLCommandBuffer>, Keep) {
self.shared.recording.fetch_sub(1, Ordering::AcqRel);
(self.cb, self.keep)
}
}
impl Drop for MetalCommandBuffer {
fn drop(&mut self) {
if let Some(recorded) = self.0.get_mut().take() {
let shared = recorded.shared.clone();
let (cb, keep) = recorded.close();
drop(cb);
shared.recycle(keep);
}
}
}
fn origin(o: wgpu::Origin3d, z: u32) -> MTLOrigin { MTLOrigin { x: o.x as usize, y: o.y as usize, z: z as usize } }
fn extent(width: u32, height: u32, depth: u32) -> MTLSize { MTLSize { width: width as usize, height: height as usize, depth: depth as usize } }
/// A buffer layout's row and image strides in bytes, filling in tightly packed defaults.
fn strides(format: wgpu::TextureFormat, layout: wgpu::TexelCopyBufferLayout, size: wgpu::Extent3d) -> (usize, usize) {
let (bw, bh) = format.block_dimensions();
let block = format.block_copy_size(None).expect("a copyable color format");
let row = layout.bytes_per_row.unwrap_or(size.width.div_ceil(bw) * block) as usize;
let rows = layout.rows_per_image.unwrap_or(size.height).div_ceil(bh) as usize;
(row, row * rows)
}
/// The copies a texture region splits into: one per array layer, or one for a 3D texture.
/// Yields (slice, z, depth, image index).
fn layers(t: &TextureRaw, at: wgpu::Origin3d, size: wgpu::Extent3d) -> impl Iterator<Item = (usize, u32, u32, usize)> {
let three = t.dimension == wgpu::TextureDimension::D3;
let count = if three { 1 } else { size.depth_or_array_layers };
(0..count).map(move |i| if three { (0, at.z, size.depth_or_array_layers, 0) } else { ((at.z + i) as usize, 0, 1, i as usize) })
}
/// Bytes of zeros a texture's first clear copies from: the widest row, 16384 texels of 16 bytes.
const ZEROS: usize = 256 << 10;
/// A buffer of `ZEROS` zeroed bytes, outside the live buffer count.
#[derive(Debug)]
pub(super) struct Zeros(Obj<dyn MTLBuffer>);
send_sync!(Zeros);
impl Zeros {
pub(super) fn new(shared: &Shared) -> Self {
let raw = shared.device.newBufferWithLength_options(ZEROS, MTLResourceOptions::StorageModeShared).expect("a Metal buffer");
#[cfg(debug_assertions)]
raw.setLabel(Some(&NSString::from_str("rune metal zeros")));
Zeros(raw)
}
}
/// Zeroes every mip and layer of a new texture, which wgpu promises reads as zero until written.
pub(super) fn zero_texture(blit: &ProtocolObject<dyn MTLBlitCommandEncoder>, zeros: &Zeros, texture: &TextureRaw) {
let Some(block) = texture.format.block_copy_size(None) else { return };
let (bw, bh) = texture.format.block_dimensions();
let three = texture.dimension == wgpu::TextureDimension::D3;
let raw = &texture.raw;
for mip in 0..texture.mips as usize {
let (w, h) = ((raw.width() >> mip).max(1), (raw.height() >> mip).max(1));
let row = w.div_ceil(bw as usize) * block as usize;
let strip = (ZEROS / row).max(1) * bh as usize;
let slices = if three { (raw.depth() >> mip).max(1) } else { texture.layers as usize };
for s in 0..slices {
let (slice, z) = if three { (0, s) } else { (s, 0) };
for y in (0..h).step_by(strip) {
// SAFETY: each strip is within the mip and reads at most `ZEROS` bytes.
unsafe {
blit.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(
&zeros.0, 0, row, 0, MTLSize { width: w, height: strip.min(h - y), depth: 1 },
raw, slice, mip, MTLOrigin { x: 0, y, z })
}
}
}
}
}
pub(super) fn buffer_to_texture(blit: &ProtocolObject<dyn MTLBlitCommandEncoder>, buffer: &ProtocolObject<dyn MTLBuffer>,
layout: wgpu::TexelCopyBufferLayout, texture: &TextureRaw, mip: u32, at: wgpu::Origin3d, size: wgpu::Extent3d) {
let (row, image) = strides(texture.format, layout, size);
for (slice, z, depth, i) in layers(texture, at, size) {
let per_image = if depth > 1 { image } else { 0 };
// SAFETY: wgpu validated the regions against both resources.
unsafe {
blit.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(
buffer, layout.offset as usize + image * i, row, per_image, extent(size.width, size.height, depth),
&texture.raw, slice, mip as usize, origin(at, z))
}
}
}
fn texture_to_buffer(blit: &ProtocolObject<dyn MTLBlitCommandEncoder>, texture: &TextureRaw, mip: u32, at: wgpu::Origin3d,
buffer: &ProtocolObject<dyn MTLBuffer>, layout: wgpu::TexelCopyBufferLayout, size: wgpu::Extent3d) {
let (row, image) = strides(texture.format, layout, size);
for (slice, z, depth, i) in layers(texture, at, size) {
let per_image = if depth > 1 { image } else { 0 };
// SAFETY: wgpu validated the regions against both resources.
unsafe {
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage(
&texture.raw, slice, mip as usize, origin(at, z), extent(size.width, size.height, depth),
buffer, layout.offset as usize + image * i, row, per_image)
}
}
}
fn texture(info: &wgpu::TexelCopyTextureInfo<'_>) -> Arc<TextureRaw> {
info.texture.as_custom::<MetalTexture>().expect("a Metal texture").raw.clone()
}
fn buffer(buffer: &DispatchBuffer) -> &MetalBuffer { buffer.as_custom::<MetalBuffer>().expect("a Metal buffer") }
impl CommandEncoderInterface for MetalEncoder {
fn copy_buffer_to_buffer(&self, source: &DispatchBuffer, from: wgpu::BufferAddress, destination: &DispatchBuffer,
to: wgpu::BufferAddress, size: Option<wgpu::BufferAddress>) {
let size = size.unwrap_or_else(|| buffer(source).raw().size - from);
if size == 0 { return }
let mut rec = self.rec.lock();
rec.cb();
let (src, dst) = (buffer(source).raw(), buffer(destination).store.gpu_write());
// SAFETY: wgpu validated both ranges.
unsafe { rec.blit().copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size(&src.raw, from as usize, &dst.raw, to as usize, size as usize) };
rec.keep([src as _, dst as _]);
}
fn copy_buffer_to_texture(&self, source: wgpu::TexelCopyBufferInfo<'_>, destination: wgpu::TexelCopyTextureInfo<'_>, size: wgpu::Extent3d) {
if size.width == 0 || size.height == 0 || size.depth_or_array_layers == 0 { return }
let mut rec = self.rec.lock();
rec.cb();
let (src, dst) = (source.buffer.as_custom::<MetalBuffer>().expect("a Metal buffer").raw(), texture(&destination));
buffer_to_texture(rec.blit(), &src.raw, source.layout, &dst, destination.mip_level, destination.origin, size);
rec.drawable |= dst.drawable;
rec.keep([src as _, dst as _]);
}
fn copy_texture_to_buffer(&self, source: wgpu::TexelCopyTextureInfo<'_>, destination: wgpu::TexelCopyBufferInfo<'_>, size: wgpu::Extent3d) {
if size.width == 0 || size.height == 0 || size.depth_or_array_layers == 0 { return }
let (src, dst) = (texture(&source), destination.buffer.as_custom::<MetalBuffer>().expect("a Metal buffer").store.gpu_write());
let mut rec = self.rec.lock();
texture_to_buffer(rec.blit(), &src, source.mip_level, source.origin, &dst.raw, destination.layout, size);
rec.keep([src as _, dst as _]);
}
fn copy_texture_to_texture(&self, source: wgpu::TexelCopyTextureInfo<'_>, destination: wgpu::TexelCopyTextureInfo<'_>, size: wgpu::Extent3d) {
if size.width == 0 || size.height == 0 || size.depth_or_array_layers == 0 { return }
let (src, dst) = (texture(&source), texture(&destination));
let mut rec = self.rec.lock();
let blit = rec.blit();
for ((from_slice, from_z, depth, _), (to_slice, to_z, _, _)) in layers(&src, source.origin, size).zip(layers(&dst, destination.origin, size)) {
// SAFETY: wgpu validated both regions.
unsafe {
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(
&src.raw, from_slice, source.mip_level as usize, origin(source.origin, from_z), extent(size.width, size.height, depth),
&dst.raw, to_slice, destination.mip_level as usize, origin(destination.origin, to_z))
}
}
rec.drawable |= dst.drawable;
rec.keep([src as _, dst as _]);
}
fn begin_compute_pass(&self, desc: &wgpu::ComputePassDescriptor<'_>) -> DispatchComputePass {
DispatchComputePass::custom(MetalComputePass::begin(self.rec.clone(), desc))
}
fn begin_render_pass(&self, desc: &wgpu::RenderPassDescriptor<'_>) -> DispatchRenderPass {
DispatchRenderPass::custom(MetalPass::begin(self.rec.clone(), desc))
}
fn finish(&mut self) -> DispatchCommandBuffer {
let mut rec = self.rec.lock();
let recorded = std::mem::take(&mut rec.open).close().map(|cb| Recorded { cb, keep: std::mem::take(&mut rec.keep), drawable: rec.drawable, shared: rec.shared.clone() });
DispatchCommandBuffer::custom(MetalCommandBuffer(Mutex::new(recorded)))
}
fn clear_texture(&self, _: &DispatchTexture, _: &wgpu::ImageSubresourceRange) {
super::unsupported!("CommandEncoder::clear_texture")
}
fn clear_buffer(&self, target: &DispatchBuffer, offset: wgpu::BufferAddress, size: Option<wgpu::BufferAddress>) {
let raw = buffer(target).store.gpu_write();
let size = size.unwrap_or(raw.size - offset);
if size == 0 { return }
let mut rec = self.rec.lock();
rec.blit().fillBuffer_range_value(&raw.raw, NSRange::new(offset as usize, size as usize), 0);
rec.keep([raw as _]);
}
fn insert_debug_marker(&self, _: &str) {}
fn push_debug_group(&self, _: &str) {}
fn pop_debug_group(&self) {}
fn write_timestamp(&self, _: &DispatchQuerySet, _: u32) { super::unsupported!("timestamps between passes") }
fn resolve_query_set(&self, set: &DispatchQuerySet, first: u32, count: u32, destination: &DispatchBuffer, offset: wgpu::BufferAddress) {
if count == 0 { return }
let set = set.as_custom::<QuerySet>().expect("a Metal query set").raw.clone();
let dst = buffer(destination).store.gpu_write();
let mut rec = self.rec.lock();
// SAFETY: wgpu validated the range against the set and the destination's size.
unsafe { rec.blit().resolveCounters_inRange_destinationBuffer_destinationOffset(&set.0, NSRange::new(first as usize, count as usize), &dst.raw, offset as usize) };
rec.keep([set as _, dst as _]);
}
fn mark_acceleration_structures_built<'a>(&self, _: &mut dyn Iterator<Item = &'a wgpu::Blas>, _: &mut dyn Iterator<Item = &'a wgpu::Tlas>) {
super::unsupported!("ray tracing")
}
fn build_acceleration_structures<'a>(&self, _: &mut dyn Iterator<Item = &'a wgpu::BlasBuildEntry<'a>>, _: &mut dyn Iterator<Item = &'a wgpu::Tlas>) {
super::unsupported!("ray tracing")
}
fn transition_resources<'a>(&mut self, _: &mut dyn Iterator<Item = wgpu::wgt::BufferTransition<&'a DispatchBuffer>>,
_: &mut dyn Iterator<Item = wgpu::wgt::TextureTransition<&'a DispatchTexture>>) {}
}
impl CommandBufferInterface for MetalCommandBuffer {}
impl PipelineCacheInterface for Inert {
fn get_data(&self) -> Option<Vec<u8>> { None }
}
+219
View File
@@ -0,0 +1,219 @@
//! Bind group layouts, pipeline layouts and bind groups. A pipeline layout hands each stage's
//! buffers, textures and samplers slots counted up group by group, as wgpu-hal does: immediates
//! first, then every group's entries in binding order, then the sizes buffer when a stage sees
//! a storage buffer. A bind group records its resources per stage at slots relative to its
//! group's first, so binding it is adding the layout's base.
use std::sync::Arc;
use objc2_metal::{MTLSamplerState, MTLTexture};
use wgpu::custom::*;
use wgpu::naga::{self, back::msl};
use super::resource::{Live, MetalBuffer, MetalSampler, MetalView};
use super::store::Store;
use super::{Obj, send_sync};
/// The stages a pipeline binds resources for: vertex and fragment for render pipelines, then compute.
pub(super) const STAGES: [wgpu::ShaderStages; 3] = [wgpu::ShaderStages::VERTEX, wgpu::ShaderStages::FRAGMENT, wgpu::ShaderStages::COMPUTE];
/// The compute stage's index in `STAGES`.
pub(super) const COMPUTE: usize = 2;
/// Slots of each kind a stage has handed out.
#[derive(Debug, Clone, Copy, Default)]
pub(super) struct Counts {
pub(super) buffers: u8,
pub(super) textures: u8,
pub(super) samplers: u8,
}
#[derive(Debug)]
pub(crate) struct BindGroupLayout {
/// Sorted by binding.
entries: Arc<[wgpu::BindGroupLayoutEntry]>,
}
#[derive(Debug)]
pub(crate) struct PipelineLayout {
pub(super) raw: Arc<LayoutRaw>,
}
#[derive(Debug)]
pub(crate) struct LayoutRaw {
/// Each group's first slots, per stage.
pub(super) bases: Vec<[Counts; 3]>,
pub(super) stages: [msl::EntryPointResources; 3],
pub(super) immediates: u32,
/// Each group's entries, for `get_bind_group_layout`.
groups: Vec<Arc<[wgpu::BindGroupLayoutEntry]>>,
}
impl LayoutRaw {
/// Group `index`'s layout, as a pipeline made with this layout hands it out.
pub(super) fn group(&self, index: u32) -> DispatchBindGroupLayout {
let entries = self.groups.get(index as usize).unwrap_or_else(|| panic!("no bind group {index} in the pipeline's layout")).clone();
DispatchBindGroupLayout::custom(BindGroupLayout { entries })
}
}
#[derive(Debug)]
pub(crate) struct BindGroup {
pub(super) raw: Arc<GroupRaw>,
}
#[derive(Debug, Default)]
pub(crate) struct GroupRaw {
pub(super) stages: [StageBinds; 3],
/// Storage buffers' bound lengths by binding, which the sizes buffer reports.
pub(super) sizes: Vec<(u32, u32)>,
/// Owners of the textures it binds that this backend didn't make.
#[allow(dead_code, reason = "held, never read")]
owners: Vec<super::Owner>,
#[allow(dead_code, reason = "held, never read")]
live: Option<Live>,
}
#[derive(Debug, Default)]
pub(super) struct StageBinds {
pub(super) buffers: Vec<BufferBind>,
pub(super) textures: Vec<(u8, Obj<dyn MTLTexture>)>,
pub(super) samplers: Vec<(u8, Obj<dyn MTLSamplerState>)>,
}
#[derive(Debug)]
pub(super) struct BufferBind {
pub(super) slot: u8,
/// Resolved to its current storage when the group is applied.
pub(super) store: Arc<Store>,
pub(super) offset: u64,
/// Its index among the group's dynamic offsets.
pub(super) dynamic: Option<usize>,
}
send_sync!(GroupRaw);
/// The bind target an entry takes in a stage, counting its slot.
fn target(ty: &wgpu::BindingType, counts: &mut Counts) -> msl::BindTarget {
let mut target = msl::BindTarget::default();
match *ty {
wgpu::BindingType::Buffer { ty, .. } => {
target.buffer = Some(counts.buffers);
target.mutable = matches!(ty, wgpu::BufferBindingType::Storage { read_only: false });
counts.buffers += 1;
}
wgpu::BindingType::Sampler(_) => {
target.sampler = Some(msl::BindSamplerTarget::Resource(counts.samplers));
counts.samplers += 1;
}
wgpu::BindingType::Texture { .. } => {
target.texture = Some(counts.textures);
counts.textures += 1;
}
wgpu::BindingType::StorageTexture { access, .. } => {
target.texture = Some(counts.textures);
target.mutable = access != wgpu::StorageTextureAccess::ReadOnly;
counts.textures += 1;
}
ref other => super::unsupported!("binding {other:?}"),
}
target
}
impl BindGroupLayout {
pub(crate) fn new(desc: &wgpu::BindGroupLayoutDescriptor<'_>) -> Self {
let mut entries = desc.entries.to_vec();
entries.sort_by_key(|e| e.binding);
if entries.iter().any(|e| e.count.is_some()) { super::unsupported!("binding arrays") }
BindGroupLayout { entries: entries.into() }
}
}
impl BindGroupLayoutInterface for BindGroupLayout {}
impl PipelineLayout {
pub(crate) fn new(desc: &wgpu::PipelineLayoutDescriptor<'_>) -> Self {
let groups: Vec<_> = desc.bind_group_layouts.iter()
.map(|layout| layout.map(|l| l.as_custom::<BindGroupLayout>().expect("a Metal bind group layout")))
.collect();
Self::from_groups(&groups, desc.immediate_size)
}
pub(super) fn from_groups(groups: &[Option<&BindGroupLayout>], immediate_size: u32) -> Self {
let mut counts = [Counts::default(); 3];
let mut stages: [msl::EntryPointResources; 3] = Default::default();
let mut storage = [false; 3];
if immediate_size > 0 {
for (s, resources) in stages.iter_mut().enumerate() {
resources.immediates_buffer = Some(counts[s].buffers);
counts[s].buffers += 1;
}
}
let mut bases = Vec::new();
let mut entries = Vec::new();
for (group, layout) in groups.iter().enumerate() {
bases.push(counts);
entries.push(layout.map_or_else(|| Arc::from([]), |l| l.entries.clone()));
let Some(layout) = layout else { continue };
for entry in layout.entries.iter() {
let binding = naga::ResourceBinding { group: group as u32, binding: entry.binding };
for (s, stage) in STAGES.iter().enumerate() {
if !entry.visibility.contains(*stage) { continue }
storage[s] |= matches!(entry.ty, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { .. }, .. });
stages[s].resources.insert(binding, target(&entry.ty, &mut counts[s]));
}
}
}
for s in 0..3 {
if storage[s] { stages[s].sizes_buffer = Some(counts[s].buffers); }
}
PipelineLayout { raw: Arc::new(LayoutRaw { bases, stages, immediates: immediate_size, groups: entries }) }
}
}
impl PipelineLayoutInterface for PipelineLayout {}
impl BindGroup {
pub(crate) fn new(desc: &wgpu::BindGroupDescriptor<'_>, live: Live) -> Self {
let layout = desc.layout.as_custom::<BindGroupLayout>().expect("a Metal bind group layout");
let mut group = GroupRaw { live: Some(live), ..GroupRaw::default() };
let mut counts = [Counts::default(); 3];
let mut dynamic = 0;
for entry in layout.entries.iter() {
let resource = &desc.entries.iter().find(|e| e.binding == entry.binding).expect("a bind group entry for every layout entry").resource;
let dynamic_index = match entry.ty {
wgpu::BindingType::Buffer { has_dynamic_offset: true, .. } => { dynamic += 1; Some(dynamic - 1) }
_ => None,
};
if let (wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { .. }, .. }, wgpu::BindingResource::Buffer(b)) = (&entry.ty, resource) {
let size = b.size.map_or_else(|| b.buffer.size() - b.offset, |s| s.get());
group.sizes.push((entry.binding, u32::try_from(size).unwrap_or(u32::MAX)));
}
for (s, stage) in STAGES.iter().enumerate() {
if !entry.visibility.contains(*stage) { continue }
let slot = target(&entry.ty, &mut counts[s]);
let binds = &mut group.stages[s];
match resource {
wgpu::BindingResource::Buffer(b) => {
let store = b.buffer.as_custom::<MetalBuffer>().expect("a Metal buffer").store.clone();
if slot.mutable { store.gpu_write(); }
binds.buffers.push(BufferBind { slot: slot.buffer.unwrap(), store, offset: b.offset, dynamic: dynamic_index });
}
wgpu::BindingResource::TextureView(v) => {
let view = &v.as_custom::<MetalView>().expect("a Metal texture view").raw;
binds.textures.push((slot.texture.unwrap(), view.raw.clone()));
group.owners.extend(view.owner.clone());
}
wgpu::BindingResource::Sampler(sampler) => {
let Some(msl::BindSamplerTarget::Resource(at)) = slot.sampler else { unreachable!() };
binds.samplers.push((at, sampler.as_custom::<MetalSampler>().expect("a Metal sampler").raw.0.clone()));
}
other => super::unsupported!("bind group resource {other:?}"),
}
}
}
BindGroup { raw: Arc::new(group) }
}
}
impl BindGroupInterface for BindGroup {}
+243
View File
@@ -0,0 +1,243 @@
//! Rune's native Metal backend, macOS's default (research/34), through wgpu's
//! `custom` backend, so compositors and the frame loop keep calling wgpu types.
//!
//! Shaders stay WGSL: naga translates each pipeline's entry points to MSL with the pipeline
//! layout's slots, as wgpu-hal does, minus its vertex pulling (vertex inputs use a vertex
//! descriptor). The uber shader instead loads `uber_native.metallib`, that MSL precompiled, and
//! Rune's other pipelines take theirs from `builtin_native.metallib` (`builtin`). Buffers are
//! `MTLStorageModeShared`; textures are private.
//!
//! A command encoder records one `MTLCommandBuffer` with unretained references: everything it
//! uses is kept alive until the queue's `MTLSharedEvent` reaches that buffer's value. A submit
//! that drew into a drawable holds its buffer, and `Queue::present` presents the drawable on it
//! and commits it, so a frame is one command buffer.
//!
//! The CPU writes buffers in place (`store`): `Staging` and `Frame::write_buffer` writes always,
//! swapping in a spare storage while the GPU still reads the current one, and
//! `Queue::write_buffer` when no recorded command uses the buffer. Writes to buffers the GPU
//! writes, and `write_texture`, stage through a blit buffer committed ahead of the next submit,
//! as wgpu orders them. Map and work-done callbacks run from `Device::poll` and `Queue::submit`
//! once their work has finished.
//!
//! Rune's layer tweaks (materials, present timing, transactions, occlusion) reach this backend's
//! CAMetalLayer through `gpu::with_layer`. Video planes from CoreVideo wrap as textures
//! (`texture_from_raw`) whose owner the bind groups and command buffers using them keep.
//! Compute passes, timestamps at pass boundaries (`TIMESTAMP_QUERY`), and immediates
//! (`IMMEDIATES`, set as inline vertex and fragment bytes, up to Metal's 4 KB) are as wgpu-hal's.
//! New textures read as zero, as wgpu promises. A pipeline without a layout derives one from
//! its shaders, as wgpu-core does (`derive`). Other queries, render bundles, indirect commands,
//! depth and multisampling are not implemented: they panic naming the way back to wgpu
//! (`unsupported!`).
#[doc(hidden)]
pub mod bench;
mod builtin;
mod compute;
#[cfg(test)]
mod compute_tests;
mod derive;
#[cfg(test)]
mod derive_tests;
mod device;
mod encode;
mod layout;
mod pass;
mod pipeline;
mod query;
mod resource;
mod shader;
#[cfg(test)]
mod shader_tests;
mod store;
#[cfg(test)]
mod store_tests;
mod submit;
mod surface;
#[cfg(test)]
mod tests;
use std::future::ready;
use std::pin::Pin;
use objc2_metal::{MTLCopyAllDevices, MTLDevice};
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use wgpu::custom::*;
pub(crate) use device::{MetalDevice, Shared};
pub type Obj<P> = Retained<ProtocolObject<P>>;
/// Keeps memory a texture made outside this backend reads valid, as long as the texture, its
/// views, bind groups using them, or a command buffer using those is alive.
pub type Owner = std::sync::Arc<dyn std::any::Any + Send + Sync>;
/// The Metal device under `device`, when it's this backend's.
pub fn raw_device(device: &wgpu::Device) -> Option<&ProtocolObject<dyn MTLDevice>> {
device.as_custom::<MetalDevice>().map(|d| &*d.shared.device)
}
/// A texture over `raw`, made on `raw_device`'s device and matching `desc`, which `owner` keeps valid.
pub fn texture_from_raw(raw: Obj<dyn objc2_metal::MTLTexture>, desc: &wgpu::TextureDescriptor<'_>, owner: Owner) -> wgpu::Texture {
wgpu::Texture::from_custom(resource::MetalTexture::from_raw(raw, desc, owner), desc)
}
/// Whether `module`, made on this backend, can make pipelines from all its entry points: false
/// for a precompiled library Metal refused or that lacks one of them.
pub fn module_ready(module: &wgpu::ShaderModule) -> bool {
module.as_custom::<shader::ShaderModule>().is_some_and(shader::ShaderModule::ready)
}
/// The MSL this backend compiles `wgsl`'s `vs` and `fs` to, in MSL `lang`, for a render
/// pipeline whose one bind group has `entries`.
#[doc(hidden)]
pub fn render_msl(wgsl: &str, entries: &[wgpu::BindGroupLayoutEntry], lang: (u8, u8)) -> [String; 2] {
let ir = shader::Ir::parse("render_msl", wgsl, wgpu::ShaderRuntimeChecks::checked());
let group = layout::BindGroupLayout::new(&wgpu::BindGroupLayoutDescriptor { label: None, entries });
let layout = layout::PipelineLayout::from_groups(&[Some(&group)], 0);
[(wgpu::naga::ShaderStage::Vertex, "vs", 0), (wgpu::naga::ShaderStage::Fragment, "fs", 1)].map(|(kind, entry, s)| {
let point = shader::Point { kind, entry: Some(entry), constants: &[] };
shader::translate(&ir, &point, &layout.raw.stages[s], false, lang).unwrap_or_else(|e| panic!("{e}")).source
})
}
/// How many pipelines compiled at runtime because the precompiled library lacked them.
#[doc(hidden)]
pub fn builtin_misses() -> usize { builtin::misses() }
/// The wgpu features this backend can offer: a compositor that wants others draws with wgpu
/// unless the app or `RUNE_GPU_BACKEND` asked for this backend (`backend::wgpu_for`).
pub(crate) const FEATURES: wgpu::Features = wgpu::Features::TIMESTAMP_QUERY.union(wgpu::Features::IMMEDIATES);
/// The most immediate data a pipeline takes: what `setVertexBytes` and `setFragmentBytes` copy.
const MAX_IMMEDIATE_SIZE: u32 = 4096;
/// Whether `adapter` is this backend's.
pub(crate) fn owns_adapter(adapter: &wgpu::Adapter) -> bool { adapter.as_custom::<MetalAdapter>().is_some() }
/// Whether this backend draws: the default, unless `App::gpu_backend` or `RUNE_GPU_BACKEND`
/// picks wgpu.
pub fn enabled() -> bool {
crate::backend::current() == crate::GpuBackend::Metal
}
pub fn instance() -> wgpu::Instance {
rune_staging::set_direct(write_in_place);
wgpu::Instance::from_custom(MetalInstance)
}
/// Whether `queue` is this backend's.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn owns(queue: &wgpu::Queue) -> bool { queue.as_custom::<submit::MetalQueue>().is_some() }
/// Staging's in-place writer: a Metal buffer the GPU only reads takes writes into its storage.
fn write_in_place(buffer: &wgpu::Buffer, offset: u64, data: &[u8]) -> bool {
buffer.as_custom::<resource::MetalBuffer>().is_some_and(|b| b.store.write_ahead(&b.shared, offset, data, || true))
}
/// The CAMetalLayer a surface of this backend presents into.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn layer<'s>(surface: &'s wgpu::Surface<'_>) -> Option<&'s objc2::runtime::AnyObject> {
surface.as_custom::<surface::MetalSurface>().map(|s| -> &objc2::runtime::AnyObject { s.layer() })
}
macro_rules! send_sync {
($($t:ty),*) => { $(
// SAFETY: Metal devices, queues, resources and events are thread-safe; command buffers,
// encoders and drawables are used by one thread at a time, as wgpu's handles are.
#[allow(unsafe_code)]
unsafe impl Send for $t {}
// SAFETY: as above; shared Metal objects are thread-safe and single-thread handles follow wgpu's contract.
#[allow(unsafe_code)]
unsafe impl Sync for $t {}
)* };
}
pub(crate) use send_sync;
/// Panics for a wgpu feature this backend doesn't implement, naming the way back to wgpu.
macro_rules! unsupported {
($($what:tt)*) => {
panic!("Rune's Metal backend doesn't support {}; draw with wgpu instead: App::gpu_backend(GpuBackend::Wgpu) or RUNE_GPU_BACKEND=wgpu", format_args!($($what)*))
};
}
pub(crate) use unsupported;
#[derive(Debug)]
struct MetalInstance;
impl InstanceInterface for MetalInstance {
fn new(_: wgpu::InstanceDescriptor) -> Self { MetalInstance }
#[allow(unsafe_code)]
unsafe fn create_surface(&self, target: wgpu::SurfaceTargetUnsafe) -> Result<DispatchSurface, wgpu::CreateSurfaceError> {
// SAFETY: caller upholds `InstanceInterface::create_surface`'s contract that `target` names a live layer or view.
Ok(unsafe { surface::create(target) })
}
fn request_adapter(&self, options: &wgpu::RequestAdapterOptions<'_, '_>) -> Pin<Box<dyn RequestAdapterFuture>> {
let device = preferred(devices(), options.power_preference).expect("Rune's Metal backend needs a Metal device");
Box::pin(ready(Ok(DispatchAdapter::custom(MetalAdapter { device }))))
}
fn poll_all_devices(&self, _: bool) -> bool { true }
fn wgsl_language_features(&self) -> wgpu::WgslLanguageFeatures { wgpu::WgslLanguageFeatures::empty() }
fn enumerate_adapters(&self, _: wgpu::Backends) -> Pin<Box<dyn EnumerateAdapterFuture>> {
Box::pin(ready(devices().into_iter().map(|device| DispatchAdapter::custom(MetalAdapter { device })).collect()))
}
}
#[derive(Debug)]
struct MetalAdapter {
device: Obj<dyn MTLDevice>,
}
send_sync!(MetalAdapter);
/// The Mac's GPUs, as wgpu-hal lists them. Not `MTLCreateSystemDefaultDevice`: to find the main
/// display's GPU it connects to the window server, which costs a fresh process about 8 ms more
/// (14 ms instead of 5.5 on an M-series Mac), on every headless run and on a launch's prewarm.
fn devices() -> Vec<Obj<dyn MTLDevice>> {
MTLCopyAllDevices().to_vec()
}
/// The first integrated GPU, or for `HighPerformance` the first discrete one, else the first: the
/// order wgpu ranks adapters in.
fn preferred(devices: Vec<Obj<dyn MTLDevice>>, power: wgpu::PowerPreference) -> Option<Obj<dyn MTLDevice>> {
let integrated = power != wgpu::PowerPreference::HighPerformance;
let at = devices.iter().position(|d| d.hasUnifiedMemory() == integrated).unwrap_or(0);
devices.into_iter().nth(at)
}
fn info(device: &ProtocolObject<dyn MTLDevice>) -> wgpu::AdapterInfo {
let kind = if device.hasUnifiedMemory() { wgpu::DeviceType::IntegratedGpu } else { wgpu::DeviceType::DiscreteGpu };
let mut info = wgpu::AdapterInfo::new(kind, wgpu::Backend::Metal);
info.name = device.name().to_string();
info.driver = "rune metal".into();
info
}
/// What a Metal GPU of the Apple or Mac 2 families can do, in wgpu's terms.
fn limits() -> wgpu::Limits {
wgpu::Limits {
max_texture_dimension_1d: 16384, max_texture_dimension_2d: 16384, max_buffer_size: 1 << 30, max_immediate_size: MAX_IMMEDIATE_SIZE,
..wgpu::Limits::default()
}
}
impl AdapterInterface for MetalAdapter {
fn request_device(&self, desc: &wgpu::DeviceDescriptor<'_>) -> Pin<Box<dyn RequestDeviceFuture>> {
let (device, queue) = device::new(self.device.clone(), desc);
Box::pin(ready(Ok((DispatchDevice::custom(device), DispatchQueue::custom(queue)))))
}
fn is_surface_supported(&self, _: &DispatchSurface) -> bool { true }
fn features(&self) -> wgpu::Features {
if query::supported(&self.device) { FEATURES } else { FEATURES - wgpu::Features::TIMESTAMP_QUERY }
}
fn limits(&self) -> wgpu::Limits { limits() }
fn downlevel_capabilities(&self) -> wgpu::DownlevelCapabilities { Default::default() }
fn get_info(&self) -> wgpu::AdapterInfo { info(&self.device) }
fn get_texture_format_features(&self, format: wgpu::TextureFormat) -> wgpu::TextureFormatFeatures {
use wgpu::TextureFormatFeatureFlags as F;
let float = format.sample_type(None, None).is_some_and(|t| matches!(t, wgpu::TextureSampleType::Float { .. }));
let flags = if float { F::FILTERABLE | F::BLENDABLE } else { F::empty() };
wgpu::TextureFormatFeatures { allowed_usages: wgpu::TextureUsages::all(), flags }
}
fn get_presentation_timestamp(&self) -> wgpu::PresentationTimestamp { wgpu::PresentationTimestamp(0) }
fn cooperative_matrix_properties(&self) -> Vec<wgpu::wgt::CooperativeMatrixProperties> { Vec::new() }
}
+326
View File
@@ -0,0 +1,326 @@
//! Render passes. Bind groups are applied at the next draw, against the pipeline bound then, so
//! groups set before their pipeline land at the right slots; a pipeline with another layout
//! rebinds every group. The sizes buffer and immediates travel as inline bytes.
#![allow(unsafe_code)]
use std::ops::Range;
use std::ptr::NonNull;
use std::sync::Arc;
use std::sync::atomic::Ordering;
#[cfg(debug_assertions)]
use objc2_foundation::NSString;
use objc2_metal::{
MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCounterDontSample, MTLIndexType, MTLLoadAction, MTLRenderCommandEncoder, MTLRenderPassDescriptor,
MTLScissorRect, MTLStoreAction, MTLViewport,
};
use objc2::rc::autoreleasepool;
use parking_lot::Mutex;
use wgpu::custom::*;
use super::encode::Rec;
use super::layout::{Counts, GroupRaw};
use super::pipeline::{PipelineRaw, RenderPipeline, vertex_slot};
use super::query::{self, QuerySet};
use super::resource::{BufferRaw, MetalBuffer, MetalView};
use super::store::{SWAPS, Store};
use super::submit::Keep;
use super::{Obj, send_sync};
const GROUPS: usize = 8;
#[derive(Debug)]
pub(crate) struct MetalPass {
rec: Arc<Mutex<Rec>>,
raw: Obj<dyn MTLRenderCommandEncoder>,
keep: Keep,
pipeline: Option<Arc<PipelineRaw>>,
groups: [Option<(Arc<GroupRaw>, Vec<u32>)>; GROUPS],
/// Groups to apply at the next draw, a bit each.
dirty: u32,
sizes_dirty: bool,
immediates: Vec<u8>,
immediates_dirty: bool,
index: Option<(Arc<Store>, Arc<BufferRaw>, u64, MTLIndexType, u64)>,
vertex: Vec<(u32, Arc<Store>, u64)>,
/// `SWAPS` when buffers were last bound: a swap since may have moved a bound buffer.
swaps: u64,
}
send_sync!(MetalPass);
fn view(view: &wgpu::TextureView) -> &MetalView { view.as_custom::<MetalView>().expect("a Metal texture view") }
impl MetalPass {
pub(super) fn begin(rec: Arc<Mutex<Rec>>, desc: &wgpu::RenderPassDescriptor<'_>) -> Self {
if desc.depth_stencil_attachment.is_some() { super::unsupported!("depth and stencil") }
if desc.color_attachments.len() > 4 { super::unsupported!("more than four color attachments") }
let d = MTLRenderPassDescriptor::new();
let mut keep = rec.lock().shared().keep_list();
let mut drawable = false;
if let Some(ts) = &desc.timestamp_writes {
let set = ts.query_set.as_custom::<QuerySet>().expect("a Metal query set").raw.clone();
// SAFETY: attachment 0 exists on every descriptor; the indices are within the query set, as wgpu validated.
unsafe {
let attachment = d.sampleBufferAttachments().objectAtIndexedSubscript(0);
attachment.setSampleBuffer(Some(&set.0));
attachment.setStartOfVertexSampleIndex(query::index(ts.beginning_of_pass_write_index));
attachment.setEndOfVertexSampleIndex(MTLCounterDontSample);
attachment.setStartOfFragmentSampleIndex(MTLCounterDontSample);
attachment.setEndOfFragmentSampleIndex(query::index(ts.end_of_pass_write_index));
}
keep.push(set);
}
for (i, attachment) in desc.color_attachments.iter().enumerate() {
let Some(attachment) = attachment else { continue };
if attachment.resolve_target.is_some() { super::unsupported!("multisample resolves") }
let target = view(attachment.view).raw.clone();
// SAFETY: at most four attachments, checked above.
let color = unsafe { d.colorAttachments().objectAtIndexedSubscript(i) };
color.setTexture(Some(&target.raw));
if let Some(slice) = attachment.depth_slice { color.setDepthPlane(slice as usize); }
match attachment.ops.load {
wgpu::LoadOp::Clear(c) => {
color.setLoadAction(MTLLoadAction::Clear);
color.setClearColor(MTLClearColor { red: c.r, green: c.g, blue: c.b, alpha: c.a });
}
wgpu::LoadOp::Load => color.setLoadAction(MTLLoadAction::Load),
wgpu::LoadOp::DontCare(_) => color.setLoadAction(MTLLoadAction::DontCare),
}
color.setStoreAction(match attachment.ops.store {
wgpu::StoreOp::Store => MTLStoreAction::Store,
wgpu::StoreOp::Discard => MTLStoreAction::DontCare,
});
drawable |= target.drawable;
keep.push(target);
}
let raw = {
let mut rec = rec.lock();
rec.drawable |= drawable;
let cb = rec.pass_buffer();
autoreleasepool(|_| cb.renderCommandEncoderWithDescriptor(&d)).expect("a Metal render encoder")
};
#[cfg(debug_assertions)]
{
let label = desc.label.unwrap_or("rune metal render pass");
raw.setLabel(Some(&NSString::from_str(label)));
}
MetalPass {
rec, raw, keep, pipeline: None, groups: Default::default(), dirty: 0, sizes_dirty: false,
immediates: Vec::new(), immediates_dirty: false, index: None, vertex: Vec::new(), swaps: SWAPS.load(Ordering::Relaxed),
}
}
/// Rebinds bound buffers whose storage a write swapped since they were bound.
fn rebind(&mut self) {
let swaps = SWAPS.load(Ordering::Relaxed);
if swaps == self.swaps { return }
self.swaps = swaps;
self.dirty = self.groups.iter().enumerate().filter(|(_, g)| g.is_some()).fold(0, |m, (i, _)| m | 1 << i);
for (slot, store, offset) in &self.vertex {
let raw = store.current();
// SAFETY: as in `set_vertex_buffer`.
unsafe { self.raw.setVertexBuffer_offset_atIndex(Some(&raw.raw), *offset as usize, vertex_slot(*slot)) };
self.keep.push(raw);
}
if let Some((store, raw, ..)) = &mut self.index {
*raw = store.current();
self.keep.push(raw.clone());
}
}
/// Applies what changed since the last draw against the bound pipeline.
fn flush(&mut self) {
self.rebind();
let Some(pipeline) = &self.pipeline else { return };
let layout = &pipeline.layout;
while self.dirty != 0 {
let index = self.dirty.trailing_zeros() as usize;
self.dirty &= self.dirty - 1;
let (Some((group, offsets)), Some(bases)) = (&self.groups[index], layout.bases.get(index)) else { continue };
apply(&self.raw, group, offsets, bases, &mut self.keep);
self.sizes_dirty = true;
}
if std::mem::take(&mut self.sizes_dirty) {
for (s, sized) in pipeline.sized.iter().enumerate() {
let Some(slot) = layout.stages[s].sizes_buffer else { continue };
if sized.is_empty() { continue }
let sizes: Vec<u32> = sized.iter().map(|b| {
let group = self.groups.get(b.group as usize).and_then(Option::as_ref);
group.and_then(|(g, _)| g.sizes.iter().find(|(at, _)| *at == b.binding)).map_or(0, |&(_, size)| size)
}).collect();
bytes(&self.raw, s, &sizes, slot);
}
}
if std::mem::take(&mut self.immediates_dirty) && !self.immediates.is_empty() {
for s in 0..2 {
if let Some(slot) = layout.stages[s].immediates_buffer { bytes(&self.raw, s, &self.immediates, slot); }
}
}
}
}
/// Sets `data` inline at buffer `slot` of stage `s` (0 vertex, 1 fragment).
fn bytes<T: Copy>(raw: &Obj<dyn MTLRenderCommandEncoder>, s: usize, data: &[T], slot: u8) {
let ptr = NonNull::from(data).cast();
let len = std::mem::size_of_val(data);
// SAFETY: Metal copies `len` bytes from `ptr` before returning.
unsafe {
if s == 0 { raw.setVertexBytes_length_atIndex(ptr, len, slot as usize) } else { raw.setFragmentBytes_length_atIndex(ptr, len, slot as usize) }
}
}
fn apply(raw: &Obj<dyn MTLRenderCommandEncoder>, group: &GroupRaw, offsets: &[u32], bases: &[Counts; 3], keep: &mut Keep) {
for (s, binds) in group.stages[..2].iter().enumerate() {
let base = bases[s];
// SAFETY: slots come from the pipeline layout the shaders were compiled against, and the
// resources stay alive in the pass's keep list.
unsafe {
for b in &binds.buffers {
let offset = (b.offset + b.dynamic.map_or(0, |i| u64::from(offsets[i]))) as usize;
let at = usize::from(base.buffers + b.slot);
let buffer = b.store.current();
if s == 0 { raw.setVertexBuffer_offset_atIndex(Some(&buffer.raw), offset, at) } else { raw.setFragmentBuffer_offset_atIndex(Some(&buffer.raw), offset, at) }
keep.push(buffer);
}
for (slot, texture) in &binds.textures {
let at = usize::from(base.textures + slot);
if s == 0 { raw.setVertexTexture_atIndex(Some(texture), at) } else { raw.setFragmentTexture_atIndex(Some(texture), at) }
}
for (slot, sampler) in &binds.samplers {
let at = usize::from(base.samplers + slot);
if s == 0 { raw.setVertexSamplerState_atIndex(Some(sampler), at) } else { raw.setFragmentSamplerState_atIndex(Some(sampler), at) }
}
}
}
}
impl Drop for MetalPass {
fn drop(&mut self) {
self.raw.endEncoding();
let mut rec = self.rec.lock();
rec.keep.append(&mut self.keep);
rec.shared().recycle(std::mem::take(&mut self.keep));
}
}
impl RenderPassInterface for MetalPass {
fn set_pipeline(&mut self, pipeline: &DispatchRenderPipeline) {
let next = &pipeline.as_custom::<RenderPipeline>().expect("a Metal render pipeline").raw;
if self.pipeline.as_ref().is_some_and(|p| Arc::ptr_eq(p, next)) { return }
let relayout = self.pipeline.as_ref().is_none_or(|p| !Arc::ptr_eq(&p.layout, &next.layout));
self.raw.setRenderPipelineState(&next.state);
self.raw.setCullMode(next.cull);
self.raw.setFrontFacingWinding(next.winding);
self.raw.setTriangleFillMode(next.fill);
if relayout {
self.dirty = self.groups.iter().enumerate().filter(|(_, g)| g.is_some()).fold(0, |m, (i, _)| m | 1 << i);
// Zeroed for a new layout, as wgpu-core does.
self.immediates.clear();
self.immediates.resize(next.layout.immediates as usize, 0);
self.immediates_dirty = true;
}
self.sizes_dirty = true;
self.keep.push(next.clone());
self.pipeline = Some(next.clone());
}
fn set_bind_group(&mut self, index: u32, group: Option<&DispatchBindGroup>, offsets: &[wgpu::DynamicOffset]) {
let index = index as usize;
if index >= GROUPS { super::unsupported!("bind group {index}") }
let Some(group) = group else { self.groups[index] = None; return };
let group = &group.as_custom::<super::layout::BindGroup>().expect("a Metal bind group").raw;
if let Some((bound, bound_offsets)) = &self.groups[index]
&& Arc::ptr_eq(bound, group) && bound_offsets[..] == *offsets { return }
self.keep.push(group.clone());
self.groups[index] = Some((group.clone(), offsets.to_vec()));
self.dirty |= 1 << index;
}
fn set_index_buffer(&mut self, buffer: &DispatchBuffer, format: wgpu::IndexFormat, offset: wgpu::BufferAddress, _: Option<wgpu::BufferSize>) {
let store = buffer.as_custom::<MetalBuffer>().expect("a Metal buffer").store.clone();
let raw = store.current();
let (kind, stride) = match format {
wgpu::IndexFormat::Uint16 => (MTLIndexType::UInt16, 2),
wgpu::IndexFormat::Uint32 => (MTLIndexType::UInt32, 4),
};
self.keep.push(raw.clone());
self.index = Some((store, raw, offset, kind, stride));
}
fn set_vertex_buffer(&mut self, slot: u32, buffer: Option<&DispatchBuffer>, offset: wgpu::BufferAddress, _: Option<wgpu::BufferSize>) {
let store = buffer.map(|b| b.as_custom::<MetalBuffer>().expect("a Metal buffer").store.clone());
let raw = store.as_ref().map(|s| s.current());
// SAFETY: the slot is one the pipeline's vertex descriptor reads; the buffer stays alive
// in the keep list.
unsafe { self.raw.setVertexBuffer_offset_atIndex(raw.as_ref().map(|b| &*b.raw), offset as usize, vertex_slot(slot)) };
if let Some(raw) = raw { self.keep.push(raw); }
self.vertex.retain(|(at, ..)| *at != slot);
if let Some(store) = store { self.vertex.push((slot, store, offset)); }
}
fn set_immediates(&mut self, offset: u32, data: &[u8]) {
let at = offset as usize;
if self.immediates.len() < at + data.len() { self.immediates.resize(at + data.len(), 0); }
self.immediates[at..at + data.len()].copy_from_slice(data);
self.immediates_dirty = true;
}
fn set_blend_constant(&mut self, c: wgpu::Color) {
self.raw.setBlendColorRed_green_blue_alpha(c.r as f32, c.g as f32, c.b as f32, c.a as f32);
}
fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32) {
self.raw.setScissorRect(MTLScissorRect { x: x as usize, y: y as usize, width: width as usize, height: height as usize });
}
fn set_viewport(&mut self, x: f32, y: f32, width: f32, height: f32, min_depth: f32, max_depth: f32) {
self.raw.setViewport(MTLViewport {
originX: x.into(), originY: y.into(), width: width.into(), height: height.into(), znear: min_depth.into(), zfar: max_depth.into(),
});
}
fn set_stencil_reference(&mut self, reference: u32) { self.raw.setStencilReferenceValue(reference); }
fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
if vertices.is_empty() || instances.is_empty() { return }
self.flush();
let Some(pipeline) = &self.pipeline else { return };
// SAFETY: wgpu validated the draw against the bound pipeline and buffers.
unsafe {
self.raw.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance(pipeline.primitive, vertices.start as usize,
vertices.len(), instances.len(), instances.start as usize)
}
}
fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
if indices.is_empty() || instances.is_empty() { return }
self.flush();
let (Some(pipeline), Some((_, buffer, offset, kind, stride))) = (&self.pipeline, &self.index) else { return };
// SAFETY: wgpu validated the draw against the bound pipeline and buffers.
unsafe {
self.raw.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance(
pipeline.primitive, indices.len(), *kind, &buffer.raw, (offset + u64::from(indices.start) * stride) as usize,
instances.len(), base_vertex as isize, instances.start as usize)
}
}
fn draw_mesh_tasks(&mut self, _: u32, _: u32, _: u32) { super::unsupported!("mesh shaders") }
fn draw_indirect(&mut self, _: &DispatchBuffer, _: wgpu::BufferAddress) { super::unsupported!("indirect draws") }
fn draw_indexed_indirect(&mut self, _: &DispatchBuffer, _: wgpu::BufferAddress) { super::unsupported!("indirect draws") }
fn draw_mesh_tasks_indirect(&mut self, _: &DispatchBuffer, _: wgpu::BufferAddress) { super::unsupported!("mesh shaders") }
fn multi_draw_indirect(&mut self, _: &DispatchBuffer, _: wgpu::BufferAddress, _: u32) { super::unsupported!("indirect draws") }
fn multi_draw_indexed_indirect(&mut self, _: &DispatchBuffer, _: wgpu::BufferAddress, _: u32) {
super::unsupported!("indirect draws")
}
fn multi_draw_indirect_count(&mut self, _: &DispatchBuffer, _: wgpu::BufferAddress, _: &DispatchBuffer, _: wgpu::BufferAddress, _: u32) {
super::unsupported!("indirect draws")
}
fn multi_draw_mesh_tasks_indirect(&mut self, _: &DispatchBuffer, _: wgpu::BufferAddress, _: u32) {
super::unsupported!("mesh shaders")
}
fn multi_draw_indexed_indirect_count(&mut self, _: &DispatchBuffer, _: wgpu::BufferAddress, _: &DispatchBuffer, _: wgpu::BufferAddress, _: u32) {
super::unsupported!("indirect draws")
}
fn multi_draw_mesh_tasks_indirect_count(&mut self, _: &DispatchBuffer, _: wgpu::BufferAddress, _: &DispatchBuffer, _: wgpu::BufferAddress, _: u32) {
super::unsupported!("mesh shaders")
}
fn insert_debug_marker(&mut self, _: &str) {}
fn push_debug_group(&mut self, _: &str) {}
fn pop_debug_group(&mut self) {}
fn write_timestamp(&mut self, _: &DispatchQuerySet, _: u32) { super::unsupported!("timestamps") }
fn begin_occlusion_query(&mut self, _: u32) { super::unsupported!("occlusion queries") }
fn end_occlusion_query(&mut self) { super::unsupported!("occlusion queries") }
fn begin_pipeline_statistics_query(&mut self, _: &DispatchQuerySet, _: u32) { super::unsupported!("query sets") }
fn end_pipeline_statistics_query(&mut self) { super::unsupported!("query sets") }
fn execute_bundles(&mut self, _: &mut dyn Iterator<Item = &DispatchRenderBundle>) { super::unsupported!("render bundles") }
}
+242
View File
@@ -0,0 +1,242 @@
//! Render pipelines: each stage compiled against the layout, vertex buffers described at the
//! top buffer slots (vertex buffer `i` at 30 - i), and the color targets' formats and blending.
#![allow(unsafe_code)]
use std::sync::Arc;
#[cfg(debug_assertions)]
use objc2_foundation::NSString;
use objc2_metal::{
MTLBlendFactor, MTLBlendOperation, MTLColorWriteMask, MTLCullMode, MTLDevice, MTLPixelFormat, MTLPrimitiveTopologyClass,
MTLPrimitiveType, MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLTriangleFillMode, MTLVertexDescriptor, MTLVertexFormat,
MTLVertexStepFunction, MTLWinding,
};
use wgpu::custom::*;
use wgpu::naga;
use super::derive::{self, Use};
use super::layout::{LayoutRaw, PipelineLayout};
use super::resource::pixel_format;
use super::shader::{Stage, compile};
use super::{Obj, Shared, send_sync};
/// Metal's buffer slots per stage; vertex buffers count down from the last.
const MAX_BUFFERS: usize = 31;
#[derive(Debug)]
pub(crate) struct RenderPipeline {
pub(super) raw: Arc<PipelineRaw>,
}
#[derive(Debug)]
pub(crate) struct PipelineRaw {
pub(super) state: Obj<dyn MTLRenderPipelineState>,
pub(super) layout: Arc<LayoutRaw>,
pub(super) primitive: MTLPrimitiveType,
pub(super) cull: MTLCullMode,
pub(super) winding: MTLWinding,
pub(super) fill: MTLTriangleFillMode,
/// Per stage, the bindings whose lengths its sizes buffer holds.
pub(super) sized: [Vec<naga::ResourceBinding>; 2],
}
send_sync!(PipelineRaw);
pub(super) fn vertex_slot(index: u32) -> usize { MAX_BUFFERS - 1 - index as usize }
fn vertex_format(format: wgpu::VertexFormat) -> MTLVertexFormat {
use MTLVertexFormat as M;
use wgpu::VertexFormat as V;
match format {
V::Float32 => M::Float,
V::Float32x2 => M::Float2,
V::Float32x3 => M::Float3,
V::Float32x4 => M::Float4,
V::Uint32 => M::UInt,
V::Uint32x2 => M::UInt2,
V::Uint32x3 => M::UInt3,
V::Uint32x4 => M::UInt4,
V::Sint32 => M::Int,
V::Sint32x2 => M::Int2,
V::Sint32x3 => M::Int3,
V::Sint32x4 => M::Int4,
V::Float16x2 => M::Half2,
V::Float16x4 => M::Half4,
V::Unorm8x2 => M::UChar2Normalized,
V::Unorm8x4 => M::UChar4Normalized,
V::Uint8x2 => M::UChar2,
V::Uint8x4 => M::UChar4,
V::Unorm16x2 => M::UShort2Normalized,
V::Unorm16x4 => M::UShort4Normalized,
V::Uint16x2 => M::UShort2,
V::Uint16x4 => M::UShort4,
V::Snorm16x2 => M::Short2Normalized,
V::Snorm16x4 => M::Short4Normalized,
other => super::unsupported!("vertex format {other:?}"),
}
}
fn blend_factor(factor: wgpu::BlendFactor) -> MTLBlendFactor {
use MTLBlendFactor as M;
use wgpu::BlendFactor as B;
match factor {
B::Zero => M::Zero,
B::One => M::One,
B::Src => M::SourceColor,
B::OneMinusSrc => M::OneMinusSourceColor,
B::SrcAlpha => M::SourceAlpha,
B::OneMinusSrcAlpha => M::OneMinusSourceAlpha,
B::Dst => M::DestinationColor,
B::OneMinusDst => M::OneMinusDestinationColor,
B::DstAlpha => M::DestinationAlpha,
B::OneMinusDstAlpha => M::OneMinusDestinationAlpha,
B::SrcAlphaSaturated => M::SourceAlphaSaturated,
B::Constant => M::BlendColor,
B::OneMinusConstant => M::OneMinusBlendColor,
B::Src1 => M::Source1Color,
B::OneMinusSrc1 => M::OneMinusSource1Color,
B::Src1Alpha => M::Source1Alpha,
B::OneMinusSrc1Alpha => M::OneMinusSource1Alpha,
}
}
fn blend_operation(operation: wgpu::BlendOperation) -> MTLBlendOperation {
match operation {
wgpu::BlendOperation::Add => MTLBlendOperation::Add,
wgpu::BlendOperation::Subtract => MTLBlendOperation::Subtract,
wgpu::BlendOperation::ReverseSubtract => MTLBlendOperation::ReverseSubtract,
wgpu::BlendOperation::Min => MTLBlendOperation::Min,
wgpu::BlendOperation::Max => MTLBlendOperation::Max,
}
}
fn write_mask(writes: wgpu::ColorWrites) -> MTLColorWriteMask {
let mut mask = MTLColorWriteMask::None;
mask.set(MTLColorWriteMask::Red, writes.contains(wgpu::ColorWrites::RED));
mask.set(MTLColorWriteMask::Green, writes.contains(wgpu::ColorWrites::GREEN));
mask.set(MTLColorWriteMask::Blue, writes.contains(wgpu::ColorWrites::BLUE));
mask.set(MTLColorWriteMask::Alpha, writes.contains(wgpu::ColorWrites::ALPHA));
mask
}
fn topology(topology: wgpu::PrimitiveTopology) -> (MTLPrimitiveTopologyClass, MTLPrimitiveType) {
use wgpu::PrimitiveTopology as T;
match topology {
T::PointList => (MTLPrimitiveTopologyClass::Point, MTLPrimitiveType::Point),
T::LineList => (MTLPrimitiveTopologyClass::Line, MTLPrimitiveType::Line),
T::LineStrip => (MTLPrimitiveTopologyClass::Line, MTLPrimitiveType::LineStrip),
T::TriangleList => (MTLPrimitiveTopologyClass::Triangle, MTLPrimitiveType::Triangle),
T::TriangleStrip => (MTLPrimitiveTopologyClass::Triangle, MTLPrimitiveType::TriangleStrip),
}
}
fn vertex_descriptor(buffers: &[Option<wgpu::VertexBufferLayout<'_>>]) -> Option<objc2::rc::Retained<MTLVertexDescriptor>> {
if buffers.iter().all(Option::is_none) { return None }
let d = MTLVertexDescriptor::new();
for (i, vb) in buffers.iter().enumerate() {
let Some(vb) = vb else { continue };
let slot = vertex_slot(i as u32);
// SAFETY: slots and locations are within Metal's 31 buffers and attributes.
unsafe {
let layout = d.layouts().objectAtIndexedSubscript(slot);
if vb.array_stride == 0 {
let stride = vb.attributes.iter().map(|a| a.offset + a.format.size()).max().unwrap_or(0);
layout.setStride(stride.next_multiple_of(4) as usize);
layout.setStepFunction(MTLVertexStepFunction::Constant);
layout.setStepRate(0);
} else {
layout.setStride(vb.array_stride as usize);
layout.setStepFunction(match vb.step_mode {
wgpu::VertexStepMode::Vertex => MTLVertexStepFunction::PerVertex,
wgpu::VertexStepMode::Instance => MTLVertexStepFunction::PerInstance,
});
}
for a in vb.attributes {
let attribute = d.attributes().objectAtIndexedSubscript(a.shader_location as usize);
attribute.setFormat(vertex_format(a.format));
attribute.setBufferIndex(slot);
attribute.setOffset(a.offset as usize);
}
}
}
Some(d)
}
pub(super) fn create(shared: &Shared, desc: &wgpu::RenderPipelineDescriptor<'_>) -> RenderPipeline {
let label = desc.label.unwrap_or("pipeline");
let layout = match desc.layout {
Some(layout) => layout.as_custom::<PipelineLayout>().expect("a Metal pipeline layout").raw.clone(),
None => {
let vertex = Use { module: desc.vertex.module, entry: desc.vertex.entry_point, kind: naga::ShaderStage::Vertex };
let fragment = desc.fragment.as_ref().map(|f| Use { module: f.module, entry: f.entry_point, kind: naga::ShaderStage::Fragment });
derive::layout(label, &[Some(vertex), fragment].into_iter().flatten().collect::<Vec<_>>()).raw
}
};
if desc.depth_stencil.is_some() { super::unsupported!("depth and stencil") }
let (class, primitive) = topology(desc.primitive.topology);
let points = class == MTLPrimitiveTopologyClass::Point;
let d = MTLRenderPipelineDescriptor::new();
#[cfg(debug_assertions)]
if let Some(label) = desc.label { d.setLabel(Some(&NSString::from_str(label))); }
let vertex = Stage { module: desc.vertex.module, entry: desc.vertex.entry_point, constants: desc.vertex.compilation_options.constants,
kind: naga::ShaderStage::Vertex };
let vs = compile(shared, &vertex, &layout.stages[0], points).unwrap_or_else(|e| panic!("{label}: {e}"));
d.setVertexFunction(Some(&vs.function));
let mut sized = [vs.sized, Vec::new()];
if let Some(fragment) = &desc.fragment {
let stage = Stage { module: fragment.module, entry: fragment.entry_point, constants: fragment.compilation_options.constants,
kind: naga::ShaderStage::Fragment };
let fs = compile(shared, &stage, &layout.stages[1], points).unwrap_or_else(|e| panic!("{label}: {e}"));
d.setFragmentFunction(Some(&fs.function));
sized[1] = fs.sized;
if fragment.targets.len() > 4 { super::unsupported!("more than four color targets") }
for (i, target) in fragment.targets.iter().enumerate() {
// SAFETY: at most four attachments, checked above.
let attachment = unsafe { d.colorAttachments().objectAtIndexedSubscript(i) };
let Some(target) = target else { attachment.setPixelFormat(MTLPixelFormat::Invalid); continue };
attachment.setPixelFormat(pixel_format(target.format));
attachment.setWriteMask(write_mask(target.write_mask));
if let Some(blend) = target.blend {
attachment.setBlendingEnabled(true);
attachment.setRgbBlendOperation(blend_operation(blend.color.operation));
attachment.setSourceRGBBlendFactor(blend_factor(blend.color.src_factor));
attachment.setDestinationRGBBlendFactor(blend_factor(blend.color.dst_factor));
attachment.setAlphaBlendOperation(blend_operation(blend.alpha.operation));
attachment.setSourceAlphaBlendFactor(blend_factor(blend.alpha.src_factor));
attachment.setDestinationAlphaBlendFactor(blend_factor(blend.alpha.dst_factor));
}
}
}
d.setVertexDescriptor(vertex_descriptor(desc.vertex.buffers).as_deref());
// SAFETY: the class matches the primitive type every draw with this pipeline uses.
unsafe { d.setInputPrimitiveTopology(class) };
d.setRasterSampleCount(desc.multisample.count as usize);
d.setAlphaToCoverageEnabled(desc.multisample.alpha_to_coverage_enabled);
let state = shared.device.newRenderPipelineStateWithDescriptor_error(&d).unwrap_or_else(|e| panic!("{label}: {}", e.localizedDescription()));
let raw = PipelineRaw {
state,
layout,
primitive,
cull: match desc.primitive.cull_mode {
None => MTLCullMode::None,
Some(wgpu::Face::Front) => MTLCullMode::Front,
Some(wgpu::Face::Back) => MTLCullMode::Back,
},
winding: match desc.primitive.front_face {
wgpu::FrontFace::Cw => MTLWinding::Clockwise,
wgpu::FrontFace::Ccw => MTLWinding::CounterClockwise,
},
fill: match desc.primitive.polygon_mode {
wgpu::PolygonMode::Line => MTLTriangleFillMode::Lines,
_ => MTLTriangleFillMode::Fill,
},
sized,
};
RenderPipeline { raw: Arc::new(raw) }
}
impl RenderPipelineInterface for RenderPipeline {
fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout {
self.raw.layout.group(index)
}
}
+50
View File
@@ -0,0 +1,50 @@
//! Timestamp query sets: a counter sample buffer that passes sample into at their boundaries
//! and `resolve_query_set` resolves into a buffer, as wgpu-hal does.
#![allow(unsafe_code)]
use std::sync::Arc;
use objc2_foundation::NSString;
use objc2_metal::{
MTLCounterDontSample, MTLCounterSampleBuffer, MTLCounterSampleBufferDescriptor, MTLCounterSamplingPoint, MTLCounterSet, MTLDevice,
MTLStorageMode,
};
use wgpu::custom::*;
use super::{Obj, send_sync};
#[derive(Debug)]
pub(crate) struct QuerySet {
pub(super) raw: Arc<QueryRaw>,
}
#[derive(Debug)]
pub(crate) struct QueryRaw(pub(super) Obj<dyn MTLCounterSampleBuffer>);
send_sync!(QueryRaw);
/// Whether passes can sample timestamps at their boundaries.
pub(super) fn supported(device: &Obj<dyn MTLDevice>) -> bool { device.supportsCounterSampling(MTLCounterSamplingPoint::AtStageBoundary) }
impl QuerySet {
pub(super) fn new(device: &Obj<dyn MTLDevice>, desc: &wgpu::QuerySetDescriptor<'_>) -> Self {
if !matches!(desc.ty, wgpu::QueryType::Timestamp) { super::unsupported!("{:?} queries", desc.ty) }
let d = MTLCounterSampleBufferDescriptor::new();
d.setStorageMode(MTLStorageMode::Shared);
// SAFETY: wgpu limits a query set to 4096 queries, within Metal's sample buffer size.
unsafe { d.setSampleCount(desc.count.max(1) as usize) };
if let Some(label) = desc.label { d.setLabel(&NSString::from_str(label)); }
let sets = device.counterSets().expect("Metal counter sets");
let timestamp = sets.iter().find(|s| s.name().to_string() == "timestamp").expect("a Metal timestamp counter set");
d.setCounterSet(Some(&timestamp));
let raw = device.newCounterSampleBufferWithDescriptor_error(&d).unwrap_or_else(|e| panic!("a Metal counter sample buffer: {}", e.localizedDescription()));
QuerySet { raw: Arc::new(QueryRaw(raw)) }
}
}
impl QuerySetInterface for QuerySet {
fn destroy(&self) {}
}
/// A pass's timestamp indices as Metal takes them.
pub(super) fn index(at: Option<u32>) -> usize { at.map_or(MTLCounterDontSample, |i| i as usize) }
+404
View File
@@ -0,0 +1,404 @@
//! Buffers, textures, views and samplers.
#![allow(unsafe_code)]
use std::ops::Range;
use std::ptr::NonNull;
use std::sync::Arc;
use std::sync::atomic::{AtomicIsize, Ordering};
use objc2_foundation::NSRange;
#[cfg(debug_assertions)]
use objc2_foundation::NSString;
#[cfg(debug_assertions)]
use objc2_metal::MTLResource;
use objc2_metal::{
MTLBuffer, MTLCompareFunction, MTLDevice, MTLPixelFormat, MTLResourceOptions, MTLSamplerAddressMode, MTLSamplerBorderColor,
MTLSamplerDescriptor, MTLSamplerMinMagFilter, MTLSamplerMipFilter, MTLSamplerState, MTLStorageMode, MTLTexture, MTLTextureDescriptor,
MTLTextureType, MTLTextureUsage,
};
use wgpu::custom::*;
use super::store::Store;
use super::{Obj, Owner, Shared, send_sync};
pub(crate) fn pixel_format(format: wgpu::TextureFormat) -> MTLPixelFormat {
use MTLPixelFormat as M;
use wgpu::TextureFormat as F;
match format {
F::R8Unorm => M::R8Unorm,
F::R8Snorm => M::R8Snorm,
F::R8Uint => M::R8Uint,
F::R8Sint => M::R8Sint,
F::R16Unorm => M::R16Unorm,
F::R16Uint => M::R16Uint,
F::R16Sint => M::R16Sint,
F::R16Float => M::R16Float,
F::Rg8Unorm => M::RG8Unorm,
F::Rg8Snorm => M::RG8Snorm,
F::Rg8Uint => M::RG8Uint,
F::R32Uint => M::R32Uint,
F::R32Sint => M::R32Sint,
F::R32Float => M::R32Float,
F::Rg16Unorm => M::RG16Unorm,
F::Rg16Uint => M::RG16Uint,
F::Rg16Float => M::RG16Float,
F::Rgba8Unorm => M::RGBA8Unorm,
F::Rgba8UnormSrgb => M::RGBA8Unorm_sRGB,
F::Rgba8Snorm => M::RGBA8Snorm,
F::Rgba8Uint => M::RGBA8Uint,
F::Bgra8Unorm => M::BGRA8Unorm,
F::Bgra8UnormSrgb => M::BGRA8Unorm_sRGB,
F::Rgb10a2Unorm => M::RGB10A2Unorm,
F::Rg11b10Ufloat => M::RG11B10Float,
F::Rg32Uint => M::RG32Uint,
F::Rg32Float => M::RG32Float,
F::Rgba16Unorm => M::RGBA16Unorm,
F::Rgba16Uint => M::RGBA16Uint,
F::Rgba16Float => M::RGBA16Float,
F::Rgba32Uint => M::RGBA32Uint,
F::Rgba32Float => M::RGBA32Float,
F::Depth32Float => M::Depth32Float,
F::Depth16Unorm => M::Depth16Unorm,
other => super::unsupported!("texture format {other:?}"),
}
}
/// A buffer's storage, which its CPU pointer stays valid with.
#[derive(Debug)]
pub(crate) struct BufferRaw {
pub(super) raw: Obj<dyn MTLBuffer>,
contents: NonNull<u8>,
pub(super) size: u64,
live: Arc<AtomicIsize>,
}
#[derive(Debug)]
pub(crate) struct MetalBuffer {
pub(super) store: Arc<Store>,
pub(super) shared: Arc<Shared>,
}
#[derive(Debug)]
pub(crate) struct MappedRange {
at: NonNull<u8>,
len: usize,
}
#[derive(Debug)]
pub(crate) struct TextureRaw {
pub(super) raw: Obj<dyn MTLTexture>,
pub(super) format: wgpu::TextureFormat,
pub(super) dimension: wgpu::TextureDimension,
pub(super) layers: u32,
pub(super) mips: u32,
pub(super) drawable: bool,
/// What keeps a texture this backend didn't make valid (`texture_from_raw`).
owner: Option<Owner>,
#[allow(dead_code, reason = "held, never read")]
live: Option<Live>,
}
#[derive(Debug)]
pub(crate) struct MetalTexture {
pub(super) raw: Arc<TextureRaw>,
}
#[derive(Debug)]
pub(crate) struct ViewRaw {
pub(super) raw: Obj<dyn MTLTexture>,
pub(super) drawable: bool,
/// Its texture's owner, which bind groups and passes that use the view keep.
pub(super) owner: Option<Owner>,
}
#[derive(Debug)]
pub(crate) struct MetalView {
pub(super) raw: Arc<ViewRaw>,
}
#[derive(Debug)]
pub(crate) struct SamplerRaw(pub(super) Obj<dyn MTLSamplerState>);
#[derive(Debug)]
pub(crate) struct MetalSampler {
pub(super) raw: Arc<SamplerRaw>,
}
send_sync!(BufferRaw, MappedRange, TextureRaw, ViewRaw, SamplerRaw);
/// Counts one live resource of a kind, for `Device::get_internal_counters`, until dropped.
#[derive(Debug)]
pub(crate) struct Live(Arc<AtomicIsize>);
impl Live {
pub(super) fn new(count: &Arc<AtomicIsize>) -> Self {
count.fetch_add(1, Ordering::Relaxed);
Live(count.clone())
}
}
impl Drop for Live {
fn drop(&mut self) { self.0.fetch_sub(1, Ordering::Relaxed); }
}
impl Drop for BufferRaw {
fn drop(&mut self) { self.live.fetch_sub(1, Ordering::Relaxed); }
}
impl BufferRaw {
fn from(shared: &Shared, raw: Obj<dyn MTLBuffer>, size: u64) -> Self {
shared.buffers.fetch_add(1, Ordering::Relaxed);
let contents = raw.contents().cast();
BufferRaw { raw, contents, size, live: shared.buffers.clone() }
}
/// A shared buffer of `size` zeroed bytes.
pub(super) fn new(shared: &Shared, size: u64, label: Option<&str>) -> Self {
let raw = shared.device.newBufferWithLength_options(size.max(4) as usize, MTLResourceOptions::StorageModeShared).expect("a Metal buffer");
#[cfg(debug_assertions)]
if let Some(label) = label { raw.setLabel(Some(&NSString::from_str(label))); }
#[cfg(not(debug_assertions))]
let _ = label;
Self::from(shared, raw, size)
}
/// A shared buffer holding a copy of `data`, which is not empty.
pub(super) fn with_bytes(shared: &Shared, data: &[u8], label: Option<&str>) -> Self {
// SAFETY: `data` is valid for its length, which is nonzero.
let raw = unsafe {
shared.device.newBufferWithBytes_length_options(NonNull::from(data).cast(), data.len(), MTLResourceOptions::StorageModeShared)
}.expect("a Metal buffer");
#[cfg(debug_assertions)]
if let Some(label) = label { raw.setLabel(Some(&NSString::from_str(label))); }
#[cfg(not(debug_assertions))]
let _ = label;
Self::from(shared, raw, data.len() as u64)
}
/// Writes `data` at `offset` from the CPU, which the GPU must not be reading then.
pub(super) fn write(&self, offset: u64, data: &[u8]) {
assert!(offset + data.len() as u64 <= self.size, "a write past the end of a buffer");
// SAFETY: in bounds, checked above, of storage that lives as long as `raw`.
unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), self.contents.as_ptr().add(offset as usize), data.len()) };
}
/// Copies `range` of `other`, a buffer of the same size, into the same range here.
pub(super) fn copy_from(&self, other: &BufferRaw, range: Range<u64>) {
if range.is_empty() { return }
assert!(range.end <= self.size && range.end <= other.size, "a copy past the end of a buffer");
// SAFETY: in bounds of both, checked above; distinct allocations.
unsafe {
std::ptr::copy_nonoverlapping(other.contents.as_ptr().add(range.start as usize), self.contents.as_ptr().add(range.start as usize),
(range.end - range.start) as usize)
};
}
fn range(&self, range: Range<u64>) -> MappedRange {
assert!(range.start <= range.end && range.end <= self.size, "a mapped range past the end of a buffer");
// SAFETY: in bounds, checked above.
MappedRange { at: unsafe { self.contents.add(range.start as usize) }, len: (range.end - range.start) as usize }
}
}
impl MetalBuffer {
pub(crate) fn new(shared: &Arc<Shared>, size: u64, label: Option<&str>) -> Self {
MetalBuffer { store: Arc::new(Store::new(BufferRaw::new(shared, size, label))), shared: shared.clone() }
}
/// The storage commands recorded now read.
pub(super) fn raw(&self) -> Arc<BufferRaw> { self.store.current() }
}
impl BufferInterface for MetalBuffer {
fn map_async(&self, _: wgpu::MapMode, _: Range<wgpu::BufferAddress>, callback: BufferMapCallback) {
self.shared.map_after_work(callback);
}
fn get_mapped_range(&self, range: Range<wgpu::BufferAddress>) -> Result<DispatchBufferMappedRange, wgpu::MapRangeError> {
Ok(DispatchBufferMappedRange::custom(self.store.current().range(range)))
}
fn unmap(&self) {}
fn destroy(&self) {}
}
impl BufferMappedRangeInterface for MappedRange {
fn len(&self) -> usize { self.len }
unsafe fn read_slice(&self) -> &[u8] {
// SAFETY: `self.at..self.at + self.len` was bounds-checked against the shared `MTLBuffer`
// in `BufferRaw::range`, and the caller guarantees the buffer stays mapped with no concurrent writes.
unsafe { std::slice::from_raw_parts(self.at.as_ptr(), self.len) }
}
unsafe fn write_slice(&mut self) -> wgpu::WriteOnly<'_, [u8]> {
// SAFETY: `self.at..self.at + self.len` was bounds-checked against the shared `MTLBuffer`
// in `BufferRaw::range`, and the caller guarantees exclusive mutable access while mapped.
unsafe { std::slice::from_raw_parts_mut(self.at.as_ptr(), self.len) }.into()
}
}
fn texture_type(dimension: wgpu::TextureViewDimension) -> MTLTextureType {
use wgpu::TextureViewDimension as D;
match dimension {
D::D1 => MTLTextureType::Type1D,
D::D2 => MTLTextureType::Type2D,
D::D2Array => MTLTextureType::Type2DArray,
D::Cube => MTLTextureType::TypeCube,
D::CubeArray => MTLTextureType::TypeCubeArray,
D::D3 => MTLTextureType::Type3D,
}
}
impl TextureRaw {
/// A drawable's texture, which a surface hands out for one frame.
pub(super) fn drawable(raw: Obj<dyn MTLTexture>, format: wgpu::TextureFormat) -> Self {
TextureRaw { raw, format, dimension: wgpu::TextureDimension::D2, layers: 1, mips: 1, drawable: true, owner: None, live: None }
}
fn view_dimension(&self) -> wgpu::TextureViewDimension {
match self.dimension {
wgpu::TextureDimension::D1 => wgpu::TextureViewDimension::D1,
wgpu::TextureDimension::D2 if self.layers > 1 => wgpu::TextureViewDimension::D2Array,
wgpu::TextureDimension::D2 => wgpu::TextureViewDimension::D2,
wgpu::TextureDimension::D3 => wgpu::TextureViewDimension::D3,
}
}
}
impl MetalTexture {
pub(crate) fn new(device: &Obj<dyn MTLDevice>, desc: &wgpu::TextureDescriptor<'_>, live: Live) -> Self {
if desc.sample_count != 1 { super::unsupported!("multisampled textures") }
let layers = if desc.dimension == wgpu::TextureDimension::D3 { 1 } else { desc.size.depth_or_array_layers };
let raw = TextureRaw { raw: device_texture(device, desc, layers), format: desc.format, dimension: desc.dimension, layers,
mips: desc.mip_level_count, drawable: false, owner: None, live: Some(live) };
MetalTexture { raw: Arc::new(raw) }
}
/// Over `raw`, a texture made elsewhere that matches `desc`, kept valid by `owner`.
pub(crate) fn from_raw(raw: Obj<dyn MTLTexture>, desc: &wgpu::TextureDescriptor<'_>, owner: Owner) -> Self {
let raw = TextureRaw { raw, format: desc.format, dimension: desc.dimension, layers: desc.size.depth_or_array_layers,
mips: desc.mip_level_count, drawable: false, owner: Some(owner), live: None };
MetalTexture { raw: Arc::new(raw) }
}
}
fn device_texture(device: &Obj<dyn MTLDevice>, desc: &wgpu::TextureDescriptor<'_>, layers: u32) -> Obj<dyn MTLTexture> {
use wgpu::TextureUsages as U;
let d = MTLTextureDescriptor::new();
let kind = match desc.dimension {
wgpu::TextureDimension::D1 => MTLTextureType::Type1D,
wgpu::TextureDimension::D2 if layers > 1 => MTLTextureType::Type2DArray,
wgpu::TextureDimension::D2 => MTLTextureType::Type2D,
wgpu::TextureDimension::D3 => MTLTextureType::Type3D,
};
d.setTextureType(kind);
d.setPixelFormat(pixel_format(desc.format));
// SAFETY: nonzero sizes, within the device's limits as wgpu's validation would require.
unsafe {
d.setWidth(desc.size.width.max(1) as usize);
d.setHeight(desc.size.height.max(1) as usize);
d.setDepth(if kind == MTLTextureType::Type3D { desc.size.depth_or_array_layers.max(1) as usize } else { 1 });
d.setArrayLength(layers.max(1) as usize);
d.setMipmapLevelCount(desc.mip_level_count.max(1) as usize);
}
let mut usage = MTLTextureUsage::Unknown;
if desc.usage.intersects(U::TEXTURE_BINDING | U::STORAGE_BINDING) { usage |= MTLTextureUsage::ShaderRead; }
if desc.usage.contains(U::STORAGE_BINDING) { usage |= MTLTextureUsage::ShaderWrite; }
if desc.usage.contains(U::RENDER_ATTACHMENT) { usage |= MTLTextureUsage::RenderTarget; }
if desc.view_formats.iter().any(|f| *f != desc.format) { usage |= MTLTextureUsage::PixelFormatView; }
d.setUsage(usage);
d.setStorageMode(MTLStorageMode::Private);
let raw = device.newTextureWithDescriptor(&d).expect("a Metal texture");
#[cfg(debug_assertions)]
if let Some(label) = desc.label { raw.setLabel(Some(&NSString::from_str(label))); }
raw
}
impl TextureInterface for MetalTexture {
fn create_view(&self, desc: &wgpu::TextureViewDescriptor<'_>) -> DispatchTextureView {
let t = &self.raw;
let format = desc.format.unwrap_or(t.format);
let dimension = desc.dimension.unwrap_or_else(|| t.view_dimension());
let mips = desc.mip_level_count.unwrap_or(t.mips - desc.base_mip_level);
let layers = desc.array_layer_count.unwrap_or(t.layers - desc.base_array_layer);
let whole = format == t.format && dimension == t.view_dimension() && desc.base_mip_level == 0 && mips == t.mips
&& desc.base_array_layer == 0 && layers == t.layers;
let raw = if whole {
t.raw.clone()
} else {
let levels = NSRange::new(desc.base_mip_level as usize, mips as usize);
let slices = NSRange::new(desc.base_array_layer as usize, layers as usize);
// SAFETY: the ranges are within the texture, as wgpu's validation would require.
let view = unsafe { t.raw.newTextureViewWithPixelFormat_textureType_levels_slices(pixel_format(format), texture_type(dimension), levels, slices) }
.expect("a Metal texture view");
#[cfg(debug_assertions)]
if let Some(label) = desc.label {
view.setLabel(Some(&NSString::from_str(label)));
} else if let Some(label) = t.raw.label() {
view.setLabel(Some(&label));
}
view
};
DispatchTextureView::custom(MetalView { raw: Arc::new(ViewRaw { raw, drawable: t.drawable, owner: t.owner.clone() }) })
}
fn destroy(&self) {}
}
impl TextureViewInterface for MetalView {}
fn address(mode: wgpu::AddressMode) -> MTLSamplerAddressMode {
match mode {
wgpu::AddressMode::ClampToEdge => MTLSamplerAddressMode::ClampToEdge,
wgpu::AddressMode::Repeat => MTLSamplerAddressMode::Repeat,
wgpu::AddressMode::MirrorRepeat => MTLSamplerAddressMode::MirrorRepeat,
wgpu::AddressMode::ClampToBorder => MTLSamplerAddressMode::ClampToBorderColor,
}
}
fn min_mag(mode: wgpu::FilterMode) -> MTLSamplerMinMagFilter {
match mode {
wgpu::FilterMode::Nearest => MTLSamplerMinMagFilter::Nearest,
wgpu::FilterMode::Linear => MTLSamplerMinMagFilter::Linear,
}
}
pub(super) fn compare(function: wgpu::CompareFunction) -> MTLCompareFunction {
use wgpu::CompareFunction as C;
match function {
C::Never => MTLCompareFunction::Never,
C::Less => MTLCompareFunction::Less,
C::Equal => MTLCompareFunction::Equal,
C::LessEqual => MTLCompareFunction::LessEqual,
C::Greater => MTLCompareFunction::Greater,
C::NotEqual => MTLCompareFunction::NotEqual,
C::GreaterEqual => MTLCompareFunction::GreaterEqual,
C::Always => MTLCompareFunction::Always,
}
}
impl MetalSampler {
pub(crate) fn new(device: &Obj<dyn MTLDevice>, desc: &wgpu::SamplerDescriptor<'_>) -> Self {
let d = MTLSamplerDescriptor::new();
d.setSAddressMode(address(desc.address_mode_u));
d.setTAddressMode(address(desc.address_mode_v));
d.setRAddressMode(address(desc.address_mode_w));
d.setMinFilter(min_mag(desc.min_filter));
d.setMagFilter(min_mag(desc.mag_filter));
d.setMipFilter(match desc.mipmap_filter {
wgpu::MipmapFilterMode::Nearest => MTLSamplerMipFilter::Nearest,
wgpu::MipmapFilterMode::Linear => MTLSamplerMipFilter::Linear,
});
d.setLodMinClamp(desc.lod_min_clamp);
d.setLodMaxClamp(desc.lod_max_clamp);
d.setMaxAnisotropy(usize::from(desc.anisotropy_clamp.max(1)));
if let Some(function) = desc.compare { d.setCompareFunction(compare(function)); }
d.setBorderColor(match desc.border_color {
Some(wgpu::SamplerBorderColor::OpaqueBlack) => MTLSamplerBorderColor::OpaqueBlack,
Some(wgpu::SamplerBorderColor::OpaqueWhite) => MTLSamplerBorderColor::OpaqueWhite,
_ => MTLSamplerBorderColor::TransparentBlack,
});
#[cfg(debug_assertions)]
if let Some(label) = desc.label { d.setLabel(Some(&NSString::from_str(label))); }
MetalSampler { raw: Arc::new(SamplerRaw(device.newSamplerStateWithDescriptor(&d).expect("a Metal sampler"))) }
}
}
impl SamplerInterface for MetalSampler {}
+293
View File
@@ -0,0 +1,293 @@
//! Shader modules stay naga IR until a pipeline names an entry point; then naga translates it
//! to MSL with the pipeline layout's slots and Metal compiles it, as wgpu-hal does. A pipeline
//! of Rune's own (`builtin`) takes that function precompiled instead, and a module whose every
//! pipeline is one of those is never parsed. A module from a precompiled `.metallib`
//! (`create_shader_module_passthrough`) skips both: its functions are looked up by name, and
//! must read no sizes buffer.
#![allow(unsafe_code)]
use std::ffi::c_void;
use std::future::ready;
use std::pin::Pin;
use std::ptr::NonNull;
use std::sync::OnceLock;
use objc2_foundation::{NSError, NSString};
use objc2_metal::{MTLCompileOptions, MTLDevice, MTLFunction, MTLLibrary};
use objc2::msg_send;
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, ProtocolObject};
use wgpu::custom::*;
use wgpu::naga::{
self,
back::{msl, pipeline_constants::process_overrides},
proc::{BoundsCheckPolicies, BoundsCheckPolicy},
valid::{Capabilities, ValidationFlags, Validator},
};
use super::{Obj, Shared, builtin, send_sync};
#[derive(Debug)]
pub(crate) enum ShaderModule {
Naga(Ir),
/// A precompiled library, or why Metal refused it, and its entry points' workgroup sizes.
Library { library: Result<Obj<dyn MTLLibrary>, String>, entries: Vec<(String, [u32; 3])> },
}
send_sync!(ShaderModule);
/// A WGSL module, validated when first needed, and the runtime checks its MSL keeps.
#[derive(Debug)]
pub(crate) struct Ir {
label: String,
source: String,
pub(super) hash: blake3::Hash,
parsed: OnceLock<(naga::Module, naga::valid::ModuleInfo)>,
pub(super) checks: wgpu::ShaderRuntimeChecks,
}
/// An entry point compiled for one pipeline, and the storage bindings whose byte sizes it reads
/// from the sizes buffer, in the order it reads them.
pub(super) struct Compiled {
pub(super) function: Obj<dyn MTLFunction>,
pub(super) sized: Vec<naga::ResourceBinding>,
/// Threads per workgroup, for a compute entry point.
pub(super) workgroup: [u32; 3],
/// Byte size of each `var<workgroup>` global used by a compute entry point, in Naga's MSL parameter order.
pub(super) workgroup_memory: Vec<u32>,
}
/// One stage of a pipeline, as `compile` needs it.
pub(super) struct Stage<'a> {
pub(super) module: &'a wgpu::ShaderModule,
pub(super) entry: Option<&'a str>,
pub(super) constants: &'a [(&'a str, f64)],
pub(super) kind: naga::ShaderStage,
}
/// The entry point a stage runs, named or the module's only one of its kind.
pub(super) struct Point<'a> {
pub(super) kind: naga::ShaderStage,
pub(super) entry: Option<&'a str>,
pub(super) constants: &'a [(&'a str, f64)],
}
/// An entry point translated to MSL: the source, the function's name in it, and what `Compiled` keeps.
pub(super) struct Msl {
pub(super) source: String,
pub(super) function: String,
pub(super) sized: Vec<naga::ResourceBinding>,
pub(super) workgroup: [u32; 3],
pub(super) workgroup_memory: Vec<u32>,
}
#[link(name = "System")]
unsafe extern "C" {
fn dispatch_data_create(buffer: NonNull<c_void>, size: usize, queue: *mut c_void, destructor: *mut c_void) -> *mut AnyObject;
fn dispatch_release(object: *mut AnyObject);
}
impl Ir {
/// Parses and validates `source` now, unless it is a built-in shader, which parses only if a
/// pipeline needs a function the precompiled library lacks.
pub(super) fn new(label: &str, source: &str, checks: wgpu::ShaderRuntimeChecks) -> Self {
let hash = source_hash(source);
let ir = Ir { label: label.into(), source: source.into(), hash, parsed: OnceLock::new(), checks };
if !builtin::known(&hash) { ir.parsed(); }
ir
}
pub(super) fn parse(label: &str, source: &str, checks: wgpu::ShaderRuntimeChecks) -> Self {
let ir = Ir { label: label.into(), source: source.into(), hash: source_hash(source), parsed: OnceLock::new(), checks };
ir.parsed();
ir
}
fn parsed(&self) -> &(naga::Module, naga::valid::ModuleInfo) {
self.parsed.get_or_init(|| {
let (label, source) = (&self.label, &self.source);
let module = naga::front::wgsl::parse_str(source).unwrap_or_else(|e| panic!("{label}: {}", e.emit_to_string(source)));
let info = Validator::new(ValidationFlags::all(), Capabilities::all())
.validate(&module)
.unwrap_or_else(|e| panic!("{label}: {}", e.emit_to_string(source)));
(module, info)
})
}
pub(super) fn parts(&self) -> (&naga::Module, &naga::valid::ModuleInfo) {
let (module, info) = self.parsed();
(module, info)
}
#[cfg(test)]
pub(super) fn was_parsed(&self) -> bool { self.parsed.get().is_some() }
}
/// BLAKE3 of `source` with each `\r\n` read as `\n`: a built-in shader's WGSL from a checkout
/// with CRLF line endings (one made before `.gitattributes`, or an archive) keys the same
/// precompiled function as an LF one. LF text, the usual case, costs one scan for `\r`.
fn source_hash(source: &str) -> blake3::Hash {
if !source.as_bytes().contains(&b'\r') {
return blake3::hash(source.as_bytes());
}
let mut hasher = blake3::Hasher::new();
for (i, line) in source.split("\r\n").enumerate() {
if i > 0 { hasher.update(b"\n"); }
hasher.update(line.as_bytes());
}
hasher.finalize()
}
impl ShaderModule {
pub(crate) fn new(desc: wgpu::ShaderModuleDescriptor<'_>, checks: wgpu::ShaderRuntimeChecks) -> Self {
let wgpu::ShaderSource::Wgsl(source) = desc.source else { super::unsupported!("shaders other than WGSL") };
ShaderModule::Naga(Ir::new(desc.label.unwrap_or("shader"), &source, checks))
}
pub(crate) fn passthrough(shared: &Shared, desc: &wgpu::ShaderModuleDescriptorPassthrough<'_>) -> Self {
let bytes = desc.metallib.as_deref().unwrap_or_else(|| super::unsupported!("passthrough shaders other than a metallib"));
let entries = desc.entry_points.iter().map(|e| (e.name.to_string(), [e.workgroup_size.0, e.workgroup_size.1, e.workgroup_size.2])).collect();
ShaderModule::Library { library: library(shared, bytes), entries }
}
/// Whether every entry point can make a pipeline: a precompiled library loaded and holds
/// them all. A module from WGSL already passed validation.
pub(crate) fn ready(&self) -> bool {
match self {
ShaderModule::Naga(_) => true,
ShaderModule::Library { library: Ok(library), entries } => {
let names = library.functionNames();
entries.iter().all(|(name, _)| names.iter().any(|n| n.to_string() == *name))
}
ShaderModule::Library { library: Err(_), .. } => false,
}
}
}
impl ShaderModuleInterface for ShaderModule {
fn get_compilation_info(&self) -> Pin<Box<dyn ShaderCompilationInfoFuture>> {
Box::pin(ready(wgpu::CompilationInfo { messages: Vec::new() }))
}
}
pub(super) fn compile(shared: &Shared, stage: &Stage<'_>, resources: &msl::EntryPointResources, points: bool) -> Result<Compiled, String> {
let shader = stage.module.as_custom::<ShaderModule>().expect("a Metal shader module");
match shader {
ShaderModule::Naga(ir) => {
let point = Point { kind: stage.kind, entry: stage.entry, constants: stage.constants };
let key = builtin::key(ir, &point, resources, points);
if let Some(compiled) = builtin::find(shared, &key) {
return Ok(compiled);
}
builtin::capture(ir, &point, resources, points, &key);
let (lang, version) = shared.msl;
let msl = translate(ir, &point, resources, points, lang)?;
let compile = MTLCompileOptions::new();
compile.setLanguageVersion(version);
compile.setPreserveInvariance(true);
let library = shared.device.newLibraryWithSource_options_error(&NSString::from_str(&msl.source), Some(&compile))
.map_err(|e| format!("{}: Metal: {}", msl.function, e.localizedDescription()))?;
let function = function(&library, &msl.function)?;
Ok(Compiled { function, sized: msl.sized, workgroup: msl.workgroup, workgroup_memory: msl.workgroup_memory })
}
ShaderModule::Library { library, entries } => {
let library = library.as_ref().map_err(|e| format!("metallib: {e}"))?;
if resources.sizes_buffer.is_some() {
return Err("a precompiled library can't read storage buffers' sizes".into());
}
let (name, workgroup) = match stage.entry {
Some(name) => entries.iter().find(|(n, _)| n == name).ok_or_else(|| format!("no entry point {name}"))?,
None => match entries.as_slice() {
[entry] => entry,
_ => return Err(format!("no single {:?} entry point", stage.kind)),
},
};
Ok(Compiled { function: function(library, name)?, sized: Vec::new(), workgroup: *workgroup, workgroup_memory: Vec::new() })
}
}
}
/// The library a `.metallib`'s bytes hold, or why Metal refused it.
pub(super) fn library(shared: &Shared, bytes: &[u8]) -> Result<Obj<dyn MTLLibrary>, String> {
NonNull::new(bytes.as_ptr().cast_mut()).ok_or_else(|| "an empty metallib".to_string()).and_then(|buffer| {
// SAFETY: dispatch copies `bytes` (the default destructor), and the data object is
// released after Metal has read it.
unsafe {
let data = dispatch_data_create(buffer.cast(), bytes.len(), std::ptr::null_mut(), std::ptr::null_mut());
assert!(!data.is_null(), "dispatch data for a metallib");
let library: Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>> =
msg_send![&*shared.device, newLibraryWithData: data, error: _];
dispatch_release(data);
library.map_err(|e| e.localizedDescription().to_string())
}
})
}
pub(super) fn function(library: &ProtocolObject<dyn MTLLibrary>, name: &str) -> Result<Obj<dyn MTLFunction>, String> {
library.newFunctionWithName(&NSString::from_str(name)).ok_or_else(|| format!("no function {name}"))
}
/// Translates `point` to MSL `lang`, binding `resources`.
pub(super) fn translate(ir: &Ir, point: &Point<'_>, resources: &msl::EntryPointResources, points: bool, lang: (u8, u8)) -> Result<Msl, String> {
let (module, info) = ir.parsed();
let checks = &ir.checks;
let name = match point.entry {
Some(name) => name.to_string(),
None => {
let mut eps = module.entry_points.iter().filter(|e| e.stage == point.kind);
match (eps.next(), eps.next()) {
(Some(ep), None) => ep.name.clone(),
_ => return Err(format!("no single {:?} entry point", point.kind)),
}
}
};
let constants: naga::back::PipelineConstants = point.constants.iter().map(|&(k, v)| (k.to_string(), v)).collect();
let (module, info) = process_overrides(module, info, Some((point.kind, &name)), &constants)
.map_err(|e| format!("{name}: overrides: {e:?}"))?;
let policy = if checks.bounds_checks { BoundsCheckPolicy::Restrict } else { BoundsCheckPolicy::Unchecked };
let options = msl::Options {
lang_version: lang,
inline_samplers: Default::default(),
spirv_cross_compatibility: false,
fake_missing_bindings: false,
per_entry_point_map: msl::EntryPointResourceMap::from([(name.clone(), resources.clone())]),
bounds_check_policies: BoundsCheckPolicies { index: policy, buffer: policy, image_load: policy, binding_array: BoundsCheckPolicy::Unchecked },
zero_initialize_workgroup_memory: true,
force_loop_bounding: checks.force_loop_bounding,
task_dispatch_limits: None,
mesh_shader_primitive_indices_clamp: checks.mesh_shader_primitive_indices_clamp,
emit_int_div_checks: checks.int_div_checks,
ray_query_initialization_tracking: checks.ray_query_initialization_tracking,
};
let pipeline = msl::PipelineOptions {
entry_point: Some((point.kind, name.clone())),
allow_and_force_point_size: points,
vertex_pulling_transform: false,
vertex_buffer_mappings: Vec::new(),
binding_array_length_map: Default::default(),
};
let (source, translated) = msl::write_string(&module, &info, &options, &pipeline).map_err(|e| format!("{name}: MSL: {e:?}"))?;
let function = translated.entry_point_names[0].as_ref().map_err(|e| format!("{name}: {e}"))?.clone();
// The sizes buffer holds one length per global that needs it, in global order, as naga reads it.
let sized = module.global_variables.iter()
.filter(|(_, g)| matches!(g.space, naga::AddressSpace::Uniform | naga::AddressSpace::Storage { .. }))
.filter(|(_, g)| module.types[g.ty].inner.needs_host_buffer_byte_size(&module.types))
.filter_map(|(_, g)| g.binding)
.collect();
let ep_index = module.entry_points.iter().position(|e| e.stage == point.kind && e.name == name);
let workgroup = ep_index.map_or([1; 3], |i| module.entry_points[i].workgroup_size);
// Naga emits each used `var<workgroup>` global as a `threadgroup` kernel parameter in
// `module.global_variables` order (`naga` MSL writer), matching `wgpu-hal`'s `wg_memory_sizes`.
let workgroup_memory = if point.kind == naga::ShaderStage::Compute
&& let Some(ep_index) = ep_index
{
let ep_info = info.get_entry_point(ep_index);
module.global_variables.iter()
.filter(|&(handle, var)| var.space == naga::AddressSpace::WorkGroup && !ep_info[handle].is_empty())
.map(|(_, var)| module.types[var.ty].inner.size(module.to_ctx()))
.collect()
} else {
Vec::new()
};
Ok(Msl { source, function, sized, workgroup, workgroup_memory })
}
@@ -0,0 +1,274 @@
//! Every WGSL shader in rune, rune-fx and rune-light, composed the way its crate composes it,
//! through naga to MSL with wgpu-hal's Metal options and then `newLibraryWithSource`, one library
//! per entry point as wgpu-hal builds them. The question it answers: can a native backend keep
//! WGSL as the one shader language, by translating with naga itself?
use objc2_foundation::NSString;
use objc2_metal::{MTLCompileOptions, MTLCreateSystemDefaultDevice, MTLDevice};
use objc2::runtime::ProtocolObject;
use super::device::msl_version;
use wgpu::naga::{
self,
back::{msl, pipeline_constants::process_overrides},
proc::{BoundsCheckPolicies, BoundsCheckPolicy},
valid::{Capabilities, ValidationFlags, Validator},
};
const CLIP: &str = include_str!("../../../rune/src/shaders/clip.wgsl");
const FX_COMMON: &str = include_str!("../../../rune-fx/src/shaders/common.wgsl");
const LIGHT_COMMON: &str = include_str!("../../../rune-light/src/shaders/common.wgsl");
const GI: &str = include_str!("../../../rune-light/src/shaders/gi.wgsl");
const GLASS: &str = include_str!("../../../rune-light/src/shaders/glass.wgsl");
const REEL: &str = include_str!("../../../rune-light/examples/reel/reel.wgsl");
/// One shader module as its crate builds it: the files it is made of, its source, and the
/// pipeline constants it is built with (one module per set).
struct Case {
name: String,
files: Vec<&'static str>,
source: String,
constants: Vec<Vec<(&'static str, f64)>>,
}
fn case(name: &str, files: &[&'static str], source: String) -> Case {
Case { name: name.into(), files: files.to_vec(), source, constants: vec![Vec::new()] }
}
/// `gi_section` in rune-light's gpu.rs.
fn gi_section(name: &str) -> String {
let mut parts = GI.split("// ---- ");
let header = parts.next().unwrap_or_default();
let body = parts.find(|p| p.starts_with(name)).unwrap_or_default();
format!("{LIGHT_COMMON}\n{header}\n// ---- {body}")
}
/// `section` in rune-light's glass.rs.
fn glass_section(name: &str) -> String {
let (main, pyramid) = GLASS.split_once("// ---- pyramid ----").unwrap_or((GLASS, ""));
if name == "pyramid" {
format!("@vertex\nfn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {{\n let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));\n return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);\n}}\n{pyramid}")
} else {
main.to_string()
}
}
/// `wgsl_part` in rune-light's reel example.
fn reel_part(name: &str) -> String {
let (viz, rest) = REEL.split_once("// ---- bloom ----").unwrap();
let (bloom, rest) = rest.split_once("// ---- per-probe mean of a cascade level ----").unwrap();
let (mean, enc) = rest.split_once("// ---- final encode ----").unwrap();
match name { "viz" => viz, "bloom" => bloom, "mean" => mean, _ => enc }.to_string()
}
fn cases() -> Vec<Case> {
let mut cases = vec![
case("rune uber", &["rune/src/shaders/clip.wgsl", "rune/src/shaders/shader.wgsl", "rune-gpu/src/springs.wgsl"],
format!("{CLIP}\n{}\n{}", include_str!("../../../rune/src/shaders/shader.wgsl"), include_str!("../springs.wgsl"))),
case("rune backdrop blur", &["rune/src/shaders/backdrop_blur.wgsl"], include_str!("../../../rune/src/shaders/backdrop_blur.wgsl").into()),
case("rune backdrop composite", &["rune/src/shaders/clip.wgsl", "rune/src/shaders/backdrop_composite.wgsl"],
format!("{CLIP}\n{}", include_str!("../../../rune/src/shaders/backdrop_composite.wgsl"))),
case("rune video", &["rune-media/src/native_surface/video.wgsl"], include_str!("../../../rune-media/src/native_surface/video.wgsl").into()),
];
let mut blur = case("rune layer blur", &["rune/src/shaders/layer_blur.wgsl"], include_str!("../../../rune/src/shaders/layer_blur.wgsl").into());
blur.constants = [(0.0, 0.0), (0.0, 1.0), (2.0, 0.0), (2.0, 1.0), (3.0, 0.0)].iter().map(|&(m, a)| vec![("MODE", m), ("ADDITIVE", a)]).collect();
cases.push(blur);
let fx_effects: [(&str, &'static str, &str); 8] = [
("glow", "rune-fx/src/shaders/glow.wgsl", include_str!("../../../rune-fx/src/shaders/glow.wgsl")),
("pulse", "rune-fx/src/shaders/pulse.wgsl", include_str!("../../../rune-fx/src/shaders/pulse.wgsl")),
("electric", "rune-fx/src/shaders/electric.wgsl", include_str!("../../../rune-fx/src/shaders/electric.wgsl")),
("fire", "rune-fx/src/shaders/fire.wgsl", include_str!("../../../rune-fx/src/shaders/fire.wgsl")),
("distort", "rune-fx/src/shaders/distort.wgsl", include_str!("../../../rune-fx/src/shaders/distort.wgsl")),
("motion", "rune-fx/src/shaders/motion.wgsl", include_str!("../../../rune-fx/src/shaders/motion.wgsl")),
("extras", "rune-fx/src/shaders/extras.wgsl", include_str!("../../../rune-fx/src/shaders/extras.wgsl")),
("fill", "rune-fx/src/shaders/fill.wgsl", include_str!("../../../rune-fx/src/shaders/fill.wgsl")),
];
for (name, file, src) in fx_effects {
cases.push(case(&format!("fx {name}"), &["rune/src/shaders/clip.wgsl", "rune-fx/src/shaders/common.wgsl", file], format!("{CLIP}\n{FX_COMMON}\n{src}")));
}
cases.extend([
case("fx mip", &["rune-fx/src/shaders/mip.wgsl"], include_str!("../../../rune-fx/src/shaders/mip.wgsl").into()),
case("fx blur", &["rune-fx/src/shaders/blur.wgsl"], include_str!("../../../rune-fx/src/shaders/blur.wgsl").into()),
case("fx firesim", &["rune-fx/src/shaders/firesim.wgsl"], include_str!("../../../rune-fx/src/shaders/firesim.wgsl").into()),
case("fx gallery ui", &["rune-fx/examples/gallery/ui.wgsl"], include_str!("../../../rune-fx/examples/gallery/ui.wgsl").into()),
case("fx gallery resolve", &["rune-fx/examples/gallery/resolve.wgsl"], include_str!("../../../rune-fx/examples/gallery/resolve.wgsl").into()),
]);
let light: [(&str, &'static str, &str); 4] = [
("gbuffer", "rune-light/src/shaders/gbuffer.wgsl", include_str!("../../../rune-light/src/shaders/gbuffer.wgsl")),
("field", "rune-light/src/shaders/field.wgsl", include_str!("../../../rune-light/src/shaders/field.wgsl")),
("shadow", "rune-light/src/shaders/shadow.wgsl", include_str!("../../../rune-light/src/shaders/shadow.wgsl")),
("composite", "rune-light/src/shaders/composite.wgsl", include_str!("../../../rune-light/src/shaders/composite.wgsl")),
];
for (name, file, src) in light {
cases.push(case(&format!("light {name}"), &["rune-light/src/shaders/common.wgsl", file], format!("{LIGHT_COMMON}\n{src}")));
}
for name in ["scene", "cascades", "fluence"] {
cases.push(case(&format!("light gi {name}"), &["rune-light/src/shaders/common.wgsl", "rune-light/src/shaders/gi.wgsl"], gi_section(name)));
}
for name in ["glass", "pyramid"] {
cases.push(case(&format!("light glass {name}"), &["rune-light/src/shaders/glass.wgsl"], glass_section(name)));
}
for name in ["viz", "bloom", "mean", "enc"] {
cases.push(case(&format!("light reel {name}"), &["rune-light/examples/reel/reel.wgsl"], reel_part(name)));
}
cases
}
/// Slots as wgpu-hal hands them out for a layout holding every binding the module declares:
/// buffers, textures and samplers each counted up in (group, binding) order.
fn resources(module: &naga::Module, stage: naga::ShaderStage) -> msl::EntryPointResources {
let mut bound: Vec<_> = module.global_variables.iter().filter_map(|(_, g)| Some((g.binding.clone()?, g))).collect();
bound.sort_by_key(|(b, _)| (b.group, b.binding));
let (mut buffers, mut textures, mut samplers) = (0u8, 0u8, 0u8);
let mut out = msl::EntryPointResources::default();
for (binding, global) in bound {
let mut target = msl::BindTarget::default();
match (global.space, &module.types[global.ty].inner) {
(naga::AddressSpace::Uniform, _) => { target.buffer = Some(buffers); buffers += 1; }
(naga::AddressSpace::Storage { access }, _) => {
target.buffer = Some(buffers);
target.mutable = access.contains(naga::StorageAccess::STORE);
buffers += 1;
}
(_, naga::TypeInner::Sampler { .. }) => { target.sampler = Some(msl::BindSamplerTarget::Resource(samplers)); samplers += 1; }
(_, naga::TypeInner::Image { class, .. }) => {
target.texture = Some(textures);
target.mutable = matches!(class, naga::ImageClass::Storage { access, .. } if access.contains(naga::StorageAccess::STORE));
textures += 1;
}
(_, other) => panic!("binding type this test doesn't map yet: {other:?}"),
}
out.resources.insert(binding, target);
}
if stage == naga::ShaderStage::Vertex || buffers > 0 { out.sizes_buffer = Some(buffers); }
out
}
fn vertex_format(inner: &naga::TypeInner) -> Option<wgpu::VertexFormat> {
use wgpu::VertexFormat as V;
let (n, scalar) = match *inner {
naga::TypeInner::Scalar(s) => (1, s),
naga::TypeInner::Vector { size, scalar } => (size as u8, scalar),
_ => return None,
};
Some(match (scalar.kind, n) {
(naga::ScalarKind::Float, 1) => V::Float32,
(naga::ScalarKind::Float, 2) => V::Float32x2,
(naga::ScalarKind::Float, 3) => V::Float32x3,
(naga::ScalarKind::Float, _) => V::Float32x4,
(naga::ScalarKind::Uint, 1) => V::Uint32,
(naga::ScalarKind::Uint, 2) => V::Uint32x2,
(naga::ScalarKind::Uint, 3) => V::Uint32x3,
(naga::ScalarKind::Uint, _) => V::Uint32x4,
(naga::ScalarKind::Sint, 1) => V::Sint32,
(naga::ScalarKind::Sint, 2) => V::Sint32x2,
(naga::ScalarKind::Sint, 3) => V::Sint32x3,
_ => V::Sint32x4,
})
}
/// One tightly packed vertex buffer at slot 30 holding every `@location` input, which is the
/// shape the vertex-pulling transform needs; the real pipelines' strides differ, the MSL doesn't.
fn vertex_buffers(module: &naga::Module, ep: &naga::EntryPoint) -> Vec<msl::VertexBufferMapping> {
let mut inputs = Vec::new();
for arg in &ep.function.arguments {
match (&arg.binding, &module.types[arg.ty].inner) {
(Some(naga::Binding::Location { location, .. }), inner) => inputs.push((*location, vertex_format(inner).unwrap())),
(None, naga::TypeInner::Struct { members, .. }) => {
for m in members {
if let Some(naga::Binding::Location { location, .. }) = m.binding {
inputs.push((location, vertex_format(&module.types[m.ty].inner).unwrap()));
}
}
}
_ => {}
}
}
if inputs.is_empty() { return Vec::new(); }
let mut offset = 0;
let attributes = inputs.into_iter().map(|(shader_location, format)| {
let at = offset;
offset += format.size() as u32;
msl::AttributeMapping { shader_location, offset: at, format }
}).collect();
vec![msl::VertexBufferMapping { id: 30, stride: offset, step_mode: msl::VertexBufferStepMode::ByInstance, attributes }]
}
/// Translates and compiles each entry point; the error of the first that fails.
fn compile(device: &ProtocolObject<dyn MTLDevice>, case: &Case) -> Result<usize, String> {
let module = naga::front::wgsl::parse_str(&case.source).map_err(|e| format!("parse: {}", e.emit_to_string(&case.source)))?;
let info = Validator::new(ValidationFlags::all(), Capabilities::all())
.validate(&module)
.map_err(|e| format!("validate: {}", e.emit_to_string(&case.source)))?;
let ((major, minor), version) = msl_version();
let limits = wgpu::Limits::default();
let mut libraries = 0;
for constants in &case.constants {
let constants: naga::back::PipelineConstants = constants.iter().map(|&(k, v)| (k.to_string(), v)).collect();
for ep in &module.entry_points {
let (ep_module, ep_info) = process_overrides(&module, &info, Some((ep.stage, &ep.name)), &constants)
.map_err(|e| format!("{}: overrides: {e:?}", ep.name))?;
let ep = ep_module.entry_points.iter().find(|e| e.name == ep.name && e.stage == ep.stage).expect("the entry point survives");
let options = msl::Options {
lang_version: (major, minor),
inline_samplers: Default::default(),
spirv_cross_compatibility: false,
fake_missing_bindings: false,
per_entry_point_map: msl::EntryPointResourceMap::from([(ep.name.clone(), resources(&ep_module, ep.stage))]),
bounds_check_policies: BoundsCheckPolicies {
index: BoundsCheckPolicy::Restrict,
buffer: BoundsCheckPolicy::Restrict,
image_load: BoundsCheckPolicy::Restrict,
binding_array: BoundsCheckPolicy::Unchecked,
},
zero_initialize_workgroup_memory: true,
force_loop_bounding: true,
task_dispatch_limits: Some(naga::back::TaskDispatchLimits {
max_mesh_workgroups_per_dim: limits.max_mesh_workgroups_per_dimension,
max_mesh_workgroups_total: limits.max_mesh_workgroup_total_count,
}),
mesh_shader_primitive_indices_clamp: true,
emit_int_div_checks: true,
ray_query_initialization_tracking: true,
};
let pipeline = msl::PipelineOptions {
entry_point: Some((ep.stage, ep.name.clone())),
allow_and_force_point_size: false,
vertex_pulling_transform: true,
vertex_buffer_mappings: if ep.stage == naga::ShaderStage::Vertex { vertex_buffers(&ep_module, ep) } else { Vec::new() },
binding_array_length_map: Default::default(),
};
let (source, _) = msl::write_string(&ep_module, &ep_info, &options, &pipeline).map_err(|e| format!("{}: msl: {e:?}", ep.name))?;
let compile = MTLCompileOptions::new();
compile.setLanguageVersion(version);
compile.setPreserveInvariance(true);
device.newLibraryWithSource_options_error(&NSString::from_str(&source), Some(&compile))
.map_err(|e| format!("{}: metal: {}", ep.name, e.localizedDescription()))?;
libraries += 1;
}
}
Ok(libraries)
}
#[test]
fn every_wgsl_shader_compiles_to_a_metal_library() {
let device = MTLCreateSystemDefaultDevice().expect("a Metal device");
let mut files: Vec<(&str, bool)> = Vec::new();
let mut failures = Vec::new();
for case in cases() {
let result = compile(&device, &case);
match &result {
Ok(n) => println!("ok {:<26} {n} libraries", case.name),
Err(e) => { println!("FAIL {:<26} {e}", case.name); failures.push(case.name.clone()); }
}
for &file in &case.files {
match files.iter_mut().find(|(f, _)| *f == file) {
Some((_, ok)) => *ok &= result.is_ok(),
None => files.push((file, result.is_ok())),
}
}
}
let passed = files.iter().filter(|(_, ok)| *ok).count();
println!("{passed}/{} WGSL files compile in every module they are part of", files.len());
assert_eq!(files.len(), 29, "a WGSL file was added or removed: update this test");
assert!(failures.is_empty(), "failed: {failures:?}");
}
+152
View File
@@ -0,0 +1,152 @@
//! A buffer's shared storage, written straight from the CPU. While a recorded or running
//! command buffer still uses the storage, a write swaps in a spare brought up to date, so what
//! was recorded reads the old bytes and what is recorded next reads the new: a small ring per
//! written buffer, as deep as the frames in flight.
use std::collections::VecDeque;
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
#[cfg(debug_assertions)]
use objc2_metal::MTLResource;
use parking_lot::Mutex;
use super::Shared;
use super::resource::BufferRaw;
/// Spares a written buffer keeps: one per frame the GPU may still be reading.
const SPARES: usize = 2;
/// Written ranges remembered, to bring a spare up to date by copying only what it misses.
const LOG: usize = 8;
/// Swaps made in the process. A pass that sees it change rebinds its buffers' current storage.
pub(super) static SWAPS: AtomicU64 = AtomicU64::new(0);
#[derive(Debug)]
pub(crate) struct Store {
slots: Mutex<Slots>,
/// The GPU writes this buffer (a copy into it, a writable storage binding, a staged queue
/// write), so its storage is never swapped: a copy of the rest would miss what is in flight.
pinned: AtomicBool,
}
#[derive(Debug)]
struct Slots {
current: Arc<BufferRaw>,
/// Writes made so far, which numbers them.
writes: u64,
/// The latest writes' numbers and ranges.
log: VecDeque<(u64, Range<u64>)>,
/// Earlier storage, and how many writes it holds.
spares: VecDeque<(Arc<BufferRaw>, u64)>,
swaps: u64,
/// Bytes swaps copied forward, for tests.
#[cfg(test)]
copied: u64,
}
/// Whether anything besides the store holds `raw`: a command buffer's keep list, recorded or
/// running, holds what it uses until it completes.
fn idle(raw: &Arc<BufferRaw>) -> bool { Arc::strong_count(raw) == 1 }
impl Slots {
fn write(&mut self, offset: u64, data: &[u8]) {
self.current.write(offset, data);
self.writes += 1;
self.log.push_back((self.writes, offset..offset + data.len() as u64));
if self.log.len() > LOG { self.log.pop_front(); }
}
/// The span written since a storage holding `held` writes: everything if the log has lost
/// some of them.
fn missed(&self, held: u64) -> Range<u64> {
if self.log.front().is_none_or(|(at, _)| *at > held + 1) && held < self.writes { return 0..self.current.size }
self.log.iter().filter(|(at, _)| *at > held).fold(0..0, |hull, (_, r)| {
if hull.is_empty() { r.clone() } else { hull.start.min(r.start)..hull.end.max(r.end) }
})
}
}
impl Store {
pub(super) fn new(raw: BufferRaw) -> Self {
let slots = Slots {
current: Arc::new(raw), writes: 0, log: VecDeque::new(), spares: VecDeque::new(), swaps: 0,
#[cfg(test)]
copied: 0,
};
Store { slots: Mutex::new(slots), pinned: AtomicBool::new(false) }
}
/// The storage commands recorded now read and write.
pub(super) fn current(&self) -> Arc<BufferRaw> { self.slots.lock().current.clone() }
/// Notes that the GPU writes this buffer, which pins its storage.
pub(super) fn gpu_write(&self) -> Arc<BufferRaw> {
self.pinned.store(true, Ordering::Relaxed);
self.current()
}
pub(super) fn pinned(&self) -> bool { self.pinned.load(Ordering::Relaxed) }
/// Writes `data` at `offset` now if no recorded or running command uses the storage, which
/// is then exactly as if the write came ahead of every command recorded or submitted later.
pub(super) fn write_idle(&self, shared: &Shared, offset: u64, data: &[u8]) -> bool {
for retired in [false, true] {
// Buffers that completed since the last submit still hold their keep lists.
if retired { shared.retire(); }
let mut slots = self.slots.lock();
if idle(&slots.current) {
slots.write(offset, data);
return true;
}
}
false
}
/// Writes `data` at `offset` for the commands recorded from now on; those recorded before
/// keep reading the old bytes. False if the buffer is pinned, or if `may_swap`, asked under
/// the store's lock, says the old storage must take the write too, so it must be staged.
pub(super) fn write_ahead(&self, shared: &Shared, offset: u64, data: &[u8], may_swap: impl FnOnce() -> bool) -> bool {
if self.pinned() { return false }
if self.write_idle(shared, offset, data) { return true }
let mut slots = self.slots.lock();
if !may_swap() { return false }
let size = slots.current.size;
let (next, held) = match slots.spares.iter().position(|(raw, _)| idle(raw)) {
Some(i) => slots.spares.remove(i).expect("a spare"),
None => {
let fresh = BufferRaw::new(shared, size, None);
#[cfg(debug_assertions)]
if let Some(label) = slots.current.raw.label() { fresh.raw.setLabel(Some(&label)); }
(Arc::new(fresh), u64::MAX)
}
};
let missed = if held == u64::MAX { 0..size } else { slots.missed(held) };
let end = offset + data.len() as u64;
// Only what the write leaves: a write over everything it missed copies nothing.
let (before, after) = (missed.start..missed.end.min(offset), missed.start.max(end)..missed.end);
#[cfg(test)] { slots.copied += before.end.saturating_sub(before.start) + after.end.saturating_sub(after.start); }
next.copy_from(&slots.current, before);
next.copy_from(&slots.current, after);
let held = slots.writes;
let old = std::mem::replace(&mut slots.current, next);
slots.spares.push_back((old, held));
if slots.spares.len() > SPARES { slots.spares.pop_front(); }
slots.write(offset, data);
slots.swaps += 1;
SWAPS.fetch_add(1, Ordering::Relaxed);
true
}
/// Spares held and swaps made, for tests.
#[cfg(test)]
pub(super) fn swaps(&self) -> (usize, u64) {
let slots = self.slots.lock();
(slots.spares.len(), slots.swaps)
}
/// Bytes swaps copied forward, for tests.
#[cfg(test)]
pub(super) fn copied(&self) -> u64 { self.slots.lock().copied }
}
+215
View File
@@ -0,0 +1,215 @@
use super::bench::{clear, gpu};
use super::resource::MetalBuffer;
use super::*;
fn buffer(device: &wgpu::Device, size: u64, usage: wgpu::BufferUsages) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor { label: None, size, usage, mapped_at_creation: false })
}
fn read(device: &wgpu::Device, buffer: &wgpu::Buffer) -> Vec<u8> {
let slice = buffer.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let out = slice.get_mapped_range().unwrap().to_vec();
buffer.unmap();
out
}
/// Spares `buffer` holds and the swaps it made.
fn swaps(buffer: &wgpu::Buffer) -> (usize, u64) { buffer.as_custom::<MetalBuffer>().unwrap().store.swaps() }
#[cfg(feature = "test-gpu-counters")]
fn live(device: &wgpu::Device) -> isize { device.get_internal_counters().hal.buffers.read() }
/// Each frame writes parts of a buffer while the last frame's copy of it is recorded but not yet
/// submitted, so every frame swaps storage: each copy still reads what was written before it,
/// and once warm a frame makes no buffers.
#[cfg(feature = "test-gpu-counters")]
#[test]
fn writes_while_the_gpu_reads_swap_storage_and_land_in_order() {
use wgpu::BufferUsages as B;
const WORDS: usize = 64;
const FRAMES: usize = 24;
let (device, queue) = gpu();
let source = buffer(&device, (WORDS * 4) as u64, B::COPY_SRC | B::COPY_DST);
let out = buffer(&device, (WORDS * 4 * FRAMES) as u64, B::COPY_DST | B::MAP_READ);
let mut model = [7u32; WORDS];
assert!(write_in_place(&source, 0, bytemuck::cast_slice(&model)));
let (mut want, mut recorded, mut buffers) = (Vec::new(), None, 0);
for frame in 0..FRAMES {
if frame == 4 { buffers = live(&device); }
// Up to more writes than the store's log remembers, over different spans.
for k in 0..1 + frame % 11 {
let at = (frame * 5 + k * 13) % (WORDS - 4);
let words = [(frame * 100 + k) as u32; 4];
model[at..at + 4].copy_from_slice(&words);
assert!(write_in_place(&source, (at * 4) as u64, bytemuck::cast_slice(&words)));
}
want.extend_from_slice(&model);
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_buffer_to_buffer(&source, 0, &out, (frame * WORDS * 4) as u64, (WORDS * 4) as u64);
if let Some(last) = recorded.replace(encoder.finish()) {
let index = queue.submit([last]);
device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: None }).unwrap();
}
}
queue.submit(recorded);
assert_eq!(live(&device), buffers, "warm frames made no buffers");
let (spares, swapped) = swaps(&source);
assert_eq!(swapped, FRAMES as u64 - 1, "each frame but the first swapped");
assert!(spares <= 2, "{spares} spares");
let got = read(&device, &out);
for (frame, (got, want)) in got.chunks(WORDS * 4).zip(want.chunks(WORDS)).enumerate() {
assert_eq!(got, bytemuck::cast_slice::<u32, u8>(want), "frame {frame}");
}
}
/// A frame that writes the whole buffer while the GPU reads it swaps in a spare and copies
/// nothing forward, and a partial write after it still copies what it leaves: every frame reads
/// exactly what was written by then.
#[test]
fn a_partial_write_after_a_whole_one_reads_the_right_bytes() {
use wgpu::BufferUsages as B;
const WORDS: usize = 64;
let (device, queue) = gpu();
let source = buffer(&device, (WORDS * 4) as u64, B::COPY_SRC | B::COPY_DST);
let frames: [&[(usize, usize)]; 6] = [&[(0, WORDS)], &[(0, WORDS)], &[(8, 12)], &[(0, WORDS)], &[(60, 64), (0, 2)], &[(30, 31)]];
let out = buffer(&device, (WORDS * 4 * frames.len()) as u64, B::COPY_DST | B::MAP_READ);
let store = &source.as_custom::<MetalBuffer>().unwrap().store;
let (mut model, mut want, mut recorded) = ([0u32; WORDS], Vec::new(), None);
for (frame, writes) in frames.iter().enumerate() {
let copied = store.copied();
for (k, &(a, b)) in writes.iter().enumerate() {
let words = vec![(frame * 100 + k + 1) as u32; b - a];
model[a..b].copy_from_slice(&words);
assert!(write_in_place(&source, (a * 4) as u64, bytemuck::cast_slice(&words)));
}
if writes[..] == [(0, WORDS)] { assert_eq!(store.copied(), copied, "frame {frame} wrote everything, so copied nothing"); }
want.extend_from_slice(&model);
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_buffer_to_buffer(&source, 0, &out, (frame * WORDS * 4) as u64, (WORDS * 4) as u64);
if let Some(last) = recorded.replace(encoder.finish()) {
let index = queue.submit([last]);
device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: None }).unwrap();
}
}
queue.submit(recorded);
assert_eq!(swaps(&source).1, frames.len() as u64 - 1, "each frame but the first swapped");
assert!(store.copied() > 0, "partial writes copied what they left");
let got = read(&device, &out);
for (frame, (got, want)) in got.chunks(WORDS * 4).zip(want.chunks(WORDS)).enumerate() {
assert_eq!(got, bytemuck::cast_slice::<u32, u8>(want), "frame {frame}");
}
}
const FILL: &str = "
@group(0) @binding(0) var<uniform> color: vec4<f32>;
@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
return vec4<f32>(vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u)) * 2.0 - 1.0, 0.0, 1.0);
}
@fragment fn fs() -> @location(0) vec4<f32> { return color; }
";
/// A write that swaps a buffer a pass has bound reaches the pass's later draws, though the
/// group isn't set again: the draw before it reads the old color, the one after the new.
#[test]
fn a_pass_rebinds_a_buffer_swapped_under_it() {
let (device, queue) = gpu();
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(FILL.into()) });
let groups = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &[wgpu::BindGroupLayoutEntry {
binding: 0, visibility: wgpu::ShaderStages::FRAGMENT, count: None,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
}] });
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&groups)], immediate_size: 0 });
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None, layout: Some(&layout),
vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] },
fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some("fs"), compilation_options: Default::default(),
targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())] }),
primitive: Default::default(), depth_stencil: None, multisample: Default::default(), multiview_mask: None, cache: None,
});
let color = buffer(&device, 16, wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST);
let group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &groups,
entries: &[wgpu::BindGroupEntry { binding: 0, resource: color.as_entire_binding() }] });
let target = device.create_texture(&wgpu::TextureDescriptor {
label: None, size: wgpu::Extent3d { width: 64, height: 1, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, view_formats: &[],
});
let view = target.create_view(&Default::default());
assert!(write_in_place(&color, 0, bytemuck::cast_slice(&[1.0f32, 0.0, 0.0, 1.0])));
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = clear(&mut encoder, &view);
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &group, &[]);
pass.set_scissor_rect(0, 0, 32, 1);
pass.draw(0..3, 0..1);
assert!(write_in_place(&color, 0, bytemuck::cast_slice(&[0.0f32, 0.0, 1.0, 1.0])));
assert_eq!(swaps(&color).1, 1, "the pass held the storage, so the write swapped it");
pass.set_scissor_rect(32, 0, 32, 1);
pass.draw(0..3, 0..1);
}
let out = buffer(&device, 256, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ);
encoder.copy_texture_to_buffer(target.as_image_copy(), wgpu::TexelCopyBufferInfo {
buffer: &out, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256), rows_per_image: None },
}, target.size());
queue.submit([encoder.finish()]);
let pixels = read(&device, &out);
assert_eq!(pixels[..4], [255, 0, 0, 255], "the first draw read the old color");
assert_eq!(pixels[32 * 4..32 * 4 + 4], [0, 0, 255, 255], "the second the new");
}
/// A queue write lands ahead of the next submit, so an encoder recorded before it and submitted
/// after reads it, as on wgpu: written in place only while nothing recorded uses the buffer.
#[test]
fn a_queue_write_reaches_an_encoder_recorded_before_it() {
use wgpu::BufferUsages as B;
let (device, queue) = gpu();
let source = buffer(&device, 16, B::COPY_SRC | B::COPY_DST);
let out = buffer(&device, 32, B::COPY_DST | B::MAP_READ);
queue.write_buffer(&source, 0, bytemuck::cast_slice(&[1u32; 4]));
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_buffer_to_buffer(&source, 0, &out, 0, 16);
let early = encoder.finish();
queue.write_buffer(&source, 0, bytemuck::cast_slice(&[2u32; 4]));
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_buffer_to_buffer(&source, 0, &out, 16, 16);
queue.submit([early, encoder.finish()]);
let words: Vec<u32> = bytemuck::cast_slice(&read(&device, &out)).to_vec();
assert_eq!(words, [[2u32; 4], [2; 4]].concat());
}
/// A queue write to a buffer only submitted work reads swaps in a spare instead of staging a copy
/// of its own, so the frame after it stays one command buffer, and the submitted work still
/// reads the old bytes.
#[test]
fn a_queue_write_behind_submitted_work_swaps_rather_than_stages() {
use objc2_metal::{MTLCommandBuffer, MTLDevice, MTLEvent, MTLSharedEvent};
use wgpu::BufferUsages as B;
let (device, queue) = gpu();
let shared = device.as_custom::<MetalDevice>().unwrap().shared.clone();
// Holds the GPU until the end, so the first copy is still waiting when the write comes.
let gate = shared.device.newSharedEvent().unwrap();
let wait = shared.command_buffer();
wait.encodeWaitForEvent_value(ProtocolObject::<dyn MTLEvent>::from_ref(&*gate), 1);
wait.commit();
let source = buffer(&device, 16, B::COPY_SRC | B::COPY_DST);
let out = buffer(&device, 32, B::COPY_DST | B::MAP_READ);
let copy = |at| {
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_buffer_to_buffer(&source, 0, &out, at, 16);
encoder.finish()
};
queue.write_buffer(&source, 0, bytemuck::cast_slice(&[1u32; 4]));
queue.submit([copy(0)]);
let before = shared.state.lock().last;
queue.write_buffer(&source, 0, bytemuck::cast_slice(&[2u32; 4]));
queue.submit([copy(16)]);
assert_eq!(shared.state.lock().last, before + 1, "no staged copy of its own");
assert_eq!(swaps(&source).1, 1, "the write swapped storage under the waiting copy");
gate.setSignaledValue(1);
wait.waitUntilCompleted();
let words: Vec<u32> = bytemuck::cast_slice(&read(&device, &out)).to_vec();
assert_eq!(words, [[1u32; 4], [2; 4]].concat());
}
+420
View File
@@ -0,0 +1,420 @@
//! Submission: values on the shared event, the held frame buffer, staged writes, retirement of
//! what command buffers used, and the callbacks that wait on it.
use std::any::Any;
use std::collections::VecDeque;
use std::sync::Arc;
#[cfg(debug_assertions)]
use objc2_foundation::NSString;
use objc2_metal::{
MTLBlitCommandEncoder, MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandEncoder, MTLCommandQueue, MTLDrawable, MTLEvent, MTLSharedEvent,
};
use objc2_quartz_core::CAMetalDrawable;
use objc2::rc::autoreleasepool;
use objc2::runtime::ProtocolObject;
use parking_lot::MutexGuard;
use wgpu::custom::*;
use super::encode::{MetalCommandBuffer, buffer_to_texture};
use super::resource::{BufferRaw, MetalBuffer, MetalTexture};
use super::surface::MetalOutput;
use super::{Obj, Shared};
/// What a command buffer uses, kept alive until it completes.
pub(super) type Keep = Vec<Arc<dyn Any + Send + Sync>>;
/// Frames the CPU may run ahead of the GPU.
const IN_FLIGHT: usize = 2;
/// Emptied keep lists kept for the next encoders, so a steady frame allocates none.
const SPARE_KEEPS: usize = 8;
enum Callback {
Map(BufferMapCallback),
Done(BoxSubmittedWorkDoneCallback),
}
/// A committed command buffer and the resources it references without retaining.
struct Pending {
value: u64,
cb: Obj<dyn MTLCommandBuffer>,
keep: Keep,
drawable: Option<Obj<dyn CAMetalDrawable>>,
}
/// A frame's command buffer waiting for `present` so `presentDrawable` lands on the same buffer.
struct Held {
cb: Obj<dyn MTLCommandBuffer>,
value: u64,
keep: Keep,
}
#[derive(Default)]
pub(crate) struct State {
/// The value the last submitted command buffer signals when it completes.
pub(super) last: u64,
/// The highest value whose command buffer has reached `Completed` or `Error` and been retired.
retired: u64,
/// A frame's command buffer waiting for its drawable's present. While one is held it is the
/// last assigned value, and every other commit commits it first.
held: Option<Held>,
uploads: Option<Uploads>,
retire: VecDeque<Pending>,
callbacks: VecDeque<(u64, Callback)>,
frames: VecDeque<u64>,
pub(super) spare: Vec<Keep>,
}
/// Writes staged since the last submit, committed ahead of it.
struct Uploads {
blit: Obj<dyn MTLBlitCommandEncoder>,
cb: Obj<dyn MTLCommandBuffer>,
keep: Keep,
}
fn completed(cb: &ProtocolObject<dyn MTLCommandBuffer>) -> bool {
matches!(cb.status(), MTLCommandBufferStatus::Completed | MTLCommandBufferStatus::Error)
}
impl std::fmt::Debug for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("State").field("last", &self.last).field("held", &self.held.is_some()).finish_non_exhaustive()
}
}
impl Shared {
fn lock(&self) -> MutexGuard<'_, State> { self.state.lock() }
/// A command buffer that doesn't retain what it uses. Made in a pool of its own, so the
/// buffer is freed when its last owner here drops it rather than when the thread's pool drains.
pub(super) fn command_buffer(&self) -> Obj<dyn MTLCommandBuffer> {
autoreleasepool(|_| self.queue.commandBufferWithUnretainedReferences()).expect("a Metal command buffer")
}
/// An empty keep list, reusing one a retired command buffer emptied.
pub(super) fn keep_list(&self) -> Keep {
self.lock().spare.pop().unwrap_or_else(|| Vec::with_capacity(32))
}
/// Empties `keep`, releasing what it held, and saves it for a later encoder.
pub(super) fn recycle(&self, mut keep: Keep) {
keep.clear();
if keep.capacity() == 0 { return }
let mut st = self.lock();
if st.spare.len() < SPARE_KEEPS { st.spare.push(keep); }
}
/// Signals `value` on the shared event, commits `cb`, and tracks `cb` with its unretained
/// resources until Metal marks `cb` completed.
fn commit_pending(
&self,
st: &mut State,
value: u64,
cb: Obj<dyn MTLCommandBuffer>,
keep: Keep,
drawable: Option<Obj<dyn CAMetalDrawable>>,
) {
cb.encodeSignalEvent_value(ProtocolObject::<dyn MTLEvent>::from_ref(&*self.event), value);
cb.commit();
st.retire.push_back(Pending { value, cb, keep, drawable });
}
fn flush_held(&self, st: &mut State) {
if let Some(Held { cb, value, keep }) = st.held.take() {
self.commit_pending(st, value, cb, keep, None);
}
}
/// Commits a held buffer whose drawable was dropped or never presented.
pub(super) fn flush(&self) {
let mut st = self.lock();
self.flush_held(&mut st);
}
fn commit_uploads(&self, st: &mut State) {
let Some(Uploads { blit, cb, keep }) = st.uploads.take() else { return };
blit.endEncoding();
st.last += 1;
let value = st.last;
self.commit_pending(st, value, cb, keep, None);
}
/// Encodes a staged write into the blit buffer the next submit commits first.
pub(super) fn upload(
&self,
encode: impl FnOnce(&ProtocolObject<dyn MTLBlitCommandEncoder>),
keep: impl IntoIterator<Item = Arc<dyn Any + Send + Sync>>,
) {
let mut st = self.lock();
let State { uploads, spare, .. } = &mut *st;
let uploads = uploads.get_or_insert_with(|| {
let cb = self.command_buffer();
let blit = autoreleasepool(|_| cb.blitCommandEncoder()).expect("a Metal blit encoder");
#[cfg(debug_assertions)]
{
cb.setLabel(Some(&NSString::from_str("rune metal uploads")));
blit.setLabel(Some(&NSString::from_str("rune metal uploads blit")));
}
let keep = spare.pop().unwrap_or_else(|| Vec::with_capacity(8));
Uploads { blit, cb, keep }
});
encode(&uploads.blit);
uploads.keep.extend(keep);
}
fn after(&self, callback: Callback) {
let mut st = self.lock();
let at = st.last;
st.callbacks.push_back((at, callback));
}
/// Releases what completed command buffers used and runs the callbacks waiting on them.
/// One at a time, outside the lock: callbacks may call back into the device. Returns the
/// value it retired up to.
pub(super) fn retire(&self) -> u64 { self.retire_inner(false) }
/// Retires completed command buffers from the front of `st.retire`. When `check_unsignaled`
/// is false, skips `cb.status()` on command buffers whose shared-event value has not yet
/// signaled (a command buffer cannot complete before its signal); after `waitUntilCompleted`
/// it checks every entry so an errored buffer that skipped its signal still retires.
fn retire_inner(&self, check_unsignaled: bool) -> u64 {
let signaled = if check_unsignaled { u64::MAX } else { self.event.signaledValue() };
let mut emptied: Option<Keep> = None;
let (done, has_callbacks) = loop {
let pending = {
let mut st = self.lock();
if let Some(keep) = emptied.take()
&& st.spare.len() < SPARE_KEEPS
{
st.spare.push(keep);
}
if st.retire.front().is_some_and(|p| p.value <= signaled && completed(&p.cb)) {
if let Some(p) = st.retire.pop_front() {
st.retired = st.retired.max(p.value);
Some(p)
} else {
None
}
} else {
let done = st.retired;
let has_cb = st.callbacks.front().is_some_and(|(at, _)| *at <= done);
break (done, has_cb);
}
};
let Some(Pending { cb, mut keep, drawable, .. }) = pending else { continue };
// Drop the completed command buffer before any object it referenced without retaining.
drop(cb);
drop(drawable);
keep.clear();
if keep.capacity() > 0 { emptied = Some(keep); }
};
if has_callbacks {
loop {
let next = {
let mut st = self.lock();
if st.callbacks.front().is_some_and(|(at, _)| *at <= done) { st.callbacks.pop_front() } else { None }
};
match next {
Some((_, Callback::Map(f))) => f(Ok(())),
Some((_, Callback::Done(f))) => f(),
None => break,
}
}
}
done
}
pub(super) fn poll(&self, poll: wgpu::wgt::PollType<u64>) -> Result<wgpu::PollStatus, wgpu::PollError> {
let wgpu::wgt::PollType::Wait { submission_index, timeout } = poll else {
// Empty only as of the value retire ran callbacks up to: work finishing after it
// still has callbacks to run, so the caller polls again.
let done = self.retire();
let st = self.lock();
let idle = done >= st.last && st.retire.is_empty() && st.held.is_none() && st.callbacks.is_empty();
return Ok(if idle { wgpu::PollStatus::QueueEmpty } else { wgpu::PollStatus::Poll });
};
let last = {
let mut st = self.lock();
self.flush_held(&mut st);
st.last
};
let target = submission_index.unwrap_or(last);
if target > last { return Err(wgpu::PollError::WrongSubmissionIndex(target, last)); }
if let Some(t) = timeout {
if t.is_zero() {
let done = self.retire();
if done < target { return Err(wgpu::PollError::Timeout); }
let st = self.lock();
let empty = st.retire.is_empty() && st.held.is_none() && st.callbacks.is_empty();
return Ok(if empty { wgpu::PollStatus::QueueEmpty } else { wgpu::PollStatus::WaitSucceeded });
}
let ms = u64::try_from(t.as_millis()).unwrap_or(u64::MAX).max(1);
if self.event.signaledValue() < target && !self.event.waitUntilSignaledValue_timeoutMS(target, ms) {
return Err(wgpu::PollError::Timeout);
}
}
// Wait until Metal marks every command buffer through `target` completed: the shared event
// signals on the GPU before Metal finishes completing the command buffer, so retiring or
// dropping resources on the event alone frees them while the command buffer still tracks them.
loop {
let cb = {
let st = self.lock();
st.retire.iter().find(|p| p.value <= target && !completed(&p.cb)).map(|p| p.cb.clone())
};
let Some(cb) = cb else { break };
cb.waitUntilCompleted();
}
self.retire_inner(true);
let st = self.lock();
let empty = st.retire.is_empty() && st.held.is_none() && st.callbacks.is_empty();
Ok(if empty { wgpu::PollStatus::QueueEmpty } else { wgpu::PollStatus::WaitSucceeded })
}
/// Waits until at most `IN_FLIGHT - 1` presented frames are still on the GPU.
pub(super) fn pace(&self) {
let oldest = {
let mut st = self.lock();
if st.frames.len() < IN_FLIGHT { return }
st.frames.pop_front()
};
if let Some(at) = oldest.filter(|at| self.event.signaledValue() < *at) {
self.event.waitUntilSignaledValue_timeoutMS(at, 1000);
}
}
pub(super) fn map_after_work(&self, callback: BufferMapCallback) { self.after(Callback::Map(callback)); }
/// Stamps and commits a buffer recorded outside an encoder, as a submit would.
pub(super) fn commit(&self, cb: Obj<dyn MTLCommandBuffer>) {
{
let mut st = self.lock();
self.flush_held(&mut st);
self.commit_uploads(&mut st);
st.last += 1;
let value = st.last;
self.commit_pending(&mut st, value, cb, Vec::new(), None);
}
self.retire();
}
/// Pending command buffers waiting for completion, for tests.
#[cfg(test)]
pub(super) fn pending_cbs(&self) -> Vec<(u64, Obj<dyn MTLCommandBuffer>)> {
self.lock().retire.iter().map(|p| (p.value, p.cb.clone())).collect()
}
}
impl Drop for Shared {
/// Runs what was recorded and waits for Metal to complete every command buffer before
/// releasing their resources and the device's own buffers, since command buffers don't
/// retain what they use.
fn drop(&mut self) {
{
let mut st = self.lock();
self.flush_held(&mut st);
self.commit_uploads(&mut st);
}
loop {
let cb = {
let st = self.lock();
st.retire.iter().find(|p| !completed(&p.cb)).map(|p| p.cb.clone())
};
let Some(cb) = cb else { break };
cb.waitUntilCompleted();
}
self.retire_inner(true);
}
}
#[derive(Debug)]
pub(crate) struct MetalQueue(pub(super) Arc<Shared>);
impl QueueInterface for MetalQueue {
#[allow(unsafe_code)]
fn write_buffer(&self, buffer: &DispatchBuffer, offset: wgpu::BufferAddress, data: &[u8]) {
if data.is_empty() { return }
let store = &buffer.as_custom::<MetalBuffer>().expect("a Metal buffer").store;
// Written now if nothing recorded uses the storage, or into a spare if only submitted
// work does: an encoder recorded earlier and submitted later must read these bytes too.
// Staged, it pins the storage, since a later swap would copy the rest without this write.
// An encoder counts in `recording` before it reads any storage, which it does under the
// store's lock, the one `may_swap` is asked under.
let idle = || self.0.recording.load(std::sync::atomic::Ordering::Acquire) == 0;
if store.write_ahead(&self.0, offset, data, idle) { return }
let target = store.gpu_write();
let staging = Arc::new(BufferRaw::with_bytes(&self.0, data, Some("rune metal write_buffer")));
self.0.upload(|blit| {
// SAFETY: both ranges are in bounds; wgpu checked the target's.
unsafe { blit.copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size(&staging.raw, 0, &target.raw, offset as usize, data.len()) }
}, [staging.clone() as _, target.clone() as _]);
}
fn create_staging_buffer(&self, _: wgpu::BufferSize) -> Option<DispatchQueueWriteBuffer> { None }
fn validate_write_buffer(&self, _: &DispatchBuffer, _: wgpu::BufferAddress, _: wgpu::BufferSize) -> Option<()> { Some(()) }
fn write_staging_buffer(&self, _: &DispatchBuffer, _: wgpu::BufferAddress, _: &DispatchQueueWriteBuffer) {
super::unsupported!("Queue::write_buffer_with")
}
fn write_texture(&self, dst: wgpu::TexelCopyTextureInfo<'_>, data: &[u8], layout: wgpu::TexelCopyBufferLayout, size: wgpu::Extent3d) {
let data = &data[layout.offset as usize..];
if data.is_empty() || size.width == 0 || size.height == 0 || size.depth_or_array_layers == 0 { return }
let texture = dst.texture.as_custom::<MetalTexture>().expect("a Metal texture").raw.clone();
let staging = Arc::new(BufferRaw::with_bytes(&self.0, data, Some("rune metal write_texture")));
let layout = wgpu::TexelCopyBufferLayout { offset: 0, ..layout };
self.0.upload(|blit| buffer_to_texture(blit, &staging.raw, layout, &texture, dst.mip_level, dst.origin, size), [staging.clone() as _, texture.clone() as _]);
}
fn submit(&self, command_buffers: &mut dyn Iterator<Item = DispatchCommandBuffer>) -> u64 {
let last = {
let mut st = self.0.lock();
self.0.flush_held(&mut st);
self.0.commit_uploads(&mut st);
for buffer in command_buffers {
let Some(recorded) = buffer.as_custom::<MetalCommandBuffer>().and_then(MetalCommandBuffer::take) else { continue };
self.0.flush_held(&mut st);
let drawable = recorded.drawable;
let (cb, keep) = recorded.close();
st.last += 1;
let value = st.last;
if drawable {
st.held = Some(Held { cb, value, keep });
} else {
self.0.commit_pending(&mut st, value, cb, keep, None);
}
}
st.last
};
self.0.retire();
last
}
fn get_timestamp_period(&self) -> f32 { 1.0 }
fn on_submitted_work_done(&self, callback: BoxSubmittedWorkDoneCallback) { self.0.after(Callback::Done(callback)) }
fn compact_blas(&self, _: &DispatchBlas) -> (Option<u64>, DispatchBlas) { super::unsupported!("ray tracing") }
fn present(&self, detail: &DispatchSurfaceOutputDetail) {
let Some(output) = detail.as_custom::<MetalOutput>() else { return };
let Some(drawable) = &output.drawable else { return };
let mtl_drawable = ProtocolObject::<dyn MTLDrawable>::from_ref(&**drawable);
let wait_cb = {
let mut st = self.0.lock();
let Held { cb, value, keep } = match st.held.take() {
Some(held) => held,
None => {
let cb = self.0.command_buffer();
#[cfg(debug_assertions)]
cb.setLabel(Some(&NSString::from_str("rune metal present")));
st.last += 1;
Held { cb, value: st.last, keep: Vec::new() }
}
};
if !output.transaction {
cb.presentDrawable(mtl_drawable);
}
let wait_cb = output.transaction.then(|| cb.clone());
self.0.commit_pending(&mut st, value, cb, keep, Some(drawable.clone()));
st.frames.push_back(value);
wait_cb
};
if let Some(cb) = wait_cb {
cb.waitUntilScheduled();
mtl_drawable.present();
}
}
}
+147
View File
@@ -0,0 +1,147 @@
//! The CAMetalLayer a surface presents into, and its drawables. The layer comes from
//! raw-window-metal as wgpu-hal's does: a sublayer of the view's layer that follows the view's
//! bounds and the screen's scale as they change.
#![allow(unsafe_code)]
use std::sync::Arc;
use objc2_core_foundation::CGSize;
use objc2_quartz_core::{CALayer, CAMetalDrawable, CAMetalLayer};
use objc2::rc::{Retained, autoreleasepool};
use parking_lot::Mutex;
use raw_window_metal::Layer;
use wgpu::custom::*;
use super::resource::{MetalTexture, TextureRaw, pixel_format};
use super::{MetalDevice, Obj, Shared, send_sync};
#[derive(Debug)]
pub(crate) struct MetalSurface {
layer: Retained<CAMetalLayer>,
configured: Mutex<Option<(Arc<Shared>, wgpu::TextureFormat)>>,
}
#[derive(Debug)]
pub(crate) struct MetalOutput {
pub(super) drawable: Option<Obj<dyn CAMetalDrawable>>,
/// The layer's `presentsWithTransaction` when the drawable was acquired.
pub(super) transaction: bool,
shared: Option<Arc<Shared>>,
}
send_sync!(MetalSurface, MetalOutput);
/// A surface on a CAMetalLayer as given, or on one filling an AppKit or UIKit view (on the main thread).
pub(super) unsafe fn create(target: wgpu::SurfaceTargetUnsafe) -> DispatchSurface {
// SAFETY: the caller hands a live layer or view.
let layer = unsafe {
match target {
wgpu::SurfaceTargetUnsafe::CoreAnimationLayer(layer) => Layer::from_ca_layer(std::ptr::NonNull::new(layer).expect("a CALayer")),
wgpu::SurfaceTargetUnsafe::RawHandle { raw_window_handle: wgpu::rwh::RawWindowHandle::AppKit(handle), .. } => Layer::from_ns_view(handle.ns_view),
wgpu::SurfaceTargetUnsafe::RawHandle { raw_window_handle: wgpu::rwh::RawWindowHandle::UiKit(handle), .. } => Layer::from_ui_view(handle.ui_view),
_ => panic!("RUNE_GPU_BACKEND=metal needs an AppKit or UIKit view or a CALayer"),
}
};
// SAFETY: `into_raw` hands over its retain of a CAMetalLayer.
let layer = unsafe { Retained::from_raw(layer.into_raw().as_ptr().cast::<CAMetalLayer>()) }.expect("a CAMetalLayer");
DispatchSurface::custom(MetalSurface { layer, configured: Mutex::new(None) })
}
impl MetalSurface {
pub(super) fn layer(&self) -> &CAMetalLayer { &self.layer }
}
/// The `NSWindow` hosting `layer`: the first ancestor layer with a delegate is the backing
/// `NSView`, and its window is the one.
#[cfg(target_os = "macos")]
fn hosting_window(layer: &CALayer) -> Option<Retained<objc2::runtime::NSObject>> {
use objc2::{Message, msg_send};
let mut current = Some(layer.retain());
while let Some(layer) = current {
if let Some(delegate) = layer.delegate() {
// SAFETY: a layer's delegate with a `window` is its NSView.
return unsafe { msg_send![&*delegate, window] };
}
current = layer.superlayer();
}
None
}
/// Whether the window hosting `layer` is fully covered or hidden, where `nextDrawable` would
/// wait out its timeout for a vsync that never comes. On iOS the host stops its display link
/// while the app is in the background, so there is nothing to check.
#[cfg(target_os = "macos")]
fn occluded(layer: &CALayer) -> bool {
const VISIBLE: usize = 1 << 1;
let Some(window) = hosting_window(layer) else { return false };
// SAFETY: `occlusionState` is an NSWindow property returning NSWindowOcclusionState.
let state: usize = unsafe { objc2::msg_send![&*window, occlusionState] };
state & VISIBLE == 0
}
#[cfg(not(target_os = "macos"))]
fn occluded(_: &CALayer) -> bool { false }
impl SurfaceInterface for MetalSurface {
fn get_capabilities(&self, _: &DispatchAdapter) -> wgpu::SurfaceCapabilities {
use wgpu::TextureFormat as F;
let formats = vec![F::Bgra8Unorm, F::Bgra8UnormSrgb, F::Rgba16Float, F::Rgb10a2Unorm];
wgpu::SurfaceCapabilities {
format_capabilities: formats.iter().map(|&format| wgpu::SurfaceFormatCapabilities { format, color_spaces: wgpu::SurfaceColorSpaces::SRGB }).collect(),
formats,
present_modes: vec![wgpu::PresentMode::Fifo, wgpu::PresentMode::Immediate],
alpha_modes: vec![wgpu::CompositeAlphaMode::Opaque, wgpu::CompositeAlphaMode::PostMultiplied],
usages: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,
}
}
fn configure(&self, device: &DispatchDevice, config: &wgpu::SurfaceConfiguration) {
let device = device.as_custom::<MetalDevice>().expect("a Metal device");
assert!(matches!(config.color_space, wgpu::SurfaceColorSpace::Auto | wgpu::SurfaceColorSpace::Srgb),
"RUNE_GPU_BACKEND=metal: surface color space {:?}", config.color_space);
*self.configured.lock() = Some((device.shared.clone(), config.format));
let layer = &self.layer;
layer.setDevice(Some(&device.shared.device));
layer.setPixelFormat(pixel_format(config.format));
layer.setFramebufferOnly(config.usage == wgpu::TextureUsages::RENDER_ATTACHMENT);
match config.alpha_mode {
wgpu::CompositeAlphaMode::Opaque => layer.setOpaque(true),
wgpu::CompositeAlphaMode::PostMultiplied => layer.setOpaque(false),
_ => {}
}
// The layer keeps the colour space its window gave it (sRGB, `pin_contents_top_left`): a
// reconfigure, as on every resize, must not untag it.
layer.setMaximumDrawableCount(config.desired_maximum_frame_latency.clamp(1, 2) as usize + 1);
layer.setDrawableSize(CGSize::new(f64::from(config.width), f64::from(config.height)));
// iOS layers are always display-synced, and keep the drawable timeout as wgpu-hal does: with
// no occlusion check, a host that misses a background transition gets a skipped frame
// rather than a main thread waiting forever.
#[cfg(target_os = "macos")]
{
layer.setAllowsNextDrawableTimeout(false);
layer.setDisplaySyncEnabled(!matches!(config.present_mode, wgpu::PresentMode::Immediate | wgpu::PresentMode::AutoNoVsync));
}
}
fn get_current_texture(&self) -> (Option<DispatchTexture>, wgpu::SurfaceStatus, DispatchSurfaceOutputDetail) {
let (shared, format) = match self.configured.lock().clone() {
Some((shared, format)) => (Some(shared), format),
None => (None, wgpu::TextureFormat::Bgra8Unorm),
};
let none = |status, shared| (None, status, DispatchSurfaceOutputDetail::custom(MetalOutput { drawable: None, transaction: false, shared }));
if occluded(&self.layer) { return none(wgpu::SurfaceStatus::Occluded, shared) }
if let Some(shared) = &shared { shared.pace(); }
let Some(drawable) = autoreleasepool(|_| self.layer.nextDrawable()) else { return none(wgpu::SurfaceStatus::Timeout, shared) };
let texture = MetalTexture { raw: Arc::new(TextureRaw::drawable(drawable.texture(), format)) };
let output = MetalOutput { drawable: Some(drawable), transaction: self.layer.presentsWithTransaction(), shared };
(Some(DispatchTexture::custom(texture)), wgpu::SurfaceStatus::Good, DispatchSurfaceOutputDetail::custom(output))
}
}
impl SurfaceOutputDetailInterface for MetalOutput {
fn texture_discard(&self) {
if let Some(shared) = &self.shared { shared.flush(); }
}
fn texture_release(&self) {}
}
+490
View File
@@ -0,0 +1,490 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use super::bench::{clear, gpu};
use super::resource::MetalBuffer;
use super::*;
const W: u32 = 64;
const H: u32 = 32;
fn shared(device: &wgpu::Device) -> Arc<Shared> { device.as_custom::<MetalDevice>().unwrap().shared.clone() }
fn last(device: &wgpu::Device) -> u64 { shared(device).state.lock().last }
fn wgpu_metal() -> (wgpu::Device, wgpu::Queue) {
let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
descriptor.backends = wgpu::Backends::METAL;
let instance = wgpu::Instance::new(descriptor);
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).unwrap();
// The iOS simulator passes fewer inter-stage variables than wgpu's defaults ask for.
let desc = wgpu::DeviceDescriptor { required_limits: adapter.limits(), ..Default::default() };
pollster::block_on(adapter.request_device(&desc)).unwrap()
}
fn texture(device: &wgpu::Device, format: wgpu::TextureFormat, (width, height): (u32, u32), usage: wgpu::TextureUsages) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: None, size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, format, usage, view_formats: &[],
})
}
fn buffer(device: &wgpu::Device, size: u64, usage: wgpu::BufferUsages) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor { label: None, size, usage, mapped_at_creation: false })
}
fn copy_out(encoder: &mut wgpu::CommandEncoder, from: &wgpu::Texture, to: &wgpu::Buffer) {
encoder.copy_texture_to_buffer(from.as_image_copy(), wgpu::TexelCopyBufferInfo {
buffer: to, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256), rows_per_image: Some(H) },
}, from.size());
}
fn read(device: &wgpu::Device, buffer: &wgpu::Buffer) -> Vec<u8> {
let slice = buffer.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let out = slice.get_mapped_range().unwrap().to_vec();
buffer.unmap();
out
}
const SCENE: &str = r#"
struct U { color: vec4<f32>, offset: vec2<f32> };
@group(0) @binding(0) var<uniform> u: U;
@group(0) @binding(1) var<storage, read> weights: array<f32>;
@group(1) @binding(0) var tex: texture_2d<f32>;
@group(1) @binding(1) var samp: sampler;
struct VOut { @builtin(position) pos: vec4<f32>, @location(0) uv: vec2<f32>, @location(1) tint: vec4<f32> };
@vertex fn vs(@builtin(vertex_index) vi: u32, @location(0) rect: vec4<f32>, @location(1) tint: vec4<f32>) -> VOut {
let corner = vec2<f32>(f32(vi & 1u), f32(vi >> 1u));
let xy = rect.xy + corner * rect.zw + u.offset;
var o: VOut;
o.pos = vec4<f32>(xy.x * 2.0 - 1.0, 1.0 - xy.y * 2.0, 0.0, 1.0);
o.uv = corner;
o.tint = tint;
return o;
}
struct FOut { @location(0) color: vec4<f32>, @location(1) mask: vec4<f32> };
@fragment fn fs(i: VOut) -> FOut {
let n = arrayLength(&weights);
var o: FOut;
o.color = textureSample(tex, samp, i.uv) * i.tint * u.color * weights[n - 1u];
o.mask = vec4<f32>(f32(n) / 8.0, 0.0, 0.0, 1.0);
return o;
}
"#;
/// A frame using most of what Rune's renderers do: two targets, instanced vertex buffers, a
/// dynamic uniform offset, a runtime-sized storage array, a sampled texture written through the
/// queue, blending, a scissor, and buffer and texture copies on the way out. Returns the color
/// target (through a texture-to-texture copy) and the mask target, as read back.
fn scene(device: &wgpu::Device, queue: &wgpu::Queue) -> (Vec<u8>, Vec<u8>) {
use wgpu::{BufferUsages as B, ShaderStages as S, TextureUsages as T};
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("scene"), source: wgpu::ShaderSource::Wgsl(SCENE.into()) });
let uniform = |dynamic| wgpu::BindGroupLayoutEntry { binding: 0, visibility: S::VERTEX_FRAGMENT, count: None,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: dynamic, min_binding_size: None } };
let globals = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &[
uniform(true),
wgpu::BindGroupLayoutEntry { binding: 1, visibility: S::FRAGMENT, count: None,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: None } },
] });
let images = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &[
wgpu::BindGroupLayoutEntry { binding: 0, visibility: S::FRAGMENT, count: None, ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false } },
wgpu::BindGroupLayoutEntry { binding: 1, visibility: S::FRAGMENT, count: None, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering) },
] });
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&globals), Some(&images)], immediate_size: 0 });
let attributes = wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4];
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("scene"),
layout: Some(&layout),
vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout { array_stride: 32, step_mode: wgpu::VertexStepMode::Instance, attributes: &attributes })] },
fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some("fs"), compilation_options: Default::default(), targets: &[
Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Rgba8Unorm, blend: Some(wgpu::BlendState::ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL }),
Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::R8Unorm, blend: None, write_mask: wgpu::ColorWrites::ALL }),
] }),
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleStrip, ..Default::default() },
depth_stencil: None,
multisample: Default::default(),
multiview_mask: None,
cache: None,
});
let uniforms = buffer(device, 512, B::UNIFORM | B::COPY_DST);
let records: [[f32; 8]; 2] = [[0.0; 8], [1.0, 0.8, 0.6, 0.9, 0.05, 0.1, 0.0, 0.0]];
queue.write_buffer(&uniforms, 0, bytemuck::cast_slice(&records[0]));
queue.write_buffer(&uniforms, 256, bytemuck::cast_slice(&records[1]));
// Staged through a copy, so the shader sees the second write's weights.
let weights = buffer(device, 32, B::STORAGE | B::COPY_DST);
let staging = buffer(device, 32, B::COPY_SRC | B::COPY_DST);
queue.write_buffer(&staging, 0, bytemuck::cast_slice(&[0.1f32, 0.2, 0.3, 0.75, 0.0, 0.0, 0.0, 0.0]));
let instances = buffer(device, 64, B::VERTEX | B::COPY_DST);
let rects: [[f32; 8]; 2] = [[0.1, 0.1, 0.5, 0.6, 1.0, 1.0, 1.0, 1.0], [0.3, 0.4, 0.6, 0.5, 0.2, 0.9, 0.4, 0.7]];
queue.write_buffer(&instances, 0, bytemuck::cast_slice(&rects));
let image = texture(device, wgpu::TextureFormat::Rgba8Unorm, (2, 2), T::TEXTURE_BINDING | T::COPY_DST);
let texels: [u8; 16] = [255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 128];
queue.write_texture(image.as_image_copy(), &texels, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(8), rows_per_image: None }, image.size());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() });
let image_view = image.create_view(&Default::default());
let group0 = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &globals, entries: &[
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &uniforms, offset: 0, size: wgpu::BufferSize::new(32) }) },
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &weights, offset: 0, size: wgpu::BufferSize::new(16) }) },
] });
let group1 = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &images, entries: &[
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&image_view) },
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&sampler) },
] });
let color = texture(device, wgpu::TextureFormat::Rgba8Unorm, (W, H), T::RENDER_ATTACHMENT | T::COPY_SRC);
let mask = texture(device, wgpu::TextureFormat::R8Unorm, (W, H), T::RENDER_ATTACHMENT | T::COPY_SRC);
let copy = texture(device, wgpu::TextureFormat::Rgba8Unorm, (W, H), T::COPY_DST | T::COPY_SRC);
let (color_view, mask_view) = (color.create_view(&Default::default()), mask.create_view(&Default::default()));
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_buffer_to_buffer(&staging, 0, &weights, 0, 32);
{
let attachment = |view, load| Some(wgpu::RenderPassColorAttachment { view, resolve_target: None, depth_slice: None,
ops: wgpu::Operations { load, store: wgpu::StoreOp::Store } });
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[attachment(&color_view, wgpu::LoadOp::Clear(wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 })),
attachment(&mask_view, wgpu::LoadOp::Clear(wgpu::Color::BLACK))],
..Default::default()
});
// Groups before the pipeline: they land at the slots it reads.
pass.set_bind_group(1, &group1, &[]);
pass.set_bind_group(0, &group0, &[256]);
pass.set_pipeline(&pipeline);
pass.set_vertex_buffer(0, instances.slice(..));
pass.set_scissor_rect(4, 2, W - 8, H - 4);
pass.draw(0..4, 0..2);
}
encoder.copy_texture_to_texture(color.as_image_copy(), copy.as_image_copy(), color.size());
let (color_out, mask_out) = (buffer(device, 256 * u64::from(H), B::COPY_DST | B::MAP_READ), buffer(device, 256 * u64::from(H), B::COPY_DST | B::MAP_READ));
copy_out(&mut encoder, &copy, &color_out);
copy_out(&mut encoder, &mask, &mask_out);
queue.submit([encoder.finish()]);
(read(device, &color_out), read(device, &mask_out))
}
#[test]
fn a_scene_matches_wgpus_pixel_for_pixel() {
let (device, queue) = gpu();
let (color, mask) = scene(&device, &queue);
let (wgpu_device, wgpu_queue) = wgpu_metal();
let (want_color, want_mask) = scene(&wgpu_device, &wgpu_queue);
let at = |x: u32, y: u32| (y * 256 + x * 4) as usize;
assert_ne!(color[at(20, 12)..at(20, 12) + 4], [26, 51, 77, 255], "the quads drew");
assert_eq!(&color[at(0, 0)..at(0, 0) + 4], &[26, 51, 77, 255], "the scissor kept the clear");
assert_eq!(mask[(12 * 256 + 20) as usize], 128, "the shader saw four weights");
assert!(color == want_color, "color differs from wgpu's at {:?}", color.iter().zip(&want_color).position(|(a, b)| a != b));
assert!(mask == want_mask, "mask differs from wgpu's at {:?}", mask.iter().zip(&want_mask).position(|(a, b)| a != b));
}
const IMMEDIATE_SCENE: &str = r#"
struct I { offset: vec2<f32>, scale: f32, alpha: f32, tint: vec4<f32> };
var<immediate> i: I;
@group(0) @binding(0) var<uniform> base: vec4<f32>;
@vertex fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
let corner = vec2<f32>(f32(vi & 1u), f32(vi >> 1u));
let xy = i.offset + corner * i.scale;
return vec4<f32>(xy.x * 2.0 - 1.0, 1.0 - xy.y * 2.0, 0.0, 1.0);
}
@fragment fn fs() -> @location(0) vec4<f32> {
return vec4<f32>(base.rgb * i.tint.rgb, i.alpha);
}
"#;
/// Two quads whose immediates both stages read beside a bind group (so the group's slots sit
/// after the immediates'), the second changing only part of them. Returns the target, read back.
fn immediate_scene(device: &wgpu::Device, queue: &wgpu::Queue) -> Vec<u8> {
use wgpu::{BufferUsages as B, ShaderStages as S, TextureUsages as T};
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("immediates"), source: wgpu::ShaderSource::Wgsl(IMMEDIATE_SCENE.into()) });
let group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &[wgpu::BindGroupLayoutEntry {
binding: 0, visibility: S::FRAGMENT, count: None,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
}] });
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&group_layout)], immediate_size: 32 });
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("immediates"),
layout: Some(&layout),
vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] },
fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some("fs"), compilation_options: Default::default(), targets: &[
Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Rgba8Unorm, blend: Some(wgpu::BlendState::ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL }),
] }),
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleStrip, ..Default::default() },
depth_stencil: None,
multisample: Default::default(),
multiview_mask: None,
cache: None,
});
let uniform = buffer(device, 16, B::UNIFORM | B::COPY_DST);
queue.write_buffer(&uniform, 0, bytemuck::cast_slice(&[1.0f32, 0.8, 0.5, 1.0]));
let group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &group_layout, entries: &[
wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
] });
let target = texture(device, wgpu::TextureFormat::Rgba8Unorm, (W, H), T::RENDER_ATTACHMENT | T::COPY_SRC);
let view = target.create_view(&Default::default());
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, resolve_target: None, depth_slice: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 }), store: wgpu::StoreOp::Store } })],
..Default::default()
});
// The group before the pipeline: it lands after the immediates' slot.
pass.set_bind_group(0, &group, &[]);
pass.set_pipeline(&pipeline);
pass.set_immediates(0, bytemuck::cast_slice(&[0.1f32, 0.1, 0.4, 0.9, 0.2, 1.0, 0.6, 1.0]));
pass.draw(0..4, 0..1);
// Only the offset and the tint's first channel change.
pass.set_immediates(0, bytemuck::cast_slice(&[0.5f32, 0.4]));
pass.set_immediates(16, bytemuck::cast_slice(&[0.9f32]));
pass.draw(0..4, 0..1);
}
let out = buffer(device, 256 * u64::from(H), B::COPY_DST | B::MAP_READ);
copy_out(&mut encoder, &target, &out);
queue.submit([encoder.finish()]);
read(device, &out)
}
#[test]
fn immediates_match_wgpus_pixel_for_pixel() {
let adapter = pollster::block_on(instance().request_adapter(&Default::default())).unwrap();
assert!(adapter.features().contains(wgpu::Features::IMMEDIATES));
assert_eq!(adapter.limits().max_immediate_size, 4096, "what setVertexBytes takes");
let (device, queue) = gpu();
let pixels = immediate_scene(&device, &queue);
let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
descriptor.backends = wgpu::Backends::METAL;
let theirs = pollster::block_on(wgpu::Instance::new(descriptor).request_adapter(&Default::default())).unwrap();
let desc = wgpu::DeviceDescriptor { required_features: wgpu::Features::IMMEDIATES, required_limits: theirs.limits(), ..Default::default() };
let (wgpu_device, wgpu_queue) = pollster::block_on(theirs.request_device(&desc)).unwrap();
let want = immediate_scene(&wgpu_device, &wgpu_queue);
let at = |x: u32, y: u32| (y * 256 + x * 4) as usize;
assert_ne!(pixels[at(10, 6)..at(10, 6) + 4], [26, 51, 77, 255], "the first quad drew");
assert_ne!(pixels[at(40, 20)..at(40, 20) + 4], pixels[at(10, 6)..at(10, 6) + 4], "the second, in another tint");
assert!(pixels == want, "differs from wgpu's at {:?}", pixels.iter().zip(&want).position(|(a, b)| a != b));
}
#[test]
#[allow(unsafe_code)]
fn a_frame_is_one_command_buffer_and_writes_land() {
let (device, queue) = gpu();
let target = texture(&device, wgpu::TextureFormat::Bgra8UnormSrgb, (64, 64), wgpu::TextureUsages::RENDER_ATTACHMENT);
queue.submit([]);
assert_eq!(last(&device), 1, "a new texture's zeroing commits on the next submit");
let empty = device.create_command_encoder(&Default::default());
queue.submit([empty.finish()]);
assert_eq!(last(&device), 1, "an empty encoder commits nothing");
let view = target.create_view(&Default::default());
let mut encoder = device.create_command_encoder(&Default::default());
drop(clear(&mut encoder, &view));
queue.submit([encoder.finish()]);
assert_eq!(last(&device), 2);
let staged = buffer(&device, 16, wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST);
queue.write_buffer(&staged, 4, &[1, 2, 3, 4]);
queue.submit([]);
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let mapped = staged.as_custom::<MetalBuffer>().unwrap().get_mapped_range(0..16).unwrap();
// SAFETY: the GPU finished with the buffer.
assert_eq!(unsafe { &mapped.read_slice()[4..8] }, &[1, 2, 3, 4]);
}
#[test]
fn a_map_waits_for_the_work_before_it() {
let (device, queue) = gpu();
let source = texture(&device, wgpu::TextureFormat::Rgba8Unorm, (W, H), wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC);
let out = buffer(&device, 256 * u64::from(H), wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ);
let view = source.create_view(&Default::default());
let mut encoder = device.create_command_encoder(&Default::default());
drop(clear(&mut encoder, &view));
copy_out(&mut encoder, &source, &out);
let index = queue.submit([encoder.finish()]);
let mapped = Arc::new(AtomicBool::new(false));
let flag = mapped.clone();
out.slice(..).map_async(wgpu::MapMode::Read, move |r| { if r.is_ok() { flag.store(true, Ordering::SeqCst) } });
assert!(!mapped.load(Ordering::SeqCst), "callbacks wait for a poll after their work");
device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: None }).unwrap();
assert!(mapped.load(Ordering::SeqCst), "the callback runs once the work completed");
assert_eq!(&out.slice(..).get_mapped_range().unwrap()[..4], &[0, 0, 51, 102], "the copy landed before the map");
}
#[test]
fn what_a_buffer_used_lives_until_it_completes() {
let (device, queue) = gpu();
let target = texture(&device, wgpu::TextureFormat::Rgba8Unorm, (W, H), wgpu::TextureUsages::RENDER_ATTACHMENT);
let view = target.create_view(&Default::default());
let raw = view.as_custom::<super::resource::MetalView>().unwrap().raw.clone();
let mut encoder = device.create_command_encoder(&Default::default());
drop(clear(&mut encoder, &view));
let recorded = encoder.finish();
drop((view, target));
assert!(Arc::strong_count(&raw) > 1, "the recorded buffer holds the view");
let index = queue.submit([recorded]);
device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: None }).unwrap();
assert_eq!(Arc::strong_count(&raw), 1, "retired once the GPU finished");
}
/// Unretained command buffers require every referenced Metal object to stay alive until Metal
/// marks the command buffer completed — not merely until its GPU-side shared event signals.
#[test]
fn resources_stay_alive_until_command_buffer_completes() {
use objc2_metal::{MTLCommandBuffer, MTLCommandBufferStatus, MTLDevice, MTLEvent, MTLSharedEvent};
let completed = |cb: &Obj<dyn MTLCommandBuffer>| {
matches!(cb.status(), MTLCommandBufferStatus::Completed | MTLCommandBufferStatus::Error)
};
let (device, queue) = gpu();
let sh = shared(&device);
// Gate the queue so both the zeroing upload CB and the render CB stay in flight while we
// grab handles to them and drop the caller's own texture and view handles.
let gate = sh.device.newSharedEvent().unwrap();
let wait = sh.command_buffer();
wait.encodeWaitForEvent_value(ProtocolObject::<dyn MTLEvent>::from_ref(&*gate), 1);
wait.commit();
let target = device.create_texture(&wgpu::TextureDescriptor {
label: Some("lifetime target"),
size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 2 },
mip_level_count: 2,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = target.create_view(&wgpu::TextureViewDescriptor {
label: Some("lifetime view"),
dimension: Some(wgpu::TextureViewDimension::D2),
base_mip_level: 0,
mip_level_count: Some(1),
base_array_layer: 0,
array_layer_count: Some(1),
..Default::default()
});
let tex_weak = Arc::downgrade(&target.as_custom::<super::resource::MetalTexture>().unwrap().raw);
let view_weak = Arc::downgrade(&view.as_custom::<super::resource::MetalView>().unwrap().raw);
let mut encoder = device.create_command_encoder(&Default::default());
drop(clear(&mut encoder, &view));
let recorded = encoder.finish();
drop((view, target));
let index = queue.submit([recorded]);
let pending = sh.pending_cbs();
assert_eq!(pending.len(), 2, "upload and render command buffers are both tracked");
let (upload_cb, (render_val, render_cb)) = (pending[0].1.clone(), (pending[1].0, pending[1].1.clone()));
assert!(tex_weak.strong_count() > 0, "upload CB keeps the texture alive while gated");
assert!(view_weak.strong_count() > 0, "render CB keeps the view alive while gated");
gate.setSignaledValue(1);
// Spin through the window where the GPU event has signaled `render_val` before Metal marks the
// command buffers completed: neither resource may drop before its command buffer completes.
while sh.event.signaledValue() < render_val {
std::hint::spin_loop();
}
for _ in 0..256 {
sh.retire();
if tex_weak.strong_count() == 0 {
assert!(completed(&upload_cb), "texture dropped before upload CB reached Completed ({:?})", upload_cb.status());
}
if view_weak.strong_count() == 0 {
assert!(completed(&render_cb), "view dropped before render CB reached Completed ({:?})", render_cb.status());
break;
}
std::hint::spin_loop();
}
device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: None }).unwrap();
assert!(completed(&upload_cb), "poll(Wait) left upload CB uncompleted: {:?}", upload_cb.status());
assert!(completed(&render_cb), "poll(Wait) left render CB uncompleted: {:?}", render_cb.status());
assert_eq!(tex_weak.strong_count(), 0, "upload texture retired once upload CB completed");
assert_eq!(view_weak.strong_count(), 0, "render view retired once render CB completed");
wait.waitUntilCompleted();
}
/// Metal ends a dropped buffer's open passes when it frees the buffer, which reads their
/// attachments; a thread's exit used to free it after its attachments were gone.
#[test]
fn an_encoder_dropped_mid_frame_frees_its_buffer_before_its_targets() {
let (device, queue) = gpu();
let raws = std::thread::spawn({
let device = device.clone();
move || {
let target = texture(&device, wgpu::TextureFormat::Rgba8Unorm, (W, H), wgpu::TextureUsages::RENDER_ATTACHMENT);
let view = target.create_view(&Default::default());
let raw = view.as_custom::<super::resource::MetalView>().unwrap().raw.clone();
let mut encoder = device.create_command_encoder(&Default::default());
drop(clear(&mut encoder, &view));
drop((encoder, view, target));
raw
}
})
.join()
.unwrap();
assert_eq!(Arc::strong_count(&raws), 1, "a dropped encoder lets go of its targets");
assert_eq!(last(&device), 0, "and never runs");
queue.submit([]);
}
#[test]
fn a_steady_frame_reuses_its_keep_lists() {
let (device, queue) = gpu();
let target = texture(&device, wgpu::TextureFormat::Rgba8Unorm, (W, H), wgpu::TextureUsages::RENDER_ATTACHMENT);
queue.submit([]);
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let view = target.create_view(&Default::default());
let frame = || {
let mut encoder = device.create_command_encoder(&Default::default());
drop(clear(&mut encoder, &view));
let index = queue.submit([encoder.finish()]);
device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: None }).unwrap();
};
let spare = || {
let mut lists: Vec<usize> = shared(&device).state.lock().spare.iter().map(|k| k.as_ptr() as usize).collect();
lists.sort_unstable();
lists
};
frame();
let lists = spare();
assert_eq!(lists.len(), 2, "the encoder's and the pass's");
frame();
frame();
assert_eq!(spare(), lists, "later frames take the same lists back");
}
/// A poll that finds the queue empty has run every callback: the GPU finishing between the two
/// must not leave one waiting for a poll nobody makes.
#[test]
fn an_empty_poll_has_run_every_callback() {
let (device, queue) = gpu();
let target = texture(&device, wgpu::TextureFormat::Rgba8Unorm, (W, H), wgpu::TextureUsages::RENDER_ATTACHMENT);
let view = target.create_view(&Default::default());
for frame in 0..300 {
let ran = Arc::new(AtomicBool::new(false));
let flag = ran.clone();
let mut encoder = device.create_command_encoder(&Default::default());
drop(clear(&mut encoder, &view));
encoder.on_submitted_work_done(move || flag.store(true, Ordering::SeqCst));
queue.submit([encoder.finish()]);
while !matches!(device.poll(wgpu::PollType::Poll).unwrap(), wgpu::PollStatus::QueueEmpty) {}
assert!(ran.load(Ordering::SeqCst), "frame {frame}: the queue read empty before its callback ran");
}
}
#[test]
fn adapters_are_the_ones_wgpu_picks() {
let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
descriptor.backends = wgpu::Backends::METAL;
let ours = instance();
let theirs = wgpu::Instance::new(descriptor);
for power_preference in [wgpu::PowerPreference::LowPower, wgpu::PowerPreference::HighPerformance] {
let options = wgpu::RequestAdapterOptions { power_preference, ..Default::default() };
let name = |instance: &wgpu::Instance| pollster::block_on(instance.request_adapter(&options)).unwrap().get_info().name;
assert_eq!(name(&ours), name(&theirs), "{power_preference:?}");
}
let count = |instance: &wgpu::Instance| pollster::block_on(instance.enumerate_adapters(wgpu::Backends::METAL)).len();
assert_eq!(count(&ours), count(&theirs));
}
+493
View File
@@ -0,0 +1,493 @@
//! Choosing the GPU adapter. On a machine with two GPUs, the one a Wayland compositor renders
//! and scans out with is the one whose buffers it can show: Hyprland on an NVIDIA card shows an
//! integrated GPU's buffers as black rectangles. So Rune asks the compositor for its main device
//! (`zwp_linux_dmabuf_v1` feedback) and takes the adapter on the same PCI device. A laptop that
//! drives its panel from the integrated GPU and offloads to the discrete one gets the integrated
//! GPU, as before.
//!
//! On Windows, every device takes the adapter that drives the primary display (the one with the
//! taskbar), else the next display's: windows, overlays, offscreen renders and tests alike.
//! Offscreen work for an existing window (snapshots, drag image, video) uses that window's own
//! device, whichever display it is on. Only when no display's GPU has an adapter (a headless
//! server, a remote session, a VM) does Rune take the lowest-power one. Offscreen work used to
//! take the lowest-power adapter: on a desktop that is often an integrated GPU no monitor uses,
//! far slower than the discrete card beside it, where a test's single submission ran past
//! Windows' 2-second limit and reset it. On a hybrid laptop whose panel is on the integrated GPU,
//! that GPU drives the primary display, so nothing changes there and the discrete GPU stays
//! asleep. On a hybrid laptop whose monitors hang off the discrete GPU, that's the discrete GPU,
//! for the main window and the HUD alike: an AMD integrated GPU presenting the HUD across to
//! them grew the process by gigabytes over an hour of dictation (hex#1268). A swapchain on a GPU
//! that drives none (a desktop's unused integrated GPU beside the discrete card the monitors
//! hang off) is presented across adapters: each one costs the display GPU's driver a device of
//! its own (about 37 threads with the NVIDIA driver, one of them waking 64 times a second) and
//! about 100 MB per full-screen surface on each GPU, and takes 50 to 160 ms to make instead of
//! 6 ms.
//!
//! `WGPU_ADAPTER_NAME` (a case-insensitive part of the adapter's name, software adapters
//! included: `Microsoft Basic Render Driver` is WARP) and `WGPU_POWER_PREF` (`low`, `high` or
//! `none`) override the choice. A named adapter is picked or the pick fails with an error: Rune
//! never falls through to another GPU, and on Windows DX12 finds it from DXGI without making a
//! device on any other adapter. A replacement device after a loss follows the same rule: the
//! named adapter (or error), else the GPU a window would get, never falling back to lowest power
//! when a display GPU exists. Without overrides, a compositor device or a display's GPU, Rune
//! takes the lowest-power adapter. `RUNE_GPU_LOG=1` prints every pick in a process with its
//! reason; without it, a machine with more than one GPU still prints the first once per process.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reason {
EnvName,
EnvPower,
Compositor,
Display,
/// Offscreen or test work, on the GPU driving the primary display.
WindowGpu,
LowPower,
}
impl Reason {
fn describe(self) -> &'static str {
match self {
Reason::EnvName => "WGPU_ADAPTER_NAME",
Reason::EnvPower => "WGPU_POWER_PREF",
Reason::Compositor => "the compositor's GPU",
Reason::Display => "the GPU driving the primary display",
Reason::WindowGpu => "the GPU a window would get (it drives the primary display)",
Reason::LowPower => "lowest power",
}
}
}
pub struct Pick {
pub adapter: wgpu::Adapter,
pub reason: Reason,
/// The compositor's main device as a PCI address, when it told us one.
compositor: Option<String>,
}
impl Pick {
/// The user chose the adapter; nothing else should swap it.
pub fn from_env(&self) -> bool {
matches!(self.reason, Reason::EnvName | Reason::EnvPower)
}
/// Whether `info` is an adapter on the compositor's device.
pub fn on_compositor_device(&self, info: &wgpu::AdapterInfo) -> bool {
self.compositor.as_deref().is_some_and(|pci| same_pci(pci, &info.device_pci_bus_id))
}
/// Whether the compositor can show `info`'s buffers: any adapter's when it named no device,
/// otherwise only its own device's.
pub fn shows(&self, info: &wgpu::AdapterInfo) -> bool {
shows(self.compositor.as_deref(), &info.device_pci_bus_id)
}
}
/// `Pick::shows` for an adapter on PCI device `pci`.
fn shows(compositor: Option<&str>, pci: &str) -> bool {
compositor.is_none_or(|compositor| same_pci(compositor, pci))
}
/// The adapter for `surface` (or for offscreen work without one, unless it's for a surface not
/// made yet: `presented`), by the order in the module docs.
pub fn pick(instance: &wgpu::Instance, surface: Option<&wgpu::Surface<'_>>, presented: bool) -> Result<Pick, String> {
// DX12: the same order through DXGI's adapter list, and only the chosen adapter goes to wgpu.
#[cfg(target_os = "windows")]
if let Some(picked) = dxgi::pick(instance, surface, presented) {
let (pick, adapters) = picked.inspect_err(|error| log_failure(error))?;
return Ok(log(pick, Some(adapters)));
}
let usable = |adapter: &wgpu::Adapter| surface.is_none_or(|s| adapter.is_surface_supported(s));
let compositor = compositor_pci();
let mut enumerated = None;
if let Some(name) = rune_core::env::var("WGPU_ADAPTER_NAME") {
let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all()));
let infos: Vec<_> = adapters.iter().map(|a| (a.get_info(), usable(a))).collect();
let found = by_name(&name, &infos);
enumerated = Some(infos.len());
let Some(adapter) = found.and_then(|index| adapters.into_iter().nth(index)) else {
let error = format!("no GPU adapter matches WGPU_ADAPTER_NAME={name:?}");
log_failure(&error);
return Err(error);
};
return Ok(log(Pick { adapter, reason: Reason::EnvName, compositor }, enumerated));
}
if let Some(power) = wgpu::PowerPreference::from_env() {
let adapter = request(instance, surface, power)?;
return Ok(log(Pick { adapter, reason: Reason::EnvPower, compositor }, enumerated));
}
if let Some(pci) = compositor.as_deref() {
let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all()));
let infos: Vec<_> = adapters.iter().map(|a| (a.get_info(), usable(a))).collect();
enumerated = Some(infos.iter().filter(|(info, _)| info.device_type != wgpu::DeviceType::Cpu).count());
if let Some(adapter) = by_pci(pci, &infos).and_then(|index| adapters.into_iter().nth(index)) {
return Ok(log(Pick { adapter, reason: Reason::Compositor, compositor }, enumerated));
}
}
// Every device takes the GPU a window would get; `presented` only names the reason.
let displays = display_devices();
if !displays.is_empty() {
let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all()));
let infos: Vec<_> = adapters.iter().map(|a| (a.get_info(), usable(a))).collect();
enumerated = Some(infos.iter().filter(|(info, _)| info.device_type != wgpu::DeviceType::Cpu).count());
if let Some(adapter) = by_display(&displays, &infos).and_then(|index| adapters.into_iter().nth(index)) {
let reason = if surface.is_some() || presented { Reason::Display } else { Reason::WindowGpu };
return Ok(log(Pick { adapter, reason, compositor }, enumerated));
}
}
let adapter = request(instance, surface, wgpu::PowerPreference::LowPower)?;
Ok(log(Pick { adapter, reason: Reason::LowPower, compositor }, enumerated))
}
fn request(instance: &wgpu::Instance, surface: Option<&wgpu::Surface<'_>>, power_preference: wgpu::PowerPreference) -> Result<wgpu::Adapter, String> {
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference,
force_fallback_adapter: false,
compatible_surface: surface,
apply_limit_buckets: false,
}))
.map_err(|error| format!("no GPU adapter: {error}"))
}
/// The first usable adapter whose name contains `name`, ignoring case.
fn by_name(name: &str, adapters: &[(wgpu::AdapterInfo, bool)]) -> Option<usize> {
let name = name.to_lowercase();
adapters.iter().position(|(info, usable)| *usable && info.name.to_lowercase().contains(&name))
}
/// The usable adapter on PCI device `pci`, Vulkan first.
fn by_pci(pci: &str, adapters: &[(wgpu::AdapterInfo, bool)]) -> Option<usize> {
let on = |(info, usable): &(wgpu::AdapterInfo, bool)| *usable && same_pci(pci, &info.device_pci_bus_id);
adapters.iter().position(|a| on(a) && a.0.backend == wgpu::Backend::Vulkan).or_else(|| adapters.iter().position(on))
}
/// Windows: the pick made from DXGI's adapter list, which makes no device and loads no driver;
/// wgpu then gets the one adapter chosen (`wgpu_hal::dx12::Instance::expose_adapter`, from the
/// vendored wgpu-hal). wgpu's own `enumerate_adapters` and `request_adapter` make a device on every
/// adapter to describe it, the discrete GPU and WARP included: 1,050,000–1,110,000 µs on a
/// two-GPU laptop, waking a discrete GPU the window never uses.
#[cfg(target_os = "windows")]
#[allow(unsafe_code)]
mod dxgi {
use super::{Pick, Reason};
use windows::Win32::Graphics::Dxgi::{
CreateDXGIFactory1, DXGI_ADAPTER_DESC1, DXGI_ADAPTER_FLAG_SOFTWARE, DXGI_GPU_PREFERENCE, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
DXGI_GPU_PREFERENCE_MINIMUM_POWER, IDXGIAdapter1, IDXGIFactory1, IDXGIFactory6,
};
use windows::core::Interface;
// Unused when the vendored wgpu-hal's inherent `expose_adapter` takes the call.
#[allow(unused_imports)]
use without_patch::ExposeAdapter as _;
/// An app whose workspace doesn't patch wgpu-hal with Rune's copy (`[patch.crates-io]`, see
/// `vendor/wgpu-hal`) gets wgpu-hal as published, which has no `expose_adapter`: the call then
/// lands here (an inherent method wins over a trait's), and the pick falls back to wgpu's list.
mod without_patch {
use std::cell::Cell;
thread_local! {
pub(super) static UNPATCHED: Cell<bool> = const { Cell::new(false) };
}
#[allow(dead_code)]
pub(super) trait ExposeAdapter {
unsafe fn expose_adapter(&self, _: &windows::Win32::Graphics::Dxgi::IDXGIAdapter1) -> Option<wgpu::hal::ExposedAdapter<wgpu::hal::api::Dx12>> {
UNPATCHED.with(|unpatched| unpatched.set(true));
None
}
}
impl ExposeAdapter for wgpu::hal::dx12::Instance {}
}
/// The pick and how many hardware adapters DXGI lists; None when the instance isn't DX12's,
/// `wgpu-hal` is unpatched, or an automatic choice can't run D3D12 or present to `surface`
/// (the caller then asks wgpu). For `WGPU_ADAPTER_NAME` the answer is final: the adapter it
/// names, or the error saying why not, without making a device on any other adapter.
pub(super) fn pick(instance: &wgpu::Instance, surface: Option<&wgpu::Surface<'_>>, presented: bool) -> Option<Result<(Pick, usize), String>> {
// SAFETY: wgpu's DX12 instance, borrowed for this call.
let hal = unsafe { instance.as_hal::<wgpu::hal::api::Dx12>() }?;
// SAFETY: a DXGI factory and its adapters, asked for their descriptions.
let factory = unsafe { CreateDXGIFactory1::<IDXGIFactory1>() }.ok()?;
let all: Vec<(IDXGIAdapter1, DXGI_ADAPTER_DESC1)> = (0..)
.map_while(|i| {
// SAFETY: `factory` is a live `IDXGIFactory1`; out-of-range `i` returns `DXGI_ERROR_NOT_FOUND`.
unsafe { factory.EnumAdapters1(i) }.ok()
})
.filter_map(|a| {
// SAFETY: `a` is a live `IDXGIAdapter1` returned by `EnumAdapters1`.
unsafe { a.GetDesc1() }.ok().map(|d| (a, d))
})
.collect();
let hardware: Vec<&(IDXGIAdapter1, DXGI_ADAPTER_DESC1)> =
all.iter().filter(|(_, d)| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0).collect();
let count = hardware.len();
let by_preference = |preference: DXGI_GPU_PREFERENCE| -> Option<IDXGIAdapter1> {
let factory6 = factory.cast::<IDXGIFactory6>().ok()?;
(0..)
.map_while(|i| {
// SAFETY: `factory6` is a live `IDXGIFactory6`; out-of-range `i` returns `DXGI_ERROR_NOT_FOUND`.
unsafe { factory6.EnumAdapterByGpuPreference::<IDXGIAdapter1>(i, preference) }.ok()
})
.find(|a| {
// SAFETY: `a` is a live `IDXGIAdapter1` returned by `EnumAdapterByGpuPreference`.
unsafe { a.GetDesc1() }.is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0)
})
};
let description = |d: &DXGI_ADAPTER_DESC1| {
let len = d.Description.iter().position(|&c| c == 0).unwrap_or(d.Description.len());
String::from_utf16_lossy(&d.Description[..len])
};
if let Some(wanted) = rune_core::env::var("WGPU_ADAPTER_NAME") {
let wanted_lower = wanted.to_lowercase();
// Software adapters too: `Microsoft Basic Render Driver` names WARP. Try every match
// in DXGI order: headless Windows lists a non-software WARP entry that `expose_adapter`
// rejects before the real software WARP adapter, and multi-adapter matches should skip
// unusable ones just like `by_name`.
let mut tried = Vec::new();
for (adapter, desc) in all.iter().filter(|(_, d)| description(d).to_lowercase().contains(&wanted_lower)) {
let label = description(desc);
without_patch::UNPATCHED.with(|unpatched| unpatched.set(false));
// SAFETY: `adapter` comes from a DXGI factory in this process, as `expose_adapter` asks.
let Some(exposed) = (unsafe { hal.expose_adapter(adapter) }) else {
if without_patch::UNPATCHED.with(|unpatched| unpatched.replace(false)) {
return None;
}
tried.push(format!("{label:?} (can't make a D3D12 device now)"));
continue;
};
// SAFETY: `exposed` was exposed from this same DX12 `instance`'s HAL.
let adapter = unsafe { instance.create_adapter_from_hal(exposed) };
if surface.is_some_and(|s| !adapter.is_surface_supported(s)) {
tried.push(format!("{label:?} (can't present to this window)"));
continue;
}
return Some(Ok((Pick { adapter, reason: Reason::EnvName, compositor: None }, count)));
}
let error = if tried.is_empty() {
format!("no GPU adapter matches WGPU_ADAPTER_NAME={wanted:?}")
} else {
format!("WGPU_ADAPTER_NAME={wanted:?} matched {}, none usable", tried.join(", "))
};
return Some(Err(error));
}
let (adapter, reason) = if let Some(power) = wgpu::PowerPreference::from_env() {
let preference = if power == wgpu::PowerPreference::HighPerformance { DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE } else { DXGI_GPU_PREFERENCE_MINIMUM_POWER };
(by_preference(preference)?, Reason::EnvPower)
} else if let Some(found) = super::display_devices()
.iter()
.find_map(|ids| hardware.iter().find(|(_, d)| (d.VendorId, d.DeviceId) == *ids))
{
// Every device takes the GPU a window would get; `presented` only names the reason.
(found.0.clone(), if surface.is_some() || presented { Reason::Display } else { Reason::WindowGpu })
} else {
(by_preference(DXGI_GPU_PREFERENCE_MINIMUM_POWER).or_else(|| hardware.first().map(|h| h.0.clone()))?, Reason::LowPower)
};
// SAFETY: `adapter` comes from a DXGI factory in this process, as `expose_adapter` asks.
let exposed = unsafe { hal.expose_adapter(&adapter) }?;
// SAFETY: `exposed` was exposed from this same DX12 `instance`'s HAL.
let adapter = unsafe { instance.create_adapter_from_hal(exposed) };
if surface.is_some_and(|s| !adapter.is_surface_supported(s)) {
return None;
}
Some(Ok((Pick { adapter, reason, compositor: None }, count)))
}
}
/// The usable hardware adapter for the first of `displays` (PCI vendor and device IDs, the
/// primary display's first) that has one.
fn by_display(displays: &[(u32, u32)], adapters: &[(wgpu::AdapterInfo, bool)]) -> Option<usize> {
displays.iter().find_map(|ids| {
adapters.iter().position(|(info, usable)| *usable && info.device_type != wgpu::DeviceType::Cpu && (info.vendor, info.device) == *ids)
})
}
/// `PowerPreference::LowPower`'s order; a software adapter comes last.
pub fn power_rank(device: wgpu::DeviceType) -> u8 {
match device {
wgpu::DeviceType::IntegratedGpu => 0,
wgpu::DeviceType::DiscreteGpu => 1,
wgpu::DeviceType::VirtualGpu => 2,
wgpu::DeviceType::Other => 3,
wgpu::DeviceType::Cpu => 4,
}
}
/// The PCI vendor of the GPU driving the primary display, which `pick` chooses for a window:
/// known before any GPU is made, for the CPU renderer that draws until then. Read once, at
/// launch (`find_display_vendor_soon`): enumerating the display devices takes ~1,500 µs.
pub fn display_vendor() -> Option<u32> {
*DISPLAY_VENDOR.get_or_init(|| display_devices().first().map(|ids| ids.0))
}
static DISPLAY_VENDOR: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
/// Starts reading [`display_vendor`] on a thread of its own once the event loop exists, so the
/// first window needn't wait for it; a window that asks sooner waits for that thread.
#[cfg(target_os = "windows")]
pub fn find_display_vendor_soon() {
std::thread::Builder::new().name("rune-display-vendor".into()).spawn(display_vendor).ok();
}
/// The PCI vendor and device IDs of the GPUs driving a display on the desktop, the primary
/// display's first.
#[cfg(target_os = "windows")]
#[allow(unsafe_code)]
fn display_devices() -> Vec<(u32, u32)> {
use windows_sys::Win32::Graphics::Gdi::{DISPLAY_DEVICE_ATTACHED_TO_DESKTOP, DISPLAY_DEVICE_PRIMARY_DEVICE, DISPLAY_DEVICEW, EnumDisplayDevicesW};
let mut found = Vec::new();
for index in 0.. {
// SAFETY: `DISPLAY_DEVICEW` is a plain Win32 C struct where all-zero bytes are valid.
let mut device = DISPLAY_DEVICEW { cb: std::mem::size_of::<DISPLAY_DEVICEW>() as u32, ..unsafe { std::mem::zeroed() } };
// SAFETY: `device` is a DISPLAY_DEVICEW with `cb` set, as the call requires.
if unsafe { EnumDisplayDevicesW(std::ptr::null(), index, &mut device, 0) } == 0 { break; }
if device.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP == 0 { continue; }
let len = device.DeviceID.iter().position(|&c| c == 0).unwrap_or(device.DeviceID.len());
let Some(ids) = pci_ids(&String::from_utf16_lossy(&device.DeviceID[..len])) else { continue };
if device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE != 0 {
found.retain(|other| *other != ids);
found.insert(0, ids);
} else if !found.contains(&ids) {
found.push(ids);
}
}
found
}
#[cfg(not(target_os = "windows"))]
fn display_devices() -> Vec<(u32, u32)> {
Vec::new()
}
/// The vendor and device IDs in a PnP hardware ID (`PCI\VEN_10DE&DEV_2C05&SUBSYS_…`); None for
/// a display that isn't on a PCI GPU (a remote or indirect display).
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn pci_ids(id: &str) -> Option<(u32, u32)> {
let rest = id.get(..4).filter(|p| p.eq_ignore_ascii_case("PCI\\")).and_then(|_| id.get(4..))?;
let field = |key: &str| rest.split('&').find_map(|part| {
let value = part.get(..key.len()).filter(|k| k.eq_ignore_ascii_case(key)).and_then(|_| part.get(key.len()..))?;
u32::from_str_radix(value, 16).ok()
});
Some((field("VEN_")?, field("DEV_")?))
}
fn same_pci(a: &str, b: &str) -> bool {
!a.is_empty() && a.eq_ignore_ascii_case(b)
}
fn log(pick: Pick, adapters: Option<usize>) -> Pick {
static FIRST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
if gpu_log() || (adapters.is_some_and(|n| n > 1) && FIRST.swap(false, std::sync::atomic::Ordering::Relaxed)) {
let info = pick.adapter.get_info();
let pci = if info.device_pci_bus_id.is_empty() { String::new() } else { format!(", {}", info.device_pci_bus_id) };
let compositor = pick.compositor.as_deref().map(|c| format!("; compositor on {c}")).unwrap_or_default();
eprintln!("rune: GPU {:?} ({}; {:?}, {:?}{pci}): {}{compositor}", info.name, crate::backend::label(&pick.adapter), info.backend, info.device_type, pick.reason.describe());
}
pick
}
/// A pick that found no adapter, said always: the device it was for won't be made.
fn log_failure(error: &str) {
eprintln!("rune: no GPU: {error}");
}
fn gpu_log() -> bool {
rune_core::env::var_os("RUNE_GPU_LOG").is_some_and(|v| v != "0")
}
/// The compositor's main device as a PCI address, asked once per process.
#[cfg(target_os = "linux")]
fn compositor_pci() -> Option<String> {
static PCI: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
PCI.get_or_init(|| {
let (major, minor) = dev_numbers(&dmabuf::main_device()?)?;
pci_address(&std::fs::read_link(format!("/sys/dev/char/{major}:{minor}/device")).ok()?)
})
.clone()
}
#[cfg(not(target_os = "linux"))]
fn compositor_pci() -> Option<String> {
None
}
/// A `dev_t` sent as native-endian bytes, split into major and minor numbers (glibc's and the
/// kernel's encoding).
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn dev_numbers(bytes: &[u8]) -> Option<(u32, u32)> {
let dev = match bytes.len() {
8 => u64::from_ne_bytes(bytes.try_into().ok()?),
4 => u64::from(u32::from_ne_bytes(bytes.try_into().ok()?)),
_ => return None,
};
let major = ((dev >> 32) & 0xffff_f000) | ((dev >> 8) & 0x0fff);
let minor = ((dev >> 12) & 0xffff_ff00) | (dev & 0xff);
Some((major as u32, minor as u32))
}
/// The PCI address a DRM node's `device` link points at (`../../../0000:01:00.0`), lowercased;
/// None for a device that isn't on PCI.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn pci_address(link: &std::path::Path) -> Option<String> {
let name = link.file_name()?.to_str()?.to_ascii_lowercase();
let (domain, rest) = name.split_once(':')?;
let (bus, rest) = rest.split_once(':')?;
let (device, function) = rest.split_once('.')?;
let hex = |s: &str, len: usize| s.len() == len && s.bytes().all(|b| b.is_ascii_hexdigit());
(hex(domain, 4) && hex(bus, 2) && hex(device, 2) && hex(function, 1)).then_some(name)
}
#[cfg(target_os = "linux")]
mod dmabuf {
use wayland_client::globals::{GlobalListContents, registry_queue_init};
use wayland_client::protocol::wl_registry::WlRegistry;
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle};
use wayland_protocols::wp::linux_dmabuf::zv1::client::zwp_linux_dmabuf_feedback_v1::{self, ZwpLinuxDmabufFeedbackV1};
use wayland_protocols::wp::linux_dmabuf::zv1::client::zwp_linux_dmabuf_v1::ZwpLinuxDmabufV1;
#[derive(Default)]
struct State {
main: Option<Vec<u8>>,
done: bool,
}
impl Dispatch<WlRegistry, GlobalListContents> for State {
fn event(_: &mut Self, _: &WlRegistry, _: <WlRegistry as Proxy>::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle<Self>) {}
}
impl Dispatch<ZwpLinuxDmabufV1, ()> for State {
fn event(_: &mut Self, _: &ZwpLinuxDmabufV1, _: <ZwpLinuxDmabufV1 as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {}
}
impl Dispatch<ZwpLinuxDmabufFeedbackV1, ()> for State {
fn event(state: &mut Self, _: &ZwpLinuxDmabufFeedbackV1, event: zwp_linux_dmabuf_feedback_v1::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {
match event {
zwp_linux_dmabuf_feedback_v1::Event::MainDevice { device } => state.main = Some(device),
zwp_linux_dmabuf_feedback_v1::Event::Done => state.done = true,
_ => {}
}
}
}
/// The compositor's main device `dev_t`, from its default dmabuf feedback on a short-lived
/// connection of our own. None off Wayland or before `zwp_linux_dmabuf_v1` version 4.
/// Version 6 stops sending the main device, so Rune binds at most 5.
pub(super) fn main_device() -> Option<Vec<u8>> {
std::env::var_os("WAYLAND_DISPLAY")?;
let conn = Connection::connect_to_env().ok()?;
let (globals, mut queue) = registry_queue_init::<State>(&conn).ok()?;
let dmabuf = globals.bind::<ZwpLinuxDmabufV1, _, _>(&queue.handle(), 4..=5, ()).ok()?;
let feedback = dmabuf.get_default_feedback(&queue.handle(), ());
let mut state = State::default();
for _ in 0..4 {
if state.done { break; }
queue.roundtrip(&mut state).ok()?;
}
feedback.destroy();
dmabuf.destroy();
queue.flush().ok();
state.main
}
}
#[cfg(test)]
#[path = "pick_tests.rs"]
mod tests;
+107
View File
@@ -0,0 +1,107 @@
use super::{by_display, by_name, by_pci, dev_numbers, pci_address, pci_ids, power_rank, shows};
use std::path::Path;
fn adapter(name: &str, backend: wgpu::Backend, pci: &str) -> wgpu::AdapterInfo {
wgpu::AdapterInfo { name: name.into(), backend, device_pci_bus_id: pci.into(), ..wgpu::AdapterInfo::new(wgpu::DeviceType::Other, backend) }
}
/// glibc's `makedev`.
fn makedev(major: u64, minor: u64) -> u64 {
((major & 0xffff_f000) << 32) | ((major & 0x0fff) << 8) | ((minor & 0xffff_ff00) << 12) | (minor & 0xff)
}
#[test]
fn dev_t_bytes_split_into_major_and_minor() {
assert_eq!(dev_numbers(&makedev(226, 128).to_ne_bytes()), Some((226, 128)));
assert_eq!(dev_numbers(&makedev(226, 1).to_ne_bytes()), Some((226, 1)));
assert_eq!(dev_numbers(&makedev(0x12345, 0x6789a).to_ne_bytes()), Some((0x12345, 0x6789a)));
assert_eq!(dev_numbers(&((226u32 << 8) | 128).to_ne_bytes()), Some((226, 128)));
assert_eq!(dev_numbers(&[1, 2, 3]), None);
}
#[test]
fn drm_device_links_give_their_pci_address() {
assert_eq!(pci_address(Path::new("../../../0000:01:00.0")).as_deref(), Some("0000:01:00.0"));
assert_eq!(pci_address(Path::new("../../../0000:C5:00.0")).as_deref(), Some("0000:c5:00.0"));
assert_eq!(pci_address(Path::new("../../../simple-framebuffer.0")), None);
assert_eq!(pci_address(Path::new("../../../fd4ab000.gpu")), None);
}
#[test]
fn the_compositor_device_picks_the_adapter_on_it() {
let adapters = [
(adapter("AMD Radeon Graphics (RADV RAPHAEL_MENDOCINO)", wgpu::Backend::Vulkan, "0000:0f:00.0"), true),
(adapter("NVIDIA GeForce RTX 5070", wgpu::Backend::Gl, "0000:01:00.0"), true),
(adapter("NVIDIA GeForce RTX 5070", wgpu::Backend::Vulkan, "0000:01:00.0"), true),
(adapter("llvmpipe", wgpu::Backend::Vulkan, ""), true),
];
assert_eq!(by_pci("0000:01:00.0", &adapters), Some(2), "Vulkan before GL");
assert_eq!(by_pci("0000:0F:00.0", &adapters), Some(0));
assert_eq!(by_pci("0000:02:00.0", &adapters), None);
assert_eq!(by_pci("", &adapters), None, "no address matches llvmpipe's empty one");
}
#[test]
fn an_adapter_that_cant_present_is_skipped() {
let adapters = [
(adapter("NVIDIA GeForce RTX 5070", wgpu::Backend::Vulkan, "0000:01:00.0"), false),
(adapter("AMD Radeon Graphics", wgpu::Backend::Vulkan, "0000:0f:00.0"), true),
];
assert_eq!(by_pci("0000:01:00.0", &adapters), None);
assert_eq!(by_name("nvidia", &adapters), None);
assert_eq!(by_name("RADEON", &adapters), Some(1));
}
/// Once the compositor names its GPU, only that GPU's buffers can be shown: an integrated GPU
/// or lavapipe (no PCI device) never takes an overlay on GNOME + NVIDIA (hex#979, #982).
#[test]
fn only_the_compositors_gpu_shows_once_it_named_one() {
assert!(shows(Some("0000:01:00.0"), "0000:01:00.0"));
assert!(!shows(Some("0000:01:00.0"), "0000:7c:00.0"));
assert!(!shows(Some("0000:01:00.0"), ""));
assert!(shows(None, "0000:7c:00.0"));
assert!(shows(None, ""));
}
#[test]
fn low_power_order_puts_integrated_first_and_software_last() {
use wgpu::DeviceType::*;
let mut devices = [Cpu, DiscreteGpu, Other, IntegratedGpu, VirtualGpu];
devices.sort_by_key(|d| power_rank(*d));
assert_eq!(devices, [IntegratedGpu, DiscreteGpu, VirtualGpu, Other, Cpu]);
}
#[test]
fn a_pci_hardware_id_gives_its_vendor_and_device() {
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_2C05&SUBSYS_205E1458&REV_A1"), Some((0x10de, 0x2c05)));
assert_eq!(pci_ids("pci\\ven_1002&dev_13c0&subsys_d0001458&rev_c9"), Some((0x1002, 0x13c0)));
assert_eq!(pci_ids("SWD\\RemoteDisplayEnum"), None, "a remote display");
assert_eq!(pci_ids("PCI\\VEN_10DE"), None);
assert_eq!(pci_ids(""), None);
}
fn gpu(name: &str, device_type: wgpu::DeviceType, vendor: u32, device: u32) -> wgpu::AdapterInfo {
wgpu::AdapterInfo { name: name.into(), vendor, device, ..wgpu::AdapterInfo::new(device_type, wgpu::Backend::Dx12) }
}
/// A desktop or laptop whose primary monitor is on its discrete card draws there, not on the
/// integrated GPU (hex#1268); a laptop whose primary display is its panel on the integrated GPU
/// keeps it.
#[test]
fn the_gpu_driving_the_primary_display_is_picked() {
use wgpu::DeviceType::*;
let adapters = [
(gpu("NVIDIA GeForce RTX 5070 Ti", DiscreteGpu, 0x10de, 0x2c05), true),
(gpu("AMD Radeon(TM) Graphics", IntegratedGpu, 0x1002, 0x13c0), true),
(gpu("Microsoft Basic Render Driver", Cpu, 0x1414, 0x8c), true),
];
assert_eq!(by_display(&[(0x10de, 0x2c05)], &adapters), Some(0), "only the discrete card drives a display");
assert_eq!(by_display(&[(0x10de, 0x2c05), (0x1002, 0x13c0)], &adapters), Some(0), "both do: the primary display's");
assert_eq!(by_display(&[(0x1002, 0x13c0), (0x10de, 0x2c05)], &adapters), Some(1), "the laptop panel is primary");
assert_eq!(by_display(&[(0x8086, 0x56a0), (0x10de, 0x2c05)], &adapters), Some(0), "the primary display's GPU has no adapter: the next display's");
assert_eq!(by_display(&[(0x1002, 0x13c0)], &adapters), Some(1), "a laptop panel");
assert_eq!(by_display(&[(0x1414, 0x8c)], &adapters), None, "never the software adapter");
assert_eq!(by_display(&[(0x8086, 0x56a0)], &adapters), None, "no adapter drives it");
let cant_present = [(adapters[0].0.clone(), false), adapters[1].clone()];
assert_eq!(by_display(&[(0x10de, 0x2c05)], &cant_present), None);
}
+236
View File
@@ -0,0 +1,236 @@
//! Opt-in retained translation/opacity tracks. Layout, glyph placement, presence and app events
//! remain CPU-owned. Callers sample on demand for hit testing and stop ticks at `settle_at()`.
use bytemuck::{Pod, Zeroable};
use rune_motion::Spring;
pub const SHADER: &str = include_str!("springs.wgsl");
pub fn split_time(time: f64) -> [f32; 2] {
assert!(time.is_finite() && time >= 0.0 && time < 16_777_216.0);
let hi = time.floor() as f32;
[hi, (time - hi as f64) as f32]
}
/// GPU ABI, 48 bytes. Keep fields private: construction validates finite inputs.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Track {
abcd: [f32; 4],
rates: [f32; 2],
target: f32,
kind: u32,
start: [f32; 2],
duration: f32,
pad: f32,
}
const _: () = {
assert!(std::mem::size_of::<Track>() == 48);
assert!(std::mem::offset_of!(Track, abcd) == 0);
assert!(std::mem::offset_of!(Track, rates) == 16);
assert!(std::mem::offset_of!(Track, target) == 24);
assert!(std::mem::offset_of!(Track, kind) == 28);
assert!(std::mem::offset_of!(Track, start) == 32);
assert!(std::mem::offset_of!(Track, duration) == 40);
assert!(std::mem::offset_of!(Track, pad) == 44);
assert!(std::mem::size_of::<Node>() == 144);
assert!(std::mem::offset_of!(Node, x) == 0);
assert!(std::mem::offset_of!(Node, y) == 48);
assert!(std::mem::offset_of!(Node, opacity) == 96);
};
impl Track {
pub fn new(spring: Spring, time: f64, from: f32, target: f32, velocity: f32, epsilon: f32) -> Self {
assert!([from, target, velocity].iter().all(|v| v.is_finite()));
let duration = spring.settling_duration_from(from, velocity, target, epsilon);
let a = from - target;
let w = spring.omega();
let z = spring.zeta();
let (kind, abcd, rates) = if a == 0.0 && velocity == 0.0 {
(0, [0.0; 4], [0.0; 2])
} else if (z - 1.0).abs() < 1e-4 {
let b = velocity + w * a;
(2, [a, b, b - w * a, -w * b], [w, 0.0])
} else if z < 1.0 {
let sigma = z * w;
let wd = w * (1.0 - z * z).sqrt();
let b = (velocity + sigma * a) / wd;
(1, [a, b, b * wd - sigma * a, -a * wd - sigma * b], [sigma, wd])
} else {
let root = (z * z - 1.0).sqrt();
let r1 = -w * (z - root);
let r2 = -w * (z + root);
let c1 = (velocity - r2 * a) / (r1 - r2);
(3, [c1, a - c1, r1, r2], [0.0; 2])
};
assert!(abcd.iter().chain(rates.iter()).all(|x| x.is_finite()));
Self { abcd, rates, target, kind, start: split_time(time), duration, pad: 0.0 }
}
pub fn constant(value: f32) -> Self {
Self::new(Spring::DEFAULT, 0.0, value, value, 0.0, 0.001)
}
pub fn settle_at(&self) -> f64 {
self.start[0] as f64 + self.start[1] as f64 + self.duration as f64
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Node {
pub x: Track,
pub y: Track,
pub opacity: Track,
}
impl Node {
pub fn settle_at(&self) -> f64 {
self.x.settle_at().max(self.y.settle_at()).max(self.opacity.settle_at())
}
}
#[doc(hidden)]
pub struct Bindings {
pub group: wgpu::BindGroup,
pub nodes: wgpu::Buffer,
pub deadlines: Vec<f64>,
pub settle_at: f64,
}
impl Bindings {
pub fn layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("spring properties"),
entries: &[0, 1].map(|binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}),
})
}
pub fn new(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, nodes: &[Node], ids: &[u32]) -> Self {
use wgpu::util::DeviceExt;
assert!(!nodes.is_empty() && !ids.is_empty());
assert!(ids.iter().all(|&id| (id as usize) < nodes.len()));
let deadlines: Vec<_> = nodes.iter().map(Node::settle_at).collect();
let settle_at = deadlines.iter().copied().fold(0.0, f64::max);
let nodes = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("spring nodes"),
contents: bytemuck::cast_slice(nodes),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
let ids = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("spring ids"),
contents: bytemuck::cast_slice(ids),
usage: wgpu::BufferUsages::STORAGE,
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("spring properties"),
layout,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: nodes.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: ids.as_entire_binding() },
],
});
Self { group, nodes, deadlines, settle_at }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn arbitrary_retarget_settle_bounds_hold_for_the_tail() {
assert_eq!(std::mem::size_of::<Track>(), 48);
assert_eq!(std::mem::size_of::<Node>(), 144);
for bounce in [-0.9, -0.2, 0.0, 0.16, 0.8] {
let spring = Spring::new(0.4, bounce);
for velocity in [-800.0, 0.0, 900.0] {
let (from, velocity) = spring.sample(-120.0, velocity, 40.0, 0.12);
let duration = spring.settling_duration_from(from, velocity, -30.0, 0.001);
for i in 0..200 {
let (x, v) = spring.sample(from, velocity, -30.0, duration + i as f32 / 120.0);
assert!((x + 30.0).abs() <= 0.00101, "{bounce}: {x}");
assert!(v.abs() <= 0.01001, "{bounce}: {v}");
}
}
}
assert_eq!(Track::constant(1.0).settle_at(), 0.0);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn wgsl_spring_layouts_match_rust() {
use wgpu::naga::{TypeInner, front::wgsl, proc::Layouter, valid::{Capabilities, ValidationFlags, Validator}};
// `springs.wgsl` is concatenated after `shader.wgsl`; stub the vertex interface it references.
const STUB: &str = r#"
struct Globals { viewport: vec2<f32>, pad: vec2<f32>, flags: vec4<f32> };
@group(0) @binding(0) var<uniform> g: Globals;
struct In {
@location(0) rect: vec4<f32>,
@location(1) radii: vec4<f32>,
@location(2) fill: vec4<f32>,
@location(3) border: vec4<f32>,
@location(4) params: vec4<f32>,
@location(5) uv: vec4<f32>,
};
struct Out { @builtin(position) pos: vec4<f32> };
fn base_vs(i: In) -> Out { var o: Out; o.pos = vec4<f32>(0.0); return o; }
"#;
let source = format!("{STUB}\n{SHADER}");
let module = wgsl::parse_str(&source).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&source)));
Validator::new(ValidationFlags::all(), Capabilities::default())
.validate(&module)
.expect("validate springs.wgsl");
let mut layouter = Layouter::default();
layouter.update(module.to_ctx()).expect("layout springs.wgsl");
let check = |name: &str, size: usize, expected: &[(&str, usize)]| {
let (handle, ty) = module
.types
.iter()
.find(|(_, t)| t.name.as_deref() == Some(name))
.unwrap_or_else(|| panic!("WGSL struct {name} not found"));
assert_eq!(layouter[handle].size as usize, size, "{name} size");
let TypeInner::Struct { members, span } = &ty.inner else { panic!("{name} is not a struct") };
assert_eq!(*span as usize, size, "{name} span");
assert_eq!(members.len(), expected.len(), "{name} member count");
for (member, &(field, offset)) in members.iter().zip(expected) {
assert_eq!(member.name.as_deref(), Some(field), "{name}.{field} name");
assert_eq!(member.offset as usize, offset, "{name}.{field} offset");
}
};
check(
"SpringTrack",
std::mem::size_of::<Track>(),
&[
("abcd", std::mem::offset_of!(Track, abcd)),
("rates", std::mem::offset_of!(Track, rates)),
("goal", std::mem::offset_of!(Track, target)),
("kind", std::mem::offset_of!(Track, kind)),
("start", std::mem::offset_of!(Track, start)),
("duration", std::mem::offset_of!(Track, duration)),
("pad", std::mem::offset_of!(Track, pad)),
],
);
check(
"SpringNode",
std::mem::size_of::<Node>(),
&[
("x", std::mem::offset_of!(Node, x)),
("y", std::mem::offset_of!(Node, y)),
("opacity", std::mem::offset_of!(Node, opacity)),
],
);
}
}
+85
View File
@@ -0,0 +1,85 @@
// Coefficients are prepared once at retarget using rune-motion's damping branches.
struct SpringTrack {
abcd: vec4<f32>,
rates: vec2<f32>,
goal: f32,
kind: u32,
start: vec2<f32>,
duration: f32,
pad: f32,
};
// Match rune_motion::math::exp for overdamped roots: near-critical coefficients
// nearly cancel, amplifying native-exp differences by four orders of magnitude.
fn spring_exp(x: f32) -> f32 {
if (x < -87.0) { return 0.0; }
let xc = clamp(x, -87.0, 88.0);
let k = round(xc * 1.4426950408889634);
let r = fma(-k, 0.0000014286068, fma(-k, 0.69314575, xc));
let r2 = r * r;
let a = 1.0 + r;
let b = fma(r, 1.0 / 6.0, 0.5);
let c = fma(r, 1.0 / 120.0, 1.0 / 24.0);
let p = fma(r2, fma(r2, fma(r2, 1.0 / 720.0, c), b), a);
return p * bitcast<f32>(u32(i32(k) + 127) << 23u);
}
// Split seconds preserve sub-frame precision after days of application uptime.
fn spring_sample(s: SpringTrack, time: vec2<f32>) -> vec2<f32> {
// Integer subtraction is an optimization barrier against fast-math reassociating
// (hi-hi)+(lo-lo) into lossy absolute f32 timestamps on Metal.
let whole = f32(i32(time.x) - i32(s.start.x));
let t = max(whole + (time.y - s.start.y), 0.0);
if (s.kind == 0u || t >= s.duration) { return vec2<f32>(s.goal, 0.0); }
let c = s.abcd;
if (s.kind == 1u) {
let e = exp(-s.rates.x * t);
let co = cos(s.rates.y * t);
let si = sin(s.rates.y * t);
return vec2<f32>(s.goal + e * (c.x * co + c.y * si), e * (c.z * co + c.w * si));
}
if (s.kind == 2u) {
let e = exp(-s.rates.x * t);
return vec2<f32>(s.goal + (c.x + c.y * t) * e, (c.z + c.w * t) * e);
}
let e1 = spring_exp(c.z * t);
let e2 = spring_exp(c.w * t);
return vec2<f32>(s.goal + (c.x * e1 + c.y * e2), c.x * c.z * e1 + c.y * c.w * e2);
}
struct SpringNode { x: SpringTrack, y: SpringTrack, opacity: SpringTrack };
@group(1) @binding(0) var<storage, read> spring_nodes: array<SpringNode>;
@group(1) @binding(1) var<storage, read> spring_ids: array<u32>;
@vertex
fn vs_springs(input: In, @builtin(instance_index) instance: u32) -> Out {
let node = spring_nodes[spring_ids[instance]];
let time = g.pad;
let offset = vec2<f32>(spring_sample(node.x, time).x, spring_sample(node.y, time).x);
let alpha = clamp(spring_sample(node.opacity, time).x, 0.0, 1.0);
var i = input;
let kind = i.params.y;
// This spike translates geometry under a fixed screen-space clip. No text reflow or scaling.
i.rect = vec4<f32>(i.rect.xy + offset, i.rect.zw);
i.fill *= alpha;
// Match CPU opacity folding (`render/instance.rs` `end_layer`):
// - Rect (0) and Gradient (4) carry opacity in `params.w` for `border_over`.
// - Gradient (4) carries its bottom colour in `uv`.
// - Glyph (2) and Layer (8) store non-colour data in `border`.
if (kind < 0.5) {
i.border *= alpha;
i.params.w *= alpha;
} else if (kind > 3.5 && kind < 4.5) {
i.border *= alpha;
i.uv *= alpha;
i.params.w *= alpha;
} else if (!(kind > 1.5 && kind < 2.5) && !(kind > 7.5 && kind < 8.5)) {
i.border *= alpha;
}
// Vector endpoints are screen-space geometry, unlike image/glyph atlas UVs.
if (kind > 4.5 && kind < 6.5) {
i.radii += vec4<f32>(offset, offset);
if (kind > 5.5) { i.uv = vec4<f32>(i.uv.xy + offset, i.uv.zw); }
}
return base_vs(i);
}