Skip to main content

ultrafast_render/
lib.rs

1//! ultrafast renderer: compiles documents into fused GPU plans and executes them.
2//!
3//! Per frame the renderer: (1) checks the document's structure signature and
4//! recompiles the plan only if it changed, (2) packs params for every group
5//! into the frame's param arena, (3) skips static groups whose inputs and
6//! params are unchanged, (4) dispatches one kernel per group, falling back to
7//! tier-0 kernels for groups whose fused kernel is still compiling.
8//!
9//! Every texture a kernel reads is *placed*: a texture plus the frame
10//! position of its top-left texel. Frame-sized intermediates sit at the
11//! origin; rasterized paths and text get textures sized to their bounds, so
12//! their cost scales with what they cover, not with the frame.
13
14// Engine code: wide kernel and pass signatures and indexed loops over
15// parallel arrays are the clearest form here.
16#![allow(
17    clippy::too_many_arguments,
18    clippy::type_complexity,
19    clippy::needless_range_loop,
20    clippy::should_implement_trait
21)]
22
23pub mod autofaces;
24pub mod blocks;
25pub mod captions;
26mod charts;
27pub mod code;
28pub mod codegen;
29mod glyph_atlas;
30pub mod images;
31pub mod kernels;
32pub mod layout;
33pub mod lottie;
34pub mod particles;
35pub mod plan;
36pub mod pushdown;
37pub mod raymarch;
38pub mod review;
39pub mod scene3d;
40mod sim;
41mod specialize;
42pub mod svg;
43pub mod swarm;
44pub mod tables;
45pub mod transitions;
46
47// Text, vector geometry, the face camera and the op vocabulary live in CPU
48// crates (tools use them without a GPU), re-exported at
49// their old paths.
50pub use ultrafast_framing::follow;
51pub use ultrafast_geom::{fontfetch, geom, lru, markup};
52pub use ultrafast_ops::{builtins, ops, schema};
53
54use images::ImageCache;
55use kernels::{KernelState, Kernels};
56use ops::ResourceInfo;
57use plan::{GroupKind, Plan, TexSource};
58use std::collections::{BTreeMap, HashMap};
59use std::path::{Path, PathBuf};
60use std::sync::Arc;
61use std::time::Instant;
62use ultrafast_gpu::{
63    Bindings, Buffer, BufferBinding, CommandList, Device, GpuError, PixelFormat, Submitted, Texture, TextureDesc,
64};
65use ultrafast_graph::{Document, DocumentError, NodeId};
66
67#[derive(Debug, thiserror::Error)]
68pub enum RenderError {
69    #[error(transparent)]
70    Gpu(#[from] GpuError),
71    #[error(transparent)]
72    Document(#[from] DocumentError),
73    #[error("node `{node}` has unknown op `{op}`")]
74    UnknownOp { node: NodeId, op: String },
75    #[error("node `{node}` is missing required input `{port}`")]
76    MissingPort { node: NodeId, port: String },
77    #[error("node `{node}` param `{param}`: {reason}")]
78    BadParam {
79        node: NodeId,
80        param: String,
81        reason: String,
82    },
83    #[error("node `{node}` needs {count} texture inputs in one kernel (max 16)")]
84    TooManyInputs { node: NodeId, count: usize },
85    #[error("kernel setup failed: {0}")]
86    Setup(String),
87}
88
89/// Geometry errors are the render errors of the same name.
90impl From<ultrafast_geom::GeomError> for RenderError {
91    fn from(e: ultrafast_geom::GeomError) -> Self {
92        match e {
93            ultrafast_geom::GeomError::BadParam { node, param, reason } => {
94                RenderError::BadParam { node, param, reason }
95            }
96        }
97    }
98}
99
100/// Op errors are the render errors of the same name.
101impl From<ultrafast_ops::OpsError> for RenderError {
102    fn from(e: ultrafast_ops::OpsError) -> Self {
103        match e {
104            ultrafast_ops::OpsError::UnknownOp { node, op } => RenderError::UnknownOp { node, op },
105            ultrafast_ops::OpsError::MissingPort { node, port } => RenderError::MissingPort { node, port },
106            ultrafast_ops::OpsError::BadParam { node, param, reason } => RenderError::BadParam { node, param, reason },
107        }
108    }
109}
110
111/// How [`Renderer::render_readback`] hands a frame back.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum Readback {
114    /// sRGB RGBA8.
115    Srgb8,
116    /// sRGB-encoded RGBA half floats, for 10-bit codecs.
117    SrgbHalf,
118    /// Linear RGBA half floats (EXR); straight alpha, as encoders that
119    /// premultiply take it.
120    LinearHalf,
121}
122
123/// How the renderer treats kernels that are still compiling.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum Mode {
126    /// Never stall: use tier-0 fallbacks and placeholders while compiling or
127    /// loading. For live preview.
128    Live,
129    /// Wait for every fused kernel and resource. Deterministic; for export.
130    Exact,
131}
132
133/// What one frame cost and how it was produced.
134#[derive(Debug, Clone, Copy, Default)]
135pub struct FrameReport {
136    pub replanned: bool,
137    pub kernels_run: usize,
138    pub groups_cached: usize,
139    /// Groups skipped because nothing they feed is visible at this time.
140    pub groups_skipped: usize,
141    /// Groups rendered with tier-0 kernels because their fused kernel was
142    /// still compiling.
143    pub groups_fallback: usize,
144    /// Simulation steps taken, and frames rendered only to bring
145    /// simulations up to this one (after a seek).
146    pub sim_steps: usize,
147    pub sim_catchup_frames: usize,
148    /// Motion blur: samples taken this frame (1 when nothing moved), the
149    /// group up to which they were taken, and how many groups up to it read
150    /// nothing moving and ran once instead.
151    pub mb_samples: u32,
152    pub mb_split: usize,
153    pub mb_once: usize,
154    /// Images still decoding and videos whose frame for this time was not
155    /// decoded yet (live mode draws what it has): a later frame at the same
156    /// time will differ, so a paused player draws again.
157    pub media_pending: usize,
158    pub cpu_encode_ms: f64,
159    pub plan_ms: f64,
160}
161
162/// A problem tied to a node that does not stop rendering (bad shader code,
163/// missing image). Agents read these to fix their documents.
164#[derive(Debug, Clone, PartialEq)]
165pub struct Diagnostic {
166    pub node: NodeId,
167    pub message: String,
168}
169
170impl Diagnostic {
171    /// "warning" for parts of an imported file ultrafast leaves out (the rest
172    /// renders), "error" for problems that stop a node from rendering.
173    pub fn severity(&self) -> &'static str {
174        if self.message.starts_with("lottie: ") || self.message.starts_with("svg: ") {
175            "warning"
176        } else {
177            "error"
178        }
179    }
180}
181
182/// The final image of a frame, handed to [`Renderer::submit_frame_with`]
183/// callbacks so they can consume it in the same command buffer.
184pub struct FrameOutput<'a> {
185    pub list: &'a mut CommandList,
186    pub kernels: &'a Kernels,
187    pub texture: &'a Texture,
188    /// Frame position of the texture's top-left texel.
189    pub origin: [f32; 2],
190    /// Frame header (time, frame, width, height) for kernel params.
191    pub header: [f32; 4],
192}
193
194/// How a frame maps onto the textures it renders into: `px` frame pixels
195/// per device texel (1 at the document's own size, 0.5 for twice its
196/// size) and the device size. Everything in a document stays in frame
197/// pixels; only texture sizes and texel steps follow the view.
198#[derive(Debug, Clone, Copy, PartialEq)]
199pub(crate) struct View {
200    pub px: f32,
201    pub w: u32,
202    pub h: u32,
203}
204
205impl View {
206    /// The document at its own size.
207    pub fn native(doc: &Document) -> View {
208        View {
209            px: 1.0,
210            w: doc.format.width,
211            h: doc.format.height,
212        }
213    }
214
215    /// The document drawn at `w` x `h`: one texel step for both axes, the
216    /// finer of the two, so every texel is inside the frame.
217    pub fn sized(doc: &Document, size: Option<(u32, u32)>) -> View {
218        let (fw, fh) = (doc.format.width.max(1), doc.format.height.max(1));
219        match size {
220            Some((w, h)) if (w, h) != (fw, fh) && w > 0 && h > 0 => View {
221                px: 1.0 / (w as f32 / fw as f32).max(h as f32 / fh as f32),
222                w,
223                h,
224            },
225            _ => View::native(doc),
226        }
227    }
228}
229
230/// A texture positioned in the frame.
231#[derive(Clone)]
232struct Placed {
233    tex: Texture,
234    origin: [f32; 2],
235    /// Frame px per texel: 1, or more for a blur kept at the reduced
236    /// resolution it was computed at (the kernels reading it sample it).
237    scale: f32,
238}
239
240struct TexturePool {
241    free: HashMap<TextureDesc, Vec<Texture>>,
242    max_free_per_desc: usize,
243    /// Bytes held in free lists, and the most they may hold: raster
244    /// textures come in many sizes, so a per-size count alone is unbounded.
245    free_bytes: u64,
246    max_free_bytes: u64,
247    /// When each size was last leased or given back: a full pool lets go
248    /// of the sizes nothing has asked for longest (type that grew past a
249    /// size, last week's shot) to keep the ones every frame uses.
250    clock: u64,
251    last_used: HashMap<TextureDesc, u64>,
252}
253
254fn tex_bytes(d: TextureDesc) -> u64 {
255    d.width as u64 * d.height as u64 * d.format.bytes_per_pixel() as u64
256}
257
258impl TexturePool {
259    fn lease(&mut self, device: &Device, desc: TextureDesc) -> Texture {
260        self.clock += 1;
261        self.last_used.insert(desc, self.clock);
262        match self.free.get_mut(&desc).and_then(Vec::pop) {
263            Some(t) => {
264                self.free_bytes -= tex_bytes(desc);
265                t
266            }
267            None => device.create_texture(desc),
268        }
269    }
270
271    fn give_back(&mut self, tex: Texture) {
272        let desc = tex.desc();
273        let bytes = tex_bytes(desc);
274        if bytes > self.max_free_bytes || self.free.get(&desc).is_some_and(|l| l.len() >= self.max_free_per_desc) {
275            return;
276        }
277        self.clock += 1;
278        self.last_used.insert(desc, self.clock);
279        // Make room by dropping the sizes asked for least recently.
280        while self.free_bytes + bytes > self.max_free_bytes {
281            let Some(old) = self
282                .free
283                .iter()
284                .filter(|(d, l)| !l.is_empty() && **d != desc)
285                .min_by_key(|(d, _)| self.last_used.get(*d).copied().unwrap_or(0))
286                .map(|(d, _)| *d)
287            else {
288                return;
289            };
290            let list = self.free.get_mut(&old).unwrap();
291            while self.free_bytes + bytes > self.max_free_bytes && list.pop().is_some() {
292                self.free_bytes -= tex_bytes(old);
293            }
294            if list.is_empty() {
295                self.free.remove(&old);
296                self.last_used.remove(&old);
297            }
298        }
299        self.free.entry(desc).or_default().push(tex);
300        self.free_bytes += bytes;
301    }
302}
303
304type StaticKey = (Vec<f32>, Vec<usize>);
305
306#[derive(Default)]
307struct Profiler {
308    pending: Vec<(String, Submitted)>,
309    totals: HashMap<String, (f64, u32)>,
310}
311
312/// An element under a point of the frame ([`Renderer::pick`]).
313#[derive(Debug, Clone, serde::Serialize)]
314pub struct Picked {
315    /// The document node it belongs to (edit this one).
316    pub node: String,
317    pub op: String,
318    /// The node that drew it (inside a component or block: `node/...`).
319    pub part: String,
320    /// Frame px [x0, y0, x1, y1].
321    pub bounds: [f32; 4],
322}
323
324/// An element on screen ([`Renderer::visible`]).
325#[derive(Debug, Clone, serde::Serialize)]
326pub struct Visible {
327    #[serde(flatten)]
328    pub element: Picked,
329    /// What it reads, for text.
330    #[serde(skip_serializing_if = "Option::is_none")]
331    pub text: Option<String>,
332}
333
334/// Where a document's GPU time goes ([`Renderer::profile_frames`]).
335#[derive(Debug, Clone, serde::Serialize)]
336pub struct ProfileReport {
337    pub frames: u64,
338    pub from: f64,
339    pub gpu_ms_per_frame: f64,
340    /// Most expensive first.
341    pub groups: Vec<GroupShare>,
342    /// Work outside groups: motion-blur averaging, output conversion.
343    pub rest_ms_per_frame: f64,
344}
345
346#[derive(Debug, Clone, serde::Serialize)]
347pub struct GroupShare {
348    /// The group's kind and the nodes it renders.
349    pub group: String,
350    pub ms_per_frame: f64,
351    pub share: f64,
352    /// Motion-blur samples run groups several times a frame.
353    pub runs_per_frame: f64,
354}
355
356/// What one render group cost on the GPU while profiling.
357#[derive(Debug, Clone, serde::Serialize)]
358pub struct GroupCost {
359    /// The group's kind and the nodes it renders.
360    pub group: String,
361    /// Total GPU milliseconds.
362    pub ms: f64,
363    /// Times it ran (motion blur samples run groups several times a frame).
364    pub runs: u32,
365}
366
367struct Active {
368    plan: Plan,
369    /// Frame-sized group outputs. A slot gets a texture the first time a
370    /// live group needs it and gives it back when unused slots outgrow the
371    /// memory budget (long films plan thousands of slots; a frame touches
372    /// a few). Non-resident slots hold the placeholder.
373    slots: Vec<Texture>,
374    resident: Vec<bool>,
375    /// Frame each slot was last needed in.
376    slot_used: Vec<u64>,
377    /// Groups writing each slot (their caches die with its texture).
378    slot_groups: Vec<Vec<usize>>,
379    slot_desc: TextureDesc,
380    /// The view the slots are sized for.
381    view: View,
382    /// Frame each group was last live in (cold raster textures are given
383    /// back under the same budget).
384    group_used: Vec<u64>,
385    /// For static groups: params and input identities of the last run.
386    cache: Vec<Option<StaticKey>>,
387    /// Bounds-sized output textures of raster groups.
388    raster: Vec<Option<Placed>>,
389    /// What each raster group last drew (geometry and paint), so geometry
390    /// that holds still is not drawn again.
391    drawn: Vec<u64>,
392    /// Fused groups that only pass an earlier group's output through at
393    /// the current time (inactive layers, empty foregrounds) show it
394    /// directly instead of copying it.
395    alias: Vec<Option<usize>>,
396    /// Groups whose `raster` entry is another group's texture shown as it is
397    /// (an inactive blur passing its source through): not theirs to reuse
398    /// or return to the pool.
399    borrowed: Vec<bool>,
400    /// Where each group's output can be non-transparent (frame px), as the
401    /// last pass that ran it found.
402    bounds: Vec<ops::Rect>,
403    /// Per blur group: the fused groups reading it, when every reader can
404    /// sample it at the reduced resolution it is computed at (fused groups
405    /// outside their loops, and blurs); None when it must be full size.
406    low_readers: Vec<Option<Vec<usize>>>,
407}
408
409/// A motion-blurred frame's schedule, for the passes that run it.
410struct MbFrame {
411    /// Per group: read by a group of a later phase, so what it makes must
412    /// last until then (no showing a slot another group may write first).
413    crosses: Vec<bool>,
414    /// The shutter's span (seconds): particles drawn once blur themselves
415    /// along their paths over it.
416    span: f64,
417}
418
419/// One sampled group's average across a frame's samples.
420struct MbAccum {
421    /// Running sum (newest, spare) of frame-sized outputs.
422    sum: Option<(Texture, Texture)>,
423    /// Copies of bounds-sized outputs, summed over their union at the end.
424    stash: Vec<Placed>,
425    /// Union of the samples' content bounds.
426    bounds: ops::Rect,
427}
428
429impl Default for MbAccum {
430    fn default() -> Self {
431        MbAccum {
432            sum: None,
433            stash: Vec::new(),
434            bounds: ops::EMPTY,
435        }
436    }
437}
438
439/// Which groups a pass over the plan runs, and what it returns.
440#[derive(Default, Clone, Copy)]
441struct Pass<'a> {
442    /// Only these groups (default: every group that reaches the output now).
443    only: Option<&'a [bool]>,
444    /// The group whose output the pass returns (default: the last).
445    target: Option<usize>,
446    /// Groups whose outputs were replaced outside the pass.
447    changed: &'a [usize],
448    /// Keep the bounds earlier passes this frame found for the groups this
449    /// one does not run (motion blur's samples read what its once-a-frame
450    /// pass made).
451    keep_bounds: bool,
452}
453
454pub struct Renderer {
455    device: Device,
456    kernels: Kernels,
457    active: Option<Active>,
458    seen_revision: Option<(u64, u64)>,
459    pool: TexturePool,
460    images: ImageCache,
461    placeholder: Texture,
462    export: Option<Texture>,
463    mode: Mode,
464    diagnostics: Vec<Diagnostic>,
465    scratch: Vec<f32>,
466    ran: Vec<bool>,
467    /// Per-group GPU timing: each group submitted on its own (see
468    /// [`Renderer::set_profiling`]).
469    profile: Option<Profiler>,
470    /// ULTRAFAST_NO_SKIP: draw every live group every time (a reference for
471    /// checking that skipped work was really redundant).
472    no_skip: bool,
473    /// ULTRAFAST_NO_FRAMED: rasterize off-frame content even when nothing reads
474    /// it (a reference for checking [`plan::Plan::framed`]).
475    no_framed: bool,
476    /// Exact renders wait for a group's fused kernel (default); without,
477    /// groups whose ops all have tier-0 kernels render op by op while it
478    /// compiles (a new look starts at once; see `set_wait_for_fused`).
479    wait_fused: bool,
480    fonts: geom::Fonts,
481    base_dir: PathBuf,
482    /// Built geometry per node: full key, content key (shape without
483    /// placement), the transform it was built under, the geometry.
484    geometry: HashMap<NodeId, (u64, u64, ops::Affine, Arc<geom::Geometry>)>,
485    /// The geometry each node last had built from scratch (key, content
486    /// key, placement), which turns and scales map instead of rebuilding.
487    built: HashMap<NodeId, (u64, u64, ops::Affine, Arc<geom::Geometry>)>,
488    bounds: HashMap<NodeId, [f32; 4]>,
489    acc: Option<Buffer>,
490    videos: HashMap<NodeId, VideoState>,
491    flat: Option<((u64, u64), Arc<ultrafast_graph::Flat>)>,
492    /// Loudness envelopes of soundtracks driving params (120 per second,
493    /// normalized), by file, band and release.
494    envelopes: HashMap<String, Option<Arc<Vec<f32>>>>,
495    /// Where swarm particles settle, by the shape they form.
496    swarm_homes: HashMap<u64, Arc<Vec<[f32; 2]>>>,
497    three: Option<Three>,
498    /// Ping-pong accumulation targets for motion blur.
499    accum: Option<(Texture, Texture)>,
500    /// Color glyph (emoji) bitmaps, created on first use.
501    glyph_atlas: Option<glyph_atlas::GlyphAtlas>,
502    diff_buf: Option<Buffer>,
503    /// Particle pipelines (over, add), the sequential index buffer, and a
504    /// white 1x1 fallback sprite.
505    sprites: Option<(
506        ultrafast_gpu::DrawPipeline,
507        ultrafast_gpu::DrawPipeline,
508        Buffer,
509        Texture,
510    )>,
511    /// Decoded video frames referenced by in-flight GPU work, by frame number.
512    retained: std::collections::VecDeque<(u64, Arc<ultrafast_media::VideoFrame>)>,
513    /// Seconds spent waiting for decoded video frames, and for images an
514    /// exact render needs (decode and upload).
515    media_wait: f64,
516    /// Media not ready for the frame being encoded (see FrameReport::media_pending).
517    media_pending: usize,
518    image_wait: f64,
519    frame_no: u64,
520    /// Simulation state by node.
521    sims: HashMap<NodeId, sim::SimState>,
522    /// Built blocks by their params and frame size.
523    blocks: HashMap<String, Arc<ultrafast_graph::Component>>,
524    /// Built caption tracks by their params and transcript file time.
525    captions: HashMap<String, Arc<ultrafast_graph::Component>>,
526    /// Built face-follow cameras by their params, face file time and format.
527    follows: HashMap<String, Arc<ultrafast_graph::Component>>,
528    /// Imported SVG files by (src, size), with the file time they were read at.
529    svgs: HashMap<String, (Option<std::time::SystemTime>, Arc<svg::Imported>)>,
530    lotties: HashMap<String, (Option<std::time::SystemTime>, Arc<lottie::Imported>)>,
531    /// The frame being rendered (motion-blur samples share it).
532    frame_t: f64,
533    /// While rendering motion-blur samples: (sample, samples, frame time,
534    /// shutter seconds).
535    mb_sample: Option<(u32, u32, f64, f64)>,
536    /// Sample everything every frame (reference renders; ULTRAFAST_MB_FULL=1).
537    mb_full: bool,
538    /// The motion-blurred frame being encoded, its sampled groups' averages,
539    /// and textures it used that go back to the pool next frame.
540    mb_frame: Option<MbFrame>,
541    mb_acc: Vec<Option<MbAccum>>,
542    mb_release: Vec<Texture>,
543    /// Motion blur turned off (a player while it plays: one sample a frame).
544    mb_off: bool,
545    /// Bytes of resident slot textures before unused ones are given back.
546    slot_budget: u64,
547    /// Frames are rendered once each, in order (an export): no seeking
548    /// back, so simulations keep no checkpoints.
549    pub(crate) sequential: bool,
550    /// The output size asked for (None: each document's own).
551    out_size: Option<(u32, u32)>,
552    /// This frame's view.
553    pub(crate) view: View,
554}
555
556/// GPU state of the 3D pass, created on first use.
557struct Three {
558    pipeline: ultrafast_gpu::DrawPipeline,
559    shadow_pipeline: ultrafast_gpu::DrawPipeline,
560    /// Light-space depth (R32F) and its depth attachment.
561    shadow_map: Texture,
562    shadow_depth: Texture,
563    /// Multisampled color and depth attachments, at frame size.
564    attachments: Option<(Texture, Texture)>,
565    /// Depth of field: camera-distance pass, its target (R32F) and depth
566    /// attachment, and the sharp image it blurs (all at frame size).
567    dist_pipeline: ultrafast_gpu::DrawPipeline,
568    dof: Option<(Texture, Texture, Texture)>,
569    white: Texture,
570    /// Vertex buffer, index buffer, index count, local bounds (min, max).
571    meshes: HashMap<String, (Buffer, Buffer, u32, [[f32; 3]; 2])>,
572}
573
574#[derive(Default)]
575struct VideoState {
576    path: String,
577    /// The file as it was when it was opened.
578    stamp: Option<images::FileStamp>,
579    source: Option<ultrafast_media::VideoSource>,
580    error: Option<String>,
581    prepared: Option<Texture>,
582    prepared_pts: Option<f64>,
583}
584
585/// Raster output textures are allocated in steps of this many pixels so
586/// small changes in bounds reuse the same texture.
587const RASTER_BUCKET: u32 = 64;
588/// Largest raster region side, in pixels.
589const MAX_RASTER: i64 = 8192;
590/// Frames of an image sequence decoded ahead of the playhead.
591const SEQUENCE_AHEAD: usize = 12;
592
593/// Where a document's media reference points: URLs (`https://...`, decoded
594/// by ffmpeg straight from the network) and absolute paths as they are,
595/// relative paths under `base`.
596pub fn media_path(base: &Path, src: &str) -> PathBuf {
597    if src.contains("://") || Path::new(src).is_absolute() {
598        PathBuf::from(src)
599    } else {
600        base.join(src)
601    }
602}
603
604impl Renderer {
605    pub fn new(device: Device) -> Result<Self, RenderError> {
606        let kernels = Kernels::new(device.clone()).map_err(RenderError::Setup)?;
607        Self::with_kernels(device, kernels)
608    }
609
610    /// A renderer whose ops' tier-0 kernels compile only when a frame first
611    /// needs one ([`Kernels::on_demand`]), for a command that renders and
612    /// exits (an export, a frame, a check): its exact renders wait for
613    /// their fused kernels anyway. On the first run after an install or an
614    /// upgrade it starts about 0.9 s sooner. [`Renderer::new`] builds them
615    /// all first, so a live session never waits on the compiler.
616    pub fn new_on_demand(device: Device) -> Result<Self, RenderError> {
617        let kernels = Kernels::on_demand(device.clone()).map_err(RenderError::Setup)?;
618        Self::with_kernels(device, kernels)
619    }
620
621    fn with_kernels(device: Device, kernels: Kernels) -> Result<Self, RenderError> {
622        let placeholder = device.create_texture(TextureDesc {
623            width: 1,
624            height: 1,
625            format: PixelFormat::Rgba16Float,
626            cpu_readable: false,
627        });
628        let r = Self {
629            device,
630            kernels,
631            active: None,
632            seen_revision: None,
633            pool: TexturePool {
634                free: HashMap::new(),
635                max_free_per_desc: 128,
636                free_bytes: 0,
637                max_free_bytes: 1 << 30,
638                clock: 0,
639                last_used: HashMap::new(),
640            },
641            images: ImageCache::new(),
642            placeholder,
643            export: None,
644            mode: Mode::Exact,
645            diagnostics: Vec::new(),
646            scratch: Vec::with_capacity(256),
647            ran: Vec::new(),
648            profile: None,
649            no_skip: std::env::var_os("ULTRAFAST_NO_SKIP").is_some(),
650            no_framed: std::env::var_os("ULTRAFAST_NO_FRAMED").is_some(),
651            wait_fused: true,
652            fonts: geom::Fonts::new(),
653            base_dir: PathBuf::from("."),
654            geometry: HashMap::new(),
655            built: HashMap::new(),
656            bounds: HashMap::new(),
657            acc: None,
658            videos: HashMap::new(),
659            flat: None,
660            envelopes: HashMap::new(),
661            swarm_homes: HashMap::new(),
662            three: None,
663            accum: None,
664            glyph_atlas: None,
665            diff_buf: None,
666            sprites: None,
667            retained: std::collections::VecDeque::new(),
668            media_wait: 0.0,
669            media_pending: 0,
670            image_wait: 0.0,
671            frame_no: 0,
672            sims: HashMap::new(),
673            svgs: HashMap::new(),
674            lotties: HashMap::new(),
675            captions: HashMap::new(),
676            follows: HashMap::new(),
677            blocks: HashMap::new(),
678            frame_t: 0.0,
679            mb_sample: None,
680            mb_full: std::env::var("ULTRAFAST_MB_FULL").is_ok(),
681            mb_frame: None,
682            mb_acc: Vec::new(),
683            mb_release: Vec::new(),
684            mb_off: false,
685            slot_budget: 0,
686            sequential: false,
687            out_size: None,
688            view: View { px: 1.0, w: 1, h: 1 },
689        };
690        // Slots may take a third of GPU memory, shared by ULTRAFAST_WORKERS
691        // processes (ULTRAFAST_SLOT_BUDGET_MB overrides).
692        let mut r = r;
693        r.slot_budget = std::env::var("ULTRAFAST_SLOT_BUDGET_MB")
694            .ok()
695            .and_then(|v| v.parse::<u64>().ok())
696            .map(|mb| mb << 20)
697            .unwrap_or_else(|| {
698                // Processes sharing the GPU (parallel export) split it.
699                let workers = std::env::var("ULTRAFAST_WORKERS")
700                    .ok()
701                    .and_then(|v| v.parse::<u64>().ok())
702                    .unwrap_or(1)
703                    .max(1);
704                r.device.memory_bytes() / 3 / workers
705            });
706        // New textures are uninitialized; clear the placeholder once.
707        let mut list = r.device.begin();
708        list.dispatch(
709            &r.kernels.utility("k_clear"),
710            &r.placeholder,
711            &[],
712            &[0.0, 0.0, 1.0, 1.0],
713        );
714        list.submit().wait()?;
715        let device = r.device.clone();
716        r.images.set_device(&device);
717        Ok(r)
718    }
719
720    /// Bytes resident group slots and kept raster textures may use before
721    /// cold ones are given back.
722    pub fn set_slot_budget(&mut self, bytes: u64) {
723        self.slot_budget = bytes;
724        self.pool.max_free_bytes = (bytes / 8).min(1 << 30);
725    }
726
727    /// Declares that frames will be rendered once each, in order (an
728    /// export), so state kept only for seeking back can be skipped.
729    pub fn set_sequential(&mut self, on: bool) {
730        self.sequential = on;
731    }
732
733    /// Lets go of everything held for the current document (plan, group
734    /// and raster textures, decoders, images, simulations, built parts)
735    /// and keeps what any document reuses: compiled kernels, pipelines and
736    /// fonts. A warm renderer serving one document after another calls this
737    /// between them, so GPU memory returns to its baseline instead of
738    /// collecting every earlier document's resources. Call with no frames
739    /// in flight.
740    /// Pins font files to their family, weight and style for what renders
741    /// next, until [`Renderer::unpin_fonts`] (see
742    /// [`geom::Fonts::pin`]): a document laid out elsewhere with those
743    /// files sets its text with them here.
744    pub fn pin_fonts(&mut self, pins: &[geom::FontPin]) -> Result<(), String> {
745        self.release_document();
746        self.fonts.pin(pins)
747    }
748
749    /// How what renders next sets the writing systems its fonts do not
750    /// cover, until [`Renderer::unpin_fonts`] (see
751    /// [`geom::Fonts::set_script_fonts`]).
752    pub fn set_script_fonts(&mut self, rows: Vec<geom::ScriptFont>) {
753        self.release_document();
754        self.fonts.set_script_fonts(rows);
755    }
756
757    /// Drops the pins of [`Renderer::pin_fonts`].
758    pub fn unpin_fonts(&mut self) {
759        self.release_document();
760        self.fonts.unpin();
761    }
762
763    /// Drops the decoded images and video decoders whose files changed on
764    /// disk since they were read (a look re-rendered into the same file, a
765    /// sheet rebuilt), and the cached results made from them, so the next
766    /// frame shows the files as they are now. Returns how many it dropped;
767    /// costs a stat per image and video held. A player calls it when a
768    /// document is (re)loaded and every so often while it is open.
769    pub fn refresh_changed_media(&mut self) -> usize {
770        let mut n = self.images.drop_changed();
771        let base = self.base_dir.clone();
772        self.videos.retain(|_, v| {
773            if v.path.is_empty() || v.path.contains("://") {
774                return true;
775            }
776            let same = images::file_stamp(&media_path(&base, &v.path)) == v.stamp;
777            n += (!same) as usize;
778            same
779        });
780        if n > 0
781            && let Some(a) = self.active.as_mut()
782        {
783            for c in a.cache.iter_mut() {
784                *c = None;
785            }
786        }
787        n
788    }
789
790    pub fn release_document(&mut self) {
791        self.active = None;
792        self.seen_revision = None;
793        self.pool.free.clear();
794        self.pool.last_used.clear();
795        self.pool.free_bytes = 0;
796        let base = self.base_dir.clone();
797        self.images = ImageCache::new();
798        self.images.set_base_dir(&base);
799        self.images.set_device(&self.device);
800        self.export = None;
801        self.geometry.clear();
802        self.built.clear();
803        self.bounds.clear();
804        self.acc = None;
805        self.videos.clear();
806        self.flat = None;
807        self.envelopes.clear();
808        self.swarm_homes.clear();
809        if let Some(three) = self.three.as_mut() {
810            three.attachments = None;
811            three.dof = None;
812            three.meshes.clear();
813        }
814        self.accum = None;
815        self.glyph_atlas = None;
816        self.diff_buf = None;
817        self.retained.clear();
818        self.sims.clear();
819        self.blocks.clear();
820        self.captions.clear();
821        self.follows.clear();
822        self.svgs.clear();
823        self.lotties.clear();
824        self.diagnostics.clear();
825    }
826
827    /// Seconds this renderer has spent waiting for decoded media and
828    /// uploading decoded images (part of the CPU time of the frames).
829    pub fn media_wait(&self) -> f64 {
830        self.media_wait + self.image_wait
831    }
832
833    /// The part of [`media_wait`](Self::media_wait) spent on images.
834    pub fn image_wait(&self) -> f64 {
835        self.image_wait
836    }
837
838    pub fn device(&self) -> &Device {
839        &self.device
840    }
841
842    /// Profiling: every group is submitted to the GPU on its own and timed,
843    /// which is slower but says what each part of a film costs. Read the
844    /// totals with [`Renderer::profile`].
845    pub fn set_profiling(&mut self, on: bool) {
846        self.profile = on.then(Profiler::default);
847    }
848
849    /// GPU time per group so far (waits for groups still running), most
850    /// expensive first.
851    pub fn profile(&mut self) -> Result<Vec<GroupCost>, RenderError> {
852        let Some(p) = &mut self.profile else {
853            return Ok(Vec::new());
854        };
855        for (label, sub) in p.pending.drain(..) {
856            let ms = sub.wait()?.gpu_ms;
857            let e = p.totals.entry(label).or_insert((0.0, 0));
858            e.0 += ms;
859            e.1 += 1;
860        }
861        let mut out: Vec<GroupCost> = p
862            .totals
863            .iter()
864            .map(|(k, &(ms, runs))| GroupCost {
865                group: k.clone(),
866                ms,
867                runs,
868            })
869            .collect();
870        out.sort_by(|a, b| b.ms.total_cmp(&a.ms));
871        Ok(out)
872    }
873
874    /// Whether to skip work that cannot change the frame (redrawing still
875    /// geometry, copying layers that only pass through). On by default;
876    /// off (or ULTRAFAST_NO_SKIP) renders a reference to check it against.
877    pub fn set_skip_redundant(&mut self, on: bool) {
878        self.no_skip = !on;
879    }
880
881    /// Renders `frames` frames from `from` seconds with every group timed
882    /// on its own: where the GPU time of `doc` goes, per frame.
883    pub fn profile_frames(&mut self, doc: &Document, frames: u64, from: f64) -> Result<ProfileReport, RenderError> {
884        // Compile the plan's kernels first so they are not timed.
885        self.submit_frame(doc, from, false)?.0.wait()?;
886        self.set_profiling(true);
887        let first = (from * doc.format.fps).round() as u64;
888        let n = doc.format.frame_count().max(1);
889        let frames = frames.max(1);
890        let mut rest = 0.0;
891        let result = (|| {
892            for i in 0..frames {
893                let (sub, _) = self.submit_frame(doc, doc.format.time_of((first + i) % n), false)?;
894                rest += sub.wait()?.gpu_ms;
895                if i % 16 == 15 {
896                    self.profile()?;
897                }
898            }
899            self.profile()
900        })();
901        self.set_profiling(false);
902        let costs = result?;
903        let f = frames as f64;
904        let total = costs.iter().map(|c| c.ms).sum::<f64>() + rest;
905        Ok(ProfileReport {
906            frames,
907            from,
908            gpu_ms_per_frame: total / f,
909            groups: costs
910                .into_iter()
911                .map(|c| GroupShare {
912                    share: c.ms / total.max(1e-9),
913                    ms_per_frame: c.ms / f,
914                    runs_per_frame: c.runs as f64 / f,
915                    group: c.group,
916                })
917                .collect(),
918            rest_ms_per_frame: rest / f,
919        })
920    }
921
922    /// Motion blur samples every group on every frame instead of only what
923    /// moves (reference renders).
924    pub fn set_full_motion_blur(&mut self, full: bool) {
925        self.mb_full = full;
926    }
927
928    /// Turns the document's motion blur on or off for the frames that
929    /// follow. A player turns it off while it plays (one render a frame
930    /// keeps playback smooth) and back on when it stops, so a still frame
931    /// shows exactly what the export will.
932    pub fn set_motion_blur(&mut self, on: bool) {
933        self.mb_off = !on;
934    }
935
936    pub fn set_mode(&mut self, mode: Mode) {
937        self.mode = mode;
938    }
939
940    /// Whether exact renders wait for fused kernels still compiling. Off,
941    /// such a group renders op by op with the tier-0 kernels (built at
942    /// startup) until its fused kernel is ready: the same image to within
943    /// half-float rounding of the intermediates, with no compile stall when
944    /// a document's structure is new (a new look on a render service).
945    /// Groups with an op that has no tier-0 kernel (custom shaders) still
946    /// wait.
947    pub fn set_wait_for_fused(&mut self, on: bool) {
948        self.wait_fused = on;
949    }
950
951    pub fn waits_for_fused(&self) -> bool {
952        self.wait_fused
953    }
954
955    pub fn mode(&self) -> Mode {
956        self.mode
957    }
958
959    /// Directory relative resource paths resolve against.
960    pub fn set_base_dir(&mut self, dir: &Path) {
961        self.base_dir = dir.to_path_buf();
962        self.images.set_base_dir(dir);
963    }
964
965    pub fn base_dir(&self) -> &Path {
966        &self.base_dir
967    }
968
969    pub fn plan(&self) -> Option<&Plan> {
970        self.active.as_ref().map(|a| &a.plan)
971    }
972
973    pub fn kernels(&self) -> &Kernels {
974        &self.kernels
975    }
976
977    pub fn diagnostics(&self) -> &[Diagnostic] {
978        &self.diagnostics
979    }
980
981    pub fn clear_diagnostics(&mut self) {
982        self.diagnostics.clear();
983    }
984
985    fn diagnose(&mut self, node: &str, message: String) {
986        let d = Diagnostic {
987            node: node.to_string(),
988            message,
989        };
990        if !self.diagnostics.contains(&d) {
991            self.diagnostics.push(d);
992        }
993    }
994
995    /// Bounds (min x, min y, max x, max y) in output pixels of a path or text
996    /// node, as of the last frame it was rasterized.
997    /// Outlines of a text node as SVG path data (pixels, placed), for
998    /// morphing letters or reusing type as vector shapes.
999    pub fn text_outline(&mut self, node: &ultrafast_graph::Node) -> Result<String, RenderError> {
1000        let fmt = ultrafast_graph::Format {
1001            width: 1,
1002            height: 1,
1003            fps: 1.0,
1004            duration: 1.0,
1005            motion_blur: None,
1006        };
1007        let mut all = kurbo::BezPath::new();
1008        for (p, _, _) in geom::text_paths(
1009            "text",
1010            node,
1011            &fmt,
1012            0.0,
1013            ops::Affine::IDENTITY,
1014            &mut self.fonts,
1015            &self.base_dir,
1016        )?
1017        .0
1018        {
1019            all.extend(p);
1020        }
1021        Ok(all.to_svg())
1022    }
1023
1024    /// Glyph-by-glyph metrics of a single-line text node (see
1025    /// [`geom::measure`]), with this renderer's fonts and base directory.
1026    pub fn measure_text(&mut self, node: &ultrafast_graph::Node) -> Result<geom::LineMetrics, RenderError> {
1027        Ok(geom::measure("text", node, 0.0, &mut self.fonts, &self.base_dir)?)
1028    }
1029
1030    pub fn node_bounds(&self, id: &str) -> Option<[f32; 4]> {
1031        self.bounds.get(id).copied()
1032    }
1033
1034    /// What is under frame point (x, y) at `t`, as last rendered: the
1035    /// smallest visible element there (text, path, shape, image, video),
1036    /// named by the document node it belongs to (a component instance or
1037    /// block for its parts) and by the part itself, with its frame bounds.
1038    pub fn pick(&self, doc: &Document, t: f64, x: f32, y: f32) -> Option<Picked> {
1039        let (px, py) = (x as f64, y as f64);
1040        self.elements(doc, t)
1041            .into_iter()
1042            .filter(|(p, _)| {
1043                let b = p.bounds;
1044                px >= b[0] as f64 && px <= b[2] as f64 && py >= b[1] as f64 && py <= b[3] as f64
1045            })
1046            .min_by(|a, b| {
1047                let area = |p: &Picked| (p.bounds[2] - p.bounds[0]) as f64 * (p.bounds[3] - p.bounds[1]) as f64;
1048                area(&a.0).total_cmp(&area(&b.0))
1049            })
1050            .map(|(p, _)| p)
1051    }
1052
1053    /// Every visible element at `t`, as last rendered (render `t` first):
1054    /// texts, paths, shapes, images and videos that are active and inside
1055    /// the frame, with their document node, bounds, and the words of text.
1056    pub fn visible(&self, doc: &Document, t: f64) -> Vec<Visible> {
1057        let (fw, fh) = (doc.format.width as f32, doc.format.height as f32);
1058        self.elements(doc, t)
1059            .into_iter()
1060            .filter(|(p, _)| p.bounds[2] > 0.0 && p.bounds[3] > 0.0 && p.bounds[0] < fw && p.bounds[1] < fh)
1061            .map(|(p, text)| Visible { element: p, text })
1062            .collect()
1063    }
1064
1065    fn elements(&self, doc: &Document, t: f64) -> Vec<(Picked, Option<String>)> {
1066        let Some(active) = self.active.as_ref() else {
1067            return Vec::new();
1068        };
1069        let plan = &active.plan;
1070        let (fw, fh) = (doc.format.width as f64, doc.format.height as f64);
1071        let flat = self.flat.as_ref().map(|(_, f)| f.clone());
1072        let node_of = |id: &str| {
1073            flat.as_ref()
1074                .and_then(|f| f.doc.nodes.get(id).cloned())
1075                .or_else(|| doc.nodes.get(id).cloned())
1076        };
1077        // What reaches the output at `t`: an inactive composite passes its
1078        // background through (a transition before its change shows only
1079        // the outgoing shot), an inactive effect its source, and nothing
1080        // shows through a zero opacity.
1081        let n = plan.nodes.len();
1082        let mut reaches = vec![false; n];
1083        let output = flat
1084            .as_ref()
1085            .map(|f| f.doc.output.clone())
1086            .unwrap_or_else(|| doc.output.clone());
1087        let mut stack: Vec<usize> = plan
1088            .nodes
1089            .iter()
1090            .position(|pn| pn.id == output)
1091            .or(n.checked_sub(1))
1092            .into_iter()
1093            .collect();
1094        while let Some(i) = stack.pop() {
1095            if reaches[i] {
1096                continue;
1097            }
1098            reaches[i] = true;
1099            let pn = &plan.nodes[i];
1100            let (lt, on) = local_time(pn, t);
1101            let num = |k: &str, d: f64| {
1102                node_of(&pn.id)
1103                    .and_then(|nd| nd.params.get(k).and_then(|p| p.eval(lt)))
1104                    .and_then(|v| v.first().copied())
1105                    .unwrap_or(d)
1106            };
1107            let ports = pn.def.ports;
1108            let port = |name: &str| {
1109                (pn.inputs.len() == ports.len())
1110                    .then(|| ports.iter().position(|p| *p == name).map(|k| pn.inputs[k]))
1111                    .flatten()
1112            };
1113            let next: Vec<usize> = match (on, pn.def.name) {
1114                (false, _) => port("bg").or(port("source")).into_iter().collect(),
1115                (true, "over" | "blend") if num("opacity", 1.0) <= 1e-3 => port("bg").into_iter().collect(),
1116                (true, "opacity") if num("opacity", 1.0) <= 1e-3 => Vec::new(),
1117                (true, "mix") if num("t", 0.5) <= 1e-3 => port("a").into_iter().collect(),
1118                (true, "mix") if num("t", 0.5) >= 1.0 - 1e-3 => port("b").into_iter().collect(),
1119                _ => pn.inputs.clone(),
1120            };
1121            stack.extend(next);
1122        }
1123        let mut out = Vec::new();
1124        for (i, pn) in plan.nodes.iter().enumerate() {
1125            let (lt, on) = local_time(pn, t);
1126            if !on || !reaches[i] {
1127                continue;
1128            }
1129            // Faded out entirely.
1130            if node_of(&pn.id)
1131                .and_then(|nd| nd.params.get("opacity").and_then(|p| p.eval(lt)))
1132                .and_then(|v| v.first().copied())
1133                .is_some_and(|o| o <= 1e-3)
1134            {
1135                continue;
1136            }
1137            let b = match self.bounds.get(&pn.id) {
1138                Some(b) if b[0] < b[2] => [b[0] as f64, b[1] as f64, b[2] as f64, b[3] as f64],
1139                Some(_) => continue,
1140                None if pn.inputs.is_empty() && matches!(pn.def.name, "shape" | "image" | "video") => {
1141                    let Some(node) = node_of(&pn.id) else { continue };
1142                    let r = ops::bounds(pn.def, &node, &doc.format, lt, &[], None);
1143                    // Whole-frame backgrounds are not things to point at.
1144                    if r[0] <= 0.0 && r[1] <= 0.0 && r[2] >= fw && r[3] >= fh {
1145                        continue;
1146                    }
1147                    r
1148                }
1149                None => continue,
1150            };
1151            let node = pn.id.split('/').next().unwrap_or(&pn.id).to_string();
1152            let text = (pn.def.name == "text")
1153                .then(|| node_of(&pn.id).map(|n| geom::display_text(&n, lt)))
1154                .flatten();
1155            let r = |v: f64| ((v * 10.0).round() / 10.0) as f32;
1156            out.push((
1157                Picked {
1158                    op: doc.nodes.get(&node).map(|n| n.op.clone()).unwrap_or_default(),
1159                    node,
1160                    part: pn.id.clone(),
1161                    bounds: [r(b[0]), r(b[1]), r(b[2]), r(b[3])],
1162                },
1163                text,
1164            ));
1165        }
1166        out
1167    }
1168
1169    /// Frame bounds of a node's vector content: its own, or the union over
1170    /// the nodes of a component instance (`id/...`), as last rendered.
1171    pub fn content_bounds(&self, id: &str) -> Option<[f32; 4]> {
1172        let prefix = format!("{id}/");
1173        self.bounds
1174            .iter()
1175            .filter(|(k, b)| (k.as_str() == id || k.starts_with(&prefix)) && b[0] < b[2])
1176            .map(|(_, b)| *b)
1177            .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])])
1178    }
1179
1180    /// Replans if the document's structure changed. Returns whether it did.
1181    /// Document with components expanded, cached per revision.
1182    fn flattened(&mut self, doc: &Document) -> Result<Arc<ultrafast_graph::Flat>, RenderError> {
1183        let key = (doc.instance, doc.revision);
1184        if let Some((k, f)) = &self.flat
1185            && *k == key
1186        {
1187            return Ok(f.clone());
1188        }
1189        // Components whose nodes expand from their params get a copy per
1190        // instance with the instance's values in, so those nodes expand
1191        // wherever they are.
1192        let specialized;
1193        let doc = match specialize::per_instance(
1194            doc,
1195            &["block", "code", "stack", "captions", "clip_camera", "svg", "lottie"],
1196        ) {
1197            Some(d) => {
1198                specialized = d;
1199                &specialized
1200            }
1201            None => doc,
1202        };
1203        let with_blocks;
1204        let doc = if uses_op(doc, &["block", "code"]) {
1205            let mut d = doc.clone();
1206            self.in_scopes(&mut d, Self::expand_blocks);
1207            if self.blocks.len() > 64 {
1208                self.blocks.clear();
1209            }
1210            with_blocks = d;
1211            &with_blocks
1212        } else {
1213            doc
1214        };
1215        let laid_out;
1216        let doc = if uses_op(doc, &["stack"]) {
1217            let base = self.base_dir.clone();
1218            let (mut d, mut problems) = if layout::used_by(doc) {
1219                layout::expand(doc, &mut self.fonts, &base)
1220            } else {
1221                (doc.clone(), Vec::new())
1222            };
1223            // Stacks inside components lay out in the component's own graph;
1224            // its input ports stand in as empty layers while they do.
1225            let inner: Vec<String> = d
1226                .components
1227                .iter()
1228                .filter(|(_, c)| c.nodes.values().any(|n| n.op == "stack"))
1229                .map(|(k, _)| k.clone())
1230                .collect();
1231            for name in inner {
1232                let c = &d.components[&name];
1233                let mut nodes = c.nodes.clone();
1234                let ports: Vec<String> = c.inputs.iter().map(|p| format!("${p}")).collect();
1235                for port in &ports {
1236                    nodes.insert(
1237                        port.clone(),
1238                        ultrafast_graph::Node {
1239                            op: "solid".into(),
1240                            params: [("color".to_string(), ultrafast_graph::Param::Text("#00000000".into()))].into(),
1241                            ..Default::default()
1242                        },
1243                    );
1244                }
1245                let scoped = Document {
1246                    version: d.version,
1247                    format: d.format,
1248                    output: c.output.clone(),
1249                    nodes,
1250                    components: Default::default(),
1251                    revision: 0,
1252                    structure_revision: 0,
1253                    instance: 0,
1254                };
1255                let (mut out, p) = layout::expand(&scoped, &mut self.fonts, &base);
1256                problems.extend(p.into_iter().map(|(n, m)| (format!("{name}/{n}"), m)));
1257                for port in &ports {
1258                    out.nodes.remove(port);
1259                }
1260                if let Some(c) = d.components.get_mut(&name) {
1261                    c.nodes = out.nodes;
1262                }
1263            }
1264            for (n, m) in problems {
1265                self.diagnose(&n, m);
1266            }
1267            laid_out = d;
1268            &laid_out
1269        } else {
1270            doc
1271        };
1272        let with_raymarch;
1273        let doc = if let Some((d, problems)) = expand_everywhere(doc, raymarch::used_by, raymarch::expand) {
1274            for (n, m) in problems {
1275                self.diagnose(&n, m);
1276            }
1277            with_raymarch = d;
1278            &with_raymarch
1279        } else {
1280            doc
1281        };
1282        let with_transitions;
1283        let doc = if let Some((d, problems)) = expand_everywhere(doc, transitions::used_by, transitions::expand) {
1284            for (n, m) in problems {
1285                self.diagnose(&n, m);
1286            }
1287            with_transitions = d;
1288            &with_transitions
1289        } else {
1290            doc
1291        };
1292        let with_captions;
1293        let doc = if uses_op(doc, &["captions"]) {
1294            let mut d = doc.clone();
1295            self.in_scopes(&mut d, Self::expand_captions);
1296            if self.captions.len() > 32 {
1297                self.captions.clear();
1298            }
1299            with_captions = d;
1300            &with_captions
1301        } else {
1302            doc
1303        };
1304        let with_follow;
1305        let doc = if uses_op(doc, &["clip_camera"]) {
1306            let mut d = doc.clone();
1307            self.in_scopes(&mut d, Self::expand_follow);
1308            if self.follows.len() > 32 {
1309                self.follows.clear();
1310            }
1311            with_follow = d;
1312            &with_follow
1313        } else {
1314            doc
1315        };
1316        let expanded;
1317        let doc = if svg::used_by(doc) {
1318            let base = self.base_dir.clone();
1319            let mut problems = Vec::new();
1320            let svgs = &mut self.svgs;
1321            expanded = svg::expand(
1322                doc,
1323                |_, node| {
1324                    let key = format!("{:?}", (node.params.get("src"), node.params.get("size")));
1325                    let src = match node.params.get("src") {
1326                        Some(ultrafast_graph::Param::Text(s)) => base.join(s),
1327                        _ => PathBuf::new(),
1328                    };
1329                    let mtime = std::fs::metadata(&src).and_then(|m| m.modified()).ok();
1330                    if let Some((m, imp)) = svgs.get(&key)
1331                        && *m == mtime
1332                    {
1333                        return Ok(imp.clone());
1334                    }
1335                    let imp = Arc::new(svg::import_node(node, &base)?);
1336                    svgs.insert(key, (mtime, imp.clone()));
1337                    Ok(imp)
1338                },
1339                |node, msg| problems.push((node.to_string(), msg)),
1340            );
1341            for (n, m) in problems {
1342                self.diagnose(&n, m);
1343            }
1344            &expanded
1345        } else {
1346            doc
1347        };
1348        let with_lottie;
1349        let doc = if lottie::used_by(doc) {
1350            let base = self.base_dir.clone();
1351            let mut problems = Vec::new();
1352            let cache = &mut self.lotties;
1353            let fonts = &mut self.fonts;
1354            with_lottie = lottie::expand(
1355                doc,
1356                |_, node| {
1357                    let key = format!("{:?}", (node.params.get("src"), node.params.get("size")));
1358                    let src = match node.params.get("src") {
1359                        Some(ultrafast_graph::Param::Text(s)) => base.join(s),
1360                        _ => PathBuf::new(),
1361                    };
1362                    let mtime = std::fs::metadata(&src).and_then(|m| m.modified()).ok();
1363                    if let Some((m, imp)) = cache.get(&key)
1364                        && *m == mtime
1365                    {
1366                        return Ok(imp.clone());
1367                    }
1368                    let imp = Arc::new(lottie::import_node(node, &base, fonts)?);
1369                    cache.insert(key, (mtime, imp.clone()));
1370                    Ok(imp)
1371                },
1372                |node, msg| problems.push((node.to_string(), msg)),
1373            );
1374            for (n, m) in problems {
1375                self.diagnose(&n, m);
1376            }
1377            &with_lottie
1378        } else {
1379            doc
1380        };
1381        let mut f = if builtins::used_by(doc) {
1382            builtins::with_builtins(doc).flatten()?
1383        } else {
1384            doc.flatten()?
1385        };
1386        self.bake_audio_drivers(&mut f.doc);
1387        if pushdown::wanted(&f.doc) {
1388            pushdown::distribute(&mut f);
1389        }
1390        let f = Arc::new(f);
1391        self.flat = Some((key, f.clone()));
1392        Ok(f)
1393    }
1394
1395    /// Runs an expansion pass on the document's own nodes and on each
1396    /// component's (`scope` names where, for the components a pass makes),
1397    /// adding what it makes to the document's components.
1398    fn in_scopes(
1399        &mut self,
1400        d: &mut Document,
1401        mut pass: impl FnMut(
1402            &mut Self,
1403            &mut BTreeMap<String, ultrafast_graph::Node>,
1404            &mut BTreeMap<String, ultrafast_graph::Component>,
1405            &ultrafast_graph::Format,
1406            &str,
1407        ),
1408    ) {
1409        let fmt = d.format;
1410        let mut made = BTreeMap::new();
1411        pass(self, &mut d.nodes, &mut made, &fmt, "");
1412        let names: Vec<String> = d.components.keys().cloned().collect();
1413        for name in names {
1414            let Some(c) = d.components.get_mut(&name) else { continue };
1415            let mut nodes = std::mem::take(&mut c.nodes);
1416            pass(self, &mut nodes, &mut made, &fmt, &format!("{name}/"));
1417            if let Some(c) = d.components.get_mut(&name) {
1418                c.nodes = nodes;
1419            }
1420        }
1421        d.components.extend(made);
1422    }
1423
1424    /// `block` and `code` nodes become components of their own.
1425    fn expand_blocks(
1426        &mut self,
1427        nodes: &mut BTreeMap<String, ultrafast_graph::Node>,
1428        made: &mut BTreeMap<String, ultrafast_graph::Component>,
1429        fmt: &ultrafast_graph::Format,
1430        scope: &str,
1431    ) {
1432        let base = self.base_dir.clone();
1433        let ids: Vec<String> = nodes
1434            .iter()
1435            .filter(|(_, n)| n.op == "block" || n.op == "code")
1436            .map(|(k, _)| k.clone())
1437            .collect();
1438        for id in ids {
1439            let node = nodes[&id].clone();
1440            let key = format!("{}|{:?}|{:?}", node.op, node.params, (fmt.width, fmt.height));
1441            let built = match self.blocks.get(&key) {
1442                Some(c) => Ok(c.clone()),
1443                None if node.op == "code" => code::build(&node, fmt, &mut self.fonts, &base).map(Arc::new),
1444                None => blocks::build(&node, fmt, &mut self.fonts, &base).map(Arc::new),
1445            };
1446            let n = nodes.get_mut(&id).unwrap();
1447            match built {
1448                Ok(c) => {
1449                    self.blocks.insert(key, c.clone());
1450                    // A block costs nothing once it has exited: it
1451                    // gets a window over its own lifetime.
1452                    if n.op == "block"
1453                        && let Some(life) = blocks::lifetime(n)
1454                    {
1455                        let tm = n.timing.get_or_insert_with(Default::default);
1456                        if !tm.has_window() && tm.loop_duration.is_none() && tm.speed > 0.0 {
1457                            tm.in_point = Some(tm.offset);
1458                            tm.out_point = Some(tm.offset + life / tm.speed);
1459                        }
1460                    }
1461                    let name = format!("{}:{scope}{id}", n.op);
1462                    made.insert(name.clone(), (*c).clone());
1463                    n.op = name;
1464                    n.params.retain(|k, _| blocks::PARAMS.contains(&k.as_str()));
1465                }
1466                Err(e) => {
1467                    self.diagnose(&format!("{scope}{id}"), e);
1468                    n.op = "solid".into();
1469                    n.params = [("color".to_string(), ultrafast_graph::Param::Text("#00000000".into()))].into();
1470                }
1471            }
1472        }
1473    }
1474
1475    /// `captions` nodes become components of word nodes.
1476    fn expand_captions(
1477        &mut self,
1478        nodes: &mut BTreeMap<String, ultrafast_graph::Node>,
1479        made: &mut BTreeMap<String, ultrafast_graph::Component>,
1480        fmt: &ultrafast_graph::Format,
1481        scope: &str,
1482    ) {
1483        let base = self.base_dir.clone();
1484        let ids: Vec<String> = nodes
1485            .iter()
1486            .filter(|(_, n)| n.op == "captions")
1487            .map(|(k, _)| k.clone())
1488            .collect();
1489        for id in ids {
1490            let node = nodes[&id].clone();
1491            let src_time = match node.params.get("src") {
1492                Some(ultrafast_graph::Param::Text(s)) => {
1493                    std::fs::metadata(base.join(s)).and_then(|m| m.modified()).ok()
1494                }
1495                _ => None,
1496            };
1497            let key = format!("{:?}|{:?}|{:?}", node.params, src_time, (fmt.width, fmt.height));
1498            let built = match self.captions.get(&key) {
1499                Some(c) => Ok(c.clone()),
1500                None => captions::words_of(&node, &base)
1501                    .and_then(|w| captions::build(&w, &node, fmt, &mut self.fonts, &base))
1502                    .map(Arc::new),
1503            };
1504            let n = nodes.get_mut(&id).unwrap();
1505            match built {
1506                Ok(c) => {
1507                    self.captions.insert(key, c.clone());
1508                    let name = format!("captions:{scope}{id}");
1509                    made.insert(name.clone(), (*c).clone());
1510                    n.op = name;
1511                    n.params.retain(|k, _| captions::PARAMS.contains(&k.as_str()));
1512                }
1513                Err(e) => {
1514                    self.diagnose(&format!("{scope}{id}"), e);
1515                    n.op = "solid".into();
1516                    n.params = [("color".to_string(), ultrafast_graph::Param::Text("#00000000".into()))].into();
1517                }
1518            }
1519        }
1520    }
1521
1522    /// A `clip_camera` node with `faces`: as given, or tracked from its
1523    /// footage (see [`autofaces`]) when it has none.
1524    fn with_faces(
1525        &mut self,
1526        node: &ultrafast_graph::Node,
1527        fmt: &ultrafast_graph::Format,
1528        base: &Path,
1529    ) -> Result<ultrafast_graph::Node, String> {
1530        use ultrafast_graph::Param;
1531        if node.params.contains_key("faces") {
1532            return Ok(node.clone());
1533        }
1534        let Some(Param::Text(src)) = node.params.get("src") else {
1535            return Err("`clip_camera` needs `src` (the source video)".into());
1536        };
1537        let num = |k: &str| {
1538            node.params
1539                .get(k)
1540                .and_then(|p| p.eval(0.0))
1541                .and_then(|v| v.first().copied())
1542        };
1543        let start = num("start").unwrap_or(0.0);
1544        let duration = num("duration").unwrap_or(fmt.duration);
1545        let path = if Path::new(src).is_absolute() {
1546            PathBuf::from(src)
1547        } else {
1548            base.join(src)
1549        };
1550        let faces = autofaces::track(&self.device, &path, start, start + duration)?;
1551        let mut node = node.clone();
1552        node.params.insert("faces".into(), Param::Text(faces.to_string()));
1553        Ok(node)
1554    }
1555
1556    /// `clip_camera` nodes become components of keyed video nodes.
1557    fn expand_follow(
1558        &mut self,
1559        nodes: &mut BTreeMap<String, ultrafast_graph::Node>,
1560        made: &mut BTreeMap<String, ultrafast_graph::Component>,
1561        fmt: &ultrafast_graph::Format,
1562        scope: &str,
1563    ) {
1564        let base = self.base_dir.clone();
1565        let ids: Vec<String> = nodes
1566            .iter()
1567            .filter(|(_, n)| n.op == "clip_camera")
1568            .map(|(k, _)| k.clone())
1569            .collect();
1570        for id in ids {
1571            let node = nodes[&id].clone();
1572            let key = format!(
1573                "{:?}|{:?}|{:?}",
1574                node.params,
1575                follow::inputs_time(&node, &base),
1576                (fmt.width, fmt.height, fmt.fps.to_bits(), fmt.duration.to_bits())
1577            );
1578            let built = match self.follows.get(&key) {
1579                Some(c) => Ok(c.clone()),
1580                None => self
1581                    .with_faces(&node, fmt, &base)
1582                    .and_then(|node| follow::build(&node, fmt, &base).map(Arc::new)),
1583            };
1584            let n = nodes.get_mut(&id).unwrap();
1585            match built {
1586                Ok(c) => {
1587                    self.follows.insert(key, c.clone());
1588                    let name = format!("clip_camera:{scope}{id}");
1589                    made.insert(name.clone(), (*c).clone());
1590                    n.op = name;
1591                    n.params.retain(|k, _| follow::PARAMS.contains(&k.as_str()));
1592                }
1593                Err(e) => {
1594                    self.diagnose(&format!("{scope}{id}"), e);
1595                    n.op = "solid".into();
1596                    n.params = [("color".to_string(), ultrafast_graph::Param::Text("#00000000".into()))].into();
1597                }
1598            }
1599        }
1600    }
1601
1602    /// Fetches the font families `doc` names that this machine lacks,
1603    /// several at once, before its first render would fetch them one by one.
1604    pub fn prefetch_fonts(&mut self, doc: &Document) {
1605        let mut names: Vec<String> = Vec::new();
1606        let mut scan = |nodes: &BTreeMap<String, ultrafast_graph::Node>| {
1607            for n in nodes.values() {
1608                for k in ["font", "em_font"] {
1609                    if let Some(ultrafast_graph::Param::Text(f)) = n.params.get(k) {
1610                        for name in f.split(',').map(|x| x.trim().trim_matches(|c| c == '"' || c == '\'')) {
1611                            if !name.is_empty() && !names.iter().any(|x| x == name) {
1612                                names.push(name.to_string());
1613                            }
1614                        }
1615                    }
1616                }
1617            }
1618        };
1619        scan(&doc.nodes);
1620        for c in doc.components.values() {
1621            scan(&c.nodes);
1622        }
1623        let missing: Vec<String> = names.into_iter().filter(|n| self.fonts.lacks(n)).collect();
1624        if !missing.is_empty() {
1625            fontfetch::prefetch(&missing);
1626        }
1627    }
1628
1629    /// Replaces audio-driven params with keyframes (60 per second) that
1630    /// follow the soundtrack's loudness in the chosen band.
1631    fn bake_audio_drivers(&mut self, doc: &mut Document) {
1632        let duration = doc.format.duration;
1633        let mut baked: Vec<(String, String, ultrafast_graph::Param)> = Vec::new();
1634        for (id, node) in &doc.nodes {
1635            for (name, p) in &node.params {
1636                let ultrafast_graph::Param::Audio { audio } = p else {
1637                    continue;
1638                };
1639                let Some(env) = self.envelope(audio) else { continue };
1640                let (lo, hi) = (
1641                    audio.range.first().copied().unwrap_or(0.0),
1642                    audio.range.get(1).copied().unwrap_or(1.0),
1643                );
1644                let n = (duration * 60.0).ceil() as usize + 1;
1645                let keys: Vec<ultrafast_graph::Key> = (0..n)
1646                    .map(|i| {
1647                        let t = i as f64 / 60.0;
1648                        let k = ((t + audio.start) * 120.0).round().max(0.0) as usize;
1649                        let v = env.get(k).copied().unwrap_or(0.0) as f64;
1650                        ultrafast_graph::Key {
1651                            t,
1652                            v: vec![lo + (hi - lo) * v],
1653                            ease: ultrafast_graph::Ease::Linear,
1654                        }
1655                    })
1656                    .collect();
1657                baked.push((
1658                    id.clone(),
1659                    name.clone(),
1660                    ultrafast_graph::Param::Animated { keys, repeat: None },
1661                ));
1662            }
1663        }
1664        for (id, name, p) in baked {
1665            doc.nodes.get_mut(&id).unwrap().params.insert(name, p);
1666        }
1667    }
1668
1669    fn envelope(&mut self, a: &ultrafast_graph::driver::AudioDriver) -> Option<Arc<Vec<f32>>> {
1670        let key = format!("{}|{}|{}", a.src, a.band, a.smooth);
1671        if let Some(e) = self.envelopes.get(&key) {
1672            return e.clone();
1673        }
1674        let path = media_path(&self.base_dir, &a.src);
1675        let env = match ultrafast_media::audio::decode(&path) {
1676            Ok(Some(pcm)) => Some(Arc::new(audio_envelope(&pcm, &a.band, a.smooth))),
1677            Ok(None) => {
1678                self.diagnose("audio", format!("{} has no audio track", path.display()));
1679                None
1680            }
1681            Err(e) => {
1682                self.diagnose("audio", format!("{}: {e}", path.display()));
1683                None
1684            }
1685        };
1686        self.envelopes.insert(key, env.clone());
1687        env
1688    }
1689
1690    fn ensure_plan(&mut self, doc: &Document, chains: Option<&plan::Chains>) -> Result<bool, RenderError> {
1691        self.view = View::sized(doc, self.out_size);
1692        let view = self.view;
1693        let same_view = self.active.as_ref().is_some_and(|a| a.view == view);
1694        if !same_view {
1695            // Geometry built for another density is not mapped to this one
1696            // (outlines are flattened and glyphs drawn for their size): a
1697            // size renders the same however the renderer got to it.
1698            self.geometry.clear();
1699            self.built.clear();
1700        }
1701        if same_view && self.seen_revision == Some((doc.instance, doc.revision)) {
1702            return Ok(false);
1703        }
1704        self.seen_revision = Some((doc.instance, doc.revision));
1705        let sig = plan::signature(doc, chains);
1706        if same_view && self.active.as_ref().is_some_and(|a| a.plan.signature == sig) {
1707            return Ok(false);
1708        }
1709        let plan = plan::compile(doc, chains)?;
1710        // Per-node caches of nodes that no longer exist are dropped.
1711        self.geometry.retain(|id, _| doc.nodes.contains_key(id));
1712        self.built.retain(|id, _| doc.nodes.contains_key(id));
1713        self.bounds.retain(|id, _| doc.nodes.contains_key(id));
1714        if let Some(three) = self.three.as_mut()
1715            && three.meshes.len() > 64
1716        {
1717            three.meshes.clear();
1718        }
1719        // Video decoders of nodes that no longer exist are dropped.
1720        self.videos
1721            .retain(|id, _| doc.nodes.get(id).is_some_and(|n| n.op == "video"));
1722        // Queue every fused kernel this plan needs; known ones are no-ops.
1723        let jobs: Vec<(String, String)> = plan
1724            .groups
1725            .iter()
1726            .filter(|g| g.kind == GroupKind::Fused || (g.kind == GroupKind::Sim && !g.key.is_empty()))
1727            .map(|g| (g.key.clone(), g.body.clone()))
1728            .collect();
1729        self.kernels.request(jobs);
1730        for g in &plan.groups {
1731            for t in &g.textures {
1732                if let TexSource::Resource(src) = t
1733                    && let Some(path) = src.strip_prefix("image:").or_else(|| src.strip_prefix("lut:"))
1734                {
1735                    // Sequences are requested per frame.
1736                    if !path.contains("{frame") {
1737                        self.images.request(path);
1738                    }
1739                }
1740            }
1741        }
1742        if let Some(old) = self.active.take() {
1743            for (t, r) in old.slots.into_iter().zip(old.resident) {
1744                if r {
1745                    self.pool.give_back(t);
1746                }
1747            }
1748            for (p, b) in old.raster.into_iter().zip(old.borrowed) {
1749                if let (Some(p), false) = (p, b) {
1750                    self.pool.give_back(p.tex);
1751                }
1752            }
1753        }
1754        let desc = TextureDesc {
1755            width: view.w,
1756            height: view.h,
1757            format: PixelFormat::Rgba16Float,
1758            cpu_readable: false,
1759        };
1760        let mut slot_groups = vec![Vec::new(); plan.slot_count];
1761        for (gi, g) in plan.groups.iter().enumerate() {
1762            if let Some(s) = slot_groups.get_mut(g.output) {
1763                s.push(gi);
1764            }
1765        }
1766        let n = plan.groups.len();
1767        let low = low_readers(&plan);
1768        self.active = Some(Active {
1769            slots: vec![self.placeholder.clone(); plan.slot_count],
1770            resident: vec![false; plan.slot_count],
1771            slot_used: vec![0; plan.slot_count],
1772            slot_groups,
1773            slot_desc: desc,
1774            view,
1775            group_used: vec![0; n],
1776            plan,
1777            cache: vec![None; n],
1778            raster: vec![None; n],
1779            drawn: vec![0; n],
1780            alias: vec![None; n],
1781            borrowed: vec![false; n],
1782            bounds: vec![ops::UNBOUNDED; n],
1783            low_readers: low,
1784        });
1785        Ok(true)
1786    }
1787
1788    /// Renders the frames that follow at `size` (device pixels) instead of
1789    /// each document's own size; None goes back to that. The document stays
1790    /// in its own frame pixels: a 1920x1080 document at 3840x2160 is drawn
1791    /// with twice the texels (text, paths, blurs, particles, 3D re-rendered
1792    /// at the finer grid), not scaled up. A size of another shape keeps the
1793    /// finer of the two scales and crops the last texel row or column.
1794    pub fn set_output_size(&mut self, size: Option<(u32, u32)>) {
1795        self.out_size = size;
1796    }
1797
1798    /// The output size asked for (None: each document's own).
1799    pub fn output_size(&self) -> Option<(u32, u32)> {
1800        self.out_size
1801    }
1802
1803    /// The size frames of `doc` render at, in device pixels.
1804    pub fn frame_size(&self, doc: &Document) -> (u32, u32) {
1805        let v = View::sized(doc, self.out_size);
1806        (v.w, v.h)
1807    }
1808
1809    fn export_texture(&mut self, w: u32, h: u32, format: PixelFormat) -> Texture {
1810        let desc = TextureDesc {
1811            width: w,
1812            height: h,
1813            format,
1814            cpu_readable: true,
1815        };
1816        match &self.export {
1817            Some(t) if t.desc() == desc => t.clone(),
1818            _ => {
1819                let t = self.device.create_texture(desc);
1820                self.export = Some(t.clone());
1821                t
1822            }
1823        }
1824    }
1825
1826    /// Encodes and submits frame `t` (seconds). With `export`, the final image
1827    /// is also encoded to sRGB RGBA8 in a CPU-readable texture for
1828    /// [`Renderer::read_export`]. Does not wait for the GPU.
1829    pub fn submit_frame(
1830        &mut self,
1831        doc: &Document,
1832        t: f64,
1833        export: bool,
1834    ) -> Result<(Submitted, FrameReport), RenderError> {
1835        if !export {
1836            return self.submit_frame_with(doc, t, |_| {});
1837        }
1838        let (w, h) = self.frame_size(doc);
1839        let ex = self.export_texture(w, h, PixelFormat::Rgba8Unorm);
1840        self.submit_frame_with(doc, t, |o| {
1841            let mut p = o.header.to_vec();
1842            p.extend(o.origin);
1843            p.push(0.0);
1844            o.list
1845                .dispatch(&o.kernels.utility("k_encode_srgb8"), &ex, &[o.texture], &p);
1846        })
1847    }
1848
1849    /// Encodes frame `t`, then lets `finish` add work that consumes the
1850    /// final image (export, display, video encode) before submitting.
1851    pub fn submit_frame_with(
1852        &mut self,
1853        doc: &Document,
1854        t: f64,
1855        finish: impl FnOnce(FrameOutput),
1856    ) -> Result<(Submitted, FrameReport), RenderError> {
1857        let start = Instant::now();
1858        let flat = if needs_flat(doc) {
1859            Some(self.flattened(doc)?)
1860        } else {
1861            None
1862        };
1863        let doc: &Document = flat.as_ref().map(|f| &f.doc).unwrap_or(doc);
1864        let chains = flat.as_ref().map(|f| &f.chains);
1865        let replanned = self.ensure_plan(doc, chains)?;
1866        let plan_ms = start.elapsed().as_secs_f64() * 1000.0;
1867        let mut report = FrameReport {
1868            replanned,
1869            plan_ms,
1870            ..Default::default()
1871        };
1872        self.media_pending = 0;
1873        // Under memory pressure (zooming layers replace big textures every
1874        // frame), finish the frames in flight and let go of what they and
1875        // the pool hold before starting another.
1876        if self.device.memory_in_use() > self.device.memory_bytes() / 10 * 7 {
1877            self.pool.free.clear();
1878            self.pool.last_used.clear();
1879            self.pool.free_bytes = 0;
1880            self.device.reclaim();
1881        }
1882        let mut list = self.device.begin();
1883        for tex in std::mem::take(&mut self.mb_release) {
1884            self.pool.give_back(tex);
1885        }
1886        // Frames older than the in-flight window are no longer read by the GPU.
1887        self.frame_no += 1;
1888        while self.retained.front().is_some_and(|(n, _)| *n + 4 < self.frame_no) {
1889            self.retained.pop_front();
1890        }
1891        self.prepare_images(&mut list);
1892
1893        let mut active = self.active.take().expect("plan");
1894        self.trim_slots(&mut active);
1895        self.frame_t = t;
1896        let result = self
1897            .sim_catch_up(&mut active, doc, t, &mut list, &mut report)
1898            .and_then(
1899                |_| match doc.format.motion_blur.filter(|m| m.samples > 1 && !self.mb_off) {
1900                    None => self.encode_groups(&mut active, doc, t, &mut list, &mut report),
1901                    Some(mb) => self.encode_motion_blur(&mut active, doc, t, mb, &mut list, &mut report),
1902                },
1903            );
1904        self.active = Some(active);
1905        let output = result?;
1906        // Consumers get the frame in device texels: the texture at the
1907        // view's density, its origin and the header's size in texels.
1908        let output = self.on_device_grid(output, doc, t, &mut list);
1909        let v = self.view;
1910        finish(FrameOutput {
1911            list: &mut list,
1912            kernels: &self.kernels,
1913            texture: &output.tex,
1914            origin: [output.origin[0] / v.px, output.origin[1] / v.px],
1915            header: [t as f32, 1.0, v.w as f32, v.h as f32],
1916        });
1917        report.cpu_encode_ms = start.elapsed().as_secs_f64() * 1000.0;
1918        report.media_pending = self.media_pending;
1919        self.images.end_frame();
1920        Ok((list.submit(), report))
1921    }
1922
1923    /// `p` at the view's density: as it is when it already is, else
1924    /// resampled into a frame-sized texture (given back next frame).
1925    fn on_device_grid(&mut self, p: Placed, doc: &Document, t: f64, list: &mut CommandList) -> Placed {
1926        let v = self.view;
1927        let aligned = |o: f32| (o / v.px - (o / v.px).round()).abs() < 1e-3;
1928        if p.scale == v.px && aligned(p.origin[0]) && aligned(p.origin[1]) {
1929            return p;
1930        }
1931        let desc = TextureDesc {
1932            width: v.w,
1933            height: v.h,
1934            format: PixelFormat::Rgba16Float,
1935            cpu_readable: false,
1936        };
1937        let tex = self.pool.lease(&self.device, desc);
1938        let taps = (v.px / p.scale).ceil().max(1.0);
1939        let mut prm = header(doc, t, v).to_vec();
1940        prm.extend([v.px, 0.0, 0.0, p.origin[0], p.origin[1], p.scale, taps]);
1941        list.dispatch(&self.kernels.utility("k_resample"), &tex, &[&p.tex], &prm);
1942        self.mb_release.push(tex.clone());
1943        Placed {
1944            tex,
1945            origin: [0.0, 0.0],
1946            scale: v.px,
1947        }
1948    }
1949
1950    /// Keeps frame-to-frame GPU memory under the budget: while resident
1951    /// slots and kept raster textures exceed it, the ones no frame needed
1952    /// lately are given back, oldest first. Their groups' caches are dropped,
1953    /// so they render again when next needed.
1954    fn trim_slots(&mut self, active: &mut Active) {
1955        let slot_bytes = tex_bytes(active.slot_desc);
1956        // (last used, slot or group, bytes)
1957        let mut held = 0u64;
1958        let mut cold: Vec<(u64, Result<usize, usize>, u64)> = Vec::new();
1959        for s in 0..active.slots.len() {
1960            if active.resident[s] {
1961                held += slot_bytes;
1962                if active.slot_used[s] + 1 < self.frame_no {
1963                    cold.push((active.slot_used[s], Ok(s), slot_bytes));
1964                }
1965            }
1966        }
1967        for g in 0..active.raster.len() {
1968            if let (Some(p), false) = (&active.raster[g], active.borrowed[g]) {
1969                let b = tex_bytes(p.tex.desc());
1970                held += b;
1971                if active.group_used[g] + 1 < self.frame_no {
1972                    cold.push((active.group_used[g], Err(g), b));
1973                }
1974            }
1975        }
1976        if std::env::var_os("ULTRAFAST_DEBUG_MEM").is_some()
1977            && self.frame_no
1978                % std::env::var("ULTRAFAST_DEBUG_MEM")
1979                    .ok()
1980                    .and_then(|v| v.parse().ok())
1981                    .filter(|&n: &u64| n > 1)
1982                    .unwrap_or(30)
1983                == 0
1984        {
1985            eprintln!(
1986                "mem: frame {}: slots+rasters {} MiB (budget {} MiB, {} cold), pool {} MiB, acc {} MiB, sims {}, images {} MiB, allocated {}/{} MiB, device {} MiB, rss {} MiB",
1987                self.frame_no,
1988                held >> 20,
1989                self.slot_budget >> 20,
1990                cold.len(),
1991                self.pool.free_bytes >> 20,
1992                self.acc.as_ref().map_or(0, |b| b.len()) >> 20,
1993                self.sims.len(),
1994                self.images.bytes() >> 20,
1995                self.device.memory_allocated().0 >> 20,
1996                self.device.memory_allocated().1 >> 20,
1997                self.device.memory_in_use() >> 20,
1998                std::fs::read_to_string("/proc/self/statm")
1999                    .ok()
2000                    .and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
2001                    .map_or(0, |pages| pages * 4096 >> 20)
2002            );
2003            if self.frame_no % 10 == 0 {
2004                eprintln!("mem:   {}", self.device.memory_breakdown(8));
2005            }
2006        }
2007        if held <= self.slot_budget {
2008            return;
2009        }
2010        cold.sort_by_key(|c| c.0);
2011        for (_, which, bytes) in cold {
2012            if held <= self.slot_budget {
2013                break;
2014            }
2015            held -= bytes;
2016            // Dropped, not pooled: the point is to free the memory.
2017            match which {
2018                Ok(s) => {
2019                    drop(std::mem::replace(&mut active.slots[s], self.placeholder.clone()));
2020                    active.resident[s] = false;
2021                    for &g in &active.slot_groups[s] {
2022                        active.cache[g] = None;
2023                    }
2024                }
2025                Err(g) => {
2026                    drop(active.raster[g].take());
2027                    active.drawn[g] = 0;
2028                }
2029            }
2030        }
2031    }
2032
2033    /// Uploads newly decoded images and converts them to the working space.
2034    fn prepare_images(&mut self, list: &mut CommandList) {
2035        let block = self.mode == Mode::Exact;
2036        let t0 = Instant::now();
2037        let fresh = self.images.poll(&self.device, block);
2038        self.image_wait += t0.elapsed().as_secs_f64();
2039        if fresh.is_empty() {
2040            return;
2041        }
2042        let prep = self.kernels.utility("k_prep_srgb8");
2043        for (src, raw) in fresh {
2044            let d = raw.desc();
2045            let tex = self.device.create_texture(TextureDesc {
2046                width: d.width,
2047                height: d.height,
2048                format: PixelFormat::Rgba16Float,
2049                cpu_readable: false,
2050            });
2051            list.dispatch(&prep, &tex, &[&raw], &[0.0, 0.0, d.width as f32, d.height as f32, 0.0]);
2052            self.images.mark_ready(&src, tex);
2053        }
2054    }
2055
2056    fn resource(
2057        &mut self,
2058        key: &str,
2059        node: &str,
2060        doc: &Document,
2061        t: f64,
2062        list: &mut CommandList,
2063    ) -> (Texture, Option<ResourceInfo>) {
2064        if let Some(rest) = key.strip_prefix("video:") {
2065            let path = rest.split('\u{1f}').next().unwrap_or(rest);
2066            return self.video_frame(path, node, doc, t, list);
2067        }
2068        let raw = key
2069            .strip_prefix("image:")
2070            .or_else(|| key.strip_prefix("lut:"))
2071            .unwrap_or(key);
2072        // A sequence's key carries its node id after a unit separator.
2073        let raw = raw.split('\u{1f}').next().unwrap_or(raw);
2074        // Image sequences resolve to this frame's file.
2075        let resolved;
2076        let src = if raw.contains("{frame") && !node.is_empty() {
2077            resolved = ops::sequence_path(raw, &doc.nodes[node], t, doc.format.fps);
2078            self.images.request(&resolved);
2079            // The next frames decode on other threads while this one renders.
2080            for i in 1..=SEQUENCE_AHEAD {
2081                let next = ops::sequence_path(raw, &doc.nodes[node], t + i as f64 / doc.format.fps, doc.format.fps);
2082                if next != resolved {
2083                    self.images.prefetch(&next);
2084                }
2085            }
2086            if self.mode == Mode::Exact {
2087                self.prepare_images(list);
2088            }
2089            resolved.as_str()
2090        } else {
2091            // Still images are requested when the plan is built, but the LRU
2092            // may drop one before its first use (a cutout sequence filling
2093            // the cache while the image waits for its window): ask again,
2094            // or it stays a placeholder for the rest of an export.
2095            if !self.images.is_known(raw) {
2096                self.images.request(raw);
2097                if self.mode == Mode::Exact {
2098                    self.prepare_images(list);
2099                }
2100            }
2101            raw
2102        };
2103        match self.images.get(src) {
2104            Some(images::ImageState::Ready(t)) => {
2105                let d = t.desc();
2106                (
2107                    t.clone(),
2108                    Some(ResourceInfo {
2109                        width: d.width,
2110                        height: d.height,
2111                    }),
2112                )
2113            }
2114            Some(images::ImageState::Failed(e)) => {
2115                let e = e.clone();
2116                self.diagnose(node, e);
2117                (self.placeholder.clone(), None)
2118            }
2119            _ => {
2120                self.media_pending += 1;
2121                (self.placeholder.clone(), None)
2122            }
2123        }
2124    }
2125
2126    /// The current frame of a `video` node, converted to the working space.
2127    /// Decoded frames arrive zero-copy from the hardware decoder (or as the
2128    /// decoder's bytes in GPU-visible memory); one pass per new source
2129    /// frame converts, turns upright and linearizes them into a node-owned
2130    /// texture.
2131    fn video_frame(
2132        &mut self,
2133        path: &str,
2134        node: &str,
2135        doc: &Document,
2136        t: f64,
2137        list: &mut CommandList,
2138    ) -> (Texture, Option<ResourceInfo>) {
2139        let state = self.videos.entry(node.to_string()).or_default();
2140        if state.path != path {
2141            let full = media_path(&self.base_dir, path);
2142            *state = VideoState {
2143                path: path.to_string(),
2144                stamp: images::file_stamp(&full),
2145                ..Default::default()
2146            };
2147            match ultrafast_media::VideoSource::open(&self.device, &full) {
2148                Ok(s) => state.source = Some(s),
2149                Err(e) => state.error = Some(e.to_string()),
2150            }
2151        }
2152        if let Some(e) = state.error.clone() {
2153            self.diagnose(node, e);
2154            return (self.placeholder.clone(), None);
2155        }
2156        let source = state.source.as_ref().unwrap();
2157        let info = ResourceInfo {
2158            width: source.info.width,
2159            height: source.info.height,
2160        };
2161        let tau = ops::video_time(&doc.nodes[node], t, source.info.duration);
2162        let waited = source.waited();
2163        let frame = source.frame_at(tau, self.mode == Mode::Exact);
2164        self.media_wait += source.waited() - waited;
2165        let frame = match frame {
2166            Ok(f) => f,
2167            Err(e) => {
2168                state.error = Some(e.to_string());
2169                self.diagnose(node, e.to_string());
2170                return (self.placeholder.clone(), None);
2171            }
2172        };
2173        let Some(frame) = frame else {
2174            self.media_pending += 1;
2175            return match &state.prepared {
2176                Some(p) => (p.clone(), Some(info)),
2177                None => (self.placeholder.clone(), Some(info)),
2178            };
2179        };
2180        if state.prepared.is_none() || state.prepared_pts != Some(frame.pts) {
2181            let tex = state
2182                .prepared
2183                .get_or_insert_with(|| {
2184                    self.device.create_texture(TextureDesc {
2185                        width: info.width,
2186                        height: info.height,
2187                        format: PixelFormat::Rgba16Float,
2188                        cpu_readable: false,
2189                    })
2190                })
2191                .clone();
2192            let mut p = vec![0.0, 0.0, info.width as f32, info.height as f32];
2193            p.extend(source.format.params(source.info.rotation));
2194            let kernel = self.kernels.utility("k_prep_video");
2195            #[cfg(all(target_os = "macos", not(feature = "vulkan")))]
2196            let (input, data) = (frame.texture(), BufferBinding::Data(&[0u8; 16]));
2197            #[cfg(not(all(target_os = "macos", not(feature = "vulkan"))))]
2198            let (input, data) = (&self.placeholder, BufferBinding::Buffer(frame.buffer()));
2199            list.dispatch_ex(
2200                &kernel,
2201                &tex,
2202                &[input],
2203                &p,
2204                Bindings {
2205                    buffers: &[data],
2206                    ..Default::default()
2207                },
2208            );
2209            state.prepared_pts = Some(frame.pts);
2210            // The decoded frame must outlive the GPU work reading it.
2211            self.retained.push_back((self.frame_no, frame));
2212        }
2213        (state.prepared.clone().unwrap(), Some(info))
2214    }
2215
2216    /// Renders `mb.samples` sub-frames across the shutter (more where
2217    /// things move fast, up to `mb.max_samples`) and averages them layer by
2218    /// layer, as a compositor blurs each moving layer. Every
2219    /// group runs in one phase: groups that read nothing moving run once, at
2220    /// the frame's time, first (phase 0); groups holding a moving layer run
2221    /// per sample, in waves (odd phases), chained to the sampled groups of
2222    /// their wave they read; a sampled group read by a later phase is
2223    /// averaged across the samples, and the groups that read it run once,
2224    /// after its wave (even phases), on that average. A frame where nothing
2225    /// moves renders once.
2226    fn encode_motion_blur(
2227        &mut self,
2228        active: &mut Active,
2229        doc: &Document,
2230        t: f64,
2231        mb: ultrafast_graph::MotionBlur,
2232        list: &mut CommandList,
2233        report: &mut FrameReport,
2234    ) -> Result<Placed, RenderError> {
2235        let span = mb.shutter / doc.format.fps;
2236        let moving = if self.mb_full {
2237            vec![true; active.plan.nodes.len()]
2238        } else {
2239            self.moving_nodes(&active.plan, doc, t - span / 2.0, t + span / 2.0)
2240        };
2241        let n = match mb.max_samples {
2242            Some(max) if max > mb.samples => {
2243                // Motion measured in device texels: a larger view takes more
2244                // samples for the same move, so it blurs as smoothly.
2245                mb.samples_for(
2246                    self.motion_extent_px(&active.plan, doc, &moving, t - span / 2.0, t + span / 2.0)
2247                        / self.view.px as f64,
2248                )
2249            }
2250            _ => mb.samples,
2251        };
2252        let plan = &active.plan;
2253        let ng = plan.groups.len();
2254        // What reaches the output at any time in the shutter (a cut inside
2255        // it shows the shot before it in the first samples).
2256        let mut live = live_groups(plan, t);
2257        for s in 0..n {
2258            let ts = t - span / 2.0 + span * (s as f64 + 0.5) / n as f64;
2259            for (l, m) in live.iter_mut().zip(live_groups(plan, ts)) {
2260                *l |= m;
2261            }
2262        }
2263        let here: Vec<bool> = plan.groups.iter().map(|g| g.nodes.iter().any(|&m| moving[m])).collect();
2264        // Phases in plan order (inputs come first). A group that reads
2265        // nothing moving: 0. One holding a moving node: odd, the wave of the
2266        // sampled groups it reads, or the next one after anything else it
2267        // reads (whose sampled inputs it then reads as averages). Any other
2268        // group reading something moving: even, after what it reads.
2269        let mut phase = vec![0u32; ng];
2270        let mut affected = vec![false; ng];
2271        for g in 0..ng {
2272            let mut p = 0u32;
2273            for ts in &plan.groups[g].textures {
2274                let TexSource::Group(i) = *ts else { continue };
2275                if !affected[i] {
2276                    continue;
2277                }
2278                let sampled_i = phase[i] % 2 == 1;
2279                p = p.max(match (here[g], sampled_i) {
2280                    (true, true) | (false, false) => phase[i],
2281                    _ => phase[i] + 1,
2282                });
2283            }
2284            affected[g] = here[g] || p > 0;
2285            phase[g] = match (affected[g], here[g]) {
2286                (false, _) => 0,
2287                (true, true) => p.max(1) | 1,
2288                (true, false) => p.max(2),
2289            };
2290        }
2291        let sampled: Vec<bool> = phase.iter().map(|p| p % 2 == 1).collect();
2292        if !(0..ng).any(|g| sampled[g] && live[g]) {
2293            report.mb_samples = 1;
2294            return self.encode_groups(active, doc, t, list, report);
2295        }
2296        let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); ng];
2297        for (c, gr) in plan.groups.iter().enumerate() {
2298            for ts in &gr.textures {
2299                if let TexSource::Group(s) = *ts {
2300                    consumers[s].push(c);
2301                }
2302            }
2303        }
2304        // Read by a later phase: what it makes must last until then.
2305        let crosses: Vec<bool> = (0..ng)
2306            .map(|g| consumers[g].iter().any(|&c| phase[c] > phase[g]))
2307            .collect();
2308        // A group that runs once and crosses, with a slot that another
2309        // group writes while it is still needed, renders into a texture of
2310        // its own this frame.
2311        let writes_slot = |k: usize| {
2312            matches!(
2313                plan.groups[k].kind,
2314                GroupKind::Fused | GroupKind::Render3D | GroupKind::Sim
2315            )
2316        };
2317        let pinned: Vec<usize> = (0..ng)
2318            .filter(|&g| {
2319                let gr = &plan.groups[g];
2320                !sampled[g]
2321                    && crosses[g]
2322                    && live[g]
2323                    && gr.kind == GroupKind::Fused
2324                    && !gr.is_static
2325                    && (0..ng).any(|k| {
2326                        k != g
2327                            && writes_slot(k)
2328                            && plan.groups[k].output == gr.output
2329                            && (phase[k] > phase[g] || (phase[k] == phase[g] && k > g))
2330                    })
2331            })
2332            .collect();
2333        report.mb_samples = n;
2334        report.mb_split = (0..ng).rev().find(|&g| sampled[g] && live[g]).unwrap_or(0);
2335        report.mb_once = (0..ng).filter(|&g| !sampled[g] && live[g]).count();
2336        if std::env::var_os("ULTRAFAST_DEBUG_MB").is_some() {
2337            let names: Vec<&str> = moving
2338                .iter()
2339                .enumerate()
2340                .filter(|(_, m)| **m)
2341                .map(|(i, _)| plan.nodes[i].id.as_str())
2342                .collect();
2343            let per: Vec<String> = (0..ng)
2344                .filter(|&g| sampled[g] && live[g])
2345                .map(|g| format!("g{g}@{}", phase[g]))
2346                .collect();
2347            eprintln!(
2348                "t={t:.3} {} once ({} pinned), sampled {}; moving: {}",
2349                report.mb_once,
2350                pinned.len(),
2351                per.join(" "),
2352                names.join(" ")
2353            );
2354        }
2355        for &g in &pinned {
2356            let tex = self.pool.lease(&self.device, active.slot_desc);
2357            active.raster[g] = Some(Placed {
2358                tex,
2359                origin: [0.0, 0.0],
2360                scale: active.view.px,
2361            });
2362        }
2363        self.mb_frame = Some(MbFrame { crosses, span });
2364        let mut installed = Vec::new();
2365        let out = self.motion_blur_phases(active, doc, t, n, span, &phase, &live, &mut installed, list, report);
2366        self.mb_frame = None;
2367        self.mb_sample = None;
2368        self.mb_acc.clear();
2369        // Pinned textures and averages are this frame's only; they go back
2370        // to the pool once the next frame is under way.
2371        for g in pinned.into_iter().chain(installed) {
2372            if let Some(p) = active.raster[g].take() {
2373                self.mb_release.push(p.tex);
2374            }
2375        }
2376        out
2377    }
2378
2379    /// The phases of a motion-blurred frame, in order. Returns the output.
2380    #[allow(clippy::too_many_arguments)]
2381    fn motion_blur_phases(
2382        &mut self,
2383        active: &mut Active,
2384        doc: &Document,
2385        t: f64,
2386        n: u32,
2387        span: f64,
2388        phase: &[u32],
2389        live: &[bool],
2390        installed: &mut Vec<usize>,
2391        list: &mut CommandList,
2392        report: &mut FrameReport,
2393    ) -> Result<Placed, RenderError> {
2394        let ng = active.plan.groups.len();
2395        let crosses = self.mb_frame.as_ref().map(|f| f.crosses.clone()).unwrap_or_default();
2396        let last = phase.iter().copied().max().unwrap_or(0);
2397        for p in 0..=last {
2398            if p % 2 == 0 {
2399                let only: Vec<bool> = (0..ng).map(|g| phase[g] == p && live[g]).collect();
2400                if only.iter().any(|&o| o) {
2401                    let pass = Pass {
2402                        only: Some(&only),
2403                        keep_bounds: p > 0,
2404                        ..Default::default()
2405                    };
2406                    self.encode_groups_masked(active, doc, t, list, report, pass)?;
2407                }
2408                continue;
2409            }
2410            // A wave: its groups per sample; those a later phase reads (and
2411            // the output) are averaged.
2412            self.mb_acc.clear();
2413            self.mb_acc.resize_with(ng, || None);
2414            for g in 0..ng {
2415                if phase[g] == p && (crosses[g] || g == ng - 1) {
2416                    self.mb_acc[g] = Some(MbAccum::default());
2417                }
2418            }
2419            // Every sample renders the wave's groups, including those not
2420            // reaching the output at that instant (a cut in the shutter): an
2421            // average is of the layer itself, and what reads it shows or
2422            // hides it in its own samples.
2423            let only: Vec<bool> = (0..ng).map(|g| phase[g] == p && live[g]).collect();
2424            for s in 0..n {
2425                let ts = t - span / 2.0 + span * (s as f64 + 0.5) / n as f64;
2426                self.mb_sample = Some((s, n, t, span));
2427                let pass = Pass {
2428                    only: Some(&only),
2429                    keep_bounds: true,
2430                    ..Default::default()
2431                };
2432                let r = self.encode_groups_masked(active, doc, ts, list, report, pass);
2433                self.mb_sample = None;
2434                r?;
2435            }
2436            for g in 0..ng {
2437                if let Some(acc) = self.mb_acc[g].take() {
2438                    self.mb_install(active, g, acc, n, t, list, installed);
2439                }
2440            }
2441        }
2442        Ok(placed_output(active, ng - 1))
2443    }
2444
2445    /// Adds the output of sampled group `gi` (as its readers see it now) to
2446    /// its average: a running sum when frame-sized, else a copy of each
2447    /// sample, summed over their union once the wave is done.
2448    fn mb_collect(&mut self, gi: usize, out: Placed, bounds: ops::Rect, doc: &Document, list: &mut CommandList) {
2449        let Some((_, n, t, _)) = self.mb_sample else {
2450            return;
2451        };
2452        let Some(mut acc) = self.mb_acc.get_mut(gi).and_then(Option::take) else {
2453            return;
2454        };
2455        acc.bounds = [
2456            acc.bounds[0].min(bounds[0]),
2457            acc.bounds[1].min(bounds[1]),
2458            acc.bounds[2].max(bounds[2]),
2459            acc.bounds[3].max(bounds[3]),
2460        ];
2461        let frame = TextureDesc {
2462            width: self.view.w,
2463            height: self.view.h,
2464            format: PixelFormat::Rgba16Float,
2465            cpu_readable: false,
2466        };
2467        // Large outputs (a frame-sized slot, particles all over) go into a
2468        // frame-sized running sum; small ones (a word) are copied and summed
2469        // over their union at the end.
2470        let d = out.tex.desc();
2471        let large = d.width as u64 * d.height as u64 * 4 >= frame.width as u64 * frame.height as u64;
2472        if acc.sum.is_some() || (large && acc.stash.is_empty()) {
2473            let first = acc.sum.is_none();
2474            let (sum, spare) = acc.sum.take().unwrap_or_else(|| {
2475                (
2476                    self.pool.lease(&self.device, frame),
2477                    self.pool.lease(&self.device, frame),
2478                )
2479            });
2480            let mut p = header(doc, t, self.view).to_vec();
2481            p.extend([out.origin[0], out.origin[1], 1.0 / n as f32, first as u8 as f32]);
2482            list.dispatch(&self.kernels.utility("k_accumulate"), &spare, &[&out.tex, &sum], &p);
2483            acc.sum = Some((spare, sum));
2484        } else {
2485            let tex = self.pool.lease(&self.device, d);
2486            let p = [t as f32, 1.0, d.width as f32, d.height as f32];
2487            list.dispatch(&self.kernels.utility("k_copy"), &tex, &[&out.tex], &p);
2488            acc.stash.push(Placed {
2489                tex,
2490                origin: out.origin,
2491                scale: out.scale,
2492            });
2493        }
2494        self.mb_acc[gi] = Some(acc);
2495    }
2496
2497    /// Makes a wave's average of group `g` its output for the rest of the
2498    /// frame only (`installed`: next frame draws the group afresh, in a
2499    /// texture of its own size).
2500    #[allow(clippy::too_many_arguments)]
2501    fn mb_install(
2502        &mut self,
2503        active: &mut Active,
2504        g: usize,
2505        acc: MbAccum,
2506        n: u32,
2507        t: f64,
2508        list: &mut CommandList,
2509        installed: &mut Vec<usize>,
2510    ) {
2511        // What the averages were summed from goes straight back to the pool
2512        // (later work in this frame writes it only after these reads).
2513        let placed = if let Some((sum, spare)) = acc.sum {
2514            self.pool.give_back(spare);
2515            for s in acc.stash {
2516                self.pool.give_back(s.tex);
2517            }
2518            Placed {
2519                tex: sum,
2520                origin: [0.0, 0.0],
2521                scale: self.view.px,
2522            }
2523        } else if !acc.stash.is_empty() {
2524            let mut u = ops::EMPTY;
2525            for s in &acc.stash {
2526                let e = extent(s);
2527                u = [u[0].min(e[0]), u[1].min(e[1]), u[2].max(e[2]), u[3].max(e[3])];
2528            }
2529            // The union on the device grid (texels of the view's size).
2530            let px = self.view.px as f64;
2531            let (x0, y0) = ((u[0] / px).floor(), (u[1] / px).floor());
2532            let bucket = |v: f64| ((v.max(1.0) as u32).div_ceil(RASTER_BUCKET) * RASTER_BUCKET).max(RASTER_BUCKET);
2533            let desc = TextureDesc {
2534                width: bucket((u[2] / px).ceil() - x0),
2535                height: bucket((u[3] / px).ceil() - y0),
2536                format: PixelFormat::Rgba16Float,
2537                cpu_readable: false,
2538            };
2539            let (mut a, mut b) = (self.pool.lease(&self.device, desc), self.pool.lease(&self.device, desc));
2540            let k = self.kernels.utility("k_accumulate");
2541            for (i, s) in acc.stash.iter().enumerate() {
2542                let p = [
2543                    t as f32,
2544                    1.0,
2545                    desc.width as f32,
2546                    desc.height as f32,
2547                    s.origin[0] / px as f32 - x0 as f32,
2548                    s.origin[1] / px as f32 - y0 as f32,
2549                    1.0 / n as f32,
2550                    (i == 0) as u8 as f32,
2551                ];
2552                list.dispatch(&k, &b, &[&s.tex, &a], &p);
2553                std::mem::swap(&mut a, &mut b);
2554            }
2555            self.pool.give_back(b);
2556            for s in acc.stash {
2557                self.pool.give_back(s.tex);
2558            }
2559            Placed {
2560                tex: a,
2561                origin: [(x0 * px) as f32, (y0 * px) as f32],
2562                scale: px as f32,
2563            }
2564        } else {
2565            // Not shown during the samples: nothing to average.
2566            return;
2567        };
2568        let borrowed = std::mem::replace(&mut active.borrowed[g], false);
2569        if let Some(old) = active.raster[g].replace(placed)
2570            && !borrowed
2571        {
2572            self.mb_release.push(old.tex);
2573        }
2574        active.drawn[g] = 0;
2575        installed.push(g);
2576        active.alias[g] = None;
2577        active.bounds[g] = acc.bounds;
2578    }
2579
2580    /// How far (px) the fastest moving layer travels over the shutter
2581    /// [t0, t1], which sets how many samples an adaptive motion blur takes.
2582    /// A vector layer is measured on its bounds as last drawn under its own
2583    /// placement and the transforms it absorbs; any other moving transform
2584    /// on the corners of what it moves (its source's bounds); both mapped
2585    /// into the frame by the transforms after them, and only while on
2586    /// screen. A transform over unbounded content is measured on the
2587    /// frame's corners, shapes and waves by their own measures. What it
2588    /// cannot measure (shaders, glyph animation) adds nothing: those take
2589    /// the format's `samples`.
2590    fn motion_extent_px(&self, plan: &Plan, doc: &Document, moving: &[bool], t0: f64, t1: f64) -> f64 {
2591        let (w, h) = (doc.format.width as f64, doc.format.height as f64);
2592        let tm = (t0 + t1) / 2.0;
2593        let n = plan.nodes.len();
2594        let affine_of = |i: usize, t: f64| {
2595            let pn = &plan.nodes[i];
2596            ops::transform_affine(&doc.nodes[&pn.id], &doc.format, local_time(pn, t).0)
2597        };
2598        // Where each node's output lands in the frame: the transforms after
2599        // it (along its last consumer), at the frame's time.
2600        let mut down: Vec<Option<ops::Affine>> = vec![None; n];
2601        if n > 0 {
2602            down[n - 1] = Some(ops::Affine::IDENTITY);
2603        }
2604        for i in (0..n).rev() {
2605            let Some(d) = down[i] else { continue };
2606            let pn = &plan.nodes[i];
2607            let d = if pn.def.name == "transform" && local_time(pn, tm).1 {
2608                d.mul(affine_of(i, tm))
2609            } else {
2610                d
2611            };
2612            for &c in &pn.inputs {
2613                down[c].get_or_insert(d);
2614            }
2615        }
2616        let down = |i: usize| down[i].unwrap_or(ops::Affine::IDENTITY);
2617        let corners = |b: ops::Rect| [(b[0], b[1]), (b[2], b[1]), (b[0], b[3]), (b[2], b[3])];
2618        let bbox = |pts: [(f64, f64); 4]| {
2619            pts.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |r, &(x, y)| {
2620                [r[0].min(x), r[1].min(y), r[2].max(x), r[3].max(y)]
2621            })
2622        };
2623        // The part of `b` (in the space `f` maps into the frame) that the
2624        // frame shows, if any.
2625        let visible = |b: ops::Rect, f: ops::Affine| -> Option<ops::Rect> {
2626            let back = f.inverse()?;
2627            let fr = bbox(corners([0.0, 0.0, w, h]).map(|(x, y)| back.apply(x, y)));
2628            let r = [b[0].max(fr[0]), b[1].max(fr[1]), b[2].min(fr[2]), b[3].min(fr[3])];
2629            (r[0] < r[2] && r[1] < r[3] && {
2630                let s = bbox(corners(r).map(|(x, y)| f.apply(x, y)));
2631                s[2] > 0.0 && s[3] > 0.0 && s[0] < w && s[1] < h
2632            })
2633            .then_some(r)
2634        };
2635        let mut chained = vec![false; n];
2636        let mut most = 0.0f64;
2637        for g in &plan.groups {
2638            let Some(rc) = g.raster.as_ref() else { continue };
2639            for &ti in &rc.transforms {
2640                chained[ti] = true;
2641            }
2642            if !moving[rc.node] && !rc.transforms.iter().any(|&ti| moving[ti]) {
2643                continue;
2644            }
2645            let rn = &plan.nodes[rc.node];
2646            let Some(b) = self.bounds.get(&rn.id) else { continue };
2647            let b = [b[0] as f64, b[1] as f64, b[2] as f64, b[3] as f64];
2648            // Its bounds are in its chain's output space: the frame, unless
2649            // transforms follow it.
2650            let d = down(*rc.transforms.last().unwrap_or(&rc.node));
2651            let Some(b) = visible(b, d) else { continue };
2652            let node = &doc.nodes[&rn.id];
2653            let full = |t: f64| {
2654                let outer = rc
2655                    .transforms
2656                    .iter()
2657                    .fold(ops::Affine::IDENTITY, |acc, &ti| affine_of(ti, t).mul(acc));
2658                outer.mul(geom::placement_affine(node, local_time(rn, t).0))
2659            };
2660            let (f0, fm, f1) = (full(t0), full(tm), full(t1));
2661            // (A layer at zero scale is nowhere: its growth shows in the
2662            // other pairs.)
2663            for (a, z) in [(f0, f1), (f0, fm), (fm, f1)] {
2664                let Some(back) = a.inverse() else { continue };
2665                let m = z.mul(back);
2666                for (x, y) in corners(b) {
2667                    let (u, v) = m.apply(x, y);
2668                    let ((x, y), (u, v)) = (d.apply(x, y), d.apply(u, v));
2669                    most = most.max((u - x).hypot(v - y));
2670                }
2671            }
2672        }
2673        // Bounds of each node's output in its own space, at the frame's time.
2674        let mut local = vec![ops::EMPTY; n];
2675        for (i, pn) in plan.nodes.iter().enumerate() {
2676            let ins: Vec<ops::Rect> = pn.inputs.iter().map(|&c| local[c]).collect();
2677            let (lt, on) = local_time(pn, tm);
2678            local[i] = if on {
2679                ops::bounds(pn.def, &doc.nodes[&pn.id], &doc.format, lt, &ins, None)
2680            } else {
2681                ops::passthrough(pn.def, ins.len())
2682                    .map(|k| ins[k])
2683                    .unwrap_or(ops::EMPTY)
2684            };
2685        }
2686        for (i, pn) in plan.nodes.iter().enumerate() {
2687            if !moving[i] || chained[i] || !matches!(pn.def.name, "transform" | "shape" | "wave") {
2688                continue;
2689            }
2690            let (l0, lm, l1) = (local_time(pn, t0).0, local_time(pn, tm).0, local_time(pn, t1).0);
2691            let node = &doc.nodes[&pn.id];
2692            let b = pn.inputs.first().map(|&s| local[s]).unwrap_or(ops::UNBOUNDED);
2693            if pn.def.name == "transform" && b[0] > -1e8 && b[2] < 1e8 {
2694                if b[0] > b[2] || b[1] > b[3] {
2695                    continue;
2696                }
2697                // What it moves, where the frame shows it, at each time.
2698                let d = down(i);
2699                let at = |t: f64| d.mul(affine_of(i, t));
2700                let (f0, fm, f1) = (at(t0), at(tm), at(t1));
2701                let Some(b) = visible(b, fm) else { continue };
2702                for (a, z) in [(f0, f1), (f0, fm), (fm, f1)] {
2703                    for (x, y) in corners(b) {
2704                        let ((x0, y0), (x1, y1)) = (a.apply(x, y), z.apply(x, y));
2705                        most = most.max((x1 - x0).hypot(y1 - y0));
2706                    }
2707                }
2708                continue;
2709            }
2710            let f = |a: f64, b: f64| match pn.def.name {
2711                "transform" => transform_motion_px(node, &doc.format, a, b),
2712                "shape" => ops::shape_motion_px(node, &doc.format, a, b),
2713                _ => ops::wave_motion_px(node, a, b),
2714            };
2715            most = most.max(f(l0, l1).max(f(l0, lm)).max(f(lm, l1)));
2716        }
2717        most
2718    }
2719
2720    /// Plan nodes whose image moves during [t0, t1], which motion blur
2721    /// samples: params animating to different values, appearing or
2722    /// vanishing, particles and simulations. Time-driven content holds at
2723    /// the frame's time instead (footage and image-sequence frames, shader
2724    /// clocks: a camera already blurred its footage, and flicker or noise
2725    /// would average away), and so do changes that move nothing on screen
2726    /// (colors, opacities, grades; a transform moving content less than
2727    /// half a pixel; a 3D scene moving less than 0.75 px). Overlay textures
2728    /// (grain) count as still.
2729    fn moving_nodes(&self, plan: &Plan, doc: &Document, t0: f64, t1: f64) -> Vec<bool> {
2730        let mut moving = vec![false; plan.nodes.len()];
2731        for (i, pn) in plan.nodes.iter().enumerate() {
2732            if pn.is_static || plan.overlay[i] {
2733                continue;
2734            }
2735            // Simulations step on the first sample (as seeks replay them),
2736            // so they stay with the sampled groups.
2737            if pn.def.form == ops::Form::Sim {
2738                moving[i] = true;
2739                continue;
2740            }
2741            let (l0, on0) = local_time(pn, t0);
2742            let (l1, on1) = local_time(pn, t1);
2743            if on0 != on1 {
2744                moving[i] = true;
2745                continue;
2746            }
2747            if !on0 {
2748                continue;
2749            }
2750            // A particle system blurs itself along its particles' paths
2751            // (drawn once); a swarm is sampled.
2752            if pn.def.name == "swarm" {
2753                moving[i] = true;
2754                continue;
2755            }
2756            if pn.def.name == "particles" {
2757                continue;
2758            }
2759            let node = &doc.nodes[&pn.id];
2760            // Also the middle of the shutter: what turns back within it (a
2761            // key at the frame's time) ends where it began.
2762            let lm = local_time(pn, (t0 + t1) / 2.0).0;
2763            let varies = |p: &ultrafast_graph::Param| {
2764                p.is_animated() && {
2765                    let v0 = p.eval(l0);
2766                    v0 != p.eval(l1) || v0 != p.eval(lm)
2767                }
2768            };
2769            // A shader is an effect: held at the frame's time (its clock and
2770            // its u values: flicker, pulses, glitches stay crisp) unless it
2771            // asks to be sampled.
2772            if pn.def.name == "shader" {
2773                moving[i] =
2774                    ops::samples_motion(node) && (ops::time_varying(pn.def, node) || node.params.values().any(varies));
2775                continue;
2776            }
2777            // A counter's number or decoding text changes glyphs, not position.
2778            let changed: Vec<&str> = node
2779                .params
2780                .iter()
2781                .filter(|(k, p)| {
2782                    *k != "number" && *k != "scramble" && !schema::moves_nothing(pn.def.name, k) && varies(p)
2783                })
2784                .map(|(k, _)| k.as_str())
2785                .collect();
2786            // Moving less than 1.5 px over the shutter blurs nothing anyone
2787            // can see (a 3D scene renders once per 1.5 px too).
2788            // The most it moves between the shutter's ends and its middle.
2789            let most = |f: &dyn Fn(f64, f64) -> f64| f(l0, l1).max(f(l0, lm)).max(f(lm, l1));
2790            moving[i] = match pn.def.name {
2791                _ if changed.is_empty() => false,
2792                "transform" => most(&|a, b| transform_motion_px(node, &doc.format, a, b)) >= 1.5,
2793                "shape" if changed.iter().all(|k| ops::SHAPE_PLACEMENT.contains(k)) => {
2794                    most(&|a, b| ops::shape_motion_px(node, &doc.format, a, b)) >= 1.5
2795                }
2796                "wave" if changed.iter().all(|k| matches!(*k, "amplitude" | "phase")) => {
2797                    most(&|a, b| ops::wave_motion_px(node, a, b)) >= 1.5
2798                }
2799                _ => true,
2800            };
2801        }
2802        for g in &plan.groups {
2803            if g.kind == GroupKind::Render3D
2804                && g.nodes.iter().any(|&m| moving[m])
2805                && self.scene_motion_px(plan, g, doc, t0, t1) < 0.75
2806            {
2807                for &m in &g.nodes {
2808                    moving[m] = false;
2809                }
2810            }
2811        }
2812        // A simulation steps on the first sample, reading what it reads at
2813        // that instant (as a seek's catch-up does): that moves with it.
2814        for (gi, g) in plan.groups.iter().enumerate() {
2815            if g.kind == GroupKind::Sim {
2816                for (i, pn) in plan.nodes.iter().enumerate() {
2817                    if !pn.is_static && plan::bit(&plan.group_up[gi], i) {
2818                        moving[i] = true;
2819                    }
2820                }
2821            }
2822        }
2823        moving
2824    }
2825
2826    /// Encodes every group; returns the placed output of the last one.
2827    fn encode_groups(
2828        &mut self,
2829        active: &mut Active,
2830        doc: &Document,
2831        t: f64,
2832        list: &mut CommandList,
2833        report: &mut FrameReport,
2834    ) -> Result<Placed, RenderError> {
2835        self.encode_groups_masked(active, doc, t, list, report, Pass::default())
2836    }
2837
2838    /// Like [`Renderer::encode_groups`], running the groups `pass` picks
2839    /// and returning its target's output.
2840    fn encode_groups_masked(
2841        &mut self,
2842        active: &mut Active,
2843        doc: &Document,
2844        t: f64,
2845        list: &mut CommandList,
2846        report: &mut FrameReport,
2847        pass: Pass,
2848    ) -> Result<Placed, RenderError> {
2849        let Pass {
2850            only,
2851            target,
2852            changed,
2853            keep_bounds,
2854        } = pass;
2855        let Active {
2856            plan,
2857            slots,
2858            resident,
2859            slot_used,
2860            slot_groups,
2861            slot_desc,
2862            view: _,
2863            group_used,
2864            cache,
2865            raster,
2866            drawn,
2867            alias,
2868            borrowed,
2869            bounds,
2870            low_readers,
2871        } = active;
2872        self.ran.clear();
2873        self.ran.resize(plan.groups.len(), false);
2874        for &g in changed {
2875            self.ran[g] = true;
2876            alias[g] = None;
2877        }
2878        // Work that cannot reach the output at this time (layers outside their
2879        // windows, and everything only they use) is skipped.
2880        let live = match only {
2881            Some(m) => m.to_vec(),
2882            None => live_groups(plan, t),
2883        };
2884        // Live groups' slots get textures before anything reads them.
2885        for (gi, g) in plan.groups.iter().enumerate() {
2886            if !live[gi] {
2887                continue;
2888            }
2889            group_used[gi] = self.frame_no;
2890            let s = g.output;
2891            if s >= slots.len() {
2892                continue;
2893            }
2894            slot_used[s] = self.frame_no;
2895            if !resident[s] {
2896                slots[s] = self.pool.lease(&self.device, *slot_desc);
2897                resident[s] = true;
2898                for &w in &slot_groups[s] {
2899                    cache[w] = None;
2900                }
2901            }
2902        }
2903        let px = self.view.px;
2904        let placed_of = |raster: &Vec<Option<Placed>>, alias: &Vec<Option<usize>>, mut gi: usize| -> Placed {
2905            while let Some(src) = alias[gi] {
2906                gi = src;
2907            }
2908            match &raster[gi] {
2909                Some(p) => p.clone(),
2910                None => Placed {
2911                    tex: slots[plan.groups[gi].output].clone(),
2912                    origin: [0.0, 0.0],
2913                    scale: px,
2914                },
2915            }
2916        };
2917        let last = target.unwrap_or(plan.groups.len() - 1);
2918
2919        let frame_rect = [0.0, 0.0, doc.format.width as f64, doc.format.height as f64];
2920        // Where each group's output can be non-transparent (frame px).
2921        if !keep_bounds || bounds.len() != plan.groups.len() {
2922            bounds.clear();
2923            bounds.resize(plan.groups.len(), ops::UNBOUNDED);
2924        }
2925        let content = bounds;
2926        let collect = self.mb_sample.is_some() && !self.mb_acc.is_empty();
2927        for (gi, g) in plan.groups.iter().enumerate() {
2928            // Motion blur: the group before, as its readers see it, joins
2929            // its average (before anything later can write its slot).
2930            if collect && gi > 0 && live[gi - 1] && self.mb_acc[gi - 1].is_some() {
2931                let out = placed_of(raster, alias, gi - 1);
2932                self.mb_collect(gi - 1, out, content[gi - 1], doc, list);
2933            }
2934            if !live[gi] {
2935                report.groups_skipped += 1;
2936                continue;
2937            }
2938            content[gi] = ops::UNBOUNDED;
2939            // Resolve input textures (placed) and resource sizes.
2940            let mut inputs: Vec<Placed> = Vec::with_capacity(g.textures.len());
2941            let mut res_info: HashMap<&str, ResourceInfo> = HashMap::new();
2942            for ts in &g.textures {
2943                match ts {
2944                    TexSource::Group(s) => inputs.push(placed_of(raster, alias, *s)),
2945                    TexSource::Resource(src) => {
2946                        let user = g.nodes.iter().map(|&n| &plan.nodes[n]).find(|n| n.variant == *src);
2947                        // Under motion blur, footage and image sequences hold
2948                        // the frame's own picture across the shutter.
2949                        let timed = src.starts_with("video:") || src.contains("{frame");
2950                        let at = match self.mb_sample {
2951                            Some((_, _, tc, _)) if timed => tc,
2952                            _ => t,
2953                        };
2954                        let (user_id, user_t, user_on) = match user {
2955                            Some(n) => (n.id.clone(), local_time(n, at).0, local_time(n, t).1),
2956                            None => (String::new(), at, true),
2957                        };
2958                        // A media node outside its window in a fused group
2959                        // that is live for its other layers: nothing samples
2960                        // it, so do not decode (or seek) it.
2961                        if !user_on && (src.starts_with("video:") || src.contains("{frame")) {
2962                            inputs.push(Placed {
2963                                tex: self.placeholder.clone(),
2964                                origin: [0.0, 0.0],
2965                                scale: 1.0,
2966                            });
2967                            continue;
2968                        }
2969                        let (tex, info) = self.resource(src, &user_id, doc, user_t, list);
2970                        if let Some(i) = info {
2971                            res_info.insert(src.as_str(), i);
2972                        }
2973                        inputs.push(Placed {
2974                            tex,
2975                            origin: [0.0, 0.0],
2976                            scale: 1.0,
2977                        });
2978                    }
2979                }
2980            }
2981
2982            // Pack params: header, then the group's layout (node blocks,
2983            // literal values, padding, texture origins), then the blocks of
2984            // the run layers showing now.
2985            self.scratch.clear();
2986            self.scratch.extend(header(doc, t, self.view));
2987            let mut run_headers: Vec<(usize, usize)> = Vec::new();
2988            for slot in &g.params {
2989                match slot {
2990                    plan::ParamSlot::Node(ni) => {
2991                        let pn = &plan.nodes[*ni];
2992                        let info = if ops::uses_resource(pn.def) {
2993                            res_info.get(pn.variant.as_str()).copied()
2994                        } else {
2995                            None
2996                        };
2997                        let (lt, on) = local_time(pn, t);
2998                        // A static group is time-invariant: pack it at one
2999                        // fixed time so its params compare equal from frame
3000                        // to frame (a shader that never reads time() still
3001                        // receives it).
3002                        let lt = if g.is_static { 0.0 } else { lt };
3003                        ops::pack(
3004                            pn.def,
3005                            &pn.id,
3006                            &doc.nodes[&pn.id],
3007                            &doc.format,
3008                            lt,
3009                            info,
3010                            &mut self.scratch,
3011                        )?;
3012                        self.hold_shader_clock(pn, &doc.nodes[&pn.id], g.is_static);
3013                        if pn.gated {
3014                            self.scratch.push(on as u8 as f32);
3015                        }
3016                        if ops::guarded(pn.def) {
3017                            let b = subtree_bounds(plan, g, pn.inputs[0], doc, t, &inputs, &res_info, &content);
3018                            self.scratch.extend(b.map(|v| v as f32));
3019                        }
3020                        if let Some(tables) = &pn.tables {
3021                            self.scratch.extend_from_slice(tables);
3022                        }
3023                    }
3024                    plan::ParamSlot::Run(r) => {
3025                        run_headers.push((*r, self.scratch.len()));
3026                        self.scratch.extend([0.0, 0.0]);
3027                    }
3028                    plan::ParamSlot::Value(v) => self.scratch.push(*v),
3029                    plan::ParamSlot::Pad(n) => self.scratch.extend(std::iter::repeat_n(0.0, *n)),
3030                    plan::ParamSlot::Origins => {
3031                        for p in &inputs {
3032                            self.scratch.extend(p.origin);
3033                            self.scratch.push(p.scale);
3034                        }
3035                    }
3036                }
3037            }
3038            for (r, at) in run_headers {
3039                let run = &g.runs[r];
3040                let start = self.scratch.len();
3041                let mut shown = 0;
3042                for (kind, ci, layer) in &run.layers {
3043                    let pn = &plan.nodes[*ci];
3044                    let (lt, on) = local_time(pn, t);
3045                    // Out of its window, or nothing to lay: the background
3046                    // shows through, as it would without the layer.
3047                    if !on {
3048                        continue;
3049                    }
3050                    let b = subtree_bounds(plan, g, pn.inputs[0], doc, t, &inputs, &res_info, &content);
3051                    if b[0] >= b[2] || b[1] >= b[3] {
3052                        continue;
3053                    }
3054                    let lt = if g.is_static { 0.0 } else { lt };
3055                    let block = self.scratch.len();
3056                    self.scratch.push(*kind as f32);
3057                    ops::pack(
3058                        pn.def,
3059                        &pn.id,
3060                        &doc.nodes[&pn.id],
3061                        &doc.format,
3062                        lt,
3063                        None,
3064                        &mut self.scratch,
3065                    )?;
3066                    self.hold_shader_clock(pn, &doc.nodes[&pn.id], g.is_static);
3067                    self.scratch.extend(b.map(|v| v as f32));
3068                    match layer {
3069                        codegen::LayerRef::Texture(binding) => {
3070                            let d = inputs[*binding].tex.desc();
3071                            self.scratch.extend([*binding as f32, d.width as f32, d.height as f32]);
3072                        }
3073                        codegen::LayerRef::Gen(gi) => {
3074                            let gn = &plan.nodes[*gi];
3075                            let (glt, _) = local_time(gn, t);
3076                            let glt = if g.is_static { 0.0 } else { glt };
3077                            ops::pack(
3078                                gn.def,
3079                                &gn.id,
3080                                &doc.nodes[&gn.id],
3081                                &doc.format,
3082                                glt,
3083                                None,
3084                                &mut self.scratch,
3085                            )?;
3086                            self.hold_shader_clock(gn, &doc.nodes[&gn.id], g.is_static);
3087                        }
3088                    }
3089                    self.scratch.resize(block + run.stride, 0.0);
3090                    shown += 1;
3091                }
3092                self.scratch[at] = start as f32;
3093                self.scratch[at + 1] = shown as f32;
3094            }
3095            match g.kind {
3096                GroupKind::Fused => {
3097                    content[gi] = intersect(
3098                        subtree_bounds(plan, g, g.root, doc, t, &inputs, &res_info, &content),
3099                        frame_rect,
3100                    )
3101                }
3102                GroupKind::Render3D | GroupKind::Sim => content[gi] = frame_rect,
3103                _ => {}
3104            }
3105
3106            // A fused group that at this time only passes an input through
3107            // (its layers are out of their windows, or what it composites
3108            // over is empty here) shows that input as it is.
3109            alias[gi] = None;
3110            if g.kind == GroupKind::Fused && gi != last && !self.no_skip {
3111                let crossing = self.mb_frame.as_ref().is_some_and(|f| f.crosses[gi]);
3112                alias[gi] = passthrough_group(plan, g, g.root, doc, t, &inputs, &res_info, &content).filter(|&src| {
3113                    // Only while nothing reuses the source's slot before the
3114                    // last group that reads this one (with motion blur, a
3115                    // later phase reads it: only a texture of its own).
3116                    let mut f = src;
3117                    while let Some(n) = alias[f] {
3118                        f = n;
3119                    }
3120                    if let Some(p) = &raster[f] {
3121                        // A blur kept at reduced resolution is only for its own
3122                        // readers' kernels.
3123                        return p.scale == px;
3124                    }
3125                    if crossing {
3126                        return false;
3127                    }
3128                    let slot = plan.groups[f].output;
3129                    let last_use = (gi + 1..plan.groups.len())
3130                        .filter(|&k| plan.groups[k].textures.contains(&TexSource::Group(gi)))
3131                        .max()
3132                        .unwrap_or(gi);
3133                    !(gi + 1..=last_use).any(|k| plan.groups[k].output == slot)
3134                });
3135                if let Some(src) = alias[gi] {
3136                    if std::env::var_os("ULTRAFAST_DEBUG_ALIAS").is_some() {
3137                        eprintln!("t={t:.3} g{gi} -> g{src} (last g{last})");
3138                    }
3139                    content[gi] = content[src];
3140                    self.ran[gi] = self.ran[src];
3141                    cache[gi] = None;
3142                    report.groups_cached += 1;
3143                    continue;
3144                }
3145            }
3146
3147            // Raster geometry identity: node params, absorbed transforms, time.
3148            // A raster chain shows while its raster node is active; a timed
3149            // transform outside its window passes it through unmoved.
3150            let raster_geo = g.raster.as_ref().map(|rc| {
3151                // Built on the device grid: the view's density times the
3152                // transforms the raster absorbed (curves flattened and glyphs
3153                // drawn for that size).
3154                let d = 1.0 / px as f64;
3155                let outer = ops::Affine::scale(d, d).mul(absorbed(plan, doc, &rc.transforms, t));
3156                let rn = &plan.nodes[rc.node];
3157                let (lt, on) = local_time(rn, t);
3158                let key = if on {
3159                    geom::geometry_key(&doc.nodes[&rn.id], lt, &outer)
3160                } else {
3161                    0
3162                };
3163                (rc.node, outer, key, lt, on)
3164            });
3165
3166            // Static groups rerun only when params, inputs or upstream changed.
3167            // The time/frame header is excluded: static means time-invariant.
3168            // (Only static groups own their output slot across frames, so
3169            // only they can be reused this way.)
3170            if g.is_static {
3171                let mut ids: Vec<usize> = inputs.iter().map(|p| p.tex.id()).collect();
3172                if let Some((_, _, key, _, _)) = raster_geo {
3173                    ids.push(key as usize);
3174                }
3175                if g.kind == GroupKind::Render3D {
3176                    ids.push(scene_key(plan, g, doc, t) as usize);
3177                }
3178                let upstream_ran = g
3179                    .textures
3180                    .iter()
3181                    .any(|ts| matches!(ts, TexSource::Group(s) if self.ran[*s]));
3182                if std::env::var_os("ULTRAFAST_DEBUG_CACHE").is_some() {
3183                    let why = match &cache[gi] {
3184                        _ if upstream_ran => {
3185                            let ups: Vec<usize> = g
3186                                .textures
3187                                .iter()
3188                                .filter_map(|ts| match ts {
3189                                    TexSource::Group(s) if self.ran[*s] => Some(*s),
3190                                    _ => None,
3191                                })
3192                                .collect();
3193                            format!("upstream ran: {ups:?}")
3194                        }
3195                        None => "first run".to_string(),
3196                        Some((p, _)) if p[..] != self.scratch[2..] => {
3197                            let k = p.iter().zip(&self.scratch[2..]).position(|(a, b)| a != b);
3198                            format!("params differ at {k:?} (len {} vs {})", p.len(), self.scratch.len() - 2)
3199                        }
3200                        Some((_, i)) if *i != ids => format!("inputs differ: {i:?} vs {ids:?}"),
3201                        _ => String::new(),
3202                    };
3203                    if !why.is_empty() {
3204                        eprintln!("t={t:.3} g{gi} reruns: {why}");
3205                    }
3206                }
3207                if !upstream_ran
3208                    && let Some((p, i)) = &cache[gi]
3209                    && p[..] == self.scratch[2..]
3210                    && *i == ids
3211                {
3212                    report.groups_cached += 1;
3213                    if matches!(g.kind, GroupKind::Raster | GroupKind::Blur) {
3214                        content[gi] = extent(&placed_of(raster, alias, gi));
3215                    }
3216                    continue;
3217                }
3218                cache[gi] = Some((self.scratch[2..].to_vec(), ids));
3219            }
3220
3221            let mut in_tex: Vec<&Texture> = inputs.iter().map(|p| &p.tex).collect();
3222            if g.pad_textures {
3223                in_tex.resize(plan::MAX_TEXTURES, &self.placeholder);
3224            }
3225            match g.kind {
3226                GroupKind::Raster => {
3227                    let (rn, outer, key, lt, on) = raster_geo.expect("raster group");
3228                    let framed = plan.framed[gi] && !self.no_framed;
3229                    // The same geometry in the same paint as last time: its
3230                    // texture still holds it (text that has settled, shapes
3231                    // between keys, motion-blur samples of still layers).
3232                    let paint = {
3233                        use std::hash::{Hash, Hasher};
3234                        let mut h = std::collections::hash_map::DefaultHasher::new();
3235                        (key, on, framed).hash(&mut h);
3236                        for v in &self.scratch[4..9] {
3237                            v.to_bits().hash(&mut h);
3238                        }
3239                        h.finish() | 1
3240                    };
3241                    if drawn[gi] == paint
3242                        && !self.no_skip
3243                        && let Some(p) = &raster[gi]
3244                    {
3245                        content[gi] = extent(p);
3246                        report.groups_cached += 1;
3247                        continue;
3248                    }
3249                    drawn[gi] = paint;
3250                    let geo = if on {
3251                        self.geometry(&plan.nodes[rn].id, doc, lt, outer, key)?
3252                    } else {
3253                        Arc::new(geom::Geometry::default())
3254                    };
3255                    let prev = raster[gi].take();
3256                    // Color glyphs keep their own colors and fade with the
3257                    // node's opacity only.
3258                    let opacity = doc.nodes[&plan.nodes[rn].id]
3259                        .params
3260                        .get("opacity")
3261                        .and_then(|p| p.eval(lt))
3262                        .and_then(|v| v.first().copied())
3263                        .unwrap_or(1.0)
3264                        .clamp(0.0, 1.0) as f32;
3265                    let placed = self.encode_raster(&geo, prev, opacity, framed, doc, t, list);
3266                    content[gi] = extent(&placed);
3267                    raster[gi] = Some(placed);
3268                    report.kernels_run += 2;
3269                }
3270                GroupKind::Particles => {
3271                    let prev = raster[gi].take();
3272                    let sprite = inputs.first().cloned();
3273                    let placed = self.encode_particles(plan, g, sprite, prev, doc, t, list)?;
3274                    content[gi] = extent(&placed);
3275                    raster[gi] = Some(placed);
3276                    report.kernels_run += 1;
3277                }
3278                GroupKind::Render3D => {
3279                    let out = slots[g.output].clone();
3280                    // Motion blur: a 3D scene is rendered only as often as
3281                    // it moves (about every 1.5 px on screen during the
3282                    // shutter); samples in between reuse the last render.
3283                    let plan_mb = self.mb_sample.filter(|_| !self.mb_full).map(|(s, n, tc, span)| {
3284                        let m = self.scene_motion_px(plan, g, doc, tc - span / 2.0, tc + span / 2.0) / px;
3285                        if s == 0 && std::env::var("ULTRAFAST_DEBUG_MB").is_ok() {
3286                            eprintln!("t={tc:.2} group {gi}: 3D moves {m:.2} px over the shutter");
3287                        }
3288                        let k = if m.is_finite() {
3289                            ((m / 1.5).ceil() as u32).clamp(1, n)
3290                        } else {
3291                            n
3292                        };
3293                        let bucket = |s: u32| s * k / n;
3294                        let first = s == 0 || bucket(s) != bucket(s - 1);
3295                        let at = tc - span / 2.0 + span * (bucket(s) as f64 + 0.5) / k as f64;
3296                        (first, at)
3297                    });
3298                    match plan_mb {
3299                        Some((false, _)) => report.groups_cached += 1,
3300                        Some((true, at)) => {
3301                            self.encode_render3d(plan, g, &inputs, &out, doc, at, list)?;
3302                            report.kernels_run += 1;
3303                        }
3304                        None => {
3305                            self.encode_render3d(plan, g, &inputs, &out, doc, t, list)?;
3306                            report.kernels_run += 1;
3307                        }
3308                    }
3309                }
3310                GroupKind::Sim => {
3311                    let out = slots[g.output].clone();
3312                    self.encode_sim(plan, gi, &inputs, &out, doc, t, list, report)?;
3313                    report.kernels_run += 1;
3314                }
3315                GroupKind::Blur => {
3316                    // Blur only the region the source covers (plus the blur's
3317                    // reach), at reduced resolution for large radii.
3318                    let src = inputs[0].clone();
3319                    let src_bounds = match g.textures[0] {
3320                        TexSource::Group(s) => intersect(extent(&src), content[s]),
3321                        _ => extent(&src),
3322                    };
3323                    // A texture this group borrowed is not its own to reuse.
3324                    let prev = raster[gi]
3325                        .take()
3326                        .filter(|_| !std::mem::replace(&mut borrowed[gi], false));
3327                    if local_time(&plan.nodes[g.root], t).1 {
3328                        // Kept at its reduced resolution when every reader can
3329                        // sample it there and has its kernel (not while motion
3330                        // blur averages it, nor for a fallback reader).
3331                        let keep_low = self.mb_sample.is_none()
3332                            && low_readers[gi].as_ref().is_some_and(|rs| {
3333                                rs.iter().all(|&c| {
3334                                    matches!(self.kernels.get(&plan.groups[c].key), Some(KernelState::Ready(_)))
3335                                })
3336                            });
3337                        let (placed, b) =
3338                            self.encode_blur(&src, src_bounds, self.scratch[4], prev, keep_low, doc, t, list);
3339                        raster[gi] = Some(placed);
3340                        content[gi] = b;
3341                        report.kernels_run += 2;
3342                    } else {
3343                        // Inactive: the source passes through untouched. Shown
3344                        // as it is when nothing writes its slot before the last
3345                        // reader of this group; otherwise copied, since a
3346                        // later group would reuse that slot first.
3347                        let slot = slots.iter().position(|s| s.id() == src.tex.id());
3348                        let last_use = (gi + 1..plan.groups.len())
3349                            .filter(|&k| plan.groups[k].textures.contains(&TexSource::Group(gi)))
3350                            .max()
3351                            .unwrap_or(gi);
3352                        let crossing = self.mb_frame.as_ref().is_some_and(|f| f.crosses[gi]);
3353                        let clobbered =
3354                            slot.is_some_and(|sl| crossing || (gi + 1..=last_use).any(|k| plan.groups[k].output == sl));
3355                        if clobbered {
3356                            let desc = src.tex.desc();
3357                            let tex = match prev {
3358                                Some(p) if p.tex.desc() == desc => p.tex,
3359                                other => {
3360                                    if let Some(p) = other {
3361                                        self.pool.give_back(p.tex);
3362                                    }
3363                                    self.pool.lease(&self.device, desc)
3364                                }
3365                            };
3366                            list.dispatch(
3367                                &self.kernels.utility("k_copy"),
3368                                &tex,
3369                                &[&src.tex],
3370                                &header(doc, t, self.view),
3371                            );
3372                            raster[gi] = Some(Placed {
3373                                tex,
3374                                origin: src.origin,
3375                                scale: src.scale,
3376                            });
3377                        } else {
3378                            if let Some(p) = prev {
3379                                self.pool.give_back(p.tex);
3380                            }
3381                            raster[gi] = Some(src);
3382                            borrowed[gi] = true;
3383                        }
3384                        content[gi] = src_bounds;
3385                    }
3386                }
3387                GroupKind::Fused => {
3388                    // A fused group pinned for this frame (motion blur) renders
3389                    // into its own texture instead of its shared slot.
3390                    let out = &match &raster[gi] {
3391                        Some(p) => p.tex.clone(),
3392                        None => slots[g.output].clone(),
3393                    };
3394                    let op_by_op = || {
3395                        g.nodes
3396                            .iter()
3397                            .all(|&n| self.kernels.tier0(plan.nodes[n].def.func).is_some())
3398                    };
3399                    let state = match self.mode {
3400                        Mode::Exact if self.wait_fused || !op_by_op() => self.kernels.wait(&g.key),
3401                        _ => self.kernels.get(&g.key).unwrap_or(KernelState::Pending),
3402                    };
3403                    let scale = ops::render_scale(&doc.nodes[&plan.nodes[g.root].id]);
3404                    match state {
3405                        KernelState::Ready(k) if scale.is_some() => {
3406                            // Reduced resolution: render coarse texels, then
3407                            // upscale into the slot.
3408                            let r = scale.unwrap() as f32;
3409                            let v = self.view;
3410                            let low = TextureDesc {
3411                                width: ((v.w as f32 * r).ceil() as u32).max(1),
3412                                height: ((v.h as f32 * r).ceil() as u32).max(1),
3413                                format: PixelFormat::Rgba16Float,
3414                                cpu_readable: false,
3415                            };
3416                            let tmp = self.pool.lease(&self.device, low);
3417                            self.scratch[1] = v.px / r;
3418                            list.dispatch(&k, &tmp, &in_tex, &self.scratch);
3419                            self.scratch[1] = v.px;
3420                            let mut p = header(doc, t, v).to_vec();
3421                            p.extend([v.px, 0.0, 0.0, 0.0, 0.0, v.px / r, 1.0]);
3422                            list.dispatch(&self.kernels.utility("k_resample"), out, &[&tmp], &p);
3423                            self.pool.give_back(tmp);
3424                            report.kernels_run += 2;
3425                        }
3426                        KernelState::Ready(k) => {
3427                            list.dispatch(&k, out, &in_tex, &self.scratch);
3428                            report.kernels_run += 1;
3429                        }
3430                        KernelState::Pending => {
3431                            self.encode_fallback(plan, gi, &inputs, out, doc, t, list, &res_info)?;
3432                            report.groups_fallback += 1;
3433                            // A fallback result is not final: never cache it.
3434                            cache[gi] = None;
3435                        }
3436                        KernelState::Failed(e) => {
3437                            self.diagnose(&plan.nodes[g.root].id.clone(), e);
3438                            list.dispatch(&self.kernels.utility("k_clear"), out, &[], &header(doc, t, self.view));
3439                        }
3440                    }
3441                }
3442            }
3443            self.ran[gi] = true;
3444            if self.profile.is_some() {
3445                let ids: Vec<&str> = g.nodes.iter().map(|&n| plan.nodes[n].id.as_str()).collect();
3446                let names = if ids.len() > 4 {
3447                    format!("{} +{}", ids[..3].join(" "), ids.len() - 3)
3448                } else {
3449                    ids.join(" ")
3450                };
3451                let label = format!("g{gi} {:?} [{names}]", g.kind);
3452                let sub = std::mem::replace(list, self.device.begin()).submit();
3453                // Timed now: a backend may reuse the submission's slot (and
3454                // its timestamps) before a later read.
3455                let ms = sub.wait()?.gpu_ms;
3456                if let Some(p) = &mut self.profile {
3457                    let e = p.totals.entry(label).or_insert((0.0, 0));
3458                    e.0 += ms;
3459                    e.1 += 1;
3460                }
3461            }
3462        }
3463        let gl = plan.groups.len();
3464        if collect && gl > 0 && live[gl - 1] && self.mb_acc[gl - 1].is_some() {
3465            let out = placed_of(raster, alias, gl - 1);
3466            self.mb_collect(gl - 1, out, content[gl - 1], doc, list);
3467        }
3468        Ok(placed_of(raster, alias, last))
3469    }
3470
3471    /// Under motion blur a shader's clock reads the frame's time, not the
3472    /// sample's (its last packed value, right after `ops::pack`), unless the
3473    /// shader asks to be sampled.
3474    fn hold_shader_clock(&mut self, pn: &plan::PlanNode, node: &ultrafast_graph::Node, is_static: bool) {
3475        if pn.def.name == "shader"
3476            && !ops::samples_motion(node)
3477            && let Some((_, _, tc, _)) = self.mb_sample
3478            && let Some(v) = self.scratch.last_mut()
3479        {
3480            *v = if is_static { 0.0 } else { local_time(pn, tc).0 as f32 };
3481        }
3482    }
3483
3484    /// Largest on-screen movement (frame px) of any mesh's bounds between
3485    /// t0 and t1; infinite when it cannot tell (meshes not built yet,
3486    /// visibility changing, corners behind the camera).
3487    fn scene_motion_px(&self, plan: &Plan, g: &plan::Group, doc: &Document, t0: f64, t1: f64) -> f32 {
3488        use scene3d::{Mat4, Params};
3489        let Some(three) = self.three.as_ref() else {
3490            return f32::INFINITY;
3491        };
3492        let (fw, fh) = (doc.format.width as f32, doc.format.height as f32);
3493        let project = |t: f64| -> Option<Vec<[f32; 2]>> {
3494            let (mut eye, mut target, mut up) = ([0.0f32, 0.0, 5.0], [0.0f32, 0.0, 0.0], [0.0f32, 1.0, 0.0]);
3495            let (mut fov, mut near, mut far) = (45.0f32, 0.1f32, 1000.0f32);
3496            for &o in &g.nodes[..g.nodes.len() - 1] {
3497                let pn = &plan.nodes[o];
3498                let (lt, on) = local_time(pn, t);
3499                if pn.def.name != "camera" || !on {
3500                    continue;
3501                }
3502                let node = &doc.nodes[&pn.id];
3503                let p = Params { node, t: lt };
3504                target = p.vec("target", target);
3505                up = p.vec("up", up);
3506                fov = p.num("fov", fov);
3507                near = p.num("near", near);
3508                far = p.num("far", far);
3509                eye = if pn_has(node, "orbit") {
3510                    let [az, el, dist] = p.vec("orbit", [0.0, 0.0, 5.0]);
3511                    let (az, el) = (az.to_radians(), el.to_radians());
3512                    [
3513                        target[0] + dist * el.cos() * az.sin(),
3514                        target[1] + dist * el.sin(),
3515                        target[2] + dist * el.cos() * az.cos(),
3516                    ]
3517                } else {
3518                    p.vec("position", eye)
3519                };
3520            }
3521            let vp = Mat4::perspective(fov, fw / fh.max(1.0), near, far).mul(&Mat4::look_at(eye, target, up));
3522            let mut pts = Vec::new();
3523            for &o in &g.nodes[..g.nodes.len() - 1] {
3524                let pn = &plan.nodes[o];
3525                if pn.def.name != "mesh" {
3526                    continue;
3527                }
3528                let (lt, on) = local_time(pn, t);
3529                if !on {
3530                    // Appearing or vanishing within the shutter is motion.
3531                    pts.push([-1e6, -1e6]);
3532                    continue;
3533                }
3534                let node = &doc.nodes[&pn.id];
3535                let [lo, hi] = three.meshes.get(&scene3d::mesh_key(node))?.3;
3536                let m = Params { node, t: lt }.model().0;
3537                let v = &vp.0;
3538                for corner in 0..8 {
3539                    let c = [
3540                        if corner & 1 == 0 { lo[0] } else { hi[0] },
3541                        if corner & 2 == 0 { lo[1] } else { hi[1] },
3542                        if corner & 4 == 0 { lo[2] } else { hi[2] },
3543                    ];
3544                    let w = [
3545                        m[0] * c[0] + m[1] * c[1] + m[2] * c[2] + m[3],
3546                        m[4] * c[0] + m[5] * c[1] + m[6] * c[2] + m[7],
3547                        m[8] * c[0] + m[9] * c[1] + m[10] * c[2] + m[11],
3548                        1.0,
3549                    ];
3550                    let clip: Vec<f32> = (0..4).map(|r| (0..4).map(|k| v[r * 4 + k] * w[k]).sum()).collect();
3551                    // Corners behind the camera (a ground plane) say nothing.
3552                    if clip[3] <= 1e-3 {
3553                        pts.push([f32::NAN, f32::NAN]);
3554                        continue;
3555                    }
3556                    pts.push([
3557                        (clip[0] / clip[3] * 0.5 + 0.5) * fw,
3558                        (0.5 - clip[1] / clip[3] * 0.5) * fh,
3559                    ]);
3560                }
3561            }
3562            Some(pts)
3563        };
3564        match (project(t0), project(t1)) {
3565            (Some(a), Some(b)) if a.len() == b.len() => a
3566                .iter()
3567                .zip(&b)
3568                .map(|(p, q)| {
3569                    let d = ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt();
3570                    if d.is_nan() { 0.0 } else { d }
3571                })
3572                .fold(0.0, f32::max),
3573            _ => f32::INFINITY,
3574        }
3575    }
3576
3577    /// Renders a `render3d` group: every connected mesh, lit by the connected
3578    /// lights (the first directional light casts a shadow map), seen through
3579    /// the connected camera, with depth and 4x MSAA.
3580    #[allow(clippy::too_many_arguments)]
3581    fn encode_render3d(
3582        &mut self,
3583        plan: &Plan,
3584        g: &plan::Group,
3585        inputs: &[Placed],
3586        out: &Texture,
3587        doc: &Document,
3588        t: f64,
3589        list: &mut CommandList,
3590    ) -> Result<(), RenderError> {
3591        use scene3d::{Mat4, Params};
3592        const SAMPLES: u32 = 4;
3593        const SHADOW: u32 = 2048;
3594        let (fw, fh) = (doc.format.width, doc.format.height);
3595        // The scene draws on the device grid (the view's size); the shaders
3596        // place textures and find screen positions in its texels, and every
3597        // input texture is at the view's density.
3598        let v = self.view;
3599        let (dw, dh) = (v.w, v.h);
3600        let dev = |o: [f32; 2]| [o[0] / v.px, o[1] / v.px];
3601        if self.three.is_none() {
3602            let target = if self.device.backend() == "metal" {
3603                ultrafast_shaderc::Target::Metal
3604            } else {
3605                ultrafast_shaderc::Target::Spirv
3606            };
3607            use ultrafast_shaderc::Stage;
3608            let code = ultrafast_shaderc::Compiler::new()
3609                .compile_stages(
3610                    include_str!("../shaders/lib3d.slang"),
3611                    &[
3612                        ("vs_mesh", Stage::Vertex),
3613                        ("fs_mesh", Stage::Fragment),
3614                        ("vs_shadow", Stage::Vertex),
3615                        ("fs_shadow", Stage::Fragment),
3616                        ("fs_dist", Stage::Fragment),
3617                    ],
3618                    target,
3619                )
3620                .map_err(|e| RenderError::Setup(e.to_string()))?;
3621            let lib = self.device.library(&code.code)?;
3622            let pipeline = self.device.draw_pipeline(
3623                &lib,
3624                "vs_mesh",
3625                "fs_mesh",
3626                SAMPLES,
3627                true,
3628                ultrafast_gpu::Blend::Opaque,
3629                PixelFormat::Rgba16Float,
3630            )?;
3631            let shadow_pipeline = self.device.draw_pipeline(
3632                &lib,
3633                "vs_shadow",
3634                "fs_shadow",
3635                1,
3636                true,
3637                ultrafast_gpu::Blend::Opaque,
3638                PixelFormat::R32Float,
3639            )?;
3640            let dist_pipeline = self.device.draw_pipeline(
3641                &lib,
3642                "vs_shadow",
3643                "fs_dist",
3644                1,
3645                true,
3646                ultrafast_gpu::Blend::Opaque,
3647                PixelFormat::R32Float,
3648            )?;
3649            // 1x1 white RGBA16F (half 1.0 = 0x3c00).
3650            let one = 0x3c00u16.to_le_bytes();
3651            let white = self.device.upload_texture(
3652                TextureDesc {
3653                    width: 1,
3654                    height: 1,
3655                    format: PixelFormat::Rgba16Float,
3656                    cpu_readable: false,
3657                },
3658                &[one[0], one[1], one[0], one[1], one[0], one[1], one[0], one[1]],
3659            );
3660            let shadow_map = self.device.create_texture(TextureDesc {
3661                width: SHADOW,
3662                height: SHADOW,
3663                format: PixelFormat::R32Float,
3664                cpu_readable: false,
3665            });
3666            let shadow_depth = self
3667                .device
3668                .create_attachment(SHADOW, SHADOW, PixelFormat::Depth32Float, 1);
3669            self.three = Some(Three {
3670                pipeline,
3671                shadow_pipeline,
3672                shadow_map,
3673                shadow_depth,
3674                attachments: None,
3675                dist_pipeline,
3676                dof: None,
3677                white,
3678                meshes: HashMap::new(),
3679            });
3680        }
3681
3682        let root = &plan.nodes[g.root];
3683        let (root_t, active) = local_time(root, t);
3684        let rp = Params {
3685            node: &doc.nodes[&root.id],
3686            t: root_t,
3687        };
3688        let clear = rp.color("background", [0.0, 0.0, 0.0, 0.0]);
3689        // Outside its time window the scene draws nothing, background included.
3690        let clear = if active {
3691            [clear[0] * clear[3], clear[1] * clear[3], clear[2] * clear[3], clear[3]]
3692        } else {
3693            [0.0; 4]
3694        };
3695        let sky = rp.color("sky", [0.9, 0.95, 1.0, 1.0]);
3696        let ground = rp.color("ground", [0.35, 0.3, 0.28, 1.0]);
3697        let ambient = rp.num("ambient", 0.35);
3698        let shadows_on = !matches!(
3699            doc.nodes[&root.id].params.get("shadows"),
3700            Some(ultrafast_graph::Param::Bool(false))
3701        );
3702        let shadow_strength = rp.num("shadow_strength", 0.85);
3703        // Fog toward `fog_color` (the background by default) between
3704        // `fog` [start, end] world units from the camera.
3705        let fog = match doc.nodes[&root.id].params.get("fog").and_then(|p| p.eval(root_t)) {
3706            Some(v) if v.len() >= 2 => Some((v[0] as f32, (v[1] as f32).max(v[0] as f32 + 1e-3))),
3707            _ => None,
3708        };
3709        let fog_color = {
3710            let c = rp.color("fog_color", rp.color("background", [0.0, 0.0, 0.0, 1.0]));
3711            [c[0], c[1], c[2]]
3712        };
3713        let env_intensity = rp.num("environment_intensity", 1.0);
3714        let env_rotation = rp.num("environment_rotation", 0.0);
3715        // An image on the `environment` port lights and reflects in the scene.
3716        let env: Option<usize> = doc.nodes[&root.id].inputs.get("environment").and_then(|src| {
3717            let si = root.inputs.iter().copied().find(|&i| plan.nodes[i].id == *src)?;
3718            g.textures
3719                .iter()
3720                .position(|ts| *ts == TexSource::Group(plan.group_of[si]))
3721        });
3722        let env_origin = dev(env.map(|i| inputs[i].origin).unwrap_or([0.0, 0.0]));
3723        // A blurred copy of the environment, for rough surfaces and diffuse
3724        // light (a sparse disk over the sharp image would band).
3725        let env_soft: Option<Placed> = match env {
3726            Some(i) if active => {
3727                let frame_rect = [0.0, 0.0, fw as f64, fh as f64];
3728                let sigma = (fw.max(fh) as f32) * 0.025;
3729                Some(
3730                    self.encode_blur(&inputs[i], frame_rect, sigma, None, false, doc, t, list)
3731                        .0,
3732                )
3733            }
3734            _ => None,
3735        };
3736        let env_soft_origin = dev(env_soft.as_ref().map(|p| p.origin).unwrap_or([0.0, 0.0]));
3737        // Constant depth bias, in shadow-map texels of depth.
3738        let shadow_bias = rp.num("shadow_bias", 1.0);
3739
3740        // Camera and lights.
3741        let aspect = fw as f32 / fh.max(1) as f32;
3742        let mut eye = [0.0f32, 0.0, 5.0];
3743        let mut target = [0.0f32, 0.0, 0.0];
3744        let mut up = [0.0f32, 1.0, 0.0];
3745        let (mut fov, mut near, mut far) = (45.0f32, 0.1f32, 1000.0f32);
3746        let mut lights: Vec<[f32; 8]> = Vec::new();
3747        let mut meshes: Vec<usize> = Vec::new();
3748        for &o in &g.nodes[..g.nodes.len() - 1] {
3749            let pn = &plan.nodes[o];
3750            let (lt, on) = local_time(pn, t);
3751            if !on || !active {
3752                continue;
3753            }
3754            let p = Params {
3755                node: &doc.nodes[&pn.id],
3756                t: lt,
3757            };
3758            match pn.def.name {
3759                "camera" => {
3760                    target = p.vec("target", target);
3761                    up = p.vec("up", up);
3762                    fov = p.num("fov", fov);
3763                    near = p.num("near", near);
3764                    far = p.num("far", far);
3765                    eye = if pn_has(&doc.nodes[&pn.id], "orbit") {
3766                        // Orbit: azimuth, elevation (degrees), distance around target.
3767                        let [az, el, dist] = p.vec("orbit", [0.0, 0.0, 5.0]);
3768                        let (az, el) = (az.to_radians(), el.to_radians());
3769                        [
3770                            target[0] + dist * el.cos() * az.sin(),
3771                            target[1] + dist * el.sin(),
3772                            target[2] + dist * el.cos() * az.cos(),
3773                        ]
3774                    } else {
3775                        p.vec("position", eye)
3776                    };
3777                }
3778                "light" => {
3779                    let c = p.color("color", [1.0, 1.0, 1.0, 1.0]);
3780                    let point = p.text("kind") == Some("point");
3781                    let v = if point {
3782                        p.vec("position", [0.0, 2.0, 2.0])
3783                    } else {
3784                        p.vec("direction", [0.4, 0.8, 0.6])
3785                    };
3786                    lights.push([
3787                        point as u8 as f32,
3788                        v[0],
3789                        v[1],
3790                        v[2],
3791                        c[0],
3792                        c[1],
3793                        c[2],
3794                        p.num("intensity", 3.0),
3795                    ]);
3796                }
3797                "mesh" => meshes.push(o),
3798                _ => {}
3799            }
3800        }
3801        if lights.is_empty() {
3802            // A default key and rim light so an unlit scene is still readable.
3803            lights.push([0.0, 0.5, 0.8, 0.6, 1.0, 0.98, 0.95, 3.0]);
3804            lights.push([0.0, -0.6, 0.3, -0.7, 0.6, 0.7, 1.0, 1.2]);
3805        }
3806        // The first directional light casts the shadow: put it first.
3807        if let Some(i) = lights.iter().position(|l| l[0] < 0.5) {
3808            lights.swap(0, i);
3809        }
3810        lights.truncate(16);
3811        let view = Mat4::look_at(eye, target, up);
3812        let view_proj = Mat4::perspective(fov, aspect, near, far).mul(&view);
3813
3814        // Meshes: geometry from the cache, uploaded once.
3815        let three = self.three.as_mut().unwrap();
3816        if three
3817            .attachments
3818            .as_ref()
3819            .is_none_or(|(c, _)| c.desc().width != dw || c.desc().height != dh)
3820        {
3821            three.attachments = Some((
3822                self.device.create_attachment(dw, dh, PixelFormat::Rgba16Float, SAMPLES),
3823                self.device
3824                    .create_attachment(dw, dh, PixelFormat::Depth32Float, SAMPLES),
3825            ));
3826        }
3827        struct MeshDraw {
3828            key: String,
3829            model: Mat4,
3830            params: Vec<f32>,
3831            texture: Option<usize>,
3832            /// Glass: transmission, index of refraction, thickness,
3833            /// dispersion.
3834            glass: Option<[f32; 4]>,
3835        }
3836        let mut draws_params: Vec<MeshDraw> = Vec::new();
3837        let mut scene_min = [f32::MAX; 3];
3838        let mut scene_max = [f32::MIN; 3];
3839        for &o in &meshes {
3840            let pn = &plan.nodes[o];
3841            let node = &doc.nodes[&pn.id];
3842            let key = scene3d::mesh_key(node);
3843            if !three.meshes.contains_key(&key) {
3844                let m = scene3d::build_mesh(&pn.id, node, &self.base_dir, &mut self.fonts)?;
3845                let vb = self
3846                    .device
3847                    .create_buffer(m.vertices.len() * 4, Some(f32_bytes(&m.vertices)));
3848                let ib = self
3849                    .device
3850                    .create_buffer(m.indices.len() * 4, Some(u32_bytes(&m.indices)));
3851                let mut lo = [f32::MAX; 3];
3852                let mut hi = [f32::MIN; 3];
3853                for v in m.vertices.chunks_exact(8) {
3854                    for k in 0..3 {
3855                        lo[k] = lo[k].min(v[k]);
3856                        hi[k] = hi[k].max(v[k]);
3857                    }
3858                }
3859                three
3860                    .meshes
3861                    .insert(key.clone(), (vb, ib, m.indices.len() as u32, [lo, hi]));
3862            }
3863            let p = Params {
3864                node,
3865                t: local_time(pn, t).0,
3866            };
3867            let model = p.model();
3868            // World bounds for fitting the shadow camera.
3869            let [lo, hi] = three.meshes[&key].3;
3870            for corner in 0..8 {
3871                let c = [
3872                    if corner & 1 == 0 { lo[0] } else { hi[0] },
3873                    if corner & 2 == 0 { lo[1] } else { hi[1] },
3874                    if corner & 4 == 0 { lo[2] } else { hi[2] },
3875                ];
3876                let m = &model.0;
3877                let w = [
3878                    m[0] * c[0] + m[1] * c[1] + m[2] * c[2] + m[3],
3879                    m[4] * c[0] + m[5] * c[1] + m[6] * c[2] + m[7],
3880                    m[8] * c[0] + m[9] * c[1] + m[10] * c[2] + m[11],
3881                ];
3882                for k in 0..3 {
3883                    scene_min[k] = scene_min[k].min(w[k]);
3884                    scene_max[k] = scene_max[k].max(w[k]);
3885                }
3886            }
3887            let normal = model.inverse_affine().transpose();
3888            let base = p.color("color", [0.8, 0.8, 0.8, 1.0]);
3889            let emissive = p.color("emissive", [0.0, 0.0, 0.0, 1.0]);
3890            let texture = pn.inputs.first().and_then(|&src| {
3891                g.textures
3892                    .iter()
3893                    .position(|ts| *ts == TexSource::Group(plan.group_of[src]))
3894            });
3895            let origin = dev(texture.map(|i| inputs[i].origin).unwrap_or([0.0, 0.0]));
3896            let mut prm = header(doc, t, self.view).to_vec();
3897            prm.extend(model.0);
3898            prm.extend(view_proj.0);
3899            prm.extend(normal.0);
3900            prm.extend(base);
3901            prm.extend([
3902                p.num("metallic", 0.0),
3903                p.num("roughness", 0.5),
3904                texture.is_some() as u8 as f32,
3905                p.num("opacity", 1.0),
3906            ]);
3907            prm.extend([emissive[0], emissive[1], emissive[2], 0.0]);
3908            prm.extend([eye[0], eye[1], eye[2], lights.len() as f32]);
3909            prm.extend([sky[0], sky[1], sky[2], ambient, ground[0], ground[1], ground[2], 0.0]);
3910            prm.extend([origin[0], origin[1], fw as f32 / v.px, fh as f32 / v.px]);
3911            let transmission = p.num("transmission", 0.0);
3912            let glass = (transmission > 0.0).then(|| {
3913                [
3914                    transmission.min(1.0),
3915                    p.num("ior", 1.45).max(1.0),
3916                    p.num("thickness", 0.5),
3917                    p.num("dispersion", 0.0),
3918                ]
3919            });
3920            draws_params.push(MeshDraw {
3921                key,
3922                model,
3923                params: prm,
3924                texture,
3925                glass,
3926            });
3927        }
3928
3929        // Shadow camera: orthographic along the shadow light, fitted to the
3930        // scene's bounding sphere.
3931        let shadow_light = lights
3932            .first()
3933            .filter(|l| l[0] < 0.5 && shadows_on && !draws_params.is_empty())
3934            .copied();
3935        let light_vp = shadow_light.map(|l| {
3936            let c = [
3937                (scene_min[0] + scene_max[0]) / 2.0,
3938                (scene_min[1] + scene_max[1]) / 2.0,
3939                (scene_min[2] + scene_max[2]) / 2.0,
3940            ];
3941            let r = ((0..3).map(|k| (scene_max[k] - scene_min[k]).powi(2)).sum::<f32>()).sqrt() / 2.0 + 1e-3;
3942            let len = (l[1] * l[1] + l[2] * l[2] + l[3] * l[3]).sqrt().max(1e-6);
3943            let d = [l[1] / len, l[2] / len, l[3] / len];
3944            let eye = [c[0] + d[0] * r * 2.0, c[1] + d[1] * r * 2.0, c[2] + d[2] * r * 2.0];
3945            let up = if d[1].abs() > 0.95 {
3946                [0.0, 0.0, 1.0]
3947            } else {
3948                [0.0, 1.0, 0.0]
3949            };
3950            let view = Mat4::look_at(eye, c, up);
3951            let (n, f) = (r * 0.5, r * 3.5);
3952            let ortho = Mat4([
3953                1.0 / r,
3954                0.0,
3955                0.0,
3956                0.0,
3957                0.0,
3958                1.0 / r,
3959                0.0,
3960                0.0,
3961                0.0,
3962                0.0,
3963                -1.0 / (f - n),
3964                -n / (f - n),
3965                0.0,
3966                0.0,
3967                0.0,
3968                1.0,
3969            ]);
3970            (ortho.mul(&view), 2.0 * r)
3971        });
3972        for d in &mut draws_params {
3973            match light_vp {
3974                Some((lvp, extent)) => {
3975                    d.params.extend(lvp.0);
3976                    // Biases scale with how much world one shadow texel covers.
3977                    let texel_world = extent / SHADOW as f32;
3978                    d.params
3979                        .extend([1.0, shadow_bias / SHADOW as f32, 1.0 / SHADOW as f32, shadow_strength]);
3980                    d.params.push(texel_world * 1.5);
3981                }
3982                None => {
3983                    d.params.extend(Mat4::IDENTITY.0);
3984                    d.params.extend([0.0; 5]);
3985                }
3986            }
3987            // [101..106] environment, [106..112] fog.
3988            d.params.extend([
3989                env.is_some() as u8 as f32,
3990                env_intensity,
3991                env_rotation,
3992                env_origin[0],
3993                env_origin[1],
3994                fog.is_some() as u8 as f32,
3995                fog.map(|f| f.0).unwrap_or(0.0),
3996                fog.map(|f| f.1).unwrap_or(1.0),
3997                fog_color[0],
3998                fog_color[1],
3999                fog_color[2],
4000            ]);
4001            // [112..114] blurred environment origin, [114..118] glass,
4002            // [118..120] unused.
4003            let g = d.glass.unwrap_or([0.0; 4]);
4004            d.params
4005                .extend([env_soft_origin[0], env_soft_origin[1], g[0], g[1], g[2], g[3], 0.0, 0.0]);
4006            for l in &lights {
4007                d.params.extend(l);
4008            }
4009        }
4010
4011        if active && let Some((lvp, _)) = light_vp {
4012            let shadow_params: Vec<Vec<f32>> = draws_params
4013                .iter()
4014                .map(|d| {
4015                    let mut p = header(doc, t, self.view).to_vec();
4016                    p.extend(d.model.0);
4017                    p.extend(lvp.0);
4018                    p
4019                })
4020                .collect();
4021            let shadow_draws: Vec<ultrafast_gpu::Draw> = draws_params
4022                .iter()
4023                .zip(&shadow_params)
4024                .map(|(d, p)| {
4025                    let (vb, ib, n, _) = &three.meshes[&d.key];
4026                    ultrafast_gpu::Draw {
4027                        pipeline: &three.shadow_pipeline,
4028                        params: p,
4029                        vertices: ultrafast_gpu::BufferBinding::Buffer(vb),
4030                        indices: ib,
4031                        index_count: *n,
4032                        texture: &three.white,
4033                        texture2: &three.white,
4034                        texture3: &three.white,
4035                        texture4: &three.white,
4036                    }
4037                })
4038                .collect();
4039            list.draw_pass(
4040                ultrafast_gpu::DrawTarget {
4041                    resolve: &three.shadow_map,
4042                    color: None,
4043                    depth: Some(&three.shadow_depth),
4044                    clear: [1.0, 1.0, 1.0, 1.0],
4045                },
4046                &shadow_draws,
4047            );
4048        }
4049        // Depth of field: a camera-distance pass, the sharp image, a gather.
4050        let aperture = rp.num("aperture", 0.0);
4051        let focus = if pn_has(&doc.nodes[&root.id], "focus") {
4052            rp.num("focus", 5.0)
4053        } else {
4054            ((eye[0] - target[0]).powi(2) + (eye[1] - target[1]).powi(2) + (eye[2] - target[2]).powi(2)).sqrt()
4055        };
4056        let dof_on = active && aperture > 0.25 && !draws_params.is_empty();
4057        if dof_on {
4058            if three
4059                .dof
4060                .as_ref()
4061                .is_none_or(|(d, _, _)| d.desc().width != dw || d.desc().height != dh)
4062            {
4063                let tex = |format| TextureDesc {
4064                    width: dw,
4065                    height: dh,
4066                    format,
4067                    cpu_readable: false,
4068                };
4069                three.dof = Some((
4070                    self.device.create_texture(tex(PixelFormat::R32Float)),
4071                    self.device.create_attachment(dw, dh, PixelFormat::Depth32Float, 1),
4072                    self.device.create_texture(tex(PixelFormat::Rgba16Float)),
4073                ));
4074            }
4075            let dist_params: Vec<Vec<f32>> = draws_params
4076                .iter()
4077                .map(|d| {
4078                    let mut p = header(doc, t, self.view).to_vec();
4079                    p.extend(d.model.0);
4080                    p.extend(view_proj.0);
4081                    p.extend(eye);
4082                    p
4083                })
4084                .collect();
4085            let (dist, dist_depth, _) = three.dof.as_ref().unwrap();
4086            let dist_draws: Vec<ultrafast_gpu::Draw> = draws_params
4087                .iter()
4088                .zip(&dist_params)
4089                .map(|(d, p)| {
4090                    let (vb, ib, n, _) = &three.meshes[&d.key];
4091                    ultrafast_gpu::Draw {
4092                        pipeline: &three.dist_pipeline,
4093                        params: p,
4094                        vertices: ultrafast_gpu::BufferBinding::Buffer(vb),
4095                        indices: ib,
4096                        index_count: *n,
4097                        texture: &three.white,
4098                        texture2: &three.white,
4099                        texture3: &three.white,
4100                        texture4: &three.white,
4101                    }
4102                })
4103                .collect();
4104            list.draw_pass(
4105                ultrafast_gpu::DrawTarget {
4106                    resolve: dist,
4107                    color: None,
4108                    depth: Some(dist_depth),
4109                    clear: [1.0e6, 0.0, 0.0, 1.0],
4110                },
4111                &dist_draws,
4112            );
4113        }
4114        let (color, depth) = three.attachments.as_ref().unwrap();
4115        // Glass draws after everything else, refracting the finished opaque
4116        // scene (which it samples instead of an albedo texture).
4117        let draws: Vec<ultrafast_gpu::Draw> = if active {
4118            draws_params
4119                .iter()
4120                .filter(|d| d.glass.is_none())
4121                .map(|d| {
4122                    let (vb, ib, n, _) = &three.meshes[&d.key];
4123                    ultrafast_gpu::Draw {
4124                        pipeline: &three.pipeline,
4125                        params: &d.params,
4126                        vertices: ultrafast_gpu::BufferBinding::Buffer(vb),
4127                        indices: ib,
4128                        index_count: *n,
4129                        texture: d.texture.map(|i| &inputs[i].tex).unwrap_or(&three.white),
4130                        texture2: &three.shadow_map,
4131                        texture3: env.map(|i| &inputs[i].tex).unwrap_or(&three.white),
4132                        texture4: env_soft.as_ref().map(|p| &p.tex).unwrap_or(&three.white),
4133                    }
4134                })
4135                .collect()
4136        } else {
4137            Vec::new()
4138        };
4139        let target_tex = if dof_on { &three.dof.as_ref().unwrap().2 } else { out };
4140        list.draw_pass(
4141            ultrafast_gpu::DrawTarget {
4142                resolve: target_tex,
4143                color: Some(color),
4144                depth: Some(depth),
4145                clear,
4146            },
4147            &draws,
4148        );
4149        if dof_on {
4150            let (dist, _, sharp) = three.dof.as_ref().unwrap();
4151            // Gather at half resolution, then mix back by each pixel's blur.
4152            // Both passes work in device texels: the header's frame is the
4153            // device's, and the aperture (the largest blur, frame px) is
4154            // measured in its texels.
4155            let half = TextureDesc {
4156                width: dw.div_ceil(2),
4157                height: dh.div_ceil(2),
4158                format: PixelFormat::Rgba16Float,
4159                cpu_readable: false,
4160            };
4161            let soft = self.pool.lease(&self.device, half);
4162            let (tf, dwf, dhf) = (t as f32, dw as f32, dh as f32);
4163            let ap = aperture / v.px;
4164            let p = [tf, 2.0, dwf, dhf, focus, ap, (aperture * 2.5).clamp(24.0, 64.0)];
4165            list.dispatch(&self.kernels.utility("k_dof"), &soft, &[sharp, dist], &p);
4166            let p = [tf, 1.0, dwf, dhf, focus, ap, 0.0, 2.0];
4167            list.dispatch(&self.kernels.utility("k_dof_mix"), out, &[sharp, &soft, dist], &p);
4168            self.pool.give_back(soft);
4169        }
4170        if active && draws_params.iter().any(|d| d.glass.is_some()) {
4171            let frame = TextureDesc {
4172                width: dw,
4173                height: dh,
4174                format: PixelFormat::Rgba16Float,
4175                cpu_readable: false,
4176            };
4177            let scene = self.pool.lease(&self.device, frame);
4178            list.dispatch(
4179                &self.kernels.utility("k_copy"),
4180                &scene,
4181                &[out],
4182                &header(doc, t, self.view),
4183            );
4184            let glass_tex = self.pool.lease(&self.device, frame);
4185            let three = self.three.as_ref().unwrap();
4186            let (color, depth) = three.attachments.as_ref().unwrap();
4187            let glass: Vec<ultrafast_gpu::Draw> = draws_params
4188                .iter()
4189                .filter(|d| d.glass.is_some())
4190                .map(|d| {
4191                    let (vb, ib, n, _) = &three.meshes[&d.key];
4192                    ultrafast_gpu::Draw {
4193                        pipeline: &three.pipeline,
4194                        params: &d.params,
4195                        vertices: ultrafast_gpu::BufferBinding::Buffer(vb),
4196                        indices: ib,
4197                        index_count: *n,
4198                        texture: &scene,
4199                        texture2: &three.shadow_map,
4200                        texture3: env.map(|i| &inputs[i].tex).unwrap_or(&three.white),
4201                        texture4: env_soft.as_ref().map(|p| &p.tex).unwrap_or(&three.white),
4202                    }
4203                })
4204                .collect();
4205            list.draw_pass(
4206                ultrafast_gpu::DrawTarget {
4207                    resolve: &glass_tex,
4208                    color: Some(color),
4209                    depth: Some(depth),
4210                    clear: [0.0; 4],
4211                },
4212                &glass,
4213            );
4214            let mut p = header(doc, t, self.view).to_vec();
4215            p.extend([0.0, 0.0, 0.0, 0.0]);
4216            list.dispatch(&self.kernels.utility("k_over_frames"), out, &[&glass_tex, &scene], &p);
4217            self.pool.give_back(scene);
4218            self.pool.give_back(glass_tex);
4219        }
4220        if let Some(p) = env_soft {
4221            self.pool.give_back(p.tex);
4222        }
4223        Ok(())
4224    }
4225
4226    /// Gaussian blur of `src` over the region its content covers plus the
4227    /// blur's reach. Large radii run at 1/2..1/8 resolution (the result is
4228    /// band-limited anyway) and are upsampled into the output, or with
4229    /// `keep_low` returned at that resolution (its readers sample it).
4230    /// Returns the placed result and its content bounds.
4231    #[allow(clippy::too_many_arguments)]
4232    fn encode_blur(
4233        &mut self,
4234        src: &Placed,
4235        src_bounds: ops::Rect,
4236        sigma: f32,
4237        prev: Option<Placed>,
4238        keep_low: bool,
4239        doc: &Document,
4240        t: f64,
4241        list: &mut CommandList,
4242    ) -> (Placed, ops::Rect) {
4243        let (fw, fh) = (doc.format.width as f64, doc.format.height as f64);
4244        let pad = (3.0 * sigma as f64).ceil() + 2.0;
4245        let r = intersect(
4246            [
4247                src_bounds[0] - pad,
4248                src_bounds[1] - pad,
4249                src_bounds[2] + pad,
4250                src_bounds[3] + pad,
4251            ],
4252            [-pad, -pad, fw + pad, fh + pad],
4253        );
4254        // The region on the device grid: texels of the view's size (px
4255        // frame px each), so a blur at a larger size keeps its detail.
4256        let px = self.view.px;
4257        let pxd = px as f64;
4258        let (x0, y0) = ((r[0] / pxd).floor(), (r[1] / pxd).floor());
4259        let (x1, y1) = ((r[2] / pxd).ceil().max(x0 + 1.0), (r[3] / pxd).ceil().max(y0 + 1.0));
4260        let (rw, rh) = ((x1 - x0) as u32, (y1 - y0) as u32);
4261        let bucket = |v: u32| (v.div_ceil(RASTER_BUCKET) * RASTER_BUCKET).max(RASTER_BUCKET);
4262        let desc = |w: u32, h: u32| TextureDesc {
4263            width: w,
4264            height: h,
4265            format: PixelFormat::Rgba16Float,
4266            cpu_readable: false,
4267        };
4268        // Downscale so each pass needs about 3 sigma of taps at >= 3 texels.
4269        let mut f = 1.0f32;
4270        while f < 8.0 && sigma / px / (f * 2.0) >= 3.0 {
4271            f *= 2.0;
4272        }
4273        let out_desc = if f > 1.0 && keep_low {
4274            desc(bucket(rw.div_ceil(f as u32)), bucket(rh.div_ceil(f as u32)))
4275        } else {
4276            desc(bucket(rw), bucket(rh))
4277        };
4278        let out = match prev {
4279            Some(p) if p.tex.desc() == out_desc => p.tex,
4280            Some(p) => {
4281                self.pool.give_back(p.tex);
4282                self.pool.lease(&self.device, out_desc)
4283            }
4284            None => self.pool.lease(&self.device, out_desc),
4285        };
4286        let blur = self.kernels.utility("k_blur_region");
4287        let resample = self.kernels.utility("k_resample");
4288        let hdr = header(doc, t, self.view);
4289        let (ox, oy) = ((x0 * pxd) as f32, (y0 * pxd) as f32);
4290        let p = |v: &[f32]| {
4291            let mut x = hdr.to_vec();
4292            x.extend_from_slice(v);
4293            x
4294        };
4295        let si = src.scale;
4296        // Texel sizes in frame px: the view's, and f of them downscaled.
4297        let (t1, tf) = (px, f * px);
4298        let scale = if f == 1.0 {
4299            let tmp = self.pool.lease(&self.device, out_desc);
4300            list.dispatch(
4301                &blur,
4302                &tmp,
4303                &[&src.tex],
4304                &p(&[sigma, 1.0, 0.0, t1, ox, oy, src.origin[0], src.origin[1], si]),
4305            );
4306            list.dispatch(&blur, &out, &[&tmp], &p(&[sigma, 0.0, 1.0, t1, ox, oy, ox, oy, t1]));
4307            self.pool.give_back(tmp);
4308            t1
4309        } else if keep_low {
4310            let b = self.pool.lease(&self.device, out_desc);
4311            list.dispatch(
4312                &resample,
4313                &out,
4314                &[&src.tex],
4315                &p(&[tf, ox, oy, src.origin[0], src.origin[1], si, 2.0]),
4316            );
4317            list.dispatch(&blur, &b, &[&out], &p(&[sigma, 1.0, 0.0, tf, ox, oy, ox, oy, tf]));
4318            list.dispatch(&blur, &out, &[&b], &p(&[sigma, 0.0, 1.0, tf, ox, oy, ox, oy, tf]));
4319            self.pool.give_back(b);
4320            tf
4321        } else {
4322            let low = desc(bucket(rw.div_ceil(f as u32)), bucket(rh.div_ceil(f as u32)));
4323            let a = self.pool.lease(&self.device, low);
4324            let b = self.pool.lease(&self.device, low);
4325            list.dispatch(
4326                &resample,
4327                &a,
4328                &[&src.tex],
4329                &p(&[tf, ox, oy, src.origin[0], src.origin[1], si, 2.0]),
4330            );
4331            list.dispatch(&blur, &b, &[&a], &p(&[sigma, 1.0, 0.0, tf, ox, oy, ox, oy, tf]));
4332            list.dispatch(&blur, &a, &[&b], &p(&[sigma, 0.0, 1.0, tf, ox, oy, ox, oy, tf]));
4333            list.dispatch(&resample, &out, &[&a], &p(&[t1, ox, oy, ox, oy, tf, 1.0]));
4334            self.pool.give_back(a);
4335            self.pool.give_back(b);
4336            t1
4337        };
4338        (
4339            Placed {
4340                tex: out,
4341                origin: [ox, oy],
4342                scale,
4343            },
4344            [x0 * pxd, y0 * pxd, x1 * pxd, y1 * pxd],
4345        )
4346    }
4347
4348    /// Draws a particle system into a texture sized to its bounds.
4349    #[allow(clippy::too_many_arguments)]
4350    fn encode_particles(
4351        &mut self,
4352        plan: &Plan,
4353        g: &plan::Group,
4354        sprite: Option<Placed>,
4355        prev: Option<Placed>,
4356        doc: &Document,
4357        t: f64,
4358        list: &mut CommandList,
4359    ) -> Result<Placed, RenderError> {
4360        let pn = &plan.nodes[g.root];
4361        let (lt, on) = local_time(pn, t);
4362        let node = &doc.nodes[&pn.id];
4363        let sys = if on && node.op == "swarm" {
4364            swarm::evaluate(&pn.id, node, lt, &mut self.fonts, &self.base_dir, &mut self.swarm_homes)?
4365        } else if on {
4366            particles::evaluate(&pn.id, node, lt)?
4367        } else {
4368            particles::Particles {
4369                data: Vec::new(),
4370                count: 0,
4371                bounds: [0.0; 4],
4372            }
4373        };
4374        if self.sprites.is_none() {
4375            let target = if self.device.backend() == "metal" {
4376                ultrafast_shaderc::Target::Metal
4377            } else {
4378                ultrafast_shaderc::Target::Spirv
4379            };
4380            let code = ultrafast_shaderc::Compiler::new()
4381                .compile_stages(
4382                    include_str!("../shaders/particles.slang"),
4383                    &[
4384                        ("vs_particle", ultrafast_shaderc::Stage::Vertex),
4385                        ("fs_particle", ultrafast_shaderc::Stage::Fragment),
4386                    ],
4387                    target,
4388                )
4389                .map_err(|e| RenderError::Setup(e.to_string()))?;
4390            let lib = self.device.library(&code.code)?;
4391            let over = self.device.draw_pipeline(
4392                &lib,
4393                "vs_particle",
4394                "fs_particle",
4395                1,
4396                false,
4397                ultrafast_gpu::Blend::Over,
4398                PixelFormat::Rgba16Float,
4399            )?;
4400            let add = self.device.draw_pipeline(
4401                &lib,
4402                "vs_particle",
4403                "fs_particle",
4404                1,
4405                false,
4406                ultrafast_gpu::Blend::Add,
4407                PixelFormat::Rgba16Float,
4408            )?;
4409            let one = 0x3c00u16.to_le_bytes();
4410            let white = self.device.upload_texture(
4411                TextureDesc {
4412                    width: 1,
4413                    height: 1,
4414                    format: PixelFormat::Rgba16Float,
4415                    cpu_readable: false,
4416                },
4417                &[one[0], one[1], one[0], one[1], one[0], one[1], one[0], one[1]],
4418            );
4419            self.sprites = Some((over, add, self.device.create_buffer(16, None), white));
4420        }
4421        // Under motion blur, drawn once, each particle blurs itself along its
4422        // path over the shutter (within the sampled waves the samples do).
4423        let span = match (&self.mb_frame, self.mb_sample) {
4424            (Some(f), None) if !self.mb_full => f.span,
4425            _ => 0.0,
4426        };
4427        let reach = if span > 0.0 {
4428            sys.data
4429                .chunks_exact(12)
4430                .map(|d| (d[8] as f64).hypot(d[9] as f64))
4431                .fold(0.0, f64::max)
4432                * span
4433                / 2.0
4434                + 1.0
4435        } else {
4436            0.0
4437        };
4438        // Region: the particles' bounds, clipped to a window around the
4439        // frame, in device texels (px frame px each).
4440        let px = self.view.px as f64;
4441        let (fw, fh) = (self.view.w as f64, self.view.h as f64);
4442        let b = [
4443            (sys.bounds[0] - reach) / px,
4444            (sys.bounds[1] - reach) / px,
4445            (sys.bounds[2] + reach) / px,
4446            (sys.bounds[3] + reach) / px,
4447        ];
4448        let r = if sys.count == 0 {
4449            [0.0, 0.0, 1.0, 1.0]
4450        } else {
4451            intersect(
4452                [b[0].floor(), b[1].floor(), b[2].ceil(), b[3].ceil()],
4453                [-fw, -fh, 2.0 * fw, 2.0 * fh],
4454            )
4455        };
4456        let (rw, rh) = (((r[2] - r[0]).max(1.0)) as u32, ((r[3] - r[1]).max(1.0)) as u32);
4457        let bucket = |v: u32| (v.div_ceil(RASTER_BUCKET) * RASTER_BUCKET).max(RASTER_BUCKET);
4458        let desc = TextureDesc {
4459            width: bucket(rw).min(8192),
4460            height: bucket(rh).min(8192),
4461            format: PixelFormat::Rgba16Float,
4462            cpu_readable: false,
4463        };
4464        let out = match prev {
4465            Some(p) if p.tex.desc() == desc => p.tex,
4466            Some(p) => {
4467                self.pool.give_back(p.tex);
4468                self.pool.lease(&self.device, desc)
4469            }
4470            None => self.pool.lease(&self.device, desc),
4471        };
4472        // Sequential indices 0..6n, grown as needed.
4473        let need = sys.count * 6 * 4;
4474        let (over, add, mut idx, white) = self.sprites.clone().unwrap();
4475        if idx.len() < need {
4476            let n = (sys.count * 6).next_power_of_two();
4477            let seq: Vec<u32> = (0..n as u32).collect();
4478            idx = self.device.create_buffer(n * 4, Some(u32_bytes(&seq)));
4479            self.sprites.as_mut().unwrap().2 = idx.clone();
4480        }
4481        let additive = ops::text(node, "blend") == Some("add");
4482        // Region origin and size in frame px: particles are placed there.
4483        let mut p = header(doc, t, self.view).to_vec();
4484        p.extend([
4485            (r[0] * px) as f32,
4486            (r[1] * px) as f32,
4487            (desc.width as f64 * px) as f32,
4488            (desc.height as f64 * px) as f32,
4489            span as f32,
4490        ]);
4491        let sprite_tex = sprite.as_ref().map(|s| &s.tex).unwrap_or(&white);
4492        let draws = if sys.count > 0 {
4493            vec![ultrafast_gpu::Draw {
4494                pipeline: if additive { &add } else { &over },
4495                params: &p,
4496                vertices: ultrafast_gpu::BufferBinding::Data(f32_bytes(&sys.data)),
4497                indices: &idx,
4498                index_count: (sys.count * 6) as u32,
4499                texture: sprite_tex,
4500                texture2: &white,
4501                texture3: &white,
4502                texture4: &white,
4503            }]
4504        } else {
4505            Vec::new()
4506        };
4507        list.draw_pass(
4508            ultrafast_gpu::DrawTarget {
4509                resolve: &out,
4510                color: None,
4511                depth: None,
4512                clear: [0.0; 4],
4513            },
4514            &draws,
4515        );
4516        Ok(Placed {
4517            tex: out,
4518            origin: [(r[0] * px) as f32, (r[1] * px) as f32],
4519            scale: px as f32,
4520        })
4521    }
4522
4523    /// Copies a placed texture into a frame-sized one (tier-0 `opacity` at 1).
4524    fn copy_placed(
4525        &self,
4526        src: &Placed,
4527        dst: &Texture,
4528        doc: &Document,
4529        t: f64,
4530        list: &mut CommandList,
4531    ) -> Result<(), RenderError> {
4532        let k = self.kernels.tier0_kernel("opacity").map_err(RenderError::Setup)?;
4533        let mut p = header(doc, t, self.view).to_vec();
4534        p.extend([1.0, src.origin[0], src.origin[1], src.scale]);
4535        list.dispatch(&k, dst, &[&src.tex], &p);
4536        Ok(())
4537    }
4538
4539    /// Flattened geometry for a raster node, rebuilt only when its key changes.
4540    fn geometry(
4541        &mut self,
4542        id: &str,
4543        doc: &Document,
4544        t: f64,
4545        outer: ops::Affine,
4546        key: u64,
4547    ) -> Result<Arc<geom::Geometry>, RenderError> {
4548        if let Some((k, _, _, g)) = self.geometry.get(id)
4549            && *k == key
4550        {
4551            return Ok(g.clone());
4552        }
4553        let node = &doc.nodes[id];
4554        let content = geom::content_key(node, t);
4555        let full = outer.mul(geom::placement_affine(node, t));
4556        // Moved, turned or shrunk but otherwise unchanged (the common
4557        // animated case): map the geometry as last built instead of building
4558        // it again (curves flattened for its size stay as fine; grown, it is
4559        // built again).
4560        if let Some((_, c, built_at, built)) = self.built.get(id)
4561            && *c == content
4562            && let Some(back) = built_at.inverse()
4563        {
4564            let m = full.mul(back);
4565            let same_linear = (0..4).all(|i| (built_at.0[i] - full.0[i]).abs() < 1e-9);
4566            // Largest stretch of the 2x2 part: its biggest singular value.
4567            let [a, b, cc, d, ..] = m.0;
4568            let (p, q) = ((a * a + b * b + cc * cc + d * d) / 2.0, (a * d - b * cc).abs());
4569            let stretch = (p + (p * p - q * q).max(0.0).sqrt()).sqrt();
4570            if same_linear || stretch <= 1.0005 {
4571                let g = Arc::new(if same_linear {
4572                    built.translated(full.0[4] - built_at.0[4], full.0[5] - built_at.0[5])
4573                } else {
4574                    built.transformed(m.0)
4575                });
4576                self.bounds.insert(id.to_string(), self.frame_bounds(g.bounds));
4577                self.geometry.insert(id.to_string(), (key, content, full, g.clone()));
4578                return Ok(g);
4579            }
4580        }
4581        let g = Arc::new(match node.op.as_str() {
4582            "text" => geom::text_node(id, node, &doc.format, t, outer, &mut self.fonts, &self.base_dir)?,
4583            _ => geom::path(id, node, &doc.format, t, outer)?,
4584        });
4585        self.bounds.insert(id.to_string(), self.frame_bounds(g.bounds));
4586        self.geometry.insert(id.to_string(), (key, content, full, g.clone()));
4587        self.built.insert(id.to_string(), (key, content, full, g.clone()));
4588        Ok(g)
4589    }
4590
4591    /// Bounds of geometry built on the device grid, in frame px (what
4592    /// picking, inspection and motion extents read).
4593    fn frame_bounds(&self, b: [f32; 4]) -> [f32; 4] {
4594        let px = self.view.px;
4595        [b[0] * px, b[1] * px, b[2] * px, b[3] * px]
4596    }
4597
4598    /// The color glyphs of `geo` for `k_raster_resolve`: their bitmaps put
4599    /// in the atlas (recorded on `list` before the resolve reads them), and
4600    /// twelve floats each (see `glyph_images` in lib.slang).
4601    fn glyph_records(&mut self, geo: &geom::Geometry, list: &mut CommandList) -> Vec<f32> {
4602        if geo.images.is_empty() {
4603            return Vec::new();
4604        }
4605        let put = self.kernels.utility("k_atlas_put");
4606        let atlas = self
4607            .glyph_atlas
4608            .get_or_insert_with(|| glyph_atlas::GlyphAtlas::new(&self.device));
4609        let mut place_all = |atlas: &mut glyph_atlas::GlyphAtlas| -> Vec<Option<[u32; 4]>> {
4610            geo.images
4611                .iter()
4612                .map(|im| atlas.place(&self.device, list, &put, &im.bitmap))
4613                .collect()
4614        };
4615        let generation = atlas.generation;
4616        let mut rects = place_all(atlas);
4617        // The atlas started over partway: place them all again.
4618        if atlas.generation != generation {
4619            rects = place_all(atlas);
4620        }
4621        let mut out = Vec::with_capacity(geo.images.len() * 12);
4622        for (im, rect) in geo.images.iter().zip(rects) {
4623            let Some(r) = rect else { continue };
4624            let m = im.xf;
4625            let det = m[0] * m[3] - m[1] * m[2];
4626            if det.abs() < 1e-12 {
4627                continue;
4628            }
4629            // Inverse of (u, v) -> (a u + c v + e, b u + d v + f).
4630            let (ia, ib, ic, id) = (m[3] / det, -m[1] / det, -m[2] / det, m[0] / det);
4631            let (ie, if_) = (-(ia * m[4] + ic * m[5]), -(ib * m[4] + id * m[5]));
4632            out.extend([
4633                ia as f32,
4634                ic as f32,
4635                ie as f32,
4636                im.weight,
4637                ib as f32,
4638                id as f32,
4639                if_ as f32,
4640                0.0,
4641                r[0] as f32,
4642                r[1] as f32,
4643                r[2] as f32,
4644                r[3] as f32,
4645            ]);
4646        }
4647        out
4648    }
4649
4650    /// Rasterizes geometry into a texture covering its bounds: clear the
4651    /// accumulator rows it touches, deposit segment areas, prefix-sum rows
4652    /// into coverage times color. Reuses `prev` when its size still fits.
4653    #[allow(clippy::too_many_arguments)]
4654    fn encode_raster(
4655        &mut self,
4656        geo: &geom::Geometry,
4657        prev: Option<Placed>,
4658        image_opacity: f32,
4659        framed: bool,
4660        doc: &Document,
4661        t: f64,
4662        list: &mut CommandList,
4663    ) -> Placed {
4664        // The region covers the geometry's bounds, even off-frame: content
4665        // placed outside the frame may be moved in by later warps, blurs or
4666        // shaders. It is limited to a window around the frame, to the frame
4667        // itself when nothing downstream looks outside it (layers zoomed far
4668        // past the frame then cost a frame, not nine), and to the texture
4669        // size limit.
4670        // In device texels: the geometry was built on the view's grid.
4671        let (fw, fh) = (self.view.w as i64, self.view.h as i64);
4672        let (wx0, wy0, wx1, wy1) = if framed {
4673            (0, 0, fw, fh)
4674        } else {
4675            (-fw, -fh, 2 * fw, 2 * fh)
4676        };
4677        let b = geo.bounds;
4678        let (mut x0, mut y0, mut x1, mut y1) = if geo.is_empty() || b[0] > b[2] {
4679            (0, 0, 1, 1)
4680        } else {
4681            (
4682                (b[0].floor() as i64 - 1).max(wx0),
4683                (b[1].floor() as i64 - 1).max(wy0),
4684                (b[2].ceil() as i64 + 2).min(wx1),
4685                (b[3].ceil() as i64 + 2).min(wy1),
4686            )
4687        };
4688        x1 = x1.min(x0 + MAX_RASTER);
4689        y1 = y1.min(y0 + MAX_RASTER);
4690        if x1 <= x0 || y1 <= y0 {
4691            (x0, y0, x1, y1) = (0, 0, 1, 1);
4692        }
4693        let (rw, rh) = ((x1 - x0) as usize, (y1 - y0) as usize);
4694        let bucket = |v: usize| ((v as u32).div_ceil(RASTER_BUCKET) * RASTER_BUCKET).max(RASTER_BUCKET);
4695        let desc = TextureDesc {
4696            width: bucket(rw),
4697            height: bucket(rh),
4698            format: PixelFormat::Rgba16Float,
4699            cpu_readable: false,
4700        };
4701        // The last texture is kept while the geometry fits and fills at
4702        // least four fifths of it (the resolve clears the rest, so slack
4703        // costs GPU time). Geometry that grows (zooming type) gets an eighth
4704        // more room, so it does not need a new texture on every frame and
4705        // motion-blur sample; each replaced one stays alive until the frames
4706        // using it finish.
4707        let area = |d: TextureDesc| d.width as u64 * d.height as u64;
4708        let tex = match prev {
4709            Some(p)
4710                if p.tex.desc().width >= desc.width
4711                    && p.tex.desc().height >= desc.height
4712                    && area(p.tex.desc()) * 4 <= 5 * area(desc) =>
4713            {
4714                p.tex
4715            }
4716            Some(p) => {
4717                let grew = p.tex.desc().width < desc.width || p.tex.desc().height < desc.height;
4718                self.pool.give_back(p.tex);
4719                let room = |v: usize, b: u32| {
4720                    if grew {
4721                        bucket(v + v / 8).min(MAX_RASTER as u32 + RASTER_BUCKET)
4722                    } else {
4723                        b
4724                    }
4725                };
4726                let grown = TextureDesc {
4727                    width: room(rw, desc.width),
4728                    height: room(rh, desc.height),
4729                    ..desc
4730                };
4731                self.pool.lease(&self.device, grown)
4732            }
4733            None => self.pool.lease(&self.device, desc),
4734        };
4735
4736        // One accumulator plane per color group (grown with room to spare:
4737        // a replaced buffer also lives until in-flight frames finish).
4738        let groups = geo.groups.len().max(1);
4739        let bytes = (rw + 2) * rh * 4 * groups;
4740        if self.acc.as_ref().is_none_or(|b| b.len() < bytes) {
4741            self.acc = Some(self.device.create_private_buffer(bytes + bytes / 2));
4742        }
4743        let acc = self.acc.clone().unwrap();
4744        list.clear_buffer_range(&acc, 0, bytes);
4745
4746        let hdr = header(doc, t, self.view);
4747        let n = geo.count();
4748        if n > 0 {
4749            let seg_bytes =
4750                unsafe { std::slice::from_raw_parts(geo.segments.as_ptr().cast::<u8>(), geo.segments.len() * 4) };
4751            let mut p = hdr.to_vec();
4752            p.extend([n as f32, rw as f32, rh as f32, x0 as f32, y0 as f32]);
4753            list.dispatch_ex(
4754                &self.kernels.utility("k_raster_lines"),
4755                &tex,
4756                &[],
4757                &p,
4758                Bindings {
4759                    buffers: &[BufferBinding::Buffer(&acc), BufferBinding::Data(seg_bytes)],
4760                    grid: Some((n as u32, 1)),
4761                    threadgroup: Some((64, 1)),
4762                },
4763            );
4764        }
4765        // Packed after the header: [4..8] color, [8] fill rule.
4766        let mut p = hdr.to_vec();
4767        p.push(self.scratch[8]);
4768        p.extend_from_slice(&self.scratch[4..8]);
4769        p.extend([rw as f32, rh as f32, groups as f32]);
4770        // Group colors: the node's own, or a group's color faded with it.
4771        let node_alpha = self.scratch[7];
4772        if geo.groups.is_empty() {
4773            p.extend_from_slice(&self.scratch[4..8]);
4774        }
4775        for g in &geo.groups {
4776            match g {
4777                None => p.extend_from_slice(&self.scratch[4..8]),
4778                Some(c) => {
4779                    let a = c[3] * node_alpha;
4780                    p.extend([c[0] * a, c[1] * a, c[2] * a, a]);
4781                }
4782            }
4783        }
4784        // Color glyphs: their bitmaps in the atlas, and per glyph the map
4785        // from frame px to its unit square.
4786        let records = self.glyph_records(geo, list);
4787        p.extend([(records.len() / 12) as f32, x0 as f32, y0 as f32, image_opacity]);
4788        let atlas = match (&self.glyph_atlas, records.is_empty()) {
4789            (Some(a), false) => a.tex.clone(),
4790            _ => self.placeholder.clone(),
4791        };
4792        let record_bytes: &[u8] = if records.is_empty() {
4793            &[0u8; 48]
4794        } else {
4795            unsafe { std::slice::from_raw_parts(records.as_ptr().cast::<u8>(), records.len() * 4) }
4796        };
4797        list.dispatch_ex(
4798            &self.kernels.utility("k_raster_resolve"),
4799            &tex,
4800            &[&atlas],
4801            &p,
4802            Bindings {
4803                buffers: &[BufferBinding::Buffer(&acc), BufferBinding::Data(record_bytes)],
4804                grid: Some((256, tex.desc().height)),
4805                threadgroup: Some((256, 1)),
4806            },
4807        );
4808        Placed {
4809            tex,
4810            origin: [x0 as f32 * self.view.px, y0 as f32 * self.view.px],
4811            scale: self.view.px,
4812        }
4813    }
4814
4815    /// Runs a fused group as a chain of tier-0 kernels (one per node, through
4816    /// pooled temporaries) while its fused kernel compiles.
4817    #[allow(clippy::too_many_arguments)]
4818    fn encode_fallback(
4819        &mut self,
4820        plan: &Plan,
4821        gi: usize,
4822        inputs: &[Placed],
4823        out: &Texture,
4824        doc: &Document,
4825        t: f64,
4826        list: &mut CommandList,
4827        res_info: &HashMap<&str, ResourceInfo>,
4828    ) -> Result<(), RenderError> {
4829        let g = &plan.groups[gi];
4830        let desc = out.desc();
4831        let mut value: HashMap<usize, Placed> = HashMap::new();
4832        let mut leased = Vec::new();
4833        let external =
4834            |ts: TexSource| -> Option<Placed> { g.textures.iter().position(|x| *x == ts).map(|p| inputs[p].clone()) };
4835        for &ni in &g.nodes {
4836            let pn = &plan.nodes[ni];
4837            let target = if ni == g.root {
4838                out.clone()
4839            } else {
4840                let tex = self.pool.lease(&self.device, desc);
4841                leased.push(tex.clone());
4842                tex
4843            };
4844            // Inputs: inlined nodes come from temporaries, materialized ones
4845            // are this group's external textures.
4846            let port_tex: Vec<Placed> = pn
4847                .inputs
4848                .iter()
4849                .map(|&src| {
4850                    value.get(&src).cloned().unwrap_or_else(|| {
4851                        external(TexSource::Group(plan.group_of[src])).unwrap_or(Placed {
4852                            tex: self.placeholder.clone(),
4853                            origin: [0.0, 0.0],
4854                            scale: 1.0,
4855                        })
4856                    })
4857                })
4858                .collect();
4859            let mut p = header(doc, t, self.view).to_vec();
4860            let info = if ops::uses_resource(pn.def) {
4861                res_info.get(pn.variant.as_str()).copied()
4862            } else {
4863                None
4864            };
4865            let (lt, on) = local_time(pn, t);
4866            ops::pack(pn.def, &pn.id, &doc.nodes[&pn.id], &doc.format, lt, info, &mut p)?;
4867            if ops::guarded(pn.def) {
4868                p.extend(ops::UNBOUNDED.map(|v| v as f32));
4869            }
4870            // Inactive nodes pass their destination/source through, or go
4871            // transparent if they have none.
4872            if !on {
4873                match ops::passthrough(pn.def, port_tex.len()) {
4874                    Some(i) => self.copy_placed(&port_tex[i], &target, doc, t, list)?,
4875                    None => list.dispatch(&self.kernels.utility("k_clear"), &target, &[], &p),
4876                }
4877                value.insert(
4878                    ni,
4879                    Placed {
4880                        tex: target,
4881                        origin: [0.0, 0.0],
4882                        scale: self.view.px,
4883                    },
4884                );
4885                continue;
4886            }
4887            match self.kernels.tier0(pn.def.func).cloned() {
4888                Some(t0) => {
4889                    let k = self.kernels.tier0_kernel(pn.def.func).map_err(RenderError::Setup)?;
4890                    let bound: Vec<Placed> = t0
4891                        .bindings
4892                        .iter()
4893                        .map(|&b| {
4894                            if b == usize::MAX {
4895                                external(TexSource::Resource(pn.variant.clone())).unwrap_or(Placed {
4896                                    tex: self.placeholder.clone(),
4897                                    origin: [0.0, 0.0],
4898                                    scale: 1.0,
4899                                })
4900                            } else {
4901                                port_tex[b].clone()
4902                            }
4903                        })
4904                        .collect();
4905                    for b in &bound {
4906                        p.extend(b.origin);
4907                        p.push(b.scale);
4908                    }
4909                    let refs: Vec<&Texture> = bound.iter().map(|b| &b.tex).collect();
4910                    list.dispatch(&k, &target, &refs, &p);
4911                }
4912                None => list.dispatch(&self.kernels.utility("k_clear"), &target, &[], &p),
4913            }
4914            value.insert(
4915                ni,
4916                Placed {
4917                    tex: target,
4918                    origin: [0.0, 0.0],
4919                    scale: self.view.px,
4920                },
4921            );
4922        }
4923        // Temporaries go back to the pool now: later frames reuse them in
4924        // queue order, after this frame's reads.
4925        for tex in leased {
4926            self.pool.give_back(tex);
4927        }
4928        Ok(())
4929    }
4930
4931    /// Mean squared error (8-bit sRGB units, over black) between frame `t`
4932    /// and `reference` (an RGBA8 sRGB texture of the frame's size), reduced
4933    /// on the GPU: only one partial sum per 16x16 tile is read back.
4934    pub fn frame_mse(&mut self, doc: &Document, t: f64, reference: &Texture) -> Result<f64, RenderError> {
4935        let (w, h) = self.frame_size(doc);
4936        let groups = (w.div_ceil(16) * h.div_ceil(16)) as usize;
4937        if self.diff_buf.as_ref().is_none_or(|b| b.len() < groups * 4) {
4938            self.diff_buf = Some(self.device.create_buffer(groups * 4, None));
4939        }
4940        let buf = self.diff_buf.clone().unwrap();
4941        let (sub, _) = self.submit_frame_with(doc, t, |o| {
4942            let mut p = o.header.to_vec();
4943            p.extend(o.origin);
4944            o.list.dispatch_ex(
4945                &o.kernels.utility("k_diff"),
4946                o.texture,
4947                &[o.texture, reference],
4948                &p,
4949                Bindings {
4950                    buffers: &[BufferBinding::Buffer(&buf)],
4951                    grid: Some((w, h)),
4952                    threadgroup: Some((16, 16)),
4953                },
4954            );
4955        })?;
4956        sub.wait()?;
4957        let sum: u64 = self
4958            .device
4959            .read_buffer(&buf, groups * 4)
4960            .chunks_exact(4)
4961            .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as u64)
4962            .sum();
4963        Ok(sum as f64 / (w as f64 * h as f64 * 3.0))
4964    }
4965
4966    /// Renders frame `t`, waits, and returns tightly packed sRGB RGBA8 pixels.
4967    pub fn render_rgba8(&mut self, doc: &Document, t: f64) -> Result<(Vec<u8>, FrameReport), RenderError> {
4968        let (sub, report) = self.submit_frame(doc, t, true)?;
4969        sub.wait()?;
4970        let mut px = self.read_export();
4971        clear_transparent(&mut px);
4972        Ok((px, report))
4973    }
4974
4975    /// Renders frame `t`, waits, and returns it tightly packed as `kind`.
4976    /// `opaque` flattens it over black, as a video without alpha shows it;
4977    /// otherwise alpha is straight.
4978    pub fn render_readback(
4979        &mut self,
4980        doc: &Document,
4981        t: f64,
4982        kind: Readback,
4983        opaque: bool,
4984    ) -> Result<(Vec<u8>, FrameReport), RenderError> {
4985        let format = match kind {
4986            Readback::Srgb8 => PixelFormat::Rgba8Unorm,
4987            Readback::SrgbHalf | Readback::LinearHalf => PixelFormat::Rgba16Float,
4988        };
4989        let mode = match (kind, opaque) {
4990            (Readback::LinearHalf, true) => 3.0,
4991            (Readback::LinearHalf, false) => 2.0,
4992            (_, true) => 1.0,
4993            (_, false) => 0.0,
4994        };
4995        let (w, h) = self.frame_size(doc);
4996        let ex = self.export_texture(w, h, format);
4997        let (sub, report) = self.submit_frame_with(doc, t, |o| {
4998            let mut p = o.header.to_vec();
4999            p.extend(o.origin);
5000            p.push(mode);
5001            o.list
5002                .dispatch(&o.kernels.utility("k_encode_srgb8"), &ex, &[o.texture], &p);
5003        })?;
5004        sub.wait()?;
5005        let mut px = self.read_export();
5006        if kind == Readback::Srgb8 && !opaque {
5007            clear_transparent(&mut px);
5008        }
5009        Ok((px, report))
5010    }
5011
5012    /// Renders frame `t` the way the player shows it: letterboxed into a
5013    /// `width` x `height` view with the timeline drawn over it (`hud`: on,
5014    /// playhead 0..1, loop in, loop out, emphasis, playing). RGBA8, sRGB.
5015    pub fn render_presented(
5016        &mut self,
5017        doc: &Document,
5018        t: f64,
5019        width: u32,
5020        height: u32,
5021        hud: [f32; 6],
5022        marks: &[([f32; 4], f32)],
5023    ) -> Result<Vec<u8>, RenderError> {
5024        let view = self.device.create_texture(TextureDesc {
5025            width,
5026            height,
5027            format: PixelFormat::Rgba8Unorm,
5028            cpu_readable: true,
5029        });
5030        let (fw, fh) = self.frame_size(doc);
5031        let (fw, fh) = (fw as f32, fh as f32);
5032        let (dw, dh) = (width as f32, height as f32);
5033        let s = (dw / fw).min(dh / fh);
5034        let rect = [(dw - fw * s) / 2.0, (dh - fh * s) / 2.0, fw * s, fh * s];
5035        let (sub, _) = self.submit_frame_with(doc, t, |o| {
5036            let mut p = o.header.to_vec();
5037            p.extend(o.origin);
5038            p.extend(rect);
5039            p.extend([dw, dh, 0.07, 0.07, 0.08]);
5040            p.extend(hud);
5041            // Edit outlines: frame-space bounds mapped into the view.
5042            p.push(marks.len().min(4) as f32);
5043            for k in 0..4 {
5044                match marks.get(k) {
5045                    Some((b, a)) => p.extend([
5046                        rect[0] + b[0] * s - 6.0,
5047                        rect[1] + b[1] * s - 6.0,
5048                        rect[0] + b[2] * s + 6.0,
5049                        rect[1] + b[3] * s + 6.0,
5050                        *a,
5051                    ]),
5052                    None => p.extend([0.0; 5]),
5053                }
5054            }
5055            o.list.dispatch_ex(
5056                &o.kernels.utility("k_present"),
5057                &view,
5058                &[o.texture],
5059                &p,
5060                ultrafast_gpu::Bindings {
5061                    grid: Some((width, height)),
5062                    ..Default::default()
5063                },
5064            );
5065        })?;
5066        sub.wait()?;
5067        Ok(self.device.readback(&view))
5068    }
5069
5070    /// Reads the last exported frame. Counted as a readback.
5071    pub fn read_export(&self) -> Vec<u8> {
5072        self.device
5073            .readback(self.export.as_ref().expect("no frame exported yet"))
5074    }
5075}
5076
5077/// Straight-alpha RGBA8 whose alpha rounded to 0 carries no color: the
5078/// encoder divides color by coverage, and coverage a hair above zero (the
5079/// tails exact-coverage rasterization leaves along a row) would otherwise
5080/// paint full color into transparent pixels, invisible when composited but
5081/// seen as streaks by anything that reads the color channels alone.
5082fn clear_transparent(px: &mut [u8]) {
5083    for p in px.chunks_exact_mut(4) {
5084        if p[3] == 0 {
5085            p[..3].fill(0);
5086        }
5087    }
5088}
5089
5090type Expansion = (Document, Vec<(String, String)>);
5091
5092/// Runs a node expansion on the document and inside every component (a
5093/// film pulled in as a component keeps its raymarch scenes and
5094/// transitions). None when nothing uses it.
5095/// Whether a node of the document or of one of its components is one of
5096/// `ops`.
5097fn uses_op(doc: &Document, ops: &[&str]) -> bool {
5098    let any = |nodes: &BTreeMap<String, ultrafast_graph::Node>| nodes.values().any(|n| ops.contains(&n.op.as_str()));
5099    any(&doc.nodes) || doc.components.values().any(|c| any(&c.nodes))
5100}
5101
5102fn expand_everywhere(
5103    doc: &Document,
5104    used_by: fn(&Document) -> bool,
5105    expand: fn(&Document) -> Expansion,
5106) -> Option<Expansion> {
5107    let as_doc = |c: &ultrafast_graph::Component| Document {
5108        version: doc.version,
5109        format: doc.format,
5110        output: c.output.clone(),
5111        nodes: c.nodes.clone(),
5112        components: Default::default(),
5113        revision: 0,
5114        structure_revision: 0,
5115        instance: 0,
5116    };
5117    let inner: Vec<&String> = doc
5118        .components
5119        .iter()
5120        .filter(|(_, c)| used_by(&as_doc(c)))
5121        .map(|(name, _)| name)
5122        .collect();
5123    if !used_by(doc) && inner.is_empty() {
5124        return None;
5125    }
5126    let (mut out, mut problems) = if used_by(doc) {
5127        expand(doc)
5128    } else {
5129        (doc.clone(), Vec::new())
5130    };
5131    for name in inner {
5132        let (d, p) = expand(&as_doc(&doc.components[name]));
5133        if let Some(c) = out.components.get_mut(name) {
5134            c.nodes = d.nodes;
5135        }
5136        problems.extend(p.into_iter().map(|(n, m)| (format!("{name}/{n}"), m)));
5137    }
5138    Some((out, problems))
5139}
5140
5141/// Whether rendering `doc` goes through [`Renderer::flattened`].
5142fn needs_flat(doc: &Document) -> bool {
5143    doc.needs_flatten()
5144        || builtins::used_by(doc)
5145        || svg::used_by(doc)
5146        || lottie::used_by(doc)
5147        || captions::used_by(doc)
5148        || follow::used_by(doc)
5149        || layout::used_by(doc)
5150        || blocks::used_by(doc)
5151        || code::used_by(doc)
5152        || raymarch::used_by(doc)
5153        || transitions::used_by(doc)
5154        || pushdown::wanted(doc)
5155        || !doc.components.is_empty()
5156}
5157
5158/// Kernel header: time, output texel size in frame pixels (the view's: 1
5159/// at the document's own size, 0.5 at twice it), frame width and height
5160/// (always the document's).
5161fn header(doc: &Document, t: f64, view: View) -> [f32; 4] {
5162    [t as f32, view.px, doc.format.width as f32, doc.format.height as f32]
5163}
5164
5165/// Loudness of `pcm` in a band, 120 values per second, with an instant
5166/// attack and a `release` (seconds), normalized so the loudest moment is 1.
5167fn audio_envelope(pcm: &ultrafast_media::audio::Pcm, band: &str, release: f64) -> Vec<f32> {
5168    let rate = ultrafast_media::audio::RATE as f32;
5169    let one_pole = |cut: f32| 1.0 - (-2.0 * std::f32::consts::PI * cut / rate).exp();
5170    let (lo_a, hi_a) = match band {
5171        "low" => (one_pole(160.0), 0.0),
5172        "mid" => (one_pole(2400.0), one_pole(250.0)),
5173        "high" => (1.0, one_pole(4500.0)),
5174        _ => (1.0, 0.0),
5175    };
5176    let win = (rate / 120.0) as usize;
5177    let mut out = Vec::with_capacity(pcm.frames() / win + 1);
5178    let (mut lp, mut hp_lp, mut acc, mut n) = (0.0f32, 0.0f32, 0.0f32, 0usize);
5179    for f in pcm.samples.chunks_exact(ultrafast_media::audio::CHANNELS) {
5180        let x = (f[0] + f[1]) * 0.5;
5181        lp += lo_a * (x - lp);
5182        hp_lp += hi_a * (lp - hp_lp);
5183        let y = lp - hp_lp;
5184        acc += y * y;
5185        n += 1;
5186        if n == win {
5187            out.push((acc / n as f32).sqrt());
5188            acc = 0.0;
5189            n = 0;
5190        }
5191    }
5192    // Peak follower: rises at once, falls over `release`.
5193    let fall = (-1.0 / (120.0 * release.max(1e-3) as f32)).exp();
5194    let mut e = 0.0f32;
5195    for v in out.iter_mut() {
5196        e = v.max(e * fall);
5197        *v = e;
5198    }
5199    let peak = out.iter().copied().fold(1e-9f32, f32::max);
5200    for v in out.iter_mut() {
5201        *v /= peak;
5202    }
5203    out
5204}
5205
5206/// Which groups can affect the output at time `t`: walk back from the
5207/// output; an inactive gated node keeps only its passthrough input alive.
5208fn live_groups(plan: &Plan, t: f64) -> Vec<bool> {
5209    let roots: Vec<usize> = plan.nodes.len().checked_sub(1).into_iter().collect();
5210    live_from(plan, t, &roots)
5211}
5212
5213/// Groups needed to evaluate `roots` (node indices) at time `t`.
5214fn live_from(plan: &Plan, t: f64, roots: &[usize]) -> Vec<bool> {
5215    let n = plan.nodes.len();
5216    let mut live = vec![false; n];
5217    let mut stack: Vec<usize> = roots.to_vec();
5218    while let Some(i) = stack.pop() {
5219        if live[i] {
5220            continue;
5221        }
5222        live[i] = true;
5223        let pn = &plan.nodes[i];
5224        if pn.gated && !local_time(pn, t).1 {
5225            if let Some(k) = ops::passthrough(pn.def, pn.inputs.len()) {
5226                stack.push(pn.inputs[k]);
5227            }
5228            continue;
5229        }
5230        stack.extend(pn.inputs.iter().copied());
5231    }
5232    plan.groups.iter().map(|g| g.nodes.iter().any(|&m| live[m])).collect()
5233}
5234
5235/// Local time of a node at composition time `t`, and whether it is active
5236/// (inside every visibility window of its timing chain).
5237/// Per blur group, the fused groups reading it when every reader samples
5238/// its inputs where it needs them (fused groups outside their loops, which
5239/// read layer textures texel for texel, and other blurs): such a blur can
5240/// stay at the reduced resolution it is computed at. Never the output.
5241fn low_readers(plan: &Plan) -> Vec<Option<Vec<usize>>> {
5242    let ng = plan.groups.len();
5243    (0..ng)
5244        .map(|g| {
5245            if plan.groups[g].kind != GroupKind::Blur || g + 1 == ng {
5246                return None;
5247            }
5248            let mut fused = Vec::new();
5249            for (c, gr) in plan.groups.iter().enumerate() {
5250                let bindings: Vec<usize> = (0..gr.textures.len())
5251                    .filter(|&b| gr.textures[b] == TexSource::Group(g))
5252                    .collect();
5253                if bindings.is_empty() {
5254                    continue;
5255                }
5256                match gr.kind {
5257                    GroupKind::Blur => {}
5258                    GroupKind::Fused
5259                        if !gr.runs.iter().any(|r| {
5260                            r.layers
5261                                .iter()
5262                                .any(|(_, _, l)| matches!(l, codegen::LayerRef::Texture(b) if bindings.contains(b)))
5263                        }) =>
5264                    {
5265                        fused.push(c)
5266                    }
5267                    _ => return None,
5268                }
5269            }
5270            Some(fused)
5271        })
5272        .collect()
5273}
5274
5275/// A group's output as its readers see it (through passthroughs).
5276fn placed_output(active: &Active, mut gi: usize) -> Placed {
5277    while let Some(src) = active.alias[gi] {
5278        gi = src;
5279    }
5280    match &active.raster[gi] {
5281        Some(p) => p.clone(),
5282        None => Placed {
5283            tex: active.slots[active.plan.groups[gi].output].clone(),
5284            origin: [0.0, 0.0],
5285            scale: active.view.px,
5286        },
5287    }
5288}
5289
5290/// How far (frame px) a `transform` node moves what it shows between local
5291/// times l0 and l1: the largest shift of any point of the frame.
5292fn transform_motion_px(node: &ultrafast_graph::Node, fmt: &ultrafast_graph::Format, l0: f64, l1: f64) -> f64 {
5293    let a0 = ops::transform_affine(node, fmt, l0);
5294    let a1 = ops::transform_affine(node, fmt, l1);
5295    let Some(back) = a0.inverse() else {
5296        return f64::INFINITY;
5297    };
5298    let m = a1.mul(back);
5299    let (w, h) = (fmt.width as f64, fmt.height as f64);
5300    [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)]
5301        .iter()
5302        .map(|&(x, y)| {
5303            let (u, v) = m.apply(x, y);
5304            (u - x).hypot(v - y)
5305        })
5306        .fold(0.0, f64::max)
5307}
5308
5309/// The absorbed transforms of a raster chain as one affine at time `t`. A
5310/// timed transform outside its window passes its source through, so it adds
5311/// nothing.
5312pub(crate) fn absorbed(plan: &Plan, doc: &Document, transforms: &[usize], t: f64) -> ops::Affine {
5313    transforms.iter().fold(ops::Affine::IDENTITY, |acc, &ti| {
5314        let tn = &plan.nodes[ti];
5315        match local_time(tn, t) {
5316            (lt, true) => ops::transform_affine(&doc.nodes[&tn.id], &doc.format, lt).mul(acc),
5317            (_, false) => acc,
5318        }
5319    })
5320}
5321
5322fn local_time(n: &plan::PlanNode, t: f64) -> (f64, bool) {
5323    match ultrafast_graph::resolve_chain(&n.chain, t) {
5324        Some(lt) => (lt, true),
5325        None => (t, false),
5326    }
5327}
5328
5329fn pn_has(node: &ultrafast_graph::Node, param: &str) -> bool {
5330    node.params.contains_key(param)
5331}
5332
5333fn f32_bytes(v: &[f32]) -> &[u8] {
5334    unsafe { std::slice::from_raw_parts(v.as_ptr().cast::<u8>(), std::mem::size_of_val(v)) }
5335}
5336
5337fn u32_bytes(v: &[u32]) -> &[u8] {
5338    unsafe { std::slice::from_raw_parts(v.as_ptr().cast::<u8>(), std::mem::size_of_val(v)) }
5339}
5340
5341/// Hash of every parameter a 3D pass depends on, for static caching.
5342fn scene_key(plan: &Plan, g: &plan::Group, doc: &Document, t: f64) -> u64 {
5343    use std::hash::{Hash, Hasher};
5344    let mut h = std::collections::hash_map::DefaultHasher::new();
5345    for &m in &g.nodes {
5346        let pn = &plan.nodes[m];
5347        let (lt, on) = local_time(pn, t);
5348        on.hash(&mut h);
5349        geom::geometry_key(&doc.nodes[&pn.id], lt, &ops::Affine::IDENTITY).hash(&mut h);
5350    }
5351    h.finish()
5352}
5353
5354/// Bounds of node `ni`'s output as seen inside group `g` (for guards).
5355/// Nodes outside the group are textures: their bounds are the placed
5356/// texture's extent.
5357fn subtree_bounds(
5358    plan: &Plan,
5359    g: &plan::Group,
5360    ni: usize,
5361    doc: &Document,
5362    t: f64,
5363    inputs: &[Placed],
5364    res_info: &HashMap<&str, ResourceInfo>,
5365    content: &[ops::Rect],
5366) -> ops::Rect {
5367    if !plan.in_group(plan.group_of[g.root], ni) {
5368        let gs = plan.group_of[ni];
5369        return match g.textures.iter().position(|ts| *ts == TexSource::Group(gs)) {
5370            Some(i) => intersect(extent(&inputs[i]), content[gs]),
5371            None => ops::UNBOUNDED,
5372        };
5373    }
5374    let pn = &plan.nodes[ni];
5375    let (lt, on) = local_time(pn, t);
5376    let mut buf = [ops::EMPTY; 8];
5377    let heap: Vec<ops::Rect>;
5378    let ins: &[ops::Rect] = if pn.inputs.len() <= buf.len() {
5379        for (k, &c) in pn.inputs.iter().enumerate() {
5380            buf[k] = subtree_bounds(plan, g, c, doc, t, inputs, res_info, content);
5381        }
5382        &buf[..pn.inputs.len()]
5383    } else {
5384        heap = pn
5385            .inputs
5386            .iter()
5387            .map(|&c| subtree_bounds(plan, g, c, doc, t, inputs, res_info, content))
5388            .collect();
5389        &heap
5390    };
5391    if !on {
5392        return ops::passthrough(pn.def, ins.len())
5393            .map(|i| ins[i])
5394            .unwrap_or(ops::EMPTY);
5395    }
5396    let info = if ops::uses_resource(pn.def) {
5397        res_info.get(pn.variant.as_str()).copied()
5398    } else {
5399        None
5400    };
5401    ops::bounds(pn.def, &doc.nodes[&pn.id], &doc.format, lt, ins, info)
5402}
5403
5404/// The earlier group whose output equals fused group `g`'s at `t`, when
5405/// all `g` would do is pass it through: inactive layers and effects pass
5406/// their source, a composite over an empty foreground its background.
5407#[allow(clippy::too_many_arguments)]
5408fn passthrough_group(
5409    plan: &Plan,
5410    g: &plan::Group,
5411    ni: usize,
5412    doc: &Document,
5413    t: f64,
5414    inputs: &[Placed],
5415    res_info: &HashMap<&str, ResourceInfo>,
5416    content: &[ops::Rect],
5417) -> Option<usize> {
5418    if !plan.in_group(plan.group_of[g.root], ni) {
5419        let gs = plan.group_of[ni];
5420        return g.textures.contains(&TexSource::Group(gs)).then_some(gs);
5421    }
5422    let pn = &plan.nodes[ni];
5423    if !local_time(pn, t).1 {
5424        let i = ops::passthrough(pn.def, pn.inputs.len())?;
5425        return passthrough_group(plan, g, pn.inputs[i], doc, t, inputs, res_info, content);
5426    }
5427    if pn.def.name == "over" && pn.inputs.len() == 2 {
5428        let fg = subtree_bounds(plan, g, pn.inputs[0], doc, t, inputs, res_info, content);
5429        if fg[0] >= fg[2] || fg[1] >= fg[3] {
5430            return passthrough_group(plan, g, pn.inputs[1], doc, t, inputs, res_info, content);
5431        }
5432    }
5433    None
5434}
5435
5436/// Frame extent of a placed texture.
5437fn extent(p: &Placed) -> ops::Rect {
5438    let d = p.tex.desc();
5439    let (x, y, s) = (p.origin[0] as f64, p.origin[1] as f64, p.scale as f64);
5440    [x, y, x + d.width as f64 * s, y + d.height as f64 * s]
5441}
5442
5443fn intersect(a: ops::Rect, b: ops::Rect) -> ops::Rect {
5444    [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]
5445}