Repository: ManimCommunity/manim

Issue:
LinearTransformationScene crashes on multiple transformations
## Description of bug / unexpected behavior
<!-- Add a clear and concise description of the problem you encountered. -->
When transforming a LinearTransformationScene (i.e. using `self.apply_matrix` or `self.wait`), the `self.moving_mobjects` is changed in such a way that upcoming calls to `self.apply_function` will cause the rendering to crash. This seems to be a problem with `VectorScene`:s `get_moving_mobject_movement` function not being able to handle unexpected values for `self.moving_mobjects`, hence "resetting" it to equal `[]` seems to solve the problem (although I don't know what side-effects that might have).

A similar problem is described on [StackOverflow](https://stackoverflow.com/questions/67543673/multiple-linear-non-linear-transformations-in-manim), and the same quick-fix seems to work there as well.

## Expected behavior
<!-- Add a clear and concise description of what you expected to happen. -->
The expected result is something along the lines of what is produced by the following code:
```py
from manim import *

class LinearTransformationSceneExample(LinearTransformationScene):
    def construct(self):
        matrix = [[0, -1], [1, 0]]
        self.apply_matrix(matrix)
        self.wait()
        self.moving_mobjects = [] # Quick-fix
        self.apply_inverse(matrix)
```


## How to reproduce the issue
<!-- Provide a piece of code illustrating the undesired behavior. -->

<details><summary>Code for reproducing the problem</summary>

```py
from manim import *

class LinearTransformationSceneExample(LinearTransformationScene):
    def construct(self):
        matrix = [[0, -1], [1, 0]]
        self.apply_matrix(matrix)
        self.wait()
        self.apply_inverse(matrix)
```

</details>

## Logs
<details><summary>Terminal output</summary>
<!-- Add "-v DEBUG" when calling manim to generate more detailed logs -->

```
Manim Community v0.7.0

[06/21/21 16:32:33] DEBUG    Hashing ...                                                                                                                                                                            hashing.py:305
                    DEBUG    Hashing done in 0.154551 s.                                                                                                                                                            hashing.py:317
                    DEBUG    Hash generated :  3163782288_1461710331_2020087857                                                                                                                                     hashing.py:320
                    INFO     Animation 0 : Using cached data (hash : 3163782288_1461710331_2020087857)                                                                                                       cairo_renderer.py:100
                    DEBUG    List of the first few animation hashes of the scene: ['3163782288_1461710331_2020087857']                                                                                       cairo_renderer.py:108
                    DEBUG    Animation with empty mobject                                                                                                                                                         animation.py:151
                    DEBUG    Hashing ...                                                                                                                                                                            hashing.py:305
                    DEBUG    Hashing done in 0.140771 s.                                                                                                                                                            hashing.py:317
                    DEBUG    Hash generated :  607903841_3466882479_540558082                                                                                                                                       hashing.py:320
                    INFO     Animation 1 : Using cached data (hash : 607903841_3466882479_540558082)                                                                                                         cairo_renderer.py:100
                    DEBUG    List of the first few animation hashes of the scene: ['3163782288_1461710331_2020087857', '607903841_3466882479_540558082']                                                     cairo_renderer.py:108
╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮
│ /usr/local/lib/python3.8/site-packages/manim/cli/render/commands.py:157 in render                │
│                                                                                                  │
│   154 │   │   for SceneClass in scene_classes_from_file(file):                                   │
│   155 │   │   │   try:                                                                           │
│   156 │   │   │   │   scene = SceneClass()                                                       │
│ ❱ 157 │   │   │   │   scene.render()                                                             │
│   158 │   │   │   except Exception:                                                              │
│   159 │   │   │   │   error_console.print_exception()                                            │
│   160 │   │   │   │   sys.exit(1)                                                                │
│                                                                                                  │
│ /usr/local/lib/python3.8/site-packages/manim/scene/scene.py:201 in render                        │
│                                                                                                  │
│    198 │   │   """                                                                               │
│    199 │   │   self.setup()                                                                      │
│    200 │   │   try:                                                                              │
│ ❱  201 │   │   │   self.construct()                                                              │
│    202 │   │   except EndSceneEarlyException:                                                    │
│    203 │   │   │   pass                                                                          │
│    204 │   │   except RerunSceneException as e:                                                  │
│                                                                                                  │
│ /workspaces/manim-devcontainer/ltse.py:9 in construct                                            │
│                                                                                                  │
│   6 │   │   self.apply_matrix(matrix)                                                            │
│   7 │   │   self.wait()                                                                          │
│   8 │   │   #self.moving_mobjects = []                                                           │
│ ❱ 9 │   │   self.apply_inverse(matrix)                                                           │
│                                                                                                  │
│ /usr/local/lib/python3.8/site-packages/manim/scene/vector_space_scene.py:1047 in apply_inverse   │
│                                                                                                  │
│   1044 │   │   **kwargs                                                                          │
│   1045 │   │   │   Any valid keyword argument of self.apply_matrix()                             │
│   1046 │   │   """                                                                               │
│ ❱ 1047 │   │   self.apply_matrix(np.linalg.inv(matrix), **kwargs)                                │
│   1048 │                                                                                         │
│   1049 │   def apply_transposed_matrix(self, transposed_matrix, **kwargs):                       │
│   1050 │   │   """                                                                               │
│                                                                                                  │
│ /usr/local/lib/python3.8/site-packages/manim/scene/vector_space_scene.py:1032 in apply_matrix    │
│                                                                                                  │
│   1029 │   │   **kwargs                                                                          │
│   1030 │   │   │   Any valid keyword argument of self.apply_transposed_matrix()                  │
│   1031 │   │   """                                                                               │
│ ❱ 1032 │   │   self.apply_transposed_matrix(np.array(matrix).T, **kwargs)                        │
│   1033 │                                                                                         │
│   1034 │   def apply_inverse(self, matrix, **kwargs):                                            │
│   1035 │   │   """                                                                               │
│                                                                                                  │
│ /usr/local/lib/python3.8/site-packages/manim/scene/vector_space_scene.py:1068 in                 │
│ apply_transposed_matrix                                                                          │
│                                                                                                  │
│   1065 │   │   │   │   [angle_of_vector(func(RIGHT)), angle_of_vector(func(UP)) - np.pi / 2]     │
│   1066 │   │   │   )                                                                             │
│   1067 │   │   │   kwargs["path_arc"] = net_rotation                                             │
│ ❱ 1068 │   │   self.apply_function(func, **kwargs)                                               │
│   1069 │                                                                                         │
│   1070 │   def apply_inverse_transpose(self, t_matrix, **kwargs):                                │
│   1071 │   │   """                                                                               │
│                                                                                                  │
│ /usr/local/lib/python3.8/site-packages/manim/scene/vector_space_scene.py:1131 in apply_function  │
│                                                                                                  │
│   1128 │   │   │   + [                                                                           │
│   1129 │   │   │   │   self.get_vector_movement(function),                                       │
│   1130 │   │   │   │   self.get_transformable_label_movement(),                                  │
│ ❱ 1131 │   │   │   │   self.get_moving_mobject_movement(function),                               │
│   1132 │   │   │   ]                                                                             │
│   1133 │   │   │   + [Animation(f_mob) for f_mob in self.foreground_mobjects]                    │
│   1134 │   │   │   + added_anims                                                                 │
│                                                                                                  │
│ /usr/local/lib/python3.8/site-packages/manim/scene/vector_space_scene.py:971 in                  │
│ get_moving_mobject_movement                                                                      │
│                                                                                                  │
│    968 │   │   Animation                                                                         │
│    969 │   │   │   The animation of the movement.                                                │
│    970 │   │   """                                                                               │
│ ❱  971 │   │   for m in self.moving_mobjects:                                                    │
│    972 │   │   │   if m.target is None:                                                          │
│    973 │   │   │   │   m.target = m.copy()                                                       │
│    974 │   │   │   target_point = func(m.get_center())                                           │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
TypeError: 'NoneType' object is not iterable
```

<!-- Insert screenshots here (only when absolutely necessary, we prefer copy/pasted output!) -->

</details>


## System specifications

<details><summary>System Details</summary>

- OS: Debian 10 through Docker Desktop (WSL2) on Windows 10 (using a modified version of [this Dockerfile](https://github.com/ManimCommunity/manim/blob/a8a37882daf7f7fc7dfb212e4d75996a623beafc/docker/Dockerfile))
- RAM: 16GB
- Python version: 3.8.10
- Installed modules:
```
alabaster                     0.7.12
Babel                         2.9.1
beautifulsoup4                4.9.3
certifi                       2021.5.30
chardet                       4.0.0
click                         8.0.1
click-default-group           1.2.2
cloup                         0.7.1
colorama                      0.4.4
colour                        0.1.5
commonmark                    0.9.1
decorator                     5.0.9
docutils                      0.17.1
furo                          2021.4.11b34
glcontext                     2.3.4
idna                          2.10
imagesize                     1.2.0
Jinja2                        3.0.1
manim                         0.7.0
ManimPango                    0.3.0
mapbox-earcut                 0.12.10
MarkupSafe                    2.0.1
moderngl                      5.6.4
moderngl-window               2.3.0
multipledispatch              0.6.0
networkx                      2.5
numpy                         1.20.3
packaging                     20.9
Pillow                        8.2.0
pip                           21.1.2
pycairo                       1.20.1
pydub                         0.25.1
pyglet                        1.5.17
Pygments                      2.9.0
pyparsing                     2.4.7
pyrr                          0.10.3
pytz                          2021.1
recommonmark                  0.7.1
requests                      2.25.1
rich                          10.3.0
scipy                         1.6.3
setuptools                    57.0.0
six                           1.16.0
snowballstemmer               2.1.0
soupsieve                     2.2.1
Sphinx                        3.5.3
sphinx-copybutton             0.3.3
sphinxcontrib-applehelp       1.0.2
sphinxcontrib-devhelp         1.0.2
sphinxcontrib-htmlhelp        2.0.0
sphinxcontrib-jsmath          1.0.1
sphinxcontrib-qthelp          1.0.3
sphinxcontrib-serializinghtml 1.1.5
sphinxext-opengraph           0.4.2
tqdm                          4.61.1
urllib3                       1.26.5
watchdog                      2.1.2
wheel                         0.36.2
```
</details>

<details><summary>LaTeX details</summary>

+ LaTeX distribution: pdfTeX 3.141592653-2.6-1.40.22 (TeX Live 2021)
+ Installed LaTeX packages:
```
i adobemapping: Adobe cmap and pdfmapping files
i amscls: AMS document classes for LaTeX
i amsfonts: TeX fonts from the American Mathematical Society
i amsmath: AMS mathematical facilities for LaTeX
i arphic: Arphic (Chinese) font packages
i atbegshi: Execute stuff at \shipout time
i atveryend: Hooks at the very end of a document
i auxhook: Hooks for auxiliary files
i babel: Multilingual support for LaTeX, LuaLaTeX, XeLaTeX, and Plain TeX
i babel-english: Babel support for English
i beamer: A LaTeX class for producing presentations and slides
i bibtex: Process bibliographies for LaTeX, etc
i bibtex.x86_64-linux: x86_64-linux files of bibtex
i bigintcalc: Integer calculations on very large numbers
i bitset: Handle bit-vector datatype
i cbfonts-fd: LaTeX font description files for the CB Greek fonts
i cjk: CJK language support
i cjkpunct: Adjust locations and kerning of CJK punctuation marks
i cm: Computer Modern fonts
i cm-super: CM-Super family of fonts
i cns: Chinese/Japanese/Korean bitmap fonts
i collection-basic: Essential programs and files
i colorprofiles: Collection of free ICC profiles
i ctablestack: Catcode table stable support
i ctex: LaTeX classes and packages for Chinese typesetting
i dehyph: German hyphenation patterns for traditional orthography
i doublestroke: Typeset mathematical double stroke symbols
i dvipdfmx: An extended version of dvipdfm
i dvipdfmx.x86_64-linux: x86_64-linux files of dvipdfmx
i dvips: A DVI to PostScript driver
i dvips.x86_64-linux: x86_64-linux files of dvips
i dvisvgm: Convert DVI, EPS, and PDF files to Scalable Vector Graphics format (SVG)
i dvisvgm.x86_64-linux: x86_64-linux files of dvisvgm
i ec: Computer modern fonts in T1 and TS1 encodings
i enctex: A TeX extension that translates input on its way into TeX
i epstopdf-pkg: Call epstopdf "on the fly"
i etex: An extended version of TeX, from the NTS project
i etex-pkg: E-TeX support package
i etexcmds: Avoid name clashes with e-TeX commands
i etoolbox: e-TeX tools for LaTeX
i euenc: Unicode font encoding definitions for XeTeX
i everyhook: Hooks for standard TeX token lists
i everysel: Provides hooks into \selectfont
i everyshi: Take action at every \shipout
i fandol: Four basic fonts for Chinese typesetting
i firstaid: First aid for external LaTeX files and packages that need updating
i fonts-tlwg: Thai fonts for LaTeX from TLWG
i fontspec: Advanced font selection in XeLaTeX and LuaLaTeX
i fp: Fixed point arithmetic
i frcursive: French cursive hand fonts
i fundus-calligra: Support for the calligra font in LaTeX documents
i garuda-c90: TeX support (from CJK) for the garuda font
i geometry: Flexible and complete interface to document dimensions
i gettitlestring: Clean up title references
i glyphlist: Adobe Glyph List and TeX extensions
i gnu-freefont: A Unicode font, with rather wide coverage
i graphics: The LaTeX standard graphics bundle
i graphics-cfg: Sample configuration files for LaTeX color and graphics
i graphics-def: Colour and graphics option files
i hycolor: Implements colour for packages hyperref and bookmark
i hyperref: Extensive support for hypertext in LaTeX
i hyph-utf8: Hyphenation patterns expressed in UTF-8
i hyphen-base: core hyphenation support files
i hyphenex: US English hyphenation exceptions file
i ifplatform: Conditionals to test which platform is being used
i iftex: Am I running under pdfTeX, XeTeX or LuaTeX?
i infwarerr: Complete set of information/warning/error message macros
i intcalc: Expandable arithmetic operations with integers
i jknapltx: Miscellaneous packages by Joerg Knappen
i knuth-lib: Core TeX and Metafont sources from Knuth
i knuth-local: Knuth's local information
i kpathsea: Path searching library for TeX-related files
i kpathsea.x86_64-linux: x86_64-linux files of kpathsea
i kvdefinekeys: Define keys for use in the kvsetkeys package
i kvoptions: Key value format for package options
i kvsetkeys: Key value parser with default handler support
i l3backend: LaTeX3 backend drivers
i l3kernel: LaTeX3 programming conventions
i l3packages: High-level LaTeX3 concepts
i latex: A TeX macro package that defines LaTeX
i latex-base-dev: Development pre-release of the LaTeX kernel
i latex-bin: LaTeX executables and man pages
i latex-bin.x86_64-linux: x86_64-linux files of latex-bin
i latex-firstaid-dev: Development pre-release of the LaTeX firstaid package
i latex-fonts: A collection of fonts used in LaTeX distributions
i latexconfig: configuration files for LaTeX-related formats
i letltxmacro: Let assignment for LaTeX macros
i lm: Latin modern fonts in outline formats
i ltxcmds: Some LaTeX kernel commands for general use
i lua-alt-getopt: Process application arguments the same way as getopt_long
i luahbtex: LuaTeX with HarfBuzz library for glyph shaping
i luahbtex.x86_64-linux: x86_64-linux files of luahbtex
i lualibs: Additional Lua functions for LuaTeX macro programmers
i luaotfload: OpenType 'loader' for Plain TeX and LaTeX
i luaotfload.x86_64-linux: x86_64-linux files of luaotfload
i luatex: The LuaTeX engine
i luatex.x86_64-linux: x86_64-linux files of luatex
i luatexbase: Basic resource management for LuaTeX code
i luatexja: Typeset Japanese with Lua(La)TeX
i makeindex: Makeindex development sources
i makeindex.x86_64-linux: x86_64-linux files of makeindex
i mathastext: Use the text font in maths mode
i metafont: A system for specifying fonts
i metafont.x86_64-linux: x86_64-linux files of metafont
i mflogo: LaTeX support for Metafont logo fonts
i mfware: Supporting tools for use with Metafont
i mfware.x86_64-linux: x86_64-linux files of mfware
i microtype: Subliminal refinements towards typographical perfection
i modes: A collection of Metafont mode_def's
i mptopdf: mpost to PDF, native MetaPost graphics inclusion
i mptopdf.x86_64-linux: x86_64-linux files of mptopdf
i ms: Various LaTeX packages by Martin Schroder
i norasi-c90: TeX support (from CJK) for the norasi font
i pdfescape: Implements pdfTeX's escape features using TeX or e-TeX
i pdftex: A TeX extension for direct creation of PDF
i pdftex.x86_64-linux: x86_64-linux files of pdftex
i pdftexcmds: LuaTeX support for pdfTeX utility functions
i pgf: Create PostScript and PDF graphics in TeX
i physics: Macros supporting the Mathematics of Physics
i plain: The Plain TeX format
i platex: pLaTeX2e and miscellaneous macros for pTeX
i platex-tools: pLaTeX standard tools bundle
i platex.x86_64-linux: x86_64-linux files of platex
i preview: Extract bits of a LaTeX source for output
i ptex: A TeX system for publishing in Japanese
i ptex-base: Plain TeX format for pTeX and e-pTeX
i ptex-fonts: Fonts for use with pTeX
i ptex.x86_64-linux: x86_64-linux files of ptex
i ragged2e: Alternative versions of "ragged"-type commands
i refcount: Counter operations with label references
i relsize: Set the font size relative to the current font size
i rerunfilecheck: Checksum based rerun checks on auxiliary files
i rsfs: Ralph Smith's Formal Script font
i scheme-infraonly: infrastructure-only scheme (no TeX at all)
i scheme-minimal: minimal scheme (plain only)
i setspace: Set space between lines
i standalone: Compile TeX pictures stand-alone or as part of a document
i stringenc: Converting a string between different encodings
i svn-prov: Subversion variants of \Provides... macros
i tex: A sophisticated typesetting engine
i tex-ini-files: Model TeX format creation files
i tex.x86_64-linux: x86_64-linux files of tex
i texlive-common: TeX Live documentation (common elements)
i texlive-en: TeX Live manual (English)
i texlive-msg-translations: translations of the TeX Live installer and TeX Live Manager
i texlive-scripts: TeX Live infrastructure programs
i texlive-scripts.x86_64-linux: x86_64-linux files of texlive-scripts
i texlive.infra: basic TeX Live infrastructure
i texlive.infra.x86_64-linux: x86_64-linux files of texlive.infra
i tipa: Fonts and macros for IPA phonetics characters
i tlshell: GUI frontend (tcl/tk-based) for tlmgr
i tlshell.x86_64-linux: x86_64-linux files of tlshell
i tools: The LaTeX standard tools bundle
i translator: Easy translation of strings in LaTeX
i ttfutils: convert TrueType to TFM and PK fonts
i ttfutils.x86_64-linux: x86_64-linux files of ttfutils
i uhc: Fonts for the Korean language
i ulem: Package for underlining
i unicode-data: Unicode data and loaders for TeX
i uniquecounter: Provides unlimited unique counter
i uplatex: pLaTeX2e and miscellaneous macros for upTeX
i uplatex.x86_64-linux: x86_64-linux files of uplatex
i uptex: Unicode version of pTeX
i uptex-base: Plain TeX formats and documents for upTeX
i uptex-fonts: Fonts for use with upTeX
i uptex.x86_64-linux: x86_64-linux files of uptex
i url: Verbatim with URL-sensitive line breaks
i wadalab: Wadalab (Japanese) font packages
i wasy: The wasy fonts (Waldi symbol fonts)
i wasysym: LaTeX support for the wasy fonts
i xcjk2uni: Convert CJK characters to Unicode, in pdfTeX
i xcolor: Driver-independent color extensions for LaTeX and pdfLaTeX
i xdvi: A DVI previewer for the X Window System
i xdvi.x86_64-linux: x86_64-linux files of xdvi
i xecjk: Support for CJK documents in XeLaTeX
i xetex: An extended variant of TeX for use with Unicode sources
i xetex.x86_64-linux: x86_64-linux files of xetex
i xetexconfig: crop.cfg for XeLaTeX
i xkeyval: Extension of the keyval package
i xpinyin: Automatically add pinyin to Chinese characters
i xunicode: Generate Unicode characters from accented glyphs
i zapfding: URW "Base 35" font pack for LaTeX
i zhmetrics: TFM subfont files for using Chinese fonts in 8-bit TeX
i zhmetrics-uptex: Chinese font metrics for upTeX
i zhnumber: Typeset Chinese representations of numbers
```
</details>

<details><summary>FFMPEG</summary>

Output of `ffmpeg -version`:

```
ffmpeg version 4.1.6-1~deb10u1 Copyright (c) 2000-2020 the FFmpeg developers
built with gcc 8 (Debian 8.3.0-6)
configuration: --prefix=/usr --extra-version='1~deb10u1' --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --arch=amd64 --enable-gpl --disable-stripping --enable-avresample --disable-filter=resample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librsvg --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared
libavutil      56. 22.100 / 56. 22.100
libavcodec     58. 35.100 / 58. 35.100
libavformat    58. 20.100 / 58. 20.100
libavdevice    58.  5.100 / 58.  5.100
libavfilter     7. 40.101 /  7. 40.101
libavresample   4.  0.  0 /  4.  0.  0
libswscale      5.  3.100 /  5.  3.100
libswresample   3.  3.100 /  3.  3.100
libpostproc    55.  3.100 / 55.  3.100
```
</details>


Discussion:

Resolving patch:
diff --git a/manim/renderer/cairo_renderer.py b/manim/renderer/cairo_renderer.py
--- a/manim/renderer/cairo_renderer.py
+++ b/manim/renderer/cairo_renderer.py
@@ -153,7 +153,7 @@ def update_frame(  # TODO Description in Docstring
         """
         if self.skip_animations and not ignore_skipping:
             return
-        if mobjects is None:
+        if not mobjects:
             mobjects = list_update(
                 scene.mobjects,
                 scene.foreground_mobjects,
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -101,8 +101,8 @@ def __init__(
 
         self.animations = None
         self.stop_condition = None
-        self.moving_mobjects = None
-        self.static_mobjects = None
+        self.moving_mobjects = []
+        self.static_mobjects = []
         self.time_progression = None
         self.duration = None
         self.last_t = None
@@ -906,8 +906,8 @@ def compile_animation_data(self, *animations: Animation, **play_kwargs):
 
         self.last_t = 0
         self.stop_condition = None
-        self.moving_mobjects = None
-        self.static_mobjects = None
+        self.moving_mobjects = []
+        self.static_mobjects = []
 
         if not config.renderer == "opengl":
             if len(self.animations) == 1 and isinstance(self.animations[0], Wait):


Test patch: