Skip to main content

oxframe_core/
runtime.rs

1//! Per-thread context of the scene being executed.
2//!
3//! The [`Executor`](crate::Executor) installs its runtime for the duration
4//! of each step, so free functions like [`now`] and [`wait_until`]
5//! (crate::wait_until) work inside scene code without passing handles.
6
7use std::cell::{Cell, RefCell};
8use std::rc::Rc;
9
10use oxframe_protocol::Meta;
11use rand::SeedableRng;
12use rand_chacha::ChaCha8Rng;
13
14use crate::CubicBezier;
15use crate::ease::presets;
16use crate::flow::Task;
17use crate::transition::Recorded;
18
19pub(crate) struct Runtime {
20    pub fps: f64,
21    pub frame: Cell<u32>,
22    /// Virtual time of the task being polled. It can lag behind the frame
23    /// time by a fraction of a frame: when a tween ends between frames, the
24    /// next tween starts at the exact end time, so timings do not drift.
25    pub task_time: Cell<f64>,
26    pub spawned: RefCell<Vec<Task>>,
27    pub meta: RefCell<Meta>,
28    pub meta_changed: Cell<bool>,
29    pub rng: RefCell<ChaCha8Rng>,
30    /// Set by the engine: this scene has one before it, so a transition blends.
31    pub has_previous: Cell<bool>,
32    /// The transition declared by the scene, if it starts one.
33    pub transition: RefCell<Option<Recorded>>,
34}
35
36impl Runtime {
37    pub fn new(fps: f64, meta: Meta, seed: u64) -> Rc<Self> {
38        assert!(fps > 0.0 && fps.is_finite(), "fps must be positive");
39        Rc::new(Self {
40            fps,
41            frame: Cell::new(0),
42            task_time: Cell::new(0.0),
43            spawned: RefCell::new(Vec::new()),
44            meta: RefCell::new(meta),
45            meta_changed: Cell::new(false),
46            rng: RefCell::new(ChaCha8Rng::seed_from_u64(seed)),
47            has_previous: Cell::new(false),
48            transition: RefCell::new(None),
49        })
50    }
51
52    pub fn now(&self) -> f64 {
53        f64::from(self.frame.get()) / self.fps
54    }
55}
56
57thread_local! {
58    static CURRENT: RefCell<Option<Rc<Runtime>>> = const { RefCell::new(None) };
59}
60
61/// Restores the previously installed runtime on drop.
62pub(crate) struct Installed(Option<Rc<Runtime>>);
63
64pub(crate) fn install(rt: &Rc<Runtime>) -> Installed {
65    Installed(CURRENT.with(|c| c.borrow_mut().replace(rt.clone())))
66}
67
68impl Drop for Installed {
69    fn drop(&mut self) {
70        let prev = self.0.take();
71        CURRENT.with(|c| *c.borrow_mut() = prev);
72    }
73}
74
75pub(crate) fn with<R>(f: impl FnOnce(&Runtime) -> R) -> R {
76    CURRENT.with(|c| {
77        let c = c.borrow();
78        let rt = c
79            .as_ref()
80            .expect("oxframe: this function can only be called while a scene is running");
81        f(rt)
82    })
83}
84
85/// Index of the frame being computed.
86pub fn frame() -> u32 {
87    with(|rt| rt.frame.get())
88}
89
90/// Frames per second of the running project.
91pub fn fps() -> f64 {
92    with(|rt| rt.fps)
93}
94
95/// Duration of one frame in seconds, `1 / fps`.
96pub fn dt() -> f64 {
97    with(|rt| 1.0 / rt.fps)
98}
99
100/// Time of the current frame, `frame / fps` seconds.
101pub fn now() -> f64 {
102    with(|rt| rt.now())
103}
104
105/// Whether the running scene has a scene before it.
106pub fn has_previous() -> bool {
107    with(|rt| rt.has_previous.get())
108}
109
110/// Records `spec`, letting `meta.json` override its duration the way markers
111/// do. Returns the duration to wait. Panics if the scene already started one.
112pub fn begin_transition(mut spec: Recorded) -> f64 {
113    with(|rt| {
114        if rt.transition.borrow().is_some() {
115            panic!("oxframe: a scene can declare only one transition; call it once, at the start");
116        }
117        let stored = rt.meta.borrow().transition.as_ref().map(|t| t.seconds);
118        if let Some(seconds) = stored {
119            spec.seconds = if seconds.is_finite() {
120                seconds.max(0.0)
121            } else {
122                0.0
123            };
124        } else if spec.seconds.is_finite() && spec.seconds > 0.0 {
125            let seconds = spec.seconds;
126            rt.meta.borrow_mut().transition = Some(oxframe_protocol::TransitionMeta { seconds });
127            rt.meta_changed.set(true);
128        } else {
129            spec.seconds = 0.0;
130        }
131        let seconds = spec.seconds;
132        if seconds > 0.0 {
133            *rt.transition.borrow_mut() = Some(spec);
134        }
135        seconds
136    })
137}
138
139/// Virtual time of the current task — where the next animation starts.
140pub fn time() -> f64 {
141    with(|rt| rt.task_time.get())
142}
143
144/// Value of tunable `name` from `meta.json`; `default` is recorded there on
145/// first use. Use through the `tune!` macro.
146pub fn tunable(name: &str, default: f64) -> f64 {
147    with(|rt| {
148        let mut meta = rt.meta.borrow_mut();
149        if let Some(v) = meta.tunables.get(name) {
150            return *v;
151        }
152        meta.tunables.insert(name.to_owned(), default);
153        rt.meta_changed.set(true);
154        default
155    })
156}
157
158/// Named easing from `meta.json`; `default` is recorded there on first use.
159/// Use through the `ease!` macro.
160pub fn ease_named(name: &str, default: Option<CubicBezier>) -> CubicBezier {
161    with(|rt| {
162        let mut meta = rt.meta.borrow_mut();
163        if let Some(v) = meta.eases.get(name) {
164            return CubicBezier::from_array(*v);
165        }
166        let default = default.unwrap_or(presets::DEFAULT);
167        meta.eases.insert(name.to_owned(), default.to_array());
168        rt.meta_changed.set(true);
169        default
170    })
171}
172
173/// Marker time from `meta.json`; the current task time is recorded on first
174/// encounter.
175pub(crate) fn marker(name: &str) -> f64 {
176    with(|rt| {
177        let mut meta = rt.meta.borrow_mut();
178        if let Some(v) = meta.markers.get(name) {
179            return *v;
180        }
181        let t = rt.task_time.get();
182        meta.markers.insert(name.to_owned(), t);
183        rt.meta_changed.set(true);
184        t
185    })
186}
187
188/// Copy of the running scene's markers, eases and tunables.
189pub fn meta_snapshot() -> Meta {
190    with(|rt| rt.meta.borrow().clone())
191}
192
193/// Runs `f` with the scene's random generator. It is seeded from the
194/// project seed and the scene name, so results are reproducible; never use
195/// `rand::rng()` or other entropy sources in scenes.
196pub fn with_rng<R>(f: impl FnOnce(&mut ChaCha8Rng) -> R) -> R {
197    with(|rt| f(&mut rt.rng.borrow_mut()))
198}
199
200/// Uniform random number in `[0, 1)` from the scene's seeded generator.
201pub fn random() -> f64 {
202    use rand::RngExt;
203    with_rng(|r| r.random::<f64>())
204}
205
206/// Uniform random number in `[min, max)` from the scene's seeded generator.
207pub fn random_range(min: f64, max: f64) -> f64 {
208    min + (max - min) * random()
209}
210
211/// A generator seeded by the caller. Drawing with this does not advance the
212/// scene's [`random`] generator, and the same seed always yields the same
213/// sequence, including after a seek.
214#[derive(Clone)]
215pub struct SeededRng(ChaCha8Rng);
216
217impl SeededRng {
218    /// Generator for `seed`. The same seed is the same sequence.
219    pub fn new(seed: u64) -> Self {
220        Self(ChaCha8Rng::seed_from_u64(seed))
221    }
222
223    /// Uniform number in `[0, 1)`.
224    pub fn next_f64(&mut self) -> f64 {
225        use rand::RngExt;
226        self.0.random::<f64>()
227    }
228
229    /// Uniform number in `span` (`end` is excluded).
230    pub fn range(&mut self, span: std::ops::Range<f64>) -> f64 {
231        let w = span.end - span.start;
232        span.start + w * self.next_f64()
233    }
234}