The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Render faster, and hold the code to its declared types
Sina Atalay32413c0d40eb
diff --git a/AGENTS.md b/AGENTS.mdindex eb6f09f9..bb2fc705 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -31,10 +31,11 @@ manifests change, so there is no separate build step.## Rules- No `Any` in public signatures: keyword arguments are a `TypedDict` taken with `Unpack`.-- ty honors `# ty: ignore[rule]` and a bare `# type: ignore`, not `# type: ignore[code]`, and- an unused suppression is an error. ruff's formatter splits a line too long without its- trailing suppression and moves the suppression to the last line, so run `just check` after- `just format`.+- The checkers are ty and ruff. A declared type is trusted, not checked again as the code+ runs; a suppression is `# ty: ignore[rule]` (ty reads no `# type: ignore`), only where no+ type can say it, and an unused one is an error. ruff's formatter splits a line too long+ without its trailing suppression and moves the suppression to the last line, so run+ `just check` after `just format`.- Manim CE is the source of the API, not of the behavior: don't copy CE's behavior, or itsbugs, for compatibility. The corpus is the specification.- Measure before and after any change to the engine or the render path (`just bench main`);diff --git a/docs/content/changelog.md b/docs/content/changelog.mdindex 372a9252..de3ada1e 100644--- a/docs/content/changelog.md+++ b/docs/content/changelog.md@@ -25,6 +25,9 @@ The notable changes to ManimGX, release by release. The format follows### Changed+- Render faster: a graph's area reads its points' coordinates all at once, colors mix without numpy's overhead and are converted to OKLab once, and a family is listed in one pass. The frames are the same.+- Draw and encode a film's frames on a thread of their own: the scene's Python no longer waits for the GPU or the encoder, but for the pixels it asks for and its video's end. The videos are the same.+- Hold the API to its declared types, which ty checks where it is called: `add`, `ApplyFunction`, `SurroundingRectangle`, `ArcPolygonFromArcs` and `voices.Fal` no longer check them again as they run, and an `Animation` always has a mobject (`Wait` and a sound pass a plain `Mobject()`, where `None` stood). `interpolate` is typed by what it mixes (numbers, complex numbers or arrays), and `midpoint`, `center_of_mass`, `bezier`, `partial_bezier_points`, `subdivide_bezier` and `bezier_remap` by the array-likes they take (and `subdivide_bezier`'s count by numpy's integers too).- Show measured render times in a static benchmark chart.- Use a Markdown table for the benchmark comparison images.- Install ManimGX in the Quickstart with one command, `pip install manimgx`, and run `manimgx` directly throughout the docs.@@ -35,6 +38,8 @@ The notable changes to ManimGX, release by release. The format follows- Keep resources needed by queued video frames until their transparency retries finish, fixing render failures during cache cleanup ([#16](https://github.com/academa-labs/manimgx/issues/16)).- Draw a storyboard picture without dropping the frame the film holds back, fixing `manimgx render` failures ("unknown shape") under memory pressure.+- Draw a vectorized curve whose function gives a component as one number (`use_vectorized` with `lambda t: (t, t**2, 0)`), which failed with numpy's inhomogeneous-shape error.+- Name a partite layout's vertex that is not in the graph, and a vertex's keywords or an edge's `tip_config` that are not a mapping, in the error raised.- Preserve the benchmark comparison images' aspect ratios when PyPI narrows the README table.- Credit Filament, whose code the 3D lighting is adapted from, in the README and the wheels' third-party notices.diff --git a/docs/content/developer-guide/engine.md b/docs/content/developer-guide/engine.mdindex 6433545b..51eaae2f 100644--- a/docs/content/developer-guide/engine.md+++ b/docs/content/developer-guide/engine.md@@ -4,7 +4,8 @@ The engine is the Rust crate in [`rust/engine/`](https://github.com/academa-labscrates of the Rust workspace, [`rust/`](https://github.com/academa-labs/manimgx/tree/main/rust).maturin compiles it into the package as `manimgx._engine`, a Python extension module. Itdoes three things: it draws frames on the GPU, encodes them into an MP4, and typesets text.-Python decides what each frame shows; the engine makes the pixels. It also records a film as+Python decides what each frame shows; the engine makes the pixels, on a thread of its own, so+the scene goes on while its frames are drawn and encoded. It also records a film asa *take*, the same work written down, for ManimGX's player to play: one player, the same in awindow of its own on this machine's screen (`manimgx preview`) and on a page's canvas, wherethe engine itself, compiled to WebAssembly, is the player.@@ -39,9 +40,10 @@ The crate's dependencies do the heavy lifting:| File | What it holds || --- | --- || [`src/lib.rs`](https://github.com/academa-labs/manimgx/blob/main/rust/engine/src/lib.rs) | The crate: its builds (features), and the content key |-| [`src/render.rs`](https://github.com/academa-labs/manimgx/blob/main/rust/engine/src/render.rs) | The GPU's player (`Player`, Python's too): the store of shapes, a frame's passes, the GPU |+| [`src/render.rs`](https://github.com/academa-labs/manimgx/blob/main/rust/engine/src/render.rs) | The GPU's player (`Player`): the store of shapes, a frame's passes, the GPU || [`src/lavapipe.rs`](https://github.com/academa-labs/manimgx/blob/main/rust/engine/src/lavapipe.rs) | Mesa's lavapipe, which a Linux wheel bundles, loaded where no GPU driver is || [`src/python.rs`](https://github.com/academa-labs/manimgx/blob/main/rust/engine/src/python.rs) | The Python module: the `Player` and `Recorder` classes and the functions Python calls |+| [`src/stage.rs`](https://github.com/academa-labs/manimgx/blob/main/rust/engine/src/stage.rs) | Python's player on a thread of its own: its calls queued, and carried out in order || [`src/take.rs`](https://github.com/academa-labs/manimgx/blob/main/rust/engine/src/take.rs) | A take's messages, written and read || [`src/pack.rs`](https://github.com/academa-labs/manimgx/blob/main/rust/engine/src/pack.rs) | A take's arrays, each coded against the one it replaces || [`src/project.rs`](https://github.com/academa-labs/manimgx/blob/main/rust/engine/src/project.rs) | The projector: takes as they come, any frame of them drawn on demand, in bounded memory |@@ -92,11 +94,21 @@ code against it.extends a path, and `evict` forgets what no frame shows any more. A frame is then a viewand its records: `render` draws one and reads it back as RGBA, and `push` sends one tothe video that `begin_export` started and `end_export` finishes.+- **The player plays on a thread of its own.** A call is checked where Python makes it (a+ mistake in what it sends is a `ValueError` there), then queued, and carried out on the+ player's thread in the order it was made (`stage.rs`): so a scene does not wait for the+ GPU or x264, but for what it asks of them (pixels, from `render` or `push` with `capture`;+ the video, from `end_export`), and for room when the queue holds 256 MB not yet carried+ out. An eviction waits for the+ video's frames in flight that may be drawn again (their see-through fragments may+ overflow), so none loses what it draws. What goes wrong on the player's thread abandons+ the video and is raised at the next call. The player tells what it holds as it changes+ (`held`, `pressured`), so the feed's budget is read without waiting.- **A take is the same calls, written down.** `Recorder` takes the uploads a `Player` takes,then `frame` for each frame, and writes them as messages: a take, which the projector readsback (see [The player](#the-player) and [The browser](#the-browser)). A film given `take`records into one.-- **The GIL is released** while the engine draws and encodes, so other Python threads run.+- **The GIL is released** while a call waits, so other Python threads run.- **One GPU per process**, brought up on a thread of its own once the process knows it willdraw (`start_gpu`): a drawing command starts it before the rest of the command line loads,and a film with a video or frames as it begins. It comes up meanwhile, and the first framediff --git a/docs/content/developer-guide/project-management.md b/docs/content/developer-guide/project-management.mdindex 64172c0e..3c5a04ca 100644--- a/docs/content/developer-guide/project-management.md+++ b/docs/content/developer-guide/project-management.md@@ -181,9 +181,9 @@ rules follow:in ManimGX and in a user's scene alike. [`Style`][manimgx.drawing.paint.Style], in[`drawing/paint.py`](https://github.com/academa-labs/manimgx/blob/main/src/manimgx/drawing/paint.py),is the style keywords; [`Polygon`][manimgx.Polygon] takes `**kwargs: Unpack[Style]`.-- **Only live suppressions, in ty's form.** ty honors `# ty: ignore[rule]` and a bare- `# type: ignore`, not `# type: ignore[code]`. A suppression that suppresses nothing is an- error (`[tool.ty]` makes it one), so one that a fix has made useless fails the check.+- **Only live suppressions, in ty's form.** A suppression is `# ty: ignore[rule]`, only where+ no type can say it. `[tool.ty]` makes ty read no other form, and makes a suppression that+ suppresses nothing an error, so one that a fix has made useless fails the check.ruff's formatter does not count a trailing suppression comment in a line's width, but itsplits a line too long without one and moves the comment to the last line, so run`just check` after `just format`.diff --git a/pyproject.toml b/pyproject.tomlindex b1f6d2e3..3e169c6f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -262,9 +262,11 @@ include = ["src", "fonts", "docs", "scripts", "benchmarks", "tests"]exclude = ["benchmarks/scenes", "tests/integration/cases"][tool.ty.analysis]+# a suppression is ty's own, `# ty: ignore[rule]`: `# type: ignore` is a comment like any other+respect-type-ignore-comments = false# svgelements declares an ISO-8859-1 source encoding, which ty does not read (it sees an empty-# module); pyright checks its uses against the source. Manim CE is installed only with the `ce`-# group: the corpus's CE runner is checked the same with it or without it+# module): its names are Any. Manim CE is installed only with the `ce` group: the corpus's CE+# runner is checked the same with it or without itreplace-imports-with-any = ["svgelements", "svgelements.*", "manim", "manim.**"]allowed-unresolved-imports = ["manim", "manim.**"]diff --git a/rust/engine/src/export.rs b/rust/engine/src/export.rsindex ba7e7954..2c628784 100644--- a/rust/engine/src/export.rs+++ b/rust/engine/src/export.rs@@ -1,7 +1,7 @@//! A film's video, natively: each frame drawn, converted to NV12 on the GPU where it changed,//! read back and handed to x264 on a thread of its own (see `encode`), muxed into an MP4.-use std::collections::{HashSet, VecDeque};+use std::collections::VecDeque;use std::sync::Arc;use std::sync::atomic::{AtomicBool, Ordering};use std::time::Instant;@@ -42,18 +42,39 @@ impl Player {dirty}- pub(crate) fn push_frames(&mut self, gpu: &mut Gpu, frames: Vec<Frame>, repeat: u32, key: bool, capture: bool) -> Result<(), String> {+ /// The video's next frame, shown for `repeat` frames (`key`: a keyframe, where a player can+ /// start): drawn, and converted only where a change can touch it; with `capture`, its pixels+ /// too, the same draw's (RGBA8 rows, top to bottom), read into it once its retries are done.+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn push_frames(&mut self, gpu: &mut Gpu, frames: Vec<Frame>, repeat: u32, key: bool, capture: Option<&mut [u8]>) -> Result<(), String> {let mut export = self.export.take().ok_or("no export is open")?;let result = (|| {- // A pixel consumer waits for this frame. Settle older draws before making it,- // so their overflow retries cannot replace its captured pixels.- if capture {- while !export.pending.is_empty() { self.retire(gpu, &mut export)?; }+ // the frames before it first: their retries cannot then replace its pixels+ if capture.is_some() {+ while !export.pending.is_empty() {+ self.retire(gpu, &mut export)?;+ }}- self.push_into(gpu, &mut export, frames, repeat, key, capture)?;- if capture {+ self.push_into(gpu, &mut export, frames, repeat, key, capture.is_some())?;+ if let Some(into) = capture {+ self.retire(gpu, &mut export)?;+ self.read_pixels(gpu, into)?;+ }+ Ok(())+ })();+ self.export = Some(export);+ result+ }++ /// Settle the video's frames in flight that may be drawn again (their see-through fragments+ /// may overflow the lists: see `retire`), and those before them: nothing they draw may be+ /// evicted or changed until then.+ #[cfg(feature = "python")]+ pub(crate) fn settle(&mut self, gpu: &mut Gpu) -> Result<(), String> {+ let Some(mut export) = self.export.take() else { return Ok(()) };+ let result = (|| {+ while export.pending.iter().any(|p| p.kept.is_some()) {self.retire(gpu, &mut export)?;- self.map_pixels(gpu)?;}Ok(())})();@@ -83,13 +104,15 @@ impl Player {// read (see `retire`)let lists = self.lists.as_ref().filter(|_| composited && !listed.is_empty()).map(|l| l.capacity);self.convert(gpu, export, &mut command, &listed, slot, lists.is_some());- if capture { self.copy_pixels(&mut command); }+ if capture {+ self.copy_pixels(&mut command);+ }gpu.queue.submit(Some(command.finish()));export.map(slot, listed.len());gpu.device.poll(wgpu::PollType::Poll).map_err(|e| e.to_string())?;let first = export.previous.is_none();let kept = lists.map(|capacity| (frames.clone(), capacity));- export.pending.push_back(Pending { slot, listed, repeat, first, key, kept, capture, keys: None });+ export.pending.push_back(Pending { slot, listed, repeat, first, key, kept, capture });export.previous = frames.into_iter().last();export.drawn += 1;Ok(())@@ -147,7 +170,9 @@ impl Player {let (mut command, ..) = self.encode(gpu, frames)?;capacity = self.lists.as_ref().map_or(0, |l| l.capacity);self.convert(gpu, export, &mut command, &p.listed, p.slot, true);- if p.capture { self.copy_pixels(&mut command); }+ if p.capture {+ self.copy_pixels(&mut command);+ }gpu.queue.submit(Some(command.finish()));export.map(p.slot, p.listed.len());export.wait(&gpu.device, p.slot)?;@@ -172,8 +197,7 @@ pub(crate) struct Pending {first: bool,key: bool,kept: Option<(Vec<Frame>, u64)>, // a frame composited through the lists, and their capacity- keys: Option<Vec<u64>>, // retry dependencies, collected only when eviction asks- capture: bool, // copy its final successful draw for a simultaneous pixel consumer+ capture: bool, // its pixels are waited for: a retry copies them again}/// A video being written: each frame drawn, converted to NV12 where it changed, read back and@@ -197,9 +221,9 @@ pub(crate) struct Export {}impl Export {- #[allow(clippy::too_many_arguments)]- pub(crate) fn new(gpu: &Gpu, width: u32, height: u32, fps: u32, preset: &str, crf: f32, options: &[(String, String)], path: &str) -> Result<Self, String> {- let worker = encode::Worker::new(encode::Encoder::new(width, height, fps, preset, crf, options, path)?, width as usize, height as usize);+ /// A video of `width` × `height` frames, which `encoder` encodes.+ pub(crate) fn new(gpu: &Gpu, encoder: encode::Encoder, width: u32, height: u32) -> Result<Self, String> {+ let worker = encode::Worker::new(encoder, width as usize, height as usize);let size = (width.div_ceil(16) * height.div_ceil(16) * 384) as u64;let buffer = |label, usage| gpu.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: size + COUNT_BYTES, usage, mapped_at_creation: false });let convert = gpu.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {@@ -228,32 +252,6 @@ impl Export {})}- /// Keep uploads a queued retry may still draw, in any of its camera views. Cache each- /// pending frame's unique keys so repeated pressure does not rescan all its records.- pub(crate) fn evictable(&mut self, mut keys: Vec<u64>) -> Vec<u64> {- if keys.is_empty() {- return keys;- }- let candidates: HashSet<u64> = keys.iter().copied().collect();- let mut blocked = HashSet::new();- for pending in &mut self.pending {- if let Some((frames, _)) = &pending.kept {- let cached = pending.keys.get_or_insert_with(|| {- let mut unique = HashSet::new();- for frame in frames {- for slots in crate::take::slots(bytemuck::cast_slice(&frame.records)) {- unique.extend(slots.into_iter().filter(|&key| key != 0));- }- }- unique.into_iter().collect()- });- blocked.extend(cached.iter().copied().filter(|key| candidates.contains(key)));- }- }- keys.retain(|key| !blocked.contains(key));- keys- }-/// Read `slot` back once its frame is converted: its `listed` macroblocks, and the lists'/// count after them.fn map(&self, slot: usize, listed: usize) {diff --git a/rust/engine/src/lib.rs b/rust/engine/src/lib.rsindex 42ec1ba9..06001afa 100644--- a/rust/engine/src/lib.rs+++ b/rust/engine/src/lib.rs@@ -2,7 +2,8 @@//! (`typeset`).//!//! It is Python's extension module (`python`), which also reads sound (`audio`): natively with-//! the GPU, a film's video encoded by x264, its sound as AAC (`export`); in Pyodide without it,+//! the GPU, on a thread of its own (`stage`), a film's video encoded by x264, its sound as AAC+//! (`export`); in Pyodide without it,//! a scene's frames recorded as a take (`take`: its arrays coded against the ones they//! replace, `pack`). A take is played by the player (`player`: a projector of takes, `project`,//! on a clock, with a face, `chrome`, and a sound, `speaker`), the same on two screens: a window@@ -34,6 +35,8 @@ mod python;mod speaker;#[cfg(feature = "render")]mod render;+#[cfg(all(feature = "python", feature = "export"))]+mod stage;mod take;#[cfg(feature = "player")]mod text;diff --git a/rust/engine/src/python.rs b/rust/engine/src/python.rsindex 5d1f6eac..0e89c256 100644--- a/rust/engine/src/python.rs+++ b/rust/engine/src/python.rs@@ -1,6 +1,6 @@-//! The engine as Python's extension module, `manimgx._engine`: the player (natively: read back-//! or encoded to MP4), the recorder of a take (everywhere), the typesetter and the content keys,-//! over the core in `render`, `take` and `typeset`.+//! The engine as Python's extension module, `manimgx._engine`: the player (natively, on a thread+//! of its own: read back or encoded to MP4, see `stage`), the recorder of a take (everywhere), the+//! typesetter and the content keys, over the core in `render`, `take` and `typeset`.#[cfg(feature = "render")]use pyo3::exceptions::PyRuntimeError;@@ -9,7 +9,7 @@ use pyo3::prelude::*;use pyo3::types::PyBytes;#[cfg(feature = "render")]-use crate::render::{COUNT_BYTES, Player, count, with_gpu};+use crate::render::with_gpu;use crate::{CameraView, take};// One source for the native binding and every Python export entry point.@@ -19,181 +19,158 @@ const DEFAULT_ENCODER_CRF: f32 = 23.0;#[cfg(feature = "typeset")]pyo3::create_exception!(_engine, TypstError, pyo3::exceptions::PyException);-#[cfg(feature = "render")]+/// The GPU's player, natively: shapes, brushes and images uploaded once under a key, then frames+/// drawn — into a video, or read back. Each call is checked here and carried out on the player's+/// own thread, in order (see `stage`): so a call waits only for room in the queue, and for what it+/// asks for (pixels, the video's end).+#[cfg(feature = "export")]+#[pyclass(module = "manimgx._engine")]+struct Player {+ stage: crate::stage::Stage,+ width: u32,+ height: u32,+}++#[cfg(feature = "export")]impl Player {- /// The common readback for directly evaluated frames and recorded takes.- fn readback<'py>(&mut self, py: Python<'py>, frames: Vec<crate::render::Frame>) -> PyResult<Bound<'py, PyBytes>> {- py.detach(|| {- with_gpu(|gpu| -> Result<(), String> {- // drawn again while its see-through fragments overflow the lists- loop {- let (mut encoder, _, composited) = self.encode(gpu, &frames)?;- let t = self.targets.as_ref().expect("targets");- let pixels = t.padded as u64 * self.height as u64;- self.copy_pixels(&mut encoder);- let lists = self.lists.as_ref().filter(|_| composited);- if let Some(lists) = lists {- encoder.copy_buffer_to_buffer(&lists.appended, 0, &t.readback, pixels, Some(COUNT_BYTES));- }- let capacity = lists.map(|l| l.capacity);- gpu.queue.submit(Some(encoder.finish()));- self.map_pixels(gpu)?;- let Some(capacity) = capacity else { return Ok(()) };- let appended = count(&t.readback.slice(pixels..).get_mapped_range().map_err(|e| e.to_string())?);- if !self.overflowed(gpu, appended, capacity) {- return Ok(());- }- self.targets.as_ref().expect("targets").readback.unmap();- }- })?- })- .map_err(PyRuntimeError::new_err)?;- self.pixels(py)- }-- fn pixels<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {- let (width, height) = (self.width, self.height);- // copied once: from the mapped buffer into the bytes Python gets- let t = self.targets.as_ref().expect("targets");- let mapped = t.readback.slice(..t.padded as u64 * height as u64).get_mapped_range().map_err(|e| PyRuntimeError::new_err(e.to_string()))?;- let row = (width * 4) as usize;- let pixels = if t.padded as usize == row {- PyBytes::new(py, &mapped)- } else {- PyBytes::new_with(py, row * height as usize, |out| {- for (to, from) in out.chunks_exact_mut(row).zip(mapped.chunks_exact(t.padded as usize)) {- to.copy_from_slice(&from[..row]);- }- Ok(())- })?- };- drop(mapped);- t.readback.unmap();- Ok(pixels)+ /// Queue an upload made from what Python sent (a mistake in it is Python's: a ValueError).+ fn upload(&self, py: Python<'_>, made: Result<crate::render::Upload, String>) -> PyResult<()> {+ let upload = made.map_err(PyValueError::new_err)?;+ self.call(py, crate::stage::Call::Upload(upload))+ }++ fn call(&self, py: Python<'_>, call: crate::stage::Call) -> PyResult<()> {+ py.detach(|| self.stage.call(call)).map_err(PyRuntimeError::new_err)}}-#[cfg(feature = "render")]+#[cfg(feature = "export")]#[pymethods]impl Player {#[new]#[pyo3(signature = (width, height, samples = 4))]- fn py_new(width: u32, height: u32, samples: u32) -> Self {- Self::new(width, height, samples)+ fn new(width: u32, height: u32, samples: u32) -> Self {+ Self { stage: crate::stage::Stage::new(width, height, samples), width, height }}- #[pyo3(name = "add_path")]- fn py_add_path(&mut self, key: u64, points: &[u8], subpaths: &[u8], centroid_area: [f32; 6]) -> PyResult<()> {- self.add_path(key, points, subpaths, centroid_area).map_err(PyValueError::new_err)+ fn add_path(&self, py: Python<'_>, key: u64, points: &[u8], subpaths: &[u8], centroid_area: [f32; 6]) -> PyResult<()> {+ self.upload(py, crate::render::Upload::path(key, points, subpaths, centroid_area))}- #[pyo3(name = "add_points")]- fn py_add_points(&mut self, key: u64, vertices: &[u8]) -> PyResult<()> {- self.add_points(key, vertices).map_err(PyValueError::new_err)+ fn add_points(&self, py: Python<'_>, key: u64, vertices: &[u8]) -> PyResult<()> {+ self.upload(py, crate::render::Upload::points(key, vertices))}- #[pyo3(name = "add_mesh", signature = (key, points, uvs, normals, triangles, outline = 0, block = 0))]+ #[pyo3(signature = (key, points, uvs, normals, triangles, outline = 0, block = 0))]#[allow(clippy::too_many_arguments)]- fn py_add_mesh(&mut self, key: u64, points: &[u8], uvs: &[u8], normals: &[u8], triangles: &[u8], outline: u32, block: u32) -> PyResult<()> {- self.add_mesh(key, points, uvs, normals, triangles, outline, block).map_err(PyValueError::new_err)+ fn add_mesh(&self, py: Python<'_>, key: u64, points: &[u8], uvs: &[u8], normals: &[u8], triangles: &[u8], outline: u32, block: u32) -> PyResult<()> {+ self.upload(py, crate::render::Upload::mesh(key, points, uvs, normals, triangles, outline, block))}- #[pyo3(name = "grow_path", signature = (key, points, closed = false))]- fn py_grow_path(&mut self, key: u64, points: &[u8], closed: bool) -> PyResult<()> {- self.grow_path(key, points, closed).map_err(PyValueError::new_err)+ #[pyo3(signature = (key, points, closed = false))]+ fn grow_path(&self, py: Python<'_>, key: u64, points: &[u8], closed: bool) -> PyResult<()> {+ self.upload(py, crate::render::Upload::grow(key, points, closed))}- #[pyo3(name = "evict")]- fn py_evict(&mut self, keys: Vec<u64>) -> Vec<u64> {- self.evict(keys)+ fn add_rows(&self, py: Python<'_>, key: u64, rows: &[u8]) -> PyResult<()> {+ self.upload(py, crate::render::Upload::rows(key, rows))}- #[pyo3(name = "stored")]- fn py_stored(&self) -> (usize, usize) {- self.stored()+ fn add_texture(&self, py: Python<'_>, key: u64, width: u32, height: u32, rgba: &[u8]) -> PyResult<()> {+ self.upload(py, crate::render::Upload::texture(key, width, height, rgba))}- #[pyo3(name = "pressured")]- fn py_pressured(&self, py: Python<'_>) -> PyResult<bool> {- py.detach(|| with_gpu(|gpu| self.pressured(gpu))).map_err(PyRuntimeError::new_err)+ fn add_environment(&self, py: Python<'_>, id: u32, width: u32, height: u32, rgbe: &[u8]) -> PyResult<()> {+ self.upload(py, crate::render::Upload::environment(id, width, height, rgbe))}- #[pyo3(name = "add_rows")]- fn py_add_rows(&mut self, key: u64, rows: &[u8]) -> PyResult<()> {- self.add_rows(key, rows).map_err(PyValueError::new_err)+ /// Forget shapes, brushes and textures, once the video's frames in flight that may draw them+ /// again are settled.+ fn evict(&self, py: Python<'_>, keys: Vec<u64>) -> PyResult<()> {+ self.call(py, crate::stage::Call::Evict(keys))}- #[pyo3(name = "add_texture")]- fn py_add_texture(&mut self, key: u64, width: u32, height: u32, rgba: &[u8]) -> PyResult<()> {- self.add_texture(key, width, height, rgba).map_err(PyValueError::new_err)+ /// The bytes it holds alive (shapes, brushes, textures), as of the calls carried out.+ fn held(&self) -> usize {+ self.stage.held()}- #[pyo3(name = "add_environment")]- fn py_add_environment(&mut self, id: u32, width: u32, height: u32, rgbe: &[u8]) -> PyResult<()> {- self.add_environment(id, width, height, rgbe).map_err(PyValueError::new_err)+ /// Whether what it holds outgrows a GPU buffer's binding (each frame then binds only what it+ /// draws), as of the calls carried out.+ fn pressured(&self) -> bool {+ self.stage.pressured()}- /// Render one frame and read it back: RGBA8 rows, top to bottom. `cameras` are views drawn- /// first, each into a texture that textured meshes of later views sample by its key:- /// (key, width, height, view, records).+ /// Render one frame, as the calls before it left the player, and read it back: RGBA8 rows,+ /// top to bottom. `cameras` are views drawn first, each into a texture that textured meshes+ /// of later views sample by its key: (key, width, height, view, records).#[pyo3(signature = (view, records, cameras = Vec::new()))]- fn render<'py>(&mut self, py: Python<'py>, view: &[u8], records: &[u8], cameras: Vec<CameraView>) -> PyResult<Bound<'py, PyBytes>> {- let frames = self.views(view, records, cameras).map_err(PyValueError::new_err)?;- self.readback(py, frames)+ fn render<'py>(&self, py: Python<'py>, view: &[u8], records: &[u8], cameras: Vec<CameraView>) -> PyResult<Bound<'py, PyBytes>> {+ PyBytes::new_with(py, (4 * self.width * self.height) as usize, |into| {+ py.detach(|| {+ self.stage.now(|player| {+ let frames = player.views(view, records, cameras)?;+ with_gpu(|gpu| player.pixels(gpu, &frames, into))?+ })+ })+ .map_err(PyRuntimeError::new_err)+ })}- #[cfg(feature = "export")]/// Start an MP4 at `path`; frames follow with `push`, and `end_export` writes the file. x264/// runs at `preset` and `crf` (the module's defaults), with `options` — its own settings/// over those (as `-x264-params`, e.g. `[("keyint", "600")]`).#[pyo3(signature = (path, fps = 60, preset = DEFAULT_ENCODER_PRESET.to_string(), crf = DEFAULT_ENCODER_CRF, options = Vec::new()))]- fn begin_export(&mut self, py: Python<'_>, path: String, fps: u32, preset: String, crf: f32, options: Vec<(String, String)>) -> PyResult<()> {- if self.export.is_some() {- return Err(PyRuntimeError::new_err("an export is already open"));- }- let (width, height) = (self.width, self.height);- let export = py.detach(|| with_gpu(|gpu| crate::export::Export::new(gpu, width, height, fps, &preset, crf, &options, &path))?).map_err(PyRuntimeError::new_err)?;- self.export = Some(export);- Ok(())+ fn begin_export(&self, py: Python<'_>, path: String, fps: u32, preset: String, crf: f32, options: Vec<(String, String)>) -> PyResult<()> {+ let encoder = crate::encode::Encoder::new(self.width, self.height, fps, &preset, crf, &options, &path).map_err(PyRuntimeError::new_err)?;+ self.call(py, crate::stage::Call::Video(encoder))}- #[cfg(feature = "export")]/// The next frame of the video, shown for `repeat` frames: a view and its records, with- /// `cameras` drawn first (as for `render`); `key`: a keyframe, where a player can start.+ /// `cameras` drawn first (as for `render`); `key`: a keyframe, where a player can start. With+ /// `capture`, wait for its pixels and return them: the same draw's.#[pyo3(signature = (view, records, repeat = 1, cameras = Vec::new(), key = false, capture = false))]#[allow(clippy::too_many_arguments)]- fn push<'py>(&mut self, py: Python<'py>, view: &[u8], records: &[u8], repeat: u32, cameras: Vec<CameraView>, key: bool, capture: bool) -> PyResult<Option<Bound<'py, PyBytes>>> {- let frames = self.views(view, records, cameras).map_err(PyValueError::new_err)?;- py.detach(|| with_gpu(|gpu| self.push_frames(gpu, frames, repeat, key, capture))?).map_err(PyRuntimeError::new_err)?;- capture.then(|| self.pixels(py)).transpose()- }-- #[cfg(feature = "export")]- /// Abandon the video: nothing is written.- fn abort_export(&mut self) {- self.export = None;+ fn push<'py>(&self, py: Python<'py>, view: &[u8], records: &[u8], repeat: u32, cameras: Vec<CameraView>, key: bool, capture: bool) -> PyResult<Option<Bound<'py, PyBytes>>> {+ if !capture {+ let (view, records) = (view.to_vec(), records.to_vec());+ self.call(py, crate::stage::Call::Frame { view, records, cameras, repeat, key })?;+ return Ok(None);+ }+ let pixels = PyBytes::new_with(py, (4 * self.width * self.height) as usize, |into| {+ py.detach(|| {+ self.stage+ .now(|player| {+ let frames = player.views(view, records, cameras)?;+ with_gpu(|gpu| player.push_frames(gpu, frames, repeat, key, Some(into)))?+ })+ .inspect_err(|error| self.stage.fail(error))+ })+ .map_err(PyRuntimeError::new_err)+ })?;+ Ok(Some(pixels))+ }++ /// Abandon the video: nothing is written (once this returns, nor is any part of it).+ fn abort_export(&self, py: Python<'_>) {+ // a player stopped by a mistake has abandoned it already+ let _ = py.detach(|| {+ self.stage.now(|player| {+ player.export = None;+ Ok(())+ })+ });}- #[cfg(feature = "export")]/// Finish the video, with `sound` beside it if given — its soundtrack: float32 samples,/// interleaved, `channels` of them, at `rate` samples a second, encoded as AAC-LC at about/// `bitrate` bits a second. Returns (seconds since it began, of which in x264, fraction of/// macroblocks converted, bytes written).#[pyo3(signature = (sound = None, channels = 1, rate = 48000, bitrate = 192000))]- fn end_export(&mut self, py: Python<'_>, sound: Option<&[u8]>, channels: usize, rate: u32, bitrate: u32) -> PyResult<(f64, f64, f64, u64)> {- let mut export = self.export.take().ok_or_else(|| PyRuntimeError::new_err("no export is open"))?;- let pcm: Option<Vec<f32>> = sound.map(|s| crate::read(s, "sound")).transpose().map_err(PyValueError::new_err)?;- py.detach(|| {- // the sound is encoded while the encoder's thread finishes the pictures- let audio = pcm.map(|p| crate::aac::encode(&p, channels, rate, bitrate)).transpose()?;- with_gpu(|gpu| {- while !export.pending.is_empty() {- self.retire(gpu, &mut export)?;- }- export.finish(audio)- })?- })- .map_err(PyRuntimeError::new_err)+ fn end_export(&self, py: Python<'_>, sound: Option<&[u8]>, channels: usize, rate: u32, bitrate: u32) -> PyResult<crate::stage::Made> {+ let samples: Option<Vec<f32>> = sound.map(|s| crate::read(s, "sound")).transpose().map_err(PyValueError::new_err)?;+ let sound = samples.map(|samples| crate::stage::Sound { samples, channels, rate, bitrate });+ py.detach(|| self.stage.now(|player| crate::stage::end(player, sound))).map_err(PyRuntimeError::new_err)}}@@ -230,7 +207,11 @@ impl Replay {return Err(pyo3::exceptions::PyIndexError::new_err(format!("frame {frame} is outside the take's {} frames", self.take.frames)));}let frames = self.take.frame_views(frame as u32).map_err(PyValueError::new_err)?;- self.take.player.readback(py, frames)+ let take = &mut self.take;+ let (width, height) = take.size;+ PyBytes::new_with(py, (4 * width * height) as usize, |into| {+ py.detach(|| with_gpu(|gpu| take.player.pixels(gpu, &frames, into))?).map_err(PyRuntimeError::new_err)+ })}}@@ -324,14 +305,14 @@ impl Recorder {self.writer.grow(key, points, closed);}- /// The feeder may forget every key: a take keeps the uploads its frames need itself.- fn evict(&mut self, keys: Vec<u64>) -> Vec<u64> {- keys+ /// Nothing: a take keeps the uploads its frames need itself (its player holds what it draws).+ fn evict(&mut self, keys: Vec<u64>) {+ let _ = keys;}- /// (0, 0): a take holds nothing on a GPU (its player keeps what it is sent).- fn stored(&self) -> (usize, usize) {- (0, 0)+ /// 0: a take holds nothing on a GPU.+ fn held(&self) -> usize {+ 0}/// The next frame, shown for `repeat` frames: a view and its records, `cameras` drawn first@@ -533,9 +514,10 @@ fn _engine(m: &Bound<'_, PyModule>) -> PyResult<()> {m.add("DEFAULT_ENCODER_PRESET", DEFAULT_ENCODER_PRESET)?;m.add("DEFAULT_ENCODER_CRF", DEFAULT_ENCODER_CRF)?;m.add("TAKE_VERSION", take::VERSION)?;+ #[cfg(feature = "export")]+ m.add_class::<Player>()?;#[cfg(feature = "render")]{- m.add_class::<Player>()?;m.add_function(wrap_pyfunction!(start_gpu, m)?)?;m.py().import("atexit")?.call_method1("register", (wrap_pyfunction!(settle, m)?,))?;}diff --git a/rust/engine/src/render.rs b/rust/engine/src/render.rsindex 4dcaa794..8c842975 100644--- a/rust/engine/src/render.rs+++ b/rust/engine/src/render.rs@@ -1719,7 +1719,6 @@ enum Drawing {Vector(vector::Plan, Vec<(u32, Vec<Draw>)>),}-#[cfg_attr(feature = "python", pyo3::pyclass(module = "manimgx._engine"))]pub(crate) struct Player {pub(crate) width: u32,pub(crate) height: u32,@@ -1778,7 +1777,28 @@ fn run(pass: &mut wgpu::RenderPass, current: &mut *const wgpu::RenderPipeline, p}impl Player {- /// Copy the drawn frame's full-quality RGBA rows, independently of video conversion.+ /// Draw `frames` and read the last one back into `into`: RGBA8 rows, top to bottom (drawn+ /// again while its see-through fragments overflow the lists).+ #[cfg(feature = "python")]+ pub(crate) fn pixels(&mut self, gpu: &mut Gpu, frames: &[Frame], into: &mut [u8]) -> Result<(), String> {+ loop {+ let (mut encoder, _, composited) = self.encode(gpu, frames)?;+ self.copy_pixels(&mut encoder);+ let t = self.targets.as_ref().expect("targets");+ let lists = self.lists.as_ref().filter(|_| composited);+ if let Some(lists) = lists {+ encoder.copy_buffer_to_buffer(&lists.appended, 0, &t.readback, t.padded as u64 * self.height as u64, Some(COUNT_BYTES));+ }+ let capacity = lists.map(|l| l.capacity);+ gpu.queue.submit(Some(encoder.finish()));+ let appended = self.read_pixels(gpu, into)?;+ if !capacity.is_some_and(|capacity| self.overflowed(gpu, appended, capacity)) {+ return Ok(());+ }+ }+ }++ /// Copy the frame drawn into the readback buffer: its RGBA rows (padded).#[cfg(any(feature = "python", feature = "export"))]pub(crate) fn copy_pixels(&self, encoder: &mut wgpu::CommandEncoder) {let t = self.targets.as_ref().expect("targets");@@ -1789,11 +1809,27 @@ impl Player {);}+ /// The readback buffer, read once the GPU is done: the RGBA8 rows `copy_pixels` copied, top+ /// to bottom, into `into` (a frame's bytes); the see-through count copied after them (if one+ /// was).#[cfg(any(feature = "python", feature = "export"))]- pub(crate) fn map_pixels(&self, gpu: &Gpu) -> Result<(), String> {- self.targets.as_ref().expect("targets").readback.slice(..).map_async(wgpu::MapMode::Read, |_| {});+ pub(crate) fn read_pixels(&self, gpu: &Gpu, into: &mut [u8]) -> Result<u64, String> {+ let (row, height) = ((self.width * 4) as usize, self.height as usize);+ if into.len() != row * height {+ return Err(format!("a frame of {}x{} takes {} bytes, not {}", self.width, self.height, row * height, into.len()));+ }+ let t = self.targets.as_ref().expect("targets");+ t.readback.slice(..).map_async(wgpu::MapMode::Read, |_| {});gpu.device.poll(wgpu::PollType::wait_indefinitely()).map_err(|e| e.to_string())?;- Ok(())+ let mapped = t.readback.slice(..).get_mapped_range().map_err(|e| e.to_string())?;+ let (padded, rows) = (t.padded as usize, t.padded as usize * height);+ for (to, from) in into.chunks_exact_mut(row).zip(mapped[..rows].chunks_exact(padded)) {+ to.copy_from_slice(&from[..row]);+ }+ let appended = count(&mapped[rows..]);+ drop(mapped);+ t.readback.unmap();+ Ok(appended)}/// Bring the GPU up to date: images made textures, the store's arrays sent — only what was@@ -2596,6 +2632,100 @@ impl Player {}}+/// An upload, checked and made as the store takes it from what its caller sends: so it can be+/// made where it is sent from and stored where the player draws (`stage`).+pub(crate) enum Upload {+ Path { key: u64, points: Vec<[f64; 3]>, ranges: Vec<[u32; 4]>, centroid: [f32; 3], area: [f32; 3] },+ Points { key: u64, vertices: Vec<[f32; 4]> },+ Mesh { key: u64, vertices: Vec<[f32; 4]>, extras: Vec<[f32; 4]>, triangles: Vec<u32>, outline: u32, block: u32 },+ Rows { key: u64, rows: Vec<[f32; 4]> },+ Texture { key: u64, width: u32, height: u32, rgba: Vec<u8> },+ Grow { key: u64, tail: Vec<[f64; 3]>, closed: bool },+ Environment { id: u32, width: u32, height: u32, rgbe: Vec<u8> },+}++impl Upload {+ /// A path: its control points (float64 x, y, z; four per curve), its subpaths (u32 first+ /// curve, end curve, closed, 0) and (centroid, Newell area vector) of its control points.+ pub(crate) fn path(key: u64, points: &[u8], subpaths: &[u8], centroid_area: [f32; 6]) -> Result<Self, String> {+ check_key(key)?;+ let points: Vec<[f64; 3]> = read(points, "points")?;+ let ranges: Vec<[u32; 4]> = read(subpaths, "subpaths")?;+ if !points.len().is_multiple_of(4) || ranges.iter().any(|r| r[0] >= r[1] || r[1] as usize > points.len() / 4) {+ return Err("a path is whole curves, its subpaths ranges of them".into());+ }+ let [cx, cy, cz, ax, ay, az] = centroid_area;+ Ok(Upload::Path { key, points, ranges, centroid: [cx, cy, cz], area: [ax, ay, az] })+ }++ /// A point cloud: positions (x, y, z, 0).+ pub(crate) fn points(key: u64, vertices: &[u8]) -> Result<Self, String> {+ check_key(key)?;+ Ok(Upload::Points { key, vertices: read(vertices, "vertices")? })+ }++ /// A mesh as its object defines it: its points and texture coordinates (float64 x, y, z and+ /// u, v), its triangles (three u32 each) and its normals (float64) when its geometry gives+ /// them — a surface's spline, a flat face — or none, for the area-weighted sum of each+ /// vertex's faces. `outline` > 2: the vertices are faces — blocks of `block` (by default+ /// `outline`), each beginning with a closed loop of `outline` — stroked when drawn.+ pub(crate) fn mesh(key: u64, points: &[u8], uvs: &[u8], normals: &[u8], triangles: &[u8], outline: u32, block: u32) -> Result<Self, String> {+ check_key(key)?;+ let mesh = Mesh::new(points, uvs, normals, triangles, outline, block)?;+ let vertices = mesh.points.iter().zip(&*mesh.uvs).map(|(p, uv)| [p[0] as f32, p[1] as f32, p[2] as f32, uv[1] as f32]).collect();+ let extras = mesh.normals.iter().zip(&*mesh.uvs).map(|(n, uv)| [n[0] as f32, n[1] as f32, n[2] as f32, uv[0] as f32]).collect();+ Ok(Upload::Mesh { key, vertices, extras, triangles: mesh.triangles.into_owned(), outline: mesh.outline, block: mesh.block })+ }++ /// A brush of several rows (RGBA): gradient stops, or one color per point or vertex.+ pub(crate) fn rows(key: u64, rows: &[u8]) -> Result<Self, String> {+ check_key(key)?;+ Ok(Upload::Rows { key, rows: read(rows, "rows")? })+ }++ /// An image: straight RGBA8 rows, top to bottom (premultiplied on the way in).+ pub(crate) fn texture(key: u64, width: u32, height: u32, rgba: &[u8]) -> Result<Self, String> {+ check_key(key)?;+ if rgba.len() != (width * height * 4) as usize {+ return Err("texture size does not match its bytes".into());+ }+ Ok(Upload::Texture { key, width, height, rgba: rgba.to_vec() })+ }++ /// Curves appended to a path: its last subpath continues with these control points (float64+ /// x, y, z; four per curve); `closed`: whether that subpath now ends where it begins.+ pub(crate) fn grow(key: u64, points: &[u8], closed: bool) -> Result<Self, String> {+ let tail: Vec<[f64; 3]> = read(points, "points")?;+ if !tail.len().is_multiple_of(4) {+ return Err("a path grows by whole curves".into());+ }+ Ok(Upload::Grow { key, tail, closed })+ }++ /// An environment (an `EnvironmentLight`'s picture: equirectangular RGBE rows, top to+ /// bottom), the id its views' lights give it.+ pub(crate) fn environment(id: u32, width: u32, height: u32, rgbe: &[u8]) -> Result<Self, String> {+ if rgbe.len() != (width * height * 4) as usize || width == 0 || height == 0 {+ return Err("environment size does not match its bytes".into());+ }+ Ok(Upload::Environment { id, width, height, rgbe: rgbe.to_vec() })+ }++ /// The bytes it holds.+ #[cfg(all(feature = "python", feature = "export"))]+ pub(crate) fn size(&self) -> usize {+ match self {+ Upload::Path { points, ranges, .. } => size_of_val(&points[..]) + size_of_val(&ranges[..]),+ Upload::Points { vertices, .. } => size_of_val(&vertices[..]),+ Upload::Mesh { vertices, extras, triangles, .. } => size_of_val(&vertices[..]) + size_of_val(&extras[..]) + size_of_val(&triangles[..]),+ Upload::Rows { rows, .. } => size_of_val(&rows[..]),+ Upload::Texture { rgba, .. } => rgba.len(),+ Upload::Grow { tail, .. } => size_of_val(&tail[..]),+ Upload::Environment { rgbe, .. } => rgbe.len(),+ }+ }+}+/// What every host asks of a player: shapes, brushes and images uploaded once under a key, then/// frames drawn from views and records (see `python` and `web`).impl Player {@@ -2623,59 +2753,51 @@ impl Player {/// A path: its control points (float64 x, y, z; four per curve), its subpaths (u32 first/// curve, end curve, closed, 0) and (centroid, Newell area vector) of its control points.pub(crate) fn add_path(&mut self, key: u64, points: &[u8], subpaths: &[u8], centroid_area: [f32; 6]) -> Result<(), String> {- check_key(key)?;- let points: Vec<[f64; 3]> = read(points, "points")?;- let ranges: Vec<[u32; 4]> = read(subpaths, "subpaths")?;- if !points.len().is_multiple_of(4) || ranges.iter().any(|r| r[0] >= r[1] || r[1] as usize > points.len() / 4) {- return Err("a path is whole curves, its subpaths ranges of them".into());- }- let [cx, cy, cz, ax, ay, az] = centroid_area;- self.store.add_path(key, &points, &ranges, [cx, cy, cz], [ax, ay, az]);- Ok(())+ self.upload(Upload::path(key, points, subpaths, centroid_area)?)}/// A point cloud: positions (x, y, z, 0).pub(crate) fn add_points(&mut self, key: u64, vertices: &[u8]) -> Result<(), String> {- check_key(key)?;- self.store.add_points(key, &read(vertices, "vertices")?);- Ok(())+ self.upload(Upload::points(key, vertices)?)}- /// A mesh as its object defines it: its points and texture coordinates (float64 x, y, z and- /// u, v), its triangles (three u32 each) and its normals (float64) when its geometry gives- /// them — a surface's spline, a flat face — or none, for the area-weighted sum of each- /// vertex's faces. `outline` > 2: the vertices are faces — blocks of `block` (by default- /// `outline`), each beginning with a closed loop of `outline` — stroked when drawn.+ /// A mesh (see `Upload::mesh`).#[allow(clippy::too_many_arguments)]pub(crate) fn add_mesh(&mut self, key: u64, points: &[u8], uvs: &[u8], normals: &[u8], triangles: &[u8], outline: u32, block: u32) -> Result<(), String> {- check_key(key)?;- let mesh = Mesh::new(points, uvs, normals, triangles, outline, block)?;- let v: Vec<[f32; 4]> = mesh.points.iter().zip(&*mesh.uvs).map(|(p, uv)| [p[0] as f32, p[1] as f32, p[2] as f32, uv[1] as f32]).collect();- let e: Vec<[f32; 4]> = mesh.normals.iter().zip(&*mesh.uvs).map(|(n, uv)| [n[0] as f32, n[1] as f32, n[2] as f32, uv[0] as f32]).collect();- self.store.add_mesh(key, &v, &e, &mesh.triangles, mesh.outline, mesh.block);- Ok(())+ self.upload(Upload::mesh(key, points, uvs, normals, triangles, outline, block)?)}- /// Append curves to a path: its last subpath continues with these control points (float64- /// x, y, z; four per curve); `closed`: whether that subpath now ends where it begins.+ /// Append curves to a path (see `Upload::grow`).pub(crate) fn grow_path(&mut self, key: u64, points: &[u8], closed: bool) -> Result<(), String> {- let tail: Vec<[f64; 3]> = read(points, "points")?;- if !tail.len().is_multiple_of(4) {- return Err("a path grows by whole curves".into());+ self.upload(Upload::grow(key, points, closed)?)+ }++ /// Store an upload made ready for it.+ pub(crate) fn upload(&mut self, upload: Upload) -> Result<(), String> {+ match upload {+ Upload::Path { key, points, ranges, centroid, area } => self.store.add_path(key, &points, &ranges, centroid, area),+ Upload::Points { key, vertices } => self.store.add_points(key, &vertices),+ Upload::Mesh { key, vertices, extras, triangles, outline, block } => self.store.add_mesh(key, &vertices, &extras, &triangles, outline, block),+ Upload::Rows { key, rows } => self.store.add_rows(key, &rows),+ Upload::Texture { key, width, height, rgba } => {+ if rgba.chunks_exact(4).all(|p| p[3] == 255) {+ self.opaque_images.insert(key, ());+ }+ self.images.insert(key, (width, height, rgba));+ }+ Upload::Grow { key, tail, closed } => return self.store.grow_path(key, &tail, closed),+ Upload::Environment { id, width, height, rgbe } => {+ self.environments.insert(id, environment::Environment::new(width, height, rgbe));+ }}- self.store.grow_path(key, &tail, closed)+ Ok(())}#[cfg(any(feature = "python", feature = "player"))]- /// Forget shapes, brushes and textures, except those queued export retries still need.- /// Return the accepted keys (unknown keys are ignored); the shapes' space is reused once- /// most of the store is dead. Refused keys may be offered again after their frames retire.+ /// Forget shapes, brushes and textures (unknown keys are ignored): the shapes' space is+ /// reused once most of the store is dead. A video's frames in flight that may be drawn again+ /// must be settled first (`settle`).pub(crate) fn evict(&mut self, keys: Vec<u64>) -> Vec<u64> {- #[cfg(feature = "export")]- let keys = match &mut self.export {- Some(export) => export.evictable(keys),- None => keys,- };self.store.evict(&keys);for key in &keys {// a texture goes with its key (key 0, the white image, is never a texture's)@@ -2688,24 +2810,18 @@ impl Player {keys}- #[cfg(feature = "python")]- /// (bytes in the store's arrays, of which dead).- pub(crate) fn stored(&self) -> (usize, usize) {- (self.store.bytes(), self.store.dead)- }-- #[cfg(feature = "python")]- /// Whether retaining the current cache exceeds an individual GPU buffer's capacity.- pub(crate) fn pressured(&self, gpu: &Gpu) -> bool {- !self.store.fits(&gpu.device.limits())- }-#[cfg(feature = "player")]/// Whether it holds `key`: a shape, brush or texture.pub(crate) fn has(&self, key: u64) -> bool {self.store.shapes.contains_key(&key) || self.store.brushes.contains_key(&key) || self.images.contains_key(&key)}+ #[cfg(all(feature = "python", feature = "export"))]+ /// Whether what it holds fits a GPU buffer's binding (else each frame binds only what it draws).+ pub(crate) fn fits(&self, limits: &wgpu::Limits) -> bool {+ self.store.fits(limits)+ }+#[cfg(feature = "player")]/// The bytes it holds alive: its arrays' (the GPU's copy mirrors them) and its textures'.pub(crate) fn held(&self) -> usize {@@ -2714,32 +2830,17 @@ impl Player {/// A brush of several rows (RGBA): gradient stops, or one color per point or vertex.pub(crate) fn add_rows(&mut self, key: u64, rows: &[u8]) -> Result<(), String> {- check_key(key)?;- self.store.add_rows(key, &read(rows, "rows")?);- Ok(())+ self.upload(Upload::rows(key, rows)?)}- /// An image: straight RGBA8 rows, top to bottom (premultiplied on the way in).+ /// An image (see `Upload::texture`).pub(crate) fn add_texture(&mut self, key: u64, width: u32, height: u32, rgba: &[u8]) -> Result<(), String> {- check_key(key)?;- if rgba.len() != (width * height * 4) as usize {- return Err("texture size does not match its bytes".into());- }- if rgba.chunks_exact(4).all(|p| p[3] == 255) {- self.opaque_images.insert(key, ());- }- self.images.insert(key, (width, height, rgba.to_vec()));- Ok(())+ self.upload(Upload::texture(key, width, height, rgba)?)}- /// An environment (an `EnvironmentLight`'s picture: equirectangular RGBE rows, top to bottom), the id its views'- /// lights give it.+ /// An environment (see `Upload::environment`).pub(crate) fn add_environment(&mut self, id: u32, width: u32, height: u32, rgbe: &[u8]) -> Result<(), String> {- if rgbe.len() != (width * height * 4) as usize || width == 0 || height == 0 {- return Err("environment size does not match its bytes".into());- }- self.environments.insert(id, environment::Environment::new(width, height, rgbe.to_vec()));- Ok(())+ self.upload(Upload::environment(id, width, height, rgbe)?)}/// A view's environment's diffuse light and its cube's unit (none: 0 and 1).diff --git a/rust/engine/src/stage.rs b/rust/engine/src/stage.rsnew file mode 100644index 00000000..327a3947--- /dev/null+++ b/rust/engine/src/stage.rs@@ -0,0 +1,262 @@+//! The stage: the GPU's player for Python (`python`), with a thread of its own. Python's calls —+//! uploads, evictions, its video's frames — are queued as it makes them and carried out on the+//! stage's thread in the order they were made, as the player (`render`) and its video (`export`)+//! would carry them out on Python's thread; so a scene does not wait for the GPU or the encoder.+//! What Python waits for — pixels, its video's end — it carries out itself, on its own thread,+//! once every call made before is carried out (`now`): nothing crosses threads to answer it. What+//! is queued and not yet carried out is bounded (`QUEUED` bytes): past it, Python waits for room.+//!+//! Something going wrong on the stage's thread — the GPU, the encoder, an upload the player+//! refuses — stops the stage: its video is abandoned (no file), and Python hears of it at its next+//! call. What its player holds is told as it changes, so Python reads it without waiting (`held`,+//! `pressured`).++use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::mpsc::{self, Receiver, Sender};+use std::sync::{Arc, Condvar, Mutex, OnceLock};++use crate::CameraView;+use crate::encode::Encoder;+use crate::export::Export;+use crate::render::{Player, Upload, with_gpu};++/// Bytes queued and not yet carried out, at most (but for a call larger than that alone).+const QUEUED: usize = 256 << 20;++/// A call of Python's that the stage's thread carries out.+pub(crate) enum Call {+ Upload(Upload),+ Evict(Vec<u64>),+ /// The video's encoder: its frames follow.+ Video(Encoder),+ /// The video's next frame, shown for `repeat` frames (`key`: a keyframe): a view and its+ /// records, its cameras' views drawn first.+ Frame { view: Vec<u8>, records: Vec<u8>, cameras: Vec<CameraView>, repeat: u32, key: bool },+}++impl Call {+ /// The bytes it holds, as the queue counts them.+ fn size(&self) -> usize {+ match self {+ Call::Upload(upload) => upload.size(),+ Call::Evict(keys) => 8 * keys.len(),+ Call::Frame { view, records, cameras, .. } => view.len() + records.len() + cameras.iter().map(|c| c.3.len() + c.4.len()).sum::<usize>(),+ Call::Video(_) => 0,+ }+ }+}++/// The calls queued and not yet carried out, and the bytes they hold.+#[derive(Default)]+struct Queued {+ calls: usize,+ bytes: usize,+}++/// What Python and the stage's thread share: the player; what is queued; what stopped the stage;+/// whether it is let go of (what is queued then is dropped); what its player holds.+struct Shared {+ player: Mutex<Player>,+ queued: Mutex<Queued>,+ room: Condvar,+ fault: OnceLock<String>,+ left: AtomicBool,+ held: AtomicUsize,+ pressured: AtomicBool,+ limits: OnceLock<wgpu::Limits>, // the GPU's, once the player has drawn+}++impl Shared {+ /// Tell what the player holds, now that a call changed it.+ fn tell(&self, player: &Player) {+ self.held.store(player.held(), Ordering::Release);+ self.pressured.store(self.limits.get().is_some_and(|limits| !player.fits(limits)), Ordering::Release);+ }++ /// The GPU's limits, known from now on: the player draws.+ fn drew(&self) {+ if self.limits.get().is_none()+ && let Ok(limits) = with_gpu(|gpu| gpu.device.limits())+ {+ let _ = self.limits.set(limits);+ }+ }+}++/// The stage (see the module): a player, its thread, and the queue to it.+pub(crate) struct Stage {+ inbox: Option<Sender<Call>>,+ thread: Option<std::thread::JoinHandle<()>>,+ shared: Arc<Shared>,+}++impl Stage {+ /// A stage whose player draws `width` × `height` frames, with `samples` per pixel.+ pub(crate) fn new(width: u32, height: u32, samples: u32) -> Self {+ let (inbox, calls) = mpsc::channel();+ let shared = Arc::new(Shared {+ player: Mutex::new(Player::new(width, height, samples)),+ queued: Mutex::new(Queued::default()),+ room: Condvar::new(),+ fault: OnceLock::new(),+ left: AtomicBool::new(false),+ held: AtomicUsize::new(0),+ pressured: AtomicBool::new(false),+ limits: OnceLock::new(),+ });+ let theirs = shared.clone();+ let thread = std::thread::Builder::new().name("manimgx stage".into()).spawn(move || run(&calls, &theirs)).expect("a stage's thread");+ Self { inbox: Some(inbox), thread: Some(thread), shared }+ }++ /// Queue a call, once there is room for it; what stopped the stage, if something did.+ pub(crate) fn call(&self, call: Call) -> Result<(), String> {+ let size = call.size();+ let mut queued = self.shared.queued.lock().expect("the queue's count");+ loop {+ if let Some(fault) = self.shared.fault.get() {+ return Err(fault.clone());+ }+ if queued.calls == 0 || queued.bytes + size <= QUEUED {+ break;+ }+ queued = self.shared.room.wait(queued).expect("the queue's count");+ }+ queued.calls += 1;+ queued.bytes += size;+ drop(queued);+ self.inbox.as_ref().ok_or_else(ended)?.send(call).map_err(|_| ended())+ }++ /// Once every call queued before is carried out, `then` on the player, here: what Python+ /// waits for. What stopped the stage, if something did.+ pub(crate) fn now<T>(&self, then: impl FnOnce(&mut Player) -> Result<T, String>) -> Result<T, String> {+ let mut queued = self.shared.queued.lock().expect("the queue's count");+ loop {+ if let Some(fault) = self.shared.fault.get() {+ return Err(fault.clone());+ }+ if queued.calls == 0 {+ break;+ }+ queued = self.shared.room.wait(queued).expect("the queue's count");+ }+ drop(queued);+ let mut player = self.shared.player.lock().expect("the player");+ let done = then(&mut player);+ self.shared.drew();+ self.shared.tell(&player);+ done+ }++ /// Stop the stage for what went wrong with its video, here: the video is abandoned.+ pub(crate) fn fail(&self, error: &str) {+ self.shared.player.lock().expect("the player").export = None;+ let _ = self.shared.fault.set(error.into());+ self.shared.room.notify_all();+ }++ /// The bytes its player holds alive (`render::Player::held`), as of the calls carried out.+ pub(crate) fn held(&self) -> usize {+ self.shared.held.load(Ordering::Acquire)+ }++ /// Whether what its player holds outgrows a GPU buffer's binding, as of the calls carried out.+ pub(crate) fn pressured(&self) -> bool {+ self.shared.pressured.load(Ordering::Acquire)+ }+}++impl Drop for Stage {+ /// Let go of: what is queued is dropped, and a video not ended is abandoned.+ fn drop(&mut self) {+ self.shared.left.store(true, Ordering::Release);+ self.inbox = None;+ if let Some(thread) = self.thread.take() {+ let _ = thread.join();+ }+ }+}++fn ended() -> String {+ "the film's stage has ended".into()+}++/// The stage's thread: each call carried out as it comes, in order, until the stage is let go of.+fn run(calls: &Receiver<Call>, shared: &Shared) {+ // however the thread ends, Python stops waiting for it+ struct Leaving<'a>(&'a Shared);+ impl Drop for Leaving<'_> {+ fn drop(&mut self) {+ let _ = self.0.fault.set(ended());+ self.0.room.notify_all();+ }+ }+ let _leaving = Leaving(shared);+ for call in calls {+ let size = call.size();+ if !shared.left.load(Ordering::Acquire) && shared.fault.get().is_none() {+ let draws = matches!(call, Call::Video(_) | Call::Frame { .. });+ let mut player = shared.player.lock().expect("the player");+ if let Err(error) = carry(&mut player, call) {+ player.export = None; // abandoned: its file goes+ let _ = shared.fault.set(error);+ }+ if draws {+ shared.drew();+ }+ shared.tell(&player);+ }+ let mut queued = shared.queued.lock().expect("the queue's count");+ queued.calls -= 1;+ queued.bytes -= size;+ drop(queued);+ shared.room.notify_all();+ }+}++/// How a video was made: seconds since it began, of them in x264, the share of macroblocks+/// converted, bytes written.+pub(crate) type Made = (f64, f64, f64, u64);++/// A film's sound, as its video carries it: float32 samples, interleaved, `channels` of them, at+/// `rate` a second, encoded as AAC-LC at about `bitrate` bits a second.+pub(crate) struct Sound {+ pub(crate) samples: Vec<f32>,+ pub(crate) channels: usize,+ pub(crate) rate: u32,+ pub(crate) bitrate: u32,+}++/// The player's video written, with `sound` beside it: what it made.+pub(crate) fn end(player: &mut Player, sound: Option<Sound>) -> Result<Made, String> {+ let mut export = player.export.take().ok_or("no export is open")?;+ let audio = sound.map(|s| crate::aac::encode(&s.samples, s.channels, s.rate, s.bitrate)).transpose()?;+ with_gpu(|gpu| {+ while !export.pending.is_empty() {+ player.retire(gpu, &mut export)?;+ }+ export.finish(audio)+ })?+}++/// Carry out a call.+fn carry(player: &mut Player, call: Call) -> Result<(), String> {+ match call {+ Call::Upload(upload) => player.upload(upload),+ Call::Evict(keys) => {+ with_gpu(|gpu| player.settle(gpu))??;+ player.evict(keys);+ Ok(())+ }+ Call::Video(encoder) => {+ let (width, height) = (player.width, player.height);+ player.export = Some(with_gpu(|gpu| Export::new(gpu, encoder, width, height))??);+ Ok(())+ }+ Call::Frame { view, records, cameras, repeat, key } => {+ let frames = player.views(&view, &records, cameras)?;+ with_gpu(|gpu| player.push_frames(gpu, frames, repeat, key, None))?+ }+ }+}diff --git a/scripts/release/smoke_test.py b/scripts/release/smoke_test.pyindex 12a50ea2..c518db7b 100644--- a/scripts/release/smoke_test.py+++ b/scripts/release/smoke_test.py@@ -83,10 +83,15 @@ def main() -> None:def take() -> None:+ import manimgx as m+scene: dict[str, object] = {}exec(scene_source(), scene)+ smoke = scene["Smoke"]+ assert isinstance(smoke, type)+ assert issubclass(smoke, m.Scene)chunks: list[bytes] = []- film = scene["Smoke"]().render(take=chunks.append) # ty: ignore[call-non-callable]+ film = smoke().render(take=chunks.append)if not film.frame_count or not b"".join(chunks):sys.exit("ManimGX recorded no take")validate_take(b"".join(chunks), film.frame_count)diff --git a/src/manimgx/_engine.pyi b/src/manimgx/_engine.pyiindex 4c5477c2..b072c2a1 100644--- a/src/manimgx/_engine.pyi+++ b/src/manimgx/_engine.pyi@@ -9,8 +9,9 @@ its layout read off Typst's frames (see `manimgx.drawing.typesetting`).from collections.abc import Sequencefrom pathlib import Path+from typing import Final-DEFAULT_ENCODER_PRESET: str+DEFAULT_ENCODER_PRESET: Final = "medium"DEFAULT_ENCODER_CRF: floatTAKE_VERSION: int@@ -22,7 +23,10 @@ type CameraView = tuple[int, int, int, bytes, bytes]class Player:"""The GPU's player (natively only: in Pyodide the engine has no GPU, and a film records a- take instead, with `Recorder`)."""+ take instead, with `Recorder`). It runs on a thread of its own: each call is checked here+ and carried out there, in order, so a call waits only for room in its queue and for what+ it asks for (pixels, from `render` or `push` with `capture`; the video, from `end_export`).+ Something going wrong there abandons its video and is raised at the next call."""def __init__(self, width: int, height: int, samples: int = 4) -> None: ...def add_path(@@ -61,19 +65,23 @@ class Player:"""Append curves (float64 control points, four per curve) to a path's last subpath;`closed`: whether it now ends where it begins."""- def evict(self, keys: Sequence[int]) -> list[int]:- """Forget resources except those needed by queued export retries; return the accepted keys."""+ def evict(self, keys: Sequence[int]) -> None:+ """Forget resources, once the video's frames in flight that may draw them again are+ settled."""- def stored(self) -> tuple[int, int]:- """(bytes in the store's arrays, of which dead): what the arrays sent to the GPU hold."""+ def held(self) -> int:+ """The bytes it holds alive (shapes, brushes, textures), as of the calls carried+ out."""def pressured(self) -> bool:- """Whether the resident arrays exceed a GPU buffer's capacity; brings up the GPU."""+ """Whether what it holds outgrows a GPU buffer's binding, as of the calls carried+ out (each frame then binds only what it draws)."""def render(self, view: bytes, records: bytes, cameras: Sequence[CameraView] = ...) -> bytes:- """One frame, read back: RGBA8 rows, top to bottom."""+ """One frame, drawn as the calls before it left the player, and read back: RGBA8 rows,+ top to bottom."""def begin_export(self,@@ -95,11 +103,11 @@ class Player:capture: bool = False,) -> bytes | None:"""The next frame of the video, shown for `repeat` frames; `key`: a keyframe, where a- player can start (a section's first frame). With `capture`, return the same draw's- full-quality RGBA8 pixels, waiting for any overflow retries."""+ player can start (a section's first frame). With `capture`, wait for the same draw's+ pixels (RGBA8 rows, top to bottom), once its retries are done, and return them."""def abort_export(self) -> None:- """Abandon the video: nothing is written."""+ """Abandon the video: nothing is written (once this returns, nor any part of it)."""def end_export(self,@@ -186,10 +194,10 @@ class Recorder:self, id: int, width: int, height: int, rgbe: bytes) -> None: ...def grow_path(self, key: int, points: bytes, closed: bool = False) -> None: ...- def evict(self, keys: Sequence[int]) -> list[int]:- """Return all keys: the feeder may forget uploads retained by the take itself."""- def stored(self) -> tuple[int, int]:- """(0, 0): a take holds nothing on a GPU."""+ def evict(self, keys: Sequence[int]) -> None:+ """Nothing: a take keeps the uploads its frames need itself."""+ def held(self) -> int:+ """0: a take holds nothing on a GPU."""def frame(self,diff --git a/src/manimgx/animation/motion.py b/src/manimgx/animation/motion.pyindex 410b57f9..c3591374 100644--- a/src/manimgx/animation/motion.py+++ b/src/manimgx/animation/motion.py@@ -1329,12 +1329,7 @@ class ApplyFunction(Transform):super().__init__(mobject, keys=(None, self._apply), **kwargs)def _apply(self, copy: Mobject) -> Mobject:- target = self.function(copy)- if not isinstance(target, Mobject):- raise TypeError(- "Functions passed to ApplyFunction must return object of type Mobject"- )- return target+ return self.function(copy)class ApplyMatrix(ApplyPointwiseFunction):diff --git a/src/manimgx/animation/timeline.py b/src/manimgx/animation/timeline.pyindex 9342bc06..dfa7aeea 100644--- a/src/manimgx/animation/timeline.py+++ b/src/manimgx/animation/timeline.py@@ -174,7 +174,8 @@ class Animation[M: Mobject = Mobject]:changes nothing: it holds its mobject in the scene for its run time.Args:- mobject: The mobject to animate; None for none, as a [`Wait`][manimgx.Wait] has.+ mobject: The mobject to animate: a plain `Mobject()` for an animation that+ changes none, as a [`Wait`][manimgx.Wait] does.**options: [Animation options][manimgx.animation.timeline.AnimationOptions].Examples:@@ -211,11 +212,7 @@ class Animation[M: Mobject = Mobject]:animation._call = args, kwargsreturn animation- def __init__(- self,- mobject: M | None,- **options: Unpack[AnimationOptions],- ) -> None:+ def __init__(self, mobject: M, **options: Unpack[AnimationOptions]) -> None:o = animation_defaults(type(self)) | optionsself.run_time = o.get("run_time", 1.0)self.rate_func = o.get("rate_func", smooth)@@ -229,9 +226,7 @@ class Animation[M: Mobject = Mobject]:self.frames: list[Mobject] = [] # the keyframes, as derived (`derive`)self._model: M | None = Noneself._scene: Scene | None = None # the scene it plays in (`_setup_scene`)- self._mobject: M = (- mobject if mobject is not None else Mobject() # pyright: ignore[reportAttributeAccessIssue] # ty: ignore[invalid-assignment] # none: an Animation[Mobject]- )+ self._mobject = mobject# read-only, so an animation of a Circle is an animation of a Mobject (M is covariant)@property@@ -738,7 +733,7 @@ class Wait(Animation[Mobject]):self.duration = run_timeself.stop_condition = stop_conditionself.is_static_wait = frozen_frame- super().__init__(None, run_time=run_time, **kwargs)+ super().__init__(Mobject(), run_time=run_time, **kwargs)def begin(self) -> None: ...def finish(self) -> None: ...diff --git a/src/manimgx/animation/transform.py b/src/manimgx/animation/transform.pyindex 8783725b..d8059c28 100644--- a/src/manimgx/animation/transform.py+++ b/src/manimgx/animation/transform.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport functoolsimport inspectfrom collections.abc import Callable, Sequence-from typing import TYPE_CHECKING, Never, Protocol, Self, Unpack, cast, overload+from typing import TYPE_CHECKING, Literal, Never, Protocol, Self, Unpack, overloadfrom warnings import deprecatedimport numpy as np@@ -35,7 +35,6 @@ from manimgx.drawing.geometry import (from manimgx.mobject import Group, Mobject, VMobject, _animate_playsfrom manimgx.typing import (PathFunc,- Point3D,Point3DLike,Point3DLike_Array,Vector3DLike,@@ -243,11 +242,11 @@ class Transform[M: Mobject = Mobject](Animation[M]):# each leaf moves between its keyframes along `path_func`: from the object to a target# of its own, or between states a preset derives (`keys`)- _moving: bool | None = None # `moving_target`, once decided+ _moving: Mobject | Literal[False] | None = None # `moving_target`, once decideddef __init__(self,- mobject: M | None,+ mobject: M,target_mobject: Mobject | None = None,path_func: PathFunc | None = None,path_arc: float = 0,@@ -309,8 +308,8 @@ class Transform[M: Mobject = Mobject](Animation[M]):# from now, its updaters live from when the animation begins to run themself._moving = Nonesuper().begin()- if self.moving_target():- cast("Mobject", self.keys[-1])._stamp(clock.now)+ if (target := self.moving_target()) is not None:+ target._stamp(clock.now)def take(self) -> None:# take the object; in a play, join the tweens driving its leaves@@ -346,18 +345,20 @@ class Transform[M: Mobject = Mobject](Animation[M]):return steps, np.linalg.inv(carried((step, 1.0) for step in steps))@deprecated("Manim CE's machinery: ManimGX calls it itself", category=None)- def moving_target(self) -> bool:- """Whether the target moves while the animation plays.+ def moving_target(self) -> Mobject | None:+ """The target, if it moves while the animation plays; None if it doesn't.- It does when it is a mobject of its own with updaters that the scene does not+ It moves when it is a mobject of its own with updaters that the scene does notrun: the animation runs them (`advance`), and the keyframes follow it. Decidedonce, when first asked."""# decided once: not a walk of the scene per animation, nor of the target per# frame- if self._moving is None:+ moving = self._moving+ if moving is None:target = self.keys[-1]- self._moving = (+ moving = False+ if (isinstance(target, Mobject)and _updating(target)and (@@ -366,19 +367,21 @@ class Transform[M: Mobject = Mobject](Animation[M]):target is m for m in self._scene.get_mobject_family_members()))- )- return self._moving+ ):+ moving = target+ self._moving = moving+ return None if moving is False else movingdef advance(self, t: Fraction) -> None:# the object's updaters, brought to scene time `t` on its model, a moving target's# too; then the keyframes followmoving = self.moving_target()- if self.model is None and not moving:+ if self.model is None and moving is None:returnif self.model is not None:self.model.advance(t)- if moving:- cast("Mobject", self.keys[-1]).advance(t)+ if moving is not None:+ moving.advance(t)self.rederive()def rederive(self) -> None:@@ -1016,7 +1019,7 @@ def _turn(bound = inspect.signature(func).bind(None, *item.args, **item.kwargs)bound.apply_defaults()given = bound.arguments- angle = PI if name == "flip" else float(cast("float", given["angle"]))+ angle = PI if name == "flip" else float(given["angle"])axis = np.asarray(given["axis"], dtype=np.float64)except (TypeError, KeyError, ValueError):return None@@ -1026,7 +1029,7 @@ def _turn(def pivot(mob: Mobject) -> Floats:if point is not None:return np.asarray(point, dtype=np.float64)- return mob.get_critical_point(ORIGIN if edge is None else cast("Point3D", edge))+ return mob.get_critical_point(ORIGIN if edge is None else edge)return angle, axis, pivotdiff --git a/src/manimgx/audio/fal.py b/src/manimgx/audio/fal.pyindex 2257a5d6..f41a1ff5 100644--- a/src/manimgx/audio/fal.py+++ b/src/manimgx/audio/fal.py@@ -12,9 +12,8 @@ the models below:| `fal-ai/qwen-3-tts/text-to-speech/1.7b` | [`Qwen`][manimgx.audio.fal.Qwen] | estimated |A model takes settings of its own, typed per model: a type checker knows which settings a-model takes and which values (its voices, say), and `Fal` checks their names as it is made.-The key is `FAL_KEY`'s (fal's dashboard gives one), or `key=`; it never names the voice in the-cache.+model takes and which values (its voices, say). The key is `FAL_KEY`'s (fal's dashboard+gives one), or `key=`; it never names the voice in the cache."""import json@@ -428,7 +427,7 @@ class _Spec:fixed: tuple[tuple[str, object], ...] = ()-_MODELS: dict[str, _Spec] = {+_MODELS: dict[Model, _Spec] = {"fal-ai/elevenlabs/tts/eleven-v3": _Spec("text", ElevenV3, fixed=(("timestamps", True),)),@@ -525,14 +524,6 @@ class Fal:key: str | None = None,**settings: object,) -> None:- spec = _MODELS.get(model)- if spec is None:- raise ValueError(f"fal: no model {model!r} here: {', '.join(_MODELS)}")- known = spec.settings.__annotations__- if unknown := sorted(settings.keys() - known.keys()):- raise TypeError(- f"{model} takes {', '.join(known)}; not {', '.join(unknown)}"- )object.__setattr__(self, "model", model)object.__setattr__(self, "settings", {k: _ordered(v) for k, v in sorted(settings.items())}diff --git a/src/manimgx/audio/sound.py b/src/manimgx/audio/sound.pyindex ee8a303f..b986b489 100644--- a/src/manimgx/audio/sound.py+++ b/src/manimgx/audio/sound.py@@ -90,7 +90,7 @@ class Sound(Animation[Mobject]):self.source = sourceself.rate = rateself._edit = _Edit()- super().__init__(None)+ super().__init__(Mobject())# ── edits: each makes a new sound ─────────────────────────────────────────def _but(self, **changes: float | None) -> Self:diff --git a/src/manimgx/drawing/geometry.py b/src/manimgx/drawing/geometry.pyindex 08f32e8c..9c427fe6 100644--- a/src/manimgx/drawing/geometry.py+++ b/src/manimgx/drawing/geometry.py@@ -19,7 +19,7 @@ import mathfrom collections.abc import Callable, Iterable, Sequencefrom dataclasses import dataclass, fieldfrom types import ModuleType-from typing import TYPE_CHECKING, Final, Literal, NamedTuple+from typing import TYPE_CHECKING, Final, Literal, NamedTuple, overloadfrom warnings import deprecatedimport numpy as np@@ -402,7 +402,7 @@ def find_intersection(return result-def midpoint(p1: Point3D, p2: Point3D) -> Point3D:+def midpoint(p1: Point3DLike, p2: Point3DLike) -> Point3D:"""The point halfway between two points.Args:@@ -523,7 +523,7 @@ def cross2d(a: np.ndarray, b: np.ndarray) -> npt.NDArray[np.float64] | float:@deprecated("use numpy: np.mean(points, axis=0)", category=None)-def center_of_mass(points: Point3D_Array) -> Point3D:+def center_of_mass(points: Point3DLike_Array) -> Point3D:"""The average of points.Returns:@@ -1204,7 +1204,19 @@ class QuickHull:break-def interpolate[T](start: T, end: T, alpha: float | np.ndarray) -> T:+@overload+def interpolate(start: float, end: float, alpha: float) -> float: ...+@overload+def interpolate(start: complex, end: complex, alpha: float) -> complex: ...+@overload+def interpolate(start: float, end: float, alpha: np.ndarray) -> np.ndarray: ...+@overload+def interpolate(+ start: np.ndarray, end: np.ndarray, alpha: float | np.ndarray+) -> np.ndarray: ...+def interpolate(+ start: complex | np.ndarray, end: complex | np.ndarray, alpha: float | np.ndarray+) -> complex | np.ndarray:"""The value a fraction of the way from one value to another: (1 − alpha)·start +alpha·end.@@ -1217,7 +1229,7 @@ def interpolate[T](start: T, end: T, alpha: float | np.ndarray) -> T:Returns:The value between."""- return (1 - alpha) * start + alpha * end # pyright: ignore[reportOperatorIssue] # ty: ignore[unsupported-operator] # T: numbers, arrays+ return (1 - alpha) * start + alpha * enddef integer_interpolate(start: float, end: float, alpha: float) -> tuple[int, float]:@@ -1260,18 +1272,24 @@ def inverse_interpolate(start: float, end: float, value: float) -> float:_NPPCC = 4-def sample(function: Callable[..., object], *args: np.ndarray) -> np.ndarray:+def sample(+ function: Callable[..., object], *args: np.ndarray, checked: bool = True+) -> np.ndarray:"""Evaluate a function at every point of a grid of arguments.`args` are arrays of one shape, one per argument of `function`. The function iscalled once on the whole arrays, as most numeric functions allow, and checkedagainst single calls at the first, middle and last points; a function written forone value at a time (`math.cos`, `if t < 0`) raises or differs there, and is then- called once per point.+ called once per point. A value given as its components (`(t, t**2, 0)`) takes a+ component that is one number across the grid.Args:function: The function, from the arguments to a value.*args: The arguments' values: arrays of one shape.+ checked: Whether the whole arrays' values are checked against single calls;+ unchecked, a function that takes arrays is trusted to give what single+ calls would.Returns:The values: an array of the arguments' shape, followed by a value's.@@ -1279,12 +1297,15 @@ def sample(function: Callable[..., object], *args: np.ndarray) -> np.ndarray:shape, n = args[0].shape, args[0].sizeflat = [a.ravel() for a in args]try:- out = np.asarray(function(*args), dtype=float)+ value = function(*args)+ if isinstance(value, (tuple, list)): # its components: a number taken across+ value = np.broadcast_arrays(*(np.asarray(c, dtype=float) for c in value))+ out = np.asarray(value, dtype=float)k = len(shape)if out.shape[:k] != shape and out.shape[-k:] == shape: # values firstout = np.moveaxis(out, range(out.ndim - k, out.ndim), range(k))values = out.reshape(n, -1)- for i in {0, n // 2, n - 1}:+ for i in {0, n // 2, n - 1} if checked else ():one = np.asarray(function(*(float(f[i]) for f in flat)), dtype=float)if not np.allclose(values[i], one.ravel(), rtol=1e-9, atol=1e-12):raise ValueError(i)@@ -1344,7 +1365,7 @@ def _to_path(points: Point3D_Array, tolerance: float) -> SkiaPath:return path-def bezier(points: Point3D_Array) -> Callable[[float], Point3D]:+def bezier(points: Point3DLike_Array) -> Callable[[float], Point3D]:"""A cubic Bézier curve as a function: from its first control point at 0 to its lastat 1.@@ -1363,7 +1384,9 @@ def bezier(points: Point3D_Array) -> Callable[[float], Point3D]:return cubic-def partial_bezier_points(points: Point3D_Array, a: float, b: float) -> Point3D_Array:+def partial_bezier_points(+ points: Point3DLike_Array, a: float, b: float+) -> Point3D_Array:"""The control points of part of a cubic Bézier curve, from its parameter `a` to`b`.@@ -1434,7 +1457,9 @@ def _subdivision_matrix(n: int | np.integer) -> np.ndarray:return _SUBDIVISION.keep(n, m)-def subdivide_bezier(points: Point3D_Array, n_divisions: int) -> Point3D_Array:+def subdivide_bezier(+ points: Point3DLike_Array, n_divisions: int | np.integer+) -> Point3D_Array:"""Split a cubic Bézier curve into curves over equal stretches of its parameter.Args:@@ -1450,7 +1475,7 @@ def subdivide_bezier(points: Point3D_Array, n_divisions: int) -> Point3D_Array:return _subdivision_matrix(n_divisions) @ points-def bezier_remap(tuples: np.ndarray, new_count: int) -> np.ndarray:+def bezier_remap(tuples: npt.ArrayLike, new_count: int) -> np.ndarray:"""Split cubic Bézier curves into more, their shape unchanged.Each curve is split over equal stretches of its parameter, the new curves spreaddiff --git a/src/manimgx/drawing/paint.py b/src/manimgx/drawing/paint.pyindex 95dd1c47..cb522d6b 100644--- a/src/manimgx/drawing/paint.py+++ b/src/manimgx/drawing/paint.py@@ -204,12 +204,18 @@ def from_oklab(lab: Floats) -> Floats:_LABS: Memo[int, tuple[Floats, Floats]] = Memo(1 << 12)+_COLOR_LABS: Memo[bytes, Floats] = Memo(1 << 12)def _lab(rgba: Floats) -> Floats:"""OKLab of an RGBA array's colors — once per array when the array cannot change (a- paint's rows are read-only): a tween mixes the same two paints on every frame."""+ paint's rows are read-only): a tween mixes the same two paints on every frame; and once+ per value for one color (a color's own array): an updater mixes the same colors on+ every frame."""if rgba.flags.writeable:+ if rgba.shape == (4,):+ rgb = rgba[:3]+ return _COLOR_LABS.recall(rgb.tobytes(), lambda: frozen(to_oklab(rgb)))return to_oklab(rgba[..., :3])known = _LABS.recall(id(rgba), lambda: (rgba, to_oklab(rgba[..., :3])))if known[0] is not rgba: # another array, since gone, had its id@@ -235,6 +241,13 @@ def mix_rgba(a: Floats, b: Floats, t: float | Floats) -> Floats:Returns:The mixed colors, an array of the same shape; exactly `a` at 0 and `b` at 1."""+ if a.shape == b.shape == (4,) and not isinstance(t, np.ndarray):+ return _mix_color(a, b, t)+ return _mix_rows(a, b, t)+++def _mix_rows(a: Floats, b: Floats, t: float | Floats) -> Floats:+ """`mix_rgba`, row by row, in numpy: any shape."""rows = isinstance(t, np.ndarray) and t.ndim > 0if rows:t = t.astype(float)[..., None]@@ -261,6 +274,32 @@ def mix_rgba(a: Floats, b: Floats, t: float | Floats) -> Floats:return mixed if not rows else np.where(t <= 0.0, a, np.where(t >= 1.0, b, mixed))+def _mix_color(a: Floats, b: Floats, t: float) -> Floats:+ """`mix_rgba` of one color and another: `_mix_rows`'s arithmetic, step by step, on+ floats (each step rounds as numpy's does), around numpy's OKLab conversion. An updater+ mixes one color at a time, every frame, where numpy's calls cost more than the+ arithmetic they do."""+ if t <= 0.0:+ return np.array(a, dtype=float)+ if t >= 1.0:+ return np.array(b, dtype=float)+ (ar, ag, ab, aa), (br, bg, bb, ba) = a.tolist(), b.tolist()+ if (ar, ag, ab) == (br, bg, bb): # one color: only opacity moves+ out = np.array(a, dtype=float)+ out[3] = aa * (1.0 - t) + ba * t+ return out+ wa, wb = aa * (1.0 - t), ba * t+ opacity = wa + wb+ la, lb = _lab(a).tolist(), _lab(b).tolist()+ if opacity > 1e-9:+ lab = [+ (x * wa + y * wb) / max(opacity, 1e-9) for x, y in zip(la, lb, strict=True)+ ]+ else:+ lab = [x * (1.0 - t) + y * t for x, y in zip(la, lb, strict=True)]+ return np.array([*from_oklab(np.array(lab)).tolist(), opacity])++type ParsableManimColor = ManimColor | str | int | Sequence[float] | np.ndarray"""Anything [ManimColor][manimgx.ManimColor] reads as a color: a color, a hex string(`"#58C4DD"`) or a color's name (`"BLUE"`), an integer (`0x58C4DD`), or three or four@@ -412,7 +451,7 @@ class ManimColor(str):Returns:A new color."""- return ManimColor(tuple(mix_rgba(self._rgba, other._rgba, alpha)))+ return _made(ManimColor, mix_rgba(self._rgba, other._rgba, alpha))def opacity(self, opacity: float) -> "ManimColor":"""This color with another opacity.@@ -585,7 +624,7 @@ class ManimColor(str):def _bytes(rgba: np.ndarray) -> list[int]:- return [round(float(c) * 255) for c in np.clip(rgba, 0.0, 1.0)]+ return [round(min(max(c, 0.0), 1.0) * 255) for c in rgba.tolist()]def _hex(rgba: np.ndarray) -> str:@@ -719,7 +758,7 @@ def interpolate_color(a: ManimColor, b: ManimColor, alpha: float) -> ManimColor:self.add(swatches.arrange(buff=0.5))```"""- return ManimColor(a).interpolate(ManimColor(b), alpha)+ return a.interpolate(b, alpha)def color_gradient(@@ -788,6 +827,13 @@ type Colorscale = (pairs, each color at its value (see [colors_by_value][manimgx.colors_by_value])."""+def _paired(+ colorscale: Colorscale,+) -> TypeIs[Sequence[tuple[ParsableManimColor, float]]]:+ """Is the colorscale (color, value) pairs, rather than colors spread evenly?"""+ return all(isinstance(c, (tuple, list)) and len(c) == 2 for c in colorscale)++def colors_by_value(colorscale: Colorscale, values: Iterable[float], low: float, high: float) -> list[ManimColor]:@@ -834,13 +880,11 @@ def rgbas_by_value(An (n, 4) array, a row per value, each from 0 to 1."""# the pivots are the colors' values, given or spread evenly over [low, high]- if all(isinstance(c, (tuple, list)) and len(c) == 2 for c in colorscale):- pairs = cast("Sequence[tuple[ParsableManimColor, float]]", colorscale)- colors = np.array([ManimColor(c).to_rgba() for c, _ in pairs])- pivots = np.array([p for _, p in pairs], dtype=float)+ if _paired(colorscale):+ colors = np.array([ManimColor(c).to_rgba() for c, _ in colorscale])+ pivots = np.array([p for _, p in colorscale], dtype=float)else:- scale = cast("Sequence[ParsableManimColor]", colorscale)- colors = np.array([ManimColor(c).to_rgba() for c in scale])+ colors = np.array([ManimColor(c).to_rgba() for c in colorscale])pivots = np.linspace(low, high, len(colors))v = np.asarray(values, dtype=float).reshape(-1)i = np.searchsorted(pivots, v, side="right") # the first pivot above each value@@ -1654,11 +1698,12 @@ class Paint:for name in _LERPED:x, y = getattr(a, name), getattr(b, name)changes[name] = y if alpha == 1.0 or x is y else interpolate(x, y, alpha)- for (- name- ) in _WIDTHS: # past its ends an overshooting rate function: no width < 0- if cast("float", changes[name]) < 0: # (a field kept is kept by identity)- changes[name] = 0.0+ for name, w, v in (+ ("stroke_width", a.stroke_width, b.stroke_width),+ ("background_width", a.background_width, b.background_width),+ ): # past its ends an overshooting rate function: no width < 0+ width = v if alpha == 1.0 or w is v else interpolate(w, v, alpha)+ changes[name] = 0.0 if width < 0 else widthfor name, slot in _SLOTS.items():x, y = getattr(a, slot), getattr(b, slot) # None: a tween'sif alpha >= 1.0 or alpha <= 0.0:@@ -1676,14 +1721,7 @@ class Paint:return self._but(changes) # a frame's paint: nothing to remember it by-_WIDTHS = ("stroke_width", "background_width")-_LERPED = (- "stroke_width",- "background_width",- "sheen_direction",- "sheen_factor",- "trim",-)+_LERPED = ("sheen_direction", "sheen_factor", "trim")def _kept(name: str, value: object) -> object:@@ -1728,9 +1766,26 @@ _ARRAYS = ("_fill", "_stroke", "_background", "sheen_direction", "trim")_NUMERIC = frozenset({"stroke_width", "background_width", "sheen_factor", "dash"})-class PaintAttribute[G, S = G]:- """A CE style attribute of a mobject (`mob.joint_type`), kept in its paint's `field` (G: what- is read, S: what may be set; the paint keeps arrays as float values)."""+class PaintAttribute[T]:+ """A CE style attribute of a mobject (`mob.joint_type`), kept in its paint's `field`."""++ def __init__(self, field: str) -> None:+ self.field = field++ @overload+ def __get__(self, mob: None, owner: type) -> Self: ...+ @overload+ def __get__(self, mob: "Mobject", owner: type) -> T: ...+ def __get__(self, mob: "Mobject | None", owner: type) -> "T | Self":+ return self if mob is None else getattr(mob.paint, self.field)++ def __set__(self, mob: "Mobject", value: T) -> None:+ mob.paint = mob.paint.but(**{self.field: value})+++class PaintArray[G: np.ndarray, S: npt.ArrayLike = npt.ArrayLike]:+ """A CE style attribute of a mobject that is an array (`mob.fill_rgbas`), kept in its+ paint's `field`: read as the paint keeps it (G), set from S, copied as float values."""def __init__(self, field: str) -> None:self.field = field@@ -1743,9 +1798,5 @@ class PaintAttribute[G, S = G]:return self if mob is None else getattr(mob.paint, self.field)def __set__(self, mob: "Mobject", value: S) -> None:- own = (- frozen(np.array(cast("npt.ArrayLike", value), dtype=float, copy=True))- if value is not None and (self.field in _SLOTS or self.field in _ARRAYS)- else value- )- mob.paint = mob.paint.but(**{self.field: own})+ array = frozen(np.array(value, dtype=float, copy=True))+ mob.paint = mob.paint.but(**{self.field: array})diff --git a/src/manimgx/mobject.py b/src/manimgx/mobject.pyindex ed1cc167..173c21d4 100644--- a/src/manimgx/mobject.py+++ b/src/manimgx/mobject.py@@ -88,6 +88,7 @@ from manimgx.drawing.paint import (ManimColor,Material,Paint,+ PaintArray,PaintAttribute,ParsableManimColor,SimpleStyle,@@ -642,6 +643,25 @@ def remove_list_redundancies[T](items: Sequence[T]) -> list[T]:def _family(roots: Iterable["Mobject"]) -> list["Mobject"]:"""Preorder from these roots, each member once at its last occurrence."""+ # Members held once (most families) are the preorder itself, made in one pass; a member+ # met again sends the work to the walk that keeps last occurrences.+ roots = list(roots)+ preorder: list[Mobject] = []+ met: set[int] = set()+ pending = roots[::-1]+ while pending:+ item = pending.pop()+ if id(item) in met:+ return _family_of_repeats(roots)+ met.add(id(item))+ preorder.append(item)+ if item.submobjects:+ pending.extend(item.submobjects[::-1])+ return preorder+++def _family_of_repeats(roots: list["Mobject"]) -> list["Mobject"]:+ """`_family` of roots whose families share members, or repeat them."""# Right-to-left postorder is reversed preorder. Keep its first occurrences,# skipping already visited subtrees, then reverse to keep preorder's last ones.family: list[Mobject] = []@@ -728,16 +748,16 @@ class Mobject:"""How much the mobject's own colors lighten toward its `sheen_direction`, from -1to 1 (0: none; negative: they darken); see[set_sheen][manimgx.Mobject.set_sheen]."""- sheen_direction = PaintAttribute[Vector3D, Vector3DLike]("sheen_direction")+ sheen_direction = PaintArray[Vector3D, Vector3DLike]("sheen_direction")"""The direction the mobject's own colors lighten toward, which its color gradientsrun along too."""- fill_rgbas = PaintAttribute[RGBA_Array, npt.ArrayLike]("fill")+ fill_rgbas = PaintArray[RGBA_Array]("fill")"""The mobject's own fill colors, as rows of red, green, blue and opacity, from 0 to1: one row per gradient stop."""- stroke_rgbas = PaintAttribute[RGBA_Array, npt.ArrayLike]("stroke")+ stroke_rgbas = PaintArray[RGBA_Array]("stroke")"""The mobject's own stroke colors, as rows of red, green, blue and opacity, from 0to 1."""- background_stroke_rgbas = PaintAttribute[RGBA_Array, npt.ArrayLike]("background")+ background_stroke_rgbas = PaintArray[RGBA_Array]("background")"""The colors of the mobject's own background stroke (an outline drawn behind itsfill), as rows of red, green, blue and opacity, from 0 to 1."""background_stroke_width = PaintAttribute[float]("background_width")@@ -1154,12 +1174,7 @@ class Mobject:def _place(self, index: int | None, mobjects: Sequence["Mobject"]) -> Self:"""The one way submobjects join: each a mobject that neither is this one nor holdsit, once (where it last occurs), at `index` among the others (None: last)."""- for i, m in enumerate(mobjects):- if not isinstance(m, Mobject):- raise TypeError(- f"Only Mobjects can be added to {type(self).__name__}, got"- f" {type(m).__name__} at index {i}"- )+ for m in mobjects:if m is self or (m.submobjects and any(member is self for member in m.get_family())):@@ -1359,7 +1374,7 @@ class Mobject:if _per_frame(updater):updater(self)else:- cast("Callable[[Self, float], object]", updater)(self, dt)+ updater(self, dt)if recursive:for sub in self.submobjects:sub.update(dt, recursive)@@ -1422,7 +1437,7 @@ class Mobject:since = self._sincestart = since.get(updater, t)since[updater] = t- on = cast("clock.Clock | None", getattr(updater, "clock", None))+ on: clock.Clock | None = getattr(updater, "clock", None)dt = float(t - start) if on is None else on.at(float(t)) - on.at(float(start))updater(self, dt)@@ -1524,7 +1539,7 @@ class Mobject:if _per_frame(update_function):update_function(self)else:- cast("Callable[[Self, float], object]", update_function)(self, 0)+ update_function(self, 0)return selfdef remove_updater(self, update_function: Updater[Never]) -> Self:@@ -1635,9 +1650,7 @@ class Mobject:mobject: The mobject whose updaters to take (its own, not its family's)."""self.clear_updaters()- self.updaters.extend(- mobject.get_updaters() # ty: ignore[invalid-argument-type] # CE: another mobject's updaters, applied to this one- )+ self.updaters.extend(mobject.updaters)self._stamp(clock.now, recursive=False)return self@@ -4322,15 +4335,11 @@ class Mobject:def _members(items: Iterable[Mobject | Iterable[Mobject]]) -> list[Mobject]:"""Mobjects and iterables of mobjects, flattened one level."""flat: list[Mobject] = []- for i, m in enumerate(items):+ for m in items:if isinstance(m, Mobject):flat.append(m)- elif isinstance(m, Iterable):- flat.extend(m)else:- raise TypeError(- f"Only mobjects can be grouped, got {type(m).__name__} at index {i}"- )+ flat.extend(m)return flat@@ -4373,7 +4382,7 @@ class Group[T: Mobject = Mobject](Mobject):# Group, VGroup and PGroup are this one class# a Group[T] only ever adds T- submobjects: list[T] # pyright: ignore[reportIncompatibleVariableOverride]+ submobjects: list[T]"""The group's members, in drawing order."""@overload # `Group(a, b)`: members of any kinds@@ -4390,7 +4399,7 @@ class Group[T: Mobject = Mobject](Mobject):super().__init__(**kwargs)Mobject.add(self, *_members(mobjects))- def add( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # a Group[T] adds T+ def add( # ty: ignore[invalid-method-override] # a Group[T] adds Tself, *mobjects: T | Iterable[T]) -> Self:"""Add members after the ones the group has: mobjects, or iterables of mobjects@@ -4591,7 +4600,7 @@ class ValueTracker[V: (float, complex) = float](Mobject):def get_value(self) -> V:"""The number the tracker holds."""- return float(self.points[0, 0]) # pyright: ignore[reportReturnType] # V is float here+ return float(self.points[0, 0])def set_value(self, value: V) -> Self:"""Set the number the tracker holds; through@@ -6127,9 +6136,7 @@ class VDict[T: Mobject = Mobject](Mobject):) -> None: ...def __init__[Key: Hashable](self,- mapping_or_iterable: (- Mapping[Key, Mobject] | Iterable[tuple[Key, Mobject]]- ) = {},+ mapping_or_iterable: Mapping[Key, T] | Iterable[tuple[Key, T]] = {},show_keys: bool = False,**kwargs: Unpack[Style],) -> None:@@ -6137,11 +6144,9 @@ class VDict[T: Mobject = Mobject](Mobject):self.show_keys = show_keysself.submob_dict: dict[Hashable, T] = {}"""The members, by key."""- self.add(- mapping_or_iterable # ty: ignore[invalid-argument-type] # a VDict[T] is given T- )+ self.add(mapping_or_iterable)- def add[Key: Hashable]( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: by key+ def add[Key: Hashable]( # ty: ignore[invalid-method-override] # CE's: by keyself, mapping_or_iterable: Mapping[Key, T] | Iterable[tuple[Key, T]]) -> Self:"""Add members by key, after the group's.@@ -6158,7 +6163,7 @@ class VDict[T: Mobject = Mobject](Mobject):self.add_key_value_pair(key, value)return self- def remove( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: by key+ def remove( # ty: ignore[invalid-method-override] # CE's: by keyself, key: Hashable) -> Self:"""Remove the member with a key from the group.diff --git a/src/manimgx/mobjects/annotations.py b/src/manimgx/mobjects/annotations.pyindex 89479576..2a07d945 100644--- a/src/manimgx/mobjects/annotations.py+++ b/src/manimgx/mobjects/annotations.py@@ -69,7 +69,6 @@ from manimgx.mobjects.text import (MathTexOptions,Tex,Text,- Typst,TypstOptions,)from manimgx.typing import ManimTextLabel@@ -143,10 +142,6 @@ class SurroundingRectangle(RoundedRectangle):corner_radius: float = 0.0,**kwargs: Unpack[Style],) -> None:- if not all(isinstance(mob, Mobject) for mob in mobjects):- raise TypeError(- "Expected all inputs for parameter mobjects to be a Mobjects"- )if isinstance(buff, tuple):buff_x = buff[0]buff_y = buff[1]@@ -352,12 +347,8 @@ class Label(VGroup):if isinstance(label, str):self.rendered_label: ManimTextLabel = MathTex(label, **label_style)"""The label's text or math, a submobject."""- elif isinstance(label, Typst):- self.rendered_label = labelelse:- raise TypeError(- "Unsupported label type. Must be MathTex, Tex, Text or Typst."- )+ self.rendered_label = labelself.background_rect = BackgroundRectangle(self.rendered_label, **box_style)"""The rectangle behind the label, a submobject."""self.frame = SurroundingRectangle(self.rendered_label, **frame_style)@@ -725,7 +716,7 @@ class Brace(VMobjectFromSVGPath):"""return self.points[28]- def get_direction( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: a brace's direction is a vector, a path's a winding+ def get_direction( # ty: ignore[invalid-method-override] # CE's: a brace's direction is a vector, a path's a windingself,) -> Vector3D:"""The direction the brace points to: from its center to its tip.diff --git a/src/manimgx/mobjects/graph.py b/src/manimgx/mobjects/graph.pyindex 1bd68e63..48ad75fc 100644--- a/src/manimgx/mobjects/graph.py+++ b/src/manimgx/mobjects/graph.py@@ -111,9 +111,9 @@ def _partite_layout(partition_count = len(partitions)for i in range(partition_count):for v in partitions[i]:- if nx_graph.nodes[v] is None:+ if v not in nx_graph:raise ValueError(- "The partition must contain arrays of vertices in the graph"+ f"{v!r}, in partition {i}, is not a vertex of the graph")nx_graph.nodes[v]["subset"] = ifor v in nx_graph.nodes:@@ -494,9 +494,12 @@ def _split[K: Hashable](shared: Config = {k: v for k, v in given.items() if isinstance(k, str) and k not in names}- return shared, {- k: dict(cast("Mapping[str, object]", given[k])) for k in names if k in given- }+ own: dict[K, Config] = {}+ for k in names & given.keys():+ if not isinstance(keywords := given[k], Mapping):+ raise TypeError(f"{k!r}'s own keywords are not a mapping: {keywords!r}")+ own[k] = dict(keywords)+ return shared, ownclass GenericGraph[V: Hashable = Hashable](VMobject):@@ -630,7 +633,7 @@ class GenericGraph[V: Hashable = Hashable](VMobject):for u, v in edges}- def __getitem__( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE: a graph is indexed by vertex and edge, not position+ def __getitem__( # ty: ignore[invalid-method-override] # CE: a graph is indexed by vertex and edge, not positionself, k: V | Edge[V]) -> Mobject:if k in self.vertices:@@ -1119,10 +1122,9 @@ class DiGraph[V: Hashable = Hashable](GenericGraph[V]):def _make_edge(self, edge_type: Maker, u: V, v: V, config_: Config) -> Mobject:style = config_.copy()- tips = cast(- "TipConfig",- style.pop("tip_config", self.default_edge_config.get("tip_config", {})),- )+ tips = style.pop("tip_config", self.default_edge_config.get("tip_config", {}))+ if not isinstance(tips, Mapping):+ raise TypeError(f"an edge's tip_config is not a mapping: {tips!r}")edge = edge_type(start=self[u], end=self[v], z_index=-1, **style)if isinstance(edge, Line):edge.add_tip(**tips)diff --git a/src/manimgx/mobjects/images.py b/src/manimgx/mobjects/images.pyindex e819f8a3..55aeec5e 100644--- a/src/manimgx/mobjects/images.py+++ b/src/manimgx/mobjects/images.py@@ -168,7 +168,7 @@ class ImageMobject(MeshMobject):height = h / self.scale_to_resolution * short if self.scale_to_resolution else 3return self.stretch_to_fit_height(height).stretch_to_fit_width(height * w / h)- def set_color( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: an image's tint, then its alpha+ def set_color( # ty: ignore[invalid-method-override] # CE's: an image's tint, then its alphaself,color: ParsableManimColor = YELLOW_C,alpha: float | None = None,diff --git a/src/manimgx/mobjects/plotting.py b/src/manimgx/mobjects/plotting.pyindex 2fcb236c..0b983ccb 100644--- a/src/manimgx/mobjects/plotting.py+++ b/src/manimgx/mobjects/plotting.py@@ -109,6 +109,7 @@ if TYPE_CHECKING:from manimgx.typing import (ManimTextLabel,Point3D,+ Point3D_Array,Point3DLike,Point3DLike_Array,Vector3D,@@ -369,10 +370,10 @@ class ParametricFunction(VMobject):The function is sampled every `t_step`, and at `t_max`, and the samples are joinedby a smooth curve through them (or by straight segments, without`use_smoothing`). Where the function jumps, give its `discontinuities`: the curve- is drawn in pieces between them, each stopping `dt` short. Unless- `use_vectorized`, the function is first tried on all the values of t at once, as- an array, and checked against single calls; a function that does not take arrays- is called once per value.+ is drawn in pieces between them, each stopping `dt` short. The function is first+ tried on all the values of t at once, as an array, and checked against single calls+ (unless `use_vectorized` vouches for it); a function that does not take arrays is+ called once per value.The discontinuities are kept as the list they were when the curve was made, beforerange filtering, so copies and regenerated curves keep all its breaks.@@ -391,8 +392,8 @@ class ParametricFunction(VMobject):use_smoothing: Whether the samples are joined by a smooth curve through them,rather than by straight segments.use_vectorized: Whether `function` takes all the values of t at once, as an- array, and returns the arrays of x, y and z (a z that is not an array is- taken as 0).+ array, and gives what single calls would: it is then not checked against+ them. Its x, y and z may each be an array or one number for every t.Examples:```python@@ -438,8 +439,14 @@ class ParametricFunction(VMobject):def internal_parametric_function(t: float) -> Point3D:return np.asarray(function(t))+ # sampled as given, on all the values of t at once if it can be: a function, as+ # copies share one, whatever callable was given+ def given(t: float) -> Point3DLike:+ return function(t)+self.function = internal_parametric_function"""The curve's function: from t to its point, as an array."""+ self._given = givenif len(t_range) == 2:t_range = (*t_range, 0.01)self.scaling = scaling@@ -494,15 +501,7 @@ class ParametricFunction(VMobject):self.scaling.function(t2),])- if self.use_vectorized: # the function takes all the parameters at once- x, y, z = cast(- "Callable[[np.ndarray], Sequence[np.ndarray]]", self.function- )(t_range)- if not isinstance(z, np.ndarray):- z = np.zeros_like(x)- points = np.stack([x, y, z], axis=1)- else:- points = sample(self.function, t_range)+ points = sample(self._given, t_range, checked=not self.use_vectorized)self.start_new_path(points[0])self.add_points_as_corners(points[1:])if self.use_smoothing:@@ -737,6 +736,17 @@ class NumberLineOptions(_Tipped, total=False, closed=True):without `include_numbers` (default None: the ticks')."""+def _along(offsets: np.ndarray, direction: Vector3D) -> np.ndarray:+ """The projections of an offset, or of an array of them, onto a unit direction. Along a+ coordinate axis, as a straight number line runs, a projection is that coordinate times+ ±1: what the dot product gives in any order of summing, so that a point's number is the+ same alone and among others."""+ (nonzero,) = np.nonzero(direction)+ if len(nonzero) == 1:+ return offsets[..., nonzero[0]] * direction[nonzero[0]]+ return np.dot(offsets, direction)++class NumberLine(Line):"""A number line: a line with ticks at every step of its range, numbers if askedfor, and a map between numbers and points; white, with a stroke 2 wide, unless@@ -1069,7 +1079,7 @@ class NumberLine(Line):point = np.asarray(point, dtype=float)start, end = self.get_start(), self.get_end()unit_vect = normalize(end - start)- proportion: float = np.dot(point - start, unit_vect) / np.dot(+ proportion: float = _along(point - start, unit_vect) / np.dot(end - start, unit_vect)# along the range, then through the scale, as number_to_point goes back@@ -2496,21 +2506,29 @@ class Axes(VGroup):a = max(a, bounded_graph.t_min)b = min(b, bounded_graph.t_max)if bounded_graph is None:- points = (- [self.c2p(a), graph.function(a)]- + [p for p in graph.points if a <= self.p2c(p)[0] <= b]- + [graph.function(b), self.c2p(b)]- )+ points = [+ self.c2p(a),+ graph.function(a),+ *self._points_between(graph, a, b),+ graph.function(b),+ self.c2p(b),+ ]else:graph_points, bounded_graph_points = (- [g.function(a)]- + [p for p in g.points if a <= self.p2c(p)[0] <= b]- + [g.function(b)]+ [g.function(a), *self._points_between(g, a, b), g.function(b)]for g in (graph, bounded_graph))points = graph_points + bounded_graph_points[::-1]return Polygon(*points, **kwargs).set_opacity(opacity).set_color(color)+ def _points_between(+ self, graph: ParametricFunction, a: float, b: float+ ) -> Point3D_Array:+ """The graph's points whose x on the axes is from `a` to `b`, in order: their+ coordinates read all at once."""+ x = self.p2c(graph.points)[:, 0]+ return graph.points[(a <= x) & (x <= b)]+def angle_of_tangent(self, x: float, graph: ParametricFunction, dx: float = 1e-08) -> float:@@ -3685,7 +3703,7 @@ class PolarPlane(_Plane):case _:return MathTex(f"{turns:g}", font_size=size)- def add_coordinates( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: a polar plane numbers radii and angles+ def add_coordinates( # ty: ignore[invalid-method-override] # CE's: a polar plane numbers radii and anglesself,r_values: Iterable[float] | None = None,a_values: Iterable[float] | None = None,@@ -3837,7 +3855,7 @@ class ComplexPlane(NumberPlane):)return self.coordinate_labels- def add_coordinates( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: numbers, not per-axis values+ def add_coordinates( # ty: ignore[invalid-method-override] # CE's: numbers, not per-axis valuesself, *numbers: float | complex, **kwargs: Unpack[DecimalNumberOptions]) -> Self:"""Label numbers of the plane, asdiff --git a/src/manimgx/mobjects/shapes.py b/src/manimgx/mobjects/shapes.pyindex 86fa459f..f342849a 100644--- a/src/manimgx/mobjects/shapes.py+++ b/src/manimgx/mobjects/shapes.py@@ -12,7 +12,7 @@ import warningsfrom collections.abc import Iterator, Sequencefrom functools import reducefrom math import ceil-from typing import TYPE_CHECKING, ClassVar, Literal, Self, Unpack, cast+from typing import TYPE_CHECKING, ClassVar, Literal, Self, Unpackfrom warnings import deprecatedimport numpy as np@@ -826,9 +826,7 @@ class ArcBetweenPoints(Arc):if radius is None:center = self.get_arc_center(warning=False)if not self._failed_to_get_center:- self.radius = cast(- float, np.linalg.norm(np.array(start) - np.array(center))- )+ self.radius = float(np.linalg.norm(np.array(start) - np.array(center)))else:self.radius = np.inf@@ -1463,10 +1461,6 @@ class ArcPolygonFromArcs(VMobject):"""def __init__(self, *arcs: Arc | ArcBetweenPoints, **kwargs: Unpack[Style]) -> None:- if not all(isinstance(m, (Arc, ArcBetweenPoints)) for m in arcs):- raise ValueError(- "All ArcPolygon submobjects must be of type Arc/ArcBetweenPoints"- )super().__init__(**kwargs)self.add(*arcs)self.arcs = [*arcs]diff --git a/src/manimgx/mobjects/text.py b/src/manimgx/mobjects/text.pyindex 4a21112d..5514568f 100644--- a/src/manimgx/mobjects/text.py+++ b/src/manimgx/mobjects/text.py@@ -1299,7 +1299,7 @@ class SingleStringMathTex(Typst):tex_environment: str | None = "align*",**kwargs: Unpack[TypstOptions],) -> None:- self.tex_string = tex_string = str(tex_string)+ self.tex_string = tex_string"""The LaTeX the formula was typeset from."""self.tex_environment = tex_environmentbody = (diff --git a/src/manimgx/mobjects/three_d.py b/src/manimgx/mobjects/three_d.pyindex c3720298..379d7388 100644--- a/src/manimgx/mobjects/three_d.py+++ b/src/manimgx/mobjects/three_d.py@@ -31,7 +31,7 @@ __all__ = ["Torus",]from collections.abc import Callable, Hashable, Iterable, Sequence-from typing import TYPE_CHECKING, ClassVar, Literal, Self, Unpack, cast+from typing import TYPE_CHECKING, ClassVar, Literal, Self, Unpackimport numpy as npfrom typing_extensions import TypedDict@@ -72,6 +72,7 @@ from manimgx.drawing.paint import (ManimColor,ParsableManimColor,Style,+ _paired,_Style,rgbas_by_value,)@@ -424,11 +425,8 @@ class Surface(MeshMobject):)return selflow, high = (axes.x_range, axes.y_range, axes.z_range or (0, 0))[axis][:2]- if all(isinstance(c, (tuple, list)) and len(c) == 2 for c in colorscale):- pivots = [- float(cast("tuple[ParsableManimColor, float]", c)[1])- for c in colorscale- ]+ if _paired(colorscale):+ pivots = [p for _, p in colorscale]low, high = min(pivots), max(pivots)values = np.asarray(axes.point_to_coords(self.points), dtype=float)[:, axis]span = high - low if high > low else 1.0diff --git a/src/manimgx/rendering/feed.py b/src/manimgx/rendering/feed.pyindex 30cfab27..6482514d 100644--- a/src/manimgx/rendering/feed.py+++ b/src/manimgx/rendering/feed.py@@ -14,12 +14,12 @@ import itertoolsimport structfrom collections.abc import Iterator, Sequencefrom dataclasses import dataclass-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Protocolimport numpy as npfrom manimgx import _engine-from manimgx._engine import Recorder, digest+from manimgx._engine import digestfrom manimgx.caches import forgetsfrom manimgx.constants import CapStyleType, LineJointTypefrom manimgx.drawing.geometry import (@@ -515,13 +515,48 @@ Player: type[_engine.Player] | None = getattr(_engine, "Player", None)film is then recorded as a take, with a `Recorder`)."""+class Store(Protocol):+ """What a feed uploads to, by key: the GPU's player, or a recorder writing a take. It+ takes each shape, row block, texture and environment once, grows paths, forgets what is+ evicted, and tells the bytes it holds."""++ def add_path(+ self,+ key: int,+ points: bytes,+ subpaths: bytes,+ centroid_area: Sequence[float],+ /,+ ) -> None: ...+ def add_points(self, key: int, vertices: bytes, /) -> None: ...+ def add_mesh(+ self,+ key: int,+ points: bytes,+ uvs: bytes,+ normals: bytes,+ triangles: bytes,+ outline: int,+ block: int,+ /,+ ) -> None: ...+ def add_rows(self, key: int, rows: bytes, /) -> None: ...+ def add_texture(+ self, key: int, width: int, height: int, rgba: bytes, /+ ) -> None: ...+ def add_environment(+ self, id: int, width: int, height: int, rgbe: bytes, /+ ) -> None: ...+ def grow_path(self, key: int, points: bytes, closed: bool, /) -> None: ...+ def evict(self, keys: Sequence[int], /) -> None: ...+ def held(self) -> int: ...++class Feeder:"""Turns a frame's display list into player records, uploading what appears the first time:to the GPU's player, or to a recorder writing them into a take."""- def __init__(- self, width: int, height: int, player: "_engine.Player | Recorder"- ) -> None:+ def __init__(self, width: int, height: int, player: Store) -> None:self.player = playerself.serial = next(_FEEDERS) # records kept on objects are this feeder'sself.width, self.height = width, height@@ -537,7 +572,6 @@ class Feeder:) # the environment pictures the player has, by id# id(texture array) → (the array, its key): kept, so no other array takes its idself.textures: dict[int, tuple[np.ndarray, int]] = {}- self.texture_bytes: dict[int, int] = {} # key → bytes, for the budget# id(read-only rows) → (rows, key)self.row_keys: dict[int, tuple[np.ndarray, int]] = {}# id(shape) → (shape, topology, uvs, steps, key, A): the mesh's upload inputs.@@ -578,9 +612,9 @@ class Feeder:"""Evict what no frame has shown for KEEP frames (frames mark what they show every MARKframes; the film holds back at most one frame). Memory pressure keeps only the latestframe and the records pinned by the caller, including every pending camera view.- The player also retains resources its queued export retries still need."""- stored, dead = self.player.stored()- pressed |= stored - dead + sum(self.texture_bytes.values()) > BUDGET+ The player evicts in turn: after the frames sent before, and once its video's frames+ in flight that may be drawn again are settled."""+ pressed |= self.player.held() > BUDGETif self.frames - self.swept < SWEEP and not pressed:returnfor data in (*self.latest, *pinned):@@ -594,18 +628,13 @@ class Feeder:# it is only forgottenresident = [k for k in stale if self.sizes.get(k, -1) != -1]if resident:- accepted = set(self.player.evict(resident))- blocked = set(resident) - accepted- stale = [key for key in stale if key not in blocked]- if not stale:- return+ self.player.evict(resident)self.evictions += 1gone = set(stale)for key in stale:del self.last_used[key]self.sizes.pop(key, None)self.structures.pop(key, None)- self.texture_bytes.pop(key, None)# inputs of evicted resources are hashed again if shown againself.textures = {i: kept for i, kept in self.textures.items() if kept[1] not in gone@@ -862,7 +891,6 @@ class Feeder:h, w = data.shape[:2]self.player.add_texture(key, w, h, data.tobytes())self.sizes[key] = 0- self.texture_bytes[key] = data.nbytesself.last_used[key] = self.framesif len(self.textures) > 1 << 8:self.textures.clear()@@ -1077,7 +1105,7 @@ class Feeder:gradient_a[3] = p.stroke_width * 0.01if len(fill[0]) > 1:head[2], head[4] = self.rows(fill[0]), self.rows(fill[1])- elif isinstance(mob, MeshMobject):+ else: # a mesh: the first dispatch drew nothing elsesteps = len(mob.triangles) // (1 if lattice is None else 2)params = [*p.window(steps), p.stroke_width * 0.01, 0.0]if (@@ -1095,8 +1123,6 @@ class Feeder:head[6] = self.camera_view(p.texture, mob, camera, mobjects, width, height, cameras)- else:- return Noneplaced: list[float] = []for i, ((key, a), (matrix, _)) in enumerate(zip(keys, terms[:2], strict=False)):head[i] = keydiff --git a/src/manimgx/rendering/film.py b/src/manimgx/rendering/film.pyindex 72c86efe..3bdd7f2e 100644--- a/src/manimgx/rendering/film.py+++ b/src/manimgx/rendering/film.py@@ -11,7 +11,7 @@ import osfrom collections.abc import Callablefrom dataclasses import asdict, dataclassfrom fractions import Fraction-from typing import TYPE_CHECKING, Final, Literal, cast, get_args+from typing import TYPE_CHECKING, Final, Literal, get_argsfrom warnings import deprecatedfrom manimgx import _engine@@ -44,9 +44,7 @@ X264Preset = Literal[]"""The x264 presets, from fastest to slowest."""-DEFAULT_ENCODER_PRESET: Final[X264Preset] = cast(- X264Preset, _engine.DEFAULT_ENCODER_PRESET-)+DEFAULT_ENCODER_PRESET: Final[X264Preset] = _engine.DEFAULT_ENCODER_PRESET"""The native encoder's default preset, shared by Python and the command line."""DEFAULT_ENCODER_CRF: Final[float] = _engine.DEFAULT_ENCODER_CRF"""The native encoder's default constant rate factor."""@@ -239,7 +237,7 @@ class Film:preset: The x264 preset the video is encoded with: faster presets make largerfiles.crf: The video's quality, as x264's constant rate factor, from 0 to 51:- lower is better, the default value is 18.+ lower is better, the default value is 23."""def __init__(diff --git a/src/manimgx/scene.py b/src/manimgx/scene.pyindex 72473abc..416737c6 100644--- a/src/manimgx/scene.py+++ b/src/manimgx/scene.py@@ -926,7 +926,7 @@ class Scene:and kind.interpolate_keyframes is Transform.interpolate_keyframesand kind.hidden is Animation.hidden # (it hides nothing)and not _updating(node.mobject) # (no updaters act while it plays)- and not node.moving_target()+ and node.moving_target() is None):return Noneif closes.any() and ( # it leaves before the play ends: as a removerdiff --git a/tests/integration/corpus/typecheck.py b/tests/integration/corpus/typecheck.pyindex 4621cdc1..3fea2c49 100644--- a/tests/integration/corpus/typecheck.py+++ b/tests/integration/corpus/typecheck.py@@ -46,7 +46,7 @@ STRICT = ()_REVEAL = re.compile(r"^info\[revealed-type\] Revealed type: `(?P<type>.*)`$")-_SUPPRESSION = re.compile(r"#\s*(?:type|ty|pyright)\s*:\s*ignore")+_SUPPRESSION = re.compile(r"#\s*ty\s*:\s*ignore")_IMPRECISE = re.compile(r"\bUnknown\b|\bAny\b|@Todo")_CALLABLE = re.compile(r"^(bound method |Overload\[|def |<class |<module |<bound method |<function"diff --git a/tests/integration/test_light.py b/tests/integration/test_light.pyindex 708c793b..c45c0f11 100644--- a/tests/integration/test_light.py+++ b/tests/integration/test_light.py@@ -21,6 +21,7 @@ unchanged. A mobject without a material is shaded as it always was, whatever theimport itertoolsfrom collections.abc import Callablefrom pathlib import Path+from typing import Literalimport numpy as npimport pytest@@ -330,9 +331,9 @@ def test_an_environments_sun_casts_a_shadow(tmp_path: Path) -> None:def test_agx_rolls_off_what_clipping_saturates() -> None:- def shown(tone: str) -> np.ndarray:+ def shown(tone: Literal["linear", "agx"]) -> np.ndarray:def build(scene: m.ThreeDScene) -> None:- scene.camera.tone_mapping = tone # type: ignore+ scene.camera.tone_mapping = tonescene.add(plane(), m.SunLight(5 * m.OUT, intensity=4.0))scene.wait(0.1)diff --git a/tests/integration/test_video.py b/tests/integration/test_video.pyindex 11ff7441..9b4e7c16 100644--- a/tests/integration/test_video.py+++ b/tests/integration/test_video.py@@ -221,49 +221,54 @@ def test_eviction_preserves_queued_transparency_retries(@pytest.mark.parametrize("auxiliary", [False, True])-def test_retry_resources_become_evictable_after_their_last_pending_frame(+def test_evicting_what_a_frame_in_flight_draws_waits_for_its_retries(tmp_path: Path, auxiliary: bool) -> None:- player = Player(*SIZE)- feeder = Feeder(*SIZE, player)- camera = m.Camera(three_d=True)- cloud = m.PMobject(stroke_width=4).add_points(- np.random.default_rng(7).uniform(-3, 3, (20, 3)),- rgbas=np.random.default_rng(8).random((20, 4)),- )- image = m.ImageMobject(np.full((2, 2, 4), 128, np.uint8))- view, records, _ = feeder.frame(camera, [cloud, image])- keys = sorted(- {- int(row[name])- for row in np.frombuffer(records, feed.RECORD)- for name in (*feed.KEYS, "texture")- if row[name]- }- )- empty_view, empty_records, _ = feeder.frame(camera, [])- unused = feeder.texture(np.zeros((2, 2, 4), np.uint8))- player.begin_export(str(tmp_path / "pending.mp4"), 30)- for _ in range(2):- cloud.shift(0.1 * m.RIGHT)- view, records, _ = feeder.frame(camera, [cloud, image])+ def film(path: Path, evicting: bool) -> None:+ player = Player(*SIZE)+ feeder = Feeder(*SIZE, player)+ camera = m.Camera(three_d=True)+ # see-through layers overflow the first frame's lists: it is drawn again later, from+ # what it draws, the cloud's and the image's uploads among it+ layers = [+ m.MeshMobject(+ np.array([[-8, -5, z], [8, -5, z], [8, 5, z], [-8, 5, z]]),+ np.array([[0, 1, 2], [0, 2, 3]]),+ color=m.BLUE if i % 2 else m.RED,+ fill_opacity=0.2,+ )+ for i, z in enumerate(np.linspace(-0.2, 0.2, 12))+ ]+ cloud = m.PMobject(stroke_width=4).add_points(+ np.random.default_rng(7).uniform(-3, 3, (20, 3)),+ rgbas=np.random.default_rng(8).random((20, 4)),+ )+ image = m.ImageMobject(np.full((2, 2, 4), 128, np.uint8))+ player.begin_export(str(path), 30)+ view, records, _ = feeder.frame(camera, [*layers, cloud, image])if auxiliary:+ empty_view, empty_records, _ = feeder.frame(camera, [])player.push(empty_view, empty_records, cameras=[(123, *SIZE, view, records)])else:player.push(view, records)- # Empty and repeated requests must not discard dependencies cached on the first.- assert player.evict([]) == []- assert player.evict(keys[:1]) == []- assert player.evict([*keys, unused]) == [unused]- # The ring holds six frames. After five more pushes only the second use is pending.- for _ in range(5):- player.push(empty_view, empty_records)- assert player.evict(keys) == []- player.push(empty_view, empty_records)- assert player.evict(keys) == keys- player.end_export()+ if evicting:+ player.evict(+ [+ key+ for row in np.frombuffer(records, feed.RECORD)+ for key in (int(row[name]) for name in (*feed.KEYS, "texture"))+ if key+ ]+ )+ player.push(*feeder.frame(camera, [m.Square(fill_opacity=1)])[:2])+ player.end_export()++ reference, evicted = tmp_path / "reference.mp4", tmp_path / "evicted.mp4"+ film(reference, False)+ film(evicted, True)+ assert evicted.read_bytes() == reference.read_bytes()@pytest.mark.config(frame_rate=10)diff --git a/tests/test_release.py b/tests/test_release.pyindex 16c28f1d..46ed7e7f 100644--- a/tests/test_release.py+++ b/tests/test_release.py@@ -20,6 +20,8 @@ import pytestimport yamlfrom scripts.release import create_executable, linux_sources, publish_npm, smoke_test+import manimgx as m+ROOT = Path(__file__).parents[1]JOBS = yaml.safe_load((ROOT / ".github/workflows/release.yaml").read_text(encoding="utf-8")@@ -480,8 +482,11 @@ def test_release_smoke_records_decoded_audio_and_a_complete_versioned_take(relocated = runpy.run_path(str(script))scene: dict[str, object] = {}exec(relocated["scene_source"](), scene)+ smoke = scene["Smoke"]+ assert isinstance(smoke, type)+ assert issubclass(smoke, m.Scene)chunks: list[bytes] = []- film = scene["Smoke"]().render(take=chunks.append) # ty: ignore[call-non-callable]+ film = smoke().render(take=chunks.append)take = b"".join(chunks)smoke_test.validate_take(take, film.frame_count)# A nonempty/truncated/failed take used to pass the artifact smoke gate.diff --git a/tests/unit/audio/test_fal.py b/tests/unit/audio/test_fal.pyindex cbb5472b..6feb57c9 100644--- a/tests/unit/audio/test_fal.py+++ b/tests/unit/audio/test_fal.py@@ -4,8 +4,8 @@ audio.- A model is asked at its endpoint with the key, its text in the model's own input, the settingsgiven (over what ManimGX sends unless told otherwise), and what the model is always sent; whatit says is the audio at the URL fal answers with.-- A model's settings are its own: another's are refused as the voice is made, and by a type- checker.+- A model's settings and their values are its own: a type checker refuses another model's, and+ a value the model doesn't take.- A voice is named by its model and its settings, however they were written, never by its key;without a key, it says where to get one.- A model's timing of its text times the words; timing that runs backwards, or none, leaves@@ -67,17 +67,20 @@ def service(monkeypatch: pytest.MonkeyPatch) -> Service:return fake-def written_otherwise(value: object) -> object:+def written_otherwise(settings: dict[str, object]) -> dict[str, object]:"""The same settings, every dict's keys in the other order."""- if isinstance(value, dict):- return {k: written_otherwise(v) for k, v in reversed(value.items())}- return value+ return {+ k: written_otherwise(v) if isinstance(v, dict) else v+ for k, v in reversed(settings.items())+ }models = st.sampled_from(sorted(fal._MODELS))+# `Fal` for a model drawn at run time: no type checker reads the settings it is given+untyped = cast("Callable[..., Fal]", Fal)-def settings_of(model: str) -> st.SearchStrategy[dict[str, object]]:+def settings_of(model: fal.Model) -> st.SearchStrategy[dict[str, object]]:"""Any settings a model's schema allows."""return cast("st.SearchStrategy[dict[str, object]]",@@ -88,14 +91,14 @@ def settings_of(model: str) -> st.SearchStrategy[dict[str, object]]:class TestAsking:@given(model=models, data=st.data(), text=st.text(min_size=1))def test_a_model_is_asked_for_its_text(- self, model: str, data: st.DataObject, text: str+ self, model: fal.Model, data: st.DataObject, text: str) -> None:spec = fal._MODELS[model]settings = data.draw(settings_of(model), label="settings")fake = Service()with pytest.MonkeyPatch.context() as patch:patch.setattr(fal, "_fetch", fake)- speech = Fal(model, key="k", **settings)(text) # type: ignore (a model drawn at run time)+ speech = untyped(model, key="k", **settings)(text)(url, body, headers), (audio_url, nothing, _) = fake.askedassert url == f"https://fal.run/{model}"assert headers == {"Authorization": "Key k"}@@ -110,15 +113,13 @@ class TestAsking:assert speech.text == textassert speech.duration == pytest.approx(0.1)- def test_another_models_settings_are_refused(self) -> None:- untyped = cast("Callable[..., Fal]", Fal) # as a caller no type checker reads- with pytest.raises(TypeError, match="takes"):- untyped("google/gemini-3.8-flash-tts", stability=0.5)-- def test_a_type_checker_knows_each_models_values(self) -> None:- # the suppression is the test: `just check` fails if it goes unused- voice = Fal("google/gemini-3.8-flash-tts", voice="Nobody") # type: ignore- assert voice.settings == {"voice": "Nobody"} # fal refuses it as it speaks+ def test_a_type_checker_knows_each_models_settings(self) -> None:+ # the suppressions are the test: `just check` fails if one goes unused+ others = Fal("google/gemini-3.8-flash-tts", stability=0.5) # ty: ignore[invalid-argument-type]+ nobody = Fal("google/gemini-3.8-flash-tts", voice="Nobody") # ty: ignore[no-matching-overload]+ # a voice keeps what it is given: its type is the check+ assert others.settings == {"stability": 0.5}+ assert nobody.settings == {"voice": "Nobody"}def test_without_a_key_it_says_where_to_get_one(self, monkeypatch: pytest.MonkeyPatch@@ -135,20 +136,20 @@ class TestAsking:class TestNaming:@given(model=models, data=st.data(), key=st.text(min_size=1))def test_a_voice_is_named_by_its_model_and_settings_never_its_key(- self, model: str, data: st.DataObject, key: str+ self, model: fal.Model, data: st.DataObject, key: str) -> None:settings = data.draw(settings_of(model), label="settings")other = data.draw(settings_of(model), label="other settings")- voice = Fal(model, key=key, **settings) # type: ignore (a model drawn at run time)- again = Fal(model, **written_otherwise(settings)) # type: ignore (the same)+ voice = untyped(model, key=key, **settings)+ again = untyped(model, **written_otherwise(settings))assert voices._identity(voice) == voices._identity(again)assert repr(voice) == repr(again)assert voice == againsame = json.dumps(other, sort_keys=True) == json.dumps(settings, sort_keys=True)- named = voices._identity(Fal(model, **other)) # type: ignore (the same)+ named = voices._identity(untyped(model, **other))assert (named == voices._identity(voice)) == samefor another in fal._MODELS.keys() - {model}:- assert voices._identity(Fal(another)) != voices._identity(voice) # type: ignore+ assert voices._identity(Fal(another)) != voices._identity(voice)class TestTiming:diff --git a/tests/unit/audio/test_sound.py b/tests/unit/audio/test_sound.pyindex 717469cb..b16ba10a 100644--- a/tests/unit/audio/test_sound.py+++ b/tests/unit/audio/test_sound.py@@ -397,7 +397,7 @@ class Begun(m.Animation):"""An animation that notes the instant it begins."""def __init__(self, log: list[Fraction], run_time: float = 1.0) -> None:- super().__init__(None, run_time=run_time)+ super().__init__(m.Mobject(), run_time=run_time)self.log = logdef begin(self) -> None:diff --git a/tests/unit/drawing/test_geometry.py b/tests/unit/drawing/test_geometry.pyindex 2bbd71f9..e89fd997 100644--- a/tests/unit/drawing/test_geometry.py+++ b/tests/unit/drawing/test_geometry.py@@ -116,7 +116,7 @@ class TestCurve:# numpy's integers, as numpy code passes themcount = np.int32(n) if numpy else nwith np.errstate(over="raise", invalid="raise"):- split = g.subdivide_bezier(points, count) # ty: ignore[invalid-argument-type]+ split = g.subdivide_bezier(points, count)pieces = split.reshape(n, 4, 3)close(oracles.bezier_points(pieces, np.array([s]))[:, 0],diff --git a/tests/unit/drawing/test_paint.py b/tests/unit/drawing/test_paint.pyindex 70296b41..609baf5b 100644--- a/tests/unit/drawing/test_paint.py+++ b/tests/unit/drawing/test_paint.py@@ -5,7 +5,9 @@from 0 to 255 otherwise); anything else is an error, a malformed hex string too.- Written as hex and read back, a color is itself, to the 8 bits a digit pair holds.- Colors mix in OKLab, weighted by opacity: exactly the ends at 0 and 1, symmetric, in the- gamut, and a transparent end does not tint the mix. A gradient runs from its first color to+ gamut, and a transparent end does not tint the mix. One color mixes to the bit as rows of+ them do, and a color mixed with another holds their mix; a color's array changed in place+ mixes as its new value. A gradient runs from its first color toits last, a colorscale holds its ends and hits its stops.- The conversions are inverse: OKLab, HSV, HSL, and inverting a color.@@ -161,6 +163,38 @@ class TestMix:for row, mixed in zip(a, together, strict=True):np.testing.assert_allclose(mixed, color.mix_rgba(row, b, t), atol=1e-12)+ @given(a=rgba_values, b=rgba_values, t=st.floats(0, 1))+ @example(a=np.array([0.2, 0.4, 0.6, 1.0]), b=np.array([0.2, 0.4, 0.6, 0.5]), t=0.5)+ @example(a=np.array([1.0, 0.0, 0.0, 0.0]), b=np.array([0.0, 0.0, 1.0, 0.0]), t=0.5)+ def test_one_color_mixes_to_the_bit_as_rows_do(+ self, a: np.ndarray, b: np.ndarray, t: float+ ) -> None:+ np.testing.assert_array_equal(+ color._mix_color(a, b, t), color._mix_rows(a, b, t)+ )++ @given(a=rgba_values, b=rgba_values, t=st.floats(0, 1))+ def test_a_color_mixed_with_another_holds_their_mix(+ self, a: np.ndarray, b: np.ndarray, t: float+ ) -> None:+ x = m.ManimColor(tuple(float(v) for v in a))+ y = m.ManimColor(tuple(float(v) for v in b))+ mixed = color.mix_rgba(x.to_rgba(), y.to_rgba(), t)+ made = m.interpolate_color(x, y, t)+ np.testing.assert_array_equal(made.to_rgba(), mixed)+ assert made == m.ManimColor(tuple(mixed.tolist()))++ @given(a=rgba_values, b=rgba_values, c=rgba_values, t=st.floats(0, 1))+ def test_a_color_changed_in_place_mixes_as_its_new_value(+ self, a: np.ndarray, b: np.ndarray, c: np.ndarray, t: float+ ) -> None:+ held = a.copy()+ color.mix_rgba(held, b, t)+ held[:] = c+ np.testing.assert_array_equal(+ color.mix_rgba(held, b, t), color.mix_rgba(c.copy(), b, t)+ )+@given(x=rgbs)def test_oklab_is_inverse(self, x: np.ndarray) -> None:# to 1e-7: the sRGB curve's two standard thresholds are 3e-8 apartdiff --git a/tests/unit/mobjects/test_graph.py b/tests/unit/mobjects/test_graph.pyindex 5a9b1e7f..114b7edd 100644--- a/tests/unit/mobjects/test_graph.py+++ b/tests/unit/mobjects/test_graph.py@@ -12,6 +12,8 @@partitions and root vertex given), and what it does to that graph stays there; a layout byname lays the vertices out as a graph made afresh with that layout would.- Spectral coordinates depend on Laplacian eigenspaces, independent of their solved basis.+- A partite layout's partitions hold only the graph's vertices.+- A vertex's or an edge's own keywords, and an edge's `tip_config`, are mappings.- Each edge uses its current settings; removing it releases those settings and their keys.- A copy goes on apart: what is done to it leaves the graph it was copied from."""@@ -552,3 +554,15 @@ def test_removing_a_vertex_releases_the_keys_of_its_edge_settings() -> None:del keygc.collect()assert reference() is None+++def test_a_partitions_vertices_are_the_graphs() -> None:+ with pytest.raises(ValueError, match="3, in partition 1, is not a vertex"):+ m.Graph([1, 2], [(1, 2)], layout="partite", partitions=[[1], [3]])+++def test_own_keywords_are_mappings() -> None:+ with pytest.raises(TypeError, match="1's own keywords are not a mapping"):+ m.Graph([1, 2], [(1, 2)], vertex_config={1: "red"})+ with pytest.raises(TypeError, match="tip_config is not a mapping"):+ m.DiGraph([1, 2], [(1, 2)], edge_config={"tip_config": 3})diff --git a/tests/unit/mobjects/test_plotting.py b/tests/unit/mobjects/test_plotting.pyindex 22270b66..937f60aa 100644--- a/tests/unit/mobjects/test_plotting.py+++ b/tests/unit/mobjects/test_plotting.py@@ -3,15 +3,17 @@- A number line's `number_to_point` and `point_to_number` are inverse, on any line: anyrange, length, turn and place, linear or logarithmic; the ends of its range are the ends ofthe line, and equal steps of the range are equal steps along it (of exponents, on a- logarithmic line). Ticks and numbers added later follow the line's attributes as they are- then, as if it had been made with them.+ logarithmic line). Points read together read as each does alone: to the bit on a line+ along a coordinate axis, to rounding on a turned one. Ticks and numbers added later follow+ the line's attributes as they are then, as if it had been made with them.- A graph of a function samples it the same however the function takes its argument: arrays- at once, one value at a time, or arrays answered wrongly; an error the function raises- reaches the caller.+ at once (a component given as one number holds for every value), one value at a time, or+ arrays answered wrongly; an error the function raises reaches the caller.- Axes' `coords_to_point` and `point_to_coords` are inverse, for any ranges and lengths, onlinear and logarithmic axes alike; `c2p` and `axes @ coords` are the same map; the origin iswhere the axes cross. Their lengths are the lengths they were made with. Riemann rectangles- span their sample and their base, on turned axes too. A line graph's vertices are its+ span their sample and their base, on turned axes too. The area under a graph holds exactly+ the graph's points whose x is in its range. A line graph's vertices are itscoordinates' points; an empty one draws nothing; its coordinates come in equal numbers.- A plane's lines are its grid: a number plane's at every step from each axis, outward oneach side, every `faded_line_ratio`-th a background line and the ones between faded (the@@ -91,6 +93,37 @@ def test_the_ranges_ends_are_the_lines_ends(line: m.NumberLine) -> None:np.testing.assert_allclose(end, points[-1], atol=1e-9)+def straight_lines(draw: st.DrawFn) -> m.NumberLine:+ """A line along the x axis: made, then only moved."""+ line = m.NumberLine(+ x_range=draw(_axis_ranges()),+ length=draw(st.floats(1, 12)),+ include_tip=draw(st.booleans()),+ )+ return line.shift(draw(arrays(3, 5)))+++@given(line=straight_lines(), offsets=arrays((6, 3), 20))+def test_a_straight_line_reads_points_together_exactly_as_alone(+ line: m.NumberLine, offsets: np.ndarray+) -> None:+ points = line.get_center() + offsets+ alone = [line.point_to_number(point) for point in points]+ np.testing.assert_array_equal(line.point_to_number(points), alone)+++@given(line=lines(), offsets=arrays((6, 3), 20))+def test_a_turned_line_reads_points_together_as_alone(+ line: m.NumberLine, offsets: np.ndarray+) -> None:+ points = line.get_center() + offsets+ alone = [line.point_to_number(point) for point in points]+ np.testing.assert_allclose(+ line.point_to_number(points), alone, rtol=1e-12, atol=1e-9+ )++def test_ticks_and_numbers_added_later_follow_the_lines_attributes() -> None:line = m.NumberLine((0, 3, 1), include_ticks=False, numbers_to_exclude=[0.0])line.font_size = 27@@ -172,6 +205,37 @@ def test_a_graph_samples_its_function_however_it_takes_its_argument()+def test_a_vectorized_curves_number_component_holds_for_every_t() -> None:+ whole = m.ParametricFunction(+ lambda t: (t, t**2, 0), t_range=(0, 1, 0.1), use_vectorized=True+ )+ single = m.ParametricFunction(lambda t: (t, t * t, 0.0), t_range=(0, 1, 0.1))+ np.testing.assert_allclose(whole.points, single.points, rtol=1e-12, atol=1e-12)+++@given(+ function=st.sampled_from(sorted(FUNCTIONS)),+ low=st.floats(-3, 0),+ span=st.floats(0.5, 4),+ ends=st.tuples(st.floats(0, 1), st.floats(0, 1)),+ shift=arrays(3, 2),+)+def test_an_area_holds_its_graphs_points_within_its_range(+ function: str,+ low: float,+ span: float,+ ends: tuple[float, float],+ shift: np.ndarray,+) -> None:+ axes = m.Axes(x_range=(-4, 5, 1), y_range=(-5, 5, 1)).scale(0.8).shift(shift)+ graph = axes.plot(FUNCTIONS[function], x_range=(low, low + span))+ a, b = sorted(low + end * span for end in ends)+ within = [p for p in graph.points if a <= axes.p2c(p)[0] <= b]+ edge = [axes.c2p(a), graph.function(a), *within, graph.function(b), axes.c2p(b)]+ area = axes.get_area(graph, x_range=(a, b))+ np.testing.assert_array_equal(area.points, m.Polygon(*edge).points)++def test_an_error_the_function_raises_reaches_the_caller() -> None:def fail(t: float) -> float:if t < 0:diff --git a/tests/unit/rendering/test_feed.py b/tests/unit/rendering/test_feed.pyindex a1697403..c9cee09e 100644--- a/tests/unit/rendering/test_feed.py+++ b/tests/unit/rendering/test_feed.py@@ -33,7 +33,7 @@ keeps the player's store in step with its own books; the player derives what draimport contextlibimport gcimport weakref-from collections.abc import Callable+from collections.abc import Callable, Sequencefrom dataclasses import dataclassimport numpy as np@@ -46,6 +46,7 @@ from tests.scenes import frames, scene_3dimport manimgx as mfrom manimgx._engine import Player, Recorder, digest+from manimgx.drawing.geometry import Pathfrom manimgx.rendering import feed@@ -354,7 +355,7 @@ def test_batched_reveals_follow_the_same_pace_as_individual_frames(def record_of(mob: m.Mobject, sink: "Sink | Recorder") -> np.void:"""The record a feed of its own makes of a mobject alone, in a 2D view."""- feeder = feed.Feeder(32, 32, sink) # ty: ignore[invalid-argument-type]+ feeder = feed.Feeder(32, 32, sink)objects: list[m.Mobject] = [mob]made = feed.unpack(feeder.record(mob, m.Camera(), False, objects, 32, 32, [], set())@@ -483,7 +484,6 @@ class Sink:self.kinds: dict[int, str] = {} # what each key was uploaded asself.vertices: dict[int, int] = {} # a mesh's vertex count, as sentself.failing: set[str] = set()- self.protected: set[int] = set() # resources retained by queued framesdef _add(self, kind: str, key: int, parts: list[Part], *args: object) -> None:if kind in self.failing:@@ -498,7 +498,7 @@ class Sink:self.resident[key] = contentdef add_path(- self, key: int, points: bytes, subpaths: bytes, ca: list[float]+ self, key: int, points: bytes, subpaths: bytes, ca: Sequence[float]) -> None:self._add("path", key, [(points, "<f8"), (subpaths, None)], points, subpaths, ca@@ -526,18 +526,17 @@ class Sink:def grow_path(self, key: int, points: bytes, closed: bool = False) -> None:raise AssertionError("no growing paths here")- def evict(self, keys: list[int]) -> list[int]:+ def evict(self, keys: Sequence[int]) -> None:if "evict" in self.failing:self.failing.discard("evict")raise Injected("evict")- accepted = self.engine.evict([key for key in keys if key not in self.protected])- for key in accepted:+ self.engine.evict(keys)+ for key in keys:assert key in self.resident, f"{key:x} evicted, never resident"del self.resident[key]- return accepted- def stored(self) -> tuple[int, int]:- return self.engine.stored()+ def held(self) -> int:+ return self.engine.held()def test_a_tween_materializes_only_the_frames_consumed_and_reloads_evicted_values() -> (@@ -552,7 +551,7 @@ def test_a_tween_materializes_only_the_frames_consumed_and_reloads_evicted_valueleaf = start.copy()progress = np.tile(np.linspace(0.1, 0.9, 25), 3)camera, path, sink = m.Camera(), m.straight_path(), Sink()- feeder = feed.Feeder(32, 32, sink) # ty: ignore[invalid-argument-type]+ feeder = feed.Feeder(32, 32, sink)frames = iter(feeder.tween(camera,@@ -566,7 +565,7 @@ def test_a_tween_materializes_only_the_frames_consumed_and_reloads_evicted_valueif number == 0:assert sum(kind == "points" for kind in sink.kinds.values()) <= 2expected_sink = Sink()- expected = feed.Feeder(32, 32, expected_sink) # ty: ignore[invalid-argument-type]+ expected = feed.Feeder(32, 32, expected_sink)alone = start.copy()alone.interpolate(start, end, float(t), path)assert records == expected.frame(camera, [alone])[1]@@ -593,15 +592,22 @@ def test_streaming_still_mixes_whole_keyframe_intervals(start.copy().shift(m.UP),]leaf, sink, camera = start.copy(), Sink(), m.Camera()- feeder = feed.Feeder(32, 32, sink) # ty: ignore[invalid-argument-type]+ feeder = feed.Feeder(32, 32, sink)intervals = np.repeat([0, 1, 0], 30)progress = np.tile(np.linspace(0, 1, 30), 3)batches: list[int] = []mix = feeder.mix- def measured(*args: object) -> np.ndarray | None:- batches.append(len(args[3])) # ty: ignore[invalid-argument-type]- return mix(*args) # ty: ignore[invalid-argument-type]+ def measured(+ a: m.Mobject,+ b: m.Mobject,+ path: Path,+ t: np.ndarray,+ args: tuple,+ live: np.void | None,+ ) -> np.ndarray | None:+ batches.append(len(t))+ return mix(a, b, path, t, args, live)monkeypatch.setattr(feeder, "mix", measured)frames = feeder.tween(@@ -642,7 +648,7 @@ def test_a_delayed_tween_can_return_before_its_start_after_eviction(camera, sink = m.Camera(), Sink()if fixed:camera.fixed_in_frame_mobjects.add(leaf)- feeder = feed.Feeder(32, 32, sink) # ty: ignore[invalid-argument-type]+ feeder = feed.Feeder(32, 32, sink)original = feeder.frame(camera, [leaf])[1]for number, (_, records) in enumerate(feeder.tween(camera, [leaf], leaves)):if number in (0, 3):@@ -660,7 +666,7 @@ def test_a_delayed_tween_can_return_before_its_start_after_eviction(def test_pressure_preserves_pending_current_and_camera_resources() -> None:sink = Sink()- feeder = feed.Feeder(32, 32, sink) # ty: ignore[invalid-argument-type]+ feeder = feed.Feeder(32, 32, sink)keys = [feeder.path(m.RegularPolygon(n)._geometry.terms[0][1])[0] for n in range(3, 7)]@@ -770,7 +776,7 @@ class Residency(RuleBasedStateMachine):@initialize()def begin(self) -> None:self.sink = Sink()- self.feeder = feed.Feeder(32, 32, self.sink) # ty: ignore[invalid-argument-type]+ self.feeder = feed.Feeder(32, 32, self.sink)self.camera = m.Camera()self.pool: list[m.Mobject] = [mobject(k, 0) for k in range(6)]self.held: list[Handed] = [] # the direct uploads whose inputs the test holds@@ -849,12 +855,6 @@ class Residency(RuleBasedStateMachine):self.feeder.sweep()self.sink.failing.discard("evict")- @rule(which=st.lists(st.integers(0, 63), max_size=6))- def pending(self, which: list[int]) -> None:- """Queued frames may retain some resources until a later sweep."""- keys = list(self.sink.resident)- self.sink.protected = {keys[i % len(keys)] for i in which} if keys else set()-@rule(kind=st.sampled_from(["path", "points", "mesh", "rows", "texture", "evict"]))def fail_next(self, kind: str) -> None:self.sink.failing.add(kind)@@ -911,7 +911,6 @@ class Residency(RuleBasedStateMachine):go of is collected: a key in flight (a failed upload's) holds its input until then."""self.held, self.pool = [], []self.sink.failing.clear()- self.sink.protected.clear()self.feeder.frame(self.camera, []) # a frame of nothing: the last shown holds nothing@@ -928,7 +927,7 @@ TestResidency.settings = settings(max_examples=60, stateful_step_count=40)def test_a_picture_is_not_one_of_the_films_frames() -> None:sink = Sink()- feeder = feed.Feeder(32, 32, sink) # ty: ignore[invalid-argument-type]+ feeder = feed.Feeder(32, 32, sink)camera = m.Camera()feeder.frame(camera, [m.Square(fill_opacity=1)])held = set(sink.resident)diff --git a/tests/unit/test_mobject.py b/tests/unit/test_mobject.pyindex 1e5b79c2..8c8682ac 100644--- a/tests/unit/test_mobject.py+++ b/tests/unit/test_mobject.py@@ -2,7 +2,7 @@- Its family is a tree: whatever is added, removed, inserted or assigned, and however, no mobjectholds itself (not even through another), and the family lists each member once, in preorder,- where it last occurs. Adding anything else is an error.+ where it last occurs.- A transform is the same transform of its points: shifts, scales, turns, stretches andmatrices, about the points their docstrings name (its box's center or edge by default), inany order, leave the family's points where plain arithmetic puts them.@@ -252,17 +252,6 @@ TestFamily = Family.TestCaseTestFamily.settings = settings(stateful_step_count=25)[email protected]("value", [1, "a", None, np.zeros(3)])-def test_only_mobjects_join_a_family(value: object) -> None:- for join in (- lambda g: g.add(value),- lambda g: g.add_to_back(value),- lambda g: g.insert(0, value),- ):- with pytest.raises(TypeError):- join(m.VGroup())--class Transforms(RuleBasedStateMachine):"""A group of paths under any chain of transforms has the points plain arithmetic gives,about the pivots the docstrings name."""