Merge origin/main into #800 (execute in: source dimension)
main's #880 added Source::level and Source::elsewhere for server players teleported into another level; this branch adds Source::dimension and moves the local player. Kept dimension (it covers what elsewhere was read for) and level; /tp tries main's teleport_across for a server's players first, then this branch's local-player level switch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,7 +7,8 @@ runs through the CLI (one horizon-ctl process per command) and through `horizon-
|
||||
small JSON-RPC client, and saves a screenshot of each run. The ui scenario drives the menus by
|
||||
widget id instead: the title screen, the options (a slider set by id) and the inventory's slots;
|
||||
the options scenario reads and sets options.txt values by key; the events scenario waits for
|
||||
states (wait-for) and reads the event log.
|
||||
states (wait-for) and reads the event log; the consume scenario eats and drinks consumables (a
|
||||
golden apple, milk, honey, chorus fruit) and checks their effects, remainders and teleport.
|
||||
|
||||
python3 tools/agent_control_e2e.py # both modes
|
||||
python3 tools/agent_control_e2e.py --mode mcp # one of them
|
||||
@@ -378,7 +379,52 @@ def events_scenario(d, out):
|
||||
return {'events': len(events)}
|
||||
|
||||
|
||||
SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario}
|
||||
def consume_scenario(d, out):
|
||||
# Consumables finish as vanilla's Consumable.onConsume: always-edible food at full hunger with its
|
||||
# effects, milk and honey (no food or drink sounds) with their effects and use remainders, and
|
||||
# chorus fruit's random teleport.
|
||||
d('click', id='singleplayer')
|
||||
if 'game' not in widgets(d):
|
||||
d('click', id='create-new-world')
|
||||
d('type', field='name', replace=True, text='Consume')
|
||||
d('click', id='create-new-world')
|
||||
d('wait_for', condition='loaded', timeout=400)
|
||||
|
||||
def consume(item, seconds):
|
||||
d('command', command='clear @s')
|
||||
d('give', item=item, count=1)
|
||||
d('use_item', hold=seconds)
|
||||
d('wait', ticks=5)
|
||||
state = d('state')
|
||||
return state, {e['id'] for e in state['player']['effects']}
|
||||
|
||||
def held(state):
|
||||
return state['held'] and state['held']['item']
|
||||
|
||||
state, effects = consume('golden_apple', 2.2)
|
||||
assert state['player']['food'] == 20 and {'regeneration', 'absorption'} <= effects, effects
|
||||
assert held(state) is None, state['held']
|
||||
d('command', command='effect give @s minecraft:speed 60')
|
||||
state, effects = consume('milk_bucket', 2.2)
|
||||
assert effects == set(), effects
|
||||
assert held(state) == 'minecraft:bucket', state['held']
|
||||
d('command', command='effect give @s minecraft:poison 60')
|
||||
d('command', command='effect give @s minecraft:speed 60')
|
||||
state, effects = consume('honey_bottle', 2.6)
|
||||
assert effects == {'speed'}, effects
|
||||
assert held(state) == 'minecraft:glass_bottle', state['held']
|
||||
before = d('state')['player']['position']
|
||||
state, _ = consume('chorus_fruit', 2.2)
|
||||
after = state['player']['position']
|
||||
moved = [b - a for a, b in zip(before, after)]
|
||||
assert held(state) is None, state['held']
|
||||
assert moved != [0, 0, 0] and abs(moved[0]) <= 8 and abs(moved[2]) <= 8, moved
|
||||
d('screenshot', path=str(out / f'consume-{d.name}.png'))
|
||||
return {'teleported': [round(m, 2) for m in moved]}
|
||||
|
||||
|
||||
SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario,
|
||||
'consume': consume_scenario}
|
||||
|
||||
|
||||
def run(mode, ctl, out, resources, which='survival'):
|
||||
|
||||
+10
-3
@@ -5,7 +5,8 @@ Windows .exe: every DLL in the import and delay-import tables must ship with
|
||||
Windows (no VCRUNTIME140.dll, vulkan-1.dll, ...): Vulkan and the like are
|
||||
loaded at run time, so a missing driver is an error message, not a dialog.
|
||||
Linux ELF: the loader must be the standard one (not a /nix/store path) and the
|
||||
needed libraries the ones every desktop distribution has.
|
||||
needed libraries the ones every desktop distribution has. `--server`: a server
|
||||
build, which may not need ALSA or udev either (minimal server images lack them).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -30,6 +31,8 @@ LINUX_SYSTEM = {
|
||||
"libc.so.6", "libm.so.6", "libgcc_s.so.1", "libdl.so.2", "libpthread.so.0", "librt.so.1",
|
||||
"ld-linux-x86-64.so.2", "libasound.so.2", "libudev.so.1",
|
||||
}
|
||||
# The game's sound (cpal) and controllers (gilrs): a desktop has them, a server image may not.
|
||||
LINUX_DESKTOP_ONLY = {"libasound.so.2", "libudev.so.1"}
|
||||
|
||||
|
||||
def windows_allowed(name):
|
||||
@@ -111,7 +114,7 @@ def elf_needs(data):
|
||||
return interpreter, needed, runpath
|
||||
|
||||
|
||||
def check(path):
|
||||
def check(path, server=False):
|
||||
data = Path(path).read_bytes()
|
||||
problems = []
|
||||
if data[:2] == b"MZ":
|
||||
@@ -123,6 +126,8 @@ def check(path):
|
||||
if interpreter not in (None, LINUX_LOADER):
|
||||
problems.append(f"loader is {interpreter}, not {LINUX_LOADER}")
|
||||
problems += [f"needs {n}, which not every distribution has" for n in needed if n not in LINUX_SYSTEM]
|
||||
if server:
|
||||
problems += [f"needs {n}, which a server may not have" for n in needed if n in LINUX_DESKTOP_ONLY]
|
||||
problems += [f"has a run path to {p}" for p in runpath if "/nix/store" in p]
|
||||
summary = f"{interpreter}; " + ", ".join(needed)
|
||||
print(f"{path}: {summary}")
|
||||
@@ -134,8 +139,10 @@ def check(path):
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("binaries", nargs="+")
|
||||
parser.add_argument("--server", action="store_true",
|
||||
help="a server build: not even ALSA or udev (the game's sound and controllers)")
|
||||
args = parser.parse_args()
|
||||
ok = all([check(path) for path in args.binaries])
|
||||
ok = all([check(path, args.server) for path in args.binaries])
|
||||
sys.exit(0 if ok else 1)
|
||||
|
||||
|
||||
|
||||
+818
-13
@@ -19,10 +19,24 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
- hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes,
|
||||
drowning and the void (then respawns);
|
||||
- pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing;
|
||||
- respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the
|
||||
respawned player is a new entity to the others); the host dies, and on the server thread
|
||||
the guest too;
|
||||
- hurt: a pig the guest hits, and one the host hits, flashes red on the other side too (the
|
||||
server's damage event) (#848);
|
||||
- containers: the guest's ender chest holds the guest's items, not the host's, and a double chest
|
||||
opens as 9x6 with the right half first;
|
||||
- machines: a hopper, a dispenser and a dropper open on the guest's screen with their 5 and 9
|
||||
slots, and keep what the guest shift-clicks into them (#848);
|
||||
- brewing: a brewing stand opens on the guest's screen; blaze powder, nether wart and a bottle the
|
||||
guest shift-clicks go to the fuel, ingredient and bottle slots, and the stand's fuel shows
|
||||
(#848);
|
||||
- feedback: the guest's command feedback names the guest and shows the numbers;
|
||||
- chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the
|
||||
server thread the host window's too;
|
||||
- effects: a beacon's power reaches every player in range, the host and the guest;
|
||||
- distance: (--server-thread) the server follows the host's render distance, past vanilla's 32 too
|
||||
(IntegratedServer.tickServer), and the guest's chunks follow the server's (#804)
|
||||
- portals: (--server-thread) the server holds a level per dimension: the guest goes to the Nether
|
||||
through a portal while the host stays, then the host goes to the End while the guest is in
|
||||
the Nether, and both come back.
|
||||
@@ -30,6 +44,36 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
tree (Tab), and runs what it completed;
|
||||
- recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it
|
||||
places a log in the inventory's crafting grid (the server places it).
|
||||
- feedback: the guest's command feedback names the guest and shows the numbers, and the host (an
|
||||
operator) is told of it as `[Guest: ...]`.
|
||||
- clicks: with real mouse presses (not click-slot, which skips the screen's press and drag
|
||||
handling), the guest puts a stack into a chest and a furnace, drags planks across
|
||||
its crafting grid and gathers a stack with a double click; the server has each.
|
||||
- sleep: at night the guest lies down in its own bed (not the host); alone it stays night, it
|
||||
gets up with Escape, and once the host sleeps too the night ends and both wake.
|
||||
- push: a cow standing in the guest pushes it just clear of the cow (the guest's own client
|
||||
pushes it, as in vanilla), not ever faster across the ground.
|
||||
- eat: holding right click with bread, the guest's own screen plays the eating (the item in use
|
||||
counts up) and the server eats one loaf and feeds the guest.
|
||||
- eating: each side sees the other player eat: the item in use (LivingEntity's flags) on the
|
||||
player it draws, and no longer once the bread is eaten (#803);
|
||||
- xp: experience orbs 4 blocks away fly to the guest, show on the guest's screen and give the
|
||||
guest their points (not the host).
|
||||
- objects: boats, minecarts, armor stands, item frames and paintings the host summons reach the
|
||||
guest as the host has them (kind, place, rotation, what they hold or wear, the variant).
|
||||
- projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where
|
||||
the host has them; a falling block lands on both sides.
|
||||
- plates: a stone pressure plate the guest steps on is pressed on both sides, and comes up once
|
||||
the guest steps off (#848).
|
||||
- swings: each side sees the other's arm swing while it mines a block, and the guest sees its own
|
||||
swing when its hoe tills dirt (the server's use) (#848).
|
||||
- time: the guest's clock is the host's: it stops with `/time pause`, and catches up with the
|
||||
server's game time after the guest's game stalls for a few seconds (#848).
|
||||
- growth: far from the host, the chunks around the guest tick (#890): water placed there flows
|
||||
and wheat on farmland grows (random ticks), however the host runs its world.
|
||||
- light: the guest's light matches the host's: around a torch placed near it, under a roof and
|
||||
once a block of the roof is removed under the sky, and in the last chunk it tracks next to
|
||||
glowstone in a chunk it doesn't (only the server's light updates bring that one).
|
||||
|
||||
Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of
|
||||
both sides go to --out (host-*.png, guest-*.png).
|
||||
@@ -47,9 +91,11 @@ import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
@@ -61,7 +107,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
GUEST_NAME = 'Guest'
|
||||
# The host plays single player on its server thread (--server-thread).
|
||||
SERVER_THREAD = False
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'recipes', 'trials', 'effects', 'portals']
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'plates', 'effects', 'portals', 'distance', 'growth']
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -174,7 +220,7 @@ def check_armour(host, guest, out):
|
||||
face_each_other(host, guest)
|
||||
host.shot(out, 'armour')
|
||||
guest.shot(out, 'armour')
|
||||
seen = host.raw('lan', 'status')['guests'][0].get('model_armor')
|
||||
seen = lan_guest(host).get('model_armor')
|
||||
assert seen == [None, 'minecraft:diamond_chestplate', 'minecraft:diamond_leggings', None], \
|
||||
f'the host draws the guest in {seen}'
|
||||
host_gear = [e for e in remote(guest).get('player_equipment', [])]
|
||||
@@ -337,6 +383,33 @@ def nether_portal(game, x, y, z):
|
||||
game('command', command=f'fill {x} {y} {z} {x + 1} {y + 2} {z} minecraft:nether_portal[axis=x]')
|
||||
|
||||
|
||||
def lan_guest(host):
|
||||
"""The guest's entry in the host's `lan status` (on the server thread the owner is listed too)."""
|
||||
guests = host.raw('lan', 'status')['guests']
|
||||
return next(g for g in guests if g['name'] == GUEST_NAME)
|
||||
|
||||
def check_distance(host, guest, out):
|
||||
"""IntegratedServer.tickServer: the server takes the host's render distance as its view distance
|
||||
(past 32, which Horizon's options allow) and sends it to every player (SetChunkCacheRadius)."""
|
||||
if not SERVER_THREAD:
|
||||
return 'skipped (needs --server-thread)'
|
||||
seen = {}
|
||||
try:
|
||||
for distance in (48, 6):
|
||||
host.raw('render-distance', distance)
|
||||
# The pause screen doesn't hold the server here: it follows on its next tick.
|
||||
host.wait(20)
|
||||
guest.wait(20)
|
||||
seen[distance] = (host('status').get('render_distance'), guest('status').get('render_distance'))
|
||||
finally:
|
||||
host.raw('render-distance', 12)
|
||||
# A client streams out to min(its render distance, the server's view distance + 1).
|
||||
assert seen[48][0] == 48, f'the host at 48 streams {seen[48][0]} chunks out (all: {seen})'
|
||||
assert seen[6][0] == 6, f'the host at 6 streams {seen[6][0]} chunks out (all: {seen})'
|
||||
assert seen[6][1] == 7, f'the guest streams {seen[6][1]} with the server at 6 (all: {seen})'
|
||||
return seen
|
||||
|
||||
|
||||
def check_portals(host, guest, out):
|
||||
if not SERVER_THREAD:
|
||||
return 'skipped (needs --server-thread)'
|
||||
@@ -441,6 +514,9 @@ def check_hazards(host, guest, out):
|
||||
# A fresh life: full health, so no regeneration eats food while the guest runs.
|
||||
guest('command', command='kill @s')
|
||||
guest.wait(20)
|
||||
# ServerPlayer.doTick sends the dead player's health of 0 too.
|
||||
died = {'screen': guest('state').get('screen'), 'health': remote(guest)['health']}
|
||||
assert died == {'screen': 'dead', 'health': 0.0}, f'the guest was killed: {died}'
|
||||
guest.raw('respawn')
|
||||
guest.wait(40)
|
||||
# Sprint-jumping down a stone lane: ServerPlayer.jumpFromGround and checkMovementStatistics.
|
||||
@@ -449,14 +525,14 @@ def check_hazards(host, guest, out):
|
||||
guest.wait(10)
|
||||
x, y, z = pos_of(guest)
|
||||
guest.raw('look-at', f'{x + 60:.2f}', f'{y + 1.6:.2f}', f'{z:.2f}')
|
||||
food = host.raw('lan', 'status')['guests'][0]['food']
|
||||
food = lan_guest(host)['food']
|
||||
for k in ('w', 'ctrl', 'space'):
|
||||
guest.raw('key', k, 'down')
|
||||
guest.wait(160)
|
||||
for k in ('space', 'ctrl', 'w'):
|
||||
guest.raw('key', k, 'up')
|
||||
guest.wait(10)
|
||||
fed = host.raw('lan', 'status')['guests'][0]['food']
|
||||
fed = lan_guest(host)['food']
|
||||
hunger = {'before': food, 'after': fed}
|
||||
hurt = {}
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
@@ -493,7 +569,7 @@ def check_hazards(host, guest, out):
|
||||
assert spent > 1.0, f'no hunger from moving: {hunger} ({spent:.2f} spent)'
|
||||
for name, (before, after) in hurt.items():
|
||||
assert after < before, f'{name} never hurt the guest: health {before} -> {after} (all: {hurt})'
|
||||
return {'hunger': hunger, **hurt}
|
||||
return {'died': died, 'hunger': hunger, **hurt}
|
||||
|
||||
|
||||
def check_pvp(host, guest, out):
|
||||
@@ -522,6 +598,72 @@ def check_pvp(host, guest, out):
|
||||
return hits
|
||||
|
||||
|
||||
def dead_players(game, want, ticks=60):
|
||||
"""The other players `game`'s client draws dead, once that is `want` (empty or not) or after `ticks`."""
|
||||
for _ in range(ticks // 5):
|
||||
dead = remote(game)['dead_players']
|
||||
if bool(dead) == want:
|
||||
return dead
|
||||
game.wait(5)
|
||||
return dead
|
||||
|
||||
|
||||
def check_respawn(host, guest, out):
|
||||
# ServerLevel.removePlayerImmediately and addRespawnedPlayer: a respawned player is removed
|
||||
# from the other players and paired again as a new entity, so their clients drop the body.
|
||||
# The host window only has a client's view of the guest on the server thread.
|
||||
for g in (host, guest):
|
||||
back_to_game(g)
|
||||
results = {}
|
||||
sides = [('host', host, guest)] + ([('guest', guest, host)] if SERVER_THREAD else [])
|
||||
for name, dying, watching in sides:
|
||||
face_each_other(host, guest)
|
||||
dying('command', command='kill @s')
|
||||
dying.wait(30)
|
||||
dead = dead_players(watching, True)
|
||||
watching.shot(out, f'respawn-{name}-dead')
|
||||
dying.raw('respawn')
|
||||
dying.wait(40)
|
||||
back_to_game(dying)
|
||||
# Back within tracking range of the other player, wherever the respawn point is.
|
||||
x, y, z = pos_of(dying)
|
||||
watching('command', command=f'tp @s {x + 3:.2f} {y:.2f} {z:.2f}')
|
||||
watching.wait(40)
|
||||
alive = dead_players(watching, False)
|
||||
watching.shot(out, f'respawn-{name}-alive')
|
||||
results[name] = {'dead': dead, 'after_respawn': alive}
|
||||
assert dead, f'the {name} was not drawn dead: {results}'
|
||||
assert not alive, f'the {name} still lies dead after respawning: {results}'
|
||||
return results
|
||||
|
||||
|
||||
def check_hurt(host, guest, out):
|
||||
for g in (host, guest):
|
||||
g('command', command='gamemode survival')
|
||||
g('command', command='clear @s')
|
||||
face_each_other(host, guest)
|
||||
hx, hy, hz = pos_of(host)
|
||||
# Between the two, within both players' reach; bare hands leave it alive.
|
||||
host('command', command=f'summon minecraft:pig {hx + 1.5:.2f} {hy:.2f} {hz + 0.8:.2f} {{NoAI:1b}}')
|
||||
host.wait(30)
|
||||
|
||||
def pig(game):
|
||||
return game.raw('entities', 6, 'pig')['entities'][0]
|
||||
seen = {}
|
||||
for name, attacker, watcher in (('guest hits', guest, host), ('host hits', host, guest)):
|
||||
attacker.wait(30) # a full attack charge
|
||||
attacker.raw('attack', pig(attacker)['id'])
|
||||
seen[name] = {'attacker': pig(attacker)['hurt_time'], 'watcher': pig(watcher)['hurt_time']}
|
||||
attacker.shot(out, 'hurt-' + name.replace(' ', '-'))
|
||||
watcher.shot(out, 'hurt-' + name.replace(' ', '-') + '-seen')
|
||||
attacker.wait(20)
|
||||
host('command', command='kill @e[type=minecraft:pig]')
|
||||
# LivingEntity.hurtTime: 10 when hurt, one less each tick; the reads come a few ticks later.
|
||||
for name, sides in seen.items():
|
||||
assert all(t > 0 for t in sides.values()), f'{name}: the pig\'s hurt flash {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def container_items(game):
|
||||
"""The open container's stacks by slot (Horizon's container slots are 300 and up) and its size."""
|
||||
slots = [s for s in game('screen').get('slots', []) if s.get('slot', 0) >= 300]
|
||||
@@ -584,12 +726,162 @@ def check_containers(host, guest, out):
|
||||
return {'ender': ender, 'double': double, 'taken': taken}
|
||||
|
||||
|
||||
def check_machines(host, guest, out):
|
||||
# After `recipes`: the stacks given here unlock recipes, which would move the book's first one.
|
||||
guest('command', command='gamemode survival')
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
at = (x, y, z + 2)
|
||||
seen = {}
|
||||
for block in ('hopper', 'dispenser', 'dropper'):
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='give @s minecraft:cobblestone 4')
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:{block}')
|
||||
guest.wait(10)
|
||||
guest.raw('interact', *at)
|
||||
guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
|
||||
guest.wait(10)
|
||||
size = container_items(guest)[1]
|
||||
guest.shot(out, f'machines-{block}')
|
||||
guest.raw('click-slot', hotbar_slot(guest, 'minecraft:cobblestone'), 'shift')
|
||||
guest.wait(10)
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(10)
|
||||
# Opened again, the menu holds what the server has.
|
||||
seen[block] = (size, open_container(guest, at, out, f'machines-{block}-after')[0])
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
want = {'hopper': (5, {0: 'minecraft:cobblestone'}), 'dispenser': (9, {0: 'minecraft:cobblestone'}),
|
||||
'dropper': (9, {0: 'minecraft:cobblestone'})}
|
||||
assert seen == want, f'the machines on the guest: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def check_brewing(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
loads = ('blaze_powder', 'nether_wart', 'glass_bottle')
|
||||
for item in loads:
|
||||
guest('command', command=f'give @s minecraft:{item}')
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
at = (x, y, z + 2)
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:brewing_stand')
|
||||
guest.wait(10)
|
||||
guest.raw('interact', *at)
|
||||
guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
|
||||
guest.wait(10)
|
||||
size = container_items(guest)[1]
|
||||
# BrewingStandMenu.quickMoveStack: blaze powder to the fuel slot, an ingredient to its slot,
|
||||
# a bottle to the bottle slots.
|
||||
for item in loads:
|
||||
guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift')
|
||||
guest.wait(5)
|
||||
# BrewingStandBlockEntity.serverTick burns the blaze powder into 20 uses; the guest sees them
|
||||
# through the menu's data slots.
|
||||
guest.wait(10)
|
||||
info = guest.raw('menu')['info']
|
||||
guest.shot(out, 'brewing')
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(10)
|
||||
items = open_container(guest, at, out, 'brewing-after')[0]
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
seen = {'size': size, 'items': items, 'fuel': info and info.get('fuel')}
|
||||
want = {'size': 5, 'items': {0: 'minecraft:glass_bottle', 3: 'minecraft:nether_wart'}, 'fuel': 20}
|
||||
assert seen == want, f'the brewing stand on the guest: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def slot_point(game, slot):
|
||||
"""The GUI point in the middle of slot `slot` of the open screen (`ui`'s slot-N)."""
|
||||
for w in game.raw('ui')['widgets']:
|
||||
if w.get('id') == f'slot-{slot}':
|
||||
x, y, width, height = w['bounds']
|
||||
return x + width / 2, y + height / 2
|
||||
raise Failed(f'no slot {slot} on the screen')
|
||||
|
||||
|
||||
def mouse(game, *slots, right=False):
|
||||
"""Press over the first slot, move over the others and release: one click, or a drag."""
|
||||
points = [f'{v:.1f}' for s in slots for v in slot_point(game, s)]
|
||||
game.raw('drag-at', *(['right'] if right else []), *points)
|
||||
game.wait(4)
|
||||
|
||||
|
||||
def hotbar_slot(game, item):
|
||||
return next(s['slot'] for s in game('inventory')['hotbar'] if s and s.get('item') == item)
|
||||
|
||||
|
||||
def check_clicks(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='give @s minecraft:cobblestone 10')
|
||||
guest('command', command='give @s minecraft:coal 3')
|
||||
guest('command', command='give @s minecraft:raw_iron 2')
|
||||
guest('command', command='give @s minecraft:oak_planks 2')
|
||||
guest.wait(10)
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
chest, furnace = (x, y, z + 2), (x, y, z - 2)
|
||||
guest('command', command=f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest')
|
||||
guest('command', command=f'setblock {furnace[0]} {furnace[1]} {furnace[2]} minecraft:furnace')
|
||||
guest.wait(10)
|
||||
# Pick the cobblestone up and put it down in the chest's first slot.
|
||||
guest.raw('interact', *chest)
|
||||
guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
|
||||
guest.wait(10)
|
||||
mouse(guest, hotbar_slot(guest, 'minecraft:cobblestone'))
|
||||
mouse(guest, 300)
|
||||
guest.wait(10)
|
||||
guest.shot(out, 'clicks-chest')
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(10)
|
||||
in_chest, _ = open_container(guest, chest, out, 'clicks-chest-after')
|
||||
# Coal into the fuel slot, raw iron into the input.
|
||||
guest.raw('interact', *furnace)
|
||||
guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
|
||||
guest.wait(10)
|
||||
mouse(guest, hotbar_slot(guest, 'minecraft:coal'))
|
||||
mouse(guest, 301)
|
||||
mouse(guest, hotbar_slot(guest, 'minecraft:raw_iron'))
|
||||
mouse(guest, 300)
|
||||
guest.wait(10)
|
||||
guest.shot(out, 'clicks-furnace')
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(10)
|
||||
# Opening the furnace again resends the whole menu: the server's own view.
|
||||
in_furnace, _ = open_container(guest, furnace, out, 'clicks-furnace-after')
|
||||
# Two planks dragged over the 2x2 grid's left column: one each, four sticks.
|
||||
guest.raw('key', 'e', 'tap')
|
||||
guest.raw('wait-for', 'screen', 'inventory')
|
||||
guest.wait(5)
|
||||
mouse(guest, hotbar_slot(guest, 'minecraft:oak_planks'))
|
||||
mouse(guest, 100, 102)
|
||||
guest.wait(10)
|
||||
grid = {s['slot']: (s.get('item'), s.get('count')) for s in guest('screen').get('slots', [])
|
||||
if s.get('slot') in (100, 102, 200) and s.get('item')}
|
||||
guest.shot(out, 'clicks-drag')
|
||||
guest.raw('click-slot', 200, 'shift')
|
||||
guest.wait(10)
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(10)
|
||||
# The chest's menu brings the whole inventory as the server has it.
|
||||
open_container(guest, chest, out, 'clicks-inventory')
|
||||
counts = guest('inventory')['counts']
|
||||
for at in (chest, furnace):
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
assert in_chest == {0: 'minecraft:cobblestone'}, f'the chest holds {in_chest} after the guest put cobblestone in'
|
||||
assert in_furnace == {0: 'minecraft:raw_iron', 1: 'minecraft:coal'}, f'the furnace holds {in_furnace}'
|
||||
assert grid.get(100) == ('minecraft:oak_planks', 1) and grid.get(102) == ('minecraft:oak_planks', 1), \
|
||||
f'the drag left the grid as {grid}'
|
||||
assert counts.get('minecraft:stick') == 4 and 'minecraft:cobblestone' not in counts, f'inventory after: {counts}'
|
||||
return {'chest': in_chest, 'furnace': in_furnace, 'grid': grid, 'inventory': counts}
|
||||
|
||||
|
||||
def check_feedback(host, guest, out):
|
||||
x, y, z = (round(v, 1) for v in pos_of(guest))
|
||||
guest('command', command='item replace entity @s weapon.mainhand with minecraft:stick')
|
||||
guest('command', command=f'tp @s {x:.1f} {y:.1f} {z:.1f}')
|
||||
guest.wait(10)
|
||||
chat = guest.raw('messages', 5)['chat']
|
||||
# The host is an operator: broadcastToAdmins tells it, as `[Guest: ...]`.
|
||||
host_chat = host.raw('messages', 5)['chat']
|
||||
guest.raw('key', 't', 'tap')
|
||||
guest.wait(5)
|
||||
guest.shot(out, 'feedback')
|
||||
@@ -600,7 +892,9 @@ def check_feedback(host, guest, out):
|
||||
assert any(replaced in line for line in chat), f'no "{replaced}" in {chat}'
|
||||
assert any(line.startswith(f'Teleported {GUEST_NAME} to {x:.6f}') for line in chat), f'teleport feedback: {chat}'
|
||||
assert screen in (None, 'playing'), f'the chat did not close: {screen}'
|
||||
return chat
|
||||
told = f'[{GUEST_NAME}: Teleported {GUEST_NAME} to {x:.6f}'
|
||||
assert any(line.startswith(told) for line in host_chat), f'no "{told}" for the host: {host_chat}'
|
||||
return chat + host_chat
|
||||
|
||||
|
||||
def chat_input(game):
|
||||
@@ -634,11 +928,29 @@ def check_commands(host, guest, out):
|
||||
screen = guest('state').get('screen')
|
||||
guest('command', command='gamemode survival')
|
||||
guest.wait(10)
|
||||
# A node the tree marks ask_server (a bossbar id): the guest asks the
|
||||
# server, which completes it from its own bossbars.
|
||||
host('command', command='bossbar add pt6:check "Check"')
|
||||
host.wait(5)
|
||||
guest.raw('key', 'slash', 'tap')
|
||||
guest.wait(3)
|
||||
guest.raw('type', 'bossbar get pt')
|
||||
guest.wait(10)
|
||||
guest.raw('key', 'tab', 'tap')
|
||||
guest.wait(2)
|
||||
asked = chat_input(guest)
|
||||
for _ in range(3):
|
||||
if guest('screen').get('screen') != 'chat':
|
||||
break
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(3)
|
||||
host('command', command='bossbar remove pt6:check')
|
||||
assert literal == '/gamemode', f'Tab after /gamem: {literal!r}'
|
||||
assert argument == '/gamemode creative', f'Tab after /gamemode cr: {argument!r}'
|
||||
assert mode == 'creative', f'the completed command did not run: {mode}'
|
||||
assert screen in (None, 'playing'), f'the chat did not close: {screen}'
|
||||
return {'literal': literal, 'argument': argument, 'mode': mode}
|
||||
assert asked == '/bossbar get pt6:check', f'Tab after /bossbar get pt: {asked!r}'
|
||||
return {'literal': literal, 'argument': argument, 'mode': mode, 'ask_server': asked}
|
||||
|
||||
|
||||
def centre(rect):
|
||||
@@ -677,6 +989,33 @@ def check_recipes(host, guest, out):
|
||||
return {'known': known, 'grid': grid}
|
||||
|
||||
|
||||
def check_titles(host, guest, out):
|
||||
# TitleCommand sends the guest its title packets; its HUD shows and clears them.
|
||||
for command in ('title @s times 10 400 10', 'title @s subtitle "Under"', 'title @s title "Over"',
|
||||
'title @s actionbar "Bar"'):
|
||||
guest('command', command=command)
|
||||
guest.wait(5)
|
||||
shown = {k: guest.raw('messages', 1)[k] for k in ('title', 'subtitle', 'actionbar')}
|
||||
guest.shot(out, 'titles')
|
||||
guest('command', command='title @s clear')
|
||||
guest.wait(5)
|
||||
cleared = {k: guest.raw('messages', 1)[k] for k in ('title', 'subtitle')}
|
||||
assert shown == {'title': 'Over', 'subtitle': 'Under', 'actionbar': 'Bar'}, f'titles shown: {shown}'
|
||||
assert cleared == {'title': None, 'subtitle': None}, f'titles cleared: {cleared}'
|
||||
return {'shown': shown, 'cleared': cleared}
|
||||
|
||||
|
||||
def check_chat(host, guest, out):
|
||||
# The agent's event log follows a remote client's chat: `wait-for chat` sees the line another
|
||||
# player sends (and on the server thread the host window's own line, back from the server).
|
||||
line = f'chat check {int(time.time())}'
|
||||
host.raw('chat', line)
|
||||
seen = {g.name: g.raw('wait-for', 'chat', line, '--timeout', 10, '--since', 0).get('ok')
|
||||
for g in ((guest, host) if SERVER_THREAD else (guest,))}
|
||||
guest.shot(out, 'chat')
|
||||
return seen
|
||||
|
||||
|
||||
def png_rows(path):
|
||||
"""The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel."""
|
||||
data = Path(path).read_bytes()
|
||||
@@ -721,7 +1060,7 @@ def changed_pixels(a, b):
|
||||
def sneaking_on_host(host, want, ticks=40):
|
||||
"""Whether the host sees the guest crouching, once it matches `want` or after `ticks`."""
|
||||
for _ in range(ticks // 5):
|
||||
sneaking = host.raw('lan', 'status')['guests'][0]['sneaking']
|
||||
sneaking = lan_guest(host)['sneaking']
|
||||
if sneaking == want:
|
||||
return sneaking
|
||||
host.wait(5)
|
||||
@@ -782,6 +1121,27 @@ def wait_state(game, pos, key, want, ticks):
|
||||
return state_of(game, pos, key)
|
||||
|
||||
|
||||
def check_plates(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
plate = (x + 2, y, z)
|
||||
guest('command', command=f'setblock {plate[0]} {plate[1]} {plate[2]} minecraft:stone_pressure_plate')
|
||||
guest.wait(10)
|
||||
guest('command', command=f'tp @s {plate[0] + 0.5} {plate[1]} {plate[2] + 0.5}')
|
||||
pressed = {'host': wait_state(host, plate, 'powered', 'true', 40),
|
||||
'guest': wait_state(guest, plate, 'powered', 'true', 40)}
|
||||
guest.shot(out, 'plate-pressed')
|
||||
guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
|
||||
# PressurePlateBlock.getPressedTime: a stone plate checks again every 20 ticks.
|
||||
released = {'host': wait_state(host, plate, 'powered', 'false', 60),
|
||||
'guest': wait_state(guest, plate, 'powered', 'false', 60)}
|
||||
guest('command', command=f'setblock {plate[0]} {plate[1]} {plate[2]} minecraft:air')
|
||||
detail = {'pressed': pressed, 'released': released}
|
||||
assert pressed == {'host': 'true', 'guest': 'true'}, f'the plate under the guest: {detail}'
|
||||
assert released == {'host': 'false', 'guest': 'false'}, f'the plate after the guest left: {detail}'
|
||||
return detail
|
||||
|
||||
|
||||
def check_trials(host, guest, out):
|
||||
# The host watches as a spectator, whom neither block detects: only the guest can wake them.
|
||||
hx, hy, hz = pos_of(host)
|
||||
@@ -824,13 +1184,458 @@ def check_trials(host, guest, out):
|
||||
return {'spawner': trial, 'vault': active, 'rewarded': uuid(rewarded), 'host': uuid(host_uuid)}
|
||||
|
||||
|
||||
def bed_at(game, foot):
|
||||
"""A bed whose foot is at `foot`, its head one block east."""
|
||||
x, y, z = foot
|
||||
game('command', command=f'setblock {x} {y} {z} minecraft:red_bed[facing=east,part=foot]')
|
||||
game('command', command=f'setblock {x + 1} {y} {z} minecraft:red_bed[facing=east,part=head]')
|
||||
return [x + 1, y, z]
|
||||
|
||||
|
||||
def check_sleep(host, guest, out):
|
||||
for g in (host, guest):
|
||||
g('command', command='gamemode survival')
|
||||
host('command', command='time set midnight')
|
||||
gx, gy, gz = (int(v // 1) for v in pos_of(guest))
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
guest_bed = bed_at(guest, (gx, gy, gz + 2))
|
||||
host_bed = bed_at(host, (hx, hy, hz + 2))
|
||||
guest.wait(10)
|
||||
guest.raw('interact', *guest_bed)
|
||||
guest.wait(10)
|
||||
asleep = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'),
|
||||
'server': lan_guest(host).get('sleeping')}
|
||||
guest.shot(out, 'sleep-guest')
|
||||
# Alone in bed: still night 120 ticks later (everyone must sleep).
|
||||
guest.wait(120)
|
||||
night = host('state')['time']['time_of_day']
|
||||
# Escape gets the guest up (InBedChatScreen), then back to bed.
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(10)
|
||||
up = guest('state').get('sleeping')
|
||||
guest.raw('interact', *guest_bed)
|
||||
host.raw('interact', *host_bed)
|
||||
host.wait(130)
|
||||
after = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'),
|
||||
'time': host('state')['time']['time_of_day']}
|
||||
guest.shot(out, 'sleep-morning')
|
||||
for at in (guest_bed, host_bed):
|
||||
guest('command', command=f'fill {at[0] - 1} {at[1]} {at[2]} {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
host('command', command='time set day')
|
||||
detail = {'asleep': asleep, 'night': night, 'up': up, 'after': after}
|
||||
assert asleep['guest'] == guest_bed and asleep['server'] == guest_bed, f'the guest is not in its bed: {detail}'
|
||||
assert asleep['host'] is None, f'the guest\'s bed put the host to sleep: {detail}'
|
||||
assert 13000 < night < 23000, f'one of two players asleep ended the night: {detail}'
|
||||
assert up is None, f'Escape did not get the guest up: {detail}'
|
||||
assert after['guest'] is None and after['host'] is None and after['time'] < 1000, f'no morning: {detail}'
|
||||
return detail
|
||||
def check_push(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
x, y, z = (int(v // 1) + 0.5 for v in pos_of(guest))
|
||||
guest('command', command=f'tp @s {x} {y - 0.5} {z}')
|
||||
guest.wait(20)
|
||||
x, y, z = pos_of(guest)
|
||||
# A cow that doesn't walk, 0.3 east of the guest: the two boxes overlap until their centres are
|
||||
# 0.75 apart, so the push stops a fraction of a block away.
|
||||
guest('command', command=f'summon minecraft:cow {x + 0.3:.2f} {y:.2f} {z:.2f} {{NoAI:1b}}')
|
||||
guest.wait(60)
|
||||
nx, _, nz = pos_of(guest)
|
||||
guest.shot(out, 'push')
|
||||
guest('command', command='kill @e[type=minecraft:cow]')
|
||||
moved = ((nx - x) ** 2 + (nz - z) ** 2) ** 0.5
|
||||
detail = {'from': [round(x, 3), round(z, 3)], 'to': [round(nx, 3), round(nz, 3)], 'moved': round(moved, 3)}
|
||||
assert nx < x, f'the cow did not push the guest west: {detail}'
|
||||
assert moved < 1.5, f'the cow pushed the guest too far: {detail}'
|
||||
return detail
|
||||
def check_eat(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
# Hungry: the eating needs food below 20 (Player.canEat).
|
||||
guest('command', command='effect give @s minecraft:hunger 3 255')
|
||||
guest.wait(70)
|
||||
guest('command', command='effect clear @s')
|
||||
guest('command', command='give @s minecraft:bread 3')
|
||||
guest.wait(5)
|
||||
guest.raw('select', 'minecraft:bread')
|
||||
hungry = guest('state')['player']['food']
|
||||
# use-item --hold returns once released: watch the guest's screen meanwhile.
|
||||
hold = threading.Thread(target=guest.raw, args=('use-item', '--hold', 2.2))
|
||||
hold.start()
|
||||
using = []
|
||||
for _ in range(4):
|
||||
time.sleep(0.2)
|
||||
using.append(guest('state').get('using'))
|
||||
guest.shot(out, 'eat')
|
||||
hold.join()
|
||||
guest.wait(10)
|
||||
fed = guest('state')['player']['food']
|
||||
left = guest('inventory')['counts'].get('minecraft:bread', 0)
|
||||
detail = {'hungry': hungry, 'fed': fed, 'bread': left, 'using': using, 'after': guest('state').get('using')}
|
||||
assert hungry < 20, f'the guest is not hungry: {detail}'
|
||||
ticks = [u['ticks'] for u in using if u]
|
||||
assert len(ticks) >= 3 and ticks == sorted(ticks) and ticks[-1] > ticks[0], f'no eating on the guest\'s screen: {detail}'
|
||||
assert left == 2 and fed > hungry, f'the server did not eat one loaf: {detail}'
|
||||
assert detail['after'] is None, f'still eating after the release: {detail}'
|
||||
return detail
|
||||
|
||||
|
||||
def watch_mining(miner, pos, seen):
|
||||
"""Mine the block at `pos` (by hand, for seconds) and sample `seen()` meanwhile."""
|
||||
dig = threading.Thread(target=miner.raw, args=('break', *pos))
|
||||
dig.start()
|
||||
samples = []
|
||||
for _ in range(8):
|
||||
time.sleep(0.25)
|
||||
samples.append(seen())
|
||||
dig.join()
|
||||
return samples
|
||||
|
||||
|
||||
def check_swings(host, guest, out):
|
||||
for g in (host, guest):
|
||||
g('command', command='gamemode survival')
|
||||
g('command', command='clear @s')
|
||||
face_each_other(host, guest)
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
gx, gy, gz = (int(v // 1) for v in pos_of(guest))
|
||||
# Stone by hand takes 7.5 seconds: ServerboundPunchPacket every tick keeps the arm swinging.
|
||||
guest('command', command=f'setblock {gx} {gy} {gz + 1} minecraft:stone')
|
||||
host('command', command=f'setblock {hx} {hy} {hz + 1} minecraft:stone')
|
||||
host.wait(10)
|
||||
def swinging(game):
|
||||
# On its server thread the host's window is a client of its server too.
|
||||
if game is host and not SERVER_THREAD:
|
||||
return lan_guest(host).get('model_swinging')
|
||||
return any(e.get('swinging') for e in remote(game).get('player_equipment', []))
|
||||
# Most samples: a swing restarts only past its first half (SwingState.startIfAble), so a sample can
|
||||
# fall between two.
|
||||
host_sees = watch_mining(guest, (gx, gy, gz + 1), lambda: swinging(host))
|
||||
guest_sees = watch_mining(host, (hx, hy, hz + 1), lambda: swinging(guest))
|
||||
# A hoe on dirt: the server tills it and swings the guest's hand, on the guest's screen too.
|
||||
# Where the guest stands now (an earlier check can leave it on a ledge it then drops from).
|
||||
gx, gy, gz = (int(v // 1) for v in pos_of(guest))
|
||||
soil = (gx, gy - 1, gz + 1)
|
||||
guest('command', command=f'setblock {soil[0]} {soil[1]} {soil[2]} minecraft:dirt')
|
||||
# HoeItem.useOn tills only under air.
|
||||
guest('command', command=f'setblock {soil[0]} {soil[1] + 1} {soil[2]} minecraft:air')
|
||||
guest('command', command='give @s minecraft:wooden_hoe')
|
||||
guest.wait(10)
|
||||
guest.raw('select', 'minecraft:wooden_hoe')
|
||||
before = guest('state')['swings']
|
||||
guest.raw('interact', *soil)
|
||||
guest.wait(10)
|
||||
hoe = {'swings': guest('state')['swings'] - before, 'soil': host.raw('block', *soil)['block']}
|
||||
guest('command', command=f'setblock {soil[0]} {soil[1]} {soil[2]} minecraft:stone')
|
||||
detail = {'host_sees_guest': host_sees, 'guest_sees_host': guest_sees, 'hoe': hoe}
|
||||
assert sum(map(bool, host_sees)) >= 4, f'the host does not see the guest mine: {detail}'
|
||||
assert sum(map(bool, guest_sees)) >= 4, f'the guest does not see the host mine: {detail}'
|
||||
assert hoe == {'swings': 1, 'soil': 'minecraft:farmland'}, f'the guest\'s hoe: {detail}'
|
||||
return detail
|
||||
|
||||
|
||||
def check_eating(host, guest, out):
|
||||
for g in (host, guest):
|
||||
g('command', command='gamemode survival')
|
||||
g('command', command='clear @s')
|
||||
# Hungry: Player.canEat.
|
||||
g('command', command='effect give @s minecraft:hunger 3 255')
|
||||
host.wait(70)
|
||||
for g in (host, guest):
|
||||
g('command', command='effect clear @s')
|
||||
g('command', command='give @s minecraft:bread 2')
|
||||
host.wait(5)
|
||||
face_each_other(host, guest)
|
||||
|
||||
def using(game):
|
||||
# On its server thread the host's window is a client of its server too.
|
||||
if game is host and not SERVER_THREAD:
|
||||
return lan_guest(host).get('model_using') or 0
|
||||
return max((e.get('using') or 0 for e in remote(game).get('player_equipment', [])), default=0)
|
||||
seen = {}
|
||||
for name, eater, watcher in (('host eats', host, guest), ('guest eats', guest, host)):
|
||||
eater.raw('select', 'minecraft:bread')
|
||||
hold = threading.Thread(target=eater.raw, args=('use-item', '--hold', 2.2))
|
||||
hold.start()
|
||||
samples = []
|
||||
for _ in range(4):
|
||||
time.sleep(0.3)
|
||||
samples.append(using(watcher))
|
||||
watcher.shot(out, 'eating-' + name.replace(' ', '-'))
|
||||
hold.join()
|
||||
eater.wait(10)
|
||||
seen[name] = {'during': samples, 'after': using(watcher)}
|
||||
for name, s in seen.items():
|
||||
assert sum(1 for u in s['during'] if u > 0) >= 3 and s['after'] == 0, f'{name}: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def check_xp(host, guest, out):
|
||||
for g in (host, guest):
|
||||
g('command', command='gamemode survival')
|
||||
g('command', command='xp set @s 0 levels')
|
||||
g('command', command='xp set @s 0 points')
|
||||
# Out of the orbs' way wherever an earlier check left the host (ExperienceOrb follows the
|
||||
# nearest player who isn't a spectator).
|
||||
host('command', command='gamemode spectator')
|
||||
guest.wait(10)
|
||||
# `xp set` leaves Player.totalExperience (the score): experience from earlier checks stays in it.
|
||||
total = guest('state')['player']['xp']['total']
|
||||
host_total = host('state')['player']['xp']['total']
|
||||
x, y, z = pos_of(guest)
|
||||
# Three orbs of 7 points 4 blocks east of the guest (out of reach, within the 8 blocks orbs
|
||||
# follow from): they fly to the guest.
|
||||
for _ in range(3):
|
||||
guest('command', command=f'summon minecraft:experience_orb {x + 4:.2f} {y + 0.5:.2f} {z:.2f} {{Value:7s}}')
|
||||
guest.wait(2)
|
||||
seen = remote(guest).get('entities', {}).get('minecraft:experience_orb', 0)
|
||||
guest.shot(out, 'xp-orbs')
|
||||
guest.wait(60)
|
||||
xp = guest('state')['player']['xp']
|
||||
host_xp = host('state')['player']['xp']
|
||||
left = remote(guest).get('entities', {}).get('minecraft:experience_orb', 0)
|
||||
detail = {'seen': seen, 'guest': xp, 'host': host_xp, 'left': left}
|
||||
# ExperienceOrb.scanForMerges: orbs of one value side by side can merge into one.
|
||||
assert 1 <= seen <= 3, f'the guest saw {seen} orbs: {detail}'
|
||||
assert xp['total'] - total == 21 and xp['level'] == 2, f'the guest\'s experience after three 7-point orbs: {detail}'
|
||||
assert host_xp['total'] == host_total, f'the host took the orbs: {detail}'
|
||||
assert left == 0, f'orbs left on the guest\'s screen: {detail}'
|
||||
return {'seen': seen, 'guest': xp, 'host': host_xp}
|
||||
|
||||
|
||||
def check_time(host, guest, out):
|
||||
def times():
|
||||
return host('state')['time']['day_time'], guest('state')['time']['day_time']
|
||||
host('command', command='time set 1000')
|
||||
host('command', command='time pause')
|
||||
host.wait(60)
|
||||
paused = times()
|
||||
host('command', command='time resume')
|
||||
guest.wait(20)
|
||||
# A stalled game runs at most 10 missed ticks when it wakes (DeltaTracker); the server's
|
||||
# game time, sent every second, moves the guest's clock on (ClientClockManager.tick).
|
||||
os.kill(guest.pid, signal.SIGSTOP)
|
||||
time.sleep(4)
|
||||
os.kill(guest.pid, signal.SIGCONT)
|
||||
guest.wait(60)
|
||||
stalled = times()
|
||||
detail = {'paused': paused, 'after_stall': stalled}
|
||||
assert paused[0] == paused[1] and 1000 <= paused[0] < 1010, f'the clock while paused: {detail}'
|
||||
# The two reads are a tick or two apart.
|
||||
assert abs(stalled[0] - stalled[1]) <= 3, f'the guest\'s clock after its game stalled: {detail}'
|
||||
return detail
|
||||
|
||||
|
||||
def objects_near(game, centre, key='objects'):
|
||||
"""`status`'s objects within 8 blocks of centre, without their ids (each side numbers its own)."""
|
||||
out = []
|
||||
for o in game('status')[key]:
|
||||
if all(abs(o['position'][i] - centre[i]) <= 8 for i in (0, 2)):
|
||||
o = dict(o)
|
||||
o.pop('id')
|
||||
o['position'] = [round(v, 2) for v in o['position']]
|
||||
if 'yaw' in o: # as the packets carry it, in 256ths of a turn
|
||||
o['yaw'] = round(o['yaw'] * 256 / 360) % 256
|
||||
out.append(o)
|
||||
return sorted(out, key=json.dumps)
|
||||
|
||||
|
||||
def check_objects(host, guest, out):
|
||||
x, y, z = (int(v // 1) for v in pos_of(host))
|
||||
commands = [
|
||||
f'fill {x - 6} {y} {z - 6} {x + 6} {y + 3} {z - 6} minecraft:stone',
|
||||
f'summon minecraft:minecart {x - 4.5} {y} {z + 3.5}',
|
||||
f'summon minecraft:chest_minecart {x - 2.5} {y} {z + 3.5}',
|
||||
f'summon minecraft:furnace_minecart {x + 1.5} {y} {z + 3.5}',
|
||||
f'summon minecraft:tnt_minecart {x + 4.5} {y} {z + 3.5}',
|
||||
f'summon minecraft:oak_boat {x - 4.5} {y} {z + 6.5} {{Rotation:[45f,0f]}}',
|
||||
f'summon minecraft:birch_chest_boat {x - 1.5} {y} {z + 6.5}',
|
||||
f'summon minecraft:bamboo_raft {x + 2.5} {y} {z + 6.5}',
|
||||
f'summon minecraft:armor_stand {x - 2.5} {y} {z - 2.5} {{Rotation:[90f,0f]}}',
|
||||
f'summon minecraft:armor_stand {x - 4.5} {y} {z - 2.5} {{ShowArms:1b,Small:1b,NoBasePlate:1b,'
|
||||
'equipment:{head:{id:"minecraft:diamond_helmet",count:1}}}',
|
||||
f'summon minecraft:item_frame {x - 3.5} {y + 1} {z - 4.97} {{block_pos:[I;{x - 4},{y + 1},{z - 5}],Facing:3b,'
|
||||
'Item:{id:"minecraft:diamond",count:1},ItemRotation:3b}',
|
||||
f'summon minecraft:glow_item_frame {x - 1.5} {y + 1} {z - 4.97} {{block_pos:[I;{x - 2},{y + 1},{z - 5}],Facing:3b}}',
|
||||
f'summon minecraft:painting {x + 1.5} {y + 1} {z - 4.97} {{block_pos:[I;{x + 1},{y + 1},{z - 5}],facing:0b,'
|
||||
'variant:"minecraft:kebab"}',
|
||||
f'summon minecraft:painting {x + 4} {y + 1} {z - 4.97} {{block_pos:[I;{x + 4},{y + 1},{z - 5}],facing:0b,'
|
||||
'variant:"minecraft:courbet"}',
|
||||
]
|
||||
try:
|
||||
for command in commands:
|
||||
host('command', command=command)
|
||||
host.wait(60)
|
||||
guest.raw('look-at', x, y, z - 5)
|
||||
guest.wait(10)
|
||||
guest.shot(out, 'objects')
|
||||
host.shot(out, 'objects')
|
||||
mine, theirs = objects_near(host, (x, y, z)), objects_near(guest, (x, y, z))
|
||||
finally:
|
||||
host('command', command=f'kill @e[type=!minecraft:player,x={x - 8},y={y - 2},z={z - 8},dx=16,dy=8,dz=16]')
|
||||
host('command', command=f'fill {x - 6} {y} {z - 6} {x + 6} {y + 3} {z - 6} minecraft:air')
|
||||
assert len(mine) == len(commands) - 1, f'the host has {len(mine)} objects: {mine}'
|
||||
assert theirs == mine, f'the guest sees {theirs}\nthe host has {mine}'
|
||||
return f'{len(theirs)} objects identical'
|
||||
|
||||
|
||||
def check_projectiles(host, guest, out):
|
||||
x, y, z = (int(v // 1) for v in pos_of(host))
|
||||
commands = [
|
||||
f'summon minecraft:tnt {x + 4.5} {y} {z + 4.5} {{fuse:2000s}}',
|
||||
f'summon minecraft:end_crystal {x - 4.5} {y} {z + 4.5} {{ShowBottom:0b}}',
|
||||
f'summon minecraft:tnt {x + 2.5} {y + 5} {z - 3.5} {{fuse:2000s}}',
|
||||
f'summon minecraft:arrow {x - 2.5} {y + 4} {z - 2.5} {{Motion:[0.2d,0d,0d]}}',
|
||||
f'summon minecraft:falling_block {x - 0.5} {y + 6} {z - 4.5} {{BlockState:{{Name:"minecraft:sand"}}}}',
|
||||
]
|
||||
try:
|
||||
for command in commands:
|
||||
host('command', command=command)
|
||||
host.wait(80)
|
||||
guest.raw('look-at', x, y, z)
|
||||
guest.wait(5)
|
||||
guest.shot(out, 'projectiles')
|
||||
mine = objects_near(host, (x, y, z), 'projectiles')
|
||||
theirs = objects_near(guest, (x, y, z), 'projectiles')
|
||||
finally:
|
||||
host('command', command=f'kill @e[type=!minecraft:player,x={x - 8},y={y - 2},z={z - 8},dx=16,dy=10,dz=16]')
|
||||
host('command', command=f'setblock {x - 1} {y} {z - 5} minecraft:air')
|
||||
assert len(mine) == len(commands) - 1, f'the host has {len(mine)}: {mine}'
|
||||
# The fuse counts down every tick: the guest's, read a moment later, may be a tick or two behind.
|
||||
fuses = [(m.pop('fuse', 0), t.pop('fuse', 0)) for m, t in zip(mine, theirs)]
|
||||
assert theirs == mine, f'the guest sees {theirs}\nthe host has {mine}'
|
||||
assert all(abs(a - b) <= 2 for a, b in fuses), f'fuses (host, guest): {fuses}'
|
||||
return f'{len(theirs)} identical, fuses (host, guest) {fuses}'
|
||||
|
||||
|
||||
def light_differences(host, guest, lo, hi):
|
||||
"""Positions of the box loaded on both sides, and those whose sky or block light differ."""
|
||||
h, g = host.raw('light', *lo, *hi), guest.raw('light', *lo, *hi)
|
||||
both = [i for i in range(len(h['sky'])) if h['sky'][i] != '.' and g['sky'][i] != '.']
|
||||
differ = [i for i in both if (h['sky'][i], h['block'][i]) != (g['sky'][i], g['block'][i])]
|
||||
return h, g, both, differ
|
||||
|
||||
|
||||
def same_light(host, guest, lo, hi, what, ticks=100):
|
||||
"""Wait until the guest's light over the box is the host's; the number of positions compared."""
|
||||
for _ in range(ticks // 10):
|
||||
h, g, both, differ = light_differences(host, guest, lo, hi)
|
||||
if not differ:
|
||||
assert both, f'{what}: no position of the box is loaded on both sides'
|
||||
return len(both)
|
||||
host.wait(10)
|
||||
i = differ[0]
|
||||
nx, nz = hi[0] - lo[0] + 1, hi[2] - lo[2] + 1
|
||||
pos = (lo[0] + i % nx, lo[1] + i // (nx * nz), lo[2] + i // nx % nz)
|
||||
raise AssertionError(f'{what}: {len(differ)} of {len(both)} positions differ, first {pos}: host sky '
|
||||
f'{h["sky"][i]} block {h["block"][i]}, guest sky {g["sky"][i]} block {g["block"][i]}')
|
||||
|
||||
|
||||
def check_growth(host, guest, out):
|
||||
"""Block ticks near a guest 1000 blocks from the host: only the guest's tickets tick them."""
|
||||
x0, y0, z0 = pos_of(guest)
|
||||
guest('command', command='gamemode creative')
|
||||
guest('command', command=f'tp @s {x0 + 1000:.2f} 200 {z0:.2f}')
|
||||
guest.wait(100)
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
# A platform in the air over wherever the guest landed: a water source two blocks east of the
|
||||
# guest, wheat on farmland two blocks west. Vanilla's water spreads only towards the nearest
|
||||
# drop (FlowingFluid.getSpread), so any of the source's four neighbours may take it. Wheat
|
||||
# grows only in daylight (raw brightness 9 or more).
|
||||
top = max(y + 12, 120)
|
||||
water = (x + 2, top + 1, z)
|
||||
beside = [(water[0] + dx, water[1], water[2] + dz) for dx, dz in ((1, 0), (-1, 0), (0, 1), (0, -1))]
|
||||
wheat = (x - 2, top + 1, z)
|
||||
flowed = []
|
||||
try:
|
||||
host('command', command='time set noon')
|
||||
guest('command', command=f'fill {x - 4} {top} {z - 2} {x + 4} {top} {z + 2} minecraft:stone')
|
||||
guest('command', command=f'setblock {wheat[0]} {top} {wheat[2]} minecraft:farmland[moisture=7]')
|
||||
guest('command', command=f'setblock {wheat[0]} {wheat[1]} {wheat[2]} minecraft:wheat[age=0]')
|
||||
guest('command', command='gamerule random_tick_speed 1000')
|
||||
guest('command', command=f'setblock {water[0]} {water[1]} {water[2]} minecraft:water')
|
||||
for _ in range(40):
|
||||
guest.wait(10)
|
||||
flowed = [p for p in beside if guest.raw('block', *p).get('block') == 'minecraft:water']
|
||||
if flowed:
|
||||
break
|
||||
age = wait_state(guest, wheat, 'age', '7', 2400)
|
||||
guest.shot(out, 'growth')
|
||||
finally:
|
||||
guest('command', command='gamerule random_tick_speed 3')
|
||||
host('command', command='time set day')
|
||||
guest('command', command=f'tp @s {x0:.2f} {y0:.2f} {z0:.2f}')
|
||||
guest('command', command='gamemode survival')
|
||||
guest.wait(40)
|
||||
detail = {'flowed': flowed, 'wheat age': age}
|
||||
assert flowed, f'the water beside the guest did not flow: {detail}'
|
||||
assert age == '7', f'the wheat beside the guest did not grow: {detail}'
|
||||
return detail
|
||||
|
||||
|
||||
def check_light(host, guest, out):
|
||||
gx, gy, gz = (int(v // 1) for v in pos_of(guest))
|
||||
results = {}
|
||||
# A torch near the guest: the guest lights it itself, as vanilla's client does.
|
||||
torch = (gx + 3, gy, gz + 3)
|
||||
host('command', command=f'setblock {torch[0]} {torch[1]} {torch[2]} minecraft:torch')
|
||||
try:
|
||||
results['torch'] = same_light(host, guest, (gx - 12, gy - 1, gz - 12), (gx + 16, gy + 3, gz + 16), 'torch')
|
||||
finally:
|
||||
host('command', command=f'setblock {torch[0]} {torch[1]} {torch[2]} minecraft:air')
|
||||
# A roof over the guest, then a hole in it: sky light falls through.
|
||||
roof = f'{gx - 3} {gy + 4} {gz - 3} {gx + 3} {gy + 4} {gz + 3}'
|
||||
box = (gx - 6, gy - 1, gz - 6), (gx + 6, gy + 5, gz + 6)
|
||||
host('command', command=f'fill {roof} minecraft:stone')
|
||||
try:
|
||||
results['roof'] = same_light(host, guest, *box, 'roof')
|
||||
host('command', command=f'setblock {gx} {gy + 4} {gz} minecraft:air')
|
||||
results['hole'] = same_light(host, guest, *box, 'hole in the roof')
|
||||
finally:
|
||||
host('command', command=f'fill {roof} minecraft:air')
|
||||
# The last chunk the guest tracks eastwards, and glowstone high up just past it in a chunk it
|
||||
# doesn't track: the guest never sees that block, only the light updates of its border chunk.
|
||||
y = 200
|
||||
row = guest.raw('light', gx, y, gz, gx + 16 * 24, y, gz)['sky']
|
||||
assert '.' in row, 'the guest has every chunk 24 chunks east'
|
||||
untracked = (gx + row.index('.')) >> 4
|
||||
near = untracked * 16 + 1
|
||||
# On its server thread the host's own game is a client too, sent the same light updates.
|
||||
if not SERVER_THREAD:
|
||||
assert host.raw('light', near, y, gz, near, y, gz)['sky'] != '.', 'the host lacks the chunk past the guest'
|
||||
host('command', command=f'setblock {near} {y} {gz} minecraft:glowstone')
|
||||
try:
|
||||
lo, hi = (untracked * 16 - 16, y - 3, gz - 8), (untracked * 16 - 1, y + 3, gz + 8)
|
||||
# On the server thread the host's game is a client too, as dark as the guest until the light
|
||||
# update arrives: wait for it before comparing them.
|
||||
for _ in range(10):
|
||||
lit = guest.raw('light', near - 2, y, gz, near - 2, y, gz)['block']
|
||||
if lit == 'd':
|
||||
break
|
||||
host.wait(10)
|
||||
assert lit == 'd', f'the border chunk by the glowstone has block light {lit}, not 13, after 100 ticks'
|
||||
results['border'] = same_light(host, guest, lo, hi, 'border chunk')
|
||||
finally:
|
||||
host('command', command=f'setblock {near} {y} {gz} minecraft:air')
|
||||
results['border_cleared'] = same_light(host, guest, lo, hi, 'border chunk without the glowstone')
|
||||
return results
|
||||
|
||||
|
||||
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
|
||||
'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage,
|
||||
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp,
|
||||
'containers': check_containers, 'feedback': check_feedback, 'commands': check_commands,
|
||||
'recipes': check_recipes,
|
||||
'trials': check_trials,
|
||||
'walls': check_walls, 'effects': check_effects, 'portals': check_portals}
|
||||
'respawn': check_respawn,
|
||||
'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat,
|
||||
'machines': check_machines,
|
||||
'brewing': check_brewing,
|
||||
'hurt': check_hurt,
|
||||
'commands': check_commands,
|
||||
'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls,
|
||||
'effects': check_effects, 'portals': check_portals, 'distance': check_distance, 'clicks': check_clicks,
|
||||
'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'eating': check_eating,
|
||||
'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles,
|
||||
'light': check_light, 'plates': check_plates,
|
||||
'swings': check_swings,
|
||||
'time': check_time, 'growth': check_growth}
|
||||
|
||||
|
||||
def run(ctl, out, resources, checks):
|
||||
@@ -853,7 +1658,7 @@ def run(ctl, out, resources, checks):
|
||||
host('command', command='gamerule spawn_mobs false')
|
||||
port = host.raw('lan', 'open', 0, 'commands')['port']
|
||||
host.player = host.raw('lan', 'status').get('host', 'Player') # the host's profile name
|
||||
guest('launch', wait=False, offscreen=sys.platform == 'darwin')
|
||||
guest.pid = guest('launch', wait=False, offscreen=sys.platform == 'darwin')['pid']
|
||||
guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME)
|
||||
guest.raw('wait-for', 'loaded', '--timeout', 300)
|
||||
guest.wait(40)
|
||||
|
||||
+26
-25
@@ -36,8 +36,9 @@ import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -61,14 +62,14 @@ SHIM = STATE_DIR / "shim"
|
||||
# so a harness whose inputs match one that passed elsewhere doesn't run again.
|
||||
SHARED = Path(os.environ.get("PARITY_SHARED") or (LOCAL / "minecraft").resolve().parent / "parity-shared")
|
||||
MACHINE_JOBS = int(os.environ.get("PARITY_MACHINE_JOBS") or max(1, (os.cpu_count() or 4) // 2))
|
||||
HOST = os.uname().nodename.split(".")[0]
|
||||
HOST = socket.gethostname().split(".")[0]
|
||||
DEFAULT_MEMORY = 3 << 30 # assumed peak for a harness that never ran here
|
||||
|
||||
|
||||
def harness_settings(path):
|
||||
"""PARITY_SHARDS and PARITY_RUST_SCOPE, read from a harness's source without running it."""
|
||||
import ast
|
||||
text = Path(path).read_text()
|
||||
text = Path(path).read_text(encoding="utf-8")
|
||||
settings = {}
|
||||
if "PARITY_" in text:
|
||||
for node in ast.parse(text).body:
|
||||
@@ -102,7 +103,7 @@ def base_name(name):
|
||||
|
||||
|
||||
def load_state():
|
||||
return json.loads(STATE.read_text()) if STATE.exists() else {"harnesses": {}, "hashes": {}}
|
||||
return json.loads(STATE.read_text(encoding="utf-8")) if STATE.exists() else {"harnesses": {}, "hashes": {}}
|
||||
|
||||
|
||||
def save_state(state):
|
||||
@@ -129,7 +130,7 @@ class Hasher:
|
||||
if cached and cached[0] == stamp:
|
||||
return cached[1]
|
||||
if keep:
|
||||
digest = hashlib.sha256(crate_root_without_modules(Path(real).read_text(), set(keep.split(","))).encode()).hexdigest()
|
||||
digest = hashlib.sha256(crate_root_without_modules(Path(real).read_text(encoding="utf-8"), set(keep.split(","))).encode()).hexdigest()
|
||||
else:
|
||||
with open(real, "rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
@@ -168,7 +169,7 @@ def environment_key(hasher):
|
||||
return (result.stdout + result.stderr).strip()
|
||||
except FileNotFoundError:
|
||||
return "missing"
|
||||
lock = json.loads((ROOT / "research-lock.json").read_text())
|
||||
lock = json.loads((ROOT / "research-lock.json").read_text(encoding="utf-8"))
|
||||
version_dir = LOCAL / "minecraft" / lock["minecraft"]["version"]
|
||||
parts = [version(["rustc", "-V"]), version(["java", "-version"]), version(["javac", "-version"]),
|
||||
json.dumps(PROFILE, sort_keys=True), hasher(ROOT / "research-lock.json"), hasher(ROOT / "Cargo.lock"),
|
||||
@@ -197,7 +198,7 @@ def dep_info(binary):
|
||||
if not info.exists():
|
||||
return []
|
||||
sources = []
|
||||
for line in info.read_text().splitlines():
|
||||
for line in info.read_text(encoding="utf-8").splitlines():
|
||||
_, separator, rest = line.partition(": ")
|
||||
if separator:
|
||||
sources += [part.replace("\\ ", " ") for part in re.split(r"(?<!\\) ", rest.strip()) if part]
|
||||
@@ -371,17 +372,17 @@ def narrow_rust_sources(sources, scope):
|
||||
for candidate in (crate_dir / "src" / Path(*parts[:count - 1]) / f"{parts[count - 1]}.rs",
|
||||
crate_dir / "src" / Path(*parts[:count]) / "mod.rs"):
|
||||
if candidate.is_file():
|
||||
return str(candidate.relative_to(ROOT)), count
|
||||
return candidate.relative_to(ROOT).as_posix(), count
|
||||
return None, 0
|
||||
|
||||
def module_path(path):
|
||||
parts = list(Path(*Path(path).parts[3:]).with_suffix("").parts) # crates/<crate>/src/...
|
||||
parts = list(PurePosixPath(path).parts[3:-1] + (PurePosixPath(path).with_suffix("").name,))
|
||||
return parts[:-1] if parts[-1] in ("mod", "lib") else parts
|
||||
|
||||
defined_types, used_macros, kept_modules = set(), set(), {}
|
||||
for path in inner + entry:
|
||||
text = rust_code((ROOT / path).read_text(errors="replace"))
|
||||
crate_name = Path(path).parts[1].replace("-", "_")
|
||||
text = rust_code((ROOT / path).read_text(encoding="utf-8", errors="replace"))
|
||||
crate_name = PurePosixPath(path).parts[1].replace("-", "_")
|
||||
nesting = inline_modules(text)
|
||||
if re.search(r"\binclude!\s*\(", text):
|
||||
return sources, f"{path} includes source"
|
||||
@@ -401,7 +402,7 @@ def narrow_rust_sources(sources, scope):
|
||||
if head in crates: # a workspace crate
|
||||
base, crate_name = [], head
|
||||
elif head.startswith(("crate", "self", "super")) and path in inner:
|
||||
own, crate_name = module_path(path) + nesting(match.start()), Path(path).parts[1].replace("-", "_")
|
||||
own, crate_name = module_path(path) + nesting(match.start()), PurePosixPath(path).parts[1].replace("-", "_")
|
||||
ups = head.count("super")
|
||||
if head != "crate" and ups <= len(nesting(match.start())):
|
||||
continue # within this file
|
||||
@@ -415,14 +416,14 @@ def narrow_rust_sources(sources, scope):
|
||||
item = (base + parts)[0]
|
||||
defined_in_root = root.is_file() and re.search(
|
||||
rf"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const|static|fn|struct|enum|type|trait|union)\s+{item}\b",
|
||||
root.read_text(), re.MULTILINE)
|
||||
root.read_text(encoding="utf-8"), re.MULTILINE)
|
||||
if not defined_in_root:
|
||||
return sources, f"{path} names {head}::{rest}, which the crate root doesn't define itself"
|
||||
continue
|
||||
if not scoped(target):
|
||||
return sources, f"{path} names {head}::{rest} ({target})"
|
||||
for path in outside:
|
||||
text = rust_code((ROOT / path).read_text(errors="replace"))
|
||||
text = rust_code((ROOT / path).read_text(encoding="utf-8", errors="replace"))
|
||||
defined = set(RUST_MACRO_DEFINITION.findall(text)) & used_macros
|
||||
if defined:
|
||||
return sources, f"the scope uses macro {sorted(defined)[0]}! defined in {path}"
|
||||
@@ -433,7 +434,7 @@ def narrow_rust_sources(sources, scope):
|
||||
kept = [path for path in sources if path not in outside and not path.endswith("/src/lib.rs")]
|
||||
for path in sources:
|
||||
if path.endswith("/src/lib.rs"):
|
||||
modules = kept_modules.get(Path(path).parts[1].replace("-", "_")) or {"-"} # "-": no module of it is reachable
|
||||
modules = kept_modules.get(PurePosixPath(path).parts[1].replace("-", "_")) or {"-"} # "-": no module of it is reachable
|
||||
kept.append(f"{path}{KEEP}{','.join(sorted(modules))}")
|
||||
return sorted(kept), None
|
||||
|
||||
@@ -549,7 +550,7 @@ def clear_large_outputs(name, trace):
|
||||
everything else large under the harness's .local directories is rebuilt on
|
||||
its next run."""
|
||||
local = LOCAL.resolve()
|
||||
keep = {os.path.realpath(line) for line in outputs_listing(name).read_text().splitlines() if line}
|
||||
keep = {os.path.realpath(line) for line in outputs_listing(name).read_text(encoding="utf-8").splitlines() if line}
|
||||
directories = set()
|
||||
for command in trace["commands"]:
|
||||
for argument in command[1:]:
|
||||
@@ -600,7 +601,7 @@ def memory_available():
|
||||
"""Bytes the system can give harnesses now: MemAvailable on Linux, free and reclaimable pages on macOS."""
|
||||
meminfo = Path("/proc/meminfo")
|
||||
if meminfo.exists():
|
||||
for line in meminfo.read_text().splitlines():
|
||||
for line in meminfo.read_text(encoding="utf-8").splitlines():
|
||||
if line.startswith("MemAvailable:"):
|
||||
return int(line.split()[1]) * 1024
|
||||
try:
|
||||
@@ -634,7 +635,7 @@ def outcome(name, script, passed, elapsed, trace_path, hasher=None):
|
||||
record = {"status": "pass" if passed else "fail", "seconds": round(elapsed, 1),
|
||||
"finished": time.strftime("%Y-%m-%dT%H:%M:%S"), "host": HOST}
|
||||
try:
|
||||
trace = json.loads(Path(trace_path).read_text())
|
||||
trace = json.loads(Path(trace_path).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
trace = None # killed before writing it, or the disk was full: the pass can't be keyed
|
||||
if trace:
|
||||
@@ -726,7 +727,7 @@ class LocalExecutor:
|
||||
def host_config():
|
||||
"""tools/parity_hosts.json: the machines harnesses can run on, and the harnesses that must stay local."""
|
||||
path = ROOT / "tools" / "parity_hosts.json"
|
||||
return json.loads(path.read_text()) if path.exists() else {"default": [], "hosts": {}, "local_only": {}}
|
||||
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"default": [], "hosts": {}, "local_only": {}}
|
||||
|
||||
|
||||
class RemoteExecutor:
|
||||
@@ -1017,11 +1018,11 @@ def stale(name, state, hasher, environment):
|
||||
candidates = [record] if record and record.get("dependencies") else []
|
||||
template = SHARED / "dependencies" / f"{name}.json"
|
||||
if template.exists():
|
||||
candidates.append(json.loads(template.read_text()))
|
||||
candidates.append(json.loads(template.read_text(encoding="utf-8")))
|
||||
for candidate in candidates:
|
||||
shared = SHARED / "passes" / name / f"{key(candidate, hasher, environment)}.json"
|
||||
if shared.exists():
|
||||
state["harnesses"][name] = dict(json.loads(shared.read_text()), shared=True)
|
||||
state["harnesses"][name] = dict(json.loads(shared.read_text(encoding="utf-8")), shared=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -1088,7 +1089,7 @@ def changed_harnesses(found, records, ref):
|
||||
for name, script in found.items():
|
||||
specific = [path for path in records.get(name, {}).get("dependencies", [])
|
||||
if path.startswith("mods/horizon/src/test/") or "/examples/" in path or "/src/bin/" in path]
|
||||
if str(Path(script).relative_to(ROOT)) in changed or any(path in changed for path in specific):
|
||||
if Path(script).relative_to(ROOT).as_posix() in changed or any(path in changed for path in specific):
|
||||
found_changed.add(name)
|
||||
return found_changed
|
||||
|
||||
@@ -1103,8 +1104,8 @@ def affected_harnesses(found, records, changed):
|
||||
dependencies = records.get(name, {}).get("dependencies")
|
||||
template = SHARED / "dependencies" / f"{name}.json"
|
||||
if dependencies is None and template.exists():
|
||||
dependencies = json.loads(template.read_text()).get("dependencies")
|
||||
if dependencies is None or str(Path(script).relative_to(ROOT)) in changed or \
|
||||
dependencies = json.loads(template.read_text(encoding="utf-8")).get("dependencies")
|
||||
if dependencies is None or Path(script).relative_to(ROOT).as_posix() in changed or \
|
||||
any(path.split(KEEP)[0] in changed for path in dependencies):
|
||||
affected.add(name)
|
||||
return affected
|
||||
@@ -1180,7 +1181,7 @@ def main():
|
||||
chosen = [name for name in found if records.get(name, {}).get("status") == "fail"]
|
||||
elif args.changed or args.changed_files:
|
||||
if args.changed_files:
|
||||
changed, since = set(Path(args.changed_files).read_text().split("\n")) - {""}, ""
|
||||
changed, since = set(Path(args.changed_files).read_text(encoding="utf-8").split("\n")) - {""}, ""
|
||||
else:
|
||||
changed, since = changed_files(args.changed), f" since the merge base with {args.changed}"
|
||||
if changed is None:
|
||||
|
||||
@@ -364,6 +364,20 @@ def run_horizon(args, distance):
|
||||
for carry in dev_mods(args):
|
||||
command += ["--dev-mod", str(carry)]
|
||||
env = dict(os.environ, HORIZON_NO_AUDIO="1")
|
||||
if args.warm:
|
||||
# A first start to the title screen builds what later starts reuse (the content-mod
|
||||
# root, the block behaviour snapshot). It is not measured: players see it once.
|
||||
with (WORK / f"horizon-rd{distance}-warm.log").open("w") as log:
|
||||
proc = subprocess.Popen(command, cwd=game_dir, env=env, stdout=log, stderr=subprocess.STDOUT)
|
||||
try:
|
||||
poll(Control(sock), lambda s: s.get("screen") == "title", 600)
|
||||
try:
|
||||
Control(sock)("quit", timeout=60)
|
||||
except (OSError, ValueError, RuntimeError):
|
||||
pass
|
||||
finally:
|
||||
stop(proc)
|
||||
sock.unlink(missing_ok=True)
|
||||
log = (WORK / f"horizon-rd{distance}.log").open("w")
|
||||
started = time.time()
|
||||
proc = subprocess.Popen(command, cwd=game_dir, env=env, stdout=log, stderr=subprocess.STDOUT)
|
||||
@@ -774,6 +788,8 @@ def main():
|
||||
p.add_argument("--build", default=str(ROOT / "target/release"))
|
||||
p.add_argument("--repeats", type=int, default=3, help="games per render distance; the report gives means and 95%% CIs")
|
||||
p.add_argument("--port-work", help="horizon: also load the mods carried over in this horizon-port-pack work folder")
|
||||
p.add_argument("--warm", action="store_true",
|
||||
help="horizon: measure a later start, after one start to the title screen built the caches")
|
||||
p.add_argument("--mod-jars", help="neoforge: the mod jars to load (the user's own; never committed)")
|
||||
p.add_argument("--deps", help="neoforge: their required libraries")
|
||||
p.add_argument("--table", nargs="+", metavar="LABEL", help="print markdown tables of saved runs, and exit")
|
||||
|
||||
+63
-1
@@ -29,6 +29,10 @@ import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
if os.name == "nt":
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
FLEET_SHARED = Path.home() / "code" / "horizon-parity" / "shared-local" / "parity-shared"
|
||||
@@ -184,7 +188,7 @@ def line_counts(base, changed):
|
||||
for path in git("ls-files", "--others", "--exclude-standard").splitlines():
|
||||
if path in changed:
|
||||
try:
|
||||
counts[path] = (len((ROOT / path).read_text().splitlines()), 0)
|
||||
counts[path] = (len((ROOT / path).read_text(encoding="utf-8").splitlines()), 0)
|
||||
except (UnicodeDecodeError, OSError):
|
||||
pass
|
||||
return counts
|
||||
@@ -303,6 +307,9 @@ def run_script(steps, host, verbose):
|
||||
"""Runs the steps in one shell on host (here for "local"), each between markers, reading results as they come."""
|
||||
if not steps:
|
||||
return
|
||||
if host == "local" and os.name == "nt":
|
||||
run_windows(steps, verbose)
|
||||
return
|
||||
parts = [HOST_SETUP.get(host, ""), "set +e"]
|
||||
for index, step in enumerate(steps):
|
||||
parts.append(f"echo '@@pr_ready:begin:{index}'; started=$(date +%s)\n( {step.command}\n) 2>&1 < /dev/null\n"
|
||||
@@ -338,6 +345,61 @@ def run_script(steps, host, verbose):
|
||||
finish(step, verbose)
|
||||
|
||||
|
||||
def run_windows(steps, verbose):
|
||||
"""Run local checks directly on Windows without requiring a Unix shell."""
|
||||
for step in steps:
|
||||
command = shlex.split(step.command)
|
||||
cwd = ROOT
|
||||
env = os.environ.copy()
|
||||
env["PYTHONUTF8"] = "1"
|
||||
if step.name == "Public tree":
|
||||
command = [sys.executable, "tools/check_public_tree.py"]
|
||||
elif step.name == "Python tests":
|
||||
command = [sys.executable, "-m", "unittest", "discover", "-s", "tests"]
|
||||
elif step.name == "rustfmt":
|
||||
command = ["cargo", "fmt", "--all", "--", "--check"]
|
||||
elif step.name == "clippy":
|
||||
command = ["cargo", "clippy", "--workspace", "--all-targets", "--locked", "--", "-D", "warnings"]
|
||||
elif step.name.startswith("tests"):
|
||||
command = shlex.split(step.command)
|
||||
elif step.name == "tokens.css up to date":
|
||||
command = shlex.split(step.command)
|
||||
elif step.name == "launcher rustfmt":
|
||||
command = ["cargo", "fmt", "--check"]
|
||||
cwd = ROOT / "launcher"
|
||||
elif step.name == "launcher clippy":
|
||||
command = ["cargo", "clippy", "--all-targets", "--locked", "--", "-D", "warnings"]
|
||||
cwd = ROOT / "launcher"
|
||||
elif step.name == "launcher tests":
|
||||
command = ["cargo", "test", "--locked", "--lib"]
|
||||
cwd = ROOT / "launcher"
|
||||
elif step.name == "Parity":
|
||||
command = shlex.split(step.command)
|
||||
if command and command[0] == "PARITY_HOSTS=":
|
||||
command.pop(0)
|
||||
if command and command[0] == "python3":
|
||||
command[0] = sys.executable
|
||||
env["PARITY_HOSTS"] = ""
|
||||
elif command and command[0] == "python3":
|
||||
command[0] = sys.executable
|
||||
|
||||
print(f" {step.name}...", file=sys.stderr, flush=True)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
with subprocess.Popen(command, cwd=cwd, env=env, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, text=True, errors="replace") as process:
|
||||
for line in process.stdout:
|
||||
step.output += line
|
||||
if verbose:
|
||||
print(" " + line, end="", file=sys.stderr)
|
||||
status = process.wait()
|
||||
step.status = "pass" if status == 0 else "fail"
|
||||
except OSError as error:
|
||||
step.status, step.detail = "fail", str(error)
|
||||
step.seconds = int(time.monotonic() - started)
|
||||
finish(step, verbose)
|
||||
|
||||
|
||||
def finish(step, verbose):
|
||||
if step.status == "pass" and step.summary:
|
||||
step.detail = step.summary(step.output)
|
||||
|
||||
+46
-2
@@ -19,7 +19,9 @@ The bots can run on another machine, so they don't take the server's CPU: `--bot
|
||||
`--bots-bin` naming horizon-bots there and `--connect` the address it reaches this machine at. `--nice 19`
|
||||
runs every server at the lowest priority (a shared machine). The explore bots fly as fast as each server
|
||||
sends them chunks, so a faster server gets more terrain to generate; `--explore-speed` slows them to a rate
|
||||
both servers keep up with, for equal work.
|
||||
both servers keep up with, for equal work. After the runs, the work table compares the servers at each bot
|
||||
count: chunks sent and new chunks generated a second, against the busiest server's. A run whose work is more
|
||||
than 10 % apart isn't a fair comparison of its tick times.
|
||||
|
||||
The vanilla side runs the pinned server jar from tools/lab.py prepare (your own copy). It needs Java 25. The
|
||||
Horizon side runs target/release/horizon-server with the engine beside it; build both first:
|
||||
@@ -306,6 +308,38 @@ def run_once(kind, bots, behaviour, args, out):
|
||||
return result
|
||||
|
||||
|
||||
# How far apart two servers' chunks a second (sent, and new) may be and still count as the same work: 10 %,
|
||||
# or a chunk a second when there are few.
|
||||
EQUAL_WORK = 0.10
|
||||
|
||||
|
||||
def work(runs):
|
||||
"""Each pass and bot count that ran on more than one server: every server's chunks sent and new chunks a
|
||||
second as a share of the busiest one's, the ticks a second its bots stood waiting for their own chunk,
|
||||
and whether the work was equal (within EQUAL_WORK on both)."""
|
||||
groups = {}
|
||||
for r in runs:
|
||||
if 'error' not in r:
|
||||
groups.setdefault((r['behaviour'], r['bots']), []).append(r)
|
||||
rows = []
|
||||
for (behaviour, bots), group in groups.items():
|
||||
if len(group) < 2:
|
||||
continue
|
||||
row = {'behaviour': behaviour, 'bots': bots, 'servers': {}, 'equal': True}
|
||||
for key in ('chunks_per_second', 'unique_per_second'):
|
||||
top = max(r.get(key) or 0 for r in group)
|
||||
for r in group:
|
||||
value = r.get(key) or 0
|
||||
share = round(value / top, 3) if top else 1.0
|
||||
row['servers'].setdefault(r['server'], {})[key] = {'value': value, 'share': share}
|
||||
if top - value > max(EQUAL_WORK * top, 1.0):
|
||||
row['equal'] = False
|
||||
for r in group:
|
||||
row['servers'][r['server']]['waited_ticks_per_second'] = r.get('waited_ticks_per_second')
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
|
||||
parser.add_argument('--servers', default='horizon,vanilla')
|
||||
@@ -346,6 +380,7 @@ def main():
|
||||
'java': subprocess.run(['java', '--version'], capture_output=True, text=True).stdout.splitlines()[:1],
|
||||
'settings': {**vars(args), 'out': str(args.out), 'properties': PROPERTIES},
|
||||
'runs': runs,
|
||||
'work': work(runs),
|
||||
}
|
||||
path = args.out or out / 'report.json'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -356,11 +391,20 @@ def main():
|
||||
if 'error' in r:
|
||||
print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} failed: {r["error"].splitlines()[0]}')
|
||||
continue
|
||||
per_bot = r['chunks_per_bot'].get(r['behaviour'])
|
||||
# A mixed pass: every bot's.
|
||||
per_bot = r['chunks_per_bot'].get(r['behaviour']) or round((r['chunks_total'] or 0) / r['bots'])
|
||||
print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} {r["start_seconds"]:>8} {r["mspt"]["average"]!s:>6} '
|
||||
f'{r["mspt"]["p95"]!s:>6} {r["mspt"]["p99"]!s:>6} {r["rss_mb"]["mean"]!s:>7} {r["cpu_percent"]!s:>6} '
|
||||
f'{r["chunks_per_second"]!s:>8} {per_bot!s:>6} {r["resent"]!s:>6} {r["pulled_back"]!s:>6} '
|
||||
f'{r["bots_joined"]!s:>6}')
|
||||
if report['work']:
|
||||
print(f'\nWork, against the busiest server (chunks a second sent, new; ticks a second bots waited):')
|
||||
for row in report['work']:
|
||||
cells = ' '.join(
|
||||
f'{server} {w["chunks_per_second"]["value"]} ({w["chunks_per_second"]["share"]:.0%}), '
|
||||
f'{w["unique_per_second"]["value"]} ({w["unique_per_second"]["share"]:.0%}), '
|
||||
f'{w["waited_ticks_per_second"]}' for server, w in row['servers'].items())
|
||||
print(f'{row["behaviour"]:8} {row["bots"]:>4} {"equal" if row["equal"] else "NOT EQUAL"} {cells}')
|
||||
print(f'\nWrote {path}')
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the order block entities tick in with vanilla's `Level.blockEntityTickers`.
|
||||
|
||||
Random scenarios load chunks with block entities in a save order (enough in
|
||||
one chunk to make its block entity map grow), place, replace and remove block
|
||||
entities, give jukeboxes a record and take it, and unload chunks, with ticks
|
||||
in between. `VanillaBlockEntityTickerOracle` runs them on real `LevelChunk`s
|
||||
of a server level and prints, after each tick, the positions of the live
|
||||
tickers in list order; `examples/block_entity_tickers_fixture` runs the same
|
||||
on `horizon_client::block_entities::BlockEntities`. The block entities are
|
||||
the kinds the game ticks in that list (hoppers, furnaces, beacons, spawners,
|
||||
trial spawners, vaults, hives, crafters, brewing stands, jukebox), with chests and barrels,
|
||||
which have no ticker, among them.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
|
||||
TICKING = ['hopper', 'furnace', 'blast_furnace', 'smoker', 'beacon', 'spawner', 'trial_spawner', 'vault',
|
||||
'beehive', 'bee_nest', 'crafter', 'brewing_stand', 'jukebox_record']
|
||||
KINDS = TICKING + ['jukebox', 'chest', 'barrel']
|
||||
|
||||
|
||||
def scenario(rng):
|
||||
"""One scenario's lines: a few chunks near the origin and the ops on them."""
|
||||
lines = ['reset']
|
||||
loaded, blocks = set(), {}
|
||||
|
||||
def free(cx, cz):
|
||||
while True:
|
||||
p = (cx * 16 + rng.randrange(16), rng.randrange(-64, 320), cz * 16 + rng.randrange(16))
|
||||
if p not in blocks:
|
||||
return p
|
||||
|
||||
def load():
|
||||
options = [(x, z) for x in range(-2, 3) for z in range(-2, 3) if (x, z) not in loaded]
|
||||
if not options:
|
||||
return
|
||||
cx, cz = rng.choice(options)
|
||||
loaded.add((cx, cz))
|
||||
words = ['load', str(cx), str(cz)]
|
||||
for _ in range(rng.choice([0, 1, 3, 8, 20, 30, 60])):
|
||||
p, kind = free(cx, cz), rng.choice(KINDS)
|
||||
blocks[p] = kind
|
||||
words += [kind, *map(str, p)]
|
||||
lines.append(' '.join(words))
|
||||
for _ in range(rng.randrange(1, 4)):
|
||||
load()
|
||||
lines.append('tick')
|
||||
for _ in range(rng.randrange(10, 60)):
|
||||
op = rng.random()
|
||||
mine = sorted(blocks)
|
||||
if op < 0.25 and loaded:
|
||||
cx, cz = rng.choice(sorted(loaded))
|
||||
p, kind = free(cx, cz), rng.choice(KINDS)
|
||||
blocks[p] = kind
|
||||
lines.append(f'place {kind} {p[0]} {p[1]} {p[2]}')
|
||||
elif op < 0.4 and mine:
|
||||
p = rng.choice(mine)
|
||||
lines.append(f'replace {p[0]} {p[1]} {p[2]}')
|
||||
elif op < 0.6 and mine:
|
||||
p = rng.choice(mine)
|
||||
del blocks[p]
|
||||
lines.append(f'remove {p[0]} {p[1]} {p[2]}')
|
||||
elif op < 0.72:
|
||||
jukeboxes = [p for p in mine if blocks[p].startswith('jukebox')]
|
||||
if jukeboxes:
|
||||
p = rng.choice(jukeboxes)
|
||||
record = blocks[p] == 'jukebox'
|
||||
blocks[p] = 'jukebox_record' if record else 'jukebox'
|
||||
lines.append(f'record {p[0]} {p[1]} {p[2]} {int(record)}')
|
||||
elif op < 0.78 and loaded:
|
||||
cx, cz = rng.choice(sorted(loaded))
|
||||
loaded.discard((cx, cz))
|
||||
for p in [p for p in blocks if (p[0] >> 4, p[2] >> 4) == (cx, cz)]:
|
||||
del blocks[p]
|
||||
lines.append(f'unload {cx} {cz}')
|
||||
elif op < 0.85:
|
||||
load()
|
||||
else:
|
||||
lines.append('tick')
|
||||
lines.append('tick')
|
||||
return lines
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--scenarios', type=int, default=3000)
|
||||
parser.add_argument('--seed', type=int, default=0x7469636b)
|
||||
args = parser.parse_args()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / 'rust-block-entity-tickers-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
rng = random.Random(args.seed)
|
||||
lines = [line for _ in range(args.scenarios) for line in scenario(rng)]
|
||||
inputs = build / 'inputs.txt'
|
||||
inputs.write_text('\n'.join(lines) + '\n')
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w') as log:
|
||||
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log,
|
||||
stderr=subprocess.STDOUT)
|
||||
if result.returncode:
|
||||
print((build / (name + '.log')).read_text()[-4000:])
|
||||
sys.exit(f'{name} failed')
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies,
|
||||
'-d', classes, *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaBlockEntityTickerOracle'))],
|
||||
'compile-java')
|
||||
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaBlockEntityTickerOracle', inputs, build / 'vanilla.txt'], 'vanilla')
|
||||
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example',
|
||||
'block_entity_tickers_fixture', '--', inputs, build / 'rust.txt'], 'rust')
|
||||
matched = base.compare(build / 'vanilla.txt', build / 'rust.txt')
|
||||
ticks = sum(1 for line in lines if line == 'tick')
|
||||
listed = sum(len(line.split()) - 1 for line in (build / 'vanilla.txt').read_text().splitlines())
|
||||
print(f'block entity tickers: {args.scenarios} scenarios, {matched} of {ticks} ticks match vanilla '
|
||||
f'({listed} tickers listed)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -5,8 +5,9 @@ A container, jukebox, lectern, campfire, decorated pot, chiseled bookshelf,
|
||||
shelf, shulker box or another block entity holder at the origin holds random
|
||||
contents; the case then replaces it with `Level.setBlock` (another block, the
|
||||
same block in another state, with or without UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS),
|
||||
destroys it with `Level.destroyBlock` (with or without drops) or removes it with
|
||||
`Level.removeBlock`. Vanilla runs over the headless level of the dispenser oracle
|
||||
destroys it with `Level.destroyBlock` (with or without drops), removes it with
|
||||
`Level.removeBlock`, or a survival player mines it (`ServerPlayerGameMode.destroyBlock`,
|
||||
holding a tool or nothing, #844). Vanilla runs over the headless level of the dispenser oracle
|
||||
(`VanillaDispenserOracle`, "remove" cases), which replays `LevelChunk.setBlockState`'s
|
||||
`BlockEntity.preRemoveSideEffects`; Horizon runs its game glue in a headless game
|
||||
(`HORIZON_DISPENSE_FIXTURE`). Both print the block changes, the contents left,
|
||||
@@ -63,6 +64,10 @@ LISTED = {'chest', 'trapped_chest', 'barrel', 'hopper', 'dispenser', 'dropper',
|
||||
REPLACEMENTS = ['air', 'stone', 'glass', 'water', 'oak_planks', 'barrel', 'chest', 'hopper', 'blue_shulker_box', 'dirt', 'tnt',
|
||||
'copper_chest', 'oxidized_copper_chest', 'lectern', 'jukebox']
|
||||
FLAGS = [3, 3, 3, 2, 18, 2 | 256, 816, 3 | 64, 1]
|
||||
# What a mining player holds: the right tool, a tool too weak or of another kind (swords and maces
|
||||
# wear 2 a block, shears any block but fire), or nothing.
|
||||
TOOLS = [plain('diamond_pickaxe'), plain('wooden_pickaxe'), plain('stone_axe'), plain('iron_shovel'), plain('iron_sword'),
|
||||
plain('shears'), plain('mace'), '-']
|
||||
|
||||
|
||||
def contents(rng, name, slots, pool):
|
||||
@@ -135,8 +140,12 @@ def cases(facts, count, seed, only):
|
||||
op = {'op': 'destroy', 'drop': True}
|
||||
elif roll < 0.85:
|
||||
op = {'op': 'destroy', 'drop': False}
|
||||
else:
|
||||
elif roll < 0.92:
|
||||
op = {'op': 'remove'}
|
||||
else:
|
||||
# ServerPlayerGameMode.destroyBlock: a survival player mines it (#844). The tool comes
|
||||
# from the roll, not another draw, so the cases after this one stay the same.
|
||||
op = {'op': 'mine', 'item': TOOLS[int(roll * 1000) % len(TOOLS)]}
|
||||
case = {**h.environment(rng), 'mode': 'remove', 'pos': [0, 0, 0], 'cells': cells, 'items': items, 'remove': op}
|
||||
case.pop('raining', None)
|
||||
case.pop('thundering', None)
|
||||
|
||||
@@ -268,6 +268,12 @@ def run_side(label, command, directory, client):
|
||||
# it stays put; experience keeps its profession).
|
||||
server.console('summon minecraft:villager ~1 ~ ~ {NoAI:1b,Xp:1,VillagerData:'
|
||||
'{profession:"minecraft:librarian",level:2,type:"minecraft:plains"}}')
|
||||
# The saved world still has fluid ticks due in the area the client is sent (a lava fall
|
||||
# that never settles), and they run once their chunk ticks. When that is, against when the
|
||||
# chunk is sent, follows how fast the server loads the chunks around the joining player:
|
||||
# each run, vanilla sends a different set of them already flowed. Frozen until the client
|
||||
# has its chunks, both servers send the world as saved; blocks tick again from the chat on.
|
||||
server.console('tick freeze')
|
||||
port = int(PROPERTIES_PORTS[label])
|
||||
legacy = legacy_ping(port)
|
||||
# The client asks to be made an operator once it has traded, runs /kill and respawns.
|
||||
@@ -282,7 +288,11 @@ def run_side(label, command, directory, client):
|
||||
joined = threading.Thread(target=join)
|
||||
joined.start()
|
||||
deadline = time.time() + 300
|
||||
frozen = True
|
||||
while joined.is_alive() and not any('<Tester> ready to respawn' in l for l in server.lines):
|
||||
if frozen and any('<Tester> hello from the parity client' in l for l in server.lines):
|
||||
server.console('tick unfreeze')
|
||||
frozen = False
|
||||
if time.time() > deadline:
|
||||
break
|
||||
time.sleep(0.2)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare queued interaction ordering with the real Minecraft.handleKeybinds."""
|
||||
import itertools
|
||||
import json
|
||||
import random
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def corpus():
|
||||
rng = random.Random(0x434C49434B)
|
||||
for using, destroying, attack_down, use_down, entity in itertools.product([False, True], repeat=5):
|
||||
for clicks in [[], [1], [0, 1], [1, 0], [2, 1, 0], [0, 0, 1, 1, 2]]:
|
||||
for delay in [0, 3]:
|
||||
yield dict(using=using, destroying=destroying, attack_down=attack_down,
|
||||
use_down=use_down, entity=entity, clicks=clicks, delay=delay,
|
||||
dig_on_attack=rng.choice([False, True]),
|
||||
begin_using=rng.choice([False, True]))
|
||||
# A player interaction returning PASS must go directly to the held item.
|
||||
# The level still reports a solid block underneath the entity hit.
|
||||
for entity in [False, True]:
|
||||
for clicks in [[1], [1, 1], [0, 1], [1, 2]]:
|
||||
yield dict(using=False, destroying=False, attack_down=False, use_down=False,
|
||||
entity=entity, clicks=clicks, delay=0, dig_on_attack=False,
|
||||
begin_using=False, passing=True)
|
||||
|
||||
|
||||
def main():
|
||||
def inputs(build):
|
||||
rows = list(corpus())
|
||||
path = build / "inputs.jsonl"
|
||||
path.write_text("".join(json.dumps(row) + "\n" for row in rows))
|
||||
return path, len(rows)
|
||||
|
||||
harness.differential(
|
||||
"interaction-input-parity", "VanillaInteractionInputOracle", "interaction_input_fixture", inputs,
|
||||
"Invokes Minecraft.handleKeybinds itself with real KeyMapping click counters. "
|
||||
"Compares attack/use/pick ordering, release gating, drained clicks during use, "
|
||||
"held-button repetition and use cooldowns for block/entity targets. "
|
||||
"Includes passing entity interactions over solid blocks: only the held "
|
||||
"item may be tried afterward. "
|
||||
"Game-mode side effects and world simulation are controlled fixtures.",
|
||||
sources=[lab.ROOT / "crates/horizon-client/src/interaction_input.rs",
|
||||
lab.ROOT / "crates/horizon-client/src/game/remote.rs",
|
||||
lab.ROOT / "crates/horizon-client/src/game/hand.rs",
|
||||
lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare movement packet selection and teleport velocity with the pinned client."""
|
||||
import json
|
||||
import random
|
||||
import struct
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def corpus():
|
||||
# Stationary heartbeats, rotation-only updates, status changes and corrected
|
||||
# positions followed by unchanged looks must retain vanilla's packet types.
|
||||
yield dict(kind="movement", ops=[[0, 0, 0, 0, 0, False, False]] * 61)
|
||||
yield dict(kind="movement", ops=[
|
||||
[0, 64, 0, 90, 0, True, False],
|
||||
[0, 64, 0, 90, 0, True, False],
|
||||
[0, 64, 0, 91, 0, True, False],
|
||||
[100, 80, -20, 180, 20, False, False],
|
||||
[100, 80, -20, 180, 20, True, False],
|
||||
[100, 80, -20, 180, 20, True, True],
|
||||
])
|
||||
rng = random.Random(0x53594E43)
|
||||
for _ in range(300):
|
||||
state = [0, 0, 0, 0, 0, False, False]
|
||||
ops = []
|
||||
for _ in range(80):
|
||||
if rng.random() < 0.5:
|
||||
axis = rng.randrange(3)
|
||||
state[axis] += rng.choice([0, 0.0001, 0.0002, 0.0002000001, 0.1, 10])
|
||||
if rng.random() < 0.3:
|
||||
state[3] += rng.choice([-360, -1, 0, 0.001, 1, 360])
|
||||
state[4] = rng.choice([-90, 0, 30, 90])
|
||||
if rng.random() < 0.2:
|
||||
state[rng.randrange(5, 7)] = rng.choice([False, True])
|
||||
ops.append(state.copy())
|
||||
yield dict(kind="movement", ops=ops)
|
||||
for flags in range(16):
|
||||
for _ in range(40):
|
||||
yield dict(kind="velocity", flags=flags << 5,
|
||||
velocity=[rng.uniform(-4, 4) for _ in range(3)],
|
||||
delta=[rng.uniform(-4, 4) for _ in range(3)],
|
||||
old=[rng.uniform(-720, 720), rng.uniform(-90, 90)],
|
||||
new=[rng.uniform(-720, 720), rng.uniform(-90, 90)])
|
||||
|
||||
|
||||
def main():
|
||||
def inputs(build):
|
||||
rows = list(corpus())
|
||||
def bits(v):
|
||||
return struct.pack(">d", v).hex()
|
||||
for row in rows:
|
||||
if row["kind"] == "movement":
|
||||
row["ops"] = [[*map(bits, op[:5]), *op[5:]] for op in row["ops"]]
|
||||
else:
|
||||
for key in ["velocity", "delta", "old", "new"]:
|
||||
row[key] = list(map(bits, row[key]))
|
||||
path = build / "inputs.jsonl"
|
||||
path.write_text("".join(json.dumps(row) + "\n" for row in rows))
|
||||
return path, len(rows)
|
||||
|
||||
harness.differential(
|
||||
"player-sync-parity", "VanillaPlayerSyncOracle", "player_sync_fixture", inputs,
|
||||
"Actual LocalPlayer.sendPosition packet payloads over persistent movement "
|
||||
"sequences; PositionMoveRotation.calculateAbsolute velocity with every "
|
||||
"relative-delta/rotate-delta combination. World simulation, connection "
|
||||
"scheduling and live anticheat behaviour are outside this harness.",
|
||||
sources=[lab.ROOT / "crates/horizon-client/src/player_sync.rs",
|
||||
lab.ROOT / "crates/horizon-client/src/game/remote.rs",
|
||||
lab.ROOT / "crates/horizon-client/src/net.rs"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,317 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Secure chat on vanilla's dedicated server and Horizon's, with no real account.
|
||||
|
||||
A mock of the Minecraft services stands in for Mojang's: its key set (the
|
||||
`authentication` / `getPublicKeys` endpoint) holds a key pair the harness
|
||||
makes, so the profile keys it signs are as good as Mojang's to both servers.
|
||||
Vanilla finds the mock through authlib's `-Dminecraft.api.discovery.host`,
|
||||
Horizon through `HORIZON_API_DISCOVERY`. SecureChatClient (vanilla's own
|
||||
codecs and chat classes) plays several players at once: each signs its chat
|
||||
with a profile key the mock signed, acknowledges what it saw, and checks the
|
||||
signature of every chat it receives against the sender's session from the
|
||||
player list, as vanilla's client does.
|
||||
|
||||
Two servers, each run on vanilla then on Horizon:
|
||||
- offline mode (enforce-secure-profile is then off): signed chat with the
|
||||
last-seen window and the signature cache, unsigned chat beside it, /say,
|
||||
/me and /msg with signed and unsigned arguments, a signed argument under
|
||||
the wrong name, a forged signature and the broken chain after it, and an
|
||||
acknowledgement past the window;
|
||||
- online mode with enforce-secure-profile: the status and the login packet
|
||||
say so, unsigned chat and unsigned commands with a message are refused, and
|
||||
a key signed for another player is refused.
|
||||
|
||||
Compared: every player's transcript, the status' `enforcesSecureChat`, and
|
||||
the servers' log lines about chat.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import threading
|
||||
import urllib.parse
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as oh, test_rust_parity as base
|
||||
from .test_dedicated_server_parity import Server, free_port
|
||||
except ImportError:
|
||||
import lab
|
||||
import oracle_harness as oh
|
||||
import test_rust_parity as base
|
||||
from test_dedicated_server_parity import Server, free_port
|
||||
|
||||
NAME = 'secure-chat-parity'
|
||||
SCENARIOS = {
|
||||
'offline': {'online-mode': 'false'},
|
||||
'online': {'online-mode': 'true', 'enforce-secure-profile': 'true'},
|
||||
}
|
||||
PROPERTIES = {
|
||||
'white-list': 'false',
|
||||
'level-seed': '12345',
|
||||
'view-distance': '3',
|
||||
'simulation-distance': '3',
|
||||
'spawn-protection': '0',
|
||||
'max-players': '8',
|
||||
'pause-when-empty-seconds': '-1',
|
||||
}
|
||||
|
||||
|
||||
def account(name):
|
||||
"""The mock services' account id for a name."""
|
||||
return hashlib.md5(f'account:{name}'.encode()).hexdigest()
|
||||
|
||||
|
||||
class Services:
|
||||
"""Discovery, the key set, the session service's join and hasJoined, profiles by name."""
|
||||
|
||||
def __init__(self, key_set):
|
||||
self.joined = {}
|
||||
self.lock = threading.Lock()
|
||||
services = self
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def reply(self, status, body=None):
|
||||
data = b'' if body is None else json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
if body is not None:
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Content-Length', str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
url = urllib.parse.urlparse(self.path)
|
||||
query = dict(urllib.parse.parse_qsl(url.query))
|
||||
if url.path == '/minecraft/client':
|
||||
return self.reply(200, services.discovery())
|
||||
if url.path == '/publickeys':
|
||||
return self.reply(200, key_set)
|
||||
if url.path.startswith('/users/profiles/minecraft/'):
|
||||
name = urllib.parse.unquote(url.path.rsplit('/', 1)[1])
|
||||
return self.reply(200, {'id': account(name), 'name': name})
|
||||
if url.path == '/session/minecraft/hasJoined':
|
||||
name = query.get('username')
|
||||
with services.lock:
|
||||
ok = services.joined.get(name) == query.get('serverId')
|
||||
if ok:
|
||||
return self.reply(200, {'id': account(name), 'name': name, 'properties': []})
|
||||
return self.reply(204)
|
||||
self.reply(404, {'error': 'NotFound'})
|
||||
|
||||
def do_POST(self):
|
||||
body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', 0))) or b'{}')
|
||||
if self.path != '/session/minecraft/join':
|
||||
return self.reply(404, {'error': 'NotFound'})
|
||||
# The test client names its account instead of its id.
|
||||
with services.lock:
|
||||
services.joined[body.get('selectedProfile')] = body.get('serverId')
|
||||
self.reply(204)
|
||||
|
||||
self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
||||
self.url = f'http://127.0.0.1:{self.server.server_address[1]}'
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
|
||||
def discovery(self):
|
||||
def endpoints(**names):
|
||||
return {'endpoints': {k: {'uri': self.url + v} for k, v in names.items()}}
|
||||
return {'environment': 'mock', 'product': 'minecraft', 'discovery': {
|
||||
'authentication': endpoints(getPublicKeys='/publickeys'),
|
||||
'session': endpoints(join='/session/minecraft/join', verify='/session/minecraft/hasJoined',
|
||||
getProfileById='/session/minecraft/profile/{profileId}'),
|
||||
'player': {'endpoints': {}},
|
||||
'profiles': {'endpoints': {'getTexture': {'validUris': [self.url + '/texture/{textureId}']},
|
||||
'getByName': {'uri': self.url + '/users/profiles/minecraft/{name}'}}},
|
||||
'telemetry': {'endpoints': {}},
|
||||
}}
|
||||
|
||||
def stop(self):
|
||||
self.server.shutdown()
|
||||
|
||||
|
||||
def player_id(name, scenario):
|
||||
"""The player's id: the account's online, UUIDUtil.createOfflinePlayerUUID offline."""
|
||||
if scenario == 'online':
|
||||
return account(name)
|
||||
digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest())
|
||||
digest[6] = digest[6] & 0x0F | 0x30
|
||||
digest[8] = digest[8] & 0x3F | 0x80
|
||||
return digest.hex()
|
||||
|
||||
|
||||
def dashed(u):
|
||||
return f'{u[:8]}-{u[8:12]}-{u[12:16]}-{u[16:20]}-{u[20:]}'
|
||||
|
||||
|
||||
def varint(n):
|
||||
out = b''
|
||||
while True:
|
||||
b = n & 0x7F
|
||||
n >>= 7
|
||||
out += bytes([b | (0x80 if n else 0)])
|
||||
if not n:
|
||||
return out
|
||||
|
||||
|
||||
def status(port):
|
||||
"""The status response's JSON (ServerStatus)."""
|
||||
def packet(body):
|
||||
return varint(len(body)) + body
|
||||
|
||||
def read_varint(s):
|
||||
value = 0
|
||||
for i in range(5):
|
||||
b = s.recv(1)[0]
|
||||
value |= (b & 0x7F) << (7 * i)
|
||||
if not b & 0x80:
|
||||
return value
|
||||
with socket.create_connection(('127.0.0.1', port), timeout=10) as s:
|
||||
host = b'127.0.0.1'
|
||||
s.sendall(packet(b'\x00' + varint(777) + varint(len(host)) + host + port.to_bytes(2, 'big') + b'\x01'))
|
||||
s.sendall(packet(b'\x00'))
|
||||
length = read_varint(s)
|
||||
data = b''
|
||||
while len(data) < length:
|
||||
data += s.recv(length - len(data))
|
||||
text = data[1:]
|
||||
n, shift, i = 0, 0, 0
|
||||
while True:
|
||||
b = text[i]
|
||||
n |= (b & 0x7F) << shift
|
||||
shift += 7
|
||||
i += 1
|
||||
if not b & 0x80:
|
||||
break
|
||||
return json.loads(text[i:i + n])
|
||||
|
||||
|
||||
# The servers' lines about chat, with their level. The thread is left out:
|
||||
# vanilla handles acknowledgements on its network threads, named per platform.
|
||||
CHAT_LINE = re.compile(r'^\[\d\d:\d\d:\d\d\] \[([^\]]+)\]: (.*(?:<\w+>|\[Not Secure\]|\[\w+\] |\* \w+ |secure chat|'
|
||||
r'signable|Signed command|acknowledgement|profile key|chat session|expired chat|lost connection|'
|
||||
r'Disconnecting).*)$')
|
||||
|
||||
|
||||
def chat_lines(lines):
|
||||
out = []
|
||||
for line in lines:
|
||||
if m := CHAT_LINE.match(line):
|
||||
text = re.sub(r'/127\.0\.0\.1:\d+', '/127.0.0.1:_', m.group(2))
|
||||
out.append(f'[{m.group(1).rsplit("/", 1)[-1]}] {text}')
|
||||
return out
|
||||
|
||||
|
||||
def run_side(label, scenario, command, directory, client):
|
||||
port = free_port()
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir(parents=True)
|
||||
props = dict(PROPERTIES, **SCENARIOS[scenario], **{'server-port': str(port)})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
# Alice and Carol are operators (/say needs it), by their ids.
|
||||
ops = [{'uuid': dashed(player_id(name, scenario)), 'name': name, 'level': 4, 'bypassesPlayerLimit': False}
|
||||
for name in ('Alice', 'Carol')]
|
||||
(directory / 'ops.json').write_text(json.dumps(ops, indent=2))
|
||||
server = Server(command, directory, f'{label}-{scenario}')
|
||||
try:
|
||||
server.wait_for(r'Done \(', timeout=600)
|
||||
# A server can drop a ping in its first moments (the network thread still starting): try again.
|
||||
for attempt in range(5):
|
||||
try:
|
||||
enforces = status(port).get('enforcesSecureChat', False)
|
||||
break
|
||||
except (OSError, IndexError):
|
||||
if attempt == 4:
|
||||
raise
|
||||
time.sleep(2)
|
||||
out = directory.parent / f'{label}-{scenario}.txt'
|
||||
client(port, scenario, out)
|
||||
transcript = [f'status enforcesSecureChat {enforces}'] + out.read_text(encoding='utf-8').splitlines()
|
||||
finally:
|
||||
server.stop()
|
||||
return transcript, chat_lines(server.lines)
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
classes = build / 'classes'
|
||||
shutil.rmtree(classes, ignore_errors=True)
|
||||
classes.mkdir()
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/SecureChatClient.java'
|
||||
oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
|
||||
build, 'compile-java')
|
||||
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
|
||||
'compile-rust')
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
java = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.SecureChatClient']
|
||||
oh.run_logged([*java, 'keys', build], build, 'keys')
|
||||
services = Services(json.loads((build / 'publickeys.json').read_text()))
|
||||
discovery = services.url + '/minecraft/client'
|
||||
os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery)
|
||||
servers = {
|
||||
'vanilla': ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}',
|
||||
'-cp', dependencies, 'net.minecraft.server.Main', 'nogui'],
|
||||
'horizon': [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'],
|
||||
}
|
||||
|
||||
def client(port, scenario, out):
|
||||
oh.run_logged([*java, '127.0.0.1', port, build / 'services-private.der', out, scenario, services.url],
|
||||
build, out.stem, timeout=300)
|
||||
|
||||
differences = []
|
||||
try:
|
||||
for scenario in SCENARIOS:
|
||||
results = {}
|
||||
for label, command in servers.items():
|
||||
results[label] = run_side(label, scenario, command, build / f'{label}-{scenario}', client)
|
||||
transcript, log = results[label]
|
||||
(build / f'{label}-{scenario}-all.txt').write_text('\n'.join(transcript + ['--- log'] + log) + '\n',
|
||||
encoding='utf-8')
|
||||
import difflib
|
||||
for part, index in (('transcript', 0), ('log', 1)):
|
||||
diff = [l for l in difflib.unified_diff(results['vanilla'][index], results['horizon'][index],
|
||||
'vanilla', 'horizon', n=0, lineterm='')
|
||||
if l[:1] in '+-' and l[:3] not in ('+++', '---')]
|
||||
if diff:
|
||||
differences.append(f'{scenario} {part}:\n ' + '\n '.join(diff[:60]))
|
||||
errors = [l for l in results['vanilla'][0] if l.startswith('error')]
|
||||
if errors:
|
||||
differences.append(f'{scenario}: the vanilla run failed: {errors}')
|
||||
finally:
|
||||
services.stop()
|
||||
if differences:
|
||||
raise AssertionError('\n'.join(differences) + f'\n(transcripts in {build})')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
scope='Secure chat against vanilla\'s dedicated server: chat sessions validated against mock services keys, '
|
||||
'signed chat with last seen and the signature cache, unsigned chat, /say /me /msg with signed and '
|
||||
'unsigned arguments, mismatched and forged signatures, the broken chain, a bad acknowledgement; '
|
||||
'enforce-secure-profile in online mode (status, login, refusals, a borrowed key); the chat log lines.'))
|
||||
print('secure chat: transcripts and chat log lines identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as error:
|
||||
sys.exit(f'{NAME}: {error}')
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Players in different dimensions on a dedicated server, against vanilla's, seen by vanilla clients.
|
||||
|
||||
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat
|
||||
world vanilla generated first, with Alice and Bob as operators in creative. LocatorBarClient joins them both
|
||||
(players made of vanilla's protocol code) and records, step by step, the other players each is sent and loses
|
||||
(ClientboundAddEntityPacket, ClientboundRemoveEntitiesPacket) and the dimensions it respawns into
|
||||
(ClientboundRespawnPacket), with the locator bar's waypoints, while they change dimensions (ServerPlayer.teleport
|
||||
through `execute in ... run tp`, and an End portal): Bob goes to the Nether and back, Alice to the End, Bob
|
||||
follows her there, both come back to the Overworld, then Bob steps into an End portal and comes back. Between
|
||||
the steps each client sends its position (the reminder a still client sends every second). Each player's lines in each step are compared exactly.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
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
|
||||
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
|
||||
|
||||
NAME = 'server-dimension-players-parity'
|
||||
NETHER, END, OVERWORLD = 'minecraft:the_nether', 'minecraft:the_end', 'minecraft:overworld'
|
||||
# (label, what the players do).
|
||||
SCRIPT = [
|
||||
('bob-nether', [f'cmd Bob execute in {NETHER} run tp @s 0.5 100 0.5']),
|
||||
('bob-back', [f'cmd Bob execute in {OVERWORLD} run tp @s 2.5 100 0.5']),
|
||||
('alice-end', [f'cmd Alice execute in {END} run tp @s 0.5 100 0.5']),
|
||||
('bob-end', [f'cmd Bob execute in {END} run tp @s 2.5 100 0.5']),
|
||||
('alice-back', [f'cmd Alice execute in {OVERWORLD} run tp @s 0.5 100 0.5']),
|
||||
('bob-back-again', [f'cmd Bob execute in {OVERWORLD} run tp @s 2.5 100 0.5']),
|
||||
# Through an End portal (Entity.handlePortal), and back by command.
|
||||
('bob-portal', ['cmd Bob setblock 2 101 3 minecraft:end_portal', 'cmd Bob tp @s 2.5 101 3.5']),
|
||||
('bob-portal-back', [f'cmd Bob execute in {OVERWORLD} run tp @s 2.5 100 0.5']),
|
||||
]
|
||||
STEP_SECONDS = 5.0
|
||||
|
||||
|
||||
def run_side(label, server_command, client_command, build, world):
|
||||
directory = build / label
|
||||
port = server_dir(directory, world)
|
||||
out = build / f'{label}.txt'
|
||||
out.unlink(missing_ok=True)
|
||||
server = Server(server_command, directory, label)
|
||||
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()
|
||||
try:
|
||||
tell('players on')
|
||||
tell('step joins')
|
||||
for name, x in (('Alice', 0.5), ('Bob', 2.5)):
|
||||
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)
|
||||
for step, actions in SCRIPT:
|
||||
tell(f'step {step}')
|
||||
for action in actions:
|
||||
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)
|
||||
finally:
|
||||
if client.poll() is None:
|
||||
client.kill()
|
||||
finally:
|
||||
server.stop()
|
||||
if not out.exists():
|
||||
raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)')
|
||||
return out.read_text(encoding='utf-8').splitlines()
|
||||
|
||||
|
||||
def shown(lines):
|
||||
"""Each player's adds, removes and respawns, without the waypoints (the locator bar harness has those)."""
|
||||
return [l for l in lines if l.split(' ', 2)[2:3] and l.split(' ', 2)[2].split(' ')[0] in ('add', 'remove', 'respawn')]
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java'
|
||||
classes = build / 'classes'
|
||||
shutil.rmtree(classes, ignore_errors=True)
|
||||
classes.mkdir()
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
|
||||
cwd=lab.ROOT, check=True, capture_output=True)
|
||||
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
check=True, capture_output=True)
|
||||
import json
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
|
||||
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
|
||||
|
||||
world = generate_world(vanilla_server, build)
|
||||
vanilla_all = run_side('vanilla', vanilla_server, client, build, world)
|
||||
horizon_all = run_side('horizon', horizon_server, client, build, world)
|
||||
errors = [l for l in vanilla_all + horizon_all if ' error ' in f' {l} ' or 'disconnected' in l]
|
||||
vanilla, horizon = shown(vanilla_all), shown(horizon_all)
|
||||
if errors or vanilla != horizon:
|
||||
import difflib
|
||||
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm=''))
|
||||
raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n'
|
||||
+ '\n'.join(errors[:10]) + '\n' + diff[:6000])
|
||||
if sum(' respawn ' in l for l in vanilla) < 6:
|
||||
raise AssertionError(f'vanilla sent too few respawns: the script did not run (see {build})')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='Two players on a dedicated server changing dimensions (Nether, End, back): the other players each '
|
||||
'is sent and loses, and the dimensions it respawns into.'))
|
||||
print(f'server dimension players: {len(vanilla)} lines identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as error:
|
||||
sys.exit(f'{NAME}: {error}')
|
||||
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Entities other than mobs and items, tracked to a vanilla client, against vanilla's dedicated server.
|
||||
|
||||
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat
|
||||
world vanilla generated first, with the same server.properties (offline, view distance 4). A vanilla-codec
|
||||
client (VanillaProtocolClient in its entity mode) joins, and once its chunks are in it asks for the scene: the
|
||||
console freezes the ticks, builds a wall and a rail and summons, around the spawn, every kind of minecart (one
|
||||
set rolling along the rail), boats and a raft (one falling onto the ground), armor stands (posed, small, with
|
||||
arms, wearing a helmet, one falling), a chicken jockey, a slime, a pig whose scale `/attribute` sets, item
|
||||
frames (one holding a turned diamond), paintings, primed TNT (one falling), a floating falling block, an arrow
|
||||
that lands and an end crystal. The client records for 20 seconds, the ticks running for 200 more after 3, what
|
||||
ClientPacketListener would make of the packets (EntityTranscript): each entity's spawn
|
||||
packet (position, rotations, data, motion), the entity data it was paired with and all it was sent since, its
|
||||
equipment, its attribute instances (ClientboundUpdateAttributesPacket: the ones its first tick creates, the
|
||||
type's set by finalizeSpawn, the baby speed modifier, effects', equipment's and /attribute's) and passengers, and
|
||||
where its position syncs leave it; and the attribute instances the player itself is sent from its login on. Both
|
||||
transcripts must match exactly, entity by entity (named by type and the block it was added in), once the amounts
|
||||
of vanilla's random spawn modifiers are normalised (only client-syncable attributes are sent, so follow range and
|
||||
knockback resistance never show).
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
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
|
||||
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
|
||||
|
||||
NAME = 'server-entities-parity'
|
||||
# Ticks the scene runs for once it is summoned: 10 seconds, within the client's 20.
|
||||
STEPS = 200
|
||||
PLAYER = 'Tester'
|
||||
|
||||
# Around the spawn at 0 -60 0 on the flat world's grass: a wall to the north for the frames and paintings,
|
||||
# a rail to the south.
|
||||
SCENE = [
|
||||
'fill -7 -60 -6 7 -57 -6 minecraft:stone',
|
||||
'fill -7 -60 9 7 -60 9 minecraft:rail',
|
||||
# Minecarts.
|
||||
'summon minecraft:minecart -5.5 -60 3.5',
|
||||
'summon minecraft:chest_minecart -3.5 -60 3.5',
|
||||
'summon minecraft:furnace_minecart -1.5 -60 3.5',
|
||||
'summon minecraft:hopper_minecart 1.5 -60 3.5',
|
||||
'summon minecraft:tnt_minecart 3.5 -60 3.5',
|
||||
'summon minecraft:command_block_minecart 5.5 -60 1.5 {Command:"say hi"}',
|
||||
'summon minecraft:minecart -6.5 -60 9.5 {Motion:[0.5d,0d,0d]}',
|
||||
# Boats.
|
||||
'summon minecraft:oak_boat -5.5 -60 6.5 {Rotation:[45f,0f]}',
|
||||
'summon minecraft:birch_chest_boat -2.5 -60 6.5',
|
||||
'summon minecraft:bamboo_raft 0.5 -60 6.5',
|
||||
'summon minecraft:oak_boat 4.5 -56 6.5',
|
||||
# Armor stands.
|
||||
'summon minecraft:armor_stand -2.5 -60 -2.5 {Rotation:[90f,0f]}',
|
||||
'summon minecraft:armor_stand 6.5 -57 -2.5',
|
||||
'summon minecraft:armor_stand -4.5 -60 -2.5 {ShowArms:1b,Small:1b,NoBasePlate:1b,'
|
||||
'Pose:{Head:[10f,20f,0f],RightArm:[-30f,0f,15f]},equipment:{head:{id:"minecraft:diamond_helmet",count:1}}}',
|
||||
# A chicken jockey (passengers).
|
||||
'summon minecraft:chicken -6.5 -60 -2.5 {NoAI:1b,Passengers:[{id:"minecraft:husk",IsBaby:1b,NoAI:1b}]}',
|
||||
# Attributes: a slime's size sets its bases, /attribute a pig's scale.
|
||||
'summon minecraft:slime 2.5 -60 1.5 {Size:1,NoAI:1b}',
|
||||
'summon minecraft:pig -0.5 -60 1.5 {NoAI:1b}',
|
||||
'attribute @e[type=minecraft:pig,limit=1,x=-0.5,y=-60,z=1.5,distance=..1] minecraft:scale base set 1.5',
|
||||
# Frames and paintings on the wall's south face.
|
||||
'summon minecraft:item_frame -3.5 -59 -4.97 {block_pos:[I;-4,-59,-5],Facing:3b,'
|
||||
'Item:{id:"minecraft:diamond",count:1},ItemRotation:3b}',
|
||||
'summon minecraft:glow_item_frame -1.5 -59 -4.97 {block_pos:[I;-2,-59,-5],Facing:3b}',
|
||||
'summon minecraft:painting 1.5 -59 -4.97 {block_pos:[I;1,-59,-5],facing:0b,variant:"minecraft:kebab"}',
|
||||
'summon minecraft:painting 4 -59 -4.97 {block_pos:[I;4,-59,-5],facing:0b,variant:"minecraft:courbet"}',
|
||||
# Primed TNT that won't go off (one falling), a floating falling block, an arrow that lands, an end crystal.
|
||||
'summon minecraft:tnt 6.5 -60 6.5 {fuse:2000s}',
|
||||
'summon minecraft:tnt 6.5 -56 4.5 {fuse:2000s}',
|
||||
'summon minecraft:falling_block 2.5 -58 -0.5 {BlockState:{Name:"minecraft:sand"},NoGravity:1b}',
|
||||
'summon minecraft:arrow 0.5 -55 -1.5 {Motion:[0.3d,0d,0d]}',
|
||||
'summon minecraft:end_crystal -6.5 -60 6.5 {ShowBottom:0b}',
|
||||
]
|
||||
|
||||
|
||||
# finalizeSpawn's random modifiers on client-syncable attributes (a leader zombie's max health); their amounts
|
||||
# differ from one server to the other.
|
||||
RANDOM_MODIFIERS = re.compile(r'(id=minecraft:(?:random_spawn_bonus|leader_zombie_bonus), amount=)[^,]+')
|
||||
|
||||
|
||||
def scene_lines(lines):
|
||||
"""The transcript's entities in the scene's area (the world's own animals and slimes wander elsewhere), the
|
||||
amounts of random spawn modifiers normalised."""
|
||||
out = []
|
||||
for line in lines:
|
||||
m = re.match(r'play-entities entity \S+ (-?\d+),-?\d+,(-?\d+)', line)
|
||||
if m and -8 <= int(m.group(1)) <= 8 and -7 <= int(m.group(2)) <= 10 or line.startswith('play-entities self '):
|
||||
out.append(RANDOM_MODIFIERS.sub(r'\1~', line))
|
||||
return out
|
||||
|
||||
|
||||
def run_side(label, server_command, client_command, build, world):
|
||||
directory = build / label
|
||||
port = server_dir(directory, world)
|
||||
out = build / f'{label}-client.txt'
|
||||
out.unlink(missing_ok=True)
|
||||
server = Server(server_command, directory, label)
|
||||
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), PLAYER, str(out), 'entities'],
|
||||
cwd=lab.ROOT, stdout=log, stderr=subprocess.STDOUT, text=True)
|
||||
try:
|
||||
server.wait_for(rf'<{PLAYER}> summon the entities', timeout=180)
|
||||
# Frozen, so that every entity is paired as it was summoned whenever each server tracks it in
|
||||
# its tick; then they fall and roll.
|
||||
server.console('tick freeze')
|
||||
for command in SCENE:
|
||||
server.console(command)
|
||||
time.sleep(3)
|
||||
# A fixed number of ticks, so that what still changes (a TNT fuse) ends the same.
|
||||
server.console(f'tick step {STEPS}')
|
||||
client.wait(timeout=120)
|
||||
finally:
|
||||
if client.poll() is None:
|
||||
client.kill()
|
||||
finally:
|
||||
server.stop()
|
||||
if not out.exists():
|
||||
raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)')
|
||||
lines = out.read_text(encoding='utf-8').splitlines()
|
||||
(build / f'{label}.txt').write_text('\n'.join(lines) + '\n', encoding='utf-8')
|
||||
return lines
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java'
|
||||
classes = build / 'classes'
|
||||
shutil.rmtree(classes, ignore_errors=True)
|
||||
classes.mkdir()
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
|
||||
cwd=lab.ROOT, check=True, capture_output=True)
|
||||
# SERVER_ENTITIES_SIDES=vanilla (or horizon) runs one side and reads the other's last transcript.
|
||||
sides = [s for s in os.environ.get('SERVER_ENTITIES_SIDES', 'vanilla,horizon').split(',') if s]
|
||||
if 'horizon' in sides:
|
||||
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
check=True, capture_output=True)
|
||||
import json
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
|
||||
client = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaProtocolClient']
|
||||
|
||||
world = generate_world(vanilla_server, build)
|
||||
results = {}
|
||||
for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]:
|
||||
if label in sides:
|
||||
results[label] = run_side(label, command, client, build, world)
|
||||
else:
|
||||
results[label] = (build / f'{label}.txt').read_text(encoding='utf-8').splitlines()
|
||||
vanilla, horizon = scene_lines(results['vanilla']), scene_lines(results['horizon'])
|
||||
errors = [l for l in results['vanilla'] + results['horizon'] if l.startswith('error')]
|
||||
if errors or vanilla != horizon:
|
||||
import difflib
|
||||
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=0, lineterm=''))
|
||||
raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n'
|
||||
+ '\n'.join(errors[:10]) + '\n' + diff[:8000])
|
||||
if len(vanilla) < len(SCENE) - 2:
|
||||
raise AssertionError(f'only {len(vanilla)} entities tracked: the scene did not run (see {build})')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
entities=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='Minecarts (one rolling), boats (one falling), armor stands, a chicken jockey, a slime, a pig with a '
|
||||
'scale, item frames, paintings, primed TNT, a falling block, an arrow and an end crystal '
|
||||
'tracked to a vanilla-codec client by a dedicated server: spawn packets, entity data, equipment, '
|
||||
'attributes, passengers and the positions the syncs leave them at.'))
|
||||
print(f'server entities: {len(vanilla)} entities identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as error:
|
||||
sys.exit(f'{NAME}: {error}')
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Command feedback the operators get on a dedicated server (`[Server: ...]`), against vanilla's.
|
||||
|
||||
CommandSourceStack.broadcastToAdmins: a command's success that vanilla sends with `broadcast` goes, gray and
|
||||
italic as `[name: message]`, to every other operator while `send_command_feedback` is on, including the
|
||||
console's own commands when `broadcast-console-to-ops` is (DedicatedServer.shouldInformAdmins).
|
||||
|
||||
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat
|
||||
world vanilla generated first, with the same server.properties and Alice and Bob as operators. LocatorBarClient
|
||||
joins them both (players made of vanilla's protocol code) and records the system chat each receives while, step
|
||||
by step, the console sets the time, asks for the difficulty (a query, told to nobody), whitelists a player,
|
||||
deops Bob (who stops hearing of it) and ops him again, turns `send_command_feedback` off and on and saves, and
|
||||
Alice runs a command herself (Bob hears of it as an operator). Then again with `broadcast-console-to-ops=false`.
|
||||
Each player's chat in each step is compared exactly.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
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
|
||||
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
|
||||
|
||||
NAME = 'server-ops-feedback-parity'
|
||||
# (label, what the console does, what the players do).
|
||||
BROADCAST = [
|
||||
('console-time', ['time set 1000'], []),
|
||||
('console-query', ['difficulty'], []),
|
||||
('console-whitelist', ['whitelist add Alice'], []),
|
||||
('console-deop', ['deop Bob'], []),
|
||||
('bob-not-op', ['time set 2000'], []),
|
||||
('alice-bob-not-op', [], ['cmd Alice time set 3000']),
|
||||
('console-op', ['op Bob'], []),
|
||||
('alice-bob-op', [], ['cmd Alice time set 4000']),
|
||||
('feedback-off', ['gamerule send_command_feedback false'], []),
|
||||
('console-feedback-off', ['time set 5000'], []),
|
||||
('feedback-on', ['gamerule send_command_feedback true'], []),
|
||||
('console-save', ['save-all'], []),
|
||||
]
|
||||
QUIET = [
|
||||
('console-time', ['time set 1000'], []),
|
||||
('console-whitelist', ['whitelist add Alice'], []),
|
||||
('alice', [], ['cmd Alice time set 3000']),
|
||||
]
|
||||
CASES = {'broadcast': ({}, BROADCAST), 'quiet': ({'broadcast-console-to-ops': 'false'}, QUIET)}
|
||||
STEP_SECONDS = 2.0
|
||||
|
||||
|
||||
def run_side(label, case, server_command, client_command, build, world):
|
||||
properties, script = CASES[case]
|
||||
directory = build / label / case
|
||||
directory.parent.mkdir(parents=True, exist_ok=True)
|
||||
port = server_dir(directory, world)
|
||||
with (directory / 'server.properties').open('a', encoding='iso-8859-1') as f:
|
||||
f.writelines(f'{k}={v}\n' for k, v in properties.items())
|
||||
out = build / f'{label}-{case}.txt'
|
||||
out.unlink(missing_ok=True)
|
||||
server = Server(server_command, directory, f'{label}-{case}')
|
||||
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()
|
||||
try:
|
||||
for name in ('Alice', 'Bob'):
|
||||
tell(f'join {name}')
|
||||
server.wait_for(rf'{name} joined the game', timeout=120)
|
||||
time.sleep(STEP_SECONDS)
|
||||
tell('chat on')
|
||||
for step, console, actions in script:
|
||||
tell(f'step {step}')
|
||||
for command in console:
|
||||
server.console(command)
|
||||
for action in actions:
|
||||
tell(action)
|
||||
time.sleep(STEP_SECONDS)
|
||||
tell('end')
|
||||
client.wait(timeout=60)
|
||||
finally:
|
||||
if client.poll() is None:
|
||||
client.kill()
|
||||
finally:
|
||||
server.stop()
|
||||
if not out.exists():
|
||||
raise AssertionError(f'{label} {case}: the client wrote no transcript (see {build}/{label}-{case}-client.log)')
|
||||
lines = out.read_text(encoding='utf-8').splitlines()
|
||||
errors = [l for l in lines if ' error ' in f' {l} ' or 'disconnected' in l]
|
||||
return [f'{case} {l}' for l in lines if l.split(' ', 2)[2:3] and l.split(' ', 2)[2].startswith('chat ')], errors
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java'
|
||||
classes = build / 'classes'
|
||||
shutil.rmtree(classes, ignore_errors=True)
|
||||
classes.mkdir()
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
|
||||
cwd=lab.ROOT, check=True, capture_output=True)
|
||||
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
check=True, capture_output=True)
|
||||
import json
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
|
||||
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
|
||||
|
||||
world = generate_world(vanilla_server, build)
|
||||
sides = {'vanilla': ([], []), 'horizon': ([], [])}
|
||||
for case in CASES:
|
||||
for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]:
|
||||
lines, errors = run_side(label, case, command, client, build, world)
|
||||
sides[label][0].extend(lines)
|
||||
sides[label][1].extend(errors)
|
||||
(vanilla, vanilla_errors), (horizon, horizon_errors) = sides['vanilla'], sides['horizon']
|
||||
(build / 'vanilla.txt').write_text('\n'.join(vanilla) + '\n', encoding='utf-8')
|
||||
(build / 'horizon.txt').write_text('\n'.join(horizon) + '\n', encoding='utf-8')
|
||||
errors = vanilla_errors + horizon_errors
|
||||
if errors or vanilla != horizon:
|
||||
import difflib
|
||||
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm=''))
|
||||
raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n'
|
||||
+ '\n'.join(errors[:10]) + '\n' + diff[:6000])
|
||||
if sum('[Server' in l or 'chat.type.admin' in l for l in vanilla) < 5:
|
||||
raise AssertionError(f'vanilla sent the operators too little: the script did not run (see {build})')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='The system chat two operators get on a dedicated server while the console and one of them run '
|
||||
'commands: broadcastToAdmins for the console (broadcast-console-to-ops on and off) and a player, '
|
||||
'queries, deop and op, send_command_feedback off and on, and save-all.'))
|
||||
print(f'server ops feedback: {len(vanilla)} chat lines identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as error:
|
||||
sys.exit(f'{NAME}: {error}')
|
||||
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Commands acting on other players of a dedicated server, against vanilla's, seen by vanilla clients.
|
||||
|
||||
EntitySelector.findPlayers and EntityArgument's player targets: names, UUIDs, `@a`, `@p`, `@r`, `@s` under
|
||||
`execute as`, from the console and from an operator, with `give`, `gamemode`, `tp` (to a place, to a player, with a
|
||||
rotation, and into another level by `execute in`, the console's own level or the destination's), `effect give` and
|
||||
`effect clear`, and `kill`.
|
||||
|
||||
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat world
|
||||
vanilla generated first, with Alice and Bob as operators in creative. LocatorBarClient joins them both (players made
|
||||
of vanilla's protocol code) and records, step by step, the system chat each receives and what the server changes
|
||||
about it: game mode events, teleports, inventory slots, effects, its death (with the death message), the other
|
||||
players it is sent or loses and the levels it respawns into. Each player's lines in each step are compared exactly,
|
||||
in sorted order (the packets of one step may leave in another order within the tick). The locator bar's waypoints
|
||||
and what a death does besides its messages are left to their own harnesses.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid as uuidlib
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
NAME = 'server-player-targets-parity'
|
||||
NETHER, OVERWORLD = 'minecraft:the_nether', 'minecraft:overworld'
|
||||
|
||||
|
||||
def offline_uuid(name):
|
||||
"""UUIDUtil.createOfflinePlayerUUID."""
|
||||
digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest())
|
||||
digest[6] = (digest[6] & 0x0F) | 0x30
|
||||
digest[8] = (digest[8] & 0x3F) | 0x80
|
||||
return str(uuidlib.UUID(bytes=bytes(digest)))
|
||||
|
||||
|
||||
# (label, what the console does, what the players do).
|
||||
SCRIPT = [
|
||||
('console-give', ['give Bob minecraft:diamond 3'], []),
|
||||
('console-give-all', ['give @a minecraft:apple'], []),
|
||||
('alice-give-bob', [], ['cmd Alice give Bob minecraft:stick 2']),
|
||||
('console-give-uuid', [f'give {offline_uuid("Bob")} minecraft:iron_ingot'], []),
|
||||
('console-give-nearest', ['give @p minecraft:emerald'], []),
|
||||
('alice-give-random', [], ['cmd Alice give @r[name=Bob] minecraft:gold_ingot']),
|
||||
('console-gamemode', ['gamemode survival Bob'], []),
|
||||
('alice-gamemode-bob', [], ['cmd Alice gamemode creative Bob']),
|
||||
('alice-gamemode-all', [], ['cmd Alice gamemode adventure @a']),
|
||||
('console-gamemode-back', ['gamemode creative @a'], []),
|
||||
('console-tp', ['tp Bob 8.5 -60 8.5'], []),
|
||||
('alice-tp-bob-to-alice', [], ['cmd Alice tp Bob Alice']),
|
||||
('console-tp-rotation', ['tp Bob 4.5 -60 0.5 90 10'], []),
|
||||
('bob-tp-self', [], ['cmd Bob tp @s 6.5 -60 0.5']),
|
||||
('console-execute-as', ['execute as Bob run tp @s ~ ~ ~2'], []),
|
||||
('console-execute-at', ['execute at Bob run tp Alice ~1 ~ ~'], []),
|
||||
('alice-execute-as-all', [], ['cmd Alice execute as @a run give @s minecraft:bread']),
|
||||
('console-effect', ['effect give Bob minecraft:speed 30 1'], []),
|
||||
('alice-effect-all', [], ['cmd Alice effect give @a minecraft:haste infinite']),
|
||||
('console-effect-clear', ['effect clear Bob'], []),
|
||||
('alice-effect-clear-all', [], ['cmd Alice effect clear @a minecraft:haste']),
|
||||
('console-nether', [f'execute in {NETHER} run tp Bob 0.5 100 0.5'], []),
|
||||
('console-tp-home', ['tp Bob 4.5 -60 0.5'], []),
|
||||
('alice-nether', [], [f'cmd Alice execute in {NETHER} run tp Bob 0.5 100 0.5']),
|
||||
('console-tp-to-alice', ['tp Bob Alice'], []),
|
||||
('alice-kill-missing', [], ['cmd Alice kill Carol']),
|
||||
('console-kill', ['kill Bob'], []),
|
||||
]
|
||||
# What the players' locator bars show has its own harness (test_locator_bar_parity), and what a death does
|
||||
# besides its messages (drops, the body leaving) the player combat ones: here only the messages of `kill`.
|
||||
WAYPOINTS = ('track ', 'untrack ', 'update ')
|
||||
DEATH_STEP = 'step=console-kill'
|
||||
STEP_SECONDS = 2.5
|
||||
|
||||
|
||||
def run_side(label, server_command, client_command, build, world):
|
||||
directory = build / label
|
||||
port = server_dir(directory, world)
|
||||
out = build / f'{label}.txt'
|
||||
out.unlink(missing_ok=True)
|
||||
server = Server(server_command, directory, label)
|
||||
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()
|
||||
try:
|
||||
for name, x in (('Alice', 0.5), ('Bob', 4.5)):
|
||||
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} -60 0.5 0 0')
|
||||
time.sleep(STEP_SECONDS)
|
||||
for flag in ('chat', 'state', 'players'):
|
||||
tell(f'{flag} on')
|
||||
for step, console, actions in SCRIPT:
|
||||
tell(f'step {step}')
|
||||
for command in console:
|
||||
server.console(command)
|
||||
for action in actions:
|
||||
tell(action)
|
||||
time.sleep(STEP_SECONDS)
|
||||
for name in ('Alice', 'Bob'):
|
||||
tell(f'still {name}')
|
||||
tell('end')
|
||||
client.wait(timeout=60)
|
||||
finally:
|
||||
if client.poll() is None:
|
||||
client.kill()
|
||||
finally:
|
||||
server.stop()
|
||||
if not out.exists():
|
||||
raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)')
|
||||
lines = out.read_text(encoding='utf-8').splitlines()
|
||||
errors = [l for l in lines if ' error ' in f' {l} ' or 'disconnected' in l]
|
||||
steps = {}
|
||||
for line in lines:
|
||||
who, step, rest = line.split(' ', 2)
|
||||
# At the death, Alice picks up Bob's drops (and gets their advancements) in vanilla.
|
||||
death_side = step == DEATH_STEP and (not rest.startswith(('chat ', 'killed '))
|
||||
or 'chat.type.advancement' in rest)
|
||||
if rest.startswith(WAYPOINTS) or death_side:
|
||||
continue
|
||||
if step != 'step=start':
|
||||
steps.setdefault((who, step), []).append(line)
|
||||
order = {f'step={s}': i for i, (s, _, _) in enumerate(SCRIPT)}
|
||||
keys = sorted(steps, key=lambda k: (k[0], order.get(k[1], -1)))
|
||||
return [l for k in keys for l in sorted(steps[k])], errors
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java'
|
||||
classes = build / 'classes'
|
||||
shutil.rmtree(classes, ignore_errors=True)
|
||||
classes.mkdir()
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
|
||||
cwd=lab.ROOT, check=True, capture_output=True)
|
||||
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
check=True, capture_output=True)
|
||||
import json
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
|
||||
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
|
||||
|
||||
world = generate_world(vanilla_server, build)
|
||||
vanilla, vanilla_errors = run_side('vanilla', vanilla_server, client, build, world)
|
||||
horizon, horizon_errors = run_side('horizon', horizon_server, client, build, world)
|
||||
(build / 'vanilla.txt').write_text('\n'.join(vanilla) + '\n', encoding='utf-8')
|
||||
(build / 'horizon.txt').write_text('\n'.join(horizon) + '\n', encoding='utf-8')
|
||||
errors = vanilla_errors + horizon_errors
|
||||
if errors or vanilla != horizon:
|
||||
import difflib
|
||||
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm=''))
|
||||
raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n'
|
||||
+ '\n'.join(errors[:10]) + '\n' + diff[:8000])
|
||||
for needle in ('gamemode 0', 'minecraft:diamond x3', 'effect minecraft:speed', 'respawn ' + NETHER,
|
||||
'death.attack.genericKill'):
|
||||
if not any(needle in l for l in vanilla):
|
||||
raise AssertionError(f'vanilla never sent {needle!r}: the script did not run (see {build})')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='Commands from the console and an operator acting on another player of a dedicated server: names, '
|
||||
'UUIDs, @a, @p, @r and @s under execute as/at, with give, gamemode, tp (place, player, rotation, '
|
||||
'execute in, across levels), effect give and clear and kill, as the players see them.'))
|
||||
print(f'server player targets: {len(vanilla)} lines identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as error:
|
||||
sys.exit(f'{NAME}: {error}')
|
||||
@@ -10,7 +10,10 @@ to the preset's classic ones) and `generate-structures`.
|
||||
Each case starts vanilla's server and Horizon's (`horizon-client --dedicated --nogui`) in a new folder, waits
|
||||
for `Done` and stops them. Compared exactly: the world's `data/minecraft/world_gen_settings.dat`, tag types
|
||||
included, and the warnings and errors logged while the world's settings are read (the `Worker-Main` lines;
|
||||
the worker's number is left out).
|
||||
the worker's number is left out). In a world without structures (`generate-structures=false`), also what
|
||||
`locate structure` answers on the console for a village and a mineshaft (ChunkGenerator.findNearestMapStructure
|
||||
finds none) and how many of the saved chunks hold structure starts or references (none:
|
||||
ChunkStatusTasks.generateStructureStarts does nothing).
|
||||
|
||||
Horizon generates the normal and flat presets only: `large_biomes`, `amplified`, `single_biome_surface` and
|
||||
`debug_all_block_states` aren't tested.
|
||||
@@ -23,6 +26,7 @@ import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
try:
|
||||
from . import anvil_dump, lab, test_rust_parity as base
|
||||
@@ -60,6 +64,32 @@ CASES = {
|
||||
'unknown': {'level-type': 'Some Type', 'level-seed': '42'},
|
||||
}
|
||||
WORKER = re.compile(r'\[Worker-Main-\d+/(WARN|ERROR)\]: (.*)')
|
||||
LOCATE = ['locate structure #minecraft:village', 'locate structure minecraft:mineshaft']
|
||||
REPLY = re.compile(r'\]: (?:System chat: )?((?:Could not find|The nearest|Unknown|Incorrect).*)')
|
||||
|
||||
|
||||
def console_reply(server, command, timeout=300):
|
||||
"""The first command reply the console logs after `command`."""
|
||||
start = len(server.lines)
|
||||
server.console(command)
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
for line in server.lines[start:]:
|
||||
if m := REPLY.search(line):
|
||||
return m.group(1)
|
||||
time.sleep(0.2)
|
||||
raise AssertionError(f'no reply to {command!r} in {timeout} s:\n' + '\n'.join(server.lines[-20:]))
|
||||
|
||||
|
||||
def structure_chunks(world):
|
||||
"""How many saved overworld chunks hold structure starts, and how many references."""
|
||||
starts = references = 0
|
||||
for region in sorted((world / 'region').glob('*.mca')):
|
||||
for chunk in anvil_dump.region_chunks(region).values():
|
||||
structures = anvil_dump.plain(chunk, True).get('structures', {})
|
||||
starts += bool(structures.get('starts'))
|
||||
references += bool(structures.get('References'))
|
||||
return f'chunks with structure starts: {starts}, with references: {references}'
|
||||
|
||||
|
||||
def escape(value):
|
||||
@@ -77,11 +107,16 @@ def run_case(label, command, build, case):
|
||||
encoding='iso-8859-1')
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
server = Server(command, directory, f'{label}-{case}')
|
||||
replies = []
|
||||
try:
|
||||
server.wait_for(r'Done \(')
|
||||
if CASES[case].get('generate-structures') == 'false':
|
||||
replies = [f'{c}: {console_reply(server, c)}' for c in LOCATE]
|
||||
finally:
|
||||
server.stop()
|
||||
out = [f'# {case}']
|
||||
out = [f'# {case}', *replies]
|
||||
if replies:
|
||||
out.append(structure_chunks(directory / 'world'))
|
||||
out += [f'{m.group(1)}: {m.group(2)}' for l in server.lines if (m := WORKER.search(l))]
|
||||
settings = anvil_dump.plain(anvil_dump.read_dat(directory / 'world/data/minecraft/world_gen_settings.dat'),
|
||||
True, typed=True)
|
||||
@@ -121,7 +156,8 @@ def main():
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
cases=list(CASES), lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='a new dedicated-server world: level-type (flat, normal, unknown), a flat world\'s '
|
||||
'generator-settings, generate-structures, as world_gen_settings.dat and the lines logged.'))
|
||||
'generator-settings, generate-structures, as world_gen_settings.dat and the lines logged; without '
|
||||
'structures, locate structure\'s replies and the saved chunks\' structure starts and references.'))
|
||||
print(f'server world gen: {len(CASES)} cases, {len(vanilla)} lines identical')
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare item tooltip display visibility with the pinned vanilla client."""
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def cases(build):
|
||||
values = [
|
||||
(False, False, False),
|
||||
(False, False, True),
|
||||
(False, True, True),
|
||||
(True, False, False),
|
||||
(True, True, False),
|
||||
(True, True, True),
|
||||
]
|
||||
path = build / 'cases.txt'
|
||||
# Lowercase: Rust's bool parser takes only true/false (Java's parseBoolean ignores case).
|
||||
path.write_text('\n'.join('\t'.join(str(v).lower() for v in row) for row in values) + '\n')
|
||||
return path, len(values)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
harness.differential(
|
||||
'tooltip-display-parity', 'VanillaTooltipDisplayOracle', 'tooltip_display_fixture', cases,
|
||||
'Diamond sword name and attribute tooltip visibility for hide_tooltip, hidden_components, and creative flags',
|
||||
sources=[
|
||||
lab.ROOT / 'crates/horizon-client/src/game/stations.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs',
|
||||
],
|
||||
expected_lines=6)
|
||||
@@ -18,18 +18,28 @@ except ImportError:
|
||||
|
||||
def corpus(facts):
|
||||
def bits(v):return struct.pack('>d',float(v)).hex()
|
||||
def row(state,delta=(1,-0.08,0),step=0.6,grounded=True,context=2,offset=0,fail=-1,extra=(),entities=(),border=None):
|
||||
def row(state,delta=(1,-0.08,0),step=0.6,grounded=True,context=2,offset=0,fail=-1,extra=(),entities=(),border=None,box=None):
|
||||
blocks=[[x+offset,-1,z,facts['defaults']['minecraft:stone']] for x in range(-2,4) for z in range(-2,3)]
|
||||
blocks.append([offset,0,0,state]);blocks.extend(extra)
|
||||
return dict(chunks=[[x,z] for x in range((offset>>4)-1,(offset>>4)+2) for z in range(-1,2)],
|
||||
blocks=blocks,context=context,y=bits(0),entities=[0,0],fail=fail,limit=100000,suffocating=False,
|
||||
box=list(map(bits,[-0.6+offset,0,0.2,-0.2+offset,1.8,0.8])),
|
||||
box=list(map(bits,box if box is not None else [-0.6+offset,0,0.2,-0.2+offset,1.8,0.8])),
|
||||
movement=dict(delta=list(map(bits,delta)),step=bits(step),grounded=grounded,
|
||||
entities=[list(map(bits,b)) for b in entities],border=None if border is None else list(map(bits,border))))
|
||||
states=facts['states']
|
||||
for state in range(len(states)):
|
||||
yield row(state,context=state%4)
|
||||
defaults=facts['defaults']
|
||||
falling_surfaces=[('minecraft:stone_slab',0.5),('minecraft:oak_stairs',1.0),('minecraft:snow',0.125),
|
||||
('minecraft:oak_fence',1.5),('minecraft:iron_bars',1.0),('minecraft:soul_sand',0.875),
|
||||
('minecraft:farmland',0.9375)]
|
||||
for block_id,top in falling_surfaces:
|
||||
state=defaults[block_id]
|
||||
size=struct.unpack('>f',struct.pack('>f',0.98))[0]
|
||||
half=size/2
|
||||
bottom=top+0.1
|
||||
box=[0.5-half,bottom,0.5-half,0.5+half,bottom+size,0.5+half]
|
||||
yield row(state,delta=(0,-0.25,0),step=0,grounded=False,context=2,box=box)
|
||||
obstacles=[i for i,s in enumerate(states) if s['id'] in ['minecraft:oak_stairs','minecraft:stone_slab',
|
||||
'minecraft:snow','minecraft:scaffolding','minecraft:powder_snow','minecraft:water',
|
||||
'minecraft:shulker_box','minecraft:moving_piston','minecraft:piston','minecraft:soul_sand',
|
||||
@@ -114,7 +124,7 @@ def main():
|
||||
'definition_counts':dict(collections.Counter(definitions.values())),
|
||||
'native_chunk_storage':'ProtoChunk', 'rust_chunk_storage':'TerrainChunk', 'fixtures':count, 'sources_sha256':tested, 'fixtures_sha256':fixtures,
|
||||
'rust_output_sha256':lab.digest(build/'rust.txt', 'sha256'), 'references':references,
|
||||
'scope':'Actual native Entity.collide executes initial collision and step-up decisions over BlockCollisions, registered block shapes and resident ProtoChunk sections. Rust combines owned/fallible step resolution with registry-bound TerrainChunk scanning. All registered states are used as obstacles, plus step heights, falling/grounded motion, zero and underflow motion, partial blocks, fluids, dynamic blocks, ceilings, chunk boundaries and query failures. Entity collider lists and world-border proximity/shape are controlled inputs; query order and reuse, shape collection and resulting displacement are compared. Contexts are deliberately supplied empty/position/placement snapshots in both worlds. This does not establish entity broad-phase selection, actual world-border proximity, travel/gravity/velocity or grounded side effects, experimental minecarts or a playable game.'}
|
||||
'scope':'Actual native Entity.collide executes initial collision and step-up decisions over BlockCollisions, registered block shapes and resident ProtoChunk sections. Rust combines owned/fallible step resolution with registry-bound TerrainChunk scanning. All registered states are used as obstacles, plus step heights, falling/grounded motion, zero and underflow motion, partial blocks including exact falling-block-sized boxes over slabs, stairs, snow, fences, iron bars, soul sand and farmland, fluids, dynamic blocks, ceilings, chunk boundaries and query failures. Entity collider lists and world-border proximity/shape are controlled inputs; query order and reuse, shape collection and resulting displacement are compared. Contexts are deliberately supplied empty/position/placement snapshots in both worlds. This does not establish entity broad-phase selection, actual world-border proximity, travel/gravity/velocity or grounded side effects, experimental minecarts or a playable game.'}
|
||||
lab.write_json(report_path, report);print(f'Scoped world movement parity passed: {report_path}', flush=True)
|
||||
|
||||
|
||||
|
||||
+17
-6
@@ -5,6 +5,10 @@ servers: --offlineDeveloperMode) and optionally join a server straight away
|
||||
|
||||
vscreen start python3 tools/vanilla_client.py --name Guest --join localhost:25565
|
||||
|
||||
On Linux (x86_64) and on macOS (Apple silicon, from the logged-in screen session), from the files
|
||||
tools/lab.py prepared on that machine. On macOS vsync is off: with it on, a window nobody can see (a
|
||||
locked session, or covered) blocks in SDL_GL_SwapWindow and the client stops before it joins.
|
||||
|
||||
Sound goes to OpenAL's null backend. The game directory gets an options.txt
|
||||
that skips the first-run screens, keeps the game running unfocused and
|
||||
renders few chunks, so a harness can drive it with vscreen keys.
|
||||
@@ -21,6 +25,9 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GAME = ROOT / ".local/minecraft/26.3"
|
||||
MAC = sys.platform == "darwin"
|
||||
# The natives of this machine's platform, and the shared libraries in them.
|
||||
NATIVES, LIBRARY_SUFFIX = ("natives-macos-arm64.jar", ".dylib") if MAC else ("natives-linux.jar", ".so")
|
||||
|
||||
OPTIONS = {
|
||||
"onboardAccessibility": "false",
|
||||
@@ -40,6 +47,8 @@ OPTIONS = {
|
||||
"onlyShowSecureChat": "false",
|
||||
"rawMouseInput": "false",
|
||||
}
|
||||
if sys.platform == "darwin":
|
||||
OPTIONS["enableVsync"] = "false"
|
||||
|
||||
|
||||
def offline_uuid(name):
|
||||
@@ -49,10 +58,12 @@ def offline_uuid(name):
|
||||
return uuid.UUID(bytes=bytes(digest))
|
||||
|
||||
|
||||
def linux_library(path):
|
||||
def host_library(path):
|
||||
name = Path(path).name
|
||||
if "natives-" in name:
|
||||
return name.endswith("natives-linux.jar")
|
||||
return name.endswith(NATIVES)
|
||||
if MAC:
|
||||
return "netty-transport-native" not in name or "linux" not in name
|
||||
if "netty-transport-native" in name and ("osx" in name or "aarch_64" in name):
|
||||
return False
|
||||
return "java-objc-bridge" not in name
|
||||
@@ -60,18 +71,18 @@ def linux_library(path):
|
||||
|
||||
def classpath():
|
||||
prepared = json.loads((GAME / "prepared.json").read_text())
|
||||
jars = [ROOT / p for p in prepared["libraries"]["client"] if linux_library(p)]
|
||||
jars = [ROOT / p for p in prepared["libraries"]["client"] if host_library(p)]
|
||||
return [GAME / "jars/client.jar", *jars]
|
||||
|
||||
|
||||
def extract_natives(jars, target):
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
for jar in jars:
|
||||
if not jar.name.endswith("natives-linux.jar"):
|
||||
if not jar.name.endswith(NATIVES):
|
||||
continue
|
||||
with zipfile.ZipFile(jar) as archive:
|
||||
for name in archive.namelist():
|
||||
if name.endswith(".so") and "arm" not in name and "aarch" not in name:
|
||||
if name.endswith(LIBRARY_SUFFIX) and (MAC or ("arm" not in name and "aarch" not in name)):
|
||||
out = target / Path(name).name
|
||||
if not out.exists():
|
||||
out.write_bytes(archive.read(name))
|
||||
@@ -105,7 +116,7 @@ def command(args):
|
||||
extract_natives(jars, natives)
|
||||
assets = args.assets or (args.game_dir / "assets")
|
||||
(assets / "indexes").mkdir(parents=True, exist_ok=True)
|
||||
cmd = ["java", f"-Xmx{args.heap}", "-XX:StackShadowPages=32",
|
||||
cmd = ["java", f"-Xmx{args.heap}", *(["-XstartOnFirstThread"] if MAC else []), "-XX:StackShadowPages=32",
|
||||
"--enable-native-access=ALL-UNNAMED",
|
||||
"--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED",
|
||||
f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}",
|
||||
|
||||
Reference in New Issue
Block a user