Skip to content

Minecraft: Java Edition 26.3 rewritten from scratch in Rust, checked against vanilla with 281 differential harnesses. Get it with the Horizon launcher.

Add live default game mode to server management

TiggerTakkyTTT3a9559fe3c0f
diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs
index f3ca01e5d..196d438c9 100644
--- a/crates/horizon-client/src/game/dedicated.rs
+++ b/crates/horizon-client/src/game/dedicated.rs
@@ -618,6 +618,8 @@ struct ServerState {
/// View and simulation distance, and the player limit, for the report.
view: (u32, u32),
max_players: usize,
+ /// The mutable `gamemode` server property (`DedicatedServer.gameMode`).
+ game_mode: i32,
}
/// The dedicated-only commands' replies vanilla sends with `broadcast`
@@ -985,6 +987,7 @@ impl Game<'_> {
broadcast_console: props.broadcast_console_to_ops,
broadcast_rcon: props.broadcast_rcon_to_ops,
op_level: props.op_permission_level,
+ game_mode: props.game_mode,
report: None,
view: (
props.view_distance.clamp(2, 32) as u32,
diff --git a/crates/horizon-client/src/game/dedicated/management.rs b/crates/horizon-client/src/game/dedicated/management.rs
index b4139250c..4f3128b48 100644
--- a/crates/horizon-client/src/game/dedicated/management.rs
+++ b/crates/horizon-client/src/game/dedicated/management.rs
@@ -3,7 +3,7 @@
//! `AllowlistService`, `BanlistService`, `IpBanlistService` and `OperatorService` on the running server's lists. Players are found as
//! `MinecraftPlayerListService.getUser` finds them, each change is logged as `JsonRpcLogger` logs it, and the
//! players a change shuts out are disconnected. The supervisor answers with the lists, from their files.
-use super::{ServerState, log};
+use super::{GAME_MODES, ServerState, log};
use crate::game::Game;
use horizon_client::{
command::vanilla::DIFFICULTIES,
@@ -70,6 +70,25 @@ impl Game<'_> {
self.store_property("motd", value.to_owned());
return json!({ "value": value });
}
+ "serversettings/game_mode" => {
+ return json!({ "value": GAME_MODES[state.game_mode as usize] });
+ }
+ "serversettings/game_mode/set" => {
+ let Some(value) = body["value"].as_str() else {
+ return json!({ "error": "game mode must be a string" });
+ };
+ let Some(index) = GAME_MODES.iter().position(|name| *name == value) else {
+ return json!({ "error": format!("unknown game mode {value:?}") });
+ };
+ rpc(format!(
+ "Update game mode from '{}' to '{}'",
+ GAME_MODES[state.game_mode as usize], value
+ ));
+ self.store_property("gamemode", value.to_owned());
+ state.game_mode = index as i32;
+ self.set_default_game_mode(state.game_mode);
+ return json!({ "value": GAME_MODES[state.game_mode as usize] });
+ }
"serversettings/difficulty" => {
return json!({ "value": DIFFICULTIES[self.level.difficulty_id() as usize] });
}
diff --git a/crates/horizon-server/src/management_methods.rs b/crates/horizon-server/src/management_methods.rs
index e032a55d7..1bad12936 100644
--- a/crates/horizon-server/src/management_methods.rs
+++ b/crates/horizon-server/src/management_methods.rs
@@ -50,6 +50,15 @@ pub fn call(shared: &Shared, client: u32, short: &str, argument: &Value) -> Resu
.ok_or_else(|| invalid_params("Not a string"))?,
),
),
+ "serversettings/game_mode" => game.game_mode(client, None),
+ "serversettings/game_mode/set" => game.game_mode(
+ client,
+ Some(
+ argument
+ .as_str()
+ .ok_or_else(|| invalid_params("Not a string"))?,
+ ),
+ ),
"allowlist" => Ok(lists.allowlist()),
"bans" => Ok(lists.bans()),
"ip_bans" => Ok(lists.ip_bans()),
@@ -281,6 +290,29 @@ struct Game<'a> {
}
impl Game<'_> {
+ /// `MinecraftServerSettingsServiceImpl.getGameMode` and `setGameMode`.
+ fn game_mode(&self, client: u32, value: Option<&str>) -> Result<Value, Failure> {
+ let mut request = json!({ "method": "serversettings/game_mode" });
+ if let Some(value) = value {
+ request["method"] = json!("serversettings/game_mode/set");
+ request["value"] = json!(value);
+ }
+ let reply = self.ask(&format!("management {client} {request}"))?;
+ if let Some(error) = reply["error"].as_str() {
+ return Err((INTERNAL_ERROR, Some(error.to_owned())));
+ }
+ if let Some(value) = value {
+ crate::config::update(
+ &self.shared.dir,
+ "world",
+ "game_mode",
+ toml::Value::String(value.into()),
+ )
+ .map_err(|e| (INTERNAL_ERROR, Some(e)))?;
+ }
+ Ok(reply["value"].clone())
+ }
+
/// `MinecraftServerSettingsServiceImpl.getMotd` and `setMotd`: the live server-list message.
fn motd(&self, client: u32, value: Option<&str>) -> Result<Value, Failure> {
let mut request = json!({ "method": "serversettings/motd" });
diff --git a/tools/test_management_protocol_parity.py b/tools/test_management_protocol_parity.py
index 888d16390..587c0df5e 100644
--- a/tools/test_management_protocol_parity.py
+++ b/tools/test_management_protocol_parity.py
@@ -16,7 +16,7 @@ sent the same things over TLS, and every answer is compared exactly:
vanilla's data generator), `server/status`, the four lists, `players`, kicking nobody, `server/save` and
`server/system_message` with no one online, the four lists changed (`add`, `remove`, `set`,
`clear`; with no profile service, players named resolve to offline players on both), the live server
- message and the difficulty read and changed (an empty message, the saved difficulty property), and
+ message, difficulty and default game mode read and changed (including their saved properties), and
`server/stop`;
- the TLS version each server agrees on.
@@ -133,6 +133,11 @@ MESSAGES = [
'{"jsonrpc":"2.0","id":47,"method":"minecraft:serversettings/difficulty"}',
'{"jsonrpc":"2.0","id":48,"method":"minecraft:serversettings/difficulty/set","params":["peaceful"]}',
'{"jsonrpc":"2.0","id":49,"method":"minecraft:serversettings/difficulty"}',
+ '{"jsonrpc":"2.0","id":50,"method":"minecraft:serversettings/game_mode"}',
+ '{"jsonrpc":"2.0","id":51,"method":"minecraft:serversettings/game_mode/set","params":["creative"]}',
+ '{"jsonrpc":"2.0","id":52,"method":"minecraft:serversettings/game_mode"}',
+ '{"jsonrpc":"2.0","id":53,"method":"minecraft:serversettings/game_mode/set","params":["spectator"]}',
+ '{"jsonrpc":"2.0","id":54,"method":"minecraft:serversettings/game_mode"}',
]
@@ -352,9 +357,13 @@ def main():
sides[side]['saved_difficulty'] = next(
(line.partition('=')[2] for line in properties.splitlines()
if line.startswith('difficulty=')), None)
+ sides[side]['saved_game_mode'] = next(
+ (line.partition('=')[2] for line in properties.splitlines()
+ if line.startswith('gamemode=')), None)
if side == 'horizon':
world = (folder / 'server.toml').read_text().partition('[world]')[2].split('\n[', 1)[0]
sides[side]['saved_config_difficulty'] = 'difficulty = "peaceful"' in world
+ sides[side]['saved_config_game_mode'] = 'game_mode = "spectator"' in world
finally:
server.stop()
vanilla, horizon = sides['vanilla'], sides['horizon']
@@ -369,6 +378,10 @@ def main():
failures.append(f"saved difficulty: vanilla {vanilla['saved_difficulty']!r}, Horizon {horizon['saved_difficulty']!r}")
if not horizon['saved_config_difficulty']:
failures.append('Horizon did not save peaceful difficulty in server.toml')
+ if vanilla['saved_game_mode'] != horizon['saved_game_mode'] or vanilla['saved_game_mode'] != 'spectator':
+ failures.append(f"saved game mode: vanilla {vanilla['saved_game_mode']!r}, Horizon {horizon['saved_game_mode']!r}")
+ if not horizon['saved_config_game_mode']:
+ failures.append('Horizon did not save spectator game mode in server.toml')
(build / 'report.json').write_text(json.dumps(sides, indent=1))
report = lab.LOCAL / 'datagen/out/reports/json-rpc-api-schema.json'
discovered = horizon['answers'][MESSAGES.index('{"jsonrpc":"2.0","id":12,"method":"rpc.discover"}')]