Skip to main content

egui_pop_viewport/
source.rs

1//! Where the pixels come from: a [`TileSource`] the application
2//! implements, asynchronous and live.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! - The viewport **asks** for tiles ([`TileSource::request`]): square
8//!   tiles of [`TileRequest::size`] pixels at a scale of the image, first
9//!   a *proxy* of the whole image at a coarse scale, then the *exact*
10//!   tiles of what is visible at the view's own scale. A call never
11//!   blocks: the source works elsewhere (a thread, an engine, a server).
12//! - The source **delivers** through a [`TileSink`] (from
13//!   [`ViewportState::sink`](crate::ViewportState::sink)), from any thread;
14//!   the sink wakes the interface.
15//! - **Cancellation**: a request the view no longer needs (the user
16//!   panned on) has its [`CancelToken`] set; the source may check it and
17//!   drop the work. A late tile is dropped by the viewport anyway.
18//! - **Live content**: when the image changes (a parameter moved), the
19//!   source says which region with [`TileSink::changed`]; the tiles there
20//!   stay on screen until their replacements arrive.
21//! - **Pixels** come either display-ready ([`Pixels::Display`], the
22//!   source applied its own display transform on the CPU) or
23//!   scene-referred ([`Pixels::Scene`], linear floats the viewport passes
24//!   through the display transform, on the GPU when it can).
25//! - **Device tiles** (feature `wgpu`): a source rendering on the GPU
26//!   hands over a texture or a storage buffer that lives on the render
27//!   device (`TileSink::deliver_device`, see the `device` module);
28//!   nothing is copied, and the display transform runs in the shader as
29//!   for scene pixels.
30//! - **Where the pixels are converted**: by default the sink converts
31//!   each tile on the thread that delivers it (the display transform on
32//!   the CPU path, the half-float texels on the GPU path), so tiles
33//!   arrive ready to upload and the interface thread only hands them to
34//!   the GPU, within an upload budget per frame. With
35//!   [`ViewportState::set_prepare_on_worker`](crate::ViewportState::set_prepare_on_worker)`(false)`,
36//!   the interface thread converts each tile when it takes it in.
37
38use std::fmt;
39use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
40use std::sync::mpsc::{Receiver, Sender, channel};
41use std::sync::{Arc, Mutex};
42
43use egui::{Color32, ColorImage};
44
45#[cfg(feature = "wgpu")]
46use crate::device::{DeviceTile, RenderDevice};
47use crate::display::{self, DisplayTarget, DisplayTransform};
48
49/// A tile's quality.
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
51pub enum Quality {
52    /// Part of the coarse picture of the whole image, shown first.
53    Proxy,
54    /// What is visible, at the view's own scale.
55    Exact,
56}
57
58impl Quality {
59    pub fn name(self) -> &'static str {
60        match self {
61            Quality::Proxy => "proxy",
62            Quality::Exact => "exact",
63        }
64    }
65}
66
67/// A scale of the image (scaled pixels per image pixel, at most 1),
68/// hashable.
69#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
70pub struct Scale(u64);
71
72impl Scale {
73    pub fn new(s: f64) -> Scale {
74        Scale(s.to_bits())
75    }
76
77    pub fn get(self) -> f64 {
78        f64::from_bits(self.0)
79    }
80}
81
82impl fmt::Debug for Scale {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        write!(f, "Scale({})", self.get())
85    }
86}
87
88/// Which image a tile belongs to: the one edited, or the "before" of a
89/// comparison.
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
91pub enum Side {
92    After,
93    Before,
94}
95
96/// A tile: column `x` and row `y` of the grid of `size`-pixel squares
97/// covering the image scaled by `scale`.
98#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
99pub struct TileKey {
100    pub scale: Scale,
101    pub x: i64,
102    pub y: i64,
103}
104
105/// A request's id, unique per viewport state.
106#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
107pub struct RequestId(pub u64);
108
109/// Set when the viewport no longer needs a request.
110#[derive(Clone, Debug, Default)]
111pub struct CancelToken(Arc<AtomicBool>);
112
113impl CancelToken {
114    pub fn is_cancelled(&self) -> bool {
115        self.0.load(Ordering::Relaxed)
116    }
117
118    pub(crate) fn cancel(&self) {
119        self.0.store(true, Ordering::Relaxed);
120    }
121}
122
123/// One tile wanted.
124#[derive(Clone, Debug)]
125pub struct TileRequest {
126    pub id: RequestId,
127    pub key: TileKey,
128    pub quality: Quality,
129    /// The scaled image's pixels the tile covers: `[x, y]` (top left)
130    /// and `[w, h]`, clipped to the scaled image.
131    pub origin: [i64; 2],
132    pub size: [u32; 2],
133    pub cancel: CancelToken,
134}
135
136impl TileRequest {
137    /// The scale (scaled pixels per image pixel).
138    pub fn scale(&self) -> f64 {
139        self.key.scale.get()
140    }
141
142    /// Whether the viewport gave up on it.
143    pub fn is_cancelled(&self) -> bool {
144        self.cancel.is_cancelled()
145    }
146
147    /// The image point sampled by the centre of scaled pixel `(i, j)` of
148    /// this tile (`i`, `j` from 0): how a source samples consistently.
149    pub fn image_point(&self, i: u32, j: u32) -> [f64; 2] {
150        let s = self.scale();
151        [
152            (self.origin[0] as f64 + f64::from(i) + 0.5) / s,
153            (self.origin[1] as f64 + f64::from(j) + 0.5) / s,
154        ]
155    }
156}
157
158/// A tile's pixels, row by row, `size[0] × size[1]`.
159#[derive(Clone, PartialEq)]
160pub enum Pixels {
161    /// RGBA, 8 bits, sRGB-encoded, not premultiplied: the source applied
162    /// its display transform itself (the CPU path).
163    Display(Vec<u8>),
164    /// RGBA, linear floats in the source's working space: the viewport
165    /// applies the display transform (the GPU path when installed).
166    Scene(Vec<f32>),
167}
168
169impl fmt::Debug for Pixels {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        match self {
172            Pixels::Display(v) => write!(f, "Display({} bytes)", v.len()),
173            Pixels::Scene(v) => write!(f, "Scene({} floats)", v.len()),
174        }
175    }
176}
177
178impl Pixels {
179    /// Bytes held on the CPU.
180    pub fn bytes(&self) -> usize {
181        match self {
182            Pixels::Display(v) => v.len(),
183            Pixels::Scene(v) => v.len() * 4,
184        }
185    }
186}
187
188/// A tile delivered.
189#[derive(Clone, Debug)]
190pub struct Tile {
191    /// The request it answers.
192    pub request: RequestId,
193    pub key: TileKey,
194    pub size: [u32; 2],
195    pub pixels: Pixels,
196}
197
198impl Tile {
199    /// A tile answering `request`.
200    pub fn answer(request: &TileRequest, pixels: Pixels) -> Tile {
201        Tile {
202            request: request.id,
203            key: request.key,
204            size: request.size,
205            pixels,
206        }
207    }
208}
209
210/// The values under a pixel, from the source.
211#[derive(Clone, Debug, PartialEq)]
212pub struct Readout {
213    pub side: Side,
214    pub pixel: [i64; 2],
215    /// Named values (`R`, `G`, `B`, `L`...).
216    pub values: Vec<(String, f32)>,
217}
218
219pub(crate) enum Message {
220    Tile(Side, Arrival),
221    Changed(Side, Option<[f64; 4]>),
222    Failed(Side, RequestId, String),
223    /// A device tile refused, and why.
224    #[cfg(feature = "wgpu")]
225    Refused(String),
226    Readout(Readout),
227}
228
229/// What the delivering thread needs to convert a tile: the display
230/// transform and target of the last frame, and the GPU path's texel
231/// format. `stamp` changes with any of them.
232#[derive(Clone, Debug)]
233pub(crate) struct Prep {
234    pub stamp: u64,
235    pub transform: Arc<dyn DisplayTransform>,
236    pub target: DisplayTarget,
237    /// The GPU path is installed; `true` for half-float texels.
238    pub gpu: Option<bool>,
239}
240
241/// A tile's pixels as they reach the interface thread.
242#[derive(Debug)]
243pub(crate) enum Body {
244    /// As the source made them: converted on the interface thread.
245    Raw(Pixels),
246    /// Ready for an egui texture; `baked` when made from scene pixels
247    /// through the transform of `stamp`.
248    Image {
249        image: ColorImage,
250        baked: bool,
251        stamp: u64,
252    },
253    /// Ready for a GPU path texture: texels in the format of `stamp`.
254    Texels { data: Vec<u8>, stamp: u64 },
255    /// Already on the render device ([`TileSink::deliver_device`]):
256    /// bound, nothing copied.
257    #[cfg(feature = "wgpu")]
258    Device(Box<DeviceTile>),
259}
260
261impl Body {
262    /// Bytes the upload copies.
263    pub(crate) fn upload_bytes(&self, size: [u32; 2], gpu: bool) -> usize {
264        let n = size[0] as usize * size[1] as usize;
265        match self {
266            Body::Raw(Pixels::Scene(_)) if gpu => n * 8,
267            Body::Raw(_) | Body::Image { .. } => n * 4,
268            Body::Texels { data, .. } => data.len(),
269            #[cfg(feature = "wgpu")]
270            Body::Device(_) => 0,
271        }
272    }
273}
274
275/// A tile delivered, as the viewport takes it in.
276#[derive(Debug)]
277pub(crate) struct Arrival {
278    pub request: RequestId,
279    pub key: TileKey,
280    pub size: [u32; 2],
281    pub body: Body,
282    /// The CPU pixels of a device tile refused on the delivering side:
283    /// asked for again when the render device changes.
284    pub fallback: bool,
285}
286
287/// The GPU path's texels for scene pixels: half floats, else 32-bit
288/// floats, little endian.
289pub(crate) fn texels(data: &[f32], half_float: bool) -> Vec<u8> {
290    #[cfg(feature = "wgpu")]
291    if half_float {
292        return data
293            .iter()
294            .flat_map(|v| half::f16::from_f32(*v).to_bits().to_le_bytes())
295            .collect();
296    }
297    let _ = half_float;
298    data.iter().flat_map(|v| v.to_le_bytes()).collect()
299}
300
301impl Prep {
302    /// Converts a tile's pixels on the calling thread; the pixels back
303    /// when their size is wrong (the interface thread reports it).
304    fn convert(&self, size: [u32; 2], pixels: Pixels) -> Body {
305        // On the delivering thread: what the interface thread did when
306        // taking the tile in.
307        profiling::scope!("pop.tiles.prepare");
308        let n = size[0] as usize * size[1] as usize;
309        let ok = match &pixels {
310            Pixels::Display(v) => v.len() == n * 4,
311            Pixels::Scene(v) => v.len() == n * 4,
312        };
313        if !ok || n == 0 {
314            return Body::Raw(pixels);
315        }
316        let dims = [size[0] as usize, size[1] as usize];
317        match (pixels, self.gpu) {
318            (Pixels::Scene(data), Some(half)) => Body::Texels {
319                data: texels(&data, half),
320                stamp: self.stamp,
321            },
322            (Pixels::Scene(data), None) => {
323                let mut out = vec![Color32::BLACK; n];
324                display::apply_cpu(self.transform.as_ref(), &self.target, &data, &mut out);
325                Body::Image {
326                    image: ColorImage::new(dims, out),
327                    baked: true,
328                    stamp: self.stamp,
329                }
330            }
331            (Pixels::Display(bytes), _) => Body::Image {
332                image: ColorImage::from_rgba_unmultiplied(dims, &bytes),
333                baked: false,
334                stamp: self.stamp,
335            },
336        }
337    }
338}
339
340/// What a source does with the sink, counted; [`Stats::snapshot`] for
341/// the debug bridge and the tests.
342#[derive(Debug, Default)]
343pub struct Stats {
344    pub requested: AtomicU64,
345    pub delivered: AtomicU64,
346    /// Tiles that arrived for a request no longer wanted.
347    pub dropped: AtomicU64,
348    pub cancelled: AtomicU64,
349    pub failed: AtomicU64,
350    pub evicted: AtomicU64,
351    pub changed: AtomicU64,
352    /// Device tiles taken in (bound on the render device, not copied).
353    pub device: AtomicU64,
354    /// Device tiles refused (another device, no GPU path, a resource
355    /// that does not fit), fallback or not.
356    pub refused: AtomicU64,
357    /// Changes folded into one change of the whole image, and readouts
358    /// dropped, while the viewport was not drawn and
359    /// [`NOTICES`] were already waiting.
360    pub coalesced: AtomicU64,
361}
362
363impl Stats {
364    /// The counters, by name.
365    pub fn snapshot(&self) -> [(&'static str, u64); 10] {
366        let g = |a: &AtomicU64| a.load(Ordering::Relaxed);
367        [
368            ("requested", g(&self.requested)),
369            ("delivered", g(&self.delivered)),
370            ("dropped", g(&self.dropped)),
371            ("cancelled", g(&self.cancelled)),
372            ("failed", g(&self.failed)),
373            ("evicted", g(&self.evicted)),
374            ("changed", g(&self.changed)),
375            ("device", g(&self.device)),
376            ("refused", g(&self.refused)),
377            ("coalesced", g(&self.coalesced)),
378        ]
379    }
380
381    pub(crate) fn add(a: &AtomicU64, n: u64) {
382        a.fetch_add(n, Ordering::Relaxed);
383    }
384}
385
386#[derive(Default)]
387struct Waker(Mutex<Option<egui::Context>>);
388
389impl Waker {
390    fn wake(&self) {
391        if let Some(ctx) = self
392            .0
393            .lock()
394            .unwrap_or_else(std::sync::PoisonError::into_inner)
395            .as_ref()
396        {
397            ctx.request_repaint();
398        }
399    }
400}
401
402/// How many changes and readouts wait at most for the viewport to take
403/// them in. Tiles and failures answer requests, which the viewport makes
404/// only when drawn; changes and readouts come when the source says, so a
405/// viewport no longer drawn (a tab behind another) would keep them all.
406/// Past this many, a change becomes one change of the whole image, kept
407/// as a flag, and a readout is dropped (the next one replaces it).
408pub const NOTICES: usize = 256;
409
410/// What waits on the channel beyond the answers to requests.
411#[derive(Debug, Default)]
412pub(crate) struct Backlog {
413    /// Changes and readouts sent and not taken in yet.
414    queued: AtomicUsize,
415    /// A side changed everywhere, its changes folded past [`NOTICES`]
416    /// (after, before).
417    whole: [AtomicBool; 2],
418    /// Changes folded and readouts dropped since last taken in.
419    coalesced: AtomicU64,
420}
421
422impl Backlog {
423    fn slot(side: Side) -> usize {
424        match side {
425            Side::After => 0,
426            Side::Before => 1,
427        }
428    }
429
430    /// Whether a notice may go on the channel; counts it if so.
431    fn admit(&self) -> bool {
432        let admitted = self
433            .queued
434            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| {
435                (n < NOTICES).then_some(n + 1)
436            })
437            .is_ok();
438        if !admitted {
439            self.coalesced.fetch_add(1, Ordering::Relaxed);
440        }
441        admitted
442    }
443
444    /// A notice taken in from the channel.
445    pub(crate) fn taken(&self) {
446        let _ = self
447            .queued
448            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1));
449    }
450
451    /// The sides whose changes were folded, cleared, and how many
452    /// notices were folded or dropped since the last call.
453    pub(crate) fn take_folded(&self) -> (Vec<Side>, u64) {
454        let sides = [Side::After, Side::Before]
455            .into_iter()
456            .filter(|s| self.whole[Self::slot(*s)].swap(false, Ordering::AcqRel))
457            .collect();
458        (sides, self.coalesced.swap(0, Ordering::Relaxed))
459    }
460
461    /// Changes and readouts waiting.
462    pub(crate) fn queued(&self) -> usize {
463        self.queued.load(Ordering::Acquire)
464    }
465}
466
467/// Where a source delivers; cheap to clone, usable from any thread.
468#[derive(Clone)]
469pub struct TileSink {
470    side: Side,
471    tx: Sender<Message>,
472    waker: Arc<Waker>,
473    prep: Arc<Mutex<Option<Prep>>>,
474    backlog: Arc<Backlog>,
475}
476
477impl fmt::Debug for TileSink {
478    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
479        f.debug_struct("TileSink")
480            .field("side", &self.side)
481            .finish()
482    }
483}
484
485impl TileSink {
486    fn send(&self, m: Message) {
487        // The viewport is gone: nothing to do.
488        if self.tx.send(m).is_ok() {
489            self.waker.wake();
490        }
491    }
492
493    /// Delivers a tile. When the viewport prepares on the worker side,
494    /// the pixels are converted here, on the calling thread.
495    pub fn deliver(&self, tile: Tile) {
496        self.deliver_pixels(tile, false);
497    }
498
499    fn deliver_pixels(&self, tile: Tile, fallback: bool) {
500        let prep = self
501            .prep
502            .lock()
503            .unwrap_or_else(std::sync::PoisonError::into_inner)
504            .clone();
505        let body = match prep {
506            Some(p) => p.convert(tile.size, tile.pixels),
507            None => Body::Raw(tile.pixels),
508        };
509        self.send(Message::Tile(
510            self.side,
511            Arrival {
512                request: tile.request,
513                key: tile.key,
514                size: tile.size,
515                body,
516                fallback,
517            },
518        ));
519    }
520
521    /// Delivers a tile that lives on the render device (feature `wgpu`,
522    /// see [`crate::device`]): bound by the GPU path, nothing copied.
523    /// The work writing it must have been submitted to the render
524    /// device's queue before this call. Checked here, on the calling
525    /// thread, against the render device installed now
526    /// ([`TileSink::render_device`]): a tile the viewport cannot draw is
527    /// refused, the error kept
528    /// ([`ViewportState::last_error`](crate::ViewportState::last_error)),
529    /// and its fallback pixels, when it has some, made here and
530    /// delivered as [`TileSink::deliver`] does; without, the request
531    /// fails. Fallback pixels are asked for again as a device tile when
532    /// the render device changes (the GPU path installed late).
533    ///
534    /// The interface checks the tile again when it takes it in: one
535    /// refused there (the device changed in between) is dropped and its
536    /// request made again through [`TileSource::request`], so the
537    /// fallback never runs on the interface thread.
538    #[cfg(feature = "wgpu")]
539    pub fn deliver_device(&self, request: &TileRequest, tile: DeviceTile) {
540        let render = self.render_device();
541        match tile.check(render.as_ref(), request.size) {
542            Ok(()) => self.send(Message::Tile(
543                self.side,
544                Arrival {
545                    request: request.id,
546                    key: request.key,
547                    size: request.size,
548                    body: Body::Device(Box::new(tile)),
549                    fallback: false,
550                },
551            )),
552            Err(e) => {
553                let error = format!("device tile refused: {e}");
554                match tile.fallback.and_then(|f| f()) {
555                    Some(pixels) => {
556                        self.send(Message::Refused(error));
557                        self.deliver_pixels(Tile::answer(request, pixels), true);
558                    }
559                    None => {
560                        self.send(Message::Refused(error.clone()));
561                        self.failed(request.id, error);
562                    }
563                }
564            }
565        }
566    }
567
568    /// The render device device tiles must be created on (feature
569    /// `wgpu`): the one installed now in the viewport's context
570    /// ([`gpu::render_device`](crate::gpu::render_device)), read when
571    /// called. `None` without a GPU path, and before the viewport's first
572    /// frame (the sink learns its context there). It reads egui's
573    /// context: not from inside one of its closures (`ctx.input(|i| …)`),
574    /// as for any context call.
575    #[cfg(feature = "wgpu")]
576    pub fn render_device(&self) -> Option<RenderDevice> {
577        let ctx = self
578            .waker
579            .0
580            .lock()
581            .unwrap_or_else(std::sync::PoisonError::into_inner)
582            .clone()?;
583        crate::gpu::render_device(&ctx)
584    }
585
586    /// The image changed in `region` (`[x0, y0, x1, y1]`, image pixels),
587    /// or everywhere (`None`, also for a new size). While [`NOTICES`]
588    /// changes and readouts wait (the viewport is not drawn), it is
589    /// folded into one change of the whole image.
590    pub fn changed(&self, region: Option<[f64; 4]>) {
591        if self.backlog.admit() {
592            self.send(Message::Changed(self.side, region));
593        } else {
594            self.backlog.whole[Backlog::slot(self.side)].store(true, Ordering::Release);
595            self.waker.wake();
596        }
597    }
598
599    /// A request could not be served.
600    pub fn failed(&self, request: RequestId, error: impl Into<String>) {
601        self.send(Message::Failed(self.side, request, error.into()));
602    }
603
604    /// Answers [`TileSource::readout`]. Dropped while [`NOTICES`]
605    /// changes and readouts wait (the viewport is not drawn).
606    pub fn readout(&self, pixel: [i64; 2], values: Vec<(String, f32)>) {
607        if !self.backlog.admit() {
608            return;
609        }
610        self.send(Message::Readout(Readout {
611            side: self.side,
612            pixel,
613            values,
614        }));
615    }
616}
617
618/// The receiving end, kept by the viewport state.
619pub(crate) struct Feed {
620    tx: Sender<Message>,
621    pub(crate) rx: Receiver<Message>,
622    waker: Arc<Waker>,
623    /// Set when tiles are converted by the delivering thread.
624    pub(crate) prep: Arc<Mutex<Option<Prep>>>,
625    /// The changes and readouts waiting, bounded.
626    pub(crate) backlog: Arc<Backlog>,
627}
628
629impl Default for Feed {
630    fn default() -> Self {
631        let (tx, rx) = channel();
632        Feed {
633            tx,
634            rx,
635            waker: Arc::default(),
636            prep: Arc::default(),
637            backlog: Arc::default(),
638        }
639    }
640}
641
642impl fmt::Debug for Feed {
643    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
644        f.write_str("Feed")
645    }
646}
647
648impl Feed {
649    pub(crate) fn sink(&self, side: Side) -> TileSink {
650        TileSink {
651            side,
652            tx: self.tx.clone(),
653            waker: self.waker.clone(),
654            prep: self.prep.clone(),
655            backlog: self.backlog.clone(),
656        }
657    }
658
659    /// What the delivering threads convert with, or `None` to leave
660    /// the conversion to the interface thread.
661    pub(crate) fn set_prep(&self, prep: Option<Prep>) {
662        *self
663            .prep
664            .lock()
665            .unwrap_or_else(std::sync::PoisonError::into_inner) = prep;
666    }
667
668    pub(crate) fn set_context(&self, ctx: &egui::Context) {
669        let mut w = self
670            .waker
671            .0
672            .lock()
673            .unwrap_or_else(std::sync::PoisonError::into_inner);
674        if w.is_none() {
675            *w = Some(ctx.clone());
676        }
677    }
678}
679
680/// The application's pixels. Every method returns at once; work happens
681/// elsewhere and comes back through the [`TileSink`].
682pub trait TileSource {
683    /// The image's size in pixels, `None` while unknown. Cheap: read on
684    /// every frame.
685    fn size(&self) -> Option<[u32; 2]>;
686
687    /// New tiles wanted, most useful first. Requests the viewport stops
688    /// wanting get their [`CancelToken`] set.
689    fn request(&self, requests: Vec<TileRequest>);
690
691    /// The pointer is over `pixel`: answer with
692    /// [`TileSink::readout`] when the values are known (default: no
693    /// readout).
694    fn readout(&self, pixel: [i64; 2]) {
695        let _ = pixel;
696    }
697}