Files
vectorcraft/crates/ui-egui/src/render_worker.rs
T
dotCooCoo a9c4e259f9 Canvas: a drag over a frame the render worker drew shows the edit in the frame it is made in
In a document whose frames take over 8 ms, every frame of an edit went to
the render worker once the frame shown came from it, so a Pen drag's curve
trailed the pointer by the worker's render time plus the wait for a busy
worker. The changed part of a worker's frame is now drawn again on the UI
thread, as it already was for frames rendered there, when the part's share
of the frame's last render time is at most 8 ms.

The part is not drawn there, and the frame goes to the worker as before,
when the frame shown drew raster effects made before their objects moved,
holds pixels copied from the worker's last frame, or drew art in a way that
depends on the frame's size, or when the part itself draws such art. A
worker frame on its way blocks the part only when it is of another document
or not older than the edit.

Part of #8296.
2026-11-25 21:26:27 -08:00

146 lines
5.7 KiB
Rust

//! Background rendering (native): heavy documents render off the UI thread while the canvas shows
//! the previous frame reprojected to the current view. A second worker renders a low-resolution
//! frame for the parts that frame does not reach (`canvas::fill_uncovered`). Light documents
//! render synchronously so edits never lag behind overlays, after a first frame that renders here
//! too: the UI thread waits for it only briefly (`canvas::raster::FIRST_FRAME_GRACE`).
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, channel};
use craft::platform::clock::monotonic_ms;
use vectorcraft_doc::Document;
use vectorcraft_engine::file_access::ScopeHandle;
use vectorcraft_geom::Affine;
use vectorcraft_render::{RenderOptions, Rendered, Renderer};
use crate::CacheKey;
pub struct Job {
pub key: CacheKey,
pub doc: Arc<Document>,
pub w: u32,
pub h: u32,
pub view: Affine,
pub opts: RenderOptions,
/// The automation roots in force where the job was made: the render reads linked files under
/// them, as it would on that thread.
pub scope: ScopeHandle,
/// The document's deferred live-effect plug-in stages and first-view budget: the render runs
/// inside their view ([`vectorcraft_plugins::deferred::Deferrals::view`]).
pub effects: vectorcraft_plugins::deferred::Deferrals,
/// The render may copy pixels from the worker's last frame ([`crate::canvas::render_job`]).
/// Off: it renders the whole frame.
pub may_copy: bool,
/// The worker may keep the frame for its next frame to copy from
/// ([`crate::canvas::render_job`]). Off: the worker holds no frame after this one.
pub may_keep: bool,
/// The display profile the finished frame is converted into ([`crate::display_profile`]).
/// The frame the worker keeps stays sRGB.
pub display: Option<Arc<craft::color_ui::display::DisplayTransform>>,
}
pub struct Done {
pub key: CacheKey,
/// The document rendered, and the options it was rendered with.
pub doc: Arc<Document>,
pub opts: RenderOptions,
pub img: Rendered,
pub ms: f64,
/// [`vectorcraft_render::FrameStats::moved`] of the frame.
pub moved: usize,
/// The frame holds pixels copied from the worker's last frame ([`crate::canvas::render_job`]),
/// and `ms` is the time of the copy and of the parts rendered.
pub reused: bool,
/// The frame drew art in a way that depends on its size
/// ([`vectorcraft_render::FrameStats::view_sized`]): a part of it drawn on its own may differ.
pub view_sized: bool,
}
/// Render `job` as the worker thread does: inside the job's automation roots and deferred
/// effects, with the worker's renderer `r` and its last frame `kept`.
pub(crate) fn render(r: &mut Renderer, kept: &mut Option<crate::canvas::KeptFrame>, job: Job) -> Done {
let t0 = monotonic_ms();
let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(r, kept, &job)));
let ms = monotonic_ms() - t0;
Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused, view_sized: frame.view_sized }
}
pub struct Worker {
tx: Sender<Job>,
rx: Receiver<Done>,
pub pending: Option<CacheKey>,
}
impl Worker {
/// Spawn the worker thread (None on wasm, where rendering stays synchronous).
pub fn spawn(ctx: egui::Context) -> Option<Self> {
if cfg!(target_arch = "wasm32") {
return None;
}
let (tx, jobs) = channel::<Job>();
let (done_tx, rx) = channel::<Done>();
std::thread::Builder::new()
.name("vectorcraft-render".into())
.spawn(move || {
let mut r = Renderer::new();
let mut kept = None;
while let Ok(mut job) = jobs.recv() {
// Skip stale jobs: only the newest matters.
while let Ok(newer) = jobs.try_recv() {
job = newer;
}
if done_tx.send(render(&mut r, &mut kept, job)).is_err() {
break;
}
ctx.request_repaint();
}
})
.ok()?;
Some(Self { tx, rx, pending: None })
}
/// A controlled worker: tests receive jobs and decide when a frame completes.
#[cfg(test)]
pub(crate) fn test_channel() -> (Self, Receiver<Job>, Sender<Done>) {
let (tx, jobs) = channel();
let (done_tx, rx) = channel();
(Self { tx, rx, pending: None }, jobs, done_tx)
}
/// Queue `job`, unless the job pending is the same frame. Whether it was queued.
pub fn submit(&mut self, job: Job) -> bool {
if self.pending.as_ref() == Some(&job.key) {
return false;
}
self.pending = Some(job.key.clone());
// A worker that has stopped renders nothing: the canvas keeps the frame it shows.
self.tx.send(job).is_ok()
}
/// The newest finished frame, if any.
pub fn poll(&mut self) -> Option<Done> {
self.newest(None)
}
/// The newest finished frame, waiting up to `timeout` for one when none has finished yet.
pub fn wait(&mut self, timeout: std::time::Duration) -> Option<Done> {
let first = self.rx.try_recv().ok().or_else(|| self.rx.recv_timeout(timeout).ok())?;
self.newest(Some(first))
}
/// The newest of `first` and the frames finished since, the pending job cleared when it is
/// the one.
fn newest(&mut self, first: Option<Done>) -> Option<Done> {
let mut last = first;
while let Ok(d) = self.rx.try_recv() {
last = Some(d);
}
if let Some(d) = &last
&& self.pending.as_ref() == Some(&d.key)
{
self.pending = None;
}
last
}
}