The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Give <manimgx-player> a video's controls, loop and muted
Sina Atalayd8b8fc226ab5
diff --git a/browser/README.md b/browser/README.mdindex 304accc8..5674303d 100644--- a/browser/README.md+++ b/browser/README.md@@ -13,7 +13,7 @@ npm install manimgximport "manimgx";</script>-<manimgx-player autoplay>+<manimgx-player controls autoplay><script type="text/python">import manimgx as m@@ -41,6 +41,9 @@ document.body.append(player);WebAssembly draws the film with WebGPU, and its face over it: the controls, the time, thetimeline in the scene's plays (each named by its line of code), captions, the scene's errorand the keys (`?` lists them), all in ManimGX's fonts. A click, a tap and a key do the same.+- **A `<video>`'s attributes**: `controls` (without them, the player is a picture that plays,+ and every click, key and wheel is the page's), `autoplay`, `loop` and `muted`.+ `<manimgx-player autoplay loop muted>` plays a scene as a GIF does.- **Any frame, at once**: the film is recorded as it is made (a *take*: each shape once, theneach frame), and any moment of it is drawn at once, so it plays before the scene hasfinished and seeks instantly. Each frame is drawn at the size the page shows it, in thediff --git a/browser/src/engine.ts b/browser/src/engine.tsindex 185b9a46..4dc675d1 100644--- a/browser/src/engine.ts+++ b/browser/src/engine.ts@@ -18,6 +18,9 @@ export interface Player {resize(width: number, height: number, scale: number): void;hide(hidden: boolean): void;fullscreen(on: boolean): void;+ controls(on: boolean): void;+ looping(on: boolean): void;+ mute(on: boolean): void;wake(): number;draw(): void;asks(): (["scene", string] | ["fullscreen", boolean])[];diff --git a/browser/src/player.ts b/browser/src/player.tsindex fab0e602..1a3b2897 100644--- a/browser/src/player.ts+++ b/browser/src/player.ts@@ -3,9 +3,11 @@// time, the plays, captions, the scene's error, the keys) onto a canvas with WebGPU, and keeps the// clock and the sound. The element only hands it what its viewer does, in the web's own words,// draws it when it is due, and does what it asks (another scene, full screen). Its scene is-// Python, run in the browser by Pyodide (see director.ts).+// Python, run in the browser by Pyodide (see director.ts). It takes a <video>'s `controls`+// (without them, it is a picture that plays, the page handling every event), `autoplay`, `loop`+// and `muted`.//-// <manimgx-player><script type="text/python"> …a scene… </script></manimgx-player>+// <manimgx-player controls><script type="text/python"> …a scene… </script></manimgx-player>// player.source = code (the film made again, time kept)import type { Engine, Player } from "./engine.js";@@ -103,9 +105,9 @@ function begin(): Page {let films = 0;/** A scene written in Python, made in the page and played on a canvas by ManimGX's engine,- * with the engine's own controls. */+ * with the engine's own controls if it has `controls`. */export class ManimgxPlayer extends HTMLElement {- static observedAttributes = ["scene"];+ static observedAttributes = ["scene", "controls", "loop", "muted"];#film = 0;#canvas: HTMLCanvasElement;@@ -115,6 +117,7 @@ export class ManimgxPlayer extends HTMLElement {#wants: { time: number; playing: boolean | null } = { time: 0, playing: null };#begun = false;#failed = false;+ #tabbed = false; // its tabindex is its own, not the page's#player: Player | null = null; // native GPU resources belong to one connected lifetime#connection: AbortController | undefined;#timer: number | undefined;@@ -137,7 +140,6 @@ export class ManimgxPlayer extends HTMLElement {}connectedCallback(): void {- if (!this.hasAttribute("tabindex")) this.tabIndex = 0; // it takes keysif (this.#connection || this.#failed) return;this.#film = ++films; // late bytes from an earlier connection belong to its old decoderconst connection = (this.#connection = new AbortController());@@ -173,8 +175,14 @@ export class ManimgxPlayer extends HTMLElement {}}- attributeChangedCallback(): void {- if (this.#begun && this.#source !== null) this.#run();+ attributeChangedCallback(name: string): void {+ if (name === "scene") {+ if (this.#begun && this.#source !== null) this.#run();+ return;+ }+ if (name === "controls") this.#tab();+ this.#heed(name);+ this.#after();}/** The scene's Python source: set it, and the film is made again (the time kept). */@@ -262,6 +270,7 @@ export class ManimgxPlayer extends HTMLElement {try {const { time, playing } = this.#wants;this.#player = new made.Player(canvas, time, playing ?? this.hasAttribute("autoplay"), MAC);+ for (const name of ["controls", "loop", "muted"]) this.#heed(name);this.#player.resize(canvas.width, canvas.height, devicePixelRatio);} catch (error) {return this.#fail(error);@@ -272,6 +281,27 @@ export class ManimgxPlayer extends HTMLElement {this.#after();}+ /** Its `controls`, `loop` or `muted`, the player's. */+ #heed(name: string): void {+ const on = this.hasAttribute(name);+ if (name === "controls") this.#player?.controls(on);+ if (name === "loop") this.#player?.looping(on);+ if (name === "muted") this.#player?.mute(on);+ }++ /** With its controls it takes keys: a stop in the page's tab order (unless the page set its+ * own `tabindex`); without them, it is none. */+ #tab(): void {+ if (this.hasAttribute("controls")) {+ if (this.hasAttribute("tabindex")) return;+ this.tabIndex = 0;+ this.#tabbed = true;+ } else if (this.#tabbed) {+ this.removeAttribute("tabindex");+ this.#tabbed = false;+ }+ }+#wait(): void {if (!this.#player && !this.#failed) this.#said.textContent = begin().status;}@@ -342,10 +372,11 @@ export class ManimgxPlayer extends HTMLElement {on(canvas, "pointermove", (e) => p.pointer(...at(e)));on(canvas, "pointerdown", (e) => {if (pressed !== null || e.button !== 0 || !e.isPrimary) return false;+ if (!p.press(...at(e), e.pointerType === "touch")) return false; // no controls: the page'spressed = e.pointerId;this.focus({ preventScroll: true });canvas.setPointerCapture(e.pointerId);- return p.press(...at(e), e.pointerType === "touch");+ return true;});const end = (e: PointerEvent, ended: () => boolean | void): boolean | void => {if (e.pointerId !== pressed) return false;diff --git a/browser/tests/browser.test.ts b/browser/tests/browser.test.tsindex dad92c0a..fd8e3adc 100644--- a/browser/tests/browser.test.ts+++ b/browser/tests/browser.test.ts@@ -41,6 +41,7 @@ async function page(cursor = "default";feeds: number[][] = [];fullscreenChanges = 0;+ switches = { controls: true, looping: false, mute: false };wakeAfter = -1;frees = 0;constructor(_canvas: unknown, time: number, playing: boolean) {@@ -68,6 +69,15 @@ async function page(fullscreen() {this.fullscreenChanges++;}+ controls(on: boolean) {+ this.switches.controls = on;+ }+ looping(on: boolean) {+ this.switches.looping = on;+ }+ mute(on: boolean) {+ this.switches.mute = on;+ }}const waiting = { textContent: "", remove() {} };const canvas = Object.assign(new EventTarget(), {@@ -79,7 +89,6 @@ async function page(class Element extends EventTarget {isConnected = true;- tabIndex = -1;style = { setProperty() {} };attributes = new Map<string, string>();shadowRoot = {@@ -101,13 +110,23 @@ async function page(}setAttribute(name: string, value: string) {this.attributes.set(name, value);- this.attributeChangedCallback();+ this.#changed(name);}removeAttribute(name: string) {this.attributes.delete(name);- this.attributeChangedCallback();+ this.#changed(name);+ }+ get tabIndex() {+ return Number(this.getAttribute("tabindex") ?? -1);+ }+ set tabIndex(value: number) {+ this.setAttribute("tabindex", String(value));}- attributeChangedCallback() {}+ #changed(name: string) {+ const { observedAttributes } = this.constructor as { observedAttributes?: string[] };+ if (observedAttributes?.includes(name)) this.attributeChangedCallback(name);+ }+ attributeChangedCallback(_name: string) {}}class Director {@@ -272,7 +291,6 @@ describe("published browser module", () => {{ film: 1, run: { source: "class Demo(Scene):\n pass\n", scene: null } },]);expect(state.canvas).toMatchObject({ width: 640, height: 360 });- expect(player.tabIndex).toBe(0);await director.onmessage!({ data: { status: "Installing ManimGX…" } });expect(state.waiting.textContent).toBe("Installing ManimGX…");player.source = "class Changed(Scene): pass";@@ -354,6 +372,34 @@ describe("published browser module", () => {expect(state.waiting.textContent).toBe("decode failed");});+ test("takes a video's controls, loop and muted, and is a tab stop only with its controls", async () => {+ const state = await page();+ const player = new state.api.ManimgxPlayer();+ player.setAttribute("loop", "");+ player.connectedCallback();+ state.flush();+ expect(player.hasAttribute("tabindex")).toBe(false);+ await state.workers[0]!.onmessage!({+ data: { engine: { js: "", wasm: new Uint8Array(), fonts: [] } },+ });+ await settle();+ const native = state.natives[0]!;+ expect(native.switches).toEqual({ controls: false, looping: true, mute: false });+ player.setAttribute("controls", "");+ player.setAttribute("muted", "");+ player.removeAttribute("loop");+ expect(native.switches).toEqual({ controls: true, looping: false, mute: true });+ expect(player.tabIndex).toBe(0);+ player.removeAttribute("controls");+ expect(native.switches.controls).toBe(false);+ expect(player.hasAttribute("tabindex")).toBe(false);+ // the page's own tabindex stays the page's+ player.tabIndex = -1;+ player.setAttribute("controls", "");+ player.removeAttribute("controls");+ expect(player.tabIndex).toBe(-1);+ });+test("disconnecting during boot does not create an orphan native player", async () => {const state = await page();const player = new state.api.ManimgxPlayer();diff --git a/docs/content/changelog.md b/docs/content/changelog.mdindex c3d7bcfd..6ea9cc77 100644--- a/docs/content/changelog.md+++ b/docs/content/changelog.md@@ -26,6 +26,7 @@ The notable changes to ManimGX, release by release. The format follows- Add Manim CE's `partial_bezier_points`, `subdivide_bezier`, `bezier_remap`, `integer_interpolate`, `is_closed` and `get_smooth_cubic_bezier_handle_points` to the package.- Add `remove_fixed_in_frame_mobjects` to `ThreeDScene` and `Camera`, Manim CE's undo of `add_fixed_in_frame_mobjects`: the camera moves the mobjects again.- Add `get_height()`, deprecated in favor of `height`, as `get_width()` is in favor of `width`: Manim CE scenes call both.+- Give `<manimgx-player>` a `<video>`'s `controls`, `loop` and `muted`, so `<manimgx-player autoplay loop muted>` plays a scene as a GIF does, with nothing over it ([#31](https://github.com/academa-labs/manimgx/issues/31)). A page's own buttons can play it with sound: `play()` and taking away `muted` let the page sound, as a click on the controls does.### Changed@@ -45,6 +46,7 @@ The notable changes to ManimGX, release by release. The format follows- Name the settings' module `manimgx.settings`. `manimgx.config` is the settings themselves, as `m.config` is: after `import manimgx.config`, `manimgx.config.Config` failed.- Name the value that says how a transform's points travel `Trajectory`, where it was `Path`, which `from manimgx import *` put in place of `pathlib.Path` ([#35](https://github.com/academa-labs/manimgx/issues/35)).- Name more of Manim CE's differences on the migration page: a fraction's glyph order, `line_spacing`, `rate_functions`, `pixel_array`, held frames and `ffmpeg -ss`, and a scene's own `say` ([#35](https://github.com/academa-labs/manimgx/issues/35)).+- Show `<manimgx-player>`'s controls only with `controls`, as a `<video>` does: without them, the player takes no click, key or wheel, and is no stop in the page's tab order ([#31](https://github.com/academa-labs/manimgx/issues/31)).### Fixeddiff --git a/docs/content/user-guide/rendering.md b/docs/content/user-guide/rendering.mdindex 68257baf..7d4a46b7 100644--- a/docs/content/user-guide/rendering.md+++ b/docs/content/user-guide/rendering.md@@ -174,7 +174,7 @@ through your bundler, and put a scene in a `<manimgx-player>`:import "manimgx";</script>-<manimgx-player autoplay>+<manimgx-player controls autoplay><script type="text/python">import manimgx as m@@ -187,7 +187,9 @@ through your bundler, and put a scene in a `<manimgx-player>`:</manimgx-player>```-The player has the keys of the preview window. The first video on a page downloads+With `controls`, the player has the controls and keys of the preview window. It takes a+`<video>`'s `autoplay`, `loop` and `muted` too: `<manimgx-player autoplay loop muted>` plays+like a GIF, with nothing over it. The first video on a page downloadsPython ([Pyodide](https://pyodide.org)) and ManimGX, about 26 MB; the browser keeps themfor later. It needs WebGPU: Chrome and Edge 113 or later, or Safari 26. Two things don'twork in the browser yet: shapes made from other shapes, such as `Union`, and Chinese,diff --git a/rust/engine/src/player.rs b/rust/engine/src/player.rsindex 6164f011..5ba85210 100644--- a/rust/engine/src/player.rs+++ b/rust/engine/src/player.rs@@ -66,12 +66,16 @@ impl Clock {self.since = None;}- /// Keep it within the film: at its end, it stops there; past its last frame made (or a time- /// beyond it the clock was set to) while it is being made, it waits there, and runs on once- /// more is made.- fn bound(&mut self, made: f64, ended: bool) {+ /// Keep it within the film: at its end, it stops there, or, `looping`, plays it again from+ /// its start (true: it jumped); past its last frame made (or a time beyond it the clock was+ /// set to) while it is being made, it waits there, and runs on once more is made.+ fn bound(&mut self, made: f64, ended: bool, looping: bool) -> bool {if !self.playing() || self.now() < made {- return;+ return false;+ }+ if ended && looping && made > 0.0 {+ self.set(0.0);+ return true;}if ended {self.set(made);@@ -80,6 +84,7 @@ impl Clock {self.time = self.time.max(made);self.since = Some(Instant::now());}+ false}}@@ -437,6 +442,8 @@ pub(crate) struct Player {captions: bool,fullscreen: bool,mac: bool,+ controls: bool, // it shows its controls and takes its viewer's input+ looping: bool, // at its end, it plays the film againhidden: bool, // it takes no picture: drawn again once it showscounting: bool, // the frame drawn last has its see-through count coming backdue: bool, // to be drawn@@ -467,6 +474,8 @@ impl Player {captions: false,fullscreen: false,mac: options.mac,+ controls: true,+ looping: false,hidden: false,counting: false,due: true,@@ -570,6 +579,7 @@ impl Player {}pub(crate) fn play(&mut self) {+ self.sound.resume(); // played in a gesture (a page's own button's too, as a <video> is): it may soundif self.take().is_some_and(|t| t.2) && self.time() >= self.made() - 1e-6 {self.seek(0.0); // from the start again}@@ -666,6 +676,9 @@ impl Player {/// A key pressed: `key` is its value as the web names it (`" "`, `"k"`, `"ArrowLeft"`,/// `"Escape"`…). Whether the player took it.pub(crate) fn key(&mut self, key: &str, m: Modifiers) -> bool {+ if !self.controls {+ return false;+ }self.sound.resume(); // a key pressed: the page may sound nowlet Some(act) = keyed(key, m, self.clock.playing(), self.help || self.fullscreen, self.mac) else { return false };self.act(act);@@ -693,6 +706,9 @@ impl Player {/// The pointer moved to (x, y): pixels from the screen's top left.pub(crate) fn pointer(&mut self, x: f64, y: f64) {+ if !self.controls {+ return;+ }self.cursor = (x, y);self.active = Some(Instant::now());self.due = true;@@ -706,6 +722,9 @@ impl Player {/// The pointer pressed (a finger, if `touch`) at (x, y), pixels from the screen's top left./// Whether the player took it.pub(crate) fn press(&mut self, x: f64, y: f64, touch: bool) -> bool {+ if !self.controls {+ return false;+ }self.sound.resume();// what showed before it (a finger comes down where nothing pointed)let shown = self.shows_controls();@@ -789,6 +808,9 @@ impl Player {/// sideways it moves the playhead, a second per 100 points; else the player lets it go by/// (the page scrolls). Whether it took it.pub(crate) fn wheel(&mut self, dx: f64, dy: f64) -> bool {+ if !self.controls {+ return false;+ }if matches!(self.pointer, Pointer::Over(Some(Control::Mute))) && dy.abs() > dx.abs() {self.wheeled -= dy;let steps = (self.wheeled / 50.0).trunc();@@ -840,6 +862,34 @@ impl Player {self.due = true;}+ /// It shows its controls and takes its viewer's keys, pointer and wheel, or not: a picture+ /// that plays (its status and errors still show), its page handling every event.+ #[cfg(feature = "web")]+ pub(crate) fn controls(&mut self, on: bool) {+ if !on {+ self.cancel(); // a drag ends where it is+ self.help = false;+ }+ self.controls = on;+ self.due = true;+ }++ /// At the film's end, it plays it again from its start, or stops there.+ #[cfg(feature = "web")]+ pub(crate) fn looping(&mut self, on: bool) {+ self.looping = on;+ }++ /// Its sound muted, or not. Unmuted (by a page, in its viewer's gesture), it may sound.+ #[cfg(feature = "web")]+ pub(crate) fn mute(&mut self, on: bool) {+ if self.sound.muted && !on {+ self.sound.resume();+ }+ self.sound.muted = on;+ self.due = true;+ }+/// What it asks of its screen, since it was last asked.pub(crate) fn asks(&mut self) -> Vec<Ask> {std::mem::take(&mut self.asks)@@ -850,7 +900,7 @@ impl Player {fn shows_controls(&self) -> bool {let lately = self.active.is_some_and(|at| at.elapsed() < IDLE);let on = matches!(self.pointer, Pointer::Over(Some(_)) | Pointer::Dragging { .. } | Pointer::Down { on: Some(_), .. });- self.takes.shown.is_some() && (!self.clock.playing() || self.waits() || lately || on || self.help)+ self.controls && self.takes.shown.is_some() && (!self.clock.playing() || self.waits() || lately || on || self.help)}/// What the face shows now, at `time`.@@ -924,7 +974,9 @@ impl Player {pub(crate) fn draw(&mut self, presenting: impl FnOnce()) -> Result<(), String> {self.due = false;let (made, ended, playing) = (self.made(), self.take().is_some_and(|t| t.2), self.clock.playing());- self.clock.bound(made, ended);+ if self.clock.bound(made, ended, self.looping) {+ self.sound.jumped();+ }let time = self.time();let shown = self.takes.show(time);self.notes.retain(|&take, _| take >= shown); // a take replaced goes, its notes with it@@ -1035,4 +1087,24 @@ mod tests {}assert_eq!(notes.chapters(3.0), [(0.0, 1.0, "Intro".into()), (1.0, 2.0, "Middle".into()), (2.0, 3.0, "End".into())]);}++ #[test]+ fn at_the_films_end_the_clock_stops_or_plays_it_again() {+ // run from 0 for 5 seconds: past a film of 3+ let ran = Clock { time: 0.0, since: Some(Instant::now() - Duration::from_secs(5)), rate: 1.0 };+ let mut clock = ran;+ assert!(!clock.bound(3.0, true, false));+ assert!(!clock.playing() && (clock.time - 3.0).abs() < 0.1);+ let mut clock = ran;+ assert!(clock.bound(3.0, true, true));+ assert!(clock.playing() && clock.now() < 1.0);+ // a film still being made waits at its last frame, looping or not+ let mut clock = ran;+ assert!(!clock.bound(3.0, false, true));+ assert!(clock.playing() && clock.now() >= 3.0 && clock.now() < 4.0);+ // with no frame yet, there is nothing to play again+ let mut clock = ran;+ assert!(!clock.bound(0.0, true, true));+ assert!(!clock.playing() && clock.time < 0.1);+ }}diff --git a/rust/engine/src/web.rs b/rust/engine/src/web.rsindex 0ad6cb42..3959c7c4 100644--- a/rust/engine/src/web.rs+++ b/rust/engine/src/web.rs@@ -121,6 +121,22 @@ impl Player {self.player.fullscreen(on);}+ /// Its controls, as `<video controls>`: it shows them and takes its viewer's keys, pointer+ /// and wheel, or it is a picture that plays, the page handling every event.+ pub fn controls(&mut self, on: bool) {+ self.player.controls(on);+ }++ /// As `<video loop>`: at the film's end, it plays it again from its start.+ pub fn looping(&mut self, on: bool) {+ self.player.looping(on);+ }++ /// As `<video muted>`: its sound muted, or not.+ pub fn mute(&mut self, on: bool) {+ self.player.mute(on);+ }+/// When to draw it next: 0, at the next animation frame; milliseconds from now; −1, once/// something happens.pub fn wake(&mut self) -> Result<f64, JsError> {@@ -151,11 +167,12 @@ impl Player {.collect()}- /// The cursor over it, as CSS names it.+ /// The cursor over it, as CSS names it; empty where it has none of its own (the page's shows:+ /// an arrow, unless the page says otherwise).#[wasm_bindgen(getter)]pub fn cursor(&self) -> String {match self.player.cursor() {- Cursor::Arrow => "default",+ Cursor::Arrow => "",Cursor::Hand => "pointer",Cursor::Hidden => "none",}