Merge branch 'main' into worktree-agent-a38a174c36aa9f23a
This commit is contained in:
@@ -325,7 +325,7 @@ fn raster_into(e: &mut Enc, s: &Scene) -> Option<(wgpu::Texture, wgpu::Texture)>
|
||||
/// Rasterise a scene and read it back ([`effectcraft_render::Accelerator::raster_3d`]). `None`
|
||||
/// when the device can't (no readback, size or buffer limits).
|
||||
pub(crate) fn render(g: &GpuContext, s: &Scene) -> Option<Target> {
|
||||
if !g.can_readback() {
|
||||
if !g.can_wait() {
|
||||
return None;
|
||||
}
|
||||
let mut e = Enc::new(g);
|
||||
@@ -520,7 +520,7 @@ fn storage_buf(g: &GpuContext, size: u64, label: &str) -> wgpu::Buffer {
|
||||
|
||||
/// Read a storage buffer back (submits and waits).
|
||||
fn read_buffer(e: &mut Enc, buf: &wgpu::Buffer, size: u64) -> Option<Vec<u8>> {
|
||||
if !e.g.can_readback() {
|
||||
if !e.g.can_wait() {
|
||||
return None;
|
||||
}
|
||||
let rb = e.g.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
@@ -560,7 +560,7 @@ const BIG: f32 = 3.0e38;
|
||||
pub(crate) fn resolve_run(e: &mut Enc, prep: &Prepared) -> Option<Option<Resolved>> {
|
||||
let (w, h) = prep.out;
|
||||
let g = e.g;
|
||||
if !g.fits(w, h) || (prep.dof.is_some() && !g.can_readback()) {
|
||||
if !g.fits(w, h) || (prep.dof.is_some() && !g.can_wait()) {
|
||||
return None;
|
||||
}
|
||||
let px = w as u64 * h as u64;
|
||||
@@ -673,7 +673,7 @@ pub(crate) fn finish(e: &mut Enc, r: &Resolved, encode: bool, canvas: Option<&Gp
|
||||
/// [`effectcraft_render::Accelerator::render_3d`]: the whole prepared run on the GPU, read
|
||||
/// back.
|
||||
pub(crate) fn render_prepared(g: &GpuContext, prep: &Prepared) -> Option<Rendered> {
|
||||
if !g.can_readback() {
|
||||
if !g.can_wait() {
|
||||
return None;
|
||||
}
|
||||
let mut e = Enc::new(g);
|
||||
|
||||
+67
-16
@@ -262,6 +262,8 @@ pub struct GpuContext {
|
||||
/// GPU particle pipeline (built on first use) and simulation checkpoints.
|
||||
pub(crate) particles: crate::particles::PipesCell,
|
||||
pub(crate) particle_states: crate::particles::StatesCell,
|
||||
/// Deferred readbacks (a browser worker's WebGPU device), see [`crate::deferred`].
|
||||
pub(crate) deferred: Option<Arc<crate::deferred::Deferred>>,
|
||||
}
|
||||
|
||||
fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
|
||||
@@ -452,27 +454,43 @@ impl GpuContext {
|
||||
adv3d: std::sync::OnceLock::new(),
|
||||
particles: Default::default(),
|
||||
particle_states: Default::default(),
|
||||
deferred: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A device of its own on the best adapter (CLI, tests, benchmarks). `None` when no
|
||||
/// adapter qualifies.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn headless() -> Option<GpuContext> {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let adapter = pollster::block_on(
|
||||
instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }),
|
||||
)
|
||||
.ok()?;
|
||||
/// Switch to deferred readbacks (see [`crate::deferred`]): readbacks are never waited for.
|
||||
pub fn set_deferred(&mut self, on: bool) {
|
||||
self.deferred = on.then(Default::default);
|
||||
}
|
||||
|
||||
pub fn deferred(&self) -> Option<&Arc<crate::deferred::Deferred>> {
|
||||
self.deferred.as_ref()
|
||||
}
|
||||
|
||||
/// A device of its own on the best adapter, without blocking (a browser worker: WebGPU
|
||||
/// only; natively any backend). `Err` says why there is none.
|
||||
pub async fn request() -> Result<GpuContext, String> {
|
||||
#[allow(unused_mut)]
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
desc.backends = wgpu::Backends::BROWSER_WEBGPU;
|
||||
}
|
||||
let instance = wgpu::Instance::new(desc);
|
||||
let adapter = instance
|
||||
.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() })
|
||||
.await
|
||||
.map_err(|e| format!("no adapter: {e}"))?;
|
||||
let limits = adapter.limits();
|
||||
let required_limits = wgpu::Limits {
|
||||
max_texture_dimension_2d: limits.max_texture_dimension_2d.min(16384),
|
||||
max_buffer_size: limits.max_buffer_size,
|
||||
..wgpu::Limits::default()
|
||||
};
|
||||
let (device, queue) =
|
||||
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("effectcraft gpu"), required_limits, ..Default::default() }))
|
||||
.ok()?;
|
||||
let (device, queue) = adapter
|
||||
.request_device(&wgpu::DeviceDescriptor { label: Some("effectcraft gpu"), required_limits, ..Default::default() })
|
||||
.await
|
||||
.map_err(|e| format!("no device: {e}"))?;
|
||||
device.on_uncaptured_error(Arc::new(|e| {
|
||||
// Under test a validation error (a WGSL typo invalidates every kernel) fails loudly.
|
||||
if cfg!(test) {
|
||||
@@ -480,12 +498,26 @@ impl GpuContext {
|
||||
}
|
||||
log::error!("wgpu: {e}")
|
||||
}));
|
||||
GpuContext::new(&adapter, device, queue).map_err(|e| log::info!("gpu: {e}")).ok()
|
||||
GpuContext::new(&adapter, device, queue)
|
||||
}
|
||||
|
||||
/// Readback (GPU → CPU) waits for the device; impossible on the browser's main thread.
|
||||
/// A device of its own on the best adapter (CLI, tests, benchmarks). `None` when no
|
||||
/// adapter qualifies.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn headless() -> Option<GpuContext> {
|
||||
pollster::block_on(GpuContext::request()).map_err(|e| log::info!("gpu: {e}")).ok()
|
||||
}
|
||||
|
||||
/// Readbacks (GPU → CPU) are possible: waited for natively, or deferred (a browser
|
||||
/// worker, [`crate::deferred`]). Impossible on the browser's main thread.
|
||||
pub fn can_readback(&self) -> bool {
|
||||
cfg!(not(target_arch = "wasm32"))
|
||||
self.can_wait() || self.deferred.is_some()
|
||||
}
|
||||
|
||||
/// Readbacks can be waited for (natively, unless deferred). Steps that read back without a
|
||||
/// key ([`crate::deferred`]) need this.
|
||||
pub fn can_wait(&self) -> bool {
|
||||
cfg!(not(target_arch = "wasm32")) && self.deferred.is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn fits(&self, w: u32, h: u32) -> bool {
|
||||
@@ -802,7 +834,7 @@ impl<'g> Enc<'g> {
|
||||
|
||||
/// [`Enc::read_texture`] into `out` (`w × bpp × h` bytes), through a reused staging buffer.
|
||||
fn read_texture_into(&mut self, texture: &wgpu::Texture, w: u32, h: u32, bpp: u32, out: &mut [u8]) -> Option<()> {
|
||||
if !self.g.can_readback() {
|
||||
if !self.g.can_wait() {
|
||||
return None;
|
||||
}
|
||||
self.g.transfers.count(false, out.len());
|
||||
@@ -889,6 +921,25 @@ impl<'g> Enc<'g> {
|
||||
let _ = self.g.device.poll(wgpu::PollType::Poll);
|
||||
}
|
||||
|
||||
/// A deferred readback of `img` (RGBA f32) under `key` (see [`crate::deferred`]): the bytes
|
||||
/// once they arrived (`Some(None)`: the readback failed), else `None` after starting the
|
||||
/// copy if needed and marking the pass missed.
|
||||
pub(crate) fn read_keyed(&mut self, img: &GpuImage, key: u128, offset: [f64; 2], scale: f64) -> Option<Option<crate::deferred::Readback>> {
|
||||
use crate::deferred::Lookup;
|
||||
let d = self.g.deferred.clone()?;
|
||||
match d.lookup(key) {
|
||||
Lookup::Ready(r) => return Some(r),
|
||||
Lookup::InFlight => {}
|
||||
Lookup::Absent => {
|
||||
self.g.transfers.count(false, img.width as usize * img.height as usize * 16);
|
||||
let done = d.start(key, img.width, img.height, offset, scale);
|
||||
self.read_texture_async(&img.texture, img.width, img.height, 16, done);
|
||||
}
|
||||
}
|
||||
d.miss();
|
||||
None
|
||||
}
|
||||
|
||||
/// A data buffer for kernels that read tables (curves).
|
||||
pub fn data(&self, v: &[f32]) -> wgpu::Buffer {
|
||||
let mut bytes = Vec::with_capacity(v.len().max(4) * 4);
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Deferred readbacks: rendering on a device whose readbacks cannot be waited for (WebGPU in a
|
||||
//! browser worker: a buffer maps only once the worker returns to its event loop).
|
||||
//!
|
||||
//! A frame renders in passes (see [`effectcraft_render::Accelerator::frame_begin`]). Every
|
||||
//! readback the renderer needs is keyed by what determines its pixels: a GPU effect chain by
|
||||
//! its input buffer's pixels and the chain's parameters, the top-level frame by comp, time and
|
||||
//! render options. A key seen for the first time records the GPU work, starts an asynchronous
|
||||
//! copy (`map_async`) and *misses*: the step returns a placeholder and the pass is marked missed
|
||||
//! (raising the gate that keeps placeholder-derived buffers out of the layer cache). The caller
|
||||
//! awaits [`Deferred::settled`] and renders again; keys whose bytes arrived are served from
|
||||
//! here. A pass without a miss is the finished frame.
|
||||
//!
|
||||
//! Correctness: a result is only computed from genuine inputs. Pixels a chain reads are part
|
||||
//! of its key, and a chain whose kernels read other data through the effect host (other layers,
|
||||
//! other times) is not started when that data missed while it ran (the miss counter moved).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::future::Future;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll, Waker};
|
||||
|
||||
use effectcraft_effects::Buf;
|
||||
use effectcraft_render::FxStep;
|
||||
|
||||
/// Bytes read back for one key, with the geometry they describe.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Readback {
|
||||
pub bytes: Vec<u8>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Layer buffer offset and scale (chains).
|
||||
pub offset: [f64; 2],
|
||||
pub scale: f64,
|
||||
}
|
||||
|
||||
/// What [`Deferred::lookup`] knows about a key.
|
||||
pub(crate) enum Lookup {
|
||||
/// The bytes arrived (`None`: the readback failed; render this step another way).
|
||||
Ready(Option<Readback>),
|
||||
/// Started in this frame, not arrived yet.
|
||||
InFlight,
|
||||
/// Never asked for in this frame.
|
||||
Absent,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
/// Frame generation: results of an older frame's readbacks are dropped.
|
||||
generation: u64,
|
||||
ready: HashMap<u128, Option<Readback>>,
|
||||
waiting: HashSet<u128>,
|
||||
in_flight: usize,
|
||||
/// Misses so far in this frame (a counter, so a chain sees misses during its own work).
|
||||
misses: u64,
|
||||
wakers: Vec<Waker>,
|
||||
}
|
||||
|
||||
/// Deferred readback state of a device (see the module docs).
|
||||
#[derive(Default)]
|
||||
pub struct Deferred {
|
||||
st: Mutex<State>,
|
||||
/// Raised from the pass's first miss to its end.
|
||||
gate: Arc<AtomicBool>,
|
||||
/// Passes and readbacks (diagnostics).
|
||||
pub(crate) passes: std::sync::atomic::AtomicU64,
|
||||
pub(crate) readbacks: std::sync::atomic::AtomicU64,
|
||||
}
|
||||
|
||||
impl Deferred {
|
||||
pub fn frame_begin(&self) {
|
||||
if let Ok(mut s) = self.st.lock() {
|
||||
s.generation += 1;
|
||||
s.ready.clear();
|
||||
s.waiting.clear();
|
||||
s.misses = 0;
|
||||
}
|
||||
self.gate.store(false, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn pass_begin(&self) {
|
||||
self.gate.store(false, Ordering::Relaxed);
|
||||
self.passes.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn missed(&self) -> bool {
|
||||
self.gate.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn gate(&self) -> Arc<AtomicBool> {
|
||||
self.gate.clone()
|
||||
}
|
||||
|
||||
/// Misses so far in this frame.
|
||||
pub(crate) fn misses(&self) -> u64 {
|
||||
self.st.lock().map(|s| s.misses).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Mark the pass as missed.
|
||||
pub(crate) fn miss(&self) {
|
||||
if let Ok(mut s) = self.st.lock() {
|
||||
s.misses += 1;
|
||||
}
|
||||
self.gate.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn lookup(&self, key: u128) -> Lookup {
|
||||
let Ok(s) = self.st.lock() else { return Lookup::Ready(None) };
|
||||
if let Some(r) = s.ready.get(&key) {
|
||||
return Lookup::Ready(r.clone());
|
||||
}
|
||||
if s.waiting.contains(&key) { Lookup::InFlight } else { Lookup::Absent }
|
||||
}
|
||||
|
||||
/// A readback for `key` is being started; returns the callback that stores its bytes.
|
||||
pub(crate) fn start(self: &Arc<Self>, key: u128, width: u32, height: u32, offset: [f64; 2], scale: f64) -> impl FnOnce(Option<Vec<u8>>) + 'static {
|
||||
let generation = match self.st.lock() {
|
||||
Ok(mut s) => {
|
||||
s.waiting.insert(key);
|
||||
s.in_flight += 1;
|
||||
s.generation
|
||||
}
|
||||
Err(_) => 0,
|
||||
};
|
||||
self.readbacks.fetch_add(1, Ordering::Relaxed);
|
||||
let me = self.clone();
|
||||
move |bytes: Option<Vec<u8>>| {
|
||||
let wakers = match me.st.lock() {
|
||||
Ok(mut s) => {
|
||||
s.in_flight = s.in_flight.saturating_sub(1);
|
||||
if s.generation == generation {
|
||||
s.waiting.remove(&key);
|
||||
s.ready.insert(key, bytes.map(|bytes| Readback { bytes, width, height, offset, scale }));
|
||||
}
|
||||
if s.in_flight == 0 { std::mem::take(&mut s.wakers) } else { vec![] }
|
||||
}
|
||||
Err(_) => vec![],
|
||||
};
|
||||
for w in wakers {
|
||||
w.wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Readbacks still in flight.
|
||||
pub fn in_flight(&self) -> usize {
|
||||
self.st.lock().map(|s| s.in_flight).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Resolves once no readback is in flight (on the web the browser's event loop delivers
|
||||
/// them; natively a device poll does).
|
||||
pub fn settled(self: &Arc<Self>) -> Settled {
|
||||
Settled(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`Deferred::settled`].
|
||||
pub struct Settled(Arc<Deferred>);
|
||||
|
||||
impl Future for Settled {
|
||||
type Output = ();
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
|
||||
let Ok(mut s) = self.0.st.lock() else { return Poll::Ready(()) };
|
||||
if s.in_flight == 0 {
|
||||
return Poll::Ready(());
|
||||
}
|
||||
s.wakers.push(cx.waker().clone());
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
/// 128-bit key from two differently seeded std hashers (deterministic within a process).
|
||||
pub(crate) struct Key(std::collections::hash_map::DefaultHasher, std::collections::hash_map::DefaultHasher);
|
||||
|
||||
impl Key {
|
||||
pub fn new(tag: u64) -> Key {
|
||||
let mut a = std::collections::hash_map::DefaultHasher::new();
|
||||
let mut b = std::collections::hash_map::DefaultHasher::new();
|
||||
tag.hash(&mut a);
|
||||
(tag ^ 0x9e37_79b9_7f4a_7c15).hash(&mut b);
|
||||
0xa5u8.hash(&mut b);
|
||||
Key(a, b)
|
||||
}
|
||||
|
||||
pub fn bytes(&mut self, v: &[u8]) {
|
||||
self.0.write(v);
|
||||
self.1.write(v);
|
||||
}
|
||||
|
||||
pub fn u64(&mut self, v: u64) {
|
||||
self.bytes(&v.to_le_bytes());
|
||||
}
|
||||
|
||||
pub fn f64(&mut self, v: f64) {
|
||||
self.u64(v.to_bits());
|
||||
}
|
||||
|
||||
pub fn debug(&mut self, v: &impl std::fmt::Debug) {
|
||||
self.bytes(format!("{v:?}").as_bytes());
|
||||
self.bytes(&[0xff]);
|
||||
}
|
||||
|
||||
pub fn finish(&self) -> u128 {
|
||||
((self.0.finish() as u128) << 64) | self.1.finish() as u128
|
||||
}
|
||||
}
|
||||
|
||||
/// Key of a GPU effect chain on `buf`: the input pixels and geometry, the bit depth, and every
|
||||
/// step's effect, parameters (sorted) and context.
|
||||
pub(crate) fn chain_key(chain: &[FxStep], buf: &Buf, levels: Option<f32>) -> u128 {
|
||||
let mut k = Key::new(1);
|
||||
k.u64(buf.img.width as u64);
|
||||
k.u64(buf.img.height as u64);
|
||||
k.bytes(bytemuck::cast_slice(&buf.img.data));
|
||||
k.f64(buf.offset[0]);
|
||||
k.f64(buf.offset[1]);
|
||||
k.f64(buf.scale);
|
||||
k.debug(&levels);
|
||||
for s in chain {
|
||||
let c = &s.ctx;
|
||||
k.bytes(s.spec.id.as_bytes());
|
||||
let mut names: Vec<&String> = c.params.values.keys().collect();
|
||||
names.sort();
|
||||
for n in names {
|
||||
k.bytes(n.as_bytes());
|
||||
k.debug(&c.params.values[n]);
|
||||
}
|
||||
k.f64(c.time);
|
||||
k.f64(c.layer_size[0]);
|
||||
k.f64(c.layer_size[1]);
|
||||
k.u64(c.seed as u64);
|
||||
k.u64(c.adjustment as u64);
|
||||
let e = &c.env;
|
||||
k.debug(&e.masks);
|
||||
k.u64(e.host.is_some() as u64);
|
||||
k.f64(e.comp_time);
|
||||
k.f64(e.frame_rate);
|
||||
k.u64(e.effect_index as u64);
|
||||
k.debug(&e.working_space);
|
||||
k.u64(e.working_linear as u64);
|
||||
k.debug(&e.shutter);
|
||||
}
|
||||
k.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn keys_are_stable_and_distinct() {
|
||||
let mut a = Key::new(1);
|
||||
a.bytes(b"abc");
|
||||
let mut b = Key::new(1);
|
||||
b.bytes(b"abc");
|
||||
let mut c = Key::new(2);
|
||||
c.bytes(b"abc");
|
||||
assert_eq!(a.finish(), b.finish());
|
||||
assert_ne!(a.finish(), c.finish());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readbacks_resolve_and_old_frames_are_dropped() {
|
||||
let d = Arc::new(Deferred::default());
|
||||
d.frame_begin();
|
||||
d.pass_begin();
|
||||
assert!(matches!(d.lookup(7), Lookup::Absent));
|
||||
let done = d.start(7, 2, 1, [1.0, 2.0], 0.5);
|
||||
d.miss();
|
||||
assert!(d.missed() && d.gate().load(Ordering::Relaxed));
|
||||
assert!(matches!(d.lookup(7), Lookup::InFlight));
|
||||
assert_eq!(d.in_flight(), 1);
|
||||
// The settle future wakes when the last readback lands.
|
||||
let mut fut = std::pin::pin!(d.settled());
|
||||
let waker = Waker::noop();
|
||||
assert!(fut.as_mut().poll(&mut Context::from_waker(waker)).is_pending());
|
||||
done(Some(vec![1, 2, 3, 4, 5, 6, 7, 8]));
|
||||
assert!(fut.as_mut().poll(&mut Context::from_waker(waker)).is_ready());
|
||||
let Lookup::Ready(Some(r)) = d.lookup(7) else { panic!("not ready") };
|
||||
assert_eq!((r.width, r.height, r.offset, r.scale, r.bytes.len()), (2, 1, [1.0, 2.0], 0.5, 8));
|
||||
d.pass_begin();
|
||||
assert!(!d.missed());
|
||||
// A readback of the previous frame arriving late is dropped.
|
||||
let late = d.start(9, 1, 1, [0.0; 2], 1.0);
|
||||
d.frame_begin();
|
||||
late(Some(vec![0; 4]));
|
||||
assert!(matches!(d.lookup(9), Lookup::Absent));
|
||||
assert!(matches!(d.lookup(7), Lookup::Absent));
|
||||
assert_eq!(d.in_flight(), 0);
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,20 @@ pub(crate) fn run_chain(e: &mut Enc, chain: &[FxStep], buf: &Buf, levels: Option
|
||||
if !e.g.can_readback() || buf.img.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Deferred readbacks (a browser worker): served by key once the bytes arrived.
|
||||
let deferred = e.g.deferred.clone();
|
||||
let key = deferred.as_ref().map(|_| crate::deferred::chain_key(chain, buf, levels));
|
||||
if let (Some(d), Some(k)) = (&deferred, key) {
|
||||
match d.lookup(k) {
|
||||
crate::deferred::Lookup::Ready(r) => return r.and_then(readback_buf),
|
||||
crate::deferred::Lookup::InFlight => {
|
||||
d.miss();
|
||||
return Some(buf.clone());
|
||||
}
|
||||
crate::deferred::Lookup::Absent => {}
|
||||
}
|
||||
}
|
||||
let misses = deferred.as_ref().map(|d| d.misses());
|
||||
let mut b = GBuf { img: e.g.upload_image(&buf.img)?, offset: buf.offset, scale: buf.scale };
|
||||
for step in chain {
|
||||
b = apply(e, step.spec.id, &step.ctx, b)?;
|
||||
@@ -58,10 +72,30 @@ pub(crate) fn run_chain(e: &mut Enc, chain: &[FxStep], buf: &Buf, levels: Option
|
||||
b.img = ops::quantize(e, &b.img, l);
|
||||
}
|
||||
}
|
||||
if let (Some(d), Some(k)) = (&deferred, key) {
|
||||
// Data the kernels fetched through the effect host missed meanwhile: not genuine.
|
||||
if Some(d.misses()) != misses {
|
||||
d.miss();
|
||||
return Some(buf.clone());
|
||||
}
|
||||
// The placeholder (the input) keeps this pass cheap; the next pass gets the result.
|
||||
return match e.read_keyed(&b.img, k, b.offset, b.scale) {
|
||||
Some(r) => r.and_then(readback_buf),
|
||||
None => Some(buf.clone()),
|
||||
};
|
||||
}
|
||||
let img = e.download(&b.img)?;
|
||||
Some(Buf { img, offset: b.offset, scale: b.scale })
|
||||
}
|
||||
|
||||
/// A layer buffer from deferred readback bytes (RGBA f32).
|
||||
fn readback_buf(r: crate::deferred::Readback) -> Option<Buf> {
|
||||
let mut img = effectcraft_raster::Image::new(r.width, r.height);
|
||||
let dst: &mut [u8] = bytemuck::cast_slice_mut(&mut img.data);
|
||||
(dst.len() == r.bytes.len()).then(|| dst.copy_from_slice(&r.bytes))?;
|
||||
Some(Buf { img, offset: r.offset, scale: r.scale })
|
||||
}
|
||||
|
||||
/// An effect stack running on a GPU-resident image (adjustment layers): GPU chains stay on
|
||||
/// the device; CPU effects read the image back, run, and upload the result.
|
||||
pub(crate) struct GpuFx<'e, 'g> {
|
||||
|
||||
+101
-1
@@ -49,6 +49,7 @@ mod adv3d;
|
||||
mod bokeh;
|
||||
mod classic3d;
|
||||
mod context;
|
||||
pub mod deferred;
|
||||
mod effects;
|
||||
mod fx_color;
|
||||
mod fx_distort;
|
||||
@@ -112,6 +113,44 @@ impl Gpu {
|
||||
Gpu { ctx: Arc::new(ctx), auto: Default::default() }
|
||||
}
|
||||
|
||||
/// A device of its own without blocking, with deferred readbacks (a browser worker, see
|
||||
/// [`deferred`]); natively the same device works too (tests). `Err` says why there is none.
|
||||
pub async fn request_deferred() -> Result<Gpu, String> {
|
||||
let mut ctx = GpuContext::request().await?;
|
||||
ctx.set_deferred(true);
|
||||
Ok(Gpu::from_context(ctx))
|
||||
}
|
||||
|
||||
/// [`Gpu::request_deferred`] blocking (tests of the browser worker's path, natively).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn headless_deferred() -> Option<Gpu> {
|
||||
pollster::block_on(Gpu::request_deferred()).map_err(|e| log::info!("gpu: {e}")).ok()
|
||||
}
|
||||
|
||||
/// The deferred readback state, when readbacks are deferred.
|
||||
pub fn deferred(&self) -> Option<&Arc<deferred::Deferred>> {
|
||||
self.ctx.deferred()
|
||||
}
|
||||
|
||||
/// Resolves once no deferred readback is in flight (immediately without deferred readbacks).
|
||||
pub async fn settled(&self) {
|
||||
if let Some(d) = self.ctx.deferred() {
|
||||
d.settled().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Deliver finished readbacks without blocking (native; the browser delivers them itself).
|
||||
pub fn poll(&self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let _ = self.ctx.device.poll(wgpu::PollType::Poll);
|
||||
}
|
||||
|
||||
/// `{passes, readbacks, inFlight}` of deferred rendering (diagnostics).
|
||||
pub fn deferred_stats(&self) -> Option<(u64, u64, usize)> {
|
||||
let d = self.ctx.deferred()?;
|
||||
Some((d.passes.load(std::sync::atomic::Ordering::Relaxed), d.readbacks.load(std::sync::atomic::Ordering::Relaxed), d.in_flight()))
|
||||
}
|
||||
|
||||
pub fn context(&self) -> &GpuContext {
|
||||
&self.ctx
|
||||
}
|
||||
@@ -146,11 +185,50 @@ impl Gpu {
|
||||
if !self.ctx.can_readback() {
|
||||
return None;
|
||||
}
|
||||
if let Some(d) = self.ctx.deferred.clone() {
|
||||
return self.render_deferred(&d, r, comp, t);
|
||||
}
|
||||
let mut e = Enc::new(&self.ctx);
|
||||
let img = walk::render(&mut e, r, comp, t)?;
|
||||
e.download(&img)
|
||||
}
|
||||
|
||||
/// [`Gpu::render`] with deferred readbacks: the frame's readback is keyed by comp, time and
|
||||
/// render options; until it arrives (or while layer steps still miss) the pass gets a
|
||||
/// placeholder.
|
||||
fn render_deferred(&self, d: &Arc<deferred::Deferred>, r: &Renderer, comp: ItemId, t: Tick) -> Option<Image> {
|
||||
let mut k = deferred::Key::new(2);
|
||||
k.u64(comp.0);
|
||||
k.u64(t.0 as u64);
|
||||
k.debug(&r.opts);
|
||||
let key = k.finish();
|
||||
let image = |rb: deferred::Readback| -> Option<Image> {
|
||||
let mut img = Image::new(rb.width, rb.height);
|
||||
let dst: &mut [u8] = bytemuck::cast_slice_mut(&mut img.data);
|
||||
(dst.len() == rb.bytes.len()).then(|| dst.copy_from_slice(&rb.bytes))?;
|
||||
Some(img)
|
||||
};
|
||||
match d.lookup(key) {
|
||||
deferred::Lookup::Ready(rb) => return rb.and_then(image),
|
||||
deferred::Lookup::InFlight => {
|
||||
d.miss();
|
||||
return Some(Image::new(1, 1));
|
||||
}
|
||||
deferred::Lookup::Absent => {}
|
||||
}
|
||||
let misses = d.misses();
|
||||
let mut e = Enc::new(&self.ctx);
|
||||
let img = walk::render(&mut e, r, comp, t)?;
|
||||
if d.misses() != misses {
|
||||
// Layer steps are still in flight: this pass's canvas is not the frame.
|
||||
return Some(Image::new(1, 1));
|
||||
}
|
||||
match e.read_keyed(&img, key, [0.0; 2], 1.0) {
|
||||
Some(rb) => rb.and_then(image),
|
||||
None => Some(Image::new(1, 1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for all submitted GPU work (benchmarks).
|
||||
pub fn wait(&self) {
|
||||
let _ = self.ctx.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
@@ -183,12 +261,32 @@ impl Accelerator for Gpu {
|
||||
}
|
||||
|
||||
fn particles(&self) -> Option<&dyn effectcraft_effects::psim::ParticleSim> {
|
||||
self.ctx.can_readback().then_some(self as &dyn effectcraft_effects::psim::ParticleSim)
|
||||
self.ctx.can_wait().then_some(self as &dyn effectcraft_effects::psim::ParticleSim)
|
||||
}
|
||||
|
||||
fn auto_pick(&self) -> Option<&effectcraft_render::AutoPick> {
|
||||
Some(&self.auto)
|
||||
}
|
||||
|
||||
fn frame_begin(&self) {
|
||||
if let Some(d) = self.ctx.deferred() {
|
||||
d.frame_begin();
|
||||
}
|
||||
}
|
||||
|
||||
fn pass_begin(&self) {
|
||||
if let Some(d) = self.ctx.deferred() {
|
||||
d.pass_begin();
|
||||
}
|
||||
}
|
||||
|
||||
fn pass_missed(&self) -> bool {
|
||||
self.ctx.deferred().is_some_and(|d| d.missed())
|
||||
}
|
||||
|
||||
fn miss_gate(&self) -> Option<Arc<std::sync::atomic::AtomicBool>> {
|
||||
self.ctx.deferred().map(|d| d.gate())
|
||||
}
|
||||
}
|
||||
|
||||
impl effectcraft_effects::psim::ParticleSim for Gpu {
|
||||
@@ -206,6 +304,8 @@ mod tests_adjust;
|
||||
#[cfg(test)]
|
||||
mod tests_adv3d;
|
||||
#[cfg(test)]
|
||||
mod tests_deferred;
|
||||
#[cfg(test)]
|
||||
mod tests_fx_color;
|
||||
#[cfg(test)]
|
||||
mod tests_fx_distort;
|
||||
|
||||
@@ -109,7 +109,7 @@ fn uniforms(req: &SimRequest, n: u32, s0: u64, prev_n: u32) -> Vec<u8> {
|
||||
|
||||
/// Simulate `req` (see [`effectcraft_effects::psim::ParticleSim`]).
|
||||
pub(crate) fn simulate(g: &GpuContext, req: &SimRequest) -> Option<Vec<SimParticle>> {
|
||||
if !g.can_readback() || req.steps > u32::MAX as u64 {
|
||||
if !g.can_wait() || req.steps > u32::MAX as u64 {
|
||||
return None;
|
||||
}
|
||||
let n = req.births.len() as u32;
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
// effectcraft-effects operation for operation. Every name here is prefixed `fxn_` (the
|
||||
// family files share one module).
|
||||
|
||||
const FXN_MAX: f32 = 3.40282347e38;
|
||||
// f32::MAX exactly (a decimal that rounds above it is rejected by browsers' WGSL compilers).
|
||||
const FXN_MAX: f32 = 3.4028234663852886e38;
|
||||
|
||||
fn fxn_pixel(gid: vec3<u32>) -> vec2<i32> {
|
||||
let dims = out_dims();
|
||||
|
||||
@@ -562,3 +562,45 @@ fn backend_selection_and_display_frames() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Browsers' WGSL compilers reject an f32 literal whose exact decimal value lies outside the f32
|
||||
/// range (`3.40282347e38` rounds to f32::MAX in Rust but exceeds it), which invalidates the whole
|
||||
/// module (every kernel); naga accepts it, so native runs can't catch it. Every float literal
|
||||
/// with an exponent must be within the f32 range exactly.
|
||||
#[test]
|
||||
fn wgsl_float_literals_fit_f32() {
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/shaders");
|
||||
let mut checked = 0;
|
||||
for entry in std::fs::read_dir(&dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let src = std::fs::read_to_string(&path).unwrap();
|
||||
for (n, line) in src.lines().enumerate() {
|
||||
let code = line.split("//").next().unwrap_or("");
|
||||
let bytes = code.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
let starts = bytes[i].is_ascii_digit() && (i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_' || bytes[i - 1] == b'.'));
|
||||
if !starts {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i;
|
||||
while j < bytes.len()
|
||||
&& (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'.' || ((bytes[j] == b'-' || bytes[j] == b'+') && matches!(bytes[j - 1], b'e' | b'E')))
|
||||
{
|
||||
j += 1;
|
||||
}
|
||||
let lit = code[i..j].trim_end_matches('f');
|
||||
if !lit.starts_with("0x")
|
||||
&& lit.contains(['e', 'E'])
|
||||
&& let Ok(v) = lit.parse::<f64>()
|
||||
{
|
||||
checked += 1;
|
||||
assert!(v.abs() <= f32::MAX as f64, "{}:{}: {lit} is outside the f32 range", path.display(), n + 1);
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(checked > 0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Deferred readbacks (the browser worker's WebGPU path) vs the CPU: a frame renders in passes
|
||||
//! until no readback is missing, and the result matches the CPU render. Natively the same
|
||||
//! device works with readbacks deferred; a device poll delivers them, as the browser's event
|
||||
//! loop does.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build;
|
||||
use effectcraft_project::{BitDepth, Comp, ItemKind, LayerSource};
|
||||
use effectcraft_render::{Accelerator, Backend, LayerCache, RenderOpts, Renderer};
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
|
||||
use crate::Gpu;
|
||||
use crate::tests::{Pattern, Scene, diff, n, set, tolerance, v3};
|
||||
|
||||
/// The device, held exclusively: deferred state is per device and a frame renders at a time
|
||||
/// (a frame worker renders one frame at a time too).
|
||||
fn deferred_gpu() -> Option<(&'static Gpu, std::sync::MutexGuard<'static, ()>)> {
|
||||
static G: OnceLock<Option<Gpu>> = OnceLock::new();
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
let g = G.get_or_init(|| pollster::block_on(Gpu::request_deferred()).map_err(|e| eprintln!("deferred gpu tests skipped: {e}")).ok()).as_ref()?;
|
||||
Some((g, LOCK.lock().unwrap_or_else(|e| e.into_inner())))
|
||||
}
|
||||
|
||||
/// Footage with GPU effects around a CPU-only one, a solid with Glow, and a precomp whose
|
||||
/// layer is blurred inside and outside (a chain whose input is another chain's result).
|
||||
fn scene() -> Scene {
|
||||
let cpu_only = "ec.blur.ccradial";
|
||||
assert!(!effectcraft_effects::GPU_EFFECTS.contains(&cpu_only));
|
||||
let mut s = Scene::new(BitDepth::Bpc32);
|
||||
let mut bg = s.footage(97, 61);
|
||||
s.effect(&mut bg, "ec.blur.gaussian", &[("blurriness", n(5.0))]);
|
||||
s.effect(&mut bg, cpu_only, &[]);
|
||||
s.effect(&mut bg, "ec.color.levels", &[("gamma", n(1.3))]);
|
||||
s.push(bg);
|
||||
let mut solid = s.solid([0.9, 0.4, 0.1], 30, 20);
|
||||
s.effect(&mut solid, "ec.stylize.glow", &[("threshold", n(20.0)), ("radius", n(6.0))]);
|
||||
set(&mut solid, "transform/position", v3(30.0, 20.0));
|
||||
s.push(solid);
|
||||
// Precomp: a footage layer blurred inside; the precomp layer blurred again outside.
|
||||
let inner = Comp::new(60, 40, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
|
||||
let inner_id = s.p.add_item("Inner", effectcraft_color::Label::Blue, None, ItemKind::Comp(inner.clone().into()));
|
||||
{
|
||||
let mut ins = Scene { p: std::mem::take(&mut s.p), cid: inner_id, comp: inner };
|
||||
let mut l = ins.footage(50, 30);
|
||||
ins.effect(&mut l, "ec.blur.fastbox", &[("radius", n(3.0))]);
|
||||
ins.push(l);
|
||||
s.p = ins.p;
|
||||
}
|
||||
let mut pre = build::layer(&mut s.p, &s.comp, "Inner", LayerSource::Comp { item: inner_id }, (60, 40), None);
|
||||
s.effect(&mut pre, "ec.blur.directional", &[("length", n(6.0)), ("direction", Value::Scalar(30.0))]);
|
||||
set(&mut pre, "transform/position", v3(60.0, 35.0));
|
||||
s.push(pre);
|
||||
s
|
||||
}
|
||||
|
||||
/// Render in passes with deferred readbacks; returns the frame and the number of passes.
|
||||
fn render_passes(g: &Gpu, s: &Scene, opts: RenderOpts, cache: &LayerCache, t: Tick) -> (effectcraft_raster::Image, usize) {
|
||||
cache.set_gate(g.miss_gate());
|
||||
let mut r = Renderer::new(&s.p, &Pattern, opts);
|
||||
r.accel = Some(g);
|
||||
r.cache = Some(cache);
|
||||
g.frame_begin();
|
||||
for pass in 1..=12 {
|
||||
g.pass_begin();
|
||||
let img = r.comp_frame(s.cid, t);
|
||||
if !g.pass_missed() {
|
||||
assert_eq!(g.deferred().unwrap().in_flight(), 0);
|
||||
return (img, pass);
|
||||
}
|
||||
// The browser awaits `Gpu::settled`; natively a blocking poll delivers the readbacks.
|
||||
g.wait();
|
||||
pollster::block_on(g.settled());
|
||||
}
|
||||
panic!("the frame never completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deferred_passes_match_the_cpu() {
|
||||
let Some((g, _lock)) = deferred_gpu() else { return };
|
||||
assert!(g.context().can_readback() && !g.context().can_wait());
|
||||
let s = scene();
|
||||
let t = Tick::from_seconds_f64(0.5);
|
||||
let cpu = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Cpu, ..Default::default() }).comp_frame_cpu(s.cid, t);
|
||||
let tol = tolerance(BitDepth::Bpc32) * 2.0;
|
||||
// The whole frame on the GPU (GPU compositor + chains + the frame's readback).
|
||||
let cache = LayerCache::default();
|
||||
let (img, passes) = render_passes(g, &s, RenderOpts { backend: Backend::Gpu, ..Default::default() }, &cache, t);
|
||||
let d = diff(&cpu, &img, tol);
|
||||
assert!(d.over == 0, "whole-frame GPU: {d:?}");
|
||||
assert!(passes >= 3, "chains, the nested chain, then the frame readback: {passes} passes");
|
||||
// Again (a new frame: results are per frame; the layer cache holds the genuine buffers of
|
||||
// the cacheable layers): the same pixels.
|
||||
let (img2, passes2) = render_passes(g, &s, RenderOpts { backend: Backend::Gpu, ..Default::default() }, &cache, t);
|
||||
assert_eq!(img2.data, img.data);
|
||||
assert!(passes2 <= passes, "{passes2} <= {passes}");
|
||||
// CPU compositing with GPU chains (a region of interest keeps the frame off the GPU
|
||||
// compositor): every placeholder is gone by the last pass.
|
||||
let roi = Some([0.0, 0.0, 97.0, 61.0]);
|
||||
let cpu_roi = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Cpu, roi, ..Default::default() }).comp_frame_cpu(s.cid, t);
|
||||
let (img3, passes3) = render_passes(g, &s, RenderOpts { backend: Backend::Gpu, roi, ..Default::default() }, &LayerCache::default(), t);
|
||||
let d = diff(&cpu_roi, &img3, tol);
|
||||
assert!(d.over == 0, "CPU composite, GPU chains: {d:?}");
|
||||
assert!(passes3 >= 2);
|
||||
let (p, rb, inflight) = g.deferred_stats().unwrap();
|
||||
assert!(p >= (passes + passes2 + passes3) as u64 && rb > 0 && inflight == 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholders_never_reach_the_layer_cache() {
|
||||
let Some((g, _lock)) = deferred_gpu() else { return };
|
||||
let s = scene();
|
||||
let t = Tick::from_seconds_f64(1.0);
|
||||
let cache = LayerCache::default();
|
||||
cache.set_gate(g.miss_gate());
|
||||
let mut r = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Gpu, roi: Some([0.0, 0.0, 97.0, 61.0]), ..Default::default() });
|
||||
r.accel = Some(g);
|
||||
r.cache = Some(&cache);
|
||||
g.frame_begin();
|
||||
g.pass_begin();
|
||||
let _ = r.comp_frame(s.cid, t);
|
||||
assert!(g.pass_missed());
|
||||
// Only buffers computed before the first miss were kept (the first layer's input up to its
|
||||
// first chain: nothing with an effect result).
|
||||
let first_pass_entries = cache.stats().entries;
|
||||
g.wait();
|
||||
pollster::block_on(g.settled());
|
||||
let (img, _) = render_passes(g, &s, RenderOpts { backend: Backend::Gpu, roi: Some([0.0, 0.0, 97.0, 61.0]), ..Default::default() }, &cache, t);
|
||||
assert!(cache.stats().entries > first_pass_entries, "{first_pass_entries} → {:?}", cache.stats());
|
||||
// A fresh CPU render through the same cache (served from it) agrees with the CPU.
|
||||
let mut cr = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Cpu, roi: Some([0.0, 0.0, 97.0, 61.0]), ..Default::default() });
|
||||
cr.cache = Some(&cache);
|
||||
let cached = cr.comp_frame_cpu(s.cid, t);
|
||||
let fresh =
|
||||
Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Cpu, roi: Some([0.0, 0.0, 97.0, 61.0]), ..Default::default() }).comp_frame_cpu(s.cid, t);
|
||||
let tol = tolerance(BitDepth::Bpc32) * 2.0;
|
||||
assert_eq!(diff(&fresh, &cached, tol).over, 0);
|
||||
assert_eq!(diff(&fresh, &img, tol).over, 0);
|
||||
}
|
||||
Reference in New Issue
Block a user