Merge remote-tracking branch 'origin/main' into mm1-1447
# Conflicts: # .github/workflows/ci.yml
This commit is contained in:
@@ -1,85 +0,0 @@
|
||||
# Reproducing PR #607 block-facts startup profiles
|
||||
|
||||
These are loader-only measurements. They include `Assets::load`, `BlockFacts`, and
|
||||
`Behaviours` and exclude content root preparation, graphics, input setup, first
|
||||
frame, and the rest of the client startup sequence. No full-client startup gain
|
||||
has been measured. The prepared `26.3` resource root must match the revision.
|
||||
|
||||
## Historical release builds
|
||||
|
||||
From the PR branch checkout, use an absolute prepared resource-root path and a
|
||||
single, explicit Cargo release profile for each detached historical worktree:
|
||||
|
||||
```sh
|
||||
PR_ROOT="$(pwd)"
|
||||
BENCH_ROOT="$(mktemp -d)"
|
||||
mkdir -p "$BENCH_ROOT/bin"
|
||||
CARGO_TARGET_DIR="$BENCH_ROOT/target"
|
||||
export CARGO_TARGET_DIR
|
||||
|
||||
for entry in baseline:e422bd13 a01:a01d47f2 cf:cf837118 cd:cd61e11b; do
|
||||
name="${entry%%:*}"
|
||||
revision="${entry#*:}"
|
||||
git worktree add --detach "$BENCH_ROOT/$name" "$revision"
|
||||
done
|
||||
|
||||
# e422bd13 predates the profiler; add the same baseline example source used
|
||||
# for the benchmark, without changing any production implementation.
|
||||
cp "$PR_ROOT/tools/baseline_loader_profile.rs" \
|
||||
"$BENCH_ROOT/baseline/crates/horizon-client/examples/shared_json_startup_profile.rs"
|
||||
|
||||
for name in baseline a01 cf cd; do
|
||||
(cd "$BENCH_ROOT/$name" && \
|
||||
cargo build --offline --release -p horizon-client --example shared_json_startup_profile)
|
||||
cp "$CARGO_TARGET_DIR/release/examples/shared_json_startup_profile" \
|
||||
"$BENCH_ROOT/bin/$name"
|
||||
done
|
||||
|
||||
cargo build --offline --release -p horizon-client --example shared_json_startup_profile
|
||||
cp "$CARGO_TARGET_DIR/release/examples/shared_json_startup_profile" "$BENCH_ROOT/bin/current"
|
||||
|
||||
python3 tools/profile_shared_json.py \
|
||||
--resources /absolute/path/to/.local/horizon-client/26.3 \
|
||||
--baseline-binary "$BENCH_ROOT/bin/baseline" \
|
||||
--a01-binary "$BENCH_ROOT/bin/a01" \
|
||||
--cf-binary "$BENCH_ROOT/bin/cf" \
|
||||
--cd-binary "$BENCH_ROOT/bin/cd" \
|
||||
--binary "$BENCH_ROOT/bin/current" \
|
||||
--repeats 10 --output "$BENCH_ROOT/five-way.json"
|
||||
```
|
||||
|
||||
The source tree of each historical revision is exact. The baseline profiler is
|
||||
an added standalone measurement example, and therefore does not alter its
|
||||
historical loader logic. Comparisons use alternating forward/reverse process
|
||||
order, separate processes, Linux `wait4` CPU time and peak RSS, and saved raw
|
||||
samples with 25th/75th percentiles, extrema, build hashes and system load.
|
||||
Keep concurrent compilation and other CPU-intensive jobs idle if possible.
|
||||
`ru_maxrss` records process peak residency and cannot establish the real game's
|
||||
memory usage after rendering begins. If system load rises, preserve rather than
|
||||
discard outliers and report the uncertainty.
|
||||
|
||||
## Decoding passes and buffer lifetime
|
||||
|
||||
```sh
|
||||
cargo build --offline --release -p horizon-client --example gameplay_decode_profile
|
||||
python3 tools/profile_gameplay_decode.py \
|
||||
--resources /absolute/path/to/.local/horizon-client/26.3 \
|
||||
--repeats 10 --output "$BENCH_ROOT/decode.json"
|
||||
|
||||
python3 tools/profile_shared_json.py \
|
||||
--resources /absolute/path/to/.local/horizon-client/26.3 \
|
||||
--variant released="$BENCH_ROOT/bin/current"@deferred \
|
||||
--variant retained="$BENCH_ROOT/bin/current"@deferred-held \
|
||||
--repeats 10 --output "$BENCH_ROOT/lifetime.json"
|
||||
```
|
||||
|
||||
The decoder profile measures the `Validate` pass and typed `Gameplay` pass
|
||||
separately, including the JSON read in `total_ms`. The primary facts loader
|
||||
continues both passes to preserve JSON validation, error precedence and useful
|
||||
diagnostics, including overwritten fields and raw geometry. The lifetime
|
||||
comparison measures current process `VmRSS` after materialisation, plus peak
|
||||
RSS across the process. An explicit `drop` releases owned Rust values, but the
|
||||
allocator may retain physical pages, so immediate RSS savings are not implied.
|
||||
|
||||
When finished, `git worktree remove` each temporary historical worktree. Do
|
||||
not `git clean` or reset the active PR working tree.
|
||||
@@ -1,36 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Group the mismatches of tools/test_command_parse_parity.py by cause.
|
||||
|
||||
usage: command_parse_summary.py MISMATCHES.jsonl [ROOT]
|
||||
"""
|
||||
import collections
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def describe(side, kind):
|
||||
if kind == 'parse':
|
||||
if side.get('ok'):
|
||||
return 'OK'
|
||||
return f"ERR {side.get('error')!r}@{'c' if side.get('cursor') else '0'}"
|
||||
return f"SUGG[{len(side['list'])}]"
|
||||
|
||||
|
||||
path = Path(sys.argv[1])
|
||||
only = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
groups = collections.Counter()
|
||||
examples = {}
|
||||
for line in path.open(encoding='utf-8'):
|
||||
m = json.loads(line)
|
||||
root = m['in'].split(' ')[0]
|
||||
if only and root != only:
|
||||
continue
|
||||
key = (m['kind'], describe(m['vanilla'], m['kind']), describe(m['rust'], m['kind']))
|
||||
if m['kind'] == 'parse':
|
||||
key = key[:1] + (key[1][:90], key[2][:90])
|
||||
groups[key] += 1
|
||||
examples.setdefault(key, m)
|
||||
for key, count in sorted(groups.items(), key=lambda kv: -kv[1])[:int(sys.argv[3]) if len(sys.argv) > 3 else 40]:
|
||||
ex = examples[key]
|
||||
print(f'{count:6} {key[0]} vanilla={key[1]} rust={key[2]}\n e.g. {ex["in"]!r}')
|
||||
@@ -1,79 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Structural diff between vanilla's exported command tree and Horizon's.
|
||||
|
||||
usage: command_tree_diff.py VANILLA_TREE.json RUST_TREE.json [ROOT]
|
||||
|
||||
Reports, for every shared node, the children Horizon lacks or adds, differing
|
||||
argument parsers and executable/redirect flags. Missing subtrees are reported
|
||||
once at their root.
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
LOOSE = {
|
||||
# Horizon's coarse argument kinds that stand in for several vanilla parsers.
|
||||
'brigadier:string': {'brigadier:string', 'minecraft:message', 'minecraft:component'},
|
||||
}
|
||||
|
||||
|
||||
def same_parser(vanilla, rust):
|
||||
if vanilla == rust:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def keyed(children):
|
||||
"""Literals by name; arguments by position (their names are internal)."""
|
||||
out = {}
|
||||
index = 0
|
||||
for name, child in children.items():
|
||||
if child['type'] == 'literal':
|
||||
out[('l', name)] = (name, child)
|
||||
else:
|
||||
out[('a', index)] = (name, child)
|
||||
index += 1
|
||||
return out
|
||||
|
||||
|
||||
def diff(path, v, r, out):
|
||||
vc, rc = keyed(v.get('children', {})), keyed(r.get('children', {}))
|
||||
for key, (name, node) in vc.items():
|
||||
if key not in rc:
|
||||
out.append(('missing', path + [name], node.get('parser') or 'literal', count(node)))
|
||||
for key, (name, node) in rc.items():
|
||||
if key not in vc:
|
||||
out.append(('extra', path + [name], node.get('parser') or 'literal', count(node)))
|
||||
for key, (name, a) in vc.items():
|
||||
if key not in rc:
|
||||
continue
|
||||
_, b = rc[key]
|
||||
if a['type'] == 'argument' and not same_parser(a['parser'], b['parser']):
|
||||
out.append(('parser', path + [name], f"{a['parser']} vs {b['parser']}", 0))
|
||||
if bool(a.get('executable')) != bool(b.get('executable')):
|
||||
out.append(('executable', path + [name], f"vanilla={bool(a.get('executable'))}", 0))
|
||||
if bool(a.get('redirect')) != bool(b.get('redirect')):
|
||||
out.append(('redirect', path + [name], f"vanilla={bool(a.get('redirect'))}", 0))
|
||||
diff(path + [name], a, b, out)
|
||||
|
||||
|
||||
def count(node):
|
||||
return 1 + sum(count(c) for c in node.get('children', {}).values())
|
||||
|
||||
|
||||
def main():
|
||||
vanilla = json.load(open(sys.argv[1]))
|
||||
rust = json.load(open(sys.argv[2]))
|
||||
only = sys.argv[3] if len(sys.argv) > 3 else None
|
||||
if only:
|
||||
vanilla = {'children': {only: vanilla['children'][only]}, 'type': 'root'}
|
||||
rust = {'children': {only: rust['children'].get(only, {'children': {}, 'type': 'literal'})}, 'type': 'root'}
|
||||
out = []
|
||||
diff([], vanilla, rust, out)
|
||||
for kind, path, detail, size in out:
|
||||
print(f'{kind:10} {" ".join(path)} [{detail}]' + (f' ({size} nodes)' if size else ''))
|
||||
missing = sum(size for kind, _, _, size in out if kind == 'missing')
|
||||
print(f'-- {len(out)} differences, {missing} vanilla nodes missing in Horizon')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,91 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare Rust container loot (examples/loot_fill) with vanilla LootTable.fill.
|
||||
|
||||
usage: compare_loot_fill.py RESOURCES TABLES SEED...
|
||||
TABLES is a comma-separated list or `chests` for every chest table. Builds the
|
||||
loot_fill example, runs VanillaLootFillOracle and diffs slot contents
|
||||
(enchantments compared as sets). Tables vanilla cannot fill without a level
|
||||
(exploration maps) are reported and skipped.
|
||||
"""
|
||||
import collections
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
|
||||
def build_dir():
|
||||
return Path(os.environ['HORIZON_ORACLE_BUILD']) if os.environ.get('HORIZON_ORACLE_BUILD') else lab.LOCAL/'loot-fill-oracle'
|
||||
|
||||
|
||||
def run_oracle(out, tables, seeds):
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLootFillOracle.java'
|
||||
build = build_dir()
|
||||
classes = build/'classes'
|
||||
classes.mkdir(parents=True, exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
compiled = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies,
|
||||
'-d', str(classes), str(source)], capture_output=True, text=True)
|
||||
if compiled.returncode:
|
||||
raise SystemExit('javac failed:\n' + compiled.stderr[-3000:])
|
||||
result = subprocess.run(['java', '-Xmx2G', '-cp', str(classes)+os.pathsep+dependencies,
|
||||
'dev.horizonlab.parity.VanillaLootFillOracle', str(out), tables, *seeds],
|
||||
capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
lines = [line for line in (result.stdout + result.stderr).splitlines() if 'Exception' in line or 'Caused' in line]
|
||||
raise SystemExit('oracle failed: ' + ' | '.join(lines[:5]))
|
||||
|
||||
|
||||
def parse(lines):
|
||||
fills, errors = collections.defaultdict(list), set()
|
||||
for line in lines:
|
||||
t = line.split()
|
||||
if not t:
|
||||
continue
|
||||
if t[0] == 'table':
|
||||
fills[(t[1], t[2])]
|
||||
elif t[0] == 'error':
|
||||
errors.add((t[1], t[2]))
|
||||
elif t[0] == 'fill':
|
||||
fills[(t[1], t[2])].append((int(t[3]), t[4], t[5], t[6], tuple(sorted(t[7:]))))
|
||||
return fills, errors
|
||||
|
||||
|
||||
def main():
|
||||
resources, tables, seeds = sys.argv[1], sys.argv[2], sys.argv[3:]
|
||||
out = build_dir()/'vanilla.txt'
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
run_oracle(out, tables, seeds)
|
||||
vanilla, errors = parse(out.read_text().splitlines())
|
||||
names = sorted({k[0] for k in vanilla} | {k[0] for k in errors})
|
||||
subprocess.run(['cargo', 'build', '--profile', 'fast', '-q', '-p', 'horizon-world', '--example', 'loot_fill'],
|
||||
check=True, cwd=lab.ROOT)
|
||||
rust_out = subprocess.run([str(lab.cargo_target()/'fast/examples/loot_fill'), resources, ','.join(names), *seeds],
|
||||
check=True, capture_output=True, text=True).stdout
|
||||
rust, _ = parse(rust_out.splitlines())
|
||||
matched = differ = 0
|
||||
for key in sorted(vanilla):
|
||||
if key in errors:
|
||||
continue
|
||||
if vanilla[key] == rust.get(key):
|
||||
matched += 1
|
||||
continue
|
||||
differ += 1
|
||||
if differ <= 20:
|
||||
print('DIFF', key, '\n vanilla', vanilla[key], '\n rust ', rust.get(key))
|
||||
tables = collections.Counter(k[0] for k in vanilla if k not in errors and vanilla[k] != rust.get(k))
|
||||
if tables:
|
||||
print('differing tables:', dict(tables))
|
||||
skipped = sorted({k[0] for k in errors})
|
||||
print(f'{matched} of {matched + differ} fills match; skipped (needs a level): {skipped}')
|
||||
return 1 if differ else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -1,113 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare structure placement (terrain + structure pieces, no placed features)
|
||||
between vanilla and Rust for target chunks.
|
||||
|
||||
usage: compare_structure_blocks.py RESOURCES SEED DIMENSION CX,CZ...
|
||||
Runs VanillaStructurePlacementOracle and the structure_blocks example and
|
||||
reports, per chunk, the blocks and block entities that differ.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
|
||||
def build_dir():
|
||||
return Path(os.environ['HORIZON_ORACLE_BUILD']) if os.environ.get('HORIZON_ORACLE_BUILD') else lab.LOCAL/'structure-placement-oracle'
|
||||
|
||||
|
||||
def run_oracle(out, args):
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructurePlacementOracle.java'
|
||||
classes = build_dir()/'classes'
|
||||
classes.mkdir(parents=True, exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
compiled = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies,
|
||||
'-d', str(classes), str(source)], capture_output=True, text=True)
|
||||
if compiled.returncode:
|
||||
raise SystemExit('javac failed:\n' + compiled.stderr[-3000:])
|
||||
result = subprocess.run(['java', '-Xmx4G', '-cp', str(classes)+os.pathsep+dependencies,
|
||||
'dev.horizonlab.parity.VanillaStructurePlacementOracle', str(out), *args],
|
||||
capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
lines = [line for line in (result.stdout + result.stderr).splitlines() if 'Exception' in line or 'Error' in line or '\tat ' in line]
|
||||
raise SystemExit('oracle failed: ' + ' | '.join(lines[:8]))
|
||||
|
||||
|
||||
def parse(lines):
|
||||
chunks, current = {}, None
|
||||
for line in lines:
|
||||
t = line.split()
|
||||
if not t:
|
||||
continue
|
||||
if t[0] == 'chunk':
|
||||
current = (int(t[1]), int(t[2]))
|
||||
chunks[current] = {'rows': {}, 'be': []}
|
||||
elif t[0] == 'y' and current:
|
||||
chunks[current]['rows'][int(t[1])] = t[2:]
|
||||
elif t[0] == 'be' and current:
|
||||
# Position, loot table and seed; the block entity type follows
|
||||
# from the (separately compared) block state.
|
||||
chunks[current]['be'].append(' '.join(t[1:4] + t[5:]))
|
||||
return chunks
|
||||
|
||||
|
||||
def state_names(resources):
|
||||
names = {}
|
||||
report = lab.LOCAL/'datagen/out/reports/blocks.json'
|
||||
if report.exists():
|
||||
for block, info in json.loads(report.read_text()).items():
|
||||
for state in info['states']:
|
||||
props = ','.join(f'{k}={v}' for k, v in sorted(state.get('properties', {}).items()))
|
||||
names[str(state['id'])] = block + (f'[{props}]' if props else '')
|
||||
return names
|
||||
|
||||
|
||||
def main():
|
||||
resources, seed, dimension, targets = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4:]
|
||||
out = build_dir()/'vanilla.txt'
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
run_oracle(out, [seed, dimension, *targets])
|
||||
vanilla = parse(out.read_text().splitlines())
|
||||
subprocess.run(['cargo', 'build', '--profile', 'fast', '-q', '-p', 'horizon-world', '--example', 'structure_blocks'],
|
||||
check=True, cwd=lab.ROOT)
|
||||
rust_out = subprocess.run([str(lab.cargo_target()/'fast/examples/structure_blocks'), resources, seed, dimension, *targets],
|
||||
check=True, capture_output=True, text=True).stdout
|
||||
(build_dir()/'rust.txt').write_text(rust_out)
|
||||
rust = parse(rust_out.splitlines())
|
||||
names = state_names(resources)
|
||||
failed = 0
|
||||
for key in sorted(vanilla):
|
||||
v, r = vanilla[key], rust.get(key)
|
||||
if r is None:
|
||||
print(key, 'missing from Rust')
|
||||
failed += 1
|
||||
continue
|
||||
diffs = []
|
||||
for y, row in v['rows'].items():
|
||||
other = r['rows'].get(y, [])
|
||||
for i, (a, b) in enumerate(zip(row, other)):
|
||||
if a != b:
|
||||
diffs.append((key[0] * 16 + i % 16, y, key[1] * 16 + i // 16, a, b))
|
||||
total = sum(len(row) for row in v['rows'].values())
|
||||
be_v, be_r = set(v['be']), set(r['be'])
|
||||
status = 'match' if not diffs and be_v == be_r else 'DIFF'
|
||||
print(f'chunk {key}: {status}; {total - len(diffs)} of {total} blocks equal; block entities {len(be_v & be_r)} of {len(be_v)} equal')
|
||||
for x, y, z, a, b in diffs[:12]:
|
||||
print(f' {x} {y} {z} vanilla {names.get(a, a)} rust {names.get(b, b)}')
|
||||
for e in sorted(be_v - be_r)[:6]:
|
||||
print(' only vanilla be', e)
|
||||
for e in sorted(be_r - be_v)[:6]:
|
||||
print(' only rust be', e)
|
||||
failed += status != 'match'
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -1,55 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare Rust structure starts (chunkgen_bench --starts) with the vanilla oracle.
|
||||
|
||||
usage: compare_structure_starts.py VANILLA RUST [--all]
|
||||
Pieces are compared by type, bounding box and (for jigsaw pieces) position,
|
||||
rotation, ground level delta and junction count. Without --all, vanilla
|
||||
starts of structure types Rust does not generate yet are only counted.
|
||||
"""
|
||||
import collections
|
||||
import sys
|
||||
|
||||
|
||||
def load(path):
|
||||
starts = {}
|
||||
current = None
|
||||
for line in open(path):
|
||||
t = line.split()
|
||||
if not t:
|
||||
continue
|
||||
if t[0] == 'start':
|
||||
current = (int(t[1]), int(t[2]), t[3])
|
||||
starts[current] = [' '.join(t[4:])]
|
||||
elif t[0] == 'piece' and current:
|
||||
starts[current].append(' '.join(t[1:14]))
|
||||
return starts
|
||||
|
||||
|
||||
def main():
|
||||
vanilla, rust = load(sys.argv[1]), load(sys.argv[2])
|
||||
generated = {k[2] for k in rust}
|
||||
matched = 0
|
||||
missing = collections.Counter()
|
||||
for key in sorted(vanilla):
|
||||
if key not in rust:
|
||||
missing[key[2]] += 1
|
||||
if key[2] in generated or '--all' in sys.argv:
|
||||
print('missing', key)
|
||||
continue
|
||||
if vanilla[key] == rust[key]:
|
||||
matched += 1
|
||||
continue
|
||||
v, r = vanilla[key], rust[key]
|
||||
print('DIFF', key, 'pieces', len(v) - 1, len(r) - 1)
|
||||
for i, (a, b) in enumerate(zip(v, r)):
|
||||
if a != b:
|
||||
print(' first difference at line', i, '\n vanilla', a, '\n rust ', b)
|
||||
break
|
||||
for key in sorted(set(rust) - set(vanilla)):
|
||||
print('extra', key)
|
||||
print(f'{matched} of {len(vanilla)} vanilla starts match exactly; not generated by Rust:', dict(missing))
|
||||
return 0 if matched == len(rust) == sum(1 for k in vanilla if k[2] in generated) else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -23,6 +23,8 @@ import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import lab
|
||||
|
||||
BX, BZ, SIZE = 144, 144, 96 # south-west corner and size of the platforms (inside the spawn chunks)
|
||||
LAYERS = list(range(100, 245, 16)) # platform y levels: one chunk section each, the last one reaches y = 255
|
||||
UUID_HI = 0x6000
|
||||
@@ -1743,7 +1745,7 @@ LAST = {}
|
||||
def populate(server, Bot, port, protocol, name, problems):
|
||||
"""Build the whole 1.12.2 scene, save it for good and return the (still joined) bot."""
|
||||
harness = sys.modules[Bot.__module__]
|
||||
Player = make_player(Bot, harness.varint, harness.parse_varint, harness.mcstring)
|
||||
Player = make_player(Bot, lab.varint, lab.parse_varint, harness.mcstring)
|
||||
set_protocol(protocol)
|
||||
say = lambda cmds, **kw: batch(server, cmds, problems, **kw)
|
||||
if ERA < 12:
|
||||
@@ -1874,7 +1876,7 @@ def build_flat(h, force=False):
|
||||
return []
|
||||
work = h.LOCAL / 'gen' / (version + '-flat')
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
port = h.free_port()
|
||||
port = lab.free_port()
|
||||
|
||||
class FlatServer(h.Server):
|
||||
def __init__(self, directory): # as Server.__init__, with a flat world
|
||||
@@ -1900,7 +1902,7 @@ def build_flat(h, force=False):
|
||||
# A flat world's spawn is found far away; make it (64, 64), and let a bot visit the scene's area so that its chunks
|
||||
# are loaded (they stay loaded, being within the spawn radius).
|
||||
batch(server, ['setworldspawn 64 4 64'], problems)
|
||||
Player = make_player(h.Bot, h.varint, h.parse_varint, h.mcstring)
|
||||
Player = make_player(h.Bot, lab.varint, lab.parse_varint, h.mcstring)
|
||||
visitor = Player(port, protocol, h.BOT)
|
||||
time.sleep(2)
|
||||
for x, z in ((24, 24), (24, 72), (24, 104), (72, 24), (72, 72), (72, 104), (104, 24), (104, 72), (104, 104), (72, 123), (-8, 63), (32, 103)):
|
||||
|
||||
+16
-51
@@ -23,7 +23,6 @@ import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zipfile
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
@@ -31,6 +30,7 @@ from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import datafix_scene as scene # noqa: E402
|
||||
import datafix_scene_12 as scene12 # noqa: E402
|
||||
import lab # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LOCAL = ROOT / '.local' / 'datafix'
|
||||
@@ -159,12 +159,6 @@ def install_runtime(pin, home):
|
||||
target.symlink_to(to)
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(('127.0.0.1', 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
class Server:
|
||||
def __init__(self, directory, jar, port, packs=(), java='java', props_override=None):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
@@ -230,38 +224,9 @@ def failed(lines):
|
||||
|
||||
# ------------------------------------------------------------------ minimal bot
|
||||
|
||||
def varint(v):
|
||||
out = b''
|
||||
v &= 0xFFFFFFFF
|
||||
while True:
|
||||
b = v & 0x7F
|
||||
v >>= 7
|
||||
out += bytes([b | (0x80 if v else 0)])
|
||||
if not v:
|
||||
return out
|
||||
|
||||
|
||||
def mcstring(s):
|
||||
data = s.encode()
|
||||
return varint(len(data)) + data
|
||||
|
||||
|
||||
def parse_varint(data, pos):
|
||||
value = shift = 0
|
||||
while True:
|
||||
b = data[pos]
|
||||
pos += 1
|
||||
value |= (b & 0x7F) << shift
|
||||
shift += 7
|
||||
if not b & 0x80:
|
||||
return pos, value
|
||||
|
||||
|
||||
def offline_uuid(name):
|
||||
digest = bytearray(hashlib.md5(('OfflinePlayer:' + name).encode()).digest())
|
||||
digest[6] = (digest[6] & 0x0F) | 0x30
|
||||
digest[8] = (digest[8] & 0x3F) | 0x80
|
||||
return uuid.UUID(bytes=bytes(digest))
|
||||
return lab.varint(len(data)) + data
|
||||
|
||||
|
||||
class Bot:
|
||||
@@ -273,21 +238,21 @@ class Bot:
|
||||
self.buffer = b''
|
||||
self.protocol = protocol
|
||||
self.stop = threading.Event()
|
||||
self.send(0, varint(protocol) + mcstring('127.0.0.1') + struct.pack('>H', port) + varint(2))
|
||||
self.send(0, lab.varint(protocol) + mcstring('127.0.0.1') + struct.pack('>H', port) + lab.varint(2))
|
||||
if protocol <= 758: # 1.18.2: the name only
|
||||
self.send(0, mcstring(name))
|
||||
elif protocol == 759: # 1.19: no signature data
|
||||
self.send(0, mcstring(name) + b'\x00')
|
||||
elif protocol == 760: # 1.19.2: no signature data, optional UUID
|
||||
self.send(0, mcstring(name) + b'\x00' + b'\x01' + offline_uuid(name).bytes)
|
||||
self.send(0, mcstring(name) + b'\x00' + b'\x01' + lab.offline_uuid(name).bytes)
|
||||
elif protocol <= 763: # 1.19.3 - 1.20.1: optional UUID
|
||||
self.send(0, mcstring(name) + b'\x01' + offline_uuid(name).bytes)
|
||||
self.send(0, mcstring(name) + b'\x01' + lab.offline_uuid(name).bytes)
|
||||
else:
|
||||
self.send(0, mcstring(name) + offline_uuid(name).bytes)
|
||||
self.send(0, mcstring(name) + lab.offline_uuid(name).bytes)
|
||||
while True:
|
||||
pid, data = self.receive()
|
||||
if pid == 3:
|
||||
self.threshold = parse_varint(data, 0)[1]
|
||||
self.threshold = lab.parse_varint(data, 0)[1]
|
||||
elif pid == 2:
|
||||
break
|
||||
elif pid == 0:
|
||||
@@ -312,15 +277,15 @@ class Bot:
|
||||
elif pid == disconnect:
|
||||
raise RuntimeError(f'disconnected during configuration: {data!r}')
|
||||
elif not old and self.known_packs(data):
|
||||
self.send(7, varint(0)) # claim no packs: the server sends full registries
|
||||
self.send(7, lab.varint(0)) # claim no packs: the server sends full registries
|
||||
|
||||
@staticmethod
|
||||
def known_packs(data):
|
||||
try:
|
||||
pos, count = parse_varint(data, 0)
|
||||
pos, count = lab.parse_varint(data, 0)
|
||||
if count < 1:
|
||||
return False
|
||||
pos, n = parse_varint(data, pos)
|
||||
pos, n = lab.parse_varint(data, pos)
|
||||
return data[pos:pos + n] == b'minecraft'
|
||||
except IndexError:
|
||||
return False
|
||||
@@ -359,18 +324,18 @@ class Bot:
|
||||
return value
|
||||
|
||||
def send(self, packet_id, payload=b''):
|
||||
body = varint(packet_id) + payload
|
||||
body = lab.varint(packet_id) + payload
|
||||
if self.threshold >= 0:
|
||||
body = varint(len(body)) + zlib.compress(body) if len(body) >= self.threshold else varint(0) + body
|
||||
self.sock.sendall(varint(len(body)) + body)
|
||||
body = lab.varint(len(body)) + zlib.compress(body) if len(body) >= self.threshold else lab.varint(0) + body
|
||||
self.sock.sendall(lab.varint(len(body)) + body)
|
||||
|
||||
def receive(self):
|
||||
length = self.read_varint()
|
||||
body = self.read_exact(length)
|
||||
if self.threshold >= 0:
|
||||
pos, size = parse_varint(body, 0)
|
||||
pos, size = lab.parse_varint(body, 0)
|
||||
body = zlib.decompress(body[pos:]) if size else body[pos:]
|
||||
pos, packet_id = parse_varint(body, 0)
|
||||
pos, packet_id = lab.parse_varint(body, 0)
|
||||
return packet_id, body[pos:]
|
||||
|
||||
|
||||
@@ -428,7 +393,7 @@ def build(name, force=False):
|
||||
era = scene.era(data_version)
|
||||
work = LOCAL / 'gen' / name
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
port = free_port()
|
||||
port = lab.free_port()
|
||||
server = Server(work, jar, port, scene.experiments(data_version), java(version), props)
|
||||
problems = []
|
||||
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Copy the pinned version's indexed client assets that are not in the game
|
||||
jar from your own official launcher install: language files and the language
|
||||
list (pack.mcmeta), the unifont glyph archives and their font definitions, and
|
||||
the built-in Programmer Art and High Contrast resource packs. Every object's
|
||||
SHA-1 is verified. Nothing is downloaded; files go to the private client
|
||||
resource directory (or --target) and are never committed."""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
import lab
|
||||
|
||||
|
||||
def wanted(name):
|
||||
return (name == 'pack.mcmeta'
|
||||
or name.startswith('minecraft/lang/')
|
||||
or name.startswith('minecraft/font/')
|
||||
or name.startswith('minecraft/resourcepacks/'))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--target', type=Path, default=lab.RESOURCES,
|
||||
help='prepared resource directory (default: .local/horizon-client/<pinned version>)')
|
||||
parser.add_argument('--minecraft-dir', type=Path,
|
||||
help="official launcher game directory (default: the launcher's own)")
|
||||
args = parser.parse_args()
|
||||
lock, directory = lab.config()
|
||||
manifest = lab.import_manifest(lock, directory, args.minecraft_dir)
|
||||
store, index = lab.launcher_assets(manifest, args.minecraft_dir)
|
||||
target = args.target
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(index, target / 'asset-index.json')
|
||||
objects = lab.json.loads(index.read_text())['objects']
|
||||
selected = {name: info for name, info in objects.items() if wanted(name)}
|
||||
total = 0
|
||||
for name, info in selected.items():
|
||||
source = lab.launcher_object(store, info['hash'])
|
||||
lab.import_copy(source, target / 'assets' / name, info['hash'])
|
||||
total += info['size']
|
||||
print(f'Client assets ready: {len(selected)} files, {total / 1e6:.1f} MB')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+64
-1
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pinned Java Edition import/decompilation. Game files come from the user's own
|
||||
copy (their official launcher install and the server jar they downloaded); all
|
||||
generated files stay in .local/."""
|
||||
generated files stay in .local/. Also the small helpers the harnesses share
|
||||
(free ports, offline UUIDs, VarInts, float bits)."""
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
@@ -12,11 +13,13 @@ import platform
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -61,6 +64,66 @@ def digest(path, algorithm):
|
||||
return hashlib.file_digest(stream, algorithm).hexdigest()
|
||||
|
||||
|
||||
def free_port():
|
||||
"""A free local TCP port, for a server a harness starts."""
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def offline_uuid(name):
|
||||
"""UUIDUtil.createOfflinePlayerUUID: the UUID an offline-mode server gives a player name."""
|
||||
digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest())
|
||||
digest[6] = (digest[6] & 0x0F) | 0x30
|
||||
digest[8] = (digest[8] & 0x3F) | 0x80
|
||||
return uuid.UUID(bytes=bytes(digest))
|
||||
|
||||
|
||||
def varint(value):
|
||||
"""FriendlyByteBuf.writeVarInt: the int's 32 bits, 7 at a time."""
|
||||
out = b""
|
||||
value &= 0xFFFFFFFF
|
||||
while True:
|
||||
b = value & 0x7F
|
||||
value >>= 7
|
||||
out += bytes([b | (0x80 if value else 0)])
|
||||
if not value:
|
||||
return out
|
||||
|
||||
|
||||
def parse_varint(data, pos):
|
||||
"""The VarInt at data[pos]: (the position after it, its unsigned value)."""
|
||||
value = shift = 0
|
||||
while True:
|
||||
b = data[pos]
|
||||
pos += 1
|
||||
value |= (b & 0x7F) << shift
|
||||
shift += 7
|
||||
if not b & 0x80:
|
||||
return pos, value
|
||||
|
||||
|
||||
def fbits(value):
|
||||
"""A float's IEEE 754 bits in hex, as the Java oracles print them."""
|
||||
return struct.pack(">f", value).hex()
|
||||
|
||||
|
||||
def dbits(value):
|
||||
"""A double's IEEE 754 bits in hex, as the Java oracles print them."""
|
||||
return struct.pack(">d", value).hex()
|
||||
|
||||
|
||||
def settled(lines):
|
||||
"""One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint:
|
||||
what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more
|
||||
than once on the way there; the packet by packet order is test_locator_bar_parity's."""
|
||||
def waypoint(line):
|
||||
parts = line.split(" ")
|
||||
return parts[3] if len(parts) > 3 and parts[2] in ("track", "untrack", "update") else None
|
||||
last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)}
|
||||
return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i]
|
||||
|
||||
|
||||
def download(url, destination, checksum, algorithm="sha1"):
|
||||
"""Never promote an unverified or partial download into the artifact cache."""
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
+188
-2
@@ -107,6 +107,11 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
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.
|
||||
- thrown: a splash potion and an eye of ender the host and the guest each throw fly on both
|
||||
sides (#1363, #1391);
|
||||
- sparks: level events' particles on both sides: the host's and the guest's bone meal on wheat
|
||||
(growth sparks), honeycomb on copper and an axe taking the wax off, and a spawner's
|
||||
burst when it spawns (#1395, #1401, #1402);
|
||||
- fireball: a fire charge a dispenser shoots onto stone lights a fire both sides see, and the fire
|
||||
goes out on its own within a minute (it ticks: FireBlock.tick on a floor that doesn't burn)
|
||||
|
||||
@@ -208,7 +213,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', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater']
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater']
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -2612,6 +2617,183 @@ def check_projectiles(host, guest, out):
|
||||
return f'{len(theirs)} identical, fuses (host, guest) {fuses}'
|
||||
|
||||
|
||||
def check_thrown(host, guest, out):
|
||||
spots = apart(host, guest)
|
||||
result = {}
|
||||
for label, player, other in (('host', host, guest), ('guest', guest, host)):
|
||||
x, y, z = spots[label]
|
||||
player('command', command='gamemode survival')
|
||||
for item, kind in (('splash_potion', 'minecraft:splash_potion'), ('ender_eye', 'minecraft:eye_of_ender')):
|
||||
player('command', command=f'item replace entity @s weapon.mainhand with minecraft:{item}')
|
||||
player.wait(10)
|
||||
# Up at 45 degrees, into open sky.
|
||||
player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 11.6:.2f}', f'{z + 10.5:.2f}')
|
||||
player.raw('use-item')
|
||||
seen = {'own': 0, 'other': 0}
|
||||
for _ in range(10):
|
||||
player.wait(2)
|
||||
for side, game in (('own', player), ('other', other)):
|
||||
if any(p['kind'] == kind for p in game('status')['projectiles']):
|
||||
seen[side] += 1
|
||||
if all(seen.values()):
|
||||
break
|
||||
player.shot(out, f'thrown-{label}-{item}')
|
||||
other.shot(out, f'thrown-{label}-{item}-seen')
|
||||
player.wait(100) # it lands or drops
|
||||
result[f'{label} {item}'] = seen
|
||||
for name, seen in result.items():
|
||||
assert all(seen.values()), f'{name}: seen in flight (samples) {result}'
|
||||
return result
|
||||
|
||||
|
||||
def made(game, kind):
|
||||
"""How many `kind` particles `game` has made so far."""
|
||||
return game('status').get('particles', {}).get(kind, 0)
|
||||
|
||||
|
||||
def sparked(player, other, kinds, act, ticks=20):
|
||||
"""The `kinds` particles each side makes while `act` runs and for up to `ticks` after."""
|
||||
before = {(side, k): made(g, k) for side, g in (('own', player), ('other', other)) for k in kinds}
|
||||
act()
|
||||
seen = {}
|
||||
for _ in range(ticks // 2):
|
||||
player.wait(2)
|
||||
seen = {f'{side} {k}': made(g, k) - before[(side, k)]
|
||||
for side, g in (('own', player), ('other', other)) for k in kinds}
|
||||
if all(seen.values()):
|
||||
break
|
||||
return seen
|
||||
|
||||
|
||||
def check_sparks(host, guest, out):
|
||||
spots = apart(host, guest)
|
||||
result = {}
|
||||
for label, player, other in (('host', host, guest), ('guest', guest, host)):
|
||||
x, y, z = spots[label]
|
||||
at = (x, y, z + 2)
|
||||
player('command', command='gamemode survival')
|
||||
try:
|
||||
player('command', command=f'setblock {at[0]} {at[1] - 1} {at[2]} minecraft:farmland')
|
||||
player('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:wheat')
|
||||
player('command', command='item replace entity @s weapon.mainhand with minecraft:bone_meal 8')
|
||||
player.wait(10)
|
||||
|
||||
def click(height):
|
||||
player.raw('look-at', f'{at[0] + 0.5:.2f}', f'{at[1] + height:.2f}', f'{at[2] + 0.5:.2f}')
|
||||
player.raw('mouse', 'right', 'click')
|
||||
result[f'{label} bone meal'] = sparked(player, other, ['happy_villager'], lambda: click(0.1))
|
||||
player('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:copper_block')
|
||||
player('command', command='item replace entity @s weapon.mainhand with minecraft:honeycomb')
|
||||
player.wait(10)
|
||||
result[f'{label} wax'] = sparked(player, other, ['wax_on'], lambda: click(0.5))
|
||||
player('command', command='item replace entity @s weapon.mainhand with minecraft:iron_axe')
|
||||
player.wait(10)
|
||||
result[f'{label} wax off'] = sparked(player, other, ['wax_off'], lambda: click(0.5))
|
||||
block = player.raw('block', *at).get('block', '')
|
||||
result[f'{label} copper'] = block
|
||||
finally:
|
||||
player('command', command=f'fill {at[0]} {at[1] - 1} {at[2]} {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
player('command', command=f'setblock {at[0]} {at[1] - 1} {at[2]} minecraft:stone')
|
||||
player('command', command='clear @s')
|
||||
# A spawner beside the host, at night: its burst when the zombie comes.
|
||||
x, y, z = spots['host']
|
||||
host('command', command='time set midnight')
|
||||
try:
|
||||
host('command', command=f'setblock {x} {y} {z + 3} minecraft:spawner{{Delay:20s,SpawnCount:1s,'
|
||||
'SpawnData:{entity:{id:"minecraft:zombie",NoAI:1b}}}')
|
||||
result['spawner'] = sparked(host, guest, ['flame', 'smoke'], lambda: None, ticks=200)
|
||||
finally:
|
||||
host('command', command=f'setblock {x} {y} {z + 3} minecraft:air')
|
||||
host('command', command=f'kill @e[type=minecraft:zombie,x={x},y={y},z={z},distance=..12]')
|
||||
host('command', command='time set day')
|
||||
wrong = {k: v for k, v in result.items() if isinstance(v, dict) and not all(n > 0 for n in v.values())}
|
||||
assert not wrong, f'no particles: {wrong}\n{result}'
|
||||
return result
|
||||
|
||||
|
||||
def hearts(game):
|
||||
"""The player's maximum and current health as its own client holds them."""
|
||||
p = game('status')['player']
|
||||
return p.get('max_health'), round(p['health'], 1)
|
||||
|
||||
|
||||
def check_hud(host, guest, out):
|
||||
result = {}
|
||||
for label, player in (('host', host), ('guest', guest)):
|
||||
player('command', command='gamemode survival')
|
||||
try:
|
||||
for maximum in (40, 10):
|
||||
player('command', command=f'attribute @s minecraft:max_health base set {maximum}')
|
||||
player.wait(10)
|
||||
player('command', command='effect give @s minecraft:instant_health 1 10')
|
||||
seen = None
|
||||
for _ in range(15):
|
||||
player.wait(2)
|
||||
seen = hearts(player)
|
||||
if seen == (maximum, maximum):
|
||||
break
|
||||
result[f'{label} {maximum}'] = seen
|
||||
player.shot(out, f'hearts-{label}-{maximum}')
|
||||
finally:
|
||||
player('command', command='attribute @s minecraft:max_health base reset')
|
||||
player('command', command='effect give @s minecraft:instant_health 1 10')
|
||||
# BossBarCommands' new bar starts visible (ServerBossEvent's constructor).
|
||||
host('command', command='bossbar add lan_e2e:bar "LAN bar"')
|
||||
try:
|
||||
host('command', command='bossbar get lan_e2e:bar visible')
|
||||
host.wait(5)
|
||||
result['bar'] = [line for line in host.raw('messages', 5)['chat'] if 'lan_e2e:bar' in line or 'LAN bar' in line]
|
||||
finally:
|
||||
host('command', command='bossbar remove lan_e2e:bar')
|
||||
wrong = {k: v for k, v in result.items() if k != 'bar' and v != (int(k.split()[1]),) * 2}
|
||||
assert not wrong, f'hearts: {wrong}\n{result}'
|
||||
assert any('currently visible' in line for line in result['bar']), f'bar: {result["bar"]}'
|
||||
return result
|
||||
|
||||
|
||||
def sidebars(host, guest, want, ticks=40):
|
||||
"""Each side's sidebar (objective and scores) once both show `want` (host, guest), or after `ticks`."""
|
||||
seen = None
|
||||
for _ in range(ticks // 2):
|
||||
host.wait(2)
|
||||
seen = tuple(g('status').get('sidebar') for g in (host, guest))
|
||||
got = tuple(s and (s['objective'], s['scores']) for s in seen)
|
||||
if got == want:
|
||||
break
|
||||
return seen
|
||||
|
||||
|
||||
def check_sidebar(host, guest, out):
|
||||
result = {}
|
||||
run = lambda *cmds: [host('command', command=c) for c in cmds]
|
||||
try:
|
||||
run('scoreboard objectives add audit dummy {"text":"Audit board","color":"aqua"}',
|
||||
'scoreboard players set Alpha audit 7', 'scoreboard players set Beta audit 3',
|
||||
'scoreboard objectives setdisplay sidebar audit')
|
||||
both = ('audit', {'Alpha': 7, 'Beta': 3})
|
||||
result['shown'] = sidebars(host, guest, (both, both))
|
||||
host.shot(out, 'sidebar')
|
||||
guest.shot(out, 'sidebar')
|
||||
run('scoreboard players set Alpha audit 12', 'scoreboard players reset Beta audit')
|
||||
both = ('audit', {'Alpha': 12})
|
||||
result['changed'] = sidebars(host, guest, (both, both))
|
||||
# The guest's team's sidebar replaces the sidebar for the guest only.
|
||||
run('team add red', 'team modify red color red', f'team join red {GUEST_NAME}',
|
||||
'scoreboard objectives add reds dummy', f'scoreboard players set {GUEST_NAME} reds 5',
|
||||
'scoreboard objectives setdisplay sidebar.team.red reds')
|
||||
result['team'] = sidebars(host, guest, (both, ('reds', {GUEST_NAME: 5})))
|
||||
run('scoreboard objectives remove reds', 'scoreboard objectives setdisplay sidebar')
|
||||
result['cleared'] = sidebars(host, guest, (None, None))
|
||||
finally:
|
||||
run('scoreboard objectives remove audit', 'scoreboard objectives remove reds', 'team remove red')
|
||||
want = {'shown': (('audit', {'Alpha': 7, 'Beta': 3}),) * 2, 'changed': (('audit', {'Alpha': 12}),) * 2,
|
||||
'team': (('audit', {'Alpha': 12}), ('reds', {GUEST_NAME: 5})), 'cleared': (None, None)}
|
||||
got = {k: tuple(s and (s['objective'], s['scores']) for s in v) for k, v in result.items()}
|
||||
wrong = {k: v for k, v in got.items() if v != want[k]}
|
||||
assert not wrong, f'sidebars: {wrong}\n{result}'
|
||||
return result
|
||||
|
||||
|
||||
def check_blast(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
@@ -3945,7 +4127,11 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour,
|
||||
'lava': check_lava, 'levels': check_levels, 'drops': check_drops,
|
||||
'underwater': check_underwater,
|
||||
'looks': check_looks,
|
||||
'leads': check_leads}
|
||||
'leads': check_leads,
|
||||
'thrown': check_thrown,
|
||||
'sparks': check_sparks,
|
||||
'hud': check_hud,
|
||||
'sidebar': check_sidebar}
|
||||
|
||||
|
||||
def run(ctl, out, resources, checks):
|
||||
|
||||
+86
-21
@@ -27,9 +27,10 @@ Harness probes build into .local/parity-target with release optimisations but
|
||||
without LTO and with 16 codegen units (`PROFILE` below), which builds in
|
||||
seconds instead of minutes. Rust does not let those settings change results:
|
||||
there is no fast-math, and overflow checks stay as in release. Probes built in
|
||||
the dev profile are optimised too, keeping their overflow checks. Probes the
|
||||
recorded harnesses need are built in one Cargo run before the harnesses start,
|
||||
so parallel harnesses don't queue on Cargo's lock.
|
||||
the dev profile are optimised too, keeping their overflow checks. The probes the
|
||||
selected harnesses built last time are built before they start, so parallel
|
||||
harnesses don't queue on Cargo's lock, with each harness's own package and
|
||||
feature flags so that its Cargo run then finds them fresh.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -210,18 +211,42 @@ def artifact_path(kind, name, profile):
|
||||
return TARGET / directory / ("examples" if kind == "example" else "") / name
|
||||
|
||||
|
||||
SELECTION_FLAGS = {"-p", "--package", "-F", "--features"} # followed by a value
|
||||
SELECTION_SWITCHES = {"--workspace", "--all", "--all-features", "--no-default-features"}
|
||||
|
||||
|
||||
def artifacts_of(arguments):
|
||||
"""The [kind, name, profile] targets a cargo build/run command line names."""
|
||||
"""The [kind, name, profile, selection, examples] targets a cargo build/run command line names.
|
||||
|
||||
kind is example, bin, or examples/bins (every one, name ""). selection is the command's package and feature
|
||||
flags, and examples whether the command builds any example (which turns on dev-dependencies): together they
|
||||
decide how Cargo unifies features, so the probe prebuild must repeat them exactly. A `--workspace` build of
|
||||
the same example gives its dependencies other features, and the harness's own `-p` build then compiles
|
||||
everything again."""
|
||||
arguments = arguments[:arguments.index("--")] if "--" in arguments else arguments
|
||||
profile = "release" if "--release" in arguments else "dev"
|
||||
if "--profile" in arguments:
|
||||
profile = arguments[arguments.index("--profile") + 1]
|
||||
selection = []
|
||||
found = []
|
||||
for flag, kind in (("--example", "example"), ("--bin", "bin")):
|
||||
for index, argument in enumerate(arguments[:-1]):
|
||||
if argument == flag:
|
||||
found.append([kind, arguments[index + 1], profile])
|
||||
return found
|
||||
index = 1
|
||||
while index < len(arguments):
|
||||
argument = arguments[index]
|
||||
flag, _, value = argument.partition("=")
|
||||
if flag in SELECTION_FLAGS | {"--profile", "--example", "--bin"} and not value and index + 1 < len(arguments):
|
||||
value = arguments[index + 1]
|
||||
index += 1
|
||||
if flag == "--profile":
|
||||
profile = value
|
||||
elif flag in SELECTION_FLAGS:
|
||||
selection += ["-p" if flag == "--package" else "--features" if flag == "-F" else flag, value]
|
||||
elif flag in SELECTION_SWITCHES:
|
||||
selection.append("--workspace" if flag == "--all" else flag)
|
||||
elif flag in ("--example", "--bin"):
|
||||
found.append([flag[2:], value])
|
||||
elif flag in ("--examples", "--bins"):
|
||||
found.append([flag[2:], ""])
|
||||
index += 1
|
||||
examples = any(kind in ("example", "examples") for kind, _ in found)
|
||||
return [[kind, name, profile, selection, examples] for kind, name in found]
|
||||
|
||||
|
||||
RUST_PATH = re.compile(r"(?<![\w:])((?:crate|self|super)(?:::super)*|[a-z_][a-z0-9_]*)::((?:[A-Za-z_]\w*::)*[A-Za-z_]\w*)")
|
||||
@@ -457,8 +482,9 @@ def dependencies(trace, scope=None):
|
||||
for argument in arguments[1:]:
|
||||
if isinstance(argument, str) and os.path.isfile(argument):
|
||||
found.add(argument)
|
||||
for kind, name, profile in artifacts:
|
||||
found.update(dep_info(artifact_path(kind, name, profile)))
|
||||
for kind, name, profile, *_ in artifacts:
|
||||
if name:
|
||||
found.update(dep_info(artifact_path(kind, name, profile)))
|
||||
kept = set()
|
||||
for path in found:
|
||||
path = Path(path) if os.path.isabs(path) else ROOT / path
|
||||
@@ -515,15 +541,49 @@ def default_build_jobs():
|
||||
return jobs
|
||||
|
||||
|
||||
def target_packages():
|
||||
"""{(kind, name): package} for the workspace's examples and binaries."""
|
||||
result = subprocess.run(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=ROOT, capture_output=True,
|
||||
text=True)
|
||||
if result.returncode:
|
||||
return {}
|
||||
return {(kind, target["name"]): package["name"] for package in json.loads(result.stdout)["packages"]
|
||||
for target in package["targets"] for kind in target["kind"] if kind in ("example", "bin")}
|
||||
|
||||
|
||||
def prebuild_commands(artifacts, packages=None):
|
||||
"""The Cargo runs that build the recorded probes exactly as their harnesses do: one per profile, package and
|
||||
feature selection, and whether examples are among the command's targets (see artifacts_of).
|
||||
|
||||
packages: target_packages(). Records of targets that no longer exist (a probe renamed or deleted since a harness
|
||||
ran it) are left out, since one unknown target fails its whole Cargo run. A [kind, name, profile] record from
|
||||
before selections were kept is taken as built with `-p` and its own crate, as nearly every harness does; the
|
||||
harness's next run records the real one."""
|
||||
groups = {}
|
||||
for artifact in artifacts:
|
||||
if packages and artifact[1] and tuple(artifact[:2]) not in packages:
|
||||
continue
|
||||
if len(artifact) == 3 and (packages or {}).get(tuple(artifact[:2])):
|
||||
kind, name, profile = artifact
|
||||
artifact = [kind, name, profile, ["-p", packages[(kind, name)]], kind == "example"]
|
||||
if len(artifact) < 5:
|
||||
continue
|
||||
kind, name, profile, selection, examples = artifact
|
||||
targets = groups.setdefault((profile, tuple(selection), examples), [])
|
||||
target = [f"--{kind}", name] if name else [f"--{kind}"]
|
||||
if target not in targets:
|
||||
targets.append(target)
|
||||
return [["cargo", "build", "--locked", "--profile", profile, *selection, *(part for target in targets for part in target)]
|
||||
for (profile, selection, _), targets in sorted(groups.items())]
|
||||
|
||||
|
||||
def prebuild(artifacts, jobs):
|
||||
"""Build every recorded probe in one Cargo run so harnesses don't serialise on its lock."""
|
||||
"""Build the recorded probes before the harnesses start, so they don't serialise on Cargo's lock."""
|
||||
environment = run_environment()
|
||||
environment["CARGO_BUILD_JOBS"] = str(jobs)
|
||||
errors = ""
|
||||
for profile in sorted({profile for _, _, profile in artifacts}):
|
||||
command = ["cargo", "build", "--locked", "--workspace", "--profile", profile]
|
||||
for kind, name, _ in (artifact for artifact in artifacts if artifact[2] == profile):
|
||||
command += ["--examples", "--bins"] if kind == "all" else [f"--{kind}", name]
|
||||
packages = target_packages()
|
||||
for command in prebuild_commands(artifacts, packages):
|
||||
result = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
errors += result.stderr
|
||||
@@ -1217,10 +1277,15 @@ def main():
|
||||
finished_run([])
|
||||
return 0
|
||||
|
||||
# Harnesses that never ran here have no recorded probes: build them all.
|
||||
artifacts = [["all", "", "release"]] if any("artifacts" not in records.get(name, {}) for name in selected) else []
|
||||
# The probes the selected harnesses built last time, here or (for those that never ran here) in another
|
||||
# worktree. A harness with no record builds its own: building every probe for it would be ~275 binaries.
|
||||
artifacts = []
|
||||
for name in selected:
|
||||
for artifact in records.get(name, {}).get("artifacts", []):
|
||||
record = records.get(name)
|
||||
if not record or "artifacts" not in record:
|
||||
template = SHARED / "dependencies" / f"{name}.json"
|
||||
record = json.loads(template.read_text(encoding="utf-8")) if template.exists() else {}
|
||||
for artifact in record.get("artifacts", []):
|
||||
if artifact not in artifacts:
|
||||
artifacts.append(artifact)
|
||||
config = host_config()
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""A sharded harness's share of its cases.
|
||||
|
||||
A harness that declares PARITY_SHARDS = n runs as n entries in tools/parity.py, which sets PARITY_SHARD=i/n for
|
||||
each. Outside the runner PARITY_SHARD is unset and a harness runs everything. Kept out of lab.py: every harness
|
||||
imports lab.py, so a change there reruns them all.
|
||||
"""
|
||||
import os
|
||||
|
||||
|
||||
def shard(items):
|
||||
"""Every n-th item from the i-th, or all of them outside the runner."""
|
||||
spec = os.environ.get("PARITY_SHARD")
|
||||
if not spec:
|
||||
return items
|
||||
index, count = map(int, spec.split("/"))
|
||||
return items[index - 1::count]
|
||||
|
||||
|
||||
def label():
|
||||
"""A directory name for this share ("2-4", or "all"): shards run at once and must not share outputs."""
|
||||
return os.environ.get("PARITY_SHARD", "all").replace("/", "-")
|
||||
@@ -1,57 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure the resource-dependent Behaviours::load portion of client startup.
|
||||
|
||||
Build the behaviour_load_profile example in the checkout to be measured first:
|
||||
cargo build --release -p horizon-world --example behaviour_load_profile
|
||||
|
||||
Run the profiler from the repository root with the matching example binary.
|
||||
This measures behaviour loading, not time to first rendered frame. With
|
||||
--cache-dir, the example reads and refreshes the resolved snapshot there, as the
|
||||
client does with its .horizon-cache folder: the first load of a run builds it
|
||||
when it is missing, the next loads restore it.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--binary", type=Path, default=Path("target/release/examples/behaviour_load_profile"))
|
||||
parser.add_argument("--resources", type=Path, default=Path(".local/horizon-client/26.3"))
|
||||
parser.add_argument("--cache-dir", type=Path,
|
||||
help="snapshot folder (default: no snapshot, every load is uncached)")
|
||||
parser.add_argument("--repeats", type=int, default=5)
|
||||
parser.add_argument("--output", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.repeats < 1:
|
||||
parser.error("--repeats must be at least one")
|
||||
samples = []
|
||||
for _ in range(args.repeats):
|
||||
command = [str(args.binary.resolve()), str(args.resources.resolve())]
|
||||
if args.cache_dir:
|
||||
command.append(str(args.cache_dir.resolve()))
|
||||
run = subprocess.run(command, text=True, capture_output=True, check=True)
|
||||
values = {key: float(value) for key, value in
|
||||
re.findall(r"^(registry_ms|behaviours_[0-2]_ms)=([\d.]+)$", run.stderr, re.M)}
|
||||
if len(values) != 4:
|
||||
raise RuntimeError(f"incomplete profile output: {run.stderr}")
|
||||
samples.append(values)
|
||||
summary = {key: {"median_ms": round(statistics.median(row[key] for row in samples), 3),
|
||||
"samples_ms": [row[key] for row in samples]}
|
||||
for key in samples[0]}
|
||||
result = {"scope": "behaviour loader only; not full client startup",
|
||||
"binary": str(args.binary), "resources": str(args.resources), "repeats": args.repeats,
|
||||
"cache_dir": str(args.cache_dir) if args.cache_dir else None,
|
||||
"metrics": summary}
|
||||
print(json.dumps(result, indent=2))
|
||||
if args.output:
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(result, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,220 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Promotes Horizon's beta game releases to stable once a day (.github/workflows/promote.yml, docs/release-flow.md).
|
||||
|
||||
python3 tools/release_channels.py promote # the newest beta that is due, if any
|
||||
python3 tools/release_channels.py promote --tag v2026.10.19.03 # that beta now (by hand)
|
||||
python3 tools/release_channels.py promote --tag v2026.10.19.03 --force # even if blocked or untested
|
||||
python3 tools/release_channels.py promote --dry-run # say what would happen, change nothing
|
||||
|
||||
Every game release goes out as a beta (a GitHub pre-release): launchers on the Alpha channel install it at once.
|
||||
Stable moves once a day, at PROMOTE_AT (20:00 UTC). A beta is due for stable when:
|
||||
- it is newer than the stable release (GitHub's "latest", which launchers and servers install by default),
|
||||
- it had been out PROMOTE_AFTER (6 hours) at the day's promotion time, so every run until the next one picks the
|
||||
same beta and a run GitHub starts late (or a second try) never promotes twice; by hand (--tag) skips the wait,
|
||||
- its release smoke test passed: release.yml attaches smoke-test.json only after the Mac mini ran the game,
|
||||
- and no issue labelled release-blocker covers it. An open blocker holds every beta; one closed as completed keeps
|
||||
holding the betas published before it closed (they still have the bug); one closed as not planned holds nothing.
|
||||
Only people who can triage the repository can add the label, and the issue's text is never read: whoever wrote
|
||||
the issue could edit it afterwards, so it can't decide which betas go out.
|
||||
|
||||
The newest due beta is promoted: marked stable and latest, with notes covering everything since the previous
|
||||
stable release (tools/release_train.py notes --stable). Older betas stay betas: the stable one contains them.
|
||||
Nothing older than the current stable release is ever promoted, even with --force: GitHub's "latest" is what
|
||||
horizon-server update and install.sh download, and it only moves forward.
|
||||
|
||||
When the oldest beta newer than the stable release has waited STALL_AFTER (30 hours: past one daily promotion it
|
||||
was due for, so a normal day never trips it), promotion has stalled
|
||||
(blocked, smoke tests not running, the schedule off): an issue says so, and is closed once a beta is promoted.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tools.release_train import is_game_tag, tag_key # noqa: E402 (vYYYY.MM.DD[.N] and v0.2.0: docs/versioning.md)
|
||||
|
||||
REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon")
|
||||
PROMOTE_AFTER = dt.timedelta(hours=6)
|
||||
# The daily promotion (21:00 in Paris in winter time, 22:00 in summer); promote.yml's schedule runs just after it.
|
||||
PROMOTE_AT = dt.time(20, 0)
|
||||
SMOKE_ASSET = "smoke-test.json"
|
||||
BLOCKER = "release-blocker"
|
||||
STALL_AFTER = dt.timedelta(hours=30)
|
||||
STALLED = "Promotion to stable has stalled"
|
||||
|
||||
|
||||
def parse_time(text):
|
||||
return dt.datetime.fromisoformat(text.replace("Z", "+00:00")) if text else None
|
||||
|
||||
|
||||
def covers(blocker, release):
|
||||
"""Whether a release-blocker issue holds this beta back. Only its state and dates count, never its text."""
|
||||
if blocker.get("state") != "closed":
|
||||
return True
|
||||
closed = parse_time(blocker.get("closed_at"))
|
||||
return blocker.get("state_reason") == "completed" and bool(closed) and parse_time(release["published_at"]) < closed
|
||||
|
||||
|
||||
def promotion_time(now):
|
||||
"""The last daily promotion time (PROMOTE_AT, UTC) at or before now."""
|
||||
now = now.astimezone(dt.timezone.utc)
|
||||
at = dt.datetime.combine(now.date(), PROMOTE_AT, dt.timezone.utc)
|
||||
return at if at <= now else at - dt.timedelta(days=1)
|
||||
|
||||
|
||||
def stable(releases):
|
||||
"""The newest stable (non pre-release) game release."""
|
||||
stables = [r for r in releases if not r["prerelease"]]
|
||||
return max(stables, key=lambda r: tag_key(r["tag_name"]), default=None)
|
||||
|
||||
|
||||
def reasons_against(release, current, blockers, now, by_hand=False):
|
||||
"""Why this beta can't become stable now: an empty list when it can."""
|
||||
reasons = []
|
||||
if not release["prerelease"]:
|
||||
reasons.append("it is already stable")
|
||||
if current and tag_key(release["tag_name"]) <= tag_key(current["tag_name"]):
|
||||
reasons.append(f"it is not newer than the stable {current['tag_name']}")
|
||||
ready = parse_time(release["published_at"]) + PROMOTE_AFTER
|
||||
if not by_hand and ready > promotion_time(now):
|
||||
due = promotion_time(ready)
|
||||
due += dt.timedelta(days=1 if due < ready else 0)
|
||||
reasons.append(f"it had not been out {PROMOTE_AFTER.seconds // 3600} h at a daily promotion yet: "
|
||||
f"the one at {due:%Y-%m-%d %H:%M} UTC takes it")
|
||||
if not any(asset["name"] == SMOKE_ASSET for asset in release.get("assets", [])):
|
||||
reasons.append(f"it has no {SMOKE_ASSET}: the release smoke test did not run")
|
||||
for blocker in blockers:
|
||||
if covers(blocker, release):
|
||||
reasons.append(f"release-blocker #{blocker['number']}")
|
||||
return reasons
|
||||
|
||||
|
||||
def choose(releases, blockers, now, tag=None, force=False):
|
||||
"""(the beta to promote or None, a line saying why) for the game releases `releases`."""
|
||||
games = [r for r in releases if not r["draft"] and is_game_tag(r["tag_name"])]
|
||||
current = stable(games)
|
||||
if tag:
|
||||
release = next((r for r in games if r["tag_name"] == tag), None)
|
||||
if not release:
|
||||
return None, f"no published game release is tagged {tag}"
|
||||
reasons = reasons_against(release, current, blockers, now, by_hand=True)
|
||||
if force:
|
||||
# Even forced, "latest" only moves forward: horizon-server update and install.sh follow it.
|
||||
reasons = [r for r in reasons if r == "it is already stable" or r.startswith("it is not newer")]
|
||||
if reasons:
|
||||
return None, f"{tag} stays a beta: " + "; ".join(reasons)
|
||||
return release, f"{tag} promoted by hand" + (" with force" if force else "")
|
||||
betas = sorted((r for r in games if r["prerelease"]), key=lambda r: tag_key(r["tag_name"]), reverse=True)
|
||||
held = []
|
||||
for release in betas:
|
||||
reasons = reasons_against(release, current, blockers, now)
|
||||
if not reasons:
|
||||
return release, f"{release['tag_name']} had been out {PROMOTE_AFTER.seconds // 3600} h at the daily promotion, " \
|
||||
"passed its smoke test and no release-blocker covers it"
|
||||
held.append(f"{release['tag_name']}: " + "; ".join(reasons))
|
||||
return None, "no beta is due" + (" (" + " / ".join(held[:3]) + ")" if held else "")
|
||||
|
||||
|
||||
def stalled(releases, now):
|
||||
"""(the oldest beta newer than the stable release, how long it has waited) once that is STALL_AFTER, else None."""
|
||||
games = [r for r in releases if not r["draft"] and is_game_tag(r["tag_name"])]
|
||||
current = stable(games)
|
||||
waiting = [r for r in games if r["prerelease"] and (not current or tag_key(r["tag_name"]) > tag_key(current["tag_name"]))]
|
||||
if not waiting:
|
||||
return None
|
||||
oldest = min(waiting, key=lambda r: parse_time(r["published_at"]))
|
||||
age = now - parse_time(oldest["published_at"])
|
||||
return (oldest, age) if age >= STALL_AFTER else None
|
||||
|
||||
|
||||
def stall_issue(releases, stall, reason):
|
||||
"""The title and body of the issue saying promotion has stalled."""
|
||||
oldest, age = stall
|
||||
current = stable([r for r in releases if not r["draft"] and is_game_tag(r["tag_name"])])
|
||||
hours = int(age.total_seconds() // 3600)
|
||||
body = (f"Opened by .github/workflows/promote.yml, not by a person.\n\n"
|
||||
f"No beta has become stable for {hours} hours: {oldest['tag_name']} has waited since "
|
||||
f"{oldest['published_at']}, and launchers, servers and install.sh still get "
|
||||
f"{current['tag_name'] if current else 'no stable release'}.\n\n"
|
||||
f"The last check said: {reason}\n\n"
|
||||
"Usual causes: an open `release-blocker` issue (it holds every beta until it is closed), the Mac mini's "
|
||||
"release smoke test not running (no smoke-test.json on the betas), or the promote workflow disabled. "
|
||||
"To promote a beta by hand: `gh workflow run promote -f tag=<tag>` (add `-f force=true` to skip the "
|
||||
"smoke test and blockers). This issue closes itself once a beta is promoted.")
|
||||
return f"{STALLED}: {oldest['tag_name']} has waited {hours} h", body
|
||||
|
||||
|
||||
def gh(*arguments, capture=True):
|
||||
result = subprocess.run(["gh", *arguments], cwd=ROOT, capture_output=capture, text=True)
|
||||
if result.returncode:
|
||||
raise SystemExit(f"gh {' '.join(arguments)}: {(result.stderr or '').strip()}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def gh_pages(path):
|
||||
return [item for page in json.loads(gh("api", path, "--paginate", "--slurp") or "[]") for item in page]
|
||||
|
||||
|
||||
def promote(release):
|
||||
"""Marks the beta stable and latest, with notes covering everything since the previous stable release."""
|
||||
tag = release["tag_name"]
|
||||
with tempfile.TemporaryDirectory() as out:
|
||||
subprocess.run([sys.executable, str(ROOT / "tools" / "release_train.py"), "notes", "--kind", "game", "--tag", tag,
|
||||
"--head", tag, "--stable", "--out", out], cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
|
||||
title = (Path(out) / "title.txt").read_text().strip()
|
||||
gh("release", "edit", tag, "--repo", REPO, "--prerelease=false", "--latest", "--title", title,
|
||||
"--notes-file", str(Path(out) / "body.md"))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("command", choices=["promote"])
|
||||
parser.add_argument("--tag", help="promote this beta now (by hand: no wait for the daily promotion)")
|
||||
parser.add_argument("--force", action="store_true", help="with --tag: even without a smoke test or with a blocker")
|
||||
parser.add_argument("--dry-run", action="store_true", help="say what would be promoted, change nothing")
|
||||
parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)")
|
||||
args = parser.parse_args()
|
||||
if args.force and not args.tag:
|
||||
parser.error("--force needs --tag: only a named beta is forced")
|
||||
now = dt.datetime.fromisoformat(args.now) if args.now else dt.datetime.now(dt.timezone.utc)
|
||||
now = now if now.tzinfo else now.replace(tzinfo=dt.timezone.utc)
|
||||
releases = gh_pages(f"repos/{REPO}/releases?per_page=100")
|
||||
blockers = [issue for issue in gh_pages(f"repos/{REPO}/issues?labels={BLOCKER}&state=all&per_page=100")
|
||||
if "pull_request" not in issue]
|
||||
release, reason = choose(releases, blockers, now, args.tag, args.force)
|
||||
if release and not args.dry_run:
|
||||
promote(release)
|
||||
line = ("Would promote: " if release and args.dry_run else "") + reason
|
||||
print(line)
|
||||
if os.environ.get("GITHUB_STEP_SUMMARY"):
|
||||
with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary:
|
||||
summary.write(f"### {line}\n")
|
||||
report_stall(releases, release, reason, now, args.dry_run)
|
||||
return 1 if args.tag and not release else 0
|
||||
|
||||
|
||||
def report_stall(releases, promoted, reason, now, dry_run):
|
||||
"""Opens the stalled-promotion issue when one is due and none is open; closes it after a promotion."""
|
||||
open_issues = [issue for issue in gh_pages(f"repos/{REPO}/issues?state=open&per_page=100")
|
||||
if "pull_request" not in issue and issue["title"].startswith(STALLED)]
|
||||
stall = None if promoted else stalled(releases, now)
|
||||
if stall and not open_issues:
|
||||
title, body = stall_issue(releases, stall, reason)
|
||||
print(("Would open: " if dry_run else "Opening: ") + title)
|
||||
if not dry_run:
|
||||
gh("issue", "create", "--repo", REPO, "--title", title, "--body", body)
|
||||
if promoted and not dry_run:
|
||||
for issue in open_issues:
|
||||
gh("issue", "close", str(issue["number"]), "--repo", REPO, "--comment",
|
||||
f"{promoted['tag_name']} is stable now (promote.yml).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+71
-28
@@ -4,13 +4,14 @@
|
||||
python3 tools/release_train.py decide --kind game [--head SHA] [--force]
|
||||
python3 tools/release_train.py decide --kind launcher
|
||||
python3 tools/release_train.py notes --kind game --tag v2026.10.15 --out dist/notes
|
||||
python3 tools/release_train.py notes --kind game --tag v2026.10.15 --head v2026.10.15 --stable # at promotion
|
||||
python3 tools/release_train.py gate --kind game --smoke dist/smoke-test.json [--blockers] # before publishing
|
||||
|
||||
A kind releases when a pull request merged into main since its last published release changed one of its
|
||||
player-facing paths (GAME_PATHS, LAUNCHER_PATHS) and the newest of them merged at least DEBOUNCE ago (a burst
|
||||
of merges becomes one release), or the oldest at least MAX_WAIT ago (merges that never pause still ship), or when one
|
||||
of those pull requests is labelled release-now. Pull requests labelled skip-release (work players don't see) don't count
|
||||
towards a release and aren't listed in the notes. RELEASES_PAUSED=1 (a repository variable) stops automatic releases.
|
||||
towards a release and aren't listed in the notes. RELEASES_PAUSED=1 (a repository variable) stops automatic releases,
|
||||
and an open issue labelled release-blocker stops game releases, even forced ones, until it is closed.
|
||||
|
||||
Tags (docs/versioning.md): with a release line in .github/release-line.txt (MAJOR.MINOR, e.g. 0.2), game releases
|
||||
are vMAJOR.MINOR.PATCH and launcher releases launcher@MAJOR.MINOR.PATCH, each the patch after the last tag of its kind
|
||||
@@ -19,9 +20,11 @@ file, the tags from before 0.2: vYYYY.MM.DD, then .01, .02 the same UTC day, and
|
||||
the last launcher tag or the next minor when a merged pull request is labelled feature. Every 0.2 tag is newer than
|
||||
every tag from before (tag_key). Notes:
|
||||
"### New" lists the pull requests labelled feature, "### Fixed" the others, "### Known issues" the bullets of
|
||||
docs/known-issues.md. Game releases go out as betas (GitHub pre-releases) and tools/release_channels.py promotes
|
||||
them to stable; a beta's notes cover what changed since the release before it (beta or stable), a promoted
|
||||
release's (--stable) everything since the last stable one. See docs/release-flow.md.
|
||||
docs/known-issues.md. Every release is published as the release, GitHub's latest, which launchers, servers and
|
||||
install.sh take at once; one channel, no promotion. A game release is published only after `gate`: its smoke test
|
||||
passed and no release-blocker is open. Notes cover everything since the last published release; the game
|
||||
pre-releases of the old Alpha channel (v0.2.1 on) don't count, so the first release after them lists all of
|
||||
it since v0.2.0. See docs/release-flow.md.
|
||||
|
||||
Prints the decision as JSON and writes it to $GITHUB_OUTPUT when set. Needs git history and the gh CLI.
|
||||
"""
|
||||
@@ -37,7 +40,7 @@ import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon")
|
||||
# Alpha builds ship constantly: a merge starts a release within minutes, once its wave of merges has settled.
|
||||
# Releases ship constantly: a merge starts a release within minutes, once its wave of merges has settled.
|
||||
DEBOUNCE = dt.timedelta(minutes=5)
|
||||
MAX_WAIT = dt.timedelta(minutes=20)
|
||||
# Kept as typed in release titles, where the clauses after the first are lowercased.
|
||||
@@ -72,12 +75,13 @@ LAUNCHER_IGNORED = ["launcher/links.json", "launcher/docs/", "launcher/tests/"]
|
||||
FOOTER = {
|
||||
"game": "Install or update it from the Horizon launcher: it installs new versions by itself. "
|
||||
"New here? Get the launcher at https://playhorizon.dev. You need your own copy of Minecraft: Java Edition.",
|
||||
"beta": "This is an alpha build: launchers on the Alpha channel (Settings, Updates) install it now; Stable gets it "
|
||||
"in the next daily update if it holds up.",
|
||||
"launcher": "Your launcher updates itself. New here? Download the archive for your system below, extract it, "
|
||||
"and run `horizon-launcher`. Website: https://playhorizon.dev",
|
||||
}
|
||||
DISCLAIMER = "Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft."
|
||||
# An open issue with this label holds every game release (docs/release-flow.md). Only people who can triage the
|
||||
# repository can add it, and the issue's text is never read: its author could edit it afterwards.
|
||||
BLOCKER = "release-blocker"
|
||||
|
||||
|
||||
def run(*command, check=True):
|
||||
@@ -225,11 +229,37 @@ def pull_request(number):
|
||||
}
|
||||
|
||||
|
||||
def published_releases(betas=True):
|
||||
"""Published (not draft) releases with their tags and dates; without betas (pre-releases) when betas is False."""
|
||||
def published_releases():
|
||||
"""Published releases with their tags and dates: no drafts, and no pre-releases (the old Alpha channel's)."""
|
||||
releases = gh_json("api", f"repos/{REPO}/releases?per_page=100", "--paginate", "--slurp")
|
||||
flat = [release for page in releases for release in page]
|
||||
return [release for release in flat if not release["draft"] and (betas or not release["prerelease"])]
|
||||
return [release for release in flat if not release["draft"] and not release["prerelease"]]
|
||||
|
||||
|
||||
def open_blockers():
|
||||
"""The numbers of the open issues labelled release-blocker (pull requests left out)."""
|
||||
issues = gh_json("api", f"repos/{REPO}/issues?labels={BLOCKER}&state=open&per_page=100", "--paginate", "--slurp")
|
||||
return sorted(issue["number"] for page in issues for issue in page if "pull_request" not in issue)
|
||||
|
||||
|
||||
def smoke_problem(report):
|
||||
"""Why a release smoke test's report (the game's --smoke-report) fails, or None when the game drew a world."""
|
||||
if report is None:
|
||||
return "no smoke-test.json: the release smoke test did not run"
|
||||
if report.get("error") is not None:
|
||||
return f"the smoke run failed: {report['error']}"
|
||||
if report.get("frames", 0) < 1500 or not report.get("chunks") or not report.get("meshed_sections") \
|
||||
or not report.get("player"):
|
||||
return "the smoke run did not draw a world"
|
||||
return None
|
||||
|
||||
|
||||
def gate(report, blockers):
|
||||
"""Why a built game release must not be published, or None: it is published as the latest at once, so its
|
||||
smoke test must have passed and no release-blocker may be open."""
|
||||
problems = [problem for problem in [smoke_problem(report)] if problem]
|
||||
problems += [f"release-blocker #{number} is open" for number in blockers]
|
||||
return "; ".join(problems) or None
|
||||
|
||||
|
||||
def last_release(releases, kind):
|
||||
@@ -238,13 +268,16 @@ def last_release(releases, kind):
|
||||
return max(ours, key=lambda release: tag_key(release["tag_name"]), default=None)
|
||||
|
||||
|
||||
def decision(kind, prs, now, paused=False, force=False, new_line=None):
|
||||
def decision(kind, prs, now, paused=False, force=False, new_line=None, blockers=()):
|
||||
"""Whether to release now, and why. prs: the merged pull requests since the last release, each with the
|
||||
files it changed under "paths" (player-facing ones only) and when it merged ("merged_at"). new_line: the
|
||||
release line ("0.2") when it has no release of this kind yet; its first goes out at once."""
|
||||
release line ("0.2") when it has no release of this kind yet; its first goes out at once. blockers: the open
|
||||
release-blocker issues; they hold every release, forced ones too."""
|
||||
counted = [pr for pr in prs if pr["paths"] and "skip-release" not in pr["labels"]]
|
||||
urgent = [pr for pr in counted if "release-now" in pr["labels"]]
|
||||
merged = [pr["merged_at"] for pr in counted if pr.get("merged_at")]
|
||||
if blockers:
|
||||
return False, "held by " + ", ".join(f"release-blocker #{number}" for number in blockers)
|
||||
if force:
|
||||
return True, "started by hand with force"
|
||||
if paused:
|
||||
@@ -323,9 +356,8 @@ def line_intro(kind, version, previous):
|
||||
f"`horizon-server update --version {version}`.")
|
||||
|
||||
|
||||
def notes(kind, version, prs, issues, beta=False, previous=None):
|
||||
"""(title, body) of a release; a game beta's say it is one. previous: the release before it, for a line's
|
||||
first release."""
|
||||
def notes(kind, version, prs, issues, previous=None):
|
||||
"""(title, body) of a release. previous: the release before it, for a line's first release."""
|
||||
shown = [pr for pr in prs if pr["paths"] and "skip-release" not in pr["labels"]]
|
||||
new = [pr for pr in shown if "feature" in pr["labels"]]
|
||||
fixed = [pr for pr in shown if "feature" not in pr["labels"]]
|
||||
@@ -346,17 +378,15 @@ def notes(kind, version, prs, issues, beta=False, previous=None):
|
||||
contributors = sorted({pr["author"] for pr in shown if pr["author"] and pr["author"] != REPO.split("/")[0]})
|
||||
if contributors:
|
||||
parts.append("Thanks to " + ", ".join(f"@{name}" for name in contributors) + ".")
|
||||
if beta and kind == "game":
|
||||
parts.append(FOOTER["beta"])
|
||||
parts.append(FOOTER[kind])
|
||||
parts.append(DISCLAIMER)
|
||||
return title, "\n\n".join(parts) + "\n"
|
||||
|
||||
|
||||
def gather(kind, head, releases=None, betas=True):
|
||||
"""The last published release of this kind (stable only when betas is False) and the pull requests merged
|
||||
since, with their player-facing paths."""
|
||||
releases = published_releases(betas) if releases is None else releases
|
||||
def gather(kind, head, releases=None):
|
||||
"""The last published release of this kind and the pull requests merged since, with their player-facing
|
||||
paths."""
|
||||
releases = published_releases() if releases is None else releases
|
||||
last = last_release(releases, kind)
|
||||
base = last["tag_name"] if last else run("git", "rev-list", "--max-parents=0", head).split()[0]
|
||||
exporter_paths = exporters()
|
||||
@@ -387,18 +417,29 @@ def write_outputs(values):
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("command", choices=["decide", "notes"])
|
||||
parser.add_argument("command", choices=["decide", "notes", "gate"])
|
||||
parser.add_argument("--kind", choices=["game", "launcher"], required=True)
|
||||
parser.add_argument("--head", help="the commit to release (default: the newest commit on main whose checks passed)")
|
||||
parser.add_argument("--tag", help="notes: the release's tag")
|
||||
parser.add_argument("--force", action="store_true", help="release even without player-facing changes, before merges settle or while paused")
|
||||
parser.add_argument("--out", type=Path, help="notes: write title.txt and body.md here")
|
||||
parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)")
|
||||
parser.add_argument("--stable", action="store_true",
|
||||
help="notes: for promoting a beta to stable, so since the last stable release, without the beta line")
|
||||
parser.add_argument("--smoke", type=Path, help="gate: the release smoke test's report (smoke-test.json)")
|
||||
parser.add_argument("--blockers", action="store_true", help="gate: also check that no release-blocker is open")
|
||||
args = parser.parse_args()
|
||||
now = dt.datetime.fromisoformat(args.now) if args.now else dt.datetime.now(dt.timezone.utc)
|
||||
|
||||
if args.command == "gate":
|
||||
report = json.loads(args.smoke.read_text()) if args.smoke and args.smoke.exists() else None
|
||||
problem = gate(report, open_blockers() if args.blockers else [])
|
||||
line = f"Not publishing: {problem}" if problem else "Ready to publish: the smoke test passed" + (
|
||||
" and no release-blocker is open" if args.blockers else "")
|
||||
print(json.dumps(report) if report else "", line, sep="\n")
|
||||
if os.environ.get("GITHUB_STEP_SUMMARY"):
|
||||
with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary:
|
||||
summary.write(f"### {line}\n")
|
||||
return 1 if problem else 0
|
||||
|
||||
head = args.head or green_main_head()
|
||||
if not head:
|
||||
result = {"release": False, "reason": "main's latest checks did not pass"}
|
||||
@@ -406,11 +447,11 @@ def main():
|
||||
write_outputs({"release": "false", "reason": result["reason"]})
|
||||
return 0
|
||||
head = run("git", "rev-parse", head).strip()
|
||||
last, prs = gather(args.kind, head, betas=not args.stable)
|
||||
last, prs = gather(args.kind, head)
|
||||
if args.command == "notes":
|
||||
version = args.tag or "unreleased"
|
||||
previous = last["tag_name"] if last and last["tag_name"] != version else None
|
||||
title, body = notes(args.kind, version, prs, known_issues(), beta=not args.stable, previous=previous)
|
||||
title, body = notes(args.kind, version, prs, known_issues(), previous=previous)
|
||||
if args.out:
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
(args.out / "title.txt").write_text(title + "\n")
|
||||
@@ -422,7 +463,9 @@ def main():
|
||||
line = release_line()
|
||||
prefix = GAME_PREFIX if args.kind == "game" else LAUNCHER_PREFIX
|
||||
new_line = f"{line[0]}.{line[1]}" if line and first_on_line(tags, prefix, line) else None
|
||||
release, reason = decision(args.kind, prs, now, os.environ.get("RELEASES_PAUSED") == "1", args.force, new_line)
|
||||
blockers = open_blockers() if args.kind == "game" else []
|
||||
release, reason = decision(args.kind, prs, now, os.environ.get("RELEASES_PAUSED") == "1", args.force, new_line,
|
||||
blockers)
|
||||
minor = any("feature" in pr["labels"] for pr in prs if pr["paths"])
|
||||
tag = next_game_tag(tags, now.date(), line) if args.kind == "game" else next_launcher_tag(tags, minor, line)
|
||||
result = {
|
||||
|
||||
@@ -45,7 +45,6 @@ from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -81,12 +80,6 @@ PROPERTIES = {
|
||||
}
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(('127.0.0.1', 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def cpu_seconds(text):
|
||||
"""ps's cumulative CPU time: [[DD-]HH:]MM:SS[.ss]."""
|
||||
days, _, rest = text.rpartition('-')
|
||||
@@ -282,7 +275,7 @@ def run_once(kind, bots, behaviour, args, out):
|
||||
directory = out / name
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir(parents=True)
|
||||
port = free_port()
|
||||
port = lab.free_port()
|
||||
props = dict(PROPERTIES, **{'server-port': str(port), 'level-seed': str(args.seed)})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the vanilla structure-start oracle for a seed and chunk rectangle.
|
||||
|
||||
usage: structure_start_oracle.py OUT SEED X0 Z0 X1 Z1
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import sys
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
|
||||
def main():
|
||||
out, seed, x0, z0, x1, z1 = sys.argv[1:7]
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java'
|
||||
build = Path(os.environ['HORIZON_ORACLE_BUILD']) if os.environ.get('HORIZON_ORACLE_BUILD') else lab.LOCAL/'structure-start-oracle'
|
||||
classes = build/'classes'
|
||||
classes.mkdir(parents=True, exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
compiled = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies,
|
||||
'-d', str(classes), str(source)], capture_output=True, text=True)
|
||||
if compiled.returncode:
|
||||
raise SystemExit('javac failed:\n' + compiled.stderr[-3000:])
|
||||
result = subprocess.run(['java', '-Xmx2G', '-cp', str(classes)+os.pathsep+dependencies,
|
||||
'dev.horizonlab.parity.VanillaStructureStartOracle', out, seed, x0, z0, x1, z1],
|
||||
capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
lines = [line for line in (result.stdout + result.stderr).splitlines() if 'Exception' in line or 'Caused' in line]
|
||||
raise SystemExit('oracle failed: ' + ' | '.join(lines[:5]))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -17,16 +17,12 @@ playing instance and the subtitle notifications. Horizon's `Ambience` and
|
||||
"""
|
||||
import json
|
||||
import random
|
||||
import struct
|
||||
|
||||
try:
|
||||
from . import audio_harness as h
|
||||
from . import audio_harness as h, lab
|
||||
except ImportError:
|
||||
import audio_harness as h
|
||||
|
||||
|
||||
def dbits(v):
|
||||
return struct.pack('>d', v).hex()
|
||||
import lab
|
||||
|
||||
|
||||
def settings():
|
||||
@@ -54,11 +50,11 @@ class Script:
|
||||
self.lines.append(' '.join(map(str, parts)))
|
||||
|
||||
def sounds(self, value):
|
||||
mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], dbits(value['mood'][3]))
|
||||
self.add('sounds', value['loop'] or '-', mood, *[f'{s},{dbits(c)}' for s, c in value['additions']])
|
||||
mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], lab.dbits(value['mood'][3]))
|
||||
self.add('sounds', value['loop'] or '-', mood, *[f'{s},{lab.dbits(c)}' for s, c in value['additions']])
|
||||
|
||||
def player(self, at=(0.5, 64.0, 0.5), eye=1.62, water=0, spectator=0, removed=0, mode=0, height=1.8, columns=()):
|
||||
self.add('player', *map(dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height),
|
||||
self.add('player', *map(lab.dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height),
|
||||
*[f'{x},{y},{z},{d}' for x, y, z, d in columns])
|
||||
|
||||
def tick(self, n=1):
|
||||
|
||||
@@ -8,11 +8,9 @@ overhangs approached from every angle with varied speeds, input vectors,
|
||||
sizes, jump boost and the canAutoJump preconditions."""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import random
|
||||
import struct
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
@@ -23,14 +21,6 @@ except ImportError:
|
||||
import test_native_client as client
|
||||
|
||||
|
||||
def fbits(v):
|
||||
return struct.pack('>f', v).hex()
|
||||
|
||||
|
||||
def dbits(v):
|
||||
return struct.pack('>d', v).hex()
|
||||
|
||||
|
||||
BLOCKS = [
|
||||
('stone', {}), ('stone', {}), ('stone', {}),
|
||||
('stone_slab', {'type': 'bottom'}), ('stone_slab', {'type': 'top'}), ('stone_slab', {'type': 'double'}),
|
||||
@@ -64,12 +54,12 @@ DIMS = [(0.6, 1.8), (0.6, 1.8), (0.6, 1.5), (0.6, 0.6), (0.3, 0.9), (1.2, 3.6),
|
||||
|
||||
def player(rng, x, y, z, yaw):
|
||||
w, h = rng.choice(DIMS)
|
||||
return dict(pos=[dbits(x), dbits(y), dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08,
|
||||
yr=fbits(yaw), xr=fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])),
|
||||
speed=fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])),
|
||||
move=[fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677),
|
||||
return dict(pos=[lab.dbits(x), lab.dbits(y), lab.dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08,
|
||||
yr=lab.fbits(yaw), xr=lab.fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])),
|
||||
speed=lab.fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])),
|
||||
move=[lab.fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677),
|
||||
(0.0, -1.0), (0.0, 0.0), (0.3, 0.3)])],
|
||||
width=fbits(w), height=fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]),
|
||||
width=lab.fbits(w), height=lab.fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]),
|
||||
enabled=rng.random() < 0.93, time=rng.choice([0] * 12 + [1, -3, 2]))
|
||||
|
||||
|
||||
@@ -86,18 +76,18 @@ def cases(rng):
|
||||
x = ox + 0.5 - dx * 1.1
|
||||
z = oz + 0.5 - dz * 1.1
|
||||
p = player(rng, x, float(oy), z, yaw)
|
||||
p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)],
|
||||
width=fbits(0.6), height=fbits(1.8), xr=fbits(0.0))
|
||||
yield dict(blocks=blocks, player=p, xa=fbits(dx * step), za=fbits(dz * step))
|
||||
p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[lab.fbits(0.0), lab.fbits(1.0)],
|
||||
width=lab.fbits(0.6), height=lab.fbits(1.8), xr=lab.fbits(0.0))
|
||||
yield dict(blocks=blocks, player=p, xa=lab.fbits(dx * step), za=lab.fbits(dz * step))
|
||||
# Ceilings above the player and above the step.
|
||||
for ceiling in range(2, 6):
|
||||
for step_height in (0, 1):
|
||||
blocks = [[ox, oy + step_height, oz, 'minecraft:stone', {}], [ox - 1, oy + ceiling, oz, 'minecraft:stone', {}],
|
||||
[ox, oy + ceiling + step_height, oz, 'minecraft:stone_slab', {'type': 'top'}]]
|
||||
p = player(rng, ox - 0.5, float(oy), oz + 0.5, -90.0)
|
||||
p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)],
|
||||
width=fbits(0.6), height=fbits(1.8))
|
||||
yield dict(blocks=blocks, player=p, xa=fbits(0.2), za=fbits(0.0))
|
||||
p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[lab.fbits(0.0), lab.fbits(1.0)],
|
||||
width=lab.fbits(0.6), height=lab.fbits(1.8))
|
||||
yield dict(blocks=blocks, player=p, xa=lab.fbits(0.2), za=lab.fbits(0.0))
|
||||
for _ in range(9000):
|
||||
blocks = placed(rng, rng.choice([1, 2, 4, 8, 16, 30]))
|
||||
x = ox + rng.uniform(-2, 3)
|
||||
@@ -108,7 +98,7 @@ def cases(rng):
|
||||
move = rng.choice([0.0, 0.0, 0.01, 0.1, 0.215, 0.3, rng.uniform(0, 0.4)])
|
||||
angle = rng.uniform(0, 6.283)
|
||||
|
||||
yield dict(blocks=blocks, player=p, xa=fbits(math.cos(angle) * move), za=fbits(math.sin(angle) * move))
|
||||
yield dict(blocks=blocks, player=p, xa=lab.fbits(math.cos(angle) * move), za=lab.fbits(math.sin(angle) * move))
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
+35
-43
@@ -20,14 +20,6 @@ except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def fbits(v):
|
||||
return struct.pack('>f', v).hex()
|
||||
|
||||
|
||||
def dbits(v):
|
||||
return struct.pack('>d', v).hex()
|
||||
|
||||
|
||||
def f32(v):
|
||||
return struct.unpack('>f', struct.pack('>f', v))[0]
|
||||
|
||||
@@ -39,8 +31,8 @@ TICKS = [0, 1, 5, 10, 19, 20, 21, 72000, -5, 3]
|
||||
|
||||
def fov_fields(rng):
|
||||
use = rng.choice([None, None, ['bow', rng.choice(TICKS)], ['spyglass', rng.choice(TICKS)], ['other', rng.choice(TICKS)]])
|
||||
return dict(flying=rng.random() < 0.3, ws=fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])),
|
||||
speed=dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use)
|
||||
return dict(flying=rng.random() < 0.3, ws=lab.fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])),
|
||||
speed=lab.dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use)
|
||||
|
||||
|
||||
def fov_cases(rng):
|
||||
@@ -50,9 +42,9 @@ def fov_cases(rng):
|
||||
for use in [None, ['bow', 0], ['bow', 7], ['bow', 20], ['bow', 40], ['spyglass', 2], ['other', 5]]:
|
||||
for fp in (False, True):
|
||||
for scale in (0.0, 0.5, 1.0):
|
||||
yield dict(t='fov', flying=flying, ws=fbits(ws), speed=dbits(speed), use=use, fp=fp, scale=fbits(scale))
|
||||
yield dict(t='fov', flying=flying, ws=lab.fbits(ws), speed=lab.dbits(speed), use=use, fp=fp, scale=lab.fbits(scale))
|
||||
for _ in range(3000):
|
||||
yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=fbits(rng.choice([0.0, 1.0, rng.random()])))
|
||||
yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=lab.fbits(rng.choice([0.0, 1.0, rng.random()])))
|
||||
|
||||
|
||||
FULL = [[0, 0, 0, 1, 1, 1]]
|
||||
@@ -65,7 +57,7 @@ def world(rng, center):
|
||||
cx, cy, cz = center
|
||||
for _ in range(rng.choice([0, 3, 10, 40, 120])):
|
||||
p = (cx + rng.randint(-6, 6), cy + rng.randint(-3, 5), cz + rng.randint(-6, 6))
|
||||
cells[f'{p[0]} {p[1]} {p[2]}'] = [[dbits(v) for v in box] for box in rng.choice(SHAPES)]
|
||||
cells[f'{p[0]} {p[1]} {p[2]}'] = [[lab.dbits(v) for v in box] for box in rng.choice(SHAPES)]
|
||||
return cells
|
||||
|
||||
|
||||
@@ -81,22 +73,22 @@ def entity_state(rng, center):
|
||||
prev = [p - rng.choice([0, 0, 0.1, 0.3, 1.0, rng.uniform(-1, 1)]) for p in pos]
|
||||
kind = 'player' if rng.random() < 0.85 else 'marker'
|
||||
xr, yr = angle(rng), angle(rng)
|
||||
s = dict(kind=kind, pos=[dbits(v) for v in pos], prev=[dbits(v) for v in prev], xr=fbits(xr), yr=fbits(yr),
|
||||
xro=fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=fbits(rng.choice([yr, yr + 10, angle(rng)])),
|
||||
eye=fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)])))
|
||||
s = dict(kind=kind, pos=[lab.dbits(v) for v in pos], prev=[lab.dbits(v) for v in prev], xr=lab.fbits(xr), yr=lab.fbits(yr),
|
||||
xro=lab.fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=lab.fbits(rng.choice([yr, yr + 10, angle(rng)])),
|
||||
eye=lab.fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)])))
|
||||
s.update(fov_fields(rng))
|
||||
s.update(scale_attr=dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])),
|
||||
dist=dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])),
|
||||
s.update(scale_attr=lab.dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])),
|
||||
dist=lab.dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])),
|
||||
sleeping=rng.choice([None] * 6 + [[None], [0], [1], [2], [3]]),
|
||||
dead=rng.choice([None] * 6 + [0, 1, 5, 19, 20, 25]),
|
||||
mount=rng.choice([None] * 4 + [[dbits(rng.choice([1.0, 2.0, 0.5])), dbits(rng.choice([4.0, 8.0, 1.0]))]]))
|
||||
mount=rng.choice([None] * 4 + [[lab.dbits(rng.choice([1.0, 2.0, 0.5])), lab.dbits(rng.choice([4.0, 8.0, 1.0]))]]))
|
||||
return s
|
||||
|
||||
|
||||
def window(rng):
|
||||
"""Window size and Camera.depthFar for the world and hand projections."""
|
||||
w, h = rng.choice([(1600, 1000), (854, 480), (1920, 1080), (800, 1200), (1, 1), (rng.randint(1, 4000), rng.randint(1, 3000))])
|
||||
return [fbits(w), fbits(h), fbits(rng.choice([768.0, 128.0, 2048.0, 4096.0, rng.uniform(32, 4096)]))]
|
||||
return [lab.fbits(w), lab.fbits(h), lab.fbits(rng.choice([768.0, 128.0, 2048.0, 4096.0, rng.uniform(32, 4096)]))]
|
||||
|
||||
|
||||
def camera_cases(rng):
|
||||
@@ -113,11 +105,11 @@ def camera_cases(rng):
|
||||
ops.append(['tick'])
|
||||
elif kind == 'frame':
|
||||
pt = rng.choice([0.0, 1.0, 0.5, 0.25, 0.999, rng.random()])
|
||||
ops.append(['frame', fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05] + window(rng))
|
||||
ops.append(['frame', lab.fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05] + window(rng))
|
||||
else:
|
||||
ops.append(['type', rng.randrange(3)])
|
||||
yield dict(t='camera', fov=rng.choice([70, 30, 110, 90, rng.randint(30, 110)]),
|
||||
effect=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]),
|
||||
effect=lab.dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]),
|
||||
cells=world(rng, center), ops=ops)
|
||||
# The hand's projection at FOV 30, 70 and 110 while walking, sprinting, under
|
||||
# speed, drawing a bow, dying and in fluids: GameRenderer.render3dHud uses
|
||||
@@ -127,13 +119,13 @@ def camera_cases(rng):
|
||||
for use in (None, ['bow', 10]):
|
||||
for dead in (None, 5):
|
||||
for fluid in (0, 1, 2):
|
||||
s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)],
|
||||
xr=fbits(0.0), yr=fbits(0.0), xro=fbits(0.0), yro=fbits(0.0), eye=fbits(1.62), flying=False,
|
||||
ws=fbits(0.1), speed=dbits(speed), use=use, scale_attr=dbits(1.0), dist=dbits(4.0),
|
||||
s = dict(kind='player', pos=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], prev=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)],
|
||||
xr=lab.fbits(0.0), yr=lab.fbits(0.0), xro=lab.fbits(0.0), yro=lab.fbits(0.0), eye=lab.fbits(1.62), flying=False,
|
||||
ws=lab.fbits(0.1), speed=lab.dbits(speed), use=use, scale_attr=lab.dbits(1.0), dist=lab.dbits(4.0),
|
||||
sleeping=None, dead=dead, mount=None)
|
||||
ops = [['entity', s]] + [['tick']] * 8 + [['frame', fbits(pt), fluid, False, fbits(1600.0), fbits(1000.0), fbits(768.0)]
|
||||
ops = [['entity', s]] + [['tick']] * 8 + [['frame', lab.fbits(pt), fluid, False, lab.fbits(1600.0), lab.fbits(1000.0), lab.fbits(768.0)]
|
||||
for pt in (0.0, 0.5, 1.0)]
|
||||
yield dict(t='camera', fov=fov, effect=dbits(1.0), type=0, cells={}, ops=ops)
|
||||
yield dict(t='camera', fov=fov, effect=lab.dbits(1.0), type=0, cells={}, ops=ops)
|
||||
# A walled-in third-person camera stepping through every distance bound.
|
||||
for dist in [0.0, 0.5, 1.0, 2.0, 4.0, 8.0, 32.0]:
|
||||
for wall in range(0, 6):
|
||||
@@ -141,28 +133,28 @@ def camera_cases(rng):
|
||||
cells = {}
|
||||
for dx in range(-6, 7):
|
||||
for dy in range(62, 68):
|
||||
cells[f'{dx} {dy} {-wall - 1}'] = [[dbits(v) for v in box] for box in FULL]
|
||||
cells[f'{dx} {dy} {wall + 1}'] = [[dbits(v) for v in box] for box in FULL]
|
||||
s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)],
|
||||
xr=fbits(15.0), yr=fbits(yaw), xro=fbits(15.0), yro=fbits(yaw), eye=fbits(1.62), flying=False,
|
||||
ws=fbits(0.1), speed=dbits(f32(0.1)), use=None, scale_attr=dbits(1.0), dist=dbits(dist),
|
||||
cells[f'{dx} {dy} {-wall - 1}'] = [[lab.dbits(v) for v in box] for box in FULL]
|
||||
cells[f'{dx} {dy} {wall + 1}'] = [[lab.dbits(v) for v in box] for box in FULL]
|
||||
s = dict(kind='player', pos=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], prev=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)],
|
||||
xr=lab.fbits(15.0), yr=lab.fbits(yaw), xro=lab.fbits(15.0), yro=lab.fbits(yaw), eye=lab.fbits(1.62), flying=False,
|
||||
ws=lab.fbits(0.1), speed=lab.dbits(f32(0.1)), use=None, scale_attr=lab.dbits(1.0), dist=lab.dbits(dist),
|
||||
sleeping=None, dead=None, mount=None)
|
||||
ops = [['entity', s]] + [['tick']] * 6 + [['frame', fbits(pt), 0, False] + window(rng) for pt in (0.0, 0.5, 1.0)]
|
||||
yield dict(t='camera', fov=70, effect=dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops)
|
||||
ops = [['entity', s]] + [['tick']] * 6 + [['frame', lab.fbits(pt), 0, False] + window(rng) for pt in (0.0, 0.5, 1.0)]
|
||||
yield dict(t='camera', fov=70, effect=lab.dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops)
|
||||
|
||||
|
||||
def bob_cases(rng):
|
||||
for n in range(6000):
|
||||
living = None
|
||||
if rng.random() < 0.8:
|
||||
living = dict(hurt=fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])),
|
||||
duration=rng.choice([10, 10, 0, 5, 20]), dir=fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])),
|
||||
death=rng.choice([None, None, None, fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))]))
|
||||
living = dict(hurt=lab.fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])),
|
||||
duration=rng.choice([10, 10, 0, 5, 20]), dir=lab.fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])),
|
||||
death=rng.choice([None, None, None, lab.fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))]))
|
||||
player = None
|
||||
if rng.random() < 0.8:
|
||||
player = [fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])),
|
||||
fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))]
|
||||
yield dict(t='bob', living=living, player=player, tilt=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])),
|
||||
player = [lab.fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])),
|
||||
lab.fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))]
|
||||
yield dict(t='bob', living=living, player=player, tilt=lab.dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])),
|
||||
view=rng.random() < 0.8)
|
||||
|
||||
|
||||
@@ -174,12 +166,12 @@ def avatar_cases(rng):
|
||||
if kind == 'tick':
|
||||
ops.append(['tick'])
|
||||
elif kind == 'move':
|
||||
ops.append(['move', fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))])
|
||||
ops.append(['move', lab.fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), lab.fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))])
|
||||
elif kind == 'bob':
|
||||
v = [rng.choice([0.0, 0.05, -0.2, rng.uniform(-0.5, 0.5)]), rng.uniform(-1, 1), rng.choice([0.0, 0.08, rng.uniform(-0.5, 0.5)])]
|
||||
ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [dbits(x) for x in v]])
|
||||
ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [lab.dbits(x) for x in v]])
|
||||
elif kind == 'frame':
|
||||
ops.append(['frame', fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))])
|
||||
ops.append(['frame', lab.fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))])
|
||||
else:
|
||||
ops.append(['reset'])
|
||||
yield dict(t='avatar', ops=ops)
|
||||
|
||||
@@ -33,6 +33,7 @@ from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import anvil_dump # noqa: E402
|
||||
import parity_shard # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LOCAL = ROOT / '.local' / 'datafix'
|
||||
@@ -63,7 +64,7 @@ def java_classpath():
|
||||
import test_model_baking_parity as baking
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
libraries = baking.client_libraries()
|
||||
build = LOCAL / 'build' / os.environ.get('PARITY_SHARD', 'all').replace('/', '-') # shards compile apart
|
||||
build = LOCAL / 'build' / parity_shard.label() # shards compile apart
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
classes, dependencies, _ = harness.compile_oracle(build, 'VanillaDataFixOracle', jars, libraries,
|
||||
lock['minecraft']['java_major'])
|
||||
@@ -78,15 +79,6 @@ def build_rust():
|
||||
return Path(meta['target_directory']) / 'release' / 'examples' / 'datafix_world'
|
||||
|
||||
|
||||
def shard(items):
|
||||
"""This run's share of items when tools/parity.py runs the harness in parts (PARITY_SHARD=i/n)."""
|
||||
spec = os.environ.get('PARITY_SHARD')
|
||||
if not spec:
|
||||
return items
|
||||
index, count = map(int, spec.split('/'))
|
||||
return items[index - 1::count]
|
||||
|
||||
|
||||
def run_vanilla(classpath, world, out, target=None):
|
||||
# The oracle replaces OUT itself: left in place, an unchanged run's outputs can be reused.
|
||||
log = out.parent / (out.name + '.log')
|
||||
@@ -226,7 +218,7 @@ def main():
|
||||
band = args.band
|
||||
if band and not args.versions: # worlds in the layout of before 1.16, saved before the target
|
||||
worlds = [w for w in worlds if json.loads((world_path(w) / 'datafix-source.json').read_text())['data_version'] < band]
|
||||
versions = shard(args.versions or worlds)
|
||||
versions = parity_shard.shard(args.versions or worlds)
|
||||
classpath = java_classpath()
|
||||
binary = None if args.vanilla_only else Path(args.binary) if args.binary else build_rust()
|
||||
total = 0
|
||||
|
||||
@@ -68,10 +68,12 @@ import zlib
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as oh, test_rust_parity as base
|
||||
from .lab import free_port # the other server harnesses import it from here
|
||||
except ImportError:
|
||||
import lab
|
||||
import oracle_harness as oh
|
||||
import test_rust_parity as base
|
||||
from lab import free_port
|
||||
|
||||
NAME = 'dedicated-server-parity'
|
||||
SEED = 12345
|
||||
@@ -89,12 +91,6 @@ PROPERTIES = {
|
||||
}
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(('127.0.0.1', 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def icon_png():
|
||||
"""A 64x64 RGBA PNG (server-icon.png)."""
|
||||
rows = b''.join(b'\0' + b''.join(bytes((x * 4, y * 4, (x ^ y) * 4, 255)) for x in range(64)) for y in range(64))
|
||||
|
||||
@@ -18,14 +18,6 @@ except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def fbits(v):
|
||||
return struct.pack('>f', v).hex()
|
||||
|
||||
|
||||
def dbits(v):
|
||||
return struct.pack('>d', v).hex()
|
||||
|
||||
|
||||
def f32(v):
|
||||
return struct.unpack('>f', struct.pack('>f', v))[0]
|
||||
|
||||
@@ -52,15 +44,15 @@ def step(hit=('miss',), ac=0, uc=0, ad=False, ud=False, busy=False, using=False,
|
||||
"""rot: the player's (xRot, yRot) from this step on (LocalPlayer.applyInput's hand sway)."""
|
||||
return dict(hit=list(hit), ac=ac, uc=uc, ad=ad, ud=ud, busy=busy, using=using,
|
||||
uses=uses or dict(entity='pass', block='pass', item='pass'), shrink=shrink, set=set,
|
||||
rot=None if rot is None else [fbits(rot[0]), fbits(rot[1])])
|
||||
rot=None if rot is None else [lab.fbits(rot[0]), lab.fbits(rot[1])])
|
||||
|
||||
|
||||
def case(steps, creative=False, main=None, off=None, blocks=None, haste=None, fatigue=None):
|
||||
return dict(creative=creative, main=main, off=off, haste=haste, fatigue=fatigue,
|
||||
blocks=[[*p, b] for p, b in (blocks or {}).items()], steps=steps,
|
||||
rust=dict(blocks={k: [fbits(v[0]), v[1]] for k, v in BLOCKS.items()},
|
||||
tools={k: [fbits(v[0]), v[1]] for k, v in TOOLS.items()},
|
||||
attack_speed={k: dbits(v) for k, v in SPEEDS.items()}))
|
||||
rust=dict(blocks={k: [lab.fbits(v[0]), v[1]] for k, v in BLOCKS.items()},
|
||||
tools={k: [lab.fbits(v[0]), v[1]] for k, v in TOOLS.items()},
|
||||
attack_speed={k: lab.dbits(v) for k, v in SPEEDS.items()}))
|
||||
|
||||
|
||||
def block_hit(pos, face=1):
|
||||
|
||||
@@ -72,12 +72,6 @@ def wait_for(endpoint, line, predicate, timeout=60, what=None):
|
||||
raise AssertionError(f'timed out waiting for {what or line}: {last}')
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(('127.0.0.1', 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def health(relay_url):
|
||||
with urllib.request.urlopen(f'http://{relay_url}/health', timeout=5) as r:
|
||||
return json.loads(r.read())
|
||||
@@ -204,7 +198,7 @@ def leave(host, guest, name):
|
||||
|
||||
def start_relay(args, work):
|
||||
"""A relay on a free local port, as anyone would run their own."""
|
||||
port = free_port()
|
||||
port = lab.free_port()
|
||||
url = f'127.0.0.1:{port}'
|
||||
log = (work / 'relay.log').open('w+')
|
||||
process = subprocess.Popen([str(args.relay.resolve())], env=dict(os.environ, PORT=str(port)),
|
||||
|
||||
@@ -6,9 +6,7 @@ and absolute motion, sensitivity curve, cinematic smoothing, inversion,
|
||||
scroll accumulation and discrete scrolling), Entity.turn and ToggleKeyMapping,
|
||||
all driven with identical synthetic input and time sequences."""
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import struct
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
@@ -16,14 +14,6 @@ except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def fbits(v):
|
||||
return struct.pack('>f', v).hex()
|
||||
|
||||
|
||||
def dbits(v):
|
||||
return struct.pack('>d', v).hex()
|
||||
|
||||
|
||||
def timer_cases(rng):
|
||||
for n in range(700):
|
||||
tps = rng.choice([20.0, 20.0, 10.0, 60.0, 1.0, 144.0])
|
||||
@@ -38,12 +28,12 @@ def timer_cases(rng):
|
||||
now -= rng.randrange(0, 30)
|
||||
if kind == 'adv':
|
||||
mspt = rng.choice([None, None, None, 50.0, 25.0, 100.0, 500.0, 1000.0, 0.5, 5.0, 0.1])
|
||||
ops.append(['adv', now, None if mspt is None else fbits(mspt)])
|
||||
ops.append(['adv', now, None if mspt is None else lab.fbits(mspt)])
|
||||
elif kind == 'real':
|
||||
ops.append(['real', now])
|
||||
else:
|
||||
ops.append([kind, rng.random() < 0.5])
|
||||
yield dict(t='timer', tps=fbits(tps), start=start, ops=ops)
|
||||
yield dict(t='timer', tps=lab.fbits(tps), start=start, ops=ops)
|
||||
|
||||
|
||||
def rate_cases(rng):
|
||||
@@ -55,7 +45,7 @@ def rate_cases(rng):
|
||||
kind = rng.choice(['rate', 'freeze', 'step', 'stopstep', 'sprint', 'check', 'check', 'check', 'end', 'stopsprint',
|
||||
'tick', 'tick', 'tick'])
|
||||
if kind == 'rate':
|
||||
ops.append(['rate', fbits(rng.choice(rates))])
|
||||
ops.append(['rate', lab.fbits(rng.choice(rates))])
|
||||
elif kind == 'freeze':
|
||||
ops.append(['freeze', rng.random() < 0.5])
|
||||
elif kind == 'step':
|
||||
@@ -78,7 +68,7 @@ def scale_cases(rng):
|
||||
for uni in (False, True):
|
||||
sw, sh = rng.choice([(w, h), (max(w // 2, 1), max(h // 2, 1)), (w + 1, h + 3)])
|
||||
yield dict(t='scale', w=w, h=h, max=maxs, uni=uni, sw=sw, sh=sh,
|
||||
x=dbits(rng.uniform(0, w)), y=dbits(rng.uniform(0, h)))
|
||||
x=lab.dbits(rng.uniform(0, w)), y=lab.dbits(rng.uniform(0, h)))
|
||||
|
||||
|
||||
def limit_cases(rng):
|
||||
@@ -103,13 +93,13 @@ def mouse_cases(rng):
|
||||
if kind == 'move':
|
||||
x, y = rng.uniform(0, 1920), rng.uniform(0, 1080)
|
||||
big = rng.choice([1, 1, 1, 50, 5000])
|
||||
ops.append(['move', dbits(x), dbits(y), dbits(rng.uniform(-30, 30) * big), dbits(rng.uniform(-30, 30) * big)])
|
||||
ops.append(['move', lab.dbits(x), lab.dbits(y), lab.dbits(rng.uniform(-30, 30) * big), lab.dbits(rng.uniform(-30, 30) * big)])
|
||||
elif kind == 'frame':
|
||||
time += rng.choice([0.0, 0.001, 0.0069, 0.016, 0.0167, 0.05, 0.5, 2.0])
|
||||
ops.append(['frame', dbits(time)])
|
||||
ops.append(['frame', lab.dbits(time)])
|
||||
else:
|
||||
ops.append(['ignore'])
|
||||
yield dict(t='mouse', sens=dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3,
|
||||
yield dict(t='mouse', sens=lab.dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3,
|
||||
ix=rng.random() < 0.3, iy=rng.random() < 0.3, grabbed=rng.random() < 0.85, active=rng.random() < 0.9, ops=ops)
|
||||
|
||||
|
||||
@@ -119,14 +109,14 @@ def scroll_cases(rng):
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
x = rng.choice([0.0, 0.0, 0.0, 1.0, -1.0, 0.25, -0.25, 0.4, 2.0, 5.5, -7.0, rng.uniform(-3, 3)])
|
||||
y = rng.choice([0.0, 1.0, -1.0, 1.0, -1.0, 0.1, -0.3, 0.5, -0.5, 2.0, -3.0, 120.0, rng.uniform(-3, 3)])
|
||||
ops.append([dbits(x), dbits(y)])
|
||||
case = dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])),
|
||||
ops.append([lab.dbits(x), lab.dbits(y)])
|
||||
case = dict(t='scroll', discrete=rng.random() < 0.4, sens=lab.dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])),
|
||||
slot=rng.randrange(9), ops=ops)
|
||||
yield case
|
||||
yield dict(case, spectator=True)
|
||||
# Bounds, recovery from each bound, fractional accumulation, and horizontal-only input.
|
||||
yield dict(t='scroll', discrete=False, sens=dbits(1.0), slot=4, spectator=True,
|
||||
ops=[[dbits(x), dbits(y)] for x, y in
|
||||
yield dict(t='scroll', discrete=False, sens=lab.dbits(1.0), slot=4, spectator=True,
|
||||
ops=[[lab.dbits(x), lab.dbits(y)] for x, y in
|
||||
[(0, 100), (0, -1), (0, -100), (0, 1), (0, .4), (0, .7),
|
||||
(0, -.4), (0, -.7), (5, 0), (-5, 0)]])
|
||||
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check LAN shutdown when leaving a singleplayer world through the pause menu,
|
||||
and that offline guests joining with their default names are not refused as the
|
||||
host's profile (#195: everyone was "Player").
|
||||
|
||||
Requires a built horizon-client, prepared resources and a display on Unix:
|
||||
xvfb-run -a python3 tools/test_lan_lifecycle.py --client target/fast/horizon-client
|
||||
Worlds and settings are created in a temporary directory.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
try:
|
||||
from . import lab
|
||||
except ImportError:
|
||||
import lab
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GROUP = '224.0.2.60'
|
||||
DISCOVERY_PORT = 4445
|
||||
|
||||
|
||||
def command(endpoint, line):
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
|
||||
connection.settimeout(60)
|
||||
connection.connect(str(endpoint))
|
||||
connection.sendall((line + '\n').encode())
|
||||
with connection.makefile('r') as reply:
|
||||
result = json.loads(reply.readline())
|
||||
assert 'error' not in result, (line, result)
|
||||
return result
|
||||
|
||||
|
||||
def wait_for(endpoint, line, predicate, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
result = command(endpoint, line)
|
||||
except (FileNotFoundError, ConnectionRefusedError):
|
||||
time.sleep(0.1)
|
||||
continue
|
||||
if predicate(result):
|
||||
return result
|
||||
time.sleep(0.1)
|
||||
raise AssertionError(f'timed out waiting for {line}')
|
||||
|
||||
|
||||
def announcement(scanner, port, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
marker = f'[AD]{port}[/AD]'.encode()
|
||||
while time.monotonic() < deadline:
|
||||
scanner.settimeout(max(0.001, deadline - time.monotonic()))
|
||||
try:
|
||||
message, _ = scanner.recvfrom(4096)
|
||||
except socket.timeout:
|
||||
return False
|
||||
if marker in message:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def scenario(endpoint, scanner):
|
||||
wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title')
|
||||
command(endpoint, 'open LanLifecycle 0 creative')
|
||||
wait_for(endpoint, 'status', lambda value: value['player'] is not None
|
||||
and value['pending_chunks'] == 0)
|
||||
assert command(endpoint, 'lan status') == {'open': False}
|
||||
port = 0
|
||||
for _ in range(2):
|
||||
port = command(endpoint, f'lan open {port}')['port']
|
||||
with socket.create_connection(('127.0.0.1', port), timeout=2):
|
||||
pass
|
||||
assert announcement(scanner, port, 5), 'LAN world was not advertised'
|
||||
command(endpoint, 'key esc tap')
|
||||
screen = wait_for(endpoint, 'screen', lambda value: any(
|
||||
button['label'] == 'Save and Quit to Title' for button in value['buttons']))
|
||||
assert screen['screen'] == 'paused', screen
|
||||
command(endpoint, 'click-button Save and Quit to Title')
|
||||
wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title')
|
||||
assert command(endpoint, 'lan status') == {'open': False}, 'LAN stayed open after leaving'
|
||||
try:
|
||||
connection = socket.create_connection(('127.0.0.1', port), timeout=2)
|
||||
except ConnectionRefusedError:
|
||||
pass
|
||||
else:
|
||||
connection.close()
|
||||
raise AssertionError('LAN still accepts connections after leaving')
|
||||
# Discard datagrams queued before shutdown, then listen for more than
|
||||
# two announcement intervals (the pinger sends every 1.5 seconds).
|
||||
scanner.setblocking(False)
|
||||
try:
|
||||
while True:
|
||||
scanner.recvfrom(4096)
|
||||
except BlockingIOError:
|
||||
pass
|
||||
assert not announcement(scanner, port, 3.5), 'LAN kept advertising after leaving'
|
||||
command(endpoint, 'open LanLifecycle')
|
||||
wait_for(endpoint, 'status', lambda value: value['player'] is not None
|
||||
and value['pending_chunks'] == 0)
|
||||
assert command(endpoint, 'lan status') == {'open': False}, 'LAN reopened with the world'
|
||||
command(endpoint, 'lan open 0')
|
||||
command(endpoint, 'quit')
|
||||
|
||||
|
||||
def start_client(client, resources, home, endpoint, log, *extra):
|
||||
return subprocess.Popen([
|
||||
str(client), '--resources', str(resources), '--render-distance', '2',
|
||||
'--test-terrain', '--control-socket', str(endpoint), '--timeout-seconds', '180', *extra,
|
||||
], cwd=home, env=dict(os.environ, HORIZON_HOME=str(home), HORIZON_NO_AUDIO='1',
|
||||
HORIZON_PLAYER_NAME=''),
|
||||
stdout=log, stderr=subprocess.STDOUT)
|
||||
|
||||
|
||||
def guest_names(endpoint, port, guests):
|
||||
"""Two guests with default names join together; a guest named like the host is refused."""
|
||||
names = []
|
||||
for home, guest in guests:
|
||||
wait_for(guest, 'screen', lambda value: value['screen'] == 'title')
|
||||
command(guest, f'connect 127.0.0.1:{port}')
|
||||
wait_for(guest, 'status', lambda value: (value.get('server') or {}).get('joined'))
|
||||
kept = (home / 'horizon-player.txt').read_text()
|
||||
assert kept.startswith('name:Player') and kept.strip() != 'name:Player', kept
|
||||
names.append(kept.strip().removeprefix('name:'))
|
||||
assert names[0] != names[1], names
|
||||
status = wait_for(endpoint, 'lan status', lambda value: len(value['guests']) == 2)
|
||||
assert sorted(g['name'] for g in status['guests']) == sorted(names), status
|
||||
# The same home keeps its name: leave and join again as the same profile.
|
||||
home, guest = guests[0]
|
||||
command(guest, 'disconnect')
|
||||
wait_for(endpoint, 'lan status', lambda value: len(value['guests']) == 1)
|
||||
command(guest, f'connect 127.0.0.1:{port}')
|
||||
wait_for(guest, 'status', lambda value: (value.get('server') or {}).get('joined'))
|
||||
assert (home / 'horizon-player.txt').read_text().strip() == f'name:{names[0]}'
|
||||
# A guest that really is the host's offline profile is refused, the others stay.
|
||||
command(guest, 'disconnect')
|
||||
command(guest, f'connect 127.0.0.1:{port} Player')
|
||||
refused = wait_for(guest, 'screen', lambda value: (value.get('menu') or {}).get('disconnected'))
|
||||
assert 'another location' in refused['menu']['disconnected'], refused
|
||||
status = command(endpoint, 'lan status')
|
||||
assert [g['name'] for g in status['guests']] == [names[1]], status
|
||||
return names
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--client', type=Path, required=True)
|
||||
parser.add_argument('--resources', type=Path, default=lab.RESOURCES)
|
||||
args = parser.parse_args()
|
||||
client, resources = args.client.resolve(), args.resources.resolve()
|
||||
with tempfile.TemporaryDirectory(prefix='horizon-lan-') as directory:
|
||||
work = Path(directory)
|
||||
endpoint = work / 'control.sock'
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as scanner:
|
||||
scanner.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
scanner.bind(('', DISCOVERY_PORT))
|
||||
scanner.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
|
||||
socket.inet_aton(GROUP) + socket.inet_aton('0.0.0.0'))
|
||||
with (work / 'client.log').open('w+') as log:
|
||||
process = start_client(client, resources, work, endpoint, log)
|
||||
try:
|
||||
scenario(endpoint, scanner)
|
||||
assert process.wait(timeout=20) == 0, 'client exited unsuccessfully'
|
||||
except Exception:
|
||||
log.seek(0)
|
||||
print('\n'.join(log.read().splitlines()[-20:]))
|
||||
raise
|
||||
finally:
|
||||
stop(process)
|
||||
names = guests_scenario(client, resources, work)
|
||||
print('LAN lifecycle passed: leaving stops hosting and discovery; reopening stays private')
|
||||
print(f'LAN guests passed: default names {names[0]} and {names[1]} joined together and kept; '
|
||||
'"Player" refused as the host\'s profile')
|
||||
|
||||
|
||||
def stop(process):
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=10)
|
||||
|
||||
|
||||
def guests_scenario(client, resources, work):
|
||||
host_home = work / 'host'
|
||||
homes = [work / 'guest-a', work / 'guest-b']
|
||||
processes, logs = [], []
|
||||
try:
|
||||
for home in [host_home, *homes]:
|
||||
home.mkdir()
|
||||
log = (home / 'client.log').open('w+')
|
||||
logs.append(log)
|
||||
processes.append(start_client(client, resources, home, home / 'control.sock', log))
|
||||
endpoint = host_home / 'control.sock'
|
||||
wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title')
|
||||
command(endpoint, 'open LanGuests 0 creative')
|
||||
wait_for(endpoint, 'status', lambda value: value['player'] is not None
|
||||
and value['pending_chunks'] == 0)
|
||||
port = command(endpoint, 'lan open 0')['port']
|
||||
return guest_names(endpoint, port, [(home, home / 'control.sock') for home in homes])
|
||||
except Exception:
|
||||
for log in logs:
|
||||
log.seek(0)
|
||||
print(f'--- {log.name}')
|
||||
print('\n'.join(log.read().splitlines()[-20:]))
|
||||
raise
|
||||
finally:
|
||||
for process in processes:
|
||||
stop(process)
|
||||
for log in logs:
|
||||
log.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -109,15 +109,9 @@ BENIGN = re.compile(r'(Unpacking |OFFLINE/INSECURE|online-mode|authenticate user
|
||||
|
||||
# ---------------------------------------------------------------- vanilla server
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(('127.0.0.1', 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
class Vanilla:
|
||||
def __init__(self, directory, port=None, world='world', extra=None):
|
||||
port = port or free_port()
|
||||
port = port or lab.free_port()
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
props = {
|
||||
|
||||
@@ -41,12 +41,12 @@ 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
|
||||
from .test_dedicated_server_parity import Server
|
||||
except ImportError:
|
||||
import lab
|
||||
import oracle_harness as oh
|
||||
import test_rust_parity as base
|
||||
from test_dedicated_server_parity import Server, free_port
|
||||
from test_dedicated_server_parity import Server
|
||||
|
||||
NAME = 'secure-chat-parity'
|
||||
SCENARIOS = {
|
||||
@@ -153,20 +153,10 @@ 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
|
||||
return lab.varint(len(body)) + body
|
||||
|
||||
def read_varint(s):
|
||||
value = 0
|
||||
@@ -177,7 +167,7 @@ def status(port):
|
||||
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' + lab.varint(777) + lab.varint(len(host)) + host + port.to_bytes(2, 'big') + b'\x01'))
|
||||
s.sendall(packet(b'\x00'))
|
||||
length = read_varint(s)
|
||||
data = b''
|
||||
@@ -212,7 +202,7 @@ def chat_lines(lines):
|
||||
|
||||
|
||||
def run_side(label, scenario, command, directory, client):
|
||||
port = free_port()
|
||||
port = lab.free_port()
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir(parents=True)
|
||||
props = dict(PROPERTIES, **SCENARIOS[scenario], **{'server-port': str(port)})
|
||||
|
||||
@@ -96,17 +96,6 @@ def run_side(label, server_command, client_command, build, world):
|
||||
SHOWN = ('add', 'remove', 'respawn', 'track', 'untrack', 'update')
|
||||
|
||||
|
||||
def settled(lines):
|
||||
"""One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint:
|
||||
what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more
|
||||
than once on the way there; the packet by packet order is test_locator_bar_parity's."""
|
||||
def waypoint(line):
|
||||
parts = line.split(' ')
|
||||
return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None
|
||||
last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)}
|
||||
return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i]
|
||||
|
||||
|
||||
def shown(lines):
|
||||
"""Each player's adds, removes, respawns and waypoints (as the step leaves them), step by step; sorted within a
|
||||
step (the packets of one step may leave in another order within the tick)."""
|
||||
@@ -115,7 +104,7 @@ def shown(lines):
|
||||
parts = line.split(' ', 2)
|
||||
if len(parts) == 3 and parts[2].split(' ')[0] in SHOWN:
|
||||
steps.setdefault((parts[0], parts[1]), []).append(line)
|
||||
return [l for key in steps for l in sorted(settled(steps[key]))]
|
||||
return [l for key in steps for l in sorted(lab.settled(steps[key]))]
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -15,7 +15,6 @@ in sorted order (the packets of one step may leave in another order within the t
|
||||
waypoints as each step leaves them (one manager per level: a player in another level is untracked). What a death does besides its messages
|
||||
is left to its own harness.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
@@ -23,7 +22,6 @@ import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid as uuidlib
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
@@ -39,20 +37,12 @@ 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-uuid', [f'give {lab.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'], []),
|
||||
@@ -83,17 +73,6 @@ DEATH_STEP = 'step=console-kill'
|
||||
STEP_SECONDS = 2.5
|
||||
|
||||
|
||||
def settled(lines):
|
||||
"""One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint:
|
||||
what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more
|
||||
than once on the way there; the packet by packet order is test_locator_bar_parity's."""
|
||||
def waypoint(line):
|
||||
parts = line.split(' ')
|
||||
return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None
|
||||
last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)}
|
||||
return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i]
|
||||
|
||||
|
||||
def run_side(label, server_command, client_command, build, world):
|
||||
directory = build / label
|
||||
port = server_dir(directory, world)
|
||||
@@ -151,7 +130,7 @@ def run_side(label, server_command, client_command, build, world):
|
||||
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(settled(steps[k]))], errors
|
||||
return [l for k in keys for l in sorted(lab.settled(steps[k]))], errors
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -18,14 +18,10 @@ import math
|
||||
import random
|
||||
|
||||
try:
|
||||
from . import audio_harness as h
|
||||
from . import audio_harness as h, lab
|
||||
except ImportError:
|
||||
import audio_harness as h
|
||||
|
||||
|
||||
def dbits(v):
|
||||
import struct
|
||||
return struct.pack('>d', v).hex()
|
||||
import lab
|
||||
|
||||
|
||||
class Script:
|
||||
@@ -37,11 +33,11 @@ class Script:
|
||||
self.lines.append(' '.join(map(str, parts)))
|
||||
|
||||
def play(self, name, event, source=4, volume=1.0, pitch=1.0, at=(0.0, 0.0, 0.0), looping=0, delay=0, linear=True, relative=0, seed=0, kind='simple'):
|
||||
self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(dbits, at), looping, delay,
|
||||
self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(lab.dbits, at), looping, delay,
|
||||
'linear' if linear else 'none', relative, seed)
|
||||
|
||||
def cart(self, name, at, delta, removed=0):
|
||||
self.add('cart', name, *map(dbits, at), *map(dbits, delta), removed)
|
||||
self.add('cart', name, *map(lab.dbits, at), *map(lab.dbits, delta), removed)
|
||||
|
||||
def tick(self, n=1, paused=0):
|
||||
for _ in range(n):
|
||||
|
||||
@@ -29,6 +29,10 @@ Seeds: the player report's seed (1891623539983467248: Horizon spawned at
|
||||
-48 -48, vanilla at 152 145), the chunk generation harness's seeds and
|
||||
--random seeds from a fixed generator.
|
||||
|
||||
tools/parity.py runs it in PARITY_SHARDS parts, each creating the worlds of
|
||||
every PARITY_SHARDS-th seed: each seed is a vanilla and a Horizon server start,
|
||||
~15 s, and 60 seeds in one run were the longest harness (~25 min).
|
||||
|
||||
usage: test_world_spawn_parity.py [--random N] [--jobs N] [--origins-only]
|
||||
"""
|
||||
import argparse
|
||||
@@ -43,16 +47,18 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from . import anvil_dump, lab, oracle_harness as oh, test_rust_parity as base
|
||||
from . import anvil_dump, lab, oracle_harness as oh, parity_shard, test_rust_parity as base
|
||||
from .test_dedicated_server_parity import Server, free_port
|
||||
except ImportError:
|
||||
import anvil_dump
|
||||
import lab
|
||||
import oracle_harness as oh
|
||||
import parity_shard
|
||||
import test_rust_parity as base
|
||||
from test_dedicated_server_parity import Server, free_port
|
||||
|
||||
NAME = 'world-spawn-parity'
|
||||
PARITY_SHARDS = 4
|
||||
REPORT = 1891623539983467248
|
||||
SEEDS = [REPORT, 12345, -7046029254386353131, 987654321987, 4242, -1, 0x5DEECE66D, 20260607, 777, 0]
|
||||
RESOURCES = lab.RESOURCES
|
||||
@@ -107,7 +113,7 @@ def main():
|
||||
parser.add_argument('--seed', type=int, action='append', help='only these seeds (repeatable)')
|
||||
args = parser.parse_args()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build = lab.LOCAL / NAME / parity_shard.label() # shards run at once
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
classes = build / 'classes'
|
||||
@@ -116,7 +122,7 @@ def main():
|
||||
'-d', classes, lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java'],
|
||||
build, 'compile-java')
|
||||
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'spawn_origin'], build, 'compile-probe')
|
||||
all_seeds = args.seed or seeds(args.random)
|
||||
all_seeds = parity_shard.shard(args.seed or seeds(args.random))
|
||||
started = time.time()
|
||||
|
||||
vanilla, rust = origins(build, classes, dependencies, all_seeds)
|
||||
|
||||
@@ -9,7 +9,6 @@ level.dat, player and data/*.dat files) is applied exactly. The original is kept
|
||||
upgrade_world.py SOURCE_WORLD DEST_WORLD
|
||||
"""
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -24,12 +23,6 @@ ROOT = Path(__file__).resolve().parent.parent
|
||||
SERVER = lab.GAME / 'jars' / 'server.jar'
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(('127.0.0.1', 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 3:
|
||||
sys.exit(__doc__)
|
||||
@@ -42,7 +35,7 @@ def main():
|
||||
scratch = Path(scratch)
|
||||
(scratch / 'eula.txt').write_text('eula=true\n')
|
||||
(scratch / 'server.properties').write_text(
|
||||
f'level-name=world\nonline-mode=false\nserver-port={free_port()}\n')
|
||||
f'level-name=world\nonline-mode=false\nserver-port={lab.free_port()}\n')
|
||||
shutil.copytree(source, scratch / 'world')
|
||||
# The server upgrades at startup, then keeps running as a normal server: stop it
|
||||
# once it reports "Done".
|
||||
|
||||
+1
-10
@@ -14,12 +14,10 @@ that skips the first-run screens, keeps the game running unfocused and
|
||||
renders few chunks, so a harness can drive it with vscreen keys.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
@@ -56,13 +54,6 @@ if sys.platform == "darwin":
|
||||
OPTIONS["enableVsync"] = "false"
|
||||
|
||||
|
||||
def offline_uuid(name):
|
||||
digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest())
|
||||
digest[6] = (digest[6] & 0x0F) | 0x30
|
||||
digest[8] = (digest[8] & 0x3F) | 0x80
|
||||
return uuid.UUID(bytes=bytes(digest))
|
||||
|
||||
|
||||
def host_library(path):
|
||||
name = Path(path).name
|
||||
if "natives-" in name:
|
||||
@@ -127,7 +118,7 @@ def command(args):
|
||||
f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}",
|
||||
f"-Dio.netty.native.workdir={natives}",
|
||||
"-cp", os.pathsep.join(map(str, jars)), "net.minecraft.client.main.Main",
|
||||
"--username", args.name, "--uuid", offline_uuid(args.name).hex,
|
||||
"--username", args.name, "--uuid", lab.offline_uuid(args.name).hex,
|
||||
"--accessToken", "0", "--offlineDeveloperMode",
|
||||
"--version", lab.VERSION, "--gameDir", str(args.game_dir),
|
||||
"--assetsDir", str(assets), "--assetIndex", json.loads((GAME / "manifest.json").read_text())["assetIndex"]["id"],
|
||||
|
||||
+12
-43
@@ -11,12 +11,10 @@ its log reports the position it read, and console commands such as
|
||||
`data get entity NAME` can inspect the loaded player meanwhile.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
try:
|
||||
@@ -25,27 +23,9 @@ except ImportError:
|
||||
import lab
|
||||
|
||||
|
||||
def offline_uuid(name):
|
||||
digest = bytearray(hashlib.md5(('OfflinePlayer:' + name).encode()).digest())
|
||||
digest[6] = (digest[6] & 0x0F) | 0x30
|
||||
digest[8] = (digest[8] & 0x3F) | 0x80
|
||||
return uuid.UUID(bytes=bytes(digest))
|
||||
|
||||
|
||||
def varint(v):
|
||||
out = b''
|
||||
v &= 0xFFFFFFFF
|
||||
while True:
|
||||
b = v & 0x7F
|
||||
v >>= 7
|
||||
out += bytes([b | (0x80 if v else 0)])
|
||||
if not v:
|
||||
return out
|
||||
|
||||
|
||||
def string(s):
|
||||
data = s.encode()
|
||||
return varint(len(data)) + data
|
||||
return lab.varint(len(data)) + data
|
||||
|
||||
|
||||
class Connection:
|
||||
@@ -73,44 +53,33 @@ class Connection:
|
||||
return value
|
||||
|
||||
def send(self, packet_id, payload=b''):
|
||||
body = varint(packet_id) + payload
|
||||
body = lab.varint(packet_id) + payload
|
||||
if self.threshold >= 0:
|
||||
if len(body) >= self.threshold:
|
||||
body = varint(len(body)) + zlib.compress(body)
|
||||
body = lab.varint(len(body)) + zlib.compress(body)
|
||||
else:
|
||||
body = varint(0) + body
|
||||
self.sock.sendall(varint(len(body)) + body)
|
||||
body = lab.varint(0) + body
|
||||
self.sock.sendall(lab.varint(len(body)) + body)
|
||||
|
||||
def receive(self):
|
||||
length = self.read_varint()
|
||||
body = self.read_exact(length)
|
||||
if self.threshold >= 0:
|
||||
pos, size = parse_varint(body, 0)
|
||||
pos, size = lab.parse_varint(body, 0)
|
||||
body = zlib.decompress(body[pos:]) if size else body[pos:]
|
||||
pos, packet_id = parse_varint(body, 0)
|
||||
pos, packet_id = lab.parse_varint(body, 0)
|
||||
return packet_id, body[pos:]
|
||||
|
||||
|
||||
def parse_varint(data, pos):
|
||||
value = shift = 0
|
||||
while True:
|
||||
b = data[pos]
|
||||
pos += 1
|
||||
value |= (b & 0x7F) << shift
|
||||
shift += 7
|
||||
if not b & 0x80:
|
||||
return pos, value
|
||||
|
||||
|
||||
def join(host, port, name, seconds):
|
||||
c = Connection(host, port)
|
||||
c.send(0, varint(lab.version_info()['protocol_version']) + string(host) + struct.pack('>H', port) + varint(2))
|
||||
c.send(0, string(name) + offline_uuid(name).bytes)
|
||||
c.send(0, lab.varint(lab.version_info()['protocol_version']) + string(host) + struct.pack('>H', port) + lab.varint(2))
|
||||
c.send(0, string(name) + lab.offline_uuid(name).bytes)
|
||||
# Login: compression, then login finished.
|
||||
while True:
|
||||
pid, data = c.receive()
|
||||
if pid == 3:
|
||||
c.threshold = parse_varint(data, 0)[1]
|
||||
c.threshold = lab.parse_varint(data, 0)[1]
|
||||
elif pid == 2:
|
||||
break
|
||||
elif pid == 0:
|
||||
@@ -119,7 +88,7 @@ def join(host, port, name, seconds):
|
||||
while True:
|
||||
pid, data = c.receive()
|
||||
if pid == 15: # select known packs: claim none, receive full registries
|
||||
c.send(7, varint(0))
|
||||
c.send(7, lab.varint(0))
|
||||
elif pid == 4: # keep alive
|
||||
c.send(4, data)
|
||||
elif pid == 5: # ping
|
||||
@@ -153,7 +122,7 @@ def main():
|
||||
p.add_argument('--uuid', action='store_true')
|
||||
args = p.parse_args()
|
||||
if args.uuid:
|
||||
print(offline_uuid(args.name))
|
||||
print(lab.offline_uuid(args.name))
|
||||
return 0
|
||||
join(args.host, args.port, args.name, args.seconds)
|
||||
return 0
|
||||
|
||||
@@ -17,12 +17,16 @@ load failures.
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
try:
|
||||
from . import lab
|
||||
except ImportError:
|
||||
import lab
|
||||
|
||||
SUSPICIOUS = re.compile(
|
||||
r'(ERROR|login failed|Exception|Couldn\'t load|Failed to|Skipping|Invalid|Unknown|corrupt|'
|
||||
r'Recreating|upgrad|DataFix|out of bounds|missing|Mismatch)', re.IGNORECASE)
|
||||
@@ -31,12 +35,6 @@ BENIGN = re.compile(r'(Unpacking |OFFLINE/INSECURE|online-mode|authenticate user
|
||||
r'Failed to load properties|Failed to load eula)')
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(('127.0.0.1', 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('--jar', required=True)
|
||||
@@ -48,7 +46,7 @@ def main():
|
||||
p.add_argument('--wait-after', type=float, default=1.0)
|
||||
p.add_argument('--timeout', type=float, default=240)
|
||||
args = p.parse_args()
|
||||
port = args.port or free_port()
|
||||
port = args.port or lab.free_port()
|
||||
os.makedirs(args.dir, exist_ok=True)
|
||||
with open(os.path.join(args.dir, 'eula.txt'), 'w') as f:
|
||||
f.write('eula=true\n')
|
||||
|
||||
Reference in New Issue
Block a user