egui_large_image/lib.rs
1/*
2File: lib.rs
3
4Purpose:
5Crate root of `egui_large_image`: module wiring, public re-exports, the texture-side helpers
6(`PORTABLE_TILE_SIDE`, `max_texture_side`, `tile_side_for`), the per-tile allocation cap
7`MAX_TILES`, and the crate-level documentation.
8
9Key items:
10- `PxRect`, `TileGrid`, `GridError` (grid.rs) — tiling geometry
11- `Placement` (placement.rs) — pixel -> screen mapping
12- `Alpha`, `crop_rgba`, `crop_color_image`, `PreparedTiles`, `SplitError` (split.rs) — CPU split
13- `TileContent`, `TileSource` (source.rs) — where uploads get pixels
14- `UploadBudget` (budget.rs) — per-frame upload allowance
15- `TiledTexture`, `UploadScope`, `VisibleScope`, `UploadReport`, `PaintReport` (texture.rs) — GPU side
16
17Notes:
18Dependencies are egui, thiserror and log only. No module here knows any application.
19*/
20
21//! Draw images larger than the GPU texture limit in [egui](https://github.com/emilk/egui).
22//!
23//! egui uploads every texture in one piece, and a backend accepts only textures up to
24//! `max_texture_side` pixels per side (2048 is the portable minimum; desktop GPUs usually allow
25//! 8192-16384). A long webtoon page, a scan or a map does not fit. This crate splits such an image
26//! into a grid of tiles and treats the grid as one image:
27//!
28//! 1. **Split** on a worker thread: [`PreparedTiles::from_rgba`] crops the image into
29//! `Arc<ColorImage>` tiles using [`PORTABLE_TILE_SIDE`] (worker threads have no
30//! `egui::Context` to ask for the real limit).
31//! 2. **Upload** on the GUI thread: [`TiledTexture::upload`] turns pending tiles into egui
32//! textures, only as many per frame as an [`UploadBudget`] allows, optionally only the ones
33//! on screen ([`UploadScope::visible`]). Uploading a prepared tile is a reference bump, not a
34//! pixel copy.
35//! 3. **Paint**: [`TiledTexture::paint`] draws the visible tiles through a [`Placement`] (pixel
36//! to screen mapping), culled against a screen rect.
37//!
38//! ```no_run
39//! use egui_large_image::{Alpha, Placement, PreparedTiles, TiledTexture, UploadBudget, UploadScope, PORTABLE_TILE_SIDE};
40//!
41//! // On a worker thread (the pixels are an RGBA8 buffer, e.g. `image::RgbaImage::as_raw()`):
42//! # fn worker(rgba: &[u8], width: usize, height: usize) -> Result<PreparedTiles, egui_large_image::SplitError> {
43//! let prepared = PreparedTiles::from_rgba(rgba, [width, height], Alpha::Unmultiplied, PORTABLE_TILE_SIDE)?;
44//! # Ok(prepared) }
45//!
46//! // On the GUI thread, every frame:
47//! # fn frame(ui: &mut egui::Ui, prepared: &mut PreparedTiles, texture: &mut TiledTexture, zoom: f32) {
48//! let placement = Placement::scaled(ui.min_rect().min, zoom);
49//! let cull = ui.clip_rect();
50//! let mut budget = UploadBudget::new(4, 24 * 1024 * 1024);
51//! let report = texture.upload(ui.ctx(), prepared, &mut budget, UploadScope::visible(placement, cull));
52//! texture.paint(ui.painter(), placement, cull, egui::Color32::WHITE);
53//! if report.wants_repaint() {
54//! ui.ctx().request_repaint(); // the budget left tiles for the next frame
55//! }
56//! # }
57//! # fn create(prepared: &PreparedTiles) -> Result<TiledTexture, egui_large_image::GridError> {
58//! // Once, when the prepared tiles arrive:
59//! let texture = TiledTexture::new(*prepared.grid(), "my-page", egui::TextureOptions::LINEAR)?;
60//! # Ok(texture) }
61//! ```
62//!
63//! # Details worth knowing
64//!
65//! * **Tile side and the backend limit.** [`max_texture_side`] reads the running backend's
66//! limit; [`TileGrid::for_context`] / [`tile_side_for`] cap a preferred side to it. A tile
67//! larger than the limit is rejected by `upload` with a log line (egui itself would only
68//! `debug_assert!`).
69//! * **No gutters.** Each tile is its own texture sampled with clamp-to-edge, so under linear
70//! magnification the pixels along a tile seam blend with themselves, not with the neighbouring
71//! tile. Changing the tile side moves the seams; keep it fixed if pixel-exact output matters.
72//! * **Dirty tiles.** [`TiledTexture::mark_dirty`] marks the tiles under a pixel rect; the next
73//! `upload` re-sends them in place (`TextureHandle::set`, the `TextureId` is kept), and the old
74//! pixels keep drawing meanwhile. [`TiledTexture::set_options`] (e.g. `NEAREST` when zoomed in)
75//! works the same way.
76//! * **Memory.** [`TiledTexture::resident_bytes`], [`TiledTexture::drop_textures`] and
77//! [`TiledTexture::last_painted_frame`] (stamped by `paint`, or by
78//! [`TiledTexture::mark_painted`] after a custom draw) are the hooks for your own eviction
79//! policy; the crate has none. After a drop, the [`TileSource`] must be able to supply the
80//! pixels again.
81//! * **Repaints.** [`UploadReport::wants_repaint`] is true while the budget deferred tiles to a
82//! later frame. Tiles waiting for their source ([`TileContent::NotReady`]) are not a reason to
83//! repaint: whoever makes the pixels ready requests the repaint.
84//! * **Threading.** Everything in [`TileGrid`], [`Placement`], the crop functions and
85//! [`PreparedTiles`] is plain data and runs anywhere. [`TiledTexture`] methods that take a
86//! `Context` or `Painter` run on the GUI thread, and so does a [`TileSource`].
87
88#![warn(clippy::pedantic)]
89#![deny(missing_docs)]
90#![allow(clippy::module_name_repetitions)] // `GridError` in `grid`, `SplitError` in `split` read best as-is.
91
92mod budget;
93mod grid;
94mod placement;
95mod source;
96mod split;
97mod texture;
98
99pub use budget::UploadBudget;
100pub use grid::{GridError, PxRect, TileGrid};
101pub use placement::Placement;
102pub use source::{TileContent, TileSource};
103pub use split::{Alpha, PreparedTiles, SplitError, crop_color_image, crop_rgba};
104pub use texture::{PaintReport, TiledTexture, UploadReport, UploadScope, VisibleScope};
105
106/// A tile side every egui backend accepts (egui's own default `max_texture_side`, the WebGL2 /
107/// GL ES 3 minimum). Use it where no `egui::Context` is available, e.g. on worker threads.
108pub const PORTABLE_TILE_SIDE: usize = 2048;
109
110/// The most tiles a [`TiledTexture`] or [`PreparedTiles`] accepts (2^20). Both allocate one
111/// entry per tile up front; a tile side far too small for the image (say 1 px on a
112/// 100 000 x 100 000 image) is reported as [`GridError::TooManyTiles`] instead of exhausting
113/// memory. Real grids stay far below it (an 8192 x 65 536 page at 256-px tiles is 8192 tiles).
114pub const MAX_TILES: usize = 1 << 20;
115
116/// The running backend's maximum texture side in pixels, as reported to `ctx` (egui's
117/// `InputState::max_texture_side`; 2048 before the backend's first frame).
118#[must_use]
119pub fn max_texture_side(ctx: &egui::Context) -> usize {
120 ctx.input(|input| input.max_texture_side)
121}
122
123/// `preferred` capped at the backend's maximum texture side, and at least 1.
124#[must_use]
125pub fn tile_side_for(ctx: &egui::Context, preferred: usize) -> usize {
126 preferred.min(max_texture_side(ctx)).max(1)
127}