Coverage for src/manimgx/drawing/paint.py: 98%

649 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-26 05:52 +0000

1# SPDX-FileCopyrightText: 2026 Academa, Inc. 

2# SPDX-FileCopyrightText: 2024 the Manim Community Developers 

3# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC 

4# SPDX-License-Identifier: MIT 

5 

6"""Colors and immutable paint shared by paths, points and meshes. 

7 

8Colors retain exact RGBA beside their string form. Paint owns the brushes and 

9appearance of a drawing; its geometry kind gives each brush row its meaning. 

10""" 

11 

12import colorsys 

13import random 

14import re 

15from collections.abc import Iterable, Sequence 

16from dataclasses import dataclass 

17from enum import Enum 

18from pathlib import PurePath 

19from typing import TYPE_CHECKING, Final, Self, TypeIs, cast, overload 

20from warnings import deprecated 

21 

22import numpy as np 

23import numpy.typing as npt 

24from typing_extensions import TypedDict 

25 

26from manimgx.caches import Memo, unchanged 

27from manimgx.constants import UL, CapStyleType, LineJointType 

28from manimgx.drawing.geometry import Floats, interpolate 

29from manimgx.typing import RGBA_Array, Vector3D, Vector3DLike 

30 

31__all__ = [ 

32 "BLACK", 

33 "BLUE", 

34 "BLUE_A", 

35 "BLUE_B", 

36 "BLUE_C", 

37 "BLUE_D", 

38 "BLUE_E", 

39 "DARKER_GRAY", 

40 "DARKER_GREY", 

41 "DARK_BLUE", 

42 "DARK_BROWN", 

43 "DARK_GRAY", 

44 "DARK_GREY", 

45 "GOLD", 

46 "GOLD_A", 

47 "GOLD_B", 

48 "GOLD_C", 

49 "GOLD_D", 

50 "GOLD_E", 

51 "GRAY", 

52 "GRAY_A", 

53 "GRAY_B", 

54 "GRAY_BROWN", 

55 "GRAY_C", 

56 "GRAY_D", 

57 "GRAY_E", 

58 "GREEN", 

59 "GREEN_A", 

60 "GREEN_B", 

61 "GREEN_C", 

62 "GREEN_D", 

63 "GREEN_E", 

64 "GREY", 

65 "GREY_A", 

66 "GREY_B", 

67 "GREY_BROWN", 

68 "GREY_C", 

69 "GREY_D", 

70 "GREY_E", 

71 "HSV", 

72 "LIGHTER_GRAY", 

73 "LIGHTER_GREY", 

74 "LIGHT_BROWN", 

75 "LIGHT_GRAY", 

76 "LIGHT_GREY", 

77 "LIGHT_PINK", 

78 "LOGO_BLACK", 

79 "LOGO_BLUE", 

80 "LOGO_GREEN", 

81 "LOGO_RED", 

82 "LOGO_WHITE", 

83 "MAROON", 

84 "MAROON_A", 

85 "MAROON_B", 

86 "MAROON_C", 

87 "MAROON_D", 

88 "MAROON_E", 

89 "ORANGE", 

90 "PALETTE", 

91 "PINK", 

92 "PURE_BLUE", 

93 "PURE_CYAN", 

94 "PURE_GREEN", 

95 "PURE_MAGENTA", 

96 "PURE_RED", 

97 "PURE_YELLOW", 

98 "PURPLE", 

99 "PURPLE_A", 

100 "PURPLE_B", 

101 "PURPLE_C", 

102 "PURPLE_D", 

103 "PURPLE_E", 

104 "RED", 

105 "RED_A", 

106 "RED_B", 

107 "RED_C", 

108 "RED_D", 

109 "RED_E", 

110 "TEAL", 

111 "TEAL_A", 

112 "TEAL_B", 

113 "TEAL_C", 

114 "TEAL_D", 

115 "TEAL_E", 

116 "WHITE", 

117 "YELLOW", 

118 "YELLOW_A", 

119 "YELLOW_B", 

120 "YELLOW_C", 

121 "YELLOW_D", 

122 "YELLOW_E", 

123 "Colorscale", 

124 "ManimColor", 

125 "Material", 

126 "ParsableManimColor", 

127 "RandomColorGenerator", 

128 "average_color", 

129 "color_gradient", 

130 "color_to_rgb", 

131 "colors_by_value", 

132 "from_oklab", 

133 "interpolate_color", 

134 "invert_color", 

135 "mix_rgba", 

136 "parse_colors", 

137 "random_bright_color", 

138 "random_color", 

139 "rgb_to_color", 

140 "rgbas_by_value", 

141 "stretch_array_to_length", 

142 "to_oklab", 

143] 

144 

145# ── mixing: one rule for every blend of colors ───────────────────────────────── 

146# Colors mix in OKLab, where lightness moves evenly (the midpoint of two colors sits exactly 

147# halfway in perceived lightness), premultiplied by opacity so an invisible color never tints 

148# the result; opacity itself mixes linearly. Compositing (drawing translucent layers) stays in 

149# sRGB, where 50% opacity looks half as bright. 

150_LMS: Floats = np.array( 

151 [ 

152 [0.4122214708, 0.5363325363, 0.0514459929], 

153 [0.2119034982, 0.6806995451, 0.1073969566], 

154 [0.0883024619, 0.2817188376, 0.6299787005], 

155 ] 

156) 

157_LAB: Floats = np.array( 

158 [ 

159 [0.2104542553, 0.7936177850, -0.0040720468], 

160 [1.9779984951, -2.4285922050, 0.4505937099], 

161 [0.0259040371, 0.7827717662, -0.8086757660], 

162 ] 

163) 

164_LMS_INV: Floats = np.linalg.inv(_LMS) 

165_LAB_INV: Floats = np.linalg.inv(_LAB) 

166 

167 

168@deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

169def to_oklab(rgb: Floats) -> Floats: 

170 """Convert sRGB colors to OKLab, the color space colors are mixed in. 

171 

172 Along a straight line in OKLab, colors pass through those the eye sees between its 

173 ends, and lightness changes evenly. 

174 

175 Args: 

176 rgb: Red, green and blue, from 0 to 1, along the last axis: an array of shape 

177 (…, 3). 

178 

179 Returns: 

180 Lightness L and the axes a and b, as an array of the same shape. 

181 """ 

182 linear = np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4) 

183 return np.cbrt(linear @ _LMS.T) @ _LAB.T 

184 

185 

186@deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

187def from_oklab(lab: Floats) -> Floats: 

188 """Convert OKLab colors to sRGB, clipped to the colors a screen shows. 

189 

190 Args: 

191 lab: Lightness L and the axes a and b, along the last axis: an array of shape 

192 (…, 3). 

193 

194 Returns: 

195 Red, green and blue, from 0 to 1, as an array of the same shape. 

196 """ 

197 linear = np.clip(((lab @ _LAB_INV.T) ** 3) @ _LMS_INV.T, 0.0, 1.0) 

198 return np.where( 

199 linear <= 0.0031308, 12.92 * linear, 1.055 * linear ** (1 / 2.4) - 0.055 

200 ) 

201 

202 

203_LABS: Memo[int, tuple[Floats, Floats]] = Memo(1 << 12) 

204_COLOR_LABS: Memo[bytes, Floats] = Memo(1 << 12) 

205 

206 

207def _lab(rgba: Floats) -> Floats: 

208 """OKLab of an RGBA array's colors — once per array when the array cannot change (a 

209 paint's rows are read-only): a tween mixes the same two paints on every frame; and once 

210 per value for one color (a color's own array): an updater mixes the same colors on 

211 every frame.""" 

212 if rgba.flags.writeable: 

213 if rgba.shape == (4,): 

214 rgb = rgba[:3] 

215 return _COLOR_LABS.recall(rgb.tobytes(), lambda: frozen(to_oklab(rgb))) 

216 return to_oklab(rgba[..., :3]) 

217 known = _LABS.recall(id(rgba), lambda: (rgba, to_oklab(rgba[..., :3]))) 

218 if known[0] is not rgba: # another array, since gone, had its id 

219 known = _LABS[id(rgba)] = (rgba, to_oklab(rgba[..., :3])) 

220 return known[1] 

221 

222 

223@deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

224def mix_rgba(a: Floats, b: Floats, t: float | Floats) -> Floats: 

225 """Mix colors given as rows of red, green, blue and opacity: `a` at 0, `b` at 1. 

226 

227 Every blend of colors in ManimGX mixes this way. The colors mix in OKLab, weighted 

228 by their opacities, so a transparent color does not tint the mix; the opacity mixes 

229 evenly. Rows of one color only change their opacity. 

230 

231 Args: 

232 a: The colors at 0: red, green, blue and opacity, from 0 to 1, along the last 

233 axis. 

234 b: The colors at 1, an array of the same shape. 

235 t: How far from `a` to `b`, from 0 to 1: one fraction for every row, or one per 

236 row (an array of `a`'s shape without its last axis). 

237 

238 Returns: 

239 The mixed colors, an array of the same shape; exactly `a` at 0 and `b` at 1. 

240 """ 

241 if a.shape == b.shape == (4,) and not isinstance(t, np.ndarray): 

242 return _mix_color(a, b, t) 

243 return _mix_rows(a, b, t) 

244 

245 

246def _mix_rows(a: Floats, b: Floats, t: float | Floats) -> Floats: 

247 """`mix_rgba`, row by row, in numpy: any shape.""" 

248 rows = isinstance(t, np.ndarray) and t.ndim > 0 

249 if rows: 

250 t = t.astype(float)[..., None] 

251 elif t <= 0.0: 

252 return np.array(a, dtype=float) 

253 elif t >= 1.0: 

254 return np.array(b, dtype=float) 

255 elif np.array_equal(a[..., :3], b[..., :3]): # one color: only opacity moves 

256 out = np.array(a, dtype=float) 

257 out[..., 3] = a[..., 3] * (1.0 - t) + b[..., 3] * t 

258 return out 

259 wa, wb = a[..., 3:4] * (1.0 - t), b[..., 3:4] * t 

260 opacity = wa + wb 

261 la, lb = _lab(a), _lab(b) 

262 straight = la * (1.0 - t) + lb * t 

263 lab = np.where( 

264 opacity > 1e-9, (la * wa + lb * wb) / np.maximum(opacity, 1e-9), straight 

265 ) 

266 mixed = np.concatenate([from_oklab(lab), opacity], axis=-1) 

267 # row by row too: a row of one color only changes its opacity 

268 same = np.all(a[..., :3] == b[..., :3], axis=-1, keepdims=True) 

269 if same.any(): 

270 mixed[..., :3] = np.where(same, a[..., :3], mixed[..., :3]) 

271 return mixed if not rows else np.where(t <= 0.0, a, np.where(t >= 1.0, b, mixed)) 

272 

273 

274def _mix_color(a: Floats, b: Floats, t: float) -> Floats: 

275 """`mix_rgba` of one color and another: `_mix_rows`'s arithmetic, step by step, on 

276 floats (each step rounds as numpy's does), around numpy's OKLab conversion. An updater 

277 mixes one color at a time, every frame, where numpy's calls cost more than the 

278 arithmetic they do.""" 

279 if t <= 0.0: 

280 return np.array(a, dtype=float) 

281 if t >= 1.0: 

282 return np.array(b, dtype=float) 

283 (ar, ag, ab, aa), (br, bg, bb, ba) = a.tolist(), b.tolist() 

284 if (ar, ag, ab) == (br, bg, bb): # one color: only opacity moves 

285 out = np.array(a, dtype=float) 

286 out[3] = aa * (1.0 - t) + ba * t 

287 return out 

288 wa, wb = aa * (1.0 - t), ba * t 

289 opacity = wa + wb 

290 la, lb = _lab(a).tolist(), _lab(b).tolist() 

291 if opacity > 1e-9: 

292 lab = [ 

293 (x * wa + y * wb) / max(opacity, 1e-9) for x, y in zip(la, lb, strict=True) 

294 ] 

295 else: 

296 lab = [x * (1.0 - t) + y * t for x, y in zip(la, lb, strict=True)] 

297 return np.array([*from_oklab(np.array(lab)).tolist(), opacity]) 

298 

299 

300type ParsableManimColor = ManimColor | str | int | Sequence[float] | np.ndarray 

301"""Anything [ManimColor][manimgx.ManimColor] reads as a color: a color, a hex string 

302(`"#58C4DD"`) or a color's name (`"BLUE"`), an integer (`0x58C4DD`), or three or four 

303numbers (red, green, blue and opacity).""" 

304 

305# a hex color: `#` or `0x`, then 3, 4, 6 or 8 digits (the opacity's last, when there are 4 or 8) 

306_HEX = re.compile(r"(?:#|0x)([0-9A-F]{3,4}|[0-9A-F]{6}|[0-9A-F]{8})", re.IGNORECASE) 

307 

308 

309class ManimColor(str): 

310 """A color: red, green, blue and opacity, from 0 to 1, which is also its hex string. 

311 

312 As a string it is `"#RRGGBB"`, or `"#RRGGBBAA"` when translucent, so it goes 

313 wherever a string does; [to_rgba][manimgx.ManimColor.to_rgba] gives its values. 

314 `ManimColor(value, alpha=1.0)` reads `value` as a color, of opacity `alpha` (from 0 

315 to 1) where `value` gives none. `value` is: 

316 

317 - a hex string, `"#FC6255"` or `"0xFC6255"`, of 3, 4, 6 or 8 digits (the fourth of 

318 four, and the last two of eight, are the opacity); 

319 - a color's name, in any case: `"BLUE"`, `"blue_c"`; 

320 - an integer, `0xFC6255`; 

321 - three or four numbers, red, green, blue and opacity: from 0 to 1 if all are 

322 floats, from 0 to 255 otherwise (`(1.0, 0.5, 0.0)` is orange, `(1, 0.5, 0)` nearly 

323 black); 

324 - another color, copied as it is; 

325 - None, for black. 

326 

327 Examples: 

328 ```python 

329 import manimgx as m 

330 

331 

332 class ManimColorExample(m.Scene): 

333 def construct(self) -> None: 

334 colors = [ 

335 m.ManimColor("#58C4DD"), 

336 m.ManimColor("orange"), 

337 m.ManimColor((0.9, 0.3, 0.5)), 

338 m.ManimColor.from_hsv((0.75, 0.6, 0.9)), 

339 m.RED.lighter(0.4), 

340 m.RED.darker(0.4), 

341 ] 

342 swatches = m.VGroup( 

343 *( 

344 m.VGroup( 

345 m.Square(side_length=1.6, color=color, fill_opacity=1), 

346 m.Text(color, font_size=24), 

347 ).arrange(m.DOWN) 

348 for color in colors 

349 ) 

350 ) 

351 self.add(swatches.arrange(buff=0.4)) 

352 ``` 

353 """ 

354 

355 _rgba: np.ndarray 

356 

357 def __new__( 

358 cls, value: ParsableManimColor | None = None, alpha: float = 1.0 

359 ) -> Self: 

360 return _made(cls, _parse(value, alpha)) 

361 

362 @overload 

363 @classmethod 

364 def parse(cls, value: "ParsableManimColor | None", alpha: float = 1.0) -> Self: ... 

365 @overload 

366 @classmethod 

367 def parse( 

368 cls, 

369 value: "list[ParsableManimColor] | tuple[ParsableManimColor, ...]", 

370 alpha: float = 1.0, 

371 ) -> list[Self]: ... 

372 @classmethod 

373 @deprecated("use ManimColor(...)", category=None) 

374 def parse( 

375 cls, 

376 value: "ParsableManimColor | Sequence[ParsableManimColor] | None", 

377 alpha: float = 1.0, 

378 ) -> Self | list[Self]: 

379 """Read one color, or a list of colors from a list or tuple of them. 

380 

381 A color of this class is returned as it is. 

382 

383 Args: 

384 value: A color in any form [ManimColor][manimgx.ManimColor] reads (three or 

385 four numbers are one color), or a list or tuple of them. 

386 alpha: The opacity, from 0 to 1, of those that give none. 

387 

388 Returns: 

389 The color, or a list of the colors. 

390 """ 

391 if ( 

392 value is None 

393 or isinstance(value, (str, ManimColor, int)) 

394 or _numbers(value) 

395 ): 

396 return value if isinstance(value, cls) else cls(value, alpha) 

397 return [cls.parse(v, alpha) for v in value] 

398 

399 def to_rgb(self) -> np.ndarray: 

400 """The color's red, green and blue. 

401 

402 Returns: 

403 An array of three floats, from 0 to 1. 

404 """ 

405 return self._rgba[:3] 

406 

407 def to_rgba(self) -> np.ndarray: 

408 """The color's red, green, blue and opacity. 

409 

410 Returns: 

411 An array of four floats, from 0 to 1. 

412 """ 

413 return self._rgba 

414 

415 @deprecated("use to_rgba", category=None) 

416 def to_rgba_with_alpha(self, alpha: float) -> np.ndarray: 

417 """The color's red, green and blue, with another opacity. 

418 

419 Args: 

420 alpha: The opacity, from 0 to 1. 

421 

422 Returns: 

423 An array of red, green, blue and `alpha`. 

424 """ 

425 return np.array((*self._rgba[:3], alpha)) 

426 

427 def to_hex(self, with_alpha: bool = False) -> str: 

428 """The color as a hex string, `"#RRGGBB"`, in capitals. 

429 

430 Args: 

431 with_alpha: Whether to add the opacity's two digits: `"#RRGGBBAA"`. 

432 

433 Returns: 

434 The string. 

435 """ 

436 r, g, b, a = _bytes(self._rgba) 

437 return f"#{r:02X}{g:02X}{b:02X}" + (f"{a:02X}" if with_alpha else "") 

438 

439 def interpolate(self, other: "ManimColor", alpha: float) -> "ManimColor": 

440 """The color a fraction of the way from this one to another, mixed as every 

441 blend of colors is: in OKLab, where the colors between two are those the eye sees 

442 between them. 

443 

444 Args: 

445 other: The color at 1. 

446 alpha: How far toward it, from 0 (this color) to 1 (`other`). 

447 

448 Returns: 

449 A new color. 

450 """ 

451 return _made(ManimColor, mix_rgba(self._rgba, other._rgba, alpha)) 

452 

453 def opacity(self, opacity: float) -> "ManimColor": 

454 """This color with another opacity. 

455 

456 Args: 

457 opacity: The opacity, from 0 (transparent) to 1 (opaque). 

458 

459 Returns: 

460 A new color. 

461 """ 

462 return ManimColor((*self._rgba[:3], float(opacity))) 

463 

464 def lighter(self, blend: float = 0.2) -> "ManimColor": 

465 """This color mixed toward white, its opacity kept. 

466 

467 Args: 

468 blend: How far toward white, from 0 (this color) to 1 (white). 

469 

470 Returns: 

471 A new color. 

472 """ 

473 return self.interpolate(WHITE, blend).opacity(self._rgba[3]) 

474 

475 def darker(self, blend: float = 0.2) -> "ManimColor": 

476 """This color mixed toward black, its opacity kept. 

477 

478 Args: 

479 blend: How far toward black, from 0 (this color) to 1 (black). 

480 

481 Returns: 

482 A new color. 

483 """ 

484 return self.interpolate(BLACK, blend).opacity(self._rgba[3]) 

485 

486 @classmethod 

487 def from_hex(cls, hex_str: str, alpha: float = 1.0) -> "ManimColor": 

488 """The color of a hex string, read as the constructor reads it (`"#RRGGBB"`, 

489 `"#RGB"`, with or without opacity digits; a color's name too). 

490 

491 Args: 

492 hex_str: The string. 

493 alpha: The opacity, from 0 to 1, if the string gives none. 

494 

495 Returns: 

496 A new color. 

497 """ 

498 return cls(hex_str, alpha) 

499 

500 @classmethod 

501 def from_rgb( 

502 cls, rgb: Sequence[float] | Floats, alpha: float = 1.0 

503 ) -> "ManimColor": 

504 """The color of a red, green and blue. 

505 

506 Args: 

507 rgb: Red, green and blue, from 0 to 1. 

508 alpha: The opacity, from 0 to 1. 

509 

510 Returns: 

511 A new color. 

512 """ 

513 return cls(tuple(float(x) for x in rgb), alpha) 

514 

515 @classmethod 

516 def from_rgba(cls, rgba: Sequence[float] | Floats) -> "ManimColor": 

517 """The color of a red, green, blue and opacity. 

518 

519 Args: 

520 rgba: Red, green, blue and opacity, from 0 to 1. 

521 

522 Returns: 

523 A new color. 

524 """ 

525 return cls(tuple(float(x) for x in rgba[:3]), float(rgba[3])) 

526 

527 @classmethod 

528 def from_hsv( 

529 cls, hsv: Sequence[float] | Floats, alpha: float = 1.0 

530 ) -> "ManimColor": 

531 """The color of a hue, saturation and value. 

532 

533 Args: 

534 hsv: Hue, saturation and value, each a float from 0 to 1: a hue of 0 (or 1) 

535 is red, 1/3 green, 2/3 blue. 

536 alpha: The opacity, from 0 to 1. 

537 

538 Returns: 

539 A new color. 

540 """ 

541 return cls(colorsys.hsv_to_rgb(*hsv[:3]), alpha) 

542 

543 @classmethod 

544 def from_hsl( 

545 cls, hsl: Sequence[float] | Floats, alpha: float = 1.0 

546 ) -> "ManimColor": 

547 """The color of a hue, saturation and lightness. 

548 

549 Args: 

550 hsl: Hue, saturation and lightness, each from 0 to 1: a hue of 0 (or 1) is 

551 red, 1/3 green, 2/3 blue; a lightness of 0.5 is the full color. 

552 alpha: The opacity, from 0 to 1. 

553 

554 Returns: 

555 A new color. 

556 """ 

557 hue, saturation, lightness = hsl[:3] 

558 return cls(colorsys.hls_to_rgb(hue, lightness, saturation), alpha) 

559 

560 def to_hsv(self) -> np.ndarray: 

561 """The color's hue, saturation and value. 

562 

563 Returns: 

564 An array of three floats, from 0 to 1. 

565 """ 

566 return np.array(colorsys.rgb_to_hsv(*self.to_rgb())) 

567 

568 @deprecated("use HSV(...)", category=None) 

569 def into[C: "ManimColor"](self, cls: type[C]) -> C: 

570 """This color as an instance of another color class, such as 

571 [HSV][manimgx.HSV]. 

572 

573 Args: 

574 cls: The class: ManimColor or a subclass of it. 

575 

576 Returns: 

577 A new color of that class, of the same value. 

578 """ 

579 return _made(cls, self._rgba.copy()) 

580 

581 def contrasting( 

582 self, 

583 threshold: float = 0.5, 

584 light: "ManimColor | None" = None, 

585 dark: "ManimColor | None" = None, 

586 ) -> "ManimColor": 

587 """A color that stands out against this one, as text on it would: dark on a 

588 light color, light on a dark one. 

589 

590 Args: 

591 threshold: The luma (0.30 red + 0.59 green + 0.11 blue), from 0 to 1, 

592 above which this color counts as light. 

593 light: The color for a dark color; None for white. 

594 dark: The color for a light color; None for black. 

595 

596 Returns: 

597 `dark` or `light`. 

598 """ 

599 luminance = colorsys.rgb_to_yiq(*self.to_rgb())[0] 

600 return (dark or BLACK) if luminance > threshold else (light or WHITE) 

601 

602 def invert(self) -> "ManimColor": 

603 """The color's complement: each of red, green and blue taken from 1, the opacity 

604 kept. 

605 

606 Returns: 

607 A new color. 

608 """ 

609 return ManimColor((*(1.0 - self._rgba[:3]), self._rgba[3])) 

610 

611 def __repr__(self) -> str: 

612 return f"{type(self).__name__}('{self}')" 

613 

614 def __str__(self) -> str: 

615 """The hex of the color's value (a color changed since it was made, as an `HSV` can be, 

616 says what it is now).""" 

617 return _hex(self._rgba) 

618 

619 def __reduce__(self) -> tuple[object, ...]: 

620 return _made, (type(self), self._rgba.copy()) 

621 

622 

623def _bytes(rgba: np.ndarray) -> list[int]: 

624 return [round(min(max(c, 0.0), 1.0) * 255) for c in rgba.tolist()] 

625 

626 

627def _hex(rgba: np.ndarray) -> str: 

628 r, g, b, a = _bytes(rgba) 

629 return f"#{r:02X}{g:02X}{b:02X}" + ("" if a == 255 else f"{a:02X}") 

630 

631 

632def _made[C: ManimColor](cls: type[C], rgba: np.ndarray) -> C: 

633 """A color of class `cls` with the value `rgba` (as it stands: no parsing).""" 

634 color = str.__new__(cls, _hex(rgba)) 

635 color._rgba = rgba 

636 return color 

637 

638 

639def _parse(value: "ParsableManimColor | None", alpha: float) -> np.ndarray: 

640 if value is None: 

641 return np.array((0.0, 0.0, 0.0, alpha)) 

642 if isinstance(value, ManimColor): 

643 return value._rgba.copy() 

644 if isinstance(value, int): 

645 return np.array( 

646 ( 

647 (value >> 16 & 255) / 255, 

648 (value >> 8 & 255) / 255, 

649 (value & 255) / 255, 

650 alpha, 

651 ) 

652 ) 

653 if isinstance(value, str): 

654 m = _HEX.fullmatch(value.strip()) 

655 if m is None: 

656 if value.strip()[:2].lower() in ("0x",) or value.strip().startswith("#"): 

657 raise ValueError( 

658 f"{value!r} is not a hex color: `#` or `0x` and 3, 4, 6 or 8 digits" 

659 ) 

660 named = PALETTE.get(value.upper()) 

661 if named is None: 

662 raise ValueError(f"Color {value} not found") 

663 return np.array((*named.to_rgb(), alpha)) 

664 h = m.group(1) 

665 if len(h) in (3, 4): 

666 h = "".join(c * 2 for c in h) 

667 if len(h) == 6: 

668 h += "FF" 

669 else: 

670 alpha = (int(h, 16) & 255) / 255 

671 tmp = int(h, 16) 

672 return np.array( 

673 ( 

674 (tmp >> 24 & 255) / 255, 

675 (tmp >> 16 & 255) / 255, 

676 (tmp >> 8 & 255) / 255, 

677 alpha, 

678 ) 

679 ) 

680 arr = np.asarray(value) 

681 floats = all(isinstance(x, (float, np.floating)) for x in value) 

682 scale = 1.0 if floats else 255.0 

683 if len(arr) == 3: 

684 return np.array((*(arr / scale), alpha), dtype=float) 

685 if len(arr) == 4: 

686 return np.asarray(arr / scale, dtype=float) 

687 raise ValueError(f"ManimColor accepts length 3 or 4 sequences, not {len(arr)}") 

688 

689 

690@deprecated("color_to_rgb(color) is ManimColor(color).to_rgb(): use it", category=None) 

691def color_to_rgb(color: ParsableManimColor) -> np.ndarray: 

692 """The red, green and blue of a color. 

693 

694 Args: 

695 color: The color, in any form [ManimColor][manimgx.ManimColor] reads. 

696 

697 Returns: 

698 An array of three floats, from 0 to 1. 

699 """ 

700 return ManimColor(color).to_rgb() 

701 

702 

703@deprecated("rgb_to_color(rgb) is ManimColor.from_rgb(rgb): use it", category=None) 

704def rgb_to_color(rgb: Sequence[float] | np.ndarray) -> ManimColor: 

705 """The color of a red, green and blue. 

706 

707 Args: 

708 rgb: Red, green and blue, from 0 to 1. 

709 

710 Returns: 

711 A new, opaque color. 

712 """ 

713 return ManimColor(tuple(float(x) for x in rgb)) 

714 

715 

716def invert_color(color: ParsableManimColor) -> ManimColor: 

717 """A color's complement: each of red, green and blue taken from 1, the opacity kept. 

718 

719 Args: 

720 color: The color, in any form [ManimColor][manimgx.ManimColor] reads. 

721 

722 Returns: 

723 A new color. 

724 """ 

725 return ManimColor(color).invert() 

726 

727 

728def interpolate_color(a: ManimColor, b: ManimColor, alpha: float) -> ManimColor: 

729 """The color a fraction of the way from one color to another. 

730 

731 The two mix as every blend of colors does: in OKLab, where the colors between two 

732 are those the eye sees between them. 

733 

734 Args: 

735 a: The color at 0. 

736 b: The color at 1. 

737 alpha: How far from `a` to `b`, from 0 to 1. 

738 

739 Returns: 

740 A new color. 

741 

742 Examples: 

743 ```python 

744 import manimgx as m 

745 

746 

747 class InterpolateColorExample(m.Scene): 

748 def construct(self) -> None: 

749 swatches = m.VGroup() 

750 for alpha in (0, 0.25, 0.5, 0.75, 1): 

751 color = m.interpolate_color(m.BLUE, m.RED, alpha) 

752 square = m.Square(side_length=1.8, color=color, fill_opacity=1) 

753 label = m.Text(str(alpha), font_size=32).next_to(square, m.DOWN) 

754 swatches.add(m.VGroup(square, label)) 

755 self.add(swatches.arrange(buff=0.5)) 

756 ``` 

757 """ 

758 return a.interpolate(b, alpha) 

759 

760 

761def color_gradient( 

762 reference_colors: Sequence[ParsableManimColor], length_of_output: int 

763) -> list[ManimColor]: 

764 """Colors evenly spaced along a gradient through reference colors, from the first to 

765 the last. 

766 

767 Each is mixed between the two reference colors on either side of it, as 

768 [interpolate_color][manimgx.interpolate_color] mixes them. 

769 

770 Args: 

771 reference_colors: The colors the gradient runs through, evenly spaced along it. 

772 length_of_output: How many colors to return; one is the last reference color. 

773 

774 Returns: 

775 The colors, in order along the gradient. 

776 

777 Examples: 

778 ```python 

779 import manimgx as m 

780 

781 

782 class ColorGradientExample(m.Scene): 

783 def construct(self) -> None: 

784 colors = m.color_gradient([m.BLUE, m.GREEN, m.YELLOW, m.RED], 12) 

785 dots = m.VGroup(*(m.Dot(radius=0.4, color=color) for color in colors)) 

786 self.add(dots.arrange(buff=0.3)) 

787 ``` 

788 """ 

789 if length_of_output == 0: 

790 return [] 

791 if len(reference_colors) == 1: 

792 return [ManimColor(reference_colors[0])] * length_of_output 

793 rgbas = [ManimColor(c).to_rgba() for c in reference_colors] 

794 alphas = np.linspace(0, len(rgbas) - 1, length_of_output) 

795 floors = alphas.astype(int) 

796 alphas_mod1 = alphas % 1 

797 alphas_mod1[-1] = 1 

798 floors[-1] = len(rgbas) - 2 

799 return [ 

800 ManimColor(tuple(mix_rgba(rgbas[i], rgbas[i + 1], float(a)))) 

801 for i, a in zip(floors, alphas_mod1, strict=True) 

802 ] 

803 

804 

805def average_color(*colors: ParsableManimColor) -> ManimColor: 

806 """The average of colors, taken in OKLab: the color the eye sees as their middle. 

807 

808 Their opacities are left out: the average is opaque. 

809 

810 Args: 

811 *colors: The colors, in any form [ManimColor][manimgx.ManimColor] reads. 

812 

813 Returns: 

814 A new, opaque color. 

815 """ 

816 lab = np.mean([to_oklab(ManimColor(c).to_rgb()) for c in colors], axis=0) 

817 return ManimColor(tuple(from_oklab(lab))) 

818 

819 

820type Colorscale = ( 

821 Sequence[ParsableManimColor] | Sequence[tuple[ParsableManimColor, float]] 

822) 

823"""Colors for a range of values: colors spread evenly over the range, or (color, value) 

824pairs, each color at its value (see [colors_by_value][manimgx.colors_by_value]).""" 

825 

826 

827def _paired( 

828 colorscale: Colorscale, 

829) -> TypeIs[Sequence[tuple[ParsableManimColor, float]]]: 

830 """Is the colorscale (color, value) pairs, rather than colors spread evenly?""" 

831 return all(isinstance(c, (tuple, list)) and len(c) == 2 for c in colorscale) 

832 

833 

834def colors_by_value( 

835 colorscale: Colorscale, values: Iterable[float], low: float, high: float 

836) -> list[ManimColor]: 

837 """The color of each value on a colorscale: mixed between the colors on either side 

838 of it, and held beyond the colorscale's ends. 

839 

840 The colors mix as every blend of colors does: in OKLab, where the colors between 

841 two are those the eye sees between them. 

842 

843 Args: 

844 colorscale: Colors spread evenly from `low` to `high`, or (color, value) pairs, 

845 each color at its value, in increasing order of value. 

846 values: The values to color. 

847 low: The value of the first color, when the colors are spread evenly. 

848 high: The value of the last color, when the colors are spread evenly. 

849 

850 Returns: 

851 One color per value, in order. 

852 """ 

853 rows = rgbas_by_value(colorscale, list(values), low, high) 

854 return [ManimColor(tuple(row)) for row in rows] 

855 

856 

857@deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

858def rgbas_by_value( 

859 colorscale: Colorscale, values: npt.ArrayLike, low: float, high: float 

860) -> Floats: 

861 """The color of each value on a colorscale, as a row of red, green, blue and 

862 opacity: [colors_by_value][manimgx.colors_by_value], for many values at once. 

863 

864 Each value's color is mixed between the colors on either side of it, as every blend 

865 of colors mixes (see [mix_rgba][manimgx.mix_rgba]), and held beyond the 

866 colorscale's ends. 

867 

868 Args: 

869 colorscale: Colors spread evenly from `low` to `high`, or (color, value) pairs, 

870 each color at its value, in increasing order of value. 

871 values: The values to color: numbers, in an array of any shape (read in 

872 order, flattened). 

873 low: The value of the first color, when the colors are spread evenly. 

874 high: The value of the last color, when the colors are spread evenly. 

875 

876 Returns: 

877 An (n, 4) array, a row per value, each from 0 to 1. 

878 """ 

879 # the pivots are the colors' values, given or spread evenly over [low, high] 

880 if _paired(colorscale): 

881 colors = np.array([ManimColor(c).to_rgba() for c, _ in colorscale]) 

882 pivots = np.array([p for _, p in colorscale], dtype=float) 

883 else: 

884 colors = np.array([ManimColor(c).to_rgba() for c in colorscale]) 

885 pivots = np.linspace(low, high, len(colors)) 

886 v = np.asarray(values, dtype=float).reshape(-1) 

887 i = np.searchsorted(pivots, v, side="right") # the first pivot above each value 

888 inside = (i > 0) & (i < len(pivots)) 

889 ia, ib = np.clip(i - 1, 0, len(pivots) - 1), np.minimum(i, len(pivots) - 1) 

890 span = np.where(inside, pivots[ib] - pivots[ia], 1.0) 

891 t = np.where(inside, np.minimum(1.0, (v - pivots[ia]) / span), 0.0) 

892 mixed = mix_rgba(colors[ia], colors[ib], t) 

893 return np.where( 

894 inside[:, None], mixed, colors[np.where(i == 0, 0, len(pivots) - 1)] 

895 ) 

896 

897 

898def random_color() -> ManimColor: 

899 """A named color, drawn at random. 

900 

901 Python's `random` draws it, so `random.seed` makes it repeatable; see 

902 [RandomColorGenerator][manimgx.RandomColorGenerator] for a stream of its own. 

903 

904 Returns: 

905 One of the named colors. 

906 """ 

907 return random.choice(list(PALETTE.values())) 

908 

909 

910def random_bright_color() -> ManimColor: 

911 """A light color, drawn at random: its red, green and blue each from 0.5 to 1. 

912 

913 NumPy's global generator draws it, so `np.random.seed` makes it repeatable. 

914 

915 Returns: 

916 A new, opaque color. 

917 """ 

918 return ManimColor(tuple(1.0 - 0.5 * np.random.random(3))) 

919 

920 

921def _numbers(value: object) -> TypeIs[Sequence[float] | np.ndarray]: 

922 """An rgb(a) tuple or array: one color, not several.""" 

923 return isinstance(value, (Sequence, np.ndarray)) and all( 

924 isinstance(x, (int, float, np.integer, np.floating)) for x in value 

925 ) 

926 

927 

928@deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

929def parse_colors( 

930 value: ParsableManimColor | Iterable[ParsableManimColor] | None, 

931) -> list[ManimColor]: 

932 """Read one color or several, as a list. 

933 

934 Args: 

935 value: A color in any form [ManimColor][manimgx.ManimColor] reads (three or four 

936 numbers are one color), several colors, or None for black. 

937 

938 Returns: 

939 The colors, in a list. 

940 """ 

941 if value is None: 

942 return [BLACK] 

943 if isinstance(value, (str, ManimColor, int)) or _numbers(value): 

944 return [ManimColor(value)] 

945 return [ManimColor(c) for c in value] 

946 

947 

948# ── the named palette (Manim CE 0.21 names and values), as real constants ────── 

949WHITE: Final = ManimColor("#FFFFFF") 

950GRAY_A: Final = ManimColor("#DDDDDD") 

951GREY_A: Final = ManimColor("#DDDDDD") 

952GRAY_B: Final = ManimColor("#BBBBBB") 

953GREY_B: Final = ManimColor("#BBBBBB") 

954GRAY_C: Final = ManimColor("#888888") 

955GREY_C: Final = ManimColor("#888888") 

956GRAY_D: Final = ManimColor("#444444") 

957GREY_D: Final = ManimColor("#444444") 

958GRAY_E: Final = ManimColor("#222222") 

959GREY_E: Final = ManimColor("#222222") 

960BLACK: Final = ManimColor( 

961 "#000000" 

962) # here, as CE orders its palette (`random_color` draws from it) 

963LIGHTER_GRAY: Final = ManimColor("#DDDDDD") 

964LIGHTER_GREY: Final = ManimColor("#DDDDDD") 

965LIGHT_GRAY: Final = ManimColor("#BBBBBB") 

966LIGHT_GREY: Final = ManimColor("#BBBBBB") 

967GRAY: Final = ManimColor("#888888") 

968GREY: Final = ManimColor("#888888") 

969DARK_GRAY: Final = ManimColor("#444444") 

970DARK_GREY: Final = ManimColor("#444444") 

971DARKER_GRAY: Final = ManimColor("#222222") 

972DARKER_GREY: Final = ManimColor("#222222") 

973PURE_RED: Final = ManimColor("#FF0000") 

974PURE_GREEN: Final = ManimColor("#00FF00") 

975PURE_BLUE: Final = ManimColor("#0000FF") 

976PURE_CYAN: Final = ManimColor("#00FFFF") 

977PURE_MAGENTA: Final = ManimColor("#FF00FF") 

978PURE_YELLOW: Final = ManimColor("#FFFF00") 

979BLUE_A: Final = ManimColor("#C7E9F1") 

980BLUE_B: Final = ManimColor("#9CDCEB") 

981BLUE_C: Final = ManimColor("#58C4DD") 

982BLUE_D: Final = ManimColor("#29ABCA") 

983BLUE_E: Final = ManimColor("#236B8E") 

984BLUE: Final = ManimColor("#58C4DD") 

985DARK_BLUE: Final = ManimColor("#236B8E") 

986TEAL_A: Final = ManimColor("#ACEAD7") 

987TEAL_B: Final = ManimColor("#76DDC0") 

988TEAL_C: Final = ManimColor("#5CD0B3") 

989TEAL_D: Final = ManimColor("#55C1A7") 

990TEAL_E: Final = ManimColor("#49A88F") 

991TEAL: Final = ManimColor("#5CD0B3") 

992GREEN_A: Final = ManimColor("#C9E2AE") 

993GREEN_B: Final = ManimColor("#A6CF8C") 

994GREEN_C: Final = ManimColor("#83C167") 

995GREEN_D: Final = ManimColor("#77B05D") 

996GREEN_E: Final = ManimColor("#699C52") 

997GREEN: Final = ManimColor("#83C167") 

998YELLOW_A: Final = ManimColor("#FFF1B6") 

999YELLOW_B: Final = ManimColor("#FFEA94") 

1000YELLOW_C: Final = ManimColor("#F7D96F") 

1001YELLOW_D: Final = ManimColor("#F4D345") 

1002YELLOW_E: Final = ManimColor("#E8C11C") 

1003YELLOW: Final = ManimColor("#F7D96F") 

1004GOLD_A: Final = ManimColor("#F7C797") 

1005GOLD_B: Final = ManimColor("#F9B775") 

1006GOLD_C: Final = ManimColor("#F0AC5F") 

1007GOLD_D: Final = ManimColor("#E1A158") 

1008GOLD_E: Final = ManimColor("#C78D46") 

1009GOLD: Final = ManimColor("#F0AC5F") 

1010RED_A: Final = ManimColor("#F7A1A3") 

1011RED_B: Final = ManimColor("#FF8080") 

1012RED_C: Final = ManimColor("#FC6255") 

1013RED_D: Final = ManimColor("#E65A4C") 

1014RED_E: Final = ManimColor("#CF5044") 

1015RED: Final = ManimColor("#FC6255") 

1016MAROON_A: Final = ManimColor("#ECABC1") 

1017MAROON_B: Final = ManimColor("#EC92AB") 

1018MAROON_C: Final = ManimColor("#C55F73") 

1019MAROON_D: Final = ManimColor("#A24D61") 

1020MAROON_E: Final = ManimColor("#94424F") 

1021MAROON: Final = ManimColor("#C55F73") 

1022PURPLE_A: Final = ManimColor("#CAA3E8") 

1023PURPLE_B: Final = ManimColor("#B189C6") 

1024PURPLE_C: Final = ManimColor("#9A72AC") 

1025PURPLE_D: Final = ManimColor("#715582") 

1026PURPLE_E: Final = ManimColor("#644172") 

1027PURPLE: Final = ManimColor("#9A72AC") 

1028PINK: Final = ManimColor("#D147BD") 

1029LIGHT_PINK: Final = ManimColor("#DC75CD") 

1030ORANGE: Final = ManimColor("#FF862F") 

1031LIGHT_BROWN: Final = ManimColor("#CD853F") 

1032DARK_BROWN: Final = ManimColor("#8B4513") 

1033GRAY_BROWN: Final = ManimColor("#736357") 

1034GREY_BROWN: Final = ManimColor("#736357") 

1035LOGO_WHITE: Final = ManimColor("#ECE7E2") 

1036LOGO_GREEN: Final = ManimColor("#87C2A5") 

1037LOGO_BLUE: Final = ManimColor("#525893") 

1038LOGO_RED: Final = ManimColor("#E07A5F") 

1039LOGO_BLACK: Final = ManimColor("#343434") 

1040 

1041PALETTE: Final[dict[str, ManimColor]] = { 

1042 name: value 

1043 for name, value in globals().items() 

1044 if isinstance(value, ManimColor) and name.isupper() 

1045} 

1046"""The named colors, by name: `PALETTE["BLUE"]` is `BLUE`. A color's name, in any case, 

1047is read as the color.""" 

1048 

1049 

1050class HSV(ManimColor): 

1051 """A color made from a hue, saturation and value, which can be read and set. 

1052 

1053 `HSV(hsv, alpha=1.0)` takes the hue, saturation and value, each from 0 to 1, and 

1054 the opacity: a fourth number of `hsv`, if given, or else `alpha`, from 0 to 1. 

1055 Setting [hue][manimgx.HSV.hue], [saturation][manimgx.HSV.saturation] or 

1056 [value][manimgx.HSV.value] changes the color, as a value and as its `str`; it still 

1057 compares equal to (and hashes as) the string it was made as. 

1058 

1059 Examples: 

1060 ```python 

1061 import manimgx as m 

1062 

1063 

1064 class HSVExample(m.Scene): 

1065 def construct(self) -> None: 

1066 color = m.HSV((0.0, 0.7, 0.9)) 

1067 swatches = m.VGroup() 

1068 for step in range(8): 

1069 color.hue = step / 8 

1070 swatches.add(m.Square(side_length=1.2, color=color, fill_opacity=1)) 

1071 self.add(swatches.arrange(buff=0.3)) 

1072 ``` 

1073 """ 

1074 

1075 def __new__(cls, hsv: Sequence[float], alpha: float = 1.0) -> Self: 

1076 rgb = colorsys.hsv_to_rgb(*(float(x) for x in hsv[:3])) 

1077 return _made( 

1078 cls, np.array((*rgb, hsv[3] if len(hsv) > 3 else alpha), dtype=float) 

1079 ) 

1080 

1081 def _set(self, index: int, value: float) -> None: 

1082 hsv = list(self.to_hsv()) 

1083 hsv[index] = value 

1084 self._rgba[:3] = colorsys.hsv_to_rgb(*hsv) 

1085 

1086 h = hue = property( 

1087 lambda self: float(self.to_hsv()[0]), lambda self, v: self._set(0, v) 

1088 ) 

1089 """The color's hue, from 0 to 1: 0 (or 1) red, 1/3 green, 2/3 blue. Set it to change 

1090 the color.""" 

1091 s = saturation = property( 

1092 lambda self: float(self.to_hsv()[1]), lambda self, v: self._set(1, v) 

1093 ) 

1094 """The color's saturation, from 0 (grey) to 1 (the full color). Set it to change the 

1095 color.""" 

1096 v = value = property( 

1097 lambda self: float(self.to_hsv()[2]), lambda self, v: self._set(2, v) 

1098 ) 

1099 """The color's value, from 0 (black) to 1 (the brightest). Set it to change the 

1100 color.""" 

1101 

1102 

1103class RandomColorGenerator: 

1104 """A stream of colors drawn at random, the same for the same seed. 

1105 

1106 Args: 

1107 seed: The seed; None for a different stream each run. 

1108 sample_colors: The colors to draw from; None (or no colors) for the named 

1109 colors. 

1110 

1111 Examples: 

1112 ```python 

1113 import manimgx as m 

1114 

1115 

1116 class RandomColorGeneratorExample(m.Scene): 

1117 def construct(self) -> None: 

1118 palette = [m.RED, m.GREEN, m.BLUE, m.YELLOW, m.PURPLE, m.TEAL] 

1119 colors = m.RandomColorGenerator(seed=7, sample_colors=palette) 

1120 squares = m.VGroup( 

1121 *( 

1122 m.Square(side_length=1, color=colors.next(), fill_opacity=1) 

1123 for _ in range(40) 

1124 ) 

1125 ) 

1126 self.add(squares.arrange_in_grid(rows=4, buff=0.2)) 

1127 ``` 

1128 """ 

1129 

1130 def __init__( 

1131 self, seed: int | None = None, sample_colors: list[ManimColor] | None = None 

1132 ) -> None: 

1133 self.choice = random.Random(seed).choice 

1134 self.colors = sample_colors or list(PALETTE.values()) 

1135 

1136 def next(self) -> ManimColor: 

1137 """The stream's next color: one of its colors, drawn at random.""" 

1138 return self.choice(self.colors) 

1139 

1140 

1141if TYPE_CHECKING: 

1142 from manimgx.mobject import Mobject 

1143 from manimgx.scene import Camera 

1144 

1145type Colors = ParsableManimColor | Sequence[ParsableManimColor] 

1146 

1147 

1148@dataclass(frozen=True) 

1149class Material: 

1150 """How a surface reflects light: a physically based model, its base color the mobject's fill. 

1151 

1152 A mobject with a material is lit by the scene's lights 

1153 ([`SunLight`][manimgx.SunLight], [`PointLight`][manimgx.PointLight], 

1154 [`SpotLight`][manimgx.SpotLight], [`AmbientLight`][manimgx.AmbientLight], 

1155 [`EnvironmentLight`][manimgx.EnvironmentLight]) in a three-dimensional scene, and a mobject without one keeps Manim's shading 

1156 (`shade_in_3d`). Surfaces are lit, and so are flat filled shapes (their fill: a 

1157 shape's strokes keep their color); the shadows of whatever the scene shows fall on 

1158 them. What is fixed in the frame is not in the scene, and is not lit. A material 

1159 tweens: its numbers are mixed like colors. 

1160 

1161 Args: 

1162 metallic: How metallic it is, from 0 (a dielectric: plastic, paint, stone, skin) to 1 

1163 (a metal, whose reflections take its color). 

1164 roughness: How rough it is, from 0 (a mirror finish: sharp highlights) to 1 (matte). 

1165 reflectance: How much a dielectric reflects when seen head on, from 0 to 1 (0.5: 4%, 

1166 most materials; 0.35: water's 2%; 1: 16%, gems). 

1167 

1168 Examples: 

1169 ```python 

1170 import manimgx as m 

1171 

1172 

1173 class MaterialExample(m.ThreeDScene): 

1174 def construct(self) -> None: 

1175 self.set_camera_orientation(phi=70 * m.DEGREES, theta=-45 * m.DEGREES) 

1176 self.add( 

1177 m.SunLight(5 * m.UP + 3 * m.OUT), m.AmbientLight(intensity=0.2) 

1178 ) 

1179 for i, roughness in enumerate([0.2, 0.5, 0.9]): 

1180 sphere = m.Sphere(radius=0.8, resolution=(48, 48)) 

1181 sphere.set_color(m.GOLD).shift(2 * (i - 1) * m.RIGHT) 

1182 self.add( 

1183 sphere.set_material(m.Material(metallic=1, roughness=roughness)) 

1184 ) 

1185 ``` 

1186 """ 

1187 

1188 metallic: float = 0.0 

1189 roughness: float = 0.5 

1190 reflectance: float = 0.5 

1191 

1192 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

1193 def mixed(self, other: "Material", alpha: float) -> "Material": 

1194 """This material's numbers moved `alpha` of the way to `other`'s.""" 

1195 return Material( 

1196 *( 

1197 a + (b - a) * alpha 

1198 for a, b in ( 

1199 (self.metallic, other.metallic), 

1200 (self.roughness, other.roughness), 

1201 (self.reflectance, other.reflectance), 

1202 ) 

1203 ) 

1204 ) 

1205 

1206 

1207# Style is keyword-only, and a class never re-declares a style keyword to change its default 

1208# (that is what made typed kwargs combinatorial): it lists what it changes in `defaults`, and 

1209# the class hierarchy cascades. The one exception is `color`, which a few classes take by 

1210# position (as `Circle(1, RED)`); they declare it with a None default ("not given") and use 

1211# `StyleBase` for the rest. 

1212 

1213 

1214class _Look(TypedDict, total=False): 

1215 """Look's keys, open, for the keywords that add to them.""" 

1216 

1217 background_stroke_color: Colors | None 

1218 """The color of an outline drawn behind the fill (default black).""" 

1219 background_stroke_opacity: float | Sequence[float] 

1220 """The outline's opacity, from 0 to 1 (default 1).""" 

1221 background_stroke_width: float 

1222 """The outline's width, in hundredths of a scene unit (default 0: none).""" 

1223 sheen_factor: float 

1224 """How much the colors lighten toward `sheen_direction`, from -1 to 1 (default 0); 

1225 a negative factor darkens.""" 

1226 sheen_direction: Vector3DLike 

1227 """The direction the colors lighten toward (default [`UL`][manimgx.UL]).""" 

1228 joint_type: LineJointType | None 

1229 """How the stroke is joined where its path turns: round, beveled or mitered, as a 

1230 two-dimensional scene draws it (see [LineJointType][manimgx.LineJointType]; default 

1231 AUTO: mitered).""" 

1232 cap_style: CapStyleType 

1233 """How the stroke ends, at each end it shows (an open path's, a dash's): round, butt 

1234 or square, as a two-dimensional scene draws it (see 

1235 [CapStyleType][manimgx.CapStyleType]; default AUTO: butt).""" 

1236 shade_in_3d: bool 

1237 """Whether a three-dimensional scene's light shades the mobject.""" 

1238 material: Material | None 

1239 """How its surface reflects the scene's lights in a three-dimensional scene (see 

1240 [Material][manimgx.Material]); None: Manim's shading (default).""" 

1241 name: str | None 

1242 """A name for the mobject; its class's name if not given.""" 

1243 z_index: float 

1244 """Its place in the drawing order: a higher index is drawn over a lower one 

1245 (default 0).""" 

1246 target: "Mobject | None" 

1247 """The state [`MoveToTarget`][manimgx.MoveToTarget] moves the mobject to.""" 

1248 

1249 

1250class Look(_Look, total=False, closed=True): 

1251 """The style keywords that are not paint. 

1252 

1253 A mobject whose paint comes from its source (an SVG file, typeset text) takes these, 

1254 with [`Repaint`][manimgx.drawing.paint.Repaint] to paint over its source's colors. 

1255 """ 

1256 

1257 

1258class Repaint(TypedDict, total=False): 

1259 """Paint over the paint a mobject's source gives its parts. 

1260 

1261 An SVG file and typeset text color their own parts; each of these keywords, when given, 

1262 paints over them, and when absent (or None) keeps the source's. 

1263 """ 

1264 

1265 color: Colors | None 

1266 """The color of both fill and stroke.""" 

1267 opacity: float | None 

1268 """The opacity of both fill and stroke, from 0 to 1.""" 

1269 fill_color: Colors | None 

1270 """The fill's color.""" 

1271 fill_opacity: float | Sequence[float] | None 

1272 """The fill's opacity, from 0 to 1.""" 

1273 stroke_color: Colors | None 

1274 """The stroke's color.""" 

1275 stroke_opacity: float | Sequence[float] | None 

1276 """The stroke's opacity, from 0 to 1.""" 

1277 stroke_width: float | None 

1278 """The stroke's width, in hundredths of a scene unit.""" 

1279 

1280 

1281class _StyleBase(_Look, total=False): 

1282 """StyleBase's keys, open, for the keywords that add to them.""" 

1283 

1284 fill_color: Colors | None 

1285 """The fill's color; `color` if not given. Several colors make a gradient along 

1286 `sheen_direction`.""" 

1287 fill_opacity: float | Sequence[float] 

1288 """The fill's opacity, from 0 to 1 (default 0: no fill).""" 

1289 stroke_color: Colors | None 

1290 """The stroke's color; `color` if not given. Several colors make a gradient.""" 

1291 stroke_opacity: float | Sequence[float] 

1292 """The stroke's opacity, from 0 to 1 (default 1).""" 

1293 stroke_width: float 

1294 """The stroke's width, in hundredths of a scene unit (default 4; 0: no stroke).""" 

1295 

1296 

1297class StyleBase(_StyleBase, total=False, closed=True): 

1298 """Every style keyword but `color`. 

1299 

1300 A class that takes `color` by position declares it itself, and the rest with this. 

1301 """ 

1302 

1303 

1304class _Style(_StyleBase, total=False): 

1305 """Style's keys, open, for the keywords that add to them.""" 

1306 

1307 color: Colors | None 

1308 """The color of both fill and stroke (default white); None for the class's default.""" 

1309 

1310 

1311class Style(_Style, total=False, closed=True): 

1312 """The style keywords: one vocabulary for every mobject and every group. 

1313 

1314 Every mobject takes these keywords, and each class sets its own defaults for them 

1315 (a [`Circle`][manimgx.Circle] is red, a [`Dot`][manimgx.Dot] is filled). A color is 

1316 anything [`ManimColor`][manimgx.ManimColor] parses: a named color such as `BLUE`, 

1317 a hex string, or RGB values. 

1318 """ 

1319 

1320 

1321class Fill(TypedDict): 

1322 """A fill's color and opacity: an image's style (`ImageMobject.get_style()`).""" 

1323 

1324 fill_color: ManimColor 

1325 fill_opacity: float 

1326 

1327 

1328class SimpleStyle(Fill): 

1329 """A style by its first brushes (`VMobject.get_style(simple=True)`).""" 

1330 

1331 stroke_color: ManimColor 

1332 stroke_opacity: float 

1333 stroke_width: float 

1334 

1335 

1336class StyleSnapshot(TypedDict): 

1337 """A style, brush by brush (`VMobject.get_style()`): `set_style(**snapshot)` restores it.""" 

1338 

1339 fill_color: list[ManimColor] 

1340 fill_opacity: list[float] 

1341 stroke_color: list[ManimColor] 

1342 stroke_opacity: list[float] 

1343 stroke_width: float 

1344 background_stroke_color: list[ManimColor] 

1345 background_stroke_opacity: list[float] 

1346 background_stroke_width: float 

1347 sheen_factor: float 

1348 sheen_direction: Vector3D 

1349 

1350 

1351def key_of(value: object) -> object: 

1352 """A plain value as a memo's key, by what it is: a color by its exact RGBA (not its 

1353 hex), a small array by its dtype and bytes, a path by its text, a list or tuple 

1354 item by item. Scalar types distinguish integer RGB from normalized floats. 

1355 Anything else (a mobject, a function, a picture) raises TypeError: what is made 

1356 from it is not remembered.""" 

1357 if isinstance(value, ManimColor): 

1358 return (ManimColor, *value.to_rgba()) 

1359 if value is None: 

1360 return None 

1361 if isinstance(value, (str, int, float, Enum)): 

1362 return (type(value), value) 

1363 if isinstance(value, Material): 

1364 return (Material, value.metallic, value.roughness, value.reflectance) 

1365 if type(value) is dict: 

1366 return (dict, tuple((key_of(k), key_of(v)) for k, v in value.items())) 

1367 if isinstance(value, (list, tuple)): 

1368 return (type(value), tuple(key_of(v) for v in value)) 

1369 if isinstance(value, np.ndarray) and value.size <= 64 and not value.dtype.hasobject: 

1370 return (np.ndarray, value.dtype, value.shape, value.tobytes()) 

1371 if isinstance(value, PurePath): 

1372 return (PurePath, str(value)) 

1373 raise TypeError(type(value)) 

1374 

1375 

1376_PARSED: Memo[tuple[object, object], RGBA_Array] = Memo(1 << 12) 

1377 

1378 

1379def rgbas( 

1380 color: ParsableManimColor | Iterable[ParsableManimColor] | None, 

1381 opacity: float | Iterable[float] | None, 

1382) -> RGBA_Array: 

1383 """CE `generate_rgbas_array` without sheen (None color: black; None opacity: 0), parsed once 

1384 per distinct (color, opacity).""" 

1385 try: 

1386 key = (key_of(color), key_of(opacity)) 

1387 except TypeError: 

1388 return _rgbas(color, opacity) 

1389 return _PARSED.recall(key, lambda: frozen(_rgbas(color, opacity))) 

1390 

1391 

1392def _rgbas( 

1393 color: ParsableManimColor | Iterable[ParsableManimColor] | None, 

1394 opacity: float | Iterable[float] | None, 

1395) -> RGBA_Array: 

1396 colors = parse_colors(color) 

1397 opacities = list(opacity) if isinstance(opacity, Iterable) else [opacity] 

1398 opacities = [o if o is not None else 0.0 for o in opacities] 

1399 n = max(len(colors), len(opacities)) 

1400 colors = stretch(colors, n) 

1401 opacities = stretch(opacities, n) 

1402 return np.array( 

1403 [c.to_rgba_with_alpha(o) for c, o in zip(colors, opacities, strict=True)] 

1404 ) 

1405 

1406 

1407def stretch[T](values: list[T], n: int) -> list[T]: 

1408 """CE `make_even` for one list: repeat entries so the list has length n.""" 

1409 if len(values) == n: 

1410 return values 

1411 return [values[i * len(values) // n] for i in range(n)] 

1412 

1413 

1414def stretch_array(array: np.ndarray, n: int) -> np.ndarray: 

1415 """Stretch an array to `n` items, repeating its items evenly, in order. 

1416 

1417 Item `i` of the result is item `i * len(array) // n` of the array. 

1418 

1419 Args: 

1420 array: The items, along its first axis. 

1421 n: How many items the result has: at least as many as the array has (fewer 

1422 raise ValueError). 

1423 

1424 Returns: 

1425 The array itself if it has `n` items; else a new one. 

1426 """ 

1427 cur = len(array) 

1428 if cur == n: 

1429 return array 

1430 if cur > n: 

1431 raise ValueError("Can't stretch array to a shorter length") 

1432 return array[(np.arange(n) * cur // n).astype(int)] 

1433 

1434 

1435@deprecated("stretch_array_to_length is stretch_array: use it", category=None) 

1436def stretch_array_to_length(array: np.ndarray, n: int) -> np.ndarray: 

1437 """Manim CE's name for [stretch_array][manimgx.stretch_array].""" 

1438 return stretch_array(array, n) 

1439 

1440 

1441def frozen(values: npt.ArrayLike, held: object = None) -> np.ndarray: 

1442 """Adopt an internal float array as read-only; keep `held` when they are equal. 

1443 

1444 Inputs are fresh buffers or values already owned by paint. Public style 

1445 setters copy borrowed arrays before transferring them here. 

1446 """ 

1447 array = np.asarray(values, dtype=float) 

1448 if isinstance(held, np.ndarray) and unchanged(array, held): 

1449 return held 

1450 if array.flags.writeable: 

1451 if not array.flags.owndata: 

1452 array = array.copy() 

1453 array.flags.writeable = False 

1454 return array 

1455 

1456 

1457class Paint: 

1458 """How a mobject is painted, as a value: a change makes a new paint, so copies share one and 

1459 what is derived from it (a record) holds while a mobject keeps it. It stores only what differs 

1460 from the default (the class attributes). A tween's paint leaves brushes (None) to its `mix` 

1461 (brushes_a, brushes_b, t), which the player mixes. Capturing brush inputs 

1462 materializes any prior mixes; no source paint or its other resources is kept.""" 

1463 

1464 _fill: RGBA_Array | None = frozen([[1.0, 1.0, 1.0, 0.0]]) 

1465 _stroke: RGBA_Array | None = frozen([[1.0, 1.0, 1.0, 1.0]]) 

1466 _background: RGBA_Array | None = frozen([[0.0, 0.0, 0.0, 1.0]]) 

1467 stroke_width: float = 4.0 

1468 background_width: float = 0.0 

1469 sheen_factor: float = 0.0 

1470 sheen_direction: np.ndarray = frozen(UL) 

1471 joint: LineJointType = LineJointType.AUTO 

1472 cap: CapStyleType = CapStyleType.AUTO 

1473 shade_in_3d: bool = False 

1474 material: "Material | None" = None 

1475 texture: "np.ndarray | Camera | None" = None # pixels (h, w, 4) uint8, or a camera 

1476 # the texture is the fill's colors by value (a colormap): a fill color replaces it 

1477 colormap: bool = False 

1478 trim: np.ndarray = frozen([0.0, 1.0]) # the reveal window, fractions of the length 

1479 pace: tuple[np.ndarray, np.ndarray] | None = ( 

1480 None # (length fraction, u) at reveal start 

1481 ) 

1482 # dashes: (period, duty, phase) over the path's parameter, drawn where 

1483 # frac((u − phase) / period) < duty — a second, periodic window beside `trim` 

1484 dash: tuple[float, float, float] | None = None 

1485 mix: tuple[tuple[RGBA_Array, ...], tuple[RGBA_Array, ...], float] | None = None 

1486 # what was derived from this paint: changes asked of it, and their results (its own, made with it) 

1487 _derived: dict[tuple[object, ...], object] 

1488 

1489 def __init__(self) -> None: 

1490 self.__dict__["_derived"] = {} 

1491 

1492 def __setattr__(self, name: str, value: object) -> None: 

1493 raise AttributeError("a paint never changes: derive one with `but`") 

1494 

1495 @property 

1496 def fill(self) -> RGBA_Array: 

1497 return self._fill if self._fill is not None else self._mixed("fill") 

1498 

1499 @property 

1500 def stroke(self) -> RGBA_Array: 

1501 return self._stroke if self._stroke is not None else self._mixed("stroke") 

1502 

1503 @property 

1504 def background(self) -> RGBA_Array: 

1505 b = self._background 

1506 return b if b is not None else self._mixed("background") 

1507 

1508 def _mixed(self, name: str) -> RGBA_Array: 

1509 """A brush left to the tween, read here: mixed as the player mixes it, once.""" 

1510 known = self._derived.get(("brush", name)) 

1511 if known is None: 

1512 assert self.mix is not None 

1513 a, b, t = self.mix 

1514 index = _BRUSHES.index(name) 

1515 known = self._derived[("brush", name)] = frozen( 

1516 mix_rgba(a[index], b[index], t) 

1517 ) 

1518 return cast("RGBA_Array", known) 

1519 

1520 def ends(self, name: str) -> tuple[RGBA_Array, RGBA_Array]: 

1521 """A brush's two arrays as the player draws them, mixed by `mix`.""" 

1522 own = getattr(self, _SLOTS[name]) 

1523 if own is not None: 

1524 return own, own 

1525 assert self.mix is not None 

1526 a, b, _ = self.mix 

1527 index = _BRUSHES.index(name) 

1528 return a[index], b[index] 

1529 

1530 def but(self, **changes: object) -> "Paint": 

1531 """This paint with some fields changed (`fill`, `stroke`, `background`: brushes) — 

1532 itself when they change nothing (arrays equal to those it holds), and the same paint 

1533 for the same plain changes, so what was derived from it holds too. Textures are 

1534 borrowed resources: equal only by identity, and their changes are not remembered. 

1535 

1536 Internal brush and direction arrays transfer ownership: callers must not 

1537 change them or their aliases afterward. Public mobject style setters 

1538 snapshot borrowed values before deriving a paint. 

1539 """ 

1540 try: 

1541 key: tuple[object, ...] | None = ( 

1542 "but", 

1543 *((name, _kept(name, value)) for name, value in changes.items()), 

1544 ) 

1545 except TypeError: 

1546 key = None 

1547 derived = self._derived 

1548 if key is not None and (known := derived.get(key)) is not None: 

1549 return cast("Paint", known) 

1550 new = self._but(changes) 

1551 if key is not None and all( 

1552 not isinstance(value, np.ndarray) 

1553 or value is getattr(new, _SLOTS.get(name, name), None) 

1554 for name, value in changes.items() 

1555 ): 

1556 if len(derived) > 32: 

1557 derived.clear() 

1558 derived[key] = new 

1559 return new 

1560 

1561 def _but(self, changes: dict[str, object]) -> "Paint": 

1562 fields = self.__dict__.copy() 

1563 changed = False 

1564 numbers: list[tuple[object, object]] = [] # given anew: equal to those held? 

1565 for name, value in changes.items(): 

1566 slot = _SLOTS.get(name, name) 

1567 held = getattr(self, slot, None) 

1568 if value is not None and (name in _ARRAYS or name in _SLOTS): 

1569 value = frozen(cast("npt.ArrayLike", value), held) 

1570 elif ( 

1571 name != "texture" 

1572 and isinstance(value, np.ndarray) 

1573 and unchanged(value, held) 

1574 ): 

1575 value = held 

1576 elif name in _NUMERIC and value is not held: 

1577 numbers.append((value, held)) # (compared only if nothing else changes) 

1578 fields[slot] = value 

1579 continue 

1580 changed = changed or value is not held 

1581 fields[slot] = value 

1582 if not changed and all(_same_number(*pair) for pair in numbers): 

1583 return self 

1584 fields["_derived"] = {} 

1585 if fields.get("mix") is not None and all( 

1586 fields.get(slot, True) is not None for slot in _SLOTS.values() 

1587 ): 

1588 fields["mix"] = None # no brush is left to the tween 

1589 new = object.__new__(Paint) 

1590 object.__setattr__(new, "__dict__", fields) 

1591 return new 

1592 

1593 def window(self, steps: int) -> tuple[float, float]: 

1594 """The reveal window over u ∈ [0, steps] — what the player draws. u counts a shape's 

1595 steps: a path's curves (its parameter, paced by `pace`), a cloud's points, a mesh's 

1596 triangles, a surface's faces; a step the window reaches into shows, with all it draws.""" 

1597 if self.pace is None: 

1598 return float(self.trim[0]) * steps, float(self.trim[1]) * steps 

1599 s, u = self.pace 

1600 lo, hi = np.interp(self.trim, s, u) 

1601 return float(lo), float(hi) 

1602 

1603 def updated( 

1604 self, 

1605 name: str, 

1606 color: ParsableManimColor | Iterable[ParsableManimColor] | None, 

1607 opacity: float | Iterable[float] | None, 

1608 ) -> "Paint": 

1609 """CE `update_rgbas_array`: colors and/or opacities written into one brush — remembered, 

1610 and the paint itself when nothing changes.""" 

1611 try: 

1612 key: tuple[object, ...] | None = ( 

1613 "updated", 

1614 name, 

1615 key_of(color), 

1616 key_of(opacity), 

1617 ) 

1618 except TypeError: 

1619 key = None 

1620 derived = self._derived 

1621 if key is not None and (known := derived.get(key)) is not None: 

1622 return cast("Paint", known) 

1623 result = self._updated(name, color, opacity) 

1624 if key is not None: 

1625 if len(derived) > 32: 

1626 derived.clear() 

1627 derived[key] = result 

1628 return result 

1629 

1630 def _updated( 

1631 self, 

1632 name: str, 

1633 color: ParsableManimColor | Iterable[ParsableManimColor] | None, 

1634 opacity: float | Iterable[float] | None, 

1635 ) -> "Paint": 

1636 new = rgbas(color, opacity) 

1637 if self.sheen_factor != 0 and len(new) == 1: 

1638 light = new.copy() 

1639 light[:, :3] = np.clip(light[:, :3] + self.sheen_factor, 0, 1) 

1640 new = np.append(new, light, axis=0) 

1641 cur = getattr(self, name) 

1642 if len(cur) == 0: # a brush of no rows (a cloud of no points): nothing to color 

1643 return self 

1644 if len(cur) < len(new): 

1645 cur = stretch_array(cur, len(new)) 

1646 elif len(new) < len(cur): 

1647 new = stretch_array(new, len(cur)) 

1648 out = np.array(cur, dtype=float) 

1649 if color is not None: 

1650 out[:, :3] = new[:, :3] 

1651 if opacity is not None: 

1652 out[:, 3] = new[:, 3] 

1653 if color is not None and name == "fill" and self.colormap: 

1654 return self.but(fill=out, texture=None, colormap=False) 

1655 if unchanged(out, cur): # what is written changes nothing (the brush stretched) 

1656 return self 

1657 return self.but(**{name: out}) 

1658 

1659 @staticmethod 

1660 def aligned(a: "Paint", b: "Paint") -> tuple["Paint", "Paint"]: 

1661 """Both paints with the same number of brush rows (CE `align_rgbas`).""" 

1662 changes_a: dict[str, np.ndarray] = {} 

1663 changes_b: dict[str, np.ndarray] = {} 

1664 for name in _BRUSHES: 

1665 x, y = getattr(a, name), getattr(b, name) 

1666 if len(x) > len(y): 

1667 changes_b[name] = stretch_array(y, len(x)) 

1668 elif len(y) > len(x): 

1669 changes_a[name] = stretch_array(x, len(y)) 

1670 return (a.but(**changes_a) if changes_a else a), ( 

1671 b.but(**changes_b) if changes_b else b 

1672 ) 

1673 

1674 def mixed(self, a: "Paint", b: "Paint", alpha: float) -> "Paint": 

1675 """This paint with a's numeric fields blended into b's (joint, cap… stay this paint's): 

1676 brushes left to the tween (`mix`, OKLab, by the player), the rest linearly.""" 

1677 changes: dict[str, object] = { 

1678 "pace": b.pace if alpha == 1.0 or a.pace is None else a.pace, 

1679 "dash": ( 

1680 (b.dash if alpha >= 0.5 else a.dash) # dashed ↔ solid: at the middle 

1681 if a.dash is None or b.dash is None 

1682 else tuple( 

1683 x + (y - x) * alpha for x, y in zip(a.dash, b.dash, strict=True) 

1684 ) 

1685 ), 

1686 "mix": None, 

1687 "material": ( 

1688 ( 

1689 b.material if alpha >= 0.5 else a.material 

1690 ) # lit ↔ Manim's shading: at the middle 

1691 if a.material is None or b.material is None 

1692 else a.material.mixed(b.material, alpha) 

1693 ), 

1694 } 

1695 for name in _LERPED: 

1696 x, y = getattr(a, name), getattr(b, name) 

1697 changes[name] = y if alpha == 1.0 or x is y else interpolate(x, y, alpha) 

1698 for name, w, v in ( 

1699 ("stroke_width", a.stroke_width, b.stroke_width), 

1700 ("background_width", a.background_width, b.background_width), 

1701 ): # past its ends an overshooting rate function: no width < 0 

1702 width = v if alpha == 1.0 or w is v else interpolate(w, v, alpha) 

1703 changes[name] = 0.0 if width < 0 else width 

1704 for name, slot in _SLOTS.items(): 

1705 x, y = getattr(a, slot), getattr(b, slot) # None: a tween's 

1706 if alpha >= 1.0 or alpha <= 0.0: 

1707 changes[name] = getattr(b if alpha >= 1.0 else a, name) 

1708 elif x is not None and x is y: 

1709 changes[name] = x 

1710 else: 

1711 changes[name] = None 

1712 if changes["mix"] is None: 

1713 changes["mix"] = ( 

1714 (a.fill, a.stroke, a.background), 

1715 (b.fill, b.stroke, b.background), 

1716 alpha, 

1717 ) 

1718 return self._but(changes) # a frame's paint: nothing to remember it by 

1719 

1720 

1721_LERPED = ("sheen_direction", "sheen_factor", "trim") 

1722 

1723 

1724def _kept(name: str, value: object) -> object: 

1725 """A change as a key: plain values by value; a read-only array a paint keeps by identity (the 

1726 derived paint holds it, so no other array can take its id while remembered).""" 

1727 if name == "texture" and isinstance(value, np.ndarray): 

1728 raise TypeError(type(value)) 

1729 if ( 

1730 isinstance(value, np.ndarray) 

1731 and not value.flags.writeable 

1732 and value.dtype == np.float64 

1733 and (name in _SLOTS or name in _ARRAYS) 

1734 ): 

1735 return ("kept", id(value)) 

1736 return key_of(value) 

1737 

1738 

1739_BRUSHES = ("fill", "stroke", "background") 

1740 

1741 

1742# numbers as concrete classes: `isinstance` on an ABC (`numbers.Real`) is slow 

1743_NUMBERS = (int, float, np.number) 

1744 

1745 

1746def _same_number(value: object, held: object) -> bool: 

1747 """Whether `value` is a number, or a tuple of numbers (a dash), equal to the one held: a 

1748 change to it is none (an equal width of another type, or another object, keeps the 

1749 paint).""" 

1750 if isinstance(value, _NUMBERS): # (as floats: a numpy scalar's == is a ufunc's) 

1751 return isinstance(held, _NUMBERS) and float(value) == float(held) 

1752 return ( 

1753 isinstance(value, tuple) 

1754 and isinstance(held, tuple) 

1755 and len(value) == len(held) > 0 

1756 and isinstance(value[0], _NUMBERS) 

1757 and all(map(_same_number, value, held)) 

1758 ) 

1759 

1760 

1761_SLOTS = {"fill": "_fill", "stroke": "_stroke", "background": "_background"} 

1762_ARRAYS = ("_fill", "_stroke", "_background", "sheen_direction", "trim") 

1763_NUMERIC = frozenset({"stroke_width", "background_width", "sheen_factor", "dash"}) 

1764 

1765 

1766class PaintAttribute[T]: 

1767 """A CE style attribute of a mobject (`mob.joint_type`), kept in its paint's `field`.""" 

1768 

1769 def __init__(self, field: str) -> None: 

1770 self.field = field 

1771 

1772 @overload 

1773 def __get__(self, mob: None, owner: type) -> Self: ... 

1774 @overload 

1775 def __get__(self, mob: "Mobject", owner: type) -> T: ... 

1776 def __get__(self, mob: "Mobject | None", owner: type) -> "T | Self": 

1777 return self if mob is None else getattr(mob.paint, self.field) 

1778 

1779 def __set__(self, mob: "Mobject", value: T) -> None: 

1780 mob.paint = mob.paint.but(**{self.field: value}) 

1781 

1782 

1783class PaintArray[G: np.ndarray, S: npt.ArrayLike = npt.ArrayLike]: 

1784 """A CE style attribute of a mobject that is an array (`mob.fill_rgbas`), kept in its 

1785 paint's `field`: read as the paint keeps it (G), set from S, copied as float values.""" 

1786 

1787 def __init__(self, field: str) -> None: 

1788 self.field = field 

1789 

1790 @overload 

1791 def __get__(self, mob: None, owner: type) -> Self: ... 

1792 @overload 

1793 def __get__(self, mob: "Mobject", owner: type) -> G: ... 

1794 def __get__(self, mob: "Mobject | None", owner: type) -> "G | Self": 

1795 return self if mob is None else getattr(mob.paint, self.field) 

1796 

1797 def __set__(self, mob: "Mobject", value: S) -> None: 

1798 array = frozen(np.array(value, dtype=float, copy=True)) 

1799 mob.paint = mob.paint.but(**{self.field: array})