A community-maintained Python framework for creating mathematical animations.
Adds config["assets_dir"]/CLI argument, documentation, and bug fix? (#649)
Jason Villanueva31d6ffb9d3f1
diff --git a/docs/source/examples/shapes_images_positions.rst b/docs/source/examples/shapes_images_positions.rstindex 8888db588..e66e3b46b 100644--- a/docs/source/examples/shapes_images_positions.rst+++ b/docs/source/examples/shapes_images_positions.rst@@ -51,6 +51,68 @@ Shapes, Images and Positionsself.wait()+.. manim:: ManimCELogo+ :save_last_frame:++ class ManimCELogo(Scene):+ def construct(self):+ logo_green = "#87c2a5"+ logo_blue = "#525893"+ logo_red = "#e07a5f"+ ds_m = MathTex(r"\mathbb{M}", z_index=20).scale(7)+ ds_m.shift(2.25*LEFT + 1.5*UP)+ circle = Circle(color=logo_green,+ fill_opacity=1,+ z_index=7)+ square = Square(color=logo_blue,+ fill_opacity=1,+ z_index=5)+ triangle = Triangle(color=logo_red,+ fill_opacity=1,+ z_index=3)+ circle.shift(LEFT)+ square.shift(UP)+ triangle.shift(RIGHT)+ self.add(triangle, square, circle, ds_m) # Order matters+ self.wait()++Download the resource for the following example `here <https://github.com/ManimCommunity/manim/blob/master/docs/source/_static/manim-logo-sidebar.svg>`_++.. manim:: ManimCELogoFromSVG++ class ManimCELogoFromSVG(Scene):+ def construct(self):+ v_image = SVGMobject(file_name="manim-logo-sidebar.svg")+ self.add(v_image)++ # Custom colors can be defined with hex strings+ logo_blue, logo_green, logo_red = "#525893", "#87C2A5", "#E07A5F"++ # An SVG file with multiple objects can be decomposed into+ # their subcomponents+ triangle = v_image.submobjects[0]+ square = v_image.submobjects[1]+ circle = v_image.submobjects[2]+ m = v_image.submobjects[3]++ self.play(+ ApplyMethod(triangle.set_fill, logo_red),+ ApplyMethod(square.set_fill, logo_blue),+ ApplyMethod(circle.set_fill, logo_green),+ ApplyMethod(m.set_fill, WHITE, opacity=1),+ )+ self.wait()++Download the resource for the following example `here <https://github.com/ManimCommunity/manim/blob/master/docs/source/_static/favicon.ico>`_++.. manim:: ManimCELogoFromImage+ :save_last_frame:++ class ManimCELogoFromImage(Scene):+ def construct(self):+ image = ImageMobject(filename_or_array="favicon.ico")+ self.add(image)+.. manim:: GradientImageFromArray:save_last_frame:diff --git a/docs/source/manim_directive.py b/docs/source/manim_directive.pyindex ff9678d6d..5ce1b1ec2 100644--- a/docs/source/manim_directive.py+++ b/docs/source/manim_directive.py@@ -197,6 +197,7 @@ class ManimDirective(Directive):config.images_dir = "{media_dir}/images"config.video_dir = "{media_dir}/videos/{quality}"output_file = f"{clsname}-{classnamedict[clsname]}"+ config.assets_dir = Path("_static")config_code = [f'config["frame_rate"] = {frame_rate}',diff --git a/manim/_config/default.cfg b/manim/_config/default.cfgindex 4ab92eddd..7647738f7 100644--- a/manim/_config/default.cfg+++ b/manim/_config/default.cfg@@ -74,6 +74,9 @@ media_dir = ./media# --log_dirlog_dir = {media_dir}/logs+# --assets_dir+assets_dir = ./+# the following do not have CLI arguments but depend on media_dirvideo_dir = {media_dir}/videos/{module_name}/{quality}images_dir = {media_dir}/images/{module_name}diff --git a/manim/_config/utils.py b/manim/_config/utils.pyindex f7ba1c981..84d8168df 100644--- a/manim/_config/utils.py+++ b/manim/_config/utils.py@@ -245,6 +245,7 @@ class ManimConfig(MutableMapping):"""_OPTS = {+ "assets_dir","background_color","background_opacity","custom_folders",@@ -523,6 +524,7 @@ class ManimConfig(MutableMapping):# str keysfor key in [+ "assets_dir","verbosity","media_dir","log_dir",@@ -1153,6 +1155,7 @@ class ManimConfig(MutableMapping):"""dirs = [+ "assets_dir","media_dir","video_dir","images_dir",@@ -1195,6 +1198,12 @@ class ManimConfig(MutableMapping):else:self._d.__setitem__(key, val)+ assets_dir = property(+ lambda self: self._d["assets_dir"],+ lambda self, val: self._set_dir("assets_dir", val),+ doc="Directory to locate video assets.",+ )+log_dir = property(lambda self: self._d["log_dir"],lambda self, val: self._set_dir("log_dir", val),diff --git a/manim/mobject/svg/svg_mobject.py b/manim/mobject/svg/svg_mobject.pyindex f40e8cfa5..dde7d5940 100644--- a/manim/mobject/svg/svg_mobject.py+++ b/manim/mobject/svg/svg_mobject.py@@ -12,6 +12,7 @@ import warningsfrom xml.dom import minidom+from ... import configfrom ...constants import *from ...mobject.geometry import Circlefrom ...mobject.geometry import Rectangle@@ -30,6 +31,47 @@ def string_to_numbers(num_string):class SVGMobject(VMobject):+ """A SVGMobject is a Vector Mobject constructed from an SVG (or XDV) file.++ SVGMobjects are constructed from the XML data within the SVG file+ structure. As such, subcomponents from the XML data can be accessed via+ the submobjects attribute. There is varying amounts of support for SVG+ elements, experiment with SVG files at your own peril.++ Examples+ --------++ .. code-block:: python++ class Sample(Scene):+ def construct(self):+ self.play(+ FadeIn(SVGMobject("manim-logo-sidebar.svg"))+ )++ Parameters+ --------+ file_name : :class:`str`+ The file's path name. When possible, the full path is preferred but a+ relative path may be used as well. Relative paths are relative to the+ directory specified by the `--assets_dir` command line argument.++ Other Parameters+ --------+ should_center : :class:`bool`+ Whether the SVGMobject should be centered to the origin. Defaults to `True`.+ height : :class:`float`+ Specify the final height of the SVG file. Defaults to 2 units.+ width : :class:`float`+ Specify the width the SVG file should occupy. Defaults to `None`.+ unpack_groups : :class:`bool`+ Whether the hierarchies of VGroups generated should be flattened. Defaults to `True`.+ stroke_width : :class:`float`+ The stroke width of the outer edge of an SVG path element. Defaults to `4`.+ fill_opacity : :class:`float`+ Specifies the opacity of the image. `1` is opaque, `0` is transparent. Defaults to `1`.+ """+CONFIG = {"should_center": True,"height": 2,@@ -50,13 +92,28 @@ class SVGMobject(VMobject):self.move_into_position()def ensure_valid_file(self):+ """Reads self.file_name and determines whether the given input file_name+ is valid.+ """if self.file_name is None:raise Exception("Must specify file for SVGMobject")++ if os.path.exists(self.file_name):+ self.file_path = self.file_name+ return++ relative = os.path.join(os.getcwd(), self.file_name)+ if os.path.exists(relative):+ self.file_path = relative+ return+possible_paths = [- os.path.join(os.path.join("assets", "svg_images"), self.file_name),- os.path.join(os.path.join("assets", "svg_images"), self.file_name + ".svg"),- os.path.join(os.path.join("assets", "svg_images"), self.file_name + ".xdv"),+ os.path.join(config.get_dir("assets_dir"), self.file_name),+ os.path.join(config.get_dir("assets_dir"), self.file_name + ".svg"),+ os.path.join(config.get_dir("assets_dir"), self.file_name + ".xdv"),self.file_name,+ self.file_name + ".svg",+ self.file_name + ".xdv",]for path in possible_paths:if os.path.exists(path):@@ -68,6 +125,10 @@ class SVGMobject(VMobject):raise IOError(error)def generate_points(self):+ """Called by the Mobject abstract base class. Responsible for generating+ the SVGMobject's points from XML tags, populating self.mobjects, and+ any submobjects within self.mobjects.+ """doc = minidom.parse(self.file_path)self.ref_to_element = {}for svg in doc.getElementsByTagName("svg"):@@ -79,6 +140,18 @@ class SVGMobject(VMobject):doc.unlink()def get_mobjects_from(self, element):+ """Parses a given SVG element into a Mobject.++ Parameters+ ----------+ element : :class:`str`+ The SVG data in the XML to be parsed.++ Returns+ -------+ VMobject+ A VMobject representing the associated SVG element.+ """result = []if not isinstance(element, minidom.Element):return result@@ -115,14 +188,51 @@ class SVGMobject(VMobject):return resultdef g_to_mobjects(self, g_element):+ """Converts the ``g`` SVG element into VMobjects.++ Parameters+ ----------+ g_element : :class:`str`+ A ``g`` element is a group of other SVG elements. As such a ``g`` element is equivalent to a VGroup.++ Returns+ -------+ List[VMobject]+ A list of VMobject reprsented by the group.+ """mob = VGroup(*self.get_mobjects_from(g_element))self.handle_transforms(g_element, mob)return mob.submobjectsdef path_string_to_mobject(self, path_string):+ """Converts a SVG path element's ``d`` attribute to a mobject.++ Parameters+ ----------+ path_string : str+ A path with potentially multiple path commands to create a shape.++ Returns+ -------+ VMobjectFromSVGPathstring+ A VMobject from the given path string, or d attribute.+ """return VMobjectFromSVGPathstring(path_string)def use_to_mobjects(self, use_element):+ """Converts a SVG <use> element to VMobject.++ Parameters+ ----------+ use_element : str+ An SVG <use> element which represents nodes that should be+ duplicated elsewhere.++ Returns+ -------+ VMobject+ A VMobject+ """# Remove initial "#" characterref = use_element.getAttribute("xlink:href")[1:]if ref not in self.ref_to_element:@@ -131,13 +241,37 @@ class SVGMobject(VMobject):return self.get_mobjects_from(self.ref_to_element[ref])def attribute_to_float(self, attr):+ """A helper method which converts the attribute to float.++ Parameters+ ----------+ attr : str+ An SVG path attribute.++ Returns+ -------+ float+ A float representing the attribute string value.+ """stripped_attr = "".join([char for char in attr if char in string.digits + "." + "-"])return float(stripped_attr)def polygon_to_mobject(self, polygon_element):- # TODO, This seems hacky...+ """Constructs a VMobject from a SVG <polygon> element.++ Parameters+ ----------+ polygon_element : str+ An SVG polygon element.++ Returns+ -------+ VMobjectFromSVGPathstring+ A VMobject representing the polygon.+ """+ # TODO, This seems hacky... yes it is.path_string = polygon_element.getAttribute("points")for digit in string.digits:path_string = path_string.replace(" " + digit, " L" + digit)@@ -147,6 +281,18 @@ class SVGMobject(VMobject):# <circle class="st1" cx="143.8" cy="268" r="22.6"/>def circle_to_mobject(self, circle_element):+ """Creates a Circle VMobject from a SVG <circle> command.++ Parameters+ ----------+ circle_element : str+ A SVG circle path command.++ Returns+ -------+ Circle+ A Circle VMobject+ """x, y, r = [self.attribute_to_float(circle_element.getAttribute(key))if circle_element.hasAttribute(key)@@ -156,6 +302,19 @@ class SVGMobject(VMobject):return Circle(radius=r).shift(x * RIGHT + y * DOWN)def ellipse_to_mobject(self, circle_element):+ """Creates a stretched Circle VMobject from a SVG <circle> path+ command.++ Parameters+ ----------+ circle_element : str+ A SVG circle path command.++ Returns+ -------+ Circle+ A Circle VMobject+ """x, y, rx, ry = [self.attribute_to_float(circle_element.getAttribute(key))if circle_element.hasAttribute(key)@@ -165,6 +324,19 @@ class SVGMobject(VMobject):return Circle().scale(rx * RIGHT + ry * UP).shift(x * RIGHT + y * DOWN)def rect_to_mobject(self, rect_element):+ """Converts a SVG <rect> command to a VMobject.++ Parameters+ ----------+ rect_element : str+ A SVG rect path command.++ Returns+ -------+ Rectangle+ Creates either a Rectangle, or RoundRectangle, VMobject from a+ rect element.+ """fill_color = rect_element.getAttribute("fill")stroke_color = rect_element.getAttribute("stroke")stroke_width = rect_element.getAttribute("stroke-width")@@ -217,6 +389,17 @@ class SVGMobject(VMobject):return mobdef handle_transforms(self, element, mobject):+ """Applies the SVG transform to the specified mobject. Tranforms include:+ ``rotate``, ``translate``, ``scale``, and ``skew``.++ Parameters+ ----------+ element : str+ The transform command to perform++ mobject : Mobject+ The Mobject to transform.+ """x, y = 0, 0try:x = self.attribute_to_float(element.getAttribute("x"))@@ -278,6 +461,7 @@ class SVGMobject(VMobject):# TODO, ...def flatten(self, input_list):+ """A helper method to flatten the ``input_list`` into an 1D array."""output_list = []for i in input_list:if isinstance(i, list):@@ -287,6 +471,19 @@ class SVGMobject(VMobject):return output_listdef get_all_childNodes_have_id(self, element):+ """Gets all child nodes containing the `id` attribute and returns+ them in a flattened list.++ Parameters+ --------+ element : :class:`str`+ An element from SVG XML data. Elements use a unique `id`.++ Returns+ -------+ List[DOM element]+ A flattened list of DOM elements containing the `id` attribute.+ """all_childNodes_have_id = []if not isinstance(element, minidom.Element):return@@ -297,12 +494,22 @@ class SVGMobject(VMobject):return self.flatten([e for e in all_childNodes_have_id if e])def update_ref_to_element(self, defs):+ """Updates the ``ref_to_element`` dictionary.+ Parameters+ --------+ defs : :class:`defs`+ The new defs+ """new_refs = dict([(e.getAttribute("id"), e) for e in self.get_all_childNodes_have_id(defs)])self.ref_to_element.update(new_refs)def move_into_position(self):+ """Uses the SVGMobject's config dictionary to set the Mobject's+ width, height, and/or center it. Use ``width``, ``height``, and+ ``should_center`` respectively to modify this.+ """if self.should_center:self.center()if self.height is not None:@@ -317,6 +524,17 @@ class VMobjectFromSVGPathstring(VMobject):VMobject.__init__(self, **kwargs)def get_path_commands(self):+ """Returns a list of possible path commands used within an SVG ``d``+ attribute.++ See: https://svgwg.org/svg2-draft/paths.html#DProperty for further+ details on what each path command does.++ Returns+ -------+ List[:class:`str`]+ The various upper and lower cased path commands.+ """result = ["M", # moveto"L", # lineto@@ -333,6 +551,7 @@ class VMobjectFromSVGPathstring(VMobject):return resultdef generate_points(self):+ """Generates points from a given an SVG ``d`` attribute."""pattern = "[%s]" % ("".join(self.get_path_commands()))pairs = list(zip(@@ -348,6 +567,7 @@ class VMobjectFromSVGPathstring(VMobject):self.rotate(np.pi, RIGHT, about_point=ORIGIN)def handle_command(self, command, coord_string):+ """Core logic for handling each of the various path commands."""isLower = command.islower()command = command.upper()# new_points are the points that will be added to the curr_points@@ -416,6 +636,9 @@ class VMobjectFromSVGPathstring(VMobject):self.add_cubic_bezier_curve_to(*new_points[i : i + 3])def string_to_points(self, coord_string):+ """Since the SVG file's path command is provided as a string, this+ converts the coordinates into numbers.+ """numbers = string_to_numbers(coord_string)if len(numbers) % 2 == 1:numbers.append(0)@@ -425,4 +648,5 @@ class VMobjectFromSVGPathstring(VMobject):return resultdef get_original_path_string(self):+ """A simple getter for the path's ``d`` attribute."""return self.path_stringdiff --git a/manim/mobject/types/image_mobject.py b/manim/mobject/types/image_mobject.pyindex e49aeefd3..1130df534 100644--- a/manim/mobject/types/image_mobject.py+++ b/manim/mobject/types/image_mobject.py@@ -115,6 +115,7 @@ class ImageMobject(AbstractImageMobject):AbstractImageMobject.__init__(self, scale_to_resolution, **kwargs)def change_to_rgba_array(self):+ """Converts an RGB array into RGBA with the alpha value opacity maxed."""pa = self.pixel_arrayif len(pa.shape) == 2:pa = pa.reshape(list(pa.shape) + [1])@@ -128,6 +129,7 @@ class ImageMobject(AbstractImageMobject):self.pixel_array = padef get_pixel_array(self):+ """A simple getter method."""return self.pixel_arraydef set_color(self, color, alpha=None, family=True):@@ -141,15 +143,47 @@ class ImageMobject(AbstractImageMobject):return selfdef set_opacity(self, alpha):+ """Sets the image's opacity.++ Parameters+ ----------+ alpha : float+ The alpha value of the object, 1 being opaque and 0 being+ transparent.+ """self.pixel_array[:, :, 3] = int(255 * alpha)return selfdef fade(self, darkness=0.5, family=True):+ """Sets the image's opacity using a 1 - alpha relationship.++ Parameters+ ----------+ darkness : float+ The alpha value of the object, 1 being transparent and 0 being+ opaque.+ family : Boolean+ Whether the submobjects of the ImageMobject should be affected.+ """self.set_opacity(1 - darkness)super().fade(darkness, family)return selfdef interpolate_color(self, mobject1, mobject2, alpha):+ """Interpolates an array of pixel color values into another array of+ equal size.++ Parameters+ ----------+ mobject1 : ImageMobject+ The ImageMobject to tranform from.++ mobject1 : ImageMobject++ The ImageMobject to tranform into.+ alpha : float+ Used to track the lerp relationship. Not opacity related.+ """assert mobject1.pixel_array.shape == mobject2.pixel_array.shape, (f"Mobject pixel array shapes incompatible for interpolation.\n"f"Mobject 1 ({mobject1}) : {mobject1.pixel_array.shape}\n"diff --git a/manim/utils/images.py b/manim/utils/images.pyindex ad9a5dc63..0f63c4776 100644--- a/manim/utils/images.py+++ b/manim/utils/images.py@@ -6,6 +6,7 @@ __all__ = ["get_full_raster_image_path", "drag_pixels", "invert_image"]import numpy as npimport os+from .. import configfrom PIL import Imagefrom ..utils.file_ops import seek_full_path_from_defaults@@ -14,8 +15,8 @@ from ..utils.file_ops import seek_full_path_from_defaultsdef get_full_raster_image_path(image_file_name):return seek_full_path_from_defaults(image_file_name,- default_dir=os.path.join("assets", "raster_images"),- extensions=[".jpg", ".png", ".gif"],+ default_dir=config.get_dir("assets_dir"),+ extensions=[".jpg", ".png", ".gif", ".ico"],)