{
+ let row = div().flex().items_center().gap(px(2.));
+ Some(match horizon::rating(id)? {
+ None => row.text_color(t.muted).child("No ratings yet"),
+ Some(r) => {
+ let lit = r.average.round() as usize;
+ row.children((0..5).map(|i| {
+ blocks::icon(
+ "star",
+ 12.,
+ if i < lit {
+ t.warn
+ } else {
+ t.muted.opacity(0.6)
+ },
+ )
+ }))
+ .child(div().ml(px(4.)).child(format!(
+ "{:.1} ({})",
+ r.average,
+ count(r.count)
+ )))
+ }
+ })
+}
+
/// A checksum as the page shows it: the algorithm and the first and last hex digits.
fn short_sum(checksum: &str) -> String {
let (algo, hex) = checksum.split_once(':').unwrap_or(("", checksum));
@@ -968,9 +996,7 @@ impl Launcher {
if !p.author.is_empty() {
by.push(format!("by {}", p.author));
}
- if p.source != SourceId::Horizon {
- by.push(format!("{} downloads", count(p.downloads)));
- }
+ by.push(format!("{} downloads", count(p.downloads)));
by.push(format!("from {}", p.source.label()));
if !p.license.is_empty() {
by.push(p.license.clone());
@@ -980,6 +1006,11 @@ impl Launcher {
.flex_col()
.child(div().truncate().child(p.summary.clone()))
.child(by.join(" · "))
+ .children(
+ (p.source == SourceId::Horizon)
+ .then(|| stars(&p.id, &t))
+ .flatten(),
+ )
.children(
support
.reason()
diff --git a/launcher/src/mods_project.rs b/launcher/src/mods_project.rs
index 97d23e0aa..72a95b142 100644
--- a/launcher/src/mods_project.rs
+++ b/launcher/src/mods_project.rs
@@ -491,6 +491,21 @@ impl Launcher {
.gap(px(24.))
.child(div().flex().child(back))
.child(head);
+ // Registry projects are rated on the site, signed in with GitHub (one rating per account).
+ if p.source == SourceId::Horizon {
+ let url = browser::horizon::rate_url(&p.id);
+ page = page.child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(16.))
+ .children(super::mods_page::stars(&p.id, &t).map(|s| text(theme::UI).child(s)))
+ .child(
+ button("mods-rate", "Sign in with GitHub to rate", Kind::Ghost, &t)
+ .on_click(move |_, _, cx| cx.open_url(&url)),
+ ),
+ );
+ }
if let Some(why) = support.reason() {
page = page.child(
text(theme::UI)
diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/KnockbackClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/KnockbackClient.java
index d8c0483b6..0c02fa9aa 100644
--- a/mods/horizon/src/test/java/dev/horizonlab/parity/KnockbackClient.java
+++ b/mods/horizon/src/test/java/dev/horizonlab/parity/KnockbackClient.java
@@ -5,9 +5,12 @@ import io.netty.buffer.Unpooled;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
+import java.io.FileDescriptor;
+import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
+import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
@@ -76,7 +79,8 @@ import net.minecraft.world.phys.Vec3;
* {@code step LABEL}, {@code join NAME}, {@code cmd NAME COMMAND...} (waits
* for its feedback), {@code pos NAME X Y Z YAW PITCH GROUND} (one client tick
* at that place, on the ground or not), {@code sprint NAME on|off}, {@code
- * attack NAME TARGET} (ServerboundAttackPacket then the swing; TARGET is a
+ * sync NAME} (a round trip through the server thread; "synced NAME" on stdout when
+ * it is back), {@code attack NAME TARGET} (ServerboundAttackPacket then the swing; TARGET is a
* player's name or an entity type's path, the last one added), {@code use
* NAME} (ServerboundUseItemPacket, main hand) and {@code end}. Each player
* records the ClientboundSetEntityMotionPacket it receives, its own sprint
@@ -88,6 +92,8 @@ public final class KnockbackClient {
private static final Map
NAMES = new LinkedHashMap<>();
public static void main(String[] args) throws Exception {
+ // Bootstrap sends System.out to the logger: `synced` lines go to the real stdout.
+ PrintStream stdout = new PrintStream(new FileOutputStream(FileDescriptor.out), true, StandardCharsets.UTF_8);
ParityData.init();
String host = args[0];
int port = Integer.parseInt(args[1]);
@@ -116,6 +122,13 @@ public final class KnockbackClient {
case "attack" -> players.get(w[1]).attack(w[2]);
case "use" -> players.get(w[1]).send(new ServerboundUseItemPacket(InteractionHand.MAIN_HAND, 0, 0, 0));
case "punch" -> players.get(w[1]).send(net.minecraft.network.protocol.game.ServerboundPunchPacket.INSTANCE);
+ case "sync" -> {
+ try {
+ players.get(w[1]).sync();
+ } finally {
+ stdout.println("synced " + w[1]);
+ }
+ }
case "mark" -> players.get(w[1]).mark();
case "await" -> players.get(w[1]).await();
case "end" -> {
@@ -157,6 +170,7 @@ public final class KnockbackClient {
private final Map last = new java.util.concurrent.ConcurrentHashMap<>();
private final Object replyLock = new Object();
private int replies;
+ private int syncs;
/** The motion packets about this player it was sent, and how many there were at the last `mark`. */
private int pushes;
private int marked;
@@ -181,6 +195,24 @@ public final class KnockbackClient {
}
}
+ /** A round trip through the server thread, its reply left out of the transcript: every packet this player
+ * was sent before the reply has been recorded when it returns. */
+ void sync() throws Exception {
+ synchronized (replyLock) {
+ int before = syncs;
+ send(new ServerboundChatCommandPacket("time query gametime"));
+ long until = System.nanoTime() + 30_000_000_000L;
+ while (syncs == before) {
+ long left = (until - System.nanoTime()) / 1_000_000L;
+ if (left <= 0) {
+ record("error no reply to sync");
+ return;
+ }
+ replyLock.wait(left);
+ }
+ }
+ }
+
void mark() {
synchronized (replyLock) {
marked = pushes;
@@ -327,6 +359,13 @@ public final class KnockbackClient {
for (var value : d.packedItems()) {
if (value.id() == 0) record("sprinting " + ((((Byte) value.value()) & 8) != 0));
}
+ } else if (p instanceof ClientboundSystemChatPacket c
+ && c.content().getContents() instanceof net.minecraft.network.chat.contents.TranslatableContents t
+ && t.getKey().equals("commands.time.query.gametime")) {
+ synchronized (replyLock) {
+ syncs++;
+ replyLock.notifyAll();
+ }
} else if (p instanceof ClientboundSystemChatPacket c) {
record("chat " + c.content().getString());
synchronized (replyLock) {
diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java
index dc5f8c8df..64a848826 100644
--- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java
+++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java
@@ -223,7 +223,9 @@ public final class VanillaEntityAnimOracle {
}
/** Render-state values vanilla derives from entity state; the case gives the entity-side input. */
- private static void hooks(EntityRenderState state, JsonObject kase) {
+ private static void hooks(EntityRenderState state, JsonObject kase) throws Exception {
+ if (state instanceof net.minecraft.client.renderer.entity.state.BatRenderState bat && kase.has("@batTicks"))
+ batHistory(bat, kase.getAsJsonArray("@batTicks"));
if (state instanceof net.minecraft.client.renderer.entity.state.SheepRenderState sheep && kase.has("eatTick")) {
// Sheep.getHeadEatPositionScale / getHeadEatAngleScale at partial tick 0.
int t = kase.get("eatTick").getAsInt();
@@ -242,6 +244,34 @@ public final class VanillaEntityAnimOracle {
phantom.flapTime = kase.get("flapOffset").getAsFloat() + phantom.ageInTicks;
}
+ /** Only the server's flags are supplied; the shipped Bat starts/stops its own clocks. */
+ private static final class AnimationBat extends net.minecraft.world.entity.ambient.Bat {
+ int flags;
+ AnimationBat() { super(null, null); }
+ @Override public boolean isResting() { return (flags & 1) != 0; }
+ }
+
+ private static void batHistory(net.minecraft.client.renderer.entity.state.BatRenderState state, JsonArray ticks) throws Exception {
+ // Allocate without a world, as the other controlled entity oracles do.
+ var allocator = Class.forName("sun.misc.Unsafe");
+ var field = allocator.getDeclaredField("theUnsafe");
+ field.setAccessible(true);
+ var bat = (AnimationBat) allocator.getMethod("allocateInstance", Class.class).invoke(field.get(null), AnimationBat.class);
+ var type = net.minecraft.world.entity.ambient.Bat.class;
+ type.getField("flyAnimationState").set(bat, new net.minecraft.world.entity.AnimationState());
+ type.getField("restAnimationState").set(bat, new net.minecraft.world.entity.AnimationState());
+ var setup = type.getDeclaredMethod("setupAnimationStates");
+ setup.setAccessible(true);
+ for (var flags : ticks) {
+ bat.tickCount++;
+ bat.flags = flags.getAsInt();
+ setup.invoke(bat);
+ }
+ state.isResting = bat.isResting();
+ state.flyAnimationState.copyFrom(bat.flyAnimationState);
+ state.restAnimationState.copyFrom(bat.restAnimationState);
+ }
+
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
@@ -282,6 +312,19 @@ public final class VanillaEntityAnimOracle {
state.getClass();
for (var entry : kase.entrySet())
if (!entry.getKey().startsWith("@")) set(state, entry.getKey(), entry.getValue());
+ if (kase.has("@walkTicks")) {
+ var walk = new net.minecraft.world.entity.WalkAnimationState();
+ for (var speed : kase.getAsJsonArray("@walkTicks"))
+ walk.update(speed.getAsFloat(), 0.4F, 1.0F);
+ // LivingEntity.calculateEntityAnimation stops passengers/dead entities;
+ // LivingEntityRenderer.extractRenderState also zeros both fields.
+ if (kase.get("isPassenger").getAsBoolean() || !kase.get("@alive").getAsBoolean())
+ walk.stop();
+ float partial = kase.get("@partial").getAsFloat();
+ set(state, "walkAnimationPos", gson.toJsonTree(walk.position(partial)));
+ set(state, "walkAnimationSpeed", gson.toJsonTree(walk.speed(partial)));
+ result.add("walk", gson.toJsonTree(new float[]{walk.position(partial), walk.speed(partial)}));
+ }
hooks(state, kase);
if (state instanceof net.minecraft.client.renderer.entity.state.ArmedEntityRenderState armed && armed.swingAnimation > 0)
armed.currentSwing = new net.minecraft.world.entity.LivingEntity.SwingDescription(net.minecraft.world.InteractionHand.MAIN_HAND, net.minecraft.world.item.component.SwingAnimation.DEFAULT, 6);
diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java
index eb5235adf..256333d46 100644
--- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java
+++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java
@@ -60,6 +60,7 @@ import net.minecraft.util.debugchart.SampleLogger;
import net.minecraft.world.clock.WorldClocks;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntitySpawnReason;
+import net.minecraft.world.entity.EntitySpawnRequest;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.entity.monster.creaking.Creaking;
@@ -159,6 +160,7 @@ public final class VanillaMobAiOracle {
static final class Scenario {
String name;
int ticks;
+ int difficulty = 2;
long time = 6000;
boolean rain, thunder;
int originX, originZ;
@@ -204,6 +206,7 @@ public final class VanillaMobAiOracle {
switch (kv[0]) {
case "ticks" -> s.ticks = Integer.parseInt(kv[1]);
case "time" -> s.time = Long.parseLong(kv[1]);
+ case "difficulty" -> s.difficulty = Integer.parseInt(kv[1]);
case "rain" -> s.rain = true;
case "thunder" -> s.thunder = true;
case "levelseed" -> s.levelSeed = Long.parseLong(kv[1]);
@@ -494,6 +497,7 @@ public final class VanillaMobAiOracle {
}
void run(Scenario s, ServerLevel level) throws Exception {
+ this.setDifficulty(net.minecraft.world.Difficulty.byId(s.difficulty), true);
out.println("== " + s.name);
var clock = level.registryAccess().lookupOrThrow(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD);
this.clockManager().setTotalTicks(clock, s.time);
@@ -537,7 +541,9 @@ public final class VanillaMobAiOracle {
int id = 100000;
for (MobSpec spec : s.mobs) {
EntityType> type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type));
- Mob mob = (Mob) type.create(level, EntitySpawnReason.COMMAND);
+ // Ignore canSpawn: a Peaceful scenario's hostile mob is one that was already
+ // in the world when the difficulty changed (create returns null at Peaceful).
+ Mob mob = (Mob) type.create(level, new EntitySpawnRequest(EntitySpawnReason.COMMAND, true));
if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, ENTS.size()));
mob.setId(id++);
mob.snapTo(spec.x, spec.y, spec.z, spec.yaw, 0.0F);
@@ -553,6 +559,10 @@ public final class VanillaMobAiOracle {
String v = kv.length > 1 ? kv[1] : "";
switch (kv[0]) {
case "persistent" -> mob.setPersistenceRequired();
+ case "named" -> {
+ mob.setCustomName(net.minecraft.network.chat.Component.literal("Peaceful regression"));
+ mob.setPersistenceRequired();
+ }
case "ridden" -> mob.setItemSlot(net.minecraft.world.entity.EquipmentSlot.BODY,
new net.minecraft.world.item.ItemStack(BuiltInRegistries.ITEM.getValue(
net.minecraft.resources.Identifier.parse("minecraft:red_harness"))));
diff --git a/roadmap/roadmap.toml b/roadmap/roadmap.toml
index 669596fba..1dbed9c37 100644
--- a/roadmap/roadmap.toml
+++ b/roadmap/roadmap.toml
@@ -1039,54 +1039,54 @@ links = ["#1437", "#1660"]
[[item]]
id = "item-cooldowns"
title = "Cooldowns drawn on items"
-status = "help-wanted"
+status = "now"
area = "gameplay"
plain = """After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla."""
dev = """Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot \
(`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue #1763."""
-links = ["#1763"]
+links = ["#1763", "#1933"]
[[item]]
id = "chat-settings"
title = "Chat settings and team prefixes"
-status = "help-wanted"
+status = "now"
area = "gameplay"
plain = """The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before \
names in chat."""
dev = """Vanilla checks `ChatVisiblity` before it delivers chat and system messages (#1376), and chat uses the \
team-formatted display name (#1378). Both issues have exact steps to reproduce."""
-links = ["#1376", "#1378"]
+links = ["#1376", "#1378", "#1932", "#1841"]
[[item]]
id = "pointer-hand"
title = "A pointing hand over buttons"
-status = "help-wanted"
+status = "now"
area = "gameplay"
plain = """The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3."""
dev = """26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's \
`CursorIcon::Pointer` gives the same shape. Issue #1347."""
-links = ["#1347"]
+links = ["#1347", "#1897"]
[[item]]
id = "text-field-keys"
title = "Ctrl+Backspace and scroll bars in menus"
-status = "help-wanted"
+status = "now"
area = "gameplay"
plain = """Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be \
draggable."""
dev = """`EditBox` deletes by word with Ctrl (#1764); the Game Rules and Statistics lists' scroll bars can't be \
dragged (#1782, after #978)."""
-links = ["#1764", "#1782"]
+links = ["#1764", "#1782", "#1884", "#1931"]
[[item]]
id = "chicken-flap"
title = "Chickens flap while they fall"
-status = "help-wanted"
+status = "now"
area = "gameplay"
plain = """Chickens should flap their wings while they fall, not stand still in the air."""
dev = """Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the \
model's wings follow them. Issue #1706."""
-links = ["#1706"]
+links = ["#1706", "#1892"]
# ---------------------------------------------------------------------------------------------------- Shipped
# Newest first: `tools/roadmap.py sync` adds each newly shipped item on top.
diff --git a/tests/test_parity_main.py b/tests/test_parity_main.py
index aa58375a6..46e3d0466 100644
--- a/tests/test_parity_main.py
+++ b/tests/test_parity_main.py
@@ -45,7 +45,7 @@ class ParityMainTests(unittest.TestCase):
last_run.parent.mkdir(parents=True)
last_run.write_text('{"failed": ["music"]}')
real_run = parity_main.subprocess.run
- for broken_from, blamed in ((None, None), (0, None), (2, "2")):
+ for broken_from, blamed, code in ((None, None, 0), (0, None, 1), (2, "2", 1)):
comments = []
# git runs for real in the scratch repo; a `gh pr comment` is only recorded, never sent.
fake_run = lambda command, **kwargs: (comments.append(command) if command[0] == "gh"
@@ -55,7 +55,8 @@ class ParityMainTests(unittest.TestCase):
and commits.index(git("rev-parse", "HEAD")) >= broken_from), \
mock.patch.object(parity_main.subprocess, "run", fake_run), \
mock.patch("builtins.print") as printed:
- parity_main.bisect(commits[0], 60, comment=True)
+ self.assertEqual(parity_main.bisect(commits[0], 60, comment=True), code,
+ "0 only when the failures pass again at HEAD")
if blamed:
self.assertEqual([command[3] for command in comments], [blamed])
else:
diff --git a/tests/test_world_input_capture.py b/tests/test_world_input_capture.py
index df91e3153..5607c3684 100644
--- a/tests/test_world_input_capture.py
+++ b/tests/test_world_input_capture.py
@@ -101,6 +101,7 @@ impl Default for Game {
}
impl Game {
fn stop_mining(&mut self) { self.mining = false; }
+ fn reset_inventory_clicks(&mut self) {}
METHODS
}
fn main() {
diff --git a/tools/ci/linux-runner.sh b/tools/ci/linux-runner.sh
index 699742bf1..5a5e72697 100755
--- a/tools/ci/linux-runner.sh
+++ b/tools/ci/linux-runner.sh
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# A Horizon CI runner (labels self-hosted, Linux, X64, horizon-game and the host's name) on a Linux machine of the
-# maintainer's (NixOS: ludodesktop, ludothinkpad), as a systemd user service of the account that holds his
-# Minecraft files, like the Mac mini's runners (docs/release-flow.md). Run it on that machine, as that user:
+# maintainer's (NixOS: ludodesktop, ludothinkpad; Ubuntu: playhorizon, a partner's server), as a systemd user service
+# of the account that holds his Minecraft files, like the Mac mini's runners (docs/release-flow.md). Run it on that
+# machine, as that user:
#
# bash tools/ci/linux-runner.sh install # register (gh login), install, start; again to update the scripts
# bash tools/ci/linux-runner.sh status # the services, the runner's state, the pause watcher's last lines
@@ -12,10 +13,16 @@
# never runs as the service). horizon-runner-pause.service (runner_pause.py) starts the runner only while nobody
# uses the machine (screen locked or untouched for 15 min, no game), and stops it otherwise. The runner runs nice,
# in horizon-ci.slice (low CPU and I/O weight, memory capped), on its own virtual screen: vscreen (a headless sway)
-# where it is installed, else Xvfb from nixpkgs with Mesa's Vulkan drivers.
+# where it is installed, else Xvfb with Mesa's Vulkan drivers (from nixpkgs on NixOS, from the system elsewhere).
# HORIZON_SHARED_SOURCE: the imported vanilla data (default ~/horizon-local/shared-local, else
# ~/code/horizon/.local); RUNNER_JOBS: cargo jobs and harnesses at once (default a third of the threads, at most 8:
# ludodesktop froze under ~7 cold cargo builds on 2026-10-14, and it is the maintainer's own machine).
+# RUNNER_CPUS and RUNNER_MEMORY (GB): the slice's CPU quota and memory cap (default half the threads, two thirds of
+# the memory), for a machine that does nothing else. RUNNER_TOKEN: the registration (or, for uninstall, removal)
+# token, made with gh on another machine, where gh must not be logged in (a machine someone else also runs):
+# RUNNER_TOKEN=$(gh api -X POST repos/ludovic111/horizon/actions/runners/registration-token --jq .token)
+# Without Nix (Debian, Ubuntu), the packages come from apt (the list in system_packages) and python3.13 from the
+# PATH (uv python install 3.13, linked into ~/.local/bin).
set -euo pipefail
repo=ludovic111/horizon
dir=$HOME/.actions-runners/horizon
@@ -27,9 +34,16 @@ here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# Nix packages the jobs need, kept alive by GC roots in $dir/nix. nix-build prints the store path; the root's name
# gets the output's suffix (alsa-dev-dev for alsa-lib.dev), so it is not read back from the link.
nix_out() { nix-build '' -A "$1" -o "$dir/nix/$2" | tail -1; }
+nixos() { [ -d /run/current-system/sw ]; }
+system_packages="build-essential pkg-config cmake libasound2-dev libudev-dev sccache mesa-vulkan-drivers libvulkan1 xvfb
+ libx11-6 libxcursor1 libxrandr2 libxi6 libxinerama1 libxkbcommon0 libxkbcommon-x11-0 libgl1 libegl1 rsync git curl"
# The runner is a .NET program: on NixOS its native libraries (libstdc++, ICU, OpenSSL) come from nix-ld.
-export LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
+if nixos; then export LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}; fi
+
+token() {
+ if [ -n "${RUNNER_TOKEN:-}" ]; then echo "$RUNNER_TOKEN"; else gh api -X POST "repos/$repo/actions/runners/$1" --jq .token; fi
+}
# NixOS has no /bin/bash: the runner's scripts (again after each of its self-updates) get a portable one.
fix_shebangs() { sed -i '1s|^#!/bin/bash|#!/usr/bin/env bash|' "$dir"/*.sh "$dir"/bin/*.sh; }
@@ -77,32 +91,59 @@ install() {
fi
tar xzf "$cache" -C "$dir"
fix_shebangs
- gh api -X POST "repos/$repo/actions/runners/registration-token" --jq .token |
+ token registration-token |
(cd "$dir" && bash ./config.sh --unattended --replace --url "https://github.com/$repo" --token "$(cat)" \
--name "$name" --labels "${RUNNER_LABELS:-horizon-game,$(hostname)}" --work _work > /dev/null)
fi
# Libraries for building (pkg-config) and running (dlopen) the game, the JDK pinned by research-lock.json, sccache.
- local alsa udev java
- alsa=$(nix_out alsa-lib.dev alsa-dev)
- udev=$(nix_out systemd.dev systemd-dev)
- java=$(nix_out "jdk$(sed -n 's/.*"java_major": *\([0-9]*\).*/\1/p' "$here/../../research-lock.json" | head -1)_headless" jdk)/lib/openjdk
- nix_out sccache sccache > /dev/null # on the PATH below: runner-env.sh hands it to cargo
- local libs=/run/opengl-driver/lib:/run/current-system/sw/share/nix-ld/lib
- if ! command -v vscreen > /dev/null; then
- local mesa x
- mesa=$(nix_out mesa mesa)
- x=$(nix_out xvfb-run xvfb-run)
- for lib in libx11 libxcursor libxrandr libxi libxext libxinerama libxrender libxxf86vm libxcb libxkbcommon \
- vulkan-loader libGL; do
- libs=$libs:$(nix_out "$lib" "$lib")/lib
- done
- libs=$mesa/lib:$libs
- echo "VK_DRIVER_FILES=$mesa/share/vulkan/icd.d/intel_icd.x86_64.json:$mesa/share/vulkan/icd.d/lvp_icd.x86_64.json" \
- > "$dir/.env.display"
- echo "$x/bin" > "$dir/.path.display"
+ local major java platform_env path
+ major=$(sed -n 's/.*"java_major": *\([0-9]*\).*/\1/p' "$here/../../research-lock.json" | head -1)
+ if nixos; then
+ local alsa udev libs=/run/opengl-driver/lib:/run/current-system/sw/share/nix-ld/lib display_path=""
+ alsa=$(nix_out alsa-lib.dev alsa-dev)
+ udev=$(nix_out systemd.dev systemd-dev)
+ java=$(nix_out "jdk${major}_headless" jdk)/lib/openjdk
+ nix_out sccache sccache > /dev/null # on the PATH below: runner-env.sh hands it to cargo
+ platform_env="PKG_CONFIG_PATH=$alsa/lib/pkgconfig:$udev/lib/pkgconfig
+C_INCLUDE_PATH=$udev/include
+NIX_LD=/run/current-system/sw/share/nix-ld/lib/ld.so
+NIX_LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib"
+ if ! command -v vscreen > /dev/null; then
+ local mesa x
+ mesa=$(nix_out mesa mesa)
+ x=$(nix_out xvfb-run xvfb-run)
+ for lib in libx11 libxcursor libxrandr libxi libxext libxinerama libxrender libxxf86vm libxcb libxkbcommon \
+ vulkan-loader libGL; do
+ libs=$libs:$(nix_out "$lib" "$lib")/lib
+ done
+ libs=$mesa/lib:$libs
+ platform_env="$platform_env
+VK_DRIVER_FILES=$mesa/share/vulkan/icd.d/intel_icd.x86_64.json:$mesa/share/vulkan/icd.d/lvp_icd.x86_64.json"
+ display_path=$x/bin:
+ fi
+ platform_env="$platform_env
+LD_LIBRARY_PATH=$libs"
+ path="$dir/cargo/bin:$display_path$dir/nix/sccache/bin:$java/bin:$HOME/.local/bin:/run/wrappers/bin:/etc/profiles/per-user/$USER/bin:/run/current-system/sw/bin"
+ else
+ # apt's packages (installed here when sudo needs no password), its JDK, and Mesa's software Vulkan (lavapipe):
+ # a server has no GPU.
+ local missing
+ missing=$(dpkg-query -W -f='${Package} ${Status}\n' $system_packages "openjdk-$major-jdk-headless" 2>&1 |
+ awk '/^dpkg-query: no packages found matching/ {print $NF; next} !/ installed$/ {print $1}' | tr '\n' ' ')
+ if [ -n "${missing// /}" ]; then
+ sudo -n env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq $missing > /dev/null ||
+ { echo "Install first: sudo apt-get install $missing"; exit 1; }
+ fi
+ command -v python3.13 > /dev/null || [ -x "$HOME/.local/bin/python3.13" ] ||
+ { echo "No python3.13: uv python install 3.13, then link it into ~/.local/bin"; exit 1; }
+ java=$(ls -d /usr/lib/jvm/java-"$major"-openjdk-* | head -1)
+ platform_env=""
+ command -v vscreen > /dev/null || platform_env="VK_DRIVER_FILES=$(ls /usr/share/vulkan/icd.d/lvp_icd*.json | head -1)"
+ path="$dir/cargo/bin:$java/bin:$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin"
fi
- cat > "$dir/.env" <> "$dir/.env"; else echo "VSCREEN=ci-horizon" >> "$dir/.env"; fi
- echo "$dir/cargo/bin:$(cat "$dir/.path.display" 2>/dev/null || true)${dir}/nix/sccache/bin:$java/bin:$HOME/.local/bin:/run/wrappers/bin:/etc/profiles/per-user/$USER/bin:/run/current-system/sw/bin" \
- | sed 's/::/:/g' > "$dir/.path"
+ [ -n "$platform_env" ] && echo "$platform_env"
+ command -v vscreen > /dev/null && echo "VSCREEN=ci-horizon"
+ true
+ } > "$dir/.env"
+ echo "$path" > "$dir/.path"
+ rm -f "$dir/.env.display" "$dir/.path.display" # written by older versions of this script
+ local memory cpus
+ memory=${RUNNER_MEMORY:-$(( $(awk '/MemTotal/ {print int($2 / 1048576)}' /proc/meminfo) * 2 / 3 ))}
+ cpus=${RUNNER_CPUS:-$(( threads / 2 > 1 ? threads / 2 : 1 ))}
cat > "$units/horizon-ci.slice" < "$units/horizon-runner.service" </dev/null || true
- gh api -X POST "repos/$repo/actions/runners/remove-token" --jq .token |
+ token remove-token |
(cd "$dir" && bash ./config.sh remove --token "$(cat)")
rm -f "$units/horizon-runner.service" "$units/horizon-runner-pause.service" "$units/horizon-ci.slice"
systemctl --user daemon-reload
diff --git a/tools/ci/runner-env.sh b/tools/ci/runner-env.sh
index 39828b7d7..14e9e6762 100755
--- a/tools/ci/runner-env.sh
+++ b/tools/ci/runner-env.sh
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# The tools the vanilla harnesses need, on a self-hosted runner (label horizon-game): the Mac mini's, whose service
-# starts with a bare PATH, and the Linux ones (tools/ci/linux-runner.sh, NixOS). Python 3.13 and the JDK pinned by
+# starts with a bare PATH, and the Linux ones (tools/ci/linux-runner.sh: NixOS, Ubuntu). Python 3.13 and the JDK pinned by
# research-lock.json come from the machine, never from a download. Writes them to $GITHUB_PATH and $GITHUB_ENV for
# the next steps.
set -euo pipefail
diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py
index 449d47c0b..6dabe6dd7 100755
--- a/tools/lan_e2e.py
+++ b/tools/lan_e2e.py
@@ -2103,6 +2103,53 @@ def check_recipes(host, guest, out):
guest.raw('key', 'esc', 'tap')
guest.wait(5)
assert any('oak_log' in str(item) for item in grid.values()), f'nothing placed in the grid: {grid}'
+ # #2019: the alternatives popup belongs to one screen. Check both the
+ # in-frame host (or --server-thread host) and the remote guest, with both
+ # inventory-close keys and a different recipe-book type on reopening.
+ for game in (host, guest):
+ game('command', command='recipe give @s minecraft:oak_planks')
+ game('command', command='recipe give @s minecraft:birch_planks')
+ game.wait(10)
+ for close_key, reopen in (('e', 'inventory'), ('esc', 'furnace')):
+ game.raw('key', 'e', 'tap')
+ game.wait(5)
+ book = game('screen')['recipe_book']
+ if len(book['targets']) == 1:
+ game.raw('click-at', *centre(book['targets'][0]))
+ game.wait(5)
+ book = game('screen')['recipe_book']
+ for rect in book['targets']:
+ if rect[2:] != [25.0, 25.0]:
+ continue
+ game.raw('click-at', *centre(rect), 'right')
+ game.wait(2)
+ targets = game('screen')['recipe_book']['targets']
+ if targets and all(r[2:] == [24.0, 24.0] for r in targets):
+ break
+ else:
+ raise AssertionError(f'{game.name}: no alternatives popup opened: {book}')
+ game.shot(out, f'recipe-overlay-{close_key}-before')
+ game.raw('key', close_key, 'tap')
+ game.wait(5)
+ if reopen == 'inventory':
+ game.raw('key', 'e', 'tap')
+ else:
+ x, y, z = (int(v // 1) for v in pos_of(game))
+ game('command', command=f'setblock {x} {y} {z - 2} minecraft:furnace')
+ game.wait(5)
+ game.raw('interact', x, y, z - 2)
+ game.wait(5)
+ targets = game('screen')['recipe_book']['targets']
+ if reopen == 'furnace' and len(targets) == 1 and targets[0][2:] == [20.0, 18.0]:
+ game.raw('click-at', *centre(targets[0]))
+ game.wait(5)
+ targets = game('screen')['recipe_book']['targets']
+ game.shot(out, f'recipe-overlay-{close_key}-after')
+ assert any(r[2:] == [20.0, 18.0] for r in targets), f'{game.name}: stale popup: {targets}'
+ if reopen == 'inventory':
+ assert len(targets) > 1, f'{game.name}: the book forgot its open setting'
+ game.raw('key', 'esc', 'tap')
+ game.wait(5)
return {'known': known, 'grid': grid}
@@ -6664,6 +6711,94 @@ CHECKS += ['sprint-fov']
CHECK_FNS['sprint-fov'] = check_sprint_fov
+def check_critical_hits(host, guest, out):
+ """#1898: a real falling melee hit emits crits on the attacker and observer.
+ Grounded hits and refused falling hits emit none, against mobs and players.
+ """
+ x, y, z = map(math.floor, pos_of(host))
+ target = [x + 2.5, y, z + 0.5]
+ tag = 'critical_hit_particles'
+ seen = {}
+ host('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 6} {y - 1} {z + 6} minecraft:stone')
+ host('command', command=f'fill {x - 3} {y} {z - 3} {x + 6} {y + 5} {z + 6} minecraft:air')
+ host('command', command='time set midnight')
+ host('command', command='gamerule natural_health_regeneration false')
+ try:
+ for label, player, other in (('host', host, guest), ('guest', guest, host)):
+ for kind in ('zombie', 'player'):
+ for hit in ('grounded', 'critical', 'refused'):
+ case = f'{label}-{kind}-{hit}'
+ for game in (player, other):
+ game('command', command='gamemode survival')
+ game('command', command='clear @s')
+ game('command', command='effect clear @s')
+ game('command', command='effect give @s minecraft:instant_health 1 5 true')
+ player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
+ other_at = target if kind == 'player' else [x + 0.5, y, z + 4.5]
+ other('command', command=f'tp @s {other_at[0]} {other_at[1]} {other_at[2]}')
+ host('command', command=f'gamerule pvp {str(hit != "refused").lower()}')
+ mob_id = None
+ if kind == 'zombie':
+ host('command', command=f'summon minecraft:zombie {target[0]} {y} {target[2]} '
+ f'{{NoAI:1b,PersistenceRequired:1b,Invulnerable:{int(hit == "refused")}b,Tags:["{tag}"]}}')
+ player.wait(20) # full attack charge and paired entities
+ if kind == 'zombie':
+ mob = next(m for m in player.raw('mobs', 16)['near']
+ if m['kind'] == 'minecraft:zombie' and math.dist(m['pos'], target) < 0.1)
+ mob_id = mob['id']
+ assert mob_seen(other, mob_id), f'{case}: observer has not paired the zombie'
+ health_before = mob_seen(player, mob_id)['health'] if mob_id is not None else hearts(other)[1]
+ sound = 'minecraft:entity.player.attack.crit'
+ sounds_before = {side: heard(g, sound) for side, g in (('own', player), ('other', other))}
+
+ def strike():
+ if hit != 'grounded':
+ player.raw('key', 'space', 'down')
+ player.wait(1)
+ player.raw('key', 'space', 'up')
+ body = None
+ for _ in range(15):
+ body = player('state')['player']
+ # Let the server record the fall before the attack packet.
+ if not body['on_ground'] and body['velocity'][1] < -0.2:
+ break
+ player.wait(1)
+ assert body and not body['on_ground'] and body['velocity'][1] < -0.2, \
+ f'{case}: jump never reached its falling phase: {body}'
+ player.raw('look-at', target[0], y + 1, target[2])
+ player.raw('mouse', 'left', 'click')
+
+ particles = sparked(player, other, ['crit'], strike)
+ player.shot(out, f'critical-hits-{kind}-{hit}-{label}')
+ player.wait(10) # finish the three-tick emitter and health replication
+ health_after = mob_seen(player, mob_id)['health'] if mob_id is not None else hearts(other)[1]
+ sounds = {side: heard(g, sound) - sounds_before[side]
+ for side, g in (('own', player), ('other', other))}
+ seen[case] = {'particles': particles, 'crit_sounds': sounds,
+ 'health': [health_before, health_after]}
+ host('command', command=f'kill @e[tag={tag}]')
+ assert (health_after == health_before) if hit == 'refused' else (health_after < health_before), \
+ f'{case}: unexpected damage: {seen[case]}'
+ assert all(n == int(hit == 'critical') for n in sounds.values()), \
+ f'{case}: the server did not recognize the expected crit: {seen[case]}'
+ wrong = {case: result for case, result in seen.items()
+ if any((n <= 0 if case.endswith('-critical') else n != 0)
+ for n in result['particles'].values())}
+ assert not wrong, f'critical-hit particles: {wrong}'
+ return seen
+ finally:
+ host('command', command=f'kill @e[tag={tag}]')
+ host('command', command='gamerule pvp true')
+ host('command', command='gamerule natural_health_regeneration true')
+ host('command', command='time set day')
+ for game in (host, guest):
+ game.raw('key', 'space', 'up')
+
+
+CHECKS += ['critical-hits']
+CHECK_FNS['critical-hits'] = check_critical_hits
+
+
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.
@@ -6769,5 +6904,56 @@ CHECKS += ['replant']
CHECK_FNS['replant'] = check_replant
+def check_sonic(host, guest, out):
+ """A real warden's ray reaches connected clients once, with normal damage.
+
+ Run with and without --server-thread to cover the window's local renderer too.
+ The creative observer sees the same ray nearby and none outside sendParticles' range.
+ """
+ x, y, z = (int(v // 1) for v in pos_of(host))
+ result = {}
+ guest('command', command='gamemode creative')
+ host('command', command='difficulty normal')
+ host('command', command='gamerule natural_health_regeneration false')
+ try:
+ host('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 85} {y - 1} {z + 14} minecraft:stone')
+ host('command', command=f'fill {x - 3} {y} {z - 3} {x + 15} {y + 4} {z + 14} minecraft:air')
+ host('command', command=f'fill {x - 2} {y} {z + 4} {x + 2} {y + 3} {z + 4} minecraft:stone')
+ for near in (True, False):
+ guest('command', command=f'tp @s {x + (3 if near else 80) + 0.5} {y} {z + 0.5}')
+ host('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0')
+ host('command', command='gamemode survival')
+ host('command', command='effect give @s minecraft:instant_health 1 5')
+ host.wait(4)
+ host('command', command=f'summon minecraft:warden {x + 0.5} {y} {z + 9.5} {{NoAI:1b,Tags:["sonic_test"]}}')
+ host('command', command='attribute @e[tag=sonic_test,limit=1] minecraft:knockback_resistance base set 1')
+ before = {side: made(g, 'sonic_boom') for side, g in (('host', host), ('guest', guest))}
+ health = host('status')['player']['health']
+ host('command', command='data merge entity @e[tag=sonic_test,limit=1] {NoAI:0b}')
+ host('command', command='attribute @e[tag=sonic_test,limit=1] minecraft:movement_speed base set 0')
+ host('command', command='damage @e[tag=sonic_test,limit=1] 1 minecraft:player_attack by @s')
+ for _ in range(400):
+ host.wait(2)
+ if host('status')['player']['health'] < health:
+ break
+ host.wait(2) # let the observer process the same packet batch
+ seen = {side: made(g, 'sonic_boom') - before[side] for side, g in (('host', host), ('guest', guest))}
+ after = host('status')['player']['health']
+ result['near' if near else 'far'] = {'particles': seen, 'health': [health, after]}
+ host.shot(out, f'sonic-{"near" if near else "far"}')
+ host('command', command='kill @e[tag=sonic_test]')
+ assert after == health - 10, result
+ assert seen['host'] == 15, result
+ assert seen['guest'] == (15 if near else 0), result
+ finally:
+ host('command', command='kill @e[tag=sonic_test]')
+ host('command', command='gamerule natural_health_regeneration true')
+ return result
+
+
+CHECKS += ['sonic']
+CHECK_FNS['sonic'] = check_sonic
+
+
if __name__ == '__main__':
main()
diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json
index 164a3ff42..b98091f4f 100644
--- a/tools/parity_hosts.json
+++ b/tools/parity_hosts.json
@@ -20,6 +20,16 @@
"nice": 19,
"note": "ludodesktop, the maintainer's own machine: only while nobody uses it (tools/ci/runner_pause.py: screen locked or untouched for 15 min, no game; a paused desktop refuses workers and stops the running ones, whose harnesses then run here); 8 jobs at most, in the CI runner's environment and slice"
},
+ "playhorizon": {
+ "ssh": "ludovic@playhorizon",
+ "root": ".actions-runners/horizon/parity-host",
+ "shell": "systemd-run --user --scope --quiet --slice=horizon-ci.slice --unit=horizon-parity-worker-$$ bash -c",
+ "setup": "test ! -e ~/.actions-runners/horizon/paused && set -a && . ~/.actions-runners/horizon/.env && set +a && export PATH=$(cat ~/.actions-runners/horizon/.path) && unset WAYLAND_DISPLAY && export DISPLAY=:$(cat ~/.actions-runners/horizon/display)",
+ "python": "python3.13",
+ "jobs": 6,
+ "nice": 10,
+ "note": "a partner's server (Ubuntu, 8 EPYC threads, 30 GB, Detroit; tailnet only), used by nothing else: 6 jobs, in the CI runner's environment, slice and Xvfb screen (tools/ci/linux-runner.sh); the light Linux checks that used to go to the ThinkPad go here"
+ },
"thinkpad": {
"ssh": "thinkpad",
"root": "code/horizon-parity",
diff --git a/tools/parity_main.py b/tools/parity_main.py
index 76fa49070..f61c9b028 100644
--- a/tools/parity_main.py
+++ b/tools/parity_main.py
@@ -78,34 +78,35 @@ def bisect(since, timeout, comment):
failed = json.loads(LAST_RUN.read_text(encoding="utf-8")).get("failed") or []
if not failed:
print("No failed harness recorded: nothing to bisect.")
- return 0
+ return 1
head = git("rev-parse", "HEAD").stdout.strip()
commits = git("rev-list", "--first-parent", "--reverse", f"{since}..{head}").stdout.split()
if not commits:
print("No merge since the base.")
- return 0
+ return 1
def fails(commit):
print(f"--- {commit[:9]} {git('log', '-1', '--format=%s', commit).stdout.strip()}", flush=True)
git("checkout", "-q", "--detach", commit)
return run_harnesses(failed, timeout)
- def blame_nobody(why):
+ def blame_nobody(why, code):
line = f"parity-main: {', '.join(failed)} {why}: no merge is named."
print(line)
if os.environ.get("GITHUB_STEP_SUMMARY"):
with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary:
summary.write(f"### {line}\n")
- return 0
+ return code
# A merge is named only when the harnesses fail again at HEAD and pass at the base: otherwise the search would
# end on the newest merge (a flake, or a runner missing files, passes everywhere now) or the oldest one (the
- # runner fails at every commit) and blame it for nothing.
+ # runner fails at every commit) and blame it for nothing. The exit code is the run's verdict: 0 only when every
+ # failed harness passes when run again at HEAD (the commit is good, so releases may follow it), 1 otherwise.
try:
if not fails(head):
- return blame_nobody(f"pass when run again at {head[:9]}: a flake or the runner")
+ return blame_nobody(f"pass when run again at {head[:9]}: a flake, counted as a pass", 0)
if fails(since):
- return blame_nobody(f"fail at the base {since[:9]} too: the runner or a flake")
+ return blame_nobody(f"fail at the base {since[:9]} too: the runner or a flake", 1)
culprit = first_bad(commits, fails) if len(commits) > 1 else commits[0]
finally:
git("checkout", "-q", "--detach", head)
@@ -122,7 +123,7 @@ def bisect(since, timeout, comment):
body = (f"🤖 Agent: parity-main found that this merge breaks {', '.join(f'`{name}`' for name in failed)} on main "
f"(bisected over {len(commits)} merges: {url}). Releases wait until parity-main passes again.")
subprocess.run(["gh", "pr", "comment", number.group(1), "--repo", REPO, "--body", body])
- return 0
+ return 1
def main():
diff --git a/tools/quiet_commands_e2e.py b/tools/quiet_commands_e2e.py
new file mode 100644
index 000000000..f7008bbd6
--- /dev/null
+++ b/tools/quiet_commands_e2e.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python3
+"""Mods' quiet commands on Horizon's dedicated server, end to end (horizon_protocol::quiet).
+
+Horizon's dedicated server (a flat world) and Horizon's headless client (`HORIZON_NET_REPORT`, the net
+harness), which joins, then sends a batch of quiet commands as a mod would (`HORIZON_NET_QUIET`):
+
+- as a player who isn't an operator: `setblock` is refused (the block stays air), as it would be typed;
+- as an operator: `setblock` runs, a `fill` that changes nothing fails, and `say` is refused (a chat
+ message needs the player's signature);
+- either way the player's chat gets nothing of them, and the server logs one line per batch: the player,
+ the mod, how many ran and how many failed.
+
+ python3 tools/quiet_commands_e2e.py --bin-dir target/fast
+
+The client runs with fresh HORIZON_HOME, launcher and XDG folders and without audio; the logs go to --out.
+"""
+import argparse
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import lab # noqa: E402
+from integration_env import run_game # noqa: E402
+from test_dedicated_server_parity import Server # noqa: E402
+
+ROOT = Path(__file__).resolve().parents[1]
+PLAYER = 'Tester'
+PROPERTIES = {
+ 'online-mode': 'false',
+ 'white-list': 'false',
+ 'level-type': 'minecraft\\:flat',
+ 'generate-structures': 'false',
+ 'spawn-protection': '0',
+ 'view-distance': '3',
+ 'simulation-distance': '3',
+ 'pause-when-empty-seconds': '-1',
+}
+BLOCK = '2 -55 2'
+# What a player would see of these commands, were they typed.
+FEEDBACK = ['Changed the block', 'No blocks were filled', 'Unknown or incomplete command', 'hi from a mod',
+ 'Could not set the block']
+
+
+def join(binary, port, out, label, lines):
+ """The headless client joins, sends `lines` as one quiet batch and leaves: its report."""
+ home = Path(tempfile.mkdtemp(prefix=f'quiet-{label}-'))
+ report = out / f'{label}-report.json'
+ # run_game gives the game fresh home, launcher and XDG folders.
+ env = dict(HORIZON_NET_REPORT=str(report), HORIZON_NET_QUIET=';'.join(lines))
+ with (out / f'{label}-client.log').open('w') as log:
+ run_game([str(binary), '--resources', str(lab.RESOURCES), '--render-distance', '2',
+ '--server', f'127.0.0.1:{port}', '--name', PLAYER],
+ cwd=home, env=dict(os.environ, **env), stdout=log, stderr=subprocess.STDOUT, timeout=300,
+ check=True)
+ shutil.rmtree(home, ignore_errors=True)
+ return json.loads(report.read_text())
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument('--bin-dir', help='a prebuilt horizon-client (default: build it with the fast profile)')
+ parser.add_argument('--out', default=str(ROOT / '.local/quiet-commands-e2e'), help='logs go here')
+ args = parser.parse_args()
+ out = Path(args.out)
+ shutil.rmtree(out, ignore_errors=True)
+ out.mkdir(parents=True)
+ if args.bin_dir:
+ binary = Path(args.bin_dir) / 'horizon-client'
+ else:
+ subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'],
+ cwd=ROOT, check=True)
+ binary = Path(lab.cargo_target()) / 'fast' / 'horizon-client'
+ port = lab.free_port()
+ directory = out / 'server'
+ directory.mkdir()
+ props = dict(PROPERTIES, **{'server-port': str(port)})
+ (directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()),
+ encoding='iso-8859-1')
+ (directory / 'eula.txt').write_text('eula=true\n')
+ server = Server([binary, '--resources', lab.RESOURCES, '--dedicated', '--nogui'], directory, 'server')
+ failures = []
+
+ def check(what, ok, detail=''):
+ print(('PASS ' if ok else 'FAIL ') + what + ('' if ok else f': {detail}'))
+ if not ok:
+ failures.append(what)
+
+ def test_block(want):
+ """The console's `execute if block`: 'Test passed' when the block is `want`."""
+ before = len(server.lines)
+ server.console(f'execute if block {BLOCK} {want}')
+ deadline = time.time() + 30
+ while time.time() < deadline:
+ answer = [l for l in server.lines[before:] if 'Test passed' in l or 'Test failed' in l]
+ if answer:
+ return 'Test passed' in answer[0]
+ time.sleep(0.2)
+ raise AssertionError('the console never answered execute if block')
+
+ try:
+ server.wait_for(r'Done \(')
+ # Not an operator: the setblock is refused, as typed.
+ got = join(binary, port, out, 'not-op', [f'setblock {BLOCK} minecraft:gold_block'])
+ server.wait_for(rf'{PLAYER} ran 1 quiet command\(s\) from mod net_harness: 1 failed', timeout=30)
+ check('not an operator: connected throughout', got['error'] is None, got['error'])
+ check("not an operator: a quiet setblock is refused", not test_block('minecraft:gold_block'))
+ heard = [c for c in got['chat'] if any(f in c for f in FEEDBACK)]
+ check('not an operator: nothing in the chat', not heard, heard)
+ server.wait_for(rf'{PLAYER} left the game', timeout=60)
+ # An operator: it runs, quietly.
+ server.console(f'op {PLAYER}')
+ server.wait_for(rf'Made {PLAYER} a server operator', timeout=30)
+ got = join(binary, port, out, 'op', [f'setblock {BLOCK} minecraft:gold_block',
+ f'fill {BLOCK} {BLOCK} minecraft:gold_block', 'say hi from a mod'])
+ server.wait_for(rf'{PLAYER} ran 3 quiet command\(s\) from mod net_harness: 2 failed', timeout=30)
+ check('operator: connected throughout', got['error'] is None, got['error'])
+ check('operator: the quiet setblock ran', test_block('minecraft:gold_block'))
+ heard = [c for c in got['chat'] if any(f in c for f in FEEDBACK)]
+ check('operator: nothing in the chat (no feedback, no failure, no say)', not heard, heard)
+ said = [l for l in server.lines if 'hi from a mod' in l]
+ check('operator: say is refused', not said, said)
+ finally:
+ server.stop()
+ print(f'logs: {out}')
+ sys.exit(1 if failures else 0)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py
index ee0eb46f5..7572ee3e2 100644
--- a/tools/test_dedicated_server_parity.py
+++ b/tools/test_dedicated_server_parity.py
@@ -206,6 +206,17 @@ def game_time(server, timeout=300):
raise AssertionError(f'{server.log_path.name}: no game time in {timeout:.0f} s')
+def wait_ticks(server, count, timeout=300):
+ """Waits until the server's game clock has advanced `count` ticks: a server that stalls under load still gets
+ as many ticks as an idle one, where a sleep gives it fewer. (Not while ticking is frozen.)"""
+ deadline = time.time() + timeout
+ until = game_time(server, timeout) + count
+ while game_time(server, max(1.0, deadline - time.time())) < until:
+ if time.time() > deadline:
+ raise AssertionError(f'{server.log_path.name}: the game clock did not advance {count} ticks in {timeout} s')
+ time.sleep(0.2)
+
+
def legacy_ping(port):
"""The reply to a 1.6 client's 0xFE 0x01 0xFA MC|PingHost query (LegacyQueryHandler)."""
host = 'localhost'
@@ -333,7 +344,9 @@ def run_side(label, command, directory, client):
joined.join()
if failure:
raise failure[0]
- time.sleep(1)
+ # The client has gone; `list` must find no one, once the server has handled its leaving (a busy machine
+ # took longer than a second).
+ server.wait_for(rf'{PLAYER} left the game', timeout=60)
server.console('list')
server.console('say console says hi')
server.wait_for(r'\[Server\] console says hi', timeout=30)
diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py
index 0cfc509f3..8394561b0 100644
--- a/tools/test_entity_model_parity.py
+++ b/tools/test_entity_model_parity.py
@@ -164,6 +164,15 @@ def cases(layer, model=None):
cases_out = [{**c, **DEFAULTS.get(name, {})} for c in cases_out]
yield from cases_out
yield from species_cases(layer, cases_out)
+ # Exercise render-state extraction with a live walk clock, including the
+ # first mounted frame. Existing setupAnim cases bypass anim::state.
+ if name == 'skeleton':
+ for passenger in [False, True]:
+ for alive in [False, True]:
+ for partial in [0.0, 0.5, 1.0]:
+ yield {**cases_out[2], 'isPassenger': passenger,
+ '@walkTicks': [0.5, 1.0, 0.75],
+ '@alive': alive, '@partial': partial}
part = model and scaled_part(model)
if part:
for index, scale in enumerate(PART_SCALES):
@@ -276,6 +285,14 @@ def species_cases(layer, base_cases):
for extra in SPECIES.get(name, []):
for index in (2, 3, 6):
yield {**base_cases[index], **extra}
+ if name == 'bat':
+ # Entity clocks, rather than injected render clocks: flight, rest, transitions and
+ # unrelated flag bits. Exercise the in-frame tick and server-client visual update.
+ for flags in ([0] * 4, [1] * 4, [0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1], [2, 3, 2, 2]):
+ for in_frame in (False, True):
+ for partial in (0.0, 0.5):
+ yield {**base_cases[0], 'ageInTicks': len(flags) + partial,
+ '@batTicks': flags, '@batInFrame': in_frame}
def compare_vertices(v, r, args, stats):
@@ -379,6 +396,10 @@ def main():
skipped.add(layer); continue
checked += 1
bad = []
+ if 'walk' in v:
+ for a, b in zip(v['walk'], r['walk']):
+ if abs(a - b) > args.tolerance * (1.0 + abs(a)):
+ bad.append(('@walk', f'{v["walk"]} != {r["walk"]}'))
for path, expected in v['parts'].items():
got = r['parts'].get(path)
if got is None:
diff --git a/tools/test_locator_bar_parity.py b/tools/test_locator_bar_parity.py
index 985b87a35..6574af76e 100644
--- a/tools/test_locator_bar_parity.py
+++ b/tools/test_locator_bar_parity.py
@@ -23,15 +23,14 @@ import platform
import shutil
import subprocess
import sys
-import time
try:
from . import lab, test_rust_parity as base
- from .test_dedicated_server_parity import Server, free_port
+ from .test_dedicated_server_parity import Server, free_port, wait_ticks
except ImportError:
import lab
import test_rust_parity as base
- from test_dedicated_server_parity import Server, free_port
+ from test_dedicated_server_parity import Server, free_port, wait_ticks
NAME = 'locator-bar-parity'
PROPERTIES = {
@@ -82,7 +81,7 @@ SCRIPT = [
('creative', [], ['cmd Bob gamemode creative', 'cmd Bob tp @s 6.5 100 0.5']),
('bob-leaves', [], ['quit Bob']),
]
-STEP_SECONDS = 2.0
+STEP_TICKS = 40
# Vanilla's server moves a player who just joined on their own first ticks (a tiny step and back), which tracks
# them where they spawned; Horizon does not simulate its guests. These steps compare what the bar shows at
# their end (Bob has moved by then) rather than every packet.
@@ -147,6 +146,47 @@ def server_dir(directory, world=None):
return port
+class Client:
+ """A LocatorBarClient process driven by a script on its stdin. A step ends by the server's clock, not the wall's:
+ every script line has run (`sync`), the server has ticked `ticks` more times, and each client holds what the
+ server sent until then (a last `sync`). A server that stalls under load still gets all its ticks in the step,
+ where a fixed sleep filed a stalled server's packets under the next step."""
+
+ def __init__(self, command, port, out, log):
+ self.log = log
+ self.process = subprocess.Popen([*map(str, command), '127.0.0.1', str(port), str(out)], cwd=lab.ROOT,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+ text=True)
+
+ def tell(self, line):
+ self.process.stdin.write(line + '\n')
+ self.process.stdin.flush()
+
+ def sync(self, names):
+ """Every line told so far has run for these joined players, and they have received what the server sent
+ before."""
+ for name in names:
+ self.tell(f'sync {name}')
+ for name in names:
+ while (line := self.process.stdout.readline()) != f'synced {name}\n':
+ if not line:
+ raise AssertionError(f'the client exited (see {self.log.name})')
+ self.log.write(line)
+
+ def wait(self, server, names, ticks):
+ self.sync(names)
+ wait_ticks(server, ticks)
+ self.sync(names)
+
+ def end(self):
+ self.tell('end')
+ self.log.write(self.process.communicate(timeout=60)[0])
+
+ def kill(self):
+ if self.process.poll() is None:
+ self.process.kill()
+
+
def generate_world(server_command, build):
"""The flat world both servers load, made once by vanilla: players appear at its spawn itself
(respawn_radius 0), on the ground at 0 -60 0, and the chunks around it are saved."""
@@ -176,28 +216,26 @@ def run_side(label, server_command, client_command, build, world):
try:
server.wait_for(r'Done \(')
with (build / f'{label}-client.log').open('w') as log:
- client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)],
- cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
- text=True)
+ client = Client(client_command, port, out, log)
+ joined = []
try:
for step, console, actions in SCRIPT:
- client.stdin.write(f'step {step}\n')
- client.stdin.flush()
+ client.tell(f'step {step}')
for command in console:
server.console(command)
for action in actions:
- client.stdin.write(action + '\n')
- client.stdin.flush()
- if action.startswith('join'):
+ client.tell(action)
+ verb, *rest = action.split()
+ if verb == 'join':
# Joining takes the world's first chunks: wait for the server to place the player.
- server.wait_for(rf'{action.split()[1]} joined the game', timeout=120)
- time.sleep(STEP_SECONDS)
- client.stdin.write('end\n')
- client.stdin.flush()
- client.wait(timeout=60)
+ server.wait_for(rf'{rest[0]} joined the game', timeout=120)
+ joined.append(rest[0])
+ elif verb == 'quit':
+ joined.remove(rest[0])
+ client.wait(server, joined, STEP_TICKS)
+ client.end()
finally:
- if client.poll() is None:
- client.kill()
+ client.kill()
finally:
server.stop()
if not out.exists():
@@ -234,10 +272,11 @@ def sides(name):
def one_player(name, script, shown, check, scope, step_seconds=4.0):
"""A harness of one player, Alice: on each server she joins, then runs `script`, a list of (step, client
- actions) `step_seconds` apart. The lines `shown(transcript)` keeps must match vanilla's exactly, and
+ actions) that each last `step_seconds` of the server's time (20 ticks a second). The lines `shown(transcript)` keeps must match vanilla's exactly, and
`check(vanilla's shown lines, vanilla's transcript)` returns why vanilla's run is no proof (the script did
not run), or None."""
lock, build, vanilla_server, horizon_server, client = sides(name)
+ ticks = round(step_seconds * 20)
def run(label, server_command, world):
directory = build / label
@@ -248,27 +287,20 @@ def one_player(name, script, shown, check, scope, step_seconds=4.0):
try:
server.wait_for(r'Done \(')
with (build / f'{label}-client.log').open('w') as log:
- process = subprocess.Popen([*map(str, client), '127.0.0.1', str(port), str(out)], cwd=lab.ROOT,
- stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, text=True)
-
- def tell(line):
- process.stdin.write(line + '\n')
- process.stdin.flush()
+ session = Client(client, port, out, log)
try:
for line in ['players on', 'state on', 'step joins', 'join Alice']:
- tell(line)
+ session.tell(line)
server.wait_for(r'Alice joined the game', timeout=120)
- time.sleep(step_seconds)
+ session.wait(server, ['Alice'], ticks)
for step, actions in script:
- tell(f'step {step}')
+ session.tell(f'step {step}')
for action in actions:
- tell(action)
- time.sleep(step_seconds)
- tell('end')
- process.wait(timeout=60)
+ session.tell(action)
+ session.wait(server, ['Alice'], ticks)
+ session.end()
finally:
- if process.poll() is None:
- process.kill()
+ session.kill()
finally:
server.stop()
if not out.exists():
diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py
index 87a7a1403..2ce6541e8 100644
--- a/tools/test_mob_ai_parity.py
+++ b/tools/test_mob_ai_parity.py
@@ -311,6 +311,23 @@ def scenarios():
add('villager_golem_panic', 100, ['fill -2 -60 -3 4 -60 4 minecraft:oak_fence', 'fill -1 -60 -2 3 -60 3 minecraft:air',
'player 14.5 -60 0.5'] + golem_callers[:3]
+ ['mob minecraft:zombie 6.5 -60 0.5 90 86 persistent noai'], 'time=18000')
+ # Mob.checkDespawn removes disallowed types before persistence/NoAI checks.
+ # Keep the non-Peaceful controls and the allowed hostile/neutral exceptions.
+ for difficulty in range(4):
+ for flags in ('', 'persistent', 'named', 'noai', 'persistent noai'):
+ suffix = flags.replace(' ', '_') or 'ordinary'
+ add(f'peaceful_zombie_{difficulty}_{suffix}', 1, [
+ 'player 6.5 -60 0.5',
+ f'mob minecraft:zombie 0.5 -60 0.5 0 1 {flags}',
+ ], f'difficulty={difficulty} time=18000')
+ # Not slime, piglin or bee: a slime made without finalizeSpawn keeps 20 health, the probe
+ # doesn't model a piglin's brain, and a NoAI bee's flower cooldown differs (none of it Peaceful).
+ for species in ('skeleton', 'creeper', 'warden', 'wither', 'shulker', 'wolf', 'iron_golem', 'cow'):
+ add(f'peaceful_type_{species}', 1, [
+ 'player 6.5 -60 0.5',
+ f'mob minecraft:{species} 0.5 -60 0.5 0 1 persistent noai',
+ ], 'difficulty=0 time=18000')
+
return s
diff --git a/tools/test_server_dimension_players_parity.py b/tools/test_server_dimension_players_parity.py
index 7ce04cb3f..ea026a509 100644
--- a/tools/test_server_dimension_players_parity.py
+++ b/tools/test_server_dimension_players_parity.py
@@ -16,17 +16,16 @@ import platform
import shutil
import subprocess
import sys
-import time
try:
from . import lab, test_rust_parity as base
from .test_dedicated_server_parity import Server
- from .test_locator_bar_parity import generate_world, server_dir
+ from .test_locator_bar_parity import Client, generate_world, server_dir
except ImportError:
import lab
import test_rust_parity as base
from test_dedicated_server_parity import Server
- from test_locator_bar_parity import generate_world, server_dir
+ from test_locator_bar_parity import Client, generate_world, server_dir
NAME = 'server-dimension-players-parity'
NETHER, END, OVERWORLD = 'minecraft:the_nether', 'minecraft:the_end', 'minecraft:overworld'
@@ -47,7 +46,8 @@ SCRIPT = [
('bob-retarget-portal', ['cmd Bob setblock 0 101 3 minecraft:end_portal', 'cmd Bob tp @s 0.5 101 3.5']),
('bob-retarget-back', [f'cmd Bob execute in {OVERWORLD} run tp @s 2.5 100 0.5']),
]
-STEP_SECONDS = 5.0
+PLAYERS = ('Alice', 'Bob')
+STEP_TICKS = 100
def run_side(label, server_command, client_command, build, world):
@@ -59,38 +59,30 @@ def run_side(label, server_command, client_command, build, world):
try:
server.wait_for(r'Done \(')
with (build / f'{label}-client.log').open('w') as log:
- client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)],
- cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
- text=True)
-
- def tell(line):
- client.stdin.write(line + '\n')
- client.stdin.flush()
+ client = Client(client_command, port, out, log)
try:
- tell('players on')
- tell('step joins')
- for name, x in (('Alice', 0.5), ('Bob', 2.5)):
- tell(f'join {name}')
+ client.tell('players on')
+ client.tell('step joins')
+ for name, x in zip(PLAYERS, (0.5, 2.5)):
+ client.tell(f'join {name}')
server.wait_for(rf'{name} joined the game', timeout=120)
- tell(f'fly {name} on')
- tell(f'cmd {name} tp @s {x} 100 0.5')
- time.sleep(STEP_SECONDS)
+ client.tell(f'fly {name} on')
+ client.tell(f'cmd {name} tp @s {x} 100 0.5')
+ client.wait(server, PLAYERS, STEP_TICKS)
for step, actions in SCRIPT:
- tell(f'step {step}')
+ client.tell(f'step {step}')
for action in actions:
- tell(action)
+ client.tell(action)
# Standing still, a client still sends its position every 20 ticks
# (LocalPlayer.sendPosition): the server then tracks to it what it has sent the
# chunks of since (ChunkMap.move).
- time.sleep(STEP_SECONDS / 2)
- tell('still Alice')
- tell('still Bob')
- time.sleep(STEP_SECONDS / 2)
- tell('end')
- client.wait(timeout=60)
+ client.wait(server, PLAYERS, STEP_TICKS // 2)
+ for name in PLAYERS:
+ client.tell(f'still {name}')
+ client.wait(server, PLAYERS, STEP_TICKS // 2)
+ client.end()
finally:
- if client.poll() is None:
- client.kill()
+ client.kill()
finally:
server.stop()
if not out.exists():
diff --git a/tools/test_server_knockback_parity.py b/tools/test_server_knockback_parity.py
index d7fbaeba1..66b75946e 100644
--- a/tools/test_server_knockback_parity.py
+++ b/tools/test_server_knockback_parity.py
@@ -18,6 +18,11 @@ players made of vanilla's protocol code, joins them both and runs one script on
travelled a tick (the mob's hit, then ServerPlayer's travel, then ServerEntity.sendChanges). It is night, so
that no zombie burns (a burning mob is in its hurt cooldown).
+The script waits on the server, not on the wall: `ticks N` is N ticks of its game clock (with a `sync` round trip
+before and after, so each client holds what the server sent), `tickstep` is one `/tick step` that has run, `frozen`
+a frozen game that has stopped, and `hit` a hit that has landed (a frozen server still ticks its players, so a hit
+lands in Alice's next tick). A server that stalls under load gets the same ticks as an idle one.
+
Each case is compared on its own. KNOWN lists the cases Horizon still gets wrong and why; one that matches
again is reported, and should leave the list.
"""
@@ -32,15 +37,16 @@ import time
try:
from . import lab, test_rust_parity as base
- from .test_dedicated_server_parity import Server, free_port
+ from .test_dedicated_server_parity import Server, free_port, game_time, wait_ticks
from .test_locator_bar_parity import generate_world, ops_json
except ImportError:
import lab
import test_rust_parity as base
- from test_dedicated_server_parity import Server, free_port
+ from test_dedicated_server_parity import Server, free_port, game_time, wait_ticks
from test_locator_bar_parity import generate_world, ops_json
NAME = 'server-knockback-parity'
+PLAYERS = ('Alice', 'Bob')
PROPERTIES = {
'online-mode': 'false',
'white-list': 'false',
@@ -82,18 +88,17 @@ def mob_case(kind, weapon=SWORD, sprint=False, crit=False, air=False):
f'cmd Alice effect give {mob} minecraft:slowness 100000 127 true']
lines = ['cmd Alice kill @e[type=!player]', 'cmd Alice gamemode creative', 'cmd Bob gamemode creative',
f'cmd Alice item replace entity @s weapon.mainhand with {weapon}', 'cmd Alice tp Bob 2.5 -60 12.5',
- *stand('Alice', A, -90), 'sleep 1.2']
+ *stand('Alice', A, -90), 'ticks 24']
# In the air: frozen before its first tick, so it has not landed.
- lines += ['cmd Alice tick freeze', *summon] if air else [*summon, 'sleep 1.5', 'cmd Alice tick freeze']
- lines += ['sleep 0.3', f'cmd Alice data get entity {mob} Pos']
+ lines += ['cmd Alice tick freeze', 'frozen', *summon] if air else [*summon, 'ticks 30', 'cmd Alice tick freeze', 'frozen']
+ lines += [f'cmd Alice data get entity {mob} Pos']
if sprint:
lines.append('sprint Alice on')
if crit:
lines += falling(0.8)
- lines += ['sleep 0.2', f'attack Alice {kind}', 'sleep 0.2', f'cmd Alice data get entity {mob} Motion']
+ lines += [f'hit {kind}', f'cmd Alice data get entity {mob} Motion']
for _ in range(20):
- lines += ['cmd Alice tick step 1', 'sleep 0.25', f'cmd Alice data get entity {mob} Pos',
- f'cmd Alice data get entity {mob} Motion']
+ lines += ['tickstep', f'cmd Alice data get entity {mob} Pos', f'cmd Alice data get entity {mob} Motion']
lines += ['cmd Alice tick unfreeze', 'cmd Alice kill @e[type=!player]']
if sprint:
lines.append('sprint Alice off')
@@ -114,7 +119,7 @@ def pvp_case(weapon=SWORD, sprint=False, crit=False, shield=False, armour=False,
if shield:
# A shield blocks from five ticks after it is raised.
lines += ['cmd Bob item replace entity @s weapon.mainhand with minecraft:shield', 'use Bob']
- lines += ['sleep 1.5', *stand('Bob', V, 90, ticks=1)]
+ lines += ['ticks 30', *stand('Bob', V, 90, ticks=1)]
if sprint:
lines.append('sprint Alice on')
if crit:
@@ -124,10 +129,12 @@ def pvp_case(weapon=SWORD, sprint=False, crit=False, shield=False, armour=False,
if cooldown:
# A swing at the air first: the hit is weak, and the stronger one four ticks later lands inside Bob's hurt
# cooldown (LivingEntity.hurtServer: it hurts by the difference, with no knockback and no motion packet).
- lines += ['sleep 0.2', 'punch Alice', 'attack Alice Bob']
- lines += ['sleep 0.2', 'attack Alice Bob', 'sleep 0.3']
+ lines += ['ticks 4', 'punch Alice', 'attack Alice Bob']
+ # The gap between those two hits is an upper bound on the server's ticks, so a stalled server (which gets
+ # fewer in a wall's 0.2 s) still lands the second inside the cooldown; the rest is to have the server's ticks.
+ lines += ['sleep 0.2' if cooldown else 'ticks 4', 'attack Alice Bob', 'ticks 6']
if twice:
- lines += [*stand('Bob', V, 90, ticks=20), 'sleep 1.5', 'attack Alice Bob', 'sleep 0.3']
+ lines += [*stand('Bob', V, 90, ticks=20), 'ticks 30', 'attack Alice Bob', 'ticks 6']
if sprint:
lines.append('sprint Alice off')
lines += stand('Alice', A, -90)
@@ -144,7 +151,7 @@ def mob_hits_case(kind):
hit = ['mark Bob', f'cmd Alice summon minecraft:{kind} {V[0] + 1} {V[1]} {V[2]} {{Rotation:[90f,0f]}}',
f'cmd Alice effect give {mob} minecraft:slowness 100000 127 true', 'await Bob', f'cmd Alice kill {mob}']
return ['cmd Bob clear @s', 'cmd Bob effect give @s minecraft:resistance 1000 4 true', 'cmd Alice gamemode creative',
- *stand('Bob', V, 90), *hit, 'sleep 2', *stand('Bob', V, 90), *hit, 'sleep 1',
+ *stand('Bob', V, 90), *hit, 'ticks 40', *stand('Bob', V, 90), *hit, 'ticks 20',
'cmd Alice kill @e[type=!player]', 'cmd Alice gamemode survival']
@@ -173,7 +180,20 @@ CASES = {
}
SETUP = ['cmd Alice gamerule spawn_mobs false', 'cmd Alice gamerule spawn_monsters false',
'cmd Alice kill @e[type=!player]', 'cmd Alice gamerule advance_time false', 'cmd Alice time set midnight',
- f'cmd Alice tp Alice {A[0]} {A[1]} {A[2]} -90 0', f'cmd Alice tp Bob {V[0]} {V[1]} {V[2]} 90 0', 'sleep 2']
+ f'cmd Alice tp Alice {A[0]} {A[1]} {A[2]} -90 0', f'cmd Alice tp Bob {V[0]} {V[1]} {V[2]} 90 0', 'ticks 40']
+
+
+def server_data(server, selector, path, timeout=120):
+ """An entity's data, asked from the console (its reply stays in the server's log, out of the clients')."""
+ deadline = time.time() + timeout
+ start = len(server.lines)
+ server.console(f'data get entity {selector} {path}')
+ while time.time() < deadline:
+ for line in server.lines[start:]:
+ if 'has the following entity data' in line:
+ return line.split('data: ', 1)[-1]
+ time.sleep(0.02)
+ raise AssertionError(f'{server.log_path.name}: no entity data in {timeout} s')
def server_dir(directory, world):
@@ -201,29 +221,72 @@ def run_side(label, server_command, client_command, build, world):
server.wait_for(r'Done \(')
with (build / f'{label}-client.log').open('w') as log:
client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)],
- cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
- text=True)
+ cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT, text=True)
+
+ def sync():
+ """Every script line sent so far has run, and each client holds what its server sent before."""
+ for name in PLAYERS:
+ client.stdin.write(f'sync {name}\n')
+ client.stdin.flush()
+ for name in PLAYERS:
+ while (reply := client.stdout.readline()) != f'synced {name}\n':
+ if not reply:
+ raise AssertionError(f'{label}: the client exited (see {build}/{label}-client.log)')
+ log.write(reply)
def send(line):
- if line.startswith('sleep '):
+ """A script line for the client, or one of ours: the waits are on the server's game clock, not the
+ wall's, so a server that stalls under load still gets the ticks each case needs."""
+ word = line.split()[0]
+ if word == 'sleep':
time.sleep(float(line.split()[1]))
+ elif word == 'ticks':
+ sync()
+ wait_ticks(server, int(line.split()[1]))
+ sync()
+ elif word == 'frozen':
+ # The tick in flight when ticking was frozen has finished: the clock reads the same twice.
+ sync()
+ while game_time(server) != game_time(server):
+ pass
+ elif word == 'hit':
+ # Alice hits the mob. A frozen server still ticks its players, and the hit lands in Alice's
+ # next tick, not when the packet arrives: the mob's motion says when it has.
+ sync()
+ mob = f'@e[type=minecraft:{line.split()[1]},limit=1]'
+ before = server_data(server, mob, 'Motion')
+ client.stdin.write(f'attack Alice {line.split()[1]}\n')
+ client.stdin.flush()
+ while server_data(server, mob, 'Motion') == before:
+ time.sleep(0.05)
+ sync()
+ elif word == 'tickstep':
+ # `/tick step 1` answers at once and the tick runs after: the clock says when it has.
+ sync()
+ before = game_time(server)
+ client.stdin.write('cmd Alice tick step 1\n')
+ client.stdin.flush()
+ while game_time(server) == before:
+ time.sleep(0.05)
+ sync()
else:
client.stdin.write(line + '\n')
client.stdin.flush()
try:
- for name in ('Alice', 'Bob'):
+ for name in PLAYERS:
send(f'join {name}')
server.wait_for(rf'{name} joined the game', timeout=120)
- time.sleep(2)
+ wait_ticks(server, 40)
for line in SETUP:
send(line)
for case, lines in CASES.items():
send(f'step {case}')
for line in lines:
send(line)
- time.sleep(0.5)
+ send('ticks 10')
send('end')
- client.wait(timeout=60)
+ log.write(client.communicate(timeout=60)[0])
finally:
if client.poll() is None:
client.kill()
diff --git a/tools/test_server_ops_feedback_parity.py b/tools/test_server_ops_feedback_parity.py
index f7b7a0e73..91854fac6 100644
--- a/tools/test_server_ops_feedback_parity.py
+++ b/tools/test_server_ops_feedback_parity.py
@@ -19,17 +19,16 @@ import platform
import shutil
import subprocess
import sys
-import time
try:
from . import lab, test_rust_parity as base
- from .test_dedicated_server_parity import Server
- from .test_locator_bar_parity import generate_world, server_dir
+ from .test_dedicated_server_parity import Server, game_time
+ from .test_locator_bar_parity import Client, generate_world, server_dir
except ImportError:
import lab
import test_rust_parity as base
- from test_dedicated_server_parity import Server
- from test_locator_bar_parity import generate_world, server_dir
+ from test_dedicated_server_parity import Server, game_time
+ from test_locator_bar_parity import Client, generate_world, server_dir
NAME = 'server-ops-feedback-parity'
# (label, what the console does, what the players do).
@@ -53,7 +52,11 @@ QUIET = [
('alice', [], ['cmd Alice time set 3000']),
]
CASES = {'broadcast': ({}, BROADCAST), 'quiet': ({'broadcast-console-to-ops': 'false'}, QUIET)}
-STEP_SECONDS = 2.0
+STEP_TICKS = 40
+# A step ends by the server's clock (Client.wait): after a round trip of Alice's (Bob is deopped for a while, so
+# his is not used). While send_command_feedback is off a command has no reply for her, so those steps wait for
+# the ticks alone.
+NO_SYNC = {'feedback-off', 'console-feedback-off'}
# Steps whose reply can take longer than a step: the next step waits for this console line first. A loaded machine
# took 2 s to save vanilla's world, and the transcript ended before "Saved the game".
WAIT_FOR = {'console-save': r'System chat: Saved the game'}
@@ -72,33 +75,26 @@ def run_side(label, case, server_command, client_command, build, world):
try:
server.wait_for(r'Done \(')
with (build / f'{label}-{case}-client.log').open('w') as log:
- client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)],
- cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
- text=True)
-
- def tell(line):
- client.stdin.write(line + '\n')
- client.stdin.flush()
+ client = Client(client_command, port, out, log)
try:
for name in ('Alice', 'Bob'):
- tell(f'join {name}')
+ client.tell(f'join {name}')
server.wait_for(rf'{name} joined the game', timeout=120)
- time.sleep(STEP_SECONDS)
- tell('chat on')
+ client.wait(server, ['Alice'], STEP_TICKS)
+ client.tell('chat on')
for step, console, actions in script:
- tell(f'step {step}')
+ client.tell(f'step {step}')
for command in console:
server.console(command)
+ game_time(server) # the console runs its queue in order: these commands have run
for action in actions:
- tell(action)
+ client.tell(action)
if step in WAIT_FOR:
server.wait_for(WAIT_FOR[step], timeout=120)
- time.sleep(STEP_SECONDS)
- tell('end')
- client.wait(timeout=60)
+ client.wait(server, [] if step in NO_SYNC else ['Alice'], STEP_TICKS)
+ client.end()
finally:
- if client.poll() is None:
- client.kill()
+ client.kill()
finally:
server.stop()
if not out.exists():
diff --git a/website/build.mjs b/website/build.mjs
index b979f83f8..8e93c82b4 100644
--- a/website/build.mjs
+++ b/website/build.mjs
@@ -18,7 +18,7 @@ import { CPUS, GPUS, singleThread } from "./src/hardware.js";
import { isGame, isLauncher, launcherVersion, newestFirst } from "./src/versions.js";
import { contributorsFrom, contributorsHtml } from "./src/contributors.js";
import { areaFilterHtml, boardFilterHtml, boardFrom, boardHtml, creditFrom, creditHtml, helpWantedHtml, journalFrom, journalHtml, journalJson, overviewHtml, roadmapHtml, slimIssue, suggestItemsHtml } from "./src/hub.js";
-import { INDEX_URL, KINDS, SUBMIT, listHtml, projectHtml, readIndex, submitHtml } from "./src/mods.js";
+import { INDEX_URL, KINDS, SORTS, SUBMIT, listHtml, projectHtml, readIndex, sorted, submitHtml } from "./src/mods.js";
const site = dirname(fileURLToPath(import.meta.url));
const dist = join(site, "dist");
@@ -484,10 +484,11 @@ const modsList = ` ModsMade for Horizon, r
${KINDS.map(([k, label]) => ` `).join("\n")}
+
-${listHtml(modProjects)}
+${listHtml(sorted(modProjects, "downloads"))}
`;
const modPages = [
{ file: "mods.html", path: "/mods", title: "Mods", description: "Mods, modpacks and resource packs made for Horizon, reviewed, each with what it may do and how to install it.", main: modsList },
diff --git a/website/data/roadmap.json b/website/data/roadmap.json
index 58d697257..050b89394 100644
--- a/website/data/roadmap.json
+++ b/website/data/roadmap.json
@@ -1034,58 +1034,65 @@
{
"id": "item-cooldowns",
"title": "Cooldowns drawn on items",
- "status": "help-wanted",
+ "status": "now",
"area": "gameplay",
"plain": "After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla.",
"dev": "Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue #1763.",
"links": [
- "#1763"
+ "#1763",
+ "#1933"
]
},
{
"id": "chat-settings",
"title": "Chat settings and team prefixes",
- "status": "help-wanted",
+ "status": "now",
"area": "gameplay",
"plain": "The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before names in chat.",
"dev": "Vanilla checks `ChatVisiblity` before it delivers chat and system messages (#1376), and chat uses the team-formatted display name (#1378). Both issues have exact steps to reproduce.",
"links": [
"#1376",
- "#1378"
+ "#1378",
+ "#1932",
+ "#1841"
]
},
{
"id": "pointer-hand",
"title": "A pointing hand over buttons",
- "status": "help-wanted",
+ "status": "now",
"area": "gameplay",
"plain": "The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3.",
"dev": "26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue #1347.",
"links": [
- "#1347"
+ "#1347",
+ "#1897"
]
},
{
"id": "text-field-keys",
"title": "Ctrl+Backspace and scroll bars in menus",
- "status": "help-wanted",
+ "status": "now",
"area": "gameplay",
"plain": "Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be draggable.",
"dev": "`EditBox` deletes by word with Ctrl (#1764); the Game Rules and Statistics lists' scroll bars can't be dragged (#1782, after #978).",
"links": [
"#1764",
- "#1782"
+ "#1782",
+ "#1884",
+ "#1931"
]
},
{
"id": "chicken-flap",
"title": "Chickens flap while they fall",
- "status": "help-wanted",
+ "status": "now",
"area": "gameplay",
"plain": "Chickens should flap their wings while they fall, not stand still in the air.",
"dev": "Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue #1706.",
"links": [
- "#1706"
+ "#1706",
+ "#1892"
]
},
{
diff --git a/website/src/mods-page.js b/website/src/mods-page.js
index 121ba8067..335e863bd 100644
--- a/website/src/mods-page.js
+++ b/website/src/mods-page.js
@@ -1,32 +1,47 @@
-// /mods and /mods/