1use ferravex_core::session::{GameSession, SessionState};
10use ferravex_play::camera::{Input3, Mode3, NoObstructions, Pose3, Rig3, Settings3, Target3};
11use ferravex_play::feedback::{FeedbackConfig, FeedbackController, FeedbackEvent, FeedbackFrame};
12use ferravex_play::particles::{
13 Emitter, EmitterTransform, ParticlePool, RibbonFacing, Trail, TrailConfig, TrailSample, presets,
14};
15use ferravex_play::vehicle::{FlightHandling, FlightState};
16use ferravex_render::audio::{Cue, GameAudio};
17use ferravex_render::effects::{
18 BillboardView, EffectStyle, ParticleRenderer, ParticleStyle, draw_ribbon,
19};
20use ferravex_render::input::{
21 HintDevice, PlayerInput, Preset,
22 touch::{Control, Output, Region},
23};
24use ferravex_render::preferences;
25use ferravex_render::ui::kit::ButtonMotion;
26use ferravex_render::ui::{ButtonOptions, Ui, UiRect, Viewport};
27use ferravex_render::{
28 demo::Demo,
29 mesh::Mesh3d,
30 prelude::*,
31 shaders::{LitMaterial, LitSettings},
32};
33
34#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
35mod capture;
36mod courier;
37mod flight_ui;
38mod look;
39mod overlay;
40mod presentation;
41mod quips;
42use courier::{BONUS_RADIUS, BONUS_RINGS, Impact, Ledger, line_miss};
43use flight_ui::{Coach, HudView, Progress, Results, hud};
44use presentation::FlightPresentation;
45
46const INK: Color = Color::new(0.10, 0.20, 0.22, 1.0);
47const CREAM: Color = Color::new(0.95, 0.91, 0.78, 1.0);
48const CORAL: Color = Color::new(0.82, 0.36, 0.23, 1.0);
49const AMBER: Color = Color::new(0.93, 0.70, 0.34, 1.0);
50const GATES: usize = 5;
51const DELIVERY_SPEED: f32 = 18.;
52const ROUTE: [Vec3; 6] = [
53 vec3(0., 24., 100.),
54 vec3(44., 40., 205.),
55 vec3(-20., 30., 320.),
56 vec3(-62., 47., 430.),
57 vec3(10., 34., 550.),
58 vec3(0., 16., 680.),
59];
60const ISLANDS: [(Vec3, f32); 9] = [
61 (vec3(-42., 1., 73.), 30.),
62 (vec3(67., 13., 207.), 30.),
63 (vec3(-48., 7., 315.), 31.),
64 (vec3(-86., 22., 430.), 30.),
65 (vec3(38., 10., 553.), 30.),
66 (vec3(0., 8., 680.), 37.),
67 (vec3(112., 4., 380.), 40.),
68 (vec3(-130., 14., 170.), 36.),
69 (vec3(105., 7., 680.), 29.),
70];
71
72#[derive(Default, Clone, Copy)]
73struct Input {
74 turn: f32,
75 climb: f32,
76 boost: bool,
77 slow: bool,
78}
79impl Input {
80 fn neutral(self) -> bool {
81 self.turn.abs() < 0.05 && self.climb.abs() < 0.05 && !self.boost && !self.slow
82 }
83}
84#[derive(Clone, Copy, Debug, PartialEq)]
85enum Outcome {
86 Flying,
87 Delivered,
88 Lost,
89}
90struct Flight {
91 pos: Vec3,
92 motor: FlightState,
93 next: usize,
94 hull: u8,
95 remaining: f32,
96 outcome: Outcome,
97 recovery: f32,
98 boost_energy: f32,
99 boost_exhausted: bool,
100 gate_notice: f32,
101 boosting: bool,
102 slowing: bool,
103 ledger: Ledger,
104 bonus_notice: f32,
106}
107impl Flight {
108 fn new() -> Self {
109 Self {
110 pos: vec3(0., 20., 0.),
111 motor: FlightState {
112 yaw: 0.,
113 pitch: 0.,
114 bank: 0.,
115 turn_rate: 0.,
116 speed: 24.,
117 },
118 next: 0,
119 hull: 3,
120 remaining: 90.,
121 outcome: Outcome::Flying,
122 recovery: 0.,
123 boost_energy: 1.,
124 boost_exhausted: false,
125 gate_notice: 0.,
126 boosting: false,
127 slowing: false,
128 ledger: Ledger::default(),
129 bonus_notice: 0.,
130 }
131 }
132 fn forward(&self) -> Vec3 {
133 self.motor.forward()
134 }
135 #[cfg(test)]
136 fn damage(&mut self) {
137 self.crash(Impact::Water);
138 }
139 fn crash(&mut self, cause: Impact) {
140 if self.recovery > 0. || self.outcome != Outcome::Flying {
141 return;
142 }
143 self.ledger.impact(cause);
144 self.hull = self.hull.saturating_sub(1);
145 self.remaining = (self.remaining - 5.).max(0.);
146 if self.hull == 0 || self.remaining == 0. {
147 self.outcome = Outcome::Lost;
148 return;
149 }
150 self.pos = if self.next == 0 {
151 vec3(0., 20., 0.)
152 } else {
153 ROUTE[self.next - 1]
154 };
155 let delta = ROUTE[self.next] - self.pos;
156 self.motor
157 .reset(delta.x.atan2(delta.z), 0., 24.)
158 .expect("authored checkpoint heading and cruise speed");
159 self.boosting = false;
160 self.slowing = false;
161 self.recovery = 2.5;
162 }
163 fn tick(&mut self, input: Input, dt: f32) {
164 if self.outcome != Outcome::Flying {
165 return;
166 }
167 self.remaining = (self.remaining - dt).max(0.);
168 if self.remaining <= 0. {
169 self.outcome = Outcome::Lost;
170 return;
171 }
172 self.recovery = (self.recovery - dt).max(0.);
173 self.gate_notice = (self.gate_notice - dt).max(0.);
174 self.bonus_notice = (self.bonus_notice - dt).max(0.);
175 if self.boost_energy < 0.03 {
176 self.boost_exhausted = true;
177 }
178 if self.boost_energy > 0.3 {
179 self.boost_exhausted = false;
180 }
181 let boosting = input.boost && !input.slow && !self.boost_exhausted;
182 self.boosting = boosting;
183 self.slowing = input.slow;
184 self.boost_energy =
185 (self.boost_energy + dt * if boosting { -0.32 } else { 0.16 }).clamp(0., 1.);
186 let target_speed = if input.slow {
187 13.
188 } else if boosting {
189 35.
190 } else {
191 24.
192 };
193 self.motor
194 .step(
195 FlightHandling::default(),
196 input.turn,
197 input.climb,
198 target_speed,
199 dt,
200 )
201 .unwrap();
202 let previous = self.pos;
203 self.pos += self.forward() * self.motor.speed * dt;
204 let impact = if self.pos.y < -17. {
205 Some(Impact::Water)
206 } else if self.pos.y > 110.
207 || self.pos.x.abs() > 260.
208 || self.pos.z < -90.
209 || self.pos.z > 850.
210 {
211 Some(Impact::Boundary)
212 } else if island_hit(self.pos) {
213 Some(Impact::Island)
214 } else {
215 None
216 };
217 if let Some(cause) = impact {
218 self.crash(cause);
219 return;
220 }
221 for (index, ring) in BONUS_RINGS.iter().enumerate() {
223 if segment_hits(previous, self.pos, *ring, BONUS_RADIUS)
224 && self.ledger.bonus(index).is_some()
225 {
226 self.boost_energy = 1.;
227 self.boost_exhausted = false;
228 self.bonus_notice = 2.5;
229 }
230 }
231 let radius = if self.next == GATES { 8. } else { 8.5 };
233 if segment_hits(previous, self.pos, ROUTE[self.next], radius)
234 && (self.next < GATES || self.motor.speed <= DELIVERY_SPEED)
235 {
236 let miss = line_miss(self.pos, self.forward(), ROUTE[self.next]);
238 if self.next < GATES {
239 self.ledger.gate(self.next, miss, self.boosting);
240 } else {
241 self.ledger.deliver(miss, self.motor.speed, self.remaining);
242 }
243 self.boost_energy = (self.boost_energy + 0.18).min(1.);
244 self.next += 1;
245 self.gate_notice = 2.;
246 if self.next == ROUTE.len() {
247 self.outcome = Outcome::Delivered;
248 }
249 }
250 }
251 fn steer_toward(&self, target: Vec3) -> Input {
253 let delta = target - self.pos;
254 let bearing = (delta.x.atan2(delta.z) - self.motor.yaw + std::f32::consts::PI)
255 .rem_euclid(std::f32::consts::TAU)
256 - std::f32::consts::PI;
257 let pitch = delta.y.atan2(vec2(delta.x, delta.z).length());
258 Input {
259 turn: (bearing * 2.7).clamp(-1., 1.),
260 climb: (pitch / 0.58).clamp(-1., 1.),
261 ..Input::default()
262 }
263 }
264 fn autopilot(&self) -> Input {
265 if self.outcome != Outcome::Flying {
266 return Input::default();
267 }
268 let delta = ROUTE[self.next] - self.pos;
269 Input {
270 slow: self.next == GATES && delta.length() < 90.,
271 ..self.steer_toward(ROUTE[self.next])
272 }
273 }
274 #[cfg(any(test, all(debug_assertions, not(target_arch = "wasm32"))))]
276 fn scenic_tour(&self) -> Input {
277 if self.outcome == Outcome::Flying {
278 for (index, after) in [1, 3, 5].into_iter().enumerate() {
279 if self.next == after && self.ledger.bonus & (1 << index) == 0 {
280 return self.steer_toward(BONUS_RINGS[index]);
281 }
282 }
283 }
284 self.autopilot()
285 }
286 fn navigation(&self) -> Option<Navigation> {
287 let target = *ROUTE.get(self.next)?;
288 let delta = target - self.pos;
289 Some(Navigation {
290 bearing: (delta.x.atan2(delta.z) - self.motor.yaw + std::f32::consts::PI)
291 .rem_euclid(std::f32::consts::TAU)
292 - std::f32::consts::PI,
293 altitude: delta.y,
294 distance: delta.length(),
295 })
296 }
297 fn flight_mode(&self) -> &'static str {
298 if self.outcome != Outcome::Flying {
299 "FLIGHT ENDED"
300 } else if self.slowing {
301 "SLOW FLIGHT"
302 } else if self.boosting {
303 "BOOSTING"
304 } else if self.boost_exhausted {
305 "RECHARGING"
306 } else {
307 "CRUISE"
308 }
309 }
310 fn countdown(&self) -> u32 {
311 self.remaining.ceil() as u32
313 }
314}
315
316struct Navigation {
317 bearing: f32,
318 altitude: f32,
319 distance: f32,
320}
321impl Navigation {
322 fn turn(&self) -> &'static str {
323 if self.bearing.abs() < 0.12 {
324 "ON COURSE"
325 } else if self.bearing < 0. {
326 "TURN LEFT"
327 } else {
328 "TURN RIGHT"
329 }
330 }
331 fn climb(&self) -> &'static str {
332 if self.altitude.abs() < 3. {
333 "HOLD ALTITUDE"
334 } else if self.altitude > 0. {
335 "CLIMB"
336 } else {
337 "DESCEND"
338 }
339 }
340}
341
342#[derive(Default)]
343struct FlightFrame {
344 seconds: f32,
345 gates: usize,
346 damaged: bool,
347 outcome: Option<Outcome>,
348 bonus: u8,
350}
351
352struct FlightRun {
354 session: GameSession,
355 flight: Flight,
356 release_controls: bool,
357 elapsed: f64,
358}
359impl FlightRun {
360 fn new(autoplay: bool) -> Self {
361 Self {
362 session: GameSession::new(120., 12, autoplay),
363 flight: Flight::new(),
364 release_controls: !autoplay,
365 elapsed: 0.,
366 }
367 }
368 fn restart(&mut self) {
369 self.flight = Flight::new();
370 self.session.restart();
371 self.release_controls = true;
372 self.elapsed = 0.;
373 }
374 fn advance(&mut self, elapsed: f64, mut input: Input, autoplay: bool) -> FlightFrame {
375 let mut frame = FlightFrame::default();
376 if !self.session.is_playing() {
377 self.session.advance(elapsed);
378 return frame;
379 }
380 if self.release_controls && !autoplay {
381 self.release_controls = !input.neutral();
382 input = Input::default();
383 }
384 let steps = self.session.advance(elapsed);
385 for _ in 0..steps.steps {
386 let next = self.flight.next;
387 let hull = self.flight.hull;
388 let bonus = self.flight.ledger.bonus;
389 self.flight.tick(
390 if autoplay {
391 self.flight.autopilot()
392 } else {
393 input
394 },
395 steps.dt,
396 );
397 frame.seconds += steps.dt;
398 self.elapsed += f64::from(steps.dt);
399 frame.gates += self.flight.next - next;
400 frame.damaged |= self.flight.hull < hull;
401 frame.bonus |= self.flight.ledger.bonus & !bonus;
402 if self.flight.outcome != Outcome::Flying {
403 self.session
404 .finish(self.flight.outcome == Outcome::Delivered);
405 frame.outcome = Some(self.flight.outcome);
406 break;
407 }
408 }
409 frame
410 }
411}
412fn segment_hits(a: Vec3, b: Vec3, center: Vec3, radius: f32) -> bool {
413 let delta = b - a;
414 let t = if delta.length_squared() > 0. {
415 ((center - a).dot(delta) / delta.length_squared()).clamp(0., 1.)
416 } else {
417 0.
418 };
419 (a + delta * t).distance_squared(center) <= radius * radius
420}
421fn island_hit(pos: Vec3) -> bool {
422 ISLANDS.iter().any(|(center, radius)| {
423 let horizontal = vec2(pos.x - center.x, pos.z - center.z).length();
424 horizontal < radius * 0.85 + 1. && pos.y < center.y + 2. && pos.y > center.y - 27.
425 })
426}
427
428struct Scene {
429 ocean: Mesh3d,
430 islands: Vec<(Mesh3d, Mesh3d)>,
431 house: Mesh3d,
432 roof: Mesh3d,
433 trunk: Mesh3d,
434 leaves: Mesh3d,
435 body: Mesh3d,
436 nose: Mesh3d,
437 wing: Mesh3d,
438 tail: Mesh3d,
439 fin: Mesh3d,
440 glass: Mesh3d,
441 float: Mesh3d,
442 strut: Mesh3d,
443 propeller: Mesh3d,
444 ring: Mesh3d,
445 hot_ring: Mesh3d,
446 dim_ring: Mesh3d,
447 bonus_ring: Mesh3d,
448 pad: Mesh3d,
449 stripe: Mesh3d,
450 cloud: Mesh3d,
451 puff: Mesh3d,
452 parcel: Mesh3d,
453 gull_body: Mesh3d,
454 gull_wing: Mesh3d,
455}
456#[derive(Clone, Copy, Default)]
458struct SceneTime {
459 propeller: f32,
461 clock: f32,
463 roll: f32,
465 aircraft: bool,
467 ambient: f32,
469 bob: f32,
471}
472impl Scene {
473 fn new() -> Self {
474 Self {
475 ocean: Mesh3d::plane(vec2(1200., 1400.), Color::from_rgba(50, 108, 128, 255), 28),
476 islands: ISLANDS
477 .iter()
478 .map(|(_, r)| {
479 (
480 Mesh3d::frustum(r * 0.35, *r, 24., Color::from_rgba(122, 106, 98, 255), 7),
481 Mesh3d::frustum(*r, r * 0.85, 3., Color::from_rgba(160, 168, 102, 255), 7),
482 )
483 })
484 .collect(),
485 house: Mesh3d::cuboid(vec3(6., 5., 5.), Color::from_rgba(242, 228, 200, 255)),
486 roof: Mesh3d::cone(5., 3.4, CORAL, 4),
487 trunk: Mesh3d::cylinder(0.55, 4., Color::from_rgba(104, 89, 65, 255), 5),
488 leaves: Mesh3d::cone(3.6, 8., Color::from_rgba(50, 92, 76, 255), 6),
489 body: Mesh3d::cuboid(vec3(1.9, 1.6, 5.5), CREAM),
490 nose: Mesh3d::cylinder(1., 1.8, CORAL, 7),
491 wing: Mesh3d::cuboid(vec3(11.5, 0.23, 1.9), CORAL),
492 tail: Mesh3d::cuboid(vec3(4.5, 0.2, 1.3), CREAM),
493 fin: Mesh3d::cuboid(vec3(0.2, 1.8, 1.5), CORAL),
494 glass: Mesh3d::cuboid(vec3(1.6, 0.85, 1.8), Color::from_rgba(61, 89, 94, 255)),
495 float: Mesh3d::cuboid(vec3(0.65, 0.6, 4.2), Color::from_rgba(76, 85, 81, 255)),
496 strut: Mesh3d::cuboid(vec3(0.12, 1.6, 0.12), INK),
497 propeller: Mesh3d::cuboid(vec3(0.15, 3.3, 0.12), INK),
498 ring: Mesh3d::cuboid(vec3(3.6, 0.45, 0.5), Color::from_rgba(236, 178, 86, 255)),
499 hot_ring: Mesh3d::cuboid(vec3(3.7, 0.6, 0.65), Color::from_rgba(255, 236, 150, 255)),
500 dim_ring: Mesh3d::cuboid(vec3(3.6, 0.4, 0.4), Color::from_rgba(121, 163, 157, 255)),
501 bonus_ring: Mesh3d::cuboid(vec3(2.5, 0.5, 0.5), Color::from_rgba(255, 226, 120, 255)),
502 pad: Mesh3d::cylinder(11., 0.25, Color::from_rgba(228, 206, 146, 255), 16),
503 stripe: Mesh3d::cuboid(vec3(1.2, 0.12, 9.), CORAL),
504 cloud: Mesh3d::sphere(10., Color::from_rgba(255, 238, 224, 255), 12, 7),
505 puff: Mesh3d::sphere(6.5, Color::from_rgba(255, 244, 232, 255), 10, 6),
506 parcel: Mesh3d::cuboid(vec3(1.4, 1.2, 1.1), Color::from_rgba(165, 121, 71, 255)),
507 gull_body: Mesh3d::cuboid(vec3(0.35, 0.3, 1.1), Color::from_rgba(246, 242, 234, 255)),
508 gull_wing: Mesh3d::cuboid(vec3(1.5, 0.08, 0.5), Color::from_rgba(236, 232, 224, 255)),
509 }
510 }
511 fn draw(&self, game: &Flight, t: SceneTime) {
512 let SceneTime {
513 propeller: time,
514 clock,
515 roll,
516 aircraft,
517 ambient,
518 bob,
519 } = t;
520 self.ocean.draw(vec3(0., -20., 350.), Quat::IDENTITY);
521 for (i, (center, radius)) in ISLANDS.iter().enumerate() {
522 let (rock, grass) = &self.islands[i];
523 rock.draw(*center - Vec3::Y * 13.5, Quat::IDENTITY);
524 grass.draw(*center, Quat::IDENTITY);
525 for j in 0..5 {
526 let a = j as f32 * 1.23 + i as f32;
527 let p = *center + vec3(a.cos() * radius * 0.57, 3.4, a.sin() * radius * 0.57);
528 self.trunk.draw(p, Quat::IDENTITY);
529 self.leaves.draw(p + Vec3::Y * 4.5, Quat::IDENTITY);
530 }
531 let p = *center + vec3(radius * 0.3, 4., -radius * 0.15);
532 self.house.draw(p, Quat::IDENTITY);
533 self.roof.draw(
534 p + Vec3::Y * 4.1,
535 Quat::from_rotation_y(std::f32::consts::FRAC_PI_4),
536 );
537 }
538 let hot = game.ledger.multiplier() >= 3;
540 for (i, gate) in ROUTE.iter().enumerate().take(5) {
541 if i < game.next {
542 continue;
543 }
544 let current = i == game.next;
545 let mesh = match (current, hot) {
546 (true, true) => &self.hot_ring,
547 (true, false) => &self.ring,
548 _ => &self.dim_ring,
549 };
550 let radius = if current {
551 9. * (1. + 0.05 * (clock * 4.).sin())
552 } else {
553 9.
554 };
555 for segment in 0..16 {
556 let angle = segment as f32 * std::f32::consts::TAU / 16.;
557 let position = *gate + vec3(angle.cos() * radius, angle.sin() * radius, 0.);
558 mesh.draw(
559 position,
560 Quat::from_rotation_z(angle + std::f32::consts::FRAC_PI_2),
561 );
562 }
563 }
564 for (i, ring) in BONUS_RINGS.iter().enumerate() {
566 if game.ledger.bonus & (1 << i) != 0 {
567 continue;
568 }
569 let spin = Quat::from_rotation_y(clock * 0.9 + i as f32);
570 for segment in 0..12 {
571 let angle = segment as f32 * std::f32::consts::TAU / 12.;
572 let offset = spin * vec3(angle.cos() * 5.5, angle.sin() * 5.5, 0.);
573 self.bonus_ring.draw(
574 *ring + offset,
575 spin * Quat::from_rotation_z(angle + std::f32::consts::FRAC_PI_2),
576 );
577 }
578 }
579 self.pad.draw(vec3(0., 9.7, 680.), Quat::IDENTITY);
580 self.stripe.draw(vec3(0., 9.9, 680.), Quat::IDENTITY);
581 self.stripe.draw(
582 vec3(0., 9.9, 680.),
583 Quat::from_rotation_y(std::f32::consts::FRAC_PI_2),
584 );
585 for i in 0..13 {
587 let drift = (ambient * 0.06 + i as f32).sin() * 3.;
588 let x = ((i * 79) % 330) as f32 - 165. + drift;
589 let z = i as f32 * 67. - 50.;
590 let y = 79. + (i % 3) as f32 * 10.;
591 self.cloud.draw(vec3(x, y, z), Quat::IDENTITY);
592 self.puff
593 .draw(vec3(x + 11., y - 3., z + 3.), Quat::IDENTITY);
594 self.puff.draw(vec3(x - 9., y - 4., z - 2.), Quat::IDENTITY);
595 }
596 for index in 0..6 {
597 let (pos, heading, flap) = look::gull(index, ambient);
598 let body = Quat::from_rotation_y(heading);
599 self.gull_body.draw(pos, body);
600 for side in [-1., 1.] {
601 let wing = body * Quat::from_rotation_z(side * flap);
602 self.gull_wing
603 .draw(pos + wing * vec3(side * 0.8, 0.05, 0.), wing);
604 }
605 }
606 if !aircraft {
607 return;
608 }
609 let game_pos = game.pos + Vec3::Y * bob;
610 let rotation = Quat::from_rotation_y(game.motor.yaw)
611 * Quat::from_rotation_x(-game.motor.pitch)
612 * Quat::from_rotation_z(game.motor.bank + roll);
613 let draw = |mesh: &Mesh3d, offset: Vec3| mesh.draw(game_pos + rotation * offset, rotation);
614 draw(&self.body, Vec3::ZERO);
615 self.nose.draw(
616 game_pos + rotation * vec3(0., 0., 3.2),
617 rotation * Quat::from_rotation_x(std::f32::consts::FRAC_PI_2),
618 );
619 draw(&self.wing, vec3(0., 0.2, 0.6));
620 draw(&self.tail, vec3(0., 0.3, -3.));
621 draw(&self.fin, vec3(0., 1., -2.8));
622 draw(&self.glass, vec3(0., 1., 0.5));
623 draw(&self.parcel, vec3(0., -1.2, -0.8));
624 for x in [-1.5, 1.5] {
625 draw(&self.float, vec3(x, -2., 0.));
626 draw(&self.strut, vec3(x, -1.1, 0.7));
627 draw(&self.strut, vec3(x, -1.1, -1.3));
628 }
629 self.propeller.draw(
630 game_pos + rotation * vec3(0., 0., 4.2),
631 rotation * Quat::from_rotation_z(time * 42.),
632 );
633 }
634}
635
636fn ui_rect(x: f32, y: f32, w: f32, h: f32) -> UiRect {
637 UiRect {
638 min: [x, y],
639 size: [w, h],
640 }
641}
642fn control_hint<'a>(player: &PlayerInput, action: &str, buffer: &'a mut [u8]) -> &'a str {
643 if player.current_device() == HintDevice::Touch && !player.touch_customized() {
644 return match action {
646 "move_x" | "move_y" => "Left stick",
647 "brake" => "Right side",
648 "confirm" => "Tap button",
649 _ => "Open Controls",
650 };
651 }
652 match player.format_hint(action, buffer) {
653 Ok(label) if label.len() <= 32 => label,
654 _ => "Open Controls",
657 }
658}
659#[cfg(test)]
660fn movement_hint<'a>(
661 player: &PlayerInput,
662 actions: [&str; 3],
663 buffers: &'a mut [[u8; 96]; 3],
664) -> (&'a str, &'a str) {
665 let [axis, negative, positive] = buffers;
666 let axis = control_hint(player, actions[0], axis);
667 if axis != "Unbound" {
668 return (axis, "");
669 }
670 let negative = control_hint(player, actions[1], negative);
671 let positive = control_hint(player, actions[2], positive);
672 if negative.len() + positive.len() > 32 {
673 ("Open Controls", "")
674 } else {
675 (negative, positive)
676 }
677}
678fn conf() -> Conf {
679 #[allow(unused_mut)]
680 let mut conf = ferravex_render::window_conf("Sky Courier — Ferravex");
681 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
682 capture::window(&mut conf);
683 conf
684}
685
686const RECORD_RULES: u64 = 0x534b_5943_0001;
688const RECORD_ID: &str = "north-coast-mail";
689
690fn best_tips(records: Option<&ferravex_render::storage::Records>) -> Option<u32> {
693 records?
694 .get(RECORD_ID, RECORD_RULES)
695 .filter(|record| record.fastest_us.is_some())
696 .map(|record| record.score.min(u64::from(u32::MAX)) as u32)
697}
698
699ferravex_render::game!(conf, game);
700async fn game() {
701 let mut demo = Demo::new();
702 let mut sound = GameAudio::new();
703 let mut presentation = FlightPresentation::new();
704 let mut exhaust_renderer = ParticleRenderer::new(128).unwrap();
705 let mut spark_renderer = ParticleRenderer::new(256).unwrap();
706 let mut run = FlightRun::new(demo.autoplay);
707 let mut ui = Ui::new();
708 let mut menu_button = ButtonMotion::default();
709 let mut activate = false;
710 let mut menu_ready = true;
711 let scene = Scene::new();
712 let mut grade = look::Grade::default();
713 let material = LitMaterial::new().expect("portable flight material");
714 let mut player_input = PlayerInput::preset("sky-courier", Preset::Flight);
715 let mut reported = false;
716 let mut records = ferravex_render::storage::Records::new("sky-courier").ok();
718 let mut results = Results::default();
719 let mut coach = Coach::default();
720 let mut pauses = 0_u32;
721 let mut shifts = 0_u32;
722 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
723 let mut capture = capture::Capture::from_env();
724 loop {
725 let w = screen_width();
726 let h = screen_height();
727 player_input
729 .set_touch_layout(&[
730 Control {
731 region: Region::Circle {
732 center: vec2(90., h - 100.),
733 radius: 85.,
734 },
735 output: Output::Stick {
736 x: 0,
737 y: 1,
738 radius: 60.,
739 floating: false,
740 },
741 },
742 Control {
743 region: Region::Rect(Rect::new(w * 0.55, 0., w * 0.45, h)),
744 output: Output::Button(6),
745 },
746 ])
747 .unwrap();
748 player_input.sample_play();
749 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
750 if capture.pause_now(&run) {
751 player_input.set_paused(true);
752 }
753 let activated = std::mem::take(&mut activate);
754 let restart = player_input.pressed("restart")
755 || (activated && matches!(run.session.state(), SessionState::Won | SessionState::Lost));
756 let mut transitioned = false;
757 if restart && !player_input.controls_open() {
758 run.restart();
759 player_input.set_paused(false);
760 player_input.sample(true);
761 presentation.reset(run.flight.pos);
762 sound.reset();
763 reported = false;
764 ui.cancel();
765 transitioned = true;
766 } else if activated && !player_input.controls_open() {
767 player_input.set_paused(false);
768 player_input.sample(true);
769 transitioned = run.session.start() || run.session.set_paused(false);
770 }
771 let was_paused = run.session.is_paused();
773 transitioned |= run.session.set_paused(
774 player_input.paused() || (!demo.autoplay && !player_input.gameplay_active()),
775 );
776 if run.session.is_paused() && !was_paused {
777 pauses = pauses.wrapping_add(1);
778 }
779 let movement = player_input.movement();
780 #[allow(unused_mut)]
781 let mut human = Input {
782 turn: movement.x,
783 climb: movement.y,
784 boost: player_input.held("boost"),
785 slow: player_input.held("brake"),
786 };
787 #[allow(unused_mut)]
788 let mut autoplay = demo.autoplay;
789 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
790 if demo.autoplay
791 && let Some(input) = capture.input(&run.flight)
792 {
793 human = input;
794 autoplay = false;
795 }
796 let frame = run.advance(
797 if transitioned { 0. } else { demo.dt() as f64 },
798 human,
799 autoplay,
800 );
801 coach.update(&run.flight, frame.seconds);
802 if let Some(outcome) = frame.outcome {
803 shifts = shifts.wrapping_add(1);
805 let delivered = outcome == Outcome::Delivered;
806 results = Results {
807 previous_best: best_tips(records.as_ref()),
808 shift: shifts,
809 demo: demo.autoplay,
810 };
811 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
812 if let Some(best) = capture.fake_best() {
813 results.previous_best = Some(best);
814 results.demo = false;
815 }
816 if !demo.autoplay
817 && let Some(records) = records.as_mut()
818 {
819 let tips = if delivered { run.flight.ledger.tips } else { 0 };
820 let time = if delivered {
821 ferravex_render::storage::run_micros(run.elapsed as f32)
822 } else {
823 None
824 };
825 let _ = records.attempt(RECORD_ID, RECORD_RULES, u64::from(tips), time);
826 if let Some(record) = records.get(RECORD_ID, RECORD_RULES) {
827 results.shift = record.runs.min(u64::from(u32::MAX)) as u32;
828 }
829 }
830 }
831 let flight = &run.flight;
832 let (view, feedback) = presentation.update(&run, &frame, demo.dt(), |cue, gain| {
833 sound.cue(cue, gain);
834 });
835 sound.motor(flight.motor.speed, 38., run.session.is_playing());
836 let camera_pos = view.position;
837 grade.apply(run.session.state());
838 clear_background(look::ZENITH);
839 let camera = Camera3D {
840 position: camera_pos,
841 target: view.target,
842 up: view.up,
843 fovy: view.fov_y,
844 z_near: 0.2,
845 z_far: 650.,
846 ..Default::default()
847 };
848 let projector = overlay::Projector::new(&camera, w, h);
849 look::sky(&projector, camera_pos, view.target, w, h);
850 set_camera(&camera);
851 material.begin(LitSettings {
852 camera_position: camera_pos,
853 fog_color: look::HORIZON,
854 fog_start: 160.,
855 fog_end: 500.,
856 ambient: 0.65,
857 ..Default::default()
858 });
859 scene.draw(
860 flight,
861 SceneTime {
862 propeller: presentation.propeller_time,
863 clock: presentation.clock,
864 roll: presentation.roll_angle(),
865 aircraft: presentation.aircraft_visible(flight),
866 ambient: presentation.ambient,
867 bob: presentation.bob(run.session.state()),
868 },
869 );
870 material.end();
871 for trail in &presentation.wing_trails {
872 draw_ribbon(
873 trail,
874 RibbonFacing::Camera {
875 eye: camera_pos.to_array(),
876 up: view.up.to_array(),
877 },
878 2.,
879 EffectStyle::default(),
880 )
881 .unwrap();
882 }
883 let billboard = BillboardView::new(
884 camera_pos,
885 (view.target - camera_pos).cross(view.up),
886 view.up,
887 )
888 .unwrap();
889 exhaust_renderer
890 .draw_3d(&presentation.exhaust, billboard, ParticleStyle::default())
891 .unwrap();
892 spark_renderer
893 .draw_3d(&presentation.sparks, billboard, ParticleStyle::default())
894 .unwrap();
895 set_default_camera();
896 look::glows(
897 &projector,
898 flight,
899 camera_pos,
900 view.target,
901 presentation.clock,
902 !preferences::feedback_policy().reduced_flash(),
903 );
904 post_fx_hud_begin();
905 if run.session.is_playing() {
906 overlay::speed_lines(&presentation, w, h);
907 }
908 overlay::gate_glow(&presentation, w, h);
909 if feedback.flash > 0. && run.session.is_playing() {
910 draw_rectangle_lines(
912 2.,
913 2.,
914 (w - 4.).max(0.),
915 (h - 4.).max(0.),
916 4.,
917 Color::new(CORAL.r, CORAL.g, CORAL.b, feedback.flash * 0.55),
918 );
919 }
920 if run.session.is_playing() {
921 overlay::waypoint(&projector, flight, w, h);
922 }
923 overlay::pops(&projector, &presentation);
924 if player_input.touch_seen() && !player_input.touch_customized() && run.session.is_playing()
925 {
926 draw_circle_lines(90., h - 100., 60., 2., CREAM);
927 draw_circle(90., h - 100., 4., CREAM);
928 }
929 if demo.autoplay && flight.outcome != Outcome::Flying && !reported {
930 println!(
931 "Sky Courier autoplay: {:?}; beacons={}; hull={}; remaining={:.1}s; tips=${}; streak={}; rings={}/3",
932 flight.outcome,
933 flight.next,
934 flight.hull,
935 flight.remaining,
936 flight.ledger.tips,
937 flight.ledger.best_streak,
938 flight.ledger.bonus_count()
939 );
940 reported = true;
941 }
942 if transitioned || frame.outcome.is_some() {
944 menu_ready = false;
945 } else if !player_input.held("confirm") && !player_input.held("restart") {
946 menu_ready = true;
947 }
948 let hud_view = HudView {
949 progress: Progress {
950 best_tips: best_tips(records.as_ref()),
951 },
952 results: &results,
953 coach: &coach,
954 pauses,
955 fx: presentation.hud_fx(),
956 };
957 activate = hud(
958 &run,
959 &mut ui,
960 &mut player_input,
961 menu_ready,
962 &hud_view,
963 &mut menu_button,
964 demo.dt(),
965 )
966 .expect("bounded courier HUD");
967 player_input.draw_controls();
968 #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
969 capture.end_frame();
970 if demo.finish_frame() {
971 break;
972 }
973 next_frame().await;
974 }
975}
976
977#[cfg(test)]
978mod journey200_tests;
979
980#[cfg(test)]
981mod tests {
982 use super::*;
983
984 #[test]
985 fn control_hints_follow_remaps_unbinding_and_bounded_fallbacks() {
986 use ferravex_render::input::{Binding, InputCode};
987 let mut player = PlayerInput::preset("sky-courier-hint-test", Preset::Flight);
988 let mut buffer = [0; 96];
989 assert_eq!(control_hint(&player, "boost", &mut buffer), "Space");
990 player
991 .rebind(
992 "boost",
993 vec![Binding::digital(InputCode::Key(KeyCode::B as u16))],
994 )
995 .unwrap();
996 assert_eq!(control_hint(&player, "boost", &mut buffer), "B");
997 player.rebind("brake", vec![]).unwrap();
998 assert_eq!(control_hint(&player, "brake", &mut buffer), "Unbound");
999 player
1000 .rebind(
1001 "pause",
1002 vec![Binding::digital(InputCode::Key(KeyCode::P as u16))],
1003 )
1004 .unwrap();
1005 assert_eq!(control_hint(&player, "pause", &mut buffer), "P");
1006 player
1007 .rebind(
1008 "confirm",
1009 vec![Binding::digital(InputCode::Key(KeyCode::C as u16))],
1010 )
1011 .unwrap();
1012 assert_eq!(control_hint(&player, "confirm", &mut buffer), "C");
1013 player
1014 .rebind(
1015 "boost",
1016 vec![Binding::digital(InputCode::Key(KeyCode::B as u16)); 32],
1017 )
1018 .unwrap();
1019 assert_eq!(control_hint(&player, "boost", &mut buffer), "Open Controls");
1020 assert_eq!(
1021 control_hint(&player, "missing", &mut buffer),
1022 "Open Controls"
1023 );
1024 let mut buffers = [[0; 96]; 3];
1025 assert_eq!(
1026 movement_hint(&player, ["move_x", "move_left", "move_right"], &mut buffers),
1027 ("A / Left", "D / Right")
1028 );
1029 player
1030 .rebind(
1031 "move_x",
1032 vec![Binding::digital(InputCode::Key(KeyCode::J as u16))],
1033 )
1034 .unwrap();
1035 assert_eq!(
1036 movement_hint(&player, ["move_x", "move_left", "move_right"], &mut buffers),
1037 ("J", "")
1038 );
1039 player.rebind("move_x", vec![]).unwrap();
1040 assert_eq!(
1041 movement_hint(&player, ["move_x", "move_left", "move_right"], &mut buffers),
1042 ("A / Left", "D / Right")
1043 );
1044 }
1045
1046 #[test]
1047 fn flight_status_reports_accepted_boost_slow_and_exhaustion_without_advancing_on_render() {
1048 let mut run = FlightRun::new(true);
1049 let boost = Input {
1050 boost: true,
1051 ..Default::default()
1052 };
1053 assert_eq!(run.flight.flight_mode(), "CRUISE");
1054 run.advance(0., boost, false);
1055 assert_eq!(run.flight.flight_mode(), "CRUISE");
1056 run.advance(1. / 120., boost, false);
1057 assert_eq!(run.flight.flight_mode(), "BOOSTING");
1058 run.advance(
1059 1. / 120.,
1060 Input {
1061 slow: true,
1062 ..boost
1063 },
1064 false,
1065 );
1066 assert_eq!(run.flight.flight_mode(), "SLOW FLIGHT");
1067 run.flight.boost_energy = 0.;
1068 run.advance(1. / 120., boost, false);
1069 assert_eq!(run.flight.flight_mode(), "RECHARGING");
1070 let elapsed = run.elapsed;
1071 run.session.set_paused(true);
1072 run.advance(15., Input::default(), false);
1073 assert_eq!(run.elapsed, elapsed);
1074 run.restart();
1075 assert_eq!(run.elapsed, 0.);
1076 assert_eq!(run.flight.flight_mode(), "CRUISE");
1077 }
1078
1079 #[test]
1080 fn checkpoint_motor_reset_preserves_route_boost_and_penalty() {
1081 let mut game = Flight::new();
1082 game.pos = ROUTE[0];
1083 game.tick(Input::default(), 1. / 120.);
1084 assert_eq!(game.next, 1);
1085 game.motor.pitch = 0.4;
1086 game.motor.bank = 0.5;
1087 game.motor.turn_rate = 1.;
1088 game.motor.speed = 35.;
1089 game.boost_energy = 0.4;
1090 let before = game.remaining;
1091 game.damage();
1092 assert_eq!(game.pos, ROUTE[0]);
1093 assert_eq!(game.next, 1);
1094 assert_eq!(game.remaining, before - 5.);
1095 assert_eq!(game.boost_energy, 0.4);
1096 assert_eq!(
1097 (
1098 game.motor.pitch,
1099 game.motor.bank,
1100 game.motor.turn_rate,
1101 game.motor.speed
1102 ),
1103 (0., 0., 0., 24.)
1104 );
1105 assert!(game.navigation().unwrap().bearing.abs() < 0.001);
1106 let position = game.pos;
1107 game.damage();
1108 assert_eq!(game.pos, position);
1109 assert_eq!(game.hull, 2);
1110 }
1111
1112 #[test]
1113 fn ready_and_pause_freeze_flight_countdown_and_feedback_without_catch_up() {
1114 let mut run = FlightRun::new(false);
1115 let position = run.flight.pos;
1116 assert_eq!(run.session.state(), SessionState::Ready);
1117 assert_eq!(run.advance(30., Input::default(), false).seconds, 0.);
1118 assert_eq!(run.flight.pos, position);
1119 assert_eq!(run.flight.remaining, 90.);
1120 assert!(run.session.start());
1121 run.flight.recovery = 2.;
1122 run.flight.gate_notice = 1.;
1123 run.advance(1. / 120., Input::default(), false);
1124 let before = (
1125 run.flight.pos,
1126 run.flight.remaining,
1127 run.flight.recovery,
1128 run.flight.gate_notice,
1129 run.session.tick(),
1130 );
1131 assert!(run.session.set_paused(true));
1132 for _ in 0..10 {
1133 let frame = run.advance(
1134 10.,
1135 Input {
1136 boost: true,
1137 ..Default::default()
1138 },
1139 false,
1140 );
1141 assert_eq!(frame.seconds, 0.);
1142 assert_eq!(frame.gates, 0);
1143 assert!(!frame.damaged);
1144 assert_eq!(frame.outcome, None);
1145 }
1146 assert_eq!(
1147 (
1148 run.flight.pos,
1149 run.flight.remaining,
1150 run.flight.recovery,
1151 run.flight.gate_notice,
1152 run.session.tick()
1153 ),
1154 before
1155 );
1156 assert!(run.session.set_paused(false));
1157 let frame = run.advance(1. / 120., Input::default(), false);
1158 assert!((frame.seconds - 1. / 120.).abs() < 0.00001);
1159 assert_eq!(run.session.tick(), before.4 + 1);
1160 assert!(before.1 - run.flight.remaining < 0.01);
1161 }
1162
1163 #[test]
1164 fn retry_clears_clock_progress_and_holds_controls_until_released() {
1165 let mut run = FlightRun::new(true);
1166 run.advance(1. / 240., Input::default(), false);
1167 run.flight.next = 3;
1168 run.flight.hull = 1;
1169 run.flight.remaining = 7.;
1170 run.flight.recovery = 2.;
1171 run.flight.gate_notice = 1.;
1172 run.session.set_paused(true);
1173 run.restart();
1174 assert_eq!(run.session.state(), SessionState::Playing);
1175 assert_eq!(run.session.tick(), 0);
1176 assert_eq!(run.flight.next, 0);
1177 assert_eq!(run.flight.hull, 3);
1178 assert_eq!(run.flight.remaining, 90.);
1179 assert_eq!(run.flight.recovery, 0.);
1180 assert_eq!(run.flight.gate_notice, 0.);
1181 let stale = Input {
1182 turn: 1.,
1183 climb: 1.,
1184 boost: true,
1185 slow: false,
1186 };
1187 assert_eq!(run.advance(1. / 240., stale, false).seconds, 0.);
1188 for _ in 0..10 {
1189 run.advance(1. / 60., stale, false);
1190 }
1191 assert_eq!(run.flight.motor.yaw, 0.);
1192 assert_eq!(run.flight.motor.pitch, 0.);
1193 assert_eq!(run.flight.motor.speed, 24.);
1194 assert_eq!(run.flight.boost_energy, 1.);
1195 run.advance(1. / 60., Input::default(), false);
1196 run.advance(1. / 60., stale, false);
1197 assert!(run.flight.motor.yaw > 0. && run.flight.motor.pitch > 0.);
1198 assert!(run.flight.motor.speed > 24. && run.flight.boost_energy < 1.);
1199 run.restart();
1200 run.advance(
1201 0.1,
1202 Input {
1203 slow: true,
1204 ..Default::default()
1205 },
1206 false,
1207 );
1208 assert_eq!(run.flight.motor.speed, 24.);
1209 }
1210
1211 #[test]
1212 fn crash_penalty_can_close_delivery_window_on_the_same_tick() {
1213 let mut run = FlightRun::new(true);
1214 run.flight.remaining = 4.;
1215 run.flight.pos.y = -21.;
1216 let frame = run.advance(0.1, Input::default(), false);
1217 assert!(frame.damaged);
1218 assert_eq!(frame.outcome, Some(Outcome::Lost));
1219 assert_eq!(run.flight.hull, 2);
1220 assert_eq!(run.flight.remaining, 0.);
1221 assert_eq!(run.session.state(), SessionState::Lost);
1222 assert!((frame.seconds - 1. / 120.).abs() < 0.00001);
1223 let position = run.flight.pos;
1224 let frame = run.advance(30., Input::default(), false);
1225 assert_eq!(frame.seconds, 0.);
1226 assert_eq!(frame.outcome, None);
1227 assert_eq!(run.flight.pos, position);
1228 }
1229
1230 #[test]
1231 fn guidance_wraps_bearings_and_countdown_never_expires_early() {
1232 let mut game = Flight::new();
1233 assert_eq!(game.navigation().unwrap().turn(), "ON COURSE");
1234 assert_eq!(game.navigation().unwrap().climb(), "CLIMB");
1235 game.pos = ROUTE[0] + vec3(10., 10., -30.);
1236 assert_eq!(game.navigation().unwrap().turn(), "TURN LEFT");
1237 assert_eq!(game.navigation().unwrap().climb(), "DESCEND");
1238 game.motor.yaw = std::f32::consts::TAU;
1239 assert_eq!(game.navigation().unwrap().turn(), "TURN LEFT");
1240 game.pos = ROUTE[0] - Vec3::X * 20.;
1241 assert_eq!(game.navigation().unwrap().turn(), "TURN RIGHT");
1242 assert_eq!(game.navigation().unwrap().climb(), "HOLD ALTITUDE");
1243 assert!((game.navigation().unwrap().distance - 20.).abs() < 0.001);
1244 game.remaining = 0.001;
1245 assert_eq!(game.countdown(), 1);
1246 game.remaining = 60.01;
1247 assert_eq!(game.countdown(), 61);
1248 game.remaining = 0.;
1249 assert_eq!(game.countdown(), 0);
1250 game.next = ROUTE.len();
1251 assert!(game.navigation().is_none());
1252 }
1253
1254 #[test]
1255 fn session_autoplay_delivers_identically_at_regular_and_irregular_frame_rates() {
1256 fn deliver(pattern: &[f64]) -> FlightRun {
1257 let mut run = FlightRun::new(true);
1258 let mut gates = 0;
1259 let mut successes = 0;
1260 for frame in 0..30_000 {
1261 let events = run.advance(pattern[frame % pattern.len()], Input::default(), true);
1262 gates += events.gates;
1263 successes += usize::from(events.outcome == Some(Outcome::Delivered));
1264 if !run.session.is_playing() {
1265 break;
1266 }
1267 }
1268 assert_eq!(run.session.state(), SessionState::Won);
1269 assert_eq!(run.flight.hull, 3);
1270 assert_eq!(gates, 6);
1271 assert_eq!(successes, 1);
1272 assert_eq!(run.advance(5., Input::default(), true).outcome, None);
1273 run
1274 }
1275 let baseline = deliver(&[1. / 60.]);
1276 for pattern in [
1277 &[1. / 30.][..],
1278 &[1. / 144.][..],
1279 &[0., 1. / 240., 0.08, 1. / 60.][..],
1280 ] {
1281 let run = deliver(pattern);
1282 assert_eq!(run.flight.pos, baseline.flight.pos);
1283 assert_eq!(run.flight.remaining, baseline.flight.remaining);
1284 assert_eq!(run.flight.motor.speed, baseline.flight.motor.speed);
1285 }
1286 }
1287
1288 #[test]
1289 fn boost_is_a_recoverable_resource_and_slow_overrides_it() {
1290 let mut game = Flight::new();
1291 for _ in 0..600 {
1292 game.tick(
1293 Input {
1294 boost: true,
1295 ..Default::default()
1296 },
1297 1. / 120.,
1298 );
1299 }
1300 assert_eq!(game.outcome, Outcome::Flying);
1301 assert!(game.boost_energy < 0.3 && game.motor.speed < 34.);
1302 let energy = game.boost_energy;
1303 for _ in 0..360 {
1304 game.tick(
1305 Input {
1306 boost: true,
1307 slow: true,
1308 ..Default::default()
1309 },
1310 1. / 120.,
1311 );
1312 }
1313 assert!(game.boost_energy > energy + 0.3);
1314 assert!(game.motor.speed < 14.);
1315 }
1316
1317 #[test]
1318 fn ordinary_flight_inputs_complete_the_route_and_delivery() {
1319 let mut game = Flight::new();
1320 for _ in 0..120 * 85 {
1321 game.tick(game.autopilot(), 1. / 120.);
1322 }
1323 assert_eq!(game.outcome, Outcome::Delivered);
1324 assert_eq!(game.next, 6);
1325 assert_eq!(game.hull, 3);
1326 assert!(game.remaining > 0.);
1327 }
1328 #[test]
1329 fn beacons_must_be_visited_in_order() {
1330 let mut game = Flight::new();
1331 game.pos = ROUTE[3];
1332 game.tick(Input::default(), 1. / 120.);
1333 assert_eq!(game.next, 0);
1334 game.pos = ROUTE[0];
1335 game.tick(Input::default(), 1. / 120.);
1336 assert_eq!(game.next, 1);
1337 }
1338 #[test]
1339 fn damage_recovers_and_three_crashes_end_the_flight() {
1340 let mut game = Flight::new();
1341 for hull in [2, 1, 0] {
1342 game.recovery = 0.;
1343 game.pos.y = -21.;
1344 game.tick(Input::default(), 1. / 120.);
1345 assert_eq!(game.hull, hull);
1346 if hull > 0 {
1347 assert_eq!(game.pos, vec3(0., 20., 0.));
1348 }
1349 }
1350 assert_eq!(game.outcome, Outcome::Lost);
1351 assert!(island_hit(ISLANDS[0].0));
1352 assert!(!island_hit(ISLANDS[0].0 + Vec3::Y * 30.));
1353 }
1354 #[test]
1355 fn timeout_freezes_and_restart_restores_game() {
1356 let mut game = Flight::new();
1357 game.remaining = 0.001;
1358 game.tick(Input::default(), 0.02);
1359 assert_eq!(game.outcome, Outcome::Lost);
1360 let pos = game.pos;
1361 game.tick(Input::default(), 1.);
1362 assert_eq!(game.pos, pos);
1363 game = Flight::new();
1364 assert_eq!(game.next, 0);
1365 assert_eq!(game.hull, 3);
1366 assert_eq!(game.outcome, Outcome::Flying);
1367 }
1368 #[test]
1369 fn cargo_requires_a_slow_pass_and_swept_capture_handles_fast_motion() {
1370 let mut game = Flight::new();
1371 game.next = 5;
1372 game.pos = ROUTE[5];
1373 game.motor.speed = 30.;
1374 game.tick(Input::default(), 1. / 120.);
1375 assert_eq!(game.next, 5);
1376 game.motor.speed = 13.;
1377 game.tick(
1378 Input {
1379 slow: true,
1380 ..Input::default()
1381 },
1382 1. / 120.,
1383 );
1384 assert_eq!(game.outcome, Outcome::Delivered);
1385 assert!(segment_hits(Vec3::ZERO, Vec3::Z * 20., Vec3::Z * 10., 1.));
1386 }
1387}
1388
1389#[cfg(test)]
1390mod courier_tests {
1391 use super::*;
1392
1393 fn fly(pattern: &[f64], tour: bool) -> (FlightRun, u8, usize) {
1394 let mut run = FlightRun::new(true);
1395 let mut bonus = 0;
1396 let mut bonus_events = 0;
1397 for frame in 0..30_000 {
1398 let input = if tour {
1399 run.flight.scenic_tour()
1400 } else {
1401 run.flight.autopilot()
1402 };
1403 let events = run.advance(pattern[frame % pattern.len()], input, false);
1406 assert_eq!(bonus & events.bonus, 0, "a hidden ring is reported once");
1407 bonus |= events.bonus;
1408 bonus_events += events.bonus.count_ones() as usize;
1409 if !run.session.is_playing() {
1410 break;
1411 }
1412 }
1413 (run, bonus, bonus_events)
1414 }
1415
1416 #[test]
1417 fn hidden_rings_are_off_route_safe_and_reachable_with_ordinary_inputs() {
1418 for ring in BONUS_RINGS {
1419 assert!(!island_hit(ring), "{ring:?} is clear of terrain");
1420 assert!(ring.y - BONUS_RADIUS > -17. && ring.y + BONUS_RADIUS < 110.);
1421 for gate in ROUTE {
1422 assert!(ring.distance(gate) > 40., "hidden rings stay off-route");
1423 }
1424 }
1425 let (route, bonus, _) = fly(&[1. / 120.], false);
1426 assert_eq!(route.session.state(), SessionState::Won);
1427 assert_eq!(
1428 (bonus, route.flight.ledger.bonus),
1429 (0, 0),
1430 "autopilot never stumbles on them"
1431 );
1432 let (tour, bonus, events) = fly(&[1. / 120.], true);
1433 assert_eq!(tour.session.state(), SessionState::Won);
1434 assert_eq!(tour.flight.hull, 3);
1435 assert_eq!((bonus, events), (0b111, 3));
1436 assert!(tour.flight.ledger.scenic());
1437 assert!(tour.flight.ledger.tips > route.flight.ledger.tips + 150);
1438 assert_eq!(
1439 quips::rank(&tour.flight.ledger, true, 3, GATES).0,
1440 "Scenic Route Specialist"
1441 );
1442 }
1443
1444 #[test]
1445 fn autopilot_ledger_is_a_clean_deterministic_streak() {
1446 let (run, _, _) = fly(&[1. / 120.], false);
1447 let ledger = &run.flight.ledger;
1448 assert_eq!(ledger.best_streak, GATES as u32);
1449 assert_eq!(ledger.impacts, 0);
1450 assert!(ledger.gates.iter().all(Option::is_some));
1451 let drop = ledger.drop.expect("graded delivery");
1452 assert_eq!(drop.multiplier, courier::MAX_MULTIPLIER);
1453 let gates: u32 = ledger.gates.iter().flatten().map(|g| g.tip).sum();
1454 assert_eq!(ledger.tips, gates + drop.tip + drop.early);
1455 for pattern in [
1457 &[1. / 30.][..],
1458 &[1. / 144.],
1459 &[0., 1. / 240., 0.08, 1. / 60.],
1460 ] {
1461 let (other, _, _) = fly(pattern, false);
1462 assert_eq!(other.flight.ledger, run.flight.ledger);
1463 }
1464 }
1465
1466 #[test]
1467 fn impacts_break_the_streak_and_record_their_cause() {
1468 let mut game = Flight::new();
1469 game.pos = ROUTE[0];
1470 game.tick(Input::default(), 1. / 120.);
1471 assert_eq!((game.ledger.streak, game.ledger.multiplier()), (1, 2));
1472 game.pos = ISLANDS[1].0;
1473 game.tick(Input::default(), 1. / 120.);
1474 assert_eq!(game.hull, 2);
1475 assert_eq!(game.ledger.last_impact, Impact::Island);
1476 assert_eq!((game.ledger.streak, game.ledger.impacts), (0, 1));
1477 game.recovery = 0.;
1478 game.pos = vec3(0., 115., 300.);
1479 game.tick(Input::default(), 1. / 120.);
1480 assert_eq!(game.ledger.last_impact, Impact::Boundary);
1481 assert_eq!(game.ledger.best_streak, 1);
1482 game.pos = vec3(0., -30., 300.);
1484 game.tick(Input::default(), 1. / 120.);
1485 assert_eq!(game.ledger.impacts, 2);
1486 }
1487}