Dataset Viewer
Auto-converted to Parquet
file_path
stringlengths
19
57
content
stringlengths
0
77.2k
manim_3b1b/README.md
<p align="center"> <a href="https://github.com/3b1b/manim"> <img src="https://raw.githubusercontent.com/3b1b/manim/master/logo/cropped.png"> </a> </p> [![pypi version](https://img.shields.io/pypi/v/manimgl?logo=pypi)](https://pypi.org/project/manimgl/) [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](http://choosealicense.com/licenses/mit/) [![Manim Subreddit](https://img.shields.io/reddit/subreddit-subscribers/manim.svg?color=ff4301&label=reddit&logo=reddit)](https://www.reddit.com/r/manim/) [![Manim Discord](https://img.shields.io/discord/581738731934056449.svg?label=discord&logo=discord)](https://discord.com/invite/bYCyhM9Kz2) [![docs](https://github.com/3b1b/manim/workflows/docs/badge.svg)](https://3b1b.github.io/manim/) Manim is an engine for precise programmatic animations, designed for creating explanatory math videos. Note, there are two versions of manim. This repository began as a personal project by the author of [3Blue1Brown](https://www.3blue1brown.com/) for the purpose of animating those videos, with video-specific code available [here](https://github.com/3b1b/videos). In 2020 a group of developers forked it into what is now the [community edition](https://github.com/ManimCommunity/manim/), with a goal of being more stable, better tested, quicker to respond to community contributions, and all around friendlier to get started with. See [this page](https://docs.manim.community/en/stable/faq/installation.html#different-versions) for more details. ## Installation > **WARNING:** These instructions are for ManimGL _only_. Trying to use these instructions to install [ManimCommunity/manim](https://github.com/ManimCommunity/manim) or instructions there to install this version will cause problems. You should first decide which version you wish to install, then only follow the instructions for your desired version. > > **Note**: To install manim directly through pip, please pay attention to the name of the installed package. This repository is ManimGL of 3b1b. The package name is `manimgl` instead of `manim` or `manimlib`. Please use `pip install manimgl` to install the version in this repository. Manim runs on Python 3.7 or higher. System requirements are [FFmpeg](https://ffmpeg.org/), [OpenGL](https://www.opengl.org/) and [LaTeX](https://www.latex-project.org) (optional, if you want to use LaTeX). For Linux, [Pango](https://pango.gnome.org) along with its development headers are required. See instruction [here](https://github.com/ManimCommunity/ManimPango#building). ### Directly ```sh # Install manimgl pip install manimgl # Try it out manimgl ``` For more options, take a look at the [Using manim](#using-manim) sections further below. If you want to hack on manimlib itself, clone this repository and in that directory execute: ```sh # Install manimgl pip install -e . # Try it out manimgl example_scenes.py OpeningManimExample # or manim-render example_scenes.py OpeningManimExample ``` ### Directly (Windows) 1. [Install FFmpeg](https://www.wikihow.com/Install-FFmpeg-on-Windows). 2. Install a LaTeX distribution. [MiKTeX](https://miktex.org/download) is recommended. 3. Install the remaining Python packages. ```sh git clone https://github.com/3b1b/manim.git cd manim pip install -e . manimgl example_scenes.py OpeningManimExample ``` ### Mac OSX 1. Install FFmpeg, LaTeX in terminal using homebrew. ```sh brew install ffmpeg mactex ``` 2. Install latest version of manim using these command. ```sh git clone https://github.com/3b1b/manim.git cd manim pip install -e . manimgl example_scenes.py OpeningManimExample ``` ## Anaconda Install 1. Install LaTeX as above. 2. Create a conda environment using `conda create -n manim python=3.8`. 3. Activate the environment using `conda activate manim`. 4. Install manimgl using `pip install -e .`. ## Using manim Try running the following: ```sh manimgl example_scenes.py OpeningManimExample ``` This should pop up a window playing a simple scene. Some useful flags include: * `-w` to write the scene to a file * `-o` to write the scene to a file and open the result * `-s` to skip to the end and just show the final frame. * `-so` will save the final frame to an image and show it * `-n <number>` to skip ahead to the `n`'th animation of a scene. * `-f` to make the playback window fullscreen Take a look at custom_config.yml for further configuration. To add your customization, you can either edit this file, or add another file by the same name "custom_config.yml" to whatever directory you are running manim from. For example [this is the one](https://github.com/3b1b/videos/blob/master/custom_config.yml) for 3blue1brown videos. There you can specify where videos should be output to, where manim should look for image files and sounds you want to read in, and other defaults regarding style and video quality. Look through the [example scenes](https://3b1b.github.io/manim/getting_started/example_scenes.html) to get a sense of how it is used, and feel free to look through the code behind [3blue1brown videos](https://github.com/3b1b/videos) for a much larger set of example. Note, however, that developments are often made to the library without considering backwards compatibility with those old videos. To run an old project with a guarantee that it will work, you will have to go back to the commit which completed that project. ### Documentation Documentation is in progress at [3b1b.github.io/manim](https://3b1b.github.io/manim/). And there is also a Chinese version maintained by [**@manim-kindergarten**](https://manim.org.cn): [docs.manim.org.cn](https://docs.manim.org.cn/) (in Chinese). [manim-kindergarten](https://github.com/manim-kindergarten/) wrote and collected some useful extra classes and some codes of videos in [manim_sandbox repo](https://github.com/manim-kindergarten/manim_sandbox). ## Contributing Is always welcome. As mentioned above, the [community edition](https://github.com/ManimCommunity/manim) has the most active ecosystem for contributions, with testing and continuous integration, but pull requests are welcome here too. Please explain the motivation for a given change and examples of its effect. ## License This project falls under the MIT license.
manim_3b1b/LICENSE.md
MIT License Copyright (c) 2020-2023 3Blue1Brown LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
manim_3b1b/setup.py
import setuptools setuptools.setup()
manim_3b1b/example_scenes.py
from manimlib import * import numpy as np # To watch one of these scenes, run the following: # manimgl example_scenes.py OpeningManimExample # Use -s to skip to the end and just save the final frame # Use -w to write the animation to a file # Use -o to write it to a file and open it once done # Use -n <number> to skip ahead to the n'th animation of a scene. class OpeningManimExample(Scene): def construct(self): intro_words = Text(""" The original motivation for manim was to better illustrate mathematical functions as transformations. """) intro_words.to_edge(UP) self.play(Write(intro_words)) self.wait(2) # Linear transform grid = NumberPlane((-10, 10), (-5, 5)) matrix = [[1, 1], [0, 1]] linear_transform_words = VGroup( Text("This is what the matrix"), IntegerMatrix(matrix, include_background_rectangle=True), Text("looks like") ) linear_transform_words.arrange(RIGHT) linear_transform_words.to_edge(UP) linear_transform_words.set_backstroke(width=5) self.play( ShowCreation(grid), FadeTransform(intro_words, linear_transform_words) ) self.wait() self.play(grid.animate.apply_matrix(matrix), run_time=3) self.wait() # Complex map c_grid = ComplexPlane() moving_c_grid = c_grid.copy() moving_c_grid.prepare_for_nonlinear_transform() c_grid.set_stroke(BLUE_E, 1) c_grid.add_coordinate_labels(font_size=24) complex_map_words = TexText(""" Or thinking of the plane as $\\mathds{C}$,\\\\ this is the map $z \\rightarrow z^2$ """) complex_map_words.to_corner(UR) complex_map_words.set_backstroke(width=5) self.play( FadeOut(grid), Write(c_grid, run_time=3), FadeIn(moving_c_grid), FadeTransform(linear_transform_words, complex_map_words), ) self.wait() self.play( moving_c_grid.animate.apply_complex_function(lambda z: z**2), run_time=6, ) self.wait(2) class AnimatingMethods(Scene): def construct(self): grid = Tex(R"\pi").get_grid(10, 10, height=4) self.add(grid) # You can animate the application of mobject methods with the # ".animate" syntax: self.play(grid.animate.shift(LEFT)) # Both of those will interpolate between the mobject's initial # state and whatever happens when you apply that method. # For this example, calling grid.shift(LEFT) would shift the # grid one unit to the left, but both of the previous calls to # "self.play" animate that motion. # The same applies for any method, including those setting colors. self.play(grid.animate.set_color(YELLOW)) self.wait() self.play(grid.animate.set_submobject_colors_by_gradient(BLUE, GREEN)) self.wait() self.play(grid.animate.set_height(TAU - MED_SMALL_BUFF)) self.wait() # The method Mobject.apply_complex_function lets you apply arbitrary # complex functions, treating the points defining the mobject as # complex numbers. self.play(grid.animate.apply_complex_function(np.exp), run_time=5) self.wait() # Even more generally, you could apply Mobject.apply_function, # which takes in functions form R^3 to R^3 self.play( grid.animate.apply_function( lambda p: [ p[0] + 0.5 * math.sin(p[1]), p[1] + 0.5 * math.sin(p[0]), p[2] ] ), run_time=5, ) self.wait() class TextExample(Scene): def construct(self): # To run this scene properly, you should have "Consolas" font in your computer # for full usage, you can see https://github.com/3b1b/manim/pull/680 text = Text("Here is a text", font="Consolas", font_size=90) difference = Text( """ The most important difference between Text and TexText is that\n you can change the font more easily, but can't use the LaTeX grammar """, font="Arial", font_size=24, # t2c is a dict that you can choose color for different text t2c={"Text": BLUE, "TexText": BLUE, "LaTeX": ORANGE} ) VGroup(text, difference).arrange(DOWN, buff=1) self.play(Write(text)) self.play(FadeIn(difference, UP)) self.wait(3) fonts = Text( "And you can also set the font according to different words", font="Arial", t2f={"font": "Consolas", "words": "Consolas"}, t2c={"font": BLUE, "words": GREEN} ) fonts.set_width(FRAME_WIDTH - 1) slant = Text( "And the same as slant and weight", font="Consolas", t2s={"slant": ITALIC}, t2w={"weight": BOLD}, t2c={"slant": ORANGE, "weight": RED} ) VGroup(fonts, slant).arrange(DOWN, buff=0.8) self.play(FadeOut(text), FadeOut(difference, shift=DOWN)) self.play(Write(fonts)) self.wait() self.play(Write(slant)) self.wait() class TexTransformExample(Scene): def construct(self): # Tex to color map t2c = { "A": BLUE, "B": TEAL, "C": GREEN, } # Configuration to pass along to each Tex mobject kw = dict(font_size=72, t2c=t2c) lines = VGroup( Tex("A^2 + B^2 = C^2", **kw), Tex("A^2 = C^2 - B^2", **kw), Tex("A^2 = (C + B)(C - B)", **kw), Tex(R"A = \sqrt{(C + B)(C - B)}", **kw), ) lines.arrange(DOWN, buff=LARGE_BUFF) self.add(lines[0]) # The animation TransformMatchingStrings will line up parts # of the source and target which have matching substring strings. # Here, giving it a little path_arc makes each part rotate into # their final positions, which feels appropriate for the idea of # rearranging an equation self.play( TransformMatchingStrings( lines[0].copy(), lines[1], # matched_keys specifies which substring should # line up. If it's not specified, the animation # will align the longest matching substrings. # In this case, the substring "^2 = C^2" would # trip it up matched_keys=["A^2", "B^2", "C^2"], # When you want a substring from the source # to go to a non-equal substring from the target, # use the key map. key_map={"+": "-"}, path_arc=90 * DEGREES, ), ) self.wait() self.play(TransformMatchingStrings( lines[1].copy(), lines[2], matched_keys=["A^2"] )) self.wait() self.play( TransformMatchingStrings( lines[2].copy(), lines[3], key_map={"2": R"\sqrt"}, path_arc=-30 * DEGREES, ), ) self.wait(2) self.play(LaggedStartMap(FadeOut, lines, shift=2 * RIGHT)) # TransformMatchingShapes will try to line up all pieces of a # source mobject with those of a target, regardless of the # what Mobject type they are. source = Text("the morse code", height=1) target = Text("here come dots", height=1) saved_source = source.copy() self.play(Write(source)) self.wait() kw = dict(run_time=3, path_arc=PI / 2) self.play(TransformMatchingShapes(source, target, **kw)) self.wait() self.play(TransformMatchingShapes(target, saved_source, **kw)) self.wait() class TexIndexing(Scene): def construct(self): # You can index into Tex mobject (or other StringMobjects) by substrings equation = Tex(R"e^{\pi i} = -1", font_size=144) self.add(equation) self.play(FlashAround(equation["e"])) self.wait() self.play(Indicate(equation[R"\pi"])) self.wait() self.play(TransformFromCopy( equation[R"e^{\pi i}"].copy().set_opacity(0.5), equation["-1"], path_arc=-PI / 2, run_time=3 )) self.play(FadeOut(equation)) # Or regular expressions equation = Tex("A^2 + B^2 = C^2", font_size=144) self.play(Write(equation)) for part in equation[re.compile(r"\w\^2")]: self.play(FlashAround(part)) self.wait() self.play(FadeOut(equation)) # Indexing by substrings like this may not work when # the order in which Latex draws symbols does not match # the order in which they show up in the string. # For example, here the infinity is drawn before the sigma # so we don't get the desired behavior. equation = Tex(R"\sum_{n = 1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}", font_size=72) self.play(FadeIn(equation)) self.play(equation[R"\infty"].animate.set_color(RED)) # Doesn't hit the infinity self.wait() self.play(FadeOut(equation)) # However you can always fix this by explicitly passing in # a string you might want to isolate later. Also, using # \over instead of \frac helps to avoid the issue for fractions equation = Tex( R"\sum_{n = 1}^\infty {1 \over n^2} = {\pi^2 \over 6}", # Explicitly mark "\infty" as a substring you might want to access isolate=[R"\infty"], font_size=72 ) self.play(FadeIn(equation)) self.play(equation[R"\infty"].animate.set_color(RED)) # Got it! self.wait() self.play(FadeOut(equation)) class UpdatersExample(Scene): def construct(self): square = Square() square.set_fill(BLUE_E, 1) # On all frames, the constructor Brace(square, UP) will # be called, and the mobject brace will set its data to match # that of the newly constructed object brace = always_redraw(Brace, square, UP) label = TexText("Width = 0.00") number = label.make_number_changable("0.00") # This ensures that the method deicmal.next_to(square) # is called on every frame always(label.next_to, brace, UP) # You could also write the following equivalent line # label.add_updater(lambda m: m.next_to(brace, UP)) # If the argument itself might change, you can use f_always, # for which the arguments following the initial Mobject method # should be functions returning arguments to that method. # The following line ensures thst decimal.set_value(square.get_y()) # is called every frame f_always(number.set_value, square.get_width) # You could also write the following equivalent line # number.add_updater(lambda m: m.set_value(square.get_width())) self.add(square, brace, label) # Notice that the brace and label track with the square self.play( square.animate.scale(2), rate_func=there_and_back, run_time=2, ) self.wait() self.play( square.animate.set_width(5, stretch=True), run_time=3, ) self.wait() self.play( square.animate.set_width(2), run_time=3 ) self.wait() # In general, you can alway call Mobject.add_updater, and pass in # a function that you want to be called on every frame. The function # should take in either one argument, the mobject, or two arguments, # the mobject and the amount of time since the last frame. now = self.time w0 = square.get_width() square.add_updater( lambda m: m.set_width(w0 * math.sin(self.time - now) + w0) ) self.wait(4 * PI) class CoordinateSystemExample(Scene): def construct(self): axes = Axes( # x-axis ranges from -1 to 10, with a default step size of 1 x_range=(-1, 10), # y-axis ranges from -2 to 2 with a step size of 0.5 y_range=(-2, 2, 0.5), # The axes will be stretched so as to match the specified # height and width height=6, width=10, # Axes is made of two NumberLine mobjects. You can specify # their configuration with axis_config axis_config=dict( stroke_color=GREY_A, stroke_width=2, numbers_to_exclude=[0], ), # Alternatively, you can specify configuration for just one # of them, like this. y_axis_config=dict( numbers_with_elongated_ticks=[-2, 2], ) ) # Keyword arguments of add_coordinate_labels can be used to # configure the DecimalNumber mobjects which it creates and # adds to the axes axes.add_coordinate_labels( font_size=20, num_decimal_places=1, ) self.add(axes) # Axes descends from the CoordinateSystem class, meaning # you can call call axes.coords_to_point, abbreviated to # axes.c2p, to associate a set of coordinates with a point, # like so: dot = Dot(color=RED) dot.move_to(axes.c2p(0, 0)) self.play(FadeIn(dot, scale=0.5)) self.play(dot.animate.move_to(axes.c2p(3, 2))) self.wait() self.play(dot.animate.move_to(axes.c2p(5, 0.5))) self.wait() # Similarly, you can call axes.point_to_coords, or axes.p2c # print(axes.p2c(dot.get_center())) # We can draw lines from the axes to better mark the coordinates # of a given point. # Here, the always_redraw command means that on each new frame # the lines will be redrawn h_line = always_redraw(lambda: axes.get_h_line(dot.get_left())) v_line = always_redraw(lambda: axes.get_v_line(dot.get_bottom())) self.play( ShowCreation(h_line), ShowCreation(v_line), ) self.play(dot.animate.move_to(axes.c2p(3, -2))) self.wait() self.play(dot.animate.move_to(axes.c2p(1, 1))) self.wait() # If we tie the dot to a particular set of coordinates, notice # that as we move the axes around it respects the coordinate # system defined by them. f_always(dot.move_to, lambda: axes.c2p(1, 1)) self.play( axes.animate.scale(0.75).to_corner(UL), run_time=2, ) self.wait() self.play(FadeOut(VGroup(axes, dot, h_line, v_line))) # Other coordinate systems you can play around with include # ThreeDAxes, NumberPlane, and ComplexPlane. class GraphExample(Scene): def construct(self): axes = Axes((-3, 10), (-1, 8), height=6) axes.add_coordinate_labels() self.play(Write(axes, lag_ratio=0.01, run_time=1)) # Axes.get_graph will return the graph of a function sin_graph = axes.get_graph( lambda x: 2 * math.sin(x), color=BLUE, ) # By default, it draws it so as to somewhat smoothly interpolate # between sampled points (x, f(x)). If the graph is meant to have # a corner, though, you can set use_smoothing to False relu_graph = axes.get_graph( lambda x: max(x, 0), use_smoothing=False, color=YELLOW, ) # For discontinuous functions, you can specify the point of # discontinuity so that it does not try to draw over the gap. step_graph = axes.get_graph( lambda x: 2.0 if x > 3 else 1.0, discontinuities=[3], color=GREEN, ) # Axes.get_graph_label takes in either a string or a mobject. # If it's a string, it treats it as a LaTeX expression. By default # it places the label next to the graph near the right side, and # has it match the color of the graph sin_label = axes.get_graph_label(sin_graph, "\\sin(x)") relu_label = axes.get_graph_label(relu_graph, Text("ReLU")) step_label = axes.get_graph_label(step_graph, Text("Step"), x=4) self.play( ShowCreation(sin_graph), FadeIn(sin_label, RIGHT), ) self.wait(2) self.play( ReplacementTransform(sin_graph, relu_graph), FadeTransform(sin_label, relu_label), ) self.wait() self.play( ReplacementTransform(relu_graph, step_graph), FadeTransform(relu_label, step_label), ) self.wait() parabola = axes.get_graph(lambda x: 0.25 * x**2) parabola.set_stroke(BLUE) self.play( FadeOut(step_graph), FadeOut(step_label), ShowCreation(parabola) ) self.wait() # You can use axes.input_to_graph_point, abbreviated # to axes.i2gp, to find a particular point on a graph dot = Dot(color=RED) dot.move_to(axes.i2gp(2, parabola)) self.play(FadeIn(dot, scale=0.5)) # A value tracker lets us animate a parameter, usually # with the intent of having other mobjects update based # on the parameter x_tracker = ValueTracker(2) f_always( dot.move_to, lambda: axes.i2gp(x_tracker.get_value(), parabola) ) self.play(x_tracker.animate.set_value(4), run_time=3) self.play(x_tracker.animate.set_value(-2), run_time=3) self.wait() class TexAndNumbersExample(Scene): def construct(self): axes = Axes((-3, 3), (-3, 3), unit_size=1) axes.to_edge(DOWN) axes.add_coordinate_labels(font_size=16) circle = Circle(radius=2) circle.set_stroke(YELLOW, 3) circle.move_to(axes.get_origin()) self.add(axes, circle) # When numbers show up in tex, they can be readily # replaced with DecimalMobjects so that methods like # get_value and set_value can be called on them, and # animations like ChangeDecimalToValue can be called # on them. tex = Tex("x^2 + y^2 = 4.00") tex.next_to(axes, UP, buff=0.5) value = tex.make_number_changable("4.00") # This will tie the right hand side of our equation to # the square of the radius of the circle value.add_updater(lambda v: v.set_value(circle.get_radius()**2)) self.add(tex) text = Text(""" You can manipulate numbers in Tex mobjects """, font_size=30) text.next_to(tex, RIGHT, buff=1.5) arrow = Arrow(text, tex) self.add(text, arrow) self.play( circle.animate.set_height(2.0), run_time=4, rate_func=there_and_back, ) # By default, tex.make_number_changable replaces the first occurance # of the number,but by passing replace_all=True it replaces all and # returns a group of the results exponents = tex.make_number_changable("2", replace_all=True) self.play( LaggedStartMap( FlashAround, exponents, lag_ratio=0.2, buff=0.1, color=RED ), exponents.animate.set_color(RED) ) def func(x, y): # Switch from manim coords to axes coords xa, ya = axes.point_to_coords(np.array([x, y, 0])) return xa**4 + ya**4 - 4 new_curve = ImplicitFunction(func) new_curve.match_style(circle) circle.rotate(angle_of_vector(new_curve.get_start())) # Align value.clear_updaters() self.play( *(ChangeDecimalToValue(exp, 4) for exp in exponents), ReplacementTransform(circle.copy(), new_curve), circle.animate.set_stroke(width=1, opacity=0.5), ) class SurfaceExample(ThreeDScene): def construct(self): surface_text = Text("For 3d scenes, try using surfaces") surface_text.fix_in_frame() surface_text.to_edge(UP) self.add(surface_text) self.wait(0.1) torus1 = Torus(r1=1, r2=1) torus2 = Torus(r1=3, r2=1) sphere = Sphere(radius=3, resolution=torus1.resolution) # You can texture a surface with up to two images, which will # be interpreted as the side towards the light, and away from # the light. These can be either urls, or paths to a local file # in whatever you've set as the image directory in # the custom_config.yml file # day_texture = "EarthTextureMap" # night_texture = "NightEarthTextureMap" day_texture = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4d/Whole_world_-_land_and_oceans.jpg/1280px-Whole_world_-_land_and_oceans.jpg" night_texture = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/ba/The_earth_at_night.jpg/1280px-The_earth_at_night.jpg" surfaces = [ TexturedSurface(surface, day_texture, night_texture) for surface in [sphere, torus1, torus2] ] for mob in surfaces: mob.shift(IN) mob.mesh = SurfaceMesh(mob) mob.mesh.set_stroke(BLUE, 1, opacity=0.5) surface = surfaces[0] self.play( FadeIn(surface), ShowCreation(surface.mesh, lag_ratio=0.01, run_time=3), ) for mob in surfaces: mob.add(mob.mesh) surface.save_state() self.play(Rotate(surface, PI / 2), run_time=2) for mob in surfaces[1:]: mob.rotate(PI / 2) self.play( Transform(surface, surfaces[1]), run_time=3 ) self.play( Transform(surface, surfaces[2]), # Move camera frame during the transition self.frame.animate.increment_phi(-10 * DEGREES), self.frame.animate.increment_theta(-20 * DEGREES), run_time=3 ) # Add ambient rotation self.frame.add_updater(lambda m, dt: m.increment_theta(-0.1 * dt)) # Play around with where the light is light_text = Text("You can move around the light source") light_text.move_to(surface_text) light_text.fix_in_frame() self.play(FadeTransform(surface_text, light_text)) light = self.camera.light_source self.add(light) light.save_state() self.play(light.animate.move_to(3 * IN), run_time=5) self.play(light.animate.shift(10 * OUT), run_time=5) drag_text = Text("Try moving the mouse while pressing d or f") drag_text.move_to(light_text) drag_text.fix_in_frame() self.play(FadeTransform(light_text, drag_text)) self.wait() class InteractiveDevelopment(Scene): def construct(self): circle = Circle() circle.set_fill(BLUE, opacity=0.5) circle.set_stroke(BLUE_E, width=4) square = Square() self.play(ShowCreation(square)) self.wait() # This opens an iPython terminal where you can keep writing # lines as if they were part of this construct method. # In particular, 'square', 'circle' and 'self' will all be # part of the local namespace in that terminal. self.embed() # Try copying and pasting some of the lines below into # the interactive shell self.play(ReplacementTransform(square, circle)) self.wait() self.play(circle.animate.stretch(4, 0)) self.play(Rotate(circle, 90 * DEGREES)) self.play(circle.animate.shift(2 * RIGHT).scale(0.25)) text = Text(""" In general, using the interactive shell is very helpful when developing new scenes """) self.play(Write(text)) # In the interactive shell, you can just type # play, add, remove, clear, wait, save_state and restore, # instead of self.play, self.add, self.remove, etc. # To interact with the window, type touch(). You can then # scroll in the window, or zoom by holding down 'z' while scrolling, # and change camera perspective by holding down 'd' while moving # the mouse. Press 'r' to reset to the standard camera position. # Press 'q' to stop interacting with the window and go back to # typing new commands into the shell. # In principle you can customize a scene to be responsive to # mouse and keyboard interactions always(circle.move_to, self.mouse_point) class ControlsExample(Scene): drag_to_pan = False def setup(self): self.textbox = Textbox() self.checkbox = Checkbox() self.color_picker = ColorSliders() self.panel = ControlPanel( Text("Text", font_size=24), self.textbox, Line(), Text("Show/Hide Text", font_size=24), self.checkbox, Line(), Text("Color of Text", font_size=24), self.color_picker ) self.add(self.panel) def construct(self): text = Text("text", font_size=96) def text_updater(old_text): assert(isinstance(old_text, Text)) new_text = Text(self.textbox.get_value(), font_size=old_text.font_size) # new_text.align_data_and_family(old_text) new_text.move_to(old_text) if self.checkbox.get_value(): new_text.set_fill( color=self.color_picker.get_picked_color(), opacity=self.color_picker.get_picked_opacity() ) else: new_text.set_opacity(0) old_text.become(new_text) text.add_updater(text_updater) self.add(MotionMobject(text)) self.textbox.set_value("Manim") # self.wait(60) # self.embed() # See https://github.com/3b1b/videos for many, many more
manim_3b1b/manimlib/shader_wrapper.py
from __future__ import annotations import copy import os import re import OpenGL.GL as gl import moderngl import numpy as np from manimlib.utils.iterables import resize_array from manimlib.utils.shaders import get_shader_code_from_file from manimlib.utils.shaders import get_shader_program from manimlib.utils.shaders import image_path_to_texture from manimlib.utils.shaders import get_texture_id from manimlib.utils.shaders import get_fill_canvas from manimlib.utils.shaders import release_texture from manimlib.utils.shaders import set_program_uniform from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import List, Optional, Dict from manimlib.typing import UniformDict # Mobjects that should be rendered with # the same shader will be organized and # clumped together based on keeping track # of a dict holding all the relevant information # to that shader class ShaderWrapper(object): def __init__( self, ctx: moderngl.context.Context, vert_data: np.ndarray, vert_indices: Optional[np.ndarray] = None, shader_folder: Optional[str] = None, mobject_uniforms: Optional[UniformDict] = None, # A dictionary mapping names of uniform variables texture_paths: Optional[dict[str, str]] = None, # A dictionary mapping names to filepaths for textures. depth_test: bool = False, render_primitive: int = moderngl.TRIANGLE_STRIP, ): self.ctx = ctx self.vert_data = vert_data self.vert_indices = (vert_indices or np.zeros(0)).astype(int) self.vert_attributes = vert_data.dtype.names self.shader_folder = shader_folder self.depth_test = depth_test self.render_primitive = render_primitive self.program_uniform_mirror: UniformDict = dict() self.bind_to_mobject_uniforms(mobject_uniforms or dict()) self.init_program_code() self.init_program() self.texture_names_to_ids = dict() if texture_paths is not None: self.init_textures(texture_paths) self.init_vao() self.refresh_id() def init_program_code(self) -> None: def get_code(name: str) -> str | None: return get_shader_code_from_file( os.path.join(self.shader_folder, f"{name}.glsl") ) self.program_code: dict[str, str | None] = { "vertex_shader": get_code("vert"), "geometry_shader": get_code("geom"), "fragment_shader": get_code("frag"), } def init_program(self): if not self.shader_folder: self.program = None self.vert_format = None return self.program = get_shader_program(self.ctx, **self.program_code) self.vert_format = moderngl.detect_format(self.program, self.vert_attributes) def init_textures(self, texture_paths: dict[str, str]): self.texture_names_to_ids = { name: get_texture_id(image_path_to_texture(path, self.ctx)) for name, path in texture_paths.items() } def init_vao(self): self.vbo = None self.ibo = None self.vao = None def bind_to_mobject_uniforms(self, mobject_uniforms: UniformDict): self.mobject_uniforms = mobject_uniforms def __eq__(self, shader_wrapper: ShaderWrapper): return all(( np.all(self.vert_data == shader_wrapper.vert_data), np.all(self.vert_indices == shader_wrapper.vert_indices), self.shader_folder == shader_wrapper.shader_folder, all( self.mobject_uniforms[key] == shader_wrapper.mobject_uniforms[key] for key in self.mobject_uniforms ), self.depth_test == shader_wrapper.depth_test, self.render_primitive == shader_wrapper.render_primitive, )) def copy(self): result = copy.copy(self) result.ctx = self.ctx result.vert_data = self.vert_data.copy() result.vert_indices = self.vert_indices.copy() result.init_vao() return result def is_valid(self) -> bool: return all([ self.vert_data is not None, self.program_code["vertex_shader"] is not None, self.program_code["fragment_shader"] is not None, ]) def get_id(self) -> str: return self.id def create_id(self) -> str: # A unique id for a shader program_id = hash("".join( self.program_code[f"{name}_shader"] or "" for name in ("vertex", "geometry", "fragment") )) return "|".join(map(str, [ program_id, self.mobject_uniforms, self.depth_test, self.render_primitive, self.texture_names_to_ids, ])) def refresh_id(self) -> None: self.id = self.create_id() def replace_code(self, old: str, new: str) -> None: code_map = self.program_code for name in code_map: if code_map[name] is None: continue code_map[name] = re.sub(old, new, code_map[name]) self.init_program() self.refresh_id() # Changing context def use_clip_plane(self): if "clip_plane" not in self.mobject_uniforms: return False return any(self.mobject_uniforms["clip_plane"]) def set_ctx_depth_test(self, enable: bool = True) -> None: if enable: self.ctx.enable(moderngl.DEPTH_TEST) else: self.ctx.disable(moderngl.DEPTH_TEST) def set_ctx_clip_plane(self, enable: bool = True) -> None: if enable: gl.glEnable(gl.GL_CLIP_DISTANCE0) # Adding data def combine_with(self, *shader_wrappers: ShaderWrapper) -> ShaderWrapper: if len(shader_wrappers) > 0: data_list = [self.vert_data, *(sw.vert_data for sw in shader_wrappers)] indices_list = [self.vert_indices, *(sw.vert_indices for sw in shader_wrappers)] self.read_in(data_list, indices_list) return self def read_in( self, data_list: List[np.ndarray], indices_list: List[np.ndarray] | None = None ) -> ShaderWrapper: # Assume all are of the same type total_len = sum(len(data) for data in data_list) self.vert_data = resize_array(self.vert_data, total_len) if total_len == 0: return self # Stack the data np.concatenate(data_list, out=self.vert_data) if indices_list is None: self.vert_indices = resize_array(self.vert_indices, 0) return self total_verts = sum(len(vi) for vi in indices_list) if total_verts == 0: return self self.vert_indices = resize_array(self.vert_indices, total_verts) # Stack vert_indices, but adding the appropriate offset # alogn the way n_points = 0 n_verts = 0 for data, indices in zip(data_list, indices_list): new_n_verts = n_verts + len(indices) self.vert_indices[n_verts:new_n_verts] = indices + n_points n_verts = new_n_verts n_points += len(data) return self # Related to data and rendering def pre_render(self): self.set_ctx_depth_test(self.depth_test) self.set_ctx_clip_plane(self.use_clip_plane()) def render(self): assert(self.vao is not None) self.vao.render() def update_program_uniforms(self, camera_uniforms: UniformDict): if self.program is None: return for uniforms in [self.mobject_uniforms, camera_uniforms, self.texture_names_to_ids]: for name, value in uniforms.items(): set_program_uniform(self.program, name, value) def get_vertex_buffer_object(self, refresh: bool = True): if refresh: self.vbo = self.ctx.buffer(self.vert_data) return self.vbo def get_index_buffer_object(self, refresh: bool = True): if refresh and len(self.vert_indices) > 0: self.ibo = self.ctx.buffer(self.vert_indices.astype(np.uint32)) return self.ibo def generate_vao(self, refresh: bool = True): self.release() # Data buffer vbo = self.get_vertex_buffer_object(refresh) ibo = self.get_index_buffer_object(refresh) # Vertex array object self.vao = self.ctx.vertex_array( program=self.program, content=[(vbo, self.vert_format, *self.vert_attributes)], index_buffer=ibo, mode=self.render_primitive, ) return self.vao def release(self): for obj in (self.vbo, self.ibo, self.vao): if obj is not None: obj.release() self.vbo = None self.ibo = None self.vao = None class FillShaderWrapper(ShaderWrapper): def __init__( self, ctx: moderngl.context.Context, *args, **kwargs ): super().__init__(ctx, *args, **kwargs) self.fill_canvas = get_fill_canvas(self.ctx) def render(self): winding = (len(self.vert_indices) == 0) self.program['winding'].value = winding if not winding: super().render() return original_fbo = self.ctx.fbo texture_fbo, texture_vao = self.fill_canvas texture_fbo.clear() texture_fbo.use() gl.glBlendFuncSeparate( # Ordinary blending for colors gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA, # The effect of blending with -a / (1 - a) # should be to cancel out gl.GL_ONE_MINUS_DST_ALPHA, gl.GL_ONE, ) super().render() original_fbo.use() gl.glBlendFunc(gl.GL_ONE, gl.GL_ONE_MINUS_SRC_ALPHA) texture_vao.render() gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
manim_3b1b/manimlib/__main__.py
#!/usr/bin/env python from manimlib import __version__ import manimlib.config import manimlib.extract_scene import manimlib.logger import manimlib.utils.init_config def main(): print(f"ManimGL \033[32mv{__version__}\033[0m") args = manimlib.config.parse_cli() if args.version and args.file is None: return if args.log_level: manimlib.logger.log.setLevel(args.log_level) if args.config: manimlib.utils.init_config.init_customization() else: config = manimlib.config.get_configuration(args) scenes = manimlib.extract_scene.main(config) for scene in scenes: scene.run() if __name__ == "__main__": main()
manim_3b1b/manimlib/default_config.yml
directories: # Set this to true if you want the path to video files # to match the directory structure of the path to the # sourcecode generating that video mirror_module_path: False # Where should manim output video and image files? output: "" # If you want to use images, manim will look to these folders to find them raster_images: "" vector_images: "" # If you want to use sounds, manim will look here to find it. sounds: "" # Manim often generates tex_files or other kinds of serialized data # to keep from having to generate the same thing too many times. By # default, these will be stored at tempfile.gettempdir(), e.g. this might # return whatever is at to the TMPDIR environment variable. If you want to # specify them elsewhere, temporary_storage: "" universal_import_line: "from manimlib import *" style: tex_template: "default" font: "Consolas" text_alignment: "LEFT" background_color: "#333333" # Set the position of preview window, you can use directions, e.g. UL/DR/OL/OO/... # also, you can also specify the position(pixel) of the upper left corner of # the window on the monitor, e.g. "960,540" window_position: UR window_monitor: 0 full_screen: False # If break_into_partial_movies is set to True, then many small # files will be written corresponding to each Scene.play and # Scene.wait call, and these files will then be combined # to form the full scene. Sometimes video-editing is made # easier when working with the broken up scene, which # effectively has cuts at all the places you might want. break_into_partial_movies: False camera_resolutions: low: "854x480" med: "1280x720" high: "1920x1080" 4k: "3840x2160" default_resolution: "high" fps: 30 embed_exception_mode: "Verbose" embed_error_sound: False
manim_3b1b/manimlib/__init__.py
import pkg_resources __version__ = pkg_resources.get_distribution("manimgl").version from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import * from manimlib.constants import * from manimlib.window import * from manimlib.animation.animation import * from manimlib.animation.composition import * from manimlib.animation.creation import * from manimlib.animation.fading import * from manimlib.animation.growing import * from manimlib.animation.indication import * from manimlib.animation.movement import * from manimlib.animation.numbers import * from manimlib.animation.rotation import * from manimlib.animation.specialized import * from manimlib.animation.transform import * from manimlib.animation.transform_matching_parts import * from manimlib.animation.update import * from manimlib.camera.camera import * from manimlib.mobject.boolean_ops import * from manimlib.mobject.changing import * from manimlib.mobject.coordinate_systems import * from manimlib.mobject.frame import * from manimlib.mobject.functions import * from manimlib.mobject.geometry import * from manimlib.mobject.interactive import * from manimlib.mobject.matrix import * from manimlib.mobject.mobject import * from manimlib.mobject.mobject_update_utils import * from manimlib.mobject.number_line import * from manimlib.mobject.numbers import * from manimlib.mobject.probability import * from manimlib.mobject.shape_matchers import * from manimlib.mobject.svg.brace import * from manimlib.mobject.svg.drawings import * from manimlib.mobject.svg.tex_mobject import * from manimlib.mobject.svg.string_mobject import * from manimlib.mobject.svg.svg_mobject import * from manimlib.mobject.svg.special_tex import * from manimlib.mobject.svg.tex_mobject import * from manimlib.mobject.svg.text_mobject import * from manimlib.mobject.three_dimensions import * from manimlib.mobject.types.dot_cloud import * from manimlib.mobject.types.image_mobject import * from manimlib.mobject.types.point_cloud_mobject import * from manimlib.mobject.types.surface import * from manimlib.mobject.types.vectorized_mobject import * from manimlib.mobject.value_tracker import * from manimlib.mobject.vector_field import * from manimlib.scene.interactive_scene import * from manimlib.scene.scene import * from manimlib.utils.bezier import * from manimlib.utils.color import * from manimlib.utils.dict_ops import * from manimlib.utils.customization import * from manimlib.utils.debug import * from manimlib.utils.directories import * from manimlib.utils.file_ops import * from manimlib.utils.images import * from manimlib.utils.iterables import * from manimlib.utils.paths import * from manimlib.utils.rate_functions import * from manimlib.utils.simple_functions import * from manimlib.utils.shaders import * from manimlib.utils.sounds import * from manimlib.utils.space_ops import * from manimlib.utils.tex import *
manim_3b1b/manimlib/constants.py
from __future__ import annotations import numpy as np from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import List from manimlib.typing import ManimColor, Vect3 # Sizes relevant to default camera frame ASPECT_RATIO: float = 16.0 / 9.0 FRAME_HEIGHT: float = 8.0 FRAME_WIDTH: float = FRAME_HEIGHT * ASPECT_RATIO FRAME_SHAPE: tuple[float, float] = (FRAME_WIDTH, FRAME_HEIGHT) FRAME_Y_RADIUS: float = FRAME_HEIGHT / 2 FRAME_X_RADIUS: float = FRAME_WIDTH / 2 DEFAULT_PIXEL_HEIGHT: int = 1080 DEFAULT_PIXEL_WIDTH: int = 1920 DEFAULT_FPS: int = 30 SMALL_BUFF: float = 0.1 MED_SMALL_BUFF: float = 0.25 MED_LARGE_BUFF: float = 0.5 LARGE_BUFF: float = 1 DEFAULT_MOBJECT_TO_EDGE_BUFFER: float = MED_LARGE_BUFF DEFAULT_MOBJECT_TO_MOBJECT_BUFFER: float = MED_SMALL_BUFF # In seconds DEFAULT_WAIT_TIME: float = 1.0 ORIGIN: Vect3 = np.array([0., 0., 0.]) UP: Vect3 = np.array([0., 1., 0.]) DOWN: Vect3 = np.array([0., -1., 0.]) RIGHT: Vect3 = np.array([1., 0., 0.]) LEFT: Vect3 = np.array([-1., 0., 0.]) IN: Vect3 = np.array([0., 0., -1.]) OUT: Vect3 = np.array([0., 0., 1.]) X_AXIS: Vect3 = np.array([1., 0., 0.]) Y_AXIS: Vect3 = np.array([0., 1., 0.]) Z_AXIS: Vect3 = np.array([0., 0., 1.]) NULL_POINTS = np.array([[0., 0., 0.]]) # Useful abbreviations for diagonals UL: Vect3 = UP + LEFT UR: Vect3 = UP + RIGHT DL: Vect3 = DOWN + LEFT DR: Vect3 = DOWN + RIGHT TOP: Vect3 = FRAME_Y_RADIUS * UP BOTTOM: Vect3 = FRAME_Y_RADIUS * DOWN LEFT_SIDE: Vect3 = FRAME_X_RADIUS * LEFT RIGHT_SIDE: Vect3 = FRAME_X_RADIUS * RIGHT PI: float = np.pi TAU: float = 2 * PI DEGREES: float = TAU / 360 # Nice to have a constant for readability # when juxtaposed with expressions like 30 * DEGREES RADIANS: float = 1 FFMPEG_BIN: str = "ffmpeg" JOINT_TYPE_MAP: dict = { "no_joint": 0, "auto": 1, "bevel": 2, "miter": 3, } # Related to Text NORMAL: str = "NORMAL" ITALIC: str = "ITALIC" OBLIQUE: str = "OBLIQUE" BOLD: str = "BOLD" DEFAULT_STROKE_WIDTH: float = 4 # For keyboard interactions CTRL_SYMBOL: int = 65508 SHIFT_SYMBOL: int = 65505 COMMAND_SYMBOL: int = 65517 DELETE_SYMBOL: int = 65288 ARROW_SYMBOLS: list[int] = list(range(65361, 65365)) SHIFT_MODIFIER: int = 1 CTRL_MODIFIER: int = 2 COMMAND_MODIFIER: int = 64 # Colors BLUE_E: ManimColor = "#1C758A" BLUE_D: ManimColor = "#29ABCA" BLUE_C: ManimColor = "#58C4DD" BLUE_B: ManimColor = "#9CDCEB" BLUE_A: ManimColor = "#C7E9F1" TEAL_E: ManimColor = "#49A88F" TEAL_D: ManimColor = "#55C1A7" TEAL_C: ManimColor = "#5CD0B3" TEAL_B: ManimColor = "#76DDC0" TEAL_A: ManimColor = "#ACEAD7" GREEN_E: ManimColor = "#699C52" GREEN_D: ManimColor = "#77B05D" GREEN_C: ManimColor = "#83C167" GREEN_B: ManimColor = "#A6CF8C" GREEN_A: ManimColor = "#C9E2AE" YELLOW_E: ManimColor = "#E8C11C" YELLOW_D: ManimColor = "#F4D345" YELLOW_C: ManimColor = "#FFFF00" YELLOW_B: ManimColor = "#FFEA94" YELLOW_A: ManimColor = "#FFF1B6" GOLD_E: ManimColor = "#C78D46" GOLD_D: ManimColor = "#E1A158" GOLD_C: ManimColor = "#F0AC5F" GOLD_B: ManimColor = "#F9B775" GOLD_A: ManimColor = "#F7C797" RED_E: ManimColor = "#CF5044" RED_D: ManimColor = "#E65A4C" RED_C: ManimColor = "#FC6255" RED_B: ManimColor = "#FF8080" RED_A: ManimColor = "#F7A1A3" MAROON_E: ManimColor = "#94424F" MAROON_D: ManimColor = "#A24D61" MAROON_C: ManimColor = "#C55F73" MAROON_B: ManimColor = "#EC92AB" MAROON_A: ManimColor = "#ECABC1" PURPLE_E: ManimColor = "#644172" PURPLE_D: ManimColor = "#715582" PURPLE_C: ManimColor = "#9A72AC" PURPLE_B: ManimColor = "#B189C6" PURPLE_A: ManimColor = "#CAA3E8" GREY_E: ManimColor = "#222222" GREY_D: ManimColor = "#444444" GREY_C: ManimColor = "#888888" GREY_B: ManimColor = "#BBBBBB" GREY_A: ManimColor = "#DDDDDD" WHITE: ManimColor = "#FFFFFF" BLACK: ManimColor = "#000000" GREY_BROWN: ManimColor = "#736357" DARK_BROWN: ManimColor = "#8B4513" LIGHT_BROWN: ManimColor = "#CD853F" PINK: ManimColor = "#D147BD" LIGHT_PINK: ManimColor = "#DC75CD" GREEN_SCREEN: ManimColor = "#00FF00" ORANGE: ManimColor = "#FF862F" MANIM_COLORS: List[ManimColor] = [ BLACK, GREY_E, GREY_D, GREY_C, GREY_B, GREY_A, WHITE, BLUE_E, BLUE_D, BLUE_C, BLUE_B, BLUE_A, TEAL_E, TEAL_D, TEAL_C, TEAL_B, TEAL_A, GREEN_E, GREEN_D, GREEN_C, GREEN_B, GREEN_A, YELLOW_E, YELLOW_D, YELLOW_C, YELLOW_B, YELLOW_A, GOLD_E, GOLD_D, GOLD_C, GOLD_B, GOLD_A, RED_E, RED_D, RED_C, RED_B, RED_A, MAROON_E, MAROON_D, MAROON_C, MAROON_B, MAROON_A, PURPLE_E, PURPLE_D, PURPLE_C, PURPLE_B, PURPLE_A, GREY_BROWN, DARK_BROWN, LIGHT_BROWN, PINK, LIGHT_PINK, ] # Abbreviated names for the "median" colors BLUE: ManimColor = BLUE_C TEAL: ManimColor = TEAL_C GREEN: ManimColor = GREEN_C YELLOW: ManimColor = YELLOW_C GOLD: ManimColor = GOLD_C RED: ManimColor = RED_C MAROON: ManimColor = MAROON_C PURPLE: ManimColor = PURPLE_C GREY: ManimColor = GREY_C COLORMAP_3B1B: List[ManimColor] = [BLUE_E, GREEN, YELLOW, RED]
manim_3b1b/manimlib/typing.py
from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Union, Tuple, Annotated, Literal, Iterable from colour import Color import numpy as np import re try: from typing import Self except ImportError: from typing_extensions import Self # Abbreviations for a common types ManimColor = Union[str, Color, None] RangeSpecifier = Tuple[float, float, float] | Tuple[float, float] Span = tuple[int, int] SingleSelector = Union[ str, re.Pattern, tuple[Union[int, None], Union[int, None]], ] Selector = Union[SingleSelector, Iterable[SingleSelector]] UniformDict = Dict[str, float | bool | np.ndarray | tuple] # These are various alternate names for np.ndarray meant to specify # certain shapes. # # In theory, these annotations could be used to check arrays sizes # at runtime, but at the moment nothing actually uses them, and # the names are here primarily to enhance readibility and allow # for some stronger type checking if numpy has stronger typing # in the future FloatArray = np.ndarray[int, np.dtype[np.float64]] Vect2 = Annotated[FloatArray, Literal[2]] Vect3 = Annotated[FloatArray, Literal[3]] Vect4 = Annotated[FloatArray, Literal[4]] VectN = Annotated[FloatArray, Literal["N"]] Matrix3x3 = Annotated[FloatArray, Literal[3, 3]] Vect2Array = Annotated[FloatArray, Literal["N", 2]] Vect3Array = Annotated[FloatArray, Literal["N", 3]] Vect4Array = Annotated[FloatArray, Literal["N", 4]] VectNArray = Annotated[FloatArray, Literal["N", "M"]]
manim_3b1b/manimlib/config.py
from __future__ import annotations import argparse from argparse import Namespace import colour import importlib import inspect import os from screeninfo import get_monitors import sys import yaml from manimlib.logger import log from manimlib.utils.dict_ops import merge_dicts_recursively from manimlib.utils.init_config import init_customization from manimlib.constants import FRAME_HEIGHT from typing import TYPE_CHECKING if TYPE_CHECKING: Module = importlib.util.types.ModuleType __config_file__ = "custom_config.yml" def parse_cli(): try: parser = argparse.ArgumentParser() module_location = parser.add_mutually_exclusive_group() module_location.add_argument( "file", nargs="?", help="Path to file holding the python code for the scene", ) parser.add_argument( "scene_names", nargs="*", help="Name of the Scene class you want to see", ) parser.add_argument( "-w", "--write_file", action="store_true", help="Render the scene as a movie file", ) parser.add_argument( "-s", "--skip_animations", action="store_true", help="Save the last frame", ) parser.add_argument( "-l", "--low_quality", action="store_true", help="Render at a low quality (for faster rendering)", ) parser.add_argument( "-m", "--medium_quality", action="store_true", help="Render at a medium quality", ) parser.add_argument( "--hd", action="store_true", help="Render at a 1080p", ) parser.add_argument( "--uhd", action="store_true", help="Render at a 4k", ) parser.add_argument( "-f", "--full_screen", action="store_true", help="Show window in full screen", ) parser.add_argument( "-p", "--presenter_mode", action="store_true", help="Scene will stay paused during wait calls until " + \ "space bar or right arrow is hit, like a slide show" ) parser.add_argument( "-g", "--save_pngs", action="store_true", help="Save each frame as a png", ) parser.add_argument( "-i", "--gif", action="store_true", help="Save the video as gif", ) parser.add_argument( "-t", "--transparent", action="store_true", help="Render to a movie file with an alpha channel", ) parser.add_argument( "--vcodec", help="Video codec to use with ffmpeg", ) parser.add_argument( "--pix_fmt", help="Pixel format to use for the output of ffmpeg, defaults to `yuv420p`", ) parser.add_argument( "-q", "--quiet", action="store_true", help="", ) parser.add_argument( "-a", "--write_all", action="store_true", help="Write all the scenes from a file", ) parser.add_argument( "-o", "--open", action="store_true", help="Automatically open the saved file once its done", ) parser.add_argument( "--finder", action="store_true", help="Show the output file in finder", ) parser.add_argument( "--config", action="store_true", help="Guide for automatic configuration", ) parser.add_argument( "--file_name", help="Name for the movie or image file", ) parser.add_argument( "-n", "--start_at_animation_number", help="Start rendering not from the first animation, but " + \ "from another, specified by its index. If you pass " + \ "in two comma separated values, e.g. \"3,6\", it will end " + \ "the rendering at the second value", ) parser.add_argument( "-e", "--embed", nargs="?", const="", help="Creates a new file where the line `self.embed` is inserted " + \ "into the Scenes construct method. " + \ "If a string is passed in, the line will be inserted below the " + \ "last line of code including that string." ) parser.add_argument( "-r", "--resolution", help="Resolution, passed as \"WxH\", e.g. \"1920x1080\"", ) parser.add_argument( "--fps", help="Frame rate, as an integer", ) parser.add_argument( "-c", "--color", help="Background color", ) parser.add_argument( "--leave_progress_bars", action="store_true", help="Leave progress bars displayed in terminal", ) parser.add_argument( "--show_animation_progress", action="store_true", help="Show progress bar for each animation", ) parser.add_argument( "--prerun", action="store_true", help="Calculate total framecount, to display in a progress bar, by doing " + \ "an initial run of the scene which skips animations." ) parser.add_argument( "--video_dir", help="Directory to write video", ) parser.add_argument( "--config_file", help="Path to the custom configuration file", ) parser.add_argument( "-v", "--version", action="store_true", help="Display the version of manimgl" ) parser.add_argument( "--log-level", help="Level of messages to Display, can be DEBUG / INFO / WARNING / ERROR / CRITICAL" ) args = parser.parse_args() args.write_file = any([args.write_file, args.open, args.finder]) return args except argparse.ArgumentError as err: log.error(str(err)) sys.exit(2) def get_manim_dir(): manimlib_module = importlib.import_module("manimlib") manimlib_dir = os.path.dirname(inspect.getabsfile(manimlib_module)) return os.path.abspath(os.path.join(manimlib_dir, "..")) def get_module(file_name: str | None) -> Module: if file_name is None: return None module_name = file_name.replace(os.sep, ".").replace(".py", "") spec = importlib.util.spec_from_file_location(module_name, file_name) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def get_indent(line: str): return len(line) - len(line.lstrip()) def get_module_with_inserted_embed_line( file_name: str, scene_name: str, line_marker: str ): """ This is hacky, but convenient. When user includes the argument "-e", it will try to recreate a file that inserts the line `self.embed()` into the end of the scene's construct method. If there is an argument passed in, it will insert the line after the last line in the sourcefile which includes that string. """ with open(file_name, 'r') as fp: lines = fp.readlines() try: scene_line_number = next( i for i, line in enumerate(lines) if line.startswith(f"class {scene_name}") ) except StopIteration: log.error(f"No scene {scene_name}") return prev_line_num = -1 n_spaces = None if len(line_marker) == 0: # Find the end of the construct method in_construct = False for index in range(scene_line_number, len(lines) - 1): line = lines[index] if line.lstrip().startswith("def construct"): in_construct = True n_spaces = get_indent(line) + 4 elif in_construct: if len(line.strip()) > 0 and get_indent(line) < (n_spaces or 0): prev_line_num = index - 1 break if prev_line_num < 0: prev_line_num = len(lines) - 1 elif line_marker.isdigit(): # Treat the argument as a line number prev_line_num = int(line_marker) - 1 elif len(line_marker) > 0: # Treat the argument as a string try: prev_line_num = next( i for i in range(scene_line_number, len(lines) - 1) if line_marker in lines[i] ) except StopIteration: log.error(f"No lines matching {line_marker}") sys.exit(2) # Insert the embed line, rewrite file, then write it back when done if n_spaces is None: n_spaces = get_indent(lines[prev_line_num]) inserted_line = " " * n_spaces + "self.embed()\n" new_lines = list(lines) new_lines.insert(prev_line_num + 1, inserted_line) new_file = file_name.replace(".py", "_insert_embed.py") with open(new_file, 'w') as fp: fp.writelines(new_lines) module = get_module(new_file) # This is to pretend the module imported from the edited lines # of code actually comes from the original file. module.__file__ = file_name os.remove(new_file) return module def get_scene_module(args: Namespace) -> Module: if args.embed is None: return get_module(args.file) else: return get_module_with_inserted_embed_line( args.file, args.scene_names[0], args.embed ) def get_custom_config(): global __config_file__ global_defaults_file = os.path.join(get_manim_dir(), "manimlib", "default_config.yml") if os.path.exists(global_defaults_file): with open(global_defaults_file, "r") as file: custom_config = yaml.safe_load(file) if os.path.exists(__config_file__): with open(__config_file__, "r") as file: local_defaults = yaml.safe_load(file) if local_defaults: custom_config = merge_dicts_recursively( custom_config, local_defaults, ) else: with open(__config_file__, "r") as file: custom_config = yaml.safe_load(file) # Check temporary storage(custom_config) if custom_config["directories"]["temporary_storage"] == "" and sys.platform == "win32": log.warning( "You may be using Windows platform and have not specified the path of" + \ " `temporary_storage`, which may cause OSError. So it is recommended" + \ " to specify the `temporary_storage` in the config file (.yml)" ) return custom_config def init_global_config(config_file): global __config_file__ # ensure __config_file__ always exists if config_file is not None: if not os.path.exists(config_file): log.error(f"Can't find {config_file}.") if sys.platform == 'win32': log.info(f"Copying default configuration file to {config_file}...") os.system(f"copy default_config.yml {config_file}") elif sys.platform in ["linux2", "darwin"]: log.info(f"Copying default configuration file to {config_file}...") os.system(f"cp default_config.yml {config_file}") else: log.info("Please create the configuration file manually.") log.info("Read configuration from default_config.yml.") else: __config_file__ = config_file global_defaults_file = os.path.join(get_manim_dir(), "manimlib", "default_config.yml") if not (os.path.exists(global_defaults_file) or os.path.exists(__config_file__)): log.info("There is no configuration file detected. Switch to the config file initializer:") init_customization() elif not os.path.exists(__config_file__): log.info(f"Using the default configuration file, which you can modify in `{global_defaults_file}`") log.info( "If you want to create a local configuration file, you can create a file named" + \ f" `{__config_file__}`, or run `manimgl --config`" ) def get_file_ext(args: Namespace) -> str: if args.transparent: file_ext = ".mov" elif args.gif: file_ext = ".gif" else: file_ext = ".mp4" return file_ext def get_animations_numbers(args: Namespace) -> tuple[int | None, int | None]: stan = args.start_at_animation_number if stan is None: return (None, None) elif "," in stan: return tuple(map(int, stan.split(","))) else: return int(stan), None def get_output_directory(args: Namespace, custom_config: dict) -> str: dir_config = custom_config["directories"] output_directory = args.video_dir or dir_config["output"] if dir_config["mirror_module_path"] and args.file: to_cut = dir_config["removed_mirror_prefix"] ext = os.path.abspath(args.file) ext = ext.replace(to_cut, "").replace(".py", "") if ext.startswith("_"): ext = ext[1:] output_directory = os.path.join(output_directory, ext) return output_directory def get_file_writer_config(args: Namespace, custom_config: dict) -> dict: result = { "write_to_movie": not args.skip_animations and args.write_file, "break_into_partial_movies": custom_config["break_into_partial_movies"], "save_last_frame": args.skip_animations and args.write_file, "save_pngs": args.save_pngs, # If -t is passed in (for transparent), this will be RGBA "png_mode": "RGBA" if args.transparent else "RGB", "movie_file_extension": get_file_ext(args), "output_directory": get_output_directory(args, custom_config), "file_name": args.file_name, "input_file_path": args.file or "", "open_file_upon_completion": args.open, "show_file_location_upon_completion": args.finder, "quiet": args.quiet, } if args.vcodec: result["video_codec"] = args.vcodec elif args.transparent: result["video_codec"] = 'prores_ks' result["pixel_format"] = '' elif args.gif: result["video_codec"] = '' if args.pix_fmt: result["pixel_format"] = args.pix_fmt return result def get_window_config(args: Namespace, custom_config: dict, camera_config: dict) -> dict: # Default to making window half the screen size # but make it full screen if -f is passed in monitors = get_monitors() mon_index = custom_config["window_monitor"] monitor = monitors[min(mon_index, len(monitors) - 1)] aspect_ratio = camera_config["pixel_width"] / camera_config["pixel_height"] window_width = monitor.width if not (args.full_screen or custom_config["full_screen"]): window_width //= 2 window_height = int(window_width / aspect_ratio) return dict(size=(window_width, window_height)) def get_camera_config(args: Namespace, custom_config: dict) -> dict: camera_config = {} camera_resolutions = custom_config["camera_resolutions"] if args.resolution: resolution = args.resolution elif args.low_quality: resolution = camera_resolutions["low"] elif args.medium_quality: resolution = camera_resolutions["med"] elif args.hd: resolution = camera_resolutions["high"] elif args.uhd: resolution = camera_resolutions["4k"] else: resolution = camera_resolutions[camera_resolutions["default_resolution"]] if args.fps: fps = int(args.fps) else: fps = custom_config["fps"] width_str, height_str = resolution.split("x") width = int(width_str) height = int(height_str) camera_config.update({ "pixel_width": width, "pixel_height": height, "frame_config": { "frame_shape": ((width / height) * FRAME_HEIGHT, FRAME_HEIGHT), }, "fps": fps, }) try: bg_color = args.color or custom_config["style"]["background_color"] camera_config["background_color"] = colour.Color(bg_color) except ValueError as err: log.error("Please use a valid color") log.error(err) sys.exit(2) # If rendering a transparent image/move, make sure the # scene has a background opacity of 0 if args.transparent: camera_config["background_opacity"] = 0 return camera_config def get_configuration(args: Namespace) -> dict: init_global_config(args.config_file) custom_config = get_custom_config() camera_config = get_camera_config(args, custom_config) window_config = get_window_config(args, custom_config, camera_config) start, end = get_animations_numbers(args) return { "module": get_scene_module(args), "scene_names": args.scene_names, "file_writer_config": get_file_writer_config(args, custom_config), "camera_config": camera_config, "window_config": window_config, "quiet": args.quiet or args.write_all, "write_all": args.write_all, "skip_animations": args.skip_animations, "start_at_animation_number": start, "end_at_animation_number": end, "preview": not args.write_file, "presenter_mode": args.presenter_mode, "leave_progress_bars": args.leave_progress_bars, "show_animation_progress": args.show_animation_progress, "prerun": args.prerun, "embed_exception_mode": custom_config["embed_exception_mode"], "embed_error_sound": custom_config["embed_error_sound"], }
manim_3b1b/manimlib/tex_templates.yml
# Classical TeX templates default: description: "" compiler: latex preamble: |- \usepackage[english]{babel} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{amsmath} \usepackage{amssymb} \usepackage{dsfont} \usepackage{setspace} \usepackage{tipa} \usepackage{relsize} \usepackage{textcomp} \usepackage{mathrsfs} \usepackage{calligra} \usepackage{wasysym} \usepackage{ragged2e} \usepackage{physics} \usepackage{xcolor} \usepackage{microtype} \usepackage{pifont} \DisableLigatures{encoding = *, family = * } \linespread{1} ctex: description: "" compiler: xelatex preamble: |- \usepackage[UTF8]{ctex} \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \usepackage{dsfont} \usepackage{setspace} \usepackage{tipa} \usepackage{relsize} \usepackage{textcomp} \usepackage{mathrsfs} \usepackage{calligra} \usepackage{wasysym} \usepackage{ragged2e} \usepackage{physics} \usepackage{xcolor} \usepackage{microtype} \linespread{1} # Simplified TeX templates basic: description: "" compiler: latex preamble: |- \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} basic_ctex: description: "" compiler: xelatex preamble: |- \usepackage[UTF8]{ctex} \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} empty: description: "" compiler: latex preamble: "" empty_ctex: description: "" compiler: xelatex preamble: "" # A collection of TeX templates for the fonts described at # http://jf.burnol.free.fr/showcase.html american_typewriter: description: American Typewriter compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{American Typewriter} \usepackage[defaultmathsizes]{mathastext} antykwa: description: Antykwa Poltawskiego (TX Fonts for Greek and math symbols) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[OT4,OT1]{fontenc} \usepackage{txfonts} \usepackage[upright]{txgreeks} \usepackage{antpolt} \usepackage[defaultmathsizes,nolessnomore]{mathastext} apple_chancery: description: Apple Chancery compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Apple Chancery} \usepackage[defaultmathsizes]{mathastext} auriocus_kalligraphicus: description: Auriocus Kalligraphicus (Symbol Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{aurical} \renewcommand{\rmdefault}{AuriocusKalligraphicus} \usepackage[symbolgreek]{mathastext} baskervald_adf_fourier: description: Baskervald ADF with Fourier compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[upright]{fourier} \usepackage{baskervald} \usepackage[defaultmathsizes,noasterisk]{mathastext} baskerville_it: description: Baskerville (Italic) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Baskerville} \usepackage[defaultmathsizes,italic]{mathastext} biolinum: description: Biolinum compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{txfonts} \usepackage[upright]{txgreeks} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Minion Pro} \setsansfont[Mapping=tex-text,Scale=MatchUppercase]{Myriad Pro} \renewcommand\familydefault\sfdefault \usepackage[defaultmathsizes]{mathastext} \renewcommand\familydefault\rmdefault brushscriptx: description: BrushScriptX-Italic (PX math and Greek) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{pxfonts} \renewcommand{\rmdefault}{pbsi} \renewcommand{\mddefault}{xl} \renewcommand{\bfdefault}{xl} \usepackage[defaultmathsizes,noasterisk]{mathastext} \boldmath chalkboard_se: description: Chalkboard SE compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Chalkboard SE} \usepackage[defaultmathsizes]{mathastext} chalkduster: description: Chalkduster compiler: lualatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Chalkduster} \usepackage[defaultmathsizes]{mathastext} comfortaa: description: Comfortaa compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[default]{comfortaa} \usepackage[LGRgreek,defaultmathsizes,noasterisk]{mathastext} \let\varphi\phi \linespread{1.06} comic_sans: description: Comic Sans MS compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Comic Sans MS} \usepackage[defaultmathsizes]{mathastext} droid_sans: description: Droid Sans compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[default]{droidsans} \usepackage[LGRgreek]{mathastext} \let\varepsilon\epsilon droid_sans_it: description: Droid Sans (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[default]{droidsans} \usepackage[LGRgreek,defaultmathsizes,italic]{mathastext} \let\varphi\phi droid_serif: description: Droid Serif compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[default]{droidserif} \usepackage[LGRgreek]{mathastext} \let\varepsilon\epsilon droid_serif_px_it: description: Droid Serif (PX math symbols) (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{pxfonts} \usepackage[default]{droidserif} \usepackage[LGRgreek,defaultmathsizes,italic,basic]{mathastext} \let\varphi\phi ecf_augie: description: ECF Augie (Euler Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \renewcommand\familydefault{fau} \usepackage[defaultmathsizes,eulergreek]{mathastext} ecf_jd: description: ECF JD (with TX fonts) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{txfonts} \usepackage[upright]{txgreeks} \renewcommand\familydefault{fjd} \usepackage{mathastext} \mathversion{bold} ecf_skeetch: description: ECF Skeetch (CM Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \DeclareFontFamily{T1}{fsk}{} \DeclareFontShape{T1}{fsk}{m}{n}{<->s*[1.315] fskmw8t}{} \renewcommand\rmdefault{fsk} \usepackage[noendash,defaultmathsizes,nohbar,defaultimath]{mathastext} ecf_tall_paul: description: ECF Tall Paul (with Symbol font) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \DeclareFontFamily{T1}{ftp}{} \DeclareFontShape{T1}{ftp}{m}{n}{<->s*[1.4] ftpmw8t}{} \renewcommand\familydefault{ftp} \usepackage[symbol]{mathastext} \let\infty\inftypsy ecf_webster: description: ECF Webster (with TX fonts) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{txfonts} \usepackage[upright]{txgreeks} \renewcommand\familydefault{fwb} \usepackage{mathastext} \renewcommand{\int}{\intop\limits} \linespread{1.5} \mathversion{bold} electrum_adf: description: Electrum ADF (CM Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[LGRgreek,basic,defaultmathsizes]{mathastext} \usepackage[lf]{electrum} \Mathastext \let\varphi\phi epigrafica: description: Epigrafica compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[LGR,OT1]{fontenc} \usepackage{epigrafica} \usepackage[basic,LGRgreek,defaultmathsizes]{mathastext} \let\varphi\phi \linespread{1.2} fourier_utopia: description: Fourier Utopia (Fourier upright Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[upright]{fourier} \usepackage{mathastext} french_cursive: description: French Cursive (Euler Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[default]{frcursive} \usepackage[eulergreek,noplusnominus,noequal,nohbar,nolessnomore,noasterisk]{mathastext} gfs_bodoni: description: GFS Bodoni compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \renewcommand{\rmdefault}{bodoni} \usepackage[LGRgreek]{mathastext} \let\varphi\phi \linespread{1.06} gfs_didot: description: GFS Didot (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \renewcommand\rmdefault{udidot} \usepackage[LGRgreek,defaultmathsizes,italic]{mathastext} \let\varphi\phi gfs_neohellenic: description: GFS NeoHellenic compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \renewcommand{\rmdefault}{neohellenic} \usepackage[LGRgreek]{mathastext} \let\varphi\phi \linespread{1.06} gnu_freesans_tx: description: GNU FreeSerif (and TX fonts symbols) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \usepackage{txfonts} \setmainfont[ExternalLocation,Mapping=tex-text,BoldFont=FreeSerifBold,ItalicFont=FreeSerifItalic,BoldItalicFont=FreeSerifBoldItalic]{FreeSerif} \usepackage[defaultmathsizes]{mathastext} gnu_freeserif_freesans: description: GNU FreeSerif and FreeSans compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[ExternalLocation,Mapping=tex-text,BoldFont=FreeSerifBold,ItalicFont=FreeSerifItalic,BoldItalicFont=FreeSerifBoldItalic]{FreeSerif} \setsansfont[ExternalLocation,Mapping=tex-text,BoldFont=FreeSansBold,ItalicFont=FreeSansOblique,BoldItalicFont=FreeSansBoldOblique,Scale=MatchLowercase]{FreeSans} \renewcommand{\familydefault}{lmss} \usepackage[LGRgreek,defaultmathsizes,noasterisk]{mathastext} \renewcommand{\familydefault}{\sfdefault} \Mathastext \let\varphi\phi \renewcommand{\familydefault}{\rmdefault} helvetica_fourier_it: description: Helvetica with Fourier (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[scaled]{helvet} \usepackage{fourier} \renewcommand{\rmdefault}{phv} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} latin_modern_tw: description: Latin Modern Typewriter Proportional compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[variablett]{lmodern} \renewcommand{\rmdefault}{\ttdefault} \usepackage[LGRgreek]{mathastext} \MTgreekfont{lmtt} \Mathastext \let\varepsilon\epsilon latin_modern_tw_it: description: Latin Modern Typewriter Proportional (CM Greek) (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[variablett,nomath]{lmodern} \renewcommand{\familydefault}{\ttdefault} \usepackage[frenchmath]{mathastext} \linespread{1.08} libertine: description: Libertine compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{libertine} \usepackage[greek=n]{libgreek} \usepackage[noasterisk,defaultmathsizes]{mathastext} libris_adf_fourier: description: Libris ADF with Fourier compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[upright]{fourier} \usepackage{libris} \renewcommand{\familydefault}{\sfdefault} \usepackage[noasterisk]{mathastext} minion_pro_myriad_pro: description: Minion Pro and Myriad Pro (and TX fonts symbols) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage[default]{droidserif} \usepackage[LGRgreek]{mathastext} \let\varepsilon\epsilon minion_pro_tx: description: Minion Pro (and TX fonts symbols) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{txfonts} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Minion Pro} \usepackage[defaultmathsizes]{mathastext} new_century_schoolbook: description: New Century Schoolbook (Symbol Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{newcent} \usepackage[symbolgreek]{mathastext} \linespread{1.1} new_century_schoolbook_px: description: New Century Schoolbook (Symbol Greek, PX math symbols) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{pxfonts} \usepackage{newcent} \usepackage[symbolgreek,defaultmathsizes]{mathastext} \linespread{1.06} noteworthy_light: description: Noteworthy Light compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Noteworthy Light} \usepackage[defaultmathsizes]{mathastext} palatino: description: Palatino (Symbol Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{palatino} \usepackage[symbolmax,defaultmathsizes]{mathastext} papyrus: description: Papyrus compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Papyrus} \usepackage[defaultmathsizes]{mathastext} romande_adf_fourier_it: description: Romande ADF with Fourier (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{fourier} \usepackage{romande} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} \renewcommand{\itshape}{\swashstyle} slitex: description: SliTeX (Euler Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{tpslifonts} \usepackage[eulergreek,defaultmathsizes]{mathastext} \MTEulerScale{1.06} \linespread{1.2} times_fourier_it: description: Times with Fourier (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{fourier} \renewcommand{\rmdefault}{ptm} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} urw_avant_garde: description: URW Avant Garde (Symbol Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{avant} \renewcommand{\familydefault}{\sfdefault} \usepackage[symbolgreek,defaultmathsizes]{mathastext} urw_zapf_chancery: description: URW Zapf Chancery (CM Greek) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \DeclareFontFamily{T1}{pzc}{} \DeclareFontShape{T1}{pzc}{mb}{it}{<->s*[1.2] pzcmi8t}{} \DeclareFontShape{T1}{pzc}{m}{it}{<->ssub * pzc/mb/it}{} \DeclareFontShape{T1}{pzc}{mb}{sl}{<->ssub * pzc/mb/it}{} \DeclareFontShape{T1}{pzc}{m}{sl}{<->ssub * pzc/mb/sl}{} \DeclareFontShape{T1}{pzc}{m}{n}{<->ssub * pzc/mb/it}{} \usepackage{chancery} \usepackage{mathastext} \linespread{1.05} \boldmath venturis_adf_fourier_it: description: Venturis ADF with Fourier (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{fourier} \usepackage[lf]{venturis} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} verdana_it: description: Verdana (Italic) compiler: xelatex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Verdana} \usepackage[defaultmathsizes,italic]{mathastext} vollkorn: description: Vollkorn (TX fonts for Greek and math symbols) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage[T1]{fontenc} \usepackage{txfonts} \usepackage[upright]{txgreeks} \usepackage{vollkorn} \usepackage[defaultmathsizes]{mathastext} vollkorn_fourier_it: description: Vollkorn with Fourier (Italic) compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \usepackage{fourier} \usepackage{vollkorn} \usepackage[italic,nohbar]{mathastext} zapf_chancery: description: Zapf Chancery compiler: latex preamble: |- \usepackage{amsmath} \usepackage{amssymb} \usepackage{xcolor} \DeclareFontFamily{T1}{pzc}{} \DeclareFontShape{T1}{pzc}{mb}{it}{<->s*[1.2] pzcmi8t}{} \DeclareFontShape{T1}{pzc}{m}{it}{<->ssub * pzc/mb/it}{} \usepackage{chancery} \renewcommand\shapedefault\itdefault \renewcommand\bfdefault\mddefault \usepackage[defaultmathsizes]{mathastext} \linespread{1.05}
manim_3b1b/manimlib/window.py
from __future__ import annotations import numpy as np import moderngl_window as mglw from moderngl_window.context.pyglet.window import Window as PygletWindow from moderngl_window.timers.clock import Timer from screeninfo import get_monitors from manimlib.constants import FRAME_SHAPE from manimlib.utils.customization import get_customization from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.scene.scene import Scene class Window(PygletWindow): fullscreen: bool = False resizable: bool = True gl_version: tuple[int, int] = (3, 3) vsync: bool = True cursor: bool = True def __init__( self, scene: Scene, size: tuple[int, int] = (1280, 720), samples: int = 0 ): scene.window = self super().__init__(size=size, samples=samples) self.default_size = size self.default_position = self.find_initial_position(size) self.scene = scene self.pressed_keys = set() self.title = str(scene) self.size = size mglw.activate_context(window=self) self.timer = Timer() self.config = mglw.WindowConfig(ctx=self.ctx, wnd=self, timer=self.timer) self.timer.start() self.to_default_position() def to_default_position(self): self.position = self.default_position # Hack. Sometimes, namely when configured to open in a separate window, # the window needs to be resized to display correctly. w, h = self.default_size self.size = (w - 1, h - 1) self.size = (w, h) def find_initial_position(self, size: tuple[int, int]) -> tuple[int, int]: custom_position = get_customization()["window_position"] monitors = get_monitors() mon_index = get_customization()["window_monitor"] monitor = monitors[min(mon_index, len(monitors) - 1)] window_width, window_height = size # Position might be specified with a string of the form # x,y for integers x and y if "," in custom_position: return tuple(map(int, custom_position.split(","))) # Alternatively, it might be specified with a string like # UR, OO, DL, etc. specifying what corner it should go to char_to_n = {"L": 0, "U": 0, "O": 1, "R": 2, "D": 2} width_diff = monitor.width - window_width height_diff = monitor.height - window_height return ( monitor.x + char_to_n[custom_position[1]] * width_diff // 2, -monitor.y + char_to_n[custom_position[0]] * height_diff // 2, ) # Delegate event handling to scene def pixel_coords_to_space_coords( self, px: int, py: int, relative: bool = False ) -> np.ndarray: if not hasattr(self.scene, "frame"): return np.zeros(3) pixel_shape = np.array(self.size) fixed_frame_shape = np.array(FRAME_SHAPE) frame = self.scene.frame coords = np.zeros(3) coords[:2] = (fixed_frame_shape / pixel_shape) * np.array([px, py]) if not relative: coords[:2] -= 0.5 * fixed_frame_shape return frame.from_fixed_frame_point(coords, relative) def on_mouse_motion(self, x: int, y: int, dx: int, dy: int) -> None: super().on_mouse_motion(x, y, dx, dy) point = self.pixel_coords_to_space_coords(x, y) d_point = self.pixel_coords_to_space_coords(dx, dy, relative=True) self.scene.on_mouse_motion(point, d_point) def on_mouse_drag(self, x: int, y: int, dx: int, dy: int, buttons: int, modifiers: int) -> None: super().on_mouse_drag(x, y, dx, dy, buttons, modifiers) point = self.pixel_coords_to_space_coords(x, y) d_point = self.pixel_coords_to_space_coords(dx, dy, relative=True) self.scene.on_mouse_drag(point, d_point, buttons, modifiers) def on_mouse_press(self, x: int, y: int, button: int, mods: int) -> None: super().on_mouse_press(x, y, button, mods) point = self.pixel_coords_to_space_coords(x, y) self.scene.on_mouse_press(point, button, mods) def on_mouse_release(self, x: int, y: int, button: int, mods: int) -> None: super().on_mouse_release(x, y, button, mods) point = self.pixel_coords_to_space_coords(x, y) self.scene.on_mouse_release(point, button, mods) def on_mouse_scroll(self, x: int, y: int, x_offset: float, y_offset: float) -> None: super().on_mouse_scroll(x, y, x_offset, y_offset) point = self.pixel_coords_to_space_coords(x, y) offset = self.pixel_coords_to_space_coords(x_offset, y_offset, relative=True) self.scene.on_mouse_scroll(point, offset, x_offset, y_offset) def on_key_press(self, symbol: int, modifiers: int) -> None: self.pressed_keys.add(symbol) # Modifiers? super().on_key_press(symbol, modifiers) self.scene.on_key_press(symbol, modifiers) def on_key_release(self, symbol: int, modifiers: int) -> None: self.pressed_keys.difference_update({symbol}) # Modifiers? super().on_key_release(symbol, modifiers) self.scene.on_key_release(symbol, modifiers) def on_resize(self, width: int, height: int) -> None: super().on_resize(width, height) self.scene.on_resize(width, height) def on_show(self) -> None: super().on_show() self.scene.on_show() def on_hide(self) -> None: super().on_hide() self.scene.on_hide() def on_close(self) -> None: super().on_close() self.scene.on_close() def is_key_pressed(self, symbol: int) -> bool: return (symbol in self.pressed_keys)
manim_3b1b/manimlib/extract_scene.py
import copy import inspect import sys from manimlib.config import get_custom_config from manimlib.logger import log from manimlib.scene.interactive_scene import InteractiveScene from manimlib.scene.scene import Scene class BlankScene(InteractiveScene): def construct(self): exec(get_custom_config()["universal_import_line"]) self.embed() def is_child_scene(obj, module): if not inspect.isclass(obj): return False if not issubclass(obj, Scene): return False if obj == Scene: return False if not obj.__module__.startswith(module.__name__): return False return True def prompt_user_for_choice(scene_classes): name_to_class = {} max_digits = len(str(len(scene_classes))) for idx, scene_class in enumerate(scene_classes, start=1): name = scene_class.__name__ print(f"{str(idx).zfill(max_digits)}: {name}") name_to_class[name] = scene_class try: user_input = input( "\nThat module has multiple scenes, " + \ "which ones would you like to render?" + \ "\nScene Name or Number: " ) return [ name_to_class[split_str] if not split_str.isnumeric() else scene_classes[int(split_str) - 1] for split_str in user_input.replace(" ", "").split(",") ] except IndexError: log.error("Invalid scene number") sys.exit(2) except KeyError: log.error("Invalid scene name") sys.exit(2) except EOFError: sys.exit(1) def get_scene_config(config): scene_parameters = inspect.signature(Scene).parameters.keys() return { key: config[key] for key in set(scene_parameters).intersection(config.keys()) } def compute_total_frames(scene_class, scene_config): """ When a scene is being written to file, a copy of the scene is run with skip_animations set to true so as to count how many frames it will require. This allows for a total progress bar on rendering, and also allows runtime errors to be exposed preemptively for long running scenes. """ pre_config = copy.deepcopy(scene_config) pre_config["file_writer_config"]["write_to_movie"] = False pre_config["file_writer_config"]["save_last_frame"] = False pre_config["file_writer_config"]["quiet"] = True pre_config["skip_animations"] = True pre_scene = scene_class(**pre_config) pre_scene.run() total_time = pre_scene.time - pre_scene.skip_time return int(total_time * scene_config["camera_config"]["fps"]) def scene_from_class(scene_class, scene_config, config): fw_config = scene_config["file_writer_config"] if fw_config["write_to_movie"] and config["prerun"]: fw_config["total_frames"] = compute_total_frames(scene_class, scene_config) return scene_class(**scene_config) def get_scenes_to_render(all_scene_classes, scene_config, config): if config["write_all"]: return [sc(**scene_config) for sc in all_scene_classes] names_to_classes = {sc.__name__ : sc for sc in all_scene_classes} scene_names = config["scene_names"] for name in set.difference(set(scene_names), names_to_classes): log.error(f"No scene named {name} found") scene_names.remove(name) if scene_names: classes_to_run = [names_to_classes[name] for name in scene_names] elif len(all_scene_classes) == 1: classes_to_run = [all_scene_classes[0]] else: classes_to_run = prompt_user_for_choice(all_scene_classes) return [ scene_from_class(scene_class, scene_config, config) for scene_class in classes_to_run ] def get_scene_classes_from_module(module): if hasattr(module, "SCENES_IN_ORDER"): return module.SCENES_IN_ORDER else: return [ member[1] for member in inspect.getmembers( module, lambda x: is_child_scene(x, module) ) ] def main(config): module = config["module"] scene_config = get_scene_config(config) if module is None: # If no module was passed in, just play the blank scene return [BlankScene(**scene_config)] all_scene_classes = get_scene_classes_from_module(module) scenes = get_scenes_to_render(all_scene_classes, scene_config, config) return scenes
manim_3b1b/manimlib/logger.py
import logging from rich.logging import RichHandler __all__ = ["log"] FORMAT = "%(message)s" logging.basicConfig( level=logging.WARNING, format=FORMAT, datefmt="[%X]", handlers=[RichHandler()] ) log = logging.getLogger("manimgl") log.setLevel("DEBUG")
manim_3b1b/manimlib/scene/__init__.py
manim_3b1b/manimlib/scene/interactive_scene.py
from __future__ import annotations import itertools as it import numpy as np import pyperclip from IPython.core.getipython import get_ipython from manimlib.animation.fading import FadeIn from manimlib.constants import ARROW_SYMBOLS, CTRL_SYMBOL, DELETE_SYMBOL, SHIFT_SYMBOL from manimlib.constants import COMMAND_MODIFIER, SHIFT_MODIFIER from manimlib.constants import DL, DOWN, DR, LEFT, ORIGIN, RIGHT, UL, UP, UR from manimlib.constants import FRAME_WIDTH, FRAME_HEIGHT, SMALL_BUFF from manimlib.constants import PI from manimlib.constants import DEGREES from manimlib.constants import MANIM_COLORS, WHITE, GREY_A, GREY_C from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import Square from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Mobject from manimlib.mobject.numbers import DecimalNumber from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.dot_cloud import DotCloud from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VHighlight from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.scene.scene import Scene from manimlib.scene.scene import SceneState from manimlib.scene.scene import PAN_3D_KEY from manimlib.utils.family_ops import extract_mobject_family_members from manimlib.utils.space_ops import get_norm from manimlib.utils.tex_file_writing import LatexError from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import Vect3 SELECT_KEY = 's' UNSELECT_KEY = 'u' GRAB_KEY = 'g' X_GRAB_KEY = 'h' Y_GRAB_KEY = 'v' GRAB_KEYS = [GRAB_KEY, X_GRAB_KEY, Y_GRAB_KEY] RESIZE_KEY = 't' COLOR_KEY = 'c' INFORMATION_KEY = 'i' CURSOR_KEY = 'k' # Note, a lot of the functionality here is still buggy and very much a work in progress. class InteractiveScene(Scene): """ To select mobjects on screen, hold ctrl and move the mouse to highlight a region, or just tap ctrl to select the mobject under the cursor. Pressing command + t will toggle between modes where you either select top level mobjects part of the scene, or low level pieces. Hold 'g' to grab the selection and move it around Hold 'h' to drag it constrained in the horizontal direction Hold 'v' to drag it constrained in the vertical direction Hold 't' to resize selection, adding 'shift' to resize with respect to a corner Command + 'c' copies the ids of selections to clipboard Command + 'v' will paste either: - The copied mobject - A Tex mobject based on copied LaTeX - A Text mobject based on copied Text Command + 'z' restores selection back to its original state Command + 's' saves the selected mobjects to file """ corner_dot_config = dict( color=WHITE, radius=0.05, glow_factor=2.0, ) selection_rectangle_stroke_color = WHITE selection_rectangle_stroke_width = 1.0 palette_colors = MANIM_COLORS selection_nudge_size = 0.05 cursor_location_config = dict( font_size=24, fill_color=GREY_C, num_decimal_places=3, ) time_label_config = dict( font_size=24, fill_color=GREY_C, num_decimal_places=1, ) crosshair_width = 0.2 crosshair_style = dict( stroke_color=GREY_A, stroke_width=[3, 0, 3], ) def setup(self): self.selection = Group() self.selection_highlight = self.get_selection_highlight() self.selection_rectangle = self.get_selection_rectangle() self.crosshair = self.get_crosshair() self.information_label = self.get_information_label() self.color_palette = self.get_color_palette() self.unselectables = [ self.selection, self.selection_highlight, self.selection_rectangle, self.crosshair, self.information_label, self.camera.frame ] self.select_top_level_mobs = True self.regenerate_selection_search_set() self.is_selecting = False self.is_grabbing = False self.add(self.selection_highlight) def get_selection_rectangle(self): rect = Rectangle( stroke_color=self.selection_rectangle_stroke_color, stroke_width=self.selection_rectangle_stroke_width, ) rect.fix_in_frame() rect.fixed_corner = ORIGIN rect.add_updater(self.update_selection_rectangle) return rect def update_selection_rectangle(self, rect: Rectangle): p1 = rect.fixed_corner p2 = self.frame.to_fixed_frame_point(self.mouse_point.get_center()) rect.set_points_as_corners([ p1, np.array([p2[0], p1[1], 0]), p2, np.array([p1[0], p2[1], 0]), p1, ]) return rect def get_selection_highlight(self): result = Group() result.tracked_mobjects = [] result.add_updater(self.update_selection_highlight) return result def update_selection_highlight(self, highlight: Mobject): if set(highlight.tracked_mobjects) == set(self.selection): return # Otherwise, refresh contents of highlight highlight.tracked_mobjects = list(self.selection) highlight.set_submobjects([ self.get_highlight(mob) for mob in self.selection ]) try: index = min(( i for i, mob in enumerate(self.mobjects) for sm in self.selection if sm in mob.get_family() )) self.mobjects.remove(highlight) self.mobjects.insert(index - 1, highlight) except ValueError: pass def get_crosshair(self): lines = VMobject().replicate(2) lines[0].set_points([LEFT, ORIGIN, RIGHT]) lines[1].set_points([UP, ORIGIN, DOWN]) crosshair = VGroup(*lines) crosshair.set_width(self.crosshair_width) crosshair.set_style(**self.crosshair_style) crosshair.set_animating_status(True) crosshair.fix_in_frame() return crosshair def get_color_palette(self): palette = VGroup(*( Square(fill_color=color, fill_opacity=1, side_length=1) for color in self.palette_colors )) palette.set_stroke(width=0) palette.arrange(RIGHT, buff=0.5) palette.set_width(FRAME_WIDTH - 0.5) palette.to_edge(DOWN, buff=SMALL_BUFF) palette.fix_in_frame() return palette def get_information_label(self): loc_label = VGroup(*( DecimalNumber(**self.cursor_location_config) for n in range(3) )) def update_coords(loc_label): for mob, coord in zip(loc_label, self.mouse_point.get_location()): mob.set_value(coord) loc_label.arrange(RIGHT, buff=loc_label.get_height()) loc_label.to_corner(DR, buff=SMALL_BUFF) loc_label.fix_in_frame() return loc_label loc_label.add_updater(update_coords) time_label = DecimalNumber(0, **self.time_label_config) time_label.to_corner(DL, buff=SMALL_BUFF) time_label.fix_in_frame() time_label.add_updater(lambda m, dt: m.increment_value(dt)) return VGroup(loc_label, time_label) # Overrides def get_state(self): return SceneState(self, ignore=[ self.selection_highlight, self.selection_rectangle, self.crosshair, ]) def restore_state(self, scene_state: SceneState): super().restore_state(scene_state) self.mobjects.insert(0, self.selection_highlight) def add(self, *mobjects: Mobject): super().add(*mobjects) self.regenerate_selection_search_set() def remove(self, *mobjects: Mobject): super().remove(*mobjects) self.regenerate_selection_search_set() # Related to selection def toggle_selection_mode(self): self.select_top_level_mobs = not self.select_top_level_mobs self.refresh_selection_scope() self.regenerate_selection_search_set() def get_selection_search_set(self) -> list[Mobject]: return self.selection_search_set def regenerate_selection_search_set(self): selectable = list(filter( lambda m: m not in self.unselectables, self.mobjects )) if self.select_top_level_mobs: self.selection_search_set = selectable else: self.selection_search_set = [ submob for mob in selectable for submob in mob.family_members_with_points() ] def refresh_selection_scope(self): curr = list(self.selection) if self.select_top_level_mobs: self.selection.set_submobjects([ mob for mob in self.mobjects if any(sm in mob.get_family() for sm in curr) ]) self.selection.refresh_bounding_box(recurse_down=True) else: self.selection.set_submobjects( extract_mobject_family_members( curr, exclude_pointless=True, ) ) def get_corner_dots(self, mobject: Mobject) -> Mobject: dots = DotCloud(**self.corner_dot_config) radius = float(self.corner_dot_config["radius"]) if mobject.get_depth() < 1e-2: vects = [DL, UL, UR, DR] else: vects = np.array(list(it.product(*3 * [[-1, 1]]))) dots.add_updater(lambda d: d.set_points([ mobject.get_corner(v) + v * radius for v in vects ])) return dots def get_highlight(self, mobject: Mobject) -> Mobject: if isinstance(mobject, VMobject) and mobject.has_points() and not self.select_top_level_mobs: length = max([mobject.get_height(), mobject.get_width()]) result = VHighlight( mobject, max_stroke_addition=min([50 * length, 10]), ) result.add_updater(lambda m: m.replace(mobject, stretch=True)) return result elif isinstance(mobject, DotCloud): return Mobject() else: return self.get_corner_dots(mobject) def add_to_selection(self, *mobjects: Mobject): mobs = list(filter( lambda m: m not in self.unselectables and m not in self.selection, mobjects )) if len(mobs) == 0: return self.selection.add(*mobs) for mob in mobs: mob.set_animating_status(True) def toggle_from_selection(self, *mobjects: Mobject): for mob in mobjects: if mob in self.selection: self.selection.remove(mob) mob.set_animating_status(False) mob.refresh_bounding_box() else: self.add_to_selection(mob) def clear_selection(self): for mob in self.selection: mob.set_animating_status(False) mob.refresh_bounding_box() self.selection.set_submobjects([]) def disable_interaction(self, *mobjects: Mobject): for mob in mobjects: for sm in mob.get_family(): self.unselectables.append(sm) self.regenerate_selection_search_set() def enable_interaction(self, *mobjects: Mobject): for mob in mobjects: for sm in mob.get_family(): if sm in self.unselectables: self.unselectables.remove(sm) # Functions for keyboard actions def copy_selection(self): names = [] shell = get_ipython() for mob in self.selection: name = str(id(mob)) if shell is None: continue for key, value in shell.user_ns.items(): if mob is value: name = key names.append(name) pyperclip.copy(", ".join(names)) def paste_selection(self): clipboard_str = pyperclip.paste() # Try pasting a mobject try: ids = map(int, clipboard_str.split(",")) mobs = map(self.id_to_mobject, ids) mob_copies = [m.copy() for m in mobs if m is not None] self.clear_selection() self.play(*( FadeIn(mc, run_time=0.5, scale=1.5) for mc in mob_copies )) self.add_to_selection(*mob_copies) return except ValueError: pass # Otherwise, treat as tex or text if set("\\^=+").intersection(clipboard_str): # Proxy to text for LaTeX try: new_mob = Tex(clipboard_str) except LatexError: return else: new_mob = Text(clipboard_str) self.clear_selection() self.add(new_mob) self.add_to_selection(new_mob) def delete_selection(self): self.remove(*self.selection) self.clear_selection() def enable_selection(self): self.is_selecting = True self.add(self.selection_rectangle) self.selection_rectangle.fixed_corner = self.frame.to_fixed_frame_point( self.mouse_point.get_center() ) def gather_new_selection(self): self.is_selecting = False if self.selection_rectangle in self.mobjects: self.remove(self.selection_rectangle) additions = [] for mob in reversed(self.get_selection_search_set()): if self.selection_rectangle.is_touching(mob): additions.append(mob) if self.selection_rectangle.get_arc_length() < 1e-2: break self.toggle_from_selection(*additions) def prepare_grab(self): mp = self.mouse_point.get_center() self.mouse_to_selection = mp - self.selection.get_center() self.is_grabbing = True def prepare_resizing(self, about_corner=False): center = self.selection.get_center() mp = self.mouse_point.get_center() if about_corner: self.scale_about_point = self.selection.get_corner(center - mp) else: self.scale_about_point = center self.scale_ref_vect = mp - self.scale_about_point self.scale_ref_width = self.selection.get_width() self.scale_ref_height = self.selection.get_height() def toggle_color_palette(self): if len(self.selection) == 0: return if self.color_palette not in self.mobjects: self.save_state() self.add(self.color_palette) else: self.remove(self.color_palette) def display_information(self, show=True): if show: self.add(self.information_label) else: self.remove(self.information_label) def group_selection(self): group = self.get_group(*self.selection) self.add(group) self.clear_selection() self.add_to_selection(group) def ungroup_selection(self): pieces = [] for mob in list(self.selection): self.remove(mob) pieces.extend(list(mob)) self.clear_selection() self.add(*pieces) self.add_to_selection(*pieces) def nudge_selection(self, vect: np.ndarray, large: bool = False): nudge = self.selection_nudge_size if large: nudge *= 10 self.selection.shift(nudge * vect) def save_selection_to_file(self): if len(self.selection) == 1: self.save_mobject_to_file(self.selection[0]) else: self.save_mobject_to_file(self.selection) # Key actions def on_key_press(self, symbol: int, modifiers: int) -> None: super().on_key_press(symbol, modifiers) char = chr(symbol) if char == SELECT_KEY and modifiers == 0: self.enable_selection() if char == UNSELECT_KEY: self.clear_selection() elif char in GRAB_KEYS and modifiers == 0: self.prepare_grab() elif char == RESIZE_KEY and modifiers in [0, SHIFT_MODIFIER]: self.prepare_resizing(about_corner=(modifiers == SHIFT_MODIFIER)) elif symbol == SHIFT_SYMBOL: if self.window.is_key_pressed(ord("t")): self.prepare_resizing(about_corner=True) elif char == COLOR_KEY and modifiers == 0: self.toggle_color_palette() elif char == INFORMATION_KEY and modifiers == 0: self.display_information() elif char == "c" and modifiers == COMMAND_MODIFIER: self.copy_selection() elif char == "v" and modifiers == COMMAND_MODIFIER: self.paste_selection() elif char == "x" and modifiers == COMMAND_MODIFIER: self.copy_selection() self.delete_selection() elif symbol == DELETE_SYMBOL: self.delete_selection() elif char == "a" and modifiers == COMMAND_MODIFIER: self.clear_selection() self.add_to_selection(*self.mobjects) elif char == "g" and modifiers == COMMAND_MODIFIER: self.group_selection() elif char == "g" and modifiers == COMMAND_MODIFIER | SHIFT_MODIFIER: self.ungroup_selection() elif char == "t" and modifiers == COMMAND_MODIFIER: self.toggle_selection_mode() elif char == "s" and modifiers == COMMAND_MODIFIER: self.save_selection_to_file() elif char == PAN_3D_KEY and modifiers == COMMAND_MODIFIER: self.copy_frame_anim_call() elif symbol in ARROW_SYMBOLS: self.nudge_selection( vect=[LEFT, UP, RIGHT, DOWN][ARROW_SYMBOLS.index(symbol)], large=(modifiers & SHIFT_MODIFIER), ) # Adding crosshair if char == CURSOR_KEY: if self.crosshair in self.mobjects: self.remove(self.crosshair) else: self.add(self.crosshair) if char == SELECT_KEY: self.add(self.crosshair) # Conditions for saving state if char in [GRAB_KEY, X_GRAB_KEY, Y_GRAB_KEY, RESIZE_KEY]: self.save_state() def on_key_release(self, symbol: int, modifiers: int) -> None: super().on_key_release(symbol, modifiers) if chr(symbol) == SELECT_KEY: self.gather_new_selection() if chr(symbol) in GRAB_KEYS: self.is_grabbing = False elif chr(symbol) == INFORMATION_KEY: self.display_information(False) elif symbol == SHIFT_SYMBOL and self.window.is_key_pressed(ord(RESIZE_KEY)): self.prepare_resizing(about_corner=False) # Mouse actions def handle_grabbing(self, point: Vect3): diff = point - self.mouse_to_selection if self.window.is_key_pressed(ord(GRAB_KEY)): self.selection.move_to(diff) elif self.window.is_key_pressed(ord(X_GRAB_KEY)): self.selection.set_x(diff[0]) elif self.window.is_key_pressed(ord(Y_GRAB_KEY)): self.selection.set_y(diff[1]) def handle_resizing(self, point: Vect3): if not hasattr(self, "scale_about_point"): return vect = point - self.scale_about_point if self.window.is_key_pressed(CTRL_SYMBOL): for i in (0, 1): scalar = vect[i] / self.scale_ref_vect[i] self.selection.rescale_to_fit( scalar * [self.scale_ref_width, self.scale_ref_height][i], dim=i, about_point=self.scale_about_point, stretch=True, ) else: scalar = get_norm(vect) / get_norm(self.scale_ref_vect) self.selection.set_width( scalar * self.scale_ref_width, about_point=self.scale_about_point ) def handle_sweeping_selection(self, point: Vect3): mob = self.point_to_mobject( point, search_set=self.get_selection_search_set(), buff=SMALL_BUFF ) if mob is not None: self.add_to_selection(mob) def choose_color(self, point: Vect3): # Search through all mobject on the screen, not just the palette to_search = [ sm for mobject in self.mobjects for sm in mobject.family_members_with_points() if mobject not in self.unselectables ] mob = self.point_to_mobject(point, to_search) if mob is not None: self.selection.set_color(mob.get_color()) self.remove(self.color_palette) def on_mouse_motion(self, point: Vect3, d_point: Vect3) -> None: super().on_mouse_motion(point, d_point) self.crosshair.move_to(self.frame.to_fixed_frame_point(point)) if self.is_grabbing: self.handle_grabbing(point) elif self.window.is_key_pressed(ord(RESIZE_KEY)): self.handle_resizing(point) elif self.window.is_key_pressed(ord(SELECT_KEY)) and self.window.is_key_pressed(SHIFT_SYMBOL): self.handle_sweeping_selection(point) def on_mouse_drag( self, point: Vect3, d_point: Vect3, buttons: int, modifiers: int ) -> None: super().on_mouse_drag(point, d_point, buttons, modifiers) self.crosshair.move_to(self.frame.to_fixed_frame_point(point)) def on_mouse_release(self, point: Vect3, button: int, mods: int) -> None: super().on_mouse_release(point, button, mods) if self.color_palette in self.mobjects: self.choose_color(point) else: self.clear_selection() # Copying code to recreate state def copy_frame_anim_call(self): frame = self.frame center = frame.get_center() height = frame.get_height() angles = frame.get_euler_angles() call = f"self.frame.animate.reorient" call += str(tuple((angles / DEGREES).astype(int))) if any(center != 0): call += f".move_to({list(np.round(center, 2))})" if height != FRAME_HEIGHT: call += ".set_height({:.2f})".format(height) pyperclip.copy(call)
manim_3b1b/manimlib/scene/scene.py
from __future__ import annotations from collections import OrderedDict import inspect import os import platform import pyperclip import random import time from functools import wraps from IPython.terminal import pt_inputhooks from IPython.terminal.embed import InteractiveShellEmbed from IPython.core.getipython import get_ipython import numpy as np from tqdm.auto import tqdm as ProgressDisplay from manimlib.animation.animation import prepare_animation from manimlib.animation.fading import VFadeInThenOut from manimlib.camera.camera import Camera from manimlib.camera.camera_frame import CameraFrame from manimlib.config import get_module from manimlib.constants import ARROW_SYMBOLS from manimlib.constants import DEFAULT_WAIT_TIME from manimlib.constants import COMMAND_MODIFIER from manimlib.constants import SHIFT_MODIFIER from manimlib.constants import RED from manimlib.event_handler import EVENT_DISPATCHER from manimlib.event_handler.event_type import EventType from manimlib.logger import log from manimlib.mobject.frame import FullScreenRectangle from manimlib.mobject.mobject import _AnimationBuilder from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Mobject from manimlib.mobject.mobject import Point from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.scene.scene_file_writer import SceneFileWriter from manimlib.utils.family_ops import extract_mobject_family_members from manimlib.utils.family_ops import recursive_mobject_remove from manimlib.utils.iterables import batch_by_property from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable from manimlib.typing import Vect3 from PIL.Image import Image from manimlib.animation.animation import Animation PAN_3D_KEY = 'd' FRAME_SHIFT_KEY = 'f' RESET_FRAME_KEY = 'r' QUIT_KEY = 'q' class Scene(object): random_seed: int = 0 pan_sensitivity: float = 0.5 scroll_sensitivity: float = 20 drag_to_pan: bool = True max_num_saved_states: int = 50 default_camera_config: dict = dict() default_window_config: dict = dict() default_file_writer_config: dict = dict() samples = 0 # Euler angles, in degrees default_frame_orientation = (0, 0) def __init__( self, window_config: dict = dict(), camera_config: dict = dict(), file_writer_config: dict = dict(), skip_animations: bool = False, always_update_mobjects: bool = False, start_at_animation_number: int | None = None, end_at_animation_number: int | None = None, leave_progress_bars: bool = False, preview: bool = True, presenter_mode: bool = False, show_animation_progress: bool = False, embed_exception_mode: str = "", embed_error_sound: bool = False, ): self.skip_animations = skip_animations self.always_update_mobjects = always_update_mobjects self.start_at_animation_number = start_at_animation_number self.end_at_animation_number = end_at_animation_number self.leave_progress_bars = leave_progress_bars self.preview = preview self.presenter_mode = presenter_mode self.show_animation_progress = show_animation_progress self.embed_exception_mode = embed_exception_mode self.embed_error_sound = embed_error_sound self.camera_config = {**self.default_camera_config, **camera_config} self.window_config = {**self.default_window_config, **window_config} for config in self.camera_config, self.window_config: config["samples"] = self.samples self.file_writer_config = {**self.default_file_writer_config, **file_writer_config} # Initialize window, if applicable if self.preview: from manimlib.window import Window self.window = Window(scene=self, **self.window_config) self.camera_config["window"] = self.window self.camera_config["fps"] = 30 # Where's that 30 from? else: self.window = None # Core state of the scene self.camera: Camera = Camera(**self.camera_config) self.frame: CameraFrame = self.camera.frame self.frame.reorient(*self.default_frame_orientation) self.frame.make_orientation_default() self.file_writer = SceneFileWriter(self, **self.file_writer_config) self.mobjects: list[Mobject] = [self.camera.frame] self.render_groups: list[Mobject] = [] self.id_to_mobject_map: dict[int, Mobject] = dict() self.num_plays: int = 0 self.time: float = 0 self.skip_time: float = 0 self.original_skipping_status: bool = self.skip_animations self.checkpoint_states: dict[str, list[tuple[Mobject, Mobject]]] = dict() self.undo_stack = [] self.redo_stack = [] if self.start_at_animation_number is not None: self.skip_animations = True if self.file_writer.has_progress_display(): self.show_animation_progress = False # Items associated with interaction self.mouse_point = Point() self.mouse_drag_point = Point() self.hold_on_wait = self.presenter_mode self.quit_interaction = False # Much nicer to work with deterministic scenes if self.random_seed is not None: random.seed(self.random_seed) np.random.seed(self.random_seed) def __str__(self) -> str: return self.__class__.__name__ def run(self) -> None: self.virtual_animation_start_time: float = 0 self.real_animation_start_time: float = time.time() self.file_writer.begin() self.setup() try: self.construct() self.interact() except EndScene: pass except KeyboardInterrupt: # Get rid keyboard interupt symbols print("", end="\r") self.file_writer.ended_with_interrupt = True self.tear_down() def setup(self) -> None: """ This is meant to be implement by any scenes which are comonly subclassed, and have some common setup involved before the construct method is called. """ pass def construct(self) -> None: # Where all the animation happens # To be implemented in subclasses pass def tear_down(self) -> None: self.stop_skipping() self.file_writer.finish() if self.window: self.window.destroy() self.window = None def interact(self) -> None: """ If there is a window, enter a loop which updates the frame while under the hood calling the pyglet event loop """ if self.window is None: return log.info( "\nTips: Using the keys `d`, `f`, or `z` " + "you can interact with the scene. " + "Press `command + q` or `esc` to quit" ) self.skip_animations = False while not self.is_window_closing(): self.update_frame(1 / self.camera.fps) def embed( self, close_scene_on_exit: bool = True, show_animation_progress: bool = False, ) -> None: if not self.preview: return # Embed is only relevant with a preview self.stop_skipping() self.update_frame() self.save_state() self.show_animation_progress = show_animation_progress # Create embedded IPython terminal to be configured shell = InteractiveShellEmbed.instance() # Use the locals namespace of the caller caller_frame = inspect.currentframe().f_back local_ns = dict(caller_frame.f_locals) # Add a few custom shortcuts local_ns.update( play=self.play, wait=self.wait, add=self.add, remove=self.remove, clear=self.clear, save_state=self.save_state, undo=self.undo, redo=self.redo, i2g=self.i2g, i2m=self.i2m, checkpoint_paste=self.checkpoint_paste, ) # Enables gui interactions during the embed def inputhook(context): while not context.input_is_ready(): if not self.is_window_closing(): self.update_frame(dt=0) if self.is_window_closing(): shell.ask_exit() pt_inputhooks.register("manim", inputhook) shell.enable_gui("manim") # This is hacky, but there's an issue with ipython which is that # when you define lambda's or list comprehensions during a shell session, # they are not aware of local variables in the surrounding scope. Because # That comes up a fair bit during scene construction, to get around this, # we (admittedly sketchily) update the global namespace to match the local # namespace, since this is just a shell session anyway. shell.events.register( "pre_run_cell", lambda: shell.user_global_ns.update(shell.user_ns) ) # Operation to run after each ipython command def post_cell_func(): if not self.is_window_closing(): self.update_frame(dt=0, ignore_skipping=True) self.save_state() shell.events.register("post_run_cell", post_cell_func) # Flash border, and potentially play sound, on exceptions def custom_exc(shell, etype, evalue, tb, tb_offset=None): # still show the error don't just swallow it shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset) if self.embed_error_sound: os.system("printf '\a'") rect = FullScreenRectangle().set_stroke(RED, 30).set_fill(opacity=0) rect.fix_in_frame() self.play(VFadeInThenOut(rect, run_time=0.5)) shell.set_custom_exc((Exception,), custom_exc) # Set desired exception mode shell.magic(f"xmode {self.embed_exception_mode}") # Launch shell shell( local_ns=local_ns, # Pretend like we're embeding in the caller function, not here stack_depth=2, # Specify that the present module is the caller's, not here module=get_module(caller_frame.f_globals["__file__"]) ) # End scene when exiting an embed if close_scene_on_exit: raise EndScene() # Only these methods should touch the camera def get_image(self) -> Image: if self.window is not None: self.camera.use_window_fbo(False) self.camera.capture(*self.render_groups) image = self.camera.get_image() if self.window is not None: self.camera.use_window_fbo(True) return image def show(self) -> None: self.update_frame(ignore_skipping=True) self.get_image().show() def update_frame(self, dt: float = 0, ignore_skipping: bool = False) -> None: self.increment_time(dt) self.update_mobjects(dt) if self.skip_animations and not ignore_skipping: return if self.is_window_closing(): raise EndScene() if self.window: self.window.clear() self.camera.capture(*self.render_groups) if self.window: self.window.swap_buffers() vt = self.time - self.virtual_animation_start_time rt = time.time() - self.real_animation_start_time if rt < vt: self.update_frame(0) def emit_frame(self) -> None: if not self.skip_animations: self.file_writer.write_frame(self.camera) # Related to updating def update_mobjects(self, dt: float) -> None: for mobject in self.mobjects: mobject.update(dt) def should_update_mobjects(self) -> bool: return self.always_update_mobjects or any([ len(mob.get_family_updaters()) > 0 for mob in self.mobjects ]) def has_time_based_updaters(self) -> bool: return any([ sm.has_time_based_updater() for mob in self.mobjects() for sm in mob.get_family() ]) # Related to time def get_time(self) -> float: return self.time def increment_time(self, dt: float) -> None: self.time += dt # Related to internal mobject organization def get_top_level_mobjects(self) -> list[Mobject]: # Return only those which are not in the family # of another mobject from the scene mobjects = self.get_mobjects() families = [m.get_family() for m in mobjects] def is_top_level(mobject): num_families = sum([ (mobject in family) for family in families ]) return num_families == 1 return list(filter(is_top_level, mobjects)) def get_mobject_family_members(self) -> list[Mobject]: return extract_mobject_family_members(self.mobjects) def assemble_render_groups(self): """ Rendering can be more efficient when mobjects of the same type are grouped together, so this function creates Groups of all clusters of adjacent Mobjects in the scene """ batches = batch_by_property( self.mobjects, lambda m: str(type(m)) + str(m.get_uniforms()) ) for group in self.render_groups: group.clear() self.render_groups = [ batch[0].get_group_class()(*batch) for batch, key in batches ] def affects_mobject_list(func: Callable): @wraps(func) def wrapper(self, *args, **kwargs): func(self, *args, **kwargs) self.assemble_render_groups() return self return wrapper @affects_mobject_list def add(self, *new_mobjects: Mobject): """ Mobjects will be displayed, from background to foreground in the order with which they are added. """ self.remove(*new_mobjects) self.mobjects += new_mobjects self.id_to_mobject_map.update({ id(sm): sm for m in new_mobjects for sm in m.get_family() }) return self def add_mobjects_among(self, values: Iterable): """ This is meant mostly for quick prototyping, e.g. to add all mobjects defined up to a point, call self.add_mobjects_among(locals().values()) """ self.add(*filter( lambda m: isinstance(m, Mobject), values )) return self @affects_mobject_list def replace(self, mobject: Mobject, *replacements: Mobject): if mobject in self.mobjects: index = self.mobjects.index(mobject) self.mobjects = [ *self.mobjects[:index], *replacements, *self.mobjects[index + 1:] ] return self @affects_mobject_list def remove(self, *mobjects_to_remove: Mobject): """ Removes anything in mobjects from scenes mobject list, but in the event that one of the items to be removed is a member of the family of an item in mobject_list, the other family members are added back into the list. For example, if the scene includes Group(m1, m2, m3), and we call scene.remove(m1), the desired behavior is for the scene to then include m2 and m3 (ungrouped). """ to_remove = set(extract_mobject_family_members(mobjects_to_remove)) new_mobjects, _ = recursive_mobject_remove(self.mobjects, to_remove) self.mobjects = new_mobjects def bring_to_front(self, *mobjects: Mobject): self.add(*mobjects) return self @affects_mobject_list def bring_to_back(self, *mobjects: Mobject): self.remove(*mobjects) self.mobjects = list(mobjects) + self.mobjects return self @affects_mobject_list def clear(self): self.mobjects = [] return self def get_mobjects(self) -> list[Mobject]: return list(self.mobjects) def get_mobject_copies(self) -> list[Mobject]: return [m.copy() for m in self.mobjects] def point_to_mobject( self, point: np.ndarray, search_set: Iterable[Mobject] | None = None, buff: float = 0 ) -> Mobject | None: """ E.g. if clicking on the scene, this returns the top layer mobject under a given point """ if search_set is None: search_set = self.mobjects for mobject in reversed(search_set): if mobject.is_point_touching(point, buff=buff): return mobject return None def get_group(self, *mobjects): if all(isinstance(m, VMobject) for m in mobjects): return VGroup(*mobjects) else: return Group(*mobjects) def id_to_mobject(self, id_value): return self.id_to_mobject_map[id_value] def ids_to_group(self, *id_values): return self.get_group(*filter( lambda x: x is not None, map(self.id_to_mobject, id_values) )) def i2g(self, *id_values): return self.ids_to_group(*id_values) def i2m(self, id_value): return self.id_to_mobject(id_value) # Related to skipping def update_skipping_status(self) -> None: if self.start_at_animation_number is not None: if self.num_plays == self.start_at_animation_number: self.skip_time = self.time if not self.original_skipping_status: self.stop_skipping() if self.end_at_animation_number is not None: if self.num_plays >= self.end_at_animation_number: raise EndScene() def stop_skipping(self) -> None: self.virtual_animation_start_time = self.time self.skip_animations = False # Methods associated with running animations def get_time_progression( self, run_time: float, n_iterations: int | None = None, desc: str = "", override_skip_animations: bool = False ) -> list[float] | np.ndarray | ProgressDisplay: if self.skip_animations and not override_skip_animations: return [run_time] times = np.arange(0, run_time, 1 / self.camera.fps) self.file_writer.set_progress_display_description(sub_desc=desc) if self.show_animation_progress: return ProgressDisplay( times, total=n_iterations, leave=self.leave_progress_bars, ascii=True if platform.system() == 'Windows' else None, desc=desc, bar_format="{l_bar} {n_fmt:3}/{total_fmt:3} {rate_fmt}{postfix}", ) else: return times def get_run_time(self, animations: Iterable[Animation]) -> float: return np.max([animation.get_run_time() for animation in animations]) def get_animation_time_progression( self, animations: Iterable[Animation] ) -> list[float] | np.ndarray | ProgressDisplay: animations = list(animations) run_time = self.get_run_time(animations) description = f"{self.num_plays} {animations[0]}" if len(animations) > 1: description += ", etc." time_progression = self.get_time_progression(run_time, desc=description) return time_progression def get_wait_time_progression( self, duration: float, stop_condition: Callable[[], bool] | None = None ) -> list[float] | np.ndarray | ProgressDisplay: kw = {"desc": f"{self.num_plays} Waiting"} if stop_condition is not None: kw["n_iterations"] = -1 # So it doesn't show % progress kw["override_skip_animations"] = True return self.get_time_progression(duration, **kw) def pre_play(self): if self.presenter_mode and self.num_plays == 0: self.hold_loop() self.update_skipping_status() if not self.skip_animations: self.file_writer.begin_animation() if self.window: self.real_animation_start_time = time.time() self.virtual_animation_start_time = self.time def post_play(self): if not self.skip_animations: self.file_writer.end_animation() if self.skip_animations and self.window is not None: # Show some quick frames along the way self.update_frame(dt=0, ignore_skipping=True) self.num_plays += 1 def begin_animations(self, animations: Iterable[Animation]) -> None: for animation in animations: animation.begin() # Anything animated that's not already in the # scene gets added to the scene. Note, for # animated mobjects that are in the family of # those on screen, this can result in a restructuring # of the scene.mobjects list, which is usually desired. if animation.mobject not in self.mobjects: self.add(animation.mobject) def progress_through_animations(self, animations: Iterable[Animation]) -> None: last_t = 0 for t in self.get_animation_time_progression(animations): dt = t - last_t last_t = t for animation in animations: animation.update_mobjects(dt) alpha = t / animation.run_time animation.interpolate(alpha) self.update_frame(dt) self.emit_frame() def finish_animations(self, animations: Iterable[Animation]) -> None: for animation in animations: animation.finish() animation.clean_up_from_scene(self) if self.skip_animations: self.update_mobjects(self.get_run_time(animations)) else: self.update_mobjects(0) @affects_mobject_list def play( self, *proto_animations: Animation | _AnimationBuilder, run_time: float | None = None, rate_func: Callable[[float], float] | None = None, lag_ratio: float | None = None, ) -> None: if len(proto_animations) == 0: log.warning("Called Scene.play with no animations") return animations = list(map(prepare_animation, proto_animations)) for anim in animations: anim.update_rate_info(run_time, rate_func, lag_ratio) self.pre_play() self.begin_animations(animations) self.progress_through_animations(animations) self.finish_animations(animations) self.post_play() def wait( self, duration: float = DEFAULT_WAIT_TIME, stop_condition: Callable[[], bool] = None, note: str = None, ignore_presenter_mode: bool = False ): self.pre_play() self.update_mobjects(dt=0) # Any problems with this? if self.presenter_mode and not self.skip_animations and not ignore_presenter_mode: if note: log.info(note) self.hold_loop() else: time_progression = self.get_wait_time_progression(duration, stop_condition) last_t = 0 for t in time_progression: dt = t - last_t last_t = t self.update_frame(dt) self.emit_frame() if stop_condition is not None and stop_condition(): break self.post_play() def hold_loop(self): while self.hold_on_wait: self.update_frame(dt=1 / self.camera.fps) self.hold_on_wait = True def wait_until( self, stop_condition: Callable[[], bool], max_time: float = 60 ): self.wait(max_time, stop_condition=stop_condition) def force_skipping(self): self.original_skipping_status = self.skip_animations self.skip_animations = True return self def revert_to_original_skipping_status(self): if hasattr(self, "original_skipping_status"): self.skip_animations = self.original_skipping_status return self def add_sound( self, sound_file: str, time_offset: float = 0, gain: float | None = None, gain_to_background: float | None = None ): if self.skip_animations: return time = self.get_time() + time_offset self.file_writer.add_sound(sound_file, time, gain, gain_to_background) # Helpers for interactive development def get_state(self) -> SceneState: return SceneState(self) @affects_mobject_list def restore_state(self, scene_state: SceneState): scene_state.restore_scene(self) def save_state(self) -> None: if not self.preview: return state = self.get_state() if self.undo_stack and state.mobjects_match(self.undo_stack[-1]): return self.redo_stack = [] self.undo_stack.append(state) if len(self.undo_stack) > self.max_num_saved_states: self.undo_stack.pop(0) def undo(self): if self.undo_stack: self.redo_stack.append(self.get_state()) self.restore_state(self.undo_stack.pop()) def redo(self): if self.redo_stack: self.undo_stack.append(self.get_state()) self.restore_state(self.redo_stack.pop()) def checkpoint_paste( self, skip: bool = False, record: bool = False, progress_bar: bool = True ): """ Used during interactive development to run (or re-run) a block of scene code. If the copied selection starts with a comment, this will revert to the state of the scene the first time this function was called on a block of code starting with that comment. """ shell = get_ipython() if shell is None or self.window is None: raise Exception( "Scene.checkpoint_paste cannot be called outside of " + "an ipython shell" ) pasted = pyperclip.paste() line0 = pasted.lstrip().split("\n")[0] if line0.startswith("#"): if line0 not in self.checkpoint_states: self.checkpoint(line0) else: self.revert_to_checkpoint(line0) prev_skipping = self.skip_animations self.skip_animations = skip prev_progress = self.show_animation_progress self.show_animation_progress = progress_bar if record: self.camera.use_window_fbo(False) self.file_writer.begin_insert() shell.run_cell(pasted) if record: self.file_writer.end_insert() self.camera.use_window_fbo(True) self.skip_animations = prev_skipping self.show_animation_progress = prev_progress def checkpoint(self, key: str): self.checkpoint_states[key] = self.get_state() def revert_to_checkpoint(self, key: str): if key not in self.checkpoint_states: log.error(f"No checkpoint at {key}") return all_keys = list(self.checkpoint_states.keys()) index = all_keys.index(key) for later_key in all_keys[index + 1:]: self.checkpoint_states.pop(later_key) self.restore_state(self.checkpoint_states[key]) def clear_checkpoints(self): self.checkpoint_states = dict() def save_mobject_to_file(self, mobject: Mobject, file_path: str | None = None) -> None: if file_path is None: file_path = self.file_writer.get_saved_mobject_path(mobject) if file_path is None: return mobject.save_to_file(file_path) def load_mobject(self, file_name): if os.path.exists(file_name): path = file_name else: directory = self.file_writer.get_saved_mobject_directory() path = os.path.join(directory, file_name) return Mobject.load(path) def is_window_closing(self): return self.window and (self.window.is_closing or self.quit_interaction) # Event handling def on_mouse_motion( self, point: Vect3, d_point: Vect3 ) -> None: assert(self.window is not None) self.mouse_point.move_to(point) event_data = {"point": point, "d_point": d_point} propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseMotionEvent, **event_data) if propagate_event is not None and propagate_event is False: return frame = self.camera.frame # Handle perspective changes if self.window.is_key_pressed(ord(PAN_3D_KEY)): ff_d_point = frame.to_fixed_frame_point(d_point, relative=True) ff_d_point *= self.pan_sensitivity frame.increment_theta(-ff_d_point[0]) frame.increment_phi(ff_d_point[1]) # Handle frame movements elif self.window.is_key_pressed(ord(FRAME_SHIFT_KEY)): frame.shift(-d_point) def on_mouse_drag( self, point: Vect3, d_point: Vect3, buttons: int, modifiers: int ) -> None: self.mouse_drag_point.move_to(point) if self.drag_to_pan: self.frame.shift(-d_point) event_data = {"point": point, "d_point": d_point, "buttons": buttons, "modifiers": modifiers} propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseDragEvent, **event_data) if propagate_event is not None and propagate_event is False: return def on_mouse_press( self, point: Vect3, button: int, mods: int ) -> None: self.mouse_drag_point.move_to(point) event_data = {"point": point, "button": button, "mods": mods} propagate_event = EVENT_DISPATCHER.dispatch(EventType.MousePressEvent, **event_data) if propagate_event is not None and propagate_event is False: return def on_mouse_release( self, point: Vect3, button: int, mods: int ) -> None: event_data = {"point": point, "button": button, "mods": mods} propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseReleaseEvent, **event_data) if propagate_event is not None and propagate_event is False: return def on_mouse_scroll( self, point: Vect3, offset: Vect3, x_pixel_offset: float, y_pixel_offset: float ) -> None: event_data = {"point": point, "offset": offset} propagate_event = EVENT_DISPATCHER.dispatch(EventType.MouseScrollEvent, **event_data) if propagate_event is not None and propagate_event is False: return rel_offset = y_pixel_offset / self.camera.get_pixel_height() self.frame.scale( 1 - self.scroll_sensitivity * rel_offset, about_point=point ) def on_key_release( self, symbol: int, modifiers: int ) -> None: event_data = {"symbol": symbol, "modifiers": modifiers} propagate_event = EVENT_DISPATCHER.dispatch(EventType.KeyReleaseEvent, **event_data) if propagate_event is not None and propagate_event is False: return def on_key_press( self, symbol: int, modifiers: int ) -> None: try: char = chr(symbol) except OverflowError: log.warning("The value of the pressed key is too large.") return event_data = {"symbol": symbol, "modifiers": modifiers} propagate_event = EVENT_DISPATCHER.dispatch(EventType.KeyPressEvent, **event_data) if propagate_event is not None and propagate_event is False: return if char == RESET_FRAME_KEY: self.play(self.camera.frame.animate.to_default_state()) elif char == "z" and modifiers == COMMAND_MODIFIER: self.undo() elif char == "z" and modifiers == COMMAND_MODIFIER | SHIFT_MODIFIER: self.redo() # command + q elif char == QUIT_KEY and modifiers == COMMAND_MODIFIER: self.quit_interaction = True # Space or right arrow elif char == " " or symbol == ARROW_SYMBOLS[2]: self.hold_on_wait = False def on_resize(self, width: int, height: int) -> None: pass def on_show(self) -> None: pass def on_hide(self) -> None: pass def on_close(self) -> None: pass class SceneState(): def __init__(self, scene: Scene, ignore: list[Mobject] | None = None): self.time = scene.time self.num_plays = scene.num_plays self.mobjects_to_copies = OrderedDict.fromkeys(scene.mobjects) if ignore: for mob in ignore: self.mobjects_to_copies.pop(mob, None) last_m2c = scene.undo_stack[-1].mobjects_to_copies if scene.undo_stack else dict() for mob in self.mobjects_to_copies: # If it hasn't changed since the last state, just point to the # same copy as before if mob in last_m2c and last_m2c[mob].looks_identical(mob): self.mobjects_to_copies[mob] = last_m2c[mob] else: self.mobjects_to_copies[mob] = mob.copy() def __eq__(self, state: SceneState): return all(( self.time == state.time, self.num_plays == state.num_plays, self.mobjects_to_copies == state.mobjects_to_copies )) def mobjects_match(self, state: SceneState): return self.mobjects_to_copies == state.mobjects_to_copies def n_changes(self, state: SceneState): m2c = state.mobjects_to_copies return sum( 1 - int(mob in m2c and mob.looks_identical(m2c[mob])) for mob in self.mobjects_to_copies ) def restore_scene(self, scene: Scene): scene.time = self.time scene.num_plays = self.num_plays scene.mobjects = [ mob.become(mob_copy) for mob, mob_copy in self.mobjects_to_copies.items() ] class EndScene(Exception): pass class ThreeDScene(Scene): samples = 4 default_frame_orientation = (-30, 70) always_depth_test = True def add(self, *mobjects, set_depth_test: bool = True): for mob in mobjects: if set_depth_test and not mob.is_fixed_in_frame() and self.always_depth_test: mob.apply_depth_test() super().add(*mobjects)
manim_3b1b/manimlib/scene/scene_file_writer.py
from __future__ import annotations import os import platform import shutil import subprocess as sp import sys import numpy as np from pydub import AudioSegment from tqdm.auto import tqdm as ProgressDisplay from manimlib.constants import FFMPEG_BIN from manimlib.logger import log from manimlib.mobject.mobject import Mobject from manimlib.utils.file_ops import add_extension_if_not_present from manimlib.utils.file_ops import get_sorted_integer_files from manimlib.utils.file_ops import guarantee_existence from manimlib.utils.sounds import get_full_sound_file_path from typing import TYPE_CHECKING if TYPE_CHECKING: from PIL.Image import Image from manimlib.camera.camera import Camera from manimlib.scene.scene import Scene class SceneFileWriter(object): def __init__( self, scene: Scene, write_to_movie: bool = False, break_into_partial_movies: bool = False, save_pngs: bool = False, # TODO, this currently does nothing png_mode: str = "RGBA", save_last_frame: bool = False, movie_file_extension: str = ".mp4", # What python file is generating this scene input_file_path: str = "", # Where should this be written output_directory: str | None = None, file_name: str | None = None, subdirectory_for_videos: bool = False, open_file_upon_completion: bool = False, show_file_location_upon_completion: bool = False, quiet: bool = False, total_frames: int = 0, progress_description_len: int = 40, video_codec: str = "libx264", pixel_format: str = "yuv420p", saturation: float = 1.0, gamma: float = 1.0, ): self.scene: Scene = scene self.write_to_movie = write_to_movie self.break_into_partial_movies = break_into_partial_movies self.save_pngs = save_pngs self.png_mode = png_mode self.save_last_frame = save_last_frame self.movie_file_extension = movie_file_extension self.input_file_path = input_file_path self.output_directory = output_directory self.file_name = file_name self.open_file_upon_completion = open_file_upon_completion self.subdirectory_for_videos = subdirectory_for_videos self.show_file_location_upon_completion = show_file_location_upon_completion self.quiet = quiet self.total_frames = total_frames self.progress_description_len = progress_description_len self.video_codec = video_codec self.pixel_format = pixel_format self.saturation = saturation self.gamma = gamma # State during file writing self.writing_process: sp.Popen | None = None self.progress_display: ProgressDisplay | None = None self.ended_with_interrupt: bool = False self.init_output_directories() self.init_audio() # Output directories and files def init_output_directories(self) -> None: out_dir = self.output_directory or "" scene_name = self.file_name or self.get_default_scene_name() if self.save_last_frame: image_dir = guarantee_existence(os.path.join(out_dir, "images")) image_file = add_extension_if_not_present(scene_name, ".png") self.image_file_path = os.path.join(image_dir, image_file) if self.write_to_movie: if self.subdirectory_for_videos: movie_dir = guarantee_existence(os.path.join(out_dir, "videos")) else: movie_dir = guarantee_existence(out_dir) movie_file = add_extension_if_not_present(scene_name, self.movie_file_extension) self.movie_file_path = os.path.join(movie_dir, movie_file) if self.break_into_partial_movies: self.partial_movie_directory = guarantee_existence(os.path.join( movie_dir, "partial_movie_files", scene_name, )) # A place to save mobjects self.saved_mobject_directory = os.path.join( out_dir, "mobjects", str(self.scene) ) def get_default_module_directory(self) -> str: path, _ = os.path.splitext(self.input_file_path) if path.startswith("_"): path = path[1:] return path def get_default_scene_name(self) -> str: name = str(self.scene) saan = self.scene.start_at_animation_number eaan = self.scene.end_at_animation_number if saan is not None: name += f"_{saan}" if eaan is not None: name += f"_{eaan}" return name def get_resolution_directory(self) -> str: pixel_height = self.scene.camera.pixel_height fps = self.scene.camera.fps return "{}p{}".format( pixel_height, fps ) # Directory getters def get_image_file_path(self) -> str: return self.image_file_path def get_next_partial_movie_path(self) -> str: result = os.path.join( self.partial_movie_directory, "{:05}{}".format( self.scene.num_plays, self.movie_file_extension, ) ) return result def get_movie_file_path(self) -> str: return self.movie_file_path def get_saved_mobject_directory(self) -> str: return guarantee_existence(self.saved_mobject_directory) def get_saved_mobject_path(self, mobject: Mobject) -> str | None: directory = self.get_saved_mobject_directory() files = os.listdir(directory) default_name = str(mobject) + "_0.mob" index = 0 while default_name in files: default_name = default_name.replace(str(index), str(index + 1)) index += 1 if platform.system() == 'Darwin': cmds = [ "osascript", "-e", f""" set chosenfile to (choose file name default name "{default_name}" default location "{directory}") POSIX path of chosenfile """, ] process = sp.Popen(cmds, stdout=sp.PIPE) file_path = process.stdout.read().decode("utf-8").split("\n")[0] if not file_path: return else: user_name = input(f"Enter mobject file name (default is {default_name}): ") file_path = os.path.join(directory, user_name or default_name) if os.path.exists(file_path) or os.path.exists(file_path + ".mob"): if input(f"{file_path} already exists. Overwrite (y/n)? ") != "y": return if not file_path.endswith(".mob"): file_path = file_path + ".mob" return file_path # Sound def init_audio(self) -> None: self.includes_sound: bool = False def create_audio_segment(self) -> None: self.audio_segment = AudioSegment.silent() def add_audio_segment( self, new_segment: AudioSegment, time: float | None = None, gain_to_background: float | None = None ) -> None: if not self.includes_sound: self.includes_sound = True self.create_audio_segment() segment = self.audio_segment curr_end = segment.duration_seconds if time is None: time = curr_end if time < 0: raise Exception("Adding sound at timestamp < 0") new_end = time + new_segment.duration_seconds diff = new_end - curr_end if diff > 0: segment = segment.append( AudioSegment.silent(int(np.ceil(diff * 1000))), crossfade=0, ) self.audio_segment = segment.overlay( new_segment, position=int(1000 * time), gain_during_overlay=gain_to_background, ) def add_sound( self, sound_file: str, time: float | None = None, gain: float | None = None, gain_to_background: float | None = None ) -> None: file_path = get_full_sound_file_path(sound_file) new_segment = AudioSegment.from_file(file_path) if gain: new_segment = new_segment.apply_gain(gain) self.add_audio_segment(new_segment, time, gain_to_background) # Writers def begin(self) -> None: if not self.break_into_partial_movies and self.write_to_movie: self.open_movie_pipe(self.get_movie_file_path()) def begin_animation(self) -> None: if self.break_into_partial_movies and self.write_to_movie: self.open_movie_pipe(self.get_next_partial_movie_path()) def end_animation(self) -> None: if self.break_into_partial_movies and self.write_to_movie: self.close_movie_pipe() def finish(self) -> None: if self.write_to_movie: if self.break_into_partial_movies: self.combine_movie_files() else: self.close_movie_pipe() if self.includes_sound: self.add_sound_to_video() self.print_file_ready_message(self.get_movie_file_path()) if self.save_last_frame: self.scene.update_frame(ignore_skipping=True) self.save_final_image(self.scene.get_image()) if self.should_open_file(): self.open_file() def open_movie_pipe(self, file_path: str) -> None: stem, ext = os.path.splitext(file_path) self.final_file_path = file_path self.temp_file_path = stem + "_temp" + ext fps = self.scene.camera.fps width, height = self.scene.camera.get_pixel_shape() vf_arg = 'vflip' if self.pixel_format.startswith("yuv"): vf_arg += f',eq=saturation={self.saturation}:gamma={self.gamma}' command = [ FFMPEG_BIN, '-y', # overwrite output file if it exists '-f', 'rawvideo', '-s', f'{width}x{height}', # size of one frame '-pix_fmt', 'rgba', '-r', str(fps), # frames per second '-i', '-', # The input comes from a pipe '-vf', vf_arg, '-an', # Tells FFMPEG not to expect any audio '-loglevel', 'error', ] if self.video_codec: command += ['-vcodec', self.video_codec] if self.pixel_format: command += ['-pix_fmt', self.pixel_format] command += [self.temp_file_path] self.writing_process = sp.Popen(command, stdin=sp.PIPE) if not self.quiet: self.progress_display = ProgressDisplay( range(self.total_frames), leave=False, ascii=True if platform.system() == 'Windows' else None, dynamic_ncols=True, ) self.set_progress_display_description() def use_fast_encoding(self): self.video_codec = "libx264rgb" self.pixel_format = "rgb32" def begin_insert(self): # Begin writing process self.write_to_movie = True self.init_output_directories() movie_path = self.get_movie_file_path() count = 0 while os.path.exists(name := movie_path.replace(".", f"_insert_{count}.")): count += 1 self.inserted_file_path = name self.open_movie_pipe(self.inserted_file_path) def end_insert(self): self.close_movie_pipe() self.write_to_movie = False self.print_file_ready_message(self.inserted_file_path) def has_progress_display(self): return self.progress_display is not None def set_progress_display_description(self, file: str = "", sub_desc: str = "") -> None: if self.progress_display is None: return desc_len = self.progress_description_len if not file: file = os.path.split(self.get_movie_file_path())[1] full_desc = f"{file} {sub_desc}" if len(full_desc) > desc_len: full_desc = full_desc[:desc_len - 3] + "..." else: full_desc += " " * (desc_len - len(full_desc)) self.progress_display.set_description(full_desc) def write_frame(self, camera: Camera) -> None: if self.write_to_movie: raw_bytes = camera.get_raw_fbo_data() self.writing_process.stdin.write(raw_bytes) if self.progress_display is not None: self.progress_display.update() def close_movie_pipe(self) -> None: self.writing_process.stdin.close() self.writing_process.wait() self.writing_process.terminate() if self.progress_display is not None: self.progress_display.close() if not self.ended_with_interrupt: shutil.move(self.temp_file_path, self.final_file_path) else: self.movie_file_path = self.temp_file_path def combine_movie_files(self) -> None: kwargs = { "remove_non_integer_files": True, "extension": self.movie_file_extension, } if self.scene.start_at_animation_number is not None: kwargs["min_index"] = self.scene.start_at_animation_number if self.scene.end_at_animation_number is not None: kwargs["max_index"] = self.scene.end_at_animation_number else: kwargs["remove_indices_greater_than"] = self.scene.num_plays - 1 partial_movie_files = get_sorted_integer_files( self.partial_movie_directory, **kwargs ) if len(partial_movie_files) == 0: log.warning("No animations in this scene") return # Write a file partial_file_list.txt containing all # partial movie files file_list = os.path.join( self.partial_movie_directory, "partial_movie_file_list.txt" ) with open(file_list, 'w') as fp: for pf_path in partial_movie_files: if os.name == 'nt': pf_path = pf_path.replace('\\', '/') fp.write(f"file \'{pf_path}\'\n") movie_file_path = self.get_movie_file_path() commands = [ FFMPEG_BIN, '-y', # overwrite output file if it exists '-f', 'concat', '-safe', '0', '-i', file_list, '-loglevel', 'error', '-c', 'copy', movie_file_path ] if not self.includes_sound: commands.insert(-1, '-an') combine_process = sp.Popen(commands) combine_process.wait() def add_sound_to_video(self) -> None: movie_file_path = self.get_movie_file_path() stem, ext = os.path.splitext(movie_file_path) sound_file_path = stem + ".wav" # Makes sure sound file length will match video file self.add_audio_segment(AudioSegment.silent(0)) self.audio_segment.export( sound_file_path, bitrate='312k', ) temp_file_path = stem + "_temp" + ext commands = [ FFMPEG_BIN, "-i", movie_file_path, "-i", sound_file_path, '-y', # overwrite output file if it exists "-c:v", "copy", "-c:a", "aac", "-b:a", "320k", # select video stream from first file "-map", "0:v:0", # select audio stream from second file "-map", "1:a:0", '-loglevel', 'error', # "-shortest", temp_file_path, ] sp.call(commands) shutil.move(temp_file_path, movie_file_path) os.remove(sound_file_path) def save_final_image(self, image: Image) -> None: file_path = self.get_image_file_path() image.save(file_path) self.print_file_ready_message(file_path) def print_file_ready_message(self, file_path: str) -> None: if not self.quiet: log.info(f"File ready at {file_path}") def should_open_file(self) -> bool: return any([ self.show_file_location_upon_completion, self.open_file_upon_completion, ]) def open_file(self) -> None: if self.quiet: curr_stdout = sys.stdout sys.stdout = open(os.devnull, "w") current_os = platform.system() file_paths = [] if self.save_last_frame: file_paths.append(self.get_image_file_path()) if self.write_to_movie: file_paths.append(self.get_movie_file_path()) for file_path in file_paths: if current_os == "Windows": os.startfile(file_path) else: commands = [] if current_os == "Linux": commands.append("xdg-open") elif current_os.startswith("CYGWIN"): commands.append("cygstart") else: # Assume macOS commands.append("open") if self.show_file_location_upon_completion: commands.append("-R") commands.append(file_path) FNULL = open(os.devnull, 'w') sp.call(commands, stdout=FNULL, stderr=sp.STDOUT) FNULL.close() if self.quiet: sys.stdout.close() sys.stdout = curr_stdout
manim_3b1b/manimlib/mobject/matrix.py
from __future__ import annotations import itertools as it import numpy as np from manimlib.constants import DEFAULT_MOBJECT_TO_MOBJECT_BUFFER from manimlib.constants import DOWN, LEFT, RIGHT, UP from manimlib.constants import WHITE from manimlib.mobject.numbers import DecimalNumber from manimlib.mobject.numbers import Integer from manimlib.mobject.shape_matchers import BackgroundRectangle from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence import numpy.typing as npt from manimlib.mobject.mobject import Mobject from manimlib.typing import ManimColor, Vect3, Self VECTOR_LABEL_SCALE_FACTOR = 0.8 def matrix_to_tex_string(matrix: npt.ArrayLike) -> str: matrix = np.array(matrix).astype("str") if matrix.ndim == 1: matrix = matrix.reshape((matrix.size, 1)) n_rows, n_cols = matrix.shape prefix = R"\left[ \begin{array}{%s}" % ("c" * n_cols) suffix = R"\end{array} \right]" rows = [ " & ".join(row) for row in matrix ] return prefix + R" \\ ".join(rows) + suffix def matrix_to_mobject(matrix: npt.ArrayLike) -> Tex: return Tex(matrix_to_tex_string(matrix)) def vector_coordinate_label( vector_mob: VMobject, integer_labels: bool = True, n_dim: int = 2, color: ManimColor = WHITE ) -> Matrix: vect = np.array(vector_mob.get_end()) if integer_labels: vect = np.round(vect).astype(int) vect = vect[:n_dim] vect = vect.reshape((n_dim, 1)) label = Matrix(vect, add_background_rectangles_to_entries=True) label.scale(VECTOR_LABEL_SCALE_FACTOR) shift_dir = np.array(vector_mob.get_end()) if shift_dir[0] >= 0: # Pointing right shift_dir -= label.get_left() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * LEFT else: # Pointing left shift_dir -= label.get_right() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * RIGHT label.shift(shift_dir) label.set_color(color) label.rect = BackgroundRectangle(label) label.add_to_back(label.rect) return label class Matrix(VMobject): def __init__( self, matrix: Sequence[Sequence[str | float | VMobject]], v_buff: float = 0.8, h_buff: float = 1.0, bracket_h_buff: float = 0.2, bracket_v_buff: float = 0.25, add_background_rectangles_to_entries: bool = False, include_background_rectangle: bool = False, element_alignment_corner: Vect3 = DOWN, **kwargs ): """ Matrix can either include numbers, tex_strings, or mobjects """ super().__init__() mob_matrix = self.matrix_to_mob_matrix(matrix, **kwargs) self.mob_matrix = mob_matrix self.organize_mob_matrix(mob_matrix, v_buff, h_buff, element_alignment_corner) self.elements = VGroup(*it.chain(*mob_matrix)) self.add(self.elements) self.add_brackets(bracket_v_buff, bracket_h_buff) self.center() if add_background_rectangles_to_entries: for mob in self.elements: mob.add_background_rectangle() if include_background_rectangle: self.add_background_rectangle() def element_to_mobject(self, element: str | float | VMobject, **config) -> VMobject: if isinstance(element, VMobject): return element return Tex(str(element), **config) def matrix_to_mob_matrix( self, matrix: Sequence[Sequence[str | float | VMobject]], **config ) -> list[list[VMobject]]: return [ [ self.element_to_mobject(item, **config) for item in row ] for row in matrix ] def organize_mob_matrix( self, matrix: list[list[VMobject]], v_buff: float, h_buff: float, aligned_corner: Vect3, ) -> Self: for i, row in enumerate(matrix): for j, elem in enumerate(row): mob = matrix[i][j] mob.move_to( i * v_buff * DOWN + j * h_buff * RIGHT, aligned_corner ) return self def add_brackets(self, v_buff: float, h_buff: float) -> Self: height = len(self.mob_matrix) brackets = Tex("".join(( R"\left[\begin{array}{c}", *height * [R"\quad \\"], R"\end{array}\right]", ))) brackets.set_height(self.get_height() + v_buff) l_bracket = brackets[:len(brackets) // 2] r_bracket = brackets[len(brackets) // 2:] l_bracket.next_to(self, LEFT, h_buff) r_bracket.next_to(self, RIGHT, h_buff) brackets.set_submobjects([l_bracket, r_bracket]) self.brackets = brackets self.add(*brackets) return self def get_columns(self) -> VGroup: return VGroup(*[ VGroup(*[row[i] for row in self.mob_matrix]) for i in range(len(self.mob_matrix[0])) ]) def get_rows(self) -> VGroup: return VGroup(*[ VGroup(*row) for row in self.mob_matrix ]) def set_column_colors(self, *colors: ManimColor) -> Self: columns = self.get_columns() for color, column in zip(colors, columns): column.set_color(color) return self def add_background_to_entries(self) -> Self: for mob in self.get_entries(): mob.add_background_rectangle() return self def get_mob_matrix(self) -> list[list[Mobject]]: return self.mob_matrix def get_entries(self) -> VGroup: return self.elements def get_brackets(self) -> VGroup: return self.brackets class DecimalMatrix(Matrix): def element_to_mobject(self, element: float, num_decimal_places: int = 1, **config) -> DecimalNumber: return DecimalNumber(element, num_decimal_places=num_decimal_places, **config) class IntegerMatrix(Matrix): def __init__( self, matrix: npt.ArrayLike, element_alignment_corner: Vect3 = UP, **kwargs ): super().__init__(matrix, element_alignment_corner=element_alignment_corner, **kwargs) def element_to_mobject(self, element: int, **config) -> Integer: return Integer(element, **config) class MobjectMatrix(Matrix): def element_to_mobject(self, element: VMobject, **config) -> VMobject: return element def get_det_text( matrix: Matrix, determinant: int | str | None = None, background_rect: bool = False, initial_scale_factor: int = 2 ) -> VGroup: parens = Tex("()") parens.scale(initial_scale_factor) parens.stretch_to_fit_height(matrix.get_height()) l_paren, r_paren = parens.split() l_paren.next_to(matrix, LEFT, buff=0.1) r_paren.next_to(matrix, RIGHT, buff=0.1) det = TexText("det") det.scale(initial_scale_factor) det.next_to(l_paren, LEFT, buff=0.1) if background_rect: det.add_background_rectangle() det_text = VGroup(det, l_paren, r_paren) if determinant is not None: eq = Tex("=") eq.next_to(r_paren, RIGHT, buff=0.1) result = Tex(str(determinant)) result.next_to(eq, RIGHT, buff=0.2) det_text.add(eq, result) return det_text
manim_3b1b/manimlib/mobject/value_tracker.py
from __future__ import annotations import numpy as np from manimlib.mobject.mobject import Mobject from manimlib.utils.iterables import listify from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import Self class ValueTracker(Mobject): """ Not meant to be displayed. Instead the position encodes some number, often one which another animation or continual_animation uses for its update function, and by treating it as a mobject it can still be animated and manipulated just like anything else. """ value_type: type = np.float64 def __init__( self, value: float | complex | np.ndarray = 0, **kwargs ): self.value = value super().__init__(**kwargs) def init_uniforms(self) -> None: super().init_uniforms() self.uniforms["value"] = np.array( listify(self.value), dtype=self.value_type, ) def get_value(self) -> float | complex | np.ndarray: result = self.uniforms["value"] if len(result) == 1: return result[0] return result def set_value(self, value: float | complex | np.ndarray) -> Self: self.uniforms["value"][:] = value return self def increment_value(self, d_value: float | complex) -> None: self.set_value(self.get_value() + d_value) class ExponentialValueTracker(ValueTracker): """ Operates just like ValueTracker, except it encodes the value as the exponential of a position coordinate, which changes how interpolation behaves """ def get_value(self) -> float | complex: return np.exp(ValueTracker.get_value(self)) def set_value(self, value: float | complex): return ValueTracker.set_value(self, np.log(value)) class ComplexValueTracker(ValueTracker): value_type: type = np.complex128
manim_3b1b/manimlib/mobject/__init__.py
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
14