kart: make boost effective on straights and add engine Rust tests
- Commit
ceb5a967ffd0f806d2ebf8512fc770316b7cfe23- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 21:26 UTC (18 days ago)
- Parents
0b35d18
71 new tests (29 -> 100, now 103 with fix tests): track geometry, physics, items/AI, race, mesh, engine. Fix: boost only raised the top-speed cap while the accel/drag equilibrium stayed at the unboosted cap, so a mushroom at full speed on a straight gained nothing even though the AI fires them there; thrust is now scaled by BOOST_MULT while boost is active, lifting the equilibrium to the boosted cap without changing unboosted balance. Also corrected two doc mismatches proven from callers (lateral is positive-left along the track normal; AiDriver wobble is 0.90..=0.98). cargo test -p kart_engine green.
Diff
games/kart/src/main/rust/src/engine.rs
diff --git a/games/kart/src/main/rust/src/engine.rs b/games/kart/src/main/rust/src/engine.rsindex 10783ed823..b011139553 100644--- a/games/kart/src/main/rust/src/engine.rs+++ b/games/kart/src/main/rust/src/engine.rs@@ -456,6 +456,8 @@ pub fn has_renderer() -> bool { with_engine(|s| s.renderer.is_some()).unwrap_or(false) } +#[cfg(test)]+mod engine_tests; #[cfg(test)] mod tests { use super::*;
games/kart/src/main/rust/src/engine/engine_tests.rs
diff --git a/games/kart/src/main/rust/src/engine/engine_tests.rs b/games/kart/src/main/rust/src/engine/engine_tests.rsnew file mode 100644index 0000000000..27acbe4432--- /dev/null+++ b/games/kart/src/main/rust/src/engine/engine_tests.rs@@ -0,0 +1,90 @@+//! Extra deterministic tests for pure engine helpers (sibling of+//! `engine::tests`). Avoids the global ENGINE lock except via constructed+//! `EngineState` values, so tests stay parallel-safe.+use super::*;+use crate::physics::DriveInput;+use std::time::Instant;++fn state_with_pending(n: usize) -> EngineState {+ EngineState {+ race: None,+ renderer: None,+ track_count: 0,+ pending: (0..n).map(|_| DriveInput::default()).collect(),+ window_ptr: None,+ width: 0,+ height: 0,+ last_tick: Instant::now(),+ accumulator: 0.0,+ running: false,+ }+}++#[test]+fn escape_only_escapes_backslash_and_quote() {+ assert_eq!(escape("plain p1"), "plain p1");+ assert_eq!(escape(""), "");+ assert_eq!(escape("a\"b"), "a\\\"b");+ assert_eq!(escape("a\\b"), "a\\\\b");+ // Backslash first: an existing \" becomes \\\" (not a double escape of+ // the quote alone).+ assert_eq!(escape("\\\""), "\\\\\\\"");+ assert_eq!(escape("a\nb\tc"), "a\nb\tc", "other controls pass through");+}++#[test]+fn ensure_pending_grows_preserves_and_never_shrinks() {+ let mut s = state_with_pending(0);+ ensure_pending(&mut s, 0);+ assert_eq!(s.pending.len(), 0);+ ensure_pending(&mut s, 3);+ assert_eq!(s.pending.len(), 3);+ assert!(s.pending.iter().all(|p| p.throttle == 0.0 && !p.drift && !p.item));+ s.pending[0].throttle = 0.7;+ s.pending[0].drift = true;+ ensure_pending(&mut s, 5);+ assert_eq!(s.pending.len(), 5);+ assert_eq!(s.pending[0].throttle, 0.7, "existing samples survive growth");+ assert!(s.pending[0].drift);+ ensure_pending(&mut s, 2);+ assert_eq!(s.pending.len(), 5, "seats never shrink mid-race");+ ensure_pending(&mut s, 5);+ assert_eq!(s.pending.len(), 5);+}++#[test]+fn fixed_step_is_sixty_hertz() {+ assert!((STEP - 1.0 / 60.0).abs() < 1e-9);+ assert!(STEP > 0.0 && STEP < 0.1);+}++#[test]+fn view_proj_is_finite_for_degenerate_sizes() {+ for (w, h) in [(0, 0), (0, 720), (1280, 0), (1, 1)] {+ let m = view_proj_for([0.0, 4.0, 20.0], [0.0, 1.0, 0.0], w, h, (false, 0.0));+ assert!(m.iter().flatten().all(|v| v.is_finite()), "size {w}x{h}");+ let swapped = view_proj_for([0.0, 4.0, 20.0], [0.0, 1.0, 0.0], w, h, (true, 0.0));+ assert!(swapped.iter().flatten().all(|v| v.is_finite()));+ }+}++#[test]+fn view_proj_depends_on_camera_aspect_swap_and_rotation() {+ let cam = [10.0, 4.2, -30.0];+ let look = [10.0, 1.0, -40.0];+ let a = view_proj_for(cam, look, 1280, 720, (false, 0.0));+ // Deterministic.+ assert_eq!(a, view_proj_for(cam, look, 1280, 720, (false, 0.0)));+ // Moving the camera changes the matrix.+ assert_ne!(a, view_proj_for([0.0, 4.2, 0.0], look, 1280, 720, (false, 0.0)));+ // Looking elsewhere changes it too.+ assert_ne!(a, view_proj_for(cam, [0.0, 1.0, 0.0], 1280, 720, (false, 0.0)));+ // Swapped aspect (portrait panel) and pre-rotation both change it.+ assert_ne!(a, view_proj_for(cam, look, 1280, 720, (true, 0.0)));+ assert_ne!(a, view_proj_for(cam, look, 1280, 720, (false, 0.5)));+ // Portrait vs landscape aspect differ.+ assert_ne!(+ view_proj_for(cam, look, 720, 1280, (false, 0.0)),+ view_proj_for(cam, look, 1280, 720, (false, 0.0))+ );+}
games/kart/src/main/rust/src/items.rs
diff --git a/games/kart/src/main/rust/src/items.rs b/games/kart/src/main/rust/src/items.rsindex 962df700de..3e5ce18cd3 100644--- a/games/kart/src/main/rust/src/items.rs+++ b/games/kart/src/main/rust/src/items.rs@@ -85,7 +85,7 @@ pub fn deal_item(position: usize, kart_count: usize) -> HeldItem { /// One AI driver: pace wobble plus a steering lookahead. #[derive(Debug, Clone)] pub struct AiDriver {- /// 0.92..1.0 per-driver pace multiplier (mirrors the placeholder wobble).+ /// 0.90..=0.98 per-driver pace multiplier (mirrors the placeholder wobble). pub wobble: f32, /// Current steering output -1..1, smoothed so AI karts don't jitter. pub steer: f32,@@ -184,6 +184,8 @@ pub fn tick_shells(shells: &mut Vec<Shell>, karts: &[KartBody], dt: f32) -> Vec< hits } +#[cfg(test)]+mod items_tests; #[cfg(test)] mod tests { use super::*;
games/kart/src/main/rust/src/items/items_tests.rs
diff --git a/games/kart/src/main/rust/src/items/items_tests.rs b/games/kart/src/main/rust/src/items/items_tests.rsnew file mode 100644index 0000000000..59bcfd8018--- /dev/null+++ b/games/kart/src/main/rust/src/items/items_tests.rs@@ -0,0 +1,191 @@+//! Extra deterministic tests for items/AI (sibling of `items::tests`).+use super::*;+use crate::physics::TOP_SPEED;++fn kart_at(x: f32, z: f32) -> KartBody {+ let mut k = KartBody::spawn(0.0, 0.0);+ k.x = x;+ k.z = z;+ k+}++#[test]+fn deal_item_table_by_field_size() {+ // Solo always mushroom.+ assert_eq!(deal_item(0, 1), HeldItem::Mushroom);+ assert_eq!(deal_item(0, 0), HeldItem::Mushroom);+ // Two: leader mushroom, trailer shell.+ assert_eq!(deal_item(0, 2), HeldItem::Mushroom);+ assert_eq!(deal_item(1, 2), HeldItem::Shell);+ // Back half is inclusive of the exact middle in even fields.+ for (pos, want) in [+ (0, HeldItem::Mushroom), (1, HeldItem::Mushroom),+ (2, HeldItem::Shell), (3, HeldItem::Shell),+ ] {+ assert_eq!(deal_item(pos, 4), want, "pos {pos}/4");+ }+ // Odd field: position*2 >= count decides.+ assert_eq!(deal_item(1, 3), HeldItem::Mushroom); // 2 < 3+ assert_eq!(deal_item(2, 3), HeldItem::Shell); // 4 >= 3+ assert_eq!(deal_item(3, 8), HeldItem::Mushroom); // 6 < 8+ assert_eq!(deal_item(4, 8), HeldItem::Shell); // 8 >= 8+}++#[test]+fn rubber_boost_is_stepped_and_floored() {+ assert_eq!(rubber_boost(0.0), 0.0);+ assert_eq!(rubber_boost(-10.0), 0.0);+ assert_eq!(rubber_boost(RUBBER_STEP * 0.99), 0.0);+ assert_eq!(rubber_boost(RUBBER_STEP), RUBBER_GAIN);+ assert_eq!(rubber_boost(RUBBER_STEP * 1.99), RUBBER_GAIN);+ assert_eq!(rubber_boost(RUBBER_STEP * 3.0), RUBBER_GAIN * 3.0);+ // Monotonic non-decreasing over a sweep.+ let mut prev = 0.0;+ for i in 0..50 {+ let b = rubber_boost(i as f32 * 0.01);+ assert!(b >= prev);+ prev = b;+ }+}++#[test]+fn effective_pace_combines_wobble_boost_and_cap() {+ assert!((effective_pace(1.0, 0.0) - AI_PACE).abs() < 1e-6);+ assert!((effective_pace(0.5, 0.0) - AI_PACE * 0.5).abs() < 1e-6);+ assert_eq!(effective_pace(1.0, 100.0), AI_PACE_MAX);+ assert_eq!(effective_pace(0.9, 100.0), AI_PACE_MAX);+ // One step of deficit adds exactly RUBBER_GAIN unless capped.+ let base = effective_pace(0.9, 0.0);+ assert!((effective_pace(0.9, RUBBER_STEP) - (base + RUBBER_GAIN)).abs() < 1e-6);+ // Never exceeds cap, never below base for non-negative deficit.+ for deficit in [0.0f32, 0.03, 0.2, 1.0, 5.0] {+ let p = effective_pace(0.95, deficit);+ assert!(p >= AI_PACE * 0.95 - 1e-6 && p <= AI_PACE_MAX);+ }+}++#[test]+fn ai_driver_wobble_spread() {+ assert!((AiDriver::new(0, 1).wobble - 0.98).abs() < 1e-6);+ assert!((AiDriver::new(0, 4).wobble - 0.98).abs() < 1e-6);+ assert!((AiDriver::new(3, 4).wobble - 0.90).abs() < 1e-6);+ let mid = AiDriver::new(1, 3);+ assert!(mid.wobble > 0.90 && mid.wobble < 0.98);+ assert_eq!(mid.steer, 0.0);+ // First driver is never slower-wobbled than the last.+ assert!(AiDriver::new(0, 8).wobble >= AiDriver::new(7, 8).wobble);+ for i in 0..4 {+ let w = AiDriver::new(i, 4).wobble;+ assert!((0.90..=0.98).contains(&w), "wobble {w}");+ }+}++#[test]+fn ai_control_uses_effective_pace_and_never_brakes_or_fires() {+ let kart = KartBody::spawn(10.0, 0.0);+ let mut ai = AiDriver::new(0, 3);+ let c = ai.control(&kart, 0.0);+ assert!((c.throttle - effective_pace(ai.wobble, 0.0)).abs() < 1e-6);+ assert_eq!(c.brake, 0.0);+ assert!(!c.item);+ assert!((-1.0..=1.0).contains(&c.steering));+ let behind = ai.control(&kart, 0.25);+ assert!(behind.throttle > c.throttle, "rubber band must raise throttle");+ assert!(behind.throttle <= AI_PACE_MAX);+}++#[test]+fn ai_control_steering_is_smoothed() {+ // Face away from the lookahead: target saturates, first output is only+ // 18% of the way there.+ let mut kart = KartBody::spawn(10.0, 0.0);+ kart.yaw += std::f32::consts::PI;+ let mut ai = AiDriver::new(0, 3);+ let first = ai.control(&kart, 0.0);+ assert!(first.steering.abs() <= 0.18 + 1e-5, "first {}", first.steering);+ assert!(first.steering.abs() > 0.05, "must steer toward the line");+ let second = ai.control(&kart, 0.0);+ assert!(second.steering.abs() > first.steering.abs(), "smoothing converges");+ assert_eq!(second.steering.signum(), first.steering.signum());+}++#[test]+fn ai_control_drifts_only_when_corner_is_tight() {+ // Aligned with the track on a straight: no drift.+ let kart = KartBody::spawn(10.0, 0.0);+ let mut ai = AiDriver::new(0, 3);+ let c = ai.control(&kart, 0.0);+ assert!(!c.drift);+ // Pointing backwards: heading error is huge, drift engages.+ let mut backwards = KartBody::spawn(10.0, 0.0);+ backwards.yaw += std::f32::consts::PI;+ let mut ai2 = AiDriver::new(0, 3);+ assert!(ai2.control(&backwards, 0.0).drift);+}++#[test]+fn shell_moves_along_yaw_and_ages() {+ let mut shells = vec![Shell { owner: 9, x: 0.0, z: 0.0, yaw: 0.0, life: 5.0, grace: 0.0 }];+ let hits = tick_shells(&mut shells, &[], 0.1);+ assert!(hits.is_empty() && shells.len() == 1);+ // yaw 0 travels -Z at SHELL_SPEED.+ assert!((shells[0].z + SHELL_SPEED * 0.1).abs() < 1e-3);+ assert!(shells[0].x.abs() < 1e-3);+ assert!((shells[0].life - 4.9).abs() < 1e-4);+ // yaw +90deg travels +X.+ let mut shells = vec![Shell { owner: 9, x: 1.0, z: 2.0, yaw: std::f32::consts::FRAC_PI_2, life: 5.0, grace: 0.0 }];+ tick_shells(&mut shells, &[], 0.1);+ assert!((shells[0].x - (1.0 + SHELL_SPEED * 0.1)).abs() < 1e-3);+ assert!((shells[0].z - 2.0).abs() < 1e-3);+}++#[test]+fn shell_expires_without_hitting() {+ let victim = kart_at(0.0, 0.0);+ let mut shells = vec![Shell { owner: 9, x: 0.0, z: 0.0, yaw: 0.0, life: 0.05, grace: 0.0 }];+ let hits = tick_shells(&mut shells, &[victim], 0.1);+ assert!(hits.is_empty(), "expired shell cannot hit");+ assert!(shells.is_empty());+ // Life exactly consumed also expires.+ let mut shells = vec![Shell { owner: 9, x: 0.0, z: 0.0, yaw: 0.0, life: 0.1, grace: 0.0 }];+ assert!(tick_shells(&mut shells, &[], 0.1).is_empty());+ assert!(shells.is_empty());+}++#[test]+fn shell_hit_radius_boundary() {+ // Shell moves 46*0.001 = 0.046 in -Z first, then hit is tested.+ let shell = || Shell { owner: 9, x: 0.0, z: 0.0, yaw: 0.0, life: 5.0, grace: 0.0 };+ let inside = kart_at(0.0, -0.046 + crate::physics::HIT_RADIUS - 0.1);+ let mut shells = vec![shell()];+ assert_eq!(tick_shells(&mut shells, &[inside], 0.001), vec![0]);+ assert!(shells.is_empty(), "hit consumes the shell");+ let outside = kart_at(0.0, -0.046 + crate::physics::HIT_RADIUS + 0.5);+ let mut shells = vec![shell()];+ assert!(tick_shells(&mut shells, &[outside], 0.001).is_empty());+ assert_eq!(shells.len(), 1, "missed shell flies on");+}++#[test]+fn shell_hits_only_first_kart_and_reports_its_index() {+ let a = kart_at(0.0, -1.0);+ let b = kart_at(0.0, -1.0);+ let mut shells = vec![Shell { owner: 9, x: 0.0, z: 0.0, yaw: 0.0, life: 5.0, grace: 0.0 }];+ let hits = tick_shells(&mut shells, &[a, b], 0.01);+ assert_eq!(hits, vec![0], "one shell, one hit, first kart wins");+ // Victim at index 2 is reported as 2.+ let far = kart_at(100.0, 100.0);+ let near = kart_at(0.0, -1.0);+ let mut shells = vec![Shell { owner: 9, x: 0.0, z: 0.0, yaw: 0.0, life: 5.0, grace: 0.0 }];+ assert_eq!(tick_shells(&mut shells, &[far.clone(), far, near], 0.01), vec![2]);+}++#[test]+fn empty_shells_and_empty_field_are_fine() {+ let mut shells: Vec<Shell> = Vec::new();+ assert!(tick_shells(&mut shells, &[], 0.016).is_empty());+ let mut shells = vec![Shell { owner: 0, x: 0.0, z: 0.0, yaw: 1.0, life: 5.0, grace: 0.0 }];+ assert!(tick_shells(&mut shells, &[], 0.016).is_empty());+ assert_eq!(shells.len(), 1);+ let _ = TOP_SPEED;+}
games/kart/src/main/rust/src/mesh.rs
diff --git a/games/kart/src/main/rust/src/mesh.rs b/games/kart/src/main/rust/src/mesh.rsindex 09014654e3..18bbd4e25e 100644--- a/games/kart/src/main/rust/src/mesh.rs+++ b/games/kart/src/main/rust/src/mesh.rs@@ -285,6 +285,8 @@ pub fn build_shell_mesh(out: &mut Vec<KartVertex>, x: f32, z: f32, ticks: u64) { box_at(out, [x, 0.35, z], [0.9, 0.7, 0.9], SHELL_COLOR); } +#[cfg(test)]+mod mesh_tests; #[cfg(test)] mod tests { use super::*;
games/kart/src/main/rust/src/mesh/mesh_tests.rs
diff --git a/games/kart/src/main/rust/src/mesh/mesh_tests.rs b/games/kart/src/main/rust/src/mesh/mesh_tests.rsnew file mode 100644index 0000000000..99d421b948--- /dev/null+++ b/games/kart/src/main/rust/src/mesh/mesh_tests.rs@@ -0,0 +1,143 @@+//! Extra deterministic tests for mesh builders (sibling of `mesh::tests`).+use super::*;++fn spec(x: f32, z: f32, yaw: f32, seat: usize, ai: bool, spin: f32, boost: bool) -> KartMeshSpec {+ KartMeshSpec { x, z, yaw, seat, ai, spin, boost }+}+fn build(s: KartMeshSpec) -> Vec<KartVertex> {+ let mut out = Vec::new();+ build_kart_mesh(&mut out, s);+ out+}+fn same_mesh(a: &[KartVertex], b: &[KartVertex]) -> bool {+ a.len() == b.len()+ && a.iter().zip(b).all(|(u, v)| u.pos == v.pos && u.color == v.color)+}++#[test]+fn darken_scales_each_channel() {+ assert_eq!(darken([1.0, 0.5, 0.25], 0.5), [0.5, 0.25, 0.125]);+ assert_eq!(darken([0.3, 0.6, 0.9], 0.0), [0.0, 0.0, 0.0]);+ assert_eq!(darken([0.3, 0.6, 0.9], 1.0), [0.3, 0.6, 0.9]);+ assert_eq!(darken([0.0, 0.0, 0.0], 0.55), [0.0, 0.0, 0.0]);+}++#[test]+fn quad_emits_two_triangles_in_order() {+ let mut out = Vec::new();+ let (a, b, c, d) = ([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0]);+ quad(&mut out, a, b, c, d, [1.0, 0.0, 0.0]);+ assert_eq!(out.len(), 6);+ assert_eq!([out[0].pos, out[1].pos, out[2].pos], [a, b, c]);+ assert_eq!([out[3].pos, out[4].pos, out[5].pos], [c, b, d]);+ assert!(out.iter().all(|v| v.color == [1.0, 0.0, 0.0]));+}++#[test]+fn box_at_emits_five_faces_within_bounds() {+ let mut out = Vec::new();+ box_at(&mut out, [10.0, 2.0, -5.0], [4.0, 3.0, 2.0], [0.8, 0.4, 0.2]);+ assert_eq!(out.len(), 30, "5 quads x 6 verts, no bottom face");+ for v in &out {+ assert!((8.0..=12.0).contains(&v.pos[0]));+ assert!((2.0..=5.0).contains(&v.pos[1]), "y is bottom-centre based");+ assert!((-6.0..=-4.0).contains(&v.pos[2]));+ assert!(v.color.iter().all(|c| (0.0..=0.8).contains(c)));+ }+ // Top face reaches y=5, and some face uses the undarkened colour.+ assert!(out.iter().any(|v| v.pos[1] == 5.0));+ assert!(out.iter().any(|v| v.color == [0.8, 0.4, 0.2]));+}++#[test]+fn kart_mesh_vertex_count_is_stable_across_variants() {+ let base = build(spec(0.0, 0.0, 0.0, 0, false, 0.0, false));+ assert_eq!(base.len(), 168, "body 30 + cabin 18 + 4 wheels x 30");+ for s in [+ spec(5.0, -3.0, 1.2, 3, true, 0.0, false),+ spec(0.0, 0.0, 0.0, 0, false, 0.7, false),+ spec(0.0, 0.0, 0.0, 0, false, 0.0, true),+ spec(0.0, 0.0, 0.0, 7, true, 0.3, true),+ ] {+ assert_eq!(build(s).len(), base.len());+ }+ assert!(base.iter().all(|v| v.pos.iter().all(|c| c.is_finite())));+ assert!(base.iter().all(|v| v.color.iter().all(|c| (0.0..=1.0).contains(c))));+}++#[test]+fn kart_mesh_seat_color_wraps_and_ai_darkens() {+ assert_eq!(KART_COLORS.len(), 8);+ let seat0 = build(spec(0.0, 0.0, 0.0, 0, false, 0.0, false));+ let seat8 = build(spec(0.0, 0.0, 0.0, 8, false, 0.0, false));+ assert!(same_mesh(&seat0, &seat8), "seat index wraps modulo palette");+ // First vertex is the body top in the seat colour.+ assert_eq!(seat0[0].color, KART_COLORS[0]);+ let ai = build(spec(0.0, 0.0, 0.0, 0, true, 0.0, false));+ assert_eq!(ai[0].color, darken(KART_COLORS[0], AI_DARKEN));+ let seat1 = build(spec(0.0, 0.0, 0.0, 1, false, 0.0, false));+ assert_eq!(seat1[0].color, KART_COLORS[1]);+ assert_ne!(seat0[0].color, seat1[0].color);+ // Palette entries are pairwise distinct.+ for i in 0..KART_COLORS.len() {+ for j in i + 1..KART_COLORS.len() {+ assert_ne!(KART_COLORS[i], KART_COLORS[j]);+ }+ }+}++#[test]+fn kart_mesh_translates_with_position_and_changes_with_spin_and_boost() {+ let a = build(spec(0.0, 0.0, 0.3, 0, false, 0.0, false));+ let b = build(spec(10.0, -7.0, 0.3, 0, false, 0.0, false));+ for (u, v) in a.iter().zip(&b) {+ assert!((v.pos[0] - u.pos[0] - 10.0).abs() < 1e-4);+ assert!((v.pos[1] - u.pos[1]).abs() < 1e-4);+ assert!((v.pos[2] - u.pos[2] + 7.0).abs() < 1e-4);+ }+ assert!(!same_mesh(&a, &build(spec(0.0, 0.0, 0.3, 0, false, 0.9, false))), "spin rotates");+ assert!(!same_mesh(&a, &build(spec(0.0, 0.0, 0.3, 0, false, 0.0, true))), "boost stretches");+ // Deterministic for identical specs.+ assert!(same_mesh(&a, &build(spec(0.0, 0.0, 0.3, 0, false, 0.0, false))));+}++#[test]+fn box_and_shell_markers_have_expected_shape() {+ let mut out = Vec::new();+ build_box_mesh(&mut out, 4.0, -2.0, 0);+ assert_eq!(out.len(), 30);+ // box_at darkens side faces; the top keeps the base colour.+ assert!(out.iter().any(|v| v.color == BOX_COLOR));+ assert!(out.iter().all(|v| v.color[0] <= BOX_COLOR[0] && v.color[1] <= BOX_COLOR[1] && v.color[2] <= BOX_COLOR[2]));+ // At ticks=0 the bob is 0.9, box is 1.2 tall starting there.+ assert!(out.iter().all(|v| (0.9..=2.1 + 1e-4).contains(&v.pos[1])));+ assert!(out.iter().all(|v| (3.4..=4.6).contains(&v.pos[0])));+ // Later ticks bob the box to a different height.+ let mut later = Vec::new();+ build_box_mesh(&mut later, 4.0, -2.0, 15);+ assert_ne!(out[0].pos[1], later[0].pos[1]);++ let mut s0 = Vec::new();+ build_shell_mesh(&mut s0, 1.0, 1.0, 0);+ let mut s1 = Vec::new();+ build_shell_mesh(&mut s1, 1.0, 1.0, 999_999);+ assert_eq!(s0.len(), 30);+ assert!(s0.iter().any(|v| v.color == SHELL_COLOR));+ assert!(same_mesh(&s0, &s1), "shell mesh ignores ticks");+}++#[test]+fn track_mesh_contains_each_surface_kind() {+ let mesh = build_track_mesh();+ assert!(mesh.iter().any(|v| v.pos[1] == WALL_HEIGHT), "wall tops exist");+ assert!(mesh.iter().any(|v| (v.pos[1] + 0.05).abs() < 1e-6), "grass at -0.05");+ assert!(mesh.iter().any(|v| v.pos[1] == 0.0), "asphalt/walls at ground");+ assert!(mesh.iter().all(|v| (-0.05..=WALL_HEIGHT).contains(&v.pos[1])));+ // Start-line checker appears before plain asphalt does.+ assert!(mesh.iter().take(6).all(|v| v.color == CHECKER_A));+ assert!(mesh.iter().any(|v| v.color == CHECKER_B));+ assert!(mesh.iter().any(|v| v.color == ASPHALT));+ assert!(mesh.iter().any(|v| v.color == GRASS_A || v.color == GRASS_B));+ assert!(mesh.iter().any(|v| v.color == WALL_A));+ assert!(mesh.iter().any(|v| v.color == WALL_B));+}
games/kart/src/main/rust/src/physics.rs
diff --git a/games/kart/src/main/rust/src/physics.rs b/games/kart/src/main/rust/src/physics.rsindex 73952f82ca..c5203ff58c 100644--- a/games/kart/src/main/rust/src/physics.rs+++ b/games/kart/src/main/rust/src/physics.rs@@ -16,7 +16,9 @@ pub const TOP_SPEED: f32 = 40.0; /// Seconds 0 → top speed at full throttle. Also the drag time constant: /// /// the tick integrates `speed += (accel - braking) * dt - speed * dt /-/// ACCEL_TIME`, so sustained speed settles exactly at `TOP_SPEED * throttle`.+/// ACCEL_TIME`, so sustained speed settles exactly at `TOP_SPEED * throttle`+/// (at `TOP_SPEED * BOOST_MULT * throttle` while boosting: boost scales the+/// thrust, not just the cap — see [`BOOST_MULT`]). /// An AI pace of 0.78 then genuinely runs at 78% (mirroring the placeholder's /// `AI_PACE`), and lifting off coasts down over a couple of seconds. pub const ACCEL_TIME: f32 = 2.2;@@ -31,7 +33,11 @@ pub const DRIFT_KEEP: f32 = 0.88; pub const GRIP_SCRUB: f32 = 0.18; /// Seconds of continuous drift to earn a boost. pub const DRIFT_CHARGE_TIME: f32 = 1.2;-/// Boost top-speed multiplier while the charge burns.+/// Boost multiplier while the charge burns: scales both the top-speed cap+/// and the engine thrust, so the accel/drag equilibrium rises to+/// `TOP_SPEED * BOOST_MULT * throttle`. Scaling only the cap would grant+/// ~nothing on a straight, where the unboosted equilibrium+/// (`TOP_SPEED * throttle`) already sits below the boosted cap. pub const BOOST_MULT: f32 = 1.35; /// Seconds a drift boost burns. pub const BOOST_TIME: f32 = 1.6;@@ -120,7 +126,8 @@ impl KartBody { GRIP_SCRUB }; let mut top = TOP_SPEED * (1.0 - grip_loss);- if self.boost_left > 0.0 {+ let boosting = self.boost_left > 0.0;+ if boosting { self.boost_left -= dt; top *= BOOST_MULT; }@@ -132,12 +139,18 @@ impl KartBody { if !track::on_track(self.x, self.z, &p) { top *= track::OFF_TRACK_KEEP; }- let accel = TOP_SPEED / ACCEL_TIME * throttle;+ // Boost scales thrust as well as the cap (`top` above), so the+ // equilibrium below rises with it; otherwise a mushroom fired at+ // full speed on a straight (exactly what the AI does) would add+ // no speed at all. Unboosted thrust is unchanged.+ let thrust_mult = if boosting { BOOST_MULT } else { 1.0 };+ let accel = TOP_SPEED / ACCEL_TIME * throttle * thrust_mult; let braking = TOP_SPEED / BRAKE_TIME * brake; self.speed += (accel - braking) * dt; // Linear drag with time constant ACCEL_TIME: sustained speed- // settles at TOP * throttle, so an AI pace of 0.78 genuinely runs- // at 78% (mirroring the placeholder's AI_PACE), and coasting to a+ // settles at TOP * throttle (TOP * BOOST_MULT * throttle while+ // boosting), so an AI pace of 0.78 genuinely runs at 78%+ // (mirroring the placeholder's AI_PACE), and coasting to a // standstill takes a couple of seconds rather than forever. self.speed -= self.speed * dt / ACCEL_TIME; self.speed = self.speed.clamp(0.0, top.max(0.0));@@ -187,6 +200,8 @@ impl KartBody { } } +#[cfg(test)]+mod physics_tests; #[cfg(test)] mod tests { use super::*;
games/kart/src/main/rust/src/physics/physics_tests.rs
diff --git a/games/kart/src/main/rust/src/physics/physics_tests.rs b/games/kart/src/main/rust/src/physics/physics_tests.rsnew file mode 100644index 0000000000..3bdcb271eb--- /dev/null+++ b/games/kart/src/main/rust/src/physics/physics_tests.rs@@ -0,0 +1,318 @@+//! Extra deterministic tests for kart physics (sibling of `physics::tests`).+use super::*;+use crate::track;++fn inp(throttle: f32, steering: f32, brake: f32, drift: bool) -> DriveInput {+ DriveInput { throttle, steering, brake, drift, item: false }+}++#[test]+fn spawn_places_kart_on_centerline_plus_lane() {+ for (s, lane) in [(0.0f32, 0.0f32), (8.0, -3.0), (100.0, 4.5), (400.0, -6.0)] {+ let k = KartBody::spawn(s, lane);+ let p = track::point_at(s);+ assert!((k.x - (p.x + p.nx * lane)).abs() < 1e-4, "x s={s}");+ assert!((k.z - (p.z + p.nz * lane)).abs() < 1e-4, "z s={s}");+ assert!((k.yaw - track::tangent_yaw(&p)).abs() < 1e-4);+ assert_eq!(k.speed, 0.0);+ assert_eq!(k.lap, 0);+ assert_eq!(k.drift_charge, 0.0);+ assert_eq!(k.boost_left, 0.0);+ assert_eq!(k.spin_left, 0.0);+ assert_eq!(k.track_s, track::advance(s, 0.0));+ }+}++#[test]+fn zero_and_negative_dt_are_noops() {+ for dt in [0.0f32, -1.0, -0.001] {+ let mut k = KartBody::spawn(20.0, 1.0);+ k.speed = 12.0;+ let (x, z, yaw, s) = (k.x, k.z, k.yaw, k.track_s);+ k.tick(&inp(1.0, 1.0, 0.0, false), dt);+ assert_eq!((k.x, k.z, k.yaw, k.track_s, k.speed), (x, z, yaw, s, 12.0));+ }+}++#[test]+fn dt_over_one_second_is_clamped_to_one() {+ let mut a = KartBody::spawn(10.0, 0.0);+ let mut b = KartBody::spawn(10.0, 0.0);+ a.tick(&inp(1.0, 0.2, 0.0, false), 5.0);+ b.tick(&inp(1.0, 0.2, 0.0, false), 1.0);+ assert_eq!(a.x.to_bits(), b.x.to_bits());+ assert_eq!(a.z.to_bits(), b.z.to_bits());+ assert_eq!(a.speed.to_bits(), b.speed.to_bits());+ assert_eq!(a.yaw.to_bits(), b.yaw.to_bits());+}++#[test]+fn inputs_are_clamped_to_normalized_ranges() {+ let mut wild = KartBody::spawn(10.0, 0.0);+ let mut tame = KartBody::spawn(10.0, 0.0);+ wild.tick(&inp(9.0, -9.0, 0.0, false), 1.0 / 60.0);+ tame.tick(&inp(1.0, -1.0, 0.0, false), 1.0 / 60.0);+ assert_eq!(wild.speed.to_bits(), tame.speed.to_bits());+ assert_eq!(wild.yaw.to_bits(), tame.yaw.to_bits());+ // Negative throttle/brake behave as zero.+ let mut neg = KartBody::spawn(10.0, 0.0);+ neg.tick(&inp(-3.0, 0.0, -2.0, false), 0.5);+ assert_eq!(neg.speed, 0.0);+}++#[test]+fn braking_never_makes_speed_negative() {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = 1.0;+ for _ in 0..120 {+ k.tick(&inp(0.0, 0.0, 1.0, false), 1.0 / 60.0);+ assert!(k.speed >= 0.0);+ }+ assert_eq!(k.speed, 0.0);+}++#[test]+fn coasting_decays_but_does_not_stop_instantly() {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = TOP_SPEED;+ let mut prev = k.speed;+ for _ in 0..60 {+ k.tick(&inp(0.0, 0.0, 0.0, false), 1.0 / 60.0);+ assert!(k.speed < prev, "coast must decay");+ assert!(k.speed > 0.0);+ prev = k.speed;+ }+ // After 1s of drag (time constant ACCEL_TIME) still well above zero.+ assert!(k.speed > TOP_SPEED * 0.4, "speed={}", k.speed);+}++#[test]+fn parked_kart_steers_at_floor_authority() {+ let mut k = KartBody::spawn(10.0, 0.0);+ let yaw0 = k.yaw;+ k.tick(&inp(0.0, 1.0, 0.0, false), 0.5);+ let expected = TURN_RATE * 0.15 * 0.5;+ assert!((k.yaw - yaw0 - expected).abs() < 1e-4, "yaw delta {}", k.yaw - yaw0);+ // Negative steering turns the other way.+ let mut k2 = KartBody::spawn(10.0, 0.0);+ k2.tick(&inp(0.0, -1.0, 0.0, false), 0.5);+ assert!(k2.yaw < yaw0);+ assert_eq!(k.speed, 0.0);+}++#[test]+fn steering_authority_and_drift_multiplier_scale_turn() {+ let turn = |speed: f32, drift: bool| {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = speed;+ let y0 = k.yaw;+ k.tick(&inp(0.0, 1.0, 0.0, drift), 1.0 / 60.0);+ k.yaw - y0+ };+ assert!(turn(TOP_SPEED, false) > turn(TOP_SPEED * 0.3, false));+ let normal = turn(TOP_SPEED * 0.5, false);+ let drifting = turn(TOP_SPEED * 0.5, true);+ assert!((drifting / normal - 1.35).abs() < 0.02, "ratio {}", drifting / normal);+}++#[test]+fn forward_motion_follows_yaw_convention() {+ // yaw 0 faces -Z.+ let mut k = KartBody::spawn(200.0, 0.0);+ k.yaw = 0.0;+ k.speed = 10.0;+ let (x0, z0) = (k.x, k.z);+ k.tick(&inp(0.0, 0.0, 0.0, false), 0.1);+ assert!((k.x - x0).abs() < 1e-3);+ assert!(k.z < z0, "yaw 0 must move -Z");+ // yaw +90deg faces +X.+ let mut k = KartBody::spawn(200.0, 0.0);+ k.yaw = std::f32::consts::FRAC_PI_2;+ k.speed = 10.0;+ let (x0, z0) = (k.x, k.z);+ k.tick(&inp(0.0, 0.0, 0.0, false), 0.1);+ assert!(k.x > x0, "yaw pi/2 must move +X");+ assert!((k.z - z0).abs() < 1e-3);+}++#[test]+fn drift_charge_needs_speed_steering_and_hold() {+ // Too slow: no charge.+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = TOP_SPEED * 0.39;+ for _ in 0..30 { k.tick(&inp(1.0, 0.9, 0.0, true), 1.0 / 60.0); }+ // Speed may have risen under throttle; use a fresh slow kart with no throttle.+ let mut slow = KartBody::spawn(10.0, 0.0);+ slow.speed = TOP_SPEED * 0.3;+ for _ in 0..30 { slow.tick(&inp(0.0, 0.9, 0.0, true), 1.0 / 60.0); }+ assert_eq!(slow.drift_charge, 0.0);+ let _ = k;+ // Steering at exactly 0.35 does not charge (needs > 0.35).+ let mut edge = KartBody::spawn(10.0, 0.0);+ edge.speed = TOP_SPEED;+ for _ in 0..30 { edge.tick(&inp(1.0, 0.35, 0.0, true), 1.0 / 60.0); }+ assert_eq!(edge.drift_charge, 0.0);+ // Just above threshold accumulates ~dt per tick (before any boost).+ let mut ok = KartBody::spawn(10.0, 0.0);+ ok.speed = TOP_SPEED;+ for _ in 0..12 { ok.tick(&inp(1.0, 0.5, 0.0, true), 1.0 / 60.0); }+ assert!(ok.drift_charge > 0.15 && ok.drift_charge <= 12.0 / 60.0 + 1e-4, "{}", ok.drift_charge);+}++#[test]+fn drift_charge_resets_on_release_or_straightening() {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = TOP_SPEED;+ for _ in 0..20 { k.tick(&inp(1.0, 0.8, 0.0, true), 1.0 / 60.0); }+ assert!(k.drift_charge > 0.0);+ k.tick(&inp(1.0, 0.8, 0.0, false), 1.0 / 60.0);+ assert_eq!(k.drift_charge, 0.0);+ // Recharge then straighten the wheel.+ for _ in 0..20 { k.tick(&inp(1.0, 0.8, 0.0, true), 1.0 / 60.0); }+ assert!(k.drift_charge > 0.0);+ k.tick(&inp(1.0, 0.0, 0.0, true), 1.0 / 60.0);+ assert_eq!(k.drift_charge, 0.0);+}++#[test]+fn completed_drift_grants_boost_and_clears_charge() {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = TOP_SPEED;+ let mut granted = false;+ for _ in 0..200 {+ k.tick(&inp(1.0, 0.8, 0.0, true), 1.0 / 60.0);+ if k.boost_left > 0.0 { granted = true; break; }+ }+ assert!(granted, "drift for >DRIFT_CHARGE_TIME must boost");+ assert_eq!(k.drift_charge, 0.0);+}++#[test]+fn boost_now_and_spin_interactions() {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.boost_now();+ assert_eq!(k.boost_left, BOOST_TIME);+ k.spin();+ assert_eq!(k.spin_left, 1.2);+ assert_eq!(k.boost_left, 0.0, "spin cancels boost");+ k.boost_now();+ assert_eq!(k.boost_left, BOOST_TIME, "boost_now works even while spun (by design)");+}++#[test]+fn boost_at_full_speed_on_straight_gains_speed() {+ // Regression: boost used to raise only the cap, but the accel/drag+ // equilibrium sits at TOP_SPEED * throttle below that cap, so a mushroom+ // at full speed on a straight (what the AI does) granted ~nothing.+ let run = |boost: bool| {+ // s=10 is on the 200 m top straight; ~1 s of travel stays on it.+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = TOP_SPEED;+ if boost { k.boost_now(); }+ for _ in 0..60 { k.tick(&inp(1.0, 0.0, 0.0, false), 1.0 / 60.0); }+ k.speed+ };+ let plain = run(false);+ let boosted = run(true);+ assert!((plain - TOP_SPEED).abs() < 0.5, "unboosted equilibrium {plain}");+ assert!(boosted > TOP_SPEED + 3.0, "boost must gain speed, got {boosted}");+ assert!(boosted > plain + 3.0, "boosted {boosted} vs plain {plain}");+ assert!(boosted <= TOP_SPEED * BOOST_MULT + 0.01, "over cap: {boosted}");+}++#[test]+fn non_boost_equilibrium_is_unchanged() {+ // Full throttle settles at TOP_SPEED, part throttle at TOP_SPEED*throttle.+ for (throttle, want) in [(1.0f32, TOP_SPEED), (0.5, TOP_SPEED * 0.5)] {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = want;+ for _ in 0..60 { k.tick(&inp(throttle, 0.0, 0.0, false), 1.0 / 60.0); }+ assert!((k.speed - want).abs() < 0.5, "throttle {throttle}: {}", k.speed);+ assert!(k.speed <= TOP_SPEED + 1e-3, "unboosted over cap: {}", k.speed);+ }+}++#[test]+fn boost_expires_after_boost_time() {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = TOP_SPEED;+ k.boost_now();+ for _ in 0..((BOOST_TIME * 60.0) as usize + 5) {+ k.tick(&inp(1.0, 0.0, 0.0, false), 1.0 / 60.0);+ }+ assert!(k.boost_left <= 0.0, "boost_left={}", k.boost_left);+}++#[test]+fn boost_keeps_more_speed_through_full_lock_than_no_boost() {+ let run = |boost: bool| {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = TOP_SPEED;+ if boost { k.boost_now(); }+ k.tick(&inp(1.0, 1.0, 0.0, false), 1.0 / 60.0);+ k.speed+ };+ assert!(run(true) > run(false) + 1.0, "boost must raise the scrubbed cap");+ // Unboosted full-lock speed is capped near TOP*(1-GRIP_SCRUB).+ assert!(run(false) <= TOP_SPEED * (1.0 - GRIP_SCRUB) + 0.6);+}++#[test]+fn spin_locks_steering_rotates_and_then_recovers() {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = TOP_SPEED * 0.8;+ k.spin();+ let y0 = k.yaw;+ k.tick(&inp(1.0, -1.0, 0.0, false), 0.25);+ // Spin rotation dominates: +7 rad/s regardless of -1 steering.+ assert!((k.yaw - y0 - 7.0 * 0.25).abs() < 1e-3, "delta {}", k.yaw - y0);+ assert!(k.speed < TOP_SPEED * 0.8);+ // Burn off the spin (1.2s total), then steering works again.+ for _ in 0..10 { k.tick(&inp(0.0, 0.0, 0.0, false), 0.25); }+ assert!(k.spin_left <= 0.0);+ k.speed = TOP_SPEED * 0.5;+ let y1 = k.yaw;+ k.tick(&inp(0.0, 1.0, 0.0, false), 0.1);+ let delta = k.yaw - y1;+ assert!(delta > 0.0 && delta < 1.0, "post-spin steering delta {delta}");+}++#[test]+fn off_track_caps_speed_but_on_track_does_not() {+ let mut off = KartBody::spawn(10.0, 0.0);+ let p = track::point_at(off.track_s);+ off.x = p.x + p.nx * (track::HALF_WIDTH + 5.0);+ off.z = p.z + p.nz * (track::HALF_WIDTH + 5.0);+ off.speed = TOP_SPEED;+ off.tick(&inp(1.0, 0.0, 0.0, false), 1.0 / 60.0);+ assert!(off.speed <= TOP_SPEED * track::OFF_TRACK_KEEP + 0.6, "off speed {}", off.speed);++ let mut on = KartBody::spawn(10.0, 0.0);+ on.speed = TOP_SPEED;+ on.tick(&inp(1.0, 0.0, 0.0, false), 1.0 / 60.0);+ assert!(on.speed > TOP_SPEED * 0.9, "on speed {}", on.speed);+}++#[test]+fn grip_scrub_exceeds_drift_speed_loss() {+ let run = |drift: bool| {+ let mut k = KartBody::spawn(10.0, 0.0);+ k.speed = TOP_SPEED;+ k.tick(&inp(1.0, 1.0, 0.0, drift), 1.0 / 60.0);+ k.speed+ };+ let grip = run(false);+ let drift = run(true);+ assert!(drift > grip, "drift keeps more speed: {drift} vs {grip}");+ assert!(grip <= TOP_SPEED * (1.0 - GRIP_SCRUB) + 0.6);+ assert!(drift <= TOP_SPEED * DRIFT_KEEP + 0.6);+}++#[test]+fn no_lap_credit_for_mid_track_motion() {+ let mut k = KartBody::spawn(100.0, 0.0);+ k.speed = TOP_SPEED;+ for _ in 0..60 { k.tick(&inp(1.0, 0.0, 0.0, false), 1.0 / 60.0); }+ assert_eq!(k.lap, 0);+ assert!(k.track_s > 100.0);+}
games/kart/src/main/rust/src/race.rs
diff --git a/games/kart/src/main/rust/src/race.rs b/games/kart/src/main/rust/src/race.rsindex 503151a006..0e18111826 100644--- a/games/kart/src/main/rust/src/race.rs+++ b/games/kart/src/main/rust/src/race.rs@@ -326,6 +326,8 @@ fn grid_lane(i: usize, _grid: usize) -> f32 { } } +#[cfg(test)]+mod race_tests; #[cfg(test)] mod tests { use super::*;
games/kart/src/main/rust/src/race/race_tests.rs
diff --git a/games/kart/src/main/rust/src/race/race_tests.rs b/games/kart/src/main/rust/src/race/race_tests.rsnew file mode 100644index 0000000000..bee31a2f34--- /dev/null+++ b/games/kart/src/main/rust/src/race/race_tests.rs@@ -0,0 +1,282 @@+//! Extra deterministic tests for race state (sibling of `race::tests`).+//! Child module: may inspect private seats/boxes/shells and helpers.+use super::*;+use crate::items::{HeldItem, Shell, BOX_RESPAWN};+use crate::physics::{DriveInput, KartBody, BOOST_TIME};+use crate::track;++fn drive(item: bool) -> DriveInput {+ DriveInput { throttle: 0.0, steering: 0.0, brake: 0.0, drift: false, item }+}++#[test]+fn grid_lane_alternates_and_progress_key_orders() {+ assert_eq!(grid_lane(0, 4), -3.0);+ assert_eq!(grid_lane(1, 4), 3.0);+ assert_eq!(grid_lane(2, 4), -3.0);+ assert_eq!(grid_lane(7, 8), 3.0);+ let mut k = KartBody::spawn(0.0, 0.0);+ k.lap = 2;+ k.track_s = track::TRACK_LENGTH / 2.0;+ assert!((progress_key(&k) - 2.5).abs() < 1e-5);+ k.lap = 0;+ k.track_s = 0.0;+ assert_eq!(progress_key(&k), 0.0);+}++#[test]+fn new_race_with_no_humans_is_all_ai() {+ let race = Race::new(&[]);+ assert_eq!(race.seat_count(), AI_COUNT);+ assert_eq!(race.cam_seat, 0);+ assert_eq!(race.ticks, 0);+ assert!(!race.finished);+ for (i, s) in race.seats.iter().enumerate() {+ assert_eq!(s.id, format!("ai-{i}"));+ assert!(s.ai.is_some());+ assert_eq!(s.held, HeldItem::None);+ }+ assert_eq!(race.seat_of("ai-2"), Some(2));+ assert_eq!(race.seat_of("nobody"), None);+}++#[test]+fn new_race_caps_seats_at_max() {+ let many: Vec<String> = (0..20).map(|i| format!("p{i}")).collect();+ let race = Race::new(&many);+ assert_eq!(race.seat_count(), MAX_SEATS);+ assert!(race.seats.iter().all(|s| s.ai.is_none()), "full human grid has no AI");+ // 6 humans leave room for only 2 AI.+ let six: Vec<String> = (0..6).map(|i| format!("p{i}")).collect();+ let race = Race::new(&six);+ assert_eq!(race.seat_count(), MAX_SEATS);+ assert_eq!(race.seats.iter().filter(|s| s.ai.is_some()).count(), 2);+ // 1 human + AI_COUNT.+ let race = Race::new(&["solo".to_string()]);+ assert_eq!(race.seat_count(), 1 + AI_COUNT);+ assert_eq!(race.seats[0].id, "solo");+ assert!(race.seats[0].ai.is_none());+}++#[test]+fn grid_spawn_positions_stagger_by_seat() {+ let race = Race::new(&["a".to_string(), "b".to_string()]);+ for (i, s) in race.seats.iter().enumerate() {+ assert!((s.kart.track_s - (8.0 + i as f32 * 6.0)).abs() < 1e-4, "seat {i} s");+ // Lane alternates -3/+3 (checked via lateral offset at spawn point).+ let p = track::point_at(s.kart.track_s);+ let lat = track::lateral(s.kart.x, s.kart.z, &p);+ assert!((lat.abs() - 3.0).abs() < 1e-3, "seat {i} lane {lat}");+ assert_eq!(s.kart.speed, 0.0);+ }+}++#[test]+fn item_boxes_are_spread_and_alternate_lanes() {+ let race = Race::new(&["a".to_string()]);+ assert_eq!(race.boxes.len(), BOX_COUNT);+ for (i, b) in race.boxes.iter().enumerate() {+ let want_s = track::TRACK_LENGTH * (i as f32 + 0.5) / BOX_COUNT as f32;+ assert!((b.track_s - want_s).abs() < 1e-3);+ assert_eq!(b.lane, if i % 2 == 0 { -4.0 } else { 4.0 });+ assert_eq!(b.respawn_left, 0.0);+ }+ // All boxes start live for the renderer.+ assert_eq!(race.box_positions().len(), BOX_COUNT);+}++#[test]+fn set_input_only_drives_human_seats() {+ let mut race = Race::new(&["a".to_string()]);+ let sample = DriveInput { throttle: 0.7, steering: 0.2, brake: 0.1, drift: true, item: false };+ race.set_input(0, sample);+ assert_eq!(race.seats[0].input.throttle, 0.7);+ // AI seat ignores set_input.+ let ai_seat = race.seats.iter().position(|s| s.ai.is_some()).unwrap();+ race.set_input(ai_seat, sample);+ assert_eq!(race.seats[ai_seat].input.throttle, 0.0);+ // Out-of-range seat is a no-op, not a panic.+ race.set_input(999, sample);+}++#[test]+fn standings_clamp_lap_and_progress() {+ let mut race = Race::new(&["a".to_string()]);+ race.seats[0].kart.lap = 99;+ race.seats[0].kart.track_s = track::TRACK_LENGTH * 3.0;+ let st = race.standings();+ let mine = st.iter().find(|(id, _, _)| id == "a").unwrap();+ assert_eq!(mine.1, RACE_LAPS, "lap clamped for display");+ assert!((mine.2 - 1.0).abs() < 1e-6, "progress clamped to 1");+ // Sorted descending by (lap, progress).+ for w in st.windows(2) {+ assert!((w[0].1, w[0].2) >= (w[1].1, w[1].2));+ }+}++#[test]+fn standings_ties_keep_seat_order() {+ let mut race = Race::new(&["a".to_string(), "b".to_string()]);+ for s in race.seats.iter_mut() {+ s.kart.lap = 1;+ s.kart.track_s = 42.0;+ }+ let st = race.standings();+ let ids: Vec<&str> = st.iter().map(|(id, _, _)| id.as_str()).collect();+ let seat_ids: Vec<&str> = race.seats.iter().map(|s| s.id.as_str()).collect();+ assert_eq!(ids, seat_ids, "stable sort preserves grid order on ties");+}++#[test]+fn empty_race_standings_camera_and_tick() {+ let mut race = Race { seats: Vec::new(), boxes: Vec::new(), shells: Vec::new(), ticks: 0, finished: false, cam_seat: 0 };+ assert!(race.standings().is_empty());+ assert_eq!(race.winner(), None);+ race.finished = true;+ assert_eq!(race.winner(), None, "finished but empty: still no winner");+ let (pos, look) = race.camera();+ assert_eq!(pos, [0.0, 8.0, 20.0]);+ assert_eq!(look, [0.0, 0.0, 0.0]);+ assert!(race.kart_transforms().is_empty());+ assert!(race.shell_positions().is_empty());+ assert!(race.box_positions().is_empty());+ race.tick(1.0 / 60.0);+ assert_eq!(race.ticks, 1);+}++#[test]+fn camera_sits_behind_and_looks_ahead_of_kart() {+ let mut race = Race::new(&["a".to_string()]);+ race.seats[0].kart.x = 50.0;+ race.seats[0].kart.z = 20.0;+ race.seats[0].kart.yaw = 0.0; // faces -Z+ let (pos, look) = race.camera();+ // Behind is +Z of the kart, at CAM_HEIGHT; look is ahead (-Z) at y=1.+ assert!((pos[0] - 50.0).abs() < 1e-4);+ assert!((pos[1] - CAM_HEIGHT).abs() < 1e-4);+ assert!((pos[2] - (20.0 + CAM_DIST)).abs() < 1e-4, "pos {pos:?}");+ assert!((look[0] - 50.0).abs() < 1e-4);+ assert_eq!(look[1], 1.0);+ assert!((look[2] - (20.0 - CAM_LOOK_AHEAD)).abs() < 1e-4);+ // Out-of-range cam_seat falls back to the first seat.+ race.cam_seat = 999;+ let (pos2, _) = race.camera();+ assert_eq!(pos2, pos);+}++#[test]+fn transforms_and_positions_reflect_state() {+ let mut race = Race::new(&["a".to_string()]);+ race.seats[0].kart.x = 3.0;+ race.seats[0].kart.z = -4.0;+ race.seats[0].kart.yaw = 0.5;+ let t = race.kart_transforms();+ assert_eq!(t.len(), race.seat_count());+ assert_eq!(t[0], (3.0, -4.0, 0.5, false));+ assert!(t[1].3, "second seat is AI");+ race.shells.push(Shell { owner: 0, x: 7.0, z: 8.0, yaw: 0.0, life: 3.0, grace: 0.0 });+ assert_eq!(race.shell_positions(), vec![(7.0, 8.0)]);+ // A box on respawn disappears from the renderer list.+ race.boxes[0].respawn_left = 2.0;+ assert_eq!(race.box_positions().len(), BOX_COUNT - 1);+}++#[test]+fn fire_item_variants() {+ let mut race = Race::new(&["a".to_string()]);+ // Empty hands: nothing happens.+ race.fire_item(0);+ assert!(race.shells.is_empty());+ assert_eq!(race.seats[0].kart.boost_left, 0.0);+ // Mushroom -> boost, slot clears.+ race.seats[0].held = HeldItem::Mushroom;+ race.fire_item(0);+ assert_eq!(race.seats[0].kart.boost_left, BOOST_TIME);+ assert_eq!(race.seats[0].held, HeldItem::None);+ // Shell -> projectile 3m ahead of the nose, slot clears.+ race.seats[0].held = HeldItem::Shell;+ race.seats[0].kart.x = 10.0;+ race.seats[0].kart.z = 10.0;+ race.seats[0].kart.yaw = 0.0;+ race.fire_item(0);+ assert_eq!(race.seats[0].held, HeldItem::None);+ assert_eq!(race.shells.len(), 1);+ let sh = &race.shells[0];+ assert_eq!(sh.owner, 0);+ assert!((sh.x - 10.0).abs() < 1e-4);+ assert!((sh.z - 7.0).abs() < 1e-4, "yaw 0 nose is -Z so shell spawns 3m ahead at z-3, got {}", sh.z);+ assert_eq!(sh.life, crate::items::SHELL_LIFE);+ assert_eq!(sh.grace, 0.5);+ // Out-of-range seat is a no-op.+ race.fire_item(999);+ assert_eq!(race.shells.len(), 1);+}++#[test]+fn item_button_is_rising_edge_only() {+ let mut race = Race::new(&["a".to_string()]);+ race.seats[0].held = HeldItem::Mushroom;+ race.set_input(0, drive(true));+ race.tick(1.0 / 60.0);+ assert_eq!(race.seats[0].held, HeldItem::None, "first press fires");+ assert!(race.seats[0].kart.boost_left > 0.0);+ // Holding the button with a fresh mushroom must not refire.+ race.seats[0].held = HeldItem::Mushroom;+ race.seats[0].kart.boost_left = 0.0;+ race.tick(1.0 / 60.0);+ assert_eq!(race.seats[0].held, HeldItem::Mushroom, "held button must not refire");+ assert_eq!(race.seats[0].kart.boost_left, 0.0);+ // Release, then press again: fires.+ race.set_input(0, drive(false));+ race.tick(1.0 / 60.0);+ race.set_input(0, drive(true));+ race.tick(1.0 / 60.0);+ assert_eq!(race.seats[0].held, HeldItem::None);+ assert!(race.seats[0].kart.boost_left > 0.0);+}++#[test]+fn driving_over_a_live_box_deals_an_item() {+ let mut race = Race::new(&["a".to_string()]);+ let b = race.boxes[0].clone();+ let p = track::point_at(b.track_s);+ race.seats[0].kart.x = p.x + p.nx * b.lane;+ race.seats[0].kart.z = p.z + p.nz * b.lane;+ race.seats[0].kart.track_s = b.track_s;+ race.seats[0].kart.speed = 0.0;+ race.tick(1.0 / 60.0);+ assert_ne!(race.seats[0].held, HeldItem::None, "box must deal");+ assert!((race.boxes[0].respawn_left - BOX_RESPAWN).abs() < 1e-4);+ // The same box on cooldown deals nothing to a second kart placed on it.+ let dealt = race.seats[0].held;+ race.seats[0].held = HeldItem::None;+ race.tick(1.0 / 60.0);+ // Kart may have drifted off the box with zero throttle it has not, but+ // cooldown alone must prevent a redeal while it sits there.+ if race.seats[0].held != HeldItem::None {+ // Only acceptable if a different box was hit; box0 must stay on cooldown.+ assert!(race.boxes[0].respawn_left > 0.0);+ }+ let _ = dealt;+}++#[test]+fn tick_clamps_dt_and_counts_ticks() {+ let mut race = Race::new(&["a".to_string()]);+ race.boxes[0].respawn_left = 8.0;+ race.tick(10.0);+ assert_eq!(race.ticks, 1);+ // dt clamped to 0.25: respawn drops by at most a quarter second.+ assert!(race.boxes[0].respawn_left > 7.7, "respawn {}", race.boxes[0].respawn_left);+ race.tick(0.0);+ assert_eq!(race.ticks, 2, "even a zero-dt tick counts");+}++#[test]+fn reaching_race_laps_sets_finished() {+ let mut race = Race::new(&["a".to_string()]);+ race.seats[0].kart.lap = RACE_LAPS;+ race.tick(1.0 / 60.0);+ assert!(race.finished);+ assert!(race.winner().is_some());+}
games/kart/src/main/rust/src/track.rs
diff --git a/games/kart/src/main/rust/src/track.rs b/games/kart/src/main/rust/src/track.rsindex 1eea0e7f8b..63025165ce 100644--- a/games/kart/src/main/rust/src/track.rs+++ b/games/kart/src/main/rust/src/track.rs@@ -111,7 +111,12 @@ pub fn point_at(s: f32) -> TrackPoint { } } -/// Signed lateral offset in metres: negative is left of centre, positive right.+/// Signed lateral offset in metres: positive is left of centre, negative+/// right — i.e. along the point's normal (`(-tz, tx)`, see [`TrackPoint`]).+/// Lane offsets everywhere (`KartBody::spawn`, item boxes, the mesh) are+/// likewise `centre + normal * lane`, so `lateral` of a point placed at+/// lane `L` is exactly `L`; the only production caller, [`on_track`], uses+/// the absolute value. pub fn lateral(x: f32, z: f32, p: &TrackPoint) -> f32 { (x - p.x) * p.nx + (z - p.z) * p.nz }@@ -146,6 +151,8 @@ pub fn wrap_angle(a: f32) -> f32 { v } +#[cfg(test)]+mod track_tests; #[cfg(test)] mod tests { use super::*;
games/kart/src/main/rust/src/track/track_tests.rs
diff --git a/games/kart/src/main/rust/src/track/track_tests.rs b/games/kart/src/main/rust/src/track/track_tests.rsnew file mode 100644index 0000000000..7d340f87eb--- /dev/null+++ b/games/kart/src/main/rust/src/track/track_tests.rs@@ -0,0 +1,173 @@+//! Extra deterministic tests for track geometry (sibling of `track::tests`).+use super::*;+use std::f32::consts::PI;++fn approx(a: f32, b: f32) -> bool {+ (a - b).abs() < 1e-4+}++#[test]+fn wrap_handles_zero_full_lap_and_negative() {+ assert!(approx(wrap(0.0), 0.0));+ assert!(approx(wrap(TRACK_LENGTH), 0.0));+ assert!(approx(wrap(-1.0), TRACK_LENGTH - 1.0));+ assert!(approx(wrap(TRACK_LENGTH + 12.5), 12.5));+ assert!(approx(wrap(-TRACK_LENGTH - 3.0), TRACK_LENGTH - 3.0));+}++#[test]+fn wrap_angle_bounds_and_boundaries() {+ assert!(approx(wrap_angle(0.0), 0.0));+ assert!(approx(wrap_angle(PI), PI));+ assert!(approx(wrap_angle(-PI), PI) || approx(wrap_angle(-PI), -PI));+ assert!(approx(wrap_angle(3.0 * PI), PI) || approx(wrap_angle(3.0 * PI), -PI));+ assert!(approx(wrap_angle(2.0 * PI), 0.0));+ assert!(approx(wrap_angle(-2.0 * PI), 0.0));+ assert!(approx(wrap_angle(PI / 2.0), PI / 2.0));+ assert!(approx(wrap_angle(-PI / 2.0), -PI / 2.0));+ for a in [-100.0f32, -7.3, -3.2, 3.2, 7.3, 100.0, 1000.0] {+ let w = wrap_angle(a);+ assert!((-PI..=PI).contains(&w), "wrap_angle({a})={w}");+ }+ // Wrapping by a full turn is identity.+ assert!(approx(wrap_angle(0.37 + 2.0 * PI), 0.37));+ assert!(approx(wrap_angle(0.37 - 4.0 * PI), 0.37));+}++#[test]+fn advance_zero_full_lap_and_negative() {+ assert!(approx(advance(100.0, 0.0), 100.0));+ assert!(approx(advance(100.0, TRACK_LENGTH), 100.0));+ assert!(approx(advance(10.0, -20.0), TRACK_LENGTH - 10.0));+ assert!(approx(advance(0.0, -0.5), TRACK_LENGTH - 0.5));+ let s = advance(TRACK_LENGTH - 0.25, 0.5);+ assert!(approx(s, 0.25));+}++#[test]+fn point_at_negative_and_over_length_match_wrapped() {+ for s in [0.0f32, 1.0, 77.0, 250.0, 500.0, 776.0] {+ let a = point_at(s - TRACK_LENGTH);+ let b = point_at(s);+ assert!(approx(a.x, b.x) && approx(a.z, b.z), "neg s={s}");+ let c = point_at(s + 2.0 * TRACK_LENGTH);+ assert!(approx(c.x, b.x) && approx(c.z, b.z), "over s={s}");+ // Deterministic: repeated calls agree exactly.+ let d = point_at(s);+ assert_eq!(d.x.to_bits(), b.x.to_bits());+ assert_eq!(d.z.to_bits(), b.z.to_bits());+ }+}++#[test]+fn tangents_and_normals_are_unit_and_orthogonal_everywhere() {+ let mut s = 0.0f32;+ while s < TRACK_LENGTH {+ let p = point_at(s);+ assert!(approx(p.tx.hypot(p.tz), 1.0), "tangent s={s}");+ assert!(approx(p.nx.hypot(p.nz), 1.0), "normal s={s}");+ assert!(approx(p.tx * p.nx + p.tz * p.nz, 0.0), "dot s={s}");+ // Normal is tangent rotated: (-tz, tx) by definition in docs.+ assert!(approx(p.nx, -p.tz) && approx(p.nz, p.tx), "rot s={s}");+ s += 13.7;+ }+}++#[test]+fn joint_positions_are_exact() {+ let cap = PI * RADIUS;+ let cases = [+ (0.0, CAP_CX_FOR_TEST, -RADIUS),+ (STRAIGHT, -CAP_CX_FOR_TEST, -RADIUS),+ (STRAIGHT + cap, -CAP_CX_FOR_TEST, RADIUS),+ (2.0 * STRAIGHT + cap, CAP_CX_FOR_TEST, RADIUS),+ ];+ for (s, x, z) in cases {+ let p = point_at(s);+ assert!(approx(p.x, x) && approx(p.z, z), "s={s} got {},{}", p.x, p.z);+ }+ // Full lap returns to start.+ let p = point_at(TRACK_LENGTH);+ let q = point_at(0.0);+ assert!(approx(p.x, q.x) && approx(p.z, q.z));+}++const CAP_CX_FOR_TEST: f32 = STRAIGHT / 2.0;++#[test]+fn segment_midpoints() {+ let top = point_at(STRAIGHT / 2.0);+ assert!(approx(top.x, 0.0) && approx(top.z, -RADIUS));+ let cap = PI * RADIUS;+ let bottom = point_at(STRAIGHT + cap + STRAIGHT / 2.0);+ assert!(approx(bottom.x, 0.0) && approx(bottom.z, RADIUS));+ // Top straight runs at z=-R for its whole length.+ for s in [0.0f32, 50.0, 199.0] {+ assert!(approx(point_at(s).z, -RADIUS));+ }+}++#[test]+fn lateral_projection_sign_and_magnitude() {+ let p = point_at(40.0);+ assert!(approx(lateral(p.x, p.z, &p), 0.0));+ let along_n = lateral(p.x + p.nx * 5.0, p.z + p.nz * 5.0, &p);+ assert!(approx(along_n, 5.0), "along +n: {along_n}");+ let against_n = lateral(p.x - p.nx * 3.0, p.z - p.nz * 3.0, &p);+ assert!(approx(against_n, -3.0));+ // Moving along tangent does not change lateral offset.+ let along_t = lateral(p.x + p.tx * 20.0, p.z + p.tz * 20.0, &p);+ assert!(approx(along_t, 0.0));+}++#[test]+fn lateral_matches_lane_placement_convention() {+ // Docs: positive lateral is along +normal (left of centre). Every lane+ // placement in the crate is `centre + normal * lane`, so lateral must+ // return that lane verbatim — flipping the sign would break that+ // invariant (on_track itself is sign-insensitive: it uses abs()).+ for s in [10.0f32, 250.0, 450.0, 650.0] {+ let p = point_at(s);+ for lane in [-6.0f32, -3.0, 3.0, 6.0] {+ let got = lateral(p.x + p.nx * lane, p.z + p.nz * lane, &p);+ assert!(approx(got, lane), "s={s} lane={lane} got {got}");+ }+ }+}++#[test]+fn on_track_boundary_is_half_width_plus_kerb() {+ for s in [10.0f32, 250.0, 450.0, 650.0] {+ let p = point_at(s);+ let edge = HALF_WIDTH + 0.5;+ assert!(on_track(p.x + p.nx * edge, p.z + p.nz * edge, &p), "edge s={s}");+ assert!(on_track(p.x - p.nx * edge, p.z - p.nz * edge, &p), "-edge s={s}");+ assert!(!on_track(p.x + p.nx * (edge + 0.01), p.z + p.nz * (edge + 0.01), &p));+ assert!(!on_track(p.x - p.nx * (edge + 1.0), p.z - p.nz * (edge + 1.0), &p));+ }+}++#[test]+fn heading_error_zero_opposite_and_offset() {+ let p = point_at(30.0);+ let yaw = tangent_yaw(&p);+ assert!(approx(heading_error(yaw, &p), 0.0));+ let opp = heading_error(yaw + PI, &p);+ assert!(approx(opp.abs(), PI), "opposite err {opp}");+ // Kart yawed +0.3 from tangent: error is -0.3 (wrapped).+ assert!(approx(heading_error(yaw + 0.3, &p), -0.3));+ assert!(approx(heading_error(yaw - 0.3, &p), 0.3));+}++#[test]+fn successive_samples_have_small_heading_change() {+ let mut prev = point_at(0.0);+ let mut s = 1.0f32;+ while s <= TRACK_LENGTH {+ let p = point_at(s);+ let err = heading_error(tangent_yaw(&prev), &p).abs();+ assert!(err < 0.05, "heading jump {err} at s={s}");+ prev = p;+ s += 1.0;+ }+}