Coverage for src/manimgx/animation/clock.py: 100%

61 statements  

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

1"""Scene time: one exact clock, and the clocks that run off it. 

2 

3A frame shows the world at one instant (frame k at k/fps). An animation is evaluated at its own 

4window of scene time; a time-based updater gets the time its clock ran since it last stepped; a 

5per-frame updater re-establishes its relation. A flow (an updater whose steps compose) is exact 

6at any instant; any other time-based updater is simulated on the simulation clock 

7(`config.simulation_rate` ticks a second, plus the scene's events), so it behaves the same at 

8every frame rate. `speed` runs off scene time, warped by ChangeSpeed.""" 

9 

10from collections.abc import Callable 

11from fractions import Fraction 

12from itertools import pairwise 

13from math import inf, nextafter, ulp 

14 

15 

16def _rounding_cell(value: float) -> tuple[Fraction, Fraction, bool]: 

17 """The binary64 rounding interval, and whether its ties belong to this value.""" 

18 magnitude = abs(value) 

19 exact = Fraction(magnitude) 

20 low = (exact + Fraction(nextafter(magnitude, -inf))) / 2 

21 high = exact + Fraction(ulp(magnitude)) / 2 

22 closed = float(low) == magnitude 

23 return (-high, -low, closed) if value < 0 else (low, high, closed) 

24 

25 

26def rational(value: float | Fraction) -> Fraction: 

27 """Recover the simplest rational that rounds to an authored float. 

28 

29 A duration such as 5/6 keeps its frame boundary, while distinct floats stay distinct 

30 and a positive duration never becomes zero. Integers and explicit fractions are exact. 

31 """ 

32 exact = Fraction(value) 

33 if not isinstance(value, float) or exact.denominator == 1: 

34 return exact 

35 low, high, _ = _rounding_cell(abs(value)) 

36 # Both midpoints have larger denominators than exact itself, so excluding ties 

37 # cannot exclude the simplest candidate and avoids either neighbor's tie rule. 

38 # The continued fractions of the rounding interval share these integer parts. 

39 # The first integer strictly inside it gives the smallest possible denominator. 

40 a, b, c, d = low.numerator, low.denominator, high.numerator, high.denominator 

41 before, denominator = 1, 0 

42 while True: 

43 whole = a // b 

44 if (whole + 1) * d < c: 

45 denominator = (whole + 1) * denominator + before 

46 return Fraction(round(exact * denominator), denominator) 

47 before, denominator = denominator, whole * denominator + before 

48 a, b, c, d = d, c - whole * d, b, a - whole * b 

49 

50 

51def frame_at(time: float | Fraction, rate: Fraction, *, after: bool = False) -> int: 

52 """First frame at this observed instant or later (strictly later with `after`).""" 

53 low, high, closed = _rounding_cell(float(time)) 

54 at = (high if after else low) * rate 

55 return int(at // 1 + 1 if closed == after else -(-at // 1)) 

56 

57 

58now = Fraction(0) 

59"""The instant being computed — or, between plays, the end of the last one (where the scene's 

60own code runs).""" 

61stepping: bool = True 

62"""Do simulated updaters (time-based, not flows) step at `now`? At every instant — unless the 

63scene is simulating: then at the ticks of its simulation clock and at its events only.""" 

64framing: bool = True 

65"""Do per-frame updaters run at `now`? At frames and events — not at a tick between frames: an 

66updater that takes no time is called once a frame, whatever else the scene simulates.""" 

67 

68 

69class Clock: 

70 """Local time as a function of scene time: scene time, except over its warps (from `start`, for 

71 `duration`, covering `span` of local time along `progress`, a monotone map of [0, 1] onto 

72 itself). Where warps overlap, the one begun last rules while it lasts, so the clock only ever 

73 runs forward.""" 

74 

75 def __init__(self) -> None: 

76 self.warps: list[tuple[float, float, float, Callable[[float], float]]] = [] 

77 

78 def warp( 

79 self, 

80 start: float, 

81 duration: float, 

82 span: float, 

83 progress: Callable[[float], float], 

84 ) -> None: 

85 self.warps.append((start, duration, span, progress)) 

86 self.warps.sort(key=lambda w: w[0]) 

87 

88 def at(self, t: float) -> float: 

89 # scene time cut at every warp's start and end; each piece runs at the pace of the 

90 # warp begun last among those covering it, or at scene time's own 

91 cuts = sorted({0.0, t, *(x for w in self.warps for x in (w[0], w[0] + w[1]))}) 

92 local = 0.0 

93 for a, b in pairwise(cuts): 

94 if b > t: 

95 break 

96 ruling = None 

97 for w in self.warps: # sorted by start: the last one covering (a, b) rules 

98 if w[0] <= a and b <= w[0] + w[1]: 

99 ruling = w 

100 if ruling is None: 

101 local += b - a 

102 else: 

103 start, duration, span, progress = ruling 

104 if duration > 0: 

105 local += span * ( 

106 progress((b - start) / duration) 

107 - progress((a - start) / duration) 

108 ) 

109 return local 

110 

111 

112speed = Clock() 

113 

114 

115def reset() -> None: 

116 """A new scene: its clock at 0, no warps.""" 

117 global now, stepping, framing 

118 now, stepping, framing = Fraction(0), True, True 

119 speed.warps.clear()