diff --git a/Cargo.lock b/Cargo.lock index 19973ceb..e8a48704 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8103,6 +8103,7 @@ dependencies = [ "bevy", "glam", "recreation_towers", + "recreation_towers_ground", "teleoperation_shared", "visualization_battlefield", "visualization_engine", diff --git a/domains/recreation/README.md b/domains/recreation/README.md index 41692934..84dfa7e1 100644 --- a/domains/recreation/README.md +++ b/domains/recreation/README.md @@ -216,6 +216,51 @@ A person's seat runs advisors too (`advisors::attend`, in the commander app, `-- lookahead by default): the app's ADVISOR panel lists the live proposals, best first, and a click on one, or the key Y for the first, sends that order and queue for that drone. +#### A person flies a unit + +A drone always runs: the basic unit is ArduPilot in AGENT mode. A person can fly one winged drone by +the sticks instead (the quad is the server's and is refused; one pilot to a drone). The seat is +`Join::Unit { team, drone }` (drone from 0); the client sends `ToServer::Sticks { roll, pitch, +throttle, yaw }` (roll and yaw right positive, pitch positive for the stick pulled back, throttle 0 +to 1) at 20 Hz or more. + +- **Take-over.** The server still takes the drone off and puts it on the wing in FBWA with its own + `Preflight` (the pilot's own take-off is later). Then the sticks are the drone's radio channels in + place of the server's, mode switch at FBWA. A pilot who joins after the ground put the drone in AGENT + gets it too: one second after the seat is taken (the ground station is told at once), the mode switch + leaves FBWA for 1.5 s of game time and comes back, which ArduPilot takes as a change. +- **The commander.** Seats that command get `ToSeat::Piloted(Vec)` with each update: the drones + (numbers in the team) a person flies. The station does not put them in AGENT or send plans, but still + hears their telemetry, so they stay on the team's map; orders for them still go to the server. +- **The mission.** The pilot's seat gets `ToSeat::Mission` four times a second: the commander's order, + low flag and queue, as last heard by the drone (they do not change while the drone is out of contact + by `World::in_reach`, the radio rule of `air.rs`, and catch up after), plus what the drone knows + (`EdgeObs`: enemies and towers its camera sees, battery, time out of contact), its velocity, attitude, + the tower names and places, the clock and the outcome. No map, no umpire, no truth. +- **Hand-back.** Sticks silent for 2 s (`STICKS_TIMEOUT`), or the seat gone: the drone is the computer's; + its station switches it to AGENT and it flies its order. Sticks that come back reclaim a free drone. + +```bash +towers_view --fly blue:2 # the cockpit: drone 2 of Blue (names count from 1), --server ADDR +towers_pilot --team blue --drone 2 --after 5 --for 30 # a scripted pilot: a gentle bank, then lets go +``` + +The cockpit shows the drone's nose camera full screen (the engine's FPV view, drawn from the mission's +own place and attitude and the enemies its camera sees: no other drone, and the truth is not read) with +a HUD: speed, height, heading, battery, in contact or out (with the time), enemies in sight, and the +mission (the order with the tower's name, bearing and distance; the queue). Keys: W/S throttle, +Left/Right roll, Up/Down pitch (Up pushes the stick forward: nose down), A/D yaw, Space centres the +sticks. A gamepad is read as mode 2 (right stick roll and pitch, left stick rudder and throttle); a +joystick whose name looks like a radio (TX15, EdgeTX, ...) as AETR channels. The TX15 mapping is the sim's +default axes and has not been tried on a radio here. The window is on screen only with `--fly`. + +The rules are checked by the server's tests with seat clients and no ArduPilot +(`cargo test --release -p recreation_towers_server --bins` and `-p recreation_towers_ground`); they are +not expectations, because a state that no driver of the suite shows breaks the suite's coverage plans. +The game with a scripted pilot on SITL is +[expectations/09-towers/arduplane/02-pilot.expect](../../expectations/09-towers/arduplane/02-pilot.expect), +run by `cargo test --release -p recreation_towers_server --test acceptance`. + The rules and the commander are specified in [expectations/09-towers](../../expectations/09-towers) and run with no window by `cargo test --release -p recreation_towers`; a whole game with ArduPilot, with the fog checked from a seat against a spectator, by diff --git a/domains/recreation/towers/src/seat.rs b/domains/recreation/towers/src/seat.rs index 5a77a12d..97242843 100644 --- a/domains/recreation/towers/src/seat.rs +++ b/domains/recreation/towers/src/seat.rs @@ -9,7 +9,10 @@ //! server tells it only the umpire's word ([`ToSeat::Umpire`]) and what its towers and base see //! ([`ToSeat::Sites`]). Only a spectator gets the whole game ([`ToSeat::Truth`]). -use crate::{Advice, Drone, Game, Order, Outcome, Queued, Rules, Sites, Standing, Team, TeamView, Tower, Umpire}; +use crate::{ + Advice, Drone, EdgeObs, Game, Order, Outcome, Queued, Rules, Sites, Standing, Team, TeamView, Tower, Umpire, +}; +use glam::Vec2; use serde::{Deserialize, Serialize}; /// The game server's port for seats: never a SITL port (those end in 0, 2 or 3). @@ -27,6 +30,10 @@ pub enum Join { Watch(Team), /// Watches the whole game, with no fog. Spectate, + /// Flies one drone of a team (its number in the team, from 0) by the sticks, as the drone's + /// pilot: a winged drone, one pilot at a time. The server still takes the drone off and puts it + /// on the wing; then the sticks are the pilot's. + Unit { team: Team, drone: usize }, } impl Join { @@ -34,9 +41,74 @@ impl Join { pub fn commands(self) -> Option { match self { Join::Command(t) | Join::Compute(t) => Some(t), - Join::Watch(_) | Join::Spectate => None, + Join::Watch(_) | Join::Spectate | Join::Unit { .. } => None, } } + + /// The team and drone the seat flies, for a pilot. + pub fn pilots(self) -> Option<(Team, usize)> { + match self { + Join::Unit { team, drone } => Some((team, drone)), + _ => None, + } + } +} + +/// A pilot's sticks, as a radio sends them: the server's drone takes them as its radio's channels. +/// Roll right and yaw right are positive; pitch is positive for the stick pulled back (nose up), +/// as the elevator of the radio is. Throttle is 0 (down) to 1 (up). A pilot sends them 20 times a +/// second or more: after [`STICKS_TIMEOUT`] s without them the drone is no longer flown by the pilot. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Sticks { + pub roll: f32, + pub pitch: f32, + pub throttle: f32, + pub yaw: f32, +} + +impl Sticks { + /// The sticks of a pilot who lets go: centred, throttle half. + pub const CENTRED: Sticks = Sticks { roll: 0.0, pitch: 0.0, throttle: 0.5, yaw: 0.0 }; + + /// The same, held to what a radio can send. + pub fn clamped(self) -> Sticks { + let c = |x: f32| if x.is_finite() { x.clamp(-1.0, 1.0) } else { 0.0 }; + let throttle = if self.throttle.is_finite() { self.throttle.clamp(0.0, 1.0) } else { 0.0 }; + Sticks { roll: c(self.roll), pitch: c(self.pitch), throttle, yaw: c(self.yaw) } + } +} + +/// The pilot's sticks stopping this long (s of the wall's time) gives the drone back to its computer. +pub const STICKS_TIMEOUT: f32 = 2.0; + +/// What a pilot is shown: the commander's instructions as a mission, and what the drone itself +/// knows. The mission (`order`, `low`, `queue`) is the commander's last word that reached the +/// drone: while the drone is out of contact it does not change, and it catches up when contact +/// returns. The rest is the drone's own: its camera, its battery and the time it has been out of +/// contact. The game does not check that the pilot flies the mission. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Mission { + /// The drone's number in its team. + pub drone: usize, + pub order: Option, + /// The order is flown low, along the lanes. + pub low: bool, + pub queue: Vec, + /// The drone is in contact with its team now (its radio reaches it). + pub in_contact: bool, + /// What the drone knows on board: where it is, what its camera sees, battery, time out of contact. + pub obs: EdgeObs, + /// Its velocity (m/s, north, east): the drone knows how it flies. + pub vel: Vec2, + /// How it sits (body to the world, a quaternion x, y, z, w, in the 3D view's frame: x east, y up, + /// z south): the drone's own attitude, for the pilot's camera. `[0; 4]` when not known. + #[serde(default)] + pub attitude: [f32; 4], + /// The towers, by their number in the game: their names and places (the field is known to all). + pub towers: Vec<(String, Vec2)>, + pub time: f32, + pub time_left: f32, + pub outcome: Option, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -58,6 +130,8 @@ pub enum ToServer { #[serde(default, skip_serializing_if = "Vec::is_empty")] queue: Vec, }, + /// The pilot's sticks, from a seat that is [`Join::Unit`]. + Sticks(Sticks), } /// The whole game, for a spectator. @@ -122,6 +196,12 @@ pub enum ToSeat { Truth(Truth), /// The advisor of the team speaks, to a seat that commands it, when something matters. Advice(Advice), + /// The drones of the team (by number in the team) that a person flies by the sticks now, to a + /// seat that commands: the ground station leaves them alone (it does not put them in AGENT or + /// send them plans), but their telemetry still comes down, so they stay on the map. Often. + Piloted(Vec), + /// To a pilot's seat: its mission, and what its drone knows, often. + Mission(Mission), } /// A message as a line (without its newline). @@ -149,6 +229,26 @@ mod tests { assert_eq!(decode::(&encode(&msg)).unwrap(), msg); } + #[test] + fn a_pilots_seat_and_sticks_survive_the_wire_and_a_pilot_commands_nobody() { + let join = Join::Unit { team: Team::Blue, drone: 1 }; + assert_eq!(decode::(&encode(&ToServer::Join(join))).unwrap(), ToServer::Join(join)); + assert_eq!((join.commands(), join.pilots()), (None, Some((Team::Blue, 1)))); + assert_eq!(Join::Command(Team::Red).pilots(), None); + let sticks = ToServer::Sticks(Sticks { roll: 0.25, pitch: -0.5, throttle: 0.75, yaw: 1.0 }); + assert_eq!(decode::(&encode(&sticks)).unwrap(), sticks); + let piloted = ToSeat::Piloted(vec![0, 2]); + assert_eq!(decode::(&encode(&piloted)).unwrap(), piloted); + } + + #[test] + fn sticks_are_held_to_what_a_radio_sends() { + let wild = Sticks { roll: 3.0, pitch: f32::NAN, throttle: -2.0, yaw: -9.0 }.clamped(); + assert_eq!(wild, Sticks { roll: 1.0, pitch: 0.0, throttle: 0.0, yaw: -1.0 }); + assert_eq!(Sticks { throttle: 7.0, ..Sticks::CENTRED }.clamped().throttle, 1.0); + assert_eq!(Sticks::CENTRED.clamped(), Sticks::CENTRED); + } + #[test] fn an_order_from_an_old_seat_has_no_queue_and_keeps_its_standing_order() { let old = r#"{"Order":{"drone":0,"order":"Hold","standing":{"after":5.0,"then":"Home"}}}"#; diff --git a/domains/recreation/towers_ground/Cargo.toml b/domains/recreation/towers_ground/Cargo.toml index 5e43db42..323627a3 100644 --- a/domains/recreation/towers_ground/Cargo.toml +++ b/domains/recreation/towers_ground/Cargo.toml @@ -8,6 +8,10 @@ description = "Recreation domain: the ground of Towers: the MAVLink side of a te name = "towers_advisor" path = "src/bin/towers_advisor.rs" +[[bin]] +name = "towers_pilot" +path = "src/bin/towers_pilot.rs" + [[bin]] name = "towers_commander" path = "src/bin/towers_commander.rs" diff --git a/domains/recreation/towers_ground/src/bin/towers_pilot.rs b/domains/recreation/towers_ground/src/bin/towers_pilot.rs new file mode 100644 index 00000000..8a34791c --- /dev/null +++ b/domains/recreation/towers_ground/src/bin/towers_pilot.rs @@ -0,0 +1,41 @@ +//! A scripted pilot for one drone of Towers, with no person at the sticks: +//! `towers_pilot --team blue|red --drone N [--host 127.0.0.1] [--port 5955] [--after S] [--for S] +//! [--roll R]`. It takes the seat of drone `N` of the team (from 1: Blue2 is `--team blue --drone 2`), +//! waits `--after` seconds of wall time before it does (0), flies a gentle bank (`--roll`, 0.3) for +//! `--for` seconds (30) and lets go: the drone is its computer's again. It prints what its seat +//! showed it. See `recreation_towers_ground::pilot`. + +use recreation_towers::Team; +use recreation_towers_ground::pilot::{self, Script}; +use std::sync::atomic::AtomicBool; +use std::time::Duration; + +fn main() { + let args: Vec = std::env::args().collect(); + let arg = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned(); + let secs = |name: &str, default: f32| arg(name).and_then(|s| s.parse().ok()).unwrap_or(default); + let team = match arg("--team").as_deref() { + Some("blue") => Team::Blue, + Some("red") => Team::Red, + _ => usage(), + }; + let Some(drone) = arg("--drone").and_then(|d| d.parse::().ok()).filter(|&d| d >= 1) else { usage() }; + let host = arg("--host").unwrap_or_else(|| "127.0.0.1".into()); + let port: u16 = arg("--port").and_then(|p| p.parse().ok()).unwrap_or(recreation_towers::seat::PORT); + let script = Script { roll: secs("--roll", 0.3), ..Script::bank() }; + std::thread::sleep(Duration::from_secs_f32(secs("--after", 0.0))); + let flown = pilot::fly( + &format!("{host}:{port}"), + team, + drone - 1, + &script, + Duration::from_secs_f32(secs("--for", 30.0)), + &AtomicBool::new(false), + ); + println!("{flown:#?}"); +} + +fn usage() -> ! { + eprintln!("usage: towers_pilot --team blue|red --drone N [--host H] [--port P] [--after S] [--for S] [--roll R]"); + std::process::exit(2); +} diff --git a/domains/recreation/towers_ground/src/lib.rs b/domains/recreation/towers_ground/src/lib.rs index bc9258a1..f780b9a7 100644 --- a/domains/recreation/towers_ground/src/lib.rs +++ b/domains/recreation/towers_ground/src/lib.rs @@ -15,6 +15,7 @@ pub mod advisors; pub mod claude; pub mod commander; pub mod map; +pub mod pilot; pub mod seat; pub mod station; diff --git a/domains/recreation/towers_ground/src/pilot.rs b/domains/recreation/towers_ground/src/pilot.rs new file mode 100644 index 00000000..809e8278 --- /dev/null +++ b/domains/recreation/towers_ground/src/pilot.rs @@ -0,0 +1,196 @@ +//! A scripted pilot: a client that takes the seat of one drone ([`Join::Unit`]) and flies it by +//! the sticks, with no person, so that the whole path from sticks to drone and from commander to +//! mission is tested. It is a pilot with one idea: hold a gentle bank, and keep the height and the +//! speed that a drone needs to stay in the air. It reads only what a pilot is shown (the +//! [`Mission`]), as a person does, and writes down what the seat gave it ([`Flown`]). + +use crate::seat::{Seat, Status}; +use recreation_towers::seat::{Join, Mission, Sticks}; +use recreation_towers::{Order, Queued, Team}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +/// How often the sticks are sent (Hz): the server wants 20 or more. +pub const STICKS_HZ: f32 = 25.0; + +/// What the scripted pilot does with the sticks. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Script { + /// The roll stick held (-1 to 1): a bank, and so a turn. + pub roll: f32, + /// The height it keeps (m) and the speed (m/s). + pub height: f32, + pub speed: f32, +} + +impl Script { + /// A gentle bank to the right at 60 m and 20 m/s. + pub fn bank() -> Script { + Script { roll: 0.3, height: 60.0, speed: 20.0 } + } + + /// The sticks for what the pilot is shown: the roll stick as the script holds it, the elevator + /// to climb to its height and the throttle to hold its speed. + pub fn sticks(&self, m: &Mission) -> Sticks { + let speed = m.vel.length(); + // Pulled back (positive) to climb; not more than a gentle climb or dive. + let pitch = (0.012 * (self.height - m.obs.alt)).clamp(-0.25, 0.3); + let throttle = (0.6 + 0.04 * (self.speed - speed)).clamp(0.3, 1.0); + Sticks { roll: self.roll, pitch, throttle, yaw: 0.0 } + } +} + +/// What the scripted pilot saw and did. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Flown { + /// Why the seat was refused, if it was. + pub refused: Option, + /// How many sticks were sent, and how many different missions the seat showed. + pub sticks_sent: usize, + pub missions: usize, + /// The distinct orders of the mission, in the order they came. + pub orders: Vec>, + /// The queue of the last mission. + pub queue: Vec, + /// How far the drone's course turned in all (degrees, right is positive), from its velocity. + pub turned: f32, + /// Missions shown out of contact, and how many of those differed from the last one shown in contact. + pub dark: usize, + pub changed_in_the_dark: usize, + /// The towers the mission is about, as the screen would say: name, then bearing and distance. + pub target: Option, + /// The game's time at the last mission, and whether the game was over. + pub time: f32, + pub over: bool, +} + +/// Takes the seat of drone `drone` (from 0) of `team` on the server at `addr`, flies `script` for +/// `for_` (wall time), and lets go. Stops early when `stop` is set or the game is over. Waits up +/// to a minute for the seat. +pub fn fly(addr: &str, team: Team, drone: usize, script: &Script, for_: Duration, stop: &AtomicBool) -> Flown { + let seat = Seat::connect(addr, Join::Unit { team, drone }); + let mut flown = Flown::default(); + let wait = Instant::now() + Duration::from_secs(60); + loop { + match seat.state().status.clone() { + Status::Seated(_) => break, + Status::Refused(why) => { + flown.refused = Some(why); + seat.stop(); + return flown; + } + Status::Connecting => {} + } + if Instant::now() > wait || stop.load(Ordering::SeqCst) { + flown.refused = Some("no seat in time".into()); + seat.stop(); + return flown; + } + std::thread::sleep(Duration::from_millis(50)); + } + let end = Instant::now() + for_; + let (mut last_time, mut course, mut last_in_contact) = (f32::NEG_INFINITY, None::, None::); + while Instant::now() < end && !stop.load(Ordering::SeqCst) { + let mission = seat.state().mission.clone(); + let sticks = mission.as_ref().map_or(Sticks::CENTRED, |m| script.sticks(m)); + seat.sticks(sticks); + flown.sticks_sent += 1; + if let Some(m) = mission.filter(|m| m.time != last_time || flown.missions == 0) { + last_time = m.time; + flown.missions += 1; + flown.time = m.time; + flown.over = m.outcome.is_some(); + if flown.orders.last() != Some(&m.order) { + flown.orders.push(m.order); + } + flown.queue = m.queue.clone(); + flown.target = target_text(&m); + if m.in_contact { + last_in_contact = Some(m.clone()); + } else if let Some(shown) = &last_in_contact { + flown.dark += 1; + if (shown.order, &shown.queue, shown.low) != (m.order, &m.queue, m.low) { + flown.changed_in_the_dark += 1; + } + } + if m.vel.length() > 5.0 { + let now = m.vel.y.atan2(m.vel.x).to_degrees(); + if let Some(before) = course { + flown.turned += (now - before + 540.0).rem_euclid(360.0) - 180.0; + } + course = Some(now); + } + if flown.over { + break; + } + } + std::thread::sleep(Duration::from_secs_f32(1.0 / STICKS_HZ)); + } + // Let go: the seat goes, and the drone is its computer's again. + seat.stop(); + flown +} + +/// What the mission says to fly to, as a screen says it: "take the west tower, 310 m at 120 degrees". +pub fn target_text(m: &Mission) -> Option { + let (what, at) = match m.order? { + Order::Take(t) => { + let (name, at) = m.towers.get(t)?; + (format!("take the {name} tower"), *at) + } + Order::Goto(p) => ("go to a point".to_string(), p), + Order::Circle(p, _) => ("circle a point".to_string(), p), + Order::Hold => return Some("hold".into()), + Order::Home => return Some("go home".into()), + }; + let to = at - m.obs.at; + // The bearing clockwise from north: the field is north, east. + let bearing = to.y.atan2(to.x).to_degrees().rem_euclid(360.0); + Some(format!("{what}, {:.0} m at {bearing:.0} degrees", to.length())) +} + +#[cfg(test)] +mod tests { + use super::*; + use glam::Vec2; + use recreation_towers::EdgeObs; + + fn mission(at: Vec2, alt: f32, vel: Vec2, order: Option) -> Mission { + Mission { + drone: 1, + order, + low: false, + queue: vec![], + in_contact: true, + obs: EdgeObs { at, alt, enemies: vec![], towers: vec![], battery: None, silent: 0.0 }, + vel, + attitude: [0.0; 4], + towers: vec![("Blue home".into(), Vec2::new(-430.0, 0.0)), ("west".into(), Vec2::new(0.0, -300.0))], + time: 0.0, + time_left: 600.0, + outcome: None, + } + } + + #[test] + fn the_scripted_pilot_banks_climbs_when_low_and_speeds_up_when_slow() { + let script = Script::bank(); + let low_and_slow = script.sticks(&mission(Vec2::ZERO, 20.0, Vec2::new(0.0, 12.0), None)); + assert_eq!(low_and_slow.roll, 0.3); + assert!(low_and_slow.pitch > 0.2, "pulled back to climb"); + assert!(low_and_slow.throttle > 0.8); + let high_and_fast = script.sticks(&mission(Vec2::ZERO, 90.0, Vec2::new(0.0, 28.0), None)); + assert!(high_and_fast.pitch < 0.0, "forward to come down"); + assert!(high_and_fast.throttle < 0.4); + } + + #[test] + fn the_target_is_said_with_its_bearing_and_distance() { + let m = mission(Vec2::ZERO, 50.0, Vec2::ZERO, Some(Order::Take(1))); + assert_eq!(target_text(&m).unwrap(), "take the west tower, 300 m at 270 degrees"); + let home = mission(Vec2::new(-530.0, 0.0), 50.0, Vec2::ZERO, Some(Order::Take(0))); + assert_eq!(target_text(&home).unwrap(), "take the Blue home tower, 100 m at 0 degrees"); + assert_eq!(target_text(&mission(Vec2::ZERO, 0.0, Vec2::ZERO, Some(Order::Home))).unwrap(), "go home"); + assert_eq!(target_text(&mission(Vec2::ZERO, 0.0, Vec2::ZERO, None)), None); + } +} diff --git a/domains/recreation/towers_ground/src/seat.rs b/domains/recreation/towers_ground/src/seat.rs index a63bf264..927ffd74 100644 --- a/domains/recreation/towers_ground/src/seat.rs +++ b/domains/recreation/towers_ground/src/seat.rs @@ -2,7 +2,7 @@ //! map the server sent and sends the orders the commander gives. If the connection is lost, or //! the server is not up yet, it tries again. -use recreation_towers::seat::{self, Join, ToSeat, ToServer}; +use recreation_towers::seat::{self, Join, Mission, Sticks, ToSeat, ToServer}; use recreation_towers::{Advice, Order, Proposal, Rules, Sites, TeamView, Umpire}; use std::io::{BufRead, BufReader, Write}; use std::net::TcpStream; @@ -38,6 +38,11 @@ pub struct State { /// What the advisors beside the seat propose now (advisors.rs: `attend`), each good until its /// own game time. The app lists them and `Seat::accept` takes one. pub proposals: Vec, + /// The drones of the team (by number in the team) that a person flies by the sticks now: the + /// station leaves them alone (station.rs). Told to a seat that commands. + pub piloted: Vec, + /// For a pilot's seat: the mission and what the drone knows, as the server last said. + pub mission: Option, } /// How many pieces of advice the seat keeps. @@ -75,6 +80,8 @@ impl Seat { orders: vec![], advice: vec![], proposals: vec![], + piloted: vec![], + mission: None, })), orders: Mutex::new(tx), generation: Arc::new(AtomicU64::new(0)), @@ -113,6 +120,12 @@ impl Seat { let _ = self.orders.lock().unwrap().send(ToServer::Order { drone, order, low, standing: None, queue }); } + /// A pilot's seat: sends the sticks (20 times a second or more, or the server gives the drone + /// back to its computer). + pub fn sticks(&self, sticks: Sticks) { + let _ = self.orders.lock().unwrap().send(ToServer::Sticks(sticks)); + } + /// Puts proposals among the live ones, as if an advisor had just sent them. pub fn offer(&self, proposals: impl IntoIterator) { self.state().proposals.extend(proposals); @@ -167,6 +180,8 @@ impl Seat { orders: vec![], advice: vec![], proposals: vec![], + piloted: vec![], + mission: None, }; let (tx, rx) = channel(); *self.orders.lock().unwrap() = tx; @@ -224,6 +239,8 @@ fn run(addr: &str, join: Join, state: &Mutex, orders: Receiver, ToSeat::Sites(sites) => s.sites = Some(sites), ToSeat::Orders(orders) => s.orders = orders, ToSeat::Truth(_) => {} + ToSeat::Piloted(p) => s.piloted = p, + ToSeat::Mission(m) => s.mission = Some(m), ToSeat::Advice(a) => { s.advice.push((a, Instant::now())); let extra = s.advice.len().saturating_sub(ADVICE_KEPT); diff --git a/domains/recreation/towers_ground/src/station.rs b/domains/recreation/towers_ground/src/station.rs index b7d2e95b..e31b6ca4 100644 --- a/domains/recreation/towers_ground/src/station.rs +++ b/domains/recreation/towers_ground/src/station.rs @@ -75,6 +75,11 @@ pub struct Tally { pub taken: [AtomicUsize; 2], /// A line about each drone of the game, by number in the game. pub lines: Mutex>, + /// Looks of a station at a drone that a person flies: how many had its telemetry (a report + /// under 3 s old: it is on the team's map), and how many found it in AGENT mode more than 5 s + /// (wall) after the pilot took it (it should never be). By team. + pub piloted_mapped: [AtomicUsize; 2], + pub piloted_in_agent: [AtomicUsize; 2], /// Warnings of the stations, by team. pub warnings: Mutex<[Vec; 2]>, } @@ -92,6 +97,14 @@ impl Tally { self.taken.iter().map(|n| n.load(Ordering::SeqCst)).sum() } + pub fn piloted_mapped(&self) -> usize { + self.piloted_mapped.iter().map(|n| n.load(Ordering::SeqCst)).sum() + } + + pub fn piloted_in_agent(&self) -> usize { + self.piloted_in_agent.iter().map(|n| n.load(Ordering::SeqCst)).sum() + } + pub fn refused(&self) -> usize { self.refused.iter().map(|n| n.load(Ordering::SeqCst)).sum() } @@ -119,6 +132,22 @@ struct Flying { first: usize, clock: Clock, home: (f64, f64, f32), + /// Since when a person has flown each drone of the team (wall time). + piloted_since: Vec>, +} + +/// Whether the ground flies a drone: it has taken off and is past the transition. A drone that a +/// person flies is left alone whatever its mode (the ground does not put it in AGENT or send it +/// plans) and its telemetry still comes down. In FBWA with the transition done (fast enough to +/// fly), or already in AGENT or QLOITER: AGENT asked for in the middle of the transition stalls the drone. +fn on_the_wing(piloted: bool, up: bool, mode: Option, speed: f32) -> bool { + !piloted + && up + && match mode { + Some(FBWA_MODE) => speed >= WING_SPEED, + Some(m) => [AGENT_MODE, QLOITER_MODE].contains(&m), + None => false, + } } fn run(seat: &Seat, host: &str, tally: Option<&Tally>) { @@ -129,9 +158,9 @@ fn run(seat: &Seat, host: &str, tally: Option<&Tally>) { if seat.stopped() { return; } - let (status, rules, umpire, sites, air, orders) = { + let (status, rules, umpire, sites, air, orders, piloted) = { let s = seat.state(); - (s.status.clone(), s.rules, s.umpire, s.sites.clone(), s.air.clone(), s.orders.clone()) + (s.status.clone(), s.rules, s.umpire, s.sites.clone(), s.air.clone(), s.orders.clone(), s.piloted.clone()) }; let (Status::Seated(join), Some(rules), Some(umpire), Some(sites)) = (status, rules, umpire, sites) else { flying = None; @@ -166,6 +195,7 @@ fn run(seat: &Seat, host: &str, tally: Option<&Tally>) { first, clock: Clock::new(), home: sitl_home(), + piloted_since: vec![None; n], }); } let f = flying.as_mut().expect("a ground"); @@ -201,6 +231,22 @@ fn run(seat: &Seat, host: &str, tally: Option<&Tally>) { })); } let view = map::build(&umpire, &sites, &own, &seen, &orders, &f.rules); + for (k, report) in own.iter().enumerate() { + if !piloted.contains(&k) { + f.piloted_since[k] = None; + continue; + } + let since = *f.piloted_since[k].get_or_insert_with(Instant::now); + if let Some(t) = tally { + let ti = team.index(); + if report.as_ref().is_some_and(|r| r.age < 3.0) { + t.piloted_mapped[ti].fetch_add(1, Ordering::SeqCst); + } + if since.elapsed() > Duration::from_secs(5) && f.ground.mode_of(k) == Some(AGENT_MODE) { + t.piloted_in_agent[ti].fetch_add(1, Ordering::SeqCst); + } + } + } // The picture the ground plans from is the map: the drones where the team has them. for d in &view.drones { let g = &mut f.game.drones[f.first + d.k]; @@ -224,15 +270,7 @@ fn run(seat: &Seat, host: &str, tally: Option<&Tally>) { .map(|i| { let Some(k) = i.checked_sub(f.first).filter(|&k| k < n) else { return false }; let d = &view.drones[k]; - // On the wing: in FBWA with the transition done (fast enough to fly), or already in - // AGENT or QLOITER. AGENT asked for in the middle of the transition stalls the drone. - let mode = f.ground.mode_of(k); - let up = d.phase == Phase::Flying; - up && match mode { - Some(FBWA_MODE) => d.vel.length() >= WING_SPEED, - Some(m) => [AGENT_MODE, QLOITER_MODE].contains(&m), - None => false, - } + on_the_wing(piloted.contains(&k), d.phase == Phase::Flying, f.ground.mode_of(k), d.vel.length()) }) .collect(); let situation = Situation { @@ -255,7 +293,8 @@ fn run(seat: &Seat, host: &str, tally: Option<&Tally>) { let mut lines = t.lines.lock().unwrap(); lines.resize(2 * n, String::new()); for k in 0..n { - lines[f.first + k] = f.ground.describe(f.first + k); + lines[f.first + k] = + f.ground.describe(f.first + k) + if piloted.contains(&k) { " [PILOTED]" } else { "" }; } t.warnings.lock().unwrap()[ti] = f.ground.verdict(); } @@ -263,3 +302,23 @@ fn run(seat: &Seat, host: &str, tally: Option<&Tally>) { seat.state().view = Some(view); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_station_leaves_a_drone_that_a_person_flies_alone_in_any_mode() { + for mode in [Some(FBWA_MODE), Some(AGENT_MODE), Some(QLOITER_MODE), None] { + assert!(!on_the_wing(true, true, mode, 25.0), "{mode:?}"); + } + } + + #[test] + fn the_station_takes_a_drone_when_it_is_past_the_transition_and_the_pilot_has_gone() { + assert!(on_the_wing(false, true, Some(FBWA_MODE), 20.0), "fast in FBWA"); + assert!(!on_the_wing(false, true, Some(FBWA_MODE), 5.0), "still in the transition"); + assert!(on_the_wing(false, true, Some(AGENT_MODE), 5.0)); + assert!(!on_the_wing(false, false, Some(AGENT_MODE), 20.0), "on the ground"); + } +} diff --git a/domains/recreation/towers_ground/tests/pilot.rs b/domains/recreation/towers_ground/tests/pilot.rs new file mode 100644 index 00000000..ab98c451 --- /dev/null +++ b/domains/recreation/towers_ground/tests/pilot.rs @@ -0,0 +1,118 @@ +//! A scripted pilot against a fake game server that speaks only the seat protocol (no SITL): it takes +//! the seat of one drone, sends its sticks at 20 Hz or more, reads the mission, and lets go. A seat +//! that commands, on the same fake, learns which drones a person flies. + +use glam::Vec2; +use recreation_towers::seat::{self, Join, Mission, Sticks, ToSeat, ToServer}; +use recreation_towers::{EdgeObs, Order, Queued, Rules, Team}; +use recreation_towers_ground::pilot::{self, Script}; +use recreation_towers_ground::seat::{Seat, Status}; +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpListener; +use std::sync::atomic::AtomicBool; +use std::sync::mpsc::channel; +use std::time::{Duration, Instant}; + +fn mission(time: f32, order: Order, in_contact: bool, course: f32) -> Mission { + let v = Vec2::from_angle((90.0 - course).to_radians()) * 20.0; + Mission { + drone: 1, + order: Some(order), + low: false, + queue: vec![Queued::done(Order::Home)], + in_contact, + obs: EdgeObs { at: Vec2::ZERO, alt: 30.0, enemies: vec![], towers: vec![], battery: None, silent: 0.0 }, + // The velocity is (north, east): a course of 90 degrees is due east. + vel: Vec2::new(v.y, v.x), + attitude: [0.0, 0.0, 0.0, 1.0], + towers: vec![("west".into(), Vec2::new(0.0, -300.0)), ("east".into(), Vec2::new(0.0, 300.0))], + time, + time_left: 600.0 - time, + outcome: None, + } +} + +#[test] +fn a_scripted_pilot_sends_sticks_at_20_hz_reads_the_mission_and_turns_with_its_bank() { + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = format!("127.0.0.1:{}", server.local_addr().unwrap().port()); + let (tx, sticks) = channel::(); + std::thread::spawn(move || { + let (stream, _) = server.accept().unwrap(); + let mut out = stream.try_clone().unwrap(); + let mut lines = BufReader::new(stream).lines().map_while(Result::ok); + let ToServer::Join(join) = seat::decode(&lines.next().unwrap()).unwrap() else { panic!("not a join") }; + assert_eq!(join, Join::Unit { team: Team::Blue, drone: 1 }); + writeln!(out, "{}", seat::encode(&ToSeat::Welcome { join, rules: Rules::default(), air: vec![] })).unwrap(); + // The mission, 10 a second: the drone turns right 5 degrees each time, and its radio is cut + // in the middle; the commander's order changes meanwhile, and the screen should not. + let mut writer = out.try_clone().unwrap(); + std::thread::spawn(move || { + for k in 0..40 { + let (order, dark) = match k { + 0..=14 => (Order::Take(0), false), + 15..=29 => (Order::Take(1), true), + _ => (Order::Take(1), false), + }; + let shown = if (15..30).contains(&k) { Order::Take(0) } else { order }; + let m = mission(k as f32, shown, !dark, 5.0 * k as f32); + if writeln!(writer, "{}", seat::encode(&ToSeat::Mission(m))).is_err() { + return; + } + std::thread::sleep(Duration::from_millis(100)); + } + }); + for line in lines { + if let Ok(ToServer::Sticks(s)) = seat::decode(&line) { + let _ = tx.send(s); + } + } + }); + let script = Script::bank(); + let started = Instant::now(); + let flown = pilot::fly(&addr, Team::Blue, 1, &script, Duration::from_millis(4200), &AtomicBool::new(false)); + let took = started.elapsed().as_secs_f32(); + assert_eq!(flown.refused, None); + let sent: Vec = sticks.try_iter().collect(); + assert!(sent.len() as f32 / took >= 20.0, "{} sticks in {took:.1} s: at least 20 a second", sent.len()); + assert!(sent.iter().any(|s| s.roll == script.roll), "the script's bank reached the seat"); + assert!(flown.missions >= 30, "{} missions", flown.missions); + assert_eq!(flown.orders, vec![Some(Order::Take(0)), Some(Order::Take(1))]); + assert_eq!(flown.queue, vec![Queued::done(Order::Home)]); + assert!(flown.turned > 150.0, "turned {} degrees", flown.turned); + assert_eq!(flown.target.as_deref(), Some("take the east tower, 300 m at 90 degrees")); + assert!(flown.dark >= 10, "{} missions in the dark", flown.dark); + assert_eq!(flown.changed_in_the_dark, 0, "the mission did not change in the dark"); +} + +#[test] +fn a_pilot_that_is_refused_says_why_and_a_seat_that_commands_learns_the_piloted_drones() { + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = format!("127.0.0.1:{}", server.local_addr().unwrap().port()); + std::thread::spawn(move || { + // The first seat is refused, the second is a commander and is told of a pilot. + let (stream, _) = server.accept().unwrap(); + let mut out = stream.try_clone().unwrap(); + let _ = BufReader::new(stream).lines().next(); + writeln!(out, "{}", seat::encode(&ToSeat::Refused("Blue2 has its pilot".into()))).unwrap(); + let (stream, _) = server.accept().unwrap(); + let mut out = stream.try_clone().unwrap(); + let mut lines = BufReader::new(stream).lines(); + let _ = lines.next(); + let join = Join::Command(Team::Blue); + writeln!(out, "{}", seat::encode(&ToSeat::Welcome { join, rules: Rules::default(), air: vec![] })).unwrap(); + writeln!(out, "{}", seat::encode(&ToSeat::Piloted(vec![1, 3]))).unwrap(); + for _ in lines {} + }); + let flown = pilot::fly(&addr, Team::Blue, 1, &Script::bank(), Duration::from_millis(300), &AtomicBool::new(false)); + assert_eq!(flown.refused.as_deref(), Some("Blue2 has its pilot")); + assert_eq!(flown.sticks_sent, 0); + let seat = Seat::connect(&addr, Join::Command(Team::Blue)); + let end = Instant::now() + Duration::from_secs(5); + while seat.state().piloted != vec![1, 3] { + assert!(Instant::now() < end, "the seat was never told: {:?}", seat.state().status); + std::thread::sleep(Duration::from_millis(20)); + } + assert!(matches!(seat.state().status, Status::Seated(Join::Command(Team::Blue)))); + seat.stop(); +} diff --git a/domains/recreation/towers_server/src/main.rs b/domains/recreation/towers_server/src/main.rs index d09186de..55b51c10 100644 --- a/domains/recreation/towers_server/src/main.rs +++ b/domains/recreation/towers_server/src/main.rs @@ -25,6 +25,10 @@ //! that dies, hangs or writes nonsense is dropped with a line in the log, and the game goes on. A //! person's seat runs its own advisors in the commander app. //! +//! A person can fly one winged drone by the sticks (`Join::Unit`, see seats.rs and the README): the +//! server takes it off as always, the pilot's sticks become its radio, the team's station leaves it +//! alone, and the commander's order is the pilot's mission. Sticks silent for 2 s hand it back. +//! //! A seat changes hands during the game. A person who joins a team that a computer commands takes //! the seat (the computer is relieved; the person's seat starts with the orders the drones have). When //! a person leaves, the seat is free; a second later, with `--on-leave computer` (the default), a @@ -365,6 +369,7 @@ fn main() { // Each drone's physics moves it on its own: look again, so that every map is of this // moment, the moment the spectator gets. w.game.look(); + w.expire_pilots(); seats.send(&w); } let mut w = world.lock().unwrap(); @@ -425,6 +430,8 @@ fn main() { println!("RESULT in_agent={in_agent}"); println!("RESULT refused={refused}"); println!("RESULT crashes={}", w.crashes); + println!("RESULT piloted_mapped={}", tally.piloted_mapped()); + println!("RESULT piloted_in_agent={}", tally.piloted_in_agent()); println!("RESULT proposals={}", tally.proposals()); println!("RESULT proposals_taken={}", tally.taken()); println!("RESULT taken_blue={}", w.taken[0]); diff --git a/domains/recreation/towers_server/src/seats.rs b/domains/recreation/towers_server/src/seats.rs index 35a14d54..2be10c35 100644 --- a/domains/recreation/towers_server/src/seats.rs +++ b/domains/recreation/towers_server/src/seats.rs @@ -3,6 +3,12 @@ //! may watch a team or the whole game. Each gets what it may know, from the same moment of the game, //! four times a second. //! +//! A pilot's seat (`Join::Unit`) is not a seat of a team: it flies one winged drone by the sticks it +//! sends (`ToServer::Sticks`), and gets what that drone itself knows (`ToSeat::Mission`), nothing +//! of the team's map or the truth. The seats that command are told which drones are flown by a person +//! (`ToSeat::Piloted`), so that the team's ground station leaves them alone. When the pilot's +//! sticks stop for `STICKS_TIMEOUT` s, or the seat goes, the drone is the computer's again. +//! //! A seat changes hands during a game. A person who joins a team that a computer commands takes the //! seat: the computer is told it is relieved and its connection is closed. When a person's client //! leaves, the seat is free; if it is still free after a grace time, the server has a computer @@ -116,9 +122,16 @@ impl Seats { let mut truth = Truth::of(game); truth.attitudes = world.planes.iter().map(|p| p.rot.to_array()).collect(); let truth = seat::encode(&ToSeat::Truth(truth)); + let piloted = [Team::Blue, Team::Red].map(|t| seat::encode(&ToSeat::Piloted(world.piloted(t)))); self.clients.lock().unwrap().retain_mut(|c| match c.join { Join::Command(t) | Join::Compute(t) => { - writeln!(c.stream, "{umpire}").is_ok() && writeln!(c.stream, "{}", sites[t.index()]).is_ok() + writeln!(c.stream, "{umpire}").is_ok() + && writeln!(c.stream, "{}", sites[t.index()]).is_ok() + && writeln!(c.stream, "{}", piloted[t.index()]).is_ok() + } + Join::Unit { team, drone } => { + let mission = seat::encode(&ToSeat::Mission(world.mission(game.drone(team, drone)))); + writeln!(c.stream, "{mission}").is_ok() } Join::Watch(t) => writeln!(c.stream, "{}", views[t.index()]).is_ok(), Join::Spectate => writeln!(c.stream, "{truth}").is_ok(), @@ -126,6 +139,45 @@ impl Seats { } } +/// A pilot's seat: it flies drone `drone` of `team` by its sticks until it goes. +fn pilot(mut out: TcpStream, lines: impl Iterator, team: Team, drone: usize, shared: Shared) { + let Shared { clients, world, next_id, .. } = shared; + let id = next_id.fetch_add(1, Ordering::SeqCst); + let (rules, i) = { + let mut w = world.lock().unwrap(); + let rules = w.game.rules; + if drone >= rules.drones { + let why = format!("{team:?} has no drone {}", drone + 1); + let _ = writeln!(out, "{}", seat::encode(&ToSeat::Refused(why))); + return; + } + let i = w.game.drone(team, drone); + if let Err(why) = w.claim_pilot(i, id) { + let _ = writeln!(out, "{}", seat::encode(&ToSeat::Refused(why))); + return; + } + (rules, i) + }; + let join = Join::Unit { team, drone }; + let welcome = seat::encode(&ToSeat::Welcome { join, rules, air: vec![] }); + let Ok(stream) = out.try_clone() else { + world.lock().unwrap().release_pilot(i, id); + return; + }; + if writeln!(out, "{welcome}").is_err() { + world.lock().unwrap().release_pilot(i, id); + return; + } + clients.lock().unwrap().push(Client { id, join, stream }); + for line in lines { + if let Ok(ToServer::Sticks(sticks)) = seat::decode::(&line) { + world.lock().unwrap().fly(i, id, sticks); + } + } + clients.lock().unwrap().retain(|c| c.id != id); + world.lock().unwrap().release_pilot(i, id); +} + /// One seat's connection: what it is, then its orders. fn seat(stream: TcpStream, shared: Shared) { let Shared { clients, world, air, free, next_id } = shared; @@ -136,6 +188,9 @@ fn seat(stream: TcpStream, shared: Shared) { return; }; let ToServer::Join(join) = join else { return }; + if let Join::Unit { team, drone } = join { + return pilot(out, lines, team, drone, Shared { clients, world, air, free, next_id }); + } let (rules, told): (Rules, Vec<_>) = { let w = world.lock().unwrap(); (w.game.rules, w.told.clone()) @@ -212,7 +267,8 @@ fn seat(stream: TcpStream, shared: Shared) { mod tests { use super::*; use glam::Vec2; - use recreation_towers::{Order, Phase}; + use recreation_towers::seat::{STICKS_TIMEOUT, Sticks}; + use recreation_towers::{Order, Phase, Queued}; use recreation_towers_ground::map; use std::collections::BTreeSet; use std::sync::mpsc::{Receiver, channel}; @@ -263,10 +319,17 @@ mod tests { ToSeat::Orders(_) => "Orders", ToSeat::Truth(_) => "Truth", ToSeat::Advice(_) => "Advice", + ToSeat::Piloted(_) => "Piloted", + ToSeat::Mission(_) => "Mission", }) .collect() } + fn send(&self, msg: &ToServer) { + let mut w = self.out.try_clone().unwrap(); + writeln!(w, "{}", seat::encode(msg)).unwrap(); + } + fn leave(self) { let _ = self.out.shutdown(Shutdown::Both); } @@ -322,7 +385,7 @@ mod tests { } spectator.wait("the truth", |m| m.iter().any(|m| matches!(m, ToSeat::Truth(_)))); assert_eq!(person.kinds(), computer.kinds(), "the same kind of messages"); - assert_eq!(person.kinds(), ["Orders", "Sites", "Umpire", "Welcome"].into()); + assert_eq!(person.kinds(), ["Orders", "Piloted", "Sites", "Umpire", "Welcome"].into()); // The map of Blue's seat, made from what it got and no telemetry, has no enemy in it. let (umpire, sites) = { let got = person.got.lock().unwrap(); @@ -389,6 +452,159 @@ mod tests { assert!(!seats.people_seated()); } + fn pilot_of(team: Team, drone: usize) -> Join { + Join::Unit { team, drone } + } + + fn refused(c: &Client, what: &str) { + c.wait("a refusal", |m| m.iter().any(|m| matches!(m, ToSeat::Refused(w) if w.contains(what)))); + } + + fn wait_for(f: impl Fn() -> bool) { + let end = Instant::now() + Duration::from_secs(5); + while !f() { + assert!(Instant::now() < end, "timed out"); + std::thread::sleep(Duration::from_millis(10)); + } + } + + #[test] + fn a_pilots_sticks_reach_the_drones_radio_and_the_quad_and_a_second_pilot_are_refused() { + let (seats, world, _) = server([false, false], 50); + let i = world.lock().unwrap().game.drone(Team::Blue, 1); + let pilot = Client::join(seats.port(), pilot_of(Team::Blue, 1)); + pilot.wait("a welcome", |m| matches!(m.first(), Some(ToSeat::Welcome { .. }))); + assert!(world.lock().unwrap().pilots[i].is_some(), "the drone has its pilot"); + pilot.send(&ToServer::Sticks(Sticks { roll: 0.4, pitch: -0.2, throttle: 0.9, yaw: 0.1 })); + wait_for(|| world.lock().unwrap().pilots[i].as_ref().is_some_and(|p| p.sticks.aileron == 0.4)); + let sticks = world.lock().unwrap().pilots[i].as_ref().unwrap().sticks; + assert_eq!((sticks.aileron, sticks.elevator, sticks.throttle, sticks.rudder), (0.4, -0.2, 0.9, 0.1)); + // The quad is the server's, and a drone has one pilot. + let quad = Client::join(seats.port(), pilot_of(Team::Blue, 4)); + refused(&quad, "quad"); + let second = Client::join(seats.port(), pilot_of(Team::Blue, 1)); + refused(&second, "has its pilot"); + let nobody = Client::join(seats.port(), pilot_of(Team::Blue, 9)); + refused(&nobody, "no drone"); + let w = world.lock().unwrap(); + assert!(w.pilots[w.game.drone(Team::Blue, 4)].is_none()); + } + + #[test] + fn sticks_that_stop_or_a_seat_that_goes_give_the_drone_back_to_its_computer() { + let (seats, world, _) = server([false, false], 50); + let (a, b) = { + let w = world.lock().unwrap(); + (w.game.drone(Team::Blue, 0), w.game.drone(Team::Red, 2)) + }; + let silent = Client::join(seats.port(), pilot_of(Team::Blue, 0)); + let leaving = Client::join(seats.port(), pilot_of(Team::Red, 2)); + for c in [&silent, &leaving] { + c.wait("a welcome", |m| matches!(m.first(), Some(ToSeat::Welcome { .. }))); + } + silent.send(&ToServer::Sticks(Sticks::CENTRED)); + assert_eq!(world.lock().unwrap().piloted(Team::Blue), vec![0]); + // The one that leaves is given back at once. + leaving.leave(); + wait_for(|| world.lock().unwrap().pilots[b].is_none()); + // The one that stays silent is given back after the time the sticks may stop for. + std::thread::sleep(Duration::from_secs_f32(STICKS_TIMEOUT + 0.3)); + world.lock().unwrap().expire_pilots(); + assert!(world.lock().unwrap().pilots[a].is_none(), "its sticks stopped"); + // If its sticks come back and nobody else has the drone, it has it again. + silent.send(&ToServer::Sticks(Sticks::CENTRED)); + wait_for(|| world.lock().unwrap().pilots[a].is_some()); + } + + #[test] + fn a_seat_that_commands_learns_which_drones_are_piloted_and_a_pilots_seat_gets_no_map() { + let (seats, world, _) = server([false, false], 50); + let commander = Client::join(seats.port(), Join::Compute(Team::Blue)); + let red = Client::join(seats.port(), Join::Compute(Team::Red)); + let pilot = Client::join(seats.port(), pilot_of(Team::Blue, 2)); + let spectator = Client::join(seats.port(), Join::Spectate); + for c in [&commander, &red, &pilot, &spectator] { + c.wait("a welcome", |m| m.iter().any(|m| matches!(m, ToSeat::Welcome { .. }))); + } + tick(&seats, &world); + commander.wait("the piloted drones", |m| m.iter().any(|m| *m == ToSeat::Piloted(vec![2]))); + red.wait("the piloted drones", |m| m.iter().any(|m| *m == ToSeat::Piloted(vec![]))); + pilot.wait("its mission", |m| m.iter().any(|m| matches!(m, ToSeat::Mission(_)))); + spectator.wait("the truth", |m| m.iter().any(|m| matches!(m, ToSeat::Truth(_)))); + // Welcome and Mission: no map of the team (View), no umpire, no sites, no truth, no orders. + assert_eq!(pilot.kinds(), ["Mission", "Welcome"].into()); + let got = pilot.got.lock().unwrap(); + let Some(ToSeat::Welcome { air, .. }) = got.first() else { panic!("{got:?}") }; + assert!(air.is_empty(), "a pilot has no way to the team's drones"); + } + + #[test] + fn the_mission_follows_an_order_in_contact_and_stays_as_it_was_out_of_contact() { + let (seats, world, _) = server([false, false], 50); + let rules = world.lock().unwrap().game.rules; + let i = world.lock().unwrap().game.drone(Team::Blue, 1); + let commander = Client::join(seats.port(), Join::Compute(Team::Blue)); + let pilot = Client::join(seats.port(), pilot_of(Team::Blue, 1)); + for c in [&commander, &pilot] { + c.wait("a welcome", |m| m.iter().any(|m| matches!(m, ToSeat::Welcome { .. }))); + } + let ordered = |order: Order| ToServer::Order { + drone: 1, + order, + low: false, + standing: None, + queue: vec![Queued::done(Order::Home)], + }; + let mission_of = |p: &Client| { + p.got + .lock() + .unwrap() + .iter() + .rev() + .find_map(|m| if let ToSeat::Mission(m) = m { Some(m.clone()) } else { None }) + }; + let step = || { + // The radio's link, as drone 0's physics thread works it after each step of the referee. + { + let mut w = world.lock().unwrap(); + w.game.look(); + w.link_up(); + } + tick(&seats, &world); + }; + commander.send(&ordered(Order::Take(2))); + wait_for(|| world.lock().unwrap().orders[i] == Some(Order::Take(2))); + step(); + pilot.wait("the order as its mission", |m| { + m.iter().any(|m| matches!(m, ToSeat::Mission(x) if x.order == Some(Order::Take(2)) && x.in_contact)) + }); + let m = mission_of(&pilot).unwrap(); + assert_eq!((m.drone, m.queue.clone()), (1, vec![Queued::done(Order::Home)])); + assert_eq!(m.towers.len(), world.lock().unwrap().game.towers.len()); + assert!(m.obs.at.distance(rules.base(Team::Blue)) < 40.0, "what the drone knows is where it is"); + // The radio is cut: the commander's next order does not reach the pilot's screen. + { + let mut w = world.lock().unwrap(); + let red_home = w.game.tower("Red home"); + w.game.towers[red_home].holder = Some(Team::Red); + w.game.drones[i].at = w.game.towers[red_home].at + glam::Vec2::new(10.0, 0.0); + (w.game.drones[i].alt, w.game.drones[i].phase) = (30.0, Phase::Flying); + } + commander.send(&ordered(Order::Hold)); + wait_for(|| world.lock().unwrap().orders[i] == Some(Order::Hold)); + step(); + pilot.wait("out of contact", |m| m.iter().any(|m| matches!(m, ToSeat::Mission(x) if !x.in_contact))); + let m = mission_of(&pilot).unwrap(); + assert!(!m.in_contact); + assert_eq!(m.order, Some(Order::Take(2)), "the mission does not change in a shadow"); + // It catches up when the radio reaches the drone again. + world.lock().unwrap().game.drones[i].at = rules.base(Team::Blue); + step(); + pilot.wait("the new order", |m| { + m.iter().any(|m| matches!(m, ToSeat::Mission(x) if x.order == Some(Order::Hold) && x.in_contact)) + }); + } + #[test] fn two_people_one_for_each_team_can_join_the_same_server() { let (seats, world, _) = server([true, true], 50); diff --git a/domains/recreation/towers_server/src/world.rs b/domains/recreation/towers_server/src/world.rs index 61df8431..5a1f2a83 100644 --- a/domains/recreation/towers_server/src/world.rs +++ b/domains/recreation/towers_server/src/world.rs @@ -9,13 +9,22 @@ use crate::terrain::Valley; use crate::trees::Forest; use glam::{Vec2, Vec3}; use recreation_games::{Controls, Preflight, Radio, flying_slot, mode_slot}; +use recreation_towers::seat::{Mission, STICKS_TIMEOUT, Sticks}; use recreation_towers::{ Class, Game, Instruction, Link, Order, Phase as Referee, Queued, Rules, Standing, Team, queue_of, }; -use recreation_towers_ground::leg_for; +use recreation_towers_ground::{drone_name, leg_for}; use simulation_aircraft::{ActuatorCommands, AircraftParams}; use simulation_physics::Obstacle; use simulation_physics::{Environment, FlightState, Phase, Start, step}; +use std::time::Instant; + +/// A new pilot's sticks are the drone's this long (wall seconds) after the pilot took the seat: the +/// ground station of the team is told at once, and has this long to leave the drone alone. +pub const HANDOVER: f32 = 1.0; +/// A pilot who takes a drone that flies in AGENT sends it a radio mode that is not FBWA this long +/// (s of the game) before FBWA: ArduPilot only changes mode when the switch moves. +const MODE_PULSE: f32 = 1.5; /// A crashed drone is back at its base this long after the crash (s). pub const RESPAWN: f32 = 15.0; @@ -111,6 +120,19 @@ pub fn aircraft(class: recreation_towers::Class) -> AircraftParams { (simulation_aircraft::find(class.aircraft()).expect("a plane for every class").params)() } +/// A person who flies a drone by the sticks (a seat that is `Join::Unit`). +pub struct Pilot { + /// The seat's connection. + pub id: u64, + pub sticks: Controls, + /// When the sticks were last heard, and when the pilot took the drone (wall time). + heard: Instant, + since: Instant, + /// The game seconds left of the switch that takes a drone out of AGENT (`MODE_PULSE`); `None` + /// until the sticks are the pilot's. A drone that takes off under its pilot needs none. + pulse: Option, +} + /// The game and the drones' planes. pub struct World { pub game: Game, @@ -137,6 +159,11 @@ pub struct World { /// was told while it was in contact. A drone out of contact flies on, and its team is not told /// what it flies now (the order is the team's, and the drone's own failsafe is not). pub told: Vec<(Option, bool)>, + /// The person who flies each drone, if one does (by its index in the game). + pub pilots: Vec>, + /// The mission each drone's pilot is shown: the order, whether it is low, and the queue that + /// last reached the drone, which is the commander's last word while the radio reached it. + pub shown: Vec<(Option, bool, Vec)>, /// The ground: flat, with the mountains. terrain: Valley, /// The trees, for the flight model, and the ones near the plane being stepped. @@ -179,6 +206,8 @@ impl World { queue: vec![vec![]; n], queue_taken: vec![0; n], standing: vec![None; n], + pilots: (0..n).map(|_| None).collect(), + shown: vec![(Some(Order::Home), false, vec![]); n], terrain, forest, near: vec![], @@ -323,8 +352,13 @@ impl World { /// What the drones' radios do after a step of the referee: a drone in contact tells its team /// its order; one that is out of contact long enough flies its standing order, or, with none, /// home (the failsafe), and stays on that order until the team can give it another. - fn link_up(&mut self) { + pub(crate) fn link_up(&mut self) { for i in 0..self.orders.len() { + // The mission on a pilot's screen is what reached the drone: it does not change in a + // radio shadow, and catches up when the radio reaches the drone again. + if self.in_reach(i) { + self.shown[i] = (self.orders[i], self.lows[i], self.queue[i].clone()); + } if self.game.link(i) == Link::Up { self.told[i] = (self.orders[i], self.lows[i]); continue; @@ -396,7 +430,28 @@ impl World { return off; } let agl = s.pos.y; - self.preflight[i].radio(p, s, agl, dt).unwrap_or_else(|| { + match self.preflight[i].radio(p, s, agl, dt) { + Some(radio) => { + // A pilot who has the drone before it is on the wing needs no switch to get it out + // of AGENT: it has not been in it. + if let Some(pilot) = self.pilots[i].as_mut() { + pilot.pulse.get_or_insert(0.0); + } + radio + } + None => self.on_the_wing(i, dt), + } + } + + /// What drone `i`'s radio sends once it is on the wing: the pilot's sticks, if a person flies + /// it; else the sticks of the server's quad, or the sticks centred for the AGENT mode. + fn on_the_wing(&mut self, i: usize, dt: f32) -> Radio { + if let Some(radio) = self.pilot_radio(i, dt) { + return radio; + } + let p = &self.params[i]; + let s = &self.planes[i]; + { // A drone on the wing is flown by its plan. One with no wing is flown by the sticks // to where its order sends it. let sticks = if self.game.drones[i].class == recreation_towers::Class::Light { @@ -410,7 +465,110 @@ impl World { Controls { throttle: 0.5, ..Default::default() } }; Radio { sticks, arm: true, mode: flying_slot(p) } - }) + } + } + + /// Takes the wing of drone `i` for the pilot `id`, or says why not. + pub fn claim_pilot(&mut self, i: usize, id: u64) -> Result<(), String> { + let name = drone_name(&self.game.rules, i); + if self.game.drones[i].class == Class::Light { + return Err(format!("{name} is a quad: the server flies it, and only a winged drone has a pilot")); + } + if self.pilots[i].is_some() { + return Err(format!("{name} has its pilot")); + } + let now = Instant::now(); + self.pilots[i] = Some(Pilot { + id, + sticks: Controls { throttle: 0.5, ..Default::default() }, + heard: now, + since: now, + pulse: None, + }); + println!("pilot: {name} is flown by a person"); + Ok(()) + } + + /// The pilot `id` sends its sticks. A pilot whose sticks had stopped, and whose drone nobody + /// else has taken, has it again. + pub fn fly(&mut self, i: usize, id: u64, sticks: Sticks) { + if self.pilots[i].is_none() { + let _ = self.claim_pilot(i, id); + } + if let Some(pilot) = self.pilots[i].as_mut().filter(|p| p.id == id) { + let s = sticks.clamped(); + pilot.sticks = Controls { aileron: s.roll, elevator: s.pitch, rudder: s.yaw, throttle: s.throttle }; + pilot.heard = Instant::now(); + } + } + + /// The pilot `id` has gone: the drone is the computer's again. + pub fn release_pilot(&mut self, i: usize, id: u64) { + if self.pilots[i].as_ref().is_some_and(|p| p.id == id) { + self.pilots[i] = None; + println!("pilot: {} is given back to the computer: the seat is gone", drone_name(&self.game.rules, i)); + } + } + + /// Gives back the drones whose pilots' sticks have stopped for [`STICKS_TIMEOUT`] s. + pub fn expire_pilots(&mut self) { + for i in 0..self.pilots.len() { + if self.pilots[i].as_ref().is_some_and(|p| p.heard.elapsed().as_secs_f32() > STICKS_TIMEOUT) { + self.pilots[i] = None; + println!( + "pilot: {} is given back to the computer: the sticks stopped", + drone_name(&self.game.rules, i) + ); + } + } + } + + /// The drones of `team` (by their number in the team) that a person flies now. + pub fn piloted(&self, team: Team) -> Vec { + let n = self.game.rules.drones; + (0..n).filter(|&k| self.pilots[self.game.drone(team, k)].is_some()).collect() + } + + /// What the radio of drone `i` sends when its pilot flies it: the pilot's sticks, the mode + /// switch at FBWA; `None` while the drone is the computer's. For [`HANDOVER`] s after the pilot + /// takes it the computer's station still has it; then, if it is in AGENT, the mode switch moves + /// to another mode for a moment, so that the switch's return to FBWA is a change ArduPilot takes. + fn pilot_radio(&mut self, i: usize, dt: f32) -> Option { + self.expire_pilots(); + let params = &self.params[i]; + let pilot = self.pilots[i].as_mut()?; + if pilot.since.elapsed().as_secs_f32() < HANDOVER { + return None; + } + let pulse = pilot.pulse.get_or_insert(MODE_PULSE); + let fbwa = flying_slot(params); + if *pulse > 0.0 { + *pulse -= dt; + let other = + params.rc_modes.iter().position(|m| *m == "CRUISE").unwrap_or((fbwa + 1) % params.rc_modes.len()); + return Some(Radio { sticks: Controls { throttle: 0.5, ..Default::default() }, arm: true, mode: other }); + } + Some(Radio { sticks: pilot.sticks, arm: true, mode: fbwa }) + } + + /// What drone `i`'s pilot is shown: the mission and what the drone itself knows. + pub fn mission(&self, i: usize) -> Mission { + let game = &self.game; + let d = &game.drones[i]; + Mission { + drone: i % game.rules.drones, + order: self.shown[i].0, + low: self.shown[i].1, + queue: self.shown[i].2.clone(), + in_contact: self.in_reach(i), + obs: game.edge_obs(i), + vel: d.vel, + attitude: self.planes[i].rot.to_array(), + towers: game.towers.iter().map(|t| (t.name.clone(), t.at)).collect(), + time: game.time, + time_left: game.time_left(), + outcome: game.outcome, + } } /// Drone `i` in the referee's game as its plane is. @@ -453,6 +611,92 @@ mod tests { World::new(Rules::default().without_batteries(), 0.0) } + #[test] + fn a_pilots_sticks_are_the_drones_radio_after_the_handover_and_a_drone_in_agent_is_taken_out_of_it() { + let mut w = world(); + let i = w.game.drone(Team::Blue, 1); + let fbwa = flying_slot(&w.params[i]); + let sticks = Sticks { roll: 0.5, pitch: -0.25, throttle: 0.8, yaw: -0.5 }; + w.claim_pilot(i, 7).unwrap(); + w.fly(i, 7, sticks); + // For the first second the computer's station still has the drone: sticks centred, FBWA. + let r = w.on_the_wing(i, 0.1); + assert_eq!((r.sticks.aileron, r.mode), (0.0, fbwa)); + // Then the sticks are the pilot's. The drone may be in AGENT: the mode switch leaves FBWA + // for a moment (1.5 s of the game) and comes back, which is a change that ArduPilot takes. + w.pilots[i].as_mut().unwrap().since = Instant::now() - std::time::Duration::from_secs(2); + let r = w.on_the_wing(i, 0.5); + assert_ne!(r.mode, fbwa, "the switch moves"); + assert_eq!(r.sticks.aileron, 0.0, "the sticks are centred meanwhile"); + for _ in 0..3 { + w.on_the_wing(i, 0.5); + } + let r = w.on_the_wing(i, 0.5); + assert_eq!(r.mode, fbwa); + assert!(r.arm); + assert_eq!((r.sticks.aileron, r.sticks.elevator, r.sticks.throttle, r.sticks.rudder), (0.5, -0.25, 0.8, -0.5)); + // A pilot whose sticks have stopped for good gives the drone back: centred again. + w.pilots[i].as_mut().unwrap().heard = Instant::now() - std::time::Duration::from_secs(3); + let r = w.on_the_wing(i, 0.1); + assert_eq!((r.sticks.aileron, r.sticks.throttle, r.mode), (0.0, 0.5, fbwa)); + assert!(w.pilots[i].is_none()); + } + + #[test] + fn a_pilot_who_took_the_drone_before_the_wing_needs_no_switch() { + let mut w = world(); + let i = w.game.drone(Team::Blue, 0); + w.claim_pilot(i, 1).unwrap(); + w.fly(i, 1, Sticks { roll: 1.0, ..Sticks::CENTRED }); + w.pilots[i].as_mut().unwrap().since = Instant::now() - std::time::Duration::from_secs(2); + // The drone is still taking off: the preflight flies it, and the pilot has not been in AGENT. + w.pilots[i].as_mut().unwrap().pulse.get_or_insert(0.0); + let r = w.on_the_wing(i, 0.1); + assert_eq!((r.sticks.aileron, r.mode), (1.0, flying_slot(&w.params[i]))); + } + + #[test] + fn a_quad_has_no_pilot_and_a_drone_has_one() { + let mut w = world(); + let quad = w.game.drone(Team::Red, 4); + assert!(w.claim_pilot(quad, 1).unwrap_err().contains("quad")); + let i = w.game.drone(Team::Red, 0); + assert!(w.claim_pilot(i, 1).is_ok()); + assert!(w.claim_pilot(i, 2).unwrap_err().contains("has its pilot")); + // Another seat's sticks are not the pilot's. + w.fly(i, 2, Sticks { roll: 1.0, ..Sticks::CENTRED }); + assert_eq!(w.pilots[i].as_ref().unwrap().sticks.aileron, 0.0); + w.release_pilot(i, 2); + assert!(w.pilots[i].is_some(), "a seat gives up only its own drone"); + w.release_pilot(i, 1); + assert_eq!(w.piloted(Team::Red), Vec::::new()); + } + + #[test] + fn the_mission_a_pilot_is_shown_is_the_last_order_that_reached_the_drone() { + let mut w = world(); + let i = w.game.drone(Team::Blue, 0); + w.command(i, Order::Take(1), false); + w.link_up(); + assert_eq!(w.mission(i).order, Some(Order::Take(1))); + // Out of reach (a shadow): the team gives another order, and the mission stays. + let red_home = w.game.tower("Red home"); + w.game.towers[red_home].holder = Some(Team::Red); + w.game.drones[i].at = w.game.towers[red_home].at; + w.game.drones[i].phase = Referee::Flying; + w.game.look(); + w.command(i, Order::Hold, true); + w.link_up(); + let m = w.mission(i); + assert_eq!((m.order, m.low, m.in_contact), (Some(Order::Take(1)), false, false)); + assert!(m.obs.silent >= 0.0); + w.game.drones[i].at = w.game.rules.base(Team::Blue); + w.game.look(); + w.link_up(); + let m = w.mission(i); + assert_eq!((m.order, m.low, m.in_contact), (Some(Order::Hold), true, true)); + } + #[test] fn the_field_and_the_world_agree_with_the_ned_of_the_ground() { let p = to_world(Vec2::new(100.0, 20.0), 30.0); diff --git a/domains/recreation/towers_server/tests/acceptance.rs b/domains/recreation/towers_server/tests/acceptance.rs index 628312f4..31a6d519 100644 --- a/domains/recreation/towers_server/tests/acceptance.rs +++ b/domains/recreation/towers_server/tests/acceptance.rs @@ -26,6 +26,7 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; const EVENT: &str = "two computer teams play a game of Towers"; +const PILOT_EVENT: &str = "two computer teams play a game of Towers while a person flies the second Blue drone"; /// The seat port the test's server listens on. const PORT: u16 = 5955; /// A whole game takes about a minute and a half at ten times real time. @@ -208,6 +209,132 @@ fn play(bin: &Path) -> Result { Ok(played) } +/// A game with a scripted pilot on the second Blue drone: what the server and the pilot left. +#[derive(Clone, Default)] +struct PilotGame { + results: HashMap, + flown: recreation_towers_ground::pilot::Flown, + /// After the server said it gave the drone back, a report shows Blue2 in AGENT with a plan. + agent_after: bool, + log: Vec, +} + +/// The game time (s) of the latest report line in the server's log, if any. +fn game_time(lines: &[String]) -> Option { + lines.iter().rev().find_map(|l| { + let (_, rest) = l.split_once("] t ")?; + rest.split_once("s (playing)")?.0.trim().parse().ok() + }) +} + +/// Plays a game at 10x with computer commanders, and, after `JOIN_AT` s of play, a scripted pilot +/// that takes the second Blue drone, banks it for `FLY_FOR` s (wall) and lets go. Only the server's +/// own process is stopped: the test never kills another game's SITL. +fn play_piloted(bin: &Path) -> Result { + const JOIN_AT: f32 = 40.0; + const FLY_FOR: u64 = 25; + let mut child = Command::new(env!("CARGO_BIN_EXE_towers_server")) + .args(["--speedup", "10", "--timeout", "350", "--seat-port", &PORT.to_string()]) + .env("SIM001_BIN", bin) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .map_err(|e| format!("couldn't start the game server: {e}"))?; + let out = child.stdout.take().unwrap(); + let lines = Arc::new(Mutex::new(Vec::::new())); + let l2 = lines.clone(); + let reader = std::thread::spawn(move || { + for line in BufReader::new(out).lines().map_while(Result::ok) { + println!("server: {line}"); + l2.lock().unwrap().push(line); + } + }); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let mut pilot = None; + let end = Instant::now() + PATIENCE; + let status = loop { + match child.try_wait() { + Ok(Some(s)) => break Some(s), + _ if Instant::now() > end => break None, + _ => {} + } + if pilot.is_none() && game_time(&lines.lock().unwrap()).is_some_and(|t| t >= JOIN_AT) { + let stop = stop.clone(); + pilot = Some(std::thread::spawn(move || { + recreation_towers_ground::pilot::fly( + &format!("127.0.0.1:{PORT}"), + Team::Blue, + 1, + &recreation_towers_ground::pilot::Script::bank(), + Duration::from_secs(FLY_FOR), + &stop, + ) + })); + } + std::thread::sleep(Duration::from_millis(200)); + }; + stop.store(true, std::sync::atomic::Ordering::SeqCst); + if status.is_none() { + let _ = child.kill(); + let _ = child.wait(); + } + let _ = reader.join(); + let lines = lines.lock().unwrap().clone(); + let tail = || lines.iter().rev().take(20).rev().cloned().collect::>().join("\n"); + match status { + Some(s) if s.success() => {} + Some(s) => return Err(format!("the game server failed ({s}); its last lines:\n{}", tail())), + None => return Err(format!("the game server did not finish; its last lines:\n{}", tail())), + } + let flown = pilot.ok_or("the game ended before the pilot could join")?.join().map_err(|_| "the pilot panicked")?; + if let Some(why) = &flown.refused { + return Err(format!("the pilot's seat was refused: {why}")); + } + let mut game = PilotGame { flown, ..Default::default() }; + for l in &lines { + if let Some((k, v)) = l.strip_prefix("RESULT ").and_then(|r| r.split_once('=')) { + game.results.insert(k.to_string(), v.to_string()); + } + } + let back = lines.iter().position(|l| l.contains("pilot: Blue2 is given back")); + game.agent_after = back.is_some_and(|b| { + lines[b..].iter().any(|l| l.contains("Blue2 AGENT plan") && !l.contains("plan -") && !l.contains("[PILOTED]")) + }); + println!( + "pilot game: turned {:.0} degrees, {} orders seen, {} missions in the dark ({} changed), AGENT with a plan after hand-back: {}", + game.flown.turned, + game.flown.orders.len(), + game.flown.dark, + game.flown.changed_in_the_dark, + game.agent_after + ); + game.log = lines; + Ok(game) +} + +fn observe_piloted(g: &PilotGame, subject: &str) -> Option { + let result = |k: &str| g.results.get(k).and_then(|v| v.parse::().ok()); + Some(match subject { + "the looks at the second Blue drone in AGENT mode while a person flies it" => { + Value::from(result("piloted_in_agent")?) + } + "the looks of the Blue ground at the second Blue drone on its map while a person flies it" => { + Value::from(result("piloted_mapped")?) + } + "the turn of the second Blue drone under its pilot" => Value::from(f64::from(g.flown.turned.abs())), + "the orders that the pilot of the second Blue drone saw as its mission" => { + Value::from(g.flown.orders.len() as f64) + } + "the missions that changed on the pilot's screen out of contact" => { + Value::from(g.flown.changed_in_the_dark as f64) + } + "the second Blue drone after the pilot let go" => { + Value::from(if g.agent_after { "in AGENT mode with a plan" } else { "not in AGENT mode" }) + } + _ => return None, + }) +} + /// The states a fresh game starts in: the section's start, the only one the server can arrange. const START: &[(&str, &str)] = &[ ("the game of Towers", "in play"), @@ -239,6 +366,12 @@ const OBSERVED: &[&str] = &[ "the seconds that the first light drone took to leave its base", "the top speed of the light drones", "the light drones that fly low", + "the looks at the second Blue drone in AGENT mode while a person flies it", + "the turn of the second Blue drone under its pilot", + "the looks of the Blue ground at the second Blue drone on its map while a person flies it", + "the orders that the pilot of the second Blue drone saw as its mission", + "the missions that changed on the pilot's screen out of contact", + "the second Blue drone after the pilot let go", ]; fn is(v: &Variable, subject: &str) -> bool { @@ -252,6 +385,9 @@ fn text(v: &Value) -> String { struct Server { bin: PathBuf, played: Option>, + /// The game with a pilot is one game for each expectation that asks about it: it is played + /// once (a game takes minutes, and only one may run on this machine). + piloted: Option>, } impl Driver for Server { @@ -273,6 +409,12 @@ impl Driver for Server { } fn perform(&mut self, event: &Event) -> Result<(), String> { + if event.text.eq_ignore_ascii_case(PILOT_EVENT) { + if self.piloted.is_none() { + self.piloted = Some(play_piloted(&self.bin)); + } + return self.piloted.clone().and_then(Result::err).map_or(Ok(()), Err); + } if !event.text.eq_ignore_ascii_case(EVENT) { return Err(format!("the game server can't make {} happen", event.text)); } @@ -289,6 +431,11 @@ impl Driver for Server { { return Ok(v.parse::().map_or_else(|_| Value::from(*v), Value::from)); } + if let Some(Ok(g)) = &self.piloted + && let Some(v) = observe_piloted(g, &var.subject) + { + return Ok(v); + } let Some(Ok(p)) = &self.played else { return Err("no game has been played".into()) }; let result = |k: &str| p.results.get(k).and_then(|v| v.parse::().ok()).ok_or(format!("no RESULT {k}")); let n = match var.subject.as_str() { @@ -334,7 +481,7 @@ impl Driver for Server { match need { Need::Arrange(v) => START.iter().any(|(s, _)| is(v, s)), Need::Set(_) => false, - Need::Perform(e) => e.text.eq_ignore_ascii_case(EVENT), + Need::Perform(e) => e.text.eq_ignore_ascii_case(EVENT) || e.text.eq_ignore_ascii_case(PILOT_EVENT), Need::Observe(v) => OBSERVED.iter().any(|s| is(v, s)) || START.iter().any(|(s, _)| is(v, s)), } } @@ -346,7 +493,7 @@ fn the_server_plays_a_game_with_arduplane() { let a = Acceptance::load_for(&dir, "sim").unwrap_or_else(|e| panic!("{e}")).with_coverage(); let section = a.suite.sections.iter().find(|s| s.slug == "towers").expect("a towers section").id; let ours = a.suite.subtree(section); - let mut driver = Server { bin: agent_dir(), played: None }; + let mut driver = Server { bin: agent_dir(), played: None, piloted: None }; let mut services = Services::new().with(agent_service()); let missing = services.missing(&["ardupilot-agent"]); if let Some(why) = missing.first() { diff --git a/domains/recreation/towers_view/Cargo.toml b/domains/recreation/towers_view/Cargo.toml index 7309d0d5..11428565 100644 --- a/domains/recreation/towers_view/Cargo.toml +++ b/domains/recreation/towers_view/Cargo.toml @@ -10,6 +10,8 @@ path = "src/main.rs" [dependencies] recreation_towers = { path = "../towers" } +# The seat client, for the cockpit (`--fly`): a pilot's seat on the game server. +recreation_towers_ground = { path = "../towers_ground" } visualization_engine = { path = "../../visualization/engine" } # The battlefield of each team, for its commander app. visualization_battlefield = { path = "../../visualization/battlefield" } diff --git a/domains/recreation/towers_view/src/cockpit.rs b/domains/recreation/towers_view/src/cockpit.rs new file mode 100644 index 00000000..6a1440dd --- /dev/null +++ b/domains/recreation/towers_view/src/cockpit.rs @@ -0,0 +1,446 @@ +//! The cockpit: `towers_view --fly blue:2` takes the seat of one drone as its pilot +//! (`Join::Unit`), shows that drone's nose camera full screen with a small HUD, and sends the +//! pilot's sticks to the server. +//! +//! The picture is made from what the drone's seat is told (`Mission`): the drone's own place and +//! attitude, and the enemy drones its camera sees. No other drone is drawn, and the team's map and +//! the truth are not read. The HUD shows the speed, the height, the battery, whether the drone +//! is in contact, and the mission: the commander's order and queue, and the tower's name with its +//! bearing and distance. +//! +//! Keys: W / S throttle up and down, Left / Right roll, Up / Down pitch (Up pushes the stick +//! forward: nose down), A / D yaw, Space centres the sticks with the throttle at half. +//! A gamepad or the RadioMaster TX15 (a USB joystick) is read as well, and wins while it moves. + +use bevy::input::gamepad::{Gamepad, GamepadAxis}; +use bevy::prelude::*; +use recreation_towers::seat::{Join, Mission, Sticks}; +use recreation_towers::{Order, Team}; +use recreation_towers_ground::pilot::target_text; +use recreation_towers_ground::seat::{Seat, Status}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use visualization_engine::camera::{CamMode, CamState}; +use visualization_engine::{EngineSet, Pose, Scene}; + +/// The sticks are sent this often (Hz): the server gives the drone back after 2 s without them. +const SEND_HZ: f32 = 30.0; +/// How fast a key moves a stick (per second), and how fast it comes back when it is let go. +const KEY_RATE: f32 = 2.5; +const KEY_RETURN: f32 = 4.0; +/// How fast W and S move the throttle (per second). +const THROTTLE_RATE: f32 = 0.5; +/// The pilot's own plane is in this slot of the scene, and the engine's FPV camera follows it. +const OWN_SLOT: usize = 0; + +/// The drone to fly: its team and its number in the team, from 0. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Fly { + pub team: Team, + pub drone: usize, +} + +/// `blue:2` is the second Blue drone: the team, a colon, and the drone's number from 1, as the +/// game's names say it (Blue2). +pub fn parse(s: &str) -> Result { + let bad = || format!("--fly takes a team and a drone, like blue:2 (the second Blue drone), not {s:?}"); + let (team, drone) = s.split_once(':').ok_or_else(bad)?; + let team = match team.to_lowercase().as_str() { + "blue" => Team::Blue, + "red" => Team::Red, + _ => return Err(bad()), + }; + let drone: usize = drone.parse().map_err(|_| bad())?; + if drone == 0 { + return Err(bad()); + } + Ok(Fly { team, drone: drone - 1 }) +} + +#[derive(Resource)] +struct Cockpit { + seat: Arc, + fly: Fly, + /// The sticks as the pilot holds them now, sent 30 times a second by a thread of its own. + sticks: Arc>, + /// Their last value from the keys (they move by degrees). + keys: Sticks, +} + +#[derive(Component)] +struct Readout; +#[derive(Component)] +struct MissionText; +#[derive(Component)] +struct Notice; + +pub fn plugin(app: &mut App, fly: Fly, server: &str) { + let seat = Seat::connect(server, Join::Unit { team: fly.team, drone: fly.drone }); + let sticks = Arc::new(Mutex::new(Sticks::CENTRED)); + { + let (seat, sticks) = (seat.clone(), sticks.clone()); + std::thread::spawn(move || { + while !seat.stopped() { + let s = *sticks.lock().unwrap(); + seat.sticks(s); + std::thread::sleep(Duration::from_secs_f32(1.0 / SEND_HZ)); + } + }); + } + app.insert_resource(Cockpit { seat, fly, sticks, keys: Sticks::CENTRED }) + .add_systems(Startup, (look_through_the_nose, hud)) + .add_systems(Update, (read_sticks, publish.before(EngineSet::Draw), show)); +} + +/// The engine's FPV camera is a nose camera, on the plane in the first slot. +fn look_through_the_nose(mut cs: ResMut) { + cs.mode = CamMode::Fpv; +} + +/// How a drone's body sits in the view's world, from the quaternion the drone reports. +fn attitude(q: [f32; 4]) -> Quat { + let q = Quat::from_xyzw(q[0], q[1], q[2], q[3]); + if q.length_squared() > 0.5 { q.normalize() } else { Quat::IDENTITY } +} + +/// The scene: the drone itself in the first slot, and the enemy drones its camera sees in the slots +/// of the other team's liveries. Nothing else: a pilot sees what the drone sees. +fn publish(cockpit: Res, mut scene: ResMut) { + scene.vehicles.fill(None); + let Some(m) = cockpit.seat.state().mission.clone() else { return }; + let to_world = |at: glam::Vec2, alt: f32| Vec3::new(at.y, alt, -at.x); + let own = Pose { + pos: to_world(m.obs.at, m.obs.alt), + rot: attitude(m.attitude), + spool: vec![0.6; 3], + tilt: vec![0.0, 0.0, 0.0], + ..default() + }; + scene.vehicles[OWN_SLOT] = Some(own); + // The Red drones of a Blue pilot are in the slots from 5, the Blue drones of a Red pilot from 1 + // (the liveries of the view: Blue's first, then Red's). + let first = if cockpit.fly.team == Team::Blue { 5 } else { 1 }; + for (k, e) in m.obs.enemies.iter().enumerate() { + if let Some(slot) = scene.vehicles.get_mut(first + k) { + let (spool, tilt) = match e.class { + recreation_towers::Class::Light => (vec![0.6; 4], vec![]), + _ => (vec![0.6; 3], vec![0.0, 0.0, 0.0]), + }; + *slot = Some(Pose { pos: to_world(m.obs.at + e.offset, e.alt), spool, tilt, ..default() }); + } + } +} + +// ---- the sticks ---- + +/// What the keys hold: each stick's direction, -1, 0 or 1, and the throttle's. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Keys { + pub roll: f32, + /// Positive: the stick pulled back, nose up. + pub pitch: f32, + pub yaw: f32, + pub throttle: f32, + pub centre: bool, +} + +/// The sticks one step on from `now`, with `keys` held for `dt` seconds: a stick moves toward the +/// direction of its key and comes back to the middle when it is let go, as a spring does; the +/// throttle stays where it is. +pub fn step_keys(now: Sticks, keys: Keys, dt: f32) -> Sticks { + if keys.centre { + return Sticks::CENTRED; + } + let towards = |x: f32, dir: f32| { + if dir == 0.0 { + let back = KEY_RETURN * dt; + if x.abs() <= back { 0.0 } else { x - back * x.signum() } + } else { + (x + dir * KEY_RATE * dt).clamp(-1.0, 1.0) + } + }; + Sticks { + roll: towards(now.roll, keys.roll), + pitch: towards(now.pitch, keys.pitch), + yaw: towards(now.yaw, keys.yaw), + throttle: (now.throttle + keys.throttle * THROTTLE_RATE * dt).clamp(0.0, 1.0), + } +} + +/// The raw axes of a joystick or gamepad, as Bevy reads them (up is positive on a gamepad). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Axes { + pub left_x: f32, + pub left_y: f32, + pub right_x: f32, + pub right_y: f32, + /// The fourth channel of a radio's joystick (rudder), which has no name in Bevy. + pub other: f32, +} + +/// The sticks of a radio that is a USB joystick (a RadioMaster TX15 with EdgeTX, channels AETR): +/// roll and pitch on the left stick axes, the throttle absolute on the right stick's X and the rudder +/// on the fourth channel, as the sim's default mapping has them. A radio's elevator axis is positive +/// for the stick pulled back. +pub fn radio_sticks(a: Axes) -> Sticks { + Sticks { roll: a.left_x, pitch: a.left_y, throttle: 0.5 + 0.5 * a.right_x, yaw: a.other }.clamped() +} + +/// The sticks of a gamepad in mode 2: the right stick rolls and pitches (up pushes the stick forward, +/// nose down), the left stick's X is the rudder, and its Y moves the throttle (the throttle is `held` +/// and moves by `dt`). +pub fn gamepad_sticks(a: Axes, held: f32, dt: f32) -> Sticks { + Sticks { + roll: a.right_x, + pitch: -a.right_y, + throttle: (held + a.left_y * THROTTLE_RATE * 1.4 * dt).clamp(0.0, 1.0), + yaw: a.left_x, + } + .clamped() +} + +/// The names that mark a joystick as a radio. +const RADIOS: [&str; 9] = ["tx15", "edgetx", "radiomaster", "opentx", "frsky", "jumper", "tx16", "boxer", "zorro"]; + +fn is_radio(name: &str) -> bool { + let n = name.to_lowercase(); + RADIOS.iter().any(|r| n.contains(r)) +} + +/// Whether a stick is off the middle, so that a pad that is only lying there does not take over. +fn moved(s: Sticks) -> bool { + s.roll.abs() > 0.1 || s.pitch.abs() > 0.1 || s.yaw.abs() > 0.1 +} + +fn read_sticks( + time: Res