Skip to main content

egui_shader_layers/
lib.rs

1/*
2File: lib.rs
3
4Purpose:
5Crate root of `egui_shader_layers`: public re-exports, backend installers, and the crate-level
6documentation (semantics, shader model, backend matrix).
7
8Key items:
9- `ShaderLayer`, `FilterChain`, `Pass`, `Effect` (re-exported from their modules)
10- `presets` module (its `WaveObstacle` also re-exported at the root: the one preset input type)
11- `Impulses` (+ `Impulse`, `ImpulsePack`, param-name constants): input-driven transient effects
12- `install_glow()` / `destroy_glow()` (feature `glow`), `install_wgpu()` / `WgpuOptions`
13  (feature `wgpu`), `status()`, `failed_effects()`, `failed_textures()`
14- user textures: `TEXTURE_SLOTS`, `TextureError`, `TextureFailure` (`ShaderLayer::texture`)
15- persistent state (F7): `StateOptions`, `StateFormat`, `StateError`, `StateFailure`,
16  `reset_state()`, `state_count()`, `failed_states()` (`Effect::new_state`, `ShaderLayer::id`)
17- `offline` module and its re-exports (`OfflineRenderer`, ...; features `image` / `video`)
18- `HotEffect`, `rebind` (+ options, events, errors; feature `hot-reload`, native only)
19- shape masks (F9): `Mask`, `MaskError` (`ShaderLayer::mask`, `OfflineOptions::with_mask`)
20- regions (R1): `Region`, `MAX_REGIONS`, `REGION_NONE` (`ShaderLayer::regions`)
21- entries (R3): `Entry`, `Overlap` (`ShaderLayer::from_entries` / `with_entry` / `overlap`);
22  offline `OfflineEntry`, `OfflineLayer` (`OfflineRenderer::process_layer`)
23
24Notes:
25Backends plug in behind the crate-internal `backend::Backend` trait; nothing outside a backend
26module names a backend type.
27*/
28
29//! GPU **shader layers** for [egui](https://github.com/emilk/egui): a shape that takes
30//! everything already painted beneath a rect and redraws that region through a chain of
31//! WGSL filter passes — blur, colour adjustments, refraction, or your own shader.
32//!
33//! ```no_run
34//! # #[cfg(feature = "glow")]
35//! # fn app_setup(cc_gl: &glow::Context, ctx: &egui::Context) {
36//! // Once, at startup (eframe: `cc.gl` in your app creator):
37//! egui_shader_layers::install_glow(ctx, cc_gl).ok();
38//! # }
39//! # fn frame(ui: &mut egui::Ui) {
40//! use egui_shader_layers::{ShaderLayer, presets};
41//! // Every frame, after painting whatever should end up blurred:
42//! let rect = egui::Rect::from_min_size(egui::pos2(40.0, 40.0), egui::vec2(240.0, 160.0));
43//! ShaderLayer::new(rect, presets::gaussian_blur(8.0).then(presets::saturation(1.3)))
44//!     .corner_radius(16)
45//!     .paint(ui.painter());
46//! # }
47//! ```
48//!
49//! What the crate offers, each detailed below:
50//!
51//! * **Presets** ([`presets`]): blurs (Gaussian, dual-Kawase [`presets::kawase_blur`]), colour
52//!   adjustments, sharpen, pixelate, lens, vignette, frosted glass, [`presets::bloom`], animated
53//!   ripples, input-driven [`presets::click_ripples`], and the stateful [`presets::trails`] and
54//!   water ([`presets::wave_sim`] + [`presets::wave_display`] around [`WaveObstacle`]s).
55//! * **Custom effects** ([`Effect`]): one WGSL function with a prelude (the pass input, the
56//!   untouched backdrop `original()`, time, frame, pointer, user textures, persistent state),
57//!   validated by naga with errors located in your snippet; typed **named parameters** from a
58//!   `struct Params` ([`Pass::set`]).
59//! * **Chains** ([`FilterChain`]) of passes, each optionally at reduced resolution
60//!   ([`Pass::with_scale`]).
61//! * **Input**: [`Impulses`] turns clicks into transient animations that repaint only while alive.
62//! * **User textures** ([`ShaderLayer::texture`]), **persistent per-layer state**
63//!   ([`Effect::new_state`], [`ShaderLayer::id`]) and **shape masks** ([`ShaderLayer::mask`]).
64//! * **Many areas in one layer**: per-area parameters of one chain ([`ShaderLayer::regions`]) or
65//!   several independent areas, each with its own chain ([`Entry`], [`ShaderLayer::from_entries`]);
66//!   see [Regions and entries](#regions-and-entries).
67//! * **Backends**: `egui_glow` and `egui-wgpu`; **offline** processing of images and video
68//!   (features `image` / `video`); **hot reload** of WGSL files (feature `hot-reload`).
69//!
70//! # Semantics
71//!
72//! * **"Beneath" means earlier in egui's paint order**: lower layers and the shapes painted
73//!   earlier into the same layer. Content painted later — later shapes of the same layer, higher
74//!   `egui::Order` areas, popups, tooltips — is drawn on top and is not filtered.
75//! * The filter is **view-only**: it never touches egui textures or your data.
76//! * **Neighbourhood effects need padding.** The capture is the layer rect expanded by the chain's
77//!   total sample radius ([`FilterChain::padding_points`]), clamped to the screen. At the screen
78//!   edge, sampling clamps to the last available pixel.
79//! * **Precision**: the backdrop is captured as 8-bit, gamma-encoded, premultiplied RGBA — exactly
80//!   what egui wrote. Intermediate pass textures are RGBA16F where the backend can render to it
81//!   (wgpu where the adapter supports it, desktop GL 3.3, WebGL2 with `EXT_color_buffer_float`),
82//!   otherwise RGBA8;
83//!   see [`BackendStatus::Active`].
84//! * With no backend installed, or after a backend failure, layers draw nothing extra (the
85//!   backdrop stays unfiltered). Nothing panics; check [`status`].
86//!
87//! # Writing an effect
88//!
89//! An [`Effect`] is one WGSL function, validated by naga when you build it:
90//!
91//! ```wgsl
92//! fn effect(uv: vec2<f32>) -> vec4<f32> {
93//!     let wave = sin(uv.y * 40.0 + fl.time * 3.0) * params(0u).x;
94//!     return src_px(vec2<f32>(wave, 0.0));
95//! }
96//! ```
97//!
98//! `uv` is the position of the pixel being written in the captured region: `(0, 0)` top-left,
99//! `(1, 1)` bottom-right, y down. The prelude provides:
100//!
101//! | name | meaning |
102//! |---|---|
103//! | `src(uv)` | the pass input (bilinear, clamped to the captured region) |
104//! | `src_px(offset)` | the input at `offset` pixels OF THE INPUT from the current pixel (physical pixels unless the previous pass is scaled) |
105//! | `src_texel()`, `out_texel()` | one pixel of the pass's input / of its own output, in `uv` units (both `fl.texel` at full resolution) |
106//! | `original(uv)` | the untouched captured backdrop (before any pass), in every pass of the chain |
107//! | `p.<name>` | a named parameter: member `<name>` of the snippet's own `struct Params` (see below) |
108//! | `params(i)` | anonymous parameter slot `i` (`0..16`) of the [`Pass`], a `vec4<f32>` (the untyped block; prefer named parameters) |
109//! | `fl.texel` | size of one physical pixel in `uv` units (of the capture, also in scaled passes) |
110//! | `fl.size_px` | captured region size in physical pixels |
111//! | `fl.rect_uv` | the layer rect inside the capture (`xy` = min, `zw` = size), in `uv` units |
112//! | `fl.time` | seconds (egui input time); reading it makes the effect animated (see below) |
113//! | `fl.delta_time` | seconds since the previous frame: egui's `stable_dt` clamped to `0..=0.1` (offline: `OfflineOptions::with_delta_time`, or the video frame step) |
114//! | `fl.frame` | frame counter, `u32` (egui's `cumulative_frame_nr`, wrapping; offline: the video frame index) |
115//! | `fl.pointer` | the pointer: `xy` in `uv` units (outside `0..1` off the capture), `z` = 1 while the primary button is down, `w` = 1 when a pointer exists (`w = 0`: none, all zero) |
116//! | `fl.pixels_per_point` | physical pixels per layer point (egui's scale factor × the layer transform's zoom), to convert point distances to pixels |
117//! | `fl.pass_scale` | this pass's output resolution relative to the capture ([`Pass::with_scale`]; `1` = full) |
118//! | `to_linear(c)`, `to_gamma(c)` | sRGB transfer functions on `rgb` (alpha untouched) |
119//! | `premultiply(c)`, `unpremultiply(c)`, `luma(rgb)` | colour helpers |
120//! | `tex(i, uv)` | user texture `i` (`0..`[`TEXTURE_SLOTS`], attached with [`ShaderLayer::texture`]) at `uv` in the TEXTURE's own `0..1` coordinates (top-left origin), through its own sampler (its egui `TextureOptions`: filters, wrap mode; mip level 0) |
121//! | `tex_size(i)` | size of user texture `i` in texels (`vec2<f32>`) |
122//! | `tex_load(i, px)` | the exact texel `px` (`vec2<i32>`, clamped to the texture) of user texture `i`, no filtering |
123//! | `state(uv)` | the layer's persistent state at `uv` (bilinear; see [Persistent state](#persistent-state)); zero without a state pass |
124//! | `state_load(px)`, `state_px(offset)` | the exact state texel `px` (`vec2<i32>`, (0, 0) top-left, clamped) / the one under the current pixel offset by `offset` texels, no filtering |
125//! | `state_size()`, `state_texel()` | the state's size in texels / one state texel in `uv` units |
126//! | `fl.pass_index` | index of this pass among the chain's passes of its kind (state or display), `u32`: the substep number of consecutive state passes |
127//! | `region()`, `region_at(uv)` | the id (`u32`) of the [`Region`] that owns the current pixel / capture `uv` (its index in [`Mask::Regions`]); `REGION_NONE` outside every region and on layers without regions (see [Masks](#masks)) |
128//! | `REGION_NONE` | `255u`, the "no region" id ([`REGION_NONE`] in Rust) |
129//!
130//! An effect whose code reads `fl.time` is **animated**: painting a layer that uses it requests
131//! an egui repaint every frame, so it keeps moving in an otherwise idle app. The detection walks
132//! naga's IR (a real `fl.time` access, not a text match); override it with
133//! [`Effect::with_animated`]. Reading `fl.delta_time`, `fl.frame` or `fl.pointer` does **not**:
134//! pointer changes arrive with input, which repaints anyway, and an effect that must advance
135//! every frame on its own reads `fl.time` or is marked with [`Effect::with_animated`]. The three
136//! are per frame, not per layer: every layer painted in one frame sees the same values.
137//!
138//! ## Named parameters
139//!
140//! A snippet may declare `struct Params { ... }`; the crate then binds it as `p` and the effect
141//! reads `p.<member>`. Each [`Pass`] stores its own values, set by name and type-checked against
142//! the struct ([`Pass::set`], [`Pass::with`], [`Pass::set_slice`] for arrays); a mismatch is a
143//! [`ParamError`], never a panic. [`Effect::params`] reflects the members ([`ParamInfo`]: name,
144//! [`ParamType`], offset, array length) so a UI can build its controls from the effect alone.
145//! Members start at zero (WGSL has no default values).
146//!
147//! ```
148//! use egui_shader_layers::{Effect, ParamError, ParamType, Pass};
149//!
150//! let effect = Effect::new("tint", "
151//! struct Params {
152//!     color: vec4<f32>,
153//!     amount: f32,
154//!     stops: array<vec4<f32>, 4>,
155//! }
156//! fn effect(uv: vec2<f32>) -> vec4<f32> {
157//!     return mix(src(uv), p.color, p.amount) + p.stops[0] * 0.0;
158//! }")?;
159//! assert_eq!(effect.params().len(), 3);
160//! assert_eq!(effect.param("amount").map(|info| info.ty), Some(ParamType::F32));
161//!
162//! let mut pass = Pass::new(&effect).with("color", [1.0, 0.5, 0.0, 1.0])?.with("amount", 0.25)?;
163//! pass.set_slice("stops", &[[0.0_f32, 0.0, 0.0, 1.0]])?; // the remaining elements become zero
164//! assert!(matches!(pass.set("amount", 1), Err(ParamError::Type { .. }))); // `1` is an i32
165//! # Ok::<(), Box<dyn std::error::Error>>(())
166//! ```
167//!
168//! Accepted member types: `f32`, `i32`, `u32`, `vec2<f32>`, `vec3<f32>`, `vec4<f32>`,
169//! `mat4x4<f32>` and fixed-size arrays of `vec3<f32>` / `vec4<f32>` / `mat4x4<f32>` (uniform
170//! arrays need a 16-byte stride). Anything else (`bool`, nested structs, `array<f32, N>`) and a
171//! struct over 16 KiB (the WebGL2 uniform block limit) is an [`EffectError::Interface`] pointing
172//! at the declaration. The snippet must not declare its own module-scope `p`. Named and
173//! anonymous (`params(i)`) parameters can be used together.
174//!
175//! ## Textures
176//!
177//! A layer attaches up to [`TEXTURE_SLOTS`] (3, on every backend) egui textures with
178//! [`ShaderLayer::texture`] — noise, normal maps, lookup tables, images — which its effects read
179//! with `tex(i, uv)`, `tex_size(i)` and `tex_load(i, px)`. Values are premultiplied gamma RGBA,
180//! like `src()`. Each texture is read through its own sampler only (its `TextureOptions`); exact
181//! reads use `tex_load`, which needs none.
182//!
183//! ```
184//! use egui_shader_layers::{Effect, ShaderLayer, Pass};
185//! # fn frame(ui: &mut egui::Ui, noise: &egui::TextureHandle, rect: egui::Rect) -> Result<(), egui_shader_layers::EffectError> {
186//! // `noise` from `ctx.load_texture(.., egui::TextureOptions::LINEAR_REPEAT)`, kept alive.
187//! let displace = Effect::new("displace", "
188//! fn effect(uv: vec2<f32>) -> vec4<f32> {
189//!     let n = tex(0u, uv * 4.0).rg - vec2<f32>(0.5);
190//!     return src(uv + n * 8.0 * fl.texel);
191//! }")?.with_sample_radius(4.0);
192//! assert!(displace.reads_texture(0) && !displace.reads_texture(1));
193//! ShaderLayer::new(rect, Pass::new(&displace)).texture(0, noise.id()).paint(ui.painter());
194//! # Ok(()) }
195//! ```
196//!
197//! Which slots an effect reads is found in naga's IR ([`Effect::reads_texture`]; a slot index
198//! that is not a constant counts as every slot). A layer whose effect reads a slot with nothing
199//! attached is refused before drawing — [`ShaderLayer::check_textures`] returns the
200//! [`TextureError`], `paint` draws nothing and logs it once — never silently fed a dummy. A
201//! texture id the renderer does not know (freed: keep the `TextureHandle` alive) skips the
202//! layers attaching it and is listed by [`failed_textures`]. Offline runs attach an
203//! `OfflineTexture` with `OfflineOptions::with_texture` (features `image` / `video`).
204//!
205//! ## Impulses: transient effects from input
206//!
207//! [`Impulses`] is a small collection you keep in your app state: push an impulse where the
208//! user clicked ([`Impulses::push_point`], positions relative to the layer rect), and every
209//! frame hand it to [`presets::click_ripples`] (rings expanding from each click) or to your own
210//! effect through [`Impulses::apply`], which fills the named parameters [`IMPULSES_PARAM`]
211//! (`impulses: array<vec4<f32>, 16>`, each `(uv.x, uv.y, age_seconds, strength)`) and
212//! [`IMPULSE_COUNT_PARAM`] (`impulse_count: u32`). Impulses age against the clock you pass
213//! (egui's `input.time` in the UI, frame time offline), expire after their life, and a full
214//! collection drops the oldest first ([`IMPULSE_SLOTS`] at most). Such effects are not animated by
215//! `fl.time`: call [`Impulses::request_repaint_if_alive`] each frame, so the app repaints while a
216//! ring is alive and stays idle afterwards.
217//!
218//! Colours are **premultiplied-alpha, gamma-space** RGBA in and out. Names starting with `fl_`
219//! and the prelude names above are reserved. An effect cannot declare its own bindings or entry
220//! points. If it reads further than the current pixel, declare how far with
221//! [`Effect::with_sample_radius`] (or per pass with [`Pass::with_sample_radius`]).
222//!
223//! ## Persistent state
224//!
225//! A **state pass** ([`Effect::new_state`]) writes the layer's persistent state instead of the
226//! next image: two RGBA textures per layer (ping-pong) that survive from frame to frame —
227//! simulations (water, [`presets::wave_sim`]), trails ([`presets::trails`]), accumulation.
228//!
229//! * **Reading.** Every pass reads the latest state with `state(uv)` (bilinear), `state_load(px)` /
230//!   `state_px(offset)` (exact texels) — a display pass sees what the last state pass BEFORE it
231//!   wrote (or last frame's state), a state pass the state it steps. Inside a state pass `src()` is
232//!   the display chain's input at that point (a state pass does not advance it), `original()` the
233//!   backdrop. N consecutive state passes are N substeps (`fl.pass_index` = 0..N).
234//! * **Identity.** A layer whose chain has a state pass needs [`ShaderLayer::id`]: the state is
235//!   kept per id and viewport. Without an id it is refused ([`ShaderLayer::check_state`]:
236//!   [`StateError::MissingId`]; it draws nothing, logged once). Painting one id twice in a frame
237//!   steps it once (the second paint shows the state as it is).
238//! * **Size.** The state spans the whole capture (the padded rect, `uv` space) at
239//!   `ceil(capture * scale)` texels ([`StateOptions::with_scale`]); it lives in layer uv, so a
240//!   moved layer keeps it, and a resized layer reads the previous state stretched (no reset).
241//! * **Format.** [`StateFormat::Rgba16Float`] by default (signed, unbounded): it must be
242//!   renderable and filterable on the device, else stateful layers are refused and listed by
243//!   [`failed_states`] (WebGL2 / GLES without `EXT_color_buffer_float`); never silently downgraded.
244//!   [`StateFormat::Rgba8Unorm`] is an explicit opt-in for effects that pack their state in 8 bits.
245//! * **Lifetime.** A state starts at zero; [`reset_state`] zeroes it at the id's next paint that
246//!   actually runs (a paint that draws nothing, e.g. off screen, keeps the request pending); a
247//!   state not painted for 120 frames OF ITS OWN VIEWPORT and 2 seconds is freed (so an idle
248//!   viewport keeps its states while another animates; [`state_count`] for debugging); a
249//!   re-install (or `destroy_glow`) drops all. It advances only on painted frames: the effect is
250//!   not animated by itself — repaint while it should move.
251//! * **Offline**, the renderer carries the state from one `process` call to the next
252//!   (`OfflineOptions::with_state`, `OfflineRenderer::reset_state`, a video processor's frames);
253//!   stateful chains are never tiled (`OfflineError::NotTileable`).
254//!
255//! ```
256//! use egui_shader_layers::{Effect, FilterChain, ShaderLayer, Pass};
257//! # fn frame(ui: &mut egui::Ui, rect: egui::Rect) -> Result<(), egui_shader_layers::EffectError> {
258//! // Accumulates the backdrop's brightness over frames and shows it.
259//! let accumulate = Effect::new_state("glow", "
260//! fn effect(uv: vec2<f32>) -> vec4<f32> {
261//!     return state_px(vec2<i32>(0)) * 0.9 + src(uv) * 0.1;
262//! }")?;
263//! let show = Effect::new("show", "fn effect(uv: vec2<f32>) -> vec4<f32> { return state(uv); }")?;
264//! let chain = FilterChain::new().then(Pass::new(&accumulate)).then(Pass::new(&show));
265//! ShaderLayer::new(rect, chain).id(ui.id().with("glow")).paint(ui.painter());
266//! # Ok(()) }
267//! ```
268//!
269//! **Reduced-resolution passes.** [`Pass::with_scale`] runs a pass over `ceil(capture * scale)`
270//! pixels; the next pass (or the final composite, bilinearly) reads that smaller image. `uv`,
271//! `src()`, `original()`, `fl.texel` and `fl.size_px` keep their capture meaning, so an
272//! effect's distance maths is the same at any scale; kernels that step in pixels use `src_px()`
273//! / `src_texel()` (input pixels) or `out_texel()`. [`presets::kawase_blur`] and
274//! [`presets::bloom`] are built from such passes. Offline, a scaled chain refuses tiling.
275//!
276//! **Masks.** A layer filters its whole rect, or a rounded rect ([`ShaderLayer::corner_radius`]),
277//! or any egui shape: [`ShaderLayer::mask`] with [`Mask::Shape`] — paths, circles, rects,
278//! meshes, text galleys (UI only), in the layer's points (so it follows layer transforms). The
279//! shape's alpha is the coverage (paint it opaque for a full-strength filter; egui's feathered edge
280//! anti-aliases it); outside it the backdrop stays untouched. It is tessellated when the layer is
281//! painted and rasterized into a coverage texture at capture resolution; the coverage of several
282//! pieces is the sum of their alphas, capped at 1, so pieces meeting edge to edge leave no seam
283//! (their feathered edges add up to full coverage). egui fills convex paths only: build a concave
284//! outline from convex pieces (abutting or overlapping) or from a mesh.
285//!
286//! ```no_run
287//! # fn frame(ui: &mut egui::Ui, rect: egui::Rect) {
288//! use egui_shader_layers::{ShaderLayer, Mask, presets};
289//! let lens = egui::Shape::circle_filled(rect.center(), 60.0, egui::Color32::WHITE);
290//! ShaderLayer::new(rect, presets::gaussian_blur(8.0)).mask(Mask::Shape(lens)).paint(ui.painter());
291//! # }
292//! ```
293//!
294//! **Regions.** One layer can run its chain differently per area: [`ShaderLayer::regions`] (a
295//! [`Mask::Regions`] of up to [`MAX_REGIONS`] [`Region`]s) masks by the union of the regions (no
296//! seam where they abut) and tells every pass which region a pixel belongs to: `region()` is the
297//! region's index, `region_at(uv)` the one at another point (a kernel that must not cross into a
298//! neighbour compares `region_at(uv + d) == region()`). Per-region values are named-parameter
299//! arrays indexed by it; scalars go four to a `vec4` (`array<f32, N>` is not accepted). Where
300//! regions overlap the LATER one wins, and the boundary between two regions is pixel-hard (a soft
301//! transition between two parameter sets needs two layers). One capture and one chain run serve
302//! every region, which is what makes many small areas cheaper than many layers. Regions run on the
303//! wgpu and glow backends and offline (`OfflineOptions::with_mask`, tiled like any mask).
304//!
305//! ```no_run
306//! # fn frame(ui: &mut egui::Ui, rect: egui::Rect) -> Result<(), Box<dyn std::error::Error>> {
307//! use egui_shader_layers::{Effect, ShaderLayer, Pass, Region};
308//! let tint = Effect::new("tint", "struct Params { tint: array<vec4<f32>, 2> }
309//! fn effect(uv: vec2<f32>) -> vec4<f32> { return mix(src(uv), p.tint[min(region(), 1u)], 0.5); }")?;
310//! let mut pass = Pass::new(&tint);
311//! pass.set_slice("tint", &[[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]])?;
312//! let (left, right) = rect.split_left_right_at_fraction(0.5);
313//! ShaderLayer::new(rect, pass).regions([Region::rounded_rect(left, 8), Region::rounded_rect(right, 8)]).paint(ui.painter());
314//! # Ok(()) }
315//! ```
316//!
317//! **Distances are in layer points.** Sample radii, corner radii and every effect distance
318//! converted with `fl.pixels_per_point` are measured in the points of the layer the filter is
319//! painted in. Inside a transformed layer (an `egui::Scene`, `Context::set_transform_layer`) they
320//! scale with its zoom exactly like the painted content: a 4-point blur covers 8 pixels at zoom 2
321//! and 2 pixels at zoom 0.5 (at 1 pixel per point), and the capture padding follows.
322//!
323//! # Regions and entries
324//!
325//! Three ways to filter many areas:
326//!
327//! * **Regions** ([`ShaderLayer::regions`]): ONE chain, one capture (the layer rect, which must
328//!   cover the regions) and one run for every area; effects read `region()` to vary their
329//!   parameters. Use it for many small areas that share the effect and differ only in parameters
330//!   (a grid of tinted glass tiles); the boundary between two regions is hard. The capture covers
331//!   the whole rect, so a few areas far apart pay for the space between them.
332//! * **Entries** ([`Entry`], [`ShaderLayer::from_entries`], [`ShaderLayer::with_entry`]): each
333//!   area has its OWN chain, mask, textures and state, and captures ONLY its own padded rect;
334//!   the entries share one paint callback (and on wgpu one selection and tessellation of the
335//!   content beneath). [`Overlap`] says what a later entry filters where entries overlap:
336//!   [`Overlap::Independent`] (the original backdrop; the later one covers the earlier) or
337//!   [`Overlap::Stacked`] (the earlier entries' result, like separate layers — on EVERY backend,
338//!   while separate layers on wgpu cannot see each other). Composites are in list order. The
339//!   layer-level builders (`mask`, `corner_radius`, `regions`, `texture`, `state`) apply to every
340//!   entry present, the accessors return the first entry's; a stateful entry keeps its own state
341//!   under the layer's id and its index in the list (also while an earlier entry draws nothing),
342//!   and [`reset_state`] resets them all. A layer is drawn or refused as a
343//!   whole (any failing entry refuses it). Offline: `OfflineLayer` + `OfflineEntry` with
344//!   `OfflineRenderer::process_layer` (never tiled). Entries run on the wgpu and glow backends and
345//!   offline, in both overlap modes.
346//! * **Separate layers**: one [`ShaderLayer`] per area. The most general (each its own position
347//!   in egui's paint order), and the costliest on wgpu: every layer selects, tessellates and
348//!   re-renders the content beneath it again.
349//!
350//! Rule of thumb: the same effect with different parameters → regions; different chains, masks or
351//! state per area → entries (or regions with one branching chain when there are many dense
352//! areas); different paint-order positions → separate layers. Prefer [`Overlap::Independent`]
353//! unless a later entry must see an earlier entry's result: on wgpu `Stacked` adds a hand-off draw
354//! into every later entry whose padded capture an earlier one reaches.
355//!
356//! Measured by `bench_many_elements` (N frosted, tinted tiles filling a busy 256x128 backdrop,
357//! release build, Ryzen 5 9600X iGPU, Mesa 26.0.3, wall time per frame including egui, GPU
358//! completion and readback; ms for N = 4 / 16 / 64; the backdrop alone costs 0.09 ms on wgpu and
359//! 0.16 ms on glow):
360//!
361//! | mode | wgpu (Vulkan) | glow |
362//! |---|---|---|
363//! | N layers | 0.57 / 1.39 / 5.75 | 0.50 / 0.80 / 1.64 |
364//! | 1 layer, N regions | 0.41 / 0.42 / 0.53 | 0.41 / 0.43 / 0.56 |
365//! | 1 layer, N entries | 0.57 / 1.38 / 5.97 | 0.49 / 0.81 / 1.61 |
366//! | 1 layer, N entries, stacked | 0.60 / 2.23 / 9.74 | 0.49 / 0.82 / 1.60 |
367//!
368//! Regions stay nearly flat as N grows; layers and entries grow with N, steeply on wgpu. With a few small areas far apart on a large screen
369//! the regions capture grows with the screen, while layers and entries stay at their areas' size.
370//!
371//! # Backends
372//!
373//! | backend | how the backdrop is obtained | status |
374//! |---|---|---|
375//! | `egui_glow` (GL 3.3+, GLES 3.0+, WebGL2) | copied out of the framebuffer inside the paint callback (MSAA resolved) | feature `glow` |
376//! | `egui_glow` on `WebGL1` / GL < 3.3 | — | unsupported: [`InstallError::Unsupported`] |
377//! | `egui-wgpu` (native and web) | the content beneath is **rendered a second time** offscreen | feature `wgpu`, `install_wgpu` |
378//!
379//! **Warning — wgpu draws the content under a filter twice.** egui-wgpu renders into a surface
380//! that cannot be read back mid-pass, so the wgpu backend re-renders everything beneath each
381//! shader layer (clipped to its padded rect) into an offscreen texture. The content under a
382//! filter is therefore **drawn twice** per frame on wgpu. Paint callbacks beneath a filter —
383//! including a lower shader layer — cannot be re-rendered and are left out of its backdrop.
384// Backend items exist only with their feature: sentences linking to them are feature-gated so
385// the docs build with `-D warnings` under any feature set (docs.rs builds with all features).
386#![cfg_attr(feature = "wgpu", doc = "See [`install_wgpu`].")]
387//!
388#![cfg_attr(feature = "glow", doc = "OpenGL objects must be freed explicitly: call [`destroy_glow`] from `eframe::App::on_exit`.")]
389#![cfg_attr(not(feature = "glow"), doc = "OpenGL objects must be freed explicitly: call `destroy_glow` (feature `glow`) from `eframe::App::on_exit`.")]
390//!
391//! The installed backend is stored in the `egui::Context` itself (as a hook-less egui plugin),
392//! not in egui `Memory`, so resetting memory does not uninstall it.
393//!
394//! # Offline processing
395//!
396//! With the `image` or `video` feature, an `OfflineRenderer` (wgpu only, also for glow apps) runs
397//! the same chains over ordinary images and video frames and returns the pixels — identical to a
398//! layer over that frame in the UI under the conditions listed in the `offline` module docs.
399//! `video` adds a frame-stream processor, source / sink traits and ffmpeg adapters.
400#![cfg_attr(any(feature = "image", feature = "video"), doc = "See [`offline`].")]
401//!
402//! # Hot reload
403//!
404//! With the `hot-reload` feature (native only; on wasm32 it compiles to nothing), a `HotEffect`
405//! follows a WGSL file on disk: a background thread polls its modification time, recompiles it
406//! off the GUI thread, and `HotEffect::poll` (once per frame, never blocking) swaps in the new
407//! effect. While the file is broken the last good effect keeps rendering and the error, with
408//! naga's diagnostic, is available for an overlay. `rebind` rebuilds a `Pass` on the reloaded
409//! effect, keeping named parameter values whose name and type still match.
410
411// docs.rs builds with `--cfg docsrs` on nightly: badge feature-gated items with their feature.
412#![cfg_attr(docsrs, feature(doc_cfg))]
413#![warn(clippy::pedantic)]
414#![warn(clippy::undocumented_unsafe_blocks)]
415#![deny(missing_docs)]
416#![allow(clippy::module_name_repetitions)] // `ShaderLayer` in `layer`, `EffectError` in `effect` read best as-is.
417// Without any backend feature the backend-facing internals (LayerJob fields, registry writers,
418// binding constants) have no reader by design; the crate still builds for validation-only use.
419#![cfg_attr(not(any(feature = "glow", feature = "wgpu")), allow(dead_code))]
420
421mod backend;
422mod effect;
423mod entry;
424mod geometry;
425mod impulses;
426mod layer;
427mod mask;
428mod pass;
429mod plan;
430pub mod presets;
431mod state;
432
433#[cfg(feature = "glow")]
434mod glow_backend;
435#[cfg(feature = "wgpu")]
436mod wgpu_backend;
437
438// Offline processing: the core is shared by the `image` and `video` features; this gate is the
439// one place to widen when another feature needs it.
440#[cfg(any(feature = "image", feature = "video"))]
441pub mod offline;
442
443// Hot reload needs a file system and threads: native only. On wasm32 the feature is accepted
444// (so `--all-features` builds everywhere) but the module is absent.
445#[cfg(all(feature = "hot-reload", not(target_arch = "wasm32")))]
446mod hot;
447
448pub use backend::{BackendKind, BackendStatus, EffectFailure, InstallError, TextureError, TextureFailure, failed_effects, failed_textures, status};
449pub use effect::{Effect, EffectError, ParamError, ParamInfo, ParamType, ParamValue, SnippetLocation, TEXTURE_SLOTS};
450pub use entry::{Entry, Overlap};
451pub use impulses::{IMPULSE_COUNT_PARAM, IMPULSE_SLOTS, IMPULSES_PARAM, Impulse, ImpulsePack, Impulses};
452pub use layer::ShaderLayer;
453pub use mask::{MAX_REGIONS, Mask, MaskError, REGION_NONE, Region};
454pub use pass::{FilterChain, MIN_PASS_SCALE, PARAM_SLOTS, ParamIndexError, Params, Pass};
455pub use presets::WaveObstacle;
456pub use state::{StateError, StateFailure, StateFormat, StateOptions, failed_states, reset_state, state_count};
457
458#[cfg(feature = "glow")]
459pub use glow_backend::{destroy_glow, install_glow};
460#[cfg(feature = "wgpu")]
461pub use wgpu_backend::{WgpuOptions, install_wgpu};
462#[cfg(any(feature = "image", feature = "video"))]
463pub use offline::{AlphaMode, FrameRef, OfflineEntry, OfflineError, OfflineLayer, OfflineOptions, OfflineRenderer, OfflineTexture, PointerState, RgbaFrame};
464#[cfg(all(feature = "hot-reload", not(target_arch = "wasm32")))]
465pub use hot::{DEFAULT_POLL_INTERVAL, HotEffect, HotOptions, HotReloadError, HotReloadEvent, MIN_POLL_INTERVAL, Rebound, rebind};