SPLITSCREEN CLUB / DOCUMENTATION
Bevy
gamenight-bevy is a Bevy plugin that does the Splitscreen Club side of a game for
you. Add it next to DefaultPlugins, read GameNightEvent messages and ask
GameNight for each seat's controller. The plugin:
- connects when Splitscreen Club launched the game and runs standalone otherwise, with the keyboard and every local gamepad as seats, so your input code is the same in both modes;
- follows Prepare, Start, Pause, Resume and Dispose, and sends Ready two frames
after you call
ready(), so the first frame of your level exists before Start; - keeps the window hidden and unfocused while warming, shows it borderless fullscreen on Start and Resume and hides it on Pause and Dispose;
- pauses every playing
AudioSinkwhile you are not on the TV and updates at 10 fps while warm or paused, while still hearing Resume; - gives each seat its own controller by host token, with deadzones, press edges and a release required after Start and Resume;
- reports activity so nobody is marked asleep, and rumbles a seat's pad;
- re-declares your settings, phone buttons, phone screen and text commands after every reconnect, and replays setting changes from your own menu;
- reports frame timing every ten seconds of play, with CPU, GPU, OS, memory and window size;
- sends F1 to the party (physical Back is the host's own) and exits when the host goes away.
The demo game in sdk/bevy/demo, Star
Catch, uses every feature on this page. Each excerpt below is read from it.
CI runs it through the conformance harness against a real
host on every push.
Add the plugin
The plugin targets Bevy 0.20 (Rust 1.97.1 or newer). Pin a reviewed commit of the public repository:
[dependencies]
bevy = "0.20"
gamenight-bevy = { git = "https://github.com/ontola/gamepad-party", rev = "YOUR_REVIEWED_COMMIT" }
Replace YOUR_REVIEWED_COMMIT with an actual commit hash.
Set up the app
Wrap your window in managed_window, so a game Splitscreen Club launched starts
hidden and unfocused. A window that flashes up while warming steals the TV
from the game being played. Run simulation systems only while
gameplay_runs: that is what freezes play, timers and bots on Pause.
fn main() {
let args = Args::parse();
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(managed_window(Window {
title: TITLE.into(),
resolution: (1280u32, 720u32).into(),
..default()
})),
..default()
}))
.add_plugins(GameNightPlugin::new("bevy-demo"))
.insert_resource(ClearColor(Color::srgb(0.06, 0.07, 0.13)))
.insert_resource(Match {
rules: Rules {
round_seconds: args.round.unwrap_or(60),
..default()
},
..default()
})
.insert_resource(args)
.init_resource::<Menu>()
.add_systems(Startup, (setup, declare))
.add_systems(
Update,
(
gamenight_events,
standalone_start,
menu_input,
(steer, bots, physics, stars, bombs, round_clock)
.chain()
.run_if(gameplay_runs)
.run_if(menu_closed),
(draw_hud, draw_menu, phone_updates, music_volume, shot),
)
.chain(),
)
.run();
}
Source: sdk/bevy/demo/src/main.rs
GameNightPlugin::new turns the window, audio and throttling on. Set
manage_window, fullscreen, manage_audio, throttle_when_hidden or
report_activity to false to handle one of them yourself.
Follow the session
Every message from Splitscreen Club arrives as a GameNightEvent. On Prepare, build
the level for exactly the seats you were given, then call ready(). Opt into
live roster changes with participation(true) first if new players can join
mid-round, as here. Nothing restarts on RosterChanged or PlayersUpdated:
newcomers get a pawn, leavers lose theirs, and a new name, colour or face is
painted onto the same pawn.
fn gamenight_events(
mut commands: Commands,
mut gn: ResMut<GameNight>,
mut events: MessageReader<GameNightEvent>,
mut game: ResMut<Match>,
mut menu: ResMut<Menu>,
art: Res<Art>,
mut images: ResMut<Assets<Image>>,
mut materials: ResMut<Assets<ColorMaterial>>,
balls: Query<(Entity, &Ball)>,
stars: Query<Entity, Or<(With<Star>, With<Bomb>, With<Blast>)>>,
mut music: Query<&mut AudioSink, With<Music>>,
) {
// Pawns despawned earlier in this batch (Dispose then Prepare arrive together).
let mut gone = Vec::new();
for event in events.read() {
match event {
GameNightEvent::Prepare { seats, players, .. } => {
// Load everything while hidden. New players can drop in mid-round.
gn.participation(true);
*menu = Menu::default();
let rules = game.rules.clone();
*game = Match { rules, ..default() };
clear(&mut gone, &mut commands, &balls, &stars);
spawn_balls(
&mut commands,
&gn,
seats,
players,
&art,
&mut images,
&mut materials,
&mut game,
);
new_round(&mut commands, &mut game, &art);
game.started = true;
gn.ready();
}
// The plugin shows the window and plays audio on Start and Resume,
// and hides and pauses them on Pause. Simulation systems run only
// while `gameplay_runs`, so there is nothing else to do here.
GameNightEvent::Start { .. }
| GameNightEvent::Pause { .. }
| GameNightEvent::Resume { .. } => {}
GameNightEvent::Dispose { .. } => {
clear(&mut gone, &mut commands, &balls, &stars);
game.started = false;
}
GameNightEvent::RosterChanged { seats, players, .. } => {
// Keep the match going: add newcomers, drop pawns of those who left.
let mut known = Vec::new();
let alive: Vec<(Entity, &Ball)> =
balls.iter().filter(|(e, _)| !gone.contains(e)).collect();
for (entity, ball) in alive {
let still = seats
.iter()
.any(|s| s.index == ball.seat && s.occupant.player_id() == ball.player);
if still {
known.push(ball.seat);
} else {
commands.entity(entity).try_despawn();
gone.push(entity);
}
}
let fresh: Vec<Seat> = seats
.iter()
.filter(|s| !known.contains(&s.index))
.cloned()
.collect();
spawn_balls(
&mut commands,
&gn,
&fresh,
players,
&art,
&mut images,
&mut materials,
&mut game,
);
}
GameNightEvent::PlayersUpdated { players } => {
// A new name, colour or face for the same player: repaint, never restart.
for (entity, ball) in balls.iter().filter(|(e, _)| !gone.contains(e)) {
if let Some(player) = players.iter().find(|p| Some(p.id) == ball.player) {
commands.entity(entity).despawn_children();
dress(
&mut commands,
entity,
Some(player),
ball.seat,
&gn,
&art,
&mut images,
&mut materials,
);
}
}
}
GameNightEvent::SettingChanged { key, value } => {
game.rules.apply(key, value);
}
GameNightEvent::PlayerSettings { player_id, .. } => {
for (entity, ball) in balls.iter().filter(|(e, _)| !gone.contains(e)) {
if ball.player == Some(*player_id) {
commands.entity(entity).despawn_children();
let player = gn.player(*player_id).cloned();
dress(
&mut commands,
entity,
player.as_ref(),
ball.seat,
&gn,
&art,
&mut images,
&mut materials,
);
}
}
}
GameNightEvent::ActionTriggered { key, player_id } if key == "new_round" => {
let who = gn
.player(*player_id)
.map_or("Someone".into(), |p| p.name.clone());
info!("{who} asked for a new round");
new_round(&mut commands, &mut game, &art);
}
GameNightEvent::CompanionMessage { player_id, data } => {
if data.get("action").and_then(|a| a.as_str()) == Some("dash") {
for (entity, ball) in balls.iter().filter(|(e, _)| !gone.contains(e)) {
if ball.player == Some(*player_id) {
commands
.entity(entity)
.entry::<Ball>()
.and_modify(|mut b| b.phone_dash = true);
}
}
}
}
GameNightEvent::CompanionPresence {
player_id,
connected: true,
} => {
let view = phone_view(&gn, &game, *player_id);
gn.companion_message(Some(*player_id), view);
}
GameNightEvent::GameCommand { id, text, .. } => {
let (ok, answer) = command(&mut gn, text);
gn.command_result(id.clone(), ok, answer);
}
GameNightEvent::HostMusic { playing } => {
if let Ok(mut sink) = music.single_mut() {
sink.set_volume(Volume::Linear(if *playing { 0.0 } else { 0.35 }));
}
}
_ => {}
}
}
}
Source: sdk/bevy/demo/src/main.rs
Prepare can follow a Dispose in the same frame (a replay, a skip). Despawn
with try_despawn and skip entities you already removed in the same batch.
Read each seat's controller
gn.pad(seat) returns the seat's controller for this frame: neutral when the
seat has none, when input is more than 250 ms old and while the game is not
running. stick applies a radial deadzone (up is positive y, as in Bevy's
world), trigger a trigger deadzone. just_pressed is true once per press,
and a button still held from the lobby has to be released before it counts.
Never use Bevy's gamepad order under Splitscreen Club: a seat's controller is a host
token.
fn steer(
gn: Res<GameNight>,
mut game: ResMut<Match>,
mut balls: Query<&mut Ball>,
time: Res<Time>,
) {
let dt = time.delta_secs();
game.present = balls.iter().map(|b| b.seat).collect();
for mut ball in &mut balls {
ball.dash = (ball.dash - dt).max(-0.6);
ball.stunned = (ball.stunned - dt).max(0.0);
if ball.bot || ball.stunned > 0.0 {
continue;
}
let pad = gn.pad(ball.seat);
let target = pad.stick(0)
+ Vec2::new(
pad.pressed(PadButton::Right) as i32 as f32
- pad.pressed(PadButton::Left) as i32 as f32,
pad.pressed(PadButton::Up) as i32 as f32
- pad.pressed(PadButton::Down) as i32 as f32,
);
let target = target.clamp_length_max(1.0) * SPEED;
ball.velocity = ball.velocity.lerp(target, (dt * 12.0).min(1.0));
let dash = pad.just_pressed(PadButton::A) || std::mem::take(&mut ball.phone_dash);
if dash && ball.dash <= -0.6 {
let dir = if target != Vec2::ZERO {
target.normalize()
} else {
ball.velocity.normalize_or(Vec2::X)
};
ball.velocity = dir * DASH_SPEED;
ball.dash = 0.18;
}
}
}
Source: sdk/bevy/demo/src/main.rs
AI seats get bots, empty seats get nothing. rumble(seat, weak, strong, seconds) vibrates a pad; standalone it drives the local gamepad.
Declare settings, phone buttons and a phone screen
Declare once at startup; the plugin declares again after each reconnect, and
Splitscreen Club replays the values the party picked. A player scope gives every
player a value of their own, which arrives as PlayerSettings.
fn settings() -> Vec<SettingSpec> {
vec![
SettingSpec {
key: "round_seconds".into(),
label: "Round length (next round)".into(),
description: Some("Seconds per round.".into()),
kind: SettingKind::Number {
default: 60,
min: 20,
max: 180,
},
scope: SettingScope::Party,
},
SettingSpec {
key: "stars".into(),
label: "Stars".into(),
description: None,
kind: SettingKind::Choice {
default: "normal".into(),
options: vec!["few".into(), "normal".into(), "lots".into()],
},
scope: SettingScope::Party,
},
SettingSpec {
key: "bombs".into(),
label: "Bombs".into(),
description: Some("Bombs flash, then knock stars out of everyone nearby.".into()),
kind: SettingKind::Toggle { default: true },
scope: SettingScope::Party,
},
SettingSpec {
key: "shape".into(),
label: "My shape".into(),
description: Some("Every player picks their own.".into()),
kind: SettingKind::Choice {
default: "round".into(),
options: vec!["round".into(), "square".into()],
},
scope: SettingScope::Player,
},
]
}
Source: sdk/bevy/demo/src/main.rs
/// Declare once; the plugin declares again after a reconnect.
fn declare(mut gn: ResMut<GameNight>) {
gn.declare_settings(settings());
gn.declare_actions(vec![GameAction {
key: "new_round".into(),
label: "New round".into(),
description: Some("Ends this round for everyone.".into()),
confirm: true,
}]);
gn.declare_companion_folder("phone", "index.html");
gn.declare_commands(
"Change the round length, the number of stars or bombs.",
vec![
"90 second rounds".into(),
"lots of stars".into(),
"no bombs".into(),
],
);
}
Source: sdk/bevy/demo/src/main.rs
declare_companion_folder looks for a relative folder next to the executable,
under BEVY_ASSET_ROOT or CARGO_MANIFEST_DIR, then the working directory.
Ship the folder with your build. The page loads /assets/companion.js; see
Phone screens and the demo's
phone page.
Plain-text requests from the Splitscreen Club app or the session assistant arrive as
GameCommand. Answer every one with command_result:
fn command(gn: &mut GameNight, text: &str) -> (bool, String) {
let text = text.to_lowercase();
if let Some(n) = text
.split(|c: char| !c.is_ascii_digit())
.find_map(|w| w.parse::<i64>().ok())
{
let n = n.clamp(20, 180);
gn.set_setting("round_seconds", SettingValue::Number(n));
return (
true,
format!("Rounds last {n} seconds from the next round."),
);
}
for (word, value) in [
("few", "few"),
("less", "few"),
("lots", "lots"),
("more", "lots"),
("normal", "normal"),
] {
if text.contains(word) && text.contains("star") {
gn.set_setting("stars", SettingValue::Choice(value.into()));
return (true, format!("Stars: {value}."));
}
}
if text.contains("bomb") {
let on = !(text.contains("no ") || text.contains("off") || text.contains("geen"));
gn.set_setting("bombs", SettingValue::Toggle(on));
return (true, format!("Bombs {}.", if on { "on" } else { "off" }));
}
(
false,
"I can change the round length, the stars and the bombs.".into(),
)
}
Source: sdk/bevy/demo/src/main.rs
The Start menu
Start opens your own menu, for everyone; Back belongs to Splitscreen Club. The game's
name heads the menu, then Resume, then New round, then the settings, without
button hints. The menu changes settings through set_setting, so the change
also shows in the apps and comes back as SettingChanged (standalone too).
/// Start opens and closes the menu for everyone; any player can use it.
/// Back is never read: it belongs to GameNight.
fn menu_input(
mut commands: Commands,
mut gn: ResMut<GameNight>,
mut menu: ResMut<Menu>,
mut game: ResMut<Match>,
art: Res<Art>,
) {
if !gn.is_running() {
return;
}
let seats: Vec<u8> = gn.seats.iter().map(|s| s.index).collect();
for seat in seats {
let pad = gn.pad(seat);
if pad.just_pressed(PadButton::Start) {
menu.open = !menu.open;
menu.row = 0;
continue;
}
if !menu.open {
continue;
}
let vertical =
pad.just_pressed(PadButton::Down) as i32 - pad.just_pressed(PadButton::Up) as i32;
menu.row = (menu.row as i32 + vertical).rem_euclid(MENU_ROWS.len() as i32) as usize;
let step =
pad.just_pressed(PadButton::Right) as i64 - pad.just_pressed(PadButton::Left) as i64;
let row = MENU_ROWS[menu.row];
match row {
"Resume" if pad.just_pressed(PadButton::A) || pad.just_pressed(PadButton::B) => {
menu.open = false
}
"New round" if pad.just_pressed(PadButton::A) => {
menu.open = false;
new_round(&mut commands, &mut game, &art);
}
"Resume" | "New round" => {
if pad.just_pressed(PadButton::B) {
menu.open = false;
}
}
key => {
let step = if pad.just_pressed(PadButton::A) && step == 0 {
1
} else {
step
};
if step != 0 {
let next = next_value(key, &game.rules.value(key), step);
// Through GameNight, so the apps show the same value.
gn.set_setting(key, next);
}
if pad.just_pressed(PadButton::B) {
menu.open = false;
}
}
}
}
}
Source: sdk/bevy/demo/src/main.rs
Rounds keep going
At the end of a round, show the result briefly, put the winner in the room log,
save each player's progress and call finished(). Then start the next round
yourself: finished() does not end the session. Players leave with Back.
fn round_clock(
mut commands: Commands,
mut gn: ResMut<GameNight>,
mut game: ResMut<Match>,
art: Res<Art>,
time: Res<Time>,
) {
let dt = time.delta_secs();
if game.in_results() {
game.results -= dt;
if game.results <= 0.0 {
new_round(&mut commands, &mut game, &art);
}
return;
}
game.clock -= dt;
if game.clock > 0.0 {
return;
}
// Round over: show the result, tell GameNight, save stats, go again.
game.clock = 0.0;
game.results = RESULTS_SECONDS;
let best = game.scores.iter().max_by_key(|e| e.stars).copied();
if let Some(best) = best.filter(|e| e.stars > 0) {
let name = best
.player
.and_then(|id| gn.player(id))
.map_or("A bot".into(), |p| p.name.clone());
gn.room_log(format!(
"{name} wins round {} with {} stars",
game.round, best.stars
));
}
// Lifetime stars and wins follow each profile to the next game night.
for entry in game.scores.clone() {
let Some(id) = entry.player else { continue };
let old = gn.player_data(id).cloned().unwrap_or_else(|| json!({}));
let total = old.get("stars").and_then(|v| v.as_u64()).unwrap_or(0) + entry.stars as u64;
let won = best.is_some_and(|b| b.player == Some(id) && b.stars > 0);
let wins = old.get("wins").and_then(|v| v.as_u64()).unwrap_or(0) + u64::from(won);
gn.save_player_data(id, json!({ "stars": total, "wins": wins }));
}
gn.finished();
}
Source: sdk/bevy/demo/src/main.rs
save_player_data keeps up to 64 KB of JSON with a player's profile between
nights; player_data reads it back. Guests keep it for the night only.
Faces, colours and couch order
avatar_image(player) decodes a player's drawn face into a nearest-filtered
Image plus where the head sits in it. Draw a circle in the skin colour and
put the drawing's head centre on it. hex_color reads profile colours.
/// The body in the player's colour, a head in their skin colour and their face.
fn dress(
commands: &mut Commands,
entity: Entity,
player: Option<&Player>,
seat: u8,
gn: &GameNight,
art: &Art,
images: &mut Assets<Image>,
materials: &mut Assets<ColorMaterial>,
) {
let fallback = bot_color(seat);
let color = hex_color(player.and_then(|p| p.color.as_deref()), fallback);
let skin = hex_color(
player.and_then(|p| p.skin_color.as_deref()),
Color::srgb(0.96, 0.8, 0.66),
);
let square = player
.and_then(|p| gn.player_setting(p.id, "shape"))
.is_some_and(|v| v == SettingValue::Choice("square".into()));
let body = if square {
art.square.clone()
} else {
art.circle.clone()
};
commands.entity(entity).with_children(|parent| {
parent.spawn((
Body,
Mesh2d(body),
MeshMaterial2d(materials.add(color)),
Transform::from_scale(Vec3::splat(BODY)),
));
parent.spawn((
Mesh2d(art.circle.clone()),
MeshMaterial2d(materials.add(skin)),
Transform::from_xyz(0.0, 4.0, 0.1).with_scale(Vec3::splat(HEAD)),
));
match player.and_then(avatar_image) {
Some((image, head)) => {
// Put the head centre of the drawing on the head circle.
let scale = HEAD / head.radius;
let size = Vec2::new(image.width() as f32, image.height() as f32);
let offset = (size / 2.0 - Vec2::from(head.center)) * Vec2::new(1.0, -1.0) * scale;
parent.spawn((
Face,
Sprite {
image: images.add(image),
custom_size: Some(size * scale),
..default()
},
Transform::from_xyz(offset.x, 4.0 + offset.y, 0.2),
));
}
None => {
for x in [-7.0, 7.0] {
parent.spawn((
Mesh2d(art.circle.clone()),
MeshMaterial2d(art.dark.clone()),
Transform::from_xyz(x, 7.0, 0.2).with_scale(Vec3::splat(3.2)),
));
}
}
}
});
}
Source: sdk/bevy/demo/src/main.rs
Lay anything that runs left to right out with couch_order(seats, players):
the order in which players sit, which they choose in the lobby. Call it again
when players update, because people move mid-match.
Host music
When the host plays music, GameNightEvent::HostMusic { playing: true }
arrives and host_music_playing() is true. Mute your music, not your effects,
and turn it back up when it stops.
Run and test
cd sdk/bevy
cargo run -p bevy-demo # standalone: keyboard and gamepads
cargo run -p bevy-demo -- --bots 3 # with three bots
cargo run -p bevy-demo -- --bots 3 --shot star-catch.png
xvfb-run -a cargo test --workspace # plugin tests and the conformance harness
To play it through a development host, start the host and set
GAMENIGHT_ADDR=127.0.0.1:7912 before running the demo. For your own game, run
the harness the same way, with your game id and binary:
cargo run -p gamenight-certify -- my-game --players 2 -- path/to/my-game
What is not covered yet
These were checked on Linux (X11, software rendering) with synthetic controller frames. Windows and macOS window behaviour, the Windows foreground-permission helper the Godot SDK uses on Pause, physical controllers and real audio devices still need testing on hardware. The plugin hides the window rather than minimising it; Alt-Tab back to a paused game goes through the lobby. See Engine support for how this compares with the other engines.