Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Replaced `self.data["attr"]` and `self.uniforms["attr"]` with `self.attr`. (#1898)

Laith Bahodieb98af84d31f
diff --git a/manim/mobject/number_line.py b/manim/mobject/number_line.py
index e918b66bb..798a524dd 100644
--- a/manim/mobject/number_line.py
+++ b/manim/mobject/number_line.py
@@ -183,7 +183,6 @@ class NumberLine(Line):
self.longer_tick_multiple = longer_tick_multiple
self.exclude_origin_tick = exclude_origin_tick
# visuals
- self.stroke_width = stroke_width
self.rotation = rotation
self.color = color
# tip
@@ -202,7 +201,7 @@ class NumberLine(Line):
super().__init__(
self.x_min * RIGHT,
self.x_max * RIGHT,
- stroke_width=self.stroke_width,
+ stroke_width=stroke_width,
color=self.color,
**kwargs,
)
diff --git a/manim/mobject/opengl_mobject.py b/manim/mobject/opengl_mobject.py
index 2bdf6bf8f..087598c48 100644
--- a/manim/mobject/opengl_mobject.py
+++ b/manim/mobject/opengl_mobject.py
@@ -14,6 +14,7 @@ from .. import config
from ..constants import *
from ..utils.bezier import interpolate
from ..utils.color import *
+from ..utils.config_ops import _Data, _Uniforms
# from ..utils.iterables import batch_by_property
from ..utils.iterables import (
@@ -44,6 +45,15 @@ class OpenGLMobject:
]
shader_folder = ""
+ # _Data and _Uniforms are set as class variables to tell manim how to handle setting/getting these attributes later.
+ points = _Data()
+ bounding_box = _Data()
+ rgbas = _Data()
+
+ is_fixed_in_frame = _Uniforms()
+ gloss = _Uniforms()
+ shadow = _Uniforms()
+
def __init__(
self,
color=WHITE,
@@ -66,6 +76,9 @@ class OpenGLMobject:
model_matrix=None,
**kwargs,
):
+ # getattr in case data/uniforms are already defined in parent classes.
+ self.data = getattr(self, "data", {})
+ self.uniforms = getattr(self, "uniforms", {})
self.color = Color(color)
self.opacity = opacity
@@ -80,7 +93,7 @@ class OpenGLMobject:
self.texture_paths = texture_paths
self.depth_test = depth_test
# If true, the mobject will not get rotated according to camera position
- self.is_fixed_in_frame = is_fixed_in_frame
+ self.is_fixed_in_frame = float(is_fixed_in_frame)
# Must match in attributes of vert shader
# Event listener
self.listen_to_events = listen_to_events
@@ -97,7 +110,6 @@ class OpenGLMobject:
self.model_matrix = model_matrix
self.init_data()
- self.init_uniforms()
self.init_updaters()
# self.init_event_listners()
self.init_points()
@@ -112,18 +124,11 @@ class OpenGLMobject:
return self.__class__.__name__
def init_data(self):
- self.data = {
- "points": np.zeros((0, 3)),
- "bounding_box": np.zeros((3, 3)),
- "rgbas": np.zeros((1, 4)),
- }
-
- def init_uniforms(self):
- self.uniforms = {
- "is_fixed_in_frame": float(self.is_fixed_in_frame),
- "gloss": self.gloss,
- "shadow": self.shadow,
- }
+ """Initializes the ``points``, ``bounding_box`` and ``rgbas`` attributes and groups them into self.data.
+ Subclasses can inherit and overwrite this method to extend `self.data`."""
+ self.points = np.zeros((0, 3))
+ self.bounding_box = np.zeros((3, 3))
+ self.rgbas = np.zeros((1, 4))
def init_colors(self):
self.set_color(self.color, self.opacity)
@@ -244,23 +249,23 @@ class OpenGLMobject:
self.rescale_to_fit(value, 2, stretch=False)
def resize_points(self, new_length, resize_func=resize_array):
- if new_length != len(self.data["points"]):
- self.data["points"] = resize_func(self.data["points"], new_length)
+ if new_length != len(self.points):
+ self.points = resize_func(self.points, new_length)
self.refresh_bounding_box()
return self
def set_points(self, points):
- if len(points) == len(self.data["points"]):
- self.data["points"][:] = points
+ if len(points) == len(self.points):
+ self.points[:] = points
elif isinstance(points, np.ndarray):
- self.data["points"] = points.copy()
+ self.points = points.copy()
else:
- self.data["points"] = np.array(points)
+ self.points = np.array(points)
self.refresh_bounding_box()
return self
def append_points(self, new_points):
- self.data["points"] = np.vstack([self.data["points"], new_points])
+ self.points = np.vstack([self.points, new_points])
self.refresh_bounding_box()
return self
@@ -302,33 +307,33 @@ class OpenGLMobject:
self.set_points(mobject.get_points())
def get_points(self):
- return self.data["points"]
+ return self.points
def clear_points(self):
self.resize_points(0)
def get_num_points(self):
- return len(self.data["points"])
+ return len(self.points)
def get_all_points(self):
if self.submobjects:
return np.vstack([sm.get_points() for sm in self.get_family()])
else:
- return self.get_points()
+ return self.points
def has_points(self):
return self.get_num_points() > 0
def get_bounding_box(self):
if self.needs_new_bounding_box:
- self.data["bounding_box"] = self.compute_bounding_box()
+ self.bounding_box = self.compute_bounding_box()
self.needs_new_bounding_box = False
- return self.data["bounding_box"]
+ return self.bounding_box
def compute_bounding_box(self):
all_points = np.vstack(
[
- self.get_points(),
+ self.points,
*(
mob.get_bounding_box()
for mob in self.get_family()[1:]
@@ -1276,10 +1281,10 @@ class OpenGLMobject:
return self
def get_color(self):
- return rgb_to_hex(self.data["rgbas"][0, :3])
+ return rgb_to_hex(self.rgbas[0, :3])
def get_opacity(self):
- return self.data["rgbas"][0, 3]
+ return self.rgbas[0, 3]
def set_color_by_gradient(self, *colors):
self.set_submobject_colors_by_gradient(*colors)
@@ -1303,19 +1308,19 @@ class OpenGLMobject:
self.set_opacity(1.0 - darkness, recurse=recurse)
def get_gloss(self):
- return self.uniforms["gloss"]
+ return self.gloss
def set_gloss(self, gloss, recurse=True):
for mob in self.get_family(recurse):
- mob.uniforms["gloss"] = gloss
+ mob.gloss = gloss
return self
def get_shadow(self):
- return self.uniforms["shadow"]
+ return self.shadow
def set_shadow(self, shadow, recurse=True):
for mob in self.get_family(recurse):
- mob.uniforms["shadow"] = shadow
+ mob.shadow = shadow
return self
# Background rectangle
@@ -1430,17 +1435,17 @@ class OpenGLMobject:
def get_start(self):
self.throw_error_if_no_points()
- return np.array(self.get_points()[0])
+ return np.array(self.points[0])
def get_end(self):
self.throw_error_if_no_points()
- return np.array(self.get_points()[-1])
+ return np.array(self.points[-1])
def get_start_and_end(self):
return self.get_start(), self.get_end()
def point_from_proportion(self, alpha):
- points = self.get_points()
+ points = self.points
i, subalpha = integer_interpolate(0, len(points) - 1, alpha)
return interpolate(points[i], points[i + 1], subalpha)
@@ -1689,12 +1694,12 @@ class OpenGLMobject:
@affects_shader_info_id
def fix_in_frame(self):
- self.uniforms["is_fixed_in_frame"] = 1.0
+ self.is_fixed_in_frame = 1.0
return self
@affects_shader_info_id
def unfix_from_frame(self):
- self.uniforms["is_fixed_in_frame"] = 0.0
+ self.is_fixed_in_frame = 0.0
return self
@affects_shader_info_id
@@ -1800,7 +1805,7 @@ class OpenGLMobject:
def get_resized_shader_data_array(self, length):
# If possible, try to populate an existing array, rather
# than recreating it each frame
- points = self.data["points"]
+ points = self.points
shader_data = np.zeros(len(points), dtype=self.shader_dtype)
return shader_data
@@ -1942,7 +1947,7 @@ class OpenGLPoint(OpenGLMobject):
return self.artificial_height
def get_location(self):
- return self.get_points()[0].copy()
+ return self.points[0].copy()
def get_bounding_box_point(self, *args, **kwargs):
return self.get_location()
diff --git a/manim/mobject/svg/svg_mobject.py b/manim/mobject/svg/svg_mobject.py
index 3c8c78618..c287bb264 100644
--- a/manim/mobject/svg/svg_mobject.py
+++ b/manim/mobject/svg/svg_mobject.py
@@ -517,7 +517,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
for mob in mobject.family_members_with_points():
if config["renderer"] == "opengl":
- mob.data["points"] = np.dot(mob.data["points"], matrix)
+ mob.points = np.dot(mob.points, matrix)
else:
mob.points = np.dot(mob.points, matrix)
mobject.shift(x * RIGHT + y * UP)
diff --git a/manim/mobject/svg/svg_path.py b/manim/mobject/svg/svg_path.py
index 1e9ef24fb..2d6f8ac4e 100644
--- a/manim/mobject/svg/svg_path.py
+++ b/manim/mobject/svg/svg_path.py
@@ -284,7 +284,7 @@ class SVGPathMobject(VMobject, metaclass=ConvertToOpenGL):
# Keep track of the most recently completed point
if config["renderer"] == "opengl":
- points = self.data["points"]
+ points = self.points
else:
points = self.points
start_point = points[-1] if points.shape[0] else np.zeros((1, self.dim))
@@ -313,7 +313,7 @@ class SVGPathMobject(VMobject, metaclass=ConvertToOpenGL):
elif command == "S": # Smooth cubic
if config["renderer"] == "opengl":
- points = self.data["points"]
+ points = self.points
else:
points = self.points
prev_handle = start_point
diff --git a/manim/mobject/types/opengl_surface.py b/manim/mobject/types/opengl_surface.py
index d8ffd2734..3ce45ef4f 100644
--- a/manim/mobject/types/opengl_surface.py
+++ b/manim/mobject/types/opengl_surface.py
@@ -5,6 +5,7 @@ from ...constants import *
from ...mobject.opengl_mobject import OpenGLMobject
from ...utils.bezier import integer_interpolate, interpolate
from ...utils.color import *
+from ...utils.config_ops import _Data, _Uniforms
from ...utils.images import get_full_raster_image_path
from ...utils.iterables import listify
from ...utils.space_ops import normalize_along_axis
@@ -114,7 +115,7 @@ class OpenGLSurface(OpenGLMobject):
return self.triangle_indices
def get_surface_points_and_nudged_points(self):
- points = self.get_points()
+ points = self.points
k = len(points) // 3
return points[:k], points[k : 2 * k], points[2 * k :]
@@ -175,7 +176,7 @@ class OpenGLSurface(OpenGLMobject):
def sort_faces_back_to_front(self, vect=OUT):
tri_is = self.triangle_indices
indices = list(range(len(tri_is) // 3))
- points = self.get_points()
+ points = self.points
def index_dot(index):
return np.dot(points[tri_is[3 * index]], vect)
@@ -223,10 +224,15 @@ class OpenGLTexturedSurface(OpenGLSurface):
("opacity", np.float32, (1,)),
]
shader_folder = "textured_surface"
+ im_coords = _Data()
+ opacity = _Data()
+ num_textures = _Uniforms()
def __init__(
self, uv_surface, image_file, dark_image_file=None, shader_folder=None, **kwargs
):
+ self.uniforms = {}
+
if not isinstance(uv_surface, OpenGLSurface):
raise Exception("uv_surface must be of type OpenGLSurface")
# Set texture information
@@ -250,13 +256,13 @@ class OpenGLTexturedSurface(OpenGLSurface):
def init_data(self):
super().init_data()
- self.data["im_coords"] = np.zeros((0, 2))
- self.data["opacity"] = np.zeros((0, 1))
+ self.im_coords = np.zeros((0, 2))
+ self.opacity = np.zeros((0, 1))
def init_points(self):
nu, nv = self.uv_surface.resolution
- self.set_points(self.uv_surface.get_points())
- self.data["im_coords"] = np.array(
+ self.set_points(self.uv_surface.points)
+ self.im_coords = np.array(
[
[u, v]
for u in np.linspace(0, 1, nu)
@@ -264,22 +270,18 @@ class OpenGLTexturedSurface(OpenGLSurface):
]
)
- def init_uniforms(self):
- super().init_uniforms()
- self.uniforms["num_textures"] = self.num_textures
-
def init_colors(self):
- self.data["opacity"] = np.array([self.uv_surface.data["rgbas"][:, 3]])
+ self.opacity = np.array([self.uv_surface.rgbas[:, 3]])
def set_opacity(self, opacity, recurse=True):
for mob in self.get_family(recurse):
- mob.data["opacity"] = np.array([[o] for o in listify(opacity)])
+ mob.opacity = np.array([[o] for o in listify(opacity)])
return self
def pointwise_become_partial(self, tsmobject, a, b, axis=1):
super().pointwise_become_partial(tsmobject, a, b, axis)
- im_coords = self.data["im_coords"]
- im_coords[:] = tsmobject.data["im_coords"]
+ im_coords = self.im_coords
+ im_coords[:] = tsmobject.im_coords
if a <= 0 and b >= 1:
return self
nu, nv = tsmobject.resolution
diff --git a/manim/mobject/types/opengl_vectorized_mobject.py b/manim/mobject/types/opengl_vectorized_mobject.py
index 6ab3d7c34..9209e9e1d 100644
--- a/manim/mobject/types/opengl_vectorized_mobject.py
+++ b/manim/mobject/types/opengl_vectorized_mobject.py
@@ -18,6 +18,7 @@ from ...utils.bezier import (
partial_quadratic_bezier_points,
)
from ...utils.color import *
+from ...utils.config_ops import _Data
from ...utils.deprecation import deprecated_params
from ...utils.iterables import listify, make_even, resize_with_interpolation
from ...utils.space_ops import (
@@ -55,6 +56,11 @@ class OpenGLVMobject(OpenGLMobject):
stroke_shader_folder = "quadratic_bezier_stroke"
fill_shader_folder = "quadratic_bezier_fill"
+ fill_rgba = _Data()
+ stroke_rgba = _Data()
+ stroke_width = _Data()
+ unit_normal = _Data()
+
def __init__(
self,
fill_color=None,
@@ -83,6 +89,7 @@ class OpenGLVMobject(OpenGLMobject):
triangulation_locked=False,
**kwargs,
):
+ self.data = {}
self.fill_color = fill_color
self.fill_opacity = fill_opacity
self.stroke_color = stroke_color
@@ -123,14 +130,10 @@ class OpenGLVMobject(OpenGLMobject):
def init_data(self):
super().init_data()
self.data.pop("rgbas")
- self.data.update(
- {
- "fill_rgba": np.zeros((1, 4)),
- "stroke_rgba": np.zeros((1, 4)),
- "stroke_width": np.zeros((1, 1)),
- "unit_normal": np.zeros((1, 3)),
- }
- )
+ self.fill_rgba = np.zeros((1, 4))
+ self.stroke_rgba = np.zeros((1, 4))
+ self.unit_normal = np.zeros((1, 3))
+ # stroke_width belongs to self.data, but is defined through init_colors+set_stroke
# Colors
def init_colors(self):
@@ -159,9 +162,7 @@ class OpenGLVMobject(OpenGLMobject):
if width is not None:
for mob in self.get_family(recurse):
- mob.data["stroke_width"] = np.array(
- [[width] for width in listify(width)]
- )
+ mob.stroke_width = np.array([[width] for width in listify(width)])
if background is not None:
for mob in self.get_family(recurse):
@@ -182,16 +183,12 @@ class OpenGLVMobject(OpenGLMobject):
recurse=True,
):
if fill_rgba is not None:
- self.data["fill_rgba"] = resize_with_interpolation(
- fill_rgba, len(fill_rgba)
- )
+ self.fill_rgba = resize_with_interpolation(fill_rgba, len(fill_rgba))
else:
self.set_fill(color=fill_color, opacity=fill_opacity, recurse=recurse)
if stroke_rgba is not None:
- self.data["stroke_rgba"] = resize_with_interpolation(
- stroke_rgba, len(fill_rgba)
- )
+ self.stroke_rgba = resize_with_interpolation(stroke_rgba, len(fill_rgba))
self.set_stroke(width=stroke_width)
else:
self.set_stroke(
@@ -209,11 +206,11 @@ class OpenGLVMobject(OpenGLMobject):
def get_style(self):
return {
- "fill_rgba": self.data["fill_rgba"],
- "stroke_rgba": self.data["stroke_rgba"],
- "stroke_width": self.data["stroke_width"],
- "gloss": self.get_gloss(),
- "shadow": self.get_shadow(),
+ "fill_rgba": self.fill_rgba,
+ "stroke_rgba": self.stroke_rgba,
+ "stroke_width": self.stroke_width,
+ "gloss": self.gloss,
+ "shadow": self.shadow,
}
def match_style(self, vmobject, recurse=True):
@@ -257,19 +254,19 @@ class OpenGLVMobject(OpenGLMobject):
return self
def get_fill_colors(self):
- return [rgb_to_hex(rgba[:3]) for rgba in self.data["fill_rgba"]]
+ return [rgb_to_hex(rgba[:3]) for rgba in self.fill_rgba]
def get_fill_opacities(self):
- return self.data["fill_rgba"][:, 3]
+ return self.fill_rgba[:, 3]
def get_stroke_colors(self):
- return [rgb_to_hex(rgba[:3]) for rgba in self.data["stroke_rgba"]]
+ return [rgb_to_hex(rgba[:3]) for rgba in self.stroke_rgba]
def get_stroke_opacities(self):
- return self.data["stroke_rgba"][:, 3]
+ return self.stroke_rgba[:, 3]
def get_stroke_widths(self):
- return self.data["stroke_width"]
+ return self.stroke_width
# TODO, it's weird for these to return the first of various lists
# rather than the full information
@@ -781,9 +778,9 @@ class OpenGLVMobject(OpenGLMobject):
def get_unit_normal(self, recompute=False):
if not recompute:
- return self.data["unit_normal"][0]
+ return self.unit_normal[0]
- if len(self.data["points"]) < 3:
+ if len(self.points) < 3:
return OUT
area_vect = self.get_area_vector()
@@ -799,7 +796,7 @@ class OpenGLVMobject(OpenGLMobject):
def refresh_unit_normal(self):
for mob in self.get_family():
- mob.data["unit_normal"][:] = mob.get_unit_normal(recompute=True)
+ mob.unit_normal[:] = mob.get_unit_normal(recompute=True)
return self
# Alignment
@@ -1153,7 +1150,7 @@ class OpenGLVMobject(OpenGLMobject):
}
def get_stroke_shader_data(self):
- points = self.data["points"]
+ points = self.points
stroke_data = np.zeros(len(points), dtype=OpenGLVMobject.stroke_dtype)
nppc = self.n_points_per_curve
@@ -1170,7 +1167,7 @@ class OpenGLVMobject(OpenGLMobject):
return stroke_data
def get_fill_shader_data(self):
- points = self.data["points"]
+ points = self.points
fill_data = np.zeros(len(points), dtype=OpenGLVMobject.fill_dtype)
fill_data["vert_index"][:, 0] = range(len(points))
diff --git a/manim/renderer/opengl_renderer.py b/manim/renderer/opengl_renderer.py
index 5d34fb639..5aa7787d3 100644
--- a/manim/renderer/opengl_renderer.py
+++ b/manim/renderer/opengl_renderer.py
@@ -16,6 +16,7 @@ from ..mobject.opengl_mobject import OpenGLMobject, OpenGLPoint
from ..mobject.types.opengl_vectorized_mobject import OpenGLVMobject
from ..scene.scene_file_writer import SceneFileWriter
from ..utils import opengl
+from ..utils.config_ops import _Data
from ..utils.simple_functions import clip
from ..utils.space_ops import (
angle_of_vector,
@@ -32,6 +33,8 @@ from .vectorized_mobject_rendering import (
class OpenGLCamera(OpenGLMobject):
+ euler_angles = _Data()
+
def __init__(
self,
frame_shape=None,
@@ -72,10 +75,8 @@ class OpenGLCamera(OpenGLMobject):
else:
self.center_point = center_point
- if euler_angles is None:
- self.euler_angles = [0, 0, 0]
- else:
- self.euler_angles = euler_angles
+ if model_matrix is None:
+ model_matrix = opengl.translation_matrix(0, 0, 11)
self.focal_distance = focal_distance
@@ -85,12 +86,15 @@ class OpenGLCamera(OpenGLMobject):
self.light_source_position = light_source_position
self.light_source = OpenGLPoint(self.light_source_position)
- if model_matrix is None:
- model_matrix = opengl.translation_matrix(0, 0, 11)
-
+ self.default_model_matrix = model_matrix
super().__init__(model_matrix=model_matrix, **kwargs)
- self.default_model_matrix = model_matrix
+ if euler_angles is None:
+ euler_angles = [0, 0, 0]
+ euler_angles = np.array(euler_angles, dtype=float)
+
+ self.euler_angles = euler_angles
+ self.refresh_rotation_matrix()
def get_position(self):
return self.model_matrix[:, 3][:3]
@@ -105,11 +109,6 @@ class OpenGLCamera(OpenGLMobject):
else:
return np.linalg.inv(self.model_matrix)
- def init_data(self):
- super().init_data()
- self.data["euler_angles"] = np.array(self.euler_angles, dtype=float)
- self.refresh_rotation_matrix()
-
def init_points(self):
self.set_points([ORIGIN, LEFT, RIGHT, DOWN, UP])
self.set_width(self.frame_shape[0], stretch=True)
@@ -126,7 +125,7 @@ class OpenGLCamera(OpenGLMobject):
def refresh_rotation_matrix(self):
# Rotate based on camera orientation
- theta, phi, gamma = self.data["euler_angles"]
+ theta, phi, gamma = self.euler_angles
quat = quaternion_mult(
quaternion_from_angle_axis(theta, OUT, axis_normalized=True),
quaternion_from_angle_axis(phi, RIGHT, axis_normalized=True),
@@ -151,11 +150,11 @@ class OpenGLCamera(OpenGLMobject):
def set_euler_angles(self, theta=None, phi=None, gamma=None):
if theta is not None:
- self.data["euler_angles"][0] = theta
+ self.euler_angles[0] = theta
if phi is not None:
- self.data["euler_angles"][1] = phi
+ self.euler_angles[1] = phi
if gamma is not None:
- self.data["euler_angles"][2] = gamma
+ self.euler_angles[2] = gamma
self.refresh_rotation_matrix()
return self
@@ -169,19 +168,19 @@ class OpenGLCamera(OpenGLMobject):
return self.set_euler_angles(gamma=gamma)
def increment_theta(self, dtheta):
- self.data["euler_angles"][0] += dtheta
+ self.euler_angles[0] += dtheta
self.refresh_rotation_matrix()
return self
def increment_phi(self, dphi):
- phi = self.data["euler_angles"][1]
+ phi = self.euler_angles[1]
new_phi = clip(phi + dphi, -PI / 2, PI / 2)
- self.data["euler_angles"][1] = new_phi
+ self.euler_angles[1] = new_phi
self.refresh_rotation_matrix()
return self
def increment_gamma(self, dgamma):
- self.data["euler_angles"][2] += dgamma
+ self.euler_angles[2] += dgamma
self.refresh_rotation_matrix()
return self
diff --git a/manim/renderer/vectorized_mobject_rendering.py b/manim/renderer/vectorized_mobject_rendering.py
index 506dab2b1..db6d96d02 100644
--- a/manim/renderer/vectorized_mobject_rendering.py
+++ b/manim/renderer/vectorized_mobject_rendering.py
@@ -63,7 +63,7 @@ def render_mobject_fills_with_matrix(renderer, model_matrix, mobjects):
end_offset = write_offset + mobject_triangulation.shape[0]
attributes[write_offset:end_offset] = mobject_triangulation
attributes["in_color"][write_offset:end_offset] = np.repeat(
- submob.data["fill_rgba"], mobject_triangulation.shape[0], axis=0
+ submob.fill_rgba, mobject_triangulation.shape[0], axis=0
)
write_offset = end_offset
@@ -195,7 +195,7 @@ def render_mobject_strokes_with_matrix(renderer, model_matrix, mobjects):
# Precompute the total number of vertices for which to reserve space.
total_size = 0
for submob in mobjects:
- total_size += submob.data["points"].shape[0]
+ total_size += submob.points.shape[0]
points = np.empty((total_size, 3))
colors = np.empty((total_size, 4))
@@ -205,14 +205,14 @@ def render_mobject_strokes_with_matrix(renderer, model_matrix, mobjects):
for submob in mobjects:
if not submob.has_points():
continue
- end_offset = write_offset + submob.data["points"].shape[0]
+ end_offset = write_offset + submob.points.shape[0]
- points[write_offset:end_offset] = submob.data["points"]
+ points[write_offset:end_offset] = submob.points
colors[write_offset:end_offset] = np.repeat(
- submob.data["stroke_rgba"], submob.data["points"].shape[0], axis=0
+ submob.stroke_rgba, submob.points.shape[0], axis=0
)
widths[write_offset:end_offset] = np.repeat(
- submob.data["stroke_width"], submob.data["points"].shape[0]
+ submob.stroke_width, submob.points.shape[0]
)
write_offset = end_offset
@@ -266,7 +266,7 @@ def render_mobject_strokes_with_matrix(renderer, model_matrix, mobjects):
),
)
shader.set_uniform("u_projection_matrix", renderer.scene.camera.projection_matrix)
- shader.set_uniform("manim_unit_normal", tuple(-mobjects[0].data["unit_normal"][0]))
+ shader.set_uniform("manim_unit_normal", tuple(-mobjects[0].unit_normal[0]))
vbo = renderer.context.buffer(stroke_data.tobytes())
vao = renderer.context.simple_vertex_array(
diff --git a/manim/utils/config_ops.py b/manim/utils/config_ops.py
index a3ee8bad1..6351d6a1d 100644
--- a/manim/utils/config_ops.py
+++ b/manim/utils/config_ops.py
@@ -9,6 +9,8 @@ __all__ = [
import itertools as it
+import numpy as np
+
def merge_dicts_recursively(*dicts):
"""
@@ -42,3 +44,33 @@ def update_dict_recursively(current_dict, *others):
class DictAsObject(object):
def __init__(self, dictin):
self.__dict__ = dictin
+
+
+class _Data:
+ """Descriptor that allows _Data variables to be grouped and accessed from self.data["attr"] via self.attr.
+ self.data attributes must be arrays.
+ """
+
+ def __set_name__(self, obj, name):
+ self.name = name
+
+ def __get__(self, obj, owner):
+ return obj.__dict__["data"][self.name]
+
+ def __set__(self, obj, array: np.ndarray):
+ obj.__dict__["data"][self.name] = array
+
+
+class _Uniforms:
+ """Descriptor that allows _Uniforms variables to be grouped from self.uniforms["attr"] via self.attr.
+ self.uniforms attributes must be floats.
+ """
+
+ def __set_name__(self, obj, name):
+ self.name = name
+
+ def __get__(self, obj, owner):
+ return obj.__dict__["uniforms"][self.name]
+
+ def __set__(self, obj, num: float):
+ obj.__dict__["uniforms"][self.name] = num
diff --git a/tests/test_set_attr.py b/tests/test_set_attr.py
new file mode 100644
index 000000000..c5d64dffb
--- /dev/null
+++ b/tests/test_set_attr.py
@@ -0,0 +1,36 @@
+import numpy as np
+import pytest
+
+from manim.constants import RIGHT
+from manim.opengl import OpenGLSquare
+
+
+def test_Data():
+ a = OpenGLSquare().move_to(RIGHT)
+ data_bb = a.data["bounding_box"]
+ assert np.array_equal(
+ data_bb, np.array([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [2.0, 1.0, 0.0]])
+ )
+
+ # test that calling the attribute equals calling it from self.data
+ assert np.array_equal(a.bounding_box, data_bb)
+
+ # test that the array can be indexed
+ assert np.array_equal(
+ a.bounding_box[1],
+ np.array(
+ [1.0, 0.0, 0.0],
+ ),
+ )
+
+ # test that a value can be set
+ a.bounding_box[1] = 300
+
+ # test that both the attr and self.data arrays match after adjusting a value
+
+ data_bb = a.data["bounding_box"]
+ assert np.array_equal(
+ data_bb, np.array([[0.0, -1.0, 0.0], [300.0, 300.0, 300.0], [2.0, 1.0, 0.0]])
+ )
+
+ assert np.array_equal(a.bounding_box, data_bb)