Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

45 changes: 45 additions & 0 deletions domains/recreation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize>)` 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
Expand Down
104 changes: 102 additions & 2 deletions domains/recreation/towers/src/seat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -27,16 +30,85 @@ 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 {
/// The team the seat commands, for a person or a computer.
pub fn commands(self) -> Option<Team> {
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<Order>,
/// The order is flown low, along the lanes.
pub low: bool,
pub queue: Vec<Queued>,
/// 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<Outcome>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
Expand All @@ -58,6 +130,8 @@ pub enum ToServer {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
queue: Vec<Queued>,
},
/// The pilot's sticks, from a seat that is [`Join::Unit`].
Sticks(Sticks),
}

/// The whole game, for a spectator.
Expand Down Expand Up @@ -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<usize>),
/// To a pilot's seat: its mission, and what its drone knows, often.
Mission(Mission),
}

/// A message as a line (without its newline).
Expand Down Expand Up @@ -149,6 +229,26 @@ mod tests {
assert_eq!(decode::<ToServer>(&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::<ToServer>(&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::<ToServer>(&encode(&sticks)).unwrap(), sticks);
let piloted = ToSeat::Piloted(vec![0, 2]);
assert_eq!(decode::<ToSeat>(&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"}}}"#;
Expand Down
4 changes: 4 additions & 0 deletions domains/recreation/towers_ground/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
41 changes: 41 additions & 0 deletions domains/recreation/towers_ground/src/bin/towers_pilot.rs
Original file line number Diff line number Diff line change
@@ -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<String> = 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::<usize>().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);
}
1 change: 1 addition & 0 deletions domains/recreation/towers_ground/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Loading
Loading