The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Show an image drawn smaller than its pixels as their mean
Sina Atalay3f78be359aa9
diff --git a/docs/content/changelog.md b/docs/content/changelog.mdindex dc814ef0..814d2fab 100644--- a/docs/content/changelog.md+++ b/docs/content/changelog.md@@ -51,6 +51,7 @@ The notable changes to ManimGX, release by release. The format follows- Make the folder a video or a storyboard is written in when it is missing (`render -o new/out.mp4`, `inspect -o new/sheet.png` and `Scene.render`), instead of failing with "No such file or directory" ([#34](https://github.com/academa-labs/manimgx/issues/34)).- Raise a ValueError, naming where it is, for a nested, unclosed or stray bracket in a `say` script, which was spoken and captioned ([#39](https://github.com/academa-labs/manimgx/issues/39)).- Time and caption speech in the pieces Unicode lets a line break between, so a `say` span in Chinese, Japanese or Thai, written without spaces, is timed by its own characters or words, where the whole sentence was one word ([#40](https://github.com/academa-labs/manimgx/issues/40)). Captions are the text as it is written, at most 42 columns wide (a Chinese or Japanese character takes two); a line never starts with a closing mark such as `,` or `」`, and ends where a sentence does, a quoted one too. A speech's words are found in its text by themselves, so a trimmed speech, or a voice that cuts its words its own way, no longer fails or mistimes a span; and an empty span after the last word starts where that word ends.+- Show an image drawn smaller than its pixels as their mean: each pixel of the video shows the mean of the picture's pixels it covers, however the image is squashed and whatever its `resampling_algorithm`, where it showed the picture at one point, so thin lines broke up and small text was unreadable ([#36](https://github.com/academa-labs/manimgx/issues/36)). An image at its size or larger is drawn as before.- 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.diff --git a/docs/content/developer-guide/engine.md b/docs/content/developer-guide/engine.mdindex 51eaae2f..af66ac9b 100644--- a/docs/content/developer-guide/engine.md+++ b/docs/content/developer-guide/engine.md@@ -168,7 +168,11 @@ second term only while a shape morphs). The kinds differ only in how their vertitriangles:- A point is a disk that faces the camera.-- A mesh is its triangles, optionally textured.+- A mesh is its triangles, optionally textured. Where a pixel covers at most one of a+ texture's pixels, it shows the texture as its image's `resampling_algorithm`+ reconstructs it; where it covers more, the mean of the pixels it covers, from up to 16+ points of its footprint, each read from the image's levels of detail (made when the+ image is uploaded).Transparent mesh fragments are collected in lists and composited in depth order. Pointsprites are sorted and drawn between the other geometry's depth layers. Raster samplediff --git a/rust/engine/src/blend.wgsl b/rust/engine/src/blend.wgslindex 7aab6629..55fba142 100644--- a/rust/engine/src/blend.wgsl+++ b/rust/engine/src/blend.wgsl@@ -502,13 +502,57 @@ fn lit_texel(texel: vec4<f32>, light: f32, opacity: f32) -> vec4<f32> {return vec4<f32>(clamp(texel.rgb + light * texel.a, vec3<f32>(0.0), vec3<f32>(texel.a)), texel.a) * opacity;}-// A mesh's picture at the fragment: textures are premultiplied; an image is reconstructed by its resampling algorithm:-// linear (and a camera's view, a colormap) by the sampler, nearest and cubic here.+// The picture at uv, reconstructed from its pixels by an image's resampling algorithm: linear (and a camera's view, a+// colormap) by the sampler, nearest and cubic here. Textures are premultiplied.+fn picture(uv: vec2<f32>, kernel: u32) -> vec4<f32> {+ if ((kernel & (NEAREST | CUBIC)) != 0u) {+ return reconstructed(uv, kernel);+ }+ return textureSampleLevel(image, image_sampler, uv, 0.0);+}++const TAPS: u32 = 16u; // the most points a pixel's mean of a picture is found from++// A mesh's picture at the fragment. Where the pixel covers at most one of the picture's pixels each way, the picture+// at its centre; where more, the picture's mean over what it covers: the pixel's square as it lies on the picture (uv's+// derivatives), at the centres of up to TAPS cells, as near square as they can be and no more than it takes for cells+// one of the picture's pixels wide, each the picture there (reconstructed by its algorithm while there are at most+// four, linearly among more), or, where a cell is wider, the mean of the pixels it covers (the level of detail whose+// pixels are as wide, linear between two: `render.rs`'s `levels`). From one of the picture's pixels to a quarter more,+// it passes from the one to the other, so a picture shrinking past its size changes smoothly. (The derivatives are+// taken before anything branches.)fn texel_of(in: Shaded) -> vec4<f32> {- if ((in.textured & (NEAREST | CUBIC)) != 0u) {- return reconstructed(in.uv, in.textured);+ let size = vec2<f32>(textureDimensions(image));+ let right = dpdx(in.uv); // the step to the next pixel right, on the picture+ let below = dpdy(in.uv);+ let across = length(right * size); // in the picture's pixels+ let down = length(below * size);+ let share = clamp(4.0 * (max(across, down) - 1.0), 0.0, 1.0); // how much of it the mean is+ var texel = vec4<f32>(0.0);+ if (share < 1.0) {+ texel = picture(in.uv, in.textured);+ }+ if (share > 0.0) {+ // (less a thousandth: what covers a whole number of cells takes no more, though derivatives round)+ let cell = max(1.0, sqrt(across * down / f32(TAPS)));+ let rows = clamp(u32(ceil(down / cell - 1e-3)), 1u, TAPS);+ let columns = clamp(u32(ceil(across / cell - 1e-3)), 1u, TAPS / rows);+ let level = log2(max(across / f32(columns), down / f32(rows)));+ let reconstructed_points = level <= 0.0 && rows * columns <= 4u;+ var sum = vec4<f32>(0.0);+ for (var j = 0u; j < rows; j++) {+ for (var i = 0u; i < columns; i++) {+ let at = in.uv + ((f32(i) + 0.5) / f32(columns) - 0.5) * right + ((f32(j) + 0.5) / f32(rows) - 0.5) * below;+ if (reconstructed_points) {+ sum += picture(at, in.textured);+ } else {+ sum += textureSampleLevel(image, image_sampler, at, max(level, 0.0));+ }+ }+ }+ texel = mix(texel, sum / f32(rows * columns), share);}- return textureSampleLevel(image, image_sampler, in.uv, 0.0); // (one level)+ return texel;}// A mesh without a material: its colour; a textured one keeps its pixels (lit, if it is: a surface's colormap) anddiff --git a/rust/engine/src/render.rs b/rust/engine/src/render.rsindex 8c842975..763a7c58 100644--- a/rust/engine/src/render.rs+++ b/rust/engine/src/render.rs@@ -1168,10 +1168,12 @@ impl Gpu {let lists = depth.map(|depth| layout("append", &[written(0), written(1), written(2), depth]));let slabs = depth.map(|depth| [layout("slab bounds", &[bounds]), layout("slab bounds and depth", &[bounds, depth])]);let raster = RasterLayouts { scene: layout("scene", &[view, storage(1), storage(2), storage(4), storage(5), storage(6), storage(7)]), lists, slabs, shadows };+ // a picture's (and a camera's view's): linear in a level of detail and between two (see `levels`)let sampler = device.create_sampler(&wgpu::SamplerDescriptor {label: Some("image"),mag_filter: wgpu::FilterMode::Linear,min_filter: wgpu::FilterMode::Linear,+ mipmap_filter: wgpu::MipmapFilterMode::Linear,..Default::default()});let shadow_compare = device.create_sampler(&wgpu::SamplerDescriptor {@@ -1355,12 +1357,13 @@ impl Gpu {[(p[0] as u32 * a / 255) as u8, (p[1] as u32 * a / 255) as u8, (p[2] as u32 * a / 255) as u8, p[3]]}).collect();+ let (mip_level_count, levels) = levels(width as usize, height as usize, premultiplied);let texture = self.device.create_texture_with_data(&self.queue,&wgpu::TextureDescriptor {label: Some("image"),size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },- mip_level_count: 1,+ mip_level_count,sample_count: 1,dimension: wgpu::TextureDimension::D2,format: COLOR,@@ -1368,7 +1371,7 @@ impl Gpu {view_formats: &[],},wgpu::util::TextureDataOrder::LayerMajor,- &premultiplied,+ &levels,);let view = texture.create_view(&Default::default());self.device.create_bind_group(&wgpu::BindGroupDescriptor {@@ -1382,6 +1385,58 @@ impl Gpu {}}+/// A picture's levels of detail, as a texture with every mip level takes them: how many, and their RGBA8 pixels one+/// level after another, level 0 the picture's own. Each level is half the one before each way (rounded down, at least+/// 1), and each of its pixels the mean of what it covers of the level before: so, as near as 8-bit values round, the+/// mean of the picture's own pixels it covers (`blend.wgsl`'s `texel_of` reads them where a pixel of the view covers+/// many). Premultiplied pixels, so a transparent one adds no color.+fn levels(width: usize, height: usize, picture: Vec<u8>) -> (u32, Vec<u8>) {+ let sizes: Vec<(usize, usize)> = std::iter::successors(Some((width, height)), |&(w, h)| (w > 1 || h > 1).then(|| ((w / 2).max(1), (h / 2).max(1)))).collect();+ let mut all = picture;+ all.reserve_exact(sizes[1..].iter().map(|&(w, h)| w * h * 4).sum());+ let mut at = 0;+ for &(w, h) in &sizes[..sizes.len() - 1] {+ let next = halved(&all[at..at + w * h * 4], w, h);+ at += w * h * 4;+ all.extend(next);+ }+ (sizes.len() as u32, all)+}++/// A level of `w` x `h` pixels halved each way (rounded down, at least 1): each pixel the mean of the pixels it covers,+/// each counting by how much of it is covered (where a side is odd, a pixel straddles two): exact in integers, rounded+/// to the nearest once.+fn halved(level: &[u8], w: usize, h: usize) -> Vec<u8> {+ // a side of n pixels becoming m: pixel j of the half spans [j n, (j + 1) n) in m-ths of a pixel, so it covers pixel+ // i, [i m, (i + 1) m), by their overlap, and all it covers by n+ let spans = |n: usize| -> Vec<Vec<(usize, u64)>> {+ let m = (n / 2).max(1);+ let span = |j: usize| {+ let (lo, hi) = (j * n, (j + 1) * n);+ (lo / m..hi.div_ceil(m)).map(|i| (i, (hi.min((i + 1) * m) - lo.max(i * m)) as u64)).collect()+ };+ (0..m).map(span).collect()+ };+ let (across, down) = (spans(w), spans(h));+ let whole = (w * h) as u64;+ let mut to = Vec::with_capacity(across.len() * down.len() * 4);+ for ys in &down {+ for xs in &across {+ let mut sum = [0u64; 4];+ for &(y, wy) in ys {+ for &(x, wx) in xs {+ let pixel = &level[(y * w + x) * 4..][..4];+ for (s, &v) in sum.iter_mut().zip(pixel) {+ *s += wy * wx * u64::from(v);+ }+ }+ }+ to.extend(sum.map(|s| ((s + whole / 2) / whole) as u8));+ }+ }+ to+}+/// Where a view is drawn — the frame, or a texture another view samples (a camera's view) — by/// a 2D view's composite, or by the raster pipeline (it gets the pipeline's attachments when that/// first draws into it). Also the raster atlas a 2D view's point clouds and meshes are drawn in.@@ -2897,6 +2952,51 @@ pub(crate) fn count(bytes: &[u8]) -> u64 {bytemuck::pod_read_unaligned::<u32>(&bytes[..4]) as u64}+#[cfg(test)]+mod levels_of_detail {+ use super::*;++ /// A picture's levels' sizes and pixels, one channel of each (the first).+ fn levels_of(width: usize, height: usize, picture: &[u8]) -> Vec<(usize, usize, Vec<u8>)> {+ let (count, all) = levels(width, height, picture.iter().flat_map(|&v| [v, 0, 0, 0]).collect());+ let (mut w, mut h, mut at, mut out) = (width, height, 0, Vec::new());+ for _ in 0..count {+ out.push((w, h, all[at..at + w * h * 4].iter().step_by(4).copied().collect()));+ at += w * h * 4;+ (w, h) = ((w / 2).max(1), (h / 2).max(1));+ }+ assert_eq!(at, all.len());+ out+ }++ #[test]+ fn a_level_halves_the_one_before_down_to_one_pixel() {+ let sizes: Vec<(usize, usize)> = levels_of(6, 3, &[0; 18]).iter().map(|&(w, h, _)| (w, h)).collect();+ assert_eq!(sizes, [(6, 3), (3, 1), (1, 1)]);+ assert_eq!(levels_of(1, 1, &[7]), [(1, 1, vec![7])]);+ }++ #[test]+ fn a_pixel_is_the_mean_of_the_pixels_it_covers() {+ // even sides: each pixel the mean of 2 x 2, rounded to the nearest+ let even = levels_of(4, 2, &[0, 10, 200, 201, 20, 30, 100, 100]);+ assert_eq!(even[1].2, [15, 150]); // 150.25: rounded once, not after each way+ assert_eq!(even[2].2, [83]); // (15 + 150) / 2, from the level before+ // an odd side: 5 become 2, each covering 2.5 of them, the middle one split between both+ let odd = levels_of(5, 1, &[0, 50, 100, 150, 250]);+ assert_eq!(odd[1].2, [40, 180]); // (2·0 + 2·50 + 100) / 5, (100 + 2·150 + 2·250) / 5+ // 3 become 1: the mean of all+ assert_eq!(levels_of(1, 3, &[30, 60, 90])[1].2, [60]);+ }++ #[test]+ fn a_transparent_pixel_adds_no_color() {+ // premultiplied: an opaque red pixel and a transparent one make half-transparent red+ let (_, all) = levels(2, 1, vec![255, 0, 0, 255, 0, 0, 0, 0]);+ assert_eq!(&all[8..], [128, 0, 0, 128]);+ }+}+#[cfg(test)]mod buffer_contract {use super::*;diff --git a/src/manimgx/constants.py b/src/manimgx/constants.pyindex 599b27d6..f3000a36 100644--- a/src/manimgx/constants.py+++ b/src/manimgx/constants.py@@ -260,10 +260,11 @@ START_Y = 20"""Kept for Manim compatibility; unused."""type Resampling = Literal[0, 2, 3]-"""How an image is reconstructed from its pixels where it is drawn larger than they are,-numbered as the Pillow library numbers its filters: 0, nearest (each pixel a square of-its color); 2, linear; 3, cubic (Keys' cubic convolution with a = −1/2, Pillow's-BICUBIC: smooth, and through every pixel)."""+"""How an image is reconstructed from its pixels where it is drawn larger than they are+(drawn smaller, it shows their mean, whatever the algorithm), numbered as the Pillow+library numbers its filters: 0, nearest (each pixel a square of its color); 2, linear;+3, cubic (Keys' cubic convolution with a = −1/2, Pillow's BICUBIC: smooth, and through+every pixel)."""RESAMPLING_ALGORITHMS: dict[str, Resampling] = {"nearest": 0,"none": 0,diff --git a/src/manimgx/mobjects/images.py b/src/manimgx/mobjects/images.pyindex fbde29ab..4c71dbfc 100644--- a/src/manimgx/mobjects/images.py+++ b/src/manimgx/mobjects/images.py@@ -36,7 +36,9 @@ class ImageMobject(MeshMobject):larger than its pixels, the picture is reconstructed from them by`resampling_algorithm`: by default a smooth cubic through every pixel; linear blendsneighboring pixels; nearest shows each pixel as a square of its color. Shown smaller,- it is sampled, not averaged. The mobject's opacity multiplies its pixels' own.+ each pixel of the video shows the mean of the picture's pixels it covers, whatever+ the algorithm, so thin lines and small text stay whole at any size. The mobject's+ opacity multiplies its pixels' own.Args:filename_or_array: The picture: an image file's path, the file's contentsdiff --git a/tests/integration/test_drawing.py b/tests/integration/test_drawing.pyindex 4f6013ee..e98453c9 100644--- a/tests/integration/test_drawing.py+++ b/tests/integration/test_drawing.py@@ -14,7 +14,8 @@ Strokes are drawn as SVG and PostScript define them (h: half the stroke's width)A fill covers what its curves enclose (closed by a straight return to their start), howeverfar its control points bulge. An image enlarged is reconstructed from its pixels by its`resampling_algorithm`: nearest holds each pixel, linear runs straight between pixel centres,-cubic follows Keys' kernel.+cubic follows Keys' kernel. An image shrunk shows in each pixel the mean of its own pixels+that pixel covers, whatever its algorithm and however it is squashed."""from collections.abc import Callable@@ -240,6 +241,79 @@ def test_an_image_is_reconstructed_by_its_resampling_algorithm(assert row[columns] == pytest.approx(255 * kernel(t), abs=1.5)+NOISE = np.random.default_rng(36).integers(0, 256, (384, 384), dtype=np.uint8)+"""Gray noise: no two neighboring pixels alike, so a pixel that shows only some of the+pixels it covers shows something else than their mean."""+++def _frame(+ pixels: np.ndarray, size: tuple[float, float], algorithm: Resampling = 3+) -> np.ndarray:+ """A gray picture drawn `size` pixels wide and tall at the frame's centre: the frame's+ red."""++ def drawn(scene: m.Scene) -> None:+ image = m.ImageMobject(pixels, resampling_algorithm=algorithm)+ unit = config.frame_height / config.pixel_height # a pixel, in scene units+ image.stretch_to_fit_width(size[0] * unit)+ scene.add(image.stretch_to_fit_height(size[1] * unit))++ return scenes.frames(scenes.scene(drawn))[-1][..., 0].astype(float)+++def _shrunk(pixels: np.ndarray, algorithm: Resampling = 3) -> np.ndarray:+ """A picture of 48 x 48 blocks drawn 48 x 48 pixels: what the frame shows of it, but its+ outermost pixels, which show its edge too."""+ top, left = (config.pixel_height - 48) // 2, (config.pixel_width - 48) // 2+ return _frame(pixels, (48, 48), algorithm)[top + 1 : top + 47, left + 1 : left + 47]+++def _means(pixels: np.ndarray) -> np.ndarray:+ """The means of the picture's 48 x 48 blocks, but the outermost."""+ h, w = pixels.shape[0] // 48, pixels.shape[1] // 48+ return pixels.reshape(48, h, 48, w).mean(axis=(1, 3))[1:-1, 1:-1]++[email protected](pixel_width=320, pixel_height=180)[email protected]("algorithm", [0, 2, 3], ids=["nearest", "linear", "cubic"])[email protected]("shrink", [1, 2, 3, 4, 8])+def test_an_image_shrunk_shows_in_each_pixel_the_mean_of_the_pixels_it_covers(+ shrink: int, algorithm: Resampling+) -> None:+ pixels = NOISE[: 48 * shrink, : 48 * shrink]+ assert np.abs(_shrunk(pixels, algorithm) - _means(pixels)).max() <= 1++[email protected](pixel_width=320, pixel_height=180)[email protected]("shrink", [5, 6, 7])+def test_an_image_shrunk_any_amount_shows_nearly_the_mean(shrink: int) -> None:+ # where a pixel's points on the picture are more than a pixel of it apart, each is the+ # mean of a cell of its pixels, from its levels of detail, which count whole pixels+ pixels = NOISE[: 48 * shrink, : 48 * shrink]+ error = np.abs(_shrunk(pixels) - _means(pixels))+ assert error.mean() < 4+ assert error.max() < 20++[email protected](pixel_width=320, pixel_height=180)+def test_an_image_squashed_one_way_keeps_its_detail_the_other() -> None:+ # 8 times as wide as it is drawn, as tall: a pixel shows the mean of the 8 pixels of+ # its row it covers, and each row its own+ pixels = NOISE[:48, : 48 * 8]+ assert np.abs(_shrunk(pixels) - _means(pixels)).max() <= 1++[email protected](pixel_width=320, pixel_height=180)+def test_an_image_a_little_smaller_than_its_pixels_is_nearly_as_at_their_size() -> None:+ # a picture shrinking past its size passes from its reconstruction to the mean of what a+ # pixel covers over a quarter more of its pixels a pixel: so a line one pixel wide, 2%+ # smaller, keeps nearly all its light in its pixel, not a quarter less at once+ line = np.zeros((96, 96), dtype=np.uint8)+ line[:, 48] = 255 # the column whose centre is the frame's pixel 160's, at its size+ assert _frame(line, (96, 96), 2)[90, 160] == 255+ assert _frame(line, (96 / 1.02, 96 / 1.02), 2)[90, 160] > 240++def _filled(mob: m.VMobject) -> float:"""The area a white fill shows alone on black, in square units: its pixels' coveragesummed."""