forked from bevyengine/bevy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
time.rs
298 lines (264 loc) · 10.3 KB
/
time.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use bevy_ecs::{reflect::ReflectResource, system::Resource};
use bevy_reflect::{FromReflect, Reflect};
use bevy_utils::{Duration, Instant};
/// The duration after which the time will go wrap back to 0
#[derive(Debug, Clone, Copy)]
pub enum WrapDuration {
/// Will wrap after 1 hour or 3600 seconds
Default,
/// Used to provide any duration to use as the period.
///
/// It is highly recommended to not go above the maximum value of a day
Custom(Duration),
/// Will wrap after 1 day or 86400 seconds.
///
/// `f32`'s have about 6-7 significant numbers and a day is 86400 seconds,
/// add a few decimal places for millis and you will start to get precision errors.
Max,
}
impl From<WrapDuration> for Duration {
fn from(val: WrapDuration) -> Self {
match val {
WrapDuration::Default => Duration::from_secs(60 * 60), // 1 hour
WrapDuration::Custom(duration) => duration,
WrapDuration::Max => Duration::from_secs(60 * 60 * 24), // 1 day
}
}
}
/// Tracks elapsed time since the last update and since the App has started
#[derive(Resource, Reflect, FromReflect, Debug, Clone)]
#[reflect(Resource)]
pub struct Time {
delta: Duration,
last_update: Option<Instant>,
delta_seconds_f64: f64,
delta_seconds: f32,
seconds_since_startup: f64,
time_since_startup: Duration,
startup: Instant,
}
impl Default for Time {
fn default() -> Time {
Time {
delta: Duration::from_secs(0),
last_update: None,
startup: Instant::now(),
delta_seconds_f64: 0.0,
seconds_since_startup: 0.0,
time_since_startup: Duration::from_secs(0),
delta_seconds: 0.0,
}
}
}
impl Time {
/// Updates the internal time measurements.
///
/// Calling this method on the [`Time`] resource as part of your app will most likely result in
/// inaccurate timekeeping, as the resource is ordinarily managed by the
/// [`TimePlugin`](crate::TimePlugin).
pub fn update(&mut self) {
self.update_with_instant(Instant::now());
}
/// Update time with a specified [`Instant`]
///
/// This method is provided for use in tests. Calling this method on the [`Time`] resource as
/// part of your app will most likely result in inaccurate timekeeping, as the resource is
/// ordinarily managed by the [`TimePlugin`](crate::TimePlugin).
///
/// # Examples
///
/// ```
/// # use bevy_time::prelude::*;
/// # use bevy_ecs::prelude::*;
/// # use bevy_utils::Duration;
/// # fn main () {
/// # test_health_system();
/// # }
/// #[derive(Resource)]
/// struct Health {
/// // Health value between 0.0 and 1.0
/// health_value: f32,
/// }
///
/// fn health_system(time: Res<Time>, mut health: ResMut<Health>) {
/// // Increase health value by 0.1 per second, independent of frame rate,
/// // but not beyond 1.0
/// health.health_value = (health.health_value + 0.1 * time.delta_seconds()).min(1.0);
/// }
///
/// // Mock time in tests
/// fn test_health_system() {
/// let mut world = World::default();
/// let mut time = Time::default();
/// time.update();
/// world.insert_resource(time);
/// world.insert_resource(Health { health_value: 0.2 });
///
/// let mut update_stage = SystemStage::single_threaded();
/// update_stage.add_system(health_system);
///
/// // Simulate that 30 ms have passed
/// let mut time = world.resource_mut::<Time>();
/// let last_update = time.last_update().unwrap();
/// time.update_with_instant(last_update + Duration::from_millis(30));
///
/// // Run system
/// update_stage.run(&mut world);
///
/// // Check that 0.003 has been added to the health value
/// let expected_health_value = 0.2 + 0.1 * 0.03;
/// let actual_health_value = world.resource::<Health>().health_value;
/// assert_eq!(expected_health_value, actual_health_value);
/// }
/// ```
pub fn update_with_instant(&mut self, instant: Instant) {
if let Some(last_update) = self.last_update {
self.delta = instant - last_update;
self.delta_seconds_f64 = self.delta.as_secs_f64();
self.delta_seconds = self.delta.as_secs_f32();
}
self.time_since_startup = instant - self.startup;
self.seconds_since_startup = self.time_since_startup.as_secs_f64();
self.last_update = Some(instant);
}
/// The delta between the current tick and last tick as a [`Duration`]
#[inline]
pub fn delta(&self) -> Duration {
self.delta
}
/// The delta between the current and last tick as [`f32`] seconds
#[inline]
pub fn delta_seconds(&self) -> f32 {
self.delta_seconds
}
/// The delta between the current and last tick as [`f64`] seconds
#[inline]
pub fn delta_seconds_f64(&self) -> f64 {
self.delta_seconds_f64
}
/// The time from startup to the last update in seconds
///
/// If you need an `f32` value, it is highly recommended to use [`Time::seconds_since_startup_f32_wrapped`]
/// instead of casting it. Casting to an `f32` can cause floating point precision issues pretty fast.
#[inline]
pub fn seconds_since_startup(&self) -> f64 {
self.seconds_since_startup
}
/// The time from the last wrap period to the last update in seconds.
///
/// When used in shaders, the time is limited to `f32` which can introduce floating point precision issues
/// fairly quickly if the app is left open for a while.
/// This will wrap the value to 0.0 on the update after the `Self::max_wrapping_period`.
///
/// Defaults to wrapping every hour.
#[inline]
pub fn seconds_since_startup_f32_wrapped(&self, duration: WrapDuration) -> f32 {
let duration: Duration = duration.into();
(self.seconds_since_startup % duration.as_secs_f64()) as f32
}
/// The [`Instant`] the app was started
#[inline]
pub fn startup(&self) -> Instant {
self.startup
}
/// The [`Instant`] when [`Time::update`] was last called, if it exists
#[inline]
pub fn last_update(&self) -> Option<Instant> {
self.last_update
}
/// The [`Duration`] from startup to the last update
#[inline]
pub fn time_since_startup(&self) -> Duration {
self.time_since_startup
}
}
#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
use super::{Time, WrapDuration};
use bevy_utils::{Duration, Instant};
#[test]
fn update_test() {
let start_instant = Instant::now();
// Create a `Time` for testing
let mut time = Time {
startup: start_instant,
..Default::default()
};
// Ensure `time` was constructed correctly
assert_eq!(time.delta(), Duration::from_secs(0));
assert_eq!(time.last_update(), None);
assert_eq!(time.startup(), start_instant);
assert_eq!(time.delta_seconds_f64(), 0.0);
assert_eq!(time.seconds_since_startup(), 0.0);
assert_eq!(time.time_since_startup(), Duration::from_secs(0));
assert_eq!(time.delta_seconds(), 0.0);
assert_eq!(
time.seconds_since_startup_f32_wrapped(WrapDuration::Default),
0.0
);
// Update `time` and check results
let first_update_instant = Instant::now();
time.update_with_instant(first_update_instant);
assert_eq!(time.delta(), Duration::from_secs(0));
assert_eq!(time.last_update(), Some(first_update_instant));
assert_eq!(time.startup(), start_instant);
assert_eq!(time.delta_seconds_f64(), 0.0);
assert_eq!(
time.seconds_since_startup(),
(first_update_instant - start_instant).as_secs_f64()
);
assert_eq!(
time.time_since_startup(),
(first_update_instant - start_instant)
);
assert_eq!(time.delta_seconds(), 0.0);
assert_float_eq(
time.seconds_since_startup_f32_wrapped(WrapDuration::Default),
time.seconds_since_startup() as f32,
);
// Update `time` again and check results
let second_update_instant = Instant::now();
time.update_with_instant(second_update_instant);
assert_eq!(time.delta(), second_update_instant - first_update_instant);
assert_eq!(time.last_update(), Some(second_update_instant));
assert_eq!(time.startup(), start_instant);
// At this point its safe to use time.delta as a valid value
// because it's been previously verified to be correct
assert_eq!(time.delta_seconds_f64(), time.delta().as_secs_f64());
assert_eq!(
time.seconds_since_startup(),
(second_update_instant - start_instant).as_secs_f64()
);
assert_eq!(
time.time_since_startup(),
(second_update_instant - start_instant)
);
assert_eq!(time.delta_seconds(), time.delta().as_secs_f32());
assert_float_eq(
time.seconds_since_startup_f32_wrapped(WrapDuration::Default),
time.seconds_since_startup() as f32,
);
}
#[test]
fn update_wrapping() {
let start_instant = Instant::now();
let mut time = Time {
startup: start_instant,
..Default::default()
};
let wrap_duration = WrapDuration::Custom(Duration::from_secs(3));
assert_eq!(time.seconds_since_startup_f32_wrapped(wrap_duration), 0.0);
time.update_with_instant(start_instant + Duration::from_secs(1));
assert_float_eq(time.seconds_since_startup_f32_wrapped(wrap_duration), 1.0);
time.update_with_instant(start_instant + Duration::from_secs(2));
assert_float_eq(time.seconds_since_startup_f32_wrapped(wrap_duration), 2.0);
time.update_with_instant(start_instant + Duration::from_secs(3));
assert_float_eq(time.seconds_since_startup_f32_wrapped(wrap_duration), 0.0);
time.update_with_instant(start_instant + Duration::from_secs(4));
assert_float_eq(time.seconds_since_startup_f32_wrapped(wrap_duration), 1.0);
}
fn assert_float_eq(a: f32, b: f32) {
assert!((a - b).abs() <= f32::EPSILON, "{a} != {b}");
}
}