A community-maintained Python framework for creating mathematical animations.
Scene better keeps track of all mobjects
Grant Sanderson3dd98abbc317
diff --git a/camera.py b/camera.pyindex e5e41acb6..ebcdfe369 100644--- a/camera.py+++ b/camera.py@@ -79,11 +79,13 @@ class Camera(object):self.adjusted_thickness(mobject.stroke_width))#TODO, more? Call out if it's unknown?- image = Image.fromarray(self.pixel_array, mode = "RGB")++ image = Image.fromarray(self.pixel_array, mode = "RGB")canvas = aggdraw.Draw(image)+for vmobject in vmobjects:self.display_vectorized(vmobject, canvas)- canvas.flush()+ canvas.flush()self.pixel_array[:,:] = np.array(image)diff --git a/extract_scene.py b/extract_scene.pyindex 6b0eb7737..d2943cc37 100644--- a/extract_scene.py+++ b/extract_scene.py@@ -14,7 +14,7 @@ from camera import CameraHELP_MESSAGE = """Usage:- python extract_scene.py <module> [<scene name>] [<arg_string>]+ python extract_scene.py <module> [<scene name>]-p preview in low quality-s show and save picture of last frame@@ -48,7 +48,6 @@ def get_configuration(sys_argv):config = {"file" : None,"scene_name" : "",- "args_extension" : "","camera_config" : PRODUCTION_QUALITY_CAMERA_CONFIG,"preview" : False,"write" : False,@@ -88,8 +87,6 @@ def get_configuration(sys_argv):config["file"] = args[0]if len(args) > 1:config["scene_name"] = args[1]- if len(args) > 2:- config["args_extension"] = " ".join(args[2:])return configdef handle_scene(scene, **config):@@ -137,35 +134,6 @@ def prompt_user_for_choice(name_to_obj):print INVALID_NUMBER_MESSAGEsys.exit()-def get_scene_args(SceneClass, config):- """- Return arguments as a sequence- """- tuplify = lambda x : x if type(x) == tuple else (x,)- args_list = map(tuplify, SceneClass.args_list)- preset_extensions = [- SceneClass.args_to_string(*args)- for args in args_list- ]- if len(args_list) > 0:- num_args = len(args_list[0])- else:- num_args = len(inspect.getargspec(SceneClass.construct).args) - 1-- if num_args == 0:- return [()]- if config["write_all"]:- return args_list- if config["args_extension"] in preset_extensions:- index = preset_extensions.index(config["args_extension"])- return [args_list[index]]- if config["args_extension"] == "" :- if len(args_list) == 1:- return args_list- name_to_args = dict(zip(preset_extensions, args_list))- return prompt_user_for_choice(name_to_args)- return [SceneClass.string_to_args(config["args_extension"])]-def get_scene_classes(scene_names_to_classes, config):if len(scene_names_to_classes) == 0:print NO_SCENE_MESSAGE@@ -189,7 +157,6 @@ def get_module(file_name):last_module = imp.load_module(part, *load_args)return last_module-def main():config = get_configuration(sys.argv)module = get_module(config["file"])@@ -202,17 +169,14 @@ def main():"skip_animations" : config["skip_animations"],}for SceneClass in get_scene_classes(scene_names_to_classes, config):- for args in get_scene_args(SceneClass, config):- scene_kwargs["construct_args"] = tuplify(args)- try:- handle_scene(SceneClass(**scene_kwargs), **config)- play_finish_sound()- except:- print "\n\n"- traceback.print_exc()- print "\n\n"- play_error_sound()-+ try:+ handle_scene(SceneClass(**scene_kwargs), **config)+ play_finish_sound()+ except:+ print "\n\n"+ traceback.print_exc()+ print "\n\n"+ play_error_sound()if __name__ == "__main__":diff --git a/scene/scene.py b/scene/scene.pyindex 90067f3ae..0c7f39d1b 100644--- a/scene/scene.py+++ b/scene/scene.py@@ -44,8 +44,7 @@ class Scene(object):def __str__(self):if hasattr(self, "name"):return self.name- return self.__class__.__name__ + \- self.args_to_string(*self.construct_args)+ return self.__class__.__name__def set_name(self, name):self.name = name@@ -62,6 +61,7 @@ class Scene(object):def update_frame(self, mobjects = None, background = None, **kwargs):if mobjects is None:mobjects = self.mobjects+ kwargs["include_submobjects"] = Falseif background is not None:self.camera.set_image(background)else:@@ -74,26 +74,28 @@ class Scene(object):self.clear()###- def extract_mobjects_with_points(self, *mobjects):+ def extract_mobject_family_members(self, *mobjects):return list(it.chain(*[- m.family_members_with_points()+ m.submobject_family()for m in mobjects]))-- def add(self, *mobjects):+ def add(self, *mobjects_to_add):"""Mobjects will be displayed, from background to foreground,in the order with which they are entered.- Scene class only keeps track of top-level monjects, all- concerns with submobjects is left to animations and subclass- implementations of the construct method.+ Scene class keep track not just of the mobject directly added,+ but also of every family member therein."""- if not all_elements_are_instances(mobjects, Mobject):+ if not all_elements_are_instances(mobjects_to_add, Mobject):raise Exception("Adding something which is not a mobject")- old_mobjects = filter(lambda m : m not in mobjects, self.mobjects)- self.mobjects = old_mobjects + list(mobjects)+ mobjects_to_add = self.extract_mobject_family_members(*mobjects_to_add)+ old_mobjects = filter(+ lambda m : m not in mobjects_to_add,+ self.mobjects+ )+ self.mobjects = old_mobjects + mobjects_to_addreturn selfdef add_mobjects_among(self, values):@@ -105,16 +107,12 @@ class Scene(object):self.add(*mobjects)return self- def remove(self, *mobjects):- if not all_elements_are_instances(mobjects, Mobject):+ def remove(self, *mobjects_to_remove):+ if not all_elements_are_instances(mobjects_to_remove, Mobject):raise Exception("Removing something which is not a mobject")- mobjects = list(it.chain(*[m.submobject_family() for m in mobjects]))- if len(mobjects) == 0:- return+ mobjects_to_remove = self.extract_mobject_family_members(*mobjects_to_remove)self.mobjects = filter(- lambda m : not set(- m.family_members_with_points()- ).issubset(mobjects),+ lambda m : m not in mobjects_to_remove,self.mobjects)return self@@ -155,11 +153,12 @@ class Scene(object):def separate_moving_and_static_mobjects(self, *animations):""""""- moving_mobjects = [anim.mobject for anim in animations]- moving_parts = self.extract_mobjects_with_points(*moving_mobjects)+ moving_mobjects = self.extract_mobject_family_members(+ *[anim.mobject for anim in animations]+ )static_mobjects = filter(- lambda m : m not in moving_parts,- self.extract_mobjects_with_points(*self.mobjects)+ lambda m : m not in moving_mobjects,+ self.mobjects)return moving_mobjects, static_mobjects@@ -207,7 +206,7 @@ class Scene(object):state["last_method"] = state["curr_method"]state["curr_method"] = Nonestate["method_args"] = []-+for arg in args:if isinstance(arg, Animation):compile_method(state)@@ -241,7 +240,7 @@ class Scene(object):for animation in animations:animation.update(t / animation.run_time)self.update_frame(moving_mobjects, static_image)- self.frames.append(self.get_frame())+ self.add_frames(self.get_frame())self.clean_up_animations(*animations)return self@@ -291,9 +290,12 @@ class Scene(object):if self.skip_animations:return selfself.update_frame()- self.frames += [self.get_frame()]*int(duration / self.frame_duration)+ self.add_frames(*[self.get_frame()]*int(duration / self.frame_duration))return self+ def add_frames(self, *frames):+ self.frames += list(frames)+def repeat_frames(self, num):self.frames = self.frames*numreturn self@@ -353,9 +355,9 @@ class Scene(object):'-vcodec','rawvideo','-s', '%dx%d'%(width, height), # size of one frame'-pix_fmt', 'rgb24',- '-r', str(fps), # frames per second- '-i', '-', # The imput comes from a pipe- '-an', # Tells FFMPEG not to expect any audio+ '-r', str(fps), # frames per second+ '-i', '-', # The imput comes from a pipe+ '-an', # Tells FFMPEG not to expect any audio'-vcodec', 'mpeg','-c:v', 'libx264','-pix_fmt', 'yuv420p',@@ -368,20 +370,6 @@ class Scene(object):process.stdin.close()process.wait()- # To list possible args that subclasses have- # Elements should always be a tuple- args_list = []-- # For subclasses to turn args in the above- # list into stings which can be appended to the name- @staticmethod- def args_to_string(*args):- return ""-- @staticmethod- def string_to_args(string):- raise Exception("string_to_args Not Implemented!")-