Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

Page: a Vello draw that was skipped (a scene past its bump buffers: Vello's fine stage then writes nothing and reports no error, so a pooled layer showed its last frame's picture, or nothing) is found by a sentinel texel read back without a wait, and the frame read back next and those in flight are drawn again at Vello's own sizes, which stay on; a draw skipped at those too refuses the frame by its number. The check's cost on an ordinary 1080p page, five alternating 300-frame renders each: 257.7 fps without it, 253.3 with it. RAEA_VELLO_BUMP=full and RAEA_PAGE_DRAWN_CHECK=0 in docs/settings.md (closes #23)

shinyobjectzabd167408a55
diff --git a/docs/settings.md b/docs/settings.md
index 0291d6a6..58d43afd 100644
--- a/docs/settings.md
+++ b/docs/settings.md
@@ -41,3 +41,10 @@ libraries (pianos, General MIDI instruments, orchestral and percussion samples,
|---|---|
| `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` | The checks' judge model (clef-omni on Workers AI) |
| `RAEA_GUIDES` | A folder of craft references for the agent's `guide` tool (`captions.md`, `motion-rules.md`, ...) |
+
+## Rendering
+
+| Setting | What |
+|---|---|
+| `RAEA_VELLO_BUMP=full` | Pages are drawn with Vello's own buffer sizes from the first frame, instead of raea's smaller ones (about 100 MB less GPU memory). A page past raea's sizes is found and drawn again at Vello's anyway, with a line on stderr, so this only saves that redraw |
+| `RAEA_PAGE_DRAWN_CHECK=0` | Pages are drawn without checking that Vello drew them. For measuring what the check costs (about 2% in one test): a page past Vello's buffers then shows the frame before it again, or nothing |
diff --git a/engine/render/src/engine/output.rs b/engine/render/src/engine/output.rs
index df7dc54c..e0262faa 100644
--- a/engine/render/src/engine/output.rs
+++ b/engine/render/src/engine/output.rs
@@ -174,7 +174,10 @@ impl Engine {
#[cfg(feature = "native")]
pub(crate) fn black_checked(&mut self, f: i64, px: Vec<u8>) -> Result<Vec<u8>, String> {
if self.nv12 {
- return raea_gpu_device::check::refused().map_or(Ok(px), |why| Err(format!("frame {f}: {why}")));
+ if let Some(why) = raea_gpu_device::check::refused() {
+ return Err(format!("frame {f}: {why}"));
+ }
+ return raea_gpu_device::check::skip_checked(f, px, raea_sys_page::redraw_full, || self.frame(f));
}
let (px, black) = raea_gpu_device::check::black_checked(f, px, raea_sys_page::redraw_full, || self.frame(f))?;
if black {
diff --git a/gpu/device/src/check.rs b/gpu/device/src/check.rs
index ad67d2e7..d961f571 100644
--- a/gpu/device/src/check.rs
+++ b/gpu/device/src/check.rs
@@ -108,6 +108,58 @@ pub fn refused() -> Option<String> {
REFUSED.lock().unwrap_or_else(|e| e.into_inner()).take()
}
+/// A page draw Vello skipped (raea-page skipped.rs: past its bump buffers, with no error), found as its read back came
+/// in, with what it says if Vello's own sizes skip it too.
+static SKIPPED: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
+/// Frames still to draw again since a skipped draw was found: its answer comes in with the wait for some frame's
+/// pixels, which may be that frame's or one drawn ahead of it (a render keeps up to 3 in flight: raea-render output.rs
+/// frames_run), so the frame being read back and the 3 after it are drawn again.
+static REDRAW_LEFT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+const IN_FLIGHT: u32 = 3;
+
+/// A page draw was skipped: `why` says so if it's skipped at Vello's own sizes too (the first one's kept until read).
+pub fn skipped_draw(why: String) {
+ SKIPPED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(why);
+}
+
+/// What makes the draws' read backs that are done answer (raea-page's non-blocking poll of its device, `on_settle`).
+static SETTLE: std::sync::OnceLock<fn()> = std::sync::OnceLock::new();
+
+/// Called before each frame's check: by then the frame's draws are done on the GPU, so their read backs answer.
+pub fn on_settle(settle: fn()) {
+ let _ = SETTLE.set(settle);
+}
+
+fn take_skipped() -> Option<String> {
+ if let Some(settle) = SETTLE.get() {
+ settle();
+ }
+ SKIPPED.lock().unwrap_or_else(|e| e.into_inner()).take()
+}
+
+/// Frame `f`'s pixels, drawn again (`again`, every page with Vello's own sizes: `redraw_full`) when a page draw was skipped since the last
+/// frame read back or in the frames just before it; Err naming the frame when the redraw is skipped too (#23). Every
+/// render's readback calls it, through `black_checked` or (NV12) on its own.
+pub fn skip_checked(f: i64, px: Vec<u8>, redraw_full: fn(bool), again: impl FnOnce() -> Result<Vec<u8>, String>) -> Result<Vec<u8>, String> {
+ use std::sync::atomic::Ordering::Relaxed;
+ if take_skipped().is_some() {
+ REDRAW_LEFT.store(IN_FLIGHT + 1, Relaxed);
+ }
+ if REDRAW_LEFT.load(Relaxed) == 0 {
+ return Ok(px);
+ }
+ REDRAW_LEFT.fetch_sub(1, Relaxed);
+ // every page drawn again (a page painted as before isn't, else)
+ redraw_full(true);
+ let redrawn = again();
+ redraw_full(false);
+ let redrawn = redrawn?;
+ if let Some(why) = take_skipped() {
+ return Err(format!("frame {f}: {why}"));
+ }
+ Ok(redrawn)
+}
+
/// Vello's seven bump buffers for a render of `w` x `h`, in bytes, at the sizes the render has (vello_encoding's
/// bump_sizes_for: grown with the target past 1080p).
pub fn bump_bytes(w: u32, h: u32) -> [(&'static str, u64); 7] {
@@ -171,6 +223,32 @@ mod tests {
assert!(e.contains("15360x8640") && e.contains("isn't drawn"), "{e}");
}
+ // a skipped page draw (#23): the frame read back and the 3 in flight after it drawn again with every page redrawn;
+ // a redraw skipped too refuses the frame by its number. One test, as the state is the process's.
+ #[test]
+ fn skipped_draws_are_drawn_again_or_refused() {
+ static FULL: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+ fn full(on: bool) {
+ if on {
+ FULL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ }
+ }
+ assert_eq!(skip_checked(1, vec![1], full, || panic!("no draw skipped")).unwrap(), vec![1]);
+ skipped_draw("past even Vello's sizes".into());
+ for f in 2..6 {
+ assert_eq!(skip_checked(f, vec![1], full, || Ok(vec![2])).unwrap(), vec![2], "frame {f} drawn again");
+ }
+ assert_eq!(FULL.load(std::sync::atomic::Ordering::Relaxed), 4, "every page redrawn each time");
+ assert_eq!(skip_checked(6, vec![1], full, || panic!("past the frames in flight")).unwrap(), vec![1]);
+ skipped_draw("past even Vello's sizes".into());
+ let e = skip_checked(7, vec![1], full, || {
+ skipped_draw("a page (1920x1080) wasn't drawn".into());
+ Ok(vec![2])
+ })
+ .unwrap_err();
+ assert_eq!(e, "frame 7: a page (1920x1080) wasn't drawn");
+ }
+
#[test]
fn render_memory_fits_or_refuses() {
let cap = Some(24 << 30);
@@ -188,10 +266,11 @@ mod tests {
/// a Vello overflow or a GPU fault (wgpu-hal's Metal backend doesn't report a command buffer that ended in error) draws
/// a frame black and says nothing. kitchen/water.tsx came out so under a loaded GPU, 10-26. Black again too, or black
/// once the render knows its scene draws black (`scene_black`), (true): the caller asks the GPUs (`black_twice`).
-pub fn black_checked(f: i64, px: Vec<u8>, redraw_full: fn(bool), again: impl FnOnce() -> Result<Vec<u8>, String>) -> Result<(Vec<u8>, bool), String> {
+pub fn black_checked(f: i64, px: Vec<u8>, redraw_full: fn(bool), mut again: impl FnMut() -> Result<Vec<u8>, String>) -> Result<(Vec<u8>, bool), String> {
if let Some(why) = refused() {
return Err(format!("frame {f}: {why}"));
}
+ let px = skip_checked(f, px, redraw_full, &mut again)?;
let px = injected(px, false);
if !black(&px) {
return Ok((px, false));
diff --git a/systems/page/src/draw.rs b/systems/page/src/draw.rs
index 6c657139..b3e33bbe 100644
--- a/systems/page/src/draw.rs
+++ b/systems/page/src/draw.rs
@@ -174,7 +174,7 @@ pub fn draw(mut scenes: ResMut<Scenes>, mut vello: NonSendMut<Vello>, device: Re
for before in &layers[..i] {
renderer.mark_override_image_dirty(&before.image);
}
- let drawn = passes.texture(device, layer.size, TextureFormat::Rgba8Unorm, TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING | TextureUsages::RENDER_ATTACHMENT);
+ let drawn = passes.texture(device, layer.size, TextureFormat::Rgba8Unorm, TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING | TextureUsages::RENDER_ATTACHMENT | skipped::USAGE);
let mut passes_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("raea-page filters") });
match &layer.linear {
// a pattern tile's gradient, drawn exactly (filters.rs Linear)
@@ -187,8 +187,8 @@ pub fn draw(mut scenes: ResMut<Scenes>, mut vello: NonSendMut<Vello>, device: Re
if let Err(why) = bump_guard(device, layer.size.0, layer.size.1) {
error!("raea-page: {why}");
raea_gpu_device::check::refuse(why);
- } else if let Err(err) = renderer.render_to_texture(device, &queue, &layer.scene, &drawn.create_view(&default()), &params) {
- error!("raea-page: vello, a filtered layer: {err}");
+ } else if let Err(err) = skipped::render(renderer, device, &queue, &layer.scene, &drawn, &params, "a filtered layer") {
+ error!("raea-page: {err}");
}
}
}
@@ -203,7 +203,6 @@ pub fn draw(mut scenes: ResMut<Scenes>, mut vello: NonSendMut<Vello>, device: Re
*at = px;
}
}).or_insert_with(|| (storage(device, px), px));
- let view = tex.create_view(&default());
let params = vello::RenderParams { base_color: vello::peniko::Color::TRANSPARENT, width: px.x, height: px.y, antialiasing_method: vello::AaConfig::Area };
if std::env::var_os("RAEA_VELLO_BUMP_USE").is_some() {
bump_use("page", scene, px.x, px.y);
@@ -221,15 +220,16 @@ pub fn draw(mut scenes: ResMut<Scenes>, mut vello: NonSendMut<Vello>, device: Re
for layer in layers {
renderer.mark_override_image_dirty(&layer.image);
}
- let drew = renderer.render_to_texture(device, &queue, &scene, &view, &params);
+ let drew = skipped::render(renderer, device, &queue, scene, tex, &params, "a page");
+ let view = tex.create_view(&default());
for layer in layers {
renderer.override_image(&layer.image, None);
}
if std::env::var_os("RAEA_TRACE").is_some() {
- eprintln!("trace raea-page: page drawn {}x{}, full bump {}, {}", px.x, px.y, REDRAW_FULL.load(std::sync::atomic::Ordering::Relaxed), drew.as_ref().map_or_else(|e| e.to_string(), |_| "ok".into()));
+ eprintln!("trace raea-page: page drawn {}x{}, full bump {}, {}", px.x, px.y, REDRAW_FULL.load(std::sync::atomic::Ordering::Relaxed), drew.as_ref().map_or_else(Clone::clone, |_| "ok".into()));
}
if let Err(err) = drew {
- error!("raea-page: vello: {err}");
+ error!("raea-page: {err}");
continue;
}
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
@@ -276,7 +276,7 @@ pub fn storage(device: &wgpu::Device, px: UVec2) -> wgpu::Texture {
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba8Unorm,
- usage: TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING,
+ usage: TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING | skipped::USAGE,
view_formats: &[],
})
}
diff --git a/systems/page/src/lib.rs b/systems/page/src/lib.rs
index d1ce5c14..2b264a52 100644
--- a/systems/page/src/lib.rs
+++ b/systems/page/src/lib.rs
@@ -17,6 +17,7 @@
//! raea-runtime-input (pointer and keys) and raea-page (a composition's page).
mod draw;
+mod skipped;
/// a page's loads (raea-sys-page-net: FileNet, FrameNet, the page's fetch, the image decoder)
pub use raea_sys_page_net as net;
/// Blitz's extension points as Bevy resources (S6d)
@@ -206,7 +207,8 @@ static REDRAW_FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBoo
/// so a scene past raea's sizes draws whole the second time.
pub fn redraw_full(on: bool) {
REDRAW_FULL.store(on, std::sync::atomic::Ordering::Relaxed);
- vello::low_level::vello_encoding::set_bump_full(on);
+ // (once a scene overflowed raea's sizes, Vello's own stay on: skipped.rs)
+ vello::low_level::vello_encoding::set_bump_full(on || skipped::STAY_FULL.load(std::sync::atomic::Ordering::Relaxed));
}
/// RAEA_VELLO_BUMP_USE: a line per scene drawn, its bump buffers' use against the sizes its render has (raea_gpu_device::bump).
@@ -245,6 +247,7 @@ impl Plugin for PaintPlugin {
#[cfg(target_vendor = "apple")]
parley::set_fallback_hook(raea_sys_fonts::coretext_fallback);
parley::set_missing_hook(raea_sys_fonts::missing);
+ raea_gpu_device::check::on_settle(skipped::settle);
providers::defaults(app);
widgets::install_page_plugins(app);
app.init_non_send::<Docs>()
diff --git a/systems/page/src/skipped.rs b/systems/page/src/skipped.rs
new file mode 100644
index 00000000..c7a46004
--- /dev/null
+++ b/systems/page/src/skipped.rs
@@ -0,0 +1,64 @@
+//! Whether Vello drew a scene at all. Past one of its bump buffers, Vello's fine stage returns before writing a texel
+//! (vello_shaders fine.wgsl: `ptcl[0] == ~0u`) and `render_to_texture` still returns Ok, so the target keeps what it
+//! held: a pooled layer texture its last frame's picture, a new one nothing (#23). A sentinel texel written at (0,0)
+//! before the draw and read back after says which: the fine stage writes every texel when it runs, and never this one,
+//! since its colour is straight (an alpha of 0 comes out with a colour of about 0, never magenta).
+//! The read back isn't waited for (a wait on every draw cost a fifth of a render's speed): its answer comes in the
+//! wait for the frame's own pixels. A skipped draw puts Vello's own bump sizes on for the rest of the process and is
+//! counted (raea_gpu_device::check::skipped_draw), and the frame's check (`skip_checked`) draws the frames since again
+//! at those sizes, or refuses one skipped at them too, so the render fails naming it.
+//! RAEA_PAGE_DRAWN_CHECK=0 draws without the check (for measuring what it costs; a skipped draw goes unseen again).
+
+use std::sync::atomic::{AtomicBool, Ordering};
+
+/// The sentinel, as Rgba8Unorm bytes: magenta at an alpha of 0.
+const SENTINEL: [u8; 4] = [255, 0, 255, 0];
+
+/// On once a scene overflowed raea's smaller sizes: every draw since has Vello's own (lib.rs `redraw_full` keeps it).
+pub(crate) static STAY_FULL: AtomicBool = AtomicBool::new(false);
+
+/// What the texture's usage needs for the check: the sentinel written in and read back.
+pub const USAGE: wgpu::TextureUsages = wgpu::TextureUsages::COPY_SRC.union(wgpu::TextureUsages::COPY_DST);
+
+/// The device the draws are on, polled without waiting for read backs that are done (`settle`).
+static DEVICE: std::sync::OnceLock<wgpu::Device> = std::sync::OnceLock::new();
+
+/// The read backs that are done answered: raea_gpu_device::check calls it before each frame's check (lib.rs).
+pub fn settle() {
+ if let Some(d) = DEVICE.get() {
+ let _ = d.poll(wgpu::PollType::Poll);
+ }
+}
+
+/// `scene` drawn by Vello into `target` with `params`, its sentinel's read back on its way (`what` names it).
+pub fn render(renderer: &mut vello::Renderer, device: &wgpu::Device, queue: &wgpu::Queue, scene: &vello::Scene, target: &wgpu::Texture, params: &vello::RenderParams, what: &str) -> Result<(), String> {
+ let check = std::env::var_os("RAEA_PAGE_DRAWN_CHECK").is_none_or(|v| v != "0");
+ let texel = wgpu::TexelCopyTextureInfo { texture: target, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All };
+ let one = wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 };
+ let layout = wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: None, rows_per_image: None };
+ if check {
+ queue.write_texture(texel, &SENTINEL, layout, one);
+ }
+ renderer.render_to_texture(device, queue, scene, &target.create_view(&Default::default()), params).map_err(|e| format!("vello, {what}: {e}"))?;
+ if !check {
+ return Ok(());
+ }
+ DEVICE.get_or_init(|| device.clone());
+ let buf = device.create_buffer(&wgpu::BufferDescriptor { label: Some("raea-page drawn?"), size: 4, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("raea-page drawn?") });
+ enc.copy_texture_to_buffer(texel, wgpu::TexelCopyBufferInfo { buffer: &buf, layout }, one);
+ queue.submit([enc.finish()]);
+ let (read, what, (w, h)) = (buf.clone(), what.to_string(), (params.width, params.height));
+ buf.slice(..).map_async(wgpu::MapMode::Read, move |r| {
+ let skipped = r.is_ok() && read.slice(..).get_mapped_range().is_ok_and(|d| d[..4] == SENTINEL);
+ read.unmap();
+ if skipped {
+ if !STAY_FULL.swap(true, Ordering::Relaxed) {
+ vello::low_level::vello_encoding::set_bump_full(true);
+ eprintln!("raea-page: {what} ({w}x{h}) is past raea's Vello buffers and wasn't drawn: it's drawn again, and every page from now on, at Vello's own sizes");
+ }
+ raea_gpu_device::check::skipped_draw(format!("{what} ({w}x{h}) wasn't drawn: its scene is past Vello's bump buffers even at Vello's own sizes (fewer full-frame layers under one filter, or a smaller render, draws it)"));
+ }
+ });
+ Ok(())
+}