byte-engine 0.1.0

A composable Rust game engine focused on graphics, input, audio, physics, and retained UI.
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use std::time::Instant;

use crate::{
	time::MediaTime,
	ui::layout::{context::Context, engine::EvaluationContext},
};

const MAX_STEP: f32 = 1.0 / 30.0;
const SETTLE_EPSILON: f32 = 0.001;

pub enum Curves {
	Linear,
}

type EaseFunction = fn(f32) -> f32;

fn capped_frame_duration(dt: MediaTime) -> MediaTime {
	MediaTime::from_seconds_f32(dt.as_seconds_f32().min(MAX_STEP))
}

fn ease_in_curve(t: f32) -> f32 {
	let t = t.clamp(0.0, 1.0);
	t * t
}

fn ease_out_curve(t: f32) -> f32 {
	let t = t.clamp(0.0, 1.0);
	1.0 - (1.0 - t) * (1.0 - t)
}

fn ease_out_cubic_curve(t: f32) -> f32 {
	let t = t.clamp(0.0, 1.0);
	1.0 - (1.0 - t).powi(3)
}

fn ease_out_quart_curve(t: f32) -> f32 {
	let t = t.clamp(0.0, 1.0);
	1.0 - (1.0 - t).powi(4)
}

fn emphasized_out_curve(t: f32) -> f32 {
	let t = t.clamp(0.0, 1.0);
	1.0 - (1.0 - t).powi(5)
}

fn ease_in_out_curve(t: f32) -> f32 {
	let t = t.clamp(0.0, 1.0);
	if t < 0.5 {
		2.0 * t * t
	} else {
		1.0 - (-2.0 * t + 2.0).powi(2) * 0.5
	}
}

pub trait AnimationDriver {
	fn value(&self) -> f32;
	fn advance(&mut self, dt: MediaTime) -> f32;
	fn is_complete(&self) -> bool;
	fn finish(&mut self) -> f32;
}

#[derive(Debug, Clone, Copy)]
pub struct Easing {
	elapsed: f32,
	duration: f32,
	curve: EaseFunction,
}

#[derive(Debug, Clone, Copy)]
pub struct BackOut {
	elapsed: f32,
	duration: f32,
	overshoot: f32,
}

pub fn ease_in(duration: f32) -> Easing {
	Easing::new(duration, ease_in_curve)
}

pub fn ease_out(duration: f32) -> Easing {
	Easing::new(duration, ease_out_curve)
}

pub fn ease_out_cubic(duration: f32) -> Easing {
	Easing::new(duration, ease_out_cubic_curve)
}

pub fn ease_out_quart(duration: f32) -> Easing {
	Easing::new(duration, ease_out_quart_curve)
}

pub fn emphasized_out(duration: f32) -> Easing {
	Easing::new(duration, emphasized_out_curve)
}

pub fn ease_in_out(duration: f32) -> Easing {
	Easing::new(duration, ease_in_out_curve)
}

pub fn back_out(duration: f32, overshoot: f32) -> BackOut {
	BackOut::new(duration, overshoot)
}

impl Easing {
	fn new(duration: f32, curve: EaseFunction) -> Self {
		Self {
			elapsed: 0.0,
			duration: duration.max(0.0),
			curve,
		}
	}

	fn progress(&self) -> f32 {
		if self.duration == 0.0 {
			1.0
		} else {
			(self.elapsed / self.duration).clamp(0.0, 1.0)
		}
	}
}

impl BackOut {
	fn new(duration: f32, overshoot: f32) -> Self {
		Self {
			elapsed: 0.0,
			duration: duration.max(0.0),
			overshoot: overshoot.max(0.0),
		}
	}

	fn progress(&self) -> f32 {
		if self.duration == 0.0 {
			1.0
		} else {
			(self.elapsed / self.duration).clamp(0.0, 1.0)
		}
	}
}

impl AnimationDriver for Easing {
	fn value(&self) -> f32 {
		(self.curve)(self.progress())
	}

	fn advance(&mut self, dt: MediaTime) -> f32 {
		self.elapsed = (self.elapsed + dt.as_seconds_f32()).min(self.duration);
		self.value()
	}

	fn is_complete(&self) -> bool {
		self.elapsed >= self.duration
	}

	fn finish(&mut self) -> f32 {
		self.elapsed = self.duration;
		self.value()
	}
}

impl AnimationDriver for BackOut {
	fn value(&self) -> f32 {
		let t = self.progress() - 1.0;
		1.0 + t * t * ((self.overshoot + 1.0) * t + self.overshoot)
	}

	fn advance(&mut self, dt: MediaTime) -> f32 {
		self.elapsed = (self.elapsed + dt.as_seconds_f32()).min(self.duration);
		self.value()
	}

	fn is_complete(&self) -> bool {
		self.elapsed >= self.duration
	}

	fn finish(&mut self) -> f32 {
		self.elapsed = self.duration;
		self.value()
	}
}

#[derive(Debug, Clone, Copy)]
pub struct Spring {
	value: f32,
	target: f32,
	velocity: f32,
	mass: f32,
	stiffness: f32,
	damping: f32,
}

pub fn spring(from: f32, to: f32) -> Spring {
	Spring::new(from, to)
}

impl Spring {
	pub fn new(from: f32, to: f32) -> Self {
		Self {
			value: from,
			target: to,
			velocity: 0.0,
			mass: 1.0,
			stiffness: 380.0,
			damping: 16.0,
		}
	}

	pub fn value(&self) -> f32 {
		self.value
	}

	pub fn target(&self) -> f32 {
		self.target
	}

	pub fn velocity(&self) -> f32 {
		self.velocity
	}

	pub fn step(&mut self, dt: MediaTime) -> f32 {
		let dt = dt.as_seconds_f32().min(MAX_STEP);
		if dt <= 0.0 {
			return self.value;
		}

		let displacement = self.value - self.target;
		let spring_force = -self.stiffness * displacement;
		let damping_force = -self.damping * self.velocity;
		let acceleration = (spring_force + damping_force) / self.mass;

		self.velocity += acceleration * dt;
		self.value += self.velocity * dt;
		self.value
	}

	pub fn is_settled(&self) -> bool {
		(self.value - self.target).abs() <= SETTLE_EPSILON && self.velocity.abs() <= SETTLE_EPSILON
	}

	pub fn finish(&mut self) -> f32 {
		self.value = self.target;
		self.velocity = 0.0;
		self.value
	}
}

impl AnimationDriver for Spring {
	fn value(&self) -> f32 {
		Spring::value(self)
	}

	fn advance(&mut self, dt: MediaTime) -> f32 {
		Spring::step(self, dt)
	}

	fn is_complete(&self) -> bool {
		Spring::is_settled(self)
	}

	fn finish(&mut self) -> f32 {
		Spring::finish(self)
	}
}

pub async fn animate<C: 'static, A, F>(target: &mut EvaluationContext<C>, mut animation: A, mut apply: F)
where
	A: AnimationDriver,
	F: FnMut(&mut EvaluationContext<C>, f32),
{
	apply(target, animation.value());

	let mut last_frame = Instant::now();
	while !animation.is_complete() {
		target.render().await;
		let now = Instant::now();
		animation.advance(capped_frame_duration(MediaTime::from_std(now.duration_since(last_frame))));
		last_frame = now;
		apply(target, animation.value());
	}

	apply(target, animation.finish());
}

pub struct Animation<V: Interpolate> {
	keyframes: Vec<(f32, V)>,
}

impl<V: Interpolate> Default for Animation<V> {
	fn default() -> Self {
		Self::new()
	}
}

impl<V: Interpolate> Animation<V> {
	pub fn new() -> Self {
		Self { keyframes: Vec::new() }
	}

	pub fn add_keyframe(&mut self, time: f32, value: V) {
		self.keyframes.push((time, value));
	}
}

pub struct Track<V: Interpolate> {
	animation: Animation<V>,
	duration: f32,
	current_time: f32,
}

impl<V: Interpolate> Track<V> {
	pub fn new(animation: Animation<V>, duration: f32) -> Self {
		Self {
			animation,
			duration,
			current_time: 0.0,
		}
	}

	pub fn update(&mut self, dt: f32) -> V {
		self.current_time += dt;
		if self.current_time > self.duration {
			self.current_time = 0.0;
		}

		let mut keyframes = self.animation.keyframes.iter();
		let mut prev = keyframes.next().unwrap();
		for curr in keyframes {
			if self.current_time < curr.0 {
				return prev.1.interpolate(&curr.1, (self.current_time - prev.0) / (curr.0 - prev.0));
			}
			prev = curr;
		}
		prev.1.interpolate(&prev.1, 0.0)
	}
}

pub trait Interpolate {
	fn interpolate(&self, other: &Self, t: f32) -> Self;
}

impl Interpolate for f32 {
	fn interpolate(&self, other: &Self, t: f32) -> Self {
		self * (1.0 - t) + other * t
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn spring_moves_toward_target() {
		let mut spring = spring(0.0, 1.0);

		spring.step(MediaTime::from_millis(16));

		assert!(spring.value() > 0.0);
		assert!(spring.value() < 1.0);
	}

	#[test]
	fn spring_overshoots_with_default_config() {
		let mut spring = spring(0.0, 1.0);
		let mut peak = 0.0f32;

		for _ in 0..60 {
			spring.step(MediaTime::from_millis(16));
			peak = peak.max(spring.value());
		}

		assert!(peak > 1.08);
	}

	#[test]
	fn spring_settles_to_exact_target() {
		let mut spring = spring(0.0, 1.0);

		for _ in 0..240 {
			spring.step(MediaTime::from_millis(16));
			if spring.is_settled() {
				break;
			}
		}

		assert!(spring.is_settled());
		assert_eq!(spring.finish(), 1.0);
		assert_eq!(spring.velocity(), 0.0);
	}

	#[test]
	fn spring_clamps_large_steps() {
		let mut large_step = spring(0.0, 1.0);
		let mut capped_step = spring(0.0, 1.0);

		large_step.step(MediaTime::from_seconds(1));
		capped_step.step(MediaTime::from_seconds_f32(MAX_STEP));

		assert_eq!(large_step.value(), capped_step.value());
	}

	#[test]
	fn animation_frame_duration_is_capped_for_all_drivers() {
		assert!((capped_frame_duration(MediaTime::from_seconds(1)).as_seconds_f32() - MAX_STEP).abs() < f32::EPSILON);
		assert!((capped_frame_duration(MediaTime::from_millis(16)).as_seconds_f32() - 0.016).abs() < f32::EPSILON);
	}

	#[test]
	fn easing_drivers_preserve_endpoints_and_handle_zero_duration() {
		let mut ease_in_driver = ease_in(1.0);
		let mut ease_out_driver = ease_out(1.0);
		let mut ease_in_out_driver = ease_in_out(1.0);
		let mut emphasized_out_driver = emphasized_out(1.0);
		let mut back_out_driver = back_out(1.0, 1.70158);

		assert_eq!(ease_in_driver.value(), 0.0);
		assert_eq!(ease_out_driver.value(), 0.0);
		assert_eq!(ease_in_out_driver.value(), 0.0);
		assert_eq!(emphasized_out_driver.value(), 0.0);
		assert_eq!(back_out_driver.value(), 0.0);

		assert_eq!(ease_in_driver.finish(), 1.0);
		assert_eq!(ease_out_driver.finish(), 1.0);
		assert_eq!(ease_in_out_driver.finish(), 1.0);
		assert_eq!(emphasized_out_driver.finish(), 1.0);
		assert_eq!(back_out_driver.finish(), 1.0);

		assert_eq!(ease_in(-1.0).value(), 1.0);
	}

	#[test]
	fn easing_drivers_have_expected_midpoint_shape() {
		let mut ease_in_driver = ease_in(1.0);
		let mut ease_out_driver = ease_out(1.0);
		let mut ease_in_out_driver = ease_in_out(1.0);

		ease_in_driver.advance(MediaTime::from_millis(500));
		ease_out_driver.advance(MediaTime::from_millis(500));
		ease_in_out_driver.advance(MediaTime::from_millis(500));

		assert!(ease_in_driver.value() < 0.5);
		assert!(ease_out_driver.value() > 0.5);
		assert_eq!(ease_in_out_driver.value(), 0.5);

		let mut ease_in_out_first_half = ease_in_out(1.0);
		let mut ease_in_out_second_half = ease_in_out(1.0);
		ease_in_out_first_half.advance(MediaTime::from_millis(250));
		ease_in_out_second_half.advance(MediaTime::from_millis(750));

		assert!(ease_in_out_first_half.value() < 0.25);
		assert!(ease_in_out_second_half.value() > 0.75);
	}

	#[test]
	fn emphasized_easing_moves_more_decisively_than_quadratic_ease_out() {
		let mut quadratic = ease_out(1.0);
		let mut cubic = ease_out_cubic(1.0);
		let mut quart = ease_out_quart(1.0);
		let mut emphasized = emphasized_out(1.0);

		quadratic.advance(MediaTime::from_millis(250));
		cubic.advance(MediaTime::from_millis(250));
		quart.advance(MediaTime::from_millis(250));
		emphasized.advance(MediaTime::from_millis(250));

		assert!(cubic.value() > quadratic.value());
		assert!(quart.value() > cubic.value());
		assert!(emphasized.value() > quart.value());
		assert!(emphasized.value() < 1.0);
	}

	#[test]
	fn back_out_overshoots_before_settling() {
		let mut driver = back_out(1.0, 1.70158);

		driver.advance(MediaTime::from_millis(600));
		assert!(driver.value() > 1.0);

		assert_eq!(driver.finish(), 1.0);
	}
}