Merge pull request #1955 from rdbtCVS/t3/migrate-parity-server-thread
🤖 Agent: Thanks rdbt! The command, dispenser and sculk fixtures now run on a server Game. Checked:
This commit is contained in:
@@ -352,10 +352,7 @@ impl Options {
|
||||
dedicated: None,
|
||||
benchmark: None,
|
||||
dev_mods: Vec::new(),
|
||||
// The command harness (HORIZON_COMMAND_SCRIPT) drives the world
|
||||
// itself, without the event loop: it stays in the frame.
|
||||
server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0")
|
||||
&& std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(),
|
||||
server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0"),
|
||||
execution_role: execution_role::ExecutionRole::Client,
|
||||
};
|
||||
let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok();
|
||||
@@ -13172,11 +13169,11 @@ fn start_game<'a>(
|
||||
);
|
||||
}
|
||||
if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") {
|
||||
game.dispense_fixture(&spec)?;
|
||||
game.run_component_harness(integrated::ComponentHarness::Dispenser(spec))?;
|
||||
return Ok(None);
|
||||
}
|
||||
if let Ok(spec) = std::env::var("HORIZON_SCULK_FIXTURE") {
|
||||
game.sculk_fixture(&spec)?;
|
||||
game.run_component_harness(integrated::ComponentHarness::Sculk(spec))?;
|
||||
return Ok(None);
|
||||
}
|
||||
if game.options.execution_role == execution_role::ExecutionRole::DedicatedServer {
|
||||
@@ -13198,8 +13195,8 @@ fn start_game<'a>(
|
||||
Some(folder) => {
|
||||
let (seed, creative) = (game.options.seed, game.options.creative);
|
||||
if std::env::var_os("HORIZON_COMMAND_SCRIPT").is_some() {
|
||||
// The command harness runs before entering the window loop.
|
||||
game.open_world(&folder, None, Some(seed), creative, None)?;
|
||||
// Headless, but with the same server and memory connection as play.
|
||||
game.open_integrated(&folder, None, Some(seed), creative, None)?;
|
||||
} else {
|
||||
// Start after the window is handed over, so --world uses the
|
||||
// same responsive initialization path as the title screen.
|
||||
@@ -13226,11 +13223,10 @@ fn start_game<'a>(
|
||||
game.title = Some(title);
|
||||
}
|
||||
}
|
||||
if let (Some(script), Some(output)) = (
|
||||
std::env::var_os("HORIZON_COMMAND_SCRIPT"),
|
||||
std::env::var_os("HORIZON_COMMAND_OUTPUT"),
|
||||
) {
|
||||
game.run_command_harness(script.as_ref(), output.as_ref())?;
|
||||
if std::env::var_os("HORIZON_COMMAND_SCRIPT").is_some()
|
||||
&& std::env::var_os("HORIZON_COMMAND_OUTPUT").is_some()
|
||||
{
|
||||
game.wait_command_harness()?;
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(game))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Headless command runner for `tools/test_command_exec_parity.py`: with
|
||||
//! `HORIZON_COMMAND_SCRIPT` and `HORIZON_COMMAND_OUTPUT` set, the opened world
|
||||
//! runs without a window. Each script line is a JSON operation: `cmd` runs a
|
||||
//! runs on its server thread with a connected, headless client. Each script
|
||||
//! line is a JSON operation: `cmd` runs a
|
||||
//! command as the player (Commands.performPrefixedCommand) and records every
|
||||
//! system message it produced, as styled spans, with the results reported to
|
||||
//! the player's `CommandResultCallback`; `tick` advances the game; `settle`
|
||||
@@ -41,30 +42,100 @@ pub(super) fn spans(text: &Text) -> Value {
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Pump the real client's connection, without predicting movement: the
|
||||
/// oracle's player stays where commands put it. Errors cross the server
|
||||
/// boundary through Integrated::stop, including script and save failures.
|
||||
pub(super) fn wait_command_harness(&mut self) -> Result<()> {
|
||||
let server = self.integrated.take().ok_or("command harness: no server")?;
|
||||
while !server.stopped() {
|
||||
self.poll_stationary_client()?;
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
server.stop()
|
||||
}
|
||||
|
||||
/// The owner's authoritative body and level, using the same swaps as a
|
||||
/// server command. Always put them back, also when a script operation fails.
|
||||
fn harness_owner<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
|
||||
let owner = self
|
||||
.serving
|
||||
.as_ref()
|
||||
.ok_or("command harness: not a server")?
|
||||
.owner;
|
||||
let mut host = self.lan.take().ok_or("command harness: no hub")?;
|
||||
let guest = host.hub.guests.iter().find(|g| g.uuid == owner && g.placed);
|
||||
let Some(guest) = guest else {
|
||||
self.lan = Some(host);
|
||||
return Err("command harness: owner is not connected".into());
|
||||
};
|
||||
let (conn, dim, back) = (guest.conn, super::Dim::from_id(&guest.dimension), self.dim);
|
||||
if let Err(error) = self.enter_level(Some(&mut host), dim) {
|
||||
self.lan = Some(host);
|
||||
return Err(error);
|
||||
}
|
||||
let swap = self
|
||||
.enter_guest(&mut host, conn)
|
||||
.expect("the owner is not already acting");
|
||||
self.lan = Some(host);
|
||||
let result = f(self);
|
||||
let mut host = self.lan.take().expect("the operation puts the hub back");
|
||||
self.leave_guest(&mut host, swap);
|
||||
host.hub.sync_all_effects();
|
||||
self.run_level_teleports(&mut host);
|
||||
let restored = self.enter_level(Some(&mut host), back);
|
||||
self.lan = Some(host);
|
||||
restored?;
|
||||
result
|
||||
}
|
||||
|
||||
/// The player's portal process finished in the nether portal it stands
|
||||
/// in (the oracle's player is not ticked, so neither is the wait).
|
||||
fn harness_portal(&mut self) -> Result<()> {
|
||||
let Some(p) = &self.player else {
|
||||
return Err("command harness: portal without a player".into());
|
||||
};
|
||||
let entry = horizon_core::position::BlockPos::containing(p.position);
|
||||
let block = self.world.block(entry.x, entry.y, entry.z);
|
||||
if &*self.res.facts().get(block).name != "minecraft:nether_portal" {
|
||||
return Err("command harness: the player is not in a nether portal".into());
|
||||
}
|
||||
self.player_through_nether_portal(entry)
|
||||
let (conn, plan) = self.harness_owner(|g| {
|
||||
let p = g
|
||||
.player
|
||||
.as_ref()
|
||||
.ok_or("command harness: portal without a player")?;
|
||||
let entry = horizon_core::position::BlockPos::containing(p.position);
|
||||
let block = g.world.block(entry.x, entry.y, entry.z);
|
||||
if &*g.res.facts().get(block).name != "minecraft:nether_portal" {
|
||||
return Err("command harness: the player is not in a nether portal".into());
|
||||
}
|
||||
let plan = g.portal_plan(
|
||||
entry,
|
||||
p.position,
|
||||
p.dimensions.width,
|
||||
p.dimensions.height,
|
||||
true,
|
||||
);
|
||||
Ok((
|
||||
g.lan_acting.ok_or("command harness: no acting owner")?,
|
||||
plan,
|
||||
))
|
||||
})?;
|
||||
// Start travel after restoring the owner's body: change_level updates
|
||||
// its hub record, which leave_guest would otherwise overwrite.
|
||||
self.in_owner_level(|g| {
|
||||
let mut host = g.lan.take().ok_or("command harness: no hub")?;
|
||||
g.start_server_trip(&mut host, conn, plan.dim, Some(plan));
|
||||
g.lan = Some(host);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
/// Load terrain until the player stands in lit chunks.
|
||||
fn harness_settle(&mut self, deadline: Instant) -> Result<()> {
|
||||
loop {
|
||||
self.update_world();
|
||||
self.spawn_player()?;
|
||||
if let Some(p) = &self.player {
|
||||
let (cx, cz) = (
|
||||
(p.position.x.floor() as i32) >> 4,
|
||||
(p.position.z.floor() as i32) >> 4,
|
||||
);
|
||||
if (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
|
||||
// Finish requested terrain before inspecting it, so worker
|
||||
// timing cannot change which command positions are loaded.
|
||||
if !self.streaming.busy()
|
||||
&& (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz)))
|
||||
{
|
||||
// The oracle's settle also waits for the entities saved
|
||||
// in those chunks (areEntitiesActuallyLoadedAndTicking):
|
||||
// after a dimension change they come back from the save.
|
||||
@@ -95,7 +166,19 @@ impl Game<'_> {
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(600),
|
||||
);
|
||||
self.harness_settle(deadline)?;
|
||||
// Join/configuration uses the normal hub, but never advances the world.
|
||||
while !self
|
||||
.lan
|
||||
.as_ref()
|
||||
.is_some_and(|h| h.hub.guests.iter().any(|g| g.placed && g.loaded))
|
||||
{
|
||||
self.tick_server(true)?;
|
||||
if Instant::now() > deadline {
|
||||
return Err("command harness: owner did not connect".into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
self.harness_owner(|g| g.harness_settle(deadline))?;
|
||||
let mut out = String::new();
|
||||
for line in std::fs::read_to_string(script)?.lines() {
|
||||
if line.trim().is_empty() {
|
||||
@@ -107,9 +190,12 @@ impl Game<'_> {
|
||||
let command = op["cmd"].as_str().unwrap_or("");
|
||||
self.chat_capture = Some(Vec::new());
|
||||
self.cmds.results = Some(Vec::new());
|
||||
self.as_console(|g| {
|
||||
g.run_command(command.strip_prefix('/').unwrap_or(command))
|
||||
});
|
||||
self.harness_owner(|g| {
|
||||
g.as_console(|g| {
|
||||
g.run_command(command.strip_prefix('/').unwrap_or(command))
|
||||
});
|
||||
Ok(())
|
||||
})?;
|
||||
let messages = self.chat_capture.take().unwrap_or_default();
|
||||
let results = self.cmds.results.take().unwrap_or_default();
|
||||
if op["record"].as_bool() != Some(false) {
|
||||
@@ -124,17 +210,8 @@ impl Game<'_> {
|
||||
}
|
||||
"tick" => {
|
||||
self.chat_capture = Some(Vec::new());
|
||||
// The oracle's player has no client moving it: hold the
|
||||
// player where commands put it while the game ticks.
|
||||
let held = self.player.as_ref().map(|p| p.position);
|
||||
for _ in 0..op["n"].as_u64().unwrap_or(1) {
|
||||
self.update_world();
|
||||
self.tick()?;
|
||||
if let (Some(p), Some(at)) = (self.player.as_mut(), held) {
|
||||
p.position = at;
|
||||
p.velocity = horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0);
|
||||
p.fall_distance = 0.0;
|
||||
}
|
||||
self.tick_server(false)?;
|
||||
}
|
||||
let messages = self.chat_capture.take().unwrap_or_default();
|
||||
if op["record"].as_bool() == Some(true) {
|
||||
@@ -147,7 +224,17 @@ impl Game<'_> {
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
"settle" => self.harness_settle(deadline)?,
|
||||
"settle" => {
|
||||
// Finish portal arrivals using connection-only passes too.
|
||||
while !self.server_trips.is_empty() {
|
||||
self.tick_server(true)?;
|
||||
if Instant::now() > deadline {
|
||||
return Err("command harness: portal did not arrive".into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
self.harness_owner(|g| g.harness_settle(deadline))?;
|
||||
}
|
||||
"portal" => self.harness_portal()?,
|
||||
other => return Err(format!("command harness: unknown op {other}").into()),
|
||||
}
|
||||
|
||||
@@ -752,7 +752,8 @@ impl Game<'_> {
|
||||
&& !id.ends_with("get")
|
||||
&& let Ok(t) = self.entities(ctx, "target", false)
|
||||
{
|
||||
self.cmds.waypoint_dirty.push(t[0]);
|
||||
let target = self.waypoint_target(t[0]);
|
||||
self.cmds.waypoint_dirty.push(target);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
@@ -214,8 +214,22 @@ impl Game<'_> {
|
||||
|
||||
// ---- /waypoint ------------------------------------------------------
|
||||
|
||||
/// A guest's body is only `Player` during its turn; retained command state
|
||||
/// must use its connection so the next server tick still finds that body.
|
||||
pub(super) fn waypoint_target(&self, t: Target) -> Target {
|
||||
match t {
|
||||
Target::Player => self.lan_acting.map_or(t, Target::Guest),
|
||||
_ => t,
|
||||
}
|
||||
}
|
||||
|
||||
/// A living entity's `waypoint_transmit_range` (`isTransmittingWaypoint`).
|
||||
fn transmit_range(&mut self, t: Target) -> f64 {
|
||||
if matches!(t, Target::Guest(_)) {
|
||||
return self
|
||||
.for_player(t, |g| g.transmit_range(Target::Player))
|
||||
.unwrap_or(0.0);
|
||||
}
|
||||
if t == Target::Player {
|
||||
return self
|
||||
.player
|
||||
@@ -244,7 +258,7 @@ impl Game<'_> {
|
||||
fn waypoint_transmitters(&mut self) -> Vec<Target> {
|
||||
if self.cmds.waypoints.is_none() {
|
||||
let tracked = if self.transmit_range(Target::Player) > 0.0 {
|
||||
vec![Target::Player]
|
||||
vec![self.waypoint_target(Target::Player)]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
@@ -257,6 +271,12 @@ impl Game<'_> {
|
||||
.collect();
|
||||
self.cmds.waypoints = Some(alive.clone());
|
||||
alive
|
||||
.into_iter()
|
||||
.map(|t| match t {
|
||||
Target::Guest(conn) if self.lan_acting == Some(conn) => Target::Player,
|
||||
_ => t,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
/// The waypoint part of a living entity's tick: dirty transmit ranges
|
||||
/// track or untrack it.
|
||||
@@ -279,7 +299,7 @@ impl Game<'_> {
|
||||
fn waypoint_icon(&self, t: Target) -> WaypointIcon {
|
||||
self.cmds
|
||||
.waypoint_icons
|
||||
.get(&t)
|
||||
.get(&self.waypoint_target(t))
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -389,6 +409,7 @@ impl Game<'_> {
|
||||
&[Text::colored(name, rgb)],
|
||||
)
|
||||
};
|
||||
let t = self.waypoint_target(t);
|
||||
self.cmds.waypoint_icons.insert(t, icon);
|
||||
// WaypointCommand.mutateIcon: untrack, change, track again.
|
||||
self.waypoint_transmitters();
|
||||
@@ -608,6 +629,7 @@ impl Game<'_> {
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| lan.hub.singleplayer_owner != Some(g.uuid))
|
||||
.filter(|g| match &s.player_name {
|
||||
Some(name) => g.name.eq_ignore_ascii_case(name),
|
||||
None => s.kind == 'a' || s.kind == 'e',
|
||||
@@ -619,7 +641,7 @@ impl Game<'_> {
|
||||
if host.is_empty() && guests.is_empty() {
|
||||
return Err(err("argument.entity.notfound.player", &[]));
|
||||
}
|
||||
if self.lan.is_none() {
|
||||
if self.lan.is_none() || (self.serving() && self.published_port().is_none()) {
|
||||
return Err(err("commands.kick.singleplayer.failed", &[]));
|
||||
}
|
||||
let reason_raw = match ctx.get("reason") {
|
||||
|
||||
@@ -90,6 +90,10 @@ enum Target {
|
||||
impl Game<'_> {
|
||||
/// Run every case of `spec` ("CASES,OUTPUT") and write the results.
|
||||
pub(super) fn dispense_fixture(&mut self, spec: &str) -> Result<()> {
|
||||
assert!(
|
||||
!self.options.execution_role.is_client(),
|
||||
"fixture requires a server Game"
|
||||
);
|
||||
let (input, output) = spec
|
||||
.split_once(',')
|
||||
.ok_or("HORIZON_DISPENSE_FIXTURE=CASES,OUTPUT")?;
|
||||
|
||||
@@ -143,7 +143,7 @@ pub(super) struct Serving {
|
||||
flags: Arc<Flags>,
|
||||
tasks: Receiver<Task>,
|
||||
/// The window's profile.
|
||||
owner: u128,
|
||||
pub(super) owner: u128,
|
||||
/// Open to LAN or closed from inside a player's command, while the hub
|
||||
/// is out of its place: applied after the tick.
|
||||
pending: Option<Publish>,
|
||||
@@ -357,6 +357,16 @@ impl Game<'_> {
|
||||
});
|
||||
let _ = ready.send(Ok((pipe, self.level.name.clone())));
|
||||
self.settle_spawn()?;
|
||||
if let (Some(script), Some(output)) = (
|
||||
std::env::var_os("HORIZON_COMMAND_SCRIPT"),
|
||||
std::env::var_os("HORIZON_COMMAND_OUTPUT"),
|
||||
) {
|
||||
// The script owns the clock: connection setup and terrain loading
|
||||
// cannot add wall-clock-dependent world ticks to oracle output.
|
||||
let result = self.run_command_harness(script.as_ref(), output.as_ref());
|
||||
let stopped = self.stop_integrated();
|
||||
return result.and(stopped);
|
||||
}
|
||||
let mut next = Instant::now();
|
||||
while !flags.stop.load(Ordering::Relaxed) {
|
||||
self.run_tasks();
|
||||
@@ -692,6 +702,48 @@ fn serve(
|
||||
tasks: Receiver<Task>,
|
||||
ready: &Sender<Ready>,
|
||||
) -> Result<()> {
|
||||
let mut server = server_game(res, pack, options, settings)?;
|
||||
server.run_integrated(launch, flags, tasks, ready)
|
||||
}
|
||||
|
||||
/// Component oracles supply their own synthetic levels and entity phases.
|
||||
/// They still execute on a server Game, never the client's world.
|
||||
pub(super) enum ComponentHarness {
|
||||
Dispenser(String),
|
||||
Sculk(String),
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
pub(super) fn run_component_harness(&self, fixture: ComponentHarness) -> Result<()> {
|
||||
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
|
||||
let mut options = self.options.clone();
|
||||
options.execution_role = ExecutionRole::IntegratedServer;
|
||||
options.dedicated = Some(Vec::new());
|
||||
options.server_thread = false;
|
||||
let result = std::thread::Builder::new()
|
||||
.name("Server thread".into())
|
||||
.spawn(move || {
|
||||
let run = || -> Result<()> {
|
||||
let mut server = server_game(&res, pack, options, settings)?;
|
||||
match fixture {
|
||||
ComponentHarness::Dispenser(spec) => server.dispense_fixture(&spec),
|
||||
ComponentHarness::Sculk(spec) => server.sculk_fixture(&spec),
|
||||
}
|
||||
};
|
||||
run().map_err(|e| e.to_string())
|
||||
})?
|
||||
.join()
|
||||
.map_err(|_| "the component harness server panicked")?;
|
||||
result.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
fn server_game(
|
||||
res: &Arc<Resources>,
|
||||
pack: PackResources,
|
||||
options: Options,
|
||||
settings: Settings,
|
||||
) -> Result<Game<'_>> {
|
||||
// It draws nothing: only the font, which books and chat measure with.
|
||||
let atlas = HudAtlas::fonts(&options.resources)?;
|
||||
let gui = UiResources {
|
||||
@@ -702,8 +754,7 @@ fn serve(
|
||||
}),
|
||||
};
|
||||
let audio = Audio::silent(&options.resources);
|
||||
let mut server = Game::new(res, pack, gui, options, settings, audio, None)?;
|
||||
server.run_integrated(launch, flags, tasks, ready)
|
||||
Game::new(res, pack, gui, options, settings, audio, None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -21,7 +21,7 @@ use super::{
|
||||
use horizon_client::{
|
||||
Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections,
|
||||
save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership,
|
||||
ticket_levels::ChunkTickets, world::World,
|
||||
ticket_levels::ChunkTickets, vanillagen::VanillaTerrain, world::World,
|
||||
};
|
||||
use horizon_world::level::{LevelEvent, Ticks};
|
||||
use std::{
|
||||
@@ -39,6 +39,7 @@ const IDLE_TICKS: u32 = 300;
|
||||
pub(super) struct Parked {
|
||||
world: World,
|
||||
streaming: Streaming,
|
||||
locator: Option<Arc<VanillaTerrain>>,
|
||||
save: Arc<SaveDir>,
|
||||
block_ticks: Ticks,
|
||||
tick_chunks: TickChunkMembership,
|
||||
@@ -109,13 +110,21 @@ pub(super) struct Levels {
|
||||
impl Game<'_> {
|
||||
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
|
||||
fn open_level(&self, dim: Dim) -> Result<Parked> {
|
||||
let (streaming, save) =
|
||||
self.make_streaming(&self.world_root.clone(), dim, self.level.seed)?;
|
||||
let (streaming, save, locator) = super::world_loading::make_streaming(
|
||||
&self.res,
|
||||
&self.pack,
|
||||
&self.options,
|
||||
&self.settings,
|
||||
&self.world_root,
|
||||
dim,
|
||||
self.level.seed,
|
||||
)?;
|
||||
let mut world = World::new(self.res.facts().air, self.level.seed);
|
||||
world.fast_lava = dim == Dim::Nether;
|
||||
Ok(Parked {
|
||||
world,
|
||||
streaming,
|
||||
locator,
|
||||
save,
|
||||
block_ticks: Ticks::new(self.level.seed as i32),
|
||||
tick_chunks: Default::default(),
|
||||
@@ -163,6 +172,9 @@ impl Game<'_> {
|
||||
use std::mem::swap;
|
||||
swap(&mut self.world, &mut p.world);
|
||||
swap(&mut self.streaming, &mut p.streaming);
|
||||
let mut locator = self.end.locator();
|
||||
swap(&mut locator, &mut p.locator);
|
||||
self.end.set_locator(locator);
|
||||
swap(&mut self.save, &mut p.save);
|
||||
swap(&mut self.block_ticks, &mut p.block_ticks);
|
||||
swap(&mut self.tick_chunks, &mut p.tick_chunks);
|
||||
|
||||
@@ -720,6 +720,23 @@ impl Game<'_> {
|
||||
pub(super) fn remote_backlog(&self) -> usize {
|
||||
self.remote.as_ref().map_or(0, |r| r.backlog.len())
|
||||
}
|
||||
/// A headless command oracle has a real connection but no movement tick.
|
||||
/// Acknowledge loaded terrain without predicting or sending movement.
|
||||
pub(super) fn poll_stationary_client(&mut self) -> Result<()> {
|
||||
self.poll_remote()?;
|
||||
let loaded = self.player.as_ref().is_some_and(|p| {
|
||||
self.streaming.is_lit(
|
||||
(p.position.x.floor() as i32) >> 4,
|
||||
(p.position.z.floor() as i32) >> 4,
|
||||
)
|
||||
});
|
||||
if loaded && self.remote.as_ref().is_some_and(|r| !r.loaded_sent) {
|
||||
self.send(S::PlayerLoaded(Empty));
|
||||
self.remote.as_mut().unwrap().loaded_sent = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Process what the network thread received (once per frame, like the
|
||||
/// client's packet processor), in order. Chunk packets get
|
||||
/// `CHUNK_PACKETS_PER_FRAME`: once a frame has spent it, the events from
|
||||
|
||||
@@ -156,6 +156,10 @@ const CLIENT_SOUNDS: &[&str] = &[
|
||||
impl Game<'_> {
|
||||
/// Run every scenario of `spec` ("SCENARIOS,OUTPUT") and write the results.
|
||||
pub(super) fn sculk_fixture(&mut self, spec: &str) -> Result<()> {
|
||||
assert!(
|
||||
!self.options.execution_role.is_client(),
|
||||
"fixture requires a server Game"
|
||||
);
|
||||
let (input, output) = spec
|
||||
.split_once(',')
|
||||
.ok_or("HORIZON_SCULK_FIXTURE=SCENARIOS,OUTPUT")?;
|
||||
|
||||
@@ -170,7 +170,7 @@ impl Game<'_> {
|
||||
/// The player moves to `target`'s level (opened if nobody was there)
|
||||
/// and is told it is there, at the approximate exit, while it loads. The
|
||||
/// level whose tick is running is put back in place afterwards.
|
||||
fn start_server_trip(
|
||||
pub(super) fn start_server_trip(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
|
||||
@@ -80,6 +80,34 @@ An agent working an area merges the integration branch first, uses `tools/parity
|
||||
|
||||
On ludodesktop, source `~/code/horizon-parity/env.sh` first: it sets the ALSA build path and the Cargo job cap. Debug builds carry line tables only (`[profile.dev]` in `Cargo.toml`), which keeps backtraces readable while keeping each worktree's build small; a fresh worktree builds `horizon-client` and its tests in under a minute.
|
||||
|
||||
## Server execution in game fixtures
|
||||
|
||||
`HORIZON_COMMAND_SCRIPT` runs on the integrated server's `Server thread`, with the
|
||||
headless client joined through the normal memory connection. Commands use the connected
|
||||
owner's body and dimension. The script owns the clock: each `tick` calls `tick_server`,
|
||||
while login and portal arrival pump connection-only passes. The client acknowledges
|
||||
terrain and teleports without predicting movement, matching the command oracle's stationary
|
||||
player. Script and save errors return through server shutdown; output keeps the existing
|
||||
styled messages and `CommandResultCallback` schema. `--in-frame` is not needed.
|
||||
|
||||
`HORIZON_DISPENSE_FIXTURE` and `HORIZON_SCULK_FIXTURE` are component probes. They construct
|
||||
a server `Game` on a server thread and retain the oracles' synthetic levels, seeded random
|
||||
streams and explicit entity/block phases. A synthetic sculk player controls warning levels,
|
||||
not client input; dispenser probes call one activation without running unrelated world ticks.
|
||||
Keep those controls when extending the fixtures. Player interactions belong in connected-client
|
||||
coverage alongside the components:
|
||||
|
||||
```sh
|
||||
python3 tools/test_command_exec_parity.py
|
||||
python3 tools/test_dispenser_parity.py
|
||||
python3 tools/test_sculk_parity.py
|
||||
python3 tools/lan_e2e.py --server-thread --check machines --check fireball --check sculk_container
|
||||
```
|
||||
|
||||
The LAN checks open and fill machines through the guest's inventory packets, observe a
|
||||
powered dispenser's projectile on both clients, and open a chest to activate a sculk sensor
|
||||
and shrieker. They supplement the deterministic component comparisons.
|
||||
|
||||
## Reading vanilla
|
||||
|
||||
Besides the Vineflower sources in `.local/minecraft/<version>/sources/`, `tools/rea_vanilla.py` queries the shipped bytecode through REA (callers through lambdas, overloads, a second decompiler); see [decompilation status](decompilation-status.md#querying-the-shipped-bytecode-with-rea).
|
||||
|
||||
@@ -628,7 +628,9 @@ def world_misc():
|
||||
cmd('/fill 0 210 0 2 212 2 minecraft:glass keep'),
|
||||
cmd('/fill 0 210 0 2 212 2 minecraft:dirt replace #minecraft:base_stone_overworld'),
|
||||
cmd('/fill 0 210 0 2 212 2 minecraft:air strict'),
|
||||
cmd('/fill 0 210 0 100 300 100 minecraft:stone'),
|
||||
# A connected server loads more terrain than the oracle's 5x5 core.
|
||||
# Keep the far corner unambiguously unloaded in both executions.
|
||||
cmd('/fill 0 210 0 1000 300 1000 minecraft:stone'),
|
||||
cmd('/setblock 0 211 0 minecraft:oak_sign{front_text:{messages:["a","b","c","d"]}}'),
|
||||
cmd('/data get block 0 211 0 front_text.messages'),
|
||||
cmd('/clone 0 211 0 0 211 0 1 211 1 replace move'),
|
||||
@@ -831,6 +833,9 @@ def functions_and_packs():
|
||||
|
||||
def ticking():
|
||||
return [
|
||||
# Isolate named-stream commands from earlier loot rolls, including
|
||||
# ocean vegetation updated while asynchronous terrain loads settle.
|
||||
*setup('/random reset *'),
|
||||
cmd('/tick query'),
|
||||
cmd('/tick rate 40'),
|
||||
cmd('/tick query'),
|
||||
@@ -1063,9 +1068,25 @@ def test_command():
|
||||
]
|
||||
|
||||
|
||||
def server_clock():
|
||||
"""Only explicit tick operations advance the script's authoritative clock."""
|
||||
return [
|
||||
*setup('/scoreboard objectives add harness_clock dummy',
|
||||
'/execute store result score before harness_clock run time query gametime'),
|
||||
{'op': 'tick', 'n': 3},
|
||||
*setup('/execute store result score elapsed harness_clock run time query gametime',
|
||||
'/scoreboard players operation elapsed harness_clock -= before harness_clock'),
|
||||
cmd('/scoreboard players get elapsed harness_clock'),
|
||||
# The connected owner is the only player; @s and @a use the same body.
|
||||
cmd('/execute as @a run say connected owner'),
|
||||
*setup('/scoreboard objectives remove harness_clock'),
|
||||
]
|
||||
|
||||
|
||||
def groups():
|
||||
return [
|
||||
('setup', group_setup()),
|
||||
('server clock', server_clock()),
|
||||
('client commands', client_commands()),
|
||||
('game state', game_state()),
|
||||
('player state', player_state()),
|
||||
|
||||
@@ -6486,6 +6486,45 @@ CHECKS += ['sprint-fov']
|
||||
CHECK_FNS['sprint-fov'] = check_sprint_fov
|
||||
|
||||
|
||||
def check_sculk_container(host, guest, out):
|
||||
"""A real guest's container interaction emits a server game event. Both
|
||||
clients see the sensor and the non-summoning shrieker activate and reset.
|
||||
The component oracle separately controls warning levels and seeded mobs.
|
||||
"""
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
chest, sensor, shrieker = (x + 2, y, z), (x + 3, y, z), (x + 4, y, z)
|
||||
guest('command', command='gamemode survival')
|
||||
for at, block in ((chest, 'chest'), (shrieker, 'sculk_shrieker'), (sensor, 'sculk_sensor')):
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:{block}')
|
||||
guest.wait(60)
|
||||
seen = {}
|
||||
# Keep the sensor's 30-tick active window observable while both clients
|
||||
# acknowledge the container and the control socket inspects them.
|
||||
host('command', command='tick rate 4')
|
||||
try:
|
||||
guest.raw('interact', *chest)
|
||||
guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
|
||||
for game in (host, guest):
|
||||
active = wait_state(game, sensor, 'sculk_sensor_phase', 'active', 40)
|
||||
shrieking = wait_state(game, shrieker, 'shrieking', 'true', 40)
|
||||
seen[game.name] = (active, shrieking)
|
||||
assert all(s == ('active', 'true') for s in seen.values()), seen
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
for game in (host, guest):
|
||||
assert wait_state(game, sensor, 'sculk_sensor_phase', 'inactive', 160) == 'inactive', seen
|
||||
assert wait_state(game, shrieker, 'shrieking', 'false', 160) == 'false', seen
|
||||
finally:
|
||||
host('command', command='tick rate 20')
|
||||
if guest('state').get('screen') == 'container':
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
for at in (sensor, shrieker, chest):
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
return seen
|
||||
|
||||
|
||||
CHECKS += ['sculk_container']
|
||||
CHECK_FNS['sculk_container'] = check_sculk_container
|
||||
|
||||
def check_replant(host, guest, out):
|
||||
"""Instant breaks leave no server dig that can destroy a replacement (#1880).
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
Java (VanillaCommandExecOracle) starts a stand-in integrated server: a real
|
||||
MinecraftServer with a generated world, Commands.CommandSelection.INTEGRATED
|
||||
and one single-player owner named Player. Rust runs the same script through
|
||||
the Horizon client headless (HORIZON_COMMAND_SCRIPT). Both run each command as
|
||||
Horizon's integrated server with a connected headless client (HORIZON_COMMAND_SCRIPT). Both run each command as
|
||||
the player through Commands.performPrefixedCommand and record every system or
|
||||
chat message the player receives (text and resolved style: colour, bold,
|
||||
italic, underlined, strikethrough, obfuscated) together with the results the
|
||||
@@ -82,7 +82,7 @@ def main():
|
||||
rust_dir = build / 'rust'
|
||||
shutil.rmtree(rust_dir, ignore_errors=True)
|
||||
rust_dir.mkdir()
|
||||
env = lab.game_env(HORIZON_COMMAND_SCRIPT=script_path, HORIZON_COMMAND_OUTPUT=build / 'rust.jsonl')
|
||||
env = lab.game_env(HORIZON_SERVER_THREAD=1, HORIZON_PLAYER_NAME="Player", HORIZON_COMMAND_SCRIPT=script_path, HORIZON_COMMAND_OUTPUT=build / 'rust.jsonl')
|
||||
run([binary, '--resources', lab.RESOURCES, '--world', 'harness', '--seed', SEED, '--radius', 4], 'rust', cwd=rust_dir, env=env)
|
||||
|
||||
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').open(encoding='utf-8')]
|
||||
|
||||
@@ -5,7 +5,7 @@ A dispenser or dropper at the origin faces a random direction and holds the
|
||||
case's items; the block in front (and below it) comes from a palette of blocks
|
||||
the behaviours care about, and some cases put a target entity in front. Vanilla
|
||||
`DispenserBlock.dispenseFrom` runs over the headless level of the block update
|
||||
oracle (`VanillaDispenserOracle`); Horizon runs its game glue in a headless game
|
||||
oracle (`VanillaDispenserOracle`); Horizon runs its game glue as a component probe on a server thread
|
||||
(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, container contents,
|
||||
spawned entities (type, position, motion), the targets afterwards, level events,
|
||||
sounds, game events and the level random. Motion drawn from an entity's own
|
||||
|
||||
@@ -5,7 +5,7 @@ The Java oracle (VanillaSculkOracle) runs each scenario in a real, headless, fla
|
||||
level: it builds the blocks, places the player (with a warning level) and entities, and ticks the
|
||||
level in ServerLevel.tick's order while scripted game events and block changes happen at given
|
||||
ticks. Horizon runs the same scenarios through its game code (`HORIZON_SCULK_FIXTURE`, the
|
||||
same functions the game ticks). Both print, per tick, what changed at the watched blocks (state,
|
||||
same server phases, with synthetic player and entity state). Both print, per tick, what changed at the watched blocks (state,
|
||||
vibration, selector, last frequency, warning level, charge cursors), sounds, level events, the
|
||||
player's warden warning level and darkness, new entities, and the level random. The harness
|
||||
reports each scenario's first differing tick.
|
||||
|
||||
Reference in New Issue
Block a user