Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

WIP setup of configparser

leotrs6d0d7a3afd92
diff --git a/manim/__init__.py b/manim/__init__.py
index 2c56030b4..0f7d59660 100644
--- a/manim/__init__.py
+++ b/manim/__init__.py
@@ -1,4 +1,7 @@
#!/usr/bin/env python
+
+# Importing config should be the first thing since other modules use it
+from .config import config
from .constants import *
from .animation.animation import *
diff --git a/manim/__main__.py b/manim/__main__.py
index 08dc1d325..e6e30ff84 100644
--- a/manim/__main__.py
+++ b/manim/__main__.py
@@ -1,13 +1,10 @@
+from .config import config
from . import extract_scene
-from . import config
from . import constants
def main():
- args = config.parse_cli()
- cfg = config.get_configuration(args)
- config.initialize_directories(cfg)
- extract_scene.main(cfg)
+ extract_scene.main(config)
if __name__ == "__main__":
diff --git a/manim/animation/transform.py b/manim/animation/transform.py
index 9bf330a18..13f58a91f 100644
--- a/manim/animation/transform.py
+++ b/manim/animation/transform.py
@@ -321,4 +321,4 @@ class TransformAnimations(Transform):
def interpolate(self, alpha):
self.start_anim.interpolate(alpha)
self.end_anim.interpolate(alpha)
- Transform.interpolate(self, alpha)
\ No newline at end of file
+ Transform.interpolate(self, alpha)
diff --git a/manim/camera/camera.py b/manim/camera/camera.py
index 5a76684b9..619f914e6 100644
--- a/manim/camera/camera.py
+++ b/manim/camera/camera.py
@@ -36,14 +36,14 @@ class Camera(object):
self.background_image : str, optional
The path to an image that should be the background image.
If not set, the background is filled with `self.background_color`
-
+
self.pixel_height
"""
CONFIG = {
"background_image": None,
- "pixel_height": DEFAULT_PIXEL_HEIGHT,
- "pixel_width": DEFAULT_PIXEL_WIDTH,
- "frame_rate": DEFAULT_FRAME_RATE,
+ "pixel_height": PIXEL_HEIGHT,
+ "pixel_width": PIXEL_WIDTH,
+ "frame_rate": FRAME_RATE,
# Note: frame height and width will be resized to match
# the pixel aspect ratio
"frame_height": FRAME_HEIGHT,
@@ -1328,4 +1328,4 @@ class BackgroundColoredVMobjectDisplayer(object):
else:
curr_array = np.maximum(curr_array, new_array)
self.reset_pixel_array()
- return curr_array
\ No newline at end of file
+ return curr_array
diff --git a/manim/config.cfg b/manim/config.cfg
deleted file mode 100644
index 7c199022f..000000000
--- a/manim/config.cfg
+++ /dev/null
@@ -1,83 +0,0 @@
-[DEFAULT]
-
-# Geometry
-START_X = 30
-START_Y = 20
-
-# Frame config
-FRAME_HEIGHT = 8.0
-FRAME_WIDTH = FRAME_HEIGHT * DEFAULT_PIXEL_WIDTH / DEFAULT_PIXEL_HEIGHT
-FRAME_Y_RADIUS = FRAME_HEIGHT / 2
-FRAME_X_RADIUS = FRAME_WIDTH / 2
-
-# Default buffers (padding)
-SMALL_BUFF = 0.1
-MED_SMALL_BUFF = 0.25
-MED_LARGE_BUFF = 0.5
-LARGE_BUFF = 1
-MOBJECT_TO_EDGE_BUFFER = MED_LARGE_BUFF
-MOBJECT_TO_MOBJECT_BUFFER = MED_SMALL_BUFF
-
-# Times in seconds
-POINTWISE_FUNCTION_RUN_TIME = 3.0
-WAIT_TIME = 1.0
-
-# Misc
-POINT_DENSITY_2D = 25
-POINT_DENSITY_1D = 250
-STROKE_WIDTH = 4
-
-# Default quality config
-FRAME_RATE = 60
-PIXEL_HEIGHT = 1440
-PIXEL_WIDTH = 2560
-
-
-[production-quality]
- PIXEL_HEIGHT = 1440
- PIXEL_WIDTH = 2560
- FRAME_RATE = 60
-
-
-[fourk-quality]
- PIXEL_HEIGHT = 2160
- PIXEL_WIDTH = 3840
- FRAME_RATE = 60
-
-
-[high-quality]
- PIXEL_HEIGHT = 1080
- PIXEL_WIDTH = 1920
- FRAME_RATE = 60
-
-
-[medium-quality]
- PIXEL_HEIGHT = 720
- PIXEL_WIDTH = 1280
- FRAME_RATE = 30
-
-
-[low-quality]
- PIXEL_HEIGHT = 480
- PIXEL_WIDTH = 854
- FRAME_RATE = 15
-
-
-[streaming]
-LIVE_STREAM_NAME = LiveStream
-TWITCH_STREAM_KEY = YOUR_STREAM_KEY
-STREAMING_PROTOCOL = tcp
-STREAMING_IP = 127.0.0.1
-STREAMING_PORT = 2000
-STREAMING_CLIENT = ffplay
-STREAMING_URL = f"{STREAMING_PROTOCOL}://{STREAMING_IP}:{STREAMING_PORT}?listen"
-STREAMING_CONSOLE_BANNER = Manim is now running in streaming mode.
- Stream animations by passing them to manim.play(), e.g.
- >>> c = Circle()
- >>> manim.play(ShowCreation(c))
-
-[dirs]
-MEDIA_DIR =
-VIDEO_DIR =
-TEX_DIR =
-TEXT_DIR =
diff --git a/manim/config.py b/manim/config.py
index 8ce22b62d..f4fbfd5bf 100644
--- a/manim/config.py
+++ b/manim/config.py
@@ -2,226 +2,329 @@
config.py
---------
-Process the files constants.py, config.cfg, and the command line arguments
-into a single config object.
+Process the manim.cfg file and the command line arguments into a single
+config object.
"""
-import argparse
-import colour
import os
import sys
-import types
+import argparse
+import configparser
+import colour
-from . import constants
-from . import dirs
from .logger import logger
-__all__ = ["parse_cli", "get_configuration", "initialize_directories"]
-
-
-def parse_cli():
- try:
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "file",
- 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(
- "-p", "--preview",
- action="store_true",
- help="Automatically open the saved file once its done",
- )
- parser.add_argument(
- "-w", "--write_to_movie",
- action="store_true",
- help="Render the scene as a movie file",
- )
- parser.add_argument(
- "-s", "--save_last_frame",
- action="store_true",
- help="Save the last frame",
- )
- parser.add_argument(
- "--dry_run",
- action="store_true",
- help= "Do a dry run (render scenes but generate no output files)",
- )
- parser.add_argument(
- "-l", "--low_quality",
- action="store_true",
- help="Render at low quality (for fastest rendering)",
- ),
- parser.add_argument(
- "-m", "--medium_quality",
- action="store_true",
- help="Render at medium quality (for much faster rendering)",
- ),
- parser.add_argument(
- "-e", "--high_quality",
- action="store_true",
- help="Render at high quality (for slightly faster rendering)",
- ),
- parser.add_argument(
- "-k", "--four_k",
- action="store_true",
- help="Render at 4K quality (slower rendering)",
- ),
- parser.add_argument(
- "-g", "--save_pngs",
- action="store_true",
- help="Save each frame as a png",
- )
- parser.add_argument(
- "-i", "--save_as_gif",
- action="store_true",
- help="Save the video as gif",
- )
- parser.add_argument(
- "-f", "--show_file_in_finder",
- action="store_true",
- help="Show the output file in finder",
- )
- parser.add_argument(
- "-t", "--transparent",
- action="store_true",
- help="Render to a movie file with an alpha channel",
- )
- 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", "--file_name",
- help="Specify the name of the output file, if"
- "it should be different from the scene class name",
- )
- 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(
- "-r", "--resolution",
- help="Resolution, passed as \"height,width\"",
- )
- parser.add_argument(
- "-c", "--color",
- help="Background color",
- )
- parser.add_argument(
- "--sound",
- action="store_true",
- help="Play a success/failure sound",
- )
- parser.add_argument(
- "--leave_progress_bars",
- action="store_true",
- help="Leave progress bars displayed in terminal",
- )
- parser.add_argument(
- "--media_dir",
- help="directory to write media",
- )
- video_group = parser.add_mutually_exclusive_group()
- video_group.add_argument(
- "--video_dir",
- help="directory to write file tree for video",
- )
- parser.add_argument(
- "--tex_dir",
- help="directory to write tex",
- )
- parser.add_argument(
- "--text_dir",
- help="directory to write text",
- )
- return parser.parse_args()
- except argparse.ArgumentError as err:
- logger.error(str(err))
- sys.exit(2)
-
-
-def get_configuration(args):
- file_writer_config = {
- # By default, write to file
- "write_to_movie": (args.write_to_movie or not args.save_last_frame) and not args.dry_run,
- "save_last_frame": args.save_last_frame and not args.dry_run,
- "save_pngs": args.save_pngs,
- "save_as_gif": args.save_as_gif,
- # If -t is passed in (for transparent), this will be RGBA
- "png_mode": "RGBA" if args.transparent else "RGB",
- "movie_file_extension": ".mov" if args.transparent else ".mp4",
- "file_name": args.file_name,
- "input_file_path": args.file,
- }
- config = {
- "file": args.file,
- "scene_names": args.scene_names,
- "open_video_upon_completion": args.preview,
- "show_file_in_finder": args.show_file_in_finder,
- "file_writer_config": file_writer_config,
- "quiet": args.quiet or args.write_all,
- "ignore_waits": args.preview,
- "write_all": args.write_all,
- "start_at_animation_number": args.start_at_animation_number,
- "end_at_animation_number": None,
- "sound": args.sound,
- "leave_progress_bars": args.leave_progress_bars,
- "media_dir": args.media_dir,
- "video_dir": args.video_dir,
- "tex_dir": args.tex_dir,
- "text_dir": args.text_dir,
- }
-
- # Camera configuration
- config["camera_config"] = get_camera_configuration(args)
-
- # Arguments related to skipping
- stan = config["start_at_animation_number"]
- if stan is not None:
- if "," in stan:
- start, end = stan.split(",")
- config["start_at_animation_number"] = int(start)
- config["end_at_animation_number"] = int(end)
- else:
- config["start_at_animation_number"] = int(stan)
+__all__ = ['config']
+
+
+def _parse_config(input_file, config_files):
+ # This only loads the [CLI] section of the manim.cfg file. If using
+ # CLI arguments, the _update_config_with_args function will take care
+ # of overriding any of these defaults.
+ config_parser = configparser.ConfigParser()
+ successfully_read_files = config_parser.read(config_files)
+ if not successfully_read_files:
+ raise FileNotFoundError('Config file could not be read')
+
+ # Put everything in a dict
+ config = {}
+
+ # Make sure we have an input file
+ config['INPUT_FILE'] = input_file
+
+ # ConfigParser options are all strings, so need to convert to the
+ # appropriate type
+
+ # booleans
+ for opt in ['PREVIEW', 'SHOW_FILE_IN_FINDER', 'QUIET', 'SOUND',
+ 'LEAVE_PROGRESS_BARS', 'WRITE_ALL', 'WRITE_TO_MOVIE',
+ 'SAVE_LAST_FRAME', 'DRY_RUN', 'SAVE_PNGS', 'SAVE_AS_GIF']:
+ config[opt] = config_parser['CLI'].getboolean(opt)
+
+ # numbers
+ for opt in ['FROM_ANIMATION_NUMBER', 'UPTO_ANIMATION_NUMBER',
+ 'BACKGROUND_OPACITY']:
+ config[opt] = config_parser['CLI'].getint(opt)
+
+ # UPTO_ANIMATION_NUMBER is special because -1 actually means np.inf
+ if config['UPTO_ANIMATION_NUMBER'] == -1:
+ import numpy as np
+ config['UPTO_ANIMATION_NUMBER'] = np.inf
- config["skip_animations"] = any([
- file_writer_config["save_last_frame"],
- config["start_at_animation_number"],
+ # strings
+ for opt in ['PNG_MODE', 'MOVIE_FILE_EXTENSION', 'MEDIA_DIR',
+ 'OUTPUT_FILE', 'VIDEO_DIR', 'TEX_DIR', 'TEXT_DIR',
+ 'BACKGROUND_COLOR']:
+ config[opt] = config_parser['CLI'][opt]
+
+ # streaming section -- all values are strings
+ config['STREAMING'] = {}
+ for opt in ['LIVE_STREAM_NAME', 'TWITCH_STREAM_KEY',
+ 'STREAMING_PROTOCOL', 'STREAMING_PROTOCOL', 'STREAMING_IP',
+ 'STREAMING_PORT', 'STREAMING_PORT', 'STREAMING_CLIENT',
+ 'STREAMING_CONSOLE_BANNER']:
+ config['STREAMING'][opt] = config_parser['streaming'][opt]
+
+ # for internal use (no CLI flag)
+ config['SKIP_ANIMATIONS'] = any([
+ config['SAVE_LAST_FRAME'],
+ config['FROM_ANIMATION_NUMBER'],
])
- return config
+ # camera config -- all happen to be integers
+ config['CAMERA_CONFIG'] = {}
+ for opt in ['FRAME_RATE', 'PIXEL_HEIGHT', 'PIXEL_WIDTH']:
+ config['CAMERA_CONFIG'][opt] = config_parser['CLI'].getint(opt)
-def get_camera_configuration(args):
- camera_config = {}
- if args.low_quality:
- camera_config.update(constants.LOW_QUALITY_CAMERA_CONFIG)
- elif args.medium_quality:
- camera_config.update(constants.MEDIUM_QUALITY_CAMERA_CONFIG)
- elif args.high_quality:
- camera_config.update(constants.HIGH_QUALITY_CAMERA_CONFIG)
- elif args.four_k:
- camera_config.update(constants.FOURK_CAMERA_CONFIG)
- else:
- camera_config.update(constants.PRODUCTION_QUALITY_CAMERA_CONFIG)
+ # file writer config -- just pull them from the overall config for now
+ config['FILE_WRITER_CONFIG'] = {key: config[key] for key in [
+ "WRITE_TO_MOVIE", "SAVE_LAST_FRAME", "SAVE_PNGS",
+ "SAVE_AS_GIF", "PNG_MODE", "MOVIE_FILE_EXTENSION",
+ "OUTPUT_FILE", "INPUT_FILE"]}
+
+ return config, config_parser
+
+
+def _parse_cli():
+ parser = argparse.ArgumentParser(
+ description='Animation engine for explanatory math videos',
+ epilog='Made with <3 by the manim community devs'
+ )
+ parser.add_argument(
+ "file",
+ 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(
+ "-o", "--output_file",
+ help="Specify the name of the output file, if"
+ "it should be different from the scene class name",
+ )
+
+ # Note the following use (action='store_const', const=True),
+ # instead of using the built-in (action='store_true'). The reason
+ # is that these two are not equivalent. The latter is equivalent
+ # to (action='store_const', const=True, default=False), while the
+ # former sets no default value. We do not want to set the default
+ # here, but in the manim.cfg file. Therefore we use the latter,
+ # (action='store_const', const=True).
+ parser.add_argument(
+ "-p", "--preview",
+ action="store_const",
+ const=True,
+ help="Automatically open the saved file once its done",
+ )
+ parser.add_argument(
+ "-f", "--show_file_in_finder",
+ action="store_const",
+ const=True,
+ help="Show the output file in finder",
+ )
+ parser.add_argument(
+ "-q", "--quiet",
+ action="store_const",
+ const=True,
+ help="Quiet mode",
+ )
+ parser.add_argument(
+ "--sound",
+ action="store_const",
+ const=True,
+ help="Play a success/failure sound",
+ )
+ parser.add_argument(
+ "--leave_progress_bars",
+ action="store_const",
+ const=True,
+ help="Leave progress bars displayed in terminal",
+ )
+ parser.add_argument(
+ "-a", "--write_all",
+ action="store_const",
+ const=True,
+ help="Write all the scenes from a file",
+ )
+ parser.add_argument(
+ "-w", "--write_to_movie",
+ action="store_const",
+ const=True,
+ help="Render the scene as a movie file",
+ )
+ parser.add_argument(
+ "-s", "--save_last_frame",
+ action="store_const",
+ const=True,
+ help="Save the last frame",
+ )
+ parser.add_argument(
+ "-g", "--save_pngs",
+ action="store_const",
+ const=True,
+ help="Save each frame as a png",
+ )
+ parser.add_argument(
+ "-i", "--save_as_gif",
+ action="store_const",
+ const=True,
+ help="Save the video as gif",
+ )
+
+ # The default value of the following is set in manim.cfg
+ parser.add_argument(
+ "-c", "--color",
+ help="Background color",
+ )
+ parser.add_argument(
+ "--background_opacity",
+ help="Background opacity",
+ )
+ parser.add_argument(
+ "--media_dir",
+ help="directory to write media",
+ )
+ video_group = parser.add_mutually_exclusive_group()
+ video_group.add_argument(
+ "--video_dir",
+ help="directory to write file tree for video",
+ )
+ parser.add_argument(
+ "--tex_dir",
+ help="directory to write tex",
+ )
+ parser.add_argument(
+ "--text_dir",
+ help="directory to write text",
+ )
+
+ # All of the following use (action="store_true"). This means that
+ # they are by default False. In contrast to the previous ones that
+ # used (action="store_const", const=True), the following do not
+ # correspond to a single configuration option. Rather, they
+ # override several options at the same time.
+
+ # The following overrides -w, -a, -g, and -i
+ parser.add_argument(
+ "--dry_run",
+ action="store_true",
+ help="Do a dry run (render scenes but generate no output files)",
+ )
+
+ # The following overrides PNG_MODE, MOVIE_FILE_EXTENSION, and
+ # BACKGROUND_OPACITY
+ parser.add_argument(
+ "-t", "--transparent",
+ action="store_true",
+ help="Render to a movie file with an alpha channel",
+ )
+
+ # The following are mutually exclusive and each overrides
+ # FRAME_RATE, PIXEL_HEIGHT, and PIXEL_WIDTH,
+ parser.add_argument(
+ "-l", "--low_quality",
+ action="store_true",
+ help="Render at low quality (for fastest rendering)",
+ )
+ parser.add_argument(
+ "-m", "--medium_quality",
+ action="store_true",
+ help="Render at medium quality (for much faster rendering)",
+ )
+ parser.add_argument(
+ "-e", "--high_quality",
+ action="store_true",
+ help="Render at high quality (for slightly faster rendering)",
+ )
+ parser.add_argument(
+ "-k", "--fourk_quality",
+ action="store_true",
+ help="Render at 4K quality (slower rendering)",
+ )
- # If the resolution was passed in via -r
- if args.resolution:
+ # This overrides any of the above
+ parser.add_argument(
+ "-r", "--resolution",
+ help="Resolution, passed as \"height,width\"",
+ )
+
+ # This sets FROM_ANIMATION_NUMBER and UPTO_ANIMATION_NUMBER
+ parser.add_argument(
+ "-n", "--from_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",
+ )
+
+ # Specify the manim.cfg file
+ parser.add_argument(
+ "--config_file",
+ help="Specify the configuration file",
+ )
+
+ return parser.parse_args()
+
+
+def _update_config_with_args(config, config_parser, args):
+ # Take care of options that do not have defaults in manim.cfg
+ config['FILE'] = args.file
+ config['SCENE_NAMES'] = (args.scene_names
+ if args.scene_names is not None else [])
+
+ # Flags that directly override config defaults.
+ for opt in ['PREVIEW', 'SHOW_FILE_IN_FINDER', 'QUIET', 'SOUND',
+ 'LEAVE_PROGRESS_BARS', 'WRITE_ALL', 'WRITE_TO_MOVIE',
+ 'SAVE_LAST_FRAME', 'SAVE_PNGS', 'SAVE_AS_GIF', 'MEDIA_DIR',
+ 'VIDEO_DIR', 'TEX_DIR', 'TEXT_DIR', 'BACKGROUND_OPACITY',
+ 'OUTPUT_FILE']:
+ if getattr(args, opt.lower()) is not None:
+ config[opt] = getattr(args, opt.lower())
+
+ # Parse the -n flag.
+ nflag = args.from_animation_number
+ if nflag is not None:
+ if ',' in nflag:
+ start, end = nflag.split(',')
+ config['FROM_ANIMATION_NUMBER'] = int(start)
+ config['UPTO_ANIMATION_NUMBER'] = int(end)
+ else:
+ config['FROM_ANIMATION_NUMBER'] = int(nflag)
+
+ # The following flags use the options in the corresponding manim.cfg
+ # sections to override default options. For example, passing the -t
+ # (--transparent) flag takes all of the options defined in the
+ # [transparent] section of manim.cfg and uses their values to override
+ # the values of those options defined in CLI.
+
+ # -t, --transparent
+ if args.transparent:
+ config.update({
+ 'PNG_MODE': config_parser['transparent']['PNG_MODE'],
+ 'MOVIE_FILE_EXTENSION': config_parser['transparent']['MOVIE_FILE_EXTENSION'],
+ 'BACKGROUND_OPACITY': config_parser['transparent'].getfloat('BACKGROUND_OPACITY')
+ })
+
+ # --dry_run happens to override options that are all booleans
+ if args.dry_run:
+ config.update({opt.upper(): config_parser['dry_run'].getboolean(opt)
+ for opt in config_parser['dry_run']})
+
+ # the *_quality arguments happen to override options that are all ints
+ for flag in ['fourk_quality', 'high_quality', 'medium_quality',
+ 'low_quality']:
+ if getattr(args, flag) is not None:
+ config['CAMERA_CONFIG'].update(
+ {opt.upper(): config_parser[flag].getint(opt)
+ for opt in config_parser[flag]})
+
+ # Parse the -r (--resolution) flag. Note the -r flag does not
+ # correspond to any section in manim.cfg, but overrides the same
+ # options as the *_quality sections.
+ if args.resolution is not None:
if "," in args.resolution:
height_str, width_str = args.resolution.split(",")
height = int(height_str)
@@ -229,64 +332,75 @@ def get_camera_configuration(args):
else:
height = int(args.resolution)
width = int(16 * height / 9)
- camera_config.update({
- "pixel_height": height,
- "pixel_width": width,
- })
+ config['CAMERA_CONFIG'].update({'pixel_height': height,
+ 'pixel_width': width})
- if args.color:
+ # Parse the -c (--color) flag
+ if args.color is not None:
try:
- camera_config["background_color"] = colour.Color(args.color)
+ config['CAMERA_CONFIG']['BACKGROUND_COLOR'] = colour.Color(args.color)
except AttributeError as err:
- logger.warning("Please use a valid color")
+ logger.warning('Please use a valid color')
logger.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
+ # As before, make FILE_WRITER_CONFIG by pulling form the overall
+ config['FILE_WRITER_CONFIG'] = {key: config[key] for key in [
+ "WRITE_TO_MOVIE", "SAVE_LAST_FRAME", "SAVE_PNGS",
+ "SAVE_AS_GIF", "PNG_MODE", "MOVIE_FILE_EXTENSION",
+ "OUTPUT_FILE", "INPUT_FILE"]}
+ return config
-def initialize_directories(config):
- dir_config = {}
- dir_config["media_dir"] = config["media_dir"] or dirs.MEDIA_DIR
- dir_config["video_dir"] = config["video_dir"] or dirs.VIDEO_DIR
- if not (config["video_dir"] and config["tex_dir"]):
- if config["media_dir"]:
- if not os.path.isdir(dir_config["media_dir"]):
- os.makedirs(dir_config["media_dir"])
- if not os.path.isdir(dir_config["media_dir"]):
- dir_config["media_dir"] = "./media"
+def _init_dirs(config):
+ if not (config["VIDEO_DIR"] and config["TEX_DIR"]):
+ if config["MEDIA_DIR"]:
+ if not os.path.isdir(config["MEDIA_DIR"]):
+ os.makedirs(config["MEDIA_DIR"])
+ if not os.path.isdir(config["MEDIA_DIR"]):
+ config["MEDIA_DIR"] = "./media"
else:
print(
- f"Media will be written to {dir_config['media_dir'] + os.sep}. You can change "
- "this behavior with the --media_dir flag, or by adjusting dirs.py.,"
+ f"Media will be written to {config['media_dir'] + os.sep}. You can change "
+ "this behavior with the --media_dir flag, or by adjusting manim.cfg."
)
else:
- if config["media_dir"]:
+ if config["MEDIA_DIR"]:
print(
"Ignoring --media_dir, since both --tex_dir and --video_dir were passed."
)
- dir_config["tex_dir"] = (config["tex_dir"]
- or dirs.TEX_DIR
- or os.path.join(dir_config["media_dir"], "Tex"))
- dir_config["text_dir"] = (config["text_dir"]
- or dirs.TEXT_DIR
- or os.path.join(dir_config["media_dir"], "texts"))
+ # Make sure all folders exist
+ for folder in [config["VIDEO_DIR"], config["TEX_DIR"], config["TEXT_DIR"]]:
+ if not os.path.exists(folder):
+ os.makedirs(folder)
- if not config["video_dir"] or dirs.VIDEO_DIR:
- dir_config["video_dir"] = os.path.join(dir_config["media_dir"], "videos")
- for folder in [dir_config["video_dir"], dir_config["tex_dir"], dir_config["text_dir"]]:
- if folder != "" and not os.path.exists(folder):
- os.makedirs(folder)
+config_filename = 'manim.cfg'
+
+foobar = os.path.join(os.path.dirname(__file__), config_filename)
+print(foobar)
+config_files = [
+ foobar,
+ os.path.expanduser('~/.{}'.format(config_filename)),
+ os.path.join(os.getcwd(), config_filename),
+ ]
+
+prog = os.path.split(sys.argv[0])[-1]
+if prog in ['manim', 'manimcm']:
+ # If called as entrypoint, set default config, and override the
+ # defaults using CLI arguments
+ args = _parse_cli()
+
+ print(args)
+
+ if args.config_file is not None:
+ config_files.append(args.config_file)
+ config, config_parser = _parse_config(args.file, config_files)
+ _update_config_with_args(config, config_parser, args)
+
+else:
+ config, _ = _parse_config('', config_files)
- dirs.MEDIA_DIR = dir_config["media_dir"]
- dirs.VIDEO_DIR = dir_config["video_dir"]
- dirs.TEX_DIR = dir_config["tex_dir"]
- dirs.TEXT_DIR = dir_config["text_dir"]
+_init_dirs(config)
diff --git a/manim/constants.py b/manim/constants.py
index 086899062..205d97655 100644
--- a/manim/constants.py
+++ b/manim/constants.py
@@ -1,8 +1,10 @@
import numpy as np
import os
+from .config import config
+
# Messages
-NOT_SETTING_FONT_MSG='''
+NOT_SETTING_FONT_MSG = '''
You haven't set font.
If you are not using English, this may cause text rendering problem.
You set font like:
@@ -51,12 +53,42 @@ UR = UP + RIGHT
DL = DOWN + LEFT
DR = DOWN + RIGHT
+# Geometry
+START_X = 30
+START_Y = 20
+
+# Geometry: frame
+FRAME_HEIGHT = 8.0
+PIXEL_WIDTH = config['CAMERA_CONFIG']['PIXEL_WIDTH']
+PIXEL_HEIGHT = config['CAMERA_CONFIG']['PIXEL_HEIGHT']
+FRAME_RATE = config['CAMERA_CONFIG']['FRAME_RATE']
+FRAME_WIDTH = FRAME_HEIGHT * PIXEL_WIDTH / PIXEL_HEIGHT
+FRAME_Y_RADIUS = FRAME_HEIGHT / 2
+FRAME_X_RADIUS = FRAME_WIDTH / 2
+
# Geometry: sides
TOP = FRAME_Y_RADIUS * UP
BOTTOM = FRAME_Y_RADIUS * DOWN
LEFT_SIDE = FRAME_X_RADIUS * LEFT
RIGHT_SIDE = FRAME_X_RADIUS * RIGHT
+# Default buffers (padding)
+SMALL_BUFF = 0.1
+MED_SMALL_BUFF = 0.25
+MED_LARGE_BUFF = 0.5
+LARGE_BUFF = 1
+DEFAULT_MOBJECT_TO_EDGE_BUFFER = MED_LARGE_BUFF
+DEFAULT_MOBJECT_TO_MOBJECT_BUFFER = MED_SMALL_BUFF
+
+# Times in seconds
+DEFAULT_POINTWISE_FUNCTION_RUN_TIME = 3.0
+DEFAULT_WAIT_TIME = 1.0
+
+# Misc
+DEFAULT_POINT_DENSITY_2D = 25
+DEFAULT_POINT_DENSITY_1D = 250
+DEFAULT_STROKE_WIDTH = 4
+
# Tex stuff
TEX_USE_CTEX = False
TEX_TEXT_TO_REPLACE = "YourTextHere"
@@ -145,108 +177,3 @@ COLOR_MAP.update({name.replace("_C", ""): COLOR_MAP[name]
if name.endswith("_C")})
PALETTE = list(COLOR_MAP.values())
locals().update(COLOR_MAP)
-
-# Settings for CodeMobject
-code_languages_list = {"abap": "abap", "as": "as", "as3": "as3", "ada": "ada", "antlr": "antlr",
- "antlr_as": "antlr-as",
- "antlr_csharp": "antlr-csharp", "antlr_cpp": "antlr-cpp", "antlr_java": "antlr-java",
- "antlr_objc": "antlr-objc", "antlr_perl": "antlr-perl", "antlr_python": "antlr-python",
- "antlr_ruby": "antlr-ruby", "apacheconf": "apacheconf", "applescript": "applescript",
- "aspectj": "aspectj",
- "aspx_cs": "aspx-cs", "aspx_vb": "aspx-vb", "asy": "asy", "ahk": "ahk", "autoit": "autoit",
- "awk": "awk",
- "basemake": "basemake", "bash": "bash", "console": "console", "bat": "bat",
- "bbcode": "bbcode",
- "befunge": "befunge", "blitzmax": "blitzmax", "boo": "boo", "brainfuck": "brainfuck",
- "bro": "bro",
- "bugs": "bugs", "c": "c", "csharp": "csharp", "cpp": "cpp", "c_objdump": "c-objdump",
- "ca65": "ca65",
- "cbmbas": "cbmbas", "ceylon": "ceylon", "cfengine3": "cfengine3", "cfs": "cfs",
- "cheetah": "cheetah",
- "clojure": "clojure", "cmake": "cmake", "cobol": "cobol", "cobolfree": "cobolfree",
- "coffee_script": "coffee-script", "cfm": "cfm", "common_lisp": "common-lisp", "coq": "coq",
- "cpp_objdump": "cpp-objdump", "croc": "croc", "css": "css", "css_django": "css+django",
- "css_genshitext": "css+genshitext", "css_lasso": "css+lasso", "css_mako": "css+mako",
- "css_myghty": "css+myghty", "css_php": "css+php", "css_erb": "css+erb",
- "css_smarty": "css+smarty",
- "cuda": "cuda", "cython": "cython", "d": "d", "d_objdump": "d-objdump", "dpatch": "dpatch",
- "dart": "dart",
- "control": "control", "sourceslist": "sourceslist", "delphi": "delphi", "dg": "dg",
- "diff": "diff",
- "django": "django", "dtd": "dtd", "duel": "duel", "dylan": "dylan",
- "dylan_console": "dylan-console",
- "dylan_lid": "dylan-lid", "ec": "ec", "ecl": "ecl", "elixir": "elixir", "iex": "iex",
- "ragel_em": "ragel-em",
- "erb": "erb", "erlang": "erlang", "erl": "erl", "evoque": "evoque", "factor": "factor",
- "fancy": "fancy",
- "fan": "fan", "felix": "felix", "fortran": "fortran", "Clipper": "Clipper",
- "fsharp": "fsharp", "gas": "gas",
- "genshi": "genshi", "genshitext": "genshitext", "pot": "pot", "Cucumber": "Cucumber",
- "glsl": "glsl",
- "gnuplot": "gnuplot", "go": "go", "gooddata_cl": "gooddata-cl", "gosu": "gosu", "gst": "gst",
- "groff": "groff",
- "groovy": "groovy", "haml": "haml", "haskell": "haskell", "hx": "hx", "html": "html",
- "html_cheetah": "html+cheetah", "html_django": "html+django", "html_evoque": "html+evoque",
- "html_genshi": "html+genshi", "html_lasso": "html+lasso", "html_mako": "html+mako",
- "html_myghty": "html+myghty", "html_php": "html+php", "html_smarty": "html+smarty",
- "html_velocity": "html+velocity", "http": "http", "haxeml": "haxeml", "hybris": "hybris",
- "idl": "idl",
- "ini": "ini", "io": "io", "ioke": "ioke", "irc": "irc", "jade": "jade", "jags": "jags",
- "java": "java",
- "jsp": "jsp", "js": "js", "js_cheetah": "js+cheetah", "js_django": "js+django",
- "js_genshitext": "js+genshitext", "js_lasso": "js+lasso", "js_mako": "js+mako",
- "js_myghty": "js+myghty",
- "js_php": "js+php", "js_erb": "js+erb", "js_smarty": "js+smarty", "json": "json",
- "julia": "julia",
- "jlcon": "jlcon", "kconfig": "kconfig", "koka": "koka", "kotlin": "kotlin", "lasso": "lasso",
- "lighty": "lighty", "lhs": "lhs", "live_script": "live-script", "llvm": "llvm",
- "logos": "logos",
- "logtalk": "logtalk", "lua": "lua", "make": "make", "mako": "mako", "maql": "maql",
- "mason": "mason",
- "matlab": "matlab", "matlabsession": "matlabsession", "minid": "minid",
- "modelica": "modelica",
- "modula2": "modula2", "trac_wiki": "trac-wiki", "monkey": "monkey", "moocode": "moocode",
- "moon": "moon",
- "mscgen": "mscgen", "mupad": "mupad", "mxml": "mxml", "myghty": "myghty", "mysql": "mysql",
- "nasm": "nasm",
- "nemerle": "nemerle", "newlisp": "newlisp", "newspeak": "newspeak", "nginx": "nginx",
- "nimrod": "nimrod",
- "nsis": "nsis", "numpy": "numpy", "objdump": "objdump", "objective_c": "objective-c",
- "objective_c_+": "objective-c++", "objective_j": "objective-j", "ocaml": "ocaml",
- "octave": "octave",
- "ooc": "ooc", "opa": "opa", "openedge": "openedge", "perl": "perl", "php": "php",
- "plpgsql": "plpgsql",
- "psql": "psql", "postgresql": "postgresql", "postscript": "postscript", "pov": "pov",
- "powershell": "powershell", "prolog": "prolog", "properties": "properties",
- "protobuf": "protobuf",
- "puppet": "puppet", "pypylog": "pypylog", "python": "python", "python3": "python3",
- "py3tb": "py3tb",
- "pycon": "pycon", "pytb": "pytb", "qml": "qml", "racket": "racket", "ragel": "ragel",
- "ragel_c": "ragel-c",
- "ragel_cpp": "ragel-cpp", "ragel_d": "ragel-d", "ragel_java": "ragel-java",
- "ragel_objc": "ragel-objc",
- "ragel_ruby": "ragel-ruby", "raw": "raw", "rconsole": "rconsole", "rd": "rd",
- "rebol": "rebol",
- "redcode": "redcode", "registry": "registry", "rst": "rst", "rhtml": "rhtml",
- "RobotFramework": "RobotFramework", "spec": "spec", "rb": "rb", "rbcon": "rbcon",
- "rust": "rust",
- "splus": "splus", "sass": "sass", "scala": "scala", "ssp": "ssp", "scaml": "scaml",
- "scheme": "scheme",
- "scilab": "scilab", "scss": "scss", "shell_session": "shell-session", "smali": "smali",
- "smalltalk": "smalltalk", "smarty": "smarty", "snobol": "snobol", "sp": "sp", "sql": "sql",
- "sqlite3": "sqlite3", "squidconf": "squidconf", "stan": "stan", "sml": "sml",
- "systemverilog": "systemverilog",
- "tcl": "tcl", "tcsh": "tcsh", "tea": "tea", "tex": "tex", "text": "text",
- "treetop": "treetop", "ts": "ts",
- "urbiscript": "urbiscript", "vala": "vala", "vb.net": "vb.net", "velocity": "velocity",
- "verilog": "verilog",
- "vgl": "vgl", "vhdl": "vhdl", "vim": "vim", "xml": "xml", "xml_cheetah": "xml+cheetah",
- "xml_django": "xml+django", "xml_evoque": "xml+evoque", "xml_lasso": "xml+lasso",
- "xml_mako": "xml+mako",
- "xml_myghty": "xml+myghty", "xml_php": "xml+php", "xml_erb": "xml+erb",
- "xml_smarty": "xml+smarty",
- "xml_velocity": "xml+velocity", "xquery": "xquery", "xslt": "xslt", "xtend": "xtend",
- "yaml": "yaml"}
-code_styles_list = {0: "autumn", 1: "borland", 2: "bw", 3: "colorful", 4: "default", 5: "emacs",
- 6: "friendly", 7: "fruity", 8: "manni", 9: "monokai", 10: "murphy", 11: "native",
- 12: "pastie", 13: "perldoc", 14: "rrt", 15: "tango", 16: "trac", 17: "vim", 18: "vs"}
diff --git a/manim/container/container.py b/manim/container/container.py
index 5f1274f03..8d84f2729 100644
--- a/manim/container/container.py
+++ b/manim/container/container.py
@@ -28,4 +28,4 @@ class Container(object):
Must be implemented by subclasses.
"""
raise Exception(
- "Container.remove is not implemented; it is up to derived classes to implement")
\ No newline at end of file
+ "Container.remove is not implemented; it is up to derived classes to implement")
diff --git a/manim/extract_scene.py b/manim/extract_scene.py
index b8a0ad96d..323833b3a 100644
--- a/manim/extract_scene.py
+++ b/manim/extract_scene.py
@@ -15,21 +15,21 @@ from .logger import logger
def open_file_if_needed(file_writer, **config):
- if config["quiet"]:
+ if config["QUIET"]:
curr_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
open_file = any([
- config["open_video_upon_completion"],
- config["show_file_in_finder"]
+ config["PREVIEW"],
+ config["SHOW_FILE_IN_FINDER"]
])
if open_file:
current_os = platform.system()
file_paths = []
- if config["file_writer_config"]["save_last_frame"]:
+ if config["FILE_WRITER_CONFIG"]["SAVE_LAST_FRAME"]:
file_paths.append(file_writer.get_image_file_path())
- if config["file_writer_config"]["write_to_movie"]:
+ if config["FILE_WRITER_CONFIG"]["WRITE_TO_MOVIE"]:
file_paths.append(file_writer.get_movie_file_path())
for file_path in file_paths:
@@ -44,7 +44,7 @@ def open_file_if_needed(file_writer, **config):
else: # Assume macOS
commands.append("open")
- if config["show_file_in_finder"]:
+ if config["SHOW_FILE_IN_FINDER"]:
commands.append("-R")
commands.append(file_path)
@@ -54,7 +54,7 @@ def open_file_if_needed(file_writer, **config):
sp.call(commands, stdout=FNULL, stderr=sp.STDOUT)
FNULL.close()
- if config["quiet"]:
+ if config["QUIET"]:
sys.stdout.close()
sys.stdout = curr_stdout
@@ -96,13 +96,13 @@ def prompt_user_for_choice(scene_classes):
def get_scenes_to_render(scene_classes, config):
- if len(scene_classes) == 0:
+ if not scene_classes:
logger.error(constants.NO_SCENE_MESSAGE)
return []
- if config["write_all"]:
+ if config["WRITE_ALL"]:
return scene_classes
result = []
- for scene_name in config["scene_names"]:
+ for scene_name in config["SCENE_NAMES"]:
found = False
for scene_class in scene_classes:
if scene_class.__name__ == scene_name:
@@ -144,40 +144,41 @@ def get_module(file_name):
logger.error(f"Failed to render scene: {str(e)}")
sys.exit(2)
else:
- 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
+ if os.path.exists(file_name):
+ 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
+ else:
+ raise FileNotFoundError(f'{file_name} not found')
def main(config):
- module = get_module(config["file"])
+ module = get_module(config["FILE"])
all_scene_classes = get_scene_classes_from_module(module)
scene_classes_to_render = get_scenes_to_render(all_scene_classes, config)
- scene_kwargs = dict([
- (key, config[key])
- for key in [
- "camera_config",
- "file_writer_config",
- "skip_animations",
- "start_at_animation_number",
- "end_at_animation_number",
- "leave_progress_bars",
+ keys = [
+ "CAMERA_CONFIG",
+ "FILE_WRITER_CONFIG",
+ "SKIP_ANIMATIONS",
+ "FROM_ANIMATION_NUMBER",
+ "UPTO_ANIMATION_NUMBER",
+ "LEAVE_PROGRESS_BARS",
]
- ])
+ scene_kwargs = {key: config[key] for key in keys}
for SceneClass in scene_classes_to_render:
try:
# By invoking, this renders the full scene
scene = SceneClass(**scene_kwargs)
open_file_if_needed(scene.file_writer, **config)
- if config["sound"]:
+ if config["SOUND"]:
play_finish_sound()
except Exception:
print("\n\n")
traceback.print_exc()
print("\n\n")
- if config["sound"]:
+ if config["SOUND"]:
play_error_sound()
diff --git a/manim/manim.cfg b/manim/manim.cfg
new file mode 100644
index 000000000..472df34d0
--- /dev/null
+++ b/manim/manim.cfg
@@ -0,0 +1,141 @@
+# manim.cfg
+# Default configuration for manim
+
+# Configure how manim behaves when called from the command line without
+# specifying any flags
+[CLI]
+
+# Each of the following will be set to True if the corresponding CLI flag
+# is present when executing manim. If the flag is not present, they will
+# be set to the value found here. For example, running manim with the -w
+# flag will set WRITE_TO_MOVIE to True. However, since the default value
+# of WRITE_TO_MOVIE defined in this file is also True, running manim
+# without the -w value will also output a movie file. To change that, set
+# WRITE_TO_MOVIE = False so that running manim without the -w flag will not
+# generate a movie file. Note all of the following accept boolean values.
+
+# -w, --write_to_movie
+WRITE_TO_MOVIE = True
+
+# -a, --write_all
+WRITE_ALL = False
+
+# -s, --save_last_frame
+SAVE_LAST_FRAME = False
+
+# -g, --save_pngs
+SAVE_PNGS = False
+
+# -i, --save_as_gif
+SAVE_AS_GIF = False
+
+# -p, --preview
+PREVIEW = False
+
+# -f, --show_file_in_finder
+SHOW_FILE_IN_FINDER = False
+
+# -q, --quiet
+QUIET = False
+
+# --sound
+SOUND = False
+
+# -o, --output_file
+OUTPUT_FILE =
+
+# --leave_progress_bars
+LEAVE_PROGRESS_BARS = False
+
+# -c, --color
+BACKGROUND_COLOR = BLACK
+
+# --background_opacity
+BACKGROUND_OPACITY = 1
+
+# The following two are both set by the -n (or --from_animation_number)
+# flag. See manim -h for more information.
+FROM_ANIMATION_NUMBER = 0
+
+# Use -1 to render all animations
+UPTO_ANIMATION_NUMBER = -1
+
+# The following are meant to be paths relative to the point of execution.
+# Set them at the CLI with the corresponding flag, or set their default
+# values here.
+# --media_dir
+MEDIA_DIR = ./media
+
+# --video_dir
+VIDEO_DIR = %(MEDIA_DIR)s/videos
+
+# --tex_dir
+TEX_DIR = %(MEDIA_DIR)s/Tex
+
+# --text_dir
+TEXT_DIR = %(MEDIA_DIR)s/texts
+
+# If the -t (--transparent) flag is used, these will be replaced with the
+# values specified in the [TRANSPARENT] section later in this file.
+PNG_MODE = RGB
+MOVIE_FILE_EXTENSION = .mp4
+
+# These can be overriden with any of -l (--low_quality), -m
+# (--medium_quality), -e (--high_quality), or -k (--fourk_quality). The
+# overriding values are found in the corresponding sections.
+FRAME_RATE = 60
+PIXEL_HEIGHT = 1440
+PIXEL_WIDTH = 2560
+
+# These override the previous by using -t, --transparent
+[transparent]
+PNG_MODE = RGBA
+MOVIE_FILE_EXTENSION = .mov
+BACKGROUND_OPACITY = 0
+
+# These override the previous by using -k, --four_k
+[fourk_quality]
+PIXEL_HEIGHT = 2160
+PIXEL_WIDTH = 3840
+FRAME_RATE = 60
+
+# These override the previous by using -e, --high_quality
+[high_quality]
+PIXEL_HEIGHT = 1080
+PIXEL_WIDTH = 1920
+FRAME_RATE = 60
+
+# These override the previous by using -m, --medium_quality
+[medium_quality]
+PIXEL_HEIGHT = 720
+PIXEL_WIDTH = 1280
+FRAME_RATE = 30
+
+# These override the previous by usnig -l, --low_quality
+[low_quality]
+PIXEL_HEIGHT = 480
+PIXEL_WIDTH = 854
+FRAME_RATE = 15
+
+# These override the previous by using --dry_run
+# Note --dry_run overrides all of -w, -a, -s, -g, -i
+[dry_run]
+WRITE_TO_MOVIE = False
+WRITE_ALL = False
+SAVE_LAST_FRAME = False
+SAVE_PNGS = False
+SAVE_AS_GIF = False
+
+# Streaming settings
+[streaming]
+LIVE_STREAM_NAME = LiveStream
+TWITCH_STREAM_KEY = YOUR_STREAM_KEY
+STREAMING_PROTOCOL = tcp
+STREAMING_IP = 127.0.0.1
+STREAMING_PORT = 2000
+STREAMING_CLIENT = ffplay
+STREAMING_URL = %(STREAMING_PROTOCOL)s://%(STREAMING_IP)s:%(STREAMING_PORT)s?listen
+STREAMING_CONSOLE_BANNER = Manim is now running in streaming mode.
+ Stream animations by passing them to manim.play(), e.g.
+ >>> c = Circle()
+ >>> manim.play(ShowCreation(c))
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index edd22af14..e460b8431 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -10,7 +10,7 @@ from colour import Color
import numpy as np
from ..constants import *
-from .. import dirs
+from ..config import config
from ..container.container import Container
from ..utils.color import color_gradient
from ..utils.color import interpolate_color
@@ -110,7 +110,7 @@ class Mobject(Container):
def save_image(self, name=None):
self.get_image().save(
- os.path.join(dirs.VIDEO_DIR, (name or str(self)) + ".png")
+ os.path.join(config['VIDEO_DIR'], (name or str(self)) + ".png")
)
def copy(self):
diff --git a/manim/mobject/svg/svg_mobject.py b/manim/mobject/svg/svg_mobject.py
index 9d569d409..321b689b7 100644
--- a/manim/mobject/svg/svg_mobject.py
+++ b/manim/mobject/svg/svg_mobject.py
@@ -428,4 +428,4 @@ class VMobjectFromSVGPathstring(VMobject):
return result
def get_original_path_string(self):
- return self.path_string
\ No newline at end of file
+ return self.path_string
diff --git a/manim/mobject/svg/text_mobject.py b/manim/mobject/svg/text_mobject.py
index f229a95ba..359271790 100644
--- a/manim/mobject/svg/text_mobject.py
+++ b/manim/mobject/svg/text_mobject.py
@@ -5,7 +5,7 @@ import hashlib
import cairo
from ...constants import *
-from ... import dirs
+from ...config import config
from ...container.container import Container
from ...logger import logger
from ...mobject.geometry import Dot, Rectangle
@@ -96,7 +96,7 @@ class Text(SVGMobject):
def get_space_width(self):
size = self.size * 10
- dir_name = dirs.TEXT_DIR
+ dir_name = config['TEXT_DIR']
file_name = os.path.join(dir_name, "space") + '.svg'
surface = cairo.SVGSurface(file_name, 600, 400)
@@ -292,7 +292,7 @@ class Text(SVGMobject):
if NOT_SETTING_FONT_MSG != '':
logger.warning(NOT_SETTING_FONT_MSG)
- dir_name = dirs.TEXT_DIR
+ dir_name = config['TEXT_DIR']
hash_name = self.text2hash()
file_name = os.path.join(dir_name, hash_name)+'.svg'
if os.path.exists(file_name):
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.py
index e354d9ce3..81335047e 100644
--- a/manim/mobject/types/vectorized_mobject.py
+++ b/manim/mobject/types/vectorized_mobject.py
@@ -973,4 +973,4 @@ class DashedVMobject(VMobject):
])
# Family is already taken care of by get_subcurve
# implementation
- self.match_style(vmobject, family=False)
\ No newline at end of file
+ self.match_style(vmobject, family=False)
diff --git a/manim/mobject/vector_field.py b/manim/mobject/vector_field.py
index 774b753ee..cc7735370 100644
--- a/manim/mobject/vector_field.py
+++ b/manim/mobject/vector_field.py
@@ -27,8 +27,8 @@ DEFAULT_SCALAR_FIELD_COLORS = [BLUE_E, GREEN, YELLOW, RED]
def get_colored_background_image(scalar_field_func,
number_to_rgb_func,
- pixel_height=DEFAULT_PIXEL_HEIGHT,
- pixel_width=DEFAULT_PIXEL_WIDTH):
+ pixel_height=PIXEL_HEIGHT,
+ pixel_width=PIXEL_WIDTH):
ph = pixel_height
pw = pixel_width
fw = FRAME_WIDTH
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
index ce24579c4..b69e2c3aa 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -44,21 +44,21 @@ class Scene(Container):
"""
CONFIG = {
"camera_class": Camera,
- "camera_config": {},
- "file_writer_config": {},
- "skip_animations": False,
+ "CAMERA_CONFIG": {},
+ "FILE_WRITER_CONFIG": {},
+ "SKIP_ANIMATIONS": False,
"always_update_mobjects": False,
"random_seed": 0,
- "start_at_animation_number": None,
- "end_at_animation_number": None,
- "leave_progress_bars": False,
+ "FROM_ANIMATION_NUMBER": None,
+ "UPTO_ANIMATION_NUMBER": None,
+ "LEAVE_PROGRESS_BARS": False,
}
def __init__(self, **kwargs):
Container.__init__(self, **kwargs)
- self.camera = self.camera_class(**self.camera_config)
+ self.camera = self.camera_class(**self.CAMERA_CONFIG)
self.file_writer = SceneFileWriter(
- self, **self.file_writer_config,
+ self, **self.FILE_WRITER_CONFIG,
)
self.mobjects = []
@@ -66,7 +66,7 @@ class Scene(Container):
self.foreground_mobjects = []
self.num_plays = 0
self.time = 0
- self.original_skipping_status = self.skip_animations
+ self.original_skipping_status = self.SKIP_ANIMATIONS
if self.random_seed is not None:
random.seed(self.random_seed)
np.random.seed(self.random_seed)
@@ -238,7 +238,7 @@ class Scene(Container):
**kwargs
"""
- if self.skip_animations and not ignore_skipping:
+ if self.SKIP_ANIMATIONS and not ignore_skipping:
return
if mobjects is None:
mobjects = list_update(
@@ -679,14 +679,14 @@ class Scene(Container):
ProgressDisplay
The CommandLine Progress Bar.
"""
- if self.skip_animations and not override_skip_animations:
+ if self.SKIP_ANIMATIONS and not override_skip_animations:
times = [run_time]
else:
step = 1 / self.camera.frame_rate
times = np.arange(0, run_time, step)
time_progression = ProgressDisplay(
times, total=n_iterations,
- leave=self.leave_progress_bars,
+ leave=self.LEAVE_PROGRESS_BARS,
ascii=False if platform.system() != 'Windows' else True
)
return time_progression
@@ -824,12 +824,12 @@ class Scene(Container):
raises an EndSceneEarlyException if they don't correspond.
"""
- if self.start_at_animation_number:
- if self.num_plays == self.start_at_animation_number:
- self.skip_animations = False
- if self.end_at_animation_number:
- if self.num_plays >= self.end_at_animation_number:
- self.skip_animations = True
+ if self.FROM_ANIMATION_NUMBER:
+ if self.num_plays == self.FROM_ANIMATION_NUMBER:
+ self.SKIP_ANIMATIONS = False
+ if self.UPTO_ANIMATION_NUMBER:
+ if self.num_plays >= self.UPTO_ANIMATION_NUMBER:
+ self.SKIP_ANIMATIONS = True
raise EndSceneEarlyException()
def handle_play_like_call(func):
@@ -854,7 +854,7 @@ class Scene(Container):
"""
def wrapper(self, *args, **kwargs):
self.update_skipping_status()
- allow_write = not self.skip_animations
+ allow_write = not self.SKIP_ANIMATIONS
self.file_writer.begin_animation(allow_write)
func(self, *args, **kwargs)
self.file_writer.end_animation(allow_write)
@@ -927,7 +927,7 @@ class Scene(Container):
self.mobjects_from_last_animation = [
anim.mobject for anim in animations
]
- if self.skip_animations:
+ if self.SKIP_ANIMATIONS:
# TODO, run this call in for each animation?
self.update_mobjects(self.get_run_time(animations))
else:
@@ -1070,7 +1070,7 @@ class Scene(Container):
if stop_condition is not None and stop_condition():
time_progression.close()
break
- elif self.skip_animations:
+ elif self.SKIP_ANIMATIONS:
# Do nothing
return self
else:
@@ -1109,8 +1109,8 @@ class Scene(Container):
Scene
The Scene, with skipping turned on.
"""
- self.original_skipping_status = self.skip_animations
- self.skip_animations = True
+ self.original_skipping_status = self.SKIP_ANIMATIONS
+ self.SKIP_ANIMATIONS = True
return self
def revert_to_original_skipping_status(self):
@@ -1125,7 +1125,7 @@ class Scene(Container):
The Scene, with the original skipping status.
"""
if hasattr(self, "original_skipping_status"):
- self.skip_animations = self.original_skipping_status
+ self.SKIP_ANIMATIONS = self.original_skipping_status
return self
def add_frames(self, *frames):
@@ -1139,7 +1139,7 @@ class Scene(Container):
"""
dt = 1 / self.camera.frame_rate
self.increment_time(len(frames) * dt)
- if self.skip_animations:
+ if self.SKIP_ANIMATIONS:
return
for frame in frames:
self.file_writer.write_frame(frame)
@@ -1160,7 +1160,7 @@ class Scene(Container):
gain :
"""
- if self.skip_animations:
+ if self.SKIP_ANIMATIONS:
return
time = self.get_time() + time_offset
self.file_writer.add_sound(sound_file, time, gain, **kwargs)
diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.py
index 820e25ea8..3444fa162 100644
--- a/manim/scene/scene_file_writer.py
+++ b/manim/scene/scene_file_writer.py
@@ -9,10 +9,7 @@ import datetime
from PIL import Image
from ..constants import FFMPEG_BIN
-from ..constants import STREAMING_IP
-from ..constants import STREAMING_PORT
-from ..constants import STREAMING_PROTOCOL
-from .. import dirs
+from ..config import config
from ..logger import logger
from ..utils.config_ops import digest_config
from ..utils.file_ops import guarantee_existence
@@ -38,17 +35,15 @@ class SceneFileWriter(object):
The file-type extension of the outputted video.
"""
CONFIG = {
- "write_to_movie": False,
- "save_pngs": False,
- "png_mode": "RGBA",
- "save_last_frame": False,
- "movie_file_extension": ".mp4",
- "gif_file_extension": ".gif",
- # Previous output_file_name
- # TODO, address this in extract_scene et. al.
- "file_name": None,
- "input_file_path": "", # ??
- "output_directory": None,
+ "WRITE_TO_MOVIE": False,
+ "SAVE_PNGS": False,
+ "PNG_MODE": "RGBA",
+ "SAVE_LAST_FRAME": False,
+ "MOVIE_FILE_EXTENSION": ".mp4",
+ "GIF_FILE_EXTENSION": ".gif",
+ "OUTPUT_FILE": None,
+ "INPUT_FILE": "",
+ "OUTPUT_DIRECTORY": None,
}
def __init__(self, scene, **kwargs):
@@ -66,14 +61,12 @@ class SceneFileWriter(object):
files will be written to and read from (within MEDIA_DIR).
If they don't already exist, they will be created.
"""
- module_directory = self.output_directory or self.get_default_module_directory()
- scene_name = self.file_name or self.get_default_scene_name()
- #print("1")
- #print(dirs.MEDIA_DIR)
- if self.save_last_frame or self.save_pngs:
- if dirs.MEDIA_DIR != "":
+ module_directory = self.OUTPUT_DIRECTORY or self.get_default_module_directory()
+ scene_name = self.OUTPUT_FILE or self.get_default_scene_name()
+ if self.SAVE_LAST_FRAME or self.SAVE_PNGS:
+ if config['MEDIA_DIR'] != "":
image_dir = guarantee_existence(os.path.join(
- dirs.MEDIA_DIR,
+ config['MEDIA_DIR'],
"images",
module_directory,
))
@@ -81,23 +74,24 @@ class SceneFileWriter(object):
image_dir,
add_extension_if_not_present(scene_name, ".png")
)
- if self.write_to_movie:
- if dirs.VIDEO_DIR != "":
+
+ if config['WRITE_TO_MOVIE']:
+ if config['VIDEO_DIR']:
movie_dir = guarantee_existence(os.path.join(
- dirs.VIDEO_DIR,
+ config['VIDEO_DIR'],
module_directory,
self.get_resolution_directory(),
))
self.movie_file_path = os.path.join(
movie_dir,
add_extension_if_not_present(
- scene_name, self.movie_file_extension
+ scene_name, self.MOVIE_FILE_EXTENSION
)
)
self.gif_file_path = os.path.join(
movie_dir,
add_extension_if_not_present(
- scene_name, self.gif_file_extension
+ scene_name, self.GIF_FILE_EXTENSION
)
)
self.partial_movie_directory = guarantee_existence(os.path.join(
@@ -116,7 +110,7 @@ class SceneFileWriter(object):
str
The name of the directory.
"""
- filename = os.path.basename(self.input_file_path)
+ filename = os.path.basename(self.INPUT_FILE)
root, _ = os.path.splitext(filename)
return root
@@ -132,10 +126,10 @@ class SceneFileWriter(object):
str
The default scene name.
"""
- if self.file_name is None:
- return self.scene.__class__.__name__
+ if self.OUTPUT_FILE:
+ return self.OUTPUT_FILE
else:
- return self.file_name
+ return self.scene.__class__.__name__
def get_resolution_directory(self):
"""
@@ -146,7 +140,7 @@ class SceneFileWriter(object):
that immediately contains the video file will be
480p15.
The file structure should look something like:
-
+
MEDIA_DIR
|--Tex
|--texts
@@ -172,7 +166,7 @@ class SceneFileWriter(object):
written to.
It is usually named "images", but can be changed by changing
"image_file_path".
-
+
Returns
-------
str
@@ -183,7 +177,7 @@ class SceneFileWriter(object):
def get_next_partial_movie_path(self):
"""
Manim renders each play-like call in a short partial
- video file. All such files are then concatenated with
+ video file. All such files are then concatenated with
the help of FFMPEG.
This method returns the path of the next partial movie.
@@ -197,7 +191,7 @@ class SceneFileWriter(object):
self.partial_movie_directory,
"{:05}{}".format(
self.scene.num_plays,
- self.movie_file_extension,
+ self.MOVIE_FILE_EXTENSION,
)
)
return result
@@ -230,18 +224,18 @@ class SceneFileWriter(object):
time=None,
gain_to_background=None):
"""
- This method adds an audio segment from an
+ This method adds an audio segment from an
AudioSegment type object and suitable parameters.
-
+
Parameters
----------
new_segment : AudioSegment
The audio segment to add
-
+
time : int, float, optional
the timestamp at which the
sound should be added.
-
+
gain_to_background : optional
The gain of the segment from the background.
"""
@@ -276,7 +270,7 @@ class SceneFileWriter(object):
----------
sound_file : str
The path to the sound file.
-
+
time : float or int, optional
The timestamp at which the audio should be added.
@@ -305,7 +299,7 @@ class SceneFileWriter(object):
allow_write : bool, optional
Whether or not to write to a video file.
"""
- if self.write_to_movie and allow_write:
+ if self.WRITE_TO_MOVIE and allow_write:
self.open_movie_pipe()
def end_animation(self, allow_write=False):
@@ -318,7 +312,7 @@ class SceneFileWriter(object):
allow_write : bool, optional
Whether or not to write to a video file.
"""
- if self.write_to_movie and allow_write:
+ if self.WRITE_TO_MOVIE and allow_write:
self.close_movie_pipe()
def write_frame(self, frame):
@@ -331,9 +325,9 @@ class SceneFileWriter(object):
frame : np.array
Pixel array of the frame.
"""
- if self.write_to_movie:
+ if self.WRITE_TO_MOVIE:
self.writing_process.stdin.write(frame.tostring())
- if self.save_pngs:
+ if self.SAVE_PNGS:
path, extension = os.path.splitext(self.image_file_path)
Image.fromarray(frame).save(f'{path}{self.frame_count}{extension}')
self.frame_count += 1
@@ -376,11 +370,11 @@ class SceneFileWriter(object):
If save_last_frame is True, saves the last
frame in the default image directory.
"""
- if self.write_to_movie:
+ if self.WRITE_TO_MOVIE:
if hasattr(self, "writing_process"):
self.writing_process.terminate()
self.combine_movie_files()
- if self.save_last_frame:
+ if self.SAVE_LAST_FRAME:
self.scene.update_frame(ignore_skipping=True)
self.save_final_image(self.scene.get_image())
@@ -391,8 +385,7 @@ class SceneFileWriter(object):
buffer.
"""
file_path = self.get_next_partial_movie_path()
- temp_file_path = os.path.splitext(file_path)[0] + '_temp' + self.movie_file_extension
-
+ temp_file_path = os.path.splitext(file_path)[0] + '_temp' + self.MOVIE_FILE_EXTENSION
self.partial_movie_file_path = file_path
self.temp_partial_movie_file_path = temp_file_path
@@ -413,7 +406,7 @@ class SceneFileWriter(object):
]
# TODO, the test for a transparent background should not be based on
# the file extension.
- if self.movie_file_extension == ".mov":
+ if self.MOVIE_FILE_EXTENSION == ".mov":
# This is if the background of the exported
# video should be transparent.
command += [
@@ -455,12 +448,12 @@ class SceneFileWriter(object):
# single piece.
kwargs = {
"remove_non_integer_files": True,
- "extension": self.movie_file_extension,
+ "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
+ if self.scene.FROM_ANIMATION_NUMBER is not None:
+ kwargs["min_index"] = self.scene.FROM_ANIMATION_NUMBER
+ if self.scene.UPTO_ANIMATION_NUMBER is not None:
+ kwargs["max_index"] = self.scene.UPTO_ANIMATION_NUMBER
else:
kwargs["remove_indices_greater_than"] = self.scene.num_plays - 1
partial_movie_files = get_sorted_integer_files(
@@ -502,7 +495,7 @@ class SceneFileWriter(object):
if self.includes_sound:
sound_file_path = movie_file_path.replace(
- self.movie_file_extension, ".wav"
+ self.MOVIE_FILE_EXTENSION, ".wav"
)
# Makes sure sound file length will match video file
self.add_audio_segment(AudioSegment.silent(0))
diff --git a/manim/scene/three_d_scene.py b/manim/scene/three_d_scene.py
index 6cfeff671..bbb226d59 100644
--- a/manim/scene/three_d_scene.py
+++ b/manim/scene/three_d_scene.py
@@ -1,7 +1,7 @@
from ..animation.transform import ApplyMethod
from ..camera.three_d_camera import ThreeDCamera
from ..constants import DEGREES
-from ..constants import PRODUCTION_QUALITY_CAMERA_CONFIG
+from ..config import config
from ..mobject.coordinate_systems import ThreeDAxes
from ..mobject.geometry import Line
from ..mobject.three_dimensions import Sphere
@@ -278,7 +278,7 @@ class SpecialThreeDScene(ThreeDScene):
def __init__(self, **kwargs):
digest_config(self, kwargs)
- if self.camera_config["pixel_width"] == PRODUCTION_QUALITY_CAMERA_CONFIG["pixel_width"]:
+ if self.camera_config["pixel_width"] == config['CAMERA_CONFIG']['PIXEL_WIDTH']:
config = {}
else:
config = self.low_quality_config
@@ -349,4 +349,4 @@ class SpecialThreeDScene(ThreeDScene):
"""
self.set_camera_orientation(
**self.default_angled_camera_position
- )
\ No newline at end of file
+ )
diff --git a/manim/scene/zoomed_scene.py b/manim/scene/zoomed_scene.py
index 94d6120f6..5c88794b1 100644
--- a/manim/scene/zoomed_scene.py
+++ b/manim/scene/zoomed_scene.py
@@ -141,4 +141,4 @@ class ZoomedScene(MovingCameraScene):
return fdiv(
self.zoomed_camera.frame.get_height(),
self.zoomed_display.get_height()
- )
\ No newline at end of file
+ )
diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.py
index e3951187d..72b3f3a20 100644
--- a/manim/utils/tex_file_writing.py
+++ b/manim/utils/tex_file_writing.py
@@ -3,9 +3,9 @@ import hashlib
from pathlib import Path
+from ..config import config
from ..constants import TEX_TEXT_TO_REPLACE
from ..constants import TEX_USE_CTEX
-from .. import dirs
from ..logger import logger
def tex_hash(expression, template_tex_file_body):
@@ -24,7 +24,7 @@ def tex_to_svg_file(expression, template_tex_file_body):
def generate_tex_file(expression, template_tex_file_body):
result = os.path.join(
- dirs.TEX_DIR,
+ config['TEX_DIR'],
tex_hash(expression, template_tex_file_body)
) + ".tex"
if not os.path.exists(result):
@@ -43,7 +43,7 @@ def tex_to_dvi(tex_file):
result = tex_file.replace(".tex", ".dvi" if not TEX_USE_CTEX else ".xdv")
result = Path(result).as_posix()
tex_file = Path(tex_file).as_posix()
- tex_dir = Path(dirs.TEX_DIR).as_posix()
+ tex_dir = Path(config['TEX_DIR']).as_posix()
if not os.path.exists(result):
commands = [
"latex",
diff --git a/setup.py b/setup.py
index 15a0c90a3..ea2d3cf6c 100755
--- a/setup.py
+++ b/setup.py
@@ -28,4 +28,5 @@ setup(
"pyreadline; sys_platform == 'win32'",
"rich",
],
+ data_files=[('manim/', ['manim/manim.cfg'])],
)